summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorXavier Leroy <xavier.leroy@inria.fr>2015-09-22 09:42:51 +0000
committerXavier Leroy <xavier.leroy@inria.fr>2015-09-22 09:42:51 +0000
commit1d3fbfd0965ff6689c0d799d424d1bd7719b848f (patch)
tree22027a8d3c89a513890d5fd5856ac201193c41ba
parent43370f0deae6129186a972264bd020395b493097 (diff)
parentdfcc115f12103580df568d59082050c47eeb8a64 (diff)
downloadocaml-1d3fbfd0965ff6689c0d799d424d1bd7719b848f.tar.gz
Experiment: reduce the time it takes to run the test suite
git-svn-id: http://caml.inria.fr/svn/ocaml/branches/faster-testsuite@16439 f963ae5c-01c2-4b8c-9fe0-0dff7051ff02
-rw-r--r--.depend1140
-rw-r--r--.gitignore2848
-rw-r--r--.ignore11
-rw-r--r--.merlin50
-rw-r--r--.ocp-indent2
-rw-r--r--.travis-ci.sh35
-rw-r--r--.travis.yml16
-rw-r--r--Changes4447
-rw-r--r--INSTALL356
-rw-r--r--LICENSE627
-rw-r--r--Makefile894
-rw-r--r--Makefile.nt779
-rw-r--r--README130
-rw-r--r--README.win32454
-rw-r--r--VERSION4
-rw-r--r--asmcomp/.ignore7
-rw-r--r--asmcomp/CSEgen.ml334
-rw-r--r--asmcomp/CSEgen.mli35
-rw-r--r--asmcomp/amd64/CSE.ml38
-rw-r--r--asmcomp/amd64/arch.ml128
-rw-r--r--asmcomp/amd64/emit.mlp1003
-rw-r--r--asmcomp/amd64/proc.ml333
-rw-r--r--asmcomp/amd64/reload.ml126
-rw-r--r--asmcomp/amd64/scheduling.ml18
-rw-r--r--asmcomp/amd64/selection.ml254
-rw-r--r--asmcomp/arm/CSE.ml37
-rw-r--r--asmcomp/arm/arch.ml255
-rw-r--r--asmcomp/arm/emit.mlp956
-rw-r--r--asmcomp/arm/proc.ml307
-rw-r--r--asmcomp/arm/reload.ml16
-rw-r--r--asmcomp/arm/scheduling.ml77
-rw-r--r--asmcomp/arm/selection.ml295
-rw-r--r--asmcomp/arm64/CSE.ml37
-rw-r--r--asmcomp/arm64/arch.ml158
-rw-r--r--asmcomp/arm64/emit.mlp988
-rw-r--r--asmcomp/arm64/proc.ml230
-rw-r--r--asmcomp/arm64/reload.ml16
-rw-r--r--asmcomp/arm64/scheduling.ml18
-rw-r--r--asmcomp/arm64/selection.ml243
-rw-r--r--asmcomp/asmgen.ml164
-rw-r--r--asmcomp/asmgen.mli28
-rw-r--r--asmcomp/asmlibrarian.ml78
-rw-r--r--asmcomp/asmlibrarian.mli25
-rw-r--r--asmcomp/asmlink.ml409
-rw-r--r--asmcomp/asmlink.mli41
-rw-r--r--asmcomp/asmpackager.ml214
-rw-r--r--asmcomp/asmpackager.mli28
-rw-r--r--asmcomp/branch_relaxation.ml138
-rw-r--r--asmcomp/branch_relaxation.mli26
-rw-r--r--asmcomp/branch_relaxation_intf.ml64
-rw-r--r--asmcomp/clambda.ml150
-rw-r--r--asmcomp/clambda.mli95
-rw-r--r--asmcomp/closure.ml1331
-rw-r--r--asmcomp/closure.mli16
-rw-r--r--asmcomp/cmm.ml134
-rw-r--r--asmcomp/cmm.mli147
-rw-r--r--asmcomp/cmmgen.ml2947
-rw-r--r--asmcomp/cmmgen.mli30
-rw-r--r--asmcomp/cmx_format.mli61
-rw-r--r--asmcomp/codegen.ml95
-rw-r--r--asmcomp/codegen.mli27
-rw-r--r--asmcomp/coloring.ml223
-rw-r--r--asmcomp/coloring.mli15
-rw-r--r--asmcomp/comballoc.ml88
-rw-r--r--asmcomp/comballoc.mli15
-rw-r--r--asmcomp/compilenv.ml301
-rw-r--r--asmcomp/compilenv.mli91
-rw-r--r--asmcomp/deadcode.ml67
-rw-r--r--asmcomp/deadcode.mli16
-rw-r--r--asmcomp/debuginfo.ml56
-rw-r--r--asmcomp/debuginfo.mli32
-rw-r--r--asmcomp/emit.mli18
-rw-r--r--asmcomp/emitaux.ml260
-rw-r--r--asmcomp/emitaux.mli72
-rw-r--r--asmcomp/i386/CSE.ml47
-rw-r--r--asmcomp/i386/arch.ml162
-rw-r--r--asmcomp/i386/emit.mlp1098
-rw-r--r--asmcomp/i386/proc.ml224
-rw-r--r--asmcomp/i386/reload.ml83
-rw-r--r--asmcomp/i386/scheduling.ml20
-rw-r--r--asmcomp/i386/selection.ml315
-rw-r--r--asmcomp/interf.ml188
-rw-r--r--asmcomp/interf.mli16
-rw-r--r--asmcomp/linearize.ml297
-rw-r--r--asmcomp/linearize.mli54
-rw-r--r--asmcomp/liveness.ml133
-rw-r--r--asmcomp/liveness.mli19
-rw-r--r--asmcomp/mach.ml131
-rw-r--r--asmcomp/mach.mli93
-rw-r--r--asmcomp/power/CSE.ml37
-rw-r--r--asmcomp/power/arch.ml111
-rw-r--r--asmcomp/power/emit.mlp1204
-rw-r--r--asmcomp/power/proc.ml306
-rw-r--r--asmcomp/power/reload.ml16
-rw-r--r--asmcomp/power/scheduling.ml61
-rw-r--r--asmcomp/power/selection.ml91
-rw-r--r--asmcomp/printclambda.ml193
-rw-r--r--asmcomp/printclambda.mli18
-rw-r--r--asmcomp/printcmm.ml205
-rw-r--r--asmcomp/printcmm.mli25
-rw-r--r--asmcomp/printlinear.ml80
-rw-r--r--asmcomp/printlinear.mli19
-rw-r--r--asmcomp/printmach.ml229
-rw-r--r--asmcomp/printmach.mli29
-rw-r--r--asmcomp/proc.mli62
-rw-r--r--asmcomp/reg.ml197
-rw-r--r--asmcomp/reg.mli67
-rw-r--r--asmcomp/reload.mli15
-rw-r--r--asmcomp/reloadgen.ml139
-rw-r--r--asmcomp/reloadgen.mli24
-rw-r--r--asmcomp/schedgen.ml395
-rw-r--r--asmcomp/schedgen.mli46
-rw-r--r--asmcomp/scheduling.mli15
-rw-r--r--asmcomp/selectgen.ml893
-rw-r--r--asmcomp/selectgen.mli107
-rw-r--r--asmcomp/selection.mli16
-rw-r--r--asmcomp/sparc/CSE.ml30
-rw-r--r--asmcomp/sparc/arch.ml78
-rw-r--r--asmcomp/sparc/emit.mlp768
-rw-r--r--asmcomp/sparc/proc.ml244
-rw-r--r--asmcomp/sparc/reload.ml16
-rw-r--r--asmcomp/sparc/scheduling.ml60
-rw-r--r--asmcomp/sparc/selection.ml73
-rw-r--r--asmcomp/spill.ml410
-rw-r--r--asmcomp/spill.mli17
-rw-r--r--asmcomp/split.ml214
-rw-r--r--asmcomp/split.mli17
-rw-r--r--asmcomp/strmatch.ml389
-rw-r--r--asmcomp/strmatch.mli28
-rw-r--r--asmcomp/x86_ast.mli216
-rw-r--r--asmcomp/x86_dsl.ml195
-rw-r--r--asmcomp/x86_dsl.mli188
-rw-r--r--asmcomp/x86_gas.ml305
-rw-r--r--asmcomp/x86_gas.mli15
-rw-r--r--asmcomp/x86_masm.ml258
-rw-r--r--asmcomp/x86_masm.mli15
-rw-r--r--asmcomp/x86_proc.ml272
-rw-r--r--asmcomp/x86_proc.mli88
-rw-r--r--asmrun/.depend1074
-rw-r--r--asmrun/.ignore41
-rw-r--r--asmrun/Makefile239
-rw-r--r--asmrun/Makefile.nt85
-rw-r--r--asmrun/amd64.S694
-rw-r--r--asmrun/amd64nt.asm476
-rw-r--r--asmrun/arm.S500
-rw-r--r--asmrun/arm64.S555
-rw-r--r--asmrun/backtrace_prim.c230
-rw-r--r--asmrun/fail.c184
-rw-r--r--asmrun/i386.S498
-rw-r--r--asmrun/i386nt.asm332
-rw-r--r--asmrun/natdynlink.c156
-rw-r--r--asmrun/power.S692
-rw-r--r--asmrun/roots.c455
-rw-r--r--asmrun/signals_asm.c288
-rw-r--r--asmrun/signals_osdep.h339
-rw-r--r--asmrun/sparc.S358
-rw-r--r--asmrun/stack.h111
-rw-r--r--asmrun/startup.c141
-rw-r--r--boot/.ignore6
-rwxr-xr-xboot/ocamlcbin0 -> 1816755 bytes
-rwxr-xr-xboot/ocamldepbin0 -> 570979 bytes
-rwxr-xr-xboot/ocamllexbin0 -> 259285 bytes
-rw-r--r--bytecomp/.ignore2
-rw-r--r--bytecomp/bytegen.ml954
-rw-r--r--bytecomp/bytegen.mli20
-rw-r--r--bytecomp/bytelibrarian.ml131
-rw-r--r--bytecomp/bytelibrarian.mli34
-rw-r--r--bytecomp/bytelink.ml674
-rw-r--r--bytecomp/bytelink.mli38
-rw-r--r--bytecomp/bytepackager.ml306
-rw-r--r--bytecomp/bytepackager.mli28
-rw-r--r--bytecomp/bytesections.ml98
-rw-r--r--bytecomp/bytesections.mli54
-rw-r--r--bytecomp/cmo_format.mli59
-rw-r--r--bytecomp/dll.ml181
-rw-r--r--bytecomp/dll.mli63
-rw-r--r--bytecomp/emitcode.ml431
-rw-r--r--bytecomp/emitcode.mli42
-rw-r--r--bytecomp/instruct.ml109
-rw-r--r--bytecomp/instruct.mli125
-rw-r--r--bytecomp/lambda.ml571
-rw-r--r--bytecomp/lambda.mli284
-rw-r--r--bytecomp/matching.ml3179
-rw-r--r--bytecomp/matching.mli43
-rw-r--r--bytecomp/meta.ml30
-rw-r--r--bytecomp/meta.mli32
-rw-r--r--bytecomp/printinstr.ml113
-rw-r--r--bytecomp/printinstr.mli20
-rw-r--r--bytecomp/printlambda.ml406
-rw-r--r--bytecomp/printlambda.mli19
-rw-r--r--bytecomp/runtimedef.mli16
-rw-r--r--bytecomp/simplif.ml611
-rw-r--r--bytecomp/simplif.mli24
-rw-r--r--bytecomp/switch.ml884
-rw-r--r--bytecomp/switch.mli113
-rw-r--r--bytecomp/symtable.ml393
-rw-r--r--bytecomp/symtable.mli61
-rw-r--r--bytecomp/translclass.ml851
-rw-r--r--bytecomp/translclass.mli26
-rw-r--r--bytecomp/translcore.ml1257
-rw-r--r--bytecomp/translcore.mli46
-rw-r--r--bytecomp/translmod.ml971
-rw-r--r--bytecomp/translmod.mli41
-rw-r--r--bytecomp/translobj.ml173
-rw-r--r--bytecomp/translobj.mli30
-rw-r--r--bytecomp/typeopt.ml137
-rw-r--r--bytecomp/typeopt.mli27
-rw-r--r--byterun/.depend748
-rw-r--r--byterun/.ignore13
-rw-r--r--byterun/Makefile80
-rw-r--r--byterun/Makefile.common136
-rw-r--r--byterun/Makefile.nt57
-rw-r--r--byterun/alloc.c200
-rw-r--r--byterun/array.c412
-rw-r--r--byterun/backtrace.c211
-rw-r--r--byterun/backtrace_prim.c454
-rw-r--r--byterun/callback.c258
-rw-r--r--byterun/caml/.ignore3
-rw-r--r--byterun/caml/address_class.h82
-rw-r--r--byterun/caml/alloc.h54
-rw-r--r--byterun/caml/backtrace.h130
-rw-r--r--byterun/caml/backtrace_prim.h67
-rw-r--r--byterun/caml/callback.h57
-rw-r--r--byterun/caml/compact.h25
-rw-r--r--byterun/caml/compare.h19
-rw-r--r--byterun/caml/compatibility.h373
-rw-r--r--byterun/caml/config.h183
-rw-r--r--byterun/caml/custom.h71
-rw-r--r--byterun/caml/debugger.h111
-rw-r--r--byterun/caml/dynlink.h36
-rw-r--r--byterun/caml/exec.h60
-rw-r--r--byterun/caml/fail.h127
-rw-r--r--byterun/caml/finalise.h27
-rw-r--r--byterun/caml/fix_code.h40
-rw-r--r--byterun/caml/freelist.h34
-rw-r--r--byterun/caml/gc.h56
-rw-r--r--byterun/caml/gc_ctrl.h42
-rw-r--r--byterun/caml/globroots.h25
-rw-r--r--byterun/caml/hash.h37
-rw-r--r--byterun/caml/instrtrace.h30
-rw-r--r--byterun/caml/instruct.h62
-rw-r--r--byterun/caml/int64_emul.h287
-rw-r--r--byterun/caml/int64_format.h105
-rw-r--r--byterun/caml/int64_native.h61
-rw-r--r--byterun/caml/interp.h31
-rw-r--r--byterun/caml/intext.h168
-rw-r--r--byterun/caml/io.h116
-rw-r--r--byterun/caml/major_gc.h60
-rw-r--r--byterun/caml/md5.h41
-rw-r--r--byterun/caml/memory.h434
-rw-r--r--byterun/caml/minor_gc.h53
-rw-r--r--byterun/caml/misc.h210
-rw-r--r--byterun/caml/mlvalues.h305
-rw-r--r--byterun/caml/osdeps.h68
-rw-r--r--byterun/caml/prims.h34
-rw-r--r--byterun/caml/printexc.h33
-rw-r--r--byterun/caml/reverse.h86
-rw-r--r--byterun/caml/roots.h36
-rw-r--r--byterun/caml/signals.h57
-rw-r--r--byterun/caml/signals_machdep.h68
-rw-r--r--byterun/caml/stacks.h41
-rw-r--r--byterun/caml/startup.h39
-rw-r--r--byterun/caml/startup_aux.h26
-rw-r--r--byterun/caml/sys.h28
-rw-r--r--byterun/caml/ui.h26
-rw-r--r--byterun/caml/weak.h24
-rw-r--r--byterun/compact.c506
-rw-r--r--byterun/compare.c320
-rw-r--r--byterun/custom.c110
-rw-r--r--byterun/debugger.c439
-rw-r--r--byterun/dynlink.c279
-rw-r--r--byterun/extern.c857
-rw-r--r--byterun/fail.c145
-rw-r--r--byterun/finalise.c255
-rw-r--r--byterun/fix_code.c188
-rw-r--r--byterun/floats.c514
-rw-r--r--byterun/freelist.c558
-rw-r--r--byterun/gc_ctrl.c527
-rw-r--r--byterun/globroots.c287
-rw-r--r--byterun/hash.c412
-rw-r--r--byterun/instrtrace.c263
-rw-r--r--byterun/intern.c897
-rw-r--r--byterun/interp.c1165
-rw-r--r--byterun/ints.c780
-rw-r--r--byterun/io.c816
-rw-r--r--byterun/lexing.c229
-rw-r--r--byterun/main.c57
-rw-r--r--byterun/major_gc.c569
-rw-r--r--byterun/md5.c321
-rw-r--r--byterun/memory.c602
-rw-r--r--byterun/meta.c223
-rw-r--r--byterun/minor_gc.c341
-rw-r--r--byterun/misc.c197
-rw-r--r--byterun/obj.c250
-rw-r--r--byterun/parsing.c300
-rw-r--r--byterun/printexc.c143
-rw-r--r--byterun/roots.c101
-rw-r--r--byterun/signals.c332
-rw-r--r--byterun/signals_byt.c97
-rw-r--r--byterun/stacks.c113
-rw-r--r--byterun/startup.c459
-rw-r--r--byterun/startup_aux.c92
-rw-r--r--byterun/str.c348
-rw-r--r--byterun/sys.c509
-rw-r--r--byterun/terminfo.c130
-rw-r--r--byterun/unix.c321
-rw-r--r--byterun/weak.c192
-rw-r--r--byterun/win32.c536
-rw-r--r--compilerlibs/.gitignore0
-rw-r--r--config/.ignore3
-rw-r--r--config/Makefile-templ228
-rw-r--r--config/Makefile.mingw177
-rw-r--r--config/Makefile.mingw64177
-rw-r--r--config/Makefile.msvc180
-rw-r--r--config/Makefile.msvc64184
-rw-r--r--config/auto-aux/.ignore1
-rw-r--r--config/auto-aux/align.c101
-rw-r--r--config/auto-aux/ansi.c25
-rw-r--r--config/auto-aux/async_io.c58
-rw-r--r--config/auto-aux/cckind.c28
-rw-r--r--config/auto-aux/cfi.S6
-rw-r--r--config/auto-aux/dblalign.c52
-rw-r--r--config/auto-aux/elf.c24
-rw-r--r--config/auto-aux/endian.c40
-rw-r--r--config/auto-aux/getgroups.c30
-rw-r--r--config/auto-aux/gethostbyaddr.c49
-rw-r--r--config/auto-aux/gethostbyname.c39
-rwxr-xr-xconfig/auto-aux/hasgot42
-rw-r--r--config/auto-aux/hasgot242
-rw-r--r--config/auto-aux/ia32sse2.c22
-rw-r--r--config/auto-aux/initgroups.c24
-rw-r--r--config/auto-aux/int64align.c63
-rw-r--r--config/auto-aux/nanosecond_stat.c28
-rwxr-xr-xconfig/auto-aux/runtest22
-rwxr-xr-xconfig/auto-aux/searchpath32
-rw-r--r--config/auto-aux/setgroups.c26
-rwxr-xr-xconfig/auto-aux/sharpbang2
-rwxr-xr-xconfig/auto-aux/sharpbang22
-rw-r--r--config/auto-aux/signals.c66
-rw-r--r--config/auto-aux/sizes.c25
-rw-r--r--config/auto-aux/solaris-ld21
-rw-r--r--config/auto-aux/tryassemble31
-rwxr-xr-xconfig/auto-aux/trycompile21
-rwxr-xr-xconfig/gnu/config.guess1558
-rwxr-xr-xconfig/gnu/config.sub1788
-rw-r--r--config/m-nt.h43
-rw-r--r--config/m-templ.h81
-rw-r--r--config/s-nt.h33
-rw-r--r--config/s-templ.h218
-rwxr-xr-xconfigure1857
-rw-r--r--debugger/.depend215
-rw-r--r--debugger/.ignore7
-rw-r--r--debugger/Makefile14
-rw-r--r--debugger/Makefile.nt14
-rw-r--r--debugger/Makefile.shared129
-rw-r--r--debugger/breakpoints.ml225
-rw-r--r--debugger/breakpoints.mli59
-rw-r--r--debugger/checkpoints.ml83
-rw-r--r--debugger/checkpoints.mli56
-rw-r--r--debugger/command_line.ml1225
-rw-r--r--debugger/command_line.mli20
-rw-r--r--debugger/debugcom.ml306
-rw-r--r--debugger/debugcom.mli111
-rw-r--r--debugger/debugger_config.ml84
-rw-r--r--debugger/debugger_config.mli37
-rw-r--r--debugger/eval.ml208
-rw-r--r--debugger/eval.mli38
-rw-r--r--debugger/events.ml46
-rw-r--r--debugger/events.mli27
-rw-r--r--debugger/exec.ml51
-rw-r--r--debugger/exec.mli17
-rw-r--r--debugger/frames.ml127
-rw-r--r--debugger/frames.mli53
-rw-r--r--debugger/history.ml41
-rw-r--r--debugger/history.mli18
-rw-r--r--debugger/input_handling.ml113
-rw-r--r--debugger/input_handling.mli58
-rw-r--r--debugger/int64ops.ml24
-rw-r--r--debugger/int64ops.mli24
-rw-r--r--debugger/lexer.mli17
-rw-r--r--debugger/lexer.mll95
-rw-r--r--debugger/loadprinter.ml176
-rw-r--r--debugger/loadprinter.mli32
-rw-r--r--debugger/main.ml232
-rw-r--r--debugger/parameters.ml39
-rw-r--r--debugger/parameters.mli27
-rw-r--r--debugger/parser.mly253
-rw-r--r--debugger/parser_aux.mli31
-rw-r--r--debugger/pattern_matching.ml251
-rw-r--r--debugger/pattern_matching.mli20
-rw-r--r--debugger/pos.ml25
-rw-r--r--debugger/pos.mli13
-rw-r--r--debugger/primitives.ml136
-rw-r--r--debugger/primitives.mli63
-rw-r--r--debugger/printval.ml106
-rw-r--r--debugger/printval.mli31
-rw-r--r--debugger/program_loading.ml187
-rw-r--r--debugger/program_loading.mli32
-rw-r--r--debugger/program_management.ml158
-rw-r--r--debugger/program_management.mli25
-rw-r--r--debugger/question.ml47
-rw-r--r--debugger/question.mli14
-rw-r--r--debugger/show_information.ml105
-rw-r--r--debugger/show_information.mli24
-rw-r--r--debugger/show_source.ml86
-rw-r--r--debugger/show_source.mli23
-rw-r--r--debugger/source.ml190
-rw-r--r--debugger/source.mli59
-rw-r--r--debugger/symbols.ml209
-rw-r--r--debugger/symbols.mli48
-rw-r--r--debugger/time_travel.ml648
-rw-r--r--debugger/time_travel.mli35
-rw-r--r--debugger/trap_barrier.ml45
-rw-r--r--debugger/trap_barrier.mli25
-rw-r--r--debugger/unix_tools.ml142
-rw-r--r--debugger/unix_tools.mli32
-rw-r--r--driver/compenv.ml311
-rw-r--r--driver/compenv.mli43
-rw-r--r--driver/compile.ml104
-rw-r--r--driver/compile.mli19
-rw-r--r--driver/compmisc.ml60
-rw-r--r--driver/compmisc.mli14
-rw-r--r--driver/errors.ml16
-rw-r--r--driver/errors.mli16
-rw-r--r--driver/main.ml205
-rw-r--r--driver/main.mli15
-rw-r--r--driver/main_args.ml976
-rw-r--r--driver/main_args.mli186
-rw-r--r--driver/ocamlcomp.sh.in17
-rw-r--r--driver/optcompile.ml98
-rw-r--r--driver/optcompile.mli19
-rw-r--r--driver/opterrors.ml16
-rw-r--r--driver/opterrors.mli15
-rw-r--r--driver/optmain.ml224
-rw-r--r--driver/optmain.mli15
-rw-r--r--driver/pparse.ml202
-rw-r--r--driver/pparse.mli49
-rw-r--r--emacs/.ignore2
-rw-r--r--emacs/COPYING340
-rw-r--r--emacs/Makefile82
-rw-r--r--emacs/README209
-rw-r--r--emacs/README.itz177
-rw-r--r--emacs/caml-compat.el39
-rw-r--r--emacs/caml-emacs.el43
-rw-r--r--emacs/caml-font-old.el139
-rw-r--r--emacs/caml-font.el410
-rw-r--r--emacs/caml-help.el854
-rw-r--r--emacs/caml-hilit.el65
-rw-r--r--emacs/caml-types.el793
-rw-r--r--emacs/caml-xemacs.el55
-rw-r--r--emacs/caml.el1961
-rw-r--r--emacs/camldebug.el793
-rw-r--r--emacs/inf-caml.el362
-rw-r--r--emacs/ocamltags.in139
-rw-r--r--experimental/doligez/check-bounds.diff149
-rwxr-xr-xexperimental/doligez/checkheaders152
-rw-r--r--experimental/frisch/Makefile79
-rw-r--r--experimental/frisch/copy_typedef.ml181
-rw-r--r--experimental/frisch/eval.ml141
-rw-r--r--experimental/frisch/extension_points.txt740
-rw-r--r--experimental/frisch/ifdef.ml118
-rw-r--r--experimental/frisch/js_syntax.ml112
-rw-r--r--experimental/frisch/metaquot_test.ml27
-rw-r--r--experimental/frisch/minidoc.ml72
-rw-r--r--experimental/frisch/nomli.ml114
-rw-r--r--experimental/frisch/ppx_builder.ml100
-rw-r--r--experimental/frisch/ppx_matches.ml29
-rw-r--r--experimental/frisch/test_builder.ml19
-rw-r--r--experimental/frisch/test_copy_typedef.ml19
-rw-r--r--experimental/frisch/test_copy_typedef.mli20
-rw-r--r--experimental/frisch/test_eval.ml37
-rw-r--r--experimental/frisch/test_ifdef.ml25
-rw-r--r--experimental/frisch/test_js.ml22
-rw-r--r--experimental/frisch/test_matches.ml3
-rw-r--r--experimental/frisch/test_nomli.ml30
-rw-r--r--experimental/frisch/testdoc.mli29
-rw-r--r--experimental/frisch/unused_exported_values.ml63
-rw-r--r--experimental/garrigue/.cvsignore2
-rw-r--r--experimental/garrigue/caml_set_oid.diff141
-rw-r--r--experimental/garrigue/coerce.diff93
-rw-r--r--experimental/garrigue/countchars.ml16
-rw-r--r--experimental/garrigue/dirs_multimatch1
-rw-r--r--experimental/garrigue/dirs_poly1
-rw-r--r--experimental/garrigue/fixedtypes.ml77
-rw-r--r--experimental/garrigue/gadt-escape-check.diff519
-rw-r--r--experimental/garrigue/generative-functors.diff1008
-rw-r--r--experimental/garrigue/impure-functors.diff223
-rw-r--r--experimental/garrigue/marshal_objects.diff800
-rw-r--r--experimental/garrigue/module-errors.diff403
-rw-r--r--experimental/garrigue/multimatch.diff1418
-rw-r--r--experimental/garrigue/multimatch.ml158
-rw-r--r--experimental/garrigue/newlabels.ps1458
-rw-r--r--experimental/garrigue/nongeneral-let.diff428
-rw-r--r--experimental/garrigue/objvariant.diff354
-rw-r--r--experimental/garrigue/objvariant.ml42
-rw-r--r--experimental/garrigue/parser-lessminus.diff77
-rw-r--r--experimental/garrigue/pattern-local-types.diff467
-rw-r--r--experimental/garrigue/printers.ml11
-rw-r--r--experimental/garrigue/propagation-to-patterns.diff212
-rw-r--r--experimental/garrigue/show_types.diff419
-rw-r--r--experimental/garrigue/tests.ml22
-rw-r--r--experimental/garrigue/valvirt.diff2349
-rw-r--r--experimental/garrigue/variable-names-Tvar.diff1656
-rw-r--r--experimental/garrigue/variable-names.ml4
-rw-r--r--experimental/garrigue/varunion.ml435
-rw-r--r--experimental/garrigue/with-module-type.diff530
-rw-r--r--lex/.depend34
-rw-r--r--lex/.ignore6
-rw-r--r--lex/Makefile74
-rw-r--r--lex/Makefile.nt75
-rw-r--r--lex/common.ml171
-rw-r--r--lex/common.mli28
-rw-r--r--lex/compact.ml229
-rw-r--r--lex/compact.mli31
-rw-r--r--lex/cset.ml94
-rw-r--r--lex/cset.mli31
-rw-r--r--lex/lexer.mli20
-rw-r--r--lex/lexer.mll304
-rw-r--r--lex/lexgen.ml1194
-rw-r--r--lex/lexgen.mli57
-rw-r--r--lex/main.ml122
-rw-r--r--lex/output.ml149
-rw-r--r--lex/output.mli24
-rw-r--r--lex/outputbis.ml238
-rw-r--r--lex/outputbis.mli21
-rw-r--r--lex/parser.mly199
-rw-r--r--lex/syntax.ml46
-rw-r--r--lex/syntax.mli43
-rw-r--r--lex/table.ml56
-rw-r--r--lex/table.mli31
-rw-r--r--man/Makefile24
-rw-r--r--man/ocaml.m255
-rw-r--r--man/ocamlc.m953
-rw-r--r--man/ocamlcp.m139
-rw-r--r--man/ocamldebug.m105
-rw-r--r--man/ocamldep.m138
-rw-r--r--man/ocamldoc.m459
-rw-r--r--man/ocamllex.m98
-rw-r--r--man/ocamlmktop.m94
-rw-r--r--man/ocamlopt.m707
-rw-r--r--man/ocamlprof.m84
-rw-r--r--man/ocamlrun.m227
-rw-r--r--man/ocamlyacc.m106
-rw-r--r--ocamlbuild/.depend207
-rw-r--r--ocamlbuild/AUTHORS2
-rw-r--r--ocamlbuild/ChangeLog3621
-rw-r--r--ocamlbuild/FAQ35
-rw-r--r--ocamlbuild/Makefile214
-rw-r--r--ocamlbuild/TODO38
-rw-r--r--ocamlbuild/_tags23
-rw-r--r--ocamlbuild/bool.ml40
-rw-r--r--ocamlbuild/bool.mli36
-rw-r--r--ocamlbuild/command.ml423
-rw-r--r--ocamlbuild/command.mli52
-rw-r--r--ocamlbuild/configuration.ml96
-rw-r--r--ocamlbuild/configuration.mli45
-rw-r--r--ocamlbuild/const.ml11
-rw-r--r--ocamlbuild/digest_cache.ml43
-rw-r--r--ocamlbuild/digest_cache.mli19
-rw-r--r--ocamlbuild/discard_printf.ml17
-rw-r--r--ocamlbuild/discard_printf.mli21
-rw-r--r--ocamlbuild/display.ml396
-rw-r--r--ocamlbuild/display.mli36
-rw-r--r--ocamlbuild/examples/example1/hello.ml18
-rw-r--r--ocamlbuild/examples/example2/greet.ml19
-rw-r--r--ocamlbuild/examples/example2/hello.ml27
-rw-r--r--ocamlbuild/examples/example3/epoch.ml19
-rwxr-xr-xocamlbuild/examples/example3/make.sh44
-rw-r--r--ocamlbuild/exit_codes.ml28
-rw-r--r--ocamlbuild/exit_codes.mli28
-rw-r--r--ocamlbuild/fda.ml83
-rw-r--r--ocamlbuild/fda.mli20
-rw-r--r--ocamlbuild/findlib.ml199
-rw-r--r--ocamlbuild/findlib.mli17
-rw-r--r--ocamlbuild/flags.ml79
-rw-r--r--ocamlbuild/flags.mli41
-rw-r--r--ocamlbuild/glob.ml414
-rw-r--r--ocamlbuild/glob.mli25
-rw-r--r--ocamlbuild/glob_ast.ml33
-rw-r--r--ocamlbuild/glob_ast.mli27
-rw-r--r--ocamlbuild/glob_lexer.mli29
-rw-r--r--ocamlbuild/glob_lexer.mll118
-rw-r--r--ocamlbuild/hooks.ml28
-rw-r--r--ocamlbuild/hooks.mli25
-rw-r--r--ocamlbuild/hygiene.ml177
-rw-r--r--ocamlbuild/hygiene.mli48
-rw-r--r--ocamlbuild/lexers.mli49
-rw-r--r--ocamlbuild/lexers.mll192
-rw-r--r--ocamlbuild/loc.ml35
-rw-r--r--ocamlbuild/loc.mli7
-rw-r--r--ocamlbuild/log.ml81
-rw-r--r--ocamlbuild/log.mli45
-rw-r--r--ocamlbuild/main.ml359
-rw-r--r--ocamlbuild/main.mli16
-rw-r--r--ocamlbuild/man/ocamlbuild.1268
-rw-r--r--ocamlbuild/misc/opentracer.ml103
-rw-r--r--ocamlbuild/my_std.ml432
-rw-r--r--ocamlbuild/my_std.mli68
-rw-r--r--ocamlbuild/my_unix.ml147
-rw-r--r--ocamlbuild/my_unix.mli75
-rw-r--r--ocamlbuild/ocaml_arch.ml137
-rw-r--r--ocamlbuild/ocaml_arch.mli18
-rw-r--r--ocamlbuild/ocaml_compiler.ml433
-rw-r--r--ocamlbuild/ocaml_compiler.mli97
-rw-r--r--ocamlbuild/ocaml_dependencies.ml263
-rw-r--r--ocamlbuild/ocaml_dependencies.mli45
-rw-r--r--ocamlbuild/ocaml_specific.ml806
-rw-r--r--ocamlbuild/ocaml_specific.mli18
-rw-r--r--ocamlbuild/ocaml_tools.ml164
-rw-r--r--ocamlbuild/ocaml_tools.mli35
-rw-r--r--ocamlbuild/ocaml_utils.ml179
-rw-r--r--ocamlbuild/ocaml_utils.mli47
-rw-r--r--ocamlbuild/ocamlbuild.ml17
-rw-r--r--ocamlbuild/ocamlbuild.mli16
-rw-r--r--ocamlbuild/ocamlbuild.mltop3
-rw-r--r--ocamlbuild/ocamlbuild.odocl41
-rw-r--r--ocamlbuild/ocamlbuild_executor.ml351
-rw-r--r--ocamlbuild/ocamlbuild_executor.mli56
-rw-r--r--ocamlbuild/ocamlbuild_pack.mlpack43
-rw-r--r--ocamlbuild/ocamlbuild_plugin.ml64
-rw-r--r--ocamlbuild/ocamlbuild_plugin.mli18
-rw-r--r--ocamlbuild/ocamlbuild_unix_plugin.ml96
-rw-r--r--ocamlbuild/ocamlbuild_unix_plugin.mli16
-rw-r--r--ocamlbuild/ocamlbuild_where.ml20
-rw-r--r--ocamlbuild/ocamlbuild_where.mli19
-rw-r--r--ocamlbuild/ocamlbuildlib.mllib4
-rw-r--r--ocamlbuild/ocamlbuildlight.ml16
-rw-r--r--ocamlbuild/ocamlbuildlight.mli16
-rw-r--r--ocamlbuild/ocamlbuildlightlib.mllib2
-rw-r--r--ocamlbuild/options.ml374
-rw-r--r--ocamlbuild/options.mli35
-rw-r--r--ocamlbuild/param_tags.ml63
-rw-r--r--ocamlbuild/param_tags.mli51
-rw-r--r--ocamlbuild/pathname.ml160
-rw-r--r--ocamlbuild/pathname.mli18
-rw-r--r--ocamlbuild/plugin.ml263
-rw-r--r--ocamlbuild/plugin.mli19
-rw-r--r--ocamlbuild/ppcache.ml92
-rw-r--r--ocamlbuild/ppcache.mli16
-rw-r--r--ocamlbuild/report.ml63
-rw-r--r--ocamlbuild/report.mli20
-rw-r--r--ocamlbuild/resource.ml403
-rw-r--r--ocamlbuild/resource.mli78
-rw-r--r--ocamlbuild/rule.ml339
-rw-r--r--ocamlbuild/rule.mli86
-rw-r--r--ocamlbuild/shell.ml89
-rw-r--r--ocamlbuild/shell.mli32
-rw-r--r--ocamlbuild/signatures.mli886
-rw-r--r--ocamlbuild/slurp.ml189
-rw-r--r--ocamlbuild/slurp.mli50
-rw-r--r--ocamlbuild/solver.ml135
-rw-r--r--ocamlbuild/solver.mli25
-rwxr-xr-xocamlbuild/start.sh121
-rw-r--r--ocamlbuild/tags.ml45
-rw-r--r--ocamlbuild/tags.mli17
-rw-r--r--ocamlbuild/test/good-output1473
-rwxr-xr-xocamlbuild/test/runtest.sh56
-rw-r--r--ocamlbuild/test/test1/foo.ml14
-rw-r--r--ocamlbuild/test/test10/dbdi24
-rwxr-xr-xocamlbuild/test/test10/test.sh18
-rw-r--r--ocamlbuild/test/test11/_tags14
-rw-r--r--ocamlbuild/test/test11/a/aa.ml14
-rw-r--r--ocamlbuild/test/test11/a/aa.mli14
-rw-r--r--ocamlbuild/test/test11/b/bb.ml14
-rw-r--r--ocamlbuild/test/test11/b/libb.mllib1
-rw-r--r--ocamlbuild/test/test11/myocamlbuild.ml18
-rwxr-xr-xocamlbuild/test/test11/test.sh25
-rw-r--r--ocamlbuild/test/test2/_tags15
-rw-r--r--ocamlbuild/test/test2/tata.ml14
-rw-r--r--ocamlbuild/test/test2/tata.mli15
-rwxr-xr-xocamlbuild/test/test2/test.sh30
-rw-r--r--ocamlbuild/test/test2/titi.ml14
-rw-r--r--ocamlbuild/test/test2/toto.ml18
-rw-r--r--ocamlbuild/test/test2/tutu.ml15
-rw-r--r--ocamlbuild/test/test2/tutu.mli16
-rw-r--r--ocamlbuild/test/test2/tyty.mli14
-rw-r--r--ocamlbuild/test/test2/vivi1.ml15
-rw-r--r--ocamlbuild/test/test2/vivi2.ml15
-rw-r--r--ocamlbuild/test/test2/vivi3.ml15
-rw-r--r--ocamlbuild/test/test3/_tags13
-rw-r--r--ocamlbuild/test/test3/a.ml14
-rw-r--r--ocamlbuild/test/test3/a.mli14
-rw-r--r--ocamlbuild/test/test3/b.ml14
-rw-r--r--ocamlbuild/test/test3/b.mli14
-rw-r--r--ocamlbuild/test/test3/c.ml14
-rw-r--r--ocamlbuild/test/test3/c.mli14
-rw-r--r--ocamlbuild/test/test3/d.ml14
-rw-r--r--ocamlbuild/test/test3/d.mli14
-rw-r--r--ocamlbuild/test/test3/e.ml14
-rw-r--r--ocamlbuild/test/test3/e.mli14
-rw-r--r--ocamlbuild/test/test3/f.ml15
-rw-r--r--ocamlbuild/test/test3/f.mli14
-rw-r--r--ocamlbuild/test/test3/proj.odocl1
-rwxr-xr-xocamlbuild/test/test3/test.sh23
-rw-r--r--ocamlbuild/test/test4/_tags14
-rw-r--r--ocamlbuild/test/test4/a/aa.ml14
-rw-r--r--ocamlbuild/test/test4/a/aa.mli14
-rw-r--r--ocamlbuild/test/test4/b/bb.ml15
-rwxr-xr-xocamlbuild/test/test4/test.sh23
-rw-r--r--ocamlbuild/test/test5/_tags13
-rw-r--r--ocamlbuild/test/test5/a.ml14
-rw-r--r--ocamlbuild/test/test5/a.mli14
-rw-r--r--ocamlbuild/test/test5/b.ml14
-rw-r--r--ocamlbuild/test/test5/c.mlpack1
-rw-r--r--ocamlbuild/test/test5/d.ml14
-rw-r--r--ocamlbuild/test/test5/stack.ml14
-rwxr-xr-xocamlbuild/test/test5/test.sh23
-rw-r--r--ocamlbuild/test/test6/a.ml14
-rw-r--r--ocamlbuild/test/test6/a.mli14
-rw-r--r--ocamlbuild/test/test6/b.ml14
-rw-r--r--ocamlbuild/test/test6/b.mli14
-rw-r--r--ocamlbuild/test/test6/b.mli.v114
-rw-r--r--ocamlbuild/test/test6/b.mli.v215
-rw-r--r--ocamlbuild/test/test6/d.ml15
-rw-r--r--ocamlbuild/test/test6/d.mli14
-rw-r--r--ocamlbuild/test/test6/d.mli.v115
-rw-r--r--ocamlbuild/test/test6/d.mli.v214
-rw-r--r--ocamlbuild/test/test6/main.ml14
-rw-r--r--ocamlbuild/test/test6/main.mli14
-rwxr-xr-xocamlbuild/test/test6/test.sh37
-rw-r--r--ocamlbuild/test/test7/_tags13
-rw-r--r--ocamlbuild/test/test7/aa.ml14
-rw-r--r--ocamlbuild/test/test7/bb.mli14
-rw-r--r--ocamlbuild/test/test7/bb1.ml14
-rw-r--r--ocamlbuild/test/test7/bb2.ml16
-rw-r--r--ocamlbuild/test/test7/bb3.ml16
-rw-r--r--ocamlbuild/test/test7/bbcc.mllib1
-rw-r--r--ocamlbuild/test/test7/c2.ml14
-rw-r--r--ocamlbuild/test/test7/c2.mli14
-rw-r--r--ocamlbuild/test/test7/c3.ml14
-rw-r--r--ocamlbuild/test/test7/cc.ml14
-rw-r--r--ocamlbuild/test/test7/cool_plugin.ml14
-rw-r--r--ocamlbuild/test/test7/main.ml14
-rw-r--r--ocamlbuild/test/test7/myocamlbuild.ml20
-rwxr-xr-xocamlbuild/test/test7/test.sh30
-rw-r--r--ocamlbuild/test/test8/a.ml14
-rw-r--r--ocamlbuild/test/test8/myocamlbuild.ml29
-rwxr-xr-xocamlbuild/test/test8/test.sh23
-rw-r--r--ocamlbuild/test/test9/dbgl22
-rwxr-xr-xocamlbuild/test/test9/test.sh18
-rw-r--r--ocamlbuild/test/test9/testglob.ml147
-rw-r--r--ocamlbuild/test/test_virtual/foo.itarget1
-rw-r--r--ocamlbuild/test/test_virtual/foo11
-rw-r--r--ocamlbuild/test/test_virtual/foo21
-rw-r--r--ocamlbuild/test/test_virtual/myocamlbuild.ml24
-rwxr-xr-xocamlbuild/test/test_virtual/test.sh28
-rw-r--r--ocamlbuild/testsuite/README13
-rw-r--r--ocamlbuild/testsuite/external.ml22
-rw-r--r--ocamlbuild/testsuite/external_test_header.ml7
-rw-r--r--ocamlbuild/testsuite/findlibonly.ml42
-rw-r--r--ocamlbuild/testsuite/findlibonly_test_header.ml9
-rw-r--r--ocamlbuild/testsuite/internal.ml324
-rw-r--r--ocamlbuild/testsuite/internal_test_header.ml10
-rw-r--r--ocamlbuild/testsuite/ocamlbuild_test.ml537
-rw-r--r--ocamlbuild/tools.ml47
-rw-r--r--ocamlbuild/tools.mli20
-rw-r--r--ocamldoc/.depend269
-rw-r--r--ocamldoc/.ignore16
-rw-r--r--ocamldoc/Changes.txt209
-rw-r--r--ocamldoc/Makefile357
-rw-r--r--ocamldoc/Makefile.nt253
-rw-r--r--ocamldoc/generators/odoc_literate.ml213
-rw-r--r--ocamldoc/generators/odoc_todo.ml232
-rw-r--r--ocamldoc/ocamldoc.hva31
-rw-r--r--ocamldoc/ocamldoc.sty58
-rw-r--r--ocamldoc/odoc.ml136
-rw-r--r--ocamldoc/odoc_analyse.ml466
-rw-r--r--ocamldoc/odoc_analyse.mli30
-rw-r--r--ocamldoc/odoc_args.ml395
-rw-r--r--ocamldoc/odoc_args.mli50
-rw-r--r--ocamldoc/odoc_ast.ml1932
-rw-r--r--ocamldoc/odoc_ast.mli98
-rw-r--r--ocamldoc/odoc_class.ml249
-rw-r--r--ocamldoc/odoc_comments.ml347
-rw-r--r--ocamldoc/odoc_comments.mli73
-rw-r--r--ocamldoc/odoc_comments_global.ml48
-rw-r--r--ocamldoc/odoc_comments_global.mli49
-rw-r--r--ocamldoc/odoc_config.ml17
-rw-r--r--ocamldoc/odoc_config.mli19
-rw-r--r--ocamldoc/odoc_control.ml11
-rw-r--r--ocamldoc/odoc_cross.ml1103
-rw-r--r--ocamldoc/odoc_cross.mli19
-rw-r--r--ocamldoc/odoc_dag2html.ml1749
-rw-r--r--ocamldoc/odoc_dag2html.mli28
-rw-r--r--ocamldoc/odoc_dep.ml219
-rw-r--r--ocamldoc/odoc_dot.ml144
-rw-r--r--ocamldoc/odoc_env.ml247
-rw-r--r--ocamldoc/odoc_env.mli75
-rw-r--r--ocamldoc/odoc_exception.ml30
-rw-r--r--ocamldoc/odoc_extension.ml45
-rw-r--r--ocamldoc/odoc_gen.ml61
-rw-r--r--ocamldoc/odoc_gen.mli43
-rw-r--r--ocamldoc/odoc_global.ml77
-rw-r--r--ocamldoc/odoc_global.mli97
-rw-r--r--ocamldoc/odoc_html.ml2810
-rw-r--r--ocamldoc/odoc_info.ml335
-rw-r--r--ocamldoc/odoc_info.mli1087
-rw-r--r--ocamldoc/odoc_inherit.ml11
-rw-r--r--ocamldoc/odoc_latex.ml1334
-rw-r--r--ocamldoc/odoc_latex_style.ml90
-rw-r--r--ocamldoc/odoc_lexer.mll419
-rw-r--r--ocamldoc/odoc_man.ml1316
-rw-r--r--ocamldoc/odoc_merge.ml1085
-rw-r--r--ocamldoc/odoc_merge.mli34
-rw-r--r--ocamldoc/odoc_messages.ml393
-rw-r--r--ocamldoc/odoc_misc.ml493
-rw-r--r--ocamldoc/odoc_misc.mli114
-rw-r--r--ocamldoc/odoc_module.ml554
-rw-r--r--ocamldoc/odoc_name.ml224
-rw-r--r--ocamldoc/odoc_name.mli71
-rw-r--r--ocamldoc/odoc_ocamlhtml.mll542
-rw-r--r--ocamldoc/odoc_parameter.ml122
-rw-r--r--ocamldoc/odoc_parser.mly174
-rw-r--r--ocamldoc/odoc_print.ml100
-rw-r--r--ocamldoc/odoc_print.mli31
-rw-r--r--ocamldoc/odoc_scan.ml188
-rw-r--r--ocamldoc/odoc_search.ml752
-rw-r--r--ocamldoc/odoc_search.mli239
-rw-r--r--ocamldoc/odoc_see_lexer.mll100
-rw-r--r--ocamldoc/odoc_sig.ml1562
-rw-r--r--ocamldoc/odoc_sig.mli182
-rw-r--r--ocamldoc/odoc_str.ml385
-rw-r--r--ocamldoc/odoc_str.mli59
-rw-r--r--ocamldoc/odoc_test.ml123
-rw-r--r--ocamldoc/odoc_texi.ml1313
-rw-r--r--ocamldoc/odoc_text.ml166
-rw-r--r--ocamldoc/odoc_text.mli23
-rw-r--r--ocamldoc/odoc_text_lexer.mll854
-rw-r--r--ocamldoc/odoc_text_parser.mly212
-rw-r--r--ocamldoc/odoc_to_text.ml618
-rw-r--r--ocamldoc/odoc_type.ml70
-rw-r--r--ocamldoc/odoc_types.ml140
-rw-r--r--ocamldoc/odoc_types.mli139
-rw-r--r--ocamldoc/odoc_value.ml137
-rwxr-xr-xocamldoc/remove_DEBUG20
-rw-r--r--ocamldoc/runocamldoc23
-rw-r--r--otherlibs/Makefile23
-rw-r--r--otherlibs/Makefile.nt21
-rw-r--r--otherlibs/Makefile.shared94
-rw-r--r--otherlibs/bigarray/.depend27
-rw-r--r--otherlibs/bigarray/Makefile27
-rw-r--r--otherlibs/bigarray/Makefile.nt27
-rw-r--r--otherlibs/bigarray/bigarray.h123
-rw-r--r--otherlibs/bigarray/bigarray.ml310
-rw-r--r--otherlibs/bigarray/bigarray.mli885
-rw-r--r--otherlibs/bigarray/bigarray_stubs.c1300
-rw-r--r--otherlibs/bigarray/libbigarray.clib1
-rw-r--r--otherlibs/bigarray/libbigarraywin32.clib1
-rw-r--r--otherlibs/bigarray/mmap_unix.c202
-rw-r--r--otherlibs/bigarray/mmap_win32.c153
-rw-r--r--otherlibs/dynlink/.ignore1
-rw-r--r--otherlibs/dynlink/Makefile110
-rw-r--r--otherlibs/dynlink/Makefile.nt16
-rw-r--r--otherlibs/dynlink/dynlink.ml332
-rw-r--r--otherlibs/dynlink/dynlink.mli146
-rw-r--r--otherlibs/dynlink/dynlinkaux.mlpack5
-rw-r--r--otherlibs/dynlink/extract_crc.ml51
-rw-r--r--otherlibs/dynlink/natdynlink.ml248
-rw-r--r--otherlibs/graph/.depend77
-rw-r--r--otherlibs/graph/Makefile32
-rw-r--r--otherlibs/graph/color.c231
-rw-r--r--otherlibs/graph/draw.c125
-rw-r--r--otherlibs/graph/dump_img.c56
-rw-r--r--otherlibs/graph/events.c275
-rw-r--r--otherlibs/graph/fill.c88
-rw-r--r--otherlibs/graph/graphics.ml265
-rw-r--r--otherlibs/graph/graphics.mli383
-rw-r--r--otherlibs/graph/graphics.mllib1
-rw-r--r--otherlibs/graph/graphicsX11.ml40
-rw-r--r--otherlibs/graph/graphicsX11.mli28
-rw-r--r--otherlibs/graph/image.c106
-rw-r--r--otherlibs/graph/image.h27
-rw-r--r--otherlibs/graph/libgraph.h87
-rw-r--r--otherlibs/graph/libgraphics.clib3
-rw-r--r--otherlibs/graph/make_img.c97
-rw-r--r--otherlibs/graph/open.c398
-rw-r--r--otherlibs/graph/point_col.c29
-rw-r--r--otherlibs/graph/sound.c32
-rw-r--r--otherlibs/graph/subwindow.c43
-rw-r--r--otherlibs/graph/text.c84
-rw-r--r--otherlibs/num/.depend41
-rw-r--r--otherlibs/num/.depend.nt66
-rw-r--r--otherlibs/num/Makefile37
-rw-r--r--otherlibs/num/Makefile.nt36
-rw-r--r--otherlibs/num/README55
-rw-r--r--otherlibs/num/arith_flags.ml22
-rw-r--r--otherlibs/num/arith_flags.mli18
-rw-r--r--otherlibs/num/arith_status.ml98
-rw-r--r--otherlibs/num/arith_status.mli57
-rw-r--r--otherlibs/num/big_int.ml880
-rw-r--r--otherlibs/num/big_int.mli197
-rw-r--r--otherlibs/num/bng.c433
-rw-r--r--otherlibs/num/bng.h156
-rw-r--r--otherlibs/num/bng_amd64.c195
-rw-r--r--otherlibs/num/bng_arm64.c20
-rw-r--r--otherlibs/num/bng_digit.c178
-rw-r--r--otherlibs/num/bng_ia32.c411
-rw-r--r--otherlibs/num/bng_ppc.c94
-rw-r--r--otherlibs/num/bng_sparc.c77
-rw-r--r--otherlibs/num/int_misc.ml34
-rw-r--r--otherlibs/num/int_misc.mli23
-rw-r--r--otherlibs/num/libnums.clib1
-rw-r--r--otherlibs/num/nat.h18
-rw-r--r--otherlibs/num/nat.ml575
-rw-r--r--otherlibs/num/nat.mli71
-rw-r--r--otherlibs/num/nat_stubs.c418
-rw-r--r--otherlibs/num/num.ml445
-rw-r--r--otherlibs/num/num.mli170
-rw-r--r--otherlibs/num/nums.mllib1
-rw-r--r--otherlibs/num/ratio.ml616
-rw-r--r--otherlibs/num/ratio.mli91
-rw-r--r--otherlibs/str/.depend11
-rw-r--r--otherlibs/str/Makefile33
-rw-r--r--otherlibs/str/Makefile.nt26
-rw-r--r--otherlibs/str/libstr.clib1
-rw-r--r--otherlibs/str/str.ml754
-rw-r--r--otherlibs/str/str.mli289
-rw-r--r--otherlibs/str/strstubs.c530
-rw-r--r--otherlibs/systhreads/.depend30
-rw-r--r--otherlibs/systhreads/.ignore1
-rw-r--r--otherlibs/systhreads/Makefile114
-rw-r--r--otherlibs/systhreads/Makefile.nt104
-rw-r--r--otherlibs/systhreads/condition.ml18
-rw-r--r--otherlibs/systhreads/condition.mli51
-rw-r--r--otherlibs/systhreads/event.ml272
-rw-r--r--otherlibs/systhreads/event.mli79
-rw-r--r--otherlibs/systhreads/libthreads.clib1
-rw-r--r--otherlibs/systhreads/mutex.ml18
-rw-r--r--otherlibs/systhreads/mutex.mli47
-rw-r--r--otherlibs/systhreads/st_posix.h426
-rw-r--r--otherlibs/systhreads/st_stubs.c889
-rw-r--r--otherlibs/systhreads/st_win32.h421
-rw-r--r--otherlibs/systhreads/thread.ml88
-rw-r--r--otherlibs/systhreads/thread.mli131
-rw-r--r--otherlibs/systhreads/threadUnix.ml63
-rw-r--r--otherlibs/systhreads/threadUnix.mli92
-rw-r--r--otherlibs/systhreads/threads.h66
-rw-r--r--otherlibs/systhreads/threads.mllib1
-rw-r--r--otherlibs/threads/.depend38
-rw-r--r--otherlibs/threads/.ignore3
-rw-r--r--otherlibs/threads/Makefile131
-rw-r--r--otherlibs/threads/condition.ml33
-rw-r--r--otherlibs/threads/condition.mli51
-rw-r--r--otherlibs/threads/event.ml272
-rw-r--r--otherlibs/threads/event.mli79
-rw-r--r--otherlibs/threads/libvmthreads.clib1
-rw-r--r--otherlibs/threads/marshal.ml59
-rw-r--r--otherlibs/threads/mutex.ml36
-rw-r--r--otherlibs/threads/mutex.mli47
-rw-r--r--otherlibs/threads/pervasives.ml607
-rw-r--r--otherlibs/threads/scheduler.c874
-rw-r--r--otherlibs/threads/thread.ml145
-rw-r--r--otherlibs/threads/thread.mli138
-rw-r--r--otherlibs/threads/threadUnix.ml66
-rw-r--r--otherlibs/threads/threadUnix.mli99
-rw-r--r--otherlibs/threads/threads.mllib1
-rw-r--r--otherlibs/threads/unix.ml1131
-rw-r--r--otherlibs/threads/unix.mllib1
-rw-r--r--otherlibs/unix/.depend644
-rw-r--r--otherlibs/unix/Makefile47
-rw-r--r--otherlibs/unix/accept.c52
-rw-r--r--otherlibs/unix/access.c58
-rw-r--r--otherlibs/unix/addrofstr.c86
-rw-r--r--otherlibs/unix/alarm.c20
-rw-r--r--otherlibs/unix/bind.c39
-rw-r--r--otherlibs/unix/chdir.c31
-rw-r--r--otherlibs/unix/chmod.c33
-rw-r--r--otherlibs/unix/chown.c31
-rw-r--r--otherlibs/unix/chroot.c31
-rw-r--r--otherlibs/unix/close.c26
-rw-r--r--otherlibs/unix/closedir.c36
-rw-r--r--otherlibs/unix/connect.c42
-rw-r--r--otherlibs/unix/cst2constr.c24
-rw-r--r--otherlibs/unix/cst2constr.h14
-rw-r--r--otherlibs/unix/cstringv.c28
-rw-r--r--otherlibs/unix/dup.c23
-rw-r--r--otherlibs/unix/dup2.c47
-rw-r--r--otherlibs/unix/envir.c28
-rw-r--r--otherlibs/unix/errmsg.c26
-rw-r--r--otherlibs/unix/execv.c29
-rw-r--r--otherlibs/unix/execve.c32
-rw-r--r--otherlibs/unix/execvp.c48
-rw-r--r--otherlibs/unix/exit.c22
-rw-r--r--otherlibs/unix/fchmod.c38
-rw-r--r--otherlibs/unix/fchown.c36
-rw-r--r--otherlibs/unix/fcntl.c76
-rw-r--r--otherlibs/unix/fork.c28
-rw-r--r--otherlibs/unix/ftruncate.c55
-rw-r--r--otherlibs/unix/getaddrinfo.c130
-rw-r--r--otherlibs/unix/getcwd.c56
-rw-r--r--otherlibs/unix/getegid.c20
-rw-r--r--otherlibs/unix/geteuid.c20
-rw-r--r--otherlibs/unix/getgid.c20
-rw-r--r--otherlibs/unix/getgr.c54
-rw-r--r--otherlibs/unix/getgroups.c47
-rw-r--r--otherlibs/unix/gethost.c180
-rw-r--r--otherlibs/unix/gethostname.c54
-rw-r--r--otherlibs/unix/getlogin.c27
-rw-r--r--otherlibs/unix/getnameinfo.c65
-rw-r--r--otherlibs/unix/getpeername.c39
-rw-r--r--otherlibs/unix/getpid.c20
-rw-r--r--otherlibs/unix/getppid.c20
-rw-r--r--otherlibs/unix/getproto.c66
-rw-r--r--otherlibs/unix/getpw.c63
-rw-r--r--otherlibs/unix/getserv.c72
-rw-r--r--otherlibs/unix/getsockname.c39
-rw-r--r--otherlibs/unix/gettimeofday.c36
-rw-r--r--otherlibs/unix/getuid.c20
-rw-r--r--otherlibs/unix/gmtime.c93
-rw-r--r--otherlibs/unix/initgroups.c41
-rw-r--r--otherlibs/unix/isatty.c20
-rw-r--r--otherlibs/unix/itimer.c73
-rw-r--r--otherlibs/unix/kill.c27
-rw-r--r--otherlibs/unix/libunix.clib16
-rw-r--r--otherlibs/unix/link.c34
-rw-r--r--otherlibs/unix/listen.c33
-rw-r--r--otherlibs/unix/lockf.c114
-rw-r--r--otherlibs/unix/lseek.c62
-rw-r--r--otherlibs/unix/mkdir.c33
-rw-r--r--otherlibs/unix/mkfifo.c69
-rw-r--r--otherlibs/unix/nanosecond_stat.h25
-rw-r--r--otherlibs/unix/nice.c32
-rw-r--r--otherlibs/unix/open.c82
-rw-r--r--otherlibs/unix/opendir.c42
-rw-r--r--otherlibs/unix/pipe.c27
-rw-r--r--otherlibs/unix/putenv.c47
-rw-r--r--otherlibs/unix/read.c36
-rw-r--r--otherlibs/unix/readdir.c40
-rw-r--r--otherlibs/unix/readlink.c54
-rw-r--r--otherlibs/unix/rename.c36
-rw-r--r--otherlibs/unix/rewinddir.c40
-rw-r--r--otherlibs/unix/rmdir.c31
-rw-r--r--otherlibs/unix/select.c112
-rw-r--r--otherlibs/unix/sendrecv.c146
-rw-r--r--otherlibs/unix/setgid.c21
-rw-r--r--otherlibs/unix/setgroups.c51
-rw-r--r--otherlibs/unix/setsid.c29
-rw-r--r--otherlibs/unix/setuid.c21
-rw-r--r--otherlibs/unix/shutdown.c38
-rw-r--r--otherlibs/unix/signals.c104
-rw-r--r--otherlibs/unix/sleep.c24
-rw-r--r--otherlibs/unix/socket.c54
-rw-r--r--otherlibs/unix/socketaddr.c143
-rw-r--r--otherlibs/unix/socketaddr.h60
-rw-r--r--otherlibs/unix/socketpair.c44
-rw-r--r--otherlibs/unix/sockopt.c299
-rw-r--r--otherlibs/unix/stat.c171
-rw-r--r--otherlibs/unix/strofaddr.c72
-rw-r--r--otherlibs/unix/symlink.c45
-rw-r--r--otherlibs/unix/termios.c385
-rw-r--r--otherlibs/unix/time.c22
-rw-r--r--otherlibs/unix/times.c65
-rw-r--r--otherlibs/unix/truncate.c66
-rw-r--r--otherlibs/unix/umask.c22
-rw-r--r--otherlibs/unix/unix.ml1087
-rw-r--r--otherlibs/unix/unix.mli1377
-rw-r--r--otherlibs/unix/unix.mllib1
-rw-r--r--otherlibs/unix/unixLabels.ml16
-rw-r--r--otherlibs/unix/unixLabels.mli1369
-rw-r--r--otherlibs/unix/unixsupport.c309
-rw-r--r--otherlibs/unix/unixsupport.h46
-rw-r--r--otherlibs/unix/unlink.c31
-rw-r--r--otherlibs/unix/utimes.c88
-rw-r--r--otherlibs/unix/wait.c100
-rw-r--r--otherlibs/unix/write.c84
-rw-r--r--otherlibs/win32graph/.ignore2
-rw-r--r--otherlibs/win32graph/Makefile.nt33
-rw-r--r--otherlibs/win32graph/dib.c497
-rw-r--r--otherlibs/win32graph/draw.c653
-rwxr-xr-xotherlibs/win32graph/events.c198
-rw-r--r--otherlibs/win32graph/libgraph.h76
-rw-r--r--otherlibs/win32graph/libgraphics.clib1
-rw-r--r--otherlibs/win32graph/open.c371
-rw-r--r--otherlibs/win32unix/.depend5
-rw-r--r--otherlibs/win32unix/.ignore29
-rw-r--r--otherlibs/win32unix/Makefile60
-rw-r--r--otherlibs/win32unix/Makefile.nt60
-rw-r--r--otherlibs/win32unix/accept.c64
-rw-r--r--otherlibs/win32unix/bind.c32
-rw-r--r--otherlibs/win32unix/channels.c90
-rw-r--r--otherlibs/win32unix/close.c42
-rw-r--r--otherlibs/win32unix/close_on.c41
-rw-r--r--otherlibs/win32unix/connect.c37
-rw-r--r--otherlibs/win32unix/createprocess.c91
-rw-r--r--otherlibs/win32unix/dup.c31
-rw-r--r--otherlibs/win32unix/dup2.c40
-rw-r--r--otherlibs/win32unix/errmsg.c41
-rw-r--r--otherlibs/win32unix/getpeername.c33
-rw-r--r--otherlibs/win32unix/getpid.c22
-rw-r--r--otherlibs/win32unix/getsockname.c30
-rw-r--r--otherlibs/win32unix/gettimeofday.c30
-rw-r--r--otherlibs/win32unix/libunix.clib17
-rw-r--r--otherlibs/win32unix/link.c40
-rw-r--r--otherlibs/win32unix/listen.c25
-rw-r--r--otherlibs/win32unix/lockf.c159
-rw-r--r--otherlibs/win32unix/lseek.c68
-rw-r--r--otherlibs/win32unix/mkdir.c22
-rwxr-xr-xotherlibs/win32unix/nonblock.c42
-rw-r--r--otherlibs/win32unix/open.c76
-rw-r--r--otherlibs/win32unix/pipe.c44
-rw-r--r--otherlibs/win32unix/read.c52
-rw-r--r--otherlibs/win32unix/rename.c41
-rw-r--r--otherlibs/win32unix/select.c1319
-rw-r--r--otherlibs/win32unix/sendrecv.c141
-rw-r--r--otherlibs/win32unix/shutdown.c30
-rw-r--r--otherlibs/win32unix/sleep.c25
-rw-r--r--otherlibs/win32unix/socket.c67
-rw-r--r--otherlibs/win32unix/socketaddr.h56
-rw-r--r--otherlibs/win32unix/sockopt.c227
-rw-r--r--otherlibs/win32unix/startup.c49
-rw-r--r--otherlibs/win32unix/stat.c109
-rw-r--r--otherlibs/win32unix/system.c42
-rw-r--r--otherlibs/win32unix/times.c48
-rw-r--r--otherlibs/win32unix/unix.ml994
-rw-r--r--otherlibs/win32unix/unixsupport.c311
-rw-r--r--otherlibs/win32unix/unixsupport.h77
-rw-r--r--otherlibs/win32unix/windbug.c30
-rw-r--r--otherlibs/win32unix/windbug.h40
-rw-r--r--otherlibs/win32unix/windir.c77
-rw-r--r--otherlibs/win32unix/winlist.c78
-rw-r--r--otherlibs/win32unix/winlist.h53
-rw-r--r--otherlibs/win32unix/winwait.c68
-rw-r--r--otherlibs/win32unix/winworker.c320
-rw-r--r--otherlibs/win32unix/winworker.h70
-rw-r--r--otherlibs/win32unix/write.c99
-rw-r--r--parsing/.ignore9
-rw-r--r--parsing/ast_helper.ml482
-rw-r--r--parsing/ast_helper.mli410
-rw-r--r--parsing/ast_mapper.ml908
-rw-r--r--parsing/ast_mapper.mli197
-rw-r--r--parsing/asttypes.mli54
-rw-r--r--parsing/docstrings.ml341
-rw-r--r--parsing/docstrings.mli148
-rw-r--r--parsing/lexer.mli59
-rw-r--r--parsing/lexer.mll779
-rw-r--r--parsing/location.ml443
-rw-r--r--parsing/location.mli142
-rw-r--r--parsing/longident.ml41
-rw-r--r--parsing/longident.mli22
-rw-r--r--parsing/parse.ml64
-rw-r--r--parsing/parse.mli21
-rw-r--r--parsing/parser.mly2440
-rw-r--r--parsing/parsetree.mli836
-rw-r--r--parsing/pprintast.ml1452
-rw-r--r--parsing/pprintast.mli147
-rw-r--r--parsing/printast.ml899
-rw-r--r--parsing/printast.mli22
-rw-r--r--parsing/syntaxerr.ml80
-rw-r--r--parsing/syntaxerr.mli33
-rw-r--r--stdlib/.depend301
-rw-r--r--stdlib/.ignore8
-rwxr-xr-xstdlib/Compflags28
-rw-r--r--stdlib/Makefile73
-rw-r--r--stdlib/Makefile.nt38
-rwxr-xr-xstdlib/Makefile.shared112
-rw-r--r--stdlib/StdlibModules67
-rw-r--r--stdlib/arg.ml278
-rw-r--r--stdlib/arg.mli158
-rw-r--r--stdlib/array.ml240
-rw-r--r--stdlib/array.mli215
-rw-r--r--stdlib/arrayLabels.ml16
-rw-r--r--stdlib/arrayLabels.mli221
-rw-r--r--stdlib/buffer.ml188
-rw-r--r--stdlib/buffer.mli131
-rw-r--r--stdlib/bytes.ml268
-rw-r--r--stdlib/bytes.mli431
-rw-r--r--stdlib/bytesLabels.ml16
-rw-r--r--stdlib/bytesLabels.mli215
-rw-r--r--stdlib/callback.ml25
-rw-r--r--stdlib/callback.mli32
-rw-r--r--stdlib/camlinternalFormat.ml2827
-rw-r--r--stdlib/camlinternalFormat.mli118
-rw-r--r--stdlib/camlinternalFormatBasics.ml679
-rw-r--r--stdlib/camlinternalFormatBasics.mli322
-rw-r--r--stdlib/camlinternalLazy.ml64
-rw-r--r--stdlib/camlinternalLazy.mli25
-rw-r--r--stdlib/camlinternalMod.ml72
-rw-r--r--stdlib/camlinternalMod.mli26
-rw-r--r--stdlib/camlinternalOO.ml586
-rw-r--r--stdlib/camlinternalOO.mli151
-rw-r--r--stdlib/char.ml74
-rw-r--r--stdlib/char.mli70
-rw-r--r--stdlib/complex.ml85
-rw-r--r--stdlib/complex.mli84
-rw-r--r--stdlib/digest.ml73
-rw-r--r--stdlib/digest.mli80
-rw-r--r--stdlib/filename.ml242
-rw-r--r--stdlib/filename.mli141
-rw-r--r--stdlib/format.ml1231
-rw-r--r--stdlib/format.mli756
-rw-r--r--stdlib/gc.ml100
-rw-r--r--stdlib/gc.mli279
-rw-r--r--stdlib/genlex.ml199
-rw-r--r--stdlib/genlex.mli71
-rw-r--r--stdlib/hashtbl.ml389
-rw-r--r--stdlib/hashtbl.mli364
-rw-r--r--stdlib/header.c189
-rw-r--r--stdlib/headernt.c174
-rw-r--r--stdlib/int32.ml53
-rw-r--r--stdlib/int32.mli166
-rw-r--r--stdlib/int64.ml58
-rw-r--r--stdlib/int64.mli188
-rw-r--r--stdlib/lazy.ml79
-rw-r--r--stdlib/lazy.mli88
-rw-r--r--stdlib/lexing.ml230
-rw-r--r--stdlib/lexing.mli174
-rw-r--r--stdlib/list.ml431
-rw-r--r--stdlib/list.mli298
-rw-r--r--stdlib/listLabels.ml16
-rw-r--r--stdlib/listLabels.mli295
-rw-r--r--stdlib/map.ml337
-rw-r--r--stdlib/map.mli212
-rw-r--r--stdlib/marshal.ml66
-rw-r--r--stdlib/marshal.mli178
-rw-r--r--stdlib/moreLabels.ml20
-rw-r--r--stdlib/moreLabels.mli167
-rw-r--r--stdlib/nativeint.ml54
-rw-r--r--stdlib/nativeint.mli188
-rw-r--r--stdlib/obj.ml91
-rw-r--r--stdlib/obj.mli70
-rw-r--r--stdlib/oo.ml17
-rw-r--r--stdlib/oo.mli36
-rw-r--r--stdlib/parsing.ml209
-rw-r--r--stdlib/parsing.mli103
-rw-r--r--stdlib/pervasives.ml512
-rw-r--r--stdlib/pervasives.mli1118
-rw-r--r--stdlib/printexc.ml295
-rw-r--r--stdlib/printexc.mli293
-rw-r--r--stdlib/printf.ml39
-rw-r--r--stdlib/printf.mli167
-rw-r--r--stdlib/queue.ml165
-rw-r--r--stdlib/queue.mli80
-rw-r--r--stdlib/random.ml275
-rw-r--r--stdlib/random.mli105
-rw-r--r--stdlib/scanf.ml1425
-rw-r--r--stdlib/scanf.mli537
-rw-r--r--stdlib/set.ml403
-rw-r--r--stdlib/set.mli191
-rw-r--r--stdlib/sharpbang1
-rw-r--r--stdlib/sort.ml97
-rw-r--r--stdlib/sort.mli42
-rw-r--r--stdlib/stack.ml40
-rw-r--r--stdlib/stack.mli55
-rw-r--r--stdlib/stdLabels.ml22
-rw-r--r--stdlib/stdLabels.mli27
-rw-r--r--stdlib/std_exit.ml16
-rw-r--r--stdlib/stdlib.mllib48
-rw-r--r--stdlib/stream.ml218
-rw-r--r--stdlib/stream.mli108
-rw-r--r--stdlib/string.ml137
-rw-r--r--stdlib/string.mli295
-rw-r--r--stdlib/stringLabels.ml16
-rw-r--r--stdlib/stringLabels.mli215
-rw-r--r--stdlib/sys.mli270
-rw-r--r--stdlib/sys.mlp109
-rw-r--r--stdlib/weak.ml305
-rw-r--r--stdlib/weak.mli157
-rw-r--r--testsuite/.ignore1
-rw-r--r--testsuite/Makefile104
-rw-r--r--testsuite/interactive/lib-gc/Makefile24
-rw-r--r--testsuite/interactive/lib-gc/alloc.ml48
-rw-r--r--testsuite/interactive/lib-graph-2/Makefile20
-rw-r--r--testsuite/interactive/lib-graph-2/graph_test.ml287
-rw-r--r--testsuite/interactive/lib-graph-2/graph_test.reference0
-rw-r--r--testsuite/interactive/lib-graph-3/Makefile20
-rw-r--r--testsuite/interactive/lib-graph-3/sorts.ml240
-rw-r--r--testsuite/interactive/lib-graph-3/sorts.reference0
-rw-r--r--testsuite/interactive/lib-graph/Makefile20
-rw-r--r--testsuite/interactive/lib-graph/graph_example.ml143
-rw-r--r--testsuite/interactive/lib-graph/graph_example.reference0
-rw-r--r--testsuite/interactive/lib-signals/Makefile24
-rw-r--r--testsuite/interactive/lib-signals/signals.ml44
-rw-r--r--testsuite/lib/Makefile28
-rw-r--r--testsuite/lib/empty0
-rw-r--r--testsuite/lib/testing.ml93
-rw-r--r--testsuite/lib/testing.mli32
-rw-r--r--testsuite/makefiles/Makefile.common134
-rw-r--r--testsuite/makefiles/Makefile.dlambda31
-rw-r--r--testsuite/makefiles/Makefile.dparsetree27
-rw-r--r--testsuite/makefiles/Makefile.okbad42
-rw-r--r--testsuite/makefiles/Makefile.one85
-rw-r--r--testsuite/makefiles/Makefile.several108
-rw-r--r--testsuite/makefiles/Makefile.toplevel31
-rw-r--r--testsuite/makefiles/summarize.awk117
-rw-r--r--testsuite/tests/asmcomp/.ignore7
-rw-r--r--testsuite/tests/asmcomp/Makefile94
-rw-r--r--testsuite/tests/asmcomp/alpha.S60
-rw-r--r--testsuite/tests/asmcomp/amd64.S75
-rw-r--r--testsuite/tests/asmcomp/arith.cmm217
-rw-r--r--testsuite/tests/asmcomp/arm.S37
-rw-r--r--testsuite/tests/asmcomp/arm64.S52
-rw-r--r--testsuite/tests/asmcomp/checkbound.cmm17
-rw-r--r--testsuite/tests/asmcomp/fib.cmm17
-rw-r--r--testsuite/tests/asmcomp/hppa.S161
-rw-r--r--testsuite/tests/asmcomp/i386.S55
-rw-r--r--testsuite/tests/asmcomp/i386nt.asm65
-rw-r--r--testsuite/tests/asmcomp/ia64.S116
-rw-r--r--testsuite/tests/asmcomp/integr.cmm28
-rw-r--r--testsuite/tests/asmcomp/lexcmm.mli22
-rw-r--r--testsuite/tests/asmcomp/lexcmm.mll229
-rw-r--r--testsuite/tests/asmcomp/m68k.S57
-rw-r--r--testsuite/tests/asmcomp/main.c125
-rw-r--r--testsuite/tests/asmcomp/main.ml59
-rw-r--r--testsuite/tests/asmcomp/mainarith.c311
-rw-r--r--testsuite/tests/asmcomp/mips.s69
-rw-r--r--testsuite/tests/asmcomp/optargs.ml33
-rw-r--r--testsuite/tests/asmcomp/parsecmm.mly329
-rw-r--r--testsuite/tests/asmcomp/parsecmmaux.ml38
-rw-r--r--testsuite/tests/asmcomp/parsecmmaux.mli24
-rw-r--r--testsuite/tests/asmcomp/power.S197
-rw-r--r--testsuite/tests/asmcomp/quicksort.cmm41
-rw-r--r--testsuite/tests/asmcomp/quicksort2.cmm47
-rw-r--r--testsuite/tests/asmcomp/soli.cmm107
-rw-r--r--testsuite/tests/asmcomp/sparc.S39
-rw-r--r--testsuite/tests/asmcomp/staticalloc.ml31
-rw-r--r--testsuite/tests/asmcomp/tagged-fib.cmm16
-rw-r--r--testsuite/tests/asmcomp/tagged-integr.cmm42
-rw-r--r--testsuite/tests/asmcomp/tagged-quicksort.cmm44
-rw-r--r--testsuite/tests/asmcomp/tagged-tak.cmm21
-rw-r--r--testsuite/tests/asmcomp/tak.cmm21
-rw-r--r--testsuite/tests/backtrace/Makefile97
-rw-r--r--testsuite/tests/backtrace/backtrace..reference2
-rw-r--r--testsuite/tests/backtrace/backtrace.a.reference1
-rw-r--r--testsuite/tests/backtrace/backtrace.b.reference11
-rw-r--r--testsuite/tests/backtrace/backtrace.c.reference3
-rw-r--r--testsuite/tests/backtrace/backtrace.d.reference9
-rw-r--r--testsuite/tests/backtrace/backtrace.ml29
-rw-r--r--testsuite/tests/backtrace/backtrace2.ml40
-rw-r--r--testsuite/tests/backtrace/backtrace2.reference27
-rw-r--r--testsuite/tests/backtrace/backtrace_deprecated.ml50
-rw-r--r--testsuite/tests/backtrace/backtrace_deprecated.reference27
-rw-r--r--testsuite/tests/backtrace/backtrace_slots.ml72
-rw-r--r--testsuite/tests/backtrace/backtrace_slots.reference27
-rw-r--r--testsuite/tests/backtrace/backtraces_and_finalizers.ml25
-rw-r--r--testsuite/tests/backtrace/backtraces_and_finalizers.reference1
-rw-r--r--testsuite/tests/backtrace/raw_backtrace.ml52
-rw-r--r--testsuite/tests/backtrace/raw_backtrace.reference27
-rw-r--r--testsuite/tests/basic-float/Makefile18
-rw-r--r--testsuite/tests/basic-float/float_record.ml19
-rw-r--r--testsuite/tests/basic-float/float_record.mli18
-rw-r--r--testsuite/tests/basic-float/tfloat_record.ml16
-rw-r--r--testsuite/tests/basic-float/tfloat_record.reference1
-rw-r--r--testsuite/tests/basic-io-2/Makefile19
-rw-r--r--testsuite/tests/basic-io-2/io.ml115
-rw-r--r--testsuite/tests/basic-io-2/io.reference24
-rw-r--r--testsuite/tests/basic-io-2/test-file-short-lines10
-rw-r--r--testsuite/tests/basic-io/Makefile19
-rw-r--r--testsuite/tests/basic-io/wc.ml66
-rw-r--r--testsuite/tests/basic-io/wc.reference1
-rw-r--r--testsuite/tests/basic-manyargs/Makefile19
-rw-r--r--testsuite/tests/basic-manyargs/manyargs.ml57
-rw-r--r--testsuite/tests/basic-manyargs/manyargs.reference65
-rw-r--r--testsuite/tests/basic-manyargs/manyargsprim.c37
-rw-r--r--testsuite/tests/basic-modules/Makefile19
-rw-r--r--testsuite/tests/basic-modules/main.ml26
-rw-r--r--testsuite/tests/basic-modules/main.reference1
-rw-r--r--testsuite/tests/basic-modules/offset.ml22
-rw-r--r--testsuite/tests/basic-modules/pr6726.ml30
-rw-r--r--testsuite/tests/basic-more/Makefile18
-rw-r--r--testsuite/tests/basic-more/bounds.ml38
-rw-r--r--testsuite/tests/basic-more/bounds.reference9
-rw-r--r--testsuite/tests/basic-more/morematch.ml1201
-rw-r--r--testsuite/tests/basic-more/morematch.reference2
-rw-r--r--testsuite/tests/basic-more/pr2719.ml17
-rw-r--r--testsuite/tests/basic-more/pr2719.reference4
-rw-r--r--testsuite/tests/basic-more/pr6216.ml12
-rw-r--r--testsuite/tests/basic-more/pr6216.reference2
-rw-r--r--testsuite/tests/basic-more/tbuffer.ml38
-rw-r--r--testsuite/tests/basic-more/tbuffer.reference2
-rw-r--r--testsuite/tests/basic-more/testrandom.ml24
-rw-r--r--testsuite/tests/basic-more/testrandom.reference4
-rw-r--r--testsuite/tests/basic-more/tformat.ml33
-rw-r--r--testsuite/tests/basic-more/tformat.reference2
-rw-r--r--testsuite/tests/basic-more/tprintf.ml87
-rw-r--r--testsuite/tests/basic-more/tprintf.reference2
-rw-r--r--testsuite/tests/basic-multdef/Makefile18
-rw-r--r--testsuite/tests/basic-multdef/multdef.ml14
-rw-r--r--testsuite/tests/basic-multdef/multdef.mli15
-rw-r--r--testsuite/tests/basic-multdef/usemultdef.ml13
-rw-r--r--testsuite/tests/basic-multdef/usemultdef.reference1
-rw-r--r--testsuite/tests/basic-private/Makefile19
-rw-r--r--testsuite/tests/basic-private/length.ml28
-rw-r--r--testsuite/tests/basic-private/length.mli25
-rw-r--r--testsuite/tests/basic-private/tlength.ml35
-rw-r--r--testsuite/tests/basic-private/tlength.reference0
-rw-r--r--testsuite/tests/basic/Makefile15
-rw-r--r--testsuite/tests/basic/arrays.ml146
-rw-r--r--testsuite/tests/basic/arrays.reference0
-rw-r--r--testsuite/tests/basic/bigints.ml37
-rw-r--r--testsuite/tests/basic/bigints.reference10
-rw-r--r--testsuite/tests/basic/boxedints.ml593
-rw-r--r--testsuite/tests/basic/boxedints.reference118
-rw-r--r--testsuite/tests/basic/constprop.ml116
-rw-r--r--testsuite/tests/basic/constprop.mlp129
-rw-r--r--testsuite/tests/basic/constprop.reference10
-rw-r--r--testsuite/tests/basic/divint.ml152
-rw-r--r--testsuite/tests/basic/divint.reference37
-rw-r--r--testsuite/tests/basic/equality.ml116
-rw-r--r--testsuite/tests/basic/equality.reference49
-rw-r--r--testsuite/tests/basic/float.ml13
-rw-r--r--testsuite/tests/basic/float.reference1
-rw-r--r--testsuite/tests/basic/includestruct.ml103
-rw-r--r--testsuite/tests/basic/includestruct.reference15
-rw-r--r--testsuite/tests/basic/maps.ml36
-rw-r--r--testsuite/tests/basic/maps.reference6
-rw-r--r--testsuite/tests/basic/patmatch.ml1612
-rw-r--r--testsuite/tests/basic/patmatch.reference75
-rw-r--r--testsuite/tests/basic/recvalues.ml50
-rw-r--r--testsuite/tests/basic/recvalues.reference5
-rw-r--r--testsuite/tests/basic/sets.ml37
-rw-r--r--testsuite/tests/basic/sets.reference25
-rw-r--r--testsuite/tests/basic/stringmatch.ml750
-rw-r--r--testsuite/tests/basic/stringmatch.reference0
-rw-r--r--testsuite/tests/basic/tailcalls.ml53
-rw-r--r--testsuite/tests/basic/tailcalls.reference6
-rw-r--r--testsuite/tests/callback/Makefile59
-rw-r--r--testsuite/tests/callback/callbackprim.c66
-rw-r--r--testsuite/tests/callback/reference8
-rw-r--r--testsuite/tests/callback/tcallback.ml81
-rw-r--r--testsuite/tests/embedded/.ignore1
-rw-r--r--testsuite/tests/embedded/Makefile41
-rw-r--r--testsuite/tests/embedded/cmcaml.ml28
-rw-r--r--testsuite/tests/embedded/cmmain.c35
-rw-r--r--testsuite/tests/embedded/cmstub.c30
-rw-r--r--testsuite/tests/embedded/program.reference4
-rw-r--r--testsuite/tests/exotic-syntax/Makefile17
-rw-r--r--testsuite/tests/exotic-syntax/exotic.ml157
-rw-r--r--testsuite/tests/exotic-syntax/exotic.reference0
-rw-r--r--testsuite/tests/float-unboxing/Makefile7
-rw-r--r--testsuite/tests/float-unboxing/float_subst_boxed_number.ml52
-rw-r--r--testsuite/tests/float-unboxing/float_subst_boxed_number.reference0
-rw-r--r--testsuite/tests/formats-transition/Makefile3
-rw-r--r--testsuite/tests/formats-transition/deprecated_unsigned_printers.ml22
-rw-r--r--testsuite/tests/formats-transition/deprecated_unsigned_printers.ml.reference7
-rw-r--r--testsuite/tests/formats-transition/ignored_scan_counters.ml30
-rw-r--r--testsuite/tests/formats-transition/ignored_scan_counters.ml.reference14
-rw-r--r--testsuite/tests/formats-transition/legacy_incompatible_flags.ml20
-rw-r--r--testsuite/tests/formats-transition/legacy_unfinished_modifiers.ml18
-rw-r--r--testsuite/tests/formats-transition/legacy_unfinished_modifiers.ml.reference6
-rw-r--r--testsuite/tests/gc-roots/Makefile20
-rw-r--r--testsuite/tests/gc-roots/globroots.ml92
-rw-r--r--testsuite/tests/gc-roots/globroots.reference4
-rw-r--r--testsuite/tests/gc-roots/globrootsprim.c71
-rw-r--r--testsuite/tests/int64-unboxing/Makefile21
-rw-r--r--testsuite/tests/int64-unboxing/stubs.c22
-rw-r--r--testsuite/tests/int64-unboxing/test.ml37
-rw-r--r--testsuite/tests/int64-unboxing/test.reference0
-rw-r--r--testsuite/tests/letrec/Makefile16
-rw-r--r--testsuite/tests/letrec/backreferences.ml30
-rw-r--r--testsuite/tests/letrec/backreferences.reference0
-rw-r--r--testsuite/tests/letrec/class_1.ml17
-rw-r--r--testsuite/tests/letrec/class_1.reference0
-rw-r--r--testsuite/tests/letrec/class_2.ml20
-rw-r--r--testsuite/tests/letrec/class_2.reference2
-rw-r--r--testsuite/tests/letrec/evaluation_order_1.ml32
-rw-r--r--testsuite/tests/letrec/evaluation_order_1.reference3
-rw-r--r--testsuite/tests/letrec/evaluation_order_2.ml30
-rw-r--r--testsuite/tests/letrec/evaluation_order_2.reference3
-rw-r--r--testsuite/tests/letrec/evaluation_order_3.ml23
-rw-r--r--testsuite/tests/letrec/evaluation_order_3.reference6
-rw-r--r--testsuite/tests/letrec/float_block_1.ml22
-rw-r--r--testsuite/tests/letrec/float_block_1.reference2
-rw-r--r--testsuite/tests/letrec/float_block_2.ml19
-rw-r--r--testsuite/tests/letrec/float_block_2.reference0
-rw-r--r--testsuite/tests/letrec/lists.ml20
-rw-r--r--testsuite/tests/letrec/lists.reference0
-rw-r--r--testsuite/tests/letrec/mixing_value_closures_1.ml20
-rw-r--r--testsuite/tests/letrec/mixing_value_closures_1.reference0
-rw-r--r--testsuite/tests/letrec/mixing_value_closures_2.ml20
-rw-r--r--testsuite/tests/letrec/mixing_value_closures_2.reference0
-rw-r--r--testsuite/tests/letrec/mutual_functions.ml23
-rw-r--r--testsuite/tests/letrec/mutual_functions.reference0
-rw-r--r--testsuite/tests/letrec/record_with.ml37
-rw-r--r--testsuite/tests/letrec/record_with.reference1
-rw-r--r--testsuite/tests/lib-bigarray-2/Makefile21
-rw-r--r--testsuite/tests/lib-bigarray-2/bigarrf.f26
-rw-r--r--testsuite/tests/lib-bigarray-2/bigarrfml.ml78
-rw-r--r--testsuite/tests/lib-bigarray-2/bigarrfml.reference27
-rw-r--r--testsuite/tests/lib-bigarray-2/bigarrfstub.c71
-rw-r--r--testsuite/tests/lib-bigarray/Makefile20
-rw-r--r--testsuite/tests/lib-bigarray/bigarrays.ml880
-rw-r--r--testsuite/tests/lib-bigarray/bigarrays.reference61
-rw-r--r--testsuite/tests/lib-bigarray/fftba.ml194
-rw-r--r--testsuite/tests/lib-bigarray/fftba.reference13
-rw-r--r--testsuite/tests/lib-bigarray/pr5115.ml24
-rw-r--r--testsuite/tests/lib-bigarray/pr5115.reference2
-rw-r--r--testsuite/tests/lib-digest/Makefile19
-rw-r--r--testsuite/tests/lib-digest/md5.ml243
-rw-r--r--testsuite/tests/lib-digest/md5.reference1
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/.ignore6
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/Makefile70
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/custom.reference5
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/main.ml49
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/main.reference13
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/plug1.ml19
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/plug2.ml19
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/registry.ml19
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/static.reference5
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/stub1.c24
-rw-r--r--testsuite/tests/lib-dynlink-bytecode/stub2.c25
-rw-r--r--testsuite/tests/lib-dynlink-csharp/Makefile101
-rw-r--r--testsuite/tests/lib-dynlink-csharp/bytecode.reference7
-rwxr-xr-xtestsuite/tests/lib-dynlink-csharp/entry.c41
-rwxr-xr-xtestsuite/tests/lib-dynlink-csharp/main.cs11
-rwxr-xr-xtestsuite/tests/lib-dynlink-csharp/main.ml34
-rw-r--r--testsuite/tests/lib-dynlink-csharp/native.reference7
-rwxr-xr-xtestsuite/tests/lib-dynlink-csharp/plugin.ml16
-rw-r--r--testsuite/tests/lib-dynlink-native/.ignore7
-rw-r--r--testsuite/tests/lib-dynlink-native/Makefile122
-rwxr-xr-xtestsuite/tests/lib-dynlink-native/a.ml17
-rw-r--r--testsuite/tests/lib-dynlink-native/api.ml32
-rwxr-xr-xtestsuite/tests/lib-dynlink-native/b.ml16
-rw-r--r--testsuite/tests/lib-dynlink-native/bug.ml14
-rwxr-xr-xtestsuite/tests/lib-dynlink-native/c.ml16
-rw-r--r--testsuite/tests/lib-dynlink-native/factorial.c30
-rw-r--r--testsuite/tests/lib-dynlink-native/main.ml44
-rw-r--r--testsuite/tests/lib-dynlink-native/pack_client.ml14
-rw-r--r--testsuite/tests/lib-dynlink-native/packed1.ml17
-rw-r--r--testsuite/tests/lib-dynlink-native/packed1_client.ml15
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin.ml23
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin.mli13
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin2.ml20
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin4.ml15
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin_ext.ml17
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin_high_arity.ml18
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin_ref.ml22
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin_simple.ml15
-rw-r--r--testsuite/tests/lib-dynlink-native/plugin_thread.ml27
-rw-r--r--testsuite/tests/lib-dynlink-native/reference30
-rw-r--r--testsuite/tests/lib-dynlink-native/sub/api.ml15
-rw-r--r--testsuite/tests/lib-dynlink-native/sub/api.mli13
-rw-r--r--testsuite/tests/lib-dynlink-native/sub/plugin.ml18
-rw-r--r--testsuite/tests/lib-dynlink-native/sub/plugin3.ml14
-rw-r--r--testsuite/tests/lib-format/Makefile17
-rw-r--r--testsuite/tests/lib-format/pr6824.ml7
-rw-r--r--testsuite/tests/lib-format/pr6824.reference6
-rw-r--r--testsuite/tests/lib-format/tformat.ml511
-rw-r--r--testsuite/tests/lib-format/tformat.reference91
-rw-r--r--testsuite/tests/lib-hashtbl/Makefile15
-rw-r--r--testsuite/tests/lib-hashtbl/hfun.ml54
-rw-r--r--testsuite/tests/lib-hashtbl/hfun.reference27
-rw-r--r--testsuite/tests/lib-hashtbl/htbl.ml204
-rw-r--r--testsuite/tests/lib-hashtbl/htbl.reference24
-rw-r--r--testsuite/tests/lib-marshal/Makefile19
-rw-r--r--testsuite/tests/lib-marshal/intext.ml587
-rw-r--r--testsuite/tests/lib-marshal/intext.reference173
-rw-r--r--testsuite/tests/lib-marshal/intextaux.c25
-rw-r--r--testsuite/tests/lib-num-2/Makefile20
-rw-r--r--testsuite/tests/lib-num-2/pi_big_int.ml90
-rw-r--r--testsuite/tests/lib-num-2/pi_big_int.reference100
-rw-r--r--testsuite/tests/lib-num-2/pi_num.ml84
-rw-r--r--testsuite/tests/lib-num-2/pi_num.reference100
-rw-r--r--testsuite/tests/lib-num/Makefile21
-rw-r--r--testsuite/tests/lib-num/end_test.ml13
-rw-r--r--testsuite/tests/lib-num/end_test.reference170
-rw-r--r--testsuite/tests/lib-num/test.ml114
-rw-r--r--testsuite/tests/lib-num/test_big_ints.ml1042
-rw-r--r--testsuite/tests/lib-num/test_io.ml76
-rw-r--r--testsuite/tests/lib-num/test_nats.ml161
-rw-r--r--testsuite/tests/lib-num/test_nums.ml246
-rw-r--r--testsuite/tests/lib-num/test_ratios.ml1207
-rw-r--r--testsuite/tests/lib-printf/Makefile17
-rw-r--r--testsuite/tests/lib-printf/pr6534.ml19
-rw-r--r--testsuite/tests/lib-printf/pr6534.reference14
-rw-r--r--testsuite/tests/lib-printf/pr6938.ml42
-rw-r--r--testsuite/tests/lib-printf/pr6938.reference31
-rw-r--r--testsuite/tests/lib-printf/tprintf.ml591
-rw-r--r--testsuite/tests/lib-printf/tprintf.reference91
-rw-r--r--testsuite/tests/lib-random/Makefile15
-rw-r--r--testsuite/tests/lib-random/rand.ml6
-rw-r--r--testsuite/tests/lib-random/rand.reference1
-rw-r--r--testsuite/tests/lib-scanf-2/Makefile60
-rw-r--r--testsuite/tests/lib-scanf-2/reference2
-rw-r--r--testsuite/tests/lib-scanf-2/tscanf2_io.ml31
-rw-r--r--testsuite/tests/lib-scanf-2/tscanf2_master.ml63
-rw-r--r--testsuite/tests/lib-scanf-2/tscanf2_slave.ml40
-rw-r--r--testsuite/tests/lib-scanf/.ignore1
-rw-r--r--testsuite/tests/lib-scanf/Makefile21
-rw-r--r--testsuite/tests/lib-scanf/tscanf.ml1491
-rw-r--r--testsuite/tests/lib-scanf/tscanf.reference2
-rw-r--r--testsuite/tests/lib-set/Makefile15
-rw-r--r--testsuite/tests/lib-set/testmap.ml134
-rw-r--r--testsuite/tests/lib-set/testmap.reference0
-rw-r--r--testsuite/tests/lib-set/testset.ml170
-rw-r--r--testsuite/tests/lib-set/testset.reference0
-rw-r--r--testsuite/tests/lib-str/Makefile19
-rw-r--r--testsuite/tests/lib-str/t01.ml1075
-rw-r--r--testsuite/tests/lib-str/t01.reference104
-rw-r--r--testsuite/tests/lib-stream/Makefile16
-rw-r--r--testsuite/tests/lib-stream/count_concat_bug.ml69
-rw-r--r--testsuite/tests/lib-stream/count_concat_bug.reference2
-rw-r--r--testsuite/tests/lib-string/Makefile19
-rw-r--r--testsuite/tests/lib-string/test_string.ml35
-rw-r--r--testsuite/tests/lib-string/test_string.reference0
-rw-r--r--testsuite/tests/lib-systhreads/Makefile20
-rw-r--r--testsuite/tests/lib-systhreads/testfork.ml43
-rw-r--r--testsuite/tests/lib-systhreads/testfork.precheck16
-rw-r--r--testsuite/tests/lib-systhreads/testfork.reference6
-rw-r--r--testsuite/tests/lib-threads/.ignore1
-rw-r--r--testsuite/tests/lib-threads/Makefile20
-rw-r--r--testsuite/tests/lib-threads/close.ml30
-rw-r--r--testsuite/tests/lib-threads/close.reference3
-rw-r--r--testsuite/tests/lib-threads/sieve.ml45
-rw-r--r--testsuite/tests/lib-threads/sieve.reference95
-rw-r--r--testsuite/tests/lib-threads/test-file-short-lines10
-rw-r--r--testsuite/tests/lib-threads/test1.checker13
-rw-r--r--testsuite/tests/lib-threads/test1.ml75
-rw-r--r--testsuite/tests/lib-threads/test1.reference20002
-rw-r--r--testsuite/tests/lib-threads/test2.checker13
-rw-r--r--testsuite/tests/lib-threads/test2.ml27
-rw-r--r--testsuite/tests/lib-threads/test3.checker13
-rw-r--r--testsuite/tests/lib-threads/test3.ml20
-rw-r--r--testsuite/tests/lib-threads/test3.precheck13
-rw-r--r--testsuite/tests/lib-threads/test3.runner16
-rw-r--r--testsuite/tests/lib-threads/test4.checker13
-rw-r--r--testsuite/tests/lib-threads/test4.data3
-rw-r--r--testsuite/tests/lib-threads/test4.ml33
-rw-r--r--testsuite/tests/lib-threads/test4.reference4
-rw-r--r--testsuite/tests/lib-threads/test4.runner13
-rw-r--r--testsuite/tests/lib-threads/test5.checker13
-rw-r--r--testsuite/tests/lib-threads/test5.ml31
-rw-r--r--testsuite/tests/lib-threads/test5.precheck13
-rw-r--r--testsuite/tests/lib-threads/test5.reference4
-rw-r--r--testsuite/tests/lib-threads/test5.runner16
-rw-r--r--testsuite/tests/lib-threads/test6.checker13
-rw-r--r--testsuite/tests/lib-threads/test6.ml27
-rw-r--r--testsuite/tests/lib-threads/test6.precheck13
-rw-r--r--testsuite/tests/lib-threads/test6.reference2
-rw-r--r--testsuite/tests/lib-threads/test6.runner16
-rw-r--r--testsuite/tests/lib-threads/test7.checker14
-rw-r--r--testsuite/tests/lib-threads/test7.ml38
-rw-r--r--testsuite/tests/lib-threads/test7.precheck13
-rw-r--r--testsuite/tests/lib-threads/test7.runner16
-rw-r--r--testsuite/tests/lib-threads/test8.ml63
-rw-r--r--testsuite/tests/lib-threads/test8.precheck13
-rw-r--r--testsuite/tests/lib-threads/test8.reference3
-rw-r--r--testsuite/tests/lib-threads/test9.checker13
-rw-r--r--testsuite/tests/lib-threads/test9.ml38
-rw-r--r--testsuite/tests/lib-threads/test9.precheck13
-rw-r--r--testsuite/tests/lib-threads/test9.reference2
-rw-r--r--testsuite/tests/lib-threads/testA.checker13
-rw-r--r--testsuite/tests/lib-threads/testA.ml38
-rw-r--r--testsuite/tests/lib-threads/testA.reference5
-rw-r--r--testsuite/tests/lib-threads/testexit.checker13
-rw-r--r--testsuite/tests/lib-threads/testexit.ml33
-rw-r--r--testsuite/tests/lib-threads/testexit.reference27
-rw-r--r--testsuite/tests/lib-threads/testio.ml132
-rw-r--r--testsuite/tests/lib-threads/testio.reference24
-rw-r--r--testsuite/tests/lib-threads/testsieve.ml54
-rw-r--r--testsuite/tests/lib-threads/testsieve.reference100
-rw-r--r--testsuite/tests/lib-threads/testsignal.checker13
-rw-r--r--testsuite/tests/lib-threads/testsignal.ml25
-rw-r--r--testsuite/tests/lib-threads/testsignal.precheck13
-rw-r--r--testsuite/tests/lib-threads/testsignal.runner16
-rw-r--r--testsuite/tests/lib-threads/testsignal2.checker13
-rw-r--r--testsuite/tests/lib-threads/testsignal2.ml23
-rw-r--r--testsuite/tests/lib-threads/testsignal2.precheck13
-rw-r--r--testsuite/tests/lib-threads/testsignal2.runner18
-rw-r--r--testsuite/tests/lib-threads/testsocket.ml48
-rw-r--r--testsuite/tests/lib-threads/testsocket.precheck23
-rw-r--r--testsuite/tests/lib-threads/testsocket.reference3
-rw-r--r--testsuite/tests/lib-threads/token1.ml48
-rw-r--r--testsuite/tests/lib-threads/token1.reference0
-rw-r--r--testsuite/tests/lib-threads/token2.ml51
-rw-r--r--testsuite/tests/lib-threads/token2.reference0
-rw-r--r--testsuite/tests/lib-threads/torture.data3
-rw-r--r--testsuite/tests/lib-threads/torture.ml66
-rw-r--r--testsuite/tests/lib-threads/torture.reference4
-rw-r--r--testsuite/tests/lib-threads/torture.runner13
-rw-r--r--testsuite/tests/match-exception-warnings/Makefile15
-rw-r--r--testsuite/tests/match-exception-warnings/exhaustiveness_warnings.ml12
-rw-r--r--testsuite/tests/match-exception-warnings/exhaustiveness_warnings.ml.reference11
-rw-r--r--testsuite/tests/match-exception/Makefile15
-rw-r--r--testsuite/tests/match-exception/allocation.ml25
-rw-r--r--testsuite/tests/match-exception/allocation.reference1
-rw-r--r--testsuite/tests/match-exception/exception_propagation.ml17
-rw-r--r--testsuite/tests/match-exception/exception_propagation.reference1
-rw-r--r--testsuite/tests/match-exception/match_failure.ml19
-rw-r--r--testsuite/tests/match-exception/match_failure.reference1
-rw-r--r--testsuite/tests/match-exception/nested_handlers.ml45
-rw-r--r--testsuite/tests/match-exception/nested_handlers.reference1
-rw-r--r--testsuite/tests/match-exception/raise_from_success_continuation.ml15
-rw-r--r--testsuite/tests/match-exception/raise_from_success_continuation.reference2
-rw-r--r--testsuite/tests/match-exception/streams.ml37
-rw-r--r--testsuite/tests/match-exception/streams.reference1
-rw-r--r--testsuite/tests/match-exception/tail_calls.ml21
-rw-r--r--testsuite/tests/match-exception/tail_calls.reference1
-rw-r--r--testsuite/tests/misc-kb/Makefile19
-rw-r--r--testsuite/tests/misc-kb/equations.ml112
-rw-r--r--testsuite/tests/misc-kb/equations.mli30
-rw-r--r--testsuite/tests/misc-kb/kb.ml185
-rw-r--r--testsuite/tests/misc-kb/kb.mli29
-rw-r--r--testsuite/tests/misc-kb/kbmain.ml79
-rw-r--r--testsuite/tests/misc-kb/kbmain.reference5460
-rw-r--r--testsuite/tests/misc-kb/orderings.ml96
-rw-r--r--testsuite/tests/misc-kb/orderings.mli29
-rw-r--r--testsuite/tests/misc-kb/terms.ml133
-rw-r--r--testsuite/tests/misc-kb/terms.mli29
-rw-r--r--testsuite/tests/misc-unsafe/Makefile16
-rw-r--r--testsuite/tests/misc-unsafe/almabench.ml325
-rw-r--r--testsuite/tests/misc-unsafe/almabench.reference8
-rw-r--r--testsuite/tests/misc-unsafe/fft.ml186
-rw-r--r--testsuite/tests/misc-unsafe/fft.reference16
-rw-r--r--testsuite/tests/misc-unsafe/quicksort.ml90
-rw-r--r--testsuite/tests/misc-unsafe/quicksort.reference2
-rw-r--r--testsuite/tests/misc-unsafe/soli.ml108
-rw-r--r--testsuite/tests/misc-unsafe/soli.reference50
-rw-r--r--testsuite/tests/misc/Makefile15
-rw-r--r--testsuite/tests/misc/bdd.ml229
-rw-r--r--testsuite/tests/misc/bdd.reference1
-rw-r--r--testsuite/tests/misc/boyer.ml909
-rw-r--r--testsuite/tests/misc/boyer.reference1
-rw-r--r--testsuite/tests/misc/fib.ml21
-rw-r--r--testsuite/tests/misc/fib.reference1
-rw-r--r--testsuite/tests/misc/hamming.ml103
-rw-r--r--testsuite/tests/misc/hamming.reference100
-rw-r--r--testsuite/tests/misc/nucleic.ml3236
-rw-r--r--testsuite/tests/misc/nucleic.reference1
-rw-r--r--testsuite/tests/misc/sieve.ml54
-rw-r--r--testsuite/tests/misc/sieve.reference1
-rw-r--r--testsuite/tests/misc/sorts.ml4489
-rw-r--r--testsuite/tests/misc/sorts.reference198
-rw-r--r--testsuite/tests/misc/takc.ml20
-rw-r--r--testsuite/tests/misc/takc.reference1
-rw-r--r--testsuite/tests/misc/taku.ml20
-rw-r--r--testsuite/tests/misc/taku.reference1
-rw-r--r--testsuite/tests/misc/weaklifetime.ml74
-rw-r--r--testsuite/tests/misc/weaklifetime.reference0
-rw-r--r--testsuite/tests/misc/weaktest.ml83
-rw-r--r--testsuite/tests/misc/weaktest.reference1
-rw-r--r--testsuite/tests/parsing/Makefile16
-rw-r--r--testsuite/tests/parsing/pr6865.ml3
-rw-r--r--testsuite/tests/parsing/pr6865.ml.reference47
-rw-r--r--testsuite/tests/ppx-attributes/Makefile15
-rw-r--r--testsuite/tests/ppx-attributes/warning.ml47
-rw-r--r--testsuite/tests/ppx-attributes/warning.reference0
-rw-r--r--testsuite/tests/prim-bigstring/Makefile8
-rw-r--r--testsuite/tests/prim-bigstring/bigstring_access.ml119
-rw-r--r--testsuite/tests/prim-bigstring/bigstring_access.reference6
-rw-r--r--testsuite/tests/prim-bigstring/string_access.ml106
-rw-r--r--testsuite/tests/prim-bigstring/string_access.reference6
-rw-r--r--testsuite/tests/prim-bswap/Makefile17
-rw-r--r--testsuite/tests/prim-bswap/bswap.ml30
-rw-r--r--testsuite/tests/prim-bswap/bswap.reference6
-rw-r--r--testsuite/tests/prim-revapply/Makefile16
-rw-r--r--testsuite/tests/prim-revapply/apply.ml48
-rw-r--r--testsuite/tests/prim-revapply/apply.reference10
-rw-r--r--testsuite/tests/prim-revapply/revapply.ml30
-rw-r--r--testsuite/tests/prim-revapply/revapply.reference5
-rw-r--r--testsuite/tests/regression/pr3612/Makefile18
-rw-r--r--testsuite/tests/regression/pr3612/custom_finalize.c62
-rw-r--r--testsuite/tests/regression/pr3612/pr3612.ml32
-rw-r--r--testsuite/tests/regression/pr3612/pr3612.reference1
-rw-r--r--testsuite/tests/regression/pr5080-notes/Makefile17
-rw-r--r--testsuite/tests/regression/pr5080-notes/pr5080_notes_ok.ml16
-rw-r--r--testsuite/tests/regression/pr5233/Makefile16
-rw-r--r--testsuite/tests/regression/pr5233/pr5233.ml62
-rw-r--r--testsuite/tests/regression/pr5233/pr5233.reference2
-rw-r--r--testsuite/tests/regression/pr5757/Makefile16
-rw-r--r--testsuite/tests/regression/pr5757/pr5757.ml17
-rw-r--r--testsuite/tests/regression/pr5757/pr5757.reference1
-rw-r--r--testsuite/tests/regression/pr6024/Makefile17
-rw-r--r--testsuite/tests/regression/pr6024/pr6024.ml13
-rw-r--r--testsuite/tests/regression/pr6024/pr6024.reference1
-rw-r--r--testsuite/tests/runtime-errors/.ignore1
-rw-r--r--testsuite/tests/runtime-errors/Makefile57
-rw-r--r--testsuite/tests/runtime-errors/stackoverflow.bytecode.checker13
-rw-r--r--testsuite/tests/runtime-errors/stackoverflow.bytecode.reference4
-rw-r--r--testsuite/tests/runtime-errors/stackoverflow.ml27
-rw-r--r--testsuite/tests/runtime-errors/stackoverflow.native.checker13
-rw-r--r--testsuite/tests/runtime-errors/stackoverflow.native.reference4
-rw-r--r--testsuite/tests/runtime-errors/syserror.bytecode.checker13
-rw-r--r--testsuite/tests/runtime-errors/syserror.bytecode.reference1
-rw-r--r--testsuite/tests/runtime-errors/syserror.ml13
-rw-r--r--testsuite/tests/runtime-errors/syserror.native.checker13
-rw-r--r--testsuite/tests/runtime-errors/syserror.native.reference1
-rw-r--r--testsuite/tests/tool-debugger/basic/.ignore1
-rw-r--r--testsuite/tests/tool-debugger/basic/Makefile58
-rw-r--r--testsuite/tests/tool-debugger/basic/debuggee.ml2
-rw-r--r--testsuite/tests/tool-debugger/basic/debuggee.reference5
-rwxr-xr-xtestsuite/tests/tool-debugger/basic/input_script5
-rw-r--r--testsuite/tests/tool-debugger/find-artifacts/.ignore2
-rw-r--r--testsuite/tests/tool-debugger/find-artifacts/Makefile67
-rw-r--r--testsuite/tests/tool-debugger/find-artifacts/debuggee.reference6
-rw-r--r--testsuite/tests/tool-debugger/find-artifacts/in/blah.ml3
-rw-r--r--testsuite/tests/tool-debugger/find-artifacts/in/foo.ml13
-rw-r--r--testsuite/tests/tool-debugger/find-artifacts/input_script5
-rw-r--r--testsuite/tests/tool-debugger/no_debug_event/.ignore4
-rw-r--r--testsuite/tests/tool-debugger/no_debug_event/Makefile57
-rw-r--r--testsuite/tests/tool-debugger/no_debug_event/a.ml1
-rw-r--r--testsuite/tests/tool-debugger/no_debug_event/b.ml3
-rw-r--r--testsuite/tests/tool-debugger/no_debug_event/input_script2
-rw-r--r--testsuite/tests/tool-debugger/no_debug_event/noev.reference4
-rw-r--r--testsuite/tests/tool-lexyacc/.ignore3
-rw-r--r--testsuite/tests/tool-lexyacc/Makefile22
-rw-r--r--testsuite/tests/tool-lexyacc/gram_aux.ml44
-rw-r--r--testsuite/tests/tool-lexyacc/grammar.mly111
-rw-r--r--testsuite/tests/tool-lexyacc/input131
-rw-r--r--testsuite/tests/tool-lexyacc/lexgen.ml268
-rw-r--r--testsuite/tests/tool-lexyacc/main.ml117
-rw-r--r--testsuite/tests/tool-lexyacc/main.reference312
-rw-r--r--testsuite/tests/tool-lexyacc/output.ml164
-rw-r--r--testsuite/tests/tool-lexyacc/scan_aux.ml57
-rw-r--r--testsuite/tests/tool-lexyacc/scanner.mll130
-rw-r--r--testsuite/tests/tool-lexyacc/syntax.ml38
-rw-r--r--testsuite/tests/tool-ocaml/Makefile33
-rw-r--r--testsuite/tests/tool-ocaml/lib.ml42
-rw-r--r--testsuite/tests/tool-ocaml/t000.ml7
-rw-r--r--testsuite/tests/tool-ocaml/t010-const0.ml8
-rw-r--r--testsuite/tests/tool-ocaml/t010-const1.ml8
-rw-r--r--testsuite/tests/tool-ocaml/t010-const2.ml8
-rw-r--r--testsuite/tests/tool-ocaml/t010-const3.ml8
-rw-r--r--testsuite/tests/tool-ocaml/t011-constint.ml8
-rw-r--r--testsuite/tests/tool-ocaml/t020.ml10
-rw-r--r--testsuite/tests/tool-ocaml/t021-pushconst1.ml10
-rw-r--r--testsuite/tests/tool-ocaml/t021-pushconst2.ml10
-rw-r--r--testsuite/tests/tool-ocaml/t021-pushconst3.ml10
-rw-r--r--testsuite/tests/tool-ocaml/t022-pushconstint.ml10
-rw-r--r--testsuite/tests/tool-ocaml/t040-makeblock1.ml13
-rw-r--r--testsuite/tests/tool-ocaml/t040-makeblock2.ml15
-rw-r--r--testsuite/tests/tool-ocaml/t040-makeblock3.ml17
-rw-r--r--testsuite/tests/tool-ocaml/t041-makeblock.ml19
-rw-r--r--testsuite/tests/tool-ocaml/t050-getglobal.ml8
-rw-r--r--testsuite/tests/tool-ocaml/t050-pushgetglobal.ml10
-rw-r--r--testsuite/tests/tool-ocaml/t051-getglobalfield.ml13
-rw-r--r--testsuite/tests/tool-ocaml/t051-pushgetglobalfield.ml15
-rw-r--r--testsuite/tests/tool-ocaml/t060-raise.ml15
-rw-r--r--testsuite/tests/tool-ocaml/t070-branch.ml20
-rw-r--r--testsuite/tests/tool-ocaml/t070-branchif.ml20
-rw-r--r--testsuite/tests/tool-ocaml/t070-branchifnot.ml18
-rw-r--r--testsuite/tests/tool-ocaml/t071-boolnot.ml19
-rw-r--r--testsuite/tests/tool-ocaml/t080-eq.ml21
-rw-r--r--testsuite/tests/tool-ocaml/t080-geint.ml21
-rw-r--r--testsuite/tests/tool-ocaml/t080-gtint.ml20
-rw-r--r--testsuite/tests/tool-ocaml/t080-leint.ml21
-rw-r--r--testsuite/tests/tool-ocaml/t080-ltint.ml20
-rw-r--r--testsuite/tests/tool-ocaml/t080-neq.ml20
-rw-r--r--testsuite/tests/tool-ocaml/t090-acc0.ml25
-rw-r--r--testsuite/tests/tool-ocaml/t090-acc1.ml27
-rw-r--r--testsuite/tests/tool-ocaml/t090-acc2.ml29
-rw-r--r--testsuite/tests/tool-ocaml/t090-acc3.ml31
-rw-r--r--testsuite/tests/tool-ocaml/t090-acc4.ml33
-rw-r--r--testsuite/tests/tool-ocaml/t090-acc5.ml35
-rw-r--r--testsuite/tests/tool-ocaml/t090-acc6.ml37
-rw-r--r--testsuite/tests/tool-ocaml/t090-acc7.ml39
-rw-r--r--testsuite/tests/tool-ocaml/t091-acc.ml41
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc.ml38
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc0.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc1.ml24
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc2.ml26
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc3.ml28
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc4.ml30
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc5.ml32
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc6.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t092-pushacc7.ml36
-rw-r--r--testsuite/tests/tool-ocaml/t093-pushacc.ml38
-rw-r--r--testsuite/tests/tool-ocaml/t100-pushtrap.ml21
-rw-r--r--testsuite/tests/tool-ocaml/t101-poptrap.ml21
-rw-r--r--testsuite/tests/tool-ocaml/t110-addint.ml26
-rw-r--r--testsuite/tests/tool-ocaml/t110-andint.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-asrint-1.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-asrint-2.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-divint-1.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-divint-2.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-divint-3.ml33
-rw-r--r--testsuite/tests/tool-ocaml/t110-lslint.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-lsrint.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-modint-1.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-modint-2.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t110-mulint.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-negint.ml25
-rw-r--r--testsuite/tests/tool-ocaml/t110-offsetint.ml21
-rw-r--r--testsuite/tests/tool-ocaml/t110-orint.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t110-subint.ml26
-rw-r--r--testsuite/tests/tool-ocaml/t110-xorint.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t120-getstringchar.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t121-setstringchar.ml31
-rw-r--r--testsuite/tests/tool-ocaml/t130-getvectitem.ml24
-rw-r--r--testsuite/tests/tool-ocaml/t130-vectlength.ml23
-rw-r--r--testsuite/tests/tool-ocaml/t131-setvectitem.ml33
-rw-r--r--testsuite/tests/tool-ocaml/t140-switch-1.ml32
-rw-r--r--testsuite/tests/tool-ocaml/t140-switch-2.ml32
-rw-r--r--testsuite/tests/tool-ocaml/t140-switch-3.ml31
-rw-r--r--testsuite/tests/tool-ocaml/t140-switch-4.ml31
-rw-r--r--testsuite/tests/tool-ocaml/t141-switch-5.ml38
-rw-r--r--testsuite/tests/tool-ocaml/t141-switch-6.ml38
-rw-r--r--testsuite/tests/tool-ocaml/t141-switch-7.ml37
-rw-r--r--testsuite/tests/tool-ocaml/t142-switch-8.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t142-switch-9.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t142-switch-A.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t150-push-1.ml24
-rw-r--r--testsuite/tests/tool-ocaml/t150-push-2.ml39
-rw-r--r--testsuite/tests/tool-ocaml/t160-closure.ml19
-rw-r--r--testsuite/tests/tool-ocaml/t161-apply1.ml42
-rw-r--r--testsuite/tests/tool-ocaml/t162-return.ml21
-rw-r--r--testsuite/tests/tool-ocaml/t163.ml23
-rw-r--r--testsuite/tests/tool-ocaml/t164-apply2.ml24
-rw-r--r--testsuite/tests/tool-ocaml/t164-apply3.ml25
-rw-r--r--testsuite/tests/tool-ocaml/t165-apply.ml28
-rw-r--r--testsuite/tests/tool-ocaml/t170-envacc2.ml37
-rw-r--r--testsuite/tests/tool-ocaml/t170-envacc3.ml42
-rw-r--r--testsuite/tests/tool-ocaml/t170-envacc4.ml47
-rw-r--r--testsuite/tests/tool-ocaml/t171-envacc.ml52
-rw-r--r--testsuite/tests/tool-ocaml/t172-pushenvacc1.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t172-pushenvacc2.ml37
-rw-r--r--testsuite/tests/tool-ocaml/t172-pushenvacc3.ml42
-rw-r--r--testsuite/tests/tool-ocaml/t172-pushenvacc4.ml47
-rw-r--r--testsuite/tests/tool-ocaml/t173-pushenvacc.ml52
-rw-r--r--testsuite/tests/tool-ocaml/t180-appterm1.ml35
-rw-r--r--testsuite/tests/tool-ocaml/t180-appterm2.ml38
-rw-r--r--testsuite/tests/tool-ocaml/t180-appterm3.ml39
-rw-r--r--testsuite/tests/tool-ocaml/t181-appterm.ml40
-rw-r--r--testsuite/tests/tool-ocaml/t190-makefloatblock-1.ml17
-rw-r--r--testsuite/tests/tool-ocaml/t190-makefloatblock-2.ml18
-rw-r--r--testsuite/tests/tool-ocaml/t190-makefloatblock-3.ml19
-rw-r--r--testsuite/tests/tool-ocaml/t191-vectlength.ml26
-rw-r--r--testsuite/tests/tool-ocaml/t192-getfloatfield-1.ml23
-rw-r--r--testsuite/tests/tool-ocaml/t192-getfloatfield-2.ml23
-rw-r--r--testsuite/tests/tool-ocaml/t193-setfloatfield-1.ml36
-rw-r--r--testsuite/tests/tool-ocaml/t193-setfloatfield-2.ml36
-rw-r--r--testsuite/tests/tool-ocaml/t200-getfield0.ml25
-rw-r--r--testsuite/tests/tool-ocaml/t200-getfield1.ml26
-rw-r--r--testsuite/tests/tool-ocaml/t200-getfield2.ml27
-rw-r--r--testsuite/tests/tool-ocaml/t200-getfield3.ml28
-rw-r--r--testsuite/tests/tool-ocaml/t201-getfield.ml29
-rw-r--r--testsuite/tests/tool-ocaml/t210-setfield0.ml36
-rw-r--r--testsuite/tests/tool-ocaml/t210-setfield1.ml38
-rw-r--r--testsuite/tests/tool-ocaml/t210-setfield2.ml40
-rw-r--r--testsuite/tests/tool-ocaml/t210-setfield3.ml42
-rw-r--r--testsuite/tests/tool-ocaml/t211-setfield.ml44
-rw-r--r--testsuite/tests/tool-ocaml/t220-assign.ml27
-rw-r--r--testsuite/tests/tool-ocaml/t230-check_signals.ml28
-rw-r--r--testsuite/tests/tool-ocaml/t240-c_call1.ml27
-rw-r--r--testsuite/tests/tool-ocaml/t240-c_call2.ml22
-rw-r--r--testsuite/tests/tool-ocaml/t240-c_call3.ml23
-rw-r--r--testsuite/tests/tool-ocaml/t240-c_call4.ml32
-rw-r--r--testsuite/tests/tool-ocaml/t240-c_call5.ml33
-rw-r--r--testsuite/tests/tool-ocaml/t250-closurerec-1.ml19
-rw-r--r--testsuite/tests/tool-ocaml/t250-closurerec-2.ml29
-rw-r--r--testsuite/tests/tool-ocaml/t251-pushoffsetclosure0.ml39
-rw-r--r--testsuite/tests/tool-ocaml/t251-pushoffsetclosure2.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t251-pushoffsetclosurem2.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t252-pushoffsetclosure.ml38
-rw-r--r--testsuite/tests/tool-ocaml/t253-offsetclosure0.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t253-offsetclosure2.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t253-offsetclosurem2.ml34
-rw-r--r--testsuite/tests/tool-ocaml/t254-offsetclosure.ml37
-rw-r--r--testsuite/tests/tool-ocaml/t260-offsetref.ml31
-rw-r--r--testsuite/tests/tool-ocaml/t270-push_retaddr.ml36
-rw-r--r--testsuite/tests/tool-ocaml/t300-getmethod.ml5885
-rw-r--r--testsuite/tests/tool-ocaml/t301-object.ml25
-rw-r--r--testsuite/tests/tool-ocaml/t310-alloc-1.ml1587
-rw-r--r--testsuite/tests/tool-ocaml/t310-alloc-2.ml2313
-rw-r--r--testsuite/tests/tool-ocaml/t320-gc-1.ml1589
-rw-r--r--testsuite/tests/tool-ocaml/t320-gc-2.ml1589
-rw-r--r--testsuite/tests/tool-ocaml/t320-gc-3.ml1589
-rw-r--r--testsuite/tests/tool-ocaml/t330-compact-1.ml15
-rw-r--r--testsuite/tests/tool-ocaml/t330-compact-2.ml755
-rw-r--r--testsuite/tests/tool-ocaml/t330-compact-3.ml1589
-rw-r--r--testsuite/tests/tool-ocaml/t330-compact-4.ml1589
-rw-r--r--testsuite/tests/tool-ocaml/t340-weak.ml24
-rw-r--r--testsuite/tests/tool-ocaml/t350-heapcheck.ml25
-rw-r--r--testsuite/tests/tool-ocaml/t360-stacks-1.ml43
-rw-r--r--testsuite/tests/tool-ocaml/t360-stacks-2.ml54
-rw-r--r--testsuite/tests/tool-ocamldoc/.ignore4
-rw-r--r--testsuite/tests/tool-ocamldoc/Makefile49
-rw-r--r--testsuite/tests/tool-ocamldoc/odoc_test.ml128
-rw-r--r--testsuite/tests/tool-ocamldoc/t01.ml22
-rw-r--r--testsuite/tests/tool-ocamldoc/t01.reference38
-rw-r--r--testsuite/tests/tool-ocamldoc/t02.ml10
-rw-r--r--testsuite/tests/tool-ocamldoc/t02.reference12
-rw-r--r--testsuite/tests/tool-ocamldoc/t03.ml12
-rw-r--r--testsuite/tests/tool-ocamldoc/t03.reference14
-rw-r--r--testsuite/tests/tool-toplevel/Makefile15
-rw-r--r--testsuite/tests/tool-toplevel/tracing.ml4
-rw-r--r--testsuite/tests/tool-toplevel/tracing.ml.reference30
-rw-r--r--testsuite/tests/translprim/Makefile4
-rw-r--r--testsuite/tests/translprim/array_spec.ml62
-rw-r--r--testsuite/tests/translprim/array_spec.ml.reference88
-rw-r--r--testsuite/tests/translprim/comparison_table.ml239
-rw-r--r--testsuite/tests/translprim/comparison_table.ml.reference364
-rw-r--r--testsuite/tests/translprim/module_coercion.ml37
-rw-r--r--testsuite/tests/translprim/module_coercion.ml.reference104
-rw-r--r--testsuite/tests/translprim/ref_spec.ml42
-rw-r--r--testsuite/tests/translprim/ref_spec.ml.reference33
-rw-r--r--testsuite/tests/typing-extensions/Makefile3
-rw-r--r--testsuite/tests/typing-extensions/cast.ml97
-rw-r--r--testsuite/tests/typing-extensions/cast.ml.reference33
-rw-r--r--testsuite/tests/typing-extensions/extensions.ml323
-rw-r--r--testsuite/tests/typing-extensions/extensions.ml.reference131
-rw-r--r--testsuite/tests/typing-extensions/msg.ml131
-rw-r--r--testsuite/tests/typing-extensions/msg.ml.reference23
-rw-r--r--testsuite/tests/typing-extensions/open_types.ml117
-rw-r--r--testsuite/tests/typing-extensions/open_types.ml.reference96
-rw-r--r--testsuite/tests/typing-fstclassmod/Makefile19
-rw-r--r--testsuite/tests/typing-fstclassmod/fstclassmod.ml167
-rw-r--r--testsuite/tests/typing-fstclassmod/fstclassmod.reference7
-rw-r--r--testsuite/tests/typing-gadts/Makefile15
-rw-r--r--testsuite/tests/typing-gadts/didier.ml47
-rw-r--r--testsuite/tests/typing-gadts/dynamic_frisch.ml475
-rw-r--r--testsuite/tests/typing-gadts/dynamic_frisch.ml.principal.reference177
-rw-r--r--testsuite/tests/typing-gadts/dynamic_frisch.ml.reference177
-rw-r--r--testsuite/tests/typing-gadts/omega07.ml798
-rw-r--r--testsuite/tests/typing-gadts/omega07.ml.principal.reference312
-rw-r--r--testsuite/tests/typing-gadts/omega07.ml.reference312
-rw-r--r--testsuite/tests/typing-gadts/pr5332.ml17
-rw-r--r--testsuite/tests/typing-gadts/pr5332.ml.reference19
-rw-r--r--testsuite/tests/typing-gadts/pr5689.ml74
-rw-r--r--testsuite/tests/typing-gadts/pr5689.ml.principal.reference27
-rw-r--r--testsuite/tests/typing-gadts/pr5689.ml.reference27
-rw-r--r--testsuite/tests/typing-gadts/pr5785.ml10
-rw-r--r--testsuite/tests/typing-gadts/pr5785.ml.reference15
-rw-r--r--testsuite/tests/typing-gadts/pr5848.ml14
-rw-r--r--testsuite/tests/typing-gadts/pr5848.ml.reference8
-rw-r--r--testsuite/tests/typing-gadts/pr5906.ml18
-rw-r--r--testsuite/tests/typing-gadts/pr5906.ml.reference5
-rw-r--r--testsuite/tests/typing-gadts/pr5948.ml30
-rw-r--r--testsuite/tests/typing-gadts/pr5948.ml.reference22
-rw-r--r--testsuite/tests/typing-gadts/pr5981.ml22
-rw-r--r--testsuite/tests/typing-gadts/pr5981.ml.reference28
-rw-r--r--testsuite/tests/typing-gadts/pr5985.ml102
-rw-r--r--testsuite/tests/typing-gadts/pr5985.ml.reference89
-rw-r--r--testsuite/tests/typing-gadts/pr5989.ml35
-rw-r--r--testsuite/tests/typing-gadts/pr5989.ml.reference24
-rw-r--r--testsuite/tests/typing-gadts/pr5997.ml28
-rw-r--r--testsuite/tests/typing-gadts/pr5997.ml.reference21
-rw-r--r--testsuite/tests/typing-gadts/pr6158.ml9
-rw-r--r--testsuite/tests/typing-gadts/pr6158.ml.principal.reference19
-rw-r--r--testsuite/tests/typing-gadts/pr6158.ml.reference15
-rw-r--r--testsuite/tests/typing-gadts/pr6163.ml14
-rw-r--r--testsuite/tests/typing-gadts/pr6163.ml.principal.reference18
-rw-r--r--testsuite/tests/typing-gadts/pr6163.ml.reference18
-rw-r--r--testsuite/tests/typing-gadts/pr6174.ml3
-rw-r--r--testsuite/tests/typing-gadts/pr6174.ml.principal.reference7
-rw-r--r--testsuite/tests/typing-gadts/pr6174.ml.reference7
-rw-r--r--testsuite/tests/typing-gadts/pr6241.ml16
-rw-r--r--testsuite/tests/typing-gadts/pr6241.ml.principal.reference15
-rw-r--r--testsuite/tests/typing-gadts/pr6241.ml.reference15
-rw-r--r--testsuite/tests/typing-gadts/pr6690.ml31
-rw-r--r--testsuite/tests/typing-gadts/pr6690.ml.principal.reference23
-rw-r--r--testsuite/tests/typing-gadts/pr6690.ml.reference27
-rw-r--r--testsuite/tests/typing-gadts/pr6817.ml24
-rw-r--r--testsuite/tests/typing-gadts/pr6817.ml.reference9
-rw-r--r--testsuite/tests/typing-gadts/pr6993_bad.ml12
-rw-r--r--testsuite/tests/typing-gadts/pr6993_bad.ml.reference13
-rw-r--r--testsuite/tests/typing-gadts/term-conv.ml139
-rw-r--r--testsuite/tests/typing-gadts/term-conv.ml.principal.reference71
-rw-r--r--testsuite/tests/typing-gadts/term-conv.ml.reference71
-rw-r--r--testsuite/tests/typing-gadts/test.ml548
-rw-r--r--testsuite/tests/typing-gadts/test.ml.principal.reference337
-rw-r--r--testsuite/tests/typing-gadts/test.ml.reference324
-rw-r--r--testsuite/tests/typing-gadts/unify_mb.ml170
-rw-r--r--testsuite/tests/typing-gadts/unify_mb.ml.principal.reference45
-rw-r--r--testsuite/tests/typing-gadts/unify_mb.ml.reference45
-rw-r--r--testsuite/tests/typing-gadts/yallop_bugs.ml45
-rw-r--r--testsuite/tests/typing-gadts/yallop_bugs.ml.principal.reference29
-rw-r--r--testsuite/tests/typing-gadts/yallop_bugs.ml.reference29
-rw-r--r--testsuite/tests/typing-implicit_unpack/Makefile15
-rw-r--r--testsuite/tests/typing-implicit_unpack/implicit_unpack.ml165
-rw-r--r--testsuite/tests/typing-implicit_unpack/implicit_unpack.ml.reference166
-rw-r--r--testsuite/tests/typing-labels/Makefile15
-rw-r--r--testsuite/tests/typing-labels/mixin.ml155
-rw-r--r--testsuite/tests/typing-labels/mixin.reference3
-rw-r--r--testsuite/tests/typing-labels/mixin2.ml190
-rw-r--r--testsuite/tests/typing-labels/mixin2.reference3
-rw-r--r--testsuite/tests/typing-labels/mixin3.ml184
-rw-r--r--testsuite/tests/typing-labels/mixin3.reference3
-rw-r--r--testsuite/tests/typing-misc-bugs/Makefile14
-rw-r--r--testsuite/tests/typing-misc-bugs/pr6303_bad.ml3
-rw-r--r--testsuite/tests/typing-misc/Makefile15
-rw-r--r--testsuite/tests/typing-misc/constraints.ml24
-rw-r--r--testsuite/tests/typing-misc/constraints.ml.reference34
-rw-r--r--testsuite/tests/typing-misc/labels.ml11
-rw-r--r--testsuite/tests/typing-misc/labels.ml.principal.reference16
-rw-r--r--testsuite/tests/typing-misc/labels.ml.reference16
-rw-r--r--testsuite/tests/typing-misc/occur_check.ml5
-rw-r--r--testsuite/tests/typing-misc/occur_check.ml.reference15
-rw-r--r--testsuite/tests/typing-misc/polyvars.ml15
-rw-r--r--testsuite/tests/typing-misc/polyvars.ml.principal.reference34
-rw-r--r--testsuite/tests/typing-misc/polyvars.ml.reference34
-rw-r--r--testsuite/tests/typing-misc/records.ml38
-rw-r--r--testsuite/tests/typing-misc/records.ml.principal.reference54
-rw-r--r--testsuite/tests/typing-misc/records.ml.reference54
-rw-r--r--testsuite/tests/typing-misc/variant.ml8
-rw-r--r--testsuite/tests/typing-misc/variant.ml.reference16
-rw-r--r--testsuite/tests/typing-misc/wellfounded.ml11
-rw-r--r--testsuite/tests/typing-misc/wellfounded.ml.principal.reference7
-rw-r--r--testsuite/tests/typing-misc/wellfounded.ml.reference7
-rw-r--r--testsuite/tests/typing-modules-bugs/Makefile14
-rw-r--r--testsuite/tests/typing-modules-bugs/gatien_baron_20131019_ok.ml31
-rw-r--r--testsuite/tests/typing-modules-bugs/pr5164_ok.ml9
-rw-r--r--testsuite/tests/typing-modules-bugs/pr51_ok.ml18
-rw-r--r--testsuite/tests/typing-modules-bugs/pr5663_ok.ml7
-rw-r--r--testsuite/tests/typing-modules-bugs/pr5914_ok.ml18
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6240_ok.ml11
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6293_bad.ml2
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6427_bad.ml20
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6513_ok.ml28
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6572_ok.ml19
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6651_ok.ml13
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6752_ok.ml43
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6899_first_bad.ml3
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6899_ok.ml6
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6899_second_bad.ml5
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6944_ok.ml4
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6982_ok.ml26
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6985_ok.ml7
-rw-r--r--testsuite/tests/typing-modules-bugs/pr6992_bad.ml15
-rw-r--r--testsuite/tests/typing-modules/Makefile15
-rw-r--r--testsuite/tests/typing-modules/Test.ml62
-rw-r--r--testsuite/tests/typing-modules/Test.ml.principal.reference41
-rw-r--r--testsuite/tests/typing-modules/Test.ml.reference41
-rw-r--r--testsuite/tests/typing-modules/a.mli3
-rw-r--r--testsuite/tests/typing-modules/aliases.ml246
-rw-r--r--testsuite/tests/typing-modules/aliases.ml.reference402
-rw-r--r--testsuite/tests/typing-modules/b.ml18
-rw-r--r--testsuite/tests/typing-modules/b2.ml14
-rw-r--r--testsuite/tests/typing-modules/b3.mli4
-rw-r--r--testsuite/tests/typing-modules/d.ml2
-rw-r--r--testsuite/tests/typing-modules/firstclass.ml21
-rw-r--r--testsuite/tests/typing-modules/firstclass.ml.reference27
-rw-r--r--testsuite/tests/typing-modules/generative.ml34
-rw-r--r--testsuite/tests/typing-modules/generative.ml.reference44
-rw-r--r--testsuite/tests/typing-modules/pr5911.ml14
-rw-r--r--testsuite/tests/typing-modules/pr5911.ml.reference9
-rw-r--r--testsuite/tests/typing-modules/printing.ml14
-rw-r--r--testsuite/tests/typing-modules/printing.ml.reference10
-rw-r--r--testsuite/tests/typing-objects-bugs/Makefile15
-rw-r--r--testsuite/tests/typing-objects-bugs/pr3968_bad.ml21
-rw-r--r--testsuite/tests/typing-objects-bugs/pr4018_bad.ml46
-rw-r--r--testsuite/tests/typing-objects-bugs/pr4435_bad.ml11
-rw-r--r--testsuite/tests/typing-objects-bugs/pr4766_ok.ml10
-rw-r--r--testsuite/tests/typing-objects-bugs/pr4824_ok.ml10
-rw-r--r--testsuite/tests/typing-objects-bugs/pr4824a_bad.ml6
-rw-r--r--testsuite/tests/typing-objects-bugs/pr5156_ok.ml10
-rw-r--r--testsuite/tests/typing-objects-bugs/woodyatt_ok.ml14
-rw-r--r--testsuite/tests/typing-objects-bugs/yamagata021012_ok.ml193
-rw-r--r--testsuite/tests/typing-objects/Exemples.ml333
-rw-r--r--testsuite/tests/typing-objects/Exemples.ml.principal.reference358
-rw-r--r--testsuite/tests/typing-objects/Exemples.ml.reference360
-rw-r--r--testsuite/tests/typing-objects/Makefile15
-rw-r--r--testsuite/tests/typing-objects/Tests.ml336
-rw-r--r--testsuite/tests/typing-objects/Tests.ml.principal.reference314
-rw-r--r--testsuite/tests/typing-objects/Tests.ml.reference314
-rw-r--r--testsuite/tests/typing-objects/pr5545.ml22
-rw-r--r--testsuite/tests/typing-objects/pr5545.ml.principal.reference6
-rw-r--r--testsuite/tests/typing-objects/pr5545.ml.reference6
-rw-r--r--testsuite/tests/typing-objects/pr5619_bad.ml29
-rw-r--r--testsuite/tests/typing-objects/pr5619_bad.ml.principal.reference18
-rw-r--r--testsuite/tests/typing-objects/pr5619_bad.ml.reference18
-rw-r--r--testsuite/tests/typing-objects/pr5858.ml2
-rw-r--r--testsuite/tests/typing-objects/pr5858.ml.reference7
-rw-r--r--testsuite/tests/typing-objects/pr6123_bad.ml23
-rw-r--r--testsuite/tests/typing-objects/pr6123_bad.ml.principal.reference8
-rw-r--r--testsuite/tests/typing-objects/pr6123_bad.ml.reference8
-rw-r--r--testsuite/tests/typing-objects/pr6383.ml1
-rw-r--r--testsuite/tests/typing-objects/pr6383.ml.reference6
-rw-r--r--testsuite/tests/typing-poly-bugs/Makefile15
-rw-r--r--testsuite/tests/typing-poly-bugs/pr5322_ok.ml6
-rw-r--r--testsuite/tests/typing-poly-bugs/pr5673_bad.ml23
-rw-r--r--testsuite/tests/typing-poly-bugs/pr5673_ok.ml23
-rw-r--r--testsuite/tests/typing-poly/Makefile15
-rw-r--r--testsuite/tests/typing-poly/poly.ml689
-rw-r--r--testsuite/tests/typing-poly/poly.ml.principal.reference675
-rw-r--r--testsuite/tests/typing-poly/poly.ml.reference629
-rw-r--r--testsuite/tests/typing-polyvariants-bugs-2/Makefile23
-rw-r--r--testsuite/tests/typing-polyvariants-bugs-2/pr3918a.mli1
-rw-r--r--testsuite/tests/typing-polyvariants-bugs-2/pr3918b.mli1
-rw-r--r--testsuite/tests/typing-polyvariants-bugs-2/pr3918c.ml10
-rw-r--r--testsuite/tests/typing-polyvariants-bugs/Makefile15
-rw-r--r--testsuite/tests/typing-polyvariants-bugs/pr4775_ok.ml11
-rw-r--r--testsuite/tests/typing-polyvariants-bugs/pr4933_ok.ml15
-rw-r--r--testsuite/tests/typing-polyvariants-bugs/pr5057_ok.ml14
-rw-r--r--testsuite/tests/typing-polyvariants-bugs/pr5057a_bad.ml7
-rw-r--r--testsuite/tests/typing-polyvariants-bugs/privrowsabate_ok.ml53
-rw-r--r--testsuite/tests/typing-private-bugs/Makefile15
-rw-r--r--testsuite/tests/typing-private-bugs/pr5026_bad.ml11
-rw-r--r--testsuite/tests/typing-private-bugs/pr5469_ok.ml7
-rw-r--r--testsuite/tests/typing-private/Makefile15
-rw-r--r--testsuite/tests/typing-private/private.ml113
-rw-r--r--testsuite/tests/typing-private/private.ml.principal.reference125
-rw-r--r--testsuite/tests/typing-private/private.ml.reference125
-rw-r--r--testsuite/tests/typing-recmod/Makefile15
-rw-r--r--testsuite/tests/typing-recmod/t01bad.ml2
-rw-r--r--testsuite/tests/typing-recmod/t02bad.ml3
-rw-r--r--testsuite/tests/typing-recmod/t03ok.ml3
-rw-r--r--testsuite/tests/typing-recmod/t04bad.ml2
-rw-r--r--testsuite/tests/typing-recmod/t05bad.ml3
-rw-r--r--testsuite/tests/typing-recmod/t06ok.ml3
-rw-r--r--testsuite/tests/typing-recmod/t07bad.ml3
-rw-r--r--testsuite/tests/typing-recmod/t08bad.ml4
-rw-r--r--testsuite/tests/typing-recmod/t09bad.ml5
-rw-r--r--testsuite/tests/typing-recmod/t10ok.ml5
-rw-r--r--testsuite/tests/typing-recmod/t11bad.ml5
-rw-r--r--testsuite/tests/typing-recmod/t12bad.ml13
-rw-r--r--testsuite/tests/typing-recmod/t13ok.ml5
-rw-r--r--testsuite/tests/typing-recmod/t14bad.ml17
-rw-r--r--testsuite/tests/typing-recmod/t15bad.ml3
-rw-r--r--testsuite/tests/typing-recmod/t16ok.ml30
-rw-r--r--testsuite/tests/typing-recmod/t17ok.ml41
-rw-r--r--testsuite/tests/typing-recmod/t18ok.ml25
-rw-r--r--testsuite/tests/typing-recmod/t19ok.ml15
-rw-r--r--testsuite/tests/typing-recmod/t20ok.ml30
-rw-r--r--testsuite/tests/typing-recmod/t21ok.ml27
-rw-r--r--testsuite/tests/typing-recmod/t22ok.ml511
-rw-r--r--testsuite/tests/typing-recmod/t22ok.mli134
-rw-r--r--testsuite/tests/typing-recordarg/Makefile15
-rw-r--r--testsuite/tests/typing-recordarg/recordarg.ml92
-rw-r--r--testsuite/tests/typing-recordarg/recordarg.ml.reference67
-rw-r--r--testsuite/tests/typing-rectypes-bugs/Makefile15
-rw-r--r--testsuite/tests/typing-rectypes-bugs/pr5343_bad.ml13
-rw-r--r--testsuite/tests/typing-rectypes-bugs/pr6174_bad.ml3
-rw-r--r--testsuite/tests/typing-rectypes-bugs/pr6870_bad.ml2
-rw-r--r--testsuite/tests/typing-short-paths/Makefile16
-rw-r--r--testsuite/tests/typing-short-paths/pr5918.ml7
-rw-r--r--testsuite/tests/typing-short-paths/pr5918.ml.reference6
-rw-r--r--testsuite/tests/typing-short-paths/pr6836.ml6
-rw-r--r--testsuite/tests/typing-short-paths/pr6836.ml.reference7
-rw-r--r--testsuite/tests/typing-short-paths/short-paths.ml57
-rw-r--r--testsuite/tests/typing-short-paths/short-paths.ml.reference85
-rw-r--r--testsuite/tests/typing-signatures/Makefile15
-rw-r--r--testsuite/tests/typing-signatures/els.ml95
-rw-r--r--testsuite/tests/typing-signatures/els.ml.reference95
-rw-r--r--testsuite/tests/typing-signatures/pr6371.ml7
-rw-r--r--testsuite/tests/typing-signatures/pr6371.ml.reference4
-rw-r--r--testsuite/tests/typing-signatures/pr6672.ml3
-rw-r--r--testsuite/tests/typing-signatures/pr6672.ml.reference10
-rw-r--r--testsuite/tests/typing-sigsubst/Makefile15
-rw-r--r--testsuite/tests/typing-sigsubst/sigsubst.ml40
-rw-r--r--testsuite/tests/typing-sigsubst/sigsubst.ml.reference40
-rw-r--r--testsuite/tests/typing-typeparam/Makefile15
-rw-r--r--testsuite/tests/typing-typeparam/newtype.ml32
-rw-r--r--testsuite/tests/typing-typeparam/newtype.ml.reference19
-rw-r--r--testsuite/tests/typing-unboxed/Makefile15
-rw-r--r--testsuite/tests/typing-unboxed/test.ml94
-rw-r--r--testsuite/tests/typing-unboxed/test.ml.reference129
-rw-r--r--testsuite/tests/typing-warnings/Makefile16
-rw-r--r--testsuite/tests/typing-warnings/coercions.ml5
-rw-r--r--testsuite/tests/typing-warnings/coercions.ml.principal.reference15
-rw-r--r--testsuite/tests/typing-warnings/coercions.ml.reference11
-rw-r--r--testsuite/tests/typing-warnings/pr5892.ml3
-rw-r--r--testsuite/tests/typing-warnings/pr5892.ml.reference12
-rw-r--r--testsuite/tests/typing-warnings/pr6872.ml8
-rw-r--r--testsuite/tests/typing-warnings/pr6872.ml.principal.reference35
-rw-r--r--testsuite/tests/typing-warnings/pr6872.ml.reference30
-rw-r--r--testsuite/tests/typing-warnings/records.ml180
-rw-r--r--testsuite/tests/typing-warnings/records.ml.principal.reference301
-rw-r--r--testsuite/tests/typing-warnings/records.ml.reference290
-rw-r--r--testsuite/tests/typing-warnings/unused_types.ml18
-rw-r--r--testsuite/tests/typing-warnings/unused_types.ml.reference21
-rw-r--r--testsuite/tests/unboxed-primitive-args/Makefile36
-rw-r--r--testsuite/tests/unboxed-primitive-args/README26
-rw-r--r--testsuite/tests/unboxed-primitive-args/common.ml298
-rw-r--r--testsuite/tests/unboxed-primitive-args/common.mli41
-rw-r--r--testsuite/tests/unboxed-primitive-args/gen_test.ml240
-rw-r--r--testsuite/tests/unboxed-primitive-args/main.reference0
-rw-r--r--testsuite/tests/unboxed-primitive-args/test_common.c34
-rw-r--r--testsuite/tests/unboxed-primitive-args/test_common.h41
-rw-r--r--testsuite/tests/utils/Makefile22
-rw-r--r--testsuite/tests/utils/edit_distance.ml48
-rw-r--r--testsuite/tests/utils/edit_distance.reference38
-rw-r--r--testsuite/tests/warnings/Makefile31
-rw-r--r--testsuite/tests/warnings/w01.ml55
-rw-r--r--testsuite/tests/warnings/w01.reference15
-rw-r--r--testsuite/tests/warnings/w06.ml6
-rw-r--r--testsuite/tests/warnings/w06.reference4
-rw-r--r--testsuite/tests/warnings/w51.ml5
-rw-r--r--testsuite/tests/warnings/w51.reference2
-rw-r--r--testsuite/tests/warnings/w51_bis.ml5
-rw-r--r--testsuite/tests/warnings/w51_bis.reference2
-rw-r--r--testsuite/typing33
-rw-r--r--tools/.depend80
-rw-r--r--tools/.ignore27
-rw-r--r--tools/Makefile25
-rw-r--r--tools/Makefile.nt27
-rw-r--r--tools/Makefile.shared313
-rw-r--r--tools/addlabels.ml466
-rwxr-xr-xtools/check-typo239
-rw-r--r--tools/checkstack.c40
-rwxr-xr-xtools/ci-build171
-rw-r--r--tools/cleanup-header26
-rw-r--r--tools/cmt2annot.ml211
-rw-r--r--tools/cvt_emit.mll83
-rw-r--r--tools/depend.ml380
-rw-r--r--tools/depend.mli25
-rw-r--r--tools/dumpobj.ml573
-rw-r--r--tools/eqparsetree.ml781
-rw-r--r--tools/gdb-macros318
-rw-r--r--tools/lexer299.mll458
-rw-r--r--tools/lexer301.mll459
-rw-r--r--tools/magic11
-rw-r--r--tools/make-opcodes14
-rwxr-xr-xtools/make-package-macosx134
-rwxr-xr-xtools/make-version-header.sh53
-rw-r--r--tools/objinfo.ml284
-rw-r--r--tools/objinfo_helper.c99
-rwxr-xr-xtools/ocaml-objcopy-macosx51
-rw-r--r--tools/ocaml299to3.ml138
-rw-r--r--tools/ocamlcp.ml155
-rw-r--r--tools/ocamldep.ml519
-rw-r--r--tools/ocamlmklib.ml308
-rw-r--r--tools/ocamlmktop.ml17
-rw-r--r--tools/ocamlmktop.tpl15
-rw-r--r--tools/ocamloptp.ml171
-rw-r--r--tools/ocamlprof.ml510
-rwxr-xr-xtools/ocamlsize61
-rw-r--r--tools/primreq.ml88
-rw-r--r--tools/profiling.ml54
-rw-r--r--tools/profiling.mli18
-rw-r--r--tools/read_cmt.ml94
-rw-r--r--tools/scrapelabels.ml287
-rwxr-xr-xtools/setignore44
-rw-r--r--toplevel/expunge.ml81
-rw-r--r--toplevel/genprintval.ml573
-rw-r--r--toplevel/genprintval.mli67
-rw-r--r--toplevel/opttopdirs.ml186
-rw-r--r--toplevel/opttopdirs.mli29
-rw-r--r--toplevel/opttoploop.ml464
-rw-r--r--toplevel/opttoploop.mli102
-rw-r--r--toplevel/opttopmain.ml121
-rw-r--r--toplevel/opttopmain.mli15
-rw-r--r--toplevel/opttopstart.ml13
-rw-r--r--toplevel/topdirs.ml562
-rw-r--r--toplevel/topdirs.mli33
-rw-r--r--toplevel/toplevellib.mllib21
-rw-r--r--toplevel/toploop.ml514
-rw-r--r--toplevel/toploop.mli130
-rw-r--r--toplevel/topmain.ml111
-rw-r--r--toplevel/topmain.mli15
-rw-r--r--toplevel/topstart.ml13
-rw-r--r--toplevel/trace.ml147
-rw-r--r--toplevel/trace.mli33
-rw-r--r--typing/annot.mli21
-rw-r--r--typing/btype.ml691
-rw-r--r--typing/btype.mli212
-rw-r--r--typing/cmi_format.ml102
-rw-r--r--typing/cmi_format.mli42
-rw-r--r--typing/cmt_format.ml207
-rw-r--r--typing/cmt_format.mli119
-rw-r--r--typing/ctype.ml4534
-rw-r--r--typing/ctype.mli281
-rw-r--r--typing/datarepr.ml217
-rw-r--r--typing/datarepr.mli33
-rw-r--r--typing/env.ml1890
-rw-r--r--typing/env.mli267
-rw-r--r--typing/envaux.ml95
-rw-r--r--typing/envaux.mli33
-rw-r--r--typing/ident.ml223
-rw-r--r--typing/ident.mli65
-rw-r--r--typing/includeclass.ml107
-rw-r--r--typing/includeclass.mli28
-rw-r--r--typing/includecore.ml336
-rw-r--r--typing/includecore.mli48
-rw-r--r--typing/includemod.ml621
-rw-r--r--typing/includemod.mli55
-rw-r--r--typing/mtype.ml398
-rw-r--r--typing/mtype.mli40
-rw-r--r--typing/oprint.ml633
-rw-r--r--typing/oprint.mli25
-rw-r--r--typing/outcometree.mli127
-rw-r--r--typing/parmatch.ml2040
-rw-r--r--typing/parmatch.mli65
-rw-r--r--typing/path.ml78
-rw-r--r--typing/path.mli39
-rw-r--r--typing/predef.ml223
-rw-r--r--typing/predef.mli65
-rw-r--r--typing/primitive.ml144
-rw-r--r--typing/primitive.mli54
-rw-r--r--typing/printtyp.ml1566
-rw-r--r--typing/printtyp.mli87
-rw-r--r--typing/printtyped.ml859
-rw-r--r--typing/printtyped.mli20
-rw-r--r--typing/stypes.ml209
-rw-r--r--typing/stypes.mli33
-rw-r--r--typing/subst.ml426
-rw-r--r--typing/subst.mli59
-rw-r--r--typing/tast_mapper.ml672
-rw-r--r--typing/tast_mapper.mli64
-rw-r--r--typing/typeclass.ml1880
-rw-r--r--typing/typeclass.mli111
-rw-r--r--typing/typecore.ml4120
-rw-r--r--typing/typecore.mli139
-rw-r--r--typing/typedecl.ml1813
-rw-r--r--typing/typedecl.mli94
-rw-r--r--typing/typedtree.ml596
-rw-r--r--typing/typedtree.mli528
-rw-r--r--typing/typedtreeIter.ml667
-rw-r--r--typing/typedtreeIter.mli94
-rw-r--r--typing/typedtreeMap.ml714
-rw-r--r--typing/typedtreeMap.mli91
-rw-r--r--typing/typemod.ml1799
-rw-r--r--typing/typemod.mli77
-rw-r--r--typing/types.ml314
-rw-r--r--typing/types.mli304
-rw-r--r--typing/typetexp.ml1010
-rw-r--r--typing/typetexp.mli119
-rw-r--r--typing/untypeast.ml781
-rw-r--r--typing/untypeast.mli73
-rw-r--r--utils/.ignore1
-rw-r--r--utils/ccomp.ml138
-rw-r--r--utils/ccomp.mli30
-rw-r--r--utils/clflags.ml127
-rw-r--r--utils/clflags.mli104
-rw-r--r--utils/config.mlbuild151
-rw-r--r--utils/config.mli129
-rw-r--r--utils/config.mlp143
-rw-r--r--utils/consistbl.ml63
-rw-r--r--utils/consistbl.mli59
-rw-r--r--utils/misc.ml516
-rw-r--r--utils/misc.mli237
-rw-r--r--utils/tbl.ml112
-rw-r--r--utils/tbl.mli30
-rw-r--r--utils/terminfo.ml23
-rw-r--r--utils/terminfo.mli23
-rw-r--r--utils/warnings.ml504
-rw-r--r--utils/warnings.mli87
-rw-r--r--yacc/.ignore4
-rw-r--r--yacc/Makefile47
-rw-r--r--yacc/Makefile.nt48
-rw-r--r--yacc/closure.c281
-rw-r--r--yacc/defs.h356
-rw-r--r--yacc/error.c312
-rw-r--r--yacc/lalr.c661
-rw-r--r--yacc/lr0.c618
-rw-r--r--yacc/main.c461
-rw-r--r--yacc/mkpar.c362
-rw-r--r--yacc/output.c982
-rw-r--r--yacc/reader.c1906
-rw-r--r--yacc/skeleton.c57
-rw-r--r--yacc/symtab.c127
-rw-r--r--yacc/verbose.c346
-rw-r--r--yacc/warshall.c94
2432 files changed, 408298 insertions, 0 deletions
diff --git a/.depend b/.depend
new file mode 100644
index 0000000000..c67b2efc2e
--- /dev/null
+++ b/.depend
@@ -0,0 +1,1140 @@
+utils/ccomp.cmi :
+utils/clflags.cmi :
+utils/config.cmi :
+utils/consistbl.cmi :
+utils/misc.cmi : utils/clflags.cmi
+utils/tbl.cmi :
+utils/terminfo.cmi :
+utils/warnings.cmi :
+utils/ccomp.cmo : utils/misc.cmi utils/config.cmi utils/clflags.cmi \
+ utils/ccomp.cmi
+utils/ccomp.cmx : utils/misc.cmx utils/config.cmx utils/clflags.cmx \
+ utils/ccomp.cmi
+utils/clflags.cmo : utils/config.cmi utils/clflags.cmi
+utils/clflags.cmx : utils/config.cmx utils/clflags.cmi
+utils/config.cmo : utils/config.cmi
+utils/config.cmx : utils/config.cmi
+utils/consistbl.cmo : utils/consistbl.cmi
+utils/consistbl.cmx : utils/consistbl.cmi
+utils/misc.cmo : utils/clflags.cmi utils/misc.cmi
+utils/misc.cmx : utils/clflags.cmx utils/misc.cmi
+utils/tbl.cmo : utils/tbl.cmi
+utils/tbl.cmx : utils/tbl.cmi
+utils/terminfo.cmo : utils/terminfo.cmi
+utils/terminfo.cmx : utils/terminfo.cmi
+utils/warnings.cmo : utils/warnings.cmi
+utils/warnings.cmx : utils/warnings.cmi
+parsing/ast_helper.cmi : parsing/parsetree.cmi parsing/longident.cmi \
+ parsing/location.cmi parsing/docstrings.cmi parsing/asttypes.cmi
+parsing/ast_mapper.cmi : parsing/parsetree.cmi parsing/location.cmi
+parsing/asttypes.cmi : parsing/location.cmi
+parsing/docstrings.cmi : parsing/parsetree.cmi parsing/location.cmi
+parsing/lexer.cmi : parsing/parser.cmi parsing/location.cmi
+parsing/location.cmi : utils/warnings.cmi
+parsing/longident.cmi :
+parsing/parse.cmi : parsing/parsetree.cmi
+parsing/parser.cmi : parsing/parsetree.cmi parsing/location.cmi \
+ parsing/docstrings.cmi
+parsing/parsetree.cmi : parsing/longident.cmi parsing/location.cmi \
+ parsing/asttypes.cmi
+parsing/pprintast.cmi : parsing/parsetree.cmi parsing/longident.cmi \
+ parsing/asttypes.cmi
+parsing/printast.cmi : parsing/parsetree.cmi
+parsing/syntaxerr.cmi : parsing/location.cmi
+parsing/ast_helper.cmo : parsing/parsetree.cmi parsing/longident.cmi \
+ parsing/location.cmi parsing/docstrings.cmi parsing/asttypes.cmi \
+ parsing/ast_helper.cmi
+parsing/ast_helper.cmx : parsing/parsetree.cmi parsing/longident.cmx \
+ parsing/location.cmx parsing/docstrings.cmx parsing/asttypes.cmi \
+ parsing/ast_helper.cmi
+parsing/ast_mapper.cmo : parsing/parsetree.cmi utils/misc.cmi \
+ parsing/longident.cmi parsing/location.cmi utils/config.cmi \
+ utils/clflags.cmi parsing/asttypes.cmi parsing/ast_helper.cmi \
+ parsing/ast_mapper.cmi
+parsing/ast_mapper.cmx : parsing/parsetree.cmi utils/misc.cmx \
+ parsing/longident.cmx parsing/location.cmx utils/config.cmx \
+ utils/clflags.cmx parsing/asttypes.cmi parsing/ast_helper.cmx \
+ parsing/ast_mapper.cmi
+parsing/docstrings.cmo : utils/warnings.cmi parsing/parsetree.cmi \
+ parsing/location.cmi parsing/asttypes.cmi parsing/docstrings.cmi
+parsing/docstrings.cmx : utils/warnings.cmx parsing/parsetree.cmi \
+ parsing/location.cmx parsing/asttypes.cmi parsing/docstrings.cmi
+parsing/lexer.cmo : utils/warnings.cmi parsing/parser.cmi utils/misc.cmi \
+ parsing/location.cmi parsing/docstrings.cmi parsing/lexer.cmi
+parsing/lexer.cmx : utils/warnings.cmx parsing/parser.cmx utils/misc.cmx \
+ parsing/location.cmx parsing/docstrings.cmx parsing/lexer.cmi
+parsing/location.cmo : utils/warnings.cmi utils/terminfo.cmi utils/misc.cmi \
+ utils/clflags.cmi parsing/location.cmi
+parsing/location.cmx : utils/warnings.cmx utils/terminfo.cmx utils/misc.cmx \
+ utils/clflags.cmx parsing/location.cmi
+parsing/longident.cmo : utils/misc.cmi parsing/longident.cmi
+parsing/longident.cmx : utils/misc.cmx parsing/longident.cmi
+parsing/parse.cmo : parsing/syntaxerr.cmi parsing/parser.cmi \
+ parsing/location.cmi parsing/lexer.cmi parsing/docstrings.cmi \
+ parsing/parse.cmi
+parsing/parse.cmx : parsing/syntaxerr.cmx parsing/parser.cmx \
+ parsing/location.cmx parsing/lexer.cmx parsing/docstrings.cmx \
+ parsing/parse.cmi
+parsing/parser.cmo : parsing/syntaxerr.cmi parsing/parsetree.cmi \
+ parsing/longident.cmi parsing/location.cmi parsing/docstrings.cmi \
+ utils/clflags.cmi parsing/asttypes.cmi parsing/ast_helper.cmi \
+ parsing/parser.cmi
+parsing/parser.cmx : parsing/syntaxerr.cmx parsing/parsetree.cmi \
+ parsing/longident.cmx parsing/location.cmx parsing/docstrings.cmx \
+ utils/clflags.cmx parsing/asttypes.cmi parsing/ast_helper.cmx \
+ parsing/parser.cmi
+parsing/pprintast.cmo : parsing/parsetree.cmi utils/misc.cmi \
+ parsing/longident.cmi parsing/location.cmi parsing/asttypes.cmi \
+ parsing/pprintast.cmi
+parsing/pprintast.cmx : parsing/parsetree.cmi utils/misc.cmx \
+ parsing/longident.cmx parsing/location.cmx parsing/asttypes.cmi \
+ parsing/pprintast.cmi
+parsing/printast.cmo : parsing/parsetree.cmi utils/misc.cmi \
+ parsing/longident.cmi parsing/location.cmi parsing/asttypes.cmi \
+ parsing/printast.cmi
+parsing/printast.cmx : parsing/parsetree.cmi utils/misc.cmx \
+ parsing/longident.cmx parsing/location.cmx parsing/asttypes.cmi \
+ parsing/printast.cmi
+parsing/syntaxerr.cmo : parsing/location.cmi parsing/syntaxerr.cmi
+parsing/syntaxerr.cmx : parsing/location.cmx parsing/syntaxerr.cmi
+typing/annot.cmi : parsing/location.cmi
+typing/btype.cmi : typing/types.cmi typing/path.cmi parsing/asttypes.cmi
+typing/cmi_format.cmi : typing/types.cmi
+typing/cmt_format.cmi : typing/types.cmi typing/typedtree.cmi \
+ parsing/location.cmi typing/env.cmi typing/cmi_format.cmi
+typing/ctype.cmi : typing/types.cmi typing/path.cmi parsing/longident.cmi \
+ typing/ident.cmi typing/env.cmi parsing/asttypes.cmi
+typing/datarepr.cmi : typing/types.cmi typing/path.cmi typing/ident.cmi
+typing/envaux.cmi : typing/subst.cmi typing/path.cmi typing/env.cmi
+typing/env.cmi : utils/warnings.cmi typing/types.cmi typing/subst.cmi \
+ typing/path.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi utils/consistbl.cmi parsing/asttypes.cmi
+typing/ident.cmi :
+typing/includeclass.cmi : typing/types.cmi typing/env.cmi typing/ctype.cmi
+typing/includecore.cmi : typing/types.cmi typing/typedtree.cmi \
+ typing/ident.cmi typing/env.cmi
+typing/includemod.cmi : typing/types.cmi typing/typedtree.cmi \
+ typing/path.cmi parsing/location.cmi typing/includecore.cmi \
+ typing/ident.cmi typing/env.cmi typing/ctype.cmi
+typing/mtype.cmi : typing/types.cmi typing/path.cmi typing/ident.cmi \
+ typing/env.cmi
+typing/oprint.cmi : typing/outcometree.cmi
+typing/outcometree.cmi : parsing/asttypes.cmi
+typing/parmatch.cmi : typing/types.cmi typing/typedtree.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/env.cmi parsing/asttypes.cmi
+typing/path.cmi : typing/ident.cmi
+typing/predef.cmi : typing/types.cmi typing/path.cmi typing/ident.cmi
+typing/primitive.cmi : parsing/parsetree.cmi parsing/location.cmi
+typing/printtyped.cmi : typing/typedtree.cmi
+typing/printtyp.cmi : typing/types.cmi typing/path.cmi \
+ typing/outcometree.cmi parsing/longident.cmi typing/ident.cmi \
+ typing/env.cmi parsing/asttypes.cmi
+typing/stypes.cmi : typing/typedtree.cmi parsing/location.cmi \
+ typing/annot.cmi
+typing/subst.cmi : typing/types.cmi typing/path.cmi typing/ident.cmi
+typing/tast_mapper.cmi : typing/typedtree.cmi typing/env.cmi \
+ parsing/asttypes.cmi
+typing/typeclass.cmi : typing/types.cmi typing/typedtree.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi typing/env.cmi typing/ctype.cmi parsing/asttypes.cmi
+typing/typecore.cmi : typing/types.cmi typing/typedtree.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi typing/env.cmi parsing/asttypes.cmi typing/annot.cmi
+typing/typedecl.cmi : typing/types.cmi typing/typedtree.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/includecore.cmi typing/ident.cmi typing/env.cmi \
+ parsing/asttypes.cmi
+typing/typedtreeIter.cmi : typing/typedtree.cmi parsing/asttypes.cmi
+typing/typedtreeMap.cmi : typing/typedtree.cmi
+typing/typedtree.cmi : typing/types.cmi typing/primitive.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi typing/env.cmi parsing/asttypes.cmi
+typing/typemod.cmi : typing/types.cmi typing/typedtree.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/includemod.cmi typing/ident.cmi typing/env.cmi \
+ parsing/asttypes.cmi
+typing/types.cmi : typing/primitive.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi parsing/asttypes.cmi
+typing/typetexp.cmi : typing/types.cmi typing/typedtree.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/env.cmi parsing/asttypes.cmi parsing/ast_mapper.cmi
+typing/untypeast.cmi : typing/typedtree.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi
+typing/btype.cmo : typing/types.cmi typing/path.cmi utils/misc.cmi \
+ typing/ident.cmi parsing/asttypes.cmi typing/btype.cmi
+typing/btype.cmx : typing/types.cmx typing/path.cmx utils/misc.cmx \
+ typing/ident.cmx parsing/asttypes.cmi typing/btype.cmi
+typing/cmi_format.cmo : typing/types.cmi parsing/location.cmi \
+ utils/config.cmi typing/cmi_format.cmi
+typing/cmi_format.cmx : typing/types.cmx parsing/location.cmx \
+ utils/config.cmx typing/cmi_format.cmi
+typing/cmt_format.cmo : typing/types.cmi typing/typedtree.cmi \
+ typing/tast_mapper.cmi utils/misc.cmi parsing/location.cmi \
+ parsing/lexer.cmi typing/env.cmi utils/config.cmi typing/cmi_format.cmi \
+ utils/clflags.cmi typing/cmt_format.cmi
+typing/cmt_format.cmx : typing/types.cmx typing/typedtree.cmx \
+ typing/tast_mapper.cmx utils/misc.cmx parsing/location.cmx \
+ parsing/lexer.cmx typing/env.cmx utils/config.cmx typing/cmi_format.cmx \
+ utils/clflags.cmx typing/cmt_format.cmi
+typing/ctype.cmo : typing/types.cmi typing/subst.cmi typing/path.cmi \
+ utils/misc.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi typing/env.cmi utils/clflags.cmi typing/btype.cmi \
+ parsing/asttypes.cmi typing/ctype.cmi
+typing/ctype.cmx : typing/types.cmx typing/subst.cmx typing/path.cmx \
+ utils/misc.cmx parsing/longident.cmx parsing/location.cmx \
+ typing/ident.cmx typing/env.cmx utils/clflags.cmx typing/btype.cmx \
+ parsing/asttypes.cmi typing/ctype.cmi
+typing/datarepr.cmo : typing/types.cmi typing/path.cmi parsing/location.cmi \
+ typing/ident.cmi typing/btype.cmi parsing/asttypes.cmi \
+ typing/datarepr.cmi
+typing/datarepr.cmx : typing/types.cmx typing/path.cmx parsing/location.cmx \
+ typing/ident.cmx typing/btype.cmx parsing/asttypes.cmi \
+ typing/datarepr.cmi
+typing/envaux.cmo : typing/types.cmi typing/subst.cmi typing/printtyp.cmi \
+ typing/path.cmi utils/misc.cmi typing/ident.cmi typing/env.cmi \
+ parsing/asttypes.cmi typing/envaux.cmi
+typing/envaux.cmx : typing/types.cmx typing/subst.cmx typing/printtyp.cmx \
+ typing/path.cmx utils/misc.cmx typing/ident.cmx typing/env.cmx \
+ parsing/asttypes.cmi typing/envaux.cmi
+typing/env.cmo : utils/warnings.cmi typing/types.cmi utils/tbl.cmi \
+ typing/subst.cmi typing/predef.cmi typing/path.cmi utils/misc.cmi \
+ parsing/longident.cmi parsing/location.cmi typing/ident.cmi \
+ typing/datarepr.cmi utils/consistbl.cmi utils/config.cmi \
+ typing/cmi_format.cmi utils/clflags.cmi typing/btype.cmi \
+ parsing/asttypes.cmi typing/env.cmi
+typing/env.cmx : utils/warnings.cmx typing/types.cmx utils/tbl.cmx \
+ typing/subst.cmx typing/predef.cmx typing/path.cmx utils/misc.cmx \
+ parsing/longident.cmx parsing/location.cmx typing/ident.cmx \
+ typing/datarepr.cmx utils/consistbl.cmx utils/config.cmx \
+ typing/cmi_format.cmx utils/clflags.cmx typing/btype.cmx \
+ parsing/asttypes.cmi typing/env.cmi
+typing/ident.cmo : typing/ident.cmi
+typing/ident.cmx : typing/ident.cmi
+typing/includeclass.cmo : typing/types.cmi typing/printtyp.cmi \
+ typing/ctype.cmi typing/includeclass.cmi
+typing/includeclass.cmx : typing/types.cmx typing/printtyp.cmx \
+ typing/ctype.cmx typing/includeclass.cmi
+typing/includecore.cmo : typing/types.cmi typing/typedtree.cmi \
+ typing/predef.cmi typing/path.cmi utils/misc.cmi typing/ident.cmi \
+ typing/env.cmi typing/ctype.cmi typing/btype.cmi parsing/asttypes.cmi \
+ typing/includecore.cmi
+typing/includecore.cmx : typing/types.cmx typing/typedtree.cmx \
+ typing/predef.cmx typing/path.cmx utils/misc.cmx typing/ident.cmx \
+ typing/env.cmx typing/ctype.cmx typing/btype.cmx parsing/asttypes.cmi \
+ typing/includecore.cmi
+typing/includemod.cmo : typing/types.cmi typing/typedtree.cmi utils/tbl.cmi \
+ typing/subst.cmi typing/printtyp.cmi typing/primitive.cmi typing/path.cmi \
+ typing/mtype.cmi utils/misc.cmi parsing/location.cmi \
+ typing/includecore.cmi typing/includeclass.cmi typing/ident.cmi \
+ typing/env.cmi typing/ctype.cmi typing/cmt_format.cmi utils/clflags.cmi \
+ typing/includemod.cmi
+typing/includemod.cmx : typing/types.cmx typing/typedtree.cmx utils/tbl.cmx \
+ typing/subst.cmx typing/printtyp.cmx typing/primitive.cmx typing/path.cmx \
+ typing/mtype.cmx utils/misc.cmx parsing/location.cmx \
+ typing/includecore.cmx typing/includeclass.cmx typing/ident.cmx \
+ typing/env.cmx typing/ctype.cmx typing/cmt_format.cmx utils/clflags.cmx \
+ typing/includemod.cmi
+typing/mtype.cmo : typing/types.cmi typing/subst.cmi typing/path.cmi \
+ utils/misc.cmi parsing/location.cmi typing/ident.cmi typing/env.cmi \
+ typing/ctype.cmi utils/clflags.cmi typing/btype.cmi parsing/asttypes.cmi \
+ typing/mtype.cmi
+typing/mtype.cmx : typing/types.cmx typing/subst.cmx typing/path.cmx \
+ utils/misc.cmx parsing/location.cmx typing/ident.cmx typing/env.cmx \
+ typing/ctype.cmx utils/clflags.cmx typing/btype.cmx parsing/asttypes.cmi \
+ typing/mtype.cmi
+typing/oprint.cmo : typing/outcometree.cmi parsing/asttypes.cmi \
+ typing/oprint.cmi
+typing/oprint.cmx : typing/outcometree.cmi parsing/asttypes.cmi \
+ typing/oprint.cmi
+typing/parmatch.cmo : utils/warnings.cmi typing/types.cmi \
+ typing/typedtree.cmi typing/subst.cmi typing/predef.cmi typing/path.cmi \
+ parsing/parsetree.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi typing/ident.cmi typing/env.cmi typing/ctype.cmi \
+ typing/btype.cmi parsing/asttypes.cmi parsing/ast_helper.cmi \
+ typing/parmatch.cmi
+typing/parmatch.cmx : utils/warnings.cmx typing/types.cmx \
+ typing/typedtree.cmx typing/subst.cmx typing/predef.cmx typing/path.cmx \
+ parsing/parsetree.cmi utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx typing/ident.cmx typing/env.cmx typing/ctype.cmx \
+ typing/btype.cmx parsing/asttypes.cmi parsing/ast_helper.cmx \
+ typing/parmatch.cmi
+typing/path.cmo : typing/ident.cmi typing/path.cmi
+typing/path.cmx : typing/ident.cmx typing/path.cmi
+typing/predef.cmo : typing/types.cmi typing/path.cmi parsing/location.cmi \
+ typing/ident.cmi typing/btype.cmi parsing/asttypes.cmi typing/predef.cmi
+typing/predef.cmx : typing/types.cmx typing/path.cmx parsing/location.cmx \
+ typing/ident.cmx typing/btype.cmx parsing/asttypes.cmi typing/predef.cmi
+typing/primitive.cmo : parsing/parsetree.cmi utils/misc.cmi \
+ parsing/location.cmi typing/primitive.cmi
+typing/primitive.cmx : parsing/parsetree.cmi utils/misc.cmx \
+ parsing/location.cmx typing/primitive.cmi
+typing/printtyped.cmo : typing/typedtree.cmi parsing/printast.cmi \
+ typing/path.cmi utils/misc.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi parsing/asttypes.cmi typing/printtyped.cmi
+typing/printtyped.cmx : typing/typedtree.cmx parsing/printast.cmx \
+ typing/path.cmx utils/misc.cmx parsing/longident.cmx parsing/location.cmx \
+ typing/ident.cmx parsing/asttypes.cmi typing/printtyped.cmi
+typing/printtyp.cmo : typing/types.cmi typing/primitive.cmi \
+ typing/predef.cmi typing/path.cmi parsing/parsetree.cmi \
+ typing/outcometree.cmi typing/oprint.cmi utils/misc.cmi \
+ parsing/longident.cmi parsing/location.cmi typing/ident.cmi \
+ typing/env.cmi typing/ctype.cmi utils/clflags.cmi typing/btype.cmi \
+ parsing/asttypes.cmi typing/printtyp.cmi
+typing/printtyp.cmx : typing/types.cmx typing/primitive.cmx \
+ typing/predef.cmx typing/path.cmx parsing/parsetree.cmi \
+ typing/outcometree.cmi typing/oprint.cmx utils/misc.cmx \
+ parsing/longident.cmx parsing/location.cmx typing/ident.cmx \
+ typing/env.cmx typing/ctype.cmx utils/clflags.cmx typing/btype.cmx \
+ parsing/asttypes.cmi typing/printtyp.cmi
+typing/stypes.cmo : typing/typedtree.cmi typing/printtyp.cmi \
+ parsing/location.cmi utils/clflags.cmi typing/annot.cmi typing/stypes.cmi
+typing/stypes.cmx : typing/typedtree.cmx typing/printtyp.cmx \
+ parsing/location.cmx utils/clflags.cmx typing/annot.cmi typing/stypes.cmi
+typing/subst.cmo : typing/types.cmi utils/tbl.cmi typing/path.cmi \
+ utils/misc.cmi parsing/location.cmi typing/ident.cmi utils/clflags.cmi \
+ typing/btype.cmi parsing/ast_mapper.cmi typing/subst.cmi
+typing/subst.cmx : typing/types.cmx utils/tbl.cmx typing/path.cmx \
+ utils/misc.cmx parsing/location.cmx typing/ident.cmx utils/clflags.cmx \
+ typing/btype.cmx parsing/ast_mapper.cmx typing/subst.cmi
+typing/tast_mapper.cmo : typing/typedtree.cmi typing/env.cmi \
+ parsing/asttypes.cmi typing/tast_mapper.cmi
+typing/tast_mapper.cmx : typing/typedtree.cmx typing/env.cmx \
+ parsing/asttypes.cmi typing/tast_mapper.cmi
+typing/typeclass.cmo : utils/warnings.cmi typing/typetexp.cmi \
+ typing/types.cmi typing/typedtree.cmi typing/typedecl.cmi \
+ typing/typecore.cmi parsing/syntaxerr.cmi typing/subst.cmi \
+ typing/stypes.cmi typing/printtyp.cmi typing/predef.cmi typing/path.cmi \
+ parsing/parsetree.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi typing/includeclass.cmi typing/ident.cmi \
+ typing/env.cmi typing/ctype.cmi typing/cmt_format.cmi utils/clflags.cmi \
+ typing/btype.cmi parsing/asttypes.cmi parsing/ast_helper.cmi \
+ typing/typeclass.cmi
+typing/typeclass.cmx : utils/warnings.cmx typing/typetexp.cmx \
+ typing/types.cmx typing/typedtree.cmx typing/typedecl.cmx \
+ typing/typecore.cmx parsing/syntaxerr.cmx typing/subst.cmx \
+ typing/stypes.cmx typing/printtyp.cmx typing/predef.cmx typing/path.cmx \
+ parsing/parsetree.cmi utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx typing/includeclass.cmx typing/ident.cmx \
+ typing/env.cmx typing/ctype.cmx typing/cmt_format.cmx utils/clflags.cmx \
+ typing/btype.cmx parsing/asttypes.cmi parsing/ast_helper.cmx \
+ typing/typeclass.cmi
+typing/typecore.cmo : utils/warnings.cmi typing/typetexp.cmi \
+ typing/types.cmi typing/typedtree.cmi parsing/syntaxerr.cmi \
+ typing/subst.cmi typing/stypes.cmi typing/printtyp.cmi \
+ typing/primitive.cmi typing/predef.cmi typing/path.cmi \
+ parsing/parsetree.cmi typing/parmatch.cmi typing/oprint.cmi \
+ utils/misc.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi typing/env.cmi typing/ctype.cmi typing/cmt_format.cmi \
+ utils/clflags.cmi typing/btype.cmi parsing/asttypes.cmi \
+ parsing/ast_helper.cmi typing/annot.cmi typing/typecore.cmi
+typing/typecore.cmx : utils/warnings.cmx typing/typetexp.cmx \
+ typing/types.cmx typing/typedtree.cmx parsing/syntaxerr.cmx \
+ typing/subst.cmx typing/stypes.cmx typing/printtyp.cmx \
+ typing/primitive.cmx typing/predef.cmx typing/path.cmx \
+ parsing/parsetree.cmi typing/parmatch.cmx typing/oprint.cmx \
+ utils/misc.cmx parsing/longident.cmx parsing/location.cmx \
+ typing/ident.cmx typing/env.cmx typing/ctype.cmx typing/cmt_format.cmx \
+ utils/clflags.cmx typing/btype.cmx parsing/asttypes.cmi \
+ parsing/ast_helper.cmx typing/annot.cmi typing/typecore.cmi
+typing/typedecl.cmo : utils/warnings.cmi typing/typetexp.cmi \
+ typing/types.cmi typing/typedtree.cmi parsing/syntaxerr.cmi \
+ typing/subst.cmi typing/printtyp.cmi typing/primitive.cmi \
+ typing/predef.cmi typing/path.cmi parsing/parsetree.cmi utils/misc.cmi \
+ parsing/longident.cmi parsing/location.cmi typing/includecore.cmi \
+ typing/ident.cmi typing/env.cmi typing/ctype.cmi utils/config.cmi \
+ utils/clflags.cmi typing/btype.cmi parsing/asttypes.cmi \
+ parsing/ast_helper.cmi typing/typedecl.cmi
+typing/typedecl.cmx : utils/warnings.cmx typing/typetexp.cmx \
+ typing/types.cmx typing/typedtree.cmx parsing/syntaxerr.cmx \
+ typing/subst.cmx typing/printtyp.cmx typing/primitive.cmx \
+ typing/predef.cmx typing/path.cmx parsing/parsetree.cmi utils/misc.cmx \
+ parsing/longident.cmx parsing/location.cmx typing/includecore.cmx \
+ typing/ident.cmx typing/env.cmx typing/ctype.cmx utils/config.cmx \
+ utils/clflags.cmx typing/btype.cmx parsing/asttypes.cmi \
+ parsing/ast_helper.cmx typing/typedecl.cmi
+typing/typedtreeIter.cmo : typing/typedtree.cmi utils/misc.cmi \
+ parsing/asttypes.cmi typing/typedtreeIter.cmi
+typing/typedtreeIter.cmx : typing/typedtree.cmx utils/misc.cmx \
+ parsing/asttypes.cmi typing/typedtreeIter.cmi
+typing/typedtreeMap.cmo : typing/typedtree.cmi utils/misc.cmi \
+ typing/typedtreeMap.cmi
+typing/typedtreeMap.cmx : typing/typedtree.cmx utils/misc.cmx \
+ typing/typedtreeMap.cmi
+typing/typedtree.cmo : typing/types.cmi typing/primitive.cmi typing/path.cmi \
+ parsing/parsetree.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi typing/ident.cmi typing/env.cmi parsing/asttypes.cmi \
+ typing/typedtree.cmi
+typing/typedtree.cmx : typing/types.cmx typing/primitive.cmx typing/path.cmx \
+ parsing/parsetree.cmi utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx typing/ident.cmx typing/env.cmx parsing/asttypes.cmi \
+ typing/typedtree.cmi
+typing/typemod.cmo : utils/warnings.cmi typing/typetexp.cmi typing/types.cmi \
+ typing/typedtree.cmi typing/typedecl.cmi typing/typecore.cmi \
+ typing/typeclass.cmi typing/subst.cmi typing/stypes.cmi \
+ typing/printtyp.cmi typing/path.cmi parsing/parsetree.cmi \
+ typing/mtype.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi typing/includemod.cmi typing/ident.cmi \
+ typing/env.cmi typing/ctype.cmi utils/config.cmi typing/cmt_format.cmi \
+ utils/clflags.cmi typing/btype.cmi parsing/asttypes.cmi \
+ parsing/ast_mapper.cmi typing/annot.cmi typing/typemod.cmi
+typing/typemod.cmx : utils/warnings.cmx typing/typetexp.cmx typing/types.cmx \
+ typing/typedtree.cmx typing/typedecl.cmx typing/typecore.cmx \
+ typing/typeclass.cmx typing/subst.cmx typing/stypes.cmx \
+ typing/printtyp.cmx typing/path.cmx parsing/parsetree.cmi \
+ typing/mtype.cmx utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx typing/includemod.cmx typing/ident.cmx \
+ typing/env.cmx typing/ctype.cmx utils/config.cmx typing/cmt_format.cmx \
+ utils/clflags.cmx typing/btype.cmx parsing/asttypes.cmi \
+ parsing/ast_mapper.cmx typing/annot.cmi typing/typemod.cmi
+typing/types.cmo : typing/primitive.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi parsing/asttypes.cmi typing/types.cmi
+typing/types.cmx : typing/primitive.cmx typing/path.cmx \
+ parsing/parsetree.cmi parsing/longident.cmx parsing/location.cmx \
+ typing/ident.cmx parsing/asttypes.cmi typing/types.cmi
+typing/typetexp.cmo : utils/warnings.cmi typing/types.cmi \
+ typing/typedtree.cmi utils/tbl.cmi parsing/syntaxerr.cmi \
+ typing/printtyp.cmi typing/predef.cmi typing/path.cmi \
+ parsing/parsetree.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi typing/env.cmi typing/ctype.cmi utils/clflags.cmi \
+ typing/btype.cmi parsing/asttypes.cmi parsing/ast_mapper.cmi \
+ parsing/ast_helper.cmi typing/typetexp.cmi
+typing/typetexp.cmx : utils/warnings.cmx typing/types.cmx \
+ typing/typedtree.cmx utils/tbl.cmx parsing/syntaxerr.cmx \
+ typing/printtyp.cmx typing/predef.cmx typing/path.cmx \
+ parsing/parsetree.cmi utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx typing/env.cmx typing/ctype.cmx utils/clflags.cmx \
+ typing/btype.cmx parsing/asttypes.cmi parsing/ast_mapper.cmx \
+ parsing/ast_helper.cmx typing/typetexp.cmi
+typing/untypeast.cmo : typing/typedtree.cmi typing/path.cmi \
+ parsing/parsetree.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi typing/ident.cmi typing/env.cmi parsing/asttypes.cmi \
+ parsing/ast_helper.cmi typing/untypeast.cmi
+typing/untypeast.cmx : typing/typedtree.cmx typing/path.cmx \
+ parsing/parsetree.cmi utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx typing/ident.cmx typing/env.cmx parsing/asttypes.cmi \
+ parsing/ast_helper.cmx typing/untypeast.cmi
+bytecomp/bytegen.cmi : bytecomp/lambda.cmi bytecomp/instruct.cmi
+bytecomp/bytelibrarian.cmi :
+bytecomp/bytelink.cmi : bytecomp/symtable.cmi bytecomp/cmo_format.cmi
+bytecomp/bytepackager.cmi : typing/ident.cmi typing/env.cmi
+bytecomp/bytesections.cmi :
+bytecomp/cmo_format.cmi : bytecomp/lambda.cmi typing/ident.cmi
+bytecomp/dll.cmi :
+bytecomp/emitcode.cmi : bytecomp/instruct.cmi bytecomp/cmo_format.cmi
+bytecomp/instruct.cmi : typing/types.cmi typing/subst.cmi \
+ parsing/location.cmi bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi
+bytecomp/lambda.cmi : typing/types.cmi typing/primitive.cmi typing/path.cmi \
+ parsing/location.cmi typing/ident.cmi typing/env.cmi parsing/asttypes.cmi
+bytecomp/matching.cmi : typing/typedtree.cmi parsing/location.cmi \
+ bytecomp/lambda.cmi typing/ident.cmi
+bytecomp/meta.cmi : bytecomp/instruct.cmi
+bytecomp/printinstr.cmi : bytecomp/instruct.cmi
+bytecomp/printlambda.cmi : bytecomp/lambda.cmi
+bytecomp/runtimedef.cmi :
+bytecomp/simplif.cmi : bytecomp/lambda.cmi
+bytecomp/switch.cmi :
+bytecomp/symtable.cmi : utils/misc.cmi typing/ident.cmi \
+ bytecomp/cmo_format.cmi
+bytecomp/translclass.cmi : typing/typedtree.cmi parsing/location.cmi \
+ bytecomp/lambda.cmi typing/ident.cmi parsing/asttypes.cmi
+bytecomp/translcore.cmi : typing/types.cmi typing/typedtree.cmi \
+ typing/primitive.cmi typing/path.cmi parsing/location.cmi \
+ bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi parsing/asttypes.cmi
+bytecomp/translmod.cmi : typing/typedtree.cmi typing/primitive.cmi \
+ parsing/location.cmi bytecomp/lambda.cmi typing/ident.cmi
+bytecomp/translobj.cmi : bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi
+bytecomp/typeopt.cmi : typing/types.cmi typing/typedtree.cmi typing/path.cmi \
+ bytecomp/lambda.cmi typing/env.cmi
+bytecomp/bytegen.cmo : typing/types.cmi bytecomp/switch.cmi typing/subst.cmi \
+ typing/primitive.cmi utils/misc.cmi bytecomp/matching.cmi \
+ bytecomp/lambda.cmi bytecomp/instruct.cmi typing/ident.cmi \
+ utils/config.cmi parsing/asttypes.cmi bytecomp/bytegen.cmi
+bytecomp/bytegen.cmx : typing/types.cmx bytecomp/switch.cmx typing/subst.cmx \
+ typing/primitive.cmx utils/misc.cmx bytecomp/matching.cmx \
+ bytecomp/lambda.cmx bytecomp/instruct.cmx typing/ident.cmx \
+ utils/config.cmx parsing/asttypes.cmi bytecomp/bytegen.cmi
+bytecomp/bytelibrarian.cmo : utils/misc.cmi parsing/location.cmi \
+ utils/config.cmi bytecomp/cmo_format.cmi utils/clflags.cmi \
+ bytecomp/bytelink.cmi bytecomp/bytelibrarian.cmi
+bytecomp/bytelibrarian.cmx : utils/misc.cmx parsing/location.cmx \
+ utils/config.cmx bytecomp/cmo_format.cmi utils/clflags.cmx \
+ bytecomp/bytelink.cmx bytecomp/bytelibrarian.cmi
+bytecomp/bytelink.cmo : utils/warnings.cmi bytecomp/symtable.cmi \
+ bytecomp/opcodes.cmo utils/misc.cmi parsing/location.cmi \
+ bytecomp/instruct.cmi typing/ident.cmi bytecomp/dll.cmi \
+ utils/consistbl.cmi utils/config.cmi bytecomp/cmo_format.cmi \
+ utils/clflags.cmi utils/ccomp.cmi bytecomp/bytesections.cmi \
+ bytecomp/bytelink.cmi
+bytecomp/bytelink.cmx : utils/warnings.cmx bytecomp/symtable.cmx \
+ bytecomp/opcodes.cmx utils/misc.cmx parsing/location.cmx \
+ bytecomp/instruct.cmx typing/ident.cmx bytecomp/dll.cmx \
+ utils/consistbl.cmx utils/config.cmx bytecomp/cmo_format.cmi \
+ utils/clflags.cmx utils/ccomp.cmx bytecomp/bytesections.cmx \
+ bytecomp/bytelink.cmi
+bytecomp/bytepackager.cmo : typing/typemod.cmi bytecomp/translmod.cmi \
+ typing/subst.cmi bytecomp/printlambda.cmi typing/path.cmi utils/misc.cmi \
+ parsing/location.cmi bytecomp/instruct.cmi typing/ident.cmi \
+ typing/env.cmi bytecomp/emitcode.cmi utils/config.cmi \
+ bytecomp/cmo_format.cmi utils/clflags.cmi bytecomp/bytelink.cmi \
+ bytecomp/bytegen.cmi bytecomp/bytepackager.cmi
+bytecomp/bytepackager.cmx : typing/typemod.cmx bytecomp/translmod.cmx \
+ typing/subst.cmx bytecomp/printlambda.cmx typing/path.cmx utils/misc.cmx \
+ parsing/location.cmx bytecomp/instruct.cmx typing/ident.cmx \
+ typing/env.cmx bytecomp/emitcode.cmx utils/config.cmx \
+ bytecomp/cmo_format.cmi utils/clflags.cmx bytecomp/bytelink.cmx \
+ bytecomp/bytegen.cmx bytecomp/bytepackager.cmi
+bytecomp/bytesections.cmo : utils/config.cmi bytecomp/bytesections.cmi
+bytecomp/bytesections.cmx : utils/config.cmx bytecomp/bytesections.cmi
+bytecomp/dll.cmo : utils/misc.cmi utils/config.cmi bytecomp/dll.cmi
+bytecomp/dll.cmx : utils/misc.cmx utils/config.cmx bytecomp/dll.cmi
+bytecomp/emitcode.cmo : bytecomp/translmod.cmi typing/primitive.cmi \
+ bytecomp/opcodes.cmo utils/misc.cmi bytecomp/meta.cmi \
+ parsing/location.cmi bytecomp/lambda.cmi bytecomp/instruct.cmi \
+ typing/env.cmi utils/config.cmi bytecomp/cmo_format.cmi utils/clflags.cmi \
+ typing/btype.cmi parsing/asttypes.cmi bytecomp/emitcode.cmi
+bytecomp/emitcode.cmx : bytecomp/translmod.cmx typing/primitive.cmx \
+ bytecomp/opcodes.cmx utils/misc.cmx bytecomp/meta.cmx \
+ parsing/location.cmx bytecomp/lambda.cmx bytecomp/instruct.cmx \
+ typing/env.cmx utils/config.cmx bytecomp/cmo_format.cmi utils/clflags.cmx \
+ typing/btype.cmx parsing/asttypes.cmi bytecomp/emitcode.cmi
+bytecomp/instruct.cmo : typing/types.cmi typing/subst.cmi \
+ parsing/location.cmi bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi \
+ bytecomp/instruct.cmi
+bytecomp/instruct.cmx : typing/types.cmx typing/subst.cmx \
+ parsing/location.cmx bytecomp/lambda.cmx typing/ident.cmx typing/env.cmx \
+ bytecomp/instruct.cmi
+bytecomp/lambda.cmo : typing/types.cmi typing/primitive.cmi typing/path.cmi \
+ utils/misc.cmi parsing/location.cmi typing/ident.cmi typing/env.cmi \
+ parsing/asttypes.cmi bytecomp/lambda.cmi
+bytecomp/lambda.cmx : typing/types.cmx typing/primitive.cmx typing/path.cmx \
+ utils/misc.cmx parsing/location.cmx typing/ident.cmx typing/env.cmx \
+ parsing/asttypes.cmi bytecomp/lambda.cmi
+bytecomp/matching.cmo : typing/types.cmi bytecomp/typeopt.cmi \
+ typing/typedtree.cmi bytecomp/switch.cmi bytecomp/printlambda.cmi \
+ typing/primitive.cmi typing/predef.cmi typing/path.cmi \
+ typing/parmatch.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi \
+ utils/clflags.cmi typing/btype.cmi parsing/asttypes.cmi \
+ bytecomp/matching.cmi
+bytecomp/matching.cmx : typing/types.cmx bytecomp/typeopt.cmx \
+ typing/typedtree.cmx bytecomp/switch.cmx bytecomp/printlambda.cmx \
+ typing/primitive.cmx typing/predef.cmx typing/path.cmx \
+ typing/parmatch.cmx utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx bytecomp/lambda.cmx typing/ident.cmx typing/env.cmx \
+ utils/clflags.cmx typing/btype.cmx parsing/asttypes.cmi \
+ bytecomp/matching.cmi
+bytecomp/meta.cmo : bytecomp/instruct.cmi bytecomp/meta.cmi
+bytecomp/meta.cmx : bytecomp/instruct.cmx bytecomp/meta.cmi
+bytecomp/opcodes.cmo :
+bytecomp/opcodes.cmx :
+bytecomp/printinstr.cmo : bytecomp/printlambda.cmi parsing/location.cmi \
+ bytecomp/lambda.cmi bytecomp/instruct.cmi typing/ident.cmi \
+ bytecomp/printinstr.cmi
+bytecomp/printinstr.cmx : bytecomp/printlambda.cmx parsing/location.cmx \
+ bytecomp/lambda.cmx bytecomp/instruct.cmx typing/ident.cmx \
+ bytecomp/printinstr.cmi
+bytecomp/printlambda.cmo : typing/types.cmi typing/primitive.cmi \
+ parsing/location.cmi bytecomp/lambda.cmi typing/ident.cmi \
+ parsing/asttypes.cmi bytecomp/printlambda.cmi
+bytecomp/printlambda.cmx : typing/types.cmx typing/primitive.cmx \
+ parsing/location.cmx bytecomp/lambda.cmx typing/ident.cmx \
+ parsing/asttypes.cmi bytecomp/printlambda.cmi
+bytecomp/runtimedef.cmo : bytecomp/runtimedef.cmi
+bytecomp/runtimedef.cmx : bytecomp/runtimedef.cmi
+bytecomp/simplif.cmo : utils/warnings.cmi utils/tbl.cmi typing/stypes.cmi \
+ utils/misc.cmi parsing/location.cmi bytecomp/lambda.cmi typing/ident.cmi \
+ utils/clflags.cmi parsing/asttypes.cmi typing/annot.cmi \
+ bytecomp/simplif.cmi
+bytecomp/simplif.cmx : utils/warnings.cmx utils/tbl.cmx typing/stypes.cmx \
+ utils/misc.cmx parsing/location.cmx bytecomp/lambda.cmx typing/ident.cmx \
+ utils/clflags.cmx parsing/asttypes.cmi typing/annot.cmi \
+ bytecomp/simplif.cmi
+bytecomp/switch.cmo : bytecomp/switch.cmi
+bytecomp/switch.cmx : bytecomp/switch.cmi
+bytecomp/symtable.cmo : utils/tbl.cmi bytecomp/runtimedef.cmi \
+ typing/predef.cmi utils/misc.cmi bytecomp/meta.cmi parsing/location.cmi \
+ bytecomp/lambda.cmi typing/ident.cmi bytecomp/dll.cmi utils/config.cmi \
+ bytecomp/cmo_format.cmi utils/clflags.cmi bytecomp/bytesections.cmi \
+ parsing/asttypes.cmi bytecomp/symtable.cmi
+bytecomp/symtable.cmx : utils/tbl.cmx bytecomp/runtimedef.cmx \
+ typing/predef.cmx utils/misc.cmx bytecomp/meta.cmx parsing/location.cmx \
+ bytecomp/lambda.cmx typing/ident.cmx bytecomp/dll.cmx utils/config.cmx \
+ bytecomp/cmo_format.cmi utils/clflags.cmx bytecomp/bytesections.cmx \
+ parsing/asttypes.cmi bytecomp/symtable.cmi
+bytecomp/translclass.cmo : typing/types.cmi bytecomp/typeopt.cmi \
+ typing/typedtree.cmi bytecomp/translobj.cmi bytecomp/translcore.cmi \
+ typing/path.cmi bytecomp/matching.cmi parsing/location.cmi \
+ bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi utils/clflags.cmi \
+ typing/btype.cmi parsing/asttypes.cmi bytecomp/translclass.cmi
+bytecomp/translclass.cmx : typing/types.cmx bytecomp/typeopt.cmx \
+ typing/typedtree.cmx bytecomp/translobj.cmx bytecomp/translcore.cmx \
+ typing/path.cmx bytecomp/matching.cmx parsing/location.cmx \
+ bytecomp/lambda.cmx typing/ident.cmx typing/env.cmx utils/clflags.cmx \
+ typing/btype.cmx parsing/asttypes.cmi bytecomp/translclass.cmi
+bytecomp/translcore.cmo : typing/types.cmi bytecomp/typeopt.cmi \
+ typing/typedtree.cmi bytecomp/translobj.cmi typing/primitive.cmi \
+ typing/predef.cmi typing/path.cmi typing/parmatch.cmi utils/misc.cmi \
+ bytecomp/matching.cmi parsing/longident.cmi parsing/location.cmi \
+ bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi utils/config.cmi \
+ utils/clflags.cmi typing/btype.cmi parsing/asttypes.cmi \
+ bytecomp/translcore.cmi
+bytecomp/translcore.cmx : typing/types.cmx bytecomp/typeopt.cmx \
+ typing/typedtree.cmx bytecomp/translobj.cmx typing/primitive.cmx \
+ typing/predef.cmx typing/path.cmx typing/parmatch.cmx utils/misc.cmx \
+ bytecomp/matching.cmx parsing/longident.cmx parsing/location.cmx \
+ bytecomp/lambda.cmx typing/ident.cmx typing/env.cmx utils/config.cmx \
+ utils/clflags.cmx typing/btype.cmx parsing/asttypes.cmi \
+ bytecomp/translcore.cmi
+bytecomp/translmod.cmo : typing/types.cmi typing/typedtree.cmi \
+ bytecomp/translobj.cmi bytecomp/translcore.cmi bytecomp/translclass.cmi \
+ typing/printtyp.cmi typing/primitive.cmi typing/predef.cmi \
+ typing/path.cmi typing/mtype.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi \
+ typing/ctype.cmi parsing/asttypes.cmi bytecomp/translmod.cmi
+bytecomp/translmod.cmx : typing/types.cmx typing/typedtree.cmx \
+ bytecomp/translobj.cmx bytecomp/translcore.cmx bytecomp/translclass.cmx \
+ typing/printtyp.cmx typing/primitive.cmx typing/predef.cmx \
+ typing/path.cmx typing/mtype.cmx utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx bytecomp/lambda.cmx typing/ident.cmx typing/env.cmx \
+ typing/ctype.cmx parsing/asttypes.cmi bytecomp/translmod.cmi
+bytecomp/translobj.cmo : typing/primitive.cmi utils/misc.cmi \
+ parsing/longident.cmi bytecomp/lambda.cmi typing/ident.cmi typing/env.cmi \
+ utils/clflags.cmi typing/btype.cmi parsing/asttypes.cmi \
+ bytecomp/translobj.cmi
+bytecomp/translobj.cmx : typing/primitive.cmx utils/misc.cmx \
+ parsing/longident.cmx bytecomp/lambda.cmx typing/ident.cmx typing/env.cmx \
+ utils/clflags.cmx typing/btype.cmx parsing/asttypes.cmi \
+ bytecomp/translobj.cmi
+bytecomp/typeopt.cmo : typing/types.cmi typing/typedtree.cmi \
+ typing/predef.cmi typing/path.cmi bytecomp/lambda.cmi typing/ident.cmi \
+ typing/env.cmi typing/ctype.cmi bytecomp/typeopt.cmi
+bytecomp/typeopt.cmx : typing/types.cmx typing/typedtree.cmx \
+ typing/predef.cmx typing/path.cmx bytecomp/lambda.cmx typing/ident.cmx \
+ typing/env.cmx typing/ctype.cmx bytecomp/typeopt.cmi
+asmcomp/asmgen.cmi : bytecomp/lambda.cmi asmcomp/cmm.cmi
+asmcomp/asmlibrarian.cmi :
+asmcomp/asmlink.cmi : asmcomp/cmx_format.cmi
+asmcomp/asmpackager.cmi : typing/env.cmi
+asmcomp/branch_relaxation.cmi : asmcomp/linearize.cmi \
+ asmcomp/branch_relaxation_intf.cmo
+asmcomp/clambda.cmi : bytecomp/lambda.cmi typing/ident.cmi \
+ asmcomp/debuginfo.cmi parsing/asttypes.cmi
+asmcomp/closure.cmi : bytecomp/lambda.cmi asmcomp/clambda.cmi
+asmcomp/cmmgen.cmi : asmcomp/cmx_format.cmi asmcomp/cmm.cmi \
+ asmcomp/clambda.cmi
+asmcomp/cmm.cmi : bytecomp/lambda.cmi typing/ident.cmi asmcomp/debuginfo.cmi
+asmcomp/cmx_format.cmi : asmcomp/clambda.cmi
+asmcomp/codegen.cmi : asmcomp/cmm.cmi
+asmcomp/coloring.cmi :
+asmcomp/comballoc.cmi : asmcomp/mach.cmi
+asmcomp/compilenv.cmi : typing/ident.cmi asmcomp/cmx_format.cmi \
+ asmcomp/clambda.cmi
+asmcomp/CSEgen.cmi : asmcomp/mach.cmi
+asmcomp/deadcode.cmi : asmcomp/mach.cmi
+asmcomp/debuginfo.cmi : parsing/location.cmi bytecomp/lambda.cmi
+asmcomp/emitaux.cmi : asmcomp/debuginfo.cmi
+asmcomp/emit.cmi : asmcomp/linearize.cmi asmcomp/cmm.cmi
+asmcomp/interf.cmi : asmcomp/mach.cmi
+asmcomp/linearize.cmi : asmcomp/reg.cmi asmcomp/mach.cmi bytecomp/lambda.cmi \
+ asmcomp/debuginfo.cmi
+asmcomp/liveness.cmi : asmcomp/mach.cmi
+asmcomp/mach.cmi : asmcomp/reg.cmi bytecomp/lambda.cmi asmcomp/debuginfo.cmi \
+ asmcomp/cmm.cmi asmcomp/arch.cmo
+asmcomp/printclambda.cmi : asmcomp/clambda.cmi
+asmcomp/printcmm.cmi : asmcomp/cmm.cmi
+asmcomp/printlinear.cmi : asmcomp/linearize.cmi
+asmcomp/printmach.cmi : asmcomp/reg.cmi asmcomp/mach.cmi
+asmcomp/proc.cmi : asmcomp/reg.cmi asmcomp/mach.cmi
+asmcomp/reg.cmi : typing/ident.cmi asmcomp/cmm.cmi
+asmcomp/reloadgen.cmi : asmcomp/reg.cmi asmcomp/mach.cmi
+asmcomp/reload.cmi : asmcomp/mach.cmi
+asmcomp/schedgen.cmi : asmcomp/mach.cmi asmcomp/linearize.cmi
+asmcomp/scheduling.cmi : asmcomp/linearize.cmi
+asmcomp/selectgen.cmi : utils/tbl.cmi asmcomp/reg.cmi asmcomp/mach.cmi \
+ typing/ident.cmi asmcomp/debuginfo.cmi asmcomp/cmm.cmi asmcomp/arch.cmo
+asmcomp/selection.cmi : asmcomp/mach.cmi asmcomp/cmm.cmi
+asmcomp/spill.cmi : asmcomp/mach.cmi
+asmcomp/split.cmi : asmcomp/mach.cmi
+asmcomp/strmatch.cmi : asmcomp/cmm.cmi
+asmcomp/x86_ast.cmi :
+asmcomp/x86_dsl.cmi : asmcomp/x86_ast.cmi
+asmcomp/x86_gas.cmi : asmcomp/x86_ast.cmi
+asmcomp/x86_masm.cmi : asmcomp/x86_ast.cmi
+asmcomp/x86_proc.cmi : asmcomp/x86_ast.cmi
+asmcomp/arch.cmo : utils/clflags.cmi
+asmcomp/arch.cmx : utils/clflags.cmx
+asmcomp/asmgen.cmo : bytecomp/translmod.cmi asmcomp/split.cmi \
+ asmcomp/spill.cmi asmcomp/selection.cmi asmcomp/scheduling.cmi \
+ asmcomp/reload.cmi asmcomp/reg.cmi asmcomp/proc.cmi asmcomp/printmach.cmi \
+ asmcomp/printlinear.cmi asmcomp/printcmm.cmi asmcomp/printclambda.cmi \
+ typing/primitive.cmi utils/misc.cmi asmcomp/mach.cmi parsing/location.cmi \
+ asmcomp/liveness.cmi asmcomp/linearize.cmi asmcomp/interf.cmi \
+ asmcomp/emitaux.cmi asmcomp/emit.cmi asmcomp/deadcode.cmi \
+ utils/config.cmi asmcomp/compilenv.cmi asmcomp/comballoc.cmi \
+ asmcomp/coloring.cmi asmcomp/cmmgen.cmi asmcomp/cmm.cmi \
+ asmcomp/closure.cmi utils/clflags.cmi asmcomp/CSE.cmo asmcomp/asmgen.cmi
+asmcomp/asmgen.cmx : bytecomp/translmod.cmx asmcomp/split.cmx \
+ asmcomp/spill.cmx asmcomp/selection.cmx asmcomp/scheduling.cmx \
+ asmcomp/reload.cmx asmcomp/reg.cmx asmcomp/proc.cmx asmcomp/printmach.cmx \
+ asmcomp/printlinear.cmx asmcomp/printcmm.cmx asmcomp/printclambda.cmx \
+ typing/primitive.cmx utils/misc.cmx asmcomp/mach.cmx parsing/location.cmx \
+ asmcomp/liveness.cmx asmcomp/linearize.cmx asmcomp/interf.cmx \
+ asmcomp/emitaux.cmx asmcomp/emit.cmx asmcomp/deadcode.cmx \
+ utils/config.cmx asmcomp/compilenv.cmx asmcomp/comballoc.cmx \
+ asmcomp/coloring.cmx asmcomp/cmmgen.cmx asmcomp/cmm.cmx \
+ asmcomp/closure.cmx utils/clflags.cmx asmcomp/CSE.cmx asmcomp/asmgen.cmi
+asmcomp/asmlibrarian.cmo : utils/misc.cmi parsing/location.cmi \
+ utils/config.cmi asmcomp/compilenv.cmi asmcomp/cmx_format.cmi \
+ utils/clflags.cmi asmcomp/clambda.cmi utils/ccomp.cmi asmcomp/asmlink.cmi \
+ asmcomp/asmlibrarian.cmi
+asmcomp/asmlibrarian.cmx : utils/misc.cmx parsing/location.cmx \
+ utils/config.cmx asmcomp/compilenv.cmx asmcomp/cmx_format.cmi \
+ utils/clflags.cmx asmcomp/clambda.cmx utils/ccomp.cmx asmcomp/asmlink.cmx \
+ asmcomp/asmlibrarian.cmi
+asmcomp/asmlink.cmo : bytecomp/runtimedef.cmi utils/misc.cmi \
+ parsing/location.cmi asmcomp/emitaux.cmi asmcomp/emit.cmi \
+ utils/consistbl.cmi utils/config.cmi asmcomp/compilenv.cmi \
+ asmcomp/cmx_format.cmi asmcomp/cmmgen.cmi utils/clflags.cmi \
+ utils/ccomp.cmi asmcomp/asmgen.cmi asmcomp/asmlink.cmi
+asmcomp/asmlink.cmx : bytecomp/runtimedef.cmx utils/misc.cmx \
+ parsing/location.cmx asmcomp/emitaux.cmx asmcomp/emit.cmx \
+ utils/consistbl.cmx utils/config.cmx asmcomp/compilenv.cmx \
+ asmcomp/cmx_format.cmi asmcomp/cmmgen.cmx utils/clflags.cmx \
+ utils/ccomp.cmx asmcomp/asmgen.cmx asmcomp/asmlink.cmi
+asmcomp/asmpackager.cmo : typing/typemod.cmi bytecomp/translmod.cmi \
+ utils/misc.cmi parsing/location.cmi typing/ident.cmi typing/env.cmi \
+ utils/config.cmi asmcomp/compilenv.cmi asmcomp/cmx_format.cmi \
+ utils/clflags.cmi utils/ccomp.cmi asmcomp/asmlink.cmi asmcomp/asmgen.cmi \
+ asmcomp/asmpackager.cmi
+asmcomp/asmpackager.cmx : typing/typemod.cmx bytecomp/translmod.cmx \
+ utils/misc.cmx parsing/location.cmx typing/ident.cmx typing/env.cmx \
+ utils/config.cmx asmcomp/compilenv.cmx asmcomp/cmx_format.cmi \
+ utils/clflags.cmx utils/ccomp.cmx asmcomp/asmlink.cmx asmcomp/asmgen.cmx \
+ asmcomp/asmpackager.cmi
+asmcomp/branch_relaxation_intf.cmo : asmcomp/linearize.cmi asmcomp/arch.cmo
+asmcomp/branch_relaxation_intf.cmx : asmcomp/linearize.cmx asmcomp/arch.cmx
+asmcomp/branch_relaxation.cmo : utils/misc.cmi asmcomp/mach.cmi \
+ asmcomp/linearize.cmi asmcomp/cmm.cmi asmcomp/branch_relaxation_intf.cmo \
+ asmcomp/branch_relaxation.cmi
+asmcomp/branch_relaxation.cmx : utils/misc.cmx asmcomp/mach.cmx \
+ asmcomp/linearize.cmx asmcomp/cmm.cmx asmcomp/branch_relaxation_intf.cmx \
+ asmcomp/branch_relaxation.cmi
+asmcomp/clambda.cmo : bytecomp/lambda.cmi typing/ident.cmi \
+ asmcomp/debuginfo.cmi parsing/asttypes.cmi asmcomp/clambda.cmi
+asmcomp/clambda.cmx : bytecomp/lambda.cmx typing/ident.cmx \
+ asmcomp/debuginfo.cmx parsing/asttypes.cmi asmcomp/clambda.cmi
+asmcomp/closure.cmo : utils/tbl.cmi bytecomp/switch.cmi typing/primitive.cmi \
+ utils/misc.cmi bytecomp/lambda.cmi typing/ident.cmi asmcomp/debuginfo.cmi \
+ asmcomp/compilenv.cmi utils/clflags.cmi asmcomp/clambda.cmi \
+ parsing/asttypes.cmi asmcomp/arch.cmo asmcomp/closure.cmi
+asmcomp/closure.cmx : utils/tbl.cmx bytecomp/switch.cmx typing/primitive.cmx \
+ utils/misc.cmx bytecomp/lambda.cmx typing/ident.cmx asmcomp/debuginfo.cmx \
+ asmcomp/compilenv.cmx utils/clflags.cmx asmcomp/clambda.cmx \
+ parsing/asttypes.cmi asmcomp/arch.cmx asmcomp/closure.cmi
+asmcomp/cmmgen.cmo : typing/types.cmi bytecomp/switch.cmi \
+ asmcomp/strmatch.cmi asmcomp/proc.cmi typing/primitive.cmi utils/misc.cmi \
+ bytecomp/lambda.cmi typing/ident.cmi asmcomp/debuginfo.cmi \
+ utils/config.cmi asmcomp/compilenv.cmi asmcomp/cmx_format.cmi \
+ asmcomp/cmm.cmi utils/clflags.cmi asmcomp/clambda.cmi \
+ parsing/asttypes.cmi asmcomp/arch.cmo asmcomp/cmmgen.cmi
+asmcomp/cmmgen.cmx : typing/types.cmx bytecomp/switch.cmx \
+ asmcomp/strmatch.cmx asmcomp/proc.cmx typing/primitive.cmx utils/misc.cmx \
+ bytecomp/lambda.cmx typing/ident.cmx asmcomp/debuginfo.cmx \
+ utils/config.cmx asmcomp/compilenv.cmx asmcomp/cmx_format.cmi \
+ asmcomp/cmm.cmx utils/clflags.cmx asmcomp/clambda.cmx \
+ parsing/asttypes.cmi asmcomp/arch.cmx asmcomp/cmmgen.cmi
+asmcomp/cmm.cmo : bytecomp/lambda.cmi typing/ident.cmi asmcomp/debuginfo.cmi \
+ asmcomp/arch.cmo asmcomp/cmm.cmi
+asmcomp/cmm.cmx : bytecomp/lambda.cmx typing/ident.cmx asmcomp/debuginfo.cmx \
+ asmcomp/arch.cmx asmcomp/cmm.cmi
+asmcomp/codegen.cmo : asmcomp/split.cmi asmcomp/spill.cmi asmcomp/reload.cmi \
+ asmcomp/reg.cmi asmcomp/printmach.cmi asmcomp/printlinear.cmi \
+ asmcomp/printcmm.cmi asmcomp/liveness.cmi asmcomp/linearize.cmi \
+ asmcomp/interf.cmi asmcomp/emit.cmi asmcomp/coloring.cmi asmcomp/cmm.cmi \
+ asmcomp/codegen.cmi
+asmcomp/codegen.cmx : asmcomp/split.cmx asmcomp/spill.cmx asmcomp/reload.cmx \
+ asmcomp/reg.cmx asmcomp/printmach.cmx asmcomp/printlinear.cmx \
+ asmcomp/printcmm.cmx asmcomp/liveness.cmx asmcomp/linearize.cmx \
+ asmcomp/interf.cmx asmcomp/emit.cmx asmcomp/coloring.cmx asmcomp/cmm.cmx \
+ asmcomp/codegen.cmi
+asmcomp/coloring.cmo : asmcomp/reg.cmi asmcomp/proc.cmi asmcomp/coloring.cmi
+asmcomp/coloring.cmx : asmcomp/reg.cmx asmcomp/proc.cmx asmcomp/coloring.cmi
+asmcomp/comballoc.cmo : asmcomp/reg.cmi asmcomp/mach.cmi utils/config.cmi \
+ asmcomp/arch.cmo asmcomp/comballoc.cmi
+asmcomp/comballoc.cmx : asmcomp/reg.cmx asmcomp/mach.cmx utils/config.cmx \
+ asmcomp/arch.cmx asmcomp/comballoc.cmi
+asmcomp/compilenv.cmo : utils/misc.cmi parsing/location.cmi typing/ident.cmi \
+ typing/env.cmi utils/config.cmi asmcomp/cmx_format.cmi \
+ asmcomp/clambda.cmi asmcomp/compilenv.cmi
+asmcomp/compilenv.cmx : utils/misc.cmx parsing/location.cmx typing/ident.cmx \
+ typing/env.cmx utils/config.cmx asmcomp/cmx_format.cmi \
+ asmcomp/clambda.cmx asmcomp/compilenv.cmi
+asmcomp/CSEgen.cmo : asmcomp/reg.cmi asmcomp/proc.cmi asmcomp/mach.cmi \
+ asmcomp/cmm.cmi asmcomp/CSEgen.cmi
+asmcomp/CSEgen.cmx : asmcomp/reg.cmx asmcomp/proc.cmx asmcomp/mach.cmx \
+ asmcomp/cmm.cmx asmcomp/CSEgen.cmi
+asmcomp/CSE.cmo : asmcomp/mach.cmi asmcomp/CSEgen.cmi asmcomp/arch.cmo
+asmcomp/CSE.cmx : asmcomp/mach.cmx asmcomp/CSEgen.cmx asmcomp/arch.cmx
+asmcomp/deadcode.cmo : asmcomp/reg.cmi asmcomp/proc.cmi asmcomp/mach.cmi \
+ asmcomp/deadcode.cmi
+asmcomp/deadcode.cmx : asmcomp/reg.cmx asmcomp/proc.cmx asmcomp/mach.cmx \
+ asmcomp/deadcode.cmi
+asmcomp/debuginfo.cmo : parsing/location.cmi bytecomp/lambda.cmi \
+ asmcomp/debuginfo.cmi
+asmcomp/debuginfo.cmx : parsing/location.cmx bytecomp/lambda.cmx \
+ asmcomp/debuginfo.cmi
+asmcomp/emitaux.cmo : asmcomp/linearize.cmi asmcomp/debuginfo.cmi \
+ utils/config.cmi utils/clflags.cmi asmcomp/arch.cmo asmcomp/emitaux.cmi
+asmcomp/emitaux.cmx : asmcomp/linearize.cmx asmcomp/debuginfo.cmx \
+ utils/config.cmx utils/clflags.cmx asmcomp/arch.cmx asmcomp/emitaux.cmi
+asmcomp/emit.cmo : asmcomp/x86_proc.cmi asmcomp/x86_masm.cmi \
+ asmcomp/x86_gas.cmi asmcomp/x86_dsl.cmi asmcomp/x86_ast.cmi \
+ asmcomp/reg.cmi asmcomp/proc.cmi utils/misc.cmi asmcomp/mach.cmi \
+ asmcomp/linearize.cmi bytecomp/lambda.cmi asmcomp/emitaux.cmi \
+ asmcomp/debuginfo.cmi utils/config.cmi asmcomp/compilenv.cmi \
+ asmcomp/cmm.cmi utils/clflags.cmi asmcomp/branch_relaxation.cmi \
+ asmcomp/arch.cmo asmcomp/emit.cmi
+asmcomp/emit.cmx : asmcomp/x86_proc.cmx asmcomp/x86_masm.cmx \
+ asmcomp/x86_gas.cmx asmcomp/x86_dsl.cmx asmcomp/x86_ast.cmi \
+ asmcomp/reg.cmx asmcomp/proc.cmx utils/misc.cmx asmcomp/mach.cmx \
+ asmcomp/linearize.cmx bytecomp/lambda.cmx asmcomp/emitaux.cmx \
+ asmcomp/debuginfo.cmx utils/config.cmx asmcomp/compilenv.cmx \
+ asmcomp/cmm.cmx utils/clflags.cmx asmcomp/branch_relaxation.cmx \
+ asmcomp/arch.cmx asmcomp/emit.cmi
+asmcomp/interf.cmo : asmcomp/reg.cmi asmcomp/proc.cmi asmcomp/mach.cmi \
+ asmcomp/interf.cmi
+asmcomp/interf.cmx : asmcomp/reg.cmx asmcomp/proc.cmx asmcomp/mach.cmx \
+ asmcomp/interf.cmi
+asmcomp/linearize.cmo : asmcomp/reg.cmi asmcomp/proc.cmi utils/misc.cmi \
+ asmcomp/mach.cmi bytecomp/lambda.cmi asmcomp/debuginfo.cmi \
+ asmcomp/cmm.cmi asmcomp/linearize.cmi
+asmcomp/linearize.cmx : asmcomp/reg.cmx asmcomp/proc.cmx utils/misc.cmx \
+ asmcomp/mach.cmx bytecomp/lambda.cmx asmcomp/debuginfo.cmx \
+ asmcomp/cmm.cmx asmcomp/linearize.cmi
+asmcomp/liveness.cmo : asmcomp/reg.cmi asmcomp/proc.cmi \
+ asmcomp/printmach.cmi utils/misc.cmi asmcomp/mach.cmi \
+ asmcomp/liveness.cmi
+asmcomp/liveness.cmx : asmcomp/reg.cmx asmcomp/proc.cmx \
+ asmcomp/printmach.cmx utils/misc.cmx asmcomp/mach.cmx \
+ asmcomp/liveness.cmi
+asmcomp/mach.cmo : asmcomp/reg.cmi bytecomp/lambda.cmi asmcomp/debuginfo.cmi \
+ asmcomp/cmm.cmi asmcomp/arch.cmo asmcomp/mach.cmi
+asmcomp/mach.cmx : asmcomp/reg.cmx bytecomp/lambda.cmx asmcomp/debuginfo.cmx \
+ asmcomp/cmm.cmx asmcomp/arch.cmx asmcomp/mach.cmi
+asmcomp/printclambda.cmo : bytecomp/printlambda.cmi bytecomp/lambda.cmi \
+ typing/ident.cmi asmcomp/clambda.cmi parsing/asttypes.cmi \
+ asmcomp/printclambda.cmi
+asmcomp/printclambda.cmx : bytecomp/printlambda.cmx bytecomp/lambda.cmx \
+ typing/ident.cmx asmcomp/clambda.cmx parsing/asttypes.cmi \
+ asmcomp/printclambda.cmi
+asmcomp/printcmm.cmo : bytecomp/lambda.cmi typing/ident.cmi \
+ asmcomp/debuginfo.cmi asmcomp/cmm.cmi asmcomp/printcmm.cmi
+asmcomp/printcmm.cmx : bytecomp/lambda.cmx typing/ident.cmx \
+ asmcomp/debuginfo.cmx asmcomp/cmm.cmx asmcomp/printcmm.cmi
+asmcomp/printlinear.cmo : asmcomp/printmach.cmi asmcomp/mach.cmi \
+ asmcomp/linearize.cmi bytecomp/lambda.cmi asmcomp/debuginfo.cmi \
+ asmcomp/printlinear.cmi
+asmcomp/printlinear.cmx : asmcomp/printmach.cmx asmcomp/mach.cmx \
+ asmcomp/linearize.cmx bytecomp/lambda.cmx asmcomp/debuginfo.cmx \
+ asmcomp/printlinear.cmi
+asmcomp/printmach.cmo : asmcomp/reg.cmi asmcomp/proc.cmi \
+ asmcomp/printcmm.cmi asmcomp/mach.cmi bytecomp/lambda.cmi \
+ asmcomp/debuginfo.cmi asmcomp/cmm.cmi asmcomp/arch.cmo \
+ asmcomp/printmach.cmi
+asmcomp/printmach.cmx : asmcomp/reg.cmx asmcomp/proc.cmx \
+ asmcomp/printcmm.cmx asmcomp/mach.cmx bytecomp/lambda.cmx \
+ asmcomp/debuginfo.cmx asmcomp/cmm.cmx asmcomp/arch.cmx \
+ asmcomp/printmach.cmi
+asmcomp/proc.cmo : asmcomp/x86_proc.cmi asmcomp/reg.cmi utils/misc.cmi \
+ asmcomp/mach.cmi utils/config.cmi asmcomp/cmm.cmi asmcomp/arch.cmo \
+ asmcomp/proc.cmi
+asmcomp/proc.cmx : asmcomp/x86_proc.cmx asmcomp/reg.cmx utils/misc.cmx \
+ asmcomp/mach.cmx utils/config.cmx asmcomp/cmm.cmx asmcomp/arch.cmx \
+ asmcomp/proc.cmi
+asmcomp/reg.cmo : typing/ident.cmi asmcomp/cmm.cmi asmcomp/reg.cmi
+asmcomp/reg.cmx : typing/ident.cmx asmcomp/cmm.cmx asmcomp/reg.cmi
+asmcomp/reloadgen.cmo : asmcomp/reg.cmi utils/misc.cmi asmcomp/mach.cmi \
+ asmcomp/reloadgen.cmi
+asmcomp/reloadgen.cmx : asmcomp/reg.cmx utils/misc.cmx asmcomp/mach.cmx \
+ asmcomp/reloadgen.cmi
+asmcomp/reload.cmo : asmcomp/reloadgen.cmi asmcomp/reg.cmi asmcomp/mach.cmi \
+ asmcomp/cmm.cmi utils/clflags.cmi asmcomp/reload.cmi
+asmcomp/reload.cmx : asmcomp/reloadgen.cmx asmcomp/reg.cmx asmcomp/mach.cmx \
+ asmcomp/cmm.cmx utils/clflags.cmx asmcomp/reload.cmi
+asmcomp/schedgen.cmo : asmcomp/reg.cmi asmcomp/proc.cmi asmcomp/mach.cmi \
+ asmcomp/linearize.cmi asmcomp/cmm.cmi asmcomp/arch.cmo \
+ asmcomp/schedgen.cmi
+asmcomp/schedgen.cmx : asmcomp/reg.cmx asmcomp/proc.cmx asmcomp/mach.cmx \
+ asmcomp/linearize.cmx asmcomp/cmm.cmx asmcomp/arch.cmx \
+ asmcomp/schedgen.cmi
+asmcomp/scheduling.cmo : asmcomp/schedgen.cmi asmcomp/scheduling.cmi
+asmcomp/scheduling.cmx : asmcomp/schedgen.cmx asmcomp/scheduling.cmi
+asmcomp/selectgen.cmo : utils/tbl.cmi bytecomp/simplif.cmi asmcomp/reg.cmi \
+ asmcomp/proc.cmi utils/misc.cmi asmcomp/mach.cmi bytecomp/lambda.cmi \
+ typing/ident.cmi asmcomp/debuginfo.cmi asmcomp/cmm.cmi utils/clflags.cmi \
+ asmcomp/arch.cmo asmcomp/selectgen.cmi
+asmcomp/selectgen.cmx : utils/tbl.cmx bytecomp/simplif.cmx asmcomp/reg.cmx \
+ asmcomp/proc.cmx utils/misc.cmx asmcomp/mach.cmx bytecomp/lambda.cmx \
+ typing/ident.cmx asmcomp/debuginfo.cmx asmcomp/cmm.cmx utils/clflags.cmx \
+ asmcomp/arch.cmx asmcomp/selectgen.cmi
+asmcomp/selection.cmo : asmcomp/selectgen.cmi asmcomp/proc.cmi \
+ asmcomp/mach.cmi asmcomp/cmm.cmi utils/clflags.cmi asmcomp/arch.cmo \
+ asmcomp/selection.cmi
+asmcomp/selection.cmx : asmcomp/selectgen.cmx asmcomp/proc.cmx \
+ asmcomp/mach.cmx asmcomp/cmm.cmx utils/clflags.cmx asmcomp/arch.cmx \
+ asmcomp/selection.cmi
+asmcomp/spill.cmo : asmcomp/reg.cmi asmcomp/proc.cmi utils/misc.cmi \
+ asmcomp/mach.cmi asmcomp/spill.cmi
+asmcomp/spill.cmx : asmcomp/reg.cmx asmcomp/proc.cmx utils/misc.cmx \
+ asmcomp/mach.cmx asmcomp/spill.cmi
+asmcomp/split.cmo : asmcomp/reg.cmi utils/misc.cmi asmcomp/mach.cmi \
+ asmcomp/split.cmi
+asmcomp/split.cmx : asmcomp/reg.cmx utils/misc.cmx asmcomp/mach.cmx \
+ asmcomp/split.cmi
+asmcomp/strmatch.cmo : bytecomp/lambda.cmi typing/ident.cmi asmcomp/cmm.cmi \
+ asmcomp/arch.cmo asmcomp/strmatch.cmi
+asmcomp/strmatch.cmx : bytecomp/lambda.cmx typing/ident.cmx asmcomp/cmm.cmx \
+ asmcomp/arch.cmx asmcomp/strmatch.cmi
+asmcomp/x86_dsl.cmo : asmcomp/x86_proc.cmi asmcomp/x86_ast.cmi \
+ asmcomp/x86_dsl.cmi
+asmcomp/x86_dsl.cmx : asmcomp/x86_proc.cmx asmcomp/x86_ast.cmi \
+ asmcomp/x86_dsl.cmi
+asmcomp/x86_gas.cmo : asmcomp/x86_proc.cmi asmcomp/x86_ast.cmi \
+ utils/misc.cmi asmcomp/x86_gas.cmi
+asmcomp/x86_gas.cmx : asmcomp/x86_proc.cmx asmcomp/x86_ast.cmi \
+ utils/misc.cmx asmcomp/x86_gas.cmi
+asmcomp/x86_masm.cmo : asmcomp/x86_proc.cmi asmcomp/x86_ast.cmi \
+ asmcomp/x86_masm.cmi
+asmcomp/x86_masm.cmx : asmcomp/x86_proc.cmx asmcomp/x86_ast.cmi \
+ asmcomp/x86_masm.cmi
+asmcomp/x86_proc.cmo : asmcomp/x86_ast.cmi utils/config.cmi \
+ utils/clflags.cmi utils/ccomp.cmi asmcomp/x86_proc.cmi
+asmcomp/x86_proc.cmx : asmcomp/x86_ast.cmi utils/config.cmx \
+ utils/clflags.cmx utils/ccomp.cmx asmcomp/x86_proc.cmi
+driver/compenv.cmi :
+driver/compile.cmi :
+driver/compmisc.cmi : typing/env.cmi
+driver/errors.cmi :
+driver/main_args.cmi :
+driver/main.cmi :
+driver/optcompile.cmi :
+driver/opterrors.cmi :
+driver/optmain.cmi :
+driver/pparse.cmi : parsing/parsetree.cmi
+driver/compenv.cmo : utils/warnings.cmi utils/misc.cmi parsing/location.cmi \
+ utils/config.cmi utils/clflags.cmi driver/compenv.cmi
+driver/compenv.cmx : utils/warnings.cmx utils/misc.cmx parsing/location.cmx \
+ utils/config.cmx utils/clflags.cmx driver/compenv.cmi
+driver/compile.cmo : utils/warnings.cmi typing/typemod.cmi \
+ typing/typedtree.cmi typing/typecore.cmi bytecomp/translmod.cmi \
+ typing/stypes.cmi bytecomp/simplif.cmi typing/printtyped.cmi \
+ typing/printtyp.cmi bytecomp/printlambda.cmi bytecomp/printinstr.cmi \
+ parsing/printast.cmi parsing/pprintast.cmi driver/pparse.cmi \
+ utils/misc.cmi parsing/location.cmi typing/includemod.cmi typing/env.cmi \
+ bytecomp/emitcode.cmi driver/compmisc.cmi driver/compenv.cmi \
+ utils/clflags.cmi utils/ccomp.cmi bytecomp/bytegen.cmi driver/compile.cmi
+driver/compile.cmx : utils/warnings.cmx typing/typemod.cmx \
+ typing/typedtree.cmx typing/typecore.cmx bytecomp/translmod.cmx \
+ typing/stypes.cmx bytecomp/simplif.cmx typing/printtyped.cmx \
+ typing/printtyp.cmx bytecomp/printlambda.cmx bytecomp/printinstr.cmx \
+ parsing/printast.cmx parsing/pprintast.cmx driver/pparse.cmx \
+ utils/misc.cmx parsing/location.cmx typing/includemod.cmx typing/env.cmx \
+ bytecomp/emitcode.cmx driver/compmisc.cmx driver/compenv.cmx \
+ utils/clflags.cmx utils/ccomp.cmx bytecomp/bytegen.cmx driver/compile.cmi
+driver/compmisc.cmo : typing/typemod.cmi utils/misc.cmi \
+ parsing/longident.cmi parsing/location.cmi typing/ident.cmi \
+ typing/env.cmi utils/config.cmi driver/compenv.cmi utils/clflags.cmi \
+ parsing/asttypes.cmi driver/compmisc.cmi
+driver/compmisc.cmx : typing/typemod.cmx utils/misc.cmx \
+ parsing/longident.cmx parsing/location.cmx typing/ident.cmx \
+ typing/env.cmx utils/config.cmx driver/compenv.cmx utils/clflags.cmx \
+ parsing/asttypes.cmi driver/compmisc.cmi
+driver/errors.cmo : parsing/location.cmi driver/errors.cmi
+driver/errors.cmx : parsing/location.cmx driver/errors.cmi
+driver/main_args.cmo : utils/warnings.cmi driver/main_args.cmi
+driver/main_args.cmx : utils/warnings.cmx driver/main_args.cmi
+driver/main.cmo : utils/warnings.cmi utils/misc.cmi driver/main_args.cmi \
+ parsing/location.cmi utils/config.cmi driver/compmisc.cmi \
+ driver/compile.cmi driver/compenv.cmi utils/clflags.cmi \
+ bytecomp/bytepackager.cmi bytecomp/bytelink.cmi \
+ bytecomp/bytelibrarian.cmi driver/main.cmi
+driver/main.cmx : utils/warnings.cmx utils/misc.cmx driver/main_args.cmx \
+ parsing/location.cmx utils/config.cmx driver/compmisc.cmx \
+ driver/compile.cmx driver/compenv.cmx utils/clflags.cmx \
+ bytecomp/bytepackager.cmx bytecomp/bytelink.cmx \
+ bytecomp/bytelibrarian.cmx driver/main.cmi
+driver/optcompile.cmo : utils/warnings.cmi typing/typemod.cmi \
+ typing/typedtree.cmi typing/typecore.cmi bytecomp/translmod.cmi \
+ typing/stypes.cmi bytecomp/simplif.cmi typing/printtyped.cmi \
+ typing/printtyp.cmi bytecomp/printlambda.cmi parsing/printast.cmi \
+ parsing/pprintast.cmi driver/pparse.cmi utils/misc.cmi \
+ typing/includemod.cmi typing/env.cmi utils/config.cmi driver/compmisc.cmi \
+ asmcomp/compilenv.cmi driver/compenv.cmi utils/clflags.cmi \
+ utils/ccomp.cmi asmcomp/asmgen.cmi driver/optcompile.cmi
+driver/optcompile.cmx : utils/warnings.cmx typing/typemod.cmx \
+ typing/typedtree.cmx typing/typecore.cmx bytecomp/translmod.cmx \
+ typing/stypes.cmx bytecomp/simplif.cmx typing/printtyped.cmx \
+ typing/printtyp.cmx bytecomp/printlambda.cmx parsing/printast.cmx \
+ parsing/pprintast.cmx driver/pparse.cmx utils/misc.cmx \
+ typing/includemod.cmx typing/env.cmx utils/config.cmx driver/compmisc.cmx \
+ asmcomp/compilenv.cmx driver/compenv.cmx utils/clflags.cmx \
+ utils/ccomp.cmx asmcomp/asmgen.cmx driver/optcompile.cmi
+driver/opterrors.cmo : parsing/location.cmi driver/opterrors.cmi
+driver/opterrors.cmx : parsing/location.cmx driver/opterrors.cmi
+driver/optmain.cmo : utils/warnings.cmi asmcomp/printmach.cmi \
+ driver/optcompile.cmi utils/misc.cmi driver/main_args.cmi \
+ parsing/location.cmi utils/config.cmi driver/compmisc.cmi \
+ driver/compenv.cmi utils/clflags.cmi asmcomp/asmpackager.cmi \
+ asmcomp/asmlink.cmi asmcomp/asmlibrarian.cmi asmcomp/arch.cmo \
+ driver/optmain.cmi
+driver/optmain.cmx : utils/warnings.cmx asmcomp/printmach.cmx \
+ driver/optcompile.cmx utils/misc.cmx driver/main_args.cmx \
+ parsing/location.cmx utils/config.cmx driver/compmisc.cmx \
+ driver/compenv.cmx utils/clflags.cmx asmcomp/asmpackager.cmx \
+ asmcomp/asmlink.cmx asmcomp/asmlibrarian.cmx asmcomp/arch.cmx \
+ driver/optmain.cmi
+driver/pparse.cmo : parsing/parse.cmi utils/misc.cmi parsing/location.cmi \
+ utils/config.cmi utils/clflags.cmi utils/ccomp.cmi parsing/ast_mapper.cmi \
+ driver/pparse.cmi
+driver/pparse.cmx : parsing/parse.cmx utils/misc.cmx parsing/location.cmx \
+ utils/config.cmx utils/clflags.cmx utils/ccomp.cmx parsing/ast_mapper.cmx \
+ driver/pparse.cmi
+toplevel/genprintval.cmi : typing/types.cmi typing/path.cmi \
+ typing/outcometree.cmi typing/env.cmi
+toplevel/opttopdirs.cmi : parsing/longident.cmi
+toplevel/opttoploop.cmi : utils/warnings.cmi typing/types.cmi \
+ typing/path.cmi parsing/parsetree.cmi typing/outcometree.cmi \
+ parsing/longident.cmi parsing/location.cmi typing/env.cmi
+toplevel/opttopmain.cmi :
+toplevel/topdirs.cmi : parsing/longident.cmi
+toplevel/toploop.cmi : utils/warnings.cmi typing/types.cmi typing/path.cmi \
+ parsing/parsetree.cmi typing/outcometree.cmi parsing/longident.cmi \
+ parsing/location.cmi typing/env.cmi
+toplevel/topmain.cmi :
+toplevel/trace.cmi : typing/types.cmi typing/path.cmi parsing/longident.cmi \
+ typing/env.cmi
+toplevel/expunge.cmo : bytecomp/symtable.cmi bytecomp/runtimedef.cmi \
+ utils/misc.cmi typing/ident.cmi bytecomp/bytesections.cmi
+toplevel/expunge.cmx : bytecomp/symtable.cmx bytecomp/runtimedef.cmx \
+ utils/misc.cmx typing/ident.cmx bytecomp/bytesections.cmx
+toplevel/genprintval.cmo : typing/types.cmi typing/printtyp.cmi \
+ typing/predef.cmi typing/path.cmi typing/outcometree.cmi \
+ typing/oprint.cmi utils/misc.cmi parsing/longident.cmi typing/ident.cmi \
+ typing/env.cmi typing/datarepr.cmi typing/ctype.cmi typing/btype.cmi \
+ toplevel/genprintval.cmi
+toplevel/genprintval.cmx : typing/types.cmx typing/printtyp.cmx \
+ typing/predef.cmx typing/path.cmx typing/outcometree.cmi \
+ typing/oprint.cmx utils/misc.cmx parsing/longident.cmx typing/ident.cmx \
+ typing/env.cmx typing/datarepr.cmx typing/ctype.cmx typing/btype.cmx \
+ toplevel/genprintval.cmi
+toplevel/opttopdirs.cmo : utils/warnings.cmi typing/types.cmi \
+ typing/printtyp.cmi toplevel/opttoploop.cmi utils/misc.cmi \
+ parsing/longident.cmi typing/ident.cmi typing/env.cmi typing/ctype.cmi \
+ utils/config.cmi utils/clflags.cmi asmcomp/asmlink.cmi \
+ toplevel/opttopdirs.cmi
+toplevel/opttopdirs.cmx : utils/warnings.cmx typing/types.cmx \
+ typing/printtyp.cmx toplevel/opttoploop.cmx utils/misc.cmx \
+ parsing/longident.cmx typing/ident.cmx typing/env.cmx typing/ctype.cmx \
+ utils/config.cmx utils/clflags.cmx asmcomp/asmlink.cmx \
+ toplevel/opttopdirs.cmi
+toplevel/opttoploop.cmo : utils/warnings.cmi typing/types.cmi \
+ typing/typemod.cmi typing/typedtree.cmi typing/typecore.cmi \
+ bytecomp/translmod.cmi bytecomp/simplif.cmi typing/printtyped.cmi \
+ typing/printtyp.cmi bytecomp/printlambda.cmi parsing/printast.cmi \
+ typing/predef.cmi parsing/pprintast.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/parse.cmi typing/outcometree.cmi \
+ typing/oprint.cmi utils/misc.cmi parsing/longident.cmi \
+ parsing/location.cmi parsing/lexer.cmi typing/ident.cmi \
+ toplevel/genprintval.cmi typing/env.cmi utils/config.cmi \
+ driver/compmisc.cmi asmcomp/compilenv.cmi utils/clflags.cmi \
+ typing/btype.cmi asmcomp/asmlink.cmi asmcomp/asmgen.cmi \
+ toplevel/opttoploop.cmi
+toplevel/opttoploop.cmx : utils/warnings.cmx typing/types.cmx \
+ typing/typemod.cmx typing/typedtree.cmx typing/typecore.cmx \
+ bytecomp/translmod.cmx bytecomp/simplif.cmx typing/printtyped.cmx \
+ typing/printtyp.cmx bytecomp/printlambda.cmx parsing/printast.cmx \
+ typing/predef.cmx parsing/pprintast.cmx typing/path.cmx \
+ parsing/parsetree.cmi parsing/parse.cmx typing/outcometree.cmi \
+ typing/oprint.cmx utils/misc.cmx parsing/longident.cmx \
+ parsing/location.cmx parsing/lexer.cmx typing/ident.cmx \
+ toplevel/genprintval.cmx typing/env.cmx utils/config.cmx \
+ driver/compmisc.cmx asmcomp/compilenv.cmx utils/clflags.cmx \
+ typing/btype.cmx asmcomp/asmlink.cmx asmcomp/asmgen.cmx \
+ toplevel/opttoploop.cmi
+toplevel/opttopmain.cmo : utils/warnings.cmi asmcomp/printmach.cmi \
+ toplevel/opttoploop.cmi toplevel/opttopdirs.cmi utils/misc.cmi \
+ driver/main_args.cmi parsing/location.cmi utils/config.cmi \
+ driver/compenv.cmi utils/clflags.cmi toplevel/opttopmain.cmi
+toplevel/opttopmain.cmx : utils/warnings.cmx asmcomp/printmach.cmx \
+ toplevel/opttoploop.cmx toplevel/opttopdirs.cmx utils/misc.cmx \
+ driver/main_args.cmx parsing/location.cmx utils/config.cmx \
+ driver/compenv.cmx utils/clflags.cmx toplevel/opttopmain.cmi
+toplevel/opttopstart.cmo : toplevel/opttopmain.cmi
+toplevel/opttopstart.cmx : toplevel/opttopmain.cmx
+toplevel/topdirs.cmo : utils/warnings.cmi typing/typetexp.cmi \
+ typing/types.cmi toplevel/trace.cmi toplevel/toploop.cmi \
+ bytecomp/symtable.cmi typing/printtyp.cmi typing/predef.cmi \
+ typing/path.cmi parsing/parsetree.cmi bytecomp/opcodes.cmo utils/misc.cmi \
+ bytecomp/meta.cmi parsing/longident.cmi parsing/location.cmi \
+ typing/ident.cmi typing/env.cmi bytecomp/dll.cmi typing/ctype.cmi \
+ utils/consistbl.cmi utils/config.cmi bytecomp/cmo_format.cmi \
+ utils/clflags.cmi typing/btype.cmi parsing/asttypes.cmi \
+ toplevel/topdirs.cmi
+toplevel/topdirs.cmx : utils/warnings.cmx typing/typetexp.cmx \
+ typing/types.cmx toplevel/trace.cmx toplevel/toploop.cmx \
+ bytecomp/symtable.cmx typing/printtyp.cmx typing/predef.cmx \
+ typing/path.cmx parsing/parsetree.cmi bytecomp/opcodes.cmx utils/misc.cmx \
+ bytecomp/meta.cmx parsing/longident.cmx parsing/location.cmx \
+ typing/ident.cmx typing/env.cmx bytecomp/dll.cmx typing/ctype.cmx \
+ utils/consistbl.cmx utils/config.cmx bytecomp/cmo_format.cmi \
+ utils/clflags.cmx typing/btype.cmx parsing/asttypes.cmi \
+ toplevel/topdirs.cmi
+toplevel/toploop.cmo : utils/warnings.cmi typing/types.cmi \
+ typing/typemod.cmi typing/typedtree.cmi typing/typecore.cmi \
+ bytecomp/translmod.cmi bytecomp/symtable.cmi bytecomp/simplif.cmi \
+ typing/printtyped.cmi typing/printtyp.cmi bytecomp/printlambda.cmi \
+ bytecomp/printinstr.cmi parsing/printast.cmi typing/predef.cmi \
+ parsing/pprintast.cmi driver/pparse.cmi typing/path.cmi \
+ parsing/parsetree.cmi parsing/parse.cmi typing/outcometree.cmi \
+ typing/oprint.cmi utils/misc.cmi bytecomp/meta.cmi parsing/longident.cmi \
+ parsing/location.cmi parsing/lexer.cmi typing/includemod.cmi \
+ typing/ident.cmi toplevel/genprintval.cmi typing/env.cmi \
+ bytecomp/emitcode.cmi bytecomp/dll.cmi utils/consistbl.cmi \
+ utils/config.cmi driver/compmisc.cmi utils/clflags.cmi \
+ bytecomp/bytegen.cmi typing/btype.cmi parsing/ast_helper.cmi \
+ toplevel/toploop.cmi
+toplevel/toploop.cmx : utils/warnings.cmx typing/types.cmx \
+ typing/typemod.cmx typing/typedtree.cmx typing/typecore.cmx \
+ bytecomp/translmod.cmx bytecomp/symtable.cmx bytecomp/simplif.cmx \
+ typing/printtyped.cmx typing/printtyp.cmx bytecomp/printlambda.cmx \
+ bytecomp/printinstr.cmx parsing/printast.cmx typing/predef.cmx \
+ parsing/pprintast.cmx driver/pparse.cmx typing/path.cmx \
+ parsing/parsetree.cmi parsing/parse.cmx typing/outcometree.cmi \
+ typing/oprint.cmx utils/misc.cmx bytecomp/meta.cmx parsing/longident.cmx \
+ parsing/location.cmx parsing/lexer.cmx typing/includemod.cmx \
+ typing/ident.cmx toplevel/genprintval.cmx typing/env.cmx \
+ bytecomp/emitcode.cmx bytecomp/dll.cmx utils/consistbl.cmx \
+ utils/config.cmx driver/compmisc.cmx utils/clflags.cmx \
+ bytecomp/bytegen.cmx typing/btype.cmx parsing/ast_helper.cmx \
+ toplevel/toploop.cmi
+toplevel/topmain.cmo : utils/warnings.cmi toplevel/toploop.cmi \
+ toplevel/topdirs.cmi utils/misc.cmi driver/main_args.cmi \
+ parsing/location.cmi utils/config.cmi driver/compenv.cmi \
+ utils/clflags.cmi toplevel/topmain.cmi
+toplevel/topmain.cmx : utils/warnings.cmx toplevel/toploop.cmx \
+ toplevel/topdirs.cmx utils/misc.cmx driver/main_args.cmx \
+ parsing/location.cmx utils/config.cmx driver/compenv.cmx \
+ utils/clflags.cmx toplevel/topmain.cmi
+toplevel/topstart.cmo : toplevel/topmain.cmi
+toplevel/topstart.cmx : toplevel/topmain.cmx
+toplevel/trace.cmo : typing/types.cmi toplevel/toploop.cmi \
+ typing/printtyp.cmi typing/predef.cmi typing/path.cmi utils/misc.cmi \
+ bytecomp/meta.cmi parsing/longident.cmi typing/ctype.cmi \
+ parsing/asttypes.cmi toplevel/trace.cmi
+toplevel/trace.cmx : typing/types.cmx toplevel/toploop.cmx \
+ typing/printtyp.cmx typing/predef.cmx typing/path.cmx utils/misc.cmx \
+ bytecomp/meta.cmx parsing/longident.cmx typing/ctype.cmx \
+ parsing/asttypes.cmi toplevel/trace.cmi
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000..9cb92d25a7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2848 @@
+
+# /
+/*.o
+/*.a
+/*.so
+/*.obj
+/*.lib
+/*.dll
+/*.cm[ioxat]
+/*.cmx[as]
+/*.cmti
+/*.annot
+/*.result
+/*.byte
+/*.native
+/program
+/*.exe
+/*.exe.manifest
+/.depend
+/.depend.nt
+/.DS_Store
+/configure
+/ocamlc
+/ocamlc.opt
+/expunge
+/ocaml
+/ocamlopt
+/ocamlopt.opt
+/ocamlcomp.sh
+/ocamlcompopt.sh
+/package-macosx
+/ocamlnat
+
+# /asmcomp/
+/asmcomp/*.o
+/asmcomp/*.a
+/asmcomp/*.so
+/asmcomp/*.obj
+/asmcomp/*.lib
+/asmcomp/*.dll
+/asmcomp/*.cm[ioxat]
+/asmcomp/*.cmx[as]
+/asmcomp/*.cmti
+/asmcomp/*.annot
+/asmcomp/*.result
+/asmcomp/*.byte
+/asmcomp/*.native
+/asmcomp/program
+/asmcomp/*.exe
+/asmcomp/*.exe.manifest
+/asmcomp/.depend
+/asmcomp/.depend.nt
+/asmcomp/.DS_Store
+/asmcomp/emit.ml
+/asmcomp/arch.ml
+/asmcomp/proc.ml
+/asmcomp/selection.ml
+/asmcomp/reload.ml
+/asmcomp/scheduling.ml
+/asmcomp/CSE.ml
+
+# /asmcomp/amd64/
+/asmcomp/amd64/*.o
+/asmcomp/amd64/*.a
+/asmcomp/amd64/*.so
+/asmcomp/amd64/*.obj
+/asmcomp/amd64/*.cm[ioxat]
+/asmcomp/amd64/*.cmx[as]
+/asmcomp/amd64/*.cmti
+/asmcomp/amd64/*.annot
+/asmcomp/amd64/*.result
+/asmcomp/amd64/*.byte
+/asmcomp/amd64/*.native
+/asmcomp/amd64/program
+/asmcomp/amd64/program.exe
+/asmcomp/amd64/.depend
+/asmcomp/amd64/.depend.nt
+/asmcomp/amd64/.DS_Store
+
+# /asmrun/
+/asmrun/*.o
+/asmrun/*.a
+/asmrun/*.so
+/asmrun/*.obj
+/asmrun/*.lib
+/asmrun/*.dll
+/asmrun/*.cm[ioxat]
+/asmrun/*.cmx[as]
+/asmrun/*.cmti
+/asmrun/*.annot
+/asmrun/*.result
+/asmrun/*.byte
+/asmrun/*.native
+/asmrun/program
+/asmrun/*.exe
+/asmrun/.depend
+/asmrun/.depend.nt
+/asmrun/.DS_Store
+/asmrun/*.p.c
+/asmrun/*.d.c
+/asmrun/libasmrun.a
+/asmrun/libasmrunp.a
+/asmrun/main.c
+/asmrun/misc.c
+/asmrun/freelist.c
+/asmrun/major_gc.c
+/asmrun/minor_gc.c
+/asmrun/memory.c
+/asmrun/alloc.c
+/asmrun/array.c
+/asmrun/compare.c
+/asmrun/backtrace.c
+/asmrun/ints.c
+/asmrun/floats.c
+/asmrun/str.c
+/asmrun/io.c
+/asmrun/extern.c
+/asmrun/intern.c
+/asmrun/hash.c
+/asmrun/sys.c
+/asmrun/parsing.c
+/asmrun/gc_ctrl.c
+/asmrun/terminfo.c
+/asmrun/md5.c
+/asmrun/obj.c
+/asmrun/lexing.c
+/asmrun/printexc.c
+/asmrun/callback.c
+/asmrun/weak.c
+/asmrun/compact.c
+/asmrun/finalise.c
+/asmrun/custom.c
+/asmrun/meta.c
+/asmrun/globroots.c
+/asmrun/unix.c
+/asmrun/dynlink.c
+/asmrun/signals.c
+/asmrun/debugger.c
+/asmrun/.depend.nt
+
+# /boot/
+/boot/*.o
+/boot/*.a
+/boot/*.so
+/boot/*.obj
+/boot/*.lib
+/boot/*.dll
+/boot/*.cm[ioxat]
+/boot/*.cmx[as]
+/boot/*.cmti
+/boot/*.annot
+/boot/*.result
+/boot/*.byte
+/boot/*.native
+/boot/program
+/boot/*.exe
+/boot/*.exe.manifest
+/boot/.depend
+/boot/.depend.nt
+/boot/.DS_Store
+/boot/Saved
+/boot/ocamlrun
+/boot/ocamlrun.exe
+/boot/ocamlyacc
+/boot/ocamlyacc.exe
+/boot/camlheader
+
+# /bytecomp/
+/bytecomp/*.o
+/bytecomp/*.a
+/bytecomp/*.so
+/bytecomp/*.obj
+/bytecomp/*.lib
+/bytecomp/*.dll
+/bytecomp/*.cm[ioxat]
+/bytecomp/*.cmx[as]
+/bytecomp/*.cmti
+/bytecomp/*.annot
+/bytecomp/*.result
+/bytecomp/*.byte
+/bytecomp/*.native
+/bytecomp/program
+/bytecomp/*.exe
+/bytecomp/.depend
+/bytecomp/.depend.nt
+/bytecomp/.DS_Store
+/bytecomp/runtimedef.ml
+/bytecomp/opcodes.ml
+
+# /byterun/
+/byterun/*.o
+/byterun/*.a
+/byterun/*.so
+/byterun/*.obj
+/byterun/*.cm[ioxa]
+/byterun/*.cmx[as]
+/byterun/*.annot
+/byterun/*.result
+/byterun/*.byte
+/byterun/*.native
+/byterun/program
+/byterun/program.exe
+/byterun/.depend
+/byterun/.depend.nt
+/byterun/.DS_Store
+/byterun/caml/jumptbl.h
+/byterun/primitives
+/byterun/prims.c
+/byterun/caml/opnames.h
+/byterun/caml/version.h
+/byterun/ocamlrun
+/byterun/ocamlrun.exe
+/byterun/ocamlrund
+/byterun/ocamlrund.exe
+/byterun/ld.conf
+/byterun/interp.a.lst
+/byterun/*.[sd]obj
+/byterun/*.lib
+/byterun/.gdb_history
+/byterun/*.d.c
+/byterun/*.pic.c
+
+# /compilerlibs/
+/compilerlibs/*
+
+# /config/
+/config/*.o
+/config/*.a
+/config/*.so
+/config/*.obj
+/config/*.lib
+/config/*.dll
+/config/*.cm[ioxat]
+/config/*.cmx[as]
+/config/*.cmti
+/config/*.annot
+/config/*.result
+/config/*.byte
+/config/*.native
+/config/program
+/config/*.exe
+/config/*.exe.manifest
+/config/.depend
+/config/.depend.nt
+/config/.DS_Store
+/config/m.h
+/config/s.h
+/config/Makefile
+
+# /config/auto-aux/
+/config/auto-aux/*.o
+/config/auto-aux/*.a
+/config/auto-aux/*.so
+/config/auto-aux/*.obj
+/config/auto-aux/*.cm[ioxa]
+/config/auto-aux/*.cmx[as]
+/config/auto-aux/*.annot
+/config/auto-aux/*.result
+/config/auto-aux/*.byte
+/config/auto-aux/*.native
+/config/auto-aux/program
+/config/auto-aux/.depend
+/config/auto-aux/.depend.nt
+/config/auto-aux/.DS_Store
+/config/auto-aux/camlp4_config.ml
+
+# /config/gnu/
+
+# /debugger/
+/debugger/*.o
+/debugger/*.a
+/debugger/*.so
+/debugger/*.obj
+/debugger/*.cm[ioxa]
+/debugger/*.cmx[as]
+/debugger/*.annot
+/debugger/*.result
+/debugger/*.byte
+/debugger/*.native
+/debugger/program
+/debugger/program.exe
+/debugger/.depend
+/debugger/.depend.nt
+/debugger/.DS_Store
+/debugger/lexer.ml
+/debugger/parser.ml
+/debugger/parser.mli
+/debugger/ocamldebug
+/debugger/ocamldebug.exe
+/debugger/dynlink.ml
+/debugger/dynlink.mli
+
+# /driver/
+/driver/*.o
+/driver/*.a
+/driver/*.so
+/driver/*.obj
+/driver/*.lib
+/driver/*.dll
+/driver/*.cm[ioxat]
+/driver/*.cmx[as]
+/driver/*.cmti
+/driver/*.annot
+/driver/*.result
+/driver/*.byte
+/driver/*.native
+/driver/program
+/driver/*.exe
+/driver/*.exe.manifest
+/driver/.depend
+/driver/.depend.nt
+/driver/.DS_Store
+
+# /emacs/
+/emacs/*.o
+/emacs/*.a
+/emacs/*.so
+/emacs/*.obj
+/emacs/*.lib
+/emacs/*.dll
+/emacs/*.cm[ioxat]
+/emacs/*.cmx[as]
+/emacs/*.cmti
+/emacs/*.annot
+/emacs/*.result
+/emacs/*.byte
+/emacs/*.native
+/emacs/program
+/emacs/*.exe
+/emacs/*.exe.manifest
+/emacs/.depend
+/emacs/.depend.nt
+/emacs/.DS_Store
+/emacs/ocamltags
+/emacs/*.elc
+
+# /experimental/
+
+# /experimental/garrigue/
+/experimental/garrigue/*.out
+/experimental/garrigue/*.out2
+
+# /lex/
+/lex/*.o
+/lex/*.a
+/lex/*.so
+/lex/*.obj
+/lex/*.lib
+/lex/*.dll
+/lex/*.cm[ioxat]
+/lex/*.cmx[as]
+/lex/*.cmti
+/lex/*.annot
+/lex/*.result
+/lex/*.byte
+/lex/*.native
+/lex/program
+/lex/*.exe
+/lex/*.exe.manifest
+/lex/.depend
+/lex/.depend.nt
+/lex/.DS_Store
+/lex/parser.ml
+/lex/parser.mli
+/lex/lexer.ml
+/lex/ocamllex
+/lex/ocamllex.opt
+/lex/parser.output
+
+# /ocamlbuild/
+/ocamlbuild/*.o
+/ocamlbuild/*.a
+/ocamlbuild/*.so
+/ocamlbuild/*.obj
+/ocamlbuild/*.lib
+/ocamlbuild/*.dll
+/ocamlbuild/*.cm[ioxat]
+/ocamlbuild/*.cmx[as]
+/ocamlbuild/*.cmti
+/ocamlbuild/*.annot
+/ocamlbuild/*.byte
+/ocamlbuild/*.native
+/ocamlbuild/ocamlbuild_config.ml
+/ocamlbuild/lexers.ml
+/ocamlbuild/glob_lexer.ml
+
+# /ocamldoc/
+/ocamldoc/*.o
+/ocamldoc/*.a
+/ocamldoc/*.so
+/ocamldoc/*.obj
+/ocamldoc/*.lib
+/ocamldoc/*.dll
+/ocamldoc/*.cm[ioxat]
+/ocamldoc/*.cmx[as]
+/ocamldoc/*.cmti
+/ocamldoc/*.annot
+/ocamldoc/*.result
+/ocamldoc/*.byte
+/ocamldoc/*.native
+/ocamldoc/program
+/ocamldoc/*.exe
+/ocamldoc/.depend
+/ocamldoc/.depend.nt
+/ocamldoc/.DS_Store
+/ocamldoc/ocamldoc
+/ocamldoc/ocamldoc.opt
+/ocamldoc/odoc_crc.ml
+/ocamldoc/odoc_lexer.ml
+/ocamldoc/odoc_ocamlhtml.ml
+/ocamldoc/odoc_parser.ml
+/ocamldoc/odoc_parser.mli
+/ocamldoc/odoc_see_lexer.ml
+/ocamldoc/odoc_text_lexer.ml
+/ocamldoc/odoc_text_parser.ml
+/ocamldoc/odoc_text_parser.mli
+/ocamldoc/stdlib_man
+/ocamldoc/stdlib_html
+/ocamldoc/*.output
+/ocamldoc/test_stdlib
+/ocamldoc/test_latex
+/ocamldoc/test
+
+# /ocamldoc/generators/
+/ocamldoc/generators/*.o
+/ocamldoc/generators/*.a
+/ocamldoc/generators/*.so
+/ocamldoc/generators/*.obj
+/ocamldoc/generators/*.lib
+/ocamldoc/generators/*.dll
+/ocamldoc/generators/*.cm[ioxat]
+/ocamldoc/generators/*.cmx[as]
+/ocamldoc/generators/*.cmti
+/ocamldoc/generators/*.annot
+/ocamldoc/generators/*.result
+/ocamldoc/generators/*.byte
+/ocamldoc/generators/*.native
+/ocamldoc/generators/program
+/ocamldoc/generators/*.exe
+/ocamldoc/generators/*.exe.manifest
+/ocamldoc/generators/.depend
+/ocamldoc/generators/.depend.nt
+/ocamldoc/generators/.DS_Store
+
+# /otherlibs/
+/otherlibs/.depend
+/otherlibs/configure
+/otherlibs/ocamlc
+/otherlibs/ocamlc.opt
+/otherlibs/expunge
+/otherlibs/ocaml
+/otherlibs/ocamlopt
+/otherlibs/ocamlopt.opt
+/otherlibs/ocamlcomp.sh
+/otherlibs/ocamlcompopt.sh
+/otherlibs/package-macosx
+/otherlibs/.DS_Store
+/otherlibs/*.annot
+/otherlibs/_boot_log1
+/otherlibs/_boot_log2
+/otherlibs/_build
+/otherlibs/_log
+/otherlibs/myocamlbuild_config.ml
+/otherlibs/ocamlnat
+/otherlibs/*.cm*
+/otherlibs/*.o
+
+# /otherlibs/bigarray/
+/otherlibs/bigarray/*.o
+/otherlibs/bigarray/*.a
+/otherlibs/bigarray/*.so
+/otherlibs/bigarray/*.obj
+/otherlibs/bigarray/*.lib
+/otherlibs/bigarray/*.dll
+/otherlibs/bigarray/*.cm[ioxat]
+/otherlibs/bigarray/*.cmx[as]
+/otherlibs/bigarray/*.cmti
+/otherlibs/bigarray/*.annot
+/otherlibs/bigarray/*.result
+/otherlibs/bigarray/*.byte
+/otherlibs/bigarray/*.native
+/otherlibs/bigarray/program
+/otherlibs/bigarray/*.exe
+/otherlibs/bigarray/.depend
+/otherlibs/bigarray/.depend.nt
+/otherlibs/bigarray/.DS_Store
+
+# /otherlibs/dynlink/
+/otherlibs/dynlink/*.o
+/otherlibs/dynlink/*.a
+/otherlibs/dynlink/*.so
+/otherlibs/dynlink/*.obj
+/otherlibs/dynlink/*.lib
+/otherlibs/dynlink/*.dll
+/otherlibs/dynlink/*.cm[ioxat]
+/otherlibs/dynlink/*.cmx[as]
+/otherlibs/dynlink/*.cmti
+/otherlibs/dynlink/*.annot
+/otherlibs/dynlink/*.result
+/otherlibs/dynlink/*.byte
+/otherlibs/dynlink/*.native
+/otherlibs/dynlink/program
+/otherlibs/dynlink/*.exe
+/otherlibs/dynlink/.depend
+/otherlibs/dynlink/.depend.nt
+/otherlibs/dynlink/.DS_Store
+/otherlibs/dynlink/extract_crc
+
+# /otherlibs/graph/
+/otherlibs/graph/*.o
+/otherlibs/graph/*.a
+/otherlibs/graph/*.so
+/otherlibs/graph/*.obj
+/otherlibs/graph/*.lib
+/otherlibs/graph/*.dll
+/otherlibs/graph/*.cm[ioxat]
+/otherlibs/graph/*.cmx[as]
+/otherlibs/graph/*.cmti
+/otherlibs/graph/*.annot
+/otherlibs/graph/*.result
+/otherlibs/graph/*.byte
+/otherlibs/graph/*.native
+/otherlibs/graph/program
+/otherlibs/graph/*.exe
+/otherlibs/graph/*.exe.manifest
+/otherlibs/graph/.depend
+/otherlibs/graph/.depend.nt
+/otherlibs/graph/.DS_Store
+
+# /otherlibs/num/
+/otherlibs/num/*.o
+/otherlibs/num/*.a
+/otherlibs/num/*.so
+/otherlibs/num/*.obj
+/otherlibs/num/*.lib
+/otherlibs/num/*.dll
+/otherlibs/num/*.cm[ioxat]
+/otherlibs/num/*.cmx[as]
+/otherlibs/num/*.cmti
+/otherlibs/num/*.annot
+/otherlibs/num/*.result
+/otherlibs/num/*.byte
+/otherlibs/num/*.native
+/otherlibs/num/program
+/otherlibs/num/*.exe
+/otherlibs/num/.depend
+/otherlibs/num/.depend.nt
+/otherlibs/num/.DS_Store
+
+# /otherlibs/str/
+/otherlibs/str/*.o
+/otherlibs/str/*.a
+/otherlibs/str/*.so
+/otherlibs/str/*.obj
+/otherlibs/str/*.lib
+/otherlibs/str/*.dll
+/otherlibs/str/*.cm[ioxat]
+/otherlibs/str/*.cmx[as]
+/otherlibs/str/*.cmti
+/otherlibs/str/*.annot
+/otherlibs/str/*.result
+/otherlibs/str/*.byte
+/otherlibs/str/*.native
+/otherlibs/str/program
+/otherlibs/str/*.exe
+/otherlibs/str/.depend
+/otherlibs/str/.depend.nt
+/otherlibs/str/.DS_Store
+
+# /otherlibs/systhreads/
+/otherlibs/systhreads/*.o
+/otherlibs/systhreads/*.a
+/otherlibs/systhreads/*.so
+/otherlibs/systhreads/*.obj
+/otherlibs/systhreads/*.lib
+/otherlibs/systhreads/*.dll
+/otherlibs/systhreads/*.cm[ioxat]
+/otherlibs/systhreads/*.cmx[as]
+/otherlibs/systhreads/*.cmti
+/otherlibs/systhreads/*.annot
+/otherlibs/systhreads/*.result
+/otherlibs/systhreads/*.byte
+/otherlibs/systhreads/*.native
+/otherlibs/systhreads/program
+/otherlibs/systhreads/*.exe
+/otherlibs/systhreads/.depend
+/otherlibs/systhreads/.depend.nt
+/otherlibs/systhreads/.DS_Store
+/otherlibs/systhreads/thread.ml
+
+# /otherlibs/threads/
+/otherlibs/threads/*.o
+/otherlibs/threads/*.a
+/otherlibs/threads/*.so
+/otherlibs/threads/*.obj
+/otherlibs/threads/*.lib
+/otherlibs/threads/*.dll
+/otherlibs/threads/*.cm[ioxat]
+/otherlibs/threads/*.cmx[as]
+/otherlibs/threads/*.cmti
+/otherlibs/threads/*.annot
+/otherlibs/threads/*.result
+/otherlibs/threads/*.byte
+/otherlibs/threads/*.native
+/otherlibs/threads/program
+/otherlibs/threads/*.exe
+/otherlibs/threads/*.exe.manifest
+/otherlibs/threads/.depend
+/otherlibs/threads/.depend.nt
+/otherlibs/threads/.DS_Store
+/otherlibs/threads/marshal.mli
+/otherlibs/threads/pervasives.mli
+/otherlibs/threads/unix.mli
+
+# /otherlibs/unix/
+/otherlibs/unix/*.o
+/otherlibs/unix/*.a
+/otherlibs/unix/*.so
+/otherlibs/unix/*.obj
+/otherlibs/unix/*.lib
+/otherlibs/unix/*.dll
+/otherlibs/unix/*.cm[ioxat]
+/otherlibs/unix/*.cmx[as]
+/otherlibs/unix/*.cmti
+/otherlibs/unix/*.annot
+/otherlibs/unix/*.result
+/otherlibs/unix/*.byte
+/otherlibs/unix/*.native
+/otherlibs/unix/program
+/otherlibs/unix/*.exe
+/otherlibs/unix/*.exe.manifest
+/otherlibs/unix/.depend
+/otherlibs/unix/.depend.nt
+/otherlibs/unix/.DS_Store
+
+# /otherlibs/win32graph/
+/otherlibs/win32graph/*.o
+/otherlibs/win32graph/*.a
+/otherlibs/win32graph/*.so
+/otherlibs/win32graph/*.obj
+/otherlibs/win32graph/*.lib
+/otherlibs/win32graph/*.dll
+/otherlibs/win32graph/*.cm[ioxat]
+/otherlibs/win32graph/*.cmx[as]
+/otherlibs/win32graph/*.cmti
+/otherlibs/win32graph/*.annot
+/otherlibs/win32graph/*.result
+/otherlibs/win32graph/*.byte
+/otherlibs/win32graph/*.native
+/otherlibs/win32graph/program
+/otherlibs/win32graph/*.exe
+/otherlibs/win32graph/.depend
+/otherlibs/win32graph/.depend.nt
+/otherlibs/win32graph/.DS_Store
+/otherlibs/win32graph/graphics.ml
+/otherlibs/win32graph/graphics.mli
+
+# /otherlibs/win32unix/
+/otherlibs/win32unix/*.o
+/otherlibs/win32unix/*.a
+/otherlibs/win32unix/*.so
+/otherlibs/win32unix/*.obj
+/otherlibs/win32unix/*.lib
+/otherlibs/win32unix/*.dll
+/otherlibs/win32unix/*.cm[ioxat]
+/otherlibs/win32unix/*.cmx[as]
+/otherlibs/win32unix/*.cmti
+/otherlibs/win32unix/*.annot
+/otherlibs/win32unix/*.result
+/otherlibs/win32unix/*.byte
+/otherlibs/win32unix/*.native
+/otherlibs/win32unix/program
+/otherlibs/win32unix/*.exe
+/otherlibs/win32unix/.depend
+/otherlibs/win32unix/.depend.nt
+/otherlibs/win32unix/.DS_Store
+/otherlibs/win32unix/unixLabels.ml*
+/otherlibs/win32unix/unix.mli
+/otherlibs/win32unix/unix.lib
+/otherlibs/win32unix/access.c
+/otherlibs/win32unix/addrofstr.c
+/otherlibs/win32unix/chdir.c
+/otherlibs/win32unix/chmod.c
+/otherlibs/win32unix/cst2constr.c
+/otherlibs/win32unix/cstringv.c
+/otherlibs/win32unix/envir.c
+/otherlibs/win32unix/execv.c
+/otherlibs/win32unix/execve.c
+/otherlibs/win32unix/execvp.c
+/otherlibs/win32unix/exit.c
+/otherlibs/win32unix/getaddrinfo.c
+/otherlibs/win32unix/getcwd.c
+/otherlibs/win32unix/gethost.c
+/otherlibs/win32unix/gethostname.c
+/otherlibs/win32unix/getnameinfo.c
+/otherlibs/win32unix/getproto.c
+/otherlibs/win32unix/getserv.c
+/otherlibs/win32unix/gmtime.c
+/otherlibs/win32unix/putenv.c
+/otherlibs/win32unix/rmdir.c
+/otherlibs/win32unix/socketaddr.c
+/otherlibs/win32unix/strofaddr.c
+/otherlibs/win32unix/time.c
+/otherlibs/win32unix/unlink.c
+/otherlibs/win32unix/utimes.c
+
+# /parsing/
+/parsing/*.o
+/parsing/*.a
+/parsing/*.so
+/parsing/*.obj
+/parsing/*.lib
+/parsing/*.dll
+/parsing/*.cm[ioxat]
+/parsing/*.cmx[as]
+/parsing/*.cmti
+/parsing/*.annot
+/parsing/*.result
+/parsing/*.byte
+/parsing/*.native
+/parsing/program
+/parsing/*.exe
+/parsing/*.exe.manifest
+/parsing/.depend
+/parsing/.depend.nt
+/parsing/.DS_Store
+/parsing/parser.ml
+/parsing/parser.mli
+/parsing/lexer.ml
+/parsing/lexer_tmp.mll
+/parsing/lexer_tmp.ml
+/parsing/linenum.ml
+/parsing/parser.output
+/parsing/parser.automaton
+/parsing/parser.conflicts
+
+# /stdlib/
+/stdlib/*.o
+/stdlib/*.a
+/stdlib/*.so
+/stdlib/*.obj
+/stdlib/*.lib
+/stdlib/*.dll
+/stdlib/*.cm[ioxat]
+/stdlib/*.cmx[as]
+/stdlib/*.cmti
+/stdlib/*.annot
+/stdlib/*.result
+/stdlib/*.byte
+/stdlib/*.native
+/stdlib/program
+/stdlib/*.exe
+/stdlib/.depend
+/stdlib/.depend.nt
+/stdlib/.DS_Store
+/stdlib/camlheader
+/stdlib/camlheaderd
+/stdlib/camlheader_ur
+/stdlib/labelled-*
+/stdlib/caml
+/stdlib/sys.ml
+
+# /testsuite/
+/testsuite/*.o
+/testsuite/*.a
+/testsuite/*.so
+/testsuite/*.obj
+/testsuite/*.cm[ioxa]
+/testsuite/*.cmx[as]
+/testsuite/*.annot
+/testsuite/*.result
+/testsuite/*.byte
+/testsuite/*.native
+/testsuite/program
+/testsuite/.depend
+/testsuite/.depend.nt
+/testsuite/.DS_Store
+/testsuite/_log
+
+# /testsuite/external/
+/testsuite/external/*.o
+/testsuite/external/*.a
+/testsuite/external/*.so
+/testsuite/external/*.obj
+/testsuite/external/*.lib
+/testsuite/external/*.dll
+/testsuite/external/*.cm[ioxat]
+/testsuite/external/*.cmx[as]
+/testsuite/external/*.cmti
+/testsuite/external/*.annot
+/testsuite/external/*.result
+/testsuite/external/*.byte
+/testsuite/external/*.native
+/testsuite/external/program
+/testsuite/external/*.exe
+/testsuite/external/*.exe.manifest
+/testsuite/external/.depend
+/testsuite/external/.depend.nt
+/testsuite/external/.DS_Store
+/testsuite/external/*.tar.gz
+/testsuite/external/*.tar.bz2
+/testsuite/external/*.tgz
+/testsuite/external/*.tbz
+/testsuite/external/*.zip
+/testsuite/external/log-*
+/testsuite/external/log_*
+/testsuite/external/advi
+/testsuite/external/advi-1.10.2
+/testsuite/external/altergo
+/testsuite/external/alt-ergo-0.95.2
+/testsuite/external/binprot
+/testsuite/external/bin_prot-109.30.00
+/testsuite/external/bitstring
+/testsuite/external/ocaml-bitstring-2.0.3
+/testsuite/external/boomerang
+/testsuite/external/boomerang-0.2
+/testsuite/external/calendar
+/testsuite/external/calendar-2.03.2
+/testsuite/external/camlimages
+/testsuite/external/camlimages-4.0.1
+/testsuite/external/camlpdf
+/testsuite/external/camlpdf-0.5
+/testsuite/external/camlp4
+/testsuite/external/camlp4-trunk
+/testsuite/external/camlp5
+/testsuite/external/camlp5-git
+/testsuite/external/camlzip
+/testsuite/external/camlzip-1.04
+/testsuite/external/camomile
+/testsuite/external/camomile-0.8.4
+/testsuite/external/comparelib
+/testsuite/external/comparelib-109.15.00
+/testsuite/external/compcert
+/testsuite/external/compcert-1.13
+/testsuite/external/configfile
+/testsuite/external/config-file-1.1
+/testsuite/external/coq
+/testsuite/external/coq-8.4pl2
+/testsuite/external/core
+/testsuite/external/core-109.37.00
+/testsuite/external/coreextended
+/testsuite/external/core_extended-109.36.00
+/testsuite/external/corekernel
+/testsuite/external/core_kernel-109.37.00
+/testsuite/external/cryptokit
+/testsuite/external/cryptokit-1.6
+/testsuite/external/csv
+/testsuite/external/csv-1.3.1
+/testsuite/external/customprintf
+/testsuite/external/custom_printf-109.27.00
+/testsuite/external/dbm
+/testsuite/external/camldbm-1.0
+/testsuite/external/expect
+/testsuite/external/ocaml-expect-0.0.3
+/testsuite/external/extlib
+/testsuite/external/extlib-1.5.2
+/testsuite/external/fieldslib
+/testsuite/external/fieldslib-109.15.00
+/testsuite/external/fileutils
+/testsuite/external/ocaml-fileutils-0.4.4
+/testsuite/external/findlib
+/testsuite/external/findlib-1.4.1
+/testsuite/external/framac
+/testsuite/external/frama-c-Oxygen-20120901
+/testsuite/external/geneweb
+/testsuite/external/gw-6.05-src
+/testsuite/external/herelib
+/testsuite/external/herelib-109.35.00
+/testsuite/external/hevea
+/testsuite/external/hevea-2.09
+/testsuite/external/kaputt
+/testsuite/external/kaputt-1.2
+/testsuite/external/lablgtk
+/testsuite/external/lablgtk-2.18.0
+/testsuite/external/lablgtkextras
+/testsuite/external/lablgtkextras-1.3
+/testsuite/external/lwt
+/testsuite/external/lwt-2.4.0
+/testsuite/external/menhir
+/testsuite/external/menhir-20120123
+/testsuite/external/mldonkey
+/testsuite/external/mldonkey-3.1.2
+/testsuite/external/mysql
+/testsuite/external/ocaml-mysql-1.0.4
+/testsuite/external/oasis
+/testsuite/external/oasis-0.3.0
+/testsuite/external/obrowser
+/testsuite/external/obrowser-1.1.1
+/testsuite/external/ocamlgraph
+/testsuite/external/ocamlgraph-1.8.2
+/testsuite/external/ocamlify
+/testsuite/external/ocamlify-0.0.1
+/testsuite/external/ocamlmod
+/testsuite/external/ocamlmod-0.0.3
+/testsuite/external/ocamlnet
+/testsuite/external/ocamlnet-3.5.1
+/testsuite/external/ocamlscript
+/testsuite/external/ocamlscript-2.0.3
+/testsuite/external/ocamlssl
+/testsuite/external/ocaml-ssl-0.4.6
+/testsuite/external/ocamltext
+/testsuite/external/ocaml-text-0.5
+/testsuite/external/ocgi
+/testsuite/external/ocgi-0.5
+/testsuite/external/ocsigen
+/testsuite/external/ocsigen-bundle-2.2.2
+/testsuite/external/odn
+/testsuite/external/ocaml-data-notation-0.0.10
+/testsuite/external/omake
+/testsuite/external/omake-0.9.8.6
+/testsuite/external/ounit
+/testsuite/external/ounit-1.1.2
+/testsuite/external/paounit
+/testsuite/external/pa_ounit-109.36.00
+/testsuite/external/pcre
+/testsuite/external/pcre-ocaml-6.2.5
+/testsuite/external/pipebang
+/testsuite/external/pipebang-109.28.00
+/testsuite/external/react
+/testsuite/external/react-0.9.3
+/testsuite/external/res
+/testsuite/external/res-3.2.0
+/testsuite/external/rss
+/testsuite/external/ocamlrss-2.2.2
+/testsuite/external/sexplib
+/testsuite/external/sexplib-109.15.00
+/testsuite/external/sks
+/testsuite/external/sks-1.1.3
+/testsuite/external/sqlite
+/testsuite/external/sqlite3-ocaml-2.0.1
+/testsuite/external/textutils
+/testsuite/external/textutils-109.36.00
+/testsuite/external/typeconv
+/testsuite/external/type_conv-109.28.00
+/testsuite/external/unison
+/testsuite/external/unison-2.45.4
+/testsuite/external/variantslib
+/testsuite/external/variantslib-109.15.00
+/testsuite/external/vsyml
+/testsuite/external/vsyml-2010-04-06
+/testsuite/external/xmllight
+/testsuite/external/xml-light.2.3
+/testsuite/external/xmlm
+/testsuite/external/xmlm-1.1.0
+/testsuite/external/zarith
+/testsuite/external/zarith-1.2.1
+/testsuite/external/zen
+/testsuite/external/zen_2.3.2
+/testsuite/external/._ZEN_2.3.2
+
+# /testsuite/interactive/
+/testsuite/interactive/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/interactive/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/interactive/_log
+/testsuite/interactive/*.so
+/testsuite/interactive/*.a
+/testsuite/interactive/*.result
+/testsuite/interactive/*.byte
+/testsuite/interactive/*.native
+/testsuite/interactive/program
+/testsuite/interactive/*.cm*
+/testsuite/interactive/*.o
+
+# /testsuite/interactive/lib-gc/
+/testsuite/interactive/lib-gc/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/interactive/lib-gc/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/interactive/lib-gc/_log
+/testsuite/interactive/lib-gc/*.so
+/testsuite/interactive/lib-gc/*.a
+/testsuite/interactive/lib-gc/*.result
+/testsuite/interactive/lib-gc/*.byte
+/testsuite/interactive/lib-gc/*.native
+/testsuite/interactive/lib-gc/program
+/testsuite/interactive/lib-gc/*.cm*
+/testsuite/interactive/lib-gc/*.o
+
+# /testsuite/interactive/lib-graph/
+/testsuite/interactive/lib-graph/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/interactive/lib-graph/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/interactive/lib-graph/_log
+/testsuite/interactive/lib-graph/*.so
+/testsuite/interactive/lib-graph/*.a
+/testsuite/interactive/lib-graph/*.result
+/testsuite/interactive/lib-graph/*.byte
+/testsuite/interactive/lib-graph/*.native
+/testsuite/interactive/lib-graph/program
+/testsuite/interactive/lib-graph/*.cm*
+/testsuite/interactive/lib-graph/*.o
+
+# /testsuite/interactive/lib-graph-2/
+/testsuite/interactive/lib-graph-2/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/interactive/lib-graph-2/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/interactive/lib-graph-2/_log
+/testsuite/interactive/lib-graph-2/*.so
+/testsuite/interactive/lib-graph-2/*.a
+/testsuite/interactive/lib-graph-2/*.result
+/testsuite/interactive/lib-graph-2/*.byte
+/testsuite/interactive/lib-graph-2/*.native
+/testsuite/interactive/lib-graph-2/program
+/testsuite/interactive/lib-graph-2/*.cm*
+/testsuite/interactive/lib-graph-2/*.o
+
+# /testsuite/interactive/lib-graph-3/
+/testsuite/interactive/lib-graph-3/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/interactive/lib-graph-3/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/interactive/lib-graph-3/_log
+/testsuite/interactive/lib-graph-3/*.so
+/testsuite/interactive/lib-graph-3/*.a
+/testsuite/interactive/lib-graph-3/*.result
+/testsuite/interactive/lib-graph-3/*.byte
+/testsuite/interactive/lib-graph-3/*.native
+/testsuite/interactive/lib-graph-3/program
+/testsuite/interactive/lib-graph-3/*.cm*
+/testsuite/interactive/lib-graph-3/*.o
+
+# /testsuite/interactive/lib-signals/
+/testsuite/interactive/lib-signals/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/interactive/lib-signals/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/interactive/lib-signals/_log
+/testsuite/interactive/lib-signals/*.so
+/testsuite/interactive/lib-signals/*.a
+/testsuite/interactive/lib-signals/*.result
+/testsuite/interactive/lib-signals/*.byte
+/testsuite/interactive/lib-signals/*.native
+/testsuite/interactive/lib-signals/program
+/testsuite/interactive/lib-signals/*.cm*
+/testsuite/interactive/lib-signals/*.o
+
+# /testsuite/lib/
+/testsuite/lib/*.o
+/testsuite/lib/*.a
+/testsuite/lib/*.so
+/testsuite/lib/*.obj
+/testsuite/lib/*.dll
+/testsuite/lib/*.cm[ioxat]
+/testsuite/lib/*.cmx[as]
+/testsuite/lib/*.cmti
+/testsuite/lib/*.annot
+/testsuite/lib/*.result
+/testsuite/lib/*.byte
+/testsuite/lib/*.native
+/testsuite/lib/program
+/testsuite/lib/*.exe
+/testsuite/lib/.depend
+/testsuite/lib/.depend.nt
+/testsuite/lib/.DS_Store
+
+# /testsuite/makefiles/
+/testsuite/makefiles/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/makefiles/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/makefiles/_log
+/testsuite/makefiles/*.so
+/testsuite/makefiles/*.a
+/testsuite/makefiles/*.result
+/testsuite/makefiles/*.byte
+/testsuite/makefiles/*.native
+/testsuite/makefiles/program
+/testsuite/makefiles/*.cm*
+/testsuite/makefiles/*.o
+
+# /testsuite/tests/
+/testsuite/tests/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/_log
+/testsuite/tests/*.so
+/testsuite/tests/*.a
+/testsuite/tests/*.result
+/testsuite/tests/*.byte
+/testsuite/tests/*.native
+/testsuite/tests/program
+/testsuite/tests/*.cm*
+/testsuite/tests/*.o
+
+# /testsuite/tests/asmcomp/
+/testsuite/tests/asmcomp/*.o
+/testsuite/tests/asmcomp/*.a
+/testsuite/tests/asmcomp/*.so
+/testsuite/tests/asmcomp/*.obj
+/testsuite/tests/asmcomp/*.lib
+/testsuite/tests/asmcomp/*.dll
+/testsuite/tests/asmcomp/*.cm[ioxat]
+/testsuite/tests/asmcomp/*.cmx[as]
+/testsuite/tests/asmcomp/*.cmti
+/testsuite/tests/asmcomp/*.annot
+/testsuite/tests/asmcomp/*.result
+/testsuite/tests/asmcomp/*.byte
+/testsuite/tests/asmcomp/*.native
+/testsuite/tests/asmcomp/program
+/testsuite/tests/asmcomp/*.exe
+/testsuite/tests/asmcomp/*.exe.manifest
+/testsuite/tests/asmcomp/.depend
+/testsuite/tests/asmcomp/.depend.nt
+/testsuite/tests/asmcomp/.DS_Store
+/testsuite/tests/asmcomp/codegen
+/testsuite/tests/asmcomp/parsecmm.ml
+/testsuite/tests/asmcomp/parsecmm.mli
+/testsuite/tests/asmcomp/lexcmm.ml
+/testsuite/tests/asmcomp/*.s
+/testsuite/tests/asmcomp/*.out
+/testsuite/tests/asmcomp/*.out.dSYM
+
+# /testsuite/tests/backtrace/
+/testsuite/tests/backtrace/*.o
+/testsuite/tests/backtrace/*.a
+/testsuite/tests/backtrace/*.so
+/testsuite/tests/backtrace/*.obj
+/testsuite/tests/backtrace/*.lib
+/testsuite/tests/backtrace/*.dll
+/testsuite/tests/backtrace/*.cm[ioxat]
+/testsuite/tests/backtrace/*.cmx[as]
+/testsuite/tests/backtrace/*.cmti
+/testsuite/tests/backtrace/*.annot
+/testsuite/tests/backtrace/*.result
+/testsuite/tests/backtrace/*.byte
+/testsuite/tests/backtrace/*.native
+/testsuite/tests/backtrace/program
+/testsuite/tests/backtrace/*.exe
+/testsuite/tests/backtrace/*.exe.manifest
+/testsuite/tests/backtrace/.depend
+/testsuite/tests/backtrace/.depend.nt
+/testsuite/tests/backtrace/.DS_Store
+
+# /testsuite/tests/basic/
+/testsuite/tests/basic/*.o
+/testsuite/tests/basic/*.a
+/testsuite/tests/basic/*.so
+/testsuite/tests/basic/*.obj
+/testsuite/tests/basic/*.cm[ioxa]
+/testsuite/tests/basic/*.cmx[as]
+/testsuite/tests/basic/*.annot
+/testsuite/tests/basic/*.result
+/testsuite/tests/basic/*.byte
+/testsuite/tests/basic/*.native
+/testsuite/tests/basic/program
+/testsuite/tests/basic/program.exe
+/testsuite/tests/basic/.depend
+/testsuite/tests/basic/.depend.nt
+/testsuite/tests/basic/.DS_Store
+
+# /testsuite/tests/basic-float/
+/testsuite/tests/basic-float/*.o
+/testsuite/tests/basic-float/*.a
+/testsuite/tests/basic-float/*.so
+/testsuite/tests/basic-float/*.obj
+/testsuite/tests/basic-float/*.lib
+/testsuite/tests/basic-float/*.dll
+/testsuite/tests/basic-float/*.cm[ioxat]
+/testsuite/tests/basic-float/*.cmx[as]
+/testsuite/tests/basic-float/*.cmti
+/testsuite/tests/basic-float/*.annot
+/testsuite/tests/basic-float/*.result
+/testsuite/tests/basic-float/*.byte
+/testsuite/tests/basic-float/*.native
+/testsuite/tests/basic-float/program
+/testsuite/tests/basic-float/*.exe
+/testsuite/tests/basic-float/*.exe.manifest
+/testsuite/tests/basic-float/.depend
+/testsuite/tests/basic-float/.depend.nt
+/testsuite/tests/basic-float/.DS_Store
+
+# /testsuite/tests/basic-io/
+/testsuite/tests/basic-io/*.o
+/testsuite/tests/basic-io/*.a
+/testsuite/tests/basic-io/*.so
+/testsuite/tests/basic-io/*.obj
+/testsuite/tests/basic-io/*.lib
+/testsuite/tests/basic-io/*.dll
+/testsuite/tests/basic-io/*.cm[ioxat]
+/testsuite/tests/basic-io/*.cmx[as]
+/testsuite/tests/basic-io/*.cmti
+/testsuite/tests/basic-io/*.annot
+/testsuite/tests/basic-io/*.result
+/testsuite/tests/basic-io/*.byte
+/testsuite/tests/basic-io/*.native
+/testsuite/tests/basic-io/program
+/testsuite/tests/basic-io/*.exe
+/testsuite/tests/basic-io/*.exe.manifest
+/testsuite/tests/basic-io/.depend
+/testsuite/tests/basic-io/.depend.nt
+/testsuite/tests/basic-io/.DS_Store
+
+# /testsuite/tests/basic-io-2/
+/testsuite/tests/basic-io-2/*.o
+/testsuite/tests/basic-io-2/*.a
+/testsuite/tests/basic-io-2/*.so
+/testsuite/tests/basic-io-2/*.obj
+/testsuite/tests/basic-io-2/*.lib
+/testsuite/tests/basic-io-2/*.dll
+/testsuite/tests/basic-io-2/*.cm[ioxat]
+/testsuite/tests/basic-io-2/*.cmx[as]
+/testsuite/tests/basic-io-2/*.cmti
+/testsuite/tests/basic-io-2/*.annot
+/testsuite/tests/basic-io-2/*.result
+/testsuite/tests/basic-io-2/*.byte
+/testsuite/tests/basic-io-2/*.native
+/testsuite/tests/basic-io-2/program
+/testsuite/tests/basic-io-2/*.exe
+/testsuite/tests/basic-io-2/*.exe.manifest
+/testsuite/tests/basic-io-2/.depend
+/testsuite/tests/basic-io-2/.depend.nt
+/testsuite/tests/basic-io-2/.DS_Store
+
+# /testsuite/tests/basic-manyargs/
+/testsuite/tests/basic-manyargs/*.o
+/testsuite/tests/basic-manyargs/*.a
+/testsuite/tests/basic-manyargs/*.so
+/testsuite/tests/basic-manyargs/*.obj
+/testsuite/tests/basic-manyargs/*.lib
+/testsuite/tests/basic-manyargs/*.dll
+/testsuite/tests/basic-manyargs/*.cm[ioxat]
+/testsuite/tests/basic-manyargs/*.cmx[as]
+/testsuite/tests/basic-manyargs/*.cmti
+/testsuite/tests/basic-manyargs/*.annot
+/testsuite/tests/basic-manyargs/*.result
+/testsuite/tests/basic-manyargs/*.byte
+/testsuite/tests/basic-manyargs/*.native
+/testsuite/tests/basic-manyargs/program
+/testsuite/tests/basic-manyargs/*.exe
+/testsuite/tests/basic-manyargs/*.exe.manifest
+/testsuite/tests/basic-manyargs/.depend
+/testsuite/tests/basic-manyargs/.depend.nt
+/testsuite/tests/basic-manyargs/.DS_Store
+
+# /testsuite/tests/basic-modules/
+/testsuite/tests/basic-modules/*.o
+/testsuite/tests/basic-modules/*.a
+/testsuite/tests/basic-modules/*.so
+/testsuite/tests/basic-modules/*.obj
+/testsuite/tests/basic-modules/*.lib
+/testsuite/tests/basic-modules/*.dll
+/testsuite/tests/basic-modules/*.cm[ioxat]
+/testsuite/tests/basic-modules/*.cmx[as]
+/testsuite/tests/basic-modules/*.cmti
+/testsuite/tests/basic-modules/*.annot
+/testsuite/tests/basic-modules/*.result
+/testsuite/tests/basic-modules/*.byte
+/testsuite/tests/basic-modules/*.native
+/testsuite/tests/basic-modules/program
+/testsuite/tests/basic-modules/*.exe
+/testsuite/tests/basic-modules/*.exe.manifest
+/testsuite/tests/basic-modules/.depend
+/testsuite/tests/basic-modules/.depend.nt
+/testsuite/tests/basic-modules/.DS_Store
+
+# /testsuite/tests/basic-more/
+/testsuite/tests/basic-more/*.o
+/testsuite/tests/basic-more/*.a
+/testsuite/tests/basic-more/*.so
+/testsuite/tests/basic-more/*.obj
+/testsuite/tests/basic-more/*.cm[ioxa]
+/testsuite/tests/basic-more/*.cmx[as]
+/testsuite/tests/basic-more/*.annot
+/testsuite/tests/basic-more/*.result
+/testsuite/tests/basic-more/*.byte
+/testsuite/tests/basic-more/*.native
+/testsuite/tests/basic-more/program
+/testsuite/tests/basic-more/program.exe
+/testsuite/tests/basic-more/.depend
+/testsuite/tests/basic-more/.depend.nt
+/testsuite/tests/basic-more/.DS_Store
+
+# /testsuite/tests/basic-multdef/
+/testsuite/tests/basic-multdef/*.o
+/testsuite/tests/basic-multdef/*.a
+/testsuite/tests/basic-multdef/*.so
+/testsuite/tests/basic-multdef/*.obj
+/testsuite/tests/basic-multdef/*.lib
+/testsuite/tests/basic-multdef/*.dll
+/testsuite/tests/basic-multdef/*.cm[ioxat]
+/testsuite/tests/basic-multdef/*.cmx[as]
+/testsuite/tests/basic-multdef/*.cmti
+/testsuite/tests/basic-multdef/*.annot
+/testsuite/tests/basic-multdef/*.result
+/testsuite/tests/basic-multdef/*.byte
+/testsuite/tests/basic-multdef/*.native
+/testsuite/tests/basic-multdef/program
+/testsuite/tests/basic-multdef/*.exe
+/testsuite/tests/basic-multdef/*.exe.manifest
+/testsuite/tests/basic-multdef/.depend
+/testsuite/tests/basic-multdef/.depend.nt
+/testsuite/tests/basic-multdef/.DS_Store
+
+# /testsuite/tests/basic-private/
+/testsuite/tests/basic-private/*.o
+/testsuite/tests/basic-private/*.a
+/testsuite/tests/basic-private/*.so
+/testsuite/tests/basic-private/*.obj
+/testsuite/tests/basic-private/*.lib
+/testsuite/tests/basic-private/*.dll
+/testsuite/tests/basic-private/*.cm[ioxat]
+/testsuite/tests/basic-private/*.cmx[as]
+/testsuite/tests/basic-private/*.cmti
+/testsuite/tests/basic-private/*.annot
+/testsuite/tests/basic-private/*.result
+/testsuite/tests/basic-private/*.byte
+/testsuite/tests/basic-private/*.native
+/testsuite/tests/basic-private/program
+/testsuite/tests/basic-private/*.exe
+/testsuite/tests/basic-private/*.exe.manifest
+/testsuite/tests/basic-private/.depend
+/testsuite/tests/basic-private/.depend.nt
+/testsuite/tests/basic-private/.DS_Store
+
+# /testsuite/tests/callback/
+/testsuite/tests/callback/*.o
+/testsuite/tests/callback/*.a
+/testsuite/tests/callback/*.so
+/testsuite/tests/callback/*.obj
+/testsuite/tests/callback/*.cm[ioxa]
+/testsuite/tests/callback/*.cmx[as]
+/testsuite/tests/callback/*.annot
+/testsuite/tests/callback/*.result
+/testsuite/tests/callback/*.byte
+/testsuite/tests/callback/*.native
+/testsuite/tests/callback/program
+/testsuite/tests/callback/program.exe
+/testsuite/tests/callback/.depend
+/testsuite/tests/callback/.depend.nt
+/testsuite/tests/callback/.DS_Store
+
+# /testsuite/tests/embedded/
+/testsuite/tests/embedded/*.o
+/testsuite/tests/embedded/*.a
+/testsuite/tests/embedded/*.so
+/testsuite/tests/embedded/*.obj
+/testsuite/tests/embedded/*.lib
+/testsuite/tests/embedded/*.dll
+/testsuite/tests/embedded/*.cm[ioxat]
+/testsuite/tests/embedded/*.cmx[as]
+/testsuite/tests/embedded/*.cmti
+/testsuite/tests/embedded/*.annot
+/testsuite/tests/embedded/*.result
+/testsuite/tests/embedded/*.byte
+/testsuite/tests/embedded/*.native
+/testsuite/tests/embedded/program
+/testsuite/tests/embedded/*.exe
+/testsuite/tests/embedded/*.exe.manifest
+/testsuite/tests/embedded/.depend
+/testsuite/tests/embedded/.depend.nt
+/testsuite/tests/embedded/.DS_Store
+/testsuite/tests/embedded/caml
+
+# /testsuite/tests/exotic-syntax/
+/testsuite/tests/exotic-syntax/*.o
+/testsuite/tests/exotic-syntax/*.a
+/testsuite/tests/exotic-syntax/*.so
+/testsuite/tests/exotic-syntax/*.obj
+/testsuite/tests/exotic-syntax/*.lib
+/testsuite/tests/exotic-syntax/*.dll
+/testsuite/tests/exotic-syntax/*.cm[ioxat]
+/testsuite/tests/exotic-syntax/*.cmx[as]
+/testsuite/tests/exotic-syntax/*.cmti
+/testsuite/tests/exotic-syntax/*.annot
+/testsuite/tests/exotic-syntax/*.result
+/testsuite/tests/exotic-syntax/*.byte
+/testsuite/tests/exotic-syntax/*.native
+/testsuite/tests/exotic-syntax/program
+/testsuite/tests/exotic-syntax/*.exe
+/testsuite/tests/exotic-syntax/*.exe.manifest
+/testsuite/tests/exotic-syntax/.depend
+/testsuite/tests/exotic-syntax/.depend.nt
+/testsuite/tests/exotic-syntax/.DS_Store
+
+# /testsuite/tests/formats-transition/
+/testsuite/tests/formats-transition/*.o
+/testsuite/tests/formats-transition/*.a
+/testsuite/tests/formats-transition/*.so
+/testsuite/tests/formats-transition/*.obj
+/testsuite/tests/formats-transition/*.lib
+/testsuite/tests/formats-transition/*.dll
+/testsuite/tests/formats-transition/*.cm[ioxat]
+/testsuite/tests/formats-transition/*.cmx[as]
+/testsuite/tests/formats-transition/*.cmti
+/testsuite/tests/formats-transition/*.annot
+/testsuite/tests/formats-transition/*.result
+/testsuite/tests/formats-transition/*.byte
+/testsuite/tests/formats-transition/*.native
+/testsuite/tests/formats-transition/program
+/testsuite/tests/formats-transition/*.exe
+/testsuite/tests/formats-transition/*.exe.manifest
+/testsuite/tests/formats-transition/.depend
+/testsuite/tests/formats-transition/.depend.nt
+/testsuite/tests/formats-transition/.DS_Store
+
+# /testsuite/tests/gc-roots/
+/testsuite/tests/gc-roots/*.o
+/testsuite/tests/gc-roots/*.a
+/testsuite/tests/gc-roots/*.so
+/testsuite/tests/gc-roots/*.obj
+/testsuite/tests/gc-roots/*.lib
+/testsuite/tests/gc-roots/*.dll
+/testsuite/tests/gc-roots/*.cm[ioxat]
+/testsuite/tests/gc-roots/*.cmx[as]
+/testsuite/tests/gc-roots/*.cmti
+/testsuite/tests/gc-roots/*.annot
+/testsuite/tests/gc-roots/*.result
+/testsuite/tests/gc-roots/*.byte
+/testsuite/tests/gc-roots/*.native
+/testsuite/tests/gc-roots/program
+/testsuite/tests/gc-roots/*.exe
+/testsuite/tests/gc-roots/*.exe.manifest
+/testsuite/tests/gc-roots/.depend
+/testsuite/tests/gc-roots/.depend.nt
+/testsuite/tests/gc-roots/.DS_Store
+
+# /testsuite/tests/letrec/
+/testsuite/tests/letrec/*.o
+/testsuite/tests/letrec/*.a
+/testsuite/tests/letrec/*.so
+/testsuite/tests/letrec/*.obj
+/testsuite/tests/letrec/*.cm[ioxa]
+/testsuite/tests/letrec/*.cmx[as]
+/testsuite/tests/letrec/*.annot
+/testsuite/tests/letrec/*.result
+/testsuite/tests/letrec/*.byte
+/testsuite/tests/letrec/*.native
+/testsuite/tests/letrec/program
+/testsuite/tests/letrec/program.exe
+/testsuite/tests/letrec/.depend
+/testsuite/tests/letrec/.depend.nt
+/testsuite/tests/letrec/.DS_Store
+
+# /testsuite/tests/lib-bigarray/
+/testsuite/tests/lib-bigarray/*.o
+/testsuite/tests/lib-bigarray/*.a
+/testsuite/tests/lib-bigarray/*.so
+/testsuite/tests/lib-bigarray/*.obj
+/testsuite/tests/lib-bigarray/*.lib
+/testsuite/tests/lib-bigarray/*.dll
+/testsuite/tests/lib-bigarray/*.cm[ioxat]
+/testsuite/tests/lib-bigarray/*.cmx[as]
+/testsuite/tests/lib-bigarray/*.cmti
+/testsuite/tests/lib-bigarray/*.annot
+/testsuite/tests/lib-bigarray/*.result
+/testsuite/tests/lib-bigarray/*.byte
+/testsuite/tests/lib-bigarray/*.native
+/testsuite/tests/lib-bigarray/program
+/testsuite/tests/lib-bigarray/*.exe
+/testsuite/tests/lib-bigarray/*.exe.manifest
+/testsuite/tests/lib-bigarray/.depend
+/testsuite/tests/lib-bigarray/.depend.nt
+/testsuite/tests/lib-bigarray/.DS_Store
+
+# /testsuite/tests/lib-bigarray-2/
+/testsuite/tests/lib-bigarray-2/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/lib-bigarray-2/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/lib-bigarray-2/_log
+/testsuite/tests/lib-bigarray-2/*.so
+/testsuite/tests/lib-bigarray-2/*.a
+/testsuite/tests/lib-bigarray-2/*.result
+/testsuite/tests/lib-bigarray-2/*.byte
+/testsuite/tests/lib-bigarray-2/*.native
+/testsuite/tests/lib-bigarray-2/program
+/testsuite/tests/lib-bigarray-2/*.cm*
+/testsuite/tests/lib-bigarray-2/*.o
+
+# /testsuite/tests/lib-digest/
+/testsuite/tests/lib-digest/*.o
+/testsuite/tests/lib-digest/*.a
+/testsuite/tests/lib-digest/*.so
+/testsuite/tests/lib-digest/*.obj
+/testsuite/tests/lib-digest/*.lib
+/testsuite/tests/lib-digest/*.dll
+/testsuite/tests/lib-digest/*.cm[ioxat]
+/testsuite/tests/lib-digest/*.cmx[as]
+/testsuite/tests/lib-digest/*.cmti
+/testsuite/tests/lib-digest/*.annot
+/testsuite/tests/lib-digest/*.result
+/testsuite/tests/lib-digest/*.byte
+/testsuite/tests/lib-digest/*.native
+/testsuite/tests/lib-digest/program
+/testsuite/tests/lib-digest/*.exe
+/testsuite/tests/lib-digest/*.exe.manifest
+/testsuite/tests/lib-digest/.depend
+/testsuite/tests/lib-digest/.depend.nt
+/testsuite/tests/lib-digest/.DS_Store
+
+# /testsuite/tests/lib-dynlink-bytecode/
+/testsuite/tests/lib-dynlink-bytecode/*.o
+/testsuite/tests/lib-dynlink-bytecode/*.a
+/testsuite/tests/lib-dynlink-bytecode/*.so
+/testsuite/tests/lib-dynlink-bytecode/*.obj
+/testsuite/tests/lib-dynlink-bytecode/*.lib
+/testsuite/tests/lib-dynlink-bytecode/*.dll
+/testsuite/tests/lib-dynlink-bytecode/*.cm[ioxat]
+/testsuite/tests/lib-dynlink-bytecode/*.cmx[as]
+/testsuite/tests/lib-dynlink-bytecode/*.cmti
+/testsuite/tests/lib-dynlink-bytecode/*.annot
+/testsuite/tests/lib-dynlink-bytecode/*.result
+/testsuite/tests/lib-dynlink-bytecode/*.byte
+/testsuite/tests/lib-dynlink-bytecode/*.native
+/testsuite/tests/lib-dynlink-bytecode/program
+/testsuite/tests/lib-dynlink-bytecode/*.exe
+/testsuite/tests/lib-dynlink-bytecode/*.exe.manifest
+/testsuite/tests/lib-dynlink-bytecode/.depend
+/testsuite/tests/lib-dynlink-bytecode/.depend.nt
+/testsuite/tests/lib-dynlink-bytecode/.DS_Store
+/testsuite/tests/lib-dynlink-bytecode/main
+/testsuite/tests/lib-dynlink-bytecode/static
+/testsuite/tests/lib-dynlink-bytecode/custom
+/testsuite/tests/lib-dynlink-bytecode/custom.exe
+/testsuite/tests/lib-dynlink-bytecode/marshal.data
+/testsuite/tests/lib-dynlink-bytecode/caml
+
+# /testsuite/tests/lib-dynlink-csharp/
+/testsuite/tests/lib-dynlink-csharp/*.o
+/testsuite/tests/lib-dynlink-csharp/*.a
+/testsuite/tests/lib-dynlink-csharp/*.so
+/testsuite/tests/lib-dynlink-csharp/*.obj
+/testsuite/tests/lib-dynlink-csharp/*.lib
+/testsuite/tests/lib-dynlink-csharp/*.dll
+/testsuite/tests/lib-dynlink-csharp/*.cm[ioxat]
+/testsuite/tests/lib-dynlink-csharp/*.cmx[as]
+/testsuite/tests/lib-dynlink-csharp/*.cmti
+/testsuite/tests/lib-dynlink-csharp/*.annot
+/testsuite/tests/lib-dynlink-csharp/*.result
+/testsuite/tests/lib-dynlink-csharp/*.byte
+/testsuite/tests/lib-dynlink-csharp/*.native
+/testsuite/tests/lib-dynlink-csharp/program
+/testsuite/tests/lib-dynlink-csharp/*.exe
+/testsuite/tests/lib-dynlink-csharp/*.exe.manifest
+/testsuite/tests/lib-dynlink-csharp/.depend
+/testsuite/tests/lib-dynlink-csharp/.depend.nt
+/testsuite/tests/lib-dynlink-csharp/.DS_Store
+
+# /testsuite/tests/lib-dynlink-native/
+/testsuite/tests/lib-dynlink-native/*.o
+/testsuite/tests/lib-dynlink-native/*.a
+/testsuite/tests/lib-dynlink-native/*.so
+/testsuite/tests/lib-dynlink-native/*.obj
+/testsuite/tests/lib-dynlink-native/*.lib
+/testsuite/tests/lib-dynlink-native/*.dll
+/testsuite/tests/lib-dynlink-native/*.cm[ioxat]
+/testsuite/tests/lib-dynlink-native/*.cmx[as]
+/testsuite/tests/lib-dynlink-native/*.cmti
+/testsuite/tests/lib-dynlink-native/*.annot
+/testsuite/tests/lib-dynlink-native/*.result
+/testsuite/tests/lib-dynlink-native/*.byte
+/testsuite/tests/lib-dynlink-native/*.native
+/testsuite/tests/lib-dynlink-native/program
+/testsuite/tests/lib-dynlink-native/*.exe
+/testsuite/tests/lib-dynlink-native/*.exe.manifest
+/testsuite/tests/lib-dynlink-native/.depend
+/testsuite/tests/lib-dynlink-native/.depend.nt
+/testsuite/tests/lib-dynlink-native/.DS_Store
+/testsuite/tests/lib-dynlink-native/mypack.pack.s
+/testsuite/tests/lib-dynlink-native/mypack.pack.asm
+/testsuite/tests/lib-dynlink-native/result
+/testsuite/tests/lib-dynlink-native/main
+/testsuite/tests/lib-dynlink-native/main.exe
+/testsuite/tests/lib-dynlink-native/marshal.data
+/testsuite/tests/lib-dynlink-native/caml
+
+# /testsuite/tests/lib-dynlink-native/sub/
+/testsuite/tests/lib-dynlink-native/sub/*.o
+/testsuite/tests/lib-dynlink-native/sub/*.a
+/testsuite/tests/lib-dynlink-native/sub/*.so
+/testsuite/tests/lib-dynlink-native/sub/*.obj
+/testsuite/tests/lib-dynlink-native/sub/*.lib
+/testsuite/tests/lib-dynlink-native/sub/*.dll
+/testsuite/tests/lib-dynlink-native/sub/*.cm[ioxat]
+/testsuite/tests/lib-dynlink-native/sub/*.cmx[as]
+/testsuite/tests/lib-dynlink-native/sub/*.cmti
+/testsuite/tests/lib-dynlink-native/sub/*.annot
+/testsuite/tests/lib-dynlink-native/sub/*.result
+/testsuite/tests/lib-dynlink-native/sub/*.byte
+/testsuite/tests/lib-dynlink-native/sub/*.native
+/testsuite/tests/lib-dynlink-native/sub/program
+/testsuite/tests/lib-dynlink-native/sub/*.exe
+/testsuite/tests/lib-dynlink-native/sub/*.exe.manifest
+/testsuite/tests/lib-dynlink-native/sub/.depend
+/testsuite/tests/lib-dynlink-native/sub/.depend.nt
+/testsuite/tests/lib-dynlink-native/sub/.DS_Store
+
+# /testsuite/tests/lib-format/
+/testsuite/tests/lib-format/*.o
+/testsuite/tests/lib-format/*.a
+/testsuite/tests/lib-format/*.so
+/testsuite/tests/lib-format/*.obj
+/testsuite/tests/lib-format/*.lib
+/testsuite/tests/lib-format/*.dll
+/testsuite/tests/lib-format/*.cm[ioxat]
+/testsuite/tests/lib-format/*.cmx[as]
+/testsuite/tests/lib-format/*.cmti
+/testsuite/tests/lib-format/*.annot
+/testsuite/tests/lib-format/*.result
+/testsuite/tests/lib-format/*.byte
+/testsuite/tests/lib-format/*.native
+/testsuite/tests/lib-format/program
+/testsuite/tests/lib-format/*.exe
+/testsuite/tests/lib-format/*.exe.manifest
+/testsuite/tests/lib-format/.depend
+/testsuite/tests/lib-format/.depend.nt
+/testsuite/tests/lib-format/.DS_Store
+
+# /testsuite/tests/lib-hashtbl/
+/testsuite/tests/lib-hashtbl/*.o
+/testsuite/tests/lib-hashtbl/*.a
+/testsuite/tests/lib-hashtbl/*.so
+/testsuite/tests/lib-hashtbl/*.obj
+/testsuite/tests/lib-hashtbl/*.cm[ioxa]
+/testsuite/tests/lib-hashtbl/*.cmx[as]
+/testsuite/tests/lib-hashtbl/*.annot
+/testsuite/tests/lib-hashtbl/*.result
+/testsuite/tests/lib-hashtbl/*.byte
+/testsuite/tests/lib-hashtbl/*.native
+/testsuite/tests/lib-hashtbl/program
+/testsuite/tests/lib-hashtbl/program.exe
+/testsuite/tests/lib-hashtbl/.depend
+/testsuite/tests/lib-hashtbl/.depend.nt
+/testsuite/tests/lib-hashtbl/.DS_Store
+
+# /testsuite/tests/lib-marshal/
+/testsuite/tests/lib-marshal/*.o
+/testsuite/tests/lib-marshal/*.a
+/testsuite/tests/lib-marshal/*.so
+/testsuite/tests/lib-marshal/*.obj
+/testsuite/tests/lib-marshal/*.lib
+/testsuite/tests/lib-marshal/*.dll
+/testsuite/tests/lib-marshal/*.cm[ioxat]
+/testsuite/tests/lib-marshal/*.cmx[as]
+/testsuite/tests/lib-marshal/*.cmti
+/testsuite/tests/lib-marshal/*.annot
+/testsuite/tests/lib-marshal/*.result
+/testsuite/tests/lib-marshal/*.byte
+/testsuite/tests/lib-marshal/*.native
+/testsuite/tests/lib-marshal/program
+/testsuite/tests/lib-marshal/*.exe
+/testsuite/tests/lib-marshal/*.exe.manifest
+/testsuite/tests/lib-marshal/.depend
+/testsuite/tests/lib-marshal/.depend.nt
+/testsuite/tests/lib-marshal/.DS_Store
+
+# /testsuite/tests/lib-num/
+/testsuite/tests/lib-num/*.o
+/testsuite/tests/lib-num/*.a
+/testsuite/tests/lib-num/*.so
+/testsuite/tests/lib-num/*.obj
+/testsuite/tests/lib-num/*.lib
+/testsuite/tests/lib-num/*.dll
+/testsuite/tests/lib-num/*.cm[ioxat]
+/testsuite/tests/lib-num/*.cmx[as]
+/testsuite/tests/lib-num/*.cmti
+/testsuite/tests/lib-num/*.annot
+/testsuite/tests/lib-num/*.result
+/testsuite/tests/lib-num/*.byte
+/testsuite/tests/lib-num/*.native
+/testsuite/tests/lib-num/program
+/testsuite/tests/lib-num/*.exe
+/testsuite/tests/lib-num/*.exe.manifest
+/testsuite/tests/lib-num/.depend
+/testsuite/tests/lib-num/.depend.nt
+/testsuite/tests/lib-num/.DS_Store
+
+# /testsuite/tests/lib-num-2/
+/testsuite/tests/lib-num-2/*.o
+/testsuite/tests/lib-num-2/*.a
+/testsuite/tests/lib-num-2/*.so
+/testsuite/tests/lib-num-2/*.obj
+/testsuite/tests/lib-num-2/*.cm[ioxa]
+/testsuite/tests/lib-num-2/*.cmx[as]
+/testsuite/tests/lib-num-2/*.annot
+/testsuite/tests/lib-num-2/*.result
+/testsuite/tests/lib-num-2/*.byte
+/testsuite/tests/lib-num-2/*.native
+/testsuite/tests/lib-num-2/program
+/testsuite/tests/lib-num-2/program.exe
+/testsuite/tests/lib-num-2/.depend
+/testsuite/tests/lib-num-2/.depend.nt
+/testsuite/tests/lib-num-2/.DS_Store
+
+# /testsuite/tests/lib-printf/
+/testsuite/tests/lib-printf/*.o
+/testsuite/tests/lib-printf/*.a
+/testsuite/tests/lib-printf/*.so
+/testsuite/tests/lib-printf/*.obj
+/testsuite/tests/lib-printf/*.lib
+/testsuite/tests/lib-printf/*.dll
+/testsuite/tests/lib-printf/*.cm[ioxat]
+/testsuite/tests/lib-printf/*.cmx[as]
+/testsuite/tests/lib-printf/*.cmti
+/testsuite/tests/lib-printf/*.annot
+/testsuite/tests/lib-printf/*.result
+/testsuite/tests/lib-printf/*.byte
+/testsuite/tests/lib-printf/*.native
+/testsuite/tests/lib-printf/program
+/testsuite/tests/lib-printf/*.exe
+/testsuite/tests/lib-printf/*.exe.manifest
+/testsuite/tests/lib-printf/.depend
+/testsuite/tests/lib-printf/.depend.nt
+/testsuite/tests/lib-printf/.DS_Store
+
+# /testsuite/tests/lib-random/
+/testsuite/tests/lib-random/*.o
+/testsuite/tests/lib-random/*.a
+/testsuite/tests/lib-random/*.so
+/testsuite/tests/lib-random/*.obj
+/testsuite/tests/lib-random/*.lib
+/testsuite/tests/lib-random/*.dll
+/testsuite/tests/lib-random/*.cm[ioxat]
+/testsuite/tests/lib-random/*.cmx[as]
+/testsuite/tests/lib-random/*.cmti
+/testsuite/tests/lib-random/*.annot
+/testsuite/tests/lib-random/*.result
+/testsuite/tests/lib-random/*.byte
+/testsuite/tests/lib-random/*.native
+/testsuite/tests/lib-random/program
+/testsuite/tests/lib-random/*.exe
+/testsuite/tests/lib-random/*.exe.manifest
+/testsuite/tests/lib-random/.depend
+/testsuite/tests/lib-random/.depend.nt
+/testsuite/tests/lib-random/.DS_Store
+
+# /testsuite/tests/lib-scanf/
+/testsuite/tests/lib-scanf/*.o
+/testsuite/tests/lib-scanf/*.a
+/testsuite/tests/lib-scanf/*.so
+/testsuite/tests/lib-scanf/*.obj
+/testsuite/tests/lib-scanf/*.lib
+/testsuite/tests/lib-scanf/*.dll
+/testsuite/tests/lib-scanf/*.cm[ioxat]
+/testsuite/tests/lib-scanf/*.cmx[as]
+/testsuite/tests/lib-scanf/*.cmti
+/testsuite/tests/lib-scanf/*.annot
+/testsuite/tests/lib-scanf/*.result
+/testsuite/tests/lib-scanf/*.byte
+/testsuite/tests/lib-scanf/*.native
+/testsuite/tests/lib-scanf/program
+/testsuite/tests/lib-scanf/*.exe
+/testsuite/tests/lib-scanf/*.exe.manifest
+/testsuite/tests/lib-scanf/.depend
+/testsuite/tests/lib-scanf/.depend.nt
+/testsuite/tests/lib-scanf/.DS_Store
+/testsuite/tests/lib-scanf/tscanf_data
+
+# /testsuite/tests/lib-scanf-2/
+/testsuite/tests/lib-scanf-2/*.o
+/testsuite/tests/lib-scanf-2/*.a
+/testsuite/tests/lib-scanf-2/*.so
+/testsuite/tests/lib-scanf-2/*.obj
+/testsuite/tests/lib-scanf-2/*.lib
+/testsuite/tests/lib-scanf-2/*.dll
+/testsuite/tests/lib-scanf-2/*.cm[ioxat]
+/testsuite/tests/lib-scanf-2/*.cmx[as]
+/testsuite/tests/lib-scanf-2/*.cmti
+/testsuite/tests/lib-scanf-2/*.annot
+/testsuite/tests/lib-scanf-2/*.result
+/testsuite/tests/lib-scanf-2/*.byte
+/testsuite/tests/lib-scanf-2/*.native
+/testsuite/tests/lib-scanf-2/program
+/testsuite/tests/lib-scanf-2/*.exe
+/testsuite/tests/lib-scanf-2/*.exe.manifest
+/testsuite/tests/lib-scanf-2/.depend
+/testsuite/tests/lib-scanf-2/.depend.nt
+/testsuite/tests/lib-scanf-2/.DS_Store
+
+# /testsuite/tests/lib-set/
+/testsuite/tests/lib-set/*.o
+/testsuite/tests/lib-set/*.a
+/testsuite/tests/lib-set/*.so
+/testsuite/tests/lib-set/*.obj
+/testsuite/tests/lib-set/*.cm[ioxa]
+/testsuite/tests/lib-set/*.cmx[as]
+/testsuite/tests/lib-set/*.annot
+/testsuite/tests/lib-set/*.result
+/testsuite/tests/lib-set/*.byte
+/testsuite/tests/lib-set/*.native
+/testsuite/tests/lib-set/program
+/testsuite/tests/lib-set/program.exe
+/testsuite/tests/lib-set/.depend
+/testsuite/tests/lib-set/.depend.nt
+/testsuite/tests/lib-set/.DS_Store
+
+# /testsuite/tests/lib-str/
+/testsuite/tests/lib-str/*.o
+/testsuite/tests/lib-str/*.a
+/testsuite/tests/lib-str/*.so
+/testsuite/tests/lib-str/*.obj
+/testsuite/tests/lib-str/*.cm[ioxa]
+/testsuite/tests/lib-str/*.cmx[as]
+/testsuite/tests/lib-str/*.annot
+/testsuite/tests/lib-str/*.result
+/testsuite/tests/lib-str/*.byte
+/testsuite/tests/lib-str/*.native
+/testsuite/tests/lib-str/program
+/testsuite/tests/lib-str/program.exe
+/testsuite/tests/lib-str/.depend
+/testsuite/tests/lib-str/.depend.nt
+/testsuite/tests/lib-str/.DS_Store
+
+# /testsuite/tests/lib-stream/
+/testsuite/tests/lib-stream/*.o
+/testsuite/tests/lib-stream/*.a
+/testsuite/tests/lib-stream/*.so
+/testsuite/tests/lib-stream/*.obj
+/testsuite/tests/lib-stream/*.cm[ioxa]
+/testsuite/tests/lib-stream/*.cmx[as]
+/testsuite/tests/lib-stream/*.annot
+/testsuite/tests/lib-stream/*.result
+/testsuite/tests/lib-stream/*.byte
+/testsuite/tests/lib-stream/*.native
+/testsuite/tests/lib-stream/program
+/testsuite/tests/lib-stream/program.exe
+/testsuite/tests/lib-stream/.depend
+/testsuite/tests/lib-stream/.depend.nt
+/testsuite/tests/lib-stream/.DS_Store
+
+# /testsuite/tests/lib-systhreads/
+/testsuite/tests/lib-systhreads/*.o
+/testsuite/tests/lib-systhreads/*.a
+/testsuite/tests/lib-systhreads/*.so
+/testsuite/tests/lib-systhreads/*.obj
+/testsuite/tests/lib-systhreads/*.cm[ioxa]
+/testsuite/tests/lib-systhreads/*.cmx[as]
+/testsuite/tests/lib-systhreads/*.annot
+/testsuite/tests/lib-systhreads/*.result
+/testsuite/tests/lib-systhreads/*.byte
+/testsuite/tests/lib-systhreads/*.native
+/testsuite/tests/lib-systhreads/program
+/testsuite/tests/lib-systhreads/program.exe
+/testsuite/tests/lib-systhreads/.depend
+/testsuite/tests/lib-systhreads/.depend.nt
+/testsuite/tests/lib-systhreads/.DS_Store
+
+# /testsuite/tests/lib-threads/
+/testsuite/tests/lib-threads/*.o
+/testsuite/tests/lib-threads/*.a
+/testsuite/tests/lib-threads/*.so
+/testsuite/tests/lib-threads/*.obj
+/testsuite/tests/lib-threads/*.cm[ioxa]
+/testsuite/tests/lib-threads/*.cmx[as]
+/testsuite/tests/lib-threads/*.annot
+/testsuite/tests/lib-threads/*.result
+/testsuite/tests/lib-threads/*.byte
+/testsuite/tests/lib-threads/*.native
+/testsuite/tests/lib-threads/program
+/testsuite/tests/lib-threads/program.exe
+/testsuite/tests/lib-threads/.depend
+/testsuite/tests/lib-threads/.depend.nt
+/testsuite/tests/lib-threads/.DS_Store
+/testsuite/tests/lib-threads/*.byt
+
+# /testsuite/tests/match-exception/
+/testsuite/tests/match-exception/*.o
+/testsuite/tests/match-exception/*.a
+/testsuite/tests/match-exception/*.so
+/testsuite/tests/match-exception/*.obj
+/testsuite/tests/match-exception/*.lib
+/testsuite/tests/match-exception/*.dll
+/testsuite/tests/match-exception/*.cm[ioxat]
+/testsuite/tests/match-exception/*.cmx[as]
+/testsuite/tests/match-exception/*.cmti
+/testsuite/tests/match-exception/*.annot
+/testsuite/tests/match-exception/*.result
+/testsuite/tests/match-exception/*.byte
+/testsuite/tests/match-exception/*.native
+/testsuite/tests/match-exception/program
+/testsuite/tests/match-exception/*.exe
+/testsuite/tests/match-exception/*.exe.manifest
+/testsuite/tests/match-exception/.depend
+/testsuite/tests/match-exception/.depend.nt
+/testsuite/tests/match-exception/.DS_Store
+
+# /testsuite/tests/match-exception-warnings/
+/testsuite/tests/match-exception-warnings/*.o
+/testsuite/tests/match-exception-warnings/*.a
+/testsuite/tests/match-exception-warnings/*.so
+/testsuite/tests/match-exception-warnings/*.obj
+/testsuite/tests/match-exception-warnings/*.lib
+/testsuite/tests/match-exception-warnings/*.dll
+/testsuite/tests/match-exception-warnings/*.cm[ioxat]
+/testsuite/tests/match-exception-warnings/*.cmx[as]
+/testsuite/tests/match-exception-warnings/*.cmti
+/testsuite/tests/match-exception-warnings/*.annot
+/testsuite/tests/match-exception-warnings/*.result
+/testsuite/tests/match-exception-warnings/*.byte
+/testsuite/tests/match-exception-warnings/*.native
+/testsuite/tests/match-exception-warnings/program
+/testsuite/tests/match-exception-warnings/*.exe
+/testsuite/tests/match-exception-warnings/*.exe.manifest
+/testsuite/tests/match-exception-warnings/.depend
+/testsuite/tests/match-exception-warnings/.depend.nt
+/testsuite/tests/match-exception-warnings/.DS_Store
+
+# /testsuite/tests/misc/
+/testsuite/tests/misc/*.o
+/testsuite/tests/misc/*.a
+/testsuite/tests/misc/*.so
+/testsuite/tests/misc/*.obj
+/testsuite/tests/misc/*.cm[ioxa]
+/testsuite/tests/misc/*.cmx[as]
+/testsuite/tests/misc/*.annot
+/testsuite/tests/misc/*.result
+/testsuite/tests/misc/*.byte
+/testsuite/tests/misc/*.native
+/testsuite/tests/misc/program
+/testsuite/tests/misc/program.exe
+/testsuite/tests/misc/.depend
+/testsuite/tests/misc/.depend.nt
+/testsuite/tests/misc/.DS_Store
+
+# /testsuite/tests/misc-kb/
+/testsuite/tests/misc-kb/*.o
+/testsuite/tests/misc-kb/*.a
+/testsuite/tests/misc-kb/*.so
+/testsuite/tests/misc-kb/*.obj
+/testsuite/tests/misc-kb/*.lib
+/testsuite/tests/misc-kb/*.dll
+/testsuite/tests/misc-kb/*.cm[ioxat]
+/testsuite/tests/misc-kb/*.cmx[as]
+/testsuite/tests/misc-kb/*.cmti
+/testsuite/tests/misc-kb/*.annot
+/testsuite/tests/misc-kb/*.result
+/testsuite/tests/misc-kb/*.byte
+/testsuite/tests/misc-kb/*.native
+/testsuite/tests/misc-kb/program
+/testsuite/tests/misc-kb/*.exe
+/testsuite/tests/misc-kb/*.exe.manifest
+/testsuite/tests/misc-kb/.depend
+/testsuite/tests/misc-kb/.depend.nt
+/testsuite/tests/misc-kb/.DS_Store
+
+# /testsuite/tests/misc-unsafe/
+/testsuite/tests/misc-unsafe/*.o
+/testsuite/tests/misc-unsafe/*.a
+/testsuite/tests/misc-unsafe/*.so
+/testsuite/tests/misc-unsafe/*.obj
+/testsuite/tests/misc-unsafe/*.cm[ioxa]
+/testsuite/tests/misc-unsafe/*.cmx[as]
+/testsuite/tests/misc-unsafe/*.annot
+/testsuite/tests/misc-unsafe/*.result
+/testsuite/tests/misc-unsafe/*.byte
+/testsuite/tests/misc-unsafe/*.native
+/testsuite/tests/misc-unsafe/program
+/testsuite/tests/misc-unsafe/program.exe
+/testsuite/tests/misc-unsafe/.depend
+/testsuite/tests/misc-unsafe/.depend.nt
+/testsuite/tests/misc-unsafe/.DS_Store
+
+# /testsuite/tests/ppx-attributes/
+/testsuite/tests/ppx-attributes/*.o
+/testsuite/tests/ppx-attributes/*.a
+/testsuite/tests/ppx-attributes/*.so
+/testsuite/tests/ppx-attributes/*.obj
+/testsuite/tests/ppx-attributes/*.lib
+/testsuite/tests/ppx-attributes/*.dll
+/testsuite/tests/ppx-attributes/*.cm[ioxat]
+/testsuite/tests/ppx-attributes/*.cmx[as]
+/testsuite/tests/ppx-attributes/*.cmti
+/testsuite/tests/ppx-attributes/*.annot
+/testsuite/tests/ppx-attributes/*.result
+/testsuite/tests/ppx-attributes/*.byte
+/testsuite/tests/ppx-attributes/*.native
+/testsuite/tests/ppx-attributes/program
+/testsuite/tests/ppx-attributes/*.exe
+/testsuite/tests/ppx-attributes/*.exe.manifest
+/testsuite/tests/ppx-attributes/.depend
+/testsuite/tests/ppx-attributes/.depend.nt
+/testsuite/tests/ppx-attributes/.DS_Store
+
+# /testsuite/tests/prim-bigstring/
+/testsuite/tests/prim-bigstring/*.o
+/testsuite/tests/prim-bigstring/*.a
+/testsuite/tests/prim-bigstring/*.so
+/testsuite/tests/prim-bigstring/*.obj
+/testsuite/tests/prim-bigstring/*.lib
+/testsuite/tests/prim-bigstring/*.dll
+/testsuite/tests/prim-bigstring/*.cm[ioxat]
+/testsuite/tests/prim-bigstring/*.cmx[as]
+/testsuite/tests/prim-bigstring/*.cmti
+/testsuite/tests/prim-bigstring/*.annot
+/testsuite/tests/prim-bigstring/*.result
+/testsuite/tests/prim-bigstring/*.byte
+/testsuite/tests/prim-bigstring/*.native
+/testsuite/tests/prim-bigstring/program
+/testsuite/tests/prim-bigstring/*.exe
+/testsuite/tests/prim-bigstring/*.exe.manifest
+/testsuite/tests/prim-bigstring/.depend
+/testsuite/tests/prim-bigstring/.depend.nt
+/testsuite/tests/prim-bigstring/.DS_Store
+
+# /testsuite/tests/prim-bswap/
+/testsuite/tests/prim-bswap/*.o
+/testsuite/tests/prim-bswap/*.a
+/testsuite/tests/prim-bswap/*.so
+/testsuite/tests/prim-bswap/*.obj
+/testsuite/tests/prim-bswap/*.cm[ioxat]
+/testsuite/tests/prim-bswap/*.cmx[as]
+/testsuite/tests/prim-bswap/*.cmti
+/testsuite/tests/prim-bswap/*.annot
+/testsuite/tests/prim-bswap/*.result
+/testsuite/tests/prim-bswap/*.byte
+/testsuite/tests/prim-bswap/*.native
+/testsuite/tests/prim-bswap/program
+/testsuite/tests/prim-bswap/program.exe
+/testsuite/tests/prim-bswap/.depend
+/testsuite/tests/prim-bswap/.depend.nt
+/testsuite/tests/prim-bswap/.DS_Store
+
+# /testsuite/tests/prim-revapply/
+/testsuite/tests/prim-revapply/*.o
+/testsuite/tests/prim-revapply/*.a
+/testsuite/tests/prim-revapply/*.so
+/testsuite/tests/prim-revapply/*.obj
+/testsuite/tests/prim-revapply/*.cm[ioxa]
+/testsuite/tests/prim-revapply/*.cmx[as]
+/testsuite/tests/prim-revapply/*.annot
+/testsuite/tests/prim-revapply/*.result
+/testsuite/tests/prim-revapply/*.byte
+/testsuite/tests/prim-revapply/*.native
+/testsuite/tests/prim-revapply/program
+/testsuite/tests/prim-revapply/program.exe
+/testsuite/tests/prim-revapply/.depend
+/testsuite/tests/prim-revapply/.depend.nt
+/testsuite/tests/prim-revapply/.DS_Store
+
+# /testsuite/tests/regression/pr5080-notes/
+/testsuite/tests/regression/pr5080-notes/*.o
+/testsuite/tests/regression/pr5080-notes/*.a
+/testsuite/tests/regression/pr5080-notes/*.so
+/testsuite/tests/regression/pr5080-notes/*.obj
+/testsuite/tests/regression/pr5080-notes/*.cm[ioxa]
+/testsuite/tests/regression/pr5080-notes/*.cmx[as]
+/testsuite/tests/regression/pr5080-notes/*.annot
+/testsuite/tests/regression/pr5080-notes/*.result
+/testsuite/tests/regression/pr5080-notes/*.byte
+/testsuite/tests/regression/pr5080-notes/*.native
+/testsuite/tests/regression/pr5080-notes/program
+/testsuite/tests/regression/pr5080-notes/program.exe
+/testsuite/tests/regression/pr5080-notes/.depend
+/testsuite/tests/regression/pr5080-notes/.depend.nt
+/testsuite/tests/regression/pr5080-notes/.DS_Store
+
+# /testsuite/tests/regression/pr5233/
+/testsuite/tests/regression/pr5233/*.o
+/testsuite/tests/regression/pr5233/*.a
+/testsuite/tests/regression/pr5233/*.so
+/testsuite/tests/regression/pr5233/*.obj
+/testsuite/tests/regression/pr5233/*.lib
+/testsuite/tests/regression/pr5233/*.dll
+/testsuite/tests/regression/pr5233/*.cm[ioxat]
+/testsuite/tests/regression/pr5233/*.cmx[as]
+/testsuite/tests/regression/pr5233/*.cmti
+/testsuite/tests/regression/pr5233/*.annot
+/testsuite/tests/regression/pr5233/*.result
+/testsuite/tests/regression/pr5233/*.byte
+/testsuite/tests/regression/pr5233/*.native
+/testsuite/tests/regression/pr5233/program
+/testsuite/tests/regression/pr5233/*.exe
+/testsuite/tests/regression/pr5233/*.exe.manifest
+/testsuite/tests/regression/pr5233/.depend
+/testsuite/tests/regression/pr5233/.depend.nt
+/testsuite/tests/regression/pr5233/.DS_Store
+
+# /testsuite/tests/regression/pr5757/
+/testsuite/tests/regression/pr5757/*.o
+/testsuite/tests/regression/pr5757/*.a
+/testsuite/tests/regression/pr5757/*.so
+/testsuite/tests/regression/pr5757/*.obj
+/testsuite/tests/regression/pr5757/*.lib
+/testsuite/tests/regression/pr5757/*.dll
+/testsuite/tests/regression/pr5757/*.cm[ioxat]
+/testsuite/tests/regression/pr5757/*.cmx[as]
+/testsuite/tests/regression/pr5757/*.cmti
+/testsuite/tests/regression/pr5757/*.annot
+/testsuite/tests/regression/pr5757/*.result
+/testsuite/tests/regression/pr5757/*.byte
+/testsuite/tests/regression/pr5757/*.native
+/testsuite/tests/regression/pr5757/program
+/testsuite/tests/regression/pr5757/*.exe
+/testsuite/tests/regression/pr5757/*.exe.manifest
+/testsuite/tests/regression/pr5757/.depend
+/testsuite/tests/regression/pr5757/.depend.nt
+/testsuite/tests/regression/pr5757/.DS_Store
+
+# /testsuite/tests/regression/pr6024/
+/testsuite/tests/regression/pr6024/*.o
+/testsuite/tests/regression/pr6024/*.a
+/testsuite/tests/regression/pr6024/*.so
+/testsuite/tests/regression/pr6024/*.obj
+/testsuite/tests/regression/pr6024/*.lib
+/testsuite/tests/regression/pr6024/*.dll
+/testsuite/tests/regression/pr6024/*.cm[ioxat]
+/testsuite/tests/regression/pr6024/*.cmx[as]
+/testsuite/tests/regression/pr6024/*.cmti
+/testsuite/tests/regression/pr6024/*.annot
+/testsuite/tests/regression/pr6024/*.result
+/testsuite/tests/regression/pr6024/*.byte
+/testsuite/tests/regression/pr6024/*.native
+/testsuite/tests/regression/pr6024/program
+/testsuite/tests/regression/pr6024/*.exe
+/testsuite/tests/regression/pr6024/*.exe.manifest
+/testsuite/tests/regression/pr6024/.depend
+/testsuite/tests/regression/pr6024/.depend.nt
+/testsuite/tests/regression/pr6024/.DS_Store
+
+# /testsuite/tests/runtime-errors/
+/testsuite/tests/runtime-errors/*.o
+/testsuite/tests/runtime-errors/*.a
+/testsuite/tests/runtime-errors/*.so
+/testsuite/tests/runtime-errors/*.obj
+/testsuite/tests/runtime-errors/*.lib
+/testsuite/tests/runtime-errors/*.dll
+/testsuite/tests/runtime-errors/*.cm[ioxat]
+/testsuite/tests/runtime-errors/*.cmx[as]
+/testsuite/tests/runtime-errors/*.cmti
+/testsuite/tests/runtime-errors/*.annot
+/testsuite/tests/runtime-errors/*.result
+/testsuite/tests/runtime-errors/*.byte
+/testsuite/tests/runtime-errors/*.native
+/testsuite/tests/runtime-errors/program
+/testsuite/tests/runtime-errors/*.exe
+/testsuite/tests/runtime-errors/*.exe.manifest
+/testsuite/tests/runtime-errors/.depend
+/testsuite/tests/runtime-errors/.depend.nt
+/testsuite/tests/runtime-errors/.DS_Store
+/testsuite/tests/runtime-errors/*.bytecode
+
+# /testsuite/tests/tool-debugger/
+/testsuite/tests/tool-debugger/*.o
+/testsuite/tests/tool-debugger/*.a
+/testsuite/tests/tool-debugger/*.so
+/testsuite/tests/tool-debugger/*.obj
+/testsuite/tests/tool-debugger/*.lib
+/testsuite/tests/tool-debugger/*.dll
+/testsuite/tests/tool-debugger/*.cm[ioxat]
+/testsuite/tests/tool-debugger/*.cmx[as]
+/testsuite/tests/tool-debugger/*.cmti
+/testsuite/tests/tool-debugger/*.annot
+/testsuite/tests/tool-debugger/*.result
+/testsuite/tests/tool-debugger/*.byte
+/testsuite/tests/tool-debugger/*.native
+/testsuite/tests/tool-debugger/program
+/testsuite/tests/tool-debugger/*.exe
+/testsuite/tests/tool-debugger/*.exe.manifest
+/testsuite/tests/tool-debugger/.depend
+/testsuite/tests/tool-debugger/.depend.nt
+/testsuite/tests/tool-debugger/.DS_Store
+/testsuite/tests/tool-debugger/compiler-libs
+
+# /testsuite/tests/tool-debugger/basic/
+/testsuite/tests/tool-debugger/basic/*.o
+/testsuite/tests/tool-debugger/basic/*.a
+/testsuite/tests/tool-debugger/basic/*.so
+/testsuite/tests/tool-debugger/basic/*.obj
+/testsuite/tests/tool-debugger/basic/*.lib
+/testsuite/tests/tool-debugger/basic/*.dll
+/testsuite/tests/tool-debugger/basic/*.cm[ioxat]
+/testsuite/tests/tool-debugger/basic/*.cmx[as]
+/testsuite/tests/tool-debugger/basic/*.cmti
+/testsuite/tests/tool-debugger/basic/*.annot
+/testsuite/tests/tool-debugger/basic/*.result
+/testsuite/tests/tool-debugger/basic/*.byte
+/testsuite/tests/tool-debugger/basic/*.native
+/testsuite/tests/tool-debugger/basic/program
+/testsuite/tests/tool-debugger/basic/*.exe
+/testsuite/tests/tool-debugger/basic/*.exe.manifest
+/testsuite/tests/tool-debugger/basic/.depend
+/testsuite/tests/tool-debugger/basic/.depend.nt
+/testsuite/tests/tool-debugger/basic/.DS_Store
+/testsuite/tests/tool-debugger/basic/compiler-libs
+
+# /testsuite/tests/tool-debugger/find-artifacts/
+/testsuite/tests/tool-debugger/find-artifacts/*.o
+/testsuite/tests/tool-debugger/find-artifacts/*.a
+/testsuite/tests/tool-debugger/find-artifacts/*.so
+/testsuite/tests/tool-debugger/find-artifacts/*.obj
+/testsuite/tests/tool-debugger/find-artifacts/*.lib
+/testsuite/tests/tool-debugger/find-artifacts/*.dll
+/testsuite/tests/tool-debugger/find-artifacts/*.cm[ioxat]
+/testsuite/tests/tool-debugger/find-artifacts/*.cmx[as]
+/testsuite/tests/tool-debugger/find-artifacts/*.cmti
+/testsuite/tests/tool-debugger/find-artifacts/*.annot
+/testsuite/tests/tool-debugger/find-artifacts/*.result
+/testsuite/tests/tool-debugger/find-artifacts/*.byte
+/testsuite/tests/tool-debugger/find-artifacts/*.native
+/testsuite/tests/tool-debugger/find-artifacts/program
+/testsuite/tests/tool-debugger/find-artifacts/*.exe
+/testsuite/tests/tool-debugger/find-artifacts/*.exe.manifest
+/testsuite/tests/tool-debugger/find-artifacts/.depend
+/testsuite/tests/tool-debugger/find-artifacts/.depend.nt
+/testsuite/tests/tool-debugger/find-artifacts/.DS_Store
+/testsuite/tests/tool-debugger/find-artifacts/compiler-libs
+/testsuite/tests/tool-debugger/find-artifacts/out
+
+# /testsuite/tests/tool-debugger/no_debug_event/
+/testsuite/tests/tool-debugger/no_debug_event/*.o
+/testsuite/tests/tool-debugger/no_debug_event/*.a
+/testsuite/tests/tool-debugger/no_debug_event/*.so
+/testsuite/tests/tool-debugger/no_debug_event/*.obj
+/testsuite/tests/tool-debugger/no_debug_event/*.lib
+/testsuite/tests/tool-debugger/no_debug_event/*.dll
+/testsuite/tests/tool-debugger/no_debug_event/*.cm[ioxat]
+/testsuite/tests/tool-debugger/no_debug_event/*.cmx[as]
+/testsuite/tests/tool-debugger/no_debug_event/*.cmti
+/testsuite/tests/tool-debugger/no_debug_event/*.annot
+/testsuite/tests/tool-debugger/no_debug_event/*.result
+/testsuite/tests/tool-debugger/no_debug_event/*.byte
+/testsuite/tests/tool-debugger/no_debug_event/*.native
+/testsuite/tests/tool-debugger/no_debug_event/program
+/testsuite/tests/tool-debugger/no_debug_event/*.exe
+/testsuite/tests/tool-debugger/no_debug_event/*.exe.manifest
+/testsuite/tests/tool-debugger/no_debug_event/.depend
+/testsuite/tests/tool-debugger/no_debug_event/.depend.nt
+/testsuite/tests/tool-debugger/no_debug_event/.DS_Store
+/testsuite/tests/tool-debugger/no_debug_event/compiler-libs
+/testsuite/tests/tool-debugger/no_debug_event/out
+/testsuite/tests/tool-debugger/no_debug_event/c
+/testsuite/tests/tool-debugger/no_debug_event/c.exe
+
+# /testsuite/tests/tool-lexyacc/
+/testsuite/tests/tool-lexyacc/*.o
+/testsuite/tests/tool-lexyacc/*.a
+/testsuite/tests/tool-lexyacc/*.so
+/testsuite/tests/tool-lexyacc/*.obj
+/testsuite/tests/tool-lexyacc/*.lib
+/testsuite/tests/tool-lexyacc/*.dll
+/testsuite/tests/tool-lexyacc/*.cm[ioxat]
+/testsuite/tests/tool-lexyacc/*.cmx[as]
+/testsuite/tests/tool-lexyacc/*.cmti
+/testsuite/tests/tool-lexyacc/*.annot
+/testsuite/tests/tool-lexyacc/*.result
+/testsuite/tests/tool-lexyacc/*.byte
+/testsuite/tests/tool-lexyacc/*.native
+/testsuite/tests/tool-lexyacc/program
+/testsuite/tests/tool-lexyacc/*.exe
+/testsuite/tests/tool-lexyacc/*.exe.manifest
+/testsuite/tests/tool-lexyacc/.depend
+/testsuite/tests/tool-lexyacc/.depend.nt
+/testsuite/tests/tool-lexyacc/.DS_Store
+/testsuite/tests/tool-lexyacc/scanner.ml
+/testsuite/tests/tool-lexyacc/grammar.mli
+/testsuite/tests/tool-lexyacc/grammar.ml
+
+# /testsuite/tests/tool-ocaml/
+/testsuite/tests/tool-ocaml/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/tool-ocaml/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/tool-ocaml/_log
+/testsuite/tests/tool-ocaml/*.so
+/testsuite/tests/tool-ocaml/*.a
+/testsuite/tests/tool-ocaml/*.result
+/testsuite/tests/tool-ocaml/*.byte
+/testsuite/tests/tool-ocaml/*.native
+/testsuite/tests/tool-ocaml/program
+/testsuite/tests/tool-ocaml/*.cm*
+/testsuite/tests/tool-ocaml/*.o
+
+# /testsuite/tests/tool-ocamldoc/
+/testsuite/tests/tool-ocamldoc/*.o
+/testsuite/tests/tool-ocamldoc/*.a
+/testsuite/tests/tool-ocamldoc/*.so
+/testsuite/tests/tool-ocamldoc/*.obj
+/testsuite/tests/tool-ocamldoc/*.cm[ioxa]
+/testsuite/tests/tool-ocamldoc/*.cmx[as]
+/testsuite/tests/tool-ocamldoc/*.annot
+/testsuite/tests/tool-ocamldoc/*.result
+/testsuite/tests/tool-ocamldoc/*.byte
+/testsuite/tests/tool-ocamldoc/*.native
+/testsuite/tests/tool-ocamldoc/program
+/testsuite/tests/tool-ocamldoc/.depend
+/testsuite/tests/tool-ocamldoc/.depend.nt
+/testsuite/tests/tool-ocamldoc/.DS_Store
+/testsuite/tests/tool-ocamldoc/*.html
+/testsuite/tests/tool-ocamldoc/*.sty
+/testsuite/tests/tool-ocamldoc/*.css
+/testsuite/tests/tool-ocamldoc/ocamldoc.out
+
+# /testsuite/tests/tool-toplevel/
+/testsuite/tests/tool-toplevel/*.o
+/testsuite/tests/tool-toplevel/*.a
+/testsuite/tests/tool-toplevel/*.so
+/testsuite/tests/tool-toplevel/*.obj
+/testsuite/tests/tool-toplevel/*.lib
+/testsuite/tests/tool-toplevel/*.dll
+/testsuite/tests/tool-toplevel/*.cm[ioxat]
+/testsuite/tests/tool-toplevel/*.cmx[as]
+/testsuite/tests/tool-toplevel/*.cmti
+/testsuite/tests/tool-toplevel/*.annot
+/testsuite/tests/tool-toplevel/*.result
+/testsuite/tests/tool-toplevel/*.byte
+/testsuite/tests/tool-toplevel/*.native
+/testsuite/tests/tool-toplevel/program
+/testsuite/tests/tool-toplevel/*.exe
+/testsuite/tests/tool-toplevel/*.exe.manifest
+/testsuite/tests/tool-toplevel/.depend
+/testsuite/tests/tool-toplevel/.depend.nt
+/testsuite/tests/tool-toplevel/.DS_Store
+
+# /testsuite/tests/translprim/
+/testsuite/tests/translprim/*.o
+/testsuite/tests/translprim/*.a
+/testsuite/tests/translprim/*.so
+/testsuite/tests/translprim/*.obj
+/testsuite/tests/translprim/*.lib
+/testsuite/tests/translprim/*.dll
+/testsuite/tests/translprim/*.cm[ioxat]
+/testsuite/tests/translprim/*.cmx[as]
+/testsuite/tests/translprim/*.cmti
+/testsuite/tests/translprim/*.annot
+/testsuite/tests/translprim/*.result
+/testsuite/tests/translprim/*.byte
+/testsuite/tests/translprim/*.native
+/testsuite/tests/translprim/program
+/testsuite/tests/translprim/*.exe
+/testsuite/tests/translprim/*.exe.manifest
+/testsuite/tests/translprim/.depend
+/testsuite/tests/translprim/.depend.nt
+/testsuite/tests/translprim/.DS_Store
+
+# /testsuite/tests/typing-extensions/
+/testsuite/tests/typing-extensions/*.o
+/testsuite/tests/typing-extensions/*.a
+/testsuite/tests/typing-extensions/*.so
+/testsuite/tests/typing-extensions/*.obj
+/testsuite/tests/typing-extensions/*.lib
+/testsuite/tests/typing-extensions/*.dll
+/testsuite/tests/typing-extensions/*.cm[ioxat]
+/testsuite/tests/typing-extensions/*.cmx[as]
+/testsuite/tests/typing-extensions/*.cmti
+/testsuite/tests/typing-extensions/*.annot
+/testsuite/tests/typing-extensions/*.result
+/testsuite/tests/typing-extensions/*.byte
+/testsuite/tests/typing-extensions/*.native
+/testsuite/tests/typing-extensions/program
+/testsuite/tests/typing-extensions/*.exe
+/testsuite/tests/typing-extensions/*.exe.manifest
+/testsuite/tests/typing-extensions/.depend
+/testsuite/tests/typing-extensions/.depend.nt
+/testsuite/tests/typing-extensions/.DS_Store
+
+# /testsuite/tests/typing-fstclassmod/
+/testsuite/tests/typing-fstclassmod/*.o
+/testsuite/tests/typing-fstclassmod/*.a
+/testsuite/tests/typing-fstclassmod/*.so
+/testsuite/tests/typing-fstclassmod/*.obj
+/testsuite/tests/typing-fstclassmod/*.lib
+/testsuite/tests/typing-fstclassmod/*.dll
+/testsuite/tests/typing-fstclassmod/*.cm[ioxat]
+/testsuite/tests/typing-fstclassmod/*.cmx[as]
+/testsuite/tests/typing-fstclassmod/*.cmti
+/testsuite/tests/typing-fstclassmod/*.annot
+/testsuite/tests/typing-fstclassmod/*.result
+/testsuite/tests/typing-fstclassmod/*.byte
+/testsuite/tests/typing-fstclassmod/*.native
+/testsuite/tests/typing-fstclassmod/program
+/testsuite/tests/typing-fstclassmod/*.exe
+/testsuite/tests/typing-fstclassmod/*.exe.manifest
+/testsuite/tests/typing-fstclassmod/.depend
+/testsuite/tests/typing-fstclassmod/.depend.nt
+/testsuite/tests/typing-fstclassmod/.DS_Store
+
+# /testsuite/tests/typing-gadts/
+/testsuite/tests/typing-gadts/*.o
+/testsuite/tests/typing-gadts/*.a
+/testsuite/tests/typing-gadts/*.so
+/testsuite/tests/typing-gadts/*.obj
+/testsuite/tests/typing-gadts/*.cm[ioxa]
+/testsuite/tests/typing-gadts/*.cmx[as]
+/testsuite/tests/typing-gadts/*.annot
+/testsuite/tests/typing-gadts/*.result
+/testsuite/tests/typing-gadts/*.byte
+/testsuite/tests/typing-gadts/*.native
+/testsuite/tests/typing-gadts/program
+/testsuite/tests/typing-gadts/.depend
+/testsuite/tests/typing-gadts/.depend.nt
+/testsuite/tests/typing-gadts/.DS_Store
+
+# /testsuite/tests/typing-implicit_unpack/
+/testsuite/tests/typing-implicit_unpack/*.o
+/testsuite/tests/typing-implicit_unpack/*.a
+/testsuite/tests/typing-implicit_unpack/*.so
+/testsuite/tests/typing-implicit_unpack/*.obj
+/testsuite/tests/typing-implicit_unpack/*.cm[ioxa]
+/testsuite/tests/typing-implicit_unpack/*.cmx[as]
+/testsuite/tests/typing-implicit_unpack/*.annot
+/testsuite/tests/typing-implicit_unpack/*.result
+/testsuite/tests/typing-implicit_unpack/*.byte
+/testsuite/tests/typing-implicit_unpack/*.native
+/testsuite/tests/typing-implicit_unpack/program
+/testsuite/tests/typing-implicit_unpack/.depend
+/testsuite/tests/typing-implicit_unpack/.depend.nt
+/testsuite/tests/typing-implicit_unpack/.DS_Store
+
+# /testsuite/tests/typing-labels/
+/testsuite/tests/typing-labels/*.o
+/testsuite/tests/typing-labels/*.a
+/testsuite/tests/typing-labels/*.so
+/testsuite/tests/typing-labels/*.obj
+/testsuite/tests/typing-labels/*.cm[ioxa]
+/testsuite/tests/typing-labels/*.cmx[as]
+/testsuite/tests/typing-labels/*.annot
+/testsuite/tests/typing-labels/*.result
+/testsuite/tests/typing-labels/*.byte
+/testsuite/tests/typing-labels/*.native
+/testsuite/tests/typing-labels/program
+/testsuite/tests/typing-labels/program.exe
+/testsuite/tests/typing-labels/.depend
+/testsuite/tests/typing-labels/.depend.nt
+/testsuite/tests/typing-labels/.DS_Store
+
+# /testsuite/tests/typing-misc/
+/testsuite/tests/typing-misc/*.o
+/testsuite/tests/typing-misc/*.a
+/testsuite/tests/typing-misc/*.so
+/testsuite/tests/typing-misc/*.obj
+/testsuite/tests/typing-misc/*.cm[ioxa]
+/testsuite/tests/typing-misc/*.cmx[as]
+/testsuite/tests/typing-misc/*.annot
+/testsuite/tests/typing-misc/*.result
+/testsuite/tests/typing-misc/*.byte
+/testsuite/tests/typing-misc/*.native
+/testsuite/tests/typing-misc/program
+/testsuite/tests/typing-misc/.depend
+/testsuite/tests/typing-misc/.depend.nt
+/testsuite/tests/typing-misc/.DS_Store
+
+# /testsuite/tests/typing-modules/
+/testsuite/tests/typing-modules/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/typing-modules/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/typing-modules/_log
+/testsuite/tests/typing-modules/*.so
+/testsuite/tests/typing-modules/*.a
+/testsuite/tests/typing-modules/*.result
+/testsuite/tests/typing-modules/*.byte
+/testsuite/tests/typing-modules/*.native
+/testsuite/tests/typing-modules/program
+
+# /testsuite/tests/typing-modules-bugs/
+/testsuite/tests/typing-modules-bugs/*.o
+/testsuite/tests/typing-modules-bugs/*.a
+/testsuite/tests/typing-modules-bugs/*.so
+/testsuite/tests/typing-modules-bugs/*.obj
+/testsuite/tests/typing-modules-bugs/*.cm[ioxa]
+/testsuite/tests/typing-modules-bugs/*.cmx[as]
+/testsuite/tests/typing-modules-bugs/*.annot
+/testsuite/tests/typing-modules-bugs/*.result
+/testsuite/tests/typing-modules-bugs/*.byte
+/testsuite/tests/typing-modules-bugs/*.native
+/testsuite/tests/typing-modules-bugs/program
+/testsuite/tests/typing-modules-bugs/program.exe
+/testsuite/tests/typing-modules-bugs/.depend
+/testsuite/tests/typing-modules-bugs/.depend.nt
+/testsuite/tests/typing-modules-bugs/.DS_Store
+
+# /testsuite/tests/typing-objects/
+/testsuite/tests/typing-objects/*.o
+/testsuite/tests/typing-objects/*.a
+/testsuite/tests/typing-objects/*.so
+/testsuite/tests/typing-objects/*.obj
+/testsuite/tests/typing-objects/*.cm[ioxa]
+/testsuite/tests/typing-objects/*.cmx[as]
+/testsuite/tests/typing-objects/*.annot
+/testsuite/tests/typing-objects/*.result
+/testsuite/tests/typing-objects/*.byte
+/testsuite/tests/typing-objects/*.native
+/testsuite/tests/typing-objects/program
+/testsuite/tests/typing-objects/.depend
+/testsuite/tests/typing-objects/.depend.nt
+/testsuite/tests/typing-objects/.DS_Store
+
+# /testsuite/tests/typing-objects-bugs/
+/testsuite/tests/typing-objects-bugs/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/typing-objects-bugs/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/typing-objects-bugs/_log
+/testsuite/tests/typing-objects-bugs/*.so
+/testsuite/tests/typing-objects-bugs/*.a
+/testsuite/tests/typing-objects-bugs/*.result
+/testsuite/tests/typing-objects-bugs/*.byte
+/testsuite/tests/typing-objects-bugs/*.native
+/testsuite/tests/typing-objects-bugs/program
+/testsuite/tests/typing-objects-bugs/*.cm*
+/testsuite/tests/typing-objects-bugs/*.o
+
+# /testsuite/tests/typing-poly/
+/testsuite/tests/typing-poly/*.o
+/testsuite/tests/typing-poly/*.a
+/testsuite/tests/typing-poly/*.so
+/testsuite/tests/typing-poly/*.obj
+/testsuite/tests/typing-poly/*.cm[ioxa]
+/testsuite/tests/typing-poly/*.cmx[as]
+/testsuite/tests/typing-poly/*.annot
+/testsuite/tests/typing-poly/*.result
+/testsuite/tests/typing-poly/*.byte
+/testsuite/tests/typing-poly/*.native
+/testsuite/tests/typing-poly/program
+/testsuite/tests/typing-poly/.depend
+/testsuite/tests/typing-poly/.depend.nt
+/testsuite/tests/typing-poly/.DS_Store
+
+# /testsuite/tests/typing-poly-bugs/
+/testsuite/tests/typing-poly-bugs/*.o
+/testsuite/tests/typing-poly-bugs/*.a
+/testsuite/tests/typing-poly-bugs/*.so
+/testsuite/tests/typing-poly-bugs/*.obj
+/testsuite/tests/typing-poly-bugs/*.cm[ioxa]
+/testsuite/tests/typing-poly-bugs/*.cmx[as]
+/testsuite/tests/typing-poly-bugs/*.annot
+/testsuite/tests/typing-poly-bugs/*.result
+/testsuite/tests/typing-poly-bugs/*.byte
+/testsuite/tests/typing-poly-bugs/*.native
+/testsuite/tests/typing-poly-bugs/program
+/testsuite/tests/typing-poly-bugs/program.exe
+/testsuite/tests/typing-poly-bugs/.depend
+/testsuite/tests/typing-poly-bugs/.depend.nt
+/testsuite/tests/typing-poly-bugs/.DS_Store
+
+# /testsuite/tests/typing-polyvariants-bugs/
+/testsuite/tests/typing-polyvariants-bugs/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/typing-polyvariants-bugs/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/typing-polyvariants-bugs/_log
+/testsuite/tests/typing-polyvariants-bugs/*.so
+/testsuite/tests/typing-polyvariants-bugs/*.a
+/testsuite/tests/typing-polyvariants-bugs/*.result
+/testsuite/tests/typing-polyvariants-bugs/*.byte
+/testsuite/tests/typing-polyvariants-bugs/*.native
+/testsuite/tests/typing-polyvariants-bugs/program
+/testsuite/tests/typing-polyvariants-bugs/*.cm*
+/testsuite/tests/typing-polyvariants-bugs/*.o
+
+# /testsuite/tests/typing-polyvariants-bugs-2/
+/testsuite/tests/typing-polyvariants-bugs-2/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/typing-polyvariants-bugs-2/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/typing-polyvariants-bugs-2/_log
+/testsuite/tests/typing-polyvariants-bugs-2/*.so
+/testsuite/tests/typing-polyvariants-bugs-2/*.a
+/testsuite/tests/typing-polyvariants-bugs-2/*.result
+/testsuite/tests/typing-polyvariants-bugs-2/*.byte
+/testsuite/tests/typing-polyvariants-bugs-2/*.native
+/testsuite/tests/typing-polyvariants-bugs-2/program
+/testsuite/tests/typing-polyvariants-bugs-2/*.cm*
+/testsuite/tests/typing-polyvariants-bugs-2/*.o
+
+# /testsuite/tests/typing-private/
+/testsuite/tests/typing-private/*.o
+/testsuite/tests/typing-private/*.a
+/testsuite/tests/typing-private/*.so
+/testsuite/tests/typing-private/*.obj
+/testsuite/tests/typing-private/*.cm[ioxa]
+/testsuite/tests/typing-private/*.cmx[as]
+/testsuite/tests/typing-private/*.annot
+/testsuite/tests/typing-private/*.result
+/testsuite/tests/typing-private/*.byte
+/testsuite/tests/typing-private/*.native
+/testsuite/tests/typing-private/program
+/testsuite/tests/typing-private/.depend
+/testsuite/tests/typing-private/.depend.nt
+/testsuite/tests/typing-private/.DS_Store
+
+# /testsuite/tests/typing-private-bugs/
+/testsuite/tests/typing-private-bugs/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/typing-private-bugs/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/typing-private-bugs/_log
+/testsuite/tests/typing-private-bugs/*.so
+/testsuite/tests/typing-private-bugs/*.a
+/testsuite/tests/typing-private-bugs/*.result
+/testsuite/tests/typing-private-bugs/*.byte
+/testsuite/tests/typing-private-bugs/*.native
+/testsuite/tests/typing-private-bugs/program
+/testsuite/tests/typing-private-bugs/*.cm*
+/testsuite/tests/typing-private-bugs/*.o
+
+# /testsuite/tests/typing-recmod/
+/testsuite/tests/typing-recmod/# svn propset -R svn:ignore -F .svnignore .
+/testsuite/tests/typing-recmod/# find . -name .svnignore -print | while read f; do svn propset svn:ignore -F $f `dirname $f`; done
+/testsuite/tests/typing-recmod/_log
+/testsuite/tests/typing-recmod/*.so
+/testsuite/tests/typing-recmod/*.a
+/testsuite/tests/typing-recmod/*.result
+/testsuite/tests/typing-recmod/*.byte
+/testsuite/tests/typing-recmod/*.native
+/testsuite/tests/typing-recmod/program
+/testsuite/tests/typing-recmod/*.cm*
+/testsuite/tests/typing-recmod/*.o
+
+# /testsuite/tests/typing-recordarg/
+/testsuite/tests/typing-recordarg/*.o
+/testsuite/tests/typing-recordarg/*.a
+/testsuite/tests/typing-recordarg/*.so
+/testsuite/tests/typing-recordarg/*.obj
+/testsuite/tests/typing-recordarg/*.lib
+/testsuite/tests/typing-recordarg/*.dll
+/testsuite/tests/typing-recordarg/*.cm[ioxat]
+/testsuite/tests/typing-recordarg/*.cmx[as]
+/testsuite/tests/typing-recordarg/*.cmti
+/testsuite/tests/typing-recordarg/*.annot
+/testsuite/tests/typing-recordarg/*.result
+/testsuite/tests/typing-recordarg/*.byte
+/testsuite/tests/typing-recordarg/*.native
+/testsuite/tests/typing-recordarg/program
+/testsuite/tests/typing-recordarg/*.exe
+/testsuite/tests/typing-recordarg/*.exe.manifest
+/testsuite/tests/typing-recordarg/.depend
+/testsuite/tests/typing-recordarg/.depend.nt
+/testsuite/tests/typing-recordarg/.DS_Store
+
+# /testsuite/tests/typing-short-paths/
+/testsuite/tests/typing-short-paths/*.o
+/testsuite/tests/typing-short-paths/*.a
+/testsuite/tests/typing-short-paths/*.so
+/testsuite/tests/typing-short-paths/*.obj
+/testsuite/tests/typing-short-paths/*.cm[ioxat]
+/testsuite/tests/typing-short-paths/*.cmx[as]
+/testsuite/tests/typing-short-paths/*.cmti
+/testsuite/tests/typing-short-paths/*.annot
+/testsuite/tests/typing-short-paths/*.result
+/testsuite/tests/typing-short-paths/*.byte
+/testsuite/tests/typing-short-paths/*.native
+/testsuite/tests/typing-short-paths/program
+/testsuite/tests/typing-short-paths/program.exe
+/testsuite/tests/typing-short-paths/.depend
+/testsuite/tests/typing-short-paths/.depend.nt
+/testsuite/tests/typing-short-paths/.DS_Store
+
+# /testsuite/tests/typing-signatures/
+/testsuite/tests/typing-signatures/*.o
+/testsuite/tests/typing-signatures/*.a
+/testsuite/tests/typing-signatures/*.so
+/testsuite/tests/typing-signatures/*.obj
+/testsuite/tests/typing-signatures/*.cm[ioxa]
+/testsuite/tests/typing-signatures/*.cmx[as]
+/testsuite/tests/typing-signatures/*.annot
+/testsuite/tests/typing-signatures/*.result
+/testsuite/tests/typing-signatures/*.byte
+/testsuite/tests/typing-signatures/*.native
+/testsuite/tests/typing-signatures/program
+/testsuite/tests/typing-signatures/.depend
+/testsuite/tests/typing-signatures/.depend.nt
+/testsuite/tests/typing-signatures/.DS_Store
+
+# /testsuite/tests/typing-sigsubst/
+/testsuite/tests/typing-sigsubst/*.o
+/testsuite/tests/typing-sigsubst/*.a
+/testsuite/tests/typing-sigsubst/*.so
+/testsuite/tests/typing-sigsubst/*.obj
+/testsuite/tests/typing-sigsubst/*.cm[ioxa]
+/testsuite/tests/typing-sigsubst/*.cmx[as]
+/testsuite/tests/typing-sigsubst/*.annot
+/testsuite/tests/typing-sigsubst/*.result
+/testsuite/tests/typing-sigsubst/*.byte
+/testsuite/tests/typing-sigsubst/*.native
+/testsuite/tests/typing-sigsubst/program
+/testsuite/tests/typing-sigsubst/.depend
+/testsuite/tests/typing-sigsubst/.depend.nt
+/testsuite/tests/typing-sigsubst/.DS_Store
+
+# /testsuite/tests/typing-typeparam/
+/testsuite/tests/typing-typeparam/*.o
+/testsuite/tests/typing-typeparam/*.a
+/testsuite/tests/typing-typeparam/*.so
+/testsuite/tests/typing-typeparam/*.obj
+/testsuite/tests/typing-typeparam/*.cm[ioxa]
+/testsuite/tests/typing-typeparam/*.cmx[as]
+/testsuite/tests/typing-typeparam/*.annot
+/testsuite/tests/typing-typeparam/*.result
+/testsuite/tests/typing-typeparam/*.byte
+/testsuite/tests/typing-typeparam/*.native
+/testsuite/tests/typing-typeparam/program
+/testsuite/tests/typing-typeparam/.depend
+/testsuite/tests/typing-typeparam/.depend.nt
+/testsuite/tests/typing-typeparam/.DS_Store
+
+# /testsuite/tests/typing-warnings/
+/testsuite/tests/typing-warnings/*.o
+/testsuite/tests/typing-warnings/*.a
+/testsuite/tests/typing-warnings/*.so
+/testsuite/tests/typing-warnings/*.obj
+/testsuite/tests/typing-warnings/*.cm[ioxat]
+/testsuite/tests/typing-warnings/*.cmx[as]
+/testsuite/tests/typing-warnings/*.cmti
+/testsuite/tests/typing-warnings/*.annot
+/testsuite/tests/typing-warnings/*.result
+/testsuite/tests/typing-warnings/*.byte
+/testsuite/tests/typing-warnings/*.native
+/testsuite/tests/typing-warnings/program
+/testsuite/tests/typing-warnings/program.exe
+/testsuite/tests/typing-warnings/.depend
+/testsuite/tests/typing-warnings/.depend.nt
+/testsuite/tests/typing-warnings/.DS_Store
+
+# /testsuite/tests/utils/
+/testsuite/tests/utils/*.o
+/testsuite/tests/utils/*.a
+/testsuite/tests/utils/*.so
+/testsuite/tests/utils/*.obj
+/testsuite/tests/utils/*.cm[ioxat]
+/testsuite/tests/utils/*.cmx[as]
+/testsuite/tests/utils/*.cmti
+/testsuite/tests/utils/*.annot
+/testsuite/tests/utils/*.result
+/testsuite/tests/utils/*.byte
+/testsuite/tests/utils/*.native
+/testsuite/tests/utils/program
+/testsuite/tests/utils/program.exe
+/testsuite/tests/utils/.depend
+/testsuite/tests/utils/.depend.nt
+/testsuite/tests/utils/.DS_Store
+
+# /testsuite/tests/warnings/
+/testsuite/tests/warnings/*.o
+/testsuite/tests/warnings/*.a
+/testsuite/tests/warnings/*.so
+/testsuite/tests/warnings/*.obj
+/testsuite/tests/warnings/*.lib
+/testsuite/tests/warnings/*.dll
+/testsuite/tests/warnings/*.cm[ioxat]
+/testsuite/tests/warnings/*.cmx[as]
+/testsuite/tests/warnings/*.cmti
+/testsuite/tests/warnings/*.annot
+/testsuite/tests/warnings/*.result
+/testsuite/tests/warnings/*.byte
+/testsuite/tests/warnings/*.native
+/testsuite/tests/warnings/program
+/testsuite/tests/warnings/*.exe
+/testsuite/tests/warnings/*.exe.manifest
+/testsuite/tests/warnings/.depend
+/testsuite/tests/warnings/.depend.nt
+/testsuite/tests/warnings/.DS_Store
+
+# /tools/
+/tools/*.o
+/tools/*.a
+/tools/*.so
+/tools/*.obj
+/tools/*.lib
+/tools/*.dll
+/tools/*.cm[ioxat]
+/tools/*.cmx[as]
+/tools/*.cmti
+/tools/*.annot
+/tools/*.result
+/tools/*.byte
+/tools/*.native
+/tools/program
+/tools/*.exe
+/tools/*.exe.manifest
+/tools/.depend
+/tools/.depend.nt
+/tools/.DS_Store
+/tools/ocamldep
+/tools/ocamldep.opt
+/tools/ocamldep.bak
+/tools/ocamlprof
+/tools/opnames.ml
+/tools/dumpobj
+/tools/dumpapprox
+/tools/objinfo
+/tools/cvt_emit
+/tools/cvt_emit.bak
+/tools/cvt_emit.ml
+/tools/ocamlcp
+/tools/ocamloptp
+/tools/ocamlmktop
+/tools/primreq
+/tools/ocamldumpobj
+/tools/keywords
+/tools/lexer299.ml
+/tools/ocaml299to3
+/tools/ocamlmklib
+/tools/ocamlmklibconfig.ml
+/tools/lexer301.ml
+/tools/scrapelabels
+/tools/addlabels
+/tools/objinfo_helper
+/tools/read_cmt
+/tools/read_cmt.opt
+
+# /toplevel/
+/toplevel/.depend
+/toplevel/configure
+/toplevel/ocamlc
+/toplevel/ocamlc.opt
+/toplevel/expunge
+/toplevel/ocaml
+/toplevel/ocamlopt
+/toplevel/ocamlopt.opt
+/toplevel/ocamlcomp.sh
+/toplevel/ocamlcompopt.sh
+/toplevel/package-macosx
+/toplevel/.DS_Store
+/toplevel/*.annot
+/toplevel/_boot_log1
+/toplevel/_boot_log2
+/toplevel/_build
+/toplevel/_log
+/toplevel/myocamlbuild_config.ml
+/toplevel/ocamlnat
+/toplevel/*.cm*
+/toplevel/*.o
+
+# /typing/
+/typing/*.o
+/typing/*.a
+/typing/*.so
+/typing/*.obj
+/typing/*.dll
+/typing/*.cm[ioxat]
+/typing/*.cmx[as]
+/typing/*.cmti
+/typing/*.annot
+/typing/*.result
+/typing/*.byte
+/typing/*.native
+/typing/program
+/typing/*.exe
+/typing/.depend
+/typing/.depend.nt
+/typing/.DS_Store
+
+# /utils/
+/utils/*.o
+/utils/*.a
+/utils/*.so
+/utils/*.obj
+/utils/*.dll
+/utils/*.cm[ioxat]
+/utils/*.cmx[as]
+/utils/*.cmti
+/utils/*.annot
+/utils/*.result
+/utils/*.byte
+/utils/*.native
+/utils/program
+/utils/*.exe
+/utils/.depend
+/utils/.depend.nt
+/utils/.DS_Store
+/utils/config.ml
+
+# /yacc/
+/yacc/*.o
+/yacc/*.a
+/yacc/*.so
+/yacc/*.obj
+/yacc/*.cm[ioxa]
+/yacc/*.cmx[as]
+/yacc/*.annot
+/yacc/*.result
+/yacc/*.byte
+/yacc/*.native
+/yacc/program
+/yacc/program.exe
+/yacc/.depend
+/yacc/.depend.nt
+/yacc/.DS_Store
+/yacc/ocamlyacc
+/yacc/ocamlyacc.exe
+/yacc/version.h
+/yacc/.gdb_history
diff --git a/.ignore b/.ignore
new file mode 100644
index 0000000000..6dce10ee3e
--- /dev/null
+++ b/.ignore
@@ -0,0 +1,11 @@
+configure
+ocamlc
+ocamlc.opt
+expunge
+ocaml
+ocamlopt
+ocamlopt.opt
+ocamlcomp.sh
+ocamlcompopt.sh
+package-macosx
+ocamlnat
diff --git a/.merlin b/.merlin
new file mode 100644
index 0000000000..0442978ec5
--- /dev/null
+++ b/.merlin
@@ -0,0 +1,50 @@
+S ./asmcomp
+B ./asmcomp
+
+S ./bytecomp
+B ./bytecomp
+
+S ./driver
+B ./driver
+
+S ./lex
+B ./lex
+
+S ./otherlibs/bigarray
+B ./otherlibs/bigarray
+
+S ./otherlibs/dynlink
+B ./otherlibs/dynlink
+
+S ./otherlibs/graph
+B ./otherlibs/graph
+
+S ./otherlibs/num
+B ./otherlibs/num
+
+S ./otherlibs/str
+B ./otherlibs/str
+
+S ./otherlibs/systhreads
+B ./otherlibs/systhreads
+
+S ./otherlibs/threads
+B ./otherlibs/threads
+
+S ./otherlibs/unix
+B ./otherlibs/unix
+
+S ./parsing
+B ./parsing
+
+S ./stdlib
+B ./stdlib
+
+S ./toplevel
+B ./toplevel
+
+S ./typing
+B ./typing
+
+S ./utils
+B ./utils
diff --git a/.ocp-indent b/.ocp-indent
new file mode 100644
index 0000000000..324a382764
--- /dev/null
+++ b/.ocp-indent
@@ -0,0 +1,2 @@
+match_clause=4
+strict_with=auto
diff --git a/.travis-ci.sh b/.travis-ci.sh
new file mode 100644
index 0000000000..aa37577ba9
--- /dev/null
+++ b/.travis-ci.sh
@@ -0,0 +1,35 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Anil Madhavapeddy, OCaml Labs #
+# #
+# Copyright 2014 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+case $XARCH in
+i386)
+ ./configure
+ make world.opt
+ sudo make install
+ (cd testsuite && make all)
+ mkdir external-packages
+ cd external-packages
+ git clone git://github.com/ocaml/camlp4
+ (cd camlp4 && ./configure && make && sudo make install)
+ git clone git://github.com/ocaml/opam
+ (cd opam && ./configure && make lib-ext && make && sudo make install)
+ git config --global user.email "some@name.com"
+ git config --global user.name "Some Name"
+ opam init -y -a git://github.com/ocaml/opam-repository
+ opam install -y oasis
+ # opam pin add -y utop git://github.com/diml/utop
+ ;;
+*)
+ echo unknown arch
+ exit 1
+ ;;
+esac
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000000..93c47efa69
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Anil Madhavapeddy, OCaml Labs #
+# #
+# Copyright 2014 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+language: c
+script: bash -ex .travis-ci.sh
+env:
+ - XARCH=i386
diff --git a/Changes b/Changes
new file mode 100644
index 0000000000..7dec857f54
--- /dev/null
+++ b/Changes
@@ -0,0 +1,4447 @@
+OCaml 4.03.0:
+-------------
+
+(Changes that can break existing programs are marked with a "*")
+
+Language features:
+- PR#5528: inline records for constructor arguments (Alain Frisch)
+- PR#6374: allow "_ t" as a short-hand for "(_, _, ..) t" for n-ary type
+ constructors (Alain Frisch)
+- PR#6714: allow [@@ocaml.warning] on most structure and signature items:
+ values, modules, module types
+ (Peter Zotov)
+- GPR#26: support for "(type a b)" as syntactic sugar for "(type a) (type b)"
+ (Gabriel Scherer)
+* GPR#69: Custom index operators: ( .() ), ( .[] ), ( .{} ) etc.
+ (user 'Octachron')
+ The syntax "foo.(bar) <- baz" now desugars into "( .()<- ) foo bar baz"; this
+ should allow user to define their own notations by overriding.
+ The bigarray notations ( .{} ), ( .{,} ) etc. are defined in the Bigarray
+ module, which means that the foo.{bar,baz} syntactic sugar is only available
+ when the Bigarray module is opened; this can break existing programs,
+ which should be fixed by opening the Bigarray module.
+- GPR#88: allow field punning in object copying expressions:
+ {< x; y; >} is sugar for {< x = x; y = y; >}
+ (Jeremy Yallop)
+- GPR#167: allow to annotate externals' arguments and result types so
+ they can be unboxed or untagged. Supports untagging int and unboxing
+ int32, int64, nativeint and float.
+ (Jérémie Dimino, Mark Shinwell)
+
+Compilers:
+- PR#6501: harden the native-code generator against certain uses of "%identity"
+ (Xavier Leroy, report by Antoine Miné).
+- PR#6636: add --version option
+ (Peter Zotov)
+- improve type-specialization of unapplied primitives
+ (Frédéric Bour, review by Gabriel Scherer)
+- PR#6737: fix Typedtree attributes on (fun x -> body) expressions
+- PR#6679: fix pprintast printing of constraints in type declarations
+- PR#6845: -no-check-prims to tell ocamlc not to check primitives in runtime
+- PR#6943: native-code generator for POWER/PowerPC 64 bits, both in
+ big-endian (ppc64) and little-endian (ppc64le) configuration.
+ (Xavier Leroy, with inspiration from RedHat's unofficial ppc64 and ppc64le
+ ports)
+- PR#6979: better code generation in x86-32 backend for copying floats to
+ the stack (Marc Lasson, review by Xavier Leroy)
+- GPR#17: some cmm optimizations of integer operations with constants
+ (Stephen Dolan, review by Pierre Chambart)
+- GPR#109: new unboxing strategy for float and int references (Vladimir Brankov,
+ review by Alain Frisch)
+- GPR#107: Prevent more unnecessary float boxing, especially in `if` and `match`
+ (Vladimir Brankov, review by Alain Frisch)
+- GPR#115: More precise typing of values at the C-- and Mach level,.
+ (Xavier Leroy, review by Pierre Chambart)
+- GPR#207: Colors in compiler messages (warnings, errors)
+ (Simon Cruanes, review by Gabriel Scherer)
+
+Runtime system:
+- PR#3612: allow allocating custom block with finalizers in the minor heap
+ (Pierre Chambart)
+- PR#6517: use ISO C99 types {,u}int{32,64}_t in preference to our homegrown
+ types {,u}int{32,64}.
+ (Xavier Leroy)
+- PR#6760: closures evaluated in the toplevel can now be marshalled
+ (Peter Zotov, review by Jacques-Henri Jourdan)
+- PR#6902, GPR#210: runtime emits a warning when finalizing an I/O channel
+ which is still open (Alain Frisch, review by Damien Doligez)
+- Signal handling: for read-and-clear, use GCC/Clang atomic builtins
+ if available. (Xavier Leroy)
+- GPR#226: select higher levels of optimization for GCC and Clang when
+ compiling the run-time system and C stub code. (Xavier Leroy)
+
+Standard library:
+- PR#6316: Scanf.scanf failure on %u formats when reading big integers
+ (Xavier Leroy, Benoît Vaugon)
+- PR#6390, GPR#36: expose Sys.{int_size,max_wosize} for improved js_of_ocaml
+ portability (Hugo Heuzard)
+* PR#6494: Add equal function in modules
+ Bytes, Char, Digest, Int32, Int64, Nativeint, and String
+ (Romain Calascibetta)
+* PR#6524, GPR#79: Filename: Optional ?perms argument to open_temp_file
+ (Daniel Bünzli, review by Jacques-Pascal Deplaix)
+- PR#6577: improve performance of %L, %l, %n, %S, %C format specifiers
+ (Alain Frisch)
+- PR#6585: fix memory leak in win32unix/createprocess.c
+- PR#6649, GPR#222: accept (int_of_string "+3")
+ (Christopher McAlpine)
+- PR#6645, GPR#174: Guarantee that Set.add, Set.remove, Set.filter
+ return the original set if no change is required (Alain Frisch,
+ Mohamed Iguernelala)
+- PR#6694, PR#6695: deprecate functions using ISO-8859-1 character set
+ in Char, Bytes, String and provide alternatives using US-ASCII.
+ (Peter Zotov)
+- GPR#201: generalize types of Printf.{ifprintf,ikfprintf}
+ (Maxence Guesdon)
+- GPR#216: add the missing POSIX.1-2001 signals in Sys
+ (Guillaume Bury)
+
+Type system:
+- PR#5545: Type annotations on methods cannot control the choice of abbreviation
+* PR#6465: allow incremental weakening of module aliases (Jacques Garrigue).
+ This is done by adding equations to submodules when expanding aliases.
+ In theory this may be incompatible is some corner cases defining a module
+ type through inference, but no breakage known on published code.
+- PR#6593: Functor application in tests/basic-modules fails after commit 15405
+
+Toplevel and debugger:
+- PR#6468: toplevel now supports backtraces if invoked with OCAMLRUNPARAM=b
+ (Peter Zotov and Jake Donham,
+ review by Gabriel Scherer and Jacques-Henri Jourdan)
+
+Other libraries:
+- PR#6896: serious reimplementation of Big_int.float_of_big_int and
+ Ratio.float_of_ratio, ensuring that the result is correctly rounded.
+ (Xavier Leroy)
+
+OCamlbuild:
+- PR#6794, PR#6809: pass package-specific include flags when building C files
+ (Jérémie Dimino, request by Peter Zotov)
+- GPR#208: add "asm" tag to ocamlbuild to enable flag -S
+ (ygrek)
+- Changed OCamlbuild's license to LGPLv2 with static linking exception.
+- GPR#219: speedup target-already-built builds
+ (ygrek)
+
+Bug fixes:
+- PR#3612: memory leak in bigarray read from file
+ (Pierre Chambart, report by Gary Huber)
+* PR#4539: change exception string raised when comparing functional values
+ (Nicolas Braud-Santoni, report by Eric Cooper)
+- PR#4832: Filling bigarrays may block out runtime
+ (Markus Mottl)
+- PR#5663: program rejected due to nongeneralizable type variable that
+ appears nowhere
+ (Jacques Garrigue, report by Stephen Weeks)
+- PR#5780: Strange type variable names in error messages (GADTs)
+ (only made the names more informative)
+ (Jacques Garrigue, report by Sebastien Furic)
+- PR#5887: move the byterun/*.h headers to byterun/caml/*.h to avoid header
+ name clashes
+ (Jérôme Vouillon and Adrien Nader and Peter Zotov)
+* PR#6081: ocaml should add script's directory to search path, not current
+ directory
+ (Thomas Leonard and Damien Doligez)
+- PR#6171: Error message confusing when a type escapes its scope.
+- PR#6340: Incorrect handling of \r when processing "Windows" source files
+ (Damien Doligez, report by David Allsopp)
+* PR#6521: {Bytes,Char,String}.escaped are locale-dependent
+ (Damien Doligez, report by Jun Furuse)
+- PR#6526: ocamllex warning: unescaped newline in comment string
+ (Damien Doligez, report by user 'dhekir')
+- PR#6341: ocamldoc -colorize-code adds spurious <br> tags to <pre> blocks
+- PR#6560: Wrong failure message for {Int32,Int64,NativeInt}.of_string
+ (Maxime Dénès and Gabriel Scherer)
+- PR#6648: show_module should indicate its elision
+- PR#6650: Cty_constr not handled correctly by Subst
+- PR#6651: Failing component lookup
+* PR#6664: Crash when finalising lazy values of the wrong type.
+ (Damien Doligez)
+- PR#6672: Unused variance specification allowed in with constraint
+- PR#6744: Univars can escape through polymorphic variants (partial fix)
+- PR#6776: Failure to kill the "tick" thread, segfault when exiting the runtime
+- PR#6752: Extensible variant types and scope escaping
+- PR#6808: the parsing of OCAMLRUNPARAM is too lax
+ (Damien Doligez)
+* PR#6816: reject identifiers following numeric literals without spacing, e.g.
+ let foo = 1 in (fun a b -> a,b) 23foo
+ (Hugo Heuzard)
+- PR#6874: Inefficient code generated for module function arguments
+- PR#6897: Bad error message for some pattern matching on extensible variants
+- PR#6899: Optional parameters and non generalizable type variables
+ (Thomas Refis and Leo White)
+- PR#6931: Incorrect error message
+- PR#6938: fix regression on "%047.27{l,L,n}{d,i,x,X,o,u}"
+ (Benoît Vaugon, report by Arduino Cascella)
+- PR#6944: let module X = Path in … is not typed as a module alias
+ (Jacques Garrigue, report by def)
+- PR#6982: unexpected type error when packing a module alias
+- PR#6985: `module type of struct include Bar end exposes
+ %s#row when Bar contains private row types
+- PR#6992: Segfault from bug in GADT/module typing
+- PR#6993: Segfault from recursive modules violating exhaustiveness assumptions
+- GPR#205: Clear caml_backtrace_last_exn before registering as root (report
+ and fix by Frederic Bour)
+- GPR#220: minor -dsource error on recursive modules
+ (Hongbo Zhang)
+- GPR#228: fix a dangling internal pointer in (bytecode )debug_info
+ (Gabriel Scherer and Mark Shinwell and Xavier Leroy)
+- GPR#233: Make CamlinternalMod.init_mod robust to optimization
+ (Pierre Chambart, Mark Shinwell)
+
+Features wishes:
+- PR#4714: List.cons
+- PR#5418 (comments) : generate dependencies with $(CC) instead of gcc
+- PR#6167: OCAMLPARAM support for disabling PIC generation ("pic=0")
+ (Gabor Pali)
+- PR#6367: introduce Asttypes.arg_label to encode labelled arguments
+- PR#6452, GPR#140: add internal suport for custom printing formats
+ (Jérémie Dimino)
+- PR#6611: remove the option wrapper on optional arguments in the syntax tree
+- PR#6635: support M.[], M.(), M.{< >} and M.[| |]
+ (Jeremy Yallop, review by Gabriel Radanne)
+- PR#6691: install .cmt[i] files for stdlib and compiler-libs
+ (David Sheets, request by Gabriel Radanne)
+- PR#6722: compatibility with x32 architecture (x86-64 in ILP32 mode).
+ ocamlopt is not supported, but bytecode compiles cleanly.
+- PR#6742: remove duplicate virtual_flag information from Tstr_class
+- PR#6719: improve Buffer.add_channel when not enough input is available
+ (Simon Cruanes)
+* PR#6816: reject integer and float literals followed by alphanum
+ (Hugo Heuzard)
+- PR#6876: improve warning 6 by listing the omitted labels.
+ (Eyyüb Sari)
+- PR#6924: tiny optim to avoid some spilling of floats in x87
+ (Alain Frisch)
+- GPR#111: `(f [@taillcall]) x y` warns if `f x y` is not a tail-call
+ (Simon Cruanes)
+- GPR#118: ocamldep -allow-approx: fallback to a lexer-based approximation
+ (Frédéric Bour)
+- GPR#137: add untypeast.ml (in open recursion style) to compiler-libs
+ (Gabriel Radanne)
+- GPR#142: add a CAMLdrop macro for undoing CAMLparam*/CAMLlocal*
+- GPR#145: speeedup bigarray access by optimizing Cmmgen.bigarray_indexing
+ (Vladimir Brankov, review by Gabriel Scherer)
+- GPR#147: [type 'a result = Ok of 'a | Error of 'b] in Pervasives
+ (Yaron Minsky)
+- GPR#156: Optimize reallocation of caml_frame_descriptors (dynlink speedup)
+ (Pierre Chambart, review by François Bobot, Xavier Leroy and Damien Doligez)
+- GPR#171: allow custom warning printers / catchers
+ (Benjamin Canou, review by Damien Doligez)
+- GPR#191: Making gc.h and some part of memory.h public
+ (Thomas Refis)
+- GPR#196: Make [Thread.id] and [Thread.self] [noalloc]
+ (Clark Gaebel)
+- GPR#165, GPR#221: fix windows compilation warnings
+ (Bernhard Schommer, Gabriel Scherer, report by Alain Frisch)
+- GPR#189: Added .dylib and .so as extensions for ocamlmklib
+ (Edgar Aroutiounian, Peter Zotov)
+
+OCaml 4.02.3 (27 Jul 2015):
+---------------------------
+
+Bug fixes:
+- PR#6908: Top-level custom printing for GADTs: interface change in 4.02.2
+ (Grégoire Henry, report by Jeremy Yallop)
+- PR#6919: corrupted final_table
+ (ygrek)
+- PR#6926: Regression: ocamldoc lost unattached comment
+ (Damien Doligez, report by François Bobot)
+- PR#6930: Aliased result type of GADT constructor results in assertion failure
+ (Jacques Garrigue)
+
+Feature wishes:
+- PR#6691: install .cmt[i] files for stdlib and compiler-libs
+ (David Sheets, request by Gabriel Radanne)
+- GPR#37: New primitive: caml_alloc_dummy_function
+ (Hugo Heuzard)
+
+OCaml 4.02.2 (17 Jun 2015):
+---------------------------
+
+(Changes that can break existing programs are marked with a "*")
+
+Language features:
+- PR#6583: add a new class of binary operators with the same syntactic
+ precedence as method calls; these operators start with # followed
+ by a non-empty sequence of operator symbols (for instance #+, #!?).
+ It is also possible to use '#' as part of these extra symbols
+ (for instance ##, or #+#); this is rejected by the type-checker,
+ but can be used e.g. by ppx rewriters.
+ (Alain Frisch, request by Gabriel Radanne)
+* PR#6016: add a "nonrec" keyword for type declarations
+ (Jérémie Dimino)
+
+Compilers:
+- PR#6600: make -short-paths faster by building the printing map
+ incrementally
+ (Jacques Garrigue)
+- PR#6642: replace $CAMLORIGIN in -ccopt with the path to cma or cmxa
+ (Peter Zotov, Gabriel Scherer, review by Damien Doligez)
+- PR#6797: new option -output-complete-obj
+ to output an object file with included runtime and autolink libraries
+ (Peter Zotov)
+- PR#6845: -no-check-prims to tell ocamlc not to check primitives in runtime
+ (Alain Frisch)
+- GPR#149: Attach documentation comments to parse tree
+ (Leo White)
+- GPR#159: Better locations for structure/signature items
+ (Leo White)
+
+Toplevel and debugger:
+- PR#5958: generalized polymorphic #install_printer
+ (Pierre Chambart and Grégoire Henry)
+
+OCamlbuild:
+- PR#6237: explicit "infer" tag to control or disable menhir --infer
+ (Hugo Heuzard)
+- PR#6625: pass -linkpkg to files built with -output-obj.
+ (Peter Zotov)
+- PR#6702: explicit "linkpkg" and "dontlink(foo)" flags
+ (Peter Zotov, Gabriel Scherer)
+- PR#6712: Ignore common VCS directories
+ (Peter Zotov)
+- PR#6720: pass -g to C compilers when tag 'debug' is set
+ (Peter Zotov, Gabriel Scherer)
+- PR#6733: add .byte.so and .native.so targets to pass
+ -output-obj -cclib -shared.
+ (Peter Zotov)
+- PR#6733: "runtime_variant(X)" to pass -runtime-variant X option.
+ (Peter Zotov)
+- PR#6774: new menhir-specific flags "only_tokens" and "external_tokens(Foo)"
+ (François Pottier)
+
+Libraries:
+- PR#6285: Add support for nanosecond precision in Unix.stat()
+ (Jérémie Dimino, report by user 'gfxmonk')
+- PR#6781: Add higher baud rates to Unix termios
+ (Damien Doligez, report by Berke Durak)
+- PR#6834: Add Obj.{first,last}_non_constant_constructor_tag
+ (Mark Shinwell, request by Gabriel Scherer)
+
+Libraries:
+- PR#6285: Add support for nanosecond precision in Unix.stat()
+ (Jérémie Dimino, report by user 'gfxmonk')
+
+Runtime:
+- PR#6078: Release the runtime system when calling caml_dlopen
+ (Jérémie Dimino)
+- PR#6675: GC hooks
+ (Damien Doligez and Roshan James)
+
+Build system:
+- PR#5418 (comments) : generate dependencies with $(CC) instead of gcc
+ (Damien Doligez and Michael Grünewald)
+- PR#6266: Cross compilation for iOs, Android etc
+ (Peter Zotov, review by Damien Doligez and Mark Shinwell)
+
+Installation procedure:
+- Update instructions for x86-64 PIC mode and POWER architecture builds
+ (Mark Shinwell)
+
+Bug fixes:
+- PR#5271: Location.prerr_warning is hard-coded to use Format.err_formatter
+ (Damien Doligez, report by Rolf Rolles)
+- PR#5395: OCamlbuild mishandles relative symlinks and include paths
+ (Damien Doligez, report by Didier Le Botlan)
+- PR#5822: wrong value of Options.ext_dll on windows
+ (Damien Doligez and Daniel Weil)
+- PR#5836, PR#6684: printing lazy values in ocamldebug may segfault
+ (Gabriel Scherer, request by the Coq team)
+- PR#5887: move the byterun/*.h headers to byterun/caml/*.h to avoid
+ header name clashes
+ (Jérôme Vouillon and Adrien Nader and Peter Zotov)
+- PR#6281: Graphics window does not acknowledge second click (double click)
+ (Kyle Headley)
+- PR#6490: incorrect backtraces in gdb on AArch64. Also fixes incorrect
+ backtraces on 32-bit ARM.
+ (Mark Shinwell)
+- PR#6573: extern "C" for systhreads/threads.h
+ (Mickaël Delahaye)
+- PR#6575: Array.init evaluates callback although it should not do so
+ (Alain Frisch, report by Gerd Stolpmann)
+- PR#6607: The manual doesn't mention 0x200 flag for OCAMLRUNPARAM=v
+ (Alain Frisch)
+- PR#6616: allow meaningful use of -use-runtime without -custom.
+ (Peter Zotov)
+- PR#6617: allow android build with pthreads support (since SDK r10c)
+ (Peter Zotov)
+- PR#6626: ocamlbuild on cygwin cannot find ocamlfind
+ (Gergely Szilvasy)
+- PR#6628: Configure script rejects legitimate arguments
+ (Michael Grünewald, Damien Doligez)
+- PR#6630: Failure of tests/prim-bigstring/{big,}string.ml on big-endian
+ architectures
+ (Pierre Chambart, testing by Mark Shinwell)
+- PR#6640: ocamlbuild: wrong "unused tag" warning on "precious"
+ (report by user 'william')
+- PR#6652: ocamlbuild -clean does not print a newline after output
+ (Damien Doligez, report by Andi McClure)
+- PR#6658: cross-compiler: version check not working on OS X
+ (Gerd Stolpmann)
+- PR#6665: Failure of tests/asmcomp on sparc
+ (Stéphane Glondu)
+- PR#6667: wrong implementation of %bswap16 on ARM64
+ (Xavier Leroy)
+- PR#6669: fix 4.02 regression in toplevel printing of lazy values
+ (Leo White, review by Gabriel Scherer)
+- PR#6671: Windows: environment variable 'TZ' affects Unix.gettimeofday
+ (Mickael Delahaye and Damien Doligez)
+- PR#6680: Missing parentheses in warning about polymorphic variant value
+ (Jacques Garrigue and Gabriel Scherer, report by Philippe Veber)
+- PR#6686: Bug in [subst_boxed_number]
+ (Jérémie Dimino, Mark Shinwell)
+- PR#6690: Uncaught exception (Not_found) with (wrong) wildcard or unification
+ type variable in place of a local abstract type
+ (Jacques Garrigue, report by Mikhail Mandrykin)
+- PR#6693 (part two): Incorrect relocation types in x86-64 runtime system
+ (Peter Zotov, review by Jacques-Henri Jourdan, Xavier Leroy and Mark Shinwell)
+- PR#6717: Pprintast does not print let-pattern attributes
+ (Gabriel Scherer, report by Peter Zotov)
+- PR#6727: Printf.sprintf "%F" misbehavior
+ (Benoît Vaugon, report by Vassili Karpov)
+- PR#6747: ocamlobjinfo: missing symbol caml_plugin_header due to underscore
+ (Damien Doligez, Maverick Woo)
+- PR#6749: ocamlopt returns n for (n mod 1) instead of 0
+ (Mark Shinwell and Jérémie Dimino)
+- PR#6753: Num.quo_num and Num.mod_num incorrect for some negative arguments
+ (Xavier Leroy)
+- PR#6758: Ocamldoc "analyse_module: parsetree and typedtree don't match"
+ (Damien Doligez, report by user 'maro')
+- PR#6759: big_int_of_string incorrectly parses some hexa literals
+ (Damien Doligez, report by Pierre-yves Strub)
+- PR#6763: #show with -short-paths doesn't select shortest type paths
+ (Jacques Garrigue, report by David Sheets)
+- PR#6768: Typechecker overflow the stack on cyclic type
+ (Jacques Garrigue, report by user 'darktenaibre')
+- PR#6770: (duplicate of PR#6686)
+- PR#6772: asmrun/signals_asm.c doesn't compile on NetBSD/i386
+ (Kenji Tokudome)
+- PR#6775: Digest.file leaks file descriptor on error
+ (Valentin Gatien-Baron)
+- PR#6779: Cross-compilers cannot link bytecode using custom primitives
+ (Damien Doligez, request by Peter Zotov)
+- PR#6787: Soundness bug with polymorphic variants
+ (Jacques Garrigue, with help from Leo White and Grégoire Henry,
+ report by Michael O'Connor)
+- PR#6790: otherlibs should be built with -g
+ (Damien Doligez, report by Peter Zotov)
+- PR#6791: "%s@[", "%s@{" regression in Scanf
+ (Benoît Vaugon)
+- PR#6793: ocamlbuild passes nonsensical "-ocamlc ..." commands to menhir
+ (Gabriel Scherer, report by Damien Doligez)
+- PR#6799: include guards missing for unixsupport.h and other files
+ (Andreas Hauptmann)
+- PR#6810: Improve documentation of Bigarray.Genarray.map_file
+ (Mark Shinwell and Daniel Bünzli)
+- PR#6812: -short-paths and -no-alias-deps can create inconsistent assumptions
+ (Jacques Garrigue, report by Valentin Gatien-Baron)
+- PR#6817: GADT exhaustiveness breakage with modules
+ (Leo White, report by Pierre Chambart)
+- PR#6824: fix buffer sharing on partial application of Format.asprintf
+ (Gabriel Scherer, report by Alain Frisch)
+- PR#6831: Build breaks for -aspp gcc on solaris-like OSs
+ (John Tibble)
+- PR#6836: Assertion failure using -short-paths
+ (Jacques Garrigue, report by David Sheets)
+- PR#6837: Build profiling libraries on FreeBSD and NetBSD x86-64
+ (Mark Shinwell, report by Michael Grünewald)
+- PR#6841: Changing compilation unit name with -o breaks ocamldebug
+ (Jacques Garrigue, report by Jordan Walke)
+- PR#6842: export Typemod.modtype_of_package
+- PR#6843: record weak dependencies even when the .cmi is missing
+ (Leo White, Gabriel Scherer)
+- PR#6849: Inverted pattern unification error
+ (Jacques Garrigue, report by Leo White)
+- PR#6857: __MODULE__ doesn't give the current module with -o
+ (Jacques Garrigue, report by Valentin Gatien-Baron)
+- PR#6862: Exhaustiveness check wrong for class constructor arguments
+ (Jacques Garrigue)
+- PR#6869: Improve comment on [Hashtbl.hash_param]
+ (Mark Shinwell, report by Jun Furuse)
+- PR#6870: Unsoundness when -rectypes fails to detect non-contractive type
+ (Jacques Garrigue, report by Stephen Dolan)
+- PR#6872: Type-directed propagation fails to disambiguate variants
+ that are also exception constructors
+ (Jacques Garrigue, report by Romain Beauxis)
+- PR#6878: AArch64 backend generates invalid asm: conditional branch
+ out of range (Mark Shinwell, report by Richard Jones, testing by Richard
+ Jones and Xavier Leroy, code review by Xavier Leroy and Thomas Refis)
+- PR#6879: Wrong optimization of 1 mod n
+ (Mark Shinwell, report by Jean-Christophe Filliâtre)
+- PR#6884: The __CYGWIN32__ #define should be replaced with __CYGWIN__
+ (Adrien Nader)
+- PR#6886: -no-alias-deps allows to build self-referential compilation units
+ (Jacques Garrigue, report by Valentin Gatien-Baron)
+- PR#6889: ast_mapper fails to rewrite class attributes
+ (Sébastien Briais)
+- PR#6893: ocamlbuild: "tag not used" warning when using (p)dep
+ (Gabriel Scherer, report by Christiano Haesbaert)
+- GPR#143: fix getsockopt behaviour for boolean socket options
+ (Anil Madhavapeddy and Andrew Ray)
+- GPR#190: typo in pervasives
+ (Guillaume Bury)
+- Misplaced assertion in major_gc.c for no-naked-pointers mode
+ (Stephen Dolan, Mark Shinwell)
+
+Feature wishes:
+- PR#6452, GPR#140: add internal suport for custom printing formats
+ (Jérémie Dimino)
+- PR#6641: add -g, -ocamlcflags, -ocamloptflags options to ocamlmklib
+ (Peter Zotov)
+- PR#6693: also build libasmrun_shared.so and lib{asm,caml}run_pic.a
+ (Peter Zotov, review by Mark Shinwell)
+- PR#6842: export Typemod.modtype_of_package
+ (Jacques Garrigue, request by Jun Furuse)
+- GPR#139: more versatile specification of locations of .annot
+ (Christophe Troestler, review by Damien Doligez)
+- GPR#171: allow custom warning printers / catchers
+ (Benjamin Canou, review by Damien Doligez)
+- Misplaced assertion in major_gc.c for no-naked-pointers mode
+ (Stephen Dolan, Mark Shinwell)
+- GPR#191: Making gc.h and some part of memory.h public
+ (Thomas Refis)
+
+OCaml 4.02.1 (14 Oct 2014):
+---------------------------
+
+(Changes that can break existing programs are marked with a "*")
+
+Standard library:
+* Add optional argument ?limit to Arg.align.
+
+- PR#4099: Bug in Makefile.nt: won't stop on error
+ (George Necula)
+- PR#6181: Improve MSVC build
+ (Chen Gang)
+- PR#6207: Configure doesn't detect features correctly on Haiku
+ (Jessica Hamilton)
+- PR#6466: Non-exhaustive matching warning message for open types is confusing
+ (Peter Zotov)
+- PR#6529: fix quadratic-time algorithm in Consistbl.extract.
+ (Xavier Leroy, Alain Frisch, relase-worthy report by Jacques-Pascal Deplaix)
+- PR#6530: Add stack overflow handling for native code (OpenBSD i386 and amd64)
+ (Cristopher Zimmermann)
+- PR#6533: broken semantics of %(%) when substituted by a box
+ (Benoît Vaugon, report by Boris Yakobowski)
+- PR#6534: legacy support for %.10s
+ (Benoît Vaugon, Gabriel Scherer, report by Nick Chapman)
+- PR#6536: better documentation of flag # in format strings
+ (Damien Doligez, report by Nick Chapman)
+- PR#6544: Bytes and CamlinternalFormat missing from threads stdlib.cma
+ (Christopher Zimmermann)
+- PR#6546: -dsource omits parens for `List ((`String "A")::[]) in patterns
+ (Gabriel Scherer, report by Peter Zotov)
+- PR#6547: __MODULE__ aborts the compiler if the module name cannot be inferred
+ (Jacques Garrigue, report by Kaustuv Chaudhuri)
+- PR#6549: Debug section is sometimes not readable when using -pack
+ (Hugo Heuzard, review by Gabriel Scherer)
+- PR#6553: Missing command line options for ocamldoc
+ (Maxence Guesdon)
+- PR#6554: fix race condition when retrieving backtraces
+ (Jérémie Dimino, Mark Shinwell).
+- PR#6557: String.sub throws Invalid_argument("Bytes.sub")
+ (Damien Doligez, report by Oliver Bandel)
+- PR#6562: Fix ocamldebug module source lookup
+ (Leo White)
+- PR#6563: Inclusion of packs failing to run module initializers
+ (Jacques Garrigue, report by Mark Shinwell)
+- PR#6564: infinite loop in Mtype.remove_aliases
+ (Jacques Garrigue, report by Mark Shinwell)
+- PR#6565: compilation fails with Env.Error(_)
+ (Jacques Garrigue and Mark Shinwell)
+- PR#6566: -short-paths and signature inclusion errors
+ (Jacques Garrigue, report by Mark Shinwell)
+- PR#6572: Fatal error with recursive modules
+ (Jacques Garrigue, report by Quentin Stievenart)
+- PR#6575: Array.init evaluates callback although it should not do so
+ (Alain Frisch, report by Gerd Stolpmann)
+- PR#6578: Recursive module containing alias causes Segmentation fault
+ (Jacques Garrigue)
+- PR#6581: Some bugs in generative functors
+ (Jacques Garrigue, report by Mark Shinwell)
+- PR#6584: ocamldep support for "-open M"
+ (Gabriel Scherer, review by Damien Doligez, report by Hezekiah M. Carty)
+- PR#6588: Code generation errors for ARM
+ (Mark Shinwell, Xavier Leroy)
+- PR#6590: Improve Windows (MSVC and mingw) build
+ (Chen Gang)
+- PR#6599: ocamlbuild: add -bin-annot when using -pack
+ (Christopher Zimmermann)
+- PR#6602: Fatal error when tracing a function with abstract type
+ (Jacques Garrigue, report by Hugo Herbelin)
+- ocamlbuild: add an -ocamlmklib option to change the ocamlmklib command
+ (Jérôme Vouillon)
+
+OCaml 4.02.0 (29 Aug 2014):
+---------------------------
+
+(Changes that can break existing programs are marked with a "*")
+
+Language features:
+- Attributes and extension nodes
+ (Alain Frisch)
+- Generative functors (PR#5905)
+ (Jacques Garrigue)
+* Module aliases
+ (Jacques Garrigue)
+* Alternative syntax for string literals {id|...|id} (can break comments)
+ (Alain Frisch)
+- Separation between read-only strings (type string) and read-write byte
+ sequences (type bytes). Activated by command-line option -safe-string.
+ (Damien Doligez)
+- PR#6318: Exception cases in pattern matching
+ (Jeremy Yallop, backend by Alain Frisch)
+- PR#5584: Extensible open datatypes
+ (Leo White)
+
+Build system for the OCaml distribution:
+- Use -bin-annot when building.
+- Use GNU make instead of portable makefiles.
+- Updated build instructions for 32-bit Mac OS X on Intel hardware.
+
+Shedding weight:
+* Removed Camlp4 from the distribution, now available as third-party software.
+* Removed Labltk from the distribution, now available as a third-party library.
+
+Type system:
+* PR#6235: Keep typing of pattern cases independent in principal mode
+ (i.e. information from previous cases is no longer used when typing
+ patterns; cf. 'PR#6235' in testsuite/test/typing-warnings/records.ml)
+ (Jacques Garrigue)
+- Allow opening a first-class module or applying a generative functor
+ in the body of a generative functor. Allow it also in the body of
+ an applicative functor if no types are created
+ (Jacques Garrigue, suggestion by Leo White)
+* Module aliases are now typed in a specific way, which remembers their
+ identity. Compiled interfaces become smaller, but may depend on the
+ original modules. This also changes the signature inferred by
+ "module type of".
+ (Jacques Garrigue, feedback from Leo White, Mark Shinwell and Nick Chapman)
+- PR#6331: Slight change in the criterion to distinguish private
+ abbreviations and private row types: create a private abbreviation for
+ closed objects and fixed polymorphic variants.
+ (Jacques Garrigue)
+* PR#6333: Compare first class module types structurally rather than
+ nominally. Value subtyping allows module subtyping as long as the internal
+ representation is unchanged.
+ (Jacques Garrigue)
+
+Compilers:
+- More aggressive constant propagation, including float and
+ int32/int64/nativeint arithmetic. Constant propagation for floats
+ can be turned off with option -no-float-const-prop, for codes that
+ change FP rounding modes at run-time.
+ (Xavier Leroy)
+- New back-end optimization pass: common subexpression elimination (CSE).
+ (Reuses results of previous computations instead of recomputing them.)
+ (Xavier Leroy)
+- New back-end optimization pass: dead code elimination.
+ (Removes arithmetic and load instructions whose results are unused.)
+ (Xavier Leroy)
+- PR#6269: Optimization of sequences of string patterns
+ (Benoît Vaugon and Luc Maranget)
+- Experimental native code generator for AArch64 (ARM 64 bits)
+ (Xavier Leroy)
+- PR#6042: Optimization of integer division and modulus by constant divisors
+ (Xavier Leroy and Phil Denys)
+- Add "-open" command line flag for opening a single module before typing
+ (Leo White, Mark Shinwell and Nick Chapman)
+* "-o" now sets module name to the output file name up to the first "."
+ (it also applies when "-o" is not given, i.e. the module name is then
+ the input file name up to the first ".")
+ (Leo White, Mark Shinwell and Nick Chapman)
+* PR#5779: better sharing of structured constants
+ (Alain Frisch)
+- PR#5817: new flag to keep locations in cmi files
+ (Alain Frisch)
+- PR#5854: issue warning 3 when referring to a value marked with
+ the [@@ocaml.deprecated] attribute
+ (Alain Frisch, suggestion by Pierre-Marie Pédrot)
+- PR#6017: a new format implementation based on GADTs
+ (Benoît Vaugon and Gabriel Scherer)
+* PR#6203: Constant exception constructors no longer allocate
+ (Alain Frisch)
+- PR#6260: avoid unnecessary boxing in let
+ (Vladimir Brankov)
+- PR#6345: Better compilation of optional arguments with default values
+ (Alain Frisch, review by Jacques Garrigue)
+- PR#6389: ocamlopt -opaque option for incremental native compilation
+ (Pierre Chambart, Gabriel Scherer)
+
+Toplevel interactive system:
+- PR#5377: New "#show_*" directives
+ (ygrek, Jacques Garrigue and Alain Frisch)
+
+Runtime system:
+- New configure option "-no-naked-pointers" to improve performance by
+ avoiding page table tests during block darkening and the marking phase
+ of the major GC. In this mode, all out-of-heap pointers must point at
+ things that look like OCaml values: in particular they must have a valid
+ header. The colour of said headers should be black.
+ (Mark Shinwell, reviews by Damien Doligez and Xavier Leroy)
+- Fixed bug in native code version of [caml_raise_with_string] that could
+ potentially lead to heap corruption.
+ (Mark Shinwell)
+* Blocks initialized by [CAMLlocal*] and [caml_alloc] are now filled with
+ [Val_unit] rather than zero.
+ (Mark Shinwell)
+- Fixed a major performance problem on large heaps (~1GB) by making heap
+ increments proportional to heap size by default
+ (Damien Doligez)
+- PR#4765: Structural equality treats exception specifically
+ (Alain Frisch)
+- PR#5009: efficient comparison/indexing of exceptions
+ (Alain Frisch, request by Markus Mottl)
+- PR#6075: avoid using unsafe C library functions (strcpy, strcat, sprintf)
+ (Xavier Leroy, reports from user 'jfc' and Anil Madhavapeddy)
+- An ISO C99-compliant C compiler and standard library is now assumed.
+ (Plus special exceptions for MSVC.) In particular, emulation code for
+ 64-bit integer arithmetic was removed, the C compiler must support a
+ 64-bit integer type.
+ (Xavier Leroy)
+
+Standard library:
+* Add new modules Bytes and BytesLabels for mutable byte sequences.
+ (Damien Doligez)
+- PR#4986: add List.sort_uniq and Set.of_list
+ (Alain Frisch)
+- PR#5935: a faster version of "raise" which does not maintain the backtrace
+ (Alain Frisch)
+- PR#6146: support "Unix.kill pid Sys.sigkill" under Windows
+ (Romain Bardou and Alain Frisch)
+- PR#6148: speed improvement for Buffer
+ (John Whitington)
+- PR#6180: efficient creation of uninitialized float arrays
+ (Alain Frisch, request by Markus Mottl)
+- PR#6355: Improve documentation regarding finalisers and multithreading
+ (Daniel Bünzli, Mark Shinwell)
+- Trigger warning 3 for all values marked as deprecated in the documentation.
+ (Damien Doligez)
+
+OCamldoc:
+- PR#6257: handle full doc comments for variant constructors and
+ record fields
+ (Maxence Guesdon, request by ygrek)
+- PR#6274: allow doc comments on object types
+ (Thomas Refis)
+- PR#6310: fix ocamldoc's subscript/superscript CSS font size
+ (Anil Madhavapeddy)
+- PR#6425: fix generation of man pages
+ (Maxence Guesdon, report by Anil Madhavapeddy)
+
+Bug fixes:
+- PR#2719: wrong scheduling of bound checks within a
+ try...with Invalid_argument -> _ ... (Xavier Leroy)
+- PR#4719: Sys.executable_name wrong if executable name contains dots (Windows)
+ (Alain Frisch, report by Bart Jacobs)
+- PR#5406 ocamlbuild: "tag 'package' does not expect a parameter"
+ (Gabriel Scherer)
+- PR#5598, PR#6165: Alterations to handling of \013 in source files
+ breaking other tools
+ (David Allsopp and Damien Doligez)
+- PR#5820: Fix camlp4 lexer roll back problem
+ (Hongbo Zhang)
+- PR#5946: CAMLprim taking (void) as argument
+ (Benoît Vaugon)
+- PR#6038: on x86-32, enforce 16-byte stack alignment for compatibility
+ with recent GCC and Clang. Win32/MSVC keeps 4-byte stack alignment.
+ (Xavier Leroy)
+- PR#6062: Fix a 4.01 camlp4 DELETE_RULE regression caused by commit 13047
+ (Hongbo Zhang, report by Christophe Troestler)
+- PR#6173: Typing error message is worse than before
+ (Jacques Garrigue and John Whitington)
+- PR#6174: OCaml compiler loops on an example using GADTs (-rectypes case)
+ (Jacques Garrigue and Grégoire Henry, report by Chantal Keller)
+- PR#6175: open! was not suppored by camlp4
+ (Hongbo Zhang)
+- PR#6184: ocamlbuild: `ocamlfind ocamldep` does not support -predicate
+ (Jacques-Pascal Deplaix)
+- PR#6194: Incorrect unused warning with first-class modules in patterns
+ (Jacques Garrigue, report by Markus Mottl and Leo White)
+- PR#6211: in toplevel interactive use, bad interaction between uncaught
+ exceptions and multiple bindings of the form "let x = a let y = b;;".
+ (Xavier Leroy)
+- PR#6216: inlining of GADT matches generates invalid assembly
+ (Xavier Leroy and Alain Frisch, report by Mark Shinwell)
+- PR#6232: Don't use [mktemp] on platforms where [mkstemp] is available
+ (Stéphane Glondu, Mark Shinwell)
+- PR#6233: out-of-bounds exceptions lose their locations on ARM, PowerPC
+ (Jacques-Henri Jourdan and Xavier Leroy,
+ report and testing by Stéphane Glondu)
+- PR#6235: Issue with type information flowing through a variant pattern
+ (Jacques Garrigue, report by Hongbo Zhang)
+- PR#6239: sometimes wrong stack alignment when raising exceptions
+ in -g mode with backtraces active
+ (Xavier Leroy, report by Yaron Minsky)
+- PR#6240: Fail to expand module type abbreviation during substyping
+ (Jacques Garrigue, report by Leo White)
+- PR#6241: Assumed inequality between paths involving functor arguments
+ (Jacques Garrigue, report by Jeremy Yallop)
+- PR#6243: Make "ocamlopt -g" more resistant to ill-formed locations
+ (Xavier Leroy, report by Pierre-Marie Pédrot)
+- PR#6262: equality of first-class modules take module aliases into account
+ (Alain Frisch and Leo White)
+- PR#6268: -DMODEL_$(MODEL) not passed when building asmrun/arm.p.o
+ (Peter Michael Green)
+- PR#6273: fix Sys.file_exists on large files (Win32)
+ (Christoph Bauer)
+- PR#6275: Soundness bug related to type constraints
+ (Jacques Garrigue, report by Leo White)
+- PR#6293: Assert_failure with invalid package type
+ (Jacques Garrigue, report by Elnatan Reisner)
+- PR#6300: ocamlbuild -use-ocamlfind conflicts with -ocamlc
+ (Gabriel Scherer)
+- PR#6302: bytecode debug information re-read from filesystem every time
+ (Jacques-Henri Jourdan)
+- PR#6307: Behavior of 'module type of' w.r.t. module aliases
+ (Jacques Garrigue, report by Alain Frisch)
+- PR#6332: Unix.open_process fails to pass empty arguments under Windows
+ (Damien Doligez, report Virgile Prevosto)
+- PR#6346: Build failure with latest version of xcode on OSX
+ (Jérémie Dimino)
+- PR#6348: Unification failure for GADT when original definition is hidden
+ (Leo White and Jacques Garrigue, report by Jeremy Yallop)
+- PR#6352: Automatic removal of optional arguments and sequencing
+ (Jacques Garrigue and Alain Frisch)
+- PR#6361: Hashtbl.hash not terminating on some lazy values w/ recursive types
+ (Xavier Leroy, report by Leo White)
+- PR#6383: Exception Not_found when using object type in absent module
+ (Jacques Garrigue, report by Sébastien Briais)
+- PR#6384: Uncaught Not_found exception with a hidden .cmi file
+ (Leo White)
+- PR#6385: wrong allocation of large closures by the bytecode interpreter
+ (Xavier Leroy, report by Stephen Dolan)
+- PR#6394: Assertion failed in Typecore.expand_path
+ (Alain Frisch and Jacques Garrigue)
+- PR#6405: unsound interaction of -rectypes and GADTs
+ (Jacques Garrigue, report by Gabriel Scherer and Benoît Vaugon)
+- PR#6408: Optional arguments given as ~?arg instead of ?arg in message
+ (Michael O'Connor)
+- PR#6411: missing libgcc_s_sjlj-1.dll in mingw (add -static-libgcc)
+ (Jun Furuse and Alain Frisch, Jonathan Protzenko and Adrien Nader)
+- PR#6436: Typos in @deprecated text in stdlib/arrayLabels.mli
+ (John Whitington)
+- PR#6439: Don't use the deprecated [getpagesize] function
+ (John Whitington, Mark Shinwell)
+- PR#6441: undetected tail-call in some mutually-recursive functions
+ (many arguments, and mutual block mixes functions and non-functions)
+ (Stefan Holdermans, review by Xavier Leroy)
+- PR#6443: ocaml segfault when List.fold_left is traced then executed
+ (Jacques Garrigue, report by user 'Reventlov')
+- PR#6451: some bugs in untypeast.ml
+ (Jun Furuse, review by Alain Frisch)
+- PR#6460: runtime assertion failure with large [| e1;...eN |]
+ float array expressions
+ (Leo White)
+- PR#6463: -dtypedtree fails on class fields
+ (Leo White)
+- PR#6469: invalid -dsource printing of "external _pipe = ...", "Pervasives.(!)"
+ (Gabriel Scherer and Damien Doligez, user 'ngunn')
+- PR#6482: ocamlbuild fails when _tags file in unhygienic directory
+ (Gabriel Scherer)
+- PR#6502: ocamlbuild spurious warning on "use_menhir" tag
+ (Xavier Leroy)
+- PR#6505: Missed Type-error leads to a segfault upon record access
+ (Jacques Garrigue, Jeremy Yallop, report by Christoph Höger)
+- PR#6507: crash on AArch64 resulting from incorrect setting of
+ [caml_bottom_of_stack]. (Richard Jones, Mark Shinwell)
+- PR#6509: add -linkall flag to ocamlcommon.cma
+ (Frédéric Bour)
+- PR#6513: Fatal error Ctype.Unify(_) in functor type
+- PR#6523: failure upon character bigarray access, and unnecessary change
+ in comparison ordering (Jeremy Yallop, Mark Shinwell)
+- bound-checking bug in caml_string_{get,set}{16,32,64}
+ (Pierre Chambart and Gabriel Scherer, report by Nicolas Trangez)
+- sometimes wrong stack alignment at out-of-bounds array access
+ (Gabriel Scherer and Xavier Leroy, report by Pierre Chambart)
+
+Features wishes:
+- PR#4243: make the Makefiles parallelizable
+ (Grégoire Henry and Damien Doligez)
+- PR#4323: have "of_string" in Num and Big_int work with binary and
+ hex representations
+ (Zoe Paraskevopoulou, review by Gabriel Scherer)
+- PR#4771: Clarify documentation of Dynlink.allow_only
+ (Damien Doligez, report by David Allsopp)
+- PR#4855: 'camlp4 -I +dir' accepted, dir is relative to 'camlp4 -where'
+ (Jun Furuse and Hongbo Zhang, report by Dmitry Grebeniuk)
+- PR#5201: ocamlbuild: add --norc to the bash invocation to help performances
+ (Daniel Weil)
+- PR#5650: Camlp4FoldGenerator doesn't handle well "abstract" types
+ (Hongbo Zhang)
+- PR#5808: allow simple patterns, not just identifiers, in "let p : t = ..."
+ (Alain Frisch)
+- PR#5851: warn when -r is disabled because no _tags file is present
+ (Gabriel Scherer)
+- PR#5899: a programmer-friendly access to backtrace information
+ (Jacques-Henri Jourdan and Gabriel Scherer)
+- PR#6000 comment 9644: add a warning for non-principal coercions to format
+ (Jacques Garrigue, report by Damien Doligez)
+- PR#6054: add support for M.[ foo ], M.[| foo |] etc.
+ (Kaustuv Chaudhuri)
+- PR#6064: GADT representation for Bigarray.kind + CAML_BA_CHAR runtime kind
+ (Jeremy Yallop, review by Gabriel Scherer)
+- PR#6071: Add a -noinit option to the toplevel
+ (David Sheets)
+- PR#6087: ocamlbuild, improve _tags parsing of escaped newlines
+ (Gabriel Scherer, request by Daniel Bünzli)
+- PR#6109: Typos in ocamlbuild error messages
+ (Gabriel Kerneis)
+- PR#6116: more efficient implementation of Digest.to_hex
+ (ygrek)
+- PR#6142: add cmt file support to ocamlobjinfo
+ (Anil Madhavapeddy)
+- PR#6166: document -ocamldoc option of ocamlbuild
+ (Xavier Clerc)
+- PR#6182: better message for virtual objects and class types
+ (Leo White, Stephen Dolan)
+- PR#6183: enhanced documentation for 'Unix.shutdown_connection'
+ (Anil Madhavapeddy, report by Jun Furuse)
+- PR#6187: ocamlbuild: warn when using -plugin-tag(s) without myocamlbuild.ml
+ (Jacques-Pascal Deplaix)
+- PR#6246: allow wildcard _ as for-loop index
+ (Alain Frisch, request by ygrek)
+- PR#6267: more information printed by "bt" command of ocamldebug
+ (Josh Watzman)
+- PR#6270: remove need for -I directives to ocamldebug in common case
+ (Josh Watzman, review by Xavier Clerc and Alain Frisch)
+- PR#6311: Improve signature mismatch error messages
+ (Alain Frisch, suggestion by Daniel Bünzli)
+- PR#6358: obey DESTDIR in install targets
+ (Gabriel Scherer, request by François Berenger)
+- PR#6388, PR#6424: more parsetree correctness checks for -ppx users
+ (Alain Frisch, request by Peter Zotov and Jun Furuse)
+- PR#6406: Expose OCaml version in C headers
+ (Peter Zotov and Romain Calascibetta)
+- PR#6446: improve "unused declaration" warnings wrt. name shadowing
+ (Alain Frisch)
+- PR#6495: ocamlbuild tags 'safe_string', 'unsafe_string'
+ (Anil Madhavapeddy)
+- PR#6497: pass context information to -ppx preprocessors
+ (Peter Zotov, Alain Frisch)
+- ocamllex: user-definable refill action
+ (Frédéric Bour, review by Gabriel Scherer and Luc Maranget)
+- shorten syntax for functor signatures: "functor (M1:S1) (M2:S2) .. -> .."
+ (Thomas Gazagnaire and Jeremy Yallop, review by Gabriel Scherer)
+- make ocamldebug -I auto-detection work with ocamlbuild
+ (Josh Watzman)
+
+OCaml 4.01.0 (12 Sep 2013):
+---------------------------
+
+(Changes that can break existing programs are marked with a "*")
+
+Other libraries:
+- Labltk: updated to Tcl/Tk 8.6.
+
+Type system:
+- PR#5759: use well-disciplined type information propagation to
+ disambiguate label and constructor names
+ (Jacques Garrigue, Alain Frisch and Leo P. White)
+* Propagate type information towards pattern-matching, even in the presence of
+ polymorphic variants (discarding only information about possibly-present
+ constructors). As a result, matching against absent constructors is no longer
+ allowed for exact and fixed polymorphic variant types.
+ (Jacques Garrigue)
+* PR#6035: Reject multiple declarations of the same method or instance variable
+ in an object
+ (Alain Frisch)
+
+Compilers:
+- PR#5861: raise an error when multiple private keywords are used in type
+ declarations
+ (Hongbo Zhang)
+- PR#5634: parsetree rewriter (-ppx flag)
+ (Alain Frisch)
+- ocamldep now supports -absname
+ (Alain Frisch)
+- PR#5768: On "unbound identifier" errors, use spell-checking to suggest names
+ present in the environment
+ (Gabriel Scherer)
+- ocamlc has a new option -dsource to visualize the parsetree
+ (Alain Frisch, Hongbo Zhang)
+- tools/eqparsetree compares two parsetree ignoring location
+ (Hongbo Zhang)
+- ocamlopt now uses clang as assembler on OS X if available, which enables
+ CFI support for OS X.
+ (Benedikt Meurer)
+- Added a new -short-paths option, which attempts to use the shortest
+ representation for type constructors inside types, taking open modules
+ into account. This can make types much more readable if your code
+ uses lots of functors.
+ (Jacques Garrigue)
+- PR#5986: added flag -compat-32 to ocamlc, ensuring that the generated
+ bytecode executable can be loaded on 32-bit hosts.
+ (Xavier Leroy)
+- PR#5980: warning on open statements which shadow an existing
+ identifier (if it is actually used in the scope of the open); new
+ open! syntax to silence it locally
+ (Alain Frisch, thanks to a report of Daniel Bünzli)
+* warning 3 is extended to warn about other deprecated features:
+ - ISO-latin1 characters in identifiers
+ - uses of the (&) and (or) operators instead of (&&) and (||)
+ (Damien Doligez)
+- Experimental OCAMLPARAM for ocamlc and ocamlopt
+ (Fabrice Le Fessant)
+- PR#5571: incorrect ordinal number in error message
+ (Alain Frisch, report by John Carr)
+- PR#6073: add signature to Tstr_include
+ (patch by Leo P. White)
+
+Standard library:
+- PR#5899: expose a way to inspect the current call stack,
+ Printexc.get_callstack
+ (Gabriel Scherer, Jacques-Henri Jourdan, Alain Frisch)
+- PR#5986: new flag Marshal.Compat_32 for the serialization functions
+ (Marshal.to_*), forcing the output to be readable on 32-bit hosts.
+ (Xavier Leroy)
+- infix application operators |> and @@ in Pervasives
+ (Fabrice Le Fessant)
+- PR#6176: new Format.asprintf function with a %a formatter
+ compatible with Format.fprintf (unlike Format.sprintf)
+ (Pierre Weis)
+
+Other libraries:
+- PR#5568: add O_CLOEXEC flag to Unix.openfile, so that the returned
+ file descriptor is created in close-on-exec mode
+ (Xavier Leroy)
+
+Runtime system:
+* PR#6019: more efficient implementation of caml_modify() and caml_initialize().
+ The new implementations are less lenient than the old ones: now,
+ the destination pointer of caml_modify() must point within the minor or
+ major heaps, and the destination pointer of caml_initialize() must
+ point within the major heap.
+ (Xavier Leroy, from an experiment by Brian Nigito, with feedback
+ from Yaron Minsky and Gerd Stolpmann)
+
+Internals:
+- Moved debugger/envaux.ml to typing/envaux.ml to publish env_of_only_summary
+ as part of compilerlibs, to be used on bin-annot files.
+ (Fabrice Le Fessant)
+- The test suite can now be run without installing OCaml first.
+ (Damien Doligez)
+
+Bug fixes:
+- PR#3236: Document the fact that queues are not thread-safe
+ (Damien Doligez)
+- PR#3468: (part 1) Sys_error documentation
+ (Damien Doligez)
+- PR#3679: Warning display problems
+ (Fabrice Le Fessant)
+- PR#3963: Graphics.wait_next_event in Win32 hangs if window closed
+ (Damien Doligez)
+- PR#4079: Queue.copy is now tail-recursive
+ (patch by Christophe Papazian)
+- PR#4138: Documentation for Unix.mkdir
+ (Damien Doligez)
+- PR#4469: emacs mode: caml-set-compile-command is annoying with ocamlbuild
+ (Daniel Bünzli)
+- PR#4485: Graphics: Keyboard events incorrectly delivered in native code
+ (Damien Doligez, report by Sharvil Nanavati)
+- PR#4502: ocamlbuild now reliably excludes the build-dir from hygiene check
+ (Gabriel Scherer, report by Romain Bardou)
+- PR#4762: ?? is not used at all, but registered as a lexer token
+ (Alain Frisch)
+- PR#4788: wrong error message when executable file is not found for backtrace
+ (Damien Doligez, report by Claudio Sacerdoti Coen)
+- PR#4812: otherlibs/unix: add extern int code_of_unix_error (value error);
+ (Goswin von Berdelow)
+- PR#4887: input_char after close_in crashes ocaml (msvc runtime)
+ (Alain Frisch and Christoph Bauer, report by ygrek)
+- PR#4994: ocaml-mode doesn't work with xemacs21
+ (Damien Doligez, report by Stéphane Glondu)
+- PR#5098: creating module values may lead to memory leaks
+ (Alain Frisch, report by Milan Stanojević)
+- PR#5102: ocamlbuild fails when using an unbound variable in rule dependency
+ (Xavier Clerc, report by Daniel Bünzli)
+* PR#5119: camlp4 now raises a specific exception when 'DELETE_RULE' fails,
+ rather than raising 'Not_found'
+ (ygrek)
+- PR#5121: %( %) in Format module seems to be broken
+ (Pierre Weis, first patch by Valentin Gatien-Baron, report by Khoo Yit Phang)
+- PR#5178: document in INSTALL how to build a 32-bit version under Linux x86-64
+ (Benjamin Monate)
+- PR#5212: Improve ocamlbuild error messages of _tags parser
+ (ygrek)
+- PR#5240: register exception printers for Unix.Unix_error and Dynlink.Error
+ (Jérémie Dimino)
+- PR#5300: ocamlbuild: verbose parameter should implicitly set classic display
+ (Xavier Clerc, report by Robert Jakob)
+- PR#5327: (Windows) Unix.select blocks if same socket listed in first and
+ third arguments
+ (David Allsopp, displaying impressive MSDN skills)
+- PR#5343: ocaml -rectypes is unsound wrt module subtyping (was still unsound)
+ (Jacques Garrigue)
+- PR#5350: missing return code checks in the runtime system
+ (Xavier Leroy)
+- PR#5468: ocamlbuild should preserve order of parametric tags
+ (Wojciech Meyer, report by Dario Texeira)
+- PR#5551: Avoid repeated lookups for missing cmi files
+ (Alain Frisch)
+- PR#5552: unrecognized gcc option -no-cpp-precomp
+ (Damien Doligez, report by Markus Mottl)
+* PR#5580: missed opportunities for constant propagation
+ (Xavier Leroy and John Carr)
+- PR#5611: avoid clashes betwen .cmo files and output files during linking
+ (Wojciech Meyer)
+- PR#5662: typo in md5.c
+ (Olivier Andrieu)
+- PR#5673: type equality in a polymorphic field
+ (Jacques Garrigue, report by Jean-Louis Giavitto)
+- PR#5674: Methods call are 2 times slower with 4.00 than with 3.12
+ (Jacques Garrigue, Gabriel Scherer, report by Jean-Louis Giavitto)
+- PR#5694: Exception raised by type checker
+ (Jacques Garrigue, report by Markus Mottl)
+- PR#5695: remove warnings on sparc code emitter
+ (Fabrice Le Fessant)
+- PR#5697: better location for warnings on statement expressions
+ (Dan Bensen)
+- PR#5698: remove harcoded limit of 200000 labels in emitaux.ml
+ (Fabrice Le Fessant, report by Marcin Sawicki)
+- PR#5702: bytecomp/bytelibrarian lib_sharedobjs was defined but never used
+ (Hongbo Zhang, Fabrice Le Fessant)
+- PR#5708: catch Failure"int_of_string" in ocamldebug
+ (Fabrice Le Fessant, report by user 'schommer')
+- PR#5712: (9) new option -bin-annot is not documented
+ (Damien Doligez, report by Hendrik Tews)
+- PR#5731: instruction scheduling forgot to account for destroyed registers
+ (Xavier Leroy, Benedikt Meurer, reported by Jeffrey Scofield)
+- PR#5734: improved Win32 implementation of Unix.gettimeofday
+ (David Allsopp)
+- PR#5735: %apply and %revapply not first class citizens
+ (Fabrice Le Fessant, reported by Jun Furuse)
+- PR#5738: first class module patterns not handled by ocamldep
+ (Fabrice Le Fessant, Jacques Garrigue, reported by Hongbo Zhang)
+- PR#5739: Printf.printf "%F" (-.nan) returns -nan
+ (Xavier Leroy, David Allsopp, reported by Samuel Mimram)
+- PR#5741: make pprintast.ml in compiler_libs
+ (Alain Frisch, Hongbo Zhang)
+- PR#5747: 'unused open' warning not given when compiling with -annot
+ (Alain Frisch, reported by Valentin Gatien-Baron)
+- PR#5752: missing dependencies at byte-code link with mlpack
+ (Wojciech Meyer, Nicholas Lucaroni)
+- PR#5763: ocamlbuild does not give correct flags when running menhir
+ (Gabriel Scherer, reported by Philippe Veber)
+- PR#5765: ocamllex doesn't preserve line directives
+ (Damien Doligez, reported by Martin Jambon)
+- PR#5770: Syntax error messages involving unclosed parens are sometimes
+ incorrect
+ (Michel Mauny)
+- PR#5772: problem with marshaling of mutually-recursive functions
+ (Jacques-Henri Jourdan, reported by Cédric Pasteur)
+- PR#5775: several bug fixes for tools/pprintast.ml
+ (Hongbo Zhang)
+- PR#5784: -dclambda option is ignored
+ (Pierre Chambart)
+- PR#5785: misbehaviour with abstracted structural type used as GADT index
+ (Jacques Garrigue, report by Jeremy Yallop)
+- PR#5787: Bad behavior of 'Unused ...' warnings in the toplevel
+ (Alain Frisch)
+- PR#5793: integer marshalling is inconsistent between architectures
+ (Xavier Clerc, report by Pierre-Marie Pédrot)
+- PR#5798: add ARM VFPv2 support for Raspbian (ocamlopt)
+ (Jeffrey Scofield and Anil Madhavapeddy, patch review by Benedikt Meurer)
+- PR#5802: Avoiding "let" as a value name
+ (Jacques Garrigue, report by Tiphaine Turpin)
+- PR#5805: Assert failure with warning 34 on pre-processed file
+ (Alain Frisch, report by Tiphaine Turpin)
+- PR#5806: ensure that backtrace tests are always run (testsuite)
+ (Xavier Clerc, report by user 'michi')
+- PR#5809: Generating .cmt files takes a long time, in case of type error
+ (Alain Frisch)
+- PR#5810: error in switch printing when using -dclambda
+ (Pierre Chambart)
+- PR#5811: Untypeast produces singleton tuples for constructor patterns
+ with only one argument
+ (Tiphaine Turpin)
+- PR#5813: GC not called when unmarshaling repeatedly in a tight loop (ocamlopt)
+ (Xavier Leroy, report by David Waern)
+- PR#5814: read_cmt -annot does not report internal references
+ (Alain Frisch)
+- PR#5815: Multiple exceptions in signatures gives an error
+ (Leo P. White)
+- PR#5816: read_cmt -annot does not work for partial .cmt files
+ (Alain Frisch)
+- PR#5819: segfault when using [with] on large recursive record (ocamlopt)
+ (Xavier Leroy, Damien Doligez)
+- PR#5821: Wrong record field is reported as duplicate
+ (Alain Frisch, report by Martin Jambon)
+- PR#5824: Generate more efficient code for immediate right shifts.
+ (Pierre Chambart, review by Xavier Leroy)
+- PR#5825: Add a toplevel primitive to use source file wrapped with the
+ coresponding module
+ (Grégoire Henry, Wojciech Meyer, caml-list discussion)
+- PR#5833: README.win32 can leave the wrong flexlink in the path
+ (Damien Doligez, report by William Smith)
+- PR#5835: nonoptional labeled arguments can be passed with '?'
+ (Jacques Garrigue, report by Elnatan Reisner)
+- PR#5840: improved documentation for 'Unix.lseek'
+ (Xavier Clerc, report by Matej Košík)
+- PR#5848: Assertion failure in type checker
+ (Jacques Garrigue, Alain Frisch, report by David Waern)
+- PR#5858: Assert failure during typing of class
+ (Jacques Garrigue, report by Julien Signoles)
+- PR#5865: assert failure when reporting undefined field label
+ (Jacques Garrigue, report by Anil Madhavapeddy)
+- PR#5872: Performance: Buffer.add_char is not inlined
+ (Gerd Stolpmann, Damien Doligez)
+- PR#5876: Uncaught exception with a typing error
+ (Alain Frisch, Gabriel Scherer, report by Julien Moutinho)
+- PR#5877: multiple "open" can become expensive in memory
+ (Fabrice Le Fessant and Alain Frisch)
+- PR#5880: 'Genlex.make_lexer' documention mentions the wrong exception
+ (Xavier Clerc, report by Virgile Prevosto)
+- PR#5885: Incorrect rule for compiling C stubs when shared libraries are not
+ supported.
+ (Jérôme Vouillon)
+- PR#5891: ocamlbuild: support rectypes tag for mlpack
+ (Khoo Yit Phang)
+- PR#5892: GADT exhaustiveness check is broken
+ (Jacques Garrigue and Leo P. White)
+- PR#5906: GADT exhaustiveness check is still broken
+ (Jacques Garrigue, report by Sébastien Briais)
+- PR#5907: Undetected cycle during typecheck causes exceptions
+ (Jacques Garrigue, report by Pascal Zimmer)
+- PR#5910: Fix code generation bug for "mod 1" on ARM.
+ (Benedikt Meurer, report by user 'jteg68')
+- PR#5911: Signature substitutions fail in submodules
+ (Jacques Garrigue, report by Markus Mottl)
+- PR#5912: add configure option -no-cfi (for OSX 10.6.x with XCode 4.0.2)
+ (Damien Doligez against XCode versions, report by Thomas Gazagnaire)
+- PR#5914: Functor breaks with an equivalent argument signature
+ (Jacques Garrigue, report by Markus Mottl and Grégoire Henry)
+- PR#5920, PR#5957: linking failure for big bytecodes on 32bit architectures
+ (Benoît Vaugon and Chet Murthy, report by Jun Furuse and Sebastien Mondet)
+- PR#5928: Missing space between words in manual page for ocamlmktop
+ (Damien Doligez, report by Matej Košík)
+- PR#5930: ocamldep leaks temporary preprocessing files
+ (Gabriel Scherer, report by Valentin Gatien-Baron)
+- PR#5933: Linking is slow when there are functions with large arities
+ (Valentin Gatien-Baron, review by Gabriel Scherer)
+- PR#5934: integer shift by negative amount (in otherlibs/num)
+ (Xavier Leroy, report by John Regehr)
+- PR#5944: Bad typing performances of big variant type declaration
+ (Benoît Vaugon)
+- PR#5945: Mix-up of Minor_heap_min and Minor_heap_max units
+ (Benoît Vaugon)
+- PR#5948: GADT with polymorphic variants bug
+ (Jacques Garrigue, report by Leo P. White)
+- PR#5953: Unix.system does not handle EINTR
+ (Jérémie Dimino)
+- PR#5965: disallow auto-reference to a recursive module in its definition
+ (Alain Frisch, report by Arthur Windler via Gabriel Scherer)
+- PR#5973: Format module incorrectly parses format string
+ (Pierre Weis, report by Frédéric Bour)
+- PR#5974: better documentation for Str.regexp
+ (Damien Doligez, report by william)
+- PR#5976: crash after recovering from two stack overflows (ocamlopt on MacOS X)
+ (Xavier Leroy, report by Pierre Boutillier)
+- PR#5977: Build failure on raspberry pi: "input_value: integer too large"
+ (Alain Frisch, report by Sylvain Le Gall)
+- PR#5981: Incompatibility check assumes abstracted types are injective
+ (Jacques Garrigue, report by Jeremy Yallop)
+- PR#5982: caml_leave_blocking section and errno corruption
+ (Jérémie Dimino)
+- PR#5985: Unexpected interaction between variance and GADTs
+ (Jacques Garrigue, Jeremy Yallop and Leo P. White and Gabriel Scherer)
+- PR#5988: missing from the documentation: -impl is a valid flag for ocamlopt
+ (Damien Doligez, report by Vincent Bernardoff)
+- PR#5989: Assumed inequalities involving private rows
+ (Jacques Garrigue, report by Jeremy Yallop)
+- PR#5992: Crash when pattern-matching lazy values modifies the scrutinee
+ (Luc Maranget, Leo P. White)
+- PR#5993: Variance of private type abbreviations not checked for modules
+ (Jacques Garrigue)
+- PR#5997: Non-compatibility assumed for concrete types with same constructor
+ (Jacques Garrigue, report by Gabriel Scherer)
+- PR#6004: Type information does not flow to "inherit" parameters
+ (Jacques Garrigue, report by Alain Frisch)
+- PR#6005: Type unsoundness with recursive modules
+ (Jacques Garrigue, report by Jérémie Dimino and Josh Berdine)
+- PR#6010: Big_int.extract_big_int gives wrong results on negative arguments
+ (Xavier Leroy, report by Drake Wilson via Stéphane Glondu)
+- PR#6024: Format syntax for printing @ is incompatible with 3.12.1
+ (Damien Doligez, report by Boris Yakobowski)
+- PR#6001: Reduce the memory used by compiling Camlp4
+ (Hongbo Zhang and Gabriel Scherer, report by Henri Gouraud)
+- PR#6031: Camomile problem with -with-frame-pointers
+ (Fabrice Le Fessant, report by Anil Madhavapeddy)
+- PR#6032: better Random.self_init under Windows
+ (Alain Frisch, Xavier Leroy)
+- PR#6033: Matching.inline_lazy_force needs eta-expansion (command-line flags)
+ (Pierre Chambart, Xavier Leroy and Luc Maranget,
+ regression report by Gabriel Scherer)
+- PR#6046: testsuite picks up the wrong ocamlrun dlls
+ (Anil Madhavapeddy)
+- PR#6056: Using 'match' prevents generalization of values
+ (Jacques Garrigue, report by Elnatan Reisner)
+- PR#6058: 'ocamlbuild -use-ocamlfind -tag thread -package threads t.cma' fails
+ (Gabriel Scherer, report by Hezekiah M. Carty)
+- PR#6069: ocamldoc: lexing: empty token
+ (Maxence Guesdon, Grégoire Henry, report by ygrek)
+- PR#6072: configure does not handle FreeBSD current (i.e. 10) correctly
+ (Damien Doligez, report by Prashanth Mundkur)
+- PR#6074: Wrong error message for failing Condition.broadcast
+ (Markus Mottl)
+- PR#6084: Define caml_modify and caml_initialize as weak symbols to help
+ with Netmulticore
+ (Xavier Leroy, Gerd Stolpmann)
+- PR#6090: Module constraint + private type seems broken in ocaml 4.01.0
+ (Jacques Garrigue, report by Jacques-Pascal Deplaix)
+- PR#6109: Typos in ocamlbuild error messages
+ (Gabriel Kerneis)
+- PR#6123: Assert failure when self escapes its class
+ (Jacques Garrigue, report by whitequark)
+- PR#6158: Fatal error using GADTs
+ (Jacques Garrigue, report by Jeremy Yallop)
+- PR#6163: Assert_failure using polymorphic variants in GADTs
+ (Jacques Garrigue, report by Leo P. White)
+- PR#6164: segmentation fault on Num.power_num of 0/1
+ (Fabrice Le Fessant, report by Johannes Kanig)
+- PR#6210: Camlp4 location error
+ (Hongbo Zhang, report by Jun Furuse)
+
+Feature wishes:
+- PR#5181: Merge common floating point constants in ocamlopt
+ (Benedikt Meurer)
+- PR#5243: improve the ocamlbuild API documentation in signatures.mli
+ (Christophe Troestler)
+- PR#5546: moving a function into an internal module slows down its use
+ (Alain Frisch, report by Fabrice Le Fessant)
+- PR#5597: add instruction trace option 't' to OCAMLRUNPARAM
+ (Anil Madhavapeddy, Wojciech Meyer)
+- PR#5676: IPv6 support under Windows
+ (Jérôme Vouillon, review by Jonathan Protzenko)
+- PR#5721: configure -with-frame-pointers for Linux perf profiling
+ (Fabrice Le Fessant, test by Jérémie Dimino)
+- PR#5722: toplevel: print full module path only for first record field
+ (Jacques Garrigue, report by ygrek)
+- PR#5762: Add primitives for fast access to bigarray dimensions
+ (Pierre Chambart)
+- PR#5769: Allow propagation of Sys.big_endian in native code
+ (Pierre Chambart, stealth commit by Fabrice Le Fessant)
+- PR#5771: Add primitives for reading 2, 4, 8 bytes in strings and bigarrays
+ (Pierre Chambart)
+- PR#5774: Add bswap primitives for amd64 and arm
+ (Pierre Chambart, test by Alain Frisch)
+- PR#5795: Generate sqrtsd opcode instead of external call to sqrt on amd64
+ (Pierre Chambart)
+- PR#5827: provide a dynamic command line parsing mechanism
+ (Hongbo Zhang)
+- PR#5832: patch to improve "wrong file naming" error messages
+ (William Smith)
+- PR#5864: Add a find operation to Set
+ (François Berenger)
+- PR#5886: Small changes to compile for Android
+ (Jérôme Vouillon, review by Benedikt Meurer)
+- PR#5902: -ppx based pre-processor executables accept arguments
+ (Alain Frisch, report by Wojciech Meyer)
+- PR#5986: Protect against marshaling 64-bit integers in bytecode
+ (Xavier Leroy, report by Alain Frisch)
+- PR#6049: support for OpenBSD/macppc platform
+ (Anil Madhavapeddy, review by Benedikt Meurer)
+- PR#6059: add -output-obj rules for ocamlbuild
+ (Anil Madhavapeddy)
+- PR#6060: ocamlbuild tags 'principal', 'strict_sequence' and 'short_paths'
+ (Anil Madhavapeddy)
+- ocamlbuild tag 'no_alias_deps'
+ (Daniel Bünzli)
+
+Tools:
+- OCamlbuild now features a bin_annot tag to generate .cmt files.
+ (Jonathan Protzenko)
+- OCamlbuild now features a strict_sequence tag to trigger the
+ strict-sequence option.
+ (Jonathan Protzenko)
+- OCamlbuild now picks the non-core tools like ocamlfind and menhir from PATH
+ (Wojciech Meyer)
+- PR#5884: Misc minor fixes and cleanup for emacs mode
+ (Stefan Monnier)
+- PR#6030: Improve performance of -annot
+ (Guillaume Melquiond, Alain Frisch)
+
+
+OCaml 4.00.1 (5 Oct 2012):
+--------------------------
+
+Bug fixes:
+- PR#4019: better documentation of Str.matched_string
+- PR#5111: ocamldoc, heading tags inside spans tags is illegal in html
+- PR#5278: better error message when typing "make"
+- PR#5468: ocamlbuild should preserve order of parametric tags
+- PR#5563: harden Unix.select against file descriptors above FD_SETSIZE
+- PR#5690: "ocamldoc ... -text README" raises exception
+- PR#5700: crash with native-code stack backtraces under MacOS 10.8 x86-64
+- PR#5707: AMD64 code generator: do not use r10 and r11 for parameter passing,
+ as these registers can be destroyed by the dynamic loader
+- PR#5712: some documentation problems
+- PR#5715: configuring with -no-shared-libs breaks under cygwin
+- PR#5718: false positive on 'unused constructor' warning
+- PR#5719: ocamlyacc generates code that is not warning 33-compliant
+- PR#5725: ocamldoc output of preformatted code
+- PR#5727: emacs caml-mode indents shebang line in toplevel scripts
+- PR#5729: tools/untypeast.ml creates unary Pexp_tuple
+- PR#5731: instruction scheduling forgot to account for destroyed registers
+- PR#5735: %apply and %revapply not first class citizens
+- PR#5738: first class module patterns not handled by ocamldep
+- PR#5742: missing bound checks in Array.sub
+- PR#5744: ocamldoc error on "val virtual"
+- PR#5757: GC compaction bug (crash)
+- PR#5758: Compiler bug when matching on floats
+- PR#5761: Incorrect bigarray custom block size
+
+
+OCaml 4.00.0 (26 Jul 2012):
+---------------------------
+
+(Changes that can break existing programs are marked with a "*")
+
+- The official name of the language is now OCaml.
+
+Language features:
+- Added Generalized Algebraic Data Types (GADTs) to the language.
+ See chapter "Language extensions" of the reference manual for documentation.
+- It is now possible to omit type annotations when packing and unpacking
+ first-class modules. The type-checker attempts to infer it from the context.
+ Using the -principal option guarantees forward compatibility.
+- New (module M) and (module M : S) syntax in patterns, for immediate
+ unpacking of a first-class module.
+
+Compilers:
+- Revised simplification of let-alias (PR#5205, PR#5288)
+- Better reporting of compiler version mismatch in .cmi files
+* Warning 28 is now enabled by default.
+- New option -absname to use absolute paths in error messages
+- Optimize away compile-time beta-redexes, e.g. (fun x y -> e) a b.
+- Added option -bin-annot to dump the AST with type annotations.
+- Added lots of new warnings about unused variables, opens, fields,
+ constructors, etc.
+* New meaning for warning 7: it is now triggered when a method is overridden
+ with the "method" keyword. Use "method!" to avoid the warning.
+
+Native-code compiler:
+- Optimized handling of partially-applied functions (PR#5287)
+- Small improvements in code generated for array bounds checks (PR#5345,
+ PR#5360).
+* New ARM backend (PR#5433):
+ . Supports both Linux/EABI (armel) and Linux/EABI+VFPv3 (armhf).
+ . Added support for the Thumb-2 instruction set with average code size
+ savings of 28%.
+ . Added support for position-independent code, natdynlink, profiling and
+ exception backtraces.
+- Generation of CFI information, and filename/line number debugging (with -g)
+ annotations, enabling in particular precise stack backtraces with
+ the gdb debugger. Currently supported for x86 32-bits and 64-bits only.
+ (PR#5487)
+- New tool: ocamloptp, the equivalent of ocamlcp for the native-code compiler.
+
+OCamldoc:
+- PR#5645: ocamldoc doesn't handle module/type substitution in signatures
+- PR#5544: improve HTML output (less formatting in html code)
+- PR#5522: allow refering to record fields and variant constructors
+- fix PR#5419 (error message in french)
+- fix PR#5535 (no cross ref to class after dump+load)
+* Use first class modules for custom generators, to be able to
+ load various plugins incrementally adding features to the current
+ generator
+* PR#5507: Use Location.t structures for locations.
+- fix: do not keep code when not told to keep code.
+
+Standard library:
+- Added float functions "hypot" and "copysign" (PR#3806, PR#4752, PR#5246)
+* Arg: options with empty doc strings are no longer included in the usage string
+ (PR#5437)
+- Array: faster implementations of "blit", "copy", "sub", "append" and "concat"
+ (PR#2395, PR#2787, PR#4591)
+* Hashtbl:
+ . Statistically-better generic hash function based on Murmur 3 (PR#5225)
+ . Fixed behavior of generic hash function w.r.t. -0.0 and NaN (PR#5222)
+ . Added optional "random" parameter to Hashtbl.create to randomize
+ collision patterns and improve security (PR#5572, CVE-2012-0839)
+ . Added "randomize" function and "R" parameter to OCAMLRUNPARAM
+ to turn randomization on by default (PR#5572, CVE-2012-0839)
+ . Added new functorial interface "MakeSeeded" to support randomization
+ with user-provided seeded hash functions.
+ . Install new header <caml/hash.h> for C code.
+- Filename: on-demand (lazy) initialization of the PRNG used by "temp_file".
+- Marshal: marshalling of function values (flag Marshal.Closures) now
+ also works for functions that come from dynamically-loaded modules (PR#5215)
+- Random:
+ . More random initialization (Random.self_init()), using /dev/urandom
+ when available (e.g. Linux, FreeBSD, MacOS X, Solaris)
+ * Faster implementation of Random.float (changes the generated sequences)
+- Format strings for formatted input/output revised to correct PR#5380
+ . Consistently treat %@ as a plain @ character
+ . Consistently treat %% as a plain % character
+- Scanf: width and precision for floating point numbers are now handled
+- Scanf: new function "unescaped" (PR#3888)
+- Set and Map: more efficient implementation of "filter" and "partition"
+- String: new function "map" (PR#3888)
+
+Installation procedure:
+- Compiler internals are now installed in `ocamlc -where`/compiler-libs.
+ The files available there include the .cmi interfaces for all compiler
+ modules, plus the following libraries:
+ ocamlcommon.cma/.cmxa modules common to ocamlc, ocamlopt, ocaml
+ ocamlbytecomp.cma/.cmxa modules for ocamlc and ocaml
+ ocamloptcomp.cma/.cmxa modules specific to ocamlopt
+ ocamltoplevel.cma modules specific to ocaml
+ (PR#1804, PR#4653, frequently-asked feature).
+* Some .cmi for toplevel internals that used to be installed in
+ `ocamlc -where` are now to be found in `ocamlc -where`/compiler-libs.
+ Add "-I +compiler-libs" where needed.
+* toplevellib.cma is no longer installed because subsumed by
+ ocamlcommon.cma ocamlbytecomp.cma ocamltoplevel.cma
+- Added a configuration option (-with-debug-runtime) to compile and install
+ a debug version of the runtime system, and a compiler option
+ (-runtime-variant) to select the debug runtime.
+
+Bug Fixes:
+
+- PR#1643: functions of the Lazy module whose named started with 'lazy_' have
+ been deprecated, and new ones without the prefix added
+- PR#3571: in Bigarrays, call msync() before unmapping to commit changes
+- PR#4292: various documentation problems
+- PR#4511, PR#4838: local modules remove polymorphism
+* PR#4549: Filename.dirname is not handling multiple / on Unix
+- PR#4688: (Windows) special floating-point values aren't converted to strings
+ correctly
+- PR#4697: Unix.putenv leaks memory on failure
+- PR#4705: camlp4 does not allow to define types with `True or `False
+- PR#4746: wrong detection of stack overflows in native code under Linux
+- PR#4869: rare collisions between assembly labels for code and data
+- PR#4880: "assert" constructs now show up in the exception stack backtrace
+- PR#4892: Array.set could raise "out of bounds" before evaluating 3rd arg
+- PR#4937: camlp4 incorrectly handles optional arguments if 'option' is
+ redefined
+- PR#5024: camlp4r now handles underscores in irrefutable pattern matching of
+ records
+- PR#5064, PR#5485: try to ensure that 4K words of stack are available
+ before calling into C functions, raising a Stack_overflow exception
+ otherwise. This reduces (but does not eliminate) the risk of
+ segmentation faults due to stack overflow in C code
+- PR#5073: wrong location for 'Unbound record field label' error
+- PR#5084: sub-sub-module building fails for native code compilation
+- PR#5120: fix the output function of Camlp4.Debug.formatter
+- PR#5131: compilation of custom runtime with g++ generates lots of warnings
+- PR#5137: caml-types-explore does not work
+- PR#5159: better documentation of type Lexing.position
+- PR#5171: Map.join does more comparisons than needed
+- PR#5176: emacs mode: stack overflow in regexp matcher
+- PR#5179: port OCaml to mingw-w64
+- PR#5211: updated Genlex documentation to state that camlp4 is mandatory for
+ 'parser' keyword and associated notation
+- PR#5214: ocamlfind plugin invokes 'cut' utility
+- PR#5218: use $(MAKE) instead of "make" in Makefiles
+- PR#5224: confusing error message in non-regular type definition
+- PR#5231: camlp4: fix parsing of <:str_item< type t = $x$ >>
+- PR#5233: finaliser on weak array gives dangling pointers (crash)
+- PR#5238, PR#5277: Sys_error when getting error location
+- PR#5261, PR#5497: Ocaml source-code examples are not "copy-paste-able"
+* PR#5279: executable name is not initialized properly in caml_startup_code
+- PR#5290: added hash functions for channels, nats, mutexes, conditions
+- PR#5291: undetected loop in class initialization
+- PR#5295: OS threads: problem with caml_c_thread_unregister()
+- PR#5301: camlp4r and exception equal to another one with parameters
+- PR#5305: prevent ocamlbuild from complaining about links to _build/
+- PR#5306: comparing to Thread.self() raises exception at runtime
+- PR#5309: Queue.add is not thread/signal safe
+- PR#5310: Ratio.create_ratio/create_normalized_ratio have misleading names
+- PR#5311: better message for warning 23
+* PR#5312: command-line arguments @reponsefile auto-expansion feature
+ removed from the Windows OCaml runtime, to avoid conflicts with "-w @..."
+- PR#5313: ocamlopt -g misses optimizations
+- PR#5214: ocamlfind plugin invokes 'cut' utility
+- PR#5316: objinfo now shows ccopts/ccobjs/force_link when applicable
+- PR#5318: segfault on stack overflow when reading marshaled data
+- PR#5319: %r11 clobbered by Lswitch in Windows AMD64 native-code compilation
+- PR#5322: type abbreviations expanding to a universal type variable
+- PR#5328: under Windows, Unix.select leaves sockets in non-blocking mode
+- PR#5330: thread tag with '.top' and '.inferred.mli' targets
+- PR#5331: ocamlmktop is not always a shell script
+- PR#5335: Unix.environment segfaults after a call to clearenv
+- PR#5338: sanitize.sh has windows style end-of-lines (mingw)
+- PR#5344: some predefined exceptions need special printing
+- PR#5349: Hashtbl.replace uses new key instead of reusing old key
+- PR#5356: ocamlbuild handling of 'predicates' for ocamlfind
+- PR#5364: wrong compilation of "((val m : SIG1) : SIG2)"
+- PR#5370: ocamldep omits filename in syntax error message
+- PR#5374: camlp4 creates wrong location for type definitions
+- PR#5380: strange sscanf input segfault
+- PR#5382: EOPNOTSUPP and ENOTSUPP different on exotic platforms
+- PR#5383: build failure in Win32/MSVC
+- PR#5387: camlp4: str_item and other syntactic elements with Nils are
+ not very usable
+- PR#5389: compaction sometimes leaves a very large heap
+- PR#5393: fails to build from source on GNU/kFreeBSD because of -R link option
+- PR#5394: documentation for -dtypes is missing in manpage
+- PR#5397: Filename.temp_dir_name should be mutable
+- PR#5410: fix printing of class application with Camlp4
+- PR#5416: (Windows) Unix.(set|clear)_close_on_exec now preserves blocking mode
+- PR#5435: ocamlbuild does not find .opt executables on Windows
+- PR#5436: update object ids on unmarshaling
+- PR#5442: camlp4: quotation issue with strings
+- PR#5453: configure doesn't find X11 under Ubuntu/MultiarchSpec
+- PR#5461: Double linking of bytecode modules
+- PR#5463: Bigarray.*.map_file fail if empty array is requested
+- PR#5465: increase stack size of ocamlopt.opt for windows
+- PR#5469: private record type generated by functor loses abbreviation
+- PR#5475: Wrapper script for interpreted LablTk wrongly handles command line
+ parameters
+- PR#5476: bug in native code compilation of let rec on float arrays
+- PR#5477: use pkg-config to configure graphics on linux
+- PR#5481: update camlp4 magic numbers
+- PR#5482: remove bashism in test suite scripts
+- PR#5495: camlp4o dies on infix definition (or)
+- PR#5498: Unification with an empty object only checks the absence of
+ the first method
+- PR#5503: error when ocamlbuild is passed an absolute path as build directory
+- PR#5509: misclassification of statically-allocated empty array that
+ falls exactly at beginning of an otherwise unused data page.
+- PR#5510: ocamldep has duplicate -ml{,i}-synonym options
+- PR#5511: in Bigarray.reshape, unwarranted limitation on new array dimensions.
+- PR#5513: Int64.div causes floating point exception (ocamlopt, x86)
+- PR#5516: in Bigarray C stubs, use C99 flexible array types if possible
+- PR#5518: segfault with lazy empty array
+- PR#5531: Allow ocamlbuild to add ocamldoc flags through -docflag
+ and -docflags switches
+- PR#5538: combining -i and -annot in ocamlc
+- PR#5543: in Bigarray.map_file, try to avoid using lseek() when growing file
+- PR#5648: (probably fixed) test failures in tests/lib-threads
+- PR#5551: repeated calls to find_in_path degrade performance
+- PR#5552: Mac OS X: unrecognized gcc option "-no-cpp-precomp"
+- PR#5555: add Hashtbl.reset to resize the bucket table to its initial size
+- PR#5560: incompatible type for tuple pattern with -principal
+- PR#5575: Random states are not marshallable across architectures
+- PR#5579: camlp4: when a plugin is loaded in the toplevel,
+ Token.Filter.define_filter has no effect before the first syntax error
+- PR#5585: typo: "explicitely"
+- PR#5587: documentation: "allows to" is not correct English
+- PR#5593: remove C file when -output-obj fails
+- PR#5597: register names for instrtrace primitives in embedded bytecode
+- PR#5598: add backslash-space support in strings in ocamllex
+- PR#5603: wrong .file debug info generated by ocamlopt -g
+- PR#5604: fix permissions of files created by ocamlbuild itself
+- PR#5610: new unmarshaler (from PR#5318) fails to freshen object identifiers
+- PR#5614: add missing -linkall flag when compiling ocamldoc.opt
+- PR#5616: move ocamlbuild documentation to the reference manual
+- PR#5619: Uncaught CType.Unify exception in the compiler
+- PR#5620: invalid printing of type manifest (camlp4 revised syntax)
+- PR#5637: invalid printing of anonymous type parameters (camlp4 revised syntax)
+- PR#5643: issues with .cfi and .loc directives generated by ocamlopt -g
+- PR#5644: Stream.count broken when used with Sapp or Slazy nodes
+- PR#5647: Cannot use install_printer in debugger
+- PR#5651: printer for abstract data type (camlp4 revised syntax)
+- PR#5654: self pattern variable location tweak
+- PR#5655: ocamlbuild doesn't pass cflags when building C stubs
+- PR#5657: wrong error location for abbreviated record fields
+- PR#5659: ocamlmklib -L option breaks with MSVC
+- PR#5661: fixes for the test suite
+- PR#5668: Camlp4 produces invalid syntax for "let _ = ..."
+- PR#5671: initialization of compare_ext field in caml_final_custom_operations()
+- PR#5677: do not use "value" as identifier (genprintval.ml)
+- PR#5687: dynlink broken when used from "output-obj" main program (bytecode)
+- problem with printing of string literals in camlp4 (reported on caml-list)
+- emacs mode: colorization of comments and strings now works correctly
+- problem with forall and method (reported on caml-list on 2011-07-26)
+- crash when using OCAMLRUNPARAM=a=X with invalid X (reported in private)
+
+Feature wishes:
+- PR#352: new option "-stdin" to make ocaml read stdin as a script
+- PR#1164: better error message when mixing -a and .cmxa
+- PR#1284: documentation: remove restriction on mixed streams
+- PR#1496: allow configuring LIBDIR, BINDIR, and MANDIR relative to $(PREFIX)
+- PR#1835: add Digest.from_hex
+- PR#1898: toplevel: add option to suppress continuation prompts
+- PR#4278: configure: option to disable "graph" library
+- PR#4444: new String.trim function, removing leading and trailing whistespace
+- PR#4549: make Filename.dirname/basename POSIX compliant
+- PR#4830: add option -v to expunge.ml
+- PR#4898: new Sys.big_endian boolean for machine endianness
+- PR#4963, PR#5467: no extern "C" into ocaml C-stub headers
+- PR#5199: tests are run only for bytecode if either native support is missing,
+ or a non-empty value is set to "BYTECODE_ONLY" Makefile variable
+- PR#5215: marshalling of dynlinked closure
+- PR#5236: new '%revapply' primitive with the semantics 'revapply x f = f x',
+ and '%apply' with semantics 'apply f x = f x'.
+- PR#5255: natdynlink detection on powerpc, hurd, sparc
+- PR#5295: OS threads: problem with caml_c_thread_unregister()
+- PR#5297: compiler now checks existence of builtin primitives
+- PR#5329: (Windows) more efficient Unix.select if all fd's are sockets
+- PR#5357: warning for useless open statements
+- PR#5358: first class modules don't allow "with type" declarations for types
+ in sub-modules
+- PR#5385: configure: emit a warning when MACOSX_DEPLOYMENT_TARGET is set
+- PR#5396: ocamldep: add options -sort, -all, and -one-line
+- PR#5397: Filename.temp_dir_name should be mutable
+- PR#5403: give better error message when emacs is not found in PATH
+- PR#5411: new directive for the toplevel: #load_rec
+- PR#5420: Unix.openfile share mode (Windows)
+- PR#5421: Unix: do not leak fds in various open_proc* functions
+- PR#5434: implement Unix.times in win32unix (partially)
+- PR#5438: new warnings for unused declarations
+- PR#5439: upgrade config.guess and config.sub
+- PR#5445 and others: better printing of types with user-provided names
+- PR#5454: Digest.compare is missing and md5 doc update
+- PR#5455: .emacs instructions, add lines to recognize ocaml scripts
+- PR#5456: pa_macro: replace __LOCATION__ after macro expansion; add LOCATION_OF
+- PR#5461: bytecode: emit warning when linking two modules with the same name
+- PR#5478: ocamlopt assumes ar command exists
+- PR#5479: Num.num_of_string may raise an exception, not reflected in the
+ documentation.
+- PR#5501: increase IO_BUFFER_SIZE to 64KiB
+- PR#5532: improve error message when bytecode file is wrong
+- PR#5555: add function Hashtbl.reset to resize the bucket table to
+ its initial size.
+- PR#5586: increase UNIX_BUFFER_SIZE to 64KiB
+- PR#5597: register names for instrtrace primitives in embedded bytecode
+- PR#5599: Add warn() tag in ocamlbuild to control -w compiler switch
+- PR#5628: add #remove_directory and Topdirs.remove_directory to remove
+ a directory from the load path
+- PR#5636: in system threads library, issue with linking of pthread_atfork
+- PR#5666: C includes don't provide a revision number
+- ocamldebug: ability to inspect values that contain code pointers
+- ocamldebug: new 'environment' directive to set environment variables
+ for debuggee
+- configure: add -no-camlp4 option
+
+Shedding weight:
+* Removed the obsolete native-code generators for Alpha, HPPA, IA64 and MIPS.
+* The "DBM" library (interface with Unix DBM key-value stores) is no
+ longer part of this distribution. It now lives its own life at
+ https://forge.ocamlcore.org/projects/camldbm/
+* The "OCamlWin" toplevel user interface for MS Windows is no longer
+ part of this distribution. It now lives its own life at
+ https://forge.ocamlcore.org/projects/ocamltopwin/
+
+Other changes:
+- Copy VERSION file to library directory when installing.
+
+
+OCaml 3.12.1 (4 Jul 2011):
+--------------------------
+
+Bug fixes:
+- PR#4345, PR#4767: problems with camlp4 printing of float values
+- PR#4380: ocamlbuild should not use tput on windows
+- PR#4487, PR#5164: multiple 'module type of' are incompatible
+- PR#4552: ocamlbuild does not create symlinks when using '.itarget' file
+- PR#4673, PR#5144: camlp4 fails on object copy syntax
+- PR#4702: system threads: cleanup tick thread at exit
+- PR#4732: camlp4 rejects polymorphic variants using keywords from macros
+- PR#4778: Win32/MSVC port: rare syntax error in generated MASM assembly file
+- PR#4794, PR#4959: call annotations not generated by ocamlopt
+- PR#4820: revised syntax pretty printer crashes with 'Stack_overflow'
+- PR#4928: wrong printing of classes and class types by camlp4
+- PR#4939: camlp4 rejects patterns of the '?x:_' form
+- PR#4967: ocamlbuild passes wrong switches to ocamldep through menhir
+- PR#4972: mkcamlp4 does not include 'dynlink.cma'
+- PR#5039: ocamlbuild should use '-linkpkg' only when linking programs
+- PR#5066: ocamldoc: add -charset option used in html generator
+- PR#5069: fcntl() in caml_sys_open may block, do it within blocking section
+- PR#5071, PR#5129, PR#5134: inconsistencies between camlp4 and camlp4* binaries
+- PR#5080, PR#5104: regression in type constructor handling by camlp4
+- PR#5090: bad interaction between toplevel and camlp4
+- PR#5095: ocamlbuild ignores some tags when building bytecode objects
+- PR#5100: ocamlbuild always rebuilds a 'cmxs' file
+- PR#5103: build and install objinfo when building with ocamlbuild
+- PR#5109: crash when a parser calls a lexer that calls another parser
+- PR#5110: invalid module name when using optional argument
+- PR#5115: bytecode executables produced by msvc64 port crash on 32-bit versions
+- PR#5117: bigarray: wrong function name without HAS_MMAP; missing include
+- PR#5118: Camlp4o and integer literals
+- PR#5122: camlp4 rejects lowercase identifiers for module types
+- PR#5123: shift_right_big_int returns a wrong zero
+- PR#5124: substitution inside a signature leads to odd printing
+- PR#5128: typo in 'Camlp4ListComprehension' syntax extension
+- PR#5136: obsolete function used in emacs mode
+- PR#5145: ocamldoc: missing html escapes
+- PR#5146: problem with spaces in multi-line string constants
+- PR#5149: (partial) various documentation problems
+- PR#5156: rare compiler crash with objects
+- PR#5165: ocamlbuild does not pass '-thread' option to ocamlfind
+- PR#5167: camlp4r loops when printing package type
+- PR#5172: camlp4 support for 'module type of' construct
+- PR#5175: in bigarray accesses, make sure bigarray expr is evaluated only once
+- PR#5177: Gc.compact implies Gc.full_major
+- PR#5182: use bytecode version of ocamldoc to generate man pages
+- PR#5184: under Windows, alignment issue with bigarrays mapped from files
+- PR#5188: double-free corruption in bytecode system threads
+- PR#5192: mismatch between words and bytes in interpreting max_young_wosize
+- PR#5202: error in documentation of atan2
+- PR#5209: natdynlink incorrectly detected on BSD systems
+- PR#5213: ocamlbuild should pass '-rectypes' to ocamldoc when needed
+- PR#5217: ocamlfind plugin should add '-linkpkg' for toplevel
+- PR#5228: document the exceptions raised by functions in 'Filename'
+- PR#5229: typo in build script ('TAG_LINE' vs 'TAGLINE')
+- PR#5230: error in documentation of Scanf.Scanning.open_in
+- PR#5234: option -shared reverses order of -cclib options
+- PR#5237: incorrect .size directives generated for x86-32 and x86-64
+- PR#5244: String.compare uses polymorphic compare_val (regression of PR#4194)
+- PR#5248: regression introduced while fixing PR#5118
+- PR#5252: typo in docs
+- PR#5258: win32unix: unix fd leak under windows
+- PR#5269: (tentative fix) Wrong ext_ref entries in .annot files
+- PR#5272: caml.el doesn't recognize downto as a keyword
+- PR#5276: issue with ocamlc -pack and recursively-packed modules
+- PR#5280: alignment constraints incorrectly autodetected on MIPS 32
+- PR#5281: typo in error message
+- PR#5308: unused variables not detected in "include (struct .. end)"
+- camlp4 revised syntax printing bug in the toplevel (reported on caml-list)
+- configure: do not define _WIN32 under cygwin
+- Hardened generic comparison in the case where two custom blocks
+ are compared and have different sets of custom operations.
+- Hardened comparison between bigarrays in the case where the two
+ bigarrays have different kinds.
+- Fixed wrong autodetection of expm1() and log1p().
+- don't add .exe suffix when installing the ocamlmktop shell script
+- ocamldoc: minor fixes related to the display of ocamldoc options
+- fixed bug with huge values in OCAMLRUNPARAM
+- mismatch between declaration and definition of caml_major_collection_slice
+
+Feature wishes:
+- PR#4992: added '-ml-synonym' and '-mli-synonym' options to ocamldep
+- PR#5065: added '-ocamldoc' option to ocamlbuild
+- PR#5139: added possibility to add options to ocamlbuild
+- PR#5158: added access to current camlp4 parsers and printers
+- PR#5180: improved instruction selection for float operations on amd64
+- stdlib: added a 'usage_string' function to Arg
+- allow with constraints to add a type equation to a datatype definition
+- ocamldoc: allow to merge '@before' tags like other ones
+- ocamlbuild: allow dependency on file "_oasis"
+
+Other changes:
+- Changed default minor heap size from 32k to 256k words.
+- Added new operation 'compare_ext' to custom blocks, called when
+ comparing a custom block value with an unboxed integer.
+
+
+Objective Caml 3.12.0 (2 Aug 2010):
+-----------------------------------
+
+(Changes that can break existing programs are marked with a "*" )
+
+Language features:
+- Shorthand notation for records: in expressions and patterns,
+ { lbl } stands for { lbl = lbl } and { M.lbl } for { M.lbl = lbl }
+- Record patterns of the form { lbl = pat; _ } to mark that not all
+ labels are listed, purposefully. (See new warning below.)
+- Explicit naming of a generic type; in an expression
+ "fun ... (type t) ... -> e", the type t is considered abstract in its
+ scope (the arguments that follow it and the body of the function),
+ and then replaced by a fresh type variable. In particular, the type
+ t can be used in contexts where a type variable is not allowed
+ (e.g. for defining an exception in a local module).
+- Explicit polymorphic types and polymorphic recursion. In let
+ definitions, one can write an explicit polymorphic type just
+ immediately the function name; the polymorphism will be enforced,
+ and recursive calls may use the polymorphism.
+ The syntax is the same as for polymorphic methods:
+ "let [rec] <ident> : 'a1 ... 'an. <typexp> = ..."
+- First-class packages modules.
+ New kind of type expression, for packaged modules: (module PT).
+ New kind of expression, to pack a module as a first-class value:
+ (module MODEXPR : PT).
+ New kind of module expression, to unpack a first-class value as a module:
+ (val EXPR : PT).
+ PT is a package type of the form "S" or
+ "S with type t1 = ... and ... and type tn = ..." (S refers to a module type).
+- Local opening of modules in a subexpression.
+ Syntax: "let open M in e", or "M.(e)"
+- In class definitions, method and instance variable override can now
+ be made explicit, by writing "method!", "val!" or "inherit!" in place of
+ "method", "val" and "inherit". It is an error to override an
+ undefined member (or to use overriding inheritance when nothing get
+ overridden). Additionally, these constructs disactivate respectively
+ warnings 7 (method override, code 'M') and 13 (instance variable
+ override, code 'V'). Note that, by default, warning 7 is inactive
+ and warning 13 is active.
+- "Destructive" substitution in signatures.
+ By writing "<signature> with type t := <typeconstr>" and
+ "<signature> with module M := <module-path>" one replaces "t" and "M"
+ inside the signature, removing their respective fields. Among other
+ uses, this allows to merge two signatures containing identically
+ named fields.
+* While fixing PR#4824, also corrected a gaping hole in the type checker,
+ which allowed instantiating separately object parameters and instance
+ variables in an interface. This hole was here since the beginning of
+ ocaml, and as a result many programs using object inheritance in a non
+ trivial way will need to be corrected. You can look at lablgtk2 for an
+ example.
+
+Compilers and toplevel:
+- Warnings are now numbered and can be switched on and off individually.
+ The old system with letters referring to sets of warnings is still
+ supported.
+- New warnings:
+ + 9 (code 'R') to signal record patterns without "; _" where
+ some labels of the record type are not listed in the pattern.
+ + 28 when giving a wildcard argument to a constant constructor in
+ a pattern-matching.
+ + 29 when an end-of-line appears unescaped in a string constant.
+ + 30 when the same constructor or record field is defined twice in
+ mutually-recursive type definitions.
+* The semantics of warning 7 (code 'M', method override) have changed
+ (it now detects all overrides, not just repeated definitions inside
+ the same class body), and it is now inactive by default.
+- Better error report in case of unbound qualified identifier: if the module
+ is unbound this error is reported in the first place.
+- Added option '-strict-sequence' to force left hand part of sequence to have
+ type unit.
+- Added option '-no-app-funct' to turn applicative functors off.
+ This option can help working around mysterious type incompatibilities
+ caused by the incomplete comparison of applicative paths F(X).t.
+
+Native-code compiler:
+- AMD64: shorter and slightly more efficient code generated for
+ float comparisons.
+
+Standard library:
+- Format: new function ikfprintf analoguous to ifprintf with a continuation
+ argument.
+* PR#4210, #4245: stricter range checking in string->integer conversion
+ functions (int_of_string, Int32.of_string, Int64.of_string,
+ Nativeint.of_string). The decimal string corresponding to
+ max_int + 1 is no longer accepted.
+- Scanf: to prevent confusion when mixing Scanf scanning functions and direct
+ low level input, value Scanf.stdin has been added.
+* Random: changed the algorithm to produce better randomness. Now passes the
+ DieHard tests.
+- Map: implement functions from Set that make sense for Map.
+
+Other libraries:
+* Str: letters that constitute a word now include digits 0-9 and
+ underscore _. This changes the interpretation of '\b' (word boundary)
+ in regexps, but is more consistent with other regexp libraries. (PR#4874).
+
+Ocamlbuild:
+- Add support for native dynlink.
+
+New tool:
+- ocamlobjinfo: displays various information, esp. dependencies, for
+ compiled OCaml files (.cmi, .cmo, .cma, .cmx, .cmxa, .cmxs, and bytecode
+ executables). Extends and makes more official the old objinfo tool
+ that was installed by some OCaml packages.
+
+All tools:
+- PR#4857: add a -vnum option to display the version number and nothing else
+
+Bug Fixes:
+- PR#4012: Map.map and Map.mapi do not conform to specification
+- PR#4478: better error messages for type definition mismatches
+- PR#4683: labltk script uses fixed path on windows
+- PR#4742: finalisation function raising an exception blocks other finalisations
+- PR#4775: compiler crash on crazy types (temporary fix)
+- PR#4824: narrowing the type of class parameters with a module specification
+- PR#4862: relaxed value restriction and records
+- PR#4884: optional arguments do not work when Some is redefined
+- PR#4964: parenthesized names for infix functions in annot files
+- PR#4970: better error message for instance variables
+- PR#4975: spelling mistakes
+- PR#4988: contravariance lost with ocamlc -i
+- PR#5004: problem in Buffer.add_channel with very large lengths.
+- PR#5008: on AMD64/MSVC port, rare float corruption during GC.
+- PR#5018: wrong exception raised by Dynlink.loadfile.
+- PR#5057: fatal typing error with local module + functor + polymorphic variant
+- Wrong type for Obj.add_offset.
+- Small problem with representation of Int32, Int64, and Nativeint constants.
+- Use RTLD_LOCAL for native dynlink in private mode.
+
+Objective Caml 3.11.2 (20 Jan 2010):
+------------------------------------
+
+Bug fixes:
+- PR#4151: better documentation for min and max w.r.t. NaN
+- PR#4421: ocamlbuild uses wrong compiler for C files
+- PR#4710, PR#4720: ocamlbuild does not use properly configuration information
+- PR#4750: under some Windows installations, high start-up times for Unix lib
+- PR#4777: problem with scanf and CRLF
+- PR#4783: ocamlmklib problem under Windows
+- PR#4810: BSD problem with socket addresses, e.g. in Unix.getnameinfo
+- PR#4813: issue with parsing of float literals by the GNU assembler
+- PR#4816: problem with modules and private types
+- PR#4818: missed opportunity for type-based optimization of bigarray accesses
+- PR#4821: check for duplicate method names in classes
+- PR#4823: build problem on Mac OS X
+- PR#4836: spurious errors raised by Unix.single_write under Windows
+- PR#4841, PR#4860, PR#4930: problem with ocamlopt -output-obj under Mac OS X
+- PR#4847: C compiler error with ocamlc -output-obj under Win64
+- PR#4856: ocamlbuild uses ocamlrun to execute a native plugin
+- PR#4867, PR#4760: ocamlopt -shared fails on Mac OS X 64bit
+- PR#4873: ocamlbuild ignores "thread" tag when building a custom toplevel
+- PR#4890: ocamlbuild tries to use native plugin on bytecode-only arch
+- PR#4896: ocamlbuild should always pass -I to tools for external libraries
+- PR#4900: small bug triggering automatic compaction even if max_overhead = 1M
+- PR#4902: bug in %.0F printf format
+- PR#4910: problem with format concatenation
+- PR#4922: ocamlbuild recompiles too many files
+- PR#4923: missing \xff for scanf %S
+- PR#4933: functors not handling private types correctly
+- PR#4940: problem with end-of-line in DOS text mode, tentative fix
+- PR#4953: problem compiling bytecode interpreter on ARM in Thumb mode.
+- PR#4955: compiler crash when typing recursive type expression with constraint
+- Module Printf: the simple conversion %F (without width indication) was not
+ treated properly.
+- Makefile: problem with cygwin, flexdll, and symbolic links
+- Various build problems with ocamlbuild under Windows with msvc
+
+Feature wishes:
+- PR#9: (tentative implementation) make ocamldebug use #linenum annotations
+- PR#123, PR#4477: custom exception printers
+- PR#3456: Obj.double_field and Obj.set_double_field functions
+- PR#4003: destination directory can be given to Filename.[open_]temp_file
+- PR#4647: Buffer.blit function
+- PR#4685: access to Filename.dir_sep
+- PR#4703: support for debugging embedded applications
+- PR#4723: "clear_rules" function to empty the set of ocamlbuild rules
+- PR#4921: configure option to help cross-compilers
+
+Objective Caml 3.11.1 (12 Jun 2009):
+------------------------------------
+
+Bug fixes:
+- PR#4095: ocamldebug: strange behaviour of control-C
+- PR#4403: ocamldebug: improved handling of packed modules
+- PR#4650: Str.regexp_case_fold mis-handling complemented character sets [^a]
+- PR#4660: Scanf.format_from_string: handling of double quote
+- PR#4666: Unix.exec* failure in multithread programs under MacOS X and FreeBSD
+- PR#4667: debugger out of sync with dynlink changes
+- PR#4678: random "out of memory" error with systhreads
+- PR#4690: issue with dynamic loading under MacOS 10.5
+- PR#4692: wrong error message with options -i and -pack passed to ocamlc
+- PR#4699: in otherlibs/dbm, fixed construction of dlldbm.so.
+- PR#4704: error in caml_modify_generational_global_root()
+- PR#4708: (ocamldoc) improved printing of infix identifiers such as "lor".
+- PR#4722: typo in configure script
+- PR#4729: documented the fact that PF_INET6 is not available on all platforms
+- PR#4730: incorrect typing involving abbreviation "type 'a t = 'a"
+- PR#4731: incorrect quoting of arguments passed to the assembler on x86-64
+- PR#4735: Unix.LargeFile.fstat cannot report size over 32bits on Win32
+- PR#4740: guard against possible processor error in
+ {Int32,Int64,Nativeint}.{div,rem}
+- PR#4745: type inference wrongly produced non-generalizable type variables.
+- PR#4749: better pipe size for win32unix
+- PR#4756: printf: no error reported for wrong format '%_s'
+- PR#4758: scanf: handling of \<newline> by format '%S'
+- PR#4766: incorrect simplification of some type abbreviations.
+- PR#4768: printf: %F does not respect width and precision specifications
+- PR#4769: Format.bprintf fails to flush
+- PR#4775: fatal error Ctype.Unify during module type-checking (temporary fix)
+- PR#4776: bad interaction between exceptions and classes
+- PR#4780: labltk build problem under Windows.
+- PR#4790: under Windows, map ERROR_NO_DATA Win32 error to EPIPE Unix error.
+- PR#4792: bug in Big_int.big_int_of_int64 on 32-bit platforms.
+- PR#4796: ocamlyacc: missing NUL termination of string
+- PR#4804: bug in Big_int.int64_of_big_int on 32-bit platforms.
+- PR#4805: improving compatibility with the clang C compiler
+- PR#4809: issue with Unix.create_process under Win32
+- PR#4814: ocamlbrowser: crash when editing comments
+- PR#4816: module abbreviations remove 'private' type restrictions
+- PR#4817: Object type gives error "Unbound type parameter .."
+- Module Parsing: improved computation of locations when an ocamlyacc rule
+ starts with an empty nonterminal
+- Type-checker: fixed wrong variance computation for private types
+- x86-32 code generator, MSVC port: wrong "fld" instruction generated.
+- ocamlbuild: incorrectly using the compile-time value of $OCAMLLIB
+- Makefile problem when configured with -no-shared-libs
+- ocamldoc: use dynamic loading in native code
+
+Other changes:
+- Improved wording of various error messages
+ (contributed by Jonathan Davies, Citrix).
+- Support for 64-bit mode in Solaris/x86 (PR#4670).
+
+
+Objective Caml 3.11.0 (03 Dec 2008):
+------------------------------------
+
+(Changes that can break existing programs are marked with a "*" )
+
+Language features:
+- Addition of lazy patterns: "lazy <pat>" matches suspensions whose values,
+ after forcing, match the pattern <pat>.
+- Introduction of private abbreviation types "type t = private <type-expr>",
+ for abstracting the actual manifest type in type abbreviations.
+- Subtyping is now allowed between a private abbreviation and its definition,
+ and between a polymorphic method and its monomorphic instance.
+
+Compilers:
+- The file name for a compilation unit should correspond to a valid
+ identifier (Otherwise dynamic linking and other things can fail, and
+ a warning is emitted.)
+* Revised -output-obj: the output name must now be provided; its
+ extension must be one of .o/.obj, .so/.dll, or .c for the
+ bytecode compiler. The compilers can now produce a shared library
+ (with all the needed -ccopts/-ccobjs options) directly.
+- -dtypes renamed to -annot, records (in .annot files) which function calls
+ are tail calls.
+- All compiler error messages now include a file name and location, for
+ better interaction with Emacs' compilation mode.
+- Optimized compilation of "lazy e" when the argument "e" is
+ already evaluated.
+- Optimized compilation of equality tests with a variant constant constructor.
+- The -dllib options recorded in libraries are no longer ignored when
+ -use_runtime or -use_prims is used (unless -no_auto_link is
+ explicitly used).
+- Check that at most one of -pack, -a, -shared, -c, -output-obj is
+ given on the command line.
+- Optimized compilation of private types as regular manifest types
+ (e.g. abbreviation to float, float array or record types with only
+ float fields).
+
+Native-code compiler:
+- New port: Mac OS X / Intel in 64-bit mode (configure with -cc "gcc -m64").
+- A new option "-shared" to produce a plugin that can be dynamically
+ loaded with the native version of Dynlink.
+- A new option "-nodynlink" to enable optimizations valid only for code
+ that is never dynlinked (no-op except for AMD64).
+- More aggressive unboxing of floats and boxed integers.
+- Can select which assembler and asm options to use at configuration time.
+
+Run-time system:
+- New implementation of the page table describing the heap (two-level
+ array in 32 bits, sparse hashtable in 64 bits), fixes issues with address
+ space randomization on 64-bit OS (PR#4448).
+- New "generational" API for registering global memory roots with the GC,
+ enables faster scanning of global roots.
+ (The functions are caml_*_generational_global_root in <caml/memory.h>.)
+- New function "caml_raise_with_args" to raise an exception with several
+ arguments from C.
+- Changes in implementation of dynamic linking of C code:
+ under Win32, use Alain Frisch's flexdll implementation of the dlopen
+ API; under MacOSX, use dlopen API instead of MacOSX bundle API.
+- Programs may now choose a first-fit allocation policy instead of
+ the default next-fit. First-fit reduces fragmentation but is
+ slightly slower in some cases.
+
+Standard library:
+- Parsing library: new function "set_trace" to programmatically turn
+ on or off the printing of a trace during parsing.
+- Printexc library: new functions "print_backtrace" and "get_backtrace"
+ to obtain a stack backtrace of the most recently raised exception.
+ New function "record_backtrace" to turn the exception backtrace mechanism
+ on or off from within a program.
+- Scanf library: fine-tuning of meta format implementation;
+ fscanf behaviour revisited: only one input buffer is allocated for any
+ given input channel;
+ the %n conversion does not count a lookahead character as read.
+
+Other libraries:
+- Dynlink: on some platforms, the Dynlink library is now available in
+ native code. The boolean Dynlink.is_native allows the program to
+ know whether it has been compiled in bytecode or in native code.
+- Bigarrays: added "unsafe_get" and "unsafe_set"
+ (non-bound-checking versions of "get" and "set").
+- Bigarrays: removed limitation "array dimension < 2^31".
+- Labltk: added support for TK 8.5.
+- Num: added conversions between big_int and int32, nativeint, int64.
+ More efficient implementation of Num.quo_num and Num.mod_num.
+- Threads: improved efficiency of mutex and condition variable operations;
+ improved interaction with Unix.fork (PR#4577).
+- Unix: added getsockopt_error returning type Unix.error.
+ Added support for TCP_NODELAY and IPV6_ONLY socket options.
+- Win32 Unix: "select" now supports all kinds of file descriptors.
+ Improved emulation of "lockf" (PR#4609).
+
+Tools:
+- ocamldebug now supported under Windows (MSVC and Mingw ports),
+ but without the replay feature. (Contributed by Dmitry Bely
+ and Sylvain Le Gall at OCamlCore with support from Lexifi.)
+- ocamldoc: new option -no-module-constraint-filter to include functions
+ hidden by signature constraint in documentation.
+- ocamlmklib and ocamldep.opt now available under Windows ports.
+- ocamlmklib no longer supports the -implib option.
+- ocamlnat: an experimental native toplevel (not built by default).
+
+Camlp4:
+* programs linked with camlp4lib.cma now also need dynlink.cma.
+
+Bug fixes:
+- Major GC and heap compaction: fixed bug involving lazy values and
+ out-of-heap pointers.
+- PR#3915: updated most man pages.
+- PR#4261: type-checking of recursive modules
+- PR#4308: better stack backtraces for "spontaneous" exceptions such as
+ Stack_overflow, Out_of_memory, etc.
+- PR#4338: Str.global_substitute, Str.global_replace and the Str.*split*
+ functions are now tail-recursive.
+- PR#4503: fixed bug in classify_float on ARM.
+- PR#4512: type-checking of recursive modules
+- PR#4517: crash in ocamllex-generated lexers.
+- PR#4542: problem with return value of Unix.nice.
+- PR#4557: type-checking of recursive modules.
+- PR#4562: strange %n semantics in scanf.
+- PR#4564: add note "stack is not executable" to object files generated by
+ ocamlopt (Linux/x86, Linux/AMD64).
+- PR#4566: bug in Ratio.approx_ratio_fix and Num.approx_num_fix.
+- PR#4582: clarified the documentation of functions in the String module.
+- PR#4583: stack overflow in "ocamlopt -g" during closure conversion pass.
+- PR#4585: ocamldoc and "val virtual" declarations.
+- PR#4587: ocamldoc and escaped @ characters.
+- PR#4605: Buffer.add_substitute was sometime wrong when target string had
+ backslashes.
+- PR#4614: Inconsistent declaration of CamlCBCmd in LablTk library.
+
+
+Objective Caml 3.10.2 (29 Feb 2008):
+------------------------------------
+
+Bug fixes:
+- PR#1217 (partial) Typo in ocamldep man page
+- PR#3952 (partial) ocamlopt: allocation problems on ARM
+- PR#4339 (continued) ocamlopt: problems on HPPA
+- PR#4455 str.mli not installed under Windows
+- PR#4473 crash when accessing float array with polymorphic method
+- PR#4480 runtime would not compile without gcc extensions
+- PR#4481 wrong typing of exceptions with object arguments
+- PR#4490 typo in error message
+- Random crash on 32-bit when major_heap_increment >= 2^22
+- Big performance bug in Weak hashtables
+- Small bugs in the make-package-macosx script
+- Bug in typing of polymorphic variants (reported on caml-list)
+
+
+Objective Caml 3.10.1 (11 Jan 2008):
+------------------------------------
+
+Bug fixes:
+- PR#3830 small bugs in docs
+- PR#4053 compilers: improved compilation time for large variant types
+- PR#4174 ocamlopt: fixed ocamlopt -nopervasives
+- PR#4199 otherlibs: documented a small problem in Unix.utimes
+- PR#4280 camlp4: parsing of identifier (^)
+- PR#4281 camlp4: parsing of type constraint
+- PR#4285 runtime: cannot compile under AIX
+- PR#4286 ocamlbuild: cannot compile under AIX and SunOS
+- PR#4288 compilers: including a functor application with side effects
+- PR#4295 camlp4 toplevel: synchronization after an error
+- PR#4300 ocamlopt: crash with backtrace and illegal array access
+- PR#4302 camlp4: list comprehension parsing problem
+- PR#4304 ocamlbuild: handle -I correctly
+- PR#4305 stdlib: alignment of Arg.Symbol
+- PR#4307 camlp4: assertion failure
+- PR#4312 camlp4: accept "let _ : int = 1"
+- PR#4313 ocamlbuild: -log and missing directories
+- PR#4315 camlp4: constraints in classes
+- PR#4316 compilers: crash with recursive modules and Lazy
+- PR#4318 ocamldoc: installation problem with Cygwin (tentative fix)
+- PR#4322 ocamlopt: stack overflow under Windows
+- PR#4325 compilers: wrong error message for unused var
+- PR#4326 otherlibs: marshal Big_int on win64
+- PR#4327 ocamlbuild: make emacs look for .annot in _build directory
+- PR#4328 camlp4: stack overflow with nil nodes
+- PR#4331 camlp4: guards on fun expressions
+- PR#4332 camlp4: parsing of negative 32/64 bit numbers
+- PR#4336 compilers: unsafe recursive modules
+- PR#4337 (note) camlp4: invalid character escapes
+- PR#4339 ocamlopt: problems on HP-UX (tentative fix)
+- PR#4340 camlp4: wrong pretty-printing of optional arguments
+- PR#4348 ocamlopt: crash on Mac Intel
+- PR#4349 camlp4: bug in private type definitions
+- PR#4350 compilers: type errors with records and polymorphic variants
+- PR#4352 compilers: terminal recursion under Windows (tentative fix)
+- PR#4354 ocamlcp: mismatch with ocaml on polymorphic let
+- PR#4358 ocamlopt: float constants wrong on ARM
+- PR#4360 ocamldoc: string inside comment
+- PR#4365 toplevel: wrong pretty-printing of polymorphic variants
+- PR#4373 otherlibs: leaks in win32unix
+- PR#4374 otherlibs: threads module not initialized
+- PR#4375 configure: fails to build on bytecode-only architectures
+- PR#4377 runtime: finalisation of infix pointers
+- PR#4378 ocamlbuild: typo in plugin.ml
+- PR#4379 ocamlbuild: problem with plugins under Windows
+- PR#4382 compilers: typing of polymorphic record fields
+- PR#4383 compilers: including module with private type
+- PR#4385 stdlib: Int32/Int64.format are unsafe
+- PR#4386 otherlibs: wrong signal numbers with Unix.sigprocmask etc.
+- PR#4387 ocamlbuild: build directory not used properly
+- PR#4392 ocamldep: optional argument of class
+- PR#4394 otherlibs: infinite loops in Str
+- PR#4397 otherlibs: wrong size for flag arrays in win32unix
+- PR#4402 ocamldebug: doesn't work with -rectypes
+- PR#4410 ocamlbuild: problem with plugin and -build
+- PR#4411 otherlibs: crash with Unix.access under Windows
+- PR#4412 stdlib: marshalling broken on 64 bit architectures
+- PR#4413 ocamlopt: crash on AMD64 with out-of-bound access and reraise
+- PR#4417 camlp4: pretty-printing of unary minus
+- PR#4419 camlp4: problem with constraint in type class
+- PR#4426 compilers: problem with optional labels
+- PR#4427 camlp4: wrong pretty-printing of lists of functions
+- PR#4433 ocamlopt: fails to build on MacOSX 10.5
+- PR#4435 compilers: crash with objects
+- PR#4439 fails to build on MacOSX 10.5
+- PR#4441 crash when build on sparc64 linux
+- PR#4442 stdlib: crash with weak pointers
+- PR#4446 configure: fails to detect X11 on MacOSX 10.5
+- PR#4448 runtime: huge page table on 64-bit architectures
+- PR#4450 compilers: stack overflow with recursive modules
+- PR#4470 compilers: type-checking of recursive modules too restrictive
+- PR#4472 configure: autodetection of libX11.so on Fedora x86_64
+- printf: removed (partially implemented) positional specifications
+- polymorphic < and <= comparisons: some C compiler optimizations
+ were causing incorrect results when arguments are incomparable
+
+New features:
+- made configure script work on PlayStation 3
+- ARM port: brought up-to-date for Debian 4.0 (Etch)
+- many other small changes and bugfixes in camlp4, ocamlbuild, labltk,
+ emacs files
+
+
+Objective Caml 3.10.0 (18 May 2007):
+------------------------------------
+
+(Changes that can break existing programs are marked with a "*" )
+
+Language features:
+- Added virtual instance variables in classes "val virtual v : t"
+* Changed the behaviour of instance variable overriding; the new
+ definition replaces the old one, rather than creating a new
+ variable.
+
+New tools:
+- ocamlbuild: compilation manager for OCaml applications and libraries.
+ See draft documentation at http://gallium.inria.fr/~pouillar/
+* Camlp4: heavily revised implementation, new API.
+
+New ports:
+- MacOS X PowerPC 64 bits.
+- MS Windows 64 bits (x64) using the Microsoft PSDK toolchain.
+- MS Windows 32 bits using the Visual Studio 2005 toolchain.
+
+Compilers:
+- Faster type-checking of functor applications.
+- Referencing an interface compiled with -rectypes from a module
+ not compiled with -rectypes is now an error.
+- Revised the "fragile matching" warning.
+
+Native-code compiler:
+- Print a stack backtrace on an uncaught exception.
+ (Compile and link with ocamlopt -g; execute with OCAMLRUNPARAM=b.)
+ Supported on Intel/AMD in 32 and 64 bits, PPC in 32 and 64 bits.
+- Stack overflow detection on MS Windows 32 bits (courtesy O. Andrieu).
+- Stack overflow detection on MacOS X PPC and Intel.
+- Intel/AMD 64 bits: generate position-independent code by default.
+- Fixed bug involving -for-pack and missing .cmx files (PR#4124).
+- Fixed bug causing duplication of literals (PR#4152).
+
+Run-time system:
+- C/Caml interface functions take "char const *" arguments
+ instead of "char *" when appropriate.
+- Faster string comparisons (fast case if strings are ==).
+
+Standard library:
+- Refined typing of format strings (type format6).
+- Printf, Format: new function ifprintf that consumes its arguments
+ and prints nothing (useful to print conditionally).
+- Scanf:
+ new function format_from_string to convert a string to a format string;
+ new %r conversion to accomodate user defined scanners.
+- Filename: improved Win32 implementation of Filename.quote.
+- List: List.nth now tail-recursive.
+- Sys: added Sys.is_directory. Some functions (e.g. Sys.command) that
+ could incorrectly raise Sys_io_blocked now raise Sys_error as intended.
+- String and Char: the function ``escaped'' now escapes all the characters
+ especially handled by the compiler's lexer (PR#4220).
+
+Other libraries:
+- Bigarray: mmap_file takes an optional argument specifying
+ the start position of the data in the mapped file.
+- Dynlink: now defines only two modules, Dynlink and Dynlinkaux (internal),
+ reducing risks of name conflicts with user modules.
+- Labltk under Win32: now uses Tcl/Tk 8.4 instead of 8.3 by default.
+- VM threads: improved performance of I/O operations (less polling).
+- Unix: new function Unix.isatty.
+- Unix emulation under Win32:
+ fixed incorrect error reporting in several functions (PR#4097);
+ better handling of channels opened on sockets (PR#4098);
+ fixed GC bug in Unix.system (PR#4112).
+
+Documentation generator (OCamldoc):
+- correctly handle '?' in value names (PR#4215)
+- new option -hide-warnings not to print ocamldoc warnings
+
+Lexer generator (ocamllex): improved error reporting.
+
+License: fixed a typo in the "special exception" to the LGPL.
+
+
+Objective Caml 3.09.3 (15 Sep 2006):
+------------------------------------
+
+Bug fixes:
+- ocamldoc: -using modtype constraint to filter module elements displayed
+ in doc PR#4016
+- ocamldoc: error in merging of top dependencies of modules PR#4007
+- ocamldoc: -dot-colors has no effect PR#3981
+- ocamdloc: missing crossref in text from intro files PR#4066
+- compilers: segfault with recursive modules PR#4008
+- compilers: infinite loop when compiling objects PR#4018
+- compilers: bad error message when signature mismatch PR#4001
+- compilers: infinite loop with -rectypes PR#3999
+- compilers: contravariance bug in private rows
+- compilers: unsafe cast with polymorphic exception PR#4002
+- native compiler: bad assembly code generated for AMD64 PR#4067
+- native compiler: stack alignment problems on MacOSX/i386 PR#4036
+- stdlib: crash in marshalling PR#4030
+- stdlib: crash when closing a channel twice PR#4039
+- stdlib: memory leak in Sys.readdir PR#4093
+- C interface: better definition of CAMLreturn PR#4068
+- otherlibs/unix: crash in gethostbyname PR#3043
+- tools: subtle problem with unset in makefile PR#4048
+- camlp4: install pa_o_fast.o PR#3812
+- camlp4: install more modules PR#3689
+
+New features:
+- ocamldoc: name resolution in cross-referencing {!name}: if name is not
+ found, then it is searched in the parent module/class, and in the parent
+ of the parent, and so on until it is found.
+- ocamldoc: new option -short-functors to use a short form to display
+ functors in html generator PR#4017
+- ocamlprof: added "-version" option
+
+
+
+Objective Caml 3.09.2 (14 Apr 2006):
+------------------------------------
+
+Bug fixes:
+- Makefile: problem with "make world.opt" PR#3954
+- compilers: problem compiling several modules with one command line PR#3979
+- compilers,ocamldoc: error message that Emacs cannot parse
+- compilers: crash when printing type error PR#3968
+- compilers: -dtypes wrong for monomorphic type variables PR#3894
+- compilers: wrong warning on optional arguments PR#3980
+- compilers: crash when wrong use of type constructor in let rec PR#3976
+- compilers: better wording of "statement never returns" warning PR#3889
+- runtime: inefficiency of signal handling PR#3990
+- runtime: crashes with I/O in multithread programs PR#3906
+- camlp4: empty file name in error messages PR#3886
+- camlp4: stack overflow PR#3948
+- otherlibs/labltk: ocamlbrowser ignores its command line options PR#3961
+- otherlibs/unix: Unix.times wrong under Mac OS X PR#3960
+- otherlibs/unix: wrong doc for execvp and execvpe PR#3973
+- otherlibs/win32unix: random crash in Unix.stat PR#3998
+- stdlib: update_mod not found under Windows PR#3847
+- stdlib: Filename.dirname/basename wrong on Win32 PR#3933
+- stdlib: incomplete documentation of Pervasives.abs PR#3967
+- stdlib: Printf bugs PR#3902, PR#3955
+- tools/checkstack.c: missing include
+- yacc: crash when given argument "-" PR#3956
+
+New features:
+- ported to MacOS X on Intel PR#3985
+- configure: added support for GNU Hurd PR#3991
+
+Objective Caml 3.09.1 (4 Jan 2006):
+-----------------------------------
+
+Bug fixes:
+- compilers: raise not_found with -principal PR#3855
+- compilers: assert failure in typeclass.cml PR#3856
+- compilers: assert failure in typing/ctype.ml PR#3909
+- compilers: fatal error exception Ctype.Unify PR#3918
+- compilers: spurious warning Y in objects PR#3868
+- compilers: spurious warning Z on loop index PR#3907
+- compilers: error message that emacs cannot parse
+- ocamlopt: problems with -for-pack/-pack PR#3825, PR#3826, PR#3919
+- ocamlopt: can't produce shared libraries on x86_64 PR#3869, PR#3924
+- ocamlopt: float alignment problem on SPARC PR#3944
+- ocamlopt: can't compile on MIPS PR#3936
+- runtime: missing dependence for ld.conf
+- runtime: missing dependence for .depend.nt PR#3880
+- runtime: memory leak in caml_register_named_value PR#3940
+- runtime: crash in Marshal.to_buffer PR#3879
+- stdlib: Sys.time giving wrong results on Mac OS X PR#3850
+- stdlib: Weak.get_copy causing random crashes in rare cases
+- stdlib, debugger, labltk: use TMPDIR if set PR#3895
+- stdlib: scanf bug on int32 and nativeint PR#3932
+- camlp4: mkcamlp4 option parsing problem PR#3941
+- camlp4: bug in pretty-printing of lazy/assert/new
+- camlp4: update the unmaintained makefile for _loc name
+- ocamldoc: several fixes see ocamldoc/Changes.txt
+- otherlibs/str: bug in long sequences of alternatives PR#3783
+- otherlibs/systhreads: deadlock in Windows PR#3910
+- tools: update dumpobj to handle new event format PR#3873
+- toplevel: activate warning Y in toplevel PR#3832
+
+New features:
+- otherlibs/labltk: browser uses menu bars instead of menu buttons
+
+Objective Caml 3.09.0 (27 Oct 2006):
+------------------------------------
+
+(Changes that can break existing programs are marked with a "*" )
+
+Language features:
+- Introduction of private row types, for abstracting the row in object
+ and variant types.
+
+Type checking:
+- Polymorphic variants with at most one constructor [< `A of t] are no
+ longer systematically promoted to the exact type [`A of t]. This was
+ more confusing than useful, and created problems with private row
+ types.
+
+Both compilers:
+- Added warnings 'Y' and 'Z' for local variables that are bound but
+ never used.
+- Added warning for some uses non-returning functions (e.g. raise), when they
+ are passed extra arguments, or followed by extra statements.
+- Pattern matching: more prudent compilation in case of guards; fixed PR#3780.
+- Compilation of classes: reduction in size of generated code.
+- Compilation of "module rec" definitions: fixed a bad interaction with
+ structure coercion (to a more restrictive signature).
+
+Native-code compiler (ocamlopt):
+* Revised implementation of the -pack option (packing of several compilation
+ units into one). The .cmx files that are to be packed with
+ "ocamlopt -pack -o P.cmx" must be compiled with "ocamlopt -for-pack P".
+ In exchange for this additional constraint, ocamlopt -pack is now
+ available on all platforms (no need for binutils).
+* Fixed wrong evaluation order for arguments to certain inlined functions.
+- Modified code generation for "let rec ... and ..." to reduce compilation
+ time (which was quadratic in the number of mutually-recursive functions).
+- x86 port: support tail-calls for functions with up to 21 arguments.
+- AMD64 port, Linux: recover from system stack overflow.
+- Sparc port: more portable handling of out-of-bound conditions
+ on systems other than Solaris.
+
+Standard library:
+- Pervasives: faster implementation of close_in, close_out.
+ set_binary_mode_{out,in} now working correctly under Cygwin.
+- Printf: better handling of partial applications of the printf functions.
+- Scanf: new function sscanf_format to read a format from a
+ string. The type of the resulting format is dynamically checked and
+ should be the type of the template format which is the second argument.
+- Scanf: no more spurious lookahead attempt when the end of file condition
+ is set and a correct token has already been read and could be returned.
+
+Other libraries:
+- System threads library: added Thread.sigmask; fixed race condition
+ in signal handling.
+- Bigarray library: fixed bug in Array3.of_array.
+- Unix library: use canonical signal numbers in results of Unix.wait*;
+ hardened Unix.establish_server against EINTR errors.
+
+Run-time system:
+- Support platforms where sizeof(void *) = 8 and sizeof(long) = 4.
+- Improved and cleaned up implementation of signal handling.
+
+Replay debugger:
+- Improved handling of locations in source code.
+
+OCamldoc:
+- extensible {foo } syntax
+- user can give .txt files on the command line, containing ocamldoc formatted
+ text, to be able to include bigger texts out of source files
+- -o option is now used by the html generator to indicate the prefix
+ of generated index files (to avoid conflict when a Index module exists
+ on case-insensitive file systems).
+
+Miscellaneous:
+- Configuration information is installed in `ocamlc -where`/Makefile.config
+ and can be used by client Makefiles or shell scripts.
+
+Objective Caml 3.08.4 (11 Aug 2005):
+------------------------------------
+
+New features:
+- configure: find X11 config in some 64-bit Linux distribs
+- ocamldoc: (**/**) can be canceled with another (**/**) PR#3665
+- graphics: added resize_window
+- graphics: check for invalid arguments to drawing primitives PR#3595
+- ocamlbrowser: use windows subsystem on mingw
+
+Bug fixes:
+- ocamlopt: code generation problem on AMD64 PR#3640
+- wrong code generated for some classes PR#3576
+- fatal error when compiling some OO code PR#3745
+- problem with comparison on constant constructors PR#3608
+- camlp4: cryptic error message PR#3592
+- camlp4: line numbers in multi-line antiquotations PR#3549
+- camlp4: problem with make depend
+- camlp4: parse error with :> PR#3561
+- camlp4: ident conversion problem with val/contents/contents__
+- camlp4: several small parsing problems PR#3688
+- ocamldebug: handling of spaces in executable file name PR#3736
+- emacs-mode: problem when caml-types-buffer is deleted by user PR#3704
+- ocamldoc: extra backslash in ocamldoc man page PR#3687
+- ocamldoc: improvements to HTML display PR#3698
+- ocamldoc: escaping of @ in info files
+- ocamldoc: escaping of . and \ in man pages PR#3686
+- ocamldoc: better error reporting of misplaced comments
+- graphics: fixed .depend file PR#3558
+- graphics: segfault with threads and graphics PR#3651
+- nums: several bugs: PR#3718, PR#3719, others
+- nums: inline asm problems with gcc 4.0 PR#3604, PR#3637
+- threads: problem with backtrace
+- unix: problem with getaddrinfo PR#3565
+- stdlib: documentation of Int32.rem and Int64.rem PR#3573
+- stdlib: documentation of List.rev_map2 PR#3685
+- stdlib: wrong order in Map.fold PR#3607
+- stdlib: documentation of maximum float array length PR#3714
+- better detection of cycles when using -rectypes
+- missing case of module equality PR#3738
+- better error messages for unbound type variables
+- stack overflow while printing type error message PR#3705
+- assert failure when typing some classes PR#3638
+- bug in type_approx
+- better error messages related to type variance checking
+- yacc: avoid name capture for idents of the Parsing module
+
+
+Objective Caml 3.08.3 (24 Mar 2005):
+------------------------------------
+
+New features:
+- support for ocamlopt -pack under Mac OS X (PR#2634, PR#3320)
+- ignore unknown warning options for forward and backward compatibility
+- runtime: export caml_compare_unordered (PR#3479)
+- camlp4: install argl.* files (PR#3439)
+- ocamldoc: add -man-section option
+- labltk: add the "solid" relief option (PR#3343)
+
+Bug fixes:
+- typing: fix unsoundness in type declaration variance inference.
+ Type parameters which are constrained must now have an explicit variant
+ annotation, otherwise they are invariant. This is not backward
+ compatible, so this might break code which either uses subtyping or
+ uses the relaxed value restriction (i.e. was not typable before 3.07)
+- typing: erroneous partial match warning for polymorphic variants (PR#3424)
+- runtime: handle the case of an empty command line (PR#3409, PR#3444)
+- stdlib: make Sys.executable_name an absolute path in native code (PR#3303)
+- runtime: fix memory leak in finalise.c
+- runtime: auto-trigger compaction even if gc is called manually (PR#3392)
+- stdlib: fix segfault in Obj.dup on zero-sized values (PR#3406)
+- camlp4: correct parsing of the $ identifier (PR#3310, PR#3469)
+- windows (MS tools): use link /lib instead of lib (PR#3333)
+- windows (MS tools): change default install destination
+- autoconf: better checking of SSE2 instructions (PR#3329, PR#3330)
+- graphics: make close_graph close the X display as well as the window (PR#3312)
+- num: fix big_int_of_string (empty string) (PR#3483)
+- num: fix big bug on 64-bit architecture (PR#3299)
+- str: better documentation of string_match and string_partial_match (PR#3395)
+- unix: fix file descriptor leak in Unix.accept (PR#3423)
+- unix: miscellaneous clean-ups
+- unix: fix documentation of Unix.tm (PR#3341)
+- graphics: fix problem when allocating lots of images under Windows (PR#3433)
+- compiler: fix error message with -pack when .cmi is missing (PR#3028)
+- cygwin: fix problem with compilation of camlheader (PR#3485)
+- stdlib: Filename.basename doesn't return an empty string any more (PR#3451)
+- stdlib: better documentation of Open_excl flag (PR#3450)
+- ocamlcp: accept -thread option (PR#3511)
+- ocamldep: handle spaces in file names (PR#3370)
+- compiler: remove spurious warning in pattern-matching on variants (PR#3424)
+- windows: better handling of InterpreterPath registry entry (PR#3334, PR#3432)
+
+
+Objective Caml 3.08.2 (22 Nov 2004):
+------------------------------------
+
+Bug fixes:
+- runtime: memory leak when unmarshalling big data structures (PR#3247)
+- camlp4: incorrect line numbers in errors (PR#3188)
+- emacs: xemacs-specific code, wrong call to "sit-for"
+- ocamldoc: "Lexing: empty token" (PR#3173)
+- unix: problem with close_process_* (PR#3191)
+- unix: possible coredumps (PR#3252)
+- stdlib: wrong order in Set.fold (PR#3161)
+- ocamlcp: array out of bounds in profiled programs (PR#3267)
+- yacc: problem with polymorphic variant types for grammar entries (PR#3033)
+
+Misc:
+- export <caml/printexc.h> for caml_format_exception (PR#3080)
+- clean up caml_search_exe_in_path (maybe PR#3079)
+- camlp4: new function "make_lexer" for new-style locations
+- unix: added missing #includes (PR#3088)
+
+
+Objective Caml 3.08.1 (19 Aug 2004):
+------------------------------------
+
+Licence:
+- The emacs files are now under GPL
+- Slightly relaxed some conditions of the QPL
+
+Bug fixes:
+- ld.conf now generated at compile-time instead of install-time
+- fixed -pack on Windows XP (PR#2935)
+- fixed Obj.tag (PR#2946)
+- added support for multiple dlopen in Darwin
+- run ranlib when installing camlp4 libraries (PR#2944)
+- link camlp4opt with -linkall (PR#2949)
+- camlp4 parsing of patterns now conforms to normal parsing (PR#3015)
+- install camlp4 *.cmx files (PR#2955)
+- fixed handling of linefeed in string constants in camlp4 (PR#3074)
+- ocamldoc: fixed display of class parameters in HTML and LaTeX (PR#2994)
+- ocamldoc: fixed display of link to class page in html (PR#2994)
+- Windows toplevel GUI: assorted fixes (including PR#2932)
+
+Misc:
+- added -v option to ocamllex
+- ocamldoc: new -intf and -impl options supported (PR#3036)
+
+Objective Caml 3.08.0 (13 Jul 2004):
+------------------------------------
+
+(Changes that can break existing programs are marked with a "*" )
+
+Language features:
+- Support for immediate objects, i.e. objects defined without going
+ through a class. (Syntax is "object <fields and methods> end".)
+
+Type-checking:
+- When typing record construction and record patterns, can omit
+ the module qualification on all labels except one. I.e.
+ { M.l1 = ...; l2 = ... } is interpreted as { M.l1 = ...; M.l2 = ... }
+
+Both compilers:
+- More compact compilation of classes.
+- Much more efficient handling of class definitions inside functors
+ or local modules.
+- Simpler representation for method tables. Objects can now be marshaled
+ between identical programs with the flag Marshal.Closures.
+- Improved error messages for objects and variants.
+- Improved printing of inferred module signatures (toplevel and ocamlc -i).
+ Recursion between type, class, class type and module definitions is now
+ correctly printed.
+- The -pack option now accepts compiled interfaces (.cmi files) in addition
+ to compiled implementations (.cmo or .cmx).
+* A compile-time error is signaled if an integer literal exceeds the
+ range of representable integers.
+- Fixed code generation error for "module rec" definitions.
+- The combination of options -c -o sets the name of the generated
+ .cmi / .cmo / .cmx files.
+
+Bytecode compiler:
+- Option -output-obj is now compatible with Dynlink and
+ with embedded toplevels.
+
+Native-code compiler:
+- Division and modulus by zero correctly raise exception Division_by_zero
+ (instead of causing a hardware trap).
+- Improved compilation time for the register allocation phase.
+- The float constant -0.0 was incorrectly treated as +0.0 on some processors.
+- AMD64: fixed bugs in asm glue code for GC invocation and exception raising
+ from C.
+- IA64: fixed incorrect code generated for "expr mod 1".
+- PowerPC: minor performance tweaks for the G4 and G5 processors.
+
+Standard library:
+* Revised handling of NaN floats in polymorphic comparisons.
+ The polymorphic boolean-valued comparisons (=, <, >, etc) now treat
+ NaN as uncomparable, as specified by the IEEE standard.
+ The 3-valued comparison (compare) treats NaN as equal to itself
+ and smaller than all other floats. As a consequence, x == y
+ no longer implies x = y but still implies compare x y = 0.
+* String-to-integer conversions now fail if the result overflows
+ the range of integers representable in the result type.
+* All array and string access functions now raise
+ Invalid_argument("index out of bounds") when a bounds check fails.
+ In earlier releases, different exceptions were raised
+ in bytecode and native-code.
+- Module Buffer: new functions Buffer.sub, Buffer.nth
+- Module Int32: new functions Int32.bits_of_float, Int32.float_of_bits.
+- Module Map: new functions is_empty, compare, equal.
+- Module Set: new function split.
+* Module Gc: in-order finalisation, new function finalise_release.
+
+Other libraries:
+- The Num library: complete reimplementation of the C/asm lowest
+ layer to work around potential licensing problems.
+ Improved speed on the PowerPC and AMD64 architectures.
+- The Graphics library: improved event handling under MS Windows.
+- The Str library: fixed bug in "split" functions with nullable regexps.
+- The Unix library:
+ . Added Unix.single_write.
+ . Added support for IPv6.
+ . Bug fixes in Unix.closedir.
+ . Allow thread switching on Unix.lockf.
+
+Runtime System:
+* Name space depollution: all global C identifiers are now prefixed
+ with "caml" to avoid name clashes with other libraries. This
+ includes the "external" primitives of the standard runtime.
+
+Ports:
+- Windows ports: many improvements in the OCamlWin toplevel application
+ (history, save inputs to file, etc). Contributed by Christopher A. Watford.
+- Native-code compilation supported for HPPA/Linux. Contributed by Guy Martin.
+- Removed support for MacOS9. Mac OS 9 is obsolete and the port was not
+ updated since 3.05.
+- Removed ocamlopt support for HPPA/Nextstep and Power/AIX.
+
+Ocamllex:
+- #line directives in the input file are now accepted.
+- Added character set concatenation operator "cset1 # cset2".
+
+Ocamlyacc:
+- #line directives in the input file are now accepted.
+
+Camlp4:
+* Support for new-style locations (line numbers, not just character numbers).
+- See camlp4/CHANGES and camlp4/ICHANGES for more info.
+
+
+Objective Caml 3.07 (29 Sep 2003):
+----------------------------------
+
+Language features:
+- Experimental support for recursive module definitions
+ module rec A : SIGA = StructA and B : SIGB = StructB and ...
+- Support for "private types", or more exactly concrete data types
+ with private constructors or labels. These data types can be
+ de-structured normally in pattern matchings, but values of these
+ types cannot be constructed directly outside of their defining module.
+- Added integer literals of types int32, nativeint, int64
+ (written with an 'l', 'n' or 'L' suffix respectively).
+
+Type-checking:
+- Allow polymorphic generalization of covariant parts of expansive
+ expressions. For instance, if f: unit -> 'a list, "let x = f ()"
+ gives "x" the generalized type forall 'a. 'a list, instead of '_a list
+ as before.
+- The typing of polymorphic variants in pattern matching has changed.
+ It is intended to be more regular, sticking to the principle of "closing
+ only the variants which would be otherwise incomplete". Two potential
+ consequences: (1) some types may be left open which were closed before,
+ and the resulting type might not match the interface anymore (expected to
+ be rare); (2) in some cases an incomplete match may be generated.
+- Lots of bug fixes in the handling of polymorphism and recursion inside
+ types.
+- Added a new "-dtypes" option to ocamlc/ocamlopt, and an emacs extension
+ "emacs/caml-types.el". The compiler option saves inferred type information
+ to file *.annot, and the emacs extension allows the user to look at the
+ type of any subexpression in the source file. Works even in the case
+ of a type error (all the types computed up to the error are available).
+ This new feature is also supported by ocamlbrowser.
+- Disable "method is overridden" warning when the method was explicitly
+ redefined as virtual beforehand (i.e. not through inheritance). Typing
+ and semantics are unchanged.
+
+Both compilers:
+- Added option "-dtypes" to dump detailed type information to a file.
+- The "-i" option no longer generates compiled files, it only prints
+ the inferred types.
+- The sources for the module named "Mod" can be placed either in Mod.ml or
+ in mod.ml.
+- Compilation of "let rec" on non-functional values: tightened some checks,
+ relaxed some other checks.
+- Fixed wrong code that was generated for "for i = a to max_int"
+ or "for i = a downto min_int".
+- An explicit interface Mod.mli can now be provided for the module obtained
+ by ocamlc -pack -o Mod.cmo ... or ocamlopt -pack -o Mod.cmx ...
+- Revised internal handling of source code locations, now handles
+ preprocessed code better.
+- Pattern-matching bug on float literals fixed.
+- Minor improvements on pattern-matching over variants.
+- More efficient compilation of string comparisons and the "compare" function.
+- More compact code generated for arrays of constants.
+- Fixed GC bug with mutable record fields of type "exn".
+- Added warning "E" for "fragile patterns": pattern matchings that would
+ not be flagged as partial if new constructors were added to the data type.
+
+Bytecode compiler:
+- Added option -vmthread to select the threads library with VM-level
+ scheduling. The -thread option now selects the system threads library.
+
+Native-code compiler:
+- New port: AMD64 (Opteron).
+- Fixed instruction selection bug on expressions of the kind (raise Exn)(arg).
+- Several bug fixes in ocamlopt -pack (tracking of imported modules,
+ command line too long).
+- Signal handling bug fixed.
+- x86 port:
+ Added -ffast-math option to use inline trigo and log functions.
+ Small performance tweaks for the Pentium 4.
+ Fixed illegal "imul" instruction generated by reloading phase.
+- Sparc port:
+ Enhanced code generation for Sparc V8 (option -march=v8) and
+ Sparc V9 (option -march=v9).
+ Profiling support added for Solaris.
+- PowerPC port:
+ Keep stack 16-aligned for compatibility with C calling conventions.
+
+Toplevel interactive system:
+- Tightened interface consistency checks between .cmi files, .cm[oa] files
+ loaded by #load, and the running toplevel.
+- #trace on mutually-recursive functions was broken, works again.
+- Look for .ocamlinit file in home directory in addition to the current dir.
+
+Standard library:
+- Match_failure and Assert_failure exceptions now report
+ (file, line, column), instead of (file, starting char, ending char).
+- float_of_string, int_of_string: some ill-formed input strings were not
+ rejected.
+- Added format concatenation, string_of_format, format_of_string.
+- Module Arg: added new option handlers Set_string, Set_int, Set_float,
+ Symbol, Tuple.
+- Module Format: tag handling is now turned off by default,
+ use [Format.set_tags true] to activate.
+- Modules Lexing and Parsing: added better handling of positions
+ in source file. Added function Lexing.flush_input.
+- Module Scanf: %n and %N formats to count characters / items read so far;
+ assorted bug fixes, %! to match end of input. New ``_'' special
+ flag to skip reresulting value.
+- Module Format: tags are not activated by default.
+- Modules Set and Map: fixed bugs causing trees to become unbalanced.
+- Module Printf: less restrictive typing of kprintf.
+- Module Random: better seeding; functions to generate random int32, int64,
+ nativeint; added support for explicit state management.
+- Module Sys: added Sys.readdir for reading the contents of a directory.
+
+Runtime system:
+- output_value/input_value: fixed bug with large blocks (>= 4 Mwords)
+ produced on a 64-bit platform and incorrectly read back on a 32-bit
+ platform.
+- Fixed memory compaction bug involving input_value.
+- Added MacOS X support for dynamic linking of C libraries.
+- Improved stack backtraces on uncaught exceptions.
+- Fixed float alignment problem on Sparc V9 with gcc 3.2.
+
+Other libraries:
+- Dynlink:
+ By default, dynamically-loaded code now has access to all
+ modules defined by the program; new functions Dynlink.allow_only
+ and Dynlink.prohibit implement access control.
+ Fixed Dynlink problem with files generated with ocamlc -pack.
+ Protect against references to modules not yet fully initialized.
+- LablTK/CamlTK: added support for TCL/TK 8.4.
+- Str: reimplemented regexp matching engine, now less buggy, faster,
+ and LGPL instead of GPL.
+- Graphics: fixed draw_rect and fill_rect bug under X11.
+- System threads and bytecode threads libraries can be both installed.
+- System threads: better implementation of Thread.exit.
+- Bytecode threads: fixed two library initialization bugs.
+- Unix: make Unix.openfile blocking to account for named pipes;
+ GC bug in Unix.*stat fixed; fixed problem with Unix.dup2 on Windows.
+
+Ocamllex:
+- Can name parts of the matched input text, e.g.
+ "0" (['0'-'7']+ as s) { ... s ... }
+
+Ocamldebug:
+- Handle programs that run for more than 2^30 steps.
+
+Emacs mode:
+- Added file caml-types.el to interactively display the type information
+ saved by option -dtypes.
+
+Win32 ports:
+- Cygwin port: recognize \ as directory separator in addition to /
+- MSVC port: ocamlopt -pack works provided GNU binutils are installed.
+- Graphics library: fixed bug in Graphics.blit_image; improved event handling.
+
+OCamldoc:
+- new ty_code field for types, to keep code of a type (with option -keep-code)
+- new ex_code field for types, to keep code of an exception
+ (with option -keep-code)
+- some fixes in html generation
+- don't overwrite existing style.css file when generating HTML
+- create the ocamldoc.sty file when generating LaTeX (if nonexistent)
+- man pages are now installed in man/man3 rather than man/mano
+- fix: empty [] in generated HTML indexes
+
+
+Objective Caml 3.06 (20 Aug 2002):
+----------------------------------
+
+Type-checking:
+- Apply value restriction to polymorphic record fields.
+
+Run-time system:
+- Fixed GC bug affecting lazy values.
+
+Both compilers:
+- Added option "-version" to print just the version number.
+- Fixed wrong dependencies in .cmi generated with the -pack option.
+
+Native-code compiler:
+- Fixed wrong return value for inline bigarray assignments.
+
+Libraries:
+- Unix.getsockopt: make sure result is a valid boolean.
+
+Tools:
+- ocamlbrowser: improved error reporting; small Win32 fixes.
+
+Windows ports:
+- Fixed two problems with the Mingw port under Cygwin 1.3.
+
+
+Objective Caml 3.05 (29 Jul 2002):
+----------------------------------
+
+Language features:
+- Support for polymorphic methods and record fields.
+- Allows _ separators in integer and float literals, e.g. 1_000_000.
+
+Type-checker:
+- New flag -principal to enforce principality of type inference.
+- Fixed subtle typing bug with higher-order functors.
+- Fixed several complexity problems; changed (again) the behaviour of
+ simple coercions.
+- Fixed various bugs with objects and polymorphic variants.
+- Improved some error messages.
+
+Both compilers:
+- Added option "-pack" to assemble several compilation units as one unit
+ having the given units as sub-modules.
+- More precise detection of unused sub-patterns in "or" patterns.
+- Warnings for ill-formed \ escapes in string and character literals.
+- Protect against spaces and other special characters in directory names.
+- Added interface consistency check when building a .cma or .cmxa library.
+- Minor reduction in code size for class initialization code.
+- Added option "-nostdlib" to ignore standard library entirely.
+
+Bytecode compiler:
+- Fixed issue with ocamlc.opt and dynamic linking.
+
+Native-code compiler:
+- Added link-time check for multiply-defined module names.
+- Fixed GC bug related to constant constructors of polymorphic variant types.
+- Fixed compilation bug for top-level "include" statements.
+- PowerPC port: work around limited range for relative branches,
+ thus removing assembler failures on large functions.
+- IA64 port: fixed code generation bug for 3-way constructor matching.
+
+Toplevel interactive system:
+- Can load object files given on command line before starting up.
+- ocamlmktop: minimized possibility of name clashes with user-provided modules.
+
+Run-time system:
+- Minor garbage collector no longer recursive.
+- Better support for lazy data in the garbage collector.
+- Fixed issues with the heap compactor.
+- Fixed issues with finalized Caml values.
+- The type "int64" is now supported on all platforms: we use software
+ emulation if the C compiler doesn't support 64-bit integers.
+- Support for float formats that are neither big-endian nor little-endian
+ (one known example: the ARM).
+- Fixed bug in callback*_exn functions in the exception-catching case.
+- Work around gcc 2.96 bug on RedHat 7.2 and Mandrake 8.0, 8.1 among others.
+- Stub DLLs now installed in subdir stublibs/ of standard library dir.
+
+Standard library:
+- Protect against integer overflow in sub-string and sub-array bound checks.
+- New module Complex implementing arithmetic over complex numbers.
+- New module Scanf implementing format-based scanning a la scanf() in C.
+- Module Arg: added alternate entry point Arg.parse_argv.
+- Modules Char, Int32, Int64, Nativeint, String: added type "t" and function
+ "compare" so that these modules can be used directly with e.g. Set.Make.
+- Module Digest: fixed issue with Digest.file on large files (>= 1Gb);
+ added Digest.to_hex.
+- Module Filename: added Filename.open_temp_file to atomically create and
+ open the temp file; improved security of Filename.temp_file.
+- Module Genlex: allow _ as first character of an identifier.
+- Module Lazy: more efficient implementation.
+- Module Lexing: improved performances for very large tokens.
+- Module List: faster implementation of sorting functions.
+- Module Printf:
+ added %S and %C formats (quoted, escaped strings and characters);
+ added kprintf (calls user-specified continuation on formatted string).
+- Module Queue: faster implementation (courtesy of Francois Pottier).
+- Module Random: added Random.bool.
+- Module Stack: added Stack.is_empty.
+- Module Pervasives:
+ added sub-module LargeFile to support files larger than 1Gb
+ (file offsets are int64 rather than int);
+ opening in "append" mode automatically sets "write" mode;
+ files are now opened in close-on-exec mode;
+ string_of_float distinguishes its output from a plain integer;
+ faster implementation of input_line for long lines.
+- Module Sys:
+ added Sys.ocaml_version containing the OCaml version number;
+ added Sys.executable_name containing the (exact) path of the
+ file being executable;
+ Sys.argv.(0) is now unchanged w.r.t. what was provided as 0-th argument
+ by the shell.
+- Module Weak: added weak hash tables.
+
+Other libraries:
+- Bigarray:
+ support for bigarrays of complex numbers;
+ added functions Genarray.dims,
+ {Genarray,Array1,Array2,Array3}.{kind,layout}.
+- Dynlink: fixed bug with loading of mixed-mode Caml/C libraries.
+- LablTK:
+ now supports also the CamlTK API (no labels);
+ support for Activate and Deactivate events;
+ support for virtual events;
+ added UTF conversion;
+ export the tcl interpreter as caml value, to avoid DLL dependencies.
+- Unix:
+ added sub-module LargeFile to support files larger than 1Gb
+ (file offsets are int64 rather than int);
+ added POSIX opening flags (O_NOCTTY, O_*SYNC);
+ use reentrant functions for gethostbyname and gethostbyaddr when available;
+ fixed bug in Unix.close_process and Unix.close_process_full;
+ removed some overhead in Unix.select.
+
+Tools:
+- ocamldoc (the documentation generator) is now part of the distribution.
+- Debugger: now supports the option -I +dir.
+- ocamllex: supports the same identifiers as ocamlc; warns for
+ bad \ escapes in strings and characters.
+- ocamlbrowser:
+ recenter the module boxes when showing a cross-reference;
+ include the current directory in the ocaml path.
+
+Windows port:
+- Can now compile with Mingw (the GNU compilers without the Cygwin
+ runtime library) in addition to MSVC.
+- Toplevel GUI: wrong filenames were given to #use and #load commands;
+ read_line() was buggy for short lines (2 characters or less).
+- OCamlBrowser: now fully functional.
+- Graphics library: fixed several bugs in event handling.
+- Threads library: fixed preemption bug.
+- Unix library: better handling of the underlying differences between
+ sockets and regular file descriptors;
+ added Unix.lockf and a better Unix.rename (thanks to Tracy Camp).
+- LablTk library: fixed a bug in Fileinput
+
+
+Objective Caml 3.04 (13 Dec 2001):
+----------------------------------
+
+Type-checker:
+- Allowed coercing self to the type of the current class, avoiding
+ an obscure error message about "Self type cannot be unified..."
+
+Both compilers:
+- Use OCAMLLIB environment variable to find standard library, falls
+ back on CAMLLIB if not defined.
+- Report out-of-range ASCII escapes in character or string literals
+ such as "\256".
+
+Byte-code compiler:
+- The -use-runtime and -make-runtime flags are back by popular demand
+ (same behavior as in 3.02).
+- Dynamic loading (of the C part of mixed Caml/C libraries): arrange that
+ linking in -custom mode uses the static libraries for the C parts,
+ not the shared libraries, for maximal robustness and compatibility with
+ 3.02.
+
+Native-code compiler:
+- Fixed bug in link-time consistency checking.
+
+Tools:
+- ocamlyacc: added parser debugging support (set OCAMLRUNPARAM=p to get
+ a trace of the pushdown automaton actions).
+- ocamlcp: was broken in 3.03 (Sys_error), fixed.
+
+Run-time system:
+- More work on dynamic loading of the C part of mixed Caml/C libraries.
+- On uncaught exception, flush output channels before printing exception
+ message and backtrace.
+- Corrected several errors in exception backtraces.
+
+Standard library:
+- Pervasives: integer division and modulus are now fully specified
+ on negative arguments (with round-towards-zero semantics).
+- Pervasives.float_of_string: now raises Failure on ill-formed input.
+- Pervasives: added useful float constants max_float, min_float, epsilon_float.
+- printf functions in Printf and Format: added % formats for int32, nativeint,
+ int64; "*" in width and precision specifications now supported
+ (contributed by Thorsten Ohl).
+- Added Hashtbl.copy, Stack.copy.
+- Hashtbl: revised resizing strategy to avoid quadratic behavior
+ on Hashtbl.add.
+- New module MoreLabels providing labelized versions of modules
+ Hashtbl, Map and Set.
+- Pervasives.output_value and Marshal.to_* : improved hashing strategy
+ for internal data structures, avoid excessive slowness on
+ quasi-linearly-allocated inputs.
+
+Other libraries:
+- Num: fixed bug in big integer exponentiation (Big_int.power_*).
+
+Windows port:
+- New GUI for interactive toplevel (Jacob Navia).
+- The Graphics library is now available for stand-alone executables
+ (Jacob Navia).
+- Unix library: improved reporting of system error codes.
+- Fixed error in "globbing" of * and ? patterns on command line.
+
+Emacs mode: small fixes; special color highlighting for ocamldoc comments.
+
+License: added special exception to the LGPL'ed code (libraries and
+ runtime system) allowing unrestricted linking, whether static or dynamic.
+
+
+Objective Caml 3.03 ALPHA (12 Oct 2001):
+----------------------------------------
+
+Language:
+- Removed built-in syntactic sugar for streams and stream patterns
+ [< ... >], now supported via CamlP4, which is now included in the
+ distribution.
+- Switched the default behaviour to labels mode (labels are compulsory),
+ but allows omitting labels when a function application is complete.
+ -nolabels mode is available but deprecated for programming.
+ (See also scrapelabels and addlabels tools below.)
+- Removed all labels in the standard libraries, except labltk.
+ Labelized versions are kept for ArrayLabels, ListLabels, StringLabels
+ and UnixLabels. "open StdLabels" gives access to the first three.
+- Extended polymorphic variant type syntax, allowing union types and
+ row abbreviations for both sub- and super-types. #t deprecated in types.
+- See the Upgrading file for how to adapt to all the changes above.
+
+Type-checker:
+- Fixed obscure bug in module typing causing the type-checker to loop
+ on signatures of the form
+ module type M
+ module A: sig module type T = sig module T: M end end
+ module B: A.T
+- Improved efficiency of module type-checking via lazy computation of
+ certain signature summary information.
+- An empty polymorphic variant type is now an error.
+
+Both compilers:
+- Fixed wrong code generated for "struct include M ... end" when M
+ contains one or several "external" declarations.
+
+Byte-code compiler:
+- Protect against VM stack overflow caused by module initialization code
+ with many local variables.
+- Support for dynamic loading of the C part of mixed Caml/C libraries.
+- Removed the -use-runtime and -make-runtime flags, obsoleted by dynamic
+ loading of C libraries.
+
+Native-code compiler:
+- Attempt to recover gracefully from system stack overflow. Currently
+ works on x86 under Linux and BSD.
+- Alpha: work around "as" bug in Tru64 5.1.
+
+Toplevel environment:
+- Revised printing of inferred types and evaluation results
+ so that an external printer (e.g. Camlp4's) can be hooked in.
+
+Tools:
+- The CamlP4 pre-processor-pretty-printer is now included in the standard
+ distribution.
+- New tool ocamlmklib to help build mixed Caml/C libraries.
+- New tool scrapelabels and addlabels, to either remove (non-optional)
+ labels in interfaces, or automatically add them in the definitions.
+ They provide easy transition from classic mode ocaml 3.02 sources,
+ depending on whether you want to keep labels or not.
+- ocamldep: added -pp option to handle preprocessed source files.
+
+Run-time system:
+- Support for dynamic loading of the C part of mixed Caml/C libraries.
+ Currently works under Linux, FreeBSD, Windows, Tru64, Solaris and Irix.
+- Implemented registration of global C roots with a skip list,
+ runs much faster when there are many global C roots.
+- Autoconfiguration script: fixed wrong detection of Mac OS X; problem
+ with the Sparc, gcc 3.0, and float alignment fixed.
+
+Standard library:
+- Added Pervasives.flush_all to flush all opened output channels.
+
+Other libraries:
+- All libraries revised to allow dynamic loading of the C part.
+- Graphics under X Windows: revised event handling, should no longer lose
+ mouse events between two calls to wait_next_event(); wait_next_event()
+ now interruptible by signals.
+- Bigarrays: fixed bug in marshaling of big arrays.
+
+Windows port:
+- Fixed broken Unix.{get,set}sockopt*
+
+
+
+Objective Caml 3.02 (30 Jul 2001):
+----------------------------------
+
+Both compilers:
+- Fixed embarrassing bug in pattern-matching compilation
+ (affected or-patterns containing variable bindings).
+- More optimizations in pattern-matching compilation.
+
+Byte-code compiler:
+- Protect against VM stack overflow caused by functions with many local
+ variables.
+
+Native-code compiler:
+- Removed re-sharing of string literals, causes too many surprises with
+ in-place string modifications.
+- Corrected wrong compilation of toplevel "include" statements.
+- Fixed bug in runtime function "callbackN_exn".
+- Signal handlers receive the conventional signal number as argument
+ instead of the system signal number (same behavior as with the
+ bytecode compiler).
+- ARM port: fixed issue with immediate operand overflow in large functions.
+
+Toplevel environment:
+- User-definer printers (for #install_printer) now receive as first argument
+ the pretty-printer formatter where to print their second argument.
+ Old printers (with only one argument) still supported for backward
+ compatibility.
+
+Standard library:
+- Module Hashtbl: added Hashtbl.fold.
+
+Other libraries:
+- Dynlink: better error reporting in add_interfaces for missing .cmi files.
+- Graphics: added more drawing functions (multiple points, polygons,
+ multiple lines, splines).
+- Bytecode threads: the module Unix is now thread-safe, ThreadUnix is
+ deprecated. Unix.exec* now resets standard descriptors to blocking mode.
+- Native threads: fixed a context-switch-during-GC problem causing
+ certain C runtime functions to fail, most notably input_value.
+- Unix.inet_addr_of_string: call inet_aton() when available so as to
+ handle correctly the address 255.255.255.255.
+- Unix: added more getsockopt and setsockopt functions to get/set
+ options that have values other than booleans.
+- Num: added documentation for the Big_int module.
+
+Tools:
+- ocamldep: fixed wrong dependency issue with nested modules.
+
+Run-time system:
+- Removed floating-point error at start-up on some non-IEEE platforms
+ (e.g. FreeBSD prior to 4.0R).
+- Stack backtrace mechanism now works for threads that terminate on
+ an uncaught exception.
+
+Auto-configuration:
+- Updated config.guess and config.sub scripts, should recognize a greater
+ number of recent platform.
+
+Windows port:
+- Fixed broken Unix.waitpid. Unix.file_descr can now be compared or hashed.
+- Toplevel application: issue with spaces in name of stdlib directory fixed.
+
+MacOS 9 port:
+- Removed the last traces of support for 68k
+
+
+Objective Caml 3.01 (09 Mar 2001):
+----------------------------------
+
+New language features:
+- Variables are allowed in "or" patterns, e.g.
+ match l with [t] | [_;t] -> ... t ...
+- "include <structure expression>" to re-export all components of a
+ structure inside another structure.
+- Variance annotation on parameters of type declarations, e.g.
+ type (+'a,-'b,'c) t (covariant in 'a, contravariant in 'b, invariant in 'c)
+
+New ports:
+- Intel IA64/Itanium under Linux (including the native-code compiler).
+- Cygwin under MS Windows. This port is an alternative to the earlier
+ Windows port of OCaml, which relied on MS compilers; the Cygwin
+ Windows port does not need MS Visual C++ nor MASM, runs faster
+ in bytecode, and has a better implementation of the Unix library,
+ but currently lacks threads and COM component support.
+
+Type-checking:
+- Relaxed "monomorphic restriction" on type constructors in a
+ mutually-recursive type definition, e.g. the following is again allowed
+ type u = C of int t | D of string t and 'a t = ...
+- Fixed name-capture bug in "include SIG" and "SIG with ..." constructs.
+- Improved implicit subtypes built by (... :> ty), closer to intuition.
+- Several bug fixes in type-checking of variants.
+- Typing of polymorphic variants is more restrictive:
+ do not allow conjunctive types inside the same pattern matching.
+ a type has either an upper bound, or all its tags are in the lower bound.
+ This may break some programs (this breaks lablgl-0.94).
+
+Both compilers:
+- Revised compilation of pattern matching.
+- Option -I +<subdir> to search a subdirectory <subdir> of the standard
+ library directory (i.e. write "ocamlc -I +labltk" instead of
+ "ocamlc -I /usr/local/lib/ocaml/labltk").
+- Option -warn-error to turn warnings into errors.
+- Option -where to print the location of the standard library directory.
+- Assertions are now type-checked even if the -noassert option is given,
+ thus -noassert can no longe change the types of modules.
+
+Bytecode compiler and bytecode interpreter:
+- Print stack backtrace when a program aborts due to an uncaught exception
+ (requires compilation with -g and running with ocamlrun -b or
+ OCAMLRUNPARAM="b=1").
+
+Native-code compiler:
+- Better unboxing optimizations on the int32, int64, and nativeint types.
+- Tail recursion preserved for functions having more parameters than
+ available registers (but tail calls to other functions are still
+ turned off if parameters do not fit entirely in registers).
+- Fixed name-capture bug in function inlining.
+- Improved spilling/reloading strategy for conditionals.
+- IA32, Alpha: better alignment of branch targets.
+- Removed spurious dependency on the -lcurses library.
+
+Toplevel environment:
+- Revised handling of top-level value definitions, allows reclaimation
+ of definitions that are shadowed by later definitions with the same names.
+ (E.g. "let x = <big list>;; let x = 1;;" allows <big list> to be reclaimed.)
+- Revised the tracing facility so that for standard library functions,
+ only calls from user code are traced, not calls from the system.
+- Added a "*" prompt when within a comment.
+
+Runtime system:
+- Fixed portability issue on bcopy() vs memmove(), affecting Linux RedHat 7.0
+ in particular.
+- Structural comparisons (=, <>, <, <=, >, >=, compare) reimplemented
+ so as to avoid overflowing the C stack.
+- Input/output functions: arrange so that reads and writes on closed
+ in_channel or out_channel raise Sys_error immediately.
+
+Standard library:
+- Module Gc: changed some counters to float in order to avoid overflow;
+ added alarms
+- Module Hashtbl: added Hashtbl.replace.
+- Module Int64: added bits_of_float, float_of_bits (access to IEEE 754
+ representation of floats).
+- Module List: List.partition now tail-rec;
+ improved memory behavior of List.stable_sort.
+- Module Nativeint: added Nativeint.size (number of bits in a nativeint).
+- Module Obj: fixed incorrect resizing of float arrays in Obj.resize.
+- Module Pervasives: added float constants "infinity", "neg_infinity", "nan";
+ added a "classify_float" function to test a float for NaN, infinity, etc.
+- Pervasives.input_value: fixed bug affecting shared custom objects.
+- Pervasives.output_value: fixed size bug affecting "int64" values.
+- Pervasives.int_of_string, {Int32,Int64,Nativeint}.of_string:
+ fixed bug causing bad digits to be accepted without error.
+- Module Random: added get_state and set_state to checkpoint the generator.
+- Module Sys: signal handling functions are passed the system-independent
+ signal number rather than the raw system signal number whenever possible.
+- Module Weak: added Weak.get_copy.
+
+Other libraries:
+- Bigarray: added Bigarray.reshape to take a view of the elements of a
+ bigarray with different dimensions or number of dimensions;
+ fixed bug causing "get" operations to be unavailable in custom
+ toplevels including Bigarray.
+- Dynlink: raise an error instead of crashing when the loaded module
+ refers to the not-yet-initialized module performing a dynlink operation.
+- Bytecode threads: added a thread-safe version of the Marshal module;
+ fixed a rare GC bug in the thread scheduler.
+- POSIX threads: fixed compilation problem with threads.cmxa.
+- Both thread libraries: better tail-recursion in Event.sync.
+- Num library: fixed bug in square roots (Nat.sqrt_nat, Big_int.sqrt_big_int).
+
+Tools:
+- ocamldep: fixed missing dependencies on labels of record patterns and
+ record construction operations
+
+Win32 port:
+- Unix.waitpid now implements the WNOHANG option.
+
+Mac OS ports:
+- Mac OS X public beta is supported.
+- Int64.format works on Mac OS 8/9.
+
+
+Objective Caml 3.00 (25 Apr 2000):
+----------------------------------
+
+Language:
+- OCaml/OLabl merger:
+ * Support for labeled and optional arguments for functions and classes.
+ * Support for variant types (sum types compared by structure).
+ See tutorial (chapter 2 of the OCaml manual) for more information.
+- Syntactic change: "?" in stream error handlers changed to "??".
+- Added exception renaming in structures (exception E = F).
+- (OCaml 2.99/OLabl users only) Label syntax changed to preserve
+ backward compatibility with 2.0x (labeled function application
+ is f ~lbl:arg instead of f lbl:arg). A tool is provided to help
+ convert labelized programs to OCaml 3.00.
+
+Both compilers:
+- Option -labels to select commuting label mode (labels are mandatory,
+ but labeled arguments can be passed in a different order than in
+ the definition of the function; in default mode, labels may be omitted,
+ but argument reordering is only allowed for optional arguments).
+- Libraries (.cma and .cmxa files) now "remember" C libraries given
+ at library construction time, and add them back at link time.
+ Allows linking with e.g. just unix.cma instead of
+ unix.cma -custom -cclib -lunix
+- Revised printing of error messages, now use Format.fprintf; no visible
+ difference for users, but could facilitate internationalization later.
+- Fixed bug in unboxing of records containing only floats.
+- Fixed typing bug involving applicative functors as components of modules.
+- Better error message for inconsistencies between compiled interfaces.
+
+Bytecode compiler:
+- New "modular" format for bytecode executables; no visible differences
+ for users, but will facilitate further extensions later.
+- Fixed problems in signal handling.
+
+Native-code compiler:
+- Profiling support on x86 under FreeBSD
+- Open-coding and unboxing optimizations for the new integer types
+ int32, int64, nativeint, and for bigarrays.
+- Fixed instruction selection bug with "raise" appearing in arguments
+ of strict operators, e.g. "1 + raise E".
+- Better error message when linking incomplete/incorrectly ordered set
+ of .cmx files.
+- Optimized scanning of global roots during GC, can reduce total running
+ time by up to 8% on GC-intensive programs.
+
+Interactive toplevel:
+- Better printing of exceptions, including arguments, when possible.
+- Fixed rare GC bug occurring during interpretation of scripts.
+- Added consistency checks between interfaces and implementations
+ during #load.
+
+Run-time system:
+- Added support for "custom" heap blocks (heap blocks carrying
+ C functions for finalization, comparison, hashing, serialization
+ and deserialization).
+- Support for finalisation functions written in Caml.
+
+Standard library:
+- New modules Int32, Int64, Nativeint for 32-bit, 64-bit and
+ platform-native integers
+- Module Array: added Array.sort, Array.stable_sort.
+- Module Gc: added Gc.finalise to attach Caml finalisation functions to
+ arbitrary heap-allocated data.
+- Module Hashtbl: do not bomb when resizing very large table.
+- Module Lazy: raise Lazy.Undefined when a lazy evaluation needs itself.
+- Module List: added List.sort, List.stable_sort; fixed bug in List.rev_map2.
+- Module Map: added mapi (iteration with key and data).
+- Module Set: added iterators for_all, exists, filter, partition.
+- Module Sort: still here but deprecated in favor of new sorting functions
+ in Array and List.
+- Module Stack: added Stack.top
+- Module String: fixed boundary condition on String.rindex_from
+- Added labels on function arguments where appropriate.
+
+New libraries and tools:
+- ocamlbrowser: graphical browser for OCaml sources and compiled interfaces,
+ supports cross-referencing, editing, running the toplevel.
+- LablTK: GUI toolkit based on TK, using labeled and optional arguments,
+ easier to use than CamlTK.
+- Bigarray: large, multi-dimensional numerical arrays, facilitate
+ interfacing with C/Fortran numerical code, efficient support for
+ advanced array operations such as slicing and memory-mapping of files.
+
+Other libraries:
+- Bytecode threads: timer-based preemption was broken, works back again;
+ fixed bug in Pervasives.input_line; exported Thread.yield.
+- System threads: several GC / reentrancy bugs fixed in buffered I/O
+ and Unix I/O; revised Thread.join implementation for strict POSIX
+ conformance; exported Thread.yield.
+- Graphics: added support for double buffering; added, current_x, current_y,
+ rmoveto, rlineto, and draw_rect.
+- Num: fixed bug in Num.float_of_num.
+- Str: worked around potential symbol conflicts with C standard library.
+- Dbm: fixed bug with Dbm.iter on empty database.
+
+New or updated ports:
+- Alpha/Digital Unix: lifted 256M limitation on total memory space
+ induced by -taso
+- Port to AIX 4.3 on PowerPC
+- Port to HPUX 10 on HPPA
+- Deprecated 680x0 / SunOS port
+
+Macintosh port:
+- Implemented the Unix and Thread libraries.
+- The toplevel application does not work on 68k Macintoshes; maybe
+ later if there's a demand.
+- Added a new tool, ocamlmkappli, to build an application from a
+ program written in O'Caml.
+
+
+Objective Caml 2.04 (26 Nov 1999):
+----------------------------------
+
+- C interface: corrected inconsistent change in the CAMLparam* macros.
+- Fixed internal error in ocamlc -g.
+- Fixed type-checking of "S with ...", where S is a module type name
+ abbreviating another module type name.
+- ocamldep: fixed stdout/stderr mismatch after failing on one file.
+- Random.self_init more random.
+- Windows port:
+ - Toplevel application: fixed spurious crash on exit.
+ - Native-code compiler: fixed bug in assembling certain
+ floating-point constants (masm doesn't grok 2e5, wants 2.0e5).
+
+Objective Caml 2.03 (19 Nov 1999):
+----------------------------------
+
+New ports:
+- Ported to BeOS / Intel x86 (bytecode and native-code).
+- BSD / Intel x86 port now supports both a.out and ELF binary formats.
+- Added support for {Net,Open}BSD / Alpha.
+- Revamped Rhapsody port, now works on MacOS X server.
+
+Syntax:
+- Warning for "(*)" and "*)" outside comment.
+- Removed "#line LINENO", too ambiguous with a method invocation;
+ the equivalent "# LINENO" is still supported.
+
+Typing:
+- When an incomplete pattern-matching is detected, report also a
+ value or value template that is not covered by the cases of
+ the pattern-matching.
+- Several bugs in class type matching and in type error reporting fixed.
+- Added an option -rectypes to support general recursive types,
+ not just those involving object types.
+
+Bytecode compiler:
+- Minor cleanups in the bytecode emitter.
+- Do not remove "let x = y" bindings in -g mode; makes it easier to
+ debug the code.
+
+Native-code compiler:
+- Fixed bug in grouping of allocations performed in the same basic block.
+- Fixed bug in constant propagation involving expressions containing
+ side-effects.
+- Fixed incorrect code generation for "for" loops whose upper bound is
+ a reference assigned inside the loop.
+- MIPS code generator: work around a bug in the IRIX 6 assembler.
+
+Toplevel:
+- Fixed incorrect redirection of standard formatter to stderr
+ while executing toplevel scripts.
+
+Standard library:
+- Added List.rev_map, List.rev_map2.
+- Documentation of List functions now says which functions are
+ tail-rec, and how much stack space is needed for non-tailrec functions.
+- Wrong type for Printf.bprintf fixed.
+- Fixed weird behavior of Printf.sprintf and Printf.bprintf in case of
+ partial applications.
+- Added Random.self_init, which initializes the PRNG from the system date.
+- Sort.array: serious bugs fixed.
+- Stream.count: fixed incorrect behavior with ocamlopt.
+
+Run-time system and external interface:
+- Fixed weird behavior of signal handlers w.r.t. signal masks and exceptions
+ raised from the signal handler.
+- Fixed bug in the callback*_exn() functions.
+
+Debugger:
+- Fixed wrong printing of float record fields and elements of float arrays.
+- Supports identifiers starting with '_'.
+
+Profiler:
+- Handles .mli files, so ocamlcp can be used to replace ocamlc (e.g. in a
+ makefile).
+- Now works on programs that use stream expressions and stream parsers.
+
+Other libraries:
+- Graphics: under X11, treat all mouse buttons equally; fixed problem
+ with current font reverting to the default font when the graphics
+ window is resized.
+- Str: fixed reentrancy bugs in Str.replace and Str.full_split.
+- Bytecode threads: set standard I/O descriptors to non-blocking mode.
+- OS threads: revised implementation of Thread.wait_signal.
+- All threads: added Event.wrap_abort, Event.choose [].
+- Unix.localtime, Unix.gmtime: check for errors.
+- Unix.create_process: now supports arbitrary redirections of std descriptors.
+- Added Unix.open_process_full.
+- Implemented Unix.chmod under Windows.
+- Big_int.square_big_int now gives the proper sign to its result.
+
+Others:
+- ocamldep: don't stop at first error, skip to next file.
+- Emacs mode: updated with Garrigue and Zimmerman's snapshot of 1999/10/18.
+- configure script: added -prefix option.
+- Windows toplevel application: fixed problem with graphics library
+ not loading properly.
+
+
+Objective Caml 2.02 (04 Mar 1999):
+----------------------------------
+
+* Type system:
+ - Check that all components of a signature have unique names.
+ - Fixed bug in signature matching involving a type component and
+ a module component, both sharing an abstract type.
+ - Bug involving recursive classes constrained by a class type fixed.
+ - Fixed bugs in printing class types and in printing unification errors.
+
+* Compilation:
+ - Changed compilation scheme for "{r with lbl = e}" when r has many fields
+ so as to avoid code size explosion.
+
+* Native-code compiler:
+ - Better constant propagation in boolean expressions and in conditionals.
+ - Removal of unused arguments during function inlining.
+ - Eliminated redundant tagging/untagging in bit shifts.
+ - Static allocation of closures for functions without free variables,
+ reduces the size of initialization code.
+ - Revised compilation scheme for definitions at top level of compilation
+ units, so that top level functions have no free variables.
+ - Coalesced multiple allocations of heap blocks inside one expression
+ (e.g. x :: y :: z allocates the two conses in one step).
+ - Ix86: better handling of large integer constants in instruction selection.
+ - MIPS: fixed wrong asm generated for String.length "literal".
+
+* Standard library:
+ - Added the "ignore" primitive function, which just throws away its
+ argument and returns "()". It allows to write
+ "ignore(f x); y" if "f x" doesn't have type unit and you don't
+ want the warning caused by "f x; y".
+ - Added the "Buffer" module (extensible string buffers).
+ - Module Format: added formatting to buffers and to strings.
+ - Added "mem" functions (membership test) to Hashtbl and Map.
+ - Module List: added find, filter, partition.
+ Renamed remove and removeq to remove_assoc and remove_assq.
+ - Module Marshal: fixed bug in marshaling functions when passed functional
+ values defined by mutual recursion with other functions.
+ - Module Printf: added Printf.bprintf (print to extensible buffer);
+ added %i format as synonymous for %d (as per the docs).
+ - Module Sort: added Sort.array (Quicksort).
+
+* Runtime system:
+ - New callback functions for callbacks with arbitrary many arguments
+ and for catching Caml exceptions escaping from a callback.
+
+* The ocamldep dependency generator: now performs full parsing of the
+ sources, taking into account the scope of module bindings.
+
+* The ocamlyacc parser generator: fixed sentinel error causing wrong
+ tables to be generated in some cases.
+
+* The str library:
+ - Added split_delim, full_split as variants of split that control
+ more precisely what happens to delimiters.
+ - Added replace_matched for separate matching and replacement operations.
+
+* The graphics library:
+ - Bypass color lookup for 16 bpp and 32 bpp direct-color displays.
+ - Larger color cache.
+
+* The thread library:
+ - Bytecode threads: more clever use of non-blocking I/O, makes I/O
+ operations faster.
+ - POSIX threads: gcc-ism removed, should now compile on any ANSI C compiler.
+ - Both: avoid memory leak in the Event module when a communication
+ offer is never selected.
+
+* The Unix library:
+ - Fixed inversion of ctime and mtime in Unix.stat, Unix.fstat, Unix.lstat.
+ - Unix.establish_connection: properly reclaim socket if connect fails.
+
+* The DBM library: no longer crashes when calling Dbm.close twice.
+
+* Emacs mode:
+ - Updated with Garrigue and Zimmerman's latest version.
+ - Now include an "ocamltags" script for using etags on OCaml sources.
+
+* Win32 port:
+ - Fixed end-of-line bug in ocamlcp causing problems with generated sources.
+
+
+Objective Caml 2.01 (09 Dec 1998):
+----------------------------------
+
+* Typing:
+ - Added warning for expressions of the form "a; b" where a does not have
+ type "unit"; catches silly mistake such as
+ "record.lbl = newval; ..." instead of "record.lbl <- newval; ...".
+ - Typing bug in "let module" fixed.
+
+* Compilation:
+ - Fixed bug in compilation of recursive and mutually recursive classes.
+ - Option -w to turn specific warnings on/off.
+ - Option -cc to choose the C compiler used with ocamlc -custom and ocamlopt.
+
+* Bytecode compiler and bytecode interpreter:
+ - Intel x86: removed asm declaration causing "fixed or forbidden register
+ spilled" error with egcs and gcc 2.8 (but not with gcc 2.7, go figure).
+ - Revised handling of debugging information, allows faster linking with -g.
+
+* Native-code compiler:
+ - Fixed bugs in integer constant propagation.
+ - Out-of-bound accesses in array and strings now raise an Invalid_argument
+ exception (like the bytecode system) instead of stopping the program.
+ - Corrected scheduling of bound checks.
+ - Port to the StrongARM under Linux (e.g. Corel Netwinder).
+ - I386: fixed bug in profiled code (ocamlopt -p).
+ - Mips: switched to -n32 model under IRIX; dropped the Ultrix port.
+ - Sparc: simplified the addressing modes, allows for better scheduling.
+ - Fixed calling convention bug for Pervasives.modf.
+
+* Toplevel:
+ - #trace works again.
+ - ocamlmktop: use matching ocamlc, not any ocamlc from the search path.
+
+* Memory management:
+ - Fixed bug in heap expansion that could cause the GC to loop.
+
+* C interface:
+ - New macros CAMLparam... and CAMLlocal... to simplify the handling
+ of local roots in C code.
+ - Simplified procedure for allocating and filling Caml blocks from C.
+ - Declaration of string_length in <caml/mlvalues.h>.
+
+* Standard library:
+ - Module Format: added {get,set}_all_formatter_output_functions,
+ formatter_of_out_channel, and the control sequence @<n> in printf.
+ - Module List: added mem_assoc, mem_assq, remove, removeq.
+ - Module Pervasives: added float_of_int (synonymous for float),
+ int_of_float (truncate), int_of_char (Char.code), char_of_int (Char.chr),
+ bool_of_string.
+ - Module String: added contains, contains_from, rcontains_from.
+
+* Unix library:
+ - Unix.lockf: added F_RLOCK, F_TRLOCK; use POSIX locks whenever available.
+ - Unix.tc{get,set}attr: added non-standard speeds 57600, 115200, 230400.
+ - Unix.chroot: added.
+
+* Threads:
+ - Bytecode threads: improved speed of I/O scheduling.
+ - Native threads: fixed a bug involving signals and exceptions
+ generated from C.
+
+* The "str" library:
+ - Added Str.string_partial_match.
+ - Bumped size of internal stack.
+
+* ocamlyacc: emit correct '# lineno' directive for prelude part of .mly file.
+
+* Emacs editing mode: updated with Jacques Garrigue's newest code.
+
+* Windows port:
+ - Added support for the "-cclib -lfoo" option (instead of
+ -cclib /full/path/libfoo.lib as before).
+ - Threads: fixed a bug at initialization time.
+
+* Macintosh port: source code for Macintosh application merged in.
+
+
+Objective Caml 2.00 (19 Aug 1998):
+----------------------------------
+
+* Language:
+ - New class language. See http://caml.inria.fr/ocaml/refman/
+ for a tutorial (chapter 2) and for the reference manual (section 4.9).
+ - Local module definitions "let module X = <module-expr> in <expr>".
+ - Record copying with update "{r with lbl1 = expr1; ...}".
+ - Array patterns "[|pat1; ...;patN|]" in pattern-matchings.
+ - New reserved keywords: "object", "initializer".
+ - No longer reserved: "closed", "protected".
+
+* Bytecode compiler:
+ - Use the same compact memory representations for float arrays, float
+ records and recursive closures as the native-code compiler.
+ - More type-dependent optimizations.
+ - Added the -use_runtime and -make_runtime flags to build separately
+ and reuse afterwards custom runtime systems
+ (inspired by Fabrice Le Fessant's patch).
+
+* Native-code compiler:
+ - Cross-module constant propagation of integer constants.
+ - More type-dependent optimizations.
+ - More compact code generated for "let rec" over data structures.
+ - Better code generated for "for" loops (test at bottom of code).
+ - More aggressive scheduling of stores.
+ - Added -p option for time profiling with gprof
+ (fully supported on Intel x86/Linux and Alpha/Digital Unix only)
+ (inspired by Aleksey Nogin's patch).
+ - A case of bad spilling with high register pressure fixed.
+ - Fixed GC bug when GC called from C without active Caml code.
+ - Alpha: $gp handling revised to follow Alpha's standard conventions,
+ allow running "atom" and "pixie" on ocamlopt-generated binaries.
+ - Intel x86: use movzbl and movsbl systematically to load 8-bit and 16-bit
+ quantities, no more hacks with partial registers (better for the
+ Pentium Pro, worse for the Pentium).
+ - PowerPC: more aggressive scheduling of return address reloading.
+ - Sparc: scheduling bug related to register pairs fixed.
+
+* Runtime system:
+ - Better printing of uncaught exceptions (print a fully qualified
+ name whenever possible).
+
+* New ports:
+ - Cray T3E (bytecode only) (in collaboration with CEA).
+ - PowerMac under Rhapsody.
+ - SparcStations under Linux.
+
+* Standard library:
+ - Added set_binary_mode_in and set_binary_mode_out in Pervasives
+ to toggle open channels between text and binary modes.
+ - output_value and input_value check that the given channel is in
+ binary mode.
+ - input_value no longer fails on very large marshalled data (> 16 Mbytes).
+ - Module Arg: added option Rest.
+ - Module Filename: temp_file no longer loops if temp dir doesn't exist.
+ - Module List: added rev_append (tail-rec alternative to @).
+ - Module Set: tell the truth about "elements" returning a sorted list;
+ added min_elt, max_elt, singleton.
+ - Module Sys: added Sys.time for simple measuring of CPU time.
+
+* ocamllex:
+ - Check for overflow when generating the tables for the automaton.
+ - Error messages in generated .ml file now point to .mll source.
+ - Added "let <id> = <regexp>" to name regular expressions
+ (inspired by Christian Lindig's patch).
+
+* ocamlyacc:
+ - Better error recovery in presence of EOF tokens.
+ - Error messages in generated .ml file now point to .mly source.
+ - Generated .ml file now type-safe even without the generated .mli file.
+
+* The Unix library:
+ - Use float instead of int to represent Unix times (number of seconds
+ from the epoch). This fixes a year 2005 problem on 32-bit platforms.
+ Functions affected: stat, lstat, fstat, time, gmtime, localtime,
+ mktime, utimes.
+ - Added putenv.
+ - Better handling of "unknown" error codes (EUNKNOWNERR).
+ - Fixed endianness bug in getservbyport.
+ - win32unix (the Win32 implementation of the Unix library) now has
+ the same interface as the unix implementation, this allows exchange
+ of compiled .cmo and .cmi files between Unix and Win32.
+
+* The thread libraries:
+ - Bytecode threads: bug with escaping exceptions fixed.
+ - System threads (POSIX, Win32): malloc/free bug fixed; signal bug fixed.
+ - Both: added Thread.wait_signal to wait synchronously for signals.
+
+* The graph library: bigger color cache.
+
+* The str library: added Str.quote, Str.regexp_string,
+ Str.regexp_string_case_fold.
+
+* Emacs mode:
+ - Fixed bug with paragraph fill.
+ - Fixed bug with next-error under Emacs 20.
+
+
+Objective Caml 1.07 (11 Dec 1997):
+----------------------------------
+
+* Native-code compiler:
+ - Revised interface between generated code and GC, fixes serious GC
+ problems with signals and native threads.
+ - Added "-thread" option for compatibility with ocamlc.
+
+* Debugger: correctly print instance variables of objects.
+
+* Run-time system: ported to OpenBSD.
+
+* Standard library: fixed wrong interface for Marshal.to_buffer and
+ Obj.unmarshal.
+
+* Num library: added Intel x86 optimized asm code (courtesy of
+ Bernard Serpette).
+
+* Thread libraries:
+ - Native threads: fixed GC bugs and installation procedure.
+ - Bytecode threads: fixed problem with "Marshal" module.
+ - Both: added Event.always.
+
+* MS Windows port: better handling of long command lines in Sys.command
+
+Objective Caml 1.06 (18 Nov 1997):
+----------------------------------
+
+* Language:
+ - Added two new keywords: "assert" (check assertion) and "lazy"
+ (delay evaluation).
+ - Allow identifiers to start with "_" (such identifiers are treated
+ as lowercase idents).
+
+* Objects:
+ - Added "protected" methods (visible only from subclasses, can be hidden
+ in class type declared in module signature).
+ - Objects can be compared using generic comparison functions.
+ - Fixed compilation of partial application of object constructors.
+
+* Type system:
+ - Occur-check now more strict (all recursions must traverse an object).
+ - A few bugs fixed.
+
+* Run-time system:
+ - A heap compactor was implemented, so long-running programs can now
+ fight fragmentation.
+ - The meaning of the "space_overhead" parameter has changed.
+ - The macros Push_roots and Pop_roots are superseded by Begin_roots* and
+ End_roots.
+ - Bytecode executable includes list of primitives used, avoids crashes
+ on version mismatch.
+ - Reduced startup overhead for marshalling, much faster marshalling of
+ small objects.
+ - New exception Stack_overflow distinct from Out_of_memory.
+ - Maximum stack size configurable.
+ - I/O revised for compatibility with compactor and with native threads.
+ - All C code ANSIfied (new-style function declarations, etc).
+ - Threaded code work on all 64-bit processors, not just Alpha/Digital Unix.
+ - Better printing of uncaught exceptions.
+
+* Both compilers:
+ - Parsing: more detailed reporting of syntax errors (e.g. shows
+ unmatched opening parenthesis on missing closing parenthesis).
+ - Check consistency between interfaces (.cmi).
+ - Revised rules for determining dependencies between modules.
+ - Options "-verbose" for printing calls to C compiler, "-noassert"
+ for turning assertion checks off.
+
+* Native-code compiler:
+ - Machine-dependent parts rewritten using inheritance instead of
+ parameterized modules.
+ - GC bug in value let rec fixed.
+ - Port to Linux/Alpha.
+ - Sparc: cleaned up use of %g registers, now compatible with Solaris threads.
+
+* Top-level interactive system:
+ - Can execute Caml script files given on command line.
+ - Reads commands from ./.ocamlinit on startup.
+ - Now thread-compatible.
+
+* Standard library:
+ - New library module: Lazy (delayed computations).
+ - New library module: Marshal. Allows marshalling to strings and
+ transmission of closures between identical programs (SPMD parallelism).
+ - Filename: "is_absolute" is superseded by "is_implicit" and "is_relative".
+ To adapt old programs, change "is_absolute x" to "not (is_implicit x)"
+ (but the new "is_relative" is NOT the opposite of the old "is_absolute").
+ - Array, Hashtbl, List, Map, Queue, Set, Stack, Stream:
+ the "iter" functions now take as argument a unit-returning function.
+ - Format: added "printf" interface to the formatter (see the documentation).
+ Revised behaviour of simple boxes: no more than one new line is output
+ when consecutive break hints should lead to multiple line breaks.
+ - Stream: revised implementation, renamed Parse_failure to Failure and
+ Parse_error to Error (don't you love gratuitous changes?).
+ - String: added index, rindex, index_from, rindex_from.
+ - Array: added mapi, iteri, fold_left, fold_right, init.
+ - Added Map.map, Set.subset, Printexc.to_string.
+
+* ocamllex: lexers generated by ocamllex can now handle all characters,
+ including '\000'.
+
+* ocamlyacc: fixed bug with function closures returned by parser rules.
+
+* Debugger:
+ - Revised generation of events.
+ - Break on function entrance.
+ - New commands start/previous.
+ - The command loadprinter now try to recursively load required
+ modules.
+ - Numerous small fixes.
+
+* External libraries:
+ - systhreads: can now use POSIX threads; POSIX and Win32 threads are
+ now supported by the native-code compiler.
+ - dbm and graph: work in native code.
+ - num: fixed bug in Nat.nat_of_string.
+ - str: fixed deallocation bug with case folding.
+ - win32unix: use Win32 handles instead of (buggy) VC++ emulation of Unix
+ file handles; added gettimeofday.
+
+* Emacs editing mode and debugger interface updated to July '97 version.
+
+Objective Caml 1.05 (21 Mar 1997):
+----------------------------------
+
+* Typing: fixed several bugs causing spurious type errors.
+
+* Native-code compiler: fixed instruction selection bug causing GC to
+see ill-formed pointers; fixed callbacks to support invocation from a
+main program in C.
+
+* Standard library: fixed String.lowercase; Weak now resists integers.
+
+* Toplevel: multiple phrases without intermediate ";;" now really supported;
+fixed value printing problems where the wrong printer was selected.
+
+* Debugger: fixed printing problem with local references; revised
+handling of checkpoints; various other small fixes.
+
+* Macintosh port: fixed signed division problem in bytecomp/emitcode.ml
+
+Objective Caml 1.04 (11 Mar 1997):
+----------------------------------
+
+* Replay debugger ported from Caml Light; added debugger support in
+ compiler (option -g) and runtime system. Debugger is alpha-quality
+ and needs testing.
+
+* Parsing:
+ - Support for "# linenum" directives.
+ - At toplevel, allow several phrases without intermediate ";;".
+
+* Typing:
+ - Allow constraints on datatype parameters, e.g.
+ type 'a foo = ... constraint 'a = 'b * 'c.
+ - Fixed bug in signature matching in presence of free type variables '_a.
+ - Extensive cleanup of internals of type inference.
+
+* Native-code compilation:
+ - Inlining of small functions at point of call (fairly conservative).
+ - MIPS code generator ported to SGI IRIX 6.
+ - Better code generated for large integer constants.
+ - Check for urgent GC when allocating large objects in major heap.
+ - PowerPC port: better scheduling, reduced TOC consumption.
+ - HPPA port: handle long conditional branches gracefully,
+ several span-dependent bugs fixed.
+
+* Standard library:
+ - More floating-point functions (all ANSI C float functions now available).
+ - Hashtbl: added functorial interface (allow providing own equality
+ and hash functions); rehash when resizing, avoid memory leak on
+ Hashtbl.remove.
+ - Added Char.uppercase, Char.lowercase, String.uppercase, String.lowercase,
+ String.capitalize, String.uncapitalize.
+ - New module Weak for manipulating weak pointers.
+ - New module Callback for registering closures and exceptions to be
+ used from C.
+
+* Foreign interface:
+ - Better support for callbacks (C calling Caml), exception raising
+ from C, and main() in C. Added function to remove a global root.
+ - Option -output-obj to package Caml code as a C library.
+
+* Thread library: fixed bug in timed_read and timed_write operations;
+ Lexing.from_function and Lexing.from_channel now reentrant.
+
+* Unix interface: renamed EACCESS to EACCES (the POSIX name); added setsid;
+ fixed bug in inet_addr_of_string for 64-bit platforms.
+
+* Ocamlyacc: default error function no longer prevents error recovery.
+
+* Ocamllex: fixed reentrancy problem w.r.t. exceptions during refill;
+ fixed output problem (\r\r\n) under Win32.
+
+* Macintosh port:
+ - The makefiles are provided for compiling and installing O'Caml on
+ a Macintosh with MPW 3.4.1.
+ - An application with the toplevel in a window is forthcoming.
+
+* Windows NT/95 port: updated toplevel GUI to that of Caml Light 0.73.
+
+* Emacs editing mode and debugger interface included in distribution.
+
+
+Objective Caml 1.03 (29 Oct 1996):
+----------------------------------
+
+* Typing:
+ - bug with type names escaping their scope via unification with
+ non-generalized type variables '_a completely fixed;
+ - fixed bug in occur check : it was too restrictive;
+ - fixed bug of coercion operators;
+ - check that no two types of the same name are generated in a module
+ (there was no check for classes);
+ - "#install_printer" works again;
+ - fixed bug in printing of subtyping errors;
+ - in class interfaces, construct "method m" (without type) change
+ the status of method m from abstract to concrete;
+ - in a recursive definition of class interfaces, a class can now
+ inherit from a previous class;
+ - typing of a method make use of an eventual previously given type
+ of this method, yielding clearer type errors.
+
+* Compilation (ocamlc and ocamlopt):
+ - fixed bug in compilation of classes.
+
+* Native-code compilation:
+ - optimization of functions taking tuples of arguments;
+ - code emitter for the Motorola 680x0 processors (retrocomputing week);
+ - Alpha/OSF1: generate frame descriptors, avoids crashes when e.g.
+ exp() or log() cause a domain error; fixed bug with
+ String.length "literal";
+ - Sparc, Mips, HPPA: removed marking of scanned stack frames
+ (benefits do not outweight cost).
+
+* Standard library:
+ - Arg.parse now prints documentation for command-line options;
+ - I/O buffers (types in_channel and out_channel) now heap-allocated,
+ avoids crashing when closing a channel several times;
+ - Overflow bug in compare() fixed;
+ - GC bug in raising Sys_error from I/O functions fixed;
+ - Parsing.symbol_start works even for epsilon productions.
+
+* Foreign interface: main() in C now working, fixed bug in library
+ order at link time.
+
+* Thread library: guard against calling thread functions before Thread.create.
+
+* Unix library: fixed getsockopt, setsockopt, open_process_{in,out}.
+
+* Perl-free, cpp-free, cholesterol-free installation procedure.
+
+
+Objective Caml 1.02 (27 Sep 1996):
+----------------------------------
+
+* Typing:
+ - fixed bug with type names escaping their scope via unification
+ with non-generalized type variables '_a;
+ - keep #class abbreviations longer;
+ - faster checking of well-formed abbreviation definitions;
+ - stricter checking of "with" constraints over signatures (arity
+ mismatch, overriding of an already manifest type).
+
+* Compilation (ocamlc and ocamlopt):
+ - fixed bug in compilation of recursive classes;
+ - [|...|] and let...rec... allowed inside definitions of recursive
+ data structures;
+
+* Bytecode compilation: fixed overflow in linker for programs with
+ more than 65535 globals and constants.
+
+* Native-code compilation:
+ - ocamlopt ported to HPPA under HP/UX, Intel x86 under Solaris 2,
+ PowerMacintosh under MkLinux;
+ - fixed two bugs related to floating-point arrays (one with "t array"
+ where t is an abstract type implemented as float, one with
+ comparison between two float arrays on 32 bit platforms);
+ - fixed reloading/spilling problem causing non-termination of
+ register allocation;
+ - fixed bugs in handling of () causing loss of tail recursion;
+ - fixed reloading bug in indirect calls.
+
+* Windows NT/95 port:
+ - complete port of the threads library (Pascal Cuoq);
+ - partial port of the Unix library (Pascal Cuoq);
+ - expansion of *, ? and @ on the command line.
+
+* Standard library:
+ - bug in in List.exists2 fixed;
+ - bug in "Random.int n" for very large n on 64-bit machines fixed;
+ - module Format: added a "general purpose" type of box (open_box);
+ can output on several formatters at the same time.
+
+* The "threads" library:
+ - implementation on top of native threads available for Win32 and
+ POSIX 1003.1c;
+ - added -thread option to select a thread-safe version of the
+ standard library, the ThreadIO module is no longer needed.
+
+* The "graph" library: avoid invalid pixmaps when doing
+ open_graph/close_graph several times.
+
+* The "dynlink" library: support for "private" (no re-export) dynamic loading.
+
+* ocamlyacc: skip '...' character literals correctly.
+
+* C interface: C code linked with O'Caml code can provide its own main()
+ and call caml_main() later.
+
+
+Objective Caml 1.01 (12 Jun 1996):
+----------------------------------
+
+* Typing: better report of type incompatibilities;
+ non-generalizable type variables in a struct...end no longer flagged
+ immediately as an error;
+ name clashes during "open" avoided.
+
+* Fixed bug in output_value where identical data structures
+ could have different external representations; this bug caused wrong
+ "inconsistent assumptions" errors when checking compatibility of
+ interfaces at link-time.
+
+* Standard library: fixed bug in Array.blit on overlapping array sections
+
+* Unmarshaling from strings now working.
+
+* ocamlc, ocamlopt: new flags -intf and -impl to force compilation as
+ an implementation/an interface, regardless of file extension;
+ overflow bug on wide-range integer pattern-matchings fixed.
+
+* ocamlc: fixed bytecode generation bug causing problems with compilation
+ units defining more than 256 values
+
+* ocamlopt, all platforms:
+ fixed GC bug in "let rec" over data structures;
+ link startup file first, fixes "undefined symbol" errors with some
+ libraries.
+
+* ocamlopt, Intel x86:
+ more efficient calling sequence for calling C functions;
+ floating-point wars, chapter 5: don't use float stack for holding
+ float pseudo-registers, stack-allocating them is just as efficient.
+
+* ocamlopt, Alpha and Intel x86: more compact calling sequence for garbage
+ collection.
+
+* ocamllex: generated automata no longer use callbacks for refilling
+ the input buffer (works better with threads); character literals
+ correctly skipped inside actions.
+
+* ocamldep: "-I" directories now searched in the right order
+
+* Thread library: incompatibilities with callbacks, signals, and
+ dynamic linking removed; scheduling bug with Thread.wait fixed.
+
+* New "dbm" library, interfaces with NDBM.
+
+* Object-oriented extensions:
+ instance variables can now be omitted in class types;
+ some error messages have been made clearer;
+ several bugs fixes.
+
+Objective Caml 1.00 (9 May 1996):
+---------------------------------
+
+* Merge of Jerome Vouillon and Didier Remy's object-oriented
+extensions.
+
+* All libraries: all "new" functions renamed to "create" because "new"
+is now a reserved keyword.
+
+* Compilation of "or" patterns (pat1 | pat2) completely revised to
+avoid code size explosion.
+
+* Compiler support for preprocessing source files (-pp flag).
+
+* Library construction: flag -linkall to force linking of all units in
+a library.
+
+* Native-code compiler: port to the Sparc under NetBSD.
+
+* Toplevel: fixed bug when tracing several times the same function
+under different names.
+
+* New format for marshaling arbitrary data structures, allows
+marshaling to/from strings.
+
+* Standard library: new module Genlex (configurable lexer for streams)
+
+* Thread library: much better support for I/O and blocking system calls.
+
+* Graphics library: faster reclaimation of unused pixmaps.
+
+* Unix library: new functions {set,clear}_nonblock, {set,clear}_close_on_exec,
+{set,get}itimer, inet_addr_any, {get,set}sockopt.
+
+* Dynlink library: added support for linking libraries (.cma files).
+
+Caml Special Light 1.15 (15 Mar 1996):
+--------------------------------------
+
+* Caml Special Light now runs under Windows NT and 95. Many thanks to
+Kevin Gallo (Microsoft Research) who contributed his initial port.
+
+* csllex now generates tables for a table-driven automaton.
+The resulting lexers are smaller and run faster.
+
+* Completely automatic configuration script.
+
+* Typing: more stringent checking of module type definitions against
+manifest module type specifications.
+
+* Toplevel: recursive definitions of values now working.
+
+* Native-code compiler, all platforms:
+ toplevel "let"s with refutable patterns now working;
+ fixed bug in assignment to float record fields;
+ direct support for floating-point negation and absolute value.
+
+* Native-code compiler, x86: fixed bug with tail calls (with more than
+4 arguments) from a function with a one-word stack frame.
+
+* Native-code compiler, Sparc: problem with -compact fixed.
+
+* Thread library: support for non-blocking writes; scheduler revised.
+
+* Unix library: bug in gethostbyaddr fixed; bounds checking for read,
+write, etc.
+
+Caml Special Light 1.14 (8 Feb 1996):
+-------------------------------------
+
+* cslopt ported to the PowerPC/RS6000 architecture. Better support for
+AIX in the bytecode system as well.
+
+* cslopt, all platforms: fixed bug in live range splitting around catch/exit.
+
+* cslopt for the Intel (floating-point wars, chapter 4):
+implemented Ershov's algorithm to minimize floating-point stack usage;
+out-of-order pops fixed.
+
+* Several bug fixes in callbacks and signals.
+
+Caml Special Light 1.13 (4 Jan 1996):
+-------------------------------------
+
+* Pattern-matching compilation revised to factor out accesses inside
+matched structures.
+
+* Callbacks and signals now supported in cslopt.
+Signals are only detected at allocation points, though.
+Added callback functions with 2 and 3 arguments.
+
+* More explicit error messages when a native-code program aborts due
+to array or string bound violations.
+
+* In patterns, "C _" allowed even if the constructor C has several arguments.
+
+* && and || allowed as alternate syntax for & and or.
+
+* cslopt for the Intel: code generation for floating-point
+operations entirely redone for the third time (a pox on whomever at
+Intel decided to organize the floating-point registers as a stack).
+
+* cslopt for the Sparc: don't use Sparc V8 smul and sdiv instructions,
+emulation on V7 processors is abysmal.
+
+Caml Special Light 1.12 (30 Nov 1995):
+--------------------------------------
+
+* Fixed an embarrassing bug with references to floats.
+
+Caml Special Light 1.11 (29 Nov 1995):
+--------------------------------------
+
+* Streams and stream parsers a la Caml Light are back (thanks to
+Daniel de Rauglaudre).
+
+* User-level concurrent threads, with low-level shared memory primitives
+(locks and conditions) as well as channel-based communication primitives
+with first-class synchronous events, in the style of Reppy's CML.
+
+* The native-code compiler has been ported to the HP PA-RISC processor
+running under NextStep (sorry, no HPUX, its linker keeps dumping
+core on me).
+
+* References not captured in a function are optimized into variables.
+
+* Fixed several bugs related to exceptions.
+
+* Floats behave a little more as specified in the IEEE standard
+(believe it or not, but x < y is not the negation of x >= y).
+
+* Lower memory consumption for the native-code compiler.
+
+Caml Special Light 1.10 (07 Nov 1995):
+--------------------------------------
+
+* Many bug fixes (too many to list here).
+
+* Module language: introduction of a "with module" notation over
+signatures for concise sharing of all type components of a signature;
+better support for concrete types in signatures.
+
+* Native-code compiler: the Intel 386 version has been ported to
+NextStep and FreeBSD, and generates better code (especially for
+floats)
+
+* Tools and libraries: the Caml Light profiler and library for
+arbitrary-precision arithmetic have been ported (thanks to John
+Malecki and Victor Manuel Gulias Fernandez); better docs for the Unix
+and regexp libraries.
+
+Caml Special Light 1.07 (20 Sep 1995):
+--------------------------------------
+
+* Syntax: optional ;; allowed in compilation units and structures
+(back by popular demand)
+
+* cslopt:
+generic handling of float arrays fixed
+direct function application when the function expr is not a path fixed
+compilation of "let rec" over values fixed
+multiple definitions of a value name in a module correctly handled
+no calls to ranlib in Solaris
+
+* csltop: #trace now working
+
+* Standard library: added List.memq; documentation of Array fixed.
+
+Caml Special Light 1.06 (12 Sep 1995):
+--------------------------------------
+
+* First public release.
diff --git a/INSTALL b/INSTALL
new file mode 100644
index 0000000000..a83bbd3bda
--- /dev/null
+++ b/INSTALL
@@ -0,0 +1,356 @@
+ Installing OCaml on a Unix machine
+ ----------------------------------
+
+PREREQUISITES
+
+* The GNU C compiler gcc is recommended, as the bytecode
+ interpreter takes advantage of gcc-specific features to enhance
+ performance. gcc is the standard compiler under Linux, MacOS X,
+ and many other systems.
+
+* If you do not have write access to /tmp, you should set the environment
+ variable TMPDIR to the name of some other temporary directory.
+
+* Under HP/UX, the GNU C compiler gcc, the GNU assembler gas, and GNU make
+ are all *required*. The vendor-provided compiler, assembler and make
+ have major problems.
+
+* GNU make is needed to build ocamlbuild. If your system's default
+ make is not GNU make, you need to define the GNUMAKE environment
+ variable to the name of GNU make, typically with this command:
+
+ export GNUMAKE=gmake
+
+INSTALLATION INSTRUCTIONS
+
+1- Configure the system. From the top directory, do:
+
+ ./configure
+
+This generates the three configuration files "Makefile", "m.h" and "s.h"
+in the config/ subdirectory.
+
+The "configure" script accepts the following options:
+
+-prefix <dir> (default: /usr/local)
+ Set the PREFIX variable used to define the defaults of the
+ following three options. Must be an absolute path name.
+
+-bindir <dir> (default: $(PREFIX)/bin)
+ Directory where the binaries will be installed.
+ Must be an absolute path name, or start with "$(PREFIX)"
+
+-libdir <dir> (default: $(PREFIX)/lib/ocaml)
+ Directory where the OCaml library will be installed
+ Must be an absolute path name, or start with "$(PREFIX)"
+
+-mandir <dir> (default: $(PREFIX)/man/man1)
+ Directory where the manual pages will be installed
+ Must be an absolute path name, or start with "$(PREFIX)"
+
+-cc <C compiler and options> (default: gcc if available, cc otherwise)
+ C compiler to use for building the system
+
+-libs <extra libraries> (default: none)
+ Extra libraries to link with the system
+
+-no-curses
+ Do not use the curses library.
+
+-host <hosttype> (default: determined automatically)
+ The type of the host machine, in GNU's "configuration name"
+ format (CPU-COMPANY-SYSTEM or CPU-COMPANY-KERNEL-SYSTEM).
+ This info is generally determined automatically by the
+ "configure" script, and rarely ever needs to be provided by
+ hand. The installation instructions for gcc or emacs contain a
+ complete list of configuration names.
+
+-target <targettype> (default: same as -host)
+ The type of the target machine, in GNU's "configuration name"
+ format (CPU-COMPANY-SYSTEM or CPU-COMPANY-KERNEL-SYSTEM).
+ Setting this will setup OCaml as a cross-compiler which runs on
+ $host and produces code for $target. This requires a C toolchain
+ which also produces code for $target and a native OCaml
+ compiler of the exact same version (if you want a cross 4.00.1,
+ you need a native 4.00.1).
+
+-x11include <include_dir> (default: determined automatically)
+-x11lib <lib_dir> (default: determined automatically)
+ Location of the X11 include directory (e.g. /usr/X11R6/include)
+ and the X11 library directory (e.g. /usr/X11R6/lib).
+
+-no-pthread
+ Do not attempt to use POSIX threads.
+
+-with-pthread
+ Attempt to use POSIX threads (this is the default).
+
+-no-shared-libs
+ Do not configure support for shared libraries
+
+-dldefs <cpp flags>
+-dllibs <flags and libraries>
+ These options specify where to find the libraries for dynamic
+ linking (i.e. use of shared libraries). "-dldefs" specifies
+ options for finding the header files, and "-dllibs" for finding
+ the C libraries.
+
+-as <assembler and options> (default: determined automatically)
+ The assembler to use for assembling ocamlopt-generated code.
+
+-aspp <assembler and options> (default: determined automatically)
+ The assembler to use for assembling the parts of the
+ run-time system manually written in assembly language.
+ This assembler must preprocess its input with the C preprocessor.
+
+-with-debug-runtime
+ Compile and install the debug version of the runtimes, useful
+ for debugging C stubs and other low-level code.
+
+-verbose
+ Verbose output of the configuration tests. Use it if the outcome
+ of configure is not what you were expecting.
+
+-no-debugger
+ Do not build ocamldebug.
+
+-no-ocamldoc
+ Do not build ocamldoc.
+
+-no-ocamlbuild
+ Do not build ocamlbuild.
+
+-no-graph
+ Do not compile the Graphics library.
+
+-partialld <linker and options> (default: determined automatically)
+ The linker and options to use for producing an object file
+ (rather than an executable) from several other object files.
+
+-no-cfi
+ Do not compile support for CFI directives.
+
+Examples:
+
+ Standard installation in /usr/{bin,lib,man} instead of /usr/local:
+ ./configure -prefix /usr
+
+ Installation in /usr, man pages in section "l":
+ ./configure -bindir /usr/bin -libdir /usr/lib/ocaml -mandir /usr/man/manl
+ or:
+ ./configure -prefix /usr -mandir '$(PREFIX)/man/manl'
+
+ On a Linux x86-64 host, to build a 32-bit version of OCaml:
+ ./configure -cc "gcc -m32" -as "as --32" -aspp "gcc -m32 -c" \
+ -host i386-linux -partialld "ld -r -melf_i386"
+
+ On a Linux x86-64 host, to build the run-time system in PIC mode,
+ no special options should be required---the libraries should be built
+ automatically. The old instructions were:
+ ./configure -cc "gcc -fPIC" -aspp "gcc -c -fPIC"
+
+ On a 64-bit POWER architecture host running Linux, OCaml only operates
+ in a 32-bit environment. If your system compiler is configured as 32-bit,
+ e.g. Red Hat 5.9, you don't need to do anything special. If that is
+ not the case (e.g. Red Hat 6.4), then IBM's "Advance Toolchain" can
+ be used. For example:
+ export PATH=/opt/at7.0/bin:$PATH
+ ./configure -cc "gcc -m32" -as "as -a32" -aspp "gcc -m32 -c" \
+ -partialld "ld -r -m elf32ppc"
+
+ On a MacOSX 10.5/Intel Core 2 or MacOSX 10.5/PowerPC host,
+ to build a 64-bit version of OCaml:
+ ./configure -cc "gcc -m64"
+
+ On Intel Mac OS X, to build a 32-bit version of OCaml:
+ ./configure -host "i386-apple-darwin13.2.0" -cc "gcc -arch i386 -m32" \
+ -as "as -arch i386" -aspp "gcc -arch i386 -m32 -c"
+
+ For Sun Solaris with the "acc" compiler:
+ ./configure -cc "acc -fast" -libs "-lucb"
+
+ For Sun Solaris on Sparc 64bit, to compile natively (32bit only)
+ ./configure -cc "gcc -m32" -as "as -32" -aspp "gcc -m32 -c"
+
+ For AIX 4.3 with the IBM compiler xlc:
+ ./configure -cc "xlc_r -D_AIX43 -Wl,-bexpall,-brtl -qmaxmem=8192"
+
+
+If something goes wrong during the automatic configuration, or if the
+generated files cause errors later on, then look at the template files
+
+ config/Makefile-templ
+ config/m-templ.h
+ config/s-templ.h
+
+for guidance on how to edit the generated files by hand.
+
+2- From the top directory, do:
+
+ make world
+
+This builds the OCaml bytecode compiler for the first time. This
+phase is fairly verbose; consider redirecting the output to a file:
+
+ make world > log.world 2>&1 # in sh
+ make world >& log.world # in csh
+
+3- (Optional) To be sure everything works well, you can try to
+bootstrap the system --- that is, to recompile all OCaml sources with
+the newly created compiler. From the top directory, do:
+
+ make bootstrap
+
+or, better:
+
+ make bootstrap > log.bootstrap 2>&1 # in sh
+ make bootstrap >& log.bootstrap # in csh
+
+The "make bootstrap" checks that the bytecode programs compiled with
+the new compiler are identical to the bytecode programs compiled with
+the old compiler. If this is the case, you can be pretty sure the
+system has been correctly compiled. Otherwise, this does not
+necessarily mean something went wrong. The best thing to do is to try
+a second bootstrapping phase: just do "make bootstrap" again. It will
+either crash almost immediately, or re-re-compile everything correctly
+and reach the fixpoint.
+
+4- If your platform is supported by the native-code compiler (as
+reported during the autoconfiguration), you can now build the
+native-code compiler. From the top directory, do:
+
+ make opt
+or:
+ make opt > log.opt 2>&1 # in sh
+ make opt >& log.opt # in csh
+
+5- Compile fast versions of the OCaml compilers, by compiling them
+with the native-code compiler (you have only compiled them to bytecode
+so far). Just do:
+
+ make opt.opt
+
+Later, you can compile your programs to bytecode using ocamlc.opt
+instead of ocamlc, and to native-code using ocamlopt.opt instead of
+ocamlopt. The ".opt" compilers should run faster than the normal
+compilers, especially on large input files, but they may take longer
+to start due to increased code size. If compilation times are an issue on
+your programs, try the ".opt" compilers to see if they make a
+significant difference.
+
+An alternative, and faster approach to steps 2 to 5 is
+
+ make world.opt # to build using native-code compilers
+
+The result is equivalent to "make world opt opt.opt", but this may
+fail if anything goes wrong in native-code generation.
+
+6- You can now install the OCaml system. This will create the
+following commands (in the binary directory selected during
+autoconfiguration):
+
+ ocamlc the batch bytecode compiler
+ ocamlopt the batch native-code compiler (if supported)
+ ocamlrun the runtime system for the bytecode compiler
+ ocamlyacc the parser generator
+ ocamllex the lexer generator
+ ocaml the interactive, toplevel-based system
+ ocamlmktop a tool to make toplevel systems that integrate
+ user-defined C primitives and OCaml code
+ ocamldebug the source-level replay debugger
+ ocamldep generator of "make" dependencies for OCaml sources
+ ocamldoc documentation generator
+ ocamlprof execution count profiler
+ ocamlcp the bytecode compiler in profiling mode
+
+and also, if you built them during step 5,
+
+ ocamlc.opt the batch bytecode compiler compiled with ocamlopt
+ ocamlopt.opt the batch native-code compiler compiled with ocamlopt
+ ocamllex.opt the lexer generator compiled with ocamlopt
+
+From the top directory, become superuser and do:
+
+ umask 022 # make sure to give read & execute permission to all
+ make install
+
+7- Installation is complete. Time to clean up. From the toplevel
+directory, do "make clean".
+
+8- (Optional) The emacs/ subdirectory contains Emacs-Lisp files for an
+OCaml editing mode and an interface for the debugger. To install
+these files, change to the emacs/ subdirectory and do
+
+ make EMACSDIR=<directory where to install the files> install
+or
+ make install
+
+In the latter case, the destination directory defaults to the
+"site-lisp" directory of your Emacs installation.
+
+9- After installation, do *not* strip the ocamldebug and ocamlbrowser
+executables. (These are mixed-mode executables, containing both
+compiled C code and OCaml bytecode; stripping erases the bytecode!)
+Other executables such as ocamlrun can safely be stripped.
+
+IF SOMETHING GOES WRONG:
+
+Read the "common problems" and "machine-specific hints" section at the
+end of this file.
+
+Check the files m.h and s.h in config/. Wrong endianness or alignment
+constraints in m.h will immediately crash the bytecode interpreter.
+
+If you get a "segmentation violation" signal, check the limits on the
+stack size and data segment size (type "limit" under csh or
+"ulimit -a" under bash). Make sure the limit on the stack size is
+at least 4M.
+
+Try recompiling the runtime system with optimizations turned off
+(change CFLAGS in byterun/Makefile and asmrun/Makefile).
+The runtime system contains some complex, atypical pieces of C code
+that can uncover bugs in optimizing compilers. Alternatively, try
+another C compiler (e.g. gcc instead of the vendor-supplied cc).
+
+You can also build a debug version of the runtime system. Go to the
+byterun/ directory and do "make ocamlrund". Then, copy ocamlrund to
+../boot/ocamlrun, and try again. This version of the runtime system
+contains lots of assertions and sanity checks that could help you
+pinpoint the problem.
+
+
+COMMON PROBLEMS:
+
+* The Makefiles do not support parallel make (e.g. make -j2).
+Fix: do not pass the -j option to make, and be patient.
+
+* The Makefiles use the "include" directive, which is not supported by
+all versions of make. Use GNU make if this is a problem.
+
+* Solaris make mishandles a space in our Makefiles, so you have to use GNU
+make to build on Solaris.
+
+* The Makefiles assume that make executes commands by calling /bin/sh. They
+won't work if /bin/csh is called instead. You may have to unset the SHELL
+environment variable, or set it to /bin/sh.
+
+* On some systems, localization causes build problems. You should
+try to set the C locale (export LC_ALL=C) before compiling if you have
+strange errors while compiling OCaml.
+
+* gcc 2.7.2.1 generates incorrect code for the runtime system in -O mode
+on some Intel x86 platforms (e.g. Linux RedHat 4.1 and 4.2).
+If this causes a problem, the solution is to upgrade to 2.7.2.3 or above.
+
+* Some versions of gcc 2.96 for the Intel x86 (as found in RedHat 7.2,
+Mandrake 8.0 and Mandrake 8.1) generates incorrect code for the runtime
+system. The "configure" script tries to work around this problem.
+
+* On HP 9000/700 machines under HP/UX 9. Some versions of cc are
+unable to compile correctly the runtime system (wrong code is
+generated for (x - y) where x is a pointer and y an integer).
+Fix: use gcc.
+
+* Under MacOS X 10.6, with XCode 4.0.2, the configure script mistakenly
+detects support for CFI directives in the assembler.
+Fix: give the "-no-cfi" option to configure.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000..f47ead4448
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,627 @@
+In the following, "the Library" refers to all files marked "Copyright
+INRIA" in the following directories and their sub-directories:
+
+ asmrun, byterun, config, ocamlbuild, otherlibs, stdlib, win32caml
+
+and "the Compiler" refers to all files marked "Copyright INRIA" in the
+following directories and their sub-directories:
+
+ asmcomp, boot, build, bytecomp, debugger, driver, lex, man,
+ ocamldoc, parsing, testsuite, tools, toplevel, typing,
+ utils, yacc
+
+The Compiler is distributed under the terms of the Q Public License
+version 1.0 with a change to choice of law (included below).
+
+The Library is distributed under the terms of the GNU Library General
+Public License version 2 (included below).
+
+As a special exception to the Q Public Licence, you may develop
+application programs, reusable components and other software items
+that link with the original or modified versions of the Compiler
+and are not made available to the general public, without any of the
+additional requirements listed in clause 6c of the Q Public licence.
+
+As a special exception to the GNU Library General Public License, you
+may link, statically or dynamically, a "work that uses the Library"
+with a publicly distributed version of the Library to produce an
+executable file containing portions of the Library, and distribute
+that executable file under terms of your choice, without any of the
+additional requirements listed in clause 6 of the GNU Library General
+Public License. By "a publicly distributed version of the Library",
+we mean either the unmodified Library as distributed by INRIA, or a
+modified version of the Library that is distributed under the
+conditions defined in clause 2 of the GNU Library General Public
+License. This exception does not however invalidate any other reasons
+why the executable file might be covered by the GNU Library General
+Public License.
+
+----------------------------------------------------------------------
+
+ THE Q PUBLIC LICENSE version 1.0
+
+ Copyright (C) 1999 Troll Tech AS, Norway.
+ Everyone is permitted to copy and
+ distribute this license document.
+
+The intent of this license is to establish freedom to share and change
+the software regulated by this license under the open source model.
+
+This license applies to any software containing a notice placed by the
+copyright holder saying that it may be distributed under the terms of
+the Q Public License version 1.0. Such software is herein referred to
+as the Software. This license covers modification and distribution of
+the Software, use of third-party application programs based on the
+Software, and development of free software which uses the Software.
+
+ Granted Rights
+
+1. You are granted the non-exclusive rights set forth in this license
+provided you agree to and comply with any and all conditions in this
+license. Whole or partial distribution of the Software, or software
+items that link with the Software, in any form signifies acceptance of
+this license.
+
+2. You may copy and distribute the Software in unmodified form
+provided that the entire package, including - but not restricted to -
+copyright, trademark notices and disclaimers, as released by the
+initial developer of the Software, is distributed.
+
+3. You may make modifications to the Software and distribute your
+modifications, in a form that is separate from the Software, such as
+patches. The following restrictions apply to modifications:
+
+ a. Modifications must not alter or remove any copyright notices
+ in the Software.
+
+ b. When modifications to the Software are released under this
+ license, a non-exclusive royalty-free right is granted to the
+ initial developer of the Software to distribute your
+ modification in future versions of the Software provided such
+ versions remain available under these terms in addition to any
+ other license(s) of the initial developer.
+
+4. You may distribute machine-executable forms of the Software or
+machine-executable forms of modified versions of the Software,
+provided that you meet these restrictions:
+
+ a. You must include this license document in the distribution.
+
+ b. You must ensure that all recipients of the machine-executable
+ forms are also able to receive the complete machine-readable
+ source code to the distributed Software, including all
+ modifications, without any charge beyond the costs of data
+ transfer, and place prominent notices in the distribution
+ explaining this.
+
+ c. You must ensure that all modifications included in the
+ machine-executable forms are available under the terms of this
+ license.
+
+5. You may use the original or modified versions of the Software to
+compile, link and run application programs legally developed by you or
+by others.
+
+6. You may develop application programs, reusable components and other
+software items that link with the original or modified versions of the
+Software. These items, when distributed, are subject to the following
+requirements:
+
+ a. You must ensure that all recipients of machine-executable
+ forms of these items are also able to receive and use the
+ complete machine-readable source code to the items without any
+ charge beyond the costs of data transfer.
+
+ b. You must explicitly license all recipients of your items to
+ use and re-distribute original and modified versions of the
+ items in both machine-executable and source code forms. The
+ recipients must be able to do so without any charges whatsoever,
+ and they must be able to re-distribute to anyone they choose.
+
+ c. If the items are not available to the general public, and the
+ initial developer of the Software requests a copy of the items,
+ then you must supply one.
+
+ Limitations of Liability
+
+In no event shall the initial developers or copyright holders be
+liable for any damages whatsoever, including - but not restricted to -
+lost revenue or profits or other direct, indirect, special, incidental
+or consequential damages, even if they have been advised of the
+possibility of such damages, except to the extent invariable law, if
+any, provides otherwise.
+
+ No Warranty
+
+The Software and this license document are provided AS IS with NO
+WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN,
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+
+ Choice of Law
+
+This license is governed by the Laws of France.
+
+----------------------------------------------------------------------
+
+ GNU LIBRARY GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1991 Free Software Foundation, Inc.
+ 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the library GPL. It is
+ numbered 2 because it goes with version 2 of the ordinary GPL.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Library General Public License, applies to some
+specially designated Free Software Foundation software, and to any
+other libraries whose authors decide to use it. You can use it for
+your libraries, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if
+you distribute copies of the library, or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link a program with the library, you must provide
+complete object files to the recipients so that they can relink them
+with the library, after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ Our method of protecting your rights has two steps: (1) copyright
+the library, and (2) offer you this license which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ Also, for each distributor's protection, we want to make certain
+that everyone understands that there is no warranty for this free
+library. If the library is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original
+version, so that any problems introduced by others will not reflect on
+the original authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that companies distributing free
+software will individually obtain patent licenses, thus in effect
+transforming the program into proprietary software. To prevent this,
+we have made it clear that any patent must be licensed for everyone's
+free use or not licensed at all.
+
+ Most GNU software, including some libraries, is covered by the ordinary
+GNU General Public License, which was designed for utility programs. This
+license, the GNU Library General Public License, applies to certain
+designated libraries. This license is quite different from the ordinary
+one; be sure to read it in full, and don't assume that anything in it is
+the same as in the ordinary license.
+
+ The reason we have a separate public license for some libraries is that
+they blur the distinction we usually make between modifying or adding to a
+program and simply using it. Linking a program with a library, without
+changing the library, is in some sense simply using the library, and is
+analogous to running a utility program or application program. However, in
+a textual and legal sense, the linked executable is a combined work, a
+derivative of the original library, and the ordinary General Public License
+treats it as such.
+
+ Because of this blurred distinction, using the ordinary General
+Public License for libraries did not effectively promote software
+sharing, because most developers did not use the libraries. We
+concluded that weaker conditions might promote sharing better.
+
+ However, unrestricted linking of non-free programs would deprive the
+users of those programs of all benefit from the free status of the
+libraries themselves. This Library General Public License is intended to
+permit developers of non-free programs to use free libraries, while
+preserving your freedom as a user of such programs to change the free
+libraries that are incorporated in them. (We have not seen how to achieve
+this as regards changes in header files, but we have achieved it as regards
+changes in the actual functions of the Library.) The hope is that this
+will lead to faster development of free libraries.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, while the latter only
+works together with the library.
+
+ Note that it is possible for a library to be covered by the ordinary
+General Public License rather than by this special one.
+
+ GNU LIBRARY GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library which
+contains a notice placed by the copyright holder or other authorized
+party saying it may be distributed under the terms of this Library
+General Public License (also called "this License"). Each licensee is
+addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also compile or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ c) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ d) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the source code distributed need not include anything that is normally
+distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Library General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ Appendix: How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public
+ License along with this library; if not, write to the Free
+ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
+ MA 02111-1307, USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000000..942ae3fd6e
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,894 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# The main Makefile
+
+include config/Makefile
+CAMLRUN ?= boot/ocamlrun
+CAMLYACC ?= boot/ocamlyacc
+include stdlib/StdlibModules
+
+CAMLC=$(CAMLRUN) boot/ocamlc -nostdlib -I boot
+CAMLOPT=$(CAMLRUN) ./ocamlopt -nostdlib -I stdlib -I otherlibs/dynlink
+COMPFLAGS=-strict-sequence -w +33..39+48+50 -warn-error A -bin-annot \
+ -safe-string $(INCLUDES)
+LINKFLAGS=
+
+YACCFLAGS=-v
+CAMLLEX=$(CAMLRUN) boot/ocamllex
+CAMLDEP=$(CAMLRUN) tools/ocamldep
+DEPFLAGS=$(INCLUDES)
+SHELL=/bin/sh
+MKDIR=mkdir -p
+
+OCAMLBUILDBYTE=$(WITH_OCAMLBUILD:=.byte)
+OCAMLBUILDNATIVE=$(WITH_OCAMLBUILD:=.native)
+
+OCAMLDOC_OPT=$(WITH_OCAMLDOC:=.opt)
+
+INCLUDES=-I utils -I parsing -I typing -I bytecomp -I asmcomp -I driver \
+ -I toplevel
+
+UTILS=utils/config.cmo utils/clflags.cmo \
+ utils/misc.cmo utils/tbl.cmo \
+ utils/terminfo.cmo utils/ccomp.cmo utils/warnings.cmo \
+ utils/consistbl.cmo
+
+PARSING=parsing/location.cmo parsing/longident.cmo \
+ parsing/docstrings.cmo parsing/ast_helper.cmo \
+ parsing/syntaxerr.cmo parsing/parser.cmo \
+ parsing/lexer.cmo parsing/parse.cmo parsing/printast.cmo \
+ parsing/pprintast.cmo \
+ parsing/ast_mapper.cmo
+
+TYPING=typing/ident.cmo typing/path.cmo \
+ typing/primitive.cmo typing/types.cmo \
+ typing/btype.cmo typing/oprint.cmo \
+ typing/subst.cmo typing/predef.cmo \
+ typing/datarepr.cmo typing/cmi_format.cmo typing/env.cmo \
+ typing/typedtree.cmo typing/printtyped.cmo typing/ctype.cmo \
+ typing/printtyp.cmo typing/includeclass.cmo \
+ typing/mtype.cmo typing/envaux.cmo typing/includecore.cmo \
+ typing/typedtreeIter.cmo typing/typedtreeMap.cmo \
+ typing/tast_mapper.cmo \
+ typing/cmt_format.cmo \
+ typing/includemod.cmo typing/typetexp.cmo typing/parmatch.cmo \
+ typing/stypes.cmo typing/typecore.cmo \
+ typing/typedecl.cmo typing/typeclass.cmo \
+ typing/typemod.cmo typing/untypeast.cmo
+
+COMP=bytecomp/lambda.cmo bytecomp/printlambda.cmo \
+ bytecomp/typeopt.cmo bytecomp/switch.cmo bytecomp/matching.cmo \
+ bytecomp/translobj.cmo bytecomp/translcore.cmo \
+ bytecomp/translclass.cmo bytecomp/translmod.cmo \
+ bytecomp/simplif.cmo bytecomp/runtimedef.cmo \
+ driver/pparse.cmo driver/main_args.cmo \
+ driver/compenv.cmo driver/compmisc.cmo
+
+COMMON=$(UTILS) $(PARSING) $(TYPING) $(COMP)
+
+BYTECOMP=bytecomp/meta.cmo bytecomp/instruct.cmo bytecomp/bytegen.cmo \
+ bytecomp/printinstr.cmo bytecomp/opcodes.cmo bytecomp/emitcode.cmo \
+ bytecomp/bytesections.cmo bytecomp/dll.cmo bytecomp/symtable.cmo \
+ bytecomp/bytelink.cmo bytecomp/bytelibrarian.cmo bytecomp/bytepackager.cmo \
+ driver/errors.cmo driver/compile.cmo
+
+INTEL_ASM=\
+ asmcomp/x86_proc.cmo \
+ asmcomp/x86_dsl.cmo \
+ asmcomp/x86_gas.cmo \
+ asmcomp/x86_masm.cmo
+
+ARCH_SPECIFIC_ASMCOMP=
+ifeq ($(ARCH),i386)
+ARCH_SPECIFIC_ASMCOMP=$(INTEL_ASM)
+endif
+ifeq ($(ARCH),amd64)
+ARCH_SPECIFIC_ASMCOMP=$(INTEL_ASM)
+endif
+
+ASMCOMP=\
+ $(ARCH_SPECIFIC_ASMCOMP) \
+ asmcomp/arch.cmo asmcomp/debuginfo.cmo \
+ asmcomp/cmm.cmo asmcomp/printcmm.cmo \
+ asmcomp/reg.cmo asmcomp/mach.cmo asmcomp/proc.cmo \
+ asmcomp/clambda.cmo asmcomp/printclambda.cmo asmcomp/compilenv.cmo \
+ asmcomp/closure.cmo asmcomp/strmatch.cmo asmcomp/cmmgen.cmo \
+ asmcomp/printmach.cmo asmcomp/selectgen.cmo asmcomp/selection.cmo \
+ asmcomp/comballoc.cmo \
+ asmcomp/CSEgen.cmo asmcomp/CSE.cmo \
+ asmcomp/liveness.cmo \
+ asmcomp/spill.cmo asmcomp/split.cmo \
+ asmcomp/interf.cmo asmcomp/coloring.cmo \
+ asmcomp/reloadgen.cmo asmcomp/reload.cmo \
+ asmcomp/deadcode.cmo \
+ asmcomp/printlinear.cmo asmcomp/linearize.cmo \
+ asmcomp/schedgen.cmo asmcomp/scheduling.cmo \
+ asmcomp/branch_relaxation_intf.cmo \
+ asmcomp/branch_relaxation.cmo \
+ asmcomp/emitaux.cmo asmcomp/emit.cmo asmcomp/asmgen.cmo \
+ asmcomp/asmlink.cmo asmcomp/asmlibrarian.cmo asmcomp/asmpackager.cmo \
+ driver/opterrors.cmo driver/optcompile.cmo
+
+TOPLEVEL=toplevel/genprintval.cmo toplevel/toploop.cmo \
+ toplevel/trace.cmo toplevel/topdirs.cmo toplevel/topmain.cmo
+
+BYTESTART=driver/main.cmo
+
+OPTSTART=driver/optmain.cmo
+
+TOPLEVELSTART=toplevel/topstart.cmo
+
+NATTOPOBJS=$(UTILS) $(PARSING) $(TYPING) $(COMP) $(ASMCOMP) \
+ toplevel/genprintval.cmo toplevel/opttoploop.cmo toplevel/opttopdirs.cmo \
+ toplevel/opttopmain.cmo toplevel/opttopstart.cmo
+
+PERVASIVES=$(STDLIB_MODULES) outcometree topdirs toploop
+
+# For users who don't read the INSTALL file
+defaultentry:
+ @echo "Please refer to the installation instructions in file INSTALL."
+ @echo "If you've just unpacked the distribution, something like"
+ @echo " ./configure"
+ @echo " make world.opt"
+ @echo " make install"
+ @echo "should work. But see the file INSTALL for more details."
+
+# Recompile the system using the bootstrap compiler
+all:
+ $(MAKE) runtime
+ $(MAKE) coreall
+ $(MAKE) ocaml
+ $(MAKE) otherlibraries $(OCAMLBUILDBYTE) $(WITH_DEBUGGER) \
+ $(WITH_OCAMLDOC)
+
+# Compile everything the first time
+world:
+ $(MAKE) coldstart
+ $(MAKE) all
+
+# Compile also native code compiler and libraries, fast
+world.opt:
+ $(MAKE) coldstart
+ $(MAKE) opt.opt
+
+# Hard bootstrap how-to:
+# (only necessary in some cases, for example if you remove some primitive)
+#
+# make coreboot [old system -- you were in a stable state]
+# <change the source>
+# make clean runtime coreall
+# <debug your changes>
+# make clean runtime coreall
+# make coreboot [new system -- now in a stable state]
+
+# Core bootstrapping cycle
+coreboot:
+# Save the original bootstrap compiler
+ $(MAKE) backup
+# Promote the new compiler but keep the old runtime
+# This compiler runs on boot/ocamlrun and produces bytecode for
+# byterun/ocamlrun
+ $(MAKE) promote-cross
+# Rebuild ocamlc and ocamllex (run on byterun/ocamlrun)
+ $(MAKE) partialclean
+ $(MAKE) ocamlc ocamllex ocamltools
+# Rebuild the library (using byterun/ocamlrun ./ocamlc)
+ $(MAKE) library-cross
+# Promote the new compiler and the new runtime
+ $(MAKE) promote
+# Rebuild the core system
+ $(MAKE) partialclean
+ $(MAKE) core
+# Check if fixpoint reached
+ $(MAKE) compare
+
+# Bootstrap and rebuild the whole system.
+# The compilation of ocaml will fail if the runtime has changed.
+# Never mind, just do make bootstrap to reach fixpoint again.
+bootstrap:
+ $(MAKE) coreboot
+ $(MAKE) all
+ $(MAKE) compare
+
+LIBFILES=stdlib.cma std_exit.cmo *.cmi camlheader
+
+# Start up the system from the distribution compiler
+coldstart:
+ cd byterun; $(MAKE) all
+ cp byterun/ocamlrun$(EXE) boot/ocamlrun$(EXE)
+ cd yacc; $(MAKE) all
+ cp yacc/ocamlyacc$(EXE) boot/ocamlyacc$(EXE)
+ cd stdlib; $(MAKE) COMPILER=../boot/ocamlc all
+ cd stdlib; cp $(LIBFILES) ../boot
+ if test -f boot/libcamlrun.a; then :; else \
+ ln -s ../byterun/libcamlrun.a boot/libcamlrun.a; fi
+ if test -d stdlib/caml; then :; else \
+ ln -s ../byterun/caml stdlib/caml; fi
+
+# Build the core system: the minimum needed to make depend and bootstrap
+core:
+ $(MAKE) coldstart
+ $(MAKE) coreall
+
+# Recompile the core system using the bootstrap compiler
+coreall:
+ $(MAKE) ocamlc
+ $(MAKE) ocamllex ocamlyacc ocamltools library
+
+# Save the current bootstrap compiler
+MAXSAVED=boot/Saved/Saved.prev/Saved.prev/Saved.prev/Saved.prev/Saved.prev
+backup:
+ if test -d boot/Saved; then : ; else mkdir boot/Saved; fi
+ if test -d $(MAXSAVED); then rm -r $(MAXSAVED); else : ; fi
+ mv boot/Saved boot/Saved.prev
+ mkdir boot/Saved
+ mv boot/Saved.prev boot/Saved/Saved.prev
+ cp boot/ocamlrun$(EXE) boot/Saved
+ mv boot/ocamlc boot/ocamllex boot/ocamlyacc$(EXE) boot/ocamldep \
+ boot/Saved
+ cd boot; cp $(LIBFILES) Saved
+
+# Promote the newly compiled system to the rank of cross compiler
+# (Runs on the old runtime, produces code for the new runtime)
+promote-cross:
+ cp ocamlc boot/ocamlc
+ cp lex/ocamllex boot/ocamllex
+ cp yacc/ocamlyacc$(EXE) boot/ocamlyacc$(EXE)
+ cp tools/ocamldep boot/ocamldep
+ cd stdlib; cp $(LIBFILES) ../boot
+
+# Promote the newly compiled system to the rank of bootstrap compiler
+# (Runs on the new runtime, produces code for the new runtime)
+promote: promote-cross
+ cp byterun/ocamlrun$(EXE) boot/ocamlrun$(EXE)
+
+# Restore the saved bootstrap compiler if a problem arises
+restore:
+ mv boot/Saved/* boot
+ rmdir boot/Saved
+ mv boot/Saved.prev boot/Saved
+
+# Check if fixpoint reached
+compare:
+ @if cmp boot/ocamlc ocamlc && cmp boot/ocamllex lex/ocamllex \
+ && cmp boot/ocamldep tools/ocamldep; \
+ then echo "Fixpoint reached, bootstrap succeeded."; \
+ else echo "Fixpoint not reached, try one more bootstrapping cycle."; \
+ fi
+
+# Remove old bootstrap compilers
+cleanboot:
+ rm -rf boot/Saved/Saved.prev/*
+
+# Compile the native-code compiler
+opt-core:
+ $(MAKE) runtimeopt
+ $(MAKE) ocamlopt
+ $(MAKE) libraryopt
+
+opt:
+ $(MAKE) runtimeopt
+ $(MAKE) ocamlopt
+ $(MAKE) libraryopt
+ $(MAKE) otherlibrariesopt ocamltoolsopt $(OCAMLBUILDNATIVE)
+
+# Native-code versions of the tools
+opt.opt:
+ $(MAKE) checkstack
+ $(MAKE) runtime
+ $(MAKE) core
+ $(MAKE) ocaml
+ $(MAKE) opt-core
+ $(MAKE) ocamlc.opt
+ $(MAKE) otherlibraries $(WITH_DEBUGGER) $(WITH_OCAMLDOC) \
+ $(OCAMLBUILDBYTE)
+ $(MAKE) ocamlopt.opt
+ $(MAKE) otherlibrariesopt
+ $(MAKE) ocamllex.opt ocamltoolsopt ocamltoolsopt.opt $(OCAMLDOC_OPT) \
+ $(OCAMLBUILDNATIVE)
+
+base.opt:
+ $(MAKE) checkstack
+ $(MAKE) runtime
+ $(MAKE) core
+ $(MAKE) ocaml
+ $(MAKE) opt-core
+ $(MAKE) ocamlc.opt
+ $(MAKE) otherlibraries $(OCAMLBUILDBYTE) $(WITH_DEBUGGER) \
+ $(WITH_OCAMLDOC)
+ $(MAKE) ocamlopt.opt
+ $(MAKE) otherlibrariesopt
+
+# Installation
+
+COMPLIBDIR=$(LIBDIR)/compiler-libs
+
+INSTALL_BINDIR=$(DESTDIR)$(BINDIR)
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+INSTALL_COMPLIBDIR=$(DESTDIR)$(COMPLIBDIR)
+INSTALL_STUBLIBDIR=$(DESTDIR)$(STUBLIBDIR)
+INSTALL_MANDIR=$(DESTDIR)$(MANDIR)
+
+install:
+ if test -d $(INSTALL_BINDIR); then : ; \
+ else $(MKDIR) $(INSTALL_BINDIR); fi
+ if test -d $(INSTALL_LIBDIR); then : ; \
+ else $(MKDIR) $(INSTALL_LIBDIR); fi
+ if test -d $(INSTALL_STUBLIBDIR); then : ; \
+ else $(MKDIR) $(INSTALL_STUBLIBDIR); fi
+ if test -d $(INSTALL_COMPLIBDIR); then : ; \
+ else $(MKDIR) $(INSTALL_COMPLIBDIR); fi
+ if test -d $(INSTALL_MANDIR)/man$(MANEXT); then : ; \
+ else $(MKDIR) $(INSTALL_MANDIR)/man$(MANEXT); fi
+ cp VERSION $(INSTALL_LIBDIR)/
+ cd $(INSTALL_LIBDIR); rm -f dllbigarray.so dllnums.so dllthreads.so \
+ dllunix.so dllgraphics.so dllstr.so
+ cd byterun; $(MAKE) install
+ cp ocamlc $(INSTALL_BINDIR)/ocamlc$(EXE)
+ cp ocaml $(INSTALL_BINDIR)/ocaml$(EXE)
+ cd stdlib; $(MAKE) install
+ cp lex/ocamllex $(INSTALL_BINDIR)/ocamllex$(EXE)
+ cp $(CAMLYACC)$(EXE) $(INSTALL_BINDIR)/ocamlyacc$(EXE)
+ cp utils/*.cmi utils/*.cmt utils/*.cmti \
+ parsing/*.cmi parsing/*.cmt parsing/*.cmti \
+ typing/*.cmi typing/*.cmt typing/*.cmti \
+ bytecomp/*.cmi bytecomp/*.cmt bytecomp/*.cmti \
+ driver/*.cmi driver/*.cmt driver/*.cmti \
+ toplevel/*.cmi toplevel/*.cmt toplevel/*.cmti $(INSTALL_COMPLIBDIR)
+ cp compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma \
+ compilerlibs/ocamltoplevel.cma $(BYTESTART) $(TOPLEVELSTART) \
+ $(INSTALL_COMPLIBDIR)
+ cp expunge $(INSTALL_LIBDIR)/expunge$(EXE)
+ cp toplevel/topdirs.cmi $(INSTALL_LIBDIR)
+ cd tools; $(MAKE) install
+ -cd man; $(MAKE) install
+ for i in $(OTHERLIBRARIES); do \
+ (cd otherlibs/$$i; $(MAKE) install) || exit $$?; \
+ done
+ if test -n "$(WITH_OCAMLDOC)"; then (cd ocamldoc; $(MAKE) install); else :; fi
+ if test -n "$(WITH_DEBUGGER)"; then (cd debugger; $(MAKE) install); \
+ else :; fi
+ if test -n "$(WITH_OCAMLBUILD)"; then (cd ocamlbuild; $(MAKE) install); \
+ else :; fi
+ cp config/Makefile $(INSTALL_LIBDIR)/Makefile.config
+ if test -f ocamlopt; then $(MAKE) installopt; else :; fi
+
+# Installation of the native-code compiler
+installopt:
+ cd asmrun; $(MAKE) install
+ cp ocamlopt $(INSTALL_BINDIR)/ocamlopt$(EXE)
+ cd stdlib; $(MAKE) installopt
+ cp asmcomp/*.cmi asmcomp/*.cmt asmcomp/*.cmti $(INSTALL_COMPLIBDIR)
+ cp compilerlibs/ocamloptcomp.cma $(OPTSTART) $(INSTALL_COMPLIBDIR)
+ if test -n "$(WITH_OCAMLDOC)"; then (cd ocamldoc; $(MAKE) installopt); \
+ else :; fi
+ if test -n "$(WITH_OCAMLBUILD)"; then (cd ocamlbuild; $(MAKE) installopt); \
+ else :; fi
+ for i in $(OTHERLIBRARIES); \
+ do (cd otherlibs/$$i; $(MAKE) installopt) || exit $$?; done
+ if test -f ocamlopt.opt ; then $(MAKE) installoptopt; fi
+ cd tools; $(MAKE) installopt
+
+installoptopt:
+ cp ocamlc.opt $(INSTALL_BINDIR)/ocamlc.opt$(EXE)
+ cp ocamlopt.opt $(INSTALL_BINDIR)/ocamlopt.opt$(EXE)
+ cp lex/ocamllex.opt $(INSTALL_BINDIR)/ocamllex.opt$(EXE)
+ cp compilerlibs/ocamlcommon.cmxa compilerlibs/ocamlcommon.a \
+ compilerlibs/ocamlbytecomp.cmxa compilerlibs/ocamlbytecomp.a \
+ compilerlibs/ocamloptcomp.cmxa compilerlibs/ocamloptcomp.a \
+ $(BYTESTART:.cmo=.cmx) $(BYTESTART:.cmo=.o) \
+ $(OPTSTART:.cmo=.cmx) $(OPTSTART:.cmo=.o) \
+ $(INSTALL_COMPLIBDIR)
+ cd $(INSTALL_COMPLIBDIR) && $(RANLIB) ocamlcommon.a ocamlbytecomp.a \
+ ocamloptcomp.a
+
+# Run all tests
+
+tests: opt.opt
+ cd testsuite; $(MAKE) clean && $(MAKE) all
+
+# The clean target
+
+clean:: partialclean
+
+# Shared parts of the system
+
+compilerlibs/ocamlcommon.cma: $(COMMON)
+ $(CAMLC) -a -linkall -o $@ $(COMMON)
+partialclean::
+ rm -f compilerlibs/ocamlcommon.cma
+
+# The bytecode compiler
+
+compilerlibs/ocamlbytecomp.cma: $(BYTECOMP)
+ $(CAMLC) -a -o $@ $(BYTECOMP)
+partialclean::
+ rm -f compilerlibs/ocamlbytecomp.cma
+
+ocamlc: compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma $(BYTESTART)
+ $(CAMLC) $(LINKFLAGS) -compat-32 -o ocamlc \
+ compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma $(BYTESTART)
+
+# The native-code compiler
+
+compilerlibs/ocamloptcomp.cma: $(ASMCOMP)
+ $(CAMLC) -a -o $@ $(ASMCOMP)
+partialclean::
+ rm -f compilerlibs/ocamloptcomp.cma
+
+ocamlopt: compilerlibs/ocamlcommon.cma compilerlibs/ocamloptcomp.cma $(OPTSTART)
+ $(CAMLC) $(LINKFLAGS) -o ocamlopt \
+ compilerlibs/ocamlcommon.cma compilerlibs/ocamloptcomp.cma $(OPTSTART)
+
+partialclean::
+ rm -f ocamlopt
+
+# The toplevel
+
+compilerlibs/ocamltoplevel.cma: $(TOPLEVEL)
+ $(CAMLC) -a -o $@ $(TOPLEVEL)
+partialclean::
+ rm -f compilerlibs/ocamltoplevel.cma
+
+ocaml: compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma \
+ compilerlibs/ocamltoplevel.cma $(TOPLEVELSTART) expunge
+ $(CAMLC) $(LINKFLAGS) -linkall -o ocaml.tmp \
+ compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma \
+ compilerlibs/ocamltoplevel.cma $(TOPLEVELSTART)
+ - $(CAMLRUN) ./expunge ocaml.tmp ocaml $(PERVASIVES)
+ rm -f ocaml.tmp
+
+partialclean::
+ rm -f ocaml
+
+# The native toplevel
+
+ocamlnat: ocamlopt otherlibs/dynlink/dynlink.cmxa $(NATTOPOBJS:.cmo=.cmx)
+ $(CAMLOPT) $(LINKFLAGS) otherlibs/dynlink/dynlink.cmxa -o ocamlnat \
+ $(NATTOPOBJS:.cmo=.cmx) -linkall
+
+toplevel/opttoploop.cmx: otherlibs/dynlink/dynlink.cmxa
+
+otherlibs/dynlink/dynlink.cmxa: otherlibs/dynlink/natdynlink.ml
+ cd otherlibs/dynlink && $(MAKE) allopt
+
+# The configuration file
+
+utils/config.ml: utils/config.mlp config/Makefile
+ @rm -f utils/config.ml
+ sed -e 's|%%LIBDIR%%|$(LIBDIR)|' \
+ -e 's|%%BYTERUN%%|$(BINDIR)/ocamlrun|' \
+ -e 's|%%CCOMPTYPE%%|cc|' \
+ -e 's|%%BYTECC%%|$(BYTECC) $(BYTECCCOMPOPTS) $(SHAREDCCCOMPOPTS)|' \
+ -e 's|%%NATIVECC%%|$(NATIVECC) $(NATIVECCCOMPOPTS)|' \
+ -e '/c_compiler =/s| -Werror||' \
+ -e 's|%%PACKLD%%|$(PACKLD)|' \
+ -e 's|%%BYTECCLIBS%%|$(BYTECCLIBS)|' \
+ -e 's|%%NATIVECCLIBS%%|$(NATIVECCLIBS)|' \
+ -e 's|%%RANLIBCMD%%|$(RANLIBCMD)|' \
+ -e 's|%%ARCMD%%|$(ARCMD)|' \
+ -e 's|%%CC_PROFILE%%|$(CC_PROFILE)|' \
+ -e 's|%%ARCH%%|$(ARCH)|' \
+ -e 's|%%MODEL%%|$(MODEL)|' \
+ -e 's|%%SYSTEM%%|$(SYSTEM)|' \
+ -e 's|%%EXT_OBJ%%|.o|' \
+ -e 's|%%EXT_ASM%%|.s|' \
+ -e 's|%%EXT_LIB%%|.a|' \
+ -e 's|%%EXT_DLL%%|.so|' \
+ -e 's|%%SYSTHREAD_SUPPORT%%|$(SYSTHREAD_SUPPORT)|' \
+ -e 's|%%ASM%%|$(ASM)|' \
+ -e 's|%%ASM_CFI_SUPPORTED%%|$(ASM_CFI_SUPPORTED)|' \
+ -e 's|%%WITH_FRAME_POINTERS%%|$(WITH_FRAME_POINTERS)|' \
+ -e 's|%%MKDLL%%|$(MKDLL)|' \
+ -e 's|%%MKEXE%%|$(MKEXE)|' \
+ -e 's|%%MKMAINDLL%%|$(MKMAINDLL)|' \
+ -e 's|%%HOST%%|$(HOST)|' \
+ -e 's|%%TARGET%%|$(TARGET)|' \
+ utils/config.mlp > utils/config.ml
+
+partialclean::
+ rm -f utils/config.ml
+
+beforedepend:: utils/config.ml
+
+# The parser
+
+parsing/parser.mli parsing/parser.ml: parsing/parser.mly
+ $(CAMLYACC) $(YACCFLAGS) parsing/parser.mly
+
+partialclean::
+ rm -f parsing/parser.mli parsing/parser.ml parsing/parser.output
+
+beforedepend:: parsing/parser.mli parsing/parser.ml
+
+# The lexer
+
+parsing/lexer.ml: parsing/lexer.mll
+ $(CAMLLEX) parsing/lexer.mll
+
+partialclean::
+ rm -f parsing/lexer.ml
+
+beforedepend:: parsing/lexer.ml
+
+# Shared parts of the system compiled with the native-code compiler
+
+compilerlibs/ocamlcommon.cmxa: $(COMMON:.cmo=.cmx)
+ $(CAMLOPT) -a -linkall -o $@ $(COMMON:.cmo=.cmx)
+partialclean::
+ rm -f compilerlibs/ocamlcommon.cmxa compilerlibs/ocamlcommon.a
+
+# The bytecode compiler compiled with the native-code compiler
+
+compilerlibs/ocamlbytecomp.cmxa: $(BYTECOMP:.cmo=.cmx)
+ $(CAMLOPT) -a -o $@ $(BYTECOMP:.cmo=.cmx)
+partialclean::
+ rm -f compilerlibs/ocamlbytecomp.cmxa compilerlibs/ocamlbytecomp.a
+
+ocamlc.opt: compilerlibs/ocamlcommon.cmxa compilerlibs/ocamlbytecomp.cmxa \
+ $(BYTESTART:.cmo=.cmx)
+ $(CAMLOPT) $(LINKFLAGS) -ccopt "$(BYTECCLINKOPTS)" -o ocamlc.opt \
+ compilerlibs/ocamlcommon.cmxa compilerlibs/ocamlbytecomp.cmxa \
+ $(BYTESTART:.cmo=.cmx) -cclib "$(BYTECCLIBS)"
+
+partialclean::
+ rm -f ocamlc.opt
+
+# The native-code compiler compiled with itself
+
+compilerlibs/ocamloptcomp.cmxa: $(ASMCOMP:.cmo=.cmx)
+ $(CAMLOPT) -a -o $@ $(ASMCOMP:.cmo=.cmx)
+partialclean::
+ rm -f compilerlibs/ocamloptcomp.cmxa compilerlibs/ocamloptcomp.a
+
+ocamlopt.opt: compilerlibs/ocamlcommon.cmxa compilerlibs/ocamloptcomp.cmxa \
+ $(OPTSTART:.cmo=.cmx)
+ $(CAMLOPT) $(LINKFLAGS) -o ocamlopt.opt \
+ compilerlibs/ocamlcommon.cmxa compilerlibs/ocamloptcomp.cmxa \
+ $(OPTSTART:.cmo=.cmx)
+
+partialclean::
+ rm -f ocamlopt.opt
+
+$(COMMON:.cmo=.cmx) $(BYTECOMP:.cmo=.cmx) $(ASMCOMP:.cmo=.cmx): ocamlopt
+
+# The numeric opcodes
+
+bytecomp/opcodes.ml: byterun/caml/instruct.h
+ sed -n -e '/^enum/p' -e 's/,//g' -e '/^ /p' byterun/caml/instruct.h | \
+ awk -f tools/make-opcodes > bytecomp/opcodes.ml
+
+partialclean::
+ rm -f bytecomp/opcodes.ml
+
+beforedepend:: bytecomp/opcodes.ml
+
+# The predefined exceptions and primitives
+
+byterun/primitives:
+ cd byterun; $(MAKE) primitives
+
+bytecomp/runtimedef.ml: byterun/primitives byterun/caml/fail.h
+ (echo 'let builtin_exceptions = [|'; \
+ sed -n -e 's|.*/\* \("[A-Za-z_]*"\) \*/$$| \1;|p' byterun/caml/fail.h | \
+ sed -e '$$s/;$$//'; \
+ echo '|]'; \
+ echo 'let builtin_primitives = [|'; \
+ sed -e 's/.*/ "&";/' -e '$$s/;$$//' byterun/primitives; \
+ echo '|]') > bytecomp/runtimedef.ml
+
+partialclean::
+ rm -f bytecomp/runtimedef.ml
+
+beforedepend:: bytecomp/runtimedef.ml
+
+# Choose the right machine-dependent files
+
+asmcomp/arch.ml: asmcomp/$(ARCH)/arch.ml
+ ln -s $(ARCH)/arch.ml asmcomp/arch.ml
+
+partialclean::
+ rm -f asmcomp/arch.ml
+
+beforedepend:: asmcomp/arch.ml
+
+asmcomp/proc.ml: asmcomp/$(ARCH)/proc.ml
+ ln -s $(ARCH)/proc.ml asmcomp/proc.ml
+
+partialclean::
+ rm -f asmcomp/proc.ml
+
+beforedepend:: asmcomp/proc.ml
+
+asmcomp/selection.ml: asmcomp/$(ARCH)/selection.ml
+ ln -s $(ARCH)/selection.ml asmcomp/selection.ml
+
+partialclean::
+ rm -f asmcomp/selection.ml
+
+beforedepend:: asmcomp/selection.ml
+
+asmcomp/CSE.ml: asmcomp/$(ARCH)/CSE.ml
+ ln -s $(ARCH)/CSE.ml asmcomp/CSE.ml
+
+partialclean::
+ rm -f asmcomp/CSE.ml
+
+beforedepend:: asmcomp/CSE.ml
+
+asmcomp/reload.ml: asmcomp/$(ARCH)/reload.ml
+ ln -s $(ARCH)/reload.ml asmcomp/reload.ml
+
+partialclean::
+ rm -f asmcomp/reload.ml
+
+beforedepend:: asmcomp/reload.ml
+
+asmcomp/scheduling.ml: asmcomp/$(ARCH)/scheduling.ml
+ ln -s $(ARCH)/scheduling.ml asmcomp/scheduling.ml
+
+partialclean::
+ rm -f asmcomp/scheduling.ml
+
+beforedepend:: asmcomp/scheduling.ml
+
+# Preprocess the code emitters
+
+asmcomp/emit.ml: asmcomp/$(ARCH)/emit.mlp tools/cvt_emit
+ echo \# 1 \"$(ARCH)/emit.mlp\" > asmcomp/emit.ml
+ $(CAMLRUN) tools/cvt_emit < asmcomp/$(ARCH)/emit.mlp >> asmcomp/emit.ml \
+ || { rm -f asmcomp/emit.ml; exit 2; }
+
+partialclean::
+ rm -f asmcomp/emit.ml
+
+beforedepend:: asmcomp/emit.ml
+
+tools/cvt_emit: tools/cvt_emit.mll
+ cd tools && $(MAKE) cvt_emit
+
+# The "expunge" utility
+
+expunge: compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma \
+ toplevel/expunge.cmo
+ $(CAMLC) $(LINKFLAGS) -o expunge compilerlibs/ocamlcommon.cma \
+ compilerlibs/ocamlbytecomp.cma toplevel/expunge.cmo
+
+partialclean::
+ rm -f expunge
+
+# The runtime system for the bytecode compiler
+
+runtime:
+ cd byterun; $(MAKE) all
+ if test -f stdlib/libcamlrun.a; then :; else \
+ ln -s ../byterun/libcamlrun.a stdlib/libcamlrun.a; fi
+
+clean::
+ cd byterun; $(MAKE) clean
+ rm -f stdlib/libcamlrun.a
+ rm -f stdlib/caml
+
+alldepend::
+ cd byterun; $(MAKE) depend
+
+# The runtime system for the native-code compiler
+
+runtimeopt: makeruntimeopt
+ cp asmrun/libasmrun.a stdlib/libasmrun.a
+
+makeruntimeopt:
+ cd asmrun; $(MAKE) all
+
+clean::
+ cd asmrun; $(MAKE) clean
+ rm -f stdlib/libasmrun.a
+
+alldepend::
+ cd asmrun; $(MAKE) depend
+
+# The library
+
+library: ocamlc
+ cd stdlib; $(MAKE) all
+
+library-cross:
+ cd stdlib; $(MAKE) CAMLRUN=../byterun/ocamlrun all
+
+libraryopt:
+ cd stdlib; $(MAKE) allopt
+
+partialclean::
+ cd stdlib; $(MAKE) clean
+
+alldepend::
+ cd stdlib; $(MAKE) depend
+
+# The lexer and parser generators
+
+ocamllex: ocamlyacc ocamlc
+ cd lex; $(MAKE) all
+
+ocamllex.opt: ocamlopt
+ cd lex; $(MAKE) allopt
+
+partialclean::
+ cd lex; $(MAKE) clean
+
+alldepend::
+ cd lex; $(MAKE) depend
+
+ocamlyacc:
+ cd yacc; $(MAKE) all
+
+clean::
+ cd yacc; $(MAKE) clean
+
+# Tools
+
+ocamltools: ocamlc ocamlyacc ocamllex asmcomp/cmx_format.cmi \
+ asmcomp/printclambda.cmo
+ cd tools; $(MAKE) all
+
+ocamltoolsopt: ocamlopt
+ cd tools; $(MAKE) opt
+
+ocamltoolsopt.opt: ocamlc.opt ocamlyacc ocamllex asmcomp/cmx_format.cmi \
+ asmcomp/printclambda.cmx
+ cd tools; $(MAKE) opt.opt
+
+partialclean::
+ cd tools; $(MAKE) clean
+
+alldepend::
+ cd tools; $(MAKE) depend
+
+# OCamldoc
+
+ocamldoc: ocamlc ocamlyacc ocamllex otherlibraries
+ cd ocamldoc && $(MAKE) all
+
+ocamldoc.opt: ocamlc.opt ocamlyacc ocamllex
+ cd ocamldoc && $(MAKE) opt.opt
+
+# Documentation
+
+html_doc: ocamldoc
+ make -C ocamldoc html_doc
+ @echo "documentation is in ./ocamldoc/stdlib_html/"
+
+partialclean::
+ cd ocamldoc && $(MAKE) clean
+
+alldepend::
+ cd ocamldoc && $(MAKE) depend
+
+# The extra libraries
+
+otherlibraries: ocamltools
+ for i in $(OTHERLIBRARIES); do \
+ (cd otherlibs/$$i; $(MAKE) all) || exit $$?; \
+ done
+
+otherlibrariesopt:
+ for i in $(OTHERLIBRARIES); do \
+ (cd otherlibs/$$i; $(MAKE) allopt) || exit $$?; \
+ done
+
+partialclean::
+ for i in $(OTHERLIBRARIES); do \
+ (cd otherlibs/$$i && $(MAKE) partialclean); \
+ done
+
+clean::
+ for i in $(OTHERLIBRARIES); do (cd otherlibs/$$i && $(MAKE) clean); done
+
+alldepend::
+ for i in $(OTHERLIBRARIES); do (cd otherlibs/$$i; $(MAKE) depend); done
+
+# The replay debugger
+
+ocamldebugger: ocamlc ocamlyacc ocamllex otherlibraries
+ cd debugger; $(MAKE) all
+
+partialclean::
+ cd debugger; $(MAKE) clean
+
+alldepend::
+ cd debugger; $(MAKE) depend
+
+# Ocamlbuild
+
+ocamlbuild.byte: ocamlc otherlibraries
+ cd ocamlbuild && $(MAKE) all
+
+ocamlbuild.native: ocamlopt otherlibrariesopt
+ cd ocamlbuild && $(MAKE) allopt
+
+partialclean::
+ cd ocamlbuild && $(MAKE) clean
+
+alldepend::
+ cd ocamlbuild && $(MAKE) depend
+
+# Check that the stack limit is reasonable.
+
+checkstack:
+ @if $(MKEXE) -o tools/checkstack$(EXE) tools/checkstack.c; \
+ then tools/checkstack$(EXE); \
+ else :; \
+ fi
+ @rm -f tools/checkstack
+
+# Make clean in the test suite
+
+clean::
+ cd testsuite; $(MAKE) clean
+
+# Make MacOS X package
+
+package-macosx:
+ sudo rm -rf package-macosx/root
+ $(MAKE) PREFIX="`pwd`"/package-macosx/root install
+ tools/make-package-macosx
+ sudo rm -rf package-macosx/root
+
+clean::
+ rm -rf package-macosx/*.pkg package-macosx/*.dmg
+
+# Default rules
+
+.SUFFIXES: .ml .mli .cmo .cmi .cmx
+
+.ml.cmo:
+ $(CAMLC) $(COMPFLAGS) -c $<
+
+.mli.cmi:
+ $(CAMLC) $(COMPFLAGS) -c $<
+
+.ml.cmx:
+ $(CAMLOPT) $(COMPFLAGS) -c $<
+
+partialclean::
+ for d in utils parsing typing bytecomp asmcomp driver toplevel tools; \
+ do rm -f $$d/*.cm[ioxt] $$d/*.cmti $$d/*.annot $$d/*.[so] $$d/*~; done
+ rm -f *~
+
+depend: beforedepend
+ (for d in utils parsing typing bytecomp asmcomp driver toplevel; \
+ do $(CAMLDEP) $(DEPFLAGS) $$d/*.mli $$d/*.ml; \
+ done) > .depend
+
+alldepend:: depend
+
+distclean:
+ $(MAKE) clean
+ rm -f boot/ocamlrun boot/ocamlrun.exe boot/camlheader boot/ocamlyacc \
+ boot/*.cm* boot/libcamlrun.a
+ rm -f config/Makefile config/m.h config/s.h
+ rm -f tools/*.bak
+ rm -f ocaml ocamlc
+ rm -f testsuite/_log
+
+.PHONY: all backup bootstrap checkstack clean
+.PHONY: partialclean beforedepend alldepend cleanboot coldstart
+.PHONY: compare core coreall
+.PHONY: coreboot defaultentry depend distclean install installopt
+.PHONY: library library-cross libraryopt
+.PHONY: ocamlbuild.byte ocamlbuild.native ocamldebugger ocamldoc
+.PHONY: ocamldoc.opt ocamllex ocamllex.opt ocamltools ocamltoolsopt
+.PHONY: ocamltoolsopt.opt ocamlyacc opt-core opt opt.opt otherlibraries
+.PHONY: otherlibrariesopt package-macosx promote promote-cross
+.PHONY: restore runtime runtimeopt makeruntimeopt world world.opt
+
+include .depend
diff --git a/Makefile.nt b/Makefile.nt
new file mode 100644
index 0000000000..dd96f88d92
--- /dev/null
+++ b/Makefile.nt
@@ -0,0 +1,779 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# The main Makefile
+
+include config/Makefile
+CAMLRUN ?= boot/ocamlrun
+CAMLYACC ?= boot/ocamlyacc
+include stdlib/StdlibModules
+
+CAMLC=$(CAMLRUN) boot/ocamlc -nostdlib -I boot
+CAMLOPT=$(CAMLRUN) ./ocamlopt -nostdlib -I stdlib -I otherlibs/dynlink
+COMPFLAGS=-strict-sequence -w +33..39+48 -warn-error A -bin-annot $(INCLUDES)
+LINKFLAGS=
+YACCFLAGS=
+CAMLLEX=$(CAMLRUN) boot/ocamllex
+CAMLDEP=$(CAMLRUN) tools/ocamldep
+DEPFLAGS=$(INCLUDES)
+
+OCAMLBUILDBYTE=$(WITH_OCAMLBUILD:=.byte)
+OCAMLBUILDNATIVE=$(WITH_OCAMLBUILD:=.native)
+
+OCAMLDOC_OPT=$(WITH_OCAMLDOC:=.opt)
+
+INCLUDES=-I utils -I parsing -I typing -I bytecomp -I asmcomp -I driver \
+ -I toplevel
+
+UTILS=utils/misc.cmo utils/tbl.cmo utils/config.cmo \
+ utils/clflags.cmo utils/terminfo.cmo utils/ccomp.cmo utils/warnings.cmo \
+ utils/consistbl.cmo
+
+PARSING=parsing/location.cmo parsing/longident.cmo \
+ parsing/docstrings.cmo parsing/ast_helper.cmo \
+ parsing/syntaxerr.cmo parsing/parser.cmo \
+ parsing/lexer.cmo parsing/parse.cmo parsing/printast.cmo \
+ parsing/pprintast.cmo \
+ parsing/ast_mapper.cmo
+
+TYPING=typing/ident.cmo typing/path.cmo \
+ typing/primitive.cmo typing/types.cmo \
+ typing/btype.cmo typing/oprint.cmo \
+ typing/subst.cmo typing/predef.cmo \
+ typing/datarepr.cmo typing/cmi_format.cmo typing/env.cmo \
+ typing/typedtree.cmo typing/printtyped.cmo typing/ctype.cmo \
+ typing/printtyp.cmo typing/includeclass.cmo \
+ typing/mtype.cmo typing/envaux.cmo typing/includecore.cmo \
+ typing/typedtreeIter.cmo typing/typedtreeMap.cmo \
+ typing/tast_mapper.cmo \
+ typing/cmt_format.cmo \
+ typing/includemod.cmo typing/typetexp.cmo typing/parmatch.cmo \
+ typing/stypes.cmo typing/typecore.cmo \
+ typing/typedecl.cmo typing/typeclass.cmo \
+ typing/typemod.cmo typing/untypeast.cmo
+
+COMP=bytecomp/lambda.cmo bytecomp/printlambda.cmo \
+ bytecomp/typeopt.cmo bytecomp/switch.cmo bytecomp/matching.cmo \
+ bytecomp/translobj.cmo bytecomp/translcore.cmo \
+ bytecomp/translclass.cmo bytecomp/translmod.cmo \
+ bytecomp/simplif.cmo bytecomp/runtimedef.cmo \
+ driver/pparse.cmo driver/main_args.cmo \
+ driver/compenv.cmo driver/compmisc.cmo
+
+COMMON=$(UTILS) $(PARSING) $(TYPING) $(COMP)
+
+BYTECOMP=bytecomp/meta.cmo bytecomp/instruct.cmo bytecomp/bytegen.cmo \
+ bytecomp/printinstr.cmo bytecomp/opcodes.cmo bytecomp/emitcode.cmo \
+ bytecomp/bytesections.cmo bytecomp/dll.cmo bytecomp/symtable.cmo \
+ bytecomp/bytelink.cmo bytecomp/bytelibrarian.cmo bytecomp/bytepackager.cmo \
+ driver/errors.cmo driver/compile.cmo
+
+INTEL_ASM=\
+ asmcomp/x86_proc.cmo \
+ asmcomp/x86_dsl.cmo \
+ asmcomp/x86_gas.cmo \
+ asmcomp/x86_masm.cmo
+
+ARCH_SPECIFIC_ASMCOMP=
+ifeq ($(ARCH),i386)
+ARCH_SPECIFIC_ASMCOMP=$(INTEL_ASM)
+endif
+ifeq ($(ARCH),amd64)
+ARCH_SPECIFIC_ASMCOMP=$(INTEL_ASM)
+endif
+
+ASMCOMP=\
+ $(ARCH_SPECIFIC_ASMCOMP) \
+ asmcomp/arch.cmo asmcomp/debuginfo.cmo \
+ asmcomp/cmm.cmo asmcomp/printcmm.cmo \
+ asmcomp/reg.cmo asmcomp/mach.cmo asmcomp/proc.cmo \
+ asmcomp/clambda.cmo asmcomp/printclambda.cmo asmcomp/compilenv.cmo \
+ asmcomp/closure.cmo asmcomp/strmatch.cmo asmcomp/cmmgen.cmo \
+ asmcomp/printmach.cmo asmcomp/selectgen.cmo asmcomp/selection.cmo \
+ asmcomp/comballoc.cmo \
+ asmcomp/CSEgen.cmo asmcomp/CSE.cmo \
+ asmcomp/liveness.cmo \
+ asmcomp/spill.cmo asmcomp/split.cmo \
+ asmcomp/interf.cmo asmcomp/coloring.cmo \
+ asmcomp/reloadgen.cmo asmcomp/reload.cmo \
+ asmcomp/deadcode.cmo \
+ asmcomp/printlinear.cmo asmcomp/linearize.cmo \
+ asmcomp/schedgen.cmo asmcomp/scheduling.cmo \
+ asmcomp/emitaux.cmo asmcomp/emit.cmo asmcomp/asmgen.cmo \
+ asmcomp/asmlink.cmo asmcomp/asmlibrarian.cmo asmcomp/asmpackager.cmo \
+ driver/opterrors.cmo driver/optcompile.cmo
+
+TOPLEVEL=toplevel/genprintval.cmo toplevel/toploop.cmo \
+ toplevel/trace.cmo toplevel/topdirs.cmo toplevel/topmain.cmo
+
+BYTESTART=driver/main.cmo
+
+OPTSTART=driver/optmain.cmo
+
+TOPLEVELSTART=toplevel/topstart.cmo
+
+PERVASIVES=$(STDLIB_MODULES) outcometree topdirs toploop
+
+# For users who don't read the INSTALL file
+defaultentry:
+ @echo "Please refer to the installation instructions in file README.win32."
+
+# Recompile the system using the bootstrap compiler
+all: runtime ocamlc ocamllex ocamlyacc ocamltools library ocaml \
+ otherlibraries $(OCAMLBUILDBYTE) $(WITH_DEBUGGER) \
+ $(WITH_OCAMLDOC)
+
+# The compilation of ocaml will fail if the runtime has changed.
+# Never mind, just do make bootstrap to reach fixpoint again.
+
+# Compile everything the first time
+world: coldstart all
+
+# Core bootstrapping cycle
+coreboot:
+# Save the original bootstrap compiler
+ $(MAKEREC) backup
+# Promote the new compiler but keep the old runtime
+# This compiler runs on boot/ocamlrun and produces bytecode for
+# byterun/ocamlrun
+ $(MAKEREC) promote-cross
+# Rebuild ocamlc and ocamllex (run on byterun/ocamlrun)
+ $(MAKEREC) partialclean
+ $(MAKEREC) ocamlc ocamllex ocamltools
+# Rebuild the library (using byterun/ocamlrun ./ocamlc)
+ $(MAKEREC) library-cross
+# Promote the new compiler and the new runtime
+ $(MAKEREC) promote
+# Rebuild the core system
+ $(MAKEREC) partialclean
+ $(MAKEREC) core
+# Check if fixpoint reached
+ $(MAKEREC) compare
+
+# Do a complete bootstrapping cycle
+bootstrap:
+ $(MAKEREC) coreboot
+ $(MAKEREC) all
+ $(MAKEREC) compare
+
+LIBFILES=stdlib.cma std_exit.cmo *.cmi camlheader
+
+# Start up the system from the distribution compiler
+coldstart:
+ cd byterun ; $(MAKEREC) all
+ cp byterun/ocamlrun.exe boot/ocamlrun.exe
+ cd yacc ; $(MAKEREC) all
+ cp yacc/ocamlyacc.exe boot/ocamlyacc.exe
+ cd stdlib ; $(MAKEREC) COMPILER=../boot/ocamlc all
+ cd stdlib ; cp $(LIBFILES) ../boot
+
+# Build the core system: the minimum needed to make depend and bootstrap
+core: runtime ocamlc ocamllex ocamlyacc ocamltools library
+
+# Save the current bootstrap compiler
+MAXSAVED=boot/Saved/Saved.prev/Saved.prev/Saved.prev/Saved.prev/Saved.prev
+backup:
+ mkdir -p boot/Saved
+ if test -d $(MAXSAVED); then rm -r $(MAXSAVED); fi
+ mv boot/Saved boot/Saved.prev
+ mkdir boot/Saved
+ mv boot/Saved.prev boot/Saved/Saved.prev
+ cp boot/ocamlrun.exe boot/Saved/ocamlrun.exe
+ cd boot ; mv ocamlc ocamllex ocamldep ocamlyacc.exe Saved
+ cd boot ; cp $(LIBFILES) Saved
+
+# Promote the newly compiled system to the rank of cross compiler
+# (Runs on the old runtime, produces code for the new runtime)
+promote-cross:
+ cp ocamlc boot/ocamlc
+ cp lex/ocamllex boot/ocamllex
+ cp yacc/ocamlyacc.exe boot/ocamlyacc.exe
+ cp tools/ocamldep boot/ocamldep
+ cd stdlib ; cp $(LIBFILES) ../boot
+
+# Promote the newly compiled system to the rank of bootstrap compiler
+# (Runs on the new runtime, produces code for the new runtime)
+promote: promote-cross
+ cp byterun/ocamlrun.exe boot/ocamlrun.exe
+
+# Restore the saved bootstrap compiler if a problem arises
+restore:
+ cd boot/Saved ; mv * ..
+ rmdir boot/Saved
+ mv boot/Saved.prev boot/Saved
+
+# Check if fixpoint reached
+compare:
+ - cmp -i 4096 boot/ocamlc ocamlc
+ - cmp -i 4096 boot/ocamllex lex/ocamllex
+ - cmp -i 4096 boot/ocamldep tools/ocamldep
+
+# Remove old bootstrap compilers
+cleanboot:
+ rm -rf boot/Saved/Saved.prev/*
+
+# Compile the native-code compiler
+opt-core:
+ $(MAKEREC) runtimeopt
+ $(MAKEREC) ocamlopt
+ $(MAKEREC) libraryopt
+
+opt:
+ $(MAKEREC) opt-core
+ $(MAKEREC) otherlibrariesopt ocamltoolsopt
+
+# Native-code versions of the tools
+opt.opt: core opt-core ocamlc.opt all ocamlopt.opt ocamllex.opt \
+ ocamltoolsopt ocamltoolsopt.opt $(OCAMLBUILDNATIVE) $(OCAMLDOC_OPT)
+
+# Complete build using fast compilers
+world.opt: coldstart opt.opt
+
+# Installation
+
+COMPLIBDIR=$(LIBDIR)/compiler-libs
+
+INSTALL_BINDIR=$(DESTDIR)$(BINDIR)
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+INSTALL_COMPLIBDIR=$(DESTDIR)$(COMPLIBDIR)
+INSTALL_STUBLIBDIR=$(DESTDIR)$(STUBLIBDIR)
+INSTALL_MANDIR=$(DESTDIR)$(MANDIR)
+
+install: installbyt installopt
+
+installbyt:
+ mkdir -p $(INSTALL_BINDIR)
+ mkdir -p $(INSTALL_LIBDIR)
+ mkdir -p $(INSTALL_STUBLIBDIR)
+ mkdir -p $(INSTALL_COMPLIBDIR)
+ cp VERSION $(INSTALL_LIBDIR)/
+ cd byterun ; $(MAKEREC) install
+ cp ocamlc $(INSTALL_BINDIR)/ocamlc.exe
+ cp ocaml $(INSTALL_BINDIR)/ocaml.exe
+ cd stdlib ; $(MAKEREC) install
+ cp lex/ocamllex $(INSTALL_BINDIR)/ocamllex.exe
+ cp yacc/ocamlyacc.exe $(INSTALL_BINDIR)/ocamlyacc.exe
+ cp utils/*.cmi utils/*.cmt utils/*.cmti \
+ parsing/*.cmi parsing/*.cmt parsing/*.cmti \
+ typing/*.cmi typing/*.cmt typing/*.cmti \
+ bytecomp/*.cmi bytecomp/*.cmt bytecomp/*.cmti \
+ driver/*.cmi driver/*.cmt driver/*.cmti \
+ toplevel/*.cmi toplevel/*.cmt toplevel/*.cmti $(INSTALL_COMPLIBDIR)
+ cp compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma \
+ compilerlibs/ocamltoplevel.cma $(BYTESTART) $(TOPLEVELSTART) \
+ $(INSTALL_COMPLIBDIR)
+ cp expunge $(INSTALL_LIBDIR)/expunge.exe
+ cp toplevel/topdirs.cmi $(INSTALL_LIBDIR)
+ cd tools ; $(MAKEREC) install
+ for i in $(OTHERLIBRARIES); do \
+ $(MAKEREC) -C otherlibs/$$i install || exit $$?; \
+ done
+ if test -n "$(WITH_OCAMLDOC)"; then (cd ocamldoc; $(MAKEREC) install); \
+ else :; fi
+ if test -n "$(WITH_DEBUGGER)"; then (cd debugger; $(MAKEREC) install); \
+ else :; fi
+ if test -n "$(WITH_OCAMLBUILD)"; then (cd ocamlbuild; $(MAKE) install); \
+ else :; fi
+ cp config/Makefile $(INSTALL_LIBDIR)/Makefile.config
+ cp README $(INSTALL_DISTRIB)/Readme.general.txt
+ cp README.win32 $(INSTALL_DISTRIB)/Readme.windows.txt
+ cp LICENSE $(INSTALL_DISTRIB)/License.txt
+ cp Changes $(INSTALL_DISTRIB)/Changes.txt
+
+# Installation of the native-code compiler
+installopt:
+ cd asmrun ; $(MAKEREC) install
+ cp ocamlopt $(INSTALL_BINDIR)/ocamlopt.exe
+ cd stdlib ; $(MAKEREC) installopt
+ cp asmcomp/*.cmi asmcomp/*.cmt asmcomp/*.cmti $(INSTALL_COMPLIBDIR)
+ cp compilerlibs/ocamloptcomp.cma $(OPTSTART) $(INSTALL_COMPLIBDIR)
+ if test -n "$(WITH_OCAMLDOC)"; then (cd ocamldoc; $(MAKEREC) installopt); fi
+ if test -n "$(WITH_OCAMLBUILD)"; then (cd ocamlbuild; $(MAKE) installopt); \
+ else :; fi
+ for i in $(OTHERLIBRARIES); do \
+ $(MAKEREC) -C otherlibs/$$i installopt || exit $$?; \
+ done
+ if test -f ocamlopt.opt ; then $(MAKEREC) installoptopt; fi
+ cd tools; $(MAKEREC) installopt
+
+installoptopt:
+ cp ocamlc.opt $(INSTALL_BINDIR)/ocamlc.opt$(EXE)
+ cp ocamlopt.opt $(INSTALL_BINDIR)/ocamlopt.opt$(EXE)
+ cp lex/ocamllex.opt $(INSTALL_BINDIR)/ocamllex.opt$(EXE)
+ cp compilerlibs/ocamlcommon.cmxa compilerlibs/ocamlcommon.$(A) \
+ compilerlibs/ocamlbytecomp.cmxa compilerlibs/ocamlbytecomp.$(A) \
+ compilerlibs/ocamloptcomp.cmxa compilerlibs/ocamloptcomp.$(A) \
+ $(BYTESTART:.cmo=.cmx) $(BYTESTART:.cmo=.$(O)) \
+ $(OPTSTART:.cmo=.cmx) $(OPTSTART:.cmo=.$(O)) \
+ $(INSTALL_COMPLIBDIR)
+
+clean:: partialclean
+
+# The compiler
+
+compilerlibs/ocamlcommon.cma: $(COMMON)
+ $(CAMLC) -a -o $@ $(COMMON)
+partialclean::
+ rm -f compilerlibs/ocamlcommon.cma
+
+# The bytecode compiler
+
+compilerlibs/ocamlbytecomp.cma: $(BYTECOMP)
+ $(CAMLC) -a -o $@ $(BYTECOMP)
+partialclean::
+ rm -f compilerlibs/ocamlbytecomp.cma
+
+ocamlc: compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma $(BYTESTART)
+ $(CAMLC) $(LINKFLAGS) -compat-32 -o ocamlc compilerlibs/ocamlcommon.cma \
+ compilerlibs/ocamlbytecomp.cma $(BYTESTART)
+
+partialclean::
+ rm -f ocamlc
+
+# The native-code compiler
+
+compilerlibs/ocamloptcomp.cma: $(ASMCOMP)
+ $(CAMLC) -a -o $@ $(ASMCOMP)
+partialclean::
+ rm -f compilerlibs/ocamloptcomp.cma
+
+ocamlopt: compilerlibs/ocamlcommon.cma compilerlibs/ocamloptcomp.cma $(OPTSTART)
+ $(CAMLC) $(LINKFLAGS) -o ocamlopt \
+ compilerlibs/ocamlcommon.cma compilerlibs/ocamloptcomp.cma $(OPTSTART)
+
+partialclean::
+ rm -f ocamlopt
+
+# The toplevel
+
+compilerlibs/ocamltoplevel.cma: $(TOPLEVEL)
+ $(CAMLC) -a -o $@ $(TOPLEVEL)
+partialclean::
+ rm -f compilerlibs/ocamltoplevel.cma
+
+ocaml: compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma \
+ compilerlibs/ocamltoplevel.cma $(TOPLEVELSTART) expunge
+ $(CAMLC) $(LINKFLAGS) -linkall -o ocaml.tmp \
+ compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma \
+ compilerlibs/ocamltoplevel.cma $(TOPLEVELSTART)
+ - $(CAMLRUN) ./expunge ocaml.tmp ocaml $(PERVASIVES)
+ rm -f ocaml.tmp
+
+partialclean::
+ rm -f ocaml
+
+# The native toplevel
+
+ocamlnat: ocamlopt otherlibs/dynlink/dynlink.cmxa $(NATTOPOBJS:.cmo=.cmx)
+ $(CAMLOPT) $(LINKFLAGS) otherlibs/dynlink/dynlink.cmxa -o ocamlnat \
+ $(NATTOPOBJS:.cmo=.cmx) -linkall
+
+toplevel/opttoploop.cmx: otherlibs/dynlink/dynlink.cmxa
+
+otherlibs/dynlink/dynlink.cmxa: otherlibs/dynlink/natdynlink.ml
+ cd otherlibs/dynlink && $(MAKEREC) allopt
+
+
+# The configuration file
+
+utils/config.ml: utils/config.mlp config/Makefile
+ @rm -f utils/config.ml
+ sed -e "s|%%LIBDIR%%|$(LIBDIR)|" \
+ -e "s|%%BYTERUN%%|ocamlrun|" \
+ -e 's|%%CCOMPTYPE%%|$(CCOMPTYPE)|' \
+ -e "s|%%BYTECC%%|$(BYTECC) $(BYTECCCOMPOPTS)|" \
+ -e "s|%%NATIVECC%%|$(NATIVECC) $(NATIVECCCOMPOPTS)|" \
+ -e "s|%%PARTIALLD%%|$(PARTIALLD)|" \
+ -e "s|%%PACKLD%%|$(PACKLD)|" \
+ -e "s|%%BYTECCLIBS%%|$(BYTECCLIBS)|" \
+ -e "s|%%NATIVECCLIBS%%|$(NATIVECCLIBS)|" \
+ -e 's|%%RANLIBCMD%%|$(RANLIBCMD)|' \
+ -e 's|%%ARCMD%%|$(ARCMD)|' \
+ -e 's|%%BINUTILS_NM%%|$(BINUTILS_NM)|' \
+ -e 's|%%BINUTILS_OBJCOPY%%|$(BINUTILS_OBJCOPY)|' \
+ -e "s|%%ARCH%%|$(ARCH)|" \
+ -e "s|%%MODEL%%|$(MODEL)|" \
+ -e "s|%%SYSTEM%%|$(SYSTEM)|" \
+ -e "s|%%EXT_OBJ%%|.$(O)|" \
+ -e "s|%%EXT_ASM%%|.$(S)|" \
+ -e "s|%%EXT_LIB%%|.$(A)|" \
+ -e "s|%%EXT_DLL%%|.dll|" \
+ -e "s|%%SYSTHREAD_SUPPORT%%|true|" \
+ -e 's|%%ASM%%|$(ASM)|' \
+ -e 's|%%ASM_CFI_SUPPORTED%%|false|' \
+ -e 's|%%WITH_FRAME_POINTERS%%|false|' \
+ -e 's|%%MKDLL%%|$(MKDLL)|' \
+ -e 's|%%MKEXE%%|$(MKEXE)|' \
+ -e 's|%%MKMAINDLL%%|$(MKMAINDLL)|' \
+ -e 's|%%CC_PROFILE%%||' \
+ -e 's|%%HOST%%|$(HOST)|' \
+ -e 's|%%TARGET%%|$(TARGET)|' \
+ utils/config.mlp > utils/config.ml
+
+partialclean::
+ rm -f utils/config.ml
+
+beforedepend:: utils/config.ml
+
+# The parser
+
+parsing/parser.mli parsing/parser.ml: parsing/parser.mly
+ $(CAMLYACC) $(YACCFLAGS) parsing/parser.mly
+
+partialclean::
+ rm -f parsing/parser.mli parsing/parser.ml parsing/parser.output
+
+beforedepend:: parsing/parser.mli parsing/parser.ml
+
+# The lexer
+
+parsing/lexer.ml: parsing/lexer.mll
+ $(CAMLLEX) parsing/lexer.mll
+
+partialclean::
+ rm -f parsing/lexer.ml
+
+beforedepend:: parsing/lexer.ml
+
+# Shared parts of the system compiled with the native-code compiler
+
+compilerlibs/ocamlcommon.cmxa: $(COMMON:.cmo=.cmx)
+ $(CAMLOPT) -a -o $@ $(COMMON:.cmo=.cmx)
+partialclean::
+ rm -f compilerlibs/ocamlcommon.cmxa compilerlibs/ocamlcommon.$(A)
+
+# The bytecode compiler compiled with the native-code compiler
+
+compilerlibs/ocamlbytecomp.cmxa: $(BYTECOMP:.cmo=.cmx)
+ $(CAMLOPT) -a -o $@ $(BYTECOMP:.cmo=.cmx)
+partialclean::
+ rm -f compilerlibs/ocamlbytecomp.cmxa compilerlibs/ocamlbytecomp.$(A)
+
+ocamlc.opt: compilerlibs/ocamlcommon.cmxa compilerlibs/ocamlbytecomp.cmxa \
+ $(BYTESTART:.cmo=.cmx)
+ $(CAMLOPT) $(LINKFLAGS) -ccopt "$(BYTECCLINKOPTS)" -o ocamlc.opt \
+ compilerlibs/ocamlcommon.cmxa compilerlibs/ocamlbytecomp.cmxa \
+ $(BYTESTART:.cmo=.cmx) -cclib "$(BYTECCLIBS)"
+
+partialclean::
+ rm -f ocamlc.opt
+
+# The native-code compiler compiled with itself
+
+compilerlibs/ocamloptcomp.cmxa: $(ASMCOMP:.cmo=.cmx)
+ $(CAMLOPT) -a -o $@ $(ASMCOMP:.cmo=.cmx)
+partialclean::
+ rm -f compilerlibs/ocamloptcomp.cmxa compilerlibs/ocamloptcomp.$(A)
+
+ocamlopt.opt: compilerlibs/ocamlcommon.cmxa compilerlibs/ocamloptcomp.cmxa \
+ $(OPTSTART:.cmo=.cmx)
+ $(CAMLOPT) $(LINKFLAGS) -o ocamlopt.opt \
+ compilerlibs/ocamlcommon.cmxa compilerlibs/ocamloptcomp.cmxa \
+ $(OPTSTART:.cmo=.cmx)
+
+partialclean::
+ rm -f ocamlopt.opt
+
+$(COMMON:.cmo=.cmx) $(BYTECOMP:.cmo=.cmx) $(ASMCOMP:.cmo=.cmx): ocamlopt
+
+# The numeric opcodes
+
+bytecomp/opcodes.ml: byterun/caml/instruct.h
+ sed -n -e "/^enum/p" -e "s|,||g" -e "/^ /p" byterun/caml/instruct.h | \
+ gawk -f tools/make-opcodes > bytecomp/opcodes.ml
+
+partialclean::
+ rm -f bytecomp/opcodes.ml
+
+beforedepend:: bytecomp/opcodes.ml
+
+# The predefined exceptions and primitives
+
+byterun/primitives:
+ cd byterun ; $(MAKEREC) primitives
+
+bytecomp/runtimedef.ml: byterun/primitives byterun/caml/fail.h
+ (echo 'let builtin_exceptions = [|'; \
+ sed -n -e 's|.*/\* \("[A-Za-z_]*"\) \*/$$| \1;|p' byterun/caml/fail.h | \
+ sed -e '$$s/;$$//'; \
+ echo '|]'; \
+ echo 'let builtin_primitives = [|'; \
+ sed -e 's/.*/ "&";/' -e '$$s/;$$//' byterun/primitives; \
+ echo '|]') > bytecomp/runtimedef.ml
+
+partialclean::
+ rm -f bytecomp/runtimedef.ml
+
+beforedepend:: bytecomp/runtimedef.ml
+
+# Choose the right machine-dependent files
+
+asmcomp/arch.ml: asmcomp/$(ARCH)/arch.ml
+ cp asmcomp/$(ARCH)/arch.ml asmcomp/arch.ml
+
+partialclean::
+ rm -f asmcomp/arch.ml
+
+beforedepend:: asmcomp/arch.ml
+
+asmcomp/proc.ml: asmcomp/$(ARCH)/proc.ml
+ cp asmcomp/$(ARCH)/proc.ml asmcomp/proc.ml
+
+partialclean::
+ rm -f asmcomp/proc.ml
+
+beforedepend:: asmcomp/proc.ml
+
+asmcomp/selection.ml: asmcomp/$(ARCH)/selection.ml
+ cp asmcomp/$(ARCH)/selection.ml asmcomp/selection.ml
+
+partialclean::
+ rm -f asmcomp/selection.ml
+
+beforedepend:: asmcomp/selection.ml
+
+asmcomp/CSE.ml: asmcomp/$(ARCH)/CSE.ml
+ cp asmcomp/$(ARCH)/CSE.ml asmcomp/CSE.ml
+
+partialclean::
+ rm -f asmcomp/CSE.ml
+
+beforedepend:: asmcomp/CSE.ml
+
+asmcomp/reload.ml: asmcomp/$(ARCH)/reload.ml
+ cp asmcomp/$(ARCH)/reload.ml asmcomp/reload.ml
+
+partialclean::
+ rm -f asmcomp/reload.ml
+
+beforedepend:: asmcomp/reload.ml
+
+asmcomp/scheduling.ml: asmcomp/$(ARCH)/scheduling.ml
+ cp asmcomp/$(ARCH)/scheduling.ml asmcomp/scheduling.ml
+
+partialclean::
+ rm -f asmcomp/scheduling.ml
+
+beforedepend:: asmcomp/scheduling.ml
+
+# Preprocess the code emitters
+
+asmcomp/emit.ml: asmcomp/$(ARCH)/emit.mlp tools/cvt_emit
+ $(CAMLRUN) tools/cvt_emit < asmcomp/$(ARCH)/emit.mlp > asmcomp/emit.ml
+
+partialclean::
+ rm -f asmcomp/emit.ml
+
+beforedepend:: asmcomp/emit.ml
+
+tools/cvt_emit: tools/cvt_emit.mll
+ cd tools ; $(MAKEREC) cvt_emit
+
+# The "expunge" utility
+
+expunge: compilerlibs/ocamlcommon.cma compilerlibs/ocamlbytecomp.cma \
+ toplevel/expunge.cmo
+ $(CAMLC) $(LINKFLAGS) -o expunge compilerlibs/ocamlcommon.cma \
+ compilerlibs/ocamlbytecomp.cma toplevel/expunge.cmo
+
+partialclean::
+ rm -f expunge
+
+# The runtime system for the bytecode compiler
+
+runtime: makeruntime stdlib/libcamlrun.$(A)
+
+makeruntime:
+ cd byterun ; $(MAKEREC) all
+stdlib/libcamlrun.$(A): byterun/libcamlrun.$(A)
+ cp byterun/libcamlrun.$(A) stdlib/libcamlrun.$(A)
+clean::
+ cd byterun ; $(MAKEREC) clean
+ rm -f stdlib/libcamlrun.$(A)
+alldepend::
+ cd byterun ; $(MAKEREC) depend
+
+# The runtime system for the native-code compiler
+
+runtimeopt: makeruntimeopt stdlib/libasmrun.$(A)
+
+makeruntimeopt:
+ cd asmrun ; $(MAKEREC) all
+stdlib/libasmrun.$(A): asmrun/libasmrun.$(A)
+ cp asmrun/libasmrun.$(A) stdlib/libasmrun.$(A)
+clean::
+ cd asmrun ; $(MAKEREC) clean
+ rm -f stdlib/libasmrun.$(A)
+alldepend::
+ cd asmrun ; $(MAKEREC) depend
+
+# The library
+
+library:
+ cd stdlib ; $(MAKEREC) all
+library-cross:
+ cd stdlib ; $(MAKEREC) CAMLRUN=../byterun/ocamlrun all
+libraryopt:
+ cd stdlib ; $(MAKEREC) allopt
+partialclean::
+ cd stdlib ; $(MAKEREC) clean
+alldepend::
+ cd stdlib ; $(MAKEREC) depend
+
+# The lexer and parser generators
+
+ocamllex:
+ cd lex ; $(MAKEREC) all
+ocamllex.opt:
+ cd lex ; $(MAKEREC) allopt
+partialclean::
+ cd lex ; $(MAKEREC) clean
+alldepend::
+ cd lex ; $(MAKEREC) depend
+
+ocamlyacc:
+ cd yacc ; $(MAKEREC) all
+clean::
+ cd yacc ; $(MAKEREC) clean
+
+# Tools
+
+ocamltools: ocamlc ocamlyacc ocamllex asmcomp/cmx_format.cmi \
+ asmcomp/printclambda.cmo
+ cd tools ; $(MAKEREC) all
+
+ocamltoolsopt:
+ cd tools ; $(MAKEREC) opt
+
+ocamltoolsopt.opt: ocamlc.opt ocamlyacc ocamllex asmcomp/cmx_format.cmi \
+ asmcomp/printclambda.cmx
+ cd tools ; $(MAKEREC) opt.opt
+
+partialclean::
+ cd tools ; $(MAKEREC) clean
+alldepend::
+ cd tools ; $(MAKEREC) depend
+
+# OCamldoc
+
+ocamldoc:
+ cd ocamldoc ; $(MAKEREC) all
+ocamldoc.opt:
+ cd ocamldoc ; $(MAKEREC) opt.opt
+partialclean::
+ cd ocamldoc ; $(MAKEREC) clean
+alldepend::
+ cd ocamldoc ; $(MAKEREC) depend
+
+# The extra libraries
+
+otherlibraries:
+ for i in $(OTHERLIBRARIES); do \
+ $(MAKEREC) -C otherlibs/$$i all || exit $$?; \
+ done
+otherlibrariesopt:
+ for i in $(OTHERLIBRARIES); \
+ do $(MAKEREC) -C otherlibs/$$i allopt || exit $$?; \
+ done
+partialclean::
+ for i in $(OTHERLIBRARIES); \
+ do $(MAKEREC) -C otherlibs/$$i partialclean || exit $$?; \
+ done
+clean::
+ for i in $(OTHERLIBRARIES); do \
+ $(MAKEREC) -C otherlibs/$$i clean || exit $$?; \
+ done
+alldepend::
+ for i in $(OTHERLIBRARIES); do \
+ $(MAKEREC) -C otherlibs/$$i depend || exit $$?; \
+ done
+
+# The replay debugger
+
+ocamldebugger: ocamlc ocamlyacc ocamllex
+ cd debugger; $(MAKEREC) all
+partialclean::
+ cd debugger; $(MAKEREC) clean
+alldepend::
+ cd debugger; $(MAKEREC) depend
+
+# Ocamlbuild
+
+ocamlbuild.byte: ocamlc otherlibraries
+ cd ocamlbuild && $(MAKE) all
+
+ocamlbuild.native: ocamlopt otherlibrariesopt
+ cd ocamlbuild && $(MAKE) allopt
+
+partialclean::
+ cd ocamlbuild && $(MAKE) clean
+
+alldepend::
+ cd ocamlbuild && $(MAKE) depend
+
+# Make clean in the test suite
+
+clean::
+ cd testsuite; $(MAKE) clean
+
+# Default rules
+
+.SUFFIXES: .ml .mli .cmo .cmi .cmx
+
+.ml.cmo:
+ $(CAMLC) $(COMPFLAGS) -c $<
+
+.mli.cmi:
+ $(CAMLC) $(COMPFLAGS) -c $<
+
+.ml.cmx:
+ $(CAMLOPT) $(COMPFLAGS) -c $<
+
+partialclean::
+ rm -f utils/*.cm* utils/*.$(O) utils/*.$(S)
+ rm -f parsing/*.cm* parsing/*.$(O) parsing/*.$(S)
+ rm -f typing/*.cm* typing/*.$(O) typing/*.$(S)
+ rm -f bytecomp/*.cm* bytecomp/*.$(O) bytecomp/*.$(S)
+ rm -f asmcomp/*.cm* asmcomp/*.$(O) asmcomp/*.$(S)
+ rm -f driver/*.cm* driver/*.$(O) driver/*.$(S)
+ rm -f toplevel/*.cm* toplevel/*.$(O) toplevel/*.$(S)
+ rm -f tools/*.cm* tools/*.$(O) tools/*.$(S)
+
+depend: beforedepend
+ (for d in utils parsing typing bytecomp asmcomp driver toplevel; \
+ do $(CAMLDEP) $(DEPFLAGS) $$d/*.mli $$d/*.ml; \
+ done) > .depend
+
+alldepend:: depend
+
+distclean:
+ $(MAKEREC) clean
+ rm -f asmrun/.depend.nt byterun/.depend.nt
+ rm -f boot/ocamlrun boot/ocamlrun.exe boot/camlheader boot/ocamlyacc \
+ boot/*.cm* boot/libcamlrun.a
+ rm -f config/Makefile config/m.h config/s.h
+ rm -f tools/*.bak
+ rm -f ocaml ocamlc
+ rm -f testsuite/_log
+
+.PHONY: all backup bootstrap checkstack clean
+.PHONY: partialclean beforedepend alldepend cleanboot coldstart
+.PHONY: compare core coreall
+.PHONY: coreboot defaultentry depend distclean install installopt
+.PHONY: library library-cross libraryopt ocamlbuild-mixed-boot
+.PHONY: ocamlbuild.byte ocamlbuild.native ocamldebugger ocamldoc
+.PHONY: ocamldoc.opt ocamllex ocamllex.opt ocamltools ocamltoolsopt
+.PHONY: ocamltoolsopt.opt ocamlyacc opt-core opt opt.opt otherlibraries
+.PHONY: otherlibrariesopt promote promote-cross
+.PHONY: restore runtime runtimeopt makeruntimeopt world world.opt
+
+include .depend
diff --git a/README b/README
new file mode 100644
index 0000000000..093ad8edf1
--- /dev/null
+++ b/README
@@ -0,0 +1,130 @@
+OVERVIEW:
+
+OCaml is an implementation of the ML language, based on the Caml Light
+dialect extended with a complete class-based object system and a
+powerful module system in the style of Standard ML.
+
+OCaml comprises two compilers. One generates bytecode which is then
+interpreted by a C program. This compiler runs quickly, generates
+compact code with moderate memory requirements, and is portable to
+essentially any 32 or 64 bit Unix platform. Performance of generated
+programs is quite good for a bytecoded implementation. This compiler
+can be used either as a standalone, batch-oriented compiler that
+produces standalone programs, or as an interactive, toplevel-based
+system.
+
+The other compiler generates high-performance native code for a number
+of processors. Compilation takes longer and generates bigger code, but
+the generated programs deliver excellent performance, while retaining
+the moderate memory requirements of the bytecode compiler. The
+native-code compiler currently runs on the following platforms:
+
+Tier 1 (actively used and maintained by the core OCaml team):
+
+ AMD64 (Opteron) Linux, MacOS X, MS Windows
+ IA32 (Pentium) Linux, FreeBSD, MacOS X, MS Windows
+ PowerPC Linux, MacOS X
+ ARM Linux
+
+Tier 2 (maintained when possible, with help from users):
+
+ AMD64 FreeBSD, OpenBSD
+ IA32 (Pentium) NetBSD, OpenBSD, Solaris 9
+ PowerPC NetBSD
+ SPARC Solaris, Linux, NetBSD
+
+Other operating systems for the processors above have not been tested,
+but the compiler may work under other operating systems with little work.
+
+Before the introduction of objects, OCaml was known as Caml Special
+Light. OCaml is almost upwards compatible with Caml Special Light,
+except for a few additional reserved keywords that have forced some
+renaming of standard library functions.
+
+CONTENTS:
+
+ Changes what's new with each release
+ INSTALL instructions for installation
+ LICENSE license and copyright notice
+ Makefile main Makefile
+ README this file
+ README.win32 infos on the MS Windows ports of OCaml
+ asmcomp/ native-code compiler and linker
+ asmrun/ native-code runtime library
+ boot/ bootstrap compiler
+ bytecomp/ bytecode compiler and linker
+ byterun/ bytecode interpreter and runtime system
+ config/ autoconfiguration stuff
+ debugger/ source-level replay debugger
+ driver/ driver code for the compilers
+ emacs/ OCaml editing mode and debugger interface for GNU Emacs
+ lex/ lexer generator
+ maccaml/ the Macintosh GUI
+ ocamldoc/ documentation generator
+ otherlibs/ several external libraries
+ parsing/ syntax analysis
+ stdlib/ standard library
+ tools/ various utilities
+ toplevel/ interactive system
+ typing/ typechecking
+ utils/ utility libraries
+ yacc/ parser generator
+
+COPYRIGHT:
+
+All files marked "Copyright INRIA" in this distribution are copyright
+1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
+2007, 2008, 2009, 2010, 2011, 2012 Institut National de Recherche en
+Informatique et en Automatique (INRIA) and distributed under the
+conditions stated in file LICENSE.
+
+INSTALLATION:
+
+See the file INSTALL for installation instructions on Unix, Linux and
+MacOS X machines. For MS Windows, see README.win32.
+
+DOCUMENTATION:
+
+The OCaml manual is distributed in HTML, PDF, Postscript, DVI, and
+Emacs Info files. It is available on the World Wide Web, at
+
+ http://caml.inria.fr/
+
+AVAILABILITY:
+
+The complete OCaml distribution can be accessed at
+
+ http://caml.inria.fr/
+
+KEEPING IN TOUCH WITH THE CAML COMMUNITY:
+
+There exists a mailing list of users of the OCaml implementations
+developed at INRIA. The purpose of this list is to share
+experience, exchange ideas (and even code), and report on applications
+of the OCaml language. Messages can be written in English or in
+French. The list has more than 1000 subscribers.
+
+Messages to the list should be sent to:
+
+ caml-list@inria.fr
+
+You can subscribe to this list via the Web interface at
+
+ https://sympa-roc.inria.fr/wws/info/caml-list
+
+Archives of the list are available on the Web site above.
+
+The Usenet news groups comp.lang.ml and comp.lang.functional
+also contains discussions about the ML family of programming languages,
+including OCaml.
+
+BUG REPORTS AND USER FEEDBACK:
+
+Please report bugs using the Web interface to the bug-tracking system
+at http://caml.inria.fr/bin/caml-bugs
+
+To be effective, bug reports should include a complete program
+(preferably small) that exhibits the unexpected behavior, and the
+configuration you are using (machine type, etc).
+
+You can also contact the implementors directly at caml@inria.fr.
diff --git a/README.win32 b/README.win32
new file mode 100644
index 0000000000..2a207f3e25
--- /dev/null
+++ b/README.win32
@@ -0,0 +1,454 @@
+ Release notes on the MS Windows ports of OCaml
+ ----------------------------------------------
+
+There are no less than five ports of OCaml for MS Windows available:
+ - a native Win32 port, built with the Microsoft development tools;
+ - a native Win32 port, built with the 32-bit version of the gcc
+ compiler from the mingw-w64 project, packaged in Cygwin
+ (under the name mingw64-i686);
+ - a native Win32 port, built with the 64-bit version of the gcc
+ compiler from the mingw-w64 project, packaged in Cygwin
+ (under the name mingw64-x86_64);
+ - a port consisting of the Unix sources compiled under the Cygwin
+ Unix-like environment for Windows;
+ - a native Win64 port (64-bit Windows), built with the Microsoft
+ development tools.
+
+Here is a summary of the main differences between these ports:
+
+ Native MS Native MinGW Cygwin
+
+64 bits? Win32 or Win64 Win32 or Win64 Win32 only
+
+Third-party software required
+ - for base bytecode system none none none
+ - for ocamlc -custom MSVC Cygwin Cygwin
+ - for native-code generation MSVC+MASM Cygwin Cygwin
+
+Speed of bytecode interpreter 70% 100% 100%
+
+Replay debugger yes (**) yes (**) yes
+
+The Unix library partial partial full
+
+The Threads library yes yes yes
+
+The Graphics library yes yes no
+
+Restrictions on generated executables? none none yes (*)
+
+(*) Cygwin-generated .exe files refer to a DLL that is distributed under
+the GPL. Thus, these .exe files can only be distributed under a license
+that is compatible with the GPL. Executables generated by MSVC or by
+MinGW have no such restrictions.
+
+(**) The debugger is supported but the "replay" functions are not enabled.
+Other functions are available (step, goto, run...).
+
+The remainder of this document gives more information on each port.
+
+------------------------------------------------------------------------------
+
+ The native Win32 port built with Microsoft Windows SDK
+ ------------------------------------------------------
+
+REQUIREMENTS:
+
+This port runs under MS Windows 7 (32 and 64 bits), Vista, XP, and 2000.
+
+The base bytecode system (ocamlc, ocaml, ocamllex, ocamlyacc, ...)
+runs without any additional tools.
+
+The native-code compiler (ocamlopt) requires the Microsoft Windows SDK
+(item [1]) and the flexdll tool (item [2]).
+
+Statically linking OCaml bytecode with C code (ocamlc -custom) also requires
+items [1] and [2].
+
+
+INSTALLATION:
+
+The binary distribution is a self-installing executable archive.
+Just run it and it should install OCaml automatically.
+
+THIRD-PARTY SOFTWARE:
+
+[1] Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 Service Pack 1.
+ Can be downloaded for free from
+ http://www.microsoft.com/downloads/en/default.aspx
+ under the name "Microsoft Windows 7 SDK".
+
+[2] flexdll version 0.31 or later.
+ Can be downloaded from http://alain.frisch.fr/flexdll.html
+
+RECOMPILATION FROM THE SOURCES:
+
+The command-line tools can be recompiled from the Unix source
+distribution (ocaml-X.YY.Z.tar.gz), which also contains the files modified
+for Windows.
+
+You will need the following software components to perform the recompilation:
+- Windows NT, 2000, XP, Vista, or 7 (32 or 64 bits).
+- Items [1] and [2] from the list of recommended software above.
+- The Cygwin port of GNU tools, available from http://www.cygwin.com/
+ Install at least the following packages (and their dependencies):
+ diffutils, dos2unix, gcc-core, make, ncurses.
+
+First, you need to set up your cygwin environment for using the MS
+tools. The following assumes that you have installed [1], [2], and [3]
+in their default directories. If this is not the case, you will need
+to adjust the paths accordingly.
+
+ Open a Windows Command Prompt and enter the following command:
+ set PFPATH=C:\Program Files
+ If you are compiling on the 64-bit version of Windows 7, enter the
+ following instead:
+ set PFPATH=C:\Program Files (x86)
+
+ Then enter the following commands:
+ cd "%PFPATH%\Microsoft Visual Studio 9.0\VC\bin"
+ set FLEXDLLDIR=%PFPATH%\flexdll
+ vcvars32
+ echo VCPATH="`cygpath -p '%Path%'`" >C:\cygwin\tmp\msenv
+ echo LIBPATH="%LIBPATH%" >>C:\cygwin\tmp\msenv
+ echo INCLUDE="%INCLUDE%;%FLEXDLLDIR%" >>C:\cygwin\tmp\msenv
+ echo FLPATH="`cygpath '%FLEXDLLDIR%'`" >>C:\cygwin\tmp\msenv
+ echo PATH="$VCPATH:$FLPATH:$PATH" >>C:\cygwin\tmp\msenv
+ echo export PATH LIB LIBPATH INCLUDE >>C:\cygwin\tmp\msenv
+ echo export OCAMLBUILD_FIND=/usr/bin/find >>C:\cygwin\tmp\msenv
+
+ Open a Cygwin shell and enter the following commands:
+ tr -d '\r' </tmp/msenv >.msenv32
+ echo '. $HOME/.msenv32' >>.bashrc
+
+Now, close the Command Prompt and the shell and you're set up for
+using the MS tools under Cygwin.
+
+
+To recompile OCaml, start a new Cygwin shell and change to the top-level
+directory of the OCaml distribution. Then, do
+
+ cp config/m-nt.h config/m.h
+ cp config/s-nt.h config/s.h
+ cp config/Makefile.msvc config/Makefile
+
+Then, edit config/Makefile as needed, following the comments in this file.
+Normally, the only variable that need to be changed is
+ PREFIX where to install everything
+
+Finally, use "make -f Makefile.nt" to build the system, e.g.
+
+ make -f Makefile.nt world
+ make -f Makefile.nt bootstrap
+ make -f Makefile.nt opt
+ make -f Makefile.nt opt.opt
+ make -f Makefile.nt install
+
+NOTES:
+
+* The VC++ compiler does not implement "computed gotos", and therefore
+generates inefficient code for byterun/interp.c. Consequently, the
+performance of bytecode programs is about 2/3 of that obtained under
+Unix/GCC or Cygwin or Mingw on similar hardware.
+
+* Libraries available in this port: "num", "str", "threads", "graphics",
+and large parts of "unix".
+
+* The replay debugger is partially supported (no reverse execution).
+
+CREDITS:
+
+The initial port of Caml Special Light (the ancestor of OCaml) to
+Windows NT was done by Kevin Gallo at Microsoft Research, who kindly
+contributed his changes to the OCaml project.
+
+------------------------------------------------------------------------------
+
+ The native Win32 and Win64 ports built with Mingw
+ -------------------------------------------------
+
+REQUIREMENTS:
+
+Those ports run under MS Windows Seven, Vista, XP, and 2000.
+
+The base bytecode system (ocamlc, ocaml, ocamllex, ocamlyacc, ...)
+runs without any additional tools.
+
+The native-code compiler (ocamlopt), as well as static linking of
+OCaml bytecode with C code (ocamlc -custom), require
+the Cygwin development tools, available at
+ http://www.cygwin.com/
+and the flexdll tool, available at
+ http://alain.frisch.fr/flexdll.html
+You will need to install at least the following Cygwin packages for
+the 32-bit flavor (use the Setup tool from Cygwin):
+
+ mingw64-i686-binutils
+ mingw64-i686-gcc-core
+ mingw64-i686-runtime
+
+and the following packages for the 64-bit:
+
+ mingw64-x86_64-binutils
+ mingw64-x86_64-gcc-core
+ mingw64-x86_64-runtime
+
+NOTES:
+
+ - Do not use the Cygwin version of flexdll for this port.
+
+ - There is another 32-bit gcc compiler, from the MinGW.org
+ project, packaged in Cygwin under the name mingw-gcc.
+ It is not currently supported by flexdll and OCaml.
+
+ - The standard gcc compiler shipped with Cygwin used to
+ support a "-mno-cygwin" option, which turned the compiler
+ into a mingw compiler. This option was used
+ by previous versions of flexdll and OCaml, but it is no
+ longer available in recent version, hence the switch
+ to another toolchain packaged in Cygwin.
+
+ - The standalone mingw toolchain from the MinGW-w64 project
+ (http://mingw-w64.org/) is not supported. Please use the
+ version packaged in Cygwin instead.
+
+INSTALLATION:
+
+The binary distribution is a self-installing executable archive.
+Just run it and it should install OCaml automatically.
+
+
+RECOMPILATION FROM THE SOURCES:
+
+You will need the following software components to perform the recompilation:
+- Windows NT, 2000, XP, Vista, or Seven.
+- Cygwin: http://cygwin.com/
+ Install at least the following packages (and their dependencies, as
+ computed by Cygwin's setup.exe):
+
+ For both flavor of OCaml (32-bit and 64-bit):
+ diffutils
+ make
+ ncurses
+
+ For the 32 bit flavor of OCaml:
+ mingw64-i686-binutils
+ mingw64-i686-gcc-core
+ mingw64-i686-runtime
+
+ For the 64 bit flavor of OCaml:
+ mingw64-x86_64-binutils
+ mingw64-x86_64-gcc-core
+ mingw64-x86_64-runtime
+
+- The flexdll tool (see above). Do not forget to add the flexdll directory
+ to your PATH
+
+The standalone mingw toolchain from the MinGW-w64 project
+(http://mingw-w64.org/) is not supported. Please use the
+version packaged in Cygwin instead.
+
+Start a new Cygwin shell and unpack the source distribution
+(ocaml-X.YY.Z.tar.gz) with "tar xzf". Change to the top-level
+directory of the OCaml distribution. Then, do
+
+ cp config/m-nt.h config/m.h
+ cp config/s-nt.h config/s.h
+
+For a 32 bit OCaml:
+ cp config/Makefile.mingw config/Makefile
+
+For a 64 bit OCaml:
+ cp config/Makefile.mingw64 config/Makefile
+
+Then, edit config/Makefile as needed, following the comments in this file.
+Normally, the only variable that need to be changed is
+ PREFIX where to install everything
+
+Finally, use "make -f Makefile.nt" to build the system, e.g.
+
+ make -f Makefile.nt world
+ make -f Makefile.nt bootstrap
+ make -f Makefile.nt opt
+ make -f Makefile.nt opt.opt
+ make -f Makefile.nt install
+
+
+NOTES:
+
+* Libraries available in this port: "num", "str", "threads", "graphics",
+ and large parts of "unix".
+
+* The replay debugger is partially supported (no reverse execution).
+
+* The default Makefile.mingw and Makefile.mingw64 pass -static-libgcc to
+ the linker.
+ For more information on this topic:
+
+ http://gcc.gnu.org/onlinedocs/gcc-4.9.1/gcc/Link-Options.html#Link-Options
+ http://caml.inria.fr/mantis/view.php?id=6411
+
+------------------------------------------------------------------------------
+
+ The Cygwin port of OCaml
+ ------------------------
+
+REQUIREMENTS:
+
+This port requires the Cygwin environment from Cygnus/RedHat, which
+is freely available at:
+ http://www.cygwin.com/
+
+It also requires the flexdll tool, available at:
+ http://alain.frisch.fr/flexdll.html
+
+This port runs under all versions of MS Windows supported by Cygwin.
+
+
+INSTALLATION:
+
+We do not distribute binaries for this port, but they can be found
+in the Cygwin distribution (use the Setup tool from Cygwin and select
+the OCaml packages). Alternatively, recompile from the source distribution.
+
+
+RECOMPILATION FROM THE SOURCES:
+
+Before starting, make sure that the gcc version installed by cygwin
+is not 4.5.3 (it has a bug that affects OCaml). If needed, use cygwin's
+setup.exe to downgrade to 4.3.4.
+
+You will need to recompile (and install) flexdll from source with
+Cygwin's C compiler because the official binary version of flexdll
+doesn't handle Cygwin's symbolic links and sometimes fails to
+launch the C compiler.
+
+In order to recompile flexdll, you first need to configure, compile,
+and install OCaml without flexdll support (configure with options
+-no-shared-libs), then modify the flexdll Makefile to change
+line 51 from:
+ LINKFLAGS = -ccopt "-link version_res.o"
+to:
+ LINKFLAGS = -cclib version_res.o
+
+Then "make CHAINS=cygwin" and add the flexdll directory to your PATH.
+Make sure to add it before "/usr/bin" or you will get cygwin's flexlink.
+
+Then, in OCaml's source directory, type:
+ make clean
+ make distclean
+and follow the instructions for Unix machines given in the file INSTALL.
+
+
+NOTES:
+
+- There is a problem with cygwin's port of gcc version 4.5.3. You should
+ use cygwin's setup program to downgrade to 4.3.4 before compiling OCaml.
+- The replay debugger is fully supported.
+- When upgrading from 3.12.0 to 3.12.1, you will need to remove
+ /usr/local/bin/ocamlmktop.exe before typing "make install".
+- In order to use the "graph" library, you will need to use Cygwin's
+ setup.exe to install the xinit, and libX11-devel packages before compiling
+ OCaml.
+
+------------------------------------------------------------------------------
+
+ The native Win64 port built with Microsoft Windows SDK
+ ------------------------------------------------------
+
+REQUIREMENTS:
+
+This port runs under MS Windows XP 64, Windows Server 64, and
+Windows 7 64 on Intel64/AMD64 machines.
+
+The base bytecode system (ocamlc, ocaml, ocamllex, ocamlyacc, ...)
+runs without any additional tools.
+
+Statically linking OCaml bytecode with C code (ocamlc -custom) requires the
+Microsoft Platform SDK compiler (item [1] in the section
+"third-party software" below) and the flexdll tool (item [2]).
+
+The native-code compiler (ocamlopt) requires the Microsoft compiler
+and the Microsoft assembler MASM64 (item [1]) and the flexdll tool (item [2]).
+
+INSTALLATION:
+
+There is no binary distribution yet. Please compile from sources as
+described below.
+
+
+THIRD-PARTY SOFTWARE:
+
+[1] Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 Service Pack 1.
+ Can be downloaded for free from
+ http://www.microsoft.com/downloads/en/default.aspx
+ under the name "Microsoft Windows 7 SDK".
+
+[2] flexdll version 0.31 or later.
+ Can be downloaded from http://alain.frisch.fr/flexdll.html
+
+
+RECOMPILATION FROM THE SOURCES:
+
+The command-line tools can be recompiled from the Unix source
+distribution (ocaml-X.YZ.tar.gz), which also contains the files modified
+for Windows.
+
+You will need the following software components to perform the recompilation:
+- Windows XP 64, Windows Server 64, or Windows 7 64.
+- Items [1] and [2] from the list of recommended software above.
+- The Cygwin port of GNU tools, available from http://www.cygwin.com/
+ Install at least the following packages: diffutils, make, ncurses.
+
+First, you need to set up your cygwin environment for using the MS
+tools. The following assumes that you have installed [1] and [2]
+in their default directories. If this is not the case, you will need
+to adjust the paths accordingly.
+
+ Open a Windows Command Prompt and enter the following commands:
+ set PFPATH=C:\Program Files (x86)
+ cd "%PFPATH%\Microsoft Visual Studio 9.0\VC\bin"
+ vcvars64
+ echo VCPATH="`cygpath -p '%Path%'`" >C:\cygwin\tmp\msenv
+ echo LIBPATH="%LIBPATH%" >>C:\cygwin\tmp\msenv
+ echo FLPATH="`cygpath '%PFPATH%\flexdll'`" >>C:\cygwin\tmp\msenv
+ echo PATH="$VCPATH:$FLPATH:$PATH" >>C:\cygwin\tmp\msenv
+ echo export PATH LIB LIBPATH INCLUDE >>C:\cygwin\tmp\msenv
+ echo export OCAMLBUILD_FIND=/usr/bin/find >>C:\cygwin\tmp\msenv
+
+ Open a Cygwin shell and enter the following commands:
+ tr -d '\r' </tmp/msenv >.msenv64
+ echo '. $HOME/.msenv64' >>.bashrc
+
+Now, close the Command Prompt and the shell and you're set up for
+using the MS tools under Cygwin.
+
+
+To recompile OCaml, start a new Cygwin shell and change to the top-level
+directory of the OCaml distribution. Then, do
+
+ cp config/m-nt.h config/m.h
+ cp config/s-nt.h config/s.h
+ cp config/Makefile.msvc64 config/Makefile
+
+Then, edit config/Makefile as needed, following the comments in this file.
+Normally, the only variable that need to be changed is
+ PREFIX where to install everything
+
+Finally, use "make -f Makefile.nt" to build the system, e.g.
+
+ make -f Makefile.nt world
+ make -f Makefile.nt bootstrap
+ make -f Makefile.nt opt
+ make -f Makefile.nt opt.opt
+ make -f Makefile.nt install
+
+
+NOTES:
+
+* Libraries available in this port: "num", "str", "threads", "graphics",
+ and large parts of "unix".
+
+* The replay debugger is partially supported (no reverse execution).
+
+* The graphical browser ocamlbrowser is not supported.
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000000..5310f512b9
--- /dev/null
+++ b/VERSION
@@ -0,0 +1,4 @@
+4.03.0+dev10-2015-07-29
+
+# The version string is the first line of this file.
+# It must be in the format described in stdlib/sys.mli
diff --git a/asmcomp/.ignore b/asmcomp/.ignore
new file mode 100644
index 0000000000..8c24e74ad1
--- /dev/null
+++ b/asmcomp/.ignore
@@ -0,0 +1,7 @@
+emit.ml
+arch.ml
+proc.ml
+selection.ml
+reload.ml
+scheduling.ml
+CSE.ml
diff --git a/asmcomp/CSEgen.ml b/asmcomp/CSEgen.ml
new file mode 100644
index 0000000000..8e6e285d13
--- /dev/null
+++ b/asmcomp/CSEgen.ml
@@ -0,0 +1,334 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Common subexpression elimination by value numbering over extended
+ basic blocks. *)
+
+open Mach
+
+type valnum = int
+
+(* We maintain sets of equations of the form
+ valnums = operation(valnums)
+ plus a mapping from registers to valnums (value numbers). *)
+
+type rhs = operation * valnum array
+
+module Equations =
+ Map.Make(struct type t = rhs let compare = Pervasives.compare end)
+
+type numbering =
+ { num_next: int; (* next fresh value number *)
+ num_eqs: valnum array Equations.t; (* mapping rhs -> valnums *)
+ num_reg: valnum Reg.Map.t } (* mapping register -> valnum *)
+
+let empty_numbering =
+ { num_next = 0; num_eqs = Equations.empty; num_reg = Reg.Map.empty }
+
+(** Generate a fresh value number [v] and associate it to register [r].
+ Returns a pair [(n',v)] with the updated value numbering [n']. *)
+
+let fresh_valnum_reg n r =
+ let v = n.num_next in
+ ({n with num_next = v + 1; num_reg = Reg.Map.add r v n.num_reg}, v)
+
+(* Same, for a set of registers [rs]. *)
+
+let array_fold_transf (f: numbering -> 'a -> numbering * 'b) n (a: 'a array)
+ : numbering * 'b array =
+ match Array.length a with
+ | 0 -> (n, [||])
+ | 1 -> let (n', b) = f n a.(0) in (n', [|b|])
+ | l -> let b = Array.make l 0 and n = ref n in
+ for i = 0 to l - 1 do
+ let (n', x) = f !n a.(i) in
+ b.(i) <- x; n := n'
+ done;
+ (!n, b)
+
+let fresh_valnum_regs n rs =
+ array_fold_transf fresh_valnum_reg n rs
+
+(** [valnum_reg n r] returns the value number for the contents of
+ register [r]. If none exists, a fresh value number is returned
+ and associated with register [r]. The possibly updated numbering
+ is also returned. [valnum_regs] is similar, but for an array of
+ registers. *)
+
+let valnum_reg n r =
+ try
+ (n, Reg.Map.find r n.num_reg)
+ with Not_found ->
+ fresh_valnum_reg n r
+
+let valnum_regs n rs =
+ array_fold_transf valnum_reg n rs
+
+(* Look up the set of equations for an equation with the given rhs.
+ Return [Some res] if there is one, where [res] is the lhs. *)
+
+let find_equation n rhs =
+ try
+ Some(Equations.find rhs n.num_eqs)
+ with Not_found ->
+ None
+
+(* Find a register containing the given value number. *)
+
+let find_reg_containing n v =
+ Reg.Map.fold (fun r v' res -> if v' = v then Some r else res)
+ n.num_reg None
+
+(* Find a set of registers containing the given value numbers. *)
+
+let find_regs_containing n vs =
+ match Array.length vs with
+ | 0 -> Some [||]
+ | 1 -> begin match find_reg_containing n vs.(0) with
+ | None -> None
+ | Some r -> Some [|r|]
+ end
+ | l -> let rs = Array.make l Reg.dummy in
+ begin try
+ for i = 0 to l - 1 do
+ match find_reg_containing n vs.(i) with
+ | None -> raise Exit
+ | Some r -> rs.(i) <- r
+ done;
+ Some rs
+ with Exit ->
+ None
+ end
+
+(* Associate the given value number to the given result register,
+ without adding new equations. *)
+
+let set_known_reg n r v =
+ { n with num_reg = Reg.Map.add r v n.num_reg }
+
+(* Associate the given value numbers to the given result registers,
+ without adding new equations. *)
+
+let array_fold2 f n a1 a2 =
+ let l = Array.length a1 in
+ assert (l = Array.length a2);
+ let n = ref n in
+ for i = 0 to l - 1 do n := f !n a1.(i) a2.(i) done;
+ !n
+
+let set_known_regs n rs vs =
+ array_fold2 set_known_reg n rs vs
+
+(* Record the effect of a move: no new equations, but the result reg
+ maps to the same value number as the argument reg. *)
+
+let set_move n src dst =
+ let (n1, v) = valnum_reg n src in
+ { n1 with num_reg = Reg.Map.add dst v n1.num_reg }
+
+(* Record the equation [fresh valnums = rhs] and associate the given
+ result registers [rs] to [fresh valnums]. *)
+
+let set_fresh_regs n rs rhs =
+ let (n1, vs) = fresh_valnum_regs n rs in
+ { n1 with num_eqs = Equations.add rhs vs n.num_eqs }
+
+(* Forget everything we know about the given result registers,
+ which are receiving unpredictable values at run-time. *)
+
+let set_unknown_regs n rs =
+ { n with num_reg = Array.fold_right Reg.Map.remove rs n.num_reg }
+
+(* Keep only the equations satisfying the given predicate. *)
+
+let filter_equations pred n =
+ { n with num_eqs = Equations.filter (fun (op,_) res -> pred op) n.num_eqs }
+
+(* Forget everything we know about registers of type [Addr]. *)
+
+let kill_addr_regs n =
+ { n with num_reg =
+ Reg.Map.filter (fun r n -> r.Reg.typ <> Cmm.Addr) n.num_reg }
+
+(* Prepend a set of moves before [i] to assign [srcs] to [dsts]. *)
+
+let insert_single_move i src dst = instr_cons (Iop Imove) [|src|] [|dst|] i
+
+let insert_move srcs dsts i =
+ match Array.length srcs with
+ | 0 -> i
+ | 1 -> instr_cons (Iop Imove) srcs dsts i
+ | l -> (* Parallel move: first copy srcs into tmps one by one,
+ then copy tmps into dsts one by one *)
+ let tmps = Reg.createv_like srcs in
+ let i1 = array_fold2 insert_single_move i tmps dsts in
+ array_fold2 insert_single_move i1 srcs tmps
+
+(* Classification of operations *)
+
+type op_class =
+ | Op_pure (* pure arithmetic, produce one or several result *)
+ | Op_checkbound (* checkbound-style: no result, can raise an exn *)
+ | Op_load (* memory load *)
+ | Op_store of bool (* memory store, false = init, true = assign *)
+ | Op_other (* anything else that does not allocate nor store in memory *)
+
+class cse_generic = object (self)
+
+(* Default classification of operations. Can be overriden in
+ processor-specific files to classify specific operations better. *)
+
+method class_of_operation op =
+ match op with
+ | Imove | Ispill | Ireload -> assert false (* treated specially *)
+ | Iconst_int _ | Iconst_float _ | Iconst_symbol _
+ | Iconst_blockheader _ -> Op_pure
+ | Icall_ind | Icall_imm _ | Itailcall_ind | Itailcall_imm _
+ | Iextcall _ -> assert false (* treated specially *)
+ | Istackoffset _ -> Op_other
+ | Iload(_,_) -> Op_load
+ | Istore(_,_,asg) -> Op_store asg
+ | Ialloc _ -> assert false (* treated specially *)
+ | Iintop(Icheckbound) -> Op_checkbound
+ | Iintop _ -> Op_pure
+ | Iintop_imm(Icheckbound, _) -> Op_checkbound
+ | Iintop_imm(_, _) -> Op_pure
+ | Inegf | Iabsf | Iaddf | Isubf | Imulf | Idivf
+ | Ifloatofint | Iintoffloat -> Op_pure
+ | Ispecific _ -> Op_other
+
+(* Operations that are so cheap that it isn't worth factoring them. *)
+
+method is_cheap_operation op =
+ match op with
+ | Iconst_int _ | Iconst_blockheader _ -> true
+ | _ -> false
+
+(* Forget all equations involving memory loads. Performed after a
+ non-initializing store *)
+
+method private kill_loads n =
+ filter_equations (fun o -> self#class_of_operation o <> Op_load) n
+
+(* Perform CSE on the given instruction [i] and its successors.
+ [n] is the value numbering current at the beginning of [i]. *)
+
+method private cse n i =
+ match i.desc with
+ | Iend | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _)
+ | Iexit _ | Iraise _ ->
+ i
+ | Iop (Imove | Ispill | Ireload) ->
+ (* For moves, we associate the same value number to the result reg
+ as to the argument reg. *)
+ let n1 = set_move n i.arg.(0) i.res.(0) in
+ {i with next = self#cse n1 i.next}
+ | Iop (Icall_ind | Icall_imm _ | Iextcall _) ->
+ (* For function calls, we should at least forget:
+ - equations involving memory loads, since the callee can
+ perform arbitrary memory stores;
+ - equations involving arithmetic operations that can
+ produce [Addr]-typed derived pointers into the heap
+ (see below for Ialloc);
+ - mappings from hardware registers to value numbers,
+ since the callee does not preserve these registers.
+ That doesn't leave much usable information: checkbounds
+ could be kept, but won't be usable for CSE as one of their
+ arguments is always a memory load. For simplicity, we
+ just forget everything. *)
+ {i with next = self#cse empty_numbering i.next}
+ | Iop (Ialloc _) ->
+ (* For allocations, we must avoid extending the live range of a
+ pseudoregister across the allocation if this pseudoreg
+ is a derived heap pointer (a pointer into the heap that does
+ not point to the beginning of a Caml block). PR#6484 is an
+ example of this situation. Such pseudoregs have type [Addr].
+ Pseudoregs with types other than [Addr] can be kept.
+ Moreover, allocation can trigger the asynchronous execution
+ of arbitrary Caml code (finalizer, signal handler, context
+ switch), which can contain non-initializing stores.
+ Hence, all equations over loads must be removed. *)
+ let n1 = kill_addr_regs (self#kill_loads n) in
+ let n2 = set_unknown_regs n1 i.res in
+ {i with next = self#cse n2 i.next}
+ | Iop op ->
+ begin match self#class_of_operation op with
+ | Op_pure | Op_checkbound | Op_load ->
+ let (n1, varg) = valnum_regs n i.arg in
+ let n2 = set_unknown_regs n1 (Proc.destroyed_at_oper i.desc) in
+ begin match find_equation n1 (op, varg) with
+ | Some vres ->
+ (* This operation was computed earlier. *)
+ (* Are there registers that hold the results computed earlier? *)
+ begin match find_regs_containing n1 vres with
+ | Some res when (not (self#is_cheap_operation op))
+ && (not (Proc.regs_are_volatile res)) ->
+ (* We can replace res <- op args with r <- move res,
+ provided res are stable (non-volatile) registers.
+ If the operation is very cheap to compute, e.g.
+ an integer constant, don't bother. *)
+ let n3 = set_known_regs n1 i.res vres in
+ (* This is n1 above and not n2 because the move
+ does not destroy any regs *)
+ insert_move res i.res (self#cse n3 i.next)
+ | _ ->
+ (* We already computed the operation but lost its
+ results. Associate the result registers to
+ the result valnums of the previous operation. *)
+ let n3 = set_known_regs n2 i.res vres in
+ {i with next = self#cse n3 i.next}
+ end
+ | None ->
+ (* This operation produces a result we haven't seen earlier. *)
+ let n3 = set_fresh_regs n2 i.res (op, varg) in
+ {i with next = self#cse n3 i.next}
+ end
+ | Op_store false | Op_other ->
+ (* An initializing store or an "other" operation do not invalidate
+ any equations, but we do not know anything about the results. *)
+ let n1 = set_unknown_regs n (Proc.destroyed_at_oper i.desc) in
+ let n2 = set_unknown_regs n1 i.res in
+ {i with next = self#cse n2 i.next}
+ | Op_store true ->
+ (* A non-initializing store can invalidate
+ anything we know about prior loads. *)
+ let n1 = set_unknown_regs n (Proc.destroyed_at_oper i.desc) in
+ let n2 = set_unknown_regs n1 i.res in
+ let n3 = self#kill_loads n2 in
+ {i with next = self#cse n3 i.next}
+ end
+ (* For control structures, we set the numbering to empty at every
+ join point, but propagate the current numbering across fork points. *)
+ | Iifthenelse(test, ifso, ifnot) ->
+ let n1 = set_unknown_regs n (Proc.destroyed_at_oper i.desc) in
+ {i with desc = Iifthenelse(test, self#cse n1 ifso, self#cse n1 ifnot);
+ next = self#cse empty_numbering i.next}
+ | Iswitch(index, cases) ->
+ let n1 = set_unknown_regs n (Proc.destroyed_at_oper i.desc) in
+ {i with desc = Iswitch(index, Array.map (self#cse n1) cases);
+ next = self#cse empty_numbering i.next}
+ | Iloop(body) ->
+ {i with desc = Iloop(self#cse empty_numbering body);
+ next = self#cse empty_numbering i.next}
+ | Icatch(nfail, body, handler) ->
+ {i with desc = Icatch(nfail, self#cse n body,
+ self#cse empty_numbering handler);
+ next = self#cse empty_numbering i.next}
+ | Itrywith(body, handler) ->
+ {i with desc = Itrywith(self#cse n body,
+ self#cse empty_numbering handler);
+ next = self#cse empty_numbering i.next}
+
+method fundecl f =
+ {f with fun_body = self#cse empty_numbering f.fun_body}
+
+end
diff --git a/asmcomp/CSEgen.mli b/asmcomp/CSEgen.mli
new file mode 100644
index 0000000000..0b375ff571
--- /dev/null
+++ b/asmcomp/CSEgen.mli
@@ -0,0 +1,35 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Common subexpression elimination by value numbering over extended
+ basic blocks. *)
+
+type op_class =
+ | Op_pure (* pure, produce one result *)
+ | Op_checkbound (* checkbound-style: no result, can raise an exn *)
+ | Op_load (* memory load *)
+ | Op_store of bool (* memory store, false = init, true = assign *)
+ | Op_other (* anything else that does not allocate nor store in memory *)
+
+class cse_generic : object
+ (* The following methods can be overriden to handle processor-specific
+ operations. *)
+
+ method class_of_operation: Mach.operation -> op_class
+
+ method is_cheap_operation: Mach.operation -> bool
+ (* Operations that are so cheap that it isn't worth factoring them. *)
+
+ (* The following method is the entry point and should not be overridden *)
+ method fundecl: Mach.fundecl -> Mach.fundecl
+
+end
diff --git a/asmcomp/amd64/CSE.ml b/asmcomp/amd64/CSE.ml
new file mode 100644
index 0000000000..aee43d2bca
--- /dev/null
+++ b/asmcomp/amd64/CSE.ml
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* CSE for the AMD64 *)
+
+open Arch
+open Mach
+open CSEgen
+
+class cse = object (self)
+
+inherit cse_generic as super
+
+method! class_of_operation op =
+ match op with
+ | Ispecific spec ->
+ begin match spec with
+ | Ilea _ -> Op_pure
+ | Istore_int(_, _, is_asg) | Istore_symbol(_, _, is_asg) -> Op_store is_asg
+ | Ioffset_loc(_, _) -> Op_store true
+ | Ifloatarithmem _ | Ifloatsqrtf _ -> Op_load
+ | Ibswap _ | Isqrtf -> super#class_of_operation op
+ end
+ | _ -> super#class_of_operation op
+
+end
+
+let fundecl f =
+ (new cse)#fundecl f
diff --git a/asmcomp/amd64/arch.ml b/asmcomp/amd64/arch.ml
new file mode 100644
index 0000000000..b7b0b57b90
--- /dev/null
+++ b/asmcomp/amd64/arch.ml
@@ -0,0 +1,128 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Machine-specific command-line options *)
+
+let command_line_options =
+ [ "-fPIC", Arg.Set Clflags.pic_code,
+ " Generate position-independent machine code (default)";
+ "-fno-PIC", Arg.Clear Clflags.pic_code,
+ " Generate position-dependent machine code" ]
+
+(* Specific operations for the AMD64 processor *)
+
+open Format
+
+type addressing_mode =
+ Ibased of string * int (* symbol + displ *)
+ | Iindexed of int (* reg + displ *)
+ | Iindexed2 of int (* reg + reg + displ *)
+ | Iscaled of int * int (* reg * scale + displ *)
+ | Iindexed2scaled of int * int (* reg + reg * scale + displ *)
+
+type specific_operation =
+ Ilea of addressing_mode (* "lea" gives scaled adds *)
+ | Istore_int of nativeint * addressing_mode * bool
+ (* Store an integer constant *)
+ | Istore_symbol of string * addressing_mode * bool (* Store a symbol *)
+ | Ioffset_loc of int * addressing_mode (* Add a constant to a location *)
+ | Ifloatarithmem of float_operation * addressing_mode
+ (* Float arith operation with memory *)
+ | Ibswap of int (* endiannes conversion *)
+ | Isqrtf (* Float square root *)
+ | Ifloatsqrtf of addressing_mode (* Float square root from memory *)
+and float_operation =
+ Ifloatadd | Ifloatsub | Ifloatmul | Ifloatdiv
+
+(* Sizes, endianness *)
+
+let big_endian = false
+
+let size_addr = 8
+let size_int = 8
+let size_float = 8
+
+let allow_unaligned_access = true
+
+(* Behavior of division *)
+
+let division_crashes_on_overflow = true
+
+(* Operations on addressing modes *)
+
+let identity_addressing = Iindexed 0
+
+let offset_addressing addr delta =
+ match addr with
+ Ibased(s, n) -> Ibased(s, n + delta)
+ | Iindexed n -> Iindexed(n + delta)
+ | Iindexed2 n -> Iindexed2(n + delta)
+ | Iscaled(scale, n) -> Iscaled(scale, n + delta)
+ | Iindexed2scaled(scale, n) -> Iindexed2scaled(scale, n + delta)
+
+let num_args_addressing = function
+ Ibased(s, n) -> 0
+ | Iindexed n -> 1
+ | Iindexed2 n -> 2
+ | Iscaled(scale, n) -> 1
+ | Iindexed2scaled(scale, n) -> 2
+
+(* Printing operations and addressing modes *)
+
+let print_addressing printreg addr ppf arg =
+ match addr with
+ | Ibased(s, 0) ->
+ fprintf ppf "\"%s\"" s
+ | Ibased(s, n) ->
+ fprintf ppf "\"%s\" + %i" s n
+ | Iindexed n ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a%s" printreg arg.(0) idx
+ | Iindexed2 n ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a + %a%s" printreg arg.(0) printreg arg.(1) idx
+ | Iscaled(scale, n) ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a * %i%s" printreg arg.(0) scale idx
+ | Iindexed2scaled(scale, n) ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a + %a * %i%s" printreg arg.(0) printreg arg.(1) scale idx
+
+let print_specific_operation printreg op ppf arg =
+ match op with
+ | Ilea addr -> print_addressing printreg addr ppf arg
+ | Istore_int(n, addr, is_assign) ->
+ fprintf ppf "[%a] := %nd %s"
+ (print_addressing printreg addr) arg n
+ (if is_assign then "(assign)" else "(init)")
+ | Istore_symbol(lbl, addr, is_assign) ->
+ fprintf ppf "[%a] := \"%s\" %s"
+ (print_addressing printreg addr) arg lbl
+ (if is_assign then "(assign)" else "(init)")
+ | Ioffset_loc(n, addr) ->
+ fprintf ppf "[%a] +:= %i" (print_addressing printreg addr) arg n
+ | Isqrtf ->
+ fprintf ppf "sqrtf %a" printreg arg.(0)
+ | Ifloatsqrtf addr ->
+ fprintf ppf "sqrtf float64[%a]"
+ (print_addressing printreg addr) [|arg.(0)|]
+ | Ifloatarithmem(op, addr) ->
+ let op_name = function
+ | Ifloatadd -> "+f"
+ | Ifloatsub -> "-f"
+ | Ifloatmul -> "*f"
+ | Ifloatdiv -> "/f" in
+ fprintf ppf "%a %s float64[%a]" printreg arg.(0) (op_name op)
+ (print_addressing printreg addr)
+ (Array.sub arg 1 (Array.length arg - 1))
+ | Ibswap i ->
+ fprintf ppf "bswap_%i %a" i printreg arg.(0)
diff --git a/asmcomp/amd64/emit.mlp b/asmcomp/amd64/emit.mlp
new file mode 100644
index 0000000000..1e39a9490d
--- /dev/null
+++ b/asmcomp/amd64/emit.mlp
@@ -0,0 +1,1003 @@
+# 2 "asmcomp/amd64/emit.mlp"
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Emission of Intel x86_64 assembly code *)
+
+open Misc
+open Cmm
+open Arch
+open Proc
+open Reg
+open Mach
+open Linearize
+open Emitaux
+
+open X86_ast
+open X86_proc
+open X86_dsl
+
+(* [Branch_relaxation] is not used in this file, but is required by
+ emit.mlp files for certain other targets; the reference here ensures
+ that when releases are being prepared the .depend files are correct
+ for all targets. *)
+open! Branch_relaxation
+
+let _label s = D.label ~typ:QWORD s
+
+(* Override proc.ml *)
+
+let int_reg_name =
+ [| RAX; RBX; RDI; RSI; RDX; RCX; R8; R9;
+ R12; R13; R10; R11; RBP; |]
+
+let float_reg_name = Array.init 16 (fun i -> XMM i)
+
+let register_name r =
+ if r < 100 then Reg64 (int_reg_name.(r))
+ else Regf (float_reg_name.(r - 100))
+
+(* CFI directives *)
+
+let cfi_startproc () =
+ if Config.asm_cfi_supported then D.cfi_startproc ()
+
+let cfi_endproc () =
+ if Config.asm_cfi_supported then D.cfi_endproc ()
+
+let cfi_adjust_cfa_offset n =
+ if Config.asm_cfi_supported then D.cfi_adjust_cfa_offset n
+
+let emit_debug_info dbg =
+ emit_debug_info_gen dbg D.file D.loc
+
+let fp = Config.with_frame_pointers
+
+(* Tradeoff between code size and code speed *)
+
+let fastcode_flag = ref true
+
+let stack_offset = ref 0
+
+(* Layout of the stack frame *)
+
+let frame_required () =
+ fp || !contains_calls || num_stack_slots.(0) > 0 || num_stack_slots.(1) > 0
+
+let frame_size () = (* includes return address *)
+ if frame_required() then begin
+ let sz =
+ (!stack_offset + 8 * (num_stack_slots.(0) + num_stack_slots.(1)) + 8
+ + (if fp then 8 else 0))
+ in Misc.align sz 16
+ end else
+ !stack_offset + 8
+
+let slot_offset loc cl =
+ match loc with
+ | Incoming n -> frame_size() + n
+ | Local n ->
+ if cl = 0
+ then !stack_offset + n * 8
+ else !stack_offset + (num_stack_slots.(0) + n) * 8
+ | Outgoing n -> n
+
+(* Symbols *)
+
+let symbol_prefix = if system = S_macosx then "_" else ""
+
+let emit_symbol s = string_of_symbol symbol_prefix s
+
+(* Record symbols used and defined - at the end generate extern for those
+ used but not defined *)
+
+let symbols_defined = ref StringSet.empty
+let symbols_used = ref StringSet.empty
+
+let add_def_symbol s = symbols_defined := StringSet.add s !symbols_defined
+let add_used_symbol s = symbols_used := StringSet.add s !symbols_used
+
+let imp_table = Hashtbl.create 16
+
+let reset_imp_table () = Hashtbl.clear imp_table
+
+let get_imp_symbol s =
+ match Hashtbl.find imp_table s with
+ | exception Not_found ->
+ let imps = "__caml_imp_" ^ s in
+ Hashtbl.add imp_table s imps;
+ imps
+ | imps -> imps
+
+let emit_imp_table () =
+ let f s imps =
+ _label (emit_symbol imps);
+ D.qword (ConstLabel (emit_symbol s))
+ in
+ D.data();
+ D.comment "relocation table start";
+ D.align 8;
+ Hashtbl.iter f imp_table;
+ D.comment "relocation table end"
+
+let mem__imp s =
+ let imp_s = get_imp_symbol s in
+ mem64_rip QWORD (emit_symbol imp_s)
+
+let rel_plt s =
+ if windows && !Clflags.dlcode then mem__imp s
+ else
+ let use_plt =
+ match system with
+ | S_macosx | S_mingw64 | S_cygwin | S_win64 -> false
+ | _ -> !Clflags.dlcode
+ in
+ sym (if use_plt then emit_symbol s ^ "@PLT" else emit_symbol s)
+
+let emit_call s = I.call (rel_plt s)
+
+let emit_jump s = I.jmp (rel_plt s)
+
+let load_symbol_addr s arg =
+ if !Clflags.dlcode then
+ if windows then begin
+ (* I.mov (mem__imp s) arg (\* mov __caml_imp_foo(%rip), ... *\) *)
+ I.mov (sym (emit_symbol s)) arg (* movabsq $foo, ... *)
+ end else I.mov (mem64_rip QWORD (emit_symbol s ^ "@GOTPCREL")) arg
+ else if !Clflags.pic_code then
+ I.lea (mem64_rip NONE (emit_symbol s)) arg
+ else
+ I.mov (sym (emit_symbol s)) arg
+
+(* Output a label *)
+
+let emit_label lbl =
+ match system with
+ | S_win64 -> "L" ^ string_of_int lbl
+ | _ -> ".L" ^ string_of_int lbl
+
+let emit_data_label lbl =
+ match system with
+ | S_win64 -> "Ld" ^ string_of_int lbl
+ | _ -> ".Ld" ^ string_of_int lbl
+
+let label s = sym (emit_label s)
+
+let def_label s = D.label (emit_label s)
+
+let emit_Llabel fallthrough lbl =
+ if not fallthrough && !fastcode_flag then D.align 4;
+ def_label lbl
+
+(* Output a pseudo-register *)
+
+let reg = function
+ | { loc = Reg.Reg r } -> register_name r
+ | { loc = Stack s; typ = Float } as r ->
+ let ofs = slot_offset s (register_class r) in
+ mem64 REAL8 ofs RSP
+ | { loc = Stack s } as r ->
+ let ofs = slot_offset s (register_class r) in
+ mem64 QWORD ofs RSP
+ | { loc = Unknown } ->
+ assert false
+
+let reg64 = function
+ | { loc = Reg.Reg r } -> int_reg_name.(r)
+ | _ -> assert false
+
+
+let res i n = reg i.res.(n)
+
+let arg i n = reg i.arg.(n)
+
+(* Output a reference to the lower 8, 16 or 32 bits of a register *)
+
+let reg_low_8_name = Array.map (fun r -> Reg8L r) int_reg_name
+let reg_low_16_name = Array.map (fun r -> Reg16 r) int_reg_name
+let reg_low_32_name = Array.map (fun r -> Reg32 r) int_reg_name
+
+let emit_subreg tbl typ r =
+ match r.loc with
+ | Reg.Reg r when r < 13 -> tbl.(r)
+ | Stack s -> mem64 typ (slot_offset s (register_class r)) RSP
+ | _ -> assert false
+
+let arg8 i n = emit_subreg reg_low_8_name BYTE i.arg.(n)
+let arg16 i n = emit_subreg reg_low_16_name WORD i.arg.(n)
+let arg32 i n = emit_subreg reg_low_32_name DWORD i.arg.(n)
+let arg64 i n = reg64 i.arg.(n)
+
+let res16 i n = emit_subreg reg_low_16_name WORD i.res.(n)
+let res32 i n = emit_subreg reg_low_32_name DWORD i.res.(n)
+
+(* Output an addressing mode *)
+
+let addressing addr typ i n =
+ match addr with
+ | Ibased(s, ofs) ->
+ add_used_symbol s;
+ mem64_rip typ (emit_symbol s) ~ofs
+ | Iindexed d ->
+ mem64 typ d (arg64 i n)
+ | Iindexed2 d ->
+ mem64 typ ~base:(arg64 i n) d (arg64 i (n+1))
+ | Iscaled(2, d) ->
+ mem64 typ ~base:(arg64 i n) d (arg64 i n)
+ | Iscaled(scale, d) ->
+ mem64 typ ~scale d (arg64 i n)
+ | Iindexed2scaled(scale, d) ->
+ mem64 typ ~scale ~base:(arg64 i n) d (arg64 i (n+1))
+
+(* Record live pointers at call points -- see Emitaux *)
+
+let record_frame_label live dbg =
+ let lbl = new_label() in
+ let live_offset = ref [] in
+ Reg.Set.iter
+ (function
+ | {typ = Val; loc = Reg r} ->
+ live_offset := ((r lsl 1) + 1) :: !live_offset
+ | {typ = Val; loc = Stack s} as reg ->
+ live_offset := slot_offset s (register_class reg) :: !live_offset
+ | {typ = Addr} as r ->
+ Misc.fatal_error ("bad GC root " ^ Reg.name r)
+ | _ -> ()
+ )
+ live;
+ frame_descriptors :=
+ { fd_lbl = lbl;
+ fd_frame_size = frame_size();
+ fd_live_offset = !live_offset;
+ fd_debuginfo = dbg } :: !frame_descriptors;
+ lbl
+
+let record_frame live dbg =
+ let lbl = record_frame_label live dbg in
+ def_label lbl
+
+(* Record calls to the GC -- we've moved them out of the way *)
+
+type gc_call =
+ { gc_lbl: label; (* Entry label *)
+ gc_return_lbl: label; (* Where to branch after GC *)
+ gc_frame: label } (* Label of frame descriptor *)
+
+let call_gc_sites = ref ([] : gc_call list)
+
+let emit_call_gc gc =
+ def_label gc.gc_lbl;
+ emit_call "caml_call_gc";
+ def_label gc.gc_frame;
+ I.jmp (label gc.gc_return_lbl)
+
+(* Record calls to caml_ml_array_bound_error.
+ In -g mode, we maintain one call to caml_ml_array_bound_error
+ per bound check site. Without -g, we can share a single call. *)
+
+type bound_error_call =
+ { bd_lbl: label; (* Entry label *)
+ bd_frame: label } (* Label of frame descriptor *)
+
+let bound_error_sites = ref ([] : bound_error_call list)
+let bound_error_call = ref 0
+
+let bound_error_label dbg =
+ if !Clflags.debug then begin
+ let lbl_bound_error = new_label() in
+ let lbl_frame = record_frame_label Reg.Set.empty dbg in
+ bound_error_sites :=
+ { bd_lbl = lbl_bound_error; bd_frame = lbl_frame } :: !bound_error_sites;
+ lbl_bound_error
+ end else begin
+ if !bound_error_call = 0 then bound_error_call := new_label();
+ !bound_error_call
+ end
+
+let emit_call_bound_error bd =
+ def_label bd.bd_lbl;
+ emit_call "caml_ml_array_bound_error";
+ def_label bd.bd_frame
+
+let emit_call_bound_errors () =
+ List.iter emit_call_bound_error !bound_error_sites;
+ if !bound_error_call > 0 then begin
+ def_label !bound_error_call;
+ emit_call "caml_ml_array_bound_error"
+ end
+
+(* Names for instructions *)
+
+let instr_for_intop = function
+ | Iadd -> I.add
+ | Isub -> I.sub
+ | Imul -> (fun arg1 arg2 -> I.imul arg1 (Some arg2))
+ | Iand -> I.and_
+ | Ior -> I.or_
+ | Ixor -> I.xor
+ | Ilsl -> I.sal
+ | Ilsr -> I.shr
+ | Iasr -> I.sar
+ | _ -> assert false
+
+let instr_for_floatop = function
+ | Iaddf -> I.addsd
+ | Isubf -> I.subsd
+ | Imulf -> I.mulsd
+ | Idivf -> I.divsd
+ | _ -> assert false
+
+let instr_for_floatarithmem = function
+ | Ifloatadd -> I.addsd
+ | Ifloatsub -> I.subsd
+ | Ifloatmul -> I.mulsd
+ | Ifloatdiv -> I.divsd
+
+let cond = function
+ | Isigned Ceq -> E | Isigned Cne -> NE
+ | Isigned Cle -> LE | Isigned Cgt -> G
+ | Isigned Clt -> L | Isigned Cge -> GE
+ | Iunsigned Ceq -> E | Iunsigned Cne -> NE
+ | Iunsigned Cle -> BE | Iunsigned Cgt -> A
+ | Iunsigned Clt -> B | Iunsigned Cge -> AE
+
+(* Output an = 0 or <> 0 test. *)
+
+let output_test_zero arg =
+ match arg.loc with
+ | Reg.Reg _ -> I.test (reg arg) (reg arg)
+ | _ -> I.cmp (int 0) (reg arg)
+
+(* Output a floating-point compare and branch *)
+
+let emit_float_test cmp neg i lbl =
+ (* Effect of comisd on flags and conditional branches:
+ ZF PF CF cond. branches taken
+ unordered 1 1 1 je, jb, jbe, jp
+ > 0 0 0 jne, jae, ja
+ < 0 0 1 jne, jbe, jb
+ = 1 0 0 je, jae, jbe.
+ If FP traps are on (they are off by default),
+ comisd traps on QNaN and SNaN but ucomisd traps on SNaN only.
+ *)
+ match (cmp, neg) with
+ | (Ceq, false) | (Cne, true) ->
+ let next = new_label() in
+ I.ucomisd (arg i 1) (arg i 0);
+ I.jp (label next); (* skip if unordered *)
+ I.je lbl; (* branch taken if x=y *)
+ def_label next
+ | (Cne, false) | (Ceq, true) ->
+ I.ucomisd (arg i 1) (arg i 0);
+ I.jp lbl; (* branch taken if unordered *)
+ I.jne lbl (* branch taken if x<y or x>y *)
+ | (Clt, _) ->
+ I.comisd (arg i 0) (arg i 1);
+ if not neg then I.ja lbl (* branch taken if y>x i.e. x<y *)
+ else I.jbe lbl (* taken if unordered or y<=x i.e. !(x<y) *)
+ | (Cle, _) ->
+ I.comisd (arg i 0) (arg i 1);(* swap compare *)
+ if not neg then I.jae lbl (* branch taken if y>=x i.e. x<=y *)
+ else I.jb lbl (* taken if unordered or y<x i.e. !(x<=y) *)
+ | (Cgt, _) ->
+ I.comisd (arg i 1) (arg i 0);
+ if not neg then I.ja lbl (* branch taken if x>y *)
+ else I.jbe lbl (* taken if unordered or x<=y i.e. !(x>y) *)
+ | (Cge, _) ->
+ I.comisd (arg i 1) (arg i 0);(* swap compare *)
+ if not neg then I.jae lbl (* branch taken if x>=y *)
+ else I.jb lbl (* taken if unordered or x<y i.e. !(x>=y) *)
+
+(* Deallocate the stack frame before a return or tail call *)
+
+let output_epilogue f =
+ if frame_required() then begin
+ let n = frame_size() - 8 - (if fp then 8 else 0) in
+ if n <> 0
+ then begin
+ I.add (int n) rsp;
+ cfi_adjust_cfa_offset (-n);
+ end;
+ if fp then I.pop rbp;
+ f ();
+ (* reset CFA back cause function body may continue *)
+ if n <> 0
+ then cfi_adjust_cfa_offset n
+ end
+ else
+ f ()
+
+(* Floating-point constants *)
+
+let float_constants = ref ([] : (int64 * int) list)
+
+let add_float_constant cst =
+ let repr = Int64.bits_of_float cst in
+ try
+ List.assoc repr !float_constants
+ with Not_found ->
+ let lbl = new_label() in
+ float_constants := (repr, lbl) :: !float_constants;
+ lbl
+
+let emit_float_constant f lbl =
+ _label (emit_label lbl);
+ D.qword (Const f)
+
+let emit_global_label s =
+ let lbl = Compilenv.make_symbol (Some s) in
+ add_def_symbol lbl;
+ let lbl = emit_symbol lbl in
+ D.global lbl;
+ _label lbl
+
+
+(* Output the assembly code for an instruction *)
+
+(* Name of current function *)
+let function_name = ref ""
+(* Entry point for tail recursive calls *)
+let tailrec_entry_point = ref 0
+
+(* Emit an instruction *)
+let emit_instr fallthrough i =
+ emit_debug_info i.dbg;
+ match i.desc with
+ | Lend -> ()
+ | Lop(Imove | Ispill | Ireload) ->
+ let src = i.arg.(0) and dst = i.res.(0) in
+ if src.loc <> dst.loc then
+ begin match src.typ, src.loc, dst.loc with
+ | Float, Reg.Reg _, Reg.Reg _ -> I.movapd (reg src) (reg dst)
+ | Float, _, _ -> I.movsd (reg src) (reg dst)
+ | _ -> I.mov (reg src) (reg dst)
+ end
+ | Lop(Iconst_int n | Iconst_blockheader n) ->
+ if n = 0n then begin
+ match i.res.(0).loc with
+ | Reg _ -> I.xor (res i 0) (res i 0)
+ | _ -> I.mov (int 0) (res i 0)
+ end
+ else
+ I.mov (nat n) (res i 0)
+ | Lop(Iconst_float f) ->
+ begin match Int64.bits_of_float f with
+ | 0x0000_0000_0000_0000L -> (* +0.0 *)
+ I.xorpd (res i 0) (res i 0)
+ | _ ->
+ let lbl = add_float_constant f in
+ I.movsd (mem64_rip NONE (emit_label lbl)) (res i 0)
+ end
+ | Lop(Iconst_symbol s) ->
+ add_used_symbol s;
+ load_symbol_addr s (res i 0)
+ | Lop(Icall_ind) ->
+ I.call (arg i 0);
+ record_frame i.live i.dbg
+ | Lop(Icall_imm s) ->
+ add_used_symbol s;
+ emit_call s;
+ record_frame i.live i.dbg
+ | Lop(Itailcall_ind) ->
+ output_epilogue begin fun () ->
+ I.jmp (arg i 0)
+ end
+ | Lop(Itailcall_imm s) ->
+ if s = !function_name then
+ I.jmp (label !tailrec_entry_point)
+ else begin
+ output_epilogue begin fun () ->
+ add_used_symbol s;
+ emit_jump s
+ end
+ end
+ | Lop(Iextcall(s, alloc)) ->
+ add_used_symbol s;
+ if alloc then begin
+ load_symbol_addr s rax;
+ emit_call "caml_c_call";
+ record_frame i.live i.dbg;
+ if system <> S_win64 then begin
+ (* TODO: investigate why such a diff.
+ This comes from:
+ http://caml.inria.fr/cgi-bin/viewvc.cgi?view=revision&revision=12664
+
+ If we do the same for Win64, we probably need to change
+ amd64nt.asm accordingly.
+ *)
+ load_symbol_addr "caml_young_ptr" r11;
+ I.mov (mem64 QWORD 0 R11) r15
+ end;
+ end else
+ emit_call s
+ | Lop(Istackoffset n) ->
+ if n < 0
+ then I.add (int (-n)) rsp
+ else if n > 0
+ then I.sub (int n) rsp;
+ if n <> 0
+ then cfi_adjust_cfa_offset n;
+ stack_offset := !stack_offset + n
+ | Lop(Iload(chunk, addr)) ->
+ let dest = res i 0 in
+ begin match chunk with
+ | Word_int | Word_val ->
+ I.mov (addressing addr QWORD i 0) dest
+ | Byte_unsigned ->
+ I.movzx (addressing addr BYTE i 0) dest
+ | Byte_signed ->
+ I.movsx (addressing addr BYTE i 0) dest
+ | Sixteen_unsigned ->
+ I.movzx (addressing addr WORD i 0) dest
+ | Sixteen_signed ->
+ I.movsx (addressing addr WORD i 0) dest;
+ | Thirtytwo_unsigned ->
+ I.mov (addressing addr DWORD i 0) (res32 i 0)
+ | Thirtytwo_signed ->
+ I.movsxd (addressing addr DWORD i 0) dest
+ | Single ->
+ I.cvtss2sd (addressing addr REAL4 i 0) dest
+ | Double | Double_u ->
+ I.movsd (addressing addr REAL8 i 0) dest
+ end
+ | Lop(Istore(chunk, addr, _)) ->
+ begin match chunk with
+ | Word_int | Word_val ->
+ I.mov (arg i 0) (addressing addr QWORD i 1)
+ | Byte_unsigned | Byte_signed ->
+ I.mov (arg8 i 0) (addressing addr BYTE i 1)
+ | Sixteen_unsigned | Sixteen_signed ->
+ I.mov (arg16 i 0) (addressing addr WORD i 1)
+ | Thirtytwo_signed | Thirtytwo_unsigned ->
+ I.mov (arg32 i 0) (addressing addr DWORD i 1)
+ | Single ->
+ I.cvtsd2ss (arg i 0) xmm15;
+ I.movss xmm15 (addressing addr REAL4 i 1)
+ | Double | Double_u ->
+ I.movsd (arg i 0) (addressing addr REAL8 i 1)
+ end
+ | Lop(Ialloc n) ->
+ if !fastcode_flag then begin
+ let lbl_redo = new_label() in
+ def_label lbl_redo;
+ I.sub (int n) r15;
+ if !Clflags.dlcode then begin
+ load_symbol_addr "caml_young_limit" rax;
+ I.cmp (mem64 QWORD 0 RAX) r15;
+ end else
+ I.cmp (mem64_rip QWORD (emit_symbol "caml_young_limit")) r15;
+ let lbl_call_gc = new_label() in
+ let lbl_frame = record_frame_label i.live Debuginfo.none in
+ I.jb (label lbl_call_gc);
+ I.lea (mem64 NONE 8 R15) (res i 0);
+ call_gc_sites :=
+ { gc_lbl = lbl_call_gc;
+ gc_return_lbl = lbl_redo;
+ gc_frame = lbl_frame } :: !call_gc_sites
+ end else begin
+ begin match n with
+ | 16 -> emit_call "caml_alloc1"
+ | 24 -> emit_call "caml_alloc2"
+ | 32 -> emit_call "caml_alloc3"
+ | _ ->
+ I.mov (int n) rax;
+ emit_call "caml_allocN"
+ end;
+ record_frame i.live Debuginfo.none;
+ I.lea (mem64 NONE 8 R15) (res i 0)
+ end
+ | Lop(Iintop(Icomp cmp)) ->
+ I.cmp (arg i 1) (arg i 0);
+ I.set (cond cmp) al;
+ I.movzx al (res i 0)
+ | Lop(Iintop_imm(Icomp cmp, n)) ->
+ I.cmp (int n) (arg i 0);
+ I.set (cond cmp) al;
+ I.movzx al (res i 0)
+ | Lop(Iintop Icheckbound) ->
+ let lbl = bound_error_label i.dbg in
+ I.cmp (arg i 1) (arg i 0);
+ I.jbe (label lbl)
+ | Lop(Iintop_imm(Icheckbound, n)) ->
+ let lbl = bound_error_label i.dbg in
+ I.cmp (int n) (arg i 0);
+ I.jbe (label lbl)
+ | Lop(Iintop(Idiv | Imod)) ->
+ I.cqo ();
+ I.idiv (arg i 1)
+ | Lop(Iintop(Ilsl | Ilsr | Iasr as op)) ->
+ (* We have i.arg.(0) = i.res.(0) and i.arg.(1) = %rcx *)
+ instr_for_intop op cl (res i 0)
+ | Lop(Iintop Imulh) ->
+ I.imul (arg i 1) None
+ | Lop(Iintop op) ->
+ (* We have i.arg.(0) = i.res.(0) *)
+ instr_for_intop op (arg i 1) (res i 0)
+ | Lop(Iintop_imm(Iadd, n)) when i.arg.(0).loc <> i.res.(0).loc ->
+ I.lea (mem64 NONE n (arg64 i 0)) (res i 0)
+ | Lop(Iintop_imm(Iadd, 1) | Iintop_imm(Isub, -1)) ->
+ I.inc (res i 0)
+ | Lop(Iintop_imm(Iadd, -1) | Iintop_imm(Isub, 1)) ->
+ I.dec (res i 0)
+ | Lop(Iintop_imm(op, n)) ->
+ (* We have i.arg.(0) = i.res.(0) *)
+ instr_for_intop op (int n) (res i 0)
+ | Lop(Inegf) ->
+ I.xorpd (mem64_rip OWORD (emit_symbol "caml_negf_mask")) (res i 0)
+ | Lop(Iabsf) ->
+ I.andpd (mem64_rip OWORD (emit_symbol "caml_absf_mask")) (res i 0)
+ | Lop(Iaddf | Isubf | Imulf | Idivf as floatop) ->
+ instr_for_floatop floatop (arg i 1) (res i 0)
+ | Lop(Ifloatofint) ->
+ I.cvtsi2sd (arg i 0) (res i 0)
+ | Lop(Iintoffloat) ->
+ I.cvttsd2si (arg i 0) (res i 0)
+ | Lop(Ispecific(Ilea addr)) ->
+ I.lea (addressing addr NONE i 0) (res i 0)
+ | Lop(Ispecific(Istore_int(n, addr, _))) ->
+ I.mov (nat n) (addressing addr QWORD i 0)
+ | Lop(Ispecific(Istore_symbol(s, addr, _))) ->
+ assert (not !Clflags.pic_code && not !Clflags.dlcode);
+ add_used_symbol s;
+ load_symbol_addr s (addressing addr QWORD i 0)
+ | Lop(Ispecific(Ioffset_loc(n, addr))) ->
+ I.add (int n) (addressing addr QWORD i 0)
+ | Lop(Ispecific(Ifloatarithmem(op, addr))) ->
+ instr_for_floatarithmem op (addressing addr REAL8 i 1) (res i 0)
+ | Lop(Ispecific(Ibswap 16)) ->
+ I.xchg ah al;
+ I.movzx (res16 i 0) (res i 0)
+ | Lop(Ispecific(Ibswap 32)) ->
+ I.bswap (res32 i 0);
+ I.movsxd (res32 i 0) (res i 0)
+ | Lop(Ispecific(Ibswap 64)) ->
+ I.bswap (res i 0)
+ | Lop(Ispecific(Ibswap _)) ->
+ assert false
+ | Lop(Ispecific Isqrtf) ->
+ I.sqrtsd (arg i 0) (res i 0)
+ | Lop(Ispecific(Ifloatsqrtf addr)) ->
+ I.sqrtsd (addressing addr REAL8 i 0) (res i 0)
+ | Lreloadretaddr ->
+ ()
+ | Lreturn ->
+ output_epilogue begin fun () ->
+ I.ret ()
+ end
+ | Llabel lbl ->
+ emit_Llabel fallthrough lbl
+ | Lbranch lbl ->
+ I.jmp (label lbl)
+ | Lcondbranch(tst, lbl) ->
+ let lbl = label lbl in
+ begin match tst with
+ | Itruetest ->
+ output_test_zero i.arg.(0);
+ I.jne lbl
+ | Ifalsetest ->
+ output_test_zero i.arg.(0);
+ I.je lbl
+ | Iinttest cmp ->
+ I.cmp (arg i 1) (arg i 0);
+ I.j (cond cmp) lbl
+ | Iinttest_imm((Isigned Ceq | Isigned Cne |
+ Iunsigned Ceq | Iunsigned Cne) as cmp, 0) ->
+ output_test_zero i.arg.(0);
+ I.j (cond cmp) lbl
+ | Iinttest_imm(cmp, n) ->
+ I.cmp (int n) (arg i 0);
+ I.j (cond cmp) lbl
+ | Ifloattest(cmp, neg) ->
+ emit_float_test cmp neg i lbl
+ | Ioddtest ->
+ I.test (int 1) (arg8 i 0);
+ I.jne lbl
+ | Ieventest ->
+ I.test (int 1) (arg8 i 0);
+ I.je lbl
+ end
+ | Lcondbranch3(lbl0, lbl1, lbl2) ->
+ I.cmp (int 1) (arg i 0);
+ begin match lbl0 with
+ | None -> ()
+ | Some lbl -> I.jb (label lbl)
+ end;
+ begin match lbl1 with
+ | None -> ()
+ | Some lbl -> I.je (label lbl)
+ end;
+ begin match lbl2 with
+ | None -> ()
+ | Some lbl -> I.jg (label lbl)
+ end
+ | Lswitch jumptbl ->
+ let lbl = emit_label (new_label()) in
+ (* rax and rdx are clobbered by the Lswitch,
+ meaning that no variable that is live across the Lswitch
+ is assigned to rax or rdx. However, the argument to Lswitch
+ can still be assigned to one of these two registers, so
+ we must be careful not to clobber it before use. *)
+ let (tmp1, tmp2) =
+ if i.arg.(0).loc = Reg 0 (* rax *)
+ then (phys_reg 4 (*rdx*), phys_reg 0 (*rax*))
+ else (phys_reg 0 (*rax*), phys_reg 4 (*rdx*)) in
+
+ I.lea (mem64_rip NONE lbl) (reg tmp1);
+ I.movsxd (mem64 DWORD 0 (arg64 i 0) ~scale:4 ~base:(reg64 tmp1))
+ (reg tmp2);
+ I.add (reg tmp2) (reg tmp1);
+ I.jmp (reg tmp1);
+
+ begin match system with
+ | S_macosx -> D.section ["__TEXT";"__const"] None []
+ | S_mingw64 | S_cygwin -> D.section [".rdata"] (Some "dr") []
+ | S_win64 -> () (* with MASM, use the text segment *)
+ | _ -> D.section [".rodata"] None []
+ end;
+ D.align 4;
+ _label lbl;
+ for i = 0 to Array.length jumptbl - 1 do
+ D.long (ConstSub (ConstLabel(emit_label jumptbl.(i)),
+ ConstLabel lbl))
+ done;
+ D.text ()
+ | Lsetuptrap lbl ->
+ I.call (label lbl)
+ | Lpushtrap ->
+ cfi_adjust_cfa_offset 8;
+ I.push r14;
+ cfi_adjust_cfa_offset 8;
+ I.mov rsp r14;
+ stack_offset := !stack_offset + 16
+ | Lpoptrap ->
+ I.pop r14;
+ cfi_adjust_cfa_offset (-8);
+ I.add (int 8) rsp;
+ cfi_adjust_cfa_offset (-8);
+ stack_offset := !stack_offset - 16
+ | Lraise k ->
+ begin match !Clflags.debug, k with
+ | true, Lambda.Raise_regular ->
+ emit_call "caml_raise_exn";
+ record_frame Reg.Set.empty i.dbg
+ | true, Lambda.Raise_reraise ->
+ emit_call "caml_reraise_exn";
+ record_frame Reg.Set.empty i.dbg
+ | false, _
+ | true, Lambda.Raise_notrace ->
+ I.mov r14 rsp;
+ I.pop r14;
+ I.ret ()
+ end
+
+let rec emit_all fallthrough i =
+ match i.desc with
+ | Lend -> ()
+ | _ ->
+ emit_instr fallthrough i;
+ emit_all (Linearize.has_fallthrough i.desc) i.next
+
+(* Emission of the profiling prelude *)
+
+let emit_profile () =
+ if system = S_gnu || system = S_linux then begin
+ (* mcount preserves rax, rcx, rdx, rsi, rdi, r8, r9 explicitly
+ and rbx, rbp, r12-r15 like all C functions. This includes
+ all the registers used for argument passing, so we don't
+ need to preserve other regs. We do need to initialize rbp
+ like mcount expects it, though. *)
+ I.push r10;
+ if not fp then I.mov rsp rbp;
+ emit_call "mcount";
+ I.pop r10
+ end
+
+(* Emission of a function declaration *)
+
+let fundecl fundecl =
+ function_name := fundecl.fun_name;
+ fastcode_flag := fundecl.fun_fast;
+ tailrec_entry_point := new_label();
+ stack_offset := 0;
+ call_gc_sites := [];
+ bound_error_sites := [];
+ bound_error_call := 0;
+ D.text ();
+ D.align 16;
+ add_def_symbol fundecl.fun_name;
+ if system = S_macosx
+ && not !Clflags.output_c_object
+ && is_generic_function fundecl.fun_name
+ then (* PR#4690 *)
+ D.private_extern (emit_symbol fundecl.fun_name)
+ else
+ D.global (emit_symbol fundecl.fun_name);
+ D.label (emit_symbol fundecl.fun_name);
+ emit_debug_info fundecl.fun_dbg;
+ cfi_startproc ();
+ if fp then begin
+ I.push rbp;
+ cfi_adjust_cfa_offset 8;
+ I.mov rsp rbp;
+ end;
+ if !Clflags.gprofile then emit_profile();
+ if frame_required() then begin
+ let n = frame_size() - 8 - (if fp then 8 else 0) in
+ if n <> 0
+ then begin
+ I.sub (int n) rsp;
+ cfi_adjust_cfa_offset n;
+ end;
+ end;
+ def_label !tailrec_entry_point;
+ emit_all true fundecl.fun_body;
+ List.iter emit_call_gc !call_gc_sites;
+ emit_call_bound_errors ();
+ cfi_endproc ();
+ begin match system with
+ | S_gnu | S_linux ->
+ D.type_ (emit_symbol fundecl.fun_name) "@function";
+ D.size (emit_symbol fundecl.fun_name)
+ (ConstSub (
+ ConstThis,
+ ConstLabel (emit_symbol fundecl.fun_name)))
+ | _ -> ()
+ end
+
+(* Emission of data *)
+
+let emit_item = function
+ | Cglobal_symbol s -> D.global (emit_symbol s)
+ | Cdefine_symbol s -> add_def_symbol s; _label (emit_symbol s)
+ | Cdefine_label lbl -> _label (emit_data_label lbl)
+ | Cint8 n -> D.byte (const n)
+ | Cint16 n -> D.word (const n)
+ | Cint32 n -> D.long (const_nat n)
+ | Cint n -> D.qword (const_nat n)
+ | Csingle f -> D.long (Const (Int64.of_int32 (Int32.bits_of_float f)))
+ | Cdouble f -> D.qword (Const (Int64.bits_of_float f))
+ | Csymbol_address s -> add_used_symbol s; D.qword (ConstLabel (emit_symbol s))
+ | Clabel_address lbl -> D.qword (ConstLabel (emit_data_label lbl))
+ | Cstring s -> D.bytes s
+ | Cskip n -> if n > 0 then D.space n
+ | Calign n -> D.align n
+
+let data l =
+ D.data ();
+ List.iter emit_item l
+
+(* Beginning / end of an assembly file *)
+
+let begin_assembly() =
+ X86_proc.reset_asm_code ();
+ reset_debug_info(); (* PR#5603 *)
+ reset_imp_table();
+ float_constants := [];
+ if system = S_win64 then begin
+ D.extrn "caml_young_ptr" QWORD;
+ D.extrn "caml_young_limit" QWORD;
+ D.extrn "caml_exception_pointer" QWORD;
+ D.extrn "caml_call_gc" NEAR;
+ D.extrn "caml_c_call" NEAR;
+ D.extrn "caml_allocN" NEAR;
+ D.extrn "caml_alloc1" NEAR;
+ D.extrn "caml_alloc2" NEAR;
+ D.extrn "caml_alloc3" NEAR;
+ D.extrn "caml_ml_array_bound_error" NEAR;
+ D.extrn "caml_raise_exn" NEAR;
+ D.extrn "caml_reraise_exn" NEAR;
+ end;
+
+
+ if !Clflags.dlcode then begin
+ (* from amd64.S; could emit these constants on demand *)
+ begin match system with
+ | S_macosx -> D.section ["__TEXT";"__literal16"] None ["16byte_literals"]
+ | S_mingw64 | S_cygwin -> D.section [".rdata"] (Some "dr") []
+ | S_win64 -> D.data ()
+ | _ -> D.section [".rodata.cst8"] (Some "a") ["@progbits"]
+ end;
+ D.align 16;
+ _label (emit_symbol "caml_negf_mask");
+ D.qword (Const 0x8000000000000000L);
+ D.qword (Const 0L);
+ D.align 16;
+ _label (emit_symbol "caml_absf_mask");
+ D.qword (Const 0x7FFFFFFFFFFFFFFFL);
+ D.qword (Const 0xFFFFFFFFFFFFFFFFL);
+ end;
+
+ D.data ();
+ emit_global_label "data_begin";
+
+ D.text ();
+ emit_global_label "code_begin";
+ if system = S_macosx then I.nop (); (* PR#4690 *)
+ ()
+
+let end_assembly() =
+ if !float_constants <> [] then begin
+ begin match system with
+ | S_macosx -> D.section ["__TEXT";"__literal8"] None ["8byte_literals"]
+ | S_mingw64 | S_cygwin -> D.section [".rdata"] (Some "dr") []
+ | S_win64 -> D.data ()
+ | _ -> D.section [".rodata.cst8"] (Some "a") ["@progbits"]
+ end;
+ List.iter (fun (cst,lbl) -> emit_float_constant cst lbl) !float_constants
+ end;
+
+ D.text ();
+ if system = S_macosx then I.nop ();
+ (* suppress "ld warning: atom sorting error" *)
+
+ emit_global_label "code_end";
+
+ emit_imp_table();
+
+ D.data ();
+ emit_global_label "data_end";
+ D.long (const 0);
+
+ emit_global_label "frametable";
+
+ let setcnt = ref 0 in
+ emit_frames
+ { efa_label = (fun l -> D.qword (ConstLabel (emit_label l)));
+ efa_16 = (fun n -> D.word (const n));
+ efa_32 = (fun n -> D.long (const_32 n));
+ efa_word = (fun n -> D.qword (const n));
+ efa_align = D.align;
+ efa_label_rel =
+ (fun lbl ofs ->
+ let c =
+ ConstAdd (
+ ConstSub(ConstLabel(emit_label lbl), ConstThis),
+ const_32 ofs
+ ) in
+ if system = S_macosx then begin
+ incr setcnt;
+ let s = Printf.sprintf "L$set$%d" !setcnt in
+ D.setvar (s, c);
+ D.long (ConstLabel s)
+ end else
+ D.long c
+ );
+ efa_def_label = (fun l -> _label (emit_label l));
+ efa_string = (fun s -> D.bytes (s ^ "\000"))
+ };
+
+ if system = S_linux then
+ (* Mark stack as non-executable, PR#4564 *)
+ D.section [".note.GNU-stack"] (Some "") [ "%progbits" ];
+
+ if system = S_win64 then begin
+ D.comment "External functions";
+ StringSet.iter
+ (fun s ->
+ if not (StringSet.mem s !symbols_defined) then
+ D.extrn (emit_symbol s) NEAR)
+ !symbols_used;
+ symbols_used := StringSet.empty;
+ symbols_defined := StringSet.empty;
+ end;
+
+ let asm =
+ if !Emitaux.create_asm_file then
+ Some
+ (
+ (if X86_proc.masm then X86_masm.generate_asm
+ else X86_gas.generate_asm) !Emitaux.output_channel
+ )
+ else
+ None
+ in
+ X86_proc.generate_code asm
diff --git a/asmcomp/amd64/proc.ml b/asmcomp/amd64/proc.ml
new file mode 100644
index 0000000000..a3aa9cfcbe
--- /dev/null
+++ b/asmcomp/amd64/proc.ml
@@ -0,0 +1,333 @@
+# 2 "asmcomp/amd64/proc.ml"
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Description of the AMD64 processor *)
+
+open Misc
+open Arch
+open Cmm
+open Reg
+open Mach
+
+let fp = Config.with_frame_pointers
+
+(* Which ABI to use *)
+
+let win64 =
+ match Config.system with
+ | "win64" | "mingw64" | "cygwin" -> true
+ | _ -> false
+
+(* Which asm conventions to use *)
+
+let masm =
+ match Config.ccomp_type with
+ | "msvc" -> true
+ | _ -> false
+
+(* Registers available for register allocation *)
+
+(* Register map:
+ rax 0
+ rbx 1
+ rdi 2
+ rsi 3
+ rdx 4
+ rcx 5
+ r8 6
+ r9 7
+ r12 8
+ r13 9
+ r10 10
+ r11 11
+ rbp 12
+ r14 trap pointer
+ r15 allocation pointer
+
+ xmm0 - xmm15 100 - 115 *)
+
+(* Conventions:
+ rax - r13: OCaml function arguments
+ rax: OCaml and C function results
+ xmm0 - xmm9: OCaml function arguments
+ xmm0: OCaml and C function results
+ Under Unix:
+ rdi, rsi, rdx, rcx, r8, r9: C function arguments
+ xmm0 - xmm7: C function arguments
+ rbx, rbp, r12-r15 are preserved by C
+ xmm registers are not preserved by C
+ Under Win64:
+ rcx, rdx, r8, r9: C function arguments
+ xmm0 - xmm3: C function arguments
+ rbx, rbp, rsi, rdi r12-r15 are preserved by C
+ xmm6-xmm15 are preserved by C
+ Note (PR#5707): r11 should not be used for parameter passing, as it
+ can be destroyed by the dynamic loader according to SVR4 ABI.
+ Linux's dynamic loader also destroys r10.
+*)
+
+let int_reg_name =
+ match Config.ccomp_type with
+ | "msvc" ->
+ [| "rax"; "rbx"; "rdi"; "rsi"; "rdx"; "rcx"; "r8"; "r9";
+ "r12"; "r13"; "r10"; "r11"; "rbp" |]
+ | _ ->
+ [| "%rax"; "%rbx"; "%rdi"; "%rsi"; "%rdx"; "%rcx"; "%r8"; "%r9";
+ "%r12"; "%r13"; "%r10"; "%r11"; "%rbp" |]
+
+let float_reg_name =
+ match Config.ccomp_type with
+ | "msvc" ->
+ [| "xmm0"; "xmm1"; "xmm2"; "xmm3"; "xmm4"; "xmm5"; "xmm6"; "xmm7";
+ "xmm8"; "xmm9"; "xmm10"; "xmm11";
+ "xmm12"; "xmm13"; "xmm14"; "xmm15" |]
+ | _ ->
+ [| "%xmm0"; "%xmm1"; "%xmm2"; "%xmm3"; "%xmm4"; "%xmm5"; "%xmm6"; "%xmm7";
+ "%xmm8"; "%xmm9"; "%xmm10"; "%xmm11";
+ "%xmm12"; "%xmm13"; "%xmm14"; "%xmm15" |]
+
+let num_register_classes = 2
+
+let register_class r =
+ match r.typ with
+ | Val | Int | Addr -> 0
+ | Float -> 1
+
+let num_available_registers = [| 13; 16 |]
+
+let first_available_register = [| 0; 100 |]
+
+let register_name r =
+ if r < 100 then int_reg_name.(r) else float_reg_name.(r - 100)
+
+(* Pack registers starting at %rax so as to reduce the number of REX
+ prefixes and thus improve code density *)
+let rotate_registers = false
+
+(* Representation of hard registers by pseudo-registers *)
+
+let hard_int_reg =
+ let v = Array.make 13 Reg.dummy in
+ for i = 0 to 12 do v.(i) <- Reg.at_location Int (Reg i) done;
+ v
+
+let hard_float_reg =
+ let v = Array.make 16 Reg.dummy in
+ for i = 0 to 15 do v.(i) <- Reg.at_location Float (Reg (100 + i)) done;
+ v
+
+let all_phys_regs =
+ Array.append hard_int_reg hard_float_reg
+
+let phys_reg n =
+ if n < 100 then hard_int_reg.(n) else hard_float_reg.(n - 100)
+
+let rax = phys_reg 0
+let rcx = phys_reg 5
+let rdx = phys_reg 4
+let rbp = phys_reg 12
+let rxmm15 = phys_reg 115
+
+let stack_slot slot ty =
+ Reg.at_location ty (Stack slot)
+
+(* Instruction selection *)
+
+let word_addressed = false
+
+(* Calling conventions *)
+
+let calling_conventions first_int last_int first_float last_float make_stack
+ arg =
+ let loc = Array.make (Array.length arg) Reg.dummy in
+ let int = ref first_int in
+ let float = ref first_float in
+ let ofs = ref 0 in
+ for i = 0 to Array.length arg - 1 do
+ match arg.(i).typ with
+ | Val | Int | Addr as ty ->
+ if !int <= last_int then begin
+ loc.(i) <- phys_reg !int;
+ incr int
+ end else begin
+ loc.(i) <- stack_slot (make_stack !ofs) ty;
+ ofs := !ofs + size_int
+ end
+ | Float ->
+ if !float <= last_float then begin
+ loc.(i) <- phys_reg !float;
+ incr float
+ end else begin
+ loc.(i) <- stack_slot (make_stack !ofs) Float;
+ ofs := !ofs + size_float
+ end
+ done;
+ (loc, Misc.align !ofs 16) (* keep stack 16-aligned *)
+
+let incoming ofs = Incoming ofs
+let outgoing ofs = Outgoing ofs
+let not_supported ofs = fatal_error "Proc.loc_results: cannot call"
+
+let loc_arguments arg =
+ calling_conventions 0 9 100 109 outgoing arg
+let loc_parameters arg =
+ let (loc, ofs) = calling_conventions 0 9 100 109 incoming arg in loc
+let loc_results res =
+ let (loc, ofs) = calling_conventions 0 0 100 100 not_supported res in loc
+
+(* C calling conventions under Unix:
+ first integer args in rdi, rsi, rdx, rcx, r8, r9
+ first float args in xmm0 ... xmm7
+ remaining args on stack
+ return value in rax or xmm0.
+ C calling conventions under Win64:
+ first integer args in rcx, rdx, r8, r9
+ first float args in xmm0 ... xmm3
+ each integer arg consumes a float reg, and conversely
+ remaining args on stack
+ always 32 bytes reserved at bottom of stack.
+ Return value in rax or xmm0. *)
+
+let loc_external_results res =
+ let (loc, ofs) = calling_conventions 0 0 100 100 not_supported res in loc
+
+let unix_loc_external_arguments arg =
+ calling_conventions 2 7 100 107 outgoing arg
+
+let win64_int_external_arguments =
+ [| 5 (*rcx*); 4 (*rdx*); 6 (*r8*); 7 (*r9*) |]
+let win64_float_external_arguments =
+ [| 100 (*xmm0*); 101 (*xmm1*); 102 (*xmm2*); 103 (*xmm3*) |]
+
+let win64_loc_external_arguments arg =
+ let loc = Array.make (Array.length arg) Reg.dummy in
+ let reg = ref 0
+ and ofs = ref 32 in
+ for i = 0 to Array.length arg - 1 do
+ match arg.(i).typ with
+ | Val | Int | Addr as ty ->
+ if !reg < 4 then begin
+ loc.(i) <- phys_reg win64_int_external_arguments.(!reg);
+ incr reg
+ end else begin
+ loc.(i) <- stack_slot (Outgoing !ofs) ty;
+ ofs := !ofs + size_int
+ end
+ | Float ->
+ if !reg < 4 then begin
+ loc.(i) <- phys_reg win64_float_external_arguments.(!reg);
+ incr reg
+ end else begin
+ loc.(i) <- stack_slot (Outgoing !ofs) Float;
+ ofs := !ofs + size_float
+ end
+ done;
+ (loc, Misc.align !ofs 16) (* keep stack 16-aligned *)
+
+let loc_external_arguments arg =
+ let arg =
+ Array.map (fun regs -> assert (Array.length regs = 1); regs.(0)) arg
+ in
+ let loc, alignment =
+ if win64 then win64_loc_external_arguments arg
+ else unix_loc_external_arguments arg
+ in
+ Array.map (fun reg -> [|reg|]) loc, alignment
+
+let loc_exn_bucket = rax
+
+(* Volatile registers: none *)
+
+let regs_are_volatile rs = false
+
+(* Registers destroyed by operations *)
+
+let destroyed_at_c_call =
+ if win64 then
+ (* Win64: rbx, rbp, rsi, rdi, r12-r15, xmm6-xmm15 preserved *)
+ Array.of_list(List.map phys_reg
+ [0;4;5;6;7;10;11;
+ 100;101;102;103;104;105])
+ else
+ (* Unix: rbp, rbx, r12-r15 preserved *)
+ Array.of_list(List.map phys_reg
+ [0;2;3;4;5;6;7;10;11;
+ 100;101;102;103;104;105;106;107;
+ 108;109;110;111;112;113;114;115])
+
+let destroyed_at_oper = function
+ Iop(Icall_ind | Icall_imm _ | Iextcall(_, true)) -> all_phys_regs
+ | Iop(Iextcall(_, false)) -> destroyed_at_c_call
+ | Iop(Iintop(Idiv | Imod)) | Iop(Iintop_imm((Idiv | Imod), _))
+ -> [| rax; rdx |]
+ | Iop(Istore(Single, _, _)) -> [| rxmm15 |]
+ | Iop(Ialloc _ | Iintop(Imulh | Icomp _) | Iintop_imm((Icomp _), _))
+ -> [| rax |]
+ | Iswitch(_, _) -> [| rax; rdx |]
+ | _ ->
+ if fp then
+(* prevent any use of the frame pointer ! *)
+ [| rbp |]
+ else
+ [||]
+
+
+let destroyed_at_raise = all_phys_regs
+
+(* Maximal register pressure *)
+
+
+let safe_register_pressure = function
+ Iextcall(_,_) -> if win64 then if fp then 7 else 8 else 0
+ | _ -> if fp then 10 else 11
+
+let max_register_pressure = function
+ Iextcall(_, _) ->
+ if win64 then
+ if fp then [| 7; 10 |] else [| 8; 10 |]
+ else
+ if fp then [| 3; 0 |] else [| 4; 0 |]
+ | Iintop(Idiv | Imod) | Iintop_imm((Idiv | Imod), _) ->
+ if fp then [| 10; 16 |] else [| 11; 16 |]
+ | Ialloc _ | Iintop(Icomp _) | Iintop_imm((Icomp _), _) ->
+ if fp then [| 11; 16 |] else [| 12; 16 |]
+ | Istore(Single, _, _) ->
+ if fp then [| 12; 15 |] else [| 13; 15 |]
+ | _ -> if fp then [| 12; 16 |] else [| 13; 16 |]
+
+(* Pure operations (without any side effect besides updating their result
+ registers). *)
+
+let op_is_pure = function
+ | Icall_ind | Icall_imm _ | Itailcall_ind | Itailcall_imm _
+ | Iextcall _ | Istackoffset _ | Istore _ | Ialloc _
+ | Iintop(Icheckbound) | Iintop_imm(Icheckbound, _) -> false
+ | Ispecific(Ilea _) -> true
+ | Ispecific _ -> false
+ | _ -> true
+
+(* Layout of the stack frame *)
+
+let num_stack_slots = [| 0; 0 |]
+let contains_calls = ref false
+
+(* Calling the assembler *)
+
+let assemble_file infile outfile =
+ X86_proc.assemble_file infile outfile
+
+let init () =
+ if fp then begin
+ num_available_registers.(0) <- 12
+ end else
+ num_available_registers.(0) <- 13
diff --git a/asmcomp/amd64/reload.ml b/asmcomp/amd64/reload.ml
new file mode 100644
index 0000000000..0a4ce0db54
--- /dev/null
+++ b/asmcomp/amd64/reload.ml
@@ -0,0 +1,126 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Cmm
+open Reg
+open Mach
+
+(* Reloading for the AMD64 *)
+
+(* Summary of instruction set constraints:
+ "S" means either stack or register, "R" means register only.
+ Operation Res Arg1 Arg2
+ Imove R S
+ or S R
+ Iconst_int ] S if 32-bit signed, R otherwise
+ Iconst_blockheader ]
+ Iconst_float R
+ Iconst_symbol (not PIC) S
+ Iconst_symbol (PIC) R
+ Icall_ind R
+ Itailcall_ind R
+ Iload R R R
+ Istore R R
+ Iintop(Icomp) R R S
+ or S S R
+ Iintop(Imul|Idiv|Imod) R R S
+ Iintop(Imulh) R R S
+ Iintop(shift) S S R
+ Iintop(others) R R S
+ or S S R
+ Iintop_imm(Iadd, n)/lea R R
+ Iintop_imm(others) S S
+ Inegf...Idivf R R S
+ Ifloatofint R S
+ Iintoffloat R S
+ Ispecific(Ilea) R R R
+ Ispecific(Ifloatarithmem) R R R
+
+ Conditional branches:
+ Iinttest S R
+ or R S
+ Ifloattest R S (or S R if swapped test)
+ other tests S
+*)
+
+let stackp r =
+ match r.loc with
+ Stack _ -> true
+ | _ -> false
+
+class reload = object (self)
+
+inherit Reloadgen.reload_generic as super
+
+method! reload_operation op arg res =
+ match op with
+ | Iintop(Iadd|Isub|Iand|Ior|Ixor|Icomp _|Icheckbound) ->
+ (* One of the two arguments can reside in the stack, but not both *)
+ if stackp arg.(0) && stackp arg.(1)
+ then ([|arg.(0); self#makereg arg.(1)|], res)
+ else (arg, res)
+ | Iintop_imm(Iadd, _) when arg.(0).loc <> res.(0).loc ->
+ (* This add will be turned into a lea; args and results must be
+ in registers *)
+ super#reload_operation op arg res
+ | Iintop(Imulh | Idiv | Imod | Ilsl | Ilsr | Iasr)
+ | Iintop_imm(_, _) ->
+ (* The argument(s) and results can be either in register or on stack *)
+ (* Note: Imulh, Idiv, Imod: arg(0) and res(0) already forced in regs
+ Ilsl, Ilsr, Iasr: arg(1) already forced in regs *)
+ (arg, res)
+ | Iintop(Imul) | Iaddf | Isubf | Imulf | Idivf ->
+ (* First argument (= result) must be in register, second arg
+ can reside in the stack *)
+ if stackp arg.(0)
+ then (let r = self#makereg arg.(0) in ([|r; arg.(1)|], [|r|]))
+ else (arg, res)
+ | Ifloatofint | Iintoffloat ->
+ (* Result must be in register, but argument can be on stack *)
+ (arg, (if stackp res.(0) then [| self#makereg res.(0) |] else res))
+ | Iconst_int n | Iconst_blockheader n ->
+ if n <= 0x7FFFFFFFn && n >= -0x80000000n
+ then (arg, res)
+ else super#reload_operation op arg res
+ | Iconst_symbol _ ->
+ if !Clflags.pic_code || !Clflags.dlcode
+ then super#reload_operation op arg res
+ else (arg, res)
+ | _ -> (* Other operations: all args and results in registers *)
+ super#reload_operation op arg res
+
+method! reload_test tst arg =
+ match tst with
+ Iinttest cmp ->
+ (* One of the two arguments can reside on stack *)
+ if stackp arg.(0) && stackp arg.(1)
+ then [| self#makereg arg.(0); arg.(1) |]
+ else arg
+ | Ifloattest((Clt|Cle), _) ->
+ (* Cf. emit.mlp: we swap arguments in this case *)
+ (* First argument can be on stack, second must be in register *)
+ if stackp arg.(1)
+ then [| arg.(0); self#makereg arg.(1) |]
+ else arg
+ | Ifloattest((Ceq|Cne|Cgt|Cge), _) ->
+ (* Second argument can be on stack, first must be in register *)
+ if stackp arg.(0)
+ then [| self#makereg arg.(0); arg.(1) |]
+ else arg
+ | _ ->
+ (* The argument(s) can be either in register or on stack *)
+ arg
+
+end
+
+let fundecl f =
+ (new reload)#fundecl f
diff --git a/asmcomp/amd64/scheduling.ml b/asmcomp/amd64/scheduling.ml
new file mode 100644
index 0000000000..e234431bfa
--- /dev/null
+++ b/asmcomp/amd64/scheduling.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let _ = let module M = Schedgen in () (* to create a dependency *)
+
+(* Scheduling is turned off because the processor schedules dynamically
+ much better than what we could do. *)
+
+let fundecl f = f
diff --git a/asmcomp/amd64/selection.ml b/asmcomp/amd64/selection.ml
new file mode 100644
index 0000000000..857a481dcb
--- /dev/null
+++ b/asmcomp/amd64/selection.ml
@@ -0,0 +1,254 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction selection for the AMD64 *)
+
+open Arch
+open Proc
+open Cmm
+open Mach
+
+(* Auxiliary for recognizing addressing modes *)
+
+type addressing_expr =
+ Asymbol of string
+ | Alinear of expression
+ | Aadd of expression * expression
+ | Ascale of expression * int
+ | Ascaledadd of expression * expression * int
+
+let rec select_addr exp =
+ match exp with
+ Cconst_symbol s when not !Clflags.dlcode ->
+ (Asymbol s, 0)
+ | Cop((Caddi | Caddv | Cadda), [arg; Cconst_int m]) ->
+ let (a, n) = select_addr arg in (a, n + m)
+ | Cop(Csubi, [arg; Cconst_int m]) ->
+ let (a, n) = select_addr arg in (a, n - m)
+ | Cop((Caddi | Caddv | Cadda), [Cconst_int m; arg]) ->
+ let (a, n) = select_addr arg in (a, n + m)
+ | Cop(Clsl, [arg; Cconst_int(1|2|3 as shift)]) ->
+ begin match select_addr arg with
+ (Alinear e, n) -> (Ascale(e, 1 lsl shift), n lsl shift)
+ | _ -> (Alinear exp, 0)
+ end
+ | Cop(Cmuli, [arg; Cconst_int(2|4|8 as mult)]) ->
+ begin match select_addr arg with
+ (Alinear e, n) -> (Ascale(e, mult), n * mult)
+ | _ -> (Alinear exp, 0)
+ end
+ | Cop(Cmuli, [Cconst_int(2|4|8 as mult); arg]) ->
+ begin match select_addr arg with
+ (Alinear e, n) -> (Ascale(e, mult), n * mult)
+ | _ -> (Alinear exp, 0)
+ end
+ | Cop((Caddi | Caddv | Cadda), [arg1; arg2]) ->
+ begin match (select_addr arg1, select_addr arg2) with
+ ((Alinear e1, n1), (Alinear e2, n2)) ->
+ (Aadd(e1, e2), n1 + n2)
+ | ((Alinear e1, n1), (Ascale(e2, scale), n2)) ->
+ (Ascaledadd(e1, e2, scale), n1 + n2)
+ | ((Ascale(e1, scale), n1), (Alinear e2, n2)) ->
+ (Ascaledadd(e2, e1, scale), n1 + n2)
+ | (_, (Ascale(e2, scale), n2)) ->
+ (Ascaledadd(arg1, e2, scale), n2)
+ | ((Ascale(e1, scale), n1), _) ->
+ (Ascaledadd(arg2, e1, scale), n1)
+ | _ ->
+ (Aadd(arg1, arg2), 0)
+ end
+ | arg ->
+ (Alinear arg, 0)
+
+(* Special constraints on operand and result registers *)
+
+exception Use_default
+
+let rax = phys_reg 0
+let rcx = phys_reg 5
+let rdx = phys_reg 4
+
+let pseudoregs_for_operation op arg res =
+ match op with
+ (* Two-address binary operations: arg.(0) and res.(0) must be the same *)
+ Iintop(Iadd|Isub|Imul|Iand|Ior|Ixor) | Iaddf|Isubf|Imulf|Idivf ->
+ ([|res.(0); arg.(1)|], res)
+ (* One-address unary operations: arg.(0) and res.(0) must be the same *)
+ | Iintop_imm((Iadd|Isub|Imul|Iand|Ior|Ixor|Ilsl|Ilsr|Iasr), _)
+ | Iabsf | Inegf
+ | Ispecific(Ibswap (32|64)) ->
+ (res, res)
+ (* For xchg, args must be a register allowing access to high 8 bit register
+ (rax, rbx, rcx or rdx). Keep it simple, just force the argument in rax. *)
+ | Ispecific(Ibswap 16) ->
+ ([| rax |], [| rax |])
+ (* For imulq, first arg must be in rax, rax is clobbered, and result is in
+ rdx. *)
+ | Iintop(Imulh) ->
+ ([| rax; arg.(1) |], [| rdx |])
+ | Ispecific(Ifloatarithmem(_,_)) ->
+ let arg' = Array.copy arg in
+ arg'.(0) <- res.(0);
+ (arg', res)
+ (* For shifts with variable shift count, second arg must be in rcx *)
+ | Iintop(Ilsl|Ilsr|Iasr) ->
+ ([|res.(0); rcx|], res)
+ (* For div and mod, first arg must be in rax, rdx is clobbered,
+ and result is in rax or rdx respectively.
+ Keep it simple, just force second argument in rcx. *)
+ | Iintop(Idiv) ->
+ ([| rax; rcx |], [| rax |])
+ | Iintop(Imod) ->
+ ([| rax; rcx |], [| rdx |])
+ (* Other instructions are regular *)
+ | _ -> raise Use_default
+
+let inline_ops =
+ [ "sqrt"; "caml_bswap16_direct"; "caml_int32_direct_bswap";
+ "caml_int64_direct_bswap"; "caml_nativeint_direct_bswap" ]
+
+(* The selector class *)
+
+class selector = object (self)
+
+inherit Selectgen.selector_generic as super
+
+method is_immediate n = n <= 0x7FFFFFFF && n >= -0x80000000
+
+method is_immediate_natint n = n <= 0x7FFFFFFFn && n >= -0x80000000n
+
+method! is_simple_expr e =
+ match e with
+ | Cop(Cextcall(fn, _, _, _), args)
+ when List.mem fn inline_ops ->
+ (* inlined ops are simple if their arguments are *)
+ List.for_all self#is_simple_expr args
+ | _ ->
+ super#is_simple_expr e
+
+method select_addressing chunk exp =
+ let (a, d) = select_addr exp in
+ (* PR#4625: displacement must be a signed 32-bit immediate *)
+ if d < -0x8000_0000 || d > 0x7FFF_FFFF
+ then (Iindexed 0, exp)
+ else match a with
+ | Asymbol s ->
+ (Ibased(s, d), Ctuple [])
+ | Alinear e ->
+ (Iindexed d, e)
+ | Aadd(e1, e2) ->
+ (Iindexed2 d, Ctuple[e1; e2])
+ | Ascale(e, scale) ->
+ (Iscaled(scale, d), e)
+ | Ascaledadd(e1, e2, scale) ->
+ (Iindexed2scaled(scale, d), Ctuple[e1; e2])
+
+method! select_store is_assign addr exp =
+ match exp with
+ Cconst_int n when self#is_immediate n ->
+ (Ispecific(Istore_int(Nativeint.of_int n, addr, is_assign)), Ctuple [])
+ | (Cconst_natint n | Cconst_blockheader n) when self#is_immediate_natint n ->
+ (Ispecific(Istore_int(n, addr, is_assign)), Ctuple [])
+ | Cconst_pointer n when self#is_immediate n ->
+ (Ispecific(Istore_int(Nativeint.of_int n, addr, is_assign)), Ctuple [])
+ | Cconst_natpointer n when self#is_immediate_natint n ->
+ (Ispecific(Istore_int(n, addr, is_assign)), Ctuple [])
+ | Cconst_symbol s when not (!Clflags.pic_code || !Clflags.dlcode) ->
+ (Ispecific(Istore_symbol(s, addr, is_assign)), Ctuple [])
+ | _ ->
+ super#select_store is_assign addr exp
+
+method! select_operation op args =
+ match op with
+ (* Recognize the LEA instruction *)
+ Caddi | Caddv | Cadda | Csubi ->
+ begin match self#select_addressing Word_int (Cop(op, args)) with
+ (Iindexed d, _) -> super#select_operation op args
+ | (Iindexed2 0, _) -> super#select_operation op args
+ | (addr, arg) -> (Ispecific(Ilea addr), [arg])
+ end
+ (* Recognize float arithmetic with memory. *)
+ | Caddf ->
+ self#select_floatarith true Iaddf Ifloatadd args
+ | Csubf ->
+ self#select_floatarith false Isubf Ifloatsub args
+ | Cmulf ->
+ self#select_floatarith true Imulf Ifloatmul args
+ | Cdivf ->
+ self#select_floatarith false Idivf Ifloatdiv args
+ | Cextcall("sqrt", _, false, _) ->
+ begin match args with
+ [Cop(Cload (Double|Double_u as chunk), [loc])] ->
+ let (addr, arg) = self#select_addressing chunk loc in
+ (Ispecific(Ifloatsqrtf addr), [arg])
+ | [arg] ->
+ (Ispecific Isqrtf, [arg])
+ | _ ->
+ assert false
+ end
+ (* Recognize store instructions *)
+ | Cstore (Word_int|Word_val as chunk) ->
+ begin match args with
+ [loc; Cop(Caddi, [Cop(Cload _, [loc']); Cconst_int n])]
+ when loc = loc' && self#is_immediate n ->
+ let (addr, arg) = self#select_addressing chunk loc in
+ (Ispecific(Ioffset_loc(n, addr)), [arg])
+ | _ ->
+ super#select_operation op args
+ end
+ | Cextcall("caml_bswap16_direct", _, _, _) ->
+ (Ispecific (Ibswap 16), args)
+ | Cextcall("caml_int32_direct_bswap", _, _, _) ->
+ (Ispecific (Ibswap 32), args)
+ | Cextcall("caml_int64_direct_bswap", _, _, _)
+ | Cextcall("caml_nativeint_direct_bswap", _, _, _) ->
+ (Ispecific (Ibswap 64), args)
+ (* AMD64 does not support immediate operands for multiply high signed *)
+ | Cmulhi ->
+ (Iintop Imulh, args)
+ | _ -> super#select_operation op args
+
+(* Recognize float arithmetic with mem *)
+
+method select_floatarith commutative regular_op mem_op args =
+ match args with
+ [arg1; Cop(Cload (Double|Double_u as chunk), [loc2])] ->
+ let (addr, arg2) = self#select_addressing chunk loc2 in
+ (Ispecific(Ifloatarithmem(mem_op, addr)),
+ [arg1; arg2])
+ | [Cop(Cload (Double|Double_u as chunk), [loc1]); arg2] when commutative ->
+ let (addr, arg1) = self#select_addressing chunk loc1 in
+ (Ispecific(Ifloatarithmem(mem_op, addr)),
+ [arg2; arg1])
+ | [arg1; arg2] ->
+ (regular_op, [arg1; arg2])
+ | _ ->
+ assert false
+
+method! mark_c_tailcall =
+ Proc.contains_calls := true
+
+(* Deal with register constraints *)
+
+method! insert_op_debug op dbg rs rd =
+ try
+ let (rsrc, rdst) = pseudoregs_for_operation op rs rd in
+ self#insert_moves rs rsrc;
+ self#insert_debug (Iop op) dbg rsrc rdst;
+ self#insert_moves rdst rd;
+ rd
+ with Use_default ->
+ super#insert_op_debug op dbg rs rd
+
+end
+
+let fundecl f = (new selector)#emit_fundecl f
diff --git a/asmcomp/arm/CSE.ml b/asmcomp/arm/CSE.ml
new file mode 100644
index 0000000000..bea333dc42
--- /dev/null
+++ b/asmcomp/arm/CSE.ml
@@ -0,0 +1,37 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* CSE for ARM *)
+
+open Arch
+open Mach
+open CSEgen
+
+class cse = object (self)
+
+inherit cse_generic as super
+
+method! class_of_operation op =
+ match op with
+ | Ispecific(Ishiftcheckbound _) -> Op_checkbound
+ | Ispecific _ -> Op_pure
+ | _ -> super#class_of_operation op
+
+method! is_cheap_operation op =
+ match op with
+ | Iconst_int n | Iconst_blockheader n -> n <= 255n && n >= 0n
+ | _ -> false
+
+end
+
+let fundecl f =
+ (new cse)#fundecl f
diff --git a/asmcomp/arm/arch.ml b/asmcomp/arm/arch.ml
new file mode 100644
index 0000000000..cc880551c6
--- /dev/null
+++ b/asmcomp/arm/arch.ml
@@ -0,0 +1,255 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Specific operations for the ARM processor *)
+
+open Format
+
+type abi = EABI | EABI_HF
+type arch = ARMv4 | ARMv5 | ARMv5TE | ARMv6 | ARMv6T2 | ARMv7
+type fpu = Soft | VFPv2 | VFPv3_D16 | VFPv3
+
+let abi =
+ match Config.system with
+ "linux_eabi" | "freebsd" -> EABI
+ | "linux_eabihf" -> EABI_HF
+ | _ -> assert false
+
+let string_of_arch = function
+ ARMv4 -> "armv4"
+ | ARMv5 -> "armv5"
+ | ARMv5TE -> "armv5te"
+ | ARMv6 -> "armv6"
+ | ARMv6T2 -> "armv6t2"
+ | ARMv7 -> "armv7"
+
+let string_of_fpu = function
+ Soft -> "soft"
+ | VFPv2 -> "vfpv2"
+ | VFPv3_D16 -> "vfpv3-d16"
+ | VFPv3 -> "vfpv3"
+
+(* Machine-specific command-line options *)
+
+let (arch, fpu, thumb) =
+ let (def_arch, def_fpu, def_thumb) =
+ begin match abi, Config.model with
+ (* Defaults for architecture, FPU and Thumb *)
+ EABI, "armv5" -> ARMv5, Soft, false
+ | EABI, "armv5te" -> ARMv5TE, Soft, false
+ | EABI, "armv6" -> ARMv6, Soft, false
+ | EABI, "armv6t2" -> ARMv6T2, Soft, false
+ | EABI, "armv7" -> ARMv7, Soft, false
+ | EABI, _ -> ARMv4, Soft, false
+ | EABI_HF, "armv6" -> ARMv6, VFPv2, false
+ | EABI_HF, _ -> ARMv7, VFPv3_D16, true
+ end in
+ (ref def_arch, ref def_fpu, ref def_thumb)
+
+let farch spec =
+ arch := (match spec with
+ "armv4" when abi <> EABI_HF -> ARMv4
+ | "armv5" when abi <> EABI_HF -> ARMv5
+ | "armv5te" when abi <> EABI_HF -> ARMv5TE
+ | "armv6" -> ARMv6
+ | "armv6t2" -> ARMv6T2
+ | "armv7" -> ARMv7
+ | spec -> raise (Arg.Bad spec))
+
+let ffpu spec =
+ fpu := (match spec with
+ "soft" when abi <> EABI_HF -> Soft
+ | "vfpv2" when abi = EABI_HF -> VFPv2
+ | "vfpv3-d16" when abi = EABI_HF -> VFPv3_D16
+ | "vfpv3" when abi = EABI_HF -> VFPv3
+ | spec -> raise (Arg.Bad spec))
+
+let command_line_options =
+ [ "-farch", Arg.String farch,
+ "<arch> Select the ARM target architecture"
+ ^ " (default: " ^ (string_of_arch !arch) ^ ")";
+ "-ffpu", Arg.String ffpu,
+ "<fpu> Select the floating-point hardware"
+ ^ " (default: " ^ (string_of_fpu !fpu) ^ ")";
+ "-fPIC", Arg.Set Clflags.pic_code,
+ " Generate position-independent machine code";
+ "-fno-PIC", Arg.Clear Clflags.pic_code,
+ " Generate position-dependent machine code";
+ "-fthumb", Arg.Set thumb,
+ " Enable Thumb/Thumb-2 code generation"
+ ^ (if !thumb then " (default)" else "");
+ "-fno-thumb", Arg.Clear thumb,
+ " Disable Thumb/Thumb-2 code generation"
+ ^ (if not !thumb then " (default" else "")]
+
+(* Addressing modes *)
+
+type addressing_mode =
+ Iindexed of int (* reg + displ *)
+
+(* We do not support the reg + shifted reg addressing mode, because
+ what we really need is reg + shifted reg + displ,
+ and this is decomposed in two instructions (reg + shifted reg -> tmp,
+ then addressing tmp + displ). *)
+
+(* Specific operations *)
+
+type specific_operation =
+ Ishiftarith of arith_operation * shift_operation * int
+ | Ishiftcheckbound of shift_operation * int
+ | Irevsubimm of int
+ | Imulhadd (* multiply high and add *)
+ | Imuladd (* multiply and add *)
+ | Imulsub (* multiply and subtract *)
+ | Inegmulf (* floating-point negate and multiply *)
+ | Imuladdf (* floating-point multiply and add *)
+ | Inegmuladdf (* floating-point negate, multiply and add *)
+ | Imulsubf (* floating-point multiply and subtract *)
+ | Inegmulsubf (* floating-point negate, multiply and subtract *)
+ | Isqrtf (* floating-point square root *)
+ | Ibswap of int (* endianess conversion *)
+
+and arith_operation =
+ Ishiftadd
+ | Ishiftsub
+ | Ishiftsubrev
+ | Ishiftand
+ | Ishiftor
+ | Ishiftxor
+
+and shift_operation =
+ Ishiftlogicalleft
+ | Ishiftlogicalright
+ | Ishiftarithmeticright
+
+(* Sizes, endianness *)
+
+let big_endian = false
+
+let size_addr = 4
+let size_int = 4
+let size_float = 8
+
+let allow_unaligned_access = false
+
+(* Behavior of division *)
+
+let division_crashes_on_overflow = false
+
+(* Operations on addressing modes *)
+
+let identity_addressing = Iindexed 0
+
+let offset_addressing (Iindexed n) delta = Iindexed(n + delta)
+
+let num_args_addressing (Iindexed n) = 1
+
+(* Printing operations and addressing modes *)
+
+let print_addressing printreg addr ppf arg =
+ match addr with
+ | Iindexed n ->
+ printreg ppf arg.(0);
+ if n <> 0 then fprintf ppf " + %i" n
+
+let shiftop_name = function
+ | Ishiftlogicalleft -> "<<"
+ | Ishiftlogicalright -> ">>u"
+ | Ishiftarithmeticright -> ">>s"
+
+let print_specific_operation printreg op ppf arg =
+ match op with
+ Ishiftarith(op, shiftop, amount) ->
+ let (op1_name, op2_name) = match op with
+ Ishiftadd -> ("", "+")
+ | Ishiftsub -> ("", "-")
+ | Ishiftsubrev -> ("-", "+")
+ | Ishiftand -> ("", "&")
+ | Ishiftor -> ("", "|")
+ | Ishiftxor -> ("", "^") in
+ fprintf ppf "%s%a %s (%a %s %i)"
+ op1_name
+ printreg arg.(0)
+ op2_name
+ printreg arg.(1)
+ (shiftop_name shiftop)
+ amount
+ | Ishiftcheckbound(shiftop, amount) ->
+ fprintf ppf "check (%a %s %i) > %a"
+ printreg arg.(0)
+ (shiftop_name shiftop)
+ amount
+ printreg arg.(1)
+ | Irevsubimm n ->
+ fprintf ppf "%i %s %a" n "-" printreg arg.(0)
+ | Imulhadd ->
+ fprintf ppf "%a *h %a) + %a"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Imuladd ->
+ fprintf ppf "(%a * %a) + %a"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Imulsub ->
+ fprintf ppf "-(%a * %a) + %a"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Inegmulf ->
+ fprintf ppf "-f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ | Imuladdf ->
+ fprintf ppf "%a +f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Inegmuladdf ->
+ fprintf ppf "%a -f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Imulsubf ->
+ fprintf ppf "(-f %a) +f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Inegmulsubf ->
+ fprintf ppf "(-f %a) -f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Isqrtf ->
+ fprintf ppf "sqrtf %a"
+ printreg arg.(0)
+ | Ibswap n ->
+ fprintf ppf "bswap%i %a" n
+ printreg arg.(0)
+
+(* Recognize immediate operands *)
+
+(* Immediate operands are 8-bit immediate values, zero-extended,
+ and rotated right by 0 ... 30 bits.
+ In Thumb/Thumb-2 mode we utilize 26 ... 30. *)
+
+let is_immediate n =
+ let n = ref n in
+ let s = ref 0 in
+ let m = if !thumb then 24 else 30 in
+ while (!s <= m && Int32.logand !n 0xffl <> !n) do
+ n := Int32.logor (Int32.shift_right_logical !n 2) (Int32.shift_left !n 30);
+ s := !s + 2
+ done;
+ !s <= m
diff --git a/asmcomp/arm/emit.mlp b/asmcomp/arm/emit.mlp
new file mode 100644
index 0000000000..440f4630c4
--- /dev/null
+++ b/asmcomp/arm/emit.mlp
@@ -0,0 +1,956 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Emission of ARM assembly code *)
+
+open Misc
+open Cmm
+open Arch
+open Proc
+open Reg
+open Mach
+open Linearize
+open Emitaux
+
+(* Tradeoff between code size and code speed *)
+
+let fastcode_flag = ref true
+
+(* Output a label *)
+
+let emit_label lbl =
+ emit_string ".L"; emit_int lbl
+
+let emit_data_label lbl =
+ emit_string ".Ld"; emit_int lbl
+
+(* Symbols *)
+
+let emit_symbol s =
+ Emitaux.emit_symbol '$' s
+
+let emit_call s =
+ if !Clflags.dlcode || !Clflags.pic_code
+ then `bl {emit_symbol s}(PLT)`
+ else `bl {emit_symbol s}`
+
+let emit_jump s =
+ if !Clflags.dlcode || !Clflags.pic_code
+ then `b {emit_symbol s}(PLT)`
+ else `b {emit_symbol s}`
+
+(* Output a pseudo-register *)
+
+let emit_reg = function
+ {loc = Reg r} -> emit_string (register_name r)
+ | _ -> fatal_error "Emit_arm.emit_reg"
+
+(* Layout of the stack frame *)
+
+let stack_offset = ref 0
+
+let frame_size () =
+ let sz =
+ !stack_offset +
+ 4 * num_stack_slots.(0) +
+ 8 * num_stack_slots.(1) +
+ 8 * num_stack_slots.(2) +
+ (if !contains_calls then 4 else 0)
+ in Misc.align sz 8
+
+let slot_offset loc cl =
+ match loc with
+ Incoming n ->
+ assert (n >= 0);
+ frame_size() + n
+ | Local n ->
+ if cl = 0
+ then !stack_offset + n * 4
+ else !stack_offset + num_stack_slots.(0) * 4 + n * 8
+ | Outgoing n ->
+ assert (n >= 0);
+ n
+
+(* Output a stack reference *)
+
+let emit_stack r =
+ match r.loc with
+ | Stack s ->
+ let ofs = slot_offset s (register_class r) in `[sp, #{emit_int ofs}]`
+ | _ -> fatal_error "Emit_arm.emit_stack"
+
+(* Output an addressing mode *)
+
+let emit_addressing addr r n =
+ match addr with
+ Iindexed ofs ->
+ `[{emit_reg r.(n)}, #{emit_int ofs}]`
+
+(* Record live pointers at call points *)
+
+let record_frame_label live dbg =
+ let lbl = new_label() in
+ let live_offset = ref [] in
+ Reg.Set.iter
+ (function
+ | {typ = Val; loc = Reg r} ->
+ live_offset := ((r lsl 1) + 1) :: !live_offset
+ | {typ = Val; loc = Stack s} as reg ->
+ live_offset := slot_offset s (register_class reg) :: !live_offset
+ | {typ = Addr} as r ->
+ Misc.fatal_error ("bad GC root " ^ Reg.name r)
+ | _ -> ())
+ live;
+ frame_descriptors :=
+ { fd_lbl = lbl;
+ fd_frame_size = frame_size();
+ fd_live_offset = !live_offset;
+ fd_debuginfo = dbg } :: !frame_descriptors;
+ lbl
+
+let record_frame live dbg =
+ let lbl = record_frame_label live dbg in `{emit_label lbl}:`
+
+(* Record calls to the GC -- we've moved them out of the way *)
+
+type gc_call =
+ { gc_lbl: label; (* Entry label *)
+ gc_return_lbl: label; (* Where to branch after GC *)
+ gc_frame_lbl: label } (* Label of frame descriptor *)
+
+let call_gc_sites = ref ([] : gc_call list)
+
+let emit_call_gc gc =
+ `{emit_label gc.gc_lbl}: {emit_call "caml_call_gc"}\n`;
+ `{emit_label gc.gc_frame_lbl}: b {emit_label gc.gc_return_lbl}\n`
+
+(* Record calls to caml_ml_array_bound_error.
+ In debug mode, we maintain one call to caml_ml_array_bound_error
+ per bound check site. Otherwise, we can share a single call. *)
+
+type bound_error_call =
+ { bd_lbl: label; (* Entry label *)
+ bd_frame_lbl: label } (* Label of frame descriptor *)
+
+let bound_error_sites = ref ([] : bound_error_call list)
+
+let bound_error_label dbg =
+ if !Clflags.debug || !bound_error_sites = [] then begin
+ let lbl_bound_error = new_label() in
+ let lbl_frame = record_frame_label Reg.Set.empty dbg in
+ bound_error_sites :=
+ { bd_lbl = lbl_bound_error;
+ bd_frame_lbl = lbl_frame } :: !bound_error_sites;
+ lbl_bound_error
+ end else begin
+ let bd = List.hd !bound_error_sites in bd.bd_lbl
+ end
+
+let emit_call_bound_error bd =
+ `{emit_label bd.bd_lbl}: {emit_call "caml_ml_array_bound_error"}\n`;
+ `{emit_label bd.bd_frame_lbl}:\n`
+
+(* Negate a comparison *)
+
+let negate_integer_comparison = function
+ Isigned cmp -> Isigned(negate_comparison cmp)
+ | Iunsigned cmp -> Iunsigned(negate_comparison cmp)
+
+(* Names of various instructions *)
+
+let name_for_comparison = function
+ Isigned Ceq -> "eq" | Isigned Cne -> "ne" | Isigned Cle -> "le"
+ | Isigned Cge -> "ge" | Isigned Clt -> "lt" | Isigned Cgt -> "gt"
+ | Iunsigned Ceq -> "eq" | Iunsigned Cne -> "ne" | Iunsigned Cle -> "ls"
+ | Iunsigned Cge -> "cs" | Iunsigned Clt -> "cc" | Iunsigned Cgt -> "hi"
+
+let name_for_int_operation = function
+ (* Use adds,subs,... to enable 16-bit T1 encoding *)
+ Iadd -> "adds"
+ | Isub -> "subs"
+ | Imul -> "mul"
+ | Imulh -> "smmul"
+ | Iand -> "ands"
+ | Ior -> "orrs"
+ | Ixor -> "eors"
+ | Ilsl -> "lsls"
+ | Ilsr -> "lsrs"
+ | Iasr -> "asrs"
+ | _ -> assert false
+
+let name_for_shift_operation = function
+ Ishiftlogicalleft -> "lsl"
+ | Ishiftlogicalright -> "lsr"
+ | Ishiftarithmeticright -> "asr"
+
+(* General functional to decompose a non-immediate integer constant
+ into 8-bit chunks shifted left 0 ... 30 bits. *)
+
+let decompose_intconst n fn =
+ let i = ref n in
+ let shift = ref 0 in
+ let ninstr = ref 0 in
+ while !i <> 0l do
+ if Int32.logand (Int32.shift_right !i !shift) 3l = 0l then
+ shift := !shift + 2
+ else begin
+ let bits = Int32.logand !i (Int32.shift_left 0xffl !shift) in
+ i := Int32.sub !i bits;
+ shift := !shift + 8;
+ incr ninstr;
+ fn bits
+ end
+ done;
+ !ninstr
+
+(* Load an integer constant into a register *)
+
+let emit_intconst dst n =
+ let nr = Int32.lognot n in
+ if is_immediate n then begin
+ (* Use movs here to enable 16-bit T1 encoding *)
+ ` movs {emit_reg dst}, #{emit_int32 n}\n`; 1
+ end else if is_immediate nr then begin
+ ` mvn {emit_reg dst}, #{emit_int32 nr}\n`; 1
+ end else if !arch > ARMv6 then begin
+ let nl = Int32.logand 0xffffl n in
+ let nh = Int32.logand 0xffffl (Int32.shift_right_logical n 16) in
+ if nh = 0l then begin
+ ` movw {emit_reg dst}, #{emit_int32 nl}\n`; 1
+ end else if Int32.logand nl 0xffl = nl then begin
+ ` movs {emit_reg dst}, #{emit_int32 nl}\n`;
+ ` movt {emit_reg dst}, #{emit_int32 nh}\n`; 2
+ end else begin
+ ` movw {emit_reg dst}, #{emit_int32 nl}\n`;
+ ` movt {emit_reg dst}, #{emit_int32 nh}\n`; 2
+ end
+ end else begin
+ let first = ref true in
+ decompose_intconst n
+ (fun bits ->
+ if !first
+ (* Use movs,adds here to enable 16-bit T1 encoding *)
+ then ` movs {emit_reg dst}, #{emit_int32 bits} @ {emit_int32 n}\n`
+ else ` adds {emit_reg dst}, {emit_reg dst}, #{emit_int32 bits}\n`;
+ first := false)
+ end
+
+(* Adjust sp (up or down) by the given byte amount *)
+
+let emit_stack_adjustment n =
+ if n = 0 then 0 else begin
+ let instr = if n < 0 then "sub" else "add" in
+ let ninstr = decompose_intconst (Int32.of_int (abs n))
+ (fun bits ->
+ ` {emit_string instr} sp, sp, #{emit_int32 bits}\n`) in
+ cfi_adjust_cfa_offset (-n);
+ ninstr
+ end
+
+(* Deallocate the stack frame before a return or tail call *)
+
+let output_epilogue f =
+ let n = frame_size() in
+ if n > 0 then begin
+ let ninstr = emit_stack_adjustment n in
+ let ninstr = ninstr + f () in
+ (* reset CFA back cause function body may continue *)
+ cfi_adjust_cfa_offset n;
+ ninstr
+ end else
+ f ()
+
+(* Name of current function *)
+let function_name = ref ""
+(* Entry point for tail recursive calls *)
+let tailrec_entry_point = ref 0
+(* Pending floating-point literals *)
+let float_literals = ref ([] : (int64 * label) list)
+(* Pending relative references to the global offset table *)
+let gotrel_literals = ref ([] : (label * label) list)
+(* Pending symbol literals *)
+let symbol_literals = ref ([] : (string * label) list)
+(* Total space (in words) occupied by pending literals *)
+let num_literals = ref 0
+
+(* Label a floating-point literal *)
+let float_literal f =
+ let repr = Int64.bits_of_float f in
+ try
+ List.assoc repr !float_literals
+ with Not_found ->
+ let lbl = new_label() in
+ num_literals := !num_literals + 2;
+ float_literals := (repr, lbl) :: !float_literals;
+ lbl
+
+(* Label a GOTREL literal *)
+let gotrel_literal l =
+ let lbl = new_label() in
+ num_literals := !num_literals + 1;
+ gotrel_literals := (l, lbl) :: !gotrel_literals;
+ lbl
+
+(* Label a symbol literal *)
+let symbol_literal s =
+ try
+ List.assoc s !symbol_literals
+ with Not_found ->
+ let lbl = new_label() in
+ num_literals := !num_literals + 1;
+ symbol_literals := (s, lbl) :: !symbol_literals;
+ lbl
+
+(* Emit all pending literals *)
+let emit_literals() =
+ if !float_literals <> [] then begin
+ ` .align 3\n`;
+ List.iter
+ (fun (f, lbl) ->
+ `{emit_label lbl}:`; emit_float64_split_directive ".long" f)
+ !float_literals;
+ float_literals := []
+ end;
+ if !symbol_literals <> [] then begin
+ let offset = if !thumb then 4 else 8 in
+ let suffix = if !Clflags.pic_code then "(GOT)" else "" in
+ ` .align 2\n`;
+ List.iter
+ (fun (l, lbl) ->
+ `{emit_label lbl}: .word _GLOBAL_OFFSET_TABLE_-({emit_label l}+{emit_int offset})\n`)
+ !gotrel_literals;
+ List.iter
+ (fun (s, lbl) ->
+ `{emit_label lbl}: .word {emit_symbol s}{emit_string suffix}\n`)
+ !symbol_literals;
+ gotrel_literals := [];
+ symbol_literals := []
+ end;
+ num_literals := 0
+
+(* Emit code to load the address of a symbol *)
+
+let emit_load_symbol_addr dst s =
+ if !Clflags.pic_code then begin
+ let lbl_pic = new_label() in
+ let lbl_got = gotrel_literal lbl_pic in
+ let lbl_sym = symbol_literal s in
+ (* Both r3 and r12 are marked as clobbered in PIC mode (cf. proc.ml),
+ so use r12 as temporary scratch register unless the destination is
+ r12, then we use r3 instead. *)
+ let tmp = if dst.loc = Reg 8 (*r12*)
+ then phys_reg 3 (*r3*)
+ else phys_reg 8 (*r12*) in
+ ` ldr {emit_reg tmp}, {emit_label lbl_got}\n`;
+ ` ldr {emit_reg dst}, {emit_label lbl_sym}\n`;
+ `{emit_label lbl_pic}: add {emit_reg tmp}, pc, {emit_reg tmp}\n`;
+ ` ldr {emit_reg dst}, [{emit_reg tmp}, {emit_reg dst}] @ {emit_symbol s}\n`;
+ 4
+ end else if !arch > ARMv6 && not !Clflags.dlcode && !fastcode_flag then begin
+ ` movw {emit_reg dst}, #:lower16:{emit_symbol s}\n`;
+ ` movt {emit_reg dst}, #:upper16:{emit_symbol s}\n`;
+ 2
+ end else begin
+ let lbl = symbol_literal s in
+ ` ldr {emit_reg dst}, {emit_label lbl} @ {emit_symbol s}\n`;
+ 1
+ end
+
+(* Output the assembly code for an instruction *)
+
+let emit_instr i =
+ emit_debug_info i.dbg;
+ match i.desc with
+ Lend -> 0
+ | Lop(Imove | Ispill | Ireload) ->
+ let src = i.arg.(0) and dst = i.res.(0) in
+ if src.loc = dst.loc then 0 else begin
+ begin match (src, dst) with
+ {loc = Reg _; typ = Float}, {loc = Reg _} ->
+ ` fcpyd {emit_reg dst}, {emit_reg src}\n`
+ | {loc = Reg _}, {loc = Reg _} ->
+ ` mov {emit_reg dst}, {emit_reg src}\n`
+ | {loc = Reg _; typ = Float}, _ ->
+ ` fstd {emit_reg src}, {emit_stack dst}\n`
+ | {loc = Reg _}, _ ->
+ ` str {emit_reg src}, {emit_stack dst}\n`
+ | {typ = Float}, _ ->
+ ` fldd {emit_reg dst}, {emit_stack src}\n`
+ | _ ->
+ ` ldr {emit_reg dst}, {emit_stack src}\n`
+ end; 1
+ end
+ | Lop(Iconst_int n | Iconst_blockheader n) ->
+ emit_intconst i.res.(0) (Nativeint.to_int32 n)
+ | Lop(Iconst_float f) when !fpu = Soft ->
+ let bits = Int64.bits_of_float f in
+ let high_bits = Int64.to_int32 (Int64.shift_right_logical bits 32)
+ and low_bits = Int64.to_int32 bits in
+ if is_immediate low_bits || is_immediate high_bits then begin
+ let ninstr_low = emit_intconst i.res.(0) low_bits
+ and ninstr_high = emit_intconst i.res.(1) high_bits in
+ ninstr_low + ninstr_high
+ end else begin
+ let lbl = float_literal f in
+ ` ldr {emit_reg i.res.(0)}, {emit_label lbl}\n`;
+ ` ldr {emit_reg i.res.(1)}, {emit_label lbl} + 4\n`;
+ 2
+ end
+ | Lop(Iconst_float f) when !fpu = VFPv2 ->
+ let lbl = float_literal f in
+ ` fldd {emit_reg i.res.(0)}, {emit_label lbl}\n`;
+ 1
+ | Lop(Iconst_float f) ->
+ let encode imm =
+ let sg = Int64.to_int (Int64.shift_right_logical imm 63) in
+ let ex = Int64.to_int (Int64.shift_right_logical imm 52) in
+ let ex = (ex land 0x7ff) - 1023 in
+ let mn = Int64.logand imm 0xfffffffffffffL in
+ if Int64.logand mn 0xffffffffffffL <> 0L || ex < -3 || ex > 4
+ then
+ None
+ else begin
+ let mn = Int64.to_int (Int64.shift_right_logical mn 48) in
+ if mn land 0x0f <> mn then
+ None
+ else
+ let ex = ((ex + 3) land 0x07) lxor 0x04 in
+ Some((sg lsl 7) lor (ex lsl 4) lor mn)
+ end in
+ begin match encode (Int64.bits_of_float f) with
+ None ->
+ let lbl = float_literal f in
+ ` fldd {emit_reg i.res.(0)}, {emit_label lbl}\n`
+ | Some imm8 ->
+ ` fconstd {emit_reg i.res.(0)}, #{emit_int imm8}\n`
+ end; 1
+ | Lop(Iconst_symbol s) ->
+ emit_load_symbol_addr i.res.(0) s
+ | Lop(Icall_ind) ->
+ if !arch >= ARMv5 then begin
+ ` blx {emit_reg i.arg.(0)}\n`;
+ `{record_frame i.live i.dbg}\n`; 1
+ end else begin
+ ` mov lr, pc\n`;
+ ` bx {emit_reg i.arg.(0)}\n`;
+ `{record_frame i.live i.dbg}\n`; 2
+ end
+ | Lop(Icall_imm s) ->
+ ` {emit_call s}\n`;
+ `{record_frame i.live i.dbg}\n`; 1
+ | Lop(Itailcall_ind) ->
+ output_epilogue begin fun () ->
+ if !contains_calls then
+ ` ldr lr, [sp, #{emit_int (-4)}]\n`;
+ ` bx {emit_reg i.arg.(0)}\n`; 2
+ end
+ | Lop(Itailcall_imm s) ->
+ if s = !function_name then begin
+ ` b {emit_label !tailrec_entry_point}\n`; 1
+ end else begin
+ output_epilogue begin fun () ->
+ if !contains_calls then
+ ` ldr lr, [sp, #{emit_int (-4)}]\n`;
+ ` {emit_jump s}\n`; 2
+ end
+ end
+ | Lop(Iextcall(s, false)) ->
+ ` {emit_call s}\n`; 1
+ | Lop(Iextcall(s, true)) ->
+ let ninstr = emit_load_symbol_addr (phys_reg 7 (* r7 *)) s in
+ ` {emit_call "caml_c_call"}\n`;
+ `{record_frame i.live i.dbg}\n`;
+ 1 + ninstr
+ | Lop(Istackoffset n) ->
+ assert (n mod 8 = 0);
+ let ninstr = emit_stack_adjustment (-n) in
+ stack_offset := !stack_offset + n;
+ ninstr
+ | Lop(Iload(Single, addr)) when !fpu >= VFPv2 ->
+ ` flds s14, {emit_addressing addr i.arg 0}\n`;
+ ` fcvtds {emit_reg i.res.(0)}, s14\n`; 2
+ | Lop(Iload((Double | Double_u), addr)) when !fpu = Soft ->
+ (* Use LDM or LDRD if possible *)
+ begin match i.res.(0), i.res.(1), addr with
+ {loc = Reg rt}, {loc = Reg rt2}, Iindexed 0
+ when rt < rt2 ->
+ ` ldm {emit_reg i.arg.(0)}, \{{emit_reg i.res.(0)}, {emit_reg i.res.(1)}}\n`; 1
+ | {loc = Reg rt}, {loc = Reg rt2}, addr
+ when !arch >= ARMv5TE && rt mod 2 == 0 && rt2 = rt + 1 ->
+ ` ldrd {emit_reg i.res.(0)}, {emit_reg i.res.(1)}, {emit_addressing addr i.arg 0}\n`; 1
+ | _ ->
+ let addr' = offset_addressing addr 4 in
+ if i.res.(0).loc <> i.arg.(0).loc then begin
+ ` ldr {emit_reg i.res.(0)}, {emit_addressing addr i.arg 0}\n`;
+ ` ldr {emit_reg i.res.(1)}, {emit_addressing addr' i.arg 0}\n`
+ end else begin
+ ` ldr {emit_reg i.res.(1)}, {emit_addressing addr' i.arg 0}\n`;
+ ` ldr {emit_reg i.res.(0)}, {emit_addressing addr i.arg 0}\n`
+ end; 2
+ end
+ | Lop(Iload(size, addr)) ->
+ let r = i.res.(0) in
+ let instr =
+ match size with
+ Byte_unsigned -> "ldrb"
+ | Byte_signed -> "ldrsb"
+ | Sixteen_unsigned -> "ldrh"
+ | Sixteen_signed -> "ldrsh"
+ | Double
+ | Double_u -> "fldd"
+ | _ (* 32-bit quantities *) -> "ldr" in
+ ` {emit_string instr} {emit_reg r}, {emit_addressing addr i.arg 0}\n`; 1
+ | Lop(Istore(Single, addr, _)) when !fpu >= VFPv2 ->
+ ` fcvtsd s14, {emit_reg i.arg.(0)}\n`;
+ ` fsts s14, {emit_addressing addr i.arg 1}\n`; 2
+ | Lop(Istore((Double | Double_u), addr, _)) when !fpu = Soft ->
+ (* Use STM or STRD if possible *)
+ begin match i.arg.(0), i.arg.(1), addr with
+ {loc = Reg rt}, {loc = Reg rt2}, Iindexed 0
+ when rt < rt2 ->
+ ` stm {emit_reg i.arg.(2)}, \{{emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}}\n`; 1
+ | {loc = Reg rt}, {loc = Reg rt2}, addr
+ when !arch >= ARMv5TE && rt mod 2 == 0 && rt2 = rt + 1 ->
+ ` strd {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_addressing addr i.arg 2}\n`; 1
+ | _ ->
+ let addr' = offset_addressing addr 4 in
+ ` str {emit_reg i.arg.(0)}, {emit_addressing addr i.arg 2}\n`;
+ ` str {emit_reg i.arg.(1)}, {emit_addressing addr' i.arg 2}\n`; 2
+ end
+ | Lop(Istore(size, addr, _)) ->
+ let r = i.arg.(0) in
+ let instr =
+ match size with
+ Byte_unsigned
+ | Byte_signed -> "strb"
+ | Sixteen_unsigned
+ | Sixteen_signed -> "strh"
+ | Double
+ | Double_u -> "fstd"
+ | _ (* 32-bit quantities *) -> "str" in
+ ` {emit_string instr} {emit_reg r}, {emit_addressing addr i.arg 1}\n`; 1
+ | Lop(Ialloc n) ->
+ let lbl_frame = record_frame_label i.live i.dbg in
+ if !fastcode_flag then begin
+ let lbl_redo = new_label() in
+ `{emit_label lbl_redo}:`;
+ let ninstr = decompose_intconst
+ (Int32.of_int n)
+ (fun i ->
+ ` sub alloc_ptr, alloc_ptr, #{emit_int32 i}\n`) in
+ ` cmp alloc_ptr, alloc_limit\n`;
+ ` add {emit_reg i.res.(0)}, alloc_ptr, #4\n`;
+ let lbl_call_gc = new_label() in
+ ` bcc {emit_label lbl_call_gc}\n`;
+ call_gc_sites :=
+ { gc_lbl = lbl_call_gc;
+ gc_return_lbl = lbl_redo;
+ gc_frame_lbl = lbl_frame } :: !call_gc_sites;
+ 3 + ninstr
+ end else begin
+ let ninstr =
+ begin match n with
+ 8 -> ` {emit_call "caml_alloc1"}\n`; 1
+ | 12 -> ` {emit_call "caml_alloc2"}\n`; 1
+ | 16 -> ` {emit_call "caml_alloc3"}\n`; 1
+ | _ -> let ninstr = emit_intconst (phys_reg 7) (Int32.of_int n) in
+ ` {emit_call "caml_allocN"}\n`; 1 + ninstr
+ end in
+ `{emit_label lbl_frame}: add {emit_reg i.res.(0)}, alloc_ptr, #4\n`;
+ 1 + ninstr
+ end
+ | Lop(Iintop(Icomp cmp)) ->
+ let compthen = name_for_comparison cmp in
+ let compelse = name_for_comparison (negate_integer_comparison cmp) in
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` ite {emit_string compthen}\n`;
+ ` mov{emit_string compthen} {emit_reg i.res.(0)}, #1\n`;
+ ` mov{emit_string compelse} {emit_reg i.res.(0)}, #0\n`; 4
+ | Lop(Iintop_imm(Icomp cmp, n)) ->
+ let compthen = name_for_comparison cmp in
+ let compelse = name_for_comparison (negate_integer_comparison cmp) in
+ ` cmp {emit_reg i.arg.(0)}, #{emit_int n}\n`;
+ ` ite {emit_string compthen}\n`;
+ ` mov{emit_string compthen} {emit_reg i.res.(0)}, #1\n`;
+ ` mov{emit_string compelse} {emit_reg i.res.(0)}, #0\n`; 4
+ | Lop(Iintop Icheckbound) ->
+ let lbl = bound_error_label i.dbg in
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` bls {emit_label lbl}\n`; 2
+ | Lop(Iintop_imm(Icheckbound, n)) ->
+ let lbl = bound_error_label i.dbg in
+ ` cmp {emit_reg i.arg.(0)}, #{emit_int n}\n`;
+ ` bls {emit_label lbl}\n`; 2
+ | Lop(Ispecific(Ishiftcheckbound(shiftop, n))) ->
+ let lbl = bound_error_label i.dbg in
+ let op = name_for_shift_operation shiftop in
+ ` cmp {emit_reg i.arg.(1)}, {emit_reg i.arg.(0)}, {emit_string op} #{emit_int n}\n`;
+ ` bcs {emit_label lbl}\n`; 2
+ | Lop(Iintop Imulh) when !arch < ARMv6 ->
+ ` smull r12, {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`; 1
+ | Lop(Ispecific Imulhadd) ->
+ ` smmla {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.arg.(2)}\n`; 1
+ | Lop(Iintop op) ->
+ let instr = name_for_int_operation op in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`; 1
+ | Lop(Iintop_imm(op, n)) ->
+ let instr = name_for_int_operation op in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, #{emit_int n}\n`; 1
+ | Lop(Iabsf | Inegf as op) when !fpu = Soft ->
+ let instr = (match op with
+ Iabsf -> "bic"
+ | Inegf -> "eor"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(1)}, {emit_reg i.arg.(1)}, #0x80000000\n`; 1
+ | Lop(Iabsf | Inegf | Ispecific Isqrtf as op) ->
+ let instr = (match op with
+ Iabsf -> "fabsd"
+ | Inegf -> "fnegd"
+ | Ispecific Isqrtf -> "fsqrtd"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}\n`; 1
+ | Lop(Ifloatofint) ->
+ ` fmsr s14, {emit_reg i.arg.(0)}\n`;
+ ` fsitod {emit_reg i.res.(0)}, s14\n`; 2
+ | Lop(Iintoffloat) ->
+ ` ftosizd s14, {emit_reg i.arg.(0)}\n`;
+ ` fmrs {emit_reg i.res.(0)}, s14\n`; 2
+ | Lop(Iaddf | Isubf | Imulf | Idivf | Ispecific Inegmulf as op) ->
+ let instr = (match op with
+ Iaddf -> "faddd"
+ | Isubf -> "fsubd"
+ | Imulf -> "fmuld"
+ | Idivf -> "fdivd"
+ | Ispecific Inegmulf -> "fnmuld"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ 1
+ | Lop(Ispecific(Imuladdf | Inegmuladdf | Imulsubf | Inegmulsubf as op)) ->
+ let instr = (match op with
+ Imuladdf -> "fmacd"
+ | Inegmuladdf -> "fnmacd"
+ | Imulsubf -> "fmscd"
+ | Inegmulsubf -> "fnmscd"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.arg.(2)}\n`;
+ 1
+ | Lop(Ispecific(Ishiftarith(op, shiftop, n))) ->
+ let instr = (match op with
+ Ishiftadd -> "add"
+ | Ishiftsub -> "sub"
+ | Ishiftsubrev -> "rsb"
+ | Ishiftand -> "and"
+ | Ishiftor -> "orr"
+ | Ishiftxor -> "eor") in
+ let op = name_for_shift_operation shiftop in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_string op} #{emit_int n}\n`; 1
+ | Lop(Ispecific(Irevsubimm n)) ->
+ ` rsb {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, #{emit_int n}\n`; 1
+ | Lop(Ispecific(Imuladd | Imulsub as op)) ->
+ let instr = (match op with
+ Imuladd -> "mla"
+ | Imulsub -> "mls"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.arg.(2)}\n`; 1
+ | Lop(Ispecific(Ibswap size)) ->
+ begin match size with
+ 16 ->
+ ` rev16 {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}\n`;
+ ` movt {emit_reg i.res.(0)}, #0\n`; 2
+ | 32 ->
+ ` rev {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}\n`; 1
+ | _ ->
+ assert false
+ end
+ | Lreloadretaddr ->
+ let n = frame_size() in
+ ` ldr lr, [sp, #{emit_int(n-4)}]\n`; 1
+ | Lreturn ->
+ output_epilogue begin fun () ->
+ ` bx lr\n`; 1
+ end
+ | Llabel lbl ->
+ `{emit_label lbl}:\n`; 0
+ | Lbranch lbl ->
+ ` b {emit_label lbl}\n`; 1
+ | Lcondbranch(tst, lbl) ->
+ begin match tst with
+ Itruetest ->
+ ` cmp {emit_reg i.arg.(0)}, #0\n`;
+ ` bne {emit_label lbl}\n`; 2
+ | Ifalsetest ->
+ ` cmp {emit_reg i.arg.(0)}, #0\n`;
+ ` beq {emit_label lbl}\n`; 2
+ | Iinttest cmp ->
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ let comp = name_for_comparison cmp in
+ ` b{emit_string comp} {emit_label lbl}\n`; 2
+ | Iinttest_imm(cmp, n) ->
+ ` cmp {emit_reg i.arg.(0)}, #{emit_int n}\n`;
+ let comp = name_for_comparison cmp in
+ ` b{emit_string comp} {emit_label lbl}\n`; 2
+ | Ifloattest(cmp, neg) ->
+ let comp = (match (cmp, neg) with
+ (Ceq, false) | (Cne, true) -> "eq"
+ | (Cne, false) | (Ceq, true) -> "ne"
+ | (Clt, false) -> "cc"
+ | (Clt, true) -> "cs"
+ | (Cle, false) -> "ls"
+ | (Cle, true) -> "hi"
+ | (Cgt, false) -> "gt"
+ | (Cgt, true) -> "le"
+ | (Cge, false) -> "ge"
+ | (Cge, true) -> "lt") in
+ ` fcmpd {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` fmstat\n`;
+ ` b{emit_string comp} {emit_label lbl}\n`; 3
+ | Ioddtest ->
+ ` tst {emit_reg i.arg.(0)}, #1\n`;
+ ` bne {emit_label lbl}\n`; 2
+ | Ieventest ->
+ ` tst {emit_reg i.arg.(0)}, #1\n`;
+ ` beq {emit_label lbl}\n`; 2
+ end
+ | Lcondbranch3(lbl0, lbl1, lbl2) ->
+ ` cmp {emit_reg i.arg.(0)}, #1\n`;
+ begin match lbl0 with
+ None -> ()
+ | Some lbl -> ` blt {emit_label lbl}\n`
+ end;
+ begin match lbl1 with
+ None -> ()
+ | Some lbl -> ` beq {emit_label lbl}\n`
+ end;
+ begin match lbl2 with
+ None -> ()
+ | Some lbl -> ` bgt {emit_label lbl}\n`
+ end;
+ 4
+ | Lswitch jumptbl ->
+ if !arch > ARMv6 && !thumb then begin
+ (* The Thumb-2 TBH instruction supports only forward branches,
+ so we need to generate appropriate trampolines for all labels
+ that appear before this switch instruction (PR#5623) *)
+ let tramtbl = Array.copy jumptbl in
+ ` tbh [pc, {emit_reg i.arg.(0)}, lsl #1]\n`;
+ for j = 0 to Array.length tramtbl - 1 do
+ let rec label i =
+ match i.desc with
+ Lend -> new_label()
+ | Llabel lbl when lbl = tramtbl.(j) -> lbl
+ | _ -> label i.next in
+ tramtbl.(j) <- label i.next;
+ ` .short ({emit_label tramtbl.(j)}-.)/2+{emit_int j}\n`
+ done;
+ (* Generate the necessary trampolines *)
+ for j = 0 to Array.length tramtbl - 1 do
+ if tramtbl.(j) <> jumptbl.(j) then
+ `{emit_label tramtbl.(j)}: b {emit_label jumptbl.(j)}\n`
+ done
+ end else if not !Clflags.pic_code then begin
+ ` ldr pc, [pc, {emit_reg i.arg.(0)}, lsl #2]\n`;
+ ` nop\n`;
+ for j = 0 to Array.length jumptbl - 1 do
+ ` .word {emit_label jumptbl.(j)}\n`
+ done
+ end else begin
+ (* Slightly slower, but position-independent *)
+ ` add pc, pc, {emit_reg i.arg.(0)}, lsl #2\n`;
+ ` nop\n`;
+ for j = 0 to Array.length jumptbl - 1 do
+ ` b {emit_label jumptbl.(j)}\n`
+ done
+ end;
+ 2 + Array.length jumptbl
+ | Lsetuptrap lbl ->
+ ` bl {emit_label lbl}\n`; 1
+ | Lpushtrap ->
+ stack_offset := !stack_offset + 8;
+ ` push \{trap_ptr, lr}\n`;
+ cfi_adjust_cfa_offset 8;
+ ` mov trap_ptr, sp\n`; 2
+ | Lpoptrap ->
+ ` pop \{trap_ptr, lr}\n`;
+ cfi_adjust_cfa_offset (-8);
+ stack_offset := !stack_offset - 8; 1
+ | Lraise k ->
+ begin match !Clflags.debug, k with
+ | true, (Lambda.Raise_regular | Lambda.Raise_reraise) ->
+ ` {emit_call "caml_raise_exn"}\n`;
+ `{record_frame Reg.Set.empty i.dbg}\n`; 1
+ | false, _
+ | true, Lambda.Raise_notrace ->
+ ` mov sp, trap_ptr\n`;
+ ` pop \{trap_ptr, pc}\n`; 2
+ end
+
+(* Emission of an instruction sequence *)
+
+let rec emit_all ninstr i =
+ if i.desc = Lend then () else begin
+ let n = emit_instr i in
+ let ninstr' = ninstr + n in
+ (* fldd can address up to +/-1KB, ldr can address up to +/-4KB *)
+ let limit = (if !fpu >= VFPv2 && !float_literals <> []
+ then 127
+ else 511) in
+ let limit = limit - !num_literals in
+ if ninstr' >= limit - 64 && not(has_fallthrough i.desc) then begin
+ emit_literals();
+ emit_all 0 i.next
+ end else if !num_literals != 0 && ninstr' >= limit then begin
+ let lbl = new_label() in
+ ` b {emit_label lbl}\n`;
+ emit_literals();
+ `{emit_label lbl}:\n`;
+ emit_all 0 i.next
+ end else
+ emit_all ninstr' i.next
+ end
+
+(* Emission of the profiling prelude *)
+
+let emit_profile() =
+ match Config.system with
+ "linux_eabi" | "linux_eabihf" ->
+ ` push \{lr}\n`;
+ ` {emit_call "__gnu_mcount_nc"}\n`
+ | _ -> ()
+
+(* Emission of a function declaration *)
+
+let fundecl fundecl =
+ function_name := fundecl.fun_name;
+ fastcode_flag := fundecl.fun_fast;
+ tailrec_entry_point := new_label();
+ float_literals := [];
+ gotrel_literals := [];
+ symbol_literals := [];
+ stack_offset := 0;
+ call_gc_sites := [];
+ bound_error_sites := [];
+ ` .text\n`;
+ ` .align 2\n`;
+ ` .globl {emit_symbol fundecl.fun_name}\n`;
+ if !arch > ARMv6 && !thumb then
+ ` .thumb\n`
+ else
+ ` .arm\n`;
+ ` .type {emit_symbol fundecl.fun_name}, %function\n`;
+ `{emit_symbol fundecl.fun_name}:\n`;
+ emit_debug_info fundecl.fun_dbg;
+ cfi_startproc();
+ if !Clflags.gprofile then emit_profile();
+ let n = frame_size() in
+ if n > 0 then begin
+ ignore(emit_stack_adjustment (-n));
+ if !contains_calls then begin
+ cfi_offset ~reg:14 (* lr *) ~offset:(-4);
+ ` str lr, [sp, #{emit_int(n - 4)}]\n`
+ end
+ end;
+ `{emit_label !tailrec_entry_point}:\n`;
+ emit_all 0 fundecl.fun_body;
+ emit_literals();
+ List.iter emit_call_gc !call_gc_sites;
+ List.iter emit_call_bound_error !bound_error_sites;
+ cfi_endproc();
+ ` .type {emit_symbol fundecl.fun_name}, %function\n`;
+ ` .size {emit_symbol fundecl.fun_name}, .-{emit_symbol fundecl.fun_name}\n`
+
+(* Emission of data *)
+
+let emit_item = function
+ Cglobal_symbol s -> ` .globl {emit_symbol s}\n`;
+ | Cdefine_symbol s -> `{emit_symbol s}:\n`
+ | Cdefine_label lbl -> `{emit_data_label lbl}:\n`
+ | Cint8 n -> ` .byte {emit_int n}\n`
+ | Cint16 n -> ` .short {emit_int n}\n`
+ | Cint32 n -> ` .long {emit_int32 (Nativeint.to_int32 n)}\n`
+ | Cint n -> ` .long {emit_int32 (Nativeint.to_int32 n)}\n`
+ | Csingle f -> emit_float32_directive ".long" (Int32.bits_of_float f)
+ | Cdouble f -> emit_float64_split_directive ".long" (Int64.bits_of_float f)
+ | Csymbol_address s -> ` .word {emit_symbol s}\n`
+ | Clabel_address lbl -> ` .word {emit_data_label lbl}\n`
+ | Cstring s -> emit_string_directive " .ascii " s
+ | Cskip n -> if n > 0 then ` .space {emit_int n}\n`
+ | Calign n -> ` .align {emit_int(Misc.log2 n)}\n`
+
+let data l =
+ ` .data\n`;
+ List.iter emit_item l
+
+(* Beginning / end of an assembly file *)
+
+let begin_assembly() =
+ reset_debug_info();
+ ` .syntax unified\n`;
+ begin match !arch with
+ | ARMv4 -> ` .arch armv4t\n`
+ | ARMv5 -> ` .arch armv5t\n`
+ | ARMv5TE -> ` .arch armv5te\n`
+ | ARMv6 -> ` .arch armv6\n`
+ | ARMv6T2 -> ` .arch armv6t2\n`
+ | ARMv7 -> ` .arch armv7-a\n`
+ end;
+ begin match !fpu with
+ Soft -> ` .fpu softvfp\n`
+ | VFPv2 -> ` .fpu vfpv2\n`
+ | VFPv3_D16 -> ` .fpu vfpv3-d16\n`
+ | VFPv3 -> ` .fpu vfpv3\n`
+ end;
+ `trap_ptr .req r8\n`;
+ `alloc_ptr .req r10\n`;
+ `alloc_limit .req r11\n`;
+ let lbl_begin = Compilenv.make_symbol (Some "data_begin") in
+ ` .data\n`;
+ ` .globl {emit_symbol lbl_begin}\n`;
+ `{emit_symbol lbl_begin}:\n`;
+ let lbl_begin = Compilenv.make_symbol (Some "code_begin") in
+ ` .text\n`;
+ ` .globl {emit_symbol lbl_begin}\n`;
+ `{emit_symbol lbl_begin}:\n`
+
+let end_assembly () =
+ let lbl_end = Compilenv.make_symbol (Some "code_end") in
+ ` .text\n`;
+ ` .globl {emit_symbol lbl_end}\n`;
+ `{emit_symbol lbl_end}:\n`;
+ let lbl_end = Compilenv.make_symbol (Some "data_end") in
+ ` .data\n`;
+ ` .globl {emit_symbol lbl_end}\n`;
+ `{emit_symbol lbl_end}:\n`;
+ ` .long 0\n`;
+ let lbl = Compilenv.make_symbol (Some "frametable") in
+ ` .globl {emit_symbol lbl}\n`;
+ `{emit_symbol lbl}:\n`;
+ emit_frames
+ { efa_label = (fun lbl ->
+ ` .type {emit_label lbl}, %function\n`;
+ ` .word {emit_label lbl}\n`);
+ efa_16 = (fun n -> ` .short {emit_int n}\n`);
+ efa_32 = (fun n -> ` .long {emit_int32 n}\n`);
+ efa_word = (fun n -> ` .word {emit_int n}\n`);
+ efa_align = (fun n -> ` .align {emit_int(Misc.log2 n)}\n`);
+ efa_label_rel = (fun lbl ofs ->
+ ` .word {emit_label lbl} - . + {emit_int32 ofs}\n`);
+ efa_def_label = (fun lbl -> `{emit_label lbl}:\n`);
+ efa_string = (fun s -> emit_string_directive " .asciz " s) };
+ ` .type {emit_symbol lbl}, %object\n`;
+ ` .size {emit_symbol lbl}, .-{emit_symbol lbl}\n`;
+ begin match Config.system with
+ "linux_eabihf" | "linux_eabi" ->
+ (* Mark stack as non-executable *)
+ ` .section .note.GNU-stack,\"\",%progbits\n`
+ | _ -> ()
+ end
diff --git a/asmcomp/arm/proc.ml b/asmcomp/arm/proc.ml
new file mode 100644
index 0000000000..9c088751ed
--- /dev/null
+++ b/asmcomp/arm/proc.ml
@@ -0,0 +1,307 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Description of the ARM processor *)
+
+open Misc
+open Cmm
+open Reg
+open Arch
+open Mach
+
+(* Instruction selection *)
+
+let word_addressed = false
+
+(* Registers available for register allocation *)
+
+(* Integer register map:
+ r0 - r3 general purpose (not preserved)
+ r4 - r7 general purpose (preserved)
+ r8 trap pointer (preserved)
+ r9 platform register, usually reserved
+ r10 allocation pointer (preserved)
+ r11 allocation limit (preserved)
+ r12 intra-procedural scratch register (not preserved)
+ r13 stack pointer
+ r14 return address
+ r15 program counter
+ Floating-point register map (VFPv{2,3}):
+ d0 - d7 general purpose (not preserved)
+ d8 - d15 general purpose (preserved)
+ d16 - d31 generat purpose (not preserved), VFPv3 only
+*)
+
+let int_reg_name =
+ [| "r0"; "r1"; "r2"; "r3"; "r4"; "r5"; "r6"; "r7"; "r12" |]
+
+let float_reg_name =
+ [| "d0"; "d1"; "d2"; "d3"; "d4"; "d5"; "d6"; "d7";
+ "d8"; "d9"; "d10"; "d11"; "d12"; "d13"; "d14"; "d15";
+ "d16"; "d17"; "d18"; "d19"; "d20"; "d21"; "d22"; "d23";
+ "d24"; "d25"; "d26"; "d27"; "d28"; "d29"; "d30"; "d31" |]
+
+(* We have three register classes:
+ 0 for integer registers
+ 1 for VFPv2 and VFPv3-D16
+ 2 for VFPv3
+ This way we can choose between VFPv2/VFPv3-D16 and VFPv3
+ at (ocamlopt) runtime using command line switches.
+*)
+
+let num_register_classes = 3
+
+let register_class r =
+ match (r.typ, !fpu) with
+ | (Val | Int | Addr), _ -> 0
+ | Float, VFPv2 -> 1
+ | Float, VFPv3_D16 -> 1
+ | Float, _ -> 2
+
+let num_available_registers =
+ [| 9; 16; 32 |]
+
+let first_available_register =
+ [| 0; 100; 100 |]
+
+let register_name r =
+ if r < 100 then int_reg_name.(r) else float_reg_name.(r - 100)
+
+let rotate_registers = true
+
+(* Representation of hard registers by pseudo-registers *)
+
+let hard_int_reg =
+ let v = Array.make 9 Reg.dummy in
+ for i = 0 to 8 do
+ v.(i) <- Reg.at_location Int (Reg i)
+ done;
+ v
+
+let hard_float_reg =
+ let v = Array.make 32 Reg.dummy in
+ for i = 0 to 31 do
+ v.(i) <- Reg.at_location Float (Reg(100 + i))
+ done;
+ v
+
+let all_phys_regs =
+ Array.append hard_int_reg hard_float_reg
+
+let phys_reg n =
+ if n < 100 then hard_int_reg.(n) else hard_float_reg.(n - 100)
+
+let stack_slot slot ty =
+ Reg.at_location ty (Stack slot)
+
+(* Calling conventions *)
+
+let calling_conventions first_int last_int first_float last_float make_stack
+ arg =
+ let loc = Array.make (Array.length arg) [| Reg.dummy |] in
+ let int = ref first_int in
+ let float = ref first_float in
+ let ofs = ref 0 in
+ for i = 0 to Array.length arg - 1 do
+ match arg.(i) with
+ | [| arg |] ->
+ begin match arg.typ with
+ | Val | Int | Addr as ty ->
+ if !int <= last_int then begin
+ loc.(i) <- [| phys_reg !int |];
+ incr int
+ end else begin
+ loc.(i) <- [| stack_slot (make_stack !ofs) ty |];
+ ofs := !ofs + size_int
+ end
+ | Float ->
+ assert (abi = EABI_HF);
+ assert (!fpu >= VFPv2);
+ if !float <= last_float then begin
+ loc.(i) <- [| phys_reg !float |];
+ incr float
+ end else begin
+ ofs := Misc.align !ofs size_float;
+ loc.(i) <- [| stack_slot (make_stack !ofs) Float |];
+ ofs := !ofs + size_float
+ end
+ end
+ | [| arg1; arg2 |] ->
+ (* Passing of 64-bit quantities to external functions. *)
+ begin match arg1.typ, arg2.typ with
+ | Int, Int ->
+ (* 64-bit quantities split across two registers must either be in a
+ consecutive pair of registers where the lowest numbered is an
+ even-numbered register; or in a stack slot that is 8-byte
+ aligned. *)
+ int := Misc.align !int 2;
+ if !int <= last_int - 1 then begin
+ let reg_least = phys_reg !int in
+ let reg_most = phys_reg (1 + !int) in
+ loc.(i) <- [| reg_least; reg_most |];
+ int := !int + 2
+ end else begin
+ let size_int64 = size_int * 2 in
+ ofs := Misc.align !ofs size_int64;
+ let stack_least = stack_slot (make_stack !ofs) Int in
+ let stack_most = stack_slot (make_stack (size_int + !ofs)) Int in
+ loc.(i) <- [| stack_least; stack_most |];
+ ofs := !ofs + size_int64
+ end
+ | _, _ ->
+ let f = function Int -> "I" | Addr -> "A" | Val -> "V" | Float -> "F" in
+ fatal_error (Printf.sprintf "Proc.calling_conventions: bad register \
+ type(s) for multi-register argument: %s, %s"
+ (f arg1.typ) (f arg2.typ))
+ end
+ | _ ->
+ fatal_error "Proc.calling_conventions: bad number of registers for \
+ multi-register argument"
+ done;
+ (loc, Misc.align !ofs 8) (* keep stack 8-aligned *)
+
+let incoming ofs = Incoming ofs
+let outgoing ofs = Outgoing ofs
+let not_supported ofs = fatal_error "Proc.loc_results: cannot call"
+
+(* OCaml calling convention:
+ first integer args in r0...r7
+ first float args in d0...d15 (EABI+VFP)
+ remaining args on stack.
+ Return values in r0...r7 or d0...d15. *)
+
+let single_regs arg = Array.map (fun arg -> [| arg |]) arg
+let ensure_single_regs res =
+ Array.map (function
+ | [| res |] -> res
+ | _ -> failwith "Proc.ensure_single_regs")
+ res
+
+let loc_arguments arg =
+ let (loc, alignment) =
+ calling_conventions 0 7 100 115 outgoing (single_regs arg)
+ in
+ ensure_single_regs loc, alignment
+let loc_parameters arg =
+ let (loc, _) = calling_conventions 0 7 100 115 incoming (single_regs arg) in
+ ensure_single_regs loc
+let loc_results res =
+ let (loc, _) =
+ calling_conventions 0 7 100 115 not_supported (single_regs res)
+ in
+ ensure_single_regs loc
+
+(* C calling convention:
+ first integer args in r0...r3
+ first float args in d0...d7 (EABI+VFP)
+ remaining args on stack.
+ Return values in r0...r1 or d0. *)
+
+let loc_external_arguments arg =
+ calling_conventions 0 3 100 107 outgoing arg
+let loc_external_results res =
+ let (loc, _) =
+ calling_conventions 0 1 100 100 not_supported (single_regs res)
+ in
+ ensure_single_regs loc
+
+let loc_exn_bucket = phys_reg 0
+
+(* Volatile registers: none *)
+
+let regs_are_volatile rs = false
+
+(* Registers destroyed by operations *)
+
+let destroyed_at_alloc = (* r0-r6, d0-d15 preserved *)
+ Array.of_list (List.map
+ phys_reg
+ [7;8;
+ 116;117;118;119;120;121;122;123;
+ 124;125;126;127;128;129;130;131])
+
+let destroyed_at_c_call =
+ Array.of_list (List.map
+ phys_reg
+ (match abi with
+ EABI -> (* r4-r7 preserved *)
+ [0;1;2;3;8;
+ 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]
+ | EABI_HF -> (* r4-r7, d8-d15 preserved *)
+ [0;1;2;3;8;
+ 100;101;102;103;104;105;106;107;
+ 116;117;118;119;120;121;122;123;
+ 124;125;126;127;128;129;130;131]))
+
+let destroyed_at_oper = function
+ Iop(Icall_ind | Icall_imm _)
+ | Iop(Iextcall(_, true)) ->
+ all_phys_regs
+ | Iop(Iextcall(_, false)) ->
+ destroyed_at_c_call
+ | Iop(Ialloc _) ->
+ destroyed_at_alloc
+ | Iop(Iconst_symbol _) when !Clflags.pic_code ->
+ [| phys_reg 3; phys_reg 8 |] (* r3 and r12 destroyed *)
+ | Iop(Iintop Imulh) when !arch < ARMv6 ->
+ [| phys_reg 8 |] (* r12 destroyed *)
+ | Iop(Iintoffloat | Ifloatofint | Iload(Single, _) | Istore(Single, _, _)) ->
+ [| phys_reg 107 |] (* d7 (s14-s15) destroyed *)
+ | _ -> [||]
+
+let destroyed_at_raise = all_phys_regs
+
+(* Maximal register pressure *)
+
+let safe_register_pressure = function
+ Iextcall(_, _) -> if abi = EABI then 0 else 4
+ | Ialloc _ -> if abi = EABI then 0 else 7
+ | Iconst_symbol _ when !Clflags.pic_code -> 7
+ | Iintop Imulh when !arch < ARMv6 -> 8
+ | _ -> 9
+
+let max_register_pressure = function
+ Iextcall(_, _) -> if abi = EABI then [| 4; 0; 0 |] else [| 4; 8; 8 |]
+ | Ialloc _ -> if abi = EABI then [| 7; 0; 0 |] else [| 7; 8; 8 |]
+ | Iconst_symbol _ when !Clflags.pic_code -> [| 7; 16; 32 |]
+ | Iintoffloat | Ifloatofint
+ | Iload(Single, _) | Istore(Single, _, _) -> [| 9; 15; 31 |]
+ | Iintop Imulh when !arch < ARMv6 -> [| 8; 16; 32 |]
+ | _ -> [| 9; 16; 32 |]
+
+(* Pure operations (without any side effect besides updating their result
+ registers). *)
+
+let op_is_pure = function
+ | Icall_ind | Icall_imm _ | Itailcall_ind | Itailcall_imm _
+ | Iextcall _ | Istackoffset _ | Istore _ | Ialloc _
+ | Iintop(Icheckbound) | Iintop_imm(Icheckbound, _)
+ | Ispecific(Ishiftcheckbound _) -> false
+ | _ -> true
+
+(* Layout of the stack *)
+
+let num_stack_slots = [| 0; 0; 0 |]
+let contains_calls = ref false
+
+(* Calling the assembler *)
+
+let assemble_file infile outfile =
+ Ccomp.command (Config.asm ^ " -o " ^
+ Filename.quote outfile ^ " " ^ Filename.quote infile)
+
+
+let init () = ()
diff --git a/asmcomp/arm/reload.ml b/asmcomp/arm/reload.ml
new file mode 100644
index 0000000000..bd783acb82
--- /dev/null
+++ b/asmcomp/arm/reload.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Reloading for the ARM *)
+
+let fundecl f =
+ (new Reloadgen.reload_generic)#fundecl f
diff --git a/asmcomp/arm/scheduling.ml b/asmcomp/arm/scheduling.ml
new file mode 100644
index 0000000000..0d6618ab9e
--- /dev/null
+++ b/asmcomp/arm/scheduling.ml
@@ -0,0 +1,77 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Arch
+open Mach
+
+(* Instruction scheduling for the ARM *)
+
+class scheduler = object(self)
+
+inherit Schedgen.scheduler_generic as super
+
+(* Scheduling -- based roughly on the ARM11 (ARMv6) *)
+
+method oper_latency = function
+ (* Loads have a latency of two cycles in general *)
+ Iconst_symbol _
+ | Iconst_float _
+ | Iload(_, _)
+ | Ireload
+ | Ifloatofint (* mcr/mrc count as memory access *)
+ | Iintoffloat -> 2
+ (* Multiplys have a latency of two cycles *)
+ | Iintop (Imul | Imulh)
+ | Ispecific(Imuladd | Imulsub | Imulhadd) -> 2
+ (* VFP instructions *)
+ | Iaddf
+ | Isubf
+ | Idivf
+ | Imulf | Ispecific Inegmulf
+ | Ispecific(Imuladdf | Inegmuladdf | Imulsubf | Inegmulsubf)
+ | Ispecific Isqrtf
+ | Inegf | Iabsf when !fpu >= VFPv2 -> 2
+ (* Everything else *)
+ | _ -> 1
+
+method! is_checkbound = function
+ Ispecific(Ishiftcheckbound _) -> true
+ | op -> super#is_checkbound op
+
+(* Issue cycles. Rough approximations *)
+
+method oper_issue_cycles = function
+ Ialloc _ -> 4
+ | Iintop(Ilsl | Ilsr | Iasr) -> 2
+ | Iintop(Icomp _)
+ | Iintop_imm(Icomp _, _) -> 3
+ | Iintop(Icheckbound)
+ | Iintop_imm(Icheckbound, _) -> 2
+ | Ispecific(Ishiftcheckbound _) -> 3
+ | Iintop(Imul | Imulh)
+ | Ispecific(Imuladd | Imulsub | Imulhadd) -> 2
+ (* VFP instructions *)
+ | Iaddf
+ | Isubf -> 7
+ | Imulf
+ | Ispecific Inegmulf -> 9
+ | Ispecific(Imuladdf | Inegmuladdf | Imulsubf | Inegmulsubf) -> 17
+ | Idivf
+ | Ispecific Isqrtf -> 27
+ | Inegf | Iabsf | Iconst_float _ when !fpu >= VFPv2 -> 4
+ (* Everything else *)
+ | _ -> 1
+
+end
+
+let fundecl f = (new scheduler)#schedule_fundecl f
diff --git a/asmcomp/arm/selection.ml b/asmcomp/arm/selection.ml
new file mode 100644
index 0000000000..6835804668
--- /dev/null
+++ b/asmcomp/arm/selection.ml
@@ -0,0 +1,295 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction selection for the ARM processor *)
+
+open Arch
+open Proc
+open Cmm
+open Mach
+
+let is_offset chunk n =
+ match chunk with
+ (* VFPv{2,3} load/store have -1020 to 1020 *)
+ Single | Double | Double_u
+ when !fpu >= VFPv2 ->
+ n >= -1020 && n <= 1020
+ (* ARM load/store byte/word have -4095 to 4095 *)
+ | Byte_unsigned | Byte_signed
+ | Thirtytwo_unsigned | Thirtytwo_signed
+ | Word_int | Word_val | Single
+ when not !thumb ->
+ n >= -4095 && n <= 4095
+ (* Thumb-2 load/store have -255 to 4095 *)
+ | _ when !arch > ARMv6 && !thumb ->
+ n >= -255 && n <= 4095
+ (* Everything else has -255 to 255 *)
+ | _ ->
+ n >= -255 && n <= 255
+
+let select_shiftop = function
+ Clsl -> Ishiftlogicalleft
+ | Clsr -> Ishiftlogicalright
+ | Casr -> Ishiftarithmeticright
+ | __-> assert false
+
+(* Special constraints on operand and result registers *)
+
+exception Use_default
+
+let r1 = phys_reg 1
+let r6 = phys_reg 6
+let r7 = phys_reg 7
+let r12 = phys_reg 8
+
+let pseudoregs_for_operation op arg res =
+ match op with
+ (* For mul rd,rm,rs and mla rd,rm,rs,ra (pre-ARMv6) the registers rm
+ and rd must be different. We deal with this by pretending that rm
+ is also a result of the mul / mla operation. *)
+ Iintop Imul | Ispecific Imuladd when !arch < ARMv6 ->
+ (arg, [| res.(0); arg.(0) |])
+ (* For smull rdlo,rdhi,rn,rm (pre-ARMv6) the registers rdlo, rdhi and rn
+ must be different. Also, rdlo (whose contents we discard) is always
+ forced to be r12 in proc.ml, which means that neither rdhi and rn can
+ be r12. To keep things simple, we force both of those two to specific
+ hard regs: rdhi in r6 and rn in r7. *)
+ | Iintop Imulh when !arch < ARMv6 ->
+ ([| r7; arg.(1) |], [| r6 |])
+ (* Soft-float Iabsf and Inegf: arg.(0) and res.(0) must be the same *)
+ | Iabsf | Inegf when !fpu = Soft ->
+ ([|res.(0); arg.(1)|], res)
+ (* VFPv{2,3} Imuladdf...Inegmulsubf: arg.(0) and res.(0) must be the same *)
+ | Ispecific(Imuladdf | Inegmuladdf | Imulsubf | Inegmulsubf) ->
+ let arg' = Array.copy arg in
+ arg'.(0) <- res.(0);
+ (arg', res)
+ (* We use __aeabi_idivmod for Cmodi only, and hence we care only
+ for the remainder in r1, so fix up the destination register. *)
+ | Iextcall("__aeabi_idivmod", false) ->
+ (arg, [|r1|])
+ (* Other instructions are regular *)
+ | _ -> raise Use_default
+
+(* Instruction selection *)
+class selector = object(self)
+
+inherit Selectgen.selector_generic as super
+
+method! regs_for tyv =
+ Reg.createv (if !fpu = Soft then begin
+ (* Expand floats into pairs of integer registers *)
+ (* CR mshinwell: we need to check this in conjunction with
+ the unboxed external functionality *)
+ let rec expand = function
+ [] -> []
+ | Float :: tyl -> Int :: Int :: expand tyl
+ | ty :: tyl -> ty :: expand tyl in
+ Array.of_list (expand (Array.to_list tyv))
+ end else begin
+ tyv
+ end)
+
+method is_immediate n =
+ is_immediate (Int32.of_int n)
+
+method! is_simple_expr = function
+ (* inlined floating-point ops are simple if their arguments are *)
+ | Cop(Cextcall("sqrt", _, _, _), args) when !fpu >= VFPv2 ->
+ List.for_all self#is_simple_expr args
+ (* inlined byte-swap ops are simple if their arguments are *)
+ | Cop(Cextcall("caml_bswap16_direct", _, _, _), args) when !arch >= ARMv6T2 ->
+ List.for_all self#is_simple_expr args
+ | Cop(Cextcall("caml_int32_direct_bswap", _,_,_), args) when !arch >= ARMv6 ->
+ List.for_all self#is_simple_expr args
+ | e -> super#is_simple_expr e
+
+method select_addressing chunk = function
+ | Cop((Cadda | Caddv), [arg; Cconst_int n])
+ when is_offset chunk n ->
+ (Iindexed n, arg)
+ | Cop((Cadda | Caddv as op), [arg1; Cop(Caddi, [arg2; Cconst_int n])])
+ when is_offset chunk n ->
+ (Iindexed n, Cop(op, [arg1; arg2]))
+ | arg ->
+ (Iindexed 0, arg)
+
+method select_shift_arith op arithop arithrevop args =
+ match args with
+ [arg1; Cop(Clsl | Clsr | Casr as op, [arg2; Cconst_int n])]
+ when n > 0 && n < 32 ->
+ (Ispecific(Ishiftarith(arithop, select_shiftop op, n)), [arg1; arg2])
+ | [Cop(Clsl | Clsr | Casr as op, [arg1; Cconst_int n]); arg2]
+ when n > 0 && n < 32 ->
+ (Ispecific(Ishiftarith(arithrevop, select_shiftop op, n)), [arg2; arg1])
+ | args ->
+ begin match super#select_operation op args with
+ (* Recognize multiply high and add *)
+ (Iintop Iadd, [Cop(Cmulhi, args); arg3])
+ | (Iintop Iadd, [arg3; Cop(Cmulhi, args)]) as op_args
+ when !arch >= ARMv6 ->
+ begin match self#select_operation Cmulhi args with
+ (Iintop Imulh, [arg1; arg2]) ->
+ (Ispecific Imulhadd, [arg1; arg2; arg3])
+ | _ -> op_args
+ end
+ (* Recognize multiply and add *)
+ | (Iintop Iadd, [Cop(Cmuli, args); arg3])
+ | (Iintop Iadd, [arg3; Cop(Cmuli, args)]) as op_args ->
+ begin match self#select_operation Cmuli args with
+ (Iintop Imul, [arg1; arg2]) ->
+ (Ispecific Imuladd, [arg1; arg2; arg3])
+ | _ -> op_args
+ end
+ (* Recognize multiply and subtract *)
+ | (Iintop Isub, [arg3; Cop(Cmuli, args)]) as op_args
+ when !arch > ARMv6 ->
+ begin match self#select_operation Cmuli args with
+ (Iintop Imul, [arg1; arg2]) ->
+ (Ispecific Imulsub, [arg1; arg2; arg3])
+ | _ -> op_args
+ end
+ | op_args -> op_args
+ end
+
+method! select_operation op args =
+ match (op, args) with
+ (* Recognize special shift arithmetic *)
+ ((Caddv | Cadda | Caddi), [arg; Cconst_int n])
+ when n < 0 && self#is_immediate (-n) ->
+ (Iintop_imm(Isub, -n), [arg])
+ | ((Caddv | Cadda | Caddi as op), args) ->
+ self#select_shift_arith op Ishiftadd Ishiftadd args
+ | (Csubi, [arg; Cconst_int n])
+ when n < 0 && self#is_immediate (-n) ->
+ (Iintop_imm(Iadd, -n), [arg])
+ | (Csubi, [Cconst_int n; arg])
+ when self#is_immediate n ->
+ (Ispecific(Irevsubimm n), [arg])
+ | (Csubi as op, args) ->
+ self#select_shift_arith op Ishiftsub Ishiftsubrev args
+ | (Cand as op, args) ->
+ self#select_shift_arith op Ishiftand Ishiftand args
+ | (Cor as op, args) ->
+ self#select_shift_arith op Ishiftor Ishiftor args
+ | (Cxor as op, args) ->
+ self#select_shift_arith op Ishiftxor Ishiftxor args
+ | (Ccheckbound _, [Cop(Clsl | Clsr | Casr as op, [arg1; Cconst_int n]); arg2])
+ when n > 0 && n < 32 ->
+ (Ispecific(Ishiftcheckbound(select_shiftop op, n)), [arg1; arg2])
+ (* ARM does not support immediate operands for multiplication *)
+ | (Cmuli, args) ->
+ (Iintop Imul, args)
+ | (Cmulhi, args) ->
+ (Iintop Imulh, args)
+ (* Turn integer division/modulus into runtime ABI calls *)
+ | (Cdivi, args) ->
+ (Iextcall("__aeabi_idiv", false), args)
+ | (Cmodi, args) ->
+ (* See above for fix up of return register *)
+ (Iextcall("__aeabi_idivmod", false), args)
+ (* Recognize 16-bit bswap instruction (ARMv6T2 because we need movt) *)
+ | (Cextcall("caml_bswap16_direct", _, _, _), args) when !arch >= ARMv6T2 ->
+ (Ispecific(Ibswap 16), args)
+ (* Recognize 32-bit bswap instructions (ARMv6 and above) *)
+ | (Cextcall("caml_int32_direct_bswap", _, _, _), args) when !arch >= ARMv6 ->
+ (Ispecific(Ibswap 32), args)
+ (* Turn floating-point operations into runtime ABI calls for softfp *)
+ | (op, args) when !fpu = Soft -> self#select_operation_softfp op args
+ (* Select operations for VFPv{2,3} *)
+ | (op, args) -> self#select_operation_vfpv3 op args
+
+method private select_operation_softfp op args =
+ match (op, args) with
+ (* Turn floating-point operations into runtime ABI calls *)
+ | (Caddf, args) -> (Iextcall("__aeabi_dadd", false), args)
+ | (Csubf, args) -> (Iextcall("__aeabi_dsub", false), args)
+ | (Cmulf, args) -> (Iextcall("__aeabi_dmul", false), args)
+ | (Cdivf, args) -> (Iextcall("__aeabi_ddiv", false), args)
+ | (Cfloatofint, args) -> (Iextcall("__aeabi_i2d", false), args)
+ | (Cintoffloat, args) -> (Iextcall("__aeabi_d2iz", false), args)
+ | (Ccmpf comp, args) ->
+ let func = (match comp with
+ Cne (* there's no __aeabi_dcmpne *)
+ | Ceq -> "__aeabi_dcmpeq"
+ | Clt -> "__aeabi_dcmplt"
+ | Cle -> "__aeabi_dcmple"
+ | Cgt -> "__aeabi_dcmpgt"
+ | Cge -> "__aeabi_dcmpge") in
+ let comp = (match comp with
+ Cne -> Ceq (* eq 0 => false *)
+ | _ -> Cne (* ne 0 => true *)) in
+ (Iintop_imm(Icomp(Iunsigned comp), 0),
+ [Cop(Cextcall(func, typ_int, false, Debuginfo.none), args)])
+ (* Add coercions around loads and stores of 32-bit floats *)
+ | (Cload Single, args) ->
+ (Iextcall("__aeabi_f2d", false), [Cop(Cload Word_int, args)])
+ | (Cstore Single, [arg1; arg2]) ->
+ let arg2' =
+ Cop(Cextcall("__aeabi_d2f", typ_int, false, Debuginfo.none),
+ [arg2]) in
+ self#select_operation (Cstore Word_int) [arg1; arg2']
+ (* Other operations are regular *)
+ | (op, args) -> super#select_operation op args
+
+method private select_operation_vfpv3 op args =
+ match (op, args) with
+ (* Recognize floating-point negate and multiply *)
+ (Cnegf, [Cop(Cmulf, args)]) ->
+ (Ispecific Inegmulf, args)
+ (* Recognize floating-point multiply and add *)
+ | (Caddf, [arg; Cop(Cmulf, args)])
+ | (Caddf, [Cop(Cmulf, args); arg]) ->
+ (Ispecific Imuladdf, arg :: args)
+ (* Recognize floating-point negate, multiply and subtract *)
+ | (Csubf, [Cop(Cnegf, [arg]); Cop(Cmulf, args)])
+ | (Csubf, [Cop(Cnegf, [Cop(Cmulf, args)]); arg]) ->
+ (Ispecific Inegmulsubf, arg :: args)
+ (* Recognize floating-point negate, multiply and add *)
+ | (Csubf, [arg; Cop(Cmulf, args)]) ->
+ (Ispecific Inegmuladdf, arg :: args)
+ (* Recognize multiply and subtract *)
+ | (Csubf, [Cop(Cmulf, args); arg]) ->
+ (Ispecific Imulsubf, arg :: args)
+ (* Recognize floating-point square root *)
+ | (Cextcall("sqrt", _, false, _), args) ->
+ (Ispecific Isqrtf, args)
+ (* Other operations are regular *)
+ | (op, args) -> super#select_operation op args
+
+method! select_condition = function
+ (* Turn floating-point comparisons into runtime ABI calls *)
+ Cop(Ccmpf _ as op, args) when !fpu = Soft ->
+ begin match self#select_operation_softfp op args with
+ (Iintop_imm(Icomp(Iunsigned Ceq), 0), [arg]) -> (Ifalsetest, arg)
+ | (Iintop_imm(Icomp(Iunsigned Cne), 0), [arg]) -> (Itruetest, arg)
+ | _ -> assert false
+ end
+ | expr ->
+ super#select_condition expr
+
+(* Deal with some register constraints *)
+
+method! insert_op_debug op dbg rs rd =
+ try
+ let (rsrc, rdst) = pseudoregs_for_operation op rs rd in
+ self#insert_moves rs rsrc;
+ self#insert_debug (Iop op) dbg rsrc rdst;
+ self#insert_moves rdst rd;
+ rd
+ with Use_default ->
+ super#insert_op_debug op dbg rs rd
+
+end
+
+let fundecl f = (new selector)#emit_fundecl f
diff --git a/asmcomp/arm64/CSE.ml b/asmcomp/arm64/CSE.ml
new file mode 100644
index 0000000000..f9e03e487e
--- /dev/null
+++ b/asmcomp/arm64/CSE.ml
@@ -0,0 +1,37 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* CSE for ARM64 *)
+
+open Arch
+open Mach
+open CSEgen
+
+class cse = object (self)
+
+inherit cse_generic as super
+
+method! class_of_operation op =
+ match op with
+ | Ispecific(Ishiftcheckbound _) -> Op_checkbound
+ | Ispecific _ -> Op_pure
+ | _ -> super#class_of_operation op
+
+method! is_cheap_operation op =
+ match op with
+ | Iconst_int n | Iconst_blockheader n -> n <= 65535n && n >= 0n
+ | _ -> false
+
+end
+
+let fundecl f =
+ (new cse)#fundecl f
diff --git a/asmcomp/arm64/arch.ml b/asmcomp/arm64/arch.ml
new file mode 100644
index 0000000000..3e62da89ff
--- /dev/null
+++ b/asmcomp/arm64/arch.ml
@@ -0,0 +1,158 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let command_line_options = []
+
+(* Specific operations for the ARM processor, 64-bit mode *)
+
+open Format
+
+let command_line_options = []
+
+(* Addressing modes *)
+
+type addressing_mode =
+ | Iindexed of int (* reg + displ *)
+ | Ibased of string * int (* global var + displ *)
+
+(* We do not support the reg + shifted reg addressing mode, because
+ what we really need is reg + shifted reg + displ,
+ and this is decomposed in two instructions (reg + shifted reg -> tmp,
+ then addressing tmp + displ). *)
+
+(* Specific operations *)
+
+type specific_operation =
+ | Ifar_alloc of int
+ | Ifar_intop_checkbound
+ | Ifar_intop_imm_checkbound of int
+ | Ishiftarith of arith_operation * int
+ | Ishiftcheckbound of int
+ | Ifar_shiftcheckbound of int
+ | Imuladd (* multiply and add *)
+ | Imulsub (* multiply and subtract *)
+ | Inegmulf (* floating-point negate and multiply *)
+ | Imuladdf (* floating-point multiply and add *)
+ | Inegmuladdf (* floating-point negate, multiply and add *)
+ | Imulsubf (* floating-point multiply and subtract *)
+ | Inegmulsubf (* floating-point negate, multiply and subtract *)
+ | Isqrtf (* floating-point square root *)
+ | Ibswap of int (* endianess conversion *)
+
+and arith_operation =
+ Ishiftadd
+ | Ishiftsub
+
+(* Sizes, endianness *)
+
+let big_endian = false
+
+let size_addr = 8
+let size_int = 8
+let size_float = 8
+
+let allow_unaligned_access = false
+
+(* Behavior of division *)
+
+let division_crashes_on_overflow = false
+
+(* Operations on addressing modes *)
+
+let identity_addressing = Iindexed 0
+
+let offset_addressing addr delta =
+ match addr with
+ | Iindexed n -> Iindexed(n + delta)
+ | Ibased(s, n) -> Ibased(s, n + delta)
+
+let num_args_addressing = function
+ | Iindexed n -> 1
+ | Ibased(s, n) -> 0
+
+(* Printing operations and addressing modes *)
+
+let print_addressing printreg addr ppf arg =
+ match addr with
+ | Iindexed n ->
+ printreg ppf arg.(0);
+ if n <> 0 then fprintf ppf " + %i" n
+ | Ibased(s, 0) ->
+ fprintf ppf "\"%s\"" s
+ | Ibased(s, n) ->
+ fprintf ppf "\"%s\" + %i" s n
+
+let print_specific_operation printreg op ppf arg =
+ match op with
+ | Ifar_alloc n ->
+ fprintf ppf "(far) alloc %i" n
+ | Ifar_intop_checkbound ->
+ fprintf ppf "%a (far) check > %a" printreg arg.(0) printreg arg.(1)
+ | Ifar_intop_imm_checkbound n ->
+ fprintf ppf "%a (far) check > %i" printreg arg.(0) n
+ | Ishiftarith(op, shift) ->
+ let op_name = function
+ | Ishiftadd -> "+"
+ | Ishiftsub -> "-" in
+ let shift_mark =
+ if shift >= 0
+ then sprintf "<< %i" shift
+ else sprintf ">> %i" (-shift) in
+ fprintf ppf "%a %s %a %s"
+ printreg arg.(0) (op_name op) printreg arg.(1) shift_mark
+ | Ishiftcheckbound n ->
+ fprintf ppf "check %a >> %i > %a" printreg arg.(0) n printreg arg.(1)
+ | Ifar_shiftcheckbound n ->
+ fprintf ppf
+ "(far) check %a >> %i > %a" printreg arg.(0) n printreg arg.(1)
+ | Imuladd ->
+ fprintf ppf "(%a * %a) + %a"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Imulsub ->
+ fprintf ppf "-(%a * %a) + %a"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Inegmulf ->
+ fprintf ppf "-f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ | Imuladdf ->
+ fprintf ppf "%a +f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Inegmuladdf ->
+ fprintf ppf "(-f %a) -f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Imulsubf ->
+ fprintf ppf "%a -f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Inegmulsubf ->
+ fprintf ppf "(-f %a) +f (%a *f %a)"
+ printreg arg.(0)
+ printreg arg.(1)
+ printreg arg.(2)
+ | Isqrtf ->
+ fprintf ppf "sqrtf %a"
+ printreg arg.(0)
+ | Ibswap n ->
+ fprintf ppf "bswap%i %a" n
+ printreg arg.(0)
diff --git a/asmcomp/arm64/emit.mlp b/asmcomp/arm64/emit.mlp
new file mode 100644
index 0000000000..bc0513940b
--- /dev/null
+++ b/asmcomp/arm64/emit.mlp
@@ -0,0 +1,988 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Emission of ARM assembly code, 64-bit mode *)
+
+open Misc
+open Cmm
+open Arch
+open Proc
+open Reg
+open Mach
+open Linearize
+open Emitaux
+
+(* Tradeoff between code size and code speed *)
+
+let fastcode_flag = ref true
+
+(* Names for special regs *)
+
+let reg_trap_ptr = phys_reg 23
+let reg_alloc_ptr = phys_reg 24
+let reg_alloc_limit = phys_reg 25
+let reg_tmp1 = phys_reg 26
+let reg_tmp2 = phys_reg 27
+let reg_x15 = phys_reg 15
+
+(* Output a label *)
+
+let emit_label lbl =
+ emit_string ".L"; emit_int lbl
+
+let emit_data_label lbl =
+ emit_string ".Ld"; emit_int lbl
+
+(* Symbols *)
+
+let emit_symbol s =
+ Emitaux.emit_symbol '$' s
+
+(* Output a pseudo-register *)
+
+let emit_reg = function
+ {loc = Reg r} -> emit_string (register_name r)
+ | _ -> fatal_error "Emit.emit_reg"
+
+(* Likewise, but with the 32-bit name of the register *)
+
+let int_reg_name_w =
+ [| "w0"; "w1"; "w2"; "w3"; "w4"; "w5"; "w6"; "w7";
+ "w8"; "w9"; "w10"; "w11"; "w12"; "w13"; "w14"; "w15";
+ "w19"; "w20"; "w21"; "w22"; "w23"; "w24"; "w25";
+ "w26"; "w27"; "w28"; "w16"; "w17" |]
+
+let emit_wreg = function
+ {loc = Reg r} -> emit_string int_reg_name_w.(r)
+ | _ -> fatal_error "Emit.emit_wreg"
+
+(* Layout of the stack frame *)
+
+let stack_offset = ref 0
+
+let frame_size () =
+ let sz =
+ !stack_offset +
+ 8 * num_stack_slots.(0) +
+ 8 * num_stack_slots.(1) +
+ (if !contains_calls then 8 else 0)
+ in Misc.align sz 16
+
+let slot_offset loc cl =
+ match loc with
+ Incoming n ->
+ assert (n >= 0);
+ frame_size() + n
+ | Local n ->
+ !stack_offset +
+ (if cl = 0
+ then n * 8
+ else num_stack_slots.(0) * 8 + n * 8)
+ | Outgoing n ->
+ assert (n >= 0);
+ n
+
+(* Output a stack reference *)
+
+let emit_stack r =
+ match r.loc with
+ | Stack s ->
+ let ofs = slot_offset s (register_class r) in `[sp, #{emit_int ofs}]`
+ | _ -> fatal_error "Emit.emit_stack"
+
+(* Output an addressing mode *)
+
+let emit_symbol_offset s ofs =
+ emit_symbol s;
+ if ofs > 0 then `+{emit_int ofs}`
+ else if ofs < 0 then `-{emit_int (-ofs)}`
+ else ()
+
+let emit_addressing addr r =
+ match addr with
+ | Iindexed ofs ->
+ `[{emit_reg r}, #{emit_int ofs}]`
+ | Ibased(s, ofs) ->
+ `[{emit_reg r}, #:lo12:{emit_symbol_offset s ofs}]`
+
+(* Record live pointers at call points *)
+
+let record_frame_label live dbg =
+ let lbl = new_label() in
+ let live_offset = ref [] in
+ Reg.Set.iter
+ (function
+ | {typ = Val; loc = Reg r} ->
+ live_offset := ((r lsl 1) + 1) :: !live_offset
+ | {typ = Val; loc = Stack s} as reg ->
+ live_offset := slot_offset s (register_class reg) :: !live_offset
+ | {typ = Addr} as r ->
+ Misc.fatal_error ("bad GC root " ^ Reg.name r)
+ | _ -> ())
+ live;
+ frame_descriptors :=
+ { fd_lbl = lbl;
+ fd_frame_size = frame_size();
+ fd_live_offset = !live_offset;
+ fd_debuginfo = dbg } :: !frame_descriptors;
+ lbl
+
+let record_frame live dbg =
+ let lbl = record_frame_label live dbg in `{emit_label lbl}:`
+
+(* Record calls to the GC -- we've moved them out of the way *)
+
+type gc_call =
+ { gc_lbl: label; (* Entry label *)
+ gc_return_lbl: label; (* Where to branch after GC *)
+ gc_frame_lbl: label } (* Label of frame descriptor *)
+
+let call_gc_sites = ref ([] : gc_call list)
+
+let emit_call_gc gc =
+ `{emit_label gc.gc_lbl}: bl {emit_symbol "caml_call_gc"}\n`;
+ `{emit_label gc.gc_frame_lbl}: b {emit_label gc.gc_return_lbl}\n`
+
+(* Record calls to caml_ml_array_bound_error.
+ In debug mode, we maintain one call to caml_ml_array_bound_error
+ per bound check site. Otherwise, we can share a single call. *)
+
+type bound_error_call =
+ { bd_lbl: label; (* Entry label *)
+ bd_frame_lbl: label } (* Label of frame descriptor *)
+
+let bound_error_sites = ref ([] : bound_error_call list)
+
+let bound_error_label dbg =
+ if !Clflags.debug || !bound_error_sites = [] then begin
+ let lbl_bound_error = new_label() in
+ let lbl_frame = record_frame_label Reg.Set.empty dbg in
+ bound_error_sites :=
+ { bd_lbl = lbl_bound_error;
+ bd_frame_lbl = lbl_frame } :: !bound_error_sites;
+ lbl_bound_error
+ end else begin
+ let bd = List.hd !bound_error_sites in bd.bd_lbl
+ end
+
+let emit_call_bound_error bd =
+ `{emit_label bd.bd_lbl}: bl {emit_symbol "caml_ml_array_bound_error"}\n`;
+ `{emit_label bd.bd_frame_lbl}:\n`
+
+(* Names of various instructions *)
+
+let name_for_comparison = function
+ | Isigned Ceq -> "eq" | Isigned Cne -> "ne" | Isigned Cle -> "le"
+ | Isigned Cge -> "ge" | Isigned Clt -> "lt" | Isigned Cgt -> "gt"
+ | Iunsigned Ceq -> "eq" | Iunsigned Cne -> "ne" | Iunsigned Cle -> "ls"
+ | Iunsigned Cge -> "cs" | Iunsigned Clt -> "cc" | Iunsigned Cgt -> "hi"
+
+let name_for_int_operation = function
+ | Iadd -> "add"
+ | Isub -> "sub"
+ | Imul -> "mul"
+ | Idiv -> "sdiv"
+ | Iand -> "and"
+ | Ior -> "orr"
+ | Ixor -> "eor"
+ | Ilsl -> "lsl"
+ | Ilsr -> "lsr"
+ | Iasr -> "asr"
+ | _ -> assert false
+
+(* Load an integer constant into a register *)
+
+let emit_intconst dst n =
+ let rec emit_pos first shift =
+ if shift < 0 then begin
+ if first then ` mov {emit_reg dst}, xzr\n`
+ end else begin
+ let s = Nativeint.(logand (shift_right_logical n shift) 0xFFFFn) in
+ if s = 0n then emit_pos first (shift - 16) else begin
+ if first then
+ ` movz {emit_reg dst}, #{emit_nativeint s}, lsl #{emit_int shift}\n`
+ else
+ ` movk {emit_reg dst}, #{emit_nativeint s}, lsl #{emit_int shift}\n`;
+ emit_pos false (shift - 16)
+ end
+ end
+ and emit_neg first shift =
+ if shift < 0 then begin
+ if first then ` movn {emit_reg dst}, #0\n`
+ end else begin
+ let s = Nativeint.(logand (shift_right_logical n shift) 0xFFFFn) in
+ if s = 0xFFFFn then emit_neg first (shift - 16) else begin
+ if first then
+ ` movn {emit_reg dst}, #{emit_nativeint (Nativeint.logxor s 0xFFFFn)}, lsl #{emit_int shift}\n`
+ else
+ ` movk {emit_reg dst}, #{emit_nativeint s}, lsl #{emit_int shift}\n`;
+ emit_neg false (shift - 16)
+ end
+ end
+ in
+ if n < 0n then emit_neg true 48 else emit_pos true 48
+
+let num_instructions_for_intconst n =
+ let num_instructions = ref 0 in
+ let rec count_pos first shift =
+ if shift < 0 then begin
+ if first then incr num_instructions
+ end else begin
+ let s = Nativeint.(logand (shift_right_logical n shift) 0xFFFFn) in
+ if s = 0n then count_pos first (shift - 16) else begin
+ incr num_instructions;
+ count_pos false (shift - 16)
+ end
+ end
+ and count_neg first shift =
+ if shift < 0 then begin
+ if first then incr num_instructions
+ end else begin
+ let s = Nativeint.(logand (shift_right_logical n shift) 0xFFFFn) in
+ if s = 0xFFFFn then count_neg first (shift - 16) else begin
+ incr num_instructions;
+ count_neg false (shift - 16)
+ end
+ end
+ in
+ if n < 0n then count_neg true 48 else count_pos true 48;
+ !num_instructions
+
+(* Recognize float constants appropriate for FMOV dst, #fpimm instruction:
+ "a normalized binary floating point encoding with 1 sign bit, 4
+ bits of fraction and a 3-bit exponent" *)
+
+let is_immediate_float bits =
+ let exp = (Int64.(to_int (shift_right_logical bits 52)) land 0x7FF) - 1023 in
+ let mant = Int64.logand bits 0xF_FFFF_FFFF_FFFFL in
+ exp >= -3 && exp <= 4 && Int64.logand mant 0xF_0000_0000_0000L = mant
+
+(* Adjust sp (up or down) by the given byte amount *)
+
+let emit_stack_adjustment n =
+ let instr = if n < 0 then "sub" else "add" in
+ let m = abs n in
+ assert (m < 0x1_000_000);
+ let ml = m land 0xFFF and mh = m land 0xFFF_000 in
+ if mh <> 0 then ` {emit_string instr} sp, sp, #{emit_int mh}\n`;
+ if ml <> 0 then ` {emit_string instr} sp, sp, #{emit_int ml}\n`;
+ if n <> 0 then cfi_adjust_cfa_offset (-n)
+
+(* Deallocate the stack frame and reload the return address
+ before a return or tail call *)
+
+let output_epilogue f =
+ let n = frame_size() in
+ if !contains_calls then
+ ` ldr x30, [sp, #{emit_int (n-8)}]\n`;
+ if n > 0 then
+ emit_stack_adjustment n;
+ f();
+ (* reset CFA back because function body may continue *)
+ if n > 0 then cfi_adjust_cfa_offset n
+
+(* Name of current function *)
+let function_name = ref ""
+(* Entry point for tail recursive calls *)
+let tailrec_entry_point = ref 0
+(* Pending floating-point literals *)
+let float_literals = ref ([] : (int64 * label) list)
+
+(* Label a floating-point literal *)
+let float_literal f =
+ try
+ List.assoc f !float_literals
+ with Not_found ->
+ let lbl = new_label() in
+ float_literals := (f, lbl) :: !float_literals;
+ lbl
+
+(* Emit all pending literals *)
+let emit_literals() =
+ if !float_literals <> [] then begin
+ ` .align 3\n`;
+ List.iter
+ (fun (f, lbl) ->
+ `{emit_label lbl}:`; emit_float64_directive ".quad" f)
+ !float_literals;
+ float_literals := []
+ end
+
+(* Emit code to load the address of a symbol *)
+
+let emit_load_symbol_addr dst s =
+ if (not !Clflags.dlcode) || Compilenv.symbol_in_current_unit s then begin
+ ` adrp {emit_reg dst}, {emit_symbol s}\n`;
+ ` add {emit_reg dst}, {emit_reg dst}, #:lo12:{emit_symbol s}\n`
+ end else begin
+ ` adrp {emit_reg dst}, :got:{emit_symbol s}\n`;
+ ` ldr {emit_reg dst}, [{emit_reg dst}, #:got_lo12:{emit_symbol s}]\n`
+ end
+
+(* The following functions are used for calculating the sizes of the
+ call GC and bounds check points emitted out-of-line from the function
+ body. See branch_relaxation.mli. *)
+
+let num_call_gc_and_check_bound_points instr =
+ let rec loop instr ((call_gc, check_bound) as totals) =
+ match instr.desc with
+ | Lend -> totals
+ | Lop (Ialloc _) when !fastcode_flag ->
+ loop instr.next (call_gc + 1, check_bound)
+ | Lop (Iintop Icheckbound)
+ | Lop (Iintop_imm (Icheckbound, _))
+ | Lop (Ispecific (Ishiftcheckbound _)) ->
+ let check_bound =
+ (* When not in debug mode, there is at most one check-bound point. *)
+ if not !Clflags.debug then 1
+ else check_bound + 1
+ in
+ loop instr.next (call_gc, check_bound)
+ (* The following four should never be seen, since this function is run
+ before branch relaxation. *)
+ | Lop (Ispecific (Ifar_alloc _))
+ | Lop (Ispecific Ifar_intop_checkbound)
+ | Lop (Ispecific (Ifar_intop_imm_checkbound _))
+ | Lop (Ispecific (Ifar_shiftcheckbound _)) -> assert false
+ | _ -> loop instr.next totals
+ in
+ loop instr (0, 0)
+
+let max_out_of_line_code_offset instr ~num_call_gc ~num_check_bound =
+ if num_call_gc < 1 && num_check_bound < 1 then 0
+ else begin
+ let size_of_call_gc = 2 in
+ let size_of_check_bound = 1 in
+ let size_of_last_thing =
+ (* Call-GC points come before check-bound points. *)
+ if num_check_bound >= 1 then size_of_check_bound else size_of_call_gc
+ in
+ let total_size =
+ size_of_call_gc*num_call_gc + size_of_check_bound*num_check_bound
+ in
+ let max_offset = total_size - size_of_last_thing in
+ assert (max_offset >= 0);
+ max_offset
+ end
+
+module BR = Branch_relaxation.Make (struct
+ (* CR-someday mshinwell: B and BL have +/- 128Mb ranges; for the moment we
+ assume we will never exceed this. It would seem to be most likely to
+ occur for branches between functions; in this case, the linker should be
+ able to insert veneers anyway. (See section 4.6.7 of the document
+ "ELF for the ARM 64-bit architecture (AArch64)".) *)
+
+ type distance = int
+
+ module Cond_branch = struct
+ type t = TB | CB | Bcc
+
+ let all = [TB; CB; Bcc]
+
+ (* AArch64 instructions are 32 bits wide, so [distance] in this module
+ means units of 32-bit words. *)
+ let max_displacement = function
+ | TB -> 32 * 1024 / 4 (* +/- 32Kb *)
+ | CB | Bcc -> 1 * 1024 * 1024 / 4 (* +/- 1Mb *)
+
+ let classify_instr = function
+ | Lop (Ialloc _)
+ | Lop (Iintop Icheckbound)
+ | Lop (Iintop_imm (Icheckbound, _))
+ | Lop (Ispecific (Ishiftcheckbound _)) -> Some Bcc
+ (* The various "far" variants in [specific_operation] don't need to
+ return [Some] here, since their code sequences never contain any
+ conditional branches that might need relaxing. *)
+ | Lcondbranch (Itruetest, _)
+ | Lcondbranch (Ifalsetest, _) -> Some CB
+ | Lcondbranch (Iinttest _, _)
+ | Lcondbranch (Iinttest_imm _, _)
+ | Lcondbranch (Ifloattest _, _) -> Some Bcc
+ | Lcondbranch (Ioddtest, _)
+ | Lcondbranch (Ieventest, _) -> Some TB
+ | Lcondbranch3 _ -> Some Bcc
+ | _ -> None
+ end
+
+ let offset_pc_at_branch = 0
+
+ let epilogue_size () =
+ if !contains_calls then 3 else 2
+
+ let instr_size = function
+ | Lend -> 0
+ | Lop (Imove | Ispill | Ireload) -> 1
+ | Lop (Iconst_int n | Iconst_blockheader n) ->
+ num_instructions_for_intconst n
+ | Lop (Iconst_float _) -> 2
+ | Lop (Iconst_symbol _) -> 2
+ | Lop (Icall_ind) -> 1
+ | Lop (Icall_imm _) -> 1
+ | Lop (Itailcall_ind) -> epilogue_size ()
+ | Lop (Itailcall_imm s) ->
+ if s = !function_name then 1 else epilogue_size ()
+ | Lop (Iextcall (_, false)) -> 1
+ | Lop (Iextcall (_, true)) -> 3
+ | Lop (Istackoffset _) -> 2
+ | Lop (Iload (size, addr)) | Lop (Istore (size, addr, _)) ->
+ let based = match addr with Iindexed _ -> 0 | Ibased _ -> 1 in
+ based + begin match size with Single -> 2 | _ -> 1 end
+ | Lop (Ialloc _) when !fastcode_flag -> 4
+ | Lop (Ispecific (Ifar_alloc _)) when !fastcode_flag -> 5
+ | Lop (Ialloc num_words) | Lop (Ispecific (Ifar_alloc num_words)) ->
+ begin match num_words with
+ | 16 | 24 | 32 -> 1
+ | _ -> 1 + num_instructions_for_intconst (Nativeint.of_int num_words)
+ end
+ | Lop (Iintop (Icomp _)) -> 2
+ | Lop (Iintop_imm (Icomp _, _)) -> 2
+ | Lop (Iintop Icheckbound) -> 2
+ | Lop (Ispecific Ifar_intop_checkbound) -> 3
+ | Lop (Iintop_imm (Icheckbound, _)) -> 2
+ | Lop (Ispecific (Ifar_intop_imm_checkbound _)) -> 3
+ | Lop (Ispecific (Ishiftcheckbound _)) -> 2
+ | Lop (Ispecific (Ifar_shiftcheckbound _)) -> 3
+ | Lop (Iintop Imod) -> 2
+ | Lop (Iintop Imulh) -> 1
+ | Lop (Iintop _) -> 1
+ | Lop (Iintop_imm _) -> 1
+ | Lop (Ifloatofint | Iintoffloat | Iabsf | Inegf | Ispecific Isqrtf) -> 1
+ | Lop (Iaddf | Isubf | Imulf | Idivf | Ispecific Inegmulf) -> 1
+ | Lop (Ispecific (Imuladdf | Inegmuladdf | Imulsubf | Inegmulsubf)) -> 1
+ | Lop (Ispecific (Ishiftarith _)) -> 1
+ | Lop (Ispecific (Imuladd | Imulsub)) -> 1
+ | Lop (Ispecific (Ibswap 16)) -> 2
+ | Lop (Ispecific (Ibswap _)) -> 1
+ | Lreloadretaddr -> 0
+ | Lreturn -> epilogue_size ()
+ | Llabel _ -> 0
+ | Lbranch _ -> 1
+ | Lcondbranch (tst, _) ->
+ begin match tst with
+ | Itruetest -> 1
+ | Ifalsetest -> 1
+ | Iinttest _ -> 2
+ | Iinttest_imm _ -> 2
+ | Ifloattest _ -> 2
+ | Ioddtest -> 1
+ | Ieventest -> 1
+ end
+ | Lcondbranch3 (lbl0, lbl1, lbl2) ->
+ 1 + begin match lbl0 with None -> 0 | Some _ -> 1 end
+ + begin match lbl1 with None -> 0 | Some _ -> 1 end
+ + begin match lbl2 with None -> 0 | Some _ -> 1 end
+ | Lswitch jumptbl -> 3 + Array.length jumptbl
+ | Lsetuptrap _ -> 2
+ | Lpushtrap -> 3
+ | Lpoptrap -> 1
+ | Lraise k ->
+ begin match !Clflags.debug, k with
+ | true, (Lambda.Raise_regular | Lambda.Raise_reraise) -> 1
+ | false, _
+ | true, Lambda.Raise_notrace -> 4
+ end
+
+ let relax_allocation ~num_words =
+ Lop (Ispecific (Ifar_alloc num_words))
+
+ let relax_intop_checkbound () =
+ Lop (Ispecific Ifar_intop_checkbound)
+
+ let relax_intop_imm_checkbound ~bound =
+ Lop (Ispecific (Ifar_intop_imm_checkbound bound))
+
+ let relax_specific_op = function
+ | Ishiftcheckbound shift -> Lop (Ispecific (Ifar_shiftcheckbound shift))
+ | _ -> assert false
+end)
+
+(* Output the assembly code for allocation. *)
+
+let assembly_code_for_allocation i ~n ~far =
+ let lbl_frame = record_frame_label i.live i.dbg in
+ if !fastcode_flag then begin
+ let lbl_redo = new_label() in
+ let lbl_call_gc = new_label() in
+ `{emit_label lbl_redo}:`;
+ ` sub {emit_reg reg_alloc_ptr}, {emit_reg reg_alloc_ptr}, #{emit_int n}\n`;
+ ` cmp {emit_reg reg_alloc_ptr}, {emit_reg reg_alloc_limit}\n`;
+ ` add {emit_reg i.res.(0)}, {emit_reg reg_alloc_ptr}, #8\n`;
+ if not far then begin
+ ` b.lo {emit_label lbl_call_gc}\n`
+ end else begin
+ let lbl = new_label () in
+ ` b.cs {emit_label lbl}\n`;
+ ` b {emit_label lbl_call_gc}\n`;
+ `{emit_label lbl}:\n`
+ end;
+ call_gc_sites :=
+ { gc_lbl = lbl_call_gc;
+ gc_return_lbl = lbl_redo;
+ gc_frame_lbl = lbl_frame } :: !call_gc_sites
+ end else begin
+ begin match n with
+ | 16 -> ` bl {emit_symbol "caml_alloc1"}\n`
+ | 24 -> ` bl {emit_symbol "caml_alloc2"}\n`
+ | 32 -> ` bl {emit_symbol "caml_alloc3"}\n`
+ | _ -> emit_intconst reg_x15 (Nativeint.of_int n);
+ ` bl {emit_symbol "caml_allocN"}\n`
+ end;
+ `{emit_label lbl_frame}: add {emit_reg i.res.(0)}, {emit_reg reg_alloc_ptr}, #8\n`
+ end
+
+(* Output the assembly code for an instruction *)
+
+let emit_instr i =
+ emit_debug_info i.dbg;
+ match i.desc with
+ | Lend -> ()
+ | Lop(Imove | Ispill | Ireload) ->
+ let src = i.arg.(0) and dst = i.res.(0) in
+ if src.loc <> dst.loc then begin
+ match (src, dst) with
+ | {loc = Reg _; typ = Float}, {loc = Reg _} ->
+ ` fmov {emit_reg dst}, {emit_reg src}\n`
+ | {loc = Reg _}, {loc = Reg _} ->
+ ` mov {emit_reg dst}, {emit_reg src}\n`
+ | {loc = Reg _}, {loc = Stack _} ->
+ ` str {emit_reg src}, {emit_stack dst}\n`
+ | {loc = Stack _}, {loc = Reg _} ->
+ ` ldr {emit_reg dst}, {emit_stack src}\n`
+ | _ ->
+ assert false
+ end
+ | Lop(Iconst_int n | Iconst_blockheader n) ->
+ emit_intconst i.res.(0) n
+ | Lop(Iconst_float f) ->
+ let b = Int64.bits_of_float f in
+ if b = 0L then
+ ` fmov {emit_reg i.res.(0)}, xzr\n`
+ else if is_immediate_float b then
+ ` fmov {emit_reg i.res.(0)}, #{emit_printf "0x%Lx" b}\n`
+ else begin
+ let lbl = float_literal b in
+ ` adrp {emit_reg reg_tmp1}, {emit_label lbl}\n`;
+ ` ldr {emit_reg i.res.(0)}, [{emit_reg reg_tmp1}, #:lo12:{emit_label lbl}]\n`
+ end
+ | Lop(Iconst_symbol s) ->
+ emit_load_symbol_addr i.res.(0) s
+ | Lop(Icall_ind) ->
+ ` blr {emit_reg i.arg.(0)}\n`;
+ `{record_frame i.live i.dbg}\n`
+ | Lop(Icall_imm s) ->
+ ` bl {emit_symbol s}\n`;
+ `{record_frame i.live i.dbg}\n`
+ | Lop(Itailcall_ind) ->
+ output_epilogue (fun () -> ` br {emit_reg i.arg.(0)}\n`)
+ | Lop(Itailcall_imm s) ->
+ if s = !function_name then
+ ` b {emit_label !tailrec_entry_point}\n`
+ else
+ output_epilogue (fun () -> ` b {emit_symbol s}\n`)
+ | Lop(Iextcall(s, false)) ->
+ ` bl {emit_symbol s}\n`
+ | Lop(Iextcall(s, true)) ->
+ emit_load_symbol_addr reg_x15 s;
+ ` bl {emit_symbol "caml_c_call"}\n`;
+ `{record_frame i.live i.dbg}\n`
+ | Lop(Istackoffset n) ->
+ assert (n mod 16 = 0);
+ emit_stack_adjustment (-n);
+ stack_offset := !stack_offset + n
+ | Lop(Iload(size, addr)) ->
+ let dst = i.res.(0) in
+ let base =
+ match addr with
+ | Iindexed ofs -> i.arg.(0)
+ | Ibased(s, ofs) ->
+ ` adrp {emit_reg reg_tmp1}, {emit_symbol_offset s ofs}\n`;
+ reg_tmp1 in
+ begin match size with
+ | Byte_unsigned ->
+ ` ldrb {emit_wreg dst}, {emit_addressing addr base}\n`
+ | Byte_signed ->
+ ` ldrsb {emit_reg dst}, {emit_addressing addr base}\n`
+ | Sixteen_unsigned ->
+ ` ldrh {emit_wreg dst}, {emit_addressing addr base}\n`
+ | Sixteen_signed ->
+ ` ldrsh {emit_reg dst}, {emit_addressing addr base}\n`
+ | Thirtytwo_unsigned ->
+ ` ldr {emit_wreg dst}, {emit_addressing addr base}\n`
+ | Thirtytwo_signed ->
+ ` ldrsw {emit_reg dst}, {emit_addressing addr base}\n`
+ | Single ->
+ ` ldr s7, {emit_addressing addr base}\n`;
+ ` fcvt {emit_reg dst}, s7\n`
+ | Word_int | Word_val | Double | Double_u ->
+ ` ldr {emit_reg dst}, {emit_addressing addr base}\n`
+ end
+ | Lop(Istore(size, addr, _)) ->
+ let src = i.arg.(0) in
+ let base =
+ match addr with
+ | Iindexed ofs -> i.arg.(1)
+ | Ibased(s, ofs) ->
+ ` adrp {emit_reg reg_tmp1}, {emit_symbol_offset s ofs}\n`;
+ reg_tmp1 in
+ begin match size with
+ | Byte_unsigned | Byte_signed ->
+ ` strb {emit_wreg src}, {emit_addressing addr base}\n`
+ | Sixteen_unsigned | Sixteen_signed ->
+ ` strh {emit_wreg src}, {emit_addressing addr base}\n`
+ | Thirtytwo_unsigned | Thirtytwo_signed ->
+ ` str {emit_wreg src}, {emit_addressing addr base}\n`
+ | Single ->
+ ` fcvt s7, {emit_reg src}\n`;
+ ` str s7, {emit_addressing addr base}\n`;
+ | Word_int | Word_val | Double | Double_u ->
+ ` str {emit_reg src}, {emit_addressing addr base}\n`
+ end
+ | Lop(Ialloc n) ->
+ assembly_code_for_allocation i ~n ~far:false
+ | Lop(Ispecific (Ifar_alloc n)) ->
+ assembly_code_for_allocation i ~n ~far:true
+ | Lop(Iintop(Icomp cmp)) ->
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` cset {emit_reg i.res.(0)}, {emit_string (name_for_comparison cmp)}\n`
+ | Lop(Iintop_imm(Icomp cmp, n)) ->
+ ` cmp {emit_reg i.arg.(0)}, #{emit_int n}\n`;
+ ` cset {emit_reg i.res.(0)}, {emit_string (name_for_comparison cmp)}\n`
+ | Lop(Iintop Icheckbound) ->
+ let lbl = bound_error_label i.dbg in
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` b.ls {emit_label lbl}\n`
+ | Lop(Ispecific Ifar_intop_checkbound) ->
+ let lbl = bound_error_label i.dbg in
+ let lbl2 = new_label () in
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` b.hi {emit_label lbl2}\n`;
+ ` b {emit_label lbl}\n`;
+ `{emit_label lbl2}:\n`;
+ | Lop(Iintop_imm(Icheckbound, n)) ->
+ let lbl = bound_error_label i.dbg in
+ ` cmp {emit_reg i.arg.(0)}, #{emit_int n}\n`;
+ ` b.ls {emit_label lbl}\n`
+ | Lop(Ispecific(Ifar_intop_imm_checkbound bound)) ->
+ let lbl = bound_error_label i.dbg in
+ let lbl2 = new_label () in
+ ` cmp {emit_reg i.arg.(0)}, #{emit_int bound}\n`;
+ ` b.hi {emit_label lbl2}\n`;
+ ` b {emit_label lbl}\n`;
+ `{emit_label lbl2}:\n`;
+ | Lop(Ispecific(Ishiftcheckbound shift)) ->
+ let lbl = bound_error_label i.dbg in
+ ` cmp {emit_reg i.arg.(1)}, {emit_reg i.arg.(0)}, lsr #{emit_int shift}\n`;
+ ` b.cs {emit_label lbl}\n`
+ | Lop(Ispecific(Ifar_shiftcheckbound shift)) ->
+ let lbl = bound_error_label i.dbg in
+ let lbl2 = new_label () in
+ ` cmp {emit_reg i.arg.(1)}, {emit_reg i.arg.(0)}, lsr #{emit_int shift}\n`;
+ ` b.lo {emit_label lbl2}\n`;
+ ` b {emit_label lbl}\n`;
+ `{emit_label lbl2}:\n`;
+ | Lop(Iintop Imod) ->
+ ` sdiv {emit_reg reg_tmp1}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` msub {emit_reg i.res.(0)}, {emit_reg reg_tmp1}, {emit_reg i.arg.(1)}, {emit_reg i.arg.(0)}\n`
+ | Lop(Iintop Imulh) ->
+ ` smulh {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`
+ | Lop(Iintop op) ->
+ let instr = name_for_int_operation op in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`
+ | Lop(Iintop_imm(op, n)) ->
+ let instr = name_for_int_operation op in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, #{emit_int n}\n`
+ | Lop(Ifloatofint | Iintoffloat | Iabsf | Inegf | Ispecific Isqrtf as op) ->
+ let instr = (match op with
+ | Ifloatofint -> "scvtf"
+ | Iintoffloat -> "fcvtzs"
+ | Iabsf -> "fabs"
+ | Inegf -> "fneg"
+ | Ispecific Isqrtf -> "fsqrt"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}\n`
+ | Lop(Iaddf | Isubf | Imulf | Idivf | Ispecific Inegmulf as op) ->
+ let instr = (match op with
+ | Iaddf -> "fadd"
+ | Isubf -> "fsub"
+ | Imulf -> "fmul"
+ | Idivf -> "fdiv"
+ | Ispecific Inegmulf -> "fnmul"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`
+ | Lop(Ispecific(Imuladdf | Inegmuladdf | Imulsubf | Inegmulsubf as op)) ->
+ let instr = (match op with
+ | Imuladdf -> "fmadd"
+ | Inegmuladdf -> "fnmadd"
+ | Imulsubf -> "fmsub"
+ | Inegmulsubf -> "fnmsub"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.arg.(2)}, {emit_reg i.arg.(0)}\n`
+ | Lop(Ispecific(Ishiftarith(op, shift))) ->
+ let instr = (match op with
+ Ishiftadd -> "add"
+ | Ishiftsub -> "sub") in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}`;
+ if shift >= 0
+ then `, lsl #{emit_int shift}\n`
+ else `, asr #{emit_int (-shift)}\n`
+ | Lop(Ispecific(Imuladd | Imulsub as op)) ->
+ let instr = (match op with
+ Imuladd -> "madd"
+ | Imulsub -> "msub"
+ | _ -> assert false) in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.arg.(2)}\n`
+ | Lop(Ispecific(Ibswap size)) ->
+ begin match size with
+ | 16 ->
+ ` rev16 {emit_wreg i.res.(0)}, {emit_wreg i.arg.(0)}\n`;
+ ` ubfm {emit_reg i.res.(0)}, {emit_reg i.res.(0)}, #0, #15\n`
+ | 32 ->
+ ` rev {emit_wreg i.res.(0)}, {emit_wreg i.arg.(0)}\n`
+ | 64 ->
+ ` rev {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}\n`
+ | _ ->
+ assert false
+ end
+ | Lreloadretaddr ->
+ ()
+ | Lreturn ->
+ output_epilogue (fun () -> ` ret\n`)
+ | Llabel lbl ->
+ `{emit_label lbl}:\n`
+ | Lbranch lbl ->
+ ` b {emit_label lbl}\n`
+ | Lcondbranch(tst, lbl) ->
+ begin match tst with
+ | Itruetest ->
+ ` cbnz {emit_reg i.arg.(0)}, {emit_label lbl}\n`
+ | Ifalsetest ->
+ ` cbz {emit_reg i.arg.(0)}, {emit_label lbl}\n`
+ | Iinttest cmp ->
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ let comp = name_for_comparison cmp in
+ ` b.{emit_string comp} {emit_label lbl}\n`
+ | Iinttest_imm(cmp, n) ->
+ ` cmp {emit_reg i.arg.(0)}, #{emit_int n}\n`;
+ let comp = name_for_comparison cmp in
+ ` b.{emit_string comp} {emit_label lbl}\n`
+ | Ifloattest(cmp, neg) ->
+ let comp = (match (cmp, neg) with
+ | (Ceq, false) | (Cne, true) -> "eq"
+ | (Cne, false) | (Ceq, true) -> "ne"
+ | (Clt, false) -> "cc"
+ | (Clt, true) -> "cs"
+ | (Cle, false) -> "ls"
+ | (Cle, true) -> "hi"
+ | (Cgt, false) -> "gt"
+ | (Cgt, true) -> "le"
+ | (Cge, false) -> "ge"
+ | (Cge, true) -> "lt") in
+ ` fcmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` b.{emit_string comp} {emit_label lbl}\n`
+ | Ioddtest ->
+ ` tbnz {emit_reg i.arg.(0)}, #0, {emit_label lbl}\n`
+ | Ieventest ->
+ ` tbz {emit_reg i.arg.(0)}, #0, {emit_label lbl}\n`
+ end
+ | Lcondbranch3(lbl0, lbl1, lbl2) ->
+ ` cmp {emit_reg i.arg.(0)}, #1\n`;
+ begin match lbl0 with
+ None -> ()
+ | Some lbl -> ` b.lt {emit_label lbl}\n`
+ end;
+ begin match lbl1 with
+ None -> ()
+ | Some lbl -> ` b.eq {emit_label lbl}\n`
+ end;
+ begin match lbl2 with
+ None -> ()
+ | Some lbl -> ` b.gt {emit_label lbl}\n`
+ end
+ | Lswitch jumptbl ->
+ let lbltbl = new_label() in
+ ` adr {emit_reg reg_tmp1}, {emit_label lbltbl}\n`;
+ ` add {emit_reg reg_tmp1}, {emit_reg reg_tmp1}, {emit_reg i.arg.(0)}, lsl #2\n`;
+ ` br {emit_reg reg_tmp1}\n`;
+ `{emit_label lbltbl}:`;
+ for j = 0 to Array.length jumptbl - 1 do
+ ` b {emit_label jumptbl.(j)}\n`
+ done
+(* Alternative:
+ let lbltbl = new_label() in
+ ` adr {emit_reg reg_tmp1}, {emit_label lbltbl}\n`;
+ ` ldr {emit_wreg reg_tmp2}, [{emit_reg reg_tmp1}, {emit_reg i.arg.(0)}, lsl #2]\n`;
+ ` add {emit_reg reg_tmp1}, {emit_wreg reg_tmp2}, sxtb\n`;
+ ` br {emit_reg reg_tmp1}\n`;
+ `{emit_label lbltbl}:\n`;
+ for j = 0 to Array.length jumptbl - 1 do
+ ` .word {emit_label jumptbl.(j)} - {emit_label lbltbl}\n`
+ done
+*)
+ | Lsetuptrap lbl ->
+ let lblnext = new_label() in
+ ` adr {emit_reg reg_tmp1}, {emit_label lblnext}\n`;
+ ` b {emit_label lbl}\n`;
+ `{emit_label lblnext}:\n`
+ | Lpushtrap ->
+ stack_offset := !stack_offset + 16;
+ ` str {emit_reg reg_trap_ptr}, [sp, -16]!\n`;
+ ` str {emit_reg reg_tmp1}, [sp, #8]\n`;
+ cfi_adjust_cfa_offset 16;
+ ` mov {emit_reg reg_trap_ptr}, sp\n`
+ | Lpoptrap ->
+ ` ldr {emit_reg reg_trap_ptr}, [sp], 16\n`;
+ cfi_adjust_cfa_offset (-16);
+ stack_offset := !stack_offset - 16
+ | Lraise k ->
+ begin match !Clflags.debug, k with
+ | true, (Lambda.Raise_regular | Lambda.Raise_reraise) ->
+ ` bl {emit_symbol "caml_raise_exn"}\n`;
+ `{record_frame Reg.Set.empty i.dbg}\n`
+ | false, _
+ | true, Lambda.Raise_notrace ->
+ ` mov sp, {emit_reg reg_trap_ptr}\n`;
+ ` ldr {emit_reg reg_tmp1}, [sp, #8]\n`;
+ ` ldr {emit_reg reg_trap_ptr}, [sp], 16\n`;
+ ` br {emit_reg reg_tmp1}\n`
+ end
+
+(* Emission of an instruction sequence *)
+
+let rec emit_all i =
+ if i.desc = Lend then () else (emit_instr i; emit_all i.next)
+
+(* Emission of the profiling prelude *)
+
+let emit_profile() = () (* TODO *)
+(*
+ match Config.system with
+ "linux_eabi" | "linux_eabihf" ->
+ ` push \{lr}\n`;
+ ` {emit_call "__gnu_mcount_nc"}\n`
+ | _ -> ()
+*)
+
+(* Emission of a function declaration *)
+
+let fundecl fundecl =
+ function_name := fundecl.fun_name;
+ fastcode_flag := fundecl.fun_fast;
+ tailrec_entry_point := new_label();
+ float_literals := [];
+ stack_offset := 0;
+ call_gc_sites := [];
+ bound_error_sites := [];
+ ` .text\n`;
+ ` .align 3\n`;
+ ` .globl {emit_symbol fundecl.fun_name}\n`;
+ ` .type {emit_symbol fundecl.fun_name}, %function\n`;
+ `{emit_symbol fundecl.fun_name}:\n`;
+ emit_debug_info fundecl.fun_dbg;
+ cfi_startproc();
+ if !Clflags.gprofile then emit_profile();
+ let n = frame_size() in
+ if n > 0 then
+ emit_stack_adjustment (-n);
+ if !contains_calls then begin
+ cfi_offset ~reg:30 (* return address *) ~offset:(-8);
+ ` str x30, [sp, #{emit_int (n-8)}]\n`
+ end;
+ `{emit_label !tailrec_entry_point}:\n`;
+ let num_call_gc, num_check_bound =
+ num_call_gc_and_check_bound_points fundecl.fun_body
+ in
+ let max_out_of_line_code_offset =
+ max_out_of_line_code_offset fundecl.fun_body ~num_call_gc
+ ~num_check_bound
+ in
+ BR.relax fundecl.fun_body ~max_out_of_line_code_offset;
+ emit_all fundecl.fun_body;
+ List.iter emit_call_gc !call_gc_sites;
+ List.iter emit_call_bound_error !bound_error_sites;
+ assert (List.length !call_gc_sites = num_call_gc);
+ assert (List.length !bound_error_sites = num_check_bound);
+ cfi_endproc();
+ ` .type {emit_symbol fundecl.fun_name}, %function\n`;
+ ` .size {emit_symbol fundecl.fun_name}, .-{emit_symbol fundecl.fun_name}\n`;
+ emit_literals()
+
+(* Emission of data *)
+
+let emit_item = function
+ | Cglobal_symbol s -> ` .globl {emit_symbol s}\n`;
+ | Cdefine_symbol s -> `{emit_symbol s}:\n`
+ | Cdefine_label lbl -> `{emit_data_label lbl}:\n`
+ | Cint8 n -> ` .byte {emit_int n}\n`
+ | Cint16 n -> ` .short {emit_int n}\n`
+ | Cint32 n -> ` .long {emit_nativeint n}\n`
+ | Cint n -> ` .quad {emit_nativeint n}\n`
+ | Csingle f -> emit_float32_directive ".long" (Int32.bits_of_float f)
+ | Cdouble f -> emit_float64_directive ".quad" (Int64.bits_of_float f)
+ | Csymbol_address s -> ` .quad {emit_symbol s}\n`
+ | Clabel_address lbl -> ` .quad {emit_data_label lbl}\n`
+ | Cstring s -> emit_string_directive " .ascii " s
+ | Cskip n -> if n > 0 then ` .space {emit_int n}\n`
+ | Calign n -> ` .align {emit_int(Misc.log2 n)}\n`
+
+let data l =
+ ` .data\n`;
+ ` .align 3\n`;
+ List.iter emit_item l
+
+(* Beginning / end of an assembly file *)
+
+let begin_assembly() =
+ reset_debug_info();
+ let lbl_begin = Compilenv.make_symbol (Some "data_begin") in
+ ` .data\n`;
+ ` .globl {emit_symbol lbl_begin}\n`;
+ `{emit_symbol lbl_begin}:\n`;
+ let lbl_begin = Compilenv.make_symbol (Some "code_begin") in
+ ` .text\n`;
+ ` .globl {emit_symbol lbl_begin}\n`;
+ `{emit_symbol lbl_begin}:\n`
+
+let end_assembly () =
+ let lbl_end = Compilenv.make_symbol (Some "code_end") in
+ ` .text\n`;
+ ` .globl {emit_symbol lbl_end}\n`;
+ `{emit_symbol lbl_end}:\n`;
+ let lbl_end = Compilenv.make_symbol (Some "data_end") in
+ ` .data\n`;
+ ` .globl {emit_symbol lbl_end}\n`;
+ `{emit_symbol lbl_end}:\n`;
+ ` .long 0\n`;
+ let lbl = Compilenv.make_symbol (Some "frametable") in
+ ` .globl {emit_symbol lbl}\n`;
+ `{emit_symbol lbl}:\n`;
+ emit_frames
+ { efa_label = (fun lbl ->
+ ` .type {emit_label lbl}, %function\n`;
+ ` .quad {emit_label lbl}\n`);
+ efa_16 = (fun n -> ` .short {emit_int n}\n`);
+ efa_32 = (fun n -> ` .long {emit_int32 n}\n`);
+ efa_word = (fun n -> ` .quad {emit_int n}\n`);
+ efa_align = (fun n -> ` .align {emit_int(Misc.log2 n)}\n`);
+ efa_label_rel = (fun lbl ofs ->
+ ` .long {emit_label lbl} - . + {emit_int32 ofs}\n`);
+ efa_def_label = (fun lbl -> `{emit_label lbl}:\n`);
+ efa_string = (fun s -> emit_string_directive " .asciz " s) };
+ ` .type {emit_symbol lbl}, %object\n`;
+ ` .size {emit_symbol lbl}, .-{emit_symbol lbl}\n`;
+ begin match Config.system with
+ | "linux" ->
+ (* Mark stack as non-executable *)
+ ` .section .note.GNU-stack,\"\",%progbits\n`
+ | _ -> ()
+ end
diff --git a/asmcomp/arm64/proc.ml b/asmcomp/arm64/proc.ml
new file mode 100644
index 0000000000..6522a84894
--- /dev/null
+++ b/asmcomp/arm64/proc.ml
@@ -0,0 +1,230 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Description of the ARM processor in 64-bit mode *)
+
+open Misc
+open Cmm
+open Reg
+open Arch
+open Mach
+
+(* Instruction selection *)
+
+let word_addressed = false
+
+(* Registers available for register allocation *)
+
+(* Integer register map:
+ x0 - x15 general purpose (caller-save)
+ x16, x17 temporaries (used by call veeners)
+ x18 platform register (reserved)
+ x19 - x25 general purpose (callee-save)
+ x26 trap pointer
+ x27 alloc pointer
+ x28 alloc limit
+ x29 frame pointer
+ x30 return address
+ sp / xzr stack pointer / zero register
+ Floating-point register map:
+ d0 - d7 general purpose (caller-save)
+ d8 - d15 general purpose (callee-save)
+ d16 - d31 generat purpose (caller-save)
+*)
+
+let int_reg_name =
+ [| "x0"; "x1"; "x2"; "x3"; "x4"; "x5"; "x6"; "x7";
+ "x8"; "x9"; "x10"; "x11"; "x12"; "x13"; "x14"; "x15";
+ "x19"; "x20"; "x21"; "x22"; "x23"; "x24"; "x25";
+ "x26"; "x27"; "x28"; "x16"; "x17" |]
+
+let float_reg_name =
+ [| "d0"; "d1"; "d2"; "d3"; "d4"; "d5"; "d6"; "d7";
+ "d8"; "d9"; "d10"; "d11"; "d12"; "d13"; "d14"; "d15";
+ "d16"; "d17"; "d18"; "d19"; "d20"; "d21"; "d22"; "d23";
+ "d24"; "d25"; "d26"; "d27"; "d28"; "d29"; "d30"; "d31" |]
+
+let num_register_classes = 2
+
+let register_class r =
+ match r.typ with
+ | Val | Int | Addr -> 0
+ | Float -> 1
+
+let num_available_registers =
+ [| 23; 32 |] (* first 23 int regs allocatable; all float regs allocatable *)
+
+let first_available_register =
+ [| 0; 100 |]
+
+let register_name r =
+ if r < 100 then int_reg_name.(r) else float_reg_name.(r - 100)
+
+let rotate_registers = true
+
+(* Representation of hard registers by pseudo-registers *)
+
+let hard_int_reg =
+ let v = Array.make 28 Reg.dummy in
+ for i = 0 to 27 do
+ v.(i) <- Reg.at_location Int (Reg i)
+ done;
+ v
+
+let hard_float_reg =
+ let v = Array.make 32 Reg.dummy in
+ for i = 0 to 31 do
+ v.(i) <- Reg.at_location Float (Reg(100 + i))
+ done;
+ v
+
+let all_phys_regs =
+ Array.append hard_int_reg hard_float_reg
+
+let phys_reg n =
+ if n < 100 then hard_int_reg.(n) else hard_float_reg.(n - 100)
+
+let reg_x15 = phys_reg 15
+let reg_d7 = phys_reg 107
+
+let stack_slot slot ty =
+ Reg.at_location ty (Stack slot)
+
+(* Calling conventions *)
+
+let calling_conventions
+ first_int last_int first_float last_float make_stack arg =
+ let loc = Array.make (Array.length arg) Reg.dummy in
+ let int = ref first_int in
+ let float = ref first_float in
+ let ofs = ref 0 in
+ for i = 0 to Array.length arg - 1 do
+ match arg.(i).typ with
+ | Val | Int | Addr as ty ->
+ if !int <= last_int then begin
+ loc.(i) <- phys_reg !int;
+ incr int
+ end else begin
+ loc.(i) <- stack_slot (make_stack !ofs) ty;
+ ofs := !ofs + size_int
+ end
+ | Float ->
+ if !float <= last_float then begin
+ loc.(i) <- phys_reg !float;
+ incr float
+ end else begin
+ loc.(i) <- stack_slot (make_stack !ofs) Float;
+ ofs := !ofs + size_float
+ end
+ done;
+ (loc, Misc.align !ofs 16) (* keep stack 16-aligned *)
+
+let incoming ofs = Incoming ofs
+let outgoing ofs = Outgoing ofs
+let not_supported ofs = fatal_error "Proc.loc_results: cannot call"
+
+(* OCaml calling convention:
+ first integer args in r0...r15
+ first float args in d0...d15
+ remaining args on stack.
+ Return values in r0...r15 or d0...d15. *)
+
+let loc_arguments arg =
+ calling_conventions 0 15 100 115 outgoing arg
+let loc_parameters arg =
+ let (loc, _) = calling_conventions 0 15 100 115 incoming arg in loc
+let loc_results res =
+ let (loc, _) = calling_conventions 0 15 100 115 not_supported res in loc
+
+(* C calling convention:
+ first integer args in r0...r7
+ first float args in d0...d7
+ remaining args on stack.
+ Return values in r0...r1 or d0. *)
+
+let loc_external_arguments arg =
+ let arg =
+ Array.map (fun regs -> assert (Array.length regs = 1); regs.(0)) arg
+ in
+ let loc, alignment = calling_conventions 0 7 100 107 outgoing arg in
+ Array.map (fun reg -> [|reg|]) loc, alignment
+let loc_external_results res =
+ let (loc, _) = calling_conventions 0 1 100 100 not_supported res in loc
+
+let loc_exn_bucket = phys_reg 0
+
+(* Volatile registers: none *)
+
+let regs_are_volatile rs = false
+
+(* Registers destroyed by operations *)
+
+let destroyed_at_c_call =
+ (* x19-x28, d8-d15 preserved *)
+ Array.of_list (List.map phys_reg
+ [0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;
+ 100;101;102;103;104;105;106;107;
+ 116;117;118;119;120;121;122;123;
+ 124;125;126;127;128;129;130;131])
+
+let destroyed_at_oper = function
+ | Iop(Icall_ind | Icall_imm _) | Iop(Iextcall(_, true)) ->
+ all_phys_regs
+ | Iop(Iextcall(_, false)) ->
+ destroyed_at_c_call
+ | Iop(Ialloc _) ->
+ [| reg_x15 |]
+ | Iop(Iintoffloat | Ifloatofint | Iload(Single, _) | Istore(Single, _, _)) ->
+ [| reg_d7 |] (* d7 / s7 destroyed *)
+ | _ -> [||]
+
+let destroyed_at_raise = all_phys_regs
+
+(* Maximal register pressure *)
+
+let safe_register_pressure = function
+ | Iextcall(_, _) -> 8
+ | Ialloc _ -> 25
+ | _ -> 26
+
+let max_register_pressure = function
+ | Iextcall(_, _) -> [| 10; 8 |]
+ | Ialloc _ -> [| 25; 32 |]
+ | Iintoffloat | Ifloatofint
+ | Iload(Single, _) | Istore(Single, _, _) -> [| 26; 31 |]
+ | _ -> [| 26; 32 |]
+
+(* Pure operations (without any side effect besides updating their result
+ registers). *)
+
+let op_is_pure = function
+ | Icall_ind | Icall_imm _ | Itailcall_ind | Itailcall_imm _
+ | Iextcall _ | Istackoffset _ | Istore _ | Ialloc _
+ | Iintop(Icheckbound) | Iintop_imm(Icheckbound, _)
+ | Ispecific(Ishiftcheckbound _) -> false
+ | _ -> true
+
+(* Layout of the stack *)
+
+let num_stack_slots = [| 0; 0 |]
+let contains_calls = ref false
+
+(* Calling the assembler *)
+
+let assemble_file infile outfile =
+ Ccomp.command (Config.asm ^ " -o " ^
+ Filename.quote outfile ^ " " ^ Filename.quote infile)
+
+
+let init () = ()
diff --git a/asmcomp/arm64/reload.ml b/asmcomp/arm64/reload.ml
new file mode 100644
index 0000000000..ff9214ef26
--- /dev/null
+++ b/asmcomp/arm64/reload.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Reloading for the ARM 64 bits *)
+
+let fundecl f =
+ (new Reloadgen.reload_generic)#fundecl f
diff --git a/asmcomp/arm64/scheduling.ml b/asmcomp/arm64/scheduling.ml
new file mode 100644
index 0000000000..cc244be71a
--- /dev/null
+++ b/asmcomp/arm64/scheduling.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let _ = let module M = Schedgen in () (* to create a dependency *)
+
+(* Scheduling is turned off because the processor schedules dynamically
+ much better than what we could do. *)
+
+let fundecl f = f
diff --git a/asmcomp/arm64/selection.ml b/asmcomp/arm64/selection.ml
new file mode 100644
index 0000000000..95a0a21bef
--- /dev/null
+++ b/asmcomp/arm64/selection.ml
@@ -0,0 +1,243 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* Benedikt Meurer, University of Siegen *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2012 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction selection for the ARM processor *)
+
+open Arch
+open Cmm
+open Mach
+
+let is_offset chunk n =
+ (n >= -256 && n <= 255) (* 9 bits signed unscaled *)
+|| (n >= 0 &&
+ match chunk with (* 12 bits unsigned, scaled by chunk size *)
+ | Byte_unsigned | Byte_signed ->
+ n < 0x1000
+ | Sixteen_unsigned | Sixteen_signed ->
+ n land 1 = 0 && n lsr 1 < 0x1000
+ | Thirtytwo_unsigned | Thirtytwo_signed | Single ->
+ n land 3 = 0 && n lsr 2 < 0x1000
+ | Word_int | Word_val | Double | Double_u ->
+ n land 7 = 0 && n lsr 3 < 0x1000)
+
+(* An automaton to recognize ( 0+1+0* | 1+0+1* )
+
+ 0 1 0
+ / \ / \ / \
+ \ / \ / \ /
+ -0--> [1] --1--> [2] --0--> [3]
+ /
+ [0]
+ \
+ -1--> [4] --0--> [5] --1--> [6]
+ / \ / \ / \
+ \ / \ / \ /
+ 1 0 1
+
+The accepting states are 2, 3, 5 and 6. *)
+
+let auto_table = [| (* accepting?, next on 0, next on 1 *)
+ (* state 0 *) (false, 1, 4);
+ (* state 1 *) (false, 1, 2);
+ (* state 2 *) (true, 3, 2);
+ (* state 3 *) (true, 3, 7);
+ (* state 4 *) (false, 5, 4);
+ (* state 5 *) (true, 5, 6);
+ (* state 6 *) (true, 7, 6);
+ (* state 7 *) (false, 7, 7) (* error state *)
+|]
+
+let rec run_automata nbits state input =
+ let (acc, next0, next1) = auto_table.(state) in
+ if nbits <= 0
+ then acc
+ else run_automata (nbits - 1)
+ (if input land 1 = 0 then next0 else next1)
+ (input asr 1)
+
+(* We are very conservative wrt what ARM64 supports: we don't support
+ repetitions of a 000111000 or 1110000111 pattern, just a single
+ pattern of this kind. *)
+
+let is_logical_immediate n =
+ n <> 0 && n <> -1 && run_automata 64 0 n
+
+let is_intconst = function
+ Cconst_int _ -> true
+ | _ -> false
+
+let inline_ops =
+ [ "sqrt"; "caml_bswap16_direct"; "caml_int32_direct_bswap";
+ "caml_int64_direct_bswap"; "caml_nativeint_direct_bswap" ]
+
+let use_direct_addressing symb =
+ (not !Clflags.dlcode) || Compilenv.symbol_in_current_unit symb
+
+(* Instruction selection *)
+
+class selector = object(self)
+
+inherit Selectgen.selector_generic as super
+
+method is_immediate n =
+ let mn = -n in
+ n land 0xFFF = n || n land 0xFFF_000 = n
+ || mn land 0xFFF = mn || mn land 0xFFF_000 = mn
+
+method! is_simple_expr = function
+ (* inlined floating-point ops are simple if their arguments are *)
+ | Cop(Cextcall(fn, _, _, _), args) when List.mem fn inline_ops ->
+ List.for_all self#is_simple_expr args
+ | e -> super#is_simple_expr e
+
+method select_addressing chunk = function
+ | Cop((Caddv | Cadda), [Cconst_symbol s; Cconst_int n])
+ when use_direct_addressing s ->
+ (Ibased(s, n), Ctuple [])
+ | Cop((Caddv | Cadda), [arg; Cconst_int n])
+ when is_offset chunk n ->
+ (Iindexed n, arg)
+ | Cop((Caddv | Cadda as op), [arg1; Cop(Caddi, [arg2; Cconst_int n])])
+ when is_offset chunk n ->
+ (Iindexed n, Cop(op, [arg1; arg2]))
+ | Cconst_symbol s
+ when use_direct_addressing s ->
+ (Ibased(s, 0), Ctuple [])
+ | arg ->
+ (Iindexed 0, arg)
+
+method! select_operation op args =
+ match op with
+ (* Integer addition *)
+ | Caddi | Caddv | Cadda ->
+ begin match args with
+ (* Add immediate *)
+ | [arg; Cconst_int n] | [Cconst_int n; arg] when self#is_immediate n ->
+ ((if n >= 0 then Iintop_imm(Iadd, n) else Iintop_imm(Isub, -n)),
+ [arg])
+ (* Shift-add *)
+ | [arg1; Cop(Clsl, [arg2; Cconst_int n])] when n > 0 && n < 64 ->
+ (Ispecific(Ishiftarith(Ishiftadd, n)), [arg1; arg2])
+ | [arg1; Cop(Casr, [arg2; Cconst_int n])] when n > 0 && n < 64 ->
+ (Ispecific(Ishiftarith(Ishiftadd, -n)), [arg1; arg2])
+ | [Cop(Clsl, [arg1; Cconst_int n]); arg2] when n > 0 && n < 64 ->
+ (Ispecific(Ishiftarith(Ishiftadd, n)), [arg2; arg1])
+ | [Cop(Casr, [arg1; Cconst_int n]); arg2] when n > 0 && n < 64 ->
+ (Ispecific(Ishiftarith(Ishiftadd, -n)), [arg2; arg1])
+ (* Multiply-add *)
+ | [arg1; Cop(Cmuli, args2)] | [Cop(Cmuli, args2); arg1] ->
+ begin match self#select_operation Cmuli args2 with
+ | (Iintop_imm(Ilsl, l), [arg3]) ->
+ (Ispecific(Ishiftarith(Ishiftadd, l)), [arg1; arg3])
+ | (Iintop Imul, [arg3; arg4]) ->
+ (Ispecific Imuladd, [arg3; arg4; arg1])
+ | _ ->
+ super#select_operation op args
+ end
+ | _ ->
+ super#select_operation op args
+ end
+ (* Integer subtraction *)
+ | Csubi ->
+ begin match args with
+ (* Sub immediate *)
+ | [arg; Cconst_int n] when self#is_immediate n ->
+ ((if n >= 0 then Iintop_imm(Isub, n) else Iintop_imm(Iadd, -n)),
+ [arg])
+ (* Shift-sub *)
+ | [arg1; Cop(Clsl, [arg2; Cconst_int n])] when n > 0 && n < 64 ->
+ (Ispecific(Ishiftarith(Ishiftsub, n)), [arg1; arg2])
+ | [arg1; Cop(Casr, [arg2; Cconst_int n])] when n > 0 && n < 64 ->
+ (Ispecific(Ishiftarith(Ishiftsub, -n)), [arg1; arg2])
+ (* Multiply-sub *)
+ | [arg1; Cop(Cmuli, args2)] ->
+ begin match self#select_operation Cmuli args2 with
+ | (Iintop_imm(Ilsl, l), [arg3]) ->
+ (Ispecific(Ishiftarith(Ishiftsub, l)), [arg1; arg3])
+ | (Iintop Imul, [arg3; arg4]) ->
+ (Ispecific Imulsub, [arg3; arg4; arg1])
+ | _ ->
+ super#select_operation op args
+ end
+ | _ ->
+ super#select_operation op args
+ end
+ (* Checkbounds *)
+ | Ccheckbound _ ->
+ begin match args with
+ | [Cop(Clsr, [arg1; Cconst_int n]); arg2] when n > 0 && n < 64 ->
+ (Ispecific(Ishiftcheckbound n), [arg1; arg2])
+ | _ ->
+ super#select_operation op args
+ end
+ (* Integer multiplication *)
+ (* ARM does not support immediate operands for multiplication *)
+ | Cmuli ->
+ (Iintop Imul, args)
+ | Cmulhi ->
+ (Iintop Imulh, args)
+ (* Bitwise logical operations have a different range of immediate
+ operands than the other instructions *)
+ | Cand -> self#select_logical Iand args
+ | Cor -> self#select_logical Ior args
+ | Cxor -> self#select_logical Ixor args
+ (* Recognize floating-point negate and multiply *)
+ | Cnegf ->
+ begin match args with
+ | [Cop(Cmulf, args)] -> (Ispecific Inegmulf, args)
+ | _ -> super#select_operation op args
+ end
+ (* Recognize floating-point multiply and add/sub *)
+ | Caddf ->
+ begin match args with
+ | [arg; Cop(Cmulf, args)] | [Cop(Cmulf, args); arg] ->
+ (Ispecific Imuladdf, arg :: args)
+ | _ ->
+ super#select_operation op args
+ end
+ | Csubf ->
+ begin match args with
+ | [arg; Cop(Cmulf, args)] ->
+ (Ispecific Imulsubf, arg :: args)
+ | [Cop(Cmulf, args); arg] ->
+ (Ispecific Inegmulsubf, arg :: args)
+ | _ ->
+ super#select_operation op args
+ end
+ (* Recognize floating-point square root *)
+ | Cextcall("sqrt", _, _, _) ->
+ (Ispecific Isqrtf, args)
+ (* Recognize bswap instructions *)
+ | Cextcall("caml_bswap16_direct", _, _, _) ->
+ (Ispecific(Ibswap 16), args)
+ | Cextcall("caml_int32_direct_bswap", _, _, _) ->
+ (Ispecific(Ibswap 32), args)
+ | Cextcall(("caml_int64_direct_bswap"|"caml_nativeint_direct_bswap"),
+ _, _, _) ->
+ (Ispecific (Ibswap 64), args)
+ (* Other operations are regular *)
+ | _ ->
+ super#select_operation op args
+
+method select_logical op = function
+ | [arg; Cconst_int n] when is_logical_immediate n ->
+ (Iintop_imm(op, n), [arg])
+ | [Cconst_int n; arg] when is_logical_immediate n ->
+ (Iintop_imm(op, n), [arg])
+ | args ->
+ (Iintop op, args)
+
+end
+
+let fundecl f = (new selector)#emit_fundecl f
diff --git a/asmcomp/asmgen.ml b/asmcomp/asmgen.ml
new file mode 100644
index 0000000000..0e01f9ba3f
--- /dev/null
+++ b/asmcomp/asmgen.ml
@@ -0,0 +1,164 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* From lambda to assembly code *)
+
+open Format
+open Config
+open Clflags
+open Misc
+open Cmm
+
+type error = Assembler_error of string
+
+exception Error of error
+
+let liveness ppf phrase =
+ Liveness.fundecl ppf phrase; phrase
+
+let dump_if ppf flag message phrase =
+ if !flag then Printmach.phase message ppf phrase
+
+let pass_dump_if ppf flag message phrase =
+ dump_if ppf flag message phrase; phrase
+
+let pass_dump_linear_if ppf flag message phrase =
+ if !flag then fprintf ppf "*** %s@.%a@." message Printlinear.fundecl phrase;
+ phrase
+
+let clambda_dump_if ppf ulambda =
+ if !dump_clambda then Printclambda.clambda ppf ulambda; ulambda
+
+let rec regalloc ppf round fd =
+ if round > 50 then
+ fatal_error(fd.Mach.fun_name ^
+ ": function too complex, cannot complete register allocation");
+ dump_if ppf dump_live "Liveness analysis" fd;
+ Interf.build_graph fd;
+ if !dump_interf then Printmach.interferences ppf ();
+ if !dump_prefer then Printmach.preferences ppf ();
+ Coloring.allocate_registers();
+ dump_if ppf dump_regalloc "After register allocation" fd;
+ let (newfd, redo_regalloc) = Reload.fundecl fd in
+ dump_if ppf dump_reload "After insertion of reloading code" newfd;
+ if redo_regalloc then begin
+ Reg.reinit(); Liveness.fundecl ppf newfd; regalloc ppf (round + 1) newfd
+ end else newfd
+
+let (++) x f = f x
+
+let compile_fundecl (ppf : formatter) fd_cmm =
+ Proc.init ();
+ Reg.reset();
+ fd_cmm
+ ++ Selection.fundecl
+ ++ pass_dump_if ppf dump_selection "After instruction selection"
+ ++ Comballoc.fundecl
+ ++ pass_dump_if ppf dump_combine "After allocation combining"
+ ++ CSE.fundecl
+ ++ pass_dump_if ppf dump_cse "After CSE"
+ ++ liveness ppf
+ ++ Deadcode.fundecl
+ ++ pass_dump_if ppf dump_live "Liveness analysis"
+ ++ Spill.fundecl
+ ++ liveness ppf
+ ++ pass_dump_if ppf dump_spill "After spilling"
+ ++ Split.fundecl
+ ++ pass_dump_if ppf dump_split "After live range splitting"
+ ++ liveness ppf
+ ++ regalloc ppf 1
+ ++ Linearize.fundecl
+ ++ pass_dump_linear_if ppf dump_linear "Linearized code"
+ ++ Scheduling.fundecl
+ ++ pass_dump_linear_if ppf dump_scheduling "After instruction scheduling"
+ ++ Emit.fundecl
+
+let compile_phrase ppf p =
+ if !dump_cmm then fprintf ppf "%a@." Printcmm.phrase p;
+ match p with
+ | Cfunction fd -> compile_fundecl ppf fd
+ | Cdata dl -> Emit.data dl
+
+
+(* For the native toplevel: generates generic functions unless
+ they are already available in the process *)
+let compile_genfuns ppf f =
+ List.iter
+ (function
+ | (Cfunction {fun_name = name}) as ph when f name ->
+ compile_phrase ppf ph
+ | _ -> ())
+ (Cmmgen.generic_functions true [Compilenv.current_unit_infos ()])
+
+let compile_unit asm_filename keep_asm obj_filename gen =
+ let create_asm = keep_asm || not !Emitaux.binary_backend_available in
+ Emitaux.create_asm_file := create_asm;
+ try
+ if create_asm then Emitaux.output_channel := open_out asm_filename;
+ begin try
+ gen ();
+ if create_asm then close_out !Emitaux.output_channel;
+ with exn when create_asm ->
+ close_out !Emitaux.output_channel;
+ if not keep_asm then remove_file asm_filename;
+ raise exn
+ end;
+ if Proc.assemble_file asm_filename obj_filename <> 0
+ then raise(Error(Assembler_error asm_filename));
+ if create_asm && not keep_asm then remove_file asm_filename
+ with exn ->
+ remove_file obj_filename;
+ raise exn
+
+let gen_implementation ?toplevel ppf (size, lam) =
+ Emit.begin_assembly ();
+ Closure.intro size lam
+ ++ clambda_dump_if ppf
+ ++ Cmmgen.compunit size
+ ++ List.iter (compile_phrase ppf) ++ (fun () -> ());
+ (match toplevel with None -> () | Some f -> compile_genfuns ppf f);
+
+ (* We add explicit references to external primitive symbols. This
+ is to ensure that the object files that define these symbols,
+ when part of a C library, won't be discarded by the linker.
+ This is important if a module that uses such a symbol is later
+ dynlinked. *)
+
+ compile_phrase ppf
+ (Cmmgen.reference_symbols
+ (List.filter (fun s -> s <> "" && s.[0] <> '%')
+ (List.map Primitive.native_name !Translmod.primitive_declarations))
+ );
+ Emit.end_assembly ()
+
+let compile_implementation ?toplevel prefixname ppf (size, lam) =
+ let asmfile =
+ if !keep_asm_file || !Emitaux.binary_backend_available
+ then prefixname ^ ext_asm
+ else Filename.temp_file "camlasm" ext_asm
+ in
+ compile_unit asmfile !keep_asm_file (prefixname ^ ext_obj)
+ (fun () -> gen_implementation ?toplevel ppf (size, lam))
+
+(* Error report *)
+
+let report_error ppf = function
+ | Assembler_error file ->
+ fprintf ppf "Assembler error, input left in file %a"
+ Location.print_filename file
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
diff --git a/asmcomp/asmgen.mli b/asmcomp/asmgen.mli
new file mode 100644
index 0000000000..0b5aa02294
--- /dev/null
+++ b/asmcomp/asmgen.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* From lambda to assembly code *)
+
+val compile_implementation :
+ ?toplevel:(string -> bool) ->
+ string -> Format.formatter -> int * Lambda.lambda -> unit
+val compile_phrase :
+ Format.formatter -> Cmm.phrase -> unit
+
+type error = Assembler_error of string
+exception Error of error
+val report_error: Format.formatter -> error -> unit
+
+
+val compile_unit:
+ string(*asm file*) -> bool(*keep asm*) ->
+ string(*obj file*) -> (unit -> unit) -> unit
diff --git a/asmcomp/asmlibrarian.ml b/asmcomp/asmlibrarian.ml
new file mode 100644
index 0000000000..968e1de74c
--- /dev/null
+++ b/asmcomp/asmlibrarian.ml
@@ -0,0 +1,78 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Build libraries of .cmx files *)
+
+open Misc
+open Config
+open Cmx_format
+
+type error =
+ File_not_found of string
+ | Archiver_error of string
+
+exception Error of error
+
+let read_info name =
+ let filename =
+ try
+ find_in_path !load_path name
+ with Not_found ->
+ raise(Error(File_not_found name)) in
+ let (info, crc) = Compilenv.read_unit_info filename in
+ info.ui_force_link <- !Clflags.link_everything;
+ (* There is no need to keep the approximation in the .cmxa file,
+ since the compiler will go looking directly for .cmx files.
+ The linker, which is the only one that reads .cmxa files, does not
+ need the approximation. *)
+ info.ui_approx <- Clambda.Value_unknown;
+ (Filename.chop_suffix filename ".cmx" ^ ext_obj, (info, crc))
+
+let create_archive file_list lib_name =
+ let archive_name = chop_extension_if_any lib_name ^ ext_lib in
+ let outchan = open_out_bin lib_name in
+ try
+ output_string outchan cmxa_magic_number;
+ let (objfile_list, descr_list) =
+ List.split (List.map read_info file_list) in
+ List.iter2
+ (fun file_name (unit, crc) ->
+ Asmlink.check_consistency file_name unit crc)
+ file_list descr_list;
+ let infos =
+ { lib_units = descr_list;
+ lib_ccobjs = !Clflags.ccobjs;
+ lib_ccopts = !Clflags.all_ccopts } in
+ output_value outchan infos;
+ if Ccomp.create_archive archive_name objfile_list <> 0
+ then raise(Error(Archiver_error archive_name));
+ close_out outchan
+ with x ->
+ close_out outchan;
+ remove_file lib_name;
+ remove_file archive_name;
+ raise x
+
+open Format
+
+let report_error ppf = function
+ | File_not_found name ->
+ fprintf ppf "Cannot find file %s" name
+ | Archiver_error name ->
+ fprintf ppf "Error while creating the library %s" name
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
diff --git a/asmcomp/asmlibrarian.mli b/asmcomp/asmlibrarian.mli
new file mode 100644
index 0000000000..c1a6a4788b
--- /dev/null
+++ b/asmcomp/asmlibrarian.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Build libraries of .cmx files *)
+
+open Format
+
+val create_archive: string list -> string -> unit
+
+type error =
+ File_not_found of string
+ | Archiver_error of string
+
+exception Error of error
+
+val report_error: formatter -> error -> unit
diff --git a/asmcomp/asmlink.ml b/asmcomp/asmlink.ml
new file mode 100644
index 0000000000..da6ba72e76
--- /dev/null
+++ b/asmcomp/asmlink.ml
@@ -0,0 +1,409 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Link a set of .cmx/.o files and produce an executable *)
+
+open Misc
+open Config
+open Cmx_format
+open Compilenv
+
+type error =
+ File_not_found of string
+ | Not_an_object_file of string
+ | Missing_implementations of (string * string list) list
+ | Inconsistent_interface of string * string * string
+ | Inconsistent_implementation of string * string * string
+ | Assembler_error of string
+ | Linking_error
+ | Multiple_definition of string * string * string
+ | Missing_cmx of string * string
+
+exception Error of error
+
+(* Consistency check between interfaces and implementations *)
+
+let crc_interfaces = Consistbl.create ()
+let interfaces = ref ([] : string list)
+let crc_implementations = Consistbl.create ()
+let implementations = ref ([] : string list)
+let implementations_defined = ref ([] : (string * string) list)
+let cmx_required = ref ([] : string list)
+
+let check_consistency file_name unit crc =
+ begin try
+ List.iter
+ (fun (name, crco) ->
+ interfaces := name :: !interfaces;
+ match crco with
+ None -> ()
+ | Some crc ->
+ if name = unit.ui_name
+ then Consistbl.set crc_interfaces name crc file_name
+ else Consistbl.check crc_interfaces name crc file_name)
+ unit.ui_imports_cmi
+ with Consistbl.Inconsistency(name, user, auth) ->
+ raise(Error(Inconsistent_interface(name, user, auth)))
+ end;
+ begin try
+ List.iter
+ (fun (name, crco) ->
+ implementations := name :: !implementations;
+ match crco with
+ None ->
+ if List.mem name !cmx_required then
+ raise(Error(Missing_cmx(file_name, name)))
+ | Some crc ->
+ Consistbl.check crc_implementations name crc file_name)
+ unit.ui_imports_cmx
+ with Consistbl.Inconsistency(name, user, auth) ->
+ raise(Error(Inconsistent_implementation(name, user, auth)))
+ end;
+ begin try
+ let source = List.assoc unit.ui_name !implementations_defined in
+ raise (Error(Multiple_definition(unit.ui_name, file_name, source)))
+ with Not_found -> ()
+ end;
+ implementations := unit.ui_name :: !implementations;
+ Consistbl.set crc_implementations unit.ui_name crc file_name;
+ implementations_defined :=
+ (unit.ui_name, file_name) :: !implementations_defined;
+ if unit.ui_symbol <> unit.ui_name then
+ cmx_required := unit.ui_name :: !cmx_required
+
+let extract_crc_interfaces () =
+ Consistbl.extract !interfaces crc_interfaces
+let extract_crc_implementations () =
+ Consistbl.extract !implementations crc_implementations
+
+(* Add C objects and options and "custom" info from a library descriptor.
+ See bytecomp/bytelink.ml for comments on the order of C objects. *)
+
+let lib_ccobjs = ref []
+let lib_ccopts = ref []
+
+let add_ccobjs origin l =
+ if not !Clflags.no_auto_link then begin
+ lib_ccobjs := l.lib_ccobjs @ !lib_ccobjs;
+ let replace_origin =
+ Misc.replace_substring ~before:"$CAMLORIGIN" ~after:origin
+ in
+ lib_ccopts := List.map replace_origin l.lib_ccopts @ !lib_ccopts
+ end
+
+let runtime_lib () =
+ let libname =
+ if !Clflags.gprofile
+ then "libasmrunp" ^ ext_lib
+ else "libasmrun" ^ !Clflags.runtime_variant ^ ext_lib in
+ try
+ if !Clflags.nopervasives then []
+ else [ find_in_path !load_path libname ]
+ with Not_found ->
+ raise(Error(File_not_found libname))
+
+let object_file_name name =
+ let file_name =
+ try
+ find_in_path !load_path name
+ with Not_found ->
+ fatal_error "Asmlink.object_file_name: not found" in
+ if Filename.check_suffix file_name ".cmx" then
+ Filename.chop_suffix file_name ".cmx" ^ ext_obj
+ else if Filename.check_suffix file_name ".cmxa" then
+ Filename.chop_suffix file_name ".cmxa" ^ ext_lib
+ else
+ fatal_error "Asmlink.object_file_name: bad ext"
+
+(* First pass: determine which units are needed *)
+
+let missing_globals = (Hashtbl.create 17 : (string, string list ref) Hashtbl.t)
+
+let is_required name =
+ try ignore (Hashtbl.find missing_globals name); true
+ with Not_found -> false
+
+let add_required by (name, crc) =
+ try
+ let rq = Hashtbl.find missing_globals name in
+ rq := by :: !rq
+ with Not_found ->
+ Hashtbl.add missing_globals name (ref [by])
+
+let remove_required name =
+ Hashtbl.remove missing_globals name
+
+let extract_missing_globals () =
+ let mg = ref [] in
+ Hashtbl.iter (fun md rq -> mg := (md, !rq) :: !mg) missing_globals;
+ !mg
+
+type file =
+ | Unit of string * unit_infos * Digest.t
+ | Library of string * library_infos
+
+let read_file obj_name =
+ let file_name =
+ try
+ find_in_path !load_path obj_name
+ with Not_found ->
+ raise(Error(File_not_found obj_name)) in
+ if Filename.check_suffix file_name ".cmx" then begin
+ (* This is a .cmx file. It must be linked in any case.
+ Read the infos to see which modules it requires. *)
+ let (info, crc) = read_unit_info file_name in
+ Unit (file_name,info,crc)
+ end
+ else if Filename.check_suffix file_name ".cmxa" then begin
+ let infos =
+ try read_library_info file_name
+ with Compilenv.Error(Not_a_unit_info _) ->
+ raise(Error(Not_an_object_file file_name))
+ in
+ Library (file_name,infos)
+ end
+ else raise(Error(Not_an_object_file file_name))
+
+let scan_file obj_name tolink = match read_file obj_name with
+ | Unit (file_name,info,crc) ->
+ (* This is a .cmx file. It must be linked in any case. *)
+ remove_required info.ui_name;
+ List.iter (add_required file_name) info.ui_imports_cmx;
+ (info, file_name, crc) :: tolink
+ | Library (file_name,infos) ->
+ (* This is an archive file. Each unit contained in it will be linked
+ in only if needed. *)
+ add_ccobjs (Filename.dirname file_name) infos;
+ List.fold_right
+ (fun (info, crc) reqd ->
+ if info.ui_force_link
+ || !Clflags.link_everything
+ || is_required info.ui_name
+ then begin
+ remove_required info.ui_name;
+ List.iter (add_required (Printf.sprintf "%s(%s)"
+ file_name info.ui_name))
+ info.ui_imports_cmx;
+ (info, file_name, crc) :: reqd
+ end else
+ reqd)
+ infos.lib_units tolink
+
+(* Second pass: generate the startup file and link it with everything else *)
+
+let make_startup_file ppf units_list =
+ let compile_phrase p = Asmgen.compile_phrase ppf p in
+ Location.input_name := "caml_startup"; (* set name of "current" input *)
+ Compilenv.reset "_startup"; (* set the name of the "current" compunit *)
+ Emit.begin_assembly ();
+ let name_list =
+ List.flatten (List.map (fun (info,_,_) -> info.ui_defines) units_list) in
+ compile_phrase (Cmmgen.entry_point name_list);
+ let units = List.map (fun (info,_,_) -> info) units_list in
+ List.iter compile_phrase (Cmmgen.generic_functions false units);
+ Array.iteri
+ (fun i name -> compile_phrase (Cmmgen.predef_exception i name))
+ Runtimedef.builtin_exceptions;
+ compile_phrase (Cmmgen.global_table name_list);
+ compile_phrase
+ (Cmmgen.globals_map
+ (List.map
+ (fun (unit,_,crc) ->
+ let intf_crc =
+ try
+ match List.assoc unit.ui_name unit.ui_imports_cmi with
+ None -> assert false
+ | Some crc -> crc
+ with Not_found -> assert false
+ in
+ (unit.ui_name, intf_crc, crc, unit.ui_defines))
+ units_list));
+ compile_phrase(Cmmgen.data_segment_table ("_startup" :: name_list));
+ compile_phrase(Cmmgen.code_segment_table ("_startup" :: name_list));
+ compile_phrase
+ (Cmmgen.frame_table("_startup" :: "_system" :: name_list));
+ Emit.end_assembly ()
+
+let make_shared_startup_file ppf units =
+ let compile_phrase p = Asmgen.compile_phrase ppf p in
+ Location.input_name := "caml_startup";
+ Compilenv.reset "_shared_startup";
+ Emit.begin_assembly ();
+ List.iter compile_phrase
+ (Cmmgen.generic_functions true (List.map fst units));
+ compile_phrase (Cmmgen.plugin_header units);
+ compile_phrase
+ (Cmmgen.global_table
+ (List.map (fun (ui,_) -> ui.ui_symbol) units));
+ (* this is to force a reference to all units, otherwise the linker
+ might drop some of them (in case of libraries) *)
+ Emit.end_assembly ()
+
+let call_linker_shared file_list output_name =
+ if not (Ccomp.call_linker Ccomp.Dll output_name file_list "")
+ then raise(Error Linking_error)
+
+let link_shared ppf objfiles output_name =
+ let units_tolink = List.fold_right scan_file objfiles [] in
+ List.iter
+ (fun (info, file_name, crc) -> check_consistency file_name info crc)
+ units_tolink;
+ Clflags.ccobjs := !Clflags.ccobjs @ !lib_ccobjs;
+ Clflags.all_ccopts := !lib_ccopts @ !Clflags.all_ccopts;
+ let objfiles = List.rev (List.map object_file_name objfiles) @
+ (List.rev !Clflags.ccobjs) in
+
+ let startup =
+ if !Clflags.keep_startup_file || !Emitaux.binary_backend_available
+ then output_name ^ ".startup" ^ ext_asm
+ else Filename.temp_file "camlstartup" ext_asm in
+ let startup_obj = output_name ^ ".startup" ^ ext_obj in
+ Asmgen.compile_unit
+ startup !Clflags.keep_startup_file startup_obj
+ (fun () ->
+ make_shared_startup_file ppf
+ (List.map (fun (ui,_,crc) -> (ui,crc)) units_tolink)
+ );
+ call_linker_shared (startup_obj :: objfiles) output_name;
+ remove_file startup_obj
+
+let call_linker file_list startup_file output_name =
+ let main_dll = !Clflags.output_c_object
+ && Filename.check_suffix output_name Config.ext_dll
+ and main_obj_runtime = !Clflags.output_complete_object
+ in
+ let files = startup_file :: (List.rev file_list) in
+ let files, c_lib =
+ if (not !Clflags.output_c_object) || main_dll || main_obj_runtime then
+ files @ (List.rev !Clflags.ccobjs) @ runtime_lib (),
+ (if !Clflags.nopervasives || main_obj_runtime
+ then "" else Config.native_c_libraries)
+ else
+ files, ""
+ in
+ let mode =
+ if main_dll then Ccomp.MainDll
+ else if !Clflags.output_c_object then Ccomp.Partial
+ else Ccomp.Exe
+ in
+ if not (Ccomp.call_linker mode output_name files c_lib)
+ then raise(Error Linking_error)
+
+(* Main entry point *)
+
+let link ppf objfiles output_name =
+ let stdlib =
+ if !Clflags.gprofile then "stdlib.p.cmxa" else "stdlib.cmxa" in
+ let stdexit =
+ if !Clflags.gprofile then "std_exit.p.cmx" else "std_exit.cmx" in
+ let objfiles =
+ if !Clflags.nopervasives then objfiles
+ else if !Clflags.output_c_object then stdlib :: objfiles
+ else stdlib :: (objfiles @ [stdexit]) in
+ let units_tolink = List.fold_right scan_file objfiles [] in
+ Array.iter remove_required Runtimedef.builtin_exceptions;
+ begin match extract_missing_globals() with
+ [] -> ()
+ | mg -> raise(Error(Missing_implementations mg))
+ end;
+ List.iter
+ (fun (info, file_name, crc) -> check_consistency file_name info crc)
+ units_tolink;
+ Clflags.ccobjs := !Clflags.ccobjs @ !lib_ccobjs;
+ Clflags.all_ccopts := !lib_ccopts @ !Clflags.all_ccopts;
+ (* put user's opts first *)
+ let startup =
+ if !Clflags.keep_startup_file || !Emitaux.binary_backend_available
+ then output_name ^ ".startup" ^ ext_asm
+ else Filename.temp_file "camlstartup" ext_asm in
+ let startup_obj = Filename.temp_file "camlstartup" ext_obj in
+ Asmgen.compile_unit
+ startup !Clflags.keep_startup_file startup_obj
+ (fun () -> make_startup_file ppf units_tolink);
+ Misc.try_finally
+ (fun () ->
+ call_linker (List.map object_file_name objfiles) startup_obj output_name)
+ (fun () -> remove_file startup_obj)
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | File_not_found name ->
+ fprintf ppf "Cannot find file %s" name
+ | Not_an_object_file name ->
+ fprintf ppf "The file %a is not a compilation unit description"
+ Location.print_filename name
+ | Missing_implementations l ->
+ let print_references ppf = function
+ | [] -> ()
+ | r1 :: rl ->
+ fprintf ppf "%s" r1;
+ List.iter (fun r -> fprintf ppf ",@ %s" r) rl in
+ let print_modules ppf =
+ List.iter
+ (fun (md, rq) ->
+ fprintf ppf "@ @[<hov 2>%s referenced from %a@]" md
+ print_references rq) in
+ fprintf ppf
+ "@[<v 2>No implementations provided for the following modules:%a@]"
+ print_modules l
+ | Inconsistent_interface(intf, file1, file2) ->
+ fprintf ppf
+ "@[<hov>Files %a@ and %a@ make inconsistent assumptions \
+ over interface %s@]"
+ Location.print_filename file1
+ Location.print_filename file2
+ intf
+ | Inconsistent_implementation(intf, file1, file2) ->
+ fprintf ppf
+ "@[<hov>Files %a@ and %a@ make inconsistent assumptions \
+ over implementation %s@]"
+ Location.print_filename file1
+ Location.print_filename file2
+ intf
+ | Assembler_error file ->
+ fprintf ppf "Error while assembling %a" Location.print_filename file
+ | Linking_error ->
+ fprintf ppf "Error during linking"
+ | Multiple_definition(modname, file1, file2) ->
+ fprintf ppf
+ "@[<hov>Files %a@ and %a@ both define a module named %s@]"
+ Location.print_filename file1
+ Location.print_filename file2
+ modname
+ | Missing_cmx(filename, name) ->
+ fprintf ppf
+ "@[<hov>File %a@ was compiled without access@ \
+ to the .cmx file@ for module %s,@ \
+ which was produced by `ocamlopt -for-pack'.@ \
+ Please recompile %a@ with the correct `-I' option@ \
+ so that %s.cmx@ is found.@]"
+ Location.print_filename filename name
+ Location.print_filename filename
+ name
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
+
+let reset () =
+ Consistbl.clear crc_interfaces;
+ Consistbl.clear crc_implementations;
+ implementations_defined := [];
+ cmx_required := [];
+ interfaces := [];
+ implementations := []
diff --git a/asmcomp/asmlink.mli b/asmcomp/asmlink.mli
new file mode 100644
index 0000000000..60a2111e1c
--- /dev/null
+++ b/asmcomp/asmlink.mli
@@ -0,0 +1,41 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Link a set of .cmx/.o files and produce an executable or a plugin *)
+
+open Format
+
+val link: formatter -> string list -> string -> unit
+
+val link_shared: formatter -> string list -> string -> unit
+
+val call_linker_shared: string list -> string -> unit
+
+val reset : unit -> unit
+val check_consistency: string -> Cmx_format.unit_infos -> Digest.t -> unit
+val extract_crc_interfaces: unit -> (string * Digest.t option) list
+val extract_crc_implementations: unit -> (string * Digest.t option) list
+
+type error =
+ File_not_found of string
+ | Not_an_object_file of string
+ | Missing_implementations of (string * string list) list
+ | Inconsistent_interface of string * string * string
+ | Inconsistent_implementation of string * string * string
+ | Assembler_error of string
+ | Linking_error
+ | Multiple_definition of string * string * string
+ | Missing_cmx of string * string
+
+exception Error of error
+
+val report_error: formatter -> error -> unit
diff --git a/asmcomp/asmpackager.ml b/asmcomp/asmpackager.ml
new file mode 100644
index 0000000000..553d0fe137
--- /dev/null
+++ b/asmcomp/asmpackager.ml
@@ -0,0 +1,214 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* "Package" a set of .cmx/.o files into one .cmx/.o file having the
+ original compilation units as sub-modules. *)
+
+open Misc
+open Cmx_format
+
+type error =
+ Illegal_renaming of string * string * string
+ | Forward_reference of string * string
+ | Wrong_for_pack of string * string
+ | Linking_error
+ | Assembler_error of string
+ | File_not_found of string
+
+
+exception Error of error
+
+(* Read the unit information from a .cmx file. *)
+
+type pack_member_kind = PM_intf | PM_impl of unit_infos
+
+type pack_member =
+ { pm_file: string;
+ pm_name: string;
+ pm_kind: pack_member_kind }
+
+let read_member_info pack_path file = (
+ let name =
+ String.capitalize_ascii(Filename.basename(chop_extensions file)) in
+ let kind =
+ if Filename.check_suffix file ".cmx" then begin
+ let (info, crc) = Compilenv.read_unit_info file in
+ if info.ui_name <> name
+ then raise(Error(Illegal_renaming(name, file, info.ui_name)));
+ if info.ui_symbol <>
+ (Compilenv.current_unit_infos()).ui_symbol ^ "__" ^ info.ui_name
+ then raise(Error(Wrong_for_pack(file, pack_path)));
+ Asmlink.check_consistency file info crc;
+ Compilenv.cache_unit_info info;
+ PM_impl info
+ end else
+ PM_intf in
+ { pm_file = file; pm_name = name; pm_kind = kind }
+)
+
+(* Check absence of forward references *)
+
+let check_units members =
+ let rec check forbidden = function
+ [] -> ()
+ | mb :: tl ->
+ begin match mb.pm_kind with
+ | PM_intf -> ()
+ | PM_impl infos ->
+ List.iter
+ (fun (unit, _) ->
+ if List.mem unit forbidden
+ then raise(Error(Forward_reference(mb.pm_file, unit))))
+ infos.ui_imports_cmx
+ end;
+ check (list_remove mb.pm_name forbidden) tl in
+ check (List.map (fun mb -> mb.pm_name) members) members
+
+(* Make the .o file for the package *)
+
+let make_package_object ppf members targetobj targetname coercion =
+ let objtemp =
+ if !Clflags.keep_asm_file
+ then chop_extension_if_any targetobj ^ ".pack" ^ Config.ext_obj
+ else
+ (* Put the full name of the module in the temporary file name
+ to avoid collisions with MSVC's link /lib in case of successive
+ packs *)
+ Filename.temp_file (Compilenv.make_symbol (Some "")) Config.ext_obj in
+ let components =
+ List.map
+ (fun m ->
+ match m.pm_kind with
+ | PM_intf -> None
+ | PM_impl _ -> Some(Ident.create_persistent m.pm_name))
+ members in
+ Asmgen.compile_implementation
+ (chop_extension_if_any objtemp) ppf
+ (Translmod.transl_store_package
+ components (Ident.create_persistent targetname) coercion);
+ let objfiles =
+ List.map
+ (fun m -> chop_extension_if_any m.pm_file ^ Config.ext_obj)
+ (List.filter (fun m -> m.pm_kind <> PM_intf) members) in
+ let ok =
+ Ccomp.call_linker Ccomp.Partial targetobj (objtemp :: objfiles) ""
+ in
+ remove_file objtemp;
+ if not ok then raise(Error Linking_error)
+
+(* Make the .cmx file for the package *)
+
+let build_package_cmx members cmxfile =
+ let unit_names =
+ List.map (fun m -> m.pm_name) members in
+ let filter lst =
+ List.filter (fun (name, crc) -> not (List.mem name unit_names)) lst in
+ let union lst =
+ List.fold_left
+ (List.fold_left
+ (fun accu n -> if List.mem n accu then accu else n :: accu))
+ [] lst in
+ let units =
+ List.fold_right
+ (fun m accu ->
+ match m.pm_kind with PM_intf -> accu | PM_impl info -> info :: accu)
+ members [] in
+ let ui = Compilenv.current_unit_infos() in
+ let pkg_infos =
+ { ui_name = ui.ui_name;
+ ui_symbol = ui.ui_symbol;
+ ui_defines =
+ List.flatten (List.map (fun info -> info.ui_defines) units) @
+ [ui.ui_symbol];
+ ui_imports_cmi =
+ (ui.ui_name, Some (Env.crc_of_unit ui.ui_name)) ::
+ filter(Asmlink.extract_crc_interfaces());
+ ui_imports_cmx =
+ filter(Asmlink.extract_crc_implementations());
+ ui_approx = ui.ui_approx;
+ ui_curry_fun =
+ union(List.map (fun info -> info.ui_curry_fun) units);
+ ui_apply_fun =
+ union(List.map (fun info -> info.ui_apply_fun) units);
+ ui_send_fun =
+ union(List.map (fun info -> info.ui_send_fun) units);
+ ui_force_link =
+ List.exists (fun info -> info.ui_force_link) units;
+ } in
+ Compilenv.write_unit_info pkg_infos cmxfile
+
+(* Make the .cmx and the .o for the package *)
+
+let package_object_files ppf files targetcmx
+ targetobj targetname coercion =
+ let pack_path =
+ match !Clflags.for_package with
+ | None -> targetname
+ | Some p -> p ^ "." ^ targetname in
+ let members = map_left_right (read_member_info pack_path) files in
+ check_units members;
+ make_package_object ppf members targetobj targetname coercion;
+ build_package_cmx members targetcmx
+
+(* The entry point *)
+
+let package_files ppf initial_env files targetcmx =
+ let files =
+ List.map
+ (fun f ->
+ try find_in_path !Config.load_path f
+ with Not_found -> raise(Error(File_not_found f)))
+ files in
+ let prefix = chop_extensions targetcmx in
+ let targetcmi = prefix ^ ".cmi" in
+ let targetobj = chop_extension_if_any targetcmx ^ Config.ext_obj in
+ let targetname = String.capitalize_ascii(Filename.basename prefix) in
+ (* Set the name of the current "input" *)
+ Location.input_name := targetcmx;
+ (* Set the name of the current compunit *)
+ Compilenv.reset ?packname:!Clflags.for_package targetname;
+ try
+ let coercion =
+ Typemod.package_units initial_env files targetcmi targetname in
+ package_object_files ppf files targetcmx targetobj targetname coercion
+ with x ->
+ remove_file targetcmx; remove_file targetobj;
+ raise x
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ Illegal_renaming(name, file, id) ->
+ fprintf ppf "Wrong file naming: %a@ contains the code for\
+ @ %s when %s was expected"
+ Location.print_filename file name id
+ | Forward_reference(file, ident) ->
+ fprintf ppf "Forward reference to %s in file %a" ident
+ Location.print_filename file
+ | Wrong_for_pack(file, path) ->
+ fprintf ppf "File %a@ was not compiled with the `-for-pack %s' option"
+ Location.print_filename file path
+ | File_not_found file ->
+ fprintf ppf "File %s not found" file
+ | Assembler_error file ->
+ fprintf ppf "Error while assembling %s" file
+ | Linking_error ->
+ fprintf ppf "Error during partial linking"
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
diff --git a/asmcomp/asmpackager.mli b/asmcomp/asmpackager.mli
new file mode 100644
index 0000000000..4d47f5c283
--- /dev/null
+++ b/asmcomp/asmpackager.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* "Package" a set of .cmx/.o files into one .cmx/.o file having the
+ original compilation units as sub-modules. *)
+
+val package_files: Format.formatter -> Env.t -> string list -> string -> unit
+
+type error =
+ Illegal_renaming of string * string * string
+ | Forward_reference of string * string
+ | Wrong_for_pack of string * string
+ | Linking_error
+ | Assembler_error of string
+ | File_not_found of string
+
+exception Error of error
+
+val report_error: Format.formatter -> error -> unit
diff --git a/asmcomp/branch_relaxation.ml b/asmcomp/branch_relaxation.ml
new file mode 100644
index 0000000000..d4609e4a8e
--- /dev/null
+++ b/asmcomp/branch_relaxation.ml
@@ -0,0 +1,138 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* Mark Shinwell, Jane Street Europe *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Mach
+open Linearize
+
+module Make (T : Branch_relaxation_intf.S) = struct
+ let label_map code =
+ let map = Hashtbl.create 37 in
+ let rec fill_map pc instr =
+ match instr.desc with
+ | Lend -> (pc, map)
+ | Llabel lbl -> Hashtbl.add map lbl pc; fill_map pc instr.next
+ | op -> fill_map (pc + T.instr_size op) instr.next
+ in
+ fill_map 0 code
+
+ let branch_overflows map pc_branch lbl_dest max_branch_offset =
+ let pc_dest = Hashtbl.find map lbl_dest in
+ let delta = pc_dest - (pc_branch + T.offset_pc_at_branch) in
+ delta <= -max_branch_offset || delta >= max_branch_offset
+
+ let opt_branch_overflows map pc_branch opt_lbl_dest max_branch_offset =
+ match opt_lbl_dest with
+ | None -> false
+ | Some lbl_dest ->
+ branch_overflows map pc_branch lbl_dest max_branch_offset
+
+ let instr_overflows ~code_size ~max_out_of_line_code_offset instr map pc =
+ match T.Cond_branch.classify_instr instr.desc with
+ | None -> false
+ | Some branch ->
+ let max_branch_offset =
+ (* Remember to cut some slack for multi-word instructions (in the
+ [Linearize] sense of the word) where the branch can be anywhere in
+ the middle. 12 words of slack is plenty. *)
+ T.Cond_branch.max_displacement branch - 12
+ in
+ match instr.desc with
+ | Lop (Ialloc _)
+ | Lop (Iintop Icheckbound)
+ | Lop (Iintop_imm (Icheckbound, _))
+ | Lop (Ispecific _) ->
+ (* We assume that any branches eligible for relaxation generated
+ by these instructions only branch forward. We further assume
+ that any of these may branch to an out-of-line code block. *)
+ code_size + max_out_of_line_code_offset - pc >= max_branch_offset
+ | Lcondbranch (_, lbl) ->
+ branch_overflows map pc lbl max_branch_offset
+ | Lcondbranch3 (lbl0, lbl1, lbl2) ->
+ opt_branch_overflows map pc lbl0 max_branch_offset
+ || opt_branch_overflows map pc lbl1 max_branch_offset
+ || opt_branch_overflows map pc lbl2 max_branch_offset
+ | _ ->
+ Misc.fatal_error "Unsupported instruction for branch relaxation"
+
+ let fixup_branches ~code_size ~max_out_of_line_code_offset map code =
+ let expand_optbranch lbl n arg next =
+ match lbl with
+ | None -> next
+ | Some l ->
+ instr_cons (Lcondbranch (Iinttest_imm (Isigned Cmm.Ceq, n), l))
+ arg [||] next
+ in
+ let rec fixup did_fix pc instr =
+ match instr.desc with
+ | Lend -> did_fix
+ | _ ->
+ let overflows =
+ instr_overflows ~code_size ~max_out_of_line_code_offset instr map pc
+ in
+ if not overflows then
+ fixup did_fix (pc + T.instr_size instr.desc) instr.next
+ else
+ match instr.desc with
+ | Lop (Ialloc num_words) ->
+ instr.desc <- T.relax_allocation ~num_words;
+ fixup true (pc + T.instr_size instr.desc) instr.next
+ | Lop (Iintop Icheckbound) ->
+ instr.desc <- T.relax_intop_checkbound ();
+ fixup true (pc + T.instr_size instr.desc) instr.next
+ | Lop (Iintop_imm (Icheckbound, bound)) ->
+ instr.desc <- T.relax_intop_imm_checkbound ~bound;
+ fixup true (pc + T.instr_size instr.desc) instr.next
+ | Lop (Ispecific specific) ->
+ instr.desc <- T.relax_specific_op specific;
+ fixup true (pc + T.instr_size instr.desc) instr.next
+ | Lcondbranch (test, lbl) ->
+ let lbl2 = new_label() in
+ let cont =
+ instr_cons (Lbranch lbl) [||] [||]
+ (instr_cons (Llabel lbl2) [||] [||] instr.next)
+ in
+ instr.desc <- Lcondbranch (invert_test test, lbl2);
+ instr.next <- cont;
+ fixup true (pc + T.instr_size instr.desc) instr.next
+ | Lcondbranch3 (lbl0, lbl1, lbl2) ->
+ let cont =
+ expand_optbranch lbl0 0 instr.arg
+ (expand_optbranch lbl1 1 instr.arg
+ (expand_optbranch lbl2 2 instr.arg instr.next))
+ in
+ instr.desc <- cont.desc;
+ instr.next <- cont.next;
+ fixup true pc instr
+ | _ ->
+ (* Any other instruction has already been rejected in
+ [instr_overflows] above.
+ We can *never* get here. *)
+ assert false
+ in
+ fixup false 0 code
+
+ (* Iterate branch expansion till all conditional branches are OK *)
+
+ let rec relax code ~max_out_of_line_code_offset =
+ let min_of_max_branch_offsets =
+ List.fold_left (fun min_of_max_branch_offsets branch ->
+ min min_of_max_branch_offsets
+ (T.Cond_branch.max_displacement branch))
+ max_int T.Cond_branch.all
+ in
+ let (code_size, map) = label_map code in
+ if code_size >= min_of_max_branch_offsets
+ && fixup_branches ~code_size ~max_out_of_line_code_offset map code
+ then relax code ~max_out_of_line_code_offset
+ else ()
+end
diff --git a/asmcomp/branch_relaxation.mli b/asmcomp/branch_relaxation.mli
new file mode 100644
index 0000000000..e2a93f83d1
--- /dev/null
+++ b/asmcomp/branch_relaxation.mli
@@ -0,0 +1,26 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* Mark Shinwell, Jane Street Europe *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Fix up conditional branches that exceed hardware-allowed ranges. *)
+
+module Make (T : Branch_relaxation_intf.S) : sig
+ val relax
+ : Linearize.instruction
+ (* [max_offset_of_out_of_line_code] specifies the furthest distance,
+ measured from the first address immediately after the last instruction
+ of the function, that may be branched to from within the function in
+ order to execute "out of line" code blocks such as call GC and
+ bounds check points. *)
+ -> max_out_of_line_code_offset:T.distance
+ -> unit
+end
diff --git a/asmcomp/branch_relaxation_intf.ml b/asmcomp/branch_relaxation_intf.ml
new file mode 100644
index 0000000000..0812c7c1b8
--- /dev/null
+++ b/asmcomp/branch_relaxation_intf.ml
@@ -0,0 +1,64 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* Mark Shinwell, Jane Street Europe *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+module type S = sig
+ (* The distance between two instructions, in arbitrary units (typically
+ the natural word size of instructions). *)
+ type distance = int
+
+ module Cond_branch : sig
+ (* The various types of conditional branches for a given target that
+ may require relaxation. *)
+ type t
+
+ (* All values of type [t] that the emitter may produce. *)
+ val all : t list
+
+ (* If [max_displacement branch] is [n] then [branch] is assumed to
+ reach any address in the range [pc - n, pc + n] (inclusive), after
+ the [pc] of the branch has been adjusted by [offset_pc_at_branch]
+ (see below). *)
+ val max_displacement : t -> distance
+
+ (* Which variety of conditional branch may be produced by the emitter for a
+ given instruction description. For the moment we assume that only one
+ such variety per instruction description is needed.
+
+ N.B. The only instructions supported are the following:
+ - Lop (Ialloc _)
+ - Lop (Iintop Icheckbound)
+ - Lop (Iintop_imm (Icheckbound, _))
+ - Lop (Ispecific _)
+ - Lcondbranch (_, _)
+ - Lcondbranch3 (_, _, _)
+ [classify_instr] is expected to return [None] when called on any
+ instruction not in this list. *)
+ val classify_instr : Linearize.instruction_desc -> t option
+ end
+
+ (* The value to be added to the program counter (in [distance] units)
+ when it is at a branch instruction, prior to calculating the distance
+ to a branch target. *)
+ val offset_pc_at_branch : distance
+
+ (* The maximum size of a given instruction. *)
+ val instr_size : Linearize.instruction_desc -> distance
+
+ (* Insertion of target-specific code to relax operations that cannot be
+ relaxed generically. It is assumed that these rewrites do not change
+ the size of out-of-line code (cf. branch_relaxation.mli). *)
+ val relax_allocation : num_words:int -> Linearize.instruction_desc
+ val relax_intop_checkbound : unit -> Linearize.instruction_desc
+ val relax_intop_imm_checkbound : bound:int -> Linearize.instruction_desc
+ val relax_specific_op : Arch.specific_operation -> Linearize.instruction_desc
+end
diff --git a/asmcomp/clambda.ml b/asmcomp/clambda.ml
new file mode 100644
index 0000000000..a9d652b3ff
--- /dev/null
+++ b/asmcomp/clambda.ml
@@ -0,0 +1,150 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A variant of the "lambda" code with direct / indirect calls explicit
+ and closures explicit too *)
+
+open Asttypes
+open Lambda
+
+type function_label = string
+
+type ustructured_constant =
+ | Uconst_float of float
+ | Uconst_int32 of int32
+ | Uconst_int64 of int64
+ | Uconst_nativeint of nativeint
+ | Uconst_block of int * uconstant list
+ | Uconst_float_array of float list
+ | Uconst_string of string
+
+and uconstant =
+ | Uconst_ref of string * ustructured_constant
+ | Uconst_int of int
+ | Uconst_ptr of int
+
+type ulambda =
+ Uvar of Ident.t
+ | Uconst of uconstant
+ | Udirect_apply of function_label * ulambda list * Debuginfo.t
+ | Ugeneric_apply of ulambda * ulambda list * Debuginfo.t
+ | Uclosure of ufunction list * ulambda list
+ | Uoffset of ulambda * int
+ | Ulet of Ident.t * ulambda * ulambda
+ | Uletrec of (Ident.t * ulambda) list * ulambda
+ | Uprim of primitive * ulambda list * Debuginfo.t
+ | Uswitch of ulambda * ulambda_switch
+ | Ustringswitch of ulambda * (string * ulambda) list * ulambda option
+ | Ustaticfail of int * ulambda list
+ | Ucatch of int * Ident.t list * ulambda * ulambda
+ | Utrywith of ulambda * Ident.t * ulambda
+ | Uifthenelse of ulambda * ulambda * ulambda
+ | Usequence of ulambda * ulambda
+ | Uwhile of ulambda * ulambda
+ | Ufor of Ident.t * ulambda * ulambda * direction_flag * ulambda
+ | Uassign of Ident.t * ulambda
+ | Usend of meth_kind * ulambda * ulambda * ulambda list * Debuginfo.t
+
+and ufunction = {
+ label : function_label;
+ arity : int;
+ params : Ident.t list;
+ body : ulambda;
+ dbg : Debuginfo.t
+}
+
+and ulambda_switch =
+ { us_index_consts: int array;
+ us_actions_consts : ulambda array;
+ us_index_blocks: int array;
+ us_actions_blocks: ulambda array}
+
+(* Description of known functions *)
+
+type function_description =
+ { fun_label: function_label; (* Label of direct entry point *)
+ fun_arity: int; (* Number of arguments *)
+ mutable fun_closed: bool; (* True if environment not used *)
+ mutable fun_inline: (Ident.t list * ulambda) option;
+ mutable fun_float_const_prop: bool (* Can propagate FP consts *)
+ }
+
+(* Approximation of values *)
+
+type value_approximation =
+ Value_closure of function_description * value_approximation
+ | Value_tuple of value_approximation array
+ | Value_unknown
+ | Value_const of uconstant
+ | Value_global_field of string * int
+
+(* Comparison functions for constants. We must not use Pervasives.compare
+ because it compares "0.0" and "-0.0" equal. (PR#6442) *)
+
+let compare_floats x1 x2 =
+ Int64.compare (Int64.bits_of_float x1) (Int64.bits_of_float x2)
+
+let rec compare_float_lists l1 l2 =
+ match l1, l2 with
+ | [], [] -> 0
+ | [], _::_ -> -1
+ | _::_, [] -> 1
+ | h1::t1, h2::t2 ->
+ let c = compare_floats h1 h2 in
+ if c <> 0 then c else compare_float_lists t1 t2
+
+let compare_constants c1 c2 =
+ match c1, c2 with
+ | Uconst_ref(lbl1, c1), Uconst_ref(lbl2, c2) -> String.compare lbl1 lbl2
+ (* Same labels -> same constants.
+ Different labels -> different constants, even if the contents
+ match, because of string constants that must not be
+ reshared. *)
+ | Uconst_int n1, Uconst_int n2 -> Pervasives.compare n1 n2
+ | Uconst_ptr n1, Uconst_ptr n2 -> Pervasives.compare n1 n2
+ | Uconst_ref _, _ -> -1
+ | Uconst_int _, Uconst_ref _ -> 1
+ | Uconst_int _, Uconst_ptr _ -> -1
+ | Uconst_ptr _, _ -> 1
+
+let rec compare_constant_lists l1 l2 =
+ match l1, l2 with
+ | [], [] -> 0
+ | [], _::_ -> -1
+ | _::_, [] -> 1
+ | h1::t1, h2::t2 ->
+ let c = compare_constants h1 h2 in
+ if c <> 0 then c else compare_constant_lists t1 t2
+
+let rank_structured_constant = function
+ | Uconst_float _ -> 0
+ | Uconst_int32 _ -> 1
+ | Uconst_int64 _ -> 2
+ | Uconst_nativeint _ -> 3
+ | Uconst_block _ -> 4
+ | Uconst_float_array _ -> 5
+ | Uconst_string _ -> 6
+
+let compare_structured_constants c1 c2 =
+ match c1, c2 with
+ | Uconst_float x1, Uconst_float x2 -> compare_floats x1 x2
+ | Uconst_int32 x1, Uconst_int32 x2 -> Int32.compare x1 x2
+ | Uconst_int64 x1, Uconst_int64 x2 -> Int64.compare x1 x2
+ | Uconst_nativeint x1, Uconst_nativeint x2 -> Nativeint.compare x1 x2
+ | Uconst_block(t1, l1), Uconst_block(t2, l2) ->
+ let c = t1 - t2 (* no overflow possible here *) in
+ if c <> 0 then c else compare_constant_lists l1 l2
+ | Uconst_float_array l1, Uconst_float_array l2 ->
+ compare_float_lists l1 l2
+ | Uconst_string s1, Uconst_string s2 -> String.compare s1 s2
+ | _, _ -> rank_structured_constant c1 - rank_structured_constant c2
+ (* no overflow possible here *)
diff --git a/asmcomp/clambda.mli b/asmcomp/clambda.mli
new file mode 100644
index 0000000000..fc7a14d1e2
--- /dev/null
+++ b/asmcomp/clambda.mli
@@ -0,0 +1,95 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A variant of the "lambda" code with direct / indirect calls explicit
+ and closures explicit too *)
+
+open Asttypes
+open Lambda
+
+type function_label = string
+
+type ustructured_constant =
+ | Uconst_float of float
+ | Uconst_int32 of int32
+ | Uconst_int64 of int64
+ | Uconst_nativeint of nativeint
+ | Uconst_block of int * uconstant list
+ | Uconst_float_array of float list
+ | Uconst_string of string
+
+and uconstant =
+ | Uconst_ref of string * ustructured_constant
+ | Uconst_int of int
+ | Uconst_ptr of int
+
+type ulambda =
+ Uvar of Ident.t
+ | Uconst of uconstant
+ | Udirect_apply of function_label * ulambda list * Debuginfo.t
+ | Ugeneric_apply of ulambda * ulambda list * Debuginfo.t
+ | Uclosure of ufunction list * ulambda list
+ | Uoffset of ulambda * int
+ | Ulet of Ident.t * ulambda * ulambda
+ | Uletrec of (Ident.t * ulambda) list * ulambda
+ | Uprim of primitive * ulambda list * Debuginfo.t
+ | Uswitch of ulambda * ulambda_switch
+ | Ustringswitch of ulambda * (string * ulambda) list * ulambda option
+ | Ustaticfail of int * ulambda list
+ | Ucatch of int * Ident.t list * ulambda * ulambda
+ | Utrywith of ulambda * Ident.t * ulambda
+ | Uifthenelse of ulambda * ulambda * ulambda
+ | Usequence of ulambda * ulambda
+ | Uwhile of ulambda * ulambda
+ | Ufor of Ident.t * ulambda * ulambda * direction_flag * ulambda
+ | Uassign of Ident.t * ulambda
+ | Usend of meth_kind * ulambda * ulambda * ulambda list * Debuginfo.t
+
+and ufunction = {
+ label : function_label;
+ arity : int;
+ params : Ident.t list;
+ body : ulambda;
+ dbg : Debuginfo.t;
+}
+
+and ulambda_switch =
+ { us_index_consts: int array;
+ us_actions_consts: ulambda array;
+ us_index_blocks: int array;
+ us_actions_blocks: ulambda array}
+
+(* Description of known functions *)
+
+type function_description =
+ { fun_label: function_label; (* Label of direct entry point *)
+ fun_arity: int; (* Number of arguments *)
+ mutable fun_closed: bool; (* True if environment not used *)
+ mutable fun_inline: (Ident.t list * ulambda) option;
+ mutable fun_float_const_prop: bool (* Can propagate FP consts *)
+ }
+
+(* Approximation of values *)
+
+type value_approximation =
+ Value_closure of function_description * value_approximation
+ | Value_tuple of value_approximation array
+ | Value_unknown
+ | Value_const of uconstant
+ | Value_global_field of string * int
+
+(* Comparison functions for constants *)
+
+val compare_structured_constants:
+ ustructured_constant -> ustructured_constant -> int
+val compare_constants:
+ uconstant -> uconstant -> int
diff --git a/asmcomp/closure.ml b/asmcomp/closure.ml
new file mode 100644
index 0000000000..175932c8f5
--- /dev/null
+++ b/asmcomp/closure.ml
@@ -0,0 +1,1331 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Introduction of closures, uncurrying, recognition of direct calls *)
+
+open Misc
+open Asttypes
+open Primitive
+open Lambda
+open Switch
+open Clambda
+
+module Storer =
+ Switch.Store
+ (struct
+ type t = lambda
+ type key = lambda
+ let make_key = Lambda.make_key
+ end)
+
+(* Auxiliaries for compiling functions *)
+
+let rec split_list n l =
+ if n <= 0 then ([], l) else begin
+ match l with
+ [] -> fatal_error "Closure.split_list"
+ | a::l -> let (l1, l2) = split_list (n-1) l in (a::l1, l2)
+ end
+
+let rec build_closure_env env_param pos = function
+ [] -> Tbl.empty
+ | id :: rem ->
+ Tbl.add id (Uprim(Pfield pos, [Uvar env_param], Debuginfo.none))
+ (build_closure_env env_param (pos+1) rem)
+
+(* Auxiliary for accessing globals. We change the name of the global
+ to the name of the corresponding asm symbol. This is done here
+ and no longer in Cmmgen so that approximations stored in .cmx files
+ contain the right names if the -for-pack option is active. *)
+
+let getglobal id =
+ Uprim(Pgetglobal (Ident.create_persistent (Compilenv.symbol_for_global id)),
+ [], Debuginfo.none)
+
+(* Check if a variable occurs in a [clambda] term. *)
+
+let occurs_var var u =
+ let rec occurs = function
+ Uvar v -> v = var
+ | Uconst _ -> false
+ | Udirect_apply(lbl, args, _) -> List.exists occurs args
+ | Ugeneric_apply(funct, args, _) -> occurs funct || List.exists occurs args
+ | Uclosure(fundecls, clos) -> List.exists occurs clos
+ | Uoffset(u, ofs) -> occurs u
+ | Ulet(id, def, body) -> occurs def || occurs body
+ | Uletrec(decls, body) ->
+ List.exists (fun (id, u) -> occurs u) decls || occurs body
+ | Uprim(p, args, _) -> List.exists occurs args
+ | Uswitch(arg, s) ->
+ occurs arg ||
+ occurs_array s.us_actions_consts || occurs_array s.us_actions_blocks
+ | Ustringswitch(arg,sw,d) ->
+ occurs arg ||
+ List.exists (fun (_,e) -> occurs e) sw ||
+ (match d with None -> false | Some d -> occurs d)
+ | Ustaticfail (_, args) -> List.exists occurs args
+ | Ucatch(_, _, body, hdlr) -> occurs body || occurs hdlr
+ | Utrywith(body, exn, hdlr) -> occurs body || occurs hdlr
+ | Uifthenelse(cond, ifso, ifnot) ->
+ occurs cond || occurs ifso || occurs ifnot
+ | Usequence(u1, u2) -> occurs u1 || occurs u2
+ | Uwhile(cond, body) -> occurs cond || occurs body
+ | Ufor(id, lo, hi, dir, body) -> occurs lo || occurs hi || occurs body
+ | Uassign(id, u) -> id = var || occurs u
+ | Usend(_, met, obj, args, _) ->
+ occurs met || occurs obj || List.exists occurs args
+ and occurs_array a =
+ try
+ for i = 0 to Array.length a - 1 do
+ if occurs a.(i) then raise Exit
+ done;
+ false
+ with Exit ->
+ true
+ in occurs u
+
+(* Split a function with default parameters into a wrapper and an
+ inner function. The wrapper fills in missing optional parameters
+ with their default value and tail-calls the inner function. The
+ wrapper can then hopefully be inlined on most call sites to avoid
+ the overhead associated with boxing an optional argument with a
+ 'Some' constructor, only to deconstruct it immediately in the
+ function's body. *)
+
+let split_default_wrapper fun_id kind params body =
+ let rec aux map = function
+ | Llet(Strict, id, (Lifthenelse(Lvar optparam, _, _) as def), rest) when
+ Ident.name optparam = "*opt*" && List.mem optparam params
+ && not (List.mem_assoc optparam map)
+ ->
+ let wrapper_body, inner = aux ((optparam, id) :: map) rest in
+ Llet(Strict, id, def, wrapper_body), inner
+ | _ when map = [] -> raise Exit
+ | body ->
+ (* Check that those *opt* identifiers don't appear in the remaining
+ body. This should not appear, but let's be on the safe side. *)
+ let fv = Lambda.free_variables body in
+ List.iter (fun (id, _) -> if IdentSet.mem id fv then raise Exit) map;
+
+ let inner_id = Ident.create (Ident.name fun_id ^ "_inner") in
+ let map_param p = try List.assoc p map with Not_found -> p in
+ let args = List.map (fun p -> Lvar (map_param p)) params in
+ let wrapper_body = Lapply (Lvar inner_id, args, no_apply_info) in
+
+ let inner_params = List.map map_param params in
+ let new_ids = List.map Ident.rename inner_params in
+ let subst = List.fold_left2
+ (fun s id new_id ->
+ Ident.add id (Lvar new_id) s)
+ Ident.empty inner_params new_ids
+ in
+ let body = Lambda.subst_lambda subst body in
+ let inner_fun = Lfunction{kind = Curried; params = new_ids; body} in
+ (wrapper_body, (inner_id, inner_fun))
+ in
+ try
+ let wrapper_body, inner = aux [] body in
+ [(fun_id, Lfunction{kind; params; body = wrapper_body}); inner]
+ with Exit ->
+ [(fun_id, Lfunction{kind; params; body})]
+
+
+(* Determine whether the estimated size of a clambda term is below
+ some threshold *)
+
+let prim_size prim args =
+ match prim with
+ Pidentity -> 0
+ | Pgetglobal id -> 1
+ | Psetglobal id -> 1
+ | Pmakeblock(tag, mut) -> 5 + List.length args
+ | Pfield f -> 1
+ | Psetfield(f, isptr) -> if isptr then 4 else 1
+ | Pfloatfield f -> 1
+ | Psetfloatfield f -> 1
+ | Pduprecord _ -> 10 + List.length args
+ | Pccall p -> (if p.prim_alloc then 10 else 4) + List.length args
+ | Praise _ -> 4
+ | Pstringlength -> 5
+ | Pstringrefs | Pstringsets -> 6
+ | Pmakearray kind -> 5 + List.length args
+ | Parraylength kind -> if kind = Pgenarray then 6 else 2
+ | Parrayrefu kind -> if kind = Pgenarray then 12 else 2
+ | Parraysetu kind -> if kind = Pgenarray then 16 else 4
+ | Parrayrefs kind -> if kind = Pgenarray then 18 else 8
+ | Parraysets kind -> if kind = Pgenarray then 22 else 10
+ | Pbittest -> 3
+ | Pbigarrayref(_, ndims, _, _) -> 4 + ndims * 6
+ | Pbigarrayset(_, ndims, _, _) -> 4 + ndims * 6
+ | _ -> 2 (* arithmetic and comparisons *)
+
+(* Very raw approximation of switch cost *)
+
+let lambda_smaller lam threshold =
+ let size = ref 0 in
+ let rec lambda_size lam =
+ if !size > threshold then raise Exit;
+ match lam with
+ Uvar v -> ()
+ | Uconst _ -> incr size
+ | Udirect_apply(fn, args, _) ->
+ size := !size + 4; lambda_list_size args
+ | Ugeneric_apply(fn, args, _) ->
+ size := !size + 6; lambda_size fn; lambda_list_size args
+ | Uclosure(defs, vars) ->
+ raise Exit (* inlining would duplicate function definitions *)
+ | Uoffset(lam, ofs) ->
+ incr size; lambda_size lam
+ | Ulet(id, lam, body) ->
+ lambda_size lam; lambda_size body
+ | Uletrec(bindings, body) ->
+ raise Exit (* usually too large *)
+ | Uprim(prim, args, _) ->
+ size := !size + prim_size prim args;
+ lambda_list_size args
+ | Uswitch(lam, cases) ->
+ if Array.length cases.us_actions_consts > 1 then size := !size + 5 ;
+ if Array.length cases.us_actions_blocks > 1 then size := !size + 5 ;
+ lambda_size lam;
+ lambda_array_size cases.us_actions_consts ;
+ lambda_array_size cases.us_actions_blocks
+ | Ustringswitch (lam,sw,d) ->
+ lambda_size lam ;
+ (* as ifthenelse *)
+ List.iter
+ (fun (_,lam) ->
+ size := !size+2 ;
+ lambda_size lam)
+ sw ;
+ Misc.may lambda_size d
+ | Ustaticfail (_,args) -> lambda_list_size args
+ | Ucatch(_, _, body, handler) ->
+ incr size; lambda_size body; lambda_size handler
+ | Utrywith(body, id, handler) ->
+ size := !size + 8; lambda_size body; lambda_size handler
+ | Uifthenelse(cond, ifso, ifnot) ->
+ size := !size + 2;
+ lambda_size cond; lambda_size ifso; lambda_size ifnot
+ | Usequence(lam1, lam2) ->
+ lambda_size lam1; lambda_size lam2
+ | Uwhile(cond, body) ->
+ size := !size + 2; lambda_size cond; lambda_size body
+ | Ufor(id, low, high, dir, body) ->
+ size := !size + 4; lambda_size low; lambda_size high; lambda_size body
+ | Uassign(id, lam) ->
+ incr size; lambda_size lam
+ | Usend(_, met, obj, args, _) ->
+ size := !size + 8;
+ lambda_size met; lambda_size obj; lambda_list_size args
+ and lambda_list_size l = List.iter lambda_size l
+ and lambda_array_size a = Array.iter lambda_size a in
+ try
+ lambda_size lam; !size <= threshold
+ with Exit ->
+ false
+
+(* Check if a clambda term is ``pure'',
+ that is without side-effects *and* not containing function definitions *)
+
+let rec is_pure_clambda = function
+ Uvar v -> true
+ | Uconst _ -> true
+ | Uprim((Psetglobal _ | Psetfield _ | Psetfloatfield _ | Pduprecord _ |
+ Pccall _ | Praise _ | Poffsetref _ | Pstringsetu | Pstringsets |
+ Parraysetu _ | Parraysets _ | Pbigarrayset _), _, _) -> false
+ | Uprim(p, args, _) -> List.for_all is_pure_clambda args
+ | _ -> false
+
+(* Simplify primitive operations on known arguments *)
+
+let make_const c = (Uconst c, Value_const c)
+let make_const_ref c =
+ make_const(Uconst_ref(Compilenv.new_structured_constant ~shared:true c, c))
+let make_const_int n = make_const (Uconst_int n)
+let make_const_ptr n = make_const (Uconst_ptr n)
+let make_const_bool b = make_const_ptr(if b then 1 else 0)
+let make_comparison cmp x y =
+ make_const_bool
+ (match cmp with
+ Ceq -> x = y
+ | Cneq -> x <> y
+ | Clt -> x < y
+ | Cgt -> x > y
+ | Cle -> x <= y
+ | Cge -> x >= y)
+let make_const_float n = make_const_ref (Uconst_float n)
+let make_const_natint n = make_const_ref (Uconst_nativeint n)
+let make_const_int32 n = make_const_ref (Uconst_int32 n)
+let make_const_int64 n = make_const_ref (Uconst_int64 n)
+
+(* The [fpc] parameter is true if constant propagation of
+ floating-point computations is allowed *)
+
+let simplif_arith_prim_pure fpc p (args, approxs) dbg =
+ let default = (Uprim(p, args, dbg), Value_unknown) in
+ match approxs with
+ (* int (or enumerated type) *)
+ | [ Value_const(Uconst_int n1 | Uconst_ptr n1) ] ->
+ begin match p with
+ | Pnot -> make_const_bool (n1 = 0)
+ | Pnegint -> make_const_int (- n1)
+ | Poffsetint n -> make_const_int (n + n1)
+ | Pfloatofint when fpc -> make_const_float (float_of_int n1)
+ | Pbintofint Pnativeint -> make_const_natint (Nativeint.of_int n1)
+ | Pbintofint Pint32 -> make_const_int32 (Int32.of_int n1)
+ | Pbintofint Pint64 -> make_const_int64 (Int64.of_int n1)
+ | Pbswap16 -> make_const_int (((n1 land 0xff) lsl 8)
+ lor ((n1 land 0xff00) lsr 8))
+ | _ -> default
+ end
+ (* int (or enumerated type), int (or enumerated type) *)
+ | [ Value_const(Uconst_int n1 | Uconst_ptr n1);
+ Value_const(Uconst_int n2 | Uconst_ptr n2) ] ->
+ begin match p with
+ | Psequand -> make_const_bool (n1 <> 0 && n2 <> 0)
+ | Psequor -> make_const_bool (n1 <> 0 || n2 <> 0)
+ | Paddint -> make_const_int (n1 + n2)
+ | Psubint -> make_const_int (n1 - n2)
+ | Pmulint -> make_const_int (n1 * n2)
+ | Pdivint when n2 <> 0 -> make_const_int (n1 / n2)
+ | Pmodint when n2 <> 0 -> make_const_int (n1 mod n2)
+ | Pandint -> make_const_int (n1 land n2)
+ | Porint -> make_const_int (n1 lor n2)
+ | Pxorint -> make_const_int (n1 lxor n2)
+ | Plslint when 0 <= n2 && n2 < 8 * Arch.size_int ->
+ make_const_int (n1 lsl n2)
+ | Plsrint when 0 <= n2 && n2 < 8 * Arch.size_int ->
+ make_const_int (n1 lsr n2)
+ | Pasrint when 0 <= n2 && n2 < 8 * Arch.size_int ->
+ make_const_int (n1 asr n2)
+ | Pintcomp c -> make_comparison c n1 n2
+ | _ -> default
+ end
+ (* float *)
+ | [Value_const(Uconst_ref(_, Uconst_float n1))] when fpc ->
+ begin match p with
+ | Pintoffloat -> make_const_int (int_of_float n1)
+ | Pnegfloat -> make_const_float (-. n1)
+ | Pabsfloat -> make_const_float (abs_float n1)
+ | _ -> default
+ end
+ (* float, float *)
+ | [Value_const(Uconst_ref(_, Uconst_float n1));
+ Value_const(Uconst_ref(_, Uconst_float n2))] when fpc ->
+ begin match p with
+ | Paddfloat -> make_const_float (n1 +. n2)
+ | Psubfloat -> make_const_float (n1 -. n2)
+ | Pmulfloat -> make_const_float (n1 *. n2)
+ | Pdivfloat -> make_const_float (n1 /. n2)
+ | Pfloatcomp c -> make_comparison c n1 n2
+ | _ -> default
+ end
+ (* nativeint *)
+ | [Value_const(Uconst_ref(_, Uconst_nativeint n))] ->
+ begin match p with
+ | Pintofbint Pnativeint -> make_const_int (Nativeint.to_int n)
+ | Pcvtbint(Pnativeint, Pint32) -> make_const_int32 (Nativeint.to_int32 n)
+ | Pcvtbint(Pnativeint, Pint64) -> make_const_int64 (Int64.of_nativeint n)
+ | Pnegbint Pnativeint -> make_const_natint (Nativeint.neg n)
+ | _ -> default
+ end
+ (* nativeint, nativeint *)
+ | [Value_const(Uconst_ref(_, Uconst_nativeint n1));
+ Value_const(Uconst_ref(_, Uconst_nativeint n2))] ->
+ begin match p with
+ | Paddbint Pnativeint -> make_const_natint (Nativeint.add n1 n2)
+ | Psubbint Pnativeint -> make_const_natint (Nativeint.sub n1 n2)
+ | Pmulbint Pnativeint -> make_const_natint (Nativeint.mul n1 n2)
+ | Pdivbint Pnativeint when n2 <> 0n ->
+ make_const_natint (Nativeint.div n1 n2)
+ | Pmodbint Pnativeint when n2 <> 0n ->
+ make_const_natint (Nativeint.rem n1 n2)
+ | Pandbint Pnativeint -> make_const_natint (Nativeint.logand n1 n2)
+ | Porbint Pnativeint -> make_const_natint (Nativeint.logor n1 n2)
+ | Pxorbint Pnativeint -> make_const_natint (Nativeint.logxor n1 n2)
+ | Pbintcomp(Pnativeint, c) -> make_comparison c n1 n2
+ | _ -> default
+ end
+ (* nativeint, int *)
+ | [Value_const(Uconst_ref(_, Uconst_nativeint n1));
+ Value_const(Uconst_int n2)] ->
+ begin match p with
+ | Plslbint Pnativeint when 0 <= n2 && n2 < 8 * Arch.size_int ->
+ make_const_natint (Nativeint.shift_left n1 n2)
+ | Plsrbint Pnativeint when 0 <= n2 && n2 < 8 * Arch.size_int ->
+ make_const_natint (Nativeint.shift_right_logical n1 n2)
+ | Pasrbint Pnativeint when 0 <= n2 && n2 < 8 * Arch.size_int ->
+ make_const_natint (Nativeint.shift_right n1 n2)
+ | _ -> default
+ end
+ (* int32 *)
+ | [Value_const(Uconst_ref(_, Uconst_int32 n))] ->
+ begin match p with
+ | Pintofbint Pint32 -> make_const_int (Int32.to_int n)
+ | Pcvtbint(Pint32, Pnativeint) -> make_const_natint (Nativeint.of_int32 n)
+ | Pcvtbint(Pint32, Pint64) -> make_const_int64 (Int64.of_int32 n)
+ | Pnegbint Pint32 -> make_const_int32 (Int32.neg n)
+ | _ -> default
+ end
+ (* int32, int32 *)
+ | [Value_const(Uconst_ref(_, Uconst_int32 n1));
+ Value_const(Uconst_ref(_, Uconst_int32 n2))] ->
+ begin match p with
+ | Paddbint Pint32 -> make_const_int32 (Int32.add n1 n2)
+ | Psubbint Pint32 -> make_const_int32 (Int32.sub n1 n2)
+ | Pmulbint Pint32 -> make_const_int32 (Int32.mul n1 n2)
+ | Pdivbint Pint32 when n2 <> 0l -> make_const_int32 (Int32.div n1 n2)
+ | Pmodbint Pint32 when n2 <> 0l -> make_const_int32 (Int32.rem n1 n2)
+ | Pandbint Pint32 -> make_const_int32 (Int32.logand n1 n2)
+ | Porbint Pint32 -> make_const_int32 (Int32.logor n1 n2)
+ | Pxorbint Pint32 -> make_const_int32 (Int32.logxor n1 n2)
+ | Pbintcomp(Pint32, c) -> make_comparison c n1 n2
+ | _ -> default
+ end
+ (* int32, int *)
+ | [Value_const(Uconst_ref(_, Uconst_int32 n1));
+ Value_const(Uconst_int n2)] ->
+ begin match p with
+ | Plslbint Pint32 when 0 <= n2 && n2 < 32 ->
+ make_const_int32 (Int32.shift_left n1 n2)
+ | Plsrbint Pint32 when 0 <= n2 && n2 < 32 ->
+ make_const_int32 (Int32.shift_right_logical n1 n2)
+ | Pasrbint Pint32 when 0 <= n2 && n2 < 32 ->
+ make_const_int32 (Int32.shift_right n1 n2)
+ | _ -> default
+ end
+ (* int64 *)
+ | [Value_const(Uconst_ref(_, Uconst_int64 n))] ->
+ begin match p with
+ | Pintofbint Pint64 -> make_const_int (Int64.to_int n)
+ | Pcvtbint(Pint64, Pint32) -> make_const_int32 (Int64.to_int32 n)
+ | Pcvtbint(Pint64, Pnativeint) -> make_const_natint (Int64.to_nativeint n)
+ | Pnegbint Pint64 -> make_const_int64 (Int64.neg n)
+ | _ -> default
+ end
+ (* int64, int64 *)
+ | [Value_const(Uconst_ref(_, Uconst_int64 n1));
+ Value_const(Uconst_ref(_, Uconst_int64 n2))] ->
+ begin match p with
+ | Paddbint Pint64 -> make_const_int64 (Int64.add n1 n2)
+ | Psubbint Pint64 -> make_const_int64 (Int64.sub n1 n2)
+ | Pmulbint Pint64 -> make_const_int64 (Int64.mul n1 n2)
+ | Pdivbint Pint64 when n2 <> 0L -> make_const_int64 (Int64.div n1 n2)
+ | Pmodbint Pint64 when n2 <> 0L -> make_const_int64 (Int64.rem n1 n2)
+ | Pandbint Pint64 -> make_const_int64 (Int64.logand n1 n2)
+ | Porbint Pint64 -> make_const_int64 (Int64.logor n1 n2)
+ | Pxorbint Pint64 -> make_const_int64 (Int64.logxor n1 n2)
+ | Pbintcomp(Pint64, c) -> make_comparison c n1 n2
+ | _ -> default
+ end
+ (* int64, int *)
+ | [Value_const(Uconst_ref(_, Uconst_int64 n1));
+ Value_const(Uconst_int n2)] ->
+ begin match p with
+ | Plslbint Pint64 when 0 <= n2 && n2 < 64 ->
+ make_const_int64 (Int64.shift_left n1 n2)
+ | Plsrbint Pint64 when 0 <= n2 && n2 < 64 ->
+ make_const_int64 (Int64.shift_right_logical n1 n2)
+ | Pasrbint Pint64 when 0 <= n2 && n2 < 64 ->
+ make_const_int64 (Int64.shift_right n1 n2)
+ | _ -> default
+ end
+ (* TODO: Pbbswap *)
+ (* Catch-all *)
+ | _ ->
+ default
+
+let field_approx n = function
+ | Value_tuple a when n < Array.length a -> a.(n)
+ | Value_const (Uconst_ref(_, Uconst_block(_, l))) when n < List.length l ->
+ Value_const (List.nth l n)
+ | _ -> Value_unknown
+
+let simplif_prim_pure fpc p (args, approxs) dbg =
+ match p, args, approxs with
+ (* Block construction *)
+ | Pmakeblock(tag, Immutable), _, _ ->
+ let field = function
+ | Value_const c -> c
+ | _ -> raise Exit
+ in
+ begin try
+ let cst = Uconst_block (tag, List.map field approxs) in
+ let name =
+ Compilenv.new_structured_constant cst ~shared:true
+ in
+ make_const (Uconst_ref (name, cst))
+ with Exit ->
+ (Uprim(p, args, dbg), Value_tuple (Array.of_list approxs))
+ end
+ (* Field access *)
+ | Pfield n, _, [ Value_const(Uconst_ref(_, Uconst_block(_, l))) ]
+ when n < List.length l ->
+ make_const (List.nth l n)
+ | Pfield n, [ Uprim(Pmakeblock _, ul, _) ], [approx]
+ when n < List.length ul ->
+ (List.nth ul n, field_approx n approx)
+ (* Strings *)
+ | Pstringlength, _, [ Value_const(Uconst_ref(_, Uconst_string s)) ] ->
+ make_const_int (String.length s)
+ (* Identity *)
+ | Pidentity, [arg1], [app1] ->
+ (arg1, app1)
+ (* Kind test *)
+ | Pisint, _, [a1] ->
+ begin match a1 with
+ | Value_const(Uconst_int _ | Uconst_ptr _) -> make_const_bool true
+ | Value_const(Uconst_ref _) -> make_const_bool false
+ | Value_closure _ | Value_tuple _ -> make_const_bool false
+ | _ -> (Uprim(p, args, dbg), Value_unknown)
+ end
+ (* Compile-time constants *)
+ | Pctconst c, _, _ ->
+ begin match c with
+ | Big_endian -> make_const_bool Arch.big_endian
+ | Word_size -> make_const_int (8*Arch.size_int)
+ | Int_size -> make_const_int (8*Arch.size_int - 1)
+ | Max_wosize -> make_const_int ((1 lsl ((8*Arch.size_int) - 10)) - 1 )
+ | Ostype_unix -> make_const_bool (Sys.os_type = "Unix")
+ | Ostype_win32 -> make_const_bool (Sys.os_type = "Win32")
+ | Ostype_cygwin -> make_const_bool (Sys.os_type = "Cygwin")
+ end
+ (* Catch-all *)
+ | _ ->
+ simplif_arith_prim_pure fpc p (args, approxs) dbg
+
+let simplif_prim fpc p (args, approxs as args_approxs) dbg =
+ if List.for_all is_pure_clambda args
+ then simplif_prim_pure fpc p args_approxs dbg
+ else
+ (* XXX : always return the same approxs as simplif_prim_pure? *)
+ let approx =
+ match p with
+ | Pmakeblock(_, Immutable) ->
+ Value_tuple (Array.of_list approxs)
+ | _ ->
+ Value_unknown
+ in
+ (Uprim(p, args, dbg), approx)
+
+(* Substitute variables in a [ulambda] term (a body of an inlined function)
+ and perform some more simplifications on integer primitives.
+ Also perform alpha-conversion on let-bound identifiers to avoid
+ clashes with locally-generated identifiers.
+ The variables must not be assigned in the term.
+ This is used to substitute "trivial" arguments for parameters
+ during inline expansion, and also for the translation of let rec
+ over functions. *)
+
+let approx_ulam = function
+ Uconst c -> Value_const c
+ | _ -> Value_unknown
+
+let find_action idxs acts tag =
+ if 0 <= tag && tag < Array.length idxs then begin
+ let idx = idxs.(tag) in
+ assert(0 <= idx && idx < Array.length acts);
+ Some acts.(idx)
+ end else
+ (* Can this happen? *)
+ None
+
+
+let rec substitute fpc sb ulam =
+ match ulam with
+ Uvar v ->
+ begin try Tbl.find v sb with Not_found -> ulam end
+ | Uconst _ -> ulam
+ | Udirect_apply(lbl, args, dbg) ->
+ Udirect_apply(lbl, List.map (substitute fpc sb) args, dbg)
+ | Ugeneric_apply(fn, args, dbg) ->
+ Ugeneric_apply(substitute fpc sb fn,
+ List.map (substitute fpc sb) args, dbg)
+ | Uclosure(defs, env) ->
+ (* Question: should we rename function labels as well? Otherwise,
+ there is a risk that function labels are not globally unique.
+ This should not happen in the current system because:
+ - Inlined function bodies contain no Uclosure nodes
+ (cf. function [lambda_smaller])
+ - When we substitute offsets for idents bound by let rec
+ in [close], case [Lletrec], we discard the original
+ let rec body and use only the substituted term. *)
+ Uclosure(defs, List.map (substitute fpc sb) env)
+ | Uoffset(u, ofs) -> Uoffset(substitute fpc sb u, ofs)
+ | Ulet(id, u1, u2) ->
+ let id' = Ident.rename id in
+ Ulet(id', substitute fpc sb u1,
+ substitute fpc (Tbl.add id (Uvar id') sb) u2)
+ | Uletrec(bindings, body) ->
+ let bindings1 =
+ List.map (fun (id, rhs) -> (id, Ident.rename id, rhs)) bindings in
+ let sb' =
+ List.fold_right
+ (fun (id, id', _) s -> Tbl.add id (Uvar id') s)
+ bindings1 sb in
+ Uletrec(
+ List.map
+ (fun (id, id', rhs) -> (id', substitute fpc sb' rhs))
+ bindings1,
+ substitute fpc sb' body)
+ | Uprim(p, args, dbg) ->
+ let sargs =
+ List.map (substitute fpc sb) args in
+ let (res, _) =
+ simplif_prim fpc p (sargs, List.map approx_ulam sargs) dbg in
+ res
+ | Uswitch(arg, sw) ->
+ let sarg = substitute fpc sb arg in
+ let action =
+ (* Unfortunately, we cannot easily deal with the
+ case of a constructed block (makeblock) bound to a local
+ identifier. This would require to keep track of
+ local let bindings (at least their approximations)
+ in this substitute function.
+ *)
+ match sarg with
+ | Uconst (Uconst_ref (_, Uconst_block (tag, _))) ->
+ find_action sw.us_index_blocks sw.us_actions_blocks tag
+ | Uconst (Uconst_ptr tag) ->
+ find_action sw.us_index_consts sw.us_actions_consts tag
+ | _ -> None
+ in
+ begin match action with
+ | Some u -> substitute fpc sb u
+ | None ->
+ Uswitch(sarg,
+ { sw with
+ us_actions_consts =
+ Array.map (substitute fpc sb) sw.us_actions_consts;
+ us_actions_blocks =
+ Array.map (substitute fpc sb) sw.us_actions_blocks;
+ })
+ end
+ | Ustringswitch(arg,sw,d) ->
+ Ustringswitch
+ (substitute fpc sb arg,
+ List.map (fun (s,act) -> s,substitute fpc sb act) sw,
+ Misc.may_map (substitute fpc sb) d)
+ | Ustaticfail (nfail, args) ->
+ Ustaticfail (nfail, List.map (substitute fpc sb) args)
+ | Ucatch(nfail, ids, u1, u2) ->
+ Ucatch(nfail, ids, substitute fpc sb u1, substitute fpc sb u2)
+ | Utrywith(u1, id, u2) ->
+ let id' = Ident.rename id in
+ Utrywith(substitute fpc sb u1, id',
+ substitute fpc (Tbl.add id (Uvar id') sb) u2)
+ | Uifthenelse(u1, u2, u3) ->
+ begin match substitute fpc sb u1 with
+ Uconst (Uconst_ptr n) ->
+ if n <> 0 then substitute fpc sb u2 else substitute fpc sb u3
+ | Uprim(Pmakeblock _, _, _) ->
+ substitute fpc sb u2
+ | su1 ->
+ Uifthenelse(su1, substitute fpc sb u2, substitute fpc sb u3)
+ end
+ | Usequence(u1, u2) ->
+ Usequence(substitute fpc sb u1, substitute fpc sb u2)
+ | Uwhile(u1, u2) ->
+ Uwhile(substitute fpc sb u1, substitute fpc sb u2)
+ | Ufor(id, u1, u2, dir, u3) ->
+ let id' = Ident.rename id in
+ Ufor(id', substitute fpc sb u1, substitute fpc sb u2, dir,
+ substitute fpc (Tbl.add id (Uvar id') sb) u3)
+ | Uassign(id, u) ->
+ let id' =
+ try
+ match Tbl.find id sb with Uvar i -> i | _ -> assert false
+ with Not_found ->
+ id in
+ Uassign(id', substitute fpc sb u)
+ | Usend(k, u1, u2, ul, dbg) ->
+ Usend(k, substitute fpc sb u1, substitute fpc sb u2,
+ List.map (substitute fpc sb) ul, dbg)
+
+(* Perform an inline expansion *)
+
+let is_simple_argument = function
+ | Uvar _ | Uconst _ -> true
+ | _ -> false
+
+let no_effects = function
+ | Uclosure _ -> true
+ | u -> is_simple_argument u
+
+let rec bind_params_rec fpc subst params args body =
+ match (params, args) with
+ ([], []) -> substitute fpc subst body
+ | (p1 :: pl, a1 :: al) ->
+ if is_simple_argument a1 then
+ bind_params_rec fpc (Tbl.add p1 a1 subst) pl al body
+ else begin
+ let p1' = Ident.rename p1 in
+ let u1, u2 =
+ match Ident.name p1, a1 with
+ | "*opt*", Uprim(Pmakeblock(0, Immutable), [a], dbg) ->
+ a, Uprim(Pmakeblock(0, Immutable), [Uvar p1'], dbg)
+ | _ ->
+ a1, Uvar p1'
+ in
+ let body' =
+ bind_params_rec fpc (Tbl.add p1 u2 subst) pl al body in
+ if occurs_var p1 body then Ulet(p1', u1, body')
+ else if no_effects a1 then body'
+ else Usequence(a1, body')
+ end
+ | (_, _) -> assert false
+
+let bind_params fpc params args body =
+ (* Reverse parameters and arguments to preserve right-to-left
+ evaluation order (PR#2910). *)
+ bind_params_rec fpc Tbl.empty (List.rev params) (List.rev args) body
+
+(* Check if a lambda term is ``pure'',
+ that is without side-effects *and* not containing function definitions *)
+
+let rec is_pure = function
+ Lvar v -> true
+ | Lconst cst -> true
+ | Lprim((Psetglobal _ | Psetfield _ | Psetfloatfield _ | Pduprecord _ |
+ Pccall _ | Praise _ | Poffsetref _ | Pstringsetu | Pstringsets |
+ Parraysetu _ | Parraysets _ | Pbigarrayset _), _) -> false
+ | Lprim(p, args) -> List.for_all is_pure args
+ | Levent(lam, ev) -> is_pure lam
+ | _ -> false
+
+(* Generate a direct application *)
+
+let direct_apply fundesc funct ufunct uargs =
+ let app_args =
+ if fundesc.fun_closed then uargs else uargs @ [ufunct] in
+ let app =
+ match fundesc.fun_inline with
+ | None ->
+ Udirect_apply(fundesc.fun_label, app_args, Debuginfo.none)
+ | Some(params, body) ->
+ bind_params fundesc.fun_float_const_prop params app_args body in
+ (* If ufunct can contain side-effects or function definitions,
+ we must make sure that it is evaluated exactly once.
+ If the function is not closed, we evaluate ufunct as part of the
+ arguments.
+ If the function is closed, we force the evaluation of ufunct first. *)
+ if not fundesc.fun_closed || is_pure funct
+ then app
+ else Usequence(ufunct, app)
+
+(* Add [Value_integer] or [Value_constptr] info to the approximation
+ of an application *)
+
+let strengthen_approx appl approx =
+ match approx_ulam appl with
+ (Value_const _) as intapprox ->
+ intapprox
+ | _ -> approx
+
+(* If a term has approximation Value_integer or Value_constptr and is pure,
+ replace it by an integer constant *)
+
+let check_constant_result lam ulam approx =
+ match approx with
+ Value_const c when is_pure lam -> make_const c
+ | Value_global_field (id, i) when is_pure lam ->
+ begin match ulam with
+ | Uprim(Pfield _, [Uprim(Pgetglobal _, _, _)], _) -> (ulam, approx)
+ | _ ->
+ let glb =
+ Uprim(Pgetglobal (Ident.create_persistent id), [], Debuginfo.none)
+ in
+ Uprim(Pfield i, [glb], Debuginfo.none), approx
+ end
+ | _ -> (ulam, approx)
+
+(* Evaluate an expression with known value for its side effects only,
+ or discard it if it's pure *)
+
+let sequence_constant_expr lam ulam1 (ulam2, approx2 as res2) =
+ if is_pure lam then res2 else (Usequence(ulam1, ulam2), approx2)
+
+(* Maintain the approximation of the global structure being defined *)
+
+let global_approx = ref([||] : value_approximation array)
+
+(* Maintain the nesting depth for functions *)
+
+let function_nesting_depth = ref 0
+let excessive_function_nesting_depth = 5
+
+(* Decorate clambda term with debug information *)
+
+let rec add_debug_info ev u =
+ match ev.lev_kind with
+ | Lev_after _ ->
+ begin match u with
+ | Udirect_apply(lbl, args, dinfo) ->
+ Udirect_apply(lbl, args, Debuginfo.from_call ev)
+ | Ugeneric_apply(Udirect_apply(lbl, args1, dinfo1),
+ args2, dinfo2) ->
+ Ugeneric_apply(Udirect_apply(lbl, args1, Debuginfo.from_call ev),
+ args2, Debuginfo.from_call ev)
+ | Ugeneric_apply(fn, args, dinfo) ->
+ Ugeneric_apply(fn, args, Debuginfo.from_call ev)
+ | Uprim(Praise k, args, dinfo) ->
+ Uprim(Praise k, args, Debuginfo.from_call ev)
+ | Uprim(p, args, dinfo) ->
+ Uprim(p, args, Debuginfo.from_call ev)
+ | Usend(kind, u1, u2, args, dinfo) ->
+ Usend(kind, u1, u2, args, Debuginfo.from_call ev)
+ | Usequence(u1, u2) ->
+ Usequence(u1, add_debug_info ev u2)
+ | _ -> u
+ end
+ | _ -> u
+
+(* Uncurry an expression and explicitate closures.
+ Also return the approximation of the expression.
+ The approximation environment [fenv] maps idents to approximations.
+ Idents not bound in [fenv] approximate to [Value_unknown].
+ The closure environment [cenv] maps idents to [ulambda] terms.
+ It is used to substitute environment accesses for free identifiers. *)
+
+exception NotClosed
+
+let close_approx_var fenv cenv id =
+ let approx = try Tbl.find id fenv with Not_found -> Value_unknown in
+ match approx with
+ Value_const c -> make_const c
+ | approx ->
+ let subst = try Tbl.find id cenv with Not_found -> Uvar id in
+ (subst, approx)
+
+let close_var fenv cenv id =
+ let (ulam, app) = close_approx_var fenv cenv id in ulam
+
+let rec close fenv cenv = function
+ Lvar id ->
+ close_approx_var fenv cenv id
+ | Lconst cst ->
+ let str ?(shared = true) cst =
+ let name =
+ Compilenv.new_structured_constant cst ~shared
+ in
+ Uconst_ref (name, cst)
+ in
+ let rec transl = function
+ | Const_base(Const_int n) -> Uconst_int n
+ | Const_base(Const_char c) -> Uconst_int (Char.code c)
+ | Const_pointer n -> Uconst_ptr n
+ | Const_block (tag, fields) ->
+ str (Uconst_block (tag, List.map transl fields))
+ | Const_float_array sl ->
+ (* constant float arrays are really immutable *)
+ str (Uconst_float_array (List.map float_of_string sl))
+ | Const_immstring s ->
+ str (Uconst_string s)
+ | Const_base (Const_string (s, _)) ->
+ (* strings (even literal ones) are mutable! *)
+ (* of course, the empty string is really immutable *)
+ str ~shared:false(*(String.length s = 0)*) (Uconst_string s)
+ | Const_base(Const_float x) -> str (Uconst_float (float_of_string x))
+ | Const_base(Const_int32 x) -> str (Uconst_int32 x)
+ | Const_base(Const_int64 x) -> str (Uconst_int64 x)
+ | Const_base(Const_nativeint x) -> str (Uconst_nativeint x)
+ in
+ make_const (transl cst)
+ | Lfunction{kind; params; body} as funct ->
+ close_one_function fenv cenv (Ident.create "fun") funct
+
+ (* We convert [f a] to [let a' = a in fun b c -> f a' b c]
+ when fun_arity > nargs *)
+ | Lapply(funct, args, {apply_loc=loc}) ->
+ let nargs = List.length args in
+ begin match (close fenv cenv funct, close_list fenv cenv args) with
+ ((ufunct, Value_closure(fundesc, approx_res)),
+ [Uprim(Pmakeblock(_, _), uargs, _)])
+ when List.length uargs = - fundesc.fun_arity ->
+ let app = direct_apply fundesc funct ufunct uargs in
+ (app, strengthen_approx app approx_res)
+ | ((ufunct, Value_closure(fundesc, approx_res)), uargs)
+ when nargs = fundesc.fun_arity ->
+ let app = direct_apply fundesc funct ufunct uargs in
+ (app, strengthen_approx app approx_res)
+
+ | ((ufunct, Value_closure(fundesc, approx_res)), uargs)
+ when nargs < fundesc.fun_arity ->
+ let first_args = List.map (fun arg ->
+ (Ident.create "arg", arg) ) uargs in
+ let final_args =
+ Array.to_list (Array.init (fundesc.fun_arity - nargs)
+ (fun _ -> Ident.create "arg")) in
+ let rec iter args body =
+ match args with
+ [] -> body
+ | (arg1, arg2) :: args ->
+ iter args
+ (Ulet ( arg1, arg2, body))
+ in
+ let internal_args =
+ (List.map (fun (arg1, arg2) -> Lvar arg1) first_args)
+ @ (List.map (fun arg -> Lvar arg ) final_args)
+ in
+ let (new_fun, approx) = close fenv cenv
+ (Lfunction{
+ kind = Curried;
+ params = final_args;
+ body = Lapply(funct, internal_args, mk_apply_info loc)})
+ in
+ let new_fun = iter first_args new_fun in
+ (new_fun, approx)
+
+ | ((ufunct, Value_closure(fundesc, approx_res)), uargs)
+ when fundesc.fun_arity > 0 && nargs > fundesc.fun_arity ->
+ let (first_args, rem_args) = split_list fundesc.fun_arity uargs in
+ (Ugeneric_apply(direct_apply fundesc funct ufunct first_args,
+ rem_args, Debuginfo.none),
+ Value_unknown)
+ | ((ufunct, _), uargs) ->
+ (Ugeneric_apply(ufunct, uargs, Debuginfo.none), Value_unknown)
+ end
+ | Lsend(kind, met, obj, args, _) ->
+ let (umet, _) = close fenv cenv met in
+ let (uobj, _) = close fenv cenv obj in
+ (Usend(kind, umet, uobj, close_list fenv cenv args, Debuginfo.none),
+ Value_unknown)
+ | Llet(str, id, lam, body) ->
+ let (ulam, alam) = close_named fenv cenv id lam in
+ begin match (str, alam) with
+ (Variable, _) ->
+ let (ubody, abody) = close fenv cenv body in
+ (Ulet(id, ulam, ubody), abody)
+ | (_, Value_const _)
+ when str = Alias || is_pure lam ->
+ close (Tbl.add id alam fenv) cenv body
+ | (_, _) ->
+ let (ubody, abody) = close (Tbl.add id alam fenv) cenv body in
+ (Ulet(id, ulam, ubody), abody)
+ end
+ | Lletrec(defs, body) ->
+ if List.for_all
+ (function (id, Lfunction _) -> true | _ -> false)
+ defs
+ then begin
+ (* Simple case: only function definitions *)
+ let (clos, infos) = close_functions fenv cenv defs in
+ let clos_ident = Ident.create "clos" in
+ let fenv_body =
+ List.fold_right
+ (fun (id, pos, approx) fenv -> Tbl.add id approx fenv)
+ infos fenv in
+ let (ubody, approx) = close fenv_body cenv body in
+ let sb =
+ List.fold_right
+ (fun (id, pos, approx) sb ->
+ Tbl.add id (Uoffset(Uvar clos_ident, pos)) sb)
+ infos Tbl.empty in
+ (Ulet(clos_ident, clos, substitute !Clflags.float_const_prop sb ubody),
+ approx)
+ end else begin
+ (* General case: recursive definition of values *)
+ let rec clos_defs = function
+ [] -> ([], fenv)
+ | (id, lam) :: rem ->
+ let (udefs, fenv_body) = clos_defs rem in
+ let (ulam, approx) = close_named fenv cenv id lam in
+ ((id, ulam) :: udefs, Tbl.add id approx fenv_body) in
+ let (udefs, fenv_body) = clos_defs defs in
+ let (ubody, approx) = close fenv_body cenv body in
+ (Uletrec(udefs, ubody), approx)
+ end
+ | Lprim(Pdirapply loc,[funct;arg])
+ | Lprim(Prevapply loc,[arg;funct]) ->
+ close fenv cenv (Lapply(funct, [arg], mk_apply_info loc))
+ | Lprim(Pgetglobal id, []) as lam ->
+ check_constant_result lam
+ (getglobal id)
+ (Compilenv.global_approx id)
+ | Lprim(Pfield n, [lam]) ->
+ let (ulam, approx) = close fenv cenv lam in
+ check_constant_result lam (Uprim(Pfield n, [ulam], Debuginfo.none))
+ (field_approx n approx)
+ | Lprim(Psetfield(n, _), [Lprim(Pgetglobal id, []); lam]) ->
+ let (ulam, approx) = close fenv cenv lam in
+ if approx <> Value_unknown then
+ (!global_approx).(n) <- approx;
+ (Uprim(Psetfield(n, false), [getglobal id; ulam], Debuginfo.none),
+ Value_unknown)
+ | Lprim(Praise k, [Levent(arg, ev)]) ->
+ let (ulam, approx) = close fenv cenv arg in
+ (Uprim(Praise k, [ulam], Debuginfo.from_raise ev),
+ Value_unknown)
+ | Lprim(p, args) ->
+ simplif_prim !Clflags.float_const_prop
+ p (close_list_approx fenv cenv args) Debuginfo.none
+ | Lswitch(arg, sw) ->
+ let fn fail =
+ let (uarg, _) = close fenv cenv arg in
+ let const_index, const_actions, fconst =
+ close_switch arg fenv cenv sw.sw_consts sw.sw_numconsts fail
+ and block_index, block_actions, fblock =
+ close_switch arg fenv cenv sw.sw_blocks sw.sw_numblocks fail in
+ let ulam =
+ Uswitch
+ (uarg,
+ {us_index_consts = const_index;
+ us_actions_consts = const_actions;
+ us_index_blocks = block_index;
+ us_actions_blocks = block_actions}) in
+ (fconst (fblock ulam),Value_unknown) in
+(* NB: failaction might get copied, thus it should be some Lstaticraise *)
+ let fail = sw.sw_failaction in
+ begin match fail with
+ | None|Some (Lstaticraise (_,_)) -> fn fail
+ | Some lamfail ->
+ if
+ (sw.sw_numconsts - List.length sw.sw_consts) +
+ (sw.sw_numblocks - List.length sw.sw_blocks) > 1
+ then
+ let i = next_raise_count () in
+ let ubody,_ = fn (Some (Lstaticraise (i,[])))
+ and uhandler,_ = close fenv cenv lamfail in
+ Ucatch (i,[],ubody,uhandler),Value_unknown
+ else fn fail
+ end
+ | Lstringswitch(arg,sw,d) ->
+ let uarg,_ = close fenv cenv arg in
+ let usw =
+ List.map
+ (fun (s,act) ->
+ let uact,_ = close fenv cenv act in
+ s,uact)
+ sw in
+ let ud =
+ Misc.may_map
+ (fun d ->
+ let ud,_ = close fenv cenv d in
+ ud) d in
+ Ustringswitch (uarg,usw,ud),Value_unknown
+ | Lstaticraise (i, args) ->
+ (Ustaticfail (i, close_list fenv cenv args), Value_unknown)
+ | Lstaticcatch(body, (i, vars), handler) ->
+ let (ubody, _) = close fenv cenv body in
+ let (uhandler, _) = close fenv cenv handler in
+ (Ucatch(i, vars, ubody, uhandler), Value_unknown)
+ | Ltrywith(body, id, handler) ->
+ let (ubody, _) = close fenv cenv body in
+ let (uhandler, _) = close fenv cenv handler in
+ (Utrywith(ubody, id, uhandler), Value_unknown)
+ | Lifthenelse(arg, ifso, ifnot) ->
+ begin match close fenv cenv arg with
+ (uarg, Value_const (Uconst_ptr n)) ->
+ sequence_constant_expr arg uarg
+ (close fenv cenv (if n = 0 then ifnot else ifso))
+ | (uarg, _ ) ->
+ let (uifso, _) = close fenv cenv ifso in
+ let (uifnot, _) = close fenv cenv ifnot in
+ (Uifthenelse(uarg, uifso, uifnot), Value_unknown)
+ end
+ | Lsequence(lam1, lam2) ->
+ let (ulam1, _) = close fenv cenv lam1 in
+ let (ulam2, approx) = close fenv cenv lam2 in
+ (Usequence(ulam1, ulam2), approx)
+ | Lwhile(cond, body) ->
+ let (ucond, _) = close fenv cenv cond in
+ let (ubody, _) = close fenv cenv body in
+ (Uwhile(ucond, ubody), Value_unknown)
+ | Lfor(id, lo, hi, dir, body) ->
+ let (ulo, _) = close fenv cenv lo in
+ let (uhi, _) = close fenv cenv hi in
+ let (ubody, _) = close fenv cenv body in
+ (Ufor(id, ulo, uhi, dir, ubody), Value_unknown)
+ | Lassign(id, lam) ->
+ let (ulam, _) = close fenv cenv lam in
+ (Uassign(id, ulam), Value_unknown)
+ | Levent(lam, ev) ->
+ let (ulam, approx) = close fenv cenv lam in
+ (add_debug_info ev ulam, approx)
+ | Lifused _ ->
+ assert false
+
+and close_list fenv cenv = function
+ [] -> []
+ | lam :: rem ->
+ let (ulam, _) = close fenv cenv lam in
+ ulam :: close_list fenv cenv rem
+
+and close_list_approx fenv cenv = function
+ [] -> ([], [])
+ | lam :: rem ->
+ let (ulam, approx) = close fenv cenv lam in
+ let (ulams, approxs) = close_list_approx fenv cenv rem in
+ (ulam :: ulams, approx :: approxs)
+
+and close_named fenv cenv id = function
+ Lfunction{kind; params; body} as funct ->
+ close_one_function fenv cenv id funct
+ | lam ->
+ close fenv cenv lam
+
+(* Build a shared closure for a set of mutually recursive functions *)
+
+and close_functions fenv cenv fun_defs =
+ let fun_defs =
+ List.flatten
+ (List.map
+ (function
+ | (id, Lfunction{kind; params; body}) ->
+ split_default_wrapper id kind params body
+ | _ -> assert false
+ )
+ fun_defs)
+ in
+
+ (* Update and check nesting depth *)
+ incr function_nesting_depth;
+ let initially_closed =
+ !function_nesting_depth < excessive_function_nesting_depth in
+ (* Determine the free variables of the functions *)
+ let fv =
+ IdentSet.elements (free_variables (Lletrec(fun_defs, lambda_unit))) in
+ (* Build the function descriptors for the functions.
+ Initially all functions are assumed not to need their environment
+ parameter. *)
+ let uncurried_defs =
+ List.map
+ (function
+ (id, Lfunction{kind; params; body}) ->
+ let label = Compilenv.make_symbol (Some (Ident.unique_name id)) in
+ let arity = List.length params in
+ let fundesc =
+ {fun_label = label;
+ fun_arity = (if kind = Tupled then -arity else arity);
+ fun_closed = initially_closed;
+ fun_inline = None;
+ fun_float_const_prop = !Clflags.float_const_prop } in
+ (id, params, body, fundesc)
+ | (_, _) -> fatal_error "Closure.close_functions")
+ fun_defs in
+ (* Build an approximate fenv for compiling the functions *)
+ let fenv_rec =
+ List.fold_right
+ (fun (id, params, body, fundesc) fenv ->
+ Tbl.add id (Value_closure(fundesc, Value_unknown)) fenv)
+ uncurried_defs fenv in
+ (* Determine the offsets of each function's closure in the shared block *)
+ let env_pos = ref (-1) in
+ let clos_offsets =
+ List.map
+ (fun (id, params, body, fundesc) ->
+ let pos = !env_pos + 1 in
+ env_pos := !env_pos + 1 + (if fundesc.fun_arity <> 1 then 3 else 2);
+ pos)
+ uncurried_defs in
+ let fv_pos = !env_pos in
+ (* This reference will be set to false if the hypothesis that a function
+ does not use its environment parameter is invalidated. *)
+ let useless_env = ref initially_closed in
+ (* Translate each function definition *)
+ let clos_fundef (id, params, body, fundesc) env_pos =
+ let dbg = match body with
+ | Levent (_,({lev_kind=Lev_function} as ev)) -> Debuginfo.from_call ev
+ | _ -> Debuginfo.none in
+ let env_param = Ident.create "env" in
+ let cenv_fv =
+ build_closure_env env_param (fv_pos - env_pos) fv in
+ let cenv_body =
+ List.fold_right2
+ (fun (id, params, body, fundesc) pos env ->
+ Tbl.add id (Uoffset(Uvar env_param, pos - env_pos)) env)
+ uncurried_defs clos_offsets cenv_fv in
+ let (ubody, approx) = close fenv_rec cenv_body body in
+ if !useless_env && occurs_var env_param ubody then raise NotClosed;
+ let fun_params = if !useless_env then params else params @ [env_param] in
+ let f =
+ {
+ label = fundesc.fun_label;
+ arity = fundesc.fun_arity;
+ params = fun_params;
+ body = ubody;
+ dbg;
+ }
+ in
+ (* give more chance of function with default parameters (i.e.
+ their wrapper functions) to be inlined *)
+ let n =
+ List.fold_left
+ (fun n id -> n + if Ident.name id = "*opt*" then 8 else 1)
+ 0
+ fun_params
+ in
+ if lambda_smaller ubody
+ (!Clflags.inline_threshold + n)
+ then fundesc.fun_inline <- Some(fun_params, ubody);
+
+ (f, (id, env_pos, Value_closure(fundesc, approx))) in
+ (* Translate all function definitions. *)
+ let clos_info_list =
+ if initially_closed then begin
+ let snap = Compilenv.snapshot () in
+ try List.map2 clos_fundef uncurried_defs clos_offsets
+ with NotClosed ->
+ (* If the hypothesis that the environment parameters are useless has been
+ invalidated, then set [fun_closed] to false in all descriptions and
+ recompile *)
+ Compilenv.backtrack snap; (* PR#6337 *)
+ List.iter
+ (fun (id, params, body, fundesc) ->
+ fundesc.fun_closed <- false;
+ fundesc.fun_inline <- None;
+ )
+ uncurried_defs;
+ useless_env := false;
+ List.map2 clos_fundef uncurried_defs clos_offsets
+ end else
+ (* Excessive closure nesting: assume environment parameter is used *)
+ List.map2 clos_fundef uncurried_defs clos_offsets
+ in
+ (* Update nesting depth *)
+ decr function_nesting_depth;
+ (* Return the Uclosure node and the list of all identifiers defined,
+ with offsets and approximations. *)
+ let (clos, infos) = List.split clos_info_list in
+ let fv = if !useless_env then [] else fv in
+ (Uclosure(clos, List.map (close_var fenv cenv) fv), infos)
+
+(* Same, for one non-recursive function *)
+
+and close_one_function fenv cenv id funct =
+ match close_functions fenv cenv [id, funct] with
+ | (clos, (i, _, approx) :: _) when id = i -> (clos, approx)
+ | _ -> fatal_error "Closure.close_one_function"
+
+(* Close a switch *)
+
+and close_switch arg fenv cenv cases num_keys default =
+ let ncases = List.length cases in
+ let index = Array.make num_keys 0
+ and store = Storer.mk_store () in
+
+ (* First default case *)
+ begin match default with
+ | Some def when ncases < num_keys ->
+ assert (store.act_store def = 0)
+ | _ -> ()
+ end ;
+ (* Then all other cases *)
+ List.iter
+ (fun (key,lam) ->
+ index.(key) <- store.act_store lam)
+ cases ;
+
+ (* Explicit sharing with catch/exit, as switcher compilation may
+ later unshare *)
+ let acts = store.act_get_shared () in
+ let hs = ref (fun e -> e) in
+
+ (* Compile actions *)
+ let actions =
+ Array.map
+ (function
+ | Single lam|Shared (Lstaticraise (_,[]) as lam) ->
+ let ulam,_ = close fenv cenv lam in
+ ulam
+ | Shared lam ->
+ let ulam,_ = close fenv cenv lam in
+ let i = next_raise_count () in
+(*
+ let string_of_lambda e =
+ Printlambda.lambda Format.str_formatter e ;
+ Format.flush_str_formatter () in
+ Printf.eprintf "SHARE CLOSURE %i [%s]\n%s\n" i
+ (string_of_lambda arg)
+ (string_of_lambda lam) ;
+*)
+ let ohs = !hs in
+ hs := (fun e -> Ucatch (i,[],ohs e,ulam)) ;
+ Ustaticfail (i,[]))
+ acts in
+ match actions with
+ | [| |] -> [| |], [| |], !hs (* May happen when default is None *)
+ | _ -> index, actions, !hs
+
+
+(* Collect exported symbols for structured constants *)
+
+let collect_exported_structured_constants a =
+ let rec approx = function
+ | Value_closure (fd, a) ->
+ approx a;
+ begin match fd.fun_inline with
+ | Some (_, u) -> ulam u
+ | None -> ()
+ end
+ | Value_tuple a -> Array.iter approx a
+ | Value_const c -> const c
+ | Value_unknown | Value_global_field _ -> ()
+ and const = function
+ | Uconst_ref (s, c) ->
+ Compilenv.add_exported_constant s;
+ structured_constant c
+ | Uconst_int _ | Uconst_ptr _ -> ()
+ and structured_constant = function
+ | Uconst_block (_, ul) -> List.iter const ul
+ | Uconst_float _ | Uconst_int32 _
+ | Uconst_int64 _ | Uconst_nativeint _
+ | Uconst_float_array _ | Uconst_string _ -> ()
+ and ulam = function
+ | Uvar _ -> ()
+ | Uconst c -> const c
+ | Udirect_apply (_, ul, _) -> List.iter ulam ul
+ | Ugeneric_apply (u, ul, _) -> ulam u; List.iter ulam ul
+ | Uclosure (fl, ul) ->
+ List.iter (fun f -> ulam f.body) fl;
+ List.iter ulam ul
+ | Uoffset(u, _) -> ulam u
+ | Ulet (_, u1, u2) -> ulam u1; ulam u2
+ | Uletrec (l, u) -> List.iter (fun (_, u) -> ulam u) l; ulam u
+ | Uprim (_, ul, _) -> List.iter ulam ul
+ | Uswitch (u, sl) ->
+ ulam u;
+ Array.iter ulam sl.us_actions_consts;
+ Array.iter ulam sl.us_actions_blocks
+ | Ustringswitch (u,sw,d) ->
+ ulam u ;
+ List.iter (fun (_,act) -> ulam act) sw ;
+ Misc.may ulam d
+ | Ustaticfail (_, ul) -> List.iter ulam ul
+ | Ucatch (_, _, u1, u2)
+ | Utrywith (u1, _, u2)
+ | Usequence (u1, u2)
+ | Uwhile (u1, u2) -> ulam u1; ulam u2
+ | Uifthenelse (u1, u2, u3)
+ | Ufor (_, u1, u2, _, u3) -> ulam u1; ulam u2; ulam u3
+ | Uassign (_, u) -> ulam u
+ | Usend (_, u1, u2, ul, _) -> ulam u1; ulam u2; List.iter ulam ul
+ in
+ approx a
+
+let reset () =
+ global_approx := [||];
+ function_nesting_depth := 0
+
+(* The entry point *)
+
+let intro size lam =
+ reset ();
+ let id = Compilenv.make_symbol None in
+ global_approx := Array.init size (fun i -> Value_global_field (id, i));
+ Compilenv.set_global_approx(Value_tuple !global_approx);
+ let (ulam, approx) = close Tbl.empty Tbl.empty lam in
+ if !Clflags.opaque
+ then Compilenv.set_global_approx(Value_unknown)
+ else collect_exported_structured_constants (Value_tuple !global_approx);
+ global_approx := [||];
+ ulam
diff --git a/asmcomp/closure.mli b/asmcomp/closure.mli
new file mode 100644
index 0000000000..2db6e16336
--- /dev/null
+++ b/asmcomp/closure.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Introduction of closures, uncurrying, recognition of direct calls *)
+
+val intro: int -> Lambda.lambda -> Clambda.ulambda
+val reset : unit -> unit
diff --git a/asmcomp/cmm.ml b/asmcomp/cmm.ml
new file mode 100644
index 0000000000..52cd1e5db4
--- /dev/null
+++ b/asmcomp/cmm.ml
@@ -0,0 +1,134 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type machtype_component =
+ | Val
+ | Addr
+ | Int
+ | Float
+
+type machtype = machtype_component array
+
+let typ_void = ([||] : machtype_component array)
+let typ_val = [|Val|]
+let typ_addr = [|Addr|]
+let typ_int = [|Int|]
+let typ_float = [|Float|]
+
+let size_component = function
+ | Val | Addr -> Arch.size_addr
+ | Int -> Arch.size_int
+ | Float -> Arch.size_float
+
+let size_machtype mty =
+ let size = ref 0 in
+ for i = 0 to Array.length mty - 1 do
+ size := !size + size_component mty.(i)
+ done;
+ !size
+
+type comparison =
+ Ceq
+ | Cne
+ | Clt
+ | Cle
+ | Cgt
+ | Cge
+
+let negate_comparison = function
+ Ceq -> Cne | Cne -> Ceq
+ | Clt -> Cge | Cle -> Cgt
+ | Cgt -> Cle | Cge -> Clt
+
+let swap_comparison = function
+ Ceq -> Ceq | Cne -> Cne
+ | Clt -> Cgt | Cle -> Cge
+ | Cgt -> Clt | Cge -> Cle
+
+type memory_chunk =
+ Byte_unsigned
+ | Byte_signed
+ | Sixteen_unsigned
+ | Sixteen_signed
+ | Thirtytwo_unsigned
+ | Thirtytwo_signed
+ | Word_int
+ | Word_val
+ | Single
+ | Double
+ | Double_u
+
+type operation =
+ Capply of machtype * Debuginfo.t
+ | Cextcall of string * machtype * bool * Debuginfo.t
+ | Cload of memory_chunk
+ | Calloc
+ | Cstore of memory_chunk
+ | Caddi | Csubi | Cmuli | Cmulhi | Cdivi | Cmodi
+ | Cand | Cor | Cxor | Clsl | Clsr | Casr
+ | Ccmpi of comparison
+ | Caddv | Cadda
+ | Ccmpa of comparison
+ | Cnegf | Cabsf
+ | Caddf | Csubf | Cmulf | Cdivf
+ | Cfloatofint | Cintoffloat
+ | Ccmpf of comparison
+ | Craise of Lambda.raise_kind * Debuginfo.t
+ | Ccheckbound of Debuginfo.t
+
+type expression =
+ Cconst_int of int
+ | Cconst_natint of nativeint
+ | Cconst_float of float
+ | Cconst_symbol of string
+ | Cconst_pointer of int
+ | Cconst_natpointer of nativeint
+ | Cconst_blockheader of nativeint
+ | Cvar of Ident.t
+ | Clet of Ident.t * expression * expression
+ | Cassign of Ident.t * expression
+ | Ctuple of expression list
+ | Cop of operation * expression list
+ | Csequence of expression * expression
+ | Cifthenelse of expression * expression * expression
+ | Cswitch of expression * int array * expression array
+ | Cloop of expression
+ | Ccatch of int * Ident.t list * expression * expression
+ | Cexit of int * expression list
+ | Ctrywith of expression * Ident.t * expression
+
+type fundecl =
+ { fun_name: string;
+ fun_args: (Ident.t * machtype) list;
+ fun_body: expression;
+ fun_fast: bool;
+ fun_dbg : Debuginfo.t; }
+
+type data_item =
+ Cdefine_symbol of string
+ | Cdefine_label of int
+ | Cglobal_symbol of string
+ | Cint8 of int
+ | Cint16 of int
+ | Cint32 of nativeint
+ | Cint of nativeint
+ | Csingle of float
+ | Cdouble of float
+ | Csymbol_address of string
+ | Clabel_address of int
+ | Cstring of string
+ | Cskip of int
+ | Calign of int
+
+type phrase =
+ Cfunction of fundecl
+ | Cdata of data_item list
diff --git a/asmcomp/cmm.mli b/asmcomp/cmm.mli
new file mode 100644
index 0000000000..202dbb57e6
--- /dev/null
+++ b/asmcomp/cmm.mli
@@ -0,0 +1,147 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Second intermediate language (machine independent) *)
+
+type machtype_component =
+ | Val
+ | Addr
+ | Int
+ | Float
+
+(* - [Val] denotes a valid OCaml value: either a pointer to the beginning
+ of a heap block, an infix pointer if it is preceded by the correct
+ infix header, or a 2n+1 encoded integer.
+ - [Int] is for integers (not necessarily 2n+1 encoded) and for
+ pointers outside the heap.
+ - [Addr] denotes pointers that are neither [Val] nor [Int], i.e.
+ pointers into the heap that point in the middle of a heap block.
+ Such derived pointers are produced by e.g. array indexing.
+ - [Float] is for unboxed floating-point numbers.
+
+The purpose of these types is twofold. First, they guide register
+allocation: type [Float] goes in FP registers, the other types go
+into integer registers. Second, they determine how local variables are
+tracked by the GC:
+ - Variables of type [Val] are GC roots. If they are pointers, the
+ GC will not deallocate the addressed heap block, and will update
+ the local variable if the heap block moves.
+ - Variables of type [Int] and [Float] are ignored by the GC.
+ The GC does not change their values.
+ - Variables of type [Addr] must never be live across an allocation
+ point or function call. They cannot be given as roots to the GC
+ because they don't point after a well-formed block header of the
+ kind that the GC needs. However, the GC may move the block pointed
+ into, invalidating the value of the [Addr] variable.
+*)
+
+type machtype = machtype_component array
+
+val typ_void: machtype
+val typ_val: machtype
+val typ_addr: machtype
+val typ_int: machtype
+val typ_float: machtype
+
+val size_component: machtype_component -> int
+val size_machtype: machtype -> int
+
+type comparison =
+ Ceq
+ | Cne
+ | Clt
+ | Cle
+ | Cgt
+ | Cge
+
+val negate_comparison: comparison -> comparison
+val swap_comparison: comparison -> comparison
+
+type memory_chunk =
+ Byte_unsigned
+ | Byte_signed
+ | Sixteen_unsigned
+ | Sixteen_signed
+ | Thirtytwo_unsigned
+ | Thirtytwo_signed
+ | Word_int (* integer or pointer outside heap *)
+ | Word_val (* pointer inside heap or encoded int *)
+ | Single
+ | Double (* 64-bit-aligned 64-bit float *)
+ | Double_u (* word-aligned 64-bit float *)
+
+type operation =
+ Capply of machtype * Debuginfo.t
+ | Cextcall of string * machtype * bool * Debuginfo.t
+ | Cload of memory_chunk
+ | Calloc
+ | Cstore of memory_chunk
+ | Caddi | Csubi | Cmuli | Cmulhi | Cdivi | Cmodi
+ | Cand | Cor | Cxor | Clsl | Clsr | Casr
+ | Ccmpi of comparison
+ | Caddv (* pointer addition that produces a [Val] (well-formed Caml value) *)
+ | Cadda (* pointer addition that produces a [Addr] (derived heap pointer) *)
+ | Ccmpa of comparison
+ | Cnegf | Cabsf
+ | Caddf | Csubf | Cmulf | Cdivf
+ | Cfloatofint | Cintoffloat
+ | Ccmpf of comparison
+ | Craise of Lambda.raise_kind * Debuginfo.t
+ | Ccheckbound of Debuginfo.t
+
+type expression =
+ Cconst_int of int
+ | Cconst_natint of nativeint
+ | Cconst_float of float
+ | Cconst_symbol of string
+ | Cconst_pointer of int
+ | Cconst_natpointer of nativeint
+ | Cconst_blockheader of nativeint
+ | Cvar of Ident.t
+ | Clet of Ident.t * expression * expression
+ | Cassign of Ident.t * expression
+ | Ctuple of expression list
+ | Cop of operation * expression list
+ | Csequence of expression * expression
+ | Cifthenelse of expression * expression * expression
+ | Cswitch of expression * int array * expression array
+ | Cloop of expression
+ | Ccatch of int * Ident.t list * expression * expression
+ | Cexit of int * expression list
+ | Ctrywith of expression * Ident.t * expression
+
+type fundecl =
+ { fun_name: string;
+ fun_args: (Ident.t * machtype) list;
+ fun_body: expression;
+ fun_fast: bool;
+ fun_dbg : Debuginfo.t; }
+
+type data_item =
+ Cdefine_symbol of string
+ | Cdefine_label of int
+ | Cglobal_symbol of string
+ | Cint8 of int
+ | Cint16 of int
+ | Cint32 of nativeint
+ | Cint of nativeint
+ | Csingle of float
+ | Cdouble of float
+ | Csymbol_address of string
+ | Clabel_address of int
+ | Cstring of string
+ | Cskip of int
+ | Calign of int
+
+type phrase =
+ Cfunction of fundecl
+ | Cdata of data_item list
diff --git a/asmcomp/cmmgen.ml b/asmcomp/cmmgen.ml
new file mode 100644
index 0000000000..5f2d5a4a9f
--- /dev/null
+++ b/asmcomp/cmmgen.ml
@@ -0,0 +1,2947 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translation from closed lambda to C-- *)
+
+open Misc
+open Arch
+open Asttypes
+open Primitive
+open Types
+open Lambda
+open Clambda
+open Cmm
+open Cmx_format
+
+(* Local binding of complex expressions *)
+
+let bind name arg fn =
+ match arg with
+ Cvar _ | Cconst_int _ | Cconst_natint _ | Cconst_symbol _
+ | Cconst_pointer _ | Cconst_natpointer _
+ | Cconst_blockheader _ -> fn arg
+ | _ -> let id = Ident.create name in Clet(id, arg, fn (Cvar id))
+
+let bind_load name arg fn =
+ match arg with
+ | Cop(Cload _, [Cvar _]) -> fn arg
+ | _ -> bind name arg fn
+
+let bind_nonvar name arg fn =
+ match arg with
+ Cconst_int _ | Cconst_natint _ | Cconst_symbol _
+ | Cconst_pointer _ | Cconst_natpointer _
+ | Cconst_blockheader _ -> fn arg
+ | _ -> let id = Ident.create name in Clet(id, arg, fn (Cvar id))
+
+let caml_black = Nativeint.shift_left (Nativeint.of_int 3) 8
+ (* cf. byterun/gc.h *)
+
+(* Block headers. Meaning of the tag field: see stdlib/obj.ml *)
+
+let floatarray_tag = Cconst_int Obj.double_array_tag
+
+let block_header tag sz =
+ Nativeint.add (Nativeint.shift_left (Nativeint.of_int sz) 10)
+ (Nativeint.of_int tag)
+(* Static data corresponding to "value"s must be marked black in case we are
+ in no-naked-pointers mode. See [caml_darken] and the code below that emits
+ structured constants and static module definitions. *)
+let black_block_header tag sz = Nativeint.logor (block_header tag sz) caml_black
+let white_closure_header sz = block_header Obj.closure_tag sz
+let black_closure_header sz = black_block_header Obj.closure_tag sz
+let infix_header ofs = block_header Obj.infix_tag ofs
+let float_header = block_header Obj.double_tag (size_float / size_addr)
+let floatarray_header len =
+ block_header Obj.double_array_tag (len * size_float / size_addr)
+let string_header len =
+ block_header Obj.string_tag ((len + size_addr) / size_addr)
+let boxedint32_header = block_header Obj.custom_tag 2
+let boxedint64_header = block_header Obj.custom_tag (1 + 8 / size_addr)
+let boxedintnat_header = block_header Obj.custom_tag 2
+
+let alloc_block_header tag sz = Cconst_blockheader(block_header tag sz)
+let alloc_float_header = Cconst_blockheader(float_header)
+let alloc_floatarray_header len = Cconst_blockheader(floatarray_header len)
+let alloc_closure_header sz = Cconst_blockheader(white_closure_header sz)
+let alloc_infix_header ofs = Cconst_blockheader(infix_header ofs)
+let alloc_boxedint32_header = Cconst_blockheader(boxedint32_header)
+let alloc_boxedint64_header = Cconst_blockheader(boxedint64_header)
+let alloc_boxedintnat_header = Cconst_blockheader(boxedintnat_header)
+
+(* Integers *)
+
+let max_repr_int = max_int asr 1
+let min_repr_int = min_int asr 1
+
+let int_const n =
+ if n <= max_repr_int && n >= min_repr_int
+ then Cconst_int((n lsl 1) + 1)
+ else Cconst_natint
+ (Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n)
+
+let rec add_const c n =
+ if n = 0 then c
+ else match c with
+ | Cconst_int x when no_overflow_add x n -> Cconst_int (x + n)
+ | Cop(Caddi, ([Cconst_int x; c] | [c; Cconst_int x]))
+ when no_overflow_add n x ->
+ let d = n + x in
+ if d = 0 then c else Cop(Caddi, [c; Cconst_int d])
+ | Cop(Csubi, [Cconst_int x; c]) when no_overflow_add n x ->
+ Cop(Csubi, [Cconst_int (n + x); c])
+ | Cop(Csubi, [c; Cconst_int x]) when no_overflow_sub n x ->
+ add_const c (n - x)
+ | c -> Cop(Caddi, [c; Cconst_int n])
+
+let incr_int c = add_const c 1
+let decr_int c = add_const c (-1)
+
+let rec add_int c1 c2 =
+ match (c1, c2) with
+ | (Cconst_int n, c) | (c, Cconst_int n) ->
+ add_const c n
+ | (Cop(Caddi, [c1; Cconst_int n1]), c2) ->
+ add_const (add_int c1 c2) n1
+ | (c1, Cop(Caddi, [c2; Cconst_int n2])) ->
+ add_const (add_int c1 c2) n2
+ | (_, _) ->
+ Cop(Caddi, [c1; c2])
+
+let rec sub_int c1 c2 =
+ match (c1, c2) with
+ | (c1, Cconst_int n2) when n2 <> min_int ->
+ add_const c1 (-n2)
+ | (c1, Cop(Caddi, [c2; Cconst_int n2])) when n2 <> min_int ->
+ add_const (sub_int c1 c2) (-n2)
+ | (Cop(Caddi, [c1; Cconst_int n1]), c2) ->
+ add_const (sub_int c1 c2) n1
+ | (c1, c2) ->
+ Cop(Csubi, [c1; c2])
+
+let rec lsl_int c1 c2 =
+ match (c1, c2) with
+ | (Cop(Clsl, [c; Cconst_int n1]), Cconst_int n2)
+ when n1 > 0 && n2 > 0 && n1 + n2 < size_int * 8 ->
+ Cop(Clsl, [c; Cconst_int (n1 + n2)])
+ | (Cop(Caddi, [c1; Cconst_int n1]), Cconst_int n2)
+ when no_overflow_lsl n1 n2 ->
+ add_const (lsl_int c1 c2) (n1 lsl n2)
+ | (_, _) ->
+ Cop(Clsl, [c1; c2])
+
+let rec mul_int c1 c2 =
+ match (c1, c2) with
+ | (c, Cconst_int 0) | (Cconst_int 0, c) ->
+ Cconst_int 0
+ | (c, Cconst_int 1) | (Cconst_int 1, c) ->
+ c
+ | (c, Cconst_int(-1)) | (Cconst_int(-1), c) ->
+ sub_int (Cconst_int 0) c
+ | (c, Cconst_int n) | (Cconst_int n, c) when n = 1 lsl Misc.log2 n->
+ lsl_int c (Cconst_int (Misc.log2 n))
+ | (Cop(Caddi, [c; Cconst_int n]), Cconst_int k) |
+ (Cconst_int k, Cop(Caddi, [c; Cconst_int n]))
+ when no_overflow_mul n k ->
+ add_const (mul_int c (Cconst_int k)) (n * k)
+ | (c1, c2) ->
+ Cop(Cmuli, [c1; c2])
+
+
+let ignore_low_bit_int = function
+ Cop(Caddi, [(Cop(Clsl, [_; Cconst_int n]) as c); Cconst_int 1]) when n > 0
+ -> c
+ | Cop(Cor, [c; Cconst_int 1]) -> c
+ | c -> c
+
+let lsr_int c1 c2 =
+ match c2 with
+ Cconst_int 0 ->
+ c1
+ | Cconst_int n when n > 0 ->
+ Cop(Clsr, [ignore_low_bit_int c1; c2])
+ | _ ->
+ Cop(Clsr, [c1; c2])
+
+let asr_int c1 c2 =
+ match c2 with
+ Cconst_int 0 ->
+ c1
+ | Cconst_int n when n > 0 ->
+ Cop(Casr, [ignore_low_bit_int c1; c2])
+ | _ ->
+ Cop(Casr, [c1; c2])
+
+let tag_int = function
+ Cconst_int n ->
+ int_const n
+ | Cop(Casr, [c; Cconst_int n]) when n > 0 ->
+ Cop(Cor, [asr_int c (Cconst_int (n - 1)); Cconst_int 1])
+ | c ->
+ incr_int (lsl_int c (Cconst_int 1))
+
+let force_tag_int = function
+ Cconst_int n ->
+ int_const n
+ | Cop(Casr, [c; Cconst_int n]) when n > 0 ->
+ Cop(Cor, [asr_int c (Cconst_int (n - 1)); Cconst_int 1])
+ | c ->
+ Cop(Cor, [lsl_int c (Cconst_int 1); Cconst_int 1])
+
+let untag_int = function
+ Cconst_int n -> Cconst_int(n asr 1)
+ | Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) -> c
+ | Cop(Cor, [Cop(Casr, [c; Cconst_int n]); Cconst_int 1])
+ when n > 0 && n < size_int * 8 ->
+ Cop(Casr, [c; Cconst_int (n+1)])
+ | Cop(Cor, [Cop(Clsr, [c; Cconst_int n]); Cconst_int 1])
+ when n > 0 && n < size_int * 8 ->
+ Cop(Clsr, [c; Cconst_int (n+1)])
+ | Cop(Cor, [c; Cconst_int 1]) -> Cop(Casr, [c; Cconst_int 1])
+ | c -> Cop(Casr, [c; Cconst_int 1])
+
+(* Turning integer divisions into multiply-high then shift.
+ The [division_parameters] function is used in module Emit for
+ those target platforms that support this optimization. *)
+
+(* Unsigned comparison between native integers. *)
+
+let ucompare x y = Nativeint.(compare (add x min_int) (add y min_int))
+
+(* Unsigned division and modulus at type nativeint.
+ Algorithm: Hacker's Delight section 9.3 *)
+
+let udivmod n d = Nativeint.(
+ if d < 0n then
+ if ucompare n d < 0 then (0n, n) else (1n, sub n d)
+ else begin
+ let q = shift_left (div (shift_right_logical n 1) d) 1 in
+ let r = sub n (mul q d) in
+ if ucompare r d >= 0 then (succ q, sub r d) else (q, r)
+ end)
+
+(* Compute division parameters.
+ Algorithm: Hacker's Delight chapter 10, fig 10-1. *)
+
+let divimm_parameters d = Nativeint.(
+ assert (d > 0n);
+ let twopsm1 = min_int in (* 2^31 for 32-bit archs, 2^63 for 64-bit archs *)
+ let nc = sub (pred twopsm1) (snd (udivmod twopsm1 d)) in
+ let rec loop p (q1, r1) (q2, r2) =
+ let p = p + 1 in
+ let q1 = shift_left q1 1 and r1 = shift_left r1 1 in
+ let (q1, r1) =
+ if ucompare r1 nc >= 0 then (succ q1, sub r1 nc) else (q1, r1) in
+ let q2 = shift_left q2 1 and r2 = shift_left r2 1 in
+ let (q2, r2) =
+ if ucompare r2 d >= 0 then (succ q2, sub r2 d) else (q2, r2) in
+ let delta = sub d r2 in
+ if ucompare q1 delta < 0 || (q1 = delta && r1 = 0n)
+ then loop p (q1, r1) (q2, r2)
+ else (succ q2, p - size)
+ in loop (size - 1) (udivmod twopsm1 nc) (udivmod twopsm1 d))
+
+(* The result [(m, p)] of [divimm_parameters d] satisfies the following
+ inequality:
+
+ 2^(wordsize + p) < m * d <= 2^(wordsize + p) + 2^(p + 1) (i)
+
+ from which it follows that
+
+ floor(n / d) = floor(n * m / 2^(wordsize+p))
+ if 0 <= n < 2^(wordsize-1)
+ ceil(n / d) = floor(n * m / 2^(wordsize+p)) + 1
+ if -2^(wordsize-1) <= n < 0
+
+ The correctness condition (i) above can be checked by the code below.
+ It was exhaustively tested for values of d from 2 to 10^9 in the
+ wordsize = 64 case.
+
+let add2 (xh, xl) (yh, yl) =
+ let zl = add xl yl and zh = add xh yh in
+ ((if ucompare zl xl < 0 then succ zh else zh), zl)
+
+let shl2 (xh, xl) n =
+ assert (0 < n && n < size + size);
+ if n < size
+ then (logor (shift_left xh n) (shift_right_logical xl (size - n)),
+ shift_left xl n)
+ else (shift_left xl (n - size), 0n)
+
+let mul2 x y =
+ let halfsize = size / 2 in
+ let halfmask = pred (shift_left 1n halfsize) in
+ let xl = logand x halfmask and xh = shift_right_logical x halfsize in
+ let yl = logand y halfmask and yh = shift_right_logical y halfsize in
+ add2 (mul xh yh, 0n)
+ (add2 (shl2 (0n, mul xl yh) halfsize)
+ (add2 (shl2 (0n, mul xh yl) halfsize)
+ (0n, mul xl yl)))
+
+let ucompare2 (xh, xl) (yh, yl) =
+ let c = ucompare xh yh in if c = 0 then ucompare xl yl else c
+
+let validate d m p =
+ let md = mul2 m d in
+ let one2 = (0n, 1n) in
+ let twoszp = shl2 one2 (size + p) in
+ let twop1 = shl2 one2 (p + 1) in
+ ucompare2 twoszp md < 0 && ucompare2 md (add2 twoszp twop1) <= 0
+*)
+
+let rec div_int c1 c2 dbg =
+ match (c1, c2) with
+ (c1, Cconst_int 0) ->
+ Csequence(c1, Cop(Craise (Raise_regular, dbg),
+ [Cconst_symbol "caml_exn_Division_by_zero"]))
+ | (c1, Cconst_int 1) ->
+ c1
+ | (Cconst_int 0 as c1, c2) ->
+ Csequence(c2, c1)
+ | (Cconst_int n1, Cconst_int n2) ->
+ Cconst_int (n1 / n2)
+ | (c1, Cconst_int n) when n <> min_int ->
+ let l = Misc.log2 n in
+ if n = 1 lsl l then
+ (* Algorithm:
+ t = shift-right-signed(c1, l - 1)
+ t = shift-right(t, W - l)
+ t = c1 + t
+ res = shift-right-signed(c1 + t, l)
+ *)
+ Cop(Casr, [bind "dividend" c1 (fun c1 ->
+ let t = asr_int c1 (Cconst_int (l - 1)) in
+ let t = lsr_int t (Cconst_int (Nativeint.size - l)) in
+ add_int c1 t);
+ Cconst_int l])
+ else if n < 0 then
+ sub_int (Cconst_int 0) (div_int c1 (Cconst_int (-n)) dbg)
+ else begin
+ let (m, p) = divimm_parameters (Nativeint.of_int n) in
+ (* Algorithm:
+ t = multiply-high-signed(c1, m)
+ if m < 0, t = t + c1
+ if p > 0, t = shift-right-signed(t, p)
+ res = t + sign-bit(c1)
+ *)
+ bind "dividend" c1 (fun c1 ->
+ let t = Cop(Cmulhi, [c1; Cconst_natint m]) in
+ let t = if m < 0n then Cop(Caddi, [t; c1]) else t in
+ let t = if p > 0 then Cop(Casr, [t; Cconst_int p]) else t in
+ add_int t (lsr_int c1 (Cconst_int (Nativeint.size - 1))))
+ end
+ | (c1, c2) when !Clflags.fast ->
+ Cop(Cdivi, [c1; c2])
+ | (c1, c2) ->
+ bind "divisor" c2 (fun c2 ->
+ Cifthenelse(c2,
+ Cop(Cdivi, [c1; c2]),
+ Cop(Craise (Raise_regular, dbg),
+ [Cconst_symbol "caml_exn_Division_by_zero"])))
+
+let mod_int c1 c2 dbg =
+ match (c1, c2) with
+ (c1, Cconst_int 0) ->
+ Csequence(c1, Cop(Craise (Raise_regular, dbg),
+ [Cconst_symbol "caml_exn_Division_by_zero"]))
+ | (c1, Cconst_int (1 | (-1))) ->
+ Csequence(c1, Cconst_int 0)
+ | (Cconst_int 0, c2) ->
+ Csequence(c2, Cconst_int 0)
+ | (Cconst_int n1, Cconst_int n2) ->
+ Cconst_int (n1 mod n2)
+ | (c1, (Cconst_int n as c2)) when n <> min_int ->
+ let l = Misc.log2 n in
+ if n = 1 lsl l then
+ (* Algorithm:
+ t = shift-right-signed(c1, l - 1)
+ t = shift-right(t, W - l)
+ t = c1 + t
+ t = bit-and(t, -n)
+ res = c1 - t
+ *)
+ bind "dividend" c1 (fun c1 ->
+ let t = asr_int c1 (Cconst_int (l - 1)) in
+ let t = lsr_int t (Cconst_int (Nativeint.size - l)) in
+ let t = add_int c1 t in
+ let t = Cop(Cand, [t; Cconst_int (-n)]) in
+ sub_int c1 t)
+ else
+ bind "dividend" c1 (fun c1 ->
+ sub_int c1 (mul_int (div_int c1 c2 dbg) c2))
+ | (c1, c2) when !Clflags.fast ->
+ Cop(Cmodi, [c1; c2])
+ | (c1, c2) ->
+ bind "divisor" c2 (fun c2 ->
+ Cifthenelse(c2,
+ Cop(Cmodi, [c1; c2]),
+ Cop(Craise (Raise_regular, dbg),
+ [Cconst_symbol "caml_exn_Division_by_zero"])))
+
+(* Division or modulo on boxed integers. The overflow case min_int / -1
+ can occur, in which case we force x / -1 = -x and x mod -1 = 0. (PR#5513). *)
+
+let is_different_from x = function
+ Cconst_int n -> n <> x
+ | Cconst_natint n -> n <> Nativeint.of_int x
+ | _ -> false
+
+let safe_divmod_bi mkop mkm1 c1 c2 bi dbg =
+ bind "dividend" c1 (fun c1 ->
+ bind "divisor" c2 (fun c2 ->
+ let c = mkop c1 c2 dbg in
+ if Arch.division_crashes_on_overflow
+ && (size_int = 4 || bi <> Pint32)
+ && not (is_different_from (-1) c2)
+ then Cifthenelse(Cop(Ccmpi Cne, [c2; Cconst_int(-1)]), c, mkm1 c1)
+ else c))
+
+let safe_div_bi =
+ safe_divmod_bi div_int (fun c1 -> Cop(Csubi, [Cconst_int 0; c1]))
+
+let safe_mod_bi =
+ safe_divmod_bi mod_int (fun c1 -> Cconst_int 0)
+
+(* Bool *)
+
+let test_bool = function
+ Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) -> c
+ | Cop(Clsl, [c; Cconst_int 1]) -> c
+ | c -> Cop(Ccmpi Cne, [c; Cconst_int 1])
+
+(* Float *)
+
+let box_float c = Cop(Calloc, [alloc_float_header; c])
+
+let rec unbox_float = function
+ Cop(Calloc, [header; c]) -> c
+ | Clet(id, exp, body) -> Clet(id, exp, unbox_float body)
+ | Cifthenelse(cond, e1, e2) ->
+ Cifthenelse(cond, unbox_float e1, unbox_float e2)
+ | Csequence(e1, e2) -> Csequence(e1, unbox_float e2)
+ | Cswitch(e, tbl, el) -> Cswitch(e, tbl, Array.map unbox_float el)
+ | Ccatch(n, ids, e1, e2) -> Ccatch(n, ids, unbox_float e1, unbox_float e2)
+ | Ctrywith(e1, id, e2) -> Ctrywith(unbox_float e1, id, unbox_float e2)
+ | c -> Cop(Cload Double_u, [c])
+
+(* Complex *)
+
+let box_complex c_re c_im =
+ Cop(Calloc, [alloc_floatarray_header 2; c_re; c_im])
+
+let complex_re c = Cop(Cload Double_u, [c])
+let complex_im c = Cop(Cload Double_u,
+ [Cop(Cadda, [c; Cconst_int size_float])])
+
+(* Unit *)
+
+let return_unit c = Csequence(c, Cconst_pointer 1)
+
+let rec remove_unit = function
+ Cconst_pointer 1 -> Ctuple []
+ | Csequence(c, Cconst_pointer 1) -> c
+ | Csequence(c1, c2) ->
+ Csequence(c1, remove_unit c2)
+ | Cifthenelse(cond, ifso, ifnot) ->
+ Cifthenelse(cond, remove_unit ifso, remove_unit ifnot)
+ | Cswitch(sel, index, cases) ->
+ Cswitch(sel, index, Array.map remove_unit cases)
+ | Ccatch(io, ids, body, handler) ->
+ Ccatch(io, ids, remove_unit body, remove_unit handler)
+ | Ctrywith(body, exn, handler) ->
+ Ctrywith(remove_unit body, exn, remove_unit handler)
+ | Clet(id, c1, c2) ->
+ Clet(id, c1, remove_unit c2)
+ | Cop(Capply (mty, dbg), args) ->
+ Cop(Capply (typ_void, dbg), args)
+ | Cop(Cextcall(proc, mty, alloc, dbg), args) ->
+ Cop(Cextcall(proc, typ_void, alloc, dbg), args)
+ | Cexit (_,_) as c -> c
+ | Ctuple [] as c -> c
+ | c -> Csequence(c, Ctuple [])
+
+(* Access to block fields *)
+
+let field_address ptr n =
+ if n = 0
+ then ptr
+ else Cop(Cadda, [ptr; Cconst_int(n * size_addr)])
+
+
+let get_field ptr n =
+ Cop(Cload Word_val, [field_address ptr n])
+
+let set_field ptr n newval =
+ Cop(Cstore Word_val, [field_address ptr n; newval])
+
+let header ptr =
+ Cop(Cload Word_int, [Cop(Cadda, [ptr; Cconst_int(-size_int)])])
+
+let tag_offset =
+ if big_endian then -1 else -size_int
+
+let get_tag ptr =
+ if Proc.word_addressed then (* If byte loads are slow *)
+ Cop(Cand, [header ptr; Cconst_int 255])
+ else (* If byte loads are efficient *)
+ Cop(Cload Byte_unsigned,
+ [Cop(Cadda, [ptr; Cconst_int(tag_offset)])])
+
+let get_size ptr =
+ Cop(Clsr, [header ptr; Cconst_int 10])
+
+(* Array indexing *)
+
+let log2_size_addr = Misc.log2 size_addr
+let log2_size_float = Misc.log2 size_float
+
+let wordsize_shift = 9
+let numfloat_shift = 9 + log2_size_float - log2_size_addr
+
+let is_addr_array_hdr hdr =
+ Cop(Ccmpi Cne, [Cop(Cand, [hdr; Cconst_int 255]); floatarray_tag])
+
+let is_addr_array_ptr ptr =
+ Cop(Ccmpi Cne, [get_tag ptr; floatarray_tag])
+
+let addr_array_length hdr = Cop(Clsr, [hdr; Cconst_int wordsize_shift])
+let float_array_length hdr = Cop(Clsr, [hdr; Cconst_int numfloat_shift])
+
+let lsl_const c n =
+ if n = 0 then c
+ else Cop(Clsl, [c; Cconst_int n])
+
+(* Produces a pointer to the element of the array [ptr] on the position [ofs]
+ with the given element [log2size] log2 element size. [ofs] is given as a
+ tagged int expression.
+ The optional ?typ argument is the C-- type of the result.
+ By default, it is Addr, meaning we are constructing a derived pointer
+ into the heap. If we know the pointer is outside the heap
+ (this is the case for bigarray indexing), we give type Int instead. *)
+
+let array_indexing ?typ log2size ptr ofs =
+ let add =
+ match typ with
+ | None | Some Addr -> Cadda
+ | Some Int -> Caddi
+ | _ -> assert false in
+ match ofs with
+ Cconst_int n ->
+ let i = n asr 1 in
+ if i = 0 then ptr else Cop(add, [ptr; Cconst_int(i lsl log2size)])
+ | Cop(Caddi, [Cop(Clsl, [c; Cconst_int 1]); Cconst_int 1]) ->
+ Cop(add, [ptr; lsl_const c log2size])
+ | Cop(Caddi, [c; Cconst_int n]) when log2size = 0 ->
+ Cop(add, [Cop(add, [ptr; untag_int c]); Cconst_int (n asr 1)])
+ | Cop(Caddi, [c; Cconst_int n]) ->
+ Cop(add, [Cop(add, [ptr; lsl_const c (log2size - 1)]);
+ Cconst_int((n-1) lsl (log2size - 1))])
+ | _ when log2size = 0 ->
+ Cop(add, [ptr; untag_int ofs])
+ | _ ->
+ Cop(add, [Cop(add, [ptr; lsl_const ofs (log2size - 1)]);
+ Cconst_int((-1) lsl (log2size - 1))])
+
+let addr_array_ref arr ofs =
+ Cop(Cload Word_val, [array_indexing log2_size_addr arr ofs])
+let int_array_ref arr ofs =
+ Cop(Cload Word_int, [array_indexing log2_size_addr arr ofs])
+let unboxed_float_array_ref arr ofs =
+ Cop(Cload Double_u, [array_indexing log2_size_float arr ofs])
+let float_array_ref arr ofs =
+ box_float(unboxed_float_array_ref arr ofs)
+
+let addr_array_set arr ofs newval =
+ Cop(Cextcall("caml_modify", typ_void, false, Debuginfo.none),
+ [array_indexing log2_size_addr arr ofs; newval])
+let int_array_set arr ofs newval =
+ Cop(Cstore Word_int, [array_indexing log2_size_addr arr ofs; newval])
+let float_array_set arr ofs newval =
+ Cop(Cstore Double_u, [array_indexing log2_size_float arr ofs; newval])
+
+(* String length *)
+
+(* Length of string block *)
+
+let string_length exp =
+ bind "str" exp (fun str ->
+ let tmp_var = Ident.create "tmp" in
+ Clet(tmp_var,
+ Cop(Csubi,
+ [Cop(Clsl,
+ [get_size str;
+ Cconst_int log2_size_addr]);
+ Cconst_int 1]),
+ Cop(Csubi,
+ [Cvar tmp_var;
+ Cop(Cload Byte_unsigned,
+ [Cop(Cadda, [str; Cvar tmp_var])])])))
+
+(* Message sending *)
+
+let lookup_tag obj tag =
+ bind "tag" tag (fun tag ->
+ Cop(Cextcall("caml_get_public_method", typ_val, false, Debuginfo.none),
+ [obj; tag]))
+
+let lookup_label obj lab =
+ bind "lab" lab (fun lab ->
+ let table = Cop (Cload Word_val, [obj]) in
+ addr_array_ref table lab)
+
+let call_cached_method obj tag cache pos args dbg =
+ let arity = List.length args in
+ let cache = array_indexing log2_size_addr cache pos in
+ Compilenv.need_send_fun arity;
+ Cop(Capply (typ_val, dbg),
+ Cconst_symbol("caml_send" ^ string_of_int arity) ::
+ obj :: tag :: cache :: args)
+
+(* Allocation *)
+
+let make_alloc_generic set_fn tag wordsize args =
+ if wordsize <= Config.max_young_wosize then
+ Cop(Calloc, Cconst_blockheader(block_header tag wordsize) :: args)
+ else begin
+ let id = Ident.create "alloc" in
+ let rec fill_fields idx = function
+ [] -> Cvar id
+ | e1::el -> Csequence(set_fn (Cvar id) (Cconst_int idx) e1,
+ fill_fields (idx + 2) el) in
+ Clet(id,
+ Cop(Cextcall("caml_alloc", typ_val, true, Debuginfo.none),
+ [Cconst_int wordsize; Cconst_int tag]),
+ fill_fields 1 args)
+ end
+
+let make_alloc tag args =
+ make_alloc_generic addr_array_set tag (List.length args) args
+let make_float_alloc tag args =
+ make_alloc_generic float_array_set tag
+ (List.length args * size_float / size_addr) args
+
+(* Bounds checking *)
+
+let make_checkbound dbg = function
+ | [Cop(Clsr, [a1; Cconst_int n]); Cconst_int m] when (m lsl n) > n ->
+ Cop(Ccheckbound dbg, [a1; Cconst_int(m lsl n + 1 lsl n - 1)])
+ | args ->
+ Cop(Ccheckbound dbg, args)
+
+(* To compile "let rec" over values *)
+
+let fundecls_size fundecls =
+ let sz = ref (-1) in
+ List.iter
+ (fun f -> sz := !sz + 1 + (if f.arity = 1 then 2 else 3))
+ fundecls;
+ !sz
+
+type rhs_kind =
+ | RHS_block of int
+ | RHS_floatblock of int
+ | RHS_nonrec
+;;
+let rec expr_size env = function
+ | Uvar id ->
+ begin try Ident.find_same id env with Not_found -> RHS_nonrec end
+ | Uclosure(fundecls, clos_vars) ->
+ RHS_block (fundecls_size fundecls + List.length clos_vars)
+ | Ulet(id, exp, body) ->
+ expr_size (Ident.add id (expr_size env exp) env) body
+ | Uletrec(bindings, body) ->
+ expr_size env body
+ | Uprim(Pmakeblock(tag, mut), args, _) ->
+ RHS_block (List.length args)
+ | Uprim(Pmakearray(Paddrarray | Pintarray), args, _) ->
+ RHS_block (List.length args)
+ | Uprim(Pmakearray(Pfloatarray), args, _) ->
+ RHS_floatblock (List.length args)
+ | Uprim (Pduprecord ((Record_regular | Record_inlined _), sz), _, _) ->
+ RHS_block sz
+ | Uprim (Pduprecord (Record_extension, sz), _, _) ->
+ RHS_block (sz + 1)
+ | Uprim (Pduprecord (Record_float, sz), _, _) ->
+ RHS_floatblock sz
+ | Usequence(exp, exp') ->
+ expr_size env exp'
+ | _ -> RHS_nonrec
+
+(* Record application and currying functions *)
+
+let apply_function n =
+ Compilenv.need_apply_fun n; "caml_apply" ^ string_of_int n
+let curry_function n =
+ Compilenv.need_curry_fun n;
+ if n >= 0
+ then "caml_curry" ^ string_of_int n
+ else "caml_tuplify" ^ string_of_int (-n)
+
+(* Comparisons *)
+
+let transl_comparison = function
+ Lambda.Ceq -> Ceq
+ | Lambda.Cneq -> Cne
+ | Lambda.Cge -> Cge
+ | Lambda.Cgt -> Cgt
+ | Lambda.Cle -> Cle
+ | Lambda.Clt -> Clt
+
+(* Translate structured constants *)
+
+let transl_constant = function
+ | Uconst_int n ->
+ int_const n
+ | Uconst_ptr n ->
+ if n <= max_repr_int && n >= min_repr_int
+ then Cconst_pointer((n lsl 1) + 1)
+ else Cconst_natpointer
+ (Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n)
+ | Uconst_ref (label, _) ->
+ Cconst_symbol label
+
+let transl_structured_constant cst =
+ let label = Compilenv.new_structured_constant cst ~shared:true in
+ Cconst_symbol label
+
+(* Translate constant closures *)
+
+let constant_closures =
+ ref ([] : (string * ufunction list) list)
+
+(* Boxed integers *)
+
+let box_int_constant bi n =
+ match bi with
+ Pnativeint -> Uconst_nativeint n
+ | Pint32 -> Uconst_int32 (Nativeint.to_int32 n)
+ | Pint64 -> Uconst_int64 (Int64.of_nativeint n)
+
+let operations_boxed_int bi =
+ match bi with
+ Pnativeint -> "caml_nativeint_ops"
+ | Pint32 -> "caml_int32_ops"
+ | Pint64 -> "caml_int64_ops"
+
+let alloc_header_boxed_int bi =
+ match bi with
+ Pnativeint -> alloc_boxedintnat_header
+ | Pint32 -> alloc_boxedint32_header
+ | Pint64 -> alloc_boxedint64_header
+
+let box_int bi arg =
+ match arg with
+ Cconst_int n ->
+ transl_structured_constant (box_int_constant bi (Nativeint.of_int n))
+ | Cconst_natint n ->
+ transl_structured_constant (box_int_constant bi n)
+ | _ ->
+ let arg' =
+ if bi = Pint32 && size_int = 8 && big_endian
+ then Cop(Clsl, [arg; Cconst_int 32])
+ else arg in
+ Cop(Calloc, [alloc_header_boxed_int bi;
+ Cconst_symbol(operations_boxed_int bi);
+ arg'])
+
+(* Offsets of the least and most significant words for
+ an int64 on a 32 bit target *)
+let int64_for_32bit_target_offsets =
+ if Arch.big_endian then
+ (8, 4)
+ else
+ (4, 8)
+
+let split_int64_for_32bit_target arg =
+ bind "split_int64" arg (fun arg ->
+ let least_sig_ofs, most_sig_ofs =
+ int64_for_32bit_target_offsets
+ in
+ let least_sig_addr = Cop (Cadda, [Cconst_int least_sig_ofs; arg]) in
+ let most_sig_addr = Cop (Cadda, [Cconst_int most_sig_ofs; arg]) in
+ Ctuple [Cop (Cload Thirtytwo_unsigned, [least_sig_addr]);
+ Cop (Cload Thirtytwo_unsigned, [most_sig_addr])])
+
+let rec unbox_int bi arg =
+ match arg with
+ Cop(Calloc, [hdr; ops; Cop(Clsl, [contents; Cconst_int 32])])
+ when bi = Pint32 && size_int = 8 && big_endian ->
+ (* Force sign-extension of low 32 bits *)
+ Cop(Casr, [Cop(Clsl, [contents; Cconst_int 32]); Cconst_int 32])
+ | Cop(Calloc, [hdr; ops; contents])
+ when bi = Pint32 && size_int = 8 && not big_endian ->
+ (* Force sign-extension of low 32 bits *)
+ Cop(Casr, [Cop(Clsl, [contents; Cconst_int 32]); Cconst_int 32])
+ | Cop(Calloc, [hdr; ops; contents]) ->
+ contents
+ | Clet(id, exp, body) -> Clet(id, exp, unbox_int bi body)
+ | Cifthenelse(cond, e1, e2) ->
+ Cifthenelse(cond, unbox_int bi e1, unbox_int bi e2)
+ | Csequence(e1, e2) -> Csequence(e1, unbox_int bi e2)
+ | Cswitch(e, tbl, el) -> Cswitch(e, tbl, Array.map (unbox_int bi) el)
+ | Ccatch(n, ids, e1, e2) -> Ccatch(n, ids, unbox_int bi e1, unbox_int bi e2)
+ | Ctrywith(e1, id, e2) -> Ctrywith(unbox_int bi e1, id, unbox_int bi e2)
+ | _ ->
+ if size_int = 4 && bi = Pint64 then
+ split_int64_for_32bit_target arg
+ else
+ Cop(Cload(if bi = Pint32 then Thirtytwo_signed else Word_int),
+ [Cop(Cadda, [arg; Cconst_int size_addr])])
+
+let make_unsigned_int bi arg =
+ if bi = Pint32 && size_int = 8
+ then Cop(Cand, [arg; Cconst_natint 0xFFFFFFFFn])
+ else arg
+
+(* Boxed numbers *)
+
+type boxed_number =
+ | Boxed_float
+ | Boxed_integer of boxed_integer
+
+let box_number bn arg =
+ match bn with
+ | Boxed_float -> box_float arg
+ | Boxed_integer bi -> box_int bi arg
+
+let unbox_number bn arg =
+ match bn with
+ | Boxed_float -> unbox_float arg
+ | Boxed_integer bi -> unbox_int bi arg
+
+(* Big arrays *)
+
+let bigarray_elt_size = function
+ Pbigarray_unknown -> assert false
+ | Pbigarray_float32 -> 4
+ | Pbigarray_float64 -> 8
+ | Pbigarray_sint8 -> 1
+ | Pbigarray_uint8 -> 1
+ | Pbigarray_sint16 -> 2
+ | Pbigarray_uint16 -> 2
+ | Pbigarray_int32 -> 4
+ | Pbigarray_int64 -> 8
+ | Pbigarray_caml_int -> size_int
+ | Pbigarray_native_int -> size_int
+ | Pbigarray_complex32 -> 8
+ | Pbigarray_complex64 -> 16
+
+(* Produces a pointer to the element of the bigarray [b] on the position
+ [args]. [args] is given as a list of tagged int expressions, one per array
+ dimension. *)
+let bigarray_indexing unsafe elt_kind layout b args dbg =
+ let check_ba_bound bound idx v =
+ Csequence(make_checkbound dbg [bound;idx], v) in
+ (* Validates the given multidimensional offset against the array bounds and
+ transforms it into a one dimensional offset. The offsets are expressions
+ evaluating to tagged int. *)
+ let rec ba_indexing dim_ofs delta_ofs = function
+ [] -> assert false
+ | [arg] ->
+ if unsafe then arg
+ else
+ bind "idx" arg (fun idx ->
+ (* Load the untagged int bound for the given dimension *)
+ let bound = Cop(Cload Word_int,[field_address b dim_ofs]) in
+ let idxn = untag_int idx in
+ check_ba_bound bound idxn idx)
+ | arg1 :: argl ->
+ (* The remainder of the list is transformed into a one dimensional offset
+ *)
+ let rem = ba_indexing (dim_ofs + delta_ofs) delta_ofs argl in
+ (* Load the untagged int bound for the given dimension *)
+ let bound = Cop(Cload Word_int, [field_address b dim_ofs]) in
+ if unsafe then add_int (mul_int (decr_int rem) bound) arg1
+ else
+ bind "idx" arg1 (fun idx ->
+ bind "bound" bound (fun bound ->
+ let idxn = untag_int idx in
+ (* [offset = rem * (tag_int bound) + idx] *)
+ let offset = add_int (mul_int (decr_int rem) bound) idx in
+ check_ba_bound bound idxn offset)) in
+ (* The offset as an expression evaluating to int *)
+ let offset =
+ match layout with
+ Pbigarray_unknown_layout ->
+ assert false
+ | Pbigarray_c_layout ->
+ ba_indexing (4 + List.length args) (-1) (List.rev args)
+ | Pbigarray_fortran_layout ->
+ ba_indexing 5 1 (List.map (fun idx -> sub_int idx (Cconst_int 2)) args)
+ and elt_size =
+ bigarray_elt_size elt_kind in
+ (* [array_indexing] can simplify the given expressions *)
+ array_indexing ~typ:Int (log2 elt_size)
+ (Cop(Cload Word_int, [field_address b 1])) offset
+
+let bigarray_word_kind = function
+ Pbigarray_unknown -> assert false
+ | Pbigarray_float32 -> Single
+ | Pbigarray_float64 -> Double
+ | Pbigarray_sint8 -> Byte_signed
+ | Pbigarray_uint8 -> Byte_unsigned
+ | Pbigarray_sint16 -> Sixteen_signed
+ | Pbigarray_uint16 -> Sixteen_unsigned
+ | Pbigarray_int32 -> Thirtytwo_signed
+ | Pbigarray_int64 -> Word_int
+ | Pbigarray_caml_int -> Word_int
+ | Pbigarray_native_int -> Word_int
+ | Pbigarray_complex32 -> Single
+ | Pbigarray_complex64 -> Double
+
+let bigarray_get unsafe elt_kind layout b args dbg =
+ bind "ba" b (fun b ->
+ match elt_kind with
+ Pbigarray_complex32 | Pbigarray_complex64 ->
+ let kind = bigarray_word_kind elt_kind in
+ let sz = bigarray_elt_size elt_kind / 2 in
+ bind "addr" (bigarray_indexing unsafe elt_kind layout b args dbg)
+ (fun addr ->
+ box_complex
+ (Cop(Cload kind, [addr]))
+ (Cop(Cload kind, [Cop(Cadda, [addr; Cconst_int sz])])))
+ | _ ->
+ Cop(Cload (bigarray_word_kind elt_kind),
+ [bigarray_indexing unsafe elt_kind layout b args dbg]))
+
+let bigarray_set unsafe elt_kind layout b args newval dbg =
+ bind "ba" b (fun b ->
+ match elt_kind with
+ Pbigarray_complex32 | Pbigarray_complex64 ->
+ let kind = bigarray_word_kind elt_kind in
+ let sz = bigarray_elt_size elt_kind / 2 in
+ bind "newval" newval (fun newv ->
+ bind "addr" (bigarray_indexing unsafe elt_kind layout b args dbg)
+ (fun addr ->
+ Csequence(
+ Cop(Cstore kind, [addr; complex_re newv]),
+ Cop(Cstore kind,
+ [Cop(Cadda, [addr; Cconst_int sz]); complex_im newv]))))
+ | _ ->
+ Cop(Cstore (bigarray_word_kind elt_kind),
+ [bigarray_indexing unsafe elt_kind layout b args dbg; newval]))
+
+let unaligned_load_16 ptr idx =
+ if Arch.allow_unaligned_access
+ then Cop(Cload Sixteen_unsigned, [add_int ptr idx])
+ else
+ let v1 = Cop(Cload Byte_unsigned, [add_int ptr idx]) in
+ let v2 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 1)]) in
+ let b1, b2 = if Arch.big_endian then v1, v2 else v2, v1 in
+ Cop(Cor, [lsl_int b1 (Cconst_int 8); b2])
+
+let unaligned_set_16 ptr idx newval =
+ if Arch.allow_unaligned_access
+ then Cop(Cstore Sixteen_unsigned, [add_int ptr idx; newval])
+ else
+ let v1 = Cop(Cand, [Cop(Clsr, [newval; Cconst_int 8]); Cconst_int 0xFF]) in
+ let v2 = Cop(Cand, [newval; Cconst_int 0xFF]) in
+ let b1, b2 = if Arch.big_endian then v1, v2 else v2, v1 in
+ Csequence(
+ Cop(Cstore Byte_unsigned, [add_int ptr idx; b1]),
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 1); b2]))
+
+let unaligned_load_32 ptr idx =
+ if Arch.allow_unaligned_access
+ then Cop(Cload Thirtytwo_unsigned, [add_int ptr idx])
+ else
+ let v1 = Cop(Cload Byte_unsigned, [add_int ptr idx]) in
+ let v2 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 1)]) in
+ let v3 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 2)]) in
+ let v4 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 3)]) in
+ let b1, b2, b3, b4 =
+ if Arch.big_endian
+ then v1, v2, v3, v4
+ else v4, v3, v2, v1 in
+ Cop(Cor,
+ [Cop(Cor, [lsl_int b1 (Cconst_int 24); lsl_int b2 (Cconst_int 16)]);
+ Cop(Cor, [lsl_int b3 (Cconst_int 8); b4])])
+
+let unaligned_set_32 ptr idx newval =
+ if Arch.allow_unaligned_access
+ then Cop(Cstore Thirtytwo_unsigned, [add_int ptr idx; newval])
+ else
+ let v1 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int 24]); Cconst_int 0xFF]) in
+ let v2 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int 16]); Cconst_int 0xFF]) in
+ let v3 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int 8]); Cconst_int 0xFF]) in
+ let v4 = Cop(Cand, [newval; Cconst_int 0xFF]) in
+ let b1, b2, b3, b4 =
+ if Arch.big_endian
+ then v1, v2, v3, v4
+ else v4, v3, v2, v1 in
+ Csequence(
+ Csequence(
+ Cop(Cstore Byte_unsigned, [add_int ptr idx; b1]),
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 1); b2])),
+ Csequence(
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 2); b3]),
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 3); b4])))
+
+let unaligned_load_64 ptr idx =
+ assert(size_int = 8);
+ if Arch.allow_unaligned_access
+ then Cop(Cload Word_int, [add_int ptr idx])
+ else
+ let v1 = Cop(Cload Byte_unsigned, [add_int ptr idx]) in
+ let v2 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 1)]) in
+ let v3 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 2)]) in
+ let v4 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 3)]) in
+ let v5 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 4)]) in
+ let v6 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 5)]) in
+ let v7 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 6)]) in
+ let v8 = Cop(Cload Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 7)]) in
+ let b1, b2, b3, b4, b5, b6, b7, b8 =
+ if Arch.big_endian
+ then v1, v2, v3, v4, v5, v6, v7, v8
+ else v8, v7, v6, v5, v4, v3, v2, v1 in
+ Cop(Cor,
+ [Cop(Cor,
+ [Cop(Cor, [lsl_int b1 (Cconst_int (8*7));
+ lsl_int b2 (Cconst_int (8*6))]);
+ Cop(Cor, [lsl_int b3 (Cconst_int (8*5));
+ lsl_int b4 (Cconst_int (8*4))])]);
+ Cop(Cor,
+ [Cop(Cor, [lsl_int b5 (Cconst_int (8*3));
+ lsl_int b6 (Cconst_int (8*2))]);
+ Cop(Cor, [lsl_int b7 (Cconst_int 8);
+ b8])])])
+
+let unaligned_set_64 ptr idx newval =
+ assert(size_int = 8);
+ if Arch.allow_unaligned_access
+ then Cop(Cstore Word_int, [add_int ptr idx; newval])
+ else
+ let v1 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int (8*7)]); Cconst_int 0xFF]) in
+ let v2 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int (8*6)]); Cconst_int 0xFF]) in
+ let v3 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int (8*5)]); Cconst_int 0xFF]) in
+ let v4 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int (8*4)]); Cconst_int 0xFF]) in
+ let v5 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int (8*3)]); Cconst_int 0xFF]) in
+ let v6 =
+ Cop(Cand, [Cop(Clsr, [newval; Cconst_int (8*2)]); Cconst_int 0xFF]) in
+ let v7 = Cop(Cand, [Cop(Clsr, [newval; Cconst_int 8]); Cconst_int 0xFF]) in
+ let v8 = Cop(Cand, [newval; Cconst_int 0xFF]) in
+ let b1, b2, b3, b4, b5, b6, b7, b8 =
+ if Arch.big_endian
+ then v1, v2, v3, v4, v5, v6, v7, v8
+ else v8, v7, v6, v5, v4, v3, v2, v1 in
+ Csequence(
+ Csequence(
+ Csequence(
+ Cop(Cstore Byte_unsigned, [add_int ptr idx; b1]),
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 1); b2])),
+ Csequence(
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 2); b3]),
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 3); b4]))),
+ Csequence(
+ Csequence(
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 4); b5]),
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 5); b6])),
+ Csequence(
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 6); b7]),
+ Cop(Cstore Byte_unsigned,
+ [add_int (add_int ptr idx) (Cconst_int 7); b8]))))
+
+let max_or_zero a =
+ bind "size" a (fun a ->
+ (* equivalent to
+ Cifthenelse(Cop(Ccmpi Cle, [a; Cconst_int 0]), Cconst_int 0, a)
+
+ if a is positive, sign is 0 hence sign_negation is full of 1
+ so sign_negation&a = a
+ if a is negative, sign is full of 1 hence sign_negation is 0
+ so sign_negation&a = 0 *)
+ let sign = Cop(Casr, [a; Cconst_int (size_int * 8 - 1)]) in
+ let sign_negation = Cop(Cxor, [sign; Cconst_int (-1)]) in
+ Cop(Cand, [sign_negation; a]))
+
+let check_bound unsafe dbg a1 a2 k =
+ if unsafe then k
+ else Csequence(make_checkbound dbg [max_or_zero a1;a2], k)
+
+(* Simplification of some primitives into C calls *)
+
+let default_prim name =
+ Primitive.simple ~name ~arity:0(*ignored*) ~alloc:true
+
+let simplif_primitive_32bits = function
+ Pbintofint Pint64 -> Pccall (default_prim "caml_int64_of_int")
+ | Pintofbint Pint64 -> Pccall (default_prim "caml_int64_to_int")
+ | Pcvtbint(Pint32, Pint64) -> Pccall (default_prim "caml_int64_of_int32")
+ | Pcvtbint(Pint64, Pint32) -> Pccall (default_prim "caml_int64_to_int32")
+ | Pcvtbint(Pnativeint, Pint64) ->
+ Pccall (default_prim "caml_int64_of_nativeint")
+ | Pcvtbint(Pint64, Pnativeint) ->
+ Pccall (default_prim "caml_int64_to_nativeint")
+ | Pnegbint Pint64 -> Pccall (default_prim "caml_int64_neg")
+ | Paddbint Pint64 -> Pccall (default_prim "caml_int64_add")
+ | Psubbint Pint64 -> Pccall (default_prim "caml_int64_sub")
+ | Pmulbint Pint64 -> Pccall (default_prim "caml_int64_mul")
+ | Pdivbint Pint64 -> Pccall (default_prim "caml_int64_div")
+ | Pmodbint Pint64 -> Pccall (default_prim "caml_int64_mod")
+ | Pandbint Pint64 -> Pccall (default_prim "caml_int64_and")
+ | Porbint Pint64 -> Pccall (default_prim "caml_int64_or")
+ | Pxorbint Pint64 -> Pccall (default_prim "caml_int64_xor")
+ | Plslbint Pint64 -> Pccall (default_prim "caml_int64_shift_left")
+ | Plsrbint Pint64 -> Pccall (default_prim "caml_int64_shift_right_unsigned")
+ | Pasrbint Pint64 -> Pccall (default_prim "caml_int64_shift_right")
+ | Pbintcomp(Pint64, Lambda.Ceq) -> Pccall (default_prim "caml_equal")
+ | Pbintcomp(Pint64, Lambda.Cneq) -> Pccall (default_prim "caml_notequal")
+ | Pbintcomp(Pint64, Lambda.Clt) -> Pccall (default_prim "caml_lessthan")
+ | Pbintcomp(Pint64, Lambda.Cgt) -> Pccall (default_prim "caml_greaterthan")
+ | Pbintcomp(Pint64, Lambda.Cle) -> Pccall (default_prim "caml_lessequal")
+ | Pbintcomp(Pint64, Lambda.Cge) -> Pccall (default_prim "caml_greaterequal")
+ | Pbigarrayref(unsafe, n, Pbigarray_int64, layout) ->
+ Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
+ | Pbigarrayset(unsafe, n, Pbigarray_int64, layout) ->
+ Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
+ | Pstring_load_64(_) -> Pccall (default_prim "caml_string_get64")
+ | Pstring_set_64(_) -> Pccall (default_prim "caml_string_set64")
+ | Pbigstring_load_64(_) -> Pccall (default_prim "caml_ba_uint8_get64")
+ | Pbigstring_set_64(_) -> Pccall (default_prim "caml_ba_uint8_set64")
+ | Pbbswap Pint64 -> Pccall (default_prim "caml_int64_bswap")
+ | p -> p
+
+let simplif_primitive p =
+ match p with
+ | Pduprecord _ ->
+ Pccall (default_prim "caml_obj_dup")
+ | Pbigarrayref(unsafe, n, Pbigarray_unknown, layout) ->
+ Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
+ | Pbigarrayset(unsafe, n, Pbigarray_unknown, layout) ->
+ Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
+ | Pbigarrayref(unsafe, n, kind, Pbigarray_unknown_layout) ->
+ Pccall (default_prim ("caml_ba_get_" ^ string_of_int n))
+ | Pbigarrayset(unsafe, n, kind, Pbigarray_unknown_layout) ->
+ Pccall (default_prim ("caml_ba_set_" ^ string_of_int n))
+ | p ->
+ if size_int = 8 then p else simplif_primitive_32bits p
+
+(* Build switchers both for constants and blocks *)
+
+let transl_isout h arg = tag_int (Cop(Ccmpa Clt, [h ; arg]))
+
+(* Build an actual switch (ie jump table) *)
+
+module SArgBlocks =
+struct
+ type primitive = operation
+
+ let eqint = Ccmpi Ceq
+ let neint = Ccmpi Cne
+ let leint = Ccmpi Cle
+ let ltint = Ccmpi Clt
+ let geint = Ccmpi Cge
+ let gtint = Ccmpi Cgt
+
+ type act = expression
+
+ let default = Cexit (0,[])
+ let make_const i = Cconst_int i
+ let make_prim p args = Cop (p,args)
+ let make_offset arg n = add_const arg n
+ let make_isout h arg = Cop (Ccmpa Clt, [h ; arg])
+ let make_isin h arg = Cop (Ccmpa Cge, [h ; arg])
+ let make_if cond ifso ifnot = Cifthenelse (cond, ifso, ifnot)
+ let make_switch arg cases actions = Cswitch (arg,cases,actions)
+ let bind arg body = bind "switcher" arg body
+
+ let make_catch handler = match handler with
+ | Cexit (i,[]) -> i,fun e -> e
+ | _ ->
+ let i = next_raise_count () in
+(*
+ Printf.eprintf "SHARE CMM: %i\n" i ;
+ Printcmm.expression Format.str_formatter handler ;
+ Printf.eprintf "%s\n" (Format.flush_str_formatter ()) ;
+*)
+ i,
+ (fun body -> match body with
+ | Cexit (j,_) ->
+ if i=j then handler
+ else body
+ | _ -> Ccatch (i,[],body,handler))
+
+ let make_exit i = Cexit (i,[])
+
+end
+
+(* cmm store, as sharing as normally been detected in previous
+ phases, we only share exits *)
+module StoreExp =
+ Switch.Store
+ (struct
+ type t = expression
+ type key = int
+ let make_key = function
+ | Cexit (i,[]) -> Some i
+ | _ -> None
+ end)
+
+module SwitcherBlocks = Switch.Make(SArgBlocks)
+
+(* Int switcher, arg in [low..high],
+ cases is list of individual cases, and is sorted by first component *)
+
+let transl_int_switch arg low high cases default = match cases with
+| [] -> assert false
+| _::_ ->
+ let store = StoreExp.mk_store () in
+ assert (store.Switch.act_store default = 0) ;
+ let cases =
+ List.map
+ (fun (i,act) -> i,store.Switch.act_store act)
+ cases in
+ let rec inters plow phigh pact = function
+ | [] ->
+ if phigh = high then [plow,phigh,pact]
+ else [(plow,phigh,pact); (phigh+1,high,0) ]
+ | (i,act)::rem ->
+ if i = phigh+1 then
+ if pact = act then
+ inters plow i pact rem
+ else
+ (plow,phigh,pact)::inters i i act rem
+ else (* insert default *)
+ if pact = 0 then
+ if act = 0 then
+ inters plow i 0 rem
+ else
+ (plow,i-1,pact)::
+ inters i i act rem
+ else (* pact <> 0 *)
+ (plow,phigh,pact)::
+ begin
+ if act = 0 then inters (phigh+1) i 0 rem
+ else (phigh+1,i-1,0)::inters i i act rem
+ end in
+ let inters = match cases with
+ | [] -> assert false
+ | (k0,act0)::rem ->
+ if k0 = low then inters k0 k0 act0 rem
+ else inters low (k0-1) 0 cases in
+ bind "switcher" arg
+ (fun a ->
+ SwitcherBlocks.zyva
+ (low,high)
+ a
+ (Array.of_list inters) store)
+
+
+(* Auxiliary functions for optimizing "let" of boxed numbers (floats and
+ boxed integers *)
+
+type unboxed_number_kind =
+ No_unboxing
+ | Boxed of boxed_number
+ | No_result (* expression never returns a result *)
+
+let unboxed_number_kind_of_unbox = function
+ | Same_as_ocaml_repr -> No_unboxing
+ | Unboxed_float -> Boxed Boxed_float
+ | Unboxed_integer bi -> Boxed (Boxed_integer bi)
+ | Untagged_int -> No_unboxing
+
+let rec is_unboxed_number e =
+ (* Given unboxed_number_kind from two branches of the code, returns the
+ resulting unboxed_number_kind *)
+ let join k1 e =
+ match k1, is_unboxed_number e with
+ | Boxed b1, Boxed b2 when b1 = b2 -> Boxed b1
+ | No_result, k | k, No_result ->
+ k (* if a branch never returns, it is safe to unbox it *)
+ | _, _ -> No_unboxing
+ in
+ match e with
+ | Uconst(Uconst_ref(_, Uconst_float _)) -> Boxed Boxed_float
+ | Uconst(Uconst_ref(_, Uconst_int32 _)) -> Boxed (Boxed_integer Pint32)
+ | Uconst(Uconst_ref(_, Uconst_int64 _)) -> Boxed (Boxed_integer Pint64)
+ | Uconst(Uconst_ref(_, Uconst_nativeint _)) ->
+ Boxed (Boxed_integer Pnativeint)
+ | Uprim(p, _, _) ->
+ begin match simplif_primitive p with
+ | Pccall p -> unboxed_number_kind_of_unbox p.prim_native_repr_res
+ | Pfloatfield _ -> Boxed Boxed_float
+ | Pfloatofint -> Boxed Boxed_float
+ | Pnegfloat -> Boxed Boxed_float
+ | Pabsfloat -> Boxed Boxed_float
+ | Paddfloat -> Boxed Boxed_float
+ | Psubfloat -> Boxed Boxed_float
+ | Pmulfloat -> Boxed Boxed_float
+ | Pdivfloat -> Boxed Boxed_float
+ | Parrayrefu Pfloatarray -> Boxed Boxed_float
+ | Parrayrefs Pfloatarray -> Boxed Boxed_float
+ | Pbintofint bi -> Boxed (Boxed_integer bi)
+ | Pcvtbint(src, dst) -> Boxed (Boxed_integer dst)
+ | Pnegbint bi -> Boxed (Boxed_integer bi)
+ | Paddbint bi -> Boxed (Boxed_integer bi)
+ | Psubbint bi -> Boxed (Boxed_integer bi)
+ | Pmulbint bi -> Boxed (Boxed_integer bi)
+ | Pdivbint bi -> Boxed (Boxed_integer bi)
+ | Pmodbint bi -> Boxed (Boxed_integer bi)
+ | Pandbint bi -> Boxed (Boxed_integer bi)
+ | Porbint bi -> Boxed (Boxed_integer bi)
+ | Pxorbint bi -> Boxed (Boxed_integer bi)
+ | Plslbint bi -> Boxed (Boxed_integer bi)
+ | Plsrbint bi -> Boxed (Boxed_integer bi)
+ | Pasrbint bi -> Boxed (Boxed_integer bi)
+ | Pbigarrayref(_, _, (Pbigarray_float32 | Pbigarray_float64), _) ->
+ Boxed Boxed_float
+ | Pbigarrayref(_, _, Pbigarray_int32, _) -> Boxed (Boxed_integer Pint32)
+ | Pbigarrayref(_, _, Pbigarray_int64, _) -> Boxed (Boxed_integer Pint64)
+ | Pbigarrayref(_, _, Pbigarray_native_int,_) ->
+ Boxed (Boxed_integer Pnativeint)
+ | Pstring_load_32(_) -> Boxed (Boxed_integer Pint32)
+ | Pstring_load_64(_) -> Boxed (Boxed_integer Pint64)
+ | Pbigstring_load_32(_) -> Boxed (Boxed_integer Pint32)
+ | Pbigstring_load_64(_) -> Boxed (Boxed_integer Pint64)
+ | Pbbswap bi -> Boxed (Boxed_integer bi)
+ | Praise _ -> No_result
+ | _ -> No_unboxing
+ end
+ | Ulet (_, _, e) | Uletrec (_, e) | Usequence (_, e) -> is_unboxed_number e
+ | Uswitch (_, switch) ->
+ let k = Array.fold_left join No_result switch.us_actions_consts in
+ Array.fold_left join k switch.us_actions_blocks
+ | Ustringswitch (_, actions, default_opt) ->
+ let k = List.fold_left (fun k (_, e) -> join k e) No_result actions in
+ begin match default_opt with
+ None -> k
+ | Some default -> join k default
+ end
+ | Ustaticfail _ -> No_result
+ | Uifthenelse (_, e1, e2) | Ucatch (_, _, e1, e2) | Utrywith (e1, _, e2) ->
+ join (is_unboxed_number e1) e2
+ | _ -> No_unboxing
+
+let box_chunk = function
+ | Boxed_float -> Double_u
+ | Boxed_integer Pint32 -> Thirtytwo_unsigned
+ | Boxed_integer _ -> Word_int
+
+let box_offset = function
+ | Boxed_float -> 0
+ | Boxed_integer _ -> size_addr
+
+let subst_boxed_number boxed_number boxed_id unboxed_id exp =
+ let rec subst = function
+ | Cvar id when Ident.same id boxed_id ->
+ box_number boxed_number (Cvar unboxed_id)
+ | Clet(id, arg, body) -> Clet(id, subst arg, subst body)
+ | Cassign(id, arg) when Ident.same id boxed_id ->
+ Cassign(unboxed_id, subst(unbox_number boxed_number arg))
+ | Cassign(id, arg) -> Cassign(id, subst arg)
+ | Cop(Cload chunk, [Cvar id])
+ when Ident.same id boxed_id &&
+ chunk = box_chunk boxed_number &&
+ 0 = box_offset boxed_number ->
+ Cvar unboxed_id
+ | Cop(Cload chunk, [Cop(Cadda, [Cvar id; Cconst_int ofs])])
+ when Ident.same id boxed_id
+ && chunk = box_chunk boxed_number &&
+ ofs = box_offset boxed_number ->
+ Cvar unboxed_id
+ | Cop(op, argv) -> Cop(op, List.map subst argv)
+ (* 64 bits integer on 32 bit target *)
+ | Ctuple [Cop (Cload Thirtytwo_unsigned,
+ [Cop (Cadda, [Cconst_int ofs1; Cvar id1])]);
+ Cop (Cload Thirtytwo_unsigned,
+ [Cop (Cadda, [Cconst_int ofs2; Cvar id2])])]
+ when size_int = 4 && boxed_number = Boxed_integer Pint64 &&
+ Ident.same id1 boxed_id && Ident.same id2 boxed_id &&
+ ((ofs1, ofs2) = int64_for_32bit_target_offsets) ->
+ Cvar unboxed_id
+ | Ctuple argv -> Ctuple(List.map subst argv)
+ | Csequence(e1, e2) -> Csequence(subst e1, subst e2)
+ | Cifthenelse(e1, e2, e3) -> Cifthenelse(subst e1, subst e2, subst e3)
+ | Cswitch(arg, index, cases) ->
+ Cswitch(subst arg, index, Array.map subst cases)
+ | Cloop e -> Cloop(subst e)
+ | Ccatch(nfail, ids, e1, e2) -> Ccatch(nfail, ids, subst e1, subst e2)
+ | Cexit (nfail, el) -> Cexit (nfail, List.map subst el)
+ | Ctrywith(e1, id, e2) -> Ctrywith(subst e1, id, subst e2)
+ | Cvar _
+ | Cconst_int _ | Cconst_natint _ | Cconst_float _ | Cconst_symbol _
+ | Cconst_pointer _ | Cconst_natpointer _
+ | Cconst_blockheader _ as e -> e
+ in
+ subst exp
+
+(* Translate an expression *)
+
+let functions = (Queue.create() : ufunction Queue.t)
+
+let strmatch_compile =
+ let module S =
+ Strmatch.Make
+ (struct
+ let string_block_length = get_size
+ let transl_switch = transl_int_switch
+ end) in
+ S.compile
+
+let rec transl = function
+ Uvar id ->
+ Cvar id
+ | Uconst sc ->
+ transl_constant sc
+ | Uclosure(fundecls, []) ->
+ let lbl = Compilenv.new_const_symbol() in
+ constant_closures := (lbl, fundecls) :: !constant_closures;
+ List.iter (fun f -> Queue.add f functions) fundecls;
+ Cconst_symbol lbl
+ | Uclosure(fundecls, clos_vars) ->
+ let block_size =
+ fundecls_size fundecls + List.length clos_vars in
+ let rec transl_fundecls pos = function
+ [] ->
+ List.map transl clos_vars
+ | f :: rem ->
+ Queue.add f functions;
+ let header =
+ if pos = 0
+ then alloc_closure_header block_size
+ else alloc_infix_header pos in
+ if f.arity = 1 then
+ header ::
+ Cconst_symbol f.label ::
+ int_const 1 ::
+ transl_fundecls (pos + 3) rem
+ else
+ header ::
+ Cconst_symbol(curry_function f.arity) ::
+ int_const f.arity ::
+ Cconst_symbol f.label ::
+ transl_fundecls (pos + 4) rem in
+ Cop(Calloc, transl_fundecls 0 fundecls)
+ | Uoffset(arg, offset) ->
+ (* produces a valid Caml value, pointing just after an infix header *)
+ let ptr = transl arg in
+ if offset = 0
+ then ptr
+ else Cop(Caddv, [ptr; Cconst_int(offset * size_addr)])
+ | Udirect_apply(lbl, args, dbg) ->
+ Cop(Capply(typ_val, dbg), Cconst_symbol lbl :: List.map transl args)
+ | Ugeneric_apply(clos, [arg], dbg) ->
+ bind "fun" (transl clos) (fun clos ->
+ Cop(Capply(typ_val, dbg), [get_field clos 0; transl arg; clos]))
+ | Ugeneric_apply(clos, args, dbg) ->
+ let arity = List.length args in
+ let cargs = Cconst_symbol(apply_function arity) ::
+ List.map transl (args @ [clos]) in
+ Cop(Capply(typ_val, dbg), cargs)
+ | Usend(kind, met, obj, args, dbg) ->
+ let call_met obj args clos =
+ if args = [] then
+ Cop(Capply(typ_val, dbg), [get_field clos 0;obj;clos])
+ else
+ let arity = List.length args + 1 in
+ let cargs = Cconst_symbol(apply_function arity) :: obj ::
+ (List.map transl args) @ [clos] in
+ Cop(Capply(typ_val, dbg), cargs)
+ in
+ bind "obj" (transl obj) (fun obj ->
+ match kind, args with
+ Self, _ ->
+ bind "met" (lookup_label obj (transl met)) (call_met obj args)
+ | Cached, cache :: pos :: args ->
+ call_cached_method obj (transl met) (transl cache) (transl pos)
+ (List.map transl args) dbg
+ | _ ->
+ bind "met" (lookup_tag obj (transl met)) (call_met obj args))
+ | Ulet(id, exp, body) ->
+ transl_let id exp (transl body)
+ | Uletrec(bindings, body) ->
+ transl_letrec bindings (transl body)
+
+ (* Primitives *)
+ | Uprim(prim, args, dbg) ->
+ begin match (simplif_primitive prim, args) with
+ (Pgetglobal id, []) ->
+ Cconst_symbol (Ident.name id)
+ | (Pmakeblock(tag, mut), []) ->
+ assert false
+ | (Pmakeblock(tag, mut), args) ->
+ make_alloc tag (List.map transl args)
+ | (Pccall prim, args) ->
+ transl_ccall prim args dbg
+ | (Pmakearray kind, []) ->
+ transl_structured_constant (Uconst_block(0, []))
+ | (Pmakearray kind, args) ->
+ begin match kind with
+ Pgenarray ->
+ Cop(Cextcall("caml_make_array", typ_val, true, Debuginfo.none),
+ [make_alloc 0 (List.map transl args)])
+ | Paddrarray | Pintarray ->
+ make_alloc 0 (List.map transl args)
+ | Pfloatarray ->
+ make_float_alloc Obj.double_array_tag
+ (List.map transl_unbox_float args)
+ end
+ | (Pbigarrayref(unsafe, num_dims, elt_kind, layout), arg1 :: argl) ->
+ let elt =
+ bigarray_get unsafe elt_kind layout
+ (transl arg1) (List.map transl argl) dbg in
+ begin match elt_kind with
+ Pbigarray_float32 | Pbigarray_float64 -> box_float elt
+ | Pbigarray_complex32 | Pbigarray_complex64 -> elt
+ | Pbigarray_int32 -> box_int Pint32 elt
+ | Pbigarray_int64 -> box_int Pint64 elt
+ | Pbigarray_native_int -> box_int Pnativeint elt
+ | Pbigarray_caml_int -> force_tag_int elt
+ | _ -> tag_int elt
+ end
+ | (Pbigarrayset(unsafe, num_dims, elt_kind, layout), arg1 :: argl) ->
+ let (argidx, argnewval) = split_last argl in
+ return_unit(bigarray_set unsafe elt_kind layout
+ (transl arg1)
+ (List.map transl argidx)
+ (match elt_kind with
+ Pbigarray_float32 | Pbigarray_float64 ->
+ transl_unbox_float argnewval
+ | Pbigarray_complex32 | Pbigarray_complex64 -> transl argnewval
+ | Pbigarray_int32 -> transl_unbox_int Pint32 argnewval
+ | Pbigarray_int64 -> transl_unbox_int Pint64 argnewval
+ | Pbigarray_native_int -> transl_unbox_int Pnativeint argnewval
+ | _ -> untag_int (transl argnewval))
+ dbg)
+ | (Pbigarraydim(n), [b]) ->
+ let dim_ofs = 4 + n in
+ tag_int (Cop(Cload Word_int, [field_address (transl b) dim_ofs]))
+ | (p, [arg]) ->
+ transl_prim_1 p arg dbg
+ | (p, [arg1; arg2]) ->
+ transl_prim_2 p arg1 arg2 dbg
+ | (p, [arg1; arg2; arg3]) ->
+ transl_prim_3 p arg1 arg2 arg3 dbg
+ | (_, _) ->
+ fatal_error "Cmmgen.transl:prim"
+ end
+
+ (* Control structures *)
+ | Uswitch(arg, s) ->
+ (* As in the bytecode interpreter, only matching against constants
+ can be checked *)
+ if Array.length s.us_index_blocks = 0 then
+ Cswitch
+ (untag_int (transl arg),
+ s.us_index_consts,
+ Array.map transl s.us_actions_consts)
+ else if Array.length s.us_index_consts = 0 then
+ transl_switch (get_tag (transl arg))
+ s.us_index_blocks s.us_actions_blocks
+ else
+ bind "switch" (transl arg) (fun arg ->
+ Cifthenelse(
+ Cop(Cand, [arg; Cconst_int 1]),
+ transl_switch
+ (untag_int arg) s.us_index_consts s.us_actions_consts,
+ transl_switch
+ (get_tag arg) s.us_index_blocks s.us_actions_blocks))
+ | Ustringswitch(arg,sw,d) ->
+ bind "switch" (transl arg)
+ (fun arg ->
+ strmatch_compile arg (Misc.may_map transl d)
+ (List.map (fun (s,act) -> s,transl act) sw))
+ | Ustaticfail (nfail, args) ->
+ Cexit (nfail, List.map transl args)
+ | Ucatch(nfail, [], body, handler) ->
+ make_catch nfail (transl body) (transl handler)
+ | Ucatch(nfail, ids, body, handler) ->
+ Ccatch(nfail, ids, transl body, transl handler)
+ | Utrywith(body, exn, handler) ->
+ Ctrywith(transl body, exn, transl handler)
+ | Uifthenelse(Uprim(Pnot, [arg], _), ifso, ifnot) ->
+ transl (Uifthenelse(arg, ifnot, ifso))
+ | Uifthenelse(cond, ifso, Ustaticfail (nfail, [])) ->
+ exit_if_false cond (transl ifso) nfail
+ | Uifthenelse(cond, Ustaticfail (nfail, []), ifnot) ->
+ exit_if_true cond nfail (transl ifnot)
+ | Uifthenelse(Uprim(Psequand, _, _) as cond, ifso, ifnot) ->
+ let raise_num = next_raise_count () in
+ make_catch
+ raise_num
+ (exit_if_false cond (transl ifso) raise_num)
+ (transl ifnot)
+ | Uifthenelse(Uprim(Psequor, _, _) as cond, ifso, ifnot) ->
+ let raise_num = next_raise_count () in
+ make_catch
+ raise_num
+ (exit_if_true cond raise_num (transl ifnot))
+ (transl ifso)
+ | Uifthenelse (Uifthenelse (cond, condso, condnot), ifso, ifnot) ->
+ let num_true = next_raise_count () in
+ make_catch
+ num_true
+ (make_catch2
+ (fun shared_false ->
+ Cifthenelse
+ (test_bool (transl cond),
+ exit_if_true condso num_true shared_false,
+ exit_if_true condnot num_true shared_false))
+ (transl ifnot))
+ (transl ifso)
+ | Uifthenelse(cond, ifso, ifnot) ->
+ Cifthenelse(test_bool(transl cond), transl ifso, transl ifnot)
+ | Usequence(exp1, exp2) ->
+ Csequence(remove_unit(transl exp1), transl exp2)
+ | Uwhile(cond, body) ->
+ let raise_num = next_raise_count () in
+ return_unit
+ (Ccatch
+ (raise_num, [],
+ Cloop(exit_if_false cond (remove_unit(transl body)) raise_num),
+ Ctuple []))
+ | Ufor(id, low, high, dir, body) ->
+ let tst = match dir with Upto -> Cgt | Downto -> Clt in
+ let inc = match dir with Upto -> Caddi | Downto -> Csubi in
+ let raise_num = next_raise_count () in
+ let id_prev = Ident.rename id in
+ return_unit
+ (Clet
+ (id, transl low,
+ bind_nonvar "bound" (transl high) (fun high ->
+ Ccatch
+ (raise_num, [],
+ Cifthenelse
+ (Cop(Ccmpi tst, [Cvar id; high]), Cexit (raise_num, []),
+ Cloop
+ (Csequence
+ (remove_unit(transl body),
+ Clet(id_prev, Cvar id,
+ Csequence
+ (Cassign(id,
+ Cop(inc, [Cvar id; Cconst_int 2])),
+ Cifthenelse
+ (Cop(Ccmpi Ceq, [Cvar id_prev; high]),
+ Cexit (raise_num,[]), Ctuple [])))))),
+ Ctuple []))))
+ | Uassign(id, exp) ->
+ return_unit(Cassign(id, transl exp))
+
+and transl_ccall prim args dbg =
+ let transl_arg native_repr arg =
+ match native_repr with
+ | Same_as_ocaml_repr -> transl arg
+ | Unboxed_float -> transl_unbox_float arg
+ | Unboxed_integer bi -> transl_unbox_int bi arg
+ | Untagged_int -> untag_int (transl arg)
+ in
+ let rec transl_args native_repr_args args =
+ match native_repr_args, args with
+ | [], args ->
+ (* We don't require the two lists to be of the same length as
+ [default_prim] always sets the arity to [0]. *)
+ List.map transl args
+ | _, [] -> assert false
+ | native_repr :: native_repr_args, arg :: args ->
+ transl_arg native_repr arg :: transl_args native_repr_args args
+ in
+ let typ_res, wrap_result =
+ match prim.prim_native_repr_res with
+ | Same_as_ocaml_repr -> (typ_val, fun x -> x)
+ | Unboxed_float -> (typ_float, box_float)
+ | Unboxed_integer Pint64 when size_int = 4 -> ([|Int; Int|], box_int Pint64)
+ | Unboxed_integer bi -> (typ_int, box_int bi)
+ | Untagged_int -> (typ_int, tag_int)
+ in
+ let args = transl_args prim.prim_native_repr_args args in
+ wrap_result
+ (Cop(Cextcall(Primitive.native_name prim,
+ typ_res, prim.prim_alloc, dbg), args))
+
+and transl_prim_1 p arg dbg =
+ match p with
+ (* Generic operations *)
+ Pidentity ->
+ transl arg
+ | Pignore ->
+ return_unit(remove_unit (transl arg))
+ (* Heap operations *)
+ | Pfield n ->
+ get_field (transl arg) n
+ | Pfloatfield n ->
+ let ptr = transl arg in
+ box_float(
+ Cop(Cload Double_u,
+ [if n = 0 then ptr
+ else Cop(Cadda, [ptr; Cconst_int(n * size_float)])]))
+ | Pint_as_pointer ->
+ Cop(Caddi, [transl arg; Cconst_int (-1)])
+ (* always a pointer outside the heap *)
+ (* Exceptions *)
+ | Praise k ->
+ Cop(Craise (k, dbg), [transl arg])
+ (* Integer operations *)
+ | Pnegint ->
+ Cop(Csubi, [Cconst_int 2; transl arg])
+ | Pctconst c ->
+ let const_of_bool b = tag_int (Cconst_int (if b then 1 else 0)) in
+ begin
+ match c with
+ | Big_endian -> const_of_bool Arch.big_endian
+ | Word_size -> tag_int (Cconst_int (8*Arch.size_int))
+ | Int_size -> tag_int (Cconst_int ((8*Arch.size_int) - 1))
+ | Max_wosize ->
+ tag_int (Cconst_int ((1 lsl ((8*Arch.size_int) - 10)) - 1 ))
+ | Ostype_unix -> const_of_bool (Sys.os_type = "Unix")
+ | Ostype_win32 -> const_of_bool (Sys.os_type = "Win32")
+ | Ostype_cygwin -> const_of_bool (Sys.os_type = "Cygwin")
+ end
+ | Poffsetint n ->
+ if no_overflow_lsl n 1 then
+ add_const (transl arg) (n lsl 1)
+ else
+ transl_prim_2 Paddint arg (Uconst (Uconst_int n))
+ Debuginfo.none
+ | Poffsetref n ->
+ return_unit
+ (bind "ref" (transl arg) (fun arg ->
+ Cop(Cstore Word_int,
+ [arg; add_const (Cop(Cload Word_int, [arg])) (n lsl 1)])))
+ (* Floating-point operations *)
+ | Pfloatofint ->
+ box_float(Cop(Cfloatofint, [untag_int(transl arg)]))
+ | Pintoffloat ->
+ tag_int(Cop(Cintoffloat, [transl_unbox_float arg]))
+ | Pnegfloat ->
+ box_float(Cop(Cnegf, [transl_unbox_float arg]))
+ | Pabsfloat ->
+ box_float(Cop(Cabsf, [transl_unbox_float arg]))
+ (* String operations *)
+ | Pstringlength ->
+ tag_int(string_length (transl arg))
+ (* Array operations *)
+ | Parraylength kind ->
+ begin match kind with
+ Pgenarray ->
+ let len =
+ if wordsize_shift = numfloat_shift then
+ Cop(Clsr, [header(transl arg); Cconst_int wordsize_shift])
+ else
+ bind "header" (header(transl arg)) (fun hdr ->
+ Cifthenelse(is_addr_array_hdr hdr,
+ Cop(Clsr, [hdr; Cconst_int wordsize_shift]),
+ Cop(Clsr, [hdr; Cconst_int numfloat_shift]))) in
+ Cop(Cor, [len; Cconst_int 1])
+ | Paddrarray | Pintarray ->
+ Cop(Cor, [addr_array_length(header(transl arg)); Cconst_int 1])
+ | Pfloatarray ->
+ Cop(Cor, [float_array_length(header(transl arg)); Cconst_int 1])
+ end
+ (* Boolean operations *)
+ | Pnot ->
+ Cop(Csubi, [Cconst_int 4; transl arg]) (* 1 -> 3, 3 -> 1 *)
+ (* Test integer/block *)
+ | Pisint ->
+ tag_int(Cop(Cand, [transl arg; Cconst_int 1]))
+ (* Boxed integers *)
+ | Pbintofint bi ->
+ box_int bi (untag_int (transl arg))
+ | Pintofbint bi ->
+ force_tag_int (transl_unbox_int bi arg)
+ | Pcvtbint(bi1, bi2) ->
+ box_int bi2 (transl_unbox_int bi1 arg)
+ | Pnegbint bi ->
+ box_int bi (Cop(Csubi, [Cconst_int 0; transl_unbox_int bi arg]))
+ | Pbbswap bi ->
+ let prim = match bi with
+ | Pnativeint -> "nativeint"
+ | Pint32 -> "int32"
+ | Pint64 -> "int64" in
+ box_int bi (Cop(Cextcall(Printf.sprintf "caml_%s_direct_bswap" prim,
+ typ_int, false, Debuginfo.none),
+ [transl_unbox_int bi arg]))
+ | Pbswap16 ->
+ tag_int (Cop(Cextcall("caml_bswap16_direct", typ_int, false,
+ Debuginfo.none),
+ [untag_int (transl arg)]))
+ | _ ->
+ fatal_error "Cmmgen.transl_prim_1"
+
+and transl_prim_2 p arg1 arg2 dbg =
+ match p with
+ (* Heap operations *)
+ Psetfield(n, ptr) ->
+ if ptr then
+ return_unit(Cop(Cextcall("caml_modify", typ_void, false,Debuginfo.none),
+ [field_address (transl arg1) n; transl arg2]))
+ else
+ return_unit(set_field (transl arg1) n (transl arg2))
+ | Psetfloatfield n ->
+ let ptr = transl arg1 in
+ return_unit(
+ Cop(Cstore Double_u,
+ [if n = 0 then ptr
+ else Cop(Cadda, [ptr; Cconst_int(n * size_float)]);
+ transl_unbox_float arg2]))
+
+ (* Boolean operations *)
+ | Psequand ->
+ Cifthenelse(test_bool(transl arg1), transl arg2, Cconst_int 1)
+ (* let id = Ident.create "res1" in
+ Clet(id, transl arg1,
+ Cifthenelse(test_bool(Cvar id), transl arg2, Cvar id)) *)
+ | Psequor ->
+ Cifthenelse(test_bool(transl arg1), Cconst_int 3, transl arg2)
+
+ (* Integer operations *)
+ | Paddint ->
+ decr_int(add_int (transl arg1) (transl arg2))
+ | Psubint ->
+ incr_int(sub_int (transl arg1) (transl arg2))
+ | Pmulint ->
+ begin
+ (* decrementing the non-constant part helps when the multiplication is
+ followed by an addition;
+ for example, using this trick compiles (100 * a + 7) into
+ (+ ( * a 100) -85)
+ rather than
+ (+ ( * 200 (>>s a 1)) 15)
+ *)
+ match transl arg1, transl arg2 with
+ | Cconst_int _ as c1, c2 ->
+ incr_int (mul_int (untag_int c1) (decr_int c2))
+ | c1, c2 -> incr_int (mul_int (decr_int c1) (untag_int c2))
+ end
+ | Pdivint ->
+ tag_int(div_int (untag_int(transl arg1)) (untag_int(transl arg2)) dbg)
+ | Pmodint ->
+ tag_int(mod_int (untag_int(transl arg1)) (untag_int(transl arg2)) dbg)
+ | Pandint ->
+ Cop(Cand, [transl arg1; transl arg2])
+ | Porint ->
+ Cop(Cor, [transl arg1; transl arg2])
+ | Pxorint ->
+ Cop(Cor, [Cop(Cxor, [ignore_low_bit_int(transl arg1);
+ ignore_low_bit_int(transl arg2)]);
+ Cconst_int 1])
+ | Plslint ->
+ incr_int(lsl_int (decr_int(transl arg1)) (untag_int(transl arg2)))
+ | Plsrint ->
+ Cop(Cor, [lsr_int (transl arg1) (untag_int(transl arg2));
+ Cconst_int 1])
+ | Pasrint ->
+ Cop(Cor, [asr_int (transl arg1) (untag_int(transl arg2));
+ Cconst_int 1])
+ | Pintcomp cmp ->
+ tag_int(Cop(Ccmpi(transl_comparison cmp), [transl arg1; transl arg2]))
+ | Pisout ->
+ transl_isout (transl arg1) (transl arg2)
+ (* Float operations *)
+ | Paddfloat ->
+ box_float(Cop(Caddf,
+ [transl_unbox_float arg1; transl_unbox_float arg2]))
+ | Psubfloat ->
+ box_float(Cop(Csubf,
+ [transl_unbox_float arg1; transl_unbox_float arg2]))
+ | Pmulfloat ->
+ box_float(Cop(Cmulf,
+ [transl_unbox_float arg1; transl_unbox_float arg2]))
+ | Pdivfloat ->
+ box_float(Cop(Cdivf,
+ [transl_unbox_float arg1; transl_unbox_float arg2]))
+ | Pfloatcomp cmp ->
+ tag_int(Cop(Ccmpf(transl_comparison cmp),
+ [transl_unbox_float arg1; transl_unbox_float arg2]))
+
+ (* String operations *)
+ | Pstringrefu ->
+ tag_int(Cop(Cload Byte_unsigned,
+ [add_int (transl arg1) (untag_int(transl arg2))]))
+ | Pstringrefs ->
+ tag_int
+ (bind "str" (transl arg1) (fun str ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ Csequence(
+ make_checkbound dbg [string_length str; idx],
+ Cop(Cload Byte_unsigned, [add_int str idx])))))
+
+ | Pstring_load_16(unsafe) ->
+ tag_int
+ (bind "str" (transl arg1) (fun str ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ check_bound unsafe dbg (sub_int (string_length str) (Cconst_int 1))
+ idx (unaligned_load_16 str idx))))
+
+ | Pbigstring_load_16(unsafe) ->
+ tag_int
+ (bind "ba" (transl arg1) (fun ba ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "ba_data" (Cop(Cload Word_int, [field_address ba 1]))
+ (fun ba_data ->
+ check_bound unsafe dbg (sub_int (Cop(Cload Word_int,
+ [field_address ba 5]))
+ (Cconst_int 1)) idx
+ (unaligned_load_16 ba_data idx)))))
+
+ | Pstring_load_32(unsafe) ->
+ box_int Pint32
+ (bind "str" (transl arg1) (fun str ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ check_bound unsafe dbg (sub_int (string_length str) (Cconst_int 3))
+ idx (unaligned_load_32 str idx))))
+
+ | Pbigstring_load_32(unsafe) ->
+ box_int Pint32
+ (bind "ba" (transl arg1) (fun ba ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "ba_data" (Cop(Cload Word_int, [field_address ba 1]))
+ (fun ba_data ->
+ check_bound unsafe dbg (sub_int (Cop(Cload Word_int,
+ [field_address ba 5]))
+ (Cconst_int 3)) idx
+ (unaligned_load_32 ba_data idx)))))
+
+ | Pstring_load_64(unsafe) ->
+ box_int Pint64
+ (bind "str" (transl arg1) (fun str ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ check_bound unsafe dbg (sub_int (string_length str) (Cconst_int 7))
+ idx (unaligned_load_64 str idx))))
+
+ | Pbigstring_load_64(unsafe) ->
+ box_int Pint64
+ (bind "ba" (transl arg1) (fun ba ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "ba_data" (Cop(Cload Word_int, [field_address ba 1]))
+ (fun ba_data ->
+ check_bound unsafe dbg (sub_int (Cop(Cload Word_int,
+ [field_address ba 5]))
+ (Cconst_int 7)) idx
+ (unaligned_load_64 ba_data idx)))))
+
+ (* Array operations *)
+ | Parrayrefu kind ->
+ begin match kind with
+ Pgenarray ->
+ bind "arr" (transl arg1) (fun arr ->
+ bind "index" (transl arg2) (fun idx ->
+ Cifthenelse(is_addr_array_ptr arr,
+ addr_array_ref arr idx,
+ float_array_ref arr idx)))
+ | Paddrarray ->
+ addr_array_ref (transl arg1) (transl arg2)
+ | Pintarray ->
+ int_array_ref (transl arg1) (transl arg2)
+ | Pfloatarray ->
+ float_array_ref (transl arg1) (transl arg2)
+ end
+ | Parrayrefs kind ->
+ begin match kind with
+ | Pgenarray ->
+ bind "index" (transl arg2) (fun idx ->
+ bind "arr" (transl arg1) (fun arr ->
+ bind "header" (header arr) (fun hdr ->
+ if wordsize_shift = numfloat_shift then
+ Csequence(make_checkbound dbg [addr_array_length hdr; idx],
+ Cifthenelse(is_addr_array_hdr hdr,
+ addr_array_ref arr idx,
+ float_array_ref arr idx))
+ else
+ Cifthenelse(is_addr_array_hdr hdr,
+ Csequence(make_checkbound dbg [addr_array_length hdr; idx],
+ addr_array_ref arr idx),
+ Csequence(make_checkbound dbg [float_array_length hdr; idx],
+ float_array_ref arr idx)))))
+ | Paddrarray ->
+ bind "index" (transl arg2) (fun idx ->
+ bind "arr" (transl arg1) (fun arr ->
+ Csequence(make_checkbound dbg [addr_array_length(header arr); idx],
+ addr_array_ref arr idx)))
+ | Pintarray ->
+ bind "index" (transl arg2) (fun idx ->
+ bind "arr" (transl arg1) (fun arr ->
+ Csequence(make_checkbound dbg [addr_array_length(header arr); idx],
+ int_array_ref arr idx)))
+ | Pfloatarray ->
+ box_float(
+ bind "index" (transl arg2) (fun idx ->
+ bind "arr" (transl arg1) (fun arr ->
+ Csequence(make_checkbound dbg
+ [float_array_length(header arr); idx],
+ unboxed_float_array_ref arr idx))))
+ end
+
+ (* Operations on bitvects *)
+ | Pbittest ->
+ bind "index" (untag_int(transl arg2)) (fun idx ->
+ tag_int(
+ Cop(Cand, [Cop(Clsr, [Cop(Cload Byte_unsigned,
+ [add_int (transl arg1)
+ (Cop(Clsr, [idx; Cconst_int 3]))]);
+ Cop(Cand, [idx; Cconst_int 7])]);
+ Cconst_int 1])))
+
+ (* Boxed integers *)
+ | Paddbint bi ->
+ box_int bi (Cop(Caddi,
+ [transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
+ | Psubbint bi ->
+ box_int bi (Cop(Csubi,
+ [transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
+ | Pmulbint bi ->
+ box_int bi (Cop(Cmuli,
+ [transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
+ | Pdivbint bi ->
+ box_int bi (safe_div_bi
+ (transl_unbox_int bi arg1) (transl_unbox_int bi arg2)
+ bi dbg)
+ | Pmodbint bi ->
+ box_int bi (safe_mod_bi
+ (transl_unbox_int bi arg1) (transl_unbox_int bi arg2)
+ bi dbg)
+ | Pandbint bi ->
+ box_int bi (Cop(Cand,
+ [transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
+ | Porbint bi ->
+ box_int bi (Cop(Cor,
+ [transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
+ | Pxorbint bi ->
+ box_int bi (Cop(Cxor,
+ [transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
+ | Plslbint bi ->
+ box_int bi (Cop(Clsl,
+ [transl_unbox_int bi arg1; untag_int(transl arg2)]))
+ | Plsrbint bi ->
+ box_int bi (Cop(Clsr,
+ [make_unsigned_int bi (transl_unbox_int bi arg1);
+ untag_int(transl arg2)]))
+ | Pasrbint bi ->
+ box_int bi (Cop(Casr,
+ [transl_unbox_int bi arg1; untag_int(transl arg2)]))
+ | Pbintcomp(bi, cmp) ->
+ tag_int (Cop(Ccmpi(transl_comparison cmp),
+ [transl_unbox_int bi arg1; transl_unbox_int bi arg2]))
+ | _ ->
+ fatal_error "Cmmgen.transl_prim_2"
+
+and transl_prim_3 p arg1 arg2 arg3 dbg =
+ match p with
+ (* String operations *)
+ Pstringsetu ->
+ return_unit(Cop(Cstore Byte_unsigned,
+ [add_int (transl arg1) (untag_int(transl arg2));
+ untag_int(transl arg3)]))
+ | Pstringsets ->
+ return_unit
+ (bind "str" (transl arg1) (fun str ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ Csequence(
+ make_checkbound dbg [string_length str; idx],
+ Cop(Cstore Byte_unsigned,
+ [add_int str idx; untag_int(transl arg3)])))))
+
+ (* Array operations *)
+ | Parraysetu kind ->
+ return_unit(begin match kind with
+ Pgenarray ->
+ bind "newval" (transl arg3) (fun newval ->
+ bind "index" (transl arg2) (fun index ->
+ bind "arr" (transl arg1) (fun arr ->
+ Cifthenelse(is_addr_array_ptr arr,
+ addr_array_set arr index newval,
+ float_array_set arr index (unbox_float newval)))))
+ | Paddrarray ->
+ addr_array_set (transl arg1) (transl arg2) (transl arg3)
+ | Pintarray ->
+ int_array_set (transl arg1) (transl arg2) (transl arg3)
+ | Pfloatarray ->
+ float_array_set (transl arg1) (transl arg2) (transl_unbox_float arg3)
+ end)
+ | Parraysets kind ->
+ return_unit(begin match kind with
+ | Pgenarray ->
+ bind "newval" (transl arg3) (fun newval ->
+ bind "index" (transl arg2) (fun idx ->
+ bind "arr" (transl arg1) (fun arr ->
+ bind "header" (header arr) (fun hdr ->
+ if wordsize_shift = numfloat_shift then
+ Csequence(make_checkbound dbg [addr_array_length hdr; idx],
+ Cifthenelse(is_addr_array_hdr hdr,
+ addr_array_set arr idx newval,
+ float_array_set arr idx
+ (unbox_float newval)))
+ else
+ Cifthenelse(is_addr_array_hdr hdr,
+ Csequence(make_checkbound dbg [addr_array_length hdr; idx],
+ addr_array_set arr idx newval),
+ Csequence(make_checkbound dbg [float_array_length hdr; idx],
+ float_array_set arr idx
+ (unbox_float newval)))))))
+ | Paddrarray ->
+ bind "newval" (transl arg3) (fun newval ->
+ bind "index" (transl arg2) (fun idx ->
+ bind "arr" (transl arg1) (fun arr ->
+ Csequence(make_checkbound dbg [addr_array_length(header arr); idx],
+ addr_array_set arr idx newval))))
+ | Pintarray ->
+ bind "newval" (transl arg3) (fun newval ->
+ bind "index" (transl arg2) (fun idx ->
+ bind "arr" (transl arg1) (fun arr ->
+ Csequence(make_checkbound dbg [addr_array_length(header arr); idx],
+ int_array_set arr idx newval))))
+ | Pfloatarray ->
+ bind_load "newval" (transl_unbox_float arg3) (fun newval ->
+ bind "index" (transl arg2) (fun idx ->
+ bind "arr" (transl arg1) (fun arr ->
+ Csequence(make_checkbound dbg [float_array_length(header arr);idx],
+ float_array_set arr idx newval))))
+ end)
+
+ | Pstring_set_16(unsafe) ->
+ return_unit
+ (bind "str" (transl arg1) (fun str ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "newval" (untag_int (transl arg3)) (fun newval ->
+ check_bound unsafe dbg (sub_int (string_length str) (Cconst_int 1))
+ idx (unaligned_set_16 str idx newval)))))
+
+ | Pbigstring_set_16(unsafe) ->
+ return_unit
+ (bind "ba" (transl arg1) (fun ba ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "newval" (untag_int (transl arg3)) (fun newval ->
+ bind "ba_data" (Cop(Cload Word_int, [field_address ba 1]))
+ (fun ba_data ->
+ check_bound unsafe dbg (sub_int (Cop(Cload Word_int,
+ [field_address ba 5]))
+ (Cconst_int 1))
+ idx (unaligned_set_16 ba_data idx newval))))))
+
+ | Pstring_set_32(unsafe) ->
+ return_unit
+ (bind "str" (transl arg1) (fun str ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "newval" (transl_unbox_int Pint32 arg3) (fun newval ->
+ check_bound unsafe dbg (sub_int (string_length str) (Cconst_int 3))
+ idx (unaligned_set_32 str idx newval)))))
+
+ | Pbigstring_set_32(unsafe) ->
+ return_unit
+ (bind "ba" (transl arg1) (fun ba ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "newval" (transl_unbox_int Pint32 arg3) (fun newval ->
+ bind "ba_data" (Cop(Cload Word_int, [field_address ba 1]))
+ (fun ba_data ->
+ check_bound unsafe dbg (sub_int (Cop(Cload Word_int,
+ [field_address ba 5]))
+ (Cconst_int 3))
+ idx (unaligned_set_32 ba_data idx newval))))))
+
+ | Pstring_set_64(unsafe) ->
+ return_unit
+ (bind "str" (transl arg1) (fun str ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "newval" (transl_unbox_int Pint64 arg3) (fun newval ->
+ check_bound unsafe dbg (sub_int (string_length str) (Cconst_int 7))
+ idx (unaligned_set_64 str idx newval)))))
+
+ | Pbigstring_set_64(unsafe) ->
+ return_unit
+ (bind "ba" (transl arg1) (fun ba ->
+ bind "index" (untag_int (transl arg2)) (fun idx ->
+ bind "newval" (transl_unbox_int Pint64 arg3) (fun newval ->
+ bind "ba_data" (Cop(Cload Word_int, [field_address ba 1]))
+ (fun ba_data ->
+ check_bound unsafe dbg (sub_int (Cop(Cload Word_int,
+ [field_address ba 5]))
+ (Cconst_int 7)) idx
+ (unaligned_set_64 ba_data idx newval))))))
+
+ | _ ->
+ fatal_error "Cmmgen.transl_prim_3"
+
+and transl_unbox_float = function
+ Uconst(Uconst_ref(_, Uconst_float f)) -> Cconst_float f
+ | exp -> unbox_float(transl exp)
+
+and transl_unbox_int bi = function
+ Uconst(Uconst_ref(_, Uconst_int32 n)) ->
+ Cconst_natint (Nativeint.of_int32 n)
+ | Uconst(Uconst_ref(_, Uconst_nativeint n)) ->
+ Cconst_natint n
+ | Uconst(Uconst_ref(_, Uconst_int64 n)) ->
+ if size_int = 8 then
+ Cconst_natint (Int64.to_nativeint n)
+ else
+ let low = Int64.to_nativeint n in
+ let high = Int64.to_nativeint (Int64.shift_right_logical n 32) in
+ Ctuple [Cconst_natint low; Cconst_natint high]
+ | Uprim(Pbintofint bi',[Uconst(Uconst_int i)],_) when bi = bi' ->
+ Cconst_int i
+ | exp -> unbox_int bi (transl exp)
+
+and transl_unbox_number bn arg =
+ match bn with
+ | Boxed_float -> transl_unbox_float arg
+ | Boxed_integer bi -> transl_unbox_int bi arg
+
+and transl_let id exp tr_body =
+ match is_unboxed_number exp with
+ | No_unboxing ->
+ Clet(id, transl exp, tr_body)
+ | No_result ->
+ (* the let-bound expression never returns a value, we can ignore
+ the body *)
+ transl exp
+ | Boxed boxed_number ->
+ let unboxed_id = Ident.create (Ident.name id) in
+ let subst_body =
+ subst_boxed_number boxed_number id unboxed_id tr_body
+ in
+ Clet(unboxed_id, transl_unbox_number boxed_number exp, subst_body)
+
+and make_catch ncatch body handler = match body with
+| Cexit (nexit,[]) when nexit=ncatch -> handler
+| _ -> Ccatch (ncatch, [], body, handler)
+
+and make_catch2 mk_body handler = match handler with
+| Cexit (_,[])|Ctuple []|Cconst_int _|Cconst_pointer _ ->
+ mk_body handler
+| _ ->
+ let nfail = next_raise_count () in
+ make_catch
+ nfail
+ (mk_body (Cexit (nfail,[])))
+ handler
+
+and exit_if_true cond nfail otherwise =
+ match cond with
+ | Uconst (Uconst_ptr 0) -> otherwise
+ | Uconst (Uconst_ptr 1) -> Cexit (nfail,[])
+ | Uprim(Psequor, [arg1; arg2], _) ->
+ exit_if_true arg1 nfail (exit_if_true arg2 nfail otherwise)
+ | Uprim(Psequand, _, _) ->
+ begin match otherwise with
+ | Cexit (raise_num,[]) ->
+ exit_if_false cond (Cexit (nfail,[])) raise_num
+ | _ ->
+ let raise_num = next_raise_count () in
+ make_catch
+ raise_num
+ (exit_if_false cond (Cexit (nfail,[])) raise_num)
+ otherwise
+ end
+ | Uprim(Pnot, [arg], _) ->
+ exit_if_false arg otherwise nfail
+ | Uifthenelse (cond, ifso, ifnot) ->
+ make_catch2
+ (fun shared ->
+ Cifthenelse
+ (test_bool (transl cond),
+ exit_if_true ifso nfail shared,
+ exit_if_true ifnot nfail shared))
+ otherwise
+ | _ ->
+ Cifthenelse(test_bool(transl cond), Cexit (nfail, []), otherwise)
+
+and exit_if_false cond otherwise nfail =
+ match cond with
+ | Uconst (Uconst_ptr 0) -> Cexit (nfail,[])
+ | Uconst (Uconst_ptr 1) -> otherwise
+ | Uprim(Psequand, [arg1; arg2], _) ->
+ exit_if_false arg1 (exit_if_false arg2 otherwise nfail) nfail
+ | Uprim(Psequor, _, _) ->
+ begin match otherwise with
+ | Cexit (raise_num,[]) ->
+ exit_if_true cond raise_num (Cexit (nfail,[]))
+ | _ ->
+ let raise_num = next_raise_count () in
+ make_catch
+ raise_num
+ (exit_if_true cond raise_num (Cexit (nfail,[])))
+ otherwise
+ end
+ | Uprim(Pnot, [arg], _) ->
+ exit_if_true arg nfail otherwise
+ | Uifthenelse (cond, ifso, ifnot) ->
+ make_catch2
+ (fun shared ->
+ Cifthenelse
+ (test_bool (transl cond),
+ exit_if_false ifso shared nfail,
+ exit_if_false ifnot shared nfail))
+ otherwise
+ | _ ->
+ Cifthenelse(test_bool(transl cond), otherwise, Cexit (nfail, []))
+
+and transl_switch arg index cases = match Array.length cases with
+| 0 -> fatal_error "Cmmgen.transl_switch"
+| 1 -> transl cases.(0)
+| _ ->
+ let cases = Array.map transl cases in
+ let store = StoreExp.mk_store () in
+ let index =
+ Array.map
+ (fun j -> store.Switch.act_store cases.(j))
+ index in
+ let n_index = Array.length index in
+ let inters = ref []
+ and this_high = ref (n_index-1)
+ and this_low = ref (n_index-1)
+ and this_act = ref index.(n_index-1) in
+ for i = n_index-2 downto 0 do
+ let act = index.(i) in
+ if act = !this_act then
+ decr this_low
+ else begin
+ inters := (!this_low, !this_high, !this_act) :: !inters ;
+ this_high := i ;
+ this_low := i ;
+ this_act := act
+ end
+ done ;
+ inters := (0, !this_high, !this_act) :: !inters ;
+ match !inters with
+ | [_] -> cases.(0)
+ | inters ->
+ bind "switcher" arg
+ (fun a ->
+ SwitcherBlocks.zyva
+ (0,n_index-1)
+ a
+ (Array.of_list inters) store)
+
+and transl_letrec bindings cont =
+ let bsz =
+ List.map (fun (id, exp) -> (id, exp, expr_size Ident.empty exp)) bindings in
+ let op_alloc prim sz =
+ Cop(Cextcall(prim, typ_val, true, Debuginfo.none), [int_const sz]) in
+ let rec init_blocks = function
+ | [] -> fill_nonrec bsz
+ | (id, exp, RHS_block sz) :: rem ->
+ Clet(id, op_alloc "caml_alloc_dummy" sz, init_blocks rem)
+ | (id, exp, RHS_floatblock sz) :: rem ->
+ Clet(id, op_alloc "caml_alloc_dummy_float" sz, init_blocks rem)
+ | (id, exp, RHS_nonrec) :: rem ->
+ Clet (id, Cconst_int 0, init_blocks rem)
+ and fill_nonrec = function
+ | [] -> fill_blocks bsz
+ | (id, exp, (RHS_block _ | RHS_floatblock _)) :: rem ->
+ fill_nonrec rem
+ | (id, exp, RHS_nonrec) :: rem ->
+ transl_let id exp (fill_nonrec rem)
+ and fill_blocks = function
+ | [] -> cont
+ | (id, exp, (RHS_block _ | RHS_floatblock _)) :: rem ->
+ let op =
+ Cop(Cextcall("caml_update_dummy", typ_void, false, Debuginfo.none),
+ [Cvar id; transl exp]) in
+ Csequence(op, fill_blocks rem)
+ | (id, exp, RHS_nonrec) :: rem ->
+ fill_blocks rem
+ in init_blocks bsz
+
+(* Translate a function definition *)
+
+let transl_function f =
+ Cfunction {fun_name = f.label;
+ fun_args = List.map (fun id -> (id, typ_val)) f.params;
+ fun_body = transl f.body;
+ fun_fast = !Clflags.optimize_for_speed;
+ fun_dbg = f.dbg; }
+
+(* Translate all function definitions *)
+
+module StringSet =
+ Set.Make(struct
+ type t = string
+ let compare (x:t) y = compare x y
+ end)
+
+let rec transl_all_functions already_translated cont =
+ try
+ let f = Queue.take functions in
+ if StringSet.mem f.label already_translated then
+ transl_all_functions already_translated cont
+ else begin
+ transl_all_functions
+ (StringSet.add f.label already_translated)
+ (transl_function f :: cont)
+ end
+ with Queue.Empty ->
+ cont
+
+(* Emit structured constants *)
+
+let rec emit_structured_constant symb cst cont =
+ let emit_block white_header symb cont =
+ (* Headers for structured constants must be marked black in case we
+ are in no-naked-pointers mode. See [caml_darken]. *)
+ let black_header = Nativeint.logor white_header caml_black in
+ Cint black_header :: Cdefine_symbol symb :: cont
+ in
+ match cst with
+ | Uconst_float s->
+ emit_block float_header symb (Cdouble s :: cont)
+ | Uconst_string s ->
+ emit_block (string_header (String.length s)) symb
+ (emit_string_constant s cont)
+ | Uconst_int32 n ->
+ emit_block boxedint32_header symb
+ (emit_boxed_int32_constant n cont)
+ | Uconst_int64 n ->
+ emit_block boxedint64_header symb
+ (emit_boxed_int64_constant n cont)
+ | Uconst_nativeint n ->
+ emit_block boxedintnat_header symb
+ (emit_boxed_nativeint_constant n cont)
+ | Uconst_block (tag, csts) ->
+ let cont = List.fold_right emit_constant csts cont in
+ emit_block (block_header tag (List.length csts)) symb cont
+ | Uconst_float_array fields ->
+ emit_block (floatarray_header (List.length fields)) symb
+ (Misc.map_end (fun f -> Cdouble f) fields cont)
+
+and emit_constant cst cont =
+ match cst with
+ | Uconst_int n | Uconst_ptr n ->
+ Cint(Nativeint.add (Nativeint.shift_left (Nativeint.of_int n) 1) 1n)
+ :: cont
+ | Uconst_ref (label, _) ->
+ Csymbol_address label :: cont
+
+and emit_string_constant s cont =
+ let n = size_int - 1 - (String.length s) mod size_int in
+ Cstring s :: Cskip n :: Cint8 n :: cont
+
+and emit_boxed_int32_constant n cont =
+ let n = Nativeint.of_int32 n in
+ if size_int = 8 then
+ Csymbol_address("caml_int32_ops") :: Cint32 n :: Cint32 0n :: cont
+ else
+ Csymbol_address("caml_int32_ops") :: Cint n :: cont
+
+and emit_boxed_nativeint_constant n cont =
+ Csymbol_address("caml_nativeint_ops") :: Cint n :: cont
+
+and emit_boxed_int64_constant n cont =
+ let lo = Int64.to_nativeint n in
+ if size_int = 8 then
+ Csymbol_address("caml_int64_ops") :: Cint lo :: cont
+ else begin
+ let hi = Int64.to_nativeint (Int64.shift_right n 32) in
+ if big_endian then
+ Csymbol_address("caml_int64_ops") :: Cint hi :: Cint lo :: cont
+ else
+ Csymbol_address("caml_int64_ops") :: Cint lo :: Cint hi :: cont
+ end
+
+(* Emit constant closures *)
+
+let emit_constant_closure symb fundecls cont =
+ match fundecls with
+ [] -> assert false
+ | f1 :: remainder ->
+ let rec emit_others pos = function
+ [] -> cont
+ | f2 :: rem ->
+ if f2.arity = 1 then
+ Cint(infix_header pos) ::
+ Csymbol_address f2.label ::
+ Cint 3n ::
+ emit_others (pos + 3) rem
+ else
+ Cint(infix_header pos) ::
+ Csymbol_address(curry_function f2.arity) ::
+ Cint(Nativeint.of_int (f2.arity lsl 1 + 1)) ::
+ Csymbol_address f2.label ::
+ emit_others (pos + 4) rem in
+ Cint(black_closure_header (fundecls_size fundecls)) ::
+ Cdefine_symbol symb ::
+ if f1.arity = 1 then
+ Csymbol_address f1.label ::
+ Cint 3n ::
+ emit_others 3 remainder
+ else
+ Csymbol_address(curry_function f1.arity) ::
+ Cint(Nativeint.of_int (f1.arity lsl 1 + 1)) ::
+ Csymbol_address f1.label ::
+ emit_others 4 remainder
+
+(* Emit all structured constants *)
+
+let emit_all_constants cont =
+ let c = ref cont in
+ List.iter
+ (fun (lbl, global, cst) ->
+ let cst = emit_structured_constant lbl cst [] in
+ let cst = if global then
+ Cglobal_symbol lbl :: cst
+ else cst in
+ c:= Cdata(cst):: !c)
+ (Compilenv.structured_constants());
+ List.iter
+ (fun (symb, fundecls) ->
+ c := Cdata(emit_constant_closure symb fundecls []) :: !c)
+ !constant_closures;
+ constant_closures := [];
+ !c
+
+(* Translate a compilation unit *)
+
+let compunit size ulam =
+ let glob = Compilenv.make_symbol None in
+ let init_code = transl ulam in
+ let c1 = [Cfunction {fun_name = Compilenv.make_symbol (Some "entry");
+ fun_args = [];
+ fun_body = init_code; fun_fast = false;
+ fun_dbg = Debuginfo.none }] in
+ let c2 = transl_all_functions StringSet.empty c1 in
+ let c3 = emit_all_constants c2 in
+ let space =
+ (* These words will be registered as roots and as such must contain
+ valid values, in case we are in no-naked-pointers mode. Likewise
+ the block header must be black, below (see [caml_darken]), since
+ the overall record may be referenced. *)
+ Array.to_list
+ (Array.init size (fun _index ->
+ Cint (Nativeint.of_int 1 (* Val_unit *))))
+ in
+ Cdata ([Cint(black_block_header 0 size);
+ Cglobal_symbol glob;
+ Cdefine_symbol glob] @ space) :: c3
+
+(*
+CAMLprim value caml_cache_public_method (value meths, value tag, value *cache)
+{
+ int li = 3, hi = Field(meths,0), mi;
+ while (li < hi) { // no need to check the 1st time
+ mi = ((li+hi) >> 1) | 1;
+ if (tag < Field(meths,mi)) hi = mi-2;
+ else li = mi;
+ }
+ *cache = (li-3)*sizeof(value)+1;
+ return Field (meths, li-1);
+}
+*)
+
+let cache_public_method meths tag cache =
+ let raise_num = next_raise_count () in
+ let li = Ident.create "li" and hi = Ident.create "hi"
+ and mi = Ident.create "mi" and tagged = Ident.create "tagged" in
+ Clet (
+ li, Cconst_int 3,
+ Clet (
+ hi, Cop(Cload Word_int, [meths]),
+ Csequence(
+ Ccatch
+ (raise_num, [],
+ Cloop
+ (Clet(
+ mi,
+ Cop(Cor,
+ [Cop(Clsr, [Cop(Caddi, [Cvar li; Cvar hi]); Cconst_int 1]);
+ Cconst_int 1]),
+ Csequence(
+ Cifthenelse
+ (Cop (Ccmpi Clt,
+ [tag;
+ Cop(Cload Word_int,
+ [Cop(Cadda,
+ [meths; lsl_const (Cvar mi) log2_size_addr])])]),
+ Cassign(hi, Cop(Csubi, [Cvar mi; Cconst_int 2])),
+ Cassign(li, Cvar mi)),
+ Cifthenelse
+ (Cop(Ccmpi Cge, [Cvar li; Cvar hi]), Cexit (raise_num, []),
+ Ctuple [])))),
+ Ctuple []),
+ Clet (
+ tagged, Cop(Cadda, [lsl_const (Cvar li) log2_size_addr;
+ Cconst_int(1 - 3 * size_addr)]),
+ Csequence(Cop (Cstore Word_int, [cache; Cvar tagged]),
+ Cvar tagged)))))
+
+(* Generate an application function:
+ (defun caml_applyN (a1 ... aN clos)
+ (if (= clos.arity N)
+ (app clos.direct a1 ... aN clos)
+ (let (clos1 (app clos.code a1 clos)
+ clos2 (app clos1.code a2 clos)
+ ...
+ closN-1 (app closN-2.code aN-1 closN-2))
+ (app closN-1.code aN closN-1))))
+*)
+
+let apply_function_body arity =
+ let arg = Array.make arity (Ident.create "arg") in
+ for i = 1 to arity - 1 do arg.(i) <- Ident.create "arg" done;
+ let clos = Ident.create "clos" in
+ let rec app_fun clos n =
+ if n = arity-1 then
+ Cop(Capply(typ_val, Debuginfo.none),
+ [get_field (Cvar clos) 0; Cvar arg.(n); Cvar clos])
+ else begin
+ let newclos = Ident.create "clos" in
+ Clet(newclos,
+ Cop(Capply(typ_val, Debuginfo.none),
+ [get_field (Cvar clos) 0; Cvar arg.(n); Cvar clos]),
+ app_fun newclos (n+1))
+ end in
+ let args = Array.to_list arg in
+ let all_args = args @ [clos] in
+ (args, clos,
+ if arity = 1 then app_fun clos 0 else
+ Cifthenelse(
+ Cop(Ccmpi Ceq, [get_field (Cvar clos) 1; int_const arity]),
+ Cop(Capply(typ_val, Debuginfo.none),
+ get_field (Cvar clos) 2 :: List.map (fun s -> Cvar s) all_args),
+ app_fun clos 0))
+
+let send_function arity =
+ let (args, clos', body) = apply_function_body (1+arity) in
+ let cache = Ident.create "cache"
+ and obj = List.hd args
+ and tag = Ident.create "tag" in
+ let clos =
+ let cache = Cvar cache and obj = Cvar obj and tag = Cvar tag in
+ let meths = Ident.create "meths" and cached = Ident.create "cached" in
+ let real = Ident.create "real" in
+ let mask = get_field (Cvar meths) 1 in
+ let cached_pos = Cvar cached in
+ let tag_pos = Cop(Cadda, [Cop (Cadda, [cached_pos; Cvar meths]);
+ Cconst_int(3*size_addr-1)]) in
+ let tag' = Cop(Cload Word_int, [tag_pos]) in
+ Clet (
+ meths, Cop(Cload Word_val, [obj]),
+ Clet (
+ cached, Cop(Cand, [Cop(Cload Word_int, [cache]); mask]),
+ Clet (
+ real,
+ Cifthenelse(Cop(Ccmpa Cne, [tag'; tag]),
+ cache_public_method (Cvar meths) tag cache,
+ cached_pos),
+ Cop(Cload Word_val, [Cop(Cadda, [Cop (Cadda, [Cvar real; Cvar meths]);
+ Cconst_int(2*size_addr-1)])]))))
+
+ in
+ let body = Clet(clos', clos, body) in
+ let fun_args =
+ [obj, typ_val; tag, typ_int; cache, typ_val]
+ @ List.map (fun id -> (id, typ_val)) (List.tl args) in
+ Cfunction
+ {fun_name = "caml_send" ^ string_of_int arity;
+ fun_args = fun_args;
+ fun_body = body;
+ fun_fast = true;
+ fun_dbg = Debuginfo.none }
+
+let apply_function arity =
+ let (args, clos, body) = apply_function_body arity in
+ let all_args = args @ [clos] in
+ Cfunction
+ {fun_name = "caml_apply" ^ string_of_int arity;
+ fun_args = List.map (fun id -> (id, typ_val)) all_args;
+ fun_body = body;
+ fun_fast = true;
+ fun_dbg = Debuginfo.none }
+
+(* Generate tuplifying functions:
+ (defun caml_tuplifyN (arg clos)
+ (app clos.direct #0(arg) ... #N-1(arg) clos)) *)
+
+let tuplify_function arity =
+ let arg = Ident.create "arg" in
+ let clos = Ident.create "clos" in
+ let rec access_components i =
+ if i >= arity
+ then []
+ else get_field (Cvar arg) i :: access_components(i+1) in
+ Cfunction
+ {fun_name = "caml_tuplify" ^ string_of_int arity;
+ fun_args = [arg, typ_val; clos, typ_val];
+ fun_body =
+ Cop(Capply(typ_val, Debuginfo.none),
+ get_field (Cvar clos) 2 :: access_components 0 @ [Cvar clos]);
+ fun_fast = true;
+ fun_dbg = Debuginfo.none }
+
+(* Generate currying functions:
+ (defun caml_curryN (arg clos)
+ (alloc HDR caml_curryN_1 <arity (N-1)> caml_curry_N_1_app arg clos))
+ (defun caml_curryN_1 (arg clos)
+ (alloc HDR caml_curryN_2 <arity (N-2)> caml_curry_N_2_app arg clos))
+ ...
+ (defun caml_curryN_N-1 (arg clos)
+ (let (closN-2 clos.vars[1]
+ closN-3 closN-2.vars[1]
+ ...
+ clos1 clos2.vars[1]
+ clos clos1.vars[1])
+ (app clos.direct
+ clos1.vars[0] ... closN-2.vars[0] clos.vars[0] arg clos)))
+
+ Special "shortcut" functions are also generated to handle the
+ case where a partially applied function is applied to all remaining
+ arguments in one go. For instance:
+ (defun caml_curry_N_1_app (arg2 ... argN clos)
+ (let clos' clos.vars[1]
+ (app clos'.direct clos.vars[0] arg2 ... argN clos')))
+
+ Those shortcuts may lead to a quadratic number of application
+ primitives being generated in the worst case, which resulted in
+ linking time blowup in practice (PR#5933), so we only generate and
+ use them when below a fixed arity 'max_arity_optimized'.
+*)
+
+let max_arity_optimized = 15
+let final_curry_function arity =
+ let last_arg = Ident.create "arg" in
+ let last_clos = Ident.create "clos" in
+ let rec curry_fun args clos n =
+ if n = 0 then
+ Cop(Capply(typ_val, Debuginfo.none),
+ get_field (Cvar clos) 2 ::
+ args @ [Cvar last_arg; Cvar clos])
+ else
+ if n = arity - 1 || arity > max_arity_optimized then
+ begin
+ let newclos = Ident.create "clos" in
+ Clet(newclos,
+ get_field (Cvar clos) 3,
+ curry_fun (get_field (Cvar clos) 2 :: args) newclos (n-1))
+ end else
+ begin
+ let newclos = Ident.create "clos" in
+ Clet(newclos,
+ get_field (Cvar clos) 4,
+ curry_fun (get_field (Cvar clos) 3 :: args) newclos (n-1))
+ end in
+ Cfunction
+ {fun_name = "caml_curry" ^ string_of_int arity ^
+ "_" ^ string_of_int (arity-1);
+ fun_args = [last_arg, typ_val; last_clos, typ_val];
+ fun_body = curry_fun [] last_clos (arity-1);
+ fun_fast = true;
+ fun_dbg = Debuginfo.none }
+
+let rec intermediate_curry_functions arity num =
+ if num = arity - 1 then
+ [final_curry_function arity]
+ else begin
+ let name1 = "caml_curry" ^ string_of_int arity in
+ let name2 = if num = 0 then name1 else name1 ^ "_" ^ string_of_int num in
+ let arg = Ident.create "arg" and clos = Ident.create "clos" in
+ Cfunction
+ {fun_name = name2;
+ fun_args = [arg, typ_val; clos, typ_val];
+ fun_body =
+ if arity - num > 2 && arity <= max_arity_optimized then
+ Cop(Calloc,
+ [alloc_closure_header 5;
+ Cconst_symbol(name1 ^ "_" ^ string_of_int (num+1));
+ int_const (arity - num - 1);
+ Cconst_symbol(name1 ^ "_" ^ string_of_int (num+1) ^ "_app");
+ Cvar arg; Cvar clos])
+ else
+ Cop(Calloc,
+ [alloc_closure_header 4;
+ Cconst_symbol(name1 ^ "_" ^ string_of_int (num+1));
+ int_const 1; Cvar arg; Cvar clos]);
+ fun_fast = true;
+ fun_dbg = Debuginfo.none }
+ ::
+ (if arity <= max_arity_optimized && arity - num > 2 then
+ let rec iter i =
+ if i <= arity then
+ let arg = Ident.create (Printf.sprintf "arg%d" i) in
+ (arg, typ_val) :: iter (i+1)
+ else []
+ in
+ let direct_args = iter (num+2) in
+ let rec iter i args clos =
+ if i = 0 then
+ Cop(Capply(typ_val, Debuginfo.none),
+ (get_field (Cvar clos) 2) :: args @ [Cvar clos])
+ else
+ let newclos = Ident.create "clos" in
+ Clet(newclos,
+ get_field (Cvar clos) 4,
+ iter (i-1) (get_field (Cvar clos) 3 :: args) newclos)
+ in
+ let cf =
+ Cfunction
+ {fun_name = name1 ^ "_" ^ string_of_int (num+1) ^ "_app";
+ fun_args = direct_args @ [clos, typ_val];
+ fun_body = iter (num+1)
+ (List.map (fun (arg,_) -> Cvar arg) direct_args) clos;
+ fun_fast = true;
+ fun_dbg = Debuginfo.none }
+ in
+ cf :: intermediate_curry_functions arity (num+1)
+ else
+ intermediate_curry_functions arity (num+1))
+ end
+
+let curry_function arity =
+ if arity >= 0
+ then intermediate_curry_functions arity 0
+ else [tuplify_function (-arity)]
+
+
+module IntSet = Set.Make(
+ struct
+ type t = int
+ let compare (x:t) y = compare x y
+ end)
+
+let default_apply = IntSet.add 2 (IntSet.add 3 IntSet.empty)
+ (* These apply funs are always present in the main program because
+ the run-time system needs them (cf. asmrun/<arch>.S) . *)
+
+let generic_functions shared units =
+ let (apply,send,curry) =
+ List.fold_left
+ (fun (apply,send,curry) ui ->
+ List.fold_right IntSet.add ui.ui_apply_fun apply,
+ List.fold_right IntSet.add ui.ui_send_fun send,
+ List.fold_right IntSet.add ui.ui_curry_fun curry)
+ (IntSet.empty,IntSet.empty,IntSet.empty)
+ units in
+ let apply = if shared then apply else IntSet.union apply default_apply in
+ let accu = IntSet.fold (fun n accu -> apply_function n :: accu) apply [] in
+ let accu = IntSet.fold (fun n accu -> send_function n :: accu) send accu in
+ IntSet.fold (fun n accu -> curry_function n @ accu) curry accu
+
+(* Generate the entry point *)
+
+let entry_point namelist =
+ let incr_global_inited =
+ Cop(Cstore Word_int,
+ [Cconst_symbol "caml_globals_inited";
+ Cop(Caddi, [Cop(Cload Word_int, [Cconst_symbol "caml_globals_inited"]);
+ Cconst_int 1])]) in
+ let body =
+ List.fold_right
+ (fun name next ->
+ let entry_sym = Compilenv.make_symbol ~unitname:name (Some "entry") in
+ Csequence(Cop(Capply(typ_void, Debuginfo.none),
+ [Cconst_symbol entry_sym]),
+ Csequence(incr_global_inited, next)))
+ namelist (Cconst_int 1) in
+ Cfunction {fun_name = "caml_program";
+ fun_args = [];
+ fun_body = body;
+ fun_fast = false;
+ fun_dbg = Debuginfo.none }
+
+(* Generate the table of globals *)
+
+let cint_zero = Cint 0n
+
+let global_table namelist =
+ let mksym name =
+ Csymbol_address (Compilenv.make_symbol ~unitname:name None)
+ in
+ Cdata(Cglobal_symbol "caml_globals" ::
+ Cdefine_symbol "caml_globals" ::
+ List.map mksym namelist @
+ [cint_zero])
+
+let reference_symbols namelist =
+ let mksym name = Csymbol_address name in
+ Cdata(List.map mksym namelist)
+
+let global_data name v =
+ Cdata(Cglobal_symbol name ::
+ emit_structured_constant name
+ (Uconst_string (Marshal.to_string v [])) [])
+
+let globals_map v = global_data "caml_globals_map" v
+
+(* Generate the master table of frame descriptors *)
+
+let frame_table namelist =
+ let mksym name =
+ Csymbol_address (Compilenv.make_symbol ~unitname:name (Some "frametable"))
+ in
+ Cdata(Cglobal_symbol "caml_frametable" ::
+ Cdefine_symbol "caml_frametable" ::
+ List.map mksym namelist
+ @ [cint_zero])
+
+(* Generate the table of module data and code segments *)
+
+let segment_table namelist symbol begname endname =
+ let addsyms name lst =
+ Csymbol_address (Compilenv.make_symbol ~unitname:name (Some begname)) ::
+ Csymbol_address (Compilenv.make_symbol ~unitname:name (Some endname)) ::
+ lst
+ in
+ Cdata(Cglobal_symbol symbol ::
+ Cdefine_symbol symbol ::
+ List.fold_right addsyms namelist [cint_zero])
+
+let data_segment_table namelist =
+ segment_table namelist "caml_data_segments" "data_begin" "data_end"
+
+let code_segment_table namelist =
+ segment_table namelist "caml_code_segments" "code_begin" "code_end"
+
+(* Initialize a predefined exception *)
+
+let predef_exception i name =
+ let symname = "caml_exn_" ^ name in
+ let cst = Uconst_string name in
+ let label = Compilenv.new_const_symbol () in
+ let cont = emit_structured_constant label cst [] in
+ Cdata(Cglobal_symbol symname ::
+ emit_structured_constant symname
+ (Uconst_block(Obj.object_tag,
+ [
+ Uconst_ref(label, cst);
+ Uconst_int (-i-1);
+ ])) cont)
+
+(* Header for a plugin *)
+
+let mapflat f l = List.flatten (List.map f l)
+
+let plugin_header units =
+ let mk (ui,crc) =
+ { dynu_name = ui.ui_name;
+ dynu_crc = crc;
+ dynu_imports_cmi = ui.ui_imports_cmi;
+ dynu_imports_cmx = ui.ui_imports_cmx;
+ dynu_defines = ui.ui_defines
+ } in
+ global_data "caml_plugin_header"
+ { dynu_magic = Config.cmxs_magic_number; dynu_units = List.map mk units }
diff --git a/asmcomp/cmmgen.mli b/asmcomp/cmmgen.mli
new file mode 100644
index 0000000000..46f9496655
--- /dev/null
+++ b/asmcomp/cmmgen.mli
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translation from closed lambda to C-- *)
+
+val compunit: int -> Clambda.ulambda -> Cmm.phrase list
+
+val apply_function: int -> Cmm.phrase
+val send_function: int -> Cmm.phrase
+val curry_function: int -> Cmm.phrase list
+val generic_functions: bool -> Cmx_format.unit_infos list -> Cmm.phrase list
+val entry_point: string list -> Cmm.phrase
+val global_table: string list -> Cmm.phrase
+val reference_symbols: string list -> Cmm.phrase
+val globals_map: (string * Digest.t * Digest.t * string list) list ->
+ Cmm.phrase
+val frame_table: string list -> Cmm.phrase
+val data_segment_table: string list -> Cmm.phrase
+val code_segment_table: string list -> Cmm.phrase
+val predef_exception: int -> string -> Cmm.phrase
+val plugin_header: (Cmx_format.unit_infos * Digest.t) list -> Cmm.phrase
diff --git a/asmcomp/cmx_format.mli b/asmcomp/cmx_format.mli
new file mode 100644
index 0000000000..51aa044083
--- /dev/null
+++ b/asmcomp/cmx_format.mli
@@ -0,0 +1,61 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2010 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Format of .cmx, .cmxa and .cmxs files *)
+
+(* Each .o file has a matching .cmx file that provides the following infos
+ on the compilation unit:
+ - list of other units imported, with MD5s of their .cmx files
+ - approximation of the structure implemented
+ (includes descriptions of known functions: arity and direct entry
+ points)
+ - list of currying functions and application functions needed
+ The .cmx file contains these infos (as an externed record) plus a MD5
+ of these infos *)
+
+type unit_infos =
+ { mutable ui_name: string; (* Name of unit implemented *)
+ mutable ui_symbol: string; (* Prefix for symbols *)
+ mutable ui_defines: string list; (* Unit and sub-units implemented *)
+ mutable ui_imports_cmi:
+ (string * Digest.t option) list; (* Interfaces imported *)
+ mutable ui_imports_cmx:(string * Digest.t option) list; (* Infos imported *)
+ mutable ui_approx: Clambda.value_approximation; (* Approx of the structure*)
+ mutable ui_curry_fun: int list; (* Currying functions needed *)
+ mutable ui_apply_fun: int list; (* Apply functions needed *)
+ mutable ui_send_fun: int list; (* Send functions needed *)
+ mutable ui_force_link: bool } (* Always linked *)
+
+(* Each .a library has a matching .cmxa file that provides the following
+ infos on the library: *)
+
+type library_infos =
+ { lib_units: (unit_infos * Digest.t) list; (* List of unit infos w/ MD5s *)
+ lib_ccobjs: string list; (* C object files needed *)
+ lib_ccopts: string list } (* Extra opts to C compiler *)
+
+(* Each .cmxs dynamically-loaded plugin contains a symbol
+ "caml_plugin_header" containing the following info
+ (as an externed record) *)
+
+type dynunit = {
+ dynu_name: string;
+ dynu_crc: Digest.t;
+ dynu_imports_cmi: (string * Digest.t option) list;
+ dynu_imports_cmx: (string * Digest.t option) list;
+ dynu_defines: string list;
+}
+
+type dynheader = {
+ dynu_magic: string;
+ dynu_units: dynunit list;
+}
diff --git a/asmcomp/codegen.ml b/asmcomp/codegen.ml
new file mode 100644
index 0000000000..a318246289
--- /dev/null
+++ b/asmcomp/codegen.ml
@@ -0,0 +1,95 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* From C-- to assembly code *)
+
+open Format
+open Cmm
+
+let dump_cmm = ref false
+let dump_selection = ref false
+let dump_live = ref false
+let dump_spill = ref false
+let dump_split = ref false
+let dump_interf = ref false
+let dump_prefer = ref false
+let dump_regalloc = ref false
+let dump_reload = ref false
+let dump_linear = ref false
+
+let rec regalloc fd =
+ if !dump_live then Printmach.phase "Liveness analysis" fd;
+ Interf.build_graph fd;
+ if !dump_interf then Printmach.interferences();
+ if !dump_prefer then Printmach.preferences();
+ Coloring.allocate_registers();
+ if !dump_regalloc then
+ Printmach.phase "After register allocation" fd;
+ let (newfd, redo_regalloc) = Reload.fundecl fd in
+ if !dump_reload then
+ Printmach.phase "After insertion of reloading code" newfd;
+ if redo_regalloc
+ then begin Reg.reinit(); Liveness.fundecl newfd; regalloc newfd end
+ else newfd
+
+let fundecl ppf fd_cmm =
+ if !dump_cmm then begin
+ fprintf ppf "*** C-- code@.";
+ fprintf ppf "%a@." Printcmm.fundecl fd_cmm
+ end;
+ Reg.reset();
+ let fd_sel = Sequence.fundecl fd_cmm in
+ if !dump_selection then
+ Printmach.phase "After instruction selection" fd_sel;
+ Liveness.fundecl fd_sel;
+ if !dump_live then Printmach.phase "Liveness analysis" fd_sel;
+ let fd_spill = Spill.fundecl fd_sel in
+ Liveness.fundecl fd_spill;
+ if !dump_spill then
+ Printmach.phase "After spilling" fd_spill;
+ let fd_split = Split.fundecl fd_spill in
+ Liveness.fundecl fd_split;
+ if !dump_split then
+ Printmach.phase "After live range splitting" fd_split;
+ let fd_reload = regalloc fd_split in
+ let fd_linear = Linearize.fundecl fd_reload in
+ if !dump_linear then begin
+ printf "*** Linearized code@.";
+ Printlinear.fundecl fd_linear; print_newline()
+ end;
+ Emit.fundecl fd_linear
+
+let phrase = function
+ Cfunction fd -> fundecl fd
+ | Cdata dl -> Emit.data dl
+
+let file filename =
+ let ic = open_in filename in
+ let lb = Lexing.from_channel ic in
+ try
+ while true do
+ phrase(Parsecmm.phrase Lexcmm.token lb)
+ done
+ with
+ End_of_file ->
+ close_in ic
+ | Lexcmm.Error msg ->
+ close_in ic; Lexcmm.report_error lb msg
+ | Parsing.Parse_error ->
+ close_in ic;
+ prerr_string "Syntax error near character ";
+ prerr_int (Lexing.lexeme_start lb);
+ prerr_newline()
+ | Parsecmmaux.Error msg ->
+ close_in ic; Parsecmmaux.report_error msg
+ | x ->
+ close_in ic; raise x
diff --git a/asmcomp/codegen.mli b/asmcomp/codegen.mli
new file mode 100644
index 0000000000..5dab12fc92
--- /dev/null
+++ b/asmcomp/codegen.mli
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* From C-- to assembly code *)
+
+val phrase: Cmm.phrase -> unit
+val file: string -> unit
+
+val dump_cmm: bool ref
+val dump_selection: bool ref
+val dump_live: bool ref
+val dump_spill: bool ref
+val dump_split: bool ref
+val dump_interf: bool ref
+val dump_prefer: bool ref
+val dump_regalloc: bool ref
+val dump_reload: bool ref
+val dump_linear: bool ref
diff --git a/asmcomp/coloring.ml b/asmcomp/coloring.ml
new file mode 100644
index 0000000000..aff4ad626c
--- /dev/null
+++ b/asmcomp/coloring.ml
@@ -0,0 +1,223 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Register allocation by coloring of the interference graph *)
+
+module OrderedRegSet =
+ Set.Make(struct
+ type t = Reg.t
+ let compare r1 r2 =
+ let open Reg in
+ let c1 = r1.spill_cost and d1 = r1.degree in
+ let c2 = r2.spill_cost and d2 = r2.degree in
+ let n = c2 * d1 - c1 * d2 in
+ if n <> 0 then n else
+ let n = c2 - c1 in
+ if n <> 0 then n else
+ let n = d1 - d2 in
+ if n <> 0 then n else r1.stamp - r2.stamp
+ end)
+
+open Reg
+
+let allocate_registers() =
+
+ (* Constrained regs with degree >= number of available registers,
+ sorted by spill cost (highest first).
+ The spill cost measure is [r.spill_cost / r.degree].
+ [r.spill_cost] estimates the number of accesses to [r]. *)
+ let constrained = ref OrderedRegSet.empty in
+
+ (* Unconstrained regs with degree < number of available registers *)
+ let unconstrained = ref [] in
+
+ (* Preallocate the spilled registers in the stack.
+ Split the remaining registers into constrained and unconstrained. *)
+ let remove_reg reg =
+ let cl = Proc.register_class reg in
+ if reg.spill then begin
+ (* Preallocate the registers in the stack *)
+ let nslots = Proc.num_stack_slots.(cl) in
+ let conflict = Array.make nslots false in
+ List.iter
+ (fun r ->
+ match r.loc with
+ Stack(Local n) ->
+ if Proc.register_class r = cl then conflict.(n) <- true
+ | _ -> ())
+ reg.interf;
+ let slot = ref 0 in
+ while !slot < nslots && conflict.(!slot) do incr slot done;
+ reg.loc <- Stack(Local !slot);
+ if !slot >= nslots then Proc.num_stack_slots.(cl) <- !slot + 1
+ end else if reg.degree < Proc.num_available_registers.(cl) then
+ unconstrained := reg :: !unconstrained
+ else begin
+ constrained := OrderedRegSet.add reg !constrained
+ end in
+
+ (* Iterate over all registers preferred by the given register (transitive) *)
+ let iter_preferred f reg =
+ let rec walk r w =
+ if not r.visited then begin
+ f r w;
+ begin match r.prefer with
+ [] -> ()
+ | p -> r.visited <- true;
+ List.iter (fun (r1, w1) -> walk r1 (min w w1)) p;
+ r.visited <- false
+ end
+ end in
+ reg.visited <- true;
+ List.iter (fun (r, w) -> walk r w) reg.prefer;
+ reg.visited <- false in
+
+ (* Where to start the search for a suitable register.
+ Used to introduce some "randomness" in the choice between registers
+ with equal scores. This offers more opportunities for scheduling. *)
+ let start_register = Array.make Proc.num_register_classes 0 in
+
+ (* Assign a location to a register, the best we can. *)
+ let assign_location reg =
+ let cl = Proc.register_class reg in
+ let first_reg = Proc.first_available_register.(cl) in
+ let num_regs = Proc.num_available_registers.(cl) in
+ let score = Array.make num_regs 0 in
+ let best_score = ref (-1000000) and best_reg = ref (-1) in
+ let start = start_register.(cl) in
+ if num_regs <> 0 then begin
+ (* Favor the registers that have been assigned to pseudoregs for which
+ we have a preference. If these pseudoregs have not been assigned
+ already, avoid the registers with which they conflict. *)
+ iter_preferred
+ (fun r w ->
+ match r.loc with
+ Reg n -> let n = n - first_reg in
+ if n < num_regs then
+ score.(n) <- score.(n) + w
+ | Unknown ->
+ List.iter
+ (fun neighbour ->
+ match neighbour.loc with
+ Reg n -> let n = n - first_reg in
+ if n < num_regs then
+ score.(n) <- score.(n) - w
+ | _ -> ())
+ r.interf
+ | _ -> ())
+ reg;
+ List.iter
+ (fun neighbour ->
+ (* Prohibit the registers that have been assigned
+ to our neighbours *)
+ begin match neighbour.loc with
+ Reg n -> let n = n - first_reg in
+ if n < num_regs then
+ score.(n) <- (-1000000)
+ | _ -> ()
+ end;
+ (* Avoid the registers that have been assigned to pseudoregs
+ for which our neighbours have a preference *)
+ iter_preferred
+ (fun r w ->
+ match r.loc with
+ Reg n -> let n = n - first_reg in
+ if n < num_regs then
+ score.(n) <- score.(n) - (w-1)
+ (* w-1 to break the symmetry when two conflicting regs
+ have the same preference for a third reg. *)
+ | _ -> ())
+ neighbour)
+ reg.interf;
+ (* Pick the register with the best score *)
+ for n = start to num_regs - 1 do
+ if score.(n) > !best_score then begin
+ best_score := score.(n);
+ best_reg := n
+ end
+ done;
+ for n = 0 to start - 1 do
+ if score.(n) > !best_score then begin
+ best_score := score.(n);
+ best_reg := n
+ end
+ done
+ end;
+ (* Found a register? *)
+ if !best_reg >= 0 then begin
+ reg.loc <- Reg(first_reg + !best_reg);
+ if Proc.rotate_registers then
+ start_register.(cl) <- (let start = start + 1 in
+ if start >= num_regs then 0 else start)
+ end else begin
+ (* Sorry, we must put the pseudoreg in a stack location *)
+ let nslots = Proc.num_stack_slots.(cl) in
+ let score = Array.make nslots 0 in
+ (* Compute the scores as for registers *)
+ List.iter
+ (fun (r, w) ->
+ match r.loc with
+ Stack(Local n) -> score.(n) <- score.(n) + w
+ | Unknown ->
+ List.iter
+ (fun neighbour ->
+ match neighbour.loc with
+ Stack(Local n) -> score.(n) <- score.(n) - w
+ | _ -> ())
+ r.interf
+ | _ -> ())
+ reg.prefer;
+ List.iter
+ (fun neighbour ->
+ begin match neighbour.loc with
+ Stack(Local n) -> score.(n) <- (-1000000)
+ | _ -> ()
+ end;
+ List.iter
+ (fun (r, w) ->
+ match r.loc with
+ Stack(Local n) -> score.(n) <- score.(n) - w
+ | _ -> ())
+ neighbour.prefer)
+ reg.interf;
+ (* Pick the location with the best score *)
+ let best_score = ref (-1000000) and best_slot = ref (-1) in
+ for n = 0 to nslots - 1 do
+ if score.(n) > !best_score then begin
+ best_score := score.(n);
+ best_slot := n
+ end
+ done;
+ (* Found one? *)
+ if !best_slot >= 0 then
+ reg.loc <- Stack(Local !best_slot)
+ else begin
+ (* Allocate a new stack slot *)
+ reg.loc <- Stack(Local nslots);
+ Proc.num_stack_slots.(cl) <- nslots + 1
+ end
+ end;
+ (* Cancel the preferences of this register so that they don't influence
+ transitively the allocation of registers that prefer this reg. *)
+ reg.prefer <- [] in
+
+ (* Reset the stack slot counts *)
+ for i = 0 to Proc.num_register_classes - 1 do
+ Proc.num_stack_slots.(i) <- 0;
+ done;
+
+ (* First pass: preallocate spill registers and split remaining regs
+ Second pass: assign locations to constrained regs
+ Third pass: assign locations to unconstrained regs *)
+ List.iter remove_reg (Reg.all_registers());
+ OrderedRegSet.iter assign_location !constrained;
+ List.iter assign_location !unconstrained
diff --git a/asmcomp/coloring.mli b/asmcomp/coloring.mli
new file mode 100644
index 0000000000..b0cd0437a0
--- /dev/null
+++ b/asmcomp/coloring.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Register allocation by coloring of the interference graph *)
+
+val allocate_registers: unit -> unit
diff --git a/asmcomp/comballoc.ml b/asmcomp/comballoc.ml
new file mode 100644
index 0000000000..820b1b3fa3
--- /dev/null
+++ b/asmcomp/comballoc.ml
@@ -0,0 +1,88 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Combine heap allocations occurring in the same basic block *)
+
+open Mach
+
+type allocation_state =
+ No_alloc (* no allocation is pending *)
+ | Pending_alloc of Reg.t * int (* an allocation is pending *)
+(* The arguments of Pending_alloc(reg, ofs) are:
+ reg the register holding the result of the last allocation
+ ofs the alloc position in the allocated block *)
+
+let allocated_size = function
+ No_alloc -> 0
+ | Pending_alloc(reg, ofs) -> ofs
+
+let rec combine i allocstate =
+ match i.desc with
+ Iend | Ireturn | Iexit _ | Iraise _ ->
+ (i, allocated_size allocstate)
+ | Iop(Ialloc sz) ->
+ begin match allocstate with
+ No_alloc ->
+ let (newnext, newsz) =
+ combine i.next (Pending_alloc(i.res.(0), sz)) in
+ (instr_cons (Iop(Ialloc newsz)) i.arg i.res newnext, 0)
+ | Pending_alloc(reg, ofs) ->
+ if ofs + sz < Config.max_young_wosize * Arch.size_addr then begin
+ let (newnext, newsz) =
+ combine i.next (Pending_alloc(reg, ofs + sz)) in
+ (instr_cons (Iop(Iintop_imm(Iadd, ofs))) [| reg |] i.res newnext,
+ newsz)
+ end else begin
+ let (newnext, newsz) =
+ combine i.next (Pending_alloc(i.res.(0), sz)) in
+ (instr_cons (Iop(Ialloc newsz)) i.arg i.res newnext, ofs)
+ end
+ end
+ | Iop(Icall_ind | Icall_imm _ | Iextcall _ |
+ Itailcall_ind | Itailcall_imm _) ->
+ let newnext = combine_restart i.next in
+ (instr_cons_debug i.desc i.arg i.res i.dbg newnext,
+ allocated_size allocstate)
+ | Iop op ->
+ let (newnext, sz) = combine i.next allocstate in
+ (instr_cons_debug i.desc i.arg i.res i.dbg newnext, sz)
+ | Iifthenelse(test, ifso, ifnot) ->
+ let newifso = combine_restart ifso in
+ let newifnot = combine_restart ifnot in
+ let newnext = combine_restart i.next in
+ (instr_cons (Iifthenelse(test, newifso, newifnot)) i.arg i.res newnext,
+ allocated_size allocstate)
+ | Iswitch(table, cases) ->
+ let newcases = Array.map combine_restart cases in
+ let newnext = combine_restart i.next in
+ (instr_cons (Iswitch(table, newcases)) i.arg i.res newnext,
+ allocated_size allocstate)
+ | Iloop(body) ->
+ let newbody = combine_restart body in
+ (instr_cons (Iloop(newbody)) i.arg i.res i.next,
+ allocated_size allocstate)
+ | Icatch(io, body, handler) ->
+ let (newbody, sz) = combine body allocstate in
+ let newhandler = combine_restart handler in
+ let newnext = combine_restart i.next in
+ (instr_cons (Icatch(io, newbody, newhandler)) i.arg i.res newnext, sz)
+ | Itrywith(body, handler) ->
+ let (newbody, sz) = combine body allocstate in
+ let newhandler = combine_restart handler in
+ let newnext = combine_restart i.next in
+ (instr_cons (Itrywith(newbody, newhandler)) i.arg i.res newnext, sz)
+
+and combine_restart i =
+ let (newi, _) = combine i No_alloc in newi
+
+let fundecl f =
+ {f with fun_body = combine_restart f.fun_body}
diff --git a/asmcomp/comballoc.mli b/asmcomp/comballoc.mli
new file mode 100644
index 0000000000..ee04c16b3a
--- /dev/null
+++ b/asmcomp/comballoc.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Combine heap allocations occurring in the same basic block *)
+
+val fundecl: Mach.fundecl -> Mach.fundecl
diff --git a/asmcomp/compilenv.ml b/asmcomp/compilenv.ml
new file mode 100644
index 0000000000..a313b97202
--- /dev/null
+++ b/asmcomp/compilenv.ml
@@ -0,0 +1,301 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compilation environments for compilation units *)
+
+open Config
+open Misc
+open Clambda
+open Cmx_format
+
+type error =
+ Not_a_unit_info of string
+ | Corrupted_unit_info of string
+ | Illegal_renaming of string * string * string
+
+exception Error of error
+
+let global_infos_table =
+ (Hashtbl.create 17 : (string, unit_infos option) Hashtbl.t)
+
+module CstMap =
+ Map.Make(struct
+ type t = Clambda.ustructured_constant
+ let compare = Clambda.compare_structured_constants
+ (* PR#6442: it is incorrect to use Pervasives.compare on values of type t
+ because it compares "0.0" and "-0.0" equal. *)
+ end)
+
+type structured_constants =
+ {
+ strcst_shared: string CstMap.t;
+ strcst_all: (string * Clambda.ustructured_constant) list;
+ }
+
+let structured_constants_empty =
+ {
+ strcst_shared = CstMap.empty;
+ strcst_all = [];
+ }
+
+let structured_constants = ref structured_constants_empty
+
+
+let exported_constants = Hashtbl.create 17
+
+let current_unit =
+ { ui_name = "";
+ ui_symbol = "";
+ ui_defines = [];
+ ui_imports_cmi = [];
+ ui_imports_cmx = [];
+ ui_approx = Value_unknown;
+ ui_curry_fun = [];
+ ui_apply_fun = [];
+ ui_send_fun = [];
+ ui_force_link = false }
+
+let symbolname_for_pack pack name =
+ match pack with
+ | None -> name
+ | Some p ->
+ let b = Buffer.create 64 in
+ for i = 0 to String.length p - 1 do
+ match p.[i] with
+ | '.' -> Buffer.add_string b "__"
+ | c -> Buffer.add_char b c
+ done;
+ Buffer.add_string b "__";
+ Buffer.add_string b name;
+ Buffer.contents b
+
+
+let reset ?packname name =
+ Hashtbl.clear global_infos_table;
+ let symbol = symbolname_for_pack packname name in
+ current_unit.ui_name <- name;
+ current_unit.ui_symbol <- symbol;
+ current_unit.ui_defines <- [symbol];
+ current_unit.ui_imports_cmi <- [];
+ current_unit.ui_imports_cmx <- [];
+ current_unit.ui_curry_fun <- [];
+ current_unit.ui_apply_fun <- [];
+ current_unit.ui_send_fun <- [];
+ current_unit.ui_force_link <- false;
+ Hashtbl.clear exported_constants;
+ structured_constants := structured_constants_empty
+
+let current_unit_infos () =
+ current_unit
+
+let current_unit_name () =
+ current_unit.ui_name
+
+let make_symbol ?(unitname = current_unit.ui_symbol) idopt =
+ let prefix = "caml" ^ unitname in
+ match idopt with
+ | None -> prefix
+ | Some id -> prefix ^ "__" ^ id
+
+let symbol_in_current_unit name =
+ let prefix = "caml" ^ current_unit.ui_symbol in
+ name = prefix ||
+ (let lp = String.length prefix in
+ String.length name >= 2 + lp
+ && String.sub name 0 lp = prefix
+ && name.[lp] = '_'
+ && name.[lp + 1] = '_')
+
+let read_unit_info filename =
+ let ic = open_in_bin filename in
+ try
+ let buffer = really_input_string ic (String.length cmx_magic_number) in
+ if buffer <> cmx_magic_number then begin
+ close_in ic;
+ raise(Error(Not_a_unit_info filename))
+ end;
+ let ui = (input_value ic : unit_infos) in
+ let crc = Digest.input ic in
+ close_in ic;
+ (ui, crc)
+ with End_of_file | Failure _ ->
+ close_in ic;
+ raise(Error(Corrupted_unit_info(filename)))
+
+let read_library_info filename =
+ let ic = open_in_bin filename in
+ let buffer = really_input_string ic (String.length cmxa_magic_number) in
+ if buffer <> cmxa_magic_number then
+ raise(Error(Not_a_unit_info filename));
+ let infos = (input_value ic : library_infos) in
+ close_in ic;
+ infos
+
+
+(* Read and cache info on global identifiers *)
+
+let get_global_info global_ident = (
+ let modname = Ident.name global_ident in
+ if modname = current_unit.ui_name then
+ Some current_unit
+ else begin
+ try
+ Hashtbl.find global_infos_table modname
+ with Not_found ->
+ let (infos, crc) =
+ try
+ let filename =
+ find_in_path_uncap !load_path (modname ^ ".cmx") in
+ let (ui, crc) = read_unit_info filename in
+ if ui.ui_name <> modname then
+ raise(Error(Illegal_renaming(modname, ui.ui_name, filename)));
+ (Some ui, Some crc)
+ with Not_found ->
+ (None, None) in
+ current_unit.ui_imports_cmx <-
+ (modname, crc) :: current_unit.ui_imports_cmx;
+ Hashtbl.add global_infos_table modname infos;
+ infos
+ end
+)
+
+let cache_unit_info ui =
+ Hashtbl.add global_infos_table ui.ui_name (Some ui)
+
+(* Return the approximation of a global identifier *)
+
+let toplevel_approx = Hashtbl.create 16
+
+let record_global_approx_toplevel id =
+ Hashtbl.add toplevel_approx current_unit.ui_name current_unit.ui_approx
+
+let global_approx id =
+ if Ident.is_predef_exn id then Value_unknown
+ else try Hashtbl.find toplevel_approx (Ident.name id)
+ with Not_found ->
+ match get_global_info id with
+ | None -> Value_unknown
+ | Some ui -> ui.ui_approx
+
+(* Return the symbol used to refer to a global identifier *)
+
+let symbol_for_global id =
+ if Ident.is_predef_exn id then
+ "caml_exn_" ^ Ident.name id
+ else begin
+ match get_global_info id with
+ | None -> make_symbol ~unitname:(Ident.name id) None
+ | Some ui -> make_symbol ~unitname:ui.ui_symbol None
+ end
+
+(* Register the approximation of the module being compiled *)
+
+let set_global_approx approx =
+ current_unit.ui_approx <- approx
+
+(* Record that a currying function or application function is needed *)
+
+let need_curry_fun n =
+ if not (List.mem n current_unit.ui_curry_fun) then
+ current_unit.ui_curry_fun <- n :: current_unit.ui_curry_fun
+
+let need_apply_fun n =
+ if not (List.mem n current_unit.ui_apply_fun) then
+ current_unit.ui_apply_fun <- n :: current_unit.ui_apply_fun
+
+let need_send_fun n =
+ if not (List.mem n current_unit.ui_send_fun) then
+ current_unit.ui_send_fun <- n :: current_unit.ui_send_fun
+
+(* Write the description of the current unit *)
+
+let write_unit_info info filename =
+ let oc = open_out_bin filename in
+ output_string oc cmx_magic_number;
+ output_value oc info;
+ flush oc;
+ let crc = Digest.file filename in
+ Digest.output oc crc;
+ close_out oc
+
+let save_unit_info filename =
+ current_unit.ui_imports_cmi <- Env.imports();
+ write_unit_info current_unit filename
+
+
+
+let const_label = ref 0
+
+let new_const_label () =
+ incr const_label;
+ !const_label
+
+let new_const_symbol () =
+ incr const_label;
+ make_symbol (Some (string_of_int !const_label))
+
+let snapshot () = !structured_constants
+let backtrack s = structured_constants := s
+
+let new_structured_constant cst ~shared =
+ let {strcst_shared; strcst_all} = !structured_constants in
+ if shared then
+ try
+ CstMap.find cst strcst_shared
+ with Not_found ->
+ let lbl = new_const_symbol() in
+ structured_constants :=
+ {
+ strcst_shared = CstMap.add cst lbl strcst_shared;
+ strcst_all = (lbl, cst) :: strcst_all;
+ };
+ lbl
+ else
+ let lbl = new_const_symbol() in
+ structured_constants :=
+ {
+ strcst_shared;
+ strcst_all = (lbl, cst) :: strcst_all;
+ };
+ lbl
+
+let add_exported_constant s =
+ Hashtbl.replace exported_constants s ()
+
+let structured_constants () =
+ List.map
+ (fun (lbl, cst) ->
+ (lbl, Hashtbl.mem exported_constants lbl, cst)
+ ) (!structured_constants).strcst_all
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Not_a_unit_info filename ->
+ fprintf ppf "%a@ is not a compilation unit description."
+ Location.print_filename filename
+ | Corrupted_unit_info filename ->
+ fprintf ppf "Corrupted compilation unit description@ %a"
+ Location.print_filename filename
+ | Illegal_renaming(name, modname, filename) ->
+ fprintf ppf "%a@ contains the description for unit\
+ @ %s when %s was expected"
+ Location.print_filename filename name modname
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
diff --git a/asmcomp/compilenv.mli b/asmcomp/compilenv.mli
new file mode 100644
index 0000000000..7fae3bade6
--- /dev/null
+++ b/asmcomp/compilenv.mli
@@ -0,0 +1,91 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compilation environments for compilation units *)
+
+open Cmx_format
+
+val reset: ?packname:string -> string -> unit
+ (* Reset the environment and record the name of the unit being
+ compiled (arg). Optional argument is [-for-pack] prefix. *)
+
+val current_unit_infos: unit -> unit_infos
+ (* Return the infos for the unit being compiled *)
+
+val current_unit_name: unit -> string
+ (* Return the name of the unit being compiled *)
+
+val make_symbol: ?unitname:string -> string option -> string
+ (* [make_symbol ~unitname:u None] returns the asm symbol that
+ corresponds to the compilation unit [u] (default: the current unit).
+ [make_symbol ~unitname:u (Some id)] returns the asm symbol that
+ corresponds to symbol [id] in the compilation unit [u]
+ (or the current unit). *)
+
+val symbol_in_current_unit: string -> bool
+ (* Return true if the given asm symbol belongs to the
+ current compilation unit, false otherwise. *)
+
+val symbol_for_global: Ident.t -> string
+ (* Return the asm symbol that refers to the given global identifier *)
+
+val global_approx: Ident.t -> Clambda.value_approximation
+ (* Return the approximation for the given global identifier *)
+val set_global_approx: Clambda.value_approximation -> unit
+ (* Record the approximation of the unit being compiled *)
+val record_global_approx_toplevel: unit -> unit
+ (* Record the current approximation for the current toplevel phrase *)
+
+
+val need_curry_fun: int -> unit
+val need_apply_fun: int -> unit
+val need_send_fun: int -> unit
+ (* Record the need of a currying (resp. application,
+ message sending) function with the given arity *)
+
+val new_const_symbol : unit -> string
+val new_const_label : unit -> int
+
+val new_structured_constant:
+ Clambda.ustructured_constant ->
+ shared:bool -> (* can be shared with another structually equal constant *)
+ string
+val structured_constants:
+ unit -> (string * bool * Clambda.ustructured_constant) list
+val add_exported_constant: string -> unit
+
+type structured_constants
+val snapshot: unit -> structured_constants
+val backtrack: structured_constants -> unit
+
+
+val read_unit_info: string -> unit_infos * Digest.t
+ (* Read infos and MD5 from a [.cmx] file. *)
+val write_unit_info: unit_infos -> string -> unit
+ (* Save the given infos in the given file *)
+val save_unit_info: string -> unit
+ (* Save the infos for the current unit in the given file *)
+val cache_unit_info: unit_infos -> unit
+ (* Enter the given infos in the cache. The infos will be
+ honored by [symbol_for_global] and [global_approx]
+ without looking at the corresponding .cmx file. *)
+
+val read_library_info: string -> library_infos
+
+type error =
+ Not_a_unit_info of string
+ | Corrupted_unit_info of string
+ | Illegal_renaming of string * string * string
+
+exception Error of error
+
+val report_error: Format.formatter -> error -> unit
diff --git a/asmcomp/deadcode.ml b/asmcomp/deadcode.ml
new file mode 100644
index 0000000000..cb93c2869d
--- /dev/null
+++ b/asmcomp/deadcode.ml
@@ -0,0 +1,67 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Dead code elimination: remove pure instructions whose results are
+ not used. *)
+
+open Mach
+
+(* [deadcode i] returns a pair of an optimized instruction [i']
+ and a set of registers live "before" instruction [i]. *)
+
+let rec deadcode i =
+ match i.desc with
+ | Iend | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) | Iraise _ ->
+ (i, Reg.add_set_array i.live i.arg)
+ | Iop op ->
+ let (s, before) = deadcode i.next in
+ if Proc.op_is_pure op (* no side effects *)
+ && Reg.disjoint_set_array before i.res (* results are not used after *)
+ && not (Proc.regs_are_volatile i.arg) (* no stack-like hard reg *)
+ && not (Proc.regs_are_volatile i.res) (* is involved *)
+ then begin
+ assert (Array.length i.res > 0); (* sanity check *)
+ (s, before)
+ end else begin
+ ({i with next = s}, Reg.add_set_array i.live i.arg)
+ end
+ | Iifthenelse(test, ifso, ifnot) ->
+ let (ifso', _) = deadcode ifso in
+ let (ifnot', _) = deadcode ifnot in
+ let (s, _) = deadcode i.next in
+ ({i with desc = Iifthenelse(test, ifso', ifnot'); next = s},
+ Reg.add_set_array i.live i.arg)
+ | Iswitch(index, cases) ->
+ let cases' = Array.map (fun c -> fst (deadcode c)) cases in
+ let (s, _) = deadcode i.next in
+ ({i with desc = Iswitch(index, cases'); next = s},
+ Reg.add_set_array i.live i.arg)
+ | Iloop(body) ->
+ let (body', _) = deadcode body in
+ let (s, _) = deadcode i.next in
+ ({i with desc = Iloop body'; next = s}, i.live)
+ | Icatch(nfail, body, handler) ->
+ let (body', _) = deadcode body in
+ let (handler', _) = deadcode handler in
+ let (s, _) = deadcode i.next in
+ ({i with desc = Icatch(nfail, body', handler'); next = s}, i.live)
+ | Iexit nfail ->
+ (i, i.live)
+ | Itrywith(body, handler) ->
+ let (body', _) = deadcode body in
+ let (handler', _) = deadcode handler in
+ let (s, _) = deadcode i.next in
+ ({i with desc = Itrywith(body', handler'); next = s}, i.live)
+
+let fundecl f =
+ let (new_body, _) = deadcode f.fun_body in
+ {f with fun_body = new_body}
diff --git a/asmcomp/deadcode.mli b/asmcomp/deadcode.mli
new file mode 100644
index 0000000000..6aafae0540
--- /dev/null
+++ b/asmcomp/deadcode.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Dead code elimination: remove pure instructions whose results are
+ not used. *)
+
+val fundecl: Mach.fundecl -> Mach.fundecl
diff --git a/asmcomp/debuginfo.ml b/asmcomp/debuginfo.ml
new file mode 100644
index 0000000000..3f96049eee
--- /dev/null
+++ b/asmcomp/debuginfo.ml
@@ -0,0 +1,56 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2006 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Lexing
+open Location
+
+type kind = Dinfo_call | Dinfo_raise
+
+type t = {
+ dinfo_kind: kind;
+ dinfo_file: string;
+ dinfo_line: int;
+ dinfo_char_start: int;
+ dinfo_char_end: int
+}
+
+let none = {
+ dinfo_kind = Dinfo_call;
+ dinfo_file = "";
+ dinfo_line = 0;
+ dinfo_char_start = 0;
+ dinfo_char_end = 0
+}
+
+(* PR#5643: cannot use (==) because Debuginfo values are marshalled *)
+let is_none t =
+ t = none
+
+let to_string d =
+ if d = none
+ then ""
+ else Printf.sprintf "{%s:%d,%d-%d}"
+ d.dinfo_file d.dinfo_line d.dinfo_char_start d.dinfo_char_end
+
+let from_location kind loc =
+ if loc == Location.none then none else
+ { dinfo_kind = kind;
+ dinfo_file = loc.loc_start.pos_fname;
+ dinfo_line = loc.loc_start.pos_lnum;
+ dinfo_char_start = loc.loc_start.pos_cnum - loc.loc_start.pos_bol;
+ dinfo_char_end =
+ if loc.loc_end.pos_fname = loc.loc_start.pos_fname
+ then loc.loc_end.pos_cnum - loc.loc_start.pos_bol
+ else loc.loc_start.pos_cnum - loc.loc_start.pos_bol }
+
+let from_call ev = from_location Dinfo_call ev.Lambda.lev_loc
+let from_raise ev = from_location Dinfo_raise ev.Lambda.lev_loc
diff --git a/asmcomp/debuginfo.mli b/asmcomp/debuginfo.mli
new file mode 100644
index 0000000000..ef4d55ad91
--- /dev/null
+++ b/asmcomp/debuginfo.mli
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2006 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type kind = Dinfo_call | Dinfo_raise
+
+type t = private {
+ dinfo_kind: kind;
+ dinfo_file: string;
+ dinfo_line: int;
+ dinfo_char_start: int;
+ dinfo_char_end: int
+}
+
+val none: t
+
+val is_none: t -> bool
+
+val to_string: t -> string
+
+val from_location: kind -> Location.t -> t
+
+val from_call: Lambda.lambda_event -> t
+val from_raise: Lambda.lambda_event -> t
diff --git a/asmcomp/emit.mli b/asmcomp/emit.mli
new file mode 100644
index 0000000000..ab9442efc1
--- /dev/null
+++ b/asmcomp/emit.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Generation of assembly code *)
+
+val fundecl: Linearize.fundecl -> unit
+val data: Cmm.data_item list -> unit
+val begin_assembly: unit -> unit
+val end_assembly: unit -> unit
diff --git a/asmcomp/emitaux.ml b/asmcomp/emitaux.ml
new file mode 100644
index 0000000000..8650fa4ff8
--- /dev/null
+++ b/asmcomp/emitaux.ml
@@ -0,0 +1,260 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Common functions for emitting assembly code *)
+
+open Debuginfo
+
+let output_channel = ref stdout
+
+let emit_string s = output_string !output_channel s
+
+let emit_int n = output_string !output_channel (string_of_int n)
+
+let emit_char c = output_char !output_channel c
+
+let emit_nativeint n = output_string !output_channel (Nativeint.to_string n)
+
+let emit_printf fmt =
+ Printf.fprintf !output_channel fmt
+
+let emit_int32 n = emit_printf "0x%lx" n
+
+let emit_symbol esc s =
+ for i = 0 to String.length s - 1 do
+ let c = s.[i] in
+ match c with
+ 'A'..'Z' | 'a'..'z' | '0'..'9' | '_' ->
+ output_char !output_channel c
+ | _ ->
+ Printf.fprintf !output_channel "%c%02x" esc (Char.code c)
+ done
+
+let emit_string_literal s =
+ let last_was_escape = ref false in
+ emit_string "\"";
+ for i = 0 to String.length s - 1 do
+ let c = s.[i] in
+ if c >= '0' && c <= '9' then
+ if !last_was_escape
+ then Printf.fprintf !output_channel "\\%o" (Char.code c)
+ else output_char !output_channel c
+ else if c >= ' ' && c <= '~' && c <> '"' (* '"' *) && c <> '\\' then begin
+ output_char !output_channel c;
+ last_was_escape := false
+ end else begin
+ Printf.fprintf !output_channel "\\%o" (Char.code c);
+ last_was_escape := true
+ end
+ done;
+ emit_string "\""
+
+let emit_string_directive directive s =
+ let l = String.length s in
+ if l = 0 then ()
+ else if l < 80 then begin
+ emit_string directive;
+ emit_string_literal s;
+ emit_char '\n'
+ end else begin
+ let i = ref 0 in
+ while !i < l do
+ let n = min (l - !i) 80 in
+ emit_string directive;
+ emit_string_literal (String.sub s !i n);
+ emit_char '\n';
+ i := !i + n
+ done
+ end
+
+let emit_bytes_directive directive s =
+ let pos = ref 0 in
+ for i = 0 to String.length s - 1 do
+ if !pos = 0
+ then emit_string directive
+ else emit_char ',';
+ emit_int(Char.code s.[i]);
+ incr pos;
+ if !pos >= 16 then begin emit_char '\n'; pos := 0 end
+ done;
+ if !pos > 0 then emit_char '\n'
+
+let emit_float64_directive directive x =
+ emit_printf "\t%s\t0x%Lx\n" directive x
+
+let emit_float64_split_directive directive x =
+ let lo = Int64.logand x 0xFFFF_FFFFL
+ and hi = Int64.shift_right_logical x 32 in
+ emit_printf "\t%s\t0x%Lx, 0x%Lx\n"
+ directive
+ (if Arch.big_endian then hi else lo)
+ (if Arch.big_endian then lo else hi)
+
+let emit_float32_directive directive x =
+ emit_printf "\t%s\t0x%lx\n" directive x
+
+(* Record live pointers at call points *)
+
+type frame_descr =
+ { fd_lbl: int; (* Return address *)
+ fd_frame_size: int; (* Size of stack frame *)
+ fd_live_offset: int list; (* Offsets/regs of live addresses *)
+ fd_debuginfo: Debuginfo.t } (* Location, if any *)
+
+let frame_descriptors = ref([] : frame_descr list)
+
+type emit_frame_actions =
+ { efa_label: int -> unit;
+ efa_16: int -> unit;
+ efa_32: int32 -> unit;
+ efa_word: int -> unit;
+ efa_align: int -> unit;
+ efa_label_rel: int -> int32 -> unit;
+ efa_def_label: int -> unit;
+ efa_string: string -> unit }
+
+let emit_frames a =
+ let filenames = Hashtbl.create 7 in
+ let label_filename name =
+ try
+ Hashtbl.find filenames name
+ with Not_found ->
+ let lbl = Linearize.new_label () in
+ Hashtbl.add filenames name lbl;
+ lbl in
+ let emit_frame fd =
+ a.efa_label fd.fd_lbl;
+ a.efa_16 (if Debuginfo.is_none fd.fd_debuginfo
+ then fd.fd_frame_size
+ else fd.fd_frame_size + 1);
+ a.efa_16 (List.length fd.fd_live_offset);
+ List.iter a.efa_16 fd.fd_live_offset;
+ a.efa_align Arch.size_addr;
+ if not (Debuginfo.is_none fd.fd_debuginfo) then begin
+ let d = fd.fd_debuginfo in
+ let line = min 0xFFFFF d.dinfo_line
+ and char_start = min 0xFF d.dinfo_char_start
+ and char_end = min 0x3FF d.dinfo_char_end
+ and kind = match d.dinfo_kind with Dinfo_call -> 0 | Dinfo_raise -> 1 in
+ let info =
+ Int64.add (Int64.shift_left (Int64.of_int line) 44) (
+ Int64.add (Int64.shift_left (Int64.of_int char_start) 36) (
+ Int64.add (Int64.shift_left (Int64.of_int char_end) 26)
+ (Int64.of_int kind))) in
+ a.efa_label_rel
+ (label_filename d.dinfo_file)
+ (Int64.to_int32 info);
+ a.efa_32 (Int64.to_int32 (Int64.shift_right info 32))
+ end in
+ let emit_filename name lbl =
+ a.efa_def_label lbl;
+ a.efa_string name;
+ a.efa_align Arch.size_addr in
+ a.efa_word (List.length !frame_descriptors);
+ List.iter emit_frame !frame_descriptors;
+ Hashtbl.iter emit_filename filenames;
+ frame_descriptors := []
+
+(* Detection of functions that can be duplicated between a DLL and
+ the main program (PR#4690) *)
+
+let isprefix s1 s2 =
+ String.length s1 <= String.length s2
+ && String.sub s2 0 (String.length s1) = s1
+
+let is_generic_function name =
+ List.exists
+ (fun p -> isprefix p name)
+ ["caml_apply"; "caml_curry"; "caml_send"; "caml_tuplify"]
+
+(* CFI directives *)
+
+let is_cfi_enabled () =
+ Config.asm_cfi_supported
+
+let cfi_startproc () =
+ if is_cfi_enabled () then
+ emit_string "\t.cfi_startproc\n"
+
+let cfi_endproc () =
+ if is_cfi_enabled () then
+ emit_string "\t.cfi_endproc\n"
+
+let cfi_adjust_cfa_offset n =
+ if is_cfi_enabled () then
+ begin
+ emit_string "\t.cfi_adjust_cfa_offset\t"; emit_int n; emit_string "\n";
+ end
+
+let cfi_offset ~reg ~offset =
+ if is_cfi_enabled () then begin
+ emit_string "\t.cfi_offset ";
+ emit_int reg;
+ emit_string ", ";
+ emit_int offset;
+ emit_string "\n"
+ end
+
+(* Emit debug information *)
+
+(* This assoc list is expected to be very short *)
+let file_pos_nums =
+ (ref [] : (string * int) list ref)
+
+(* Number of files *)
+let file_pos_num_cnt = ref 1
+
+(* Reset debug state at beginning of asm file *)
+let reset_debug_info () =
+ file_pos_nums := [];
+ file_pos_num_cnt := 1
+
+(* We only diplay .file if the file has not been seen before. We
+ display .loc for every instruction. *)
+let emit_debug_info_gen dbg file_emitter loc_emitter =
+ if is_cfi_enabled () &&
+ (!Clflags.debug || Config.with_frame_pointers)
+ && dbg.Debuginfo.dinfo_line > 0 (* PR#6243 *)
+ then begin
+ let { Debuginfo.
+ dinfo_line = line;
+ dinfo_char_start = col;
+ dinfo_file = file_name;
+ } = dbg in
+ let file_num =
+ try List.assoc file_name !file_pos_nums
+ with Not_found ->
+ let file_num = !file_pos_num_cnt in
+ incr file_pos_num_cnt;
+ file_emitter ~file_num ~file_name;
+ file_pos_nums := (file_name,file_num) :: !file_pos_nums;
+ file_num in
+ loc_emitter ~file_num ~line ~col;
+ end
+
+let emit_debug_info dbg =
+ emit_debug_info_gen dbg (fun ~file_num ~file_name ->
+ emit_string "\t.file\t";
+ emit_int file_num; emit_char '\t';
+ emit_string_literal file_name; emit_char '\n';
+ )
+ (fun ~file_num ~line ~col:_ ->
+ emit_string "\t.loc\t";
+ emit_int file_num; emit_char '\t';
+ emit_int line; emit_char '\n')
+
+let reset () =
+ reset_debug_info ();
+ frame_descriptors := []
+
+let binary_backend_available = ref false
+let create_asm_file = ref true
diff --git a/asmcomp/emitaux.mli b/asmcomp/emitaux.mli
new file mode 100644
index 0000000000..61aa9c906e
--- /dev/null
+++ b/asmcomp/emitaux.mli
@@ -0,0 +1,72 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Common functions for emitting assembly code *)
+
+val output_channel: out_channel ref
+val emit_string: string -> unit
+val emit_int: int -> unit
+val emit_nativeint: nativeint -> unit
+val emit_int32: int32 -> unit
+val emit_symbol: char -> string -> unit
+val emit_printf: ('a, out_channel, unit) format -> 'a
+val emit_char: char -> unit
+val emit_string_literal: string -> unit
+val emit_string_directive: string -> string -> unit
+val emit_bytes_directive: string -> string -> unit
+val emit_float64_directive: string -> int64 -> unit
+val emit_float64_split_directive: string -> int64 -> unit
+val emit_float32_directive: string -> int32 -> unit
+
+val reset : unit -> unit
+val reset_debug_info: unit -> unit
+val emit_debug_info: Debuginfo.t -> unit
+val emit_debug_info_gen :
+ Debuginfo.t ->
+ (file_num:int -> file_name:string -> unit) ->
+ (file_num:int -> line:int -> col:int -> unit) -> unit
+
+type frame_descr =
+ { fd_lbl: int; (* Return address *)
+ fd_frame_size: int; (* Size of stack frame *)
+ fd_live_offset: int list; (* Offsets/regs of live addresses *)
+ fd_debuginfo: Debuginfo.t } (* Location, if any *)
+
+val frame_descriptors : frame_descr list ref
+
+type emit_frame_actions =
+ { efa_label: int -> unit;
+ efa_16: int -> unit;
+ efa_32: int32 -> unit;
+ efa_word: int -> unit;
+ efa_align: int -> unit;
+ efa_label_rel: int -> int32 -> unit;
+ efa_def_label: int -> unit;
+ efa_string: string -> unit }
+
+val emit_frames: emit_frame_actions -> unit
+
+val is_generic_function: string -> bool
+
+val cfi_startproc : unit -> unit
+val cfi_endproc : unit -> unit
+val cfi_adjust_cfa_offset : int -> unit
+val cfi_offset : reg:int -> offset:int -> unit
+
+
+val binary_backend_available: bool ref
+ (** Is a binary backend available. If yes, we don't need
+ to generate the textual assembly file (unless the user
+ request it with -S). *)
+
+val create_asm_file: bool ref
+ (** Are we actually generating the textual assembly file? *)
diff --git a/asmcomp/i386/CSE.ml b/asmcomp/i386/CSE.ml
new file mode 100644
index 0000000000..6bea76f1a1
--- /dev/null
+++ b/asmcomp/i386/CSE.ml
@@ -0,0 +1,47 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* CSE for the i386 *)
+
+open Cmm
+open Arch
+open Mach
+open CSEgen
+
+class cse = object (self)
+
+inherit cse_generic as super
+
+method! class_of_operation op =
+ match op with
+ (* Operations that affect the floating-point stack cannot be factored *)
+ | Iconst_float _ | Inegf | Iabsf | Iaddf | Isubf | Imulf | Idivf
+ | Iintoffloat | Ifloatofint
+ | Iload((Single | Double | Double_u), _) -> Op_other
+ (* Specific ops *)
+ | Ispecific(Ilea _) -> Op_pure
+ | Ispecific(Istore_int(_, _, is_asg)) -> Op_store is_asg
+ | Ispecific(Istore_symbol(_, _, is_asg)) -> Op_store is_asg
+ | Ispecific(Ioffset_loc(_, _)) -> Op_store true
+ | Ispecific _ -> Op_other
+ | _ -> super#class_of_operation op
+
+method! is_cheap_operation op =
+ match op with
+ | Iconst_int _ | Iconst_blockheader _ -> true
+ | Iconst_symbol _ -> true
+ | _ -> false
+
+end
+
+let fundecl f =
+ (new cse)#fundecl f
diff --git a/asmcomp/i386/arch.ml b/asmcomp/i386/arch.ml
new file mode 100644
index 0000000000..1d486db3ec
--- /dev/null
+++ b/asmcomp/i386/arch.ml
@@ -0,0 +1,162 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Machine-specific command-line options *)
+
+let fast_math = ref false
+
+let command_line_options =
+ [ "-ffast-math", Arg.Set fast_math,
+ " Inline trigonometric and exponential functions" ]
+
+(* Specific operations for the Intel 386 processor *)
+
+open Format
+
+type addressing_mode =
+ Ibased of string * int (* symbol + displ *)
+ | Iindexed of int (* reg + displ *)
+ | Iindexed2 of int (* reg + reg + displ *)
+ | Iscaled of int * int (* reg * scale + displ *)
+ | Iindexed2scaled of int * int (* reg + reg * scale + displ *)
+
+type specific_operation =
+ Ilea of addressing_mode (* Lea gives scaled adds *)
+ | Istore_int of nativeint * addressing_mode * bool
+ (* Store an integer constant *)
+ | Istore_symbol of string * addressing_mode * bool (* Store a symbol *)
+ | Ioffset_loc of int * addressing_mode (* Add a constant to a location *)
+ | Ipush (* Push regs on stack *)
+ | Ipush_int of nativeint (* Push an integer constant *)
+ | Ipush_symbol of string (* Push a symbol *)
+ | Ipush_load of addressing_mode (* Load a scalar and push *)
+ | Ipush_load_float of addressing_mode (* Load a float and push *)
+ | Isubfrev | Idivfrev (* Reversed float sub and div *)
+ | Ifloatarithmem of bool * float_operation * addressing_mode
+ (* Float arith operation with memory *)
+ (* bool: true=64 bits, false=32 *)
+ | Ifloatspecial of string
+
+and float_operation =
+ Ifloatadd | Ifloatsub | Ifloatsubrev | Ifloatmul | Ifloatdiv | Ifloatdivrev
+
+(* Sizes, endianness *)
+
+let big_endian = false
+
+let size_addr = 4
+let size_int = 4
+let size_float = 8
+
+let allow_unaligned_access = true
+
+(* Behavior of division *)
+
+let division_crashes_on_overflow = true
+
+(* Operations on addressing modes *)
+
+let identity_addressing = Iindexed 0
+
+let offset_addressing addr delta =
+ match addr with
+ Ibased(s, n) -> Ibased(s, n + delta)
+ | Iindexed n -> Iindexed(n + delta)
+ | Iindexed2 n -> Iindexed2(n + delta)
+ | Iscaled(scale, n) -> Iscaled(scale, n + delta)
+ | Iindexed2scaled(scale, n) -> Iindexed2scaled(scale, n + delta)
+
+let num_args_addressing = function
+ Ibased(s, n) -> 0
+ | Iindexed n -> 1
+ | Iindexed2 n -> 2
+ | Iscaled(scale, n) -> 1
+ | Iindexed2scaled(scale, n) -> 2
+
+(* Printing operations and addressing modes *)
+
+let print_addressing printreg addr ppf arg =
+ match addr with
+ | Ibased(s, 0) ->
+ fprintf ppf "\"%s\"" s
+ | Ibased(s, n) ->
+ fprintf ppf "\"%s\" + %i" s n
+ | Iindexed n ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a%s" printreg arg.(0) idx
+ | Iindexed2 n ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a + %a%s" printreg arg.(0) printreg arg.(1) idx
+ | Iscaled(scale, n) ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a * %i%s" printreg arg.(0) scale idx
+ | Iindexed2scaled(scale, n) ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a + %a * %i%s" printreg arg.(0) printreg arg.(1) scale idx
+
+let print_specific_operation printreg op ppf arg =
+ match op with
+ | Ilea addr -> print_addressing printreg addr ppf arg
+ | Istore_int(n, addr, is_assign) ->
+ fprintf ppf "[%a] := %nd %s"
+ (print_addressing printreg addr) arg n
+ (if is_assign then "(assign)" else "(init)")
+ | Istore_symbol(lbl, addr, is_assign) ->
+ fprintf ppf "[%a] := \"%s\" %s"
+ (print_addressing printreg addr) arg lbl
+ (if is_assign then "(assign)" else "(init)")
+ | Ioffset_loc(n, addr) ->
+ fprintf ppf "[%a] +:= %i" (print_addressing printreg addr) arg n
+ | Ipush ->
+ fprintf ppf "push ";
+ for i = 0 to Array.length arg - 1 do
+ if i > 0 then fprintf ppf ", ";
+ printreg ppf arg.(i)
+ done
+ | Ipush_int n ->
+ fprintf ppf "push %s" (Nativeint.to_string n)
+ | Ipush_symbol s ->
+ fprintf ppf "push \"%s\"" s
+ | Ipush_load addr ->
+ fprintf ppf "push [%a]" (print_addressing printreg addr) arg
+ | Ipush_load_float addr ->
+ fprintf ppf "pushfloat [%a]" (print_addressing printreg addr) arg
+ | Isubfrev ->
+ fprintf ppf "%a -f(rev) %a" printreg arg.(0) printreg arg.(1)
+ | Idivfrev ->
+ fprintf ppf "%a /f(rev) %a" printreg arg.(0) printreg arg.(1)
+ | Ifloatarithmem(double, op, addr) ->
+ let op_name = function
+ | Ifloatadd -> "+f"
+ | Ifloatsub -> "-f"
+ | Ifloatsubrev -> "-f(rev)"
+ | Ifloatmul -> "*f"
+ | Ifloatdiv -> "/f"
+ | Ifloatdivrev -> "/f(rev)" in
+ let long = if double then "float64" else "float32" in
+ fprintf ppf "%a %s %s[%a]" printreg arg.(0) (op_name op) long
+ (print_addressing printreg addr) (Array.sub arg 1 (Array.length arg - 1))
+ | Ifloatspecial name ->
+ fprintf ppf "%s " name;
+ for i = 0 to Array.length arg - 1 do
+ if i > 0 then fprintf ppf ", ";
+ printreg ppf arg.(i)
+ done
+
+(* Stack alignment constraints *)
+
+let stack_alignment =
+ match Config.system with
+ | "win32" -> 4 (* MSVC *)
+ | _ -> 16
+(* PR#6038: GCC and Clang seem to require 16-byte alignment nowadays,
+ even if only MacOS X's ABI formally requires it *)
diff --git a/asmcomp/i386/emit.mlp b/asmcomp/i386/emit.mlp
new file mode 100644
index 0000000000..70b4540d9a
--- /dev/null
+++ b/asmcomp/i386/emit.mlp
@@ -0,0 +1,1098 @@
+#2 "asmcomp/i386/emit.mlp"
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Emission of Intel 386 assembly code *)
+
+open Misc
+open Cmm
+open Arch
+open Proc
+open Reg
+open Mach
+open Linearize
+open Emitaux
+
+open X86_ast
+open X86_proc
+open X86_dsl
+
+let _label s = D.label ~typ:DWORD s
+
+let mem_sym typ ?(ofs = 0) sym =
+ mem32 typ ~scale:0 ?base:None ~sym ofs RAX (*ignored since scale=0*)
+
+(* CFI directives *)
+
+let cfi_startproc () =
+ if Config.asm_cfi_supported then D.cfi_startproc ()
+
+let cfi_endproc () =
+ if Config.asm_cfi_supported then D.cfi_endproc ()
+
+let cfi_adjust_cfa_offset n =
+ if Config.asm_cfi_supported then D.cfi_adjust_cfa_offset n
+
+let emit_debug_info dbg =
+ emit_debug_info_gen dbg D.file D.loc
+
+(* Tradeoff between code size and code speed *)
+
+let fastcode_flag = ref true
+
+let stack_offset = ref 0
+
+(* Layout of the stack frame *)
+
+let frame_size () = (* includes return address *)
+ let sz =
+ !stack_offset + 4 * num_stack_slots.(0) + 8 * num_stack_slots.(1) + 4
+ in Misc.align sz stack_alignment
+
+let slot_offset loc cl =
+ match loc with
+ | Incoming n ->
+ assert (n >= 0);
+ frame_size() + n
+ | Local n ->
+ if cl = 0
+ then !stack_offset + n * 4
+ else !stack_offset + num_stack_slots.(0) * 4 + n * 8
+ | Outgoing n ->
+ assert (n >= 0);
+ n
+
+(* Record symbols used and defined - at the end generate extern for those
+ used but not defined *)
+
+let symbols_defined = ref StringSet.empty
+let symbols_used = ref StringSet.empty
+
+let add_def_symbol s = symbols_defined := StringSet.add s !symbols_defined
+let add_used_symbol s = symbols_used := StringSet.add s !symbols_used
+
+let trap_frame_size = Misc.align 8 stack_alignment
+
+(* Prefixing of symbols with "_" *)
+
+let symbol_prefix =
+ match system with
+ | S_linux_elf -> ""
+ | S_bsd_elf -> ""
+ | S_solaris -> ""
+ | S_beos -> ""
+ | S_gnu -> ""
+ | _ -> "_" (* win32 & others *)
+
+let emit_symbol s = string_of_symbol symbol_prefix s
+
+let immsym s = sym (emit_symbol s)
+
+let emit_call s = I.call (immsym s)
+
+(* Output a label *)
+
+let label_prefix =
+ match system with
+ | S_linux_elf -> ".L"
+ | S_bsd_elf -> ".L"
+ | S_solaris -> ".L"
+ | S_beos -> ".L"
+ | S_gnu -> ".L"
+ | _ -> "L"
+
+let emit_label lbl =
+ Printf.sprintf "%s%d" label_prefix lbl
+
+let emit_data_label lbl =
+ Printf.sprintf "%sd%d" label_prefix lbl
+
+let label s = sym (emit_label s)
+
+let def_label s = D.label (emit_label s)
+
+let emit_Llabel fallthrough lbl =
+ if not fallthrough && !fastcode_flag then D.align 16 ;
+ def_label lbl
+
+(* Output a pseudo-register *)
+
+let int_reg_name = [| RAX; RBX; RCX; RDX; RSI; RDI; RBP |]
+
+let float_reg_name = [| TOS |]
+
+let register_name r =
+ if r < 100 then Reg32 (int_reg_name.(r))
+ else Regf (float_reg_name.(r - 100))
+
+let sym32 ?ofs s = mem_sym ?ofs DWORD (emit_symbol s)
+
+let reg = function
+ | { loc = Reg r } -> register_name r
+ | { loc = Stack(Incoming n | Outgoing n) } when n < 0 ->
+ sym32 "caml_extra_params" ~ofs:(n + 64)
+ | { loc = Stack s; typ = Float } as r ->
+ let ofs = slot_offset s (register_class r) in
+ mem32 REAL8 ofs RSP
+ | { loc = Stack s } as r ->
+ let ofs = slot_offset s (register_class r) in
+ mem32 DWORD ofs RSP
+ | { loc = Unknown } ->
+ fatal_error "Emit_i386.reg"
+
+(* Output a reference to the lower 8 bits or lower 16 bits of a register *)
+
+let reg_low_8_name = Array.map (fun r -> Reg8L r) int_reg_name
+let reg_low_16_name = Array.map (fun r -> Reg16 r) int_reg_name
+
+let reg8 r =
+ match r.loc with
+ | Reg r when r < 4 -> reg_low_8_name.(r)
+ | _ -> fatal_error "Emit_i386.reg8"
+
+let reg16 r =
+ match r.loc with
+ | Reg r when r < 7 -> reg_low_16_name.(r)
+ | _ -> fatal_error "Emit_i386.reg16"
+
+let reg32 = function
+ | { loc = Reg.Reg r } -> int_reg_name.(r)
+ | _ -> assert false
+
+let arg32 i n = reg32 i.arg.(n)
+
+(* Output an addressing mode *)
+
+let addressing addr typ i n =
+ match addr with
+ | Ibased(s, ofs) ->
+ add_used_symbol s;
+ mem_sym typ (emit_symbol s) ~ofs
+ | Iindexed d ->
+ mem32 typ d (arg32 i n)
+ | Iindexed2 d ->
+ mem32 typ ~base:(arg32 i n) d (arg32 i (n+1))
+ | Iscaled(2, d) ->
+ mem32 typ ~base:(arg32 i n) d (arg32 i n)
+ | Iscaled(scale, d) ->
+ mem32 typ ~scale d (arg32 i n)
+ | Iindexed2scaled(scale, d) ->
+ mem32 typ ~scale ~base:(arg32 i n) d (arg32 i (n+1))
+
+(* Record live pointers at call points *)
+
+let record_frame_label live dbg =
+ let lbl = new_label() in
+ let live_offset = ref [] in
+ Reg.Set.iter
+ (function
+ | {typ = Val; loc = Reg r} ->
+ live_offset := ((r lsl 1) + 1) :: !live_offset
+ | {typ = Val; loc = Stack s} as reg ->
+ live_offset := slot_offset s (register_class reg) :: !live_offset
+ | {typ = Addr} as r ->
+ Misc.fatal_error ("bad GC root " ^ Reg.name r)
+ | _ -> ())
+ live;
+ frame_descriptors :=
+ { fd_lbl = lbl;
+ fd_frame_size = frame_size();
+ fd_live_offset = !live_offset;
+ fd_debuginfo = dbg } :: !frame_descriptors;
+ lbl
+
+let record_frame live dbg =
+ let lbl = record_frame_label live dbg in
+ def_label lbl
+
+(* Record calls to the GC -- we've moved them out of the way *)
+
+type gc_call =
+ { gc_lbl: label; (* Entry label *)
+ gc_return_lbl: label; (* Where to branch after GC *)
+ gc_frame: label } (* Label of frame descriptor *)
+
+let call_gc_sites = ref ([] : gc_call list)
+
+let emit_call_gc gc =
+ def_label gc.gc_lbl;
+ emit_call "caml_call_gc";
+ def_label gc.gc_frame;
+ I.jmp (label gc.gc_return_lbl)
+
+(* Record calls to caml_ml_array_bound_error.
+ In -g mode, we maintain one call to caml_ml_array_bound_error
+ per bound check site. Without -g, we can share a single call. *)
+
+type bound_error_call =
+ { bd_lbl: label; (* Entry label *)
+ bd_frame: label } (* Label of frame descriptor *)
+
+let bound_error_sites = ref ([] : bound_error_call list)
+let bound_error_call = ref 0
+
+let bound_error_label dbg =
+ if !Clflags.debug then begin
+ let lbl_bound_error = new_label() in
+ let lbl_frame = record_frame_label Reg.Set.empty dbg in
+ bound_error_sites :=
+ { bd_lbl = lbl_bound_error; bd_frame = lbl_frame } :: !bound_error_sites;
+ lbl_bound_error
+ end else begin
+ if !bound_error_call = 0 then bound_error_call := new_label();
+ !bound_error_call
+ end
+
+let emit_call_bound_error bd =
+ def_label bd.bd_lbl;
+ emit_call "caml_ml_array_bound_error";
+ def_label bd.bd_frame
+
+let emit_call_bound_errors () =
+ List.iter emit_call_bound_error !bound_error_sites;
+ if !bound_error_call > 0 then begin
+ def_label !bound_error_call;
+ emit_call "caml_ml_array_bound_error"
+ end
+
+(* Names for instructions *)
+
+let instr_for_intop = function
+ | Iadd -> I.add
+ | Isub -> I.sub
+ | Imul -> (fun arg1 arg2 -> I.imul arg1 (Some arg2))
+ | Iand -> I.and_
+ | Ior -> I.or_
+ | Ixor -> I.xor
+ | Ilsl -> I.sal
+ | Ilsr -> I.shr
+ | Iasr -> I.sar
+ | _ -> fatal_error "Emit_i386: instr_for_intop"
+
+let unary_instr_for_floatop = function
+ | Inegf -> I.fchs ()
+ | Iabsf -> I.fabs ()
+ | _ -> fatal_error "Emit_i386: unary_instr_for_floatop"
+
+let instr_for_floatop = function
+ | Iaddf -> I.fadd
+ | Isubf -> I.fsub
+ | Imulf -> I.fmul
+ | Idivf -> I.fdiv
+ | Ispecific Isubfrev -> I.fsubr
+ | Ispecific Idivfrev -> I.fdivr
+ | _ -> fatal_error "Emit_i386: instr_for_floatop"
+
+let instr_for_floatop_reversed = function
+ | Iaddf -> I.fadd
+ | Isubf -> I.fsubr
+ | Imulf -> I.fmul
+ | Idivf -> I.fdivr
+ | Ispecific Isubfrev -> I.fsub
+ | Ispecific Idivfrev -> I.fdiv
+ | _ -> fatal_error "Emit_i386: instr_for_floatop_reversed"
+
+
+let instr_for_floatop_reversed_pop = function
+ | Iaddf -> I.faddp
+ | Isubf -> I.fsubrp
+ | Imulf -> I.fmulp
+ | Idivf -> I.fdivrp
+ | Ispecific Isubfrev -> I.fsubp
+ | Ispecific Idivfrev -> I.fdivp
+ | _ -> fatal_error "Emit_i386: instr_for_floatop_reversed_pop"
+
+let instr_for_floatarithmem = function
+ | Ifloatadd -> I.fadd
+ | Ifloatsub -> I.fsub
+ | Ifloatsubrev -> I.fsubr
+ | Ifloatmul -> I.fmul
+ | Ifloatdiv -> I.fdiv
+ | Ifloatdivrev -> I.fdivr
+
+let cond = function
+ | Isigned Ceq -> E | Isigned Cne -> NE
+ | Isigned Cle -> LE | Isigned Cgt -> G
+ | Isigned Clt -> L | Isigned Cge -> GE
+ | Iunsigned Ceq -> E | Iunsigned Cne -> NE
+ | Iunsigned Cle -> BE | Iunsigned Cgt -> A
+ | Iunsigned Clt -> B | Iunsigned Cge -> AE
+
+(* Output an = 0 or <> 0 test. *)
+
+let output_test_zero arg =
+ match arg.loc with
+ | Reg.Reg _ -> I.test (reg arg) (reg arg)
+ | _ -> I.cmp (int 0) (reg arg)
+
+(* Deallocate the stack frame before a return or tail call *)
+
+let output_epilogue f =
+ let n = frame_size() - 4 in
+ if n > 0 then
+ begin
+ I.add (int n) esp;
+ cfi_adjust_cfa_offset (-n);
+ f ();
+ (* reset CFA back cause function body may continue *)
+ cfi_adjust_cfa_offset n
+ end
+ else
+ f ()
+
+(* Determine if the given register is the top of the floating-point stack *)
+
+let is_tos = function { loc = Reg _; typ = Float } -> true | _ -> false
+
+(* Emit the code for a floating-point comparison *)
+
+let emit_float_test cmp neg arg lbl =
+ let actual_cmp =
+ match (is_tos arg.(0), is_tos arg.(1)) with
+ | (true, true) ->
+ (* both args on top of FP stack *)
+ I.fcompp ();
+ cmp
+ | (true, false) ->
+ (* first arg on top of FP stack *)
+ I.fcomp (reg arg.(1));
+ cmp
+ | (false, true) ->
+ (* second arg on top of FP stack *)
+ I.fcomp (reg arg.(0));
+ Cmm.swap_comparison cmp
+ | (false, false) ->
+ I.fld (reg arg.(0));
+ I.fcomp (reg arg.(1));
+ cmp
+ in
+ I.fnstsw ax;
+ match actual_cmp with
+ | Ceq ->
+ if neg then begin
+ I.and_ (int 68) ah;
+ I.xor (int 64) ah;
+ I.jne lbl
+ end else begin
+ I.and_ (int 69) ah;
+ I.cmp (int 64) ah;
+ I.je lbl
+ end
+ | Cne ->
+ if neg then begin
+ I.and_ (int 69) ah;
+ I.cmp (int 64) ah;
+ I.je lbl
+ end else begin
+ I.and_ (int 68) ah;
+ I.xor (int 64) ah;
+ I.jne lbl
+ end
+ | Cle ->
+ I.and_ (int 69) ah;
+ I.dec ah;
+ I.cmp (int 64) ah;
+ if neg
+ then I.jae lbl
+ else I.jb lbl
+ | Cge ->
+ I.and_ (int 5) ah;
+ if neg
+ then I.jne lbl
+ else I.je lbl
+ | Clt ->
+ I.and_ (int 69) ah;
+ I.cmp (int 1) ah;
+ if neg
+ then I.jne lbl
+ else I.je lbl
+ | Cgt ->
+ I.and_ (int 69) ah;
+ if neg
+ then I.jne lbl
+ else I.je lbl
+
+(* Emit a Ifloatspecial instruction *)
+
+let emit_floatspecial = function
+ | "atan" -> I.fld1 (); I.fpatan ()
+ | "atan2" -> I.fpatan ()
+ | "cos" -> I.fcos ()
+ | "log" -> I.fldln2 (); I.fxch st1; I.fyl2x ()
+ | "log10" -> I.fldlg2 (); I.fxch st1; I.fyl2x ()
+ | "sin" -> I.fsin ()
+ | "sqrt" -> I.fsqrt ()
+ | "tan" -> I.fptan (); I.fstp st0
+ | _ -> assert false
+
+(* Floating-point constants *)
+
+let float_constants = ref ([] : (int64 * int) list)
+
+let add_float_constant cst =
+ let repr = Int64.bits_of_float cst in
+ try
+ List.assoc repr !float_constants
+ with
+ Not_found ->
+ let lbl = new_label() in
+ float_constants := (repr, lbl) :: !float_constants;
+ lbl
+
+let emit_float64_split_directive x =
+ let lo = Int64.logand x 0xFFFF_FFFFL
+ and hi = Int64.shift_right_logical x 32 in
+ D.long (Const (if Arch.big_endian then hi else lo));
+ D.long (Const (if Arch.big_endian then lo else hi))
+
+let emit_float_constant cst lbl =
+ _label (emit_label lbl);
+ emit_float64_split_directive cst
+
+let emit_global_label s =
+ let lbl = Compilenv.make_symbol (Some s) in
+ add_def_symbol lbl;
+ let lbl = emit_symbol lbl in
+ D.global lbl;
+ _label lbl
+
+(* Output the assembly code for an instruction *)
+
+(* Name of current function *)
+let function_name = ref ""
+(* Entry point for tail recursive calls *)
+let tailrec_entry_point = ref 0
+(* Record references to external C functions (for MacOSX) *)
+let external_symbols_direct = ref StringSet.empty
+let external_symbols_indirect = ref StringSet.empty
+
+let emit_instr fallthrough i =
+ emit_debug_info i.dbg;
+ match i.desc with
+ | Lend -> ()
+ | Lop(Imove | Ispill | Ireload) ->
+ let src = i.arg.(0) and dst = i.res.(0) in
+ if src.loc <> dst.loc then begin
+ if src.typ = Float then
+ if is_tos src then
+ I.fstp (reg dst)
+ else if is_tos dst then
+ I.fld (reg src)
+ else begin
+ I.fld (reg src);
+ I.fstp (reg dst)
+ end
+ else
+ I.mov (reg src) (reg dst)
+ end
+ | Lop(Iconst_int n | Iconst_blockheader n) ->
+ if n = 0n then begin
+ match i.res.(0).loc with
+ | Reg _ -> I.xor (reg i.res.(0)) (reg i.res.(0))
+ | _ -> I.mov (int 0) (reg i.res.(0))
+ end else
+ I.mov (nat n) (reg i.res.(0))
+ | Lop(Iconst_float f) ->
+ begin match Int64.bits_of_float f with
+ | 0x0000_0000_0000_0000L -> (* +0.0 *)
+ I.fldz ()
+ | 0x8000_0000_0000_0000L -> (* -0.0 *)
+ I.fldz (); I.fchs ()
+ | 0x3FF0_0000_0000_0000L -> (* 1.0 *)
+ I.fld1 ()
+ | 0xBFF0_0000_0000_0000L -> (* -1.0 *)
+ I.fld1 (); I.fchs ()
+ | _ ->
+ let lbl = add_float_constant f in
+ I.fld (mem_sym REAL8 (emit_label lbl))
+ end
+ | Lop(Iconst_symbol s) ->
+ add_used_symbol s;
+ I.mov (immsym s) (reg i.res.(0))
+ | Lop(Icall_ind) ->
+ I.call (reg i.arg.(0));
+ record_frame i.live i.dbg
+ | Lop(Icall_imm s) ->
+ add_used_symbol s;
+ emit_call s;
+ record_frame i.live i.dbg
+ | Lop(Itailcall_ind) ->
+ output_epilogue begin fun () ->
+ I.jmp (reg i.arg.(0))
+ end
+ | Lop(Itailcall_imm s) ->
+ if s = !function_name then
+ I.jmp (label !tailrec_entry_point)
+ else begin
+ output_epilogue begin fun () ->
+ add_used_symbol s;
+ I.jmp (immsym s)
+ end
+ end
+ | Lop(Iextcall(s, alloc)) ->
+ add_used_symbol s;
+ if alloc then begin
+ if system <> S_macosx then
+ I.mov (immsym s) eax
+ else begin
+ external_symbols_indirect :=
+ StringSet.add s !external_symbols_indirect;
+ I.mov (mem_sym DWORD (Printf.sprintf "L%s$non_lazy_ptr"
+ (emit_symbol s))) eax
+ end;
+ emit_call "caml_c_call";
+ record_frame i.live i.dbg
+ end else begin
+ if system <> S_macosx then
+ emit_call s
+ else begin
+ external_symbols_direct :=
+ StringSet.add s !external_symbols_direct;
+ I.call (sym (Printf.sprintf "L%s$stub" (emit_symbol s)))
+ end
+ end
+ | Lop(Istackoffset n) ->
+ if n < 0
+ then I.add (int (-n)) esp
+ else I.sub (int n) esp;
+ cfi_adjust_cfa_offset n;
+ stack_offset := !stack_offset + n
+ | Lop(Iload(chunk, addr)) ->
+ let dest = i.res.(0) in
+ begin match chunk with
+ | Word_int | Word_val | Thirtytwo_signed | Thirtytwo_unsigned ->
+ I.mov (addressing addr DWORD i 0) (reg dest)
+ | Byte_unsigned ->
+ I.movzx (addressing addr BYTE i 0) (reg dest)
+ | Byte_signed ->
+ I.movsx (addressing addr BYTE i 0) (reg dest)
+ | Sixteen_unsigned ->
+ I.movzx (addressing addr WORD i 0) (reg dest)
+ | Sixteen_signed ->
+ I.movsx (addressing addr WORD i 0) (reg dest)
+ | Single ->
+ I.fld (addressing addr REAL4 i 0)
+ | Double | Double_u ->
+ I.fld (addressing addr REAL8 i 0)
+ end
+ | Lop(Istore(chunk, addr, _)) ->
+ begin match chunk with
+ | Word_int | Word_val | Thirtytwo_signed | Thirtytwo_unsigned ->
+ I.mov (reg i.arg.(0)) (addressing addr DWORD i 1)
+ | Byte_unsigned | Byte_signed ->
+ I.mov (reg8 i.arg.(0)) (addressing addr BYTE i 1)
+ | Sixteen_unsigned | Sixteen_signed ->
+ I.mov (reg16 i.arg.(0)) (addressing addr WORD i 1)
+ | Single ->
+ if is_tos i.arg.(0) then
+ I.fstp (addressing addr REAL4 i 1)
+ else begin
+ I.fld (reg i.arg.(0));
+ I.fstp (addressing addr REAL4 i 1)
+ end
+ | Double | Double_u ->
+ if is_tos i.arg.(0) then
+ I.fstp (addressing addr REAL8 i 1)
+ else begin
+ I.fld (reg i.arg.(0));
+ I.fstp (addressing addr REAL8 i 1)
+ end
+ end
+ | Lop(Ialloc n) ->
+ if !fastcode_flag then begin
+ let lbl_redo = new_label() in
+ def_label lbl_redo;
+ I.mov (sym32 "caml_young_ptr") eax;
+ I.sub (int n) eax;
+ I.mov eax (sym32 "caml_young_ptr");
+ I.cmp (sym32 "caml_young_limit") eax;
+ let lbl_call_gc = new_label() in
+ let lbl_frame = record_frame_label i.live Debuginfo.none in
+ I.jb (label lbl_call_gc);
+ I.lea (mem32 NONE 4 RAX) (reg i.res.(0));
+ call_gc_sites :=
+ { gc_lbl = lbl_call_gc;
+ gc_return_lbl = lbl_redo;
+ gc_frame = lbl_frame } :: !call_gc_sites
+ end else begin
+ begin match n with
+ 8 -> emit_call "caml_alloc1"
+ | 12 -> emit_call "caml_alloc2"
+ | 16 -> emit_call "caml_alloc3"
+ | _ ->
+ I.mov (int n) eax;
+ emit_call "caml_allocN"
+ end;
+ record_frame i.live Debuginfo.none;
+ I.lea (mem32 NONE 4 RAX) (reg i.res.(0))
+ end
+ | Lop(Iintop(Icomp cmp)) ->
+ I.cmp (reg i.arg.(1)) (reg i.arg.(0));
+ I.set (cond cmp) al;
+ I.movzx al (reg i.res.(0));
+ | Lop(Iintop_imm(Icomp cmp, n)) ->
+ I.cmp (int n) (reg i.arg.(0));
+ I.set (cond cmp) al;
+ I.movzx al (reg i.res.(0))
+ | Lop(Iintop Icheckbound) ->
+ let lbl = bound_error_label i.dbg in
+ I.cmp (reg i.arg.(1)) (reg i.arg.(0));
+ I.jbe (label lbl)
+ | Lop(Iintop_imm(Icheckbound, n)) ->
+ let lbl = bound_error_label i.dbg in
+ I.cmp (int n) (reg i.arg.(0));
+ I.jbe (label lbl)
+ | Lop(Iintop(Idiv | Imod)) ->
+ I.cdq ();
+ I.idiv (reg i.arg.(1))
+ | Lop(Iintop(Ilsl | Ilsr | Iasr as op)) ->
+ (* We have i.arg.(0) = i.res.(0) and i.arg.(1) = %ecx *)
+ instr_for_intop op cl (reg i.res.(0))
+ | Lop(Iintop Imulh) ->
+ I.imul (reg i.arg.(1)) None
+ | Lop(Iintop op) ->
+ (* We have i.arg.(0) = i.res.(0) *)
+ instr_for_intop op (reg i.arg.(1)) (reg i.res.(0))
+ | Lop(Iintop_imm(Iadd, n)) when i.arg.(0).loc <> i.res.(0).loc ->
+ I.lea (mem32 NONE n (reg32 i.arg.(0))) (reg i.res.(0))
+ | Lop(Iintop_imm(Iadd, 1) | Iintop_imm(Isub, -1)) ->
+ I.inc (reg i.res.(0))
+ | Lop(Iintop_imm(Iadd, -1) | Iintop_imm(Isub, 1)) ->
+ I.dec (reg i.res.(0))
+ | Lop(Iintop_imm(op, n)) ->
+ (* We have i.arg.(0) = i.res.(0) *)
+ instr_for_intop op (int n) (reg i.res.(0))
+ | Lop(Inegf | Iabsf as floatop) ->
+ if not (is_tos i.arg.(0)) then
+ I.fld (reg i.arg.(0));
+ unary_instr_for_floatop floatop
+ | Lop(Iaddf | Isubf | Imulf | Idivf | Ispecific(Isubfrev | Idivfrev)
+ as floatop) ->
+ begin match (is_tos i.arg.(0), is_tos i.arg.(1)) with
+ (true, true) ->
+ (* both operands on top of FP stack *)
+ instr_for_floatop_reversed_pop floatop st0 st1
+ | (true, false) ->
+ (* first operand on stack *)
+ instr_for_floatop floatop (reg i.arg.(1))
+ | (false, true) ->
+ (* second operand on stack *)
+ instr_for_floatop_reversed floatop (reg i.arg.(0))
+ | (false, false) ->
+ (* both operands in memory *)
+ I.fld (reg i.arg.(0));
+ instr_for_floatop floatop (reg i.arg.(1))
+ end
+ | Lop(Ifloatofint) ->
+ begin match i.arg.(0).loc with
+ | Stack _ ->
+ I.fild (reg i.arg.(0))
+ | _ ->
+ I.push (reg i.arg.(0));
+ I.fild (mem32 DWORD 0 RSP);
+ I.add (int 4) esp
+ end
+ | Lop(Iintoffloat) ->
+ if not (is_tos i.arg.(0)) then
+ I.fld (reg i.arg.(0));
+ stack_offset := !stack_offset - 8;
+ I.sub (int 8) esp;
+ cfi_adjust_cfa_offset 8;
+ I.fnstcw (mem32 NONE 4 RSP);
+ I.mov (mem32 WORD 4 RSP) ax;
+ I.mov (int 12) ah;
+ I.mov ax (mem32 WORD 0 RSP);
+ I.fldcw (mem32 NONE 0 RSP);
+ begin match i.res.(0).loc with
+ | Stack _ ->
+ I.fistp (reg i.res.(0))
+ | _ ->
+ I.fistp (mem32 DWORD 0 RSP);
+ I.mov (mem32 DWORD 0 RSP) (reg i.res.(0))
+ end;
+ I.fldcw (mem32 NONE 4 RSP);
+ I.add (int 8) esp;
+ cfi_adjust_cfa_offset (-8);
+ stack_offset := !stack_offset + 8
+ | Lop(Ispecific(Ilea addr)) ->
+ I.lea (addressing addr DWORD i 0) (reg i.res.(0))
+ | Lop(Ispecific(Istore_int(n, addr, _))) ->
+ I.mov (nat n) (addressing addr DWORD i 0)
+ | Lop(Ispecific(Istore_symbol(s, addr, _))) ->
+ add_used_symbol s;
+ I.mov (immsym s) (addressing addr DWORD i 0)
+ | Lop(Ispecific(Ioffset_loc(n, addr))) ->
+ I.add (int n) (addressing addr DWORD i 0)
+ | Lop(Ispecific(Ipush)) ->
+ (* Push arguments in reverse order *)
+ for n = Array.length i.arg - 1 downto 0 do
+ let r = i.arg.(n) in
+ match r with
+ {loc = Reg _; typ = Float} ->
+ I.sub (int 8) esp;
+ cfi_adjust_cfa_offset 8;
+ I.fstp (mem32 REAL8 0 RSP);
+ stack_offset := !stack_offset + 8
+ | {loc = Stack sl; typ = Float} ->
+ let ofs = slot_offset sl 1 in
+ (* Use x87 stack to move from stack to stack,
+ instead of two 32-bit push instructions,
+ which could kill performance on modern CPUs (see #6979).
+ *)
+ I.fld (mem32 REAL8 ofs RSP);
+ I.sub (int 8) esp;
+ cfi_adjust_cfa_offset 8;
+ I.fstp (mem32 REAL8 0 RSP);
+ stack_offset := !stack_offset + 8
+ | _ ->
+ I.push (reg r);
+ cfi_adjust_cfa_offset 4;
+ stack_offset := !stack_offset + 4
+ done
+ | Lop(Ispecific(Ipush_int n)) ->
+ I.push (nat n);
+ cfi_adjust_cfa_offset 4;
+ stack_offset := !stack_offset + 4
+ | Lop(Ispecific(Ipush_symbol s)) ->
+ add_used_symbol s;
+ I.push (immsym s);
+ cfi_adjust_cfa_offset 4;
+ stack_offset := !stack_offset + 4
+ | Lop(Ispecific(Ipush_load addr)) ->
+ I.push (addressing addr DWORD i 0);
+ cfi_adjust_cfa_offset 4;
+ stack_offset := !stack_offset + 4
+ | Lop(Ispecific(Ipush_load_float addr)) ->
+ I.push (addressing (offset_addressing addr 4) DWORD i 0);
+ I.push (addressing addr DWORD i 0);
+ cfi_adjust_cfa_offset 8;
+ stack_offset := !stack_offset + 8
+ | Lop(Ispecific(Ifloatarithmem(double, op, addr))) ->
+ if not (is_tos i.arg.(0)) then
+ I.fld (reg i.arg.(0));
+ instr_for_floatarithmem op
+ (addressing addr
+ (if double then REAL8 else REAL4) i 1)
+ | Lop(Ispecific(Ifloatspecial s)) ->
+ (* Push args on float stack if necessary *)
+ for k = 0 to Array.length i.arg - 1 do
+ if not (is_tos i.arg.(k)) then I.fld (reg i.arg.(k))
+ done;
+ (* Fix-up for binary instrs whose args were swapped *)
+ if Array.length i.arg = 2 && is_tos i.arg.(1) then
+ I.fxch st1;
+ emit_floatspecial s
+ | Lreloadretaddr ->
+ ()
+ | Lreturn ->
+ output_epilogue begin fun () ->
+ I.ret ()
+ end
+ | Llabel lbl ->
+ emit_Llabel fallthrough lbl
+ | Lbranch lbl ->
+ I.jmp (label lbl)
+ | Lcondbranch(tst, lbl) ->
+ let lbl = label lbl in
+ begin match tst with
+ | Itruetest ->
+ output_test_zero i.arg.(0);
+ I.jne lbl;
+ | Ifalsetest ->
+ output_test_zero i.arg.(0);
+ I.je lbl
+ | Iinttest cmp ->
+ I.cmp (reg i.arg.(1)) (reg i.arg.(0));
+ I.j (cond cmp) lbl
+ | Iinttest_imm((Isigned Ceq | Isigned Cne |
+ Iunsigned Ceq | Iunsigned Cne) as cmp, 0) ->
+ output_test_zero i.arg.(0);
+ I.j (cond cmp) lbl
+ | Iinttest_imm(cmp, n) ->
+ I.cmp (int n) (reg i.arg.(0));
+ I.j (cond cmp) lbl
+ | Ifloattest(cmp, neg) ->
+ emit_float_test cmp neg i.arg lbl
+ | Ioddtest ->
+ I.test (int 1) (reg i.arg.(0));
+ I.jne lbl
+ | Ieventest ->
+ I.test (int 1) (reg i.arg.(0));
+ I.je lbl
+ end
+ | Lcondbranch3(lbl0, lbl1, lbl2) ->
+ I.cmp (int 1) (reg i.arg.(0));
+ begin match lbl0 with
+ None -> ()
+ | Some lbl -> I.jb (label lbl)
+ end;
+ begin match lbl1 with
+ None -> ()
+ | Some lbl -> I.je (label lbl)
+ end;
+ begin match lbl2 with
+ None -> ()
+ | Some lbl -> I.jg (label lbl)
+ end
+ | Lswitch jumptbl ->
+ let lbl = new_label() in
+ I.jmp (mem32 NONE 0 (reg32 i.arg.(0)) ~scale:4 ~sym:(emit_label lbl));
+ D.data ();
+ _label (emit_label lbl);
+ for i = 0 to Array.length jumptbl - 1 do
+ D.long (ConstLabel (emit_label jumptbl.(i)))
+ done;
+ D.text ()
+ | Lsetuptrap lbl ->
+ I.call (label lbl)
+ | Lpushtrap ->
+ if trap_frame_size > 8 then
+ I.sub (int (trap_frame_size - 8)) esp;
+ I.push (sym32 "caml_exception_pointer");
+ cfi_adjust_cfa_offset trap_frame_size;
+ I.mov esp (sym32 "caml_exception_pointer");
+ stack_offset := !stack_offset + trap_frame_size
+ | Lpoptrap ->
+ I.pop (sym32 "caml_exception_pointer");
+ I.add (int (trap_frame_size - 4)) esp;
+ cfi_adjust_cfa_offset (-trap_frame_size);
+ stack_offset := !stack_offset - trap_frame_size
+ | Lraise k ->
+ begin match !Clflags.debug, k with
+ | true, Lambda.Raise_regular ->
+ emit_call "caml_raise_exn";
+ record_frame Reg.Set.empty i.dbg
+ | true, Lambda.Raise_reraise ->
+ emit_call "caml_reraise_exn";
+ record_frame Reg.Set.empty i.dbg
+ | false, _
+ | true, Lambda.Raise_notrace ->
+ I.mov (sym32 "caml_exception_pointer") esp;
+ I.pop (sym32 "caml_exception_pointer");
+ if trap_frame_size > 8 then
+ I.add (int (trap_frame_size - 8)) esp;
+ I.ret ()
+ end
+
+let rec emit_all fallthrough i =
+ match i.desc with
+ | Lend -> ()
+ | _ ->
+ emit_instr fallthrough i;
+ emit_all
+ (system = S_win32 || Linearize.has_fallthrough i.desc)
+ i.next
+
+(* Emission of external symbol references (for MacOSX) *)
+
+let emit_external_symbol_direct s =
+ _label (Printf.sprintf "L%s$stub" (emit_symbol s));
+ D.indirect_symbol (emit_symbol s);
+ I.hlt (); I.hlt (); I.hlt (); I.hlt () ; I.hlt ()
+
+let emit_external_symbol_indirect s =
+ _label (Printf.sprintf "L%s$non_lazy_ptr" (emit_symbol s));
+ D.indirect_symbol (emit_symbol s);
+ D.long (const 0)
+
+let emit_external_symbols () =
+ D.section [ "__IMPORT"; "__pointers"] None ["non_lazy_symbol_pointers" ];
+ StringSet.iter emit_external_symbol_indirect !external_symbols_indirect;
+ external_symbols_indirect := StringSet.empty;
+ D.section [ "__IMPORT"; "__jump_table"] None
+ [ "symbol_stubs"; "self_modifying_code+pure_instructions"; "5" ];
+ StringSet.iter emit_external_symbol_direct !external_symbols_direct;
+ external_symbols_direct := StringSet.empty;
+ if !Clflags.gprofile then begin
+ _label "Lmcount$stub";
+ D.indirect_symbol "mcount";
+ I.hlt (); I.hlt (); I.hlt () ; I.hlt () ; I.hlt ()
+ end
+
+(* Emission of the profiling prelude *)
+
+let call_mcount mcount =
+ I.push eax;
+ I.mov esp ebp;
+ I.push ecx;
+ I.push edx;
+ I.call (sym mcount);
+ I.pop edx;
+ I.pop ecx;
+ I.pop eax
+
+let emit_profile () =
+ match system with
+ | S_linux_elf | S_gnu -> call_mcount "mcount"
+ | S_bsd_elf -> call_mcount ".mcount"
+ | S_macosx -> call_mcount "Lmcount$stub"
+ | _ -> () (*unsupported yet*)
+
+(* Emission of a function declaration *)
+
+let fundecl fundecl =
+ function_name := fundecl.fun_name;
+ fastcode_flag := fundecl.fun_fast;
+ tailrec_entry_point := new_label();
+ stack_offset := 0;
+ call_gc_sites := [];
+ bound_error_sites := [];
+ bound_error_call := 0;
+ D.text ();
+ add_def_symbol fundecl.fun_name;
+ D.align (if system = S_win32 then 4 else 16);
+ if system = S_macosx
+ && not !Clflags.output_c_object
+ && is_generic_function fundecl.fun_name
+ then (* PR#4690 *)
+ D.private_extern (emit_symbol fundecl.fun_name)
+ else
+ D.global (emit_symbol fundecl.fun_name);
+ D.label (emit_symbol fundecl.fun_name);
+ emit_debug_info fundecl.fun_dbg;
+ cfi_startproc ();
+ if !Clflags.gprofile then emit_profile();
+ let n = frame_size() - 4 in
+ if n > 0 then begin
+ I.sub (int n) esp;
+ cfi_adjust_cfa_offset n;
+ end;
+ def_label !tailrec_entry_point;
+ emit_all true fundecl.fun_body;
+ List.iter emit_call_gc !call_gc_sites;
+ emit_call_bound_errors ();
+ cfi_endproc ();
+ begin match system with
+ | S_linux_elf | S_bsd_elf | S_gnu ->
+ D.type_ (emit_symbol fundecl.fun_name) "@function";
+ D.size (emit_symbol fundecl.fun_name)
+ (ConstSub (
+ ConstThis,
+ ConstLabel (emit_symbol fundecl.fun_name)))
+ | _ -> ()
+ end
+
+
+(* Emission of data *)
+
+let emit_item = function
+ | Cglobal_symbol s -> D.global (emit_symbol s)
+ | Cdefine_symbol s -> add_def_symbol s; _label (emit_symbol s)
+ | Cdefine_label lbl -> _label (emit_data_label lbl)
+ | Cint8 n -> D.byte (const n)
+ | Cint16 n -> D.word (const n)
+ | Cint32 n -> D.long (const_nat n)
+ | Cint n -> D.long (const_nat n)
+ | Csingle f -> D.long (Const (Int64.of_int32 (Int32.bits_of_float f)))
+ | Cdouble f -> emit_float64_split_directive (Int64.bits_of_float f)
+ | Csymbol_address s -> add_used_symbol s; D.long (ConstLabel (emit_symbol s))
+ | Clabel_address lbl -> D.long (ConstLabel (emit_data_label lbl))
+ | Cstring s -> D.bytes s
+ | Cskip n -> if n > 0 then D.space n
+ | Calign n -> D.align n
+
+let data l =
+ D.data ();
+ List.iter emit_item l
+
+(* Beginning / end of an assembly file *)
+
+let begin_assembly() =
+ X86_proc.reset_asm_code ();
+ reset_debug_info(); (* PR#5603 *)
+ float_constants := [];
+ if system = S_win32 then begin
+ D.mode386 ();
+ D.model "FLAT";
+ D.extrn "_caml_young_ptr" DWORD;
+ D.extrn "_caml_young_limit" DWORD;
+ D.extrn "_caml_exception_pointer" DWORD;
+ D.extrn "_caml_extra_params" DWORD;
+ D.extrn "_caml_call_gc" PROC;
+ D.extrn "_caml_c_call" PROC;
+ D.extrn "_caml_allocN" PROC;
+ D.extrn "_caml_alloc1" PROC;
+ D.extrn "_caml_alloc2" PROC;
+ D.extrn "_caml_alloc3" PROC;
+ D.extrn "_caml_ml_array_bound_error" PROC;
+ D.extrn "_caml_raise_exn" PROC;
+ D.extrn "_caml_reraise_exn" PROC;
+ end;
+
+ D.data ();
+ emit_global_label "data_begin";
+
+ D.text ();
+ emit_global_label "code_begin";
+ if system = S_macosx then I.nop (); (* PR#4690 *)
+ ()
+
+let end_assembly() =
+ if !float_constants <> [] then begin
+ D.data ();
+ List.iter (fun (cst,lbl) -> emit_float_constant cst lbl) !float_constants
+ end;
+
+ D.text ();
+ if system = S_macosx then I.nop ();
+ (* suppress "ld warning: atom sorting error" *)
+
+ emit_global_label "code_end";
+
+ D.data ();
+ emit_global_label "data_end";
+ D.long (const 0);
+
+ emit_global_label "frametable";
+
+ emit_frames
+ { efa_label = (fun l -> D.long (ConstLabel (emit_label l)));
+ efa_16 = (fun n -> D.word (const n));
+ efa_32 = (fun n -> D.long (const_32 n));
+ efa_word = (fun n -> D.long (const n));
+ efa_align = D.align;
+ efa_label_rel = (fun lbl ofs ->
+ D.long (ConstAdd (
+ ConstSub(ConstLabel(emit_label lbl),
+ ConstThis),
+ const_32 ofs)));
+ efa_def_label = (fun l -> _label (emit_label l));
+ efa_string = (fun s -> D.bytes (s ^ "\000"))
+ };
+
+ if system = S_macosx then emit_external_symbols ();
+ if system = S_linux_elf then
+ (* Mark stack as non-executable, PR#4564 *)
+ D.section [".note.GNU-stack"] (Some "") ["%progbits"];
+
+ if system = S_win32 then begin
+ D.comment "External functions";
+ StringSet.iter
+ (fun s ->
+ if not (StringSet.mem s !symbols_defined) then
+ D.extrn (emit_symbol s) PROC)
+ !symbols_used;
+ symbols_used := StringSet.empty;
+ symbols_defined := StringSet.empty;
+ end;
+
+ let asm =
+ if !Emitaux.create_asm_file then
+ Some
+ (
+ (if X86_proc.masm then X86_masm.generate_asm
+ else X86_gas.generate_asm) !Emitaux.output_channel
+ )
+ else
+ None
+ in
+ X86_proc.generate_code asm
diff --git a/asmcomp/i386/proc.ml b/asmcomp/i386/proc.ml
new file mode 100644
index 0000000000..9f009c7878
--- /dev/null
+++ b/asmcomp/i386/proc.ml
@@ -0,0 +1,224 @@
+# 2 "asmcomp/i386/proc.ml"
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Description of the Intel 386 processor *)
+
+open Misc
+open Arch
+open Cmm
+open Reg
+open Mach
+
+(* Which asm conventions to use *)
+let masm =
+ match Config.ccomp_type with
+ | "msvc" -> true
+ | _ -> false
+
+(* Registers available for register allocation *)
+
+(* Register map:
+ eax 0 eax - edi: function arguments and results
+ ebx 1 eax: C function results
+ ecx 2 ebx, esi, edi, ebp: preserved by C
+ edx 3
+ esi 4
+ edi 5
+ ebp 6
+
+ tos 100 top of floating-point stack. *)
+
+let int_reg_name =
+ if masm then
+ [| "eax"; "ebx"; "ecx"; "edx"; "esi"; "edi"; "ebp" |]
+ else
+ [| "%eax"; "%ebx"; "%ecx"; "%edx"; "%esi"; "%edi"; "%ebp" |]
+
+let float_reg_name =
+ if masm then
+ [| "tos" |]
+ else
+ [| "%tos" |]
+
+let num_register_classes = 2
+
+let register_class r =
+ match r.typ with
+ | Val | Int | Addr -> 0
+ | Float -> 1
+
+let num_available_registers = [| 7; 0 |]
+
+let first_available_register = [| 0; 100 |]
+
+let register_name r =
+ if r < 100 then int_reg_name.(r) else float_reg_name.(r - 100)
+
+(* There is little scheduling, and some operations are more compact
+ when their argument is %eax. *)
+
+let rotate_registers = false
+
+(* Representation of hard registers by pseudo-registers *)
+
+let hard_int_reg =
+ let v = Array.make 7 Reg.dummy in
+ for i = 0 to 6 do v.(i) <- Reg.at_location Int (Reg i) done;
+ v
+
+let hard_float_reg = [| Reg.at_location Float (Reg 100) |]
+
+let all_phys_regs =
+ Array.append hard_int_reg hard_float_reg
+
+let phys_reg n =
+ if n < 100 then hard_int_reg.(n) else hard_float_reg.(n - 100)
+
+let eax = phys_reg 0
+let ecx = phys_reg 2
+let edx = phys_reg 3
+let tos = phys_reg 100
+
+let stack_slot slot ty =
+ Reg.at_location ty (Stack slot)
+
+(* Instruction selection *)
+
+let word_addressed = false
+
+(* Calling conventions *)
+
+(* To supplement the processor's meagre supply of registers, we also
+ use some global memory locations to pass arguments beyond the 6th.
+ These globals are denoted by Incoming and Outgoing stack locations
+ with negative offsets, starting at -64.
+ Unlike arguments passed on stack, arguments passed in globals
+ do not prevent tail-call elimination. The caller stores arguments
+ in these globals immediately before the call, and the first thing the
+ callee does is copy them to registers or stack locations.
+ Neither GC nor thread context switches can occur between these two
+ times. *)
+
+let calling_conventions first_int last_int first_float last_float make_stack
+ arg =
+ let loc = Array.make (Array.length arg) Reg.dummy in
+ let int = ref first_int in
+ let float = ref first_float in
+ let ofs = ref (-64) in
+ for i = 0 to Array.length arg - 1 do
+ match arg.(i).typ with
+ Val | Int | Addr as ty ->
+ if !int <= last_int then begin
+ loc.(i) <- phys_reg !int;
+ incr int
+ end else begin
+ loc.(i) <- stack_slot (make_stack !ofs) ty;
+ ofs := !ofs + size_int
+ end
+ | Float ->
+ if !float <= last_float then begin
+ loc.(i) <- phys_reg !float;
+ incr float
+ end else begin
+ loc.(i) <- stack_slot (make_stack !ofs) Float;
+ ofs := !ofs + size_float
+ end
+ done;
+ (loc, Misc.align (max 0 !ofs) stack_alignment)
+
+let incoming ofs = Incoming ofs
+let outgoing ofs = Outgoing ofs
+let not_supported ofs = fatal_error "Proc.loc_results: cannot call"
+
+let loc_arguments arg =
+ calling_conventions 0 5 100 99 outgoing arg
+let loc_parameters arg =
+ let (loc, ofs) = calling_conventions 0 5 100 99 incoming arg in loc
+let loc_results res =
+ let (loc, ofs) = calling_conventions 0 5 100 100 not_supported res in loc
+let extcall_use_push = true
+let loc_external_arguments arg =
+ fatal_error "Proc.loc_external_arguments"
+let loc_external_results res =
+ match res with
+ | [|{typ=Int};{typ=Int}|] -> [|eax; edx|]
+ | _ ->
+ let (loc, ofs) = calling_conventions 0 0 100 100 not_supported res in loc
+
+let loc_exn_bucket = eax
+
+(* Volatile registers: the x87 top of FP stack is *)
+
+let reg_is_volatile = function
+ | { typ = Float; loc = Reg _ } -> true
+ | _ -> false
+
+let regs_are_volatile rs =
+ try
+ for i = 0 to Array.length rs - 1 do
+ if reg_is_volatile rs.(i) then raise Exit
+ done;
+ false
+ with Exit ->
+ true
+
+(* Registers destroyed by operations *)
+
+let destroyed_at_c_call = (* ebx, esi, edi, ebp preserved *)
+ [|eax; ecx; edx|]
+
+let destroyed_at_oper = function
+ Iop(Icall_ind | Icall_imm _ | Iextcall(_, true)) -> all_phys_regs
+ | Iop(Iextcall(_, false)) -> destroyed_at_c_call
+ | Iop(Iintop(Idiv | Imod)) -> [| eax; edx |]
+ | Iop(Ialloc _ | Iintop Imulh) -> [| eax |]
+ | Iop(Iintop(Icomp _) | Iintop_imm(Icomp _, _)) -> [| eax |]
+ | Iop(Iintoffloat) -> [| eax |]
+ | Iifthenelse(Ifloattest(_, _), _, _) -> [| eax |]
+ | _ -> [||]
+
+let destroyed_at_raise = all_phys_regs
+
+(* Maximal register pressure *)
+
+let safe_register_pressure op = 4
+
+let max_register_pressure = function
+ Iextcall(_, _) -> [| 4; max_int |]
+ | Iintop(Idiv | Imod) -> [| 5; max_int |]
+ | Ialloc _ | Iintop(Icomp _) | Iintop_imm(Icomp _, _) |
+ Iintoffloat -> [| 6; max_int |]
+ | _ -> [|7; max_int |]
+
+(* Pure operations (without any side effect besides updating their result
+ registers). *)
+
+let op_is_pure = function
+ | Icall_ind | Icall_imm _ | Itailcall_ind | Itailcall_imm _
+ | Iextcall _ | Istackoffset _ | Istore _ | Ialloc _
+ | Iintop(Icheckbound) | Iintop_imm(Icheckbound, _) -> false
+ | Ispecific(Ilea _) -> true
+ | Ispecific _ -> false
+ | _ -> true
+
+(* Layout of the stack frame *)
+
+let num_stack_slots = [| 0; 0 |]
+let contains_calls = ref false
+
+(* Calling the assembler *)
+
+let assemble_file infile outfile =
+ X86_proc.assemble_file infile outfile
+
+let init () = ()
diff --git a/asmcomp/i386/reload.ml b/asmcomp/i386/reload.ml
new file mode 100644
index 0000000000..bc1b08f597
--- /dev/null
+++ b/asmcomp/i386/reload.ml
@@ -0,0 +1,83 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Cmm
+open Arch
+open Reg
+open Mach
+
+(* Reloading for the Intel x86 *)
+
+let stackp r =
+ match r.loc with
+ Stack _ -> true
+ | _ -> false
+
+class reload = object (self)
+
+inherit Reloadgen.reload_generic as super
+
+method! makereg r =
+ match r.typ with
+ Float -> r
+ | _ -> super#makereg r
+
+(* By overriding makereg, we make sure that pseudoregs of type float
+ will never be reloaded. Hence there is no need to make special cases for
+ floating-point operations. *)
+
+method! reload_operation op arg res =
+ match op with
+ Iintop(Iadd|Isub|Iand|Ior|Ixor|Icomp _|Icheckbound) ->
+ (* One of the two arguments can reside in the stack *)
+ if stackp arg.(0) && stackp arg.(1)
+ then ([|arg.(0); self#makereg arg.(1)|], res)
+ else (arg, res)
+ | Iintop(Imul) ->
+ (* First argument (and destination) must be in register,
+ second arg can reside in stack *)
+ if stackp arg.(0)
+ then let r = self#makereg arg.(0) in ([|r; arg.(1)|], [|r|])
+ else (arg, res)
+ | Iintop_imm(Iadd, _) when arg.(0).loc <> res.(0).loc ->
+ (* This add will be turned into a lea; args and results must be
+ in registers *)
+ super#reload_operation op arg res
+ | Iintop_imm(Imul, _) ->
+ (* First argument and destination must be in register *)
+ if stackp arg.(0)
+ then let r = self#makereg arg.(0) in ([|r|], [|r|])
+ else (arg, res)
+ | Iintop(Imulh | Ilsl | Ilsr | Iasr) | Iintop_imm(_, _)
+ | Ifloatofint | Iintoffloat | Ispecific(Ipush) ->
+ (* The argument(s) can be either in register or on stack *)
+ (* Note: Imulh: arg(0 and res(0) already forced in regs
+ Ilsl, Ilsr, Iasr: arg(1) already forced in regs *)
+ (arg, res)
+ | _ -> (* Other operations: all args and results in registers *)
+ super#reload_operation op arg res
+
+method! reload_test tst arg =
+ match tst with
+ Iinttest cmp ->
+ (* One of the two arguments can reside on stack *)
+ if stackp arg.(0) && stackp arg.(1)
+ then [| self#makereg arg.(0); arg.(1) |]
+ else arg
+ | _ ->
+ (* The argument(s) can be either in register or on stack *)
+ arg
+
+end
+
+let fundecl f =
+ (new reload)#fundecl f
diff --git a/asmcomp/i386/scheduling.ml b/asmcomp/i386/scheduling.ml
new file mode 100644
index 0000000000..b166a05a34
--- /dev/null
+++ b/asmcomp/i386/scheduling.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () = let module M = Schedgen in () (* to create a dependency *)
+
+(* Scheduling is turned off because our model does not fit the 486
+ nor the Pentium very well. In particular, it messes up with the
+ float reg stack. The Pentiums Pro / II / III / etc schedule
+ at run-time much better than what we could do. *)
+
+let fundecl f = f
diff --git a/asmcomp/i386/selection.ml b/asmcomp/i386/selection.ml
new file mode 100644
index 0000000000..be76b2c61f
--- /dev/null
+++ b/asmcomp/i386/selection.ml
@@ -0,0 +1,315 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction selection for the Intel x86 *)
+
+open Misc
+open Arch
+open Proc
+open Cmm
+open Mach
+
+(* Auxiliary for recognizing addressing modes *)
+
+type addressing_expr =
+ Asymbol of string
+ | Alinear of expression
+ | Aadd of expression * expression
+ | Ascale of expression * int
+ | Ascaledadd of expression * expression * int
+
+let rec select_addr exp =
+ match exp with
+ Cconst_symbol s ->
+ (Asymbol s, 0)
+ | Cop((Caddi | Caddv | Cadda), [arg; Cconst_int m]) ->
+ let (a, n) = select_addr arg in (a, n + m)
+ | Cop(Csubi, [arg; Cconst_int m]) ->
+ let (a, n) = select_addr arg in (a, n - m)
+ | Cop((Caddi | Caddv | Cadda), [Cconst_int m; arg]) ->
+ let (a, n) = select_addr arg in (a, n + m)
+ | Cop(Clsl, [arg; Cconst_int(1|2|3 as shift)]) ->
+ begin match select_addr arg with
+ (Alinear e, n) -> (Ascale(e, 1 lsl shift), n lsl shift)
+ | _ -> (Alinear exp, 0)
+ end
+ | Cop(Cmuli, [arg; Cconst_int(2|4|8 as mult)]) ->
+ begin match select_addr arg with
+ (Alinear e, n) -> (Ascale(e, mult), n * mult)
+ | _ -> (Alinear exp, 0)
+ end
+ | Cop(Cmuli, [Cconst_int(2|4|8 as mult); arg]) ->
+ begin match select_addr arg with
+ (Alinear e, n) -> (Ascale(e, mult), n * mult)
+ | _ -> (Alinear exp, 0)
+ end
+ | Cop((Caddi | Cadda | Caddv), [arg1; arg2]) ->
+ begin match (select_addr arg1, select_addr arg2) with
+ ((Alinear e1, n1), (Alinear e2, n2)) ->
+ (Aadd(e1, e2), n1 + n2)
+ | ((Alinear e1, n1), (Ascale(e2, scale), n2)) ->
+ (Ascaledadd(e1, e2, scale), n1 + n2)
+ | ((Ascale(e1, scale), n1), (Alinear e2, n2)) ->
+ (Ascaledadd(e2, e1, scale), n1 + n2)
+ | (_, (Ascale(e2, scale), n2)) ->
+ (Ascaledadd(arg1, e2, scale), n2)
+ | ((Ascale(e1, scale), n1), _) ->
+ (Ascaledadd(arg2, e1, scale), n1)
+ | _ ->
+ (Aadd(arg1, arg2), 0)
+ end
+ | arg ->
+ (Alinear arg, 0)
+
+(* C functions to be turned into Ifloatspecial instructions if -ffast-math *)
+
+let inline_float_ops =
+ ["atan"; "atan2"; "cos"; "log"; "log10"; "sin"; "sqrt"; "tan"]
+
+(* Estimate number of float temporaries needed to evaluate expression
+ (Ershov's algorithm) *)
+
+let rec float_needs = function
+ Cop((Cnegf | Cabsf), [arg]) ->
+ float_needs arg
+ | Cop((Caddf | Csubf | Cmulf | Cdivf), [arg1; arg2]) ->
+ let n1 = float_needs arg1 in
+ let n2 = float_needs arg2 in
+ if n1 = n2 then 1 + n1 else if n1 > n2 then n1 else n2
+ | Cop(Cextcall(fn, ty_res, alloc, dbg), args)
+ when !fast_math && List.mem fn inline_float_ops ->
+ begin match args with
+ [arg] -> float_needs arg
+ | [arg1; arg2] -> max (float_needs arg2 + 1) (float_needs arg1)
+ | _ -> assert false
+ end
+ | _ ->
+ 1
+
+(* Special constraints on operand and result registers *)
+
+exception Use_default
+
+let eax = phys_reg 0
+let ecx = phys_reg 2
+let edx = phys_reg 3
+let tos = phys_reg 100
+
+let pseudoregs_for_operation op arg res =
+ match op with
+ (* Two-address binary operations *)
+ Iintop(Iadd|Isub|Imul|Iand|Ior|Ixor) ->
+ ([|res.(0); arg.(1)|], res, false)
+ (* Two-address unary operations *)
+ | Iintop_imm((Iadd|Isub|Imul|Iand|Ior|Ixor|Ilsl|Ilsr|Iasr), _) ->
+ (res, res, false)
+ (* For imull, first arg must be in eax, eax is clobbered, and result is in
+ edx. *)
+ | Iintop(Imulh) ->
+ ([| eax; arg.(1) |], [| edx |], true)
+ (* For shifts with variable shift count, second arg must be in ecx *)
+ | Iintop(Ilsl|Ilsr|Iasr) ->
+ ([|res.(0); ecx|], res, false)
+ (* For div and mod, first arg must be in eax, edx is clobbered,
+ and result is in eax or edx respectively.
+ Keep it simple, just force second argument in ecx. *)
+ | Iintop(Idiv) ->
+ ([| eax; ecx |], [| eax |], true)
+ | Iintop(Imod) ->
+ ([| eax; ecx |], [| edx |], true)
+ (* For floating-point operations and floating-point loads,
+ the result is always left at the top of the floating-point stack *)
+ | Iconst_float _ | Inegf | Iabsf | Iaddf | Isubf | Imulf | Idivf
+ | Ifloatofint | Iload((Single | Double | Double_u), _)
+ | Ispecific(Isubfrev | Idivfrev | Ifloatarithmem _ | Ifloatspecial _) ->
+ (arg, [| tos |], false) (* don't move it immediately *)
+ (* For storing a byte, the argument must be in eax...edx.
+ (But for a short, any reg will do!)
+ Keep it simple, just force the argument to be in edx. *)
+ | Istore((Byte_unsigned | Byte_signed), addr, _) ->
+ let newarg = Array.copy arg in
+ newarg.(0) <- edx;
+ (newarg, res, false)
+ (* Other instructions are regular *)
+ | _ -> raise Use_default
+
+let chunk_double = function
+ Single -> false
+ | Double -> true
+ | Double_u -> true
+ | _ -> assert false
+
+(* The selector class *)
+
+class selector = object (self)
+
+inherit Selectgen.selector_generic as super
+
+method is_immediate (n : int) = true
+
+method! is_simple_expr e =
+ match e with
+ | Cop(Cextcall(fn, _, alloc, _), args)
+ when !fast_math && List.mem fn inline_float_ops ->
+ (* inlined float ops are simple if their arguments are *)
+ List.for_all self#is_simple_expr args
+ | _ ->
+ super#is_simple_expr e
+
+method select_addressing chunk exp =
+ match select_addr exp with
+ (Asymbol s, d) ->
+ (Ibased(s, d), Ctuple [])
+ | (Alinear e, d) ->
+ (Iindexed d, e)
+ | (Aadd(e1, e2), d) ->
+ (Iindexed2 d, Ctuple[e1; e2])
+ | (Ascale(e, scale), d) ->
+ (Iscaled(scale, d), e)
+ | (Ascaledadd(e1, e2, scale), d) ->
+ (Iindexed2scaled(scale, d), Ctuple[e1; e2])
+
+method! select_store is_assign addr exp =
+ match exp with
+ Cconst_int n ->
+ (Ispecific(Istore_int(Nativeint.of_int n, addr, is_assign)), Ctuple [])
+ | (Cconst_natint n | Cconst_blockheader n) ->
+ (Ispecific(Istore_int(n, addr, is_assign)), Ctuple [])
+ | Cconst_pointer n ->
+ (Ispecific(Istore_int(Nativeint.of_int n, addr, is_assign)), Ctuple [])
+ | Cconst_natpointer n ->
+ (Ispecific(Istore_int(n, addr, is_assign)), Ctuple [])
+ | Cconst_symbol s ->
+ (Ispecific(Istore_symbol(s, addr, is_assign)), Ctuple [])
+ | _ ->
+ super#select_store is_assign addr exp
+
+method! select_operation op args =
+ match op with
+ (* Recognize the LEA instruction *)
+ Caddi | Caddv | Cadda | Csubi ->
+ begin match self#select_addressing Word_int (Cop(op, args)) with
+ (Iindexed d, _) -> super#select_operation op args
+ | (Iindexed2 0, _) -> super#select_operation op args
+ | (addr, arg) -> (Ispecific(Ilea addr), [arg])
+ end
+ (* Recognize float arithmetic with memory.
+ In passing, apply Ershov's algorithm to reduce stack usage *)
+ | Caddf ->
+ self#select_floatarith Iaddf Iaddf Ifloatadd Ifloatadd args
+ | Csubf ->
+ self#select_floatarith Isubf (Ispecific Isubfrev) Ifloatsub Ifloatsubrev
+ args
+ | Cmulf ->
+ self#select_floatarith Imulf Imulf Ifloatmul Ifloatmul args
+ | Cdivf ->
+ self#select_floatarith Idivf (Ispecific Idivfrev) Ifloatdiv Ifloatdivrev
+ args
+ (* Recognize store instructions *)
+ | Cstore (Word_int | Word_val as chunk) ->
+ begin match args with
+ [loc; Cop(Caddi, [Cop(Cload _, [loc']); Cconst_int n])]
+ when loc = loc' ->
+ let (addr, arg) = self#select_addressing chunk loc in
+ (Ispecific(Ioffset_loc(n, addr)), [arg])
+ | _ ->
+ super#select_operation op args
+ end
+ (* Recognize inlined floating point operations *)
+ | Cextcall(fn, ty_res, false, dbg)
+ when !fast_math && List.mem fn inline_float_ops ->
+ (Ispecific(Ifloatspecial fn), args)
+ (* i386 does not support immediate operands for multiply high signed *)
+ | Cmulhi ->
+ (Iintop Imulh, args)
+ (* Default *)
+ | _ -> super#select_operation op args
+
+(* Recognize float arithmetic with mem *)
+
+method select_floatarith regular_op reversed_op mem_op mem_rev_op args =
+ match args with
+ [arg1; Cop(Cload chunk, [loc2])] ->
+ let (addr, arg2) = self#select_addressing chunk loc2 in
+ (Ispecific(Ifloatarithmem(chunk_double chunk, mem_op, addr)),
+ [arg1; arg2])
+ | [Cop(Cload chunk, [loc1]); arg2] ->
+ let (addr, arg1) = self#select_addressing chunk loc1 in
+ (Ispecific(Ifloatarithmem(chunk_double chunk, mem_rev_op, addr)),
+ [arg2; arg1])
+ | [arg1; arg2] ->
+ (* Evaluate bigger subexpression first to minimize stack usage.
+ Because of right-to-left evaluation, rightmost arg is evaluated
+ first *)
+ if float_needs arg1 <= float_needs arg2
+ then (regular_op, [arg1; arg2])
+ else (reversed_op, [arg2; arg1])
+ | _ ->
+ fatal_error "Proc_i386: select_floatarith"
+
+(* Deal with register constraints *)
+
+method! insert_op_debug op dbg rs rd =
+ try
+ let (rsrc, rdst, move_res) = pseudoregs_for_operation op rs rd in
+ self#insert_moves rs rsrc;
+ self#insert_debug (Iop op) dbg rsrc rdst;
+ if move_res then begin
+ self#insert_moves rdst rd;
+ rd
+ end else
+ rdst
+ with Use_default ->
+ super#insert_op_debug op dbg rs rd
+
+(* Selection of push instructions for external calls *)
+
+method select_push exp =
+ match exp with
+ Cconst_int n -> (Ispecific(Ipush_int(Nativeint.of_int n)), Ctuple [])
+ | Cconst_natint n -> (Ispecific(Ipush_int n), Ctuple [])
+ | Cconst_pointer n -> (Ispecific(Ipush_int(Nativeint.of_int n)), Ctuple [])
+ | Cconst_natpointer n -> (Ispecific(Ipush_int n), Ctuple [])
+ | Cconst_symbol s -> (Ispecific(Ipush_symbol s), Ctuple [])
+ | Cop(Cload (Word_int | Word_val as chunk), [loc]) ->
+ let (addr, arg) = self#select_addressing chunk loc in
+ (Ispecific(Ipush_load addr), arg)
+ | Cop(Cload Double_u, [loc]) ->
+ let (addr, arg) = self#select_addressing Double_u loc in
+ (Ispecific(Ipush_load_float addr), arg)
+ | _ -> (Ispecific(Ipush), exp)
+
+method! mark_c_tailcall =
+ Proc.contains_calls := true
+
+method! emit_extcall_args env args =
+ let rec size_pushes = function
+ | [] -> 0
+ | e :: el -> Selectgen.size_expr env e + size_pushes el in
+ let sz1 = size_pushes args in
+ let sz2 = Misc.align sz1 stack_alignment in
+ let rec emit_pushes = function
+ | [] ->
+ if sz2 > sz1 then
+ self#insert (Iop (Istackoffset (sz2 - sz1))) [||] [||]
+ | e :: el ->
+ emit_pushes el;
+ let (op, arg) = self#select_push e in
+ match self#emit_expr env arg with
+ | None -> ()
+ | Some r -> self#insert (Iop op) r [||] in
+ emit_pushes args;
+ ([||], sz2)
+
+end
+
+let fundecl f = (new selector)#emit_fundecl f
diff --git a/asmcomp/interf.ml b/asmcomp/interf.ml
new file mode 100644
index 0000000000..2d541eeee5
--- /dev/null
+++ b/asmcomp/interf.ml
@@ -0,0 +1,188 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Construction of the interference graph.
+ Annotate pseudoregs with interference lists and preference lists. *)
+
+module IntPairSet =
+ Set.Make(struct
+ type t = int * int
+ let compare ((a1,b1) : t) (a2,b2) =
+ match compare a1 a2 with
+ | 0 -> compare b1 b2
+ | c -> c
+ end)
+
+open Reg
+open Mach
+
+let build_graph fundecl =
+
+ (* The interference graph is represented in two ways:
+ - by adjacency lists for each register
+ - by a sparse bit matrix (a set of pairs of register stamps) *)
+
+ let mat = ref IntPairSet.empty in
+
+ (* Record an interference between two registers *)
+ let add_interf ri rj =
+ if Proc.register_class ri = Proc.register_class rj then begin
+ let i = ri.stamp and j = rj.stamp in
+ if i <> j then begin
+ let p = if i < j then (i, j) else (j, i) in
+ if not(IntPairSet.mem p !mat) then begin
+ mat := IntPairSet.add p !mat;
+ if ri.loc = Unknown then begin
+ ri.interf <- rj :: ri.interf;
+ if not rj.spill then ri.degree <- ri.degree + 1
+ end;
+ if rj.loc = Unknown then begin
+ rj.interf <- ri :: rj.interf;
+ if not ri.spill then rj.degree <- rj.degree + 1
+ end
+ end
+ end
+ end in
+
+ (* Record interferences between a register array and a set of registers *)
+ let add_interf_set v s =
+ for i = 0 to Array.length v - 1 do
+ let r1 = v.(i) in
+ Reg.Set.iter (add_interf r1) s
+ done in
+
+ (* Record interferences between elements of an array *)
+ let add_interf_self v =
+ for i = 0 to Array.length v - 2 do
+ let ri = v.(i) in
+ for j = i+1 to Array.length v - 1 do
+ add_interf ri v.(j)
+ done
+ done in
+
+ (* Record interferences between the destination of a move and a set
+ of live registers. Since the destination is equal to the source,
+ do not add an interference between them if the source is still live
+ afterwards. *)
+ let add_interf_move src dst s =
+ Reg.Set.iter (fun r -> if r.stamp <> src.stamp then add_interf dst r) s in
+
+ (* Compute interferences *)
+
+ let rec interf i =
+ let destroyed = Proc.destroyed_at_oper i.desc in
+ if Array.length destroyed > 0 then add_interf_set destroyed i.live;
+ match i.desc with
+ Iend -> ()
+ | Ireturn -> ()
+ | Iop(Imove | Ispill | Ireload) ->
+ add_interf_move i.arg.(0) i.res.(0) i.live;
+ interf i.next
+ | Iop(Itailcall_ind) -> ()
+ | Iop(Itailcall_imm lbl) -> ()
+ | Iop op ->
+ add_interf_set i.res i.live;
+ add_interf_self i.res;
+ interf i.next
+ | Iifthenelse(tst, ifso, ifnot) ->
+ interf ifso;
+ interf ifnot;
+ interf i.next
+ | Iswitch(index, cases) ->
+ for i = 0 to Array.length cases - 1 do
+ interf cases.(i)
+ done;
+ interf i.next
+ | Iloop body ->
+ interf body; interf i.next
+ | Icatch(_, body, handler) ->
+ interf body; interf handler; interf i.next
+ | Iexit _ ->
+ ()
+ | Itrywith(body, handler) ->
+ add_interf_set Proc.destroyed_at_raise handler.live;
+ interf body; interf handler; interf i.next
+ | Iraise _ -> () in
+
+ (* Add a preference from one reg to another.
+ Do not add anything if the two registers conflict,
+ or if the source register already has a location,
+ or if the two registers belong to different classes.
+ (The last case can occur e.g. on Sparc when passing
+ float arguments in integer registers, PR#6227.) *)
+
+ let add_pref weight r1 r2 =
+ if weight > 0 then begin
+ let i = r1.stamp and j = r2.stamp in
+ if i <> j
+ && r1.loc = Unknown
+ && Proc.register_class r1 = Proc.register_class r2
+ && (let p = if i < j then (i, j) else (j, i) in
+ not (IntPairSet.mem p !mat))
+ then r1.prefer <- (r2, weight) :: r1.prefer
+ end in
+
+ (* Add a mutual preference between two regs *)
+ let add_mutual_pref weight r1 r2 =
+ add_pref weight r1 r2; add_pref weight r2 r1 in
+
+ (* Update the spill cost of the registers involved in an operation *)
+
+ let add_spill_cost cost arg =
+ for i = 0 to Array.length arg - 1 do
+ let r = arg.(i) in r.spill_cost <- r.spill_cost + cost
+ done in
+
+ (* Compute preferences and spill costs *)
+
+ let rec prefer weight i =
+ add_spill_cost weight i.arg;
+ add_spill_cost weight i.res;
+ match i.desc with
+ Iend -> ()
+ | Ireturn -> ()
+ | Iop(Imove) ->
+ add_mutual_pref weight i.arg.(0) i.res.(0);
+ prefer weight i.next
+ | Iop(Ispill) ->
+ add_pref (weight / 4) i.arg.(0) i.res.(0);
+ prefer weight i.next
+ | Iop(Ireload) ->
+ add_pref (weight / 4) i.res.(0) i.arg.(0);
+ prefer weight i.next
+ | Iop(Itailcall_ind) -> ()
+ | Iop(Itailcall_imm lbl) -> ()
+ | Iop op ->
+ prefer weight i.next
+ | Iifthenelse(tst, ifso, ifnot) ->
+ prefer (weight / 2) ifso;
+ prefer (weight / 2) ifnot;
+ prefer weight i.next
+ | Iswitch(index, cases) ->
+ for i = 0 to Array.length cases - 1 do
+ prefer (weight / 2) cases.(i)
+ done;
+ prefer weight i.next
+ | Iloop body ->
+ (* Avoid overflow of weight and spill_cost *)
+ prefer (if weight < 1000 then 8 * weight else weight) body;
+ prefer weight i.next
+ | Icatch(_, body, handler) ->
+ prefer weight body; prefer weight handler; prefer weight i.next
+ | Iexit _ ->
+ ()
+ | Itrywith(body, handler) ->
+ prefer weight body; prefer weight handler; prefer weight i.next
+ | Iraise _ -> ()
+ in
+
+ interf fundecl.fun_body; prefer 8 fundecl.fun_body
diff --git a/asmcomp/interf.mli b/asmcomp/interf.mli
new file mode 100644
index 0000000000..a9b0b63090
--- /dev/null
+++ b/asmcomp/interf.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Construction of the interference graph.
+ Annotate pseudoregs with interference lists and preference lists. *)
+
+val build_graph: Mach.fundecl -> unit
diff --git a/asmcomp/linearize.ml b/asmcomp/linearize.ml
new file mode 100644
index 0000000000..64678c1d4d
--- /dev/null
+++ b/asmcomp/linearize.ml
@@ -0,0 +1,297 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Transformation of Mach code into a list of pseudo-instructions. *)
+
+open Reg
+open Mach
+
+type label = int
+
+let label_counter = ref 99
+
+let new_label() = incr label_counter; !label_counter
+
+type instruction =
+ { mutable desc: instruction_desc;
+ mutable next: instruction;
+ arg: Reg.t array;
+ res: Reg.t array;
+ dbg: Debuginfo.t;
+ live: Reg.Set.t }
+
+and instruction_desc =
+ Lend
+ | Lop of operation
+ | Lreloadretaddr
+ | Lreturn
+ | Llabel of label
+ | Lbranch of label
+ | Lcondbranch of test * label
+ | Lcondbranch3 of label option * label option * label option
+ | Lswitch of label array
+ | Lsetuptrap of label
+ | Lpushtrap
+ | Lpoptrap
+ | Lraise of Lambda.raise_kind
+
+let has_fallthrough = function
+ | Lreturn | Lbranch _ | Lswitch _ | Lraise _
+ | Lop Itailcall_ind | Lop (Itailcall_imm _) -> false
+ | _ -> true
+
+type fundecl =
+ { fun_name: string;
+ fun_body: instruction;
+ fun_fast: bool;
+ fun_dbg : Debuginfo.t }
+
+(* Invert a test *)
+
+let invert_integer_test = function
+ Isigned cmp -> Isigned(Cmm.negate_comparison cmp)
+ | Iunsigned cmp -> Iunsigned(Cmm.negate_comparison cmp)
+
+let invert_test = function
+ Itruetest -> Ifalsetest
+ | Ifalsetest -> Itruetest
+ | Iinttest(cmp) -> Iinttest(invert_integer_test cmp)
+ | Iinttest_imm(cmp, n) -> Iinttest_imm(invert_integer_test cmp, n)
+ | Ifloattest(cmp, neg) -> Ifloattest(cmp, not neg)
+ | Ieventest -> Ioddtest
+ | Ioddtest -> Ieventest
+
+(* The "end" instruction *)
+
+let rec end_instr =
+ { desc = Lend;
+ next = end_instr;
+ arg = [||];
+ res = [||];
+ dbg = Debuginfo.none;
+ live = Reg.Set.empty }
+
+(* Cons an instruction (live, debug empty) *)
+
+let instr_cons d a r n =
+ { desc = d; next = n; arg = a; res = r;
+ dbg = Debuginfo.none; live = Reg.Set.empty }
+
+(* Cons a simple instruction (arg, res, live empty) *)
+
+let cons_instr d n =
+ { desc = d; next = n; arg = [||]; res = [||];
+ dbg = Debuginfo.none; live = Reg.Set.empty }
+
+(* Build an instruction with arg, res, dbg, live taken from
+ the given Mach.instruction *)
+
+let copy_instr d i n =
+ { desc = d; next = n;
+ arg = i.Mach.arg; res = i.Mach.res;
+ dbg = i.Mach.dbg; live = i.Mach.live }
+
+(*
+ Label the beginning of the given instruction sequence.
+ - If the sequence starts with a branch, jump over it.
+ - If the sequence is the end, (tail call position), just do nothing
+*)
+
+let get_label n = match n.desc with
+ Lbranch lbl -> (lbl, n)
+ | Llabel lbl -> (lbl, n)
+ | Lend -> (-1, n)
+ | _ -> let lbl = new_label() in (lbl, cons_instr (Llabel lbl) n)
+
+(* Check the fallthrough label *)
+let check_label n = match n.desc with
+ | Lbranch lbl -> lbl
+ | Llabel lbl -> lbl
+ | _ -> -1
+
+(* Discard all instructions up to the next label.
+ This function is to be called before adding a non-terminating
+ instruction. *)
+
+let rec discard_dead_code n =
+ match n.desc with
+ Lend -> n
+ | Llabel _ -> n
+(* Do not discard Lpoptrap/Lpushtrap or Istackoffset instructions,
+ as this may cause a stack imbalance later during assembler generation. *)
+ | Lpoptrap | Lpushtrap -> n
+ | Lop(Istackoffset _) -> n
+ | _ -> discard_dead_code n.next
+
+(*
+ Add a branch in front of a continuation.
+ Discard dead code in the continuation.
+ Does not insert anything if we're just falling through
+ or if we jump to dead code after the end of function (lbl=-1)
+*)
+
+let add_branch lbl n =
+ if lbl >= 0 then
+ let n1 = discard_dead_code n in
+ match n1.desc with
+ | Llabel lbl1 when lbl1 = lbl -> n1
+ | _ -> cons_instr (Lbranch lbl) n1
+ else
+ discard_dead_code n
+
+let try_depth = ref 0
+
+(* Association list: exit handler -> (handler label, try-nesting factor) *)
+
+let exit_label = ref []
+
+let find_exit_label_try_depth k =
+ try
+ List.assoc k !exit_label
+ with
+ | Not_found -> Misc.fatal_error "Linearize.find_exit_label"
+
+let find_exit_label k =
+ let (label, t) = find_exit_label_try_depth k in
+ assert(t = !try_depth);
+ label
+
+let is_next_catch n = match !exit_label with
+| (n0,(_,t))::_ when n0=n && t = !try_depth -> true
+| _ -> false
+
+let local_exit k =
+ snd (find_exit_label_try_depth k) = !try_depth
+
+(* Linearize an instruction [i]: add it in front of the continuation [n] *)
+
+let rec linear i n =
+ match i.Mach.desc with
+ Iend -> n
+ | Iop(Itailcall_ind | Itailcall_imm _ as op) ->
+ copy_instr (Lop op) i (discard_dead_code n)
+ | Iop(Imove | Ireload | Ispill)
+ when i.Mach.arg.(0).loc = i.Mach.res.(0).loc ->
+ linear i.Mach.next n
+ | Iop op ->
+ copy_instr (Lop op) i (linear i.Mach.next n)
+ | Ireturn ->
+ let n1 = copy_instr Lreturn i (discard_dead_code n) in
+ if !Proc.contains_calls
+ then cons_instr Lreloadretaddr n1
+ else n1
+ | Iifthenelse(test, ifso, ifnot) ->
+ let n1 = linear i.Mach.next n in
+ begin match (ifso.Mach.desc, ifnot.Mach.desc, n1.desc) with
+ Iend, _, Lbranch lbl ->
+ copy_instr (Lcondbranch(test, lbl)) i (linear ifnot n1)
+ | _, Iend, Lbranch lbl ->
+ copy_instr (Lcondbranch(invert_test test, lbl)) i (linear ifso n1)
+ | Iexit nfail1, Iexit nfail2, _
+ when is_next_catch nfail1 && local_exit nfail2 ->
+ let lbl2 = find_exit_label nfail2 in
+ copy_instr
+ (Lcondbranch (invert_test test, lbl2)) i (linear ifso n1)
+ | Iexit nfail, _, _ when local_exit nfail ->
+ let n2 = linear ifnot n1
+ and lbl = find_exit_label nfail in
+ copy_instr (Lcondbranch(test, lbl)) i n2
+ | _, Iexit nfail, _ when local_exit nfail ->
+ let n2 = linear ifso n1 in
+ let lbl = find_exit_label nfail in
+ copy_instr (Lcondbranch(invert_test test, lbl)) i n2
+ | Iend, _, _ ->
+ let (lbl_end, n2) = get_label n1 in
+ copy_instr (Lcondbranch(test, lbl_end)) i (linear ifnot n2)
+ | _, Iend, _ ->
+ let (lbl_end, n2) = get_label n1 in
+ copy_instr (Lcondbranch(invert_test test, lbl_end)) i
+ (linear ifso n2)
+ | _, _, _ ->
+ (* Should attempt branch prediction here *)
+ let (lbl_end, n2) = get_label n1 in
+ let (lbl_else, nelse) = get_label (linear ifnot n2) in
+ copy_instr (Lcondbranch(invert_test test, lbl_else)) i
+ (linear ifso (add_branch lbl_end nelse))
+ end
+ | Iswitch(index, cases) ->
+ let lbl_cases = Array.make (Array.length cases) 0 in
+ let (lbl_end, n1) = get_label(linear i.Mach.next n) in
+ let n2 = ref (discard_dead_code n1) in
+ for i = Array.length cases - 1 downto 0 do
+ let (lbl_case, ncase) =
+ get_label(linear cases.(i) (add_branch lbl_end !n2)) in
+ lbl_cases.(i) <- lbl_case;
+ n2 := discard_dead_code ncase
+ done;
+ (* Switches with 1 and 2 branches have been eliminated earlier.
+ Here, we do something for switches with 3 branches. *)
+ if Array.length index = 3 then begin
+ let fallthrough_lbl = check_label !n2 in
+ let find_label n =
+ let lbl = lbl_cases.(index.(n)) in
+ if lbl = fallthrough_lbl then None else Some lbl in
+ copy_instr (Lcondbranch3(find_label 0, find_label 1, find_label 2))
+ i !n2
+ end else
+ copy_instr (Lswitch(Array.map (fun n -> lbl_cases.(n)) index)) i !n2
+ | Iloop body ->
+ let lbl_head = new_label() in
+ let n1 = linear i.Mach.next n in
+ let n2 = linear body (cons_instr (Lbranch lbl_head) n1) in
+ cons_instr (Llabel lbl_head) n2
+ | Icatch(io, body, handler) ->
+ let (lbl_end, n1) = get_label(linear i.Mach.next n) in
+ let (lbl_handler, n2) = get_label(linear handler n1) in
+ exit_label := (io, (lbl_handler, !try_depth)) :: !exit_label ;
+ let n3 = linear body (add_branch lbl_end n2) in
+ exit_label := List.tl !exit_label;
+ n3
+ | Iexit nfail ->
+ let lbl, t = find_exit_label_try_depth nfail in
+ (* We need to re-insert dummy pushtrap (which won't be executed),
+ so as to preserve stack offset during assembler generation.
+ It would make sense to have a special pseudo-instruction
+ only to inform the later pass about this stack offset
+ (corresponding to N traps).
+ *)
+ let rec loop i tt =
+ if t = tt then i
+ else loop (cons_instr Lpushtrap i) (tt - 1)
+ in
+ let n1 = loop (linear i.Mach.next n) !try_depth in
+ let rec loop i tt =
+ if t = tt then i
+ else loop (cons_instr Lpoptrap i) (tt - 1)
+ in
+ loop (add_branch lbl n1) !try_depth
+ | Itrywith(body, handler) ->
+ let (lbl_join, n1) = get_label (linear i.Mach.next n) in
+ incr try_depth;
+ let (lbl_body, n2) =
+ get_label (cons_instr Lpushtrap
+ (linear body (cons_instr Lpoptrap n1))) in
+ decr try_depth;
+ cons_instr (Lsetuptrap lbl_body)
+ (linear handler (add_branch lbl_join n2))
+ | Iraise k ->
+ copy_instr (Lraise k) i (discard_dead_code n)
+
+let reset () =
+ label_counter := 99;
+ exit_label := []
+
+let fundecl f =
+ { fun_name = f.Mach.fun_name;
+ fun_body = linear f.Mach.fun_body end_instr;
+ fun_fast = f.Mach.fun_fast;
+ fun_dbg = f.Mach.fun_dbg }
diff --git a/asmcomp/linearize.mli b/asmcomp/linearize.mli
new file mode 100644
index 0000000000..2996a29bf2
--- /dev/null
+++ b/asmcomp/linearize.mli
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Transformation of Mach code into a list of pseudo-instructions. *)
+
+type label = int
+val new_label: unit -> label
+
+type instruction =
+ { mutable desc: instruction_desc;
+ mutable next: instruction;
+ arg: Reg.t array;
+ res: Reg.t array;
+ dbg: Debuginfo.t;
+ live: Reg.Set.t }
+
+and instruction_desc =
+ Lend
+ | Lop of Mach.operation
+ | Lreloadretaddr
+ | Lreturn
+ | Llabel of label
+ | Lbranch of label
+ | Lcondbranch of Mach.test * label
+ | Lcondbranch3 of label option * label option * label option
+ | Lswitch of label array
+ | Lsetuptrap of label
+ | Lpushtrap
+ | Lpoptrap
+ | Lraise of Lambda.raise_kind
+
+val has_fallthrough : instruction_desc -> bool
+val end_instr: instruction
+val instr_cons:
+ instruction_desc -> Reg.t array -> Reg.t array -> instruction -> instruction
+val invert_test: Mach.test -> Mach.test
+
+type fundecl =
+ { fun_name: string;
+ fun_body: instruction;
+ fun_fast: bool;
+ fun_dbg : Debuginfo.t }
+
+val reset : unit -> unit
+val fundecl: Mach.fundecl -> fundecl
diff --git a/asmcomp/liveness.ml b/asmcomp/liveness.ml
new file mode 100644
index 0000000000..2ef322ef3e
--- /dev/null
+++ b/asmcomp/liveness.ml
@@ -0,0 +1,133 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Liveness analysis.
+ Annotate mach code with the set of regs live at each point. *)
+
+open Mach
+
+let live_at_exit = ref []
+
+let find_live_at_exit k =
+ try
+ List.assoc k !live_at_exit
+ with
+ | Not_found -> Misc.fatal_error "Liveness.find_live_at_exit"
+
+let live_at_raise = ref Reg.Set.empty
+
+let rec live i finally =
+ (* finally is the set of registers live after execution of the
+ instruction sequence.
+ The result of the function is the set of registers live just
+ before the instruction sequence.
+ The instruction i is annotated by the set of registers live across
+ the instruction. *)
+ match i.desc with
+ Iend ->
+ i.live <- finally;
+ finally
+ | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) ->
+ i.live <- Reg.Set.empty; (* no regs are live across *)
+ Reg.set_of_array i.arg
+ | Iop op ->
+ let after = live i.next finally in
+ if Proc.op_is_pure op (* no side effects *)
+ && Reg.disjoint_set_array after i.res (* results are not used after *)
+ && not (Proc.regs_are_volatile i.arg) (* no stack-like hard reg *)
+ && not (Proc.regs_are_volatile i.res) (* is involved *)
+ then begin
+ (* This operation is dead code. Ignore its arguments. *)
+ i.live <- after;
+ after
+ end else begin
+ let across_after = Reg.diff_set_array after i.res in
+ let across =
+ match op with
+ | Icall_ind | Icall_imm _ | Iextcall _
+ | Iintop Icheckbound | Iintop_imm(Icheckbound, _) ->
+ (* The function call may raise an exception, branching to the
+ nearest enclosing try ... with. Similarly for bounds checks.
+ Hence, everything that must be live at the beginning of
+ the exception handler must also be live across this instr. *)
+ Reg.Set.union across_after !live_at_raise
+ | _ ->
+ across_after in
+ i.live <- across;
+ Reg.add_set_array across i.arg
+ end
+ | Iifthenelse(test, ifso, ifnot) ->
+ let at_join = live i.next finally in
+ let at_fork = Reg.Set.union (live ifso at_join) (live ifnot at_join) in
+ i.live <- at_fork;
+ Reg.add_set_array at_fork i.arg
+ | Iswitch(index, cases) ->
+ let at_join = live i.next finally in
+ let at_fork = ref Reg.Set.empty in
+ for i = 0 to Array.length cases - 1 do
+ at_fork := Reg.Set.union !at_fork (live cases.(i) at_join)
+ done;
+ i.live <- !at_fork;
+ Reg.add_set_array !at_fork i.arg
+ | Iloop(body) ->
+ let at_top = ref Reg.Set.empty in
+ (* Yes, there are better algorithms, but we'll just iterate till
+ reaching a fixpoint. *)
+ begin try
+ while true do
+ let new_at_top = Reg.Set.union !at_top (live body !at_top) in
+ if Reg.Set.equal !at_top new_at_top then raise Exit;
+ at_top := new_at_top
+ done
+ with Exit -> ()
+ end;
+ i.live <- !at_top;
+ !at_top
+ | Icatch(nfail, body, handler) ->
+ let at_join = live i.next finally in
+ let before_handler = live handler at_join in
+ let before_body =
+ live_at_exit := (nfail,before_handler) :: !live_at_exit ;
+ let before_body = live body at_join in
+ live_at_exit := List.tl !live_at_exit ;
+ before_body in
+ i.live <- before_body;
+ before_body
+ | Iexit nfail ->
+ let this_live = find_live_at_exit nfail in
+ i.live <- this_live ;
+ this_live
+ | Itrywith(body, handler) ->
+ let at_join = live i.next finally in
+ let before_handler = live handler at_join in
+ let saved_live_at_raise = !live_at_raise in
+ live_at_raise := Reg.Set.remove Proc.loc_exn_bucket before_handler;
+ let before_body = live body at_join in
+ live_at_raise := saved_live_at_raise;
+ i.live <- before_body;
+ before_body
+ | Iraise _ ->
+ i.live <- !live_at_raise;
+ Reg.add_set_array !live_at_raise i.arg
+
+let reset () =
+ live_at_raise := Reg.Set.empty;
+ live_at_exit := []
+
+let fundecl ppf f =
+ let initially_live = live f.fun_body Reg.Set.empty in
+ (* Sanity check: only function parameters can be live at entrypoint *)
+ let wrong_live = Reg.Set.diff initially_live (Reg.set_of_array f.fun_args) in
+ if not (Reg.Set.is_empty wrong_live) then begin
+ Format.fprintf ppf "%a@." Printmach.regset wrong_live;
+ Misc.fatal_error "Liveness.fundecl"
+ end
diff --git a/asmcomp/liveness.mli b/asmcomp/liveness.mli
new file mode 100644
index 0000000000..ed2f1a8aeb
--- /dev/null
+++ b/asmcomp/liveness.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Liveness analysis.
+ Annotate mach code with the set of regs live at each point. *)
+
+open Format
+
+val reset : unit -> unit
+val fundecl: formatter -> Mach.fundecl -> unit
diff --git a/asmcomp/mach.ml b/asmcomp/mach.ml
new file mode 100644
index 0000000000..3a7174763a
--- /dev/null
+++ b/asmcomp/mach.ml
@@ -0,0 +1,131 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Representation of machine code by sequences of pseudoinstructions *)
+
+type integer_comparison =
+ Isigned of Cmm.comparison
+ | Iunsigned of Cmm.comparison
+
+type integer_operation =
+ Iadd | Isub | Imul | Imulh | Idiv | Imod
+ | Iand | Ior | Ixor | Ilsl | Ilsr | Iasr
+ | Icomp of integer_comparison
+ | Icheckbound
+
+type test =
+ Itruetest
+ | Ifalsetest
+ | Iinttest of integer_comparison
+ | Iinttest_imm of integer_comparison * int
+ | Ifloattest of Cmm.comparison * bool
+ | Ioddtest
+ | Ieventest
+
+type operation =
+ Imove
+ | Ispill
+ | Ireload
+ | Iconst_int of nativeint
+ | Iconst_float of float
+ | Iconst_symbol of string
+ | Iconst_blockheader of nativeint
+ | Icall_ind
+ | Icall_imm of string
+ | Itailcall_ind
+ | Itailcall_imm of string
+ | Iextcall of string * bool
+ | Istackoffset of int
+ | Iload of Cmm.memory_chunk * Arch.addressing_mode
+ | Istore of Cmm.memory_chunk * Arch.addressing_mode * bool
+ | Ialloc of int
+ | Iintop of integer_operation
+ | Iintop_imm of integer_operation * int
+ | Inegf | Iabsf | Iaddf | Isubf | Imulf | Idivf
+ | Ifloatofint | Iintoffloat
+ | Ispecific of Arch.specific_operation
+
+type instruction =
+ { desc: instruction_desc;
+ next: instruction;
+ arg: Reg.t array;
+ res: Reg.t array;
+ dbg: Debuginfo.t;
+ mutable live: Reg.Set.t }
+
+and instruction_desc =
+ Iend
+ | Iop of operation
+ | Ireturn
+ | Iifthenelse of test * instruction * instruction
+ | Iswitch of int array * instruction array
+ | Iloop of instruction
+ | Icatch of int * instruction * instruction
+ | Iexit of int
+ | Itrywith of instruction * instruction
+ | Iraise of Lambda.raise_kind
+
+type fundecl =
+ { fun_name: string;
+ fun_args: Reg.t array;
+ fun_body: instruction;
+ fun_fast: bool;
+ fun_dbg : Debuginfo.t }
+
+let rec dummy_instr =
+ { desc = Iend;
+ next = dummy_instr;
+ arg = [||];
+ res = [||];
+ dbg = Debuginfo.none;
+ live = Reg.Set.empty }
+
+let end_instr () =
+ { desc = Iend;
+ next = dummy_instr;
+ arg = [||];
+ res = [||];
+ dbg = Debuginfo.none;
+ live = Reg.Set.empty }
+
+let instr_cons d a r n =
+ { desc = d; next = n; arg = a; res = r;
+ dbg = Debuginfo.none; live = Reg.Set.empty }
+
+let instr_cons_debug d a r dbg n =
+ { desc = d; next = n; arg = a; res = r; dbg = dbg; live = Reg.Set.empty }
+
+let rec instr_iter f i =
+ match i.desc with
+ Iend -> ()
+ | _ ->
+ f i;
+ match i.desc with
+ Iend -> ()
+ | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) -> ()
+ | Iifthenelse(tst, ifso, ifnot) ->
+ instr_iter f ifso; instr_iter f ifnot; instr_iter f i.next
+ | Iswitch(index, cases) ->
+ for i = 0 to Array.length cases - 1 do
+ instr_iter f cases.(i)
+ done;
+ instr_iter f i.next
+ | Iloop(body) ->
+ instr_iter f body; instr_iter f i.next
+ | Icatch(_, body, handler) ->
+ instr_iter f body; instr_iter f handler; instr_iter f i.next
+ | Iexit _ -> ()
+ | Itrywith(body, handler) ->
+ instr_iter f body; instr_iter f handler; instr_iter f i.next
+ | Iraise _ -> ()
+ | _ ->
+ instr_iter f i.next
diff --git a/asmcomp/mach.mli b/asmcomp/mach.mli
new file mode 100644
index 0000000000..618e5e4ce7
--- /dev/null
+++ b/asmcomp/mach.mli
@@ -0,0 +1,93 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Representation of machine code by sequences of pseudoinstructions *)
+
+type integer_comparison =
+ Isigned of Cmm.comparison
+ | Iunsigned of Cmm.comparison
+
+type integer_operation =
+ Iadd | Isub | Imul | Imulh | Idiv | Imod
+ | Iand | Ior | Ixor | Ilsl | Ilsr | Iasr
+ | Icomp of integer_comparison
+ | Icheckbound
+
+type test =
+ Itruetest
+ | Ifalsetest
+ | Iinttest of integer_comparison
+ | Iinttest_imm of integer_comparison * int
+ | Ifloattest of Cmm.comparison * bool
+ | Ioddtest
+ | Ieventest
+
+type operation =
+ Imove
+ | Ispill
+ | Ireload
+ | Iconst_int of nativeint
+ | Iconst_float of float
+ | Iconst_symbol of string
+ | Iconst_blockheader of nativeint
+ | Icall_ind
+ | Icall_imm of string
+ | Itailcall_ind
+ | Itailcall_imm of string
+ | Iextcall of string * bool (* false = noalloc, true = alloc *)
+ | Istackoffset of int
+ | Iload of Cmm.memory_chunk * Arch.addressing_mode
+ | Istore of Cmm.memory_chunk * Arch.addressing_mode * bool
+ (* false = initialization, true = assignment *)
+ | Ialloc of int
+ | Iintop of integer_operation
+ | Iintop_imm of integer_operation * int
+ | Inegf | Iabsf | Iaddf | Isubf | Imulf | Idivf
+ | Ifloatofint | Iintoffloat
+ | Ispecific of Arch.specific_operation
+
+type instruction =
+ { desc: instruction_desc;
+ next: instruction;
+ arg: Reg.t array;
+ res: Reg.t array;
+ dbg: Debuginfo.t;
+ mutable live: Reg.Set.t }
+
+and instruction_desc =
+ Iend
+ | Iop of operation
+ | Ireturn
+ | Iifthenelse of test * instruction * instruction
+ | Iswitch of int array * instruction array
+ | Iloop of instruction
+ | Icatch of int * instruction * instruction
+ | Iexit of int
+ | Itrywith of instruction * instruction
+ | Iraise of Lambda.raise_kind
+
+type fundecl =
+ { fun_name: string;
+ fun_args: Reg.t array;
+ fun_body: instruction;
+ fun_fast: bool;
+ fun_dbg : Debuginfo.t }
+
+val dummy_instr: instruction
+val end_instr: unit -> instruction
+val instr_cons:
+ instruction_desc -> Reg.t array -> Reg.t array -> instruction ->
+ instruction
+val instr_cons_debug:
+ instruction_desc -> Reg.t array -> Reg.t array -> Debuginfo.t ->
+ instruction -> instruction
+val instr_iter: (instruction -> unit) -> instruction -> unit
diff --git a/asmcomp/power/CSE.ml b/asmcomp/power/CSE.ml
new file mode 100644
index 0000000000..ec10d2df4c
--- /dev/null
+++ b/asmcomp/power/CSE.ml
@@ -0,0 +1,37 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* CSE for the PowerPC *)
+
+open Arch
+open Mach
+open CSEgen
+
+class cse = object (self)
+
+inherit cse_generic as super
+
+method! class_of_operation op =
+ match op with
+ | Ispecific(Imultaddf | Imultsubf) -> Op_pure
+ | Ispecific(Ialloc_far _) -> Op_other
+ | _ -> super#class_of_operation op
+
+method! is_cheap_operation op =
+ match op with
+ | Iconst_int n | Iconst_blockheader n -> n <= 32767n && n >= -32768n
+ | _ -> false
+
+end
+
+let fundecl f =
+ (new cse)#fundecl f
diff --git a/asmcomp/power/arch.ml b/asmcomp/power/arch.ml
new file mode 100644
index 0000000000..fa64644381
--- /dev/null
+++ b/asmcomp/power/arch.ml
@@ -0,0 +1,111 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Specific operations for the PowerPC processor *)
+
+open Format
+
+let ppc64 =
+ match Config.model with
+ | "ppc" -> false
+ | "ppc64" | "ppc64le" -> true
+ | _ -> assert false
+
+type abi = ELF32 | ELF64v1 | ELF64v2
+
+let abi =
+ match Config.model with
+ | "ppc" -> ELF32
+ | "ppc64" -> ELF64v1
+ | "ppc64le" -> ELF64v2
+ | _ -> assert false
+
+(* Machine-specific command-line options *)
+
+let big_toc = ref false
+
+let command_line_options = [
+ "-flarge-toc", Arg.Set big_toc,
+ " Support TOC (table of contents) greater than 64 kbytes"
+]
+
+(* Specific operations *)
+
+type specific_operation =
+ Imultaddf (* multiply and add *)
+ | Imultsubf (* multiply and subtract *)
+ | Ialloc_far of int (* allocation in large functions *)
+
+(* Addressing modes *)
+
+type addressing_mode =
+ Ibased of string * int (* symbol + displ *)
+ | Iindexed of int (* reg + displ *)
+ | Iindexed2 (* reg + reg *)
+
+(* Sizes, endianness *)
+
+let big_endian =
+ match Config.model with
+ | "ppc" -> true
+ | "ppc64" -> true
+ | "ppc64le" -> false
+ | _ -> assert false
+
+let size_addr = if ppc64 then 8 else 4
+let size_int = size_addr
+let size_float = 8
+
+let allow_unaligned_access = true
+
+(* Behavior of division *)
+
+let division_crashes_on_overflow = true
+
+(* Operations on addressing modes *)
+
+let identity_addressing = Iindexed 0
+
+let offset_addressing addr delta =
+ match addr with
+ Ibased(s, n) -> Ibased(s, n + delta)
+ | Iindexed n -> Iindexed(n + delta)
+ | Iindexed2 -> assert false
+
+let num_args_addressing = function
+ Ibased(s, n) -> 0
+ | Iindexed n -> 1
+ | Iindexed2 -> 2
+
+(* Printing operations and addressing modes *)
+
+let print_addressing printreg addr ppf arg =
+ match addr with
+ | Ibased(s, n) ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "\"%s\"%s" s idx
+ | Iindexed n ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a%s" printreg arg.(0) idx
+ | Iindexed2 ->
+ fprintf ppf "%a + %a" printreg arg.(0) printreg arg.(1)
+
+let print_specific_operation printreg op ppf arg =
+ match op with
+ | Imultaddf ->
+ fprintf ppf "%a *f %a +f %a"
+ printreg arg.(0) printreg arg.(1) printreg arg.(2)
+ | Imultsubf ->
+ fprintf ppf "%a *f %a -f %a"
+ printreg arg.(0) printreg arg.(1) printreg arg.(2)
+ | Ialloc_far n ->
+ fprintf ppf "alloc_far %d" n
diff --git a/asmcomp/power/emit.mlp b/asmcomp/power/emit.mlp
new file mode 100644
index 0000000000..7ef030c257
--- /dev/null
+++ b/asmcomp/power/emit.mlp
@@ -0,0 +1,1204 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Emission of PowerPC assembly code *)
+
+open Misc
+open Cmm
+open Arch
+open Proc
+open Reg
+open Mach
+open Linearize
+open Emitaux
+
+(* Reserved space at bottom of stack *)
+
+let reserved_stack_space =
+ match abi with
+ | ELF32 -> 0
+ | ELF64v1 -> 48
+ | ELF64v2 -> 32
+
+(* Layout of the stack. The stack is kept 16-aligned. *)
+
+let stack_offset = ref 0
+
+let frame_size () =
+ let size =
+ reserved_stack_space +
+ !stack_offset + (* Trap frame, outgoing parameters *)
+ size_int * num_stack_slots.(0) + (* Local int variables *)
+ size_float * num_stack_slots.(1) + (* Local float variables *)
+ (if !contains_calls && abi = ELF32 then size_int else 0) in
+ (* The return address *)
+ Misc.align size 16
+
+let slot_offset loc cls =
+ match loc with
+ Local n ->
+ reserved_stack_space + !stack_offset +
+ (if cls = 0 then num_stack_slots.(1) * size_float + n * size_int
+ else n * size_float)
+ | Incoming n -> frame_size() + reserved_stack_space + n
+ | Outgoing n -> reserved_stack_space + n
+
+let retaddr_offset () =
+ match abi with
+ | ELF32 -> frame_size() - size_addr
+ | ELF64v1 | ELF64v2 -> frame_size() + 16
+
+let toc_save_offset () =
+ match abi with
+ | ELF32 -> assert false
+ | ELF64v1 | ELF64v2 -> frame_size() + 8
+
+let (trap_size, trap_handler_offset, trap_previous_offset) =
+ match abi with
+ | ELF32 -> (16, 0, 4)
+ | ELF64v1 -> (32, 56, 64)
+ | ELF64v2 -> (32, 40, 48)
+
+(* Output a symbol *)
+
+let emit_symbol s = Emitaux.emit_symbol '.' s
+
+(* Output a label *)
+
+let label_prefix = ".L"
+
+let emit_label lbl =
+ emit_string label_prefix; emit_int lbl
+
+let emit_data_label lbl =
+ emit_string label_prefix; emit_string "d"; emit_int lbl
+
+(* Section switching *)
+
+let code_space =
+ " .section \".text\"\n"
+
+let function_descr_space =
+ match abi with
+ | ELF32 -> code_space
+ | ELF64v1 -> " .section \".opd\",\"aw\"\n"
+ | ELF64v2 -> code_space
+
+let data_space =
+ " .section \".data\"\n"
+
+let rodata_space =
+ " .section \".rodata\"\n"
+
+let toc_space =
+ " .section \".toc\",\"aw\"\n"
+
+(* Names of instructions that differ in 32 and 64-bit modes *)
+
+let lg = if ppc64 then "ld" else "lwz"
+let stg = if ppc64 then "std" else "stw"
+let lwa = if ppc64 then "lwa" else "lwz"
+let cmpg = if ppc64 then "cmpd" else "cmpw"
+let cmplg = if ppc64 then "cmpld" else "cmplw"
+let datag = if ppc64 then ".quad" else ".long"
+let mullg = if ppc64 then "mulld" else "mullw"
+let divg = if ppc64 then "divd" else "divw"
+let tglle = if ppc64 then "tdlle" else "twlle"
+let slgi = if ppc64 then "sldi" else "slwi"
+
+(* Output a processor register *)
+
+let emit_gpr = emit_int
+
+(* Output a pseudo-register *)
+
+let emit_reg r =
+ match r.loc with
+ | Reg r -> emit_string (register_name r)
+ | _ -> fatal_error "Emit.emit_reg"
+
+(* Output a stack reference *)
+
+let emit_stack r =
+ match r.loc with
+ | Stack s ->
+ let ofs = slot_offset s (register_class r) in `{emit_int ofs}(1)`
+ | _ -> fatal_error "Emit.emit_stack"
+
+(* Output the name of a symbol plus an optional offset *)
+
+let emit_symbol_offset (s, d) =
+ emit_symbol s;
+ if d > 0 then `+`;
+ if d <> 0 then emit_int d
+
+(* Split a 32-bit integer constants in two 16-bit halves *)
+
+let low_high_u n = (n land 0xFFFF, n asr 16)
+ (* unsigned low half, for use with "ori" *)
+
+let native_low_high_u n =
+ (Nativeint.(to_int (logand n 0xFFFFn)),
+ Nativeint.(to_int (shift_right n 16)))
+ (* unsigned low half, for use with "ori" *)
+
+let low_high_s n =
+ let lo = ((n + 0x8000) land 0xFFFF) - 0x8000 in
+ (lo, (n - lo) asr 16)
+ (* signed low half, for use with "addi" *)
+
+let native_low_high_s n =
+ let lo = Nativeint.(sub (logand (add n 0x8000n) 0xFFFFn) 0x8000n) in
+ (Nativeint.to_int lo,
+ Nativeint.(to_int (shift_right (sub n lo) 16)))
+ (* signed low half, for use with "addi" *)
+
+let is_immediate n =
+ n <= 32767 && n >= -32768
+
+let is_native_immediate n =
+ n <= 32767n && n >= -32768n
+
+(* Record TOC entries *)
+
+type tocentry =
+ | TocSym of string
+ | TocLabel of int
+ | TocInt of nativeint
+ | TocFloat of int64
+
+let tocref_entries : (tocentry, label) Hashtbl.t = Hashtbl.create 64
+
+let emit_tocentry = function
+ | TocSym s -> emit_symbol s
+ | TocInt i -> emit_nativeint i
+ | TocFloat f -> emit_printf "0x%Lx # %.12g" f (Int64.float_of_bits f)
+ | TocLabel lbl -> emit_label lbl
+
+let label_for_tocref entry =
+ try
+ Hashtbl.find tocref_entries entry
+ with Not_found ->
+ let lbl = new_label() in
+ Hashtbl.add tocref_entries entry lbl;
+ lbl
+
+let emit_toctable () =
+ Hashtbl.iter
+ (fun entry lbl ->
+ `{emit_label lbl}: .quad {emit_tocentry entry}\n`)
+ tocref_entries
+
+(* Emit a load from a TOC entry *)
+
+let emit_tocload emit_dest dest entry =
+ let lbl = label_for_tocref entry in
+ if !big_toc || !Clflags.for_package <> None then begin
+ ` addis {emit_dest dest}, 2, {emit_label lbl}@toc@ha\n`;
+ ` ld {emit_dest dest}, {emit_label lbl}@toc@l({emit_dest dest}) # {emit_tocentry entry}\n`
+ end else begin
+ ` ld {emit_dest dest}, {emit_label lbl}@toc(2) # {emit_tocentry entry}\n`
+ end
+
+(* Output a "upper 16 bits" or "lower 16 bits" operator. *)
+
+let emit_upper emit_fun arg =
+ emit_fun arg; emit_string "@ha"
+
+let emit_lower emit_fun arg =
+ emit_fun arg; emit_string "@l"
+
+(* Output a load or store operation *)
+
+let valid_offset instr ofs =
+ ofs land 3 = 0 || (instr <> "ld" && instr <> "std" && instr <> "lwa")
+
+let emit_load_store instr addressing_mode addr n arg =
+ match addressing_mode with
+ | Ibased(s, d) ->
+ begin match abi with
+ | ELF32 ->
+ ` addis 11, 0, {emit_upper emit_symbol_offset (s,d)}\n`;
+ ` {emit_string instr} {emit_reg arg}, {emit_lower emit_symbol_offset (s,d)}(11)\n`
+ | ELF64v1 | ELF64v2 ->
+ emit_tocload emit_gpr 11 (TocSym s);
+ let (lo, hi) = low_high_s d in
+ if hi <> 0 then
+ ` addis 11, 11, {emit_int hi}\n`;
+ ` {emit_string instr} {emit_reg arg}, {emit_int lo}(11)\n`
+ end
+ | Iindexed ofs ->
+ if is_immediate ofs && valid_offset instr ofs then
+ ` {emit_string instr} {emit_reg arg}, {emit_int ofs}({emit_reg addr.(n)})\n`
+ else begin
+ let (lo, hi) = low_high_u ofs in
+ ` addis 0, 0, {emit_int hi}\n`;
+ if lo <> 0 then
+ ` ori 0, 0, {emit_int lo}\n`;
+ ` {emit_string instr}x {emit_reg arg}, {emit_reg addr.(n)}, 0\n`
+ end
+ | Iindexed2 ->
+ ` {emit_string instr}x {emit_reg arg}, {emit_reg addr.(n)}, {emit_reg addr.(n+1)}\n`
+
+(* After a comparison, extract the result as 0 or 1 *)
+
+let emit_set_comp cmp res =
+ ` mfcr 0\n`;
+ let bitnum =
+ match cmp with
+ Ceq | Cne -> 2
+ | Cgt | Cle -> 1
+ | Clt | Cge -> 0 in
+` rlwinm {emit_reg res}, 0, {emit_int(bitnum+1)}, 31, 31\n`;
+ begin match cmp with
+ Cne | Cle | Cge -> ` xori {emit_reg res}, {emit_reg res}, 1\n`
+ | _ -> ()
+ end
+
+(* Free the stack frame *)
+
+let emit_free_frame () =
+ let n = frame_size() in
+ if n > 0 then
+ ` addi 1, 1, {emit_int n}\n`
+
+(* Emit a "bl" instruction to a given symbol *)
+
+let emit_call s =
+ match abi with
+ | ELF32 when !Clflags.dlcode || !Clflags.pic_code ->
+ ` bl {emit_symbol s}@plt\n`
+ | _ ->
+ ` bl {emit_symbol s}\n`
+
+(* Add a nop after a "bl" call for ELF64 *)
+
+let emit_call_nop () =
+ match abi with
+ | ELF32 -> ()
+ | ELF64v1 | ELF64v2 -> ` nop \n`
+
+(* Reload the TOC register r2 from the value saved on the stack *)
+
+let emit_reload_toc () =
+ ` ld 2, {emit_int (toc_save_offset())}(1)\n`
+
+(* Adjust stack_offset and emit corresponding CFI directive *)
+
+let adjust_stack_offset delta =
+ stack_offset := !stack_offset + delta;
+ cfi_adjust_cfa_offset delta
+
+(* Record live pointers at call points *)
+
+let record_frame live dbg =
+ let lbl = new_label() in
+ let live_offset = ref [] in
+ Reg.Set.iter
+ (function
+ | {typ = Val; loc = Reg r} ->
+ live_offset := ((r lsl 1) + 1) :: !live_offset
+ | {typ = Val; loc = Stack s} as reg ->
+ live_offset := slot_offset s (register_class reg) :: !live_offset
+ | {typ = Addr} as r ->
+ Misc.fatal_error ("bad GC root " ^ Reg.name r)
+ | _ -> ())
+ live;
+ frame_descriptors :=
+ { fd_lbl = lbl;
+ fd_frame_size = frame_size();
+ fd_live_offset = !live_offset;
+ fd_debuginfo = dbg } :: !frame_descriptors;
+ `{emit_label lbl}:\n`
+
+(* Record floating-point literals (for PPC32) *)
+
+let float_literals = ref ([] : (int64 * int) list)
+
+(* Record jump tables (for PPC64). In order to reduce the size of the TOC,
+ we concatenate all jumptables and emit them at the end of the compilation
+ unit. *)
+
+let jumptables = ref ([] : label list) (* in reverse order *)
+let jumptables_lbl = ref (-1)
+
+(* Names for conditional branches after comparisons *)
+
+let branch_for_comparison = function
+ Ceq -> "beq" | Cne -> "bne"
+ | Cle -> "ble" | Cgt -> "bgt"
+ | Cge -> "bge" | Clt -> "blt"
+
+let name_for_int_comparison = function
+ Isigned cmp -> (cmpg, branch_for_comparison cmp)
+ | Iunsigned cmp -> (cmplg, branch_for_comparison cmp)
+
+(* Names for various instructions *)
+
+let name_for_intop = function
+ Iadd -> "add"
+ | Imul -> if ppc64 then "mulld" else "mullw"
+ | Imulh -> if ppc64 then "mulhd" else "mulhw"
+ | Idiv -> if ppc64 then "divd" else "divw"
+ | Iand -> "and"
+ | Ior -> "or"
+ | Ixor -> "xor"
+ | Ilsl -> if ppc64 then "sld" else "slw"
+ | Ilsr -> if ppc64 then "srd" else "srw"
+ | Iasr -> if ppc64 then "srad" else "sraw"
+ | _ -> Misc.fatal_error "Emit.Intop"
+
+let name_for_intop_imm = function
+ Iadd -> "addi"
+ | Imul -> "mulli"
+ | Iand -> "andi."
+ | Ior -> "ori"
+ | Ixor -> "xori"
+ | Ilsl -> if ppc64 then "sldi" else "slwi"
+ | Ilsr -> if ppc64 then "srdi" else "srwi"
+ | Iasr -> if ppc64 then "sradi" else "srawi"
+ | _ -> Misc.fatal_error "Emit.Intop_imm"
+
+let name_for_floatop1 = function
+ Inegf -> "fneg"
+ | Iabsf -> "fabs"
+ | _ -> Misc.fatal_error "Emit.Iopf1"
+
+let name_for_floatop2 = function
+ Iaddf -> "fadd"
+ | Isubf -> "fsub"
+ | Imulf -> "fmul"
+ | Idivf -> "fdiv"
+ | _ -> Misc.fatal_error "Emit.Iopf2"
+
+let name_for_specific = function
+ Imultaddf -> "fmadd"
+ | Imultsubf -> "fmsub"
+ | _ -> Misc.fatal_error "Emit.Ispecific"
+
+(* Name of current function *)
+let function_name = ref ""
+(* Entry point for tail recursive calls *)
+let tailrec_entry_point = ref 0
+(* Label of glue code for calling the GC *)
+let call_gc_label = ref 0
+
+(* Relaxation of branches that exceed the span of a relative branch. *)
+
+module BR = Branch_relaxation.Make (struct
+ type distance = int
+
+ module Cond_branch = struct
+ type t = Branch
+
+ let all = [Branch]
+
+ let max_displacement = function
+ (* 14-bit signed offset in words. *)
+ | Branch -> 8192
+
+ let classify_instr = function
+ | Lop (Ialloc _)
+ (* [Ialloc_far] does not need to be here, since its code sequence
+ never involves any conditional branches that might need relaxing. *)
+ | Lcondbranch _
+ | Lcondbranch3 _ -> Some Branch
+ | _ -> None
+ end
+
+ let offset_pc_at_branch = 1
+
+ let size =
+ match abi with
+ | ELF32 -> (fun a b c -> a)
+ | ELF64v1 -> (fun a b c -> b)
+ | ELF64v2 -> (fun a b c -> c)
+
+ let load_store_size = function
+ | Ibased(s, d) -> 2
+ | Iindexed ofs -> if is_immediate ofs then 1 else 3
+ | Iindexed2 -> 1
+
+ let instr_size = function
+ | Lend -> 0
+ | Lop(Imove | Ispill | Ireload) -> 1
+ | Lop(Iconst_int n | Iconst_blockheader n) ->
+ if is_native_immediate n then 1 else 2
+ | Lop(Iconst_float s) -> size 2 1 1
+ | Lop(Iconst_symbol s) -> size 2 1 1
+ | Lop(Icall_ind) -> size 2 5 4
+ | Lop(Icall_imm s) -> size 1 3 3
+ | Lop(Itailcall_ind) -> size 5 7 6
+ | Lop(Itailcall_imm s) -> if s = !function_name then 1 else size 4 8 6
+ | Lop(Iextcall(s, true)) -> 3
+ | Lop(Iextcall(s, false)) -> size 1 2 2
+ | Lop(Istackoffset n) -> 1
+ | Lop(Iload(chunk, addr)) ->
+ if chunk = Byte_signed
+ then load_store_size addr + 1
+ else load_store_size addr
+ | Lop(Istore(chunk, addr, _)) -> load_store_size addr
+ | Lop(Ialloc n) -> 4
+ | Lop(Ispecific(Ialloc_far n)) -> 5
+ | Lop(Iintop Imod) -> 3
+ | Lop(Iintop(Icomp cmp)) -> 4
+ | Lop(Iintop op) -> 1
+ | Lop(Iintop_imm(Icomp cmp, n)) -> 4
+ | Lop(Iintop_imm(op, n)) -> 1
+ | Lop(Inegf | Iabsf | Iaddf | Isubf | Imulf | Idivf) -> 1
+ | Lop(Ifloatofint) -> 9
+ | Lop(Iintoffloat) -> 4
+ | Lop(Ispecific sop) -> 1
+ | Lreloadretaddr -> 2
+ | Lreturn -> 2
+ | Llabel lbl -> 0
+ | Lbranch lbl -> 1
+ | Lcondbranch(tst, lbl) -> 2
+ | Lcondbranch3(lbl0, lbl1, lbl2) ->
+ 1 + (if lbl0 = None then 0 else 1)
+ + (if lbl1 = None then 0 else 1)
+ + (if lbl2 = None then 0 else 1)
+ | Lswitch jumptbl -> size 7 6 6
+ | Lsetuptrap lbl -> size 1 2 2
+ | Lpushtrap -> size 4 5 5
+ | Lpoptrap -> 2
+ | Lraise _ -> 6
+
+ let relax_allocation ~num_words = Lop (Ispecific (Ialloc_far num_words))
+
+ (* [classify_addr], above, never identifies these instructions as needing
+ relaxing. As such, these functions should never be called. *)
+ let relax_specific_op _ = assert false
+ let relax_intop_checkbound () = assert false
+ let relax_intop_imm_checkbound ~bound:_ = assert false
+end)
+
+(* Output the assembly code for an instruction *)
+
+let emit_instr i =
+ emit_debug_info i.dbg;
+ match i.desc with
+ | Lend -> ()
+ | Lop(Imove | Ispill | Ireload) ->
+ let src = i.arg.(0) and dst = i.res.(0) in
+ if src.loc <> dst.loc then begin
+ match (src, dst) with
+ | {loc = Reg rs; typ = (Val | Int | Addr)}, {loc = Reg rd} ->
+ ` mr {emit_reg dst}, {emit_reg src}\n`
+ | {loc = Reg rs; typ = Float}, {loc = Reg rd; typ = Float} ->
+ ` fmr {emit_reg dst}, {emit_reg src}\n`
+ | {loc = Reg rs; typ = (Val | Int | Addr)}, {loc = Stack sd} ->
+ ` {emit_string stg} {emit_reg src}, {emit_stack dst}\n`
+ | {loc = Reg rs; typ = Float}, {loc = Stack sd} ->
+ ` stfd {emit_reg src}, {emit_stack dst}\n`
+ | {loc = Stack ss; typ = (Val | Int | Addr)}, {loc = Reg rd} ->
+ ` {emit_string lg} {emit_reg dst}, {emit_stack src}\n`
+ | {loc = Stack ss; typ = Float}, {loc = Reg rd} ->
+ ` lfd {emit_reg dst}, {emit_stack src}\n`
+ | (_, _) ->
+ fatal_error "Emit: Imove"
+ end
+ | Lop(Iconst_int n | Iconst_blockheader n) ->
+ if is_native_immediate n then
+ ` li {emit_reg i.res.(0)}, {emit_nativeint n}\n`
+ else begin
+ (* Try a signed decomposition first, because the sequence
+ addis/addi is eligible for instruction fusion. *)
+ let (lo, hi) = native_low_high_s n in
+ if hi >= -0x8000 && hi <= 0x7FFF then begin
+ ` addis {emit_reg i.res.(0)}, 0, {emit_int hi}\n`;
+ if lo <> 0 then
+ ` addi {emit_reg i.res.(0)}, {emit_reg i.res.(0)}, {emit_int lo}\n`
+ end else begin
+ (* Now try an unsigned decomposition *)
+ let (lo, hi) = native_low_high_u n in
+ if hi >= -0x8000 && hi <= 0x7FFF then begin
+ ` addis {emit_reg i.res.(0)}, 0, {emit_int hi}\n`;
+ if lo <> 0 then
+ ` ori {emit_reg i.res.(0)}, {emit_reg i.res.(0)}, {emit_int lo}\n`
+ end else begin
+ match abi with
+ | ELF32 -> assert false
+ | ELF64v1 | ELF64v2 ->
+ emit_tocload emit_reg i.res.(0) (TocInt n)
+ end end end
+ | Lop(Iconst_float f) ->
+ begin match abi with
+ | ELF32 ->
+ let lbl = new_label() in
+ float_literals := (Int64.bits_of_float f, lbl) :: !float_literals;
+ ` addis 11, 0, {emit_upper emit_label lbl}\n`;
+ ` lfd {emit_reg i.res.(0)}, {emit_lower emit_label lbl}(11)\n`
+ | ELF64v1 | ELF64v2 ->
+ let entry = TocFloat (Int64.bits_of_float f) in
+ let lbl = label_for_tocref entry in
+ if !big_toc || !Clflags.for_package <> None then begin
+ ` addis 11, 2, {emit_label lbl}@toc@ha\n`;
+ ` lfd {emit_reg i.res.(0)}, {emit_label lbl}@toc@l(11) # {emit_tocentry entry}\n`
+ end else begin
+ ` lfd {emit_reg i.res.(0)}, {emit_label lbl}@toc(2) # {emit_tocentry entry}\n`
+ end
+ end
+ | Lop(Iconst_symbol s) ->
+ begin match abi with
+ | ELF32 ->
+ ` addis {emit_reg i.res.(0)}, 0, {emit_upper emit_symbol s}\n`;
+ ` addi {emit_reg i.res.(0)}, {emit_reg i.res.(0)}, {emit_lower emit_symbol s}\n`
+ | ELF64v1 | ELF64v2 ->
+ emit_tocload emit_reg i.res.(0) (TocSym s)
+ end
+ | Lop(Icall_ind) ->
+ begin match abi with
+ | ELF32 ->
+ ` mtctr {emit_reg i.arg.(0)}\n`;
+ ` bctrl\n`;
+ record_frame i.live i.dbg
+ | ELF64v1 ->
+ ` ld 0, 0({emit_reg i.arg.(0)})\n`; (* code pointer *)
+ ` mtctr 0\n`;
+ ` ld 2, 8({emit_reg i.arg.(0)})\n`; (* TOC for callee *)
+ ` bctrl\n`;
+ record_frame i.live i.dbg;
+ emit_reload_toc()
+ | ELF64v2 ->
+ ` mtctr {emit_reg i.arg.(0)}\n`;
+ ` mr 12, {emit_reg i.arg.(0)}\n`; (* addr of fn in r12 *)
+ ` bctrl\n`;
+ record_frame i.live i.dbg;
+ emit_reload_toc()
+ end
+ | Lop(Icall_imm s) ->
+ begin match abi with
+ | ELF32 ->
+ emit_call s;
+ record_frame i.live i.dbg
+ | ELF64v1 | ELF64v2 ->
+ (* For PPC64, we cannot just emit a "bl s; nop" sequence, because
+ of the following scenario:
+ - current function f1 calls f2 that has the same TOC
+ - f2 tailcalls f3 that has a different TOC
+ Because f1 and f2 have the same TOC, the linker inserted no
+ code in f1 to save and restore r2 around the call to f2.
+ Because f2 tailcalls f3, r2 will not be restored to f2's TOC
+ when f3 returns. So, we're back into f1, with the wrong TOC in r2.
+ We have two options:
+ 1- Turn the call into an indirect call, like we do for
+ Itailcall_imm. Cost: 6 instructions.
+ 2- Follow the "bl" with an instruction to restore r2
+ explicitly. If the called function has a different TOC,
+ this instruction is redundant with those inserted
+ by the linker, but this is harmless.
+ Cost: 3 instructions if same TOC, 7 if different TOC.
+ Let's try option 2. *)
+ emit_call s;
+ record_frame i.live i.dbg;
+ ` nop\n`;
+ emit_reload_toc()
+ end
+ | Lop(Itailcall_ind) ->
+ begin match abi with
+ | ELF32 ->
+ ` mtctr {emit_reg i.arg.(0)}\n`
+ | ELF64v1 ->
+ ` ld 0, 0({emit_reg i.arg.(0)})\n`; (* code pointer *)
+ ` mtctr 0\n`;
+ ` ld 2, 8({emit_reg i.arg.(0)})\n` (* TOC for callee *)
+ | ELF64v2 ->
+ ` mtctr {emit_reg i.arg.(0)}\n`;
+ ` mr 12, {emit_reg i.arg.(0)}\n` (* addr of fn in r12 *)
+ end;
+ if !contains_calls then begin
+ ` {emit_string lg} 11, {emit_int(retaddr_offset())}(1)\n`;
+ ` mtlr 11\n`
+ end;
+ emit_free_frame();
+ ` bctr\n`
+ | Lop(Itailcall_imm s) ->
+ if s = !function_name then
+ ` b {emit_label !tailrec_entry_point}\n`
+ else begin
+ begin match abi with
+ | ELF32 ->
+ ()
+ | ELF64v1 ->
+ emit_tocload emit_gpr 11 (TocSym s);
+ ` ld 0, 0(11)\n`; (* code pointer *)
+ ` mtctr 0\n`;
+ ` ld 2, 8(11)\n` (* TOC for callee *)
+ | ELF64v2 ->
+ emit_tocload emit_gpr 12 (TocSym s); (* addr of fn must be in r12 *)
+ ` mtctr 12\n`
+ end;
+ if !contains_calls then begin
+ ` {emit_string lg} 11, {emit_int(retaddr_offset())}(1)\n`;
+ ` mtlr 11\n`
+ end;
+ emit_free_frame();
+ begin match abi with
+ | ELF32 ->
+ ` b {emit_symbol s}\n`
+ | ELF64v1 | ELF64v2 ->
+ ` bctr\n`
+ end
+ end
+ | Lop(Iextcall(s, alloc)) ->
+ if not alloc then begin
+ emit_call s;
+ emit_call_nop()
+ end else begin
+ match abi with
+ | ELF32 ->
+ ` addis 28, 0, {emit_upper emit_symbol s}\n`;
+ ` addi 28, 28, {emit_lower emit_symbol s}\n`;
+ emit_call "caml_c_call";
+ record_frame i.live i.dbg
+ | ELF64v1 | ELF64v2 ->
+ emit_tocload emit_gpr 28 (TocSym s);
+ emit_call "caml_c_call";
+ record_frame i.live i.dbg;
+ ` nop\n`
+ end
+ | Lop(Istackoffset n) ->
+ ` addi 1, 1, {emit_int (-n)}\n`;
+ adjust_stack_offset n
+ | Lop(Iload(chunk, addr)) ->
+ let loadinstr =
+ match chunk with
+ | Byte_unsigned -> "lbz"
+ | Byte_signed -> "lbz"
+ | Sixteen_unsigned -> "lhz"
+ | Sixteen_signed -> "lha"
+ | Thirtytwo_unsigned -> "lwz"
+ | Thirtytwo_signed -> if ppc64 then "lwa" else "lwz"
+ | Word_int | Word_val -> lg
+ | Single -> "lfs"
+ | Double | Double_u -> "lfd" in
+ emit_load_store loadinstr addr i.arg 0 i.res.(0);
+ if chunk = Byte_signed then
+ ` extsb {emit_reg i.res.(0)}, {emit_reg i.res.(0)}\n`
+ | Lop(Istore(chunk, addr, _)) ->
+ let storeinstr =
+ match chunk with
+ | Byte_unsigned | Byte_signed -> "stb"
+ | Sixteen_unsigned | Sixteen_signed -> "sth"
+ | Thirtytwo_unsigned | Thirtytwo_signed -> "stw"
+ | Word_int | Word_val -> stg
+ | Single -> "stfs"
+ | Double | Double_u -> "stfd" in
+ emit_load_store storeinstr addr i.arg 1 i.arg.(0)
+ | Lop(Ialloc n) ->
+ if !call_gc_label = 0 then call_gc_label := new_label();
+ ` addi 31, 31, {emit_int(-n)}\n`;
+ ` {emit_string cmplg} 31, 30\n`;
+ ` addi {emit_reg i.res.(0)}, 31, {emit_int size_addr}\n`;
+ ` bltl {emit_label !call_gc_label}\n`;
+ (* Exactly 4 instructions after the beginning of the alloc sequence *)
+ record_frame i.live Debuginfo.none
+ | Lop(Ispecific(Ialloc_far n)) ->
+ if !call_gc_label = 0 then call_gc_label := new_label();
+ let lbl = new_label() in
+ ` addi 31, 31, {emit_int(-n)}\n`;
+ ` {emit_string cmplg} 31, 30\n`;
+ ` bge {emit_label lbl}\n`;
+ ` bl {emit_label !call_gc_label}\n`;
+ (* Exactly 4 instructions after the beginning of the alloc sequence *)
+ record_frame i.live Debuginfo.none;
+ `{emit_label lbl}: addi {emit_reg i.res.(0)}, 31, {emit_int size_addr}\n`
+ | Lop(Iintop Isub) -> (* subfc has swapped arguments *)
+ ` subfc {emit_reg i.res.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.arg.(0)}\n`
+ | Lop(Iintop Imod) ->
+ ` {emit_string divg} 0, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` {emit_string mullg} 0, 0, {emit_reg i.arg.(1)}\n`;
+ ` subfc {emit_reg i.res.(0)}, 0, {emit_reg i.arg.(0)}\n`
+ | Lop(Iintop(Icomp cmp)) ->
+ begin match cmp with
+ Isigned c ->
+ ` {emit_string cmpg} {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ emit_set_comp c i.res.(0)
+ | Iunsigned c ->
+ ` {emit_string cmplg} {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ emit_set_comp c i.res.(0)
+ end
+ | Lop(Iintop Icheckbound) ->
+ if !Clflags.debug then
+ record_frame Reg.Set.empty i.dbg;
+ ` {emit_string tglle} {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`
+ | Lop(Iintop op) ->
+ let instr = name_for_intop op in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`
+ | Lop(Iintop_imm(Isub, n)) ->
+ ` addi {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_int(-n)}\n`
+ | Lop(Iintop_imm(Icomp cmp, n)) ->
+ begin match cmp with
+ Isigned c ->
+ ` {emit_string cmpg}i {emit_reg i.arg.(0)}, {emit_int n}\n`;
+ emit_set_comp c i.res.(0)
+ | Iunsigned c ->
+ ` {emit_string cmplg}i {emit_reg i.arg.(0)}, {emit_int n}\n`;
+ emit_set_comp c i.res.(0)
+ end
+ | Lop(Iintop_imm(Icheckbound, n)) ->
+ if !Clflags.debug then
+ record_frame Reg.Set.empty i.dbg;
+ ` {emit_string tglle}i {emit_reg i.arg.(0)}, {emit_int n}\n`
+ | Lop(Iintop_imm(op, n)) ->
+ let instr = name_for_intop_imm op in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_int n}\n`
+ | Lop(Inegf | Iabsf as op) ->
+ let instr = name_for_floatop1 op in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}\n`
+ | Lop(Iaddf | Isubf | Imulf | Idivf as op) ->
+ let instr = name_for_floatop2 op in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`
+ | Lop(Ifloatofint) ->
+ if ppc64 then begin
+ (* Can use protected zone (288 bytes below r1 *)
+ ` std {emit_reg i.arg.(0)}, -16(1)\n`;
+ ` lfd {emit_reg i.res.(0)}, -16(1)\n`;
+ ` fcfid {emit_reg i.res.(0)}, {emit_reg i.res.(0)}\n`
+ end else begin
+ let lbl = new_label() in
+ float_literals := (0x4330000080000000L, lbl) :: !float_literals;
+ ` addis 11, 0, {emit_upper emit_label lbl}\n`;
+ ` lfd 0, {emit_lower emit_label lbl}(11)\n`;
+ ` lis 0, 0x4330\n`;
+ ` stwu 0, -16(1)\n`;
+ ` xoris 0, {emit_reg i.arg.(0)}, 0x8000\n`;
+ ` stw 0, 4(1)\n`;
+ ` lfd {emit_reg i.res.(0)}, 0(1)\n`;
+ ` addi 1, 1, 16\n`;
+ ` fsub {emit_reg i.res.(0)}, {emit_reg i.res.(0)}, 0\n`
+ end
+ | Lop(Iintoffloat) ->
+ if ppc64 then begin
+ (* Can use protected zone (288 bytes below r1 *)
+ ` fctidz 0, {emit_reg i.arg.(0)}\n`;
+ ` stfd 0, -16(1)\n`;
+ ` ld {emit_reg i.res.(0)}, -16(1)\n`
+ end else begin
+ ` fctiwz 0, {emit_reg i.arg.(0)}\n`;
+ ` stfdu 0, -16(1)\n`;
+ ` lwz {emit_reg i.res.(0)}, 4(1)\n`;
+ ` addi 1, 1, 16\n`
+ end
+ | Lop(Ispecific sop) ->
+ let instr = name_for_specific sop in
+ ` {emit_string instr} {emit_reg i.res.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.arg.(2)}\n`
+ | Lreloadretaddr ->
+ ` {emit_string lg} 11, {emit_int(retaddr_offset())}(1)\n`;
+ ` mtlr 11\n`
+ | Lreturn ->
+ emit_free_frame();
+ ` blr\n`
+ | Llabel lbl ->
+ `{emit_label lbl}:\n`
+ | Lbranch lbl ->
+ ` b {emit_label lbl}\n`
+ | Lcondbranch(tst, lbl) ->
+ begin match tst with
+ Itruetest ->
+ ` {emit_string cmpg}i {emit_reg i.arg.(0)}, 0\n`;
+ ` bne {emit_label lbl}\n`
+ | Ifalsetest ->
+ ` {emit_string cmpg}i {emit_reg i.arg.(0)}, 0\n`;
+ ` beq {emit_label lbl}\n`
+ | Iinttest cmp ->
+ let (comp, branch) = name_for_int_comparison cmp in
+ ` {emit_string comp} {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` {emit_string branch} {emit_label lbl}\n`
+ | Iinttest_imm(cmp, n) ->
+ let (comp, branch) = name_for_int_comparison cmp in
+ ` {emit_string comp}i {emit_reg i.arg.(0)}, {emit_int n}\n`;
+ ` {emit_string branch} {emit_label lbl}\n`
+ | Ifloattest(cmp, neg) ->
+ ` fcmpu 0, {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ (* bit 0 = lt, bit 1 = gt, bit 2 = eq *)
+ let (bitnum, negtst) =
+ match cmp with
+ Ceq -> (2, neg)
+ | Cne -> (2, not neg)
+ | Cle -> ` cror 3, 0, 2\n`; (* lt or eq *)
+ (3, neg)
+ | Cgt -> (1, neg)
+ | Cge -> ` cror 3, 1, 2\n`; (* gt or eq *)
+ (3, neg)
+ | Clt -> (0, neg) in
+ if negtst
+ then ` bf {emit_int bitnum}, {emit_label lbl}\n`
+ else ` bt {emit_int bitnum}, {emit_label lbl}\n`
+ | Ioddtest ->
+ ` andi. 0, {emit_reg i.arg.(0)}, 1\n`;
+ ` bne {emit_label lbl}\n`
+ | Ieventest ->
+ ` andi. 0, {emit_reg i.arg.(0)}, 1\n`;
+ ` beq {emit_label lbl}\n`
+ end
+ | Lcondbranch3(lbl0, lbl1, lbl2) ->
+ ` {emit_string cmpg}i {emit_reg i.arg.(0)}, 1\n`;
+ begin match lbl0 with
+ None -> ()
+ | Some lbl -> ` blt {emit_label lbl}\n`
+ end;
+ begin match lbl1 with
+ None -> ()
+ | Some lbl -> ` beq {emit_label lbl}\n`
+ end;
+ begin match lbl2 with
+ None -> ()
+ | Some lbl -> ` bgt {emit_label lbl}\n`
+ end
+ | Lswitch jumptbl ->
+ let lbl = new_label() in
+ if ppc64 then begin
+ if !jumptables_lbl < 0 then jumptables_lbl := lbl;
+ let start = List.length !jumptables in
+ let (start_lo, start_hi) = low_high_s start in
+ emit_tocload emit_gpr 11 (TocLabel !jumptables_lbl);
+ ` addi 12, {emit_reg i.arg.(0)}, {emit_int start_lo}\n`;
+ if start_hi <> 0 then
+ ` addis 12, 12, {emit_int start_hi}\n`;
+ ` sldi 12, 12, 2\n`
+ end else begin
+ ` addis 11, 0, {emit_upper emit_label lbl}\n`;
+ ` addi 11, 11, {emit_lower emit_label lbl}\n`;
+ ` slwi 12, {emit_reg i.arg.(0)}, 2\n`
+ end;
+ ` {emit_string lwa}x 0, 11, 12\n`;
+ ` add 0, 11, 0\n`;
+ ` mtctr 0\n`;
+ ` bctr\n`;
+ if ppc64 then begin
+ jumptables := List.rev_append (Array.to_list jumptbl) !jumptables
+ end else begin
+ emit_string rodata_space;
+ `{emit_label lbl}:`;
+ for i = 0 to Array.length jumptbl - 1 do
+ ` .long {emit_label jumptbl.(i)} - {emit_label lbl}\n`
+ done;
+ emit_string code_space
+ end
+ | Lsetuptrap lbl ->
+ ` bl {emit_label lbl}\n`;
+ begin match abi with
+ | ELF32 -> ()
+ | ELF64v1 | ELF64v2 -> emit_reload_toc()
+ end
+ | Lpushtrap ->
+ begin match abi with
+ | ELF32 ->
+ ` mflr 0\n`;
+ ` stwu 0, -16(1)\n`;
+ adjust_stack_offset 16;
+ ` stw 29, 4(1)\n`;
+ ` mr 29, 1\n`
+ | ELF64v1 | ELF64v2 ->
+ ` mflr 0\n`;
+ ` addi 1, 1, -32\n`;
+ adjust_stack_offset 32;
+ ` std 0, {emit_int trap_handler_offset}(1)\n`;
+ ` std 29, {emit_int trap_previous_offset}(1)\n`;
+ ` mr 29, 1\n`
+ end
+ | Lpoptrap ->
+ ` {emit_string lg} 29, {emit_int trap_previous_offset}(1)\n`;
+ ` addi 1, 1, {emit_int trap_size}\n`;
+ adjust_stack_offset (-trap_size)
+ | Lraise k ->
+ begin match !Clflags.debug, k with
+ | true, Lambda.Raise_regular ->
+ emit_call "caml_raise_exn";
+ record_frame Reg.Set.empty i.dbg;
+ emit_call_nop()
+ | true, Lambda.Raise_reraise ->
+ emit_call "caml_reraise_exn";
+ record_frame Reg.Set.empty i.dbg;
+ emit_call_nop()
+ | false, _
+ | true, Lambda.Raise_notrace ->
+ ` {emit_string lg} 0, {emit_int trap_handler_offset}(29)\n`;
+ ` mr 1, 29\n`;
+ ` mtctr 0\n`;
+ ` {emit_string lg} 29, {emit_int trap_previous_offset}(1)\n`;
+ ` addi 1, 1, {emit_int trap_size}\n`;
+ ` bctr\n`
+ end
+
+(* Emit a sequence of instructions *)
+
+let rec emit_all i =
+ match i.desc with
+ | Lend -> ()
+ | _ -> emit_instr i; emit_all i.next
+
+(* Emission of the profiling prelude *)
+
+let emit_profile () =
+ match abi with
+ | ELF32 ->
+ ` mflr 0\n`;
+ ` addi 1, 1, -16\n`;
+ ` stw 0, 4(1)\n`;
+ (* _mcount preserves the registers used for parameter passing *)
+ (* when it returns, lr contains the original return address *)
+ ` bl {emit_symbol "_mcount"}\n`;
+ ` addi 1, 1, 16\n`
+ | ELF64v1 | ELF64v2 ->
+ ` mflr 0\n`;
+ (* save the registers used for parameter passing *)
+ ` bl {emit_symbol "caml_before_mcount"}\n`;
+ ` bl {emit_symbol "_mcount"}\n`;
+ ` nop\n`;
+ (* restore the registers used for parameter passing *)
+ ` bl {emit_symbol "caml_after_mcount"}\n`;
+ ` mtlr 0\n`
+
+(* Emission of a function declaration *)
+
+let fundecl fundecl =
+ function_name := fundecl.fun_name;
+ tailrec_entry_point := new_label();
+ stack_offset := 0;
+ call_gc_label := 0;
+ float_literals := [];
+ jumptables := []; jumptables_lbl := -1;
+ begin match abi with
+ | ELF32 ->
+ emit_string code_space;
+ ` .globl {emit_symbol fundecl.fun_name}\n`;
+ ` .type {emit_symbol fundecl.fun_name}, @function\n`;
+ ` .align 2\n`;
+ `{emit_symbol fundecl.fun_name}:\n`
+ | ELF64v1 ->
+ emit_string function_descr_space;
+ ` .align 3\n`;
+ ` .globl {emit_symbol fundecl.fun_name}\n`;
+ ` .type {emit_symbol fundecl.fun_name}, @function\n`;
+ `{emit_symbol fundecl.fun_name}:\n`;
+ ` .quad .L.{emit_symbol fundecl.fun_name}, .TOC.@tocbase\n`;
+ emit_string code_space;
+ ` .align 2\n`;
+ `.L.{emit_symbol fundecl.fun_name}:\n`
+ | ELF64v2 ->
+ emit_string code_space;
+ ` .globl {emit_symbol fundecl.fun_name}\n`;
+ ` .type {emit_symbol fundecl.fun_name}, @function\n`;
+ ` .align 2\n`;
+ `{emit_symbol fundecl.fun_name}:\n`;
+ `0: addis 2, 12, (.TOC. - 0b)@ha\n`;
+ ` addi 2, 2, (.TOC. - 0b)@l\n`;
+ ` .localentry {emit_symbol fundecl.fun_name}, . - 0b\n`
+ end;
+ emit_debug_info fundecl.fun_dbg;
+ cfi_startproc();
+ if !Clflags.gprofile then emit_profile();
+ let n = frame_size() in
+ if n > 0 then begin
+ ` addi 1, 1, {emit_int(-n)}\n`;
+ cfi_adjust_cfa_offset n
+ end;
+ if !contains_calls then begin
+ let ra = retaddr_offset() in
+ ` mflr 0\n`;
+ ` {emit_string stg} 0, {emit_int ra}(1)\n`;
+ cfi_offset ~reg: 65 (* LR *) ~offset: (ra - n);
+ match abi with
+ | ELF32 -> ()
+ | ELF64v1 | ELF64v2 ->
+ ` std 2, {emit_int(toc_save_offset())}(1)\n`
+ end;
+ `{emit_label !tailrec_entry_point}:\n`;
+ (* On this target, there is at most one "out of line" code block per
+ function: a single "call GC" point. It comes immediately after the
+ function's body. *)
+ BR.relax fundecl.fun_body ~max_out_of_line_code_offset:0;
+ emit_all fundecl.fun_body;
+ (* Emit the glue code to call the GC *)
+ if !call_gc_label > 0 then begin
+ `{emit_label !call_gc_label}:\n`;
+ match abi with
+ | ELF32 ->
+ ` b {emit_symbol "caml_call_gc"}\n`
+ | ELF64v1 ->
+ ` std 2, 40(1)\n`;
+ (* save our TOC, will be restored by caml_call_gc *)
+ emit_tocload emit_gpr 11 (TocSym "caml_call_gc");
+ ` ld 0, 0(11)\n`;
+ ` mtctr 0\n`;
+ ` ld 2, 8(11)\n`;
+ ` bctr\n`
+ | ELF64v2 ->
+ ` std 2, 24(1)\n`;
+ (* save our TOC, will be restored by caml_call_gc *)
+ emit_tocload emit_gpr 12 (TocSym "caml_call_gc");
+ ` mtctr 12\n`;
+ ` bctr\n`
+ end;
+ cfi_endproc();
+ begin match abi with
+ | ELF32 | ELF64v2 ->
+ ` .size {emit_symbol fundecl.fun_name}, . - {emit_symbol fundecl.fun_name}\n`
+ | ELF64v1 ->
+ ` .size {emit_symbol fundecl.fun_name}, . - .L.{emit_symbol fundecl.fun_name}\n`
+ end;
+ (* Emit the numeric literals *)
+ if !float_literals <> [] then begin
+ emit_string rodata_space;
+ ` .align 3\n`;
+ List.iter
+ (fun (f, lbl) ->
+ `{emit_label lbl}:`;
+ emit_float64_split_directive ".long" f)
+ !float_literals
+ end;
+ (* Emit the jump tables *)
+ if !jumptables <> [] then begin
+ emit_string rodata_space;
+ ` .align 2\n`;
+ `{emit_label !jumptables_lbl}:`;
+ List.iter
+ (fun lbl ->
+ ` .long {emit_label lbl} - {emit_label !jumptables_lbl}\n`)
+ (List.rev !jumptables)
+ end
+
+(* Emission of data *)
+
+let declare_global_data s =
+ ` .globl {emit_symbol s}\n`;
+ ` .type {emit_symbol s}, @object\n`
+
+let emit_item = function
+ Cglobal_symbol s ->
+ declare_global_data s
+ | Cdefine_symbol s ->
+ `{emit_symbol s}:\n`;
+ | Cdefine_label lbl ->
+ `{emit_data_label lbl}:\n`
+ | Cint8 n ->
+ ` .byte {emit_int n}\n`
+ | Cint16 n ->
+ ` .short {emit_int n}\n`
+ | Cint32 n ->
+ ` .long {emit_nativeint n}\n`
+ | Cint n ->
+ ` {emit_string datag} {emit_nativeint n}\n`
+ | Csingle f ->
+ emit_float32_directive ".long" (Int32.bits_of_float f)
+ | Cdouble f ->
+ if ppc64
+ then emit_float64_directive ".quad" (Int64.bits_of_float f)
+ else emit_float64_split_directive ".long" (Int64.bits_of_float f)
+ | Csymbol_address s ->
+ ` {emit_string datag} {emit_symbol s}\n`
+ | Clabel_address lbl ->
+ ` {emit_string datag} {emit_data_label lbl}\n`
+ | Cstring s ->
+ emit_bytes_directive " .byte " s
+ | Cskip n ->
+ if n > 0 then ` .space {emit_int n}\n`
+ | Calign n ->
+ ` .align {emit_int (Misc.log2 n)}\n`
+
+let data l =
+ emit_string data_space;
+ ` .align {emit_int (if ppc64 then 3 else 2)}\n`;
+ List.iter emit_item l
+
+(* Beginning / end of an assembly file *)
+
+let begin_assembly() =
+ reset_debug_info();
+ begin match abi with
+ | ELF64v2 -> ` .abiversion 2\n`
+ | _ -> ()
+ end;
+ Hashtbl.clear tocref_entries;
+ (* Emit the beginning of the segments *)
+ let lbl_begin = Compilenv.make_symbol (Some "data_begin") in
+ emit_string data_space;
+ declare_global_data lbl_begin;
+ `{emit_symbol lbl_begin}:\n`;
+ let lbl_begin = Compilenv.make_symbol (Some "code_begin") in
+ emit_string function_descr_space;
+ (* For the ELF64v1 ABI, we must make sure that the .opd and .data
+ sections are in different pages. .opd comes after .data,
+ so aligning .opd is enough. To save space, we do it only
+ for the startup file, not for every OCaml compilation unit. *)
+ let c = Compilenv.current_unit_name() in
+ if abi = ELF64v1 && (c = "_startup" || c = "_shared_startup") then begin
+ ` .p2align 12\n`
+ end;
+ declare_global_data lbl_begin;
+ `{emit_symbol lbl_begin}:\n`
+
+let end_assembly() =
+ (* In profiling mode, for ELF64, emit the helper functions
+ for register saving and restoring. We put one copy of these
+ functions in every generated file, instead of defining
+ them once in asmrun/power.S, so that we can call them
+ without risking to save r2 in the wrong place. *)
+ if ppc64 && !Clflags.gprofile then begin
+ let save_area = reserved_stack_space + (if abi = ELF64v1 then 8*8 else 0) in
+ let stacksize = save_area + 8*8 in
+ emit_string code_space;
+ ` .align 2\n`;
+ `{emit_symbol "caml_before_mcount"}:\n`;
+ ` stdu 1, {emit_int (-stacksize)}(1)\n`;
+ ` std 0, {emit_int (16 + stacksize)}(1)\n`;
+ for i = 3 to 10 do
+ ` std {emit_gpr i}, {emit_int (save_area + (i - 3) * 8)}(1)\n`
+ done;
+ ` blr\n`;
+ `{emit_symbol "caml_after_mcount"}:\n`;
+ ` ld 0, {emit_int (16 + stacksize)}(1)\n`;
+ for i = 3 to 10 do
+ ` ld {emit_gpr i}, {emit_int (save_area + (i - 3) * 8)}(1)\n`
+ done;
+ ` addi 1, 1, {emit_int stacksize}\n`;
+ ` blr\n`
+ end;
+ (* Emit the end of the segments *)
+ emit_string function_descr_space;
+ let lbl_end = Compilenv.make_symbol (Some "code_end") in
+ declare_global_data lbl_end;
+ `{emit_symbol lbl_end}:\n`;
+ if abi <> ELF64v1 then ` .long 0\n`;
+ emit_string data_space;
+ let lbl_end = Compilenv.make_symbol (Some "data_end") in
+ declare_global_data lbl_end;
+ `{emit_symbol lbl_end}:\n`;
+ ` {emit_string datag} 0\n`;
+ (* Emit the frame descriptors *)
+ emit_string rodata_space;
+ let lbl = Compilenv.make_symbol (Some "frametable") in
+ declare_global_data lbl;
+ `{emit_symbol lbl}:\n`;
+ emit_frames
+ { efa_label = (fun l -> ` {emit_string datag} {emit_label l}\n`);
+ efa_16 = (fun n -> ` .short {emit_int n}\n`);
+ efa_32 = (fun n -> ` .long {emit_int32 n}\n`);
+ efa_word = (fun n -> ` {emit_string datag} {emit_int n}\n`);
+ efa_align = (fun n -> ` .balign {emit_int n}\n`);
+ efa_label_rel = (fun lbl ofs ->
+ ` .long ({emit_label lbl} - .) + {emit_int32 ofs}\n`);
+ efa_def_label = (fun l -> `{emit_label l}:\n`);
+ efa_string = (fun s -> emit_bytes_directive " .byte " (s ^ "\000"))
+ };
+ (* Emit the TOC entries *)
+ begin match abi with
+ | ELF32 -> ()
+ | ELF64v1 | ELF64v2 ->
+ emit_string toc_space;
+ emit_toctable();
+ Hashtbl.clear tocref_entries
+ end;
+ ` .section .note.GNU-stack,\"\",%progbits\n`
diff --git a/asmcomp/power/proc.ml b/asmcomp/power/proc.ml
new file mode 100644
index 0000000000..e97fc00e08
--- /dev/null
+++ b/asmcomp/power/proc.ml
@@ -0,0 +1,306 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Description of the Power PC *)
+
+open Misc
+open Cmm
+open Reg
+open Arch
+open Mach
+
+(* Instruction selection *)
+
+let word_addressed = false
+
+(* Registers available for register allocation *)
+
+(* Integer register map:
+ 0 temporary, null register for some operations
+ 1 stack pointer
+ 2 pointer to table of contents
+ 3 - 10 function arguments and results
+ 11 - 12 temporaries
+ 13 pointer to small data area
+ 14 - 28 general purpose, preserved by C
+ 29 trap pointer
+ 30 allocation limit
+ 31 allocation pointer
+ Floating-point register map:
+ 0 temporary
+ 1 - 13 function arguments and results
+ 14 - 31 general purpose, preserved by C
+*)
+
+let int_reg_name =
+ [| "3"; "4"; "5"; "6"; "7"; "8"; "9"; "10";
+ "14"; "15"; "16"; "17"; "18"; "19"; "20"; "21";
+ "22"; "23"; "24"; "25"; "26"; "27"; "28" |]
+
+let float_reg_name =
+ [| "1"; "2"; "3"; "4"; "5"; "6"; "7"; "8";
+ "9"; "10"; "11"; "12"; "13"; "14"; "15"; "16";
+ "17"; "18"; "19"; "20"; "21"; "22"; "23"; "24";
+ "25"; "26"; "27"; "28"; "29"; "30"; "31" |]
+
+let num_register_classes = 2
+
+let register_class r =
+ match r.typ with
+ | Val | Int | Addr -> 0
+ | Float -> 1
+
+let num_available_registers = [| 23; 31 |]
+
+let first_available_register = [| 0; 100 |]
+
+let register_name r =
+ if r < 100 then int_reg_name.(r) else float_reg_name.(r - 100)
+
+let rotate_registers = true
+
+(* Representation of hard registers by pseudo-registers *)
+
+let hard_int_reg =
+ let v = Array.make 23 Reg.dummy in
+ for i = 0 to 22 do v.(i) <- Reg.at_location Int (Reg i) done; v
+
+let hard_float_reg =
+ let v = Array.make 31 Reg.dummy in
+ for i = 0 to 30 do v.(i) <- Reg.at_location Float (Reg(100 + i)) done; v
+
+let all_phys_regs =
+ Array.append hard_int_reg hard_float_reg
+
+let phys_reg n =
+ if n < 100 then hard_int_reg.(n) else hard_float_reg.(n - 100)
+
+let stack_slot slot ty =
+ Reg.at_location ty (Stack slot)
+
+(* Calling conventions *)
+
+let calling_conventions
+ first_int last_int first_float last_float
+ make_stack stack_ofs reg_use_stack arg =
+ let loc = Array.make (Array.length arg) [| Reg.dummy |] in
+ let int = ref first_int in
+ let float = ref first_float in
+ let ofs = ref stack_ofs in
+ for i = 0 to Array.length arg - 1 do
+ match arg.(i) with
+ | [| arg |] ->
+ begin match arg.typ with
+ | Val | Int | Addr as ty ->
+ if !int <= last_int then begin
+ loc.(i) <- [| phys_reg !int |];
+ incr int;
+ if reg_use_stack then ofs := !ofs + size_int
+ end else begin
+ loc.(i) <- [| stack_slot (make_stack !ofs) ty |];
+ ofs := !ofs + size_int
+ end
+ | Float ->
+ if !float <= last_float then begin
+ loc.(i) <- [| phys_reg !float |];
+ incr float;
+ (* On 64-bit platforms, passing a float in a float register
+ reserves a normal register as well *)
+ if size_int = 8 then incr int;
+ if reg_use_stack then ofs := !ofs + size_float
+ end else begin
+ ofs := Misc.align !ofs size_float;
+ loc.(i) <- [| stack_slot (make_stack !ofs) Float |];
+ ofs := !ofs + size_float
+ end
+ end
+ | [| arg1; arg2 |] ->
+ (* Passing of 64-bit quantities to external functions
+ on 32-bit platform. *)
+ assert (size_int = 4);
+ begin match arg1.typ, arg2.typ with
+ | Int, Int ->
+ (* 64-bit quantities split across two registers must either be in a
+ consecutive pair of registers where the lowest numbered is an
+ even-numbered register; or in a stack slot that is 8-byte
+ aligned. *)
+ int := Misc.align !int 2;
+ let pos_least, pos_most = if big_endian then (1, 0) else (0, 1) in
+ if !int <= last_int - 1 then begin
+ let reg_least = phys_reg (!int + pos_least) in
+ let reg_most = phys_reg (!int + pos_most ) in
+ loc.(i) <- [| reg_least; reg_most |];
+ int := !int + 2
+ end else begin
+ let size_int64 = 8 in
+ ofs := Misc.align !ofs size_int64;
+ let ofs_least = !ofs + size_int * pos_least in
+ let ofs_most = !ofs + size_int * pos_most in
+ let stack_least = stack_slot (make_stack ofs_least) Int in
+ let stack_most = stack_slot (make_stack ofs_most ) Int in
+ loc.(i) <- [| stack_least; stack_most |];
+ ofs := !ofs + size_int64
+ end
+ | _, _ ->
+ let f = function Int -> "I" | Addr -> "A" | Val -> "V" | Float -> "F" in
+ fatal_error (Printf.sprintf "Proc.calling_conventions: bad register \
+ type(s) for multi-register argument: %s, %s"
+ (f arg1.typ) (f arg2.typ))
+ end
+ | _ ->
+ fatal_error "Proc.calling_conventions: bad number of registers for \
+ multi-register argument"
+ done;
+ (loc, Misc.align !ofs 16)
+ (* Keep stack 16-aligned. *)
+
+let incoming ofs = Incoming ofs
+let outgoing ofs = Outgoing ofs
+let not_supported ofs = fatal_error "Proc.loc_results: cannot call"
+
+let single_regs arg = Array.map (fun arg -> [| arg |]) arg
+let ensure_single_regs res =
+ Array.map (function
+ | [| res |] -> res
+ | _ -> failwith "Proc.ensure_single_regs")
+ res
+
+let loc_arguments arg =
+ let (loc, ofs) =
+ calling_conventions 0 7 100 112 outgoing 0 false (single_regs arg)
+ in
+ (ensure_single_regs loc, ofs)
+let loc_parameters arg =
+ let (loc, ofs) =
+ calling_conventions 0 7 100 112 incoming 0 false (single_regs arg)
+ in
+ ensure_single_regs loc
+let loc_results res =
+ let (loc, ofs) =
+ calling_conventions 0 7 100 112 not_supported 0 false (single_regs res)
+ in
+ ensure_single_regs loc
+
+(* C calling conventions for ELF32:
+ use GPR 3-10 and FPR 1-8 just like ML calling conventions.
+ Using a float register does not affect the int registers.
+ Always reserve 8 bytes at bottom of stack, plus whatever is needed
+ to hold the overflow arguments.
+ C calling conventions for ELF64v1:
+ Use GPR 3-10 for the first integer arguments.
+ Use FPR 1-13 for the first float arguments.
+ Always reserve stack space for all arguments, even when passed in
+ registers.
+ Always reserve at least 8 words (64 bytes) for the arguments.
+ Always reserve 48 bytes at bottom of stack, plus whatever is needed
+ to hold the arguments.
+ The reserved 48 bytes are automatically added in emit.mlp
+ and need not appear here.
+ C calling conventions for ELF64v2:
+ Use GPR 3-10 for the first integer arguments.
+ Use FPR 1-13 for the first float arguments.
+ If all arguments fit in registers, don't reserve stack space.
+ Otherwise, reserve stack space for all arguments.
+ Always reserve 32 bytes at bottom of stack, plus whatever is needed
+ to hold the arguments.
+ The reserved 32 bytes are automatically added in emit.mlp
+ and need not appear here.
+*)
+
+let loc_external_arguments =
+ match abi with
+ | ELF32 ->
+ calling_conventions 0 7 100 107 outgoing 8 false
+ | ELF64v1 ->
+ fun args ->
+ let (loc, ofs) =
+ calling_conventions 0 7 100 112 outgoing 0 true args in
+ (loc, max ofs 64)
+ | ELF64v2 ->
+ fun args ->
+ let (loc, ofs) =
+ calling_conventions 0 7 100 112 outgoing 0 true args in
+ if Array.fold_left
+ (fun stk r ->
+ assert (Array.length r = 1);
+ match r.(0).loc with
+ | Stack _ -> true
+ | _ -> stk)
+ false loc
+ then (loc, ofs)
+ else (loc, 0)
+
+let extcall_use_push = false
+
+(* Results are in GPR 3 and FPR 1 *)
+
+let loc_external_results res =
+ let (loc, ofs) =
+ calling_conventions 0 1 100 100 not_supported 0 false (single_regs res)
+ in
+ ensure_single_regs loc
+
+(* Exceptions are in GPR 3 *)
+
+let loc_exn_bucket = phys_reg 0
+
+(* Volatile registers: none *)
+
+let regs_are_volatile rs = false
+
+(* Registers destroyed by operations *)
+
+let destroyed_at_c_call =
+ Array.of_list(List.map phys_reg
+ [0; 1; 2; 3; 4; 5; 6; 7;
+ 100; 101; 102; 103; 104; 105; 106; 107; 108; 109; 110; 111; 112])
+
+let destroyed_at_oper = function
+ Iop(Icall_ind | Icall_imm _ | Iextcall(_, true)) -> all_phys_regs
+ | Iop(Iextcall(_, false)) -> destroyed_at_c_call
+ | _ -> [||]
+
+let destroyed_at_raise = all_phys_regs
+
+(* Maximal register pressure *)
+
+let safe_register_pressure = function
+ Iextcall(_, _) -> 15
+ | _ -> 23
+
+let max_register_pressure = function
+ Iextcall(_, _) -> [| 15; 18 |]
+ | _ -> [| 23; 30 |]
+
+(* Pure operations (without any side effect besides updating their result
+ registers). *)
+
+let op_is_pure = function
+ | Icall_ind | Icall_imm _ | Itailcall_ind | Itailcall_imm _
+ | Iextcall _ | Istackoffset _ | Istore _ | Ialloc _
+ | Iintop(Icheckbound) | Iintop_imm(Icheckbound, _) -> false
+ | Ispecific(Imultaddf | Imultsubf) -> true
+ | Ispecific _ -> false
+ | _ -> true
+
+(* Layout of the stack *)
+
+let num_stack_slots = [| 0; 0 |]
+let contains_calls = ref false
+
+(* Calling the assembler *)
+
+let assemble_file infile outfile =
+ Ccomp.command (Config.asm ^ " -o " ^
+ Filename.quote outfile ^ " " ^ Filename.quote infile)
+
+let init () = ()
diff --git a/asmcomp/power/reload.ml b/asmcomp/power/reload.ml
new file mode 100644
index 0000000000..98f747a81a
--- /dev/null
+++ b/asmcomp/power/reload.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Reloading for the PowerPC *)
+
+let fundecl f =
+ (new Reloadgen.reload_generic)#fundecl f
diff --git a/asmcomp/power/scheduling.ml b/asmcomp/power/scheduling.ml
new file mode 100644
index 0000000000..7adaa2eed3
--- /dev/null
+++ b/asmcomp/power/scheduling.ml
@@ -0,0 +1,61 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction scheduling for the Power PC *)
+
+open Arch
+open Mach
+
+class scheduler = object
+
+inherit Schedgen.scheduler_generic
+
+(* Latencies (in cycles). Based roughly on the "common model". *)
+
+method oper_latency = function
+ Ireload -> 2
+ | Iload(_, _) -> 2
+ | Iconst_float _ -> 2 (* turned into a load *)
+ | Iconst_symbol _ -> 1
+ | Iintop(Imul | Imulh) -> 9
+ | Iintop_imm(Imul, _) -> 5
+ | Iintop(Idiv | Imod) -> 36
+ | Iaddf | Isubf -> 4
+ | Imulf -> 5
+ | Idivf -> 33
+ | Ispecific(Imultaddf | Imultsubf) -> 5
+ | _ -> 1
+
+method reload_retaddr_latency = 12
+ (* If we can have that many cycles between the reloadretaddr and the
+ return, we can expect that the blr branch will be completely folded. *)
+
+(* Issue cycles. Rough approximations. *)
+
+method oper_issue_cycles = function
+ Iconst_float _ | Iconst_symbol _ -> 2
+ | Iload(_, Ibased(_, _)) -> 2
+ | Istore(_, Ibased(_, _), _) -> 2
+ | Ialloc _ -> 4
+ | Iintop(Imod) -> 40 (* assuming full stall *)
+ | Iintop(Icomp _) -> 4
+ | Iintop_imm(Icomp _, _) -> 4
+ | Ifloatofint -> 9
+ | Iintoffloat -> 4
+ | _ -> 1
+
+method reload_retaddr_issue_cycles = 3
+ (* load then stalling mtlr *)
+
+end
+
+let fundecl f = (new scheduler)#schedule_fundecl f
diff --git a/asmcomp/power/selection.ml b/asmcomp/power/selection.ml
new file mode 100644
index 0000000000..3e4536543c
--- /dev/null
+++ b/asmcomp/power/selection.ml
@@ -0,0 +1,91 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction selection for the Power PC processor *)
+
+open Cmm
+open Arch
+open Mach
+
+(* Recognition of addressing modes *)
+
+type addressing_expr =
+ Asymbol of string
+ | Alinear of expression
+ | Aadd of expression * expression
+
+let rec select_addr = function
+ Cconst_symbol s ->
+ (Asymbol s, 0)
+ | Cop((Caddi | Caddv | Cadda), [arg; Cconst_int m]) ->
+ let (a, n) = select_addr arg in (a, n + m)
+ | Cop((Caddi | Caddv | Cadda), [Cconst_int m; arg]) ->
+ let (a, n) = select_addr arg in (a, n + m)
+ | Cop((Caddi | Caddv | Cadda), [arg1; arg2]) ->
+ begin match (select_addr arg1, select_addr arg2) with
+ ((Alinear e1, n1), (Alinear e2, n2)) ->
+ (Aadd(e1, e2), n1 + n2)
+ | _ ->
+ (Aadd(arg1, arg2), 0)
+ end
+ | exp ->
+ (Alinear exp, 0)
+
+(* Instruction selection *)
+
+class selector = object (self)
+
+inherit Selectgen.selector_generic as super
+
+method is_immediate n = (n <= 32767) && (n >= -32768)
+
+method select_addressing chunk exp =
+ match select_addr exp with
+ (Asymbol s, d) ->
+ (Ibased(s, d), Ctuple [])
+ | (Alinear e, d) ->
+ (Iindexed d, e)
+ | (Aadd(e1, e2), d) ->
+ if d = 0
+ then (Iindexed2, Ctuple[e1; e2])
+ else (Iindexed d, Cop(Cadda, [e1; e2]))
+
+method! select_operation op args =
+ match (op, args) with
+ (* PowerPC does not support immediate operands for multiply high *)
+ (Cmulhi, _) -> (Iintop Imulh, args)
+ (* The and, or and xor instructions have a different range of immediate
+ operands than the other instructions *)
+ | (Cand, _) -> self#select_logical Iand args
+ | (Cor, _) -> self#select_logical Ior args
+ | (Cxor, _) -> self#select_logical Ixor args
+ (* Recognize mult-add and mult-sub instructions *)
+ | (Caddf, [Cop(Cmulf, [arg1; arg2]); arg3]) ->
+ (Ispecific Imultaddf, [arg1; arg2; arg3])
+ | (Caddf, [arg3; Cop(Cmulf, [arg1; arg2])]) ->
+ (Ispecific Imultaddf, [arg1; arg2; arg3])
+ | (Csubf, [Cop(Cmulf, [arg1; arg2]); arg3]) ->
+ (Ispecific Imultsubf, [arg1; arg2; arg3])
+ | _ ->
+ super#select_operation op args
+
+method select_logical op = function
+ [arg; Cconst_int n] when n >= 0 && n <= 0xFFFF ->
+ (Iintop_imm(op, n), [arg])
+ | [Cconst_int n; arg] when n >= 0 && n <= 0xFFFF ->
+ (Iintop_imm(op, n), [arg])
+ | args ->
+ (Iintop op, args)
+
+end
+
+let fundecl f = (new selector)#emit_fundecl f
diff --git a/asmcomp/printclambda.ml b/asmcomp/printclambda.ml
new file mode 100644
index 0000000000..b28d749e24
--- /dev/null
+++ b/asmcomp/printclambda.ml
@@ -0,0 +1,193 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+
+open Format
+open Asttypes
+open Clambda
+
+let rec structured_constant ppf = function
+ | Uconst_float x -> fprintf ppf "%F" x
+ | Uconst_int32 x -> fprintf ppf "%ldl" x
+ | Uconst_int64 x -> fprintf ppf "%LdL" x
+ | Uconst_nativeint x -> fprintf ppf "%ndn" x
+ | Uconst_block (tag, l) ->
+ fprintf ppf "block(%i" tag;
+ List.iter (fun u -> fprintf ppf ",%a" uconstant u) l;
+ fprintf ppf ")"
+ | Uconst_float_array [] ->
+ fprintf ppf "floatarray()"
+ | Uconst_float_array (f1 :: fl) ->
+ fprintf ppf "floatarray(%F" f1;
+ List.iter (fun f -> fprintf ppf ",%F" f) fl;
+ fprintf ppf ")"
+ | Uconst_string s -> fprintf ppf "%S" s
+
+and uconstant ppf = function
+ | Uconst_ref (s, c) ->
+ fprintf ppf "%S=%a" s structured_constant c
+ | Uconst_int i -> fprintf ppf "%i" i
+ | Uconst_ptr i -> fprintf ppf "%ia" i
+
+let rec lam ppf = function
+ | Uvar id ->
+ Ident.print ppf id
+ | Uconst c -> uconstant ppf c
+ | Udirect_apply(f, largs, _) ->
+ let lams ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ fprintf ppf "@[<2>(apply*@ %s %a)@]" f lams largs
+ | Ugeneric_apply(lfun, largs, _) ->
+ let lams ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ fprintf ppf "@[<2>(apply@ %a%a)@]" lam lfun lams largs
+ | Uclosure(clos, fv) ->
+ let idents ppf =
+ List.iter (fprintf ppf "@ %a" Ident.print)in
+ let one_fun ppf f =
+ fprintf ppf "@[<2>(fun@ %s@ %d @[<2>%a@]@ @[<2>%a@]@])"
+ f.label f.arity idents f.params lam f.body in
+ let funs ppf =
+ List.iter (fprintf ppf "@ %a" one_fun) in
+ let lams ppf =
+ List.iter (fprintf ppf "@ %a" lam) in
+ fprintf ppf "@[<2>(closure@ %a %a)@]" funs clos lams fv
+ | Uoffset(l,i) -> fprintf ppf "@[<2>(offset %a %d)@]" lam l i
+ | Ulet(id, arg, body) ->
+ let rec letbody ul = match ul with
+ | Ulet(id, arg, body) ->
+ fprintf ppf "@ @[<2>%a@ %a@]" Ident.print id lam arg;
+ letbody body
+ | _ -> ul in
+ fprintf ppf "@[<2>(let@ @[<hv 1>(@[<2>%a@ %a@]" Ident.print id lam arg;
+ let expr = letbody body in
+ fprintf ppf ")@]@ %a)@]" lam expr
+ | Uletrec(id_arg_list, body) ->
+ let bindings ppf id_arg_list =
+ let spc = ref false in
+ List.iter
+ (fun (id, l) ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<2>%a@ %a@]" Ident.print id lam l)
+ id_arg_list in
+ fprintf ppf
+ "@[<2>(letrec@ (@[<hv 1>%a@])@ %a)@]" bindings id_arg_list lam body
+ | Uprim(prim, largs, _) ->
+ let lams ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ fprintf ppf "@[<2>(%a%a)@]" Printlambda.primitive prim lams largs
+ | Uswitch(larg, sw) ->
+ let print_case tag index i ppf =
+ for j = 0 to Array.length index - 1 do
+ if index.(j) = i then fprintf ppf "case %s %i:" tag j
+ done in
+ let print_cases tag index cases ppf =
+ for i = 0 to Array.length cases - 1 do
+ fprintf ppf "@ @[<2>%t@ %a@]"
+ (print_case tag index i) sequence cases.(i)
+ done in
+ let switch ppf sw =
+ print_cases "int" sw.us_index_consts sw.us_actions_consts ppf ;
+ print_cases "tag" sw.us_index_blocks sw.us_actions_blocks ppf in
+ fprintf ppf
+ "@[<v 0>@[<2>(switch@ %a@ @]%a)@]"
+ lam larg switch sw
+ | Ustringswitch(larg,sw,d) ->
+ let switch ppf sw =
+ let spc = ref false in
+ List.iter
+ (fun (s,l) ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<hv 1>case \"%s\":@ %a@]"
+ (String.escaped s) lam l)
+ sw ;
+ begin match d with
+ | Some d ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<hv 1>default:@ %a@]" lam d
+ | None -> ()
+ end in
+ fprintf ppf
+ "@[<1>(switch %a@ @[<v 0>%a@])@]" lam larg switch sw
+ | Ustaticfail (i, ls) ->
+ let lams ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ fprintf ppf "@[<2>(exit@ %d%a)@]" i lams ls;
+ | Ucatch(i, vars, lbody, lhandler) ->
+ fprintf ppf "@[<2>(catch@ %a@;<1 -1>with (%d%a)@ %a)@]"
+ lam lbody i
+ (fun ppf vars -> match vars with
+ | [] -> ()
+ | _ ->
+ List.iter
+ (fun x -> fprintf ppf " %a" Ident.print x)
+ vars)
+ vars
+ lam lhandler
+ | Utrywith(lbody, param, lhandler) ->
+ fprintf ppf "@[<2>(try@ %a@;<1 -1>with %a@ %a)@]"
+ lam lbody Ident.print param lam lhandler
+ | Uifthenelse(lcond, lif, lelse) ->
+ fprintf ppf "@[<2>(if@ %a@ %a@ %a)@]" lam lcond lam lif lam lelse
+ | Usequence(l1, l2) ->
+ fprintf ppf "@[<2>(seq@ %a@ %a)@]" lam l1 sequence l2
+ | Uwhile(lcond, lbody) ->
+ fprintf ppf "@[<2>(while@ %a@ %a)@]" lam lcond lam lbody
+ | Ufor(param, lo, hi, dir, body) ->
+ fprintf ppf "@[<2>(for %a@ %a@ %s@ %a@ %a)@]"
+ Ident.print param lam lo
+ (match dir with Upto -> "to" | Downto -> "downto")
+ lam hi lam body
+ | Uassign(id, expr) ->
+ fprintf ppf "@[<2>(assign@ %a@ %a)@]" Ident.print id lam expr
+ | Usend (k, met, obj, largs, _) ->
+ let args ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ let kind =
+ if k = Lambda.Self then "self"
+ else if k = Lambda.Cached then "cache"
+ else "" in
+ fprintf ppf "@[<2>(send%s@ %a@ %a%a)@]" kind lam obj lam met args largs
+
+and sequence ppf ulam = match ulam with
+ | Usequence(l1, l2) ->
+ fprintf ppf "%a@ %a" sequence l1 sequence l2
+ | _ -> lam ppf ulam
+
+let clambda ppf ulam =
+ fprintf ppf "%a@." lam ulam
+
+
+let rec approx ppf = function
+ Value_closure(fundesc, a) ->
+ Format.fprintf ppf "@[<2>function %s@ arity %i"
+ fundesc.fun_label fundesc.fun_arity;
+ if fundesc.fun_closed then begin
+ Format.fprintf ppf "@ (closed)"
+ end;
+ if fundesc.fun_inline <> None then begin
+ Format.fprintf ppf "@ (inline)"
+ end;
+ Format.fprintf ppf "@ -> @ %a@]" approx a
+ | Value_tuple a ->
+ let tuple ppf a =
+ for i = 0 to Array.length a - 1 do
+ if i > 0 then Format.fprintf ppf ";@ ";
+ Format.fprintf ppf "%i: %a" i approx a.(i)
+ done in
+ Format.fprintf ppf "@[<hov 1>(%a)@]" tuple a
+ | Value_unknown ->
+ Format.fprintf ppf "_"
+ | Value_const c ->
+ fprintf ppf "@[const(%a)@]" uconstant c
+ | Value_global_field (s, i) ->
+ fprintf ppf "@[global(%s,%i)@]" s i
diff --git a/asmcomp/printclambda.mli b/asmcomp/printclambda.mli
new file mode 100644
index 0000000000..d138b958ac
--- /dev/null
+++ b/asmcomp/printclambda.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Clambda
+open Format
+
+val clambda: formatter -> ulambda -> unit
+val approx: formatter -> value_approximation -> unit
+val structured_constant: formatter -> ustructured_constant -> unit
diff --git a/asmcomp/printcmm.ml b/asmcomp/printcmm.ml
new file mode 100644
index 0000000000..e13bff04bc
--- /dev/null
+++ b/asmcomp/printcmm.ml
@@ -0,0 +1,205 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pretty-printing of C-- code *)
+
+open Format
+open Cmm
+
+let machtype_component ppf = function
+ | Val -> fprintf ppf "val"
+ | Addr -> fprintf ppf "addr"
+ | Int -> fprintf ppf "int"
+ | Float -> fprintf ppf "float"
+
+let machtype ppf mty =
+ match Array.length mty with
+ | 0 -> fprintf ppf "unit"
+ | n -> machtype_component ppf mty.(0);
+ for i = 1 to n-1 do
+ fprintf ppf "*%a" machtype_component mty.(i)
+ done
+
+let comparison = function
+ | Ceq -> "=="
+ | Cne -> "!="
+ | Clt -> "<"
+ | Cle -> "<="
+ | Cgt -> ">"
+ | Cge -> ">="
+
+let chunk = function
+ | Byte_unsigned -> "unsigned int8"
+ | Byte_signed -> "signed int8"
+ | Sixteen_unsigned -> "unsigned int16"
+ | Sixteen_signed -> "signed int16"
+ | Thirtytwo_unsigned -> "unsigned int32"
+ | Thirtytwo_signed -> "signed int32"
+ | Word_int -> "int"
+ | Word_val -> "val"
+ | Single -> "float32"
+ | Double -> "float64"
+ | Double_u -> "float64u"
+
+let operation = function
+ | Capply(ty, d) -> "app" ^ Debuginfo.to_string d
+ | Cextcall(lbl, ty, alloc, d) ->
+ Printf.sprintf "extcall \"%s\"%s" lbl (Debuginfo.to_string d)
+ | Cload c -> Printf.sprintf "load %s" (chunk c)
+ | Calloc -> "alloc"
+ | Cstore c -> Printf.sprintf "store %s" (chunk c)
+ | Caddi -> "+"
+ | Csubi -> "-"
+ | Cmuli -> "*"
+ | Cmulhi -> "*h"
+ | Cdivi -> "/"
+ | Cmodi -> "mod"
+ | Cand -> "and"
+ | Cor -> "or"
+ | Cxor -> "xor"
+ | Clsl -> "<<"
+ | Clsr -> ">>u"
+ | Casr -> ">>s"
+ | Ccmpi c -> comparison c
+ | Caddv -> "+v"
+ | Cadda -> "+a"
+ | Ccmpa c -> Printf.sprintf "%sa" (comparison c)
+ | Cnegf -> "~f"
+ | Cabsf -> "absf"
+ | Caddf -> "+f"
+ | Csubf -> "-f"
+ | Cmulf -> "*f"
+ | Cdivf -> "/f"
+ | Cfloatofint -> "floatofint"
+ | Cintoffloat -> "intoffloat"
+ | Ccmpf c -> Printf.sprintf "%sf" (comparison c)
+ | Craise (k, d) -> Lambda.raise_kind k ^ Debuginfo.to_string d
+ | Ccheckbound d -> "checkbound" ^ Debuginfo.to_string d
+
+let rec expr ppf = function
+ | Cconst_int n -> fprintf ppf "%i" n
+ | Cconst_natint n | Cconst_blockheader n ->
+ fprintf ppf "%s" (Nativeint.to_string n)
+ | Cconst_float n -> fprintf ppf "%F" n
+ | Cconst_symbol s -> fprintf ppf "\"%s\"" s
+ | Cconst_pointer n -> fprintf ppf "%ia" n
+ | Cconst_natpointer n -> fprintf ppf "%sa" (Nativeint.to_string n)
+ | Cvar id -> Ident.print ppf id
+ | Clet(id, def, (Clet(_, _, _) as body)) ->
+ let print_binding id ppf def =
+ fprintf ppf "@[<2>%a@ %a@]" Ident.print id expr def in
+ let rec in_part ppf = function
+ | Clet(id, def, body) ->
+ fprintf ppf "@ %a" (print_binding id) def;
+ in_part ppf body
+ | exp -> exp in
+ fprintf ppf "@[<2>(let@ @[<1>(%a" (print_binding id) def;
+ let exp = in_part ppf body in
+ fprintf ppf ")@]@ %a)@]" sequence exp
+ | Clet(id, def, body) ->
+ fprintf ppf
+ "@[<2>(let@ @[<2>%a@ %a@]@ %a)@]"
+ Ident.print id expr def sequence body
+ | Cassign(id, exp) ->
+ fprintf ppf "@[<2>(assign @[<2>%a@ %a@])@]" Ident.print id expr exp
+ | Ctuple el ->
+ let tuple ppf el =
+ let first = ref true in
+ List.iter
+ (fun e ->
+ if !first then first := false else fprintf ppf "@ ";
+ expr ppf e)
+ el in
+ fprintf ppf "@[<1>[%a]@]" tuple el
+ | Cop(op, el) ->
+ fprintf ppf "@[<2>(%s" (operation op);
+ List.iter (fun e -> fprintf ppf "@ %a" expr e) el;
+ begin match op with
+ | Capply (mty, _) -> fprintf ppf "@ %a" machtype mty
+ | Cextcall(_, mty, _, _) -> fprintf ppf "@ %a" machtype mty
+ | _ -> ()
+ end;
+ fprintf ppf ")@]"
+ | Csequence(e1, e2) ->
+ fprintf ppf "@[<2>(seq@ %a@ %a)@]" sequence e1 sequence e2
+ | Cifthenelse(e1, e2, e3) ->
+ fprintf ppf "@[<2>(if@ %a@ %a@ %a)@]" expr e1 expr e2 expr e3
+ | Cswitch(e1, index, cases) ->
+ let print_case i ppf =
+ for j = 0 to Array.length index - 1 do
+ if index.(j) = i then fprintf ppf "case %i:" j
+ done in
+ let print_cases ppf =
+ for i = 0 to Array.length cases - 1 do
+ fprintf ppf "@ @[<2>%t@ %a@]" (print_case i) sequence cases.(i)
+ done in
+ fprintf ppf "@[<v 0>@[<2>(switch@ %a@ @]%t)@]" expr e1 print_cases
+ | Cloop e ->
+ fprintf ppf "@[<2>(loop@ %a)@]" sequence e
+ | Ccatch(i, ids, e1, e2) ->
+ fprintf ppf
+ "@[<2>(catch@ %a@;<1 -2>with(%d%a)@ %a)@]"
+ sequence e1 i
+ (fun ppf ids ->
+ List.iter
+ (fun id -> fprintf ppf " %a" Ident.print id)
+ ids) ids
+ sequence e2
+ | Cexit (i, el) ->
+ fprintf ppf "@[<2>(exit %d" i ;
+ List.iter (fun e -> fprintf ppf "@ %a" expr e) el;
+ fprintf ppf ")@]"
+ | Ctrywith(e1, id, e2) ->
+ fprintf ppf "@[<2>(try@ %a@;<1 -2>with@ %a@ %a)@]"
+ sequence e1 Ident.print id sequence e2
+
+and sequence ppf = function
+ | Csequence(e1, e2) -> fprintf ppf "%a@ %a" sequence e1 sequence e2
+ | e -> expression ppf e
+
+and expression ppf e = fprintf ppf "%a" expr e
+
+let fundecl ppf f =
+ let print_cases ppf cases =
+ let first = ref true in
+ List.iter
+ (fun (id, ty) ->
+ if !first then first := false else fprintf ppf "@ ";
+ fprintf ppf "%a: %a" Ident.print id machtype ty)
+ cases in
+ fprintf ppf "@[<1>(function%s %s@;<1 4>@[<1>(%a)@]@ @[%a@])@]@."
+ (Debuginfo.to_string f.fun_dbg) f.fun_name
+ print_cases f.fun_args sequence f.fun_body
+
+let data_item ppf = function
+ | Cdefine_symbol s -> fprintf ppf "\"%s\":" s
+ | Cdefine_label l -> fprintf ppf "L%i:" l
+ | Cglobal_symbol s -> fprintf ppf "global \"%s\"" s
+ | Cint8 n -> fprintf ppf "byte %i" n
+ | Cint16 n -> fprintf ppf "int16 %i" n
+ | Cint32 n -> fprintf ppf "int32 %s" (Nativeint.to_string n)
+ | Cint n -> fprintf ppf "int %s" (Nativeint.to_string n)
+ | Csingle f -> fprintf ppf "single %F" f
+ | Cdouble f -> fprintf ppf "double %F" f
+ | Csymbol_address s -> fprintf ppf "addr \"%s\"" s
+ | Clabel_address l -> fprintf ppf "addr L%i" l
+ | Cstring s -> fprintf ppf "string \"%s\"" s
+ | Cskip n -> fprintf ppf "skip %i" n
+ | Calign n -> fprintf ppf "align %i" n
+
+let data ppf dl =
+ let items ppf = List.iter (fun d -> fprintf ppf "@ %a" data_item d) dl in
+ fprintf ppf "@[<hv 1>(data%t)@]" items
+
+let phrase ppf = function
+ | Cfunction f -> fundecl ppf f
+ | Cdata dl -> data ppf dl
diff --git a/asmcomp/printcmm.mli b/asmcomp/printcmm.mli
new file mode 100644
index 0000000000..1c97c4a001
--- /dev/null
+++ b/asmcomp/printcmm.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pretty-printing of C-- code *)
+
+open Format
+
+val machtype_component : formatter -> Cmm.machtype_component -> unit
+val machtype : formatter -> Cmm.machtype_component array -> unit
+val comparison : Cmm.comparison -> string
+val chunk : Cmm.memory_chunk -> string
+val operation : Cmm.operation -> string
+val expression : formatter -> Cmm.expression -> unit
+val fundecl : formatter -> Cmm.fundecl -> unit
+val data : formatter -> Cmm.data_item list -> unit
+val phrase : formatter -> Cmm.phrase -> unit
diff --git a/asmcomp/printlinear.ml b/asmcomp/printlinear.ml
new file mode 100644
index 0000000000..df58c5cc59
--- /dev/null
+++ b/asmcomp/printlinear.ml
@@ -0,0 +1,80 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pretty-printing of linearized machine code *)
+
+open Format
+open Mach
+open Printmach
+open Linearize
+
+let label ppf l =
+ Format.fprintf ppf "L%i" l
+
+let instr ppf i =
+ begin match i.desc with
+ | Lend -> ()
+ | Lop op ->
+ begin match op with
+ | Ialloc _ | Icall_ind | Icall_imm _ | Iextcall(_, _) ->
+ fprintf ppf "@[<1>{%a}@]@," regsetaddr i.live
+ | _ -> ()
+ end;
+ operation op i.arg ppf i.res
+ | Lreloadretaddr ->
+ fprintf ppf "reload retaddr"
+ | Lreturn ->
+ fprintf ppf "return %a" regs i.arg
+ | Llabel lbl ->
+ fprintf ppf "%a:" label lbl
+ | Lbranch lbl ->
+ fprintf ppf "goto %a" label lbl
+ | Lcondbranch(tst, lbl) ->
+ fprintf ppf "if %a goto %a" (test tst) i.arg label lbl
+ | Lcondbranch3(lbl0, lbl1, lbl2) ->
+ fprintf ppf "switch3 %a" reg i.arg.(0);
+ let case n = function
+ | None -> ()
+ | Some lbl ->
+ fprintf ppf "@,case %i: goto %a" n label lbl in
+ case 0 lbl0; case 1 lbl1; case 2 lbl2;
+ fprintf ppf "@,endswitch"
+ | Lswitch lblv ->
+ fprintf ppf "switch %a" reg i.arg.(0);
+ for i = 0 to Array.length lblv - 1 do
+ fprintf ppf "case %i: goto %a" i label lblv.(i)
+ done;
+ fprintf ppf "@,endswitch"
+ | Lsetuptrap lbl ->
+ fprintf ppf "setup trap %a" label lbl
+ | Lpushtrap ->
+ fprintf ppf "push trap"
+ | Lpoptrap ->
+ fprintf ppf "pop trap"
+ | Lraise k ->
+ fprintf ppf "%s %a" (Lambda.raise_kind k) reg i.arg.(0)
+ end;
+ if not (Debuginfo.is_none i.dbg) then
+ fprintf ppf " %s" (Debuginfo.to_string i.dbg)
+
+let rec all_instr ppf i =
+ match i.desc with
+ | Lend -> ()
+ | _ -> fprintf ppf "%a@,%a" instr i all_instr i.next
+
+let fundecl ppf f =
+ let dbg =
+ if Debuginfo.is_none f.fun_dbg then
+ ""
+ else
+ " " ^ Debuginfo.to_string f.fun_dbg in
+ fprintf ppf "@[<v 2>%s:%s@,%a@]" f.fun_name dbg all_instr f.fun_body
diff --git a/asmcomp/printlinear.mli b/asmcomp/printlinear.mli
new file mode 100644
index 0000000000..68eda9c1d3
--- /dev/null
+++ b/asmcomp/printlinear.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pretty-printing of linearized machine code *)
+
+open Format
+open Linearize
+
+val instr: formatter -> instruction -> unit
+val fundecl: formatter -> fundecl -> unit
diff --git a/asmcomp/printmach.ml b/asmcomp/printmach.ml
new file mode 100644
index 0000000000..7c4679f8de
--- /dev/null
+++ b/asmcomp/printmach.ml
@@ -0,0 +1,229 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pretty-printing of pseudo machine code *)
+
+open Format
+open Cmm
+open Reg
+open Mach
+
+let reg ppf r =
+ if not (Reg.anonymous r) then
+ fprintf ppf "%s" (Reg.name r)
+ else
+ fprintf ppf "%s"
+ (match r.typ with Val -> "V" | Addr -> "A" | Int -> "I" | Float -> "F");
+ fprintf ppf "/%i" r.stamp;
+ begin match r.loc with
+ | Unknown -> ()
+ | Reg r ->
+ fprintf ppf "[%s]" (Proc.register_name r)
+ | Stack(Local s) ->
+ fprintf ppf "[s%i]" s
+ | Stack(Incoming s) ->
+ fprintf ppf "[si%i]" s
+ | Stack(Outgoing s) ->
+ fprintf ppf "[so%i]" s
+ end
+
+let regs ppf v =
+ match Array.length v with
+ | 0 -> ()
+ | 1 -> reg ppf v.(0)
+ | n -> reg ppf v.(0);
+ for i = 1 to n-1 do fprintf ppf " %a" reg v.(i) done
+
+let regset ppf s =
+ let first = ref true in
+ Reg.Set.iter
+ (fun r ->
+ if !first then begin first := false; fprintf ppf "%a" reg r end
+ else fprintf ppf "@ %a" reg r)
+ s
+
+let regsetaddr ppf s =
+ let first = ref true in
+ Reg.Set.iter
+ (fun r ->
+ if !first then begin first := false; fprintf ppf "%a" reg r end
+ else fprintf ppf "@ %a" reg r;
+ match r.typ with
+ | Val -> fprintf ppf "*"
+ | Addr -> fprintf ppf "!"
+ | _ -> ())
+ s
+
+let intcomp = function
+ | Isigned c -> Printf.sprintf " %ss " (Printcmm.comparison c)
+ | Iunsigned c -> Printf.sprintf " %su " (Printcmm.comparison c)
+
+let floatcomp c =
+ Printf.sprintf " %sf " (Printcmm.comparison c)
+
+let intop = function
+ | Iadd -> " + "
+ | Isub -> " - "
+ | Imul -> " * "
+ | Imulh -> " *h "
+ | Idiv -> " div "
+ | Imod -> " mod "
+ | Iand -> " & "
+ | Ior -> " | "
+ | Ixor -> " ^ "
+ | Ilsl -> " << "
+ | Ilsr -> " >>u "
+ | Iasr -> " >>s "
+ | Icomp cmp -> intcomp cmp
+ | Icheckbound -> " check > "
+
+let test tst ppf arg =
+ match tst with
+ | Itruetest -> reg ppf arg.(0)
+ | Ifalsetest -> fprintf ppf "not %a" reg arg.(0)
+ | Iinttest cmp -> fprintf ppf "%a%s%a" reg arg.(0) (intcomp cmp) reg arg.(1)
+ | Iinttest_imm(cmp, n) -> fprintf ppf "%a%s%i" reg arg.(0) (intcomp cmp) n
+ | Ifloattest(cmp, neg) ->
+ fprintf ppf "%s%a%s%a"
+ (if neg then "not " else "")
+ reg arg.(0) (floatcomp cmp) reg arg.(1)
+ | Ieventest -> fprintf ppf "%a & 1 == 0" reg arg.(0)
+ | Ioddtest -> fprintf ppf "%a & 1 == 1" reg arg.(0)
+
+let print_live = ref false
+
+let operation op arg ppf res =
+ if Array.length res > 0 then fprintf ppf "%a := " regs res;
+ match op with
+ | Imove -> regs ppf arg
+ | Ispill -> fprintf ppf "%a (spill)" regs arg
+ | Ireload -> fprintf ppf "%a (reload)" regs arg
+ | Iconst_int n
+ | Iconst_blockheader n -> fprintf ppf "%s" (Nativeint.to_string n)
+ | Iconst_float f -> fprintf ppf "%F" f
+ | Iconst_symbol s -> fprintf ppf "\"%s\"" s
+ | Icall_ind -> fprintf ppf "call %a" regs arg
+ | Icall_imm lbl -> fprintf ppf "call \"%s\" %a" lbl regs arg
+ | Itailcall_ind -> fprintf ppf "tailcall %a" regs arg
+ | Itailcall_imm lbl -> fprintf ppf "tailcall \"%s\" %a" lbl regs arg
+ | Iextcall(lbl, alloc) ->
+ fprintf ppf "extcall \"%s\" %a%s" lbl regs arg
+ (if alloc then "" else " (noalloc)")
+ | Istackoffset n ->
+ fprintf ppf "offset stack %i" n
+ | Iload(chunk, addr) ->
+ fprintf ppf "%s[%a]"
+ (Printcmm.chunk chunk) (Arch.print_addressing reg addr) arg
+ | Istore(chunk, addr, is_assign) ->
+ fprintf ppf "%s[%a] := %a %s"
+ (Printcmm.chunk chunk)
+ (Arch.print_addressing reg addr)
+ (Array.sub arg 1 (Array.length arg - 1))
+ reg arg.(0)
+ (if is_assign then "(assign)" else "(init)")
+ | Ialloc n -> fprintf ppf "alloc %i" n
+ | Iintop(op) -> fprintf ppf "%a%s%a" reg arg.(0) (intop op) reg arg.(1)
+ | Iintop_imm(op, n) -> fprintf ppf "%a%s%i" reg arg.(0) (intop op) n
+ | Inegf -> fprintf ppf "-f %a" reg arg.(0)
+ | Iabsf -> fprintf ppf "absf %a" reg arg.(0)
+ | Iaddf -> fprintf ppf "%a +f %a" reg arg.(0) reg arg.(1)
+ | Isubf -> fprintf ppf "%a -f %a" reg arg.(0) reg arg.(1)
+ | Imulf -> fprintf ppf "%a *f %a" reg arg.(0) reg arg.(1)
+ | Idivf -> fprintf ppf "%a /f %a" reg arg.(0) reg arg.(1)
+ | Ifloatofint -> fprintf ppf "floatofint %a" reg arg.(0)
+ | Iintoffloat -> fprintf ppf "intoffloat %a" reg arg.(0)
+ | Ispecific op ->
+ Arch.print_specific_operation reg op ppf arg
+
+let rec instr ppf i =
+ if !print_live then begin
+ fprintf ppf "@[<1>{%a" regsetaddr i.live;
+ if Array.length i.arg > 0 then fprintf ppf "@ +@ %a" regs i.arg;
+ fprintf ppf "}@]@,";
+ end;
+ begin match i.desc with
+ | Iend -> ()
+ | Iop op ->
+ operation op i.arg ppf i.res
+ | Ireturn ->
+ fprintf ppf "return %a" regs i.arg
+ | Iifthenelse(tst, ifso, ifnot) ->
+ fprintf ppf "@[<v 2>if %a then@,%a" (test tst) i.arg instr ifso;
+ begin match ifnot.desc with
+ | Iend -> ()
+ | _ -> fprintf ppf "@;<0 -2>else@,%a" instr ifnot
+ end;
+ fprintf ppf "@;<0 -2>endif@]"
+ | Iswitch(index, cases) ->
+ fprintf ppf "switch %a" reg i.arg.(0);
+ for i = 0 to Array.length cases - 1 do
+ fprintf ppf "@,@[<v 2>@[";
+ for j = 0 to Array.length index - 1 do
+ if index.(j) = i then fprintf ppf "case %i:@," j
+ done;
+ fprintf ppf "@]@,%a@]" instr cases.(i)
+ done;
+ fprintf ppf "@,endswitch"
+ | Iloop(body) ->
+ fprintf ppf "@[<v 2>loop@,%a@;<0 -2>endloop@]" instr body
+ | Icatch(i, body, handler) ->
+ fprintf
+ ppf "@[<v 2>catch@,%a@;<0 -2>with(%d)@,%a@;<0 -2>endcatch@]"
+ instr body i instr handler
+ | Iexit i ->
+ fprintf ppf "exit(%d)" i
+ | Itrywith(body, handler) ->
+ fprintf ppf "@[<v 2>try@,%a@;<0 -2>with@,%a@;<0 -2>endtry@]"
+ instr body instr handler
+ | Iraise k ->
+ fprintf ppf "%s %a" (Lambda.raise_kind k) reg i.arg.(0)
+ end;
+ if not (Debuginfo.is_none i.dbg) then
+ fprintf ppf "%s" (Debuginfo.to_string i.dbg);
+ begin match i.next.desc with
+ Iend -> ()
+ | _ -> fprintf ppf "@,%a" instr i.next
+ end
+
+let fundecl ppf f =
+ let dbg =
+ if Debuginfo.is_none f.fun_dbg then
+ ""
+ else
+ " " ^ Debuginfo.to_string f.fun_dbg in
+ fprintf ppf "@[<v 2>%s(%a)%s@,%a@]"
+ f.fun_name regs f.fun_args dbg instr f.fun_body
+
+let phase msg ppf f =
+ fprintf ppf "*** %s@.%a@." msg fundecl f
+
+let interference ppf r =
+ let interf ppf =
+ List.iter
+ (fun r -> fprintf ppf "@ %a" reg r)
+ r.interf in
+ fprintf ppf "@[<2>%a:%t@]@." reg r interf
+
+let interferences ppf () =
+ fprintf ppf "*** Interferences@.";
+ List.iter (interference ppf) (Reg.all_registers())
+
+let preference ppf r =
+ let prefs ppf =
+ List.iter
+ (fun (r, w) -> fprintf ppf "@ %a weight %i" reg r w)
+ r.prefer in
+ fprintf ppf "@[<2>%a: %t@]@." reg r prefs
+
+let preferences ppf () =
+ fprintf ppf "*** Preferences@.";
+ List.iter (preference ppf) (Reg.all_registers())
diff --git a/asmcomp/printmach.mli b/asmcomp/printmach.mli
new file mode 100644
index 0000000000..bfb0dbefab
--- /dev/null
+++ b/asmcomp/printmach.mli
@@ -0,0 +1,29 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pretty-printing of pseudo machine code *)
+
+open Format
+
+val reg: formatter -> Reg.t -> unit
+val regs: formatter -> Reg.t array -> unit
+val regset: formatter -> Reg.Set.t -> unit
+val regsetaddr: formatter -> Reg.Set.t -> unit
+val operation: Mach.operation -> Reg.t array -> formatter -> Reg.t array -> unit
+val test: Mach.test -> formatter -> Reg.t array -> unit
+val instr: formatter -> Mach.instruction -> unit
+val fundecl: formatter -> Mach.fundecl -> unit
+val phase: string -> formatter -> Mach.fundecl -> unit
+val interferences: formatter -> unit -> unit
+val preferences: formatter -> unit -> unit
+
+val print_live: bool ref
diff --git a/asmcomp/proc.mli b/asmcomp/proc.mli
new file mode 100644
index 0000000000..c7bca639a6
--- /dev/null
+++ b/asmcomp/proc.mli
@@ -0,0 +1,62 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Processor descriptions *)
+
+(* Instruction selection *)
+val word_addressed: bool
+
+(* Registers available for register allocation *)
+val num_register_classes: int
+val register_class: Reg.t -> int
+val num_available_registers: int array
+val first_available_register: int array
+val register_name: int -> string
+val phys_reg: int -> Reg.t
+val rotate_registers: bool
+
+(* Calling conventions *)
+val loc_arguments: Reg.t array -> Reg.t array * int
+val loc_results: Reg.t array -> Reg.t array
+val loc_parameters: Reg.t array -> Reg.t array
+(* For argument number [n] split across multiple registers, the target-specific
+ implementation of [loc_external_arguments] must return [regs] such that
+ [regs.(n).(0)] is to hold the least significant part of the value.
+ (All that matters for the input to [loc_external_arguments] is the pattern
+ of lengths and register types of the various supplied arrays.) *)
+val loc_external_arguments: Reg.t array array -> Reg.t array array * int
+val loc_external_results: Reg.t array -> Reg.t array
+val loc_exn_bucket: Reg.t
+
+(* Maximal register pressures for pre-spilling *)
+val safe_register_pressure: Mach.operation -> int
+val max_register_pressure: Mach.operation -> int array
+
+(* Registers destroyed by operations *)
+val destroyed_at_oper: Mach.instruction_desc -> Reg.t array
+val destroyed_at_raise: Reg.t array
+
+(* Volatile registers: those that change value when read *)
+val regs_are_volatile: Reg.t array -> bool
+
+(* Pure operations *)
+val op_is_pure: Mach.operation -> bool
+
+(* Info for laying out the stack frame *)
+val num_stack_slots: int array
+val contains_calls: bool ref
+
+(* Calling the assembler *)
+val assemble_file: string -> string -> int
+
+(* Called before translating a fundecl. *)
+val init : unit -> unit
diff --git a/asmcomp/reg.ml b/asmcomp/reg.ml
new file mode 100644
index 0000000000..064be4dbb7
--- /dev/null
+++ b/asmcomp/reg.ml
@@ -0,0 +1,197 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Cmm
+
+module Raw_name = struct
+ type t =
+ | Anon
+ | R
+ | Ident of Ident.t
+
+ let create_from_ident ident = Ident ident
+
+ let to_string t =
+ match t with
+ | Anon -> None
+ | R -> Some "R"
+ | Ident ident ->
+ let name = Ident.name ident in
+ if String.length name <= 0 then None else Some name
+end
+
+type t =
+ { mutable raw_name: Raw_name.t;
+ stamp: int;
+ mutable typ: Cmm.machtype_component;
+ mutable loc: location;
+ mutable spill: bool;
+ mutable part: int option;
+ mutable interf: t list;
+ mutable prefer: (t * int) list;
+ mutable degree: int;
+ mutable spill_cost: int;
+ mutable visited: bool }
+
+and location =
+ Unknown
+ | Reg of int
+ | Stack of stack_location
+
+and stack_location =
+ Local of int
+ | Incoming of int
+ | Outgoing of int
+
+type reg = t
+
+let dummy =
+ { raw_name = Raw_name.Anon; stamp = 0; typ = Int; loc = Unknown;
+ spill = false; interf = []; prefer = []; degree = 0; spill_cost = 0;
+ visited = false; part = None;
+ }
+
+let currstamp = ref 0
+let reg_list = ref([] : t list)
+
+let create ty =
+ let r = { raw_name = Raw_name.Anon; stamp = !currstamp; typ = ty;
+ loc = Unknown; spill = false; interf = []; prefer = []; degree = 0;
+ spill_cost = 0; visited = false; part = None; } in
+ reg_list := r :: !reg_list;
+ incr currstamp;
+ r
+
+let createv tyv =
+ let n = Array.length tyv in
+ let rv = Array.make n dummy in
+ for i = 0 to n-1 do rv.(i) <- create tyv.(i) done;
+ rv
+
+let createv_like rv =
+ let n = Array.length rv in
+ let rv' = Array.make n dummy in
+ for i = 0 to n-1 do rv'.(i) <- create rv.(i).typ done;
+ rv'
+
+let clone r =
+ let nr = create r.typ in
+ nr.raw_name <- r.raw_name;
+ nr
+
+let at_location ty loc =
+ let r = { raw_name = Raw_name.R; stamp = !currstamp; typ = ty; loc;
+ spill = false; interf = []; prefer = []; degree = 0;
+ spill_cost = 0; visited = false; part = None; } in
+ incr currstamp;
+ r
+
+let anonymous t =
+ match Raw_name.to_string t.raw_name with
+ | None -> true
+ | Some _raw_name -> false
+
+let name t =
+ match Raw_name.to_string t.raw_name with
+ | None -> ""
+ | Some raw_name ->
+ let with_spilled =
+ if t.spill then
+ "spilled-" ^ raw_name
+ else
+ raw_name
+ in
+ match t.part with
+ | None -> with_spilled
+ | Some part -> with_spilled ^ "#" ^ string_of_int part
+
+let first_virtual_reg_stamp = ref (-1)
+
+let reset() =
+ (* When reset() is called for the first time, the current stamp reflects
+ all hard pseudo-registers that have been allocated by Proc, so
+ remember it and use it as the base stamp for allocating
+ soft pseudo-registers *)
+ if !first_virtual_reg_stamp = -1 then first_virtual_reg_stamp := !currstamp;
+ currstamp := !first_virtual_reg_stamp;
+ reg_list := []
+
+let all_registers() = !reg_list
+let num_registers() = !currstamp
+
+let reinit_reg r =
+ r.loc <- Unknown;
+ r.interf <- [];
+ r.prefer <- [];
+ r.degree <- 0;
+ (* Preserve the very high spill costs introduced by the reloading pass *)
+ if r.spill_cost >= 100000
+ then r.spill_cost <- 100000
+ else r.spill_cost <- 0
+
+let reinit() =
+ List.iter reinit_reg !reg_list
+
+module RegOrder =
+ struct
+ type t = reg
+ let compare r1 r2 = r1.stamp - r2.stamp
+ end
+
+module Set = Set.Make(RegOrder)
+module Map = Map.Make(RegOrder)
+
+let add_set_array s v =
+ match Array.length v with
+ 0 -> s
+ | 1 -> Set.add v.(0) s
+ | n -> let rec add_all i =
+ if i >= n then s else Set.add v.(i) (add_all(i+1))
+ in add_all 0
+
+let diff_set_array s v =
+ match Array.length v with
+ 0 -> s
+ | 1 -> Set.remove v.(0) s
+ | n -> let rec remove_all i =
+ if i >= n then s else Set.remove v.(i) (remove_all(i+1))
+ in remove_all 0
+
+let inter_set_array s v =
+ match Array.length v with
+ 0 -> Set.empty
+ | 1 -> if Set.mem v.(0) s
+ then Set.add v.(0) Set.empty
+ else Set.empty
+ | n -> let rec inter_all i =
+ if i >= n then Set.empty
+ else if Set.mem v.(i) s then Set.add v.(i) (inter_all(i+1))
+ else inter_all(i+1)
+ in inter_all 0
+
+let disjoint_set_array s v =
+ match Array.length v with
+ 0 -> true
+ | 1 -> not (Set.mem v.(0) s)
+ | n -> let rec disjoint_all i =
+ if i >= n then true
+ else if Set.mem v.(i) s then false
+ else disjoint_all (i+1)
+ in disjoint_all 0
+
+let set_of_array v =
+ match Array.length v with
+ 0 -> Set.empty
+ | 1 -> Set.add v.(0) Set.empty
+ | n -> let rec add_all i =
+ if i >= n then Set.empty else Set.add v.(i) (add_all(i+1))
+ in add_all 0
diff --git a/asmcomp/reg.mli b/asmcomp/reg.mli
new file mode 100644
index 0000000000..f705c209ee
--- /dev/null
+++ b/asmcomp/reg.mli
@@ -0,0 +1,67 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pseudo-registers *)
+
+module Raw_name : sig
+ type t
+ val create_from_ident : Ident.t -> t
+end
+
+type t =
+ { mutable raw_name: Raw_name.t; (* Name *)
+ stamp: int; (* Unique stamp *)
+ mutable typ: Cmm.machtype_component;(* Type of contents *)
+ mutable loc: location; (* Actual location *)
+ mutable spill: bool; (* "true" to force stack allocation *)
+ mutable part: int option; (* Zero-based index of part of value *)
+ mutable interf: t list; (* Other regs live simultaneously *)
+ mutable prefer: (t * int) list; (* Preferences for other regs *)
+ mutable degree: int; (* Number of other regs live sim. *)
+ mutable spill_cost: int; (* Estimate of spilling cost *)
+ mutable visited: bool } (* For graph walks *)
+
+and location =
+ Unknown
+ | Reg of int
+ | Stack of stack_location
+
+and stack_location =
+ Local of int
+ | Incoming of int
+ | Outgoing of int
+
+val dummy: t
+val create: Cmm.machtype_component -> t
+val createv: Cmm.machtype -> t array
+val createv_like: t array -> t array
+val clone: t -> t
+val at_location: Cmm.machtype_component -> location -> t
+
+val anonymous : t -> bool
+
+(* Name for printing *)
+val name : t -> string
+
+module Set: Set.S with type elt = t
+module Map: Map.S with type key = t
+
+val add_set_array: Set.t -> t array -> Set.t
+val diff_set_array: Set.t -> t array -> Set.t
+val inter_set_array: Set.t -> t array -> Set.t
+val disjoint_set_array: Set.t -> t array -> bool
+val set_of_array: t array -> Set.t
+
+val reset: unit -> unit
+val all_registers: unit -> t list
+val num_registers: unit -> int
+val reinit: unit -> unit
diff --git a/asmcomp/reload.mli b/asmcomp/reload.mli
new file mode 100644
index 0000000000..cecacbd4a4
--- /dev/null
+++ b/asmcomp/reload.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Insert load/stores for pseudoregs that got assigned to stack locations. *)
+
+val fundecl: Mach.fundecl -> Mach.fundecl * bool
diff --git a/asmcomp/reloadgen.ml b/asmcomp/reloadgen.ml
new file mode 100644
index 0000000000..30f23a8254
--- /dev/null
+++ b/asmcomp/reloadgen.ml
@@ -0,0 +1,139 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Insert load/stores for pseudoregs that got assigned to stack locations. *)
+
+open Misc
+open Reg
+open Mach
+
+let access_stack r =
+ try
+ for i = 0 to Array.length r - 1 do
+ match r.(i).loc with Stack _ -> raise Exit | _ -> ()
+ done;
+ false
+ with Exit ->
+ true
+
+let insert_move src dst next =
+ if src.loc = dst.loc
+ then next
+ else instr_cons (Iop Imove) [|src|] [|dst|] next
+
+let insert_moves src dst next =
+ let rec insmoves i =
+ if i >= Array.length src
+ then next
+ else insert_move src.(i) dst.(i) (insmoves (i+1))
+ in insmoves 0
+
+class reload_generic = object (self)
+
+val mutable redo_regalloc = false
+
+method makereg r =
+ match r.loc with
+ Unknown -> fatal_error "Reload.makereg"
+ | Reg _ -> r
+ | Stack _ ->
+ redo_regalloc <- true;
+ let newr = Reg.clone r in
+ (* Strongly discourage spilling this register *)
+ newr.spill_cost <- 100000;
+ newr
+
+method private makeregs rv =
+ let n = Array.length rv in
+ let newv = Array.make n Reg.dummy in
+ for i = 0 to n-1 do newv.(i) <- self#makereg rv.(i) done;
+ newv
+
+method private makereg1 rv =
+ let newv = Array.copy rv in
+ newv.(0) <- self#makereg rv.(0);
+ newv
+
+method reload_operation op arg res =
+ (* By default, assume that arguments and results must reside
+ in hardware registers. For moves, allow one arg or one
+ res to be stack-allocated, but do something for
+ stack-to-stack moves *)
+ match op with
+ Imove | Ireload | Ispill ->
+ begin match arg.(0), res.(0) with
+ {loc = Stack s1}, {loc = Stack s2} when s1 <> s2 ->
+ ([| self#makereg arg.(0) |], res)
+ | _ ->
+ (arg, res)
+ end
+ | _ ->
+ (self#makeregs arg, self#makeregs res)
+
+method reload_test tst args =
+ self#makeregs args
+
+method private reload i =
+ match i.desc with
+ (* For function calls, returns, etc: the arguments and results are
+ already at the correct position (e.g. on stack for some arguments).
+ However, something needs to be done for the function pointer in
+ indirect calls. *)
+ Iend | Ireturn | Iop(Itailcall_imm _) | Iraise _ -> i
+ | Iop(Itailcall_ind) ->
+ let newarg = self#makereg1 i.arg in
+ insert_moves i.arg newarg
+ {i with arg = newarg}
+ | Iop(Icall_imm _ | Iextcall _) ->
+ {i with next = self#reload i.next}
+ | Iop(Icall_ind) ->
+ let newarg = self#makereg1 i.arg in
+ insert_moves i.arg newarg
+ {i with arg = newarg; next = self#reload i.next}
+ | Iop op ->
+ let (newarg, newres) = self#reload_operation op i.arg i.res in
+ insert_moves i.arg newarg
+ {i with arg = newarg; res = newres; next =
+ (insert_moves newres i.res
+ (self#reload i.next))}
+ | Iifthenelse(tst, ifso, ifnot) ->
+ let newarg = self#reload_test tst i.arg in
+ insert_moves i.arg newarg
+ (instr_cons
+ (Iifthenelse(tst, self#reload ifso, self#reload ifnot)) newarg [||]
+ (self#reload i.next))
+ | Iswitch(index, cases) ->
+ let newarg = self#makeregs i.arg in
+ insert_moves i.arg newarg
+ (instr_cons (Iswitch(index, Array.map (self#reload) cases)) newarg [||]
+ (self#reload i.next))
+ | Iloop body ->
+ instr_cons (Iloop(self#reload body)) [||] [||] (self#reload i.next)
+ | Icatch(nfail, body, handler) ->
+ instr_cons
+ (Icatch(nfail, self#reload body, self#reload handler)) [||] [||]
+ (self#reload i.next)
+ | Iexit i ->
+ instr_cons (Iexit i) [||] [||] dummy_instr
+ | Itrywith(body, handler) ->
+ instr_cons (Itrywith(self#reload body, self#reload handler)) [||] [||]
+ (self#reload i.next)
+
+method fundecl f =
+ redo_regalloc <- false;
+ let new_body = self#reload f.fun_body in
+ ({fun_name = f.fun_name; fun_args = f.fun_args;
+ fun_body = new_body; fun_fast = f.fun_fast;
+ fun_dbg = f.fun_dbg},
+ redo_regalloc)
+
+end
diff --git a/asmcomp/reloadgen.mli b/asmcomp/reloadgen.mli
new file mode 100644
index 0000000000..45c68d1c3d
--- /dev/null
+++ b/asmcomp/reloadgen.mli
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+class reload_generic : object
+ method reload_operation :
+ Mach.operation -> Reg.t array -> Reg.t array -> Reg.t array * Reg.t array
+ method reload_test : Mach.test -> Reg.t array -> Reg.t array
+ (* Can be overridden to reflect instructions that can operate
+ directly on stack locations *)
+ method makereg : Reg.t -> Reg.t
+ (* Can be overridden to avoid creating new registers of some class
+ (i.e. if all "registers" of that class are actually on stack) *)
+ method fundecl : Mach.fundecl -> Mach.fundecl * bool
+ (* The entry point *)
+end
diff --git a/asmcomp/schedgen.ml b/asmcomp/schedgen.ml
new file mode 100644
index 0000000000..c1ba222a8d
--- /dev/null
+++ b/asmcomp/schedgen.ml
@@ -0,0 +1,395 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction scheduling *)
+
+open Reg
+open Mach
+open Linearize
+
+(* Representation of the code DAG. *)
+
+type code_dag_node =
+ { instr: instruction; (* The instruction *)
+ delay: int; (* How many cycles before result is available *)
+ mutable sons: (code_dag_node * int) list;
+ (* Instructions that depend on it *)
+ mutable date: int; (* Start date *)
+ mutable length: int; (* Length of longest path to result *)
+ mutable ancestors: int; (* Number of ancestors *)
+ mutable emitted_ancestors: int } (* Number of emitted ancestors *)
+
+let dummy_node =
+ { instr = end_instr; delay = 0; sons = []; date = 0;
+ length = -1; ancestors = 0; emitted_ancestors = 0 }
+
+(* The code dag itself is represented by two tables from registers to nodes:
+ - "results" maps registers to the instructions that produced them;
+ - "uses" maps registers to the instructions that use them.
+ In addition:
+ - code_stores contains the latest store nodes emitted so far
+ - code_loads contains all load nodes emitted since the last store
+ - code_checkbounds contains the latest checkbound node not matched
+ by a subsequent load or store. *)
+
+let code_results = (Hashtbl.create 31 : (location, code_dag_node) Hashtbl.t)
+let code_uses = (Hashtbl.create 31 : (location, code_dag_node) Hashtbl.t)
+let code_stores = ref ([] : code_dag_node list)
+let code_loads = ref ([] : code_dag_node list)
+let code_checkbounds = ref ([] : code_dag_node list)
+
+let clear_code_dag () =
+ Hashtbl.clear code_results;
+ Hashtbl.clear code_uses;
+ code_stores := [];
+ code_loads := [];
+ code_checkbounds := []
+
+(* Add an edge to the code DAG *)
+
+let add_edge ancestor son delay =
+ ancestor.sons <- (son, delay) :: ancestor.sons;
+ son.ancestors <- son.ancestors + 1
+
+let add_edge_after son ancestor = add_edge ancestor son 0
+
+(* Add edges from all instructions that define a pseudoregister [arg] being used
+ as argument to node [node] (RAW dependencies *)
+
+let add_RAW_dependencies node arg =
+ try
+ let ancestor = Hashtbl.find code_results arg.loc in
+ add_edge ancestor node ancestor.delay
+ with Not_found ->
+ ()
+
+(* Add edges from all instructions that use a pseudoregister [res] that is
+ defined by node [node] (WAR dependencies). *)
+
+let add_WAR_dependencies node res =
+ let ancestors = Hashtbl.find_all code_uses res.loc in
+ List.iter (add_edge_after node) ancestors
+
+(* Add edges from all instructions that have already defined a pseudoregister
+ [res] that is defined by node [node] (WAW dependencies). *)
+
+let add_WAW_dependencies node res =
+ try
+ let ancestor = Hashtbl.find code_results res.loc in
+ add_edge ancestor node 0
+ with Not_found ->
+ ()
+
+(* Compute length of longest path to a result.
+ For leafs of the DAG, see whether their result is used in the instruction
+ immediately following the basic block (a "critical" output). *)
+
+let is_critical critical_outputs results =
+ try
+ for i = 0 to Array.length results - 1 do
+ let r = results.(i).loc in
+ for j = 0 to Array.length critical_outputs - 1 do
+ if critical_outputs.(j).loc = r then raise Exit
+ done
+ done;
+ false
+ with Exit ->
+ true
+
+let rec longest_path critical_outputs node =
+ if node.length < 0 then begin
+ match node.sons with
+ [] ->
+ node.length <-
+ if is_critical critical_outputs node.instr.res
+ || node.instr.desc = Lreloadretaddr (* alway critical *)
+ then node.delay
+ else 0
+ | sons ->
+ node.length <-
+ List.fold_left
+ (fun len (son, delay) ->
+ max len (longest_path critical_outputs son + delay))
+ 0 sons
+ end;
+ node.length
+
+(* Remove an instruction from the ready queue *)
+
+let rec remove_instr node = function
+ [] -> []
+ | instr :: rem ->
+ if instr == node then rem else instr :: remove_instr node rem
+
+(* We treat Lreloadretaddr as a word-sized load *)
+
+let some_load = (Iload(Cmm.Word_int, Arch.identity_addressing))
+
+(* The generic scheduler *)
+
+class virtual scheduler_generic = object (self)
+
+val mutable trywith_nesting = 0
+
+(* Determine whether an operation ends a basic block or not.
+ Can be overridden for some processors to signal specific instructions
+ that terminate a basic block. *)
+
+method oper_in_basic_block = function
+ Icall_ind -> false
+ | Icall_imm _ -> false
+ | Itailcall_ind -> false
+ | Itailcall_imm _ -> false
+ | Iextcall _ -> false
+ | Istackoffset _ -> false
+ | Ialloc _ -> false
+ | _ -> true
+
+(* Determine whether an instruction ends a basic block or not *)
+
+(* PR#2719: it is generally incorrect to schedule checkbound instructions
+ within a try ... with Invalid_argument _ -> ...
+ Hence, a checkbound instruction within a try...with block ends the
+ current basic block. *)
+
+method private instr_in_basic_block instr try_nesting =
+ match instr.desc with
+ Lop op ->
+ self#oper_in_basic_block op &&
+ not (try_nesting > 0 && self#is_checkbound op)
+ | Lreloadretaddr -> true
+ | _ -> false
+
+(* Determine whether an operation is a memory store or a memory load.
+ Can be overridden for some processors to signal specific
+ load or store instructions (e.g. on the I386). *)
+
+method is_store = function
+ Istore(_, _, _) -> true
+ | _ -> false
+
+method is_load = function
+ Iload(_, _) -> true
+ | _ -> false
+
+method is_checkbound = function
+ Iintop Icheckbound -> true
+ | Iintop_imm(Icheckbound, _) -> true
+ | _ -> false
+
+method private instr_is_store instr =
+ match instr.desc with
+ Lop op -> self#is_store op
+ | _ -> false
+
+method private instr_is_load instr =
+ match instr.desc with
+ Lop op -> self#is_load op
+ | _ -> false
+
+method private instr_is_checkbound instr =
+ match instr.desc with
+ Lop op -> self#is_checkbound op
+ | _ -> false
+
+(* Estimate the latency of an operation. *)
+
+method virtual oper_latency : Mach.operation -> int
+
+(* Estimate the latency of a Lreloadretaddr operation. *)
+
+method reload_retaddr_latency = self#oper_latency some_load
+
+(* Estimate the delay needed to evaluate an instruction *)
+
+method private instr_latency instr =
+ match instr.desc with
+ Lop op -> self#oper_latency op
+ | Lreloadretaddr -> self#reload_retaddr_latency
+ | _ -> assert false
+
+(* Estimate the number of cycles consumed by emitting an operation. *)
+
+method virtual oper_issue_cycles : Mach.operation -> int
+
+(* Estimate the number of cycles consumed by emitting a Lreloadretaddr. *)
+
+method reload_retaddr_issue_cycles = self#oper_issue_cycles some_load
+
+(* Estimate the number of cycles consumed by emitting an instruction. *)
+
+method private instr_issue_cycles instr =
+ match instr.desc with
+ Lop op -> self#oper_issue_cycles op
+ | Lreloadretaddr -> self#reload_retaddr_issue_cycles
+ | _ -> assert false
+
+(* Pseudoregisters destroyed by an instruction *)
+
+method private destroyed_by_instr instr =
+ match instr.desc with
+ | Lop op -> Proc.destroyed_at_oper (Iop op)
+ | Lreloadretaddr -> [||]
+ | _ -> assert false
+
+(* Add an instruction to the code dag *)
+
+method private add_instruction ready_queue instr =
+ let delay = self#instr_latency instr in
+ let destroyed = self#destroyed_by_instr instr in
+ let node =
+ { instr = instr;
+ delay = delay;
+ sons = [];
+ date = 0;
+ length = -1;
+ ancestors = 0;
+ emitted_ancestors = 0 } in
+ (* Add edges from all instructions that define one of the registers used
+ (RAW dependencies) *)
+ Array.iter (add_RAW_dependencies node) instr.arg;
+ (* Also add edges from all instructions that use one of the result regs
+ of this instruction, or a reg destroyed by this instruction
+ (WAR dependencies). *)
+ Array.iter (add_WAR_dependencies node) instr.res;
+ Array.iter (add_WAR_dependencies node) destroyed; (* PR#5731 *)
+ (* Also add edges from all instructions that have already defined one
+ of the results of this instruction, or a reg destroyed by
+ this instruction (WAW dependencies). *)
+ Array.iter (add_WAW_dependencies node) instr.res;
+ Array.iter (add_WAW_dependencies node) destroyed; (* PR#5731 *)
+ (* If this is a load, add edges from the most recent store viewed so
+ far (if any) and remember the load. Also add edges from the most
+ recent checkbound and forget that checkbound. *)
+ if self#instr_is_load instr then begin
+ List.iter (add_edge_after node) !code_stores;
+ code_loads := node :: !code_loads;
+ List.iter (add_edge_after node) !code_checkbounds;
+ code_checkbounds := []
+ end
+ (* If this is a store, add edges from the most recent store,
+ as well as all loads viewed since then, and also the most recent
+ checkbound. Remember the store,
+ discarding the previous stores, loads and checkbounds. *)
+ else if self#instr_is_store instr then begin
+ List.iter (add_edge_after node) !code_stores;
+ List.iter (add_edge_after node) !code_loads;
+ List.iter (add_edge_after node) !code_checkbounds;
+ code_stores := [node];
+ code_loads := [];
+ code_checkbounds := []
+ end
+ else if self#instr_is_checkbound instr then begin
+ code_checkbounds := [node]
+ end;
+ (* Remember the registers used and produced by this instruction *)
+ for i = 0 to Array.length instr.res - 1 do
+ Hashtbl.add code_results instr.res.(i).loc node
+ done;
+ for i = 0 to Array.length destroyed - 1 do
+ Hashtbl.add code_results destroyed.(i).loc node (* PR#5731 *)
+ done;
+ for i = 0 to Array.length instr.arg - 1 do
+ Hashtbl.add code_uses instr.arg.(i).loc node
+ done;
+ (* If this is a root instruction (all arguments already computed),
+ add it to the ready queue *)
+ if node.ancestors = 0 then node :: ready_queue else ready_queue
+
+(* Given a list of instructions and a date, choose one or several
+ that are ready to be computed (start date <= current date)
+ and that we can emit in one cycle. Favor instructions with
+ maximal distance to result. If we can't find any, return None.
+ This does not take multiple issues into account, though. *)
+
+method private ready_instruction date queue =
+ let rec extract best = function
+ [] ->
+ if best == dummy_node then None else Some best
+ | instr :: rem ->
+ let new_best =
+ if instr.date <= date && instr.length > best.length
+ then instr else best in
+ extract new_best rem in
+ extract dummy_node queue
+
+(* Schedule a basic block, adding its instructions in front of the given
+ instruction sequence *)
+
+method private reschedule ready_queue date cont =
+ if ready_queue = [] then cont else begin
+ match self#ready_instruction date ready_queue with
+ None ->
+ self#reschedule ready_queue (date + 1) cont
+ | Some node ->
+ (* Remove node from queue *)
+ let new_queue = ref (remove_instr node ready_queue) in
+ (* Update the start date and number of ancestors emitted of
+ all descendents of this node. Enter those that become ready
+ in the queue. *)
+ let issue_cycles = self#instr_issue_cycles node.instr in
+ List.iter
+ (fun (son, delay) ->
+ let completion_date = date + issue_cycles + delay - 1 in
+ if son.date < completion_date then son.date <- completion_date;
+ son.emitted_ancestors <- son.emitted_ancestors + 1;
+ if son.emitted_ancestors = son.ancestors then
+ new_queue := son :: !new_queue)
+ node.sons;
+ { node.instr with next =
+ self#reschedule !new_queue (date + issue_cycles) cont }
+ end
+
+(* Entry point *)
+(* Don't bother to schedule for initialization code and the like. *)
+
+method schedule_fundecl f =
+
+ let rec schedule i try_nesting =
+ match i.desc with
+ | Lend -> i
+ | Lpushtrap -> { i with next = schedule i.next (try_nesting + 1) }
+ | Lpoptrap -> { i with next = schedule i.next (try_nesting - 1) }
+ | _ ->
+ if self#instr_in_basic_block i try_nesting then begin
+ clear_code_dag();
+ schedule_block [] i try_nesting
+ end else
+ { i with next = schedule i.next try_nesting }
+
+ and schedule_block ready_queue i try_nesting =
+ if self#instr_in_basic_block i try_nesting then
+ schedule_block (self#add_instruction ready_queue i) i.next try_nesting
+ else begin
+ let critical_outputs =
+ match i.desc with
+ Lop(Icall_ind | Itailcall_ind) -> [| i.arg.(0) |]
+ | Lop(Icall_imm _ | Itailcall_imm _ | Iextcall _) -> [||]
+ | Lreturn -> [||]
+ | _ -> i.arg in
+ List.iter (fun x -> ignore (longest_path critical_outputs x)) ready_queue;
+ self#reschedule ready_queue 0 (schedule i try_nesting)
+ end in
+
+ if f.fun_fast then begin
+ let new_body = schedule f.fun_body 0 in
+ clear_code_dag();
+ { fun_name = f.fun_name;
+ fun_body = new_body;
+ fun_fast = f.fun_fast;
+ fun_dbg = f.fun_dbg }
+ end else
+ f
+
+end
+
+let reset () = clear_code_dag ()
diff --git a/asmcomp/schedgen.mli b/asmcomp/schedgen.mli
new file mode 100644
index 0000000000..911330f8ac
--- /dev/null
+++ b/asmcomp/schedgen.mli
@@ -0,0 +1,46 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction scheduling *)
+
+type code_dag_node =
+ { instr: Linearize.instruction;
+ delay: int;
+ mutable sons: (code_dag_node * int) list;
+ mutable date: int;
+ mutable length: int;
+ mutable ancestors: int;
+ mutable emitted_ancestors: int }
+
+class virtual scheduler_generic : object
+ (* Can be overridden by processor description *)
+ method virtual oper_issue_cycles : Mach.operation -> int
+ (* Number of cycles needed to issue the given operation *)
+ method virtual oper_latency : Mach.operation -> int
+ (* Number of cycles needed to complete the given operation *)
+ method reload_retaddr_issue_cycles : int
+ (* Number of cycles needed to issue a Lreloadretaddr operation *)
+ method reload_retaddr_latency : int
+ (* Number of cycles needed to complete a Lreloadretaddr operation *)
+ method oper_in_basic_block : Mach.operation -> bool
+ (* Says whether the given operation terminates a basic block *)
+ method is_store : Mach.operation -> bool
+ (* Says whether the given operation is a memory store *)
+ method is_load : Mach.operation -> bool
+ (* Says whether the given operation is a memory load *)
+ method is_checkbound : Mach.operation -> bool
+ (* Says whether the given operation is a checkbound *)
+ (* Entry point *)
+ method schedule_fundecl : Linearize.fundecl -> Linearize.fundecl
+end
+
+val reset : unit -> unit
diff --git a/asmcomp/scheduling.mli b/asmcomp/scheduling.mli
new file mode 100644
index 0000000000..5949661d18
--- /dev/null
+++ b/asmcomp/scheduling.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction scheduling *)
+
+val fundecl: Linearize.fundecl -> Linearize.fundecl
diff --git a/asmcomp/selectgen.ml b/asmcomp/selectgen.ml
new file mode 100644
index 0000000000..79d95b4313
--- /dev/null
+++ b/asmcomp/selectgen.ml
@@ -0,0 +1,893 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Selection of pseudo-instructions, assignment of pseudo-registers,
+ sequentialization. *)
+
+open Misc
+open Cmm
+open Reg
+open Mach
+
+type environment = (Ident.t, Reg.t array) Tbl.t
+
+(* Infer the type of the result of an operation *)
+
+let oper_result_type = function
+ Capply(ty, _) -> ty
+ | Cextcall(s, ty, alloc, _) -> ty
+ | Cload c ->
+ begin match c with
+ | Word_val -> typ_val
+ | Single | Double | Double_u -> typ_float
+ | _ -> typ_int
+ end
+ | Calloc -> typ_val
+ | Cstore c -> typ_void
+ | Caddi | Csubi | Cmuli | Cmulhi | Cdivi | Cmodi |
+ Cand | Cor | Cxor | Clsl | Clsr | Casr |
+ Ccmpi _ | Ccmpa _ | Ccmpf _ -> typ_int
+ | Caddv -> typ_val
+ | Cadda -> typ_addr
+ | Cnegf | Cabsf | Caddf | Csubf | Cmulf | Cdivf -> typ_float
+ | Cfloatofint -> typ_float
+ | Cintoffloat -> typ_int
+ | Craise _ -> typ_void
+ | Ccheckbound _ -> typ_void
+
+(* Infer the size in bytes of the result of a simple expression *)
+
+let size_expr env exp =
+ let rec size localenv = function
+ Cconst_int _ | Cconst_natint _
+ | Cconst_blockheader _ -> Arch.size_int
+ | Cconst_symbol _ | Cconst_pointer _ | Cconst_natpointer _ ->
+ Arch.size_addr
+ | Cconst_float _ -> Arch.size_float
+ | Cvar id ->
+ begin try
+ Tbl.find id localenv
+ with Not_found ->
+ try
+ let regs = Tbl.find id env in
+ size_machtype (Array.map (fun r -> r.typ) regs)
+ with Not_found ->
+ fatal_error("Selection.size_expr: unbound var " ^
+ Ident.unique_name id)
+ end
+ | Ctuple el ->
+ List.fold_right (fun e sz -> size localenv e + sz) el 0
+ | Cop(op, args) ->
+ size_machtype(oper_result_type op)
+ | Clet(id, arg, body) ->
+ size (Tbl.add id (size localenv arg) localenv) body
+ | Csequence(e1, e2) ->
+ size localenv e2
+ | _ ->
+ fatal_error "Selection.size_expr"
+ in size Tbl.empty exp
+
+(* Swap the two arguments of an integer comparison *)
+
+let swap_intcomp = function
+ Isigned cmp -> Isigned(swap_comparison cmp)
+ | Iunsigned cmp -> Iunsigned(swap_comparison cmp)
+
+(* Naming of registers *)
+
+let all_regs_anonymous rv =
+ try
+ for i = 0 to Array.length rv - 1 do
+ if not (Reg.anonymous rv.(i)) then raise Exit
+ done;
+ true
+ with Exit ->
+ false
+
+let name_regs id rv =
+ if Array.length rv = 1 then
+ rv.(0).raw_name <- Raw_name.create_from_ident id
+ else
+ for i = 0 to Array.length rv - 1 do
+ rv.(i).raw_name <- Raw_name.create_from_ident id;
+ rv.(i).part <- Some i
+ done
+
+(* "Join" two instruction sequences, making sure they return their results
+ in the same registers. *)
+
+let join opt_r1 seq1 opt_r2 seq2 =
+ match (opt_r1, opt_r2) with
+ (None, _) -> opt_r2
+ | (_, None) -> opt_r1
+ | (Some r1, Some r2) ->
+ let l1 = Array.length r1 in
+ assert (l1 = Array.length r2);
+ let r = Array.make l1 Reg.dummy in
+ for i = 0 to l1-1 do
+ if Reg.anonymous r1.(i) then begin
+ r.(i) <- r1.(i);
+ seq2#insert_move r2.(i) r1.(i)
+ end else if Reg.anonymous r2.(i) then begin
+ r.(i) <- r2.(i);
+ seq1#insert_move r1.(i) r2.(i)
+ end else begin
+ r.(i) <- Reg.create r1.(i).typ;
+ seq1#insert_move r1.(i) r.(i);
+ seq2#insert_move r2.(i) r.(i)
+ end
+ done;
+ Some r
+
+(* Same, for N branches *)
+
+let join_array rs =
+ let some_res = ref None in
+ for i = 0 to Array.length rs - 1 do
+ let (r, s) = rs.(i) in
+ if r <> None then some_res := r
+ done;
+ match !some_res with
+ None -> None
+ | Some template ->
+ let size_res = Array.length template in
+ let res = Array.make size_res Reg.dummy in
+ for i = 0 to size_res - 1 do
+ res.(i) <- Reg.create template.(i).typ
+ done;
+ for i = 0 to Array.length rs - 1 do
+ let (r, s) = rs.(i) in
+ match r with
+ None -> ()
+ | Some r -> s#insert_moves r res
+ done;
+ Some res
+
+(* Extract debug info contained in a C-- operation *)
+let debuginfo_op = function
+ | Capply(_, dbg) -> dbg
+ | Cextcall(_, _, _, dbg) -> dbg
+ | Craise (_, dbg) -> dbg
+ | Ccheckbound dbg -> dbg
+ | _ -> Debuginfo.none
+
+(* Registers for catch constructs *)
+let catch_regs = ref []
+
+(* Name of function being compiled *)
+let current_function_name = ref ""
+
+(* The default instruction selection class *)
+
+class virtual selector_generic = object (self)
+
+(* Says if an expression is "simple". A "simple" expression has no
+ side-effects and its execution can be delayed until its value
+ is really needed. In the case of e.g. an [alloc] instruction,
+ the non-simple arguments are computed in right-to-left order
+ first, then the block is allocated, then the simple arguments are
+ evaluated and stored. *)
+
+method is_simple_expr = function
+ Cconst_int _ -> true
+ | Cconst_natint _ -> true
+ | Cconst_blockheader _ -> true
+ | Cconst_float _ -> true
+ | Cconst_symbol _ -> true
+ | Cconst_pointer _ -> true
+ | Cconst_natpointer _ -> true
+ | Cvar _ -> true
+ | Ctuple el -> List.for_all self#is_simple_expr el
+ | Clet(id, arg, body) -> self#is_simple_expr arg && self#is_simple_expr body
+ | Csequence(e1, e2) -> self#is_simple_expr e1 && self#is_simple_expr e2
+ | Cop(op, args) ->
+ begin match op with
+ (* The following may have side effects *)
+ | Capply _ | Cextcall _ | Calloc | Cstore _ | Craise _ -> false
+ (* The remaining operations are simple if their args are *)
+ | _ ->
+ List.for_all self#is_simple_expr args
+ end
+ | _ -> false
+
+(* Says whether an integer constant is a suitable immediate argument *)
+
+method virtual is_immediate : int -> bool
+
+(* Selection of addressing modes *)
+
+method virtual select_addressing :
+ Cmm.memory_chunk -> Cmm.expression -> Arch.addressing_mode * Cmm.expression
+
+(* Default instruction selection for stores (of words) *)
+
+method select_store is_assign addr arg =
+ (Istore(Word_val, addr, is_assign), arg)
+
+(* call marking methods, documented in selectgen.mli *)
+
+method mark_call =
+ Proc.contains_calls := true
+
+method mark_tailcall = ()
+
+method mark_c_tailcall = ()
+
+method mark_instr = function
+ | Iop (Icall_ind | Icall_imm _ | Iextcall _) ->
+ self#mark_call
+ | Iop (Itailcall_ind | Itailcall_imm _) ->
+ self#mark_tailcall
+ | Iop (Ialloc _) ->
+ self#mark_call (* caml_alloc*, caml_garbage_collection *)
+ | Iop (Iintop Icheckbound | Iintop_imm(Icheckbound, _)) ->
+ self#mark_c_tailcall (* caml_ml_array_bound_error *)
+ | Iraise raise_kind ->
+ begin match raise_kind with
+ | Lambda.Raise_notrace -> ()
+ | Lambda.Raise_regular | Lambda.Raise_reraise ->
+ if !Clflags.debug then (* PR#6239 *)
+ (* caml_stash_backtrace; we #mark_call rather than
+ #mark_c_tailcall to get a good stack backtrace *)
+ self#mark_call
+ end
+ | Itrywith _ ->
+ self#mark_call
+ | _ -> ()
+
+(* Default instruction selection for operators *)
+
+method select_operation op args =
+ match (op, args) with
+ (Capply(ty, dbg), Cconst_symbol s :: rem) -> (Icall_imm s, rem)
+ | (Capply(ty, dbg), _) -> (Icall_ind, args)
+ | (Cextcall(s, ty, alloc, dbg), _) -> (Iextcall(s, alloc), args)
+ | (Cload chunk, [arg]) ->
+ let (addr, eloc) = self#select_addressing chunk arg in
+ (Iload(chunk, addr), [eloc])
+ | (Cstore chunk, [arg1; arg2]) ->
+ let (addr, eloc) = self#select_addressing chunk arg1 in
+ if chunk = Word_int || chunk = Word_val then begin
+ let (op, newarg2) = self#select_store true addr arg2 in
+ (op, [newarg2; eloc])
+ end else begin
+ (Istore(chunk, addr, true), [arg2; eloc])
+ (* Inversion addr/datum in Istore *)
+ end
+ | (Calloc, _) -> (Ialloc 0, args)
+ | (Caddi, _) -> self#select_arith_comm Iadd args
+ | (Csubi, _) -> self#select_arith Isub args
+ | (Cmuli, _) -> self#select_arith_comm Imul args
+ | (Cmulhi, _) -> self#select_arith_comm Imulh args
+ | (Cdivi, _) -> (Iintop Idiv, args)
+ | (Cmodi, _) -> (Iintop Imod, args)
+ | (Cand, _) -> self#select_arith_comm Iand args
+ | (Cor, _) -> self#select_arith_comm Ior args
+ | (Cxor, _) -> self#select_arith_comm Ixor args
+ | (Clsl, _) -> self#select_shift Ilsl args
+ | (Clsr, _) -> self#select_shift Ilsr args
+ | (Casr, _) -> self#select_shift Iasr args
+ | (Ccmpi comp, _) -> self#select_arith_comp (Isigned comp) args
+ | (Caddv, _) -> self#select_arith_comm Iadd args
+ | (Cadda, _) -> self#select_arith_comm Iadd args
+ | (Ccmpa comp, _) -> self#select_arith_comp (Iunsigned comp) args
+ | (Cnegf, _) -> (Inegf, args)
+ | (Cabsf, _) -> (Iabsf, args)
+ | (Caddf, _) -> (Iaddf, args)
+ | (Csubf, _) -> (Isubf, args)
+ | (Cmulf, _) -> (Imulf, args)
+ | (Cdivf, _) -> (Idivf, args)
+ | (Cfloatofint, _) -> (Ifloatofint, args)
+ | (Cintoffloat, _) -> (Iintoffloat, args)
+ | (Ccheckbound _, _) -> self#select_arith Icheckbound args
+ | _ -> fatal_error "Selection.select_oper"
+
+method private select_arith_comm op = function
+ [arg; Cconst_int n] when self#is_immediate n ->
+ (Iintop_imm(op, n), [arg])
+ | [arg; Cconst_pointer n] when self#is_immediate n ->
+ (Iintop_imm(op, n), [arg])
+ | [Cconst_int n; arg] when self#is_immediate n ->
+ (Iintop_imm(op, n), [arg])
+ | [Cconst_pointer n; arg] when self#is_immediate n ->
+ (Iintop_imm(op, n), [arg])
+ | args ->
+ (Iintop op, args)
+
+method private select_arith op = function
+ [arg; Cconst_int n] when self#is_immediate n ->
+ (Iintop_imm(op, n), [arg])
+ | [arg; Cconst_pointer n] when self#is_immediate n ->
+ (Iintop_imm(op, n), [arg])
+ | args ->
+ (Iintop op, args)
+
+method private select_shift op = function
+ [arg; Cconst_int n] when n >= 0 && n < Arch.size_int * 8 ->
+ (Iintop_imm(op, n), [arg])
+ | args ->
+ (Iintop op, args)
+
+method private select_arith_comp cmp = function
+ [arg; Cconst_int n] when self#is_immediate n ->
+ (Iintop_imm(Icomp cmp, n), [arg])
+ | [arg; Cconst_pointer n] when self#is_immediate n ->
+ (Iintop_imm(Icomp cmp, n), [arg])
+ | [Cconst_int n; arg] when self#is_immediate n ->
+ (Iintop_imm(Icomp(swap_intcomp cmp), n), [arg])
+ | [Cconst_pointer n; arg] when self#is_immediate n ->
+ (Iintop_imm(Icomp(swap_intcomp cmp), n), [arg])
+ | args ->
+ (Iintop(Icomp cmp), args)
+
+(* Instruction selection for conditionals *)
+
+method select_condition = function
+ Cop(Ccmpi cmp, [arg1; Cconst_int n]) when self#is_immediate n ->
+ (Iinttest_imm(Isigned cmp, n), arg1)
+ | Cop(Ccmpi cmp, [Cconst_int n; arg2]) when self#is_immediate n ->
+ (Iinttest_imm(Isigned(swap_comparison cmp), n), arg2)
+ | Cop(Ccmpi cmp, [arg1; Cconst_pointer n]) when self#is_immediate n ->
+ (Iinttest_imm(Isigned cmp, n), arg1)
+ | Cop(Ccmpi cmp, [Cconst_pointer n; arg2]) when self#is_immediate n ->
+ (Iinttest_imm(Isigned(swap_comparison cmp), n), arg2)
+ | Cop(Ccmpi cmp, args) ->
+ (Iinttest(Isigned cmp), Ctuple args)
+ | Cop(Ccmpa cmp, [arg1; Cconst_pointer n]) when self#is_immediate n ->
+ (Iinttest_imm(Iunsigned cmp, n), arg1)
+ | Cop(Ccmpa cmp, [arg1; Cconst_int n]) when self#is_immediate n ->
+ (Iinttest_imm(Iunsigned cmp, n), arg1)
+ | Cop(Ccmpa cmp, [Cconst_pointer n; arg2]) when self#is_immediate n ->
+ (Iinttest_imm(Iunsigned(swap_comparison cmp), n), arg2)
+ | Cop(Ccmpa cmp, [Cconst_int n; arg2]) when self#is_immediate n ->
+ (Iinttest_imm(Iunsigned(swap_comparison cmp), n), arg2)
+ | Cop(Ccmpa cmp, args) ->
+ (Iinttest(Iunsigned cmp), Ctuple args)
+ | Cop(Ccmpf cmp, args) ->
+ (Ifloattest(cmp, false), Ctuple args)
+ | Cop(Cand, [arg; Cconst_int 1]) ->
+ (Ioddtest, arg)
+ | arg ->
+ (Itruetest, arg)
+
+(* Return an array of fresh registers of the given type.
+ Normally implemented as Reg.createv, but some
+ ports (e.g. Arm) can override this definition to store float values
+ in pairs of integer registers. *)
+
+method regs_for tys = Reg.createv tys
+
+(* Buffering of instruction sequences *)
+
+val mutable instr_seq = dummy_instr
+
+method insert_debug desc dbg arg res =
+ instr_seq <- instr_cons_debug desc arg res dbg instr_seq
+
+method insert desc arg res =
+ instr_seq <- instr_cons desc arg res instr_seq
+
+method extract =
+ let rec extract res i =
+ if i == dummy_instr
+ then res
+ else extract {i with next = res} i.next in
+ extract (end_instr()) instr_seq
+
+(* Insert a sequence of moves from one pseudoreg set to another. *)
+
+method insert_move src dst =
+ if src.stamp <> dst.stamp then
+ self#insert (Iop Imove) [|src|] [|dst|]
+
+method insert_moves src dst =
+ for i = 0 to min (Array.length src) (Array.length dst) - 1 do
+ self#insert_move src.(i) dst.(i)
+ done
+
+(* Adjust the types of destination pseudoregs for a [Cassign] assignment.
+ The type inferred at [let] binding might be [Int] while we assign
+ something of type [Val] (PR#6501). *)
+
+method adjust_type src dst =
+ let ts = src.typ and td = dst.typ in
+ if ts <> td then
+ match ts, td with
+ | Val, Int -> dst.typ <- Val
+ | Int, Val -> ()
+ | _, _ -> fatal_error("Selection.adjust_type: bad assignment to "
+ ^ Reg.name dst)
+
+method adjust_types src dst =
+ for i = 0 to min (Array.length src) (Array.length dst) - 1 do
+ self#adjust_type src.(i) dst.(i)
+ done
+
+(* Insert moves and stack offsets for function arguments and results *)
+
+method insert_move_args arg loc stacksize =
+ if stacksize <> 0 then self#insert (Iop(Istackoffset stacksize)) [||] [||];
+ self#insert_moves arg loc
+
+method insert_move_results loc res stacksize =
+ if stacksize <> 0 then self#insert(Iop(Istackoffset(-stacksize))) [||] [||];
+ self#insert_moves loc res
+
+(* Add an Iop opcode. Can be overridden by processor description
+ to insert moves before and after the operation, i.e. for two-address
+ instructions, or instructions using dedicated registers. *)
+
+method insert_op_debug op dbg rs rd =
+ self#insert_debug (Iop op) dbg rs rd;
+ rd
+
+method insert_op op rs rd =
+ self#insert_op_debug op Debuginfo.none rs rd
+
+(* Add the instructions for the given expression
+ at the end of the self sequence *)
+
+method emit_expr env exp =
+ match exp with
+ Cconst_int n ->
+ let r = self#regs_for typ_int in
+ Some(self#insert_op (Iconst_int(Nativeint.of_int n)) [||] r)
+ | Cconst_natint n ->
+ let r = self#regs_for typ_int in
+ Some(self#insert_op (Iconst_int n) [||] r)
+ | Cconst_blockheader n ->
+ let r = self#regs_for typ_int in
+ Some(self#insert_op (Iconst_blockheader n) [||] r)
+ | Cconst_float n ->
+ let r = self#regs_for typ_float in
+ Some(self#insert_op (Iconst_float n) [||] r)
+ | Cconst_symbol n ->
+ let r = self#regs_for typ_val in
+ Some(self#insert_op (Iconst_symbol n) [||] r)
+ | Cconst_pointer n ->
+ let r = self#regs_for typ_val in (* integer as Caml value *)
+ Some(self#insert_op (Iconst_int(Nativeint.of_int n)) [||] r)
+ | Cconst_natpointer n ->
+ let r = self#regs_for typ_val in (* integer as Caml value *)
+ Some(self#insert_op (Iconst_int n) [||] r)
+ | Cvar v ->
+ begin try
+ Some(Tbl.find v env)
+ with Not_found ->
+ fatal_error("Selection.emit_expr: unbound var " ^ Ident.unique_name v)
+ end
+ | Clet(v, e1, e2) ->
+ begin match self#emit_expr env e1 with
+ None -> None
+ | Some r1 -> self#emit_expr (self#bind_let env v r1) e2
+ end
+ | Cassign(v, e1) ->
+ let rv =
+ try
+ Tbl.find v env
+ with Not_found ->
+ fatal_error ("Selection.emit_expr: unbound var " ^ Ident.name v) in
+ begin match self#emit_expr env e1 with
+ None -> None
+ | Some r1 -> self#adjust_types r1 rv; self#insert_moves r1 rv; Some [||]
+ end
+ | Ctuple [] ->
+ Some [||]
+ | Ctuple exp_list ->
+ begin match self#emit_parts_list env exp_list with
+ None -> None
+ | Some(simple_list, ext_env) ->
+ Some(self#emit_tuple ext_env simple_list)
+ end
+ | Cop(Craise (k, dbg), [arg]) ->
+ begin match self#emit_expr env arg with
+ None -> None
+ | Some r1 ->
+ let rd = [|Proc.loc_exn_bucket|] in
+ self#insert (Iop Imove) r1 rd;
+ self#insert_debug (Iraise k) dbg rd [||];
+ None
+ end
+ | Cop(Ccmpf comp, args) ->
+ self#emit_expr env (Cifthenelse(exp, Cconst_int 1, Cconst_int 0))
+ | Cop(op, args) ->
+ begin match self#emit_parts_list env args with
+ None -> None
+ | Some(simple_args, env) ->
+ let ty = oper_result_type op in
+ let (new_op, new_args) = self#select_operation op simple_args in
+ let dbg = debuginfo_op op in
+ match new_op with
+ Icall_ind ->
+ let r1 = self#emit_tuple env new_args in
+ let rarg = Array.sub r1 1 (Array.length r1 - 1) in
+ let rd = self#regs_for ty in
+ let (loc_arg, stack_ofs) = Proc.loc_arguments rarg in
+ let loc_res = Proc.loc_results rd in
+ self#insert_move_args rarg loc_arg stack_ofs;
+ self#insert_debug (Iop Icall_ind) dbg
+ (Array.append [|r1.(0)|] loc_arg) loc_res;
+ self#insert_move_results loc_res rd stack_ofs;
+ Some rd
+ | Icall_imm lbl ->
+ let r1 = self#emit_tuple env new_args in
+ let rd = self#regs_for ty in
+ let (loc_arg, stack_ofs) = Proc.loc_arguments r1 in
+ let loc_res = Proc.loc_results rd in
+ self#insert_move_args r1 loc_arg stack_ofs;
+ self#insert_debug (Iop(Icall_imm lbl)) dbg loc_arg loc_res;
+ self#insert_move_results loc_res rd stack_ofs;
+ Some rd
+ | Iextcall(lbl, alloc) ->
+ let (loc_arg, stack_ofs) = self#emit_extcall_args env new_args in
+ let rd = self#regs_for ty in
+ let loc_res = self#insert_op_debug (Iextcall(lbl, alloc)) dbg
+ loc_arg (Proc.loc_external_results rd) in
+ self#insert_move_results loc_res rd stack_ofs;
+ Some rd
+ | Ialloc _ ->
+ let rd = self#regs_for typ_val in
+ let size = size_expr env (Ctuple new_args) in
+ self#insert (Iop(Ialloc size)) [||] rd;
+ self#emit_stores env new_args rd;
+ Some rd
+ | op ->
+ let r1 = self#emit_tuple env new_args in
+ let rd = self#regs_for ty in
+ Some (self#insert_op_debug op dbg r1 rd)
+ end
+ | Csequence(e1, e2) ->
+ begin match self#emit_expr env e1 with
+ None -> None
+ | Some r1 -> self#emit_expr env e2
+ end
+ | Cifthenelse(econd, eif, eelse) ->
+ let (cond, earg) = self#select_condition econd in
+ begin match self#emit_expr env earg with
+ None -> None
+ | Some rarg ->
+ let (rif, sif) = self#emit_sequence env eif in
+ let (relse, selse) = self#emit_sequence env eelse in
+ let r = join rif sif relse selse in
+ self#insert (Iifthenelse(cond, sif#extract, selse#extract))
+ rarg [||];
+ r
+ end
+ | Cswitch(esel, index, ecases) ->
+ begin match self#emit_expr env esel with
+ None -> None
+ | Some rsel ->
+ let rscases = Array.map (self#emit_sequence env) ecases in
+ let r = join_array rscases in
+ self#insert (Iswitch(index,
+ Array.map (fun (r, s) -> s#extract) rscases))
+ rsel [||];
+ r
+ end
+ | Cloop(ebody) ->
+ let (rarg, sbody) = self#emit_sequence env ebody in
+ self#insert (Iloop(sbody#extract)) [||] [||];
+ Some [||]
+ | Ccatch(nfail, ids, e1, e2) ->
+ let rs =
+ List.map
+ (fun id ->
+ let r = self#regs_for typ_val in name_regs id r; r)
+ ids in
+ catch_regs := (nfail, Array.concat rs) :: !catch_regs ;
+ let (r1, s1) = self#emit_sequence env e1 in
+ catch_regs := List.tl !catch_regs ;
+ let new_env =
+ List.fold_left
+ (fun env (id,r) -> Tbl.add id r env)
+ env (List.combine ids rs) in
+ let (r2, s2) = self#emit_sequence new_env e2 in
+ let r = join r1 s1 r2 s2 in
+ self#insert (Icatch(nfail, s1#extract, s2#extract)) [||] [||];
+ r
+ | Cexit (nfail,args) ->
+ begin match self#emit_parts_list env args with
+ None -> None
+ | Some (simple_list, ext_env) ->
+ let src = self#emit_tuple ext_env simple_list in
+ let dest =
+ try List.assoc nfail !catch_regs
+ with Not_found ->
+ Misc.fatal_error
+ ("Selectgen.emit_expr, on exit("^string_of_int nfail^")") in
+ self#insert_moves src dest ;
+ self#insert (Iexit nfail) [||] [||];
+ None
+ end
+ | Ctrywith(e1, v, e2) ->
+ let (r1, s1) = self#emit_sequence env e1 in
+ let rv = self#regs_for typ_val in
+ let (r2, s2) = self#emit_sequence (Tbl.add v rv env) e2 in
+ let r = join r1 s1 r2 s2 in
+ self#insert
+ (Itrywith(s1#extract,
+ instr_cons (Iop Imove) [|Proc.loc_exn_bucket|] rv
+ (s2#extract)))
+ [||] [||];
+ r
+
+method private emit_sequence env exp =
+ let s = {< instr_seq = dummy_instr >} in
+ let r = s#emit_expr env exp in
+ (r, s)
+
+method private bind_let env v r1 =
+ if all_regs_anonymous r1 then begin
+ name_regs v r1;
+ Tbl.add v r1 env
+ end else begin
+ let rv = Reg.createv_like r1 in
+ name_regs v rv;
+ self#insert_moves r1 rv;
+ Tbl.add v rv env
+ end
+
+method private emit_parts env exp =
+ if self#is_simple_expr exp then
+ Some (exp, env)
+ else begin
+ match self#emit_expr env exp with
+ None -> None
+ | Some r ->
+ if Array.length r = 0 then
+ Some (Ctuple [], env)
+ else begin
+ (* The normal case *)
+ let id = Ident.create "bind" in
+ if all_regs_anonymous r then
+ (* r is an anonymous, unshared register; use it directly *)
+ Some (Cvar id, Tbl.add id r env)
+ else begin
+ (* Introduce a fresh temp to hold the result *)
+ let tmp = Reg.createv_like r in
+ self#insert_moves r tmp;
+ Some (Cvar id, Tbl.add id tmp env)
+ end
+ end
+ end
+
+method private emit_parts_list env exp_list =
+ match exp_list with
+ [] -> Some ([], env)
+ | exp :: rem ->
+ (* This ensures right-to-left evaluation, consistent with the
+ bytecode compiler *)
+ match self#emit_parts_list env rem with
+ None -> None
+ | Some(new_rem, new_env) ->
+ match self#emit_parts new_env exp with
+ None -> None
+ | Some(new_exp, fin_env) -> Some(new_exp :: new_rem, fin_env)
+
+method private emit_tuple_not_flattened env exp_list =
+ let rec emit_list = function
+ [] -> []
+ | exp :: rem ->
+ (* Again, force right-to-left evaluation *)
+ let loc_rem = emit_list rem in
+ match self#emit_expr env exp with
+ None -> assert false (* should have been caught in emit_parts *)
+ | Some loc_exp -> loc_exp :: loc_rem
+ in
+ emit_list exp_list
+
+method private emit_tuple env exp_list =
+ Array.concat (self#emit_tuple_not_flattened env exp_list)
+
+method emit_extcall_args env args =
+ let args = self#emit_tuple_not_flattened env args in
+ let arg_hard_regs, stack_ofs =
+ Proc.loc_external_arguments (Array.of_list args)
+ in
+ (* Flattening [args] and [arg_hard_regs] causes parts of values split
+ across multiple registers to line up correctly, by virtue of the
+ semantics of [split_int64_for_32bit_target] in cmmgen.ml, and the
+ required semantics of [loc_external_arguments] (see proc.mli). *)
+ let args = Array.concat args in
+ let arg_hard_regs = Array.concat (Array.to_list arg_hard_regs) in
+ self#insert_move_args args arg_hard_regs stack_ofs;
+ arg_hard_regs, stack_ofs
+
+method emit_stores env data regs_addr =
+ let a =
+ ref (Arch.offset_addressing Arch.identity_addressing (-Arch.size_int)) in
+ List.iter
+ (fun e ->
+ let (op, arg) = self#select_store false !a e in
+ match self#emit_expr env arg with
+ None -> assert false
+ | Some regs ->
+ match op with
+ Istore(_, _, _) ->
+ for i = 0 to Array.length regs - 1 do
+ let r = regs.(i) in
+ let kind = if r.typ = Float then Double_u else Word_val in
+ self#insert (Iop(Istore(kind, !a, false)))
+ (Array.append [|r|] regs_addr) [||];
+ a := Arch.offset_addressing !a (size_component r.typ)
+ done
+ | _ ->
+ self#insert (Iop op) (Array.append regs regs_addr) [||];
+ a := Arch.offset_addressing !a (size_expr env e))
+ data
+
+(* Same, but in tail position *)
+
+method private emit_return env exp =
+ match self#emit_expr env exp with
+ None -> ()
+ | Some r ->
+ let loc = Proc.loc_results r in
+ self#insert_moves r loc;
+ self#insert Ireturn loc [||]
+
+method emit_tail env exp =
+ match exp with
+ Clet(v, e1, e2) ->
+ begin match self#emit_expr env e1 with
+ None -> ()
+ | Some r1 -> self#emit_tail (self#bind_let env v r1) e2
+ end
+ | Cop(Capply(ty, dbg) as op, args) ->
+ begin match self#emit_parts_list env args with
+ None -> ()
+ | Some(simple_args, env) ->
+ let (new_op, new_args) = self#select_operation op simple_args in
+ match new_op with
+ Icall_ind ->
+ let r1 = self#emit_tuple env new_args in
+ let rarg = Array.sub r1 1 (Array.length r1 - 1) in
+ let (loc_arg, stack_ofs) = Proc.loc_arguments rarg in
+ if stack_ofs = 0 then begin
+ self#insert_moves rarg loc_arg;
+ self#insert (Iop Itailcall_ind)
+ (Array.append [|r1.(0)|] loc_arg) [||]
+ end else begin
+ let rd = self#regs_for ty in
+ let loc_res = Proc.loc_results rd in
+ self#insert_move_args rarg loc_arg stack_ofs;
+ self#insert_debug (Iop Icall_ind) dbg
+ (Array.append [|r1.(0)|] loc_arg) loc_res;
+ self#insert(Iop(Istackoffset(-stack_ofs))) [||] [||];
+ self#insert Ireturn loc_res [||]
+ end
+ | Icall_imm lbl ->
+ let r1 = self#emit_tuple env new_args in
+ let (loc_arg, stack_ofs) = Proc.loc_arguments r1 in
+ if stack_ofs = 0 then begin
+ self#insert_moves r1 loc_arg;
+ self#insert (Iop(Itailcall_imm lbl)) loc_arg [||]
+ end else if lbl = !current_function_name then begin
+ let loc_arg' = Proc.loc_parameters r1 in
+ self#insert_moves r1 loc_arg';
+ self#insert (Iop(Itailcall_imm lbl)) loc_arg' [||]
+ end else begin
+ let rd = self#regs_for ty in
+ let loc_res = Proc.loc_results rd in
+ self#insert_move_args r1 loc_arg stack_ofs;
+ self#insert_debug (Iop(Icall_imm lbl)) dbg loc_arg loc_res;
+ self#insert(Iop(Istackoffset(-stack_ofs))) [||] [||];
+ self#insert Ireturn loc_res [||]
+ end
+ | _ -> fatal_error "Selection.emit_tail"
+ end
+ | Csequence(e1, e2) ->
+ begin match self#emit_expr env e1 with
+ None -> ()
+ | Some r1 -> self#emit_tail env e2
+ end
+ | Cifthenelse(econd, eif, eelse) ->
+ let (cond, earg) = self#select_condition econd in
+ begin match self#emit_expr env earg with
+ None -> ()
+ | Some rarg ->
+ self#insert (Iifthenelse(cond, self#emit_tail_sequence env eif,
+ self#emit_tail_sequence env eelse))
+ rarg [||]
+ end
+ | Cswitch(esel, index, ecases) ->
+ begin match self#emit_expr env esel with
+ None -> ()
+ | Some rsel ->
+ self#insert
+ (Iswitch(index, Array.map (self#emit_tail_sequence env) ecases))
+ rsel [||]
+ end
+ | Ccatch(nfail, ids, e1, e2) ->
+ let rs =
+ List.map
+ (fun id ->
+ let r = self#regs_for typ_val in
+ name_regs id r ;
+ r)
+ ids in
+ catch_regs := (nfail, Array.concat rs) :: !catch_regs ;
+ let s1 = self#emit_tail_sequence env e1 in
+ catch_regs := List.tl !catch_regs ;
+ let new_env =
+ List.fold_left
+ (fun env (id,r) -> Tbl.add id r env)
+ env (List.combine ids rs) in
+ let s2 = self#emit_tail_sequence new_env e2 in
+ self#insert (Icatch(nfail, s1, s2)) [||] [||]
+ | Ctrywith(e1, v, e2) ->
+ let (opt_r1, s1) = self#emit_sequence env e1 in
+ let rv = self#regs_for typ_val in
+ let s2 = self#emit_tail_sequence (Tbl.add v rv env) e2 in
+ self#insert
+ (Itrywith(s1#extract,
+ instr_cons (Iop Imove) [|Proc.loc_exn_bucket|] rv s2))
+ [||] [||];
+ begin match opt_r1 with
+ None -> ()
+ | Some r1 ->
+ let loc = Proc.loc_results r1 in
+ self#insert_moves r1 loc;
+ self#insert Ireturn loc [||]
+ end
+ | _ ->
+ self#emit_return env exp
+
+method private emit_tail_sequence env exp =
+ let s = {< instr_seq = dummy_instr >} in
+ s#emit_tail env exp;
+ s#extract
+
+(* Sequentialization of a function definition *)
+
+method emit_fundecl f =
+ Proc.contains_calls := false;
+ current_function_name := f.Cmm.fun_name;
+ let rargs =
+ List.map
+ (fun (id, ty) -> let r = self#regs_for ty in name_regs id r; r)
+ f.Cmm.fun_args in
+ let rarg = Array.concat rargs in
+ let loc_arg = Proc.loc_parameters rarg in
+ let env =
+ List.fold_right2
+ (fun (id, ty) r env -> Tbl.add id r env)
+ f.Cmm.fun_args rargs Tbl.empty in
+ self#insert_moves loc_arg rarg;
+ self#emit_tail env f.Cmm.fun_body;
+ let body = self#extract in
+ instr_iter (fun instr -> self#mark_instr instr.Mach.desc) body;
+ { fun_name = f.Cmm.fun_name;
+ fun_args = loc_arg;
+ fun_body = body;
+ fun_fast = f.Cmm.fun_fast;
+ fun_dbg = f.Cmm.fun_dbg }
+
+end
+
+(* Tail call criterion (estimated). Assumes:
+- all arguments are of type "int" (always the case for OCaml function calls)
+- one extra argument representing the closure environment (conservative).
+*)
+
+let is_tail_call nargs =
+ assert (Reg.dummy.typ = Int);
+ let args = Array.make (nargs + 1) Reg.dummy in
+ let (loc_arg, stack_ofs) = Proc.loc_arguments args in
+ stack_ofs = 0
+
+let _ =
+ Simplif.is_tail_native_heuristic := is_tail_call
+
+let reset () =
+ catch_regs := [];
+ current_function_name := ""
diff --git a/asmcomp/selectgen.mli b/asmcomp/selectgen.mli
new file mode 100644
index 0000000000..499b9ea0fe
--- /dev/null
+++ b/asmcomp/selectgen.mli
@@ -0,0 +1,107 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Selection of pseudo-instructions, assignment of pseudo-registers,
+ sequentialization. *)
+
+type environment = (Ident.t, Reg.t array) Tbl.t
+
+val size_expr : environment -> Cmm.expression -> int
+
+class virtual selector_generic : object
+ (* The following methods must or can be overridden by the processor
+ description *)
+ method virtual is_immediate : int -> bool
+ (* Must be defined to indicate whether a constant is a suitable
+ immediate operand to arithmetic instructions *)
+ method virtual select_addressing :
+ Cmm.memory_chunk -> Cmm.expression -> Arch.addressing_mode * Cmm.expression
+ (* Must be defined to select addressing modes *)
+ method is_simple_expr: Cmm.expression -> bool
+ (* Can be overridden to reflect special extcalls known to be pure *)
+ method select_operation :
+ Cmm.operation ->
+ Cmm.expression list -> Mach.operation * Cmm.expression list
+ (* Can be overridden to deal with special arithmetic instructions *)
+ method select_condition : Cmm.expression -> Mach.test * Cmm.expression
+ (* Can be overridden to deal with special test instructions *)
+ method select_store :
+ bool -> Arch.addressing_mode -> Cmm.expression ->
+ Mach.operation * Cmm.expression
+ (* Can be overridden to deal with special store constant instructions *)
+ method regs_for : Cmm.machtype -> Reg.t array
+ (* Return an array of fresh registers of the given type.
+ Default implementation is like Reg.createv.
+ Can be overridden if float values are stored as pairs of
+ integer registers. *)
+ method insert_op :
+ Mach.operation -> Reg.t array -> Reg.t array -> Reg.t array
+ (* Can be overridden to deal with 2-address instructions
+ or instructions with hardwired input/output registers *)
+ method insert_op_debug :
+ Mach.operation -> Debuginfo.t -> Reg.t array -> Reg.t array -> Reg.t array
+ (* Can be overridden to deal with 2-address instructions
+ or instructions with hardwired input/output registers *)
+ method emit_extcall_args :
+ environment -> Cmm.expression list -> Reg.t array * int
+ (* Can be overridden to deal with stack-based calling conventions *)
+ method emit_stores :
+ environment -> Cmm.expression list -> Reg.t array -> unit
+ (* Fill a freshly allocated block. Can be overridden for architectures
+ that do not provide Arch.offset_addressing. *)
+
+ method mark_call : unit
+ (* informs the code emitter that the current function is non-leaf:
+ it may perform a (non-tail) call; by default, sets
+ [Proc.contains_calls := true] *)
+
+ method mark_tailcall : unit
+ (* informs the code emitter that the current function may end with
+ a tail-call; by default, does nothing *)
+
+ method mark_c_tailcall : unit
+ (* informs the code emitter that the current function may call
+ a C function that never returns; by default, does nothing.
+
+ It is unecessary to save the stack pointer in this situation
+ (which is the main purpose of tracking leaf functions) but some
+ architectures still need to ensure that the stack is properly
+ aligned when the C function is called. This is achieved by
+ overloading this method to set [Proc.contains_calls := true] *)
+
+ method mark_instr : Mach.instruction_desc -> unit
+ (* dispatches on instructions to call one of the marking function
+ above; overloading this is useful if Ispecific instructions need
+ marking *)
+
+ (* The following method is the entry point and should not be overridden *)
+ method emit_fundecl : Cmm.fundecl -> Mach.fundecl
+
+ (* The following methods should not be overridden. They cannot be
+ declared "private" in the current implementation because they
+ are not always applied to "self", but ideally they should be private. *)
+ method extract : Mach.instruction
+ method insert : Mach.instruction_desc -> Reg.t array -> Reg.t array -> unit
+ method insert_debug : Mach.instruction_desc -> Debuginfo.t ->
+ Reg.t array -> Reg.t array -> unit
+ method insert_move : Reg.t -> Reg.t -> unit
+ method insert_move_args : Reg.t array -> Reg.t array -> int -> unit
+ method insert_move_results : Reg.t array -> Reg.t array -> int -> unit
+ method insert_moves : Reg.t array -> Reg.t array -> unit
+ method adjust_type : Reg.t -> Reg.t -> unit
+ method adjust_types : Reg.t array -> Reg.t array -> unit
+ method emit_expr :
+ (Ident.t, Reg.t array) Tbl.t -> Cmm.expression -> Reg.t array option
+ method emit_tail : (Ident.t, Reg.t array) Tbl.t -> Cmm.expression -> unit
+end
+
+val reset : unit -> unit
diff --git a/asmcomp/selection.mli b/asmcomp/selection.mli
new file mode 100644
index 0000000000..f1c9e34ce8
--- /dev/null
+++ b/asmcomp/selection.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Selection of pseudo-instructions, assignment of pseudo-registers,
+ sequentialization. *)
+
+val fundecl: Cmm.fundecl -> Mach.fundecl
diff --git a/asmcomp/sparc/CSE.ml b/asmcomp/sparc/CSE.ml
new file mode 100644
index 0000000000..e48d604365
--- /dev/null
+++ b/asmcomp/sparc/CSE.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* CSE for Sparc *)
+
+open Mach
+open CSEgen
+
+class cse = object (self)
+
+inherit cse_generic (* as super *)
+
+method! is_cheap_operation op =
+ match op with
+ | Iconst_int n | Iconst_blockheader n -> n <= 4095n && n >= -4096n
+ | _ -> false
+
+end
+
+let fundecl f =
+ (new cse)#fundecl f
diff --git a/asmcomp/sparc/arch.ml b/asmcomp/sparc/arch.ml
new file mode 100644
index 0000000000..f5c069366b
--- /dev/null
+++ b/asmcomp/sparc/arch.ml
@@ -0,0 +1,78 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Specific operations for the Sparc processor *)
+
+open Format
+
+(* SPARC V8 adds multiply and divide.
+ SPARC V9 adds double precision float operations, conditional
+ move, and more instructions that are only useful in 64 bit mode.
+ Sun calls 32 bit V9 "V8+". *)
+type arch_version = SPARC_V7 | SPARC_V8 | SPARC_V9
+
+let arch_version = ref SPARC_V7
+
+let command_line_options =
+ [ "-march=v8", Arg.Unit (fun () -> arch_version := SPARC_V8),
+ " Generate code for SPARC V8 processors";
+ "-march=v9", Arg.Unit (fun () -> arch_version := SPARC_V9),
+ " Generate code for SPARC V9 processors" ]
+
+type specific_operation = unit (* None worth mentioning *)
+
+(* Addressing modes *)
+
+type addressing_mode =
+ Ibased of string * int (* symbol + displ *)
+ | Iindexed of int (* reg + displ *)
+
+(* Sizes, endianness *)
+
+let big_endian = true
+
+let size_addr = 4
+let size_int = 4
+let size_float = 8
+
+let allow_unaligned_access = false
+
+(* Behavior of division *)
+
+let division_crashes_on_overflow = false
+
+(* Operations on addressing modes *)
+
+let identity_addressing = Iindexed 0
+
+let offset_addressing addr delta =
+ match addr with
+ Ibased(s, n) -> Ibased(s, n + delta)
+ | Iindexed n -> Iindexed(n + delta)
+
+let num_args_addressing = function
+ Ibased(s, n) -> 0
+ | Iindexed n -> 1
+
+(* Printing operations and addressing modes *)
+
+let print_addressing printreg addr ppf arg =
+ match addr with
+ | Ibased(s, n) ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "\"%s\"%s" s idx
+ | Iindexed n ->
+ let idx = if n <> 0 then Printf.sprintf " + %i" n else "" in
+ fprintf ppf "%a%s" printreg arg.(0) idx
+
+let print_specific_operation printreg op ppf arg =
+ Misc.fatal_error "Arch_sparc.print_specific_operation"
diff --git a/asmcomp/sparc/emit.mlp b/asmcomp/sparc/emit.mlp
new file mode 100644
index 0000000000..b29278fdf2
--- /dev/null
+++ b/asmcomp/sparc/emit.mlp
@@ -0,0 +1,768 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Emission of Sparc assembly code *)
+
+open Misc
+open Cmm
+open Arch
+open Proc
+open Reg
+open Mach
+open Linearize
+open Emitaux
+
+(* Solaris vs. the other ports *)
+
+let solaris = Config.system = "solaris"
+
+(* Tradeoff between code size and code speed *)
+
+let fastcode_flag = ref true
+
+(* Layout of the stack *)
+(* Always keep the stack 8-aligned.
+ Always leave 96 bytes at the bottom of the stack *)
+
+let stack_offset = ref 0
+
+let frame_size () =
+ let size =
+ !stack_offset +
+ 4 * num_stack_slots.(0) + 8 * num_stack_slots.(1) +
+ (if !contains_calls then 4 else 0) in
+ Misc.align size 8
+
+let slot_offset loc cl =
+ match loc with
+ Incoming n -> frame_size() + n + 96
+ | Local n ->
+ if cl = 0
+ then !stack_offset + num_stack_slots.(1) * 8 + n * 4 + 96
+ else !stack_offset + n * 8 + 96
+ | Outgoing n -> n + 96
+
+(* Return the other register in a register pair *)
+
+let next_in_pair = function
+ {loc = Reg r; typ = (Int | Addr | Val)} -> phys_reg (r + 1)
+ | {loc = Reg r; typ = Float} -> phys_reg (r + 16)
+ | _ -> fatal_error "Emit.next_in_pair"
+
+(* Symbols are prefixed with _ under SunOS *)
+
+let symbol_prefix =
+ if Config.system = "sunos" then "_" else ""
+
+let emit_symbol s =
+ if String.length s >= 1 && s.[0] = '.'
+ then emit_string s
+ else begin emit_string symbol_prefix; Emitaux.emit_symbol '$' s end
+
+let emit_size lbl =
+ if Config.system = "solaris" then
+ ` .size {emit_symbol lbl},.-{emit_symbol lbl}\n`
+
+let rodata () =
+ if Config.system = "solaris" (* || Config.system = "linux" *)
+ (* || Config.system = "gnu" *) then
+ ` .section \".rodata\"\n`
+ else
+ ` .data\n`
+
+(* Check if an integer or native integer is an immediate operand *)
+
+let is_immediate n =
+ n <= 4095 && n >= -4096
+
+let is_native_immediate n =
+ n <= Nativeint.of_int 4095 && n >= Nativeint.of_int (-4096)
+
+(* Output a label *)
+
+let label_prefix =
+ if Config.system = "sunos" then "L" else ".L"
+
+let emit_label lbl =
+ emit_string label_prefix; emit_int lbl
+
+let emit_data_label lbl =
+ emit_string label_prefix; emit_string "d"; emit_int lbl
+
+(* Output a pseudo-register *)
+
+let emit_reg r =
+ match r.loc with
+ Reg r -> emit_string (register_name r)
+ | _ -> fatal_error "Emit.emit_reg"
+
+(* Output a stack reference *)
+
+let emit_stack r =
+ match r.loc with
+ Stack s ->
+ let ofs = slot_offset s (register_class r) in `[%sp + {emit_int ofs}]`
+ | _ -> fatal_error "Emit.emit_stack"
+
+(* Output a load *)
+
+let emit_load instr addr arg dst =
+ match addr with
+ Ibased(s, 0) ->
+ ` sethi %hi({emit_symbol s}), %g1\n`;
+ ` {emit_string instr} [%g1 + %lo({emit_symbol s})], {emit_reg dst}\n`
+ | Ibased(s, ofs) ->
+ ` sethi %hi({emit_symbol s} + {emit_int ofs}), %g1\n`;
+ ` {emit_string instr} [%g1 + %lo({emit_symbol s} + {emit_int ofs})], {emit_reg dst}\n`
+ | Iindexed ofs ->
+ if is_immediate ofs then
+ ` {emit_string instr} [{emit_reg arg.(0)} + {emit_int ofs}], {emit_reg dst}\n`
+ else begin
+ ` sethi %hi({emit_int ofs}), %g1\n`;
+ ` or %g1, %lo({emit_int ofs}), %g1\n`;
+ ` {emit_string instr} [{emit_reg arg.(0)} + %g1], {emit_reg dst}\n`
+ end
+
+(* Output a store *)
+
+let emit_store instr addr arg src =
+ match addr with
+ Ibased(s, 0) ->
+ ` sethi %hi({emit_symbol s}), %g1\n`;
+ ` {emit_string instr} {emit_reg src}, [%g1 + %lo({emit_symbol s})]\n`
+ | Ibased(s, ofs) ->
+ ` sethi %hi({emit_symbol s} + {emit_int ofs}), %g1\n`;
+ ` {emit_string instr} {emit_reg src}, [%g1 + %lo({emit_symbol s} + {emit_int ofs})]\n`
+ | Iindexed ofs ->
+ if is_immediate ofs then
+ ` {emit_string instr} {emit_reg src}, [{emit_reg arg.(1)} + {emit_int ofs}]\n`
+ else begin
+ ` sethi %hi({emit_int ofs}), %g1\n`;
+ ` or %g1, %lo({emit_int ofs}), %g1\n`;
+ ` {emit_string instr} {emit_reg src}, [{emit_reg arg.(1)} + %g1]\n`
+ end
+
+(* Record live pointers at call points *)
+
+type frame_descr =
+ { fd_lbl: int; (* Return address *)
+ fd_frame_size: int; (* Size of stack frame *)
+ fd_live_offset: int list } (* Offsets/regs of live addresses *)
+
+let frame_descriptors = ref([] : frame_descr list)
+
+let record_frame live =
+ let lbl = new_label() in
+ let live_offset = ref [] in
+ Reg.Set.iter
+ (function
+ | {typ = Val; loc = Reg r} ->
+ live_offset := ((r lsl 1) + 1) :: !live_offset
+ | {typ = Val; loc = Stack s} as reg ->
+ live_offset := slot_offset s (register_class reg) :: !live_offset
+ | {typ = Addr} as r ->
+ Misc.fatal_error ("bad GC root " ^ Reg.name r)
+ | _ -> ())
+ live;
+ frame_descriptors :=
+ { fd_lbl = lbl;
+ fd_frame_size = frame_size();
+ fd_live_offset = !live_offset } :: !frame_descriptors;
+ `{emit_label lbl}:`
+
+let emit_frame fd =
+ ` .word {emit_label fd.fd_lbl}\n`;
+ ` .half {emit_int fd.fd_frame_size}\n`;
+ ` .half {emit_int (List.length fd.fd_live_offset)}\n`;
+ List.iter
+ (fun n ->
+ ` .half {emit_int n}\n`)
+ fd.fd_live_offset;
+ ` .align 4\n`
+
+(* Record floating-point constants *)
+
+let float_constants = ref ([] : (int * int64) list)
+
+let emit_float_constant (lbl, cst) =
+ rodata ();
+ ` .align 8\n`;
+ `{emit_label lbl}:`;
+ emit_float64_split_directive ".word" cst
+
+(* Emission of the profiling prelude *)
+let emit_profile () =
+ begin match Config.system with
+ "solaris" ->
+ let lbl = new_label() in
+ ` .section \".bss\"\n`;
+ `{emit_label lbl}: .skip 4\n`;
+ ` .text\n`;
+ ` save %sp,-96,%sp\n`;
+ ` sethi %hi({emit_label lbl}),%o0\n`;
+ ` call _mcount\n`;
+ ` or %o0,%lo({emit_label lbl}),%o0\n`;
+ ` restore\n`
+ | _ -> ()
+ end
+
+(* Names of various instructions *)
+
+let name_for_int_operation = function
+ Iadd -> "add"
+ | Isub -> "sub"
+ | Iand -> "and"
+ | Ior -> "or"
+ | Ixor -> "xor"
+ | Ilsl -> "sll"
+ | Ilsr -> "srl"
+ | Iasr -> "sra"
+ | Imul -> "smul"
+ | _ -> Misc.fatal_error "Emit.name_for_int_operation"
+
+let name_for_float_operation = function
+ Inegf -> if !arch_version = SPARC_V9 then "fnegd" else "fnegs"
+ | Iabsf -> if !arch_version = SPARC_V9 then "fabsd" else "fabss"
+ | Iaddf -> "faddd"
+ | Isubf -> "fsubd"
+ | Imulf -> "fmuld"
+ | Idivf -> "fdivd"
+ | _ -> Misc.fatal_error "Emit.name_for_float_operation"
+
+let name_for_int_movcc = function
+ Isigned Ceq -> "e" | Isigned Cne -> "ne"
+ | Isigned Cle -> "le" | Isigned Cgt -> "g"
+ | Isigned Clt -> "l" | Isigned Cge -> "ge"
+ | Iunsigned Ceq -> "e" | Iunsigned Cne -> "ne"
+ | Iunsigned Cle -> "leu" | Iunsigned Cgt -> "gu"
+ | Iunsigned Clt -> "lu" | Iunsigned Cge -> "geu"
+
+let name_for_int_comparison = function
+ Isigned Ceq -> "be" | Isigned Cne -> "bne"
+ | Isigned Cle -> "ble" | Isigned Cgt -> "bg"
+ | Isigned Clt -> "bl" | Isigned Cge -> "bge"
+ | Iunsigned Ceq -> "be" | Iunsigned Cne -> "bne"
+ | Iunsigned Cle -> "bleu" | Iunsigned Cgt -> "bgu"
+ | Iunsigned Clt -> "blu" | Iunsigned Cge -> "bgeu"
+
+let name_for_float_comparison cmp neg =
+ match cmp with
+ Ceq -> if neg then "fbne" else "fbe"
+ | Cne -> if neg then "fbe" else "fbne"
+ | Cle -> if neg then "fbug" else "fble"
+ | Cgt -> if neg then "fbule" else "fbg"
+ | Clt -> if neg then "fbuge" else "fbl"
+ | Cge -> if neg then "fbul" else "fbge"
+
+(* Output the assembly code for an instruction *)
+
+let function_name = ref ""
+let tailrec_entry_point = ref 0
+let range_check_trap = ref 0
+
+let rec emit_instr i dslot =
+ match i.desc with
+ Lend -> ()
+ | Lop(Imove | Ispill | Ireload) ->
+ let src = i.arg.(0) and dst = i.res.(0) in
+ begin match (src, dst) with
+ {loc = Reg rs; typ = (Int | Addr | Val)}, {loc = Reg rd} ->
+ ` mov {emit_reg src}, {emit_reg dst}\n`
+ | {loc = Reg rs; typ = Float}, {loc = Reg rd; typ = Float} ->
+ if !arch_version = SPARC_V9 then
+ ` fmovd {emit_reg src}, {emit_reg dst}\n`
+ else begin
+ ` fmovs {emit_reg src}, {emit_reg dst}\n`;
+ ` fmovs {emit_reg(next_in_pair src)}, {emit_reg(next_in_pair dst)}\n`
+ end
+ | {loc = Reg rs; typ = Float}, {loc = Reg rd; typ = (Int | Addr | Val)} ->
+ (* This happens when calling C functions and passing a float arg
+ in %o0...%o5 *)
+ ` sub %sp, 8, %sp\n`;
+ ` std {emit_reg src}, [%sp + 96]\n`;
+ ` ld [%sp + 96], {emit_reg dst}\n`;
+ let dst2 = i.res.(1) in
+ begin match dst2 with
+ | {loc = Reg _; typ = Int} ->
+ ` ld [%sp + 100], {emit_reg dst2}\n`;
+ | {loc = Stack _; typ = Int} ->
+ ` ld [%sp + 100], %g1\n`;
+ ` st %g1, {emit_stack dst2}\n`;
+ | _ ->
+ fatal_error "Emit: Imove Float [| _; _ |]"
+ end;
+ ` add %sp, 8, %sp\n`
+ | {loc = Reg rs; typ = (Int | Addr | Val)}, {loc = Stack sd} ->
+ ` st {emit_reg src}, {emit_stack dst}\n`
+ | {loc = Reg rs; typ = Float}, {loc = Stack sd} ->
+ ` std {emit_reg src}, {emit_stack dst}\n`
+ | {loc = Stack ss; typ = (Int | Addr | Val)}, {loc = Reg rd} ->
+ ` ld {emit_stack src}, {emit_reg dst}\n`
+ | {loc = Stack ss; typ = Float}, {loc = Reg rd} ->
+ ` ldd {emit_stack src}, {emit_reg dst}\n`
+ | (_, _) ->
+ fatal_error "Emit: Imove"
+ end
+ | Lop(Iconst_int n | Iconst_blockheader n) ->
+ if is_native_immediate n then
+ ` mov {emit_nativeint n}, {emit_reg i.res.(0)}\n`
+ else begin
+ ` sethi %hi({emit_nativeint n}), %g1\n`;
+ ` or %g1, %lo({emit_nativeint n}), {emit_reg i.res.(0)}\n`
+ end
+ | Lop(Iconst_float f) ->
+ (* On UltraSPARC, the fzero instruction could be used to set a
+ floating point register pair to zero. *)
+ let lbl = new_label() in
+ float_constants := (lbl, Int64.bits_of_float f) :: !float_constants;
+ ` sethi %hi({emit_label lbl}), %g1\n`;
+ ` ldd [%g1 + %lo({emit_label lbl})], {emit_reg i.res.(0)}\n`
+ | Lop(Iconst_symbol s) ->
+ ` sethi %hi({emit_symbol s}), %g1\n`;
+ ` or %g1, %lo({emit_symbol s}), {emit_reg i.res.(0)}\n`
+ | Lop(Icall_ind) ->
+ `{record_frame i.live} call {emit_reg i.arg.(0)}\n`;
+ fill_delay_slot dslot
+ | Lop(Icall_imm s) ->
+ `{record_frame i.live} call {emit_symbol s}\n`;
+ fill_delay_slot dslot
+ | Lop(Itailcall_ind) ->
+ let n = frame_size() in
+ if !contains_calls then
+ ` ld [%sp + {emit_int(n - 4 + 96)}], %o7\n`;
+ ` jmp {emit_reg i.arg.(0)}\n`;
+ ` add %sp, {emit_int n}, %sp\n` (* in delay slot *)
+ | Lop(Itailcall_imm s) ->
+ let n = frame_size() in
+ if s = !function_name then begin
+ ` b {emit_label !tailrec_entry_point}\n`;
+ fill_delay_slot dslot
+ end else begin
+ if !contains_calls then
+ ` ld [%sp + {emit_int(n - 4 + 96)}], %o7\n`;
+ ` sethi %hi({emit_symbol s}), %g1\n`;
+ ` jmp %g1 + %lo({emit_symbol s})\n`;
+ ` add %sp, {emit_int n}, %sp\n` (* in delay slot *)
+ end
+ | Lop(Iextcall(s, alloc)) ->
+ if alloc then begin
+ ` sethi %hi({emit_symbol s}), %g2\n`;
+ `{record_frame i.live} call {emit_symbol "caml_c_call"}\n`;
+ ` or %g2, %lo({emit_symbol s}), %g2\n` (* in delay slot *)
+ end else begin
+ ` call {emit_symbol s}\n`;
+ fill_delay_slot dslot
+ end
+ | Lop(Istackoffset n) ->
+ ` add %sp, {emit_int (-n)}, %sp\n`;
+ stack_offset := !stack_offset + n
+ | Lop(Iload(chunk, addr)) ->
+ let dest = i.res.(0) in
+ begin match chunk with
+ Double_u ->
+ emit_load "ld" addr i.arg dest;
+ emit_load "ld" (offset_addressing addr 4) i.arg (next_in_pair dest)
+ | Single ->
+ emit_load "ld" addr i.arg dest;
+ ` fstod {emit_reg dest}, {emit_reg dest}\n`
+ | _ ->
+ let loadinstr =
+ match chunk with
+ Byte_unsigned -> "ldub"
+ | Byte_signed -> "ldsb"
+ | Sixteen_unsigned -> "lduh"
+ | Sixteen_signed -> "ldsh"
+ | Double -> "ldd"
+ | _ -> "ld" in
+ emit_load loadinstr addr i.arg dest
+ end
+ | Lop(Istore(chunk, addr, _)) ->
+ let src = i.arg.(0) in
+ begin match chunk with
+ Double_u ->
+ emit_store "st" addr i.arg src;
+ emit_store "st" (offset_addressing addr 4) i.arg (next_in_pair src)
+ | Single ->
+ ` fdtos {emit_reg src}, %f30\n`;
+ emit_store "st" addr i.arg (phys_reg 115) (* %f30 *)
+ | _ ->
+ let storeinstr =
+ match chunk with
+ | Byte_unsigned | Byte_signed -> "stb"
+ | Sixteen_unsigned | Sixteen_signed -> "sth"
+ | Double -> "std"
+ | _ -> "st" in
+ emit_store storeinstr addr i.arg src
+ end
+ | Lop(Ialloc n) ->
+ if !fastcode_flag then begin
+ let lbl_cont = new_label() in
+ if solaris then begin
+ ` sub %l6, {emit_int n}, %l6\n`;
+ ` cmp %l6, %l7\n`
+ end else begin
+ ` ld [%l7], %g1\n`;
+ ` sub %l6, {emit_int n}, %l6\n`;
+ ` cmp %l6, %g1\n`
+ end;
+ ` bgeu {emit_label lbl_cont}\n`;
+ ` add %l6, 4, {emit_reg i.res.(0)}\n`; (* in delay slot *)
+ `{record_frame i.live} call {emit_symbol "caml_call_gc"}\n`;
+ ` mov {emit_int n}, %g2\n`; (* in delay slot *)
+ ` add %l6, 4, {emit_reg i.res.(0)}\n`;
+ `{emit_label lbl_cont}:\n`
+ end else begin
+ `{record_frame i.live} call {emit_symbol "caml_allocN"}\n`;
+ ` mov {emit_int n}, %g2\n`; (* in delay slot *)
+ ` add %l6, 4, {emit_reg i.res.(0)}\n`
+ end
+ | Lop(Iintop(Icomp cmp)) ->
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ if !arch_version = SPARC_V9 then begin
+ let comp = name_for_int_movcc cmp in
+ ` mov 0, {emit_reg i.res.(0)}\n`;
+ ` mov{emit_string comp} %icc, 1, {emit_reg i.res.(0)}\n`
+ end
+ else begin
+ let comp = name_for_int_comparison cmp
+ and lbl = new_label() in
+ ` {emit_string comp},a {emit_label lbl}\n`;
+ ` mov 1, {emit_reg i.res.(0)}\n`;
+ ` mov 0, {emit_reg i.res.(0)}\n`;
+ `{emit_label lbl}:\n`
+ end
+ | Lop(Iintop Icheckbound) ->
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ if solaris then
+ ` tleu 5\n` (* 5 = ST_RANGE_CHECK *)
+ else begin
+ if !range_check_trap = 0 then range_check_trap := new_label();
+ ` bleu {emit_label !range_check_trap}\n`;
+ ` nop\n` (* delay slot *)
+ end
+ | Lop(Iintop Idiv) ->
+ ` sra {emit_reg i.arg.(0)}, 31, %g1\n`;
+ ` wr %g1, %y\n`;
+ ` sdiv {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.res.(0)}\n`
+ | Lop(Iintop Imulh) ->
+ ` smul {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, %g1\n`;
+ ` rd %y, {emit_reg i.res.(0)}\n`
+ | Lop(Iintop op) ->
+ let instr = name_for_int_operation op in
+ ` {emit_string instr} {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.res.(0)}\n`
+ | Lop(Iintop_imm(Ilsl, 1)) ->
+ (* UltraSPARC has two add units but only one shifter. *)
+ ` add {emit_reg i.arg.(0)}, {emit_reg i.arg.(0)}, {emit_reg i.res.(0)}\n`
+ | Lop(Iintop_imm(Icomp cmp, n)) ->
+ ` cmp {emit_reg i.arg.(0)}, {emit_int n}\n`;
+ if !arch_version = SPARC_V9 then begin
+ let comp = name_for_int_movcc cmp in
+ ` mov 0, {emit_reg i.res.(0)}\n`;
+ ` mov{emit_string comp} %icc, 1, {emit_reg i.res.(0)}\n`
+ end else begin
+ let comp = name_for_int_comparison cmp
+ and lbl = new_label() in
+ ` {emit_string comp},a {emit_label lbl}\n`;
+ ` mov 1, {emit_reg i.res.(0)}\n`;
+ ` mov 0, {emit_reg i.res.(0)}\n`;
+ `{emit_label lbl}:\n`
+ end
+ | Lop(Iintop_imm(Icheckbound, n)) ->
+ ` cmp {emit_reg i.arg.(0)}, {emit_int n}\n`;
+ if solaris then
+ ` tleu 5\n` (* 5 = ST_RANGE_CHECK *)
+ else begin
+ if !range_check_trap = 0 then range_check_trap := new_label();
+ ` bleu {emit_label !range_check_trap}\n`;
+ ` nop\n` (* delay slot *)
+ end
+ | Lop(Iintop_imm(Imulh, n)) ->
+ ` smul {emit_reg i.arg.(0)}, {emit_int n}, %g1\n`;
+ ` rd %y, {emit_reg i.res.(0)}\n`
+ | Lop(Iintop_imm(op, n)) ->
+ let instr = name_for_int_operation op in
+ ` {emit_string instr} {emit_reg i.arg.(0)}, {emit_int n}, {emit_reg i.res.(0)}\n`
+ | Lop(Inegf | Iabsf as op) ->
+ let instr = name_for_float_operation op in
+ ` {emit_string instr} {emit_reg i.arg.(0)}, {emit_reg i.res.(0)}\n`;
+ if !arch_version <> SPARC_V9 then
+ ` fmovs {emit_reg(next_in_pair i.arg.(0))}, {emit_reg(next_in_pair i.res.(0))}\n`
+ | Lop(Iaddf | Isubf | Imulf | Idivf as op) ->
+ let instr = name_for_float_operation op in
+ ` {emit_string instr} {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}, {emit_reg i.res.(0)}\n`
+ | Lop(Ifloatofint) ->
+ ` sub %sp, 8, %sp\n`;
+ ` st {emit_reg i.arg.(0)}, [%sp + 96]\n`;
+ ` ld [%sp + 96], %f30\n`;
+ ` add %sp, 8, %sp\n`;
+ ` fitod %f30, {emit_reg i.res.(0)}\n`
+ | Lop(Iintoffloat) ->
+ ` fdtoi {emit_reg i.arg.(0)}, %f30\n`;
+ ` sub %sp, 8, %sp\n`;
+ ` st %f30, [%sp + 96]\n`;
+ ` ld [%sp + 96], {emit_reg i.res.(0)}\n`;
+ ` add %sp, 8, %sp\n`
+ | Lop(Ispecific sop) ->
+ assert false
+ | Lreloadretaddr ->
+ let n = frame_size() in
+ ` ld [%sp + {emit_int(n - 4 + 96)}], %o7\n`
+ | Lreturn ->
+ let n = frame_size() in
+ ` retl\n`;
+ if n = 0 then
+ ` nop\n`
+ else
+ ` add %sp, {emit_int n}, %sp\n`
+ | Llabel lbl ->
+ `{emit_label lbl}:\n`
+ | Lbranch lbl ->
+ ` b {emit_label lbl}\n`;
+ fill_delay_slot dslot
+ | Lcondbranch(tst, lbl) ->
+ begin match tst with
+ Itruetest ->
+ ` tst {emit_reg i.arg.(0)}\n`;
+ ` bne {emit_label lbl}\n`
+ | Ifalsetest ->
+ ` tst {emit_reg i.arg.(0)}\n`;
+ ` be {emit_label lbl}\n`
+ | Iinttest cmp ->
+ let comp = name_for_int_comparison cmp in
+ ` cmp {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` {emit_string comp} {emit_label lbl}\n`
+ | Iinttest_imm(cmp, n) ->
+ let comp = name_for_int_comparison cmp in
+ ` cmp {emit_reg i.arg.(0)}, {emit_int n}\n`;
+ ` {emit_string comp} {emit_label lbl}\n`
+ | Ifloattest(cmp, neg) ->
+ let comp = name_for_float_comparison cmp neg in
+ ` fcmpd {emit_reg i.arg.(0)}, {emit_reg i.arg.(1)}\n`;
+ ` nop\n`;
+ ` {emit_string comp} {emit_label lbl}\n`
+ | Ioddtest ->
+ ` andcc {emit_reg i.arg.(0)}, 1, %g0\n`;
+ ` bne {emit_label lbl}\n`
+ | Ieventest ->
+ ` andcc {emit_reg i.arg.(0)}, 1, %g0\n`;
+ ` be {emit_label lbl}\n`
+ end;
+ fill_delay_slot dslot
+ | Lcondbranch3(lbl0, lbl1, lbl2) ->
+ ` cmp {emit_reg i.arg.(0)}, 1\n`;
+ begin match lbl0 with
+ None -> ()
+ | Some lbl -> ` bl {emit_label lbl}\n nop\n`
+ end;
+ begin match lbl1 with
+ None -> ()
+ | Some lbl -> ` be {emit_label lbl}\n nop\n`
+ end;
+ begin match lbl2 with
+ None -> ()
+ | Some lbl -> ` bg {emit_label lbl}\n nop\n`
+ end
+ | Lswitch jumptbl ->
+ let lbl_jumptbl = new_label() in
+ ` sethi %hi({emit_label lbl_jumptbl}), %g1\n`;
+ ` or %g1, %lo({emit_label lbl_jumptbl}), %g1\n`;
+ ` sll {emit_reg i.arg.(0)}, 2, %g2\n`;
+ ` ld [%g1 + %g2], %g1\n`;
+ ` jmp %g1\n`; (* poor scheduling *)
+ ` nop\n`;
+ `{emit_label lbl_jumptbl}:`;
+ for i = 0 to Array.length jumptbl - 1 do
+ ` .word {emit_label jumptbl.(i)}\n`
+ done
+ | Lsetuptrap lbl ->
+ ` call {emit_label lbl}\n`;
+ ` sub %sp, 8, %sp\n` (* in delay slot *)
+ | Lpushtrap ->
+ stack_offset := !stack_offset + 8;
+ ` st %o7, [%sp + 96]\n`;
+ ` st %l5, [%sp + 100]\n`;
+ ` mov %sp, %l5\n`
+ | Lpoptrap ->
+ ` ld [%sp + 100], %l5\n`;
+ ` add %sp, 8, %sp\n`;
+ stack_offset := !stack_offset - 8
+ | Lraise _ ->
+ ` ld [%l5 + 96], %g1\n`;
+ ` mov %l5, %sp\n`;
+ ` ld [%sp + 100], %l5\n`;
+ ` jmp %g1 + 8\n`;
+ ` add %sp, 8, %sp\n`
+
+and fill_delay_slot = function
+ None -> ` nop\n`
+ | Some i -> emit_instr i None
+
+(* Checks if a pseudo-instruction expands to exactly one machine instruction
+ that does not branch. *)
+
+let is_one_instr_op = function
+ Imulh | Idiv | Imod | Icomp _ | Icheckbound -> false
+ | _ -> true
+
+let is_one_instr i =
+ match i.desc with
+ Lop op ->
+ begin match op with
+ Imove | Ispill | Ireload ->
+ i.arg.(0).typ <> Float && i.res.(0).typ <> Float
+ | Iconst_int n | Iconst_blockheader n -> is_native_immediate n
+ | Istackoffset _ -> true
+ | Iload(_, Iindexed n) -> i.res.(0).typ <> Float && is_immediate n
+ | Istore(_, Iindexed n, _) -> i.arg.(0).typ <> Float && is_immediate n
+ | Iintop(op) -> is_one_instr_op op
+ | Iintop_imm(op, _) -> is_one_instr_op op
+ | Iaddf | Isubf | Imulf | Idivf -> true
+ | Iabsf | Inegf -> !arch_version = SPARC_V9
+ | _ -> false
+ end
+ | _ -> false
+
+let no_interference res arg =
+ try
+ for i = 0 to Array.length arg - 1 do
+ for j = 0 to Array.length res - 1 do
+ if arg.(i).loc = res.(j).loc then raise Exit
+ done
+ done;
+ true
+ with Exit ->
+ false
+
+(* Emit a sequence of instructions, trying to fill delay slots for branches *)
+
+let rec emit_all i =
+ match i with
+ {desc = Lend} -> ()
+ | {next = {desc = Lop(Icall_imm _) | Lop(Iextcall(_, false)) | Lbranch _}}
+ when is_one_instr i ->
+ emit_instr i.next (Some i);
+ emit_all i.next.next
+ | {next = {desc = Lop(Itailcall_imm s)}}
+ when s = !function_name && is_one_instr i ->
+ emit_instr i.next (Some i);
+ emit_all i.next.next
+ | {next = {desc = Lop(Icall_ind)}}
+ when is_one_instr i && no_interference i.res i.next.arg ->
+ emit_instr i.next (Some i);
+ emit_all i.next.next
+ | {next = {desc = Lcondbranch(_, _)}}
+ when is_one_instr i && no_interference i.res i.next.arg ->
+ emit_instr i.next (Some i);
+ emit_all i.next.next
+ | _ ->
+ emit_instr i None;
+ emit_all i.next
+
+(* Emission of a function declaration *)
+
+let fundecl fundecl =
+ function_name := fundecl.fun_name;
+ fastcode_flag := fundecl.fun_fast;
+ tailrec_entry_point := new_label();
+ range_check_trap := 0;
+ stack_offset := 0;
+ float_constants := [];
+ ` .text\n`;
+ ` .align 4\n`;
+ ` .global {emit_symbol fundecl.fun_name}\n`;
+ if Config.system = "solaris" then
+ ` .type {emit_symbol fundecl.fun_name},#function\n`;
+ `{emit_symbol fundecl.fun_name}:\n`;
+ if !Clflags.gprofile then emit_profile();
+ let n = frame_size() in
+ if n > 0 then
+ ` sub %sp, {emit_int n}, %sp\n`;
+ if !contains_calls then
+ ` st %o7, [%sp + {emit_int(n - 4 + 96)}]\n`;
+ `{emit_label !tailrec_entry_point}:\n`;
+ emit_all fundecl.fun_body;
+ if !range_check_trap > 0 then begin
+ `{emit_label !range_check_trap}:\n`;
+ ` call {emit_symbol "caml_ml_array_bound_error"}\n`;
+ ` nop\n`
+ end;
+ emit_size fundecl.fun_name;
+ List.iter emit_float_constant !float_constants
+
+(* Emission of data *)
+
+let emit_item = function
+ Cglobal_symbol s ->
+ ` .global {emit_symbol s}\n`;
+ | Cdefine_symbol s ->
+ `{emit_symbol s}:\n`
+ | Cdefine_label lbl ->
+ `{emit_data_label lbl}:\n`
+ | Cint8 n ->
+ ` .byte {emit_int n}\n`
+ | Cint16 n ->
+ ` .half {emit_int n}\n`
+ | Cint32 n ->
+ ` .word {emit_nativeint n}\n`
+ | Cint n ->
+ ` .word {emit_nativeint n}\n`
+ | Csingle f ->
+ emit_float32_directive ".word" (Int32.bits_of_float f)
+ | Cdouble f ->
+ emit_float64_split_directive ".word" (Int64.bits_of_float f)
+ | Csymbol_address s ->
+ ` .word {emit_symbol s}\n`
+ | Clabel_address lbl ->
+ ` .word {emit_data_label lbl}\n`
+ | Cstring s ->
+ emit_string_directive " .ascii " s
+ | Cskip n ->
+ if n > 0 then ` .skip {emit_int n}\n`
+ | Calign n ->
+ ` .align {emit_int n}\n`
+
+let data l =
+ ` .data\n`;
+ List.iter emit_item l
+
+(* Beginning / end of an assembly file *)
+
+let begin_assembly() =
+ let lbl_begin = Compilenv.make_symbol (Some "data_begin") in
+ ` .data\n`;
+ ` .global {emit_symbol lbl_begin}\n`;
+ `{emit_symbol lbl_begin}:\n`;
+ let lbl_begin = Compilenv.make_symbol (Some "code_begin") in
+ ` .text\n`;
+ ` .global {emit_symbol lbl_begin}\n`;
+ `{emit_symbol lbl_begin}:\n`
+
+let end_assembly() =
+ ` .text\n`;
+ let lbl_end = Compilenv.make_symbol (Some "code_end") in
+ ` .global {emit_symbol lbl_end}\n`;
+ `{emit_symbol lbl_end}:\n`;
+ ` .data\n`;
+ let lbl_end = Compilenv.make_symbol (Some "data_end") in
+ ` .global {emit_symbol lbl_end}\n`;
+ `{emit_symbol lbl_end}:\n`;
+ ` .word 0\n`;
+ let lbl = Compilenv.make_symbol (Some "frametable") in
+ rodata ();
+ ` .global {emit_symbol lbl}\n`;
+ if Config.system = "solaris" then
+ ` .type {emit_symbol lbl},#object\n`;
+ `{emit_symbol lbl}:\n`;
+ ` .word {emit_int (List.length !frame_descriptors)}\n`;
+ List.iter emit_frame !frame_descriptors;
+ emit_size lbl;
+ frame_descriptors := []
diff --git a/asmcomp/sparc/proc.ml b/asmcomp/sparc/proc.ml
new file mode 100644
index 0000000000..f34a987290
--- /dev/null
+++ b/asmcomp/sparc/proc.ml
@@ -0,0 +1,244 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Description of the Sparc processor *)
+
+open Misc
+open Cmm
+open Reg
+open Arch
+open Mach
+
+(* Instruction selection *)
+
+let word_addressed = false
+
+(* Registers available for register allocation *)
+
+(* Register map:
+ %o0 - %o5 0 - 5 function results, C functions args / res
+ %i0 - %i5 6 - 11 function arguments, preserved by C
+ %l0 - %l4 12 - 16 general purpose, preserved by C
+ %g3 - %g4 17 - 18 general purpose, not preserved by C
+
+ %l5 exception pointer
+ %l6 allocation pointer
+ %l7 address of allocation limit
+
+ %g0 always zero
+ %g1 - %g2 temporaries
+ %g5 - %g7 reserved for system libraries
+
+ %f0 - %f10 100 - 105 function arguments and results
+ %f12 - %f28 106 - 114 general purpose
+ %f30 temporary *)
+
+let int_reg_name = [|
+ (* 0-5 *) "%o0"; "%o1"; "%o2"; "%o3"; "%o4"; "%o5";
+ (* 6-11 *) "%i0"; "%i1"; "%i2"; "%i3"; "%i4"; "%i5";
+ (* 12-16 *) "%l0"; "%l1"; "%l2"; "%l3"; "%l4";
+ (* 17-18 *) "%g3"; "%g4"
+|]
+
+let float_reg_name = [|
+ (* 100-105 *) "%f0"; "%f2"; "%f4"; "%f6"; "%f8"; "%f10";
+ (* 106-109 *) "%f12"; "%f14"; "%f16"; "%f18";
+ (* 110-114 *) "%f20"; "%f22"; "%f24"; "%f26"; "%f28";
+ (* 115 *) "%f30";
+ (* Odd parts of register pairs *)
+ (* 116-121 *) "%f1"; "%f3"; "%f5"; "%f7"; "%f9"; "%f11";
+ (* 122-125 *) "%f13"; "%f15"; "%f17"; "%f19";
+ (* 126-130 *) "%f21"; "%f23"; "%f25"; "%f27"; "%f29";
+ (* 131 *) "%f31"
+|]
+
+let num_register_classes = 2
+
+let register_class r =
+ match r.typ with
+ | Val | Int | Addr -> 0
+ | Float -> 1
+
+let num_available_registers = [| 19; 15 |]
+
+let first_available_register = [| 0; 100 |]
+
+let register_name r =
+ if r < 100 then int_reg_name.(r) else float_reg_name.(r - 100)
+
+let rotate_registers = true
+
+(* Representation of hard registers by pseudo-registers *)
+
+let hard_int_reg =
+ let v = Array.make 19 Reg.dummy in
+ for i = 0 to 18 do v.(i) <- Reg.at_location Int (Reg i) done;
+ v
+
+let hard_float_reg =
+ let v = Array.make 32 Reg.dummy in
+ for i = 0 to 31 do v.(i) <- Reg.at_location Float (Reg(100 + i)) done;
+ v
+
+let all_phys_regs =
+ Array.append hard_int_reg (Array.sub hard_float_reg 0 15)
+ (* No need to include the odd parts of float register pairs,
+ nor the temporary register %f30 *)
+
+let phys_reg n =
+ if n < 100 then hard_int_reg.(n) else hard_float_reg.(n - 100)
+
+let stack_slot slot ty =
+ Reg.at_location ty (Stack slot)
+
+(* Calling conventions *)
+
+let calling_conventions first_int last_int first_float last_float make_stack
+ arg =
+ let loc = Array.make (Array.length arg) Reg.dummy in
+ let int = ref first_int in
+ let float = ref first_float in
+ let ofs = ref 0 in
+ for i = 0 to Array.length arg - 1 do
+ match arg.(i).typ with
+ | Val | Int | Addr as ty ->
+ if !int <= last_int then begin
+ loc.(i) <- phys_reg !int;
+ incr int
+ end else begin
+ loc.(i) <- stack_slot (make_stack !ofs) ty;
+ ofs := !ofs + size_int
+ end
+ | Float ->
+ if !float <= last_float then begin
+ loc.(i) <- phys_reg !float;
+ incr float
+ end else begin
+ loc.(i) <- stack_slot (make_stack !ofs) Float;
+ ofs := !ofs + size_float
+ end
+ done;
+ (loc, Misc.align !ofs 8) (* Keep stack 8-aligned *)
+
+let incoming ofs = Incoming ofs
+let outgoing ofs = Outgoing ofs
+let not_supported ofs = fatal_error "Proc.loc_results: cannot call"
+
+let loc_arguments arg =
+ calling_conventions 6 15 100 105 outgoing arg
+let loc_parameters arg =
+ let (loc, ofs) = calling_conventions 6 15 100 105 incoming arg in loc
+let loc_results res =
+ let (loc, ofs) = calling_conventions 0 5 100 105 not_supported res in loc
+
+(* On the Sparc, all arguments to C functions, even floating-point arguments,
+ are passed in %o0..%o5, then on the stack *)
+
+let loc_external_arguments arg =
+ let loc = Array.make (Array.length arg) [| |] in
+ let reg = ref 0 (* %o0 *) in
+ let ofs = ref (-4) in (* start at sp + 92 = sp + 96 - 4 *)
+ let next_loc typ =
+ if !reg <= 5 (* %o5 *) then begin
+ assert (size_component typ = size_int);
+ let loc = phys_reg !reg in
+ incr reg;
+ loc
+ end else begin
+ let loc = stack_slot (outgoing !ofs) typ in
+ ofs := !ofs + size_component typ;
+ loc
+ end
+ in
+ for i = 0 to Array.length arg - 1 do
+ match arg.(i) with
+ | [| { typ = (Val | Int | Addr as typ) } |] ->
+ loc.(i) <- [| next_loc typ |]
+ | [| { typ = Float } |] ->
+ if !reg <= 5 then begin
+ let loc1 = next_loc Int in
+ let loc2 = next_loc Int in
+ loc.(i) <- [| loc1; loc2 |]
+ end else
+ loc.(i) <- [| next_loc Float |]
+ | [| { typ = Int }; { typ = Int } |] ->
+ (* int64 unboxed *)
+ let loc1 = next_loc Int in
+ let loc2 = next_loc Int in
+ assert big_endian;
+ loc.(i) <- [| loc2; loc1 |]
+ | _ ->
+ fatal_error "Proc.loc_external_arguments: cannot call"
+ done;
+ (* Keep stack 8-aligned *)
+ (loc, Misc.align (!ofs + 4) 8)
+
+let loc_external_results res =
+ let (loc, ofs) = calling_conventions 0 1 100 100 not_supported res in loc
+
+let loc_exn_bucket = phys_reg 0 (* $o0 *)
+
+(* Volatile registers: none *)
+
+let regs_are_volatile rs = false
+
+(* Registers destroyed by operations *)
+
+let destroyed_at_c_call = (* %l0-%l4, %i0-%i5 preserved *)
+ Array.of_list(List.map phys_reg
+ [0; 1; 2; 3; 4; 5; 17; 18;
+ 100; 101; 102; 103; 104; 105; 106; 107;
+ 108; 109; 110; 111; 112; 113; 114])
+
+let destroyed_at_oper = function
+ Iop(Icall_ind | Icall_imm _ | Iextcall(_, true)) -> all_phys_regs
+ | Iop(Iextcall(_, false)) -> destroyed_at_c_call
+ | _ -> [||]
+
+let destroyed_at_raise = all_phys_regs
+
+(* Maximal register pressure *)
+
+let safe_register_pressure = function
+ Iextcall(_, _) -> 0
+ | _ -> 15
+
+let max_register_pressure = function
+ Iextcall(_, _) -> [| 11; 0 |]
+ | _ -> [| 19; 15 |]
+
+(* Pure operations (without any side effect besides updating their result
+ registers). *)
+
+let op_is_pure = function
+ | Icall_ind | Icall_imm _ | Itailcall_ind | Itailcall_imm _
+ | Iextcall _ | Istackoffset _ | Istore _ | Ialloc _
+ | Iintop(Icheckbound) | Iintop_imm(Icheckbound, _) -> false
+ | _ -> true
+
+(* Layout of the stack *)
+
+let num_stack_slots = [| 0; 0 |]
+let contains_calls = ref false
+
+(* Calling the assembler and the archiver *)
+
+let assemble_file infile outfile =
+ let asflags = begin match !arch_version with
+ SPARC_V7 -> " -o "
+ | SPARC_V8 -> " -xarch=v8 -o "
+ | SPARC_V9 -> " -xarch=v8plus -o "
+ end in
+ Ccomp.command (Config.asm ^ asflags ^
+ Filename.quote outfile ^ " " ^ Filename.quote infile)
+
+let init () = ()
diff --git a/asmcomp/sparc/reload.ml b/asmcomp/sparc/reload.ml
new file mode 100644
index 0000000000..caae16d7f2
--- /dev/null
+++ b/asmcomp/sparc/reload.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Reloading for the Sparc *)
+
+let fundecl f =
+ (new Reloadgen.reload_generic)#fundecl f
diff --git a/asmcomp/sparc/scheduling.ml b/asmcomp/sparc/scheduling.ml
new file mode 100644
index 0000000000..497722bbc5
--- /dev/null
+++ b/asmcomp/sparc/scheduling.ml
@@ -0,0 +1,60 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Cmm
+open Mach
+
+(* Instruction scheduling for the Sparc *)
+
+class scheduler = object
+
+inherit Schedgen.scheduler_generic
+
+(* Latencies (in cycles). *)
+
+(* UltraSPARC issues two integer operations, plus a single load or store,
+ per cycle. At most one of the integer instructions may be a shift.
+ Most integer operations have one cycle latency. Unsigned loads take
+ two cycles. Signed loads take three cycles. Conditional moves have
+ two cycle latency and may not issue in the same cycle as any other
+ instruction. Floating point issue rules are complicated, but in
+ general independent add and multiply can dual issue with four cycle
+ latency. *)
+
+method oper_latency = function
+ Ireload -> 2
+ | Iload((Byte_signed|Sixteen_signed|Thirtytwo_signed), _) -> 3
+ | Iload(_, _) -> 2
+ | Iconst_float _ -> 2 (* turned into a load *)
+ | Inegf | Iabsf | Iaddf | Isubf | Imulf -> 4
+ | Idivf -> 15
+ | _ -> 1
+
+(* Issue cycles. Rough approximations. *)
+
+method oper_issue_cycles = function
+ Iconst_float _ -> 2
+ | Iconst_symbol _ -> 2
+ | Ialloc _ -> 6
+ | Iintop(Icomp _) -> 4
+ | Iintop(Icheckbound) -> 2
+ | Iintop_imm(Icomp _, _) -> 4
+ | Iintop_imm(Icheckbound, _) -> 2
+ | Inegf -> 2
+ | Iabsf -> 2
+ | Ifloatofint -> 6
+ | Iintoffloat -> 6
+ | _ -> 1
+
+end
+
+let fundecl f = (new scheduler)#schedule_fundecl f
diff --git a/asmcomp/sparc/selection.ml b/asmcomp/sparc/selection.ml
new file mode 100644
index 0000000000..7218d01cf6
--- /dev/null
+++ b/asmcomp/sparc/selection.ml
@@ -0,0 +1,73 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Instruction selection for the Sparc processor *)
+
+open Cmm
+open Reg
+open Arch
+open Mach
+
+class selector = object (self)
+
+inherit Selectgen.selector_generic as super
+
+method is_immediate n = (n <= 4095) && (n >= -4096)
+
+method select_addressing chunk = function
+ Cconst_symbol s ->
+ (Ibased(s, 0), Ctuple [])
+ | Cop((Caddv | Cadda), [Cconst_symbol s; Cconst_int n]) ->
+ (Ibased(s, n), Ctuple [])
+ | Cop((Caddv | Cadda), [arg; Cconst_int n]) ->
+ (Iindexed n, arg)
+ | Cop((Caddv | Cadda as op), [arg1; Cop(Caddi, [arg2; Cconst_int n])]) ->
+ (Iindexed n, Cop(op, [arg1; arg2]))
+ | arg ->
+ (Iindexed 0, arg)
+
+method! select_operation op args =
+ match (op, args) with
+ (* For SPARC V7 multiplication, division and modulus are turned into
+ calls to C library routines.
+ For SPARC V8 and V9, use hardware multiplication and division,
+ but C library routine for modulus. *)
+ (Cmuli, _) when !arch_version = SPARC_V7 ->
+ (Iextcall(".umul", false), args)
+ | (Cdivi, _) when !arch_version = SPARC_V7 ->
+ (Iextcall(".div", false), args)
+ | (Cmodi, _) ->
+ (Iextcall(".rem", false), args)
+ | _ ->
+ super#select_operation op args
+
+(* Override insert_move_args to deal correctly with floating-point
+ arguments being passed into pairs of integer registers. *)
+method! insert_move_args arg loc stacksize =
+ if stacksize <> 0 then self#insert (Iop(Istackoffset stacksize)) [||] [||];
+ let locpos = ref 0 in
+ for i = 0 to Array.length arg - 1 do
+ let src = arg.(i) in
+ let dst = loc.(!locpos) in
+ match (src, dst) with
+ ({typ = Float}, {typ = Int}) ->
+ let dst2 = loc.(!locpos + 1) in
+ self#insert (Iop Imove) [|src|] [|dst; dst2|];
+ locpos := !locpos + 2
+ | (_, _) ->
+ self#insert_move src dst;
+ incr locpos
+ done
+
+end
+
+let fundecl f = (new selector)#emit_fundecl f
diff --git a/asmcomp/spill.ml b/asmcomp/spill.ml
new file mode 100644
index 0000000000..105550d056
--- /dev/null
+++ b/asmcomp/spill.ml
@@ -0,0 +1,410 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Insertion of moves to suggest possible spilling / reloading points
+ before register allocation. *)
+
+open Reg
+open Mach
+
+(* We say that a register is "destroyed" if it is live across a construct
+ that potentially destroys all physical registers: function calls or
+ try...with constructs.
+
+ The "destroyed" registers must therefore reside in the stack during
+ these instructions.. We will insert spills (stores) just after they
+ are defined, and reloads just before their first use following a
+ "destroying" construct.
+
+ Instructions with more live registers than actual registers also
+ "destroy" registers: we mark as "destroyed" the registers live
+ across the instruction that haven't been used for the longest time.
+ These registers will be spilled and reloaded as described above. *)
+
+(* Association of spill registers to registers *)
+
+let spill_env = ref (Reg.Map.empty : Reg.t Reg.Map.t)
+
+let spill_reg r =
+ try
+ Reg.Map.find r !spill_env
+ with Not_found ->
+ let spill_r = Reg.create r.typ in
+ spill_r.spill <- true;
+ if not (Reg.anonymous r) then spill_r.raw_name <- r.raw_name;
+ spill_env := Reg.Map.add r spill_r !spill_env;
+ spill_r
+
+(* Record the position of last use of registers *)
+
+let use_date = ref (Reg.Map.empty : int Reg.Map.t)
+let current_date = ref 0
+
+let record_use regv =
+ for i = 0 to Array.length regv - 1 do
+ let r = regv.(i) in
+ let prev_date = try Reg.Map.find r !use_date with Not_found -> 0 in
+ if !current_date > prev_date then
+ use_date := Reg.Map.add r !current_date !use_date
+ done
+
+(* Check if the register pressure overflows the maximum pressure allowed
+ at that point. If so, spill enough registers to lower the pressure. *)
+
+let add_superpressure_regs op live_regs res_regs spilled =
+ let max_pressure = Proc.max_register_pressure op in
+ let regs = Reg.add_set_array live_regs res_regs in
+ (* Compute the pressure in each register class *)
+ let pressure = Array.make Proc.num_register_classes 0 in
+ Reg.Set.iter
+ (fun r ->
+ if Reg.Set.mem r spilled then () else begin
+ match r.loc with
+ Stack s -> ()
+ | _ -> let c = Proc.register_class r in
+ pressure.(c) <- pressure.(c) + 1
+ end)
+ regs;
+ (* Check if pressure is exceeded for each class. *)
+ let rec check_pressure cl spilled =
+ if cl >= Proc.num_register_classes then
+ spilled
+ else if pressure.(cl) <= max_pressure.(cl) then
+ check_pressure (cl+1) spilled
+ else begin
+ (* Find the least recently used, unspilled, unallocated, live register
+ in the class *)
+ let lru_date = ref 1000000 and lru_reg = ref Reg.dummy in
+ Reg.Set.iter
+ (fun r ->
+ if Proc.register_class r = cl &&
+ not (Reg.Set.mem r spilled) &&
+ r.loc = Unknown
+ then begin
+ try
+ let d = Reg.Map.find r !use_date in
+ if d < !lru_date then begin
+ lru_date := d;
+ lru_reg := r
+ end
+ with Not_found -> (* Should not happen *)
+ ()
+ end)
+ live_regs;
+ if !lru_reg != Reg.dummy then begin
+ pressure.(cl) <- pressure.(cl) - 1;
+ check_pressure cl (Reg.Set.add !lru_reg spilled)
+ end else
+ (* Couldn't find any spillable register, give up for this class *)
+ check_pressure (cl+1) spilled
+ end in
+ check_pressure 0 spilled
+
+(* A-list recording what is destroyed at if-then-else points. *)
+
+let destroyed_at_fork = ref ([] : (instruction * Reg.Set.t) list)
+
+(* First pass: insert reload instructions based on an approximation of
+ what is destroyed at pressure points. *)
+
+let add_reloads regset i =
+ Reg.Set.fold
+ (fun r i -> instr_cons (Iop Ireload) [|spill_reg r|] [|r|] i)
+ regset i
+
+let reload_at_exit = ref []
+
+let find_reload_at_exit k =
+ try
+ List.assoc k !reload_at_exit
+ with
+ | Not_found -> Misc.fatal_error "Spill.find_reload_at_exit"
+
+let reload_at_break = ref Reg.Set.empty
+
+let rec reload i before =
+ incr current_date;
+ record_use i.arg;
+ record_use i.res;
+ match i.desc with
+ Iend ->
+ (i, before)
+ | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) ->
+ (add_reloads (Reg.inter_set_array before i.arg) i,
+ Reg.Set.empty)
+ | Iop(Icall_ind | Icall_imm _ | Iextcall(_, true)) ->
+ (* All regs live across must be spilled *)
+ let (new_next, finally) = reload i.next i.live in
+ (add_reloads (Reg.inter_set_array before i.arg)
+ (instr_cons_debug i.desc i.arg i.res i.dbg new_next),
+ finally)
+ | Iop op ->
+ let new_before =
+ (* Quick check to see if the register pressure is below the maximum *)
+ if Reg.Set.cardinal i.live + Array.length i.res <=
+ Proc.safe_register_pressure op
+ then before
+ else add_superpressure_regs op i.live i.res before in
+ let after =
+ Reg.diff_set_array (Reg.diff_set_array new_before i.arg) i.res in
+ let (new_next, finally) = reload i.next after in
+ (add_reloads (Reg.inter_set_array new_before i.arg)
+ (instr_cons_debug i.desc i.arg i.res i.dbg new_next),
+ finally)
+ | Iifthenelse(test, ifso, ifnot) ->
+ let at_fork = Reg.diff_set_array before i.arg in
+ let date_fork = !current_date in
+ let (new_ifso, after_ifso) = reload ifso at_fork in
+ let date_ifso = !current_date in
+ current_date := date_fork;
+ let (new_ifnot, after_ifnot) = reload ifnot at_fork in
+ current_date := max date_ifso !current_date;
+ let (new_next, finally) =
+ reload i.next (Reg.Set.union after_ifso after_ifnot) in
+ let new_i =
+ instr_cons (Iifthenelse(test, new_ifso, new_ifnot))
+ i.arg i.res new_next in
+ destroyed_at_fork := (new_i, at_fork) :: !destroyed_at_fork;
+ (add_reloads (Reg.inter_set_array before i.arg) new_i,
+ finally)
+ | Iswitch(index, cases) ->
+ let at_fork = Reg.diff_set_array before i.arg in
+ let date_fork = !current_date in
+ let date_join = ref 0 in
+ let after_cases = ref Reg.Set.empty in
+ let new_cases =
+ Array.map
+ (fun c ->
+ current_date := date_fork;
+ let (new_c, after_c) = reload c at_fork in
+ after_cases := Reg.Set.union !after_cases after_c;
+ date_join := max !date_join !current_date;
+ new_c)
+ cases in
+ current_date := !date_join;
+ let (new_next, finally) = reload i.next !after_cases in
+ (add_reloads (Reg.inter_set_array before i.arg)
+ (instr_cons (Iswitch(index, new_cases))
+ i.arg i.res new_next),
+ finally)
+ | Iloop(body) ->
+ let date_start = !current_date in
+ let at_head = ref before in
+ let final_body = ref body in
+ begin try
+ while true do
+ current_date := date_start;
+ let (new_body, new_at_head) = reload body !at_head in
+ let merged_at_head = Reg.Set.union !at_head new_at_head in
+ if Reg.Set.equal merged_at_head !at_head then begin
+ final_body := new_body;
+ raise Exit
+ end;
+ at_head := merged_at_head
+ done
+ with Exit -> ()
+ end;
+ let (new_next, finally) = reload i.next Reg.Set.empty in
+ (instr_cons (Iloop(!final_body)) i.arg i.res new_next,
+ finally)
+ | Icatch(nfail, body, handler) ->
+ let new_set = ref Reg.Set.empty in
+ reload_at_exit := (nfail, new_set) :: !reload_at_exit ;
+ let (new_body, after_body) = reload body before in
+ let at_exit = !new_set in
+ reload_at_exit := List.tl !reload_at_exit ;
+ let (new_handler, after_handler) = reload handler at_exit in
+ let (new_next, finally) =
+ reload i.next (Reg.Set.union after_body after_handler) in
+ (instr_cons (Icatch(nfail, new_body, new_handler)) i.arg i.res new_next,
+ finally)
+ | Iexit nfail ->
+ let set = find_reload_at_exit nfail in
+ set := Reg.Set.union !set before;
+ (i, Reg.Set.empty)
+ | Itrywith(body, handler) ->
+ let (new_body, after_body) = reload body before in
+ (* All registers live at the beginning of the handler are destroyed,
+ except the exception bucket *)
+ let before_handler =
+ Reg.Set.remove Proc.loc_exn_bucket
+ (Reg.add_set_array handler.live handler.arg) in
+ let (new_handler, after_handler) = reload handler before_handler in
+ let (new_next, finally) =
+ reload i.next (Reg.Set.union after_body after_handler) in
+ (instr_cons (Itrywith(new_body, new_handler)) i.arg i.res new_next,
+ finally)
+ | Iraise _ ->
+ (add_reloads (Reg.inter_set_array before i.arg) i, Reg.Set.empty)
+
+(* Second pass: add spill instructions based on what we've decided to reload.
+ That is, any register that may be reloaded in the future must be spilled
+ just after its definition. *)
+
+(*
+ As an optimization, if a register needs to be spilled in one branch of
+ a conditional but not in the other, then we spill it late on entrance
+ in the branch that needs it spilled.
+ NB: This strategy is turned off in loops, as it may prevent a spill from
+ being lifted up all the way out of the loop.
+ NB again: This strategy is also off in switch arms
+ as it generates many useless spills inside switch arms
+ NB ter: is it the same thing for catch bodies ?
+*)
+
+
+let spill_at_exit = ref []
+let find_spill_at_exit k =
+ try
+ List.assoc k !spill_at_exit
+ with
+ | Not_found -> Misc.fatal_error "Spill.find_spill_at_exit"
+
+let spill_at_raise = ref Reg.Set.empty
+let inside_loop = ref false
+and inside_arm = ref false
+and inside_catch = ref false
+
+let add_spills regset i =
+ Reg.Set.fold
+ (fun r i -> instr_cons (Iop Ispill) [|r|] [|spill_reg r|] i)
+ regset i
+
+let rec spill i finally =
+ match i.desc with
+ Iend ->
+ (i, finally)
+ | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) ->
+ (i, Reg.Set.empty)
+ | Iop Ireload ->
+ let (new_next, after) = spill i.next finally in
+ let before1 = Reg.diff_set_array after i.res in
+ (instr_cons i.desc i.arg i.res new_next,
+ Reg.add_set_array before1 i.res)
+ | Iop _ ->
+ let (new_next, after) = spill i.next finally in
+ let before1 = Reg.diff_set_array after i.res in
+ let before =
+ match i.desc with
+ Iop Icall_ind | Iop(Icall_imm _) | Iop(Iextcall _)
+ | Iop(Iintop Icheckbound) | Iop(Iintop_imm(Icheckbound, _)) ->
+ Reg.Set.union before1 !spill_at_raise
+ | _ ->
+ before1 in
+ (instr_cons_debug i.desc i.arg i.res i.dbg
+ (add_spills (Reg.inter_set_array after i.res) new_next),
+ before)
+ | Iifthenelse(test, ifso, ifnot) ->
+ let (new_next, at_join) = spill i.next finally in
+ let (new_ifso, before_ifso) = spill ifso at_join in
+ let (new_ifnot, before_ifnot) = spill ifnot at_join in
+ if
+ !inside_loop || !inside_arm
+ then
+ (instr_cons (Iifthenelse(test, new_ifso, new_ifnot))
+ i.arg i.res new_next,
+ Reg.Set.union before_ifso before_ifnot)
+ else begin
+ let destroyed = List.assq i !destroyed_at_fork in
+ let spill_ifso_branch =
+ Reg.Set.diff (Reg.Set.diff before_ifso before_ifnot) destroyed
+ and spill_ifnot_branch =
+ Reg.Set.diff (Reg.Set.diff before_ifnot before_ifso) destroyed in
+ (instr_cons
+ (Iifthenelse(test, add_spills spill_ifso_branch new_ifso,
+ add_spills spill_ifnot_branch new_ifnot))
+ i.arg i.res new_next,
+ Reg.Set.diff (Reg.Set.diff (Reg.Set.union before_ifso before_ifnot)
+ spill_ifso_branch)
+ spill_ifnot_branch)
+ end
+ | Iswitch(index, cases) ->
+ let (new_next, at_join) = spill i.next finally in
+ let saved_inside_arm = !inside_arm in
+ inside_arm := true ;
+ let before = ref Reg.Set.empty in
+ let new_cases =
+ Array.map
+ (fun c ->
+ let (new_c, before_c) = spill c at_join in
+ before := Reg.Set.union !before before_c;
+ new_c)
+ cases in
+ inside_arm := saved_inside_arm ;
+ (instr_cons (Iswitch(index, new_cases)) i.arg i.res new_next,
+ !before)
+ | Iloop(body) ->
+ let (new_next, _) = spill i.next finally in
+ let saved_inside_loop = !inside_loop in
+ inside_loop := true;
+ let at_head = ref Reg.Set.empty in
+ let final_body = ref body in
+ begin try
+ while true do
+ let (new_body, before_body) = spill body !at_head in
+ let new_at_head = Reg.Set.union !at_head before_body in
+ if Reg.Set.equal new_at_head !at_head then begin
+ final_body := new_body; raise Exit
+ end;
+ at_head := new_at_head
+ done
+ with Exit -> ()
+ end;
+ inside_loop := saved_inside_loop;
+ (instr_cons (Iloop(!final_body)) i.arg i.res new_next,
+ !at_head)
+ | Icatch(nfail, body, handler) ->
+ let (new_next, at_join) = spill i.next finally in
+ let (new_handler, at_exit) = spill handler at_join in
+ let saved_inside_catch = !inside_catch in
+ inside_catch := true ;
+ spill_at_exit := (nfail, at_exit) :: !spill_at_exit ;
+ let (new_body, before) = spill body at_join in
+ spill_at_exit := List.tl !spill_at_exit;
+ inside_catch := saved_inside_catch ;
+ (instr_cons (Icatch(nfail, new_body, new_handler)) i.arg i.res new_next,
+ before)
+ | Iexit nfail ->
+ (i, find_spill_at_exit nfail)
+ | Itrywith(body, handler) ->
+ let (new_next, at_join) = spill i.next finally in
+ let (new_handler, before_handler) = spill handler at_join in
+ let saved_spill_at_raise = !spill_at_raise in
+ spill_at_raise := before_handler;
+ let (new_body, before_body) = spill body at_join in
+ spill_at_raise := saved_spill_at_raise;
+ (instr_cons (Itrywith(new_body, new_handler)) i.arg i.res new_next,
+ before_body)
+ | Iraise _ ->
+ (i, !spill_at_raise)
+
+(* Entry point *)
+
+let reset () =
+ spill_env := Reg.Map.empty;
+ use_date := Reg.Map.empty;
+ current_date := 0
+
+let fundecl f =
+ reset ();
+
+ let (body1, _) = reload f.fun_body Reg.Set.empty in
+ let (body2, tospill_at_entry) = spill body1 Reg.Set.empty in
+ let new_body =
+ add_spills (Reg.inter_set_array tospill_at_entry f.fun_args) body2 in
+ spill_env := Reg.Map.empty;
+ use_date := Reg.Map.empty;
+ { fun_name = f.fun_name;
+ fun_args = f.fun_args;
+ fun_body = new_body;
+ fun_fast = f.fun_fast;
+ fun_dbg = f.fun_dbg }
diff --git a/asmcomp/spill.mli b/asmcomp/spill.mli
new file mode 100644
index 0000000000..598a175522
--- /dev/null
+++ b/asmcomp/spill.mli
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Insertion of moves to suggest possible spilling / reloading points
+ before register allocation. *)
+
+val fundecl: Mach.fundecl -> Mach.fundecl
+val reset : unit -> unit
diff --git a/asmcomp/split.ml b/asmcomp/split.ml
new file mode 100644
index 0000000000..8c553ab9ef
--- /dev/null
+++ b/asmcomp/split.ml
@@ -0,0 +1,214 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Renaming of registers at reload points to split live ranges. *)
+
+open Reg
+open Mach
+
+(* Substitutions are represented by register maps *)
+
+type subst = Reg.t Reg.Map.t
+
+let subst_reg r (sub : subst) =
+ try
+ Reg.Map.find r sub
+ with Not_found ->
+ r
+
+let subst_regs rv sub =
+ match sub with
+ None -> rv
+ | Some s ->
+ let n = Array.length rv in
+ let nv = Array.make n Reg.dummy in
+ for i = 0 to n-1 do nv.(i) <- subst_reg rv.(i) s done;
+ nv
+
+(* We maintain equivalence classes of registers using a standard
+ union-find algorithm *)
+
+let equiv_classes = ref (Reg.Map.empty : Reg.t Reg.Map.t)
+
+let rec repres_reg r =
+ try
+ repres_reg(Reg.Map.find r !equiv_classes)
+ with Not_found ->
+ r
+
+let repres_regs rv =
+ let n = Array.length rv in
+ for i = 0 to n-1 do rv.(i) <- repres_reg rv.(i) done
+
+(* Identify two registers.
+ The second register is chosen as canonical representative. *)
+
+let identify r1 r2 =
+ let repres1 = repres_reg r1 in
+ let repres2 = repres_reg r2 in
+ if repres1.stamp = repres2.stamp then () else begin
+ equiv_classes := Reg.Map.add repres1 repres2 !equiv_classes
+ end
+
+(* Identify the image of a register by two substitutions.
+ Be careful to use the original register as canonical representative
+ in case it does not belong to the domain of one of the substitutions. *)
+
+let identify_sub sub1 sub2 reg =
+ try
+ let r1 = Reg.Map.find reg sub1 in
+ try
+ let r2 = Reg.Map.find reg sub2 in
+ identify r1 r2
+ with Not_found ->
+ identify r1 reg
+ with Not_found ->
+ try
+ let r2 = Reg.Map.find reg sub2 in
+ identify r2 reg
+ with Not_found ->
+ ()
+
+(* Identify registers so that the two substitutions agree on the
+ registers live before the given instruction. *)
+
+let merge_substs sub1 sub2 i =
+ match (sub1, sub2) with
+ (None, None) -> None
+ | (Some s1, None) -> sub1
+ | (None, Some s2) -> sub2
+ | (Some s1, Some s2) ->
+ Reg.Set.iter (identify_sub s1 s2) (Reg.add_set_array i.live i.arg);
+ sub1
+
+(* Same, for N substitutions *)
+
+let merge_subst_array subv instr =
+ let rec find_one_subst i =
+ if i >= Array.length subv then None else begin
+ match subv.(i) with
+ None -> find_one_subst (i+1)
+ | Some si as sub ->
+ for j = i+1 to Array.length subv - 1 do
+ match subv.(j) with
+ None -> ()
+ | Some sj ->
+ Reg.Set.iter (identify_sub si sj)
+ (Reg.add_set_array instr.live instr.arg)
+ done;
+ sub
+ end in
+ find_one_subst 0
+
+(* First pass: rename registers at reload points *)
+
+let exit_subst = ref []
+
+let find_exit_subst k =
+ try
+ List.assoc k !exit_subst with
+ | Not_found -> Misc.fatal_error "Split.find_exit_subst"
+
+let rec rename i sub =
+ match i.desc with
+ Iend ->
+ (i, sub)
+ | Ireturn | Iop(Itailcall_ind) | Iop(Itailcall_imm _) ->
+ (instr_cons i.desc (subst_regs i.arg sub) [||] i.next,
+ None)
+ | Iop Ireload when i.res.(0).loc = Unknown ->
+ begin match sub with
+ None -> rename i.next sub
+ | Some s ->
+ let oldr = i.res.(0) in
+ let newr = Reg.clone i.res.(0) in
+ let (new_next, sub_next) =
+ rename i.next (Some(Reg.Map.add oldr newr s)) in
+ (instr_cons i.desc i.arg [|newr|] new_next,
+ sub_next)
+ end
+ | Iop _ ->
+ let (new_next, sub_next) = rename i.next sub in
+ (instr_cons_debug i.desc (subst_regs i.arg sub) (subst_regs i.res sub)
+ i.dbg new_next,
+ sub_next)
+ | Iifthenelse(tst, ifso, ifnot) ->
+ let (new_ifso, sub_ifso) = rename ifso sub in
+ let (new_ifnot, sub_ifnot) = rename ifnot sub in
+ let (new_next, sub_next) =
+ rename i.next (merge_substs sub_ifso sub_ifnot i.next) in
+ (instr_cons (Iifthenelse(tst, new_ifso, new_ifnot))
+ (subst_regs i.arg sub) [||] new_next,
+ sub_next)
+ | Iswitch(index, cases) ->
+ let new_sub_cases = Array.map (fun c -> rename c sub) cases in
+ let sub_merge =
+ merge_subst_array (Array.map (fun (n, s) -> s) new_sub_cases) i.next in
+ let (new_next, sub_next) = rename i.next sub_merge in
+ (instr_cons (Iswitch(index, Array.map (fun (n, s) -> n) new_sub_cases))
+ (subst_regs i.arg sub) [||] new_next,
+ sub_next)
+ | Iloop(body) ->
+ let (new_body, sub_body) = rename body sub in
+ let (new_next, sub_next) = rename i.next (merge_substs sub sub_body i) in
+ (instr_cons (Iloop(new_body)) [||] [||] new_next,
+ sub_next)
+ | Icatch(nfail, body, handler) ->
+ let new_subst = ref None in
+ exit_subst := (nfail, new_subst) :: !exit_subst ;
+ let (new_body, sub_body) = rename body sub in
+ let sub_entry_handler = !new_subst in
+ exit_subst := List.tl !exit_subst;
+ let (new_handler, sub_handler) = rename handler sub_entry_handler in
+ let (new_next, sub_next) =
+ rename i.next (merge_substs sub_body sub_handler i.next) in
+ (instr_cons (Icatch(nfail, new_body, new_handler)) [||] [||] new_next,
+ sub_next)
+ | Iexit nfail ->
+ let r = find_exit_subst nfail in
+ r := merge_substs !r sub i;
+ (i, None)
+ | Itrywith(body, handler) ->
+ let (new_body, sub_body) = rename body sub in
+ let (new_handler, sub_handler) = rename handler sub in
+ let (new_next, sub_next) =
+ rename i.next (merge_substs sub_body sub_handler i.next) in
+ (instr_cons (Itrywith(new_body, new_handler)) [||] [||] new_next,
+ sub_next)
+ | Iraise k ->
+ (instr_cons_debug (Iraise k) (subst_regs i.arg sub) [||] i.dbg i.next,
+ None)
+
+(* Second pass: replace registers by their final representatives *)
+
+let set_repres i =
+ instr_iter (fun i -> repres_regs i.arg; repres_regs i.res) i
+
+(* Entry point *)
+
+let reset () =
+ equiv_classes := Reg.Map.empty;
+ exit_subst := []
+
+let fundecl f =
+ reset ();
+
+ let new_args = Array.copy f.fun_args in
+ let (new_body, sub_body) = rename f.fun_body (Some Reg.Map.empty) in
+ repres_regs new_args;
+ set_repres new_body;
+ equiv_classes := Reg.Map.empty;
+ { fun_name = f.fun_name;
+ fun_args = new_args;
+ fun_body = new_body;
+ fun_fast = f.fun_fast;
+ fun_dbg = f.fun_dbg }
diff --git a/asmcomp/split.mli b/asmcomp/split.mli
new file mode 100644
index 0000000000..1924a5ad6c
--- /dev/null
+++ b/asmcomp/split.mli
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Renaming of registers at reload points to split live ranges. *)
+
+val fundecl: Mach.fundecl -> Mach.fundecl
+
+val reset : unit -> unit
diff --git a/asmcomp/strmatch.ml b/asmcomp/strmatch.ml
new file mode 100644
index 0000000000..ad25ad8744
--- /dev/null
+++ b/asmcomp/strmatch.ml
@@ -0,0 +1,389 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translation of string matching from closed lambda to C-- *)
+
+open Lambda
+open Cmm
+
+module type I = sig
+ val string_block_length : Cmm.expression -> Cmm.expression
+ val transl_switch :
+ Cmm.expression -> int -> int ->
+ (int * Cmm.expression) list -> Cmm.expression ->
+ Cmm.expression
+end
+
+module Make(I:I) = struct
+
+(* Debug *)
+
+ let dbg = false
+
+ let mask =
+ let open Nativeint in
+ sub (shift_left one 8) one
+
+ let pat_as_string p =
+ let rec digits k n p =
+ if n <= 0 then k
+ else
+ let d = Nativeint.to_int (Nativeint.logand mask p) in
+ let d = Char.escaped (Char.chr d) in
+ digits (d::k) (n-1) (Nativeint.shift_right_logical p 8) in
+ let ds = digits [] Arch.size_addr p in
+ let ds =
+ if Arch.big_endian then ds else List.rev ds in
+ String.concat "" ds
+
+ let do_pp_cases chan cases =
+ List.iter
+ (fun (ps,_) ->
+ Printf.fprintf chan " [%s]\n"
+ (String.concat "; " (List.map pat_as_string ps)))
+ cases
+
+ let pp_cases chan tag cases =
+ Printf.eprintf "%s:\n" tag ;
+ do_pp_cases chan cases
+
+ let pp_match chan tag idxs cases =
+ Printf.eprintf
+ "%s: idx=[%s]\n" tag
+ (String.concat "; " (List.map string_of_int idxs)) ;
+ do_pp_cases chan cases
+
+(* Utilities *)
+
+ let gen_cell_id () = Ident.create "cell"
+ let gen_size_id () = Ident.create "size"
+
+ let mk_let_cell id str ind body =
+ let cell =
+ Cop(Cload Word_int,[Cop(Cadda,[str;Cconst_int(Arch.size_int*ind)])]) in
+ Clet(id, cell, body)
+
+ let mk_let_size id str body =
+ let size = I.string_block_length str in
+ Clet(id, size, body)
+
+ let mk_cmp_gen cmp_op id nat ifso ifnot =
+ let test = Cop (Ccmpi cmp_op, [ Cvar id; Cconst_natpointer nat ]) in
+ Cifthenelse (test, ifso, ifnot)
+
+ let mk_lt = mk_cmp_gen Clt
+ let mk_eq = mk_cmp_gen Ceq
+
+ module IntArg =
+ struct
+ type t = int
+ let compare (x:int) (y:int) =
+ if x < y then -1
+ else if x > y then 1
+ else 0
+ end
+
+ let interval m0 n =
+ let rec do_rec m =
+ if m >= n then []
+ else m::do_rec (m+1) in
+ do_rec m0
+
+
+(*****************************************************)
+(* Compile strings to a lists of words [native ints] *)
+(*****************************************************)
+
+ let pat_of_string str =
+ let len = String.length str in
+ let n = len / Arch.size_addr + 1 in
+ let get_byte i =
+ if i < len then int_of_char str.[i]
+ else if i < n * Arch.size_addr - 1 then 0
+ else n * Arch.size_addr - 1 - len in
+ let mk_word ind =
+ let w = ref 0n in
+ let imin = ind * Arch.size_addr
+ and imax = (ind + 1) * Arch.size_addr - 1 in
+ if Arch.big_endian then
+ for i = imin to imax do
+ w := Nativeint.logor (Nativeint.shift_left !w 8)
+ (Nativeint.of_int (get_byte i));
+ done
+ else
+ for i = imax downto imin do
+ w := Nativeint.logor (Nativeint.shift_left !w 8)
+ (Nativeint.of_int (get_byte i));
+ done;
+ !w in
+ let rec mk_words ind =
+ if ind >= n then []
+ else mk_word ind::mk_words (ind+1) in
+ mk_words 0
+
+(*****************************)
+(* Discriminating heuristics *)
+(*****************************)
+
+ module IntSet = Set.Make(IntArg)
+ module NativeSet = Set.Make(Nativeint)
+
+ let rec add_one sets ps = match sets,ps with
+ | [],[] -> []
+ | set::sets,p::ps ->
+ let sets = add_one sets ps in
+ NativeSet.add p set::sets
+ | _,_ -> assert false
+
+ let count_arities cases = match cases with
+ | [] -> assert false
+ | (ps,_)::_ ->
+ let sets =
+ List.fold_left
+ (fun sets (ps,_) -> add_one sets ps)
+ (List.map (fun _ -> NativeSet.empty) ps) cases in
+ List.map NativeSet.cardinal sets
+
+ let count_arities_first cases =
+ let set =
+ List.fold_left
+ (fun set case -> match case with
+ | (p::_,_) -> NativeSet.add p set
+ | _ -> assert false)
+ NativeSet.empty cases in
+ NativeSet.cardinal set
+
+ let count_arities_length cases =
+ let set =
+ List.fold_left
+ (fun set (ps,_) -> IntSet.add (List.length ps) set)
+ IntSet.empty cases in
+ IntSet.cardinal set
+
+ let best_col =
+ let rec do_rec kbest best k = function
+ | [] -> kbest
+ | x::xs ->
+ if x < best then
+ do_rec k x (k+1) xs
+ else
+ do_rec kbest best (k+1) xs in
+ let smallest = do_rec (-1) max_int 0 in
+ fun cases ->
+ let ars = count_arities cases in
+ smallest ars
+
+ let swap_list =
+ let rec do_rec k xs = match xs with
+ | [] -> assert false
+ | x::xs ->
+ if k <= 0 then [],x,xs
+ else
+ let xs,mid,ys = do_rec (k-1) xs in
+ x::xs,mid,ys in
+ fun k xs ->
+ let xs,x,ys = do_rec k xs in
+ x::xs @ ys
+
+ let swap k idxs cases =
+ if k = 0 then idxs,cases
+ else
+ let idxs = swap_list k idxs
+ and cases =
+ List.map
+ (fun (ps,act) -> swap_list k ps,act)
+ cases in
+ if dbg then begin
+ pp_match stderr "SWAP" idxs cases
+ end ;
+ idxs,cases
+
+ let best_first idxs cases = match idxs with
+ | []|[_] -> idxs,cases (* optimisation: one column only *)
+ | _ ->
+ let k = best_col cases in
+ swap k idxs cases
+
+(************************************)
+(* Divide according to first column *)
+(************************************)
+
+ module Divide(O:Set.OrderedType) = struct
+
+ module OMap = Map.Make(O)
+
+ let do_find key env =
+ try OMap.find key env
+ with Not_found -> assert false
+
+ let divide cases =
+ let env =
+ List.fold_left
+ (fun env (p,psact) ->
+ let old =
+ try OMap.find p env
+ with Not_found -> [] in
+ OMap.add p ((psact)::old) env)
+ OMap.empty cases in
+ let r = OMap.fold (fun key v k -> (key,v)::k) env [] in
+ List.rev r (* Now sorted *)
+ end
+
+(***************)
+(* Compilation *)
+(***************)
+
+(* Group by cell *)
+
+ module DivideNative = Divide(Nativeint)
+
+ let by_cell cases =
+ DivideNative.divide
+ (List.map
+ (fun case -> match case with
+ | (p::ps),act -> p,(ps,act)
+ | [],_ -> assert false)
+ cases)
+
+(* Split into two halves *)
+
+ let rec do_split idx env = match env with
+ | [] -> assert false
+ | (midkey,_ as x)::rem ->
+ if idx <= 0 then [],midkey,env
+ else
+ let lt,midkey,ge = do_split (idx-1) rem in
+ x::lt,midkey,ge
+
+ let split_env len env = do_split (len/2) env
+
+(* Switch according to one cell *)
+
+(*
+ Emit the switch, here as a comparison tree.
+ Argument compile_rec is to be called to compile the rest of patterns,
+ as match_on_cell can be called in two different contexts :
+ from do_compile_pats and top_compile below.
+ *)
+ let match_oncell compile_rec str default idx env =
+ let id = gen_cell_id () in
+ let rec comp_rec env =
+ let len = List.length env in
+ if len <= 3 then
+ List.fold_right
+ (fun (key,cases) ifnot ->
+ mk_eq id key
+ (compile_rec str default cases)
+ ifnot)
+ env default
+ else
+ let lt,midkey,ge = split_env len env in
+ mk_lt id midkey (comp_rec lt) (comp_rec ge) in
+ mk_let_cell id str idx (comp_rec env)
+
+(*
+ Recursive 'list of cells' compile function:
+ - choose the matched cell and switch on it
+ - notice: patterns (and idx) all have the same length
+ *)
+
+ let rec do_compile_pats idxs str default cases =
+ if dbg then begin
+ pp_match stderr "COMPILE" idxs cases
+ end ;
+ match idxs with
+ | [] ->
+ begin match cases with
+ | [] -> default
+ | (_,e)::_ -> e
+ end
+ | _::_ ->
+ let idxs,cases = best_first idxs cases in
+ begin match idxs with
+ | [] -> assert false
+ | idx::idxs ->
+ match_oncell
+ (do_compile_pats idxs) str default idx (by_cell cases)
+ end
+
+
+(* Group by size *)
+
+ module DivideInt = Divide(IntArg)
+
+
+ let by_size cases =
+ DivideInt.divide
+ (List.map
+ (fun (ps,_ as case) -> List.length ps,case)
+ cases)
+(*
+ Switch according to pattern size
+ Argument from_ind is the starting index, it can be zero
+ or one (when the swicth on the cell 0 has already been performed.
+ In that latter case pattern len is string length-1 and is corrected.
+ *)
+
+ let compile_by_size from_ind str default cases =
+ let size_cases =
+ List.map
+ (fun (len,cases) ->
+ let len = len+from_ind in
+ let act =
+ do_compile_pats
+ (interval from_ind len)
+ str default cases in
+ (len,act))
+ (by_size cases) in
+ let id = gen_size_id () in
+ let switch = I.transl_switch (Cvar id) 1 max_int size_cases default in
+ mk_let_size id str switch
+
+(*
+ Compilation entry point: we choose to switch
+ either on size or on first cell, using the
+ 'least discriminant' heuristics.
+ *)
+ let top_compile str default cases =
+ let a_len = count_arities_length cases
+ and a_fst = count_arities_first cases in
+ if a_len <= a_fst then begin
+ if dbg then pp_cases stderr "SIZE" cases ;
+ compile_by_size 0 str default cases
+ end else begin
+ if dbg then pp_cases stderr "FIRST COL" cases ;
+ let compile_size_rest str default cases =
+ compile_by_size 1 str default cases in
+ match_oncell compile_size_rest str default 0 (by_cell cases)
+ end
+
+(* Module entry point *)
+
+ let catch arg k = match arg with
+ | Cexit (e,[]) -> k arg
+ | _ ->
+ let e = next_raise_count () in
+ Ccatch (e,[],k (Cexit (e,[])),arg)
+
+ let compile str default cases =
+(* We do not attempt to really optimise default=None *)
+ let cases,default = match cases,default with
+ | (_,e)::cases,None
+ | cases,Some e -> cases,e
+ | [],None -> assert false in
+ let cases =
+ List.rev_map
+ (fun (s,act) -> pat_of_string s,act)
+ cases in
+ catch default (fun default -> top_compile str default cases)
+
+ end
diff --git a/asmcomp/strmatch.mli b/asmcomp/strmatch.mli
new file mode 100644
index 0000000000..143dae5cb6
--- /dev/null
+++ b/asmcomp/strmatch.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translation of string matching from closed lambda to C-- *)
+
+module type I = sig
+ val string_block_length : Cmm.expression -> Cmm.expression
+ val transl_switch :
+ Cmm.expression -> int -> int ->
+ (int * Cmm.expression) list -> Cmm.expression ->
+ Cmm.expression
+end
+
+module Make(I:I) : sig
+ (* Compile stringswitch (arg,cases,d)
+ Note: cases should not contain string duplicates *)
+ val compile : Cmm.expression (* arg *) -> Cmm.expression option (* d *) ->
+ (string * Cmm.expression) list (* cases *)-> Cmm.expression
+end
diff --git a/asmcomp/x86_ast.mli b/asmcomp/x86_ast.mli
new file mode 100644
index 0000000000..b7796a199f
--- /dev/null
+++ b/asmcomp/x86_ast.mli
@@ -0,0 +1,216 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Structured representation of Intel assembly language (32 and 64 bit). *)
+
+type condition =
+ | L | GE (* signed comparisons: less/greater *)
+ | LE | G
+ | B | AE (* unsigned comparisons: below/above *)
+ | BE | A
+ | E | NE (* equal *)
+ | O | NO (* overflow *)
+ | S | NS (* sign *)
+ | P | NP (* parity *)
+
+type rounding =
+ | RoundUp
+ | RoundDown
+ | RoundNearest
+ | RoundTruncate
+
+type constant =
+ | Const of int64
+ | ConstThis
+ | ConstLabel of string
+ | ConstAdd of constant * constant
+ | ConstSub of constant * constant
+
+(* data_type is used mainly on memory addressing to specify
+ the size of the addressed memory chunk. It is directly
+ used by the MASM emitter and indirectly by the GAS emitter
+ to infer the instruction suffix. *)
+
+type data_type =
+ | NONE
+ | REAL4 | REAL8 (* floating point values *)
+ | BYTE | WORD | DWORD | QWORD | OWORD (* integer values *)
+ | NEAR | PROC
+
+type reg64 =
+ | RAX | RBX | RCX | RDX | RSP | RBP | RSI | RDI
+ | R8 | R9 | R10 | R11 | R12 | R13 | R14 | R15
+
+type reg8h =
+ | AH | BH | CH | DH
+
+
+type registerf = XMM of int | TOS | ST of int
+
+type arch = X64 | X86
+
+type addr =
+ {
+ arch: arch;
+ typ: data_type;
+ idx: reg64;
+ scale: int;
+ base: reg64 option;
+ sym: string option;
+ displ: int;
+ }
+ (** Addressing modes:
+ displ + sym + base + idx * scale
+ (if scale = 0, idx is ignored and base must be None)
+ *)
+
+type arg =
+ | Imm of int64
+ (** Operand is an immediate constant integer *)
+
+ | Sym of string
+ (** Address of a symbol (absolute address except for call/jmp target
+ where it is interpreted as a relative displacement *)
+
+ | Reg8L of reg64
+ | Reg8H of reg8h
+ | Reg16 of reg64
+ | Reg32 of reg64
+ | Reg64 of reg64
+ | Regf of registerf
+
+ | Mem of addr
+ | Mem64_RIP of data_type * string * int
+
+type instruction =
+ | ADD of arg * arg
+ | ADDSD of arg * arg
+ | AND of arg * arg
+ | ANDPD of arg * arg
+ | BSWAP of arg
+ | CALL of arg
+ | CDQ
+ | CMOV of condition * arg * arg
+ | CMP of arg * arg
+ | COMISD of arg * arg
+ | CQO
+ | CVTSD2SI of arg * arg
+ | CVTSD2SS of arg * arg
+ | CVTSI2SD of arg * arg
+ | CVTSS2SD of arg * arg
+ | CVTTSD2SI of arg * arg
+ | DEC of arg
+ | DIVSD of arg * arg
+ | FABS
+ | FADD of arg
+ | FADDP of arg * arg
+ | FCHS
+ | FCOMP of arg
+ | FCOMPP
+ | FCOS
+ | FDIV of arg
+ | FDIVP of arg * arg
+ | FDIVR of arg
+ | FDIVRP of arg * arg
+ | FILD of arg
+ | FISTP of arg
+ | FLD of arg
+ | FLD1
+ | FLDCW of arg
+ | FLDLG2
+ | FLDLN2
+ | FLDZ
+ | FMUL of arg
+ | FMULP of arg * arg
+ | FNSTCW of arg
+ | FNSTSW of arg
+ | FPATAN
+ | FPTAN
+ | FSIN
+ | FSQRT
+ | FSTP of arg
+ | FSUB of arg
+ | FSUBP of arg * arg
+ | FSUBR of arg
+ | FSUBRP of arg * arg
+ | FXCH of arg
+ | FYL2X
+ | HLT
+ | IDIV of arg
+ | IMUL of arg * arg option
+ | INC of arg
+ | J of condition * arg
+ | JMP of arg
+ | LEA of arg * arg
+ | LEAVE
+ | MOV of arg * arg
+ | MOVAPD of arg * arg
+ | MOVLPD of arg * arg
+ | MOVSD of arg * arg
+ | MOVSS of arg * arg
+ | MOVSX of arg * arg
+ | MOVSXD of arg * arg
+ | MOVZX of arg * arg
+ | MULSD of arg * arg
+ | NEG of arg
+ | NOP
+ | OR of arg * arg
+ | POP of arg
+ | PUSH of arg
+ | RET
+ | ROUNDSD of rounding * arg * arg
+ | SAL of arg * arg
+ | SAR of arg * arg
+ | SET of condition * arg
+ | SHR of arg * arg
+ | SQRTSD of arg * arg
+ | SUB of arg * arg
+ | SUBSD of arg * arg
+ | TEST of arg * arg
+ | UCOMISD of arg * arg
+ | XCHG of arg * arg
+ | XOR of arg * arg
+ | XORPD of arg * arg
+
+type asm_line =
+ | Ins of instruction
+
+ | Align of bool * int
+ | Byte of constant
+ | Bytes of string
+ | Comment of string
+ | Global of string
+ | Long of constant
+ | NewLabel of string * data_type
+ | Quad of constant
+ | Section of string list * string option * string list
+ | Space of int
+ | Word of constant
+
+ (* masm only (the gas emitter will fail on them) *)
+ | External of string * data_type
+ | Mode386
+ | Model of string
+
+ (* gas only (the masm emitter will fail on them) *)
+ | Cfi_adjust_cfa_offset of int
+ | Cfi_endproc
+ | Cfi_startproc
+ | File of int * string (* (file_num, file_name) *)
+ | Indirect_symbol of string
+ | Loc of int * int * int (* (file_num, line, col) *)
+ | Private_extern of string
+ | Set of string * constant
+ | Size of string * constant
+ | Type of string * string
+
+type asm_program = asm_line list
diff --git a/asmcomp/x86_dsl.ml b/asmcomp/x86_dsl.ml
new file mode 100644
index 0000000000..45768a27bd
--- /dev/null
+++ b/asmcomp/x86_dsl.ml
@@ -0,0 +1,195 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Helpers for Intel code generators *)
+
+(* The DSL* modules expose functions to emit x86/x86_64 instructions
+ using a syntax close to AT&T (in particular, arguments are reversed compared
+ to the official Intel syntax).
+
+ Some notes:
+
+ - Unary floating point instructions such as fadd/fmul/fstp/fld/etc.
+ come with a single version supporting both the single and double
+ precision instructions. (As with Intel syntax.)
+
+ - A legacy bug in GAS:
+ https://sourceware.org/binutils/docs-2.22/as/i386_002dBugs.html#i386_002dBugs
+ is not replicated here. It is managed by X86_gas.
+*)
+
+
+open X86_ast
+open X86_proc
+
+let sym s = Sym s
+
+let nat n = Imm (Int64.of_nativeint n)
+let int n = Imm (Int64.of_int n)
+
+let const_32 n = Const (Int64.of_int32 n)
+let const_nat n = Const (Int64.of_nativeint n)
+let const n = Const (Int64.of_int n)
+
+let al = Reg8L RAX
+let ah = Reg8H AH
+let cl = Reg8L RCX
+let ax = Reg16 RAX
+let rax = Reg64 RAX
+let r10 = Reg64 R10
+let r11 = Reg64 R11
+let r14 = Reg64 R14
+let r15 = Reg64 R15
+let rsp = Reg64 RSP
+let rbp = Reg64 RBP
+let xmm15 = Regf (XMM 15)
+let eax = Reg32 RAX
+let ebx = Reg32 RBX
+let ecx = Reg32 RCX
+let edx = Reg32 RDX
+let ebp = Reg32 RBP
+let esp = Reg32 RSP
+let st0 = Regf (ST 0)
+let st1 = Regf (ST 1)
+
+let mem32 typ ?(scale = 1) ?base ?sym displ idx =
+ assert(scale >= 0);
+ Mem {arch = X86; typ; idx; scale; base; sym; displ}
+
+let mem64 typ ?(scale = 1) ?base ?sym displ idx =
+ assert(scale > 0);
+ Mem {arch = X64; typ; idx; scale; base; sym; displ}
+
+let mem64_rip typ ?(ofs = 0) s =
+ Mem64_RIP (typ, s, ofs)
+
+module D = struct
+ let section segment flags args = directive (Section (segment, flags, args))
+ let align n = directive (Align (false, n))
+ let byte n = directive (Byte n)
+ let bytes s = directive (Bytes s)
+ let cfi_adjust_cfa_offset n = directive (Cfi_adjust_cfa_offset n)
+ let cfi_endproc () = directive Cfi_endproc
+ let cfi_startproc () = directive Cfi_startproc
+ let comment s = directive (Comment s)
+ let data () = section [ ".data" ] None []
+ let extrn s ptr = directive (External (s, ptr))
+ let file ~file_num ~file_name = directive (File (file_num, file_name))
+ let global s = directive (Global s)
+ let indirect_symbol s = directive (Indirect_symbol s)
+ let label ?(typ = NONE) s = directive (NewLabel (s, typ))
+ let loc ~file_num ~line ~col = directive (Loc (file_num, line, col))
+ let long cst = directive (Long cst)
+ let mode386 () = directive Mode386
+ let model name = directive (Model name)
+ let private_extern s = directive (Private_extern s)
+ let qword cst = directive (Quad cst)
+ let setvar (x, y) = directive (Set (x, y))
+ let size name cst = directive (Size (name, cst))
+ let space n = directive (Space n)
+ let text () = section [ ".text" ] None []
+ let type_ name typ = directive (Type (name, typ))
+ let word cst = directive (Word cst)
+end
+
+module I = struct
+ let add x y = emit (ADD (x, y))
+ let addsd x y = emit (ADDSD (x, y))
+ let and_ x y= emit (AND (x, y))
+ let andpd x y = emit (ANDPD (x, y))
+ let bswap x = emit (BSWAP x)
+ let call x = emit (CALL x)
+ let cdq () = emit CDQ
+ let cmp x y = emit (CMP (x, y))
+ let comisd x y = emit (COMISD (x, y))
+ let cqo () = emit CQO
+ let cvtsd2ss x y = emit (CVTSD2SS (x, y))
+ let cvtsi2sd x y = emit (CVTSI2SD (x, y))
+ let cvtss2sd x y = emit (CVTSS2SD (x, y))
+ let cvttsd2si x y = emit (CVTTSD2SI (x, y))
+ let dec x = emit (DEC x)
+ let divsd x y = emit (DIVSD (x, y))
+ let fabs () = emit FABS
+ let fadd x = emit (FADD x)
+ let faddp x y = emit (FADDP (x, y))
+ let fchs () = emit FCHS
+ let fcomp x = emit (FCOMP x)
+ let fcompp () = emit FCOMPP
+ let fcos () = emit FCOS
+ let fdiv x = emit (FDIV x)
+ let fdivp x y = emit (FDIVP (x, y))
+ let fdivr x = emit (FDIVR x)
+ let fdivrp x y = emit (FDIVRP (x, y))
+ let fild x = emit (FILD x)
+ let fistp x = emit (FISTP x)
+ let fld x = emit (FLD x)
+ let fld1 () = emit FLD1
+ let fldcw x = emit (FLDCW x)
+ let fldlg2 () = emit FLDLG2
+ let fldln2 () = emit FLDLN2
+ let fldz () = emit FLDZ
+ let fmul x = emit (FMUL x)
+ let fmulp x y = emit (FMULP (x, y))
+ let fnstcw x = emit (FNSTCW x)
+ let fnstsw x = emit (FNSTSW x)
+ let fpatan () = emit FPATAN
+ let fptan () = emit FPTAN
+ let fsin () = emit FSIN
+ let fsqrt () = emit FSQRT
+ let fstp x = emit (FSTP x)
+ let fsub x = emit (FSUB x)
+ let fsubp x y = emit (FSUBP (x, y))
+ let fsubr x = emit (FSUBR x)
+ let fsubrp x y = emit (FSUBRP (x, y))
+ let fxch x = emit (FXCH x)
+ let fyl2x () = emit FYL2X
+ let hlt () = emit HLT
+ let idiv x = emit (IDIV x)
+ let imul x y = emit (IMUL (x, y))
+ let inc x = emit (INC x)
+ let j cond x = emit (J (cond, x))
+ let ja = j A
+ let jae = j AE
+ let jb = j B
+ let jbe = j BE
+ let je = j E
+ let jg = j G
+ let jmp x = emit (JMP x)
+ let jne = j NE
+ let jp = j P
+ let lea x y = emit (LEA (x, y))
+ let mov x y = emit (MOV (x, y))
+ let movapd x y = emit (MOVAPD (x, y))
+ let movsd x y = emit (MOVSD (x, y))
+ let movss x y = emit (MOVSS (x, y))
+ let movsx x y = emit (MOVSX (x, y))
+ let movsxd x y = emit (MOVSXD (x, y))
+ let movzx x y = emit (MOVZX (x, y))
+ let mulsd x y = emit (MULSD (x, y))
+ let nop () = emit NOP
+ let or_ x y = emit (OR (x, y))
+ let pop x = emit (POP x)
+ let push x = emit (PUSH x)
+ let ret () = emit RET
+ let sal x y = emit (SAL (x, y))
+ let sar x y = emit (SAR (x, y))
+ let set cond x = emit (SET (cond, x))
+ let shr x y = emit (SHR (x, y))
+ let sqrtsd x y = emit (SQRTSD (x, y))
+ let sub x y = emit (SUB (x, y))
+ let subsd x y = emit (SUBSD (x, y))
+ let test x y= emit (TEST (x, y))
+ let ucomisd x y = emit (UCOMISD (x, y))
+ let xchg x y = emit (XCHG (x, y))
+ let xor x y= emit (XOR (x, y))
+ let xorpd x y = emit (XORPD (x, y))
+end
diff --git a/asmcomp/x86_dsl.mli b/asmcomp/x86_dsl.mli
new file mode 100644
index 0000000000..6d1b4ca21a
--- /dev/null
+++ b/asmcomp/x86_dsl.mli
@@ -0,0 +1,188 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Helpers for Intel code generators *)
+
+(* The DSL* modules expose functions to emit x86/x86_64 instructions
+ using a syntax close to the official Intel syntax, except that
+ source and destination operands are reversed as in the AT&T
+ syntax:
+
+ mov src dst
+*)
+
+
+open X86_ast
+
+val sym: string -> arg
+val nat: nativeint -> arg
+val int: int -> arg
+val const_32: int32 -> constant
+val const_nat: nativeint -> constant
+val const: int -> constant
+val al: arg
+val ah: arg
+val cl: arg
+val ax: arg
+val rax: arg
+val r10: arg
+val r11: arg
+val r14: arg
+val r15: arg
+val rsp: arg
+val rbp: arg
+val xmm15: arg
+val eax: arg
+val ebx: arg
+val ecx: arg
+val edx: arg
+val ebp: arg
+val esp: arg
+val st0: arg
+val st1: arg
+
+val mem32:
+ data_type -> ?scale:int -> ?base:reg64 -> ?sym:string ->
+ int -> reg64 -> arg
+
+val mem64:
+ data_type -> ?scale:int -> ?base:reg64 -> ?sym:string ->
+ int -> reg64 -> arg
+
+val mem64_rip: data_type -> ?ofs:int -> string -> arg
+
+
+module D : sig
+ (** Directives *)
+
+ val align: int -> unit
+ val byte: constant -> unit
+ val bytes: string -> unit
+ val cfi_adjust_cfa_offset: int -> unit
+ val cfi_endproc: unit -> unit
+ val cfi_startproc: unit -> unit
+ val comment: string -> unit
+ val data: unit -> unit
+ val extrn: string -> data_type -> unit
+ val file: file_num:int -> file_name:string -> unit
+ val global: string -> unit
+ val indirect_symbol: string -> unit
+ val label: ?typ:data_type -> string -> unit
+ val loc: file_num:int -> line:int -> col:int -> unit
+ val long: constant -> unit
+ val mode386: unit -> unit
+ val model: string -> unit
+ val private_extern: string -> unit
+ val qword: constant -> unit
+ val section: string list -> string option -> string list -> unit
+ val setvar: string * constant -> unit
+ val size: string -> constant -> unit
+ val space: int -> unit
+ val text: unit -> unit
+ val type_: string -> string -> unit
+ val word: constant -> unit
+end
+
+module I : sig
+ (* Instructions *)
+
+ val add: arg -> arg -> unit
+ val addsd: arg -> arg -> unit
+ val and_: arg -> arg -> unit
+ val andpd: arg -> arg -> unit
+ val bswap: arg -> unit
+ val call: arg -> unit
+ val cdq: unit -> unit
+ val cmp: arg -> arg -> unit
+ val comisd: arg -> arg -> unit
+ val cqo: unit -> unit
+ val cvtsd2ss: arg -> arg -> unit
+ val cvtsi2sd: arg -> arg -> unit
+ val cvtss2sd: arg -> arg -> unit
+ val cvttsd2si: arg -> arg -> unit
+ val dec: arg -> unit
+ val divsd: arg -> arg -> unit
+ val fabs: unit -> unit
+ val fadd: arg -> unit
+ val faddp: arg -> arg -> unit
+ val fchs: unit -> unit
+ val fcomp: arg -> unit
+ val fcompp: unit -> unit
+ val fcos: unit -> unit
+ val fdiv: arg -> unit
+ val fdivp: arg -> arg -> unit
+ val fdivr: arg -> unit
+ val fdivrp: arg -> arg -> unit
+ val fild: arg -> unit
+ val fistp: arg -> unit
+ val fld1: unit -> unit
+ val fld: arg -> unit
+ val fldcw: arg -> unit
+ val fldlg2: unit -> unit
+ val fldln2: unit -> unit
+ val fldz: unit -> unit
+ val fmul: arg -> unit
+ val fmulp: arg -> arg -> unit
+ val fnstcw: arg -> unit
+ val fnstsw: arg -> unit
+ val fpatan: unit -> unit
+ val fptan: unit -> unit
+ val fsin: unit -> unit
+ val fsqrt: unit -> unit
+ val fstp: arg -> unit
+ val fsub: arg -> unit
+ val fsubp: arg -> arg -> unit
+ val fsubr: arg -> unit
+ val fsubrp: arg -> arg -> unit
+ val fxch: arg -> unit
+ val fyl2x: unit -> unit
+ val hlt: unit -> unit
+ val idiv: arg -> unit
+ val imul: arg -> arg option -> unit
+ val inc: arg -> unit
+ val j: condition -> arg -> unit
+ val ja: arg -> unit
+ val jae: arg -> unit
+ val jb: arg -> unit
+ val jbe: arg -> unit
+ val je: arg -> unit
+ val jg: arg -> unit
+ val jmp: arg -> unit
+ val jne: arg -> unit
+ val jp: arg -> unit
+ val lea: arg -> arg -> unit
+ val mov: arg -> arg -> unit
+ val movapd: arg -> arg -> unit
+ val movsd: arg -> arg -> unit
+ val movss: arg -> arg -> unit
+ val movsx: arg -> arg -> unit
+ val movsxd: arg -> arg -> unit
+ val movzx: arg -> arg -> unit
+ val mulsd: arg -> arg -> unit
+ val nop: unit -> unit
+ val or_: arg -> arg -> unit
+ val pop: arg -> unit
+ val push: arg -> unit
+ val ret: unit -> unit
+ val sal: arg -> arg -> unit
+ val sar: arg -> arg -> unit
+ val set: condition -> arg -> unit
+ val shr: arg -> arg -> unit
+ val sqrtsd: arg -> arg -> unit
+ val sub: arg -> arg -> unit
+ val subsd: arg -> arg -> unit
+ val test: arg -> arg -> unit
+ val ucomisd: arg -> arg -> unit
+ val xchg: arg -> arg -> unit
+ val xor: arg -> arg -> unit
+ val xorpd: arg -> arg -> unit
+end
diff --git a/asmcomp/x86_gas.ml b/asmcomp/x86_gas.ml
new file mode 100644
index 0000000000..dd1f9bc95a
--- /dev/null
+++ b/asmcomp/x86_gas.ml
@@ -0,0 +1,305 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open X86_ast
+open X86_proc
+
+let bprintf = Printf.bprintf
+
+let print_reg b f r =
+ Buffer.add_char b '%';
+ Buffer.add_string b (f r)
+
+let opt_displ b displ =
+ if displ = 0 then ()
+ else if displ > 0 then bprintf b "+%d" displ
+ else bprintf b "%d" displ
+
+let arg_mem b {arch; typ=_; idx; scale; base; sym; displ} =
+ let string_of_register =
+ match arch with
+ | X86 -> string_of_reg32
+ | X64 -> string_of_reg64
+ in
+ begin match sym with
+ | None ->
+ if displ <> 0 || scale = 0 then
+ Buffer.add_string b (string_of_int displ)
+ | Some s ->
+ Buffer.add_string b s;
+ opt_displ b displ
+ end;
+ if scale <> 0 then begin
+ Buffer.add_char b '(';
+ begin match base with
+ | None -> ()
+ | Some base -> print_reg b string_of_register base
+ end;
+ if base != None || scale <> 1 then Buffer.add_char b ',';
+ print_reg b string_of_register idx;
+ if scale <> 1 then bprintf b ",%s" (string_of_int scale);
+ Buffer.add_char b ')'
+ end
+
+let arg b = function
+ | Sym x -> Buffer.add_char b '$'; Buffer.add_string b x
+ | Imm x -> bprintf b "$%Ld" x
+ | Reg8L x -> print_reg b string_of_reg8l x
+ | Reg8H x -> print_reg b string_of_reg8h x
+ | Reg16 x -> print_reg b string_of_reg16 x
+ | Reg32 x -> print_reg b string_of_reg32 x
+ | Reg64 x -> print_reg b string_of_reg64 x
+ | Regf x -> print_reg b string_of_registerf x
+ | Mem addr -> arg_mem b addr
+ | Mem64_RIP (_, s, displ) -> bprintf b "%s%a(%%rip)" s opt_displ displ
+
+let rec cst b = function
+ | ConstLabel _ | Const _ | ConstThis as c -> scst b c
+ | ConstAdd (c1, c2) -> bprintf b "%a + %a" scst c1 scst c2
+ | ConstSub (c1, c2) -> bprintf b "%a - %a" scst c1 scst c2
+
+and scst b = function
+ | ConstThis -> Buffer.add_string b "."
+ | ConstLabel l -> Buffer.add_string b l
+ | Const n when n <= 0x7FFF_FFFFL && n >= -0x8000_0000L ->
+ Buffer.add_string b (Int64.to_string n)
+ | Const n -> bprintf b "0x%Lx" n
+ | ConstAdd (c1, c2) -> bprintf b "(%a + %a)" scst c1 scst c2
+ | ConstSub (c1, c2) -> bprintf b "(%a - %a)" scst c1 scst c2
+
+let typeof = function
+ | Mem {typ; _} | Mem64_RIP (typ, _, _) -> typ
+ | Reg8L _ | Reg8H _ -> BYTE
+ | Reg16 _ -> WORD
+ | Reg32 _ -> DWORD
+ | Reg64 _ -> QWORD
+ | Imm _ | Sym _ -> NONE
+ | Regf _ -> assert false
+
+let suf arg =
+ match typeof arg with
+ | BYTE -> "b"
+ | WORD -> "w"
+ | DWORD | REAL8 -> "l"
+ | QWORD -> "q"
+ | REAL4 -> "s"
+ | NONE -> ""
+ | OWORD | NEAR | PROC -> assert false
+
+let i0 b s = bprintf b "\t%s" s
+let i1 b s x = bprintf b "\t%s\t%a" s arg x
+let i1_s b s x = bprintf b "\t%s%s\t%a" s (suf x) arg x
+let i2 b s x y = bprintf b "\t%s\t%a, %a" s arg x arg y
+let i2_s b s x y = bprintf b "\t%s%s\t%a, %a" s (suf y) arg x arg y
+let i2_ss b s x y = bprintf b "\t%s%s%s\t%a, %a" s (suf x) (suf y) arg x arg y
+
+let i1_call_jmp b s = function
+ (* this is the encoding of jump labels: don't use * *)
+ | Mem {arch=X86; idx=_; scale=0; base=None; sym=Some _; _} as x ->
+ i1 b s x
+ | Reg32 _ | Reg64 _ | Mem _ | Mem64_RIP _ as x ->
+ bprintf b "\t%s\t*%a" s arg x
+ | Sym x -> bprintf b "\t%s\t%s" s x
+ | _ -> assert false
+
+let print_instr b = function
+ | ADD (arg1, arg2) -> i2_s b "add" arg1 arg2
+ | ADDSD (arg1, arg2) -> i2 b "addsd" arg1 arg2
+ | AND (arg1, arg2) -> i2_s b "and" arg1 arg2
+ | ANDPD (arg1, arg2) -> i2 b "andpd" arg1 arg2
+ | BSWAP arg -> i1 b "bswap" arg
+ | CALL arg -> i1_call_jmp b "call" arg
+ | CDQ -> i0 b "cltd"
+ | CMOV (c, arg1, arg2) -> i2 b ("cmov" ^ string_of_condition c) arg1 arg2
+ | CMP (arg1, arg2) -> i2_s b "cmp" arg1 arg2
+ | COMISD (arg1, arg2) -> i2 b "comisd" arg1 arg2
+ | CQO -> i0 b "cqto"
+ | CVTSD2SI (arg1, arg2) -> i2 b "cvtsd2si" arg1 arg2
+ | CVTSD2SS (arg1, arg2) -> i2 b "cvtsd2ss" arg1 arg2
+ | CVTSI2SD (arg1, arg2) -> i2 b ("cvtsi2sd" ^ suf arg1) arg1 arg2
+ | CVTSS2SD (arg1, arg2) -> i2 b "cvtss2sd" arg1 arg2
+ | CVTTSD2SI (arg1, arg2) -> i2_s b "cvttsd2si" arg1 arg2
+ | DEC arg -> i1_s b "dec" arg
+ | DIVSD (arg1, arg2) -> i2 b "divsd" arg1 arg2
+ | FABS -> i0 b "fabs"
+ | FADD arg -> i1_s b "fadd" arg
+ | FADDP (arg1, arg2) -> i2 b "faddp" arg1 arg2
+ | FCHS -> i0 b "fchs"
+ | FCOMP arg -> i1_s b "fcomp" arg
+ | FCOMPP -> i0 b "fcompp"
+ | FCOS -> i0 b "fcos"
+ | FDIV arg -> i1_s b "fdiv" arg
+ | FDIVP (Regf (ST 0), arg2) -> i2 b "fdivrp" (Regf (ST 0)) arg2 (* bug *)
+ | FDIVP (arg1, arg2) -> i2 b "fdivp" arg1 arg2
+ | FDIVR arg -> i1_s b "fdivr" arg
+ | FDIVRP (Regf (ST 0), arg2) -> i2 b "fdivp" (Regf (ST 0)) arg2 (* bug *)
+ | FDIVRP (arg1, arg2) -> i2 b "fdivrp" arg1 arg2
+ | FILD arg -> i1_s b "fild" arg
+ | FISTP arg -> i1_s b "fistp" arg
+ | FLD (Mem {typ=REAL4; _} as arg) -> i1 b "flds" arg
+ | FLD arg -> i1 b "fldl" arg
+ | FLD1 -> i0 b "fld1"
+ | FLDCW arg -> i1 b "fldcw" arg
+ | FLDLG2 -> i0 b "fldlg2"
+ | FLDLN2 -> i0 b "fldln2"
+ | FLDZ -> i0 b "fldz"
+ | FMUL arg -> i1_s b "fmul" arg
+ | FMULP (arg1, arg2) -> i2 b "fmulp" arg1 arg2
+ | FNSTCW arg -> i1 b "fnstcw" arg
+ | FNSTSW arg -> i1 b "fnstsw" arg
+ | FPATAN -> i0 b "fpatan"
+ | FPTAN -> i0 b "fptan"
+ | FSIN -> i0 b "fsin"
+ | FSQRT -> i0 b "fsqrt"
+ | FSTP (Mem {typ=REAL4; _} as arg) -> i1 b "fstps" arg
+ | FSTP arg -> i1 b "fstpl" arg
+ | FSUB arg -> i1_s b "fsub" arg
+ | FSUBP (Regf (ST 0), arg2) -> i2 b "fsubrp" (Regf (ST 0)) arg2 (* bug *)
+ | FSUBP (arg1, arg2) -> i2 b "fsubp" arg1 arg2
+ | FSUBR arg -> i1_s b "fsubr" arg
+ | FSUBRP (Regf (ST 0), arg2) -> i2 b "fsubp" (Regf (ST 0)) arg2 (* bug *)
+ | FSUBRP (arg1, arg2) -> i2 b "fsubrp" arg1 arg2
+ | FXCH arg -> i1 b "fxch" arg
+ | FYL2X -> i0 b "fyl2x"
+ | HLT -> i0 b "hlt"
+ | IDIV arg -> i1_s b "idiv" arg
+ | IMUL (arg, None) -> i1_s b "imul" arg
+ | IMUL (arg1, Some arg2) -> i2_s b "imul" arg1 arg2
+ | INC arg -> i1_s b "inc" arg
+ | J (c, arg) -> i1_call_jmp b ("j" ^ string_of_condition c) arg
+ | JMP arg -> i1_call_jmp b "jmp" arg
+ | LEA (arg1, arg2) -> i2_s b "lea" arg1 arg2
+ | LEAVE -> i0 b "leave"
+ | MOV ((Imm n as arg1), (Reg64 _ as arg2))
+ when not (n <= 0x7FFF_FFFFL && n >= -0x8000_0000L) ->
+ i2 b "movabsq" arg1 arg2
+ | MOV ((Sym _ as arg1), (Reg64 _ as arg2)) when windows ->
+ i2 b "movabsq" arg1 arg2
+ | MOV (arg1, arg2) -> i2_s b "mov" arg1 arg2
+ | MOVAPD (arg1, arg2) -> i2 b "movapd" arg1 arg2
+ | MOVLPD (arg1, arg2) -> i2 b "movlpd" arg1 arg2
+ | MOVSD (arg1, arg2) -> i2 b "movsd" arg1 arg2
+ | MOVSS (arg1, arg2) -> i2 b "movss" arg1 arg2
+ | MOVSX (arg1, arg2) -> i2_ss b "movs" arg1 arg2
+ | MOVSXD (arg1, arg2) -> i2 b "movslq" arg1 arg2
+ | MOVZX (arg1, arg2) -> i2_ss b "movz" arg1 arg2
+ | MULSD (arg1, arg2) -> i2 b "mulsd" arg1 arg2
+ | NEG arg -> i1 b "neg" arg
+ | NOP -> i0 b "nop"
+ | OR (arg1, arg2) -> i2_s b "or" arg1 arg2
+ | POP arg -> i1_s b "pop" arg
+ | PUSH arg -> i1_s b "push" arg
+ | RET -> i0 b "ret"
+ | ROUNDSD (r, arg1, arg2) -> i2 b (string_of_rounding r) arg1 arg2
+ | SAL (arg1, arg2) -> i2_s b "sal" arg1 arg2
+ | SAR (arg1, arg2) -> i2_s b "sar" arg1 arg2
+ | SET (c, arg) -> i1 b ("set" ^ string_of_condition c) arg
+ | SHR (arg1, arg2) -> i2_s b "shr" arg1 arg2
+ | SQRTSD (arg1, arg2) -> i2 b "sqrtsd" arg1 arg2
+ | SUB (arg1, arg2) -> i2_s b "sub" arg1 arg2
+ | SUBSD (arg1, arg2) -> i2 b "subsd" arg1 arg2
+ | TEST (arg1, arg2) -> i2_s b "test" arg1 arg2
+ | UCOMISD (arg1, arg2) -> i2 b "ucomisd" arg1 arg2
+ | XCHG (arg1, arg2) -> i2 b "xchg" arg1 arg2
+ | XOR (arg1, arg2) -> i2_s b "xor" arg1 arg2
+ | XORPD (arg1, arg2) -> i2 b "xorpd" arg1 arg2
+
+(* bug:
+ https://sourceware.org/binutils/docs-2.22/as/i386_002dBugs.html#i386_002dBugs
+
+ The AT&T syntax has a bug for fsub/fdiv/fsubr/fdivr instructions when
+ the source register is %st and the destination is %st(i). In those
+ case, AT&T use fsub (resp. fsubr) in place of fsubr (resp. fsub),
+ and idem for fdiv/fdivr.
+
+ Concretely, AT&T syntax interpretation of:
+
+ fsub %st, %st(3)
+
+ should normally be:
+
+ %st(3) := %st(3) - %st
+
+ but it should actually be interpreted as:
+
+ %st(3) := %st - %st(3)
+
+ which means the FSUBR instruction should be used.
+*)
+
+
+let print_line b = function
+ | Ins instr -> print_instr b instr
+
+ | Align (_data,n) ->
+ (* MacOSX assembler interprets the integer n as a 2^n alignment *)
+ let n = if system = S_macosx then Misc.log2 n else n in
+ bprintf b "\t.align\t%d" n
+ | Byte n -> bprintf b "\t.byte\t%a" cst n
+ | Bytes s ->
+ if system = S_solaris then buf_bytes_directive b ".byte" s
+ else bprintf b "\t.ascii\t\"%s\"" (string_of_string_literal s)
+ | Comment s -> bprintf b "\t\t\t\t/* %s */" s
+ | Global s -> bprintf b "\t.globl\t%s" s;
+ | Long n -> bprintf b "\t.long\t%a" cst n
+ | NewLabel (s, _) -> bprintf b "%s:" s
+ | Quad n -> bprintf b "\t.quad\t%a" cst n
+ | Section ([".data" ], _, _) -> bprintf b "\t.data"
+ | Section ([".text" ], _, _) -> bprintf b "\t.text"
+ | Section (name, flags, args) ->
+ bprintf b "\t.section %s" (String.concat "," name);
+ begin match flags with
+ | None -> ()
+ | Some flags -> bprintf b ",%S" flags
+ end;
+ begin match args with
+ | [] -> ()
+ | _ -> bprintf b ",%s" (String.concat "," args)
+ end
+ | Space n ->
+ if system = S_solaris then bprintf b "\t.zero\t%d" n
+ else bprintf b "\t.space\t%d" n
+ | Word n ->
+ if system = S_solaris then bprintf b "\t.value\t%a" cst n
+ else bprintf b "\t.word\t%a" cst n
+
+ (* gas only *)
+ | Cfi_adjust_cfa_offset n -> bprintf b "\t.cfi_adjust_cfa_offset %d" n
+ | Cfi_endproc -> bprintf b "\t.cfi_endproc"
+ | Cfi_startproc -> bprintf b "\t.cfi_startproc"
+ | File (file_num, file_name) ->
+ bprintf b "\t.file\t%d\t\"%s\""
+ file_num (X86_proc.string_of_string_literal file_name)
+ | Indirect_symbol s -> bprintf b "\t.indirect_symbol %s" s
+ | Loc (file_num, line, col) ->
+ bprintf b "\t.loc\t%d\t%d\t%d" file_num line col
+ | Private_extern s -> bprintf b "\t.private_extern %s" s
+ | Set (arg1, arg2) -> bprintf b "\t.set %s, %a" arg1 cst arg2
+ | Size (s, c) -> bprintf b "\t.size %s,%a" s cst c
+ | Type (s, typ) -> bprintf b "\t.type %s,%s" s typ
+
+ (* masm only *)
+ | External _
+ | Mode386
+ | Model _
+ -> assert false
+
+let generate_asm oc lines =
+ let b = Buffer.create 10000 in
+ List.iter
+ (fun i ->
+ Buffer.clear b;
+ print_line b i;
+ Buffer.add_char b '\n';
+ Buffer.output_buffer oc b;
+ )
+ lines
diff --git a/asmcomp/x86_gas.mli b/asmcomp/x86_gas.mli
new file mode 100644
index 0000000000..b25cc8f336
--- /dev/null
+++ b/asmcomp/x86_gas.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Emit assembly instructions for gas. *)
+
+val generate_asm: out_channel -> X86_ast.asm_line list -> unit
diff --git a/asmcomp/x86_masm.ml b/asmcomp/x86_masm.ml
new file mode 100644
index 0000000000..40f0ba06df
--- /dev/null
+++ b/asmcomp/x86_masm.ml
@@ -0,0 +1,258 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open X86_ast
+open X86_proc
+
+let bprintf = Printf.bprintf
+
+let string_of_datatype = function
+ | QWORD -> "QWORD"
+ | OWORD -> "OWORD"
+ | NONE -> assert false
+ | REAL4 -> "REAL4"
+ | REAL8 -> "REAL8"
+ | BYTE -> "BYTE"
+ | WORD -> "WORD"
+ | DWORD -> "DWORD"
+ | NEAR -> "NEAR"
+ | PROC -> "PROC"
+
+
+let string_of_datatype_ptr = function
+ | QWORD -> "QWORD PTR "
+ | OWORD -> "OWORD PTR "
+ | NONE -> ""
+ | REAL4 -> "REAL4 PTR "
+ | REAL8 -> "REAL8 PTR "
+ | BYTE -> "BYTE PTR "
+ | WORD -> "WORD PTR "
+ | DWORD -> "DWORD PTR "
+ | NEAR -> "NEAR PTR "
+ | PROC -> "PROC PTR "
+
+let arg_mem b {arch; typ; idx; scale; base; sym; displ} =
+ let string_of_register =
+ match arch with
+ | X86 -> string_of_reg32
+ | X64 -> string_of_reg64
+ in
+ Buffer.add_string b (string_of_datatype_ptr typ);
+ Buffer.add_char b '[';
+ begin match sym with
+ | None -> ()
+ | Some s -> Buffer.add_string b s
+ end;
+ if scale <> 0 then begin
+ if sym <> None then Buffer.add_char b '+';
+ Buffer.add_string b (string_of_register idx);
+ if scale <> 1 then bprintf b "*%d" scale;
+ end;
+ begin match base with
+ | None -> ()
+ | Some r ->
+ assert(scale > 0);
+ Buffer.add_char b '+';
+ Buffer.add_string b (string_of_register r);
+ end;
+ begin if displ > 0 then bprintf b "+%d" displ
+ else if displ < 0 then bprintf b "%d" displ
+ end;
+ Buffer.add_char b ']'
+
+let arg b = function
+ | Sym s -> bprintf b "OFFSET %s" s
+ | Imm n when n <= 0x7FFF_FFFFL && n >= -0x8000_0000L -> bprintf b "%Ld" n
+ | Imm int -> bprintf b "0%LxH" int (* force ml64 to use mov reg, imm64 *)
+ | Reg8L x -> Buffer.add_string b (string_of_reg8l x)
+ | Reg8H x -> Buffer.add_string b (string_of_reg8h x)
+ | Reg16 x -> Buffer.add_string b (string_of_reg16 x)
+ | Reg32 x -> Buffer.add_string b (string_of_reg32 x)
+ | Reg64 x -> Buffer.add_string b (string_of_reg64 x)
+ | Regf x -> Buffer.add_string b (string_of_registerf x)
+
+ (* We don't need to specify RIP on Win64, since EXTERN will provide
+ the list of external symbols that need this addressing mode, and
+ MASM will automatically use RIP addressing when needed. *)
+ | Mem64_RIP (typ, s, displ) ->
+ bprintf b "%s%s" (string_of_datatype_ptr typ) s;
+ if displ > 0 then bprintf b "+%d" displ
+ else if displ < 0 then bprintf b "%d" displ
+ | Mem addr -> arg_mem b addr
+
+let rec cst b = function
+ | ConstLabel _ | Const _ | ConstThis as c -> scst b c
+ | ConstAdd (c1, c2) -> bprintf b "%a + %a" scst c1 scst c2
+ | ConstSub (c1, c2) -> bprintf b "%a - %a" scst c1 scst c2
+
+and scst b = function
+ | ConstThis -> Buffer.add_string b "THIS BYTE"
+ | ConstLabel l -> Buffer.add_string b l
+ | Const n when n <= 0x7FFF_FFFFL && n >= -0x8000_0000L ->
+ Buffer.add_string b (Int64.to_string n)
+ | Const n -> bprintf b "0%LxH" n
+ | ConstAdd (c1, c2) -> bprintf b "(%a + %a)" scst c1 scst c2
+ | ConstSub (c1, c2) -> bprintf b "(%a - %a)" scst c1 scst c2
+
+let i0 b s = bprintf b "\t%s" s
+let i1 b s x = bprintf b "\t%s\t%a" s arg x
+let i2 b s x y = bprintf b "\t%s\t%a, %a" s arg y arg x
+
+let i1_call_jmp b s = function
+ | Sym x -> bprintf b "\t%s\t%s" s x
+ | x -> i1 b s x
+
+let print_instr b = function
+ | ADD (arg1, arg2) -> i2 b "add" arg1 arg2
+ | ADDSD (arg1, arg2) -> i2 b "addsd" arg1 arg2
+ | AND (arg1, arg2) -> i2 b "and" arg1 arg2
+ | ANDPD (arg1, arg2) -> i2 b "andpd" arg1 arg2
+ | BSWAP arg -> i1 b "bswap" arg
+ | CALL arg -> i1_call_jmp b "call" arg
+ | CDQ -> i0 b "cdq"
+ | CMOV (c, arg1, arg2) -> i2 b ("cmov" ^ string_of_condition c) arg1 arg2
+ | CMP (arg1, arg2) -> i2 b "cmp" arg1 arg2
+ | COMISD (arg1, arg2) -> i2 b "comisd" arg1 arg2
+ | CQO -> i0 b "cqo"
+ | CVTSD2SI (arg1, arg2) -> i2 b "cvtsd2si" arg1 arg2
+ | CVTSD2SS (arg1, arg2) -> i2 b "cvtsd2ss" arg1 arg2
+ | CVTSI2SD (arg1, arg2) -> i2 b "cvtsi2sd" arg1 arg2
+ | CVTSS2SD (arg1, arg2) -> i2 b "cvtss2sd" arg1 arg2
+ | CVTTSD2SI (arg1, arg2) -> i2 b "cvttsd2si" arg1 arg2
+ | DEC arg -> i1 b "dec" arg
+ | DIVSD (arg1, arg2) -> i2 b "divsd" arg1 arg2
+ | FABS -> i0 b "fabs"
+ | FADD arg -> i1 b "fadd" arg
+ | FADDP (arg1, arg2) -> i2 b "faddp" arg1 arg2
+ | FCHS -> i0 b "fchs"
+ | FCOMP arg -> i1 b "fcomp" arg
+ | FCOMPP -> i0 b "fcompp"
+ | FCOS -> i0 b "fcos"
+ | FDIV arg -> i1 b "fdiv" arg
+ | FDIVP (arg1, arg2) -> i2 b "fdivp" arg1 arg2
+ | FDIVR arg -> i1 b "fdivr" arg
+ | FDIVRP (arg1, arg2) -> i2 b "fdivrp" arg1 arg2
+ | FILD arg -> i1 b "fild" arg
+ | FISTP arg -> i1 b "fistp" arg
+ | FLD arg -> i1 b "fld" arg
+ | FLD1 -> i0 b "fld1"
+ | FLDCW arg -> i1 b "fldcw" arg
+ | FLDLG2 -> i0 b "fldlg2"
+ | FLDLN2 -> i0 b "fldln2"
+ | FLDZ -> i0 b "fldz"
+ | FMUL arg -> i1 b "fmul" arg
+ | FMULP (arg1, arg2) -> i2 b "fmulp" arg1 arg2
+ | FNSTCW arg -> i1 b "fnstcw" arg
+ | FNSTSW arg -> i1 b "fnstsw" arg
+ | FPATAN -> i0 b "fpatan"
+ | FPTAN -> i0 b "fptan"
+ | FSIN -> i0 b "fsin"
+ | FSQRT -> i0 b "fsqrt"
+ | FSTP arg -> i1 b "fstp" arg
+ | FSUB arg -> i1 b "fsub" arg
+ | FSUBP (arg1, arg2) -> i2 b "fsubp" arg1 arg2
+ | FSUBR arg -> i1 b "fsubr" arg
+ | FSUBRP (arg1, arg2) -> i2 b "fsubrp" arg1 arg2
+ | FXCH arg -> i1 b "fxch" arg
+ | FYL2X -> i0 b "fyl2x"
+ | HLT -> assert false
+ | IDIV arg -> i1 b "idiv" arg
+ | IMUL (arg, None) -> i1 b "imul" arg
+ | IMUL (arg1, Some arg2) -> i2 b "imul" arg1 arg2
+ | INC arg -> i1 b "inc" arg
+ | J (c, arg) -> i1_call_jmp b ("j" ^ string_of_condition c) arg
+ | JMP arg -> i1_call_jmp b "jmp" arg
+ | LEA (arg1, arg2) -> i2 b "lea" arg1 arg2
+ | LEAVE -> i0 b "leave"
+ | MOV (Imm n as arg1, Reg64 r) when
+ n >= 0x8000_0000L && n <= 0xFFFF_FFFFL ->
+ (* Work-around a bug in ml64. Use a mov to the corresponding
+ 32-bit lower register when the constant fits in 32-bit.
+ The associated higher 32-bit register will be zeroed. *)
+ i2 b "mov" arg1 (Reg32 r)
+ | MOV (arg1, arg2) -> i2 b "mov" arg1 arg2
+ | MOVAPD (arg1, arg2) -> i2 b "movapd" arg1 arg2
+ | MOVLPD (arg1, arg2) -> i2 b "movlpd" arg1 arg2
+ | MOVSD (arg1, arg2) -> i2 b "movsd" arg1 arg2
+ | MOVSS (arg1, arg2) -> i2 b "movss" arg1 arg2
+ | MOVSX (arg1, arg2) -> i2 b "movsx" arg1 arg2
+ | MOVSXD (arg1, arg2) -> i2 b "movsxd" arg1 arg2
+ | MOVZX (arg1, arg2) -> i2 b "movzx" arg1 arg2
+ | MULSD (arg1, arg2) -> i2 b "mulsd" arg1 arg2
+ | NEG arg -> i1 b "neg" arg
+ | NOP -> i0 b "nop"
+ | OR (arg1, arg2) -> i2 b "or" arg1 arg2
+ | POP arg -> i1 b "pop" arg
+ | PUSH arg -> i1 b "push" arg
+ | RET -> i0 b "ret"
+ | ROUNDSD (r, arg1, arg2) -> i2 b (string_of_rounding r) arg1 arg2
+ | SAL (arg1, arg2) -> i2 b "sal" arg1 arg2
+ | SAR (arg1, arg2) -> i2 b "sar" arg1 arg2
+ | SET (c, arg) -> i1 b ("set" ^ string_of_condition c) arg
+ | SHR (arg1, arg2) -> i2 b "shr" arg1 arg2
+ | SQRTSD (arg1, arg2) -> i2 b "sqrtsd" arg1 arg2
+ | SUB (arg1, arg2) -> i2 b "sub" arg1 arg2
+ | SUBSD (arg1, arg2) -> i2 b "subsd" arg1 arg2
+ | TEST (arg1, arg2) -> i2 b "test" arg1 arg2
+ | UCOMISD (arg1, arg2) -> i2 b "ucomisd" arg1 arg2
+ | XCHG (arg1, arg2) -> i2 b "xchg" arg1 arg2
+ | XOR (arg1, arg2) -> i2 b "xor" arg1 arg2
+ | XORPD (arg1, arg2) -> i2 b "xorpd" arg1 arg2
+
+
+let print_line b = function
+ | Ins instr -> print_instr b instr
+
+ | Align (_data,n) -> bprintf b "\tALIGN\t%d" n
+ | Byte n -> bprintf b "\tBYTE\t%a" cst n
+ | Bytes s -> buf_bytes_directive b "BYTE" s
+ | Comment s -> bprintf b " ; %s " s
+ | Global s -> bprintf b "\tPUBLIC\t%s" s
+ | Long n -> bprintf b "\tDWORD\t%a" cst n
+ | NewLabel (s, NONE) -> bprintf b "%s:" s
+ | NewLabel (s, ptr) -> bprintf b "%s LABEL %s" s (string_of_datatype ptr)
+ | Quad n -> bprintf b "\tQWORD\t%a" cst n
+ | Section ([".data"], None, []) -> bprintf b "\t.DATA"
+ | Section ([".text"], None, []) -> bprintf b "\t.CODE"
+ | Section _ -> assert false
+ | Space n -> bprintf b "\tBYTE\t%d DUP (?)" n
+ | Word n -> bprintf b "\tWORD\t%a" cst n
+
+ (* windows only *)
+ | External (s, ptr) -> bprintf b "\tEXTRN\t%s: %s" s (string_of_datatype ptr)
+ | Mode386 -> bprintf b "\t.386"
+ | Model name -> bprintf b "\t.MODEL %s" name (* name = FLAT *)
+
+ (* gas only *)
+ | Cfi_adjust_cfa_offset _
+ | Cfi_endproc
+ | Cfi_startproc
+ | File _
+ | Indirect_symbol _
+ | Loc _
+ | Private_extern _
+ | Set _
+ | Size _
+ | Type _
+ -> assert false
+
+let generate_asm oc lines =
+ let b = Buffer.create 10000 in
+ List.iter
+ (fun i ->
+ Buffer.clear b;
+ print_line b i;
+ Buffer.add_char b '\n';
+ Buffer.output_buffer oc b
+ )
+ lines;
+ output_string oc "\tEND\n"
diff --git a/asmcomp/x86_masm.mli b/asmcomp/x86_masm.mli
new file mode 100644
index 0000000000..1b3a6e066d
--- /dev/null
+++ b/asmcomp/x86_masm.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Emit assembly instructions for MASM (Intel syntax). *)
+
+val generate_asm: out_channel -> X86_ast.asm_line list -> unit
diff --git a/asmcomp/x86_proc.ml b/asmcomp/x86_proc.ml
new file mode 100644
index 0000000000..802013a446
--- /dev/null
+++ b/asmcomp/x86_proc.ml
@@ -0,0 +1,272 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open X86_ast
+
+type system =
+ (* 32 bits and 64 bits *)
+ | S_macosx
+ | S_gnu
+ | S_cygwin
+
+ (* 32 bits only *)
+ | S_solaris
+ | S_win32
+ | S_linux_elf
+ | S_bsd_elf
+ | S_beos
+ | S_mingw
+
+ (* 64 bits only *)
+ | S_win64
+ | S_linux
+ | S_mingw64
+
+ | S_unknown
+
+
+let system = match Config.system with
+ | "macosx" -> S_macosx
+ | "solaris" -> S_solaris
+ | "win32" -> S_win32
+ | "linux_elf" -> S_linux_elf
+ | "bsd_elf" -> S_bsd_elf
+ | "beos" -> S_beos
+ | "gnu" -> S_gnu
+ | "cygwin" -> S_cygwin
+ | "mingw" -> S_mingw
+ | "mingw64" -> S_mingw64
+ | "win64" -> S_win64
+ | "linux" -> S_linux
+
+ | _ -> S_unknown
+
+let windows =
+ match system with
+ | S_mingw64 | S_cygwin | S_win64 -> true
+ | _ -> false
+
+let string_of_string_literal s =
+ let b = Buffer.create (String.length s + 2) in
+ let last_was_escape = ref false in
+ for i = 0 to String.length s - 1 do
+ let c = s.[i] in
+ if c >= '0' && c <= '9' then
+ if !last_was_escape
+ then Printf.bprintf b "\\%o" (Char.code c)
+ else Buffer.add_char b c
+ else if c >= ' ' && c <= '~' && c <> '"' (* '"' *) && c <> '\\' then begin
+ Buffer.add_char b c;
+ last_was_escape := false
+ end else begin
+ Printf.bprintf b "\\%o" (Char.code c);
+ last_was_escape := true
+ end
+ done;
+ Buffer.contents b
+
+let string_of_symbol prefix s =
+ let spec = ref false in
+ for i = 0 to String.length s - 1 do
+ match String.unsafe_get s i with
+ | 'A'..'Z' | 'a'..'z' | '0'..'9' | '_' -> ()
+ | _ -> spec := true;
+ done;
+ if not !spec then if prefix = "" then s else prefix ^ s
+ else
+ let b = Buffer.create (String.length s + 10) in
+ Buffer.add_string b prefix;
+ String.iter
+ (function
+ | ('A'..'Z' | 'a'..'z' | '0'..'9' | '_') as c -> Buffer.add_char b c
+ | c -> Printf.bprintf b "$%02x" (Char.code c)
+ )
+ s;
+ Buffer.contents b
+
+let buf_bytes_directive b directive s =
+ let pos = ref 0 in
+ for i = 0 to String.length s - 1 do
+ if !pos = 0
+ then begin
+ if i > 0 then Buffer.add_char b '\n';
+ Buffer.add_char b '\t';
+ Buffer.add_string b directive;
+ Buffer.add_char b '\t';
+ end
+ else Buffer.add_char b ',';
+ Printf.bprintf b "%d" (Char.code s.[i]);
+ incr pos;
+ if !pos >= 16 then begin pos := 0 end
+ done
+
+let string_of_reg64 = function
+ | RAX -> "rax"
+ | RBX -> "rbx"
+ | RDI -> "rdi"
+ | RSI -> "rsi"
+ | RDX -> "rdx"
+ | RCX -> "rcx"
+ | RBP -> "rbp"
+ | RSP -> "rsp"
+ | R8 -> "r8"
+ | R9 -> "r9"
+ | R10 -> "r10"
+ | R11 -> "r11"
+ | R12 -> "r12"
+ | R13 -> "r13"
+ | R14 -> "r14"
+ | R15 -> "r15"
+
+let string_of_reg8l = function
+ | RAX -> "al"
+ | RBX -> "bl"
+ | RCX -> "cl"
+ | RDX -> "dl"
+ | RSP -> "spl"
+ | RBP -> "bpl"
+ | RSI -> "sil"
+ | RDI -> "dil"
+ | R8 -> "r8b"
+ | R9 -> "r9b"
+ | R10 -> "r10b"
+ | R11 -> "r11b"
+ | R12 -> "r12b"
+ | R13 -> "r13b"
+ | R14 -> "r14b"
+ | R15 -> "r15b"
+
+let string_of_reg8h = function
+ | AH -> "ah"
+ | BH -> "bh"
+ | CH -> "ch"
+ | DH -> "dh"
+
+let string_of_reg16 = function
+ | RAX -> "ax"
+ | RBX -> "bx"
+ | RCX -> "cx"
+ | RDX -> "dx"
+ | RSP -> "sp"
+ | RBP -> "bp"
+ | RSI -> "si"
+ | RDI -> "di"
+ | R8 -> "r8w"
+ | R9 -> "r9w"
+ | R10 -> "r10w"
+ | R11 -> "r11w"
+ | R12 -> "r12w"
+ | R13 -> "r13w"
+ | R14 -> "r14w"
+ | R15 -> "r15w"
+
+let string_of_reg32 = function
+ | RAX -> "eax"
+ | RBX -> "ebx"
+ | RCX -> "ecx"
+ | RDX -> "edx"
+ | RSP -> "esp"
+ | RBP -> "ebp"
+ | RSI -> "esi"
+ | RDI -> "edi"
+ | R8 -> "r8d"
+ | R9 -> "r9d"
+ | R10 -> "r10d"
+ | R11 -> "r11d"
+ | R12 -> "r12d"
+ | R13 -> "r13d"
+ | R14 -> "r14d"
+ | R15 -> "r15d"
+
+let string_of_registerf = function
+ | XMM n -> Printf.sprintf "xmm%d" n
+ | TOS -> Printf.sprintf "tos"
+ | ST n -> Printf.sprintf "st(%d)" n
+
+let string_of_condition = function
+ | E -> "e"
+ | AE -> "ae"
+ | A -> "a"
+ | GE -> "ge"
+ | G -> "g"
+ | NE -> "ne"
+ | B -> "b"
+ | BE -> "be"
+ | L -> "l"
+ | LE -> "le"
+ | NP -> "np"
+ | P -> "p"
+ | NS -> "ns"
+ | S -> "s"
+ | NO -> "no"
+ | O -> "o"
+
+let string_of_rounding = function
+ | RoundDown -> "roundsd.down"
+ | RoundUp -> "roundsd.up"
+ | RoundTruncate -> "roundsd.trunc"
+ | RoundNearest -> "roundsd.near"
+
+
+(* These hooks can be used to insert optimization passes on
+ the assembly code. *)
+let assembler_passes = ref ([] : (asm_program -> asm_program) list)
+
+let internal_assembler = ref None
+let register_internal_assembler f = internal_assembler := Some f
+
+(* Which asm conventions to use *)
+let masm =
+ match system with
+ | S_win32 | S_win64 -> true
+ | _ -> false
+
+(* Shall we use an external assembler command ?
+ If [binary_content] contains some data, we can directly
+ save it. Otherwise, we have to ask an external command.
+*)
+let binary_content = ref None
+
+let compile infile outfile =
+ if masm then
+ Ccomp.command (Config.asm ^
+ Filename.quote outfile ^ " " ^ Filename.quote infile ^
+ (if !Clflags.verbose then "" else ">NUL"))
+ else
+ Ccomp.command (Config.asm ^ " -o " ^
+ Filename.quote outfile ^ " " ^ Filename.quote infile)
+
+let assemble_file infile outfile =
+ match !binary_content with
+ | None -> compile infile outfile
+ | Some content -> content outfile; binary_content := None; 0
+
+let asm_code = ref []
+
+let directive dir = asm_code := dir :: !asm_code
+let emit ins = directive (Ins ins)
+
+let reset_asm_code () = asm_code := []
+
+let generate_code asm =
+ let instrs = List.rev !asm_code in
+ let instrs =
+ List.fold_left (fun instrs pass -> pass instrs) instrs !assembler_passes
+ in
+ begin match asm with
+ | Some f -> f instrs
+ | None -> ()
+ end;
+ begin match !internal_assembler with
+ | Some f -> binary_content := Some (f instrs)
+ | None -> binary_content := None
+ end
diff --git a/asmcomp/x86_proc.mli b/asmcomp/x86_proc.mli
new file mode 100644
index 0000000000..4b6dfacd70
--- /dev/null
+++ b/asmcomp/x86_proc.mli
@@ -0,0 +1,88 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+
+(** Definitions shared between the 32 and 64 bit Intel backends. *)
+
+open X86_ast
+
+(** Helpers for textual emitters *)
+
+val string_of_reg8l: reg64 -> string
+val string_of_reg8h: reg8h -> string
+val string_of_reg16: reg64 -> string
+val string_of_reg32: reg64 -> string
+val string_of_reg64: reg64 -> string
+val string_of_registerf: registerf -> string
+val string_of_string_literal: string -> string
+val string_of_condition: condition -> string
+val string_of_symbol: (*prefix*) string -> string -> string
+val string_of_rounding: rounding -> string
+val buf_bytes_directive:
+ Buffer.t -> (*directive*) string -> (*data*)string -> unit
+
+
+(** Buffer of assembly code *)
+
+val emit: instruction -> unit
+val directive: asm_line -> unit
+val reset_asm_code: unit -> unit
+
+(** Code emission *)
+
+val generate_code: (X86_ast.asm_line list -> unit) option -> unit
+ (** Post-process the stream of instructions. Dump it (using
+ the provided syntax emitter) in a file (if provided) and
+ compile it with an internal assembler (if registered
+ through [register_internal_assembler]). *)
+
+val assemble_file: (*infile*) string -> (*outfile*) string -> (*retcode*) int
+(** Generate an object file corresponding to the last call to
+ [generate_code]. An internal assembler is used if available (and
+ the input file is ignored). Otherwise, the source asm file with an
+ external assembler. *)
+
+(** System detection *)
+
+type system =
+ (* 32 bits and 64 bits *)
+ | S_macosx
+ | S_gnu
+ | S_cygwin
+
+ (* 32 bits only *)
+ | S_solaris
+ | S_win32
+ | S_linux_elf
+ | S_bsd_elf
+ | S_beos
+ | S_mingw
+
+ (* 64 bits only *)
+ | S_win64
+ | S_linux
+ | S_mingw64
+
+ | S_unknown
+
+val system: system
+val masm: bool
+val windows:bool
+
+(** Support for plumbing a binary code emitter *)
+
+val register_internal_assembler: (asm_program -> string -> unit) -> unit
+
+
+(** Hooks for rewriting the assembly code *)
+
+val assembler_passes: (asm_program -> asm_program) list ref
diff --git a/asmrun/.depend b/asmrun/.depend
new file mode 100644
index 0000000000..f08687a9d5
--- /dev/null
+++ b/asmrun/.depend
@@ -0,0 +1,1074 @@
+alloc.o: alloc.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/stacks.h ../byterun/caml/memory.h
+array.o: array.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+backtrace.o: backtrace.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/backtrace.h ../byterun/caml/exec.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h stack.h
+callback.o: callback.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/fail.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
+compact.o: compact.c ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/freelist.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/memory.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/roots.h \
+ ../byterun/caml/weak.h
+compare.o: compare.c ../byterun/caml/custom.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/misc.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+custom.o: custom.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
+debugger.o: debugger.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/debugger.h \
+ ../byterun/caml/misc.h
+dynlink.o: dynlink.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/alloc.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/dynlink.h \
+ ../byterun/caml/fail.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/prims.h \
+ ../byterun/caml/signals.h
+extern.o: extern.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/gc.h \
+ ../byterun/caml/intext.h ../byterun/caml/io.h ../byterun/caml/io.h \
+ ../byterun/caml/md5.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/reverse.h
+fail.o: fail.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/io.h ../byterun/caml/gc.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/printexc.h ../byterun/caml/signals.h stack.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/callback.h
+finalise.o: finalise.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/fail.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/signals.h
+floats.o: floats.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/reverse.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h
+freelist.o: freelist.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/freelist.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/mlvalues.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h
+gc_ctrl.o: gc_ctrl.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/compact.h ../byterun/caml/custom.h \
+ ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/freelist.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h stack.h
+globroots.o: globroots.c ../byterun/caml/memory.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/globroots.h ../byterun/caml/roots.h
+hash.o: hash.c ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/custom.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/hash.h
+intern.o: intern.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/callback.h ../byterun/caml/custom.h \
+ ../byterun/caml/fail.h ../byterun/caml/gc.h ../byterun/caml/intext.h \
+ ../byterun/caml/io.h ../byterun/caml/io.h ../byterun/caml/md5.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/reverse.h
+ints.o: ints.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/intext.h \
+ ../byterun/caml/io.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+io.o: io.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/alloc.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/custom.h \
+ ../byterun/caml/fail.h ../byterun/caml/io.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/signals.h \
+ ../byterun/caml/sys.h
+lexing.o: lexing.c ../byterun/caml/fail.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h
+main.o: main.c ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h ../byterun/caml/sys.h
+major_gc.o: major_gc.c ../byterun/caml/compact.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/custom.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/fail.h ../byterun/caml/finalise.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/weak.h
+md5.o: md5.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/md5.h ../byterun/caml/io.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/io.h ../byterun/caml/reverse.h
+memory.o: memory.c ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/signals.h
+meta.o: meta.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/fail.h \
+ ../byterun/caml/fix_code.h ../byterun/caml/interp.h \
+ ../byterun/caml/intext.h ../byterun/caml/io.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/prims.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h
+minor_gc.o: minor_gc.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/fail.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/finalise.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/memory.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/roots.h \
+ ../byterun/caml/signals.h ../byterun/caml/weak.h
+misc.o: misc.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h
+natdynlink.o: natdynlink.c ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h stack.h ../byterun/caml/callback.h \
+ ../byterun/caml/alloc.h ../byterun/caml/intext.h ../byterun/caml/io.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/fail.h \
+ ../byterun/caml/signals.h
+obj.o: obj.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/gc.h ../byterun/caml/interp.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/prims.h
+parsing.o: parsing.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/misc.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/alloc.h
+printexc.o: printexc.c ../byterun/caml/backtrace.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/exec.h ../byterun/caml/callback.h \
+ ../byterun/caml/debugger.h ../byterun/caml/fail.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/printexc.h
+roots.o: roots.c ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/globroots.h ../byterun/caml/memory.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h stack.h \
+ ../byterun/caml/roots.h
+signals_asm.o: signals_asm.c ../byterun/caml/fail.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/signals.h \
+ ../byterun/caml/signals_machdep.h signals_osdep.h stack.h
+signals.o: signals.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/callback.h ../byterun/caml/config.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/signals.h ../byterun/caml/signals_machdep.h \
+ ../byterun/caml/sys.h
+startup_aux.o: startup_aux.c ../byterun/caml/backtrace.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/exec.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/startup_aux.h
+startup.o: startup.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/backtrace.h \
+ ../byterun/caml/exec.h ../byterun/caml/custom.h \
+ ../byterun/caml/debugger.h ../byterun/caml/fail.h \
+ ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/intext.h ../byterun/caml/io.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/osdeps.h \
+ ../byterun/caml/printexc.h stack.h ../byterun/caml/startup_aux.h \
+ ../byterun/caml/sys.h
+str.o: str.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/mlvalues.h ../byterun/caml/misc.h
+sys.o: sys.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/alloc.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/debugger.h \
+ ../byterun/caml/fail.h ../byterun/caml/instruct.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/osdeps.h \
+ ../byterun/caml/signals.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/sys.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/io.h
+terminfo.o: terminfo.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/alloc.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/fail.h ../byterun/caml/io.h \
+ ../byterun/caml/mlvalues.h
+unix.o: unix.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/memory.h \
+ ../byterun/caml/config.h ../byterun/caml/gc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/osdeps.h
+weak.o: weak.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
+alloc.d.o: alloc.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/stacks.h ../byterun/caml/memory.h
+array.d.o: array.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+backtrace.d.o: backtrace.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/backtrace.h ../byterun/caml/exec.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h stack.h
+callback.d.o: callback.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/fail.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
+compact.d.o: compact.c ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/freelist.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/memory.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/roots.h \
+ ../byterun/caml/weak.h
+compare.d.o: compare.c ../byterun/caml/custom.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/misc.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+custom.d.o: custom.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
+debugger.d.o: debugger.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/debugger.h \
+ ../byterun/caml/misc.h
+dynlink.d.o: dynlink.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/alloc.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/dynlink.h \
+ ../byterun/caml/fail.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/prims.h \
+ ../byterun/caml/signals.h
+extern.d.o: extern.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/gc.h \
+ ../byterun/caml/intext.h ../byterun/caml/io.h ../byterun/caml/io.h \
+ ../byterun/caml/md5.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/reverse.h
+fail.d.o: fail.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/io.h ../byterun/caml/gc.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/printexc.h ../byterun/caml/signals.h stack.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/callback.h
+finalise.d.o: finalise.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/fail.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/signals.h
+floats.d.o: floats.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/reverse.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h
+freelist.d.o: freelist.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/freelist.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/mlvalues.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h
+gc_ctrl.d.o: gc_ctrl.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/compact.h ../byterun/caml/custom.h \
+ ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/freelist.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h stack.h
+globroots.d.o: globroots.c ../byterun/caml/memory.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/globroots.h ../byterun/caml/roots.h
+hash.d.o: hash.c ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/custom.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/hash.h
+intern.d.o: intern.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/callback.h ../byterun/caml/custom.h \
+ ../byterun/caml/fail.h ../byterun/caml/gc.h ../byterun/caml/intext.h \
+ ../byterun/caml/io.h ../byterun/caml/io.h ../byterun/caml/md5.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/reverse.h
+ints.d.o: ints.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/intext.h \
+ ../byterun/caml/io.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+io.d.o: io.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/alloc.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/custom.h \
+ ../byterun/caml/fail.h ../byterun/caml/io.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/signals.h \
+ ../byterun/caml/sys.h
+lexing.d.o: lexing.c ../byterun/caml/fail.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h
+main.d.o: main.c ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h ../byterun/caml/sys.h
+major_gc.d.o: major_gc.c ../byterun/caml/compact.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/custom.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/fail.h ../byterun/caml/finalise.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/weak.h
+md5.d.o: md5.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/md5.h ../byterun/caml/io.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/io.h ../byterun/caml/reverse.h
+memory.d.o: memory.c ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/signals.h
+meta.d.o: meta.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/fail.h \
+ ../byterun/caml/fix_code.h ../byterun/caml/interp.h \
+ ../byterun/caml/intext.h ../byterun/caml/io.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/prims.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h
+minor_gc.d.o: minor_gc.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/fail.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/finalise.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/memory.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/roots.h \
+ ../byterun/caml/signals.h ../byterun/caml/weak.h
+misc.d.o: misc.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h
+natdynlink.d.o: natdynlink.c ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h stack.h ../byterun/caml/callback.h \
+ ../byterun/caml/alloc.h ../byterun/caml/intext.h ../byterun/caml/io.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/fail.h \
+ ../byterun/caml/signals.h
+obj.d.o: obj.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/gc.h ../byterun/caml/interp.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/prims.h
+parsing.d.o: parsing.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/misc.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/alloc.h
+printexc.d.o: printexc.c ../byterun/caml/backtrace.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/exec.h ../byterun/caml/callback.h \
+ ../byterun/caml/debugger.h ../byterun/caml/fail.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/printexc.h
+roots.d.o: roots.c ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/globroots.h ../byterun/caml/memory.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h stack.h \
+ ../byterun/caml/roots.h
+signals_asm.d.o: signals_asm.c ../byterun/caml/fail.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/signals.h \
+ ../byterun/caml/signals_machdep.h signals_osdep.h stack.h
+signals.d.o: signals.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/callback.h ../byterun/caml/config.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/signals.h ../byterun/caml/signals_machdep.h \
+ ../byterun/caml/sys.h
+startup_aux.d.o: startup_aux.c ../byterun/caml/backtrace.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/exec.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/startup_aux.h
+startup.d.o: startup.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/backtrace.h \
+ ../byterun/caml/exec.h ../byterun/caml/custom.h \
+ ../byterun/caml/debugger.h ../byterun/caml/fail.h \
+ ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/intext.h ../byterun/caml/io.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/osdeps.h \
+ ../byterun/caml/printexc.h stack.h ../byterun/caml/startup_aux.h \
+ ../byterun/caml/sys.h
+str.d.o: str.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/mlvalues.h ../byterun/caml/misc.h
+sys.d.o: sys.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/alloc.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/debugger.h \
+ ../byterun/caml/fail.h ../byterun/caml/instruct.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/osdeps.h \
+ ../byterun/caml/signals.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/sys.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/io.h
+terminfo.d.o: terminfo.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/alloc.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/fail.h ../byterun/caml/io.h \
+ ../byterun/caml/mlvalues.h
+unix.d.o: unix.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/memory.h \
+ ../byterun/caml/config.h ../byterun/caml/gc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/osdeps.h
+weak.d.o: weak.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
+alloc.p.o: alloc.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/stacks.h ../byterun/caml/memory.h
+array.p.o: array.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+backtrace.p.o: backtrace.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/backtrace.h ../byterun/caml/exec.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h stack.h
+callback.p.o: callback.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/fail.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
+compact.p.o: compact.c ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/freelist.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/memory.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/roots.h \
+ ../byterun/caml/weak.h
+compare.p.o: compare.c ../byterun/caml/custom.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/misc.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+custom.p.o: custom.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
+debugger.p.o: debugger.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/debugger.h \
+ ../byterun/caml/misc.h
+dynlink.p.o: dynlink.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/alloc.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/dynlink.h \
+ ../byterun/caml/fail.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/prims.h \
+ ../byterun/caml/signals.h
+extern.p.o: extern.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/gc.h \
+ ../byterun/caml/intext.h ../byterun/caml/io.h ../byterun/caml/io.h \
+ ../byterun/caml/md5.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/reverse.h
+fail.p.o: fail.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/io.h ../byterun/caml/gc.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/printexc.h ../byterun/caml/signals.h stack.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/callback.h
+finalise.p.o: finalise.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/fail.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/signals.h
+floats.p.o: floats.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/reverse.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h
+freelist.p.o: freelist.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/freelist.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/mlvalues.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h
+gc_ctrl.p.o: gc_ctrl.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/compact.h ../byterun/caml/custom.h \
+ ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/freelist.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h stack.h
+globroots.p.o: globroots.c ../byterun/caml/memory.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/globroots.h ../byterun/caml/roots.h
+hash.p.o: hash.c ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/custom.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/hash.h
+intern.p.o: intern.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/callback.h ../byterun/caml/custom.h \
+ ../byterun/caml/fail.h ../byterun/caml/gc.h ../byterun/caml/intext.h \
+ ../byterun/caml/io.h ../byterun/caml/io.h ../byterun/caml/md5.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/reverse.h
+ints.p.o: ints.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/custom.h ../byterun/caml/fail.h ../byterun/caml/intext.h \
+ ../byterun/caml/io.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h
+io.p.o: io.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/alloc.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/custom.h \
+ ../byterun/caml/fail.h ../byterun/caml/io.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/signals.h \
+ ../byterun/caml/sys.h
+lexing.p.o: lexing.c ../byterun/caml/fail.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h
+main.p.o: main.c ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h ../byterun/caml/sys.h
+major_gc.p.o: major_gc.c ../byterun/caml/compact.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/custom.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/fail.h ../byterun/caml/finalise.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/weak.h
+md5.p.o: md5.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/md5.h ../byterun/caml/io.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/io.h ../byterun/caml/reverse.h
+memory.p.o: memory.c ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/signals.h
+meta.p.o: meta.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/config.h ../byterun/caml/fail.h \
+ ../byterun/caml/fix_code.h ../byterun/caml/interp.h \
+ ../byterun/caml/intext.h ../byterun/caml/io.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/prims.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h
+minor_gc.p.o: minor_gc.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/fail.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/finalise.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/gc.h ../byterun/caml/gc_ctrl.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/memory.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/roots.h \
+ ../byterun/caml/signals.h ../byterun/caml/weak.h
+misc.p.o: misc.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/misc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h
+natdynlink.p.o: natdynlink.c ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h stack.h ../byterun/caml/callback.h \
+ ../byterun/caml/alloc.h ../byterun/caml/intext.h ../byterun/caml/io.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/fail.h \
+ ../byterun/caml/signals.h
+obj.p.o: obj.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/gc.h ../byterun/caml/interp.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/prims.h
+parsing.p.o: parsing.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/misc.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/alloc.h
+printexc.p.o: printexc.c ../byterun/caml/backtrace.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/exec.h ../byterun/caml/callback.h \
+ ../byterun/caml/debugger.h ../byterun/caml/fail.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/printexc.h
+roots.p.o: roots.c ../byterun/caml/finalise.h ../byterun/caml/roots.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/globroots.h ../byterun/caml/memory.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h stack.h \
+ ../byterun/caml/roots.h
+signals_asm.p.o: signals_asm.c ../byterun/caml/fail.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/osdeps.h ../byterun/caml/signals.h \
+ ../byterun/caml/signals_machdep.h signals_osdep.h stack.h
+signals.p.o: signals.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/callback.h ../byterun/caml/config.h \
+ ../byterun/caml/fail.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/freelist.h \
+ ../byterun/caml/minor_gc.h ../byterun/caml/address_class.h \
+ ../byterun/caml/misc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/roots.h ../byterun/caml/memory.h \
+ ../byterun/caml/signals.h ../byterun/caml/signals_machdep.h \
+ ../byterun/caml/sys.h
+startup_aux.p.o: startup_aux.c ../byterun/caml/backtrace.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/exec.h ../byterun/caml/memory.h \
+ ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/startup_aux.h
+startup.p.o: startup.c ../byterun/caml/callback.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/misc.h ../byterun/caml/backtrace.h \
+ ../byterun/caml/exec.h ../byterun/caml/custom.h \
+ ../byterun/caml/debugger.h ../byterun/caml/fail.h \
+ ../byterun/caml/freelist.h ../byterun/caml/gc.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/intext.h ../byterun/caml/io.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/osdeps.h \
+ ../byterun/caml/printexc.h stack.h ../byterun/caml/startup_aux.h \
+ ../byterun/caml/sys.h
+str.p.o: str.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/mlvalues.h ../byterun/caml/misc.h
+sys.p.o: sys.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/alloc.h \
+ ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/debugger.h \
+ ../byterun/caml/fail.h ../byterun/caml/instruct.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/osdeps.h \
+ ../byterun/caml/signals.h ../byterun/caml/stacks.h \
+ ../byterun/caml/memory.h ../byterun/caml/gc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/sys.h \
+ ../byterun/caml/gc_ctrl.h ../byterun/caml/io.h
+terminfo.p.o: terminfo.c ../byterun/caml/config.h \
+ ../byterun/caml/../../config/m.h ../byterun/caml/../../config/s.h \
+ ../byterun/caml/alloc.h ../byterun/caml/misc.h ../byterun/caml/config.h \
+ ../byterun/caml/mlvalues.h ../byterun/caml/fail.h ../byterun/caml/io.h \
+ ../byterun/caml/mlvalues.h
+unix.p.o: unix.c ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/memory.h \
+ ../byterun/caml/config.h ../byterun/caml/gc.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/misc.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/misc.h \
+ ../byterun/caml/osdeps.h
+weak.p.o: weak.c ../byterun/caml/alloc.h ../byterun/caml/misc.h \
+ ../byterun/caml/config.h ../byterun/caml/../../config/m.h \
+ ../byterun/caml/../../config/s.h ../byterun/caml/mlvalues.h \
+ ../byterun/caml/fail.h ../byterun/caml/major_gc.h \
+ ../byterun/caml/freelist.h ../byterun/caml/memory.h ../byterun/caml/gc.h \
+ ../byterun/caml/major_gc.h ../byterun/caml/minor_gc.h \
+ ../byterun/caml/address_class.h ../byterun/caml/mlvalues.h
diff --git a/asmrun/.ignore b/asmrun/.ignore
new file mode 100644
index 0000000000..60bc139ed9
--- /dev/null
+++ b/asmrun/.ignore
@@ -0,0 +1,41 @@
+*.p.c
+*.d.c
+libasmrun.a
+libasmrunp.a
+.depend.nt
+alloc.c
+array.c
+callback.c
+compact.c
+compare.c
+custom.c
+debugger.c
+dynlink.c
+extern.c
+finalise.c
+floats.c
+freelist.c
+gc_ctrl.c
+globroots.c
+hash.c
+intern.c
+ints.c
+io.c
+lexing.c
+main.c
+major_gc.c
+md5.c
+memory.c
+meta.c
+minor_gc.c
+misc.c
+obj.c
+parsing.c
+printexc.c
+signals.c
+startup_aux.c
+str.c
+sys.c
+terminfo.c
+unix.c
+weak.c
diff --git a/asmrun/Makefile b/asmrun/Makefile
new file mode 100644
index 0000000000..64a1331830
--- /dev/null
+++ b/asmrun/Makefile
@@ -0,0 +1,239 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include ../config/Makefile
+
+CC=$(NATIVECC)
+FLAGS=-I../byterun -DCAML_NAME_SPACE -DNATIVE_CODE \
+ -DTARGET_$(ARCH) -DMODEL_$(MODEL) -DSYS_$(SYSTEM) $(IFLEXDIR)
+CFLAGS=$(FLAGS) $(NATIVECCCOMPOPTS)
+DFLAGS=$(FLAGS) -g -DDEBUG $(NATIVECCCOMPOPTS)
+PFLAGS=$(FLAGS) -pg -DPROFILING $(NATIVECCPROFOPTS) $(NATIVECCCOMPOPTS)
+PICFLAGS=$(FLAGS) $(SHAREDCCCOMPOPTS) $(NATIVECCCOMPOPTS)
+
+COBJS=startup_aux.o startup.o \
+ main.o fail.o roots.o globroots.o signals.o signals_asm.o \
+ misc.o freelist.o major_gc.o minor_gc.o memory.o alloc.o compare.o ints.o \
+ floats.o str.o array.o io.o extern.o intern.o hash.o sys.o parsing.o \
+ gc_ctrl.o terminfo.o md5.o obj.o lexing.o printexc.o callback.o weak.o \
+ compact.o finalise.o custom.o $(UNIX_OR_WIN32).o backtrace_prim.o \
+ backtrace.o \
+ natdynlink.o debugger.o meta.o dynlink.o
+
+ASMOBJS=$(ARCH).o
+
+OBJS=$(COBJS) $(ASMOBJS)
+DOBJS=$(COBJS:.o=.d.o) $(ASMOBJS)
+POBJS=$(COBJS:.o=.p.o) $(ASMOBJS:.o=.p.o)
+PICOBJS=$(COBJS:.o=.pic.o) $(ASMOBJS:.o=.pic.o)
+
+all: libasmrun.a all-$(RUNTIMED) all-$(PROFILING) all-$(SHARED)
+
+libasmrun.a: $(OBJS)
+ rm -f libasmrun.a
+ $(ARCMD) rc libasmrun.a $(OBJS)
+ $(RANLIB) libasmrun.a
+
+all-noruntimed:
+.PHONY: all-noruntimed
+
+all-runtimed: libasmrund.a
+.PHONY: all-runtimed
+
+libasmrund.a: $(DOBJS)
+ rm -f libasmrund.a
+ $(ARCMD) rc libasmrund.a $(DOBJS)
+ $(RANLIB) libasmrund.a
+
+all-noprof:
+
+all-prof: libasmrunp.a
+
+libasmrunp.a: $(POBJS)
+ rm -f libasmrunp.a
+ $(ARCMD) rc libasmrunp.a $(POBJS)
+ $(RANLIB) libasmrunp.a
+
+all-noshared:
+
+all-shared: libasmrun_pic.a libasmrun_shared.so
+
+libasmrun_pic.a: $(PICOBJS)
+ rm -f libasmrun_pic.a
+ ar rc libasmrun_pic.a $(PICOBJS)
+ $(RANLIB) libasmrun_pic.a
+
+libasmrun_shared.so: $(PICOBJS)
+ $(MKDLL) -o libasmrun_shared.so $(PICOBJS) $(NATIVECCLIBS)
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+
+install: install-default install-$(RUNTIMED) install-$(PROFILING) \
+ install-$(SHARED)
+
+install-default:
+ cp libasmrun.a $(INSTALL_LIBDIR)/libasmrun.a
+ cd $(INSTALL_LIBDIR); $(RANLIB) libasmrun.a
+.PHONY: install-default
+
+install-noruntimed:
+.PHONY: install-noruntimed
+
+install-runtimed:
+ cp libasmrund.a $(INSTALL_LIBDIR)/libasmrund.a
+ cd $(INSTALL_LIBDIR); $(RANLIB) libasmrund.a
+.PHONY: install-runtimed
+
+install-noprof:
+ rm -f $(INSTALL_LIBDIR)/libasmrunp.a
+ ln -s libasmrun.a $(INSTALL_LIBDIR)/libasmrunp.a
+.PHONY: install-noprof
+
+install-prof:
+ cp libasmrunp.a $(INSTALL_LIBDIR)/libasmrunp.a
+ cd $(INSTALL_LIBDIR); $(RANLIB) libasmrunp.a
+.PHONY: install-prof
+
+install-noshared:
+.PHONY: install-noshared
+
+install-shared:
+ cp libasmrun_pic.a $(INSTALL_LIBDIR)/libasmrun_pic.a
+ cd $(INSTALL_LIBDIR); $(RANLIB) libasmrunp.a
+ cp libasmrun_shared.so $(INSTALL_LIBDIR)/libasmrun_shared.so
+.PHONY: install-prof
+
+main.c: ../byterun/main.c
+ ln -s ../byterun/main.c main.c
+startup_aux.c: ../byterun/startup_aux.c
+ ln -s ../byterun/startup_aux.c startup_aux.c
+backtrace.c: ../byterun/backtrace.c
+ ln -s ../byterun/backtrace.c backtrace.c
+misc.c: ../byterun/misc.c
+ ln -s ../byterun/misc.c misc.c
+freelist.c: ../byterun/freelist.c
+ ln -s ../byterun/freelist.c freelist.c
+major_gc.c: ../byterun/major_gc.c
+ ln -s ../byterun/major_gc.c major_gc.c
+minor_gc.c: ../byterun/minor_gc.c
+ ln -s ../byterun/minor_gc.c minor_gc.c
+memory.c: ../byterun/memory.c
+ ln -s ../byterun/memory.c memory.c
+alloc.c: ../byterun/alloc.c
+ ln -s ../byterun/alloc.c alloc.c
+array.c: ../byterun/array.c
+ ln -s ../byterun/array.c array.c
+compare.c: ../byterun/compare.c
+ ln -s ../byterun/compare.c compare.c
+ints.c: ../byterun/ints.c
+ ln -s ../byterun/ints.c ints.c
+floats.c: ../byterun/floats.c
+ ln -s ../byterun/floats.c floats.c
+str.c: ../byterun/str.c
+ ln -s ../byterun/str.c str.c
+io.c: ../byterun/io.c
+ ln -s ../byterun/io.c io.c
+extern.c: ../byterun/extern.c
+ ln -s ../byterun/extern.c extern.c
+intern.c: ../byterun/intern.c
+ ln -s ../byterun/intern.c intern.c
+hash.c: ../byterun/hash.c
+ ln -s ../byterun/hash.c hash.c
+sys.c: ../byterun/sys.c
+ ln -s ../byterun/sys.c sys.c
+parsing.c: ../byterun/parsing.c
+ ln -s ../byterun/parsing.c parsing.c
+gc_ctrl.c: ../byterun/gc_ctrl.c
+ ln -s ../byterun/gc_ctrl.c gc_ctrl.c
+terminfo.c: ../byterun/terminfo.c
+ ln -s ../byterun/terminfo.c terminfo.c
+md5.c: ../byterun/md5.c
+ ln -s ../byterun/md5.c md5.c
+obj.c: ../byterun/obj.c
+ ln -s ../byterun/obj.c obj.c
+lexing.c: ../byterun/lexing.c
+ ln -s ../byterun/lexing.c lexing.c
+printexc.c: ../byterun/printexc.c
+ ln -s ../byterun/printexc.c printexc.c
+callback.c: ../byterun/callback.c
+ ln -s ../byterun/callback.c callback.c
+weak.c: ../byterun/weak.c
+ ln -s ../byterun/weak.c weak.c
+compact.c: ../byterun/compact.c
+ ln -s ../byterun/compact.c compact.c
+finalise.c: ../byterun/finalise.c
+ ln -s ../byterun/finalise.c finalise.c
+custom.c: ../byterun/custom.c
+ ln -s ../byterun/custom.c custom.c
+meta.c: ../byterun/meta.c
+ ln -s ../byterun/meta.c meta.c
+globroots.c: ../byterun/globroots.c
+ ln -s ../byterun/globroots.c globroots.c
+$(UNIX_OR_WIN32).c: ../byterun/$(UNIX_OR_WIN32).c
+ ln -s ../byterun/$(UNIX_OR_WIN32).c $(UNIX_OR_WIN32).c
+dynlink.c: ../byterun/dynlink.c
+ ln -s ../byterun/dynlink.c dynlink.c
+signals.c: ../byterun/signals.c
+ ln -s ../byterun/signals.c signals.c
+debugger.c: ../byterun/debugger.c
+ ln -s ../byterun/debugger.c debugger.c
+
+LINKEDFILES=misc.c freelist.c major_gc.c minor_gc.c memory.c alloc.c array.c \
+ compare.c ints.c floats.c str.c io.c extern.c intern.c hash.c sys.c \
+ parsing.c gc_ctrl.c terminfo.c md5.c obj.c lexing.c printexc.c callback.c \
+ weak.c compact.c finalise.c meta.c custom.c main.c globroots.c \
+ $(UNIX_OR_WIN32).c dynlink.c signals.c debugger.c
+
+clean::
+ rm -f $(LINKEDFILES)
+
+%.o: %.S
+ $(ASPP) -DSYS_$(SYSTEM) -DMODEL_$(MODEL) -o $@ $< || \
+ { echo "If your assembler produced syntax errors, it is probably";\
+ echo "unhappy with the preprocessor. Check your assembler, or";\
+ echo "try producing $*.o by hand.";\
+ exit 2; }
+
+%.p.o: %.S
+ $(ASPP) -DSYS_$(SYSTEM) -DMODEL_$(MODEL) $(ASPPPROFFLAGS) -o $@ $<
+
+%.pic.o: %.S
+ $(ASPP) -DSYS_$(SYSTEM) -DMODEL_$(MODEL) $(SHAREDCCCOMPOPTS) -o $@ $<
+
+%.d.o: %.c
+ $(CC) -c $(DFLAGS) -o $@ $<
+
+%.p.o: %.c
+ $(CC) -c $(PFLAGS) -o $@ $<
+
+%.pic.o: %.c
+ $(CC) -c $(PICFLAGS) -o $@ $<
+
+%.o: %.s
+ $(ASPP) -DSYS_$(SYSTEM) -o $@ $<
+
+%.p.o: %.s
+ $(ASPP) -DSYS_$(SYSTEM) $(ASPPPROFFLAGS) -o $@ $<
+
+%.pic.o: %.s
+ $(ASPP) -DSYS_$(SYSTEM) $(SHAREDCCCOMPOPTS) -o $@ $<
+
+clean::
+ rm -f *.o *.a *~
+
+depend: $(COBJS:.o=.c) ${LINKEDFILES}
+ $(CC) -MM $(FLAGS) *.c > .depend
+ $(CC) -MM $(FLAGS) -DDEBUG *.c | sed -e 's/\.o/.d.o/' >> .depend
+ $(CC) -MM $(FLAGS) *.c | sed -e 's/\.o/.p.o/' >> .depend
+
+include .depend
diff --git a/asmrun/Makefile.nt b/asmrun/Makefile.nt
new file mode 100644
index 0000000000..4a1056f6c9
--- /dev/null
+++ b/asmrun/Makefile.nt
@@ -0,0 +1,85 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include ../config/Makefile
+
+CC=$(NATIVECC)
+CFLAGS=-I../byterun -DNATIVE_CODE -DTARGET_$(ARCH) -DSYS_$(SYSTEM) \
+ $(NATIVECCCOMPOPTS)
+
+COBJS=startup_aux.$(O) startup.$(O) \
+ main.$(O) fail.$(O) roots.$(O) signals.$(O) signals_asm.$(O)\
+ misc.$(O) freelist.$(O) major_gc.$(O) minor_gc.$(O) memory.$(O) alloc.$(O) \
+ compare.$(O) ints.$(O) floats.$(O) str.$(O) array.$(O) io.$(O) extern.$(O) \
+ intern.$(O) hash.$(O) sys.$(O) parsing.$(O) gc_ctrl.$(O) terminfo.$(O) \
+ md5.$(O) obj.$(O) lexing.$(O) win32.$(O) printexc.$(O) callback.$(O) \
+ weak.$(O) compact.$(O) finalise.$(O) custom.$(O) globroots.$(O) \
+ backtrace_prim.$(O) backtrace.$(O) \
+ natdynlink.$(O) debugger.$(O) meta.$(O) dynlink.$(O)
+
+LINKEDFILES=misc.c freelist.c major_gc.c minor_gc.c memory.c alloc.c array.c \
+ compare.c ints.c floats.c str.c io.c extern.c intern.c hash.c sys.c \
+ parsing.c gc_ctrl.c terminfo.c md5.c obj.c lexing.c printexc.c callback.c \
+ weak.c compact.c meta.c finalise.c custom.c main.c globroots.c \
+ dynlink.c signals.c debugger.c startup_aux.c backtrace.c
+
+ifeq ($(TOOLCHAIN),mingw)
+ASMOBJS=$(ARCH).o
+else
+ASMOBJS=$(ARCH)nt.obj
+endif
+
+OBJS=$(COBJS) $(ASMOBJS)
+
+all: libasmrun.$(A)
+
+libasmrun.$(A): $(OBJS)
+ $(call MKLIB,libasmrun.$(A), $(OBJS))
+
+i386nt.obj: i386nt.asm
+ $(ASM)i386nt.obj i386nt.asm
+
+amd64nt.obj: amd64nt.asm
+ $(ASM)amd64nt.obj amd64nt.asm
+
+i386.o: i386.S
+ $(ASPP) -DSYS_$(SYSTEM) i386.S
+
+amd64.o: amd64.S
+ $(ASPP) -DSYS_$(SYSTEM) amd64.S
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+
+install:
+ cp libasmrun.$(A) $(INSTALL_LIBDIR)
+
+$(LINKEDFILES): %.c: ../byterun/%.c
+ cp ../byterun/$*.c $*.c
+
+# Need special compilation rule so as not to do -I../byterun
+win32.$(O): ../byterun/win32.c
+ $(CC) -c $(NATIVECCCOMPOPTS) -DNATIVE_CODE $(IFLEXDIR) ../byterun/win32.c
+
+%.$(O): %.c
+ $(CC) $(CFLAGS) -c $<
+
+clean::
+ rm -f $(LINKEDFILES)
+
+clean::
+ rm -f *.$(O) *.$(A) *~
+
+.depend.nt: .depend
+ sed -e 's/\.o/.$(O)/g' .depend > .depend.nt
+
+include .depend.nt
diff --git a/asmrun/amd64.S b/asmrun/amd64.S
new file mode 100644
index 0000000000..be38848ec2
--- /dev/null
+++ b/asmrun/amd64.S
@@ -0,0 +1,694 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Asm part of the runtime system, AMD64 processor */
+/* Must be preprocessed by cpp */
+
+/* PIC mode support based on contribution by Paul Stravers (see PR#4795) */
+
+#include "../config/m.h"
+
+#if defined(SYS_macosx)
+
+#define LBL(x) L##x
+#define G(r) _##r
+#define GREL(r) _##r@GOTPCREL
+#define GCALL(r) _##r
+#define FUNCTION_ALIGN 2
+#define EIGHT_ALIGN 3
+#define SIXTEEN_ALIGN 4
+#define FUNCTION(name) \
+ .globl name; \
+ .align FUNCTION_ALIGN; \
+ name:
+
+#elif defined(SYS_mingw64) || defined(SYS_cygwin)
+
+#define LBL(x) .L##x
+#define G(r) r
+#undef GREL
+#define GCALL(r) r
+#define FUNCTION_ALIGN 4
+#define EIGHT_ALIGN 8
+#define SIXTEEN_ALIGN 16
+#define FUNCTION(name) \
+ .globl name; \
+ .align FUNCTION_ALIGN; \
+ name:
+
+#else
+
+#define LBL(x) .L##x
+#define G(r) r
+#define GREL(r) r@GOTPCREL
+#define GCALL(r) r@PLT
+#define FUNCTION_ALIGN 4
+#define EIGHT_ALIGN 8
+#define SIXTEEN_ALIGN 16
+#define FUNCTION(name) \
+ .globl name; \
+ .type name,@function; \
+ .align FUNCTION_ALIGN; \
+ name:
+
+#endif
+
+#ifdef ASM_CFI_SUPPORTED
+#define CFI_STARTPROC .cfi_startproc
+#define CFI_ENDPROC .cfi_endproc
+#define CFI_ADJUST(n) .cfi_adjust_cfa_offset n
+#else
+#define CFI_STARTPROC
+#define CFI_ENDPROC
+#define CFI_ADJUST(n)
+#endif
+
+#ifdef WITH_FRAME_POINTERS
+
+#define ENTER_FUNCTION \
+ pushq %rbp; CFI_ADJUST(8); \
+ movq %rsp, %rbp
+#define LEAVE_FUNCTION \
+ popq %rbp; CFI_ADJUST(-8);
+
+#else
+
+#define ENTER_FUNCTION \
+ subq $8, %rsp; CFI_ADJUST (8);
+#define LEAVE_FUNCTION \
+ addq $8, %rsp; CFI_ADJUST (-8);
+
+#endif
+
+#if defined(__PIC__) && !defined(SYS_mingw64) && !defined(SYS_cygwin)
+
+/* Position-independent operations on global variables. */
+
+/* Store [srcreg] in global [dstlabel]. Clobbers %r11. */
+#define STORE_VAR(srcreg,dstlabel) \
+ movq GREL(dstlabel)(%rip), %r11 ; \
+ movq srcreg, (%r11)
+
+#define STORE_VAR32(srcreg,dstlabel) \
+ movq GREL(dstlabel)(%rip), %r11 ; \
+ movl srcreg, (%r11)
+
+/* Load global [srclabel] in register [dstreg]. Clobbers %r11. */
+#define LOAD_VAR(srclabel,dstreg) \
+ movq GREL(srclabel)(%rip), %r11 ; \
+ movq (%r11), dstreg
+
+/* Compare global [label] with register [reg]. Clobbers %rax. */
+#define CMP_VAR(label,reg) \
+ movq GREL(label)(%rip), %rax ; \
+ cmpq (%rax), reg
+
+/* Test 32-bit global [label] against mask [imm]. Clobbers %r11. */
+#define TESTL_VAR(imm,label) \
+ movq GREL(label)(%rip), %r11 ; \
+ testl imm, (%r11)
+
+/* Push global [label] on stack. Clobbers %r11. */
+#define PUSH_VAR(srclabel) \
+ movq GREL(srclabel)(%rip), %r11 ; \
+ pushq (%r11); CFI_ADJUST (8)
+
+/* Pop global [label] off stack. Clobbers %r11. */
+#define POP_VAR(dstlabel) \
+ movq GREL(dstlabel)(%rip), %r11 ; \
+ popq (%r11); CFI_ADJUST (-8)
+
+/* Record lowest stack address and return address. Clobbers %rax. */
+#define RECORD_STACK_FRAME(OFFSET) \
+ pushq %r11 ; CFI_ADJUST(8); \
+ movq 8+OFFSET(%rsp), %rax ; \
+ STORE_VAR(%rax,caml_last_return_address) ; \
+ leaq 16+OFFSET(%rsp), %rax ; \
+ STORE_VAR(%rax,caml_bottom_of_stack) ; \
+ popq %r11; CFI_ADJUST(-8)
+
+/* Load address of global [label] in register [dst]. */
+#define LEA_VAR(label,dst) \
+ movq GREL(label)(%rip), dst
+
+#else
+
+/* Non-PIC operations on global variables. Slightly faster. */
+
+#define STORE_VAR(srcreg,dstlabel) \
+ movq srcreg, G(dstlabel)(%rip)
+
+#define STORE_VAR32(srcreg,dstlabel) \
+ movl srcreg, G(dstlabel)(%rip)
+
+#define LOAD_VAR(srclabel,dstreg) \
+ movq G(srclabel)(%rip), dstreg
+
+#define CMP_VAR(label,reg) \
+ cmpq G(label)(%rip), %r15
+
+#define TESTL_VAR(imm,label) \
+ testl imm, G(label)(%rip)
+
+#define PUSH_VAR(srclabel) \
+ pushq G(srclabel)(%rip) ; CFI_ADJUST(8)
+
+#define POP_VAR(dstlabel) \
+ popq G(dstlabel)(%rip); CFI_ADJUST(-8)
+
+#define RECORD_STACK_FRAME(OFFSET) \
+ movq OFFSET(%rsp), %rax ; \
+ STORE_VAR(%rax,caml_last_return_address) ; \
+ leaq 8+OFFSET(%rsp), %rax ; \
+ STORE_VAR(%rax,caml_bottom_of_stack)
+
+#define LEA_VAR(label,dst) \
+ leaq G(label)(%rip), dst
+#endif
+
+/* Save and restore all callee-save registers on stack.
+ Keep the stack 16-aligned. */
+
+#if defined(SYS_mingw64) || defined(SYS_cygwin)
+
+/* Win64 API: callee-save regs are rbx, rbp, rsi, rdi, r12-r15, xmm6-xmm15 */
+
+#define PUSH_CALLEE_SAVE_REGS \
+ pushq %rbx; CFI_ADJUST (8); \
+ pushq %rbp; CFI_ADJUST (8); \
+ pushq %rsi; CFI_ADJUST (8); \
+ pushq %rdi; CFI_ADJUST (8); \
+ pushq %r12; CFI_ADJUST (8); \
+ pushq %r13; CFI_ADJUST (8); \
+ pushq %r14; CFI_ADJUST (8); \
+ pushq %r15; CFI_ADJUST (8); \
+ subq $(8+10*16), %rsp; CFI_ADJUST (8+10*16); \
+ movupd %xmm6, 0*16(%rsp); \
+ movupd %xmm7, 1*16(%rsp); \
+ movupd %xmm8, 2*16(%rsp); \
+ movupd %xmm9, 3*16(%rsp); \
+ movupd %xmm10, 4*16(%rsp); \
+ movupd %xmm11, 5*16(%rsp); \
+ movupd %xmm12, 6*16(%rsp); \
+ movupd %xmm13, 7*16(%rsp); \
+ movupd %xmm14, 8*16(%rsp); \
+ movupd %xmm15, 9*16(%rsp)
+
+#define POP_CALLEE_SAVE_REGS \
+ movupd 0*16(%rsp), %xmm6; \
+ movupd 1*16(%rsp), %xmm7; \
+ movupd 2*16(%rsp), %xmm8; \
+ movupd 3*16(%rsp), %xmm9; \
+ movupd 4*16(%rsp), %xmm10; \
+ movupd 5*16(%rsp), %xmm11; \
+ movupd 6*16(%rsp), %xmm12; \
+ movupd 7*16(%rsp), %xmm13; \
+ movupd 8*16(%rsp), %xmm14; \
+ movupd 9*16(%rsp), %xmm15; \
+ addq $(8+10*16), %rsp; CFI_ADJUST (-8-10*16); \
+ popq %r15; CFI_ADJUST(-8); \
+ popq %r14; CFI_ADJUST(-8); \
+ popq %r13; CFI_ADJUST(-8); \
+ popq %r12; CFI_ADJUST(-8); \
+ popq %rdi; CFI_ADJUST(-8); \
+ popq %rsi; CFI_ADJUST(-8); \
+ popq %rbp; CFI_ADJUST(-8); \
+ popq %rbx; CFI_ADJUST(-8)
+
+#else
+
+/* Unix API: callee-save regs are rbx, rbp, r12-r15 */
+
+#define PUSH_CALLEE_SAVE_REGS \
+ pushq %rbx; CFI_ADJUST(8); \
+ pushq %rbp; CFI_ADJUST(8); \
+ pushq %r12; CFI_ADJUST(8); \
+ pushq %r13; CFI_ADJUST(8); \
+ pushq %r14; CFI_ADJUST(8); \
+ pushq %r15; CFI_ADJUST(8); \
+ subq $8, %rsp; CFI_ADJUST(8)
+
+#define POP_CALLEE_SAVE_REGS \
+ addq $8, %rsp; CFI_ADJUST(-8); \
+ popq %r15; CFI_ADJUST(-8); \
+ popq %r14; CFI_ADJUST(-8); \
+ popq %r13; CFI_ADJUST(-8); \
+ popq %r12; CFI_ADJUST(-8); \
+ popq %rbp; CFI_ADJUST(-8); \
+ popq %rbx; CFI_ADJUST(-8);
+
+#endif
+
+#if defined(SYS_mingw64) || defined (SYS_cygwin)
+ /* Calls from OCaml to C must reserve 32 bytes of extra stack space */
+# define PREPARE_FOR_C_CALL subq $32, %rsp; CFI_ADJUST(32)
+# define CLEANUP_AFTER_C_CALL addq $32, %rsp; CFI_ADJUST(-32)
+#else
+# define PREPARE_FOR_C_CALL
+# define CLEANUP_AFTER_C_CALL
+#endif
+
+ .text
+
+ .globl G(caml_system__code_begin)
+G(caml_system__code_begin):
+ ret /* just one instruction, so that debuggers don't display
+ caml_system__code_begin instead of caml_call_gc */
+
+/* Allocation */
+
+FUNCTION(G(caml_call_gc))
+ CFI_STARTPROC
+ RECORD_STACK_FRAME(0)
+LBL(caml_call_gc):
+#if !defined(SYS_mingw64) && !defined(SYS_cygwin)
+ /* Touch the stack to trigger a recoverable segfault
+ if insufficient space remains */
+ subq $32768, %rsp
+ movq %rax, 0(%rsp)
+ addq $32768, %rsp
+#endif
+ /* Build array of registers, save it into caml_gc_regs */
+#ifdef WITH_FRAME_POINTERS
+ ENTER_FUNCTION ;
+#else
+ pushq %rbp; CFI_ADJUST(8);
+#endif
+ pushq %r11; CFI_ADJUST (8);
+ pushq %r10; CFI_ADJUST (8);
+ pushq %r13; CFI_ADJUST (8);
+ pushq %r12; CFI_ADJUST (8);
+ pushq %r9; CFI_ADJUST (8);
+ pushq %r8; CFI_ADJUST (8);
+ pushq %rcx; CFI_ADJUST (8);
+ pushq %rdx; CFI_ADJUST (8);
+ pushq %rsi; CFI_ADJUST (8);
+ pushq %rdi; CFI_ADJUST (8);
+ pushq %rbx; CFI_ADJUST (8);
+ pushq %rax; CFI_ADJUST (8);
+ STORE_VAR(%rsp, caml_gc_regs)
+ /* Save caml_young_ptr, caml_exception_pointer */
+ STORE_VAR(%r15, caml_young_ptr)
+ STORE_VAR(%r14, caml_exception_pointer)
+ /* Save floating-point registers */
+ subq $(16*8), %rsp; CFI_ADJUST (16*8);
+ movsd %xmm0, 0*8(%rsp)
+ movsd %xmm1, 1*8(%rsp)
+ movsd %xmm2, 2*8(%rsp)
+ movsd %xmm3, 3*8(%rsp)
+ movsd %xmm4, 4*8(%rsp)
+ movsd %xmm5, 5*8(%rsp)
+ movsd %xmm6, 6*8(%rsp)
+ movsd %xmm7, 7*8(%rsp)
+ movsd %xmm8, 8*8(%rsp)
+ movsd %xmm9, 9*8(%rsp)
+ movsd %xmm10, 10*8(%rsp)
+ movsd %xmm11, 11*8(%rsp)
+ movsd %xmm12, 12*8(%rsp)
+ movsd %xmm13, 13*8(%rsp)
+ movsd %xmm14, 14*8(%rsp)
+ movsd %xmm15, 15*8(%rsp)
+ /* Call the garbage collector */
+ PREPARE_FOR_C_CALL
+ call GCALL(caml_garbage_collection)
+ CLEANUP_AFTER_C_CALL
+ /* Restore caml_young_ptr, caml_exception_pointer */
+ LOAD_VAR(caml_young_ptr, %r15)
+ LOAD_VAR(caml_exception_pointer, %r14)
+ /* Restore all regs used by the code generator */
+ movsd 0*8(%rsp), %xmm0
+ movsd 1*8(%rsp), %xmm1
+ movsd 2*8(%rsp), %xmm2
+ movsd 3*8(%rsp), %xmm3
+ movsd 4*8(%rsp), %xmm4
+ movsd 5*8(%rsp), %xmm5
+ movsd 6*8(%rsp), %xmm6
+ movsd 7*8(%rsp), %xmm7
+ movsd 8*8(%rsp), %xmm8
+ movsd 9*8(%rsp), %xmm9
+ movsd 10*8(%rsp), %xmm10
+ movsd 11*8(%rsp), %xmm11
+ movsd 12*8(%rsp), %xmm12
+ movsd 13*8(%rsp), %xmm13
+ movsd 14*8(%rsp), %xmm14
+ movsd 15*8(%rsp), %xmm15
+ addq $(16*8), %rsp; CFI_ADJUST(-16*8)
+ popq %rax; CFI_ADJUST(-8)
+ popq %rbx; CFI_ADJUST(-8)
+ popq %rdi; CFI_ADJUST(-8)
+ popq %rsi; CFI_ADJUST(-8)
+ popq %rdx; CFI_ADJUST(-8)
+ popq %rcx; CFI_ADJUST(-8)
+ popq %r8; CFI_ADJUST(-8)
+ popq %r9; CFI_ADJUST(-8)
+ popq %r12; CFI_ADJUST(-8)
+ popq %r13; CFI_ADJUST(-8)
+ popq %r10; CFI_ADJUST(-8)
+ popq %r11; CFI_ADJUST(-8)
+#ifdef WITH_FRAME_POINTERS
+ LEAVE_FUNCTION
+#else
+ popq %rbp; CFI_ADJUST(-8);
+#endif
+ /* Return to caller */
+ ret
+CFI_ENDPROC
+
+FUNCTION(G(caml_alloc1))
+CFI_STARTPROC
+LBL(caml_alloc1):
+ subq $16, %r15
+ CMP_VAR(caml_young_limit, %r15)
+ jb LBL(100)
+ ret
+LBL(100):
+ RECORD_STACK_FRAME(0)
+ ENTER_FUNCTION
+/* subq $8, %rsp; CFI_ADJUST (8); */
+ call LBL(caml_call_gc)
+/* addq $8, %rsp; CFI_ADJUST (-8); */
+ LEAVE_FUNCTION
+ jmp LBL(caml_alloc1)
+CFI_ENDPROC
+
+FUNCTION(G(caml_alloc2))
+CFI_STARTPROC
+LBL(caml_alloc2):
+ subq $24, %r15
+ CMP_VAR(caml_young_limit, %r15)
+ jb LBL(101)
+ ret
+LBL(101):
+ RECORD_STACK_FRAME(0)
+ ENTER_FUNCTION
+/* subq $8, %rsp; CFI_ADJUST (8); */
+ call LBL(caml_call_gc)
+/* addq $8, %rsp; CFI_ADJUST (-8); */
+ LEAVE_FUNCTION
+ jmp LBL(caml_alloc2)
+CFI_ENDPROC
+
+FUNCTION(G(caml_alloc3))
+CFI_STARTPROC
+LBL(caml_alloc3):
+ subq $32, %r15
+ CMP_VAR(caml_young_limit, %r15)
+ jb LBL(102)
+ ret
+LBL(102):
+ RECORD_STACK_FRAME(0)
+ ENTER_FUNCTION
+/* subq $8, %rsp; CFI_ADJUST (8) */
+ call LBL(caml_call_gc)
+/* addq $8, %rsp; CFI_ADJUST (-8) */
+ LEAVE_FUNCTION
+ jmp LBL(caml_alloc3)
+CFI_ENDPROC
+
+FUNCTION(G(caml_allocN))
+CFI_STARTPROC
+LBL(caml_allocN):
+ pushq %rax; CFI_ADJUST(8) /* save desired size */
+ subq %rax, %r15
+ CMP_VAR(caml_young_limit, %r15)
+ jb LBL(103)
+ addq $8, %rsp; CFI_ADJUST (-8) /* drop desired size */
+ ret
+LBL(103):
+ RECORD_STACK_FRAME(8)
+#ifdef WITH_FRAME_POINTERS
+ /* Do we need 16-byte alignment here ? */
+ ENTER_FUNCTION
+#endif
+ call LBL(caml_call_gc)
+#ifdef WITH_FRAME_POINTERS
+ LEAVE_FUNCTION
+#endif
+ popq %rax; CFI_ADJUST(-8) /* recover desired size */
+ jmp LBL(caml_allocN)
+CFI_ENDPROC
+
+/* Call a C function from OCaml */
+
+FUNCTION(G(caml_c_call))
+CFI_STARTPROC
+LBL(caml_c_call):
+ /* Record lowest stack address and return address */
+ popq %r12; CFI_ADJUST(-8)
+ STORE_VAR(%r12, caml_last_return_address)
+ STORE_VAR(%rsp, caml_bottom_of_stack)
+ subq $8, %rsp; CFI_ADJUST(8) /* equivalent to pushq %r12 */
+#if !defined(SYS_mingw64) && !defined(SYS_cygwin)
+ /* Touch the stack to trigger a recoverable segfault
+ if insufficient space remains */
+ subq $32768, %rsp
+ movq %rax, 0(%rsp)
+ addq $32768, %rsp
+#endif
+ /* Make the exception handler and alloc ptr available to the C code */
+ STORE_VAR(%r15, caml_young_ptr)
+ STORE_VAR(%r14, caml_exception_pointer)
+ /* Call the function (address in %rax) */
+ /* No need to PREPARE_FOR_C_CALL since the caller already
+ reserved the stack space if needed (cf. amd64/proc.ml) */
+ jmp *%rax
+CFI_ENDPROC
+
+/* Start the OCaml program */
+
+FUNCTION(G(caml_start_program))
+ CFI_STARTPROC
+ /* Save callee-save registers */
+ PUSH_CALLEE_SAVE_REGS
+ /* Initial entry point is G(caml_program) */
+ LEA_VAR(caml_program, %r12)
+ /* Common code for caml_start_program and caml_callback* */
+LBL(caml_start_program):
+ /* Build a callback link */
+ subq $8, %rsp; CFI_ADJUST (8) /* stack 16-aligned */
+ PUSH_VAR(caml_gc_regs)
+ PUSH_VAR(caml_last_return_address)
+ PUSH_VAR(caml_bottom_of_stack)
+ /* Setup alloc ptr and exception ptr */
+ LOAD_VAR(caml_young_ptr, %r15)
+ LOAD_VAR(caml_exception_pointer, %r14)
+ /* Build an exception handler */
+ lea LBL(108)(%rip), %r13
+ pushq %r13; CFI_ADJUST(8)
+ pushq %r14; CFI_ADJUST(8)
+ CFI_ADJUST(16)
+ movq %rsp, %r14
+ /* Call the OCaml code */
+ call *%r12
+LBL(107):
+ /* Pop the exception handler */
+ popq %r14; CFI_ADJUST(-8)
+ popq %r12; CFI_ADJUST(-8) /* dummy register */
+ CFI_ADJUST(-16)
+LBL(109):
+ /* Update alloc ptr and exception ptr */
+ STORE_VAR(%r15,caml_young_ptr)
+ STORE_VAR(%r14,caml_exception_pointer)
+ /* Pop the callback link, restoring the global variables */
+ POP_VAR(caml_bottom_of_stack)
+ POP_VAR(caml_last_return_address)
+ POP_VAR(caml_gc_regs)
+ addq $8, %rsp; CFI_ADJUST (-8);
+ /* Restore callee-save registers. */
+ POP_CALLEE_SAVE_REGS
+ /* Return to caller. */
+ ret
+LBL(108):
+ /* Exception handler*/
+ /* Mark the bucket as an exception result and return it */
+ orq $2, %rax
+ jmp LBL(109)
+CFI_ENDPROC
+
+/* Registers holding arguments of C functions. */
+
+#if defined(SYS_mingw64) || defined(SYS_cygwin)
+#define C_ARG_1 %rcx
+#define C_ARG_2 %rdx
+#define C_ARG_3 %r8
+#define C_ARG_4 %r9
+#else
+#define C_ARG_1 %rdi
+#define C_ARG_2 %rsi
+#define C_ARG_3 %rdx
+#define C_ARG_4 %rcx
+#endif
+
+/* Raise an exception from OCaml */
+
+FUNCTION(G(caml_raise_exn))
+CFI_STARTPROC
+ TESTL_VAR($1, caml_backtrace_active)
+ jne LBL(110)
+ movq %r14, %rsp
+ popq %r14
+ ret
+LBL(110):
+ STORE_VAR32($0, caml_backtrace_pos)
+LBL(111):
+ movq %rax, %r12 /* Save exception bucket */
+ movq %rax, C_ARG_1 /* arg 1: exception bucket */
+#ifdef WITH_FRAME_POINTERS
+ ENTER_FUNCTION
+ movq 8(%rsp), C_ARG_2 /* arg 2: pc of raise */
+ leaq 16(%rsp), C_ARG_3 /* arg 3: sp at raise */
+#else
+ popq C_ARG_2 /* arg 2: pc of raise */
+ movq %rsp, C_ARG_3 /* arg 3: sp at raise */
+#endif
+ movq %r14, C_ARG_4 /* arg 4: sp of handler */
+ /* PR#5700: thanks to popq above, stack is now 16-aligned */
+ /* Thanks to ENTER_FUNCTION, stack is now 16-aligned */
+ PREPARE_FOR_C_CALL /* no need to cleanup after */
+ call GCALL(caml_stash_backtrace)
+ movq %r12, %rax /* Recover exception bucket */
+ movq %r14, %rsp
+ popq %r14
+ ret
+CFI_ENDPROC
+
+FUNCTION(G(caml_reraise_exn))
+CFI_STARTPROC
+ TESTL_VAR($1, caml_backtrace_active)
+ jne LBL(111)
+ movq %r14, %rsp
+ popq %r14
+ ret
+CFI_ENDPROC
+
+/* Raise an exception from C */
+
+FUNCTION(G(caml_raise_exception))
+CFI_STARTPROC
+ TESTL_VAR($1, caml_backtrace_active)
+ jne LBL(112)
+ movq C_ARG_1, %rax
+ LOAD_VAR(caml_exception_pointer, %rsp) /* Cut stack */
+ popq %r14 /* Recover previous exception handler */
+ LOAD_VAR(caml_young_ptr, %r15) /* Reload alloc ptr */
+ ret
+LBL(112):
+#ifdef WITH_FRAME_POINTERS
+ ENTER_FUNCTION ;
+#endif
+ movq C_ARG_1, %r12 /* Save exception bucket */
+ /* arg 1: exception bucket */
+ LOAD_VAR(caml_last_return_address,C_ARG_2) /* arg 2: pc of raise */
+ LOAD_VAR(caml_bottom_of_stack,C_ARG_3) /* arg 3: sp of raise */
+ LOAD_VAR(caml_exception_pointer,C_ARG_4) /* arg 4: sp of handler */
+#ifndef WITH_FRAME_POINTERS
+ subq $8, %rsp /* PR#5700: maintain stack alignment */
+#endif
+ PREPARE_FOR_C_CALL /* no need to cleanup after */
+ call GCALL(caml_stash_backtrace)
+ movq %r12, %rax /* Recover exception bucket */
+ LOAD_VAR(caml_exception_pointer,%rsp)
+ popq %r14 /* Recover previous exception handler */
+ LOAD_VAR(caml_young_ptr,%r15) /* Reload alloc ptr */
+ ret
+CFI_ENDPROC
+
+/* Raise a Stack_overflow exception on return from segv_handler()
+ (in asmrun/signals_asm.c). On entry, the stack is full, so we
+ cannot record a backtrace.
+ No CFI information here since this function disrupts the stack
+ backtrace anyway. */
+
+FUNCTION(G(caml_stack_overflow))
+ LEA_VAR(caml_exn_Stack_overflow, %rax)
+ movq %r14, %rsp /* cut the stack */
+ popq %r14 /* recover previous exn handler */
+ ret /* jump to handler's code */
+
+/* Callback from C to OCaml */
+
+FUNCTION(G(caml_callback_exn))
+CFI_STARTPROC
+ /* Save callee-save registers */
+ PUSH_CALLEE_SAVE_REGS
+ /* Initial loading of arguments */
+ movq C_ARG_1, %rbx /* closure */
+ movq C_ARG_2, %rax /* argument */
+ movq 0(%rbx), %r12 /* code pointer */
+ jmp LBL(caml_start_program)
+CFI_ENDPROC
+
+FUNCTION(G(caml_callback2_exn))
+CFI_STARTPROC
+ /* Save callee-save registers */
+ PUSH_CALLEE_SAVE_REGS
+ /* Initial loading of arguments */
+ movq C_ARG_1, %rdi /* closure -- no op with Unix conventions */
+ movq C_ARG_2, %rax /* first argument */
+ movq C_ARG_3, %rbx /* second argument */
+ LEA_VAR(caml_apply2, %r12) /* code pointer */
+ jmp LBL(caml_start_program)
+CFI_ENDPROC
+
+FUNCTION(G(caml_callback3_exn))
+CFI_STARTPROC
+ /* Save callee-save registers */
+ PUSH_CALLEE_SAVE_REGS
+ /* Initial loading of arguments */
+ movq C_ARG_2, %rax /* first argument */
+ movq C_ARG_3, %rbx /* second argument */
+ movq C_ARG_1, %rsi /* closure */
+ movq C_ARG_4, %rdi /* third argument */
+ LEA_VAR(caml_apply3, %r12) /* code pointer */
+ jmp LBL(caml_start_program)
+CFI_ENDPROC
+
+FUNCTION(G(caml_ml_array_bound_error))
+CFI_STARTPROC
+ LEA_VAR(caml_array_bound_error, %rax)
+ jmp LBL(caml_c_call)
+CFI_ENDPROC
+
+ .globl G(caml_system__code_end)
+G(caml_system__code_end):
+
+ .data
+ .globl G(caml_system__frametable)
+ .align EIGHT_ALIGN
+G(caml_system__frametable):
+ .quad 1 /* one descriptor */
+ .quad LBL(107) /* return address into callback */
+ .value -1 /* negative frame size => use callback link */
+ .value 0 /* no roots here */
+ .align EIGHT_ALIGN
+
+#if defined(SYS_macosx)
+ .literal16
+#elif defined(SYS_mingw64) || defined(SYS_cygwin)
+ .section .rdata,"dr"
+#else
+ .section .rodata.cst8,"a",@progbits
+#endif
+ .globl G(caml_negf_mask)
+ .align SIXTEEN_ALIGN
+G(caml_negf_mask):
+ .quad 0x8000000000000000, 0
+ .globl G(caml_absf_mask)
+ .align SIXTEEN_ALIGN
+G(caml_absf_mask):
+ .quad 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF
+
+#if defined(SYS_linux)
+ /* Mark stack as non-executable, PR#4564 */
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/asmrun/amd64nt.asm b/asmrun/amd64nt.asm
new file mode 100644
index 0000000000..4883ba9772
--- /dev/null
+++ b/asmrun/amd64nt.asm
@@ -0,0 +1,476 @@
+;***********************************************************************
+;* *
+;* OCaml *
+;* *
+;* Xavier Leroy, projet Gallium, INRIA Rocquencourt *
+;* *
+;* Copyright 2006 Institut National de Recherche en Informatique et *
+;* en Automatique. All rights reserved. This file is distributed *
+;* under the terms of the GNU Library General Public License, with *
+;* the special exception on linking described in file ../LICENSE. *
+;* *
+;***********************************************************************
+
+; Asm part of the runtime system, AMD64 processor, Intel syntax
+
+; Notes on Win64 calling conventions:
+; function arguments in RCX, RDX, R8, R9 / XMM0 - XMM3
+; caller must reserve 32 bytes of stack space
+; callee must preserve RBX, RBP, RSI, RDI, R12-R15, XMM6-XMM15
+
+ EXTRN caml_garbage_collection: NEAR
+ EXTRN caml_apply2: NEAR
+ EXTRN caml_apply3: NEAR
+ EXTRN caml_program: NEAR
+ EXTRN caml_array_bound_error: NEAR
+ EXTRN caml_young_limit: QWORD
+ EXTRN caml_young_ptr: QWORD
+ EXTRN caml_bottom_of_stack: QWORD
+ EXTRN caml_last_return_address: QWORD
+ EXTRN caml_gc_regs: QWORD
+ EXTRN caml_exception_pointer: QWORD
+ EXTRN caml_backtrace_pos: DWORD
+ EXTRN caml_backtrace_active: DWORD
+ EXTRN caml_stash_backtrace: NEAR
+
+ .CODE
+
+; Allocation
+
+ PUBLIC caml_call_gc
+ ALIGN 16
+caml_call_gc:
+ ; Record lowest stack address and return address
+ mov rax, [rsp]
+ mov caml_last_return_address, rax
+ lea rax, [rsp+8]
+ mov caml_bottom_of_stack, rax
+L105:
+ ; Save caml_young_ptr, caml_exception_pointer
+ mov caml_young_ptr, r15
+ mov caml_exception_pointer, r14
+ ; Build array of registers, save it into caml_gc_regs
+ push rbp
+ push r11
+ push r10
+ push r13
+ push r12
+ push r9
+ push r8
+ push rcx
+ push rdx
+ push rsi
+ push rdi
+ push rbx
+ push rax
+ mov caml_gc_regs, rsp
+ ; Save floating-point registers
+ sub rsp, 16*8
+ movsd QWORD PTR [rsp + 0*8], xmm0
+ movsd QWORD PTR [rsp + 1*8], xmm1
+ movsd QWORD PTR [rsp + 2*8], xmm2
+ movsd QWORD PTR [rsp + 3*8], xmm3
+ movsd QWORD PTR [rsp + 4*8], xmm4
+ movsd QWORD PTR [rsp + 5*8], xmm5
+ movsd QWORD PTR [rsp + 6*8], xmm6
+ movsd QWORD PTR [rsp + 7*8], xmm7
+ movsd QWORD PTR [rsp + 8*8], xmm8
+ movsd QWORD PTR [rsp + 9*8], xmm9
+ movsd QWORD PTR [rsp + 10*8], xmm10
+ movsd QWORD PTR [rsp + 11*8], xmm11
+ movsd QWORD PTR [rsp + 12*8], xmm12
+ movsd QWORD PTR [rsp + 13*8], xmm13
+ movsd QWORD PTR [rsp + 14*8], xmm14
+ movsd QWORD PTR [rsp + 15*8], xmm15
+ ; Call the garbage collector
+ sub rsp, 32 ; PR#5008: bottom 32 bytes are reserved for callee
+ call caml_garbage_collection
+ add rsp, 32 ; PR#5008
+ ; Restore all regs used by the code generator
+ movsd xmm0, QWORD PTR [rsp + 0*8]
+ movsd xmm1, QWORD PTR [rsp + 1*8]
+ movsd xmm2, QWORD PTR [rsp + 2*8]
+ movsd xmm3, QWORD PTR [rsp + 3*8]
+ movsd xmm4, QWORD PTR [rsp + 4*8]
+ movsd xmm5, QWORD PTR [rsp + 5*8]
+ movsd xmm6, QWORD PTR [rsp + 6*8]
+ movsd xmm7, QWORD PTR [rsp + 7*8]
+ movsd xmm8, QWORD PTR [rsp + 8*8]
+ movsd xmm9, QWORD PTR [rsp + 9*8]
+ movsd xmm10, QWORD PTR [rsp + 10*8]
+ movsd xmm11, QWORD PTR [rsp + 11*8]
+ movsd xmm12, QWORD PTR [rsp + 12*8]
+ movsd xmm13, QWORD PTR [rsp + 13*8]
+ movsd xmm14, QWORD PTR [rsp + 14*8]
+ movsd xmm15, QWORD PTR [rsp + 15*8]
+ add rsp, 16*8
+ pop rax
+ pop rbx
+ pop rdi
+ pop rsi
+ pop rdx
+ pop rcx
+ pop r8
+ pop r9
+ pop r12
+ pop r13
+ pop r10
+ pop r11
+ pop rbp
+ ; Restore caml_young_ptr, caml_exception_pointer
+ mov r15, caml_young_ptr
+ mov r14, caml_exception_pointer
+ ; Return to caller
+ ret
+
+ PUBLIC caml_alloc1
+ ALIGN 16
+caml_alloc1:
+ sub r15, 16
+ cmp r15, caml_young_limit
+ jb L100
+ ret
+L100:
+ mov rax, [rsp + 0]
+ mov caml_last_return_address, rax
+ lea rax, [rsp + 8]
+ mov caml_bottom_of_stack, rax
+ sub rsp, 8
+ call L105
+ add rsp, 8
+ jmp caml_alloc1
+
+ PUBLIC caml_alloc2
+ ALIGN 16
+caml_alloc2:
+ sub r15, 24
+ cmp r15, caml_young_limit
+ jb L101
+ ret
+L101:
+ mov rax, [rsp + 0]
+ mov caml_last_return_address, rax
+ lea rax, [rsp + 8]
+ mov caml_bottom_of_stack, rax
+ sub rsp, 8
+ call L105
+ add rsp, 8
+ jmp caml_alloc2
+
+ PUBLIC caml_alloc3
+ ALIGN 16
+caml_alloc3:
+ sub r15, 32
+ cmp r15, caml_young_limit
+ jb L102
+ ret
+L102:
+ mov rax, [rsp + 0]
+ mov caml_last_return_address, rax
+ lea rax, [rsp + 8]
+ mov caml_bottom_of_stack, rax
+ sub rsp, 8
+ call L105
+ add rsp, 8
+ jmp caml_alloc3
+
+ PUBLIC caml_allocN
+ ALIGN 16
+caml_allocN:
+ sub r15, rax
+ cmp r15, caml_young_limit
+ jb L103
+ ret
+L103:
+ push rax ; save desired size
+ mov rax, [rsp + 8]
+ mov caml_last_return_address, rax
+ lea rax, [rsp + 16]
+ mov caml_bottom_of_stack, rax
+ call L105
+ pop rax ; recover desired size
+ jmp caml_allocN
+
+; Call a C function from OCaml
+
+ PUBLIC caml_c_call
+ ALIGN 16
+caml_c_call:
+ ; Record lowest stack address and return address
+ pop r12
+ mov caml_last_return_address, r12
+ mov caml_bottom_of_stack, rsp
+ ; Make the exception handler and alloc ptr available to the C code
+ mov caml_young_ptr, r15
+ mov caml_exception_pointer, r14
+ ; Call the function (address in rax)
+ call rax
+ ; Reload alloc ptr
+ mov r15, caml_young_ptr
+ ; Return to caller
+ push r12
+ ret
+
+; Start the OCaml program
+
+ PUBLIC caml_start_program
+ ALIGN 16
+caml_start_program:
+ ; Save callee-save registers
+ push rbx
+ push rbp
+ push rsi
+ push rdi
+ push r12
+ push r13
+ push r14
+ push r15
+ sub rsp, 8+10*16 ; stack 16-aligned + 10 saved xmm regs
+ movapd OWORD PTR [rsp + 0*16], xmm6
+ movapd OWORD PTR [rsp + 1*16], xmm7
+ movapd OWORD PTR [rsp + 2*16], xmm8
+ movapd OWORD PTR [rsp + 3*16], xmm9
+ movapd OWORD PTR [rsp + 4*16], xmm10
+ movapd OWORD PTR [rsp + 5*16], xmm11
+ movapd OWORD PTR [rsp + 6*16], xmm12
+ movapd OWORD PTR [rsp + 7*16], xmm13
+ movapd OWORD PTR [rsp + 8*16], xmm14
+ movapd OWORD PTR [rsp + 9*16], xmm15
+ ; Initial entry point is caml_program
+ lea r12, caml_program
+ ; Common code for caml_start_program and caml_callback*
+L106:
+ ; Build a callback link
+ sub rsp, 8 ; stack 16-aligned
+ push caml_gc_regs
+ push caml_last_return_address
+ push caml_bottom_of_stack
+ ; Setup alloc ptr and exception ptr
+ mov r15, caml_young_ptr
+ mov r14, caml_exception_pointer
+ ; Build an exception handler
+ lea r13, L108
+ push r13
+ push r14
+ mov r14, rsp
+ ; Call the OCaml code
+ call r12
+L107:
+ ; Pop the exception handler
+ pop r14
+ pop r12 ; dummy register
+L109:
+ ; Update alloc ptr and exception ptr
+ mov caml_young_ptr, r15
+ mov caml_exception_pointer, r14
+ ; Pop the callback restoring, link the global variables
+ pop caml_bottom_of_stack
+ pop caml_last_return_address
+ pop caml_gc_regs
+ add rsp, 8
+ ; Restore callee-save registers.
+ movapd xmm6, OWORD PTR [rsp + 0*16]
+ movapd xmm7, OWORD PTR [rsp + 1*16]
+ movapd xmm8, OWORD PTR [rsp + 2*16]
+ movapd xmm9, OWORD PTR [rsp + 3*16]
+ movapd xmm10, OWORD PTR [rsp + 4*16]
+ movapd xmm11, OWORD PTR [rsp + 5*16]
+ movapd xmm12, OWORD PTR [rsp + 6*16]
+ movapd xmm13, OWORD PTR [rsp + 7*16]
+ movapd xmm14, OWORD PTR [rsp + 8*16]
+ movapd xmm15, OWORD PTR [rsp + 9*16]
+ add rsp, 8+10*16
+ pop r15
+ pop r14
+ pop r13
+ pop r12
+ pop rdi
+ pop rsi
+ pop rbp
+ pop rbx
+ ; Return to caller
+ ret
+L108:
+ ; Exception handler
+ ; Mark the bucket as an exception result and return it
+ or rax, 2
+ jmp L109
+
+; Raise an exception from OCaml
+
+ PUBLIC caml_raise_exn
+ ALIGN 16
+caml_raise_exn:
+ test caml_backtrace_active, 1
+ jne L110
+ mov rsp, r14 ; Cut stack
+ pop r14 ; Recover previous exception handler
+ ret ; Branch to handler
+L110:
+ mov caml_backtrace_pos, 0
+L111:
+ mov r12, rax ; Save exception bucket in r12
+ mov rcx, rax ; Arg 1: exception bucket
+ mov rdx, [rsp] ; Arg 2: PC of raise
+ lea r8, [rsp+8] ; Arg 3: SP of raise
+ mov r9, r14 ; Arg 4: SP of handler
+ sub rsp, 32 ; Reserve 32 bytes on stack
+ call caml_stash_backtrace
+ mov rax, r12 ; Recover exception bucket
+ mov rsp, r14 ; Cut stack
+ pop r14 ; Recover previous exception handler
+ ret ; Branch to handler
+
+ PUBLIC caml_reraise_exn
+ ALIGN 16
+caml_reraise_exn:
+ test caml_backtrace_active, 1
+ jne L111
+ mov rsp, r14 ; Cut stack
+ pop r14 ; Recover previous exception handler
+ ret ; Branch to handler
+
+; Raise an exception from C
+
+ PUBLIC caml_raise_exception
+ ALIGN 16
+caml_raise_exception:
+ test caml_backtrace_active, 1
+ jne L112
+ mov rax, rcx ; First argument is exn bucket
+ mov rsp, caml_exception_pointer
+ pop r14 ; Recover previous exception handler
+ mov r15, caml_young_ptr ; Reload alloc ptr
+ ret
+L112:
+ mov r12, rcx ; Save exception bucket in r12
+ ; Arg 1: exception bucket
+ mov rdx, caml_last_return_address ; Arg 2: PC of raise
+ mov r8, caml_bottom_of_stack ; Arg 3: SP of raise
+ mov r9, caml_exception_pointer ; Arg 4: SP of handler
+ sub rsp, 32 ; Reserve 32 bytes on stack
+ call caml_stash_backtrace
+ mov rax, r12 ; Recover exception bucket
+ mov rsp, caml_exception_pointer
+ pop r14 ; Recover previous exception handler
+ mov r15, caml_young_ptr ; Reload alloc ptr
+ ret
+
+; Callback from C to OCaml
+
+ PUBLIC caml_callback_exn
+ ALIGN 16
+caml_callback_exn:
+ ; Save callee-save registers
+ push rbx
+ push rbp
+ push rsi
+ push rdi
+ push r12
+ push r13
+ push r14
+ push r15
+ sub rsp, 8+10*16 ; stack 16-aligned + 10 saved xmm regs
+ movapd OWORD PTR [rsp + 0*16], xmm6
+ movapd OWORD PTR [rsp + 1*16], xmm7
+ movapd OWORD PTR [rsp + 2*16], xmm8
+ movapd OWORD PTR [rsp + 3*16], xmm9
+ movapd OWORD PTR [rsp + 4*16], xmm10
+ movapd OWORD PTR [rsp + 5*16], xmm11
+ movapd OWORD PTR [rsp + 6*16], xmm12
+ movapd OWORD PTR [rsp + 7*16], xmm13
+ movapd OWORD PTR [rsp + 8*16], xmm14
+ movapd OWORD PTR [rsp + 9*16], xmm15
+ ; Initial loading of arguments
+ mov rbx, rcx ; closure
+ mov rax, rdx ; argument
+ mov r12, [rbx] ; code pointer
+ jmp L106
+
+ PUBLIC caml_callback2_exn
+ ALIGN 16
+caml_callback2_exn:
+ ; Save callee-save registers
+ push rbx
+ push rbp
+ push rsi
+ push rdi
+ push r12
+ push r13
+ push r14
+ push r15
+ sub rsp, 8+10*16 ; stack 16-aligned + 10 saved xmm regs
+ movapd OWORD PTR [rsp + 0*16], xmm6
+ movapd OWORD PTR [rsp + 1*16], xmm7
+ movapd OWORD PTR [rsp + 2*16], xmm8
+ movapd OWORD PTR [rsp + 3*16], xmm9
+ movapd OWORD PTR [rsp + 4*16], xmm10
+ movapd OWORD PTR [rsp + 5*16], xmm11
+ movapd OWORD PTR [rsp + 6*16], xmm12
+ movapd OWORD PTR [rsp + 7*16], xmm13
+ movapd OWORD PTR [rsp + 8*16], xmm14
+ movapd OWORD PTR [rsp + 9*16], xmm15
+ ; Initial loading of arguments
+ mov rdi, rcx ; closure
+ mov rax, rdx ; first argument
+ mov rbx, r8 ; second argument
+ lea r12, caml_apply2 ; code pointer
+ jmp L106
+
+ PUBLIC caml_callback3_exn
+ ALIGN 16
+caml_callback3_exn:
+ ; Save callee-save registers
+ push rbx
+ push rbp
+ push rsi
+ push rdi
+ push r12
+ push r13
+ push r14
+ push r15
+ sub rsp, 8+10*16 ; stack 16-aligned + 10 saved xmm regs
+ movapd OWORD PTR [rsp + 0*16], xmm6
+ movapd OWORD PTR [rsp + 1*16], xmm7
+ movapd OWORD PTR [rsp + 2*16], xmm8
+ movapd OWORD PTR [rsp + 3*16], xmm9
+ movapd OWORD PTR [rsp + 4*16], xmm10
+ movapd OWORD PTR [rsp + 5*16], xmm11
+ movapd OWORD PTR [rsp + 6*16], xmm12
+ movapd OWORD PTR [rsp + 7*16], xmm13
+ movapd OWORD PTR [rsp + 8*16], xmm14
+ movapd OWORD PTR [rsp + 9*16], xmm15
+ ; Initial loading of arguments
+ mov rsi, rcx ; closure
+ mov rax, rdx ; first argument
+ mov rbx, r8 ; second argument
+ mov rdi, r9 ; third argument
+ lea r12, caml_apply3 ; code pointer
+ jmp L106
+
+ PUBLIC caml_ml_array_bound_error
+ ALIGN 16
+caml_ml_array_bound_error:
+ lea rax, caml_array_bound_error
+ jmp caml_c_call
+
+ .DATA
+ PUBLIC caml_system__frametable
+caml_system__frametable LABEL QWORD
+ QWORD 1 ; one descriptor
+ QWORD L107 ; return address into callback
+ WORD -1 ; negative frame size => use callback link
+ WORD 0 ; no roots here
+ ALIGN 8
+
+ PUBLIC caml_negf_mask
+ ALIGN 16
+caml_negf_mask LABEL QWORD
+ QWORD 8000000000000000H, 0
+
+ PUBLIC caml_absf_mask
+ ALIGN 16
+caml_absf_mask LABEL QWORD
+ QWORD 7FFFFFFFFFFFFFFFH, 0FFFFFFFFFFFFFFFFH
+
+ END
diff --git a/asmrun/arm.S b/asmrun/arm.S
new file mode 100644
index 0000000000..9720665aa3
--- /dev/null
+++ b/asmrun/arm.S
@@ -0,0 +1,500 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Benedikt Meurer, University of Siegen */
+/* */
+/* Copyright 1998 Institut National de Recherche en Informatique */
+/* et en Automatique. Copyright 2012 Benedikt Meurer. All rights */
+/* reserved. This file is distributed under the terms of the GNU */
+/* Library General Public License, with the special exception on */
+/* linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Asm part of the runtime system, ARM processor */
+/* Must be preprocessed by cpp */
+
+ .syntax unified
+ .text
+#if defined(SYS_linux_eabihf) && defined(MODEL_armv6)
+ .arch armv6
+ .fpu vfpv2
+ .arm
+
+ /* Compatibility macros */
+ .macro cbz reg, lbl
+ cmp \reg, #0
+ beq \lbl
+ .endm
+#elif defined(SYS_linux_eabihf)
+ .arch armv7-a
+ .fpu vfpv3-d16
+ .thumb
+#elif defined(SYS_linux_eabi)
+ .arch armv4t
+ .arm
+
+ /* Compatibility macros */
+ .macro blx reg
+ mov lr, pc
+ bx \reg
+ .endm
+ .macro cbz reg, lbl
+ cmp \reg, #0
+ beq \lbl
+ .endm
+#elif defined(SYS_freebsd)
+ .arch armv6
+ .arm
+
+ /* Compatibility macros */
+ .macro cbz reg, lbl
+ cmp \reg, #0
+ beq \lbl
+ .endm
+#endif
+
+trap_ptr .req r8
+alloc_ptr .req r10
+alloc_limit .req r11
+
+/* Support for CFI directives */
+
+#if defined(ASM_CFI_SUPPORTED)
+#define CFI_STARTPROC .cfi_startproc
+#define CFI_ENDPROC .cfi_endproc
+#define CFI_ADJUST(n) .cfi_adjust_cfa_offset n
+#else
+#define CFI_STARTPROC
+#define CFI_ENDPROC
+#define CFI_ADJUST(n)
+#endif
+
+/* Support for profiling with gprof */
+
+#if defined(PROFILING) && (defined(SYS_linux_eabihf) || defined(SYS_linux_eabi))
+#define PROFILE \
+ push {lr}; CFI_ADJUST(4); \
+ bl __gnu_mcount_nc; CFI_ADJUST(-4)
+#else
+#define PROFILE
+#endif
+
+/* Allocation functions and GC interface */
+
+ .globl caml_system__code_begin
+caml_system__code_begin:
+
+ .align 2
+ .globl caml_call_gc
+caml_call_gc:
+ CFI_STARTPROC
+ PROFILE
+ /* Record return address */
+ ldr r12, =caml_last_return_address
+ str lr, [r12]
+.Lcaml_call_gc:
+ /* Record lowest stack address */
+ ldr r12, =caml_bottom_of_stack
+ str sp, [r12]
+#if defined(SYS_linux_eabihf)
+ /* Save caller floating-point registers on the stack */
+ vpush {d0-d7}; CFI_ADJUST(64)
+#endif
+ /* Save integer registers and return address on the stack */
+ push {r0-r7,r12,lr}; CFI_ADJUST(40)
+ /* Store pointer to saved integer registers in caml_gc_regs */
+ ldr r12, =caml_gc_regs
+ str sp, [r12]
+ /* Save current allocation pointer for debugging purposes */
+ ldr alloc_limit, =caml_young_ptr
+ str alloc_ptr, [alloc_limit]
+ /* Save trap pointer in case an exception is raised during GC */
+ ldr r12, =caml_exception_pointer
+ str trap_ptr, [r12]
+ /* Call the garbage collector */
+ bl caml_garbage_collection
+ /* Restore integer registers and return address from the stack */
+ pop {r0-r7,r12,lr}; CFI_ADJUST(-40)
+#if defined(SYS_linux_eabihf)
+ /* Restore floating-point registers from the stack */
+ vpop {d0-d7}; CFI_ADJUST(-64)
+#endif
+ /* Reload new allocation pointer and limit */
+ /* alloc_limit still points to caml_young_ptr */
+ ldr r12, =caml_young_limit
+ ldr alloc_ptr, [alloc_limit]
+ ldr alloc_limit, [r12]
+ /* Return to caller */
+ bx lr
+ CFI_ENDPROC
+ .type caml_call_gc, %function
+ .size caml_call_gc, .-caml_call_gc
+
+ .align 2
+ .globl caml_alloc1
+caml_alloc1:
+ CFI_STARTPROC
+ PROFILE
+.Lcaml_alloc1:
+ sub alloc_ptr, alloc_ptr, 8
+ cmp alloc_ptr, alloc_limit
+ bcc 1f
+ bx lr
+1: /* Record return address */
+ ldr r7, =caml_last_return_address
+ str lr, [r7]
+ /* Call GC (preserves r7) */
+ bl .Lcaml_call_gc
+ /* Restore return address */
+ ldr lr, [r7]
+ /* Try again */
+ b .Lcaml_alloc1
+ CFI_ENDPROC
+ .type caml_alloc1, %function
+ .size caml_alloc1, .-caml_alloc1
+
+ .align 2
+ .globl caml_alloc2
+caml_alloc2:
+ CFI_STARTPROC
+ PROFILE
+.Lcaml_alloc2:
+ sub alloc_ptr, alloc_ptr, 12
+ cmp alloc_ptr, alloc_limit
+ bcc 1f
+ bx lr
+1: /* Record return address */
+ ldr r7, =caml_last_return_address
+ str lr, [r7]
+ /* Call GC (preserves r7) */
+ bl .Lcaml_call_gc
+ /* Restore return address */
+ ldr lr, [r7]
+ /* Try again */
+ b .Lcaml_alloc2
+ CFI_ENDPROC
+ .type caml_alloc2, %function
+ .size caml_alloc2, .-caml_alloc2
+
+ .align 2
+ .globl caml_alloc3
+ .type caml_alloc3, %function
+caml_alloc3:
+ CFI_STARTPROC
+ PROFILE
+.Lcaml_alloc3:
+ sub alloc_ptr, alloc_ptr, 16
+ cmp alloc_ptr, alloc_limit
+ bcc 1f
+ bx lr
+1: /* Record return address */
+ ldr r7, =caml_last_return_address
+ str lr, [r7]
+ /* Call GC (preserves r7) */
+ bl .Lcaml_call_gc
+ /* Restore return address */
+ ldr lr, [r7]
+ /* Try again */
+ b .Lcaml_alloc3
+ CFI_ENDPROC
+ .type caml_alloc3, %function
+ .size caml_alloc3, .-caml_alloc3
+
+ .align 2
+ .globl caml_allocN
+caml_allocN:
+ CFI_STARTPROC
+ PROFILE
+.Lcaml_allocN:
+ sub alloc_ptr, alloc_ptr, r7
+ cmp alloc_ptr, alloc_limit
+ bcc 1f
+ bx lr
+1: /* Record return address */
+ ldr r12, =caml_last_return_address
+ str lr, [r12]
+ /* Call GC (preserves r7) */
+ bl .Lcaml_call_gc
+ /* Restore return address */
+ ldr r12, =caml_last_return_address
+ ldr lr, [r12]
+ /* Try again */
+ b .Lcaml_allocN
+ CFI_ENDPROC
+ .type caml_allocN, %function
+ .size caml_allocN, .-caml_allocN
+
+/* Call a C function from OCaml */
+/* Function to call is in r7 */
+
+ .align 2
+ .globl caml_c_call
+caml_c_call:
+ CFI_STARTPROC
+ PROFILE
+ /* Record lowest stack address and return address */
+ ldr r5, =caml_last_return_address
+ ldr r6, =caml_bottom_of_stack
+ str lr, [r5]
+ str sp, [r6]
+ /* Preserve return address in callee-save register r4 */
+ mov r4, lr
+ /* Make the exception handler alloc ptr available to the C code */
+ ldr r5, =caml_young_ptr
+ ldr r6, =caml_exception_pointer
+ str alloc_ptr, [r5]
+ str trap_ptr, [r6]
+ /* Call the function */
+ blx r7
+ /* Reload alloc ptr and alloc limit */
+ ldr r6, =caml_young_limit
+ ldr alloc_ptr, [r5] /* r5 still points to caml_young_ptr */
+ ldr alloc_limit, [r6]
+ /* Return */
+ bx r4
+ CFI_ENDPROC
+ .type caml_c_call, %function
+ .size caml_c_call, .-caml_c_call
+
+/* Start the OCaml program */
+
+ .align 2
+ .globl caml_start_program
+caml_start_program:
+ CFI_STARTPROC
+ PROFILE
+ ldr r12, =caml_program
+
+/* Code shared with caml_callback* */
+/* Address of OCaml code to call is in r12 */
+/* Arguments to the OCaml code are in r0...r3 */
+
+.Ljump_to_caml:
+#if defined(SYS_linux_eabihf)
+ /* Save callee-save floating-point registers */
+ vpush {d8-d15}; CFI_ADJUST(64)
+#endif
+ /* Save return address and callee-save registers */
+ push {r4-r8,r10,r11,lr}; CFI_ADJUST(32) /* 8-byte alignment */
+ /* Setup a callback link on the stack */
+ sub sp, sp, 16; CFI_ADJUST(16) /* 8-byte alignment */
+ ldr r4, =caml_bottom_of_stack
+ ldr r5, =caml_last_return_address
+ ldr r6, =caml_gc_regs
+ ldr r4, [r4]
+ ldr r5, [r5]
+ ldr r6, [r6]
+ str r4, [sp, 0]
+ str r5, [sp, 4]
+ str r6, [sp, 8]
+ /* Setup a trap frame to catch exceptions escaping the OCaml code */
+ sub sp, sp, 8; CFI_ADJUST(8)
+ ldr r6, =caml_exception_pointer
+ ldr r5, =.Ltrap_handler
+ ldr r4, [r6]
+ str r4, [sp, 0]
+ str r5, [sp, 4]
+ mov trap_ptr, sp
+ /* Reload allocation pointers */
+ ldr r4, =caml_young_ptr
+ ldr alloc_ptr, [r4]
+ ldr r4, =caml_young_limit
+ ldr alloc_limit, [r4]
+ /* Call the OCaml code */
+ blx r12
+.Lcaml_retaddr:
+ /* Pop the trap frame, restoring caml_exception_pointer */
+ ldr r4, =caml_exception_pointer
+ ldr r5, [sp, 0]
+ str r5, [r4]
+ add sp, sp, 8; CFI_ADJUST(-8)
+ /* Pop the callback link, restoring the global variables */
+.Lreturn_result:
+ ldr r4, =caml_bottom_of_stack
+ ldr r5, [sp, 0]
+ str r5, [r4]
+ ldr r4, =caml_last_return_address
+ ldr r5, [sp, 4]
+ str r5, [r4]
+ ldr r4, =caml_gc_regs
+ ldr r5, [sp, 8]
+ str r5, [r4]
+ add sp, sp, 16; CFI_ADJUST(-16)
+ /* Update allocation pointer */
+ ldr r4, =caml_young_ptr
+ str alloc_ptr, [r4]
+ /* Reload callee-save registers and return address */
+ pop {r4-r8,r10,r11,lr}; CFI_ADJUST(-32)
+#if defined(SYS_linux_eabihf)
+ /* Reload callee-save floating-point registers */
+ vpop {d8-d15}; CFI_ADJUST(-64)
+#endif
+ bx lr
+ CFI_ENDPROC
+ .type .Lcaml_retaddr, %function
+ .size .Lcaml_retaddr, .-.Lcaml_retaddr
+ .type caml_start_program, %function
+ .size caml_start_program, .-caml_start_program
+
+/* The trap handler */
+
+ .align 2
+.Ltrap_handler:
+ CFI_STARTPROC
+ /* Save exception pointer */
+ ldr r12, =caml_exception_pointer
+ str trap_ptr, [r12]
+ /* Encode exception bucket as an exception result */
+ orr r0, r0, 2
+ /* Return it */
+ b .Lreturn_result
+ CFI_ENDPROC
+ .type .Ltrap_handler, %function
+ .size .Ltrap_handler, .-.Ltrap_handler
+
+/* Raise an exception from OCaml */
+
+ .align 2
+ .globl caml_raise_exn
+caml_raise_exn:
+ CFI_STARTPROC
+ PROFILE
+ /* Test if backtrace is active */
+ ldr r1, =caml_backtrace_active
+ ldr r1, [r1]
+ cbz r1, 1f
+ /* Preserve exception bucket in callee-save register r4 */
+ mov r4, r0
+ /* Stash the backtrace */
+ mov r1, lr /* arg2: pc of raise */
+ mov r2, sp /* arg3: sp of raise */
+ mov r3, trap_ptr /* arg4: sp of handler */
+ bl caml_stash_backtrace
+ /* Restore exception bucket */
+ mov r0, r4
+1: /* Cut stack at current trap handler */
+ mov sp, trap_ptr
+ /* Pop previous handler and addr of trap, and jump to it */
+ pop {trap_ptr, pc}
+ CFI_ENDPROC
+ .type caml_raise_exn, %function
+ .size caml_raise_exn, .-caml_raise_exn
+
+/* Raise an exception from C */
+
+ .align 2
+ .globl caml_raise_exception
+caml_raise_exception:
+ CFI_STARTPROC
+ PROFILE
+ /* Reload trap ptr, alloc ptr and alloc limit */
+ ldr trap_ptr, =caml_exception_pointer
+ ldr alloc_ptr, =caml_young_ptr
+ ldr alloc_limit, =caml_young_limit
+ ldr trap_ptr, [trap_ptr]
+ ldr alloc_ptr, [alloc_ptr]
+ ldr alloc_limit, [alloc_limit]
+ /* Test if backtrace is active */
+ ldr r1, =caml_backtrace_active
+ ldr r1, [r1]
+ cbz r1, 1f
+ /* Preserve exception bucket in callee-save register r4 */
+ mov r4, r0
+ ldr r1, =caml_last_return_address /* arg2: pc of raise */
+ ldr r1, [r1]
+ ldr r2, =caml_bottom_of_stack /* arg3: sp of raise */
+ ldr r2, [r2]
+ mov r3, trap_ptr /* arg4: sp of handler */
+ bl caml_stash_backtrace
+ /* Restore exception bucket */
+ mov r0, r4
+1: /* Cut stack at current trap handler */
+ mov sp, trap_ptr
+ /* Pop previous handler and addr of trap, and jump to it */
+ pop {trap_ptr, pc}
+ CFI_ENDPROC
+ .type caml_raise_exception, %function
+ .size caml_raise_exception, .-caml_raise_exception
+
+/* Callback from C to OCaml */
+
+ .align 2
+ .globl caml_callback_exn
+caml_callback_exn:
+ CFI_STARTPROC
+ PROFILE
+ /* Initial shuffling of arguments (r0 = closure, r1 = first arg) */
+ mov r12, r0
+ mov r0, r1 /* r0 = first arg */
+ mov r1, r12 /* r1 = closure environment */
+ ldr r12, [r12] /* code pointer */
+ b .Ljump_to_caml
+ CFI_ENDPROC
+ .type caml_callback_exn, %function
+ .size caml_callback_exn, .-caml_callback_exn
+
+ .align 2
+ .globl caml_callback2_exn
+caml_callback2_exn:
+ CFI_STARTPROC
+ PROFILE
+ /* Initial shuffling of arguments (r0 = closure, r1 = arg1, r2 = arg2) */
+ mov r12, r0
+ mov r0, r1 /* r0 = first arg */
+ mov r1, r2 /* r1 = second arg */
+ mov r2, r12 /* r2 = closure environment */
+ ldr r12, =caml_apply2
+ b .Ljump_to_caml
+ CFI_ENDPROC
+ .type caml_callback2_exn, %function
+ .size caml_callback2_exn, .-caml_callback2_exn
+
+ .align 2
+ .globl caml_callback3_exn
+caml_callback3_exn:
+ CFI_STARTPROC
+ PROFILE
+ /* Initial shuffling of arguments */
+ /* (r0 = closure, r1 = arg1, r2 = arg2, r3 = arg3) */
+ mov r12, r0
+ mov r0, r1 /* r0 = first arg */
+ mov r1, r2 /* r1 = second arg */
+ mov r2, r3 /* r2 = third arg */
+ mov r3, r12 /* r3 = closure environment */
+ ldr r12, =caml_apply3
+ b .Ljump_to_caml
+ CFI_ENDPROC
+ .type caml_callback3_exn, %function
+ .size caml_callback3_exn, .-caml_callback3_exn
+
+ .align 2
+ .globl caml_ml_array_bound_error
+caml_ml_array_bound_error:
+ CFI_STARTPROC
+ PROFILE
+ /* Load address of [caml_array_bound_error] in r7 */
+ ldr r7, =caml_array_bound_error
+ /* Call that function */
+ b caml_c_call
+ CFI_ENDPROC
+ .type caml_ml_array_bound_error, %function
+ .size caml_ml_array_bound_error, .-caml_ml_array_bound_error
+
+ .globl caml_system__code_end
+caml_system__code_end:
+
+/* GC roots for callback */
+
+ .data
+ .align 2
+ .globl caml_system__frametable
+caml_system__frametable:
+ .word 1 /* one descriptor */
+ .word .Lcaml_retaddr /* return address into callback */
+ .short -1 /* negative frame size => use callback link */
+ .short 0 /* no roots */
+ .align 2
+ .type caml_system__frametable, %object
+ .size caml_system__frametable, .-caml_system__frametable
diff --git a/asmrun/arm64.S b/asmrun/arm64.S
new file mode 100644
index 0000000000..7969eb629e
--- /dev/null
+++ b/asmrun/arm64.S
@@ -0,0 +1,555 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2013 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Asm part of the runtime system, ARM processor, 64-bit mode */
+/* Must be preprocessed by cpp */
+
+/* Special registers */
+
+#define TRAP_PTR x26
+#define ALLOC_PTR x27
+#define ALLOC_LIMIT x28
+#define ARG x15
+#define TMP x16
+#define TMP2 x17
+
+/* Support for CFI directives */
+
+#if defined(ASM_CFI_SUPPORTED)
+#define CFI_STARTPROC .cfi_startproc
+#define CFI_ENDPROC .cfi_endproc
+#define CFI_ADJUST(n) .cfi_adjust_cfa_offset n
+#else
+#define CFI_STARTPROC
+#define CFI_ENDPROC
+#define CFI_ADJUST(n)
+#endif
+
+/* Support for profiling with gprof */
+
+#define PROFILE
+
+/* Macros to load and store global variables. Destroy TMP2 */
+
+#if defined(__PIC__)
+
+#define ADDRGLOBAL(reg,symb) \
+ adrp TMP2, :got:symb; \
+ ldr reg, [TMP2, #:got_lo12:symb]
+
+#define LOADGLOBAL(reg,symb) \
+ ADDRGLOBAL(TMP2,symb); \
+ ldr reg, [TMP2]
+
+#define STOREGLOBAL(reg,symb) \
+ ADDRGLOBAL(TMP2,symb); \
+ str reg, [TMP2]
+
+#else
+
+#define ADDRGLOBAL(reg,symb) \
+ adrp reg, symb; \
+ add reg, reg, #:lo12:symb
+
+#define LOADGLOBAL(reg,symb) \
+ adrp TMP2, symb; \
+ ldr reg, [TMP2, #:lo12:symb]
+
+#define STOREGLOBAL(reg,symb) \
+ adrp TMP2, symb; \
+ str reg, [TMP2, #:lo12:symb]
+
+#endif
+
+/* Allocation functions and GC interface */
+
+ .globl caml_system__code_begin
+caml_system__code_begin:
+
+ .align 2
+ .globl caml_call_gc
+caml_call_gc:
+ CFI_STARTPROC
+ PROFILE
+ /* Record return address */
+ STOREGLOBAL(x30, caml_last_return_address)
+ /* Record lowest stack address */
+ mov TMP, sp
+ STOREGLOBAL(TMP, caml_bottom_of_stack)
+.Lcaml_call_gc:
+ /* Set up stack space, saving return address and frame pointer */
+ /* (2 regs RA/GP, 24 allocatable int regs, 24 caller-save float regs) * 8 */
+ stp x29, x30, [sp, -400]!
+ CFI_ADJUST(400)
+ add x29, sp, #0
+ /* Save allocatable integer registers on the stack, in the order
+ given in proc.ml */
+ stp x0, x1, [sp, 16]
+ stp x2, x3, [sp, 32]
+ stp x4, x5, [sp, 48]
+ stp x6, x7, [sp, 64]
+ stp x8, x9, [sp, 80]
+ stp x10, x11, [sp, 96]
+ stp x12, x13, [sp, 112]
+ stp x14, x15, [sp, 128]
+ stp x19, x20, [sp, 144]
+ stp x21, x22, [sp, 160]
+ stp x23, x24, [sp, 176]
+ str x25, [sp, 192]
+ /* Save caller-save floating-point registers on the stack
+ (callee-saves are preserved by caml_garbage_collection) */
+ stp d0, d1, [sp, 208]
+ stp d2, d3, [sp, 224]
+ stp d4, d5, [sp, 240]
+ stp d6, d7, [sp, 256]
+ stp d16, d17, [sp, 272]
+ stp d18, d19, [sp, 288]
+ stp d20, d21, [sp, 304]
+ stp d22, d23, [sp, 320]
+ stp d24, d25, [sp, 336]
+ stp d26, d27, [sp, 352]
+ stp d28, d29, [sp, 368]
+ stp d30, d31, [sp, 384]
+ /* Store pointer to saved integer registers in caml_gc_regs */
+ add TMP, sp, #16
+ STOREGLOBAL(TMP, caml_gc_regs)
+ /* Save current allocation pointer for debugging purposes */
+ STOREGLOBAL(ALLOC_PTR, caml_young_ptr)
+ /* Save trap pointer in case an exception is raised during GC */
+ STOREGLOBAL(TRAP_PTR, caml_exception_pointer)
+ /* Call the garbage collector */
+ bl caml_garbage_collection
+ /* Restore registers */
+ ldp x0, x1, [sp, 16]
+ ldp x2, x3, [sp, 32]
+ ldp x4, x5, [sp, 48]
+ ldp x6, x7, [sp, 64]
+ ldp x8, x9, [sp, 80]
+ ldp x10, x11, [sp, 96]
+ ldp x12, x13, [sp, 112]
+ ldp x14, x15, [sp, 128]
+ ldp x19, x20, [sp, 144]
+ ldp x21, x22, [sp, 160]
+ ldp x23, x24, [sp, 176]
+ ldr x25, [sp, 192]
+ ldp d0, d1, [sp, 208]
+ ldp d2, d3, [sp, 224]
+ ldp d4, d5, [sp, 240]
+ ldp d6, d7, [sp, 256]
+ ldp d16, d17, [sp, 272]
+ ldp d18, d19, [sp, 288]
+ ldp d20, d21, [sp, 304]
+ ldp d22, d23, [sp, 320]
+ ldp d24, d25, [sp, 336]
+ ldp d26, d27, [sp, 352]
+ ldp d28, d29, [sp, 368]
+ ldp d30, d31, [sp, 384]
+ /* Reload new allocation pointer and allocation limit */
+ LOADGLOBAL(ALLOC_PTR, caml_young_ptr)
+ LOADGLOBAL(ALLOC_LIMIT, caml_young_limit)
+ /* Free stack space and return to caller */
+ ldp x29, x30, [sp], 400
+ ret
+ CFI_ENDPROC
+ .type caml_call_gc, %function
+ .size caml_call_gc, .-caml_call_gc
+
+ .align 2
+ .globl caml_alloc1
+caml_alloc1:
+ CFI_STARTPROC
+ PROFILE
+1: sub ALLOC_PTR, ALLOC_PTR, #16
+ cmp ALLOC_PTR, ALLOC_LIMIT
+ b.lo 2f
+ ret
+2: stp x29, x30, [sp, -16]!
+ CFI_ADJUST(16)
+ /* Record the lowest address of the caller's stack frame. This is the
+ address immediately above the pair of words (x29 and x30) we just
+ pushed. Those must not be included since otherwise the distance from
+ [caml_bottom_of_stack] to the highest address in the caller's stack
+ frame won't match the frame size contained in the relevant frame
+ descriptor. */
+ add x29, sp, #16
+ STOREGLOBAL(x29, caml_bottom_of_stack)
+ add x29, sp, #0
+ /* Record return address */
+ STOREGLOBAL(x30, caml_last_return_address)
+ /* Call GC */
+ bl .Lcaml_call_gc
+ /* Restore return address */
+ ldp x29, x30, [sp], 16
+ CFI_ADJUST(-16)
+ /* Try again */
+ b 1b
+ CFI_ENDPROC
+ .type caml_alloc1, %function
+ .size caml_alloc1, .-caml_alloc1
+
+ .align 2
+ .globl caml_alloc2
+caml_alloc2:
+ CFI_STARTPROC
+ PROFILE
+1: sub ALLOC_PTR, ALLOC_PTR, #24
+ cmp ALLOC_PTR, ALLOC_LIMIT
+ b.lo 2f
+ ret
+2: stp x29, x30, [sp, -16]!
+ CFI_ADJUST(16)
+ /* Record the lowest address of the caller's stack frame.
+ See comment above. */
+ add x29, sp, #16
+ STOREGLOBAL(x29, caml_bottom_of_stack)
+ add x29, sp, #0
+ /* Record return address */
+ STOREGLOBAL(x30, caml_last_return_address)
+ /* Call GC */
+ bl .Lcaml_call_gc
+ /* Restore return address */
+ ldp x29, x30, [sp], 16
+ CFI_ADJUST(-16)
+ /* Try again */
+ b 1b
+ CFI_ENDPROC
+ .type caml_alloc2, %function
+ .size caml_alloc2, .-caml_alloc2
+
+ .align 2
+ .globl caml_alloc3
+caml_alloc3:
+ CFI_STARTPROC
+ PROFILE
+1: sub ALLOC_PTR, ALLOC_PTR, #32
+ cmp ALLOC_PTR, ALLOC_LIMIT
+ b.lo 2f
+ ret
+2: stp x29, x30, [sp, -16]!
+ CFI_ADJUST(16)
+ /* Record the lowest address of the caller's stack frame.
+ See comment above. */
+ add x29, sp, #16
+ STOREGLOBAL(x29, caml_bottom_of_stack)
+ add x29, sp, #0
+ /* Record return address */
+ STOREGLOBAL(x30, caml_last_return_address)
+ /* Call GC */
+ bl .Lcaml_call_gc
+ /* Restore return address */
+ ldp x29, x30, [sp], 16
+ CFI_ADJUST(-16)
+ /* Try again */
+ b 1b
+ CFI_ENDPROC
+ .type caml_alloc2, %function
+ .size caml_alloc2, .-caml_alloc2
+
+ .align 2
+ .globl caml_allocN
+caml_allocN:
+ CFI_STARTPROC
+ PROFILE
+1: sub ALLOC_PTR, ALLOC_PTR, ARG
+ cmp ALLOC_PTR, ALLOC_LIMIT
+ b.lo 2f
+ ret
+2: stp x29, x30, [sp, -16]!
+ CFI_ADJUST(16)
+ /* Record the lowest address of the caller's stack frame.
+ See comment above. */
+ add x29, sp, #16
+ STOREGLOBAL(x29, caml_bottom_of_stack)
+ add x29, sp, #0
+ /* Record return address */
+ STOREGLOBAL(x30, caml_last_return_address)
+ /* Call GC. This preserves ARG */
+ bl .Lcaml_call_gc
+ /* Restore return address */
+ ldp x29, x30, [sp], 16
+ CFI_ADJUST(-16)
+ /* Try again */
+ b 1b
+ CFI_ENDPROC
+ .type caml_allocN, %function
+ .size caml_allocN, .-caml_allocN
+
+/* Call a C function from OCaml */
+/* Function to call is in ARG */
+
+ .align 2
+ .globl caml_c_call
+caml_c_call:
+ CFI_STARTPROC
+ PROFILE
+ /* Preserve return address in callee-save register x19 */
+ mov x19, x30
+ /* Record lowest stack address and return address */
+ STOREGLOBAL(x30, caml_last_return_address)
+ add TMP, sp, #0
+ STOREGLOBAL(TMP, caml_bottom_of_stack)
+ /* Make the exception handler alloc ptr available to the C code */
+ STOREGLOBAL(ALLOC_PTR, caml_young_ptr)
+ STOREGLOBAL(TRAP_PTR, caml_exception_pointer)
+ /* Call the function */
+ blr ARG
+ /* Reload alloc ptr and alloc limit */
+ LOADGLOBAL(ALLOC_PTR, caml_young_ptr)
+ LOADGLOBAL(ALLOC_LIMIT, caml_young_limit)
+ /* Return */
+ ret x19
+ CFI_ENDPROC
+ .type caml_c_call, %function
+ .size caml_c_call, .-caml_c_call
+
+/* Start the OCaml program */
+
+ .align 2
+ .globl caml_start_program
+caml_start_program:
+ CFI_STARTPROC
+ PROFILE
+ ADDRGLOBAL(ARG, caml_program)
+
+/* Code shared with caml_callback* */
+/* Address of OCaml code to call is in ARG */
+/* Arguments to the OCaml code are in x0...x7 */
+
+.Ljump_to_caml:
+ /* Set up stack frame and save callee-save registers */
+ stp x29, x30, [sp, -160]!
+ CFI_ADJUST(160)
+ add x29, sp, #0
+ stp x19, x20, [sp, 16]
+ stp x21, x22, [sp, 32]
+ stp x23, x24, [sp, 48]
+ stp x25, x26, [sp, 64]
+ stp x27, x28, [sp, 80]
+ stp d8, d9, [sp, 96]
+ stp d10, d11, [sp, 112]
+ stp d12, d13, [sp, 128]
+ stp d14, d15, [sp, 144]
+ /* Setup a callback link on the stack */
+ LOADGLOBAL(x8, caml_bottom_of_stack)
+ LOADGLOBAL(x9, caml_last_return_address)
+ LOADGLOBAL(x10, caml_gc_regs)
+ stp x8, x9, [sp, -32]! /* 16-byte alignment */
+ CFI_ADJUST(32)
+ str x10, [sp, 16]
+ /* Setup a trap frame to catch exceptions escaping the OCaml code */
+ LOADGLOBAL(x8, caml_exception_pointer)
+ adr x9, .Ltrap_handler
+ stp x8, x9, [sp, -16]!
+ CFI_ADJUST(16)
+ add TRAP_PTR, sp, #0
+ /* Reload allocation pointers */
+ LOADGLOBAL(ALLOC_PTR, caml_young_ptr)
+ LOADGLOBAL(ALLOC_LIMIT, caml_young_limit)
+ /* Call the OCaml code */
+ blr ARG
+.Lcaml_retaddr:
+ /* Pop the trap frame, restoring caml_exception_pointer */
+ ldr x8, [sp], 16
+ CFI_ADJUST(-16)
+ STOREGLOBAL(x8, caml_exception_pointer)
+ /* Pop the callback link, restoring the global variables */
+.Lreturn_result:
+ ldr x10, [sp, 16]
+ ldp x8, x9, [sp], 32
+ CFI_ADJUST(-32)
+ STOREGLOBAL(x8, caml_bottom_of_stack)
+ STOREGLOBAL(x9, caml_last_return_address)
+ STOREGLOBAL(x10, caml_gc_regs)
+ /* Update allocation pointer */
+ STOREGLOBAL(ALLOC_PTR, caml_young_ptr)
+ /* Reload callee-save registers and return address */
+ ldp x19, x20, [sp, 16]
+ ldp x21, x22, [sp, 32]
+ ldp x23, x24, [sp, 48]
+ ldp x25, x26, [sp, 64]
+ ldp x27, x28, [sp, 80]
+ ldp d8, d9, [sp, 96]
+ ldp d10, d11, [sp, 112]
+ ldp d12, d13, [sp, 128]
+ ldp d14, d15, [sp, 144]
+ ldp x29, x30, [sp], 160
+ CFI_ADJUST(-160)
+ /* Return to C caller */
+ ret
+ CFI_ENDPROC
+ .type .Lcaml_retaddr, %function
+ .size .Lcaml_retaddr, .-.Lcaml_retaddr
+ .type caml_start_program, %function
+ .size caml_start_program, .-caml_start_program
+
+/* The trap handler */
+
+ .align 2
+.Ltrap_handler:
+ CFI_STARTPROC
+ /* Save exception pointer */
+ STOREGLOBAL(TRAP_PTR, caml_exception_pointer)
+ /* Encode exception bucket as an exception result */
+ orr x0, x0, #2
+ /* Return it */
+ b .Lreturn_result
+ CFI_ENDPROC
+ .type .Ltrap_handler, %function
+ .size .Ltrap_handler, .-.Ltrap_handler
+
+/* Raise an exception from OCaml */
+
+ .align 2
+ .globl caml_raise_exn
+caml_raise_exn:
+ CFI_STARTPROC
+ PROFILE
+ /* Test if backtrace is active */
+ LOADGLOBAL(TMP, caml_backtrace_active)
+ cbnz TMP, 2f
+1: /* Cut stack at current trap handler */
+ mov sp, TRAP_PTR
+ /* Pop previous handler and jump to it */
+ ldr TMP, [sp, 8]
+ ldr TRAP_PTR, [sp], 16
+ br TMP
+2: /* Preserve exception bucket in callee-save register x19 */
+ mov x19, x0
+ /* Stash the backtrace */
+ /* arg1: exn bucket, already in x0 */
+ mov x1, x30 /* arg2: pc of raise */
+ add x2, sp, #0 /* arg3: sp of raise */
+ mov x3, TRAP_PTR /* arg4: sp of handler */
+ bl caml_stash_backtrace
+ /* Restore exception bucket and raise */
+ mov x0, x19
+ b 1b
+ CFI_ENDPROC
+ .type caml_raise_exn, %function
+ .size caml_raise_exn, .-caml_raise_exn
+
+/* Raise an exception from C */
+
+ .align 2
+ .globl caml_raise_exception
+caml_raise_exception:
+ CFI_STARTPROC
+ PROFILE
+ /* Reload trap ptr, alloc ptr and alloc limit */
+ LOADGLOBAL(TRAP_PTR, caml_exception_pointer)
+ LOADGLOBAL(ALLOC_PTR, caml_young_ptr)
+ LOADGLOBAL(ALLOC_LIMIT, caml_young_limit)
+ /* Test if backtrace is active */
+ LOADGLOBAL(TMP, caml_backtrace_active)
+ cbnz TMP, 2f
+1: /* Cut stack at current trap handler */
+ mov sp, TRAP_PTR
+ /* Pop previous handler and jump to it */
+ ldr TMP, [sp, 8]
+ ldr TRAP_PTR, [sp], 16
+ br TMP
+2: /* Preserve exception bucket in callee-save register x19 */
+ mov x19, x0
+ /* Stash the backtrace */
+ /* arg1: exn bucket, already in x0 */
+ LOADGLOBAL(x1, caml_last_return_address) /* arg2: pc of raise */
+ LOADGLOBAL(x2, caml_bottom_of_stack) /* arg3: sp of raise */
+ mov x3, TRAP_PTR /* arg4: sp of handler */
+ bl caml_stash_backtrace
+ /* Restore exception bucket and raise */
+ mov x0, x19
+ b 1b
+ CFI_ENDPROC
+ .type caml_raise_exception, %function
+ .size caml_raise_exception, .-caml_raise_exception
+
+/* Callback from C to OCaml */
+
+ .align 2
+ .globl caml_callback_exn
+caml_callback_exn:
+ CFI_STARTPROC
+ PROFILE
+ /* Initial shuffling of arguments (x0 = closure, x1 = first arg) */
+ mov TMP, x0
+ mov x0, x1 /* x0 = first arg */
+ mov x1, TMP /* x1 = closure environment */
+ ldr ARG, [TMP] /* code pointer */
+ b .Ljump_to_caml
+ CFI_ENDPROC
+ .type caml_callback_exn, %function
+ .size caml_callback_exn, .-caml_callback_exn
+
+ .align 2
+ .globl caml_callback2_exn
+caml_callback2_exn:
+ CFI_STARTPROC
+ PROFILE
+ /* Initial shuffling of arguments (x0 = closure, x1 = arg1, x2 = arg2) */
+ mov TMP, x0
+ mov x0, x1 /* x0 = first arg */
+ mov x1, x2 /* x1 = second arg */
+ mov x2, TMP /* x2 = closure environment */
+ ADDRGLOBAL(ARG, caml_apply2)
+ b .Ljump_to_caml
+ CFI_ENDPROC
+ .type caml_callback2_exn, %function
+ .size caml_callback2_exn, .-caml_callback2_exn
+
+ .align 2
+ .globl caml_callback3_exn
+caml_callback3_exn:
+ CFI_STARTPROC
+ PROFILE
+ /* Initial shuffling of arguments */
+ /* (x0 = closure, x1 = arg1, x2 = arg2, x3 = arg3) */
+ mov TMP, x0
+ mov x0, x1 /* x0 = first arg */
+ mov x1, x2 /* x1 = second arg */
+ mov x2, x3 /* x2 = third arg */
+ mov x3, TMP /* x3 = closure environment */
+ ADDRGLOBAL(ARG, caml_apply3)
+ b .Ljump_to_caml
+ CFI_ENDPROC
+ .type caml_callback3_exn, %function
+ .size caml_callback3_exn, .-caml_callback3_exn
+
+ .align 2
+ .globl caml_ml_array_bound_error
+caml_ml_array_bound_error:
+ CFI_STARTPROC
+ PROFILE
+ /* Load address of [caml_array_bound_error] in ARG */
+ ADDRGLOBAL(ARG, caml_array_bound_error)
+ /* Call that function */
+ b caml_c_call
+ CFI_ENDPROC
+ .type caml_ml_array_bound_error, %function
+ .size caml_ml_array_bound_error, .-caml_ml_array_bound_error
+
+ .globl caml_system__code_end
+caml_system__code_end:
+
+/* GC roots for callback */
+
+ .data
+ .align 3
+ .globl caml_system__frametable
+caml_system__frametable:
+ .quad 1 /* one descriptor */
+ .quad .Lcaml_retaddr /* return address into callback */
+ .short -1 /* negative frame size => use callback link */
+ .short 0 /* no roots */
+ .align 3
+ .type caml_system__frametable, %object
+ .size caml_system__frametable, .-caml_system__frametable
diff --git a/asmrun/backtrace_prim.c b/asmrun/backtrace_prim.c
new file mode 100644
index 0000000000..1bc8a62e3c
--- /dev/null
+++ b/asmrun/backtrace_prim.c
@@ -0,0 +1,230 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2006 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Stack backtrace for uncaught exceptions */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "caml/alloc.h"
+#include "caml/backtrace.h"
+#include "caml/backtrace_prim.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "stack.h"
+
+/* In order to prevent the GC from walking through the debug information
+ (which have no headers), we transform frame_descr pointers into
+ 31/63 bits ocaml integers by shifting them by 1 to the right. We do
+ not lose information as descr pointers are aligned. */
+value caml_val_raw_backtrace_slot(backtrace_slot pc)
+{
+ return Val_long((uintnat)pc>>1);
+}
+
+backtrace_slot caml_raw_backtrace_slot_val(value v)
+{
+ return ((backtrace_slot)(Long_val(v)<<1));
+}
+
+/* Returns the next frame descriptor (or NULL if none is available),
+ and updates *pc and *sp to point to the following one. */
+frame_descr * caml_next_frame_descriptor(uintnat * pc, char ** sp)
+{
+ frame_descr * d;
+ uintnat h;
+
+ while (1) {
+ h = Hash_retaddr(*pc);
+ while (1) {
+ d = caml_frame_descriptors[h];
+ if (d == NULL) return NULL; /* happens if some code compiled without -g */
+ if (d->retaddr == *pc) break;
+ h = (h+1) & caml_frame_descriptors_mask;
+ }
+ /* Skip to next frame */
+ if (d->frame_size != 0xFFFF) {
+ /* Regular frame, update sp/pc and return the frame descriptor */
+#ifndef Stack_grows_upwards
+ *sp += (d->frame_size & 0xFFFC);
+#else
+ *sp -= (d->frame_size & 0xFFFC);
+#endif
+ *pc = Saved_return_address(*sp);
+#ifdef Mask_already_scanned
+ *pc = Mask_already_scanned(*pc);
+#endif
+ return d;
+ } else {
+ /* Special frame marking the top of a stack chunk for an ML callback.
+ Skip C portion of stack and continue with next ML stack chunk. */
+ struct caml_context * next_context = Callback_link(*sp);
+ *sp = next_context->bottom_of_stack;
+ *pc = next_context->last_retaddr;
+ /* A null sp means no more ML stack chunks; stop here. */
+ if (*sp == NULL) return NULL;
+ }
+ }
+}
+
+/* Stores the return addresses contained in the given stack fragment
+ into the backtrace array ; this version is performance-sensitive as
+ it is called at each [raise] in a program compiled with [-g], so we
+ preserved the global, statically bounded buffer of the old
+ implementation -- before the more flexible
+ [caml_get_current_callstack] was implemented. */
+void caml_stash_backtrace(value exn, uintnat pc, char * sp, char * trapsp)
+{
+ if (exn != caml_backtrace_last_exn) {
+ caml_backtrace_pos = 0;
+ caml_backtrace_last_exn = exn;
+ }
+ if (caml_backtrace_buffer == NULL) {
+ Assert(caml_backtrace_pos == 0);
+ caml_backtrace_buffer = malloc(BACKTRACE_BUFFER_SIZE
+ * sizeof(backtrace_slot));
+ if (caml_backtrace_buffer == NULL) return;
+ }
+
+ /* iterate on each frame */
+ while (1) {
+ frame_descr * descr = caml_next_frame_descriptor(&pc, &sp);
+ if (descr == NULL) return;
+ /* store its descriptor in the backtrace buffer */
+ if (caml_backtrace_pos >= BACKTRACE_BUFFER_SIZE) return;
+ caml_backtrace_buffer[caml_backtrace_pos++] = (backtrace_slot) descr;
+
+ /* Stop when we reach the current exception handler */
+#ifndef Stack_grows_upwards
+ if (sp > trapsp) return;
+#else
+ if (sp < trapsp) return;
+#endif
+ }
+}
+
+/* Stores upto [max_frames_value] frames of the current call stack to
+ return to the user. This is used not in an exception-raising
+ context, but only when the user requests to save the trace
+ (hopefully less often). Instead of using a bounded buffer as
+ [caml_stash_backtrace], we first traverse the stack to compute the
+ right size, then allocate space for the trace. */
+CAMLprim value caml_get_current_callstack(value max_frames_value)
+{
+ CAMLparam1(max_frames_value);
+ CAMLlocal1(trace);
+
+ /* we use `intnat` here because, were it only `int`, passing `max_int`
+ from the OCaml side would overflow on 64bits machines. */
+ intnat max_frames = Long_val(max_frames_value);
+ intnat trace_size;
+
+ /* first compute the size of the trace */
+ {
+ uintnat pc = caml_last_return_address;
+ /* note that [caml_bottom_of_stack] always points to the most recent
+ * frame, independently of the [Stack_grows_upwards] setting */
+ char * sp = caml_bottom_of_stack;
+ char * limitsp = caml_top_of_stack;
+
+ trace_size = 0;
+ while (1) {
+ frame_descr * descr = caml_next_frame_descriptor(&pc, &sp);
+ if (descr == NULL) break;
+ if (trace_size >= max_frames) break;
+ ++trace_size;
+
+#ifndef Stack_grows_upwards
+ if (sp > limitsp) break;
+#else
+ if (sp < limitsp) break;
+#endif
+ }
+ }
+
+ trace = caml_alloc((mlsize_t) trace_size, 0);
+
+ /* then collect the trace */
+ {
+ uintnat pc = caml_last_return_address;
+ char * sp = caml_bottom_of_stack;
+ intnat trace_pos;
+
+ for (trace_pos = 0; trace_pos < trace_size; trace_pos++) {
+ frame_descr * descr = caml_next_frame_descriptor(&pc, &sp);
+ Assert(descr != NULL);
+ Store_field(trace, trace_pos,
+ caml_val_raw_backtrace_slot((backtrace_slot) descr));
+ }
+ }
+
+ CAMLreturn(trace);
+}
+
+/* Extract location information for the given frame descriptor */
+void caml_extract_location_info(backtrace_slot slot,
+ /*out*/ struct caml_loc_info * li)
+{
+ uintnat infoptr;
+ uint32_t info1, info2;
+ frame_descr * d = (frame_descr *)slot;
+
+ /* If no debugging information available, print nothing.
+ When everything is compiled with -g, this corresponds to
+ compiler-inserted re-raise operations. */
+ if ((d->frame_size & 1) == 0) {
+ li->loc_valid = 0;
+ li->loc_is_raise = 1;
+ return;
+ }
+ /* Recover debugging info */
+ infoptr = ((uintnat) d +
+ sizeof(char *) + sizeof(short) + sizeof(short) +
+ sizeof(short) * d->num_live + sizeof(frame_descr *) - 1)
+ & -sizeof(frame_descr *);
+ info1 = ((uint32_t *)infoptr)[0];
+ info2 = ((uint32_t *)infoptr)[1];
+ /* Format of the two info words:
+ llllllllllllllllllll aaaaaaaa bbbbbbbbbb nnnnnnnnnnnnnnnnnnnnnnnn kk
+ 44 36 26 2 0
+ (32+12) (32+4)
+ k ( 2 bits): 0 if it's a call, 1 if it's a raise
+ n (24 bits): offset (in 4-byte words) of file name relative to infoptr
+ l (20 bits): line number
+ a ( 8 bits): beginning of character range
+ b (10 bits): end of character range */
+ li->loc_valid = 1;
+ li->loc_is_raise = (info1 & 3) != 0;
+ li->loc_filename = (char *) infoptr + (info1 & 0x3FFFFFC);
+ li->loc_lnum = info2 >> 12;
+ li->loc_startchr = (info2 >> 4) & 0xFF;
+ li->loc_endchr = ((info2 & 0xF) << 6) | (info1 >> 26);
+}
+
+CAMLprim value caml_add_debug_info(backtrace_slot start, value size,
+ value events)
+{
+ return Val_unit;
+}
+
+CAMLprim value caml_remove_debug_info(backtrace_slot start)
+{
+ return Val_unit;
+}
+
+int caml_debug_info_available(void)
+{
+ return 1;
+}
diff --git a/asmrun/fail.c b/asmrun/fail.c
new file mode 100644
index 0000000000..188651cea9
--- /dev/null
+++ b/asmrun/fail.c
@@ -0,0 +1,184 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Raising exceptions from C. */
+
+#include <stdio.h>
+#include <signal.h>
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/io.h"
+#include "caml/gc.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+#include "caml/printexc.h"
+#include "caml/signals.h"
+#include "stack.h"
+#include "caml/roots.h"
+#include "caml/callback.h"
+
+/* The globals holding predefined exceptions */
+
+typedef value caml_generated_constant[1];
+
+extern caml_generated_constant
+ caml_exn_Out_of_memory,
+ caml_exn_Sys_error,
+ caml_exn_Failure,
+ caml_exn_Invalid_argument,
+ caml_exn_End_of_file,
+ caml_exn_Division_by_zero,
+ caml_exn_Not_found,
+ caml_exn_Match_failure,
+ caml_exn_Sys_blocked_io,
+ caml_exn_Stack_overflow,
+ caml_exn_Assert_failure,
+ caml_exn_Undefined_recursive_module;
+
+/* Exception raising */
+
+CAMLnoreturn_start
+ extern void caml_raise_exception (value bucket)
+CAMLnoreturn_end;
+
+char * caml_exception_pointer = NULL;
+
+void caml_raise(value v)
+{
+ Unlock_exn();
+ if (caml_exception_pointer == NULL) caml_fatal_uncaught_exception(v);
+
+#ifndef Stack_grows_upwards
+#define PUSHED_AFTER <
+#else
+#define PUSHED_AFTER >
+#endif
+ while (caml_local_roots != NULL &&
+ (char *) caml_local_roots PUSHED_AFTER caml_exception_pointer) {
+ caml_local_roots = caml_local_roots->next;
+ }
+#undef PUSHED_AFTER
+
+ caml_raise_exception(v);
+}
+
+void caml_raise_constant(value tag)
+{
+ caml_raise(tag);
+}
+
+void caml_raise_with_arg(value tag, value arg)
+{
+ CAMLparam2 (tag, arg);
+ CAMLlocal1 (bucket);
+
+ bucket = caml_alloc_small (2, 0);
+ Field(bucket, 0) = tag;
+ Field(bucket, 1) = arg;
+ caml_raise(bucket);
+ CAMLnoreturn;
+}
+
+void caml_raise_with_args(value tag, int nargs, value args[])
+{
+ CAMLparam1 (tag);
+ CAMLxparamN (args, nargs);
+ value bucket;
+ int i;
+
+ Assert(1 + nargs <= Max_young_wosize);
+ bucket = caml_alloc_small (1 + nargs, 0);
+ Field(bucket, 0) = tag;
+ for (i = 0; i < nargs; i++) Field(bucket, 1 + i) = args[i];
+ caml_raise(bucket);
+ CAMLnoreturn;
+}
+
+void caml_raise_with_string(value tag, char const *msg)
+{
+ CAMLparam1(tag);
+ value v_msg = caml_copy_string(msg);
+ caml_raise_with_arg(tag, v_msg);
+ CAMLnoreturn;
+}
+
+void caml_failwith (char const *msg)
+{
+ caml_raise_with_string((value) caml_exn_Failure, msg);
+}
+
+void caml_invalid_argument (char const *msg)
+{
+ caml_raise_with_string((value) caml_exn_Invalid_argument, msg);
+}
+
+void caml_raise_out_of_memory(void)
+{
+ caml_raise_constant((value) caml_exn_Out_of_memory);
+}
+
+void caml_raise_stack_overflow(void)
+{
+ caml_raise_constant((value) caml_exn_Stack_overflow);
+}
+
+void caml_raise_sys_error(value msg)
+{
+ caml_raise_with_arg((value) caml_exn_Sys_error, msg);
+}
+
+void caml_raise_end_of_file(void)
+{
+ caml_raise_constant((value) caml_exn_End_of_file);
+}
+
+void caml_raise_zero_divide(void)
+{
+ caml_raise_constant((value) caml_exn_Division_by_zero);
+}
+
+void caml_raise_not_found(void)
+{
+ caml_raise_constant((value) caml_exn_Not_found);
+}
+
+void caml_raise_sys_blocked_io(void)
+{
+ caml_raise_constant((value) caml_exn_Sys_blocked_io);
+}
+
+/* We use a pre-allocated exception because we can't
+ do a GC before the exception is raised (lack of stack descriptors
+ for the ccall to [caml_array_bound_error]). */
+
+static value * caml_array_bound_error_exn = NULL;
+
+void caml_array_bound_error(void)
+{
+ if (caml_array_bound_error_exn == NULL) {
+ caml_array_bound_error_exn =
+ caml_named_value("Pervasives.array_bound_error");
+ if (caml_array_bound_error_exn == NULL) {
+ fprintf(stderr, "Fatal error: exception "
+ "Invalid_argument(\"index out of bounds\")\n");
+ exit(2);
+ }
+ }
+ caml_raise(*caml_array_bound_error_exn);
+}
+
+int caml_is_special_exception(value exn) {
+ return exn == (value) caml_exn_Match_failure
+ || exn == (value) caml_exn_Assert_failure
+ || exn == (value) caml_exn_Undefined_recursive_module;
+}
diff --git a/asmrun/i386.S b/asmrun/i386.S
new file mode 100644
index 0000000000..2fdc6f8e72
--- /dev/null
+++ b/asmrun/i386.S
@@ -0,0 +1,498 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Asm part of the runtime system, Intel 386 processor */
+/* Must be preprocessed by cpp */
+
+#include "../config/m.h"
+
+/* Linux/BSD with ELF binaries and Solaris do not prefix identifiers with _.
+ Linux/BSD with a.out binaries and NextStep do. */
+
+#if (defined(SYS_solaris) && !defined(__GNUC__))
+#define CONCAT(a,b) a/**/b
+#else
+#define CONCAT(a,b) a##b
+#endif
+
+#if defined(SYS_linux_elf) || defined(SYS_bsd_elf) \
+ || defined(SYS_solaris) || defined(SYS_beos) || defined(SYS_gnu)
+#define G(x) x
+#define LBL(x) CONCAT(.L,x)
+#else
+#define G(x) CONCAT(_,x)
+#define LBL(x) CONCAT(L,x)
+#endif
+
+#if defined(SYS_linux_elf) || defined(SYS_bsd_elf) \
+ || defined(SYS_solaris) || defined(SYS_beos) || defined(SYS_cygwin) \
+ || defined(SYS_mingw) || defined(SYS_gnu)
+#define FUNCTION_ALIGN 4
+#else
+#define FUNCTION_ALIGN 2
+#endif
+
+#define FUNCTION(name) \
+ .globl G(name); \
+ .align FUNCTION_ALIGN; \
+ G(name):
+
+#ifdef ASM_CFI_SUPPORTED
+#define CFI_STARTPROC .cfi_startproc
+#define CFI_ENDPROC .cfi_endproc
+#define CFI_ADJUST(n) .cfi_adjust_cfa_offset n
+#else
+#define CFI_STARTPROC
+#define CFI_ENDPROC
+#define CFI_ADJUST(n)
+#endif
+
+#if defined(PROFILING)
+#if defined(SYS_linux_elf) || defined(SYS_gnu)
+#define PROFILE_CAML \
+ pushl %ebp; CFI_ADJUST(4); \
+ movl %esp, %ebp; \
+ pushl %eax; CFI_ADJUST(4); \
+ pushl %ecx; CFI_ADJUST(4); \
+ pushl %edx; CFI_ADJUST(4); \
+ call mcount; \
+ popl %edx; CFI_ADJUST(-4); \
+ popl %ecx; CFI_ADJUST(-4); \
+ popl %eax; CFI_ADJUST(-4); \
+ popl %ebp; CFI_ADJUST(-4)
+#define PROFILE_C \
+ pushl %ebp; CFI_ADJUST(4); \
+ movl %esp, %ebp; \
+ call mcount; \
+ popl %ebp; CFI_ADJUST(-4)
+#elif defined(SYS_bsd_elf)
+#define PROFILE_CAML \
+ pushl %ebp; CFI_ADJUST(4); \
+ movl %esp, %ebp; \
+ pushl %eax; CFI_ADJUST(4); \
+ pushl %ecx; CFI_ADJUST(4); \
+ pushl %edx; CFI_ADJUST(4); \
+ call .mcount; \
+ popl %edx; CFI_ADJUST(-4); \
+ popl %ecx; CFI_ADJUST(-4); \
+ popl %eax; CFI_ADJUST(-4); \
+ popl %ebp; CFI_ADJUST(-4)
+#define PROFILE_C \
+ pushl %ebp; CFI_ADJUST(4); \
+ movl %esp, %ebp; \
+ call .mcount; \
+ popl %ebp; CFI_ADJUST(-4)
+#elif defined(SYS_macosx)
+#define PROFILE_CAML \
+ pushl %ebp; CFI_ADJUST(4); \
+ movl %esp, %ebp; \
+ pushl %eax; CFI_ADJUST(4); \
+ pushl %ecx; CFI_ADJUST(4); \
+ pushl %edx; CFI_ADJUST(4); \
+ call Lmcount$stub; \
+ popl %edx; CFI_ADJUST(-4); \
+ popl %ecx; CFI_ADJUST(-4); \
+ popl %eax; CFI_ADJUST(-4); \
+ popl %ebp; CFI_ADJUST(-4)
+#define PROFILE_C \
+ pushl %ebp; CFI_ADJUST(4); \
+ movl %esp, %ebp; \
+ call Lmcount$stub; \
+ popl %ebp; CFI_ADJUST(-4)
+#endif
+#else
+#define PROFILE_CAML
+#define PROFILE_C
+#endif
+
+/* PR#6038: GCC and Clang seem to require 16-byte alignment nowadays,
+ even if only MacOS X's ABI formally requires it. */
+#define ALIGN_STACK(amount) subl $ amount, %esp ; CFI_ADJUST(amount)
+#define UNDO_ALIGN_STACK(amount) addl $ amount, %esp ; CFI_ADJUST(-amount)
+
+/* Allocation */
+
+ .text
+ .globl G(caml_system__code_begin)
+G(caml_system__code_begin):
+
+FUNCTION(caml_call_gc)
+ CFI_STARTPROC
+ PROFILE_CAML
+ /* Record lowest stack address and return address */
+ movl 0(%esp), %eax
+ movl %eax, G(caml_last_return_address)
+ leal 4(%esp), %eax
+ movl %eax, G(caml_bottom_of_stack)
+LBL(105):
+#if !defined(SYS_mingw) && !defined(SYS_cygwin)
+ /* Touch the stack to trigger a recoverable segfault
+ if insufficient space remains */
+ subl $16384, %esp
+ movl %eax, 0(%esp)
+ addl $16384, %esp
+#endif
+ /* Build array of registers, save it into caml_gc_regs */
+ pushl %ebp; CFI_ADJUST(4)
+ pushl %edi; CFI_ADJUST(4)
+ pushl %esi; CFI_ADJUST(4)
+ pushl %edx; CFI_ADJUST(4)
+ pushl %ecx; CFI_ADJUST(4)
+ pushl %ebx; CFI_ADJUST(4)
+ pushl %eax; CFI_ADJUST(4)
+ movl %esp, G(caml_gc_regs)
+ /* MacOSX note: 16-alignment of stack preserved at this point */
+ /* Call the garbage collector */
+ call G(caml_garbage_collection)
+ /* Restore all regs used by the code generator */
+ popl %eax; CFI_ADJUST(-4)
+ popl %ebx; CFI_ADJUST(-4)
+ popl %ecx; CFI_ADJUST(-4)
+ popl %edx; CFI_ADJUST(-4)
+ popl %esi; CFI_ADJUST(-4)
+ popl %edi; CFI_ADJUST(-4)
+ popl %ebp; CFI_ADJUST(-4)
+ /* Return to caller */
+ ret
+ CFI_ENDPROC
+
+FUNCTION(caml_alloc1)
+ CFI_STARTPROC
+ PROFILE_CAML
+ movl G(caml_young_ptr), %eax
+ subl $8, %eax
+ movl %eax, G(caml_young_ptr)
+ cmpl G(caml_young_limit), %eax
+ jb LBL(100)
+ ret
+LBL(100):
+ movl 0(%esp), %eax
+ movl %eax, G(caml_last_return_address)
+ leal 4(%esp), %eax
+ movl %eax, G(caml_bottom_of_stack)
+ ALIGN_STACK(12)
+ call LBL(105)
+ UNDO_ALIGN_STACK(12)
+ jmp G(caml_alloc1)
+ CFI_ENDPROC
+
+FUNCTION(caml_alloc2)
+ CFI_STARTPROC
+ PROFILE_CAML
+ movl G(caml_young_ptr), %eax
+ subl $12, %eax
+ movl %eax, G(caml_young_ptr)
+ cmpl G(caml_young_limit), %eax
+ jb LBL(101)
+ ret
+LBL(101):
+ movl 0(%esp), %eax
+ movl %eax, G(caml_last_return_address)
+ leal 4(%esp), %eax
+ movl %eax, G(caml_bottom_of_stack)
+ ALIGN_STACK(12)
+ call LBL(105)
+ UNDO_ALIGN_STACK(12)
+ jmp G(caml_alloc2)
+ CFI_ENDPROC
+
+FUNCTION(caml_alloc3)
+ CFI_STARTPROC
+ PROFILE_CAML
+ movl G(caml_young_ptr), %eax
+ subl $16, %eax
+ movl %eax, G(caml_young_ptr)
+ cmpl G(caml_young_limit), %eax
+ jb LBL(102)
+ ret
+LBL(102):
+ movl 0(%esp), %eax
+ movl %eax, G(caml_last_return_address)
+ leal 4(%esp), %eax
+ movl %eax, G(caml_bottom_of_stack)
+ ALIGN_STACK(12)
+ call LBL(105)
+ UNDO_ALIGN_STACK(12)
+ jmp G(caml_alloc3)
+ CFI_ENDPROC
+
+FUNCTION(caml_allocN)
+ CFI_STARTPROC
+ PROFILE_CAML
+ subl G(caml_young_ptr), %eax /* eax = size - caml_young_ptr */
+ negl %eax /* eax = caml_young_ptr - size */
+ cmpl G(caml_young_limit), %eax
+ jb LBL(103)
+ movl %eax, G(caml_young_ptr)
+ ret
+LBL(103):
+ subl G(caml_young_ptr), %eax /* eax = - size */
+ negl %eax /* eax = size */
+ pushl %eax; CFI_ADJUST(4) /* save desired size */
+ subl %eax, G(caml_young_ptr) /* must update young_ptr */
+ movl 4(%esp), %eax
+ movl %eax, G(caml_last_return_address)
+ leal 8(%esp), %eax
+ movl %eax, G(caml_bottom_of_stack)
+ ALIGN_STACK(8)
+ call LBL(105)
+ UNDO_ALIGN_STACK(8)
+ popl %eax; CFI_ADJUST(-4) /* recover desired size */
+ jmp G(caml_allocN)
+ CFI_ENDPROC
+
+/* Call a C function from OCaml */
+
+FUNCTION(caml_c_call)
+ CFI_STARTPROC
+ PROFILE_CAML
+ /* Record lowest stack address and return address */
+ movl (%esp), %edx
+ movl %edx, G(caml_last_return_address)
+ leal 4(%esp), %edx
+ movl %edx, G(caml_bottom_of_stack)
+#if !defined(SYS_mingw) && !defined(SYS_cygwin)
+ /* Touch the stack to trigger a recoverable segfault
+ if insufficient space remains */
+ subl $16384, %esp
+ movl %eax, 0(%esp)
+ addl $16384, %esp
+#endif
+ /* Call the function (address in %eax) */
+ jmp *%eax
+ CFI_ENDPROC
+
+/* Start the OCaml program */
+
+FUNCTION(caml_start_program)
+ CFI_STARTPROC
+ PROFILE_C
+ /* Save callee-save registers */
+ pushl %ebx; CFI_ADJUST(4)
+ pushl %esi; CFI_ADJUST(4)
+ pushl %edi; CFI_ADJUST(4)
+ pushl %ebp; CFI_ADJUST(4)
+ /* Initial entry point is caml_program */
+ movl $ G(caml_program), %esi
+ /* Common code for caml_start_program and caml_callback* */
+LBL(106):
+ /* Build a callback link */
+ pushl G(caml_gc_regs); CFI_ADJUST(4)
+ pushl G(caml_last_return_address); CFI_ADJUST(4)
+ pushl G(caml_bottom_of_stack); CFI_ADJUST(4)
+ /* Note: 16-alignment preserved on MacOSX at this point */
+ /* Build an exception handler */
+ pushl $ LBL(108); CFI_ADJUST(4)
+ ALIGN_STACK(8)
+ pushl G(caml_exception_pointer); CFI_ADJUST(4)
+ movl %esp, G(caml_exception_pointer)
+ /* Call the OCaml code */
+ call *%esi
+LBL(107):
+ /* Pop the exception handler */
+ popl G(caml_exception_pointer); CFI_ADJUST(-4)
+ addl $12, %esp ; CFI_ADJUST(-12)
+LBL(109):
+ /* Pop the callback link, restoring the global variables */
+ popl G(caml_bottom_of_stack); CFI_ADJUST(-4)
+ popl G(caml_last_return_address); CFI_ADJUST(-4)
+ popl G(caml_gc_regs); CFI_ADJUST(-4)
+ /* Restore callee-save registers. */
+ popl %ebp; CFI_ADJUST(-4)
+ popl %edi; CFI_ADJUST(-4)
+ popl %esi; CFI_ADJUST(-4)
+ popl %ebx; CFI_ADJUST(-4)
+ /* Return to caller. */
+ ret
+LBL(108):
+ /* Exception handler*/
+ /* Mark the bucket as an exception result and return it */
+ orl $2, %eax
+ jmp LBL(109)
+ CFI_ENDPROC
+
+/* Raise an exception from OCaml */
+
+FUNCTION(caml_raise_exn)
+ CFI_STARTPROC
+ testl $1, G(caml_backtrace_active)
+ jne LBL(110)
+ movl G(caml_exception_pointer), %esp
+ popl G(caml_exception_pointer); CFI_ADJUST(-4)
+ UNDO_ALIGN_STACK(8)
+ ret
+LBL(110):
+ movl $0, G(caml_backtrace_pos)
+LBL(111):
+ movl %eax, %esi /* Save exception bucket in esi */
+ movl G(caml_exception_pointer), %edi /* SP of handler */
+ movl 0(%esp), %eax /* PC of raise */
+ leal 4(%esp), %edx /* SP of raise */
+ ALIGN_STACK(12)
+ pushl %edi; CFI_ADJUST(4) /* arg 4: sp of handler */
+ pushl %edx; CFI_ADJUST(4) /* arg 3: sp of raise */
+ pushl %eax; CFI_ADJUST(4) /* arg 2: pc of raise */
+ pushl %esi; CFI_ADJUST(4) /* arg 1: exception bucket */
+ call G(caml_stash_backtrace)
+ movl %esi, %eax /* Recover exception bucket */
+ movl %edi, %esp
+ popl G(caml_exception_pointer); CFI_ADJUST(-4)
+ UNDO_ALIGN_STACK(8)
+ ret
+ CFI_ENDPROC
+
+FUNCTION(caml_reraise_exn)
+ CFI_STARTPROC
+ testl $1, G(caml_backtrace_active)
+ jne LBL(111)
+ movl G(caml_exception_pointer), %esp
+ popl G(caml_exception_pointer); CFI_ADJUST(-4)
+ UNDO_ALIGN_STACK(8)
+ ret
+ CFI_ENDPROC
+
+/* Raise an exception from C */
+
+FUNCTION(caml_raise_exception)
+ CFI_STARTPROC
+ PROFILE_C
+ testl $1, G(caml_backtrace_active)
+ jne LBL(112)
+ movl 4(%esp), %eax
+ movl G(caml_exception_pointer), %esp
+ popl G(caml_exception_pointer); CFI_ADJUST(-4)
+ UNDO_ALIGN_STACK(8)
+ ret
+LBL(112):
+ movl 4(%esp), %esi /* Save exception bucket in esi */
+ ALIGN_STACK(12)
+ pushl G(caml_exception_pointer); CFI_ADJUST(4) /* 4: sp of handler */
+ pushl G(caml_bottom_of_stack); CFI_ADJUST(4) /* 3: sp of raise */
+ pushl G(caml_last_return_address); CFI_ADJUST(4)/* 2: pc of raise */
+ pushl %esi; CFI_ADJUST(4) /* 1: exception bucket */
+ call G(caml_stash_backtrace)
+ movl %esi, %eax /* Recover exception bucket */
+ movl G(caml_exception_pointer), %esp
+ popl G(caml_exception_pointer); CFI_ADJUST(-4)
+ UNDO_ALIGN_STACK(8)
+ ret
+ CFI_ENDPROC
+
+/* Callback from C to OCaml */
+
+FUNCTION(caml_callback_exn)
+ CFI_STARTPROC
+ PROFILE_C
+ /* Save callee-save registers */
+ pushl %ebx; CFI_ADJUST(4)
+ pushl %esi; CFI_ADJUST(4)
+ pushl %edi; CFI_ADJUST(4)
+ pushl %ebp; CFI_ADJUST(4)
+ /* Initial loading of arguments */
+ movl 20(%esp), %ebx /* closure */
+ movl 24(%esp), %eax /* argument */
+ movl 0(%ebx), %esi /* code pointer */
+ jmp LBL(106)
+ CFI_ENDPROC
+
+FUNCTION(caml_callback2_exn)
+ CFI_STARTPROC
+ PROFILE_C
+ /* Save callee-save registers */
+ pushl %ebx; CFI_ADJUST(4)
+ pushl %esi; CFI_ADJUST(4)
+ pushl %edi; CFI_ADJUST(4)
+ pushl %ebp; CFI_ADJUST(4)
+ /* Initial loading of arguments */
+ movl 20(%esp), %ecx /* closure */
+ movl 24(%esp), %eax /* first argument */
+ movl 28(%esp), %ebx /* second argument */
+ movl $ G(caml_apply2), %esi /* code pointer */
+ jmp LBL(106)
+ CFI_ENDPROC
+
+FUNCTION(caml_callback3_exn)
+ CFI_STARTPROC
+ PROFILE_C
+ /* Save callee-save registers */
+ pushl %ebx; CFI_ADJUST(4)
+ pushl %esi; CFI_ADJUST(4)
+ pushl %edi; CFI_ADJUST(4)
+ pushl %ebp; CFI_ADJUST(4)
+ /* Initial loading of arguments */
+ movl 20(%esp), %edx /* closure */
+ movl 24(%esp), %eax /* first argument */
+ movl 28(%esp), %ebx /* second argument */
+ movl 32(%esp), %ecx /* third argument */
+ movl $ G(caml_apply3), %esi /* code pointer */
+ jmp LBL(106)
+ CFI_ENDPROC
+
+FUNCTION(caml_ml_array_bound_error)
+ CFI_STARTPROC
+ /* Empty the floating-point stack */
+ ffree %st(0)
+ ffree %st(1)
+ ffree %st(2)
+ ffree %st(3)
+ ffree %st(4)
+ ffree %st(5)
+ ffree %st(6)
+ ffree %st(7)
+ /* Record lowest stack address and return address */
+ movl (%esp), %edx
+ movl %edx, G(caml_last_return_address)
+ leal 4(%esp), %edx
+ movl %edx, G(caml_bottom_of_stack)
+ /* Re-align the stack */
+ andl $-16, %esp
+ /* Branch to [caml_array_bound_error] (never returns) */
+ call G(caml_array_bound_error)
+ CFI_ENDPROC
+
+ .globl G(caml_system__code_end)
+G(caml_system__code_end):
+
+ .data
+ .globl G(caml_system__frametable)
+G(caml_system__frametable):
+ .long 1 /* one descriptor */
+ .long LBL(107) /* return address into callback */
+#ifndef SYS_solaris
+ .word -1 /* negative frame size => use callback link */
+ .word 0 /* no roots here */
+#else
+ .value -1 /* negative frame size => use callback link */
+ .value 0 /* no roots here */
+#endif
+
+ .globl G(caml_extra_params)
+G(caml_extra_params):
+#ifndef SYS_solaris
+ .space 64
+#else
+ .zero 64
+#endif
+
+#if defined(PROFILING) && defined(SYS_macosx)
+ .section __IMPORT,__jump_table,symbol_stubs,self_modifying_code+pure_instructions,5
+Lmcount$stub:
+ .indirect_symbol mcount
+ hlt ; hlt ; hlt ; hlt ; hlt
+ .subsections_via_symbols
+#endif
+
+#if defined(SYS_linux_elf)
+ /* Mark stack as non-executable, PR#4564 */
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/asmrun/i386nt.asm b/asmrun/i386nt.asm
new file mode 100644
index 0000000000..61ec34162f
--- /dev/null
+++ b/asmrun/i386nt.asm
@@ -0,0 +1,332 @@
+;***********************************************************************
+;* *
+;* OCaml *
+;* *
+;* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+;* *
+;* Copyright 1996 Institut National de Recherche en Informatique et *
+;* en Automatique. All rights reserved. This file is distributed *
+;* under the terms of the GNU Library General Public License, with *
+;* the special exception on linking described in file ../LICENSE. *
+;* *
+;***********************************************************************
+
+; Asm part of the runtime system, Intel 386 processor, Intel syntax
+
+ .386
+ .MODEL FLAT
+
+ EXTERN _caml_garbage_collection: PROC
+ EXTERN _caml_apply2: PROC
+ EXTERN _caml_apply3: PROC
+ EXTERN _caml_program: PROC
+ EXTERN _caml_array_bound_error: PROC
+ EXTERN _caml_young_limit: DWORD
+ EXTERN _caml_young_ptr: DWORD
+ EXTERN _caml_bottom_of_stack: DWORD
+ EXTERN _caml_last_return_address: DWORD
+ EXTERN _caml_gc_regs: DWORD
+ EXTERN _caml_exception_pointer: DWORD
+ EXTERN _caml_backtrace_pos: DWORD
+ EXTERN _caml_backtrace_active: DWORD
+ EXTERN _caml_stash_backtrace: PROC
+
+; Allocation
+
+ .CODE
+ PUBLIC _caml_alloc1
+ PUBLIC _caml_alloc2
+ PUBLIC _caml_alloc3
+ PUBLIC _caml_allocN
+ PUBLIC _caml_call_gc
+
+_caml_call_gc:
+ ; Record lowest stack address and return address
+ mov eax, [esp]
+ mov _caml_last_return_address, eax
+ lea eax, [esp+4]
+ mov _caml_bottom_of_stack, eax
+ ; Save all regs used by the code generator
+L105: push ebp
+ push edi
+ push esi
+ push edx
+ push ecx
+ push ebx
+ push eax
+ mov _caml_gc_regs, esp
+ ; Call the garbage collector
+ call _caml_garbage_collection
+ ; Restore all regs used by the code generator
+ pop eax
+ pop ebx
+ pop ecx
+ pop edx
+ pop esi
+ pop edi
+ pop ebp
+ ; Return to caller
+ ret
+
+ ALIGN 4
+_caml_alloc1:
+ mov eax, _caml_young_ptr
+ sub eax, 8
+ mov _caml_young_ptr, eax
+ cmp eax, _caml_young_limit
+ jb L100
+ ret
+L100: mov eax, [esp]
+ mov _caml_last_return_address, eax
+ lea eax, [esp+4]
+ mov _caml_bottom_of_stack, eax
+ call L105
+ jmp _caml_alloc1
+
+ ALIGN 4
+_caml_alloc2:
+ mov eax, _caml_young_ptr
+ sub eax, 12
+ mov _caml_young_ptr, eax
+ cmp eax, _caml_young_limit
+ jb L101
+ ret
+L101: mov eax, [esp]
+ mov _caml_last_return_address, eax
+ lea eax, [esp+4]
+ mov _caml_bottom_of_stack, eax
+ call L105
+ jmp _caml_alloc2
+
+ ALIGN 4
+_caml_alloc3:
+ mov eax, _caml_young_ptr
+ sub eax, 16
+ mov _caml_young_ptr, eax
+ cmp eax, _caml_young_limit
+ jb L102
+ ret
+L102: mov eax, [esp]
+ mov _caml_last_return_address, eax
+ lea eax, [esp+4]
+ mov _caml_bottom_of_stack, eax
+ call L105
+ jmp _caml_alloc3
+
+ ALIGN 4
+_caml_allocN:
+ sub eax, _caml_young_ptr ; eax = size - young_ptr
+ neg eax ; eax = young_ptr - size
+ cmp eax, _caml_young_limit
+ jb L103
+ mov _caml_young_ptr, eax
+ ret
+L103: sub eax, _caml_young_ptr ; eax = - size
+ neg eax ; eax = size
+ push eax ; save desired size
+ sub _caml_young_ptr, eax ; must update young_ptr
+ mov eax, [esp+4]
+ mov _caml_last_return_address, eax
+ lea eax, [esp+8]
+ mov _caml_bottom_of_stack, eax
+ call L105
+ pop eax ; recover desired size
+ jmp _caml_allocN
+
+; Call a C function from OCaml
+
+ PUBLIC _caml_c_call
+ ALIGN 4
+_caml_c_call:
+ ; Record lowest stack address and return address
+ mov edx, [esp]
+ mov _caml_last_return_address, edx
+ lea edx, [esp+4]
+ mov _caml_bottom_of_stack, edx
+ ; Call the function (address in %eax)
+ jmp eax
+
+; Start the OCaml program
+
+ PUBLIC _caml_start_program
+ ALIGN 4
+_caml_start_program:
+ ; Save callee-save registers
+ push ebx
+ push esi
+ push edi
+ push ebp
+ ; Initial code pointer is caml_program
+ mov esi, offset _caml_program
+
+; Code shared between caml_start_program and callback*
+
+L106:
+ ; Build a callback link
+ push _caml_gc_regs
+ push _caml_last_return_address
+ push _caml_bottom_of_stack
+ ; Build an exception handler
+ push L108
+ push _caml_exception_pointer
+ mov _caml_exception_pointer, esp
+ ; Call the OCaml code
+ call esi
+L107:
+ ; Pop the exception handler
+ pop _caml_exception_pointer
+ pop esi ; dummy register
+L109:
+ ; Pop the callback link, restoring the global variables
+ ; used by caml_c_call
+ pop _caml_bottom_of_stack
+ pop _caml_last_return_address
+ pop _caml_gc_regs
+ ; Restore callee-save registers.
+ pop ebp
+ pop edi
+ pop esi
+ pop ebx
+ ; Return to caller.
+ ret
+L108:
+ ; Exception handler
+ ; Mark the bucket as an exception result and return it
+ or eax, 2
+ jmp L109
+
+; Raise an exception for OCaml
+
+ PUBLIC _caml_raise_exn
+ ALIGN 4
+_caml_raise_exn:
+ test _caml_backtrace_active, 1
+ jne L110
+ mov esp, _caml_exception_pointer
+ pop _caml_exception_pointer
+ ret
+L110:
+ mov _caml_backtrace_pos, 0
+L111:
+ mov esi, eax ; Save exception bucket in esi
+ mov edi, _caml_exception_pointer ; SP of handler
+ mov eax, [esp] ; PC of raise
+ lea edx, [esp+4]
+ push edi ; arg 4: SP of handler
+ push edx ; arg 3: SP of raise
+ push eax ; arg 2: PC of raise
+ push esi ; arg 1: exception bucket
+ call _caml_stash_backtrace
+ mov eax, esi ; recover exception bucket
+ mov esp, edi ; cut the stack
+ pop _caml_exception_pointer
+ ret
+
+ PUBLIC _caml_reraise_exn
+ ALIGN 4
+_caml_reraise_exn:
+ test _caml_backtrace_active, 1
+ jne L111
+ mov esp, _caml_exception_pointer
+ pop _caml_exception_pointer
+ ret
+
+ ; Raise an exception from C
+
+ PUBLIC _caml_raise_exception
+ ALIGN 4
+_caml_raise_exception:
+ test _caml_backtrace_active, 1
+ jne L112
+ mov eax, [esp+4]
+ mov esp, _caml_exception_pointer
+ pop _caml_exception_pointer
+ ret
+L112:
+ mov esi, [esp+4] ; Save exception bucket in esi
+ push _caml_exception_pointer ; arg 4: SP of handler
+ push _caml_bottom_of_stack ; arg 3: SP of raise
+ push _caml_last_return_address ; arg 2: PC of raise
+ push esi ; arg 1: exception bucket
+ call _caml_stash_backtrace
+ mov eax, esi ; recover exception bucket
+ mov esp, _caml_exception_pointer ; cut the stack
+ pop _caml_exception_pointer
+ ret
+
+; Callback from C to OCaml
+
+ PUBLIC _caml_callback_exn
+ ALIGN 4
+_caml_callback_exn:
+ ; Save callee-save registers
+ push ebx
+ push esi
+ push edi
+ push ebp
+ ; Initial loading of arguments
+ mov ebx, [esp+20] ; closure
+ mov eax, [esp+24] ; argument
+ mov esi, [ebx] ; code pointer
+ jmp L106
+
+ PUBLIC _caml_callback2_exn
+ ALIGN 4
+_caml_callback2_exn:
+ ; Save callee-save registers
+ push ebx
+ push esi
+ push edi
+ push ebp
+ ; Initial loading of arguments
+ mov ecx, [esp+20] ; closure
+ mov eax, [esp+24] ; first argument
+ mov ebx, [esp+28] ; second argument
+ mov esi, offset _caml_apply2 ; code pointer
+ jmp L106
+
+ PUBLIC _caml_callback3_exn
+ ALIGN 4
+_caml_callback3_exn:
+ ; Save callee-save registers
+ push ebx
+ push esi
+ push edi
+ push ebp
+ ; Initial loading of arguments
+ mov edx, [esp+20] ; closure
+ mov eax, [esp+24] ; first argument
+ mov ebx, [esp+28] ; second argument
+ mov ecx, [esp+32] ; third argument
+ mov esi, offset _caml_apply3 ; code pointer
+ jmp L106
+
+ PUBLIC _caml_ml_array_bound_error
+ ALIGN 4
+_caml_ml_array_bound_error:
+ ; Empty the floating-point stack
+ ffree st(0)
+ ffree st(1)
+ ffree st(2)
+ ffree st(3)
+ ffree st(4)
+ ffree st(5)
+ ffree st(6)
+ ffree st(7)
+ ; Branch to caml_array_bound_error
+ mov eax, offset _caml_array_bound_error
+ jmp _caml_c_call
+
+ .DATA
+ PUBLIC _caml_system__frametable
+_caml_system__frametable LABEL DWORD
+ DWORD 1 ; one descriptor
+ DWORD L107 ; return address into callback
+ WORD -1 ; negative frame size => use callback link
+ WORD 0 ; no roots here
+
+ PUBLIC _caml_extra_params
+_caml_extra_params LABEL DWORD
+ BYTE 64 DUP (?)
+
+ END
diff --git a/asmrun/natdynlink.c b/asmrun/natdynlink.c
new file mode 100644
index 0000000000..82e8795fc8
--- /dev/null
+++ b/asmrun/natdynlink.c
@@ -0,0 +1,156 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Alain Frisch, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2007 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+#include "stack.h"
+#include "caml/callback.h"
+#include "caml/alloc.h"
+#include "caml/intext.h"
+#include "caml/osdeps.h"
+#include "caml/fail.h"
+#include "caml/signals.h"
+
+#include <stdio.h>
+#include <string.h>
+
+static void *getsym(void *handle, char *module, char *name){
+ char *fullname = caml_strconcat(3, "caml", module, name);
+ void *sym;
+ sym = caml_dlsym (handle, fullname);
+ /* printf("%s => %lx\n", fullname, (uintnat) sym); */
+ caml_stat_free(fullname);
+ return sym;
+}
+
+extern char caml_globals_map[];
+
+CAMLprim value caml_natdynlink_getmap(value unit)
+{
+ return (value)caml_globals_map;
+}
+
+CAMLprim value caml_natdynlink_globals_inited(value unit)
+{
+ return Val_int(caml_globals_inited);
+}
+
+CAMLprim value caml_natdynlink_open(value filename, value global)
+{
+ CAMLparam1 (filename);
+ CAMLlocal1 (res);
+ void *sym;
+ void *handle;
+ char *p;
+
+ /* TODO: dlclose in case of error... */
+
+ p = caml_strdup(String_val(filename));
+ caml_enter_blocking_section();
+ handle = caml_dlopen(p, 1, Int_val(global));
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+
+ if (NULL == handle)
+ CAMLreturn(caml_copy_string(caml_dlerror()));
+
+ sym = caml_dlsym(handle, "caml_plugin_header");
+ if (NULL == sym)
+ CAMLreturn(caml_copy_string("not an OCaml plugin"));
+
+ res = caml_alloc_tuple(2);
+ Field(res, 0) = (value) handle;
+ Field(res, 1) = (value) (sym);
+ CAMLreturn(res);
+}
+
+CAMLprim value caml_natdynlink_run(void *handle, value symbol) {
+ CAMLparam1 (symbol);
+ CAMLlocal1 (result);
+ void *sym,*sym2;
+ struct code_fragment * cf;
+
+#define optsym(n) getsym(handle,unit,n)
+ char *unit;
+ void (*entrypoint)(void);
+
+ unit = String_val(symbol);
+
+ sym = optsym("__frametable");
+ if (NULL != sym) caml_register_frametable(sym);
+
+ sym = optsym("");
+ if (NULL != sym) caml_register_dyn_global(sym);
+
+ sym = optsym("__data_begin");
+ sym2 = optsym("__data_end");
+ if (NULL != sym && NULL != sym2)
+ caml_page_table_add(In_static_data, sym, sym2);
+
+ sym = optsym("__code_begin");
+ sym2 = optsym("__code_end");
+ if (NULL != sym && NULL != sym2) {
+ caml_page_table_add(In_code_area, sym, sym2);
+ cf = caml_stat_alloc(sizeof(struct code_fragment));
+ cf->code_start = (char *) sym;
+ cf->code_end = (char *) sym2;
+ cf->digest_computed = 0;
+ caml_ext_table_add(&caml_code_fragments_table, cf);
+ }
+
+ entrypoint = optsym("__entry");
+ if (NULL != entrypoint) result = caml_callback((value)(&entrypoint), 0);
+ else result = Val_unit;
+
+#undef optsym
+
+ CAMLreturn (result);
+}
+
+CAMLprim value caml_natdynlink_run_toplevel(value filename, value symbol)
+{
+ CAMLparam2 (filename, symbol);
+ CAMLlocal2 (res, v);
+ void *handle;
+ char *p;
+
+ /* TODO: dlclose in case of error... */
+
+ p = caml_strdup(String_val(filename));
+ caml_enter_blocking_section();
+ handle = caml_dlopen(p, 1, 1);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+
+ if (NULL == handle) {
+ res = caml_alloc(1,1);
+ v = caml_copy_string(caml_dlerror());
+ Store_field(res, 0, v);
+ } else {
+ res = caml_alloc(1,0);
+ v = caml_natdynlink_run(handle, symbol);
+ Store_field(res, 0, v);
+ }
+ CAMLreturn(res);
+}
+
+CAMLprim value caml_natdynlink_loadsym(value symbol)
+{
+ CAMLparam1 (symbol);
+ CAMLlocal1 (sym);
+
+ sym = (value) caml_globalsym(String_val(symbol));
+ if (!sym) caml_failwith(String_val(symbol));
+ CAMLreturn(sym);
+}
diff --git a/asmrun/power.S b/asmrun/power.S
new file mode 100644
index 0000000000..e5de431adf
--- /dev/null
+++ b/asmrun/power.S
@@ -0,0 +1,692 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#if defined(MODEL_ppc64le)
+ .abiversion 2
+#endif
+
+#if defined(MODEL_ppc64) || defined(MODEL_ppc64le)
+#define EITHER(a,b) b
+#else
+#define EITHER(a,b) a
+#endif
+
+#define WORD EITHER(4,8)
+#define lg EITHER(lwz,ld)
+#define lgu EITHER(lwzu,ldu)
+#define stg EITHER(stw,std)
+#define stgu EITHER(stwu,stdu)
+#define datag EITHER(.long,.quad)
+#define wordalign EITHER(2,3)
+
+/* Stack layout */
+#if defined(MODEL_ppc)
+#define RESERVED_STACK 16
+#define PARAM_SAVE_AREA 0
+#define LR_SAVE 4
+#define TRAP_SIZE 16
+#define TRAP_HANDLER_OFFSET 0
+#define TRAP_PREVIOUS_OFFSET 4
+#define CALLBACK_LINK_SIZE 16
+#define CALLBACK_LINK_OFFSET 0
+#endif
+#if defined(MODEL_ppc64)
+#define RESERVED_STACK 48
+#define PARAM_SAVE_AREA (8*8)
+#define LR_SAVE 16
+#define TOC_SAVE 40
+#define TOC_SAVE_PARENT 8
+#define TRAP_SIZE 32
+#define TRAP_HANDLER_OFFSET 56
+#define TRAP_PREVIOUS_OFFSET 64
+#define CALLBACK_LINK_SIZE 32
+#define CALLBACK_LINK_OFFSET 48
+#endif
+#if defined(MODEL_ppc64le)
+#define RESERVED_STACK 32
+#define PARAM_SAVE_AREA 0
+#define LR_SAVE 16
+#define TOC_SAVE_PARENT 8
+#define TOC_SAVE 24
+#define TRAP_SIZE 32
+#define TRAP_HANDLER_OFFSET 40
+#define TRAP_PREVIOUS_OFFSET 48
+#define CALLBACK_LINK_SIZE 32
+#define CALLBACK_LINK_OFFSET 32
+#endif
+
+/* Function definitions */
+
+#if defined(MODEL_ppc)
+#define FUNCTION(name) \
+ .section ".text"; \
+ .globl name; \
+ .type name, @function; \
+ .align 2; \
+ name:
+
+#define ENDFUNCTION(name) \
+ .size name, . - name
+
+#endif
+
+#if defined(MODEL_ppc64)
+#define FUNCTION(name) \
+ .section ".opd","aw"; \
+ .align 3; \
+ .globl name; \
+ .type name, @function; \
+ name: .quad .L.name,.TOC.@tocbase; \
+ .text; \
+ .align 2; \
+ .L.name:
+
+#define ENDFUNCTION(name) \
+ .size name, . - .L.name
+
+#endif
+
+#if defined(MODEL_ppc64le)
+#define FUNCTION(name) \
+ .section ".text"; \
+ .globl name; \
+ .type name, @function; \
+ .align 2; \
+ name: ; \
+ 0: addis 2, 12, (.TOC. - 0b)@ha; \
+ addi 2, 2, (.TOC. - 0b)@l; \
+ .localentry name, . - 0b
+
+#define ENDFUNCTION(name) \
+ .size name, . - name
+
+#endif
+
+/* Accessing global variables. */
+
+#if defined(MODEL_ppc)
+
+#define Addrglobal(reg,glob) \
+ addis reg, 0, glob@ha; \
+ addi reg, reg, glob@l
+#define Loadglobal(reg,glob,tmp) \
+ addis tmp, 0, glob@ha; \
+ lg reg, glob@l(tmp)
+#define Storeglobal(reg,glob,tmp) \
+ addis tmp, 0, glob@ha; \
+ stg reg, glob@l(tmp)
+#define Loadglobal32(reg,glob,tmp) \
+ addis tmp, 0, glob@ha; \
+ lwz reg, glob@l(tmp)
+#define Storeglobal32(reg,glob,tmp) \
+ addis tmp, 0, glob@ha; \
+ stw reg, glob@l(tmp)
+
+#endif
+
+#if defined(MODEL_ppc64) || defined(MODEL_ppc64le)
+
+#define LSYMB(glob) .L##glob
+
+#define Addrglobal(reg,glob) \
+ ld reg, LSYMB(glob)@toc(2)
+#define Loadglobal(reg,glob,tmp) \
+ Addrglobal(tmp,glob); \
+ lg reg, 0(tmp)
+#define Storeglobal(reg,glob,tmp) \
+ Addrglobal(tmp,glob); \
+ stg reg, 0(tmp)
+#define Loadglobal32(reg,glob,tmp) \
+ Addrglobal(tmp,glob); \
+ lwz reg, 0(tmp)
+#define Storeglobal32(reg,glob,tmp) \
+ Addrglobal(tmp,glob); \
+ stw reg, 0(tmp)
+
+#endif
+
+#if defined(MODEL_ppc64)
+ .section ".opd","aw"
+#else
+ .section ".text"
+#endif
+ .globl caml_system__code_begin
+caml_system__code_begin:
+
+/* Invoke the garbage collector. */
+
+FUNCTION(caml_call_gc)
+#define STACKSIZE (WORD*32 + 8*32 + PARAM_SAVE_AREA + RESERVED_STACK)
+ /* 32 integer registers + 32 float registers + space for C call */
+ /* Set up stack frame */
+ stwu 1, -STACKSIZE(1)
+ /* Record return address into OCaml code */
+ mflr 0
+ Storeglobal(0, caml_last_return_address, 11)
+ /* Record lowest stack address */
+ addi 0, 1, STACKSIZE
+ Storeglobal(0, caml_bottom_of_stack, 11)
+ /* Record pointer to register array */
+ addi 0, 1, 8*32 + PARAM_SAVE_AREA + RESERVED_STACK
+ Storeglobal(0, caml_gc_regs, 11)
+ /* Save current allocation pointer for debugging purposes */
+ Storeglobal(31, caml_young_ptr, 11)
+ /* Save exception pointer (if e.g. a sighandler raises) */
+ Storeglobal(29, caml_exception_pointer, 11)
+ /* Save all registers used by the code generator */
+ addi 11, 1, 8*32 + PARAM_SAVE_AREA + RESERVED_STACK - WORD
+ stgu 3, WORD(11)
+ stgu 4, WORD(11)
+ stgu 5, WORD(11)
+ stgu 6, WORD(11)
+ stgu 7, WORD(11)
+ stgu 8, WORD(11)
+ stgu 9, WORD(11)
+ stgu 10, WORD(11)
+ stgu 14, WORD(11)
+ stgu 15, WORD(11)
+ stgu 16, WORD(11)
+ stgu 17, WORD(11)
+ stgu 18, WORD(11)
+ stgu 19, WORD(11)
+ stgu 20, WORD(11)
+ stgu 21, WORD(11)
+ stgu 22, WORD(11)
+ stgu 23, WORD(11)
+ stgu 24, WORD(11)
+ stgu 25, WORD(11)
+ stgu 26, WORD(11)
+ stgu 27, WORD(11)
+ stgu 28, WORD(11)
+ addi 11, 1, PARAM_SAVE_AREA + RESERVED_STACK - 8
+ stfdu 1, 8(11)
+ stfdu 2, 8(11)
+ stfdu 3, 8(11)
+ stfdu 4, 8(11)
+ stfdu 5, 8(11)
+ stfdu 6, 8(11)
+ stfdu 7, 8(11)
+ stfdu 8, 8(11)
+ stfdu 9, 8(11)
+ stfdu 10, 8(11)
+ stfdu 11, 8(11)
+ stfdu 12, 8(11)
+ stfdu 13, 8(11)
+ stfdu 14, 8(11)
+ stfdu 15, 8(11)
+ stfdu 16, 8(11)
+ stfdu 17, 8(11)
+ stfdu 18, 8(11)
+ stfdu 19, 8(11)
+ stfdu 20, 8(11)
+ stfdu 21, 8(11)
+ stfdu 22, 8(11)
+ stfdu 23, 8(11)
+ stfdu 24, 8(11)
+ stfdu 25, 8(11)
+ stfdu 26, 8(11)
+ stfdu 27, 8(11)
+ stfdu 28, 8(11)
+ stfdu 29, 8(11)
+ stfdu 30, 8(11)
+ stfdu 31, 8(11)
+ /* Call the GC */
+ bl caml_garbage_collection
+#if defined(MODEL_ppc64) || defined(MODEL_ppc64le)
+ nop
+#endif
+ /* Reload new allocation pointer and allocation limit */
+ Loadglobal(31, caml_young_ptr, 11)
+ Loadglobal(30, caml_young_limit, 11)
+ /* Restore all regs used by the code generator */
+ addi 11, 1, 8*32 + PARAM_SAVE_AREA + RESERVED_STACK - WORD
+ lgu 3, WORD(11)
+ lgu 4, WORD(11)
+ lgu 5, WORD(11)
+ lgu 6, WORD(11)
+ lgu 7, WORD(11)
+ lgu 8, WORD(11)
+ lgu 9, WORD(11)
+ lgu 10, WORD(11)
+ lgu 14, WORD(11)
+ lgu 15, WORD(11)
+ lgu 16, WORD(11)
+ lgu 17, WORD(11)
+ lgu 18, WORD(11)
+ lgu 19, WORD(11)
+ lgu 20, WORD(11)
+ lgu 21, WORD(11)
+ lgu 22, WORD(11)
+ lgu 23, WORD(11)
+ lgu 24, WORD(11)
+ lgu 25, WORD(11)
+ lgu 26, WORD(11)
+ lgu 27, WORD(11)
+ lgu 28, WORD(11)
+ addi 11, 1, PARAM_SAVE_AREA + RESERVED_STACK - 8
+ lfdu 1, 8(11)
+ lfdu 2, 8(11)
+ lfdu 3, 8(11)
+ lfdu 4, 8(11)
+ lfdu 5, 8(11)
+ lfdu 6, 8(11)
+ lfdu 7, 8(11)
+ lfdu 8, 8(11)
+ lfdu 9, 8(11)
+ lfdu 10, 8(11)
+ lfdu 11, 8(11)
+ lfdu 12, 8(11)
+ lfdu 13, 8(11)
+ lfdu 14, 8(11)
+ lfdu 15, 8(11)
+ lfdu 16, 8(11)
+ lfdu 17, 8(11)
+ lfdu 18, 8(11)
+ lfdu 19, 8(11)
+ lfdu 20, 8(11)
+ lfdu 21, 8(11)
+ lfdu 22, 8(11)
+ lfdu 23, 8(11)
+ lfdu 24, 8(11)
+ lfdu 25, 8(11)
+ lfdu 26, 8(11)
+ lfdu 27, 8(11)
+ lfdu 28, 8(11)
+ lfdu 29, 8(11)
+ lfdu 30, 8(11)
+ lfdu 31, 8(11)
+ /* Return to caller, restarting the allocation */
+ Loadglobal(11, caml_last_return_address, 11)
+ addi 11, 11, -16 /* Restart the allocation (4 instructions) */
+ mtlr 11
+ /* For PPC64: restore the TOC that the caller saved at the usual place */
+#ifdef TOC_SAVE
+ ld 2, (STACKSIZE + TOC_SAVE)(1)
+#endif
+ /* Deallocate stack frame */
+ addi 1, 1, STACKSIZE
+ blr
+#undef STACKSIZE
+ENDFUNCTION(caml_call_gc)
+
+/* Call a C function from OCaml */
+
+FUNCTION(caml_c_call)
+ .cfi_startproc
+ /* Save return address in a callee-save register */
+ mflr 27
+ .cfi_register 65, 27
+ /* Record lowest stack address and return address */
+ Storeglobal(1, caml_bottom_of_stack, 11)
+ Storeglobal(27, caml_last_return_address, 11)
+ /* Make the exception handler and alloc ptr available to the C code */
+ Storeglobal(31, caml_young_ptr, 11)
+ Storeglobal(29, caml_exception_pointer, 11)
+ /* Call C function (address in r28) */
+#if defined(MODEL_ppc)
+ mtctr 28
+ bctrl
+#elif defined(MODEL_ppc64)
+ ld 0, 0(28)
+ mr 26, 2 /* save current TOC in a callee-save register */
+ mtctr 0
+ ld 2, 8(28)
+ bctrl
+ mr 2, 26 /* restore current TOC */
+#elif defined(MODEL_ppc64le)
+ mtctr 28
+ mr 12, 28
+ mr 26, 2 /* save current TOC in a callee-save register */
+ bctrl
+ mr 2, 26 /* restore current TOC */
+#else
+#error "wrong MODEL"
+#endif
+ /* Restore return address (in 27, preserved by the C function) */
+ mtlr 27
+ /* Reload allocation pointer and allocation limit*/
+ Loadglobal(31, caml_young_ptr, 11)
+ Loadglobal(30, caml_young_limit, 11)
+ /* Return to caller */
+ blr
+ .cfi_endproc
+ENDFUNCTION(caml_c_call)
+
+/* Raise an exception from OCaml */
+
+FUNCTION(caml_raise_exn)
+ Loadglobal32(0, caml_backtrace_active, 11)
+ cmpwi 0, 0
+ bne .L111
+.L110:
+ /* Pop trap frame */
+ lg 0, TRAP_HANDLER_OFFSET(29)
+ mr 1, 29
+ mtctr 0
+ lg 29, TRAP_PREVIOUS_OFFSET(1)
+ addi 1, 1, TRAP_SIZE
+ /* Branch to handler */
+ bctr
+.L111:
+ li 0, 0
+ Storeglobal32(0, caml_backtrace_pos, 11)
+.L112:
+ mr 28, 3 /* preserve exn bucket in callee-save reg */
+ /* arg1: exception bucket, already in r3 */
+ mflr 4 /* arg2: PC of raise */
+ mr 5, 1 /* arg3: SP of raise */
+ mr 6, 29 /* arg4: SP of handler */
+ addi 1, 1, -(PARAM_SAVE_AREA + RESERVED_STACK)
+ /* reserve stack space for C call */
+ bl caml_stash_backtrace
+#if defined(MODEL_ppc64) || defined(MODEL_ppc64le)
+ nop
+#endif
+ mr 3, 28 /* restore exn bucket */
+ b .L110 /* raise the exn */
+ENDFUNCTION(caml_raise_exn)
+
+FUNCTION(caml_reraise_exn)
+ Loadglobal32(0, caml_backtrace_active, 11)
+ cmpwi 0, 0
+ bne- .L112
+ /* Pop trap frame */
+ lg 0, TRAP_HANDLER_OFFSET(29)
+ mr 1, 29
+ mtctr 0
+ lg 29, TRAP_PREVIOUS_OFFSET(1)
+ addi 1, 1, TRAP_SIZE
+ /* Branch to handler */
+ bctr
+ENDFUNCTION(caml_reraise_exn)
+
+/* Raise an exception from C */
+
+FUNCTION(caml_raise_exception)
+ Loadglobal32(0, caml_backtrace_active, 11)
+ cmpwi 0, 0
+ bne .L121
+.L120:
+ /* Reload OCaml global registers */
+ Loadglobal(1, caml_exception_pointer, 11)
+ Loadglobal(31, caml_young_ptr, 11)
+ Loadglobal(30, caml_young_limit, 11)
+ /* Pop trap frame */
+ lg 0, TRAP_HANDLER_OFFSET(1)
+ mtctr 0
+ lg 29, TRAP_PREVIOUS_OFFSET(1)
+ addi 1, 1, TRAP_SIZE
+ /* Branch to handler */
+ bctr
+.L121:
+ li 0, 0
+ Storeglobal32(0, caml_backtrace_pos, 11)
+ mr 28, 3 /* preserve exn bucket in callee-save reg */
+ /* arg1: exception bucket, already in r3 */
+ Loadglobal(4, caml_last_return_address, 11) /* arg2: PC of raise */
+ Loadglobal(5, caml_bottom_of_stack, 11) /* arg3: SP of raise */
+ Loadglobal(6, caml_exception_pointer, 11) /* arg4: SP of handler */
+ addi 1, 1, -(PARAM_SAVE_AREA + RESERVED_STACK)
+ /* reserve stack space for C call */
+ bl caml_stash_backtrace
+#if defined(MODEL_ppc64) || defined(MODEL_ppc64le)
+ nop
+#endif
+ mr 3, 28 /* restore exn bucket */
+ b .L120 /* raise the exn */
+ENDFUNCTION(caml_raise_exception)
+
+/* Start the OCaml program */
+
+FUNCTION(caml_start_program)
+ .cfi_startproc
+#define STACKSIZE (WORD*18 + 8*18 + CALLBACK_LINK_SIZE + RESERVED_STACK)
+ /* 18 callee-save GPR14...GPR31 + 18 callee-save FPR14...FPR31 */
+ Addrglobal(12, caml_program)
+/* Code shared between caml_start_program and caml_callback */
+.L102:
+ /* Allocate and link stack frame */
+ stgu 1, -STACKSIZE(1)
+ .cfi_adjust_cfa_offset STACKSIZE
+ /* Save return address */
+ mflr 0
+ stg 0, (STACKSIZE + LR_SAVE)(1)
+ .cfi_offset 65, LR_SAVE
+ /* Save TOC pointer if applicable */
+#ifdef TOC_SAVE_PARENT
+ std 2, (STACKSIZE + TOC_SAVE_PARENT)(1)
+#endif
+ /* Save all callee-save registers */
+ addi 11, 1, CALLBACK_LINK_SIZE + RESERVED_STACK - WORD
+ stgu 14, WORD(11)
+ stgu 15, WORD(11)
+ stgu 16, WORD(11)
+ stgu 17, WORD(11)
+ stgu 18, WORD(11)
+ stgu 19, WORD(11)
+ stgu 20, WORD(11)
+ stgu 21, WORD(11)
+ stgu 22, WORD(11)
+ stgu 23, WORD(11)
+ stgu 24, WORD(11)
+ stgu 25, WORD(11)
+ stgu 26, WORD(11)
+ stgu 27, WORD(11)
+ stgu 28, WORD(11)
+ stgu 29, WORD(11)
+ stgu 30, WORD(11)
+ stgu 31, WORD(11)
+ stfdu 14, 8(11)
+ stfdu 15, 8(11)
+ stfdu 16, 8(11)
+ stfdu 17, 8(11)
+ stfdu 18, 8(11)
+ stfdu 19, 8(11)
+ stfdu 20, 8(11)
+ stfdu 21, 8(11)
+ stfdu 22, 8(11)
+ stfdu 23, 8(11)
+ stfdu 24, 8(11)
+ stfdu 25, 8(11)
+ stfdu 26, 8(11)
+ stfdu 27, 8(11)
+ stfdu 28, 8(11)
+ stfdu 29, 8(11)
+ stfdu 30, 8(11)
+ stfdu 31, 8(11)
+ /* Set up a callback link */
+ Loadglobal(11, caml_bottom_of_stack, 11)
+ stg 11, CALLBACK_LINK_OFFSET(1)
+ Loadglobal(11, caml_last_return_address, 11)
+ stg 11, (CALLBACK_LINK_OFFSET + WORD)(1)
+ Loadglobal(11, caml_gc_regs, 11)
+ stg 11, (CALLBACK_LINK_OFFSET + 2 * WORD)(1)
+ /* Build an exception handler to catch exceptions escaping out of OCaml */
+ bl .L103
+ b .L104
+.L103:
+ addi 1, 1, -TRAP_SIZE
+ .cfi_adjust_cfa_offset TRAP_SIZE
+ mflr 0
+ stg 0, TRAP_HANDLER_OFFSET(1)
+ Loadglobal(11, caml_exception_pointer, 11)
+ stg 11, TRAP_PREVIOUS_OFFSET(1)
+ mr 29, 1
+ /* Reload allocation pointers */
+ Loadglobal(31, caml_young_ptr, 11)
+ Loadglobal(30, caml_young_limit, 11)
+ /* Call the OCaml code (address in r12) */
+#if defined(MODEL_ppc)
+ mtctr 12
+.L105: bctrl
+#elif defined(MODEL_ppc64)
+ ld 0, 0(12)
+ mtctr 0
+ std 2, TOC_SAVE(1)
+ ld 2, 8(12)
+.L105: bctrl
+ ld 2, TOC_SAVE(1)
+#elif defined(MODEL_ppc64le)
+ mtctr 12
+ std 2, TOC_SAVE(1)
+.L105: bctrl
+ ld 2, TOC_SAVE(1)
+#else
+#error "wrong MODEL"
+#endif
+ /* Pop the trap frame, restoring caml_exception_pointer */
+ lg 0, TRAP_PREVIOUS_OFFSET(1)
+ Storeglobal(0, caml_exception_pointer, 11)
+ addi 1, 1, TRAP_SIZE
+ .cfi_adjust_cfa_offset -TRAP_SIZE
+ /* Pop the callback link, restoring the global variables */
+.L106:
+ lg 0, CALLBACK_LINK_OFFSET(1)
+ Storeglobal(0, caml_bottom_of_stack, 11)
+ lg 0, (CALLBACK_LINK_OFFSET + WORD)(1)
+ Storeglobal(0, caml_last_return_address, 11)
+ lg 0, (CALLBACK_LINK_OFFSET + 2 * WORD)(1)
+ Storeglobal(0, caml_gc_regs, 11)
+ /* Update allocation pointer */
+ Storeglobal(31, caml_young_ptr, 11)
+ /* Restore callee-save registers */
+ addi 11, 1, CALLBACK_LINK_SIZE + RESERVED_STACK - WORD
+ lgu 14, WORD(11)
+ lgu 15, WORD(11)
+ lgu 16, WORD(11)
+ lgu 17, WORD(11)
+ lgu 18, WORD(11)
+ lgu 19, WORD(11)
+ lgu 20, WORD(11)
+ lgu 21, WORD(11)
+ lgu 22, WORD(11)
+ lgu 23, WORD(11)
+ lgu 24, WORD(11)
+ lgu 25, WORD(11)
+ lgu 26, WORD(11)
+ lgu 27, WORD(11)
+ lgu 28, WORD(11)
+ lgu 29, WORD(11)
+ lgu 30, WORD(11)
+ lgu 31, WORD(11)
+ lfdu 14, 8(11)
+ lfdu 15, 8(11)
+ lfdu 16, 8(11)
+ lfdu 17, 8(11)
+ lfdu 18, 8(11)
+ lfdu 19, 8(11)
+ lfdu 20, 8(11)
+ lfdu 21, 8(11)
+ lfdu 22, 8(11)
+ lfdu 23, 8(11)
+ lfdu 24, 8(11)
+ lfdu 25, 8(11)
+ lfdu 26, 8(11)
+ lfdu 27, 8(11)
+ lfdu 28, 8(11)
+ lfdu 29, 8(11)
+ lfdu 30, 8(11)
+ lfdu 31, 8(11)
+ /* Reload return address */
+ lg 0, (STACKSIZE + LR_SAVE)(1)
+ mtlr 0
+ /* Return */
+ addi 1, 1, STACKSIZE
+ blr
+
+ /* The trap handler: */
+.L104:
+ /* Restore TOC pointer */
+#ifdef TOC_SAVE_PARENT
+ ld 2, (STACKSIZE + TOC_SAVE_PARENT)(1)
+#endif
+ /* Update caml_exception_pointer */
+ Storeglobal(29, caml_exception_pointer, 11)
+ /* Encode exception bucket as an exception result and return it */
+ ori 3, 3, 2
+ b .L106
+#undef STACKSIZE
+ .cfi_endproc
+ENDFUNCTION(caml_start_program)
+
+/* Callback from C to OCaml */
+
+FUNCTION(caml_callback_exn)
+ /* Initial shuffling of arguments */
+ mr 0, 3 /* Closure */
+ mr 3, 4 /* Argument */
+ mr 4, 0
+ lg 12, 0(4) /* Code pointer */
+ b .L102
+ENDFUNCTION(caml_callback_exn)
+
+FUNCTION(caml_callback2_exn)
+ mr 0, 3 /* Closure */
+ mr 3, 4 /* First argument */
+ mr 4, 5 /* Second argument */
+ mr 5, 0
+ Addrglobal(12, caml_apply2)
+ b .L102
+ENDFUNCTION(caml_callback2_exn)
+
+FUNCTION(caml_callback3_exn)
+ mr 0, 3 /* Closure */
+ mr 3, 4 /* First argument */
+ mr 4, 5 /* Second argument */
+ mr 5, 6 /* Third argument */
+ mr 6, 0
+ Addrglobal(12, caml_apply3)
+ b .L102
+ENDFUNCTION(caml_callback3_exn)
+
+#if defined(MODEL_ppc64)
+ .section ".opd","aw"
+#else
+ .section ".text"
+#endif
+
+ .globl caml_system__code_end
+caml_system__code_end:
+
+/* Frame table */
+
+ .section ".data"
+ .globl caml_system__frametable
+ .type caml_system__frametable, @object
+caml_system__frametable:
+ datag 1 /* one descriptor */
+ datag .L105 + 4 /* return address into callback */
+ .short -1 /* negative size count => use callback link */
+ .short 0 /* no roots here */
+
+/* TOC entries */
+
+#if defined(MODEL_ppc64) || defined(MODEL_ppc64le)
+
+ .section ".toc", "aw"
+
+#define TOCENTRY(glob) LSYMB(glob): .quad glob
+
+TOCENTRY(caml_apply2)
+TOCENTRY(caml_apply3)
+TOCENTRY(caml_backtrace_active)
+TOCENTRY(caml_backtrace_pos)
+TOCENTRY(caml_bottom_of_stack)
+TOCENTRY(caml_exception_pointer)
+TOCENTRY(caml_gc_regs)
+TOCENTRY(caml_last_return_address)
+TOCENTRY(caml_program)
+TOCENTRY(caml_young_limit)
+TOCENTRY(caml_young_ptr)
+
+#endif
diff --git a/asmrun/roots.c b/asmrun/roots.c
new file mode 100644
index 0000000000..d889c52069
--- /dev/null
+++ b/asmrun/roots.c
@@ -0,0 +1,455 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* To walk the memory roots for garbage collection */
+
+#include "caml/finalise.h"
+#include "caml/globroots.h"
+#include "caml/memory.h"
+#include "caml/major_gc.h"
+#include "caml/minor_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "stack.h"
+#include "caml/roots.h"
+#include <string.h>
+#include <stdio.h>
+
+/* Roots registered from C functions */
+
+struct caml__roots_block *caml_local_roots = NULL;
+
+void (*caml_scan_roots_hook) (scanning_action) = NULL;
+
+/* The hashtable of frame descriptors */
+frame_descr ** caml_frame_descriptors = NULL;
+int caml_frame_descriptors_mask = 0;
+
+/* Linked-list */
+
+typedef struct link {
+ void *data;
+ struct link *next;
+} link;
+
+static link *cons(void *data, link *tl) {
+ link *lnk = caml_stat_alloc(sizeof(link));
+ lnk->data = data;
+ lnk->next = tl;
+ return lnk;
+}
+
+#define iter_list(list,lnk) \
+ for (lnk = list; lnk != NULL; lnk = lnk->next)
+
+/* Linked-list of frametables */
+
+static link *frametables = NULL;
+static intnat num_descr = 0;
+
+static int count_descriptors(link *list) {
+ intnat num_descr = 0;
+ link *lnk;
+ iter_list(list,lnk) {
+ num_descr += *((intnat*) lnk->data);
+ }
+ return num_descr;
+}
+
+static link* frametables_list_tail(link *list) {
+ link *lnk, *tail = NULL;
+ iter_list(list,lnk) {
+ tail = lnk;
+ }
+ return tail;
+}
+
+static frame_descr * next_frame_descr(frame_descr * d) {
+ uintnat nextd;
+ nextd =
+ ((uintnat)d +
+ sizeof(char *) + sizeof(short) + sizeof(short) +
+ sizeof(short) * d->num_live + sizeof(frame_descr *) - 1)
+ & -sizeof(frame_descr *);
+ if (d->frame_size & 1) nextd += 8;
+ return((frame_descr *) nextd);
+}
+
+static void fill_hashtable(link *frametables) {
+ intnat len, j;
+ intnat * tbl;
+ frame_descr * d;
+ uintnat h;
+ link *lnk = NULL;
+
+ iter_list(frametables,lnk) {
+ tbl = (intnat*) lnk->data;
+ len = *tbl;
+ d = (frame_descr *)(tbl + 1);
+ for (j = 0; j < len; j++) {
+ h = Hash_retaddr(d->retaddr);
+ while (caml_frame_descriptors[h] != NULL) {
+ h = (h+1) & caml_frame_descriptors_mask;
+ }
+ caml_frame_descriptors[h] = d;
+ d = next_frame_descr(d);
+ }
+ }
+}
+
+static void init_frame_descriptors(link *new_frametables)
+{
+ intnat tblsize, increase, i;
+ link *tail = NULL;
+
+ Assert(new_frametables);
+
+ tail = frametables_list_tail(new_frametables);
+ increase = count_descriptors(new_frametables);
+ tblsize = caml_frame_descriptors_mask + 1;
+
+ /* Reallocate the caml_frame_descriptor table if it is too small */
+ if(tblsize < (num_descr + increase) * 2) {
+
+ /* Merge both lists */
+ tail->next = frametables;
+ frametables = NULL;
+
+ /* [num_descr] can be less than [num_descr + increase] if frame
+ tables where unregistered */
+ num_descr = count_descriptors(new_frametables);
+
+ tblsize = 4;
+ while (tblsize < 2 * num_descr) tblsize *= 2;
+
+ caml_frame_descriptors_mask = tblsize - 1;
+ if(caml_frame_descriptors) caml_stat_free(caml_frame_descriptors);
+ caml_frame_descriptors =
+ (frame_descr **) caml_stat_alloc(tblsize * sizeof(frame_descr *));
+ for (i = 0; i < tblsize; i++) caml_frame_descriptors[i] = NULL;
+ } else {
+ num_descr += increase;
+ }
+
+ fill_hashtable(new_frametables);
+ tail->next = frametables;
+}
+
+void caml_init_frame_descriptors(void) {
+ intnat i;
+ link *new_frametables = NULL;
+ for (i = 0; caml_frametable[i] != 0; i++)
+ new_frametables = cons(caml_frametable[i],new_frametables);
+ init_frame_descriptors(new_frametables);
+}
+
+void caml_register_frametable(intnat *table) {
+ link *new_frametables = cons(table,NULL);
+ init_frame_descriptors(new_frametables);
+}
+
+static void remove_entry(frame_descr * d) {
+ uintnat i;
+ uintnat r;
+ uintnat j;
+
+ i = Hash_retaddr(d->retaddr);
+ while (caml_frame_descriptors[i] != d) {
+ i = (i+1) & caml_frame_descriptors_mask;
+ }
+
+ r1:
+ j = i;
+ caml_frame_descriptors[i] = NULL;
+ r2:
+ i = (i+1) & caml_frame_descriptors_mask;
+ // r3
+ if(caml_frame_descriptors[i] == NULL) return;
+ r = Hash_retaddr(caml_frame_descriptors[i]->retaddr);
+ /* If r is between i and j (cyclically), i.e. if
+ caml_frame_descriptors[i]->retaddr don't need to be moved */
+ if(( ( j < r ) && ( r <= i ) ) ||
+ ( ( i < j ) && ( j < r ) ) || /* i cycled, r not */
+ ( ( r <= i ) && ( i < j ) ) ) { /* i and r cycled */
+ goto r2;
+ }
+ // r4
+ caml_frame_descriptors[j] = caml_frame_descriptors[i];
+ goto r1;
+}
+
+void caml_unregister_frametable(intnat *table) {
+ intnat len, j;
+ link *lnk;
+ link *previous = frametables;
+ frame_descr * d;
+
+ len = *table;
+ d = (frame_descr *)(table + 1);
+ for (j = 0; j < len; j++) {
+ remove_entry(d);
+ d = next_frame_descr(d);
+ }
+
+ iter_list(frametables,lnk) {
+ if(lnk->data == table) {
+ previous->next = lnk->next;
+ caml_stat_free(lnk);
+ break;
+ }
+ previous = lnk;
+ }
+}
+
+/* Communication with [caml_start_program] and [caml_call_gc]. */
+
+char * caml_top_of_stack;
+char * caml_bottom_of_stack = NULL; /* no stack initially */
+uintnat caml_last_return_address = 1; /* not in OCaml code initially */
+value * caml_gc_regs;
+intnat caml_globals_inited = 0;
+static intnat caml_globals_scanned = 0;
+static link * caml_dyn_globals = NULL;
+
+void caml_register_dyn_global(void *v) {
+ caml_dyn_globals = cons((void*) v,caml_dyn_globals);
+}
+
+/* Call [caml_oldify_one] on (at least) all the roots that point to the minor
+ heap. */
+void caml_oldify_local_roots (void)
+{
+ char * sp;
+ uintnat retaddr;
+ value * regs;
+ frame_descr * d;
+ uintnat h;
+ int i, j, n, ofs;
+#ifdef Stack_grows_upwards
+ short * p; /* PR#4339: stack offsets are negative in this case */
+#else
+ unsigned short * p;
+#endif
+ value glob;
+ value * root;
+ struct caml__roots_block *lr;
+ link *lnk;
+
+ /* The global roots */
+ for (i = caml_globals_scanned;
+ i <= caml_globals_inited && caml_globals[i] != 0;
+ i++) {
+ glob = caml_globals[i];
+ for (j = 0; j < Wosize_val(glob); j++){
+ Oldify (&Field (glob, j));
+ }
+ }
+ caml_globals_scanned = caml_globals_inited;
+
+ /* Dynamic global roots */
+ iter_list(caml_dyn_globals, lnk) {
+ glob = (value) lnk->data;
+ for (j = 0; j < Wosize_val(glob); j++){
+ Oldify (&Field (glob, j));
+ }
+ }
+
+ /* The stack and local roots */
+ sp = caml_bottom_of_stack;
+ retaddr = caml_last_return_address;
+ regs = caml_gc_regs;
+ if (sp != NULL) {
+ while (1) {
+ /* Find the descriptor corresponding to the return address */
+ h = Hash_retaddr(retaddr);
+ while(1) {
+ d = caml_frame_descriptors[h];
+ if (d->retaddr == retaddr) break;
+ h = (h+1) & caml_frame_descriptors_mask;
+ }
+ if (d->frame_size != 0xFFFF) {
+ /* Scan the roots in this frame */
+ for (p = d->live_ofs, n = d->num_live; n > 0; n--, p++) {
+ ofs = *p;
+ if (ofs & 1) {
+ root = regs + (ofs >> 1);
+ } else {
+ root = (value *)(sp + ofs);
+ }
+ Oldify (root);
+ }
+ /* Move to next frame */
+#ifndef Stack_grows_upwards
+ sp += (d->frame_size & 0xFFFC);
+#else
+ sp -= (d->frame_size & 0xFFFC);
+#endif
+ retaddr = Saved_return_address(sp);
+#ifdef Already_scanned
+ /* Stop here if the frame has been scanned during earlier GCs */
+ if (Already_scanned(sp, retaddr)) break;
+ /* Mark frame as already scanned */
+ Mark_scanned(sp, retaddr);
+#endif
+ } else {
+ /* This marks the top of a stack chunk for an ML callback.
+ Skip C portion of stack and continue with next ML stack chunk. */
+ struct caml_context * next_context = Callback_link(sp);
+ sp = next_context->bottom_of_stack;
+ retaddr = next_context->last_retaddr;
+ regs = next_context->gc_regs;
+ /* A null sp means no more ML stack chunks; stop here. */
+ if (sp == NULL) break;
+ }
+ }
+ }
+ /* Local C roots */
+ for (lr = caml_local_roots; lr != NULL; lr = lr->next) {
+ for (i = 0; i < lr->ntables; i++){
+ for (j = 0; j < lr->nitems; j++){
+ root = &(lr->tables[i][j]);
+ Oldify (root);
+ }
+ }
+ }
+ /* Global C roots */
+ caml_scan_global_young_roots(&caml_oldify_one);
+ /* Finalised values */
+ caml_final_do_young_roots (&caml_oldify_one);
+ /* Hook */
+ if (caml_scan_roots_hook != NULL) (*caml_scan_roots_hook)(&caml_oldify_one);
+}
+
+/* Call [darken] on all roots */
+
+void caml_darken_all_roots (void)
+{
+ caml_do_roots (caml_darken);
+}
+
+void caml_do_roots (scanning_action f)
+{
+ int i, j;
+ value glob;
+ link *lnk;
+
+ /* The global roots */
+ for (i = 0; caml_globals[i] != 0; i++) {
+ glob = caml_globals[i];
+ for (j = 0; j < Wosize_val(glob); j++)
+ f (Field (glob, j), &Field (glob, j));
+ }
+
+ /* Dynamic global roots */
+ iter_list(caml_dyn_globals, lnk) {
+ glob = (value) lnk->data;
+ for (j = 0; j < Wosize_val(glob); j++){
+ f (Field (glob, j), &Field (glob, j));
+ }
+ }
+
+ /* The stack and local roots */
+ caml_do_local_roots(f, caml_bottom_of_stack, caml_last_return_address,
+ caml_gc_regs, caml_local_roots);
+ /* Global C roots */
+ caml_scan_global_roots(f);
+ /* Finalised values */
+ caml_final_do_strong_roots (f);
+ /* Hook */
+ if (caml_scan_roots_hook != NULL) (*caml_scan_roots_hook)(f);
+}
+
+void caml_do_local_roots(scanning_action f, char * bottom_of_stack,
+ uintnat last_retaddr, value * gc_regs,
+ struct caml__roots_block * local_roots)
+{
+ char * sp;
+ uintnat retaddr;
+ value * regs;
+ frame_descr * d;
+ uintnat h;
+ int i, j, n, ofs;
+#ifdef Stack_grows_upwards
+ short * p; /* PR#4339: stack offsets are negative in this case */
+#else
+ unsigned short * p;
+#endif
+ value * root;
+ struct caml__roots_block *lr;
+
+ sp = bottom_of_stack;
+ retaddr = last_retaddr;
+ regs = gc_regs;
+ if (sp != NULL) {
+ while (1) {
+ /* Find the descriptor corresponding to the return address */
+ h = Hash_retaddr(retaddr);
+ while(1) {
+ d = caml_frame_descriptors[h];
+ if (d->retaddr == retaddr) break;
+ h = (h+1) & caml_frame_descriptors_mask;
+ }
+ if (d->frame_size != 0xFFFF) {
+ /* Scan the roots in this frame */
+ for (p = d->live_ofs, n = d->num_live; n > 0; n--, p++) {
+ ofs = *p;
+ if (ofs & 1) {
+ root = regs + (ofs >> 1);
+ } else {
+ root = (value *)(sp + ofs);
+ }
+ f (*root, root);
+ }
+ /* Move to next frame */
+#ifndef Stack_grows_upwards
+ sp += (d->frame_size & 0xFFFC);
+#else
+ sp -= (d->frame_size & 0xFFFC);
+#endif
+ retaddr = Saved_return_address(sp);
+#ifdef Mask_already_scanned
+ retaddr = Mask_already_scanned(retaddr);
+#endif
+ } else {
+ /* This marks the top of a stack chunk for an ML callback.
+ Skip C portion of stack and continue with next ML stack chunk. */
+ struct caml_context * next_context = Callback_link(sp);
+ sp = next_context->bottom_of_stack;
+ retaddr = next_context->last_retaddr;
+ regs = next_context->gc_regs;
+ /* A null sp means no more ML stack chunks; stop here. */
+ if (sp == NULL) break;
+ }
+ }
+ }
+ /* Local C roots */
+ for (lr = local_roots; lr != NULL; lr = lr->next) {
+ for (i = 0; i < lr->ntables; i++){
+ for (j = 0; j < lr->nitems; j++){
+ root = &(lr->tables[i][j]);
+ f (*root, root);
+ }
+ }
+ }
+}
+
+uintnat (*caml_stack_usage_hook)(void) = NULL;
+
+uintnat caml_stack_usage (void)
+{
+ uintnat sz;
+ sz = (value *) caml_top_of_stack - (value *) caml_bottom_of_stack;
+ if (caml_stack_usage_hook != NULL)
+ sz += (*caml_stack_usage_hook)();
+ return sz;
+}
diff --git a/asmrun/signals_asm.c b/asmrun/signals_asm.c
new file mode 100644
index 0000000000..f30273bd48
--- /dev/null
+++ b/asmrun/signals_asm.c
@@ -0,0 +1,288 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2007 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Signal handling, code specific to the native-code compiler */
+
+#if defined(TARGET_amd64) && defined (SYS_linux)
+#define _GNU_SOURCE
+#endif
+#include <signal.h>
+#include <errno.h>
+#include <stdio.h>
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include "caml/osdeps.h"
+#include "caml/signals.h"
+#include "caml/signals_machdep.h"
+#include "signals_osdep.h"
+#include "stack.h"
+
+#ifdef HAS_STACK_OVERFLOW_DETECTION
+#include <sys/time.h>
+#include <sys/resource.h>
+#endif
+
+#ifndef NSIG
+#define NSIG 64
+#endif
+
+typedef void (*signal_handler)(int signo);
+
+#ifdef _WIN32
+extern signal_handler caml_win32_signal(int sig, signal_handler action);
+#define signal(sig,act) caml_win32_signal(sig,act)
+extern void caml_win32_overflow_detection();
+#endif
+
+extern char * caml_code_area_start, * caml_code_area_end;
+extern char caml_system__code_begin, caml_system__code_end;
+
+/* Do not use the macro from address_class.h here. */
+#undef Is_in_code_area
+#define Is_in_code_area(pc) \
+ ( ((char *)(pc) >= caml_code_area_start && \
+ (char *)(pc) <= caml_code_area_end) \
+|| ((char *)(pc) >= &caml_system__code_begin && \
+ (char *)(pc) <= &caml_system__code_end) \
+|| (Classify_addr(pc) & In_code_area) )
+
+/* This routine is the common entry point for garbage collection
+ and signal handling. It can trigger a callback to OCaml code.
+ With system threads, this callback can cause a context switch.
+ Hence [caml_garbage_collection] must not be called from regular C code
+ (e.g. the [caml_alloc] function) because the context of the call
+ (e.g. [intern_val]) may not allow context switching.
+ Only generated assembly code can call [caml_garbage_collection],
+ via the caml_call_gc assembly stubs. */
+
+void caml_garbage_collection(void)
+{
+ caml_young_limit = caml_young_start;
+ if (caml_young_ptr < caml_young_start || caml_force_major_slice) {
+ caml_minor_collection();
+ }
+ caml_process_pending_signals();
+}
+
+DECLARE_SIGNAL_HANDLER(handle_signal)
+{
+ int saved_errno;
+ /* Save the value of errno (PR#5982). */
+ saved_errno = errno;
+#if !defined(POSIX_SIGNALS) && !defined(BSD_SIGNALS)
+ signal(sig, handle_signal);
+#endif
+ if (sig < 0 || sig >= NSIG) return;
+ if (caml_try_leave_blocking_section_hook ()) {
+ caml_execute_signal(sig, 1);
+ caml_enter_blocking_section_hook();
+ } else {
+ caml_record_signal(sig);
+ /* Some ports cache [caml_young_limit] in a register.
+ Use the signal context to modify that register too, but only if
+ we are inside OCaml code (not inside C code). */
+#if defined(CONTEXT_PC) && defined(CONTEXT_YOUNG_LIMIT)
+ if (Is_in_code_area(CONTEXT_PC))
+ CONTEXT_YOUNG_LIMIT = (context_reg) caml_young_limit;
+#endif
+ }
+ errno = saved_errno;
+}
+
+int caml_set_signal_action(int signo, int action)
+{
+ signal_handler oldact;
+#ifdef POSIX_SIGNALS
+ struct sigaction sigact, oldsigact;
+#else
+ signal_handler act;
+#endif
+
+#ifdef POSIX_SIGNALS
+ switch(action) {
+ case 0:
+ sigact.sa_handler = SIG_DFL;
+ sigact.sa_flags = 0;
+ break;
+ case 1:
+ sigact.sa_handler = SIG_IGN;
+ sigact.sa_flags = 0;
+ break;
+ default:
+ SET_SIGACT(sigact, handle_signal);
+ break;
+ }
+ sigemptyset(&sigact.sa_mask);
+ if (sigaction(signo, &sigact, &oldsigact) == -1) return -1;
+ oldact = oldsigact.sa_handler;
+#else
+ switch(action) {
+ case 0: act = SIG_DFL; break;
+ case 1: act = SIG_IGN; break;
+ default: act = handle_signal; break;
+ }
+ oldact = signal(signo, act);
+ if (oldact == SIG_ERR) return -1;
+#endif
+ if (oldact == (signal_handler) handle_signal)
+ return 2;
+ else if (oldact == SIG_IGN)
+ return 1;
+ else
+ return 0;
+}
+
+/* Machine- and OS-dependent handling of bound check trap */
+
+#if defined(TARGET_power) || (defined(TARGET_sparc) && defined(SYS_solaris))
+DECLARE_SIGNAL_HANDLER(trap_handler)
+{
+#if defined(SYS_solaris)
+ if (info->si_code != ILL_ILLTRP) {
+ /* Deactivate our exception handler and return. */
+ struct sigaction act;
+ act.sa_handler = SIG_DFL;
+ act.sa_flags = 0;
+ sigemptyset(&act.sa_mask);
+ sigaction(sig, &act, NULL);
+ return;
+ }
+#endif
+#if defined(SYS_rhapsody)
+ /* Unblock SIGTRAP */
+ { sigset_t mask;
+ sigemptyset(&mask);
+ sigaddset(&mask, SIGTRAP);
+ sigprocmask(SIG_UNBLOCK, &mask, NULL);
+ }
+#endif
+ caml_exception_pointer = (char *) CONTEXT_EXCEPTION_POINTER;
+ caml_young_ptr = (value *) CONTEXT_YOUNG_PTR;
+ caml_bottom_of_stack = (char *) CONTEXT_SP;
+ caml_last_return_address = (uintnat) CONTEXT_PC;
+ caml_array_bound_error();
+}
+#endif
+
+/* Machine- and OS-dependent handling of stack overflow */
+
+#ifdef HAS_STACK_OVERFLOW_DETECTION
+
+static char * system_stack_top;
+static char sig_alt_stack[SIGSTKSZ];
+
+#if defined(SYS_linux)
+/* PR#4746: recent Linux kernels with support for stack randomization
+ silently add 2 Mb of stack space on top of RLIMIT_STACK.
+ 2 Mb = 0x200000, to which we add 8 kB (=0x2000) for overshoot. */
+#define EXTRA_STACK 0x202000
+#else
+#define EXTRA_STACK 0x2000
+#endif
+
+#ifdef RETURN_AFTER_STACK_OVERFLOW
+extern void caml_stack_overflow(void);
+#endif
+
+DECLARE_SIGNAL_HANDLER(segv_handler)
+{
+ struct rlimit limit;
+ struct sigaction act;
+ char * fault_addr;
+
+ /* Sanity checks:
+ - faulting address is word-aligned
+ - faulting address is within the stack
+ - we are in OCaml code */
+ fault_addr = CONTEXT_FAULTING_ADDRESS;
+ if (((uintnat) fault_addr & (sizeof(intnat) - 1)) == 0
+ && getrlimit(RLIMIT_STACK, &limit) == 0
+ && fault_addr < system_stack_top
+ && fault_addr >= system_stack_top - limit.rlim_cur - EXTRA_STACK
+#ifdef CONTEXT_PC
+ && Is_in_code_area(CONTEXT_PC)
+#endif
+ ) {
+#ifdef RETURN_AFTER_STACK_OVERFLOW
+ /* Tweak the PC part of the context so that on return from this
+ handler, we jump to the asm function [caml_stack_overflow]
+ (from $ARCH.S). */
+#ifdef CONTEXT_PC
+ CONTEXT_PC = (context_reg) &caml_stack_overflow;
+#else
+#error "CONTEXT_PC must be defined if RETURN_AFTER_STACK_OVERFLOW is"
+#endif
+#else
+ /* Raise a Stack_overflow exception straight from this signal handler */
+#if defined(CONTEXT_YOUNG_PTR) && defined(CONTEXT_EXCEPTION_POINTER)
+ caml_exception_pointer = (char *) CONTEXT_EXCEPTION_POINTER;
+ caml_young_ptr = (value *) CONTEXT_YOUNG_PTR;
+#endif
+ caml_raise_stack_overflow();
+#endif
+ } else {
+ /* Otherwise, deactivate our exception handler and return,
+ causing fatal signal to be generated at point of error. */
+ act.sa_handler = SIG_DFL;
+ act.sa_flags = 0;
+ sigemptyset(&act.sa_mask);
+ sigaction(SIGSEGV, &act, NULL);
+ }
+}
+
+#endif
+
+/* Initialization of signal stuff */
+
+void caml_init_signals(void)
+{
+ /* Bound-check trap handling */
+#if defined(TARGET_sparc) && defined(SYS_solaris)
+ { struct sigaction act;
+ sigemptyset(&act.sa_mask);
+ SET_SIGACT(act, trap_handler);
+ act.sa_flags |= SA_NODEFER;
+ sigaction(SIGILL, &act, NULL);
+ }
+#endif
+
+#if defined(TARGET_power)
+ { struct sigaction act;
+ sigemptyset(&act.sa_mask);
+ SET_SIGACT(act, trap_handler);
+#if !defined(SYS_rhapsody)
+ act.sa_flags |= SA_NODEFER;
+#endif
+ sigaction(SIGTRAP, &act, NULL);
+ }
+#endif
+
+ /* Stack overflow handling */
+#ifdef HAS_STACK_OVERFLOW_DETECTION
+ {
+ stack_t stk;
+ struct sigaction act;
+ stk.ss_sp = sig_alt_stack;
+ stk.ss_size = SIGSTKSZ;
+ stk.ss_flags = 0;
+ SET_SIGACT(act, segv_handler);
+ act.sa_flags |= SA_ONSTACK | SA_NODEFER;
+ sigemptyset(&act.sa_mask);
+ system_stack_top = (char *) &act;
+ if (sigaltstack(&stk, NULL) == 0) { sigaction(SIGSEGV, &act, NULL); }
+ }
+#endif
+#if defined(_WIN32) && !defined(_WIN64)
+ caml_win32_overflow_detection();
+#endif
+}
diff --git a/asmrun/signals_osdep.h b/asmrun/signals_osdep.h
new file mode 100644
index 0000000000..627e3b727e
--- /dev/null
+++ b/asmrun/signals_osdep.h
@@ -0,0 +1,339 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2004 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Processor- and OS-dependent signal interface */
+
+/****************** AMD64, Linux */
+
+#if defined(TARGET_amd64) && defined (SYS_linux)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, ucontext_t * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (void (*)(int,siginfo_t *,void *)) (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ typedef greg_t context_reg;
+ #define CONTEXT_PC (context->uc_mcontext.gregs[REG_RIP])
+ #define CONTEXT_EXCEPTION_POINTER (context->uc_mcontext.gregs[REG_R14])
+ #define CONTEXT_YOUNG_PTR (context->uc_mcontext.gregs[REG_R15])
+ #define CONTEXT_FAULTING_ADDRESS ((char *)context->uc_mcontext.gregs[REG_CR2])
+
+/****************** AMD64, MacOSX */
+
+#elif defined(TARGET_amd64) && defined (SYS_macosx)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, void * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (name); \
+ sigact.sa_flags = SA_SIGINFO | SA_64REGSET
+
+ #include <sys/ucontext.h>
+ #include <AvailabilityMacros.h>
+
+ #if !defined(MAC_OS_X_VERSION_10_5) \
+ || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
+ #define CONTEXT_REG(r) r
+ #else
+ #define CONTEXT_REG(r) __##r
+ #endif
+
+ typedef unsigned long long context_reg;
+ #define CONTEXT_STATE (((ucontext_t *)context)->uc_mcontext->CONTEXT_REG(ss))
+ #define CONTEXT_PC (CONTEXT_STATE.CONTEXT_REG(rip))
+ #define CONTEXT_EXCEPTION_POINTER (CONTEXT_STATE.CONTEXT_REG(r14))
+ #define CONTEXT_YOUNG_PTR (CONTEXT_STATE.CONTEXT_REG(r15))
+ #define CONTEXT_SP (CONTEXT_STATE.CONTEXT_REG(rsp))
+ #define CONTEXT_FAULTING_ADDRESS ((char *) info->si_addr)
+
+ #define RETURN_AFTER_STACK_OVERFLOW
+
+/****************** ARM, Linux */
+
+#elif defined(TARGET_arm) && (defined(SYS_linux_eabi) \
+ || defined(SYS_linux_eabihf))
+
+ #include <sys/ucontext.h>
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, ucontext_t * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (void (*)(int,siginfo_t *,void *)) (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ typedef unsigned long context_reg;
+ #define CONTEXT_PC (context->uc_mcontext.arm_pc)
+ #define CONTEXT_EXCEPTION_POINTER (context->uc_mcontext.arm_fp)
+ #define CONTEXT_YOUNG_PTR (context->uc_mcontext.arm_r8)
+ #define CONTEXT_FAULTING_ADDRESS ((char *) context->uc_mcontext.fault_address)
+
+/****************** ARM64, Linux */
+
+#elif defined(TARGET_arm64) && defined(SYS_linux)
+
+ #include <sys/ucontext.h>
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, ucontext_t * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (void (*)(int,siginfo_t *,void *)) (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ typedef unsigned long context_reg;
+ #define CONTEXT_PC (context->uc_mcontext.pc)
+ #define CONTEXT_EXCEPTION_POINTER (context->uc_mcontext.regs[26])
+ #define CONTEXT_YOUNG_PTR (context->uc_mcontext.regs[27])
+ #define CONTEXT_FAULTING_ADDRESS ((char *) context->uc_mcontext.fault_address)
+
+/****************** AMD64, Solaris x86 */
+
+#elif defined(TARGET_amd64) && defined (SYS_solaris)
+
+ #include <ucontext.h>
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, ucontext_t * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (void (*)(int,siginfo_t *,void *)) (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ typedef greg_t context_reg;
+ #define CONTEXT_PC (context->uc_mcontext.gregs[REG_RIP])
+ #define CONTEXT_EXCEPTION_POINTER (context->uc_mcontext.gregs[REG_R14])
+ #define CONTEXT_YOUNG_PTR (context->uc_mcontext.gregs[REG_R15])
+ #define CONTEXT_FAULTING_ADDRESS ((char *) info->si_addr)
+
+/****************** AMD64, OpenBSD */
+
+#elif defined(TARGET_amd64) && defined (SYS_openbsd)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, struct sigcontext * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (void (*)(int,siginfo_t *,void *)) (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ #define CONTEXT_PC (context->sc_rip)
+ #define CONTEXT_EXCEPTION_POINTER (context->sc_r14)
+ #define CONTEXT_YOUNG_PTR (context->sc_r15)
+ #define CONTEXT_FAULTING_ADDRESS ((char *) info->si_addr)
+
+/****************** I386, Linux */
+
+#elif defined(TARGET_i386) && defined(SYS_linux_elf)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, struct sigcontext context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_handler = (void (*)(int)) (name); \
+ sigact.sa_flags = 0
+
+ #define CONTEXT_FAULTING_ADDRESS ((char *) context.cr2)
+
+/****************** I386, BSD_ELF */
+
+#elif defined(TARGET_i386) && defined(SYS_bsd_elf)
+
+ #if defined (__NetBSD__)
+ #include <ucontext.h>
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, ucontext_t * context)
+ #else
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, struct sigcontext * context)
+ #endif
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (void (*)(int,siginfo_t *,void *)) (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ #if defined (__NetBSD__)
+ #define CONTEXT_PC (_UC_MACHINE_PC(context))
+ #else
+ #define CONTEXT_PC (context->sc_eip)
+ #endif
+ #define CONTEXT_FAULTING_ADDRESS ((char *) info->si_addr)
+
+/****************** I386, BSD */
+
+#elif defined(TARGET_i386) && defined(SYS_bsd)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, void * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ #define CONTEXT_FAULTING_ADDRESS ((char *) info->si_addr)
+
+/****************** I386, MacOS X */
+
+#elif defined(TARGET_i386) && defined(SYS_macosx)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, void * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ #include <sys/ucontext.h>
+ #include <AvailabilityMacros.h>
+
+ #if !defined(MAC_OS_X_VERSION_10_5) \
+ || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
+ #define CONTEXT_REG(r) r
+ #else
+ #define CONTEXT_REG(r) __##r
+ #endif
+
+ #define CONTEXT_STATE (((ucontext_t *)context)->uc_mcontext->CONTEXT_REG(ss))
+ #define CONTEXT_PC (CONTEXT_STATE.CONTEXT_REG(eip))
+ #define CONTEXT_FAULTING_ADDRESS ((char *) info->si_addr)
+
+/****************** I386, Solaris x86 */
+
+#elif defined(TARGET_i386) && defined(SYS_solaris)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, void * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ #define CONTEXT_FAULTING_ADDRESS ((char *) info->si_addr)
+
+/****************** PowerPC, MacOS X */
+
+#elif defined(TARGET_power) && defined(SYS_rhapsody)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, void * context)
+
+ #include <sys/ucontext.h>
+ #include <AvailabilityMacros.h>
+
+ #ifdef __LP64__
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (name); \
+ sigact.sa_flags = SA_SIGINFO | SA_64REGSET
+
+ typedef unsigned long long context_reg;
+
+ #define CONTEXT_MCONTEXT (((ucontext64_t *)context)->uc_mcontext64)
+ #else
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ typedef unsigned long context_reg;
+
+ #define CONTEXT_MCONTEXT (((ucontext_t *)context)->uc_mcontext)
+ #endif
+
+ #if !defined(MAC_OS_X_VERSION_10_5) \
+ || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
+ #define CONTEXT_REG(r) r
+ #else
+ #define CONTEXT_REG(r) __##r
+ #endif
+
+ #define CONTEXT_STATE (CONTEXT_MCONTEXT->CONTEXT_REG(ss))
+ #define CONTEXT_PC (CONTEXT_STATE.CONTEXT_REG(srr0))
+ #define CONTEXT_EXCEPTION_POINTER (CONTEXT_STATE.CONTEXT_REG(r29))
+ #define CONTEXT_YOUNG_LIMIT (CONTEXT_STATE.CONTEXT_REG(r30))
+ #define CONTEXT_YOUNG_PTR (CONTEXT_STATE.CONTEXT_REG(r31))
+ #define CONTEXT_SP (CONTEXT_STATE.CONTEXT_REG(r1))
+ #define CONTEXT_FAULTING_ADDRESS ((char *) info->si_addr)
+
+/****************** PowerPC, ELF (Linux) */
+
+#elif defined(TARGET_power) && defined(SYS_elf)
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, struct sigcontext * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_handler = (void (*)(int)) (name); \
+ sigact.sa_flags = 0
+
+ typedef unsigned long context_reg;
+ #define CONTEXT_PC (context->regs->nip)
+ #define CONTEXT_EXCEPTION_POINTER (context->regs->gpr[29])
+ #define CONTEXT_YOUNG_LIMIT (context->regs->gpr[30])
+ #define CONTEXT_YOUNG_PTR (context->regs->gpr[31])
+ #define CONTEXT_SP (context->regs->gpr[1])
+
+/****************** PowerPC, BSD */
+
+#elif defined(TARGET_power) && (defined(SYS_bsd) || defined(SYS_bsd_elf))
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, int code, struct sigcontext * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_handler = (void (*)(int)) (name); \
+ sigact.sa_flags = 0
+
+ typedef unsigned long context_reg;
+ #define CONTEXT_PC (context->sc_frame.srr0)
+ #define CONTEXT_EXCEPTION_POINTER (context->sc_frame.fixreg[29])
+ #define CONTEXT_YOUNG_LIMIT (context->sc_frame.fixreg[30])
+ #define CONTEXT_YOUNG_PTR (context->sc_frame.fixreg[31])
+ #define CONTEXT_SP (context->sc_frame.fixreg[1])
+
+/****************** SPARC, Solaris */
+
+#elif defined(TARGET_sparc) && defined(SYS_solaris)
+
+ #include <ucontext.h>
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig, siginfo_t * info, ucontext_t * context)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_sigaction = (void (*)(int,siginfo_t *,void *)) (name); \
+ sigact.sa_flags = SA_SIGINFO
+
+ typedef long context_reg;
+ #define CONTEXT_PC (context->uc_mcontext.gregs[REG_PC])
+ /* Local register number N is saved on the stack N words
+ after the stack pointer */
+ #define CONTEXT_SP (context->uc_mcontext.gregs[REG_SP])
+ #define SPARC_L_REG(n) ((long *)(context->uc_mcontext.gregs[REG_SP]))[n]
+ #define CONTEXT_EXCEPTION_POINTER (SPARC_L_REG(5))
+ #define CONTEXT_YOUNG_LIMIT (SPARC_L_REG(7))
+ #define CONTEXT_YOUNG_PTR (SPARC_L_REG(6))
+
+/******************** Default */
+
+#else
+
+ #define DECLARE_SIGNAL_HANDLER(name) \
+ static void name(int sig)
+
+ #define SET_SIGACT(sigact,name) \
+ sigact.sa_handler = (name); \
+ sigact.sa_flags = 0
+
+#endif
diff --git a/asmrun/sparc.S b/asmrun/sparc.S
new file mode 100644
index 0000000000..7f24b4b42d
--- /dev/null
+++ b/asmrun/sparc.S
@@ -0,0 +1,358 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Asm part of the runtime system for the Sparc processor. */
+/* Must be preprocessed by cpp */
+
+#ifndef SYS_solaris
+#define INDIRECT_LIMIT
+#endif
+
+#define Exn_ptr %l5
+#define Alloc_ptr %l6
+#define Alloc_limit %l7
+
+#define Load(symb,reg) sethi %hi(symb), %g1; ld [%g1 + %lo(symb)], reg
+#define Store(reg,symb) sethi %hi(symb), %g1; st reg, [%g1 + %lo(symb)]
+#define Address(symb,reg) sethi %hi(symb), reg; or reg, %lo(symb), reg
+
+/* Allocation functions */
+
+ .text
+
+ .global caml_system__code_begin
+caml_system__code_begin:
+
+ .global caml_allocN
+ .global caml_call_gc
+
+/* Required size in %g2 */
+caml_allocN:
+#ifdef INDIRECT_LIMIT
+ ld [Alloc_limit], %g1
+ sub Alloc_ptr, %g2, Alloc_ptr
+ cmp Alloc_ptr, %g1
+#else
+ sub Alloc_ptr, %g2, Alloc_ptr
+ cmp Alloc_ptr, Alloc_limit
+#endif
+ /*blu,pt %icc, caml_call_gc*/
+ blu caml_call_gc
+ nop
+ retl
+ nop
+
+/* Required size in %g2 */
+caml_call_gc:
+ /* Save exception pointer if GC raises */
+ Store(Exn_ptr, caml_exception_pointer)
+ /* Save current allocation pointer for debugging purposes */
+ Store(Alloc_ptr, caml_young_ptr)
+ /* Record lowest stack address */
+ Store(%sp, caml_bottom_of_stack)
+ /* Record last return address */
+ Store(%o7, caml_last_return_address)
+ /* Allocate space on stack for caml_context structure and float regs */
+ sub %sp, 20*4 + 15*8, %sp
+ /* Save int regs on stack and save it into caml_gc_regs */
+L100: add %sp, 96 + 15*8, %g1
+ st %o0, [%g1]
+ st %o1, [%g1 + 0x4]
+ st %o2, [%g1 + 0x8]
+ st %o3, [%g1 + 0xc]
+ st %o4, [%g1 + 0x10]
+ st %o5, [%g1 + 0x14]
+ st %i0, [%g1 + 0x18]
+ st %i1, [%g1 + 0x1c]
+ st %i2, [%g1 + 0x20]
+ st %i3, [%g1 + 0x24]
+ st %i4, [%g1 + 0x28]
+ st %i5, [%g1 + 0x2c]
+ st %l0, [%g1 + 0x30]
+ st %l1, [%g1 + 0x34]
+ st %l2, [%g1 + 0x38]
+ st %l3, [%g1 + 0x3c]
+ st %l4, [%g1 + 0x40]
+ st %g3, [%g1 + 0x44]
+ st %g4, [%g1 + 0x48]
+ st %g2, [%g1 + 0x4C] /* Save required size */
+ mov %g1, %g2
+ Store(%g2, caml_gc_regs)
+ /* Save the floating-point registers */
+ add %sp, 96, %g1
+ std %f0, [%g1]
+ std %f2, [%g1 + 0x8]
+ std %f4, [%g1 + 0x10]
+ std %f6, [%g1 + 0x18]
+ std %f8, [%g1 + 0x20]
+ std %f10, [%g1 + 0x28]
+ std %f12, [%g1 + 0x30]
+ std %f14, [%g1 + 0x38]
+ std %f16, [%g1 + 0x40]
+ std %f18, [%g1 + 0x48]
+ std %f20, [%g1 + 0x50]
+ std %f22, [%g1 + 0x58]
+ std %f24, [%g1 + 0x60]
+ std %f26, [%g1 + 0x68]
+ std %f28, [%g1 + 0x70]
+ /* Call the garbage collector */
+ call caml_garbage_collection
+ nop
+ /* Restore all regs used by the code generator */
+ add %sp, 96 + 15*8, %g1
+ ld [%g1], %o0
+ ld [%g1 + 0x4], %o1
+ ld [%g1 + 0x8], %o2
+ ld [%g1 + 0xc], %o3
+ ld [%g1 + 0x10], %o4
+ ld [%g1 + 0x14], %o5
+ ld [%g1 + 0x18], %i0
+ ld [%g1 + 0x1c], %i1
+ ld [%g1 + 0x20], %i2
+ ld [%g1 + 0x24], %i3
+ ld [%g1 + 0x28], %i4
+ ld [%g1 + 0x2c], %i5
+ ld [%g1 + 0x30], %l0
+ ld [%g1 + 0x34], %l1
+ ld [%g1 + 0x38], %l2
+ ld [%g1 + 0x3c], %l3
+ ld [%g1 + 0x40], %l4
+ ld [%g1 + 0x44], %g3
+ ld [%g1 + 0x48], %g4
+ ld [%g1 + 0x4C], %g2 /* Recover desired size */
+ add %sp, 96, %g1
+ ldd [%g1], %f0
+ ldd [%g1 + 0x8], %f2
+ ldd [%g1 + 0x10], %f4
+ ldd [%g1 + 0x18], %f6
+ ldd [%g1 + 0x20], %f8
+ ldd [%g1 + 0x28], %f10
+ ldd [%g1 + 0x30], %f12
+ ldd [%g1 + 0x38], %f14
+ ldd [%g1 + 0x40], %f16
+ ldd [%g1 + 0x48], %f18
+ ldd [%g1 + 0x50], %f20
+ ldd [%g1 + 0x58], %f22
+ ldd [%g1 + 0x60], %f24
+ ldd [%g1 + 0x68], %f26
+ ldd [%g1 + 0x70], %f28
+ /* Reload alloc ptr */
+ Load(caml_young_ptr, Alloc_ptr)
+ /* Allocate space for block */
+#ifdef INDIRECT_LIMIT
+ ld [Alloc_limit], %g1
+ sub Alloc_ptr, %g2, Alloc_ptr
+ cmp Alloc_ptr, %g1 /* Check that we have enough free space */
+#else
+ Load(caml_young_limit,Alloc_limit)
+ sub Alloc_ptr, %g2, Alloc_ptr
+ cmp Alloc_ptr, Alloc_limit
+#endif
+ blu L100 /* If not, call GC again */
+ nop
+ /* Return to caller */
+ Load(caml_last_return_address, %o7)
+ retl
+ add %sp, 20*4 + 15*8, %sp /* in delay slot */
+
+/* Call a C function from Ocaml */
+
+ .global caml_c_call
+/* Function to call is in %g2 */
+caml_c_call:
+ /* Record lowest stack address and return address */
+ Store(%sp, caml_bottom_of_stack)
+ Store(%o7, caml_last_return_address)
+ /* Save the exception handler and alloc pointer */
+ Store(Exn_ptr, caml_exception_pointer)
+ sethi %hi(caml_young_ptr), %g1
+ /* Call the C function */
+ call %g2
+ st Alloc_ptr, [%g1 + %lo(caml_young_ptr)] /* in delay slot */
+ /* Reload return address */
+ Load(caml_last_return_address, %o7)
+ /* Reload alloc pointer */
+ sethi %hi(caml_young_ptr), %g1
+ /* Return to caller */
+ retl
+ ld [%g1 + %lo(caml_young_ptr)], Alloc_ptr /* in delay slot */
+
+/* Start the Ocaml program */
+
+ .global caml_start_program
+caml_start_program:
+ /* Save all callee-save registers */
+ save %sp, -96, %sp
+ /* Address of code to call */
+ Address(caml_program, %l2)
+
+ /* Code shared with caml_callback* */
+L108:
+ /* Set up a callback link on the stack. */
+ sub %sp, 16, %sp
+ Load(caml_bottom_of_stack, %l0)
+ Load(caml_last_return_address, %l1)
+ Load(caml_gc_regs, %l3)
+ st %l0, [%sp + 96]
+ st %l1, [%sp + 100]
+ /* Set up a trap frame to catch exceptions escaping the Ocaml code */
+ call L111
+ st %l3, [%sp + 104]
+ b L110
+ nop
+L111: sub %sp, 8, %sp
+ Load(caml_exception_pointer, Exn_ptr)
+ st %o7, [%sp + 96]
+ st Exn_ptr, [%sp + 100]
+ mov %sp, Exn_ptr
+ /* Reload allocation pointers */
+ Load(caml_young_ptr, Alloc_ptr)
+#ifdef INDIRECT_LIMIT
+ Address(caml_young_limit, Alloc_limit)
+#else
+ Load(caml_young_limit, Alloc_limit)
+#endif
+ /* Call the Ocaml code */
+L109: call %l2
+ nop
+ /* Pop trap frame and restore caml_exception_pointer */
+ ld [%sp + 100], Exn_ptr
+ add %sp, 8, %sp
+ Store(Exn_ptr, caml_exception_pointer)
+ /* Pop callback link, restoring the global variables */
+L112: ld [%sp + 96], %l0
+ ld [%sp + 100], %l1
+ ld [%sp + 104], %l2
+ Store(%l0, caml_bottom_of_stack)
+ Store(%l1, caml_last_return_address)
+ Store(%l2, caml_gc_regs)
+ add %sp, 16, %sp
+ /* Save allocation pointer */
+ Store(Alloc_ptr, caml_young_ptr)
+ /* Reload callee-save registers and return */
+ ret
+ restore %o0, 0, %o0 /* copy %o0 in this window to caller's %o0 */
+L110:
+ /* The trap handler */
+ Store(Exn_ptr, caml_exception_pointer)
+ /* Encode exception bucket as an exception result */
+ b L112
+ or %o0, 2, %o0
+
+/* Raise an exception from C */
+
+ .global caml_raise_exception
+caml_raise_exception:
+ /* Save exception bucket in a register outside the reg windows */
+ mov %o0, %g2
+ /* Load exception pointer in a register outside the reg windows */
+ Load(caml_exception_pointer, %g3)
+ /* Pop some frames until the trap pointer is in the current frame. */
+ cmp %g3, %fp
+ blt L107 /* if Exn_ptr < %fp, over */
+ nop
+L106: restore
+ cmp %fp, %g3 /* if %fp <= Exn_ptr, loop */
+ ble L106
+ nop
+L107:
+ /* Reload allocation registers */
+ Load(caml_young_ptr, Alloc_ptr)
+#ifdef INDIRECT_LIMIT
+ Address(caml_young_limit, Alloc_limit)
+#else
+ Load(caml_young_limit, Alloc_limit)
+#endif
+ /* Branch to exception handler */
+ mov %g3, %sp
+ ld [%sp + 96], %g1
+ ld [%sp + 100], Exn_ptr
+ add %sp, 8, %sp
+ jmp %g1 + 8
+ /* Restore bucket, in delay slot */
+ mov %g2, %o0
+
+/* Callbacks C -> ML */
+
+ .global caml_callback_exn
+caml_callback_exn:
+ /* Save callee-save registers and return address */
+ save %sp, -96, %sp
+ /* Initial shuffling of arguments */
+ mov %i0, %g1
+ mov %i1, %i0 /* first arg */
+ mov %g1, %i1 /* environment */
+ b L108
+ ld [%g1], %l2 /* code pointer */
+
+ .global caml_callback2_exn
+caml_callback2_exn:
+ /* Save callee-save registers and return address */
+ save %sp, -104, %sp
+ /* Initial shuffling of arguments */
+ mov %i0, %g1
+ mov %i1, %i0 /* first arg */
+ mov %i2, %i1 /* second arg */
+ mov %g1, %i2 /* environment */
+ sethi %hi(caml_apply2), %l2
+ b L108
+ or %l2, %lo(caml_apply2), %l2
+
+ .global caml_callback3_exn
+caml_callback3_exn:
+ /* Save callee-save registers and return address */
+ save %sp, -104, %sp
+ /* Initial shuffling of arguments */
+ mov %i0, %g1
+ mov %i1, %i0 /* first arg */
+ mov %i2, %i1 /* second arg */
+ mov %i3, %i2 /* third arg */
+ mov %g1, %i3 /* environment */
+ sethi %hi(caml_apply3), %l2
+ b L108
+ or %l2, %lo(caml_apply3), %l2
+
+#ifndef SYS_solaris
+/* Glue code to call [caml_array_bound_error] */
+
+ .global caml_ml_array_bound_error
+caml_ml_array_bound_error:
+ Address(caml_array_bound_error, %g2)
+ b caml_c_call
+ nop
+#endif
+
+ .global caml_system__code_end
+caml_system__code_end:
+
+#ifdef SYS_solaris
+ .section ".rodata"
+#else
+ .data
+#endif
+ .global caml_system__frametable
+ .align 4 /* required for gas? */
+caml_system__frametable:
+ .word 1 /* one descriptor */
+ .word L109 /* return address into callback */
+ .half -1 /* negative frame size => use callback link */
+ .half 0 /* no roots */
+
+#ifdef SYS_solaris
+ .type caml_allocN, #function
+ .type caml_call_gc, #function
+ .type caml_c_call, #function
+ .type caml_start_program, #function
+ .type caml_raise_exception, #function
+ .type caml_system__frametable, #object
+#endif
diff --git a/asmrun/stack.h b/asmrun/stack.h
new file mode 100644
index 0000000000..1aa9b5c88b
--- /dev/null
+++ b/asmrun/stack.h
@@ -0,0 +1,111 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Machine-dependent interface with the asm code */
+
+#ifndef CAML_STACK_H
+#define CAML_STACK_H
+
+/* Macros to access the stack frame */
+
+#ifdef TARGET_sparc
+#define Saved_return_address(sp) *((intnat *)((sp) + 92))
+#define Callback_link(sp) ((struct caml_context *)((sp) + 104))
+#endif
+
+#ifdef TARGET_i386
+#define Saved_return_address(sp) *((intnat *)((sp) - 4))
+#ifndef SYS_win32
+#define Callback_link(sp) ((struct caml_context *)((sp) + 16))
+#else
+#define Callback_link(sp) ((struct caml_context *)((sp) + 8))
+#endif
+#endif
+
+#ifdef TARGET_power
+#if defined(MODEL_ppc)
+#define Saved_return_address(sp) *((intnat *)((sp) - 4))
+#define Callback_link(sp) ((struct caml_context *)((sp) + 16))
+#elif defined(MODEL_ppc64)
+#define Saved_return_address(sp) *((intnat *)((sp) + 16))
+#define Callback_link(sp) ((struct caml_context *)((sp) + (48 + 32)))
+#elif defined(MODEL_ppc64le)
+#define Saved_return_address(sp) *((intnat *)((sp) + 16))
+#define Callback_link(sp) ((struct caml_context *)((sp) + (32 + 32)))
+#else
+#error "TARGET_power: wrong MODEL"
+#endif
+#define Already_scanned(sp, retaddr) ((retaddr) & 1)
+#define Mask_already_scanned(retaddr) ((retaddr) & ~1)
+#define Mark_scanned(sp, retaddr) Saved_return_address(sp) = (retaddr) | 1
+#endif
+
+#ifdef TARGET_arm
+#define Saved_return_address(sp) *((intnat *)((sp) - 4))
+#define Callback_link(sp) ((struct caml_context *)((sp) + 8))
+#endif
+
+#ifdef TARGET_amd64
+#define Saved_return_address(sp) *((intnat *)((sp) - 8))
+#define Callback_link(sp) ((struct caml_context *)((sp) + 16))
+#endif
+
+#ifdef TARGET_arm64
+#define Saved_return_address(sp) *((intnat *)((sp) - 8))
+#define Callback_link(sp) ((struct caml_context *)((sp) + 16))
+#endif
+
+/* Structure of OCaml callback contexts */
+
+struct caml_context {
+ char * bottom_of_stack; /* beginning of OCaml stack chunk */
+ uintnat last_retaddr; /* last return address in OCaml code */
+ value * gc_regs; /* pointer to register block */
+};
+
+/* Structure of frame descriptors */
+
+typedef struct {
+ uintnat retaddr;
+ unsigned short frame_size;
+ unsigned short num_live;
+ unsigned short live_ofs[1];
+} frame_descr;
+
+/* Hash table of frame descriptors */
+
+extern frame_descr ** caml_frame_descriptors;
+extern int caml_frame_descriptors_mask;
+
+#define Hash_retaddr(addr) \
+ (((uintnat)(addr) >> 3) & caml_frame_descriptors_mask)
+
+extern void caml_init_frame_descriptors(void);
+extern void caml_register_frametable(intnat *);
+extern void caml_unregister_frametable(intnat *);
+extern void caml_register_dyn_global(void *);
+
+extern uintnat caml_stack_usage (void);
+extern uintnat (*caml_stack_usage_hook)(void);
+
+/* Declaration of variables used in the asm code */
+extern char * caml_top_of_stack;
+extern char * caml_bottom_of_stack;
+extern uintnat caml_last_return_address;
+extern value * caml_gc_regs;
+extern char * caml_exception_pointer;
+extern value caml_globals[];
+extern intnat caml_globals_inited;
+extern intnat * caml_frametable[];
+
+#endif /* CAML_STACK_H */
diff --git a/asmrun/startup.c b/asmrun/startup.c
new file mode 100644
index 0000000000..5cbd42cff2
--- /dev/null
+++ b/asmrun/startup.c
@@ -0,0 +1,141 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Start-up code */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "caml/callback.h"
+#include "caml/backtrace.h"
+#include "caml/custom.h"
+#include "caml/debugger.h"
+#include "caml/fail.h"
+#include "caml/freelist.h"
+#include "caml/gc.h"
+#include "caml/gc_ctrl.h"
+#include "caml/intext.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/osdeps.h"
+#include "caml/printexc.h"
+#include "stack.h"
+#include "caml/startup_aux.h"
+#include "caml/sys.h"
+#ifdef HAS_UI
+#include "caml/ui.h"
+#endif
+
+extern int caml_parser_trace;
+CAMLexport header_t caml_atom_table[256];
+char * caml_code_area_start, * caml_code_area_end;
+
+/* Initialize the atom table and the static data and code area limits. */
+
+struct segment { char * begin; char * end; };
+
+static void init_static(void)
+{
+ extern struct segment caml_data_segments[], caml_code_segments[];
+ int i;
+ struct code_fragment * cf;
+
+ caml_init_atom_table ();
+
+ for (i = 0; caml_data_segments[i].begin != 0; i++) {
+ /* PR#5509: we must include the zero word at end of data segment,
+ because pointers equal to caml_data_segments[i].end are static data. */
+ if (caml_page_table_add(In_static_data,
+ caml_data_segments[i].begin,
+ caml_data_segments[i].end + sizeof(value)) != 0)
+ caml_fatal_error("Fatal error: not enough memory for initial page table");
+ }
+
+ caml_code_area_start = caml_code_segments[0].begin;
+ caml_code_area_end = caml_code_segments[0].end;
+ for (i = 1; caml_code_segments[i].begin != 0; i++) {
+ if (caml_code_segments[i].begin < caml_code_area_start)
+ caml_code_area_start = caml_code_segments[i].begin;
+ if (caml_code_segments[i].end > caml_code_area_end)
+ caml_code_area_end = caml_code_segments[i].end;
+ }
+ /* Register the code in the table of code fragments */
+ cf = caml_stat_alloc(sizeof(struct code_fragment));
+ cf->code_start = caml_code_area_start;
+ cf->code_end = caml_code_area_end;
+ cf->digest_computed = 0;
+ caml_ext_table_init(&caml_code_fragments_table, 8);
+ caml_ext_table_add(&caml_code_fragments_table, cf);
+}
+
+/* These are termination hooks used by the systhreads library */
+struct longjmp_buffer caml_termination_jmpbuf;
+void (*caml_termination_hook)(void *) = NULL;
+
+extern value caml_start_program (void);
+extern void caml_init_ieee_floats (void);
+extern void caml_init_signals (void);
+
+#ifdef _MSC_VER
+
+/* PR 4887: avoid crash box of windows runtime on some system calls */
+extern void caml_install_invalid_parameter_handler();
+
+#endif
+
+
+void caml_main(char **argv)
+{
+ char * exe_name;
+ static char proc_self_exe[256];
+ value res;
+ char tos;
+
+ caml_init_frame_descriptors();
+ caml_init_ieee_floats();
+#ifdef _MSC_VER
+ caml_install_invalid_parameter_handler();
+#endif
+ caml_init_custom_operations();
+#ifdef DEBUG
+ caml_verb_gc = 63;
+#endif
+ caml_top_of_stack = &tos;
+ caml_parse_ocamlrunparam();
+ caml_init_gc (caml_init_minor_heap_wsz, caml_init_heap_wsz,
+ caml_init_heap_chunk_sz, caml_init_percent_free,
+ caml_init_max_percent_free);
+ init_static();
+ caml_init_signals();
+ caml_init_backtrace();
+ caml_debugger_init (); /* force debugger.o stub to be linked */
+ exe_name = argv[0];
+ if (exe_name == NULL) exe_name = "";
+ if (caml_executable_name(proc_self_exe, sizeof(proc_self_exe)) == 0)
+ exe_name = proc_self_exe;
+ else
+ exe_name = caml_search_exe_in_path(exe_name);
+ caml_sys_init(exe_name, argv);
+ if (sigsetjmp(caml_termination_jmpbuf.buf, 0)) {
+ if (caml_termination_hook != NULL) caml_termination_hook(NULL);
+ return;
+ }
+ res = caml_start_program();
+ if (Is_exception_result(res))
+ caml_fatal_uncaught_exception(Extract_exception(res));
+}
+
+void caml_startup(char **argv)
+{
+ caml_main(argv);
+}
diff --git a/boot/.ignore b/boot/.ignore
new file mode 100644
index 0000000000..30c5866b7c
--- /dev/null
+++ b/boot/.ignore
@@ -0,0 +1,6 @@
+Saved
+ocamlrun
+ocamlrun.exe
+ocamlyacc
+ocamlyacc.exe
+camlheader
diff --git a/boot/ocamlc b/boot/ocamlc
new file mode 100755
index 0000000000..db29711c46
--- /dev/null
+++ b/boot/ocamlc
Binary files differ
diff --git a/boot/ocamldep b/boot/ocamldep
new file mode 100755
index 0000000000..ca853e06f4
--- /dev/null
+++ b/boot/ocamldep
Binary files differ
diff --git a/boot/ocamllex b/boot/ocamllex
new file mode 100755
index 0000000000..b654ba7508
--- /dev/null
+++ b/boot/ocamllex
Binary files differ
diff --git a/bytecomp/.ignore b/bytecomp/.ignore
new file mode 100644
index 0000000000..d2f18a85a9
--- /dev/null
+++ b/bytecomp/.ignore
@@ -0,0 +1,2 @@
+runtimedef.ml
+opcodes.ml
diff --git a/bytecomp/bytegen.ml b/bytecomp/bytegen.ml
new file mode 100644
index 0000000000..b8df64e57a
--- /dev/null
+++ b/bytecomp/bytegen.ml
@@ -0,0 +1,954 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* bytegen.ml : translation of lambda terms to lists of instructions. *)
+
+open Misc
+open Asttypes
+open Primitive
+open Types
+open Lambda
+open Switch
+open Instruct
+
+(**** Label generation ****)
+
+let label_counter = ref 0
+
+let new_label () =
+ incr label_counter; !label_counter
+
+(**** Operations on compilation environments. ****)
+
+let empty_env =
+ { ce_stack = Ident.empty; ce_heap = Ident.empty; ce_rec = Ident.empty }
+
+(* Add a stack-allocated variable *)
+
+let add_var id pos env =
+ { ce_stack = Ident.add id pos env.ce_stack;
+ ce_heap = env.ce_heap;
+ ce_rec = env.ce_rec }
+
+let rec add_vars idlist pos env =
+ match idlist with
+ [] -> env
+ | id :: rem -> add_vars rem (pos + 1) (add_var id pos env)
+
+(**** Examination of the continuation ****)
+
+(* Return a label to the beginning of the given continuation.
+ If the sequence starts with a branch, use the target of that branch
+ as the label, thus avoiding a jump to a jump. *)
+
+let label_code = function
+ Kbranch lbl :: _ as cont -> (lbl, cont)
+ | Klabel lbl :: _ as cont -> (lbl, cont)
+ | cont -> let lbl = new_label() in (lbl, Klabel lbl :: cont)
+
+(* Return a branch to the continuation. That is, an instruction that,
+ when executed, branches to the continuation or performs what the
+ continuation performs. We avoid generating branches to branches and
+ branches to returns. *)
+
+let rec make_branch_2 lbl n cont =
+ function
+ Kreturn m :: _ -> (Kreturn (n + m), cont)
+ | Klabel _ :: c -> make_branch_2 lbl n cont c
+ | Kpop m :: c -> make_branch_2 lbl (n + m) cont c
+ | _ ->
+ match lbl with
+ Some lbl -> (Kbranch lbl, cont)
+ | None -> let lbl = new_label() in (Kbranch lbl, Klabel lbl :: cont)
+
+let make_branch cont =
+ match cont with
+ (Kbranch _ as branch) :: _ -> (branch, cont)
+ | (Kreturn _ as return) :: _ -> (return, cont)
+ | Kraise k :: _ -> (Kraise k, cont)
+ | Klabel lbl :: _ -> make_branch_2 (Some lbl) 0 cont cont
+ | _ -> make_branch_2 (None) 0 cont cont
+
+(* Avoid a branch to a label that follows immediately *)
+
+let branch_to label cont = match cont with
+| Klabel label0::_ when label = label0 -> cont
+| _ -> Kbranch label::cont
+
+(* Discard all instructions up to the next label.
+ This function is to be applied to the continuation before adding a
+ non-terminating instruction (branch, raise, return) in front of it. *)
+
+let rec discard_dead_code = function
+ [] -> []
+ | (Klabel _ | Krestart | Ksetglobal _) :: _ as cont -> cont
+ | _ :: cont -> discard_dead_code cont
+
+(* Check if we're in tailcall position *)
+
+let rec is_tailcall = function
+ Kreturn _ :: _ -> true
+ | Klabel _ :: c -> is_tailcall c
+ | Kpop _ :: c -> is_tailcall c
+ | _ -> false
+
+(* Add a Kpop N instruction in front of a continuation *)
+
+let rec add_pop n cont =
+ if n = 0 then cont else
+ match cont with
+ Kpop m :: cont -> add_pop (n + m) cont
+ | Kreturn m :: cont -> Kreturn(n + m) :: cont
+ | Kraise _ :: _ -> cont
+ | _ -> Kpop n :: cont
+
+(* Add the constant "unit" in front of a continuation *)
+
+let add_const_unit = function
+ (Kacc _ | Kconst _ | Kgetglobal _ | Kpush_retaddr _) :: _ as cont -> cont
+ | cont -> Kconst const_unit :: cont
+
+let rec push_dummies n k = match n with
+| 0 -> k
+| _ -> Kconst const_unit::Kpush::push_dummies (n-1) k
+
+
+(**** Auxiliary for compiling "let rec" ****)
+
+type rhs_kind =
+ | RHS_block of int
+ | RHS_floatblock of int
+ | RHS_nonrec
+ | RHS_function of int * int
+;;
+
+let rec check_recordwith_updates id e =
+ match e with
+ | Lsequence (Lprim ((Psetfield _ | Psetfloatfield _), [Lvar id2; _]), cont)
+ -> id2 = id && check_recordwith_updates id cont
+ | Lvar id2 -> id2 = id
+ | _ -> false
+;;
+
+let rec size_of_lambda = function
+ | Lfunction{kind; params; body} as funct ->
+ RHS_function (1 + IdentSet.cardinal(free_variables funct),
+ List.length params)
+ | Llet (Strict, id, Lprim (Pduprecord (kind, size), _), body)
+ when check_recordwith_updates id body ->
+ begin match kind with
+ | Record_regular | Record_inlined _ -> RHS_block size
+ | Record_float -> RHS_floatblock size
+ | Record_extension -> RHS_block (size + 1)
+ end
+ | Llet(str, id, arg, body) -> size_of_lambda body
+ | Lletrec(bindings, body) -> size_of_lambda body
+ | Lprim(Pmakeblock(tag, mut), args) -> RHS_block (List.length args)
+ | Lprim (Pmakearray (Paddrarray|Pintarray), args) ->
+ RHS_block (List.length args)
+ | Lprim (Pmakearray Pfloatarray, args) -> RHS_floatblock (List.length args)
+ | Lprim (Pmakearray Pgenarray, args) -> assert false
+ | Lprim (Pduprecord ((Record_regular | Record_inlined _), size), args) ->
+ RHS_block size
+ | Lprim (Pduprecord (Record_extension, size), args) ->
+ RHS_block (size + 1)
+ | Lprim (Pduprecord (Record_float, size), args) -> RHS_floatblock size
+ | Levent (lam, _) -> size_of_lambda lam
+ | Lsequence (lam, lam') -> size_of_lambda lam'
+ | _ -> RHS_nonrec
+
+(**** Merging consecutive events ****)
+
+let copy_event ev kind info repr =
+ { ev_pos = 0; (* patched in emitcode *)
+ ev_module = ev.ev_module;
+ ev_loc = ev.ev_loc;
+ ev_kind = kind;
+ ev_info = info;
+ ev_typenv = ev.ev_typenv;
+ ev_typsubst = ev.ev_typsubst;
+ ev_compenv = ev.ev_compenv;
+ ev_stacksize = ev.ev_stacksize;
+ ev_repr = repr }
+
+let merge_infos ev ev' =
+ match ev.ev_info, ev'.ev_info with
+ Event_other, info -> info
+ | info, Event_other -> info
+ | _ -> fatal_error "Bytegen.merge_infos"
+
+let merge_repr ev ev' =
+ match ev.ev_repr, ev'.ev_repr with
+ Event_none, x -> x
+ | x, Event_none -> x
+ | Event_parent r, Event_child r' when r == r' && !r = 1 -> Event_none
+ | Event_child r, Event_parent r' when r == r' -> Event_parent r
+ | _, _ -> fatal_error "Bytegen.merge_repr"
+
+let merge_events ev ev' =
+ let (maj, min) =
+ match ev.ev_kind, ev'.ev_kind with
+ (* Discard pseudo-events *)
+ Event_pseudo, _ -> ev', ev
+ | _, Event_pseudo -> ev, ev'
+ (* Keep following event, supposedly more informative *)
+ | Event_before, (Event_after _ | Event_before) -> ev', ev
+ (* Discard following events, supposedly less informative *)
+ | Event_after _, (Event_after _ | Event_before) -> ev, ev'
+ in
+ copy_event maj maj.ev_kind (merge_infos maj min) (merge_repr maj min)
+
+let weaken_event ev cont =
+ match ev.ev_kind with
+ Event_after _ ->
+ begin match cont with
+ Kpush :: Kevent ({ev_repr = Event_none} as ev') :: c ->
+ begin match ev.ev_info with
+ Event_return _ ->
+ (* Weaken event *)
+ let repr = ref 1 in
+ let ev =
+ copy_event ev Event_pseudo ev.ev_info (Event_parent repr)
+ and ev' =
+ copy_event ev' ev'.ev_kind ev'.ev_info (Event_child repr)
+ in
+ Kevent ev :: Kpush :: Kevent ev' :: c
+ | _ ->
+ (* Only keep following event, equivalent *)
+ cont
+ end
+ | _ ->
+ Kevent ev :: cont
+ end
+ | _ ->
+ Kevent ev :: cont
+
+let add_event ev =
+ function
+ Kevent ev' :: cont -> weaken_event (merge_events ev ev') cont
+ | cont -> weaken_event ev cont
+
+(**** Compilation of a lambda expression ****)
+
+let try_blocks = ref [] (* list of stack size for each nested try block *)
+
+(* association staticraise numbers -> (lbl,size of stack, try_blocks *)
+
+let sz_static_raises = ref []
+
+let push_static_raise i lbl_handler sz =
+ sz_static_raises := (i, (lbl_handler, sz, !try_blocks)) :: !sz_static_raises
+
+let find_raise_label i =
+ try
+ List.assoc i !sz_static_raises
+ with
+ | Not_found ->
+ Misc.fatal_error
+ ("exit("^string_of_int i^") outside appropriated catch")
+
+(* Will the translation of l lead to a jump to label ? *)
+let code_as_jump l sz = match l with
+| Lstaticraise (i,[]) ->
+ let label,size,tb = find_raise_label i in
+ if sz = size && tb == !try_blocks then
+ Some label
+ else
+ None
+| _ -> None
+
+(* Function bodies that remain to be compiled *)
+
+type function_to_compile =
+ { params: Ident.t list; (* function parameters *)
+ body: lambda; (* the function body *)
+ label: label; (* the label of the function entry *)
+ free_vars: Ident.t list; (* free variables of the function *)
+ num_defs: int; (* number of mutually recursive definitions *)
+ rec_vars: Ident.t list; (* mutually recursive fn names *)
+ rec_pos: int } (* rank in recursive definition *)
+
+let functions_to_compile = (Stack.create () : function_to_compile Stack.t)
+
+(* Name of current compilation unit (for debugging events) *)
+
+let compunit_name = ref ""
+
+(* Maximal stack size reached during the current function body *)
+
+let max_stack_used = ref 0
+
+
+(* Sequence of string tests *)
+
+
+(* Translate a primitive to a bytecode instruction (possibly a call to a C
+ function) *)
+
+let comp_bint_primitive bi suff args =
+ let pref =
+ match bi with Pnativeint -> "caml_nativeint_"
+ | Pint32 -> "caml_int32_"
+ | Pint64 -> "caml_int64_" in
+ Kccall(pref ^ suff, List.length args)
+
+let comp_primitive p args =
+ match p with
+ Pgetglobal id -> Kgetglobal id
+ | Psetglobal id -> Ksetglobal id
+ | Pintcomp cmp -> Kintcomp cmp
+ | Pmakeblock(tag, mut) -> Kmakeblock(List.length args, tag)
+ | Pfield n -> Kgetfield n
+ | Psetfield(n, ptr) -> Ksetfield n
+ | Pfloatfield n -> Kgetfloatfield n
+ | Psetfloatfield n -> Ksetfloatfield n
+ | Pduprecord _ -> Kccall("caml_obj_dup", 1)
+ | Pccall p -> Kccall(p.prim_name, p.prim_arity)
+ | Pnegint -> Knegint
+ | Paddint -> Kaddint
+ | Psubint -> Ksubint
+ | Pmulint -> Kmulint
+ | Pdivint -> Kdivint
+ | Pmodint -> Kmodint
+ | Pandint -> Kandint
+ | Porint -> Korint
+ | Pxorint -> Kxorint
+ | Plslint -> Klslint
+ | Plsrint -> Klsrint
+ | Pasrint -> Kasrint
+ | Poffsetint n -> Koffsetint n
+ | Poffsetref n -> Koffsetref n
+ | Pintoffloat -> Kccall("caml_int_of_float", 1)
+ | Pfloatofint -> Kccall("caml_float_of_int", 1)
+ | Pnegfloat -> Kccall("caml_neg_float", 1)
+ | Pabsfloat -> Kccall("caml_abs_float", 1)
+ | Paddfloat -> Kccall("caml_add_float", 2)
+ | Psubfloat -> Kccall("caml_sub_float", 2)
+ | Pmulfloat -> Kccall("caml_mul_float", 2)
+ | Pdivfloat -> Kccall("caml_div_float", 2)
+ | Pfloatcomp Ceq -> Kccall("caml_eq_float", 2)
+ | Pfloatcomp Cneq -> Kccall("caml_neq_float", 2)
+ | Pfloatcomp Clt -> Kccall("caml_lt_float", 2)
+ | Pfloatcomp Cgt -> Kccall("caml_gt_float", 2)
+ | Pfloatcomp Cle -> Kccall("caml_le_float", 2)
+ | Pfloatcomp Cge -> Kccall("caml_ge_float", 2)
+ | Pstringlength -> Kccall("caml_ml_string_length", 1)
+ | Pstringrefs -> Kccall("caml_string_get", 2)
+ | Pstringsets -> Kccall("caml_string_set", 3)
+ | Pstringrefu -> Kgetstringchar
+ | Pstringsetu -> Ksetstringchar
+ | Pstring_load_16(_) -> Kccall("caml_string_get16", 2)
+ | Pstring_load_32(_) -> Kccall("caml_string_get32", 2)
+ | Pstring_load_64(_) -> Kccall("caml_string_get64", 2)
+ | Pstring_set_16(_) -> Kccall("caml_string_set16", 3)
+ | Pstring_set_32(_) -> Kccall("caml_string_set32", 3)
+ | Pstring_set_64(_) -> Kccall("caml_string_set64", 3)
+ | Parraylength kind -> Kvectlength
+ | Parrayrefs Pgenarray -> Kccall("caml_array_get", 2)
+ | Parrayrefs Pfloatarray -> Kccall("caml_array_get_float", 2)
+ | Parrayrefs _ -> Kccall("caml_array_get_addr", 2)
+ | Parraysets Pgenarray -> Kccall("caml_array_set", 3)
+ | Parraysets Pfloatarray -> Kccall("caml_array_set_float", 3)
+ | Parraysets _ -> Kccall("caml_array_set_addr", 3)
+ | Parrayrefu Pgenarray -> Kccall("caml_array_unsafe_get", 2)
+ | Parrayrefu Pfloatarray -> Kccall("caml_array_unsafe_get_float", 2)
+ | Parrayrefu _ -> Kgetvectitem
+ | Parraysetu Pgenarray -> Kccall("caml_array_unsafe_set", 3)
+ | Parraysetu Pfloatarray -> Kccall("caml_array_unsafe_set_float", 3)
+ | Parraysetu _ -> Ksetvectitem
+ | Pctconst c ->
+ let const_name = match c with
+ | Big_endian -> "big_endian"
+ | Word_size -> "word_size"
+ | Int_size -> "int_size"
+ | Max_wosize -> "max_wosize"
+ | Ostype_unix -> "ostype_unix"
+ | Ostype_win32 -> "ostype_win32"
+ | Ostype_cygwin -> "ostype_cygwin" in
+ Kccall(Printf.sprintf "caml_sys_const_%s" const_name, 1)
+ | Pisint -> Kisint
+ | Pisout -> Kisout
+ | Pbittest -> Kccall("caml_bitvect_test", 2)
+ | Pbintofint bi -> comp_bint_primitive bi "of_int" args
+ | Pintofbint bi -> comp_bint_primitive bi "to_int" args
+ | Pcvtbint(Pint32, Pnativeint) -> Kccall("caml_nativeint_of_int32", 1)
+ | Pcvtbint(Pnativeint, Pint32) -> Kccall("caml_nativeint_to_int32", 1)
+ | Pcvtbint(Pint32, Pint64) -> Kccall("caml_int64_of_int32", 1)
+ | Pcvtbint(Pint64, Pint32) -> Kccall("caml_int64_to_int32", 1)
+ | Pcvtbint(Pnativeint, Pint64) -> Kccall("caml_int64_of_nativeint", 1)
+ | Pcvtbint(Pint64, Pnativeint) -> Kccall("caml_int64_to_nativeint", 1)
+ | Pnegbint bi -> comp_bint_primitive bi "neg" args
+ | Paddbint bi -> comp_bint_primitive bi "add" args
+ | Psubbint bi -> comp_bint_primitive bi "sub" args
+ | Pmulbint bi -> comp_bint_primitive bi "mul" args
+ | Pdivbint bi -> comp_bint_primitive bi "div" args
+ | Pmodbint bi -> comp_bint_primitive bi "mod" args
+ | Pandbint bi -> comp_bint_primitive bi "and" args
+ | Porbint bi -> comp_bint_primitive bi "or" args
+ | Pxorbint bi -> comp_bint_primitive bi "xor" args
+ | Plslbint bi -> comp_bint_primitive bi "shift_left" args
+ | Plsrbint bi -> comp_bint_primitive bi "shift_right_unsigned" args
+ | Pasrbint bi -> comp_bint_primitive bi "shift_right" args
+ | Pbintcomp(bi, Ceq) -> Kccall("caml_equal", 2)
+ | Pbintcomp(bi, Cneq) -> Kccall("caml_notequal", 2)
+ | Pbintcomp(bi, Clt) -> Kccall("caml_lessthan", 2)
+ | Pbintcomp(bi, Cgt) -> Kccall("caml_greaterthan", 2)
+ | Pbintcomp(bi, Cle) -> Kccall("caml_lessequal", 2)
+ | Pbintcomp(bi, Cge) -> Kccall("caml_greaterequal", 2)
+ | Pbigarrayref(_, n, _, _) -> Kccall("caml_ba_get_" ^ string_of_int n, n + 1)
+ | Pbigarrayset(_, n, _, _) -> Kccall("caml_ba_set_" ^ string_of_int n, n + 2)
+ | Pbigarraydim(n) -> Kccall("caml_ba_dim_" ^ string_of_int n, 1)
+ | Pbigstring_load_16(_) -> Kccall("caml_ba_uint8_get16", 2)
+ | Pbigstring_load_32(_) -> Kccall("caml_ba_uint8_get32", 2)
+ | Pbigstring_load_64(_) -> Kccall("caml_ba_uint8_get64", 2)
+ | Pbigstring_set_16(_) -> Kccall("caml_ba_uint8_set16", 3)
+ | Pbigstring_set_32(_) -> Kccall("caml_ba_uint8_set32", 3)
+ | Pbigstring_set_64(_) -> Kccall("caml_ba_uint8_set64", 3)
+ | Pbswap16 -> Kccall("caml_bswap16", 1)
+ | Pbbswap(bi) -> comp_bint_primitive bi "bswap" args
+ | Pint_as_pointer -> Kccall("caml_int_as_pointer", 1)
+ | _ -> fatal_error "Bytegen.comp_primitive"
+
+let is_immed n = immed_min <= n && n <= immed_max
+
+module Storer =
+ Switch.Store
+ (struct type t = lambda type key = lambda
+ let make_key = Lambda.make_key end)
+
+(* Compile an expression.
+ The value of the expression is left in the accumulator.
+ env = compilation environment
+ exp = the lambda expression to compile
+ sz = current size of the stack frame
+ cont = list of instructions to execute afterwards
+ Result = list of instructions that evaluate exp, then perform cont. *)
+
+let rec comp_expr env exp sz cont =
+ if sz > !max_stack_used then max_stack_used := sz;
+ match exp with
+ Lvar id ->
+ begin try
+ let pos = Ident.find_same id env.ce_stack in
+ Kacc(sz - pos) :: cont
+ with Not_found ->
+ try
+ let pos = Ident.find_same id env.ce_heap in
+ Kenvacc(pos) :: cont
+ with Not_found ->
+ try
+ let ofs = Ident.find_same id env.ce_rec in
+ Koffsetclosure(ofs) :: cont
+ with Not_found ->
+ fatal_error ("Bytegen.comp_expr: var " ^ Ident.unique_name id)
+ end
+ | Lconst cst ->
+ Kconst cst :: cont
+ | Lapply(func, args, info) ->
+ let nargs = List.length args in
+ if is_tailcall cont then begin
+ comp_args env args sz
+ (Kpush :: comp_expr env func (sz + nargs)
+ (Kappterm(nargs, sz + nargs) :: discard_dead_code cont))
+ end else begin
+ if nargs < 4 then
+ comp_args env args sz
+ (Kpush :: comp_expr env func (sz + nargs) (Kapply nargs :: cont))
+ else begin
+ let (lbl, cont1) = label_code cont in
+ Kpush_retaddr lbl ::
+ comp_args env args (sz + 3)
+ (Kpush :: comp_expr env func (sz + 3 + nargs)
+ (Kapply nargs :: cont1))
+ end
+ end
+ | Lsend(kind, met, obj, args, _) ->
+ let args = if kind = Cached then List.tl args else args in
+ let nargs = List.length args + 1 in
+ let getmethod, args' =
+ if kind = Self then (Kgetmethod, met::obj::args) else
+ match met with
+ Lconst(Const_base(Const_int n)) -> (Kgetpubmet n, obj::args)
+ | _ -> (Kgetdynmet, met::obj::args)
+ in
+ if is_tailcall cont then
+ comp_args env args' sz
+ (getmethod :: Kappterm(nargs, sz + nargs) :: discard_dead_code cont)
+ else
+ if nargs < 4 then
+ comp_args env args' sz
+ (getmethod :: Kapply nargs :: cont)
+ else begin
+ let (lbl, cont1) = label_code cont in
+ Kpush_retaddr lbl ::
+ comp_args env args' (sz + 3)
+ (getmethod :: Kapply nargs :: cont1)
+ end
+ | Lfunction{kind; params; body} -> (* assume kind = Curried *)
+ let lbl = new_label() in
+ let fv = IdentSet.elements(free_variables exp) in
+ let to_compile =
+ { params = params; body = body; label = lbl;
+ free_vars = fv; num_defs = 1; rec_vars = []; rec_pos = 0 } in
+ Stack.push to_compile functions_to_compile;
+ comp_args env (List.map (fun n -> Lvar n) fv) sz
+ (Kclosure(lbl, List.length fv) :: cont)
+ | Llet(str, id, arg, body) ->
+ comp_expr env arg sz
+ (Kpush :: comp_expr (add_var id (sz+1) env) body (sz+1)
+ (add_pop 1 cont))
+ | Lletrec(decl, body) ->
+ let ndecl = List.length decl in
+ if List.for_all (function (_, Lfunction _) -> true | _ -> false)
+ decl then begin
+ (* let rec of functions *)
+ let fv =
+ IdentSet.elements (free_variables (Lletrec(decl, lambda_unit))) in
+ let rec_idents = List.map (fun (id, lam) -> id) decl in
+ let rec comp_fun pos = function
+ [] -> []
+ | (id, Lfunction{kind; params; body}) :: rem ->
+ let lbl = new_label() in
+ let to_compile =
+ { params = params; body = body; label = lbl; free_vars = fv;
+ num_defs = ndecl; rec_vars = rec_idents; rec_pos = pos} in
+ Stack.push to_compile functions_to_compile;
+ lbl :: comp_fun (pos + 1) rem
+ | _ -> assert false in
+ let lbls = comp_fun 0 decl in
+ comp_args env (List.map (fun n -> Lvar n) fv) sz
+ (Kclosurerec(lbls, List.length fv) ::
+ (comp_expr (add_vars rec_idents (sz+1) env) body (sz + ndecl)
+ (add_pop ndecl cont)))
+ end else begin
+ let decl_size =
+ List.map (fun (id, exp) -> (id, exp, size_of_lambda exp)) decl in
+ let rec comp_init new_env sz = function
+ | [] -> comp_nonrec new_env sz ndecl decl_size
+ | (id, exp, RHS_floatblock blocksize) :: rem ->
+ Kconst(Const_base(Const_int blocksize)) ::
+ Kccall("caml_alloc_dummy_float", 1) :: Kpush ::
+ comp_init (add_var id (sz+1) new_env) (sz+1) rem
+ | (id, exp, RHS_block blocksize) :: rem ->
+ Kconst(Const_base(Const_int blocksize)) ::
+ Kccall("caml_alloc_dummy", 1) :: Kpush ::
+ comp_init (add_var id (sz+1) new_env) (sz+1) rem
+ | (id, exp, RHS_function (blocksize,arity)) :: rem ->
+ Kconst(Const_base(Const_int arity)) ::
+ Kpush ::
+ Kconst(Const_base(Const_int blocksize)) ::
+ Kccall("caml_alloc_dummy_function", 2) :: Kpush ::
+ comp_init (add_var id (sz+1) new_env) (sz+1) rem
+ | (id, exp, RHS_nonrec) :: rem ->
+ Kconst(Const_base(Const_int 0)) :: Kpush ::
+ comp_init (add_var id (sz+1) new_env) (sz+1) rem
+ and comp_nonrec new_env sz i = function
+ | [] -> comp_rec new_env sz ndecl decl_size
+ | (id, exp, (RHS_block _ | RHS_floatblock _ | RHS_function _))
+ :: rem ->
+ comp_nonrec new_env sz (i-1) rem
+ | (id, exp, RHS_nonrec) :: rem ->
+ comp_expr new_env exp sz
+ (Kassign (i-1) :: comp_nonrec new_env sz (i-1) rem)
+ and comp_rec new_env sz i = function
+ | [] -> comp_expr new_env body sz (add_pop ndecl cont)
+ | (id, exp, (RHS_block _ | RHS_floatblock _ | RHS_function _))
+ :: rem ->
+ comp_expr new_env exp sz
+ (Kpush :: Kacc i :: Kccall("caml_update_dummy", 2) ::
+ comp_rec new_env sz (i-1) rem)
+ | (id, exp, RHS_nonrec) :: rem ->
+ comp_rec new_env sz (i-1) rem
+ in
+ comp_init env sz decl_size
+ end
+ | Lprim(Pidentity, [arg]) ->
+ comp_expr env arg sz cont
+ | Lprim(Pignore, [arg]) ->
+ comp_expr env arg sz (add_const_unit cont)
+ | Lprim(Pdirapply loc, [func;arg])
+ | Lprim(Prevapply loc, [arg;func]) ->
+ let exp = Lapply(func, [arg], mk_apply_info loc) in
+ comp_expr env exp sz cont
+ | Lprim(Pnot, [arg]) ->
+ let newcont =
+ match cont with
+ Kbranchif lbl :: cont1 -> Kbranchifnot lbl :: cont1
+ | Kbranchifnot lbl :: cont1 -> Kbranchif lbl :: cont1
+ | _ -> Kboolnot :: cont in
+ comp_expr env arg sz newcont
+ | Lprim(Psequand, [exp1; exp2]) ->
+ begin match cont with
+ Kbranchifnot lbl :: _ ->
+ comp_expr env exp1 sz (Kbranchifnot lbl ::
+ comp_expr env exp2 sz cont)
+ | Kbranchif lbl :: cont1 ->
+ let (lbl2, cont2) = label_code cont1 in
+ comp_expr env exp1 sz (Kbranchifnot lbl2 ::
+ comp_expr env exp2 sz (Kbranchif lbl :: cont2))
+ | _ ->
+ let (lbl, cont1) = label_code cont in
+ comp_expr env exp1 sz (Kstrictbranchifnot lbl ::
+ comp_expr env exp2 sz cont1)
+ end
+ | Lprim(Psequor, [exp1; exp2]) ->
+ begin match cont with
+ Kbranchif lbl :: _ ->
+ comp_expr env exp1 sz (Kbranchif lbl ::
+ comp_expr env exp2 sz cont)
+ | Kbranchifnot lbl :: cont1 ->
+ let (lbl2, cont2) = label_code cont1 in
+ comp_expr env exp1 sz (Kbranchif lbl2 ::
+ comp_expr env exp2 sz (Kbranchifnot lbl :: cont2))
+ | _ ->
+ let (lbl, cont1) = label_code cont in
+ comp_expr env exp1 sz (Kstrictbranchif lbl ::
+ comp_expr env exp2 sz cont1)
+ end
+ | Lprim(Praise k, [arg]) ->
+ comp_expr env arg sz (Kraise k :: discard_dead_code cont)
+ | Lprim(Paddint, [arg; Lconst(Const_base(Const_int n))])
+ when is_immed n ->
+ comp_expr env arg sz (Koffsetint n :: cont)
+ | Lprim(Psubint, [arg; Lconst(Const_base(Const_int n))])
+ when is_immed (-n) ->
+ comp_expr env arg sz (Koffsetint (-n) :: cont)
+ | Lprim (Poffsetint n, [arg])
+ when not (is_immed n) ->
+ comp_expr env arg sz
+ (Kpush::
+ Kconst (Const_base (Const_int n))::
+ Kaddint::cont)
+ | Lprim(Pmakearray kind, args) ->
+ begin match kind with
+ Pintarray | Paddrarray ->
+ comp_args env args sz (Kmakeblock(List.length args, 0) :: cont)
+ | Pfloatarray ->
+ comp_args env args sz (Kmakefloatblock(List.length args) :: cont)
+ | Pgenarray ->
+ if args = []
+ then Kmakeblock(0, 0) :: cont
+ else comp_args env args sz
+ (Kmakeblock(List.length args, 0) ::
+ Kccall("caml_make_array", 1) :: cont)
+ end
+(* Integer first for enabling futher optimization (cf. emitcode.ml) *)
+ | Lprim (Pintcomp c, [arg ; (Lconst _ as k)]) ->
+ let p = Pintcomp (commute_comparison c)
+ and args = [k ; arg] in
+ comp_args env args sz (comp_primitive p args :: cont)
+ | Lprim(p, args) ->
+ comp_args env args sz (comp_primitive p args :: cont)
+ | Lstaticcatch (body, (i, vars) , handler) ->
+ let nvars = List.length vars in
+ let branch1, cont1 = make_branch cont in
+ let r =
+ if nvars <> 1 then begin (* general case *)
+ let lbl_handler, cont2 =
+ label_code
+ (comp_expr
+ (add_vars vars (sz+1) env)
+ handler (sz+nvars) (add_pop nvars cont1)) in
+ push_static_raise i lbl_handler (sz+nvars);
+ push_dummies nvars
+ (comp_expr env body (sz+nvars)
+ (add_pop nvars (branch1 :: cont2)))
+ end else begin (* small optimization for nvars = 1 *)
+ let var = match vars with [var] -> var | _ -> assert false in
+ let lbl_handler, cont2 =
+ label_code
+ (Kpush::comp_expr
+ (add_var var (sz+1) env)
+ handler (sz+1) (add_pop 1 cont1)) in
+ push_static_raise i lbl_handler sz;
+ comp_expr env body sz (branch1 :: cont2)
+ end in
+ sz_static_raises := List.tl !sz_static_raises ;
+ r
+ | Lstaticraise (i, args) ->
+ let cont = discard_dead_code cont in
+ let label,size,tb = find_raise_label i in
+ let cont = branch_to label cont in
+ let rec loop sz tbb =
+ if tb == tbb then add_pop (sz-size) cont
+ else match tbb with
+ | [] -> assert false
+ | try_sz :: tbb -> add_pop (sz-try_sz-4) (Kpoptrap :: loop try_sz tbb)
+ in
+ let cont = loop sz !try_blocks in
+ begin match args with
+ | [arg] -> (* optim, argument passed in accumulator *)
+ comp_expr env arg sz cont
+ | _ -> comp_exit_args env args sz size cont
+ end
+ | Ltrywith(body, id, handler) ->
+ let (branch1, cont1) = make_branch cont in
+ let lbl_handler = new_label() in
+ let body_cont =
+ Kpoptrap :: branch1 ::
+ Klabel lbl_handler :: Kpush ::
+ comp_expr (add_var id (sz+1) env) handler (sz+1) (add_pop 1 cont1)
+ in
+ try_blocks := sz :: !try_blocks;
+ let l = comp_expr env body (sz+4) body_cont in
+ try_blocks := List.tl !try_blocks;
+ Kpushtrap lbl_handler :: l
+ | Lifthenelse(cond, ifso, ifnot) ->
+ comp_binary_test env cond ifso ifnot sz cont
+ | Lsequence(exp1, exp2) ->
+ comp_expr env exp1 sz (comp_expr env exp2 sz cont)
+ | Lwhile(cond, body) ->
+ let lbl_loop = new_label() in
+ let lbl_test = new_label() in
+ Kbranch lbl_test :: Klabel lbl_loop :: Kcheck_signals ::
+ comp_expr env body sz
+ (Klabel lbl_test ::
+ comp_expr env cond sz (Kbranchif lbl_loop :: add_const_unit cont))
+ | Lfor(param, start, stop, dir, body) ->
+ let lbl_loop = new_label() in
+ let lbl_exit = new_label() in
+ let offset = match dir with Upto -> 1 | Downto -> -1 in
+ let comp = match dir with Upto -> Cgt | Downto -> Clt in
+ comp_expr env start sz
+ (Kpush :: comp_expr env stop (sz+1)
+ (Kpush :: Kpush :: Kacc 2 :: Kintcomp comp :: Kbranchif lbl_exit ::
+ Klabel lbl_loop :: Kcheck_signals ::
+ comp_expr (add_var param (sz+1) env) body (sz+2)
+ (Kacc 1 :: Kpush :: Koffsetint offset :: Kassign 2 ::
+ Kacc 1 :: Kintcomp Cneq :: Kbranchif lbl_loop ::
+ Klabel lbl_exit :: add_const_unit (add_pop 2 cont))))
+ | Lswitch(arg, sw) ->
+ let (branch, cont1) = make_branch cont in
+ let c = ref (discard_dead_code cont1) in
+
+(* Build indirection vectors *)
+ let store = Storer.mk_store () in
+ let act_consts = Array.make sw.sw_numconsts 0
+ and act_blocks = Array.make sw.sw_numblocks 0 in
+ begin match sw.sw_failaction with (* default is index 0 *)
+ | Some fail -> ignore (store.act_store fail)
+ | None -> ()
+ end ;
+ List.iter
+ (fun (n, act) -> act_consts.(n) <- store.act_store act) sw.sw_consts;
+ List.iter
+ (fun (n, act) -> act_blocks.(n) <- store.act_store act) sw.sw_blocks;
+(* Compile and label actions *)
+ let acts = store.act_get () in
+(*
+ let a = store.act_get_shared () in
+ Array.iter
+ (function
+ | Switch.Shared (Lstaticraise _) -> ()
+ | Switch.Shared act ->
+ Printlambda.lambda Format.str_formatter act ;
+ Printf.eprintf "SHARE BYTE:\n%s\n" (Format.flush_str_formatter ())
+ | _ -> ())
+ a ;
+*)
+ let lbls = Array.make (Array.length acts) 0 in
+ for i = Array.length acts-1 downto 0 do
+ let lbl,c1 = label_code (comp_expr env acts.(i) sz (branch :: !c)) in
+ lbls.(i) <- lbl ;
+ c := discard_dead_code c1
+ done ;
+
+(* Build label vectors *)
+ let lbl_blocks = Array.make sw.sw_numblocks 0 in
+ for i = sw.sw_numblocks - 1 downto 0 do
+ lbl_blocks.(i) <- lbls.(act_blocks.(i))
+ done;
+ let lbl_consts = Array.make sw.sw_numconsts 0 in
+ for i = sw.sw_numconsts - 1 downto 0 do
+ lbl_consts.(i) <- lbls.(act_consts.(i))
+ done;
+ comp_expr env arg sz (Kswitch(lbl_consts, lbl_blocks) :: !c)
+ | Lstringswitch (arg,sw,d) ->
+ comp_expr env (Matching.expand_stringswitch arg sw d) sz cont
+ | Lassign(id, expr) ->
+ begin try
+ let pos = Ident.find_same id env.ce_stack in
+ comp_expr env expr sz (Kassign(sz - pos) :: cont)
+ with Not_found ->
+ fatal_error "Bytegen.comp_expr: assign"
+ end
+ | Levent(lam, lev) ->
+ let event kind info =
+ { ev_pos = 0; (* patched in emitcode *)
+ ev_module = !compunit_name;
+ ev_loc = lev.lev_loc;
+ ev_kind = kind;
+ ev_info = info;
+ ev_typenv = lev.lev_env;
+ ev_typsubst = Subst.identity;
+ ev_compenv = env;
+ ev_stacksize = sz;
+ ev_repr =
+ begin match lev.lev_repr with
+ None ->
+ Event_none
+ | Some ({contents = 1} as repr) when lev.lev_kind = Lev_function ->
+ Event_child repr
+ | Some ({contents = 1} as repr) ->
+ Event_parent repr
+ | Some repr when lev.lev_kind = Lev_function ->
+ Event_parent repr
+ | Some repr ->
+ Event_child repr
+ end }
+ in
+ begin match lev.lev_kind with
+ Lev_before ->
+ let c = comp_expr env lam sz cont in
+ let ev = event Event_before Event_other in
+ add_event ev c
+ | Lev_function ->
+ let c = comp_expr env lam sz cont in
+ let ev = event Event_pseudo Event_function in
+ add_event ev c
+ | Lev_after _ when is_tailcall cont -> (* don't destroy tail call opt *)
+ comp_expr env lam sz cont
+ | Lev_after ty ->
+ let info =
+ match lam with
+ Lapply(_, args, _) -> Event_return (List.length args)
+ | Lsend(_, _, _, args, _) -> Event_return (List.length args + 1)
+ | _ -> Event_other
+ in
+ let ev = event (Event_after ty) info in
+ let cont1 = add_event ev cont in
+ comp_expr env lam sz cont1
+ end
+ | Lifused (_, exp) ->
+ comp_expr env exp sz cont
+
+(* Compile a list of arguments [e1; ...; eN] to a primitive operation.
+ The values of eN ... e2 are pushed on the stack, e2 at top of stack,
+ then e3, then ... The value of e1 is left in the accumulator. *)
+
+and comp_args env argl sz cont =
+ comp_expr_list env (List.rev argl) sz cont
+
+and comp_expr_list env exprl sz cont = match exprl with
+ [] -> cont
+ | [exp] -> comp_expr env exp sz cont
+ | exp :: rem ->
+ comp_expr env exp sz (Kpush :: comp_expr_list env rem (sz+1) cont)
+
+and comp_exit_args env argl sz pos cont =
+ comp_expr_list_assign env (List.rev argl) sz pos cont
+
+and comp_expr_list_assign env exprl sz pos cont = match exprl with
+ | [] -> cont
+ | exp :: rem ->
+ comp_expr env exp sz
+ (Kassign (sz-pos)::comp_expr_list_assign env rem sz (pos-1) cont)
+
+(* Compile an if-then-else test. *)
+
+and comp_binary_test env cond ifso ifnot sz cont =
+ let cont_cond =
+ if ifnot = Lconst const_unit then begin
+ let (lbl_end, cont1) = label_code cont in
+ Kstrictbranchifnot lbl_end :: comp_expr env ifso sz cont1
+ end else
+ match code_as_jump ifso sz with
+ | Some label ->
+ let cont = comp_expr env ifnot sz cont in
+ Kbranchif label :: cont
+ | _ ->
+ match code_as_jump ifnot sz with
+ | Some label ->
+ let cont = comp_expr env ifso sz cont in
+ Kbranchifnot label :: cont
+ | _ ->
+ let (branch_end, cont1) = make_branch cont in
+ let (lbl_not, cont2) = label_code(comp_expr env ifnot sz cont1) in
+ Kbranchifnot lbl_not ::
+ comp_expr env ifso sz (branch_end :: cont2) in
+
+ comp_expr env cond sz cont_cond
+
+(* Compile string switch *)
+
+and comp_string_switch env arg cases default sz cont = ()
+
+(**** Compilation of a code block (with tracking of stack usage) ****)
+
+let comp_block env exp sz cont =
+ max_stack_used := 0;
+ let code = comp_expr env exp sz cont in
+ (* +1 because comp_expr may have pushed one more word *)
+ if !max_stack_used + 1 > Config.stack_threshold then
+ Kconst(Const_base(Const_int(!max_stack_used + 1))) ::
+ Kccall("caml_ensure_stack_capacity", 1) ::
+ code
+ else
+ code
+
+(**** Compilation of functions ****)
+
+let comp_function tc cont =
+ let arity = List.length tc.params in
+ let rec positions pos delta = function
+ [] -> Ident.empty
+ | id :: rem -> Ident.add id pos (positions (pos + delta) delta rem) in
+ let env =
+ { ce_stack = positions arity (-1) tc.params;
+ ce_heap = positions (2 * (tc.num_defs - tc.rec_pos) - 1) 1 tc.free_vars;
+ ce_rec = positions (-2 * tc.rec_pos) 2 tc.rec_vars } in
+ let cont =
+ comp_block env tc.body arity (Kreturn arity :: cont) in
+ if arity > 1 then
+ Krestart :: Klabel tc.label :: Kgrab(arity - 1) :: cont
+ else
+ Klabel tc.label :: cont
+
+let comp_remainder cont =
+ let c = ref cont in
+ begin try
+ while true do
+ c := comp_function (Stack.pop functions_to_compile) !c
+ done
+ with Stack.Empty ->
+ ()
+ end;
+ !c
+
+(**** Compilation of a lambda phrase ****)
+
+let compile_implementation modulename expr =
+ Stack.clear functions_to_compile;
+ label_counter := 0;
+ sz_static_raises := [] ;
+ compunit_name := modulename;
+ let init_code = comp_block empty_env expr 0 [] in
+ if Stack.length functions_to_compile > 0 then begin
+ let lbl_init = new_label() in
+ Kbranch lbl_init :: comp_remainder (Klabel lbl_init :: init_code)
+ end else
+ init_code
+
+let compile_phrase expr =
+ Stack.clear functions_to_compile;
+ label_counter := 0;
+ sz_static_raises := [] ;
+ let init_code = comp_block empty_env expr 1 [Kreturn 1] in
+ let fun_code = comp_remainder [] in
+ (init_code, fun_code)
+
+let reset () =
+ label_counter := 0;
+ sz_static_raises := [];
+ compunit_name := "";
+ Stack.clear functions_to_compile;
+ max_stack_used := 0
diff --git a/bytecomp/bytegen.mli b/bytecomp/bytegen.mli
new file mode 100644
index 0000000000..24f1d64f32
--- /dev/null
+++ b/bytecomp/bytegen.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Generation of bytecode from lambda terms *)
+
+open Lambda
+open Instruct
+
+val compile_implementation: string -> lambda -> instruction list
+val compile_phrase: lambda -> instruction list * instruction list
+val reset: unit -> unit
diff --git a/bytecomp/bytelibrarian.ml b/bytecomp/bytelibrarian.ml
new file mode 100644
index 0000000000..7c96dfd0e7
--- /dev/null
+++ b/bytecomp/bytelibrarian.ml
@@ -0,0 +1,131 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Build libraries of .cmo files *)
+
+open Misc
+open Config
+open Cmo_format
+
+type error =
+ File_not_found of string
+ | Not_an_object_file of string
+
+exception Error of error
+
+(* Copy a compilation unit from a .cmo or .cma into the archive *)
+let copy_compunit ic oc compunit =
+ seek_in ic compunit.cu_pos;
+ compunit.cu_pos <- pos_out oc;
+ compunit.cu_force_link <- !Clflags.link_everything;
+ copy_file_chunk ic oc compunit.cu_codesize;
+ if compunit.cu_debug > 0 then begin
+ seek_in ic compunit.cu_debug;
+ compunit.cu_debug <- pos_out oc;
+ copy_file_chunk ic oc compunit.cu_debugsize
+ end
+
+(* Add C objects and options and "custom" info from a library descriptor *)
+
+let lib_ccobjs = ref []
+let lib_ccopts = ref []
+let lib_dllibs = ref []
+
+(* See Bytelink.add_ccobjs for explanations on how options are ordered.
+ Notice that here we scan .cma files given on the command line from
+ left to right, hence options must be added after. *)
+
+let add_ccobjs l =
+ if not !Clflags.no_auto_link then begin
+ if l.lib_custom then Clflags.custom_runtime := true;
+ lib_ccobjs := !lib_ccobjs @ l.lib_ccobjs;
+ lib_ccopts := !lib_ccopts @ l.lib_ccopts;
+ lib_dllibs := !lib_dllibs @ l.lib_dllibs
+ end
+
+let copy_object_file ppf oc name =
+ let file_name =
+ try
+ find_in_path !load_path name
+ with Not_found ->
+ raise(Error(File_not_found name)) in
+ let ic = open_in_bin file_name in
+ try
+ let buffer = really_input_string ic (String.length cmo_magic_number) in
+ if buffer = cmo_magic_number then begin
+ let compunit_pos = input_binary_int ic in
+ seek_in ic compunit_pos;
+ let compunit = (input_value ic : compilation_unit) in
+ Bytelink.check_consistency ppf file_name compunit;
+ copy_compunit ic oc compunit;
+ close_in ic;
+ [compunit]
+ end else
+ if buffer = cma_magic_number then begin
+ let toc_pos = input_binary_int ic in
+ seek_in ic toc_pos;
+ let toc = (input_value ic : library) in
+ List.iter (Bytelink.check_consistency ppf file_name) toc.lib_units;
+ add_ccobjs toc;
+ List.iter (copy_compunit ic oc) toc.lib_units;
+ close_in ic;
+ toc.lib_units
+ end else
+ raise(Error(Not_an_object_file file_name))
+ with
+ End_of_file -> close_in ic; raise(Error(Not_an_object_file file_name))
+ | x -> close_in ic; raise x
+
+let create_archive ppf file_list lib_name =
+ let outchan = open_out_bin lib_name in
+ try
+ output_string outchan cma_magic_number;
+ let ofs_pos_toc = pos_out outchan in
+ output_binary_int outchan 0;
+ let units =
+ List.flatten(List.map (copy_object_file ppf outchan) file_list) in
+ let toc =
+ { lib_units = units;
+ lib_custom = !Clflags.custom_runtime;
+ lib_ccobjs = !Clflags.ccobjs @ !lib_ccobjs;
+ lib_ccopts = !Clflags.all_ccopts @ !lib_ccopts;
+ lib_dllibs = !Clflags.dllibs @ !lib_dllibs } in
+ let pos_toc = pos_out outchan in
+ output_value outchan toc;
+ seek_out outchan ofs_pos_toc;
+ output_binary_int outchan pos_toc;
+ close_out outchan
+ with x ->
+ close_out outchan;
+ remove_file lib_name;
+ raise x
+
+open Format
+
+let report_error ppf = function
+ | File_not_found name ->
+ fprintf ppf "Cannot find file %s" name
+ | Not_an_object_file name ->
+ fprintf ppf "The file %a is not a bytecode object file"
+ Location.print_filename name
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
+
+let reset () =
+ lib_ccobjs := [];
+ lib_ccopts := [];
+ lib_dllibs := []
diff --git a/bytecomp/bytelibrarian.mli b/bytecomp/bytelibrarian.mli
new file mode 100644
index 0000000000..b9a4ced849
--- /dev/null
+++ b/bytecomp/bytelibrarian.mli
@@ -0,0 +1,34 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Build libraries of .cmo files *)
+
+(* Format of a library file:
+ magic number (Config.cma_magic_number)
+ absolute offset of content table
+ blocks of relocatable bytecode
+ content table = list of compilation units
+*)
+
+val create_archive: Format.formatter -> string list -> string -> unit
+
+type error =
+ File_not_found of string
+ | Not_an_object_file of string
+
+exception Error of error
+
+open Format
+
+val report_error: formatter -> error -> unit
+
+val reset: unit -> unit
diff --git a/bytecomp/bytelink.ml b/bytecomp/bytelink.ml
new file mode 100644
index 0000000000..2ea3f689b7
--- /dev/null
+++ b/bytecomp/bytelink.ml
@@ -0,0 +1,674 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Link a set of .cmo files and produce a bytecode executable. *)
+
+open Misc
+open Config
+open Cmo_format
+
+type error =
+ File_not_found of string
+ | Not_an_object_file of string
+ | Wrong_object_name of string
+ | Symbol_error of string * Symtable.error
+ | Inconsistent_import of string * string * string
+ | Custom_runtime
+ | File_exists of string
+ | Cannot_open_dll of string
+ | Not_compatible_32
+
+exception Error of error
+
+type link_action =
+ Link_object of string * compilation_unit
+ (* Name of .cmo file and descriptor of the unit *)
+ | Link_archive of string * compilation_unit list
+ (* Name of .cma file and descriptors of the units to be linked. *)
+
+(* Add C objects and options from a library descriptor *)
+(* Ignore them if -noautolink or -use-runtime or -use-prim was given *)
+
+let lib_ccobjs = ref []
+let lib_ccopts = ref []
+let lib_dllibs = ref []
+
+let add_ccobjs origin l =
+ if not !Clflags.no_auto_link then begin
+ if
+ String.length !Clflags.use_runtime = 0
+ && String.length !Clflags.use_prims = 0
+ then begin
+ if l.lib_custom then Clflags.custom_runtime := true;
+ lib_ccobjs := l.lib_ccobjs @ !lib_ccobjs;
+ let replace_origin =
+ Misc.replace_substring ~before:"$CAMLORIGIN" ~after:origin
+ in
+ lib_ccopts := List.map replace_origin l.lib_ccopts @ !lib_ccopts;
+ end;
+ lib_dllibs := l.lib_dllibs @ !lib_dllibs
+ end
+
+(* A note on ccobj ordering:
+ - Clflags.ccobjs is in reverse order w.r.t. what was given on the
+ ocamlc command line;
+ - l.lib_ccobjs is also in reverse order w.r.t. what was given on the
+ ocamlc -a command line when the library was created;
+ - Clflags.ccobjs is reversed just before calling the C compiler for the
+ custom link;
+ - .cma files on the command line of ocamlc are scanned right to left;
+ - Before linking, we add lib_ccobjs after Clflags.ccobjs.
+ Thus, for ocamlc a.cma b.cma obj1 obj2
+ where a.cma was built with ocamlc -i ... obja1 obja2
+ and b.cma was built with ocamlc -i ... objb1 objb2
+ lib_ccobjs starts as [],
+ becomes objb2 objb1 when b.cma is scanned,
+ then obja2 obja1 objb2 objb1 when a.cma is scanned.
+ Clflags.ccobjs was initially obj2 obj1.
+ and is set to obj2 obj1 obja2 obja1 objb2 objb1.
+ Finally, the C compiler is given objb1 objb2 obja1 obja2 obj1 obj2,
+ which is what we need. (If b depends on a, a.cma must appear before
+ b.cma, but b's C libraries must appear before a's C libraries.)
+*)
+
+(* First pass: determine which units are needed *)
+
+module IdentSet =
+ Set.Make(struct
+ type t = Ident.t
+ let compare = compare
+ end)
+
+let missing_globals = ref IdentSet.empty
+
+let is_required (rel, pos) =
+ match rel with
+ Reloc_setglobal id ->
+ IdentSet.mem id !missing_globals
+ | _ -> false
+
+let add_required (rel, pos) =
+ match rel with
+ Reloc_getglobal id ->
+ missing_globals := IdentSet.add id !missing_globals
+ | _ -> ()
+
+let remove_required (rel, pos) =
+ match rel with
+ Reloc_setglobal id ->
+ missing_globals := IdentSet.remove id !missing_globals
+ | _ -> ()
+
+let scan_file obj_name tolink =
+ let file_name =
+ try
+ find_in_path !load_path obj_name
+ with Not_found ->
+ raise(Error(File_not_found obj_name)) in
+ let ic = open_in_bin file_name in
+ try
+ let buffer = really_input_string ic (String.length cmo_magic_number) in
+ if buffer = cmo_magic_number then begin
+ (* This is a .cmo file. It must be linked in any case.
+ Read the relocation information to see which modules it
+ requires. *)
+ let compunit_pos = input_binary_int ic in (* Go to descriptor *)
+ seek_in ic compunit_pos;
+ let compunit = (input_value ic : compilation_unit) in
+ close_in ic;
+ List.iter add_required compunit.cu_reloc;
+ Link_object(file_name, compunit) :: tolink
+ end
+ else if buffer = cma_magic_number then begin
+ (* This is an archive file. Each unit contained in it will be linked
+ in only if needed. *)
+ let pos_toc = input_binary_int ic in (* Go to table of contents *)
+ seek_in ic pos_toc;
+ let toc = (input_value ic : library) in
+ close_in ic;
+ add_ccobjs (Filename.dirname file_name) toc;
+ let required =
+ List.fold_right
+ (fun compunit reqd ->
+ if compunit.cu_force_link
+ || !Clflags.link_everything
+ || List.exists is_required compunit.cu_reloc
+ then begin
+ List.iter remove_required compunit.cu_reloc;
+ List.iter add_required compunit.cu_reloc;
+ compunit :: reqd
+ end else
+ reqd)
+ toc.lib_units [] in
+ Link_archive(file_name, required) :: tolink
+ end
+ else raise(Error(Not_an_object_file file_name))
+ with
+ End_of_file -> close_in ic; raise(Error(Not_an_object_file file_name))
+ | x -> close_in ic; raise x
+
+(* Second pass: link in the required units *)
+
+(* Consistency check between interfaces *)
+
+let crc_interfaces = Consistbl.create ()
+let interfaces = ref ([] : string list)
+let implementations_defined = ref ([] : (string * string) list)
+
+let check_consistency ppf file_name cu =
+ begin try
+ List.iter
+ (fun (name, crco) ->
+ interfaces := name :: !interfaces;
+ match crco with
+ None -> ()
+ | Some crc ->
+ if name = cu.cu_name
+ then Consistbl.set crc_interfaces name crc file_name
+ else Consistbl.check crc_interfaces name crc file_name)
+ cu.cu_imports
+ with Consistbl.Inconsistency(name, user, auth) ->
+ raise(Error(Inconsistent_import(name, user, auth)))
+ end;
+ begin try
+ let source = List.assoc cu.cu_name !implementations_defined in
+ Location.print_warning (Location.in_file file_name) ppf
+ (Warnings.Multiple_definition(cu.cu_name,
+ Location.show_filename file_name,
+ Location.show_filename source))
+ with Not_found -> ()
+ end;
+ implementations_defined :=
+ (cu.cu_name, file_name) :: !implementations_defined
+
+let extract_crc_interfaces () =
+ Consistbl.extract !interfaces crc_interfaces
+
+let clear_crc_interfaces () =
+ Consistbl.clear crc_interfaces;
+ interfaces := []
+
+(* Record compilation events *)
+
+let debug_info = ref ([] : (int * Instruct.debug_event list * string list) list)
+
+(* Link in a compilation unit *)
+
+let link_compunit ppf output_fun currpos_fun inchan file_name compunit =
+ check_consistency ppf file_name compunit;
+ seek_in inchan compunit.cu_pos;
+ let code_block = LongString.input_bytes inchan compunit.cu_codesize in
+ Symtable.ls_patch_object code_block compunit.cu_reloc;
+ if !Clflags.debug && compunit.cu_debug > 0 then begin
+ seek_in inchan compunit.cu_debug;
+ let debug_event_list : Instruct.debug_event list = input_value inchan in
+ let debug_dirs : string list = input_value inchan in
+ let file_path = Filename.dirname (Location.absolute_path file_name) in
+ let debug_dirs =
+ if List.mem file_path debug_dirs
+ then debug_dirs
+ else file_path :: debug_dirs in
+ debug_info := (currpos_fun(), debug_event_list, debug_dirs) :: !debug_info
+ end;
+ Array.iter output_fun code_block;
+ if !Clflags.link_everything then
+ List.iter Symtable.require_primitive compunit.cu_primitives
+
+(* Link in a .cmo file *)
+
+let link_object ppf output_fun currpos_fun file_name compunit =
+ let inchan = open_in_bin file_name in
+ try
+ link_compunit ppf output_fun currpos_fun inchan file_name compunit;
+ close_in inchan
+ with
+ Symtable.Error msg ->
+ close_in inchan; raise(Error(Symbol_error(file_name, msg)))
+ | x ->
+ close_in inchan; raise x
+
+(* Link in a .cma file *)
+
+let link_archive ppf output_fun currpos_fun file_name units_required =
+ let inchan = open_in_bin file_name in
+ try
+ List.iter
+ (fun cu ->
+ let name = file_name ^ "(" ^ cu.cu_name ^ ")" in
+ try
+ link_compunit ppf output_fun currpos_fun inchan name cu
+ with Symtable.Error msg ->
+ raise(Error(Symbol_error(name, msg))))
+ units_required;
+ close_in inchan
+ with x -> close_in inchan; raise x
+
+(* Link in a .cmo or .cma file *)
+
+let link_file ppf output_fun currpos_fun = function
+ Link_object(file_name, unit) ->
+ link_object ppf output_fun currpos_fun file_name unit
+ | Link_archive(file_name, units) ->
+ link_archive ppf output_fun currpos_fun file_name units
+
+(* Output the debugging information *)
+(* Format is:
+ <int32> number of event lists
+ <int32> offset of first event list
+ <output_value> first event list
+ ...
+ <int32> offset of last event list
+ <output_value> last event list *)
+
+let output_debug_info oc =
+ output_binary_int oc (List.length !debug_info);
+ List.iter
+ (fun (ofs, evl, debug_dirs) ->
+ output_binary_int oc ofs;
+ output_value oc evl;
+ output_value oc debug_dirs)
+ !debug_info;
+ debug_info := []
+
+(* Output a list of strings with 0-termination *)
+
+let output_stringlist oc l =
+ List.iter (fun s -> output_string oc s; output_byte oc 0) l
+
+(* Transform a file name into an absolute file name *)
+
+let make_absolute file =
+ if Filename.is_relative file
+ then Filename.concat (Sys.getcwd()) file
+ else file
+
+(* Create a bytecode executable file *)
+
+let link_bytecode ppf tolink exec_name standalone =
+ (* Avoid the case where the specified exec output file is the same as
+ one of the objects to be linked *)
+ List.iter (function
+ | Link_object(file_name, _) when file_name = exec_name ->
+ raise (Error (Wrong_object_name exec_name));
+ | _ -> ()) tolink;
+ Misc.remove_file exec_name; (* avoid permission problems, cf PR#1911 *)
+ let outchan =
+ open_out_gen [Open_wronly; Open_trunc; Open_creat; Open_binary]
+ 0o777 exec_name in
+ try
+ if standalone then begin
+ (* Copy the header *)
+ try
+ let header =
+ if String.length !Clflags.use_runtime > 0
+ then "camlheader_ur" else "camlheader" ^ !Clflags.runtime_variant in
+ let inchan = open_in_bin (find_in_path !load_path header) in
+ copy_file inchan outchan;
+ close_in inchan
+ with Not_found | Sys_error _ -> ()
+ end;
+ Bytesections.init_record outchan;
+ (* The path to the bytecode interpreter (in use_runtime mode) *)
+ if String.length !Clflags.use_runtime > 0 then begin
+ output_string outchan ("#!" ^ (make_absolute !Clflags.use_runtime));
+ output_char outchan '\n';
+ Bytesections.record outchan "RNTM"
+ end;
+ (* The bytecode *)
+ let start_code = pos_out outchan in
+ Symtable.init();
+ clear_crc_interfaces ();
+ let sharedobjs = List.map Dll.extract_dll_name !Clflags.dllibs in
+ let check_dlls = standalone && Config.target = Config.host in
+ if check_dlls then begin
+ (* Initialize the DLL machinery *)
+ Dll.init_compile !Clflags.no_std_include;
+ Dll.add_path !load_path;
+ try Dll.open_dlls Dll.For_checking sharedobjs
+ with Failure reason -> raise(Error(Cannot_open_dll reason))
+ end;
+ let output_fun = output_bytes outchan
+ and currpos_fun () = pos_out outchan - start_code in
+ List.iter (link_file ppf output_fun currpos_fun) tolink;
+ if check_dlls then Dll.close_all_dlls();
+ (* The final STOP instruction *)
+ output_byte outchan Opcodes.opSTOP;
+ output_byte outchan 0; output_byte outchan 0; output_byte outchan 0;
+ Bytesections.record outchan "CODE";
+ (* DLL stuff *)
+ if standalone then begin
+ (* The extra search path for DLLs *)
+ output_stringlist outchan !Clflags.dllpaths;
+ Bytesections.record outchan "DLPT";
+ (* The names of the DLLs *)
+ output_stringlist outchan sharedobjs;
+ Bytesections.record outchan "DLLS"
+ end;
+ (* The names of all primitives *)
+ Symtable.output_primitive_names outchan;
+ Bytesections.record outchan "PRIM";
+ (* The table of global data *)
+ begin try
+ Marshal.to_channel outchan (Symtable.initial_global_table())
+ (if !Clflags.bytecode_compatible_32
+ then [Marshal.Compat_32] else [])
+ with Failure _ ->
+ raise (Error Not_compatible_32)
+ end;
+ Bytesections.record outchan "DATA";
+ (* The map of global identifiers *)
+ Symtable.output_global_map outchan;
+ Bytesections.record outchan "SYMB";
+ (* CRCs for modules *)
+ output_value outchan (extract_crc_interfaces());
+ Bytesections.record outchan "CRCS";
+ (* Debug info *)
+ if !Clflags.debug then begin
+ output_debug_info outchan;
+ Bytesections.record outchan "DBUG"
+ end;
+ (* The table of contents and the trailer *)
+ Bytesections.write_toc_and_trailer outchan;
+ close_out outchan
+ with x ->
+ close_out outchan;
+ remove_file exec_name;
+ raise x
+
+(* Output a string as a C array of unsigned ints *)
+
+let output_code_string_counter = ref 0
+
+let output_code_string outchan code =
+ let pos = ref 0 in
+ let len = Bytes.length code in
+ while !pos < len do
+ let c1 = Char.code(Bytes.get code !pos) in
+ let c2 = Char.code(Bytes.get code (!pos + 1)) in
+ let c3 = Char.code(Bytes.get code (!pos + 2)) in
+ let c4 = Char.code(Bytes.get code (!pos + 3)) in
+ pos := !pos + 4;
+ Printf.fprintf outchan "0x%02x%02x%02x%02x, " c4 c3 c2 c1;
+ incr output_code_string_counter;
+ if !output_code_string_counter >= 6 then begin
+ output_char outchan '\n';
+ output_code_string_counter := 0
+ end
+ done
+
+(* Output a string as a C string *)
+
+let output_data_string outchan data =
+ let counter = ref 0 in
+ for i = 0 to String.length data - 1 do
+ Printf.fprintf outchan "%d, " (Char.code(data.[i]));
+ incr counter;
+ if !counter >= 12 then begin
+ output_string outchan "\n";
+ counter := 0
+ end
+ done
+
+(* Output a debug stub *)
+
+let output_cds_file outfile =
+ Misc.remove_file outfile;
+ let outchan =
+ open_out_gen [Open_wronly; Open_trunc; Open_creat; Open_binary]
+ 0o777 outfile in
+ try
+ Bytesections.init_record outchan;
+ (* The map of global identifiers *)
+ Symtable.output_global_map outchan;
+ Bytesections.record outchan "SYMB";
+ (* Debug info *)
+ output_debug_info outchan;
+ Bytesections.record outchan "DBUG";
+ (* The table of contents and the trailer *)
+ Bytesections.write_toc_and_trailer outchan;
+ close_out outchan
+ with x ->
+ close_out outchan;
+ remove_file outfile;
+ raise x
+
+(* Output a bytecode executable as a C file *)
+
+let link_bytecode_as_c ppf tolink outfile =
+ let outchan = open_out outfile in
+ begin try
+ (* The bytecode *)
+ output_string outchan "\
+#ifdef __cplusplus\
+\nextern \"C\" {\
+\n#endif\
+\n#include <caml/mlvalues.h>\
+\nCAMLextern void caml_startup_code(\
+\n code_t code, asize_t code_size,\
+\n char *data, asize_t data_size,\
+\n char *section_table, asize_t section_table_size,\
+\n char **argv);\n";
+ output_string outchan "static int caml_code[] = {\n";
+ Symtable.init();
+ clear_crc_interfaces ();
+ let currpos = ref 0 in
+ let output_fun code =
+ output_code_string outchan code;
+ currpos := !currpos + Bytes.length code
+ and currpos_fun () = !currpos in
+ List.iter (link_file ppf output_fun currpos_fun) tolink;
+ (* The final STOP instruction *)
+ Printf.fprintf outchan "\n0x%x};\n\n" Opcodes.opSTOP;
+ (* The table of global data *)
+ output_string outchan "static char caml_data[] = {\n";
+ output_data_string outchan
+ (Marshal.to_string (Symtable.initial_global_table()) []);
+ output_string outchan "\n};\n\n";
+ (* The sections *)
+ let sections =
+ [ "SYMB", Symtable.data_global_map();
+ "PRIM", Obj.repr(Symtable.data_primitive_names());
+ "CRCS", Obj.repr(extract_crc_interfaces()) ] in
+ output_string outchan "static char caml_sections[] = {\n";
+ output_data_string outchan
+ (Marshal.to_string sections []);
+ output_string outchan "\n};\n\n";
+ (* The table of primitives *)
+ Symtable.output_primitive_table outchan;
+ (* The entry point *)
+ output_string outchan "\
+\nvoid caml_startup(char ** argv)\
+\n{\
+\n caml_startup_code(caml_code, sizeof(caml_code),\
+\n caml_data, sizeof(caml_data),\
+\n caml_sections, sizeof(caml_sections),\
+\n argv);\
+\n}\
+\n#ifdef __cplusplus\
+\n}\
+\n#endif\n";
+ close_out outchan
+ with x ->
+ close_out outchan;
+ remove_file outfile;
+ raise x
+ end;
+ if !Clflags.debug then
+ output_cds_file ((Filename.chop_extension outfile) ^ ".cds")
+
+(* Build a custom runtime *)
+
+let build_custom_runtime prim_name exec_name =
+ let runtime_lib = "-lcamlrun" ^ !Clflags.runtime_variant in
+ Ccomp.call_linker Ccomp.Exe exec_name
+ ([prim_name] @ List.rev !Clflags.ccobjs @ [runtime_lib])
+ (Clflags.std_include_flag "-I" ^ " " ^ Config.bytecomp_c_libraries)
+
+let append_bytecode_and_cleanup bytecode_name exec_name prim_name =
+ let oc = open_out_gen [Open_wronly; Open_append; Open_binary] 0 exec_name in
+ let ic = open_in_bin bytecode_name in
+ copy_file ic oc;
+ close_in ic;
+ close_out oc;
+ remove_file bytecode_name;
+ remove_file prim_name
+
+(* Fix the name of the output file, if the C compiler changes it behind
+ our back. *)
+
+let fix_exec_name name =
+ match Sys.os_type with
+ "Win32" | "Cygwin" ->
+ if String.contains name '.' then name else name ^ ".exe"
+ | _ -> name
+
+(* Main entry point (build a custom runtime if needed) *)
+
+let link ppf objfiles output_name =
+ let objfiles =
+ if !Clflags.nopervasives then objfiles
+ else if !Clflags.output_c_object then "stdlib.cma" :: objfiles
+ else "stdlib.cma" :: (objfiles @ ["std_exit.cmo"]) in
+ let tolink = List.fold_right scan_file objfiles [] in
+ Clflags.ccobjs := !Clflags.ccobjs @ !lib_ccobjs; (* put user's libs last *)
+ Clflags.all_ccopts := !lib_ccopts @ !Clflags.all_ccopts;
+ (* put user's opts first *)
+ Clflags.dllibs := !lib_dllibs @ !Clflags.dllibs; (* put user's DLLs first *)
+ if not !Clflags.custom_runtime then
+ link_bytecode ppf tolink output_name true
+ else if not !Clflags.output_c_object then begin
+ let bytecode_name = Filename.temp_file "camlcode" "" in
+ let prim_name = Filename.temp_file "camlprim" ".c" in
+ try
+ link_bytecode ppf tolink bytecode_name false;
+ let poc = open_out prim_name in
+ output_string poc "\
+ #ifdef __cplusplus\n\
+ extern \"C\" {\n\
+ #endif\n\
+ #ifdef _WIN64\n\
+ #ifdef __MINGW32__\n\
+ typedef long long value;\n\
+ #else\n\
+ typedef __int64 value;\n\
+ #endif\n\
+ #else\n\
+ typedef long value;\n\
+ #endif\n";
+ Symtable.output_primitive_table poc;
+ output_string poc "\
+ #ifdef __cplusplus\n\
+ }\n\
+ #endif\n";
+ close_out poc;
+ let exec_name = fix_exec_name output_name in
+ if not (build_custom_runtime prim_name exec_name)
+ then raise(Error Custom_runtime);
+ if !Clflags.make_runtime
+ then (remove_file bytecode_name; remove_file prim_name)
+ else append_bytecode_and_cleanup bytecode_name exec_name prim_name
+ with x ->
+ remove_file bytecode_name;
+ remove_file prim_name;
+ raise x
+ end else begin
+ let basename = Filename.chop_extension output_name in
+ let c_file =
+ if !Clflags.output_complete_object
+ then Filename.temp_file "camlobj" ".c"
+ else basename ^ ".c"
+ and obj_file =
+ if !Clflags.output_complete_object
+ then Filename.temp_file "camlobj" Config.ext_obj
+ else basename ^ Config.ext_obj
+ in
+ if Sys.file_exists c_file then raise(Error(File_exists c_file));
+ let temps = ref [] in
+ try
+ link_bytecode_as_c ppf tolink c_file;
+ if not (Filename.check_suffix output_name ".c") then begin
+ temps := c_file :: !temps;
+ if Ccomp.compile_file ~output_name:(Some obj_file) c_file <> 0 then
+ raise(Error Custom_runtime);
+ if not (Filename.check_suffix output_name Config.ext_obj) ||
+ !Clflags.output_complete_object then begin
+ temps := obj_file :: !temps;
+ let mode, c_libs =
+ if Filename.check_suffix output_name Config.ext_obj
+ then Ccomp.Partial, ""
+ else Ccomp.MainDll, Config.bytecomp_c_libraries
+ in
+ if not (
+ let runtime_lib = "-lcamlrun" ^ !Clflags.runtime_variant in
+ Ccomp.call_linker mode output_name
+ ([obj_file] @ List.rev !Clflags.ccobjs @ [runtime_lib])
+ c_libs
+ ) then raise (Error Custom_runtime);
+ end
+ end;
+ List.iter remove_file !temps
+ with x ->
+ List.iter remove_file !temps;
+ raise x
+ end
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | File_not_found name ->
+ fprintf ppf "Cannot find file %a" Location.print_filename name
+ | Not_an_object_file name ->
+ fprintf ppf "The file %a is not a bytecode object file"
+ Location.print_filename name
+ | Wrong_object_name name ->
+ fprintf ppf "The output file %s has the wrong name. The extension implies\
+ \ an object file but the link step was requested" name
+ | Symbol_error(name, err) ->
+ fprintf ppf "Error while linking %a:@ %a" Location.print_filename name
+ Symtable.report_error err
+ | Inconsistent_import(intf, file1, file2) ->
+ fprintf ppf
+ "@[<hov>Files %a@ and %a@ \
+ make inconsistent assumptions over interface %s@]"
+ Location.print_filename file1
+ Location.print_filename file2
+ intf
+ | Custom_runtime ->
+ fprintf ppf "Error while building custom runtime system"
+ | File_exists file ->
+ fprintf ppf "Cannot overwrite existing file %a"
+ Location.print_filename file
+ | Cannot_open_dll file ->
+ fprintf ppf "Error on dynamically loaded library: %a"
+ Location.print_filename file
+ | Not_compatible_32 ->
+ fprintf ppf "Generated bytecode executable cannot be run\
+ \ on a 32-bit platform"
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
+
+let reset () =
+ lib_ccobjs := [];
+ lib_ccopts := [];
+ lib_dllibs := [];
+ missing_globals := IdentSet.empty;
+ Consistbl.clear crc_interfaces;
+ implementations_defined := [];
+ debug_info := [];
+ output_code_string_counter := 0
diff --git a/bytecomp/bytelink.mli b/bytecomp/bytelink.mli
new file mode 100644
index 0000000000..37dad2b526
--- /dev/null
+++ b/bytecomp/bytelink.mli
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Link .cmo files and produce a bytecode executable. *)
+
+val link : Format.formatter -> string list -> string -> unit
+val reset : unit -> unit
+
+val check_consistency:
+ Format.formatter -> string -> Cmo_format.compilation_unit -> unit
+
+val extract_crc_interfaces: unit -> (string * Digest.t option) list
+
+type error =
+ File_not_found of string
+ | Not_an_object_file of string
+ | Wrong_object_name of string
+ | Symbol_error of string * Symtable.error
+ | Inconsistent_import of string * string * string
+ | Custom_runtime
+ | File_exists of string
+ | Cannot_open_dll of string
+ | Not_compatible_32
+
+exception Error of error
+
+open Format
+
+val report_error: formatter -> error -> unit
diff --git a/bytecomp/bytepackager.ml b/bytecomp/bytepackager.ml
new file mode 100644
index 0000000000..d8493ab322
--- /dev/null
+++ b/bytecomp/bytepackager.ml
@@ -0,0 +1,306 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* "Package" a set of .cmo files into one .cmo file having the
+ original compilation units as sub-modules. *)
+
+open Misc
+open Instruct
+open Cmo_format
+
+module StringSet = Set.Make(String)
+
+type error =
+ Forward_reference of string * Ident.t
+ | Multiple_definition of string * Ident.t
+ | Not_an_object_file of string
+ | Illegal_renaming of string * string * string
+ | File_not_found of string
+
+exception Error of error
+
+(* References accumulating information on the .cmo files *)
+
+let relocs = ref ([] : (reloc_info * int) list)
+let events = ref ([] : debug_event list)
+let debug_dirs = ref StringSet.empty
+let primitives = ref ([] : string list)
+let force_link = ref false
+
+(* Record a relocation. Update its offset, and rename GETGLOBAL and
+ SETGLOBAL relocations that correspond to one of the units being
+ consolidated. *)
+
+let rename_relocation packagename objfile mapping defined base (rel, ofs) =
+ let rel' =
+ match rel with
+ Reloc_getglobal id ->
+ begin try
+ let id' = List.assoc id mapping in
+ if List.mem id defined
+ then Reloc_getglobal id'
+ else raise(Error(Forward_reference(objfile, id)))
+ with Not_found ->
+ (* PR#5276: unique-ize dotted global names, which appear
+ if one of the units being consolidated is itself a packed
+ module. *)
+ let name = Ident.name id in
+ if String.contains name '.' then
+ Reloc_getglobal (Ident.create_persistent (packagename ^ "." ^ name))
+ else
+ rel
+ end
+ | Reloc_setglobal id ->
+ begin try
+ let id' = List.assoc id mapping in
+ if List.mem id defined
+ then raise(Error(Multiple_definition(objfile, id)))
+ else Reloc_setglobal id'
+ with Not_found ->
+ (* PR#5276, as above *)
+ let name = Ident.name id in
+ if String.contains name '.' then
+ Reloc_setglobal (Ident.create_persistent (packagename ^ "." ^ name))
+ else
+ rel
+ end
+ | _ ->
+ rel in
+ relocs := (rel', base + ofs) :: !relocs
+
+(* Record and relocate a debugging event *)
+
+let relocate_debug base prefix subst ev =
+ let ev' = { ev with ev_pos = base + ev.ev_pos;
+ ev_module = prefix ^ "." ^ ev.ev_module;
+ ev_typsubst = Subst.compose ev.ev_typsubst subst } in
+ events := ev' :: !events
+
+(* Read the unit information from a .cmo file. *)
+
+type pack_member_kind = PM_intf | PM_impl of compilation_unit
+
+type pack_member =
+ { pm_file: string;
+ pm_name: string;
+ pm_kind: pack_member_kind }
+
+let read_member_info file = (
+ let name =
+ String.capitalize_ascii(Filename.basename(chop_extensions file)) in
+ let kind =
+ if Filename.check_suffix file ".cmo" then begin
+ let ic = open_in_bin file in
+ try
+ let buffer =
+ really_input_string ic (String.length Config.cmo_magic_number)
+ in
+ if buffer <> Config.cmo_magic_number then
+ raise(Error(Not_an_object_file file));
+ let compunit_pos = input_binary_int ic in
+ seek_in ic compunit_pos;
+ let compunit = (input_value ic : compilation_unit) in
+ if compunit.cu_name <> name
+ then raise(Error(Illegal_renaming(name, file, compunit.cu_name)));
+ close_in ic;
+ PM_impl compunit
+ with x ->
+ close_in ic;
+ raise x
+ end else
+ PM_intf in
+ { pm_file = file; pm_name = name; pm_kind = kind }
+)
+
+(* Read the bytecode from a .cmo file.
+ Write bytecode to channel [oc].
+ Rename globals as indicated by [mapping] in reloc info.
+ Accumulate relocs, debug info, etc.
+ Return size of bytecode. *)
+
+let rename_append_bytecode ppf packagename oc mapping defined ofs prefix subst
+ objfile compunit =
+ let ic = open_in_bin objfile in
+ try
+ Bytelink.check_consistency ppf objfile compunit;
+ List.iter
+ (rename_relocation packagename objfile mapping defined ofs)
+ compunit.cu_reloc;
+ primitives := compunit.cu_primitives @ !primitives;
+ if compunit.cu_force_link then force_link := true;
+ seek_in ic compunit.cu_pos;
+ Misc.copy_file_chunk ic oc compunit.cu_codesize;
+ if !Clflags.debug && compunit.cu_debug > 0 then begin
+ seek_in ic compunit.cu_debug;
+ List.iter (relocate_debug ofs prefix subst) (input_value ic);
+ debug_dirs := List.fold_left
+ (fun s e -> StringSet.add e s)
+ !debug_dirs
+ (input_value ic);
+ end;
+ close_in ic;
+ compunit.cu_codesize
+ with x ->
+ close_in ic;
+ raise x
+
+(* Same, for a list of .cmo and .cmi files.
+ Return total size of bytecode. *)
+
+let rec rename_append_bytecode_list ppf packagename oc mapping defined ofs
+ prefix subst =
+ function
+ [] ->
+ ofs
+ | m :: rem ->
+ match m.pm_kind with
+ | PM_intf ->
+ rename_append_bytecode_list ppf packagename oc mapping defined ofs
+ prefix subst rem
+ | PM_impl compunit ->
+ let size =
+ rename_append_bytecode ppf packagename oc mapping defined ofs
+ prefix subst m.pm_file compunit in
+ let id = Ident.create_persistent m.pm_name in
+ let root = Path.Pident (Ident.create_persistent prefix) in
+ rename_append_bytecode_list ppf packagename oc mapping (id :: defined)
+ (ofs + size) prefix
+ (Subst.add_module id (Path.Pdot (root, Ident.name id, Path.nopos))
+ subst)
+ rem
+
+(* Generate the code that builds the tuple representing the package module *)
+
+let build_global_target oc target_name members mapping pos coercion =
+ let components =
+ List.map2
+ (fun m (id1, id2) ->
+ match m.pm_kind with
+ | PM_intf -> None
+ | PM_impl _ -> Some id2)
+ members mapping in
+ let lam =
+ Translmod.transl_package
+ components (Ident.create_persistent target_name) coercion in
+ if !Clflags.dump_lambda then
+ Format.printf "%a@." Printlambda.lambda lam;
+ let instrs =
+ Bytegen.compile_implementation target_name lam in
+ let rel =
+ Emitcode.to_packed_file oc instrs in
+ relocs := List.map (fun (r, ofs) -> (r, pos + ofs)) rel @ !relocs
+
+(* Build the .cmo file obtained by packaging the given .cmo files. *)
+
+let package_object_files ppf files targetfile targetname coercion =
+ let members =
+ map_left_right read_member_info files in
+ let unit_names =
+ List.map (fun m -> m.pm_name) members in
+ let mapping =
+ List.map
+ (fun name ->
+ (Ident.create_persistent name,
+ Ident.create_persistent(targetname ^ "." ^ name)))
+ unit_names in
+ let oc = open_out_bin targetfile in
+ try
+ output_string oc Config.cmo_magic_number;
+ let pos_depl = pos_out oc in
+ output_binary_int oc 0;
+ let pos_code = pos_out oc in
+ let ofs = rename_append_bytecode_list ppf targetname oc mapping [] 0
+ targetname Subst.identity members in
+ build_global_target oc targetname members mapping ofs coercion;
+ let pos_debug = pos_out oc in
+ if !Clflags.debug && !events <> [] then begin
+ output_value oc (List.rev !events);
+ output_value oc (StringSet.elements !debug_dirs);
+ end;
+ let pos_final = pos_out oc in
+ let imports =
+ List.filter
+ (fun (name, crc) -> not (List.mem name unit_names))
+ (Bytelink.extract_crc_interfaces()) in
+ let compunit =
+ { cu_name = targetname;
+ cu_pos = pos_code;
+ cu_codesize = pos_debug - pos_code;
+ cu_reloc = List.rev !relocs;
+ cu_imports =
+ (targetname, Some (Env.crc_of_unit targetname)) :: imports;
+ cu_primitives = !primitives;
+ cu_force_link = !force_link;
+ cu_debug = if pos_final > pos_debug then pos_debug else 0;
+ cu_debugsize = pos_final - pos_debug } in
+ output_value oc compunit;
+ seek_out oc pos_depl;
+ output_binary_int oc pos_final;
+ close_out oc
+ with x ->
+ close_out oc;
+ raise x
+
+(* The entry point *)
+
+let package_files ppf initial_env files targetfile =
+ let files =
+ List.map
+ (fun f ->
+ try find_in_path !Config.load_path f
+ with Not_found -> raise(Error(File_not_found f)))
+ files in
+ let prefix = chop_extensions targetfile in
+ let targetcmi = prefix ^ ".cmi" in
+ let targetname = String.capitalize_ascii(Filename.basename prefix) in
+ try
+ let coercion =
+ Typemod.package_units initial_env files targetcmi targetname in
+ let ret = package_object_files ppf files targetfile targetname coercion in
+ ret
+ with x ->
+ remove_file targetfile; raise x
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ Forward_reference(file, ident) ->
+ fprintf ppf "Forward reference to %s in file %a" (Ident.name ident)
+ Location.print_filename file
+ | Multiple_definition(file, ident) ->
+ fprintf ppf "File %a redefines %s"
+ Location.print_filename file
+ (Ident.name ident)
+ | Not_an_object_file file ->
+ fprintf ppf "%a is not a bytecode object file"
+ Location.print_filename file
+ | Illegal_renaming(name, file, id) ->
+ fprintf ppf "Wrong file naming: %a@ contains the code for\
+ @ %s when %s was expected"
+ Location.print_filename file name id
+ | File_not_found file ->
+ fprintf ppf "File %s not found" file
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
+
+let reset () =
+ relocs := [];
+ events := [];
+ primitives := [];
+ force_link := false
diff --git a/bytecomp/bytepackager.mli b/bytecomp/bytepackager.mli
new file mode 100644
index 0000000000..69e3c77acb
--- /dev/null
+++ b/bytecomp/bytepackager.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* "Package" a set of .cmo files into one .cmo file having the
+ original compilation units as sub-modules. *)
+
+val package_files: Format.formatter -> Env.t -> string list -> string -> unit
+
+type error =
+ Forward_reference of string * Ident.t
+ | Multiple_definition of string * Ident.t
+ | Not_an_object_file of string
+ | Illegal_renaming of string * string * string
+ | File_not_found of string
+
+exception Error of error
+
+val report_error: Format.formatter -> error -> unit
+val reset: unit -> unit
diff --git a/bytecomp/bytesections.ml b/bytecomp/bytesections.ml
new file mode 100644
index 0000000000..759bde3b29
--- /dev/null
+++ b/bytecomp/bytesections.ml
@@ -0,0 +1,98 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Handling of sections in bytecode executable files *)
+
+(* List of all sections, in reverse order *)
+
+let section_table = ref ([] : (string * int) list)
+
+(* Recording sections *)
+
+let section_beginning = ref 0
+
+let init_record outchan =
+ section_beginning := pos_out outchan;
+ section_table := []
+
+let record outchan name =
+ let pos = pos_out outchan in
+ section_table := (name, pos - !section_beginning) :: !section_table;
+ section_beginning := pos
+
+let write_toc_and_trailer outchan =
+ List.iter
+ (fun (name, len) ->
+ output_string outchan name; output_binary_int outchan len)
+ (List.rev !section_table);
+ output_binary_int outchan (List.length !section_table);
+ output_string outchan Config.exec_magic_number;
+ section_table := [];
+
+(* Read the table of sections from a bytecode executable *)
+
+exception Bad_magic_number
+
+let read_toc ic =
+ let pos_trailer = in_channel_length ic - 16 in
+ seek_in ic pos_trailer;
+ let num_sections = input_binary_int ic in
+ let header =
+ really_input_string ic (String.length Config.exec_magic_number)
+ in
+ if header <> Config.exec_magic_number then raise Bad_magic_number;
+ seek_in ic (pos_trailer - 8 * num_sections);
+ section_table := [];
+ for _i = 1 to num_sections do
+ let name = really_input_string ic 4 in
+ let len = input_binary_int ic in
+ section_table := (name, len) :: !section_table
+ done
+
+(* Return the current table of contents *)
+
+let toc () = List.rev !section_table
+
+(* Position ic at the beginning of the section named "name",
+ and return the length of that section. Raise Not_found if no
+ such section exists. *)
+
+let seek_section ic name =
+ let rec seek_sec curr_ofs = function
+ [] -> raise Not_found
+ | (n, len) :: rem ->
+ if n = name
+ then begin seek_in ic (curr_ofs - len); len end
+ else seek_sec (curr_ofs - len) rem in
+ seek_sec (in_channel_length ic - 16 - 8 * List.length !section_table)
+ !section_table
+
+(* Return the contents of a section, as a string *)
+
+let read_section_string ic name =
+ really_input_string ic (seek_section ic name)
+
+(* Return the contents of a section, as marshalled data *)
+
+let read_section_struct ic name =
+ ignore (seek_section ic name);
+ input_value ic
+
+(* Return the position of the beginning of the first section *)
+
+let pos_first_section ic =
+ in_channel_length ic - 16 - 8 * List.length !section_table -
+ List.fold_left (fun total (name, len) -> total + len) 0 !section_table
+
+let reset () =
+ section_table := [];
+ section_beginning := 0
diff --git a/bytecomp/bytesections.mli b/bytecomp/bytesections.mli
new file mode 100644
index 0000000000..12e679d73f
--- /dev/null
+++ b/bytecomp/bytesections.mli
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Handling of sections in bytecode executable files *)
+
+(** Recording sections written to a bytecode executable file *)
+
+val init_record: out_channel -> unit
+ (* Start recording sections from the current position in out_channel *)
+
+val record: out_channel -> string -> unit
+ (* Record the current position in the out_channel as the end of
+ the section with the given name *)
+
+val write_toc_and_trailer: out_channel -> unit
+ (* Write the table of contents and the standard trailer for bytecode
+ executable files *)
+
+(** Reading sections from a bytecode executable file *)
+
+val read_toc: in_channel -> unit
+ (* Read the table of sections from a bytecode executable *)
+
+exception Bad_magic_number
+ (* Raised by [read_toc] if magic number doesn't match *)
+
+val toc: unit -> (string * int) list
+ (* Return the current table of contents as a list of
+ (section name, section length) pairs. *)
+
+val seek_section: in_channel -> string -> int
+ (* Position the input channel at the beginning of the section named "name",
+ and return the length of that section. Raise Not_found if no
+ such section exists. *)
+
+val read_section_string: in_channel -> string -> string
+ (* Return the contents of a section, as a string *)
+
+val read_section_struct: in_channel -> string -> 'a
+ (* Return the contents of a section, as marshalled data *)
+
+val pos_first_section: in_channel -> int
+ (* Return the position of the beginning of the first section *)
+
+val reset: unit -> unit
diff --git a/bytecomp/cmo_format.mli b/bytecomp/cmo_format.mli
new file mode 100644
index 0000000000..0c0f08f080
--- /dev/null
+++ b/bytecomp/cmo_format.mli
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2006 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Symbol table information for .cmo and .cma files *)
+
+(* Relocation information *)
+
+type reloc_info =
+ Reloc_literal of Lambda.structured_constant (* structured constant *)
+ | Reloc_getglobal of Ident.t (* reference to a global *)
+ | Reloc_setglobal of Ident.t (* definition of a global *)
+ | Reloc_primitive of string (* C primitive number *)
+
+(* Descriptor for compilation units *)
+
+type compilation_unit =
+ { cu_name: string; (* Name of compilation unit *)
+ mutable cu_pos: int; (* Absolute position in file *)
+ cu_codesize: int; (* Size of code block *)
+ cu_reloc: (reloc_info * int) list; (* Relocation information *)
+ cu_imports:
+ (string * Digest.t option) list; (* Names and CRC of intfs imported *)
+ cu_primitives: string list; (* Primitives declared inside *)
+ mutable cu_force_link: bool; (* Must be linked even if unref'ed *)
+ mutable cu_debug: int; (* Position of debugging info, or 0 *)
+ cu_debugsize: int } (* Length of debugging info *)
+
+(* Format of a .cmo file:
+ magic number (Config.cmo_magic_number)
+ absolute offset of compilation unit descriptor
+ block of relocatable bytecode
+ debugging information if any
+ compilation unit descriptor *)
+
+(* Descriptor for libraries *)
+
+type library =
+ { lib_units: compilation_unit list; (* List of compilation units *)
+ lib_custom: bool; (* Requires custom mode linking? *)
+ lib_ccobjs: string list; (* C object files needed for -custom *)
+ lib_ccopts: string list; (* Extra opts to C compiler *)
+ lib_dllibs: string list } (* DLLs needed *)
+
+(* Format of a .cma file:
+ magic number (Config.cma_magic_number)
+ absolute offset of library descriptor
+ object code for first library member
+ ...
+ object code for last library member
+ library descriptor *)
diff --git a/bytecomp/dll.ml b/bytecomp/dll.ml
new file mode 100644
index 0000000000..21688e08ee
--- /dev/null
+++ b/bytecomp/dll.ml
@@ -0,0 +1,181 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Handling of dynamically-linked libraries *)
+
+type dll_handle
+type dll_address
+type dll_mode = For_checking | For_execution
+
+external dll_open: dll_mode -> string -> dll_handle = "caml_dynlink_open_lib"
+external dll_close: dll_handle -> unit = "caml_dynlink_close_lib"
+external dll_sym: dll_handle -> string -> dll_address
+ = "caml_dynlink_lookup_symbol"
+ (* returned dll_address may be Val_unit *)
+external add_primitive: dll_address -> int = "caml_dynlink_add_primitive"
+external get_current_dlls: unit -> dll_handle array
+ = "caml_dynlink_get_current_libs"
+
+(* Current search path for DLLs *)
+let search_path = ref ([] : string list)
+
+(* DLLs currently opened *)
+let opened_dlls = ref ([] : dll_handle list)
+
+(* File names for those DLLs *)
+let names_of_opened_dlls = ref ([] : string list)
+
+(* Add the given directories to the search path for DLLs. *)
+let add_path dirs =
+ search_path := dirs @ !search_path
+
+let remove_path dirs =
+ search_path := List.filter (fun d -> not (List.mem d dirs)) !search_path
+
+(* Extract the name of a DLLs from its external name (xxx.so or -lxxx) *)
+
+let extract_dll_name file =
+ if Filename.check_suffix file Config.ext_dll then
+ Filename.chop_suffix file Config.ext_dll
+ else if String.length file >= 2 && String.sub file 0 2 = "-l" then
+ "dll" ^ String.sub file 2 (String.length file - 2)
+ else
+ file (* will cause error later *)
+
+(* Open a list of DLLs, adding them to opened_dlls.
+ Raise [Failure msg] in case of error. *)
+
+let open_dll mode name =
+ let name = name ^ Config.ext_dll in
+ let fullname =
+ try
+ let fullname = Misc.find_in_path !search_path name in
+ if Filename.is_implicit fullname then
+ Filename.concat Filename.current_dir_name fullname
+ else fullname
+ with Not_found -> name in
+ if not (List.mem fullname !names_of_opened_dlls) then begin
+ try
+ let dll = dll_open mode fullname in
+ names_of_opened_dlls := fullname :: !names_of_opened_dlls;
+ opened_dlls := dll :: !opened_dlls
+ with Failure msg ->
+ failwith (fullname ^ ": " ^ msg)
+ end
+
+let open_dlls mode names =
+ List.iter (open_dll mode) names
+
+(* Close all DLLs *)
+
+let close_all_dlls () =
+ List.iter dll_close !opened_dlls;
+ opened_dlls := [];
+ names_of_opened_dlls := []
+
+(* Find a primitive in the currently opened DLLs.
+ Raise [Not_found] if not found. *)
+
+let find_primitive prim_name =
+ let rec find seen = function
+ [] ->
+ raise Not_found
+ | dll :: rem ->
+ let addr = dll_sym dll prim_name in
+ if addr == Obj.magic () then find (dll :: seen) rem else begin
+ if seen <> [] then opened_dlls := dll :: List.rev_append seen rem;
+ addr
+ end in
+ find [] !opened_dlls
+
+(* If linking in core (dynlink or toplevel), synchronize the VM
+ table of primitive with the linker's table of primitive
+ by storing the given primitive function at the given position
+ in the VM table of primitives. *)
+
+let linking_in_core = ref false
+
+let synchronize_primitive num symb =
+ if !linking_in_core then begin
+ let actual_num = add_primitive symb in
+ assert (actual_num = num)
+ end
+
+(* Read the [ld.conf] file and return the corresponding list of directories *)
+
+let ld_conf_contents () =
+ let path = ref [] in
+ begin try
+ let ic = open_in (Filename.concat Config.standard_library "ld.conf") in
+ begin try
+ while true do
+ path := input_line ic :: !path
+ done
+ with End_of_file -> ()
+ end;
+ close_in ic
+ with Sys_error _ -> ()
+ end;
+ List.rev !path
+
+(* Split the CAML_LD_LIBRARY_PATH environment variable and return
+ the corresponding list of directories. *)
+
+let split str sep =
+ let rec split_rec pos =
+ if pos >= String.length str then [] else begin
+ try
+ let newpos = String.index_from str pos sep in
+ String.sub str pos (newpos - pos) ::
+ split_rec (newpos + 1)
+ with Not_found ->
+ [String.sub str pos (String.length str - pos)]
+ end in
+ split_rec 0
+
+let ld_library_path_contents () =
+ let path_separator =
+ match Sys.os_type with
+ | "Unix" | "Cygwin" -> ':'
+ | "Win32" -> ';'
+ | _ -> assert false in
+ try
+ split (Sys.getenv "CAML_LD_LIBRARY_PATH") path_separator
+ with Not_found ->
+ []
+
+let split_dll_path path =
+ split path '\000'
+
+(* Initialization for separate compilation *)
+
+let init_compile nostdlib =
+ search_path :=
+ ld_library_path_contents() @
+ (if nostdlib then [] else ld_conf_contents())
+
+(* Initialization for linking in core (dynlink or toplevel) *)
+
+let init_toplevel dllpath =
+ search_path :=
+ ld_library_path_contents() @
+ split_dll_path dllpath @
+ ld_conf_contents();
+ opened_dlls := Array.to_list (get_current_dlls());
+ names_of_opened_dlls := [];
+ linking_in_core := true
+
+let reset () =
+ search_path := [];
+ opened_dlls :=[];
+ names_of_opened_dlls := [];
+ linking_in_core := false
diff --git a/bytecomp/dll.mli b/bytecomp/dll.mli
new file mode 100644
index 0000000000..878ffb919e
--- /dev/null
+++ b/bytecomp/dll.mli
@@ -0,0 +1,63 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Handling of dynamically-linked libraries *)
+
+(* Extract the name of a DLLs from its external name (xxx.so or -lxxx) *)
+val extract_dll_name: string -> string
+
+type dll_mode =
+ | For_checking (* will just check existence of symbols;
+ no need to do full symbol resolution *)
+ | For_execution (* will call functions from this DLL;
+ must resolve symbols completely *)
+
+(* Open a list of DLLs. First argument indicates whether to perform
+ full symbol resolution. Raise [Failure msg] in case of error. *)
+val open_dlls: dll_mode -> string list -> unit
+
+(* Close all DLLs *)
+val close_all_dlls: unit -> unit
+
+(* The abstract type representing C function pointers *)
+type dll_address
+
+(* Find a primitive in the currently opened DLLs and return its address.
+ Raise [Not_found] if not found. *)
+val find_primitive: string -> dll_address
+
+(* If linking in core (dynlink or toplevel), synchronize the VM
+ table of primitive with the linker's table of primitive
+ by storing the given primitive function at the given position
+ in the VM table of primitives. *)
+val synchronize_primitive: int -> dll_address -> unit
+
+(* Add the given directories at the head of the search path for DLLs *)
+val add_path: string list -> unit
+
+(* Remove the given directories from the search path for DLLs *)
+val remove_path: string list -> unit
+
+(* Initialization for separate compilation.
+ Initialize the DLL search path to the directories given in the
+ environment variable CAML_LD_LIBRARY_PATH, plus contents of ld.conf file
+ if argument is [false]. If argument is [true], ignore ld.conf. *)
+val init_compile: bool -> unit
+
+(* Initialization for linking in core (dynlink or toplevel).
+ Initialize the search path to the same path that was used to start
+ the running program (CAML_LD_LIBRARY_PATH + directories in executable +
+ contents of ld.conf file). Take note of the DLLs that were opened
+ when starting the running program. *)
+val init_toplevel: string -> unit
+
+val reset: unit -> unit
diff --git a/bytecomp/emitcode.ml b/bytecomp/emitcode.ml
new file mode 100644
index 0000000000..e8e428d481
--- /dev/null
+++ b/bytecomp/emitcode.ml
@@ -0,0 +1,431 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Generation of bytecode + relocation information *)
+
+open Config
+open Misc
+open Asttypes
+open Lambda
+open Instruct
+open Opcodes
+open Cmo_format
+
+module StringSet = Set.Make(String)
+
+(* Buffering of bytecode *)
+
+let out_buffer = ref(LongString.create 1024)
+and out_position = ref 0
+
+let out_word b1 b2 b3 b4 =
+ let p = !out_position in
+ if p >= LongString.length !out_buffer then begin
+ let len = LongString.length !out_buffer in
+ let new_buffer = LongString.create (2 * len) in
+ LongString.blit !out_buffer 0 new_buffer 0 len;
+ out_buffer := new_buffer
+ end;
+ LongString.set !out_buffer p (Char.unsafe_chr b1);
+ LongString.set !out_buffer (p+1) (Char.unsafe_chr b2);
+ LongString.set !out_buffer (p+2) (Char.unsafe_chr b3);
+ LongString.set !out_buffer (p+3) (Char.unsafe_chr b4);
+ out_position := p + 4
+
+let out opcode =
+ out_word opcode 0 0 0
+
+
+exception AsInt
+
+let const_as_int = function
+ | Const_base(Const_int i) -> i
+ | Const_base(Const_char c) -> Char.code c
+ | Const_pointer i -> i
+ | _ -> raise AsInt
+
+let is_immed i = immed_min <= i && i <= immed_max
+let is_immed_const k =
+ try
+ is_immed (const_as_int k)
+ with
+ | AsInt -> false
+
+
+let out_int n =
+ out_word n (n asr 8) (n asr 16) (n asr 24)
+
+let out_const c =
+ try
+ out_int (const_as_int c)
+ with
+ | AsInt -> Misc.fatal_error "Emitcode.const_as_int"
+
+
+(* Handling of local labels and backpatching *)
+
+type label_definition =
+ Label_defined of int
+ | Label_undefined of (int * int) list
+
+let label_table = ref ([| |] : label_definition array)
+
+let extend_label_table needed =
+ let new_size = ref(Array.length !label_table) in
+ while needed >= !new_size do new_size := 2 * !new_size done;
+ let new_table = Array.make !new_size (Label_undefined []) in
+ Array.blit !label_table 0 new_table 0 (Array.length !label_table);
+ label_table := new_table
+
+let backpatch (pos, orig) =
+ let displ = (!out_position - orig) asr 2 in
+ LongString.set !out_buffer pos (Char.unsafe_chr displ);
+ LongString.set !out_buffer (pos+1) (Char.unsafe_chr (displ asr 8));
+ LongString.set !out_buffer (pos+2) (Char.unsafe_chr (displ asr 16));
+ LongString.set !out_buffer (pos+3) (Char.unsafe_chr (displ asr 24))
+
+let define_label lbl =
+ if lbl >= Array.length !label_table then extend_label_table lbl;
+ match (!label_table).(lbl) with
+ Label_defined _ ->
+ fatal_error "Emitcode.define_label"
+ | Label_undefined patchlist ->
+ List.iter backpatch patchlist;
+ (!label_table).(lbl) <- Label_defined !out_position
+
+let out_label_with_orig orig lbl =
+ if lbl >= Array.length !label_table then extend_label_table lbl;
+ match (!label_table).(lbl) with
+ Label_defined def ->
+ out_int((def - orig) asr 2)
+ | Label_undefined patchlist ->
+ (!label_table).(lbl) <-
+ Label_undefined((!out_position, orig) :: patchlist);
+ out_int 0
+
+let out_label l = out_label_with_orig !out_position l
+
+(* Relocation information *)
+
+let reloc_info = ref ([] : (reloc_info * int) list)
+
+let enter info =
+ reloc_info := (info, !out_position) :: !reloc_info
+
+let slot_for_literal sc =
+ enter (Reloc_literal sc);
+ out_int 0
+and slot_for_getglobal id =
+ enter (Reloc_getglobal id);
+ out_int 0
+and slot_for_setglobal id =
+ enter (Reloc_setglobal id);
+ out_int 0
+and slot_for_c_prim name =
+ enter (Reloc_primitive name);
+ out_int 0
+
+(* Debugging events *)
+
+let events = ref ([] : debug_event list)
+let debug_dirs = ref StringSet.empty
+
+let record_event ev =
+ let path = ev.ev_loc.Location.loc_start.Lexing.pos_fname in
+ let abspath = Location.absolute_path path in
+ debug_dirs := StringSet.add (Filename.dirname abspath) !debug_dirs;
+ if Filename.is_relative path then
+ debug_dirs := StringSet.add (Sys.getcwd ()) !debug_dirs;
+ ev.ev_pos <- !out_position;
+ events := ev :: !events
+
+(* Initialization *)
+
+let init () =
+ out_position := 0;
+ label_table := Array.make 16 (Label_undefined []);
+ reloc_info := [];
+ debug_dirs := StringSet.empty;
+ events := []
+
+(* Emission of one instruction *)
+
+let emit_comp = function
+| Ceq -> out opEQ | Cneq -> out opNEQ
+| Clt -> out opLTINT | Cle -> out opLEINT
+| Cgt -> out opGTINT | Cge -> out opGEINT
+
+and emit_branch_comp = function
+| Ceq -> out opBEQ | Cneq -> out opBNEQ
+| Clt -> out opBLTINT | Cle -> out opBLEINT
+| Cgt -> out opBGTINT | Cge -> out opBGEINT
+
+let emit_instr = function
+ Klabel lbl -> define_label lbl
+ | Kacc n ->
+ if n < 8 then out(opACC0 + n) else (out opACC; out_int n)
+ | Kenvacc n ->
+ if n >= 1 && n <= 4
+ then out(opENVACC1 + n - 1)
+ else (out opENVACC; out_int n)
+ | Kpush ->
+ out opPUSH
+ | Kpop n ->
+ out opPOP; out_int n
+ | Kassign n ->
+ out opASSIGN; out_int n
+ | Kpush_retaddr lbl -> out opPUSH_RETADDR; out_label lbl
+ | Kapply n ->
+ if n < 4 then out(opAPPLY1 + n - 1) else (out opAPPLY; out_int n)
+ | Kappterm(n, sz) ->
+ if n < 4 then (out(opAPPTERM1 + n - 1); out_int sz)
+ else (out opAPPTERM; out_int n; out_int sz)
+ | Kreturn n -> out opRETURN; out_int n
+ | Krestart -> out opRESTART
+ | Kgrab n -> out opGRAB; out_int n
+ | Kclosure(lbl, n) -> out opCLOSURE; out_int n; out_label lbl
+ | Kclosurerec(lbls, n) ->
+ out opCLOSUREREC; out_int (List.length lbls); out_int n;
+ let org = !out_position in
+ List.iter (out_label_with_orig org) lbls
+ | Koffsetclosure ofs ->
+ if ofs = -2 || ofs = 0 || ofs = 2
+ then out (opOFFSETCLOSURE0 + ofs / 2)
+ else (out opOFFSETCLOSURE; out_int ofs)
+ | Kgetglobal q -> out opGETGLOBAL; slot_for_getglobal q
+ | Ksetglobal q -> out opSETGLOBAL; slot_for_setglobal q
+ | Kconst sc ->
+ begin match sc with
+ Const_base(Const_int i) when is_immed i ->
+ if i >= 0 && i <= 3
+ then out (opCONST0 + i)
+ else (out opCONSTINT; out_int i)
+ | Const_base(Const_char c) ->
+ out opCONSTINT; out_int (Char.code c)
+ | Const_pointer i ->
+ if i >= 0 && i <= 3
+ then out (opCONST0 + i)
+ else (out opCONSTINT; out_int i)
+ | Const_block(t, []) ->
+ if t = 0 then out opATOM0 else (out opATOM; out_int t)
+ | _ ->
+ out opGETGLOBAL; slot_for_literal sc
+ end
+ | Kmakeblock(n, t) ->
+ if n = 0 then
+ if t = 0 then out opATOM0 else (out opATOM; out_int t)
+ else if n < 4 then (out(opMAKEBLOCK1 + n - 1); out_int t)
+ else (out opMAKEBLOCK; out_int n; out_int t)
+ | Kgetfield n ->
+ if n < 4 then out(opGETFIELD0 + n) else (out opGETFIELD; out_int n)
+ | Ksetfield n ->
+ if n < 4 then out(opSETFIELD0 + n) else (out opSETFIELD; out_int n)
+ | Kmakefloatblock(n) ->
+ if n = 0 then out opATOM0 else (out opMAKEFLOATBLOCK; out_int n)
+ | Kgetfloatfield n -> out opGETFLOATFIELD; out_int n
+ | Ksetfloatfield n -> out opSETFLOATFIELD; out_int n
+ | Kvectlength -> out opVECTLENGTH
+ | Kgetvectitem -> out opGETVECTITEM
+ | Ksetvectitem -> out opSETVECTITEM
+ | Kgetstringchar -> out opGETSTRINGCHAR
+ | Ksetstringchar -> out opSETSTRINGCHAR
+ | Kbranch lbl -> out opBRANCH; out_label lbl
+ | Kbranchif lbl -> out opBRANCHIF; out_label lbl
+ | Kbranchifnot lbl -> out opBRANCHIFNOT; out_label lbl
+ | Kstrictbranchif lbl -> out opBRANCHIF; out_label lbl
+ | Kstrictbranchifnot lbl -> out opBRANCHIFNOT; out_label lbl
+ | Kswitch(tbl_const, tbl_block) ->
+ out opSWITCH;
+ out_int (Array.length tbl_const + (Array.length tbl_block lsl 16));
+ let org = !out_position in
+ Array.iter (out_label_with_orig org) tbl_const;
+ Array.iter (out_label_with_orig org) tbl_block
+ | Kboolnot -> out opBOOLNOT
+ | Kpushtrap lbl -> out opPUSHTRAP; out_label lbl
+ | Kpoptrap -> out opPOPTRAP
+ | Kraise Raise_regular -> out opRAISE
+ | Kraise Raise_reraise -> out opRERAISE
+ | Kraise Raise_notrace -> out opRAISE_NOTRACE
+ | Kcheck_signals -> out opCHECK_SIGNALS
+ | Kccall(name, n) ->
+ if n <= 5
+ then (out (opC_CALL1 + n - 1); slot_for_c_prim name)
+ else (out opC_CALLN; out_int n; slot_for_c_prim name)
+ | Knegint -> out opNEGINT | Kaddint -> out opADDINT
+ | Ksubint -> out opSUBINT | Kmulint -> out opMULINT
+ | Kdivint -> out opDIVINT | Kmodint -> out opMODINT
+ | Kandint -> out opANDINT | Korint -> out opORINT
+ | Kxorint -> out opXORINT | Klslint -> out opLSLINT
+ | Klsrint -> out opLSRINT | Kasrint -> out opASRINT
+ | Kintcomp c -> emit_comp c
+ | Koffsetint n -> out opOFFSETINT; out_int n
+ | Koffsetref n -> out opOFFSETREF; out_int n
+ | Kisint -> out opISINT
+ | Kisout -> out opULTINT
+ | Kgetmethod -> out opGETMETHOD
+ | Kgetpubmet tag -> out opGETPUBMET; out_int tag; out_int 0
+ | Kgetdynmet -> out opGETDYNMET
+ | Kevent ev -> record_event ev
+ | Kstop -> out opSTOP
+
+(* Emission of a list of instructions. Include some peephole optimization. *)
+
+let rec emit = function
+ [] -> ()
+ (* Peephole optimizations *)
+(* optimization of integer tests *)
+ | Kpush::Kconst k::Kintcomp c::Kbranchif lbl::rem
+ when is_immed_const k ->
+ emit_branch_comp c ;
+ out_const k ;
+ out_label lbl ;
+ emit rem
+ | Kpush::Kconst k::Kintcomp c::Kbranchifnot lbl::rem
+ when is_immed_const k ->
+ emit_branch_comp (negate_comparison c) ;
+ out_const k ;
+ out_label lbl ;
+ emit rem
+(* same for range tests *)
+ | Kpush::Kconst k::Kisout::Kbranchif lbl::rem
+ when is_immed_const k ->
+ out opBULTINT ;
+ out_const k ;
+ out_label lbl ;
+ emit rem
+ | Kpush::Kconst k::Kisout::Kbranchifnot lbl::rem
+ when is_immed_const k ->
+ out opBUGEINT ;
+ out_const k ;
+ out_label lbl ;
+ emit rem
+(* Some special case of push ; i ; ret generated by the match compiler *)
+ | Kpush :: Kacc 0 :: Kreturn m :: c ->
+ emit (Kreturn (m-1) :: c)
+(* General push then access scheme *)
+ | Kpush :: Kacc n :: c ->
+ if n < 8 then out(opPUSHACC0 + n) else (out opPUSHACC; out_int n);
+ emit c
+ | Kpush :: Kenvacc n :: c ->
+ if n >= 1 && n < 4
+ then out(opPUSHENVACC1 + n - 1)
+ else (out opPUSHENVACC; out_int n);
+ emit c
+ | Kpush :: Koffsetclosure ofs :: c ->
+ if ofs = -2 || ofs = 0 || ofs = 2
+ then out(opPUSHOFFSETCLOSURE0 + ofs / 2)
+ else (out opPUSHOFFSETCLOSURE; out_int ofs);
+ emit c
+ | Kpush :: Kgetglobal id :: Kgetfield n :: c ->
+ out opPUSHGETGLOBALFIELD; slot_for_getglobal id; out_int n; emit c
+ | Kpush :: Kgetglobal id :: c ->
+ out opPUSHGETGLOBAL; slot_for_getglobal id; emit c
+ | Kpush :: Kconst sc :: c ->
+ begin match sc with
+ Const_base(Const_int i) when is_immed i ->
+ if i >= 0 && i <= 3
+ then out (opPUSHCONST0 + i)
+ else (out opPUSHCONSTINT; out_int i)
+ | Const_base(Const_char c) ->
+ out opPUSHCONSTINT; out_int(Char.code c)
+ | Const_pointer i ->
+ if i >= 0 && i <= 3
+ then out (opPUSHCONST0 + i)
+ else (out opPUSHCONSTINT; out_int i)
+ | Const_block(t, []) ->
+ if t = 0 then out opPUSHATOM0 else (out opPUSHATOM; out_int t)
+ | _ ->
+ out opPUSHGETGLOBAL; slot_for_literal sc
+ end;
+ emit c
+ | Kpush :: (Kevent {ev_kind = Event_before} as ev) ::
+ (Kgetglobal _ as instr1) :: (Kgetfield _ as instr2) :: c ->
+ emit (Kpush :: instr1 :: instr2 :: ev :: c)
+ | Kpush :: (Kevent {ev_kind = Event_before} as ev) ::
+ (Kacc _ | Kenvacc _ | Koffsetclosure _ | Kgetglobal _ | Kconst _ as instr)::
+ c ->
+ emit (Kpush :: instr :: ev :: c)
+ | Kgetglobal id :: Kgetfield n :: c ->
+ out opGETGLOBALFIELD; slot_for_getglobal id; out_int n; emit c
+ (* Default case *)
+ | instr :: c ->
+ emit_instr instr; emit c
+
+(* Emission to a file *)
+
+let to_file outchan unit_name objfile code =
+ init();
+ output_string outchan cmo_magic_number;
+ let pos_depl = pos_out outchan in
+ output_binary_int outchan 0;
+ let pos_code = pos_out outchan in
+ emit code;
+ LongString.output outchan !out_buffer 0 !out_position;
+ let (pos_debug, size_debug) =
+ if !Clflags.debug then begin
+ debug_dirs := StringSet.add
+ (Filename.dirname (Location.absolute_path objfile))
+ !debug_dirs;
+ let p = pos_out outchan in
+ output_value outchan !events;
+ output_value outchan (StringSet.elements !debug_dirs);
+ (p, pos_out outchan - p)
+ end else
+ (0, 0) in
+ let compunit =
+ { cu_name = unit_name;
+ cu_pos = pos_code;
+ cu_codesize = !out_position;
+ cu_reloc = List.rev !reloc_info;
+ cu_imports = Env.imports();
+ cu_primitives = List.map Primitive.byte_name
+ !Translmod.primitive_declarations;
+ cu_force_link = false;
+ cu_debug = pos_debug;
+ cu_debugsize = size_debug } in
+ init(); (* Free out_buffer and reloc_info *)
+ Btype.cleanup_abbrev (); (* Remove any cached abbreviation
+ expansion before saving *)
+ let pos_compunit = pos_out outchan in
+ output_value outchan compunit;
+ seek_out outchan pos_depl;
+ output_binary_int outchan pos_compunit
+
+(* Emission to a memory block *)
+
+let to_memory init_code fun_code =
+ init();
+ emit init_code;
+ emit fun_code;
+ let code = Meta.static_alloc !out_position in
+ LongString.unsafe_blit_to_bytes !out_buffer 0 code 0 !out_position;
+ let reloc = List.rev !reloc_info
+ and code_size = !out_position in
+ let events = !events in
+ init();
+ (code, code_size, reloc, events)
+
+(* Emission to a file for a packed library *)
+
+let to_packed_file outchan code =
+ init();
+ emit code;
+ LongString.output outchan !out_buffer 0 !out_position;
+ let reloc = !reloc_info in
+ init();
+ reloc
+
+let reset () =
+ out_buffer := LongString.create 1024;
+ out_position := 0;
+ label_table := [| |];
+ reloc_info := []
diff --git a/bytecomp/emitcode.mli b/bytecomp/emitcode.mli
new file mode 100644
index 0000000000..f9dea1cf4a
--- /dev/null
+++ b/bytecomp/emitcode.mli
@@ -0,0 +1,42 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Generation of bytecode for .cmo files *)
+
+open Cmo_format
+open Instruct
+
+val to_file: out_channel -> string -> string -> instruction list -> unit
+ (* Arguments:
+ channel on output file
+ name of compilation unit implemented
+ path of cmo file being written
+ list of instructions to emit *)
+val to_memory: instruction list -> instruction list ->
+ bytes * int * (reloc_info * int) list * debug_event list
+ (* Arguments:
+ initialization code (terminated by STOP)
+ function code
+ Results:
+ block of relocatable bytecode
+ size of this block
+ relocation information
+ debug events *)
+val to_packed_file:
+ out_channel -> instruction list -> (reloc_info * int) list
+ (* Arguments:
+ channel on output file
+ list of instructions to emit
+ Result:
+ relocation information (reversed) *)
+
+val reset: unit -> unit
diff --git a/bytecomp/instruct.ml b/bytecomp/instruct.ml
new file mode 100644
index 0000000000..70d6222990
--- /dev/null
+++ b/bytecomp/instruct.ml
@@ -0,0 +1,109 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Lambda
+
+type compilation_env =
+ { ce_stack: int Ident.tbl;
+ ce_heap: int Ident.tbl;
+ ce_rec: int Ident.tbl }
+
+type debug_event =
+ { mutable ev_pos: int; (* Position in bytecode *)
+ ev_module: string; (* Name of defining module *)
+ ev_loc: Location.t; (* Location in source file *)
+ ev_kind: debug_event_kind; (* Before/after event *)
+ ev_info: debug_event_info; (* Extra information *)
+ ev_typenv: Env.summary; (* Typing environment *)
+ ev_typsubst: Subst.t; (* Substitution over types *)
+ ev_compenv: compilation_env; (* Compilation environment *)
+ ev_stacksize: int; (* Size of stack frame *)
+ ev_repr: debug_event_repr } (* Position of the representative *)
+
+and debug_event_kind =
+ Event_before
+ | Event_after of Types.type_expr
+ | Event_pseudo
+
+and debug_event_info =
+ Event_function
+ | Event_return of int
+ | Event_other
+
+and debug_event_repr =
+ Event_none
+ | Event_parent of int ref
+ | Event_child of int ref
+
+type label = int (* Symbolic code labels *)
+
+type instruction =
+ Klabel of label
+ | Kacc of int
+ | Kenvacc of int
+ | Kpush
+ | Kpop of int
+ | Kassign of int
+ | Kpush_retaddr of label
+ | Kapply of int (* number of arguments *)
+ | Kappterm of int * int (* number of arguments, slot size *)
+ | Kreturn of int (* slot size *)
+ | Krestart
+ | Kgrab of int (* number of arguments *)
+ | Kclosure of label * int
+ | Kclosurerec of label list * int
+ | Koffsetclosure of int
+ | Kgetglobal of Ident.t
+ | Ksetglobal of Ident.t
+ | Kconst of structured_constant
+ | Kmakeblock of int * int (* size, tag *)
+ | Kmakefloatblock of int
+ | Kgetfield of int
+ | Ksetfield of int
+ | Kgetfloatfield of int
+ | Ksetfloatfield of int
+ | Kvectlength
+ | Kgetvectitem
+ | Ksetvectitem
+ | Kgetstringchar
+ | Ksetstringchar
+ | Kbranch of label
+ | Kbranchif of label
+ | Kbranchifnot of label
+ | Kstrictbranchif of label
+ | Kstrictbranchifnot of label
+ | Kswitch of label array * label array
+ | Kboolnot
+ | Kpushtrap of label
+ | Kpoptrap
+ | Kraise of raise_kind
+ | Kcheck_signals
+ | Kccall of string * int
+ | Knegint | Kaddint | Ksubint | Kmulint | Kdivint | Kmodint
+ | Kandint | Korint | Kxorint | Klslint | Klsrint | Kasrint
+ | Kintcomp of comparison
+ | Koffsetint of int
+ | Koffsetref of int
+ | Kisint
+ | Kisout
+ | Kgetmethod
+ | Kgetpubmet of int
+ | Kgetdynmet
+ | Kevent of debug_event
+ | Kstop
+
+let immed_min = -0x40000000
+and immed_max = 0x3FFFFFFF
+
+(* Actually the abstract machine accomodates -0x80000000 to 0x7FFFFFFF,
+ but these numbers overflow the OCaml type int if the compiler runs on
+ a 32-bit processor. *)
diff --git a/bytecomp/instruct.mli b/bytecomp/instruct.mli
new file mode 100644
index 0000000000..024dba13cc
--- /dev/null
+++ b/bytecomp/instruct.mli
@@ -0,0 +1,125 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The type of the instructions of the abstract machine *)
+
+open Lambda
+
+(* Structure of compilation environments *)
+
+type compilation_env =
+ { ce_stack: int Ident.tbl; (* Positions of variables in the stack *)
+ ce_heap: int Ident.tbl; (* Structure of the heap-allocated env *)
+ ce_rec: int Ident.tbl } (* Functions bound by the same let rec *)
+
+(* The ce_stack component gives locations of variables residing
+ in the stack. The locations are offsets w.r.t. the origin of the
+ stack frame.
+ The ce_heap component gives the positions of variables residing in the
+ heap-allocated environment.
+ The ce_rec component associate offsets to identifiers for functions
+ bound by the same let rec as the current function. The offsets
+ are used by the OFFSETCLOSURE instruction to recover the closure
+ pointer of the desired function from the env register (which
+ points to the closure for the current function). *)
+
+(* Debugging events *)
+
+(* Warning: when you change these types, check byterun/backtrace.c *)
+type debug_event =
+ { mutable ev_pos: int; (* Position in bytecode *)
+ ev_module: string; (* Name of defining module *)
+ ev_loc: Location.t; (* Location in source file *)
+ ev_kind: debug_event_kind; (* Before/after event *)
+ ev_info: debug_event_info; (* Extra information *)
+ ev_typenv: Env.summary; (* Typing environment *)
+ ev_typsubst: Subst.t; (* Substitution over types *)
+ ev_compenv: compilation_env; (* Compilation environment *)
+ ev_stacksize: int; (* Size of stack frame *)
+ ev_repr: debug_event_repr } (* Position of the representative *)
+
+and debug_event_kind =
+ Event_before
+ | Event_after of Types.type_expr
+ | Event_pseudo
+
+and debug_event_info =
+ Event_function
+ | Event_return of int
+ | Event_other
+
+and debug_event_repr =
+ Event_none
+ | Event_parent of int ref
+ | Event_child of int ref
+
+(* Abstract machine instructions *)
+
+type label = int (* Symbolic code labels *)
+
+type instruction =
+ Klabel of label
+ | Kacc of int
+ | Kenvacc of int
+ | Kpush
+ | Kpop of int
+ | Kassign of int
+ | Kpush_retaddr of label
+ | Kapply of int (* number of arguments *)
+ | Kappterm of int * int (* number of arguments, slot size *)
+ | Kreturn of int (* slot size *)
+ | Krestart
+ | Kgrab of int (* number of arguments *)
+ | Kclosure of label * int
+ | Kclosurerec of label list * int
+ | Koffsetclosure of int
+ | Kgetglobal of Ident.t
+ | Ksetglobal of Ident.t
+ | Kconst of structured_constant
+ | Kmakeblock of int * int (* size, tag *)
+ | Kmakefloatblock of int
+ | Kgetfield of int
+ | Ksetfield of int
+ | Kgetfloatfield of int
+ | Ksetfloatfield of int
+ | Kvectlength
+ | Kgetvectitem
+ | Ksetvectitem
+ | Kgetstringchar
+ | Ksetstringchar
+ | Kbranch of label
+ | Kbranchif of label
+ | Kbranchifnot of label
+ | Kstrictbranchif of label
+ | Kstrictbranchifnot of label
+ | Kswitch of label array * label array
+ | Kboolnot
+ | Kpushtrap of label
+ | Kpoptrap
+ | Kraise of raise_kind
+ | Kcheck_signals
+ | Kccall of string * int
+ | Knegint | Kaddint | Ksubint | Kmulint | Kdivint | Kmodint
+ | Kandint | Korint | Kxorint | Klslint | Klsrint | Kasrint
+ | Kintcomp of comparison
+ | Koffsetint of int
+ | Koffsetref of int
+ | Kisint
+ | Kisout
+ | Kgetmethod
+ | Kgetpubmet of int
+ | Kgetdynmet
+ | Kevent of debug_event
+ | Kstop
+
+val immed_min: int
+val immed_max: int
diff --git a/bytecomp/lambda.ml b/bytecomp/lambda.ml
new file mode 100644
index 0000000000..c080683eb8
--- /dev/null
+++ b/bytecomp/lambda.ml
@@ -0,0 +1,571 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Misc
+open Path
+open Asttypes
+
+type compile_time_constant =
+ | Big_endian
+ | Word_size
+ | Int_size
+ | Max_wosize
+ | Ostype_unix
+ | Ostype_win32
+ | Ostype_cygwin
+
+type loc_kind =
+ | Loc_FILE
+ | Loc_LINE
+ | Loc_MODULE
+ | Loc_LOC
+ | Loc_POS
+
+type primitive =
+ Pidentity
+ | Pignore
+ | Prevapply of Location.t
+ | Pdirapply of Location.t
+ | Ploc of loc_kind
+ (* Globals *)
+ | Pgetglobal of Ident.t
+ | Psetglobal of Ident.t
+ (* Operations on heap blocks *)
+ | Pmakeblock of int * mutable_flag
+ | Pfield of int
+ | Psetfield of int * bool
+ | Pfloatfield of int
+ | Psetfloatfield of int
+ | Pduprecord of Types.record_representation * int
+ (* Force lazy values *)
+ | Plazyforce
+ (* External call *)
+ | Pccall of Primitive.description
+ (* Exceptions *)
+ | Praise of raise_kind
+ (* Boolean operations *)
+ | Psequand | Psequor | Pnot
+ (* Integer operations *)
+ | Pnegint | Paddint | Psubint | Pmulint | Pdivint | Pmodint
+ | Pandint | Porint | Pxorint
+ | Plslint | Plsrint | Pasrint
+ | Pintcomp of comparison
+ | Poffsetint of int
+ | Poffsetref of int
+ (* Float operations *)
+ | Pintoffloat | Pfloatofint
+ | Pnegfloat | Pabsfloat
+ | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat
+ | Pfloatcomp of comparison
+ (* String operations *)
+ | Pstringlength | Pstringrefu | Pstringsetu | Pstringrefs | Pstringsets
+ (* Array operations *)
+ | Pmakearray of array_kind
+ | Parraylength of array_kind
+ | Parrayrefu of array_kind
+ | Parraysetu of array_kind
+ | Parrayrefs of array_kind
+ | Parraysets of array_kind
+ (* Test if the argument is a block or an immediate integer *)
+ | Pisint
+ (* Test if the (integer) argument is outside an interval *)
+ | Pisout
+ (* Bitvect operations *)
+ | Pbittest
+ (* Operations on boxed integers (Nativeint.t, Int32.t, Int64.t) *)
+ | Pbintofint of boxed_integer
+ | Pintofbint of boxed_integer
+ | Pcvtbint of boxed_integer (*source*) * boxed_integer (*destination*)
+ | Pnegbint of boxed_integer
+ | Paddbint of boxed_integer
+ | Psubbint of boxed_integer
+ | Pmulbint of boxed_integer
+ | Pdivbint of boxed_integer
+ | Pmodbint of boxed_integer
+ | Pandbint of boxed_integer
+ | Porbint of boxed_integer
+ | Pxorbint of boxed_integer
+ | Plslbint of boxed_integer
+ | Plsrbint of boxed_integer
+ | Pasrbint of boxed_integer
+ | Pbintcomp of boxed_integer * comparison
+ (* Operations on big arrays: (unsafe, #dimensions, kind, layout) *)
+ | Pbigarrayref of bool * int * bigarray_kind * bigarray_layout
+ | Pbigarrayset of bool * int * bigarray_kind * bigarray_layout
+ (* size of the nth dimension of a big array *)
+ | Pbigarraydim of int
+ (* load/set 16,32,64 bits from a string: (unsafe)*)
+ | Pstring_load_16 of bool
+ | Pstring_load_32 of bool
+ | Pstring_load_64 of bool
+ | Pstring_set_16 of bool
+ | Pstring_set_32 of bool
+ | Pstring_set_64 of bool
+ (* load/set 16,32,64 bits from a
+ (char, int8_unsigned_elt, c_layout) Bigarray.Array1.t : (unsafe) *)
+ | Pbigstring_load_16 of bool
+ | Pbigstring_load_32 of bool
+ | Pbigstring_load_64 of bool
+ | Pbigstring_set_16 of bool
+ | Pbigstring_set_32 of bool
+ | Pbigstring_set_64 of bool
+ (* Compile time constants *)
+ | Pctconst of compile_time_constant
+ (* byte swap *)
+ | Pbswap16
+ | Pbbswap of boxed_integer
+ (* Integer to external pointer *)
+ | Pint_as_pointer
+
+and comparison =
+ Ceq | Cneq | Clt | Cgt | Cle | Cge
+
+and array_kind =
+ Pgenarray | Paddrarray | Pintarray | Pfloatarray
+
+and boxed_integer = Primitive.boxed_integer =
+ Pnativeint | Pint32 | Pint64
+
+and bigarray_kind =
+ Pbigarray_unknown
+ | Pbigarray_float32 | Pbigarray_float64
+ | Pbigarray_sint8 | Pbigarray_uint8
+ | Pbigarray_sint16 | Pbigarray_uint16
+ | Pbigarray_int32 | Pbigarray_int64
+ | Pbigarray_caml_int | Pbigarray_native_int
+ | Pbigarray_complex32 | Pbigarray_complex64
+
+and bigarray_layout =
+ Pbigarray_unknown_layout
+ | Pbigarray_c_layout
+ | Pbigarray_fortran_layout
+
+and raise_kind =
+ | Raise_regular
+ | Raise_reraise
+ | Raise_notrace
+
+type structured_constant =
+ Const_base of constant
+ | Const_pointer of int
+ | Const_block of int * structured_constant list
+ | Const_float_array of string list
+ | Const_immstring of string
+
+type apply_info = {
+ apply_loc : Location.t;
+ apply_should_be_tailcall : bool; (* true if [@tailcall] was specified *)
+}
+
+let mk_apply_info ?(tailcall=false) loc =
+ {apply_loc=loc;
+ apply_should_be_tailcall=tailcall; }
+
+let no_apply_info =
+ {apply_loc=Location.none; apply_should_be_tailcall=false;}
+
+type function_kind = Curried | Tupled
+
+type let_kind = Strict | Alias | StrictOpt | Variable
+
+type meth_kind = Self | Public | Cached
+
+type shared_code = (int * int) list
+
+type lambda =
+ Lvar of Ident.t
+ | Lconst of structured_constant
+ | Lapply of lambda * lambda list * apply_info
+ | Lfunction of lfunction
+ | Llet of let_kind * Ident.t * lambda * lambda
+ | Lletrec of (Ident.t * lambda) list * lambda
+ | Lprim of primitive * lambda list
+ | Lswitch of lambda * lambda_switch
+ | Lstringswitch of lambda * (string * lambda) list * lambda option
+ | Lstaticraise of int * lambda list
+ | Lstaticcatch of lambda * (int * Ident.t list) * lambda
+ | Ltrywith of lambda * Ident.t * lambda
+ | Lifthenelse of lambda * lambda * lambda
+ | Lsequence of lambda * lambda
+ | Lwhile of lambda * lambda
+ | Lfor of Ident.t * lambda * lambda * direction_flag * lambda
+ | Lassign of Ident.t * lambda
+ | Lsend of meth_kind * lambda * lambda * lambda list * Location.t
+ | Levent of lambda * lambda_event
+ | Lifused of Ident.t * lambda
+
+and lfunction =
+ { kind: function_kind;
+ params: Ident.t list;
+ body: lambda }
+
+and lambda_switch =
+ { sw_numconsts: int;
+ sw_consts: (int * lambda) list;
+ sw_numblocks: int;
+ sw_blocks: (int * lambda) list;
+ sw_failaction : lambda option}
+
+and lambda_event =
+ { lev_loc: Location.t;
+ lev_kind: lambda_event_kind;
+ lev_repr: int ref option;
+ lev_env: Env.summary }
+
+and lambda_event_kind =
+ Lev_before
+ | Lev_after of Types.type_expr
+ | Lev_function
+
+let const_unit = Const_pointer 0
+
+let lambda_unit = Lconst const_unit
+
+(* Build sharing keys *)
+(*
+ Those keys are later compared with Pervasives.compare.
+ For that reason, they should not include cycles.
+*)
+
+exception Not_simple
+
+let max_raw = 32
+
+let make_key e =
+ let count = ref 0 (* Used for controling size *)
+ and make_key = Ident.make_key_generator () in
+ (* make_key is used for normalizing let-bound variables *)
+ let rec tr_rec env e =
+ incr count ;
+ if !count > max_raw then raise Not_simple ; (* Too big ! *)
+ match e with
+ | Lvar id ->
+ begin
+ try Ident.find_same id env
+ with Not_found -> e
+ end
+ | Lconst (Const_base (Const_string _)|Const_float_array _) ->
+ (* Mutable constants are not shared *)
+ raise Not_simple
+ | Lconst _ -> e
+ | Lapply (e,es,info) ->
+ Lapply (tr_rec env e,tr_recs env es,{info with apply_loc=Location.none})
+ | Llet (Alias,x,ex,e) -> (* Ignore aliases -> substitute *)
+ let ex = tr_rec env ex in
+ tr_rec (Ident.add x ex env) e
+ | Llet (str,x,ex,e) ->
+ (* Because of side effects, keep other lets with normalized names *)
+ let ex = tr_rec env ex in
+ let y = make_key x in
+ Llet (str,y,ex,tr_rec (Ident.add x (Lvar y) env) e)
+ | Lprim (p,es) ->
+ Lprim (p,tr_recs env es)
+ | Lswitch (e,sw) ->
+ Lswitch (tr_rec env e,tr_sw env sw)
+ | Lstringswitch (e,sw,d) ->
+ Lstringswitch
+ (tr_rec env e,
+ List.map (fun (s,e) -> s,tr_rec env e) sw,
+ tr_opt env d)
+ | Lstaticraise (i,es) ->
+ Lstaticraise (i,tr_recs env es)
+ | Lstaticcatch (e1,xs,e2) ->
+ Lstaticcatch (tr_rec env e1,xs,tr_rec env e2)
+ | Ltrywith (e1,x,e2) ->
+ Ltrywith (tr_rec env e1,x,tr_rec env e2)
+ | Lifthenelse (cond,ifso,ifnot) ->
+ Lifthenelse (tr_rec env cond,tr_rec env ifso,tr_rec env ifnot)
+ | Lsequence (e1,e2) ->
+ Lsequence (tr_rec env e1,tr_rec env e2)
+ | Lassign (x,e) ->
+ Lassign (x,tr_rec env e)
+ | Lsend (m,e1,e2,es,loc) ->
+ Lsend (m,tr_rec env e1,tr_rec env e2,tr_recs env es,Location.none)
+ | Lifused (id,e) -> Lifused (id,tr_rec env e)
+ | Lletrec _|Lfunction _
+ | Lfor _ | Lwhile _
+(* Beware: (PR#6412) the event argument to Levent
+ may include cyclic structure of type Type.typexpr *)
+ | Levent _ ->
+ raise Not_simple
+
+ and tr_recs env es = List.map (tr_rec env) es
+
+ and tr_sw env sw =
+ { sw with
+ sw_consts = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_consts ;
+ sw_blocks = List.map (fun (i,e) -> i,tr_rec env e) sw.sw_blocks ;
+ sw_failaction = tr_opt env sw.sw_failaction ; }
+
+ and tr_opt env = function
+ | None -> None
+ | Some e -> Some (tr_rec env e) in
+
+ try
+ Some (tr_rec Ident.empty e)
+ with Not_simple -> None
+
+(***************)
+
+let name_lambda strict arg fn =
+ match arg with
+ Lvar id -> fn id
+ | _ -> let id = Ident.create "let" in Llet(strict, id, arg, fn id)
+
+let name_lambda_list args fn =
+ let rec name_list names = function
+ [] -> fn (List.rev names)
+ | (Lvar id as arg) :: rem ->
+ name_list (arg :: names) rem
+ | arg :: rem ->
+ let id = Ident.create "let" in
+ Llet(Strict, id, arg, name_list (Lvar id :: names) rem) in
+ name_list [] args
+
+
+let iter_opt f = function
+ | None -> ()
+ | Some e -> f e
+
+let iter f = function
+ Lvar _
+ | Lconst _ -> ()
+ | Lapply(fn, args, _) ->
+ f fn; List.iter f args
+ | Lfunction{kind; params; body} ->
+ f body
+ | Llet(str, id, arg, body) ->
+ f arg; f body
+ | Lletrec(decl, body) ->
+ f body;
+ List.iter (fun (id, exp) -> f exp) decl
+ | Lprim(p, args) ->
+ List.iter f args
+ | Lswitch(arg, sw) ->
+ f arg;
+ List.iter (fun (key, case) -> f case) sw.sw_consts;
+ List.iter (fun (key, case) -> f case) sw.sw_blocks;
+ iter_opt f sw.sw_failaction
+ | Lstringswitch (arg,cases,default) ->
+ f arg ;
+ List.iter (fun (_,act) -> f act) cases ;
+ iter_opt f default
+ | Lstaticraise (_,args) ->
+ List.iter f args
+ | Lstaticcatch(e1, (_,vars), e2) ->
+ f e1; f e2
+ | Ltrywith(e1, exn, e2) ->
+ f e1; f e2
+ | Lifthenelse(e1, e2, e3) ->
+ f e1; f e2; f e3
+ | Lsequence(e1, e2) ->
+ f e1; f e2
+ | Lwhile(e1, e2) ->
+ f e1; f e2
+ | Lfor(v, e1, e2, dir, e3) ->
+ f e1; f e2; f e3
+ | Lassign(id, e) ->
+ f e
+ | Lsend (k, met, obj, args, _) ->
+ List.iter f (met::obj::args)
+ | Levent (lam, evt) ->
+ f lam
+ | Lifused (v, e) ->
+ f e
+
+
+module IdentSet =
+ Set.Make(struct
+ type t = Ident.t
+ let compare = compare
+ end)
+
+let free_ids get l =
+ let fv = ref IdentSet.empty in
+ let rec free l =
+ iter free l;
+ fv := List.fold_right IdentSet.add (get l) !fv;
+ match l with
+ Lfunction{kind; params; body} ->
+ List.iter (fun param -> fv := IdentSet.remove param !fv) params
+ | Llet(str, id, arg, body) ->
+ fv := IdentSet.remove id !fv
+ | Lletrec(decl, body) ->
+ List.iter (fun (id, exp) -> fv := IdentSet.remove id !fv) decl
+ | Lstaticcatch(e1, (_,vars), e2) ->
+ List.iter (fun id -> fv := IdentSet.remove id !fv) vars
+ | Ltrywith(e1, exn, e2) ->
+ fv := IdentSet.remove exn !fv
+ | Lfor(v, e1, e2, dir, e3) ->
+ fv := IdentSet.remove v !fv
+ | Lassign(id, e) ->
+ fv := IdentSet.add id !fv
+ | Lvar _ | Lconst _ | Lapply _
+ | Lprim _ | Lswitch _ | Lstringswitch _ | Lstaticraise _
+ | Lifthenelse _ | Lsequence _ | Lwhile _
+ | Lsend _ | Levent _ | Lifused _ -> ()
+ in free l; !fv
+
+let free_variables l =
+ free_ids (function Lvar id -> [id] | _ -> []) l
+
+let free_methods l =
+ free_ids (function Lsend(Self, Lvar meth, obj, _, _) -> [meth] | _ -> []) l
+
+(* Check if an action has a "when" guard *)
+let raise_count = ref 0
+
+let next_raise_count () =
+ incr raise_count ;
+ !raise_count
+
+let negative_raise_count = ref 0
+
+let next_negative_raise_count () =
+ decr negative_raise_count ;
+ !negative_raise_count
+
+(* Anticipated staticraise, for guards *)
+let staticfail = Lstaticraise (0,[])
+
+let rec is_guarded = function
+ | Lifthenelse( cond, body, Lstaticraise (0,[])) -> true
+ | Llet(str, id, lam, body) -> is_guarded body
+ | Levent(lam, ev) -> is_guarded lam
+ | _ -> false
+
+let rec patch_guarded patch = function
+ | Lifthenelse (cond, body, Lstaticraise (0,[])) ->
+ Lifthenelse (cond, body, patch)
+ | Llet(str, id, lam, body) ->
+ Llet (str, id, lam, patch_guarded patch body)
+ | Levent(lam, ev) ->
+ Levent (patch_guarded patch lam, ev)
+ | _ -> fatal_error "Lambda.patch_guarded"
+
+(* Translate an access path *)
+
+let rec transl_normal_path = function
+ Pident id ->
+ if Ident.global id then Lprim(Pgetglobal id, []) else Lvar id
+ | Pdot(p, s, pos) ->
+ Lprim(Pfield pos, [transl_normal_path p])
+ | Papply(p1, p2) ->
+ fatal_error "Lambda.transl_path"
+
+(* Translation of value identifiers *)
+
+let transl_path ?(loc=Location.none) env path =
+ transl_normal_path (Env.normalize_path (Some loc) env path)
+
+(* Compile a sequence of expressions *)
+
+let rec make_sequence fn = function
+ [] -> lambda_unit
+ | [x] -> fn x
+ | x::rem ->
+ let lam = fn x in Lsequence(lam, make_sequence fn rem)
+
+(* Apply a substitution to a lambda-term.
+ Assumes that the bound variables of the lambda-term do not
+ belong to the domain of the substitution.
+ Assumes that the image of the substitution is out of reach
+ of the bound variables of the lambda-term (no capture). *)
+
+let subst_lambda s lam =
+ let rec subst = function
+ Lvar id as l ->
+ begin try Ident.find_same id s with Not_found -> l end
+ | Lconst sc as l -> l
+ | Lapply(fn, args, loc) -> Lapply(subst fn, List.map subst args, loc)
+ | Lfunction{kind; params; body} -> Lfunction{kind; params; body = subst body}
+ | Llet(str, id, arg, body) -> Llet(str, id, subst arg, subst body)
+ | Lletrec(decl, body) -> Lletrec(List.map subst_decl decl, subst body)
+ | Lprim(p, args) -> Lprim(p, List.map subst args)
+ | Lswitch(arg, sw) ->
+ Lswitch(subst arg,
+ {sw with sw_consts = List.map subst_case sw.sw_consts;
+ sw_blocks = List.map subst_case sw.sw_blocks;
+ sw_failaction = subst_opt sw.sw_failaction; })
+ | Lstringswitch (arg,cases,default) ->
+ Lstringswitch
+ (subst arg,List.map subst_strcase cases,subst_opt default)
+ | Lstaticraise (i,args) -> Lstaticraise (i, List.map subst args)
+ | Lstaticcatch(e1, io, e2) -> Lstaticcatch(subst e1, io, subst e2)
+ | Ltrywith(e1, exn, e2) -> Ltrywith(subst e1, exn, subst e2)
+ | Lifthenelse(e1, e2, e3) -> Lifthenelse(subst e1, subst e2, subst e3)
+ | Lsequence(e1, e2) -> Lsequence(subst e1, subst e2)
+ | Lwhile(e1, e2) -> Lwhile(subst e1, subst e2)
+ | Lfor(v, e1, e2, dir, e3) -> Lfor(v, subst e1, subst e2, dir, subst e3)
+ | Lassign(id, e) -> Lassign(id, subst e)
+ | Lsend (k, met, obj, args, loc) ->
+ Lsend (k, subst met, subst obj, List.map subst args, loc)
+ | Levent (lam, evt) -> Levent (subst lam, evt)
+ | Lifused (v, e) -> Lifused (v, subst e)
+ and subst_decl (id, exp) = (id, subst exp)
+ and subst_case (key, case) = (key, subst case)
+ and subst_strcase (key, case) = (key, subst case)
+ and subst_opt = function
+ | None -> None
+ | Some e -> Some (subst e)
+ in subst lam
+
+
+(* To let-bind expressions to variables *)
+
+let bind str var exp body =
+ match exp with
+ Lvar var' when Ident.same var var' -> body
+ | _ -> Llet(str, var, exp, body)
+
+and commute_comparison = function
+| Ceq -> Ceq| Cneq -> Cneq
+| Clt -> Cgt | Cle -> Cge
+| Cgt -> Clt | Cge -> Cle
+
+and negate_comparison = function
+| Ceq -> Cneq| Cneq -> Ceq
+| Clt -> Cge | Cle -> Cgt
+| Cgt -> Cle | Cge -> Clt
+
+let raise_kind = function
+ | Raise_regular -> "raise"
+ | Raise_reraise -> "reraise"
+ | Raise_notrace -> "raise_notrace"
+
+let lam_of_loc kind loc =
+ let loc_start = loc.Location.loc_start in
+ let (file, lnum, cnum) = Location.get_pos_info loc_start in
+ let enum = loc.Location.loc_end.Lexing.pos_cnum -
+ loc_start.Lexing.pos_cnum + cnum in
+ match kind with
+ | Loc_POS ->
+ Lconst (Const_block (0, [
+ Const_immstring file;
+ Const_base (Const_int lnum);
+ Const_base (Const_int cnum);
+ Const_base (Const_int enum);
+ ]))
+ | Loc_FILE -> Lconst (Const_immstring file)
+ | Loc_MODULE ->
+ let filename = Filename.basename file in
+ let name = Env.get_unit_name () in
+ let module_name = if name = "" then "//"^filename^"//" else name in
+ Lconst (Const_immstring module_name)
+ | Loc_LOC ->
+ let loc = Printf.sprintf "File %S, line %d, characters %d-%d"
+ file lnum cnum enum in
+ Lconst (Const_immstring loc)
+ | Loc_LINE -> Lconst (Const_base (Const_int lnum))
+
+let reset () =
+ raise_count := 0
diff --git a/bytecomp/lambda.mli b/bytecomp/lambda.mli
new file mode 100644
index 0000000000..9c46d2ce04
--- /dev/null
+++ b/bytecomp/lambda.mli
@@ -0,0 +1,284 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The "lambda" intermediate code *)
+
+open Asttypes
+
+type compile_time_constant =
+ | Big_endian
+ | Word_size
+ | Int_size
+ | Max_wosize
+ | Ostype_unix
+ | Ostype_win32
+ | Ostype_cygwin
+
+type loc_kind =
+ | Loc_FILE
+ | Loc_LINE
+ | Loc_MODULE
+ | Loc_LOC
+ | Loc_POS
+
+type primitive =
+ Pidentity
+ | Pignore
+ | Prevapply of Location.t
+ | Pdirapply of Location.t
+ | Ploc of loc_kind
+ (* Globals *)
+ | Pgetglobal of Ident.t
+ | Psetglobal of Ident.t
+ (* Operations on heap blocks *)
+ | Pmakeblock of int * mutable_flag
+ | Pfield of int
+ | Psetfield of int * bool
+ | Pfloatfield of int
+ | Psetfloatfield of int
+ | Pduprecord of Types.record_representation * int
+ (* Force lazy values *)
+ | Plazyforce
+ (* External call *)
+ | Pccall of Primitive.description
+ (* Exceptions *)
+ | Praise of raise_kind
+ (* Boolean operations *)
+ | Psequand | Psequor | Pnot
+ (* Integer operations *)
+ | Pnegint | Paddint | Psubint | Pmulint | Pdivint | Pmodint
+ | Pandint | Porint | Pxorint
+ | Plslint | Plsrint | Pasrint
+ | Pintcomp of comparison
+ | Poffsetint of int
+ | Poffsetref of int
+ (* Float operations *)
+ | Pintoffloat | Pfloatofint
+ | Pnegfloat | Pabsfloat
+ | Paddfloat | Psubfloat | Pmulfloat | Pdivfloat
+ | Pfloatcomp of comparison
+ (* String operations *)
+ | Pstringlength | Pstringrefu | Pstringsetu | Pstringrefs | Pstringsets
+ (* Array operations *)
+ | Pmakearray of array_kind
+ | Parraylength of array_kind
+ | Parrayrefu of array_kind
+ | Parraysetu of array_kind
+ | Parrayrefs of array_kind
+ | Parraysets of array_kind
+ (* Test if the argument is a block or an immediate integer *)
+ | Pisint
+ (* Test if the (integer) argument is outside an interval *)
+ | Pisout
+ (* Bitvect operations *)
+ | Pbittest
+ (* Operations on boxed integers (Nativeint.t, Int32.t, Int64.t) *)
+ | Pbintofint of boxed_integer
+ | Pintofbint of boxed_integer
+ | Pcvtbint of boxed_integer (*source*) * boxed_integer (*destination*)
+ | Pnegbint of boxed_integer
+ | Paddbint of boxed_integer
+ | Psubbint of boxed_integer
+ | Pmulbint of boxed_integer
+ | Pdivbint of boxed_integer
+ | Pmodbint of boxed_integer
+ | Pandbint of boxed_integer
+ | Porbint of boxed_integer
+ | Pxorbint of boxed_integer
+ | Plslbint of boxed_integer
+ | Plsrbint of boxed_integer
+ | Pasrbint of boxed_integer
+ | Pbintcomp of boxed_integer * comparison
+ (* Operations on big arrays: (unsafe, #dimensions, kind, layout) *)
+ | Pbigarrayref of bool * int * bigarray_kind * bigarray_layout
+ | Pbigarrayset of bool * int * bigarray_kind * bigarray_layout
+ (* size of the nth dimension of a big array *)
+ | Pbigarraydim of int
+ (* load/set 16,32,64 bits from a string: (unsafe)*)
+ | Pstring_load_16 of bool
+ | Pstring_load_32 of bool
+ | Pstring_load_64 of bool
+ | Pstring_set_16 of bool
+ | Pstring_set_32 of bool
+ | Pstring_set_64 of bool
+ (* load/set 16,32,64 bits from a
+ (char, int8_unsigned_elt, c_layout) Bigarray.Array1.t : (unsafe) *)
+ | Pbigstring_load_16 of bool
+ | Pbigstring_load_32 of bool
+ | Pbigstring_load_64 of bool
+ | Pbigstring_set_16 of bool
+ | Pbigstring_set_32 of bool
+ | Pbigstring_set_64 of bool
+ (* Compile time constants *)
+ | Pctconst of compile_time_constant
+ (* byte swap *)
+ | Pbswap16
+ | Pbbswap of boxed_integer
+ (* Integer to external pointer *)
+ | Pint_as_pointer
+
+and comparison =
+ Ceq | Cneq | Clt | Cgt | Cle | Cge
+
+and array_kind =
+ Pgenarray | Paddrarray | Pintarray | Pfloatarray
+
+and boxed_integer = Primitive.boxed_integer =
+ Pnativeint | Pint32 | Pint64
+
+and bigarray_kind =
+ Pbigarray_unknown
+ | Pbigarray_float32 | Pbigarray_float64
+ | Pbigarray_sint8 | Pbigarray_uint8
+ | Pbigarray_sint16 | Pbigarray_uint16
+ | Pbigarray_int32 | Pbigarray_int64
+ | Pbigarray_caml_int | Pbigarray_native_int
+ | Pbigarray_complex32 | Pbigarray_complex64
+
+and bigarray_layout =
+ Pbigarray_unknown_layout
+ | Pbigarray_c_layout
+ | Pbigarray_fortran_layout
+
+and raise_kind =
+ | Raise_regular
+ | Raise_reraise
+ | Raise_notrace
+
+type structured_constant =
+ Const_base of constant
+ | Const_pointer of int
+ | Const_block of int * structured_constant list
+ | Const_float_array of string list
+ | Const_immstring of string
+
+type apply_info = {
+ apply_loc : Location.t;
+ apply_should_be_tailcall : bool; (* true if [@tailcall] was specified *)
+}
+
+val no_apply_info : apply_info
+(** Default [apply_info]: no location, no tailcall *)
+
+val mk_apply_info : ?tailcall:bool -> Location.t -> apply_info
+(** Build apply_info
+ @param tailcall if true, the application should be in tail position;
+ default false *)
+
+type function_kind = Curried | Tupled
+
+type let_kind = Strict | Alias | StrictOpt | Variable
+(* Meaning of kinds for let x = e in e':
+ Strict: e may have side-effets; always evaluate e first
+ (If e is a simple expression, e.g. a variable or constant,
+ we may still substitute e'[x/e].)
+ Alias: e is pure, we can substitute e'[x/e] if x has 0 or 1 occurrences
+ in e'
+ StrictOpt: e does not have side-effects, but depend on the store;
+ we can discard e if x does not appear in e'
+ Variable: the variable x is assigned later in e' *)
+
+type meth_kind = Self | Public | Cached
+
+type shared_code = (int * int) list (* stack size -> code label *)
+
+type lambda =
+ Lvar of Ident.t
+ | Lconst of structured_constant
+ | Lapply of lambda * lambda list * apply_info
+ | Lfunction of lfunction
+ | Llet of let_kind * Ident.t * lambda * lambda
+ | Lletrec of (Ident.t * lambda) list * lambda
+ | Lprim of primitive * lambda list
+ | Lswitch of lambda * lambda_switch
+(* switch on strings, clauses are sorted by string order,
+ strings are pairwise distinct *)
+ | Lstringswitch of lambda * (string * lambda) list * lambda option
+ | Lstaticraise of int * lambda list
+ | Lstaticcatch of lambda * (int * Ident.t list) * lambda
+ | Ltrywith of lambda * Ident.t * lambda
+ | Lifthenelse of lambda * lambda * lambda
+ | Lsequence of lambda * lambda
+ | Lwhile of lambda * lambda
+ | Lfor of Ident.t * lambda * lambda * direction_flag * lambda
+ | Lassign of Ident.t * lambda
+ | Lsend of meth_kind * lambda * lambda * lambda list * Location.t
+ | Levent of lambda * lambda_event
+ | Lifused of Ident.t * lambda
+
+and lfunction =
+ { kind: function_kind;
+ params: Ident.t list;
+ body: lambda }
+
+and lambda_switch =
+ { sw_numconsts: int; (* Number of integer cases *)
+ sw_consts: (int * lambda) list; (* Integer cases *)
+ sw_numblocks: int; (* Number of tag block cases *)
+ sw_blocks: (int * lambda) list; (* Tag block cases *)
+ sw_failaction : lambda option} (* Action to take if failure *)
+and lambda_event =
+ { lev_loc: Location.t;
+ lev_kind: lambda_event_kind;
+ lev_repr: int ref option;
+ lev_env: Env.summary }
+
+and lambda_event_kind =
+ Lev_before
+ | Lev_after of Types.type_expr
+ | Lev_function
+
+(* Sharing key *)
+val make_key: lambda -> lambda option
+
+val const_unit: structured_constant
+val lambda_unit: lambda
+val name_lambda: let_kind -> lambda -> (Ident.t -> lambda) -> lambda
+val name_lambda_list: lambda list -> (lambda list -> lambda) -> lambda
+
+val iter: (lambda -> unit) -> lambda -> unit
+module IdentSet: Set.S with type elt = Ident.t
+val free_variables: lambda -> IdentSet.t
+val free_methods: lambda -> IdentSet.t
+
+val transl_normal_path: Path.t -> lambda (* Path.t is already normal *)
+val transl_path: ?loc:Location.t -> Env.t -> Path.t -> lambda
+val make_sequence: ('a -> lambda) -> 'a list -> lambda
+
+val subst_lambda: lambda Ident.tbl -> lambda -> lambda
+val bind : let_kind -> Ident.t -> lambda -> lambda -> lambda
+
+val commute_comparison : comparison -> comparison
+val negate_comparison : comparison -> comparison
+
+(***********************)
+(* For static failures *)
+(***********************)
+
+(* Get a new static failure ident *)
+val next_raise_count : unit -> int
+val next_negative_raise_count : unit -> int
+ (* Negative raise counts are used to compile 'match ... with
+ exception x -> ...'. This disabled some simplifications
+ performed by the Simplif module that assume that static raises
+ are in tail position in their handler. *)
+
+val staticfail : lambda (* Anticipated static failure *)
+
+(* Check anticipated failure, substitute its final value *)
+val is_guarded: lambda -> bool
+val patch_guarded : lambda -> lambda -> lambda
+
+val raise_kind: raise_kind -> string
+val lam_of_loc : loc_kind -> Location.t -> lambda
+
+val reset: unit -> unit
diff --git a/bytecomp/matching.ml b/bytecomp/matching.ml
new file mode 100644
index 0000000000..5be9074c09
--- /dev/null
+++ b/bytecomp/matching.ml
@@ -0,0 +1,3179 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compilation of pattern matching *)
+
+open Misc
+open Asttypes
+open Types
+open Typedtree
+open Lambda
+open Parmatch
+open Printf
+
+
+let dbg = false
+
+(* See Peyton-Jones, ``The Implementation of functional programming
+ languages'', chapter 5. *)
+(*
+ Bon, au commencement du monde c'etait vrai.
+ Now, see Lefessant-Maranget ``Optimizing Pattern-Matching'' ICFP'2001
+*)
+
+
+(*
+ Many functions on the various data structures of the algorithm :
+ - Pattern matrices.
+ - Default environments: mapping from matrices to exit numbers.
+ - Contexts: matrices whose column are partitioned into
+ left and right.
+ - Jump summaries: mapping from exit numbers to contexts
+*)
+
+let string_of_lam lam =
+ Printlambda.lambda Format.str_formatter lam ;
+ Format.flush_str_formatter ()
+
+type matrix = pattern list list
+
+let add_omega_column pss = List.map (fun ps -> omega::ps) pss
+
+type ctx = {left:pattern list ; right:pattern list}
+
+let pretty_ctx ctx =
+ List.iter
+ (fun {left=left ; right=right} ->
+ prerr_string "LEFT:" ;
+ pretty_line left ;
+ prerr_string " RIGHT:" ;
+ pretty_line right ;
+ prerr_endline "")
+ ctx
+
+let le_ctx c1 c2 =
+ le_pats c1.left c2.left &&
+ le_pats c1.right c2.right
+
+let lshift {left=left ; right=right} = match right with
+| x::xs -> {left=x::left ; right=xs}
+| _ -> assert false
+
+let lforget {left=left ; right=right} = match right with
+| x::xs -> {left=omega::left ; right=xs}
+| _ -> assert false
+
+let rec small_enough n = function
+ | [] -> true
+ | _::rem ->
+ if n <= 0 then false
+ else small_enough (n-1) rem
+
+let ctx_lshift ctx =
+ if small_enough 31 ctx then
+ List.map lshift ctx
+ else (* Context pruning *) begin
+ get_mins le_ctx (List.map lforget ctx)
+ end
+
+let rshift {left=left ; right=right} = match left with
+| p::ps -> {left=ps ; right=p::right}
+| _ -> assert false
+
+let ctx_rshift ctx = List.map rshift ctx
+
+let rec nchars n ps =
+ if n <= 0 then [],ps
+ else match ps with
+ | p::rem ->
+ let chars, cdrs = nchars (n-1) rem in
+ p::chars,cdrs
+ | _ -> assert false
+
+let rshift_num n {left=left ; right=right} =
+ let shifted,left = nchars n left in
+ {left=left ; right = shifted@right}
+
+let ctx_rshift_num n ctx = List.map (rshift_num n) ctx
+
+(* Recombination of contexts (eg: (_,_)::p1::p2::rem -> (p1,p2)::rem)
+ All mutable fields are replaced by '_', since side-effects in
+ guards can alter these fields *)
+
+let combine {left=left ; right=right} = match left with
+| p::ps -> {left=ps ; right=set_args_erase_mutable p right}
+| _ -> assert false
+
+let ctx_combine ctx = List.map combine ctx
+
+let ncols = function
+ | [] -> 0
+ | ps::_ -> List.length ps
+
+
+exception NoMatch
+exception OrPat
+
+let filter_matrix matcher pss =
+
+ let rec filter_rec = function
+ | (p::ps)::rem ->
+ begin match p.pat_desc with
+ | Tpat_alias (p,_,_) ->
+ filter_rec ((p::ps)::rem)
+ | Tpat_var _ ->
+ filter_rec ((omega::ps)::rem)
+ | _ ->
+ begin
+ let rem = filter_rec rem in
+ try
+ matcher p ps::rem
+ with
+ | NoMatch -> rem
+ | OrPat ->
+ match p.pat_desc with
+ | Tpat_or (p1,p2,_) -> filter_rec [(p1::ps) ;(p2::ps)]@rem
+ | _ -> assert false
+ end
+ end
+ | [] -> []
+ | _ ->
+ pretty_matrix pss ;
+ fatal_error "Matching.filter_matrix" in
+ filter_rec pss
+
+let make_default matcher env =
+ let rec make_rec = function
+ | [] -> []
+ | ([[]],i)::_ -> [[[]],i]
+ | (pss,i)::rem ->
+ let rem = make_rec rem in
+ match filter_matrix matcher pss with
+ | [] -> rem
+ | ([]::_) -> ([[]],i)::rem
+ | pss -> (pss,i)::rem in
+ make_rec env
+
+let ctx_matcher p =
+ let p = normalize_pat p in
+ match p.pat_desc with
+ | Tpat_construct (_, cstr,omegas) ->
+ begin match cstr.cstr_tag with
+ | Cstr_extension _ ->
+ let nargs = List.length omegas in
+ (fun q rem -> match q.pat_desc with
+ | Tpat_construct (_, cstr',args)
+ when List.length args = nargs ->
+ p,args @ rem
+ | Tpat_any -> p,omegas @ rem
+ | _ -> raise NoMatch)
+ | _ ->
+ (fun q rem -> match q.pat_desc with
+ | Tpat_construct (_, cstr',args)
+ when cstr.cstr_tag=cstr'.cstr_tag ->
+ p,args @ rem
+ | Tpat_any -> p,omegas @ rem
+ | _ -> raise NoMatch)
+ end
+ | Tpat_constant cst ->
+ (fun q rem -> match q.pat_desc with
+ | Tpat_constant cst' when const_compare cst cst' = 0 ->
+ p,rem
+ | Tpat_any -> p,rem
+ | _ -> raise NoMatch)
+ | Tpat_variant (lab,Some omega,_) ->
+ (fun q rem -> match q.pat_desc with
+ | Tpat_variant (lab',Some arg,_) when lab=lab' ->
+ p,arg::rem
+ | Tpat_any -> p,omega::rem
+ | _ -> raise NoMatch)
+ | Tpat_variant (lab,None,_) ->
+ (fun q rem -> match q.pat_desc with
+ | Tpat_variant (lab',None,_) when lab=lab' ->
+ p,rem
+ | Tpat_any -> p,rem
+ | _ -> raise NoMatch)
+ | Tpat_array omegas ->
+ let len = List.length omegas in
+ (fun q rem -> match q.pat_desc with
+ | Tpat_array args when List.length args=len ->
+ p,args @ rem
+ | Tpat_any -> p, omegas @ rem
+ | _ -> raise NoMatch)
+ | Tpat_tuple omegas ->
+ (fun q rem -> match q.pat_desc with
+ | Tpat_tuple args -> p,args @ rem
+ | _ -> p, omegas @ rem)
+ | Tpat_record (l,_) -> (* Records are normalized *)
+ (fun q rem -> match q.pat_desc with
+ | Tpat_record (l',_) ->
+ let l' = all_record_args l' in
+ p, List.fold_right (fun (_, _,p) r -> p::r) l' rem
+ | _ -> p,List.fold_right (fun (_, _,p) r -> p::r) l rem)
+ | Tpat_lazy omega ->
+ (fun q rem -> match q.pat_desc with
+ | Tpat_lazy arg -> p, (arg::rem)
+ | _ -> p, (omega::rem))
+ | _ -> fatal_error "Matching.ctx_matcher"
+
+
+
+
+let filter_ctx q ctx =
+
+ let matcher = ctx_matcher q in
+
+ let rec filter_rec = function
+ | ({right=p::ps} as l)::rem ->
+ begin match p.pat_desc with
+ | Tpat_or (p1,p2,_) ->
+ filter_rec ({l with right=p1::ps}::{l with right=p2::ps}::rem)
+ | Tpat_alias (p,_,_) ->
+ filter_rec ({l with right=p::ps}::rem)
+ | Tpat_var _ ->
+ filter_rec ({l with right=omega::ps}::rem)
+ | _ ->
+ begin let rem = filter_rec rem in
+ try
+ let to_left, right = matcher p ps in
+ {left=to_left::l.left ; right=right}::rem
+ with
+ | NoMatch -> rem
+ end
+ end
+ | [] -> []
+ | _ -> fatal_error "Matching.filter_ctx" in
+
+ filter_rec ctx
+
+let select_columns pss ctx =
+ let n = ncols pss in
+ List.fold_right
+ (fun ps r ->
+ List.fold_right
+ (fun {left=left ; right=right} r ->
+ let transfert, right = nchars n right in
+ try
+ {left = lubs transfert ps @ left ; right=right}::r
+ with
+ | Empty -> r)
+ ctx r)
+ pss []
+
+let ctx_lub p ctx =
+ List.fold_right
+ (fun {left=left ; right=right} r ->
+ match right with
+ | q::rem ->
+ begin try
+ {left=left ; right = lub p q::rem}::r
+ with
+ | Empty -> r
+ end
+ | _ -> fatal_error "Matching.ctx_lub")
+ ctx []
+
+let ctx_match ctx pss =
+ List.exists
+ (fun {right=qs} ->
+ List.exists
+ (fun ps -> compats qs ps)
+ pss)
+ ctx
+
+type jumps = (int * ctx list) list
+
+let pretty_jumps (env : jumps) = match env with
+| [] -> ()
+| _ ->
+ List.iter
+ (fun (i,ctx) ->
+ Printf.fprintf stderr "jump for %d\n" i ;
+ pretty_ctx ctx)
+ env
+
+
+let rec jumps_extract i = function
+ | [] -> [],[]
+ | (j,pss) as x::rem as all ->
+ if i=j then pss,rem
+ else if j < i then [],all
+ else
+ let r,rem = jumps_extract i rem in
+ r,(x::rem)
+
+let rec jumps_remove i = function
+ | [] -> []
+ | (j,_)::rem when i=j -> rem
+ | x::rem -> x::jumps_remove i rem
+
+let jumps_empty = []
+and jumps_is_empty = function
+ | [] -> true
+ | _ -> false
+
+let jumps_singleton i = function
+ | [] -> []
+ | ctx -> [i,ctx]
+
+let jumps_add i pss jumps = match pss with
+| [] -> jumps
+| _ ->
+ let rec add = function
+ | [] -> [i,pss]
+ | (j,qss) as x::rem as all ->
+ if j > i then x::add rem
+ else if j < i then (i,pss)::all
+ else (i,(get_mins le_ctx (pss@qss)))::rem in
+ add jumps
+
+
+let rec jumps_union (env1:(int*ctx list)list) env2 = match env1,env2 with
+| [],_ -> env2
+| _,[] -> env1
+| ((i1,pss1) as x1::rem1), ((i2,pss2) as x2::rem2) ->
+ if i1=i2 then
+ (i1,get_mins le_ctx (pss1@pss2))::jumps_union rem1 rem2
+ else if i1 > i2 then
+ x1::jumps_union rem1 env2
+ else
+ x2::jumps_union env1 rem2
+
+
+let rec merge = function
+ | env1::env2::rem -> jumps_union env1 env2::merge rem
+ | envs -> envs
+
+let rec jumps_unions envs = match envs with
+ | [] -> []
+ | [env] -> env
+ | _ -> jumps_unions (merge envs)
+
+let jumps_map f env =
+ List.map
+ (fun (i,pss) -> i,f pss)
+ env
+
+(* Pattern matching before any compilation *)
+
+type pattern_matching =
+ { mutable cases : (pattern list * lambda) list;
+ args : (lambda * let_kind) list ;
+ default : (matrix * int) list}
+
+(* Pattern matching after application of both the or-pat rule and the
+ mixture rule *)
+
+type pm_or_compiled =
+ {body : pattern_matching ;
+ handlers : (matrix * int * Ident.t list * pattern_matching) list ;
+ or_matrix : matrix ; }
+
+type pm_half_compiled =
+ | PmOr of pm_or_compiled
+ | PmVar of pm_var_compiled
+ | Pm of pattern_matching
+
+and pm_var_compiled =
+ {inside : pm_half_compiled ; var_arg : lambda ; }
+
+type pm_half_compiled_info =
+ {me : pm_half_compiled ;
+ matrix : matrix ;
+ top_default : (matrix * int) list ; }
+
+let pretty_cases cases =
+ List.iter
+ (fun ((ps),l) ->
+ List.iter
+ (fun p ->
+ Parmatch.top_pretty Format.str_formatter p ;
+ prerr_string " " ;
+ prerr_string (Format.flush_str_formatter ()))
+ ps ;
+(*
+ prerr_string " -> " ;
+ Printlambda.lambda Format.str_formatter l ;
+ prerr_string (Format.flush_str_formatter ()) ;
+*)
+ prerr_endline "")
+ cases
+
+let pretty_def def =
+ prerr_endline "+++++ Defaults +++++" ;
+ List.iter
+ (fun (pss,i) ->
+ Printf.fprintf stderr "Matrix for %d\n" i ;
+ pretty_matrix pss)
+ def ;
+ prerr_endline "+++++++++++++++++++++"
+
+let pretty_pm pm = pretty_cases pm.cases
+
+
+let rec pretty_precompiled = function
+ | Pm pm ->
+ prerr_endline "++++ PM ++++" ;
+ pretty_pm pm
+ | PmVar x ->
+ prerr_endline "++++ VAR ++++" ;
+ pretty_precompiled x.inside
+ | PmOr x ->
+ prerr_endline "++++ OR ++++" ;
+ pretty_pm x.body ;
+ pretty_matrix x.or_matrix ;
+ List.iter
+ (fun (_,i,_,pm) ->
+ eprintf "++ Handler %d ++\n" i ;
+ pretty_pm pm)
+ x.handlers
+
+let pretty_precompiled_res first nexts =
+ pretty_precompiled first ;
+ List.iter
+ (fun (e, pmh) ->
+ eprintf "** DEFAULT %d **\n" e ;
+ pretty_precompiled pmh)
+ nexts
+
+
+
+(* Identifing some semantically equivalent lambda-expressions,
+ Our goal here is also to
+ find alpha-equivalent (simple) terms *)
+
+(* However, as shown by PR#6359 such sharing may hinders the
+ lambda-code invariant that all bound idents are unique,
+ when switchs are compiled to test sequences.
+ The definitive fix is the systematic introduction of exit/catch
+ in case action sharing is present.
+*)
+
+
+module StoreExp =
+ Switch.Store
+ (struct
+ type t = lambda
+ type key = lambda
+ let make_key = Lambda.make_key
+ end)
+
+
+let make_exit i = Lstaticraise (i,[])
+
+(* Introduce a catch, if worth it *)
+let make_catch d k = match d with
+| Lstaticraise (_,[]) -> k d
+| _ ->
+ let e = next_raise_count () in
+ Lstaticcatch (k (make_exit e),(e,[]),d)
+
+(* Introduce a catch, if worth it, delayed version *)
+let rec as_simple_exit = function
+ | Lstaticraise (i,[]) -> Some i
+ | Llet (Alias,_,_,e) -> as_simple_exit e
+ | _ -> None
+
+
+let make_catch_delayed handler = match as_simple_exit handler with
+| Some i -> i,(fun act -> act)
+| None ->
+ let i = next_raise_count () in
+(*
+ Printf.eprintf "SHARE LAMBDA: %i\n%s\n" i (string_of_lam handler);
+*)
+ i,
+ (fun body -> match body with
+ | Lstaticraise (j,_) ->
+ if i=j then handler else body
+ | _ -> Lstaticcatch (body,(i,[]),handler))
+
+
+let raw_action l =
+ match make_key l with | Some l -> l | None -> l
+
+
+let tr_raw act = match make_key act with
+| Some act -> act
+| None -> raise Exit
+
+let same_actions = function
+ | [] -> None
+ | [_,act] -> Some act
+ | (_,act0) :: rem ->
+ try
+ let raw_act0 = tr_raw act0 in
+ let rec s_rec = function
+ | [] -> Some act0
+ | (_,act)::rem ->
+ if raw_act0 = tr_raw act then
+ s_rec rem
+ else
+ None in
+ s_rec rem
+ with
+ | Exit -> None
+
+
+(* Test for swapping two clauses *)
+
+let up_ok_action act1 act2 =
+ try
+ let raw1 = tr_raw act1
+ and raw2 = tr_raw act2 in
+ raw1 = raw2
+ with
+ | Exit -> false
+
+(* Nothing is kown about exception/extension patterns,
+ because of potential rebind *)
+let rec exc_inside p = match p.pat_desc with
+ | Tpat_construct (_,{cstr_tag=Cstr_extension _},_) -> true
+ | Tpat_any|Tpat_constant _|Tpat_var _
+ | Tpat_construct (_,_,[])
+ | Tpat_variant (_,None,_)
+ -> false
+ | Tpat_construct (_,_,ps)
+ | Tpat_tuple ps
+ | Tpat_array ps
+ -> exc_insides ps
+ | Tpat_variant (_, Some q,_)
+ | Tpat_alias (q,_,_)
+ | Tpat_lazy q
+ -> exc_inside q
+ | Tpat_record (lps,_) ->
+ List.exists (fun (_,_,p) -> exc_inside p) lps
+ | Tpat_or (p1,p2,_) -> exc_inside p1 || exc_inside p2
+
+and exc_insides ps = List.exists exc_inside ps
+
+let up_ok (ps,act_p) l =
+ if exc_insides ps then match l with [] -> true | _::_ -> false
+ else
+ List.for_all
+ (fun (qs,act_q) ->
+ up_ok_action act_p act_q ||
+ not (Parmatch.compats ps qs))
+ l
+
+
+(*
+ Simplify fonction normalize the first column of the match
+ - records are expanded so that they posses all fields
+ - aliases are removed and replaced by bindings in actions.
+ However or-patterns are simplified differently,
+ - aliases are not removed
+ - or patterns (_|p) are changed into _
+*)
+
+exception Var of pattern
+
+let simplify_or p =
+ let rec simpl_rec p = match p with
+ | {pat_desc = Tpat_any|Tpat_var _} -> raise (Var p)
+ | {pat_desc = Tpat_alias (q,id,s)} ->
+ begin try
+ {p with pat_desc = Tpat_alias (simpl_rec q,id,s)}
+ with
+ | Var q -> raise (Var {p with pat_desc = Tpat_alias (q,id,s)})
+ end
+ | {pat_desc = Tpat_or (p1,p2,o)} ->
+ let q1 = simpl_rec p1 in
+ begin try
+ let q2 = simpl_rec p2 in
+ {p with pat_desc = Tpat_or (q1, q2, o)}
+ with
+ | Var q2 -> raise (Var {p with pat_desc = Tpat_or (q1, q2, o)})
+ end
+ | {pat_desc = Tpat_record (lbls,closed)} ->
+ let all_lbls = all_record_args lbls in
+ {p with pat_desc=Tpat_record (all_lbls, closed)}
+ | _ -> p in
+ try
+ simpl_rec p
+ with
+ | Var p -> p
+
+let simplify_cases args cls = match args with
+| [] -> assert false
+| (arg,_)::_ ->
+ let rec simplify = function
+ | [] -> []
+ | ((pat :: patl, action) as cl) :: rem ->
+ begin match pat.pat_desc with
+ | Tpat_var (id, _) ->
+ (omega :: patl, bind Alias id arg action) ::
+ simplify rem
+ | Tpat_any ->
+ cl :: simplify rem
+ | Tpat_alias(p, id,_) ->
+ simplify ((p :: patl, bind Alias id arg action) :: rem)
+ | Tpat_record ([],_) ->
+ (omega :: patl, action)::
+ simplify rem
+ | Tpat_record (lbls, closed) ->
+ let all_lbls = all_record_args lbls in
+ let full_pat =
+ {pat with pat_desc=Tpat_record (all_lbls, closed)} in
+ (full_pat::patl,action)::
+ simplify rem
+ | Tpat_or _ ->
+ let pat_simple = simplify_or pat in
+ begin match pat_simple.pat_desc with
+ | Tpat_or _ ->
+ (pat_simple :: patl, action) ::
+ simplify rem
+ | _ ->
+ simplify ((pat_simple::patl,action) :: rem)
+ end
+ | _ -> cl :: simplify rem
+ end
+ | _ -> assert false in
+
+ simplify cls
+
+
+
+(* Once matchings are simplified one easily finds
+ their nature *)
+
+let rec what_is_cases cases = match cases with
+| ({pat_desc=Tpat_any} :: _, _) :: rem -> what_is_cases rem
+| (({pat_desc=(Tpat_var _|Tpat_or (_,_,_)|Tpat_alias (_,_,_))}::_),_)::_
+ -> assert false (* applies to simplified matchings only *)
+| (p::_,_)::_ -> p
+| [] -> omega
+| _ -> assert false
+
+
+
+(* A few operation on default environments *)
+let as_matrix cases = get_mins le_pats (List.map (fun (ps,_) -> ps) cases)
+
+(* For extension matching, record no imformation in matrix *)
+let as_matrix_omega cases =
+ get_mins le_pats
+ (List.map
+ (fun (ps,_) ->
+ match ps with
+ | [] -> assert false
+ | _::ps -> omega::ps)
+ cases)
+
+let cons_default matrix raise_num default =
+ match matrix with
+ | [] -> default
+ | _ -> (matrix,raise_num)::default
+
+let default_compat p def =
+ List.fold_right
+ (fun (pss,i) r ->
+ let qss =
+ List.fold_right
+ (fun qs r -> match qs with
+ | q::rem when Parmatch.compat p q -> rem::r
+ | _ -> r)
+ pss [] in
+ match qss with
+ | [] -> r
+ | _ -> (qss,i)::r)
+ def []
+
+(* Or-pattern expansion, variables are a complication w.r.t. the article *)
+let rec extract_vars r p = match p.pat_desc with
+| Tpat_var (id, _) -> IdentSet.add id r
+| Tpat_alias (p, id,_ ) ->
+ extract_vars (IdentSet.add id r) p
+| Tpat_tuple pats ->
+ List.fold_left extract_vars r pats
+| Tpat_record (lpats,_) ->
+ List.fold_left
+ (fun r (_, _, p) -> extract_vars r p)
+ r lpats
+| Tpat_construct (_, _, pats) ->
+ List.fold_left extract_vars r pats
+| Tpat_array pats ->
+ List.fold_left extract_vars r pats
+| Tpat_variant (_,Some p, _) -> extract_vars r p
+| Tpat_lazy p -> extract_vars r p
+| Tpat_or (p,_,_) -> extract_vars r p
+| Tpat_constant _|Tpat_any|Tpat_variant (_,None,_) -> r
+
+exception Cannot_flatten
+
+let mk_alpha_env arg aliases ids =
+ List.map
+ (fun id -> id,
+ if List.mem id aliases then
+ match arg with
+ | Some v -> v
+ | _ -> raise Cannot_flatten
+ else
+ Ident.create (Ident.name id))
+ ids
+
+let rec explode_or_pat arg patl mk_action rem vars aliases = function
+ | {pat_desc = Tpat_or (p1,p2,_)} ->
+ explode_or_pat
+ arg patl mk_action
+ (explode_or_pat arg patl mk_action rem vars aliases p2)
+ vars aliases p1
+ | {pat_desc = Tpat_alias (p,id, _)} ->
+ explode_or_pat arg patl mk_action rem vars (id::aliases) p
+ | {pat_desc = Tpat_var (x, _)} ->
+ let env = mk_alpha_env arg (x::aliases) vars in
+ (omega::patl,mk_action (List.map snd env))::rem
+ | p ->
+ let env = mk_alpha_env arg aliases vars in
+ (alpha_pat env p::patl,mk_action (List.map snd env))::rem
+
+let pm_free_variables {cases=cases} =
+ List.fold_right
+ (fun (_,act) r -> IdentSet.union (free_variables act) r)
+ cases IdentSet.empty
+
+
+(* Basic grouping predicates *)
+let pat_as_constr = function
+ | {pat_desc=Tpat_construct (_, cstr,_)} -> cstr
+ | _ -> fatal_error "Matching.pat_as_constr"
+
+let group_constant = function
+ | {pat_desc= Tpat_constant _} -> true
+ | _ -> false
+
+and group_constructor = function
+ | {pat_desc = Tpat_construct (_,_,_)} -> true
+ | _ -> false
+
+and group_variant = function
+ | {pat_desc = Tpat_variant (_, _, _)} -> true
+ | _ -> false
+
+and group_var = function
+ | {pat_desc=Tpat_any} -> true
+ | _ -> false
+
+and group_tuple = function
+ | {pat_desc = (Tpat_tuple _|Tpat_any)} -> true
+ | _ -> false
+
+and group_record = function
+ | {pat_desc = (Tpat_record _|Tpat_any)} -> true
+ | _ -> false
+
+and group_array = function
+ | {pat_desc=Tpat_array _} -> true
+ | _ -> false
+
+and group_lazy = function
+ | {pat_desc = Tpat_lazy _} -> true
+ | _ -> false
+
+let get_group p = match p.pat_desc with
+| Tpat_any -> group_var
+| Tpat_constant _ -> group_constant
+| Tpat_construct _ -> group_constructor
+| Tpat_tuple _ -> group_tuple
+| Tpat_record _ -> group_record
+| Tpat_array _ -> group_array
+| Tpat_variant (_,_,_) -> group_variant
+| Tpat_lazy _ -> group_lazy
+| _ -> fatal_error "Matching.get_group"
+
+
+
+let is_or p = match p.pat_desc with
+| Tpat_or _ -> true
+| _ -> false
+
+(* Conditions for appending to the Or matrix *)
+let conda p q = not (compat p q)
+and condb act ps qs = not (is_guarded act) && Parmatch.le_pats qs ps
+
+let or_ok p ps l =
+ List.for_all
+ (function
+ | ({pat_desc=Tpat_or _} as q::qs,act) ->
+ conda p q || condb act ps qs
+ | _ -> true)
+ l
+
+(* Insert or append a pattern in the Or matrix *)
+
+let equiv_pat p q = le_pat p q && le_pat q p
+
+let rec get_equiv p l = match l with
+ | (q::_,_) as cl::rem ->
+ if equiv_pat p q then
+ let others,rem = get_equiv p rem in
+ cl::others,rem
+ else
+ [],l
+ | _ -> [],l
+
+
+let insert_or_append p ps act ors no =
+ let rec attempt seen = function
+ | (q::qs,act_q) as cl::rem ->
+ if is_or q then begin
+ if compat p q then
+ if
+ IdentSet.is_empty (extract_vars IdentSet.empty p) &&
+ IdentSet.is_empty (extract_vars IdentSet.empty q) &&
+ equiv_pat p q
+ then (* attempt insert, for equivalent orpats with no variables *)
+ let _, not_e = get_equiv q rem in
+ if
+ or_ok p ps not_e && (* check append condition for head of O *)
+ List.for_all (* check insert condition for tail of O *)
+ (fun cl -> match cl with
+ | (q::_,_) -> not (compat p q)
+ | _ -> assert false)
+ seen
+ then (* insert *)
+ List.rev_append seen ((p::ps,act)::cl::rem), no
+ else (* fail to insert or append *)
+ ors,(p::ps,act)::no
+ else if condb act_q ps qs then (* check condition (b) for append *)
+ attempt (cl::seen) rem
+ else
+ ors,(p::ps,act)::no
+ else (* p # q, go on with append/insert *)
+ attempt (cl::seen) rem
+ end else (* q is not a or-pat, go on with append/insert *)
+ attempt (cl::seen) rem
+ | _ -> (* [] in fact *)
+ (p::ps,act)::ors,no in (* success in appending *)
+ attempt [] ors
+
+(* Reconstruct default information from half_compiled pm list *)
+
+let rec rebuild_matrix pmh = match pmh with
+ | Pm pm -> as_matrix pm.cases
+ | PmOr {or_matrix=m} -> m
+ | PmVar x -> add_omega_column (rebuild_matrix x.inside)
+
+let rec rebuild_default nexts def = match nexts with
+| [] -> def
+| (e, pmh)::rem ->
+ (add_omega_column (rebuild_matrix pmh), e)::
+ rebuild_default rem def
+
+let rebuild_nexts arg nexts k =
+ List.fold_right
+ (fun (e, pm) k -> (e, PmVar {inside=pm ; var_arg=arg})::k)
+ nexts k
+
+
+(*
+ Split a matching.
+ Splitting is first directed by or-patterns, then by
+ tests (e.g. constructors)/variable transitions.
+
+ The approach is greedy, every split function attempt to
+ raise rows as much as possible in the top matrix,
+ then splitting applies again to the remaining rows.
+
+ Some precompilation of or-patterns and
+ variable pattern occurs. Mostly this means that bindings
+ are performed now, being replaced by let-bindings
+ in actions (cf. simplify_cases).
+
+ Additionally, if the match argument is a variable, matchings whose
+ first column is made of variables only are splitted further
+ (cf. precompile_var).
+
+*)
+
+
+let rec split_or argo cls args def =
+
+ let cls = simplify_cases args cls in
+
+ let rec do_split before ors no = function
+ | [] ->
+ cons_next
+ (List.rev before) (List.rev ors) (List.rev no)
+ | ((p::ps,act) as cl)::rem ->
+ if up_ok cl no then
+ if is_or p then
+ let ors, no = insert_or_append p ps act ors no in
+ do_split before ors no rem
+ else begin
+ if up_ok cl ors then
+ do_split (cl::before) ors no rem
+ else if or_ok p ps ors then
+ do_split before (cl::ors) no rem
+ else
+ do_split before ors (cl::no) rem
+ end
+ else
+ do_split before ors (cl::no) rem
+ | _ -> assert false
+
+ and cons_next yes yesor = function
+ | [] ->
+ precompile_or argo yes yesor args def []
+ | rem ->
+ let {me=next ; matrix=matrix ; top_default=def},nexts =
+ do_split [] [] [] rem in
+ let idef = next_raise_count () in
+ precompile_or
+ argo yes yesor args
+ (cons_default matrix idef def)
+ ((idef,next)::nexts) in
+
+ do_split [] [] [] cls
+
+(* Ultra-naive spliting, close to semantics, used for extension,
+ as potential rebind prevents any kind of optimisation *)
+
+and split_naive cls args def k =
+
+ let rec split_exc cstr0 yes = function
+ | [] ->
+ let yes = List.rev yes in
+ { me = Pm {cases=yes; args=args; default=def;} ;
+ matrix = as_matrix_omega yes ;
+ top_default=def},
+ k
+ | (p::_,_ as cl)::rem ->
+ if group_constructor p then
+ let cstr = pat_as_constr p in
+ if cstr = cstr0 then split_exc cstr0 (cl::yes) rem
+ else
+ let yes = List.rev yes in
+ let {me=next ; matrix=matrix ; top_default=def}, nexts =
+ split_exc cstr [cl] rem in
+ let idef = next_raise_count () in
+ let def = cons_default matrix idef def in
+ { me = Pm {cases=yes; args=args; default=def} ;
+ matrix = as_matrix_omega yes ;
+ top_default = def; },
+ (idef,next)::nexts
+ else
+ let yes = List.rev yes in
+ let {me=next ; matrix=matrix ; top_default=def}, nexts =
+ split_noexc [cl] rem in
+ let idef = next_raise_count () in
+ let def = cons_default matrix idef def in
+ { me = Pm {cases=yes; args=args; default=def} ;
+ matrix = as_matrix_omega yes ;
+ top_default = def; },
+ (idef,next)::nexts
+ | _ -> assert false
+
+ and split_noexc yes = function
+ | [] -> precompile_var args (List.rev yes) def k
+ | (p::_,_ as cl)::rem ->
+ if group_constructor p then
+ let yes= List.rev yes in
+ let {me=next; matrix=matrix; top_default=def;},nexts =
+ split_exc (pat_as_constr p) [cl] rem in
+ let idef = next_raise_count () in
+ precompile_var
+ args yes
+ (cons_default matrix idef def)
+ ((idef,next)::nexts)
+ else split_noexc (cl::yes) rem
+ | _ -> assert false in
+
+ match cls with
+ | [] -> assert false
+ | (p::_,_ as cl)::rem ->
+ if group_constructor p then
+ split_exc (pat_as_constr p) [cl] rem
+ else
+ split_noexc [cl] rem
+ | _ -> assert false
+
+and split_constr cls args def k =
+ let ex_pat = what_is_cases cls in
+ match ex_pat.pat_desc with
+ | Tpat_any -> precompile_var args cls def k
+ | Tpat_construct (_,{cstr_tag=Cstr_extension _},_) ->
+ split_naive cls args def k
+ | _ ->
+
+ let group = get_group ex_pat in
+
+ let rec split_ex yes no = function
+ | [] ->
+ let yes = List.rev yes and no = List.rev no in
+ begin match no with
+ | [] ->
+ {me = Pm {cases=yes ; args=args ; default=def} ;
+ matrix = as_matrix yes ;
+ top_default = def},
+ k
+ | cl::rem ->
+ begin match yes with
+ | [] ->
+ (* Could not success in raising up a constr matching up *)
+ split_noex [cl] [] rem
+ | _ ->
+ let {me=next ; matrix=matrix ; top_default=def}, nexts =
+ split_noex [cl] [] rem in
+ let idef = next_raise_count () in
+ let def = cons_default matrix idef def in
+ {me = Pm {cases=yes ; args=args ; default=def} ;
+ matrix = as_matrix yes ;
+ top_default = def },
+ (idef, next)::nexts
+ end
+ end
+ | (p::_,_) as cl::rem ->
+ if group p && up_ok cl no then
+ split_ex (cl::yes) no rem
+ else
+ split_ex yes (cl::no) rem
+ | _ -> assert false
+
+ and split_noex yes no = function
+ | [] ->
+ let yes = List.rev yes and no = List.rev no in
+ begin match no with
+ | [] -> precompile_var args yes def k
+ | cl::rem ->
+ let {me=next ; matrix=matrix ; top_default=def}, nexts =
+ split_ex [cl] [] rem in
+ let idef = next_raise_count () in
+ precompile_var
+ args yes
+ (cons_default matrix idef def)
+ ((idef,next)::nexts)
+ end
+ | [ps,_ as cl]
+ when List.for_all group_var ps && yes <> [] ->
+ (* This enables an extra division in some frequent case :
+ last row is made of variables only *)
+ split_noex yes (cl::no) []
+ | (p::_,_) as cl::rem ->
+ if not (group p) && up_ok cl no then
+ split_noex (cl::yes) no rem
+ else
+ split_noex yes (cl::no) rem
+ | _ -> assert false in
+
+ match cls with
+ | ((p::_,_) as cl)::rem ->
+ if group p then split_ex [cl] [] rem
+ else split_noex [cl] [] rem
+ | _ -> assert false
+
+and precompile_var args cls def k = match args with
+| [] -> assert false
+| _::((Lvar v as av,_) as arg)::rargs ->
+ begin match cls with
+ | [ps,_] -> (* as splitted as it can *)
+ dont_precompile_var args cls def k
+ | _ ->
+(* Precompile *)
+ let var_cls =
+ List.map
+ (fun (ps,act) -> match ps with
+ | _::ps -> ps,act | _ -> assert false)
+ cls
+ and var_def = make_default (fun _ rem -> rem) def in
+ let {me=first ; matrix=matrix}, nexts =
+ split_or (Some v) var_cls (arg::rargs) var_def in
+
+(* Compute top information *)
+ match nexts with
+ | [] -> (* If you need *)
+ dont_precompile_var args cls def k
+ | _ ->
+ let rfirst =
+ {me = PmVar {inside=first ; var_arg = av} ;
+ matrix = add_omega_column matrix ;
+ top_default = rebuild_default nexts def ; }
+ and rnexts = rebuild_nexts av nexts k in
+ rfirst, rnexts
+ end
+| _ ->
+ dont_precompile_var args cls def k
+
+and dont_precompile_var args cls def k =
+ {me = Pm {cases = cls ; args = args ; default = def } ;
+ matrix=as_matrix cls ;
+ top_default=def},k
+
+and is_exc p = match p.pat_desc with
+| Tpat_or (p1,p2,_) -> is_exc p1 || is_exc p2
+| Tpat_alias (p,v,_) -> is_exc p
+| Tpat_construct (_,{cstr_tag=Cstr_extension _},_) -> true
+| _ -> false
+
+and precompile_or argo cls ors args def k = match ors with
+| [] -> split_constr cls args def k
+| _ ->
+ let rec do_cases = function
+ | ({pat_desc=Tpat_or _} as orp::patl, action)::rem ->
+ let do_opt = not (is_exc orp) in
+ let others,rem =
+ if do_opt then get_equiv orp rem
+ else [],rem in
+ let orpm =
+ {cases =
+ (patl, action)::
+ List.map
+ (function
+ | (_::ps,action) -> ps,action
+ | _ -> assert false)
+ others ;
+ args = (match args with _::r -> r | _ -> assert false) ;
+ default = default_compat (if do_opt then orp else omega) def} in
+ let vars =
+ IdentSet.elements
+ (IdentSet.inter
+ (extract_vars IdentSet.empty orp)
+ (pm_free_variables orpm)) in
+ let or_num = next_raise_count () in
+ let new_patl = Parmatch.omega_list patl in
+
+ let mk_new_action vs =
+ Lstaticraise
+ (or_num, List.map (fun v -> Lvar v) vs) in
+
+ let do_optrec,body,handlers = do_cases rem in
+ do_opt && do_optrec,
+ explode_or_pat
+ argo new_patl mk_new_action body vars [] orp,
+ let mat = if do_opt then [[orp]] else [[omega]] in
+ ((mat, or_num, vars , orpm):: handlers)
+ | cl::rem ->
+ let b,new_ord,new_to_catch = do_cases rem in
+ b,cl::new_ord,new_to_catch
+ | [] -> true,[],[] in
+
+ let do_opt,end_body, handlers = do_cases ors in
+ let matrix = (if do_opt then as_matrix else as_matrix_omega) (cls@ors)
+ and body = {cases=cls@end_body ; args=args ; default=def} in
+ {me = PmOr {body=body ; handlers=handlers ; or_matrix=matrix} ;
+ matrix=matrix ;
+ top_default=def},
+ k
+
+let split_precompile argo pm =
+ let {me=next}, nexts = split_or argo pm.cases pm.args pm.default in
+ if dbg && (nexts <> [] || (match next with PmOr _ -> true | _ -> false))
+ then begin
+ prerr_endline "** SPLIT **" ;
+ pretty_pm pm ;
+ pretty_precompiled_res next nexts
+ end ;
+ next, nexts
+
+
+(* General divide functions *)
+
+let add_line patl_action pm = pm.cases <- patl_action :: pm.cases; pm
+
+type cell =
+ {pm : pattern_matching ;
+ ctx : ctx list ;
+ pat : pattern}
+
+let add make_matching_fun division eq_key key patl_action args =
+ try
+ let (_,cell) = List.find (fun (k,_) -> eq_key key k) division in
+ cell.pm.cases <- patl_action :: cell.pm.cases;
+ division
+ with Not_found ->
+ let cell = make_matching_fun args in
+ cell.pm.cases <- [patl_action] ;
+ (key, cell) :: division
+
+
+let divide make eq_key get_key get_args ctx pm =
+
+ let rec divide_rec = function
+ | (p::patl,action) :: rem ->
+ let this_match = divide_rec rem in
+ add
+ (make p pm.default ctx)
+ this_match eq_key (get_key p) (get_args p patl,action) pm.args
+ | _ -> [] in
+
+ divide_rec pm.cases
+
+
+let divide_line make_ctx make get_args pat ctx pm =
+ let rec divide_rec = function
+ | (p::patl,action) :: rem ->
+ let this_match = divide_rec rem in
+ add_line (get_args p patl, action) this_match
+ | _ -> make pm.default pm.args in
+
+ {pm = divide_rec pm.cases ;
+ ctx=make_ctx ctx ;
+ pat=pat}
+
+
+
+(* Then come various functions,
+ There is one set of functions per matching style
+ (constants, constructors etc.)
+
+ - matcher function are arguments to make_default (for defaukt handlers)
+ They may raise NoMatch or OrPat and perform the full
+ matching (selection + arguments).
+
+
+ - get_args and get_key are for the compiled matrices, note that
+ selection and geting arguments are separed.
+
+ - make_ _matching combines the previous functions for produicing
+ new ``pattern_matching'' records.
+*)
+
+
+
+let rec matcher_const cst p rem = match p.pat_desc with
+| Tpat_or (p1,p2,_) ->
+ begin try
+ matcher_const cst p1 rem with
+ | NoMatch -> matcher_const cst p2 rem
+ end
+| Tpat_constant c1 when const_compare c1 cst = 0 -> rem
+| Tpat_any -> rem
+| _ -> raise NoMatch
+
+let get_key_constant caller = function
+ | {pat_desc= Tpat_constant cst} -> cst
+ | p ->
+ prerr_endline ("BAD: "^caller) ;
+ pretty_pat p ;
+ assert false
+
+let get_args_constant _ rem = rem
+
+let make_constant_matching p def ctx = function
+ [] -> fatal_error "Matching.make_constant_matching"
+ | (_ :: argl) ->
+ let def =
+ make_default
+ (matcher_const (get_key_constant "make" p)) def
+ and ctx =
+ filter_ctx p ctx in
+ {pm = {cases = []; args = argl ; default = def} ;
+ ctx = ctx ;
+ pat = normalize_pat p}
+
+
+
+
+let divide_constant ctx m =
+ divide
+ make_constant_matching
+ (fun c d -> const_compare c d = 0) (get_key_constant "divide")
+ get_args_constant
+ ctx m
+
+(* Matching against a constructor *)
+
+
+let make_field_args binding_kind arg first_pos last_pos argl =
+ let rec make_args pos =
+ if pos > last_pos
+ then argl
+ else (Lprim(Pfield pos, [arg]), binding_kind) :: make_args (pos + 1)
+ in make_args first_pos
+
+let get_key_constr = function
+ | {pat_desc=Tpat_construct (_, cstr,_)} -> cstr.cstr_tag
+ | _ -> assert false
+
+let get_args_constr p rem = match p with
+| {pat_desc=Tpat_construct (_, _, args)} -> args @ rem
+| _ -> assert false
+
+let matcher_constr cstr = match cstr.cstr_arity with
+| 0 ->
+ let rec matcher_rec q rem = match q.pat_desc with
+ | Tpat_or (p1,p2,_) ->
+ begin
+ try
+ matcher_rec p1 rem
+ with
+ | NoMatch -> matcher_rec p2 rem
+ end
+ | Tpat_construct (_, cstr1, []) when cstr.cstr_tag = cstr1.cstr_tag ->
+ rem
+ | Tpat_any -> rem
+ | _ -> raise NoMatch in
+ matcher_rec
+| 1 ->
+ let rec matcher_rec q rem = match q.pat_desc with
+ | Tpat_or (p1,p2,_) ->
+ let r1 = try Some (matcher_rec p1 rem) with NoMatch -> None
+ and r2 = try Some (matcher_rec p2 rem) with NoMatch -> None in
+ begin match r1,r2 with
+ | None, None -> raise NoMatch
+ | Some r1, None -> r1
+ | None, Some r2 -> r2
+ | Some (a1::rem1), Some (a2::_) ->
+ {a1 with
+ pat_loc = Location.none ;
+ pat_desc = Tpat_or (a1, a2, None)}::
+ rem
+ | _, _ -> assert false
+ end
+ | Tpat_construct (_, cstr1, [arg])
+ when cstr.cstr_tag = cstr1.cstr_tag -> arg::rem
+ | Tpat_any -> omega::rem
+ | _ -> raise NoMatch in
+ matcher_rec
+| _ ->
+ fun q rem -> match q.pat_desc with
+ | Tpat_or (_,_,_) -> raise OrPat
+ | Tpat_construct (_, cstr1, args)
+ when cstr.cstr_tag = cstr1.cstr_tag -> args @ rem
+ | Tpat_any -> Parmatch.omegas cstr.cstr_arity @ rem
+ | _ -> raise NoMatch
+
+let make_constr_matching p def ctx = function
+ [] -> fatal_error "Matching.make_constr_matching"
+ | ((arg, mut) :: argl) ->
+ let cstr = pat_as_constr p in
+ let newargs =
+ if cstr.cstr_inlined <> None then
+ (arg, Alias) :: argl
+ else match cstr.cstr_tag with
+ Cstr_constant _ | Cstr_block _ ->
+ make_field_args Alias arg 0 (cstr.cstr_arity - 1) argl
+ | Cstr_extension _ ->
+ make_field_args Alias arg 1 cstr.cstr_arity argl in
+ {pm=
+ {cases = []; args = newargs;
+ default = make_default (matcher_constr cstr) def} ;
+ ctx = filter_ctx p ctx ;
+ pat=normalize_pat p}
+
+
+let divide_constructor ctx pm =
+ divide
+ make_constr_matching
+ (=) get_key_constr get_args_constr
+ ctx pm
+
+(* Matching against a variant *)
+
+let rec matcher_variant_const lab p rem = match p.pat_desc with
+| Tpat_or (p1, p2, _) ->
+ begin
+ try
+ matcher_variant_const lab p1 rem
+ with
+ | NoMatch -> matcher_variant_const lab p2 rem
+ end
+| Tpat_variant (lab1,_,_) when lab1=lab -> rem
+| Tpat_any -> rem
+| _ -> raise NoMatch
+
+
+let make_variant_matching_constant p lab def ctx = function
+ [] -> fatal_error "Matching.make_variant_matching_constant"
+ | ((arg, mut) :: argl) ->
+ let def = make_default (matcher_variant_const lab) def
+ and ctx = filter_ctx p ctx in
+ {pm={ cases = []; args = argl ; default=def} ;
+ ctx=ctx ;
+ pat = normalize_pat p}
+
+let matcher_variant_nonconst lab p rem = match p.pat_desc with
+| Tpat_or (_,_,_) -> raise OrPat
+| Tpat_variant (lab1,Some arg,_) when lab1=lab -> arg::rem
+| Tpat_any -> omega::rem
+| _ -> raise NoMatch
+
+
+let make_variant_matching_nonconst p lab def ctx = function
+ [] -> fatal_error "Matching.make_variant_matching_nonconst"
+ | ((arg, mut) :: argl) ->
+ let def = make_default (matcher_variant_nonconst lab) def
+ and ctx = filter_ctx p ctx in
+ {pm=
+ {cases = []; args = (Lprim(Pfield 1, [arg]), Alias) :: argl;
+ default=def} ;
+ ctx=ctx ;
+ pat = normalize_pat p}
+
+let get_key_variant p = match p.pat_desc with
+| Tpat_variant(lab, Some _ , _) -> Cstr_block (Btype.hash_variant lab)
+| Tpat_variant(lab, None , _) -> Cstr_constant (Btype.hash_variant lab)
+| _ -> assert false
+
+let divide_variant row ctx {cases = cl; args = al; default=def} =
+ let row = Btype.row_repr row in
+ let rec divide = function
+ ({pat_desc = Tpat_variant(lab, pato, _)} as p:: patl, action) :: rem ->
+ let variants = divide rem in
+ if try Btype.row_field_repr (List.assoc lab row.row_fields) = Rabsent
+ with Not_found -> true
+ then
+ variants
+ else begin
+ let tag = Btype.hash_variant lab in
+ match pato with
+ None ->
+ add (make_variant_matching_constant p lab def ctx) variants
+ (=) (Cstr_constant tag) (patl, action) al
+ | Some pat ->
+ add (make_variant_matching_nonconst p lab def ctx) variants
+ (=) (Cstr_block tag) (pat :: patl, action) al
+ end
+ | cl -> []
+ in
+ divide cl
+
+(*
+ Three ``no-test'' cases
+ *)
+
+(* Matching against a variable *)
+
+let get_args_var _ rem = rem
+
+
+let make_var_matching def = function
+ | [] -> fatal_error "Matching.make_var_matching"
+ | _::argl ->
+ {cases=[] ;
+ args = argl ;
+ default= make_default get_args_var def}
+
+let divide_var ctx pm =
+ divide_line ctx_lshift make_var_matching get_args_var omega ctx pm
+
+(* Matching and forcing a lazy value *)
+
+let get_arg_lazy p rem = match p with
+| {pat_desc = Tpat_any} -> omega :: rem
+| {pat_desc = Tpat_lazy arg} -> arg :: rem
+| _ -> assert false
+
+let matcher_lazy p rem = match p.pat_desc with
+| Tpat_or (_,_,_) -> raise OrPat
+| Tpat_var _ -> get_arg_lazy omega rem
+| _ -> get_arg_lazy p rem
+
+(* Inlining the tag tests before calling the primitive that works on
+ lazy blocks. This is alse used in translcore.ml.
+ No call other than Obj.tag when the value has been forced before.
+*)
+
+let prim_obj_tag =
+ Primitive.simple ~name:"caml_obj_tag" ~arity:1 ~alloc:false
+
+let get_mod_field modname field =
+ lazy (
+ try
+ let mod_ident = Ident.create_persistent modname in
+ let env = Env.open_pers_signature modname Env.initial_safe_string in
+ let p = try
+ match Env.lookup_value (Longident.Lident field) env with
+ | (Path.Pdot(_,_,i), _) -> i
+ | _ -> fatal_error ("Primitive "^modname^"."^field^" not found.")
+ with Not_found ->
+ fatal_error ("Primitive "^modname^"."^field^" not found.")
+ in
+ Lprim(Pfield p, [Lprim(Pgetglobal mod_ident, [])])
+ with Not_found -> fatal_error ("Module "^modname^" unavailable.")
+ )
+
+let code_force_lazy_block =
+ get_mod_field "CamlinternalLazy" "force_lazy_block"
+;;
+
+(* inline_lazy_force inlines the beginning of the code of Lazy.force. When
+ the value argument is tagged as:
+ - forward, take field 0
+ - lazy, call the primitive that forces (without testing again the tag)
+ - anything else, return it
+
+ Using Lswitch below relies on the fact that the GC does not shortcut
+ Forward(val_out_of_heap).
+*)
+
+let inline_lazy_force_cond arg loc =
+ let idarg = Ident.create "lzarg" in
+ let varg = Lvar idarg in
+ let tag = Ident.create "tag" in
+ let force_fun = Lazy.force code_force_lazy_block in
+ Llet(Strict, idarg, arg,
+ Llet(Alias, tag, Lprim(Pccall prim_obj_tag, [varg]),
+ Lifthenelse(
+ (* if (tag == Obj.forward_tag) then varg.(0) else ... *)
+ Lprim(Pintcomp Ceq,
+ [Lvar tag; Lconst(Const_base(Const_int Obj.forward_tag))]),
+ Lprim(Pfield 0, [varg]),
+ Lifthenelse(
+ (* ... if (tag == Obj.lazy_tag) then Lazy.force varg else ... *)
+ Lprim(Pintcomp Ceq,
+ [Lvar tag; Lconst(Const_base(Const_int Obj.lazy_tag))]),
+ Lapply(force_fun, [varg], mk_apply_info loc),
+ (* ... arg *)
+ varg))))
+
+let inline_lazy_force_switch arg loc =
+ let idarg = Ident.create "lzarg" in
+ let varg = Lvar idarg in
+ let force_fun = Lazy.force code_force_lazy_block in
+ Llet(Strict, idarg, arg,
+ Lifthenelse(
+ Lprim(Pisint, [varg]), varg,
+ (Lswitch
+ (varg,
+ { sw_numconsts = 0; sw_consts = [];
+ sw_numblocks = 256; (* PR#6033 - tag ranges from 0 to 255 *)
+ sw_blocks =
+ [ (Obj.forward_tag, Lprim(Pfield 0, [varg]));
+ (Obj.lazy_tag,
+ Lapply(force_fun, [varg], mk_apply_info loc)) ];
+ sw_failaction = Some varg } ))))
+
+let inline_lazy_force arg loc =
+ if !Clflags.native_code then
+ (* Lswitch generates compact and efficient native code *)
+ inline_lazy_force_switch arg loc
+ else
+ (* generating bytecode: Lswitch would generate too many rather big
+ tables (~ 250 elts); conditionals are better *)
+ inline_lazy_force_cond arg loc
+
+let make_lazy_matching def = function
+ [] -> fatal_error "Matching.make_lazy_matching"
+ | (arg,mut) :: argl ->
+ { cases = [];
+ args =
+ (inline_lazy_force arg Location.none, Strict) :: argl;
+ default = make_default matcher_lazy def }
+
+let divide_lazy p ctx pm =
+ divide_line
+ (filter_ctx p)
+ make_lazy_matching
+ get_arg_lazy
+ p ctx pm
+
+(* Matching against a tuple pattern *)
+
+
+let get_args_tuple arity p rem = match p with
+| {pat_desc = Tpat_any} -> omegas arity @ rem
+| {pat_desc = Tpat_tuple args} ->
+ args @ rem
+| _ -> assert false
+
+let matcher_tuple arity p rem = match p.pat_desc with
+| Tpat_or (_,_,_) -> raise OrPat
+| Tpat_var _ -> get_args_tuple arity omega rem
+| _ -> get_args_tuple arity p rem
+
+let make_tuple_matching arity def = function
+ [] -> fatal_error "Matching.make_tuple_matching"
+ | (arg, mut) :: argl ->
+ let rec make_args pos =
+ if pos >= arity
+ then argl
+ else (Lprim(Pfield pos, [arg]), Alias) :: make_args (pos + 1) in
+ {cases = []; args = make_args 0 ;
+ default=make_default (matcher_tuple arity) def}
+
+
+let divide_tuple arity p ctx pm =
+ divide_line
+ (filter_ctx p)
+ (make_tuple_matching arity)
+ (get_args_tuple arity) p ctx pm
+
+(* Matching against a record pattern *)
+
+
+let record_matching_line num_fields lbl_pat_list =
+ let patv = Array.make num_fields omega in
+ List.iter (fun (_, lbl, pat) -> patv.(lbl.lbl_pos) <- pat) lbl_pat_list;
+ Array.to_list patv
+
+let get_args_record num_fields p rem = match p with
+| {pat_desc=Tpat_any} ->
+ record_matching_line num_fields [] @ rem
+| {pat_desc=Tpat_record (lbl_pat_list,_)} ->
+ record_matching_line num_fields lbl_pat_list @ rem
+| _ -> assert false
+
+let matcher_record num_fields p rem = match p.pat_desc with
+| Tpat_or (_,_,_) -> raise OrPat
+| Tpat_var _ -> get_args_record num_fields omega rem
+| _ -> get_args_record num_fields p rem
+
+let make_record_matching all_labels def = function
+ [] -> fatal_error "Matching.make_record_matching"
+ | ((arg, mut) :: argl) ->
+ let rec make_args pos =
+ if pos >= Array.length all_labels then argl else begin
+ let lbl = all_labels.(pos) in
+ let access =
+ match lbl.lbl_repres with
+ Record_regular | Record_inlined _ -> Pfield lbl.lbl_pos
+ | Record_float -> Pfloatfield lbl.lbl_pos
+ | Record_extension -> Pfield (lbl.lbl_pos + 1)
+ in
+ let str =
+ match lbl.lbl_mut with
+ Immutable -> Alias
+ | Mutable -> StrictOpt in
+ (Lprim(access, [arg]), str) :: make_args(pos + 1)
+ end in
+ let nfields = Array.length all_labels in
+ let def= make_default (matcher_record nfields) def in
+ {cases = []; args = make_args 0 ; default = def}
+
+
+let divide_record all_labels p ctx pm =
+ let get_args = get_args_record (Array.length all_labels) in
+ divide_line
+ (filter_ctx p)
+ (make_record_matching all_labels)
+ get_args
+ p ctx pm
+
+(* Matching against an array pattern *)
+
+let get_key_array = function
+ | {pat_desc=Tpat_array patl} -> List.length patl
+ | _ -> assert false
+
+let get_args_array p rem = match p with
+| {pat_desc=Tpat_array patl} -> patl@rem
+| _ -> assert false
+
+let matcher_array len p rem = match p.pat_desc with
+| Tpat_or (_,_,_) -> raise OrPat
+| Tpat_array args when List.length args=len -> args @ rem
+| Tpat_any -> Parmatch.omegas len @ rem
+| _ -> raise NoMatch
+
+let make_array_matching kind p def ctx = function
+ | [] -> fatal_error "Matching.make_array_matching"
+ | ((arg, mut) :: argl) ->
+ let len = get_key_array p in
+ let rec make_args pos =
+ if pos >= len
+ then argl
+ else (Lprim(Parrayrefu kind, [arg; Lconst(Const_base(Const_int pos))]),
+ StrictOpt) :: make_args (pos + 1) in
+ let def = make_default (matcher_array len) def
+ and ctx = filter_ctx p ctx in
+ {pm={cases = []; args = make_args 0 ; default = def} ;
+ ctx=ctx ;
+ pat = normalize_pat p}
+
+let divide_array kind ctx pm =
+ divide
+ (make_array_matching kind)
+ (=) get_key_array get_args_array ctx pm
+
+
+(*
+ Specific string test sequence
+ Will be called by the bytecode compiler, from bytegen.ml.
+ The strategy is first dichotomic search (we perform 3-way tests
+ with compare_string), then sequence of equality tests
+ when there are less then T=strings_test_threshold static strings to match.
+
+ Increasing T entails (slightly) less code, decreasing T
+ (slightly) favors runtime speed.
+ T=8 looks a decent tradeoff.
+*)
+
+(* Utilities *)
+
+let strings_test_threshold = 8
+
+let prim_string_notequal =
+ Pccall(Primitive.simple
+ ~name:"caml_string_notequal"
+ ~arity:2
+ ~alloc:false)
+
+let prim_string_compare =
+ Pccall(Primitive.simple
+ ~name:"caml_string_compare"
+ ~arity:2
+ ~alloc:false)
+
+let bind_sw arg k = match arg with
+| Lvar _ -> k arg
+| _ ->
+ let id = Ident.create "switch" in
+ Llet (Strict,id,arg,k (Lvar id))
+
+
+(* Sequential equality tests *)
+
+let make_string_test_sequence arg sw d =
+ let d,sw = match d with
+ | None ->
+ begin match sw with
+ | (_,d)::sw -> d,sw
+ | [] -> assert false
+ end
+ | Some d -> d,sw in
+ bind_sw arg
+ (fun arg ->
+ List.fold_right
+ (fun (s,lam) k ->
+ Lifthenelse
+ (Lprim
+ (prim_string_notequal,
+ [arg; Lconst (Const_immstring s)]),
+ k,lam))
+ sw d)
+
+let rec split k xs = match xs with
+| [] -> assert false
+| x0::xs ->
+ if k <= 1 then [],x0,xs
+ else
+ let xs,y0,ys = split (k-2) xs in
+ x0::xs,y0,ys
+
+let zero_lam = Lconst (Const_base (Const_int 0))
+
+let tree_way_test arg lt eq gt =
+ Lifthenelse
+ (Lprim (Pintcomp Clt,[arg;zero_lam]),lt,
+ Lifthenelse(Lprim (Pintcomp Clt,[zero_lam;arg]),gt,eq))
+
+(* Dichotomic tree *)
+
+
+let rec do_make_string_test_tree arg sw delta d =
+ let len = List.length sw in
+ if len <= strings_test_threshold+delta then
+ make_string_test_sequence arg sw d
+ else
+ let lt,(s,act),gt = split len sw in
+ bind_sw
+ (Lprim
+ (prim_string_compare,
+ [arg; Lconst (Const_immstring s)];))
+ (fun r ->
+ tree_way_test r
+ (do_make_string_test_tree arg lt delta d)
+ act
+ (do_make_string_test_tree arg gt delta d))
+
+(* Entry point *)
+let expand_stringswitch arg sw d = match d with
+| None ->
+ bind_sw arg
+ (fun arg -> do_make_string_test_tree arg sw 0 None)
+| Some e ->
+ bind_sw arg
+ (fun arg ->
+ make_catch e
+ (fun d -> do_make_string_test_tree arg sw 1 (Some d)))
+
+(**********************)
+(* Generic test trees *)
+(**********************)
+
+(* Sharing *)
+
+(* Add handler, if shared *)
+let handle_shared () =
+ let hs = ref (fun x -> x) in
+ let handle_shared act = match act with
+ | Switch.Single act -> act
+ | Switch.Shared act ->
+ let i,h = make_catch_delayed act in
+ let ohs = !hs in
+ hs := (fun act -> h (ohs act)) ;
+ make_exit i in
+ hs,handle_shared
+
+
+let share_actions_tree sw d =
+ let store = StoreExp.mk_store () in
+(* Default action is always shared *)
+ let d =
+ match d with
+ | None -> None
+ | Some d -> Some (store.Switch.act_store_shared d) in
+(* Store all other actions *)
+ let sw =
+ List.map (fun (cst,act) -> cst,store.Switch.act_store act) sw in
+
+(* Retrieve all actions, includint potentiel default *)
+ let acts = store.Switch.act_get_shared () in
+
+(* Array of actual actions *)
+ let hs,handle_shared = handle_shared () in
+ let acts = Array.map handle_shared acts in
+
+(* Recontruct default and switch list *)
+ let d = match d with
+ | None -> None
+ | Some d -> Some (acts.(d)) in
+ let sw = List.map (fun (cst,j) -> cst,acts.(j)) sw in
+ !hs,sw,d
+
+(* Note: dichotomic search requires sorted input with no duplicates *)
+let rec uniq_lambda_list sw = match sw with
+ | []|[_] -> sw
+ | (c1,_ as p1)::((c2,_)::sw2 as sw1) ->
+ if const_compare c1 c2 = 0 then uniq_lambda_list (p1::sw2)
+ else p1::uniq_lambda_list sw1
+
+let sort_lambda_list l =
+ let l =
+ List.stable_sort (fun (x,_) (y,_) -> const_compare x y) l in
+ uniq_lambda_list l
+
+let rec cut n l =
+ if n = 0 then [],l
+ else match l with
+ [] -> raise (Invalid_argument "cut")
+ | a::l -> let l1,l2 = cut (n-1) l in a::l1, l2
+
+let rec do_tests_fail fail tst arg = function
+ | [] -> fail
+ | (c, act)::rem ->
+ Lifthenelse
+ (Lprim (tst, [arg ; Lconst (Const_base c)]),
+ do_tests_fail fail tst arg rem,
+ act)
+
+let rec do_tests_nofail tst arg = function
+ | [] -> fatal_error "Matching.do_tests_nofail"
+ | [_,act] -> act
+ | (c,act)::rem ->
+ Lifthenelse
+ (Lprim (tst, [arg ; Lconst (Const_base c)]),
+ do_tests_nofail tst arg rem,
+ act)
+
+let make_test_sequence fail tst lt_tst arg const_lambda_list =
+ let const_lambda_list = sort_lambda_list const_lambda_list in
+ let hs,const_lambda_list,fail =
+ share_actions_tree const_lambda_list fail in
+
+ let rec make_test_sequence const_lambda_list =
+ if List.length const_lambda_list >= 4 && lt_tst <> Pignore then
+ split_sequence const_lambda_list
+ else match fail with
+ | None -> do_tests_nofail tst arg const_lambda_list
+ | Some fail -> do_tests_fail fail tst arg const_lambda_list
+
+ and split_sequence const_lambda_list =
+ let list1, list2 =
+ cut (List.length const_lambda_list / 2) const_lambda_list in
+ Lifthenelse(Lprim(lt_tst,[arg; Lconst(Const_base (fst(List.hd list2)))]),
+ make_test_sequence list1, make_test_sequence list2)
+ in
+ hs (make_test_sequence const_lambda_list)
+
+
+let rec explode_inter offset i j act k =
+ if i <= j then
+ explode_inter offset i (j-1) act ((j-offset,act)::k)
+ else
+ k
+
+let max_vals cases acts =
+ let vals = Array.make (Array.length acts) 0 in
+ for i=Array.length cases-1 downto 0 do
+ let l,h,act = cases.(i) in
+ vals.(act) <- h - l + 1 + vals.(act)
+ done ;
+ let max = ref 0 in
+ for i = Array.length vals-1 downto 0 do
+ if vals.(i) >= vals.(!max) then
+ max := i
+ done ;
+ if vals.(!max) > 1 then
+ !max
+ else
+ -1
+
+let as_int_list cases acts =
+ let default = max_vals cases acts in
+ let min_key,_,_ = cases.(0)
+ and _,max_key,_ = cases.(Array.length cases-1) in
+
+ let rec do_rec i k =
+ if i >= 0 then
+ let low, high, act = cases.(i) in
+ if act = default then
+ do_rec (i-1) k
+ else
+ do_rec (i-1) (explode_inter min_key low high acts.(act) k)
+ else
+ k in
+ min_key, max_key,do_rec (Array.length cases-1) [],
+ (if default >= 0 then Some acts.(default) else None)
+
+
+module SArg = struct
+ type primitive = Lambda.primitive
+
+ let eqint = Pintcomp Ceq
+ let neint = Pintcomp Cneq
+ let leint = Pintcomp Cle
+ let ltint = Pintcomp Clt
+ let geint = Pintcomp Cge
+ let gtint = Pintcomp Cgt
+
+ type act = Lambda.lambda
+
+ let make_prim p args = Lprim (p,args)
+ let make_offset arg n = match n with
+ | 0 -> arg
+ | _ -> Lprim (Poffsetint n,[arg])
+
+ let bind arg body =
+ let newvar,newarg = match arg with
+ | Lvar v -> v,arg
+ | _ ->
+ let newvar = Ident.create "switcher" in
+ newvar,Lvar newvar in
+ bind Alias newvar arg (body newarg)
+ let make_const i = Lconst (Const_base (Const_int i))
+ let make_isout h arg = Lprim (Pisout, [h ; arg])
+ let make_isin h arg = Lprim (Pnot,[make_isout h arg])
+ let make_if cond ifso ifnot = Lifthenelse (cond, ifso, ifnot)
+ let make_switch arg cases acts =
+ let l = ref [] in
+ for i = Array.length cases-1 downto 0 do
+ l := (i,acts.(cases.(i))) :: !l
+ done ;
+ Lswitch(arg,
+ {sw_numconsts = Array.length cases ; sw_consts = !l ;
+ sw_numblocks = 0 ; sw_blocks = [] ;
+ sw_failaction = None})
+ let make_catch = make_catch_delayed
+ let make_exit = make_exit
+
+end
+
+(* Action sharing for Lswitch argument *)
+let share_actions_sw sw =
+(* Attempt sharing on all actions *)
+ let store = StoreExp.mk_store () in
+ let fail = match sw.sw_failaction with
+ | None -> None
+ | Some fail ->
+ (* Fail is translated to exit, whatever happens *)
+ Some (store.Switch.act_store_shared fail) in
+ let consts =
+ List.map
+ (fun (i,e) -> i,store.Switch.act_store e)
+ sw.sw_consts
+ and blocks =
+ List.map
+ (fun (i,e) -> i,store.Switch.act_store e)
+ sw.sw_blocks in
+ let acts = store.Switch.act_get_shared () in
+ let hs,handle_shared = handle_shared () in
+ let acts = Array.map handle_shared acts in
+ let fail = match fail with
+ | None -> None
+ | Some fail -> Some (acts.(fail)) in
+ !hs,
+ { sw with
+ sw_consts = List.map (fun (i,j) -> i,acts.(j)) consts ;
+ sw_blocks = List.map (fun (i,j) -> i,acts.(j)) blocks ;
+ sw_failaction = fail; }
+
+(* Reintroduce fail action in switch argument,
+ for the sake of avoiding carrying over huge switches *)
+
+let reintroduce_fail sw = match sw.sw_failaction with
+| None ->
+ let t = Hashtbl.create 17 in
+ let seen (_,l) = match as_simple_exit l with
+ | Some i ->
+ let old = try Hashtbl.find t i with Not_found -> 0 in
+ Hashtbl.replace t i (old+1)
+ | None -> () in
+ List.iter seen sw.sw_consts ;
+ List.iter seen sw.sw_blocks ;
+ let i_max = ref (-1)
+ and max = ref (-1) in
+ Hashtbl.iter
+ (fun i c ->
+ if c > !max then begin
+ i_max := i ;
+ max := c
+ end) t ;
+ if !max >= 3 then
+ let default = !i_max in
+ let remove =
+ List.filter
+ (fun (_,lam) -> match as_simple_exit lam with
+ | Some j -> j <> default
+ | None -> true) in
+ {sw with
+ sw_consts = remove sw.sw_consts ;
+ sw_blocks = remove sw.sw_blocks ;
+ sw_failaction = Some (make_exit default)}
+ else sw
+| Some _ -> sw
+
+
+module Switcher = Switch.Make(SArg)
+open Switch
+
+let lambda_of_int i = Lconst (Const_base (Const_int i))
+
+let rec last def = function
+ | [] -> def
+ | [x,_] -> x
+ | _::rem -> last def rem
+
+let get_edges low high l = match l with
+| [] -> low, high
+| (x,_)::_ -> x, last high l
+
+
+let as_interval_canfail fail low high l =
+ let store = StoreExp.mk_store () in
+
+ let do_store tag act =
+
+ let i = store.act_store act in
+(*
+ eprintf "STORE [%s] %i %s\n" tag i (string_of_lam act) ;
+*)
+ i in
+
+ let rec nofail_rec cur_low cur_high cur_act = function
+ | [] ->
+ if cur_high = high then
+ [cur_low,cur_high,cur_act]
+ else
+ [(cur_low,cur_high,cur_act) ; (cur_high+1,high, 0)]
+ | ((i,act_i)::rem) as all ->
+ let act_index = do_store "NO" act_i in
+ if cur_high+1= i then
+ if act_index=cur_act then
+ nofail_rec cur_low i cur_act rem
+ else if act_index=0 then
+ (cur_low,i-1, cur_act)::fail_rec i i rem
+ else
+ (cur_low, i-1, cur_act)::nofail_rec i i act_index rem
+ else if act_index = 0 then
+ (cur_low, cur_high, cur_act)::
+ fail_rec (cur_high+1) (cur_high+1) all
+ else
+ (cur_low, cur_high, cur_act)::
+ (cur_high+1,i-1,0)::
+ nofail_rec i i act_index rem
+
+ and fail_rec cur_low cur_high = function
+ | [] -> [(cur_low, cur_high, 0)]
+ | (i,act_i)::rem ->
+ let index = do_store "YES" act_i in
+ if index=0 then fail_rec cur_low i rem
+ else
+ (cur_low,i-1,0)::
+ nofail_rec i i index rem in
+
+ let init_rec = function
+ | [] -> [low,high,0]
+ | (i,act_i)::rem ->
+ let index = do_store "INIT" act_i in
+ if index=0 then
+ fail_rec low i rem
+ else
+ if low < i then
+ (low,i-1,0)::nofail_rec i i index rem
+ else
+ nofail_rec i i index rem in
+
+ assert (do_store "FAIL" fail = 0) ; (* fail has action index 0 *)
+ let r = init_rec l in
+ Array.of_list r, store
+
+let as_interval_nofail l =
+ let store = StoreExp.mk_store () in
+
+ let rec i_rec cur_low cur_high cur_act = function
+ | [] ->
+ [cur_low, cur_high, cur_act]
+ | (i,act)::rem ->
+ let act_index = store.act_store act in
+ if act_index = cur_act then
+ i_rec cur_low i cur_act rem
+ else
+ (cur_low, cur_high, cur_act)::
+ i_rec i i act_index rem in
+ let inters = match l with
+ | (i,act)::rem ->
+ let act_index = store.act_store act in
+ i_rec i i act_index rem
+ | _ -> assert false in
+
+ Array.of_list inters, store
+
+
+let sort_int_lambda_list l =
+ List.sort
+ (fun (i1,_) (i2,_) ->
+ if i1 < i2 then -1
+ else if i2 < i1 then 1
+ else 0)
+ l
+
+let as_interval fail low high l =
+ let l = sort_int_lambda_list l in
+ get_edges low high l,
+ (match fail with
+ | None -> as_interval_nofail l
+ | Some act -> as_interval_canfail act low high l)
+
+let call_switcher fail arg low high int_lambda_list =
+ let edges, (cases, actions) =
+ as_interval fail low high int_lambda_list in
+ Switcher.zyva edges arg cases actions
+
+
+let exists_ctx ok ctx =
+ List.exists
+ (function
+ | {right=p::_} -> ok p
+ | _ -> assert false)
+ ctx
+
+let rec list_as_pat = function
+ | [] -> fatal_error "Matching.list_as_pat"
+ | [pat] -> pat
+ | pat::rem ->
+ {pat with pat_desc = Tpat_or (pat,list_as_pat rem,None)}
+
+
+let rec pat_as_list k = function
+ | {pat_desc=Tpat_or (p1,p2,_)} ->
+ pat_as_list (pat_as_list k p2) p1
+ | p -> p::k
+
+(* Extracting interesting patterns *)
+exception All
+
+let rec extract_pat seen k p = match p.pat_desc with
+| Tpat_or (p1,p2,_) ->
+ let k1,seen1 = extract_pat seen k p1 in
+ extract_pat seen1 k1 p2
+| Tpat_alias (p,_,_) ->
+ extract_pat seen k p
+| Tpat_var _|Tpat_any ->
+ raise All
+| _ ->
+ let q = normalize_pat p in
+ if List.exists (compat q) seen then
+ k, seen
+ else
+ q::k, q::seen
+
+let extract_mat seen pss =
+ let r,_ =
+ List.fold_left
+ (fun (k,seen) ps -> match ps with
+ | p::_ -> extract_pat seen k p
+ | _ -> assert false)
+ ([],seen)
+ pss in
+ r
+
+
+
+let complete_pats_constrs = function
+ | p::_ as pats ->
+ List.map
+ (pat_of_constr p)
+ (complete_constrs p (List.map get_key_constr pats))
+ | _ -> assert false
+
+
+let mk_res get_key env last_choice idef cant_fail ctx =
+
+ let env,fail,jumps_fail = match last_choice with
+ | [] ->
+ env, None, jumps_empty
+ | [p] when group_var p ->
+ env,
+ Some (Lstaticraise (idef,[])),
+ jumps_singleton idef ctx
+ | _ ->
+ (idef,cant_fail,last_choice)::env,
+ None, jumps_empty in
+ let klist,jumps =
+ List.fold_right
+ (fun (i,cant_fail,pats) (klist,jumps) ->
+ let act = Lstaticraise (i,[])
+ and pat = list_as_pat pats in
+ let klist =
+ List.fold_right
+ (fun pat klist -> (get_key pat,act)::klist)
+ pats klist
+ and ctx = if cant_fail then ctx else ctx_lub pat ctx in
+ klist,jumps_add i ctx jumps)
+ env ([],jumps_fail) in
+ fail, klist, jumps
+
+
+(*
+ Following two ``failaction'' function compute n, the trap handler
+ to jump to in case of failure of elementary tests
+*)
+
+let mk_failaction_neg partial ctx def = match partial with
+| Partial ->
+ begin match def with
+ | (_,idef)::_ ->
+ Some (Lstaticraise (idef,[])),jumps_singleton idef ctx
+ | [] ->
+ (* Act as Total, this means
+ If no appropriate default matrix exists,
+ then this switch cannot fail *)
+ None, jumps_empty
+ end
+| Total ->
+ None, jumps_empty
+
+
+
+(* Conforme a l'article et plus simple qu'avant *)
+let mk_failaction_pos partial seen ctx defs =
+ if dbg then begin
+ prerr_endline "**POS**" ;
+ pretty_def defs ;
+ ()
+ end ;
+ let rec scan_def env to_test defs = match to_test,defs with
+ | ([],_)|(_,[]) ->
+ List.fold_left
+ (fun (klist,jumps) (pats,i)->
+ let action = Lstaticraise (i,[]) in
+ let klist =
+ List.fold_right
+ (fun pat r -> (get_key_constr pat,action)::r)
+ pats klist
+ and jumps =
+ jumps_add i (ctx_lub (list_as_pat pats) ctx) jumps in
+ klist,jumps)
+ ([],jumps_empty) env
+ | _,(pss,idef)::rem ->
+ let now, later =
+ List.partition
+ (fun (p,p_ctx) -> ctx_match p_ctx pss) to_test in
+ match now with
+ | [] -> scan_def env to_test rem
+ | _ -> scan_def ((List.map fst now,idef)::env) later rem in
+
+ let fail_pats = complete_pats_constrs seen in
+ if List.length fail_pats < 32 then begin
+ let fail,jmps =
+ scan_def
+ []
+ (List.map
+ (fun pat -> pat, ctx_lub pat ctx)
+ fail_pats)
+ defs in
+ if dbg then begin
+ eprintf "POSITIVE JUMPS [%i]:\n" (List.length fail_pats);
+ pretty_jumps jmps
+ end ;
+ None,fail,jmps
+ end else begin (* Two many non-matched constructors -> reduced information *)
+ if dbg then eprintf "POS->NEG!!!\n%!" ;
+ let fail,jumps = mk_failaction_neg partial ctx defs in
+ if dbg then
+ eprintf "FAIL: %s\n"
+ (match fail with
+ | None -> "<none>"
+ | Some lam -> string_of_lam lam) ;
+ fail,[],jumps
+ end
+
+let combine_constant arg cst partial ctx def
+ (const_lambda_list, total, pats) =
+ let fail, local_jumps =
+ mk_failaction_neg partial ctx def in
+ let lambda1 =
+ match cst with
+ | Const_int _ ->
+ let int_lambda_list =
+ List.map (function Const_int n, l -> n,l | _ -> assert false)
+ const_lambda_list in
+ call_switcher fail arg min_int max_int int_lambda_list
+ | Const_char _ ->
+ let int_lambda_list =
+ List.map (function Const_char c, l -> (Char.code c, l)
+ | _ -> assert false)
+ const_lambda_list in
+ call_switcher fail arg 0 255 int_lambda_list
+ | Const_string _ ->
+(* Note as the bytecode compiler may resort to dichotmic search,
+ the clauses of strinswitch are sorted with duplicate removed.
+ This partly applies to the native code compiler, which requires
+ no duplicates *)
+ let const_lambda_list = sort_lambda_list const_lambda_list in
+ let sw =
+ List.map
+ (fun (c,act) -> match c with
+ | Const_string (s,_) -> s,act
+ | _ -> assert false)
+ const_lambda_list in
+ let hs,sw,fail = share_actions_tree sw fail in
+ hs (Lstringswitch (arg,sw,fail))
+ | Const_float _ ->
+ make_test_sequence
+ fail
+ (Pfloatcomp Cneq) (Pfloatcomp Clt)
+ arg const_lambda_list
+ | Const_int32 _ ->
+ make_test_sequence
+ fail
+ (Pbintcomp(Pint32, Cneq)) (Pbintcomp(Pint32, Clt))
+ arg const_lambda_list
+ | Const_int64 _ ->
+ make_test_sequence
+ fail
+ (Pbintcomp(Pint64, Cneq)) (Pbintcomp(Pint64, Clt))
+ arg const_lambda_list
+ | Const_nativeint _ ->
+ make_test_sequence
+ fail
+ (Pbintcomp(Pnativeint, Cneq)) (Pbintcomp(Pnativeint, Clt))
+ arg const_lambda_list
+ in lambda1,jumps_union local_jumps total
+
+
+
+let split_cases tag_lambda_list =
+ let rec split_rec = function
+ [] -> ([], [])
+ | (cstr, act) :: rem ->
+ let (consts, nonconsts) = split_rec rem in
+ match cstr with
+ Cstr_constant n -> ((n, act) :: consts, nonconsts)
+ | Cstr_block n -> (consts, (n, act) :: nonconsts)
+ | _ -> assert false in
+ let const, nonconst = split_rec tag_lambda_list in
+ sort_int_lambda_list const,
+ sort_int_lambda_list nonconst
+
+let split_extension_cases tag_lambda_list =
+ let rec split_rec = function
+ [] -> ([], [])
+ | (cstr, act) :: rem ->
+ let (consts, nonconsts) = split_rec rem in
+ match cstr with
+ Cstr_extension(path, true) -> ((path, act) :: consts, nonconsts)
+ | Cstr_extension(path, false) -> (consts, (path, act) :: nonconsts)
+ | _ -> assert false in
+ split_rec tag_lambda_list
+
+
+let combine_constructor arg ex_pat cstr partial ctx def
+ (tag_lambda_list, total1, pats) =
+ if cstr.cstr_consts < 0 then begin
+ (* Special cases for extensions *)
+ let fail, local_jumps =
+ mk_failaction_neg partial ctx def in
+ let lambda1 =
+ let consts, nonconsts = split_extension_cases tag_lambda_list in
+ let default, consts, nonconsts =
+ match fail with
+ | None ->
+ begin match consts, nonconsts with
+ | _, (_, act)::rem -> act, consts, rem
+ | (_, act)::rem, _ -> act, rem, nonconsts
+ | _ -> assert false
+ end
+ | Some fail -> fail, consts, nonconsts in
+ let nonconst_lambda =
+ match nonconsts with
+ [] -> default
+ | _ ->
+ let tag = Ident.create "tag" in
+ let tests =
+ List.fold_right
+ (fun (path, act) rem ->
+ Lifthenelse(Lprim(Pintcomp Ceq,
+ [Lvar tag;
+ transl_path ex_pat.pat_env path]),
+ act, rem))
+ nonconsts
+ default
+ in
+ Llet(Alias, tag, Lprim(Pfield 0, [arg]), tests)
+ in
+ List.fold_right
+ (fun (path, act) rem ->
+ Lifthenelse(Lprim(Pintcomp Ceq,
+ [arg; transl_path ex_pat.pat_env path]),
+ act, rem))
+ consts
+ nonconst_lambda
+ in
+ lambda1, jumps_union local_jumps total1
+ end else begin
+ (* Regular concrete type *)
+ let ncases = List.length tag_lambda_list
+ and nconstrs = cstr.cstr_consts + cstr.cstr_nonconsts in
+ let sig_complete = ncases = nconstrs in
+ let fail_opt,fails,local_jumps =
+ if sig_complete then None,[],jumps_empty
+ else
+ mk_failaction_pos partial pats ctx def in
+
+ let tag_lambda_list = fails @ tag_lambda_list in
+ let (consts, nonconsts) = split_cases tag_lambda_list in
+ let lambda1 =
+ match fail_opt,same_actions tag_lambda_list with
+ | None,Some act -> act (* Identical actions, no failure *)
+ | _ ->
+ match
+ (cstr.cstr_consts, cstr.cstr_nonconsts, consts, nonconsts)
+ with
+ | (1, 1, [0, act1], [0, act2]) ->
+ (* Typically, match on lists, will avoid isint primitive in that
+ case *)
+ Lifthenelse(arg, act2, act1)
+ | (n,0,_,[]) -> (* The type defines constant constructors only *)
+ call_switcher fail_opt arg 0 (n-1) consts
+ | (n, _, _, _) ->
+ let act0 =
+ (* = Some act when all non-const constructors match to act *)
+ match fail_opt,nonconsts with
+ | Some a,[] -> Some a
+ | Some _,_ ->
+ if List.length nonconsts = cstr.cstr_nonconsts then
+ same_actions nonconsts
+ else None
+ | None,_ -> same_actions nonconsts in
+ match act0 with
+ | Some act ->
+ Lifthenelse
+ (Lprim (Pisint, [arg]),
+ call_switcher
+ fail_opt arg
+ 0 (n-1) consts,
+ act)
+(* Emit a switch, as bytecode implements this sophisticated instruction *)
+ | None ->
+ let sw =
+ {sw_numconsts = cstr.cstr_consts; sw_consts = consts;
+ sw_numblocks = cstr.cstr_nonconsts; sw_blocks = nonconsts;
+ sw_failaction = fail_opt} in
+ let hs,sw = share_actions_sw sw in
+ let sw = reintroduce_fail sw in
+ hs (Lswitch (arg,sw)) in
+ lambda1, jumps_union local_jumps total1
+ end
+
+let make_test_sequence_variant_constant fail arg int_lambda_list =
+ let _, (cases, actions) =
+ as_interval fail min_int max_int int_lambda_list in
+ Switcher.test_sequence arg cases actions
+
+let call_switcher_variant_constant fail arg int_lambda_list =
+ call_switcher fail arg min_int max_int int_lambda_list
+
+
+let call_switcher_variant_constr fail arg int_lambda_list =
+ let v = Ident.create "variant" in
+ Llet(Alias, v, Lprim(Pfield 0, [arg]),
+ call_switcher
+ fail (Lvar v) min_int max_int int_lambda_list)
+
+let combine_variant row arg partial ctx def (tag_lambda_list, total1, pats) =
+ let row = Btype.row_repr row in
+ let num_constr = ref 0 in
+ if row.row_closed then
+ List.iter
+ (fun (_, f) ->
+ match Btype.row_field_repr f with
+ Rabsent | Reither(true, _::_, _, _) -> ()
+ | _ -> incr num_constr)
+ row.row_fields
+ else
+ num_constr := max_int;
+ let test_int_or_block arg if_int if_block =
+ Lifthenelse(Lprim (Pisint, [arg]), if_int, if_block) in
+ let sig_complete = List.length tag_lambda_list = !num_constr
+ and one_action = same_actions tag_lambda_list in
+ let fail, local_jumps =
+ if
+ sig_complete || (match partial with Total -> true | _ -> false)
+ then
+ None, jumps_empty
+ else
+ mk_failaction_neg partial ctx def in
+ let (consts, nonconsts) = split_cases tag_lambda_list in
+ let lambda1 = match fail, one_action with
+ | None, Some act -> act
+ | _,_ ->
+ match (consts, nonconsts) with
+ | ([n, act1], [m, act2]) when fail=None ->
+ test_int_or_block arg act1 act2
+ | (_, []) -> (* One can compare integers and pointers *)
+ make_test_sequence_variant_constant fail arg consts
+ | ([], _) ->
+ let lam = call_switcher_variant_constr
+ fail arg nonconsts in
+ (* One must not dereference integers *)
+ begin match fail with
+ | None -> lam
+ | Some fail -> test_int_or_block arg fail lam
+ end
+ | (_, _) ->
+ let lam_const =
+ call_switcher_variant_constant
+ fail arg consts
+ and lam_nonconst =
+ call_switcher_variant_constr
+ fail arg nonconsts in
+ test_int_or_block arg lam_const lam_nonconst
+ in
+ lambda1, jumps_union local_jumps total1
+
+
+let combine_array arg kind partial ctx def
+ (len_lambda_list, total1, pats) =
+ let fail, local_jumps = mk_failaction_neg partial ctx def in
+ let lambda1 =
+ let newvar = Ident.create "len" in
+ let switch =
+ call_switcher
+ fail (Lvar newvar)
+ 0 max_int len_lambda_list in
+ bind
+ Alias newvar (Lprim(Parraylength kind, [arg])) switch in
+ lambda1, jumps_union local_jumps total1
+
+(* Insertion of debugging events *)
+
+let rec event_branch repr lam =
+ begin match lam, repr with
+ (_, None) ->
+ lam
+ | (Levent(lam', ev), Some r) ->
+ incr r;
+ Levent(lam', {lev_loc = ev.lev_loc;
+ lev_kind = ev.lev_kind;
+ lev_repr = repr;
+ lev_env = ev.lev_env})
+ | (Llet(str, id, lam, body), _) ->
+ Llet(str, id, lam, event_branch repr body)
+ | Lstaticraise _,_ -> lam
+ | (_, Some r) ->
+ Printlambda.lambda Format.str_formatter lam ;
+ fatal_error
+ ("Matching.event_branch: "^Format.flush_str_formatter ())
+ end
+
+
+(*
+ This exception is raised when the compiler cannot produce code
+ because control cannot reach the compiled clause,
+
+ Unused is raised initialy in compile_test.
+
+ compile_list (for compiling switch results) catch Unused
+
+ comp_match_handlers (for compililing splitted matches)
+ may reraise Unused
+
+
+*)
+
+exception Unused
+
+let compile_list compile_fun division =
+
+ let rec c_rec totals = function
+ | [] -> [], jumps_unions totals, []
+ | (key, cell) :: rem ->
+ begin match cell.ctx with
+ | [] -> c_rec totals rem
+ | _ ->
+ try
+ let (lambda1, total1) = compile_fun cell.ctx cell.pm in
+ let c_rem, total, new_pats =
+ c_rec
+ (jumps_map ctx_combine total1::totals) rem in
+ ((key,lambda1)::c_rem), total, (cell.pat::new_pats)
+ with
+ | Unused -> c_rec totals rem
+ end in
+ c_rec [] division
+
+
+let compile_orhandlers compile_fun lambda1 total1 ctx to_catch =
+ let rec do_rec r total_r = function
+ | [] -> r,total_r
+ | (mat,i,vars,pm)::rem ->
+ begin try
+ let ctx = select_columns mat ctx in
+ let handler_i, total_i = compile_fun ctx pm in
+ match raw_action r with
+ | Lstaticraise (j,args) ->
+ if i=j then
+ List.fold_right2 (bind Alias) vars args handler_i,
+ jumps_map (ctx_rshift_num (ncols mat)) total_i
+ else
+ do_rec r total_r rem
+ | _ ->
+ do_rec
+ (Lstaticcatch (r,(i,vars), handler_i))
+ (jumps_union
+ (jumps_remove i total_r)
+ (jumps_map (ctx_rshift_num (ncols mat)) total_i))
+ rem
+ with
+ | Unused ->
+ do_rec (Lstaticcatch (r, (i,vars), lambda_unit)) total_r rem
+ end in
+ do_rec lambda1 total1 to_catch
+
+
+let compile_test compile_fun partial divide combine ctx to_match =
+ let division = divide ctx to_match in
+ let c_div = compile_list compile_fun division in
+ match c_div with
+ | [],_,_ ->
+ begin match mk_failaction_neg partial ctx to_match.default with
+ | None,_ -> raise Unused
+ | Some l,total -> l,total
+ end
+ | _ ->
+ combine ctx to_match.default c_div
+
+(* Attempt to avoid some useless bindings by lowering them *)
+
+(* Approximation of v present in lam *)
+let rec approx_present v = function
+ | Lconst _ -> false
+ | Lstaticraise (_,args) ->
+ List.exists (fun lam -> approx_present v lam) args
+ | Lprim (_,args) ->
+ List.exists (fun lam -> approx_present v lam) args
+ | Llet (Alias, _, l1, l2) ->
+ approx_present v l1 || approx_present v l2
+ | Lvar vv -> Ident.same v vv
+ | _ -> true
+
+let rec lower_bind v arg lam = match lam with
+| Lifthenelse (cond, ifso, ifnot) ->
+ let pcond = approx_present v cond
+ and pso = approx_present v ifso
+ and pnot = approx_present v ifnot in
+ begin match pcond, pso, pnot with
+ | false, false, false -> lam
+ | false, true, false ->
+ Lifthenelse (cond, lower_bind v arg ifso, ifnot)
+ | false, false, true ->
+ Lifthenelse (cond, ifso, lower_bind v arg ifnot)
+ | _,_,_ -> bind Alias v arg lam
+ end
+| Lswitch (ls,({sw_consts=[i,act] ; sw_blocks = []} as sw))
+ when not (approx_present v ls) ->
+ Lswitch (ls, {sw with sw_consts = [i,lower_bind v arg act]})
+| Lswitch (ls,({sw_consts=[] ; sw_blocks = [i,act]} as sw))
+ when not (approx_present v ls) ->
+ Lswitch (ls, {sw with sw_blocks = [i,lower_bind v arg act]})
+| Llet (Alias, vv, lv, l) ->
+ if approx_present v lv then
+ bind Alias v arg lam
+ else
+ Llet (Alias, vv, lv, lower_bind v arg l)
+| _ ->
+ bind Alias v arg lam
+
+let bind_check str v arg lam = match str,arg with
+| _, Lvar _ ->bind str v arg lam
+| Alias,_ -> lower_bind v arg lam
+| _,_ -> bind str v arg lam
+
+let comp_exit ctx m = match m.default with
+| (_,i)::_ -> Lstaticraise (i,[]), jumps_singleton i ctx
+| _ -> fatal_error "Matching.comp_exit"
+
+
+
+let rec comp_match_handlers comp_fun partial ctx arg first_match next_matchs =
+ match next_matchs with
+ | [] -> comp_fun partial ctx arg first_match
+ | rem ->
+ let rec c_rec body total_body = function
+ | [] -> body, total_body
+ (* Hum, -1 meant never taken
+ | (-1,pm)::rem -> c_rec body total_body rem *)
+ | (i,pm)::rem ->
+ let ctx_i,total_rem = jumps_extract i total_body in
+ begin match ctx_i with
+ | [] -> c_rec body total_body rem
+ | _ ->
+ try
+ let li,total_i =
+ comp_fun
+ (match rem with [] -> partial | _ -> Partial)
+ ctx_i arg pm in
+ c_rec
+ (Lstaticcatch (body,(i,[]),li))
+ (jumps_union total_i total_rem)
+ rem
+ with
+ | Unused ->
+ c_rec (Lstaticcatch (body,(i,[]),lambda_unit))
+ total_rem rem
+ end in
+ try
+ let first_lam,total = comp_fun Partial ctx arg first_match in
+ c_rec first_lam total rem
+ with Unused -> match next_matchs with
+ | [] -> raise Unused
+ | (_,x)::xs -> comp_match_handlers comp_fun partial ctx arg x xs
+
+(* To find reasonable names for variables *)
+
+let rec name_pattern default = function
+ (pat :: patl, action) :: rem ->
+ begin match pat.pat_desc with
+ Tpat_var (id, _) -> id
+ | Tpat_alias(p, id, _) -> id
+ | _ -> name_pattern default rem
+ end
+ | _ -> Ident.create default
+
+let arg_to_var arg cls = match arg with
+| Lvar v -> v,arg
+| _ ->
+ let v = name_pattern "match" cls in
+ v,Lvar v
+
+
+(*
+ The main compilation function.
+ Input:
+ repr=used for inserting debug events
+ partial=exhaustiveness information from Parmatch
+ ctx=a context
+ m=a pattern matching
+
+ Output: a lambda term, a jump summary {..., exit number -> context, .. }
+*)
+
+let rec compile_match repr partial ctx m = match m with
+| { cases = [] } -> comp_exit ctx m
+| { cases = ([], action) :: rem } ->
+ if is_guarded action then begin
+ let (lambda, total) =
+ compile_match None partial ctx { m with cases = rem } in
+ event_branch repr (patch_guarded lambda action), total
+ end else
+ (event_branch repr action, jumps_empty)
+| { args = (arg, str)::argl } ->
+ let v,newarg = arg_to_var arg m.cases in
+ let first_match,rem =
+ split_precompile (Some v)
+ { m with args = (newarg, Alias) :: argl } in
+ let (lam, total) =
+ comp_match_handlers
+ ((if dbg then do_compile_matching_pr else do_compile_matching) repr)
+ partial ctx newarg first_match rem in
+ bind_check str v arg lam, total
+| _ -> assert false
+
+
+(* verbose version of do_compile_matching, for debug *)
+
+and do_compile_matching_pr repr partial ctx arg x =
+ prerr_string "COMPILE: " ;
+ prerr_endline (match partial with Partial -> "Partial" | Total -> "Total") ;
+ prerr_endline "MATCH" ;
+ pretty_precompiled x ;
+ prerr_endline "CTX" ;
+ pretty_ctx ctx ;
+ let (_, jumps) as r = do_compile_matching repr partial ctx arg x in
+ prerr_endline "JUMPS" ;
+ pretty_jumps jumps ;
+ r
+
+and do_compile_matching repr partial ctx arg pmh = match pmh with
+| Pm pm ->
+ let pat = what_is_cases pm.cases in
+ begin match pat.pat_desc with
+ | Tpat_any ->
+ compile_no_test
+ divide_var ctx_rshift repr partial ctx pm
+ | Tpat_tuple patl ->
+ compile_no_test
+ (divide_tuple (List.length patl) (normalize_pat pat)) ctx_combine
+ repr partial ctx pm
+ | Tpat_record ((_, lbl,_)::_,_) ->
+ compile_no_test
+ (divide_record lbl.lbl_all (normalize_pat pat))
+ ctx_combine repr partial ctx pm
+ | Tpat_constant cst ->
+ compile_test
+ (compile_match repr partial) partial
+ divide_constant
+ (combine_constant arg cst partial)
+ ctx pm
+ | Tpat_construct (_, cstr, _) ->
+ compile_test
+ (compile_match repr partial) partial
+ divide_constructor (combine_constructor arg pat cstr partial)
+ ctx pm
+ | Tpat_array _ ->
+ let kind = Typeopt.array_pattern_kind pat in
+ compile_test (compile_match repr partial) partial
+ (divide_array kind) (combine_array arg kind partial)
+ ctx pm
+ | Tpat_lazy _ ->
+ compile_no_test
+ (divide_lazy (normalize_pat pat))
+ ctx_combine repr partial ctx pm
+ | Tpat_variant(lab, _, row) ->
+ compile_test (compile_match repr partial) partial
+ (divide_variant !row)
+ (combine_variant !row arg partial)
+ ctx pm
+ | _ -> assert false
+ end
+| PmVar {inside=pmh ; var_arg=arg} ->
+ let lam, total =
+ do_compile_matching repr partial (ctx_lshift ctx) arg pmh in
+ lam, jumps_map ctx_rshift total
+| PmOr {body=body ; handlers=handlers} ->
+ let lam, total = compile_match repr partial ctx body in
+ compile_orhandlers (compile_match repr partial) lam total ctx handlers
+
+and compile_no_test divide up_ctx repr partial ctx to_match =
+ let {pm=this_match ; ctx=this_ctx } = divide ctx to_match in
+ let lambda,total = compile_match repr partial this_ctx this_match in
+ lambda, jumps_map up_ctx total
+
+
+
+
+(* The entry points *)
+
+(*
+ If there is a guard in a matching or a lazy pattern,
+ then set exhaustiveness info to Partial.
+ (because of side effects, assume the worst).
+
+ Notice that exhaustiveness information is trusted by the compiler,
+ that is, a match flagged as Total should not fail at runtime.
+ More specifically, for instance if match y with x::_ -> x uis flagged
+ total (as it happens during JoCaml compilation) then y cannot be []
+ at runtime. As a consequence, the static Total exhaustiveness information
+ have to to be downgraded to Partial, in the dubious cases where guards
+ or lazy pattern execute arbitrary code that may perform side effects
+ and change the subject values.
+LM:
+ Lazy pattern was PR #5992, initial patch by lwp25.
+ I have generalized teh patch, so as to also find mutable fields.
+*)
+
+let find_in_pat pred =
+ let rec find_rec p =
+ pred p.pat_desc ||
+ begin match p.pat_desc with
+ | Tpat_alias (p,_,_) | Tpat_variant (_,Some p,_) | Tpat_lazy p ->
+ find_rec p
+ | Tpat_tuple ps|Tpat_construct (_,_,ps) | Tpat_array ps ->
+ List.exists find_rec ps
+ | Tpat_record (lpats,_) ->
+ List.exists
+ (fun (_, _, p) -> find_rec p)
+ lpats
+ | Tpat_or (p,q,_) ->
+ find_rec p || find_rec q
+ | Tpat_constant _ | Tpat_var _
+ | Tpat_any | Tpat_variant (_,None,_) -> false
+ end in
+ find_rec
+
+let is_lazy_pat = function
+ | Tpat_lazy _ -> true
+ | Tpat_alias _ | Tpat_variant _ | Tpat_record _
+ | Tpat_tuple _|Tpat_construct _ | Tpat_array _
+ | Tpat_or _ | Tpat_constant _ | Tpat_var _ | Tpat_any
+ -> false
+
+let is_lazy p = find_in_pat is_lazy_pat p
+
+let have_mutable_field p = match p with
+| Tpat_record (lps,_) ->
+ List.exists
+ (fun (_,lbl,_) ->
+ match lbl.Types.lbl_mut with
+ | Mutable -> true
+ | Immutable -> false)
+ lps
+| Tpat_alias _ | Tpat_variant _ | Tpat_lazy _
+| Tpat_tuple _|Tpat_construct _ | Tpat_array _
+| Tpat_or _
+| Tpat_constant _ | Tpat_var _ | Tpat_any
+ -> false
+
+let is_mutable p = find_in_pat have_mutable_field p
+
+(* Downgrade Total when
+ 1. Matching accesses some mutable fields;
+ 2. And there are guards or lazy patterns.
+*)
+
+let check_partial is_mutable is_lazy pat_act_list = function
+ | Partial -> Partial
+ | Total ->
+ if
+ List.exists
+ (fun (pats, lam) ->
+ is_mutable pats && (is_guarded lam || is_lazy pats))
+ pat_act_list
+ then Partial
+ else Total
+
+let check_partial_list =
+ check_partial (List.exists is_mutable) (List.exists is_lazy)
+let check_partial = check_partial is_mutable is_lazy
+
+(* have toplevel handler when appropriate *)
+
+let start_ctx n = [{left=[] ; right = omegas n}]
+
+let check_total total lambda i handler_fun =
+ if jumps_is_empty total then
+ lambda
+ else begin
+ Lstaticcatch(lambda, (i,[]), handler_fun())
+ end
+
+let compile_matching loc repr handler_fun arg pat_act_list partial =
+ let partial = check_partial pat_act_list partial in
+ match partial with
+ | Partial ->
+ let raise_num = next_raise_count () in
+ let pm =
+ { cases = List.map (fun (pat, act) -> ([pat], act)) pat_act_list;
+ args = [arg, Strict] ;
+ default = [[[omega]],raise_num]} in
+ begin try
+ let (lambda, total) = compile_match repr partial (start_ctx 1) pm in
+ check_total total lambda raise_num handler_fun
+ with
+ | Unused -> assert false (* ; handler_fun() *)
+ end
+ | Total ->
+ let pm =
+ { cases = List.map (fun (pat, act) -> ([pat], act)) pat_act_list;
+ args = [arg, Strict] ;
+ default = []} in
+ let (lambda, total) = compile_match repr partial (start_ctx 1) pm in
+ assert (jumps_is_empty total) ;
+ lambda
+
+
+let partial_function loc () =
+ (* [Location.get_pos_info] is too expensive *)
+ let (fname, line, char) = Location.get_pos_info loc.Location.loc_start in
+ Lprim(Praise Raise_regular, [Lprim(Pmakeblock(0, Immutable),
+ [transl_normal_path Predef.path_match_failure;
+ Lconst(Const_block(0,
+ [Const_base(Const_string (fname, None));
+ Const_base(Const_int line);
+ Const_base(Const_int char)]))])])
+
+let for_function loc repr param pat_act_list partial =
+ compile_matching loc repr (partial_function loc) param pat_act_list partial
+
+(* In the following two cases, exhaustiveness info is not available! *)
+let for_trywith param pat_act_list =
+ compile_matching Location.none None
+ (fun () -> Lprim(Praise Raise_reraise, [param]))
+ param pat_act_list Partial
+
+let for_let loc param pat body =
+ compile_matching loc None (partial_function loc) param [pat, body] Partial
+
+(* Handling of tupled functions and matchings *)
+
+(* Easy case since variables are available *)
+let for_tupled_function loc paraml pats_act_list partial =
+ let partial = check_partial_list pats_act_list partial in
+ let raise_num = next_raise_count () in
+ let omegas = [List.map (fun _ -> omega) paraml] in
+ let pm =
+ { cases = pats_act_list;
+ args = List.map (fun id -> (Lvar id, Strict)) paraml ;
+ default = [omegas,raise_num]
+ } in
+ try
+ let (lambda, total) = compile_match None partial
+ (start_ctx (List.length paraml)) pm in
+ check_total total lambda raise_num (partial_function loc)
+ with
+ | Unused -> partial_function loc ()
+
+
+
+let flatten_pattern size p = match p.pat_desc with
+| Tpat_tuple args -> args
+| Tpat_any -> omegas size
+| _ -> raise Cannot_flatten
+
+let rec flatten_pat_line size p k = match p.pat_desc with
+| Tpat_any -> omegas size::k
+| Tpat_tuple args -> args::k
+| Tpat_or (p1,p2,_) -> flatten_pat_line size p1 (flatten_pat_line size p2 k)
+| Tpat_alias (p,_,_) -> (* Note: if this 'as' pat is here, then this is a
+ useless binding, solves PR #3780 *)
+ flatten_pat_line size p k
+| _ -> fatal_error "Matching.flatten_pat_line"
+
+let flatten_cases size cases =
+ List.map
+ (fun (ps,action) -> match ps with
+ | [p] -> flatten_pattern size p,action
+ | _ -> fatal_error "Matching.flatten_case")
+ cases
+
+let flatten_matrix size pss =
+ List.fold_right
+ (fun ps r -> match ps with
+ | [p] -> flatten_pat_line size p r
+ | _ -> fatal_error "Matching.flatten_matrix")
+ pss []
+
+let flatten_def size def =
+ List.map
+ (fun (pss,i) -> flatten_matrix size pss,i)
+ def
+
+let flatten_pm size args pm =
+ {args = args ; cases = flatten_cases size pm.cases ;
+ default = flatten_def size pm.default}
+
+
+let flatten_precompiled size args pmh = match pmh with
+| Pm pm -> Pm (flatten_pm size args pm)
+| PmOr {body=b ; handlers=hs ; or_matrix=m} ->
+ PmOr
+ {body=flatten_pm size args b ;
+ handlers=
+ List.map
+ (fun (mat,i,vars,pm) -> flatten_matrix size mat,i,vars,pm)
+ hs ;
+ or_matrix=flatten_matrix size m ;}
+| PmVar _ -> assert false
+
+(*
+ compiled_flattened is a ``comp_fun'' argument to comp_match_handlers.
+ Hence it needs a fourth argument, which it ignores
+*)
+
+let compile_flattened repr partial ctx _ pmh = match pmh with
+| Pm pm -> compile_match repr partial ctx pm
+| PmOr {body=b ; handlers=hs} ->
+ let lam, total = compile_match repr partial ctx b in
+ compile_orhandlers (compile_match repr partial) lam total ctx hs
+| PmVar _ -> assert false
+
+let do_for_multiple_match loc paraml pat_act_list partial =
+ let repr = None in
+ let partial = check_partial pat_act_list partial in
+ let raise_num,pm1 =
+ match partial with
+ | Partial ->
+ let raise_num = next_raise_count () in
+ raise_num,
+ { cases = List.map (fun (pat, act) -> ([pat], act)) pat_act_list;
+ args = [Lprim(Pmakeblock(0, Immutable), paraml), Strict] ;
+ default = [[[omega]],raise_num] }
+ | _ ->
+ -1,
+ { cases = List.map (fun (pat, act) -> ([pat], act)) pat_act_list;
+ args = [Lprim(Pmakeblock(0, Immutable), paraml), Strict] ;
+ default = [] } in
+
+ try
+ try
+(* Once for checking that compilation is possible *)
+ let next, nexts = split_precompile None pm1 in
+
+ let size = List.length paraml
+ and idl = List.map (fun _ -> Ident.create "match") paraml in
+ let args = List.map (fun id -> Lvar id, Alias) idl in
+
+ let flat_next = flatten_precompiled size args next
+ and flat_nexts =
+ List.map
+ (fun (e,pm) -> e,flatten_precompiled size args pm)
+ nexts in
+
+ let lam, total =
+ comp_match_handlers
+ (compile_flattened repr)
+ partial (start_ctx size) () flat_next flat_nexts in
+ List.fold_right2 (bind Strict) idl paraml
+ (match partial with
+ | Partial ->
+ check_total total lam raise_num (partial_function loc)
+ | Total ->
+ assert (jumps_is_empty total) ;
+ lam)
+ with Cannot_flatten ->
+ let (lambda, total) = compile_match None partial (start_ctx 1) pm1 in
+ begin match partial with
+ | Partial ->
+ check_total total lambda raise_num (partial_function loc)
+ | Total ->
+ assert (jumps_is_empty total) ;
+ lambda
+ end
+ with Unused ->
+ assert false (* ; partial_function loc () *)
+
+(* #PR4828: Believe it or not, the 'paraml' argument below
+ may not be side effect free. *)
+
+let arg_to_var arg cls = match arg with
+| Lvar v -> v,arg
+| _ ->
+ let v = name_pattern "match" cls in
+ v,Lvar v
+
+
+let param_to_var param = match param with
+| Lvar v -> v,None
+| _ -> Ident.create "match",Some param
+
+let bind_opt (v,eo) k = match eo with
+| None -> k
+| Some e -> Lambda.bind Strict v e k
+
+let for_multiple_match loc paraml pat_act_list partial =
+ let v_paraml = List.map param_to_var paraml in
+ let paraml = List.map (fun (v,_) -> Lvar v) v_paraml in
+ List.fold_right bind_opt v_paraml
+ (do_for_multiple_match loc paraml pat_act_list partial)
diff --git a/bytecomp/matching.mli b/bytecomp/matching.mli
new file mode 100644
index 0000000000..88002e0567
--- /dev/null
+++ b/bytecomp/matching.mli
@@ -0,0 +1,43 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compilation of pattern-matching *)
+
+open Typedtree
+open Lambda
+
+
+(* Entry points to match compiler *)
+val for_function:
+ Location.t -> int ref option -> lambda -> (pattern * lambda) list ->
+ partial -> lambda
+val for_trywith:
+ lambda -> (pattern * lambda) list -> lambda
+val for_let:
+ Location.t -> lambda -> pattern -> lambda -> lambda
+val for_multiple_match:
+ Location.t -> lambda list -> (pattern * lambda) list -> partial ->
+ lambda
+
+val for_tupled_function:
+ Location.t -> Ident.t list -> (pattern list * lambda) list ->
+ partial -> lambda
+
+exception Cannot_flatten
+
+val flatten_pattern: int -> pattern -> pattern list
+
+(* Expand stringswitch to string test tree *)
+val expand_stringswitch:
+ lambda -> (string * lambda) list -> lambda option -> lambda
+
+val inline_lazy_force : lambda -> Location.t -> lambda
diff --git a/bytecomp/meta.ml b/bytecomp/meta.ml
new file mode 100644
index 0000000000..b3cecdbe0f
--- /dev/null
+++ b/bytecomp/meta.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+external global_data : unit -> Obj.t array = "caml_get_global_data"
+external realloc_global_data : int -> unit = "caml_realloc_global"
+external static_alloc : int -> bytes = "caml_static_alloc"
+external static_free : bytes -> unit = "caml_static_free"
+external static_resize : bytes -> int -> bytes = "caml_static_resize"
+external static_release_bytecode : bytes -> int -> unit
+ = "caml_static_release_bytecode"
+type closure = unit -> Obj.t
+external reify_bytecode : bytes -> int -> closure = "caml_reify_bytecode"
+external invoke_traced_function : Obj.t -> Obj.t -> Obj.t -> Obj.t
+ = "caml_invoke_traced_function"
+external get_section_table : unit -> (string * Obj.t) list
+ = "caml_get_section_table"
+external add_debug_info :
+ bytes -> int -> Instruct.debug_event list array -> unit
+ = "caml_add_debug_info"
+external remove_debug_info : bytes -> unit
+ = "caml_remove_debug_info"
diff --git a/bytecomp/meta.mli b/bytecomp/meta.mli
new file mode 100644
index 0000000000..3d9d84954d
--- /dev/null
+++ b/bytecomp/meta.mli
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* To control the runtime system and bytecode interpreter *)
+
+external global_data : unit -> Obj.t array = "caml_get_global_data"
+external realloc_global_data : int -> unit = "caml_realloc_global"
+external static_alloc : int -> bytes = "caml_static_alloc"
+external static_free : bytes -> unit = "caml_static_free"
+external static_release_bytecode : bytes -> int -> unit
+ = "caml_static_release_bytecode"
+external static_resize : bytes -> int -> bytes = "caml_static_resize"
+type closure = unit -> Obj.t
+external reify_bytecode : bytes -> int -> closure = "caml_reify_bytecode"
+external invoke_traced_function : Obj.t -> Obj.t -> Obj.t -> Obj.t
+ = "caml_invoke_traced_function"
+external get_section_table : unit -> (string * Obj.t) list
+ = "caml_get_section_table"
+external add_debug_info :
+ bytes -> int -> Instruct.debug_event list array -> unit
+ = "caml_add_debug_info"
+external remove_debug_info : bytes -> unit
+ = "caml_remove_debug_info"
diff --git a/bytecomp/printinstr.ml b/bytecomp/printinstr.ml
new file mode 100644
index 0000000000..43d8d36069
--- /dev/null
+++ b/bytecomp/printinstr.ml
@@ -0,0 +1,113 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pretty-print lists of instructions *)
+
+open Format
+open Lambda
+open Instruct
+
+let instruction ppf = function
+ | Klabel lbl -> fprintf ppf "L%i:" lbl
+ | Kacc n -> fprintf ppf "\tacc %i" n
+ | Kenvacc n -> fprintf ppf "\tenvacc %i" n
+ | Kpush -> fprintf ppf "\tpush"
+ | Kpop n -> fprintf ppf "\tpop %i" n
+ | Kassign n -> fprintf ppf "\tassign %i" n
+ | Kpush_retaddr lbl -> fprintf ppf "\tpush_retaddr L%i" lbl
+ | Kapply n -> fprintf ppf "\tapply %i" n
+ | Kappterm(n, m) ->
+ fprintf ppf "\tappterm %i, %i" n m
+ | Kreturn n -> fprintf ppf "\treturn %i" n
+ | Krestart -> fprintf ppf "\trestart"
+ | Kgrab n -> fprintf ppf "\tgrab %i" n
+ | Kclosure(lbl, n) ->
+ fprintf ppf "\tclosure L%i, %i" lbl n
+ | Kclosurerec(lbls, n) ->
+ fprintf ppf "\tclosurerec";
+ List.iter (fun lbl -> fprintf ppf " %i" lbl) lbls;
+ fprintf ppf ", %i" n
+ | Koffsetclosure n -> fprintf ppf "\toffsetclosure %i" n
+ | Kgetglobal id -> fprintf ppf "\tgetglobal %a" Ident.print id
+ | Ksetglobal id -> fprintf ppf "\tsetglobal %a" Ident.print id
+ | Kconst cst ->
+ fprintf ppf "@[<10>\tconst@ %a@]" Printlambda.structured_constant cst
+ | Kmakeblock(n, m) ->
+ fprintf ppf "\tmakeblock %i, %i" n m
+ | Kmakefloatblock(n) ->
+ fprintf ppf "\tmakefloatblock %i" n
+ | Kgetfield n -> fprintf ppf "\tgetfield %i" n
+ | Ksetfield n -> fprintf ppf "\tsetfield %i" n
+ | Kgetfloatfield n -> fprintf ppf "\tgetfloatfield %i" n
+ | Ksetfloatfield n -> fprintf ppf "\tsetfloatfield %i" n
+ | Kvectlength -> fprintf ppf "\tvectlength"
+ | Kgetvectitem -> fprintf ppf "\tgetvectitem"
+ | Ksetvectitem -> fprintf ppf "\tsetvectitem"
+ | Kgetstringchar -> fprintf ppf "\tgetstringchar"
+ | Ksetstringchar -> fprintf ppf "\tsetstringchar"
+ | Kbranch lbl -> fprintf ppf "\tbranch L%i" lbl
+ | Kbranchif lbl -> fprintf ppf "\tbranchif L%i" lbl
+ | Kbranchifnot lbl -> fprintf ppf "\tbranchifnot L%i" lbl
+ | Kstrictbranchif lbl -> fprintf ppf "\tstrictbranchif L%i" lbl
+ | Kstrictbranchifnot lbl ->
+ fprintf ppf "\tstrictbranchifnot L%i" lbl
+ | Kswitch(consts, blocks) ->
+ let labels ppf labs =
+ Array.iter (fun lbl -> fprintf ppf "@ %i" lbl) labs in
+ fprintf ppf "@[<10>\tswitch%a/%a@]" labels consts labels blocks
+ | Kboolnot -> fprintf ppf "\tboolnot"
+ | Kpushtrap lbl -> fprintf ppf "\tpushtrap L%i" lbl
+ | Kpoptrap -> fprintf ppf "\tpoptrap"
+ | Kraise k-> fprintf ppf "\t%s" (Lambda.raise_kind k)
+ | Kcheck_signals -> fprintf ppf "\tcheck_signals"
+ | Kccall(s, n) ->
+ fprintf ppf "\tccall %s, %i" s n
+ | Knegint -> fprintf ppf "\tnegint"
+ | Kaddint -> fprintf ppf "\taddint"
+ | Ksubint -> fprintf ppf "\tsubint"
+ | Kmulint -> fprintf ppf "\tmulint"
+ | Kdivint -> fprintf ppf "\tdivint"
+ | Kmodint -> fprintf ppf "\tmodint"
+ | Kandint -> fprintf ppf "\tandint"
+ | Korint -> fprintf ppf "\torint"
+ | Kxorint -> fprintf ppf "\txorint"
+ | Klslint -> fprintf ppf "\tlslint"
+ | Klsrint -> fprintf ppf "\tlsrint"
+ | Kasrint -> fprintf ppf "\tasrint"
+ | Kintcomp Ceq -> fprintf ppf "\teqint"
+ | Kintcomp Cneq -> fprintf ppf "\tneqint"
+ | Kintcomp Clt -> fprintf ppf "\tltint"
+ | Kintcomp Cgt -> fprintf ppf "\tgtint"
+ | Kintcomp Cle -> fprintf ppf "\tleint"
+ | Kintcomp Cge -> fprintf ppf "\tgeint"
+ | Koffsetint n -> fprintf ppf "\toffsetint %i" n
+ | Koffsetref n -> fprintf ppf "\toffsetref %i" n
+ | Kisint -> fprintf ppf "\tisint"
+ | Kisout -> fprintf ppf "\tisout"
+ | Kgetmethod -> fprintf ppf "\tgetmethod"
+ | Kgetpubmet n -> fprintf ppf "\tgetpubmet %i" n
+ | Kgetdynmet -> fprintf ppf "\tgetdynmet"
+ | Kstop -> fprintf ppf "\tstop"
+ | Kevent ev -> fprintf ppf "\tevent \"%s\" %i-%i"
+ ev.ev_loc.Location.loc_start.Lexing.pos_fname
+ ev.ev_loc.Location.loc_start.Lexing.pos_cnum
+ ev.ev_loc.Location.loc_end.Lexing.pos_cnum
+
+let rec instruction_list ppf = function
+ [] -> ()
+ | Klabel lbl :: il ->
+ fprintf ppf "L%i:%a" lbl instruction_list il
+ | instr :: il ->
+ fprintf ppf "%a@ %a" instruction instr instruction_list il
+
+let instrlist ppf il =
+ fprintf ppf "@[<v 0>%a@]" instruction_list il
diff --git a/bytecomp/printinstr.mli b/bytecomp/printinstr.mli
new file mode 100644
index 0000000000..dd4fd15b32
--- /dev/null
+++ b/bytecomp/printinstr.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Pretty-print lists of instructions *)
+
+open Instruct
+
+open Format
+
+val instruction: formatter -> instruction -> unit
+val instrlist: formatter -> instruction list -> unit
diff --git a/bytecomp/printlambda.ml b/bytecomp/printlambda.ml
new file mode 100644
index 0000000000..591822f3b8
--- /dev/null
+++ b/bytecomp/printlambda.ml
@@ -0,0 +1,406 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+open Asttypes
+open Primitive
+open Types
+open Lambda
+
+
+let rec struct_const ppf = function
+ | Const_base(Const_int n) -> fprintf ppf "%i" n
+ | Const_base(Const_char c) -> fprintf ppf "%C" c
+ | Const_base(Const_string (s, _)) -> fprintf ppf "%S" s
+ | Const_immstring s -> fprintf ppf "#%S" s
+ | Const_base(Const_float f) -> fprintf ppf "%s" f
+ | Const_base(Const_int32 n) -> fprintf ppf "%lil" n
+ | Const_base(Const_int64 n) -> fprintf ppf "%LiL" n
+ | Const_base(Const_nativeint n) -> fprintf ppf "%nin" n
+ | Const_pointer n -> fprintf ppf "%ia" n
+ | Const_block(tag, []) ->
+ fprintf ppf "[%i]" tag
+ | Const_block(tag, sc1::scl) ->
+ let sconsts ppf scl =
+ List.iter (fun sc -> fprintf ppf "@ %a" struct_const sc) scl in
+ fprintf ppf "@[<1>[%i:@ @[%a%a@]]@]" tag struct_const sc1 sconsts scl
+ | Const_float_array [] ->
+ fprintf ppf "[| |]"
+ | Const_float_array (f1 :: fl) ->
+ let floats ppf fl =
+ List.iter (fun f -> fprintf ppf "@ %s" f) fl in
+ fprintf ppf "@[<1>[|@[%s%a@]|]@]" f1 floats fl
+
+let array_kind = function
+ | Pgenarray -> "gen"
+ | Paddrarray -> "addr"
+ | Pintarray -> "int"
+ | Pfloatarray -> "float"
+
+let boxed_integer_name = function
+ | Pnativeint -> "nativeint"
+ | Pint32 -> "int32"
+ | Pint64 -> "int64"
+
+let print_boxed_integer name ppf bi =
+ fprintf ppf "%s_%s" (boxed_integer_name bi) name
+
+let print_boxed_integer_conversion ppf bi1 bi2 =
+ fprintf ppf "%s_of_%s" (boxed_integer_name bi2) (boxed_integer_name bi1)
+
+let boxed_integer_mark name = function
+ | Pnativeint -> Printf.sprintf "Nativeint.%s" name
+ | Pint32 -> Printf.sprintf "Int32.%s" name
+ | Pint64 -> Printf.sprintf "Int64.%s" name
+
+let print_boxed_integer name ppf bi =
+ fprintf ppf "%s" (boxed_integer_mark name bi);;
+
+let print_bigarray name unsafe kind ppf layout =
+ fprintf ppf "Bigarray.%s[%s,%s]"
+ (if unsafe then "unsafe_"^ name else name)
+ (match kind with
+ | Pbigarray_unknown -> "generic"
+ | Pbigarray_float32 -> "float32"
+ | Pbigarray_float64 -> "float64"
+ | Pbigarray_sint8 -> "sint8"
+ | Pbigarray_uint8 -> "uint8"
+ | Pbigarray_sint16 -> "sint16"
+ | Pbigarray_uint16 -> "uint16"
+ | Pbigarray_int32 -> "int32"
+ | Pbigarray_int64 -> "int64"
+ | Pbigarray_caml_int -> "camlint"
+ | Pbigarray_native_int -> "nativeint"
+ | Pbigarray_complex32 -> "complex32"
+ | Pbigarray_complex64 -> "complex64")
+ (match layout with
+ | Pbigarray_unknown_layout -> "unknown"
+ | Pbigarray_c_layout -> "C"
+ | Pbigarray_fortran_layout -> "Fortran")
+
+let record_rep ppf r =
+ match r with
+ | Record_regular -> fprintf ppf "regular"
+ | Record_inlined i -> fprintf ppf "inlined(%i)" i
+ | Record_float -> fprintf ppf "float"
+ | Record_extension -> fprintf ppf "ext"
+;;
+
+let string_of_loc_kind = function
+ | Loc_FILE -> "loc_FILE"
+ | Loc_LINE -> "loc_LINE"
+ | Loc_MODULE -> "loc_MODULE"
+ | Loc_POS -> "loc_POS"
+ | Loc_LOC -> "loc_LOC"
+
+let primitive ppf = function
+ | Pidentity -> fprintf ppf "id"
+ | Pignore -> fprintf ppf "ignore"
+ | Prevapply _ -> fprintf ppf "revapply"
+ | Pdirapply _ -> fprintf ppf "dirapply"
+ | Ploc kind -> fprintf ppf "%s" (string_of_loc_kind kind)
+ | Pgetglobal id -> fprintf ppf "global %a" Ident.print id
+ | Psetglobal id -> fprintf ppf "setglobal %a" Ident.print id
+ | Pmakeblock(tag, Immutable) -> fprintf ppf "makeblock %i" tag
+ | Pmakeblock(tag, Mutable) -> fprintf ppf "makemutable %i" tag
+ | Pfield n -> fprintf ppf "field %i" n
+ | Psetfield(n, ptr) ->
+ let instr = if ptr then "setfield_ptr " else "setfield_imm " in
+ fprintf ppf "%s%i" instr n
+ | Pfloatfield n -> fprintf ppf "floatfield %i" n
+ | Psetfloatfield n -> fprintf ppf "setfloatfield %i" n
+ | Pduprecord (rep, size) -> fprintf ppf "duprecord %a %i" record_rep rep size
+ | Plazyforce -> fprintf ppf "force"
+ | Pccall p -> fprintf ppf "%s" p.prim_name
+ | Praise k -> fprintf ppf "%s" (Lambda.raise_kind k)
+ | Psequand -> fprintf ppf "&&"
+ | Psequor -> fprintf ppf "||"
+ | Pnot -> fprintf ppf "not"
+ | Pnegint -> fprintf ppf "~"
+ | Paddint -> fprintf ppf "+"
+ | Psubint -> fprintf ppf "-"
+ | Pmulint -> fprintf ppf "*"
+ | Pdivint -> fprintf ppf "/"
+ | Pmodint -> fprintf ppf "mod"
+ | Pandint -> fprintf ppf "and"
+ | Porint -> fprintf ppf "or"
+ | Pxorint -> fprintf ppf "xor"
+ | Plslint -> fprintf ppf "lsl"
+ | Plsrint -> fprintf ppf "lsr"
+ | Pasrint -> fprintf ppf "asr"
+ | Pintcomp(Ceq) -> fprintf ppf "=="
+ | Pintcomp(Cneq) -> fprintf ppf "!="
+ | Pintcomp(Clt) -> fprintf ppf "<"
+ | Pintcomp(Cle) -> fprintf ppf "<="
+ | Pintcomp(Cgt) -> fprintf ppf ">"
+ | Pintcomp(Cge) -> fprintf ppf ">="
+ | Poffsetint n -> fprintf ppf "%i+" n
+ | Poffsetref n -> fprintf ppf "+:=%i"n
+ | Pintoffloat -> fprintf ppf "int_of_float"
+ | Pfloatofint -> fprintf ppf "float_of_int"
+ | Pnegfloat -> fprintf ppf "~."
+ | Pabsfloat -> fprintf ppf "abs."
+ | Paddfloat -> fprintf ppf "+."
+ | Psubfloat -> fprintf ppf "-."
+ | Pmulfloat -> fprintf ppf "*."
+ | Pdivfloat -> fprintf ppf "/."
+ | Pfloatcomp(Ceq) -> fprintf ppf "==."
+ | Pfloatcomp(Cneq) -> fprintf ppf "!=."
+ | Pfloatcomp(Clt) -> fprintf ppf "<."
+ | Pfloatcomp(Cle) -> fprintf ppf "<=."
+ | Pfloatcomp(Cgt) -> fprintf ppf ">."
+ | Pfloatcomp(Cge) -> fprintf ppf ">=."
+ | Pstringlength -> fprintf ppf "string.length"
+ | Pstringrefu -> fprintf ppf "string.unsafe_get"
+ | Pstringsetu -> fprintf ppf "string.unsafe_set"
+ | Pstringrefs -> fprintf ppf "string.get"
+ | Pstringsets -> fprintf ppf "string.set"
+ | Parraylength k -> fprintf ppf "array.length[%s]" (array_kind k)
+ | Pmakearray k -> fprintf ppf "makearray[%s]" (array_kind k)
+ | Parrayrefu k -> fprintf ppf "array.unsafe_get[%s]" (array_kind k)
+ | Parraysetu k -> fprintf ppf "array.unsafe_set[%s]" (array_kind k)
+ | Parrayrefs k -> fprintf ppf "array.get[%s]" (array_kind k)
+ | Parraysets k -> fprintf ppf "array.set[%s]" (array_kind k)
+ | Pctconst c ->
+ let const_name = match c with
+ | Big_endian -> "big_endian"
+ | Word_size -> "word_size"
+ | Int_size -> "int_size"
+ | Max_wosize -> "max_wosize"
+ | Ostype_unix -> "ostype_unix"
+ | Ostype_win32 -> "ostype_win32"
+ | Ostype_cygwin -> "ostype_cygwin" in
+ fprintf ppf "sys.constant_%s" const_name
+ | Pisint -> fprintf ppf "isint"
+ | Pisout -> fprintf ppf "isout"
+ | Pbittest -> fprintf ppf "testbit"
+ | Pbintofint bi -> print_boxed_integer "of_int" ppf bi
+ | Pintofbint bi -> print_boxed_integer "to_int" ppf bi
+ | Pcvtbint (bi1, bi2) -> print_boxed_integer_conversion ppf bi1 bi2
+ | Pnegbint bi -> print_boxed_integer "neg" ppf bi
+ | Paddbint bi -> print_boxed_integer "add" ppf bi
+ | Psubbint bi -> print_boxed_integer "sub" ppf bi
+ | Pmulbint bi -> print_boxed_integer "mul" ppf bi
+ | Pdivbint bi -> print_boxed_integer "div" ppf bi
+ | Pmodbint bi -> print_boxed_integer "mod" ppf bi
+ | Pandbint bi -> print_boxed_integer "and" ppf bi
+ | Porbint bi -> print_boxed_integer "or" ppf bi
+ | Pxorbint bi -> print_boxed_integer "xor" ppf bi
+ | Plslbint bi -> print_boxed_integer "lsl" ppf bi
+ | Plsrbint bi -> print_boxed_integer "lsr" ppf bi
+ | Pasrbint bi -> print_boxed_integer "asr" ppf bi
+ | Pbintcomp(bi, Ceq) -> print_boxed_integer "==" ppf bi
+ | Pbintcomp(bi, Cneq) -> print_boxed_integer "!=" ppf bi
+ | Pbintcomp(bi, Clt) -> print_boxed_integer "<" ppf bi
+ | Pbintcomp(bi, Cgt) -> print_boxed_integer ">" ppf bi
+ | Pbintcomp(bi, Cle) -> print_boxed_integer "<=" ppf bi
+ | Pbintcomp(bi, Cge) -> print_boxed_integer ">=" ppf bi
+ | Pbigarrayref(unsafe, n, kind, layout) ->
+ print_bigarray "get" unsafe kind ppf layout
+ | Pbigarrayset(unsafe, n, kind, layout) ->
+ print_bigarray "set" unsafe kind ppf layout
+ | Pbigarraydim(n) -> fprintf ppf "Bigarray.dim_%i" n
+ | Pstring_load_16(unsafe) ->
+ if unsafe then fprintf ppf "string.unsafe_get16"
+ else fprintf ppf "string.get16"
+ | Pstring_load_32(unsafe) ->
+ if unsafe then fprintf ppf "string.unsafe_get32"
+ else fprintf ppf "string.get32"
+ | Pstring_load_64(unsafe) ->
+ if unsafe then fprintf ppf "string.unsafe_get64"
+ else fprintf ppf "string.get64"
+ | Pstring_set_16(unsafe) ->
+ if unsafe then fprintf ppf "string.unsafe_set16"
+ else fprintf ppf "string.set16"
+ | Pstring_set_32(unsafe) ->
+ if unsafe then fprintf ppf "string.unsafe_set32"
+ else fprintf ppf "string.set32"
+ | Pstring_set_64(unsafe) ->
+ if unsafe then fprintf ppf "string.unsafe_set64"
+ else fprintf ppf "string.set64"
+ | Pbigstring_load_16(unsafe) ->
+ if unsafe then fprintf ppf "bigarray.array1.unsafe_get16"
+ else fprintf ppf "bigarray.array1.get16"
+ | Pbigstring_load_32(unsafe) ->
+ if unsafe then fprintf ppf "bigarray.array1.unsafe_get32"
+ else fprintf ppf "bigarray.array1.get32"
+ | Pbigstring_load_64(unsafe) ->
+ if unsafe then fprintf ppf "bigarray.array1.unsafe_get64"
+ else fprintf ppf "bigarray.array1.get64"
+ | Pbigstring_set_16(unsafe) ->
+ if unsafe then fprintf ppf "bigarray.array1.unsafe_set16"
+ else fprintf ppf "bigarray.array1.set16"
+ | Pbigstring_set_32(unsafe) ->
+ if unsafe then fprintf ppf "bigarray.array1.unsafe_set32"
+ else fprintf ppf "bigarray.array1.set32"
+ | Pbigstring_set_64(unsafe) ->
+ if unsafe then fprintf ppf "bigarray.array1.unsafe_set64"
+ else fprintf ppf "bigarray.array1.set64"
+ | Pbswap16 -> fprintf ppf "bswap16"
+ | Pbbswap(bi) -> print_boxed_integer "bswap" ppf bi
+ | Pint_as_pointer -> fprintf ppf "int_as_pointer"
+
+let rec lam ppf = function
+ | Lvar id ->
+ Ident.print ppf id
+ | Lconst cst ->
+ struct_const ppf cst
+ | Lapply(lfun, largs, info) when info.apply_should_be_tailcall ->
+ let lams ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ fprintf ppf "@[<2>(apply@ %a%a @@tailcall)@]" lam lfun lams largs
+ | Lapply(lfun, largs, _) ->
+ let lams ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ fprintf ppf "@[<2>(apply@ %a%a)@]" lam lfun lams largs
+ | Lfunction{kind; params; body} ->
+ let pr_params ppf params =
+ match kind with
+ | Curried ->
+ List.iter (fun param -> fprintf ppf "@ %a" Ident.print param) params
+ | Tupled ->
+ fprintf ppf " (";
+ let first = ref true in
+ List.iter
+ (fun param ->
+ if !first then first := false else fprintf ppf ",@ ";
+ Ident.print ppf param)
+ params;
+ fprintf ppf ")" in
+ fprintf ppf "@[<2>(function%a@ %a)@]" pr_params params lam body
+ | Llet(str, id, arg, body) ->
+ let kind = function
+ Alias -> "a" | Strict -> "" | StrictOpt -> "o" | Variable -> "v" in
+ let rec letbody = function
+ | Llet(str, id, arg, body) ->
+ fprintf ppf "@ @[<2>%a =%s@ %a@]" Ident.print id (kind str) lam arg;
+ letbody body
+ | expr -> expr in
+ fprintf ppf "@[<2>(let@ @[<hv 1>(@[<2>%a =%s@ %a@]"
+ Ident.print id (kind str) lam arg;
+ let expr = letbody body in
+ fprintf ppf ")@]@ %a)@]" lam expr
+ | Lletrec(id_arg_list, body) ->
+ let bindings ppf id_arg_list =
+ let spc = ref false in
+ List.iter
+ (fun (id, l) ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<2>%a@ %a@]" Ident.print id lam l)
+ id_arg_list in
+ fprintf ppf
+ "@[<2>(letrec@ (@[<hv 1>%a@])@ %a)@]" bindings id_arg_list lam body
+ | Lprim(prim, largs) ->
+ let lams ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ fprintf ppf "@[<2>(%a%a)@]" primitive prim lams largs
+ | Lswitch(larg, sw) ->
+ let switch ppf sw =
+ let spc = ref false in
+ List.iter
+ (fun (n, l) ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<hv 1>case int %i:@ %a@]" n lam l)
+ sw.sw_consts;
+ List.iter
+ (fun (n, l) ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<hv 1>case tag %i:@ %a@]" n lam l)
+ sw.sw_blocks ;
+ begin match sw.sw_failaction with
+ | None -> ()
+ | Some l ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<hv 1>default:@ %a@]" lam l
+ end in
+ fprintf ppf
+ "@[<1>(%s %a@ @[<v 0>%a@])@]"
+ (match sw.sw_failaction with None -> "switch*" | _ -> "switch")
+ lam larg switch sw
+ | Lstringswitch(arg, cases, default) ->
+ let switch ppf cases =
+ let spc = ref false in
+ List.iter
+ (fun (s, l) ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<hv 1>case \"%s\":@ %a@]" (String.escaped s) lam l)
+ cases;
+ begin match default with
+ | Some default ->
+ if !spc then fprintf ppf "@ " else spc := true;
+ fprintf ppf "@[<hv 1>default:@ %a@]" lam default
+ | None -> ()
+ end in
+ fprintf ppf
+ "@[<1>(stringswitch %a@ @[<v 0>%a@])@]" lam arg switch cases
+ | Lstaticraise (i, ls) ->
+ let lams ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ fprintf ppf "@[<2>(exit@ %d%a)@]" i lams ls;
+ | Lstaticcatch(lbody, (i, vars), lhandler) ->
+ fprintf ppf "@[<2>(catch@ %a@;<1 -1>with (%d%a)@ %a)@]"
+ lam lbody i
+ (fun ppf vars -> match vars with
+ | [] -> ()
+ | _ ->
+ List.iter
+ (fun x -> fprintf ppf " %a" Ident.print x)
+ vars)
+ vars
+ lam lhandler
+ | Ltrywith(lbody, param, lhandler) ->
+ fprintf ppf "@[<2>(try@ %a@;<1 -1>with %a@ %a)@]"
+ lam lbody Ident.print param lam lhandler
+ | Lifthenelse(lcond, lif, lelse) ->
+ fprintf ppf "@[<2>(if@ %a@ %a@ %a)@]" lam lcond lam lif lam lelse
+ | Lsequence(l1, l2) ->
+ fprintf ppf "@[<2>(seq@ %a@ %a)@]" lam l1 sequence l2
+ | Lwhile(lcond, lbody) ->
+ fprintf ppf "@[<2>(while@ %a@ %a)@]" lam lcond lam lbody
+ | Lfor(param, lo, hi, dir, body) ->
+ fprintf ppf "@[<2>(for %a@ %a@ %s@ %a@ %a)@]"
+ Ident.print param lam lo
+ (match dir with Upto -> "to" | Downto -> "downto")
+ lam hi lam body
+ | Lassign(id, expr) ->
+ fprintf ppf "@[<2>(assign@ %a@ %a)@]" Ident.print id lam expr
+ | Lsend (k, met, obj, largs, _) ->
+ let args ppf largs =
+ List.iter (fun l -> fprintf ppf "@ %a" lam l) largs in
+ let kind =
+ if k = Self then "self" else if k = Cached then "cache" else "" in
+ fprintf ppf "@[<2>(send%s@ %a@ %a%a)@]" kind lam obj lam met args largs
+ | Levent(expr, ev) ->
+ let kind =
+ match ev.lev_kind with
+ | Lev_before -> "before"
+ | Lev_after _ -> "after"
+ | Lev_function -> "funct-body" in
+ fprintf ppf "@[<2>(%s %s(%i)%s:%i-%i@ %a)@]" kind
+ ev.lev_loc.Location.loc_start.Lexing.pos_fname
+ ev.lev_loc.Location.loc_start.Lexing.pos_lnum
+ (if ev.lev_loc.Location.loc_ghost then "<ghost>" else "")
+ ev.lev_loc.Location.loc_start.Lexing.pos_cnum
+ ev.lev_loc.Location.loc_end.Lexing.pos_cnum
+ lam expr
+ | Lifused(id, expr) ->
+ fprintf ppf "@[<2>(ifused@ %a@ %a)@]" Ident.print id lam expr
+
+and sequence ppf = function
+ | Lsequence(l1, l2) ->
+ fprintf ppf "%a@ %a" sequence l1 sequence l2
+ | l ->
+ lam ppf l
+
+let structured_constant = struct_const
+
+let lambda = lam
diff --git a/bytecomp/printlambda.mli b/bytecomp/printlambda.mli
new file mode 100644
index 0000000000..4a546b63e8
--- /dev/null
+++ b/bytecomp/printlambda.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Lambda
+
+open Format
+
+val structured_constant: formatter -> structured_constant -> unit
+val lambda: formatter -> lambda -> unit
+val primitive: formatter -> primitive -> unit
diff --git a/bytecomp/runtimedef.mli b/bytecomp/runtimedef.mli
new file mode 100644
index 0000000000..c06038a463
--- /dev/null
+++ b/bytecomp/runtimedef.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Values and functions known and/or provided by the runtime system *)
+
+val builtin_exceptions: string array
+val builtin_primitives: string array
diff --git a/bytecomp/simplif.ml b/bytecomp/simplif.ml
new file mode 100644
index 0000000000..277ecf25aa
--- /dev/null
+++ b/bytecomp/simplif.ml
@@ -0,0 +1,611 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Elimination of useless Llet(Alias) bindings.
+ Also transform let-bound references into variables. *)
+
+open Asttypes
+open Lambda
+
+(* To transform let-bound references into variables *)
+
+exception Real_reference
+
+let rec eliminate_ref id = function
+ Lvar v as lam ->
+ if Ident.same v id then raise Real_reference else lam
+ | Lconst cst as lam -> lam
+ | Lapply(e1, el, info) ->
+ Lapply(eliminate_ref id e1, List.map (eliminate_ref id) el, info)
+ | Lfunction{kind; params; body} as lam ->
+ if IdentSet.mem id (free_variables lam)
+ then raise Real_reference
+ else lam
+ | Llet(str, v, e1, e2) ->
+ Llet(str, v, eliminate_ref id e1, eliminate_ref id e2)
+ | Lletrec(idel, e2) ->
+ Lletrec(List.map (fun (v, e) -> (v, eliminate_ref id e)) idel,
+ eliminate_ref id e2)
+ | Lprim(Pfield 0, [Lvar v]) when Ident.same v id ->
+ Lvar id
+ | Lprim(Psetfield(0, _), [Lvar v; e]) when Ident.same v id ->
+ Lassign(id, eliminate_ref id e)
+ | Lprim(Poffsetref delta, [Lvar v]) when Ident.same v id ->
+ Lassign(id, Lprim(Poffsetint delta, [Lvar id]))
+ | Lprim(p, el) ->
+ Lprim(p, List.map (eliminate_ref id) el)
+ | Lswitch(e, sw) ->
+ Lswitch(eliminate_ref id e,
+ {sw_numconsts = sw.sw_numconsts;
+ sw_consts =
+ List.map (fun (n, e) -> (n, eliminate_ref id e)) sw.sw_consts;
+ sw_numblocks = sw.sw_numblocks;
+ sw_blocks =
+ List.map (fun (n, e) -> (n, eliminate_ref id e)) sw.sw_blocks;
+ sw_failaction =
+ Misc.may_map (eliminate_ref id) sw.sw_failaction; })
+ | Lstringswitch(e, sw, default) ->
+ Lstringswitch
+ (eliminate_ref id e,
+ List.map (fun (s, e) -> (s, eliminate_ref id e)) sw,
+ Misc.may_map (eliminate_ref id) default)
+ | Lstaticraise (i,args) ->
+ Lstaticraise (i,List.map (eliminate_ref id) args)
+ | Lstaticcatch(e1, i, e2) ->
+ Lstaticcatch(eliminate_ref id e1, i, eliminate_ref id e2)
+ | Ltrywith(e1, v, e2) ->
+ Ltrywith(eliminate_ref id e1, v, eliminate_ref id e2)
+ | Lifthenelse(e1, e2, e3) ->
+ Lifthenelse(eliminate_ref id e1,
+ eliminate_ref id e2,
+ eliminate_ref id e3)
+ | Lsequence(e1, e2) ->
+ Lsequence(eliminate_ref id e1, eliminate_ref id e2)
+ | Lwhile(e1, e2) ->
+ Lwhile(eliminate_ref id e1, eliminate_ref id e2)
+ | Lfor(v, e1, e2, dir, e3) ->
+ Lfor(v, eliminate_ref id e1, eliminate_ref id e2,
+ dir, eliminate_ref id e3)
+ | Lassign(v, e) ->
+ Lassign(v, eliminate_ref id e)
+ | Lsend(k, m, o, el, loc) ->
+ Lsend(k, eliminate_ref id m, eliminate_ref id o,
+ List.map (eliminate_ref id) el, loc)
+ | Levent(l, ev) ->
+ Levent(eliminate_ref id l, ev)
+ | Lifused(v, e) ->
+ Lifused(v, eliminate_ref id e)
+
+(* Simplification of exits *)
+
+let simplify_exits lam =
+
+ (* Count occurrences of (exit n ...) statements *)
+ let exits = Hashtbl.create 17 in
+
+ let count_exit i =
+ try
+ !(Hashtbl.find exits i)
+ with
+ | Not_found -> 0
+
+ and incr_exit i =
+ try
+ incr (Hashtbl.find exits i)
+ with
+ | Not_found -> Hashtbl.add exits i (ref 1) in
+
+ let rec count = function
+ | (Lvar _| Lconst _) -> ()
+ | Lapply(l1, ll, _) -> count l1; List.iter count ll
+ | Lfunction{kind; params; body = l} -> count l
+ | Llet(str, v, l1, l2) ->
+ count l2; count l1
+ | Lletrec(bindings, body) ->
+ List.iter (fun (v, l) -> count l) bindings;
+ count body
+ | Lprim(p, ll) -> List.iter count ll
+ | Lswitch(l, sw) ->
+ count_default sw ;
+ count l;
+ List.iter (fun (_, l) -> count l) sw.sw_consts;
+ List.iter (fun (_, l) -> count l) sw.sw_blocks
+ | Lstringswitch(l, sw, d) ->
+ count l;
+ List.iter (fun (_, l) -> count l) sw;
+ begin match d with
+ | None -> ()
+ | Some d -> match sw with
+ | []|[_] -> count d
+ | _ -> count d; count d (* default will get replicated *)
+ end
+ | Lstaticraise (i,ls) -> incr_exit i ; List.iter count ls
+ | Lstaticcatch (l1,(i,[]),Lstaticraise (j,[])) ->
+ (* i will be replaced by j in l1, so each occurence of i in l1
+ increases j's ref count *)
+ count l1 ;
+ let ic = count_exit i in
+ begin try
+ let r = Hashtbl.find exits j in r := !r + ic
+ with
+ | Not_found ->
+ Hashtbl.add exits j (ref ic)
+ end
+ | Lstaticcatch(l1, (i,_), l2) ->
+ count l1;
+ (* If l1 does not contain (exit i),
+ l2 will be removed, so don't count its exits *)
+ if count_exit i > 0 then
+ count l2
+ | Ltrywith(l1, v, l2) -> count l1; count l2
+ | Lifthenelse(l1, l2, l3) -> count l1; count l2; count l3
+ | Lsequence(l1, l2) -> count l1; count l2
+ | Lwhile(l1, l2) -> count l1; count l2
+ | Lfor(_, l1, l2, dir, l3) -> count l1; count l2; count l3
+ | Lassign(v, l) -> count l
+ | Lsend(k, m, o, ll, _) -> List.iter count (m::o::ll)
+ | Levent(l, _) -> count l
+ | Lifused(v, l) -> count l
+
+ and count_default sw = match sw.sw_failaction with
+ | None -> ()
+ | Some al ->
+ let nconsts = List.length sw.sw_consts
+ and nblocks = List.length sw.sw_blocks in
+ if
+ nconsts < sw.sw_numconsts && nblocks < sw.sw_numblocks
+ then begin (* default action will occur twice in native code *)
+ count al ; count al
+ end else begin (* default action will occur once *)
+ assert (nconsts < sw.sw_numconsts || nblocks < sw.sw_numblocks) ;
+ count al
+ end
+ in
+ count lam;
+
+ (*
+ Second pass simplify ``catch body with (i ...) handler''
+ - if (exit i ...) does not occur in body, suppress catch
+ - if (exit i ...) occurs exactly once in body,
+ substitute it with handler
+ - If handler is a single variable, replace (exit i ..) with it
+ Note:
+ In ``catch body with (i x1 .. xn) handler''
+ Substituted expression is
+ let y1 = x1 and ... yn = xn in
+ handler[x1 <- y1 ; ... ; xn <- yn]
+ For the sake of preserving the uniqueness of bound variables.
+ (No alpha conversion of ``handler'' is presently needed, since
+ substitution of several ``(exit i ...)''
+ occurs only when ``handler'' is a variable.)
+ *)
+
+ let subst = Hashtbl.create 17 in
+
+ let rec simplif = function
+ | (Lvar _|Lconst _) as l -> l
+ | Lapply(l1, ll, info) -> Lapply(simplif l1, List.map simplif ll, info)
+ | Lfunction{kind; params; body = l} ->
+ Lfunction{kind; params; body = simplif l}
+ | Llet(kind, v, l1, l2) -> Llet(kind, v, simplif l1, simplif l2)
+ | Lletrec(bindings, body) ->
+ Lletrec(List.map (fun (v, l) -> (v, simplif l)) bindings, simplif body)
+ | Lprim(p, ll) -> begin
+ let ll = List.map simplif ll in
+ match p, ll with
+ (* Simplify %revapply, for n-ary functions with n > 1 *)
+ | Prevapply loc, [x; Lapply(f, args, info)]
+ | Prevapply loc, [x; Levent (Lapply(f, args, info),_)] ->
+ Lapply(f, args@[x], {info with apply_loc=loc})
+ | Prevapply loc, [x; f] -> Lapply(f, [x], mk_apply_info loc)
+
+ (* Simplify %apply, for n-ary functions with n > 1 *)
+ | Pdirapply loc, [Lapply(f, args, info); x]
+ | Pdirapply loc, [Levent (Lapply(f, args, info),_); x] ->
+ Lapply(f, args@[x], {info with apply_loc=loc})
+ | Pdirapply loc, [f; x] -> Lapply(f, [x], mk_apply_info loc)
+
+ | _ -> Lprim(p, ll)
+ end
+ | Lswitch(l, sw) ->
+ let new_l = simplif l
+ and new_consts = List.map (fun (n, e) -> (n, simplif e)) sw.sw_consts
+ and new_blocks = List.map (fun (n, e) -> (n, simplif e)) sw.sw_blocks
+ and new_fail = Misc.may_map simplif sw.sw_failaction in
+ Lswitch
+ (new_l,
+ {sw with sw_consts = new_consts ; sw_blocks = new_blocks;
+ sw_failaction = new_fail})
+ | Lstringswitch(l,sw,d) ->
+ Lstringswitch
+ (simplif l,List.map (fun (s,l) -> s,simplif l) sw,
+ Misc.may_map simplif d)
+ | Lstaticraise (i,[]) as l ->
+ begin try
+ let _,handler = Hashtbl.find subst i in
+ handler
+ with
+ | Not_found -> l
+ end
+ | Lstaticraise (i,ls) ->
+ let ls = List.map simplif ls in
+ begin try
+ let xs,handler = Hashtbl.find subst i in
+ let ys = List.map Ident.rename xs in
+ let env =
+ List.fold_right2
+ (fun x y t -> Ident.add x (Lvar y) t)
+ xs ys Ident.empty in
+ List.fold_right2
+ (fun y l r -> Llet (Alias, y, l, r))
+ ys ls (Lambda.subst_lambda env handler)
+ with
+ | Not_found -> Lstaticraise (i,ls)
+ end
+ | Lstaticcatch (l1,(i,[]),(Lstaticraise (j,[]) as l2)) ->
+ Hashtbl.add subst i ([],simplif l2) ;
+ simplif l1
+ | Lstaticcatch (l1,(i,xs),l2) ->
+ begin match count_exit i with
+ | 0 -> simplif l1
+ | 1 when i >= 0 ->
+ Hashtbl.add subst i (xs,simplif l2) ;
+ simplif l1
+ | _ ->
+ Lstaticcatch (simplif l1, (i,xs), simplif l2)
+ end
+ | Ltrywith(l1, v, l2) -> Ltrywith(simplif l1, v, simplif l2)
+ | Lifthenelse(l1, l2, l3) -> Lifthenelse(simplif l1, simplif l2, simplif l3)
+ | Lsequence(l1, l2) -> Lsequence(simplif l1, simplif l2)
+ | Lwhile(l1, l2) -> Lwhile(simplif l1, simplif l2)
+ | Lfor(v, l1, l2, dir, l3) ->
+ Lfor(v, simplif l1, simplif l2, dir, simplif l3)
+ | Lassign(v, l) -> Lassign(v, simplif l)
+ | Lsend(k, m, o, ll, loc) ->
+ Lsend(k, simplif m, simplif o, List.map simplif ll, loc)
+ | Levent(l, ev) -> Levent(simplif l, ev)
+ | Lifused(v, l) -> Lifused (v,simplif l)
+ in
+ simplif lam
+
+(* Compile-time beta-reduction of functions immediately applied:
+ Lapply(Lfunction(Curried, params, body), args, loc) ->
+ let paramN = argN in ... let param1 = arg1 in body
+ Lapply(Lfunction(Tupled, params, body), [Lprim(Pmakeblock(args))], loc) ->
+ let paramN = argN in ... let param1 = arg1 in body
+ Assumes |args| = |params|.
+*)
+
+let beta_reduce params body args =
+ List.fold_left2 (fun l param arg -> Llet(Strict, param, arg, l))
+ body params args
+
+(* Simplification of lets *)
+
+let simplify_lets lam =
+
+ (* Disable optimisations for bytecode compilation with -g flag *)
+ let optimize = !Clflags.native_code || not !Clflags.debug in
+
+ (* First pass: count the occurrences of all let-bound identifiers *)
+
+ let occ = (Hashtbl.create 83: (Ident.t, int ref) Hashtbl.t) in
+ (* The global table [occ] associates to each let-bound identifier
+ the number of its uses (as a reference):
+ - 0 if never used
+ - 1 if used exactly once in and not under a lambda or within a loop
+ - > 1 if used several times or under a lambda or within a loop.
+ The local table [bv] associates to each locally-let-bound variable
+ its reference count, as above. [bv] is enriched at let bindings
+ but emptied when crossing lambdas and loops. *)
+
+ (* Current use count of a variable. *)
+ let count_var v =
+ try
+ !(Hashtbl.find occ v)
+ with Not_found ->
+ 0
+
+ (* Entering a [let]. Returns updated [bv]. *)
+ and bind_var bv v =
+ let r = ref 0 in
+ Hashtbl.add occ v r;
+ Tbl.add v r bv
+
+ (* Record a use of a variable *)
+ and use_var bv v n =
+ try
+ let r = Tbl.find v bv in r := !r + n
+ with Not_found ->
+ (* v is not locally bound, therefore this is a use under a lambda
+ or within a loop. Increase use count by 2 -- enough so
+ that single-use optimizations will not apply. *)
+ try
+ let r = Hashtbl.find occ v in r := !r + 2
+ with Not_found ->
+ (* Not a let-bound variable, ignore *)
+ () in
+
+ let rec count bv = function
+ | Lconst cst -> ()
+ | Lvar v ->
+ use_var bv v 1
+ | Lapply(Lfunction{kind = Curried; params; body}, args, _)
+ when optimize && List.length params = List.length args ->
+ count bv (beta_reduce params body args)
+ | Lapply(Lfunction{kind = Tupled; params; body},
+ [Lprim(Pmakeblock _, args)], _)
+ when optimize && List.length params = List.length args ->
+ count bv (beta_reduce params body args)
+ | Lapply(l1, ll, _) ->
+ count bv l1; List.iter (count bv) ll
+ | Lfunction{kind; params; body = l} ->
+ count Tbl.empty l
+ | Llet(str, v, Lvar w, l2) when optimize ->
+ (* v will be replaced by w in l2, so each occurrence of v in l2
+ increases w's refcount *)
+ count (bind_var bv v) l2;
+ use_var bv w (count_var v)
+ | Llet(str, v, l1, l2) ->
+ count (bind_var bv v) l2;
+ (* If v is unused, l1 will be removed, so don't count its variables *)
+ if str = Strict || count_var v > 0 then count bv l1
+ | Lletrec(bindings, body) ->
+ List.iter (fun (v, l) -> count bv l) bindings;
+ count bv body
+ | Lprim(p, ll) -> List.iter (count bv) ll
+ | Lswitch(l, sw) ->
+ count_default bv sw ;
+ count bv l;
+ List.iter (fun (_, l) -> count bv l) sw.sw_consts;
+ List.iter (fun (_, l) -> count bv l) sw.sw_blocks
+ | Lstringswitch(l, sw, d) ->
+ count bv l ;
+ List.iter (fun (_, l) -> count bv l) sw ;
+ begin match d with
+ | Some d ->
+ begin match sw with
+ | []|[_] -> count bv d
+ | _ -> count bv d ; count bv d
+ end
+ | None -> ()
+ end
+ | Lstaticraise (i,ls) -> List.iter (count bv) ls
+ | Lstaticcatch(l1, (i,_), l2) -> count bv l1; count bv l2
+ | Ltrywith(l1, v, l2) -> count bv l1; count bv l2
+ | Lifthenelse(l1, l2, l3) -> count bv l1; count bv l2; count bv l3
+ | Lsequence(l1, l2) -> count bv l1; count bv l2
+ | Lwhile(l1, l2) -> count Tbl.empty l1; count Tbl.empty l2
+ | Lfor(_, l1, l2, dir, l3) -> count bv l1; count bv l2; count Tbl.empty l3
+ | Lassign(v, l) ->
+ (* Lalias-bound variables are never assigned, so don't increase
+ v's refcount *)
+ count bv l
+ | Lsend(_, m, o, ll, _) -> List.iter (count bv) (m::o::ll)
+ | Levent(l, _) -> count bv l
+ | Lifused(v, l) ->
+ if count_var v > 0 then count bv l
+
+ and count_default bv sw = match sw.sw_failaction with
+ | None -> ()
+ | Some al ->
+ let nconsts = List.length sw.sw_consts
+ and nblocks = List.length sw.sw_blocks in
+ if
+ nconsts < sw.sw_numconsts && nblocks < sw.sw_numblocks
+ then begin (* default action will occur twice in native code *)
+ count bv al ; count bv al
+ end else begin (* default action will occur once *)
+ assert (nconsts < sw.sw_numconsts || nblocks < sw.sw_numblocks) ;
+ count bv al
+ end
+ in
+ count Tbl.empty lam;
+
+ (* Second pass: remove Lalias bindings of unused variables,
+ and substitute the bindings of variables used exactly once. *)
+
+ let subst = Hashtbl.create 83 in
+
+(* This (small) optimisation is always legal, it may uncover some
+ tail call later on. *)
+
+ let mklet (kind,v,e1,e2) = match e2 with
+ | Lvar w when optimize && Ident.same v w -> e1
+ | _ -> Llet (kind,v,e1,e2) in
+
+
+ let rec simplif = function
+ Lvar v as l ->
+ begin try
+ Hashtbl.find subst v
+ with Not_found ->
+ l
+ end
+ | Lconst cst as l -> l
+ | Lapply(Lfunction{kind = Curried; params; body}, args, _)
+ when optimize && List.length params = List.length args ->
+ simplif (beta_reduce params body args)
+ | Lapply(Lfunction{kind = Tupled; params; body},
+ [Lprim(Pmakeblock _, args)], _)
+ when optimize && List.length params = List.length args ->
+ simplif (beta_reduce params body args)
+ | Lapply(l1, ll, loc) -> Lapply(simplif l1, List.map simplif ll, loc)
+ | Lfunction{kind; params; body = l} ->
+ begin match simplif l with
+ Lfunction{kind=Curried; params=params'; body}
+ when kind = Curried && optimize ->
+ Lfunction{kind; params = params @ params'; body}
+ | body ->
+ Lfunction{kind; params; body}
+ end
+ | Llet(str, v, Lvar w, l2) when optimize ->
+ Hashtbl.add subst v (simplif (Lvar w));
+ simplif l2
+ | Llet(Strict, v, Lprim(Pmakeblock(0, Mutable), [linit]), lbody)
+ when optimize ->
+ let slinit = simplif linit in
+ let slbody = simplif lbody in
+ begin try
+ mklet (Variable, v, slinit, eliminate_ref v slbody)
+ with Real_reference ->
+ mklet(Strict, v, Lprim(Pmakeblock(0, Mutable), [slinit]), slbody)
+ end
+ | Llet(Alias, v, l1, l2) ->
+ begin match count_var v with
+ 0 -> simplif l2
+ | 1 when optimize -> Hashtbl.add subst v (simplif l1); simplif l2
+ | n -> Llet(Alias, v, simplif l1, simplif l2)
+ end
+ | Llet(StrictOpt, v, l1, l2) ->
+ begin match count_var v with
+ 0 -> simplif l2
+ | n -> mklet(Alias, v, simplif l1, simplif l2)
+ end
+ | Llet(kind, v, l1, l2) -> mklet(kind, v, simplif l1, simplif l2)
+ | Lletrec(bindings, body) ->
+ Lletrec(List.map (fun (v, l) -> (v, simplif l)) bindings, simplif body)
+ | Lprim(p, ll) -> Lprim(p, List.map simplif ll)
+ | Lswitch(l, sw) ->
+ let new_l = simplif l
+ and new_consts = List.map (fun (n, e) -> (n, simplif e)) sw.sw_consts
+ and new_blocks = List.map (fun (n, e) -> (n, simplif e)) sw.sw_blocks
+ and new_fail = Misc.may_map simplif sw.sw_failaction in
+ Lswitch
+ (new_l,
+ {sw with sw_consts = new_consts ; sw_blocks = new_blocks;
+ sw_failaction = new_fail})
+ | Lstringswitch (l,sw,d) ->
+ Lstringswitch
+ (simplif l,List.map (fun (s,l) -> s,simplif l) sw,
+ Misc.may_map simplif d)
+ | Lstaticraise (i,ls) ->
+ Lstaticraise (i, List.map simplif ls)
+ | Lstaticcatch(l1, (i,args), l2) ->
+ Lstaticcatch (simplif l1, (i,args), simplif l2)
+ | Ltrywith(l1, v, l2) -> Ltrywith(simplif l1, v, simplif l2)
+ | Lifthenelse(l1, l2, l3) -> Lifthenelse(simplif l1, simplif l2, simplif l3)
+ | Lsequence(Lifused(v, l1), l2) ->
+ if count_var v > 0
+ then Lsequence(simplif l1, simplif l2)
+ else simplif l2
+ | Lsequence(l1, l2) -> Lsequence(simplif l1, simplif l2)
+ | Lwhile(l1, l2) -> Lwhile(simplif l1, simplif l2)
+ | Lfor(v, l1, l2, dir, l3) ->
+ Lfor(v, simplif l1, simplif l2, dir, simplif l3)
+ | Lassign(v, l) -> Lassign(v, simplif l)
+ | Lsend(k, m, o, ll, loc) ->
+ Lsend(k, simplif m, simplif o, List.map simplif ll, loc)
+ | Levent(l, ev) -> Levent(simplif l, ev)
+ | Lifused(v, l) ->
+ if count_var v > 0 then simplif l else lambda_unit
+ in
+ simplif lam
+
+(* Tail call info in annotation files *)
+
+let is_tail_native_heuristic : (int -> bool) ref =
+ ref (fun n -> true)
+
+let rec emit_tail_infos is_tail lambda =
+ let call_kind args =
+ if is_tail
+ && ((not !Clflags.native_code)
+ || (!is_tail_native_heuristic (List.length args)))
+ then Annot.Tail
+ else Annot.Stack in
+ match lambda with
+ | Lvar _ -> ()
+ | Lconst _ -> ()
+ | Lapply (func, l, ({apply_loc=loc} as info)) ->
+ if info.apply_should_be_tailcall
+ && not is_tail
+ && Warnings.is_active Warnings.Expect_tailcall
+ then Location.prerr_warning loc Warnings.Expect_tailcall;
+ emit_tail_infos false func;
+ list_emit_tail_infos false l;
+ if !Clflags.annotations then
+ Stypes.record (Stypes.An_call (loc, call_kind l));
+ | Lfunction {body = lam} ->
+ emit_tail_infos true lam
+ | Llet (_, _, lam, body) ->
+ emit_tail_infos false lam;
+ emit_tail_infos is_tail body
+ | Lletrec (bindings, body) ->
+ List.iter (fun (_, lam) -> emit_tail_infos false lam) bindings;
+ emit_tail_infos is_tail body
+ | Lprim (Pidentity, [arg]) ->
+ emit_tail_infos is_tail arg
+ | Lprim (Psequand, [arg1; arg2])
+ | Lprim (Psequor, [arg1; arg2]) ->
+ emit_tail_infos false arg1;
+ emit_tail_infos is_tail arg2
+ | Lprim (_, l) ->
+ list_emit_tail_infos false l
+ | Lswitch (lam, sw) ->
+ emit_tail_infos false lam;
+ list_emit_tail_infos_fun snd is_tail sw.sw_consts;
+ list_emit_tail_infos_fun snd is_tail sw.sw_blocks;
+ Misc.may (emit_tail_infos is_tail) sw.sw_failaction
+ | Lstringswitch (lam, sw, d) ->
+ emit_tail_infos false lam;
+ List.iter
+ (fun (_,lam) -> emit_tail_infos is_tail lam)
+ sw ;
+ Misc.may (emit_tail_infos is_tail) d
+ | Lstaticraise (_, l) ->
+ list_emit_tail_infos false l
+ | Lstaticcatch (body, _, handler) ->
+ emit_tail_infos is_tail body;
+ emit_tail_infos is_tail handler
+ | Ltrywith (body, _, handler) ->
+ emit_tail_infos false body;
+ emit_tail_infos is_tail handler
+ | Lifthenelse (cond, ifso, ifno) ->
+ emit_tail_infos false cond;
+ emit_tail_infos is_tail ifso;
+ emit_tail_infos is_tail ifno
+ | Lsequence (lam1, lam2) ->
+ emit_tail_infos false lam1;
+ emit_tail_infos is_tail lam2
+ | Lwhile (cond, body) ->
+ emit_tail_infos false cond;
+ emit_tail_infos false body
+ | Lfor (_, low, high, _, body) ->
+ emit_tail_infos false low;
+ emit_tail_infos false high;
+ emit_tail_infos false body
+ | Lassign (_, lam) ->
+ emit_tail_infos false lam
+ | Lsend (_, meth, obj, args, loc) ->
+ emit_tail_infos false meth;
+ emit_tail_infos false obj;
+ list_emit_tail_infos false args;
+ if !Clflags.annotations then
+ Stypes.record (Stypes.An_call (loc, call_kind (obj :: args)));
+ | Levent (lam, _) ->
+ emit_tail_infos is_tail lam
+ | Lifused (_, lam) ->
+ emit_tail_infos is_tail lam
+and list_emit_tail_infos_fun f is_tail =
+ List.iter (fun x -> emit_tail_infos is_tail (f x))
+and list_emit_tail_infos is_tail =
+ List.iter (emit_tail_infos is_tail)
+
+(* The entry point:
+ simplification + emission of tailcall annotations, if needed. *)
+
+let simplify_lambda lam =
+ let res = simplify_lets (simplify_exits lam) in
+ if !Clflags.annotations || Warnings.is_active Warnings.Expect_tailcall
+ then emit_tail_infos true res;
+ res
diff --git a/bytecomp/simplif.mli b/bytecomp/simplif.mli
new file mode 100644
index 0000000000..4cc6dab977
--- /dev/null
+++ b/bytecomp/simplif.mli
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Elimination of useless Llet(Alias) bindings.
+ Transformation of let-bound references into variables.
+ Simplification over staticraise/staticcatch constructs.
+ Generation of tail-call annotations if -annot is set. *)
+
+open Lambda
+
+val simplify_lambda: lambda -> lambda
+
+(* To be filled by asmcomp/selectgen.ml *)
+val is_tail_native_heuristic: (int -> bool) ref
+ (* # arguments -> can tailcall *)
diff --git a/bytecomp/switch.ml b/bytecomp/switch.ml
new file mode 100644
index 0000000000..4e49520dcb
--- /dev/null
+++ b/bytecomp/switch.ml
@@ -0,0 +1,884 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+
+type 'a shared = Shared of 'a | Single of 'a
+
+let share_out = function
+ | Shared act|Single act -> act
+
+
+type 'a t_store =
+ {act_get : unit -> 'a array ;
+ act_get_shared : unit -> 'a shared array ;
+ act_store : 'a -> int ;
+ act_store_shared : 'a -> int ; }
+
+exception Not_simple
+
+module type Stored = sig
+ type t
+ type key
+ val make_key : t -> key option
+end
+
+module Store(A:Stored) = struct
+ module AMap =
+ Map.Make(struct type t = A.key let compare = Pervasives.compare end)
+
+ type intern =
+ { mutable map : (bool * int) AMap.t ;
+ mutable next : int ;
+ mutable acts : (bool * A.t) list; }
+
+ let mk_store () =
+ let st =
+ { map = AMap.empty ;
+ next = 0 ;
+ acts = [] ; } in
+
+ let add mustshare act =
+ let i = st.next in
+ st.acts <- (mustshare,act) :: st.acts ;
+ st.next <- i+1 ;
+ i in
+
+ let store mustshare act = match A.make_key act with
+ | Some key ->
+ begin try
+ let (shared,i) = AMap.find key st.map in
+ if not shared then st.map <- AMap.add key (true,i) st.map ;
+ i
+ with Not_found ->
+ let i = add mustshare act in
+ st.map <- AMap.add key (mustshare,i) st.map ;
+ i
+ end
+ | None ->
+ add mustshare act
+
+ and get () = Array.of_list (List.rev_map (fun (_,act) -> act) st.acts)
+
+ and get_shared () =
+ let acts =
+ Array.of_list
+ (List.rev_map
+ (fun (shared,act) ->
+ if shared then Shared act else Single act)
+ st.acts) in
+ AMap.iter
+ (fun _ (shared,i) ->
+ if shared then match acts.(i) with
+ | Single act -> acts.(i) <- Shared act
+ | Shared _ -> ())
+ st.map ;
+ acts in
+ {act_store = store false ; act_store_shared = store true ;
+ act_get = get; act_get_shared = get_shared; }
+end
+
+
+
+module type S =
+ sig
+ type primitive
+ val eqint : primitive
+ val neint : primitive
+ val leint : primitive
+ val ltint : primitive
+ val geint : primitive
+ val gtint : primitive
+ type act
+
+ val bind : act -> (act -> act) -> act
+ val make_const : int -> act
+ val make_offset : act -> int -> act
+ val make_prim : primitive -> act list -> act
+ val make_isout : act -> act -> act
+ val make_isin : act -> act -> act
+ val make_if : act -> act -> act -> act
+ val make_switch : act -> int array -> act array -> act
+ val make_catch : act -> int * (act -> act)
+ val make_exit : int -> act
+ end
+
+(* The module will ``produce good code for the case statement'' *)
+(*
+ Adaptation of
+ R.L. Berstein
+ ``Producing good code for the case statement''
+ Sofware Practice and Experience, 15(10) (1985)
+ and
+ D.L. Spuler
+ ``Two-Way Comparison Search Trees, a Generalisation of Binary Search Trees
+ and Split Trees''
+ ``Compiler Code Generation for Multiway Branch Statement as
+ a Static Search Problem''
+ Technical Reports, James Cook University
+*)
+(*
+ Main adaptation is considering interval tests
+ (implemented as one addition + one unsigned test and branch)
+ which leads to exhaustive search for finding the optimal
+ test sequence in small cases and heuristics otherwise.
+*)
+module Make (Arg : S) =
+ struct
+
+ type 'a inter =
+ {cases : (int * int * int) array ;
+ actions : 'a array}
+
+type 'a t_ctx = {off : int ; arg : 'a}
+
+let cut = ref 8
+and more_cut = ref 16
+
+let pint chan i =
+ if i = min_int then Printf.fprintf chan "-oo"
+ else if i=max_int then Printf.fprintf chan "oo"
+ else Printf.fprintf chan "%d" i
+
+let pcases chan cases =
+ for i =0 to Array.length cases-1 do
+ let l,h,act = cases.(i) in
+ if l=h then
+ Printf.fprintf chan "%d:%d " l act
+ else
+ Printf.fprintf chan "%a..%a:%d " pint l pint h act
+ done
+
+ let prerr_inter i = Printf.fprintf stderr
+ "cases=%a" pcases i.cases
+
+let get_act cases i =
+ let _,_,r = cases.(i) in
+ r
+and get_low cases i =
+ let r,_,_ = cases.(i) in
+ r
+
+type ctests = {
+ mutable n : int ;
+ mutable ni : int ;
+ }
+
+let too_much = {n=max_int ; ni=max_int}
+
+let ptests chan {n=n ; ni=ni} =
+ Printf.fprintf chan "{n=%d ; ni=%d}" n ni
+
+let pta chan t =
+ for i =0 to Array.length t-1 do
+ Printf.fprintf chan "%d: %a\n" i ptests t.(i)
+ done
+
+let count_tests s =
+ let r =
+ Array.init
+ (Array.length s.actions)
+ (fun _ -> {n=0 ; ni=0 }) in
+ let c = s.cases in
+ let imax = Array.length c-1 in
+ for i=0 to imax do
+ let l,h,act = c.(i) in
+ let x = r.(act) in
+ x.n <- x.n+1 ;
+ if l < h && i<> 0 && i<>imax then
+ x.ni <- x.ni+1 ;
+ done ;
+ r
+
+
+let less_tests c1 c2 =
+ if c1.n < c2.n then
+ true
+ else if c1.n = c2.n then begin
+ if c1.ni < c2.ni then
+ true
+ else
+ false
+ end else
+ false
+
+and eq_tests c1 c2 = c1.n = c2.n && c1.ni=c2.ni
+
+let min_tests c1 c2 = if less_tests c1 c2 then c1 else c2
+
+let less2tests (c1,d1) (c2,d2) =
+ if eq_tests c1 c2 then
+ less_tests d1 d2
+ else
+ less_tests c1 c2
+
+let add_test t1 t2 =
+ t1.n <- t1.n + t2.n ;
+ t1.ni <- t1.ni + t2.ni ;
+
+type t_ret = Inter of int * int | Sep of int | No
+
+let pret chan = function
+ | Inter (i,j)-> Printf.fprintf chan "Inter %d %d" i j
+ | Sep i -> Printf.fprintf chan "Sep %d" i
+ | No -> Printf.fprintf chan "No"
+
+let coupe cases i =
+ let l,_,_ = cases.(i) in
+ l,
+ Array.sub cases 0 i,
+ Array.sub cases i (Array.length cases-i)
+
+
+let case_append c1 c2 =
+ let len1 = Array.length c1
+ and len2 = Array.length c2 in
+ match len1,len2 with
+ | 0,_ -> c2
+ | _,0 -> c1
+ | _,_ ->
+ let l1,h1,act1 = c1.(Array.length c1-1)
+ and l2,h2,act2 = c2.(0) in
+ if act1 = act2 then
+ let r = Array.make (len1+len2-1) c1.(0) in
+ for i = 0 to len1-2 do
+ r.(i) <- c1.(i)
+ done ;
+
+ let l =
+ if len1-2 >= 0 then begin
+ let _,h,_ = r.(len1-2) in
+ if h+1 < l1 then
+ h+1
+ else
+ l1
+ end else
+ l1
+ and h =
+ if 1 < len2-1 then begin
+ let l,_,_ = c2.(1) in
+ if h2+1 < l then
+ l-1
+ else
+ h2
+ end else
+ h2 in
+ r.(len1-1) <- (l,h,act1) ;
+ for i=1 to len2-1 do
+ r.(len1-1+i) <- c2.(i)
+ done ;
+ r
+ else if h1 > l1 then
+ let r = Array.make (len1+len2) c1.(0) in
+ for i = 0 to len1-2 do
+ r.(i) <- c1.(i)
+ done ;
+ r.(len1-1) <- (l1,l2-1,act1) ;
+ for i=0 to len2-1 do
+ r.(len1+i) <- c2.(i)
+ done ;
+ r
+ else if h2 > l2 then
+ let r = Array.make (len1+len2) c1.(0) in
+ for i = 0 to len1-1 do
+ r.(i) <- c1.(i)
+ done ;
+ r.(len1) <- (h1+1,h2,act2) ;
+ for i=1 to len2-1 do
+ r.(len1+i) <- c2.(i)
+ done ;
+ r
+ else
+ Array.append c1 c2
+
+
+let coupe_inter i j cases =
+ let lcases = Array.length cases in
+ let low,_,_ = cases.(i)
+ and _,high,_ = cases.(j) in
+ low,high,
+ Array.sub cases i (j-i+1),
+ case_append (Array.sub cases 0 i) (Array.sub cases (j+1) (lcases-(j+1)))
+
+type kind = Kvalue of int | Kinter of int | Kempty
+
+let pkind chan = function
+ | Kvalue i ->Printf.fprintf chan "V%d" i
+ | Kinter i -> Printf.fprintf chan "I%d" i
+ | Kempty -> Printf.fprintf chan "E"
+
+let rec pkey chan = function
+ | [] -> ()
+ | [k] -> pkind chan k
+ | k::rem ->
+ Printf.fprintf chan "%a %a" pkey rem pkind k
+
+let t = Hashtbl.create 17
+
+let make_key cases =
+ let seen = ref []
+ and count = ref 0 in
+ let rec got_it act = function
+ | [] ->
+ seen := (act,!count):: !seen ;
+ let r = !count in
+ incr count ;
+ r
+ | (act0,index) :: rem ->
+ if act0 = act then
+ index
+ else
+ got_it act rem in
+
+ let make_one l h act =
+ if l=h then
+ Kvalue (got_it act !seen)
+ else
+ Kinter (got_it act !seen) in
+
+ let rec make_rec i pl =
+ if i < 0 then
+ []
+ else
+ let l,h,act = cases.(i) in
+ if pl = h+1 then
+ make_one l h act::make_rec (i-1) l
+ else
+ Kempty::make_one l h act::make_rec (i-1) l in
+
+ let l,h,act = cases.(Array.length cases-1) in
+ make_one l h act::make_rec (Array.length cases-2) l
+
+
+ let same_act t =
+ let len = Array.length t in
+ let a = get_act t (len-1) in
+ let rec do_rec i =
+ if i < 0 then true
+ else
+ let b = get_act t i in
+ b=a && do_rec (i-1) in
+ do_rec (len-2)
+
+
+(*
+ Intervall test x in [l,h] works by checking x-l in [0,h-l]
+ * This may be false for arithmetic modulo 2^31
+ * Subtracting l may change the relative ordering of values
+ and invalid the invariant that matched values are given in
+ increasing order
+
+ To avoid this, interval check is allowed only when the
+ integers indeed present in the whole case interval are
+ in [-2^16 ; 2^16]
+
+ This condition is checked by zyva
+*)
+
+let inter_limit = 1 lsl 16
+
+let ok_inter = ref false
+
+let rec opt_count top cases =
+ let key = make_key cases in
+ try
+ let r = Hashtbl.find t key in
+ r
+ with
+ | Not_found ->
+ let r =
+ let lcases = Array.length cases in
+ match lcases with
+ | 0 -> assert false
+ | _ when same_act cases -> No, ({n=0; ni=0},{n=0; ni=0})
+ | _ ->
+ if lcases < !cut then
+ enum top cases
+ else if lcases < !more_cut then
+ heuristic top cases
+ else
+ divide top cases in
+ Hashtbl.add t key r ;
+ r
+
+and divide top cases =
+ let lcases = Array.length cases in
+ let m = lcases/2 in
+ let _,left,right = coupe cases m in
+ let ci = {n=1 ; ni=0}
+ and cm = {n=1 ; ni=0}
+ and _,(cml,cleft) = opt_count false left
+ and _,(cmr,cright) = opt_count false right in
+ add_test ci cleft ;
+ add_test ci cright ;
+ if less_tests cml cmr then
+ add_test cm cmr
+ else
+ add_test cm cml ;
+ Sep m,(cm, ci)
+
+and heuristic top cases =
+ let lcases = Array.length cases in
+
+ let sep,csep = divide false cases
+
+ and inter,cinter =
+ if !ok_inter then begin
+ let _,_,act0 = cases.(0)
+ and _,_,act1 = cases.(lcases-1) in
+ if act0 = act1 then begin
+ let low, high, inside, outside = coupe_inter 1 (lcases-2) cases in
+ let _,(cmi,cinside) = opt_count false inside
+ and _,(cmo,coutside) = opt_count false outside
+ and cmij = {n=1 ; ni=(if low=high then 0 else 1)}
+ and cij = {n=1 ; ni=(if low=high then 0 else 1)} in
+ add_test cij cinside ;
+ add_test cij coutside ;
+ if less_tests cmi cmo then
+ add_test cmij cmo
+ else
+ add_test cmij cmi ;
+ Inter (1,lcases-2),(cmij,cij)
+ end else
+ Inter (-1,-1),(too_much, too_much)
+ end else
+ Inter (-1,-1),(too_much, too_much) in
+ if less2tests csep cinter then
+ sep,csep
+ else
+ inter,cinter
+
+
+and enum top cases =
+ let lcases = Array.length cases in
+ let lim, with_sep =
+ let best = ref (-1) and best_cost = ref (too_much,too_much) in
+
+ for i = 1 to lcases-(1) do
+ let _,left,right = coupe cases i in
+ let ci = {n=1 ; ni=0}
+ and cm = {n=1 ; ni=0}
+ and _,(cml,cleft) = opt_count false left
+ and _,(cmr,cright) = opt_count false right in
+ add_test ci cleft ;
+ add_test ci cright ;
+ if less_tests cml cmr then
+ add_test cm cmr
+ else
+ add_test cm cml ;
+
+ if
+ less2tests (cm,ci) !best_cost
+ then begin
+ if top then
+ Printf.fprintf stderr "Get it: %d\n" i ;
+ best := i ;
+ best_cost := (cm,ci)
+ end
+ done ;
+ !best, !best_cost in
+
+ let ilow, ihigh, with_inter =
+ if not !ok_inter then
+ let rlow = ref (-1) and rhigh = ref (-1)
+ and best_cost= ref (too_much,too_much) in
+ for i=1 to lcases-2 do
+ let low, high, inside, outside = coupe_inter i i cases in
+ if low=high then begin
+ let _,(cmi,cinside) = opt_count false inside
+ and _,(cmo,coutside) = opt_count false outside
+ and cmij = {n=1 ; ni=0}
+ and cij = {n=1 ; ni=0} in
+ add_test cij cinside ;
+ add_test cij coutside ;
+ if less_tests cmi cmo then
+ add_test cmij cmo
+ else
+ add_test cmij cmi ;
+ if less2tests (cmij,cij) !best_cost then begin
+ rlow := i ;
+ rhigh := i ;
+ best_cost := (cmij,cij)
+ end
+ end
+ done ;
+ !rlow, !rhigh, !best_cost
+ else
+ let rlow = ref (-1) and rhigh = ref (-1)
+ and best_cost= ref (too_much,too_much) in
+ for i=1 to lcases-2 do
+ for j=i to lcases-2 do
+ let low, high, inside, outside = coupe_inter i j cases in
+ let _,(cmi,cinside) = opt_count false inside
+ and _,(cmo,coutside) = opt_count false outside
+ and cmij = {n=1 ; ni=(if low=high then 0 else 1)}
+ and cij = {n=1 ; ni=(if low=high then 0 else 1)} in
+ add_test cij cinside ;
+ add_test cij coutside ;
+ if less_tests cmi cmo then
+ add_test cmij cmo
+ else
+ add_test cmij cmi ;
+ if less2tests (cmij,cij) !best_cost then begin
+ rlow := i ;
+ rhigh := j ;
+ best_cost := (cmij,cij)
+ end
+ done
+ done ;
+ !rlow, !rhigh, !best_cost in
+ let r = ref (Inter (ilow,ihigh)) and rc = ref with_inter in
+ if less2tests with_sep !rc then begin
+ r := Sep lim ; rc := with_sep
+ end ;
+ !r, !rc
+
+ let make_if_test test arg i ifso ifnot =
+ Arg.make_if
+ (Arg.make_prim test [arg ; Arg.make_const i])
+ ifso ifnot
+
+ let make_if_lt arg i ifso ifnot = match i with
+ | 1 ->
+ make_if_test Arg.leint arg 0 ifso ifnot
+ | _ ->
+ make_if_test Arg.ltint arg i ifso ifnot
+
+ and make_if_le arg i ifso ifnot = match i with
+ | -1 ->
+ make_if_test Arg.ltint arg 0 ifso ifnot
+ | _ ->
+ make_if_test Arg.leint arg i ifso ifnot
+
+ and make_if_gt arg i ifso ifnot = match i with
+ | -1 ->
+ make_if_test Arg.geint arg 0 ifso ifnot
+ | _ ->
+ make_if_test Arg.gtint arg i ifso ifnot
+
+ and make_if_ge arg i ifso ifnot = match i with
+ | 1 ->
+ make_if_test Arg.gtint arg 0 ifso ifnot
+ | _ ->
+ make_if_test Arg.geint arg i ifso ifnot
+
+ and make_if_eq arg i ifso ifnot =
+ make_if_test Arg.eqint arg i ifso ifnot
+
+ and make_if_ne arg i ifso ifnot =
+ make_if_test Arg.neint arg i ifso ifnot
+
+ let do_make_if_out h arg ifso ifno =
+ Arg.make_if (Arg.make_isout h arg) ifso ifno
+
+ let make_if_out ctx l d mk_ifso mk_ifno = match l with
+ | 0 ->
+ do_make_if_out
+ (Arg.make_const d) ctx.arg (mk_ifso ctx) (mk_ifno ctx)
+ | _ ->
+ Arg.bind
+ (Arg.make_offset ctx.arg (-l))
+ (fun arg ->
+ let ctx = {off= (-l+ctx.off) ; arg=arg} in
+ do_make_if_out
+ (Arg.make_const d) arg (mk_ifso ctx) (mk_ifno ctx))
+
+ let do_make_if_in h arg ifso ifno =
+ Arg.make_if (Arg.make_isin h arg) ifso ifno
+
+ let make_if_in ctx l d mk_ifso mk_ifno = match l with
+ | 0 ->
+ do_make_if_in
+ (Arg.make_const d) ctx.arg (mk_ifso ctx) (mk_ifno ctx)
+ | _ ->
+ Arg.bind
+ (Arg.make_offset ctx.arg (-l))
+ (fun arg ->
+ let ctx = {off= (-l+ctx.off) ; arg=arg} in
+ do_make_if_in
+ (Arg.make_const d) arg (mk_ifso ctx) (mk_ifno ctx))
+
+ let rec c_test ctx ({cases=cases ; actions=actions} as s) =
+ let lcases = Array.length cases in
+ assert(lcases > 0) ;
+ if lcases = 1 then
+ actions.(get_act cases 0) ctx
+
+ else begin
+
+ let w,c = opt_count false cases in
+(*
+ Printf.fprintf stderr
+ "off=%d tactic=%a for %a\n"
+ ctx.off pret w pcases cases ;
+ *)
+ match w with
+ | No -> actions.(get_act cases 0) ctx
+ | Inter (i,j) ->
+ let low,high,inside, outside = coupe_inter i j cases in
+ let _,(cinside,_) = opt_count false inside
+ and _,(coutside,_) = opt_count false outside in
+(* Costs are retrieved to put the code with more remaining tests
+ in the privileged (positive) branch of ``if'' *)
+ if low=high then begin
+ if less_tests coutside cinside then
+ make_if_eq
+ ctx.arg
+ (low+ctx.off)
+ (c_test ctx {s with cases=inside})
+ (c_test ctx {s with cases=outside})
+ else
+ make_if_ne
+ ctx.arg
+ (low+ctx.off)
+ (c_test ctx {s with cases=outside})
+ (c_test ctx {s with cases=inside})
+ end else begin
+ if less_tests coutside cinside then
+ make_if_in
+ ctx
+ (low+ctx.off)
+ (high-low)
+ (fun ctx -> c_test ctx {s with cases=inside})
+ (fun ctx -> c_test ctx {s with cases=outside})
+ else
+ make_if_out
+ ctx
+ (low+ctx.off)
+ (high-low)
+ (fun ctx -> c_test ctx {s with cases=outside})
+ (fun ctx -> c_test ctx {s with cases=inside})
+ end
+ | Sep i ->
+ let lim,left,right = coupe cases i in
+ let _,(cleft,_) = opt_count false left
+ and _,(cright,_) = opt_count false right in
+ let left = {s with cases=left}
+ and right = {s with cases=right} in
+
+ if i=1 && (lim+ctx.off)=1 && get_low cases 0+ctx.off=0 then
+ make_if_ne
+ ctx.arg 0
+ (c_test ctx right) (c_test ctx left)
+ else if less_tests cright cleft then
+ make_if_lt
+ ctx.arg (lim+ctx.off)
+ (c_test ctx left) (c_test ctx right)
+ else
+ make_if_ge
+ ctx.arg (lim+ctx.off)
+ (c_test ctx right) (c_test ctx left)
+
+ end
+
+
+(* Minimal density of switches *)
+let theta = ref 0.33333
+
+(* Minmal number of tests to make a switch *)
+let switch_min = ref 3
+
+(* Particular case 0, 1, 2 *)
+let particular_case cases i j =
+ j-i = 2 &&
+ (let l1,h1,act1 = cases.(i)
+ and l2,h2,act2 = cases.(i+1)
+ and l3,h3,act3 = cases.(i+2) in
+ l1+1=l2 && l2+1=l3 && l3=h3 &&
+ act1 <> act3)
+
+let approx_count cases i j n_actions =
+ let l = j-i+1 in
+ if l < !cut then
+ let _,(_,{n=ntests}) = opt_count false (Array.sub cases i l) in
+ ntests
+ else
+ l-1
+
+(* Sends back a boolean that says whether is switch is worth or not *)
+
+let dense {cases=cases ; actions=actions} i j =
+ if i=j then true
+ else
+ let l,_,_ = cases.(i)
+ and _,h,_ = cases.(j) in
+ let ntests = approx_count cases i j (Array.length actions) in
+(*
+ (ntests+1) >= theta * (h-l+1)
+*)
+ particular_case cases i j ||
+ (ntests >= !switch_min &&
+ float_of_int ntests +. 1.0 >=
+ !theta *. (float_of_int h -. float_of_int l +. 1.0))
+
+(* Compute clusters by dynamic programming
+ Adaptation of the correction to Bernstein
+ ``Correction to `Producing Good Code for the Case Statement' ''
+ S.K. Kannan and T.A. Proebsting
+ Software Practice and Exprience Vol. 24(2) 233 (Feb 1994)
+*)
+
+let comp_clusters ({cases=cases ; actions=actions} as s) =
+ let len = Array.length cases in
+ let min_clusters = Array.make len max_int
+ and k = Array.make len 0 in
+ let get_min i = if i < 0 then 0 else min_clusters.(i) in
+
+ for i = 0 to len-1 do
+ for j = 0 to i do
+ if
+ dense s j i &&
+ get_min (j-1) + 1 < min_clusters.(i)
+ then begin
+ k.(i) <- j ;
+ min_clusters.(i) <- get_min (j-1) + 1
+ end
+ done ;
+ done ;
+ min_clusters.(len-1),k
+
+(* Assume j > i *)
+let make_switch {cases=cases ; actions=actions} i j =
+ let ll,_,_ = cases.(i)
+ and _,hh,_ = cases.(j) in
+ let tbl = Array.make (hh-ll+1) 0
+ and t = Hashtbl.create 17
+ and index = ref 0 in
+ let get_index act =
+ try
+ Hashtbl.find t act
+ with
+ | Not_found ->
+ let i = !index in
+ incr index ;
+ Hashtbl.add t act i ;
+ i in
+
+ for k=i to j do
+ let l,h,act = cases.(k) in
+ let index = get_index act in
+ for kk=l-ll to h-ll do
+ tbl.(kk) <- index
+ done
+ done ;
+ let acts = Array.make !index actions.(0) in
+ Hashtbl.iter
+ (fun act i -> acts.(i) <- actions.(act))
+ t ;
+ (fun ctx ->
+ match -ll-ctx.off with
+ | 0 -> Arg.make_switch ctx.arg tbl acts
+ | _ ->
+ Arg.bind
+ (Arg.make_offset ctx.arg (-ll-ctx.off))
+ (fun arg -> Arg.make_switch arg tbl acts))
+
+
+let make_clusters ({cases=cases ; actions=actions} as s) n_clusters k =
+ let len = Array.length cases in
+ let r = Array.make n_clusters (0,0,0)
+ and t = Hashtbl.create 17
+ and index = ref 0
+ and bidon = ref (Array.length actions) in
+ let get_index act =
+ try
+ let i,_ = Hashtbl.find t act in
+ i
+ with
+ | Not_found ->
+ let i = !index in
+ incr index ;
+ Hashtbl.add
+ t act
+ (i,(fun _ -> actions.(act))) ;
+ i
+ and add_index act =
+ let i = !index in
+ incr index ;
+ incr bidon ;
+ Hashtbl.add t !bidon (i,act) ;
+ i in
+
+ let rec zyva j ir =
+ let i = k.(j) in
+ begin if i=j then
+ let l,h,act = cases.(i) in
+ r.(ir) <- (l,h,get_index act)
+ else (* assert i < j *)
+ let l,_,_ = cases.(i)
+ and _,h,_ = cases.(j) in
+ r.(ir) <- (l,h,add_index (make_switch s i j))
+ end ;
+ if i > 0 then zyva (i-1) (ir-1) in
+
+ zyva (len-1) (n_clusters-1) ;
+ let acts = Array.make !index (fun _ -> assert false) in
+ Hashtbl.iter (fun _ (i,act) -> acts.(i) <- act) t ;
+ {cases = r ; actions = acts}
+;;
+
+
+let do_zyva (low,high) arg cases actions =
+ let old_ok = !ok_inter in
+ ok_inter := (abs low <= inter_limit && abs high <= inter_limit) ;
+ if !ok_inter <> old_ok then Hashtbl.clear t ;
+
+ let s = {cases=cases ; actions=actions} in
+
+(*
+ Printf.eprintf "ZYVA: %b [low=%i,high=%i]\n" !ok_inter low high ;
+ pcases stderr cases ;
+ prerr_endline "" ;
+*)
+ let n_clusters,k = comp_clusters s in
+ let clusters = make_clusters s n_clusters k in
+ let r = c_test {arg=arg ; off=0} clusters in
+ r
+
+let abstract_shared actions =
+ let handlers = ref (fun x -> x) in
+ let actions =
+ Array.map
+ (fun act -> match act with
+ | Single act -> act
+ | Shared act ->
+ let i,h = Arg.make_catch act in
+ let oh = !handlers in
+ handlers := (fun act -> h (oh act)) ;
+ Arg.make_exit i)
+ actions in
+ !handlers,actions
+
+let zyva lh arg cases actions =
+ assert (Array.length cases > 0) ;
+ let actions = actions.act_get_shared () in
+ let hs,actions = abstract_shared actions in
+ hs (do_zyva lh arg cases actions)
+
+and test_sequence arg cases actions =
+ assert (Array.length cases > 0) ;
+ let actions = actions.act_get_shared () in
+ let hs,actions = abstract_shared actions in
+ let old_ok = !ok_inter in
+ ok_inter := false ;
+ if !ok_inter <> old_ok then Hashtbl.clear t ;
+ let s =
+ {cases=cases ;
+ actions=Array.map (fun act -> (fun _ -> act)) actions} in
+(*
+ Printf.eprintf "SEQUENCE: %b\n" !ok_inter ;
+ pcases stderr cases ;
+ prerr_endline "" ;
+*)
+ hs (c_test {arg=arg ; off=0} s)
+;;
+
+end
diff --git a/bytecomp/switch.mli b/bytecomp/switch.mli
new file mode 100644
index 0000000000..53fd997485
--- /dev/null
+++ b/bytecomp/switch.mli
@@ -0,0 +1,113 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*
+ This module transforms generic switches in combinations
+ of if tests and switches.
+*)
+
+(* For detecting action sharing, object style *)
+
+(* Store for actions in object style:
+ act_store : store an action, returns index in table
+ In case an action with equal key exists, returns index
+ of the stored action. Otherwise add entry in table.
+ act_store_shared : This stored action will always be shared.
+ act_get : retrieve table
+ act_get_shared : retrieve table, with sharing explicit
+*)
+
+type 'a shared = Shared of 'a | Single of 'a
+
+type 'a t_store =
+ {act_get : unit -> 'a array ;
+ act_get_shared : unit -> 'a shared array ;
+ act_store : 'a -> int ;
+ act_store_shared : 'a -> int ; }
+
+exception Not_simple
+
+module type Stored = sig
+ type t
+ type key
+ val make_key : t -> key option
+end
+
+module Store(A:Stored) :
+ sig
+ val mk_store : unit -> A.t t_store
+ end
+
+(* Arguments to the Make functor *)
+module type S =
+ sig
+ (* type of basic tests *)
+ type primitive
+ (* basic tests themselves *)
+ val eqint : primitive
+ val neint : primitive
+ val leint : primitive
+ val ltint : primitive
+ val geint : primitive
+ val gtint : primitive
+ (* type of actions *)
+ type act
+
+ (* Various constructors, for making a binder,
+ adding one integer, etc. *)
+ val bind : act -> (act -> act) -> act
+ val make_const : int -> act
+ val make_offset : act -> int -> act
+ val make_prim : primitive -> act list -> act
+ val make_isout : act -> act -> act
+ val make_isin : act -> act -> act
+ val make_if : act -> act -> act -> act
+ (* construct an actual switch :
+ make_switch arg cases acts
+ NB: cases is in the value form *)
+ val make_switch :
+ act -> int array -> act array -> act
+ (* Build last minute sharing of action stuff *)
+ val make_catch : act -> int * (act -> act)
+ val make_exit : int -> act
+
+ end
+
+
+(*
+ Make.zyva arg low high cases actions where
+ - arg is the argument of the switch.
+ - low, high are the interval limits.
+ - cases is a list of sub-interval and action indices
+ - actions is an array of actions.
+
+ All these arguments specify a switch construct and zyva
+ returns an action that performs the switch,
+*)
+module Make :
+ functor (Arg : S) ->
+ sig
+(* Standard entry point, sharing is tracked *)
+ val zyva :
+ (int * int) ->
+ Arg.act ->
+ (int * int * int) array ->
+ Arg.act t_store ->
+ Arg.act
+
+(* Output test sequence, sharing tracked *)
+ val test_sequence :
+ Arg.act ->
+ (int * int * int) array ->
+ Arg.act t_store ->
+ Arg.act
+ end
diff --git a/bytecomp/symtable.ml b/bytecomp/symtable.ml
new file mode 100644
index 0000000000..a0ce27373e
--- /dev/null
+++ b/bytecomp/symtable.ml
@@ -0,0 +1,393 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* To assign numbers to globals and primitives *)
+
+open Misc
+open Asttypes
+open Lambda
+open Cmo_format
+
+(* Functions for batch linking *)
+
+type error =
+ Undefined_global of string
+ | Unavailable_primitive of string
+ | Wrong_vm of string
+ | Uninitialized_global of string
+
+exception Error of error
+
+(* Tables for numbering objects *)
+
+type 'a numtable =
+ { num_cnt: int; (* The next number *)
+ num_tbl: ('a, int) Tbl.t } (* The table of already numbered objects *)
+
+let empty_numtable = { num_cnt = 0; num_tbl = Tbl.empty }
+
+let find_numtable nt key =
+ Tbl.find key nt.num_tbl
+
+let enter_numtable nt key =
+ let n = !nt.num_cnt in
+ nt := { num_cnt = n + 1; num_tbl = Tbl.add key n !nt.num_tbl };
+ n
+
+let incr_numtable nt =
+ let n = !nt.num_cnt in
+ nt := { num_cnt = n + 1; num_tbl = !nt.num_tbl };
+ n
+
+(* Global variables *)
+
+let global_table = ref(empty_numtable : Ident.t numtable)
+and literal_table = ref([] : (int * structured_constant) list)
+
+let is_global_defined id =
+ Tbl.mem id (!global_table).num_tbl
+
+let slot_for_getglobal id =
+ try
+ find_numtable !global_table id
+ with Not_found ->
+ raise(Error(Undefined_global(Ident.name id)))
+
+let slot_for_setglobal id =
+ enter_numtable global_table id
+
+let slot_for_literal cst =
+ let n = incr_numtable global_table in
+ literal_table := (n, cst) :: !literal_table;
+ n
+
+(* The C primitives *)
+
+let c_prim_table = ref(empty_numtable : string numtable)
+
+let set_prim_table name =
+ ignore(enter_numtable c_prim_table name)
+
+let num_of_prim name =
+ try
+ find_numtable !c_prim_table name
+ with Not_found ->
+ if !Clflags.custom_runtime || Config.host <> Config.target
+ || !Clflags.no_check_prims
+ then
+ enter_numtable c_prim_table name
+ else begin
+ let symb =
+ try Dll.find_primitive name
+ with Not_found -> raise(Error(Unavailable_primitive name)) in
+ let num = enter_numtable c_prim_table name in
+ Dll.synchronize_primitive num symb;
+ num
+ end
+
+let require_primitive name =
+ if name.[0] <> '%' then ignore(num_of_prim name)
+
+let all_primitives () =
+ let prim = Array.make !c_prim_table.num_cnt "" in
+ Tbl.iter (fun name number -> prim.(number) <- name) !c_prim_table.num_tbl;
+ prim
+
+let data_primitive_names () =
+ let prim = all_primitives() in
+ let b = Buffer.create 512 in
+ for i = 0 to Array.length prim - 1 do
+ Buffer.add_string b prim.(i); Buffer.add_char b '\000'
+ done;
+ Buffer.contents b
+
+let output_primitive_names outchan =
+ output_string outchan (data_primitive_names())
+
+open Printf
+
+let output_primitive_table outchan =
+ let prim = all_primitives() in
+ for i = 0 to Array.length prim - 1 do
+ fprintf outchan "extern value %s();\n" prim.(i)
+ done;
+ fprintf outchan "typedef value (*primitive)();\n";
+ fprintf outchan "primitive caml_builtin_cprim[] = {\n";
+ for i = 0 to Array.length prim - 1 do
+ fprintf outchan " %s,\n" prim.(i)
+ done;
+ fprintf outchan " (primitive) 0 };\n";
+ fprintf outchan "const char * caml_names_of_builtin_cprim[] = {\n";
+ for i = 0 to Array.length prim - 1 do
+ fprintf outchan " \"%s\",\n" prim.(i)
+ done;
+ fprintf outchan " (char *) 0 };\n"
+
+(* Initialization for batch linking *)
+
+let init () =
+ (* Enter the predefined exceptions *)
+ Array.iteri
+ (fun i name ->
+ let id =
+ try List.assoc name Predef.builtin_values
+ with Not_found -> fatal_error "Symtable.init" in
+ let c = slot_for_setglobal id in
+ let cst = Const_block(Obj.object_tag,
+ [Const_base(Const_string (name, None));
+ Const_base(Const_int (-i-1))
+ ])
+ in
+ literal_table := (c, cst) :: !literal_table)
+ Runtimedef.builtin_exceptions;
+ (* Initialize the known C primitives *)
+ if String.length !Clflags.use_prims > 0 then begin
+ let ic = open_in !Clflags.use_prims in
+ try
+ while true do
+ set_prim_table (input_line ic)
+ done
+ with End_of_file -> close_in ic
+ | x -> close_in ic; raise x
+ end else if String.length !Clflags.use_runtime > 0 then begin
+ let primfile = Filename.temp_file "camlprims" "" in
+ try
+ if Sys.command(Printf.sprintf "%s -p > %s"
+ !Clflags.use_runtime primfile) <> 0
+ then raise(Error(Wrong_vm !Clflags.use_runtime));
+ let ic = open_in primfile in
+ try
+ while true do
+ set_prim_table (input_line ic)
+ done
+ with End_of_file -> close_in ic; remove_file primfile
+ | x -> close_in ic; raise x
+ with x -> remove_file primfile; raise x
+ end else begin
+ Array.iter set_prim_table Runtimedef.builtin_primitives
+ end
+
+(* Relocate a block of object bytecode *)
+
+(* Must use the unsafe String.set here because the block may be
+ a "fake" string as returned by Meta.static_alloc. *)
+
+let gen_patch_int str_set buff pos n =
+ str_set buff pos (Char.unsafe_chr n);
+ str_set buff (pos + 1) (Char.unsafe_chr (n asr 8));
+ str_set buff (pos + 2) (Char.unsafe_chr (n asr 16));
+ str_set buff (pos + 3) (Char.unsafe_chr (n asr 24))
+
+let gen_patch_object str_set buff patchlist =
+ List.iter
+ (function
+ (Reloc_literal sc, pos) ->
+ gen_patch_int str_set buff pos (slot_for_literal sc)
+ | (Reloc_getglobal id, pos) ->
+ gen_patch_int str_set buff pos (slot_for_getglobal id)
+ | (Reloc_setglobal id, pos) ->
+ gen_patch_int str_set buff pos (slot_for_setglobal id)
+ | (Reloc_primitive name, pos) ->
+ gen_patch_int str_set buff pos (num_of_prim name))
+ patchlist
+
+let patch_object = gen_patch_object Bytes.unsafe_set
+let ls_patch_object = gen_patch_object LongString.set
+
+(* Translate structured constants *)
+
+let rec transl_const = function
+ Const_base(Const_int i) -> Obj.repr i
+ | Const_base(Const_char c) -> Obj.repr c
+ | Const_base(Const_string (s, _)) -> Obj.repr s
+ | Const_base(Const_float f) -> Obj.repr (float_of_string f)
+ | Const_base(Const_int32 i) -> Obj.repr i
+ | Const_base(Const_int64 i) -> Obj.repr i
+ | Const_base(Const_nativeint i) -> Obj.repr i
+ | Const_pointer i -> Obj.repr i
+ | Const_immstring s -> Obj.repr s
+ | Const_block(tag, fields) ->
+ let block = Obj.new_block tag (List.length fields) in
+ let pos = ref 0 in
+ List.iter
+ (fun c -> Obj.set_field block !pos (transl_const c); incr pos)
+ fields;
+ block
+ | Const_float_array fields ->
+ Obj.repr(Array.of_list(List.map (fun f -> float_of_string f) fields))
+
+(* Build the initial table of globals *)
+
+let initial_global_table () =
+ let glob = Array.make !global_table.num_cnt (Obj.repr 0) in
+ List.iter
+ (fun (slot, cst) -> glob.(slot) <- transl_const cst)
+ !literal_table;
+ literal_table := [];
+ glob
+
+(* Save the table of globals *)
+
+let output_global_map oc =
+ output_value oc !global_table
+
+let data_global_map () =
+ Obj.repr !global_table
+
+(* Functions for toplevel use *)
+
+(* Update the in-core table of globals *)
+
+let update_global_table () =
+ let ng = !global_table.num_cnt in
+ if ng > Array.length(Meta.global_data()) then Meta.realloc_global_data ng;
+ let glob = Meta.global_data() in
+ List.iter
+ (fun (slot, cst) -> glob.(slot) <- transl_const cst)
+ !literal_table;
+ literal_table := []
+
+(* Recover data for toplevel initialization. Data can come either from
+ executable file (normal case) or from linked-in data (-output-obj). *)
+
+type section_reader = {
+ read_string: string -> string;
+ read_struct: string -> Obj.t;
+ close_reader: unit -> unit
+}
+
+let read_sections () =
+ try
+ let sections = Meta.get_section_table () in
+ { read_string =
+ (fun name -> (Obj.magic(List.assoc name sections) : string));
+ read_struct =
+ (fun name -> List.assoc name sections);
+ close_reader =
+ (fun () -> ()) }
+ with Not_found ->
+ let ic = open_in_bin Sys.executable_name in
+ Bytesections.read_toc ic;
+ { read_string = Bytesections.read_section_string ic;
+ read_struct = Bytesections.read_section_struct ic;
+ close_reader = fun () -> close_in ic }
+
+(* Initialize the linker for toplevel use *)
+
+let init_toplevel () =
+ try
+ let sect = read_sections () in
+ (* Locations of globals *)
+ global_table := (Obj.magic (sect.read_struct "SYMB") : Ident.t numtable);
+ (* Primitives *)
+ let prims = sect.read_string "PRIM" in
+ c_prim_table := empty_numtable;
+ let pos = ref 0 in
+ while !pos < String.length prims do
+ let i = String.index_from prims !pos '\000' in
+ set_prim_table (String.sub prims !pos (i - !pos));
+ pos := i + 1
+ done;
+ (* DLL initialization *)
+ let dllpath = try sect.read_string "DLPT" with Not_found -> "" in
+ Dll.init_toplevel dllpath;
+ (* Recover CRC infos for interfaces *)
+ let crcintfs =
+ try
+ (Obj.magic (sect.read_struct "CRCS") : (string * Digest.t option) list)
+ with Not_found -> [] in
+ (* Done *)
+ sect.close_reader();
+ crcintfs
+ with Bytesections.Bad_magic_number | Not_found | Failure _ ->
+ fatal_error "Toplevel bytecode executable is corrupted"
+
+(* Find the value of a global identifier *)
+
+let get_global_position id = slot_for_getglobal id
+
+let get_global_value id =
+ (Meta.global_data()).(slot_for_getglobal id)
+let assign_global_value id v =
+ (Meta.global_data()).(slot_for_getglobal id) <- v
+
+(* Check that all globals referenced in the given patch list
+ have been initialized already *)
+
+let check_global_initialized patchlist =
+ (* First determine the globals we will define *)
+ let defined_globals =
+ List.fold_left
+ (fun accu rel ->
+ match rel with
+ (Reloc_setglobal id, pos) -> id :: accu
+ | _ -> accu)
+ [] patchlist in
+ (* Then check that all referenced, not defined globals have a value *)
+ let check_reference = function
+ (Reloc_getglobal id, pos) ->
+ if not (List.mem id defined_globals)
+ && Obj.is_int (get_global_value id)
+ then raise (Error(Uninitialized_global(Ident.name id)))
+ | _ -> () in
+ List.iter check_reference patchlist
+
+(* Save and restore the current state *)
+
+type global_map = Ident.t numtable
+
+let current_state () = !global_table
+
+let restore_state st = global_table := st
+
+let hide_additions st =
+ if st.num_cnt > !global_table.num_cnt then
+ fatal_error "Symtable.hide_additions";
+ global_table :=
+ { num_cnt = !global_table.num_cnt;
+ num_tbl = st.num_tbl }
+
+(* "Filter" the global map according to some predicate.
+ Used to expunge the global map for the toplevel. *)
+
+let filter_global_map p gmap =
+ let newtbl = ref Tbl.empty in
+ Tbl.iter
+ (fun id num -> if p id then newtbl := Tbl.add id num !newtbl)
+ gmap.num_tbl;
+ {num_cnt = gmap.num_cnt; num_tbl = !newtbl}
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Undefined_global s ->
+ fprintf ppf "Reference to undefined global `%s'" s
+ | Unavailable_primitive s ->
+ fprintf ppf "The external function `%s' is not available" s
+ | Wrong_vm s ->
+ fprintf ppf "Cannot find or execute the runtime system %s" s
+ | Uninitialized_global s ->
+ fprintf ppf "The value of the global `%s' is not yet computed" s
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
+
+let reset () =
+ global_table := empty_numtable;
+ literal_table := [];
+ c_prim_table := empty_numtable
diff --git a/bytecomp/symtable.mli b/bytecomp/symtable.mli
new file mode 100644
index 0000000000..ffc878bf10
--- /dev/null
+++ b/bytecomp/symtable.mli
@@ -0,0 +1,61 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Assign locations and numbers to globals and primitives *)
+
+open Cmo_format
+
+(* Functions for batch linking *)
+
+val init: unit -> unit
+val patch_object: bytes -> (reloc_info * int) list -> unit
+val ls_patch_object: Misc.LongString.t -> (reloc_info * int) list -> unit
+val require_primitive: string -> unit
+val initial_global_table: unit -> Obj.t array
+val output_global_map: out_channel -> unit
+val output_primitive_names: out_channel -> unit
+val output_primitive_table: out_channel -> unit
+val data_global_map: unit -> Obj.t
+val data_primitive_names: unit -> string
+
+(* Functions for the toplevel *)
+
+val init_toplevel: unit -> (string * Digest.t option) list
+val update_global_table: unit -> unit
+val get_global_value: Ident.t -> Obj.t
+val is_global_defined: Ident.t -> bool
+val assign_global_value: Ident.t -> Obj.t -> unit
+val get_global_position: Ident.t -> int
+val check_global_initialized: (reloc_info * int) list -> unit
+
+type global_map
+
+val current_state: unit -> global_map
+val restore_state: global_map -> unit
+val hide_additions: global_map -> unit
+val filter_global_map: (Ident.t -> bool) -> global_map -> global_map
+
+(* Error report *)
+
+type error =
+ Undefined_global of string
+ | Unavailable_primitive of string
+ | Wrong_vm of string
+ | Uninitialized_global of string
+
+exception Error of error
+
+open Format
+
+val report_error: formatter -> error -> unit
+
+val reset: unit -> unit
diff --git a/bytecomp/translclass.ml b/bytecomp/translclass.ml
new file mode 100644
index 0000000000..b294a8d6d9
--- /dev/null
+++ b/bytecomp/translclass.ml
@@ -0,0 +1,851 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Asttypes
+open Types
+open Typedtree
+open Lambda
+open Translobj
+open Translcore
+
+(* XXX Rajouter des evenements... *)
+
+type error = Illegal_class_expr | Tags of label * label
+
+exception Error of Location.t * error
+
+let lfunction params body =
+ if params = [] then body else
+ match body with
+ | Lfunction {kind = Curried; params = params'; body = body'} ->
+ Lfunction {kind = Curried; params = params @ params'; body = body'}
+ | _ ->
+ Lfunction {kind = Curried; params; body}
+
+let lapply func args loc =
+ match func with
+ Lapply(func', args', _) ->
+ Lapply(func', args' @ args, loc)
+ | _ ->
+ Lapply(func, args, loc)
+
+let mkappl (func, args) = Lapply (func, args, no_apply_info);;
+
+let lsequence l1 l2 =
+ if l2 = lambda_unit then l1 else Lsequence(l1, l2)
+
+let lfield v i = Lprim(Pfield i, [Lvar v])
+
+let transl_label l = share (Const_immstring l)
+
+let transl_meth_list lst =
+ if lst = [] then Lconst (Const_pointer 0) else
+ share (Const_block
+ (0, List.map (fun lab -> Const_immstring lab) lst))
+
+let set_inst_var obj id expr =
+ let kind = if Typeopt.maybe_pointer expr then Paddrarray else Pintarray in
+ Lprim(Parraysetu kind, [Lvar obj; Lvar id; transl_exp expr])
+
+let copy_inst_var obj id expr templ offset =
+ let kind = if Typeopt.maybe_pointer expr then Paddrarray else Pintarray in
+ let id' = Ident.create (Ident.name id) in
+ Llet(Strict, id', Lprim (Pidentity, [Lvar id]),
+ Lprim(Parraysetu kind,
+ [Lvar obj; Lvar id';
+ Lprim(Parrayrefu kind, [Lvar templ; Lprim(Paddint,
+ [Lvar id';
+ Lvar offset])])]))
+
+let transl_val tbl create name =
+ mkappl (oo_prim (if create then "new_variable" else "get_variable"),
+ [Lvar tbl; transl_label name])
+
+let transl_vals tbl create strict vals rem =
+ List.fold_right
+ (fun (name, id) rem ->
+ Llet(strict, id, transl_val tbl create name, rem))
+ vals rem
+
+let meths_super tbl meths inh_meths =
+ List.fold_right
+ (fun (nm, id) rem ->
+ try
+ (nm, id,
+ mkappl(oo_prim "get_method", [Lvar tbl; Lvar (Meths.find nm meths)]))
+ :: rem
+ with Not_found -> rem)
+ inh_meths []
+
+let bind_super tbl (vals, meths) cl_init =
+ transl_vals tbl false StrictOpt vals
+ (List.fold_right (fun (nm, id, def) rem -> Llet(StrictOpt, id, def, rem))
+ meths cl_init)
+
+let create_object cl obj init =
+ let obj' = Ident.create "self" in
+ let (inh_init, obj_init, has_init) = init obj' in
+ if obj_init = lambda_unit then
+ (inh_init,
+ mkappl (oo_prim (if has_init then "create_object_and_run_initializers"
+ else"create_object_opt"),
+ [obj; Lvar cl]))
+ else begin
+ (inh_init,
+ Llet(Strict, obj',
+ mkappl (oo_prim "create_object_opt", [obj; Lvar cl]),
+ Lsequence(obj_init,
+ if not has_init then Lvar obj' else
+ mkappl (oo_prim "run_initializers_opt",
+ [obj; Lvar obj'; Lvar cl]))))
+ end
+
+let name_pattern default p =
+ match p.pat_desc with
+ | Tpat_var (id, _) -> id
+ | Tpat_alias(p, id, _) -> id
+ | _ -> Ident.create default
+
+let normalize_cl_path cl path =
+ Env.normalize_path (Some cl.cl_loc) cl.cl_env path
+
+let rec build_object_init cl_table obj params inh_init obj_init cl =
+ match cl.cl_desc with
+ Tcl_ident ( path, _, _) ->
+ let obj_init = Ident.create "obj_init" in
+ let envs, inh_init = inh_init in
+ let env =
+ match envs with None -> []
+ | Some envs -> [Lprim(Pfield (List.length inh_init + 1), [Lvar envs])]
+ in
+ ((envs, (obj_init, normalize_cl_path cl path)
+ ::inh_init),
+ mkappl(Lvar obj_init, env @ [obj]))
+ | Tcl_structure str ->
+ create_object cl_table obj (fun obj ->
+ let (inh_init, obj_init, has_init) =
+ List.fold_right
+ (fun field (inh_init, obj_init, has_init) ->
+ match field.cf_desc with
+ Tcf_inherit (_, cl, _, _, _) ->
+ let (inh_init, obj_init') =
+ build_object_init cl_table (Lvar obj) [] inh_init
+ (fun _ -> lambda_unit) cl
+ in
+ (inh_init, lsequence obj_init' obj_init, true)
+ | Tcf_val (_, _, id, Tcfk_concrete (_, exp), _) ->
+ (inh_init, lsequence (set_inst_var obj id exp) obj_init,
+ has_init)
+ | Tcf_method _ | Tcf_val _ | Tcf_constraint _ | Tcf_attribute _->
+ (inh_init, obj_init, has_init)
+ | Tcf_initializer _ ->
+ (inh_init, obj_init, true)
+ )
+ str.cstr_fields
+ (inh_init, obj_init obj, false)
+ in
+ (inh_init,
+ List.fold_right
+ (fun (id, expr) rem ->
+ lsequence (Lifused (id, set_inst_var obj id expr)) rem)
+ params obj_init,
+ has_init))
+ | Tcl_fun (_, pat, vals, cl, partial) ->
+ let vals = List.map (fun (id, _, e) -> id,e) vals in
+ let (inh_init, obj_init) =
+ build_object_init cl_table obj (vals @ params) inh_init obj_init cl
+ in
+ (inh_init,
+ let build params rem =
+ let param = name_pattern "param" pat in
+ Lfunction {kind = Curried; params = param::params;
+ body = Matching.for_function
+ pat.pat_loc None (Lvar param) [pat, rem] partial}
+ in
+ begin match obj_init with
+ Lfunction {kind = Curried; params; body = rem} -> build params rem
+ | rem -> build [] rem
+ end)
+ | Tcl_apply (cl, oexprs) ->
+ let (inh_init, obj_init) =
+ build_object_init cl_table obj params inh_init obj_init cl
+ in
+ (inh_init, transl_apply obj_init oexprs Location.none)
+ | Tcl_let (rec_flag, defs, vals, cl) ->
+ let vals = List.map (fun (id, _, e) -> id,e) vals in
+ let (inh_init, obj_init) =
+ build_object_init cl_table obj (vals @ params) inh_init obj_init cl
+ in
+ (inh_init, Translcore.transl_let rec_flag defs obj_init)
+ | Tcl_constraint (cl, _, vals, pub_meths, concr_meths) ->
+ build_object_init cl_table obj params inh_init obj_init cl
+
+let rec build_object_init_0 cl_table params cl copy_env subst_env top ids =
+ match cl.cl_desc with
+ Tcl_let (rec_flag, defs, vals, cl) ->
+ let vals = List.map (fun (id, _, e) -> id,e) vals in
+ build_object_init_0 cl_table (vals@params) cl copy_env subst_env top ids
+ | _ ->
+ let self = Ident.create "self" in
+ let env = Ident.create "env" in
+ let obj = if ids = [] then lambda_unit else Lvar self in
+ let envs = if top then None else Some env in
+ let ((_,inh_init), obj_init) =
+ build_object_init cl_table obj params (envs,[]) (copy_env env) cl in
+ let obj_init =
+ if ids = [] then obj_init else lfunction [self] obj_init in
+ (inh_init, lfunction [env] (subst_env env inh_init obj_init))
+
+
+let bind_method tbl lab id cl_init =
+ Llet(Strict, id, mkappl (oo_prim "get_method_label",
+ [Lvar tbl; transl_label lab]),
+ cl_init)
+
+let bind_methods tbl meths vals cl_init =
+ let methl = Meths.fold (fun lab id tl -> (lab,id) :: tl) meths [] in
+ let len = List.length methl and nvals = List.length vals in
+ if len < 2 && nvals = 0 then Meths.fold (bind_method tbl) meths cl_init else
+ if len = 0 && nvals < 2 then transl_vals tbl true Strict vals cl_init else
+ let ids = Ident.create "ids" in
+ let i = ref (len + nvals) in
+ let getter, names =
+ if nvals = 0 then "get_method_labels", [] else
+ "new_methods_variables", [transl_meth_list (List.map fst vals)]
+ in
+ Llet(Strict, ids,
+ mkappl (oo_prim getter,
+ [Lvar tbl; transl_meth_list (List.map fst methl)] @ names),
+ List.fold_right
+ (fun (lab,id) lam -> decr i; Llet(StrictOpt, id, lfield ids !i, lam))
+ (methl @ vals) cl_init)
+
+let output_methods tbl methods lam =
+ match methods with
+ [] -> lam
+ | [lab; code] ->
+ lsequence (mkappl(oo_prim "set_method", [Lvar tbl; lab; code])) lam
+ | _ ->
+ lsequence (mkappl(oo_prim "set_methods",
+ [Lvar tbl; Lprim(Pmakeblock(0,Immutable), methods)]))
+ lam
+
+let rec ignore_cstrs cl =
+ match cl.cl_desc with
+ Tcl_constraint (cl, _, _, _, _) -> ignore_cstrs cl
+ | Tcl_apply (cl, _) -> ignore_cstrs cl
+ | _ -> cl
+
+let rec index a = function
+ [] -> raise Not_found
+ | b :: l ->
+ if b = a then 0 else 1 + index a l
+
+let bind_id_as_val (id, _, _) = ("", id)
+
+let rec build_class_init cla cstr super inh_init cl_init msubst top cl =
+ match cl.cl_desc with
+ Tcl_ident ( path, _, _) ->
+ begin match inh_init with
+ (obj_init, path')::inh_init ->
+ let lpath = transl_path ~loc:cl.cl_loc cl.cl_env path in
+ (inh_init,
+ Llet (Strict, obj_init,
+ mkappl(Lprim(Pfield 1, [lpath]), Lvar cla ::
+ if top then [Lprim(Pfield 3, [lpath])] else []),
+ bind_super cla super cl_init))
+ | _ ->
+ assert false
+ end
+ | Tcl_structure str ->
+ let cl_init = bind_super cla super cl_init in
+ let (inh_init, cl_init, methods, values) =
+ List.fold_right
+ (fun field (inh_init, cl_init, methods, values) ->
+ match field.cf_desc with
+ Tcf_inherit (_, cl, _, vals, meths) ->
+ let cl_init = output_methods cla methods cl_init in
+ let inh_init, cl_init =
+ build_class_init cla false
+ (vals, meths_super cla str.cstr_meths meths)
+ inh_init cl_init msubst top cl in
+ (inh_init, cl_init, [], values)
+ | Tcf_val (name, _, id, _, over) ->
+ let values =
+ if over then values else (name.txt, id) :: values
+ in
+ (inh_init, cl_init, methods, values)
+ | Tcf_method (_, _, Tcfk_virtual _)
+ | Tcf_constraint _
+ ->
+ (inh_init, cl_init, methods, values)
+ | Tcf_method (name, _, Tcfk_concrete (_, exp)) ->
+ let met_code = msubst true (transl_exp exp) in
+ let met_code =
+ if !Clflags.native_code && List.length met_code = 1 then
+ (* Force correct naming of method for profiles *)
+ let met = Ident.create ("method_" ^ name.txt) in
+ [Llet(Strict, met, List.hd met_code, Lvar met)]
+ else met_code
+ in
+ (inh_init, cl_init,
+ Lvar(Meths.find name.txt str.cstr_meths) :: met_code @ methods,
+ values)
+ | Tcf_initializer exp ->
+ (inh_init,
+ Lsequence(mkappl (oo_prim "add_initializer",
+ Lvar cla :: msubst false (transl_exp exp)),
+ cl_init),
+ methods, values)
+ | Tcf_attribute _ ->
+ (inh_init, cl_init, methods, values))
+ str.cstr_fields
+ (inh_init, cl_init, [], [])
+ in
+ let cl_init = output_methods cla methods cl_init in
+ (inh_init, bind_methods cla str.cstr_meths values cl_init)
+ | Tcl_fun (_, pat, vals, cl, _) ->
+ let (inh_init, cl_init) =
+ build_class_init cla cstr super inh_init cl_init msubst top cl
+ in
+ let vals = List.map bind_id_as_val vals in
+ (inh_init, transl_vals cla true StrictOpt vals cl_init)
+ | Tcl_apply (cl, exprs) ->
+ build_class_init cla cstr super inh_init cl_init msubst top cl
+ | Tcl_let (rec_flag, defs, vals, cl) ->
+ let (inh_init, cl_init) =
+ build_class_init cla cstr super inh_init cl_init msubst top cl
+ in
+ let vals = List.map bind_id_as_val vals in
+ (inh_init, transl_vals cla true StrictOpt vals cl_init)
+ | Tcl_constraint (cl, _, vals, meths, concr_meths) ->
+ let virt_meths =
+ List.filter (fun lab -> not (Concr.mem lab concr_meths)) meths in
+ let concr_meths = Concr.elements concr_meths in
+ let narrow_args =
+ [Lvar cla;
+ transl_meth_list vals;
+ transl_meth_list virt_meths;
+ transl_meth_list concr_meths] in
+ let cl = ignore_cstrs cl in
+ begin match cl.cl_desc, inh_init with
+ Tcl_ident (path, _, _), (obj_init, path')::inh_init ->
+ assert (Path.same (normalize_cl_path cl path) path');
+ let lpath = transl_normal_path path' in
+ let inh = Ident.create "inh"
+ and ofs = List.length vals + 1
+ and valids, methids = super in
+ let cl_init =
+ List.fold_left
+ (fun init (nm, id, _) ->
+ Llet(StrictOpt, id, lfield inh (index nm concr_meths + ofs),
+ init))
+ cl_init methids in
+ let cl_init =
+ List.fold_left
+ (fun init (nm, id) ->
+ Llet(StrictOpt, id, lfield inh (index nm vals + 1), init))
+ cl_init valids in
+ (inh_init,
+ Llet (Strict, inh,
+ mkappl(oo_prim "inherits", narrow_args @
+ [lpath; Lconst(Const_pointer(if top then 1 else 0))]),
+ Llet(StrictOpt, obj_init, lfield inh 0, cl_init)))
+ | _ ->
+ let core cl_init =
+ build_class_init cla true super inh_init cl_init msubst top cl
+ in
+ if cstr then core cl_init else
+ let (inh_init, cl_init) =
+ core (Lsequence (mkappl (oo_prim "widen", [Lvar cla]), cl_init))
+ in
+ (inh_init,
+ Lsequence(mkappl (oo_prim "narrow", narrow_args),
+ cl_init))
+ end
+
+let rec build_class_lets cl ids =
+ match cl.cl_desc with
+ Tcl_let (rec_flag, defs, vals, cl') ->
+ let env, wrap = build_class_lets cl' [] in
+ (env, fun x ->
+ let lam = Translcore.transl_let rec_flag defs (wrap x) in
+ (* Check recursion in toplevel let-definitions *)
+ if ids = [] || Translcore.check_recursive_lambda ids lam then lam
+ else raise(Error(cl.cl_loc, Illegal_class_expr)))
+ | _ ->
+ (cl.cl_env, fun x -> x)
+
+let rec get_class_meths cl =
+ match cl.cl_desc with
+ Tcl_structure cl ->
+ Meths.fold (fun _ -> IdentSet.add) cl.cstr_meths IdentSet.empty
+ | Tcl_ident _ -> IdentSet.empty
+ | Tcl_fun (_, _, _, cl, _)
+ | Tcl_let (_, _, _, cl)
+ | Tcl_apply (cl, _)
+ | Tcl_constraint (cl, _, _, _, _) -> get_class_meths cl
+
+(*
+ XXX Il devrait etre peu couteux d'ecrire des classes :
+ class c x y = d e f
+*)
+let rec transl_class_rebind obj_init cl vf =
+ match cl.cl_desc with
+ Tcl_ident (path, _, _) ->
+ if vf = Concrete then begin
+ try if (Env.find_class path cl.cl_env).cty_new = None then raise Exit
+ with Not_found -> raise Exit
+ end;
+ (normalize_cl_path cl path, obj_init)
+ | Tcl_fun (_, pat, _, cl, partial) ->
+ let path, obj_init = transl_class_rebind obj_init cl vf in
+ let build params rem =
+ let param = name_pattern "param" pat in
+ Lfunction {kind = Curried; params = param::params;
+ body = Matching.for_function
+ pat.pat_loc None (Lvar param) [pat, rem] partial}
+ in
+ (path,
+ match obj_init with
+ Lfunction {kind = Curried; params; body} -> build params body
+ | rem -> build [] rem)
+ | Tcl_apply (cl, oexprs) ->
+ let path, obj_init = transl_class_rebind obj_init cl vf in
+ (path, transl_apply obj_init oexprs Location.none)
+ | Tcl_let (rec_flag, defs, vals, cl) ->
+ let path, obj_init = transl_class_rebind obj_init cl vf in
+ (path, Translcore.transl_let rec_flag defs obj_init)
+ | Tcl_structure _ -> raise Exit
+ | Tcl_constraint (cl', _, _, _, _) ->
+ let path, obj_init = transl_class_rebind obj_init cl' vf in
+ let rec check_constraint = function
+ Cty_constr(path', _, _) when Path.same path path' -> ()
+ | Cty_arrow (_, _, cty) -> check_constraint cty
+ | _ -> raise Exit
+ in
+ check_constraint cl.cl_type;
+ (path, obj_init)
+
+let rec transl_class_rebind_0 self obj_init cl vf =
+ match cl.cl_desc with
+ Tcl_let (rec_flag, defs, vals, cl) ->
+ let path, obj_init = transl_class_rebind_0 self obj_init cl vf in
+ (path, Translcore.transl_let rec_flag defs obj_init)
+ | _ ->
+ let path, obj_init = transl_class_rebind obj_init cl vf in
+ (path, lfunction [self] obj_init)
+
+let transl_class_rebind ids cl vf =
+ try
+ let obj_init = Ident.create "obj_init"
+ and self = Ident.create "self" in
+ let obj_init0 = lapply (Lvar obj_init) [Lvar self] no_apply_info in
+ let path, obj_init' = transl_class_rebind_0 self obj_init0 cl vf in
+ if not (Translcore.check_recursive_lambda ids obj_init') then
+ raise(Error(cl.cl_loc, Illegal_class_expr));
+ let id = (obj_init' = lfunction [self] obj_init0) in
+ if id then transl_normal_path path else
+
+ let cla = Ident.create "class"
+ and new_init = Ident.create "new_init"
+ and env_init = Ident.create "env_init"
+ and table = Ident.create "table"
+ and envs = Ident.create "envs" in
+ Llet(
+ Strict, new_init, lfunction [obj_init] obj_init',
+ Llet(
+ Alias, cla, transl_normal_path path,
+ Lprim(Pmakeblock(0, Immutable),
+ [mkappl(Lvar new_init, [lfield cla 0]);
+ lfunction [table]
+ (Llet(Strict, env_init,
+ mkappl(lfield cla 1, [Lvar table]),
+ lfunction [envs]
+ (mkappl(Lvar new_init,
+ [mkappl(Lvar env_init, [Lvar envs])]))));
+ lfield cla 2;
+ lfield cla 3])))
+ with Exit ->
+ lambda_unit
+
+(* Rewrite a closure using builtins. Improves native code size. *)
+
+let rec module_path = function
+ Lvar id ->
+ let s = Ident.name id in s <> "" && s.[0] >= 'A' && s.[0] <= 'Z'
+ | Lprim(Pfield _, [p]) -> module_path p
+ | Lprim(Pgetglobal _, []) -> true
+ | _ -> false
+
+let const_path local = function
+ Lvar id -> not (List.mem id local)
+ | Lconst _ -> true
+ | Lfunction {kind = Curried; body} ->
+ let fv = free_variables body in
+ List.for_all (fun x -> not (IdentSet.mem x fv)) local
+ | p -> module_path p
+
+let rec builtin_meths self env env2 body =
+ let const_path = const_path (env::self) in
+ let conv = function
+ (* Lvar s when List.mem s self -> "_self", [] *)
+ | p when const_path p -> "const", [p]
+ | Lprim(Parrayrefu _, [Lvar s; Lvar n]) when List.mem s self ->
+ "var", [Lvar n]
+ | Lprim(Pfield n, [Lvar e]) when Ident.same e env ->
+ "env", [Lvar env2; Lconst(Const_pointer n)]
+ | Lsend(Self, met, Lvar s, [], _) when List.mem s self ->
+ "meth", [met]
+ | _ -> raise Not_found
+ in
+ match body with
+ | Llet(_, s', Lvar s, body) when List.mem s self ->
+ builtin_meths (s'::self) env env2 body
+ | Lapply(f, [arg], _) when const_path f ->
+ let s, args = conv arg in ("app_"^s, f :: args)
+ | Lapply(f, [arg; p], _) when const_path f && const_path p ->
+ let s, args = conv arg in
+ ("app_"^s^"_const", f :: args @ [p])
+ | Lapply(f, [p; arg], _) when const_path f && const_path p ->
+ let s, args = conv arg in
+ ("app_const_"^s, f :: p :: args)
+ | Lsend(Self, Lvar n, Lvar s, [arg], _) when List.mem s self ->
+ let s, args = conv arg in
+ ("meth_app_"^s, Lvar n :: args)
+ | Lsend(Self, met, Lvar s, [], _) when List.mem s self ->
+ ("get_meth", [met])
+ | Lsend(Public, met, arg, [], _) ->
+ let s, args = conv arg in
+ ("send_"^s, met :: args)
+ | Lsend(Cached, met, arg, [_;_], _) ->
+ let s, args = conv arg in
+ ("send_"^s, met :: args)
+ | Lfunction {kind = Curried; params = [x]; body} ->
+ let rec enter self = function
+ | Lprim(Parraysetu _, [Lvar s; Lvar n; Lvar x'])
+ when Ident.same x x' && List.mem s self ->
+ ("set_var", [Lvar n])
+ | Llet(_, s', Lvar s, body) when List.mem s self ->
+ enter (s'::self) body
+ | _ -> raise Not_found
+ in enter self body
+ | Lfunction _ -> raise Not_found
+ | _ ->
+ let s, args = conv body in ("get_"^s, args)
+
+module M = struct
+ open CamlinternalOO
+ let builtin_meths self env env2 body =
+ let builtin, args = builtin_meths self env env2 body in
+ (* if not arr then [mkappl(oo_prim builtin, args)] else *)
+ let tag = match builtin with
+ "get_const" -> GetConst
+ | "get_var" -> GetVar
+ | "get_env" -> GetEnv
+ | "get_meth" -> GetMeth
+ | "set_var" -> SetVar
+ | "app_const" -> AppConst
+ | "app_var" -> AppVar
+ | "app_env" -> AppEnv
+ | "app_meth" -> AppMeth
+ | "app_const_const" -> AppConstConst
+ | "app_const_var" -> AppConstVar
+ | "app_const_env" -> AppConstEnv
+ | "app_const_meth" -> AppConstMeth
+ | "app_var_const" -> AppVarConst
+ | "app_env_const" -> AppEnvConst
+ | "app_meth_const" -> AppMethConst
+ | "meth_app_const" -> MethAppConst
+ | "meth_app_var" -> MethAppVar
+ | "meth_app_env" -> MethAppEnv
+ | "meth_app_meth" -> MethAppMeth
+ | "send_const" -> SendConst
+ | "send_var" -> SendVar
+ | "send_env" -> SendEnv
+ | "send_meth" -> SendMeth
+ | _ -> assert false
+ in Lconst(Const_pointer(Obj.magic tag)) :: args
+end
+open M
+
+
+(*
+ Traduction d'une classe.
+ Plusieurs cas:
+ * reapplication d'une classe connue -> transl_class_rebind
+ * classe sans dependances locales -> traduction directe
+ * avec dependances locale -> creation d'un arbre de stubs,
+ avec un noeud pour chaque classe locale heritee
+ Une classe est un 4-uplet:
+ (obj_init, class_init, env_init, env)
+ obj_init: fonction de creation d'objet (unit -> obj)
+ class_init: fonction d'heritage (table -> env_init)
+ (une seule par code source)
+ env_init: parametrage par l'environnement local (env -> params -> obj_init)
+ (une par combinaison de class_init herites)
+ env: environnement local
+ Si ids=0 (objet immediat), alors on ne conserve que env_init.
+*)
+
+let prerr_ids msg ids =
+ let names = List.map Ident.unique_toplevel_name ids in
+ prerr_endline (String.concat " " (msg :: names))
+
+let transl_class ids cl_id pub_meths cl vflag =
+ (* First check if it is not only a rebind *)
+ let rebind = transl_class_rebind ids cl vflag in
+ if rebind <> lambda_unit then rebind else
+
+ (* Prepare for heavy environment handling *)
+ let tables = Ident.create (Ident.name cl_id ^ "_tables") in
+ let (top_env, req) = oo_add_class tables in
+ let top = not req in
+ let cl_env, llets = build_class_lets cl ids in
+ let new_ids = if top then [] else Env.diff top_env cl_env in
+ let env2 = Ident.create "env" in
+ let meth_ids = get_class_meths cl in
+ let subst env lam i0 new_ids' =
+ let fv = free_variables lam in
+ (* prerr_ids "cl_id =" [cl_id]; prerr_ids "fv =" (IdentSet.elements fv); *)
+ let fv = List.fold_right IdentSet.remove !new_ids' fv in
+ (* We need to handle method ids specially, as they do not appear
+ in the typing environment (PR#3576, PR#4560) *)
+ (* very hacky: we add and remove free method ids on the fly,
+ depending on the visit order... *)
+ method_ids :=
+ IdentSet.diff (IdentSet.union (free_methods lam) !method_ids) meth_ids;
+ (* prerr_ids "meth_ids =" (IdentSet.elements meth_ids);
+ prerr_ids "method_ids =" (IdentSet.elements !method_ids); *)
+ let new_ids = List.fold_right IdentSet.add new_ids !method_ids in
+ let fv = IdentSet.inter fv new_ids in
+ new_ids' := !new_ids' @ IdentSet.elements fv;
+ (* prerr_ids "new_ids' =" !new_ids'; *)
+ let i = ref (i0-1) in
+ List.fold_left
+ (fun subst id ->
+ incr i; Ident.add id (lfield env !i) subst)
+ Ident.empty !new_ids'
+ in
+ let new_ids_meths = ref [] in
+ let msubst arr = function
+ Lfunction {kind = Curried; params = self :: args; body} ->
+ let env = Ident.create "env" in
+ let body' =
+ if new_ids = [] then body else
+ subst_lambda (subst env body 0 new_ids_meths) body in
+ begin try
+ (* Doesn't seem to improve size for bytecode *)
+ (* if not !Clflags.native_code then raise Not_found; *)
+ if not arr || !Clflags.debug then raise Not_found;
+ builtin_meths [self] env env2 (lfunction args body')
+ with Not_found ->
+ [lfunction (self :: args)
+ (if not (IdentSet.mem env (free_variables body')) then body' else
+ Llet(Alias, env,
+ Lprim(Parrayrefu Paddrarray,
+ [Lvar self; Lvar env2]), body'))]
+ end
+ | _ -> assert false
+ in
+ let new_ids_init = ref [] in
+ let env1 = Ident.create "env" and env1' = Ident.create "env'" in
+ let copy_env envs self =
+ if top then lambda_unit else
+ Lifused(env2, Lprim(Parraysetu Paddrarray,
+ [Lvar self; Lvar env2; Lvar env1']))
+ and subst_env envs l lam =
+ if top then lam else
+ (* must be called only once! *)
+ let lam = subst_lambda (subst env1 lam 1 new_ids_init) lam in
+ Llet(Alias, env1, (if l = [] then Lvar envs else lfield envs 0),
+ Llet(Alias, env1',
+ (if !new_ids_init = [] then Lvar env1 else lfield env1 0),
+ lam))
+ in
+
+ (* Now we start compiling the class *)
+ let cla = Ident.create "class" in
+ let (inh_init, obj_init) =
+ build_object_init_0 cla [] cl copy_env subst_env top ids in
+ let inh_init' = List.rev inh_init in
+ let (inh_init', cl_init) =
+ build_class_init cla true ([],[]) inh_init' obj_init msubst top cl
+ in
+ assert (inh_init' = []);
+ let table = Ident.create "table"
+ and class_init = Ident.create (Ident.name cl_id ^ "_init")
+ and env_init = Ident.create "env_init"
+ and obj_init = Ident.create "obj_init" in
+ let pub_meths =
+ List.sort
+ (fun s s' -> compare (Btype.hash_variant s) (Btype.hash_variant s'))
+ pub_meths in
+ let tags = List.map Btype.hash_variant pub_meths in
+ let rev_map = List.combine tags pub_meths in
+ List.iter2
+ (fun tag name ->
+ let name' = List.assoc tag rev_map in
+ if name' <> name then raise(Error(cl.cl_loc, Tags(name, name'))))
+ tags pub_meths;
+ let ltable table lam =
+ Llet(Strict, table,
+ mkappl (oo_prim "create_table", [transl_meth_list pub_meths]), lam)
+ and ldirect obj_init =
+ Llet(Strict, obj_init, cl_init,
+ Lsequence(mkappl (oo_prim "init_class", [Lvar cla]),
+ mkappl (Lvar obj_init, [lambda_unit])))
+ in
+ (* Simplest case: an object defined at toplevel (ids=[]) *)
+ if top && ids = [] then llets (ltable cla (ldirect obj_init)) else
+
+ let concrete = (vflag = Concrete)
+ and lclass lam =
+ let cl_init = llets (Lfunction{kind = Curried;
+ params = [cla]; body = cl_init}) in
+ Llet(Strict, class_init, cl_init, lam (free_variables cl_init))
+ and lbody fv =
+ if List.for_all (fun id -> not (IdentSet.mem id fv)) ids then
+ mkappl (oo_prim "make_class",[transl_meth_list pub_meths;
+ Lvar class_init])
+ else
+ ltable table (
+ Llet(
+ Strict, env_init, mkappl (Lvar class_init, [Lvar table]),
+ Lsequence(
+ mkappl (oo_prim "init_class", [Lvar table]),
+ Lprim(Pmakeblock(0, Immutable),
+ [mkappl (Lvar env_init, [lambda_unit]);
+ Lvar class_init; Lvar env_init; lambda_unit]))))
+ and lbody_virt lenvs =
+ Lprim(Pmakeblock(0, Immutable),
+ [lambda_unit;
+ Lfunction{kind = Curried; params = [cla]; body = cl_init};
+ lambda_unit;
+ lenvs])
+ in
+ (* Still easy: a class defined at toplevel *)
+ if top && concrete then lclass lbody else
+ if top then llets (lbody_virt lambda_unit) else
+
+ (* Now for the hard stuff: prepare for table cacheing *)
+ let envs = Ident.create "envs"
+ and cached = Ident.create "cached" in
+ let lenvs =
+ if !new_ids_meths = [] && !new_ids_init = [] && inh_init = []
+ then lambda_unit
+ else Lvar envs in
+ let lenv =
+ let menv =
+ if !new_ids_meths = [] then lambda_unit else
+ Lprim(Pmakeblock(0, Immutable),
+ List.map (fun id -> Lvar id) !new_ids_meths) in
+ if !new_ids_init = [] then menv else
+ Lprim(Pmakeblock(0, Immutable),
+ menv :: List.map (fun id -> Lvar id) !new_ids_init)
+ and linh_envs =
+ List.map (fun (_, p) -> Lprim(Pfield 3, [transl_normal_path p]))
+ (List.rev inh_init)
+ in
+ let make_envs lam =
+ Llet(StrictOpt, envs,
+ (if linh_envs = [] then lenv else
+ Lprim(Pmakeblock(0, Immutable), lenv :: linh_envs)),
+ lam)
+ and def_ids cla lam =
+ Llet(StrictOpt, env2,
+ mkappl (oo_prim "new_variable", [Lvar cla; transl_label ""]),
+ lam)
+ in
+ let inh_paths =
+ List.filter
+ (fun (_,path) -> List.mem (Path.head path) new_ids) inh_init in
+ let inh_keys =
+ List.map (fun (_,p) -> Lprim(Pfield 1, [transl_normal_path p])) inh_paths in
+ let lclass lam =
+ Llet(Strict, class_init,
+ Lfunction{kind = Curried; params = [cla];
+ body = def_ids cla cl_init}, lam)
+ and lcache lam =
+ if inh_keys = [] then Llet(Alias, cached, Lvar tables, lam) else
+ Llet(Strict, cached,
+ mkappl (oo_prim "lookup_tables",
+ [Lvar tables; Lprim(Pmakeblock(0, Immutable), inh_keys)]),
+ lam)
+ and lset cached i lam =
+ Lprim(Psetfield(i, true), [Lvar cached; lam])
+ in
+ let ldirect () =
+ ltable cla
+ (Llet(Strict, env_init, def_ids cla cl_init,
+ Lsequence(mkappl (oo_prim "init_class", [Lvar cla]),
+ lset cached 0 (Lvar env_init))))
+ and lclass_virt () =
+ lset cached 0 (Lfunction{kind = Curried;
+ params = [cla]; body = def_ids cla cl_init})
+ in
+ llets (
+ lcache (
+ Lsequence(
+ Lifthenelse(lfield cached 0, lambda_unit,
+ if ids = [] then ldirect () else
+ if not concrete then lclass_virt () else
+ lclass (
+ mkappl (oo_prim "make_class_store",
+ [transl_meth_list pub_meths;
+ Lvar class_init; Lvar cached]))),
+ make_envs (
+ if ids = [] then mkappl (lfield cached 0, [lenvs]) else
+ Lprim(Pmakeblock(0, Immutable),
+ if concrete then
+ [mkappl (lfield cached 0, [lenvs]);
+ lfield cached 1;
+ lfield cached 0;
+ lenvs]
+ else [lambda_unit; lfield cached 0; lambda_unit; lenvs]
+ )))))
+
+(* Wrapper for class compilation *)
+(*
+ let cl_id = ci.ci_id_class in
+(* TODO: cl_id is used somewhere else as typesharp ? *)
+ let _arity = List.length ci.ci_params in
+ let pub_meths = m in
+ let cl = ci.ci_expr in
+ let vflag = vf in
+*)
+
+let transl_class ids id pub_meths cl vf =
+ oo_wrap cl.cl_env false (transl_class ids id pub_meths cl) vf
+
+let () =
+ transl_object := (fun id meths cl -> transl_class [] id meths cl Concrete)
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Illegal_class_expr ->
+ fprintf ppf "This kind of recursive class expression is not allowed"
+ | Tags (lab1, lab2) ->
+ fprintf ppf "Method labels `%s' and `%s' are incompatible.@ %s"
+ lab1 lab2 "Change one of them."
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, err) ->
+ Some (Location.error_of_printer loc report_error err)
+ | _ ->
+ None
+ )
diff --git a/bytecomp/translclass.mli b/bytecomp/translclass.mli
new file mode 100644
index 0000000000..f7858da207
--- /dev/null
+++ b/bytecomp/translclass.mli
@@ -0,0 +1,26 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Typedtree
+open Lambda
+
+val transl_class :
+ Ident.t list -> Ident.t ->
+ string list -> class_expr -> Asttypes.virtual_flag -> lambda;;
+
+type error = Illegal_class_expr | Tags of string * string
+
+exception Error of Location.t * error
+
+open Format
+
+val report_error: formatter -> error -> unit
diff --git a/bytecomp/translcore.ml b/bytecomp/translcore.ml
new file mode 100644
index 0000000000..b75ec99395
--- /dev/null
+++ b/bytecomp/translcore.ml
@@ -0,0 +1,1257 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translation from typed abstract syntax to lambda terms,
+ for the core language *)
+
+open Misc
+open Asttypes
+open Primitive
+open Types
+open Typedtree
+open Typeopt
+open Lambda
+
+type error =
+ Illegal_letrec_pat
+ | Illegal_letrec_expr
+ | Free_super_var
+ | Unknown_builtin_primitive of string
+
+exception Error of Location.t * error
+
+(* Forward declaration -- to be filled in by Translmod.transl_module *)
+let transl_module =
+ ref((fun cc rootpath modl -> assert false) :
+ module_coercion -> Path.t option -> module_expr -> lambda)
+
+let transl_object =
+ ref (fun id s cl -> assert false :
+ Ident.t -> string list -> class_expr -> lambda)
+
+(* Translation of primitives *)
+
+let comparisons_table = create_hashtable 11 [
+ "%equal",
+ (Pccall(Primitive.simple ~name:"caml_equal" ~arity:2 ~alloc:true),
+ Pintcomp Ceq,
+ Pfloatcomp Ceq,
+ Pccall(Primitive.simple ~name:"caml_string_equal" ~arity:2
+ ~alloc:false),
+ Pbintcomp(Pnativeint, Ceq),
+ Pbintcomp(Pint32, Ceq),
+ Pbintcomp(Pint64, Ceq),
+ true);
+ "%notequal",
+ (Pccall(Primitive.simple ~name:"caml_notequal" ~arity:2 ~alloc:true),
+ Pintcomp Cneq,
+ Pfloatcomp Cneq,
+ Pccall(Primitive.simple ~name:"caml_string_notequal" ~arity:2
+ ~alloc:false),
+ Pbintcomp(Pnativeint, Cneq),
+ Pbintcomp(Pint32, Cneq),
+ Pbintcomp(Pint64, Cneq),
+ true);
+ "%lessthan",
+ (Pccall(Primitive.simple ~name:"caml_lessthan" ~arity:2 ~alloc:true),
+ Pintcomp Clt,
+ Pfloatcomp Clt,
+ Pccall(Primitive.simple ~name:"caml_string_lessthan" ~arity:2
+ ~alloc:false),
+ Pbintcomp(Pnativeint, Clt),
+ Pbintcomp(Pint32, Clt),
+ Pbintcomp(Pint64, Clt),
+ false);
+ "%greaterthan",
+ (Pccall(Primitive.simple ~name:"caml_greaterthan" ~arity:2 ~alloc:true),
+ Pintcomp Cgt,
+ Pfloatcomp Cgt,
+ Pccall(Primitive.simple ~name:"caml_string_greaterthan" ~arity:2
+ ~alloc: false),
+ Pbintcomp(Pnativeint, Cgt),
+ Pbintcomp(Pint32, Cgt),
+ Pbintcomp(Pint64, Cgt),
+ false);
+ "%lessequal",
+ (Pccall(Primitive.simple ~name:"caml_lessequal" ~arity:2 ~alloc:true),
+ Pintcomp Cle,
+ Pfloatcomp Cle,
+ Pccall(Primitive.simple ~name:"caml_string_lessequal" ~arity:2
+ ~alloc:false),
+ Pbintcomp(Pnativeint, Cle),
+ Pbintcomp(Pint32, Cle),
+ Pbintcomp(Pint64, Cle),
+ false);
+ "%greaterequal",
+ (Pccall(Primitive.simple ~name:"caml_greaterequal" ~arity:2 ~alloc:true),
+ Pintcomp Cge,
+ Pfloatcomp Cge,
+ Pccall(Primitive.simple ~name:"caml_string_greaterequal" ~arity:2
+ ~alloc:false),
+ Pbintcomp(Pnativeint, Cge),
+ Pbintcomp(Pint32, Cge),
+ Pbintcomp(Pint64, Cge),
+ false);
+ "%compare",
+ (Pccall(Primitive.simple ~name:"caml_compare" ~arity:2 ~alloc:true),
+ Pccall(Primitive.simple ~name:"caml_int_compare" ~arity:2 ~alloc:false),
+ Pccall(Primitive.simple ~name:"caml_float_compare" ~arity:2
+ ~alloc:false),
+ Pccall(Primitive.simple ~name:"caml_string_compare" ~arity:2
+ ~alloc:false),
+ Pccall(Primitive.simple ~name:"caml_nativeint_compare" ~arity:2
+ ~alloc:false),
+ Pccall(Primitive.simple ~name:"caml_int32_compare" ~arity:2
+ ~alloc:false),
+ Pccall(Primitive.simple ~name:"caml_int64_compare" ~arity:2
+ ~alloc:false),
+ false)
+]
+
+let primitives_table = create_hashtable 57 [
+ "%identity", Pidentity;
+ "%ignore", Pignore;
+ "%field0", Pfield 0;
+ "%field1", Pfield 1;
+ "%setfield0", Psetfield(0, true);
+ "%makeblock", Pmakeblock(0, Immutable);
+ "%makemutable", Pmakeblock(0, Mutable);
+ "%raise", Praise Raise_regular;
+ "%reraise", Praise Raise_reraise;
+ "%raise_notrace", Praise Raise_notrace;
+ "%sequand", Psequand;
+ "%sequor", Psequor;
+ "%boolnot", Pnot;
+ "%big_endian", Pctconst Big_endian;
+ "%word_size", Pctconst Word_size;
+ "%int_size", Pctconst Int_size;
+ "%max_wosize", Pctconst Max_wosize;
+ "%ostype_unix", Pctconst Ostype_unix;
+ "%ostype_win32", Pctconst Ostype_win32;
+ "%ostype_cygwin", Pctconst Ostype_cygwin;
+ "%negint", Pnegint;
+ "%succint", Poffsetint 1;
+ "%predint", Poffsetint(-1);
+ "%addint", Paddint;
+ "%subint", Psubint;
+ "%mulint", Pmulint;
+ "%divint", Pdivint;
+ "%modint", Pmodint;
+ "%andint", Pandint;
+ "%orint", Porint;
+ "%xorint", Pxorint;
+ "%lslint", Plslint;
+ "%lsrint", Plsrint;
+ "%asrint", Pasrint;
+ "%eq", Pintcomp Ceq;
+ "%noteq", Pintcomp Cneq;
+ "%ltint", Pintcomp Clt;
+ "%leint", Pintcomp Cle;
+ "%gtint", Pintcomp Cgt;
+ "%geint", Pintcomp Cge;
+ "%incr", Poffsetref(1);
+ "%decr", Poffsetref(-1);
+ "%intoffloat", Pintoffloat;
+ "%floatofint", Pfloatofint;
+ "%negfloat", Pnegfloat;
+ "%absfloat", Pabsfloat;
+ "%addfloat", Paddfloat;
+ "%subfloat", Psubfloat;
+ "%mulfloat", Pmulfloat;
+ "%divfloat", Pdivfloat;
+ "%eqfloat", Pfloatcomp Ceq;
+ "%noteqfloat", Pfloatcomp Cneq;
+ "%ltfloat", Pfloatcomp Clt;
+ "%lefloat", Pfloatcomp Cle;
+ "%gtfloat", Pfloatcomp Cgt;
+ "%gefloat", Pfloatcomp Cge;
+ "%string_length", Pstringlength;
+ "%string_safe_get", Pstringrefs;
+ "%string_safe_set", Pstringsets;
+ "%string_unsafe_get", Pstringrefu;
+ "%string_unsafe_set", Pstringsetu;
+ "%array_length", Parraylength Pgenarray;
+ "%array_safe_get", Parrayrefs Pgenarray;
+ "%array_safe_set", Parraysets Pgenarray;
+ "%array_unsafe_get", Parrayrefu Pgenarray;
+ "%array_unsafe_set", Parraysetu Pgenarray;
+ "%obj_size", Parraylength Pgenarray;
+ "%obj_field", Parrayrefu Pgenarray;
+ "%obj_set_field", Parraysetu Pgenarray;
+ "%obj_is_int", Pisint;
+ "%lazy_force", Plazyforce;
+ "%nativeint_of_int", Pbintofint Pnativeint;
+ "%nativeint_to_int", Pintofbint Pnativeint;
+ "%nativeint_neg", Pnegbint Pnativeint;
+ "%nativeint_add", Paddbint Pnativeint;
+ "%nativeint_sub", Psubbint Pnativeint;
+ "%nativeint_mul", Pmulbint Pnativeint;
+ "%nativeint_div", Pdivbint Pnativeint;
+ "%nativeint_mod", Pmodbint Pnativeint;
+ "%nativeint_and", Pandbint Pnativeint;
+ "%nativeint_or", Porbint Pnativeint;
+ "%nativeint_xor", Pxorbint Pnativeint;
+ "%nativeint_lsl", Plslbint Pnativeint;
+ "%nativeint_lsr", Plsrbint Pnativeint;
+ "%nativeint_asr", Pasrbint Pnativeint;
+ "%int32_of_int", Pbintofint Pint32;
+ "%int32_to_int", Pintofbint Pint32;
+ "%int32_neg", Pnegbint Pint32;
+ "%int32_add", Paddbint Pint32;
+ "%int32_sub", Psubbint Pint32;
+ "%int32_mul", Pmulbint Pint32;
+ "%int32_div", Pdivbint Pint32;
+ "%int32_mod", Pmodbint Pint32;
+ "%int32_and", Pandbint Pint32;
+ "%int32_or", Porbint Pint32;
+ "%int32_xor", Pxorbint Pint32;
+ "%int32_lsl", Plslbint Pint32;
+ "%int32_lsr", Plsrbint Pint32;
+ "%int32_asr", Pasrbint Pint32;
+ "%int64_of_int", Pbintofint Pint64;
+ "%int64_to_int", Pintofbint Pint64;
+ "%int64_neg", Pnegbint Pint64;
+ "%int64_add", Paddbint Pint64;
+ "%int64_sub", Psubbint Pint64;
+ "%int64_mul", Pmulbint Pint64;
+ "%int64_div", Pdivbint Pint64;
+ "%int64_mod", Pmodbint Pint64;
+ "%int64_and", Pandbint Pint64;
+ "%int64_or", Porbint Pint64;
+ "%int64_xor", Pxorbint Pint64;
+ "%int64_lsl", Plslbint Pint64;
+ "%int64_lsr", Plsrbint Pint64;
+ "%int64_asr", Pasrbint Pint64;
+ "%nativeint_of_int32", Pcvtbint(Pint32, Pnativeint);
+ "%nativeint_to_int32", Pcvtbint(Pnativeint, Pint32);
+ "%int64_of_int32", Pcvtbint(Pint32, Pint64);
+ "%int64_to_int32", Pcvtbint(Pint64, Pint32);
+ "%int64_of_nativeint", Pcvtbint(Pnativeint, Pint64);
+ "%int64_to_nativeint", Pcvtbint(Pint64, Pnativeint);
+ "%caml_ba_ref_1",
+ Pbigarrayref(false, 1, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_ref_2",
+ Pbigarrayref(false, 2, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_ref_3",
+ Pbigarrayref(false, 3, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_set_1",
+ Pbigarrayset(false, 1, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_set_2",
+ Pbigarrayset(false, 2, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_set_3",
+ Pbigarrayset(false, 3, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_unsafe_ref_1",
+ Pbigarrayref(true, 1, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_unsafe_ref_2",
+ Pbigarrayref(true, 2, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_unsafe_ref_3",
+ Pbigarrayref(true, 3, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_unsafe_set_1",
+ Pbigarrayset(true, 1, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_unsafe_set_2",
+ Pbigarrayset(true, 2, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_unsafe_set_3",
+ Pbigarrayset(true, 3, Pbigarray_unknown, Pbigarray_unknown_layout);
+ "%caml_ba_dim_1", Pbigarraydim(1);
+ "%caml_ba_dim_2", Pbigarraydim(2);
+ "%caml_ba_dim_3", Pbigarraydim(3);
+ "%caml_string_get16", Pstring_load_16(false);
+ "%caml_string_get16u", Pstring_load_16(true);
+ "%caml_string_get32", Pstring_load_32(false);
+ "%caml_string_get32u", Pstring_load_32(true);
+ "%caml_string_get64", Pstring_load_64(false);
+ "%caml_string_get64u", Pstring_load_64(true);
+ "%caml_string_set16", Pstring_set_16(false);
+ "%caml_string_set16u", Pstring_set_16(true);
+ "%caml_string_set32", Pstring_set_32(false);
+ "%caml_string_set32u", Pstring_set_32(true);
+ "%caml_string_set64", Pstring_set_64(false);
+ "%caml_string_set64u", Pstring_set_64(true);
+ "%caml_bigstring_get16", Pbigstring_load_16(false);
+ "%caml_bigstring_get16u", Pbigstring_load_16(true);
+ "%caml_bigstring_get32", Pbigstring_load_32(false);
+ "%caml_bigstring_get32u", Pbigstring_load_32(true);
+ "%caml_bigstring_get64", Pbigstring_load_64(false);
+ "%caml_bigstring_get64u", Pbigstring_load_64(true);
+ "%caml_bigstring_set16", Pbigstring_set_16(false);
+ "%caml_bigstring_set16u", Pbigstring_set_16(true);
+ "%caml_bigstring_set32", Pbigstring_set_32(false);
+ "%caml_bigstring_set32u", Pbigstring_set_32(true);
+ "%caml_bigstring_set64", Pbigstring_set_64(false);
+ "%caml_bigstring_set64u", Pbigstring_set_64(true);
+ "%bswap16", Pbswap16;
+ "%bswap_int32", Pbbswap(Pint32);
+ "%bswap_int64", Pbbswap(Pint64);
+ "%bswap_native", Pbbswap(Pnativeint);
+ "%int_as_pointer", Pint_as_pointer;
+]
+
+let index_primitives_table =
+ let make_ba_ref n =
+ "%caml_ba_opt_ref_"^(string_of_int n),
+ fun () -> Pbigarrayref(!Clflags.fast, n, Pbigarray_unknown,
+ Pbigarray_unknown_layout)
+ and make_ba_set n =
+ "%caml_ba_opt_set_"^(string_of_int n),
+ fun () -> Pbigarrayset(!Clflags.fast, n, Pbigarray_unknown,
+ Pbigarray_unknown_layout)
+ in
+ create_hashtable 10 [
+ "%array_opt_get", ( fun () -> if !Clflags.fast then Parrayrefu Pgenarray
+ else Parrayrefs Pgenarray );
+ "%array_opt_set", ( fun () -> if !Clflags.fast then Parraysetu Pgenarray
+ else Parraysets Pgenarray );
+ "%string_opt_get", ( fun () -> if !Clflags.fast then Pstringrefu
+ else Pstringrefs );
+ "%string_opt_set", ( fun () -> if !Clflags.fast then Pstringsetu
+ else Pstringsets );
+ make_ba_ref 1; make_ba_set 1;
+ make_ba_ref 2; make_ba_set 2;
+ make_ba_ref 3; make_ba_set 3;
+]
+
+let prim_makearray =
+ Primitive.simple ~name:"caml_make_vect" ~arity:2 ~alloc:true
+
+let prim_obj_dup =
+ Primitive.simple ~name:"caml_obj_dup" ~arity:1 ~alloc:true
+
+let find_primitive loc prim_name =
+ match prim_name with
+ "%revapply" -> Prevapply loc
+ | "%apply" -> Pdirapply loc
+ | "%loc_LOC" -> Ploc Loc_LOC
+ | "%loc_FILE" -> Ploc Loc_FILE
+ | "%loc_LINE" -> Ploc Loc_LINE
+ | "%loc_POS" -> Ploc Loc_POS
+ | "%loc_MODULE" -> Ploc Loc_MODULE
+ | name ->
+ try Hashtbl.find index_primitives_table name @@ () with
+ | Not_found -> Hashtbl.find primitives_table name
+
+let specialize_comparison table env ty =
+ let (gencomp, intcomp, floatcomp, stringcomp,
+ nativeintcomp, int32comp, int64comp, _) = table in
+ match () with
+ | () when is_base_type env ty Predef.path_int
+ || is_base_type env ty Predef.path_char
+ || not (maybe_pointer_type env ty) -> intcomp
+ | () when is_base_type env ty Predef.path_float -> floatcomp
+ | () when is_base_type env ty Predef.path_string -> stringcomp
+ | () when is_base_type env ty Predef.path_nativeint -> nativeintcomp
+ | () when is_base_type env ty Predef.path_int32 -> int32comp
+ | () when is_base_type env ty Predef.path_int64 -> int64comp
+ | () -> gencomp
+
+(* Specialize a primitive from available type information,
+ raise Not_found if primitive is unknown *)
+
+let specialize_primitive loc p env ty ~has_constant_constructor =
+ try
+ let table = Hashtbl.find comparisons_table p.prim_name in
+ let (gencomp, intcomp, _, _, _, _, _, simplify_constant_constructor) =
+ table in
+ if has_constant_constructor && simplify_constant_constructor then
+ intcomp
+ else
+ match is_function_type env ty with
+ | Some (lhs,rhs) -> specialize_comparison table env lhs
+ | None -> gencomp
+ with Not_found ->
+ let p = find_primitive loc p.prim_name in
+ (* Try strength reduction based on the type of the argument *)
+ let params = match is_function_type env ty with
+ | None -> []
+ | Some (p1, rhs) -> match is_function_type env rhs with
+ | None -> [p1]
+ | Some (p2, _) -> [p1;p2]
+ in
+ match (p, params) with
+ (Psetfield(n, _), [p1; p2]) -> Psetfield(n, maybe_pointer_type env p2)
+ | (Parraylength Pgenarray, [p]) -> Parraylength(array_type_kind env p)
+ | (Parrayrefu Pgenarray, p1 :: _) -> Parrayrefu(array_type_kind env p1)
+ | (Parraysetu Pgenarray, p1 :: _) -> Parraysetu(array_type_kind env p1)
+ | (Parrayrefs Pgenarray, p1 :: _) -> Parrayrefs(array_type_kind env p1)
+ | (Parraysets Pgenarray, p1 :: _) -> Parraysets(array_type_kind env p1)
+ | (Pbigarrayref(unsafe, n, Pbigarray_unknown, Pbigarray_unknown_layout),
+ p1 :: _) ->
+ let (k, l) = bigarray_type_kind_and_layout env p1 in
+ Pbigarrayref(unsafe, n, k, l)
+ | (Pbigarrayset(unsafe, n, Pbigarray_unknown, Pbigarray_unknown_layout),
+ p1 :: _) ->
+ let (k, l) = bigarray_type_kind_and_layout env p1 in
+ Pbigarrayset(unsafe, n, k, l)
+ | _ -> p
+
+(* Eta-expand a primitive *)
+
+let transl_primitive loc p env ty =
+ let prim =
+ try specialize_primitive loc p env ty ~has_constant_constructor:false
+ with Not_found -> Pccall p
+ in
+ match prim with
+ | Plazyforce ->
+ let parm = Ident.create "prim" in
+ Lfunction{kind = Curried; params = [parm];
+ body = Matching.inline_lazy_force (Lvar parm) Location.none }
+ | Ploc kind ->
+ let lam = lam_of_loc kind loc in
+ begin match p.prim_arity with
+ | 0 -> lam
+ | 1 -> (* TODO: we should issue a warning ? *)
+ let param = Ident.create "prim" in
+ Lfunction{kind = Curried; params = [param];
+ body = Lprim(Pmakeblock(0, Immutable), [lam; Lvar param])}
+ | _ -> assert false
+ end
+ | _ ->
+ let rec make_params n =
+ if n <= 0 then [] else Ident.create "prim" :: make_params (n-1) in
+ let params = make_params p.prim_arity in
+ Lfunction{ kind = Curried; params;
+ body = Lprim(prim, List.map (fun id -> Lvar id) params) }
+
+let transl_primitive_application loc prim env ty args =
+ let prim_name = prim.prim_name in
+ try
+ let has_constant_constructor = match args with
+ [_; {exp_desc = Texp_construct(_, {cstr_tag = Cstr_constant _}, _)}]
+ | [{exp_desc = Texp_construct(_, {cstr_tag = Cstr_constant _}, _)}; _]
+ | [_; {exp_desc = Texp_variant(_, None)}]
+ | [{exp_desc = Texp_variant(_, None)}; _] -> true
+ | _ -> false
+ in
+ specialize_primitive loc prim env ty ~has_constant_constructor
+ with Not_found ->
+ if String.length prim_name > 0 && prim_name.[0] = '%' then
+ raise(Error(loc, Unknown_builtin_primitive prim_name));
+ Pccall prim
+
+
+(* To check the well-formedness of r.h.s. of "let rec" definitions *)
+
+let check_recursive_lambda idlist lam =
+ let rec check_top idlist = function
+ | Lvar v -> not (List.mem v idlist)
+ | Llet (_, _, _, _) as lam when check_recursive_recordwith idlist lam ->
+ true
+ | Llet(str, id, arg, body) ->
+ check idlist arg && check_top (add_let id arg idlist) body
+ | Lletrec(bindings, body) ->
+ let idlist' = add_letrec bindings idlist in
+ List.for_all (fun (id, arg) -> check idlist' arg) bindings &&
+ check_top idlist' body
+ | Lprim (Pmakearray (Pgenarray), args) -> false
+ | Lsequence (lam1, lam2) -> check idlist lam1 && check_top idlist lam2
+ | Levent (lam, _) -> check_top idlist lam
+ | lam -> check idlist lam
+
+ and check idlist = function
+ | Lvar _ -> true
+ | Lfunction{kind; params; body} -> true
+ | Llet (_, _, _, _) as lam when check_recursive_recordwith idlist lam ->
+ true
+ | Llet(str, id, arg, body) ->
+ check idlist arg && check (add_let id arg idlist) body
+ | Lletrec(bindings, body) ->
+ let idlist' = add_letrec bindings idlist in
+ List.for_all (fun (id, arg) -> check idlist' arg) bindings &&
+ check idlist' body
+ | Lprim(Pmakeblock(tag, mut), args) ->
+ List.for_all (check idlist) args
+ | Lprim(Pmakearray(_), args) ->
+ List.for_all (check idlist) args
+ | Lsequence (lam1, lam2) -> check idlist lam1 && check idlist lam2
+ | Levent (lam, _) -> check idlist lam
+ | lam ->
+ let fv = free_variables lam in
+ not (List.exists (fun id -> IdentSet.mem id fv) idlist)
+
+ and add_let id arg idlist =
+ let fv = free_variables arg in
+ if List.exists (fun id -> IdentSet.mem id fv) idlist
+ then id :: idlist
+ else idlist
+
+ and add_letrec bindings idlist =
+ List.fold_right (fun (id, arg) idl -> add_let id arg idl)
+ bindings idlist
+
+ (* reverse-engineering the code generated by transl_record case 2 *)
+ (* If you change this, you probably need to change Bytegen.size_of_lambda. *)
+ and check_recursive_recordwith idlist = function
+ | Llet (Strict, id1, Lprim (Pduprecord _, [e1]), body) ->
+ check_top idlist e1
+ && check_recordwith_updates idlist id1 body
+ | _ -> false
+
+ and check_recordwith_updates idlist id1 = function
+ | Lsequence (Lprim ((Psetfield _ | Psetfloatfield _), [Lvar id2; e1]), cont)
+ -> id2 = id1 && check idlist e1
+ && check_recordwith_updates idlist id1 cont
+ | Lvar id2 -> id2 = id1
+ | _ -> false
+
+ in check_top idlist lam
+
+(* To propagate structured constants *)
+
+exception Not_constant
+
+let extract_constant = function
+ Lconst sc -> sc
+ | _ -> raise Not_constant
+
+let extract_float = function
+ Const_base(Const_float f) -> f
+ | _ -> fatal_error "Translcore.extract_float"
+
+(* To find reasonable names for let-bound and lambda-bound idents *)
+
+let rec name_pattern default = function
+ [] -> Ident.create default
+ | {c_lhs=p; _} :: rem ->
+ match p.pat_desc with
+ Tpat_var (id, _) -> id
+ | Tpat_alias(p, id, _) -> id
+ | _ -> name_pattern default rem
+
+(* Push the default values under the functional abstractions *)
+(* Also push bindings of module patterns, since this sound *)
+
+type binding =
+ | Bind_value of value_binding list
+ | Bind_module of Ident.t * string loc * module_expr
+
+let rec push_defaults loc bindings cases partial =
+ match cases with
+ [{c_lhs=pat; c_guard=None;
+ c_rhs={exp_desc = Texp_function(l, pl,partial)} as exp}] ->
+ let pl = push_defaults exp.exp_loc bindings pl partial in
+ [{c_lhs=pat; c_guard=None;
+ c_rhs={exp with exp_desc = Texp_function(l, pl, partial)}}]
+ | [{c_lhs=pat; c_guard=None;
+ c_rhs={exp_attributes=[{txt="#default"},_];
+ exp_desc = Texp_let
+ (Nonrecursive, binds, ({exp_desc = Texp_function _} as e2))}}] ->
+ push_defaults loc (Bind_value binds :: bindings)
+ [{c_lhs=pat;c_guard=None;c_rhs=e2}]
+ partial
+ | [{c_lhs=pat; c_guard=None;
+ c_rhs={exp_attributes=[{txt="#modulepat"},_];
+ exp_desc = Texp_letmodule
+ (id, name, mexpr, ({exp_desc = Texp_function _} as e2))}}] ->
+ push_defaults loc (Bind_module (id, name, mexpr) :: bindings)
+ [{c_lhs=pat;c_guard=None;c_rhs=e2}]
+ partial
+ | [case] ->
+ let exp =
+ List.fold_left
+ (fun exp binds ->
+ {exp with exp_desc =
+ match binds with
+ | Bind_value binds -> Texp_let(Nonrecursive, binds, exp)
+ | Bind_module (id, name, mexpr) ->
+ Texp_letmodule (id, name, mexpr, exp)})
+ case.c_rhs bindings
+ in
+ [{case with c_rhs=exp}]
+ | {c_lhs=pat; c_rhs=exp; c_guard=_} :: _ when bindings <> [] ->
+ let param = name_pattern "param" cases in
+ let name = Ident.name param in
+ let exp =
+ { exp with exp_loc = loc; exp_desc =
+ Texp_match
+ ({exp with exp_type = pat.pat_type; exp_desc =
+ Texp_ident (Path.Pident param, mknoloc (Longident.Lident name),
+ {val_type = pat.pat_type; val_kind = Val_reg;
+ val_attributes = [];
+ Types.val_loc = Location.none;
+ })},
+ cases, [], partial) }
+ in
+ push_defaults loc bindings
+ [{c_lhs={pat with pat_desc = Tpat_var (param, mknoloc name)};
+ c_guard=None; c_rhs=exp}]
+ Total
+ | _ ->
+ cases
+
+(* Insertion of debugging events *)
+
+let event_before exp lam = match lam with
+| Lstaticraise (_,_) -> lam
+| _ ->
+ if !Clflags.debug
+ then Levent(lam, {lev_loc = exp.exp_loc;
+ lev_kind = Lev_before;
+ lev_repr = None;
+ lev_env = Env.summary exp.exp_env})
+ else lam
+
+let event_after exp lam =
+ if !Clflags.debug
+ then Levent(lam, {lev_loc = exp.exp_loc;
+ lev_kind = Lev_after exp.exp_type;
+ lev_repr = None;
+ lev_env = Env.summary exp.exp_env})
+ else lam
+
+let event_function exp lam =
+ if !Clflags.debug then
+ let repr = Some (ref 0) in
+ let (info, body) = lam repr in
+ (info,
+ Levent(body, {lev_loc = exp.exp_loc;
+ lev_kind = Lev_function;
+ lev_repr = repr;
+ lev_env = Env.summary exp.exp_env}))
+ else
+ lam None
+
+let primitive_is_ccall = function
+ (* Determine if a primitive is a Pccall or will be turned later into
+ a C function call that may raise an exception *)
+ | Pccall _ | Pstringrefs | Pstringsets | Parrayrefs _ | Parraysets _ |
+ Pbigarrayref _ | Pbigarrayset _ | Pduprecord _ -> true
+ | _ -> false
+
+(* Assertions *)
+
+let assert_failed exp =
+ let (fname, line, char) =
+ Location.get_pos_info exp.exp_loc.Location.loc_start in
+ Lprim(Praise Raise_regular, [event_after exp
+ (Lprim(Pmakeblock(0, Immutable),
+ [transl_normal_path Predef.path_assert_failure;
+ Lconst(Const_block(0,
+ [Const_base(Const_string (fname, None));
+ Const_base(Const_int line);
+ Const_base(Const_int char)]))]))])
+;;
+
+let rec cut n l =
+ if n = 0 then ([],l) else
+ match l with [] -> failwith "Translcore.cut"
+ | a::l -> let (l1,l2) = cut (n-1) l in (a::l1,l2)
+
+(* Translation of expressions *)
+
+let try_ids = Hashtbl.create 8
+
+let has_tailcall_attribute e =
+ List.exists (fun ({txt},_) -> txt="tailcall") e.exp_attributes
+
+let rec transl_exp e =
+ let eval_once =
+ (* Whether classes for immediate objects must be cached *)
+ match e.exp_desc with
+ Texp_function _ | Texp_for _ | Texp_while _ -> false
+ | _ -> true
+ in
+ if eval_once then transl_exp0 e else
+ Translobj.oo_wrap e.exp_env true transl_exp0 e
+
+and transl_exp0 e =
+ match e.exp_desc with
+ Texp_ident(path, _, {val_kind = Val_prim p}) ->
+ let public_send = p.prim_name = "%send" in
+ if public_send || p.prim_name = "%sendself" then
+ let kind = if public_send then Public else Self in
+ let obj = Ident.create "obj" and meth = Ident.create "meth" in
+ Lfunction{kind = Curried; params = [obj; meth];
+ body = Lsend(kind, Lvar meth, Lvar obj, [], e.exp_loc)}
+ else if p.prim_name = "%sendcache" then
+ let obj = Ident.create "obj" and meth = Ident.create "meth" in
+ let cache = Ident.create "cache" and pos = Ident.create "pos" in
+ Lfunction{kind = Curried; params = [obj; meth; cache; pos];
+ body = Lsend(Cached, Lvar meth, Lvar obj,
+ [Lvar cache; Lvar pos], e.exp_loc)}
+ else
+ transl_primitive e.exp_loc p e.exp_env e.exp_type
+ | Texp_ident(path, _, {val_kind = Val_anc _}) ->
+ raise(Error(e.exp_loc, Free_super_var))
+ | Texp_ident(path, _, {val_kind = Val_reg | Val_self _}) ->
+ transl_path ~loc:e.exp_loc e.exp_env path
+ | Texp_ident _ -> fatal_error "Translcore.transl_exp: bad Texp_ident"
+ | Texp_constant cst ->
+ Lconst(Const_base cst)
+ | Texp_let(rec_flag, pat_expr_list, body) ->
+ transl_let rec_flag pat_expr_list (event_before body (transl_exp body))
+ | Texp_function (_, pat_expr_list, partial) ->
+ let ((kind, params), body) =
+ event_function e
+ (function repr ->
+ let pl = push_defaults e.exp_loc [] pat_expr_list partial in
+ transl_function e.exp_loc !Clflags.native_code repr partial pl)
+ in
+ Lfunction{kind; params; body}
+ | Texp_apply({ exp_desc = Texp_ident(path, _, {val_kind = Val_prim p});
+ exp_type = prim_type } as funct, oargs)
+ when List.length oargs >= p.prim_arity
+ && List.for_all (fun (_, arg,_) -> arg <> None) oargs ->
+ let args, args' = cut p.prim_arity oargs in
+ let wrap f =
+ if args' = []
+ then event_after e f
+ else
+ let should_be_tailcall = has_tailcall_attribute funct in
+ event_after e (transl_apply ~should_be_tailcall f args' e.exp_loc)
+ in
+ let wrap0 f =
+ if args' = [] then f else wrap f in
+ let args =
+ List.map (function _, Some x, _ -> x | _ -> assert false) args in
+ let argl = transl_list args in
+ let public_send = p.prim_name = "%send"
+ || not !Clflags.native_code && p.prim_name = "%sendcache"in
+ if public_send || p.prim_name = "%sendself" then
+ let kind = if public_send then Public else Self in
+ let obj = List.hd argl in
+ wrap (Lsend (kind, List.nth argl 1, obj, [], e.exp_loc))
+ else if p.prim_name = "%sendcache" then
+ match argl with [obj; meth; cache; pos] ->
+ wrap (Lsend(Cached, meth, obj, [cache; pos], e.exp_loc))
+ | _ -> assert false
+ else begin
+ let prim = transl_primitive_application
+ e.exp_loc p e.exp_env prim_type args in
+ match (prim, args) with
+ (Praise k, [arg1]) ->
+ let targ = List.hd argl in
+ let k =
+ match k, targ with
+ | Raise_regular, Lvar id
+ when Hashtbl.mem try_ids id ->
+ Raise_reraise
+ | _ ->
+ k
+ in
+ wrap0 (Lprim(Praise k, [event_after arg1 targ]))
+ | (Ploc kind, []) ->
+ lam_of_loc kind e.exp_loc
+ | (Ploc kind, [arg1]) ->
+ let lam = lam_of_loc kind arg1.exp_loc in
+ Lprim(Pmakeblock(0, Immutable), lam :: argl)
+ | (Ploc _, _) -> assert false
+ | (_, _) ->
+ begin match (prim, argl) with
+ | (Plazyforce, [a]) ->
+ wrap (Matching.inline_lazy_force a e.exp_loc)
+ | (Plazyforce, _) -> assert false
+ |_ -> let p = Lprim(prim, argl) in
+ if primitive_is_ccall prim then wrap p else wrap0 p
+ end
+ end
+ | Texp_apply(funct, oargs) ->
+ let should_be_tailcall = has_tailcall_attribute funct in
+ event_after e (transl_apply ~should_be_tailcall (transl_exp funct) oargs
+ e.exp_loc)
+ | Texp_match(arg, pat_expr_list, exn_pat_expr_list, partial) ->
+ transl_match e arg pat_expr_list exn_pat_expr_list partial
+ | Texp_try(body, pat_expr_list) ->
+ let id = name_pattern "exn" pat_expr_list in
+ Ltrywith(transl_exp body, id,
+ Matching.for_trywith (Lvar id) (transl_cases_try pat_expr_list))
+ | Texp_tuple el ->
+ let ll = transl_list el in
+ begin try
+ Lconst(Const_block(0, List.map extract_constant ll))
+ with Not_constant ->
+ Lprim(Pmakeblock(0, Immutable), ll)
+ end
+ | Texp_construct(_, cstr, args) ->
+ let ll = transl_list args in
+ if cstr.cstr_inlined <> None then begin match ll with
+ | [x] -> x
+ | _ -> assert false
+ end else begin match cstr.cstr_tag with
+ Cstr_constant n ->
+ Lconst(Const_pointer n)
+ | Cstr_block n ->
+ begin try
+ Lconst(Const_block(n, List.map extract_constant ll))
+ with Not_constant ->
+ Lprim(Pmakeblock(n, Immutable), ll)
+ end
+ | Cstr_extension(path, is_const) ->
+ if is_const then
+ transl_path e.exp_env path
+ else
+ Lprim(Pmakeblock(0, Immutable),
+ transl_path e.exp_env path :: ll)
+ end
+ | Texp_variant(l, arg) ->
+ let tag = Btype.hash_variant l in
+ begin match arg with
+ None -> Lconst(Const_pointer tag)
+ | Some arg ->
+ let lam = transl_exp arg in
+ try
+ Lconst(Const_block(0, [Const_base(Const_int tag);
+ extract_constant lam]))
+ with Not_constant ->
+ Lprim(Pmakeblock(0, Immutable),
+ [Lconst(Const_base(Const_int tag)); lam])
+ end
+ | Texp_record ((_, lbl1, _) :: _ as lbl_expr_list, opt_init_expr) ->
+ transl_record e.exp_env lbl1.lbl_all lbl1.lbl_repres lbl_expr_list
+ opt_init_expr
+ | Texp_record ([], _) ->
+ fatal_error "Translcore.transl_exp: bad Texp_record"
+ | Texp_field(arg, _, lbl) ->
+ let access =
+ match lbl.lbl_repres with
+ Record_regular | Record_inlined _ -> Pfield lbl.lbl_pos
+ | Record_float -> Pfloatfield lbl.lbl_pos
+ | Record_extension -> Pfield (lbl.lbl_pos + 1)
+ in
+ Lprim(access, [transl_exp arg])
+ | Texp_setfield(arg, _, lbl, newval) ->
+ let access =
+ match lbl.lbl_repres with
+ Record_regular
+ | Record_inlined _ -> Psetfield(lbl.lbl_pos, maybe_pointer newval)
+ | Record_float -> Psetfloatfield lbl.lbl_pos
+ | Record_extension -> Psetfield (lbl.lbl_pos + 1, maybe_pointer newval)
+ in
+ Lprim(access, [transl_exp arg; transl_exp newval])
+ | Texp_array expr_list ->
+ let kind = array_kind e in
+ let ll = transl_list expr_list in
+ begin try
+ (* Deactivate constant optimization if array is small enough *)
+ if List.length ll <= 4 then raise Not_constant;
+ let cl = List.map extract_constant ll in
+ let master =
+ match kind with
+ | Paddrarray | Pintarray ->
+ Lconst(Const_block(0, cl))
+ | Pfloatarray ->
+ Lconst(Const_float_array(List.map extract_float cl))
+ | Pgenarray ->
+ raise Not_constant in (* can this really happen? *)
+ Lprim(Pccall prim_obj_dup, [master])
+ with Not_constant ->
+ Lprim(Pmakearray kind, ll)
+ end
+ | Texp_ifthenelse(cond, ifso, Some ifnot) ->
+ Lifthenelse(transl_exp cond,
+ event_before ifso (transl_exp ifso),
+ event_before ifnot (transl_exp ifnot))
+ | Texp_ifthenelse(cond, ifso, None) ->
+ Lifthenelse(transl_exp cond,
+ event_before ifso (transl_exp ifso),
+ lambda_unit)
+ | Texp_sequence(expr1, expr2) ->
+ Lsequence(transl_exp expr1, event_before expr2 (transl_exp expr2))
+ | Texp_while(cond, body) ->
+ Lwhile(transl_exp cond, event_before body (transl_exp body))
+ | Texp_for(param, _, low, high, dir, body) ->
+ Lfor(param, transl_exp low, transl_exp high, dir,
+ event_before body (transl_exp body))
+ | Texp_send(_, _, Some exp) -> transl_exp exp
+ | Texp_send(expr, met, None) ->
+ let obj = transl_exp expr in
+ let lam =
+ match met with
+ Tmeth_val id -> Lsend (Self, Lvar id, obj, [], e.exp_loc)
+ | Tmeth_name nm ->
+ let (tag, cache) = Translobj.meth obj nm in
+ let kind = if cache = [] then Public else Cached in
+ Lsend (kind, tag, obj, cache, e.exp_loc)
+ in
+ event_after e lam
+ | Texp_new (cl, {Location.loc=loc}, _) ->
+ Lapply(Lprim(Pfield 0, [transl_path ~loc e.exp_env cl]),
+ [lambda_unit], no_apply_info)
+ | Texp_instvar(path_self, path, _) ->
+ Lprim(Parrayrefu Paddrarray,
+ [transl_normal_path path_self; transl_normal_path path])
+ | Texp_setinstvar(path_self, path, _, expr) ->
+ transl_setinstvar (transl_normal_path path_self) path expr
+ | Texp_override(path_self, modifs) ->
+ let cpy = Ident.create "copy" in
+ Llet(Strict, cpy,
+ Lapply(Translobj.oo_prim "copy", [transl_normal_path path_self],
+ no_apply_info),
+ List.fold_right
+ (fun (path, _, expr) rem ->
+ Lsequence(transl_setinstvar (Lvar cpy) path expr, rem))
+ modifs
+ (Lvar cpy))
+ | Texp_letmodule(id, _, modl, body) ->
+ Llet(Strict, id, !transl_module Tcoerce_none None modl, transl_exp body)
+ | Texp_pack modl ->
+ !transl_module Tcoerce_none None modl
+ | Texp_assert {exp_desc=Texp_construct(_, {cstr_name="false"}, _)} ->
+ assert_failed e
+ | Texp_assert (cond) ->
+ if !Clflags.noassert
+ then lambda_unit
+ else Lifthenelse (transl_exp cond, lambda_unit, assert_failed e)
+ | Texp_lazy e ->
+ (* when e needs no computation (constants, identifiers, ...), we
+ optimize the translation just as Lazy.lazy_from_val would
+ do *)
+ begin match e.exp_desc with
+ (* a constant expr of type <> float gets compiled as itself *)
+ | Texp_constant
+ ( Const_int _ | Const_char _ | Const_string _
+ | Const_int32 _ | Const_int64 _ | Const_nativeint _ )
+ | Texp_function(_, _, _)
+ | Texp_construct (_, {cstr_arity = 0}, _)
+ -> transl_exp e
+ | Texp_constant(Const_float _) ->
+ Lprim(Pmakeblock(Obj.forward_tag, Immutable), [transl_exp e])
+ | Texp_ident(_, _, _) -> (* according to the type *)
+ begin match e.exp_type.desc with
+ (* the following may represent a float/forward/lazy: need a
+ forward_tag *)
+ | Tvar _ | Tlink _ | Tsubst _ | Tunivar _
+ | Tpoly(_,_) | Tfield(_,_,_,_) ->
+ Lprim(Pmakeblock(Obj.forward_tag, Immutable), [transl_exp e])
+ (* the following cannot be represented as float/forward/lazy:
+ optimize *)
+ | Tarrow(_,_,_,_) | Ttuple _ | Tpackage _ | Tobject(_,_) | Tnil
+ | Tvariant _
+ -> transl_exp e
+ (* optimize predefined types (excepted float) *)
+ | Tconstr(_,_,_) ->
+ if has_base_type e Predef.path_int
+ || has_base_type e Predef.path_char
+ || has_base_type e Predef.path_string
+ || has_base_type e Predef.path_bool
+ || has_base_type e Predef.path_unit
+ || has_base_type e Predef.path_exn
+ || has_base_type e Predef.path_array
+ || has_base_type e Predef.path_list
+ || has_base_type e Predef.path_option
+ || has_base_type e Predef.path_nativeint
+ || has_base_type e Predef.path_int32
+ || has_base_type e Predef.path_int64
+ then transl_exp e
+ else
+ Lprim(Pmakeblock(Obj.forward_tag, Immutable), [transl_exp e])
+ end
+ (* other cases compile to a lazy block holding a function *)
+ | _ ->
+ let fn = Lfunction {kind = Curried; params = [Ident.create "param"];
+ body = transl_exp e} in
+ Lprim(Pmakeblock(Config.lazy_tag, Mutable), [fn])
+ end
+ | Texp_object (cs, meths) ->
+ let cty = cs.cstr_type in
+ let cl = Ident.create "class" in
+ !transl_object cl meths
+ { cl_desc = Tcl_structure cs;
+ cl_loc = e.exp_loc;
+ cl_type = Cty_signature cty;
+ cl_env = e.exp_env;
+ cl_attributes = [];
+ }
+
+and transl_list expr_list =
+ List.map transl_exp expr_list
+
+and transl_guard guard rhs =
+ let expr = event_before rhs (transl_exp rhs) in
+ match guard with
+ | None -> expr
+ | Some cond ->
+ event_before cond (Lifthenelse(transl_exp cond, expr, staticfail))
+
+and transl_case {c_lhs; c_guard; c_rhs} =
+ c_lhs, transl_guard c_guard c_rhs
+
+and transl_cases cases =
+ List.map transl_case cases
+
+and transl_case_try {c_lhs; c_guard; c_rhs} =
+ match c_lhs.pat_desc with
+ | Tpat_var (id, _)
+ | Tpat_alias (_, id, _) ->
+ Hashtbl.replace try_ids id ();
+ Misc.try_finally
+ (fun () -> c_lhs, transl_guard c_guard c_rhs)
+ (fun () -> Hashtbl.remove try_ids id)
+ | _ ->
+ c_lhs, transl_guard c_guard c_rhs
+
+and transl_cases_try cases =
+ List.map transl_case_try cases
+
+and transl_tupled_cases patl_expr_list =
+ List.map (fun (patl, guard, expr) -> (patl, transl_guard guard expr))
+ patl_expr_list
+
+and transl_apply ?(should_be_tailcall=false) lam sargs loc =
+ let lapply funct args =
+ match funct with
+ Lsend(k, lmet, lobj, largs, loc) ->
+ Lsend(k, lmet, lobj, largs @ args, loc)
+ | Levent(Lsend(k, lmet, lobj, largs, loc), _) ->
+ Lsend(k, lmet, lobj, largs @ args, loc)
+ | Lapply(lexp, largs, info) ->
+ Lapply(lexp, largs @ args, {info with apply_loc=loc})
+ | lexp ->
+ Lapply(lexp, args, mk_apply_info ~tailcall:should_be_tailcall loc)
+ in
+ let rec build_apply lam args = function
+ (None, optional) :: l ->
+ let defs = ref [] in
+ let protect name lam =
+ match lam with
+ Lvar _ | Lconst _ -> lam
+ | _ ->
+ let id = Ident.create name in
+ defs := (id, lam) :: !defs;
+ Lvar id
+ in
+ let args, args' =
+ if List.for_all (fun (_,opt) -> opt = Optional) args then [], args
+ else args, [] in
+ let lam =
+ if args = [] then lam else lapply lam (List.rev_map fst args) in
+ let handle = protect "func" lam
+ and l = List.map (fun (arg, opt) -> may_map (protect "arg") arg, opt) l
+ and id_arg = Ident.create "param" in
+ let body =
+ match build_apply handle ((Lvar id_arg, optional)::args') l with
+ Lfunction{kind = Curried; params = ids; body = lam} ->
+ Lfunction{kind = Curried; params = id_arg::ids; body = lam}
+ | Levent(Lfunction{kind = Curried; params = ids; body = lam}, _) ->
+ Lfunction{kind = Curried; params = id_arg::ids; body = lam}
+ | lam ->
+ Lfunction{kind = Curried; params = [id_arg]; body = lam}
+ in
+ List.fold_left
+ (fun body (id, lam) -> Llet(Strict, id, lam, body))
+ body !defs
+ | (Some arg, optional) :: l ->
+ build_apply lam ((arg, optional) :: args) l
+ | [] ->
+ lapply lam (List.rev_map fst args)
+ in
+ build_apply lam [] (List.map (fun (l, x,o) -> may_map transl_exp x, o) sargs)
+
+and transl_function loc untuplify_fn repr partial cases =
+ match cases with
+ [{c_lhs=pat; c_guard=None;
+ c_rhs={exp_desc = Texp_function(_, pl,partial')} as exp}]
+ when Parmatch.fluid pat ->
+ let param = name_pattern "param" cases in
+ let ((_, params), body) =
+ transl_function exp.exp_loc false repr partial' pl in
+ ((Curried, param :: params),
+ Matching.for_function loc None (Lvar param) [pat, body] partial)
+ | {c_lhs={pat_desc = Tpat_tuple pl}} :: _ when untuplify_fn ->
+ begin try
+ let size = List.length pl in
+ let pats_expr_list =
+ List.map
+ (fun {c_lhs; c_guard; c_rhs} ->
+ (Matching.flatten_pattern size c_lhs, c_guard, c_rhs))
+ cases in
+ let params = List.map (fun p -> Ident.create "param") pl in
+ ((Tupled, params),
+ Matching.for_tupled_function loc params
+ (transl_tupled_cases pats_expr_list) partial)
+ with Matching.Cannot_flatten ->
+ let param = name_pattern "param" cases in
+ ((Curried, [param]),
+ Matching.for_function loc repr (Lvar param)
+ (transl_cases cases) partial)
+ end
+ | _ ->
+ let param = name_pattern "param" cases in
+ ((Curried, [param]),
+ Matching.for_function loc repr (Lvar param)
+ (transl_cases cases) partial)
+
+and transl_let rec_flag pat_expr_list body =
+ match rec_flag with
+ Nonrecursive ->
+ let rec transl = function
+ [] ->
+ body
+ | {vb_pat=pat; vb_expr=expr} :: rem ->
+ Matching.for_let pat.pat_loc (transl_exp expr) pat (transl rem)
+ in transl pat_expr_list
+ | Recursive ->
+ let idlist =
+ List.map
+ (fun {vb_pat=pat} -> match pat.pat_desc with
+ Tpat_var (id,_) -> id
+ | Tpat_alias ({pat_desc=Tpat_any}, id,_) -> id
+ | _ -> raise(Error(pat.pat_loc, Illegal_letrec_pat)))
+ pat_expr_list in
+ let transl_case {vb_pat=pat; vb_expr=expr} id =
+ let lam = transl_exp expr in
+ if not (check_recursive_lambda idlist lam) then
+ raise(Error(expr.exp_loc, Illegal_letrec_expr));
+ (id, lam) in
+ Lletrec(List.map2 transl_case pat_expr_list idlist, body)
+
+and transl_setinstvar self var expr =
+ Lprim(Parraysetu (if maybe_pointer expr then Paddrarray else Pintarray),
+ [self; transl_normal_path var; transl_exp expr])
+
+and transl_record env all_labels repres lbl_expr_list opt_init_expr =
+ let size = Array.length all_labels in
+ (* Determine if there are "enough" new fields *)
+ if 3 + 2 * List.length lbl_expr_list >= size
+ then begin
+ (* Allocate new record with given fields (and remaining fields
+ taken from init_expr if any *)
+ let lv = Array.make (Array.length all_labels) staticfail in
+ let init_id = Ident.create "init" in
+ begin match opt_init_expr with
+ None -> ()
+ | Some init_expr ->
+ for i = 0 to Array.length all_labels - 1 do
+ let access =
+ match all_labels.(i).lbl_repres with
+ Record_regular | Record_inlined _ -> Pfield i
+ | Record_extension -> Pfield (i + 1)
+ | Record_float -> Pfloatfield i in
+ lv.(i) <- Lprim(access, [Lvar init_id])
+ done
+ end;
+ List.iter
+ (fun (_, lbl, expr) -> lv.(lbl.lbl_pos) <- transl_exp expr)
+ lbl_expr_list;
+ let ll = Array.to_list lv in
+ let mut =
+ if List.exists (fun (_, lbl, expr) -> lbl.lbl_mut = Mutable) lbl_expr_list
+ then Mutable
+ else Immutable in
+ let lam =
+ try
+ if mut = Mutable then raise Not_constant;
+ let cl = List.map extract_constant ll in
+ match repres with
+ | Record_regular -> Lconst(Const_block(0, cl))
+ | Record_inlined tag -> Lconst(Const_block(tag, cl))
+ | Record_float ->
+ Lconst(Const_float_array(List.map extract_float cl))
+ | Record_extension ->
+ raise Not_constant
+ with Not_constant ->
+ match repres with
+ Record_regular -> Lprim(Pmakeblock(0, mut), ll)
+ | Record_inlined tag -> Lprim(Pmakeblock(tag, mut), ll)
+ | Record_float -> Lprim(Pmakearray Pfloatarray, ll)
+ | Record_extension ->
+ let path =
+ match all_labels.(0).lbl_res.desc with
+ | Tconstr(p, _, _) -> p
+ | _ -> assert false
+ in
+ let slot = transl_path env path in
+ Lprim(Pmakeblock(0, mut), slot :: ll)
+ in
+ begin match opt_init_expr with
+ None -> lam
+ | Some init_expr -> Llet(Strict, init_id, transl_exp init_expr, lam)
+ end
+ end else begin
+ (* Take a shallow copy of the init record, then mutate the fields
+ of the copy *)
+ (* If you change anything here, you will likely have to change
+ [check_recursive_recordwith] in this file. *)
+ let copy_id = Ident.create "newrecord" in
+ let update_field (_, lbl, expr) cont =
+ let upd =
+ match lbl.lbl_repres with
+ Record_regular
+ | Record_inlined _ -> Psetfield(lbl.lbl_pos, maybe_pointer expr)
+ | Record_float -> Psetfloatfield lbl.lbl_pos
+ | Record_extension -> Psetfield(lbl.lbl_pos + 1, maybe_pointer expr)
+ in
+ Lsequence(Lprim(upd, [Lvar copy_id; transl_exp expr]), cont) in
+ begin match opt_init_expr with
+ None -> assert false
+ | Some init_expr ->
+ Llet(Strict, copy_id,
+ Lprim(Pduprecord (repres, size), [transl_exp init_expr]),
+ List.fold_right update_field lbl_expr_list (Lvar copy_id))
+ end
+ end
+
+and transl_match e arg pat_expr_list exn_pat_expr_list partial =
+ let id = name_pattern "exn" exn_pat_expr_list
+ and cases = transl_cases pat_expr_list
+ and exn_cases = transl_cases exn_pat_expr_list in
+ let static_catch body val_ids handler =
+ let static_exception_id = next_negative_raise_count () in
+ Lstaticcatch
+ (Ltrywith (Lstaticraise (static_exception_id, body), id,
+ Matching.for_trywith (Lvar id) exn_cases),
+ (static_exception_id, val_ids),
+ handler)
+ in
+ match arg, exn_cases with
+ | {exp_desc = Texp_tuple argl}, [] ->
+ Matching.for_multiple_match e.exp_loc (transl_list argl) cases partial
+ | {exp_desc = Texp_tuple argl}, _ :: _ ->
+ let val_ids = List.map (fun _ -> name_pattern "val" []) argl in
+ let lvars = List.map (fun id -> Lvar id) val_ids in
+ static_catch (transl_list argl) val_ids
+ (Matching.for_multiple_match e.exp_loc lvars cases partial)
+ | arg, [] ->
+ Matching.for_function e.exp_loc None (transl_exp arg) cases partial
+ | arg, _ :: _ ->
+ let val_id = name_pattern "val" pat_expr_list in
+ static_catch [transl_exp arg] [val_id]
+ (Matching.for_function e.exp_loc None (Lvar val_id) cases partial)
+
+
+(* Wrapper for class compilation *)
+
+(*
+let transl_exp = transl_exp_wrap
+
+let transl_let rec_flag pat_expr_list body =
+ match pat_expr_list with
+ [] -> body
+ | (_, expr) :: _ ->
+ Translobj.oo_wrap expr.exp_env false
+ (transl_let rec_flag pat_expr_list) body
+*)
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Illegal_letrec_pat ->
+ fprintf ppf
+ "Only variables are allowed as left-hand side of `let rec'"
+ | Illegal_letrec_expr ->
+ fprintf ppf
+ "This kind of expression is not allowed as right-hand side of `let rec'"
+ | Free_super_var ->
+ fprintf ppf
+ "Ancestor names can only be used to select inherited methods"
+ | Unknown_builtin_primitive prim_name ->
+ fprintf ppf "Unknown builtin primitive \"%s\"" prim_name
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, err) ->
+ Some (Location.error_of_printer loc report_error err)
+ | _ ->
+ None
+ )
diff --git a/bytecomp/translcore.mli b/bytecomp/translcore.mli
new file mode 100644
index 0000000000..75ba9fcf02
--- /dev/null
+++ b/bytecomp/translcore.mli
@@ -0,0 +1,46 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translation from typed abstract syntax to lambda terms,
+ for the core language *)
+
+open Asttypes
+open Typedtree
+open Lambda
+
+val transl_exp: expression -> lambda
+val transl_apply: ?should_be_tailcall:bool
+ -> lambda -> (arg_label * expression option * optional) list
+ -> Location.t -> lambda
+val transl_let: rec_flag -> value_binding list -> lambda -> lambda
+val transl_primitive: Location.t -> Primitive.description -> Env.t
+ -> Types.type_expr -> lambda
+
+val check_recursive_lambda: Ident.t list -> lambda -> bool
+
+type error =
+ Illegal_letrec_pat
+ | Illegal_letrec_expr
+ | Free_super_var
+ | Unknown_builtin_primitive of string
+
+exception Error of Location.t * error
+
+open Format
+
+val report_error: formatter -> error -> unit
+
+(* Forward declaration -- to be filled in by Translmod.transl_module *)
+val transl_module :
+ (module_coercion -> Path.t option -> module_expr -> lambda) ref
+val transl_object :
+ (Ident.t -> string list -> class_expr -> lambda) ref
diff --git a/bytecomp/translmod.ml b/bytecomp/translmod.ml
new file mode 100644
index 0000000000..42821601ab
--- /dev/null
+++ b/bytecomp/translmod.ml
@@ -0,0 +1,971 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translation from typed abstract syntax to lambda terms,
+ for the module language *)
+
+open Misc
+open Asttypes
+open Longident
+open Path
+open Types
+open Typedtree
+open Lambda
+open Translobj
+open Translcore
+open Translclass
+
+type error =
+ Circular_dependency of Ident.t
+
+
+exception Error of Location.t * error
+
+(* Keep track of the root path (from the root of the namespace to the
+ currently compiled module expression). Useful for naming extensions. *)
+
+let global_path glob = Some(Pident glob)
+let functor_path path param =
+ match path with
+ None -> None
+ | Some p -> Some(Papply(p, Pident param))
+let field_path path field =
+ match path with
+ None -> None
+ | Some p -> Some(Pdot(p, Ident.name field, Path.nopos))
+
+(* Compile type extensions *)
+
+let prim_set_oo_id =
+ Pccall (Primitive.simple ~name:"caml_set_oo_id" ~arity:1 ~alloc:false)
+
+let transl_extension_constructor env path ext =
+ let name =
+ match path with
+ None -> Ident.name ext.ext_id
+ | Some p -> Path.name p
+ in
+ match ext.ext_kind with
+ Text_decl(args, ret) ->
+ Lprim(prim_set_oo_id,
+ [Lprim(Pmakeblock(Obj.object_tag, Mutable),
+ [Lconst(Const_base(Const_string (name,None)));
+ Lconst(Const_base(Const_int 0))])])
+ | Text_rebind(path, lid) ->
+ transl_path ~loc:ext.ext_loc env path
+
+let transl_type_extension env rootpath tyext body =
+ List.fold_right
+ (fun ext body ->
+ let lam =
+ transl_extension_constructor env (field_path rootpath ext.ext_id) ext
+ in
+ Llet(Strict, ext.ext_id, lam, body))
+ tyext.tyext_constructors
+ body
+
+(* Compile a coercion *)
+
+let rec apply_coercion strict restr arg =
+ match restr with
+ Tcoerce_none ->
+ arg
+ | Tcoerce_structure(pos_cc_list, id_pos_list) ->
+ name_lambda strict arg (fun id ->
+ let get_field pos = Lprim(Pfield pos,[Lvar id]) in
+ let lam =
+ Lprim(Pmakeblock(0, Immutable),
+ List.map (apply_coercion_field get_field) pos_cc_list)
+ in
+ wrap_id_pos_list id_pos_list get_field lam)
+ | Tcoerce_functor(cc_arg, cc_res) ->
+ let param = Ident.create "funarg" in
+ name_lambda strict arg (fun id ->
+ Lfunction{kind = Curried; params = [param];
+ body = apply_coercion
+ Strict cc_res
+ (Lapply(Lvar id,
+ [apply_coercion Alias cc_arg (Lvar param)],
+ no_apply_info))})
+ | Tcoerce_primitive { pc_loc; pc_desc; pc_env; pc_type; } ->
+ transl_primitive pc_loc pc_desc pc_env pc_type
+ | Tcoerce_alias (path, cc) ->
+ name_lambda strict arg
+ (fun id -> apply_coercion Alias cc (transl_normal_path path))
+
+and apply_coercion_field get_field (pos, cc) =
+ apply_coercion Alias cc (get_field pos)
+
+and wrap_id_pos_list id_pos_list get_field lam =
+ let fv = free_variables lam in
+ (*Format.eprintf "%a@." Printlambda.lambda lam;
+ IdentSet.iter (fun id -> Format.eprintf "%a " Ident.print id) fv;
+ Format.eprintf "@.";*)
+ let (lam,s) =
+ List.fold_left (fun (lam,s) (id',pos,c) ->
+ if IdentSet.mem id' fv then
+ let id'' = Ident.create (Ident.name id') in
+ (Llet(Alias,id'',
+ apply_coercion Alias c (get_field pos),lam),
+ Ident.add id' (Lvar id'') s)
+ else (lam,s))
+ (lam, Ident.empty) id_pos_list
+ in
+ if s == Ident.empty then lam else subst_lambda s lam
+
+
+(* Compose two coercions
+ apply_coercion c1 (apply_coercion c2 e) behaves like
+ apply_coercion (compose_coercions c1 c2) e. *)
+
+let rec compose_coercions c1 c2 =
+ match (c1, c2) with
+ (Tcoerce_none, c2) -> c2
+ | (c1, Tcoerce_none) -> c1
+ | (Tcoerce_structure (pc1, ids1), Tcoerce_structure (pc2, ids2)) ->
+ let v2 = Array.of_list pc2 in
+ let ids1 =
+ List.map (fun (id,pos1,c1) ->
+ let (pos2,c2) = v2.(pos1) in (id, pos2, compose_coercions c1 c2))
+ ids1
+ in
+ Tcoerce_structure
+ (List.map
+ (function (p1, Tcoerce_primitive p) ->
+ (p1, Tcoerce_primitive p)
+ | (p1, c1) ->
+ let (p2, c2) = v2.(p1) in (p2, compose_coercions c1 c2))
+ pc1,
+ ids1 @ ids2)
+ | (Tcoerce_functor(arg1, res1), Tcoerce_functor(arg2, res2)) ->
+ Tcoerce_functor(compose_coercions arg2 arg1,
+ compose_coercions res1 res2)
+ | (c1, Tcoerce_alias (path, c2)) ->
+ Tcoerce_alias (path, compose_coercions c1 c2)
+ | (_, _) ->
+ fatal_error "Translmod.compose_coercions"
+
+(*
+let apply_coercion a b c =
+ Format.eprintf "@[<2>apply_coercion@ %a@]@." Includemod.print_coercion b;
+ apply_coercion a b c
+
+let compose_coercions c1 c2 =
+ let c3 = compose_coercions c1 c2 in
+ let open Includemod in
+ Format.eprintf "@[<2>compose_coercions@ (%a)@ (%a) =@ %a@]@."
+ print_coercion c1 print_coercion c2 print_coercion c3;
+ c3
+*)
+
+(* Record the primitive declarations occuring in the module compiled *)
+
+let primitive_declarations = ref ([] : Primitive.description list)
+let record_primitive = function
+ | {val_kind=Val_prim p} ->
+ primitive_declarations := p :: !primitive_declarations
+ | _ -> ()
+
+(* Utilities for compiling "module rec" definitions *)
+
+let mod_prim name =
+ try
+ transl_normal_path
+ (fst (Env.lookup_value (Ldot (Lident "CamlinternalMod", name))
+ Env.empty))
+ with Not_found ->
+ fatal_error ("Primitive " ^ name ^ " not found.")
+
+let undefined_location loc =
+ let (fname, line, char) = Location.get_pos_info loc.Location.loc_start in
+ Lconst(Const_block(0,
+ [Const_base(Const_string (fname, None));
+ Const_base(Const_int line);
+ Const_base(Const_int char)]))
+
+let init_shape modl =
+ let rec init_shape_mod env mty =
+ match Mtype.scrape env mty with
+ Mty_ident _ ->
+ raise Not_found
+ | Mty_alias _ ->
+ Const_block (1, [Const_pointer 0])
+ | Mty_signature sg ->
+ Const_block(0, [Const_block(0, init_shape_struct env sg)])
+ | Mty_functor(id, arg, res) ->
+ raise Not_found (* can we do better? *)
+ and init_shape_struct env sg =
+ match sg with
+ [] -> []
+ | Sig_value(id, vdesc) :: rem ->
+ let init_v =
+ match Ctype.expand_head env vdesc.val_type with
+ {desc = Tarrow(_,_,_,_)} ->
+ Const_pointer 0 (* camlinternalMod.Function *)
+ | {desc = Tconstr(p, _, _)} when Path.same p Predef.path_lazy_t ->
+ Const_pointer 1 (* camlinternalMod.Lazy *)
+ | _ -> raise Not_found in
+ init_v :: init_shape_struct env rem
+ | Sig_type(id, tdecl, _) :: rem ->
+ init_shape_struct (Env.add_type ~check:false id tdecl env) rem
+ | Sig_typext(id, ext, _) :: rem ->
+ raise Not_found
+ | Sig_module(id, md, _) :: rem ->
+ init_shape_mod env md.md_type ::
+ init_shape_struct (Env.add_module_declaration id md env) rem
+ | Sig_modtype(id, minfo) :: rem ->
+ init_shape_struct (Env.add_modtype id minfo env) rem
+ | Sig_class(id, cdecl, _) :: rem ->
+ Const_pointer 2 (* camlinternalMod.Class *)
+ :: init_shape_struct env rem
+ | Sig_class_type(id, ctyp, _) :: rem ->
+ init_shape_struct env rem
+ in
+ try
+ Some(undefined_location modl.mod_loc,
+ Lconst(init_shape_mod modl.mod_env modl.mod_type))
+ with Not_found ->
+ None
+
+(* Reorder bindings to honor dependencies. *)
+
+type binding_status = Undefined | Inprogress | Defined
+
+let reorder_rec_bindings bindings =
+ let id = Array.of_list (List.map (fun (id,_,_,_) -> id) bindings)
+ and loc = Array.of_list (List.map (fun (_,loc,_,_) -> loc) bindings)
+ and init = Array.of_list (List.map (fun (_,_,init,_) -> init) bindings)
+ and rhs = Array.of_list (List.map (fun (_,_,_,rhs) -> rhs) bindings) in
+ let fv = Array.map Lambda.free_variables rhs in
+ let num_bindings = Array.length id in
+ let status = Array.make num_bindings Undefined in
+ let res = ref [] in
+ let rec emit_binding i =
+ match status.(i) with
+ Defined -> ()
+ | Inprogress -> raise(Error(loc.(i), Circular_dependency id.(i)))
+ | Undefined ->
+ if init.(i) = None then begin
+ status.(i) <- Inprogress;
+ for j = 0 to num_bindings - 1 do
+ if IdentSet.mem id.(j) fv.(i) then emit_binding j
+ done
+ end;
+ res := (id.(i), init.(i), rhs.(i)) :: !res;
+ status.(i) <- Defined in
+ for i = 0 to num_bindings - 1 do
+ match status.(i) with
+ Undefined -> emit_binding i
+ | Inprogress -> assert false
+ | Defined -> ()
+ done;
+ List.rev !res
+
+(* Generate lambda-code for a reordered list of bindings *)
+
+let eval_rec_bindings bindings cont =
+ let rec bind_inits = function
+ [] ->
+ bind_strict bindings
+ | (id, None, rhs) :: rem ->
+ bind_inits rem
+ | (id, Some(loc, shape), rhs) :: rem ->
+ Llet(Strict, id,
+ Lapply(mod_prim "init_mod", [loc; shape], no_apply_info),
+ bind_inits rem)
+ and bind_strict = function
+ [] ->
+ patch_forwards bindings
+ | (id, None, rhs) :: rem ->
+ Llet(Strict, id, rhs, bind_strict rem)
+ | (id, Some(loc, shape), rhs) :: rem ->
+ bind_strict rem
+ and patch_forwards = function
+ [] ->
+ cont
+ | (id, None, rhs) :: rem ->
+ patch_forwards rem
+ | (id, Some(loc, shape), rhs) :: rem ->
+ Lsequence(Lapply(mod_prim "update_mod", [shape; Lvar id; rhs],
+ no_apply_info),
+ patch_forwards rem)
+ in
+ bind_inits bindings
+
+let compile_recmodule compile_rhs bindings cont =
+ eval_rec_bindings
+ (reorder_rec_bindings
+ (List.map
+ (fun {mb_id=id; mb_expr=modl; _} ->
+ (id, modl.mod_loc, init_shape modl, compile_rhs id modl))
+ bindings))
+ cont
+
+(* Extract the list of "value" identifiers bound by a signature.
+ "Value" identifiers are identifiers for signature components that
+ correspond to a run-time value: values, extensions, modules, classes.
+ Note: manifest primitives do not correspond to a run-time value! *)
+
+let rec bound_value_identifiers = function
+ [] -> []
+ | Sig_value(id, {val_kind = Val_reg}) :: rem ->
+ id :: bound_value_identifiers rem
+ | Sig_typext(id, ext, _) :: rem -> id :: bound_value_identifiers rem
+ | Sig_module(id, mty, _) :: rem -> id :: bound_value_identifiers rem
+ | Sig_class(id, decl, _) :: rem -> id :: bound_value_identifiers rem
+ | _ :: rem -> bound_value_identifiers rem
+
+
+(* Code to translate class entries in a structure *)
+
+let transl_class_bindings cl_list =
+ let ids = List.map (fun (ci, _) -> ci.ci_id_class) cl_list in
+ (ids,
+ List.map
+ (fun ({ci_id_class=id; ci_expr=cl; ci_virt=vf}, meths) ->
+ (id, transl_class ids id meths cl vf))
+ cl_list)
+
+(* Compile a module expression *)
+
+let rec transl_module cc rootpath mexp =
+ match mexp.mod_type with
+ Mty_alias _ -> apply_coercion Alias cc lambda_unit
+ | _ ->
+ match mexp.mod_desc with
+ Tmod_ident (path,_) ->
+ apply_coercion Strict cc
+ (transl_path ~loc:mexp.mod_loc mexp.mod_env path)
+ | Tmod_structure str ->
+ transl_struct [] cc rootpath str
+ | Tmod_functor( param, _, mty, body) ->
+ let bodypath = functor_path rootpath param in
+ oo_wrap mexp.mod_env true
+ (function
+ | Tcoerce_none ->
+ Lfunction{kind = Curried; params = [param];
+ body = transl_module Tcoerce_none bodypath body}
+ | Tcoerce_functor(ccarg, ccres) ->
+ let param' = Ident.create "funarg" in
+ Lfunction{kind = Curried; params = [param'];
+ body = Llet(Alias, param,
+ apply_coercion Alias ccarg (Lvar param'),
+ transl_module ccres bodypath body)}
+ | _ ->
+ fatal_error "Translmod.transl_module")
+ cc
+ | Tmod_apply(funct, arg, ccarg) ->
+ oo_wrap mexp.mod_env true
+ (apply_coercion Strict cc)
+ (Lapply(transl_module Tcoerce_none None funct,
+ [transl_module ccarg None arg], mk_apply_info mexp.mod_loc))
+ | Tmod_constraint(arg, mty, _, ccarg) ->
+ transl_module (compose_coercions cc ccarg) rootpath arg
+ | Tmod_unpack(arg, _) ->
+ apply_coercion Strict cc (Translcore.transl_exp arg)
+
+and transl_struct fields cc rootpath str =
+ transl_structure fields cc rootpath str.str_items
+
+and transl_structure fields cc rootpath = function
+ [] ->
+ begin match cc with
+ Tcoerce_none ->
+ Lprim(Pmakeblock(0, Immutable),
+ List.map (fun id -> Lvar id) (List.rev fields))
+ | Tcoerce_structure(pos_cc_list, id_pos_list) ->
+ (* Do not ignore id_pos_list ! *)
+ (*Format.eprintf "%a@.@[" Includemod.print_coercion cc;
+ List.iter (fun l -> Format.eprintf "%a@ " Ident.print l)
+ fields;
+ Format.eprintf "@]@.";*)
+ let v = Array.of_list (List.rev fields) in
+ let get_field pos = Lvar v.(pos)
+ and ids = List.fold_right IdentSet.add fields IdentSet.empty in
+ let lam =
+ (Lprim(Pmakeblock(0, Immutable),
+ List.map
+ (fun (pos, cc) ->
+ match cc with
+ Tcoerce_primitive p ->
+ transl_primitive p.pc_loc
+ p.pc_desc p.pc_env p.pc_type
+ | _ -> apply_coercion Strict cc (get_field pos))
+ pos_cc_list))
+ and id_pos_list =
+ List.filter (fun (id,_,_) -> not (IdentSet.mem id ids)) id_pos_list
+ in
+ wrap_id_pos_list id_pos_list get_field lam
+ | _ ->
+ fatal_error "Translmod.transl_structure"
+ end
+ | item :: rem ->
+ match item.str_desc with
+ | Tstr_eval (expr, _) ->
+ Lsequence(transl_exp expr, transl_structure fields cc rootpath rem)
+ | Tstr_value(rec_flag, pat_expr_list) ->
+ let ext_fields = rev_let_bound_idents pat_expr_list @ fields in
+ transl_let rec_flag pat_expr_list
+ (transl_structure ext_fields cc rootpath rem)
+ | Tstr_primitive descr ->
+ record_primitive descr.val_val;
+ transl_structure fields cc rootpath rem
+ | Tstr_type(_, decls) ->
+ transl_structure fields cc rootpath rem
+ | Tstr_typext(tyext) ->
+ let ids = List.map (fun ext -> ext.ext_id) tyext.tyext_constructors in
+ transl_type_extension item.str_env rootpath tyext
+ (transl_structure (List.rev_append ids fields) cc rootpath rem)
+ | Tstr_exception ext ->
+ let id = ext.ext_id in
+ let path = field_path rootpath id in
+ Llet(Strict, id, transl_extension_constructor item.str_env path ext,
+ transl_structure (id :: fields) cc rootpath rem)
+ | Tstr_module mb ->
+ let id = mb.mb_id in
+ Llet(pure_module mb.mb_expr, id,
+ transl_module Tcoerce_none (field_path rootpath id) mb.mb_expr,
+ transl_structure (id :: fields) cc rootpath rem)
+ | Tstr_recmodule bindings ->
+ let ext_fields =
+ List.rev_append (List.map (fun mb -> mb.mb_id) bindings) fields
+ in
+ compile_recmodule
+ (fun id modl ->
+ transl_module Tcoerce_none (field_path rootpath id) modl)
+ bindings
+ (transl_structure ext_fields cc rootpath rem)
+ | Tstr_class cl_list ->
+ let (ids, class_bindings) = transl_class_bindings cl_list in
+ Lletrec(class_bindings,
+ transl_structure (List.rev_append ids fields) cc rootpath rem)
+ | Tstr_include incl ->
+ let ids = bound_value_identifiers incl.incl_type in
+ let modl = incl.incl_mod in
+ let mid = Ident.create "include" in
+ let rec rebind_idents pos newfields = function
+ [] ->
+ transl_structure newfields cc rootpath rem
+ | id :: ids ->
+ Llet(Alias, id, Lprim(Pfield pos, [Lvar mid]),
+ rebind_idents (pos + 1) (id :: newfields) ids) in
+ Llet(pure_module modl, mid, transl_module Tcoerce_none None modl,
+ rebind_idents 0 fields ids)
+
+ | Tstr_modtype _
+ | Tstr_open _
+ | Tstr_class_type _
+ | Tstr_attribute _ ->
+ transl_structure fields cc rootpath rem
+
+and pure_module m =
+ match m.mod_desc with
+ Tmod_ident _ -> Alias
+ | Tmod_constraint (m,_,_,_) -> pure_module m
+ | _ -> Strict
+
+(* Update forward declaration in Translcore *)
+let _ =
+ Translcore.transl_module := transl_module
+
+(* Compile an implementation *)
+
+let transl_implementation module_name (str, cc) =
+ reset_labels ();
+ primitive_declarations := [];
+ let module_id = Ident.create_persistent module_name in
+ Lprim(Psetglobal module_id,
+ [transl_label_init
+ (transl_struct [] cc (global_path module_id) str)])
+
+
+(* Build the list of value identifiers defined by a toplevel structure
+ (excluding primitive declarations). *)
+
+let rec defined_idents = function
+ [] -> []
+ | item :: rem ->
+ match item.str_desc with
+ | Tstr_eval (expr, _) -> defined_idents rem
+ | Tstr_value(rec_flag, pat_expr_list) ->
+ let_bound_idents pat_expr_list @ defined_idents rem
+ | Tstr_primitive desc -> defined_idents rem
+ | Tstr_type (_, decls) -> defined_idents rem
+ | Tstr_typext tyext ->
+ List.map (fun ext -> ext.ext_id) tyext.tyext_constructors
+ @ defined_idents rem
+ | Tstr_exception ext -> ext.ext_id :: defined_idents rem
+ | Tstr_module mb -> mb.mb_id :: defined_idents rem
+ | Tstr_recmodule decls ->
+ List.map (fun mb -> mb.mb_id) decls @ defined_idents rem
+ | Tstr_modtype _ -> defined_idents rem
+ | Tstr_open _ -> defined_idents rem
+ | Tstr_class cl_list ->
+ List.map (fun (ci, _) -> ci.ci_id_class) cl_list @ defined_idents rem
+ | Tstr_class_type cl_list -> defined_idents rem
+ | Tstr_include incl ->
+ bound_value_identifiers incl.incl_type @ defined_idents rem
+ | Tstr_attribute _ -> defined_idents rem
+
+(* second level idents (module M = struct ... let id = ... end),
+ and all sub-levels idents *)
+let rec more_idents = function
+ [] -> []
+ | item :: rem ->
+ match item.str_desc with
+ | Tstr_eval (expr, _attrs) -> more_idents rem
+ | Tstr_value(rec_flag, pat_expr_list) -> more_idents rem
+ | Tstr_primitive _ -> more_idents rem
+ | Tstr_type (_, decls) -> more_idents rem
+ | Tstr_typext tyext -> more_idents rem
+ | Tstr_exception _ -> more_idents rem
+ | Tstr_recmodule decls -> more_idents rem
+ | Tstr_modtype _ -> more_idents rem
+ | Tstr_open _ -> more_idents rem
+ | Tstr_class cl_list -> more_idents rem
+ | Tstr_class_type cl_list -> more_idents rem
+ | Tstr_include _ -> more_idents rem
+ | Tstr_module {mb_expr={mod_desc = Tmod_structure str}} ->
+ all_idents str.str_items @ more_idents rem
+ | Tstr_module _ -> more_idents rem
+ | Tstr_attribute _ -> more_idents rem
+
+and all_idents = function
+ [] -> []
+ | item :: rem ->
+ match item.str_desc with
+ | Tstr_eval (expr, _attrs) -> all_idents rem
+ | Tstr_value(rec_flag, pat_expr_list) ->
+ let_bound_idents pat_expr_list @ all_idents rem
+ | Tstr_primitive _ -> all_idents rem
+ | Tstr_type (_, decls) -> all_idents rem
+ | Tstr_typext tyext ->
+ List.map (fun ext -> ext.ext_id) tyext.tyext_constructors
+ @ all_idents rem
+ | Tstr_exception ext -> ext.ext_id :: all_idents rem
+ | Tstr_recmodule decls ->
+ List.map (fun mb -> mb.mb_id) decls @ all_idents rem
+ | Tstr_modtype _ -> all_idents rem
+ | Tstr_open _ -> all_idents rem
+ | Tstr_class cl_list ->
+ List.map (fun (ci, _) -> ci.ci_id_class) cl_list @ all_idents rem
+ | Tstr_class_type cl_list -> all_idents rem
+ | Tstr_include incl ->
+ bound_value_identifiers incl.incl_type @ all_idents rem
+ | Tstr_module {mb_id;mb_expr={mod_desc = Tmod_structure str}} ->
+ mb_id :: all_idents str.str_items @ all_idents rem
+ | Tstr_module mb -> mb.mb_id :: all_idents rem
+ | Tstr_attribute _ -> all_idents rem
+
+
+(* A variant of transl_structure used to compile toplevel structure definitions
+ for the native-code compiler. Store the defined values in the fields
+ of the global as soon as they are defined, in order to reduce register
+ pressure. Also rewrites the defining expressions so that they
+ refer to earlier fields of the structure through the fields of
+ the global, not by their names.
+ "map" is a table from defined idents to (pos in global block, coercion).
+ "prim" is a list of (pos in global block, primitive declaration). *)
+
+let transl_store_subst = ref Ident.empty
+ (** In the native toplevel, this reference is threaded through successive
+ calls of transl_store_structure *)
+
+let nat_toplevel_name id =
+ try match Ident.find_same id !transl_store_subst with
+ | Lprim(Pfield pos, [Lprim(Pgetglobal glob, [])]) -> (glob,pos)
+ | _ -> raise Not_found
+ with Not_found ->
+ fatal_error("Translmod.nat_toplevel_name: " ^ Ident.unique_name id)
+
+let transl_store_structure glob map prims str =
+ let rec transl_store rootpath subst = function
+ [] ->
+ transl_store_subst := subst;
+ lambda_unit
+ | item :: rem ->
+ match item.str_desc with
+ | Tstr_eval (expr, _attrs) ->
+ Lsequence(subst_lambda subst (transl_exp expr),
+ transl_store rootpath subst rem)
+ | Tstr_value(rec_flag, pat_expr_list) ->
+ let ids = let_bound_idents pat_expr_list in
+ let lam = transl_let rec_flag pat_expr_list (store_idents ids) in
+ Lsequence(subst_lambda subst lam,
+ transl_store rootpath (add_idents false ids subst) rem)
+ | Tstr_primitive descr ->
+ record_primitive descr.val_val;
+ transl_store rootpath subst rem
+ | Tstr_type(_, decls) ->
+ transl_store rootpath subst rem
+ | Tstr_typext(tyext) ->
+ let ids = List.map (fun ext -> ext.ext_id) tyext.tyext_constructors in
+ let lam =
+ transl_type_extension item.str_env rootpath tyext (store_idents ids)
+ in
+ Lsequence(subst_lambda subst lam,
+ transl_store rootpath (add_idents false ids subst) rem)
+ | Tstr_exception ext ->
+ let id = ext.ext_id in
+ let path = field_path rootpath id in
+ let lam = transl_extension_constructor item.str_env path ext in
+ Lsequence(Llet(Strict, id, subst_lambda subst lam, store_ident id),
+ transl_store rootpath (add_ident false id subst) rem)
+ | Tstr_module{mb_id=id; mb_expr={mod_desc = Tmod_structure str}} ->
+ let lam = transl_store (field_path rootpath id) subst str.str_items in
+ (* Careful: see next case *)
+ let subst = !transl_store_subst in
+ Lsequence(lam,
+ Llet(Strict, id,
+ subst_lambda subst
+ (Lprim(Pmakeblock(0, Immutable),
+ List.map (fun id -> Lvar id)
+ (defined_idents str.str_items))),
+ Lsequence(store_ident id,
+ transl_store rootpath (add_ident true id subst)
+ rem)))
+ | Tstr_module{mb_id=id; mb_expr=modl} ->
+ let lam = transl_module Tcoerce_none (field_path rootpath id) modl in
+ (* Careful: the module value stored in the global may be different
+ from the local module value, in case a coercion is applied.
+ If so, keep using the local module value (id) in the remainder of
+ the compilation unit (add_ident true returns subst unchanged).
+ If not, we can use the value from the global
+ (add_ident true adds id -> Pgetglobal... to subst). *)
+ Llet(Strict, id, subst_lambda subst lam,
+ Lsequence(store_ident id,
+ transl_store rootpath (add_ident true id subst) rem))
+ | Tstr_recmodule bindings ->
+ let ids = List.map (fun mb -> mb.mb_id) bindings in
+ compile_recmodule
+ (fun id modl ->
+ subst_lambda subst
+ (transl_module Tcoerce_none
+ (field_path rootpath id) modl))
+ bindings
+ (Lsequence(store_idents ids,
+ transl_store rootpath (add_idents true ids subst) rem))
+ | Tstr_class cl_list ->
+ let (ids, class_bindings) = transl_class_bindings cl_list in
+ let lam = Lletrec(class_bindings, store_idents ids) in
+ Lsequence(subst_lambda subst lam,
+ transl_store rootpath (add_idents false ids subst) rem)
+ | Tstr_include incl ->
+ let ids = bound_value_identifiers incl.incl_type in
+ let modl = incl.incl_mod in
+ let mid = Ident.create "include" in
+ let rec store_idents pos = function
+ [] -> transl_store rootpath (add_idents true ids subst) rem
+ | id :: idl ->
+ Llet(Alias, id, Lprim(Pfield pos, [Lvar mid]),
+ Lsequence(store_ident id, store_idents (pos + 1) idl)) in
+ Llet(Strict, mid,
+ subst_lambda subst (transl_module Tcoerce_none None modl),
+ store_idents 0 ids)
+ | Tstr_modtype _
+ | Tstr_open _
+ | Tstr_class_type _
+ | Tstr_attribute _ ->
+ transl_store rootpath subst rem
+
+ and store_ident id =
+ try
+ let (pos, cc) = Ident.find_same id map in
+ let init_val = apply_coercion Alias cc (Lvar id) in
+ Lprim(Psetfield(pos, false), [Lprim(Pgetglobal glob, []); init_val])
+ with Not_found ->
+ fatal_error("Translmod.store_ident: " ^ Ident.unique_name id)
+
+ and store_idents idlist =
+ make_sequence store_ident idlist
+
+ and add_ident may_coerce id subst =
+ try
+ let (pos, cc) = Ident.find_same id map in
+ match cc with
+ Tcoerce_none ->
+ Ident.add id (Lprim(Pfield pos, [Lprim(Pgetglobal glob, [])])) subst
+ | _ ->
+ if may_coerce then subst else assert false
+ with Not_found ->
+ assert false
+
+ and add_idents may_coerce idlist subst =
+ List.fold_right (add_ident may_coerce) idlist subst
+
+ and store_primitive (pos, prim) cont =
+ Lsequence(Lprim(Psetfield(pos, false),
+ [Lprim(Pgetglobal glob, []);
+ transl_primitive Location.none
+ prim.pc_desc prim.pc_env prim.pc_type]),
+ cont)
+
+ in List.fold_right store_primitive prims
+ (transl_store (global_path glob) !transl_store_subst str)
+
+(* Transform a coercion and the list of value identifiers defined by
+ a toplevel structure into a table [id -> (pos, coercion)],
+ with [pos] being the position in the global block where the value of
+ [id] must be stored, and [coercion] the coercion to be applied to it.
+ A given identifier may appear several times
+ in the coercion (if it occurs several times in the signature); remember
+ to assign it the position of its last occurrence.
+ Identifiers that are not exported are assigned positions at the
+ end of the block (beyond the positions of all exported idents).
+ Also compute the total size of the global block,
+ and the list of all primitives exported as values. *)
+
+let build_ident_map restr idlist more_ids =
+ let rec natural_map pos map prims = function
+ [] ->
+ (map, prims, pos)
+ | id :: rem ->
+ natural_map (pos+1) (Ident.add id (pos, Tcoerce_none) map) prims rem in
+ let (map, prims, pos) =
+ match restr with
+ Tcoerce_none ->
+ natural_map 0 Ident.empty [] idlist
+ | Tcoerce_structure (pos_cc_list, _id_pos_list) ->
+ (* ignore _id_pos_list as the ids are already bound *)
+ let idarray = Array.of_list idlist in
+ let rec export_map pos map prims undef = function
+ [] ->
+ natural_map pos map prims undef
+ | (source_pos, Tcoerce_primitive p) :: rem ->
+ export_map (pos + 1) map ((pos, p) :: prims) undef rem
+ | (source_pos, cc) :: rem ->
+ let id = idarray.(source_pos) in
+ export_map (pos + 1) (Ident.add id (pos, cc) map)
+ prims (list_remove id undef) rem
+ in export_map 0 Ident.empty [] idlist pos_cc_list
+ | _ ->
+ fatal_error "Translmod.build_ident_map"
+ in
+ natural_map pos map prims more_ids
+
+(* Compile an implementation using transl_store_structure
+ (for the native-code compiler). *)
+
+let transl_store_gen module_name ({ str_items = str }, restr) topl =
+ reset_labels ();
+ primitive_declarations := [];
+ let module_id = Ident.create_persistent module_name in
+ let (map, prims, size) =
+ build_ident_map restr (defined_idents str) (more_idents str) in
+ let f = function
+ | [ { str_desc = Tstr_eval (expr, _attrs) } ] when topl ->
+ assert (size = 0);
+ subst_lambda !transl_store_subst (transl_exp expr)
+ | str -> transl_store_structure module_id map prims str in
+ transl_store_label_init module_id size f str
+ (*size, transl_label_init (transl_store_structure module_id map prims str)*)
+
+let transl_store_phrases module_name str =
+ transl_store_gen module_name (str,Tcoerce_none) true
+
+let transl_store_implementation module_name (str, restr) =
+ let s = !transl_store_subst in
+ transl_store_subst := Ident.empty;
+ let r = transl_store_gen module_name (str, restr) false in
+ transl_store_subst := s;
+ r
+
+(* Compile a toplevel phrase *)
+
+let toploop_ident = Ident.create_persistent "Toploop"
+let toploop_getvalue_pos = 0 (* position of getvalue in module Toploop *)
+let toploop_setvalue_pos = 1 (* position of setvalue in module Toploop *)
+
+let aliased_idents = ref Ident.empty
+
+let set_toplevel_unique_name id =
+ aliased_idents :=
+ Ident.add id (Ident.unique_toplevel_name id) !aliased_idents
+
+let toplevel_name id =
+ try Ident.find_same id !aliased_idents
+ with Not_found -> Ident.name id
+
+let toploop_getvalue id =
+ Lapply(Lprim(Pfield toploop_getvalue_pos,
+ [Lprim(Pgetglobal toploop_ident, [])]),
+ [Lconst(Const_base(Const_string (toplevel_name id, None)))],
+ no_apply_info)
+
+let toploop_setvalue id lam =
+ Lapply(Lprim(Pfield toploop_setvalue_pos,
+ [Lprim(Pgetglobal toploop_ident, [])]),
+ [Lconst(Const_base(Const_string (toplevel_name id, None))); lam],
+ no_apply_info)
+
+let toploop_setvalue_id id = toploop_setvalue id (Lvar id)
+
+let close_toplevel_term lam =
+ IdentSet.fold (fun id l -> Llet(Strict, id, toploop_getvalue id, l))
+ (free_variables lam) lam
+
+let transl_toplevel_item item =
+ match item.str_desc with
+ Tstr_eval (expr, _attrs) ->
+ transl_exp expr
+ | Tstr_value(rec_flag, pat_expr_list) ->
+ let idents = let_bound_idents pat_expr_list in
+ transl_let rec_flag pat_expr_list
+ (make_sequence toploop_setvalue_id idents)
+ | Tstr_typext(tyext) ->
+ let idents =
+ List.map (fun ext -> ext.ext_id) tyext.tyext_constructors
+ in
+ (* we need to use unique name in case of multiple
+ definitions of the same extension constructor in the toplevel *)
+ List.iter set_toplevel_unique_name idents;
+ transl_type_extension item.str_env None tyext
+ (make_sequence toploop_setvalue_id idents)
+ | Tstr_exception ext ->
+ set_toplevel_unique_name ext.ext_id;
+ toploop_setvalue ext.ext_id
+ (transl_extension_constructor item.str_env None ext)
+ | Tstr_module {mb_id=id; mb_expr=modl} ->
+ (* we need to use the unique name for the module because of issues
+ with "open" (PR#1672) *)
+ set_toplevel_unique_name id;
+ let lam = transl_module Tcoerce_none (Some(Pident id)) modl in
+ toploop_setvalue id lam
+ | Tstr_recmodule bindings ->
+ let idents = List.map (fun mb -> mb.mb_id) bindings in
+ compile_recmodule
+ (fun id modl -> transl_module Tcoerce_none (Some(Pident id)) modl)
+ bindings
+ (make_sequence toploop_setvalue_id idents)
+ | Tstr_class cl_list ->
+ (* we need to use unique names for the classes because there might
+ be a value named identically *)
+ let (ids, class_bindings) = transl_class_bindings cl_list in
+ List.iter set_toplevel_unique_name ids;
+ Lletrec(class_bindings, make_sequence toploop_setvalue_id ids)
+ | Tstr_include incl ->
+ let ids = bound_value_identifiers incl.incl_type in
+ let modl = incl.incl_mod in
+ let mid = Ident.create "include" in
+ let rec set_idents pos = function
+ [] ->
+ lambda_unit
+ | id :: ids ->
+ Lsequence(toploop_setvalue id (Lprim(Pfield pos, [Lvar mid])),
+ set_idents (pos + 1) ids) in
+ Llet(Strict, mid, transl_module Tcoerce_none None modl, set_idents 0 ids)
+ | Tstr_modtype _
+ | Tstr_open _
+ | Tstr_primitive _
+ | Tstr_type _
+ | Tstr_class_type _
+ | Tstr_attribute _ ->
+ lambda_unit
+
+let transl_toplevel_item_and_close itm =
+ close_toplevel_term (transl_label_init (transl_toplevel_item itm))
+
+let transl_toplevel_definition str =
+ reset_labels ();
+ make_sequence transl_toplevel_item_and_close str.str_items
+
+(* Compile the initialization code for a packed library *)
+
+let get_component = function
+ None -> Lconst const_unit
+ | Some id -> Lprim(Pgetglobal id, [])
+
+let transl_package component_names target_name coercion =
+ let components =
+ Lprim(Pmakeblock(0, Immutable), List.map get_component component_names) in
+ Lprim(Psetglobal target_name, [apply_coercion Strict coercion components])
+ (*
+ let components =
+ match coercion with
+ Tcoerce_none ->
+ List.map get_component component_names
+ | Tcoerce_structure (pos_cc_list, id_pos_list) ->
+ (* ignore id_pos_list as the ids are already bound *)
+ let g = Array.of_list component_names in
+ List.map
+ (fun (pos, cc) -> apply_coercion Strict cc (get_component g.(pos)))
+ pos_cc_list
+ | _ ->
+ assert false in
+ Lprim(Psetglobal target_name, [Lprim(Pmakeblock(0, Immutable), components)])
+ *)
+
+let transl_store_package component_names target_name coercion =
+ let rec make_sequence fn pos arg =
+ match arg with
+ [] -> lambda_unit
+ | hd :: tl -> Lsequence(fn pos hd, make_sequence fn (pos + 1) tl) in
+ match coercion with
+ Tcoerce_none ->
+ (List.length component_names,
+ make_sequence
+ (fun pos id ->
+ Lprim(Psetfield(pos, false),
+ [Lprim(Pgetglobal target_name, []);
+ get_component id]))
+ 0 component_names)
+ | Tcoerce_structure (pos_cc_list, id_pos_list) ->
+ let components =
+ Lprim(Pmakeblock(0, Immutable), List.map get_component component_names)
+ in
+ let blk = Ident.create "block" in
+ (List.length pos_cc_list,
+ Llet (Strict, blk, apply_coercion Strict coercion components,
+ make_sequence
+ (fun pos id ->
+ Lprim(Psetfield(pos, false),
+ [Lprim(Pgetglobal target_name, []);
+ Lprim(Pfield pos, [Lvar blk])]))
+ 0 pos_cc_list))
+ (*
+ (* ignore id_pos_list as the ids are already bound *)
+ let id = Array.of_list component_names in
+ (List.length pos_cc_list,
+ make_sequence
+ (fun dst (src, cc) ->
+ Lprim(Psetfield(dst, false),
+ [Lprim(Pgetglobal target_name, []);
+ apply_coercion Strict cc (get_component id.(src))]))
+ 0 pos_cc_list)
+ *)
+ | _ -> assert false
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ Circular_dependency id ->
+ fprintf ppf
+ "@[Cannot safely evaluate the definition@ \
+ of the recursively-defined module %a@]"
+ Printtyp.ident id
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, err) ->
+ Some (Location.error_of_printer loc report_error err)
+ | _ ->
+ None
+ )
+
+let reset () =
+ primitive_declarations := [];
+ transl_store_subst := Ident.empty;
+ toploop_ident.Ident.flags <- 0;
+ aliased_idents := Ident.empty
diff --git a/bytecomp/translmod.mli b/bytecomp/translmod.mli
new file mode 100644
index 0000000000..1d84aaabd2
--- /dev/null
+++ b/bytecomp/translmod.mli
@@ -0,0 +1,41 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translation from typed abstract syntax to lambda terms,
+ for the module language *)
+
+open Typedtree
+open Lambda
+
+val transl_implementation: string -> structure * module_coercion -> lambda
+val transl_store_phrases: string -> structure -> int * lambda
+val transl_store_implementation:
+ string -> structure * module_coercion -> int * lambda
+val transl_toplevel_definition: structure -> lambda
+val transl_package:
+ Ident.t option list -> Ident.t -> module_coercion -> lambda
+val transl_store_package:
+ Ident.t option list -> Ident.t -> module_coercion -> int * lambda
+
+val toplevel_name: Ident.t -> string
+val nat_toplevel_name: Ident.t -> Ident.t * int
+
+val primitive_declarations: Primitive.description list ref
+
+type error =
+ Circular_dependency of Ident.t
+
+exception Error of Location.t * error
+
+val report_error: Format.formatter -> error -> unit
+
+val reset: unit -> unit
diff --git a/bytecomp/translobj.ml b/bytecomp/translobj.ml
new file mode 100644
index 0000000000..a87a39e68b
--- /dev/null
+++ b/bytecomp/translobj.ml
@@ -0,0 +1,173 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Misc
+open Asttypes
+open Longident
+open Lambda
+
+(* Get oo primitives identifiers *)
+
+let oo_prim name =
+ try
+ transl_normal_path
+ (fst (Env.lookup_value (Ldot (Lident "CamlinternalOO", name)) Env.empty))
+ with Not_found ->
+ fatal_error ("Primitive " ^ name ^ " not found.")
+
+(* Share blocks *)
+
+let consts : (structured_constant, Ident.t) Hashtbl.t = Hashtbl.create 17
+
+let share c =
+ match c with
+ Const_block (n, l) when l <> [] ->
+ begin try
+ Lvar (Hashtbl.find consts c)
+ with Not_found ->
+ let id = Ident.create "shared" in
+ Hashtbl.add consts c id;
+ Lvar id
+ end
+ | _ -> Lconst c
+
+(* Collect labels *)
+
+let cache_required = ref false
+let method_cache = ref lambda_unit
+let method_count = ref 0
+let method_table = ref []
+
+let meth_tag s = Lconst(Const_base(Const_int(Btype.hash_variant s)))
+
+let next_cache tag =
+ let n = !method_count in
+ incr method_count;
+ (tag, [!method_cache; Lconst(Const_base(Const_int n))])
+
+let rec is_path = function
+ Lvar _ | Lprim (Pgetglobal _, []) | Lconst _ -> true
+ | Lprim (Pfield _, [lam]) -> is_path lam
+ | Lprim ((Parrayrefu _ | Parrayrefs _), [lam1; lam2]) ->
+ is_path lam1 && is_path lam2
+ | _ -> false
+
+let meth obj lab =
+ let tag = meth_tag lab in
+ if not (!cache_required && !Clflags.native_code) then (tag, []) else
+ if not (is_path obj) then next_cache tag else
+ try
+ let r = List.assoc obj !method_table in
+ try
+ (tag, List.assoc tag !r)
+ with Not_found ->
+ let p = next_cache tag in
+ r := p :: !r;
+ p
+ with Not_found ->
+ let p = next_cache tag in
+ method_table := (obj, ref [p]) :: !method_table;
+ p
+
+let reset_labels () =
+ Hashtbl.clear consts;
+ method_count := 0;
+ method_table := []
+
+(* Insert labels *)
+
+let string s = Lconst (Const_base (Const_string (s, None)))
+let int n = Lconst (Const_base (Const_int n))
+
+let prim_makearray =
+ Primitive.simple ~name:"caml_make_vect" ~arity:2 ~alloc:true
+
+(* Also use it for required globals *)
+let transl_label_init expr =
+ let expr =
+ Hashtbl.fold
+ (fun c id expr -> Llet(Alias, id, Lconst c, expr))
+ consts expr
+ in
+ let expr =
+ List.fold_right
+ (fun id expr -> Lsequence(Lprim(Pgetglobal id, []), expr))
+ (Env.get_required_globals ()) expr
+ in
+ Env.reset_required_globals ();
+ reset_labels ();
+ expr
+
+let transl_store_label_init glob size f arg =
+ method_cache := Lprim(Pfield size, [Lprim(Pgetglobal glob, [])]);
+ let expr = f arg in
+ let (size, expr) =
+ if !method_count = 0 then (size, expr) else
+ (size+1,
+ Lsequence(
+ Lprim(Psetfield(size, false),
+ [Lprim(Pgetglobal glob, []);
+ Lprim (Pccall prim_makearray, [int !method_count; int 0])]),
+ expr))
+ in
+ (size, transl_label_init expr)
+
+(* Share classes *)
+
+let wrapping = ref false
+let top_env = ref Env.empty
+let classes = ref []
+let method_ids = ref IdentSet.empty
+
+let oo_add_class id =
+ classes := id :: !classes;
+ (!top_env, !cache_required)
+
+let oo_wrap env req f x =
+ if !wrapping then
+ if !cache_required then f x else
+ try cache_required := true; let lam = f x in cache_required := false; lam
+ with exn -> cache_required := false; raise exn
+ else try
+ wrapping := true;
+ cache_required := req;
+ top_env := env;
+ classes := [];
+ method_ids := IdentSet.empty;
+ let lambda = f x in
+ let lambda =
+ List.fold_left
+ (fun lambda id ->
+ Llet(StrictOpt, id,
+ Lprim(Pmakeblock(0, Mutable),
+ [lambda_unit; lambda_unit; lambda_unit]),
+ lambda))
+ lambda !classes
+ in
+ wrapping := false;
+ top_env := Env.empty;
+ lambda
+ with exn ->
+ wrapping := false;
+ top_env := Env.empty;
+ raise exn
+
+let reset () =
+ Hashtbl.clear consts;
+ cache_required := false;
+ method_cache := lambda_unit;
+ method_count := 0;
+ method_table := [];
+ wrapping := false;
+ top_env := Env.empty;
+ classes := [];
+ method_ids := IdentSet.empty
diff --git a/bytecomp/translobj.mli b/bytecomp/translobj.mli
new file mode 100644
index 0000000000..a44ac683ff
--- /dev/null
+++ b/bytecomp/translobj.mli
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Lambda
+
+val oo_prim: string -> lambda
+
+val share: structured_constant -> lambda
+val meth: lambda -> string -> lambda * lambda list
+
+val reset_labels: unit -> unit
+val transl_label_init: lambda -> lambda
+val transl_store_label_init:
+ Ident.t -> int -> ('a -> lambda) -> 'a -> int * lambda
+
+val method_ids: IdentSet.t ref (* reset when starting a new wrapper *)
+
+val oo_wrap: Env.t -> bool -> ('a -> lambda) -> 'a -> lambda
+val oo_add_class: Ident.t -> Env.t * bool
+
+val reset: unit -> unit
diff --git a/bytecomp/typeopt.ml b/bytecomp/typeopt.ml
new file mode 100644
index 0000000000..5a2b593d14
--- /dev/null
+++ b/bytecomp/typeopt.ml
@@ -0,0 +1,137 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliaries for type-based optimizations, e.g. array kinds *)
+
+open Path
+open Types
+open Typedtree
+open Lambda
+
+let scrape env ty =
+ (Ctype.repr (Ctype.expand_head_opt env (Ctype.correct_levels ty))).desc
+
+let is_function_type env ty =
+ match scrape env ty with
+ | Tarrow (_, lhs, rhs, _) -> Some (lhs, rhs)
+ | _ -> None
+
+let is_base_type env ty base_ty_path =
+ match scrape env ty with
+ | Tconstr(p, _, _) -> Path.same p base_ty_path
+ | _ -> false
+
+let has_base_type exp base_ty_path =
+ is_base_type exp.exp_env exp.exp_type base_ty_path
+
+let maybe_pointer_type env typ =
+ match scrape env typ with
+ | Tconstr(p, args, abbrev) ->
+ not (Path.same p Predef.path_int) &&
+ not (Path.same p Predef.path_char) &&
+ begin try
+ match Env.find_type p env with
+ | {type_kind = Type_variant []} -> true (* type exn *)
+ | {type_kind = Type_variant cstrs} ->
+ List.exists (fun c -> c.Types.cd_args <> Cstr_tuple []) cstrs
+ | _ -> true
+ with Not_found -> true
+ (* This can happen due to e.g. missing -I options,
+ causing some .cmi files to be unavailable.
+ Maybe we should emit a warning. *)
+ end
+ | _ -> true
+
+let maybe_pointer exp = maybe_pointer_type exp.exp_env exp.exp_type
+
+let array_element_kind env ty =
+ match scrape env ty with
+ | Tvar _ | Tunivar _ ->
+ Pgenarray
+ | Tconstr(p, args, abbrev) ->
+ if Path.same p Predef.path_int || Path.same p Predef.path_char then
+ Pintarray
+ else if Path.same p Predef.path_float then
+ Pfloatarray
+ else if Path.same p Predef.path_string
+ || Path.same p Predef.path_array
+ || Path.same p Predef.path_nativeint
+ || Path.same p Predef.path_int32
+ || Path.same p Predef.path_int64 then
+ Paddrarray
+ else begin
+ try
+ match Env.find_type p env with
+ {type_kind = Type_abstract} ->
+ Pgenarray
+ | {type_kind = Type_variant cstrs}
+ when List.for_all (fun c -> c.Types.cd_args = Cstr_tuple [])
+ cstrs ->
+ Pintarray
+ | {type_kind = _} ->
+ Paddrarray
+ with Not_found ->
+ (* This can happen due to e.g. missing -I options,
+ causing some .cmi files to be unavailable.
+ Maybe we should emit a warning. *)
+ Pgenarray
+ end
+ | _ ->
+ Paddrarray
+
+let array_type_kind env ty =
+ match scrape env ty with
+ | Tconstr(p, [elt_ty], _) | Tpoly({desc = Tconstr(p, [elt_ty], _)}, _)
+ when Path.same p Predef.path_array ->
+ array_element_kind env elt_ty
+ | _ ->
+ (* This can happen with e.g. Obj.field *)
+ Pgenarray
+
+let array_kind exp = array_type_kind exp.exp_env exp.exp_type
+
+let array_pattern_kind pat = array_type_kind pat.pat_env pat.pat_type
+
+let bigarray_decode_type env ty tbl dfl =
+ match scrape env ty with
+ | Tconstr(Pdot(Pident mod_id, type_name, _), [], _)
+ when Ident.name mod_id = "Bigarray" ->
+ begin try List.assoc type_name tbl with Not_found -> dfl end
+ | _ ->
+ dfl
+
+let kind_table =
+ ["float32_elt", Pbigarray_float32;
+ "float64_elt", Pbigarray_float64;
+ "int8_signed_elt", Pbigarray_sint8;
+ "int8_unsigned_elt", Pbigarray_uint8;
+ "int16_signed_elt", Pbigarray_sint16;
+ "int16_unsigned_elt", Pbigarray_uint16;
+ "int32_elt", Pbigarray_int32;
+ "int64_elt", Pbigarray_int64;
+ "int_elt", Pbigarray_caml_int;
+ "nativeint_elt", Pbigarray_native_int;
+ "complex32_elt", Pbigarray_complex32;
+ "complex64_elt", Pbigarray_complex64]
+
+let layout_table =
+ ["c_layout", Pbigarray_c_layout;
+ "fortran_layout", Pbigarray_fortran_layout]
+
+let bigarray_type_kind_and_layout env typ =
+ match scrape env typ with
+ | Tconstr(p, [caml_type; elt_type; layout_type], abbrev) ->
+ (bigarray_decode_type env elt_type kind_table Pbigarray_unknown,
+ bigarray_decode_type env layout_type layout_table
+ Pbigarray_unknown_layout)
+ | _ ->
+ (Pbigarray_unknown, Pbigarray_unknown_layout)
diff --git a/bytecomp/typeopt.mli b/bytecomp/typeopt.mli
new file mode 100644
index 0000000000..2f52d92cc6
--- /dev/null
+++ b/bytecomp/typeopt.mli
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliaries for type-based optimizations, e.g. array kinds *)
+
+val is_function_type :
+ Env.t -> Types.type_expr -> (Types.type_expr * Types.type_expr) option
+val is_base_type : Env.t -> Types.type_expr -> Path.t -> bool
+val has_base_type : Typedtree.expression -> Path.t -> bool
+
+val maybe_pointer_type : Env.t -> Types.type_expr -> bool
+val maybe_pointer : Typedtree.expression -> bool
+
+val array_type_kind : Env.t -> Types.type_expr -> Lambda.array_kind
+val array_kind : Typedtree.expression -> Lambda.array_kind
+val array_pattern_kind : Typedtree.pattern -> Lambda.array_kind
+val bigarray_type_kind_and_layout :
+ Env.t -> Types.type_expr -> Lambda.bigarray_kind * Lambda.bigarray_layout
diff --git a/byterun/.depend b/byterun/.depend
new file mode 100644
index 0000000000..8ffd2448c8
--- /dev/null
+++ b/byterun/.depend
@@ -0,0 +1,748 @@
+alloc.o: alloc.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/mlvalues.h caml/stacks.h caml/memory.h
+array.o: array.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/mlvalues.h
+backtrace.o: backtrace.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/mlvalues.h caml/config.h \
+ caml/misc.h caml/alloc.h caml/mlvalues.h caml/custom.h caml/io.h \
+ caml/instruct.h caml/intext.h caml/io.h caml/exec.h caml/fix_code.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/startup.h caml/exec.h caml/stacks.h \
+ caml/memory.h caml/sys.h caml/backtrace.h caml/fail.h
+callback.o: callback.c caml/callback.h caml/compatibility.h \
+ caml/mlvalues.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/fail.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h caml/interp.h caml/instruct.h caml/fix_code.h \
+ caml/stacks.h caml/memory.h
+compact.o: compact.c caml/address_class.h caml/misc.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/mlvalues.h caml/config.h caml/finalise.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/freelist.h caml/gc.h \
+ caml/gc_ctrl.h caml/major_gc.h caml/memory.h caml/mlvalues.h \
+ caml/roots.h caml/weak.h
+compare.o: compare.c caml/custom.h caml/compatibility.h caml/mlvalues.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h caml/misc.h \
+ caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/misc.h caml/mlvalues.h
+custom.o: custom.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h
+debugger.o: debugger.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/config.h caml/debugger.h caml/misc.h caml/fail.h \
+ caml/fix_code.h caml/instruct.h caml/intext.h caml/io.h caml/io.h \
+ caml/mlvalues.h caml/stacks.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/sys.h
+dynlink.o: dynlink.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/dynlink.h caml/fail.h caml/mlvalues.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/osdeps.h caml/prims.h \
+ caml/signals.h
+extern.o: extern.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/gc.h caml/intext.h \
+ caml/io.h caml/io.h caml/md5.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/mlvalues.h caml/reverse.h
+fail.o: fail.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/io.h caml/gc.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/misc.h caml/mlvalues.h caml/printexc.h caml/signals.h caml/stacks.h \
+ caml/memory.h
+finalise.o: finalise.c caml/callback.h caml/compatibility.h \
+ caml/mlvalues.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/fail.h caml/mlvalues.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/signals.h
+fix_code.o: fix_code.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/debugger.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/fix_code.h caml/instruct.h \
+ caml/intext.h caml/io.h caml/md5.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/misc.h caml/mlvalues.h caml/reverse.h
+floats.o: floats.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/mlvalues.h \
+ caml/misc.h caml/reverse.h caml/stacks.h caml/memory.h
+freelist.o: freelist.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/freelist.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/gc.h caml/gc_ctrl.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/major_gc.h caml/misc.h caml/mlvalues.h
+gc_ctrl.o: gc_ctrl.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/compact.h caml/custom.h caml/finalise.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/freelist.h caml/gc.h \
+ caml/gc_ctrl.h caml/major_gc.h caml/minor_gc.h caml/misc.h \
+ caml/mlvalues.h caml/stacks.h
+globroots.o: globroots.c caml/memory.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/gc.h caml/mlvalues.h \
+ caml/misc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/memory.h caml/globroots.h caml/roots.h
+hash.o: hash.c caml/mlvalues.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/misc.h caml/custom.h \
+ caml/mlvalues.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/hash.h
+instrtrace.o: instrtrace.c
+intern.o: intern.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/callback.h caml/custom.h caml/fail.h caml/gc.h \
+ caml/intext.h caml/io.h caml/io.h caml/md5.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h caml/misc.h caml/reverse.h
+interp.o: interp.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/backtrace.h caml/exec.h caml/callback.h \
+ caml/debugger.h caml/fail.h caml/fix_code.h caml/instrtrace.h \
+ caml/instruct.h caml/interp.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/prims.h \
+ caml/signals.h caml/stacks.h caml/memory.h caml/startup_aux.h \
+ caml/jumptbl.h
+ints.o: ints.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/intext.h caml/io.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h
+io.o: io.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/alloc.h caml/misc.h caml/config.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/io.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/signals.h \
+ caml/sys.h
+lexing.o: lexing.c caml/fail.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/mlvalues.h caml/stacks.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h
+main.o: main.c caml/misc.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/misc.h \
+ caml/sys.h
+major_gc.o: major_gc.c caml/compact.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/misc.h caml/custom.h \
+ caml/mlvalues.h caml/config.h caml/fail.h caml/finalise.h caml/roots.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/freelist.h caml/gc.h caml/gc_ctrl.h \
+ caml/major_gc.h caml/misc.h caml/mlvalues.h caml/roots.h caml/weak.h
+md5.o: md5.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/md5.h caml/io.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/mlvalues.h \
+ caml/io.h caml/reverse.h
+memory.o: memory.c caml/address_class.h caml/misc.h caml/compatibility.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/freelist.h caml/gc.h caml/gc_ctrl.h \
+ caml/major_gc.h caml/freelist.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/minor_gc.h caml/address_class.h caml/minor_gc.h caml/misc.h \
+ caml/mlvalues.h caml/signals.h
+meta.o: meta.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/config.h caml/fail.h caml/fix_code.h caml/interp.h \
+ caml/intext.h caml/io.h caml/major_gc.h caml/freelist.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/minor_gc.h caml/address_class.h \
+ caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/prims.h caml/stacks.h \
+ caml/memory.h
+minor_gc.o: minor_gc.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/fail.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/finalise.h caml/roots.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/gc.h caml/gc_ctrl.h caml/major_gc.h \
+ caml/memory.h caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/signals.h caml/weak.h
+misc.o: misc.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/misc.h caml/config.h caml/memory.h caml/gc.h \
+ caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h
+obj.o: obj.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/gc.h caml/interp.h caml/major_gc.h caml/freelist.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/minor_gc.h caml/address_class.h \
+ caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/prims.h
+parsing.o: parsing.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/mlvalues.h caml/config.h \
+ caml/misc.h caml/memory.h caml/gc.h caml/mlvalues.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/alloc.h
+prims.o: prims.c caml/mlvalues.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/misc.h caml/prims.h
+printexc.o: printexc.c caml/backtrace.h caml/mlvalues.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/exec.h caml/callback.h \
+ caml/debugger.h caml/fail.h caml/misc.h caml/mlvalues.h caml/printexc.h
+roots.o: roots.c caml/finalise.h caml/roots.h caml/misc.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/memory.h caml/gc.h caml/mlvalues.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/globroots.h caml/major_gc.h caml/memory.h caml/minor_gc.h \
+ caml/misc.h caml/mlvalues.h caml/roots.h caml/stacks.h
+signals_byt.o: signals_byt.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/memory.h caml/config.h \
+ caml/gc.h caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/osdeps.h caml/signals.h \
+ caml/signals_machdep.h
+signals.o: signals.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/callback.h caml/config.h caml/fail.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/memory.h caml/signals.h caml/signals_machdep.h caml/sys.h
+stacks.o: stacks.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/fail.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/misc.h caml/mlvalues.h caml/stacks.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h
+startup_aux.o: startup_aux.c caml/backtrace.h caml/mlvalues.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/exec.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/startup_aux.h
+startup.o: startup.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/backtrace.h caml/exec.h \
+ caml/callback.h caml/custom.h caml/debugger.h caml/dynlink.h caml/exec.h \
+ caml/fail.h caml/fix_code.h caml/freelist.h caml/gc_ctrl.h \
+ caml/instrtrace.h caml/interp.h caml/intext.h caml/io.h caml/io.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/minor_gc.h caml/misc.h caml/mlvalues.h \
+ caml/osdeps.h caml/prims.h caml/printexc.h caml/reverse.h caml/signals.h \
+ caml/stacks.h caml/memory.h caml/sys.h caml/startup.h caml/startup_aux.h \
+ caml/version.h
+str.o: str.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/mlvalues.h caml/misc.h
+sys.o: sys.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/alloc.h caml/misc.h caml/config.h \
+ caml/mlvalues.h caml/debugger.h caml/fail.h caml/instruct.h \
+ caml/mlvalues.h caml/osdeps.h caml/signals.h caml/stacks.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/sys.h caml/gc_ctrl.h caml/io.h
+terminfo.o: terminfo.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/fail.h caml/io.h caml/mlvalues.h
+unix.o: unix.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/memory.h caml/config.h caml/gc.h \
+ caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/misc.h caml/osdeps.h
+weak.o: weak.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/mlvalues.h
+win32.o: win32.c caml/address_class.h caml/misc.h caml/compatibility.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/osdeps.h caml/signals.h caml/sys.h
+alloc.d.o: alloc.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/mlvalues.h caml/stacks.h caml/memory.h
+array.d.o: array.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/mlvalues.h
+backtrace.d.o: backtrace.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/mlvalues.h caml/config.h \
+ caml/misc.h caml/alloc.h caml/mlvalues.h caml/custom.h caml/io.h \
+ caml/instruct.h caml/intext.h caml/io.h caml/exec.h caml/fix_code.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/startup.h caml/exec.h caml/stacks.h \
+ caml/memory.h caml/sys.h caml/backtrace.h caml/fail.h
+callback.d.o: callback.c caml/callback.h caml/compatibility.h \
+ caml/mlvalues.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/fail.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h caml/interp.h caml/instruct.h caml/fix_code.h \
+ caml/stacks.h caml/memory.h
+compact.d.o: compact.c caml/address_class.h caml/misc.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/mlvalues.h caml/config.h caml/finalise.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/freelist.h caml/gc.h \
+ caml/gc_ctrl.h caml/major_gc.h caml/memory.h caml/mlvalues.h \
+ caml/roots.h caml/weak.h
+compare.d.o: compare.c caml/custom.h caml/compatibility.h caml/mlvalues.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h caml/misc.h \
+ caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/misc.h caml/mlvalues.h
+custom.d.o: custom.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h
+debugger.d.o: debugger.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/config.h caml/debugger.h caml/misc.h caml/fail.h \
+ caml/fix_code.h caml/instruct.h caml/intext.h caml/io.h caml/io.h \
+ caml/mlvalues.h caml/stacks.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/sys.h
+dynlink.d.o: dynlink.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/dynlink.h caml/fail.h caml/mlvalues.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/osdeps.h caml/prims.h \
+ caml/signals.h
+extern.d.o: extern.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/gc.h caml/intext.h \
+ caml/io.h caml/io.h caml/md5.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/mlvalues.h caml/reverse.h
+fail.d.o: fail.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/io.h caml/gc.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/misc.h caml/mlvalues.h caml/printexc.h caml/signals.h caml/stacks.h \
+ caml/memory.h
+finalise.d.o: finalise.c caml/callback.h caml/compatibility.h \
+ caml/mlvalues.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/fail.h caml/mlvalues.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/signals.h
+fix_code.d.o: fix_code.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/debugger.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/fix_code.h caml/instruct.h \
+ caml/intext.h caml/io.h caml/md5.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/misc.h caml/mlvalues.h caml/reverse.h
+floats.d.o: floats.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/mlvalues.h \
+ caml/misc.h caml/reverse.h caml/stacks.h caml/memory.h
+freelist.d.o: freelist.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/freelist.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/gc.h caml/gc_ctrl.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/major_gc.h caml/misc.h caml/mlvalues.h
+gc_ctrl.d.o: gc_ctrl.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/compact.h caml/custom.h caml/finalise.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/freelist.h caml/gc.h \
+ caml/gc_ctrl.h caml/major_gc.h caml/minor_gc.h caml/misc.h \
+ caml/mlvalues.h caml/stacks.h
+globroots.d.o: globroots.c caml/memory.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/gc.h caml/mlvalues.h \
+ caml/misc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/memory.h caml/globroots.h caml/roots.h
+hash.d.o: hash.c caml/mlvalues.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/misc.h caml/custom.h \
+ caml/mlvalues.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/hash.h
+instrtrace.d.o: instrtrace.c caml/instruct.h caml/misc.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/mlvalues.h caml/misc.h caml/opnames.h \
+ caml/prims.h caml/stacks.h caml/mlvalues.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/startup_aux.h
+intern.d.o: intern.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/callback.h caml/custom.h caml/fail.h caml/gc.h \
+ caml/intext.h caml/io.h caml/io.h caml/md5.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h caml/misc.h caml/reverse.h
+interp.d.o: interp.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/backtrace.h caml/exec.h caml/callback.h \
+ caml/debugger.h caml/fail.h caml/fix_code.h caml/instrtrace.h \
+ caml/instruct.h caml/interp.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/prims.h \
+ caml/signals.h caml/stacks.h caml/memory.h caml/startup_aux.h
+ints.d.o: ints.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/intext.h caml/io.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h
+io.d.o: io.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/alloc.h caml/misc.h caml/config.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/io.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/signals.h \
+ caml/sys.h
+lexing.d.o: lexing.c caml/fail.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/mlvalues.h caml/stacks.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h
+main.d.o: main.c caml/misc.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/misc.h \
+ caml/sys.h
+major_gc.d.o: major_gc.c caml/compact.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/misc.h caml/custom.h \
+ caml/mlvalues.h caml/config.h caml/fail.h caml/finalise.h caml/roots.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/freelist.h caml/gc.h caml/gc_ctrl.h \
+ caml/major_gc.h caml/misc.h caml/mlvalues.h caml/roots.h caml/weak.h
+md5.d.o: md5.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/md5.h caml/io.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/mlvalues.h \
+ caml/io.h caml/reverse.h
+memory.d.o: memory.c caml/address_class.h caml/misc.h caml/compatibility.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/freelist.h caml/gc.h caml/gc_ctrl.h \
+ caml/major_gc.h caml/freelist.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/minor_gc.h caml/address_class.h caml/minor_gc.h caml/misc.h \
+ caml/mlvalues.h caml/signals.h
+meta.d.o: meta.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/config.h caml/fail.h caml/fix_code.h caml/interp.h \
+ caml/intext.h caml/io.h caml/major_gc.h caml/freelist.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/minor_gc.h caml/address_class.h \
+ caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/prims.h caml/stacks.h \
+ caml/memory.h
+minor_gc.d.o: minor_gc.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/fail.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/finalise.h caml/roots.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/gc.h caml/gc_ctrl.h caml/major_gc.h \
+ caml/memory.h caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/signals.h caml/weak.h
+misc.d.o: misc.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/misc.h caml/config.h caml/memory.h caml/gc.h \
+ caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h
+obj.d.o: obj.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/gc.h caml/interp.h caml/major_gc.h caml/freelist.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/minor_gc.h caml/address_class.h \
+ caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/prims.h
+parsing.d.o: parsing.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/mlvalues.h caml/config.h \
+ caml/misc.h caml/memory.h caml/gc.h caml/mlvalues.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/alloc.h
+prims.d.o: prims.c caml/mlvalues.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/misc.h caml/prims.h
+printexc.d.o: printexc.c caml/backtrace.h caml/mlvalues.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/exec.h caml/callback.h \
+ caml/debugger.h caml/fail.h caml/misc.h caml/mlvalues.h caml/printexc.h
+roots.d.o: roots.c caml/finalise.h caml/roots.h caml/misc.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/memory.h caml/gc.h caml/mlvalues.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/globroots.h caml/major_gc.h caml/memory.h caml/minor_gc.h \
+ caml/misc.h caml/mlvalues.h caml/roots.h caml/stacks.h
+signals_byt.d.o: signals_byt.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/memory.h caml/config.h \
+ caml/gc.h caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/osdeps.h caml/signals.h \
+ caml/signals_machdep.h
+signals.d.o: signals.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/callback.h caml/config.h caml/fail.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/memory.h caml/signals.h caml/signals_machdep.h caml/sys.h
+stacks.d.o: stacks.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/fail.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/misc.h caml/mlvalues.h caml/stacks.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h
+startup_aux.d.o: startup_aux.c caml/backtrace.h caml/mlvalues.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/exec.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/startup_aux.h
+startup.d.o: startup.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/backtrace.h caml/exec.h \
+ caml/callback.h caml/custom.h caml/debugger.h caml/dynlink.h caml/exec.h \
+ caml/fail.h caml/fix_code.h caml/freelist.h caml/gc_ctrl.h \
+ caml/instrtrace.h caml/interp.h caml/intext.h caml/io.h caml/io.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/minor_gc.h caml/misc.h caml/mlvalues.h \
+ caml/osdeps.h caml/prims.h caml/printexc.h caml/reverse.h caml/signals.h \
+ caml/stacks.h caml/memory.h caml/sys.h caml/startup.h caml/startup_aux.h \
+ caml/version.h
+str.d.o: str.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/mlvalues.h caml/misc.h
+sys.d.o: sys.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/alloc.h caml/misc.h caml/config.h \
+ caml/mlvalues.h caml/debugger.h caml/fail.h caml/instruct.h \
+ caml/mlvalues.h caml/osdeps.h caml/signals.h caml/stacks.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/sys.h caml/gc_ctrl.h caml/io.h
+terminfo.d.o: terminfo.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/fail.h caml/io.h caml/mlvalues.h
+unix.d.o: unix.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/memory.h caml/config.h caml/gc.h \
+ caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/misc.h caml/osdeps.h
+weak.d.o: weak.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/mlvalues.h
+win32.d.o: win32.c caml/address_class.h caml/misc.h caml/compatibility.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/osdeps.h caml/signals.h caml/sys.h
+alloc.pic.o: alloc.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/mlvalues.h caml/stacks.h caml/memory.h
+array.pic.o: array.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/mlvalues.h
+backtrace.pic.o: backtrace.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/mlvalues.h caml/config.h \
+ caml/misc.h caml/alloc.h caml/mlvalues.h caml/custom.h caml/io.h \
+ caml/instruct.h caml/intext.h caml/io.h caml/exec.h caml/fix_code.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/startup.h caml/exec.h caml/stacks.h \
+ caml/memory.h caml/sys.h caml/backtrace.h caml/fail.h
+callback.pic.o: callback.c caml/callback.h caml/compatibility.h \
+ caml/mlvalues.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/fail.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h caml/interp.h caml/instruct.h caml/fix_code.h \
+ caml/stacks.h caml/memory.h
+compact.pic.o: compact.c caml/address_class.h caml/misc.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/mlvalues.h caml/config.h caml/finalise.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/freelist.h caml/gc.h \
+ caml/gc_ctrl.h caml/major_gc.h caml/memory.h caml/mlvalues.h \
+ caml/roots.h caml/weak.h
+compare.pic.o: compare.c caml/custom.h caml/compatibility.h caml/mlvalues.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h caml/misc.h \
+ caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/misc.h caml/mlvalues.h
+custom.pic.o: custom.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h
+debugger.pic.o: debugger.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/config.h caml/debugger.h caml/misc.h caml/fail.h \
+ caml/fix_code.h caml/instruct.h caml/intext.h caml/io.h caml/io.h \
+ caml/mlvalues.h caml/stacks.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/sys.h
+dynlink.pic.o: dynlink.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/dynlink.h caml/fail.h caml/mlvalues.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/osdeps.h caml/prims.h \
+ caml/signals.h
+extern.pic.o: extern.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/gc.h caml/intext.h \
+ caml/io.h caml/io.h caml/md5.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/mlvalues.h caml/reverse.h
+fail.pic.o: fail.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/io.h caml/gc.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/misc.h caml/mlvalues.h caml/printexc.h caml/signals.h caml/stacks.h \
+ caml/memory.h
+finalise.pic.o: finalise.c caml/callback.h caml/compatibility.h \
+ caml/mlvalues.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/fail.h caml/mlvalues.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/signals.h
+fix_code.pic.o: fix_code.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/debugger.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/fix_code.h caml/instruct.h \
+ caml/intext.h caml/io.h caml/md5.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/misc.h caml/mlvalues.h caml/reverse.h
+floats.pic.o: floats.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/mlvalues.h \
+ caml/misc.h caml/reverse.h caml/stacks.h caml/memory.h
+freelist.pic.o: freelist.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/freelist.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/gc.h caml/gc_ctrl.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/major_gc.h caml/misc.h caml/mlvalues.h
+gc_ctrl.pic.o: gc_ctrl.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/compact.h caml/custom.h caml/finalise.h \
+ caml/roots.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/freelist.h caml/gc.h \
+ caml/gc_ctrl.h caml/major_gc.h caml/minor_gc.h caml/misc.h \
+ caml/mlvalues.h caml/stacks.h
+globroots.pic.o: globroots.c caml/memory.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/gc.h caml/mlvalues.h \
+ caml/misc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/memory.h caml/globroots.h caml/roots.h
+hash.pic.o: hash.c caml/mlvalues.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/misc.h caml/custom.h \
+ caml/mlvalues.h caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/hash.h
+instrtrace.pic.o: instrtrace.c
+intern.pic.o: intern.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/callback.h caml/custom.h caml/fail.h caml/gc.h \
+ caml/intext.h caml/io.h caml/io.h caml/md5.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/mlvalues.h caml/misc.h caml/reverse.h
+interp.pic.o: interp.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/backtrace.h caml/exec.h caml/callback.h \
+ caml/debugger.h caml/fail.h caml/fix_code.h caml/instrtrace.h \
+ caml/instruct.h caml/interp.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/prims.h \
+ caml/signals.h caml/stacks.h caml/memory.h caml/startup_aux.h \
+ caml/jumptbl.h
+ints.pic.o: ints.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/intext.h caml/io.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h
+io.pic.o: io.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/alloc.h caml/misc.h caml/config.h \
+ caml/mlvalues.h caml/custom.h caml/fail.h caml/io.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/signals.h \
+ caml/sys.h
+lexing.pic.o: lexing.c caml/fail.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/mlvalues.h caml/stacks.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h
+main.pic.o: main.c caml/misc.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/misc.h \
+ caml/sys.h
+major_gc.pic.o: major_gc.c caml/compact.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/misc.h caml/custom.h \
+ caml/mlvalues.h caml/config.h caml/fail.h caml/finalise.h caml/roots.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/freelist.h caml/gc.h caml/gc_ctrl.h \
+ caml/major_gc.h caml/misc.h caml/mlvalues.h caml/roots.h caml/weak.h
+md5.pic.o: md5.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/md5.h caml/io.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/mlvalues.h \
+ caml/io.h caml/reverse.h
+memory.pic.o: memory.c caml/address_class.h caml/misc.h caml/compatibility.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/freelist.h caml/gc.h caml/gc_ctrl.h \
+ caml/major_gc.h caml/freelist.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/minor_gc.h caml/address_class.h caml/minor_gc.h caml/misc.h \
+ caml/mlvalues.h caml/signals.h
+meta.pic.o: meta.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/config.h caml/fail.h caml/fix_code.h caml/interp.h \
+ caml/intext.h caml/io.h caml/major_gc.h caml/freelist.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/minor_gc.h caml/address_class.h \
+ caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/prims.h caml/stacks.h \
+ caml/memory.h
+minor_gc.pic.o: minor_gc.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/fail.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/finalise.h caml/roots.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/gc.h caml/gc_ctrl.h caml/major_gc.h \
+ caml/memory.h caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/signals.h caml/weak.h
+misc.pic.o: misc.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/misc.h caml/config.h caml/memory.h caml/gc.h \
+ caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h
+obj.pic.o: obj.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/gc.h caml/interp.h caml/major_gc.h caml/freelist.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/minor_gc.h caml/address_class.h \
+ caml/minor_gc.h caml/misc.h caml/mlvalues.h caml/prims.h
+parsing.pic.o: parsing.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/mlvalues.h caml/config.h \
+ caml/misc.h caml/memory.h caml/gc.h caml/mlvalues.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/alloc.h
+prims.pic.o: prims.c caml/mlvalues.h caml/compatibility.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/misc.h caml/prims.h
+printexc.pic.o: printexc.c caml/backtrace.h caml/mlvalues.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/exec.h caml/callback.h \
+ caml/debugger.h caml/fail.h caml/misc.h caml/mlvalues.h caml/printexc.h
+roots.pic.o: roots.c caml/finalise.h caml/roots.h caml/misc.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/memory.h caml/gc.h caml/mlvalues.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/globroots.h caml/major_gc.h caml/memory.h caml/minor_gc.h \
+ caml/misc.h caml/mlvalues.h caml/roots.h caml/stacks.h
+signals_byt.pic.o: signals_byt.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/memory.h caml/config.h \
+ caml/gc.h caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/osdeps.h caml/signals.h \
+ caml/signals_machdep.h
+signals.pic.o: signals.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/callback.h caml/config.h caml/fail.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/misc.h caml/mlvalues.h caml/roots.h \
+ caml/memory.h caml/signals.h caml/signals_machdep.h caml/sys.h
+stacks.pic.o: stacks.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/fail.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/misc.h caml/mlvalues.h caml/stacks.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h
+startup_aux.pic.o: startup_aux.c caml/backtrace.h caml/mlvalues.h \
+ caml/compatibility.h caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/misc.h caml/exec.h caml/memory.h caml/gc.h \
+ caml/major_gc.h caml/freelist.h caml/minor_gc.h caml/address_class.h \
+ caml/startup_aux.h
+startup.pic.o: startup.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/backtrace.h caml/exec.h \
+ caml/callback.h caml/custom.h caml/debugger.h caml/dynlink.h caml/exec.h \
+ caml/fail.h caml/fix_code.h caml/freelist.h caml/gc_ctrl.h \
+ caml/instrtrace.h caml/interp.h caml/intext.h caml/io.h caml/io.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/minor_gc.h caml/misc.h caml/mlvalues.h \
+ caml/osdeps.h caml/prims.h caml/printexc.h caml/reverse.h caml/signals.h \
+ caml/stacks.h caml/memory.h caml/sys.h caml/startup.h caml/startup_aux.h \
+ caml/version.h
+str.pic.o: str.c caml/alloc.h caml/compatibility.h caml/misc.h caml/config.h \
+ caml/../../config/m.h caml/../../config/s.h caml/mlvalues.h caml/fail.h \
+ caml/mlvalues.h caml/misc.h
+sys.pic.o: sys.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/alloc.h caml/misc.h caml/config.h \
+ caml/mlvalues.h caml/debugger.h caml/fail.h caml/instruct.h \
+ caml/mlvalues.h caml/osdeps.h caml/signals.h caml/stacks.h caml/memory.h \
+ caml/gc.h caml/major_gc.h caml/freelist.h caml/minor_gc.h \
+ caml/address_class.h caml/sys.h caml/gc_ctrl.h caml/io.h
+terminfo.pic.o: terminfo.c caml/config.h caml/../../config/m.h \
+ caml/../../config/s.h caml/compatibility.h caml/alloc.h caml/misc.h \
+ caml/config.h caml/mlvalues.h caml/fail.h caml/io.h caml/mlvalues.h
+unix.pic.o: unix.c caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/compatibility.h caml/memory.h caml/config.h caml/gc.h \
+ caml/mlvalues.h caml/misc.h caml/major_gc.h caml/freelist.h \
+ caml/minor_gc.h caml/address_class.h caml/misc.h caml/osdeps.h
+weak.pic.o: weak.c caml/alloc.h caml/compatibility.h caml/misc.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/major_gc.h caml/freelist.h \
+ caml/memory.h caml/gc.h caml/major_gc.h caml/minor_gc.h \
+ caml/address_class.h caml/mlvalues.h
+win32.pic.o: win32.c caml/address_class.h caml/misc.h caml/compatibility.h \
+ caml/config.h caml/../../config/m.h caml/../../config/s.h \
+ caml/mlvalues.h caml/fail.h caml/memory.h caml/gc.h caml/major_gc.h \
+ caml/freelist.h caml/minor_gc.h caml/address_class.h caml/misc.h \
+ caml/osdeps.h caml/signals.h caml/sys.h
diff --git a/byterun/.ignore b/byterun/.ignore
new file mode 100644
index 0000000000..be5833e52d
--- /dev/null
+++ b/byterun/.ignore
@@ -0,0 +1,13 @@
+primitives
+prims.c
+ocamlrun
+ocamlrun.exe
+ocamlrund
+ocamlrund.exe
+ld.conf
+interp.a.lst
+*.[sd]obj
+*.lib
+.gdb_history
+*.d.c
+*.pic.c
diff --git a/byterun/Makefile b/byterun/Makefile
new file mode 100644
index 0000000000..ae57e2a7aa
--- /dev/null
+++ b/byterun/Makefile
@@ -0,0 +1,80 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include Makefile.common
+
+CFLAGS=-DCAML_NAME_SPACE $(BYTECCCOMPOPTS) $(IFLEXDIR)
+DFLAGS=-DCAML_NAME_SPACE -g -DDEBUG $(BYTECCCOMPOPTS) $(IFLEXDIR)
+
+OBJS=$(COMMONOBJS) $(UNIX_OR_WIN32).o main.o
+DOBJS=$(OBJS:.o=.d.o) instrtrace.d.o
+PICOBJS=$(OBJS:.o=.pic.o)
+
+all:: all-$(SHARED)
+
+ocamlrun$(EXE): libcamlrun.a prims.o
+ $(MKEXE) $(BYTECCLINKOPTS) -o ocamlrun$(EXE) \
+ prims.o libcamlrun.a $(BYTECCLIBS)
+
+ocamlrund$(EXE): libcamlrund.a prims.o
+ $(MKEXE) $(MKEXEDEBUGFLAG) $(BYTECCLINKOPTS) -o ocamlrund$(EXE) \
+ prims.o libcamlrund.a $(BYTECCLIBS)
+
+libcamlrun.a: $(OBJS)
+ $(ARCMD) rc libcamlrun.a $(OBJS)
+ $(RANLIB) libcamlrun.a
+
+libcamlrund.a: $(DOBJS)
+ $(ARCMD) rc libcamlrund.a $(DOBJS)
+ $(RANLIB) libcamlrund.a
+
+all-noshared:
+.PHONY: all-noshared
+
+all-shared: libcamlrun_pic.a libcamlrun_shared.so
+.PHONY: all-shared
+
+libcamlrun_pic.a: $(PICOBJS)
+ ar rc libcamlrun_pic.a $(PICOBJS)
+ $(RANLIB) libcamlrun_pic.a
+
+libcamlrun_shared.so: $(PICOBJS)
+ $(MKDLL) -o libcamlrun_shared.so $(PICOBJS) $(BYTECCLIBS)
+
+install:: install-$(SHARED)
+
+install-noshared:
+.PHONY: install-noshared
+
+install-shared:
+ cp libcamlrun_shared.so $(INSTALL_LIBDIR)/libcamlrun_shared.so
+ cp libcamlrun_pic.a $(INSTALL_LIBDIR)/libcamlrun_pic.a
+ cd $(INSTALL_LIBDIR); $(RANLIB) libcamlrun_pic.a
+.PHONY: install-shared
+
+clean::
+ rm -f libcamlrun_shared.so libcamlrun_pic.a
+
+%.d.o: %.c
+ $(CC) -c $(DFLAGS) $< -o $@
+
+%.pic.o: %.c
+ $(CC) -c $(CFLAGS) $(SHAREDCCCOMPOPTS) $< -o $@
+
+depend : prims.c caml/opnames.h caml/jumptbl.h caml/version.h
+ -$(CC) -MM $(BYTECCCOMPOPTS) *.c > .depend
+ -$(CC) -MM $(BYTECCCOMPOPTS) -DDEBUG *.c | sed -e 's/\.o/.d.o/' >> .depend
+ -$(CC) -MM $(BYTECCCOMPOPTS) *.c | sed -e 's/\.o/.pic.o/' >> .depend
+.PHONY: depend
+
+include .depend
diff --git a/byterun/Makefile.common b/byterun/Makefile.common
new file mode 100644
index 0000000000..7aef44a506
--- /dev/null
+++ b/byterun/Makefile.common
@@ -0,0 +1,136 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+
+CC=$(BYTECC)
+
+COMMONOBJS=\
+ interp.o misc.o stacks.o fix_code.o startup_aux.o startup.o \
+ freelist.o major_gc.o minor_gc.o memory.o alloc.o roots.o globroots.o \
+ fail.o signals.o signals_byt.o printexc.o backtrace_prim.o backtrace.o \
+ compare.o ints.o floats.o str.o array.o io.o extern.o intern.o \
+ hash.o sys.o meta.o parsing.o gc_ctrl.o terminfo.o md5.o obj.o \
+ lexing.o callback.o debugger.o weak.o compact.o finalise.o custom.o \
+ dynlink.o
+
+PRIMS=\
+ alloc.c array.c compare.c extern.c floats.c gc_ctrl.c hash.c \
+ intern.c interp.c ints.c io.c lexing.c md5.c meta.c obj.c parsing.c \
+ signals.c str.c sys.c terminfo.c callback.c weak.c finalise.c stacks.c \
+ dynlink.c backtrace_prim.c backtrace.c
+
+PUBLIC_INCLUDES=\
+ address_class.h alloc.h callback.h config.h custom.h fail.h gc.h \
+ hash.h intext.h \
+ memory.h misc.h mlvalues.h printexc.h signals.h compatibility.h \
+ version.h
+
+
+all:: ocamlrun$(EXE) ld.conf libcamlrun.$(A) all-$(RUNTIMED)
+.PHONY: all
+
+all-noruntimed:
+.PHONY: all-noruntimed
+
+all-runtimed: ocamlrund$(EXE) libcamlrund.$(A)
+.PHONY: all-runtimed
+
+ld.conf: ../config/Makefile
+ echo "$(STUBLIBDIR)" > ld.conf
+ echo "$(LIBDIR)" >> ld.conf
+
+# Installation
+
+INSTALL_BINDIR=$(DESTDIR)$(BINDIR)
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+
+
+install::
+ cp $(CAMLRUN)$(EXE) $(INSTALL_BINDIR)/ocamlrun$(EXE)
+ cp libcamlrun.$(A) $(INSTALL_LIBDIR)/libcamlrun.$(A)
+ cd $(INSTALL_LIBDIR); $(RANLIB) libcamlrun.$(A)
+ if test -d $(INSTALL_LIBDIR)/caml; then : ; \
+ else mkdir $(INSTALL_LIBDIR)/caml; fi
+ for i in $(PUBLIC_INCLUDES); do \
+ sed -f ../tools/cleanup-header caml/$$i > $(INSTALL_LIBDIR)/caml/$$i; \
+ done
+ cp ld.conf $(INSTALL_LIBDIR)/ld.conf
+.PHONY: install
+
+install:: install-$(RUNTIMED)
+
+install-noruntimed:
+.PHONY: install-noruntimed
+
+# TODO: when cross-compiling, do not install ocamlrund
+# it doesn't hurt to install it, but it's useless and might be confusing
+# because it's an executable for the target machine, while we're installing
+# binaries for the host.
+install-runtimed:
+ cp ocamlrund$(EXE) $(INSTALL_BINDIR)/ocamlrund$(EXE)
+ cp libcamlrund.$(A) $(INSTALL_LIBDIR)/libcamlrund.$(A)
+.PHONY: install-runtimed
+
+# If primitives contain duplicated lines (e.g. because the code is defined
+# like
+# #ifdef X
+# CAMLprim value caml_foo() ...
+# #else
+# CAMLprim value caml_foo() ...
+# end), horrible things will happen (duplicated entries in Runtimedef ->
+# double registration in Symtable -> empty entry in the PRIM table ->
+# the bytecode interpreter is confused).
+# We sort the primitive file and remove duplicates to avoid this problem.
+
+# Warning: we use "sort | uniq" instead of "sort -u" because in the MSVC
+# port, the "sort" program in the path is Microsoft's and not cygwin's
+
+primitives : $(PRIMS)
+ sed -n -e "s/CAMLprim value \([a-z0-9_][a-z0-9_]*\).*/\1/p" $(PRIMS) \
+ | sort | uniq > primitives
+
+prims.c : primitives
+ (echo '#include "caml/mlvalues.h"'; \
+ echo '#include "caml/prims.h"'; \
+ sed -e 's/.*/extern value &();/' primitives; \
+ echo 'c_primitive caml_builtin_cprim[] = {'; \
+ sed -e 's/.*/ &,/' primitives; \
+ echo ' 0 };'; \
+ echo 'char * caml_names_of_builtin_cprim[] = {'; \
+ sed -e 's/.*/ "&",/' primitives; \
+ echo ' 0 };') > prims.c
+
+caml/opnames.h : caml/instruct.h
+ sed -e '/\/\*/d' \
+ -e '/^#/d' \
+ -e 's/enum /char * names_of_/' \
+ -e 's/{$$/[] = {/' \
+ -e 's/\([[:upper:]][[:upper:]_0-9]*\)/"\1"/g' caml/instruct.h \
+ > caml/opnames.h
+
+# caml/jumptbl.h is required only if you have GCC 2.0 or later
+caml/jumptbl.h : caml/instruct.h
+ sed -n -e '/^ /s/ \([A-Z]\)/ \&\&lbl_\1/gp' \
+ -e '/^}/q' caml/instruct.h > caml/jumptbl.h
+
+caml/version.h : ../VERSION ../tools/make-version-header.sh
+ ../tools/make-version-header.sh ../VERSION > caml/version.h
+
+clean ::
+ rm -f ocamlrun$(EXE) ocamlrund$(EXE) *.$(O) *.$(A) *.$(SO)
+ rm -f primitives prims.c caml/opnames.h caml/jumptbl.h ld.conf
+ rm -f caml/version.h
+.PHONY: clean
diff --git a/byterun/Makefile.nt b/byterun/Makefile.nt
new file mode 100644
index 0000000000..257e364416
--- /dev/null
+++ b/byterun/Makefile.nt
@@ -0,0 +1,57 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include Makefile.common
+
+CFLAGS=-DOCAML_STDLIB_DIR='"$(LIBDIR)"' $(IFLEXDIR)
+
+DBGO=d.$(O)
+OBJS=$(COMMONOBJS:.o=.$(O)) win32.$(O) main.$(O)
+DOBJS=$(OBJS:.$(O)=.$(DBGO)) instrtrace.$(DBGO)
+
+ocamlrun$(EXE): libcamlrun.$(A) prims.$(O)
+ $(MKEXE) -o ocamlrun$(EXE) prims.$(O) $(call SYSLIB,ws2_32) \
+ $(EXTRALIBS) libcamlrun.$(A)
+
+ocamlrund$(EXE): libcamlrund.$(A) prims.$(O) main.$(O)
+ $(MKEXE) -o ocamlrund$(EXE) $(BYTECCDBGCOMPOPTS) prims.$(O) \
+ $(call SYSLIB,ws2_32) $(EXTRALIBS) libcamlrund.$(A)
+
+libcamlrun.$(A): $(OBJS)
+ $(call MKLIB,libcamlrun.$(A),$(OBJS))
+
+libcamlrund.$(A): $(DOBJS)
+ $(call MKLIB,libcamlrund.$(A),$(DOBJS))
+
+%.$(O): %.c
+ $(CC) $(CFLAGS) $(BYTECCCOMPOPTS) -c $<
+
+%.$(DBGO): %.c
+ $(CC) $(CFLAGS) $(BYTECCDBGCOMPOPTS) -c -o $@ $<
+
+.depend.nt: .depend
+ rm -f .depend.win32
+ echo "win32.o: win32.c caml/fail.h caml/compatibility.h \\"\
+ >> .depend.win32
+ echo " caml/misc.h caml/config.h ../config/m.h ../config/s.h \\"\
+ >> .depend.win32
+ echo " caml/mlvalues.h caml/memory.h caml/gc.h caml/major_gc.h \\"\
+ >> .depend.win32
+ echo " caml/freelist.h caml/minor_gc.h caml/osdeps.h caml/signals.h"\
+ >> .depend.win32
+ cat .depend >> .depend.win32
+ sed -e '/\.d\.o/q' -e 's/^\(.*\)\.o:/\1.$$(O) \1.$$(DBGO):/' \
+ .depend.win32 > .depend.nt
+ rm -f .depend.win32
+
+include .depend.nt
diff --git a/byterun/alloc.c b/byterun/alloc.c
new file mode 100644
index 0000000000..96a21bf1f5
--- /dev/null
+++ b/byterun/alloc.c
@@ -0,0 +1,200 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* 1. Allocation functions doing the same work as the macros in the
+ case where [Setup_for_gc] and [Restore_after_gc] are no-ops.
+ 2. Convenience functions related to allocation.
+*/
+
+#include <string.h>
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+#include "caml/stacks.h"
+
+#define Setup_for_gc
+#define Restore_after_gc
+
+CAMLexport value caml_alloc (mlsize_t wosize, tag_t tag)
+{
+ value result;
+ mlsize_t i;
+
+ Assert (tag < 256);
+ Assert (tag != Infix_tag);
+ if (wosize == 0){
+ result = Atom (tag);
+ }else if (wosize <= Max_young_wosize){
+ Alloc_small (result, wosize, tag);
+ if (tag < No_scan_tag){
+ for (i = 0; i < wosize; i++) Field (result, i) = Val_unit;
+ }
+ }else{
+ result = caml_alloc_shr (wosize, tag);
+ if (tag < No_scan_tag){
+ for (i = 0; i < wosize; i++) Field (result, i) = Val_unit;
+ }
+ result = caml_check_urgent_gc (result);
+ }
+ return result;
+}
+
+CAMLexport value caml_alloc_small (mlsize_t wosize, tag_t tag)
+{
+ value result;
+
+ Assert (wosize > 0);
+ Assert (wosize <= Max_young_wosize);
+ Assert (tag < 256);
+ Alloc_small (result, wosize, tag);
+ return result;
+}
+
+/* [n] is a number of words (fields) */
+CAMLexport value caml_alloc_tuple(mlsize_t n)
+{
+ return caml_alloc(n, 0);
+}
+
+/* [len] is a number of bytes (chars) */
+CAMLexport value caml_alloc_string (mlsize_t len)
+{
+ value result;
+ mlsize_t offset_index;
+ mlsize_t wosize = (len + sizeof (value)) / sizeof (value);
+
+ if (wosize <= Max_young_wosize) {
+ Alloc_small (result, wosize, String_tag);
+ }else{
+ result = caml_alloc_shr (wosize, String_tag);
+ result = caml_check_urgent_gc (result);
+ }
+ Field (result, wosize - 1) = 0;
+ offset_index = Bsize_wsize (wosize) - 1;
+ Byte (result, offset_index) = offset_index - len;
+ return result;
+}
+
+/* [len] is a number of words.
+ [mem] and [max] are relative (without unit).
+*/
+CAMLexport value caml_alloc_final (mlsize_t len, final_fun fun,
+ mlsize_t mem, mlsize_t max)
+{
+ return caml_alloc_custom(caml_final_custom_operations(fun),
+ len * sizeof(value), mem, max);
+}
+
+CAMLexport value caml_copy_string(char const *s)
+{
+ int len;
+ value res;
+
+ len = strlen(s);
+ res = caml_alloc_string(len);
+ memmove(String_val(res), s, len);
+ return res;
+}
+
+CAMLexport value caml_alloc_array(value (*funct)(char const *),
+ char const ** arr)
+{
+ CAMLparam0 ();
+ mlsize_t nbr, n;
+ CAMLlocal2 (v, result);
+
+ nbr = 0;
+ while (arr[nbr] != 0) nbr++;
+ if (nbr == 0) {
+ CAMLreturn (Atom(0));
+ } else {
+ result = caml_alloc (nbr, 0);
+ for (n = 0; n < nbr; n++) {
+ /* The two statements below must be separate because of evaluation
+ order (don't take the address &Field(result, n) before
+ calling funct, which may cause a GC and move result). */
+ v = funct(arr[n]);
+ caml_modify(&Field(result, n), v);
+ }
+ CAMLreturn (result);
+ }
+}
+
+CAMLexport value caml_copy_string_array(char const ** arr)
+{
+ return caml_alloc_array(caml_copy_string, arr);
+}
+
+CAMLexport int caml_convert_flag_list(value list, int *flags)
+{
+ int res;
+ res = 0;
+ while (list != Val_int(0)) {
+ res |= flags[Int_val(Field(list, 0))];
+ list = Field(list, 1);
+ }
+ return res;
+}
+
+/* For compiling let rec over values */
+
+/* [size] is a [value] representing number of words (fields) */
+CAMLprim value caml_alloc_dummy(value size)
+{
+ mlsize_t wosize = Int_val(size);
+
+ if (wosize == 0) return Atom(0);
+ return caml_alloc (wosize, 0);
+}
+
+/* [size] is a [value] representing number of words (fields) */
+CAMLprim value caml_alloc_dummy_function(value size,value arity)
+{
+ /* the arity argument is used by the js_of_ocaml runtime */
+ return caml_alloc_dummy(size);
+}
+
+/* [size] is a [value] representing number of floats. */
+CAMLprim value caml_alloc_dummy_float (value size)
+{
+ mlsize_t wosize = Int_val(size) * Double_wosize;
+
+ if (wosize == 0) return Atom(0);
+ return caml_alloc (wosize, 0);
+}
+
+CAMLprim value caml_update_dummy(value dummy, value newval)
+{
+ mlsize_t size, i;
+ tag_t tag;
+
+ size = Wosize_val(newval);
+ tag = Tag_val (newval);
+ Assert (size == Wosize_val(dummy));
+ Assert (tag < No_scan_tag || tag == Double_array_tag);
+
+ Tag_val(dummy) = tag;
+ if (tag == Double_array_tag){
+ size = Wosize_val (newval) / Double_wosize;
+ for (i = 0; i < size; i++){
+ Store_double_field (dummy, i, Double_field (newval, i));
+ }
+ }else{
+ for (i = 0; i < size; i++){
+ caml_modify (&Field(dummy, i), Field(newval, i));
+ }
+ }
+ return Val_unit;
+}
diff --git a/byterun/array.c b/byterun/array.c
new file mode 100644
index 0000000000..bb462a4e76
--- /dev/null
+++ b/byterun/array.c
@@ -0,0 +1,412 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Operations on arrays */
+
+#include <string.h>
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+
+/* returns number of elements (either fields or floats) */
+CAMLexport mlsize_t caml_array_length(value array)
+{
+ if (Tag_val(array) == Double_array_tag)
+ return Wosize_val(array) / Double_wosize;
+ else
+ return Wosize_val(array);
+}
+
+CAMLexport int caml_is_double_array(value array)
+{
+ return (Tag_val(array) == Double_array_tag);
+}
+
+CAMLprim value caml_array_get_addr(value array, value index)
+{
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx >= Wosize_val(array)) caml_array_bound_error();
+ return Field(array, idx);
+}
+
+CAMLprim value caml_array_get_float(value array, value index)
+{
+ intnat idx = Long_val(index);
+ double d;
+ value res;
+
+ if (idx < 0 || idx >= Wosize_val(array) / Double_wosize)
+ caml_array_bound_error();
+ d = Double_field(array, idx);
+#define Setup_for_gc
+#define Restore_after_gc
+ Alloc_small(res, Double_wosize, Double_tag);
+#undef Setup_for_gc
+#undef Restore_after_gc
+ Store_double_val(res, d);
+ return res;
+}
+
+CAMLprim value caml_array_get(value array, value index)
+{
+ if (Tag_val(array) == Double_array_tag)
+ return caml_array_get_float(array, index);
+ else
+ return caml_array_get_addr(array, index);
+}
+
+CAMLprim value caml_array_set_addr(value array, value index, value newval)
+{
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx >= Wosize_val(array)) caml_array_bound_error();
+ Modify(&Field(array, idx), newval);
+ return Val_unit;
+}
+
+CAMLprim value caml_array_set_float(value array, value index, value newval)
+{
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx >= Wosize_val(array) / Double_wosize)
+ caml_array_bound_error();
+ Store_double_field(array, idx, Double_val(newval));
+ return Val_unit;
+}
+
+CAMLprim value caml_array_set(value array, value index, value newval)
+{
+ if (Tag_val(array) == Double_array_tag)
+ return caml_array_set_float(array, index, newval);
+ else
+ return caml_array_set_addr(array, index, newval);
+}
+
+CAMLprim value caml_array_unsafe_get_float(value array, value index)
+{
+ double d;
+ value res;
+
+ d = Double_field(array, Long_val(index));
+#define Setup_for_gc
+#define Restore_after_gc
+ Alloc_small(res, Double_wosize, Double_tag);
+#undef Setup_for_gc
+#undef Restore_after_gc
+ Store_double_val(res, d);
+ return res;
+}
+
+CAMLprim value caml_array_unsafe_get(value array, value index)
+{
+ if (Tag_val(array) == Double_array_tag)
+ return caml_array_unsafe_get_float(array, index);
+ else
+ return Field(array, Long_val(index));
+}
+
+CAMLprim value caml_array_unsafe_set_addr(value array, value index,value newval)
+{
+ intnat idx = Long_val(index);
+ Modify(&Field(array, idx), newval);
+ return Val_unit;
+}
+
+CAMLprim value caml_array_unsafe_set_float(value array,value index,value newval)
+{
+ Store_double_field(array, Long_val(index), Double_val(newval));
+ return Val_unit;
+}
+
+CAMLprim value caml_array_unsafe_set(value array, value index, value newval)
+{
+ if (Tag_val(array) == Double_array_tag)
+ return caml_array_unsafe_set_float(array, index, newval);
+ else
+ return caml_array_unsafe_set_addr(array, index, newval);
+}
+
+/* [len] is a [value] representing number of floats */
+CAMLprim value caml_make_float_vect(value len)
+{
+ mlsize_t wosize = Long_val(len) * Double_wosize;
+ value result;
+ if (wosize == 0)
+ return Atom(0);
+ else if (wosize <= Max_young_wosize){
+#define Setup_for_gc
+#define Restore_after_gc
+ Alloc_small (result, wosize, Double_array_tag);
+#undef Setup_for_gc
+#undef Restore_after_gc
+ }else if (wosize > Max_wosize)
+ caml_invalid_argument("Array.create_float");
+ else {
+ result = caml_alloc_shr (wosize, Double_array_tag);
+ result = caml_check_urgent_gc (result);
+ }
+ return result;
+}
+
+/* [len] is a [value] representing number of words or floats */
+CAMLprim value caml_make_vect(value len, value init)
+{
+ CAMLparam2 (len, init);
+ CAMLlocal1 (res);
+ mlsize_t size, wsize, i;
+ double d;
+
+ size = Long_val(len);
+ if (size == 0) {
+ res = Atom(0);
+ }
+ else if (Is_block(init)
+ && Is_in_value_area(init)
+ && Tag_val(init) == Double_tag) {
+ d = Double_val(init);
+ wsize = size * Double_wosize;
+ if (wsize > Max_wosize) caml_invalid_argument("Array.make");
+ res = caml_alloc(wsize, Double_array_tag);
+ for (i = 0; i < size; i++) {
+ Store_double_field(res, i, d);
+ }
+ } else {
+ if (size > Max_wosize) caml_invalid_argument("Array.make");
+ if (size < Max_young_wosize) {
+ res = caml_alloc_small(size, 0);
+ for (i = 0; i < size; i++) Field(res, i) = init;
+ }
+ else if (Is_block(init) && Is_young(init)) {
+ caml_minor_collection();
+ res = caml_alloc_shr(size, 0);
+ for (i = 0; i < size; i++) Field(res, i) = init;
+ res = caml_check_urgent_gc (res);
+ }
+ else {
+ res = caml_alloc_shr(size, 0);
+ for (i = 0; i < size; i++) caml_initialize(&Field(res, i), init);
+ res = caml_check_urgent_gc (res);
+ }
+ }
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_make_array(value init)
+{
+ CAMLparam1 (init);
+ mlsize_t wsize, size, i;
+ CAMLlocal2 (v, res);
+
+ size = Wosize_val(init);
+ if (size == 0) {
+ CAMLreturn (init);
+ } else {
+ v = Field(init, 0);
+ if (Is_long(v)
+ || ! Is_in_value_area(v)
+ || Tag_val(v) != Double_tag) {
+ CAMLreturn (init);
+ } else {
+ wsize = size * Double_wosize;
+ if (wsize <= Max_young_wosize) {
+ res = caml_alloc_small(wsize, Double_array_tag);
+ } else {
+ res = caml_alloc_shr(wsize, Double_array_tag);
+ res = caml_check_urgent_gc(res);
+ }
+ for (i = 0; i < size; i++) {
+ Store_double_field(res, i, Double_val(Field(init, i)));
+ }
+ CAMLreturn (res);
+ }
+ }
+}
+
+/* Blitting */
+
+CAMLprim value caml_array_blit(value a1, value ofs1, value a2, value ofs2,
+ value n)
+{
+ value * src, * dst;
+ intnat count;
+
+ if (Tag_val(a2) == Double_array_tag) {
+ /* Arrays of floats. The values being copied are floats, not
+ pointer, so we can do a direct copy. memmove takes care of
+ potential overlap between the copied areas. */
+ memmove((double *)a2 + Long_val(ofs2),
+ (double *)a1 + Long_val(ofs1),
+ Long_val(n) * sizeof(double));
+ return Val_unit;
+ }
+ if (Is_young(a2)) {
+ /* Arrays of values, destination is in young generation.
+ Here too we can do a direct copy since this cannot create
+ old-to-young pointers, nor mess up with the incremental major GC.
+ Again, memmove takes care of overlap. */
+ memmove(&Field(a2, Long_val(ofs2)),
+ &Field(a1, Long_val(ofs1)),
+ Long_val(n) * sizeof(value));
+ return Val_unit;
+ }
+ /* Array of values, destination is in old generation.
+ We must use caml_modify. */
+ count = Long_val(n);
+ if (a1 == a2 && Long_val(ofs1) < Long_val(ofs2)) {
+ /* Copy in descending order */
+ for (dst = &Field(a2, Long_val(ofs2) + count - 1),
+ src = &Field(a1, Long_val(ofs1) + count - 1);
+ count > 0;
+ count--, src--, dst--) {
+ caml_modify(dst, *src);
+ }
+ } else {
+ /* Copy in ascending order */
+ for (dst = &Field(a2, Long_val(ofs2)), src = &Field(a1, Long_val(ofs1));
+ count > 0;
+ count--, src++, dst++) {
+ caml_modify(dst, *src);
+ }
+ }
+ /* Many caml_modify in a row can create a lot of old-to-young refs.
+ Give the minor GC a chance to run if it needs to. */
+ caml_check_urgent_gc(Val_unit);
+ return Val_unit;
+}
+
+/* A generic function for extraction and concatenation of sub-arrays */
+
+static value caml_array_gather(intnat num_arrays,
+ value arrays[/*num_arrays*/],
+ intnat offsets[/*num_arrays*/],
+ intnat lengths[/*num_arrays*/])
+{
+ CAMLparamN(arrays, num_arrays);
+ value res; /* no need to register it as a root */
+ int isfloat;
+ mlsize_t i, size, wsize, count, pos;
+ value * src;
+
+ /* Determine total size and whether result array is an array of floats */
+ size = 0;
+ isfloat = 0;
+ for (i = 0; i < num_arrays; i++) {
+ size += lengths[i];
+ if (Tag_val(arrays[i]) == Double_array_tag) isfloat = 1;
+ }
+ if (size == 0) {
+ /* If total size = 0, just return empty array */
+ res = Atom(0);
+ }
+ else if (isfloat) {
+ /* This is an array of floats. We can use memcpy directly. */
+ wsize = size * Double_wosize;
+ if (wsize > Max_wosize) caml_invalid_argument("Array.concat");
+ res = caml_alloc(wsize, Double_array_tag);
+ for (i = 0, pos = 0; i < num_arrays; i++) {
+ memcpy((double *)res + pos,
+ (double *)arrays[i] + offsets[i],
+ lengths[i] * sizeof(double));
+ pos += lengths[i];
+ }
+ Assert(pos == size);
+ }
+ else if (size > Max_wosize) {
+ /* Array of values, too big. */
+ caml_invalid_argument("Array.concat");
+ }
+ else if (size < Max_young_wosize) {
+ /* Array of values, small enough to fit in young generation.
+ We can use memcpy directly. */
+ res = caml_alloc_small(size, 0);
+ for (i = 0, pos = 0; i < num_arrays; i++) {
+ memcpy(&Field(res, pos),
+ &Field(arrays[i], offsets[i]),
+ lengths[i] * sizeof(value));
+ pos += lengths[i];
+ }
+ Assert(pos == size);
+ } else {
+ /* Array of values, must be allocated in old generation and filled
+ using caml_initialize. */
+ res = caml_alloc_shr(size, 0);
+ pos = 0;
+ for (i = 0, pos = 0; i < num_arrays; i++) {
+ for (src = &Field(arrays[i], offsets[i]), count = lengths[i];
+ count > 0;
+ count--, src++, pos++) {
+ caml_initialize(&Field(res, pos), *src);
+ }
+ }
+ Assert(pos == size);
+
+ /* Many caml_initialize in a row can create a lot of old-to-young
+ refs. Give the minor GC a chance to run if it needs to. */
+ res = caml_check_urgent_gc(res);
+ }
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_array_sub(value a, value ofs, value len)
+{
+ value arrays[1] = { a };
+ intnat offsets[1] = { Long_val(ofs) };
+ intnat lengths[1] = { Long_val(len) };
+ return caml_array_gather(1, arrays, offsets, lengths);
+}
+
+CAMLprim value caml_array_append(value a1, value a2)
+{
+ value arrays[2] = { a1, a2 };
+ intnat offsets[2] = { 0, 0 };
+ intnat lengths[2] = { caml_array_length(a1), caml_array_length(a2) };
+ return caml_array_gather(2, arrays, offsets, lengths);
+}
+
+CAMLprim value caml_array_concat(value al)
+{
+#define STATIC_SIZE 16
+ value static_arrays[STATIC_SIZE], * arrays;
+ intnat static_offsets[STATIC_SIZE], * offsets;
+ intnat static_lengths[STATIC_SIZE], * lengths;
+ intnat n, i;
+ value l, res;
+
+ /* Length of list = number of arrays */
+ for (n = 0, l = al; l != Val_int(0); l = Field(l, 1)) n++;
+ /* Allocate extra storage if too many arrays */
+ if (n <= STATIC_SIZE) {
+ arrays = static_arrays;
+ offsets = static_offsets;
+ lengths = static_lengths;
+ } else {
+ arrays = caml_stat_alloc(n * sizeof(value));
+ offsets = caml_stat_alloc(n * sizeof(intnat));
+ lengths = caml_stat_alloc(n * sizeof(value));
+ }
+ /* Build the parameters to caml_array_gather */
+ for (i = 0, l = al; l != Val_int(0); l = Field(l, 1), i++) {
+ arrays[i] = Field(l, 0);
+ offsets[i] = 0;
+ lengths[i] = caml_array_length(Field(l, 0));
+ }
+ /* Do the concatenation */
+ res = caml_array_gather(n, arrays, offsets, lengths);
+ /* Free the extra storage if needed */
+ if (n > STATIC_SIZE) {
+ caml_stat_free(arrays);
+ caml_stat_free(offsets);
+ caml_stat_free(lengths);
+ }
+ return res;
+}
diff --git a/byterun/backtrace.c b/byterun/backtrace.c
new file mode 100644
index 0000000000..37573281f0
--- /dev/null
+++ b/byterun/backtrace.c
@@ -0,0 +1,211 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Stack backtrace for uncaught exceptions */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "caml/alloc.h"
+#include "caml/memory.h"
+#include "caml/backtrace.h"
+#include "caml/backtrace_prim.h"
+#include "caml/fail.h"
+
+/* The table of debug information fragments */
+struct ext_table caml_debug_info;
+
+CAMLexport int caml_backtrace_active = 0;
+CAMLexport int caml_backtrace_pos = 0;
+CAMLexport backtrace_slot * caml_backtrace_buffer = NULL;
+CAMLexport value caml_backtrace_last_exn = Val_unit;
+
+void caml_init_backtrace(void)
+{
+ caml_register_global_root(&caml_backtrace_last_exn);
+}
+
+/* Start or stop the backtrace machinery */
+CAMLprim value caml_record_backtrace(value vflag)
+{
+ int flag = Int_val(vflag);
+
+ if (flag != caml_backtrace_active) {
+ caml_backtrace_active = flag;
+ caml_backtrace_pos = 0;
+ caml_backtrace_last_exn = Val_unit;
+ /* Note: lazy initialization of caml_backtrace_buffer in
+ caml_stash_backtrace to simplify the interface with the thread
+ libraries */
+ }
+ return Val_unit;
+}
+
+/* Return the status of the backtrace machinery */
+CAMLprim value caml_backtrace_status(value vunit)
+{
+ return Val_bool(caml_backtrace_active);
+}
+
+/* Print location information -- same behavior as in Printexc
+
+ note that the test for compiler-inserted raises is slightly redundant:
+ (!li->loc_valid && li->loc_is_raise)
+ caml_extract_location_info above guarantees that when li->loc_valid is
+ 0, then li->loc_is_raise is always 1, so the latter test is
+ useless. We kept it to keep code identical to the byterun/
+ implementation. */
+static void print_location(struct caml_loc_info * li, int index)
+{
+ char * info;
+
+ /* Ignore compiler-inserted raise */
+ if (!li->loc_valid && li->loc_is_raise) return;
+
+ if (li->loc_is_raise) {
+ /* Initial raise if index == 0, re-raise otherwise */
+ if (index == 0)
+ info = "Raised at";
+ else
+ info = "Re-raised at";
+ } else {
+ if (index == 0)
+ info = "Raised by primitive operation at";
+ else
+ info = "Called from";
+ }
+ if (! li->loc_valid) {
+ fprintf(stderr, "%s unknown location\n", info);
+ } else {
+ fprintf (stderr, "%s file \"%s\", line %d, characters %d-%d\n",
+ info, li->loc_filename, li->loc_lnum,
+ li->loc_startchr, li->loc_endchr);
+ }
+}
+
+/* Print a backtrace */
+CAMLexport void caml_print_exception_backtrace(void)
+{
+ int i;
+ struct caml_loc_info li;
+
+ if (!caml_debug_info_available()) {
+ fprintf(stderr, "(Cannot print stack backtrace: "
+ "no debug information available)\n");
+ return;
+ }
+
+ for (i = 0; i < caml_backtrace_pos; i++) {
+ caml_extract_location_info(caml_backtrace_buffer[i], &li);
+ print_location(&li, i);
+ }
+}
+
+/* Get a copy of the latest backtrace */
+CAMLprim value caml_get_exception_raw_backtrace(value unit)
+{
+ CAMLparam0();
+ CAMLlocal1(res);
+
+ /* Beware: the allocations below may cause finalizers to be run, and another
+ backtrace---possibly of a different length---to be stashed (for example
+ if the finalizer raises then catches an exception). We choose to ignore
+ any such finalizer backtraces and return the original one. */
+
+ if (!caml_backtrace_active ||
+ caml_backtrace_buffer == NULL ||
+ caml_backtrace_pos == 0) {
+ res = caml_alloc(0, 0);
+ }
+ else {
+ backtrace_slot saved_caml_backtrace_buffer[BACKTRACE_BUFFER_SIZE];
+ int saved_caml_backtrace_pos;
+ intnat i;
+
+ saved_caml_backtrace_pos = caml_backtrace_pos;
+
+ if (saved_caml_backtrace_pos > BACKTRACE_BUFFER_SIZE) {
+ saved_caml_backtrace_pos = BACKTRACE_BUFFER_SIZE;
+ }
+
+ memcpy(saved_caml_backtrace_buffer, caml_backtrace_buffer,
+ saved_caml_backtrace_pos * sizeof(backtrace_slot));
+
+ res = caml_alloc(saved_caml_backtrace_pos, 0);
+ for (i = 0; i < saved_caml_backtrace_pos; i++) {
+ Field(res, i) =
+ caml_val_raw_backtrace_slot(saved_caml_backtrace_buffer[i]);
+ }
+ }
+
+ CAMLreturn(res);
+}
+
+/* Convert the raw backtrace to a data structure usable from OCaml */
+CAMLprim value caml_convert_raw_backtrace_slot(value backtrace_slot)
+{
+ CAMLparam1(backtrace_slot);
+ CAMLlocal2(p, fname);
+ struct caml_loc_info li;
+
+ if (!caml_debug_info_available())
+ caml_failwith("No debug information available");
+
+ caml_extract_location_info(caml_raw_backtrace_slot_val(backtrace_slot), &li);
+
+ if (li.loc_valid) {
+ fname = caml_copy_string(li.loc_filename);
+ p = caml_alloc_small(5, 0);
+ Field(p, 0) = Val_bool(li.loc_is_raise);
+ Field(p, 1) = fname;
+ Field(p, 2) = Val_int(li.loc_lnum);
+ Field(p, 3) = Val_int(li.loc_startchr);
+ Field(p, 4) = Val_int(li.loc_endchr);
+ } else {
+ p = caml_alloc_small(1, 1);
+ Field(p, 0) = Val_bool(li.loc_is_raise);
+ }
+
+ CAMLreturn(p);
+}
+
+/* the function below is deprecated: we previously returned directly
+ the OCaml-usable representation, instead of the raw backtrace as an
+ abstract type, but this has a large performance overhead if you
+ store a lot of backtraces and print only some of them.
+
+ It is not used by the Printexc library anymore, or anywhere else in
+ the compiler, but we have kept it in case some user still depends
+ on it as an external. */
+CAMLprim value caml_get_exception_backtrace(value unit)
+{
+ CAMLparam0();
+ CAMLlocal3(arr, res, backtrace);
+ intnat i;
+
+ if (!caml_debug_info_available()) {
+ res = Val_int(0); /* None */
+ } else {
+ backtrace = caml_get_exception_raw_backtrace(Val_unit);
+
+ arr = caml_alloc(Wosize_val(backtrace), 0);
+ for (i = 0; i < Wosize_val(backtrace); i++) {
+ Store_field(arr, i, caml_convert_raw_backtrace_slot(Field(backtrace, i)));
+ }
+
+ res = caml_alloc_small(1, 0); Field(res, 0) = arr; /* Some */
+ }
+
+ CAMLreturn(res);
+}
diff --git a/byterun/backtrace_prim.c b/byterun/backtrace_prim.c
new file mode 100644
index 0000000000..699a1b7979
--- /dev/null
+++ b/byterun/backtrace_prim.c
@@ -0,0 +1,454 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Stack backtrace for uncaught exceptions */
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "caml/config.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+
+#include "caml/mlvalues.h"
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/io.h"
+#include "caml/instruct.h"
+#include "caml/intext.h"
+#include "caml/exec.h"
+#include "caml/fix_code.h"
+#include "caml/memory.h"
+#include "caml/startup.h"
+#include "caml/stacks.h"
+#include "caml/sys.h"
+#include "caml/backtrace.h"
+#include "caml/fail.h"
+#include "caml/backtrace_prim.h"
+
+/* The table of debug information fragments */
+struct ext_table caml_debug_info;
+
+CAMLexport char * caml_cds_file = NULL;
+
+/* Location of fields in the Instruct.debug_event record */
+enum {
+ EV_POS = 0,
+ EV_MODULE = 1,
+ EV_LOC = 2,
+ EV_KIND = 3
+};
+
+/* Location of fields in the Location.t record. */
+enum {
+ LOC_START = 0,
+ LOC_END = 1,
+ LOC_GHOST = 2
+};
+
+/* Location of fields in the Lexing.position record. */
+enum {
+ POS_FNAME = 0,
+ POS_LNUM = 1,
+ POS_BOL = 2,
+ POS_CNUM = 3
+};
+
+/* Runtime representation of the debug information, optimized
+ for quick lookup */
+struct ev_info {
+ code_t ev_pc;
+ char *ev_filename;
+ int ev_lnum;
+ int ev_startchr;
+ int ev_endchr;
+};
+
+struct debug_info {
+ code_t start;
+ code_t end;
+ mlsize_t num_events;
+ struct ev_info *events;
+ int already_read;
+};
+
+static struct debug_info *find_debug_info(code_t pc)
+{
+ int i;
+ for (i = 0; i < caml_debug_info.size; i++) {
+ struct debug_info *di = caml_debug_info.contents[i];
+ if (pc >= di->start && pc < di->end)
+ return di;
+ }
+ return NULL;
+}
+
+static int cmp_ev_info(const void *a, const void *b)
+{
+ code_t pc_a = ((const struct ev_info*)a)->ev_pc;
+ code_t pc_b = ((const struct ev_info*)b)->ev_pc;
+ if (pc_a > pc_b) return 1;
+ if (pc_a < pc_b) return -1;
+ return 0;
+}
+
+struct ev_info *process_debug_events(code_t code_start, value events_heap,
+ mlsize_t *num_events)
+{
+ CAMLparam1(events_heap);
+ CAMLlocal3(l, ev, ev_start);
+ mlsize_t i, j;
+ struct ev_info *events;
+
+ /* Compute the size of the required event buffer. */
+ *num_events = 0;
+ for (i = 0; i < caml_array_length(events_heap); i++)
+ for (l = Field(events_heap, i); l != Val_int(0); l = Field(l, 1))
+ (*num_events)++;
+
+ if (*num_events == 0)
+ CAMLreturnT(struct ev_info *, NULL);
+
+ events = malloc(*num_events * sizeof(struct ev_info));
+ if(events == NULL)
+ caml_fatal_error ("caml_add_debug_info: out of memory");
+
+ j = 0;
+ for (i = 0; i < caml_array_length(events_heap); i++) {
+ for (l = Field(events_heap, i); l != Val_int(0); l = Field(l, 1)) {
+ ev = Field(l, 0);
+
+ events[j].ev_pc = (code_t)((char*)code_start
+ + Long_val(Field(ev, EV_POS)));
+
+ ev_start = Field(Field(ev, EV_LOC), LOC_START);
+
+ {
+ uintnat fnsz = caml_string_length(Field(ev_start, POS_FNAME)) + 1;
+ events[j].ev_filename = (char*)malloc(fnsz);
+ if(events[j].ev_filename == NULL)
+ caml_fatal_error ("caml_add_debug_info: out of memory");
+ memcpy(events[j].ev_filename,
+ String_val(Field(ev_start, POS_FNAME)),
+ fnsz);
+ }
+
+ events[j].ev_lnum = Int_val(Field(ev_start, POS_LNUM));
+ events[j].ev_startchr =
+ Int_val(Field(ev_start, POS_CNUM))
+ - Int_val(Field(ev_start, POS_BOL));
+ events[j].ev_endchr =
+ Int_val(Field(Field(Field(ev, EV_LOC), LOC_END), POS_CNUM))
+ - Int_val(Field(ev_start, POS_BOL));
+
+ j++;
+ }
+ }
+
+ Assert(j == *num_events);
+
+ qsort(events, *num_events, sizeof(struct ev_info), cmp_ev_info);
+
+ CAMLreturnT(struct ev_info *, events);
+}
+
+/* Processes a (Instruct.debug_event list array) into a form suitable
+ for quick lookup and registers it for the (code_start,code_size) pc range. */
+CAMLprim value caml_add_debug_info(code_t code_start, value code_size,
+ value events_heap)
+{
+ CAMLparam1(events_heap);
+ struct debug_info *debug_info;
+
+ /* build the OCaml-side debug_info value */
+ debug_info = caml_stat_alloc(sizeof(struct debug_info));
+
+ debug_info->start = code_start;
+ debug_info->end = (code_t)((char*) code_start + Long_val(code_size));
+ if (events_heap == Val_unit) {
+ debug_info->events = NULL;
+ debug_info->num_events = 0;
+ debug_info->already_read = 0;
+ } else {
+ debug_info->events =
+ process_debug_events(code_start, events_heap, &debug_info->num_events);
+ debug_info->already_read = 1;
+ }
+
+ caml_ext_table_add(&caml_debug_info, debug_info);
+
+ CAMLreturn(Val_unit);
+}
+
+CAMLprim value caml_remove_debug_info(code_t start)
+{
+ CAMLparam0();
+ CAMLlocal2(dis, prev);
+
+ int i;
+ for (i = 0; i < caml_debug_info.size; i++) {
+ struct debug_info *di = caml_debug_info.contents[i];
+ if (di->start == start) {
+ /* note that caml_ext_table_remove calls caml_stat_free on the
+ removed resource, bracketing the caml_stat_alloc call in
+ caml_add_debug_info. */
+ caml_ext_table_remove(&caml_debug_info, di);
+ break;
+ }
+ }
+
+ CAMLreturn(Val_unit);
+}
+
+/* Store the return addresses contained in the given stack fragment
+ into the backtrace array */
+
+void caml_stash_backtrace(value exn, code_t pc, value * sp, int reraise)
+{
+ if (pc != NULL) pc = pc - 1;
+ if (exn != caml_backtrace_last_exn || !reraise) {
+ caml_backtrace_pos = 0;
+ caml_backtrace_last_exn = exn;
+ }
+
+ if (caml_backtrace_buffer == NULL) {
+ Assert(caml_backtrace_pos == 0);
+ caml_backtrace_buffer = malloc(BACKTRACE_BUFFER_SIZE * sizeof(code_t));
+ if (caml_backtrace_buffer == NULL) return;
+ }
+
+ if (caml_backtrace_pos >= BACKTRACE_BUFFER_SIZE) return;
+ /* testing the code region is needed: PR#1554 */
+ if (find_debug_info(pc) != NULL)
+ caml_backtrace_buffer[caml_backtrace_pos++] = pc;
+
+ /* Traverse the stack and put all values pointing into bytecode
+ into the backtrace buffer. */
+ for (/*nothing*/; sp < caml_trapsp; sp++) {
+ code_t p = (code_t) *sp;
+ if (caml_backtrace_pos >= BACKTRACE_BUFFER_SIZE) break;
+ if (find_debug_info(p) != NULL)
+ caml_backtrace_buffer[caml_backtrace_pos++] = p;
+ }
+}
+
+/* In order to prevent the GC from walking through the debug
+ information (which have no headers), we transform code pointers to
+ 31/63 bits ocaml integers by shifting them by 1 to the right. We do
+ not lose information as code pointers are aligned.
+
+ In particular, we do not need to use [caml_modify] when setting
+ an array element with such a value.
+*/
+value caml_val_raw_backtrace_slot(backtrace_slot pc)
+{
+ return Val_long ((uintnat)pc >> 1);
+}
+
+backtrace_slot caml_raw_backtrace_slot_val(value v)
+{
+ return ((backtrace_slot)(Long_val(v) << 1));
+}
+
+/* returns the next frame pointer (or NULL if none is available);
+ updates *sp to point to the following one, and *trsp to the next
+ trap frame, which we will skip when we reach it */
+
+code_t caml_next_frame_pointer(value ** sp, value ** trsp)
+{
+ while (*sp < caml_stack_high) {
+ code_t *p = (code_t*) (*sp)++;
+ if(&Trap_pc(*trsp) == p) {
+ *trsp = Trap_link(*trsp);
+ continue;
+ }
+
+ if (find_debug_info(*p) != NULL)
+ return *p;
+ }
+ return NULL;
+}
+
+/* Stores upto [max_frames_value] frames of the current call stack to
+ return to the user. This is used not in an exception-raising
+ context, but only when the user requests to save the trace
+ (hopefully less often). Instead of using a bounded buffer as
+ [caml_stash_backtrace], we first traverse the stack to compute the
+ right size, then allocate space for the trace. */
+
+CAMLprim value caml_get_current_callstack(value max_frames_value)
+{
+ CAMLparam1(max_frames_value);
+ CAMLlocal1(trace);
+
+ /* we use `intnat` here because, were it only `int`, passing `max_int`
+ from the OCaml side would overflow on 64bits machines. */
+ intnat max_frames = Long_val(max_frames_value);
+ intnat trace_size;
+
+ /* first compute the size of the trace */
+ {
+ value * sp = caml_extern_sp;
+ value * trsp = caml_trapsp;
+
+ for (trace_size = 0; trace_size < max_frames; trace_size++) {
+ code_t p = caml_next_frame_pointer(&sp, &trsp);
+ if (p == NULL) break;
+ }
+ }
+
+ trace = caml_alloc(trace_size, 0);
+
+ /* then collect the trace */
+ {
+ value * sp = caml_extern_sp;
+ value * trsp = caml_trapsp;
+ uintnat trace_pos;
+
+ for (trace_pos = 0; trace_pos < trace_size; trace_pos++) {
+ code_t p = caml_next_frame_pointer(&sp, &trsp);
+ Assert(p != NULL);
+ Store_field(trace, trace_pos, caml_val_raw_backtrace_slot(p));
+ }
+ }
+
+ CAMLreturn(trace);
+}
+
+/* Read the debugging info contained in the current bytecode executable. */
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+void read_main_debug_info(struct debug_info *di)
+{
+ CAMLparam0();
+ CAMLlocal3(events, evl, l);
+ char *exec_name;
+ int fd, num_events, orig, i;
+ struct channel *chan;
+ struct exec_trailer trail;
+
+ Assert(di->already_read == 0);
+ di->already_read = 1;
+
+ if (caml_cds_file != NULL) {
+ exec_name = caml_cds_file;
+ } else {
+ exec_name = caml_exe_name;
+ }
+
+ fd = caml_attempt_open(&exec_name, &trail, 1);
+ if (fd < 0){
+ caml_fatal_error ("executable program file not found");
+ CAMLreturn0;
+ }
+
+ caml_read_section_descriptors(fd, &trail);
+ if (caml_seek_optional_section(fd, &trail, "DBUG") != -1) {
+ chan = caml_open_descriptor_in(fd);
+
+ num_events = caml_getword(chan);
+ events = caml_alloc(num_events, 0);
+
+ for (i = 0; i < num_events; i++) {
+ orig = caml_getword(chan);
+ evl = caml_input_val(chan);
+ caml_input_val(chan); /* Skip the list of absolute directory names */
+ /* Relocate events in event list */
+ for (l = evl; l != Val_int(0); l = Field(l, 1)) {
+ value ev = Field(l, 0);
+ Field(ev, EV_POS) = Val_long(Long_val(Field(ev, EV_POS)) + orig);
+ }
+ /* Record event list */
+ Store_field(events, i, evl);
+ }
+
+ caml_close_channel(chan);
+
+ di->events = process_debug_events(caml_start_code, events, &di->num_events);
+ }
+
+ CAMLreturn0;
+}
+
+CAMLexport void caml_init_debug_info(void)
+{
+ caml_ext_table_init(&caml_debug_info, 1);
+ caml_add_debug_info(caml_start_code, Val_long(caml_code_size), Val_unit);
+}
+
+int caml_debug_info_available(void)
+{
+ return (caml_debug_info.size != 0);
+}
+
+/* Search the event index for the given PC. Return -1 if not found. */
+
+static struct ev_info *event_for_location(code_t pc)
+{
+ uintnat low, high;
+ struct debug_info *di = find_debug_info(pc);
+
+ if (di == NULL)
+ return NULL;
+
+ if (!di->already_read)
+ read_main_debug_info(di);
+
+ if (di->num_events == 0)
+ return NULL;
+
+ low = 0;
+ high = di->num_events;
+ while (low+1 < high) {
+ uintnat m = (low+high)/2;
+ if(pc < di->events[m].ev_pc) high = m;
+ else low = m;
+ }
+ if (di->events[low].ev_pc == pc)
+ return &di->events[low];
+ /* ocamlc sometimes moves an event past a following PUSH instruction;
+ allow mismatch by 1 instruction. */
+ if (di->events[low].ev_pc == pc + 1)
+ return &di->events[low];
+ if (low+1 < di->num_events && di->events[low+1].ev_pc == pc + 1)
+ return &di->events[low+1];
+
+ return NULL;
+}
+
+/* Extract location information for the given PC */
+
+void caml_extract_location_info(backtrace_slot slot,
+ /*out*/ struct caml_loc_info * li)
+{
+ code_t pc = slot;
+ struct ev_info *event = event_for_location(pc);
+ li->loc_is_raise =
+ caml_is_instruction(*pc, RAISE) ||
+ caml_is_instruction(*pc, RERAISE);
+ if (event == NULL) {
+ li->loc_valid = 0;
+ return;
+ }
+ li->loc_valid = 1;
+ li->loc_filename = event->ev_filename;
+ li->loc_lnum = event->ev_lnum;
+ li->loc_startchr = event->ev_startchr;
+ li->loc_endchr = event->ev_endchr;
+}
diff --git a/byterun/callback.c b/byterun/callback.c
new file mode 100644
index 0000000000..3010985162
--- /dev/null
+++ b/byterun/callback.c
@@ -0,0 +1,258 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Callbacks from C to OCaml */
+
+#include <string.h>
+#include "caml/callback.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+
+#ifndef NATIVE_CODE
+
+/* Bytecode callbacks */
+
+#include "caml/interp.h"
+#include "caml/instruct.h"
+#include "caml/fix_code.h"
+#include "caml/stacks.h"
+
+CAMLexport int caml_callback_depth = 0;
+
+#ifndef LOCAL_CALLBACK_BYTECODE
+static opcode_t callback_code[] = { ACC, 0, APPLY, 0, POP, 1, STOP };
+#endif
+
+
+#ifdef THREADED_CODE
+
+static int callback_code_threaded = 0;
+
+static void thread_callback(void)
+{
+ caml_thread_code(callback_code, sizeof(callback_code));
+ callback_code_threaded = 1;
+}
+
+#define Init_callback() if (!callback_code_threaded) thread_callback()
+
+#else
+
+#define Init_callback()
+
+#endif
+
+CAMLexport value caml_callbackN_exn(value closure, int narg, value args[])
+{
+ int i;
+ value res;
+
+ /* some alternate bytecode implementations (e.g. a JIT translator)
+ might require that the bytecode is kept in a local variable on
+ the C stack */
+#ifdef LOCAL_CALLBACK_BYTECODE
+ opcode_t local_callback_code[7];
+#endif
+
+ Assert(narg + 4 <= 256);
+
+ caml_extern_sp -= narg + 4;
+ for (i = 0; i < narg; i++) caml_extern_sp[i] = args[i]; /* arguments */
+#ifndef LOCAL_CALLBACK_BYTECODE
+ caml_extern_sp[narg] = (value) (callback_code + 4); /* return address */
+ caml_extern_sp[narg + 1] = Val_unit; /* environment */
+ caml_extern_sp[narg + 2] = Val_long(0); /* extra args */
+ caml_extern_sp[narg + 3] = closure;
+ Init_callback();
+ callback_code[1] = narg + 3;
+ callback_code[3] = narg;
+ res = caml_interprete(callback_code, sizeof(callback_code));
+#else /*have LOCAL_CALLBACK_BYTECODE*/
+ caml_extern_sp[narg] = (value) (local_callback_code + 4); /* return address */
+ caml_extern_sp[narg + 1] = Val_unit; /* environment */
+ caml_extern_sp[narg + 2] = Val_long(0); /* extra args */
+ caml_extern_sp[narg + 3] = closure;
+ local_callback_code[0] = ACC;
+ local_callback_code[1] = narg + 3;
+ local_callback_code[2] = APPLY;
+ local_callback_code[3] = narg;
+ local_callback_code[4] = POP;
+ local_callback_code[5] = 1;
+ local_callback_code[6] = STOP;
+#ifdef THREADED_CODE
+ caml_thread_code(local_callback_code, sizeof(local_callback_code));
+#endif /*THREADED_CODE*/
+ res = caml_interprete(local_callback_code, sizeof(local_callback_code));
+ caml_release_bytecode(local_callback_code, sizeof(local_callback_code));
+#endif /*LOCAL_CALLBACK_BYTECODE*/
+ if (Is_exception_result(res)) caml_extern_sp += narg + 4; /* PR#1228 */
+ return res;
+}
+
+CAMLexport value caml_callback_exn(value closure, value arg1)
+{
+ value arg[1];
+ arg[0] = arg1;
+ return caml_callbackN_exn(closure, 1, arg);
+}
+
+CAMLexport value caml_callback2_exn(value closure, value arg1, value arg2)
+{
+ value arg[2];
+ arg[0] = arg1;
+ arg[1] = arg2;
+ return caml_callbackN_exn(closure, 2, arg);
+}
+
+CAMLexport value caml_callback3_exn(value closure,
+ value arg1, value arg2, value arg3)
+{
+ value arg[3];
+ arg[0] = arg1;
+ arg[1] = arg2;
+ arg[2] = arg3;
+ return caml_callbackN_exn(closure, 3, arg);
+}
+
+#else
+
+/* Native-code callbacks. caml_callback[123]_exn are implemented in asm. */
+
+CAMLexport value caml_callbackN_exn(value closure, int narg, value args[])
+{
+ CAMLparam1 (closure);
+ CAMLxparamN (args, narg);
+ CAMLlocal1 (res);
+ int i;
+
+ res = closure;
+ for (i = 0; i < narg; /*nothing*/) {
+ /* Pass as many arguments as possible */
+ switch (narg - i) {
+ case 1:
+ res = caml_callback_exn(res, args[i]);
+ if (Is_exception_result(res)) CAMLreturn (res);
+ i += 1;
+ break;
+ case 2:
+ res = caml_callback2_exn(res, args[i], args[i + 1]);
+ if (Is_exception_result(res)) CAMLreturn (res);
+ i += 2;
+ break;
+ default:
+ res = caml_callback3_exn(res, args[i], args[i + 1], args[i + 2]);
+ if (Is_exception_result(res)) CAMLreturn (res);
+ i += 3;
+ break;
+ }
+ }
+ CAMLreturn (res);
+}
+
+#endif
+
+/* Exception-propagating variants of the above */
+
+CAMLexport value caml_callback (value closure, value arg)
+{
+ value res = caml_callback_exn(closure, arg);
+ if (Is_exception_result(res)) caml_raise(Extract_exception(res));
+ return res;
+}
+
+CAMLexport value caml_callback2 (value closure, value arg1, value arg2)
+{
+ value res = caml_callback2_exn(closure, arg1, arg2);
+ if (Is_exception_result(res)) caml_raise(Extract_exception(res));
+ return res;
+}
+
+CAMLexport value caml_callback3 (value closure, value arg1, value arg2,
+ value arg3)
+{
+ value res = caml_callback3_exn(closure, arg1, arg2, arg3);
+ if (Is_exception_result(res)) caml_raise(Extract_exception(res));
+ return res;
+}
+
+CAMLexport value caml_callbackN (value closure, int narg, value args[])
+{
+ value res = caml_callbackN_exn(closure, narg, args);
+ if (Is_exception_result(res)) caml_raise(Extract_exception(res));
+ return res;
+}
+
+/* Naming of OCaml values */
+
+struct named_value {
+ value val;
+ struct named_value * next;
+ char name[1];
+};
+
+#define Named_value_size 13
+
+static struct named_value * named_value_table[Named_value_size] = { NULL, };
+
+static unsigned int hash_value_name(char const *name)
+{
+ unsigned int h;
+ for (h = 0; *name != 0; name++) h = h * 19 + *name;
+ return h % Named_value_size;
+}
+
+CAMLprim value caml_register_named_value(value vname, value val)
+{
+ struct named_value * nv;
+ char * name = String_val(vname);
+ size_t namelen = strlen(name);
+ unsigned int h = hash_value_name(name);
+
+ for (nv = named_value_table[h]; nv != NULL; nv = nv->next) {
+ if (strcmp(name, nv->name) == 0) {
+ nv->val = val;
+ return Val_unit;
+ }
+ }
+ nv = (struct named_value *)
+ caml_stat_alloc(sizeof(struct named_value) + namelen);
+ memcpy(nv->name, name, namelen + 1);
+ nv->val = val;
+ nv->next = named_value_table[h];
+ named_value_table[h] = nv;
+ caml_register_global_root(&nv->val);
+ return Val_unit;
+}
+
+CAMLexport value * caml_named_value(char const *name)
+{
+ struct named_value * nv;
+ for (nv = named_value_table[hash_value_name(name)];
+ nv != NULL;
+ nv = nv->next) {
+ if (strcmp(name, nv->name) == 0) return &nv->val;
+ }
+ return NULL;
+}
+
+CAMLexport void caml_iterate_named_values(caml_named_action f)
+{
+ int i;
+ for(i = 0; i < Named_value_size; i++){
+ struct named_value * nv;
+ for (nv = named_value_table[i]; nv != NULL; nv = nv->next) {
+ f( &nv->val, nv->name );
+ }
+ }
+}
diff --git a/byterun/caml/.ignore b/byterun/caml/.ignore
new file mode 100644
index 0000000000..a4d2753904
--- /dev/null
+++ b/byterun/caml/.ignore
@@ -0,0 +1,3 @@
+jumptbl.h
+opnames.h
+version.h
diff --git a/byterun/caml/address_class.h b/byterun/caml/address_class.h
new file mode 100644
index 0000000000..2cf6c048a2
--- /dev/null
+++ b/byterun/caml/address_class.h
@@ -0,0 +1,82 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Classification of addresses for GC and runtime purposes. */
+
+#ifndef CAML_ADDRESS_CLASS_H
+#define CAML_ADDRESS_CLASS_H
+
+#include "misc.h"
+#include "mlvalues.h"
+
+/* Use the following macros to test an address for the different classes
+ it might belong to. */
+
+#define Is_young(val) \
+ (Assert (Is_block (val)), \
+ (addr)(val) < (addr)caml_young_end && (addr)(val) > (addr)caml_young_start)
+
+#define Is_in_heap(a) (Classify_addr(a) & In_heap)
+
+#define Is_in_heap_or_young(a) (Classify_addr(a) & (In_heap | In_young))
+
+#define Is_in_value_area(a) \
+ (Classify_addr(a) & (In_heap | In_young | In_static_data))
+
+#define Is_in_code_area(pc) \
+ ( ((char *)(pc) >= caml_code_area_start && \
+ (char *)(pc) <= caml_code_area_end) \
+ || (Classify_addr(pc) & In_code_area) )
+
+#define Is_in_static_data(a) (Classify_addr(a) & In_static_data)
+
+/***********************************************************************/
+/* The rest of this file is private and may change without notice. */
+
+extern value *caml_young_start, *caml_young_end;
+extern char * caml_code_area_start, * caml_code_area_end;
+
+#define Not_in_heap 0
+#define In_heap 1
+#define In_young 2
+#define In_static_data 4
+#define In_code_area 8
+
+#ifdef ARCH_SIXTYFOUR
+
+/* 64 bits: Represent page table as a sparse hash table */
+int caml_page_table_lookup(void * addr);
+#define Classify_addr(a) (caml_page_table_lookup((void *)(a)))
+
+#else
+
+/* 32 bits: Represent page table as a 2-level array */
+#define Pagetable2_log 11
+#define Pagetable2_size (1 << Pagetable2_log)
+#define Pagetable1_log (Page_log + Pagetable2_log)
+#define Pagetable1_size (1 << (32 - Pagetable1_log))
+CAMLextern unsigned char * caml_page_table[Pagetable1_size];
+
+#define Pagetable_index1(a) (((uintnat)(a)) >> Pagetable1_log)
+#define Pagetable_index2(a) \
+ ((((uintnat)(a)) >> Page_log) & (Pagetable2_size - 1))
+#define Classify_addr(a) \
+ caml_page_table[Pagetable_index1(a)][Pagetable_index2(a)]
+
+#endif
+
+int caml_page_table_add(int kind, void * start, void * end);
+int caml_page_table_remove(int kind, void * start, void * end);
+int caml_page_table_initialize(mlsize_t bytesize);
+
+#endif /* CAML_ADDRESS_CLASS_H */
diff --git a/byterun/caml/alloc.h b/byterun/caml/alloc.h
new file mode 100644
index 0000000000..9fbca4d906
--- /dev/null
+++ b/byterun/caml/alloc.h
@@ -0,0 +1,54 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_ALLOC_H
+#define CAML_ALLOC_H
+
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "misc.h"
+#include "mlvalues.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAMLextern value caml_alloc (mlsize_t wosize, tag_t);
+CAMLextern value caml_alloc_small (mlsize_t wosize, tag_t);
+CAMLextern value caml_alloc_tuple (mlsize_t wosize);
+CAMLextern value caml_alloc_string (mlsize_t len); /* len in bytes (chars) */
+CAMLextern value caml_copy_string (char const *);
+CAMLextern value caml_copy_string_array (char const **);
+CAMLextern value caml_copy_double (double);
+CAMLextern value caml_copy_int32 (int32_t); /* defined in [ints.c] */
+CAMLextern value caml_copy_int64 (int64_t); /* defined in [ints.c] */
+CAMLextern value caml_copy_nativeint (intnat); /* defined in [ints.c] */
+CAMLextern value caml_alloc_array (value (*funct) (char const *),
+ char const ** array);
+CAMLextern value caml_alloc_sprintf(const char * format, ...);
+
+typedef void (*final_fun)(value);
+CAMLextern value caml_alloc_final (mlsize_t wosize,
+ final_fun, /*finalization function*/
+ mlsize_t, /*resources consumed*/
+ mlsize_t /*max resources*/);
+
+CAMLextern int caml_convert_flag_list (value, int *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_ALLOC_H */
diff --git a/byterun/caml/backtrace.h b/byterun/caml/backtrace.h
new file mode 100644
index 0000000000..dd735c4a53
--- /dev/null
+++ b/byterun/caml/backtrace.h
@@ -0,0 +1,130 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_BACKTRACE_H
+#define CAML_BACKTRACE_H
+
+#include "mlvalues.h"
+#include "exec.h"
+
+/* Runtime support for backtrace generation.
+ *
+ * It has two kind of users:
+ * - high-level API to capture and decode backtraces;
+ * - low-level runtime routines, to introspect machine state and determine
+ * whether a backtrace should be generated when using "raise".
+ *
+ * Backtrace generation is split in multiple steps.
+ * The lowest-level one, done by [backtrace_prim.c] just fills the
+ * [caml_backtrace_buffer] variable each time a frame is unwinded.
+ * At that point, we don't know whether the backtrace will be useful or not so
+ * this code should be as fast as possible.
+ *
+ * If the backtrace happens to be useful, later passes will read
+ * [caml_backtrace_buffer] and turn it into a [raw_backtrace] and then a
+ * [backtrace].
+ * This is done in [backtrace.c] and [stdlib/printexc.ml].
+ *
+ * Content of buffers
+ * ------------------
+ *
+ * [caml_backtrace_buffer] (really cheap)
+ * Backend and process image dependent, abstracted by C-type backtrace_slot.
+ * [raw_backtrace] (cheap)
+ * OCaml values of abstract type [Printexc.raw_backtrace_slot],
+ * still backend and process image dependent (unsafe to marshal).
+ * [backtrace] (more expensive)
+ * OCaml values of algebraic data-type [Printexc.backtrace_slot]
+ */
+
+/* Non zero iff backtraces are recorded.
+ * One should use to change this variable [caml_record_backtrace].
+ */
+CAMLextern int caml_backtrace_active;
+
+/* The [backtrace_slot] type represents values stored in the
+ * [caml_backtrace_buffer]. In bytecode, it is the same as a
+ * [code_t], in native code it as a [frame_descr *]. The difference
+ * doesn't matter for code outside [backtrace_prim.c], so it is just
+ * exposed as a [backtrace_slot].
+ */
+typedef void * backtrace_slot;
+
+/* The [caml_backtrace_buffer] and [caml_backtrace_last_exn]
+ * variables are valid only if [caml_backtrace_active != 0].
+ *
+ * They are part of the state specific to each thread, and threading libraries
+ * are responsible for copying them on context switch.
+ * See [otherlibs/systhreads/st_stubs.c] and [otherlibs/threads/scheduler.c].
+ */
+
+/* [caml_backtrace_buffer] is filled by runtime when unwinding stack.
+ * It is an array ranging from [0] to [caml_backtrace_pos - 1].
+ * [caml_backtrace_pos] is always zero if [!caml_backtrace_active].
+ *
+ * Its maximum size is determined by [BACKTRACE_BUFFER_SIZE] from
+ * [backtrace_prim.h], but this shouldn't affect users.
+ */
+CAMLextern backtrace_slot * caml_backtrace_buffer;
+CAMLextern int caml_backtrace_pos;
+
+/* [caml_backtrace_last_exn] stores the last exception value that was raised,
+ * iff [caml_backtrace_active != 0].
+ * It is tested for equality to determine whether a raise is a re-raise of the
+ * same exception.
+ *
+ * FIXME: this shouldn't matter anymore. Since OCaml 4.02, non-parameterized
+ * exceptions are constant, so physical equality is no longer appropriate.
+ * raise and re-raise are distinguished by:
+ * - passing reraise = 1 to [caml_stash_backtrace] (see below) in the bytecode
+ * interpreter;
+ * - directly resetting [caml_backtrace_pos] to 0 in native runtimes for raise.
+ */
+CAMLextern value caml_backtrace_last_exn;
+
+/* [caml_record_backtrace] toggle backtrace recording on and off.
+ * This function can be called at runtime by user-code, or during
+ * initialization if backtraces were requested.
+ *
+ * It might be called before GC initialization, so it shouldn't do OCaml
+ * allocation.
+ */
+CAMLprim value caml_record_backtrace(value vflag);
+
+
+#ifndef NATIVE_CODE
+
+/* Path to the file containing debug information, if any, or NULL. */
+CAMLextern char * caml_cds_file;
+
+/* Primitive called _only_ by runtime to record unwinded frames to
+ * backtrace. A similar primitive exists for native code, but with a
+ * different prototype. */
+extern void caml_stash_backtrace(value exn, code_t pc, value * sp, int reraise);
+
+#endif
+
+
+/* Default (C-level) printer for backtraces. It is called if an
+ * exception causes a termination of the program or of a thread.
+ *
+ * [Printexc] provide a higher-level printer mimicking its output but making
+ * use of registered exception printers, and is used when possible in place of
+ * this function after [Printexc] initialization.
+ */
+CAMLextern void caml_print_exception_backtrace(void);
+
+void caml_init_backtrace(void);
+CAMLexport void caml_init_debug_info(void);
+
+#endif /* CAML_BACKTRACE_H */
diff --git a/byterun/caml/backtrace_prim.h b/byterun/caml/backtrace_prim.h
new file mode 100644
index 0000000000..bc2eb36af0
--- /dev/null
+++ b/byterun/caml/backtrace_prim.h
@@ -0,0 +1,67 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_BACKTRACE_PRIM_H
+#define CAML_BACKTRACE_PRIM_H
+
+#include "backtrace.h"
+
+/* Backtrace generation is split in [backtrace.c] and [backtrace_prim.c].
+ *
+ * [backtrace_prim.c] contains all backend-specific code, and has two different
+ * implementations in [byterun/backtrace_prim.c] and [asmrun/backtrace_prim.c].
+ *
+ * [backtrace.c] has a unique implementation, and expose a uniform
+ * higher level API above [backtrace_prim.c].
+ */
+
+/* Extract location information for the given raw_backtrace_slot */
+
+struct caml_loc_info {
+ int loc_valid;
+ int loc_is_raise;
+ char * loc_filename;
+ int loc_lnum;
+ int loc_startchr;
+ int loc_endchr;
+};
+
+/* Check availability of debug information before extracting a trace.
+ * Relevant for bytecode, always true for native code. */
+int caml_debug_info_available(void);
+
+/* Extract locations from backtrace_slot */
+void caml_extract_location_info(backtrace_slot pc,
+ /*out*/ struct caml_loc_info * li);
+
+/* Expose a [backtrace_slot] as a OCaml value of type [raw_backtrace_slot].
+ * The value returned should be an immediate and not an OCaml block, so that it
+ * is safe to store using direct assignment and [Field], and not [Store_field] /
+ * [caml_modify]. */
+value caml_val_raw_backtrace_slot(backtrace_slot pc);
+backtrace_slot caml_raw_backtrace_slot_val(value slot);
+
+#define BACKTRACE_BUFFER_SIZE 1024
+
+/* Besides decoding backtrace info, [backtrace_prim] has two other
+ * responsibilities:
+ *
+ * It defines the [caml_stash_backtrace] function, which is called to quickly
+ * fill the backtrace buffer by walking the stack when an exception is raised.
+ *
+ * It also defines the [caml_get_current_callstack] OCaml primitive, which also
+ * walks the stack but directly turns it into a [raw_backtrace] and is called
+ * explicitly.
+ */
+
+#endif /* CAML_BACKTRACE_PRIM_H */
diff --git a/byterun/caml/callback.h b/byterun/caml/callback.h
new file mode 100644
index 0000000000..ef50945cfc
--- /dev/null
+++ b/byterun/caml/callback.h
@@ -0,0 +1,57 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Callbacks from C to OCaml */
+
+#ifndef CAML_CALLBACK_H
+#define CAML_CALLBACK_H
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "mlvalues.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAMLextern value caml_callback (value closure, value arg);
+CAMLextern value caml_callback2 (value closure, value arg1, value arg2);
+CAMLextern value caml_callback3 (value closure, value arg1, value arg2,
+ value arg3);
+CAMLextern value caml_callbackN (value closure, int narg, value args[]);
+
+CAMLextern value caml_callback_exn (value closure, value arg);
+CAMLextern value caml_callback2_exn (value closure, value arg1, value arg2);
+CAMLextern value caml_callback3_exn (value closure,
+ value arg1, value arg2, value arg3);
+CAMLextern value caml_callbackN_exn (value closure, int narg, value args[]);
+
+#define Make_exception_result(v) ((v) | 2)
+#define Is_exception_result(v) (((v) & 3) == 2)
+#define Extract_exception(v) ((v) & ~3)
+
+CAMLextern value * caml_named_value (char const * name);
+typedef void (*caml_named_action) (value*, char *);
+CAMLextern void caml_iterate_named_values(caml_named_action f);
+
+CAMLextern void caml_main (char ** argv);
+CAMLextern void caml_startup (char ** argv);
+
+CAMLextern int caml_callback_depth;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/byterun/caml/compact.h b/byterun/caml/compact.h
new file mode 100644
index 0000000000..2abac167f3
--- /dev/null
+++ b/byterun/caml/compact.h
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_COMPACT_H
+#define CAML_COMPACT_H
+
+
+#include "config.h"
+#include "misc.h"
+
+extern void caml_compact_heap (void);
+extern void caml_compact_heap_maybe (void);
+
+
+#endif /* CAML_COMPACT_H */
diff --git a/byterun/caml/compare.h b/byterun/caml/compare.h
new file mode 100644
index 0000000000..41d6a0c9bb
--- /dev/null
+++ b/byterun/caml/compare.h
@@ -0,0 +1,19 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, Projet Moscova, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_COMPARE_H
+#define CAML_COMPARE_H
+
+CAMLextern int caml_compare_unordered;
+
+#endif /* CAML_COMPARE_H */
diff --git a/byterun/caml/compatibility.h b/byterun/caml/compatibility.h
new file mode 100644
index 0000000000..a4e4b04cfa
--- /dev/null
+++ b/byterun/caml/compatibility.h
@@ -0,0 +1,373 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Moscova, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* definitions for compatibility with old identifiers */
+
+#ifndef CAML_COMPATIBILITY_H
+#define CAML_COMPATIBILITY_H
+
+/* internal global variables renamed between 4.02.1 and 4.03.0 */
+#define caml_stat_top_heap_size Bsize_wsize(caml_stat_top_heap_wsz)
+#define caml_stat_heap_size Bsize_wsize(caml_stat_heap_wsz)
+
+#ifndef CAML_NAME_SPACE
+
+/*
+ #define --> CAMLextern (defined with CAMLexport or CAMLprim)
+ (rien) --> CAMLprim
+ g --> global C identifier
+ x --> special case
+
+ SP* signals the special cases:
+ - when the identifier was not simply prefixed with [caml_]
+ - when the [caml_] version was already used for something else, and
+ was renamed out of the way (watch out for [caml_alloc] and
+ [caml_array_bound_error] in *.s)
+*/
+
+/* a faire:
+ - ui_* (reverifier que win32.c n'en depend pas)
+*/
+
+
+/* **** alloc.c */
+#define alloc caml_alloc /*SP*/
+#define alloc_small caml_alloc_small
+#define alloc_tuple caml_alloc_tuple
+#define alloc_string caml_alloc_string
+#define alloc_final caml_alloc_final
+#define copy_string caml_copy_string
+#define alloc_array caml_alloc_array
+#define copy_string_array caml_copy_string_array
+#define convert_flag_list caml_convert_flag_list
+
+/* **** array.c */
+
+/* **** backtrace.c */
+#define backtrace_active caml_backtrace_active
+#define backtrace_pos caml_backtrace_pos
+#define backtrace_buffer caml_backtrace_buffer
+#define backtrace_last_exn caml_backtrace_last_exn
+#define print_exception_backtrace caml_print_exception_backtrace
+
+/* **** callback.c */
+#define callback_depth caml_callback_depth
+#define callbackN_exn caml_callbackN_exn
+#define callback_exn caml_callback_exn
+#define callback2_exn caml_callback2_exn
+#define callback3_exn caml_callback3_exn
+#define callback caml_callback
+#define callback2 caml_callback2
+#define callback3 caml_callback3
+#define callbackN caml_callbackN
+
+/* **** compact.c */
+
+/* **** compare.c */
+#define compare_unordered caml_compare_unordered
+
+/* **** custom.c */
+#define alloc_custom caml_alloc_custom
+#define register_custom_operations caml_register_custom_operations
+
+/* **** debugger.c */
+
+/* **** dynlink.c */
+
+/* **** extern.c */
+#define output_val caml_output_val
+#define output_value_to_malloc caml_output_value_to_malloc
+#define output_value_to_block caml_output_value_to_block
+#define serialize_int_1 caml_serialize_int_1
+#define serialize_int_2 caml_serialize_int_2
+#define serialize_int_4 caml_serialize_int_4
+#define serialize_int_8 caml_serialize_int_8
+#define serialize_float_4 caml_serialize_float_4
+#define serialize_float_8 caml_serialize_float_8
+#define serialize_block_1 caml_serialize_block_1
+#define serialize_block_2 caml_serialize_block_2
+#define serialize_block_4 caml_serialize_block_4
+#define serialize_block_8 caml_serialize_block_8
+#define serialize_block_float_8 caml_serialize_block_float_8
+
+/* **** fail.c */
+#define external_raise caml_external_raise
+#define mlraise caml_raise /*SP*/
+#define raise_constant caml_raise_constant
+#define raise_with_arg caml_raise_with_arg
+#define raise_with_string caml_raise_with_string
+#define failwith caml_failwith
+#define invalid_argument caml_invalid_argument
+#define array_bound_error caml_array_bound_error /*SP*/
+#define raise_out_of_memory caml_raise_out_of_memory
+#define raise_stack_overflow caml_raise_stack_overflow
+#define raise_sys_error caml_raise_sys_error
+#define raise_end_of_file caml_raise_end_of_file
+#define raise_zero_divide caml_raise_zero_divide
+#define raise_not_found caml_raise_not_found
+#define raise_sys_blocked_io caml_raise_sys_blocked_io
+/* **** asmrun/fail.c */
+/* **** asmrun/<arch>.s */
+
+/* **** finalise.c */
+
+/* **** fix_code.c */
+
+/* **** floats.c */
+/*#define Double_val caml_Double_val done in mlvalues.h as needed */
+/*#define Store_double_val caml_Store_double_val done in mlvalues.h as needed */
+#define copy_double caml_copy_double
+
+/* **** freelist.c */
+
+/* **** gc_ctrl.c */
+
+/* **** globroots.c */
+#define register_global_root caml_register_global_root
+#define remove_global_root caml_remove_global_root
+
+/* **** hash.c */
+#define hash_variant caml_hash_variant
+
+/* **** instrtrace.c */
+
+/* **** intern.c */
+#define input_val caml_input_val
+#define input_val_from_string caml_input_val_from_string
+#define input_value_from_malloc caml_input_value_from_malloc
+#define input_value_from_block caml_input_value_from_block
+#define deserialize_uint_1 caml_deserialize_uint_1
+#define deserialize_sint_1 caml_deserialize_sint_1
+#define deserialize_uint_2 caml_deserialize_uint_2
+#define deserialize_sint_2 caml_deserialize_sint_2
+#define deserialize_uint_4 caml_deserialize_uint_4
+#define deserialize_sint_4 caml_deserialize_sint_4
+#define deserialize_uint_8 caml_deserialize_uint_8
+#define deserialize_sint_8 caml_deserialize_sint_8
+#define deserialize_float_4 caml_deserialize_float_4
+#define deserialize_float_8 caml_deserialize_float_8
+#define deserialize_block_1 caml_deserialize_block_1
+#define deserialize_block_2 caml_deserialize_block_2
+#define deserialize_block_4 caml_deserialize_block_4
+#define deserialize_block_8 caml_deserialize_block_8
+#define deserialize_block_float_8 caml_deserialize_block_float_8
+#define deserialize_error caml_deserialize_error
+
+/* **** interp.c */
+
+/* **** ints.c */
+#define int32_ops caml_int32_ops
+#define copy_int32 caml_copy_int32
+/*#define Int64_val caml_Int64_val *** done in mlvalues.h as needed */
+#define int64_ops caml_int64_ops
+#define copy_int64 caml_copy_int64
+#define nativeint_ops caml_nativeint_ops
+#define copy_nativeint caml_copy_nativeint
+
+/* **** io.c */
+#define channel_mutex_free caml_channel_mutex_free
+#define channel_mutex_lock caml_channel_mutex_lock
+#define channel_mutex_unlock caml_channel_mutex_unlock
+#define channel_mutex_unlock_exn caml_channel_mutex_unlock_exn
+#define all_opened_channels caml_all_opened_channels
+#define open_descriptor_in caml_open_descriptor_in /*SP*/
+#define open_descriptor_out caml_open_descriptor_out /*SP*/
+#define close_channel caml_close_channel /*SP*/
+#define channel_size caml_channel_size /*SP*/
+#define channel_binary_mode caml_channel_binary_mode
+#define flush_partial caml_flush_partial /*SP*/
+#define flush caml_flush /*SP*/
+#define putword caml_putword
+#define putblock caml_putblock
+#define really_putblock caml_really_putblock
+#define seek_out caml_seek_out /*SP*/
+#define pos_out caml_pos_out /*SP*/
+#define do_read caml_do_read
+#define refill caml_refill
+#define getword caml_getword
+#define getblock caml_getblock
+#define really_getblock caml_really_getblock
+#define seek_in caml_seek_in /*SP*/
+#define pos_in caml_pos_in /*SP*/
+#define input_scan_line caml_input_scan_line /*SP*/
+#define finalize_channel caml_finalize_channel
+#define alloc_channel caml_alloc_channel
+/*#define Val_file_offset caml_Val_file_offset *** done in io.h as needed */
+/*#define File_offset_val caml_File_offset_val *** done in io.h as needed */
+
+/* **** lexing.c */
+
+/* **** main.c */
+/* *** no change */
+
+/* **** major_gc.c */
+#define heap_start caml_heap_start
+#define page_table caml_page_table
+
+/* **** md5.c */
+#define md5_string caml_md5_string
+#define md5_chan caml_md5_chan
+#define MD5Init caml_MD5Init
+#define MD5Update caml_MD5Update
+#define MD5Final caml_MD5Final
+#define MD5Transform caml_MD5Transform
+
+/* **** memory.c */
+#define alloc_shr caml_alloc_shr
+#define initialize caml_initialize
+#define modify caml_modify
+#define stat_alloc caml_stat_alloc
+#define stat_free caml_stat_free
+#define stat_resize caml_stat_resize
+
+/* **** meta.c */
+
+/* **** minor_gc.c */
+#define young_start caml_young_start
+#define young_end caml_young_end
+#define young_ptr caml_young_ptr
+#define young_limit caml_young_limit
+#define ref_table caml_ref_table
+#define minor_collection caml_minor_collection
+#define check_urgent_gc caml_check_urgent_gc
+
+/* **** misc.c */
+
+/* **** obj.c */
+
+/* **** parsing.c */
+
+/* **** prims.c */
+
+/* **** printexc.c */
+#define format_caml_exception caml_format_exception /*SP*/
+
+/* **** roots.c */
+#define local_roots caml_local_roots
+#define scan_roots_hook caml_scan_roots_hook
+#define do_local_roots caml_do_local_roots
+
+/* **** signals.c */
+#define pending_signals caml_pending_signals
+#define something_to_do caml_something_to_do
+#define enter_blocking_section_hook caml_enter_blocking_section_hook
+#define leave_blocking_section_hook caml_leave_blocking_section_hook
+#define try_leave_blocking_section_hook caml_try_leave_blocking_section_hook
+#define async_action_hook caml_async_action_hook
+#define enter_blocking_section caml_enter_blocking_section
+#define leave_blocking_section caml_leave_blocking_section
+#define convert_signal_number caml_convert_signal_number
+/* **** asmrun/signals.c */
+#define garbage_collection caml_garbage_collection
+
+/* **** stacks.c */
+#define stack_low caml_stack_low
+#define stack_high caml_stack_high
+#define stack_threshold caml_stack_threshold
+#define extern_sp caml_extern_sp
+#define trapsp caml_trapsp
+#define trap_barrier caml_trap_barrier
+
+/* **** startup.c */
+#define atom_table caml_atom_table
+/* **** asmrun/startup.c */
+#define static_data_start caml_static_data_start
+#define static_data_end caml_static_data_end
+
+/* **** str.c */
+#define string_length caml_string_length
+
+/* **** sys.c */
+#define sys_error caml_sys_error
+#define sys_exit caml_sys_exit
+
+/* **** terminfo.c */
+
+/* **** unix.c & win32.c */
+#define search_exe_in_path caml_search_exe_in_path
+
+/* **** weak.c */
+
+/* **** asmcomp/asmlink.ml */
+
+/* **** asmcomp/cmmgen.ml */
+
+/* **** asmcomp/asmlink.ml, asmcomp/cmmgen.ml, asmcomp/compilenv.ml */
+
+/* ************************************************************* */
+
+/* **** otherlibs/bigarray */
+#define int8 caml_ba_int8
+#define uint8 caml_ba_uint8
+#define int16 caml_ba_int16
+#define uint16 caml_ba_uint16
+#define MAX_NUM_DIMS CAML_BA_MAX_NUM_DIMS
+#define caml_bigarray_kind caml_ba_kind
+#define BIGARRAY_FLOAT32 CAML_BA_FLOAT32
+#define BIGARRAY_FLOAT64 CAML_BA_FLOAT64
+#define BIGARRAY_SINT8 CAML_BA_SINT8
+#define BIGARRAY_UINT8 CAML_BA_UINT8
+#define BIGARRAY_SINT16 CAML_BA_SINT16
+#define BIGARRAY_UINT16 CAML_BA_UINT16
+#define BIGARRAY_INT32 CAML_BA_INT32
+#define BIGARRAY_INT64 CAML_BA_INT64
+#define BIGARRAY_CAML_INT CAML_BA_CAML_INT
+#define BIGARRAY_NATIVE_INT CAML_BA_NATIVE_INT
+#define BIGARRAY_COMPLEX32 CAML_BA_COMPLEX32
+#define BIGARRAY_COMPLEX64 CAML_BA_COMPLEX64
+#define BIGARRAY_KIND_MASK CAML_BA_KIND_MASK
+#define caml_bigarray_layout caml_ba_layout
+#define BIGARRAY_C_LAYOUT CAML_BA_C_LAYOUT
+#define BIGARRAY_FORTRAN_LAYOUT CAML_BA_FORTRAN_LAYOUT
+#define BIGARRAY_LAYOUT_MASK CAML_BA_LAYOUT_MASK
+#define caml_bigarray_managed caml_ba_managed
+#define BIGARRAY_EXTERNAL CAML_BA_EXTERNAL
+#define BIGARRAY_MANAGED CAML_BA_MANAGED
+#define BIGARRAY_MAPPED_FILE CAML_BA_MAPPED_FILE
+#define BIGARRAY_MANAGED_MASK CAML_BA_MANAGED_MASK
+#define caml_bigarray_proxy caml_ba_proxy
+#define caml_bigarray caml_ba_array
+#define Bigarray_val Caml_ba_array_val
+#define Data_bigarray_val Caml_ba_data_val
+#define alloc_bigarray caml_ba_alloc
+#define alloc_bigarray_dims caml_ba_alloc_dims
+#define bigarray_map_file caml_ba_map_file
+#define bigarray_unmap_file caml_ba_unmap_file
+#define bigarray_element_size caml_ba_element_size
+#define bigarray_byte_size caml_ba_byte_size
+#define bigarray_deserialize caml_ba_deserialize
+#define MAX_BIGARRAY_MEMORY CAML_BA_MAX_MEMORY
+#define bigarray_create caml_ba_create
+#define bigarray_get_N caml_ba_get_N
+#define bigarray_get_1 caml_ba_get_1
+#define bigarray_get_2 caml_ba_get_2
+#define bigarray_get_3 caml_ba_get_3
+#define bigarray_get_generic caml_ba_get_generic
+#define bigarray_set_1 caml_ba_set_1
+#define bigarray_set_2 caml_ba_set_2
+#define bigarray_set_3 caml_ba_set_3
+#define bigarray_set_N caml_ba_set_N
+#define bigarray_set_generic caml_ba_set_generic
+#define bigarray_num_dims caml_ba_num_dims
+#define bigarray_dim caml_ba_dim
+#define bigarray_kind caml_ba_kind
+#define bigarray_layout caml_ba_layout
+#define bigarray_slice caml_ba_slice
+#define bigarray_sub caml_ba_sub
+#define bigarray_blit caml_ba_blit
+#define bigarray_fill caml_ba_fill
+#define bigarray_reshape caml_ba_reshape
+#define bigarray_init caml_ba_init
+
+#endif /* CAML_NAME_SPACE */
+#endif /* CAML_COMPATIBILITY_H */
diff --git a/byterun/caml/config.h b/byterun/caml/config.h
new file mode 100644
index 0000000000..63f0edd77c
--- /dev/null
+++ b/byterun/caml/config.h
@@ -0,0 +1,183 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_CONFIG_H
+#define CAML_CONFIG_H
+
+/* <include ../config/m.h> */
+/* <include ../config/s.h> */
+/* <private> */
+#include "../../config/m.h"
+#include "../../config/s.h"
+/* </private> */
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+
+#ifdef HAS_STDINT_H
+#include <stdint.h>
+#endif
+
+/* Types for 32-bit integers, 64-bit integers, and
+ native integers (as wide as a pointer type) */
+
+#ifndef ARCH_INT32_TYPE
+#if SIZEOF_INT == 4
+#define ARCH_INT32_TYPE int
+#define ARCH_UINT32_TYPE unsigned int
+#define ARCH_INT32_PRINTF_FORMAT ""
+#elif SIZEOF_LONG == 4
+#define ARCH_INT32_TYPE long
+#define ARCH_UINT32_TYPE unsigned long
+#define ARCH_INT32_PRINTF_FORMAT "l"
+#elif SIZEOF_SHORT == 4
+#define ARCH_INT32_TYPE short
+#define ARCH_UINT32_TYPE unsigned short
+#define ARCH_INT32_PRINTF_FORMAT ""
+#else
+#error "No 32-bit integer type available"
+#endif
+#endif
+
+#ifndef ARCH_INT64_TYPE
+#if SIZEOF_LONGLONG == 8
+#define ARCH_INT64_TYPE long long
+#define ARCH_UINT64_TYPE unsigned long long
+#define ARCH_INT64_PRINTF_FORMAT "ll"
+#elif SIZEOF_LONG == 8
+#define ARCH_INT64_TYPE long
+#define ARCH_UINT64_TYPE unsigned long
+#define ARCH_INT64_PRINTF_FORMAT "l"
+#else
+#error "No 64-bit integer type available"
+#endif
+#endif
+
+#ifndef HAS_STDINT_H
+/* Not a C99 compiler, typically MSVC. Define the C99 types we use. */
+typedef ARCH_INT32_TYPE int32_t;
+typedef ARCH_UINT32_TYPE uint32_t;
+typedef ARCH_INT64_TYPE int64_t;
+typedef ARCH_UINT64_TYPE uint64_t;
+#endif
+
+#if SIZEOF_PTR == SIZEOF_LONG
+/* Standard models: ILP32 or I32LP64 */
+typedef long intnat;
+typedef unsigned long uintnat;
+#define ARCH_INTNAT_PRINTF_FORMAT "l"
+#elif SIZEOF_PTR == SIZEOF_INT
+/* Hypothetical IP32L64 model */
+typedef int intnat;
+typedef unsigned int uintnat;
+#define ARCH_INTNAT_PRINTF_FORMAT ""
+#elif SIZEOF_PTR == 8
+/* Win64 model: IL32P64 */
+typedef int64_t intnat;
+typedef uint64_t uintnat;
+#define ARCH_INTNAT_PRINTF_FORMAT ARCH_INT64_PRINTF_FORMAT
+#else
+#error "No integer type available to represent pointers"
+#endif
+
+/* Endianness of floats */
+
+/* ARCH_FLOAT_ENDIANNESS encodes the byte order of doubles as follows:
+ the value [0xabcdefgh] means that the least significant byte of the
+ float is at byte offset [a], the next lsb at [b], ..., and the
+ most significant byte at [h]. */
+
+#if defined(__arm__) && !defined(__ARM_EABI__)
+#define ARCH_FLOAT_ENDIANNESS 0x45670123
+#elif defined(ARCH_BIG_ENDIAN)
+#define ARCH_FLOAT_ENDIANNESS 0x76543210
+#else
+#define ARCH_FLOAT_ENDIANNESS 0x01234567
+#endif
+
+/* We use threaded code interpretation if the compiler provides labels
+ as first-class values (GCC 2.x). */
+
+#if defined(__GNUC__) && __GNUC__ >= 2 && !defined(DEBUG) \
+ && !defined (SHRINKED_GNUC) && !defined(CAML_JIT)
+#define THREADED_CODE
+#endif
+
+
+/* Memory model parameters */
+
+/* The size of a page for memory management (in bytes) is [1 << Page_log].
+ [Page_size] must be a multiple of [sizeof (value)].
+ [Page_log] must be be >= 8 and <= 20.
+ Do not change the definition of [Page_size]. */
+#define Page_log 12 /* A page is 4 kilobytes. */
+#define Page_size (1 << Page_log)
+
+/* Initial size of stack (bytes). */
+#define Stack_size (4096 * sizeof(value))
+
+/* Minimum free size of stack (bytes); below that, it is reallocated. */
+#define Stack_threshold (256 * sizeof(value))
+
+/* Default maximum size of the stack (words). */
+#define Max_stack_def (1024 * 1024)
+
+
+/* Maximum size of a block allocated in the young generation (words). */
+/* Must be > 4 */
+#define Max_young_wosize 256
+
+
+/* Minimum size of the minor zone (words).
+ This must be at least [Max_young_wosize + 1]. */
+#define Minor_heap_min 4096
+
+/* Maximum size of the minor zone (words).
+ Must be greater than or equal to [Minor_heap_min].
+*/
+#define Minor_heap_max (1 << 28)
+
+/* Default size of the minor zone. (words) */
+#define Minor_heap_def 262144
+
+
+/* Minimum size increment when growing the heap (words).
+ Must be a multiple of [Page_size / sizeof (value)]. */
+#define Heap_chunk_min (15 * Page_size)
+
+/* Default size increment when growing the heap.
+ If this is <= 1000, it's a percentage of the current heap size.
+ If it is > 1000, it's a number of words. */
+#define Heap_chunk_def 15
+
+/* Default initial size of the major heap (words);
+ Must be a multiple of [Page_size / sizeof (value)]. */
+#define Init_heap_def (31 * Page_size)
+/* (about 512 kB for a 32-bit platform, 1 MB for a 64-bit platform.) */
+
+
+/* Default speed setting for the major GC. The heap will grow until
+ the dead objects and the free list represent this percentage of the
+ total size of live objects. */
+#define Percent_free_def 80
+
+/* Default setting for the compacter: 500%
+ (i.e. trigger the compacter when 5/6 of the heap is free or garbage)
+ This can be set quite high because the overhead is over-estimated
+ when fragmentation occurs.
+ */
+#define Max_percent_free_def 500
+
+
+#endif /* CAML_CONFIG_H */
diff --git a/byterun/caml/custom.h b/byterun/caml/custom.h
new file mode 100644
index 0000000000..70b4726989
--- /dev/null
+++ b/byterun/caml/custom.h
@@ -0,0 +1,71 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Manuel Serrano and Xavier Leroy, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_CUSTOM_H
+#define CAML_CUSTOM_H
+
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "mlvalues.h"
+
+struct custom_operations {
+ char *identifier;
+ void (*finalize)(value v);
+ int (*compare)(value v1, value v2);
+ intnat (*hash)(value v);
+ void (*serialize)(value v,
+ /*out*/ uintnat * bsize_32 /*size in bytes*/,
+ /*out*/ uintnat * bsize_64 /*size in bytes*/);
+ uintnat (*deserialize)(void * dst);
+ int (*compare_ext)(value v1, value v2);
+};
+
+#define custom_finalize_default NULL
+#define custom_compare_default NULL
+#define custom_hash_default NULL
+#define custom_serialize_default NULL
+#define custom_deserialize_default NULL
+#define custom_compare_ext_default NULL
+
+#define Custom_ops_val(v) (*((struct custom_operations **) (v)))
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+CAMLextern value caml_alloc_custom(struct custom_operations * ops,
+ uintnat size, /*size in bytes*/
+ mlsize_t mem, /*resources consumed*/
+ mlsize_t max /*max resources*/);
+
+CAMLextern void caml_register_custom_operations(struct custom_operations * ops);
+
+CAMLextern int caml_compare_unordered;
+ /* Used by custom comparison to report unordered NaN-like cases. */
+
+/* <private> */
+extern struct custom_operations * caml_find_custom_operations(char * ident);
+extern struct custom_operations *
+ caml_final_custom_operations(void (*fn)(value));
+
+extern void caml_init_custom_operations(void);
+/* </private> */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_CUSTOM_H */
diff --git a/byterun/caml/debugger.h b/byterun/caml/debugger.h
new file mode 100644
index 0000000000..e68ef756c1
--- /dev/null
+++ b/byterun/caml/debugger.h
@@ -0,0 +1,111 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Interface with the debugger */
+
+#ifndef CAML_DEBUGGER_H
+#define CAML_DEBUGGER_H
+
+#include "misc.h"
+#include "mlvalues.h"
+
+CAMLextern int caml_debugger_in_use;
+CAMLextern int caml_debugger_fork_mode; /* non-zero for parent */
+extern uintnat caml_event_count;
+
+enum event_kind {
+ EVENT_COUNT, BREAKPOINT, PROGRAM_START, PROGRAM_EXIT,
+ TRAP_BARRIER, UNCAUGHT_EXC
+};
+
+void caml_debugger_init (void);
+void caml_debugger (enum event_kind event);
+void caml_debugger_cleanup_fork (void);
+
+/* Communication protocol */
+
+/* Requests from the debugger to the runtime system */
+
+enum debugger_request {
+ REQ_SET_EVENT = 'e', /* uint32_t pos */
+ /* Set an event on the instruction at position pos */
+ REQ_SET_BREAKPOINT = 'B', /* uint32_t pos, (char k) */
+ /* Set a breakpoint at position pos */
+ /* In profiling mode, the breakpoint kind is set to k */
+ REQ_RESET_INSTR = 'i', /* uint32_t pos */
+ /* Clear an event or breapoint at position pos, restores initial instr. */
+ REQ_CHECKPOINT = 'c', /* no args */
+ /* Checkpoint the runtime system by forking a child process.
+ Reply is pid of child process or -1 if checkpoint failed. */
+ REQ_GO = 'g', /* uint32_t n */
+ /* Run the program for n events.
+ Reply is one of debugger_reply described below. */
+ REQ_STOP = 's', /* no args */
+ /* Terminate the runtime system */
+ REQ_WAIT = 'w', /* no args */
+ /* Reap one dead child (a discarded checkpoint). */
+ REQ_INITIAL_FRAME = '0', /* no args */
+ /* Set current frame to bottom frame (the one currently executing).
+ Reply is stack offset and current pc. */
+ REQ_GET_FRAME = 'f', /* no args */
+ /* Return current frame location (stack offset + current pc). */
+ REQ_SET_FRAME = 'S', /* uint32_t stack_offset */
+ /* Set current frame to given stack offset. No reply. */
+ REQ_UP_FRAME = 'U', /* uint32_t n */
+ /* Move one frame up. Argument n is size of current frame (in words).
+ Reply is stack offset and current pc, or -1 if top of stack reached. */
+ REQ_SET_TRAP_BARRIER = 'b', /* uint32_t offset */
+ /* Set the trap barrier at the given offset. */
+ REQ_GET_LOCAL = 'L', /* uint32_t slot_number */
+ /* Return the local variable at the given slot in the current frame.
+ Reply is one value. */
+ REQ_GET_ENVIRONMENT = 'E', /* uint32_t slot_number */
+ /* Return the local variable at the given slot in the heap environment
+ of the current frame. Reply is one value. */
+ REQ_GET_GLOBAL = 'G', /* uint32_t global_number */
+ /* Return the specified global variable. Reply is one value. */
+ REQ_GET_ACCU = 'A', /* no args */
+ /* Return the current contents of the accumulator. Reply is one value. */
+ REQ_GET_HEADER = 'H', /* mlvalue v */
+ /* As REQ_GET_OBJ, but sends only the header. */
+ REQ_GET_FIELD = 'F', /* mlvalue v, uint32_t fieldnum */
+ /* As REQ_GET_OBJ, but sends only one field. */
+ REQ_MARSHAL_OBJ = 'M', /* mlvalue v */
+ /* Send a copy of the data structure rooted at v, using the same
+ format as [caml_output_value]. */
+ REQ_GET_CLOSURE_CODE = 'C', /* mlvalue v */
+ /* Send the code address of the given closure.
+ Reply is one uint32_t. */
+ REQ_SET_FORK_MODE = 'K' /* uint32_t m */
+ /* Set whether to follow the child (m=0) or the parent on fork. */
+};
+
+/* Replies to a REQ_GO request. All replies are followed by three uint32_t:
+ - the value of the event counter
+ - the position of the stack
+ - the current pc. */
+
+enum debugger_reply {
+ REP_EVENT = 'e',
+ /* Event counter reached 0. */
+ REP_BREAKPOINT = 'b',
+ /* Breakpoint hit. */
+ REP_EXITED = 'x',
+ /* Program exited by calling exit or reaching the end of the source. */
+ REP_TRAP = 's',
+ /* Trap barrier crossed. */
+ REP_UNCAUGHT_EXC = 'u'
+ /* Program exited due to a stray exception. */
+};
+
+#endif /* CAML_DEBUGGER_H */
diff --git a/byterun/caml/dynlink.h b/byterun/caml/dynlink.h
new file mode 100644
index 0000000000..74cfdb663e
--- /dev/null
+++ b/byterun/caml/dynlink.h
@@ -0,0 +1,36 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Dynamic loading of C primitives. */
+
+#ifndef CAML_DYNLINK_H
+#define CAML_DYNLINK_H
+
+#include "misc.h"
+
+/* Build the table of primitives, given a search path, a list
+ of shared libraries, and a list of primitive names
+ (all three 0-separated in char arrays).
+ Abort the runtime system on error. */
+extern void caml_build_primitive_table(char * lib_path,
+ char * libs,
+ char * req_prims);
+
+/* The search path for shared libraries */
+extern struct ext_table caml_shared_libs_path;
+
+/* Build the table of primitives as a copy of the builtin primitive table.
+ Used for executables generated by ocamlc -output-obj. */
+extern void caml_build_primitive_table_builtin(void);
+
+#endif /* CAML_DYNLINK_H */
diff --git a/byterun/caml/exec.h b/byterun/caml/exec.h
new file mode 100644
index 0000000000..7e084acd41
--- /dev/null
+++ b/byterun/caml/exec.h
@@ -0,0 +1,60 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* exec.h : format of executable bytecode files */
+
+#ifndef CAML_EXEC_H
+#define CAML_EXEC_H
+
+/* Executable bytecode files are composed of a number of sections,
+ identified by 4-character names. A table of contents at the
+ end of the file lists the section names along with their sizes,
+ in the order in which they appear in the file:
+
+ offset 0 ---> initial junk
+ data for section 1
+ data for section 2
+ ...
+ data for section N
+ table of contents:
+ descriptor for section 1
+ ...
+ descriptor for section N
+ trailer
+ end of file --->
+*/
+
+/* Structure of t.o.c. entries
+ Numerical quantities are 32-bit unsigned integers, big endian */
+
+struct section_descriptor {
+ char name[4]; /* Section name */
+ uint32_t len; /* Length of data in bytes */
+};
+
+/* Structure of the trailer. */
+
+struct exec_trailer {
+ uint32_t num_sections; /* Number of sections */
+ char magic[12]; /* The magic number */
+ struct section_descriptor * section; /* Not part of file */
+};
+
+#define TRAILER_SIZE (4+12)
+
+/* Magic number for this release */
+
+#define EXEC_MAGIC "Caml1999X011"
+
+
+#endif /* CAML_EXEC_H */
diff --git a/byterun/caml/fail.h b/byterun/caml/fail.h
new file mode 100644
index 0000000000..ffdfb438b1
--- /dev/null
+++ b/byterun/caml/fail.h
@@ -0,0 +1,127 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_FAIL_H
+#define CAML_FAIL_H
+
+/* <private> */
+#include <setjmp.h>
+/* </private> */
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "misc.h"
+#include "mlvalues.h"
+
+/* <private> */
+#define OUT_OF_MEMORY_EXN 0 /* "Out_of_memory" */
+#define SYS_ERROR_EXN 1 /* "Sys_error" */
+#define FAILURE_EXN 2 /* "Failure" */
+#define INVALID_EXN 3 /* "Invalid_argument" */
+#define END_OF_FILE_EXN 4 /* "End_of_file" */
+#define ZERO_DIVIDE_EXN 5 /* "Division_by_zero" */
+#define NOT_FOUND_EXN 6 /* "Not_found" */
+#define MATCH_FAILURE_EXN 7 /* "Match_failure" */
+#define STACK_OVERFLOW_EXN 8 /* "Stack_overflow" */
+#define SYS_BLOCKED_IO 9 /* "Sys_blocked_io" */
+#define ASSERT_FAILURE_EXN 10 /* "Assert_failure" */
+#define UNDEFINED_RECURSIVE_MODULE_EXN 11 /* "Undefined_recursive_module" */
+
+#ifdef POSIX_SIGNALS
+struct longjmp_buffer {
+ sigjmp_buf buf;
+};
+#else
+struct longjmp_buffer {
+ jmp_buf buf;
+};
+#define sigsetjmp(buf,save) setjmp(buf)
+#define siglongjmp(buf,val) longjmp(buf,val)
+#endif
+
+CAMLextern struct longjmp_buffer * caml_external_raise;
+extern value caml_exn_bucket;
+int caml_is_special_exception(value exn);
+
+/* </private> */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAMLnoreturn_start
+CAMLextern void caml_raise (value bucket)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_constant (value tag)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_with_arg (value tag, value arg)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_with_args (value tag, int nargs, value arg[])
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_with_string (value tag, char const * msg)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_failwith (char const *)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_invalid_argument (char const *)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_out_of_memory (void)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_stack_overflow (void)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_sys_error (value)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_end_of_file (void)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_zero_divide (void)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_not_found (void)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_array_bound_error (void)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_raise_sys_blocked_io (void)
+CAMLnoreturn_end;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_FAIL_H */
diff --git a/byterun/caml/finalise.h b/byterun/caml/finalise.h
new file mode 100644
index 0000000000..96853f525b
--- /dev/null
+++ b/byterun/caml/finalise.h
@@ -0,0 +1,27 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Moscova, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_FINALISE_H
+#define CAML_FINALISE_H
+
+#include "roots.h"
+
+void caml_final_update (void);
+void caml_final_do_calls (void);
+void caml_final_do_strong_roots (scanning_action f);
+void caml_final_do_weak_roots (scanning_action f);
+void caml_final_do_young_roots (scanning_action f);
+void caml_final_empty_young (void);
+value caml_final_register (value f, value v);
+
+#endif /* CAML_FINALISE_H */
diff --git a/byterun/caml/fix_code.h b/byterun/caml/fix_code.h
new file mode 100644
index 0000000000..419ad327a5
--- /dev/null
+++ b/byterun/caml/fix_code.h
@@ -0,0 +1,40 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Handling of blocks of bytecode (endianness switch, threading). */
+
+#ifndef CAML_FIX_CODE_H
+#define CAML_FIX_CODE_H
+
+
+#include "config.h"
+#include "misc.h"
+#include "mlvalues.h"
+
+extern code_t caml_start_code;
+extern asize_t caml_code_size;
+extern unsigned char * caml_saved_code;
+
+void caml_init_code_fragments();
+void caml_load_code (int fd, asize_t len);
+void caml_fixup_endianness (code_t code, asize_t len);
+void caml_set_instruction (code_t pos, opcode_t instr);
+int caml_is_instruction (opcode_t instr1, opcode_t instr2);
+
+#ifdef THREADED_CODE
+extern char ** caml_instr_table;
+extern char * caml_instr_base;
+void caml_thread_code (code_t code, asize_t len);
+#endif
+
+#endif /* CAML_FIX_CODE_H */
diff --git a/byterun/caml/freelist.h b/byterun/caml/freelist.h
new file mode 100644
index 0000000000..2e811d45a8
--- /dev/null
+++ b/byterun/caml/freelist.h
@@ -0,0 +1,34 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Free lists of heap blocks. */
+
+#ifndef CAML_FREELIST_H
+#define CAML_FREELIST_H
+
+
+#include "misc.h"
+#include "mlvalues.h"
+
+extern asize_t caml_fl_cur_wsz;
+
+header_t *caml_fl_allocate (mlsize_t wo_sz);
+void caml_fl_init_merge (void);
+void caml_fl_reset (void);
+header_t *caml_fl_merge_block (value);
+void caml_fl_add_blocks (value);
+void caml_make_free_blocks (value *, mlsize_t wsz, int, int);
+void caml_set_allocation_policy (uintnat);
+
+
+#endif /* CAML_FREELIST_H */
diff --git a/byterun/caml/gc.h b/byterun/caml/gc.h
new file mode 100644
index 0000000000..3cbf08a2da
--- /dev/null
+++ b/byterun/caml/gc.h
@@ -0,0 +1,56 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_GC_H
+#define CAML_GC_H
+
+
+#include "mlvalues.h"
+
+#define Caml_white (0 << 8)
+#define Caml_gray (1 << 8)
+#define Caml_blue (2 << 8)
+#define Caml_black (3 << 8)
+
+#define Color_hd(hd) ((color_t) ((hd) & Caml_black))
+#define Color_hp(hp) (Color_hd (Hd_hp (hp)))
+#define Color_val(val) (Color_hd (Hd_val (val)))
+
+#define Is_white_hd(hd) (Color_hd (hd) == Caml_white)
+#define Is_gray_hd(hd) (Color_hd (hd) == Caml_gray)
+#define Is_blue_hd(hd) (Color_hd (hd) == Caml_blue)
+#define Is_black_hd(hd) (Color_hd (hd) == Caml_black)
+
+#define Whitehd_hd(hd) (((hd) & ~Caml_black)/*| Caml_white*/)
+#define Grayhd_hd(hd) (((hd) & ~Caml_black) | Caml_gray)
+#define Blackhd_hd(hd) (((hd)/*& ~Caml_black*/)| Caml_black)
+#define Bluehd_hd(hd) (((hd) & ~Caml_black) | Caml_blue)
+
+/* This depends on the layout of the header. See [mlvalues.h]. */
+#define Make_header(wosize, tag, color) \
+ (/*Assert ((wosize) <= Max_wosize),*/ \
+ ((header_t) (((header_t) (wosize) << 10) \
+ + (color) \
+ + (tag_t) (tag))) \
+ )
+
+#define Is_white_val(val) (Color_val(val) == Caml_white)
+#define Is_gray_val(val) (Color_val(val) == Caml_gray)
+#define Is_blue_val(val) (Color_val(val) == Caml_blue)
+#define Is_black_val(val) (Color_val(val) == Caml_black)
+
+/* For extern.c */
+#define Colornum_hd(hd) ((color_t) (((hd) >> 8) & 3))
+#define Coloredhd_hd(hd,colnum) (((hd) & ~Caml_black) | ((colnum) << 8))
+
+#endif /* CAML_GC_H */
diff --git a/byterun/caml/gc_ctrl.h b/byterun/caml/gc_ctrl.h
new file mode 100644
index 0000000000..459c685a22
--- /dev/null
+++ b/byterun/caml/gc_ctrl.h
@@ -0,0 +1,42 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_GC_CTRL_H
+#define CAML_GC_CTRL_H
+
+#include "misc.h"
+
+extern double
+ caml_stat_minor_words,
+ caml_stat_promoted_words,
+ caml_stat_major_words;
+
+extern intnat
+ caml_stat_minor_collections,
+ caml_stat_major_collections,
+ caml_stat_heap_wsz,
+ caml_stat_top_heap_wsz,
+ caml_stat_compactions,
+ caml_stat_heap_chunks;
+
+uintnat caml_normalize_heap_increment (uintnat);
+
+void caml_init_gc (uintnat, uintnat, uintnat,
+ uintnat, uintnat);
+
+
+#ifdef DEBUG
+void caml_heap_check (void);
+#endif
+
+#endif /* CAML_GC_CTRL_H */
diff --git a/byterun/caml/globroots.h b/byterun/caml/globroots.h
new file mode 100644
index 0000000000..1c3ebab289
--- /dev/null
+++ b/byterun/caml/globroots.h
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Registration of global memory roots */
+
+#ifndef CAML_GLOBROOTS_H
+#define CAML_GLOBROOTS_H
+
+#include "mlvalues.h"
+#include "roots.h"
+
+void caml_scan_global_roots(scanning_action f);
+void caml_scan_global_young_roots(scanning_action f);
+
+#endif /* CAML_GLOBROOTS_H */
diff --git a/byterun/caml/hash.h b/byterun/caml/hash.h
new file mode 100644
index 0000000000..d130068c48
--- /dev/null
+++ b/byterun/caml/hash.h
@@ -0,0 +1,37 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2011 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Auxiliary functions for custom hash functions */
+
+#ifndef CAML_HASH_H
+#define CAML_HASH_H
+
+#include "mlvalues.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAMLextern uint32_t caml_hash_mix_uint32(uint32_t h, uint32_t d);
+CAMLextern uint32_t caml_hash_mix_intnat(uint32_t h, intnat d);
+CAMLextern uint32_t caml_hash_mix_int64(uint32_t h, int64_t d);
+CAMLextern uint32_t caml_hash_mix_double(uint32_t h, double d);
+CAMLextern uint32_t caml_hash_mix_float(uint32_t h, float d);
+CAMLextern uint32_t caml_hash_mix_string(uint32_t h, value s);
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#endif /* CAML_HASH_H */
diff --git a/byterun/caml/instrtrace.h b/byterun/caml/instrtrace.h
new file mode 100644
index 0000000000..3020160811
--- /dev/null
+++ b/byterun/caml/instrtrace.h
@@ -0,0 +1,30 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Trace the instructions executed */
+
+#ifndef _instrtrace_
+#define _instrtrace_
+
+
+#include "mlvalues.h"
+#include "misc.h"
+
+extern int caml_trace_flag;
+extern intnat caml_icount;
+void caml_stop_here (void);
+void caml_disasm_instr (code_t pc);
+void caml_trace_value_file (value v, code_t prog, int proglen, FILE * f);
+void caml_trace_accu_sp_file(value accu, value * sp, code_t prog, int proglen,
+ FILE * f);
+#endif
diff --git a/byterun/caml/instruct.h b/byterun/caml/instruct.h
new file mode 100644
index 0000000000..f9cc80ee65
--- /dev/null
+++ b/byterun/caml/instruct.h
@@ -0,0 +1,62 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The instruction set. */
+
+#ifndef CAML_INSTRUCT_H
+#define CAML_INSTRUCT_H
+
+enum instructions {
+ ACC0, ACC1, ACC2, ACC3, ACC4, ACC5, ACC6, ACC7,
+ ACC, PUSH,
+ PUSHACC0, PUSHACC1, PUSHACC2, PUSHACC3,
+ PUSHACC4, PUSHACC5, PUSHACC6, PUSHACC7,
+ PUSHACC, POP, ASSIGN,
+ ENVACC1, ENVACC2, ENVACC3, ENVACC4, ENVACC,
+ PUSHENVACC1, PUSHENVACC2, PUSHENVACC3, PUSHENVACC4, PUSHENVACC,
+ PUSH_RETADDR, APPLY, APPLY1, APPLY2, APPLY3,
+ APPTERM, APPTERM1, APPTERM2, APPTERM3,
+ RETURN, RESTART, GRAB,
+ CLOSURE, CLOSUREREC,
+ OFFSETCLOSUREM2, OFFSETCLOSURE0, OFFSETCLOSURE2, OFFSETCLOSURE,
+ PUSHOFFSETCLOSUREM2, PUSHOFFSETCLOSURE0,
+ PUSHOFFSETCLOSURE2, PUSHOFFSETCLOSURE,
+ GETGLOBAL, PUSHGETGLOBAL, GETGLOBALFIELD, PUSHGETGLOBALFIELD, SETGLOBAL,
+ ATOM0, ATOM, PUSHATOM0, PUSHATOM,
+ MAKEBLOCK, MAKEBLOCK1, MAKEBLOCK2, MAKEBLOCK3, MAKEFLOATBLOCK,
+ GETFIELD0, GETFIELD1, GETFIELD2, GETFIELD3, GETFIELD, GETFLOATFIELD,
+ SETFIELD0, SETFIELD1, SETFIELD2, SETFIELD3, SETFIELD, SETFLOATFIELD,
+ VECTLENGTH, GETVECTITEM, SETVECTITEM,
+ GETSTRINGCHAR, SETSTRINGCHAR,
+ BRANCH, BRANCHIF, BRANCHIFNOT, SWITCH, BOOLNOT,
+ PUSHTRAP, POPTRAP, RAISE,
+ CHECK_SIGNALS,
+ C_CALL1, C_CALL2, C_CALL3, C_CALL4, C_CALL5, C_CALLN,
+ CONST0, CONST1, CONST2, CONST3, CONSTINT,
+ PUSHCONST0, PUSHCONST1, PUSHCONST2, PUSHCONST3, PUSHCONSTINT,
+ NEGINT, ADDINT, SUBINT, MULINT, DIVINT, MODINT,
+ ANDINT, ORINT, XORINT, LSLINT, LSRINT, ASRINT,
+ EQ, NEQ, LTINT, LEINT, GTINT, GEINT,
+ OFFSETINT, OFFSETREF, ISINT,
+ GETMETHOD,
+ BEQ, BNEQ, BLTINT, BLEINT, BGTINT, BGEINT,
+ ULTINT, UGEINT,
+ BULTINT, BUGEINT,
+ GETPUBMET, GETDYNMET,
+ STOP,
+ EVENT, BREAK,
+ RERAISE, RAISE_NOTRACE,
+FIRST_UNIMPLEMENTED_OP};
+
+
+#endif /* CAML_INSTRUCT_H */
diff --git a/byterun/caml/int64_emul.h b/byterun/caml/int64_emul.h
new file mode 100644
index 0000000000..2554df1814
--- /dev/null
+++ b/byterun/caml/int64_emul.h
@@ -0,0 +1,287 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Software emulation of 64-bit integer arithmetic, for C compilers
+ that do not support it. */
+
+#ifndef CAML_INT64_EMUL_H
+#define CAML_INT64_EMUL_H
+
+#include <math.h>
+
+#ifdef ARCH_BIG_ENDIAN
+#define I64_literal(hi,lo) { hi, lo }
+#else
+#define I64_literal(hi,lo) { lo, hi }
+#endif
+
+#define I64_split(x,hi,lo) (hi = (x).h, lo = (x).l)
+
+/* Unsigned comparison */
+static int I64_ucompare(uint64_t x, uint64_t y)
+{
+ if (x.h > y.h) return 1;
+ if (x.h < y.h) return -1;
+ if (x.l > y.l) return 1;
+ if (x.l < y.l) return -1;
+ return 0;
+}
+
+#define I64_ult(x, y) (I64_ucompare(x, y) < 0)
+
+/* Signed comparison */
+static int I64_compare(int64_t x, int64_t y)
+{
+ if ((int32_t)x.h > (int32_t)y.h) return 1;
+ if ((int32_t)x.h < (int32_t)y.h) return -1;
+ if (x.l > y.l) return 1;
+ if (x.l < y.l) return -1;
+ return 0;
+}
+
+/* Negation */
+static int64_t I64_neg(int64_t x)
+{
+ int64_t res;
+ res.l = -x.l;
+ res.h = ~x.h;
+ if (res.l == 0) res.h++;
+ return res;
+}
+
+/* Addition */
+static int64_t I64_add(int64_t x, int64_t y)
+{
+ int64_t res;
+ res.l = x.l + y.l;
+ res.h = x.h + y.h;
+ if (res.l < x.l) res.h++;
+ return res;
+}
+
+/* Subtraction */
+static int64_t I64_sub(int64_t x, int64_t y)
+{
+ int64_t res;
+ res.l = x.l - y.l;
+ res.h = x.h - y.h;
+ if (x.l < y.l) res.h--;
+ return res;
+}
+
+/* Multiplication */
+static int64_t I64_mul(int64_t x, int64_t y)
+{
+ int64_t res;
+ uint32_t prod00 = (x.l & 0xFFFF) * (y.l & 0xFFFF);
+ uint32_t prod10 = (x.l >> 16) * (y.l & 0xFFFF);
+ uint32_t prod01 = (x.l & 0xFFFF) * (y.l >> 16);
+ uint32_t prod11 = (x.l >> 16) * (y.l >> 16);
+ res.l = prod00;
+ res.h = prod11 + (prod01 >> 16) + (prod10 >> 16);
+ prod01 = prod01 << 16; res.l += prod01; if (res.l < prod01) res.h++;
+ prod10 = prod10 << 16; res.l += prod10; if (res.l < prod10) res.h++;
+ res.h += x.l * y.h + x.h * y.l;
+ return res;
+}
+
+#define I64_is_zero(x) (((x).l | (x).h) == 0)
+#define I64_is_negative(x) ((int32_t) (x).h < 0)
+#define I64_is_min_int(x) ((x).l == 0 && (x).h == 0x80000000U)
+#define I64_is_minus_one(x) (((x).l & (x).h) == 0xFFFFFFFFU)
+
+/* Bitwise operations */
+static int64_t I64_and(int64_t x, int64_t y)
+{
+ int64_t res;
+ res.l = x.l & y.l;
+ res.h = x.h & y.h;
+ return res;
+}
+
+static int64_t I64_or(int64_t x, int64_t y)
+{
+ int64_t res;
+ res.l = x.l | y.l;
+ res.h = x.h | y.h;
+ return res;
+}
+
+static int64_t I64_xor(int64_t x, int64_t y)
+{
+ int64_t res;
+ res.l = x.l ^ y.l;
+ res.h = x.h ^ y.h;
+ return res;
+}
+
+/* Shifts */
+static int64_t I64_lsl(int64_t x, int s)
+{
+ int64_t res;
+ s = s & 63;
+ if (s == 0) return x;
+ if (s < 32) {
+ res.l = x.l << s;
+ res.h = (x.h << s) | (x.l >> (32 - s));
+ } else {
+ res.l = 0;
+ res.h = x.l << (s - 32);
+ }
+ return res;
+}
+
+static int64_t I64_lsr(int64_t x, int s)
+{
+ int64_t res;
+ s = s & 63;
+ if (s == 0) return x;
+ if (s < 32) {
+ res.l = (x.l >> s) | (x.h << (32 - s));
+ res.h = x.h >> s;
+ } else {
+ res.l = x.h >> (s - 32);
+ res.h = 0;
+ }
+ return res;
+}
+
+static int64_t I64_asr(int64_t x, int s)
+{
+ int64_t res;
+ s = s & 63;
+ if (s == 0) return x;
+ if (s < 32) {
+ res.l = (x.l >> s) | (x.h << (32 - s));
+ res.h = (int32_t) x.h >> s;
+ } else {
+ res.l = (int32_t) x.h >> (s - 32);
+ res.h = (int32_t) x.h >> 31;
+ }
+ return res;
+}
+
+/* Division and modulus */
+
+#define I64_SHL1(x) x.h = (x.h << 1) | (x.l >> 31); x.l <<= 1
+#define I64_SHR1(x) x.l = (x.l >> 1) | (x.h << 31); x.h >>= 1
+
+static void I64_udivmod(uint64_t modulus, uint64_t divisor,
+ uint64_t * quo, uint64_t * mod)
+{
+ int64_t quotient, mask;
+ int cmp;
+
+ quotient.h = 0; quotient.l = 0;
+ mask.h = 0; mask.l = 1;
+ while ((int32_t) divisor.h >= 0) {
+ cmp = I64_ucompare(divisor, modulus);
+ I64_SHL1(divisor);
+ I64_SHL1(mask);
+ if (cmp >= 0) break;
+ }
+ while (mask.l | mask.h) {
+ if (I64_ucompare(modulus, divisor) >= 0) {
+ quotient.h |= mask.h; quotient.l |= mask.l;
+ modulus = I64_sub(modulus, divisor);
+ }
+ I64_SHR1(mask);
+ I64_SHR1(divisor);
+ }
+ *quo = quotient;
+ *mod = modulus;
+}
+
+static int64_t I64_div(int64_t x, int64_t y)
+{
+ int64_t q, r;
+ int32_t sign;
+
+ sign = x.h ^ y.h;
+ if ((int32_t) x.h < 0) x = I64_neg(x);
+ if ((int32_t) y.h < 0) y = I64_neg(y);
+ I64_udivmod(x, y, &q, &r);
+ if (sign < 0) q = I64_neg(q);
+ return q;
+}
+
+static int64_t I64_mod(int64_t x, int64_t y)
+{
+ int64_t q, r;
+ int32_t sign;
+
+ sign = x.h;
+ if ((int32_t) x.h < 0) x = I64_neg(x);
+ if ((int32_t) y.h < 0) y = I64_neg(y);
+ I64_udivmod(x, y, &q, &r);
+ if (sign < 0) r = I64_neg(r);
+ return r;
+}
+
+/* Coercions */
+
+static int64_t I64_of_int32(int32_t x)
+{
+ int64_t res;
+ res.l = x;
+ res.h = x >> 31;
+ return res;
+}
+
+#define I64_to_int32(x) ((int32_t) (x).l)
+
+/* Note: we assume sizeof(intnat) = 4 here, which is true otherwise
+ autoconfiguration would have selected native 64-bit integers */
+#define I64_of_intnat I64_of_int32
+#define I64_to_intnat I64_to_int32
+
+static double I64_to_double(int64_t x)
+{
+ double res;
+ int32_t sign = x.h;
+ if (sign < 0) x = I64_neg(x);
+ res = ldexp((double) x.h, 32) + x.l;
+ if (sign < 0) res = -res;
+ return res;
+}
+
+static int64_t I64_of_double(double f)
+{
+ int64_t res;
+ double frac, integ;
+ int neg;
+
+ neg = (f < 0);
+ f = fabs(f);
+ frac = modf(ldexp(f, -32), &integ);
+ res.h = (uint32_t) integ;
+ res.l = (uint32_t) ldexp(frac, 32);
+ if (neg) res = I64_neg(res);
+ return res;
+}
+
+static int64_t I64_bswap(int64_t x)
+{
+ int64_t res;
+ res.h = (((x.l & 0x000000FF) << 24) |
+ ((x.l & 0x0000FF00) << 8) |
+ ((x.l & 0x00FF0000) >> 8) |
+ ((x.l & 0xFF000000) >> 24));
+ res.l = (((x.h & 0x000000FF) << 24) |
+ ((x.h & 0x0000FF00) << 8) |
+ ((x.h & 0x00FF0000) >> 8) |
+ ((x.h & 0xFF000000) >> 24));
+ return res;
+}
+
+#endif /* CAML_INT64_EMUL_H */
diff --git a/byterun/caml/int64_format.h b/byterun/caml/int64_format.h
new file mode 100644
index 0000000000..aa8f1abab5
--- /dev/null
+++ b/byterun/caml/int64_format.h
@@ -0,0 +1,105 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* printf-like formatting of 64-bit integers, in case the C library
+ printf() function does not support them. */
+
+#ifndef CAML_INT64_FORMAT_H
+#define CAML_INT64_FORMAT_H
+
+static void I64_format(char * buffer, char * fmt, int64_t x)
+{
+ static char conv_lower[] = "0123456789abcdef";
+ static char conv_upper[] = "0123456789ABCDEF";
+ char rawbuffer[24];
+ char justify, signstyle, filler, alternate, signedconv;
+ int base, width, sign, i, rawlen;
+ char * cvtbl;
+ char * p, * r;
+ int64_t wbase, digit;
+
+ /* Parsing of format */
+ justify = '+';
+ signstyle = '-';
+ filler = ' ';
+ alternate = 0;
+ base = 0;
+ signedconv = 0;
+ width = 0;
+ cvtbl = conv_lower;
+ for (p = fmt; *p != 0; p++) {
+ switch (*p) {
+ case '-':
+ justify = '-'; break;
+ case '+': case ' ':
+ signstyle = *p; break;
+ case '0':
+ filler = '0'; break;
+ case '#':
+ alternate = 1; break;
+ case '1': case '2': case '3': case '4': case '5':
+ case '6': case '7': case '8': case '9':
+ width = atoi(p);
+ while (p[1] >= '0' && p[1] <= '9') p++;
+ break;
+ case 'd': case 'i':
+ signedconv = 1; /* fallthrough */
+ case 'u':
+ base = 10; break;
+ case 'x':
+ base = 16; break;
+ case 'X':
+ base = 16; cvtbl = conv_upper; break;
+ case 'o':
+ base = 8; break;
+ }
+ }
+ if (base == 0) { buffer[0] = 0; return; }
+ /* Do the conversion */
+ sign = 1;
+ if (signedconv && I64_is_negative(x)) { sign = -1; x = I64_neg(x); }
+ r = rawbuffer + sizeof(rawbuffer);
+ wbase = I64_of_int32(base);
+ do {
+ I64_udivmod(x, wbase, &x, &digit);
+ *--r = cvtbl[I64_to_int32(digit)];
+ } while (! I64_is_zero(x));
+ rawlen = rawbuffer + sizeof(rawbuffer) - r;
+ /* Adjust rawlen to reflect additional chars (sign, etc) */
+ if (signedconv && (sign < 0 || signstyle != '-')) rawlen++;
+ if (alternate) {
+ if (base == 8) rawlen += 1;
+ if (base == 16) rawlen += 2;
+ }
+ /* Do the formatting */
+ p = buffer;
+ if (justify == '+' && filler == ' ') {
+ for (i = rawlen; i < width; i++) *p++ = ' ';
+ }
+ if (signedconv) {
+ if (sign < 0) *p++ = '-';
+ else if (signstyle != '-') *p++ = signstyle;
+ }
+ if (alternate && base == 8) *p++ = '0';
+ if (alternate && base == 16) { *p++ = '0'; *p++ = 'x'; }
+ if (justify == '+' && filler == '0') {
+ for (i = rawlen; i < width; i++) *p++ = '0';
+ }
+ while (r < rawbuffer + sizeof(rawbuffer)) *p++ = *r++;
+ if (justify == '-') {
+ for (i = rawlen; i < width; i++) *p++ = ' ';
+ }
+ *p = 0;
+}
+
+#endif /* CAML_INT64_FORMAT_H */
diff --git a/byterun/caml/int64_native.h b/byterun/caml/int64_native.h
new file mode 100644
index 0000000000..b6716ada2a
--- /dev/null
+++ b/byterun/caml/int64_native.h
@@ -0,0 +1,61 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Wrapper macros around native 64-bit integer arithmetic,
+ so that it has the same interface as the software emulation
+ provided in int64_emul.h */
+
+#ifndef CAML_INT64_NATIVE_H
+#define CAML_INT64_NATIVE_H
+
+#define I64_literal(hi,lo) ((int64_t)(hi) << 32 | (lo))
+#define I64_split(x,hi,lo) (hi = (uint32_t)((x)>>32), lo = (uint32_t)(x))
+#define I64_compare(x,y) (((x) > (y)) - ((x) < (y)))
+#define I64_ult(x,y) ((uint64_t)(x) < (uint64_t)(y))
+#define I64_neg(x) (-(x))
+#define I64_add(x,y) ((x) + (y))
+#define I64_sub(x,y) ((x) - (y))
+#define I64_mul(x,y) ((x) * (y))
+#define I64_is_zero(x) ((x) == 0)
+#define I64_is_negative(x) ((x) < 0)
+#define I64_is_min_int(x) ((x) == ((int64_t)1 << 63))
+#define I64_is_minus_one(x) ((x) == -1)
+
+#define I64_div(x,y) ((x) / (y))
+#define I64_mod(x,y) ((x) % (y))
+#define I64_udivmod(x,y,quo,rem) \
+ (*(rem) = (uint64_t)(x) % (uint64_t)(y), \
+ *(quo) = (uint64_t)(x) / (uint64_t)(y))
+#define I64_and(x,y) ((x) & (y))
+#define I64_or(x,y) ((x) | (y))
+#define I64_xor(x,y) ((x) ^ (y))
+#define I64_lsl(x,y) ((x) << (y))
+#define I64_asr(x,y) ((x) >> (y))
+#define I64_lsr(x,y) ((uint64_t)(x) >> (y))
+#define I64_to_intnat(x) ((intnat) (x))
+#define I64_of_intnat(x) ((intnat) (x))
+#define I64_to_int32(x) ((int32_t) (x))
+#define I64_of_int32(x) ((int64_t) (x))
+#define I64_to_double(x) ((double)(x))
+#define I64_of_double(x) ((int64_t)(x))
+
+#define I64_bswap(x) ((((x) & 0x00000000000000FFULL) << 56) | \
+ (((x) & 0x000000000000FF00ULL) << 40) | \
+ (((x) & 0x0000000000FF0000ULL) << 24) | \
+ (((x) & 0x00000000FF000000ULL) << 8) | \
+ (((x) & 0x000000FF00000000ULL) >> 8) | \
+ (((x) & 0x0000FF0000000000ULL) >> 24) | \
+ (((x) & 0x00FF000000000000ULL) >> 40) | \
+ (((x) & 0xFF00000000000000ULL) >> 56))
+
+#endif /* CAML_INT64_NATIVE_H */
diff --git a/byterun/caml/interp.h b/byterun/caml/interp.h
new file mode 100644
index 0000000000..c8e2f89f8e
--- /dev/null
+++ b/byterun/caml/interp.h
@@ -0,0 +1,31 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The bytecode interpreter */
+
+#ifndef CAML_INTERP_H
+#define CAML_INTERP_H
+
+#include "misc.h"
+#include "mlvalues.h"
+
+/* interpret a bytecode */
+value caml_interprete (code_t prog, asize_t prog_size);
+
+/* tell the runtime that a bytecode program might be needed */
+void caml_prepare_bytecode(code_t prog, asize_t prog_size);
+
+/* tell the runtime that a bytecode program is no more needed */
+void caml_release_bytecode(code_t prog, asize_t prog_size);
+
+#endif /* CAML_INTERP_H */
diff --git a/byterun/caml/intext.h b/byterun/caml/intext.h
new file mode 100644
index 0000000000..2c108a4ae0
--- /dev/null
+++ b/byterun/caml/intext.h
@@ -0,0 +1,168 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Structured input/output */
+
+#ifndef CAML_INTEXT_H
+#define CAML_INTEXT_H
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "misc.h"
+#include "mlvalues.h"
+
+/* <private> */
+#include "io.h"
+
+/* Magic number */
+
+#define Intext_magic_number 0x8495A6BE
+
+/* Codes for the compact format */
+
+#define PREFIX_SMALL_BLOCK 0x80
+#define PREFIX_SMALL_INT 0x40
+#define PREFIX_SMALL_STRING 0x20
+#define CODE_INT8 0x0
+#define CODE_INT16 0x1
+#define CODE_INT32 0x2
+#define CODE_INT64 0x3
+#define CODE_SHARED8 0x4
+#define CODE_SHARED16 0x5
+#define CODE_SHARED32 0x6
+#define CODE_BLOCK32 0x8
+#define CODE_BLOCK64 0x13
+#define CODE_STRING8 0x9
+#define CODE_STRING32 0xA
+#define CODE_DOUBLE_BIG 0xB
+#define CODE_DOUBLE_LITTLE 0xC
+#define CODE_DOUBLE_ARRAY8_BIG 0xD
+#define CODE_DOUBLE_ARRAY8_LITTLE 0xE
+#define CODE_DOUBLE_ARRAY32_BIG 0xF
+#define CODE_DOUBLE_ARRAY32_LITTLE 0x7
+#define CODE_CODEPOINTER 0x10
+#define CODE_INFIXPOINTER 0x11
+#define CODE_CUSTOM 0x12
+
+#if ARCH_FLOAT_ENDIANNESS == 0x76543210
+#define CODE_DOUBLE_NATIVE CODE_DOUBLE_BIG
+#define CODE_DOUBLE_ARRAY8_NATIVE CODE_DOUBLE_ARRAY8_BIG
+#define CODE_DOUBLE_ARRAY32_NATIVE CODE_DOUBLE_ARRAY32_BIG
+#else
+#define CODE_DOUBLE_NATIVE CODE_DOUBLE_LITTLE
+#define CODE_DOUBLE_ARRAY8_NATIVE CODE_DOUBLE_ARRAY8_LITTLE
+#define CODE_DOUBLE_ARRAY32_NATIVE CODE_DOUBLE_ARRAY32_LITTLE
+#endif
+
+/* Size-ing data structures for extern. Chosen so that
+ sizeof(struct trail_block) and sizeof(struct output_block)
+ are slightly below 8Kb. */
+
+#define ENTRIES_PER_TRAIL_BLOCK 1025
+#define SIZE_EXTERN_OUTPUT_BLOCK 8100
+
+/* The entry points */
+
+void caml_output_val (struct channel * chan, value v, value flags);
+ /* Output [v] with flags [flags] on the channel [chan]. */
+
+/* </private> */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAMLextern void caml_output_value_to_malloc(value v, value flags,
+ /*out*/ char ** buf,
+ /*out*/ intnat * len);
+ /* Output [v] with flags [flags] to a memory buffer allocated with
+ malloc. On return, [*buf] points to the buffer and [*len]
+ contains the number of bytes in buffer. */
+CAMLextern intnat caml_output_value_to_block(value v, value flags,
+ char * data, intnat len);
+ /* Output [v] with flags [flags] to a user-provided memory buffer.
+ [data] points to the start of this buffer, and [len] is its size
+ in bytes. Return the number of bytes actually written in buffer.
+ Raise [Failure] if buffer is too short. */
+
+/* <private> */
+value caml_input_val (struct channel * chan);
+ /* Read a structured value from the channel [chan]. */
+/* </private> */
+
+CAMLextern value caml_input_val_from_string (value str, intnat ofs);
+ /* Read a structured value from the OCaml string [str], starting
+ at offset [ofs]. */
+CAMLextern value caml_input_value_from_malloc(char * data, intnat ofs);
+ /* Read a structured value from a malloced buffer. [data] points
+ to the beginning of the buffer, and [ofs] is the offset of the
+ beginning of the externed data in this buffer. The buffer is
+ deallocated with [free] on return, or if an exception is raised. */
+CAMLextern value caml_input_value_from_block(char * data, intnat len);
+ /* Read a structured value from a user-provided buffer. [data] points
+ to the beginning of the externed data in this buffer,
+ and [len] is the length in bytes of valid data in this buffer.
+ The buffer is never deallocated by this routine. */
+
+/* Functions for writing user-defined marshallers */
+
+CAMLextern void caml_serialize_int_1(int i);
+CAMLextern void caml_serialize_int_2(int i);
+CAMLextern void caml_serialize_int_4(int32_t i);
+CAMLextern void caml_serialize_int_8(int64_t i);
+CAMLextern void caml_serialize_float_4(float f);
+CAMLextern void caml_serialize_float_8(double f);
+CAMLextern void caml_serialize_block_1(void * data, intnat len);
+CAMLextern void caml_serialize_block_2(void * data, intnat len);
+CAMLextern void caml_serialize_block_4(void * data, intnat len);
+CAMLextern void caml_serialize_block_8(void * data, intnat len);
+CAMLextern void caml_serialize_block_float_8(void * data, intnat len);
+
+CAMLextern int caml_deserialize_uint_1(void);
+CAMLextern int caml_deserialize_sint_1(void);
+CAMLextern int caml_deserialize_uint_2(void);
+CAMLextern int caml_deserialize_sint_2(void);
+CAMLextern uint32_t caml_deserialize_uint_4(void);
+CAMLextern int32_t caml_deserialize_sint_4(void);
+CAMLextern uint64_t caml_deserialize_uint_8(void);
+CAMLextern int64_t caml_deserialize_sint_8(void);
+CAMLextern float caml_deserialize_float_4(void);
+CAMLextern double caml_deserialize_float_8(void);
+CAMLextern void caml_deserialize_block_1(void * data, intnat len);
+CAMLextern void caml_deserialize_block_2(void * data, intnat len);
+CAMLextern void caml_deserialize_block_4(void * data, intnat len);
+CAMLextern void caml_deserialize_block_8(void * data, intnat len);
+CAMLextern void caml_deserialize_block_float_8(void * data, intnat len);
+CAMLextern void caml_deserialize_error(char * msg);
+
+/* <private> */
+
+/* Auxiliary stuff for sending code pointers */
+
+struct code_fragment {
+ char * code_start;
+ char * code_end;
+ unsigned char digest[16];
+ char digest_computed;
+};
+
+struct ext_table caml_code_fragments_table;
+
+/* </private> */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_INTEXT_H */
diff --git a/byterun/caml/io.h b/byterun/caml/io.h
new file mode 100644
index 0000000000..f0bc69f967
--- /dev/null
+++ b/byterun/caml/io.h
@@ -0,0 +1,116 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Buffered input/output */
+
+#ifndef CAML_IO_H
+#define CAML_IO_H
+
+#include "misc.h"
+#include "mlvalues.h"
+
+#ifndef IO_BUFFER_SIZE
+#define IO_BUFFER_SIZE 65536
+#endif
+
+#if defined(_WIN32)
+typedef __int64 file_offset;
+#elif defined(HAS_OFF_T)
+#include <sys/types.h>
+typedef off_t file_offset;
+#else
+typedef long file_offset;
+#endif
+
+struct channel {
+ int fd; /* Unix file descriptor */
+ file_offset offset; /* Absolute position of fd in the file */
+ char * end; /* Physical end of the buffer */
+ char * curr; /* Current position in the buffer */
+ char * max; /* Logical end of the buffer (for input) */
+ void * mutex; /* Placeholder for mutex (for systhreads) */
+ struct channel * next, * prev;/* Double chaining of channels (flush_all) */
+ int revealed; /* For Cash only */
+ int old_revealed; /* For Cash only */
+ int refcount; /* For flush_all and for Cash */
+ int flags; /* Bitfield */
+ char * name; /* Optional name (to report fd leaks) */
+ char buff[IO_BUFFER_SIZE]; /* The buffer itself */
+};
+
+enum {
+ CHANNEL_FLAG_FROM_SOCKET = 1 /* For Windows */
+};
+
+/* For an output channel:
+ [offset] is the absolute position of the beginning of the buffer [buff].
+ For an input channel:
+ [offset] is the absolute position of the logical end of the buffer, [max].
+*/
+
+/* Functions and macros that can be called from C. Take arguments of
+ type struct channel *. No locking is performed. */
+
+#define putch(channel, ch) do{ \
+ if ((channel)->curr >= (channel)->end) caml_flush_partial(channel); \
+ *((channel)->curr)++ = (ch); \
+}while(0)
+
+#define getch(channel) \
+ ((channel)->curr >= (channel)->max \
+ ? caml_refill(channel) \
+ : (unsigned char) *((channel)->curr)++)
+
+CAMLextern struct channel * caml_open_descriptor_in (int);
+CAMLextern struct channel * caml_open_descriptor_out (int);
+CAMLextern void caml_close_channel (struct channel *);
+CAMLextern int caml_channel_binary_mode (struct channel *);
+CAMLextern value caml_alloc_channel(struct channel *chan);
+
+CAMLextern int caml_flush_partial (struct channel *);
+CAMLextern void caml_flush (struct channel *);
+CAMLextern void caml_putword (struct channel *, uint32_t);
+CAMLextern int caml_putblock (struct channel *, char *, intnat);
+CAMLextern void caml_really_putblock (struct channel *, char *, intnat);
+
+CAMLextern unsigned char caml_refill (struct channel *);
+CAMLextern uint32_t caml_getword (struct channel *);
+CAMLextern int caml_getblock (struct channel *, char *, intnat);
+CAMLextern int caml_really_getblock (struct channel *, char *, intnat);
+
+/* Extract a struct channel * from the heap object representing it */
+
+#define Channel(v) (*((struct channel **) (Data_custom_val(v))))
+
+/* The locking machinery */
+
+CAMLextern void (*caml_channel_mutex_free) (struct channel *);
+CAMLextern void (*caml_channel_mutex_lock) (struct channel *);
+CAMLextern void (*caml_channel_mutex_unlock) (struct channel *);
+CAMLextern void (*caml_channel_mutex_unlock_exn) (void);
+
+CAMLextern struct channel * caml_all_opened_channels;
+
+#define Lock(channel) \
+ if (caml_channel_mutex_lock != NULL) (*caml_channel_mutex_lock)(channel)
+#define Unlock(channel) \
+ if (caml_channel_mutex_unlock != NULL) (*caml_channel_mutex_unlock)(channel)
+#define Unlock_exn() \
+ if (caml_channel_mutex_unlock_exn != NULL) (*caml_channel_mutex_unlock_exn)()
+
+/* Conversion between file_offset and int64_t */
+
+#define Val_file_offset(fofs) caml_copy_int64(fofs)
+#define File_offset_val(v) ((file_offset) Int64_val(v))
+
+#endif /* CAML_IO_H */
diff --git a/byterun/caml/major_gc.h b/byterun/caml/major_gc.h
new file mode 100644
index 0000000000..047f16a4ea
--- /dev/null
+++ b/byterun/caml/major_gc.h
@@ -0,0 +1,60 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_MAJOR_GC_H
+#define CAML_MAJOR_GC_H
+
+
+#include "freelist.h"
+#include "misc.h"
+
+typedef struct {
+ void *block; /* address of the malloced block this chunk lives in */
+ asize_t alloc; /* in bytes, used for compaction */
+ asize_t size; /* in bytes */
+ char *next;
+} heap_chunk_head;
+
+#define Chunk_size(c) (((heap_chunk_head *) (c)) [-1]).size
+#define Chunk_alloc(c) (((heap_chunk_head *) (c)) [-1]).alloc
+#define Chunk_next(c) (((heap_chunk_head *) (c)) [-1]).next
+#define Chunk_block(c) (((heap_chunk_head *) (c)) [-1]).block
+
+extern int caml_gc_phase;
+extern int caml_gc_subphase;
+extern uintnat caml_allocated_words;
+extern double caml_extra_heap_resources;
+extern uintnat caml_dependent_size, caml_dependent_allocated;
+extern uintnat caml_fl_wsz_at_phase_change;
+
+#define Phase_mark 0
+#define Phase_sweep 1
+#define Phase_idle 2
+#define Subphase_main 10
+#define Subphase_weak1 11
+#define Subphase_weak2 12
+#define Subphase_final 13
+
+CAMLextern char *caml_heap_start;
+extern uintnat total_heap_size;
+extern char *caml_gc_sweep_hp;
+
+void caml_init_major_heap (asize_t); /* size in bytes */
+asize_t caml_round_heap_chunk_wsz (asize_t);
+void caml_darken (value, value *);
+intnat caml_major_collection_slice (intnat);
+void major_collection (void);
+void caml_finish_major_cycle (void);
+
+
+#endif /* CAML_MAJOR_GC_H */
diff --git a/byterun/caml/md5.h b/byterun/caml/md5.h
new file mode 100644
index 0000000000..f63667d56a
--- /dev/null
+++ b/byterun/caml/md5.h
@@ -0,0 +1,41 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1999 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* MD5 message digest */
+
+#ifndef CAML_MD5_H
+#define CAML_MD5_H
+
+
+#include "mlvalues.h"
+#include "io.h"
+
+CAMLextern value caml_md5_string (value str, value ofs, value len);
+CAMLextern value caml_md5_chan (value vchan, value len);
+CAMLextern void caml_md5_block(unsigned char digest[16],
+ void * data, uintnat len);
+
+struct MD5Context {
+ uint32_t buf[4];
+ uint32_t bits[2];
+ unsigned char in[64];
+};
+
+CAMLextern void caml_MD5Init (struct MD5Context *context);
+CAMLextern void caml_MD5Update (struct MD5Context *context, unsigned char *buf,
+ uintnat len);
+CAMLextern void caml_MD5Final (unsigned char *digest, struct MD5Context *ctx);
+CAMLextern void caml_MD5Transform (uint32_t *buf, uint32_t *in);
+
+
+#endif /* CAML_MD5_H */
diff --git a/byterun/caml/memory.h b/byterun/caml/memory.h
new file mode 100644
index 0000000000..9c8657ad39
--- /dev/null
+++ b/byterun/caml/memory.h
@@ -0,0 +1,434 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Allocation macros and functions */
+
+#ifndef CAML_MEMORY_H
+#define CAML_MEMORY_H
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "config.h"
+/* <private> */
+#include "gc.h"
+#include "major_gc.h"
+#include "minor_gc.h"
+/* </private> */
+#include "misc.h"
+#include "mlvalues.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+CAMLextern value caml_alloc_shr (mlsize_t wosize, tag_t);
+CAMLextern void caml_adjust_gc_speed (mlsize_t, mlsize_t);
+CAMLextern void caml_alloc_dependent_memory (mlsize_t bsz);
+CAMLextern void caml_free_dependent_memory (mlsize_t bsz);
+CAMLextern void caml_modify (value *, value);
+CAMLextern void caml_initialize (value *, value);
+CAMLextern value caml_check_urgent_gc (value);
+CAMLextern void * caml_stat_alloc (asize_t); /* Size in bytes. */
+CAMLextern void caml_stat_free (void *);
+CAMLextern void * caml_stat_resize (void *, asize_t); /* Size in bytes. */
+char *caml_alloc_for_heap (asize_t request); /* Size in bytes. */
+void caml_free_for_heap (char *mem);
+int caml_add_to_heap (char *mem);
+color_t caml_allocation_color (void *hp);
+
+/* void caml_shrink_heap (char *); Only used in compact.c */
+
+/* <private> */
+
+#ifdef DEBUG
+#define DEBUG_clear(result, wosize) do{ \
+ uintnat caml__DEBUG_i; \
+ for (caml__DEBUG_i = 0; caml__DEBUG_i < (wosize); ++ caml__DEBUG_i){ \
+ Field ((result), caml__DEBUG_i) = Debug_uninit_minor; \
+ } \
+}while(0)
+#else
+#define DEBUG_clear(result, wosize)
+#endif
+
+#define Alloc_small(result, wosize, tag) do{ CAMLassert ((wosize) >= 1); \
+ CAMLassert ((tag_t) (tag) < 256); \
+ CAMLassert ((wosize) <= Max_young_wosize); \
+ caml_young_ptr -= Whsize_wosize (wosize); \
+ if (caml_young_ptr < caml_young_start){ \
+ caml_young_ptr += Whsize_wosize (wosize); \
+ Setup_for_gc; \
+ caml_minor_collection (); \
+ Restore_after_gc; \
+ caml_young_ptr -= Whsize_wosize (wosize); \
+ } \
+ Hd_hp (caml_young_ptr) = Make_header ((wosize), (tag), Caml_black); \
+ (result) = Val_hp (caml_young_ptr); \
+ DEBUG_clear ((result), (wosize)); \
+}while(0)
+
+/* Deprecated alias for [caml_modify] */
+
+#define Modify(fp,val) caml_modify((fp), (val))
+
+/* </private> */
+
+struct caml__roots_block {
+ struct caml__roots_block *next;
+ intnat ntables;
+ intnat nitems;
+ value *tables [5];
+};
+
+CAMLextern struct caml__roots_block *caml_local_roots; /* defined in roots.c */
+
+/* The following macros are used to declare C local variables and
+ function parameters of type [value].
+
+ The function body must start with one of the [CAMLparam] macros.
+ If the function has no parameter of type [value], use [CAMLparam0].
+ If the function has 1 to 5 [value] parameters, use the corresponding
+ [CAMLparam] with the parameters as arguments.
+ If the function has more than 5 [value] parameters, use [CAMLparam5]
+ for the first 5 parameters, and one or more calls to the [CAMLxparam]
+ macros for the others.
+ If the function takes an array of [value]s as argument, use
+ [CAMLparamN] to declare it (or [CAMLxparamN] if you already have a
+ call to [CAMLparam] for some other arguments).
+
+ If you need local variables of type [value], declare them with one
+ or more calls to the [CAMLlocal] macros at the beginning of the
+ function, after the call to CAMLparam. Use [CAMLlocalN] (at the
+ beginning of the function) to declare an array of [value]s.
+
+ Your function may raise an exception or return a [value] with the
+ [CAMLreturn] macro. Its argument is simply the [value] returned by
+ your function. Do NOT directly return a [value] with the [return]
+ keyword. If your function returns void, use [CAMLreturn0]. If you
+ un-register the local roots (i.e. undo the effects of the [CAMLparam*]
+ and [CAMLlocal] macros) without returning immediately, use [CAMLdrop].
+
+ All the identifiers beginning with "caml__" are reserved by OCaml.
+ Do not use them for anything (local or global variables, struct or
+ union tags, macros, etc.)
+*/
+
+#define CAMLparam0() \
+ struct caml__roots_block *caml__frame = caml_local_roots
+
+#define CAMLparam1(x) \
+ CAMLparam0 (); \
+ CAMLxparam1 (x)
+
+#define CAMLparam2(x, y) \
+ CAMLparam0 (); \
+ CAMLxparam2 (x, y)
+
+#define CAMLparam3(x, y, z) \
+ CAMLparam0 (); \
+ CAMLxparam3 (x, y, z)
+
+#define CAMLparam4(x, y, z, t) \
+ CAMLparam0 (); \
+ CAMLxparam4 (x, y, z, t)
+
+#define CAMLparam5(x, y, z, t, u) \
+ CAMLparam0 (); \
+ CAMLxparam5 (x, y, z, t, u)
+
+#define CAMLparamN(x, size) \
+ CAMLparam0 (); \
+ CAMLxparamN (x, (size))
+
+/* CAMLunused is preserved for compatibility reasons.
+ Instead of the legacy GCC/Clang-only
+ CAMLunused foo;
+ you should prefer
+ CAMLunused_start foo CAMLunused_end;
+ which supports both GCC/Clang and MSVC.
+*/
+#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 7))
+ #define CAMLunused_start __attribute__ ((unused))
+ #define CAMLunused_end
+ #define CAMLunused __attribute__ ((unused))
+#elif _MSC_VER >= 1500
+ #define CAMLunused_start __pragma( warning (push) ) \
+ __pragma( warning (disable:4189 ) )
+ #define CAMLunused_end __pragma( warning (pop))
+ #define CAMLunused
+#else
+ #define CAMLunused_start
+ #define CAMLunused_end
+ #define CAMLunused
+#endif
+
+#define CAMLxparam1(x) \
+ struct caml__roots_block caml__roots_##x; \
+ CAMLunused_start int caml__dummy_##x = ( \
+ (caml__roots_##x.next = caml_local_roots), \
+ (caml_local_roots = &caml__roots_##x), \
+ (caml__roots_##x.nitems = 1), \
+ (caml__roots_##x.ntables = 1), \
+ (caml__roots_##x.tables [0] = &x), \
+ 0) \
+ CAMLunused_end
+
+#define CAMLxparam2(x, y) \
+ struct caml__roots_block caml__roots_##x; \
+ CAMLunused_start int caml__dummy_##x = ( \
+ (caml__roots_##x.next = caml_local_roots), \
+ (caml_local_roots = &caml__roots_##x), \
+ (caml__roots_##x.nitems = 1), \
+ (caml__roots_##x.ntables = 2), \
+ (caml__roots_##x.tables [0] = &x), \
+ (caml__roots_##x.tables [1] = &y), \
+ 0) \
+ CAMLunused_end
+
+#define CAMLxparam3(x, y, z) \
+ struct caml__roots_block caml__roots_##x; \
+ CAMLunused_start int caml__dummy_##x = ( \
+ (caml__roots_##x.next = caml_local_roots), \
+ (caml_local_roots = &caml__roots_##x), \
+ (caml__roots_##x.nitems = 1), \
+ (caml__roots_##x.ntables = 3), \
+ (caml__roots_##x.tables [0] = &x), \
+ (caml__roots_##x.tables [1] = &y), \
+ (caml__roots_##x.tables [2] = &z), \
+ 0) \
+ CAMLunused_end
+
+#define CAMLxparam4(x, y, z, t) \
+ struct caml__roots_block caml__roots_##x; \
+ CAMLunused_start int caml__dummy_##x = ( \
+ (caml__roots_##x.next = caml_local_roots), \
+ (caml_local_roots = &caml__roots_##x), \
+ (caml__roots_##x.nitems = 1), \
+ (caml__roots_##x.ntables = 4), \
+ (caml__roots_##x.tables [0] = &x), \
+ (caml__roots_##x.tables [1] = &y), \
+ (caml__roots_##x.tables [2] = &z), \
+ (caml__roots_##x.tables [3] = &t), \
+ 0) \
+ CAMLunused_end
+
+#define CAMLxparam5(x, y, z, t, u) \
+ struct caml__roots_block caml__roots_##x; \
+ CAMLunused_start int caml__dummy_##x = ( \
+ (caml__roots_##x.next = caml_local_roots), \
+ (caml_local_roots = &caml__roots_##x), \
+ (caml__roots_##x.nitems = 1), \
+ (caml__roots_##x.ntables = 5), \
+ (caml__roots_##x.tables [0] = &x), \
+ (caml__roots_##x.tables [1] = &y), \
+ (caml__roots_##x.tables [2] = &z), \
+ (caml__roots_##x.tables [3] = &t), \
+ (caml__roots_##x.tables [4] = &u), \
+ 0) \
+ CAMLunused_end
+
+#define CAMLxparamN(x, size) \
+ struct caml__roots_block caml__roots_##x; \
+ CAMLunused_start int caml__dummy_##x = ( \
+ (caml__roots_##x.next = caml_local_roots), \
+ (caml_local_roots = &caml__roots_##x), \
+ (caml__roots_##x.nitems = (size)), \
+ (caml__roots_##x.ntables = 1), \
+ (caml__roots_##x.tables[0] = &(x[0])), \
+ 0) \
+ CAMLunused_end
+
+#define CAMLlocal1(x) \
+ value x = Val_unit; \
+ CAMLxparam1 (x)
+
+#define CAMLlocal2(x, y) \
+ value x = Val_unit, y = Val_unit; \
+ CAMLxparam2 (x, y)
+
+#define CAMLlocal3(x, y, z) \
+ value x = Val_unit, y = Val_unit, z = Val_unit; \
+ CAMLxparam3 (x, y, z)
+
+#define CAMLlocal4(x, y, z, t) \
+ value x = Val_unit, y = Val_unit, z = Val_unit, t = Val_unit; \
+ CAMLxparam4 (x, y, z, t)
+
+#define CAMLlocal5(x, y, z, t, u) \
+ value x = Val_unit, y = Val_unit, z = Val_unit, t = Val_unit, u = Val_unit; \
+ CAMLxparam5 (x, y, z, t, u)
+
+#define CAMLlocalN(x, size) \
+ value x [(size)]; \
+ int caml__i_##x; \
+ for (caml__i_##x = 0; caml__i_##x < size; caml__i_##x ++) { \
+ x[caml__i_##x] = Val_unit; \
+ } \
+ CAMLxparamN (x, (size))
+
+
+#define CAMLdrop caml_local_roots = caml__frame
+
+#define CAMLreturn0 do{ \
+ CAMLdrop; \
+ return; \
+}while (0)
+
+#define CAMLreturnT(type, result) do{ \
+ type caml__temp_result = (result); \
+ CAMLdrop; \
+ return caml__temp_result; \
+}while(0)
+
+#define CAMLreturn(result) CAMLreturnT(value, result)
+
+#define CAMLnoreturn ((void) caml__frame)
+
+
+/* convenience macro */
+#define Store_field(block, offset, val) do{ \
+ mlsize_t caml__temp_offset = (offset); \
+ value caml__temp_val = (val); \
+ caml_modify (&Field ((block), caml__temp_offset), caml__temp_val); \
+}while(0)
+
+/*
+ NOTE: [Begin_roots] and [End_roots] are superseded by [CAMLparam]*,
+ [CAMLxparam]*, [CAMLlocal]*, [CAMLreturn].
+
+ [Begin_roots] and [End_roots] are used for C variables that are GC roots.
+ It must contain all values in C local variables and function parameters
+ at the time the minor GC is called.
+ Usage:
+ After initialising your local variables to legal OCaml values, but before
+ calling allocation functions, insert [Begin_roots_n(v1, ... vn)], where
+ v1 ... vn are your variables of type [value] that you want to be updated
+ across allocations.
+ At the end, insert [End_roots()].
+
+ Note that [Begin_roots] opens a new block, and [End_roots] closes it.
+ Thus they must occur in matching pairs at the same brace nesting level.
+
+ You can use [Val_unit] as a dummy initial value for your variables.
+*/
+
+#define Begin_root Begin_roots1
+
+#define Begin_roots1(r0) { \
+ struct caml__roots_block caml__roots_block; \
+ caml__roots_block.next = caml_local_roots; \
+ caml_local_roots = &caml__roots_block; \
+ caml__roots_block.nitems = 1; \
+ caml__roots_block.ntables = 1; \
+ caml__roots_block.tables[0] = &(r0);
+
+#define Begin_roots2(r0, r1) { \
+ struct caml__roots_block caml__roots_block; \
+ caml__roots_block.next = caml_local_roots; \
+ caml_local_roots = &caml__roots_block; \
+ caml__roots_block.nitems = 1; \
+ caml__roots_block.ntables = 2; \
+ caml__roots_block.tables[0] = &(r0); \
+ caml__roots_block.tables[1] = &(r1);
+
+#define Begin_roots3(r0, r1, r2) { \
+ struct caml__roots_block caml__roots_block; \
+ caml__roots_block.next = caml_local_roots; \
+ caml_local_roots = &caml__roots_block; \
+ caml__roots_block.nitems = 1; \
+ caml__roots_block.ntables = 3; \
+ caml__roots_block.tables[0] = &(r0); \
+ caml__roots_block.tables[1] = &(r1); \
+ caml__roots_block.tables[2] = &(r2);
+
+#define Begin_roots4(r0, r1, r2, r3) { \
+ struct caml__roots_block caml__roots_block; \
+ caml__roots_block.next = caml_local_roots; \
+ caml_local_roots = &caml__roots_block; \
+ caml__roots_block.nitems = 1; \
+ caml__roots_block.ntables = 4; \
+ caml__roots_block.tables[0] = &(r0); \
+ caml__roots_block.tables[1] = &(r1); \
+ caml__roots_block.tables[2] = &(r2); \
+ caml__roots_block.tables[3] = &(r3);
+
+#define Begin_roots5(r0, r1, r2, r3, r4) { \
+ struct caml__roots_block caml__roots_block; \
+ caml__roots_block.next = caml_local_roots; \
+ caml_local_roots = &caml__roots_block; \
+ caml__roots_block.nitems = 1; \
+ caml__roots_block.ntables = 5; \
+ caml__roots_block.tables[0] = &(r0); \
+ caml__roots_block.tables[1] = &(r1); \
+ caml__roots_block.tables[2] = &(r2); \
+ caml__roots_block.tables[3] = &(r3); \
+ caml__roots_block.tables[4] = &(r4);
+
+#define Begin_roots_block(table, size) { \
+ struct caml__roots_block caml__roots_block; \
+ caml__roots_block.next = caml_local_roots; \
+ caml_local_roots = &caml__roots_block; \
+ caml__roots_block.nitems = (size); \
+ caml__roots_block.ntables = 1; \
+ caml__roots_block.tables[0] = (table);
+
+#define End_roots() caml_local_roots = caml__roots_block.next; }
+
+
+/* [caml_register_global_root] registers a global C variable as a memory root
+ for the duration of the program, or until [caml_remove_global_root] is
+ called. */
+
+CAMLextern void caml_register_global_root (value *);
+
+/* [caml_remove_global_root] removes a memory root registered on a global C
+ variable with [caml_register_global_root]. */
+
+CAMLextern void caml_remove_global_root (value *);
+
+/* [caml_register_generational_global_root] registers a global C
+ variable as a memory root for the duration of the program, or until
+ [caml_remove_generational_global_root] is called.
+ The program guarantees that the value contained in this variable
+ will not be assigned directly. If the program needs to change
+ the value of this variable, it must do so by calling
+ [caml_modify_generational_global_root]. The [value *] pointer
+ passed to [caml_register_generational_global_root] must contain
+ a valid OCaml value before the call.
+ In return for these constraints, scanning of memory roots during
+ minor collection is made more efficient. */
+
+CAMLextern void caml_register_generational_global_root (value *);
+
+/* [caml_remove_generational_global_root] removes a memory root
+ registered on a global C variable with
+ [caml_register_generational_global_root]. */
+
+CAMLextern void caml_remove_generational_global_root (value *);
+
+/* [caml_modify_generational_global_root(r, newval)]
+ modifies the value contained in [r], storing [newval] inside.
+ In other words, the assignment [*r = newval] is performed,
+ but in a way that is compatible with the optimized scanning of
+ generational global roots. [r] must be a global memory root
+ previously registered with [caml_register_generational_global_root]. */
+
+CAMLextern void caml_modify_generational_global_root(value *r, value newval);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_MEMORY_H */
diff --git a/byterun/caml/minor_gc.h b/byterun/caml/minor_gc.h
new file mode 100644
index 0000000000..281e0b5e5e
--- /dev/null
+++ b/byterun/caml/minor_gc.h
@@ -0,0 +1,53 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_MINOR_GC_H
+#define CAML_MINOR_GC_H
+
+
+#include "address_class.h"
+
+CAMLextern value *caml_young_start, *caml_young_ptr;
+CAMLextern value *caml_young_end, *caml_young_limit;
+extern asize_t caml_minor_heap_wsz;
+extern int caml_in_minor_collection;
+
+struct caml_ref_table {
+ value **base;
+ value **end;
+ value **threshold;
+ value **ptr;
+ value **limit;
+ asize_t size;
+ asize_t reserve;
+};
+CAMLextern struct caml_ref_table caml_ref_table, caml_weak_ref_table,
+ caml_finalize_table;
+
+extern void caml_set_minor_heap_size (asize_t); /* size in bytes */
+extern void caml_empty_minor_heap (void);
+CAMLextern void caml_minor_collection (void);
+CAMLextern void garbage_collection (void); /* def in asmrun/signals_asm.c */
+extern void caml_realloc_ref_table (struct caml_ref_table *);
+extern void caml_alloc_table (struct caml_ref_table *, asize_t, asize_t);
+extern void caml_oldify_one (value, value *);
+extern void caml_oldify_mopup (void);
+
+#define Oldify(p) do{ \
+ value __oldify__v__ = *p; \
+ if (Is_block (__oldify__v__) && Is_young (__oldify__v__)){ \
+ caml_oldify_one (__oldify__v__, (p)); \
+ } \
+ }while(0)
+
+#endif /* CAML_MINOR_GC_H */
diff --git a/byterun/caml/misc.h b/byterun/caml/misc.h
new file mode 100644
index 0000000000..13a0e49813
--- /dev/null
+++ b/byterun/caml/misc.h
@@ -0,0 +1,210 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Miscellaneous macros and variables. */
+
+#ifndef CAML_MISC_H
+#define CAML_MISC_H
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "config.h"
+
+/* Standard definitions */
+
+#include <stddef.h>
+#include <stdlib.h>
+
+/* Basic types and constants */
+
+typedef size_t asize_t;
+
+#ifndef NULL
+#define NULL 0
+#endif
+
+/* <private> */
+typedef char * addr;
+/* </private> */
+
+/* Noreturn is preserved for compatibility reasons.
+ Instead of the legacy GCC/Clang-only
+ foo Noreturn;
+ you should prefer
+ CAMLnoreturn_start foo CAMLnoreturn_end;
+ which supports both GCC/Clang and MSVC.
+
+ Note: CAMLnoreturn is a different macro defined in memory.h,
+ to be used in function bodies rather than aprototype attribute.
+*/
+#ifdef __GNUC__
+ /* Works only in GCC 2.5 and later */
+ #define CAMLnoreturn_start
+ #define CAMLnoreturn_end __attribute__ ((noreturn))
+ #define Noreturn __attribute__ ((noreturn))
+#elif _MSC_VER >= 1500
+ #define CAMLnoreturn_start __declspec(noreturn)
+ #define CAMLnoreturn_end
+ #define Noreturn
+#else
+ #define CAMLnoreturn_start
+ #define CAMLnoreturn_end
+ #define Noreturn
+#endif
+
+
+
+/* Export control (to mark primitives and to handle Windows DLL) */
+
+#define CAMLexport
+#define CAMLprim
+#define CAMLextern extern
+
+/* Weak function definitions that can be overriden by external libs */
+/* Conservatively restricted to ELF and MacOSX platforms */
+#if defined(__GNUC__) && (defined (__ELF__) || defined(__APPLE__))
+#define CAMLweakdef __attribute__((weak))
+#else
+#define CAMLweakdef
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* GC timing hooks. These can be assigned by the user.
+ [caml_minor_gc_begin_hook] must not allocate nor change any heap value.
+ The others can allocate and even call back to OCaml code.
+*/
+typedef void (*caml_timing_hook) (void);
+extern caml_timing_hook caml_major_slice_begin_hook, caml_major_slice_end_hook;
+extern caml_timing_hook caml_minor_gc_begin_hook, caml_minor_gc_end_hook;
+extern caml_timing_hook caml_finalise_begin_hook, caml_finalise_end_hook;
+
+/* Assertions */
+
+#ifdef DEBUG
+#define CAMLassert(x) \
+ ((x) ? (void) 0 : caml_failed_assert ( #x , __FILE__, __LINE__))
+CAMLnoreturn_start
+CAMLextern int caml_failed_assert (char *, char *, int)
+CAMLnoreturn_end;
+#else
+#define CAMLassert(x) ((void) 0)
+#endif
+
+CAMLnoreturn_start
+CAMLextern void caml_fatal_error (char *msg)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_fatal_error_arg (char *fmt, char *arg)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+CAMLextern void caml_fatal_error_arg2 (char *fmt1, char *arg1,
+ char *fmt2, char *arg2)
+CAMLnoreturn_end;
+
+/* Safe string operations */
+
+CAMLextern char * caml_strdup(const char * s);
+CAMLextern char * caml_strconcat(int n, ...); /* n args of const char * type */
+
+/* <private> */
+
+/* Data structures */
+
+struct ext_table {
+ int size;
+ int capacity;
+ void ** contents;
+};
+
+extern void caml_ext_table_init(struct ext_table * tbl, int init_capa);
+extern int caml_ext_table_add(struct ext_table * tbl, void * data);
+extern void caml_ext_table_remove(struct ext_table * tbl, void * data);
+extern void caml_ext_table_free(struct ext_table * tbl, int free_entries);
+
+/* GC flags and messages */
+
+extern uintnat caml_verb_gc;
+void caml_gc_message (int, char *, uintnat);
+
+/* Runtime warnings */
+extern uintnat caml_runtime_warnings;
+int caml_runtime_warnings_active(void);
+
+/* Memory routines */
+
+char *caml_aligned_malloc (asize_t bsize, int, void **);
+
+#ifdef DEBUG
+#ifdef ARCH_SIXTYFOUR
+#define Debug_tag(x) (0xD700D7D7D700D6D7ul \
+ | ((uintnat) (x) << 16) \
+ | ((uintnat) (x) << 48))
+#else
+#define Debug_tag(x) (0xD700D6D7ul | ((uintnat) (x) << 16))
+#endif /* ARCH_SIXTYFOUR */
+
+/*
+ 00 -> free words in minor heap
+ 01 -> fields of free list blocks in major heap
+ 03 -> heap chunks deallocated by heap shrinking
+ 04 -> fields deallocated by [caml_obj_truncate]
+ 10 -> uninitialised fields of minor objects
+ 11 -> uninitialised fields of major objects
+ 15 -> uninitialised words of [caml_aligned_malloc] blocks
+ 85 -> filler bytes of [caml_aligned_malloc]
+
+ special case (byte by byte):
+ D7 -> uninitialised words of [caml_stat_alloc] blocks
+*/
+#define Debug_free_minor Debug_tag (0x00)
+#define Debug_free_major Debug_tag (0x01)
+#define Debug_free_shrink Debug_tag (0x03)
+#define Debug_free_truncate Debug_tag (0x04)
+#define Debug_uninit_minor Debug_tag (0x10)
+#define Debug_uninit_major Debug_tag (0x11)
+#define Debug_uninit_align Debug_tag (0x15)
+#define Debug_filler_align Debug_tag (0x85)
+
+#define Debug_uninit_stat 0xD7
+
+/* Note: the first argument is in fact a [value] but we don't have this
+ type available yet because we can't include [mlvalues.h] in this file.
+*/
+extern void caml_set_fields (intnat v, unsigned long, unsigned long);
+#endif /* DEBUG */
+
+
+#ifndef CAML_AVOID_CONFLICTS
+#define Assert CAMLassert
+#endif
+
+/* snprintf emulation for Win32 */
+
+#ifdef _WIN32
+extern int caml_snprintf(char * buf, size_t size, const char * format, ...);
+#define snprintf caml_snprintf
+#endif
+
+/* </private> */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_MISC_H */
diff --git a/byterun/caml/mlvalues.h b/byterun/caml/mlvalues.h
new file mode 100644
index 0000000000..3b94d010c6
--- /dev/null
+++ b/byterun/caml/mlvalues.h
@@ -0,0 +1,305 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_MLVALUES_H
+#define CAML_MLVALUES_H
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "config.h"
+#include "misc.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Definitions
+
+ word: Four bytes on 32 and 16 bit architectures,
+ eight bytes on 64 bit architectures.
+ long: A C integer having the same number of bytes as a word.
+ val: The ML representation of something. A long or a block or a pointer
+ outside the heap. If it is a block, it is the (encoded) address
+ of an object. If it is a long, it is encoded as well.
+ block: Something allocated. It always has a header and some
+ fields or some number of bytes (a multiple of the word size).
+ field: A word-sized val which is part of a block.
+ bp: Pointer to the first byte of a block. (a char *)
+ op: Pointer to the first field of a block. (a value *)
+ hp: Pointer to the header of a block. (a char *)
+ int32_t: Four bytes on all architectures.
+ int64_t: Eight bytes on all architectures.
+
+ Remark: A block size is always a multiple of the word size, and at least
+ one word plus the header.
+
+ bosize: Size (in bytes) of the "bytes" part.
+ wosize: Size (in words) of the "fields" part.
+ bhsize: Size (in bytes) of the block with its header.
+ whsize: Size (in words) of the block with its header.
+
+ hd: A header.
+ tag: The value of the tag field of the header.
+ color: The value of the color field of the header.
+ This is for use only by the GC.
+*/
+
+typedef intnat value;
+typedef uintnat header_t;
+typedef uintnat mlsize_t;
+typedef unsigned int tag_t; /* Actually, an unsigned char */
+typedef uintnat color_t;
+typedef uintnat mark_t;
+
+/* Longs vs blocks. */
+#define Is_long(x) (((x) & 1) != 0)
+#define Is_block(x) (((x) & 1) == 0)
+
+/* Conversion macro names are always of the form "to_from". */
+/* Example: Val_long as in "Val from long" or "Val of long". */
+#define Val_long(x) (((intnat)(x) << 1) + 1)
+#define Long_val(x) ((x) >> 1)
+#define Max_long (((intnat)1 << (8 * sizeof(value) - 2)) - 1)
+#define Min_long (-((intnat)1 << (8 * sizeof(value) - 2)))
+#define Val_int(x) Val_long(x)
+#define Int_val(x) ((int) Long_val(x))
+#define Unsigned_long_val(x) ((uintnat)(x) >> 1)
+#define Unsigned_int_val(x) ((int) Unsigned_long_val(x))
+
+/* Structure of the header:
+
+For 16-bit and 32-bit architectures:
+ +--------+-------+-----+
+ | wosize | color | tag |
+ +--------+-------+-----+
+bits 31 10 9 8 7 0
+
+For 64-bit architectures:
+
+ +--------+-------+-----+
+ | wosize | color | tag |
+ +--------+-------+-----+
+bits 63 10 9 8 7 0
+
+*/
+
+#define Tag_hd(hd) ((tag_t) ((hd) & 0xFF))
+#define Wosize_hd(hd) ((mlsize_t) ((hd) >> 10))
+
+#define Hd_val(val) (((header_t *) (val)) [-1]) /* Also an l-value. */
+#define Hd_op(op) (Hd_val (op)) /* Also an l-value. */
+#define Hd_bp(bp) (Hd_val (bp)) /* Also an l-value. */
+#define Hd_hp(hp) (* ((header_t *) (hp))) /* Also an l-value. */
+#define Hp_val(val) (((header_t *) (val)) - 1)
+#define Hp_op(op) (Hp_val (op))
+#define Hp_bp(bp) (Hp_val (bp))
+#define Val_op(op) ((value) (op))
+#define Val_hp(hp) ((value) (((header_t *) (hp)) + 1))
+#define Op_hp(hp) ((value *) Val_hp (hp))
+#define Bp_hp(hp) ((char *) Val_hp (hp))
+
+#define Num_tags (1 << 8)
+#ifdef ARCH_SIXTYFOUR
+#define Max_wosize (((intnat)1 << 54) - 1)
+#else
+#define Max_wosize ((1 << 22) - 1)
+#endif
+
+#define Wosize_val(val) (Wosize_hd (Hd_val (val)))
+#define Wosize_op(op) (Wosize_val (op))
+#define Wosize_bp(bp) (Wosize_val (bp))
+#define Wosize_hp(hp) (Wosize_hd (Hd_hp (hp)))
+#define Whsize_wosize(sz) ((sz) + 1)
+#define Wosize_whsize(sz) ((sz) - 1)
+#define Wosize_bhsize(sz) ((sz) / sizeof (value) - 1)
+#define Bsize_wsize(sz) ((sz) * sizeof (value))
+#define Wsize_bsize(sz) ((sz) / sizeof (value))
+#define Bhsize_wosize(sz) (Bsize_wsize (Whsize_wosize (sz)))
+#define Bhsize_bosize(sz) ((sz) + sizeof (header_t))
+#define Bosize_val(val) (Bsize_wsize (Wosize_val (val)))
+#define Bosize_op(op) (Bosize_val (Val_op (op)))
+#define Bosize_bp(bp) (Bosize_val (Val_bp (bp)))
+#define Bosize_hd(hd) (Bsize_wsize (Wosize_hd (hd)))
+#define Whsize_hp(hp) (Whsize_wosize (Wosize_hp (hp)))
+#define Whsize_val(val) (Whsize_hp (Hp_val (val)))
+#define Whsize_bp(bp) (Whsize_val (Val_bp (bp)))
+#define Whsize_hd(hd) (Whsize_wosize (Wosize_hd (hd)))
+#define Bhsize_hp(hp) (Bsize_wsize (Whsize_hp (hp)))
+#define Bhsize_hd(hd) (Bsize_wsize (Whsize_hd (hd)))
+
+#ifdef ARCH_BIG_ENDIAN
+#define Tag_val(val) (((unsigned char *) (val)) [-1])
+ /* Also an l-value. */
+#define Tag_hp(hp) (((unsigned char *) (hp)) [sizeof(value)-1])
+ /* Also an l-value. */
+#else
+#define Tag_val(val) (((unsigned char *) (val)) [-sizeof(value)])
+ /* Also an l-value. */
+#define Tag_hp(hp) (((unsigned char *) (hp)) [0])
+ /* Also an l-value. */
+#endif
+
+/* The lowest tag for blocks containing no value. */
+#define No_scan_tag 251
+
+
+/* 1- If tag < No_scan_tag : a tuple of fields. */
+
+/* Pointer to the first field. */
+#define Op_val(x) ((value *) (x))
+/* Fields are numbered from 0. */
+#define Field(x, i) (((value *)(x)) [i]) /* Also an l-value. */
+
+typedef int32_t opcode_t;
+typedef opcode_t * code_t;
+
+/* NOTE: [Forward_tag] and [Infix_tag] must be just under
+ [No_scan_tag], with [Infix_tag] the lower one.
+ See [caml_oldify_one] in minor_gc.c for more details.
+
+ NOTE: Update stdlib/obj.ml whenever you change the tags.
+ */
+
+/* Forward_tag: forwarding pointer that the GC may silently shortcut.
+ See stdlib/lazy.ml. */
+#define Forward_tag 250
+#define Forward_val(v) Field(v, 0)
+
+/* If tag == Infix_tag : an infix header inside a closure */
+/* Infix_tag must be odd so that the infix header is scanned as an integer */
+/* Infix_tag must be 1 modulo 4 and infix headers can only occur in blocks
+ with tag Closure_tag (see compact.c). */
+
+#define Infix_tag 249
+#define Infix_offset_hd(hd) (Bosize_hd(hd))
+#define Infix_offset_val(v) Infix_offset_hd(Hd_val(v))
+
+/* Another special case: objects */
+#define Object_tag 248
+#define Class_val(val) Field((val), 0)
+#define Oid_val(val) Long_val(Field((val), 1))
+CAMLextern value caml_get_public_method (value obj, value tag);
+/* Called as:
+ caml_callback(caml_get_public_method(obj, caml_hash_variant(name)), obj) */
+/* caml_get_public_method returns 0 if tag not in the table.
+ Note however that tags being hashed, same tag does not necessarily mean
+ same method name. */
+
+/* Special case of tuples of fields: closures */
+#define Closure_tag 247
+#define Code_val(val) (((code_t *) (val)) [0]) /* Also an l-value. */
+
+/* This tag is used (with Forward_tag) to implement lazy values.
+ See major_gc.c and stdlib/lazy.ml. */
+#define Lazy_tag 246
+
+/* Another special case: variants */
+CAMLextern value caml_hash_variant(char const * tag);
+
+/* 2- If tag >= No_scan_tag : a sequence of bytes. */
+
+/* Pointer to the first byte */
+#define Bp_val(v) ((char *) (v))
+#define Val_bp(p) ((value) (p))
+/* Bytes are numbered from 0. */
+#define Byte(x, i) (((char *) (x)) [i]) /* Also an l-value. */
+#define Byte_u(x, i) (((unsigned char *) (x)) [i]) /* Also an l-value. */
+
+/* Abstract things. Their contents is not traced by the GC; therefore they
+ must not contain any [value].
+*/
+#define Abstract_tag 251
+
+/* Strings. */
+#define String_tag 252
+#define String_val(x) ((char *) Bp_val(x))
+CAMLextern mlsize_t caml_string_length (value); /* size in bytes */
+
+/* Floating-point numbers. */
+#define Double_tag 253
+#define Double_wosize ((sizeof(double) / sizeof(value)))
+#ifndef ARCH_ALIGN_DOUBLE
+#define Double_val(v) (* (double *)(v))
+#define Store_double_val(v,d) (* (double *)(v) = (d))
+#else
+CAMLextern double caml_Double_val (value);
+CAMLextern void caml_Store_double_val (value,double);
+#define Double_val(v) caml_Double_val(v)
+#define Store_double_val(v,d) caml_Store_double_val(v,d)
+#endif
+
+/* Arrays of floating-point numbers. */
+#define Double_array_tag 254
+#define Double_field(v,i) Double_val((value)((double *)(v) + (i)))
+#define Store_double_field(v,i,d) do{ \
+ mlsize_t caml__temp_i = (i); \
+ double caml__temp_d = (d); \
+ Store_double_val((value)((double *) (v) + caml__temp_i), caml__temp_d); \
+}while(0)
+CAMLextern mlsize_t caml_array_length (value); /* size in items */
+CAMLextern int caml_is_double_array (value); /* 0 is false, 1 is true */
+
+
+/* Custom blocks. They contain a pointer to a "method suite"
+ of functions (for finalization, comparison, hashing, etc)
+ followed by raw data. The contents of custom blocks is not traced by
+ the GC; therefore, they must not contain any [value].
+ See [custom.h] for operations on method suites. */
+#define Custom_tag 255
+#define Data_custom_val(v) ((void *) &Field((v), 1))
+struct custom_operations; /* defined in [custom.h] */
+
+/* Int32.t, Int64.t and Nativeint.t are represented as custom blocks. */
+
+#define Int32_val(v) (*((int32_t *) Data_custom_val(v)))
+#define Nativeint_val(v) (*((intnat *) Data_custom_val(v)))
+#ifndef ARCH_ALIGN_INT64
+#define Int64_val(v) (*((int64_t *) Data_custom_val(v)))
+#else
+CAMLextern int64_t caml_Int64_val(value v);
+#define Int64_val(v) caml_Int64_val(v)
+#endif
+
+/* 3- Atoms are 0-tuples. They are statically allocated once and for all. */
+
+CAMLextern header_t caml_atom_table[];
+#define Atom(tag) (Val_hp (&(caml_atom_table [(tag)])))
+
+/* Booleans are integers 0 or 1 */
+
+#define Val_bool(x) Val_int((x) != 0)
+#define Bool_val(x) Int_val(x)
+#define Val_false Val_int(0)
+#define Val_true Val_int(1)
+#define Val_not(x) (Val_false + Val_true - (x))
+
+/* The unit value is 0 (tagged) */
+
+#define Val_unit Val_int(0)
+
+/* List constructors */
+#define Val_emptylist Val_int(0)
+#define Tag_cons 0
+
+/* The table of global identifiers */
+
+extern value caml_global_data;
+
+CAMLextern value caml_set_oo_id(value obj);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_MLVALUES_H */
diff --git a/byterun/caml/osdeps.h b/byterun/caml/osdeps.h
new file mode 100644
index 0000000000..8204205f74
--- /dev/null
+++ b/byterun/caml/osdeps.h
@@ -0,0 +1,68 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Operating system - specific stuff */
+
+#ifndef CAML_OSDEPS_H
+#define CAML_OSDEPS_H
+
+#include "misc.h"
+
+/* Decompose the given path into a list of directories, and add them
+ to the given table. Return the block to be freed later. */
+extern char * caml_decompose_path(struct ext_table * tbl, char * path);
+
+/* Search the given file in the given list of directories.
+ If not found, return a copy of [name]. Result is allocated with
+ [caml_stat_alloc]. */
+extern char * caml_search_in_path(struct ext_table * path, char * name);
+
+/* Same, but search an executable name in the system path for executables. */
+CAMLextern char * caml_search_exe_in_path(char * name);
+
+/* Same, but search a shared library in the given path. */
+extern char * caml_search_dll_in_path(struct ext_table * path, char * name);
+
+/* Open a shared library and return a handle on it.
+ If [for_execution] is true, perform full symbol resolution and
+ execute initialization code so that functions from the shared library
+ can be called. If [for_execution] is false, functions from this
+ shared library will not be called, but just checked for presence,
+ so symbol resolution can be skipped.
+ If [global] is true, symbols from the shared library can be used
+ to resolve for other libraries to be opened later on.
+ Return [NULL] on error. */
+extern void * caml_dlopen(char * libname, int for_execution, int global);
+
+/* Close a shared library handle */
+extern void caml_dlclose(void * handle);
+
+/* Look up the given symbol in the given shared library.
+ Return [NULL] if not found, or symbol value if found. */
+extern void * caml_dlsym(void * handle, char * name);
+
+extern void * caml_globalsym(char * name);
+
+/* Return an error message describing the most recent dynlink failure. */
+extern char * caml_dlerror(void);
+
+/* Add to [contents] the (short) names of the files contained in
+ the directory named [dirname]. No entries are added for [.] and [..].
+ Return 0 on success, -1 on error; set errno in the case of error. */
+extern int caml_read_directory(char * dirname, struct ext_table * contents);
+
+/* Recover executable name if possible (/proc/sef/exe under Linux,
+ GetModuleFileName under Windows). */
+extern int caml_executable_name(char * name, int name_len);
+
+#endif /* CAML_OSDEPS_H */
diff --git a/byterun/caml/prims.h b/byterun/caml/prims.h
new file mode 100644
index 0000000000..7a99678104
--- /dev/null
+++ b/byterun/caml/prims.h
@@ -0,0 +1,34 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Interface with C primitives. */
+
+#ifndef CAML_PRIMS_H
+#define CAML_PRIMS_H
+
+typedef value (*c_primitive)();
+
+extern c_primitive caml_builtin_cprim[];
+extern char * caml_names_of_builtin_cprim[];
+
+extern struct ext_table caml_prim_table;
+#ifdef DEBUG
+extern struct ext_table caml_prim_name_table;
+#endif
+
+#define Primitive(n) ((c_primitive)(caml_prim_table.contents[n]))
+
+extern char * caml_section_table;
+extern asize_t caml_section_table_size;
+
+#endif /* CAML_PRIMS_H */
diff --git a/byterun/caml/printexc.h b/byterun/caml/printexc.h
new file mode 100644
index 0000000000..ab9da3ce28
--- /dev/null
+++ b/byterun/caml/printexc.h
@@ -0,0 +1,33 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_PRINTEXC_H
+#define CAML_PRINTEXC_H
+
+
+#include "misc.h"
+#include "mlvalues.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+CAMLextern char * caml_format_exception (value);
+CAMLnoreturn_start void caml_fatal_uncaught_exception (value) CAMLnoreturn_end;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_PRINTEXC_H */
diff --git a/byterun/caml/reverse.h b/byterun/caml/reverse.h
new file mode 100644
index 0000000000..09d34a51f6
--- /dev/null
+++ b/byterun/caml/reverse.h
@@ -0,0 +1,86 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Swap byte-order in 16, 32, and 64-bit integers or floats */
+
+#ifndef CAML_REVERSE_H
+#define CAML_REVERSE_H
+
+#define Reverse_16(dst,src) { \
+ char * _p, * _q; \
+ char _a; \
+ _p = (char *) (src); \
+ _q = (char *) (dst); \
+ _a = _p[0]; \
+ _q[0] = _p[1]; \
+ _q[1] = _a; \
+}
+
+#define Reverse_32(dst,src) { \
+ char * _p, * _q; \
+ char _a, _b; \
+ _p = (char *) (src); \
+ _q = (char *) (dst); \
+ _a = _p[0]; \
+ _b = _p[1]; \
+ _q[0] = _p[3]; \
+ _q[1] = _p[2]; \
+ _q[3] = _a; \
+ _q[2] = _b; \
+}
+
+#define Reverse_64(dst,src) { \
+ char * _p, * _q; \
+ char _a, _b; \
+ _p = (char *) (src); \
+ _q = (char *) (dst); \
+ _a = _p[0]; \
+ _b = _p[1]; \
+ _q[0] = _p[7]; \
+ _q[1] = _p[6]; \
+ _q[7] = _a; \
+ _q[6] = _b; \
+ _a = _p[2]; \
+ _b = _p[3]; \
+ _q[2] = _p[5]; \
+ _q[3] = _p[4]; \
+ _q[5] = _a; \
+ _q[4] = _b; \
+}
+
+#define Perm_index(perm,i) ((perm >> (i * 4)) & 0xF)
+
+#define Permute_64(dst,perm_dst,src,perm_src) { \
+ char * _p; \
+ char _a, _b, _c, _d, _e, _f, _g, _h; \
+ _p = (char *) (src); \
+ _a = _p[Perm_index(perm_src, 0)]; \
+ _b = _p[Perm_index(perm_src, 1)]; \
+ _c = _p[Perm_index(perm_src, 2)]; \
+ _d = _p[Perm_index(perm_src, 3)]; \
+ _e = _p[Perm_index(perm_src, 4)]; \
+ _f = _p[Perm_index(perm_src, 5)]; \
+ _g = _p[Perm_index(perm_src, 6)]; \
+ _h = _p[Perm_index(perm_src, 7)]; \
+ _p = (char *) (dst); \
+ _p[Perm_index(perm_dst, 0)] = _a; \
+ _p[Perm_index(perm_dst, 1)] = _b; \
+ _p[Perm_index(perm_dst, 2)] = _c; \
+ _p[Perm_index(perm_dst, 3)] = _d; \
+ _p[Perm_index(perm_dst, 4)] = _e; \
+ _p[Perm_index(perm_dst, 5)] = _f; \
+ _p[Perm_index(perm_dst, 6)] = _g; \
+ _p[Perm_index(perm_dst, 7)] = _h; \
+}
+
+#endif /* CAML_REVERSE_H */
diff --git a/byterun/caml/roots.h b/byterun/caml/roots.h
new file mode 100644
index 0000000000..ca6a5d2623
--- /dev/null
+++ b/byterun/caml/roots.h
@@ -0,0 +1,36 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_ROOTS_H
+#define CAML_ROOTS_H
+
+#include "misc.h"
+#include "memory.h"
+
+typedef void (*scanning_action) (value, value *);
+
+void caml_oldify_local_roots (void);
+void caml_darken_all_roots (void);
+void caml_do_roots (scanning_action);
+#ifndef NATIVE_CODE
+CAMLextern void caml_do_local_roots (scanning_action, value *, value *,
+ struct caml__roots_block *);
+#else
+CAMLextern void caml_do_local_roots(scanning_action f, char * bottom_of_stack,
+ uintnat last_retaddr, value * gc_regs,
+ struct caml__roots_block * local_roots);
+#endif
+
+CAMLextern void (*caml_scan_roots_hook) (scanning_action);
+
+#endif /* CAML_ROOTS_H */
diff --git a/byterun/caml/signals.h b/byterun/caml/signals.h
new file mode 100644
index 0000000000..584516660c
--- /dev/null
+++ b/byterun/caml/signals.h
@@ -0,0 +1,57 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_SIGNALS_H
+#define CAML_SIGNALS_H
+
+#ifndef CAML_NAME_SPACE
+#include "compatibility.h"
+#endif
+#include "misc.h"
+#include "mlvalues.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* <private> */
+CAMLextern intnat volatile caml_signals_are_pending;
+CAMLextern intnat volatile caml_pending_signals[];
+CAMLextern int volatile caml_something_to_do;
+extern int volatile caml_force_major_slice;
+/* </private> */
+
+CAMLextern void caml_enter_blocking_section (void);
+CAMLextern void caml_leave_blocking_section (void);
+
+/* <private> */
+void caml_urge_major_slice (void);
+CAMLextern int caml_convert_signal_number (int);
+CAMLextern int caml_rev_convert_signal_number (int);
+void caml_execute_signal(int signal_number, int in_signal_handler);
+void caml_record_signal(int signal_number);
+void caml_process_pending_signals(void);
+void caml_process_event(void);
+int caml_set_signal_action(int signo, int action);
+
+CAMLextern void (*caml_enter_blocking_section_hook)(void);
+CAMLextern void (*caml_leave_blocking_section_hook)(void);
+CAMLextern int (*caml_try_leave_blocking_section_hook)(void);
+CAMLextern void (* volatile caml_async_action_hook)(void);
+/* </private> */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_SIGNALS_H */
diff --git a/byterun/caml/signals_machdep.h b/byterun/caml/signals_machdep.h
new file mode 100644
index 0000000000..505999bb0a
--- /dev/null
+++ b/byterun/caml/signals_machdep.h
@@ -0,0 +1,68 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Processor-specific operation: atomic "read and clear" */
+
+#ifndef CAML_SIGNALS_MACHDEP_H
+#define CAML_SIGNALS_MACHDEP_H
+
+#if defined(__GNUC__) && defined(__ATOMIC_SEQ_CST) \
+ && defined(__GCC_ATOMIC_LONG_LOCK_FREE)
+
+/* Use the "atomic" builtins of GCC and Clang */
+#define Read_and_clear(dst,src) \
+ ((dst) = __atomic_exchange_n(&(src), 0, __ATOMIC_SEQ_CST))
+
+#elif defined(__GNUC__) && (defined(__i386__) || (defined(__x86_64__) \
+ && defined(__ILP32__)))
+
+#define Read_and_clear(dst,src) \
+ asm("xorl %0, %0; xchgl %0, %1" \
+ : "=r" (dst), "=m" (src) \
+ : "m" (src))
+
+#elif defined(__GNUC__) && defined(__x86_64__)
+
+#define Read_and_clear(dst,src) \
+ asm("xorq %0, %0; xchgq %0, %1" \
+ : "=r" (dst), "=m" (src) \
+ : "m" (src))
+
+#elif defined(__GNUC__) && defined(__ppc__)
+
+#define Read_and_clear(dst,src) \
+ asm("0: lwarx %0, 0, %1\n\t" \
+ "stwcx. %2, 0, %1\n\t" \
+ "bne- 0b" \
+ : "=&r" (dst) \
+ : "r" (&(src)), "r" (0) \
+ : "cr0", "memory")
+
+#elif defined(__GNUC__) && defined(__ppc64__)
+
+#define Read_and_clear(dst,src) \
+ asm("0: ldarx %0, 0, %1\n\t" \
+ "stdcx. %2, 0, %1\n\t" \
+ "bne- 0b" \
+ : "=&r" (dst) \
+ : "r" (&(src)), "r" (0) \
+ : "cr0", "memory")
+
+#else
+
+/* Default, non-atomic implementation */
+#define Read_and_clear(dst,src) ((dst) = (src), (src) = 0)
+
+#endif
+
+#endif /* CAML_SIGNALS_MACHDEP_H */
diff --git a/byterun/caml/stacks.h b/byterun/caml/stacks.h
new file mode 100644
index 0000000000..c596f2550e
--- /dev/null
+++ b/byterun/caml/stacks.h
@@ -0,0 +1,41 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* structure of the stacks */
+
+#ifndef CAML_STACKS_H
+#define CAML_STACKS_H
+
+
+#include "misc.h"
+#include "mlvalues.h"
+#include "memory.h"
+
+CAMLextern value * caml_stack_low;
+CAMLextern value * caml_stack_high;
+CAMLextern value * caml_stack_threshold;
+CAMLextern value * caml_extern_sp;
+CAMLextern value * caml_trapsp;
+CAMLextern value * caml_trap_barrier;
+
+#define Trap_pc(tp) (((code_t *)(tp))[0])
+#define Trap_link(tp) (((value **)(tp))[1])
+
+void caml_init_stack (uintnat init_max_size);
+void caml_realloc_stack (asize_t required_size);
+void caml_change_max_stack_size (uintnat new_max_size);
+uintnat caml_stack_usage (void);
+
+CAMLextern uintnat (*caml_stack_usage_hook)(void);
+
+#endif /* CAML_STACKS_H */
diff --git a/byterun/caml/startup.h b/byterun/caml/startup.h
new file mode 100644
index 0000000000..0c50c05eb7
--- /dev/null
+++ b/byterun/caml/startup.h
@@ -0,0 +1,39 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_STARTUP_H
+#define CAML_STARTUP_H
+
+#include "mlvalues.h"
+#include "exec.h"
+
+CAMLextern void caml_main(char **argv);
+
+CAMLextern void caml_startup_code(
+ code_t code, asize_t code_size,
+ char *data, asize_t data_size,
+ char *section_table, asize_t section_table_size,
+ char **argv);
+
+enum { FILE_NOT_FOUND = -1, BAD_BYTECODE = -2 };
+
+extern int caml_attempt_open(char **name, struct exec_trailer *trail,
+ int do_open_script);
+extern void caml_read_section_descriptors(int fd, struct exec_trailer *trail);
+extern int32_t caml_seek_optional_section(int fd, struct exec_trailer *trail,
+ char *name);
+extern int32_t caml_seek_section(int fd, struct exec_trailer *trail,
+ char *name);
+
+
+#endif /* CAML_STARTUP_H */
diff --git a/byterun/caml/startup_aux.h b/byterun/caml/startup_aux.h
new file mode 100644
index 0000000000..f1de0e29af
--- /dev/null
+++ b/byterun/caml/startup_aux.h
@@ -0,0 +1,26 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, Jane Street Group, LLC */
+/* */
+/* Copyright 2015 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "config.h"
+
+extern void caml_init_atom_table (void);
+
+extern uintnat caml_init_percent_free;
+extern uintnat caml_init_max_percent_free;
+extern uintnat caml_init_minor_heap_wsz;
+extern uintnat caml_init_heap_chunk_sz;
+extern uintnat caml_init_heap_wsz;
+extern uintnat caml_init_max_stack_wsz;
+extern uintnat caml_trace_level;
+
+extern void caml_parse_ocamlrunparam (void);
diff --git a/byterun/caml/sys.h b/byterun/caml/sys.h
new file mode 100644
index 0000000000..5eb18fc0e5
--- /dev/null
+++ b/byterun/caml/sys.h
@@ -0,0 +1,28 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_SYS_H
+#define CAML_SYS_H
+
+#include "misc.h"
+
+#define NO_ARG Val_int(0)
+
+CAMLextern void caml_sys_error (value);
+CAMLextern void caml_sys_io_error (value);
+extern void caml_sys_init (char * exe_name, char ** argv);
+CAMLextern value caml_sys_exit (value);
+
+extern char * caml_exe_name;
+
+#endif /* CAML_SYS_H */
diff --git a/byterun/caml/ui.h b/byterun/caml/ui.h
new file mode 100644
index 0000000000..2958465038
--- /dev/null
+++ b/byterun/caml/ui.h
@@ -0,0 +1,26 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Function declarations for non-Unix user interfaces */
+
+#ifndef CAML_UI_H
+#define CAML_UI_H
+
+#include "config.h"
+
+void ui_exit (int return_code);
+int ui_read (int file_desc, char *buf, unsigned int length);
+int ui_write (int file_desc, char *buf, unsigned int length);
+void ui_print_stderr (char *format, void *arg);
+
+#endif /* CAML_UI_H */
diff --git a/byterun/caml/weak.h b/byterun/caml/weak.h
new file mode 100644
index 0000000000..0cf4b8b2b4
--- /dev/null
+++ b/byterun/caml/weak.h
@@ -0,0 +1,24 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1997 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Operations on weak arrays */
+
+#ifndef CAML_WEAK_H
+#define CAML_WEAK_H
+
+#include "mlvalues.h"
+
+extern value caml_weak_list_head;
+extern value caml_weak_none;
+
+#endif /* CAML_WEAK_H */
diff --git a/byterun/compact.c b/byterun/compact.c
new file mode 100644
index 0000000000..77b9479f53
--- /dev/null
+++ b/byterun/compact.c
@@ -0,0 +1,506 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+
+#include "caml/address_class.h"
+#include "caml/config.h"
+#include "caml/finalise.h"
+#include "caml/freelist.h"
+#include "caml/gc.h"
+#include "caml/gc_ctrl.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+#include "caml/roots.h"
+#include "caml/weak.h"
+
+extern uintnat caml_percent_free; /* major_gc.c */
+extern void caml_shrink_heap (char *); /* memory.c */
+
+/* Encoded headers: the color is stored in the 2 least significant bits.
+ (For pointer inversion, we need to distinguish headers from pointers.)
+ s is a Wosize, t is a tag, and c is a color (a two-bit number)
+
+ For the purpose of compaction, "colors" are:
+ 0: pointers (direct or inverted)
+ 1: integer or (unencoded) infix header
+ 2: inverted pointer for infix header
+ 3: integer or encoded (noninfix) header
+
+ XXX Should be fixed:
+ XXX The above assumes that all roots are aligned on a 4-byte boundary,
+ XXX which is not always guaranteed by C.
+ XXX (see [caml_register_global_roots])
+ XXX Should be able to fix it to only assume 2-byte alignment.
+*/
+#define Make_ehd(s,t,c) (((s) << 10) | (t) << 2 | (c))
+#define Whsize_ehd(h) Whsize_hd (h)
+#define Wosize_ehd(h) Wosize_hd (h)
+#define Tag_ehd(h) (((h) >> 2) & 0xFF)
+#define Ecolor(w) ((w) & 3)
+
+typedef uintnat word;
+
+static void invert_pointer_at (word *p)
+{
+ word q = *p;
+ Assert (Ecolor ((intnat) p) == 0);
+
+ /* Use Ecolor (q) == 0 instead of Is_block (q) because q could be an
+ inverted pointer for an infix header (with Ecolor == 2). */
+ if (Ecolor (q) == 0 && Is_in_heap (q)){
+ switch (Ecolor (Hd_val (q))){
+ case 0:
+ case 3: /* Pointer or header: insert in inverted list. */
+ *p = Hd_val (q);
+ Hd_val (q) = (header_t) p;
+ break;
+ case 1: /* Infix header: make inverted infix list. */
+ /* Double inversion: the last of the inverted infix list points to
+ the next infix header in this block. The last of the last list
+ contains the original block header. */
+ {
+ /* This block as a value. */
+ value val = (value) q - Infix_offset_val (q);
+ /* Get the block header. */
+ word *hp = (word *) Hp_val (val);
+
+ while (Ecolor (*hp) == 0) hp = (word *) *hp;
+ Assert (Ecolor (*hp) == 3);
+ if (Tag_ehd (*hp) == Closure_tag){
+ /* This is the first infix found in this block. */
+ /* Save original header. */
+ *p = *hp;
+ /* Link inverted infix list. */
+ Hd_val (q) = (header_t) ((word) p | 2);
+ /* Change block header's tag to Infix_tag, and change its size
+ to point to the infix list. */
+ *hp = Make_ehd (Wosize_bhsize (q - val), Infix_tag, 3);
+ }else{ Assert (Tag_ehd (*hp) == Infix_tag);
+ /* Point the last of this infix list to the current first infix
+ list of the block. */
+ *p = (word) &Field (val, Wosize_ehd (*hp)) | 1;
+ /* Point the head of this infix list to the above. */
+ Hd_val (q) = (header_t) ((word) p | 2);
+ /* Change block header's size to point to this infix list. */
+ *hp = Make_ehd (Wosize_bhsize (q - val), Infix_tag, 3);
+ }
+ }
+ break;
+ case 2: /* Inverted infix list: insert. */
+ *p = Hd_val (q);
+ Hd_val (q) = (header_t) ((word) p | 2);
+ break;
+ }
+ }
+}
+
+static void invert_root (value v, value *p)
+{
+ invert_pointer_at ((word *) p);
+}
+
+static char *compact_fl;
+
+static void init_compact_allocate (void)
+{
+ char *ch = caml_heap_start;
+ while (ch != NULL){
+ Chunk_alloc (ch) = 0;
+ ch = Chunk_next (ch);
+ }
+ compact_fl = caml_heap_start;
+}
+
+/* [size] is a number of bytes and includes the header size */
+static char *compact_allocate (mlsize_t size)
+{
+ char *chunk, *adr;
+
+ while (Chunk_size (compact_fl) - Chunk_alloc (compact_fl) <= Bhsize_wosize (3)
+ && Chunk_size (Chunk_next (compact_fl))
+ - Chunk_alloc (Chunk_next (compact_fl))
+ <= Bhsize_wosize (3)){
+ compact_fl = Chunk_next (compact_fl);
+ }
+ chunk = compact_fl;
+ while (Chunk_size (chunk) - Chunk_alloc (chunk) < size){
+ chunk = Chunk_next (chunk); Assert (chunk != NULL);
+ }
+ adr = chunk + Chunk_alloc (chunk);
+ Chunk_alloc (chunk) += size;
+ return adr;
+}
+
+static void do_compaction (void)
+{
+ char *ch, *chend;
+ Assert (caml_gc_phase == Phase_idle);
+ caml_gc_message (0x10, "Compacting heap...\n", 0);
+
+#ifdef DEBUG
+ caml_heap_check ();
+#endif
+
+ /* First pass: encode all noninfix headers. */
+ {
+ ch = caml_heap_start;
+ while (ch != NULL){
+ header_t *p = (header_t *) ch;
+
+ chend = ch + Chunk_size (ch);
+ while ((char *) p < chend){
+ header_t hd = Hd_hp (p);
+ mlsize_t sz = Wosize_hd (hd);
+
+ if (Is_blue_hd (hd)){
+ /* Free object. Give it a string tag. */
+ Hd_hp (p) = Make_ehd (sz, String_tag, 3);
+ }else{ Assert (Is_white_hd (hd));
+ /* Live object. Keep its tag. */
+ Hd_hp (p) = Make_ehd (sz, Tag_hd (hd), 3);
+ }
+ p += Whsize_wosize (sz);
+ }
+ ch = Chunk_next (ch);
+ }
+ }
+
+
+ /* Second pass: invert pointers.
+ Link infix headers in each block in an inverted list of inverted lists.
+ Don't forget roots and weak pointers. */
+ {
+ /* Invert roots first because the threads library needs some heap
+ data structures to find its roots. Fortunately, it doesn't need
+ the headers (see above). */
+ caml_do_roots (invert_root);
+ caml_final_do_weak_roots (invert_root);
+
+ ch = caml_heap_start;
+ while (ch != NULL){
+ word *p = (word *) ch;
+ chend = ch + Chunk_size (ch);
+
+ while ((char *) p < chend){
+ word q = *p;
+ size_t sz, i;
+ tag_t t;
+ word *infixes;
+
+ while (Ecolor (q) == 0) q = * (word *) q;
+ sz = Whsize_ehd (q);
+ t = Tag_ehd (q);
+
+ if (t == Infix_tag){
+ /* Get the original header of this block. */
+ infixes = p + sz;
+ q = *infixes;
+ while (Ecolor (q) != 3) q = * (word *) (q & ~(uintnat)3);
+ sz = Whsize_ehd (q);
+ t = Tag_ehd (q);
+ }
+
+ if (t < No_scan_tag){
+ for (i = 1; i < sz; i++) invert_pointer_at (&(p[i]));
+ }
+ p += sz;
+ }
+ ch = Chunk_next (ch);
+ }
+ /* Invert weak pointers. */
+ {
+ value *pp = &caml_weak_list_head;
+ value p;
+ word q;
+ size_t sz, i;
+
+ while (1){
+ p = *pp;
+ if (p == (value) NULL) break;
+ q = Hd_val (p);
+ while (Ecolor (q) == 0) q = * (word *) q;
+ sz = Wosize_ehd (q);
+ for (i = 1; i < sz; i++){
+ if (Field (p,i) != caml_weak_none){
+ invert_pointer_at ((word *) &(Field (p,i)));
+ }
+ }
+ invert_pointer_at ((word *) pp);
+ pp = &Field (p, 0);
+ }
+ }
+ }
+
+
+ /* Third pass: reallocate virtually; revert pointers; decode headers.
+ Rebuild infix headers. */
+ {
+ init_compact_allocate ();
+ ch = caml_heap_start;
+ while (ch != NULL){
+ word *p = (word *) ch;
+
+ chend = ch + Chunk_size (ch);
+ while ((char *) p < chend){
+ word q = *p;
+
+ if (Ecolor (q) == 0 || Tag_ehd (q) == Infix_tag){
+ /* There were (normal or infix) pointers to this block. */
+ size_t sz;
+ tag_t t;
+ char *newadr;
+ word *infixes = NULL;
+
+ while (Ecolor (q) == 0) q = * (word *) q;
+ sz = Whsize_ehd (q);
+ t = Tag_ehd (q);
+
+ if (t == Infix_tag){
+ /* Get the original header of this block. */
+ infixes = p + sz;
+ q = *infixes; Assert (Ecolor (q) == 2);
+ while (Ecolor (q) != 3) q = * (word *) (q & ~(uintnat)3);
+ sz = Whsize_ehd (q);
+ t = Tag_ehd (q);
+ }
+
+ newadr = compact_allocate (Bsize_wsize (sz));
+ q = *p;
+ while (Ecolor (q) == 0){
+ word next = * (word *) q;
+ * (word *) q = (word) Val_hp (newadr);
+ q = next;
+ }
+ *p = Make_header (Wosize_whsize (sz), t, Caml_white);
+
+ if (infixes != NULL){
+ /* Rebuild the infix headers and revert the infix pointers. */
+ while (Ecolor ((word) infixes) != 3){
+ infixes = (word *) ((word) infixes & ~(uintnat) 3);
+ q = *infixes;
+ while (Ecolor (q) == 2){
+ word next;
+ q = (word) q & ~(uintnat) 3;
+ next = * (word *) q;
+ * (word *) q = (word) Val_hp ((word *) newadr + (infixes - p));
+ q = next;
+ } Assert (Ecolor (q) == 1 || Ecolor (q) == 3);
+ *infixes = Make_header (infixes - p, Infix_tag, Caml_white);
+ infixes = (word *) q;
+ }
+ }
+ p += sz;
+ }else{ Assert (Ecolor (q) == 3);
+ /* This is guaranteed only if caml_compact_heap was called after a
+ nonincremental major GC: Assert (Tag_ehd (q) == String_tag);
+ */
+ /* No pointers to the header and no infix header:
+ the object was free. */
+ *p = Make_header (Wosize_ehd (q), Tag_ehd (q), Caml_blue);
+ p += Whsize_ehd (q);
+ }
+ }
+ ch = Chunk_next (ch);
+ }
+ }
+
+
+ /* Fourth pass: reallocate and move objects.
+ Use the exact same allocation algorithm as pass 3. */
+ {
+ init_compact_allocate ();
+ ch = caml_heap_start;
+ while (ch != NULL){
+ word *p = (word *) ch;
+
+ chend = ch + Chunk_size (ch);
+ while ((char *) p < chend){
+ word q = *p;
+ if (Color_hd (q) == Caml_white){
+ size_t sz = Bhsize_hd (q);
+ char *newadr = compact_allocate (sz);
+ memmove (newadr, p, sz);
+ p += Wsize_bsize (sz);
+ }else{
+ Assert (Color_hd (q) == Caml_blue);
+ p += Whsize_hd (q);
+ }
+ }
+ ch = Chunk_next (ch);
+ }
+ }
+
+ /* Shrink the heap if needed. */
+ {
+ /* Find the amount of live data and the unshrinkable free space. */
+ asize_t live = 0;
+ asize_t free = 0;
+ asize_t wanted;
+
+ ch = caml_heap_start;
+ while (ch != NULL){
+ if (Chunk_alloc (ch) != 0){
+ live += Wsize_bsize (Chunk_alloc (ch));
+ free += Wsize_bsize (Chunk_size (ch) - Chunk_alloc (ch));
+ }
+ ch = Chunk_next (ch);
+ }
+
+ /* Add up the empty chunks until there are enough, then remove the
+ other empty chunks. */
+ wanted = caml_percent_free * (live / 100 + 1);
+ ch = caml_heap_start;
+ while (ch != NULL){
+ char *next_chunk = Chunk_next (ch); /* Chunk_next (ch) will be erased */
+
+ if (Chunk_alloc (ch) == 0){
+ if (free < wanted){
+ free += Wsize_bsize (Chunk_size (ch));
+ }else{
+ caml_shrink_heap (ch);
+ }
+ }
+ ch = next_chunk;
+ }
+ }
+
+ /* Rebuild the free list. */
+ {
+ ch = caml_heap_start;
+ caml_fl_reset ();
+ while (ch != NULL){
+ if (Chunk_size (ch) > Chunk_alloc (ch)){
+ caml_make_free_blocks ((value *) (ch + Chunk_alloc (ch)),
+ Wsize_bsize (Chunk_size(ch)-Chunk_alloc(ch)), 1,
+ Caml_white);
+ }
+ ch = Chunk_next (ch);
+ }
+ }
+ ++ caml_stat_compactions;
+ caml_gc_message (0x10, "done.\n", 0);
+}
+
+uintnat caml_percent_max; /* used in gc_ctrl.c and memory.c */
+
+void caml_compact_heap (void)
+{
+ uintnat target_wsz, live;
+
+ do_compaction ();
+ /* Compaction may fail to shrink the heap to a reasonable size
+ because it deals in complete chunks: if a very large chunk
+ is at the beginning of the heap, everything gets moved to
+ it and it is not freed.
+
+ In that case, we allocate a new chunk of the desired heap
+ size, chain it at the beginning of the heap (thus pretending
+ its address is smaller), and launch a second compaction.
+ This will move all data to this new chunk and free the
+ very large chunk.
+
+ See PR#5389
+ */
+ /* We compute:
+ freewords = caml_fl_cur_wsz (exact)
+ heapwords = Wsize_bsize (caml_heap_size) (exact)
+ live = heapwords - freewords
+ wanted = caml_percent_free * (live / 100 + 1) (same as in do_compaction)
+ target_wsz = live + wanted
+ We add one page to make sure a small difference in counting sizes
+ won't make [do_compaction] keep the second block (and break all sorts
+ of invariants).
+
+ We recompact if target_wsz < heap_size / 2
+ */
+ live = caml_stat_heap_wsz - caml_fl_cur_wsz;
+ target_wsz = live + caml_percent_free * (live / 100 + 1)
+ + Wsize_bsize (Page_size);
+ target_wsz = caml_round_heap_chunk_wsz (target_wsz);
+ if (target_wsz < caml_stat_heap_wsz / 2){
+ char *chunk;
+
+ caml_gc_message (0x10, "Recompacting heap (target=%luk words)\n",
+ target_wsz / 1024);
+
+ chunk = caml_alloc_for_heap (Bsize_wsize (target_wsz));
+ if (chunk == NULL) return;
+ /* PR#5757: we need to make the new blocks blue, or they won't be
+ recognized as free by the recompaction. */
+ caml_make_free_blocks ((value *) chunk,
+ Wsize_bsize (Chunk_size (chunk)), 0, Caml_blue);
+ if (caml_page_table_add (In_heap, chunk, chunk + Chunk_size (chunk)) != 0){
+ caml_free_for_heap (chunk);
+ return;
+ }
+ Chunk_next (chunk) = caml_heap_start;
+ caml_heap_start = chunk;
+ ++ caml_stat_heap_chunks;
+ caml_stat_heap_wsz += Wsize_bsize (Chunk_size (chunk));
+ if (caml_stat_heap_wsz > caml_stat_top_heap_wsz){
+ caml_stat_top_heap_wsz = caml_stat_heap_wsz;
+ }
+ do_compaction ();
+ Assert (caml_stat_heap_chunks == 1);
+ Assert (Chunk_next (caml_heap_start) == NULL);
+ Assert (caml_stat_heap_wsz == Wsize_bsize (Chunk_size (chunk)));
+ }
+}
+
+void caml_compact_heap_maybe (void)
+{
+ /* Estimated free+garbage words in the heap:
+ FW = fl_size_at_phase_change + 3 * (caml_fl_cur_wsz
+ - caml_fl_wsz_at_phase_change)
+ FW = 3 * caml_fl_cur_wsz - 2 * caml_fl_wsz_at_phase_change
+ Estimated live words: LW = caml_stat_heap_wsz - FW
+ Estimated free percentage: FP = 100 * FW / LW
+ We compact the heap if FP > caml_percent_max
+ */
+ float fw, fp;
+ Assert (caml_gc_phase == Phase_idle);
+ if (caml_percent_max >= 1000000) return;
+ if (caml_stat_major_collections < 3) return;
+ if (caml_stat_heap_wsz <= 2 * caml_round_heap_chunk_wsz (0)) return;
+
+ fw = 3.0 * caml_fl_cur_wsz - 2.0 * caml_fl_wsz_at_phase_change;
+ if (fw < 0) fw = caml_fl_cur_wsz;
+
+ if (fw >= caml_stat_heap_wsz){
+ fp = 1000000.0;
+ }else{
+ fp = 100.0 * fw / (caml_stat_heap_wsz - fw);
+ if (fp > 1000000.0) fp = 1000000.0;
+ }
+ caml_gc_message (0x200, "FL size at phase change = %"
+ ARCH_INTNAT_PRINTF_FORMAT "u words\n",
+ (uintnat) caml_fl_wsz_at_phase_change);
+ caml_gc_message (0x200, "Estimated overhead = %"
+ ARCH_INTNAT_PRINTF_FORMAT "u%%\n",
+ (uintnat) fp);
+ if (fp >= caml_percent_max){
+ caml_gc_message (0x200, "Automatic compaction triggered.\n", 0);
+ caml_finish_major_cycle ();
+
+ /* We just did a complete GC, so we can measure the overhead exactly. */
+ fw = caml_fl_cur_wsz;
+ fp = 100.0 * fw / (caml_stat_heap_wsz - fw);
+ caml_gc_message (0x200, "Measured overhead: %"
+ ARCH_INTNAT_PRINTF_FORMAT "u%%\n",
+ (uintnat) fp);
+
+ caml_compact_heap ();
+ }
+}
diff --git a/byterun/compare.c b/byterun/compare.c
new file mode 100644
index 0000000000..d2a741b3da
--- /dev/null
+++ b/byterun/compare.c
@@ -0,0 +1,320 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <stdlib.h>
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+
+/* Structural comparison on trees. */
+
+struct compare_item { value * v1, * v2; mlsize_t count; };
+
+#define COMPARE_STACK_INIT_SIZE 256
+#define COMPARE_STACK_MAX_SIZE (1024*1024)
+
+static struct compare_item compare_stack_init[COMPARE_STACK_INIT_SIZE];
+
+static struct compare_item * compare_stack = compare_stack_init;
+static struct compare_item * compare_stack_limit = compare_stack_init
+ + COMPARE_STACK_INIT_SIZE;
+
+CAMLexport int caml_compare_unordered;
+
+/* Free the compare stack if needed */
+static void compare_free_stack(void)
+{
+ if (compare_stack != compare_stack_init) {
+ free(compare_stack);
+ /* Reinitialize the globals for next time around */
+ compare_stack = compare_stack_init;
+ compare_stack_limit = compare_stack + COMPARE_STACK_INIT_SIZE;
+ }
+}
+
+/* Same, then raise Out_of_memory */
+static void compare_stack_overflow(void)
+{
+ caml_gc_message (0x04, "Stack overflow in structural comparison\n", 0);
+ compare_free_stack();
+ caml_raise_out_of_memory();
+}
+
+/* Grow the compare stack */
+static struct compare_item * compare_resize_stack(struct compare_item * sp)
+{
+ asize_t newsize = 2 * (compare_stack_limit - compare_stack);
+ asize_t sp_offset = sp - compare_stack;
+ struct compare_item * newstack;
+
+ if (newsize >= COMPARE_STACK_MAX_SIZE) compare_stack_overflow();
+ if (compare_stack == compare_stack_init) {
+ newstack = malloc(sizeof(struct compare_item) * newsize);
+ if (newstack == NULL) compare_stack_overflow();
+ memcpy(newstack, compare_stack_init,
+ sizeof(struct compare_item) * COMPARE_STACK_INIT_SIZE);
+ } else {
+ newstack =
+ realloc(compare_stack, sizeof(struct compare_item) * newsize);
+ if (newstack == NULL) compare_stack_overflow();
+ }
+ compare_stack = newstack;
+ compare_stack_limit = newstack + newsize;
+ return newstack + sp_offset;
+}
+
+/* Structural comparison */
+
+#define LESS -1
+#define EQUAL 0
+#define GREATER 1
+#define UNORDERED ((intnat)1 << (8 * sizeof(value) - 1))
+
+/* The return value of compare_val is as follows:
+ > 0 v1 is greater than v2
+ 0 v1 is equal to v2
+ < 0 and > UNORDERED v1 is less than v2
+ UNORDERED v1 and v2 cannot be compared */
+
+static intnat compare_val(value v1, value v2, int total)
+{
+ struct compare_item * sp;
+ tag_t t1, t2;
+
+ sp = compare_stack;
+ while (1) {
+ if (v1 == v2 && total) goto next_item;
+ if (Is_long(v1)) {
+ if (v1 == v2) goto next_item;
+ if (Is_long(v2))
+ return Long_val(v1) - Long_val(v2);
+ /* Subtraction above cannot overflow and cannot result in UNORDERED */
+ if (Is_in_value_area(v2)) {
+ switch (Tag_val(v2)) {
+ case Forward_tag:
+ v2 = Forward_val(v2);
+ continue;
+ case Custom_tag: {
+ int res;
+ int (*compare)(value v1, value v2) = Custom_ops_val(v2)->compare_ext;
+ if (compare == NULL) break; /* for backward compatibility */
+ caml_compare_unordered = 0;
+ res = compare(v1, v2);
+ if (caml_compare_unordered && !total) return UNORDERED;
+ if (res != 0) return res;
+ goto next_item;
+ }
+ default: /*fallthrough*/;
+ }
+ }
+ return LESS; /* v1 long < v2 block */
+ }
+ if (Is_long(v2)) {
+ if (Is_in_value_area(v1)) {
+ switch (Tag_val(v1)) {
+ case Forward_tag:
+ v1 = Forward_val(v1);
+ continue;
+ case Custom_tag: {
+ int res;
+ int (*compare)(value v1, value v2) = Custom_ops_val(v1)->compare_ext;
+ if (compare == NULL) break; /* for backward compatibility */
+ caml_compare_unordered = 0;
+ res = compare(v1, v2);
+ if (caml_compare_unordered && !total) return UNORDERED;
+ if (res != 0) return res;
+ goto next_item;
+ }
+ default: /*fallthrough*/;
+ }
+ }
+ return GREATER; /* v1 block > v2 long */
+ }
+ /* If one of the objects is outside the heap (but is not an atom),
+ use address comparison. Since both addresses are 2-aligned,
+ shift lsb off to avoid overflow in subtraction. */
+ if (! Is_in_value_area(v1) || ! Is_in_value_area(v2)) {
+ if (v1 == v2) goto next_item;
+ return (v1 >> 1) - (v2 >> 1);
+ /* Subtraction above cannot result in UNORDERED */
+ }
+ t1 = Tag_val(v1);
+ t2 = Tag_val(v2);
+ if (t1 == Forward_tag) { v1 = Forward_val (v1); continue; }
+ if (t2 == Forward_tag) { v2 = Forward_val (v2); continue; }
+ if (t1 != t2) return (intnat)t1 - (intnat)t2;
+ switch(t1) {
+ case String_tag: {
+ mlsize_t len1, len2;
+ int res;
+ if (v1 == v2) break;
+ len1 = caml_string_length(v1);
+ len2 = caml_string_length(v2);
+ res = memcmp(String_val(v1), String_val(v2), len1 <= len2 ? len1 : len2);
+ if (res < 0) return LESS;
+ if (res > 0) return GREATER;
+ if (len1 != len2) return len1 - len2;
+ break;
+ }
+ case Double_tag: {
+ double d1 = Double_val(v1);
+ double d2 = Double_val(v2);
+ if (d1 < d2) return LESS;
+ if (d1 > d2) return GREATER;
+ if (d1 != d2) {
+ if (! total) return UNORDERED;
+ /* One or both of d1 and d2 is NaN. Order according to the
+ convention NaN = NaN and NaN < f for all other floats f. */
+ if (d1 == d1) return GREATER; /* d1 is not NaN, d2 is NaN */
+ if (d2 == d2) return LESS; /* d2 is not NaN, d1 is NaN */
+ /* d1 and d2 are both NaN, thus equal: continue comparison */
+ }
+ break;
+ }
+ case Double_array_tag: {
+ mlsize_t sz1 = Wosize_val(v1) / Double_wosize;
+ mlsize_t sz2 = Wosize_val(v2) / Double_wosize;
+ mlsize_t i;
+ if (sz1 != sz2) return sz1 - sz2;
+ for (i = 0; i < sz1; i++) {
+ double d1 = Double_field(v1, i);
+ double d2 = Double_field(v2, i);
+ if (d1 < d2) return LESS;
+ if (d1 > d2) return GREATER;
+ if (d1 != d2) {
+ if (! total) return UNORDERED;
+ /* See comment for Double_tag case */
+ if (d1 == d1) return GREATER;
+ if (d2 == d2) return LESS;
+ }
+ }
+ break;
+ }
+ case Abstract_tag:
+ compare_free_stack();
+ caml_invalid_argument("compare: abstract value");
+ case Closure_tag:
+ case Infix_tag:
+ compare_free_stack();
+ caml_invalid_argument("compare: functional value");
+ case Object_tag: {
+ intnat oid1 = Oid_val(v1);
+ intnat oid2 = Oid_val(v2);
+ if (oid1 != oid2) return oid1 - oid2;
+ break;
+ }
+ case Custom_tag: {
+ int res;
+ int (*compare)(value v1, value v2) = Custom_ops_val(v1)->compare;
+ /* Hardening against comparisons between different types */
+ if (compare != Custom_ops_val(v2)->compare) {
+ return strcmp(Custom_ops_val(v1)->identifier,
+ Custom_ops_val(v2)->identifier) < 0
+ ? LESS : GREATER;
+ }
+ if (compare == NULL) {
+ compare_free_stack();
+ caml_invalid_argument("compare: abstract value");
+ }
+ caml_compare_unordered = 0;
+ res = compare(v1, v2);
+ if (caml_compare_unordered && !total) return UNORDERED;
+ if (res != 0) return res;
+ break;
+ }
+ default: {
+ mlsize_t sz1 = Wosize_val(v1);
+ mlsize_t sz2 = Wosize_val(v2);
+ /* Compare sizes first for speed */
+ if (sz1 != sz2) return sz1 - sz2;
+ if (sz1 == 0) break;
+ /* Remember that we still have to compare fields 1 ... sz - 1 */
+ if (sz1 > 1) {
+ sp++;
+ if (sp >= compare_stack_limit) sp = compare_resize_stack(sp);
+ sp->v1 = &Field(v1, 1);
+ sp->v2 = &Field(v2, 1);
+ sp->count = sz1 - 1;
+ }
+ /* Continue comparison with first field */
+ v1 = Field(v1, 0);
+ v2 = Field(v2, 0);
+ continue;
+ }
+ }
+ next_item:
+ /* Pop one more item to compare, if any */
+ if (sp == compare_stack) return EQUAL; /* we're done */
+ v1 = *((sp->v1)++);
+ v2 = *((sp->v2)++);
+ if (--(sp->count) == 0) sp--;
+ }
+}
+
+CAMLprim value caml_compare(value v1, value v2)
+{
+ intnat res = compare_val(v1, v2, 1);
+ /* Free stack if needed */
+ if (compare_stack != compare_stack_init) compare_free_stack();
+ if (res < 0)
+ return Val_int(LESS);
+ else if (res > 0)
+ return Val_int(GREATER);
+ else
+ return Val_int(EQUAL);
+}
+
+CAMLprim value caml_equal(value v1, value v2)
+{
+ intnat res = compare_val(v1, v2, 0);
+ if (compare_stack != compare_stack_init) compare_free_stack();
+ return Val_int(res == 0);
+}
+
+CAMLprim value caml_notequal(value v1, value v2)
+{
+ intnat res = compare_val(v1, v2, 0);
+ if (compare_stack != compare_stack_init) compare_free_stack();
+ return Val_int(res != 0);
+}
+
+CAMLprim value caml_lessthan(value v1, value v2)
+{
+ intnat res = compare_val(v1, v2, 0);
+ if (compare_stack != compare_stack_init) compare_free_stack();
+ return Val_int(res < 0 && res != UNORDERED);
+}
+
+CAMLprim value caml_lessequal(value v1, value v2)
+{
+ intnat res = compare_val(v1, v2, 0);
+ if (compare_stack != compare_stack_init) compare_free_stack();
+ return Val_int(res <= 0 && res != UNORDERED);
+}
+
+CAMLprim value caml_greaterthan(value v1, value v2)
+{
+ intnat res = compare_val(v1, v2, 0);
+ if (compare_stack != compare_stack_init) compare_free_stack();
+ return Val_int(res > 0);
+}
+
+CAMLprim value caml_greaterequal(value v1, value v2)
+{
+ intnat res = compare_val(v1, v2, 0);
+ if (compare_stack != compare_stack_init) compare_free_stack();
+ return Val_int(res >= 0);
+}
diff --git a/byterun/custom.c b/byterun/custom.c
new file mode 100644
index 0000000000..ffdfd972c0
--- /dev/null
+++ b/byterun/custom.c
@@ -0,0 +1,110 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Manuel Serrano and Xavier Leroy, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+
+/* [size] is a number of bytes */
+CAMLexport value caml_alloc_custom(struct custom_operations * ops,
+ uintnat size,
+ mlsize_t mem,
+ mlsize_t max)
+{
+ mlsize_t wosize;
+ value result;
+
+ wosize = 1 + (size + sizeof(value) - 1) / sizeof(value);
+ if (wosize <= Max_young_wosize) {
+ result = caml_alloc_small(wosize, Custom_tag);
+ Custom_ops_val(result) = ops;
+ if (ops->finalize != NULL) {
+ /* Remembered that the block has a finalizer */
+ if (caml_finalize_table.ptr >= caml_finalize_table.limit){
+ CAMLassert (caml_finalize_table.ptr == caml_finalize_table.limit);
+ caml_realloc_ref_table (&caml_finalize_table);
+ }
+ *caml_finalize_table.ptr++ = (value *)result;
+ }
+ } else {
+ result = caml_alloc_shr(wosize, Custom_tag);
+ Custom_ops_val(result) = ops;
+ caml_adjust_gc_speed(mem, max);
+ result = caml_check_urgent_gc(result);
+ }
+ return result;
+}
+
+struct custom_operations_list {
+ struct custom_operations * ops;
+ struct custom_operations_list * next;
+};
+
+static struct custom_operations_list * custom_ops_table = NULL;
+
+CAMLexport void caml_register_custom_operations(struct custom_operations * ops)
+{
+ struct custom_operations_list * l =
+ caml_stat_alloc(sizeof(struct custom_operations_list));
+ Assert(ops->identifier != NULL);
+ Assert(ops->deserialize != NULL);
+ l->ops = ops;
+ l->next = custom_ops_table;
+ custom_ops_table = l;
+}
+
+struct custom_operations * caml_find_custom_operations(char * ident)
+{
+ struct custom_operations_list * l;
+ for (l = custom_ops_table; l != NULL; l = l->next)
+ if (strcmp(l->ops->identifier, ident) == 0) return l->ops;
+ return NULL;
+}
+
+static struct custom_operations_list * custom_ops_final_table = NULL;
+
+struct custom_operations * caml_final_custom_operations(final_fun fn)
+{
+ struct custom_operations_list * l;
+ struct custom_operations * ops;
+ for (l = custom_ops_final_table; l != NULL; l = l->next)
+ if (l->ops->finalize == fn) return l->ops;
+ ops = caml_stat_alloc(sizeof(struct custom_operations));
+ ops->identifier = "_final";
+ ops->finalize = fn;
+ ops->compare = custom_compare_default;
+ ops->hash = custom_hash_default;
+ ops->serialize = custom_serialize_default;
+ ops->deserialize = custom_deserialize_default;
+ ops->compare_ext = custom_compare_ext_default;
+ l = caml_stat_alloc(sizeof(struct custom_operations_list));
+ l->ops = ops;
+ l->next = custom_ops_final_table;
+ custom_ops_final_table = l;
+ return ops;
+}
+
+extern struct custom_operations caml_int32_ops,
+ caml_nativeint_ops,
+ caml_int64_ops;
+
+void caml_init_custom_operations(void)
+{
+ caml_register_custom_operations(&caml_int32_ops);
+ caml_register_custom_operations(&caml_nativeint_ops);
+ caml_register_custom_operations(&caml_int64_ops);
+}
diff --git a/byterun/debugger.c b/byterun/debugger.c
new file mode 100644
index 0000000000..41a64b1c4e
--- /dev/null
+++ b/byterun/debugger.c
@@ -0,0 +1,439 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Interface with the byte-code debugger */
+
+#ifdef _WIN32
+#include <io.h>
+#endif /* _WIN32 */
+
+#include <string.h>
+
+#include "caml/alloc.h"
+#include "caml/config.h"
+#include "caml/debugger.h"
+#include "caml/misc.h"
+
+int caml_debugger_in_use = 0;
+uintnat caml_event_count;
+int caml_debugger_fork_mode = 1; /* parent by default */
+value marshal_flags = Val_emptylist;
+
+#if !defined(HAS_SOCKETS) || defined(NATIVE_CODE)
+
+void caml_debugger_init(void)
+{
+}
+
+void caml_debugger(enum event_kind event)
+{
+}
+
+void caml_debugger_cleanup_fork(void)
+{
+}
+
+#else
+
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#include <errno.h>
+#include <sys/types.h>
+#ifndef _WIN32
+#include <sys/wait.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#else
+#define ATOM ATOM_WS
+#include <winsock.h>
+#undef ATOM
+#include <process.h>
+#endif
+
+#include "caml/fail.h"
+#include "caml/fix_code.h"
+#include "caml/instruct.h"
+#include "caml/intext.h"
+#include "caml/io.h"
+#include "caml/mlvalues.h"
+#include "caml/stacks.h"
+#include "caml/sys.h"
+
+static int sock_domain; /* Socket domain for the debugger */
+static union { /* Socket address for the debugger */
+ struct sockaddr s_gen;
+#ifndef _WIN32
+ struct sockaddr_un s_unix;
+#endif
+ struct sockaddr_in s_inet;
+} sock_addr;
+static int sock_addr_len; /* Length of sock_addr */
+
+static int dbg_socket = -1; /* The socket connected to the debugger */
+static struct channel * dbg_in; /* Input channel on the socket */
+static struct channel * dbg_out;/* Output channel on the socket */
+
+static char *dbg_addr = "(none)";
+
+static void open_connection(void)
+{
+#ifdef _WIN32
+ /* Set socket to synchronous mode so that file descriptor-oriented
+ functions (read()/write() etc.) can be used */
+
+ int oldvalue, oldvaluelen, newvalue, retcode;
+ oldvaluelen = sizeof(oldvalue);
+ retcode = getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &oldvalue, &oldvaluelen);
+ if (retcode == 0) {
+ newvalue = SO_SYNCHRONOUS_NONALERT;
+ setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &newvalue, sizeof(newvalue));
+ }
+#endif
+ dbg_socket = socket(sock_domain, SOCK_STREAM, 0);
+#ifdef _WIN32
+ if (retcode == 0) {
+ /* Restore initial mode */
+ setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &oldvalue, oldvaluelen);
+ }
+#endif
+ if (dbg_socket == -1 ||
+ connect(dbg_socket, &sock_addr.s_gen, sock_addr_len) == -1){
+ caml_fatal_error_arg2 ("cannot connect to debugger at %s\n", dbg_addr,
+ "error: %s\n", strerror (errno));
+ }
+#ifdef _WIN32
+ dbg_socket = _open_osfhandle(dbg_socket, 0);
+ if (dbg_socket == -1)
+ caml_fatal_error("_open_osfhandle failed");
+#endif
+ dbg_in = caml_open_descriptor_in(dbg_socket);
+ dbg_out = caml_open_descriptor_out(dbg_socket);
+ if (!caml_debugger_in_use) caml_putword(dbg_out, -1); /* first connection */
+#ifdef _WIN32
+ caml_putword(dbg_out, _getpid());
+#else
+ caml_putword(dbg_out, getpid());
+#endif
+ caml_flush(dbg_out);
+}
+
+static void close_connection(void)
+{
+ caml_close_channel(dbg_in);
+ caml_close_channel(dbg_out);
+ dbg_socket = -1; /* was closed by caml_close_channel */
+}
+
+#ifdef _WIN32
+static void winsock_startup(void)
+{
+ WSADATA wsaData;
+ int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
+ if (err) caml_fatal_error("WSAStartup failed");
+}
+
+static void winsock_cleanup(void)
+{
+ WSACleanup();
+}
+#endif
+
+void caml_debugger_init(void)
+{
+ char * address;
+ char * port, * p;
+ struct hostent * host;
+ int n;
+
+ caml_register_global_root(&marshal_flags);
+ marshal_flags = caml_alloc(2, Tag_cons);
+ Store_field(marshal_flags, 0, Val_int(1)); /* Marshal.Closures */
+ Store_field(marshal_flags, 1, Val_emptylist);
+
+ address = getenv("CAML_DEBUG_SOCKET");
+ if (address == NULL) return;
+ dbg_addr = address;
+
+#ifdef _WIN32
+ winsock_startup();
+ (void)atexit(winsock_cleanup);
+#endif
+ /* Parse the address */
+ port = NULL;
+ for (p = address; *p != 0; p++) {
+ if (*p == ':') { *p = 0; port = p+1; break; }
+ }
+ if (port == NULL) {
+#ifndef _WIN32
+ /* Unix domain */
+ sock_domain = PF_UNIX;
+ sock_addr.s_unix.sun_family = AF_UNIX;
+ strncpy(sock_addr.s_unix.sun_path, address,
+ sizeof(sock_addr.s_unix.sun_path));
+ sock_addr_len =
+ ((char *)&(sock_addr.s_unix.sun_path) - (char *)&(sock_addr.s_unix))
+ + strlen(address);
+#else
+ caml_fatal_error("Unix sockets not supported");
+#endif
+ } else {
+ /* Internet domain */
+ sock_domain = PF_INET;
+ for (p = (char *) &sock_addr.s_inet, n = sizeof(sock_addr.s_inet);
+ n > 0; n--) *p++ = 0;
+ sock_addr.s_inet.sin_family = AF_INET;
+ sock_addr.s_inet.sin_addr.s_addr = inet_addr(address);
+ if (sock_addr.s_inet.sin_addr.s_addr == -1) {
+ host = gethostbyname(address);
+ if (host == NULL)
+ caml_fatal_error_arg("Unknown debugging host %s\n", address);
+ memmove(&sock_addr.s_inet.sin_addr, host->h_addr, host->h_length);
+ }
+ sock_addr.s_inet.sin_port = htons(atoi(port));
+ sock_addr_len = sizeof(sock_addr.s_inet);
+ }
+ open_connection();
+ caml_debugger_in_use = 1;
+ caml_trap_barrier = caml_stack_high;
+}
+
+static value getval(struct channel *chan)
+{
+ value res;
+ if (caml_really_getblock(chan, (char *) &res, sizeof(res)) == 0)
+ caml_raise_end_of_file(); /* Bad, but consistent with caml_getword */
+ return res;
+}
+
+static void putval(struct channel *chan, value val)
+{
+ caml_really_putblock(chan, (char *) &val, sizeof(val));
+}
+
+static void safe_output_value(struct channel *chan, value val)
+{
+ struct longjmp_buffer raise_buf, * saved_external_raise;
+
+ /* Catch exceptions raised by [caml_output_val] */
+ saved_external_raise = caml_external_raise;
+ if (sigsetjmp(raise_buf.buf, 0) == 0) {
+ caml_external_raise = &raise_buf;
+ caml_output_val(chan, val, marshal_flags);
+ } else {
+ /* Send wrong magic number, will cause [caml_input_value] to fail */
+ caml_really_putblock(chan, "\000\000\000\000", 4);
+ }
+ caml_external_raise = saved_external_raise;
+}
+
+#define Pc(sp) ((code_t)((sp)[0]))
+#define Env(sp) ((sp)[1])
+#define Extra_args(sp) (Long_val(((sp)[2])))
+#define Locals(sp) ((sp) + 3)
+
+void caml_debugger(enum event_kind event)
+{
+ value * frame;
+ intnat i, pos;
+ value val;
+
+ if (dbg_socket == -1) return; /* Not connected to a debugger. */
+
+ /* Reset current frame */
+ frame = caml_extern_sp + 1;
+
+ /* Report the event to the debugger */
+ switch(event) {
+ case PROGRAM_START: /* Nothing to report */
+ goto command_loop;
+ case EVENT_COUNT:
+ putch(dbg_out, REP_EVENT);
+ break;
+ case BREAKPOINT:
+ putch(dbg_out, REP_BREAKPOINT);
+ break;
+ case PROGRAM_EXIT:
+ putch(dbg_out, REP_EXITED);
+ break;
+ case TRAP_BARRIER:
+ putch(dbg_out, REP_TRAP);
+ break;
+ case UNCAUGHT_EXC:
+ putch(dbg_out, REP_UNCAUGHT_EXC);
+ break;
+ }
+ caml_putword(dbg_out, caml_event_count);
+ if (event == EVENT_COUNT || event == BREAKPOINT) {
+ caml_putword(dbg_out, caml_stack_high - frame);
+ caml_putword(dbg_out, (Pc(frame) - caml_start_code) * sizeof(opcode_t));
+ } else {
+ /* No PC and no stack frame associated with other events */
+ caml_putword(dbg_out, 0);
+ caml_putword(dbg_out, 0);
+ }
+ caml_flush(dbg_out);
+
+ command_loop:
+
+ /* Read and execute the commands sent by the debugger */
+ while(1) {
+ switch(getch(dbg_in)) {
+ case REQ_SET_EVENT:
+ pos = caml_getword(dbg_in);
+ Assert (pos >= 0);
+ Assert (pos < caml_code_size);
+ caml_set_instruction(caml_start_code + pos / sizeof(opcode_t), EVENT);
+ break;
+ case REQ_SET_BREAKPOINT:
+ pos = caml_getword(dbg_in);
+ Assert (pos >= 0);
+ Assert (pos < caml_code_size);
+ caml_set_instruction(caml_start_code + pos / sizeof(opcode_t), BREAK);
+ break;
+ case REQ_RESET_INSTR:
+ pos = caml_getword(dbg_in);
+ Assert (pos >= 0);
+ Assert (pos < caml_code_size);
+ pos = pos / sizeof(opcode_t);
+ caml_set_instruction(caml_start_code + pos, caml_saved_code[pos]);
+ break;
+ case REQ_CHECKPOINT:
+#ifndef _WIN32
+ i = fork();
+ if (i == 0) {
+ close_connection(); /* Close parent connection. */
+ open_connection(); /* Open new connection with debugger */
+ } else {
+ caml_putword(dbg_out, i);
+ caml_flush(dbg_out);
+ }
+#else
+ caml_fatal_error("error: REQ_CHECKPOINT command");
+ exit(-1);
+#endif
+ break;
+ case REQ_GO:
+ caml_event_count = caml_getword(dbg_in);
+ return;
+ case REQ_STOP:
+ exit(0);
+ break;
+ case REQ_WAIT:
+#ifndef _WIN32
+ wait(NULL);
+#else
+ caml_fatal_error("Fatal error: REQ_WAIT command");
+ exit(-1);
+#endif
+ break;
+ case REQ_INITIAL_FRAME:
+ frame = caml_extern_sp + 1;
+ /* Fall through */
+ case REQ_GET_FRAME:
+ caml_putword(dbg_out, caml_stack_high - frame);
+ if (frame < caml_stack_high){
+ caml_putword(dbg_out, (Pc(frame) - caml_start_code) * sizeof(opcode_t));
+ }else{
+ caml_putword (dbg_out, 0);
+ }
+ caml_flush(dbg_out);
+ break;
+ case REQ_SET_FRAME:
+ i = caml_getword(dbg_in);
+ frame = caml_stack_high - i;
+ break;
+ case REQ_UP_FRAME:
+ i = caml_getword(dbg_in);
+ if (frame + Extra_args(frame) + i + 3 >= caml_stack_high) {
+ caml_putword(dbg_out, -1);
+ } else {
+ frame += Extra_args(frame) + i + 3;
+ caml_putword(dbg_out, caml_stack_high - frame);
+ caml_putword(dbg_out, (Pc(frame) - caml_start_code) * sizeof(opcode_t));
+ }
+ caml_flush(dbg_out);
+ break;
+ case REQ_SET_TRAP_BARRIER:
+ i = caml_getword(dbg_in);
+ caml_trap_barrier = caml_stack_high - i;
+ break;
+ case REQ_GET_LOCAL:
+ i = caml_getword(dbg_in);
+ putval(dbg_out, Locals(frame)[i]);
+ caml_flush(dbg_out);
+ break;
+ case REQ_GET_ENVIRONMENT:
+ i = caml_getword(dbg_in);
+ putval(dbg_out, Field(Env(frame), i));
+ caml_flush(dbg_out);
+ break;
+ case REQ_GET_GLOBAL:
+ i = caml_getword(dbg_in);
+ putval(dbg_out, Field(caml_global_data, i));
+ caml_flush(dbg_out);
+ break;
+ case REQ_GET_ACCU:
+ putval(dbg_out, *caml_extern_sp);
+ caml_flush(dbg_out);
+ break;
+ case REQ_GET_HEADER:
+ val = getval(dbg_in);
+ caml_putword(dbg_out, Hd_val(val));
+ caml_flush(dbg_out);
+ break;
+ case REQ_GET_FIELD:
+ val = getval(dbg_in);
+ i = caml_getword(dbg_in);
+ if (Tag_val(val) != Double_array_tag) {
+ putch(dbg_out, 0);
+ putval(dbg_out, Field(val, i));
+ } else {
+ double d = Double_field(val, i);
+ putch(dbg_out, 1);
+ caml_really_putblock(dbg_out, (char *) &d, 8);
+ }
+ caml_flush(dbg_out);
+ break;
+ case REQ_MARSHAL_OBJ:
+ val = getval(dbg_in);
+ safe_output_value(dbg_out, val);
+ caml_flush(dbg_out);
+ break;
+ case REQ_GET_CLOSURE_CODE:
+ val = getval(dbg_in);
+ caml_putword(dbg_out, (Code_val(val)-caml_start_code) * sizeof(opcode_t));
+ caml_flush(dbg_out);
+ break;
+ case REQ_SET_FORK_MODE:
+ caml_debugger_fork_mode = caml_getword(dbg_in);
+ break;
+ }
+ }
+}
+
+void caml_debugger_cleanup_fork(void)
+{
+ /* We could remove all of the breakpoints, but closing the connection
+ * means that they'll just be skipped anyway. */
+ close_connection();
+ caml_debugger_in_use = 0;
+}
+
+#endif
diff --git a/byterun/dynlink.c b/byterun/dynlink.c
new file mode 100644
index 0000000000..1f822a9fb1
--- /dev/null
+++ b/byterun/dynlink.c
@@ -0,0 +1,279 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Dynamic loading of C primitives. */
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include "caml/config.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#include "caml/alloc.h"
+#include "caml/dynlink.h"
+#include "caml/fail.h"
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/osdeps.h"
+#include "caml/prims.h"
+#include "caml/signals.h"
+
+#ifndef NATIVE_CODE
+
+/* The table of primitives */
+struct ext_table caml_prim_table;
+
+#ifdef DEBUG
+/* The names of primitives (for instrtrace.c) */
+struct ext_table caml_prim_name_table;
+#endif
+
+/* The table of shared libraries currently opened */
+static struct ext_table shared_libs;
+
+/* The search path for shared libraries */
+struct ext_table caml_shared_libs_path;
+
+/* Look up the given primitive name in the built-in primitive table,
+ then in the opened shared libraries (shared_libs) */
+static c_primitive lookup_primitive(char * name)
+{
+ int i;
+ void * res;
+
+ for (i = 0; caml_names_of_builtin_cprim[i] != NULL; i++) {
+ if (strcmp(name, caml_names_of_builtin_cprim[i]) == 0)
+ return caml_builtin_cprim[i];
+ }
+ for (i = 0; i < shared_libs.size; i++) {
+ res = caml_dlsym(shared_libs.contents[i], name);
+ if (res != NULL) return (c_primitive) res;
+ }
+ return NULL;
+}
+
+/* Parse the OCAML_STDLIB_DIR/ld.conf file and add the directories
+ listed there to the search path */
+
+#define LD_CONF_NAME "ld.conf"
+
+static char * parse_ld_conf(void)
+{
+ char * stdlib, * ldconfname, * config, * p, * q;
+ struct stat st;
+ int ldconf, nread;
+
+ stdlib = getenv("OCAMLLIB");
+ if (stdlib == NULL) stdlib = getenv("CAMLLIB");
+ if (stdlib == NULL) stdlib = OCAML_STDLIB_DIR;
+ ldconfname = caml_strconcat(3, stdlib, "/", LD_CONF_NAME);
+ if (stat(ldconfname, &st) == -1) {
+ caml_stat_free(ldconfname);
+ return NULL;
+ }
+ ldconf = open(ldconfname, O_RDONLY, 0);
+ if (ldconf == -1)
+ caml_fatal_error_arg("Fatal error: cannot read loader config file %s\n",
+ ldconfname);
+ config = caml_stat_alloc(st.st_size + 1);
+ nread = read(ldconf, config, st.st_size);
+ if (nread == -1)
+ caml_fatal_error_arg
+ ("Fatal error: error while reading loader config file %s\n",
+ ldconfname);
+ config[nread] = 0;
+ q = config;
+ for (p = config; *p != 0; p++) {
+ if (*p == '\n') {
+ *p = 0;
+ caml_ext_table_add(&caml_shared_libs_path, q);
+ q = p + 1;
+ }
+ }
+ if (q < p) caml_ext_table_add(&caml_shared_libs_path, q);
+ close(ldconf);
+ caml_stat_free(ldconfname);
+ return config;
+}
+
+/* Open the given shared library and add it to shared_libs.
+ Abort on error. */
+static void open_shared_lib(char * name)
+{
+ char * realname;
+ void * handle;
+
+ realname = caml_search_dll_in_path(&caml_shared_libs_path, name);
+ caml_gc_message(0x100, "Loading shared library %s\n",
+ (uintnat) realname);
+ caml_enter_blocking_section();
+ handle = caml_dlopen(realname, 1, 1);
+ caml_leave_blocking_section();
+ if (handle == NULL)
+ caml_fatal_error_arg2("Fatal error: cannot load shared library %s\n", name,
+ "Reason: %s\n", caml_dlerror());
+ caml_ext_table_add(&shared_libs, handle);
+ caml_stat_free(realname);
+}
+
+/* Build the table of primitives, given a search path and a list
+ of shared libraries (both 0-separated in a char array).
+ Abort the runtime system on error. */
+void caml_build_primitive_table(char * lib_path,
+ char * libs,
+ char * req_prims)
+{
+ char * tofree1, * tofree2;
+ char * p;
+
+ /* Initialize the search path for dynamic libraries:
+ - directories specified on the command line with the -I option
+ - directories specified in the CAML_LD_LIBRARY_PATH
+ - directories specified in the executable
+ - directories specified in the file <stdlib>/ld.conf */
+ tofree1 = caml_decompose_path(&caml_shared_libs_path,
+ getenv("CAML_LD_LIBRARY_PATH"));
+ if (lib_path != NULL)
+ for (p = lib_path; *p != 0; p += strlen(p) + 1)
+ caml_ext_table_add(&caml_shared_libs_path, p);
+ tofree2 = parse_ld_conf();
+ /* Open the shared libraries */
+ caml_ext_table_init(&shared_libs, 8);
+ if (libs != NULL)
+ for (p = libs; *p != 0; p += strlen(p) + 1)
+ open_shared_lib(p);
+ /* Build the primitive table */
+ caml_ext_table_init(&caml_prim_table, 0x180);
+#ifdef DEBUG
+ caml_ext_table_init(&caml_prim_name_table, 0x180);
+#endif
+ for (p = req_prims; *p != 0; p += strlen(p) + 1) {
+ c_primitive prim = lookup_primitive(p);
+ if (prim == NULL)
+ caml_fatal_error_arg("Fatal error: unknown C primitive `%s'\n", p);
+ caml_ext_table_add(&caml_prim_table, (void *) prim);
+#ifdef DEBUG
+ caml_ext_table_add(&caml_prim_name_table, strdup(p));
+#endif
+ }
+ /* Clean up */
+ caml_stat_free(tofree1);
+ caml_stat_free(tofree2);
+ caml_ext_table_free(&caml_shared_libs_path, 0);
+}
+
+/* Build the table of primitives as a copy of the builtin primitive table.
+ Used for executables generated by ocamlc -output-obj. */
+
+void caml_build_primitive_table_builtin(void)
+{
+ int i;
+ caml_ext_table_init(&caml_prim_table, 0x180);
+#ifdef DEBUG
+ caml_ext_table_init(&caml_prim_name_table, 0x180);
+#endif
+ for (i = 0; caml_builtin_cprim[i] != 0; i++) {
+ caml_ext_table_add(&caml_prim_table, (void *) caml_builtin_cprim[i]);
+#ifdef DEBUG
+ caml_ext_table_add(&caml_prim_name_table,
+ strdup(caml_names_of_builtin_cprim[i]));
+#endif
+ }
+}
+
+#endif /* NATIVE_CODE */
+
+/** dlopen interface for the bytecode linker **/
+
+#define Handle_val(v) (*((void **) (v)))
+
+CAMLprim value caml_dynlink_open_lib(value mode, value filename)
+{
+ void * handle;
+ value result;
+ char * p;
+
+ caml_gc_message(0x100, "Opening shared library %s\n",
+ (uintnat) String_val(filename));
+ p = caml_strdup(String_val(filename));
+ caml_enter_blocking_section();
+ handle = caml_dlopen(p, Int_val(mode), 1);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (handle == NULL) caml_failwith(caml_dlerror());
+ result = caml_alloc_small(1, Abstract_tag);
+ Handle_val(result) = handle;
+ return result;
+}
+
+CAMLprim value caml_dynlink_close_lib(value handle)
+{
+ caml_dlclose(Handle_val(handle));
+ return Val_unit;
+}
+
+/*#include <stdio.h>*/
+CAMLprim value caml_dynlink_lookup_symbol(value handle, value symbolname)
+{
+ void * symb;
+ value result;
+ symb = caml_dlsym(Handle_val(handle), String_val(symbolname));
+ /* printf("%s = 0x%lx\n", String_val(symbolname), symb);
+ fflush(stdout); */
+ if (symb == NULL) return Val_unit /*caml_failwith(caml_dlerror())*/;
+ result = caml_alloc_small(1, Abstract_tag);
+ Handle_val(result) = symb;
+ return result;
+}
+
+#ifndef NATIVE_CODE
+
+CAMLprim value caml_dynlink_add_primitive(value handle)
+{
+ return Val_int(caml_ext_table_add(&caml_prim_table, Handle_val(handle)));
+}
+
+CAMLprim value caml_dynlink_get_current_libs(value unit)
+{
+ CAMLparam0();
+ CAMLlocal1(res);
+ int i;
+
+ res = caml_alloc_tuple(shared_libs.size);
+ for (i = 0; i < shared_libs.size; i++) {
+ value v = caml_alloc_small(1, Abstract_tag);
+ Handle_val(v) = shared_libs.contents[i];
+ Store_field(res, i, v);
+ }
+ CAMLreturn(res);
+}
+
+#else
+
+value caml_dynlink_add_primitive(value handle)
+{
+ caml_invalid_argument("dynlink_add_primitive");
+ return Val_unit; /* not reached */
+}
+
+value caml_dynlink_get_current_libs(value unit)
+{
+ caml_invalid_argument("dynlink_get_current_libs");
+ return Val_unit; /* not reached */
+}
+
+#endif /* NATIVE_CODE */
diff --git a/byterun/extern.c b/byterun/extern.c
new file mode 100644
index 0000000000..c27e462dcd
--- /dev/null
+++ b/byterun/extern.c
@@ -0,0 +1,857 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Structured output */
+
+/* The interface of this file is "caml/intext.h" */
+
+#include <string.h>
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/gc.h"
+#include "caml/intext.h"
+#include "caml/io.h"
+#include "caml/md5.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/reverse.h"
+
+static uintnat obj_counter; /* Number of objects emitted so far */
+static uintnat size_32; /* Size in words of 32-bit block for struct. */
+static uintnat size_64; /* Size in words of 64-bit block for struct. */
+
+/* Flags affecting marshaling */
+
+enum {
+ NO_SHARING = 1, /* Flag to ignore sharing */
+ CLOSURES = 2, /* Flag to allow marshaling code pointers */
+ COMPAT_32 = 4 /* Flag to ensure that output can safely
+ be read back on a 32-bit platform */
+};
+
+static int extern_flags; /* logical or of some of the flags above */
+
+/* Trail mechanism to undo forwarding pointers put inside objects */
+
+struct trail_entry {
+ value obj; /* address of object + initial color in low 2 bits */
+ value field0; /* initial contents of field 0 */
+};
+
+struct trail_block {
+ struct trail_block * previous;
+ struct trail_entry entries[ENTRIES_PER_TRAIL_BLOCK];
+};
+
+static struct trail_block extern_trail_first;
+static struct trail_block * extern_trail_block;
+static struct trail_entry * extern_trail_cur, * extern_trail_limit;
+
+
+/* Stack for pending values to marshal */
+
+struct extern_item { value * v; mlsize_t count; };
+
+#define EXTERN_STACK_INIT_SIZE 256
+#define EXTERN_STACK_MAX_SIZE (1024*1024*100)
+
+static struct extern_item extern_stack_init[EXTERN_STACK_INIT_SIZE];
+
+static struct extern_item * extern_stack = extern_stack_init;
+static struct extern_item * extern_stack_limit = extern_stack_init
+ + EXTERN_STACK_INIT_SIZE;
+
+/* Forward declarations */
+
+CAMLnoreturn_start
+static void extern_out_of_memory(void)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+static void extern_invalid_argument(char *msg)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+static void extern_failwith(char *msg)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+static void extern_stack_overflow(void)
+CAMLnoreturn_end;
+
+static struct code_fragment * extern_find_code(char *addr);
+static void extern_replay_trail(void);
+static void free_extern_output(void);
+
+/* Free the extern stack if needed */
+static void extern_free_stack(void)
+{
+ if (extern_stack != extern_stack_init) {
+ free(extern_stack);
+ /* Reinitialize the globals for next time around */
+ extern_stack = extern_stack_init;
+ extern_stack_limit = extern_stack + EXTERN_STACK_INIT_SIZE;
+ }
+}
+
+static struct extern_item * extern_resize_stack(struct extern_item * sp)
+{
+ asize_t newsize = 2 * (extern_stack_limit - extern_stack);
+ asize_t sp_offset = sp - extern_stack;
+ struct extern_item * newstack;
+
+ if (newsize >= EXTERN_STACK_MAX_SIZE) extern_stack_overflow();
+ if (extern_stack == extern_stack_init) {
+ newstack = malloc(sizeof(struct extern_item) * newsize);
+ if (newstack == NULL) extern_stack_overflow();
+ memcpy(newstack, extern_stack_init,
+ sizeof(struct extern_item) * EXTERN_STACK_INIT_SIZE);
+ } else {
+ newstack =
+ realloc(extern_stack, sizeof(struct extern_item) * newsize);
+ if (newstack == NULL) extern_stack_overflow();
+ }
+ extern_stack = newstack;
+ extern_stack_limit = newstack + newsize;
+ return newstack + sp_offset;
+}
+
+/* Initialize the trail */
+
+static void init_extern_trail(void)
+{
+ extern_trail_block = &extern_trail_first;
+ extern_trail_cur = extern_trail_block->entries;
+ extern_trail_limit = extern_trail_block->entries + ENTRIES_PER_TRAIL_BLOCK;
+}
+
+/* Replay the trail, undoing the in-place modifications
+ performed on objects */
+
+static void extern_replay_trail(void)
+{
+ struct trail_block * blk, * prevblk;
+ struct trail_entry * ent, * lim;
+
+ blk = extern_trail_block;
+ lim = extern_trail_cur;
+ while (1) {
+ for (ent = &(blk->entries[0]); ent < lim; ent++) {
+ value obj = ent->obj;
+ color_t colornum = obj & 3;
+ obj = obj & ~3;
+ Hd_val(obj) = Coloredhd_hd(Hd_val(obj), colornum);
+ Field(obj, 0) = ent->field0;
+ }
+ if (blk == &extern_trail_first) break;
+ prevblk = blk->previous;
+ free(blk);
+ blk = prevblk;
+ lim = &(blk->entries[ENTRIES_PER_TRAIL_BLOCK]);
+ }
+ /* Protect against a second call to extern_replay_trail */
+ extern_trail_block = &extern_trail_first;
+ extern_trail_cur = extern_trail_block->entries;
+}
+
+/* Set forwarding pointer on an object and add corresponding entry
+ to the trail. */
+
+static void extern_record_location(value obj)
+{
+ header_t hdr;
+
+ if (extern_flags & NO_SHARING) return;
+ if (extern_trail_cur == extern_trail_limit) {
+ struct trail_block * new_block = malloc(sizeof(struct trail_block));
+ if (new_block == NULL) extern_out_of_memory();
+ new_block->previous = extern_trail_block;
+ extern_trail_block = new_block;
+ extern_trail_cur = extern_trail_block->entries;
+ extern_trail_limit = extern_trail_block->entries + ENTRIES_PER_TRAIL_BLOCK;
+ }
+ hdr = Hd_val(obj);
+ extern_trail_cur->obj = obj | Colornum_hd(hdr);
+ extern_trail_cur->field0 = Field(obj, 0);
+ extern_trail_cur++;
+ Hd_val(obj) = Bluehd_hd(hdr);
+ Field(obj, 0) = (value) obj_counter;
+ obj_counter++;
+}
+
+/* To buffer the output */
+
+static char * extern_userprovided_output;
+static char * extern_ptr, * extern_limit;
+
+struct output_block {
+ struct output_block * next;
+ char * end;
+ char data[SIZE_EXTERN_OUTPUT_BLOCK];
+};
+
+static struct output_block * extern_output_first, * extern_output_block;
+
+static void init_extern_output(void)
+{
+ extern_userprovided_output = NULL;
+ extern_output_first = malloc(sizeof(struct output_block));
+ if (extern_output_first == NULL) caml_raise_out_of_memory();
+ extern_output_block = extern_output_first;
+ extern_output_block->next = NULL;
+ extern_ptr = extern_output_block->data;
+ extern_limit = extern_output_block->data + SIZE_EXTERN_OUTPUT_BLOCK;
+}
+
+static void close_extern_output(void)
+{
+ if (extern_userprovided_output == NULL){
+ extern_output_block->end = extern_ptr;
+ }
+}
+
+static void free_extern_output(void)
+{
+ struct output_block * blk, * nextblk;
+
+ if (extern_userprovided_output != NULL) return;
+ for (blk = extern_output_first; blk != NULL; blk = nextblk) {
+ nextblk = blk->next;
+ free(blk);
+ }
+ extern_output_first = NULL;
+ extern_free_stack();
+}
+
+static void grow_extern_output(intnat required)
+{
+ struct output_block * blk;
+ intnat extra;
+
+ if (extern_userprovided_output != NULL) {
+ extern_failwith("Marshal.to_buffer: buffer overflow");
+ }
+ extern_output_block->end = extern_ptr;
+ if (required <= SIZE_EXTERN_OUTPUT_BLOCK / 2)
+ extra = 0;
+ else
+ extra = required;
+ blk = malloc(sizeof(struct output_block) + extra);
+ if (blk == NULL) extern_out_of_memory();
+ extern_output_block->next = blk;
+ extern_output_block = blk;
+ extern_output_block->next = NULL;
+ extern_ptr = extern_output_block->data;
+ extern_limit = extern_output_block->data + SIZE_EXTERN_OUTPUT_BLOCK + extra;
+}
+
+static intnat extern_output_length(void)
+{
+ struct output_block * blk;
+ intnat len;
+
+ if (extern_userprovided_output != NULL) {
+ return extern_ptr - extern_userprovided_output;
+ } else {
+ for (len = 0, blk = extern_output_first; blk != NULL; blk = blk->next)
+ len += blk->end - blk->data;
+ return len;
+ }
+}
+
+/* Exception raising, with cleanup */
+
+static void extern_out_of_memory(void)
+{
+ extern_replay_trail();
+ free_extern_output();
+ caml_raise_out_of_memory();
+}
+
+static void extern_invalid_argument(char *msg)
+{
+ extern_replay_trail();
+ free_extern_output();
+ caml_invalid_argument(msg);
+}
+
+static void extern_failwith(char *msg)
+{
+ extern_replay_trail();
+ free_extern_output();
+ caml_failwith(msg);
+}
+
+static void extern_stack_overflow(void)
+{
+ caml_gc_message (0x04, "Stack overflow in marshaling value\n", 0);
+ extern_replay_trail();
+ free_extern_output();
+ caml_raise_out_of_memory();
+}
+
+/* Write characters, integers, and blocks in the output buffer */
+
+#define Write(c) \
+ if (extern_ptr >= extern_limit) grow_extern_output(1); \
+ *extern_ptr++ = (c)
+
+static void writeblock(char *data, intnat len)
+{
+ if (extern_ptr + len > extern_limit) grow_extern_output(len);
+ memmove(extern_ptr, data, len);
+ extern_ptr += len;
+}
+
+#if ARCH_FLOAT_ENDIANNESS == 0x01234567 || ARCH_FLOAT_ENDIANNESS == 0x76543210
+#define writeblock_float8(data,ndoubles) \
+ writeblock((char *)(data), (ndoubles) * 8)
+#else
+#define writeblock_float8(data,ndoubles) \
+ caml_serialize_block_float_8((data), (ndoubles))
+#endif
+
+static void writecode8(int code, intnat val)
+{
+ if (extern_ptr + 2 > extern_limit) grow_extern_output(2);
+ extern_ptr[0] = code;
+ extern_ptr[1] = val;
+ extern_ptr += 2;
+}
+
+static void writecode16(int code, intnat val)
+{
+ if (extern_ptr + 3 > extern_limit) grow_extern_output(3);
+ extern_ptr[0] = code;
+ extern_ptr[1] = val >> 8;
+ extern_ptr[2] = val;
+ extern_ptr += 3;
+}
+
+static void write32(intnat val)
+{
+ if (extern_ptr + 4 > extern_limit) grow_extern_output(4);
+ extern_ptr[0] = val >> 24;
+ extern_ptr[1] = val >> 16;
+ extern_ptr[2] = val >> 8;
+ extern_ptr[3] = val;
+ extern_ptr += 4;
+}
+
+static void writecode32(int code, intnat val)
+{
+ if (extern_ptr + 5 > extern_limit) grow_extern_output(5);
+ extern_ptr[0] = code;
+ extern_ptr[1] = val >> 24;
+ extern_ptr[2] = val >> 16;
+ extern_ptr[3] = val >> 8;
+ extern_ptr[4] = val;
+ extern_ptr += 5;
+}
+
+#ifdef ARCH_SIXTYFOUR
+static void writecode64(int code, intnat val)
+{
+ int i;
+ if (extern_ptr + 9 > extern_limit) grow_extern_output(9);
+ *extern_ptr ++ = code;
+ for (i = 64 - 8; i >= 0; i -= 8) *extern_ptr++ = val >> i;
+}
+#endif
+
+/* Marshal the given value in the output buffer */
+
+static void extern_rec(value v)
+{
+ struct code_fragment * cf;
+ struct extern_item * sp;
+ sp = extern_stack;
+
+ while(1) {
+ if (Is_long(v)) {
+ intnat n = Long_val(v);
+ if (n >= 0 && n < 0x40) {
+ Write(PREFIX_SMALL_INT + n);
+ } else if (n >= -(1 << 7) && n < (1 << 7)) {
+ writecode8(CODE_INT8, n);
+ } else if (n >= -(1 << 15) && n < (1 << 15)) {
+ writecode16(CODE_INT16, n);
+#ifdef ARCH_SIXTYFOUR
+ } else if (n < -((intnat)1 << 30) || n >= ((intnat)1 << 30)) {
+ if (extern_flags & COMPAT_32)
+ extern_failwith("output_value: integer cannot be read back on "
+ "32-bit platform");
+ writecode64(CODE_INT64, n);
+#endif
+ } else
+ writecode32(CODE_INT32, n);
+ goto next_item;
+ }
+ if (Is_in_value_area(v)) {
+ header_t hd = Hd_val(v);
+ tag_t tag = Tag_hd(hd);
+ mlsize_t sz = Wosize_hd(hd);
+
+ if (tag == Forward_tag) {
+ value f = Forward_val (v);
+ if (Is_block (f)
+ && (!Is_in_value_area(f) || Tag_val (f) == Forward_tag
+ || Tag_val (f) == Lazy_tag || Tag_val (f) == Double_tag)){
+ /* Do not short-circuit the pointer. */
+ }else{
+ v = f;
+ continue;
+ }
+ }
+ /* Atoms are treated specially for two reasons: they are not allocated
+ in the externed block, and they are automatically shared. */
+ if (sz == 0) {
+ if (tag < 16) {
+ Write(PREFIX_SMALL_BLOCK + tag);
+ } else {
+ writecode32(CODE_BLOCK32, hd);
+ }
+ goto next_item;
+ }
+ /* Check if already seen */
+ if (Color_hd(hd) == Caml_blue) {
+ uintnat d = obj_counter - (uintnat) Field(v, 0);
+ if (d < 0x100) {
+ writecode8(CODE_SHARED8, d);
+ } else if (d < 0x10000) {
+ writecode16(CODE_SHARED16, d);
+ } else {
+ writecode32(CODE_SHARED32, d);
+ }
+ goto next_item;
+ }
+
+ /* Output the contents of the object */
+ switch(tag) {
+ case String_tag: {
+ mlsize_t len = caml_string_length(v);
+ if (len < 0x20) {
+ Write(PREFIX_SMALL_STRING + len);
+ } else if (len < 0x100) {
+ writecode8(CODE_STRING8, len);
+ } else {
+#ifdef ARCH_SIXTYFOUR
+ if (len > 0xFFFFFB && (extern_flags & COMPAT_32))
+ extern_failwith("output_value: string cannot be read back on "
+ "32-bit platform");
+#endif
+ writecode32(CODE_STRING32, len);
+ }
+ writeblock(String_val(v), len);
+ size_32 += 1 + (len + 4) / 4;
+ size_64 += 1 + (len + 8) / 8;
+ extern_record_location(v);
+ break;
+ }
+ case Double_tag: {
+ if (sizeof(double) != 8)
+ extern_invalid_argument("output_value: non-standard floats");
+ Write(CODE_DOUBLE_NATIVE);
+ writeblock_float8((double *) v, 1);
+ size_32 += 1 + 2;
+ size_64 += 1 + 1;
+ extern_record_location(v);
+ break;
+ }
+ case Double_array_tag: {
+ mlsize_t nfloats;
+ if (sizeof(double) != 8)
+ extern_invalid_argument("output_value: non-standard floats");
+ nfloats = Wosize_val(v) / Double_wosize;
+ if (nfloats < 0x100) {
+ writecode8(CODE_DOUBLE_ARRAY8_NATIVE, nfloats);
+ } else {
+#ifdef ARCH_SIXTYFOUR
+ if (nfloats > 0x1FFFFF && (extern_flags & COMPAT_32))
+ extern_failwith("output_value: float array cannot be read back on "
+ "32-bit platform");
+#endif
+ writecode32(CODE_DOUBLE_ARRAY32_NATIVE, nfloats);
+ }
+ writeblock_float8((double *) v, nfloats);
+ size_32 += 1 + nfloats * 2;
+ size_64 += 1 + nfloats;
+ extern_record_location(v);
+ break;
+ }
+ case Abstract_tag:
+ extern_invalid_argument("output_value: abstract value (Abstract)");
+ break;
+ case Infix_tag:
+ writecode32(CODE_INFIXPOINTER, Infix_offset_hd(hd));
+ v = v - Infix_offset_hd(hd); /* PR#5772 */
+ continue;
+ case Custom_tag: {
+ uintnat sz_32, sz_64;
+ char * ident = Custom_ops_val(v)->identifier;
+ void (*serialize)(value v, uintnat * bsize_32,
+ uintnat * bsize_64)
+ = Custom_ops_val(v)->serialize;
+ if (serialize == NULL)
+ extern_invalid_argument("output_value: abstract value (Custom)");
+ Write(CODE_CUSTOM);
+ writeblock(ident, strlen(ident) + 1);
+ Custom_ops_val(v)->serialize(v, &sz_32, &sz_64);
+ size_32 += 2 + ((sz_32 + 3) >> 2); /* header + ops + data */
+ size_64 += 2 + ((sz_64 + 7) >> 3);
+ extern_record_location(v);
+ break;
+ }
+ default: {
+ value field0;
+ if (tag < 16 && sz < 8) {
+ Write(PREFIX_SMALL_BLOCK + tag + (sz << 4));
+#ifdef ARCH_SIXTYFOUR
+ } else if (hd >= ((uintnat)1 << 32)) {
+ /* Is this case useful? The overflow check in extern_value will fail.*/
+ writecode64(CODE_BLOCK64, Whitehd_hd (hd));
+#endif
+ } else {
+#ifdef ARCH_SIXTYFOUR
+ if (sz > 0x3FFFFF && (extern_flags & COMPAT_32))
+ extern_failwith("output_value: array cannot be read back on "
+ "32-bit platform");
+#endif
+ writecode32(CODE_BLOCK32, Whitehd_hd (hd));
+ }
+ size_32 += 1 + sz;
+ size_64 += 1 + sz;
+ field0 = Field(v, 0);
+ extern_record_location(v);
+ /* Remember that we still have to serialize fields 1 ... sz - 1 */
+ if (sz > 1) {
+ sp++;
+ if (sp >= extern_stack_limit) sp = extern_resize_stack(sp);
+ sp->v = &Field(v,1);
+ sp->count = sz-1;
+ }
+ /* Continue serialization with the first field */
+ v = field0;
+ continue;
+ }
+ }
+ }
+ else if ((cf = extern_find_code((char *) v)) != NULL) {
+ if ((extern_flags & CLOSURES) == 0)
+ extern_invalid_argument("output_value: functional value");
+ writecode32(CODE_CODEPOINTER, (char *) v - cf->code_start);
+ writeblock((char *) cf->digest, 16);
+ } else {
+ extern_invalid_argument("output_value: abstract value (outside heap)");
+ }
+ next_item:
+ /* Pop one more item to marshal, if any */
+ if (sp == extern_stack) {
+ /* We are done. Cleanup the stack and leave the function */
+ extern_free_stack();
+ return;
+ }
+ v = *((sp->v)++);
+ if (--(sp->count) == 0) sp--;
+ }
+ /* Never reached as function leaves with return */
+}
+
+static int extern_flag_values[] = { NO_SHARING, CLOSURES, COMPAT_32 };
+
+static intnat extern_value(value v, value flags)
+{
+ intnat res_len;
+ /* Parse flag list */
+ extern_flags = caml_convert_flag_list(flags, extern_flag_values);
+ /* Initializations */
+ init_extern_trail();
+ obj_counter = 0;
+ size_32 = 0;
+ size_64 = 0;
+ /* Write magic number */
+ write32(Intext_magic_number);
+ /* Set aside space for the sizes */
+ extern_ptr += 4*4;
+ /* Marshal the object */
+ extern_rec(v);
+ /* Record end of output */
+ close_extern_output();
+ /* Undo the modifications done on externed blocks */
+ extern_replay_trail();
+ /* Write the sizes */
+ res_len = extern_output_length();
+#ifdef ARCH_SIXTYFOUR
+ if (res_len >= ((intnat)1 << 32) ||
+ size_32 >= ((intnat)1 << 32) || size_64 >= ((intnat)1 << 32)) {
+ /* The object is so big its size cannot be written in the header.
+ Besides, some of the array lengths or string lengths or shared offsets
+ it contains may have overflowed the 32 bits used to write them. */
+ free_extern_output();
+ caml_failwith("output_value: object too big");
+ }
+#endif
+ if (extern_userprovided_output != NULL)
+ extern_ptr = extern_userprovided_output + 4;
+ else {
+ extern_ptr = extern_output_first->data + 4;
+ extern_limit = extern_output_first->data + SIZE_EXTERN_OUTPUT_BLOCK;
+ }
+ write32(res_len - 5*4);
+ write32(obj_counter);
+ write32(size_32);
+ write32(size_64);
+ return res_len;
+}
+
+void caml_output_val(struct channel *chan, value v, value flags)
+{
+ struct output_block * blk, * nextblk;
+
+ if (! caml_channel_binary_mode(chan))
+ caml_failwith("output_value: not a binary channel");
+ init_extern_output();
+ extern_value(v, flags);
+ /* During [caml_really_putblock], concurrent [caml_output_val] operations
+ can take place (via signal handlers or context switching in systhreads),
+ and [extern_output_first] may change. So, save it in a local variable. */
+ blk = extern_output_first;
+ while (blk != NULL) {
+ caml_really_putblock(chan, blk->data, blk->end - blk->data);
+ nextblk = blk->next;
+ free(blk);
+ blk = nextblk;
+ }
+}
+
+CAMLprim value caml_output_value(value vchan, value v, value flags)
+{
+ CAMLparam3 (vchan, v, flags);
+ struct channel * channel = Channel(vchan);
+
+ Lock(channel);
+ caml_output_val(channel, v, flags);
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_output_value_to_string(value v, value flags)
+{
+ intnat len, ofs;
+ value res;
+ struct output_block * blk, * nextblk;
+
+ init_extern_output();
+ len = extern_value(v, flags);
+ /* PR#4030: it is prudent to save extern_output_first before allocating
+ the result, as in caml_output_val */
+ blk = extern_output_first;
+ res = caml_alloc_string(len);
+ ofs = 0;
+ while (blk != NULL) {
+ int n = blk->end - blk->data;
+ memmove(&Byte(res, ofs), blk->data, n);
+ ofs += n;
+ nextblk = blk->next;
+ free(blk);
+ blk = nextblk;
+ }
+ return res;
+}
+
+CAMLprim value caml_output_value_to_buffer(value buf, value ofs, value len,
+ value v, value flags)
+{
+ intnat len_res;
+ extern_userprovided_output = &Byte(buf, Long_val(ofs));
+ extern_ptr = extern_userprovided_output;
+ extern_limit = extern_userprovided_output + Long_val(len);
+ len_res = extern_value(v, flags);
+ return Val_long(len_res);
+}
+
+CAMLexport void caml_output_value_to_malloc(value v, value flags,
+ /*out*/ char ** buf,
+ /*out*/ intnat * len)
+{
+ intnat len_res;
+ char * res;
+ struct output_block * blk;
+
+ init_extern_output();
+ len_res = extern_value(v, flags);
+ res = malloc(len_res);
+ if (res == NULL) extern_out_of_memory();
+ *buf = res;
+ *len = len_res;
+ for (blk = extern_output_first; blk != NULL; blk = blk->next) {
+ int n = blk->end - blk->data;
+ memmove(res, blk->data, n);
+ res += n;
+ }
+ free_extern_output();
+}
+
+CAMLexport intnat caml_output_value_to_block(value v, value flags,
+ char * buf, intnat len)
+{
+ intnat len_res;
+ extern_userprovided_output = buf;
+ extern_ptr = extern_userprovided_output;
+ extern_limit = extern_userprovided_output + len;
+ len_res = extern_value(v, flags);
+ return len_res;
+}
+
+/* Functions for writing user-defined marshallers */
+
+CAMLexport void caml_serialize_int_1(int i)
+{
+ if (extern_ptr + 1 > extern_limit) grow_extern_output(1);
+ extern_ptr[0] = i;
+ extern_ptr += 1;
+}
+
+CAMLexport void caml_serialize_int_2(int i)
+{
+ if (extern_ptr + 2 > extern_limit) grow_extern_output(2);
+ extern_ptr[0] = i >> 8;
+ extern_ptr[1] = i;
+ extern_ptr += 2;
+}
+
+CAMLexport void caml_serialize_int_4(int32_t i)
+{
+ if (extern_ptr + 4 > extern_limit) grow_extern_output(4);
+ extern_ptr[0] = i >> 24;
+ extern_ptr[1] = i >> 16;
+ extern_ptr[2] = i >> 8;
+ extern_ptr[3] = i;
+ extern_ptr += 4;
+}
+
+CAMLexport void caml_serialize_int_8(int64_t i)
+{
+ caml_serialize_block_8(&i, 1);
+}
+
+CAMLexport void caml_serialize_float_4(float f)
+{
+ caml_serialize_block_4(&f, 1);
+}
+
+CAMLexport void caml_serialize_float_8(double f)
+{
+ caml_serialize_block_float_8(&f, 1);
+}
+
+CAMLexport void caml_serialize_block_1(void * data, intnat len)
+{
+ if (extern_ptr + len > extern_limit) grow_extern_output(len);
+ memmove(extern_ptr, data, len);
+ extern_ptr += len;
+}
+
+CAMLexport void caml_serialize_block_2(void * data, intnat len)
+{
+ if (extern_ptr + 2 * len > extern_limit) grow_extern_output(2 * len);
+#ifndef ARCH_BIG_ENDIAN
+ {
+ unsigned char * p;
+ char * q;
+ for (p = data, q = extern_ptr; len > 0; len--, p += 2, q += 2)
+ Reverse_16(q, p);
+ extern_ptr = q;
+ }
+#else
+ memmove(extern_ptr, data, len * 2);
+ extern_ptr += len * 2;
+#endif
+}
+
+CAMLexport void caml_serialize_block_4(void * data, intnat len)
+{
+ if (extern_ptr + 4 * len > extern_limit) grow_extern_output(4 * len);
+#ifndef ARCH_BIG_ENDIAN
+ {
+ unsigned char * p;
+ char * q;
+ for (p = data, q = extern_ptr; len > 0; len--, p += 4, q += 4)
+ Reverse_32(q, p);
+ extern_ptr = q;
+ }
+#else
+ memmove(extern_ptr, data, len * 4);
+ extern_ptr += len * 4;
+#endif
+}
+
+CAMLexport void caml_serialize_block_8(void * data, intnat len)
+{
+ if (extern_ptr + 8 * len > extern_limit) grow_extern_output(8 * len);
+#ifndef ARCH_BIG_ENDIAN
+ {
+ unsigned char * p;
+ char * q;
+ for (p = data, q = extern_ptr; len > 0; len--, p += 8, q += 8)
+ Reverse_64(q, p);
+ extern_ptr = q;
+ }
+#else
+ memmove(extern_ptr, data, len * 8);
+ extern_ptr += len * 8;
+#endif
+}
+
+CAMLexport void caml_serialize_block_float_8(void * data, intnat len)
+{
+ if (extern_ptr + 8 * len > extern_limit) grow_extern_output(8 * len);
+#if ARCH_FLOAT_ENDIANNESS == 0x01234567
+ memmove(extern_ptr, data, len * 8);
+ extern_ptr += len * 8;
+#elif ARCH_FLOAT_ENDIANNESS == 0x76543210
+ {
+ unsigned char * p;
+ char * q;
+ for (p = data, q = extern_ptr; len > 0; len--, p += 8, q += 8)
+ Reverse_64(q, p);
+ extern_ptr = q;
+ }
+#else
+ {
+ unsigned char * p;
+ char * q;
+ for (p = data, q = extern_ptr; len > 0; len--, p += 8, q += 8)
+ Permute_64(q, 0x01234567, p, ARCH_FLOAT_ENDIANNESS);
+ extern_ptr = q;
+ }
+#endif
+}
+
+/* Find where a code pointer comes from */
+
+static struct code_fragment * extern_find_code(char *addr)
+{
+ int i;
+ for (i = caml_code_fragments_table.size - 1; i >= 0; i--) {
+ struct code_fragment * cf = caml_code_fragments_table.contents[i];
+ if (! cf->digest_computed) {
+ caml_md5_block(cf->digest, cf->code_start, cf->code_end - cf->code_start);
+ cf->digest_computed = 1;
+ }
+ if (cf->code_start <= addr && addr < cf->code_end) return cf;
+ }
+ return NULL;
+}
diff --git a/byterun/fail.c b/byterun/fail.c
new file mode 100644
index 0000000000..7943f9aee1
--- /dev/null
+++ b/byterun/fail.c
@@ -0,0 +1,145 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Raising exceptions from C. */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/io.h"
+#include "caml/gc.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/printexc.h"
+#include "caml/signals.h"
+#include "caml/stacks.h"
+
+CAMLexport struct longjmp_buffer * caml_external_raise = NULL;
+value caml_exn_bucket;
+
+CAMLexport void caml_raise(value v)
+{
+ Unlock_exn();
+ caml_exn_bucket = v;
+ if (caml_external_raise == NULL) caml_fatal_uncaught_exception(v);
+ siglongjmp(caml_external_raise->buf, 1);
+}
+
+CAMLexport void caml_raise_constant(value tag)
+{
+ caml_raise(tag);
+}
+
+CAMLexport void caml_raise_with_arg(value tag, value arg)
+{
+ CAMLparam2 (tag, arg);
+ CAMLlocal1 (bucket);
+
+ bucket = caml_alloc_small (2, 0);
+ Field(bucket, 0) = tag;
+ Field(bucket, 1) = arg;
+ caml_raise(bucket);
+ CAMLnoreturn;
+}
+
+CAMLexport void caml_raise_with_args(value tag, int nargs, value args[])
+{
+ CAMLparam1 (tag);
+ CAMLxparamN (args, nargs);
+ value bucket;
+ int i;
+
+ Assert(1 + nargs <= Max_young_wosize);
+ bucket = caml_alloc_small (1 + nargs, 0);
+ Field(bucket, 0) = tag;
+ for (i = 0; i < nargs; i++) Field(bucket, 1 + i) = args[i];
+ caml_raise(bucket);
+ CAMLnoreturn;
+}
+
+CAMLexport void caml_raise_with_string(value tag, char const *msg)
+{
+ CAMLparam1(tag);
+ value v_msg = caml_copy_string(msg);
+ caml_raise_with_arg(tag, v_msg);
+ CAMLnoreturn;
+}
+
+/* PR#5115: Failure and Invalid_argument can be triggered by
+ input_value while reading the initial value of [caml_global_data]. */
+
+CAMLexport void caml_failwith (char const *msg)
+{
+ if (caml_global_data == 0) {
+ fprintf(stderr, "Fatal error: exception Failure(\"%s\")\n", msg);
+ exit(2);
+ }
+ caml_raise_with_string(Field(caml_global_data, FAILURE_EXN), msg);
+}
+
+CAMLexport void caml_invalid_argument (char const *msg)
+{
+ if (caml_global_data == 0) {
+ fprintf(stderr, "Fatal error: exception Invalid_argument(\"%s\")\n", msg);
+ exit(2);
+ }
+ caml_raise_with_string(Field(caml_global_data, INVALID_EXN), msg);
+}
+
+CAMLexport void caml_array_bound_error(void)
+{
+ caml_invalid_argument("index out of bounds");
+}
+
+CAMLexport void caml_raise_out_of_memory(void)
+{
+ caml_raise_constant(Field(caml_global_data, OUT_OF_MEMORY_EXN));
+}
+
+CAMLexport void caml_raise_stack_overflow(void)
+{
+ caml_raise_constant(Field(caml_global_data, STACK_OVERFLOW_EXN));
+}
+
+CAMLexport void caml_raise_sys_error(value msg)
+{
+ caml_raise_with_arg(Field(caml_global_data, SYS_ERROR_EXN), msg);
+}
+
+CAMLexport void caml_raise_end_of_file(void)
+{
+ caml_raise_constant(Field(caml_global_data, END_OF_FILE_EXN));
+}
+
+CAMLexport void caml_raise_zero_divide(void)
+{
+ caml_raise_constant(Field(caml_global_data, ZERO_DIVIDE_EXN));
+}
+
+CAMLexport void caml_raise_not_found(void)
+{
+ caml_raise_constant(Field(caml_global_data, NOT_FOUND_EXN));
+}
+
+CAMLexport void caml_raise_sys_blocked_io(void)
+{
+ caml_raise_constant(Field(caml_global_data, SYS_BLOCKED_IO));
+}
+
+int caml_is_special_exception(value exn) {
+ return exn == Field(caml_global_data, MATCH_FAILURE_EXN)
+ || exn == Field(caml_global_data, ASSERT_FAILURE_EXN)
+ || exn == Field(caml_global_data, UNDEFINED_RECURSIVE_MODULE_EXN);
+}
diff --git a/byterun/finalise.c b/byterun/finalise.c
new file mode 100644
index 0000000000..79b01bd42f
--- /dev/null
+++ b/byterun/finalise.c
@@ -0,0 +1,255 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Moscova, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Handling of finalised values. */
+
+#include "caml/callback.h"
+#include "caml/fail.h"
+#include "caml/mlvalues.h"
+#include "caml/roots.h"
+#include "caml/signals.h"
+
+struct final {
+ value fun;
+ value val;
+ int offset;
+};
+
+static struct final *final_table = NULL;
+static uintnat old = 0, young = 0, size = 0;
+/* [0..old) : finalisable set
+ [old..young) : recent set
+ [young..size) : free space
+*/
+
+struct to_do {
+ struct to_do *next;
+ int size;
+ struct final item[1]; /* variable size */
+};
+
+static struct to_do *to_do_hd = NULL;
+static struct to_do *to_do_tl = NULL;
+
+/* [size] is a number of elements for the [to_do.item] array */
+static void alloc_to_do (int size)
+{
+ struct to_do *result = malloc (sizeof (struct to_do)
+ + size * sizeof (struct final));
+ if (result == NULL) caml_fatal_error ("out of memory");
+ result->next = NULL;
+ result->size = size;
+ if (to_do_tl == NULL){
+ to_do_hd = result;
+ to_do_tl = result;
+ }else{
+ Assert (to_do_tl->next == NULL);
+ to_do_tl->next = result;
+ to_do_tl = result;
+ }
+}
+
+/* Find white finalisable values, put them in the finalising set, and
+ darken them.
+ The recent set is empty.
+*/
+void caml_final_update (void)
+{
+ uintnat i, j, k;
+ uintnat todo_count = 0;
+
+ Assert (young == old);
+ for (i = 0; i < old; i++){
+ Assert (Is_block (final_table[i].val));
+ Assert (Is_in_heap (final_table[i].val));
+ if (Is_white_val (final_table[i].val)) ++ todo_count;
+ }
+
+ if (todo_count > 0){
+ alloc_to_do (todo_count);
+ j = k = 0;
+ for (i = 0; i < old; i++){
+ again:
+ Assert (Is_block (final_table[i].val));
+ Assert (Is_in_heap (final_table[i].val));
+ if (Is_white_val (final_table[i].val)){
+ if (Tag_val (final_table[i].val) == Forward_tag){
+ value fv;
+ Assert (final_table[i].offset == 0);
+ fv = Forward_val (final_table[i].val);
+ if (Is_block (fv)
+ && (!Is_in_value_area(fv) || Tag_val (fv) == Forward_tag
+ || Tag_val (fv) == Lazy_tag || Tag_val (fv) == Double_tag)){
+ /* Do not short-circuit the pointer. */
+ }else{
+ final_table[i].val = fv;
+ if (Is_block (final_table[i].val)
+ && Is_in_heap (final_table[i].val)){
+ goto again;
+ }
+ }
+ }
+ to_do_tl->item[k++] = final_table[i];
+ }else{
+ final_table[j++] = final_table[i];
+ }
+ }
+ young = old = j;
+ to_do_tl->size = k;
+ for (i = 0; i < k; i++){
+ CAMLassert (Is_white_val (to_do_tl->item[i].val));
+ caml_darken (to_do_tl->item[i].val, NULL);
+ }
+ }
+}
+
+static int running_finalisation_function = 0;
+
+/* Call the finalisation functions for the finalising set.
+ Note that this function must be reentrant.
+*/
+void caml_final_do_calls (void)
+{
+ struct final f;
+ value res;
+
+ if (running_finalisation_function) return;
+
+ if (to_do_hd != NULL){
+ if (caml_finalise_begin_hook != NULL) (*caml_finalise_begin_hook) ();
+ caml_gc_message (0x80, "Calling finalisation functions.\n", 0);
+ while (1){
+ while (to_do_hd != NULL && to_do_hd->size == 0){
+ struct to_do *next_hd = to_do_hd->next;
+ free (to_do_hd);
+ to_do_hd = next_hd;
+ if (to_do_hd == NULL) to_do_tl = NULL;
+ }
+ if (to_do_hd == NULL) break;
+ Assert (to_do_hd->size > 0);
+ -- to_do_hd->size;
+ f = to_do_hd->item[to_do_hd->size];
+ running_finalisation_function = 1;
+ res = caml_callback_exn (f.fun, f.val + f.offset);
+ running_finalisation_function = 0;
+ if (Is_exception_result (res)) caml_raise (Extract_exception (res));
+ }
+ caml_gc_message (0x80, "Done calling finalisation functions.\n", 0);
+ if (caml_finalise_end_hook != NULL) (*caml_finalise_end_hook) ();
+ }
+}
+
+/* Call a scanning_action [f] on [x]. */
+#define Call_action(f,x) (*(f)) ((x), &(x))
+
+/* Call [*f] on the closures of the finalisable set and
+ the closures and values of the finalising set.
+ The recent set is empty.
+ This is called by the major GC and the compactor
+ through [caml_darken_all_roots].
+*/
+void caml_final_do_strong_roots (scanning_action f)
+{
+ uintnat i;
+ struct to_do *todo;
+
+ Assert (old == young);
+ for (i = 0; i < old; i++) Call_action (f, final_table[i].fun);
+
+ for (todo = to_do_hd; todo != NULL; todo = todo->next){
+ for (i = 0; i < todo->size; i++){
+ Call_action (f, todo->item[i].fun);
+ Call_action (f, todo->item[i].val);
+ }
+ }
+}
+
+/* Call [*f] on the values of the finalisable set.
+ The recent set is empty.
+ This is called directly by the compactor.
+*/
+void caml_final_do_weak_roots (scanning_action f)
+{
+ uintnat i;
+
+ Assert (old == young);
+ for (i = 0; i < old; i++) Call_action (f, final_table[i].val);
+}
+
+/* Call [*f] on the closures and values of the recent set.
+ This is called by the minor GC through [caml_oldify_local_roots].
+*/
+void caml_final_do_young_roots (scanning_action f)
+{
+ uintnat i;
+
+ Assert (old <= young);
+ for (i = old; i < young; i++){
+ Call_action (f, final_table[i].fun);
+ Call_action (f, final_table[i].val);
+ }
+}
+
+/* Empty the recent set into the finalisable set.
+ This is called at the end of each minor collection.
+ The minor heap must be empty when this is called.
+*/
+void caml_final_empty_young (void)
+{
+ old = young;
+}
+
+/* Put (f,v) in the recent set. */
+CAMLprim value caml_final_register (value f, value v)
+{
+ if (!Is_block (v)
+ || !Is_in_heap_or_young(v)
+ || Tag_val (v) == Lazy_tag
+ || Tag_val (v) == Double_tag) {
+ caml_invalid_argument ("Gc.finalise");
+ }
+ Assert (old <= young);
+
+ if (young >= size){
+ if (final_table == NULL){
+ uintnat new_size = 30;
+ final_table = caml_stat_alloc (new_size * sizeof (struct final));
+ Assert (old == 0);
+ Assert (young == 0);
+ size = new_size;
+ }else{
+ uintnat new_size = size * 2;
+ final_table = caml_stat_resize (final_table,
+ new_size * sizeof (struct final));
+ size = new_size;
+ }
+ }
+ Assert (young < size);
+ final_table[young].fun = f;
+ if (Tag_val (v) == Infix_tag){
+ final_table[young].offset = Infix_offset_val (v);
+ final_table[young].val = v - Infix_offset_val (v);
+ }else{
+ final_table[young].offset = 0;
+ final_table[young].val = v;
+ }
+ ++ young;
+
+ return Val_unit;
+}
+
+CAMLprim value caml_final_release (value unit)
+{
+ running_finalisation_function = 0;
+ return Val_unit;
+}
diff --git a/byterun/fix_code.c b/byterun/fix_code.c
new file mode 100644
index 0000000000..99a400cb83
--- /dev/null
+++ b/byterun/fix_code.c
@@ -0,0 +1,188 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Handling of blocks of bytecode (endianness switch, threading). */
+
+#include "caml/config.h"
+
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+
+#include "caml/debugger.h"
+#include "caml/fix_code.h"
+#include "caml/instruct.h"
+#include "caml/intext.h"
+#include "caml/md5.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/reverse.h"
+
+code_t caml_start_code;
+asize_t caml_code_size;
+unsigned char * caml_saved_code;
+
+/* Read the main bytecode block from a file */
+
+void caml_init_code_fragments() {
+ struct code_fragment * cf;
+ /* Register the code in the table of code fragments */
+ cf = caml_stat_alloc(sizeof(struct code_fragment));
+ cf->code_start = (char *) caml_start_code;
+ cf->code_end = (char *) caml_start_code + caml_code_size;
+ caml_md5_block(cf->digest, caml_start_code, caml_code_size);
+ cf->digest_computed = 1;
+ caml_ext_table_init(&caml_code_fragments_table, 8);
+ caml_ext_table_add(&caml_code_fragments_table, cf);
+}
+
+void caml_load_code(int fd, asize_t len)
+{
+ int i;
+
+ caml_code_size = len;
+ caml_start_code = (code_t) caml_stat_alloc(caml_code_size);
+ if (read(fd, (char *) caml_start_code, caml_code_size) != caml_code_size)
+ caml_fatal_error("Fatal error: truncated bytecode file.\n");
+ caml_init_code_fragments();
+ /* Prepare the code for execution */
+#ifdef ARCH_BIG_ENDIAN
+ caml_fixup_endianness(caml_start_code, caml_code_size);
+#endif
+ if (caml_debugger_in_use) {
+ len /= sizeof(opcode_t);
+ caml_saved_code = (unsigned char *) caml_stat_alloc(len);
+ for (i = 0; i < len; i++) caml_saved_code[i] = caml_start_code[i];
+ }
+#ifdef THREADED_CODE
+ /* Better to thread now than at the beginning of [caml_interprete],
+ since the debugger interface needs to perform SET_EVENT requests
+ on the code. */
+ caml_thread_code(caml_start_code, caml_code_size);
+#endif
+}
+
+/* This code is needed only if the processor is big endian */
+
+#ifdef ARCH_BIG_ENDIAN
+
+void caml_fixup_endianness(code_t code, asize_t len)
+{
+ code_t p;
+ len /= sizeof(opcode_t);
+ for (p = code; p < code + len; p++) {
+ Reverse_32(p, p);
+ }
+}
+
+#endif
+
+/* This code is needed only if we're using threaded code */
+
+#ifdef THREADED_CODE
+
+char ** caml_instr_table;
+char * caml_instr_base;
+
+static int* opcode_nargs = NULL;
+int* caml_init_opcode_nargs()
+{
+ if( opcode_nargs == NULL ){
+ int* l = (int*)caml_stat_alloc(sizeof(int) * FIRST_UNIMPLEMENTED_OP);
+ int i;
+
+ for (i = 0; i < FIRST_UNIMPLEMENTED_OP; i++) {
+ l [i] = 0;
+ }
+ /* Instructions with one operand */
+ l[PUSHACC] = l[ACC] = l[POP] = l[ASSIGN] =
+ l[PUSHENVACC] = l[ENVACC] = l[PUSH_RETADDR] = l[APPLY] =
+ l[APPTERM1] = l[APPTERM2] = l[APPTERM3] = l[RETURN] =
+ l[GRAB] = l[PUSHGETGLOBAL] = l[GETGLOBAL] = l[SETGLOBAL] =
+ l[PUSHATOM] = l[ATOM] = l[MAKEBLOCK1] = l[MAKEBLOCK2] =
+ l[MAKEBLOCK3] = l[MAKEFLOATBLOCK] = l[GETFIELD] =
+ l[GETFLOATFIELD] = l[SETFIELD] = l[SETFLOATFIELD] =
+ l[BRANCH] = l[BRANCHIF] = l[BRANCHIFNOT] = l[PUSHTRAP] =
+ l[C_CALL1] = l[C_CALL2] = l[C_CALL3] = l[C_CALL4] = l[C_CALL5] =
+ l[CONSTINT] = l[PUSHCONSTINT] = l[OFFSETINT] =
+ l[OFFSETREF] = l[OFFSETCLOSURE] = l[PUSHOFFSETCLOSURE] = 1;
+
+ /* Instructions with two operands */
+ l[APPTERM] = l[CLOSURE] = l[PUSHGETGLOBALFIELD] =
+ l[GETGLOBALFIELD] = l[MAKEBLOCK] = l[C_CALLN] =
+ l[BEQ] = l[BNEQ] = l[BLTINT] = l[BLEINT] = l[BGTINT] = l[BGEINT] =
+ l[BULTINT] = l[BUGEINT] = l[GETPUBMET] = 2;
+
+ opcode_nargs = l;
+ }
+ return opcode_nargs;
+}
+
+void caml_thread_code (code_t code, asize_t len)
+{
+ code_t p;
+ int* l = caml_init_opcode_nargs();
+ len /= sizeof(opcode_t);
+ for (p = code; p < code + len; /*nothing*/) {
+ opcode_t instr = *p;
+ if (instr < 0 || instr >= FIRST_UNIMPLEMENTED_OP){
+ /* FIXME -- should Assert(false) ?
+ caml_fatal_error_arg ("Fatal error in fix_code: bad opcode (%lx)\n",
+ (char *)(long)instr);
+ */
+ instr = STOP;
+ }
+ *p++ = (opcode_t)(caml_instr_table[instr] - caml_instr_base);
+ if (instr == SWITCH) {
+ uint32_t sizes = *p++;
+ uint32_t const_size = sizes & 0xFFFF;
+ uint32_t block_size = sizes >> 16;
+ p += const_size + block_size;
+ } else if (instr == CLOSUREREC) {
+ uint32_t nfuncs = *p++;
+ p++; /* skip nvars */
+ p += nfuncs;
+ } else {
+ p += l[instr];
+ }
+ }
+ Assert(p == code + len);
+}
+
+#else
+
+int* caml_init_opcode_nargs()
+{
+ return NULL;
+}
+
+#endif /* THREADED_CODE */
+
+void caml_set_instruction(code_t pos, opcode_t instr)
+{
+#ifdef THREADED_CODE
+ *pos = (opcode_t)(caml_instr_table[instr] - caml_instr_base);
+#else
+ *pos = instr;
+#endif
+}
+
+int caml_is_instruction(opcode_t instr1, opcode_t instr2)
+{
+#ifdef THREADED_CODE
+ return instr1 == (opcode_t)(caml_instr_table[instr2] - caml_instr_base);
+#else
+ return instr1 == instr2;
+#endif
+}
diff --git a/byterun/floats.c b/byterun/floats.c
new file mode 100644
index 0000000000..ce18c8fb7c
--- /dev/null
+++ b/byterun/floats.c
@@ -0,0 +1,514 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The interface of this file is in "caml/mlvalues.h" and "caml/alloc.h" */
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+#include "caml/misc.h"
+#include "caml/reverse.h"
+#include "caml/stacks.h"
+
+#ifdef _MSC_VER
+#include <float.h>
+#ifndef isnan
+#define isnan _isnan
+#endif
+#ifndef isfinite
+#define isfinite _finite
+#endif
+#endif
+
+#ifdef ARCH_ALIGN_DOUBLE
+
+CAMLexport double caml_Double_val(value val)
+{
+ union { value v[2]; double d; } buffer;
+
+ Assert(sizeof(double) == 2 * sizeof(value));
+ buffer.v[0] = Field(val, 0);
+ buffer.v[1] = Field(val, 1);
+ return buffer.d;
+}
+
+CAMLexport void caml_Store_double_val(value val, double dbl)
+{
+ union { value v[2]; double d; } buffer;
+
+ Assert(sizeof(double) == 2 * sizeof(value));
+ buffer.d = dbl;
+ Field(val, 0) = buffer.v[0];
+ Field(val, 1) = buffer.v[1];
+}
+
+#endif
+
+CAMLexport value caml_copy_double(double d)
+{
+ value res;
+
+#define Setup_for_gc
+#define Restore_after_gc
+ Alloc_small(res, Double_wosize, Double_tag);
+#undef Setup_for_gc
+#undef Restore_after_gc
+ Store_double_val(res, d);
+ return res;
+}
+
+CAMLprim value caml_format_float(value fmt, value arg)
+{
+ value res;
+ double d = Double_val(arg);
+
+#ifdef HAS_BROKEN_PRINTF
+ if (isfinite(d)) {
+#endif
+ res = caml_alloc_sprintf(String_val(fmt), d);
+#ifdef HAS_BROKEN_PRINTF
+ } else {
+ if (isnan(d)) {
+ res = caml_copy_string("nan");
+ } else {
+ if (d > 0)
+ res = caml_copy_string("inf");
+ else
+ res = caml_copy_string("-inf");
+ }
+ }
+#endif
+ return res;
+}
+
+#if 0
+/*CAMLprim*/ value caml_float_of_substring(value vs, value idx, value l)
+{
+ char parse_buffer[64];
+ char * buf, * src, * dst, * end;
+ mlsize_t len, lenvs;
+ double d;
+ intnat flen = Long_val(l);
+ intnat fidx = Long_val(idx);
+
+ lenvs = caml_string_length(vs);
+ len =
+ fidx >= 0 && fidx < lenvs && flen > 0 && flen <= lenvs - fidx
+ ? flen : 0;
+ buf = len < sizeof(parse_buffer) ? parse_buffer : caml_stat_alloc(len + 1);
+ src = String_val(vs) + fidx;
+ dst = buf;
+ while (len--) {
+ char c = *src++;
+ if (c != '_') *dst++ = c;
+ }
+ *dst = 0;
+ if (dst == buf) goto error;
+ d = strtod((const char *) buf, &end);
+ if (end != dst) goto error;
+ if (buf != parse_buffer) caml_stat_free(buf);
+ return caml_copy_double(d);
+ error:
+ if (buf != parse_buffer) caml_stat_free(buf);
+ caml_failwith("float_of_string");
+}
+#endif
+
+CAMLprim value caml_float_of_string(value vs)
+{
+ char parse_buffer[64];
+ char * buf, * src, * dst, * end;
+ mlsize_t len;
+ double d;
+
+ len = caml_string_length(vs);
+ buf = len < sizeof(parse_buffer) ? parse_buffer : caml_stat_alloc(len + 1);
+ src = String_val(vs);
+ dst = buf;
+ while (len--) {
+ char c = *src++;
+ if (c != '_') *dst++ = c;
+ }
+ *dst = 0;
+ if (dst == buf) goto error;
+ d = strtod((const char *) buf, &end);
+ if (end != dst) goto error;
+ if (buf != parse_buffer) caml_stat_free(buf);
+ return caml_copy_double(d);
+ error:
+ if (buf != parse_buffer) caml_stat_free(buf);
+ caml_failwith("float_of_string");
+ return Val_unit; /* not reached */
+}
+
+CAMLprim value caml_int_of_float(value f)
+{
+ return Val_long((intnat) Double_val(f));
+}
+
+CAMLprim value caml_float_of_int(value n)
+{
+ return caml_copy_double((double) Long_val(n));
+}
+
+CAMLprim value caml_neg_float(value f)
+{
+ return caml_copy_double(- Double_val(f));
+}
+
+CAMLprim value caml_abs_float(value f)
+{
+ return caml_copy_double(fabs(Double_val(f)));
+}
+
+CAMLprim value caml_add_float(value f, value g)
+{
+ return caml_copy_double(Double_val(f) + Double_val(g));
+}
+
+CAMLprim value caml_sub_float(value f, value g)
+{
+ return caml_copy_double(Double_val(f) - Double_val(g));
+}
+
+CAMLprim value caml_mul_float(value f, value g)
+{
+ return caml_copy_double(Double_val(f) * Double_val(g));
+}
+
+CAMLprim value caml_div_float(value f, value g)
+{
+ return caml_copy_double(Double_val(f) / Double_val(g));
+}
+
+CAMLprim value caml_exp_float(value f)
+{
+ return caml_copy_double(exp(Double_val(f)));
+}
+
+CAMLprim value caml_floor_float(value f)
+{
+ return caml_copy_double(floor(Double_val(f)));
+}
+
+CAMLprim value caml_fmod_float(value f1, value f2)
+{
+ return caml_copy_double(fmod(Double_val(f1), Double_val(f2)));
+}
+
+CAMLprim value caml_frexp_float(value f)
+{
+ CAMLparam1 (f);
+ CAMLlocal2 (res, mantissa);
+ int exponent;
+
+ mantissa = caml_copy_double(frexp (Double_val(f), &exponent));
+ res = caml_alloc_tuple(2);
+ Field(res, 0) = mantissa;
+ Field(res, 1) = Val_int(exponent);
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_ldexp_float(value f, value i)
+{
+ return caml_copy_double(ldexp(Double_val(f), Int_val(i)));
+}
+
+CAMLprim value caml_log_float(value f)
+{
+ return caml_copy_double(log(Double_val(f)));
+}
+
+CAMLprim value caml_log10_float(value f)
+{
+ return caml_copy_double(log10(Double_val(f)));
+}
+
+CAMLprim value caml_modf_float(value f)
+{
+ double frem;
+
+ CAMLparam1 (f);
+ CAMLlocal3 (res, quo, rem);
+
+ quo = caml_copy_double(modf (Double_val(f), &frem));
+ rem = caml_copy_double(frem);
+ res = caml_alloc_tuple(2);
+ Field(res, 0) = quo;
+ Field(res, 1) = rem;
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_sqrt_float(value f)
+{
+ return caml_copy_double(sqrt(Double_val(f)));
+}
+
+CAMLprim value caml_power_float(value f, value g)
+{
+ return caml_copy_double(pow(Double_val(f), Double_val(g)));
+}
+
+CAMLprim value caml_sin_float(value f)
+{
+ return caml_copy_double(sin(Double_val(f)));
+}
+
+CAMLprim value caml_sinh_float(value f)
+{
+ return caml_copy_double(sinh(Double_val(f)));
+}
+
+CAMLprim value caml_cos_float(value f)
+{
+ return caml_copy_double(cos(Double_val(f)));
+}
+
+CAMLprim value caml_cosh_float(value f)
+{
+ return caml_copy_double(cosh(Double_val(f)));
+}
+
+CAMLprim value caml_tan_float(value f)
+{
+ return caml_copy_double(tan(Double_val(f)));
+}
+
+CAMLprim value caml_tanh_float(value f)
+{
+ return caml_copy_double(tanh(Double_val(f)));
+}
+
+CAMLprim value caml_asin_float(value f)
+{
+ return caml_copy_double(asin(Double_val(f)));
+}
+
+CAMLprim value caml_acos_float(value f)
+{
+ return caml_copy_double(acos(Double_val(f)));
+}
+
+CAMLprim value caml_atan_float(value f)
+{
+ return caml_copy_double(atan(Double_val(f)));
+}
+
+CAMLprim value caml_atan2_float(value f, value g)
+{
+ return caml_copy_double(atan2(Double_val(f), Double_val(g)));
+}
+
+CAMLprim value caml_ceil_float(value f)
+{
+ return caml_copy_double(ceil(Double_val(f)));
+}
+
+CAMLexport double caml_hypot(double x, double y)
+{
+#ifdef HAS_C99_FLOAT_OPS
+ return hypot(x, y);
+#else
+ double tmp, ratio;
+ if (x != x) return x; /* NaN */
+ if (y != y) return y; /* NaN */
+ x = fabs(x); y = fabs(y);
+ if (x < y) { tmp = x; x = y; y = tmp; }
+ if (x == 0.0) return 0.0;
+ ratio = y / x;
+ return x * sqrt(1.0 + ratio * ratio);
+#endif
+}
+
+CAMLprim value caml_hypot_float(value f, value g)
+{
+ return caml_copy_double(caml_hypot(Double_val(f), Double_val(g)));
+}
+
+/* These emulations of expm1() and log1p() are due to William Kahan.
+ See http://www.plunk.org/~hatch/rightway.php */
+CAMLexport double caml_expm1(double x)
+{
+#ifdef HAS_C99_FLOAT_OPS
+ return expm1(x);
+#else
+ double u = exp(x);
+ if (u == 1.)
+ return x;
+ if (u - 1. == -1.)
+ return -1.;
+ return (u - 1.) * x / log(u);
+#endif
+}
+
+CAMLexport double caml_log1p(double x)
+{
+#ifdef HAS_C99_FLOAT_OPS
+ return log1p(x);
+#else
+ double u = 1. + x;
+ if (u == 1.)
+ return x;
+ else
+ return log(u) * x / (u - 1.);
+#endif
+}
+
+CAMLprim value caml_expm1_float(value f)
+{
+ return caml_copy_double(caml_expm1(Double_val(f)));
+}
+
+CAMLprim value caml_log1p_float(value f)
+{
+ return caml_copy_double(caml_log1p(Double_val(f)));
+}
+
+union double_as_two_int32 {
+ double d;
+#if defined(ARCH_BIG_ENDIAN) || (defined(__arm__) && !defined(__ARM_EABI__))
+ struct { uint32_t h; uint32_t l; } i;
+#else
+ struct { uint32_t l; uint32_t h; } i;
+#endif
+};
+
+CAMLexport double caml_copysign(double x, double y)
+{
+#ifdef HAS_C99_FLOAT_OPS
+ return copysign(x, y);
+#else
+ union double_as_two_int32 ux, uy;
+ ux.d = x;
+ uy.d = y;
+ ux.i.h &= 0x7FFFFFFFU;
+ ux.i.h |= (uy.i.h & 0x80000000U);
+ return ux.d;
+#endif
+}
+
+CAMLprim value caml_copysign_float(value f, value g)
+{
+ return caml_copy_double(caml_copysign(Double_val(f), Double_val(g)));
+}
+
+CAMLprim value caml_eq_float(value f, value g)
+{
+ return Val_bool(Double_val(f) == Double_val(g));
+}
+
+CAMLprim value caml_neq_float(value f, value g)
+{
+ return Val_bool(Double_val(f) != Double_val(g));
+}
+
+CAMLprim value caml_le_float(value f, value g)
+{
+ return Val_bool(Double_val(f) <= Double_val(g));
+}
+
+CAMLprim value caml_lt_float(value f, value g)
+{
+ return Val_bool(Double_val(f) < Double_val(g));
+}
+
+CAMLprim value caml_ge_float(value f, value g)
+{
+ return Val_bool(Double_val(f) >= Double_val(g));
+}
+
+CAMLprim value caml_gt_float(value f, value g)
+{
+ return Val_bool(Double_val(f) > Double_val(g));
+}
+
+CAMLprim value caml_float_compare(value vf, value vg)
+{
+ double f = Double_val(vf);
+ double g = Double_val(vg);
+ if (f == g) return Val_int(0);
+ if (f < g) return Val_int(-1);
+ if (f > g) return Val_int(1);
+ /* One or both of f and g is NaN. Order according to the
+ convention NaN = NaN and NaN < x for all other floats x. */
+ if (f == f) return Val_int(1); /* f is not NaN, g is NaN */
+ if (g == g) return Val_int(-1); /* g is not NaN, f is NaN */
+ return Val_int(0); /* both f and g are NaN */
+}
+
+enum { FP_normal, FP_subnormal, FP_zero, FP_infinite, FP_nan };
+
+CAMLprim value caml_classify_float(value vd)
+{
+ /* Cygwin 1.3 has problems with fpclassify (PR#1293), so don't use it */
+ /* FIXME Cygwin 1.3 is ancient! Revisit this decision. */
+#if defined(fpclassify) && !defined(__CYGWIN__) && !defined(__MINGW32__)
+ switch (fpclassify(Double_val(vd))) {
+ case FP_NAN:
+ return Val_int(FP_nan);
+ case FP_INFINITE:
+ return Val_int(FP_infinite);
+ case FP_ZERO:
+ return Val_int(FP_zero);
+ case FP_SUBNORMAL:
+ return Val_int(FP_subnormal);
+ default: /* case FP_NORMAL */
+ return Val_int(FP_normal);
+ }
+#else
+ union double_as_two_int32 u;
+ uint32_t h, l;
+
+ u.d = Double_val(vd);
+ h = u.i.h; l = u.i.l;
+ l = l | (h & 0xFFFFF);
+ h = h & 0x7FF00000;
+ if ((h | l) == 0)
+ return Val_int(FP_zero);
+ if (h == 0)
+ return Val_int(FP_subnormal);
+ if (h == 0x7FF00000) {
+ if (l == 0)
+ return Val_int(FP_infinite);
+ else
+ return Val_int(FP_nan);
+ }
+ return Val_int(FP_normal);
+#endif
+}
+
+/* The [caml_init_ieee_float] function should initialize floating-point hardware
+ so that it behaves as much as possible like the IEEE standard.
+ In particular, return special numbers like Infinity and NaN instead
+ of signalling exceptions. Currently, everyone is in IEEE mode
+ at program startup, except FreeBSD prior to 4.0R. */
+
+#ifdef __FreeBSD__
+#include <osreldate.h>
+#if (__FreeBSD_version < 400017)
+#include <floatingpoint.h>
+#endif
+#endif
+
+void caml_init_ieee_floats(void)
+{
+#if defined(__FreeBSD__) && (__FreeBSD_version < 400017)
+ fpsetmask(0);
+#endif
+}
diff --git a/byterun/freelist.c b/byterun/freelist.c
new file mode 100644
index 0000000000..176b6f846e
--- /dev/null
+++ b/byterun/freelist.c
@@ -0,0 +1,558 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#define FREELIST_DEBUG 0
+#if FREELIST_DEBUG
+#include <stdio.h>
+#endif
+
+#include <string.h>
+
+#include "caml/config.h"
+#include "caml/freelist.h"
+#include "caml/gc.h"
+#include "caml/gc_ctrl.h"
+#include "caml/memory.h"
+#include "caml/major_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+
+/* The free-list is kept sorted by increasing addresses.
+ This makes the merging of adjacent free blocks possible.
+ (See [caml_fl_merge_block].)
+*/
+
+/* A free list block is a [value] (integer representing a pointer to the
+ first word after the block's header). The end of the list is NULL. */
+#define Val_NULL ((value) NULL)
+
+/* The sentinel can be located anywhere in memory, but it must not be
+ adjacent to any heap object. */
+static struct {
+ value filler1; /* Make sure the sentinel is never adjacent to any block. */
+ header_t h;
+ value first_field;
+ value filler2; /* Make sure the sentinel is never adjacent to any block. */
+} sentinel = {0, Make_header (0, 0, Caml_blue), Val_NULL, 0};
+
+#define Fl_head (Val_bp (&(sentinel.first_field)))
+static value fl_prev = Fl_head; /* Current allocation pointer. */
+static value fl_last = Val_NULL; /* Last block in the list. Only valid
+ just after [caml_fl_allocate] returns NULL. */
+value caml_fl_merge = Fl_head; /* Current insertion pointer. Managed
+ jointly with [sweep_slice]. */
+asize_t caml_fl_cur_wsz = 0; /* Number of words in the free list,
+ including headers but not fragments. */
+
+#define FLP_MAX 1000
+static value flp [FLP_MAX];
+static int flp_size = 0;
+static value beyond = Val_NULL;
+
+#define Next(b) (Field (b, 0))
+
+#define Policy_next_fit 0
+#define Policy_first_fit 1
+uintnat caml_allocation_policy = Policy_next_fit;
+#define policy caml_allocation_policy
+
+#ifdef DEBUG
+static void fl_check (void)
+{
+ value cur, prev;
+ int prev_found = 0, flp_found = 0, merge_found = 0;
+ uintnat size_found = 0;
+ int sz = 0;
+
+ prev = Fl_head;
+ cur = Next (prev);
+ while (cur != Val_NULL){
+ size_found += Whsize_bp (cur);
+ Assert (Is_in_heap (cur));
+ if (cur == fl_prev) prev_found = 1;
+ if (policy == Policy_first_fit && Wosize_bp (cur) > sz){
+ sz = Wosize_bp (cur);
+ if (flp_found < flp_size){
+ Assert (Next (flp[flp_found]) == cur);
+ ++ flp_found;
+ }else{
+ Assert (beyond == Val_NULL || cur >= Next (beyond));
+ }
+ }
+ if (cur == caml_fl_merge) merge_found = 1;
+ prev = cur;
+ cur = Next (prev);
+ }
+ if (policy == Policy_next_fit) Assert (prev_found || fl_prev == Fl_head);
+ if (policy == Policy_first_fit) Assert (flp_found == flp_size);
+ Assert (merge_found || caml_fl_merge == Fl_head);
+ Assert (size_found == caml_fl_cur_wsz);
+}
+
+#endif
+
+/* [allocate_block] is called by [caml_fl_allocate]. Given a suitable free
+ block and the requested size, it allocates a new block from the free
+ block. There are three cases:
+ 0. The free block has the requested size. Detach the block from the
+ free-list and return it.
+ 1. The free block is 1 word longer than the requested size. Detach
+ the block from the free list. The remaining word cannot be linked:
+ turn it into an empty block (header only), and return the rest.
+ 2. The free block is large enough. Split it in two and return the right
+ block.
+ In all cases, the allocated block is right-justified in the free block:
+ it is located in the high-address words of the free block, so that
+ the linking of the free-list does not change in case 2.
+*/
+static header_t *allocate_block (mlsize_t wh_sz, int flpi, value prev,
+ value cur)
+{
+ header_t h = Hd_bp (cur);
+ Assert (Whsize_hd (h) >= wh_sz);
+ if (Wosize_hd (h) < wh_sz + 1){ /* Cases 0 and 1. */
+ caml_fl_cur_wsz -= Whsize_hd (h);
+ Next (prev) = Next (cur);
+ Assert (Is_in_heap (Next (prev)) || Next (prev) == Val_NULL);
+ if (caml_fl_merge == cur) caml_fl_merge = prev;
+#ifdef DEBUG
+ fl_last = Val_NULL;
+#endif
+ /* In case 1, the following creates the empty block correctly.
+ In case 0, it gives an invalid header to the block. The function
+ calling [caml_fl_allocate] will overwrite it. */
+ Hd_op (cur) = Make_header (0, 0, Caml_white);
+ if (policy == Policy_first_fit){
+ if (flpi + 1 < flp_size && flp[flpi + 1] == cur){
+ flp[flpi + 1] = prev;
+ }else if (flpi == flp_size - 1){
+ beyond = (prev == Fl_head) ? Val_NULL : prev;
+ -- flp_size;
+ }
+ }
+ }else{ /* Case 2. */
+ caml_fl_cur_wsz -= wh_sz;
+ Hd_op (cur) = Make_header (Wosize_hd (h) - wh_sz, 0, Caml_blue);
+ }
+ if (policy == Policy_next_fit) fl_prev = prev;
+ return (header_t *) &Field (cur, Wosize_hd (h) - wh_sz);
+}
+
+/* [caml_fl_allocate] does not set the header of the newly allocated block.
+ The calling function must do it before any GC function gets called.
+ [caml_fl_allocate] returns a head pointer.
+*/
+header_t *caml_fl_allocate (mlsize_t wo_sz)
+{
+ value cur = Val_NULL, prev;
+ header_t *result;
+ int i;
+ mlsize_t sz, prevsz;
+ Assert (sizeof (char *) == sizeof (value));
+ Assert (wo_sz >= 1);
+ switch (policy){
+ case Policy_next_fit:
+ Assert (fl_prev != Val_NULL);
+ /* Search from [fl_prev] to the end of the list. */
+ prev = fl_prev;
+ cur = Next (prev);
+ while (cur != Val_NULL){ Assert (Is_in_heap (cur));
+ if (Wosize_bp (cur) >= wo_sz){
+ return allocate_block (Whsize_wosize (wo_sz), 0, prev, cur);
+ }
+ prev = cur;
+ cur = Next (prev);
+ }
+ fl_last = prev;
+ /* Search from the start of the list to [fl_prev]. */
+ prev = Fl_head;
+ cur = Next (prev);
+ while (prev != fl_prev){
+ if (Wosize_bp (cur) >= wo_sz){
+ return allocate_block (Whsize_wosize (wo_sz), 0, prev, cur);
+ }
+ prev = cur;
+ cur = Next (prev);
+ }
+ /* No suitable block was found. */
+ return NULL;
+ break;
+
+ case Policy_first_fit: {
+ /* Search in the flp array. */
+ for (i = 0; i < flp_size; i++){
+ sz = Wosize_bp (Next (flp[i]));
+ if (sz >= wo_sz){
+#if FREELIST_DEBUG
+ if (i > 5) fprintf (stderr, "FLP: found at %d size=%d\n", i, wo_sz);
+#endif
+ result = allocate_block (Whsize_wosize (wo_sz), i, flp[i],
+ Next (flp[i]));
+ goto update_flp;
+ }
+ }
+ /* Extend the flp array. */
+ if (flp_size == 0){
+ prev = Fl_head;
+ prevsz = 0;
+ }else{
+ prev = Next (flp[flp_size - 1]);
+ prevsz = Wosize_bp (prev);
+ if (beyond != Val_NULL) prev = beyond;
+ }
+ while (flp_size < FLP_MAX){
+ cur = Next (prev);
+ if (cur == Val_NULL){
+ fl_last = prev;
+ beyond = (prev == Fl_head) ? Val_NULL : prev;
+ return NULL;
+ }else{
+ sz = Wosize_bp (cur);
+ if (sz > prevsz){
+ flp[flp_size] = prev;
+ ++ flp_size;
+ if (sz >= wo_sz){
+ beyond = cur;
+ i = flp_size - 1;
+#if FREELIST_DEBUG
+ if (flp_size > 5){
+ fprintf (stderr, "FLP: extended to %d\n", flp_size);
+ }
+#endif
+ result = allocate_block (Whsize_wosize (wo_sz), flp_size - 1, prev,
+ cur);
+ goto update_flp;
+ }
+ prevsz = sz;
+ }
+ }
+ prev = cur;
+ }
+ beyond = cur;
+
+ /* The flp table is full. Do a slow first-fit search. */
+#if FREELIST_DEBUG
+ fprintf (stderr, "FLP: table is full -- slow first-fit\n");
+#endif
+ if (beyond != Val_NULL){
+ prev = beyond;
+ }else{
+ prev = flp[flp_size - 1];
+ }
+ prevsz = Wosize_bp (Next (flp[FLP_MAX-1]));
+ Assert (prevsz < wo_sz);
+ cur = Next (prev);
+ while (cur != Val_NULL){
+ Assert (Is_in_heap (cur));
+ sz = Wosize_bp (cur);
+ if (sz < prevsz){
+ beyond = cur;
+ }else if (sz >= wo_sz){
+ return allocate_block (Whsize_wosize (wo_sz), flp_size, prev, cur);
+ }
+ prev = cur;
+ cur = Next (prev);
+ }
+ fl_last = prev;
+ return NULL;
+
+ update_flp: /* (i, sz) */
+ /* The block at [i] was removed or reduced. Update the table. */
+ Assert (0 <= i && i < flp_size + 1);
+ if (i < flp_size){
+ if (i > 0){
+ prevsz = Wosize_bp (Next (flp[i-1]));
+ }else{
+ prevsz = 0;
+ }
+ if (i == flp_size - 1){
+ if (Wosize_bp (Next (flp[i])) <= prevsz){
+ beyond = Next (flp[i]);
+ -- flp_size;
+ }else{
+ beyond = Val_NULL;
+ }
+ }else{
+ value buf [FLP_MAX];
+ int j = 0;
+ mlsize_t oldsz = sz;
+
+ prev = flp[i];
+ while (prev != flp[i+1]){
+ cur = Next (prev);
+ sz = Wosize_bp (cur);
+ if (sz > prevsz){
+ buf[j++] = prev;
+ prevsz = sz;
+ if (sz >= oldsz){
+ Assert (sz == oldsz);
+ break;
+ }
+ }
+ prev = cur;
+ }
+#if FREELIST_DEBUG
+ if (j > 2) fprintf (stderr, "FLP: update; buf size = %d\n", j);
+#endif
+ if (FLP_MAX >= flp_size + j - 1){
+ if (j != 1){
+ memmove (&flp[i+j], &flp[i+1], sizeof (value) * (flp_size-i-1));
+ }
+ if (j > 0) memmove (&flp[i], &buf[0], sizeof (value) * j);
+ flp_size += j - 1;
+ }else{
+ if (FLP_MAX > i + j){
+ if (j != 1){
+ memmove (&flp[i+j], &flp[i+1], sizeof (value) * (FLP_MAX-i-j));
+ }
+ if (j > 0) memmove (&flp[i], &buf[0], sizeof (value) * j);
+ }else{
+ if (i != FLP_MAX){
+ memmove (&flp[i], &buf[0], sizeof (value) * (FLP_MAX - i));
+ }
+ }
+ flp_size = FLP_MAX - 1;
+ beyond = Next (flp[FLP_MAX - 1]);
+ }
+ }
+ }
+ return result;
+ }
+ break;
+
+ default:
+ Assert (0); /* unknown policy */
+ break;
+ }
+ return NULL; /* NOT REACHED */
+}
+
+/* Location of the last fragment seen by the sweeping code.
+ This is a pointer to the first word after the fragment, which is
+ the header of the next block.
+ Note that [last_fragment] doesn't point to the fragment itself,
+ but to the block after it.
+*/
+static header_t *last_fragment;
+
+void caml_fl_init_merge (void)
+{
+ last_fragment = NULL;
+ caml_fl_merge = Fl_head;
+#ifdef DEBUG
+ fl_check ();
+#endif
+}
+
+static void truncate_flp (value changed)
+{
+ if (changed == Fl_head){
+ flp_size = 0;
+ beyond = Val_NULL;
+ }else{
+ while (flp_size > 0 && Next (flp[flp_size - 1]) >= changed)
+ -- flp_size;
+ if (beyond >= changed) beyond = Val_NULL;
+ }
+}
+
+/* This is called by caml_compact_heap. */
+void caml_fl_reset (void)
+{
+ Next (Fl_head) = Val_NULL;
+ switch (policy){
+ case Policy_next_fit:
+ fl_prev = Fl_head;
+ break;
+ case Policy_first_fit:
+ truncate_flp (Fl_head);
+ break;
+ default:
+ Assert (0);
+ break;
+ }
+ caml_fl_cur_wsz = 0;
+ caml_fl_init_merge ();
+}
+
+/* [caml_fl_merge_block] returns the head pointer of the next block after [bp],
+ because merging blocks may change the size of [bp]. */
+header_t *caml_fl_merge_block (value bp)
+{
+ value prev, cur;
+ header_t *adj;
+ header_t hd = Hd_val (bp);
+ mlsize_t prev_wosz;
+
+ caml_fl_cur_wsz += Whsize_hd (hd);
+
+#ifdef DEBUG
+ caml_set_fields (bp, 0, Debug_free_major);
+#endif
+ prev = caml_fl_merge;
+ cur = Next (prev);
+ /* The sweep code makes sure that this is the right place to insert
+ this block: */
+ Assert (prev < bp || prev == Fl_head);
+ Assert (cur > bp || cur == Val_NULL);
+
+ if (policy == Policy_first_fit) truncate_flp (prev);
+
+ /* If [last_fragment] and [bp] are adjacent, merge them. */
+ if (last_fragment == Hp_bp (bp)){
+ mlsize_t bp_whsz = Whsize_val (bp);
+ if (bp_whsz <= Max_wosize){
+ hd = Make_header (bp_whsz, 0, Caml_white);
+ bp = (value) last_fragment;
+ Hd_val (bp) = hd;
+ caml_fl_cur_wsz += Whsize_wosize (0);
+ }
+ }
+
+ /* If [bp] and [cur] are adjacent, remove [cur] from the free-list
+ and merge them. */
+ adj = (header_t *) &Field (bp, Wosize_hd (hd));
+ if (adj == Hp_val (cur)){
+ value next_cur = Next (cur);
+ mlsize_t cur_whsz = Whsize_val (cur);
+
+ if (Wosize_hd (hd) + cur_whsz <= Max_wosize){
+ Next (prev) = next_cur;
+ if (policy == Policy_next_fit && fl_prev == cur) fl_prev = prev;
+ hd = Make_header (Wosize_hd (hd) + cur_whsz, 0, Caml_blue);
+ Hd_val (bp) = hd;
+ adj = (header_t *) &Field (bp, Wosize_hd (hd));
+#ifdef DEBUG
+ fl_last = Val_NULL;
+ Next (cur) = (value) Debug_free_major;
+ Hd_val (cur) = Debug_free_major;
+#endif
+ cur = next_cur;
+ }
+ }
+ /* If [prev] and [bp] are adjacent merge them, else insert [bp] into
+ the free-list if it is big enough. */
+ prev_wosz = Wosize_val (prev);
+ if ((header_t *) &Field (prev, prev_wosz) == Hp_val (bp)
+ && prev_wosz + Whsize_hd (hd) < Max_wosize){
+ Hd_val (prev) = Make_header (prev_wosz + Whsize_hd (hd), 0,Caml_blue);
+#ifdef DEBUG
+ Hd_val (bp) = Debug_free_major;
+#endif
+ Assert (caml_fl_merge == prev);
+ }else if (Wosize_hd (hd) != 0){
+ Hd_val (bp) = Bluehd_hd (hd);
+ Next (bp) = cur;
+ Next (prev) = bp;
+ caml_fl_merge = bp;
+ }else{
+ /* This is a fragment. Leave it in white but remember it for eventual
+ merging with the next block. */
+ last_fragment = (header_t *) bp;
+ caml_fl_cur_wsz -= Whsize_wosize (0);
+ }
+ return adj;
+}
+
+/* This is a heap extension. We have to insert it in the right place
+ in the free-list.
+ [caml_fl_add_blocks] can only be called right after a call to
+ [caml_fl_allocate] that returned Val_NULL.
+ Most of the heap extensions are expected to be at the end of the
+ free list. (This depends on the implementation of [malloc].)
+
+ [bp] must point to a list of blocks chained by their field 0,
+ terminated by Val_NULL, and field 1 of the first block must point to
+ the last block.
+*/
+void caml_fl_add_blocks (value bp)
+{
+ Assert (fl_last != Val_NULL);
+ Assert (Next (fl_last) == Val_NULL);
+ caml_fl_cur_wsz += Whsize_bp (bp);
+
+ if (bp > fl_last){
+ Next (fl_last) = bp;
+ if (fl_last == caml_fl_merge && (char *) bp < caml_gc_sweep_hp){
+ caml_fl_merge = Field (bp, 1);
+ }
+ if (policy == Policy_first_fit && flp_size < FLP_MAX){
+ flp [flp_size++] = fl_last;
+ }
+ }else{
+ value cur, prev;
+
+ prev = Fl_head;
+ cur = Next (prev);
+ while (cur != Val_NULL && cur < bp){
+ Assert (prev < bp || prev == Fl_head);
+ /* XXX TODO: extend flp on the fly */
+ prev = cur;
+ cur = Next (prev);
+ } Assert (prev < bp || prev == Fl_head);
+ Assert (cur > bp || cur == Val_NULL);
+ Next (Field (bp, 1)) = cur;
+ Next (prev) = bp;
+ /* When inserting blocks between [caml_fl_merge] and [caml_gc_sweep_hp],
+ we must advance [caml_fl_merge] to the new block, so that [caml_fl_merge]
+ is always the last free-list block before [caml_gc_sweep_hp]. */
+ if (prev == caml_fl_merge && (char *) bp < caml_gc_sweep_hp){
+ caml_fl_merge = Field (bp, 1);
+ }
+ if (policy == Policy_first_fit) truncate_flp (bp);
+ }
+}
+
+/* Cut a block of memory into Max_wosize pieces, give them headers,
+ and optionally merge them into the free list.
+ arguments:
+ p: pointer to the first word of the block
+ size: size of the block (in words)
+ do_merge: 1 -> do merge; 0 -> do not merge
+ color: which color to give to the pieces; if [do_merge] is 1, this
+ is overridden by the merge code, but we have historically used
+ [Caml_white].
+*/
+void caml_make_free_blocks (value *p, mlsize_t size, int do_merge, int color)
+{
+ mlsize_t sz;
+
+ while (size > 0){
+ if (size > Whsize_wosize (Max_wosize)){
+ sz = Whsize_wosize (Max_wosize);
+ }else{
+ sz = size;
+ }
+ *(header_t *)p = Make_header (Wosize_whsize (sz), 0, color);
+ if (do_merge) caml_fl_merge_block (Val_hp (p));
+ size -= sz;
+ p += sz;
+ }
+}
+
+void caml_set_allocation_policy (uintnat p)
+{
+ switch (p){
+ case Policy_next_fit:
+ fl_prev = Fl_head;
+ policy = p;
+ break;
+ case Policy_first_fit:
+ flp_size = 0;
+ beyond = Val_NULL;
+ policy = p;
+ break;
+ default:
+ break;
+ }
+}
diff --git a/byterun/gc_ctrl.c b/byterun/gc_ctrl.c
new file mode 100644
index 0000000000..868f883cfa
--- /dev/null
+++ b/byterun/gc_ctrl.c
@@ -0,0 +1,527 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "caml/alloc.h"
+#include "caml/compact.h"
+#include "caml/custom.h"
+#include "caml/finalise.h"
+#include "caml/freelist.h"
+#include "caml/gc.h"
+#include "caml/gc_ctrl.h"
+#include "caml/major_gc.h"
+#include "caml/minor_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#ifdef NATIVE_CODE
+#include "stack.h"
+#else
+#include "caml/stacks.h"
+#endif
+
+#ifndef NATIVE_CODE
+extern uintnat caml_max_stack_size; /* defined in stacks.c */
+#endif
+
+double caml_stat_minor_words = 0.0,
+ caml_stat_promoted_words = 0.0,
+ caml_stat_major_words = 0.0;
+
+intnat caml_stat_minor_collections = 0,
+ caml_stat_major_collections = 0,
+ caml_stat_heap_wsz = 0,
+ caml_stat_top_heap_wsz = 0,
+ caml_stat_compactions = 0,
+ caml_stat_heap_chunks = 0;
+
+extern uintnat caml_major_heap_increment; /* percent or words; see major_gc.c */
+extern uintnat caml_percent_free; /* see major_gc.c */
+extern uintnat caml_percent_max; /* see compact.c */
+extern uintnat caml_allocation_policy; /* see freelist.c */
+
+#define Next(hp) ((hp) + Whsize_hp (hp))
+
+#ifdef DEBUG
+
+/* Check that [v]'s header looks good. [v] must be a block in the heap. */
+static void check_head (value v)
+{
+ Assert (Is_block (v));
+ Assert (Is_in_heap (v));
+
+ Assert (Wosize_val (v) != 0);
+ Assert (Color_hd (Hd_val (v)) != Caml_blue);
+ Assert (Is_in_heap (v));
+ if (Tag_val (v) == Infix_tag){
+ int offset = Wsize_bsize (Infix_offset_val (v));
+ value trueval = Val_op (&Field (v, -offset));
+ Assert (Tag_val (trueval) == Closure_tag);
+ Assert (Wosize_val (trueval) > offset);
+ Assert (Is_in_heap (&Field (trueval, Wosize_val (trueval) - 1)));
+ }else{
+ Assert (Is_in_heap (&Field (v, Wosize_val (v) - 1)));
+ }
+ if (Tag_val (v) == Double_tag){
+ Assert (Wosize_val (v) == Double_wosize);
+ }else if (Tag_val (v) == Double_array_tag){
+ Assert (Wosize_val (v) % Double_wosize == 0);
+ }
+}
+
+static void check_block (header_t *hp)
+{
+ mlsize_t i;
+ value v = Val_hp (hp);
+ value f;
+
+ check_head (v);
+ switch (Tag_hp (hp)){
+ case Abstract_tag: break;
+ case String_tag:
+ break;
+ case Double_tag:
+ Assert (Wosize_val (v) == Double_wosize);
+ break;
+ case Double_array_tag:
+ Assert (Wosize_val (v) % Double_wosize == 0);
+ break;
+ case Custom_tag:
+ Assert (!Is_in_heap (Custom_ops_val (v)));
+ break;
+
+ case Infix_tag:
+ Assert (0);
+ break;
+
+ default:
+ Assert (Tag_hp (hp) < No_scan_tag);
+ for (i = 0; i < Wosize_hp (hp); i++){
+ f = Field (v, i);
+ if (Is_block (f) && Is_in_heap (f)){
+ check_head (f);
+ Assert (Color_val (f) != Caml_blue);
+ }
+ }
+ }
+}
+
+#endif /* DEBUG */
+
+/* Check the heap structure (if compiled in debug mode) and
+ gather statistics; return the stats if [returnstats] is true,
+ otherwise return [Val_unit].
+*/
+static value heap_stats (int returnstats)
+{
+ CAMLparam0 ();
+ intnat live_words = 0, live_blocks = 0,
+ free_words = 0, free_blocks = 0, largest_free = 0,
+ fragments = 0, heap_chunks = 0;
+ char *chunk = caml_heap_start, *chunk_end;
+ header_t *cur_hp;
+#ifdef DEBUG
+ header_t *prev_hp;
+#endif
+ header_t cur_hd;
+
+#ifdef DEBUG
+ caml_gc_message (-1, "### OCaml runtime: heap check ###\n", 0);
+#endif
+
+ while (chunk != NULL){
+ ++ heap_chunks;
+ chunk_end = chunk + Chunk_size (chunk);
+#ifdef DEBUG
+ prev_hp = NULL;
+#endif
+ cur_hp = (header_t *) chunk;
+ while (cur_hp < (header_t *) chunk_end){
+ cur_hd = Hd_hp (cur_hp);
+ Assert (Next (cur_hp) <= (header_t *) chunk_end);
+ switch (Color_hd (cur_hd)){
+ case Caml_white:
+ if (Wosize_hd (cur_hd) == 0){
+ ++ fragments;
+ Assert (prev_hp == NULL
+ || Color_hp (prev_hp) != Caml_blue
+ || cur_hp == (header_t *) caml_gc_sweep_hp);
+ }else{
+ if (caml_gc_phase == Phase_sweep
+ && cur_hp >= (header_t *) caml_gc_sweep_hp){
+ ++ free_blocks;
+ free_words += Whsize_hd (cur_hd);
+ if (Whsize_hd (cur_hd) > largest_free){
+ largest_free = Whsize_hd (cur_hd);
+ }
+ }else{
+ ++ live_blocks;
+ live_words += Whsize_hd (cur_hd);
+#ifdef DEBUG
+ check_block (cur_hp);
+#endif
+ }
+ }
+ break;
+ case Caml_gray: case Caml_black:
+ Assert (Wosize_hd (cur_hd) > 0);
+ ++ live_blocks;
+ live_words += Whsize_hd (cur_hd);
+#ifdef DEBUG
+ check_block (cur_hp);
+#endif
+ break;
+ case Caml_blue:
+ Assert (Wosize_hd (cur_hd) > 0);
+ ++ free_blocks;
+ free_words += Whsize_hd (cur_hd);
+ if (Whsize_hd (cur_hd) > largest_free){
+ largest_free = Whsize_hd (cur_hd);
+ }
+ /* not true any more with big heap chunks
+ Assert (prev_hp == NULL
+ || (Color_hp (prev_hp) != Caml_blue && Wosize_hp (prev_hp) > 0)
+ || cur_hp == caml_gc_sweep_hp);
+ Assert (Next (cur_hp) == chunk_end
+ || (Color_hp (Next (cur_hp)) != Caml_blue
+ && Wosize_hp (Next (cur_hp)) > 0)
+ || (Whsize_hd (cur_hd) + Wosize_hp (Next (cur_hp)) > Max_wosize)
+ || Next (cur_hp) == caml_gc_sweep_hp);
+ */
+ break;
+ }
+#ifdef DEBUG
+ prev_hp = cur_hp;
+#endif
+ cur_hp = Next (cur_hp);
+ } Assert (cur_hp == (header_t *) chunk_end);
+ chunk = Chunk_next (chunk);
+ }
+
+ Assert (heap_chunks == caml_stat_heap_chunks);
+ Assert (live_words + free_words + fragments == caml_stat_heap_wsz);
+
+ if (returnstats){
+ CAMLlocal1 (res);
+
+ /* get a copy of these before allocating anything... */
+ double minwords = caml_stat_minor_words
+ + (double) (caml_young_end - caml_young_ptr);
+ double prowords = caml_stat_promoted_words;
+ double majwords = caml_stat_major_words + (double) caml_allocated_words;
+ intnat mincoll = caml_stat_minor_collections;
+ intnat majcoll = caml_stat_major_collections;
+ intnat heap_words = caml_stat_heap_wsz;
+ intnat cpct = caml_stat_compactions;
+ intnat top_heap_words = caml_stat_top_heap_wsz;
+
+ res = caml_alloc_tuple (16);
+ Store_field (res, 0, caml_copy_double (minwords));
+ Store_field (res, 1, caml_copy_double (prowords));
+ Store_field (res, 2, caml_copy_double (majwords));
+ Store_field (res, 3, Val_long (mincoll));
+ Store_field (res, 4, Val_long (majcoll));
+ Store_field (res, 5, Val_long (heap_words));
+ Store_field (res, 6, Val_long (heap_chunks));
+ Store_field (res, 7, Val_long (live_words));
+ Store_field (res, 8, Val_long (live_blocks));
+ Store_field (res, 9, Val_long (free_words));
+ Store_field (res, 10, Val_long (free_blocks));
+ Store_field (res, 11, Val_long (largest_free));
+ Store_field (res, 12, Val_long (fragments));
+ Store_field (res, 13, Val_long (cpct));
+ Store_field (res, 14, Val_long (top_heap_words));
+ Store_field (res, 15, Val_long (caml_stack_usage()));
+ CAMLreturn (res);
+ }else{
+ CAMLreturn (Val_unit);
+ }
+}
+
+#ifdef DEBUG
+void caml_heap_check (void)
+{
+ heap_stats (0);
+}
+#endif
+
+CAMLprim value caml_gc_stat(value v)
+{
+ Assert (v == Val_unit);
+ return heap_stats (1);
+}
+
+CAMLprim value caml_gc_quick_stat(value v)
+{
+ CAMLparam0 ();
+ CAMLlocal1 (res);
+
+ /* get a copy of these before allocating anything... */
+ double minwords = caml_stat_minor_words
+ + (double) (caml_young_end - caml_young_ptr);
+ double prowords = caml_stat_promoted_words;
+ double majwords = caml_stat_major_words + (double) caml_allocated_words;
+ intnat mincoll = caml_stat_minor_collections;
+ intnat majcoll = caml_stat_major_collections;
+ intnat heap_words = caml_stat_heap_wsz;
+ intnat top_heap_words = caml_stat_top_heap_wsz;
+ intnat cpct = caml_stat_compactions;
+ intnat heap_chunks = caml_stat_heap_chunks;
+
+ res = caml_alloc_tuple (16);
+ Store_field (res, 0, caml_copy_double (minwords));
+ Store_field (res, 1, caml_copy_double (prowords));
+ Store_field (res, 2, caml_copy_double (majwords));
+ Store_field (res, 3, Val_long (mincoll));
+ Store_field (res, 4, Val_long (majcoll));
+ Store_field (res, 5, Val_long (heap_words));
+ Store_field (res, 6, Val_long (heap_chunks));
+ Store_field (res, 7, Val_long (0));
+ Store_field (res, 8, Val_long (0));
+ Store_field (res, 9, Val_long (0));
+ Store_field (res, 10, Val_long (0));
+ Store_field (res, 11, Val_long (0));
+ Store_field (res, 12, Val_long (0));
+ Store_field (res, 13, Val_long (cpct));
+ Store_field (res, 14, Val_long (top_heap_words));
+ Store_field (res, 15, Val_long (caml_stack_usage()));
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_gc_counters(value v)
+{
+ CAMLparam0 (); /* v is ignored */
+ CAMLlocal1 (res);
+
+ /* get a copy of these before allocating anything... */
+ double minwords = caml_stat_minor_words
+ + (double) (caml_young_end - caml_young_ptr);
+ double prowords = caml_stat_promoted_words;
+ double majwords = caml_stat_major_words + (double) caml_allocated_words;
+
+ res = caml_alloc_tuple (3);
+ Store_field (res, 0, caml_copy_double (minwords));
+ Store_field (res, 1, caml_copy_double (prowords));
+ Store_field (res, 2, caml_copy_double (majwords));
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_gc_get(value v)
+{
+ CAMLparam0 (); /* v is ignored */
+ CAMLlocal1 (res);
+
+ res = caml_alloc_tuple (7);
+ Store_field (res, 0, Val_long (caml_minor_heap_wsz)); /* s */
+ Store_field (res, 1, Val_long (caml_major_heap_increment)); /* i */
+ Store_field (res, 2, Val_long (caml_percent_free)); /* o */
+ Store_field (res, 3, Val_long (caml_verb_gc)); /* v */
+ Store_field (res, 4, Val_long (caml_percent_max)); /* O */
+#ifndef NATIVE_CODE
+ Store_field (res, 5, Val_long (caml_max_stack_size)); /* l */
+#else
+ Store_field (res, 5, Val_long (0));
+#endif
+ Store_field (res, 6, Val_long (caml_allocation_policy)); /* a */
+ CAMLreturn (res);
+}
+
+#define Max(x,y) ((x) < (y) ? (y) : (x))
+
+static uintnat norm_pfree (uintnat p)
+{
+ return Max (p, 1);
+}
+
+static uintnat norm_pmax (uintnat p)
+{
+ return p;
+}
+
+static intnat norm_minsize (intnat s)
+{
+ if (s < Minor_heap_min) s = Minor_heap_min;
+ if (s > Minor_heap_max) s = Minor_heap_max;
+ return s;
+}
+
+CAMLprim value caml_gc_set(value v)
+{
+ uintnat newpf, newpm;
+ asize_t newheapincr;
+ asize_t newminwsz;
+ uintnat oldpolicy;
+
+ caml_verb_gc = Long_val (Field (v, 3));
+
+#ifndef NATIVE_CODE
+ caml_change_max_stack_size (Long_val (Field (v, 5)));
+#endif
+
+ newpf = norm_pfree (Long_val (Field (v, 2)));
+ if (newpf != caml_percent_free){
+ caml_percent_free = newpf;
+ caml_gc_message (0x20, "New space overhead: %d%%\n", caml_percent_free);
+ }
+
+ newpm = norm_pmax (Long_val (Field (v, 4)));
+ if (newpm != caml_percent_max){
+ caml_percent_max = newpm;
+ caml_gc_message (0x20, "New max overhead: %d%%\n", caml_percent_max);
+ }
+
+ newheapincr = Long_val (Field (v, 1));
+ if (newheapincr != caml_major_heap_increment){
+ caml_major_heap_increment = newheapincr;
+ if (newheapincr > 1000){
+ caml_gc_message (0x20, "New heap increment size: %luk words\n",
+ caml_major_heap_increment/1024);
+ }else{
+ caml_gc_message (0x20, "New heap increment size: %lu%%\n",
+ caml_major_heap_increment);
+ }
+ }
+ oldpolicy = caml_allocation_policy;
+ caml_set_allocation_policy (Long_val (Field (v, 6)));
+ if (oldpolicy != caml_allocation_policy){
+ caml_gc_message (0x20, "New allocation policy: %d\n",
+ caml_allocation_policy);
+ }
+
+ /* Minor heap size comes last because it will trigger a minor collection
+ (thus invalidating [v]) and it can raise [Out_of_memory]. */
+ newminwsz = norm_minsize (Long_val (Field (v, 0)));
+ if (newminwsz != caml_minor_heap_wsz){
+ caml_gc_message (0x20, "New minor heap size: %luk words\n",
+ newminwsz / 1024);
+ caml_set_minor_heap_size (Bsize_wsize (newminwsz));
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_gc_minor(value v)
+{ Assert (v == Val_unit);
+ caml_minor_collection ();
+ return Val_unit;
+}
+
+static void test_and_compact (void)
+{
+ float fp;
+
+ fp = 100.0 * caml_fl_cur_wsz / (caml_stat_heap_wsz - caml_fl_cur_wsz);
+ if (fp > 999999.0) fp = 999999.0;
+ caml_gc_message (0x200, "Estimated overhead (lower bound) = %"
+ ARCH_INTNAT_PRINTF_FORMAT "u%%\n",
+ (uintnat) fp);
+ if (fp >= caml_percent_max && caml_stat_heap_chunks > 1){
+ caml_gc_message (0x200, "Automatic compaction triggered.\n", 0);
+ caml_compact_heap ();
+ }
+}
+
+CAMLprim value caml_gc_major(value v)
+{ Assert (v == Val_unit);
+ caml_gc_message (0x1, "Major GC cycle requested\n", 0);
+ caml_empty_minor_heap ();
+ caml_finish_major_cycle ();
+ test_and_compact ();
+ caml_final_do_calls ();
+ return Val_unit;
+}
+
+CAMLprim value caml_gc_full_major(value v)
+{ Assert (v == Val_unit);
+ caml_gc_message (0x1, "Full major GC cycle requested\n", 0);
+ caml_empty_minor_heap ();
+ caml_finish_major_cycle ();
+ caml_final_do_calls ();
+ caml_empty_minor_heap ();
+ caml_finish_major_cycle ();
+ test_and_compact ();
+ caml_final_do_calls ();
+ return Val_unit;
+}
+
+CAMLprim value caml_gc_major_slice (value v)
+{
+ Assert (Is_long (v));
+ caml_empty_minor_heap ();
+ return Val_long (caml_major_collection_slice (Long_val (v)));
+}
+
+CAMLprim value caml_gc_compaction(value v)
+{ Assert (v == Val_unit);
+ caml_gc_message (0x10, "Heap compaction requested\n", 0);
+ caml_empty_minor_heap ();
+ caml_finish_major_cycle ();
+ caml_final_do_calls ();
+ caml_empty_minor_heap ();
+ caml_finish_major_cycle ();
+ caml_compact_heap ();
+ caml_final_do_calls ();
+ return Val_unit;
+}
+
+uintnat caml_normalize_heap_increment (uintnat i)
+{
+ if (i < Bsize_wsize (Heap_chunk_min)){
+ i = Bsize_wsize (Heap_chunk_min);
+ }
+ return ((i + Page_size - 1) >> Page_log) << Page_log;
+}
+
+/* [minor_size] and [major_size] are numbers of words
+ [major_incr] is either a percentage or a number of words */
+void caml_init_gc (uintnat minor_size, uintnat major_size,
+ uintnat major_incr, uintnat percent_fr,
+ uintnat percent_m)
+{
+ uintnat major_heap_size =
+ Bsize_wsize (caml_normalize_heap_increment (major_size));
+
+ if (caml_page_table_initialize(Bsize_wsize(minor_size) + major_heap_size)){
+ caml_fatal_error ("OCaml runtime error: cannot initialize page table\n");
+ }
+ caml_set_minor_heap_size (Bsize_wsize (norm_minsize (minor_size)));
+ caml_major_heap_increment = major_incr;
+ caml_percent_free = norm_pfree (percent_fr);
+ caml_percent_max = norm_pmax (percent_m);
+ caml_init_major_heap (major_heap_size);
+ caml_gc_message (0x20, "Initial minor heap size: %luk words\n",
+ caml_minor_heap_wsz / 1024);
+ caml_gc_message (0x20, "Initial major heap size: %luk bytes\n",
+ major_heap_size / 1024);
+ caml_gc_message (0x20, "Initial space overhead: %lu%%\n", caml_percent_free);
+ caml_gc_message (0x20, "Initial max overhead: %lu%%\n", caml_percent_max);
+ if (caml_major_heap_increment > 1000){
+ caml_gc_message (0x20, "Initial heap increment: %luk words\n",
+ caml_major_heap_increment / 1024);
+ }else{
+ caml_gc_message (0x20, "Initial heap increment: %lu%%\n",
+ caml_major_heap_increment);
+ }
+ caml_gc_message (0x20, "Initial allocation policy: %d\n",
+ caml_allocation_policy);
+}
+
+/* Control runtime warnings */
+
+CAMLprim value caml_ml_enable_runtime_warnings(value vbool)
+{
+ caml_runtime_warnings = Bool_val(vbool);
+ return Val_unit;
+}
+
+CAMLprim value caml_ml_runtime_warnings_enabled(value vbool)
+{
+ return Val_bool(caml_runtime_warnings);
+}
diff --git a/byterun/globroots.c b/byterun/globroots.c
new file mode 100644
index 0000000000..b5031d1f23
--- /dev/null
+++ b/byterun/globroots.c
@@ -0,0 +1,287 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Registration of global memory roots */
+
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/roots.h"
+#include "caml/globroots.h"
+
+/* The sets of global memory roots are represented as skip lists
+ (see William Pugh, "Skip lists: a probabilistic alternative to
+ balanced binary trees", Comm. ACM 33(6), 1990). */
+
+struct global_root {
+ value * root; /* the address of the root */
+ struct global_root * forward[1]; /* variable-length array */
+};
+
+#define NUM_LEVELS 17
+
+struct global_root_list {
+ value * root; /* dummy value for layout compatibility */
+ struct global_root * forward[NUM_LEVELS]; /* forward chaining */
+ int level; /* max used level */
+};
+
+/* Generate a random level for a new node: 0 with probability 3/4,
+ 1 with probability 3/16, 2 with probability 3/64, etc.
+ We use a simple linear congruential PRNG (see Knuth vol 2) instead
+ of random(), because we need exactly 32 bits of pseudo-random data
+ (i.e. 2 * (NUM_LEVELS - 1)). Moreover, the congruential PRNG
+ is faster and guaranteed to be deterministic (to reproduce bugs). */
+
+static uint32_t random_seed = 0;
+
+static int random_level(void)
+{
+ uint32_t r;
+ int level = 0;
+
+ /* Linear congruence with modulus = 2^32, multiplier = 69069
+ (Knuth vol 2 p. 106, line 15 of table 1), additive = 25173. */
+ r = random_seed = random_seed * 69069 + 25173;
+ /* Knuth (vol 2 p. 13) shows that the least significant bits are
+ "less random" than the most significant bits with a modulus of 2^m,
+ so consume most significant bits first */
+ while ((r & 0xC0000000U) == 0xC0000000U) { level++; r = r << 2; }
+ Assert(level < NUM_LEVELS);
+ return level;
+}
+
+/* Insertion in a global root list */
+
+static void caml_insert_global_root(struct global_root_list * rootlist,
+ value * r)
+{
+ struct global_root * update[NUM_LEVELS];
+ struct global_root * e, * f;
+ int i, new_level;
+
+ Assert(0 <= rootlist->level && rootlist->level < NUM_LEVELS);
+
+ /* Init "cursor" to list head */
+ e = (struct global_root *) rootlist;
+ /* Find place to insert new node */
+ for (i = rootlist->level; i >= 0; i--) {
+ while (1) {
+ f = e->forward[i];
+ if (f == NULL || f->root >= r) break;
+ e = f;
+ }
+ update[i] = e;
+ }
+ e = e->forward[0];
+ /* If already present, don't do anything */
+ if (e != NULL && e->root == r) return;
+ /* Insert additional element, updating list level if necessary */
+ new_level = random_level();
+ if (new_level > rootlist->level) {
+ for (i = rootlist->level + 1; i <= new_level; i++)
+ update[i] = (struct global_root *) rootlist;
+ rootlist->level = new_level;
+ }
+ e = caml_stat_alloc(sizeof(struct global_root) +
+ new_level * sizeof(struct global_root *));
+ e->root = r;
+ for (i = 0; i <= new_level; i++) {
+ e->forward[i] = update[i]->forward[i];
+ update[i]->forward[i] = e;
+ }
+}
+
+/* Deletion in a global root list */
+
+static void caml_delete_global_root(struct global_root_list * rootlist,
+ value * r)
+{
+ struct global_root * update[NUM_LEVELS];
+ struct global_root * e, * f;
+ int i;
+
+ Assert(0 <= rootlist->level && rootlist->level < NUM_LEVELS);
+
+ /* Init "cursor" to list head */
+ e = (struct global_root *) rootlist;
+ /* Find element in list */
+ for (i = rootlist->level; i >= 0; i--) {
+ while (1) {
+ f = e->forward[i];
+ if (f == NULL || f->root >= r) break;
+ e = f;
+ }
+ update[i] = e;
+ }
+ e = e->forward[0];
+ /* If not found, nothing to do */
+ if (e == NULL || e->root != r) return;
+ /* Rebuild list without node */
+ for (i = 0; i <= rootlist->level; i++) {
+ if (update[i]->forward[i] == e)
+ update[i]->forward[i] = e->forward[i];
+ }
+ /* Reclaim list element */
+ caml_stat_free(e);
+ /* Down-correct list level */
+ while (rootlist->level > 0 &&
+ rootlist->forward[rootlist->level] == NULL)
+ rootlist->level--;
+}
+
+/* Iterate over a global root list */
+
+static void caml_iterate_global_roots(scanning_action f,
+ struct global_root_list * rootlist)
+{
+ struct global_root * gr;
+
+ for (gr = rootlist->forward[0]; gr != NULL; gr = gr->forward[0]) {
+ f(*(gr->root), gr->root);
+ }
+}
+
+/* Empty a global root list */
+
+static void caml_empty_global_roots(struct global_root_list * rootlist)
+{
+ struct global_root * gr, * next;
+ int i;
+
+ Assert(0 <= rootlist->level && rootlist->level < NUM_LEVELS);
+
+ for (gr = rootlist->forward[0]; gr != NULL; /**/) {
+ next = gr->forward[0];
+ caml_stat_free(gr);
+ gr = next;
+ }
+ for (i = 0; i <= rootlist->level; i++) rootlist->forward[i] = NULL;
+ rootlist->level = 0;
+}
+
+/* The three global root lists */
+
+struct global_root_list caml_global_roots = { NULL, { NULL, }, 0 };
+ /* mutable roots, don't know whether old or young */
+struct global_root_list caml_global_roots_young = { NULL, { NULL, }, 0 };
+ /* generational roots pointing to minor or major heap */
+struct global_root_list caml_global_roots_old = { NULL, { NULL, }, 0 };
+ /* generational roots pointing to major heap */
+
+/* Register a global C root of the mutable kind */
+
+CAMLexport void caml_register_global_root(value *r)
+{
+ Assert (((intnat) r & 3) == 0); /* compact.c demands this (for now) */
+ caml_insert_global_root(&caml_global_roots, r);
+}
+
+/* Un-register a global C root of the mutable kind */
+
+CAMLexport void caml_remove_global_root(value *r)
+{
+ caml_delete_global_root(&caml_global_roots, r);
+}
+
+/* Register a global C root of the generational kind */
+
+CAMLexport void caml_register_generational_global_root(value *r)
+{
+ value v = *r;
+ Assert (((intnat) r & 3) == 0); /* compact.c demands this (for now) */
+ if (Is_block(v)) {
+ if (Is_young(v))
+ caml_insert_global_root(&caml_global_roots_young, r);
+ else if (Is_in_heap(v))
+ caml_insert_global_root(&caml_global_roots_old, r);
+ }
+}
+
+/* Un-register a global C root of the generational kind */
+
+CAMLexport void caml_remove_generational_global_root(value *r)
+{
+ value v = *r;
+ if (Is_block(v)) {
+ if (Is_young(v))
+ caml_delete_global_root(&caml_global_roots_young, r);
+ else if (Is_in_heap(v))
+ caml_delete_global_root(&caml_global_roots_old, r);
+ }
+}
+
+/* Modify the value of a global C root of the generational kind */
+
+CAMLexport void caml_modify_generational_global_root(value *r, value newval)
+{
+ value oldval = *r;
+
+ /* It is OK to have a root in roots_young that suddenly points to
+ the old generation -- the next minor GC will take care of that.
+ What needs corrective action is a root in roots_old that suddenly
+ points to the young generation. */
+ if (Is_block(newval) && Is_young(newval) &&
+ Is_block(oldval) && Is_in_heap(oldval)) {
+ caml_delete_global_root(&caml_global_roots_old, r);
+ caml_insert_global_root(&caml_global_roots_young, r);
+ }
+ /* PR#4704 */
+ else if (!Is_block(oldval) && Is_block(newval)) {
+ /* The previous value in the root was unboxed but now it is boxed.
+ The root won't appear in any of the root lists thus far (by virtue
+ of the operation of [caml_register_generational_global_root]), so we
+ need to make sure it gets in, or else it will never be scanned. */
+ if (Is_young(newval))
+ caml_insert_global_root(&caml_global_roots_young, r);
+ else if (Is_in_heap(newval))
+ caml_insert_global_root(&caml_global_roots_old, r);
+ }
+ else if (Is_block(oldval) && !Is_block(newval)) {
+ /* The previous value in the root was boxed but now it is unboxed, so
+ the root should be removed. If [oldval] is young, this will happen
+ anyway at the next minor collection, but it is safer to delete it
+ here. */
+ if (Is_young(oldval))
+ caml_delete_global_root(&caml_global_roots_young, r);
+ else if (Is_in_heap(oldval))
+ caml_delete_global_root(&caml_global_roots_old, r);
+ }
+ /* end PR#4704 */
+ *r = newval;
+}
+
+/* Scan all global roots */
+
+void caml_scan_global_roots(scanning_action f)
+{
+ caml_iterate_global_roots(f, &caml_global_roots);
+ caml_iterate_global_roots(f, &caml_global_roots_young);
+ caml_iterate_global_roots(f, &caml_global_roots_old);
+}
+
+/* Scan global roots for a minor collection */
+
+void caml_scan_global_young_roots(scanning_action f)
+{
+ struct global_root * gr;
+
+ caml_iterate_global_roots(f, &caml_global_roots);
+ caml_iterate_global_roots(f, &caml_global_roots_young);
+ /* Move young roots to old roots */
+ for (gr = caml_global_roots_young.forward[0];
+ gr != NULL; gr = gr->forward[0]) {
+ caml_insert_global_root(&caml_global_roots_old, gr->root);
+ }
+ caml_empty_global_roots(&caml_global_roots_young);
+}
diff --git a/byterun/hash.c b/byterun/hash.c
new file mode 100644
index 0000000000..e6be1aee14
--- /dev/null
+++ b/byterun/hash.c
@@ -0,0 +1,412 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The generic hashing primitive */
+
+/* The interface of this file is in "mlvalues.h" (for [caml_hash_variant])
+ and in "hash.h" (for the other exported functions). */
+
+#include "caml/mlvalues.h"
+#include "caml/custom.h"
+#include "caml/memory.h"
+#include "caml/hash.h"
+
+/* The new implementation, based on MurmurHash 3,
+ http://code.google.com/p/smhasher/ */
+
+#define ROTL32(x,n) ((x) << n | (x) >> (32-n))
+
+#define MIX(h,d) \
+ d *= 0xcc9e2d51; \
+ d = ROTL32(d, 15); \
+ d *= 0x1b873593; \
+ h ^= d; \
+ h = ROTL32(h, 13); \
+ h = h * 5 + 0xe6546b64;
+
+#define FINAL_MIX(h) \
+ h ^= h >> 16; \
+ h *= 0x85ebca6b; \
+ h ^= h >> 13; \
+ h *= 0xc2b2ae35; \
+ h ^= h >> 16;
+
+CAMLexport uint32_t caml_hash_mix_uint32(uint32_t h, uint32_t d)
+{
+ MIX(h, d);
+ return h;
+}
+
+/* Mix a platform-native integer. */
+
+CAMLexport uint32_t caml_hash_mix_intnat(uint32_t h, intnat d)
+{
+ uint32_t n;
+#ifdef ARCH_SIXTYFOUR
+ /* Mix the low 32 bits and the high 32 bits, in a way that preserves
+ 32/64 compatibility: we want n = (uint32_t) d
+ if d is in the range [-2^31, 2^31-1]. */
+ n = (d >> 32) ^ (d >> 63) ^ d;
+ /* If 0 <= d < 2^31: d >> 32 = 0 d >> 63 = 0
+ If -2^31 <= d < 0: d >> 32 = -1 d >> 63 = -1
+ In both cases, n = (uint32_t) d. */
+#else
+ n = d;
+#endif
+ MIX(h, n);
+ return h;
+}
+
+/* Mix a 64-bit integer. */
+
+CAMLexport uint32_t caml_hash_mix_int64(uint32_t h, int64_t d)
+{
+ uint32_t hi = (uint32_t) (d >> 32), lo = (uint32_t) d;
+ MIX(h, lo);
+ MIX(h, hi);
+ return h;
+}
+
+/* Mix a double-precision float.
+ Treats +0.0 and -0.0 identically.
+ Treats all NaNs identically.
+*/
+
+CAMLexport uint32_t caml_hash_mix_double(uint32_t hash, double d)
+{
+ union {
+ double d;
+#if defined(ARCH_BIG_ENDIAN) || (defined(__arm__) && !defined(__ARM_EABI__))
+ struct { uint32_t h; uint32_t l; } i;
+#else
+ struct { uint32_t l; uint32_t h; } i;
+#endif
+ } u;
+ uint32_t h, l;
+ /* Convert to two 32-bit halves */
+ u.d = d;
+ h = u.i.h; l = u.i.l;
+ /* Normalize NaNs */
+ if ((h & 0x7FF00000) == 0x7FF00000 && (l | (h & 0xFFFFF)) != 0) {
+ h = 0x7FF00000;
+ l = 0x00000001;
+ }
+ /* Normalize -0 into +0 */
+ else if (h == 0x80000000 && l == 0) {
+ h = 0;
+ }
+ MIX(hash, l);
+ MIX(hash, h);
+ return hash;
+}
+
+/* Mix a single-precision float.
+ Treats +0.0 and -0.0 identically.
+ Treats all NaNs identically.
+*/
+
+CAMLexport uint32_t caml_hash_mix_float(uint32_t hash, float d)
+{
+ union {
+ float f;
+ uint32_t i;
+ } u;
+ uint32_t n;
+ /* Convert to int32_t */
+ u.f = d; n = u.i;
+ /* Normalize NaNs */
+ if ((n & 0x7F800000) == 0x7F800000 && (n & 0x007FFFFF) != 0) {
+ n = 0x7F800001;
+ }
+ /* Normalize -0 into +0 */
+ else if (n == 0x80000000) {
+ n = 0;
+ }
+ MIX(hash, n);
+ return hash;
+}
+
+/* Mix an OCaml string */
+
+CAMLexport uint32_t caml_hash_mix_string(uint32_t h, value s)
+{
+ mlsize_t len = caml_string_length(s);
+ mlsize_t i;
+ uint32_t w;
+
+ /* Mix by 32-bit blocks (little-endian) */
+ for (i = 0; i + 4 <= len; i += 4) {
+#ifdef ARCH_BIG_ENDIAN
+ w = Byte_u(s, i)
+ | (Byte_u(s, i+1) << 8)
+ | (Byte_u(s, i+2) << 16)
+ | (Byte_u(s, i+3) << 24);
+#else
+ w = *((uint32_t *) &Byte_u(s, i));
+#endif
+ MIX(h, w);
+ }
+ /* Finish with up to 3 bytes */
+ w = 0;
+ switch (len & 3) {
+ case 3: w = Byte_u(s, i+2) << 16; /* fallthrough */
+ case 2: w |= Byte_u(s, i+1) << 8; /* fallthrough */
+ case 1: w |= Byte_u(s, i);
+ MIX(h, w);
+ default: /*skip*/; /* len & 3 == 0, no extra bytes, do nothing */
+ }
+ /* Finally, mix in the length. Ignore the upper 32 bits, generally 0. */
+ h ^= (uint32_t) len;
+ return h;
+}
+
+/* Maximal size of the queue used for breadth-first traversal. */
+#define HASH_QUEUE_SIZE 256
+/* Maximal number of Forward_tag links followed in one step */
+#define MAX_FORWARD_DEREFERENCE 1000
+
+/* The generic hash function */
+
+CAMLprim value caml_hash(value count, value limit, value seed, value obj)
+{
+ value queue[HASH_QUEUE_SIZE]; /* Queue of values to examine */
+ intnat rd; /* Position of first value in queue */
+ intnat wr; /* One past position of last value in queue */
+ intnat sz; /* Max number of values to put in queue */
+ intnat num; /* Max number of meaningful values to see */
+ uint32_t h; /* Rolling hash */
+ value v;
+ mlsize_t i, len;
+
+ sz = Long_val(limit);
+ if (sz < 0 || sz > HASH_QUEUE_SIZE) sz = HASH_QUEUE_SIZE;
+ num = Long_val(count);
+ h = Int_val(seed);
+ queue[0] = obj; rd = 0; wr = 1;
+
+ while (rd < wr && num > 0) {
+ v = queue[rd++];
+ again:
+ if (Is_long(v)) {
+ h = caml_hash_mix_intnat(h, v);
+ num--;
+ }
+ else if (Is_in_value_area(v)) {
+ switch (Tag_val(v)) {
+ case String_tag:
+ h = caml_hash_mix_string(h, v);
+ num--;
+ break;
+ case Double_tag:
+ h = caml_hash_mix_double(h, Double_val(v));
+ num--;
+ break;
+ case Double_array_tag:
+ for (i = 0, len = Wosize_val(v) / Double_wosize; i < len; i++) {
+ h = caml_hash_mix_double(h, Double_field(v, i));
+ num--;
+ if (num <= 0) break;
+ }
+ break;
+ case Abstract_tag:
+ /* Block contents unknown. Do nothing. */
+ break;
+ case Infix_tag:
+ /* Mix in the offset to distinguish different functions from
+ the same mutually-recursive definition */
+ h = caml_hash_mix_uint32(h, Infix_offset_val(v));
+ v = v - Infix_offset_val(v);
+ goto again;
+ case Forward_tag:
+ /* PR#6361: we can have a loop here, so limit the number of
+ Forward_tag links being followed */
+ for (i = MAX_FORWARD_DEREFERENCE; i > 0; i--) {
+ v = Forward_val(v);
+ if (Is_long(v) || !Is_in_value_area(v) || Tag_val(v) != Forward_tag)
+ goto again;
+ }
+ /* Give up on this object and move to the next */
+ break;
+ case Object_tag:
+ h = caml_hash_mix_intnat(h, Oid_val(v));
+ num--;
+ break;
+ case Custom_tag:
+ /* If no hashing function provided, do nothing. */
+ /* Only use low 32 bits of custom hash, for 32/64 compatibility */
+ if (Custom_ops_val(v)->hash != NULL) {
+ uint32_t n = (uint32_t) Custom_ops_val(v)->hash(v);
+ h = caml_hash_mix_uint32(h, n);
+ num--;
+ }
+ break;
+ default:
+ /* Mix in the tag and size, but do not count this towards [num] */
+ h = caml_hash_mix_uint32(h, Whitehd_hd(Hd_val(v)));
+ /* Copy fields into queue, not exceeding the total size [sz] */
+ for (i = 0, len = Wosize_val(v); i < len; i++) {
+ if (wr >= sz) break;
+ queue[wr++] = Field(v, i);
+ }
+ break;
+ }
+ } else {
+ /* v is a pointer outside the heap, probably a code pointer.
+ Shall we count it? Let's say yes by compatibility with old code. */
+ h = caml_hash_mix_intnat(h, v);
+ num--;
+ }
+ }
+ /* Final mixing of bits */
+ FINAL_MIX(h);
+ /* Fold result to the range [0, 2^30-1] so that it is a nonnegative
+ OCaml integer both on 32 and 64-bit platforms. */
+ return Val_int(h & 0x3FFFFFFFU);
+}
+
+/* The old implementation */
+
+static uintnat hash_accu;
+static intnat hash_univ_limit, hash_univ_count;
+
+static void hash_aux(value obj);
+
+CAMLprim value caml_hash_univ_param(value count, value limit, value obj)
+{
+ hash_univ_limit = Long_val(limit);
+ hash_univ_count = Long_val(count);
+ hash_accu = 0;
+ hash_aux(obj);
+ return Val_long(hash_accu & 0x3FFFFFFF);
+ /* The & has two purposes: ensure that the return value is positive
+ and give the same result on 32 bit and 64 bit architectures. */
+}
+
+#define Alpha 65599
+#define Beta 19
+#define Combine(new) (hash_accu = hash_accu * Alpha + (new))
+#define Combine_small(new) (hash_accu = hash_accu * Beta + (new))
+
+static void hash_aux(value obj)
+{
+ unsigned char * p;
+ mlsize_t i, j;
+ tag_t tag;
+
+ hash_univ_limit--;
+ if (hash_univ_count < 0 || hash_univ_limit < 0) return;
+
+ again:
+ if (Is_long(obj)) {
+ hash_univ_count--;
+ Combine(Long_val(obj));
+ return;
+ }
+
+ /* Pointers into the heap are well-structured blocks. So are atoms.
+ We can inspect the block contents. */
+
+ Assert (Is_block (obj));
+ if (Is_in_value_area(obj)) {
+ tag = Tag_val(obj);
+ switch (tag) {
+ case String_tag:
+ hash_univ_count--;
+ i = caml_string_length(obj);
+ for (p = &Byte_u(obj, 0); i > 0; i--, p++)
+ Combine_small(*p);
+ break;
+ case Double_tag:
+ /* For doubles, we inspect their binary representation, LSB first.
+ The results are consistent among all platforms with IEEE floats. */
+ hash_univ_count--;
+#ifdef ARCH_BIG_ENDIAN
+ for (p = &Byte_u(obj, sizeof(double) - 1), i = sizeof(double);
+ i > 0;
+ p--, i--)
+#else
+ for (p = &Byte_u(obj, 0), i = sizeof(double);
+ i > 0;
+ p++, i--)
+#endif
+ Combine_small(*p);
+ break;
+ case Double_array_tag:
+ hash_univ_count--;
+ for (j = 0; j < Bosize_val(obj); j += sizeof(double)) {
+#ifdef ARCH_BIG_ENDIAN
+ for (p = &Byte_u(obj, j + sizeof(double) - 1), i = sizeof(double);
+ i > 0;
+ p--, i--)
+#else
+ for (p = &Byte_u(obj, j), i = sizeof(double);
+ i > 0;
+ p++, i--)
+#endif
+ Combine_small(*p);
+ }
+ break;
+ case Abstract_tag:
+ /* We don't know anything about the contents of the block.
+ Better do nothing. */
+ break;
+ case Infix_tag:
+ hash_aux(obj - Infix_offset_val(obj));
+ break;
+ case Forward_tag:
+ obj = Forward_val (obj);
+ goto again;
+ case Object_tag:
+ hash_univ_count--;
+ Combine(Oid_val(obj));
+ break;
+ case Custom_tag:
+ /* If no hashing function provided, do nothing */
+ if (Custom_ops_val(obj)->hash != NULL) {
+ hash_univ_count--;
+ Combine(Custom_ops_val(obj)->hash(obj));
+ }
+ break;
+ default:
+ hash_univ_count--;
+ Combine_small(tag);
+ i = Wosize_val(obj);
+ while (i != 0) {
+ i--;
+ hash_aux(Field(obj, i));
+ }
+ break;
+ }
+ return;
+ }
+
+ /* Otherwise, obj is a pointer outside the heap, to an object with
+ a priori unknown structure. Use its physical address as hash key. */
+ Combine((intnat) obj);
+}
+
+/* Hashing variant tags */
+
+CAMLexport value caml_hash_variant(char const * tag)
+{
+ value accu;
+ /* Same hashing algorithm as in ../typing/btype.ml, function hash_variant */
+ for (accu = Val_int(0); *tag != 0; tag++)
+ accu = Val_int(223 * Int_val(accu) + *((unsigned char *) tag));
+#ifdef ARCH_SIXTYFOUR
+ accu = accu & Val_long(0x7FFFFFFFL);
+#endif
+ /* Force sign extension of bit 31 for compatibility between 32 and 64-bit
+ platforms */
+ return (int32_t) accu;
+}
diff --git a/byterun/instrtrace.c b/byterun/instrtrace.c
new file mode 100644
index 0000000000..cce707deac
--- /dev/null
+++ b/byterun/instrtrace.c
@@ -0,0 +1,263 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Trace the instructions executed */
+
+#ifdef DEBUG
+
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "caml/instruct.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/opnames.h"
+#include "caml/prims.h"
+#include "caml/stacks.h"
+#include "caml/startup_aux.h"
+
+extern code_t caml_start_code;
+
+intnat caml_icount = 0;
+
+void caml_stop_here () {}
+
+void caml_disasm_instr(pc)
+ code_t pc;
+{
+ int instr = *pc;
+ printf("%6ld %s", (long) (pc - caml_start_code),
+ instr < 0 || instr > STOP ? "???" : names_of_instructions[instr]);
+ pc++;
+ switch(instr) {
+ /* Instructions with one integer operand */
+ case PUSHACC: case ACC: case POP: case ASSIGN:
+ case PUSHENVACC: case ENVACC: case PUSH_RETADDR: case APPLY:
+ case APPTERM1: case APPTERM2: case APPTERM3: case RETURN:
+ case GRAB: case PUSHGETGLOBAL: case GETGLOBAL: case SETGLOBAL:
+ case PUSHATOM: case ATOM: case MAKEBLOCK1: case MAKEBLOCK2:
+ case MAKEBLOCK3: case MAKEFLOATBLOCK:
+ case GETFIELD: case SETFIELD: case GETFLOATFIELD: case SETFLOATFIELD:
+ case BRANCH: case BRANCHIF: case BRANCHIFNOT: case PUSHTRAP:
+ case CONSTINT: case PUSHCONSTINT: case OFFSETINT: case OFFSETREF:
+ case OFFSETCLOSURE: case PUSHOFFSETCLOSURE:
+ printf(" %d\n", pc[0]); break;
+ /* Instructions with two operands */
+ case APPTERM: case CLOSURE: case CLOSUREREC: case PUSHGETGLOBALFIELD:
+ case GETGLOBALFIELD: case MAKEBLOCK:
+ case BEQ: case BNEQ: case BLTINT: case BLEINT: case BGTINT: case BGEINT:
+ case BULTINT: case BUGEINT:
+ printf(" %d, %d\n", pc[0], pc[1]); break;
+ /* Instructions with a C primitive as operand */
+ case C_CALLN:
+ printf(" %d,", pc[0]); pc++;
+ /* fallthrough */
+ case C_CALL1: case C_CALL2: case C_CALL3: case C_CALL4: case C_CALL5:
+ if (pc[0] < 0 || pc[0] >= caml_prim_name_table.size)
+ printf(" unknown primitive %d\n", pc[0]);
+ else
+ printf(" %s\n", (char *) caml_prim_name_table.contents[pc[0]]);
+ break;
+ default:
+ printf("\n");
+ }
+ fflush (stdout);
+}
+
+char * caml_instr_string (code_t pc)
+{
+ static char buf[256];
+ char nambuf[128];
+ int instr = *pc;
+ char *nam;
+
+ nam = (instr < 0 || instr > STOP)
+ ? (snprintf (nambuf, sizeof(nambuf), "???%d", instr), nambuf)
+ : names_of_instructions[instr];
+ pc++;
+ switch (instr) {
+ /* Instructions with one integer operand */
+ case PUSHACC:
+ case ACC:
+ case POP:
+ case ASSIGN:
+ case PUSHENVACC:
+ case ENVACC:
+ case PUSH_RETADDR:
+ case APPLY:
+ case APPTERM1:
+ case APPTERM2:
+ case APPTERM3:
+ case RETURN:
+ case GRAB:
+ case PUSHGETGLOBAL:
+ case GETGLOBAL:
+ case SETGLOBAL:
+ case PUSHATOM:
+ case ATOM:
+ case MAKEBLOCK1:
+ case MAKEBLOCK2:
+ case MAKEBLOCK3:
+ case MAKEFLOATBLOCK:
+ case GETFIELD:
+ case SETFIELD:
+ case GETFLOATFIELD:
+ case SETFLOATFIELD:
+ case BRANCH:
+ case BRANCHIF:
+ case BRANCHIFNOT:
+ case PUSHTRAP:
+ case CONSTINT:
+ case PUSHCONSTINT:
+ case OFFSETINT:
+ case OFFSETREF:
+ case OFFSETCLOSURE:
+ case PUSHOFFSETCLOSURE:
+ snprintf(buf, sizeof(buf), "%s %d", nam, pc[0]);
+ break;
+ /* Instructions with two operands */
+ case APPTERM:
+ case CLOSURE:
+ case CLOSUREREC:
+ case PUSHGETGLOBALFIELD:
+ case GETGLOBALFIELD:
+ case MAKEBLOCK:
+ case BEQ:
+ case BNEQ:
+ case BLTINT:
+ case BLEINT:
+ case BGTINT:
+ case BGEINT:
+ case BULTINT:
+ case BUGEINT:
+ snprintf(buf, sizeof(buf), "%s %d, %d", nam, pc[0], pc[1]);
+ break;
+ case SWITCH:
+ snprintf(buf, sizeof(buf), "SWITCH sz%#lx=%ld::ntag%ld nint%ld",
+ (long) pc[0], (long) pc[0], (unsigned long) pc[0] >> 16,
+ (unsigned long) pc[0] & 0xffff);
+ break;
+ /* Instructions with a C primitive as operand */
+ case C_CALLN:
+ snprintf(buf, sizeof(buf), "%s %d,", nam, pc[0]);
+ pc++;
+ /* fallthrough */
+ case C_CALL1:
+ case C_CALL2:
+ case C_CALL3:
+ case C_CALL4:
+ case C_CALL5:
+ if (pc[0] < 0 || pc[0] >= caml_prim_name_table.size)
+ snprintf(buf, sizeof(buf), "%s unknown primitive %d", nam, pc[0]);
+ else
+ snprintf(buf, sizeof(buf), "%s %s",
+ nam, (char *) caml_prim_name_table.contents[pc[0]]);
+ break;
+ default:
+ snprintf(buf, sizeof(buf), "%s", nam);
+ break;
+ };
+ return buf;
+}
+
+
+void
+caml_trace_value_file (value v, code_t prog, int proglen, FILE * f)
+{
+ int i;
+ fprintf (f, "%#lx", v);
+ if (!v)
+ return;
+ if (prog && v % sizeof (int) == 0
+ && (code_t) v >= prog
+ && (code_t) v < (code_t) ((char *) prog + proglen))
+ fprintf (f, "=code@%ld", (code_t) v - prog);
+ else if (Is_long (v))
+ fprintf (f, "=long%" ARCH_INTNAT_PRINTF_FORMAT "d", Long_val (v));
+ else if ((void*)v >= (void*)caml_stack_low
+ && (void*)v < (void*)caml_stack_high)
+ fprintf (f, "=stack_%ld", (intnat*)caml_stack_high - (intnat*)v);
+ else if (Is_block (v)) {
+ int s = Wosize_val (v);
+ int tg = Tag_val (v);
+ int l = 0;
+ switch (tg) {
+ case Closure_tag:
+ fprintf (f, "=closure[s%d,cod%ld]", s, (code_t) (Code_val (v)) - prog);
+ goto displayfields;
+ case String_tag:
+ l = caml_string_length (v);
+ fprintf (f, "=string[s%dL%d]'", s, l);
+ for (i = 0; i < ((l>0x1f)?0x1f:l) ; i++) {
+ if (isprint (Byte (v, i)))
+ putc (Byte (v, i), f);
+ else
+ putc ('?', f);
+ };
+ fprintf (f, "'");
+ goto displayfields;
+ case Double_tag:
+ fprintf (f, "=float[s%d]=%g", s, Double_val (v));
+ goto displayfields;
+ case Double_array_tag:
+ fprintf (f, "=floatarray[s%d]", s);
+ for (i = 0; i < ((s>0xf)?0xf:s); i++)
+ fprintf (f, " %g", Double_field (v, i));
+ goto displayfields;
+ case Abstract_tag:
+ fprintf (f, "=abstract[s%d]", s);
+ goto displayfields;
+ case Custom_tag:
+ fprintf (f, "=custom[s%d]", s);
+ goto displayfields;
+ default:
+ fprintf (f, "=block<T%d/s%d>", tg, s);
+ displayfields:
+ if (s > 0)
+ fputs ("=(", f);
+ for (i = 0; i < s; i++) {
+ if (i > 20) {
+ fputs ("....", f);
+ break;
+ };
+ if (i > 0)
+ putc (' ', f);
+ fprintf (f, "%#lx", Field (v, i));
+ };
+ if (s > 0)
+ putc (')', f);
+ };
+ }
+}
+
+void
+caml_trace_accu_sp_file (value accu, value * sp, code_t prog, int proglen,
+ FILE * f)
+{
+ int i;
+ value *p;
+ fprintf (f, "accu=");
+ caml_trace_value_file (accu, prog, proglen, f);
+ fprintf (f, "\n sp=%#" ARCH_INTNAT_PRINTF_FORMAT "x @%ld:",
+ (intnat) sp, caml_stack_high - sp);
+ for (p = sp, i = 0; i < 12 + (1 << caml_trace_level) && p < caml_stack_high;
+ p++, i++) {
+ fprintf (f, "\n[%ld] ", caml_stack_high - p);
+ caml_trace_value_file (*p, prog, proglen, f);
+ };
+ putc ('\n', f);
+ fflush (f);
+}
+
+#endif /* DEBUG */
diff --git a/byterun/intern.c b/byterun/intern.c
new file mode 100644
index 0000000000..89d13d1169
--- /dev/null
+++ b/byterun/intern.c
@@ -0,0 +1,897 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Structured input, compact format */
+
+/* The interface of this file is "caml/intext.h" */
+
+#include <string.h>
+#include <stdio.h>
+#include "caml/alloc.h"
+#include "caml/callback.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/gc.h"
+#include "caml/intext.h"
+#include "caml/io.h"
+#include "caml/md5.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+#include "caml/misc.h"
+#include "caml/reverse.h"
+
+static unsigned char * intern_src;
+/* Reading pointer in block holding input data. */
+
+static unsigned char * intern_input;
+/* Pointer to beginning of block holding input data.
+ Meaningful only if intern_input_malloced = 1. */
+
+static int intern_input_malloced;
+/* 1 if intern_input was allocated by caml_stat_alloc()
+ and needs caml_stat_free() on error, 0 otherwise. */
+
+static header_t * intern_dest;
+/* Writing pointer in destination block */
+
+static char * intern_extra_block;
+/* If non-NULL, point to new heap chunk allocated with caml_alloc_for_heap. */
+
+static asize_t obj_counter;
+/* Count how many objects seen so far */
+
+static value * intern_obj_table;
+/* The pointers to objects already seen */
+
+static unsigned int intern_color;
+/* Color to assign to newly created headers */
+
+static header_t intern_header;
+/* Original header of the destination block.
+ Meaningful only if intern_extra_block is NULL. */
+
+static value intern_block;
+/* Point to the heap block allocated as destination block.
+ Meaningful only if intern_extra_block is NULL. */
+
+static char * intern_resolve_code_pointer(unsigned char digest[16],
+ asize_t offset);
+
+CAMLnoreturn_start
+static void intern_bad_code_pointer(unsigned char digest[16])
+CAMLnoreturn_end;
+
+static void intern_free_stack(void);
+
+#define Sign_extend_shift ((sizeof(intnat) - 1) * 8)
+#define Sign_extend(x) (((intnat)(x) << Sign_extend_shift) >> Sign_extend_shift)
+
+#define read8u() (*intern_src++)
+#define read8s() Sign_extend(*intern_src++)
+#define read16u() \
+ (intern_src += 2, \
+ (intern_src[-2] << 8) + intern_src[-1])
+#define read16s() \
+ (intern_src += 2, \
+ (Sign_extend(intern_src[-2]) << 8) + intern_src[-1])
+#define read32u() \
+ (intern_src += 4, \
+ ((uintnat)(intern_src[-4]) << 24) + (intern_src[-3] << 16) + \
+ (intern_src[-2] << 8) + intern_src[-1])
+#define read32s() \
+ (intern_src += 4, \
+ (Sign_extend(intern_src[-4]) << 24) + (intern_src[-3] << 16) + \
+ (intern_src[-2] << 8) + intern_src[-1])
+
+#ifdef ARCH_SIXTYFOUR
+static intnat read64s(void)
+{
+ intnat res;
+ int i;
+ res = 0;
+ for (i = 0; i < 8; i++) res = (res << 8) + intern_src[i];
+ intern_src += 8;
+ return res;
+}
+#endif
+
+#define readblock(dest,len) \
+ (memmove((dest), intern_src, (len)), intern_src += (len))
+
+static void intern_cleanup(void)
+{
+ if (intern_input_malloced) caml_stat_free(intern_input);
+ if (intern_obj_table != NULL) caml_stat_free(intern_obj_table);
+ if (intern_extra_block != NULL) {
+ /* free newly allocated heap chunk */
+ caml_free_for_heap(intern_extra_block);
+ } else if (intern_block != 0) {
+ /* restore original header for heap block, otherwise GC is confused */
+ Hd_val(intern_block) = intern_header;
+ }
+ /* free the recursion stack */
+ intern_free_stack();
+}
+
+static void readfloat(double * dest, unsigned int code)
+{
+ if (sizeof(double) != 8) {
+ intern_cleanup();
+ caml_invalid_argument("input_value: non-standard floats");
+ }
+ readblock((char *) dest, 8);
+ /* Fix up endianness, if needed */
+#if ARCH_FLOAT_ENDIANNESS == 0x76543210
+ /* Host is big-endian; fix up if data read is little-endian */
+ if (code != CODE_DOUBLE_BIG) Reverse_64(dest, dest);
+#elif ARCH_FLOAT_ENDIANNESS == 0x01234567
+ /* Host is little-endian; fix up if data read is big-endian */
+ if (code != CODE_DOUBLE_LITTLE) Reverse_64(dest, dest);
+#else
+ /* Host is neither big nor little; permute as appropriate */
+ if (code == CODE_DOUBLE_LITTLE)
+ Permute_64(dest, ARCH_FLOAT_ENDIANNESS, dest, 0x01234567)
+ else
+ Permute_64(dest, ARCH_FLOAT_ENDIANNESS, dest, 0x76543210);
+#endif
+}
+
+/* [len] is a number of floats */
+static void readfloats(double * dest, mlsize_t len, unsigned int code)
+{
+ mlsize_t i;
+ if (sizeof(double) != 8) {
+ intern_cleanup();
+ caml_invalid_argument("input_value: non-standard floats");
+ }
+ readblock((char *) dest, len * 8);
+ /* Fix up endianness, if needed */
+#if ARCH_FLOAT_ENDIANNESS == 0x76543210
+ /* Host is big-endian; fix up if data read is little-endian */
+ if (code != CODE_DOUBLE_ARRAY8_BIG &&
+ code != CODE_DOUBLE_ARRAY32_BIG) {
+ for (i = 0; i < len; i++) Reverse_64(dest + i, dest + i);
+ }
+#elif ARCH_FLOAT_ENDIANNESS == 0x01234567
+ /* Host is little-endian; fix up if data read is big-endian */
+ if (code != CODE_DOUBLE_ARRAY8_LITTLE &&
+ code != CODE_DOUBLE_ARRAY32_LITTLE) {
+ for (i = 0; i < len; i++) Reverse_64(dest + i, dest + i);
+ }
+#else
+ /* Host is neither big nor little; permute as appropriate */
+ if (code == CODE_DOUBLE_ARRAY8_LITTLE ||
+ code == CODE_DOUBLE_ARRAY32_LITTLE) {
+ for (i = 0; i < len; i++)
+ Permute_64(dest + i, ARCH_FLOAT_ENDIANNESS, dest + i, 0x01234567);
+ } else {
+ for (i = 0; i < len; i++)
+ Permute_64(dest + i, ARCH_FLOAT_ENDIANNESS, dest + i, 0x76543210);
+ }
+#endif
+}
+
+/* Item on the stack with defined operation */
+struct intern_item {
+ value * dest;
+ intnat arg;
+ enum {
+ OReadItems, /* read arg items and store them in dest[0], dest[1], ... */
+ OFreshOID, /* generate a fresh OID and store it in *dest */
+ OShift /* offset *dest by arg */
+ } op;
+};
+
+/* FIXME: This is duplicated in two other places, with the only difference of
+ the type of elements stored in the stack. Possible solution in C would
+ be to instantiate stack these function via. C preprocessor macro.
+ */
+
+#define INTERN_STACK_INIT_SIZE 256
+#define INTERN_STACK_MAX_SIZE (1024*1024*100)
+
+static struct intern_item intern_stack_init[INTERN_STACK_INIT_SIZE];
+
+static struct intern_item * intern_stack = intern_stack_init;
+static struct intern_item * intern_stack_limit = intern_stack_init
+ + INTERN_STACK_INIT_SIZE;
+
+/* Free the recursion stack if needed */
+static void intern_free_stack(void)
+{
+ if (intern_stack != intern_stack_init) {
+ free(intern_stack);
+ /* Reinitialize the globals for next time around */
+ intern_stack = intern_stack_init;
+ intern_stack_limit = intern_stack + INTERN_STACK_INIT_SIZE;
+ }
+}
+
+/* Same, then raise Out_of_memory */
+static void intern_stack_overflow(void)
+{
+ caml_gc_message (0x04, "Stack overflow in un-marshaling value\n", 0);
+ intern_free_stack();
+ caml_raise_out_of_memory();
+}
+
+static struct intern_item * intern_resize_stack(struct intern_item * sp)
+{
+ asize_t newsize = 2 * (intern_stack_limit - intern_stack);
+ asize_t sp_offset = sp - intern_stack;
+ struct intern_item * newstack;
+
+ if (newsize >= INTERN_STACK_MAX_SIZE) intern_stack_overflow();
+ if (intern_stack == intern_stack_init) {
+ newstack = malloc(sizeof(struct intern_item) * newsize);
+ if (newstack == NULL) intern_stack_overflow();
+ memcpy(newstack, intern_stack_init,
+ sizeof(struct intern_item) * INTERN_STACK_INIT_SIZE);
+ } else {
+ newstack =
+ realloc(intern_stack, sizeof(struct intern_item) * newsize);
+ if (newstack == NULL) intern_stack_overflow();
+ }
+ intern_stack = newstack;
+ intern_stack_limit = newstack + newsize;
+ return newstack + sp_offset;
+}
+
+/* Convenience macros for requesting operation on the stack */
+#define PushItem() \
+ do { \
+ sp++; \
+ if (sp >= intern_stack_limit) sp = intern_resize_stack(sp); \
+ } while(0)
+
+#define ReadItems(_dest,_n) \
+ do { \
+ if (_n > 0) { \
+ PushItem(); \
+ sp->op = OReadItems; \
+ sp->dest = _dest; \
+ sp->arg = _n; \
+ } \
+ } while(0)
+
+static void intern_rec(value *dest)
+{
+ unsigned int code;
+ tag_t tag;
+ mlsize_t size, len, ofs_ind;
+ value v;
+ asize_t ofs;
+ header_t header;
+ unsigned char digest[16];
+ struct custom_operations * ops;
+ char * codeptr;
+ struct intern_item * sp;
+
+ sp = intern_stack;
+
+ /* Initially let's try to read the first object from the stream */
+ ReadItems(dest, 1);
+
+ /* The un-marshaler loop, the recursion is unrolled */
+ while(sp != intern_stack) {
+
+ /* Interpret next item on the stack */
+ dest = sp->dest;
+ switch (sp->op) {
+ case OFreshOID:
+ /* Refresh the object ID */
+ /* but do not do it for predefined exception slots */
+ if (Int_val(Field((value)dest, 1)) >= 0)
+ caml_set_oo_id((value)dest);
+ /* Pop item and iterate */
+ sp--;
+ break;
+ case OShift:
+ /* Shift value by an offset */
+ *dest += sp->arg;
+ /* Pop item and iterate */
+ sp--;
+ break;
+ case OReadItems:
+ /* Pop item */
+ sp->dest++;
+ if (--(sp->arg) == 0) sp--;
+ /* Read a value and set v to this value */
+ code = read8u();
+ if (code >= PREFIX_SMALL_INT) {
+ if (code >= PREFIX_SMALL_BLOCK) {
+ /* Small block */
+ tag = code & 0xF;
+ size = (code >> 4) & 0x7;
+ read_block:
+ if (size == 0) {
+ v = Atom(tag);
+ } else {
+ v = Val_hp(intern_dest);
+ if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v;
+ *intern_dest = Make_header(size, tag, intern_color);
+ intern_dest += 1 + size;
+ /* For objects, we need to freshen the oid */
+ if (tag == Object_tag) {
+ Assert(size >= 2);
+ /* Request to read rest of the elements of the block */
+ ReadItems(&Field(v, 2), size - 2);
+ /* Request freshing OID */
+ PushItem();
+ sp->op = OFreshOID;
+ sp->dest = (value*) v;
+ sp->arg = 1;
+ /* Finally read first two block elements: method table and old OID */
+ ReadItems(&Field(v, 0), 2);
+ } else
+ /* If it's not an object then read the contents of the block */
+ ReadItems(&Field(v, 0), size);
+ }
+ } else {
+ /* Small integer */
+ v = Val_int(code & 0x3F);
+ }
+ } else {
+ if (code >= PREFIX_SMALL_STRING) {
+ /* Small string */
+ len = (code & 0x1F);
+ read_string:
+ size = (len + sizeof(value)) / sizeof(value);
+ v = Val_hp(intern_dest);
+ if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v;
+ *intern_dest = Make_header(size, String_tag, intern_color);
+ intern_dest += 1 + size;
+ Field(v, size - 1) = 0;
+ ofs_ind = Bsize_wsize(size) - 1;
+ Byte(v, ofs_ind) = ofs_ind - len;
+ readblock(String_val(v), len);
+ } else {
+ switch(code) {
+ case CODE_INT8:
+ v = Val_long(read8s());
+ break;
+ case CODE_INT16:
+ v = Val_long(read16s());
+ break;
+ case CODE_INT32:
+ v = Val_long(read32s());
+ break;
+ case CODE_INT64:
+#ifdef ARCH_SIXTYFOUR
+ v = Val_long(read64s());
+ break;
+#else
+ intern_cleanup();
+ caml_failwith("input_value: integer too large");
+ break;
+#endif
+ case CODE_SHARED8:
+ ofs = read8u();
+ read_shared:
+ Assert (ofs > 0);
+ Assert (ofs <= obj_counter);
+ Assert (intern_obj_table != NULL);
+ v = intern_obj_table[obj_counter - ofs];
+ break;
+ case CODE_SHARED16:
+ ofs = read16u();
+ goto read_shared;
+ case CODE_SHARED32:
+ ofs = read32u();
+ goto read_shared;
+ case CODE_BLOCK32:
+ header = (header_t) read32u();
+ tag = Tag_hd(header);
+ size = Wosize_hd(header);
+ goto read_block;
+ case CODE_BLOCK64:
+#ifdef ARCH_SIXTYFOUR
+ header = (header_t) read64s();
+ tag = Tag_hd(header);
+ size = Wosize_hd(header);
+ goto read_block;
+#else
+ intern_cleanup();
+ caml_failwith("input_value: data block too large");
+ break;
+#endif
+ case CODE_STRING8:
+ len = read8u();
+ goto read_string;
+ case CODE_STRING32:
+ len = read32u();
+ goto read_string;
+ case CODE_DOUBLE_LITTLE:
+ case CODE_DOUBLE_BIG:
+ v = Val_hp(intern_dest);
+ if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v;
+ *intern_dest = Make_header(Double_wosize, Double_tag, intern_color);
+ intern_dest += 1 + Double_wosize;
+ readfloat((double *) v, code);
+ break;
+ case CODE_DOUBLE_ARRAY8_LITTLE:
+ case CODE_DOUBLE_ARRAY8_BIG:
+ len = read8u();
+ read_double_array:
+ size = len * Double_wosize;
+ v = Val_hp(intern_dest);
+ if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v;
+ *intern_dest = Make_header(size, Double_array_tag, intern_color);
+ intern_dest += 1 + size;
+ readfloats((double *) v, len, code);
+ break;
+ case CODE_DOUBLE_ARRAY32_LITTLE:
+ case CODE_DOUBLE_ARRAY32_BIG:
+ len = read32u();
+ goto read_double_array;
+ case CODE_CODEPOINTER:
+ ofs = read32u();
+ readblock(digest, 16);
+ codeptr = intern_resolve_code_pointer(digest, ofs);
+ if (codeptr != NULL) {
+ v = (value) codeptr;
+ } else {
+ value * function_placeholder =
+ caml_named_value ("Debugger.function_placeholder");
+ if (function_placeholder != NULL) {
+ v = *function_placeholder;
+ } else {
+ intern_cleanup();
+ intern_bad_code_pointer(digest);
+ }
+ }
+ break;
+ case CODE_INFIXPOINTER:
+ ofs = read32u();
+ /* Read a value to *dest, then offset *dest by ofs */
+ PushItem();
+ sp->dest = dest;
+ sp->op = OShift;
+ sp->arg = ofs;
+ ReadItems(dest, 1);
+ continue; /* with next iteration of main loop, skipping *dest = v */
+ case CODE_CUSTOM:
+ ops = caml_find_custom_operations((char *) intern_src);
+ if (ops == NULL) {
+ intern_cleanup();
+ caml_failwith("input_value: unknown custom block identifier");
+ }
+ while (*intern_src++ != 0) /*nothing*/; /*skip identifier*/
+ size = ops->deserialize((void *) (intern_dest + 2));
+ size = 1 + (size + sizeof(value) - 1) / sizeof(value);
+ v = Val_hp(intern_dest);
+ if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v;
+ *intern_dest = Make_header(size, Custom_tag, intern_color);
+ Custom_ops_val(v) = ops;
+
+ if (ops->finalize != NULL && Is_young(v)) {
+ /* Remembered that the block has a finalizer */
+ if (caml_finalize_table.ptr >= caml_finalize_table.limit){
+ CAMLassert (caml_finalize_table.ptr == caml_finalize_table.limit);
+ caml_realloc_ref_table (&caml_finalize_table);
+ }
+ *caml_finalize_table.ptr++ = (value *)v;
+ }
+
+ intern_dest += 1 + size;
+ break;
+ default:
+ intern_cleanup();
+ caml_failwith("input_value: ill-formed message");
+ }
+ }
+ }
+ /* end of case OReadItems */
+ *dest = v;
+ break;
+ default:
+ Assert(0);
+ }
+ }
+ /* We are done. Cleanup the stack and leave the function */
+ intern_free_stack();
+}
+
+static void intern_alloc(mlsize_t whsize, mlsize_t num_objects)
+{
+ mlsize_t wosize;
+
+ if (whsize == 0) {
+ intern_obj_table = NULL;
+ intern_extra_block = NULL;
+ intern_block = 0;
+ return;
+ }
+ wosize = Wosize_whsize(whsize);
+ if (wosize > Max_wosize) {
+ /* Round desired size up to next page */
+ asize_t request =
+ ((Bsize_wsize(whsize) + Page_size - 1) >> Page_log) << Page_log;
+ intern_extra_block = caml_alloc_for_heap(request);
+ if (intern_extra_block == NULL) caml_raise_out_of_memory();
+ intern_color = caml_allocation_color(intern_extra_block);
+ intern_dest = (header_t *) intern_extra_block;
+ } else {
+ /* this is a specialised version of caml_alloc from alloc.c */
+ if (wosize == 0){
+ intern_block = Atom (String_tag);
+ }else if (wosize <= Max_young_wosize){
+ intern_block = caml_alloc_small (wosize, String_tag);
+ }else{
+ intern_block = caml_alloc_shr (wosize, String_tag);
+ /* do not do the urgent_gc check here because it might darken
+ intern_block into gray and break the Assert 3 lines down */
+ }
+ intern_header = Hd_val(intern_block);
+ intern_color = Color_hd(intern_header);
+ Assert (intern_color == Caml_white || intern_color == Caml_black);
+ intern_dest = (header_t *) Hp_val(intern_block);
+ intern_extra_block = NULL;
+ }
+ obj_counter = 0;
+ if (num_objects > 0)
+ intern_obj_table = (value *) caml_stat_alloc(num_objects * sizeof(value));
+ else
+ intern_obj_table = NULL;
+}
+
+static void intern_add_to_heap(mlsize_t whsize)
+{
+ /* Add new heap chunk to heap if needed */
+ if (intern_extra_block != NULL) {
+ /* If heap chunk not filled totally, build free block at end */
+ asize_t request =
+ ((Bsize_wsize(whsize) + Page_size - 1) >> Page_log) << Page_log;
+ header_t * end_extra_block =
+ (header_t *) intern_extra_block + Wsize_bsize(request);
+ Assert(intern_dest <= end_extra_block);
+ if (intern_dest < end_extra_block){
+ caml_make_free_blocks ((value *) intern_dest,
+ end_extra_block - intern_dest, 0, Caml_white);
+ }
+ caml_allocated_words +=
+ Wsize_bsize ((char *) intern_dest - intern_extra_block);
+ caml_add_to_heap(intern_extra_block);
+ }
+}
+
+value caml_input_val(struct channel *chan)
+{
+ uint32_t magic;
+ mlsize_t block_len, num_objects, whsize;
+ char * block;
+ value res;
+
+ if (! caml_channel_binary_mode(chan))
+ caml_failwith("input_value: not a binary channel");
+ magic = caml_getword(chan);
+ if (magic != Intext_magic_number) caml_failwith("input_value: bad object");
+ block_len = caml_getword(chan);
+ num_objects = caml_getword(chan);
+#ifdef ARCH_SIXTYFOUR
+ caml_getword(chan); /* skip size_32 */
+ whsize = caml_getword(chan);
+#else
+ whsize = caml_getword(chan);
+ caml_getword(chan); /* skip size_64 */
+#endif
+ /* Read block from channel */
+ block = caml_stat_alloc(block_len);
+ /* During [caml_really_getblock], concurrent [caml_input_val] operations
+ can take place (via signal handlers or context switching in systhreads),
+ and [intern_input] may change. So, wait until [caml_really_getblock]
+ is over before using [intern_input] and the other global vars. */
+ if (caml_really_getblock(chan, block, block_len) == 0) {
+ caml_stat_free(block);
+ caml_failwith("input_value: truncated object");
+ }
+ intern_input = (unsigned char *) block;
+ intern_input_malloced = 1;
+ intern_src = intern_input;
+ intern_alloc(whsize, num_objects);
+ /* Fill it in */
+ intern_rec(&res);
+ intern_add_to_heap(whsize);
+ /* Free everything */
+ caml_stat_free(intern_input);
+ if (intern_obj_table != NULL) caml_stat_free(intern_obj_table);
+ return caml_check_urgent_gc(res);
+}
+
+CAMLprim value caml_input_value(value vchan)
+{
+ CAMLparam1 (vchan);
+ struct channel * chan = Channel(vchan);
+ CAMLlocal1 (res);
+
+ Lock(chan);
+ res = caml_input_val(chan);
+ Unlock(chan);
+ CAMLreturn (res);
+}
+
+CAMLexport value caml_input_val_from_string(value str, intnat ofs)
+{
+ CAMLparam1 (str);
+ mlsize_t num_objects, whsize;
+ CAMLlocal1 (obj);
+
+ intern_src = &Byte_u(str, ofs + 2*4);
+ intern_input_malloced = 0;
+ num_objects = read32u();
+#ifdef ARCH_SIXTYFOUR
+ intern_src += 4; /* skip size_32 */
+ whsize = read32u();
+#else
+ whsize = read32u();
+ intern_src += 4; /* skip size_64 */
+#endif
+ /* Allocate result */
+ intern_alloc(whsize, num_objects);
+ intern_src = &Byte_u(str, ofs + 5*4); /* If a GC occurred */
+ /* Fill it in */
+ intern_rec(&obj);
+ intern_add_to_heap(whsize);
+ /* Free everything */
+ if (intern_obj_table != NULL) caml_stat_free(intern_obj_table);
+ CAMLreturn (caml_check_urgent_gc(obj));
+}
+
+CAMLprim value caml_input_value_from_string(value str, value ofs)
+{
+ return caml_input_val_from_string(str, Long_val(ofs));
+}
+
+static value input_val_from_block(void)
+{
+ mlsize_t num_objects, whsize;
+ value obj;
+
+ num_objects = read32u();
+#ifdef ARCH_SIXTYFOUR
+ intern_src += 4; /* skip size_32 */
+ whsize = read32u();
+#else
+ whsize = read32u();
+ intern_src += 4; /* skip size_64 */
+#endif
+ /* Allocate result */
+ intern_alloc(whsize, num_objects);
+ /* Fill it in */
+ intern_rec(&obj);
+ intern_add_to_heap(whsize);
+ /* Free internal data structures */
+ if (intern_obj_table != NULL) caml_stat_free(intern_obj_table);
+ return caml_check_urgent_gc(obj);
+}
+
+CAMLexport value caml_input_value_from_malloc(char * data, intnat ofs)
+{
+ uint32_t magic;
+ value obj;
+
+ intern_input = (unsigned char *) data;
+ intern_src = intern_input + ofs;
+ intern_input_malloced = 1;
+ magic = read32u();
+ if (magic != Intext_magic_number)
+ caml_failwith("input_value_from_malloc: bad object");
+ intern_src += 4; /* Skip block_len */
+ obj = input_val_from_block();
+ /* Free the input */
+ caml_stat_free(intern_input);
+ return obj;
+}
+
+/* [len] is a number of bytes */
+CAMLexport value caml_input_value_from_block(char * data, intnat len)
+{
+ uint32_t magic;
+ mlsize_t block_len;
+ value obj;
+
+ intern_input = (unsigned char *) data;
+ intern_src = intern_input;
+ intern_input_malloced = 0;
+ magic = read32u();
+ if (magic != Intext_magic_number)
+ caml_failwith("input_value_from_block: bad object");
+ block_len = read32u();
+ if (5*4 + block_len > len)
+ caml_failwith("input_value_from_block: bad block length");
+ obj = input_val_from_block();
+ return obj;
+}
+
+/* [ofs] is a [value] that represents a number of bytes
+ result is a [value] that represents a number of bytes
+*/
+CAMLprim value caml_marshal_data_size(value buff, value ofs)
+{
+ uint32_t magic;
+ mlsize_t block_len;
+
+ intern_src = &Byte_u(buff, Long_val(ofs));
+ intern_input_malloced = 0;
+ magic = read32u();
+ if (magic != Intext_magic_number){
+ caml_failwith("Marshal.data_size: bad object");
+ }
+ block_len = read32u();
+ return Val_long(block_len);
+}
+
+/* Resolution of code pointers */
+
+static char * intern_resolve_code_pointer(unsigned char digest[16],
+ asize_t offset)
+{
+ int i;
+ for (i = caml_code_fragments_table.size - 1; i >= 0; i--) {
+ struct code_fragment * cf = caml_code_fragments_table.contents[i];
+ if (! cf->digest_computed) {
+ caml_md5_block(cf->digest, cf->code_start, cf->code_end - cf->code_start);
+ cf->digest_computed = 1;
+ }
+ if (memcmp(digest, cf->digest, 16) == 0) {
+ if (cf->code_start + offset < cf->code_end)
+ return cf->code_start + offset;
+ else
+ return NULL;
+ }
+ }
+ return NULL;
+}
+
+static void intern_bad_code_pointer(unsigned char digest[16])
+{
+ char msg[256];
+ snprintf(msg, sizeof(msg),
+ "input_value: unknown code module "
+ "%02X%02X%02X%02X%02X%02X%02X%02X"
+ "%02X%02X%02X%02X%02X%02X%02X%02X",
+ digest[0], digest[1], digest[2], digest[3],
+ digest[4], digest[5], digest[6], digest[7],
+ digest[8], digest[9], digest[10], digest[11],
+ digest[12], digest[13], digest[14], digest[15]);
+ caml_failwith(msg);
+}
+
+/* Functions for writing user-defined marshallers */
+
+CAMLexport int caml_deserialize_uint_1(void)
+{
+ return read8u();
+}
+
+CAMLexport int caml_deserialize_sint_1(void)
+{
+ return read8s();
+}
+
+CAMLexport int caml_deserialize_uint_2(void)
+{
+ return read16u();
+}
+
+CAMLexport int caml_deserialize_sint_2(void)
+{
+ return read16s();
+}
+
+CAMLexport uint32_t caml_deserialize_uint_4(void)
+{
+ return read32u();
+}
+
+CAMLexport int32_t caml_deserialize_sint_4(void)
+{
+ return read32s();
+}
+
+CAMLexport uint64_t caml_deserialize_uint_8(void)
+{
+ uint64_t i;
+ caml_deserialize_block_8(&i, 1);
+ return i;
+}
+
+CAMLexport int64_t caml_deserialize_sint_8(void)
+{
+ int64_t i;
+ caml_deserialize_block_8(&i, 1);
+ return i;
+}
+
+CAMLexport float caml_deserialize_float_4(void)
+{
+ float f;
+ caml_deserialize_block_4(&f, 1);
+ return f;
+}
+
+CAMLexport double caml_deserialize_float_8(void)
+{
+ double f;
+ caml_deserialize_block_float_8(&f, 1);
+ return f;
+}
+
+CAMLexport void caml_deserialize_block_1(void * data, intnat len)
+{
+ memmove(data, intern_src, len);
+ intern_src += len;
+}
+
+CAMLexport void caml_deserialize_block_2(void * data, intnat len)
+{
+#ifndef ARCH_BIG_ENDIAN
+ unsigned char * p, * q;
+ for (p = intern_src, q = data; len > 0; len--, p += 2, q += 2)
+ Reverse_16(q, p);
+ intern_src = p;
+#else
+ memmove(data, intern_src, len * 2);
+ intern_src += len * 2;
+#endif
+}
+
+CAMLexport void caml_deserialize_block_4(void * data, intnat len)
+{
+#ifndef ARCH_BIG_ENDIAN
+ unsigned char * p, * q;
+ for (p = intern_src, q = data; len > 0; len--, p += 4, q += 4)
+ Reverse_32(q, p);
+ intern_src = p;
+#else
+ memmove(data, intern_src, len * 4);
+ intern_src += len * 4;
+#endif
+}
+
+CAMLexport void caml_deserialize_block_8(void * data, intnat len)
+{
+#ifndef ARCH_BIG_ENDIAN
+ unsigned char * p, * q;
+ for (p = intern_src, q = data; len > 0; len--, p += 8, q += 8)
+ Reverse_64(q, p);
+ intern_src = p;
+#else
+ memmove(data, intern_src, len * 8);
+ intern_src += len * 8;
+#endif
+}
+
+CAMLexport void caml_deserialize_block_float_8(void * data, intnat len)
+{
+#if ARCH_FLOAT_ENDIANNESS == 0x01234567
+ memmove(data, intern_src, len * 8);
+ intern_src += len * 8;
+#elif ARCH_FLOAT_ENDIANNESS == 0x76543210
+ unsigned char * p, * q;
+ for (p = intern_src, q = data; len > 0; len--, p += 8, q += 8)
+ Reverse_64(q, p);
+ intern_src = p;
+#else
+ unsigned char * p, * q;
+ for (p = intern_src, q = data; len > 0; len--, p += 8, q += 8)
+ Permute_64(q, ARCH_FLOAT_ENDIANNESS, p, 0x01234567);
+ intern_src = p;
+#endif
+}
+
+CAMLexport void caml_deserialize_error(char * msg)
+{
+ intern_cleanup();
+ caml_failwith(msg);
+}
diff --git a/byterun/interp.c b/byterun/interp.c
new file mode 100644
index 0000000000..a3d9e7034e
--- /dev/null
+++ b/byterun/interp.c
@@ -0,0 +1,1165 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The bytecode interpreter */
+#include <stdio.h>
+#include "caml/alloc.h"
+#include "caml/backtrace.h"
+#include "caml/callback.h"
+#include "caml/debugger.h"
+#include "caml/fail.h"
+#include "caml/fix_code.h"
+#include "caml/instrtrace.h"
+#include "caml/instruct.h"
+#include "caml/interp.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/prims.h"
+#include "caml/signals.h"
+#include "caml/stacks.h"
+#include "caml/startup_aux.h"
+
+/* Registers for the abstract machine:
+ pc the code pointer
+ sp the stack pointer (grows downward)
+ accu the accumulator
+ env heap-allocated environment
+ caml_trapsp pointer to the current trap frame
+ extra_args number of extra arguments provided by the caller
+
+sp is a local copy of the global variable caml_extern_sp. */
+
+/* Instruction decoding */
+
+#ifdef THREADED_CODE
+# define Instruct(name) lbl_##name
+# if defined(ARCH_SIXTYFOUR) && !defined(ARCH_CODE32)
+# define Jumptbl_base ((char *) &&lbl_ACC0)
+# else
+# define Jumptbl_base ((char *) 0)
+# define jumptbl_base ((char *) 0)
+# endif
+# ifdef DEBUG
+# define Next goto next_instr
+# else
+# define Next goto *(void *)(jumptbl_base + *pc++)
+# endif
+#else
+# define Instruct(name) case name
+# define Next break
+#endif
+
+/* GC interface */
+
+#define Setup_for_gc \
+ { sp -= 2; sp[0] = accu; sp[1] = env; caml_extern_sp = sp; }
+#define Restore_after_gc \
+ { accu = sp[0]; env = sp[1]; sp += 2; }
+#define Setup_for_c_call \
+ { saved_pc = pc; *--sp = env; caml_extern_sp = sp; }
+#define Restore_after_c_call \
+ { sp = caml_extern_sp; env = *sp++; saved_pc = NULL; }
+
+/* An event frame must look like accu + a C_CALL frame + a RETURN 1 frame */
+#define Setup_for_event \
+ { sp -= 6; \
+ sp[0] = accu; /* accu */ \
+ sp[1] = Val_unit; /* C_CALL frame: dummy environment */ \
+ sp[2] = Val_unit; /* RETURN frame: dummy local 0 */ \
+ sp[3] = (value) pc; /* RETURN frame: saved return address */ \
+ sp[4] = env; /* RETURN frame: saved environment */ \
+ sp[5] = Val_long(extra_args); /* RETURN frame: saved extra args */ \
+ caml_extern_sp = sp; }
+#define Restore_after_event \
+ { sp = caml_extern_sp; accu = sp[0]; \
+ pc = (code_t) sp[3]; env = sp[4]; extra_args = Long_val(sp[5]); \
+ sp += 6; }
+
+/* Debugger interface */
+
+#define Setup_for_debugger \
+ { sp -= 4; \
+ sp[0] = accu; sp[1] = (value)(pc - 1); \
+ sp[2] = env; sp[3] = Val_long(extra_args); \
+ caml_extern_sp = sp; }
+#define Restore_after_debugger { sp += 4; }
+
+#ifdef THREADED_CODE
+#define Restart_curr_instr \
+ goto *(jumptable[caml_saved_code[pc - 1 - caml_start_code]])
+#else
+#define Restart_curr_instr \
+ curr_instr = caml_saved_code[pc - 1 - caml_start_code]; \
+ goto dispatch_instr
+#endif
+
+/* Register optimization.
+ Some compilers underestimate the use of the local variables representing
+ the abstract machine registers, and don't put them in hardware registers,
+ which slows down the interpreter considerably.
+ For GCC, I have hand-assigned hardware registers for several architectures.
+*/
+
+#if defined(__GNUC__) && !defined(DEBUG) && !defined(__INTEL_COMPILER) \
+ && !defined(__llvm__)
+#ifdef __mips__
+#define PC_REG asm("$16")
+#define SP_REG asm("$17")
+#define ACCU_REG asm("$18")
+#endif
+#ifdef __sparc__
+#define PC_REG asm("%l0")
+#define SP_REG asm("%l1")
+#define ACCU_REG asm("%l2")
+#endif
+#ifdef __alpha__
+#ifdef __CRAY__
+#define PC_REG asm("r9")
+#define SP_REG asm("r10")
+#define ACCU_REG asm("r11")
+#define JUMPTBL_BASE_REG asm("r12")
+#else
+#define PC_REG asm("$9")
+#define SP_REG asm("$10")
+#define ACCU_REG asm("$11")
+#define JUMPTBL_BASE_REG asm("$12")
+#endif
+#endif
+#ifdef __i386__
+#define PC_REG asm("%esi")
+#define SP_REG asm("%edi")
+#define ACCU_REG
+#endif
+#if defined(__ppc__) || defined(__ppc64__)
+#define PC_REG asm("26")
+#define SP_REG asm("27")
+#define ACCU_REG asm("28")
+#endif
+#ifdef __hppa__
+#define PC_REG asm("%r18")
+#define SP_REG asm("%r17")
+#define ACCU_REG asm("%r16")
+#endif
+#ifdef __mc68000__
+#define PC_REG asm("a5")
+#define SP_REG asm("a4")
+#define ACCU_REG asm("d7")
+#endif
+/* PR#4953: these specific registers not available in Thumb mode */
+#if defined (__arm__) && !defined(__thumb__)
+#define PC_REG asm("r6")
+#define SP_REG asm("r8")
+#define ACCU_REG asm("r7")
+#endif
+#ifdef __ia64__
+#define PC_REG asm("36")
+#define SP_REG asm("37")
+#define ACCU_REG asm("38")
+#define JUMPTBL_BASE_REG asm("39")
+#endif
+#ifdef __x86_64__
+#define PC_REG asm("%r15")
+#define SP_REG asm("%r14")
+#define ACCU_REG asm("%r13")
+#endif
+#ifdef __aarch64__
+#define PC_REG asm("%x19")
+#define SP_REG asm("%x20")
+#define ACCU_REG asm("%x21")
+#define JUMPTBL_BASE_REG asm("%x22")
+#endif
+#endif
+
+#ifdef DEBUG
+static intnat caml_bcodcount;
+#endif
+
+/* The interpreter itself */
+
+value caml_interprete(code_t prog, asize_t prog_size)
+{
+#ifdef PC_REG
+ register code_t pc PC_REG;
+ register value * sp SP_REG;
+ register value accu ACCU_REG;
+#else
+ register code_t pc;
+ register value * sp;
+ register value accu;
+#endif
+#if defined(THREADED_CODE) && defined(ARCH_SIXTYFOUR) && !defined(ARCH_CODE32)
+#ifdef JUMPTBL_BASE_REG
+ register char * jumptbl_base JUMPTBL_BASE_REG;
+#else
+ register char * jumptbl_base;
+#endif
+#endif
+ value env;
+ intnat extra_args;
+ struct longjmp_buffer * initial_external_raise;
+ int initial_sp_offset;
+ /* volatile ensures that initial_local_roots and saved_pc
+ will keep correct value across longjmp */
+ struct caml__roots_block * volatile initial_local_roots;
+ volatile code_t saved_pc = NULL;
+ struct longjmp_buffer raise_buf;
+#ifndef THREADED_CODE
+ opcode_t curr_instr;
+#endif
+
+#ifdef THREADED_CODE
+ static void * jumptable[] = {
+# include "caml/jumptbl.h"
+ };
+#endif
+
+ if (prog == NULL) { /* Interpreter is initializing */
+#ifdef THREADED_CODE
+ caml_instr_table = (char **) jumptable;
+ caml_instr_base = Jumptbl_base;
+#endif
+ return Val_unit;
+ }
+
+#if defined(THREADED_CODE) && defined(ARCH_SIXTYFOUR) && !defined(ARCH_CODE32)
+ jumptbl_base = Jumptbl_base;
+#endif
+ initial_local_roots = caml_local_roots;
+ initial_sp_offset = (char *) caml_stack_high - (char *) caml_extern_sp;
+ initial_external_raise = caml_external_raise;
+ caml_callback_depth++;
+ saved_pc = NULL;
+
+ if (sigsetjmp(raise_buf.buf, 0)) {
+ caml_local_roots = initial_local_roots;
+ sp = caml_extern_sp;
+ accu = caml_exn_bucket;
+ pc = saved_pc; saved_pc = NULL;
+ if (pc != NULL) pc += 2;
+ /* +2 adjustement for the sole purpose of backtraces */
+ goto raise_exception;
+ }
+ caml_external_raise = &raise_buf;
+
+ sp = caml_extern_sp;
+ pc = prog;
+ extra_args = 0;
+ env = Atom(0);
+ accu = Val_int(0);
+
+#ifdef THREADED_CODE
+#ifdef DEBUG
+ next_instr:
+ if (caml_icount-- == 0) caml_stop_here ();
+ Assert(sp >= caml_stack_low);
+ Assert(sp <= caml_stack_high);
+#endif
+ goto *(void *)(jumptbl_base + *pc++); /* Jump to the first instruction */
+#else
+ while(1) {
+#ifdef DEBUG
+ caml_bcodcount++;
+ if (caml_icount-- == 0) caml_stop_here ();
+ if (caml_trace_level>1) printf("\n##%ld\n", caml_bcodcount);
+ if (caml_trace_level>0) caml_disasm_instr(pc);
+ if (caml_trace_level>1) {
+ printf("env=");
+ caml_trace_value_file(env,prog,prog_size,stdout);
+ putchar('\n');
+ caml_trace_accu_sp_file(accu,sp,prog,prog_size,stdout);
+ fflush(stdout);
+ };
+ Assert(sp >= caml_stack_low);
+ Assert(sp <= caml_stack_high);
+#endif
+ curr_instr = *pc++;
+
+ dispatch_instr:
+ switch(curr_instr) {
+#endif
+
+/* Basic stack operations */
+
+ Instruct(ACC0):
+ accu = sp[0]; Next;
+ Instruct(ACC1):
+ accu = sp[1]; Next;
+ Instruct(ACC2):
+ accu = sp[2]; Next;
+ Instruct(ACC3):
+ accu = sp[3]; Next;
+ Instruct(ACC4):
+ accu = sp[4]; Next;
+ Instruct(ACC5):
+ accu = sp[5]; Next;
+ Instruct(ACC6):
+ accu = sp[6]; Next;
+ Instruct(ACC7):
+ accu = sp[7]; Next;
+
+ Instruct(PUSH): Instruct(PUSHACC0):
+ *--sp = accu; Next;
+ Instruct(PUSHACC1):
+ *--sp = accu; accu = sp[1]; Next;
+ Instruct(PUSHACC2):
+ *--sp = accu; accu = sp[2]; Next;
+ Instruct(PUSHACC3):
+ *--sp = accu; accu = sp[3]; Next;
+ Instruct(PUSHACC4):
+ *--sp = accu; accu = sp[4]; Next;
+ Instruct(PUSHACC5):
+ *--sp = accu; accu = sp[5]; Next;
+ Instruct(PUSHACC6):
+ *--sp = accu; accu = sp[6]; Next;
+ Instruct(PUSHACC7):
+ *--sp = accu; accu = sp[7]; Next;
+
+ Instruct(PUSHACC):
+ *--sp = accu;
+ /* Fallthrough */
+ Instruct(ACC):
+ accu = sp[*pc++];
+ Next;
+
+ Instruct(POP):
+ sp += *pc++;
+ Next;
+ Instruct(ASSIGN):
+ sp[*pc++] = accu;
+ accu = Val_unit;
+ Next;
+
+/* Access in heap-allocated environment */
+
+ Instruct(ENVACC1):
+ accu = Field(env, 1); Next;
+ Instruct(ENVACC2):
+ accu = Field(env, 2); Next;
+ Instruct(ENVACC3):
+ accu = Field(env, 3); Next;
+ Instruct(ENVACC4):
+ accu = Field(env, 4); Next;
+
+ Instruct(PUSHENVACC1):
+ *--sp = accu; accu = Field(env, 1); Next;
+ Instruct(PUSHENVACC2):
+ *--sp = accu; accu = Field(env, 2); Next;
+ Instruct(PUSHENVACC3):
+ *--sp = accu; accu = Field(env, 3); Next;
+ Instruct(PUSHENVACC4):
+ *--sp = accu; accu = Field(env, 4); Next;
+
+ Instruct(PUSHENVACC):
+ *--sp = accu;
+ /* Fallthrough */
+ Instruct(ENVACC):
+ accu = Field(env, *pc++);
+ Next;
+
+/* Function application */
+
+ Instruct(PUSH_RETADDR): {
+ sp -= 3;
+ sp[0] = (value) (pc + *pc);
+ sp[1] = env;
+ sp[2] = Val_long(extra_args);
+ pc++;
+ Next;
+ }
+ Instruct(APPLY): {
+ extra_args = *pc - 1;
+ pc = Code_val(accu);
+ env = accu;
+ goto check_stacks;
+ }
+ Instruct(APPLY1): {
+ value arg1 = sp[0];
+ sp -= 3;
+ sp[0] = arg1;
+ sp[1] = (value)pc;
+ sp[2] = env;
+ sp[3] = Val_long(extra_args);
+ pc = Code_val(accu);
+ env = accu;
+ extra_args = 0;
+ goto check_stacks;
+ }
+ Instruct(APPLY2): {
+ value arg1 = sp[0];
+ value arg2 = sp[1];
+ sp -= 3;
+ sp[0] = arg1;
+ sp[1] = arg2;
+ sp[2] = (value)pc;
+ sp[3] = env;
+ sp[4] = Val_long(extra_args);
+ pc = Code_val(accu);
+ env = accu;
+ extra_args = 1;
+ goto check_stacks;
+ }
+ Instruct(APPLY3): {
+ value arg1 = sp[0];
+ value arg2 = sp[1];
+ value arg3 = sp[2];
+ sp -= 3;
+ sp[0] = arg1;
+ sp[1] = arg2;
+ sp[2] = arg3;
+ sp[3] = (value)pc;
+ sp[4] = env;
+ sp[5] = Val_long(extra_args);
+ pc = Code_val(accu);
+ env = accu;
+ extra_args = 2;
+ goto check_stacks;
+ }
+
+ Instruct(APPTERM): {
+ int nargs = *pc++;
+ int slotsize = *pc;
+ value * newsp;
+ int i;
+ /* Slide the nargs bottom words of the current frame to the top
+ of the frame, and discard the remainder of the frame */
+ newsp = sp + slotsize - nargs;
+ for (i = nargs - 1; i >= 0; i--) newsp[i] = sp[i];
+ sp = newsp;
+ pc = Code_val(accu);
+ env = accu;
+ extra_args += nargs - 1;
+ goto check_stacks;
+ }
+ Instruct(APPTERM1): {
+ value arg1 = sp[0];
+ sp = sp + *pc - 1;
+ sp[0] = arg1;
+ pc = Code_val(accu);
+ env = accu;
+ goto check_stacks;
+ }
+ Instruct(APPTERM2): {
+ value arg1 = sp[0];
+ value arg2 = sp[1];
+ sp = sp + *pc - 2;
+ sp[0] = arg1;
+ sp[1] = arg2;
+ pc = Code_val(accu);
+ env = accu;
+ extra_args += 1;
+ goto check_stacks;
+ }
+ Instruct(APPTERM3): {
+ value arg1 = sp[0];
+ value arg2 = sp[1];
+ value arg3 = sp[2];
+ sp = sp + *pc - 3;
+ sp[0] = arg1;
+ sp[1] = arg2;
+ sp[2] = arg3;
+ pc = Code_val(accu);
+ env = accu;
+ extra_args += 2;
+ goto check_stacks;
+ }
+
+ Instruct(RETURN): {
+ sp += *pc++;
+ if (extra_args > 0) {
+ extra_args--;
+ pc = Code_val(accu);
+ env = accu;
+ } else {
+ pc = (code_t)(sp[0]);
+ env = sp[1];
+ extra_args = Long_val(sp[2]);
+ sp += 3;
+ }
+ Next;
+ }
+
+ Instruct(RESTART): {
+ int num_args = Wosize_val(env) - 2;
+ int i;
+ sp -= num_args;
+ for (i = 0; i < num_args; i++) sp[i] = Field(env, i + 2);
+ env = Field(env, 1);
+ extra_args += num_args;
+ Next;
+ }
+
+ Instruct(GRAB): {
+ int required = *pc++;
+ if (extra_args >= required) {
+ extra_args -= required;
+ } else {
+ mlsize_t num_args, i;
+ num_args = 1 + extra_args; /* arg1 + extra args */
+ Alloc_small(accu, num_args + 2, Closure_tag);
+ Field(accu, 1) = env;
+ for (i = 0; i < num_args; i++) Field(accu, i + 2) = sp[i];
+ Code_val(accu) = pc - 3; /* Point to the preceding RESTART instr. */
+ sp += num_args;
+ pc = (code_t)(sp[0]);
+ env = sp[1];
+ extra_args = Long_val(sp[2]);
+ sp += 3;
+ }
+ Next;
+ }
+
+ Instruct(CLOSURE): {
+ int nvars = *pc++;
+ int i;
+ if (nvars > 0) *--sp = accu;
+ if (nvars < Max_young_wosize) {
+ /* nvars + 1 <= Max_young_wosize, can allocate in minor heap */
+ Alloc_small(accu, 1 + nvars, Closure_tag);
+ for (i = 0; i < nvars; i++) Field(accu, i + 1) = sp[i];
+ } else {
+ /* PR#6385: must allocate in major heap */
+ /* caml_alloc_shr and caml_initialize never trigger a GC,
+ so no need to Setup_for_gc */
+ accu = caml_alloc_shr(1 + nvars, Closure_tag);
+ for (i = 0; i < nvars; i++) caml_initialize(&Field(accu, i + 1), sp[i]);
+ }
+ /* The code pointer is not in the heap, so no need to go through
+ caml_initialize. */
+ Code_val(accu) = pc + *pc;
+ pc++;
+ sp += nvars;
+ Next;
+ }
+
+ Instruct(CLOSUREREC): {
+ int nfuncs = *pc++;
+ int nvars = *pc++;
+ mlsize_t blksize = nfuncs * 2 - 1 + nvars;
+ int i;
+ value * p;
+ if (nvars > 0) *--sp = accu;
+ if (blksize <= Max_young_wosize) {
+ Alloc_small(accu, blksize, Closure_tag);
+ p = &Field(accu, nfuncs * 2 - 1);
+ for (i = 0; i < nvars; i++, p++) *p = sp[i];
+ } else {
+ /* PR#6385: must allocate in major heap */
+ /* caml_alloc_shr and caml_initialize never trigger a GC,
+ so no need to Setup_for_gc */
+ accu = caml_alloc_shr(blksize, Closure_tag);
+ p = &Field(accu, nfuncs * 2 - 1);
+ for (i = 0; i < nvars; i++, p++) caml_initialize(p, sp[i]);
+ }
+ sp += nvars;
+ /* The code pointers and infix headers are not in the heap,
+ so no need to go through caml_initialize. */
+ p = &Field(accu, 0);
+ *p = (value) (pc + pc[0]);
+ *--sp = accu;
+ p++;
+ for (i = 1; i < nfuncs; i++) {
+ *p = Make_header(i * 2, Infix_tag, Caml_white); /* color irrelevant. */
+ p++;
+ *p = (value) (pc + pc[i]);
+ *--sp = (value) p;
+ p++;
+ }
+ pc += nfuncs;
+ Next;
+ }
+
+ Instruct(PUSHOFFSETCLOSURE):
+ *--sp = accu; /* fallthrough */
+ Instruct(OFFSETCLOSURE):
+ accu = env + *pc++ * sizeof(value); Next;
+
+ Instruct(PUSHOFFSETCLOSUREM2):
+ *--sp = accu; /* fallthrough */
+ Instruct(OFFSETCLOSUREM2):
+ accu = env - 2 * sizeof(value); Next;
+ Instruct(PUSHOFFSETCLOSURE0):
+ *--sp = accu; /* fallthrough */
+ Instruct(OFFSETCLOSURE0):
+ accu = env; Next;
+ Instruct(PUSHOFFSETCLOSURE2):
+ *--sp = accu; /* fallthrough */
+ Instruct(OFFSETCLOSURE2):
+ accu = env + 2 * sizeof(value); Next;
+
+
+/* Access to global variables */
+
+ Instruct(PUSHGETGLOBAL):
+ *--sp = accu;
+ /* Fallthrough */
+ Instruct(GETGLOBAL):
+ accu = Field(caml_global_data, *pc);
+ pc++;
+ Next;
+
+ Instruct(PUSHGETGLOBALFIELD):
+ *--sp = accu;
+ /* Fallthrough */
+ Instruct(GETGLOBALFIELD): {
+ accu = Field(caml_global_data, *pc);
+ pc++;
+ accu = Field(accu, *pc);
+ pc++;
+ Next;
+ }
+
+ Instruct(SETGLOBAL):
+ caml_modify(&Field(caml_global_data, *pc), accu);
+ accu = Val_unit;
+ pc++;
+ Next;
+
+/* Allocation of blocks */
+
+ Instruct(PUSHATOM0):
+ *--sp = accu;
+ /* Fallthrough */
+ Instruct(ATOM0):
+ accu = Atom(0); Next;
+
+ Instruct(PUSHATOM):
+ *--sp = accu;
+ /* Fallthrough */
+ Instruct(ATOM):
+ accu = Atom(*pc++); Next;
+
+ Instruct(MAKEBLOCK): {
+ mlsize_t wosize = *pc++;
+ tag_t tag = *pc++;
+ mlsize_t i;
+ value block;
+ if (wosize <= Max_young_wosize) {
+ Alloc_small(block, wosize, tag);
+ Field(block, 0) = accu;
+ for (i = 1; i < wosize; i++) Field(block, i) = *sp++;
+ } else {
+ block = caml_alloc_shr(wosize, tag);
+ caml_initialize(&Field(block, 0), accu);
+ for (i = 1; i < wosize; i++) caml_initialize(&Field(block, i), *sp++);
+ }
+ accu = block;
+ Next;
+ }
+ Instruct(MAKEBLOCK1): {
+ tag_t tag = *pc++;
+ value block;
+ Alloc_small(block, 1, tag);
+ Field(block, 0) = accu;
+ accu = block;
+ Next;
+ }
+ Instruct(MAKEBLOCK2): {
+ tag_t tag = *pc++;
+ value block;
+ Alloc_small(block, 2, tag);
+ Field(block, 0) = accu;
+ Field(block, 1) = sp[0];
+ sp += 1;
+ accu = block;
+ Next;
+ }
+ Instruct(MAKEBLOCK3): {
+ tag_t tag = *pc++;
+ value block;
+ Alloc_small(block, 3, tag);
+ Field(block, 0) = accu;
+ Field(block, 1) = sp[0];
+ Field(block, 2) = sp[1];
+ sp += 2;
+ accu = block;
+ Next;
+ }
+ Instruct(MAKEFLOATBLOCK): {
+ mlsize_t size = *pc++;
+ mlsize_t i;
+ value block;
+ if (size <= Max_young_wosize / Double_wosize) {
+ Alloc_small(block, size * Double_wosize, Double_array_tag);
+ } else {
+ block = caml_alloc_shr(size * Double_wosize, Double_array_tag);
+ }
+ Store_double_field(block, 0, Double_val(accu));
+ for (i = 1; i < size; i++){
+ Store_double_field(block, i, Double_val(*sp));
+ ++ sp;
+ }
+ accu = block;
+ Next;
+ }
+
+/* Access to components of blocks */
+
+ Instruct(GETFIELD0):
+ accu = Field(accu, 0); Next;
+ Instruct(GETFIELD1):
+ accu = Field(accu, 1); Next;
+ Instruct(GETFIELD2):
+ accu = Field(accu, 2); Next;
+ Instruct(GETFIELD3):
+ accu = Field(accu, 3); Next;
+ Instruct(GETFIELD):
+ accu = Field(accu, *pc); pc++; Next;
+ Instruct(GETFLOATFIELD): {
+ double d = Double_field(accu, *pc);
+ Alloc_small(accu, Double_wosize, Double_tag);
+ Store_double_val(accu, d);
+ pc++;
+ Next;
+ }
+
+ Instruct(SETFIELD0):
+ caml_modify(&Field(accu, 0), *sp++);
+ accu = Val_unit;
+ Next;
+ Instruct(SETFIELD1):
+ caml_modify(&Field(accu, 1), *sp++);
+ accu = Val_unit;
+ Next;
+ Instruct(SETFIELD2):
+ caml_modify(&Field(accu, 2), *sp++);
+ accu = Val_unit;
+ Next;
+ Instruct(SETFIELD3):
+ caml_modify(&Field(accu, 3), *sp++);
+ accu = Val_unit;
+ Next;
+ Instruct(SETFIELD):
+ caml_modify(&Field(accu, *pc), *sp++);
+ accu = Val_unit;
+ pc++;
+ Next;
+ Instruct(SETFLOATFIELD):
+ Store_double_field(accu, *pc, Double_val(*sp));
+ accu = Val_unit;
+ sp++;
+ pc++;
+ Next;
+
+/* Array operations */
+
+ Instruct(VECTLENGTH): {
+ mlsize_t size = Wosize_val(accu);
+ if (Tag_val(accu) == Double_array_tag) size = size / Double_wosize;
+ accu = Val_long(size);
+ Next;
+ }
+ Instruct(GETVECTITEM):
+ accu = Field(accu, Long_val(sp[0]));
+ sp += 1;
+ Next;
+ Instruct(SETVECTITEM):
+ caml_modify(&Field(accu, Long_val(sp[0])), sp[1]);
+ accu = Val_unit;
+ sp += 2;
+ Next;
+
+/* String operations */
+
+ Instruct(GETSTRINGCHAR):
+ accu = Val_int(Byte_u(accu, Long_val(sp[0])));
+ sp += 1;
+ Next;
+ Instruct(SETSTRINGCHAR):
+ Byte_u(accu, Long_val(sp[0])) = Int_val(sp[1]);
+ sp += 2;
+ accu = Val_unit;
+ Next;
+
+/* Branches and conditional branches */
+
+ Instruct(BRANCH):
+ pc += *pc;
+ Next;
+ Instruct(BRANCHIF):
+ if (accu != Val_false) pc += *pc; else pc++;
+ Next;
+ Instruct(BRANCHIFNOT):
+ if (accu == Val_false) pc += *pc; else pc++;
+ Next;
+ Instruct(SWITCH): {
+ uint32_t sizes = *pc++;
+ if (Is_block(accu)) {
+ intnat index = Tag_val(accu);
+ Assert ((uintnat) index < (sizes >> 16));
+ pc += pc[(sizes & 0xFFFF) + index];
+ } else {
+ intnat index = Long_val(accu);
+ Assert ((uintnat) index < (sizes & 0xFFFF)) ;
+ pc += pc[index];
+ }
+ Next;
+ }
+ Instruct(BOOLNOT):
+ accu = Val_not(accu);
+ Next;
+
+/* Exceptions */
+
+ Instruct(PUSHTRAP):
+ sp -= 4;
+ Trap_pc(sp) = pc + *pc;
+ Trap_link(sp) = caml_trapsp;
+ sp[2] = env;
+ sp[3] = Val_long(extra_args);
+ caml_trapsp = sp;
+ pc++;
+ Next;
+
+ Instruct(POPTRAP):
+ if (caml_something_to_do) {
+ /* We must check here so that if a signal is pending and its
+ handler triggers an exception, the exception is trapped
+ by the current try...with, not the enclosing one. */
+ pc--; /* restart the POPTRAP after processing the signal */
+ goto process_signal;
+ }
+ caml_trapsp = Trap_link(sp);
+ sp += 4;
+ Next;
+
+ Instruct(RAISE_NOTRACE):
+ if (caml_trapsp >= caml_trap_barrier) caml_debugger(TRAP_BARRIER);
+ goto raise_notrace;
+
+ Instruct(RERAISE):
+ if (caml_trapsp >= caml_trap_barrier) caml_debugger(TRAP_BARRIER);
+ if (caml_backtrace_active) caml_stash_backtrace(accu, pc, sp, 1);
+ goto raise_notrace;
+
+ Instruct(RAISE):
+ raise_exception:
+ if (caml_trapsp >= caml_trap_barrier) caml_debugger(TRAP_BARRIER);
+ if (caml_backtrace_active) caml_stash_backtrace(accu, pc, sp, 0);
+ raise_notrace:
+ if ((char *) caml_trapsp
+ >= (char *) caml_stack_high - initial_sp_offset) {
+ caml_external_raise = initial_external_raise;
+ caml_extern_sp = (value *) ((char *) caml_stack_high
+ - initial_sp_offset);
+ caml_callback_depth--;
+ return Make_exception_result(accu);
+ }
+ sp = caml_trapsp;
+ pc = Trap_pc(sp);
+ caml_trapsp = Trap_link(sp);
+ env = sp[2];
+ extra_args = Long_val(sp[3]);
+ sp += 4;
+ Next;
+
+/* Stack checks */
+
+ check_stacks:
+ if (sp < caml_stack_threshold) {
+ caml_extern_sp = sp;
+ caml_realloc_stack(Stack_threshold / sizeof(value));
+ sp = caml_extern_sp;
+ }
+ /* Fall through CHECK_SIGNALS */
+
+/* Signal handling */
+
+ Instruct(CHECK_SIGNALS): /* accu not preserved */
+ if (caml_something_to_do) goto process_signal;
+ Next;
+
+ process_signal:
+ caml_something_to_do = 0;
+ Setup_for_event;
+ caml_process_event();
+ Restore_after_event;
+ Next;
+
+/* Calling C functions */
+
+ Instruct(C_CALL1):
+ Setup_for_c_call;
+ accu = Primitive(*pc)(accu);
+ Restore_after_c_call;
+ pc++;
+ Next;
+ Instruct(C_CALL2):
+ Setup_for_c_call;
+ accu = Primitive(*pc)(accu, sp[1]);
+ Restore_after_c_call;
+ sp += 1;
+ pc++;
+ Next;
+ Instruct(C_CALL3):
+ Setup_for_c_call;
+ accu = Primitive(*pc)(accu, sp[1], sp[2]);
+ Restore_after_c_call;
+ sp += 2;
+ pc++;
+ Next;
+ Instruct(C_CALL4):
+ Setup_for_c_call;
+ accu = Primitive(*pc)(accu, sp[1], sp[2], sp[3]);
+ Restore_after_c_call;
+ sp += 3;
+ pc++;
+ Next;
+ Instruct(C_CALL5):
+ Setup_for_c_call;
+ accu = Primitive(*pc)(accu, sp[1], sp[2], sp[3], sp[4]);
+ Restore_after_c_call;
+ sp += 4;
+ pc++;
+ Next;
+ Instruct(C_CALLN): {
+ int nargs = *pc++;
+ *--sp = accu;
+ Setup_for_c_call;
+ accu = Primitive(*pc)(sp + 1, nargs);
+ Restore_after_c_call;
+ sp += nargs;
+ pc++;
+ Next;
+ }
+
+/* Integer constants */
+
+ Instruct(CONST0):
+ accu = Val_int(0); Next;
+ Instruct(CONST1):
+ accu = Val_int(1); Next;
+ Instruct(CONST2):
+ accu = Val_int(2); Next;
+ Instruct(CONST3):
+ accu = Val_int(3); Next;
+
+ Instruct(PUSHCONST0):
+ *--sp = accu; accu = Val_int(0); Next;
+ Instruct(PUSHCONST1):
+ *--sp = accu; accu = Val_int(1); Next;
+ Instruct(PUSHCONST2):
+ *--sp = accu; accu = Val_int(2); Next;
+ Instruct(PUSHCONST3):
+ *--sp = accu; accu = Val_int(3); Next;
+
+ Instruct(PUSHCONSTINT):
+ *--sp = accu;
+ /* Fallthrough */
+ Instruct(CONSTINT):
+ accu = Val_int(*pc);
+ pc++;
+ Next;
+
+/* Integer arithmetic */
+
+ Instruct(NEGINT):
+ accu = (value)(2 - (intnat)accu); Next;
+ Instruct(ADDINT):
+ accu = (value)((intnat) accu + (intnat) *sp++ - 1); Next;
+ Instruct(SUBINT):
+ accu = (value)((intnat) accu - (intnat) *sp++ + 1); Next;
+ Instruct(MULINT):
+ accu = Val_long(Long_val(accu) * Long_val(*sp++)); Next;
+
+ Instruct(DIVINT): {
+ intnat divisor = Long_val(*sp++);
+ if (divisor == 0) { Setup_for_c_call; caml_raise_zero_divide(); }
+ accu = Val_long(Long_val(accu) / divisor);
+ Next;
+ }
+ Instruct(MODINT): {
+ intnat divisor = Long_val(*sp++);
+ if (divisor == 0) { Setup_for_c_call; caml_raise_zero_divide(); }
+ accu = Val_long(Long_val(accu) % divisor);
+ Next;
+ }
+ Instruct(ANDINT):
+ accu = (value)((intnat) accu & (intnat) *sp++); Next;
+ Instruct(ORINT):
+ accu = (value)((intnat) accu | (intnat) *sp++); Next;
+ Instruct(XORINT):
+ accu = (value)(((intnat) accu ^ (intnat) *sp++) | 1); Next;
+ Instruct(LSLINT):
+ accu = (value)((((intnat) accu - 1) << Long_val(*sp++)) + 1); Next;
+ Instruct(LSRINT):
+ accu = (value)((((uintnat) accu - 1) >> Long_val(*sp++)) | 1);
+ Next;
+ Instruct(ASRINT):
+ accu = (value)((((intnat) accu - 1) >> Long_val(*sp++)) | 1); Next;
+
+#define Integer_comparison(typ,opname,tst) \
+ Instruct(opname): \
+ accu = Val_int((typ) accu tst (typ) *sp++); Next;
+
+ Integer_comparison(intnat,EQ, ==)
+ Integer_comparison(intnat,NEQ, !=)
+ Integer_comparison(intnat,LTINT, <)
+ Integer_comparison(intnat,LEINT, <=)
+ Integer_comparison(intnat,GTINT, >)
+ Integer_comparison(intnat,GEINT, >=)
+ Integer_comparison(uintnat,ULTINT, <)
+ Integer_comparison(uintnat,UGEINT, >=)
+
+#define Integer_branch_comparison(typ,opname,tst,debug) \
+ Instruct(opname): \
+ if ( *pc++ tst (typ) Long_val(accu)) { \
+ pc += *pc ; \
+ } else { \
+ pc++ ; \
+ } ; Next;
+
+ Integer_branch_comparison(intnat,BEQ, ==, "==")
+ Integer_branch_comparison(intnat,BNEQ, !=, "!=")
+ Integer_branch_comparison(intnat,BLTINT, <, "<")
+ Integer_branch_comparison(intnat,BLEINT, <=, "<=")
+ Integer_branch_comparison(intnat,BGTINT, >, ">")
+ Integer_branch_comparison(intnat,BGEINT, >=, ">=")
+ Integer_branch_comparison(uintnat,BULTINT, <, "<")
+ Integer_branch_comparison(uintnat,BUGEINT, >=, ">=")
+
+ Instruct(OFFSETINT):
+ accu += *pc << 1;
+ pc++;
+ Next;
+ Instruct(OFFSETREF):
+ Field(accu, 0) += *pc << 1;
+ accu = Val_unit;
+ pc++;
+ Next;
+ Instruct(ISINT):
+ accu = Val_long(accu & 1);
+ Next;
+
+/* Object-oriented operations */
+
+#define Lookup(obj, lab) Field (Field (obj, 0), Int_val(lab))
+
+ /* please don't forget to keep below code in sync with the
+ functions caml_cache_public_method and
+ caml_cache_public_method2 in obj.c */
+
+ Instruct(GETMETHOD):
+ accu = Lookup(sp[0], accu);
+ Next;
+
+#define CAML_METHOD_CACHE
+#ifdef CAML_METHOD_CACHE
+ Instruct(GETPUBMET): {
+ /* accu == object, pc[0] == tag, pc[1] == cache */
+ value meths = Field (accu, 0);
+ value ofs;
+#ifdef CAML_TEST_CACHE
+ static int calls = 0, hits = 0;
+ if (calls >= 10000000) {
+ fprintf(stderr, "cache hit = %d%%\n", hits / 100000);
+ calls = 0; hits = 0;
+ }
+ calls++;
+#endif
+ *--sp = accu;
+ accu = Val_int(*pc++);
+ ofs = *pc & Field(meths,1);
+ if (*(value*)(((char*)&Field(meths,3)) + ofs) == accu) {
+#ifdef CAML_TEST_CACHE
+ hits++;
+#endif
+ accu = *(value*)(((char*)&Field(meths,2)) + ofs);
+ }
+ else
+ {
+ int li = 3, hi = Field(meths,0), mi;
+ while (li < hi) {
+ mi = ((li+hi) >> 1) | 1;
+ if (accu < Field(meths,mi)) hi = mi-2;
+ else li = mi;
+ }
+ *pc = (li-3)*sizeof(value);
+ accu = Field (meths, li-1);
+ }
+ pc++;
+ Next;
+ }
+#else
+ Instruct(GETPUBMET):
+ *--sp = accu;
+ accu = Val_int(*pc);
+ pc += 2;
+ /* Fallthrough */
+#endif
+ Instruct(GETDYNMET): {
+ /* accu == tag, sp[0] == object, *pc == cache */
+ value meths = Field (sp[0], 0);
+ int li = 3, hi = Field(meths,0), mi;
+ while (li < hi) {
+ mi = ((li+hi) >> 1) | 1;
+ if (accu < Field(meths,mi)) hi = mi-2;
+ else li = mi;
+ }
+ accu = Field (meths, li-1);
+ Next;
+ }
+
+/* Debugging and machine control */
+
+ Instruct(STOP):
+ caml_external_raise = initial_external_raise;
+ caml_extern_sp = sp;
+ caml_callback_depth--;
+ return accu;
+
+ Instruct(EVENT):
+ if (--caml_event_count == 0) {
+ Setup_for_debugger;
+ caml_debugger(EVENT_COUNT);
+ Restore_after_debugger;
+ }
+ Restart_curr_instr;
+
+ Instruct(BREAK):
+ Setup_for_debugger;
+ caml_debugger(BREAKPOINT);
+ Restore_after_debugger;
+ Restart_curr_instr;
+
+#ifndef THREADED_CODE
+ default:
+#if _MSC_VER >= 1200
+ __assume(0);
+#else
+ caml_fatal_error_arg("Fatal error: bad opcode (%"
+ ARCH_INTNAT_PRINTF_FORMAT "x)\n",
+ (char *) (intnat) *(pc-1));
+#endif
+ }
+ }
+#endif
+}
+
+void caml_prepare_bytecode(code_t prog, asize_t prog_size) {
+ /* other implementations of the interpreter (such as an hypothetical
+ JIT translator) might want to do something with a bytecode before
+ running it */
+ Assert(prog);
+ Assert(prog_size>0);
+ /* actually, the threading of the bytecode might be done here */
+}
+
+void caml_release_bytecode(code_t prog, asize_t prog_size) {
+ /* other implementations of the interpreter (such as an hypothetical
+ JIT translator) might want to know when a bytecode is removed */
+ /* check that we have a program */
+ Assert(prog);
+ Assert(prog_size>0);
+}
diff --git a/byterun/ints.c b/byterun/ints.c
new file mode 100644
index 0000000000..bfc622fcf5
--- /dev/null
+++ b/byterun/ints.c
@@ -0,0 +1,780 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/intext.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+
+static char * parse_sign_and_base(char * p,
+ /*out*/ int * base,
+ /*out*/ int * signedness,
+ /*out*/ int * sign)
+{
+ *sign = 1;
+ if (*p == '-') {
+ *sign = -1;
+ p++;
+ } else if (*p == '+')
+ p++;
+ *base = 10; *signedness = 1;
+ if (*p == '0') {
+ switch (p[1]) {
+ case 'x': case 'X':
+ *base = 16; *signedness = 0; p += 2; break;
+ case 'o': case 'O':
+ *base = 8; *signedness = 0; p += 2; break;
+ case 'b': case 'B':
+ *base = 2; *signedness = 0; p += 2; break;
+ case 'u': case 'U':
+ *signedness = 0; p += 2; break;
+ }
+ }
+ return p;
+}
+
+static int parse_digit(char c)
+{
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ else if (c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
+ else if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ else
+ return -1;
+}
+
+#define INT_ERRMSG "int_of_string"
+#define INT32_ERRMSG "Int32.of_string"
+#define INT64_ERRMSG "Int64.of_string"
+#define INTNAT_ERRMSG "Nativeint.of_string"
+
+static intnat parse_intnat(value s, int nbits, const char *errmsg)
+{
+ char * p;
+ uintnat res, threshold;
+ int sign, base, signedness, d;
+
+ p = parse_sign_and_base(String_val(s), &base, &signedness, &sign);
+ threshold = ((uintnat) -1) / base;
+ d = parse_digit(*p);
+ if (d < 0 || d >= base) caml_failwith(errmsg);
+ for (p++, res = d; /*nothing*/; p++) {
+ char c = *p;
+ if (c == '_') continue;
+ d = parse_digit(c);
+ if (d < 0 || d >= base) break;
+ /* Detect overflow in multiplication base * res */
+ if (res > threshold) caml_failwith(errmsg);
+ res = base * res + d;
+ /* Detect overflow in addition (base * res) + d */
+ if (res < (uintnat) d) caml_failwith(errmsg);
+ }
+ if (p != String_val(s) + caml_string_length(s)){
+ caml_failwith(errmsg);
+ }
+ if (signedness) {
+ /* Signed representation expected, allow -2^(nbits-1) to 2^(nbits-1) - 1 */
+ if (sign >= 0) {
+ if (res >= (uintnat)1 << (nbits - 1)) caml_failwith(errmsg);
+ } else {
+ if (res > (uintnat)1 << (nbits - 1)) caml_failwith(errmsg);
+ }
+ } else {
+ /* Unsigned representation expected, allow 0 to 2^nbits - 1
+ and tolerate -(2^nbits - 1) to 0 */
+ if (nbits < sizeof(uintnat) * 8 && res >= (uintnat)1 << nbits)
+ caml_failwith(errmsg);
+ }
+ return sign < 0 ? -((intnat) res) : (intnat) res;
+}
+
+value caml_bswap16_direct(value x)
+{
+ return ((((x & 0x00FF) << 8) |
+ ((x & 0xFF00) >> 8)));
+}
+
+CAMLprim value caml_bswap16(value v)
+{
+ intnat x = Int_val(v);
+ return (Val_int ((((x & 0x00FF) << 8) |
+ ((x & 0xFF00) >> 8))));
+}
+
+/* Tagged integers */
+
+CAMLprim value caml_int_compare(value v1, value v2)
+{
+ int res = (v1 > v2) - (v1 < v2);
+ return Val_int(res);
+}
+
+CAMLprim value caml_int_of_string(value s)
+{
+ return Val_long(parse_intnat(s, 8 * sizeof(value) - 1, INT_ERRMSG));
+}
+
+#define FORMAT_BUFFER_SIZE 32
+
+static char parse_format(value fmt,
+ char * suffix,
+ char format_string[FORMAT_BUFFER_SIZE])
+{
+ char * p;
+ char lastletter;
+ mlsize_t len, len_suffix;
+
+ /* Copy OCaml format fmt to format_string,
+ adding the suffix before the last letter of the format */
+ len = caml_string_length(fmt);
+ len_suffix = strlen(suffix);
+ if (len + len_suffix + 1 >= FORMAT_BUFFER_SIZE)
+ caml_invalid_argument("format_int: format too long");
+ memmove(format_string, String_val(fmt), len);
+ p = format_string + len - 1;
+ lastletter = *p;
+ /* Compress two-letter formats, ignoring the [lnL] annotation */
+ if (p[-1] == 'l' || p[-1] == 'n' || p[-1] == 'L') p--;
+ memmove(p, suffix, len_suffix); p += len_suffix;
+ *p++ = lastletter;
+ *p = 0;
+ /* Return the conversion type (last letter) */
+ return lastletter;
+}
+
+CAMLprim value caml_format_int(value fmt, value arg)
+{
+ char format_string[FORMAT_BUFFER_SIZE];
+ char conv;
+ value res;
+
+ conv = parse_format(fmt, ARCH_INTNAT_PRINTF_FORMAT, format_string);
+ switch (conv) {
+ case 'u': case 'x': case 'X': case 'o':
+ res = caml_alloc_sprintf(format_string, Unsigned_long_val(arg));
+ break;
+ default:
+ res = caml_alloc_sprintf(format_string, Long_val(arg));
+ break;
+ }
+ return res;
+}
+
+/* 32-bit integers */
+
+static int int32_cmp(value v1, value v2)
+{
+ int32_t i1 = Int32_val(v1);
+ int32_t i2 = Int32_val(v2);
+ return (i1 > i2) - (i1 < i2);
+}
+
+static intnat int32_hash(value v)
+{
+ return Int32_val(v);
+}
+
+static void int32_serialize(value v, uintnat * bsize_32,
+ uintnat * bsize_64)
+{
+ caml_serialize_int_4(Int32_val(v));
+ *bsize_32 = *bsize_64 = 4;
+}
+
+static uintnat int32_deserialize(void * dst)
+{
+ *((int32_t *) dst) = caml_deserialize_sint_4();
+ return 4;
+}
+
+CAMLexport struct custom_operations caml_int32_ops = {
+ "_i",
+ custom_finalize_default,
+ int32_cmp,
+ int32_hash,
+ int32_serialize,
+ int32_deserialize,
+ custom_compare_ext_default
+};
+
+CAMLexport value caml_copy_int32(int32_t i)
+{
+ value res = caml_alloc_custom(&caml_int32_ops, 4, 0, 1);
+ Int32_val(res) = i;
+ return res;
+}
+
+CAMLprim value caml_int32_neg(value v)
+{ return caml_copy_int32(- Int32_val(v)); }
+
+CAMLprim value caml_int32_add(value v1, value v2)
+{ return caml_copy_int32(Int32_val(v1) + Int32_val(v2)); }
+
+CAMLprim value caml_int32_sub(value v1, value v2)
+{ return caml_copy_int32(Int32_val(v1) - Int32_val(v2)); }
+
+CAMLprim value caml_int32_mul(value v1, value v2)
+{ return caml_copy_int32(Int32_val(v1) * Int32_val(v2)); }
+
+CAMLprim value caml_int32_div(value v1, value v2)
+{
+ int32_t dividend = Int32_val(v1);
+ int32_t divisor = Int32_val(v2);
+ if (divisor == 0) caml_raise_zero_divide();
+ /* PR#4740: on some processors, division crashes on overflow.
+ Implement the same behavior as for type "int". */
+ if (dividend == (1<<31) && divisor == -1) return v1;
+ return caml_copy_int32(dividend / divisor);
+}
+
+CAMLprim value caml_int32_mod(value v1, value v2)
+{
+ int32_t dividend = Int32_val(v1);
+ int32_t divisor = Int32_val(v2);
+ if (divisor == 0) caml_raise_zero_divide();
+ /* PR#4740: on some processors, modulus crashes if division overflows.
+ Implement the same behavior as for type "int". */
+ if (dividend == (1<<31) && divisor == -1) return caml_copy_int32(0);
+ return caml_copy_int32(dividend % divisor);
+}
+
+CAMLprim value caml_int32_and(value v1, value v2)
+{ return caml_copy_int32(Int32_val(v1) & Int32_val(v2)); }
+
+CAMLprim value caml_int32_or(value v1, value v2)
+{ return caml_copy_int32(Int32_val(v1) | Int32_val(v2)); }
+
+CAMLprim value caml_int32_xor(value v1, value v2)
+{ return caml_copy_int32(Int32_val(v1) ^ Int32_val(v2)); }
+
+CAMLprim value caml_int32_shift_left(value v1, value v2)
+{ return caml_copy_int32(Int32_val(v1) << Int_val(v2)); }
+
+CAMLprim value caml_int32_shift_right(value v1, value v2)
+{ return caml_copy_int32(Int32_val(v1) >> Int_val(v2)); }
+
+CAMLprim value caml_int32_shift_right_unsigned(value v1, value v2)
+{ return caml_copy_int32((uint32_t)Int32_val(v1) >> Int_val(v2)); }
+
+static int32_t caml_swap32(int32_t x)
+{
+ return (((x & 0x000000FF) << 24) |
+ ((x & 0x0000FF00) << 8) |
+ ((x & 0x00FF0000) >> 8) |
+ ((x & 0xFF000000) >> 24));
+}
+
+value caml_int32_direct_bswap(value v)
+{ return caml_swap32(v); }
+
+CAMLprim value caml_int32_bswap(value v)
+{ return caml_copy_int32(caml_swap32(Int32_val(v))); }
+
+CAMLprim value caml_int32_of_int(value v)
+{ return caml_copy_int32(Long_val(v)); }
+
+CAMLprim value caml_int32_to_int(value v)
+{ return Val_long(Int32_val(v)); }
+
+CAMLprim value caml_int32_of_float(value v)
+{ return caml_copy_int32((int32_t)(Double_val(v))); }
+
+CAMLprim value caml_int32_to_float(value v)
+{ return caml_copy_double((double)(Int32_val(v))); }
+
+CAMLprim value caml_int32_compare(value v1, value v2)
+{
+ int32_t i1 = Int32_val(v1);
+ int32_t i2 = Int32_val(v2);
+ int res = (i1 > i2) - (i1 < i2);
+ return Val_int(res);
+}
+
+CAMLprim value caml_int32_format(value fmt, value arg)
+{
+ char format_string[FORMAT_BUFFER_SIZE];
+
+ parse_format(fmt, ARCH_INT32_PRINTF_FORMAT, format_string);
+ return caml_alloc_sprintf(format_string, Int32_val(arg));
+}
+
+CAMLprim value caml_int32_of_string(value s)
+{
+ return caml_copy_int32(parse_intnat(s, 32, INT32_ERRMSG));
+}
+
+CAMLprim value caml_int32_bits_of_float(value vd)
+{
+ union { float d; int32_t i; } u;
+ u.d = Double_val(vd);
+ return caml_copy_int32(u.i);
+}
+
+CAMLprim value caml_int32_float_of_bits(value vi)
+{
+ union { float d; int32_t i; } u;
+ u.i = Int32_val(vi);
+ return caml_copy_double(u.d);
+}
+
+/* 64-bit integers */
+
+#ifdef ARCH_ALIGN_INT64
+
+CAMLexport int64_t caml_Int64_val(value v)
+{
+ union { int32_t i[2]; int64_t j; } buffer;
+ buffer.i[0] = ((int32_t *) Data_custom_val(v))[0];
+ buffer.i[1] = ((int32_t *) Data_custom_val(v))[1];
+ return buffer.j;
+}
+
+#endif
+
+static int int64_cmp(value v1, value v2)
+{
+ int64_t i1 = Int64_val(v1);
+ int64_t i2 = Int64_val(v2);
+ return (i1 > i2) - (i1 < i2);
+}
+
+static intnat int64_hash(value v)
+{
+ int64_t x = Int64_val(v);
+ uint32_t lo = (uint32_t) x, hi = (uint32_t) (x >> 32);
+ return hi ^ lo;
+}
+
+static void int64_serialize(value v, uintnat * bsize_32,
+ uintnat * bsize_64)
+{
+ caml_serialize_int_8(Int64_val(v));
+ *bsize_32 = *bsize_64 = 8;
+}
+
+static uintnat int64_deserialize(void * dst)
+{
+#ifndef ARCH_ALIGN_INT64
+ *((int64_t *) dst) = caml_deserialize_sint_8();
+#else
+ union { int32_t i[2]; int64_t j; } buffer;
+ buffer.j = caml_deserialize_sint_8();
+ ((int32_t *) dst)[0] = buffer.i[0];
+ ((int32_t *) dst)[1] = buffer.i[1];
+#endif
+ return 8;
+}
+
+CAMLexport struct custom_operations caml_int64_ops = {
+ "_j",
+ custom_finalize_default,
+ int64_cmp,
+ int64_hash,
+ int64_serialize,
+ int64_deserialize,
+ custom_compare_ext_default
+};
+
+CAMLexport value caml_copy_int64(int64_t i)
+{
+ value res = caml_alloc_custom(&caml_int64_ops, 8, 0, 1);
+#ifndef ARCH_ALIGN_INT64
+ Int64_val(res) = i;
+#else
+ union { int32_t i[2]; int64_t j; } buffer;
+ buffer.j = i;
+ ((int32_t *) Data_custom_val(res))[0] = buffer.i[0];
+ ((int32_t *) Data_custom_val(res))[1] = buffer.i[1];
+#endif
+ return res;
+}
+
+CAMLprim value caml_int64_neg(value v)
+{ return caml_copy_int64(- Int64_val(v)); }
+
+CAMLprim value caml_int64_add(value v1, value v2)
+{ return caml_copy_int64(Int64_val(v1) + Int64_val(v2)); }
+
+CAMLprim value caml_int64_sub(value v1, value v2)
+{ return caml_copy_int64(Int64_val(v1) - Int64_val(v2)); }
+
+CAMLprim value caml_int64_mul(value v1, value v2)
+{ return caml_copy_int64(Int64_val(v1) * Int64_val(v2)); }
+
+#define Int64_min_int ((intnat) 1 << (sizeof(intnat) * 8 - 1))
+
+CAMLprim value caml_int64_div(value v1, value v2)
+{
+ int64_t dividend = Int64_val(v1);
+ int64_t divisor = Int64_val(v2);
+ if (divisor == 0) caml_raise_zero_divide();
+ /* PR#4740: on some processors, division crashes on overflow.
+ Implement the same behavior as for type "int". */
+ if (dividend == ((int64_t)1 << 63) && divisor == -1) return v1;
+ return caml_copy_int64(Int64_val(v1) / divisor);
+}
+
+CAMLprim value caml_int64_mod(value v1, value v2)
+{
+ int64_t dividend = Int64_val(v1);
+ int64_t divisor = Int64_val(v2);
+ if (divisor == 0) caml_raise_zero_divide();
+ /* PR#4740: on some processors, division crashes on overflow.
+ Implement the same behavior as for type "int". */
+ if (dividend == ((int64_t)1 << 63) && divisor == -1){
+ return caml_copy_int64(0);
+ }
+ return caml_copy_int64(Int64_val(v1) % divisor);
+}
+
+CAMLprim value caml_int64_and(value v1, value v2)
+{ return caml_copy_int64(Int64_val(v1) & Int64_val(v2)); }
+
+CAMLprim value caml_int64_or(value v1, value v2)
+{ return caml_copy_int64(Int64_val(v1) | Int64_val(v2)); }
+
+CAMLprim value caml_int64_xor(value v1, value v2)
+{ return caml_copy_int64(Int64_val(v1) ^ Int64_val(v2)); }
+
+CAMLprim value caml_int64_shift_left(value v1, value v2)
+{ return caml_copy_int64(Int64_val(v1) << Int_val(v2)); }
+
+CAMLprim value caml_int64_shift_right(value v1, value v2)
+{ return caml_copy_int64(Int64_val(v1) >> Int_val(v2)); }
+
+CAMLprim value caml_int64_shift_right_unsigned(value v1, value v2)
+{ return caml_copy_int64((uint64_t) (Int64_val(v1)) >> Int_val(v2)); }
+
+#ifdef ARCH_SIXTYFOUR
+static value caml_swap64(value x)
+{
+ return (((((x) & 0x00000000000000FF) << 56) |
+ (((x) & 0x000000000000FF00) << 40) |
+ (((x) & 0x0000000000FF0000) << 24) |
+ (((x) & 0x00000000FF000000) << 8) |
+ (((x) & 0x000000FF00000000) >> 8) |
+ (((x) & 0x0000FF0000000000) >> 24) |
+ (((x) & 0x00FF000000000000) >> 40) |
+ (((x) & 0xFF00000000000000) >> 56)));
+}
+
+value caml_int64_direct_bswap(value v)
+{ return caml_swap64(v); }
+#endif
+
+CAMLprim value caml_int64_bswap(value v)
+{
+ int64_t x = Int64_val(v);
+ return caml_copy_int64
+ (((x & 0x00000000000000FFULL) << 56) |
+ ((x & 0x000000000000FF00ULL) << 40) |
+ ((x & 0x0000000000FF0000ULL) << 24) |
+ ((x & 0x00000000FF000000ULL) << 8) |
+ ((x & 0x000000FF00000000ULL) >> 8) |
+ ((x & 0x0000FF0000000000ULL) >> 24) |
+ ((x & 0x00FF000000000000ULL) >> 40) |
+ ((x & 0xFF00000000000000ULL) >> 56));
+}
+
+CAMLprim value caml_int64_of_int(value v)
+{ return caml_copy_int64((int64_t) (Long_val(v))); }
+
+CAMLprim value caml_int64_to_int(value v)
+{ return Val_long((intnat) (Int64_val(v))); }
+
+CAMLprim value caml_int64_of_float(value v)
+{ return caml_copy_int64((int64_t) (Double_val(v))); }
+
+CAMLprim value caml_int64_to_float(value v)
+{ return caml_copy_double((double) (Int64_val(v))); }
+
+CAMLprim value caml_int64_of_int32(value v)
+{ return caml_copy_int64((int64_t) (Int32_val(v))); }
+
+CAMLprim value caml_int64_to_int32(value v)
+{ return caml_copy_int32((int32_t) (Int64_val(v))); }
+
+CAMLprim value caml_int64_of_nativeint(value v)
+{ return caml_copy_int64((int64_t) (Nativeint_val(v))); }
+
+CAMLprim value caml_int64_to_nativeint(value v)
+{ return caml_copy_nativeint((intnat) (Int64_val(v))); }
+
+CAMLprim value caml_int64_compare(value v1, value v2)
+{
+ int64_t i1 = Int64_val(v1);
+ int64_t i2 = Int64_val(v2);
+ return Val_int((i1 > i2) - (i1 < i2));
+}
+
+CAMLprim value caml_int64_format(value fmt, value arg)
+{
+ char format_string[FORMAT_BUFFER_SIZE];
+
+ parse_format(fmt, ARCH_INT64_PRINTF_FORMAT, format_string);
+ return caml_alloc_sprintf(format_string, Int64_val(arg));
+}
+
+CAMLprim value caml_int64_of_string(value s)
+{
+ char * p;
+ uint64_t res, threshold;
+ int sign, base, signedness, d;
+
+ p = parse_sign_and_base(String_val(s), &base, &signedness, &sign);
+ threshold = ((uint64_t) -1) / base;
+ d = parse_digit(*p);
+ if (d < 0 || d >= base) caml_failwith(INT64_ERRMSG);
+ res = d;
+ for (p++; /*nothing*/; p++) {
+ char c = *p;
+ if (c == '_') continue;
+ d = parse_digit(c);
+ if (d < 0 || d >= base) break;
+ /* Detect overflow in multiplication base * res */
+ if (res > threshold) caml_failwith(INT64_ERRMSG);
+ res = base * res + d;
+ /* Detect overflow in addition (base * res) + d */
+ if (res < (uint64_t) d) caml_failwith(INT64_ERRMSG);
+ }
+ if (p != String_val(s) + caml_string_length(s)){
+ caml_failwith(INT64_ERRMSG);
+ }
+ if (signedness) {
+ /* Signed representation expected, allow -2^63 to 2^63 - 1 only */
+ if (sign >= 0) {
+ if (res >= (uint64_t)1 << 63) caml_failwith(INT64_ERRMSG);
+ } else {
+ if (res > (uint64_t)1 << 63) caml_failwith(INT64_ERRMSG);
+ }
+ }
+ if (sign < 0) res = - res;
+ return caml_copy_int64(res);
+}
+
+CAMLprim value caml_int64_bits_of_float(value vd)
+{
+ union { double d; int64_t i; int32_t h[2]; } u;
+ u.d = Double_val(vd);
+#if defined(__arm__) && !defined(__ARM_EABI__)
+ { int32_t t = u.h[0]; u.h[0] = u.h[1]; u.h[1] = t; }
+#endif
+ return caml_copy_int64(u.i);
+}
+
+CAMLprim value caml_int64_float_of_bits(value vi)
+{
+ union { double d; int64_t i; int32_t h[2]; } u;
+ u.i = Int64_val(vi);
+#if defined(__arm__) && !defined(__ARM_EABI__)
+ { int32_t t = u.h[0]; u.h[0] = u.h[1]; u.h[1] = t; }
+#endif
+ return caml_copy_double(u.d);
+}
+
+/* Native integers */
+
+static int nativeint_cmp(value v1, value v2)
+{
+ intnat i1 = Nativeint_val(v1);
+ intnat i2 = Nativeint_val(v2);
+ return (i1 > i2) - (i1 < i2);
+}
+
+static intnat nativeint_hash(value v)
+{
+ intnat n = Nativeint_val(v);
+#ifdef ARCH_SIXTYFOUR
+ /* 32/64 bits compatibility trick. See explanations in file "hash.c",
+ function caml_hash_mix_intnat. */
+ return (n >> 32) ^ (n >> 63) ^ n;
+#else
+ return n;
+#endif
+}
+
+static void nativeint_serialize(value v, uintnat * bsize_32,
+ uintnat * bsize_64)
+{
+ intnat l = Nativeint_val(v);
+#ifdef ARCH_SIXTYFOUR
+ if (l >= -((intnat)1 << 31) && l < ((intnat)1 << 31)) {
+ caml_serialize_int_1(1);
+ caml_serialize_int_4((int32_t) l);
+ } else {
+ caml_serialize_int_1(2);
+ caml_serialize_int_8(l);
+ }
+#else
+ caml_serialize_int_1(1);
+ caml_serialize_int_4(l);
+#endif
+ *bsize_32 = 4;
+ *bsize_64 = 8;
+}
+
+static uintnat nativeint_deserialize(void * dst)
+{
+ switch (caml_deserialize_uint_1()) {
+ case 1:
+ *((intnat *) dst) = caml_deserialize_sint_4();
+ break;
+ case 2:
+#ifdef ARCH_SIXTYFOUR
+ *((intnat *) dst) = caml_deserialize_sint_8();
+#else
+ caml_deserialize_error("input_value: native integer value too large");
+#endif
+ break;
+ default:
+ caml_deserialize_error("input_value: ill-formed native integer");
+ }
+ return sizeof(long);
+}
+
+CAMLexport struct custom_operations caml_nativeint_ops = {
+ "_n",
+ custom_finalize_default,
+ nativeint_cmp,
+ nativeint_hash,
+ nativeint_serialize,
+ nativeint_deserialize,
+ custom_compare_ext_default
+};
+
+CAMLexport value caml_copy_nativeint(intnat i)
+{
+ value res = caml_alloc_custom(&caml_nativeint_ops, sizeof(intnat), 0, 1);
+ Nativeint_val(res) = i;
+ return res;
+}
+
+CAMLprim value caml_nativeint_neg(value v)
+{ return caml_copy_nativeint(- Nativeint_val(v)); }
+
+CAMLprim value caml_nativeint_add(value v1, value v2)
+{ return caml_copy_nativeint(Nativeint_val(v1) + Nativeint_val(v2)); }
+
+CAMLprim value caml_nativeint_sub(value v1, value v2)
+{ return caml_copy_nativeint(Nativeint_val(v1) - Nativeint_val(v2)); }
+
+CAMLprim value caml_nativeint_mul(value v1, value v2)
+{ return caml_copy_nativeint(Nativeint_val(v1) * Nativeint_val(v2)); }
+
+#define Nativeint_min_int ((intnat) 1 << (sizeof(intnat) * 8 - 1))
+
+CAMLprim value caml_nativeint_div(value v1, value v2)
+{
+ intnat dividend = Nativeint_val(v1);
+ intnat divisor = Nativeint_val(v2);
+ if (divisor == 0) caml_raise_zero_divide();
+ /* PR#4740: on some processors, modulus crashes if division overflows.
+ Implement the same behavior as for type "int". */
+ if (dividend == Nativeint_min_int && divisor == -1) return v1;
+ return caml_copy_nativeint(dividend / divisor);
+}
+
+CAMLprim value caml_nativeint_mod(value v1, value v2)
+{
+ intnat dividend = Nativeint_val(v1);
+ intnat divisor = Nativeint_val(v2);
+ if (divisor == 0) caml_raise_zero_divide();
+ /* PR#4740: on some processors, modulus crashes if division overflows.
+ Implement the same behavior as for type "int". */
+ if (dividend == Nativeint_min_int && divisor == -1){
+ return caml_copy_nativeint(0);
+ }
+ return caml_copy_nativeint(dividend % divisor);
+}
+
+CAMLprim value caml_nativeint_and(value v1, value v2)
+{ return caml_copy_nativeint(Nativeint_val(v1) & Nativeint_val(v2)); }
+
+CAMLprim value caml_nativeint_or(value v1, value v2)
+{ return caml_copy_nativeint(Nativeint_val(v1) | Nativeint_val(v2)); }
+
+CAMLprim value caml_nativeint_xor(value v1, value v2)
+{ return caml_copy_nativeint(Nativeint_val(v1) ^ Nativeint_val(v2)); }
+
+CAMLprim value caml_nativeint_shift_left(value v1, value v2)
+{ return caml_copy_nativeint(Nativeint_val(v1) << Int_val(v2)); }
+
+CAMLprim value caml_nativeint_shift_right(value v1, value v2)
+{ return caml_copy_nativeint(Nativeint_val(v1) >> Int_val(v2)); }
+
+CAMLprim value caml_nativeint_shift_right_unsigned(value v1, value v2)
+{ return caml_copy_nativeint((uintnat)Nativeint_val(v1) >> Int_val(v2)); }
+
+value caml_nativeint_direct_bswap(value v)
+{
+#ifdef ARCH_SIXTYFOUR
+ return caml_swap64(v);
+#else
+ return caml_swap32(v);
+#endif
+}
+
+CAMLprim value caml_nativeint_bswap(value v)
+{
+#ifdef ARCH_SIXTYFOUR
+ return caml_copy_nativeint(caml_swap64(Nativeint_val(v)));
+#else
+ return caml_copy_nativeint(caml_swap32(Nativeint_val(v)));
+#endif
+}
+
+CAMLprim value caml_nativeint_of_int(value v)
+{ return caml_copy_nativeint(Long_val(v)); }
+
+CAMLprim value caml_nativeint_to_int(value v)
+{ return Val_long(Nativeint_val(v)); }
+
+CAMLprim value caml_nativeint_of_float(value v)
+{ return caml_copy_nativeint((intnat)(Double_val(v))); }
+
+CAMLprim value caml_nativeint_to_float(value v)
+{ return caml_copy_double((double)(Nativeint_val(v))); }
+
+CAMLprim value caml_nativeint_of_int32(value v)
+{ return caml_copy_nativeint(Int32_val(v)); }
+
+CAMLprim value caml_nativeint_to_int32(value v)
+{ return caml_copy_int32(Nativeint_val(v)); }
+
+CAMLprim value caml_nativeint_compare(value v1, value v2)
+{
+ intnat i1 = Nativeint_val(v1);
+ intnat i2 = Nativeint_val(v2);
+ int res = (i1 > i2) - (i1 < i2);
+ return Val_int(res);
+}
+
+CAMLprim value caml_nativeint_format(value fmt, value arg)
+{
+ char format_string[FORMAT_BUFFER_SIZE];
+
+ parse_format(fmt, ARCH_INTNAT_PRINTF_FORMAT, format_string);
+ return caml_alloc_sprintf(format_string, Nativeint_val(arg));
+}
+
+CAMLprim value caml_nativeint_of_string(value s)
+{
+ return caml_copy_nativeint(parse_intnat(s, 8 * sizeof(value), INTNAT_ERRMSG));
+}
diff --git a/byterun/io.c b/byterun/io.c
new file mode 100644
index 0000000000..1339d42381
--- /dev/null
+++ b/byterun/io.c
@@ -0,0 +1,816 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Buffered input/output. */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <string.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include "caml/config.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#ifdef __CYGWIN__
+#include </usr/include/io.h>
+#endif
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/io.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/signals.h"
+#include "caml/sys.h"
+
+#ifndef SEEK_SET
+#define SEEK_SET 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+#endif
+
+/* Hooks for locking channels */
+
+CAMLexport void (*caml_channel_mutex_free) (struct channel *) = NULL;
+CAMLexport void (*caml_channel_mutex_lock) (struct channel *) = NULL;
+CAMLexport void (*caml_channel_mutex_unlock) (struct channel *) = NULL;
+CAMLexport void (*caml_channel_mutex_unlock_exn) (void) = NULL;
+
+/* List of opened channels */
+CAMLexport struct channel * caml_all_opened_channels = NULL;
+
+/* Basic functions over type struct channel *.
+ These functions can be called directly from C.
+ No locking is performed. */
+
+/* Functions shared between input and output */
+
+CAMLexport struct channel * caml_open_descriptor_in(int fd)
+{
+ struct channel * channel;
+
+ channel = (struct channel *) caml_stat_alloc(sizeof(struct channel));
+ channel->fd = fd;
+ caml_enter_blocking_section();
+ channel->offset = lseek(fd, 0, SEEK_CUR);
+ caml_leave_blocking_section();
+ channel->curr = channel->max = channel->buff;
+ channel->end = channel->buff + IO_BUFFER_SIZE;
+ channel->mutex = NULL;
+ channel->revealed = 0;
+ channel->old_revealed = 0;
+ channel->refcount = 0;
+ channel->flags = 0;
+ channel->next = caml_all_opened_channels;
+ channel->prev = NULL;
+ channel->name = NULL;
+ if (caml_all_opened_channels != NULL)
+ caml_all_opened_channels->prev = channel;
+ caml_all_opened_channels = channel;
+ return channel;
+}
+
+CAMLexport struct channel * caml_open_descriptor_out(int fd)
+{
+ struct channel * channel;
+
+ channel = caml_open_descriptor_in(fd);
+ channel->max = NULL;
+ return channel;
+}
+
+static void unlink_channel(struct channel *channel)
+{
+ if (channel->prev == NULL) {
+ Assert (channel == caml_all_opened_channels);
+ caml_all_opened_channels = caml_all_opened_channels->next;
+ if (caml_all_opened_channels != NULL)
+ caml_all_opened_channels->prev = NULL;
+ } else {
+ channel->prev->next = channel->next;
+ if (channel->next != NULL) channel->next->prev = channel->prev;
+ }
+}
+
+CAMLexport void caml_close_channel(struct channel *channel)
+{
+ close(channel->fd);
+ if (channel->refcount > 0) return;
+ if (caml_channel_mutex_free != NULL) (*caml_channel_mutex_free)(channel);
+ unlink_channel(channel);
+ caml_stat_free(channel->name);
+ caml_stat_free(channel);
+}
+
+CAMLexport file_offset caml_channel_size(struct channel *channel)
+{
+ file_offset offset;
+ file_offset end;
+ int fd;
+
+ /* We extract data from [channel] before dropping the OCaml lock, in case
+ someone else touches the block. */
+ fd = channel->fd;
+ offset = channel->offset;
+ caml_enter_blocking_section();
+ end = lseek(fd, 0, SEEK_END);
+ if (end == -1 || lseek(fd, offset, SEEK_SET) != offset) {
+ caml_leave_blocking_section();
+ caml_sys_error(NO_ARG);
+ }
+ caml_leave_blocking_section();
+ return end;
+}
+
+CAMLexport int caml_channel_binary_mode(struct channel *channel)
+{
+#if defined(_WIN32) || defined(__CYGWIN__)
+ int oldmode = setmode(channel->fd, O_BINARY);
+ if (oldmode == O_TEXT) setmode(channel->fd, O_TEXT);
+ return oldmode == O_BINARY;
+#else
+ return 1;
+#endif
+}
+
+/* Output */
+
+#ifndef EINTR
+#define EINTR (-1)
+#endif
+#ifndef EAGAIN
+#define EAGAIN (-1)
+#endif
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK (-1)
+#endif
+
+static int do_write(int fd, char *p, int n)
+{
+ int retcode;
+
+again:
+ caml_enter_blocking_section();
+ retcode = write(fd, p, n);
+ caml_leave_blocking_section();
+ if (retcode == -1) {
+ if (errno == EINTR) goto again;
+ if ((errno == EAGAIN || errno == EWOULDBLOCK) && n > 1) {
+ /* We couldn't do a partial write here, probably because
+ n <= PIPE_BUF and POSIX says that writes of less than
+ PIPE_BUF characters must be atomic.
+ We first try again with a partial write of 1 character.
+ If that fails too, we'll raise Sys_blocked_io below. */
+ n = 1; goto again;
+ }
+ }
+ if (retcode == -1) caml_sys_io_error(NO_ARG);
+ return retcode;
+}
+
+/* Attempt to flush the buffer. This will make room in the buffer for
+ at least one character. Returns true if the buffer is empty at the
+ end of the flush, or false if some data remains in the buffer.
+ */
+
+CAMLexport int caml_flush_partial(struct channel *channel)
+{
+ int towrite, written;
+
+ towrite = channel->curr - channel->buff;
+ if (towrite > 0) {
+ written = do_write(channel->fd, channel->buff, towrite);
+ channel->offset += written;
+ if (written < towrite)
+ memmove(channel->buff, channel->buff + written, towrite - written);
+ channel->curr -= written;
+ }
+ return (channel->curr == channel->buff);
+}
+
+/* Flush completely the buffer. */
+
+CAMLexport void caml_flush(struct channel *channel)
+{
+ while (! caml_flush_partial(channel)) /*nothing*/;
+}
+
+/* Output data */
+
+CAMLexport void caml_putword(struct channel *channel, uint32_t w)
+{
+ if (! caml_channel_binary_mode(channel))
+ caml_failwith("output_binary_int: not a binary channel");
+ putch(channel, w >> 24);
+ putch(channel, w >> 16);
+ putch(channel, w >> 8);
+ putch(channel, w);
+}
+
+CAMLexport int caml_putblock(struct channel *channel, char *p, intnat len)
+{
+ int n, free, towrite, written;
+
+ n = len >= INT_MAX ? INT_MAX : (int) len;
+ free = channel->end - channel->curr;
+ if (n < free) {
+ /* Write request small enough to fit in buffer: transfer to buffer. */
+ memmove(channel->curr, p, n);
+ channel->curr += n;
+ return n;
+ } else {
+ /* Write request overflows buffer (or just fills it up): transfer whatever
+ fits to buffer and write the buffer */
+ memmove(channel->curr, p, free);
+ towrite = channel->end - channel->buff;
+ written = do_write(channel->fd, channel->buff, towrite);
+ if (written < towrite)
+ memmove(channel->buff, channel->buff + written, towrite - written);
+ channel->offset += written;
+ channel->curr = channel->end - written;
+ return free;
+ }
+}
+
+CAMLexport void caml_really_putblock(struct channel *channel,
+ char *p, intnat len)
+{
+ int written;
+ while (len > 0) {
+ written = caml_putblock(channel, p, len);
+ p += written;
+ len -= written;
+ }
+}
+
+CAMLexport void caml_seek_out(struct channel *channel, file_offset dest)
+{
+ caml_flush(channel);
+ caml_enter_blocking_section();
+ if (lseek(channel->fd, dest, SEEK_SET) != dest) {
+ caml_leave_blocking_section();
+ caml_sys_error(NO_ARG);
+ }
+ caml_leave_blocking_section();
+ channel->offset = dest;
+}
+
+CAMLexport file_offset caml_pos_out(struct channel *channel)
+{
+ return channel->offset + (file_offset)(channel->curr - channel->buff);
+}
+
+/* Input */
+
+/* caml_do_read is exported for Cash */
+CAMLexport int caml_do_read(int fd, char *p, unsigned int n)
+{
+ int retcode;
+
+ do {
+ caml_enter_blocking_section();
+ retcode = read(fd, p, n);
+#if defined(_WIN32)
+ if (retcode == -1 && errno == ENOMEM && n > 16384){
+ retcode = read(fd, p, 16384);
+ }
+#endif
+ caml_leave_blocking_section();
+ } while (retcode == -1 && errno == EINTR);
+ if (retcode == -1) caml_sys_io_error(NO_ARG);
+ return retcode;
+}
+
+CAMLexport unsigned char caml_refill(struct channel *channel)
+{
+ int n;
+
+ n = caml_do_read(channel->fd, channel->buff, channel->end - channel->buff);
+ if (n == 0) caml_raise_end_of_file();
+ channel->offset += n;
+ channel->max = channel->buff + n;
+ channel->curr = channel->buff + 1;
+ return (unsigned char)(channel->buff[0]);
+}
+
+CAMLexport uint32_t caml_getword(struct channel *channel)
+{
+ int i;
+ uint32_t res;
+
+ if (! caml_channel_binary_mode(channel))
+ caml_failwith("input_binary_int: not a binary channel");
+ res = 0;
+ for(i = 0; i < 4; i++) {
+ res = (res << 8) + getch(channel);
+ }
+ return res;
+}
+
+CAMLexport int caml_getblock(struct channel *channel, char *p, intnat len)
+{
+ int n, avail, nread;
+
+ n = len >= INT_MAX ? INT_MAX : (int) len;
+ avail = channel->max - channel->curr;
+ if (n <= avail) {
+ memmove(p, channel->curr, n);
+ channel->curr += n;
+ return n;
+ } else if (avail > 0) {
+ memmove(p, channel->curr, avail);
+ channel->curr += avail;
+ return avail;
+ } else {
+ nread = caml_do_read(channel->fd, channel->buff,
+ channel->end - channel->buff);
+ channel->offset += nread;
+ channel->max = channel->buff + nread;
+ if (n > nread) n = nread;
+ memmove(p, channel->buff, n);
+ channel->curr = channel->buff + n;
+ return n;
+ }
+}
+
+CAMLexport int caml_really_getblock(struct channel *chan, char *p, intnat n)
+{
+ int r;
+ while (n > 0) {
+ r = caml_getblock(chan, p, n);
+ if (r == 0) break;
+ p += r;
+ n -= r;
+ }
+ return (n == 0);
+}
+
+CAMLexport void caml_seek_in(struct channel *channel, file_offset dest)
+{
+ if (dest >= channel->offset - (channel->max - channel->buff) &&
+ dest <= channel->offset) {
+ channel->curr = channel->max - (channel->offset - dest);
+ } else {
+ caml_enter_blocking_section();
+ if (lseek(channel->fd, dest, SEEK_SET) != dest) {
+ caml_leave_blocking_section();
+ caml_sys_error(NO_ARG);
+ }
+ caml_leave_blocking_section();
+ channel->offset = dest;
+ channel->curr = channel->max = channel->buff;
+ }
+}
+
+CAMLexport file_offset caml_pos_in(struct channel *channel)
+{
+ return channel->offset - (file_offset)(channel->max - channel->curr);
+}
+
+CAMLexport intnat caml_input_scan_line(struct channel *channel)
+{
+ char * p;
+ int n;
+
+ p = channel->curr;
+ do {
+ if (p >= channel->max) {
+ /* No more characters available in the buffer */
+ if (channel->curr > channel->buff) {
+ /* Try to make some room in the buffer by shifting the unread
+ portion at the beginning */
+ memmove(channel->buff, channel->curr, channel->max - channel->curr);
+ n = channel->curr - channel->buff;
+ channel->curr -= n;
+ channel->max -= n;
+ p -= n;
+ }
+ if (channel->max >= channel->end) {
+ /* Buffer is full, no room to read more characters from the input.
+ Return the number of characters in the buffer, with negative
+ sign to indicate that no newline was encountered. */
+ return -(channel->max - channel->curr);
+ }
+ /* Fill the buffer as much as possible */
+ n = caml_do_read(channel->fd, channel->max, channel->end - channel->max);
+ if (n == 0) {
+ /* End-of-file encountered. Return the number of characters in the
+ buffer, with negative sign since we haven't encountered
+ a newline. */
+ return -(channel->max - channel->curr);
+ }
+ channel->offset += n;
+ channel->max += n;
+ }
+ } while (*p++ != '\n');
+ /* Found a newline. Return the length of the line, newline included. */
+ return (p - channel->curr);
+}
+
+/* OCaml entry points for the I/O functions. Wrap struct channel *
+ objects into a heap-allocated object. Perform locking
+ and unlocking around the I/O operations. */
+
+/* FIXME CAMLexport, but not in io.h exported for Cash ? */
+CAMLexport void caml_finalize_channel(value vchan)
+{
+ struct channel * chan = Channel(vchan);
+ if (--chan->refcount > 0) return;
+ if (caml_channel_mutex_free != NULL) (*caml_channel_mutex_free)(chan);
+
+ if (chan->fd != -1 && chan->name && caml_runtime_warnings_active())
+ fprintf(stderr,
+ "[ocaml] channel opened on file '%s' dies without being closed\n",
+ chan->name
+ );
+
+ unlink_channel(chan);
+ caml_stat_free(chan->name);
+ caml_stat_free(chan);
+}
+
+static int compare_channel(value vchan1, value vchan2)
+{
+ struct channel * chan1 = Channel(vchan1);
+ struct channel * chan2 = Channel(vchan2);
+ return (chan1 == chan2) ? 0 : (chan1 < chan2) ? -1 : 1;
+}
+
+static intnat hash_channel(value vchan)
+{
+ return (intnat) (Channel(vchan));
+}
+
+static struct custom_operations channel_operations = {
+ "_chan",
+ caml_finalize_channel,
+ compare_channel,
+ hash_channel,
+ custom_serialize_default,
+ custom_deserialize_default,
+ custom_compare_ext_default
+};
+
+CAMLexport value caml_alloc_channel(struct channel *chan)
+{
+ value res;
+ chan->refcount++; /* prevent finalization during next alloc */
+ res = caml_alloc_custom(&channel_operations, sizeof(struct channel *),
+ 1, 1000);
+ Channel(res) = chan;
+ return res;
+}
+
+CAMLprim value caml_ml_open_descriptor_in(value fd)
+{
+ return caml_alloc_channel(caml_open_descriptor_in(Int_val(fd)));
+}
+
+CAMLprim value caml_ml_open_descriptor_out(value fd)
+{
+ return caml_alloc_channel(caml_open_descriptor_out(Int_val(fd)));
+}
+
+CAMLprim value caml_ml_set_channel_name(value vchannel, value vname)
+{
+ struct channel * channel = Channel(vchannel);
+ caml_stat_free(channel->name);
+ if (caml_string_length(vname) > 0)
+ channel->name = caml_strdup(String_val(vname));
+ else
+ channel->name = NULL;
+ return Val_unit;
+}
+
+#define Pair_tag 0
+
+CAMLprim value caml_ml_out_channels_list (value unit)
+{
+ CAMLparam0 ();
+ CAMLlocal3 (res, tail, chan);
+ struct channel * channel;
+
+ res = Val_emptylist;
+ for (channel = caml_all_opened_channels;
+ channel != NULL;
+ channel = channel->next)
+ /* Testing channel->fd >= 0 looks unnecessary, as
+ caml_ml_close_channel changes max when setting fd to -1. */
+ if (channel->max == NULL) {
+ chan = caml_alloc_channel (channel);
+ tail = res;
+ res = caml_alloc_small (2, Pair_tag);
+ Field (res, 0) = chan;
+ Field (res, 1) = tail;
+ }
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_channel_descriptor(value vchannel)
+{
+ int fd = Channel(vchannel)->fd;
+ if (fd == -1) { errno = EBADF; caml_sys_error(NO_ARG); }
+ return Val_int(fd);
+}
+
+CAMLprim value caml_ml_close_channel(value vchannel)
+{
+ int result;
+ int do_syscall;
+ int fd;
+
+ /* For output channels, must have flushed before */
+ struct channel * channel = Channel(vchannel);
+ if (channel->fd != -1){
+ fd = channel->fd;
+ channel->fd = -1;
+ do_syscall = 1;
+ }else{
+ do_syscall = 0;
+ result = 0;
+ }
+ /* Ensure that every read or write on the channel will cause an
+ immediate caml_flush_partial or caml_refill, thus raising a Sys_error
+ exception */
+ channel->curr = channel->max = channel->end;
+
+ if (do_syscall) {
+ caml_enter_blocking_section();
+ result = close(fd);
+ caml_leave_blocking_section();
+ }
+
+ if (result == -1) caml_sys_error (NO_ARG);
+ return Val_unit;
+}
+
+/* EOVERFLOW is the Unix98 error indicating that a file position or file
+ size is not representable.
+ ERANGE is the ANSI C error indicating that some argument to some
+ function is out of range. This is less precise than EOVERFLOW,
+ but guaranteed to be defined on all ANSI C environments. */
+#ifndef EOVERFLOW
+#define EOVERFLOW ERANGE
+#endif
+
+CAMLprim value caml_ml_channel_size(value vchannel)
+{
+ file_offset size = caml_channel_size(Channel(vchannel));
+ if (size > Max_long) { errno = EOVERFLOW; caml_sys_error(NO_ARG); }
+ return Val_long(size);
+}
+
+CAMLprim value caml_ml_channel_size_64(value vchannel)
+{
+ return Val_file_offset(caml_channel_size(Channel(vchannel)));
+}
+
+CAMLprim value caml_ml_set_binary_mode(value vchannel, value mode)
+{
+#if defined(_WIN32) || defined(__CYGWIN__)
+ struct channel * channel = Channel(vchannel);
+ if (setmode(channel->fd, Bool_val(mode) ? O_BINARY : O_TEXT) == -1)
+ caml_sys_error(NO_ARG);
+#endif
+ return Val_unit;
+}
+
+/*
+ If the channel is closed, DO NOT raise a "bad file descriptor"
+ exception, but do nothing (the buffer is already empty).
+ This is because some libraries will flush at exit, even on
+ file descriptors that may be closed.
+*/
+
+CAMLprim value caml_ml_flush_partial(value vchannel)
+{
+ CAMLparam1 (vchannel);
+ struct channel * channel = Channel(vchannel);
+ int res;
+
+ if (channel->fd == -1) CAMLreturn(Val_true);
+ Lock(channel);
+ res = caml_flush_partial(channel);
+ Unlock(channel);
+ CAMLreturn (Val_bool(res));
+}
+
+CAMLprim value caml_ml_flush(value vchannel)
+{
+ CAMLparam1 (vchannel);
+ struct channel * channel = Channel(vchannel);
+
+ if (channel->fd == -1) CAMLreturn(Val_unit);
+ Lock(channel);
+ caml_flush(channel);
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_ml_output_char(value vchannel, value ch)
+{
+ CAMLparam2 (vchannel, ch);
+ struct channel * channel = Channel(vchannel);
+
+ Lock(channel);
+ putch(channel, Long_val(ch));
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_ml_output_int(value vchannel, value w)
+{
+ CAMLparam2 (vchannel, w);
+ struct channel * channel = Channel(vchannel);
+
+ Lock(channel);
+ caml_putword(channel, Long_val(w));
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_ml_output_partial(value vchannel, value buff, value start,
+ value length)
+{
+ CAMLparam4 (vchannel, buff, start, length);
+ struct channel * channel = Channel(vchannel);
+ int res;
+
+ Lock(channel);
+ res = caml_putblock(channel, &Byte(buff, Long_val(start)), Long_val(length));
+ Unlock(channel);
+ CAMLreturn (Val_int(res));
+}
+
+CAMLprim value caml_ml_output(value vchannel, value buff, value start,
+ value length)
+{
+ CAMLparam4 (vchannel, buff, start, length);
+ struct channel * channel = Channel(vchannel);
+ intnat pos = Long_val(start);
+ intnat len = Long_val(length);
+
+ Lock(channel);
+ while (len > 0) {
+ int written = caml_putblock(channel, &Byte(buff, pos), len);
+ pos += written;
+ len -= written;
+ }
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_ml_seek_out(value vchannel, value pos)
+{
+ CAMLparam2 (vchannel, pos);
+ struct channel * channel = Channel(vchannel);
+
+ Lock(channel);
+ caml_seek_out(channel, Long_val(pos));
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_ml_seek_out_64(value vchannel, value pos)
+{
+ CAMLparam2 (vchannel, pos);
+ struct channel * channel = Channel(vchannel);
+
+ Lock(channel);
+ caml_seek_out(channel, File_offset_val(pos));
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_ml_pos_out(value vchannel)
+{
+ file_offset pos = caml_pos_out(Channel(vchannel));
+ if (pos > Max_long) { errno = EOVERFLOW; caml_sys_error(NO_ARG); }
+ return Val_long(pos);
+}
+
+CAMLprim value caml_ml_pos_out_64(value vchannel)
+{
+ return Val_file_offset(caml_pos_out(Channel(vchannel)));
+}
+
+CAMLprim value caml_ml_input_char(value vchannel)
+{
+ CAMLparam1 (vchannel);
+ struct channel * channel = Channel(vchannel);
+ unsigned char c;
+
+ Lock(channel);
+ c = getch(channel);
+ Unlock(channel);
+ CAMLreturn (Val_long(c));
+}
+
+CAMLprim value caml_ml_input_int(value vchannel)
+{
+ CAMLparam1 (vchannel);
+ struct channel * channel = Channel(vchannel);
+ intnat i;
+
+ Lock(channel);
+ i = caml_getword(channel);
+ Unlock(channel);
+#ifdef ARCH_SIXTYFOUR
+ i = (i << 32) >> 32; /* Force sign extension */
+#endif
+ CAMLreturn (Val_long(i));
+}
+
+CAMLprim value caml_ml_input(value vchannel, value buff, value vstart,
+ value vlength)
+{
+ CAMLparam4 (vchannel, buff, vstart, vlength);
+ struct channel * channel = Channel(vchannel);
+ intnat start, len;
+ int n, avail, nread;
+
+ Lock(channel);
+ /* We cannot call caml_getblock here because buff may move during
+ caml_do_read */
+ start = Long_val(vstart);
+ len = Long_val(vlength);
+ n = len >= INT_MAX ? INT_MAX : (int) len;
+ avail = channel->max - channel->curr;
+ if (n <= avail) {
+ memmove(&Byte(buff, start), channel->curr, n);
+ channel->curr += n;
+ } else if (avail > 0) {
+ memmove(&Byte(buff, start), channel->curr, avail);
+ channel->curr += avail;
+ n = avail;
+ } else {
+ nread = caml_do_read(channel->fd, channel->buff,
+ channel->end - channel->buff);
+ channel->offset += nread;
+ channel->max = channel->buff + nread;
+ if (n > nread) n = nread;
+ memmove(&Byte(buff, start), channel->buff, n);
+ channel->curr = channel->buff + n;
+ }
+ Unlock(channel);
+ CAMLreturn (Val_long(n));
+}
+
+CAMLprim value caml_ml_seek_in(value vchannel, value pos)
+{
+ CAMLparam2 (vchannel, pos);
+ struct channel * channel = Channel(vchannel);
+
+ Lock(channel);
+ caml_seek_in(channel, Long_val(pos));
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_ml_seek_in_64(value vchannel, value pos)
+{
+ CAMLparam2 (vchannel, pos);
+ struct channel * channel = Channel(vchannel);
+
+ Lock(channel);
+ caml_seek_in(channel, File_offset_val(pos));
+ Unlock(channel);
+ CAMLreturn (Val_unit);
+}
+
+CAMLprim value caml_ml_pos_in(value vchannel)
+{
+ file_offset pos = caml_pos_in(Channel(vchannel));
+ if (pos > Max_long) { errno = EOVERFLOW; caml_sys_error(NO_ARG); }
+ return Val_long(pos);
+}
+
+CAMLprim value caml_ml_pos_in_64(value vchannel)
+{
+ return Val_file_offset(caml_pos_in(Channel(vchannel)));
+}
+
+CAMLprim value caml_ml_input_scan_line(value vchannel)
+{
+ CAMLparam1 (vchannel);
+ struct channel * channel = Channel(vchannel);
+ intnat res;
+
+ Lock(channel);
+ res = caml_input_scan_line(channel);
+ Unlock(channel);
+ CAMLreturn (Val_long(res));
+}
diff --git a/byterun/lexing.c b/byterun/lexing.c
new file mode 100644
index 0000000000..eac302e31a
--- /dev/null
+++ b/byterun/lexing.c
@@ -0,0 +1,229 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The table-driven automaton for lexers generated by camllex. */
+
+#include "caml/fail.h"
+#include "caml/mlvalues.h"
+#include "caml/stacks.h"
+
+struct lexer_buffer {
+ value refill_buff;
+ value lex_buffer;
+ value lex_buffer_len;
+ value lex_abs_pos;
+ value lex_start_pos;
+ value lex_curr_pos;
+ value lex_last_pos;
+ value lex_last_action;
+ value lex_eof_reached;
+ value lex_mem;
+ value lex_start_p;
+ value lex_curr_p;
+};
+
+struct lexing_table {
+ value lex_base;
+ value lex_backtrk;
+ value lex_default;
+ value lex_trans;
+ value lex_check;
+ value lex_base_code;
+ value lex_backtrk_code;
+ value lex_default_code;
+ value lex_trans_code;
+ value lex_check_code;
+ value lex_code;
+};
+
+#if defined(ARCH_BIG_ENDIAN) || SIZEOF_SHORT != 2
+#define Short(tbl,n) \
+ (*((unsigned char *)((tbl) + (n) * 2)) + \
+ (*((signed char *)((tbl) + (n) * 2 + 1)) << 8))
+#else
+#define Short(tbl,n) (((short *)(tbl))[(n)])
+#endif
+
+CAMLprim value caml_lex_engine(struct lexing_table *tbl, value start_state,
+ struct lexer_buffer *lexbuf)
+{
+ int state, base, backtrk, c;
+
+ state = Int_val(start_state);
+ if (state >= 0) {
+ /* First entry */
+ lexbuf->lex_last_pos = lexbuf->lex_start_pos = lexbuf->lex_curr_pos;
+ lexbuf->lex_last_action = Val_int(-1);
+ } else {
+ /* Reentry after refill */
+ state = -state - 1;
+ }
+ while(1) {
+ /* Lookup base address or action number for current state */
+ base = Short(tbl->lex_base, state);
+ if (base < 0) return Val_int(-base-1);
+ /* See if it's a backtrack point */
+ backtrk = Short(tbl->lex_backtrk, state);
+ if (backtrk >= 0) {
+ lexbuf->lex_last_pos = lexbuf->lex_curr_pos;
+ lexbuf->lex_last_action = Val_int(backtrk);
+ }
+ /* See if we need a refill */
+ if (lexbuf->lex_curr_pos >= lexbuf->lex_buffer_len){
+ if (lexbuf->lex_eof_reached == Val_bool (0)){
+ return Val_int(-state - 1);
+ }else{
+ c = 256;
+ }
+ }else{
+ /* Read next input char */
+ c = Byte_u(lexbuf->lex_buffer, Long_val(lexbuf->lex_curr_pos));
+ lexbuf->lex_curr_pos += 2;
+ }
+ /* Determine next state */
+ if (Short(tbl->lex_check, base + c) == state)
+ state = Short(tbl->lex_trans, base + c);
+ else
+ state = Short(tbl->lex_default, state);
+ /* If no transition on this char, return to last backtrack point */
+ if (state < 0) {
+ lexbuf->lex_curr_pos = lexbuf->lex_last_pos;
+ if (lexbuf->lex_last_action == Val_int(-1)) {
+ caml_failwith("lexing: empty token");
+ } else {
+ return lexbuf->lex_last_action;
+ }
+ }else{
+ /* Erase the EOF condition only if the EOF pseudo-character was
+ consumed by the automaton (i.e. there was no backtrack above)
+ */
+ if (c == 256) lexbuf->lex_eof_reached = Val_bool (0);
+ }
+ }
+}
+
+/***********************************************/
+/* New lexer engine, with memory of positions */
+/***********************************************/
+
+static void run_mem(char *pc, value mem, value curr_pos) {
+ for (;;) {
+ unsigned char dst, src ;
+
+ dst = *pc++ ;
+ if (dst == 0xff)
+ return ;
+ src = *pc++ ;
+ if (src == 0xff) {
+ /* fprintf(stderr,"[%hhu] <- %d\n",dst,Int_val(curr_pos)) ;*/
+ Field(mem,dst) = curr_pos ;
+ } else {
+ /* fprintf(stderr,"[%hhu] <- [%hhu]\n",dst,src) ; */
+ Field(mem,dst) = Field(mem,src) ;
+ }
+ }
+}
+
+static void run_tag(char *pc, value mem) {
+ for (;;) {
+ unsigned char dst, src ;
+
+ dst = *pc++ ;
+ if (dst == 0xff)
+ return ;
+ src = *pc++ ;
+ if (src == 0xff) {
+ /* fprintf(stderr,"[%hhu] <- -1\n",dst) ; */
+ Field(mem,dst) = Val_int(-1) ;
+ } else {
+ /* fprintf(stderr,"[%hhu] <- [%hhu]\n",dst,src) ; */
+ Field(mem,dst) = Field(mem,src) ;
+ }
+ }
+}
+
+CAMLprim value caml_new_lex_engine(struct lexing_table *tbl, value start_state,
+ struct lexer_buffer *lexbuf)
+{
+ int state, base, backtrk, c, pstate ;
+ state = Int_val(start_state);
+ if (state >= 0) {
+ /* First entry */
+ lexbuf->lex_last_pos = lexbuf->lex_start_pos = lexbuf->lex_curr_pos;
+ lexbuf->lex_last_action = Val_int(-1);
+ } else {
+ /* Reentry after refill */
+ state = -state - 1;
+ }
+ while(1) {
+ /* Lookup base address or action number for current state */
+ base = Short(tbl->lex_base, state);
+ if (base < 0) {
+ int pc_off = Short(tbl->lex_base_code, state) ;
+ run_tag(Bp_val(tbl->lex_code) + pc_off, lexbuf->lex_mem);
+ /* fprintf(stderr,"Perform: %d\n",-base-1) ; */
+ return Val_int(-base-1);
+ }
+ /* See if it's a backtrack point */
+ backtrk = Short(tbl->lex_backtrk, state);
+ if (backtrk >= 0) {
+ int pc_off = Short(tbl->lex_backtrk_code, state);
+ run_tag(Bp_val(tbl->lex_code) + pc_off, lexbuf->lex_mem);
+ lexbuf->lex_last_pos = lexbuf->lex_curr_pos;
+ lexbuf->lex_last_action = Val_int(backtrk);
+
+ }
+ /* See if we need a refill */
+ if (lexbuf->lex_curr_pos >= lexbuf->lex_buffer_len){
+ if (lexbuf->lex_eof_reached == Val_bool (0)){
+ return Val_int(-state - 1);
+ }else{
+ c = 256;
+ }
+ }else{
+ /* Read next input char */
+ c = Byte_u(lexbuf->lex_buffer, Long_val(lexbuf->lex_curr_pos));
+ lexbuf->lex_curr_pos += 2;
+ }
+ /* Determine next state */
+ pstate=state ;
+ if (Short(tbl->lex_check, base + c) == state)
+ state = Short(tbl->lex_trans, base + c);
+ else
+ state = Short(tbl->lex_default, state);
+ /* If no transition on this char, return to last backtrack point */
+ if (state < 0) {
+ lexbuf->lex_curr_pos = lexbuf->lex_last_pos;
+ if (lexbuf->lex_last_action == Val_int(-1)) {
+ caml_failwith("lexing: empty token");
+ } else {
+ return lexbuf->lex_last_action;
+ }
+ }else{
+ /* If some transition, get and perform memory moves */
+ int base_code = Short(tbl->lex_base_code, pstate) ;
+ int pc_off ;
+ if (Short(tbl->lex_check_code, base_code + c) == pstate)
+ pc_off = Short(tbl->lex_trans_code, base_code + c) ;
+ else
+ pc_off = Short(tbl->lex_default_code, pstate) ;
+ if (pc_off > 0)
+ run_mem(Bp_val(tbl->lex_code) + pc_off, lexbuf->lex_mem,
+ lexbuf->lex_curr_pos) ;
+ /* Erase the EOF condition only if the EOF pseudo-character was
+ consumed by the automaton (i.e. there was no backtrack above)
+ */
+ if (c == 256) lexbuf->lex_eof_reached = Val_bool (0);
+ }
+ }
+}
diff --git a/byterun/main.c b/byterun/main.c
new file mode 100644
index 0000000000..1ad20280e3
--- /dev/null
+++ b/byterun/main.c
@@ -0,0 +1,57 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Main entry point (can be overridden by a user-provided main()
+ function that calls caml_main() later). */
+
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/sys.h"
+
+CAMLextern void caml_main (char **);
+
+#ifdef _WIN32
+CAMLextern void caml_expand_command_line (int *, char ***);
+#endif
+
+int main(int argc, char **argv)
+{
+#ifdef DEBUG
+ caml_gc_message (-1, "### OCaml runtime: debug mode ###\n", 0);
+#if 0
+ {
+ int i;
+ char *ocp;
+ char *cp;
+
+ caml_gc_message (-1, "### command line:", 0);
+ for (i = 0; i < argc; i++){
+ caml_gc_message (-1, " %s", argv[i]);
+ }
+ caml_gc_message (-1, "\n", 0);
+ ocp = getenv ("OCAMLRUNPARAM");
+ caml_gc_message (-1, "### OCAMLRUNPARAM=%s\n", ocp == NULL ? "" : ocp);
+ cp = getenv ("CAMLRUNPARAM");
+ caml_gc_message (-1, "### CAMLRUNPARAM=%s\n", cp == NULL ? "" : cp);
+ caml_gc_message (-1, "### working dir: %s\n", getcwd (NULL, 0));
+ }
+#endif
+#endif
+#ifdef _WIN32
+ /* Expand wildcards and diversions in command line */
+ caml_expand_command_line(&argc, &argv);
+#endif
+ caml_main(argv);
+ caml_sys_exit(Val_int(0));
+ return 0; /* not reached */
+}
diff --git a/byterun/major_gc.c b/byterun/major_gc.c
new file mode 100644
index 0000000000..356fa179a1
--- /dev/null
+++ b/byterun/major_gc.c
@@ -0,0 +1,569 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <limits.h>
+
+#include "caml/compact.h"
+#include "caml/custom.h"
+#include "caml/config.h"
+#include "caml/fail.h"
+#include "caml/finalise.h"
+#include "caml/freelist.h"
+#include "caml/gc.h"
+#include "caml/gc_ctrl.h"
+#include "caml/major_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/roots.h"
+#include "caml/weak.h"
+
+#if defined (NATIVE_CODE) && defined (NO_NAKED_POINTERS)
+#define NATIVE_CODE_AND_NO_NAKED_POINTERS
+#else
+#undef NATIVE_CODE_AND_NO_NAKED_POINTERS
+#endif
+
+uintnat caml_percent_free;
+uintnat caml_major_heap_increment;
+CAMLexport char *caml_heap_start;
+char *caml_gc_sweep_hp;
+int caml_gc_phase; /* always Phase_mark, Phase_sweep, or Phase_idle */
+static value *gray_vals;
+static value *gray_vals_cur, *gray_vals_end;
+static asize_t gray_vals_size;
+static int heap_is_pure; /* The heap is pure if the only gray objects
+ below [markhp] are also in [gray_vals]. */
+uintnat caml_allocated_words;
+uintnat caml_dependent_size, caml_dependent_allocated;
+double caml_extra_heap_resources;
+uintnat caml_fl_wsz_at_phase_change = 0;
+
+extern char *caml_fl_merge; /* Defined in freelist.c. */
+
+static char *markhp, *chunk, *limit;
+
+int caml_gc_subphase; /* Subphase_{main,weak1,weak2,final} */
+static value *weak_prev;
+
+#ifdef DEBUG
+static unsigned long major_gc_counter = 0;
+#endif
+
+void (*caml_major_gc_hook)(void) = NULL;
+
+static void realloc_gray_vals (void)
+{
+ value *new;
+
+ Assert (gray_vals_cur == gray_vals_end);
+ if (gray_vals_size < caml_stat_heap_wsz / 32){
+ caml_gc_message (0x08, "Growing gray_vals to %"
+ ARCH_INTNAT_PRINTF_FORMAT "uk bytes\n",
+ (intnat) gray_vals_size * sizeof (value) / 512);
+ new = (value *) realloc ((char *) gray_vals,
+ 2 * gray_vals_size * sizeof (value));
+ if (new == NULL){
+ caml_gc_message (0x08, "No room for growing gray_vals\n", 0);
+ gray_vals_cur = gray_vals;
+ heap_is_pure = 0;
+ }else{
+ gray_vals = new;
+ gray_vals_cur = gray_vals + gray_vals_size;
+ gray_vals_size *= 2;
+ gray_vals_end = gray_vals + gray_vals_size;
+ }
+ }else{
+ gray_vals_cur = gray_vals + gray_vals_size / 2;
+ heap_is_pure = 0;
+ }
+}
+
+void caml_darken (value v, value *p /* not used */)
+{
+#ifdef NATIVE_CODE_AND_NO_NAKED_POINTERS
+ if (Is_block (v) && Wosize_val (v) > 0) {
+#else
+ if (Is_block (v) && Is_in_heap (v)) {
+#endif
+ header_t h = Hd_val (v);
+ tag_t t = Tag_hd (h);
+ if (t == Infix_tag){
+ v -= Infix_offset_val(v);
+ h = Hd_val (v);
+ t = Tag_hd (h);
+ }
+#ifdef NATIVE_CODE_AND_NO_NAKED_POINTERS
+ /* We insist that naked pointers to outside the heap point to things that
+ look like values with headers coloured black. This isn't always
+ strictly necessary but is essential in certain cases---in particular
+ when the value is allocated in a read-only section. (For the values
+ where it would be safe it is a performance improvement since we avoid
+ putting them on the grey list.) */
+ CAMLassert (Is_in_heap (v) || Is_black_hd (h));
+#endif
+ CAMLassert (!Is_blue_hd (h));
+ if (Is_white_hd (h)){
+ if (t < No_scan_tag){
+ Hd_val (v) = Grayhd_hd (h);
+ *gray_vals_cur++ = v;
+ if (gray_vals_cur >= gray_vals_end) realloc_gray_vals ();
+ }else{
+ Hd_val (v) = Blackhd_hd (h);
+ }
+ }
+ }
+}
+
+static void start_cycle (void)
+{
+ Assert (caml_gc_phase == Phase_idle);
+ Assert (gray_vals_cur == gray_vals);
+ caml_gc_message (0x01, "Starting new major GC cycle\n", 0);
+ caml_darken_all_roots();
+ caml_gc_phase = Phase_mark;
+ caml_gc_subphase = Subphase_main;
+ markhp = NULL;
+#ifdef DEBUG
+ ++ major_gc_counter;
+ caml_heap_check ();
+#endif
+}
+
+static void mark_slice (intnat work)
+{
+ value *gray_vals_ptr; /* Local copy of gray_vals_cur */
+ value v, child;
+ header_t hd;
+ mlsize_t size, i;
+#ifdef NATIVE_CODE_AND_NO_NAKED_POINTERS
+ int marking_closure = 0;
+#endif
+
+ caml_gc_message (0x40, "Marking %ld words\n", work);
+ caml_gc_message (0x40, "Subphase = %ld\n", caml_gc_subphase);
+ gray_vals_ptr = gray_vals_cur;
+ while (work > 0){
+ if (gray_vals_ptr > gray_vals){
+ v = *--gray_vals_ptr;
+ hd = Hd_val(v);
+#ifdef NATIVE_CODE_AND_NO_NAKED_POINTERS
+ marking_closure =
+ (Tag_hd (hd) == Closure_tag || Tag_hd (hd) == Infix_tag);
+#endif
+ Assert (Is_gray_hd (hd));
+ Hd_val (v) = Blackhd_hd (hd);
+ size = Wosize_hd (hd);
+ if (Tag_hd (hd) < No_scan_tag){
+ for (i = 0; i < size; i++){
+ child = Field (v, i);
+#ifdef NATIVE_CODE_AND_NO_NAKED_POINTERS
+ if (Is_block (child)
+ && Wosize_val (child) > 0 /* Atoms never need to be marked. */
+ /* Closure blocks contain code pointers at offsets that cannot
+ be reliably determined, so we always use the page table when
+ marking such values. */
+ && (!marking_closure || Is_in_heap (child))) {
+#else
+ if (Is_block (child) && Is_in_heap (child)) {
+#endif
+ hd = Hd_val (child);
+ if (Tag_hd (hd) == Forward_tag){
+ value f = Forward_val (child);
+ if (Is_block (f)
+ && (!Is_in_value_area(f) || Tag_val (f) == Forward_tag
+ || Tag_val (f) == Lazy_tag || Tag_val (f) == Double_tag)){
+ /* Do not short-circuit the pointer. */
+ }else{
+ Field (v, i) = f;
+ }
+ }
+ else if (Tag_hd(hd) == Infix_tag) {
+ child -= Infix_offset_val(child);
+ hd = Hd_val(child);
+ }
+#ifdef NATIVE_CODE_AND_NO_NAKED_POINTERS
+ /* See [caml_darken] for a description of this assertion. */
+ CAMLassert (Is_in_heap (child) || Is_black_hd (hd));
+#endif
+ if (Is_white_hd (hd)){
+ Hd_val (child) = Grayhd_hd (hd);
+ *gray_vals_ptr++ = child;
+ if (gray_vals_ptr >= gray_vals_end) {
+ gray_vals_cur = gray_vals_ptr;
+ realloc_gray_vals ();
+ gray_vals_ptr = gray_vals_cur;
+ }
+ }
+ }
+ }
+ }
+ work -= Whsize_wosize(size);
+ }else if (markhp != NULL){
+ if (markhp == limit){
+ chunk = Chunk_next (chunk);
+ if (chunk == NULL){
+ markhp = NULL;
+ }else{
+ markhp = chunk;
+ limit = chunk + Chunk_size (chunk);
+ }
+ }else{
+ if (Is_gray_val (Val_hp (markhp))){
+ Assert (gray_vals_ptr == gray_vals);
+ *gray_vals_ptr++ = Val_hp (markhp);
+ }
+ markhp += Bhsize_hp (markhp);
+ }
+ }else if (!heap_is_pure){
+ heap_is_pure = 1;
+ chunk = caml_heap_start;
+ markhp = chunk;
+ limit = chunk + Chunk_size (chunk);
+ }else{
+ switch (caml_gc_subphase){
+ case Subphase_main: {
+ /* The main marking phase is over. Start removing weak pointers to
+ dead values. */
+ caml_gc_subphase = Subphase_weak1;
+ weak_prev = &caml_weak_list_head;
+ }
+ break;
+ case Subphase_weak1: {
+ value cur, curfield;
+ mlsize_t sz, i;
+ header_t hd;
+
+ cur = *weak_prev;
+ if (cur != (value) NULL){
+ hd = Hd_val (cur);
+ sz = Wosize_hd (hd);
+ for (i = 1; i < sz; i++){
+ curfield = Field (cur, i);
+ weak_again:
+ if (curfield != caml_weak_none
+ && Is_block (curfield) && Is_in_heap (curfield)){
+ if (Tag_val (curfield) == Forward_tag){
+ value f = Forward_val (curfield);
+ if (Is_block (f)) {
+ if (!Is_in_value_area(f) || Tag_val (f) == Forward_tag
+ || Tag_val (f) == Lazy_tag || Tag_val (f) == Double_tag){
+ /* Do not short-circuit the pointer. */
+ }else{
+ Field (cur, i) = curfield = f;
+ goto weak_again;
+ }
+ }
+ }
+ if (Is_white_val (curfield)){
+ Field (cur, i) = caml_weak_none;
+ }
+ }
+ }
+ weak_prev = &Field (cur, 0);
+ work -= Whsize_hd (hd);
+ }else{
+ /* Subphase_weak1 is done.
+ Handle finalised values and start removing dead weak arrays. */
+ gray_vals_cur = gray_vals_ptr;
+ caml_final_update ();
+ gray_vals_ptr = gray_vals_cur;
+ caml_gc_subphase = Subphase_weak2;
+ weak_prev = &caml_weak_list_head;
+ }
+ }
+ break;
+ case Subphase_weak2: {
+ value cur;
+ header_t hd;
+
+ cur = *weak_prev;
+ if (cur != (value) NULL){
+ hd = Hd_val (cur);
+ if (Color_hd (hd) == Caml_white){
+ /* The whole array is dead, remove it from the list. */
+ *weak_prev = Field (cur, 0);
+ }else{
+ weak_prev = &Field (cur, 0);
+ }
+ work -= 1;
+ }else{
+ /* Subphase_weak2 is done. Go to Subphase_final. */
+ caml_gc_subphase = Subphase_final;
+ }
+ }
+ break;
+ case Subphase_final: {
+ /* Initialise the sweep phase. */
+ gray_vals_cur = gray_vals_ptr;
+ caml_gc_sweep_hp = caml_heap_start;
+ caml_fl_init_merge ();
+ caml_gc_phase = Phase_sweep;
+ chunk = caml_heap_start;
+ caml_gc_sweep_hp = chunk;
+ limit = chunk + Chunk_size (chunk);
+ work = 0;
+ caml_fl_wsz_at_phase_change = caml_fl_cur_wsz;
+ if (caml_major_gc_hook) (*caml_major_gc_hook)();
+ }
+ break;
+ default: Assert (0);
+ }
+ }
+ }
+ gray_vals_cur = gray_vals_ptr;
+}
+
+static void sweep_slice (intnat work)
+{
+ char *hp;
+ header_t hd;
+
+ caml_gc_message (0x40, "Sweeping %ld words\n", work);
+ while (work > 0){
+ if (caml_gc_sweep_hp < limit){
+ hp = caml_gc_sweep_hp;
+ hd = Hd_hp (hp);
+ work -= Whsize_hd (hd);
+ caml_gc_sweep_hp += Bhsize_hd (hd);
+ switch (Color_hd (hd)){
+ case Caml_white:
+ if (Tag_hd (hd) == Custom_tag){
+ void (*final_fun)(value) = Custom_ops_val(Val_hp(hp))->finalize;
+ if (final_fun != NULL) final_fun(Val_hp(hp));
+ }
+ caml_gc_sweep_hp = (char *) caml_fl_merge_block (Val_hp (hp));
+ break;
+ case Caml_blue:
+ /* Only the blocks of the free-list are blue. See [freelist.c]. */
+ caml_fl_merge = Bp_hp (hp);
+ break;
+ default: /* gray or black */
+ Assert (Color_hd (hd) == Caml_black);
+ Hd_hp (hp) = Whitehd_hd (hd);
+ break;
+ }
+ Assert (caml_gc_sweep_hp <= limit);
+ }else{
+ chunk = Chunk_next (chunk);
+ if (chunk == NULL){
+ /* Sweeping is done. */
+ ++ caml_stat_major_collections;
+ work = 0;
+ caml_gc_phase = Phase_idle;
+ }else{
+ caml_gc_sweep_hp = chunk;
+ limit = chunk + Chunk_size (chunk);
+ }
+ }
+ }
+}
+
+/* The main entry point for the GC. Called after each minor GC.
+ [howmuch] is the amount of work to do, 0 to let the GC compute it.
+ Return the computed amount of work to do.
+ */
+intnat caml_major_collection_slice (intnat howmuch)
+{
+ double p, dp;
+ intnat computed_work;
+ /*
+ Free memory at the start of the GC cycle (garbage + free list) (assumed):
+ FM = caml_stat_heap_wsz * caml_percent_free
+ / (100 + caml_percent_free)
+
+ Assuming steady state and enforcing a constant allocation rate, then
+ FM is divided in 2/3 for garbage and 1/3 for free list.
+ G = 2 * FM / 3
+ G is also the amount of memory that will be used during this cycle
+ (still assuming steady state).
+
+ Proportion of G consumed since the previous slice:
+ PH = caml_allocated_words / G
+ = caml_allocated_words * 3 * (100 + caml_percent_free)
+ / (2 * caml_stat_heap_wsz * caml_percent_free)
+ Proportion of extra-heap resources consumed since the previous slice:
+ PE = caml_extra_heap_resources
+ Proportion of total work to do in this slice:
+ P = max (PH, PE)
+ Amount of marking work for the GC cycle:
+ MW = caml_stat_heap_wsz * 100 / (100 + caml_percent_free)
+ Amount of sweeping work for the GC cycle:
+ SW = caml_stat_heap_wsz
+
+ In order to finish marking with a non-empty free list, we will
+ use 40% of the time for marking, and 60% for sweeping.
+
+ If TW is the total work for this cycle,
+ MW = 40/100 * TW
+ SW = 60/100 * TW
+
+ Amount of work to do for this slice:
+ W = P * TW
+
+ Amount of marking work for a marking slice:
+ MS = P * MW / (40/100)
+ MS = P * caml_stat_heap_wsz * 250 / (100 + caml_percent_free)
+ Amount of sweeping work for a sweeping slice:
+ SS = P * SW / (60/100)
+ SS = P * caml_stat_heap_wsz * 5 / 3
+
+ This slice will either mark MS words or sweep SS words.
+ */
+
+ if (caml_major_slice_begin_hook != NULL) (*caml_major_slice_begin_hook) ();
+
+ if (caml_gc_phase == Phase_idle) start_cycle ();
+
+ p = (double) caml_allocated_words * 3.0 * (100 + caml_percent_free)
+ / caml_stat_heap_wsz / caml_percent_free / 2.0;
+ if (caml_dependent_size > 0){
+ dp = (double) caml_dependent_allocated * (100 + caml_percent_free)
+ / caml_dependent_size / caml_percent_free;
+ }else{
+ dp = 0.0;
+ }
+ if (p < dp) p = dp;
+ if (p < caml_extra_heap_resources) p = caml_extra_heap_resources;
+
+ caml_gc_message (0x40, "allocated_words = %"
+ ARCH_INTNAT_PRINTF_FORMAT "u\n",
+ caml_allocated_words);
+ caml_gc_message (0x40, "extra_heap_resources = %"
+ ARCH_INTNAT_PRINTF_FORMAT "uu\n",
+ (uintnat) (caml_extra_heap_resources * 1000000));
+ caml_gc_message (0x40, "amount of work to do = %"
+ ARCH_INTNAT_PRINTF_FORMAT "uu\n",
+ (uintnat) (p * 1000000));
+
+ if (caml_gc_phase == Phase_mark){
+ computed_work = (intnat) (p * caml_stat_heap_wsz * 250
+ / (100 + caml_percent_free));
+ }else{
+ computed_work = (intnat) (p * caml_stat_heap_wsz * 5 / 3);
+ }
+ caml_gc_message (0x40, "ordered work = %ld words\n", howmuch);
+ caml_gc_message (0x40, "computed work = %ld words\n", computed_work);
+ if (howmuch == 0) howmuch = computed_work;
+ if (caml_gc_phase == Phase_mark){
+ mark_slice (howmuch);
+ caml_gc_message (0x02, "!", 0);
+ }else{
+ Assert (caml_gc_phase == Phase_sweep);
+ sweep_slice (howmuch);
+ caml_gc_message (0x02, "$", 0);
+ }
+
+ if (caml_gc_phase == Phase_idle) caml_compact_heap_maybe ();
+
+ caml_stat_major_words += caml_allocated_words;
+ caml_allocated_words = 0;
+ caml_dependent_allocated = 0;
+ caml_extra_heap_resources = 0.0;
+ if (caml_major_slice_end_hook != NULL) (*caml_major_slice_end_hook) ();
+ return computed_work;
+}
+
+/* The minor heap must be empty when this function is called;
+ the minor heap is empty when this function returns.
+*/
+/* This does not call caml_compact_heap_maybe because the estimations of
+ free and live memory are only valid for a cycle done incrementally.
+ Besides, this function is called by caml_compact_heap_maybe.
+*/
+void caml_finish_major_cycle (void)
+{
+ if (caml_gc_phase == Phase_idle) start_cycle ();
+ while (caml_gc_phase == Phase_mark) mark_slice (LONG_MAX);
+ Assert (caml_gc_phase == Phase_sweep);
+ while (caml_gc_phase == Phase_sweep) sweep_slice (LONG_MAX);
+ Assert (caml_gc_phase == Phase_idle);
+ caml_stat_major_words += caml_allocated_words;
+ caml_allocated_words = 0;
+}
+
+/* Make sure the request is at least Heap_chunk_min and round it up
+ to a multiple of the page size.
+ The argument and result are both numbers of words.
+*/
+static asize_t clip_heap_chunk_size (asize_t request)
+{
+ if (request < Heap_chunk_min){
+ request = Heap_chunk_min;
+ }
+ return
+ Wsize_bsize (((Bsize_wsize (request) + Page_size - 1)
+ >> Page_log) << Page_log);
+}
+
+/* Compute the heap increment, make sure the request is at least that big,
+ then call clip_heap_chunk_size, then make sure the result is >= request.
+ The argument and result are both numbers of words.
+*/
+asize_t caml_round_heap_chunk_wsz (asize_t request)
+{
+ asize_t result = request;
+ uintnat incr;
+
+ /* Compute the heap increment as a word size. */
+ if (caml_major_heap_increment > 1000){
+ incr = caml_major_heap_increment;
+ }else{
+ incr = caml_stat_heap_wsz / 100 * caml_major_heap_increment;
+ }
+
+ if (result < incr){
+ result = incr;
+ }
+ result = clip_heap_chunk_size (result);
+
+ if (result < request){
+ caml_raise_out_of_memory ();
+ return 0; /* not reached */
+ }
+ return result;
+}
+
+/* [heap_size] is a number of bytes */
+void caml_init_major_heap (asize_t heap_size)
+{
+ caml_stat_heap_wsz = Wsize_bsize (clip_heap_chunk_size (heap_size));
+ caml_stat_top_heap_wsz = caml_stat_heap_wsz;
+ Assert (Bsize_wsize (caml_stat_heap_wsz) % Page_size == 0);
+ caml_heap_start =
+ (char *) caml_alloc_for_heap (Bsize_wsize (caml_stat_heap_wsz));
+ if (caml_heap_start == NULL)
+ caml_fatal_error ("Fatal error: not enough memory for the initial heap.\n");
+ Chunk_next (caml_heap_start) = NULL;
+ caml_stat_heap_chunks = 1;
+
+ if (caml_page_table_add(In_heap, caml_heap_start,
+ caml_heap_start + Bsize_wsize (caml_stat_heap_wsz))
+ != 0) {
+ caml_fatal_error ("Fatal error: not enough memory "
+ "for the initial page table.\n");
+ }
+
+ caml_fl_init_merge ();
+ caml_make_free_blocks ((value *) caml_heap_start,
+ caml_stat_heap_wsz, 1, Caml_white);
+ caml_gc_phase = Phase_idle;
+ gray_vals_size = 2048;
+ gray_vals = (value *) malloc (gray_vals_size * sizeof (value));
+ if (gray_vals == NULL)
+ caml_fatal_error ("Fatal error: not enough memory for the gray cache.\n");
+ gray_vals_cur = gray_vals;
+ gray_vals_end = gray_vals + gray_vals_size;
+ heap_is_pure = 1;
+ caml_allocated_words = 0;
+ caml_extra_heap_resources = 0.0;
+}
diff --git a/byterun/md5.c b/byterun/md5.c
new file mode 100644
index 0000000000..7a996b6b9f
--- /dev/null
+++ b/byterun/md5.c
@@ -0,0 +1,321 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/md5.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+#include "caml/io.h"
+#include "caml/reverse.h"
+
+/* MD5 message digest */
+
+CAMLprim value caml_md5_string(value str, value ofs, value len)
+{
+ struct MD5Context ctx;
+ value res;
+ caml_MD5Init(&ctx);
+ caml_MD5Update(&ctx, &Byte_u(str, Long_val(ofs)), Long_val(len));
+ res = caml_alloc_string(16);
+ caml_MD5Final(&Byte_u(res, 0), &ctx);
+ return res;
+}
+
+CAMLexport value caml_md5_channel(struct channel *chan, intnat toread)
+{
+ CAMLparam0();
+ struct MD5Context ctx;
+ value res;
+ intnat read;
+ char buffer[4096];
+
+ Lock(chan);
+ caml_MD5Init(&ctx);
+ if (toread < 0){
+ while (1){
+ read = caml_getblock (chan, buffer, sizeof(buffer));
+ if (read == 0) break;
+ caml_MD5Update (&ctx, (unsigned char *) buffer, read);
+ }
+ }else{
+ while (toread > 0) {
+ read = caml_getblock(chan, buffer,
+ toread > sizeof(buffer) ? sizeof(buffer) : toread);
+ if (read == 0) caml_raise_end_of_file();
+ caml_MD5Update(&ctx, (unsigned char *) buffer, read);
+ toread -= read;
+ }
+ }
+ res = caml_alloc_string(16);
+ caml_MD5Final(&Byte_u(res, 0), &ctx);
+ Unlock(chan);
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_md5_chan(value vchan, value len)
+{
+ CAMLparam2 (vchan, len);
+ CAMLreturn (caml_md5_channel(Channel(vchan), Long_val(len)));
+}
+
+CAMLexport void caml_md5_block(unsigned char digest[16],
+ void * data, uintnat len)
+{
+ struct MD5Context ctx;
+ caml_MD5Init(&ctx);
+ caml_MD5Update(&ctx, data, len);
+ caml_MD5Final(digest, &ctx);
+}
+
+/*
+ * This code implements the MD5 message-digest algorithm.
+ * The algorithm is due to Ron Rivest. This code was
+ * written by Colin Plumb in 1993, no copyright is claimed.
+ * This code is in the public domain; do with it what you wish.
+ *
+ * Equivalent code is available from RSA Data Security, Inc.
+ * This code has been tested against that, and is equivalent,
+ * except that you don't need to include two pages of legalese
+ * with every copy.
+ *
+ * To compute the message digest of a chunk of bytes, declare an
+ * MD5Context structure, pass it to caml_MD5Init, call caml_MD5Update as
+ * needed on buffers full of bytes, and then call caml_MD5Final, which
+ * will fill a supplied 16-byte array with the digest.
+ */
+
+#ifndef ARCH_BIG_ENDIAN
+#define byteReverse(buf, len) /* Nothing */
+#else
+static void byteReverse(unsigned char * buf, unsigned longs)
+{
+ uint32_t t;
+ do {
+ t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
+ ((unsigned) buf[1] << 8 | buf[0]);
+ *(uint32_t *) buf = t;
+ buf += 4;
+ } while (--longs);
+}
+#endif
+
+/*
+ * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
+ * initialization constants.
+ */
+CAMLexport void caml_MD5Init(struct MD5Context *ctx)
+{
+ ctx->buf[0] = 0x67452301;
+ ctx->buf[1] = 0xefcdab89;
+ ctx->buf[2] = 0x98badcfe;
+ ctx->buf[3] = 0x10325476;
+
+ ctx->bits[0] = 0;
+ ctx->bits[1] = 0;
+}
+
+/*
+ * Update context to reflect the concatenation of another buffer full
+ * of bytes.
+ */
+CAMLexport void caml_MD5Update(struct MD5Context *ctx, unsigned char *buf,
+ uintnat len)
+{
+ uint32_t t;
+
+ /* Update bitcount */
+
+ t = ctx->bits[0];
+ if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
+ ctx->bits[1]++; /* Carry from low to high */
+ ctx->bits[1] += len >> 29;
+
+ t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
+
+ /* Handle any leading odd-sized chunks */
+
+ if (t) {
+ unsigned char *p = (unsigned char *) ctx->in + t;
+
+ t = 64 - t;
+ if (len < t) {
+ memcpy(p, buf, len);
+ return;
+ }
+ memcpy(p, buf, t);
+ byteReverse(ctx->in, 16);
+ caml_MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+ buf += t;
+ len -= t;
+ }
+ /* Process data in 64-byte chunks */
+
+ while (len >= 64) {
+ memcpy(ctx->in, buf, 64);
+ byteReverse(ctx->in, 16);
+ caml_MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+ buf += 64;
+ len -= 64;
+ }
+
+ /* Handle any remaining bytes of data. */
+
+ memcpy(ctx->in, buf, len);
+}
+
+/*
+ * Final wrapup - pad to 64-byte boundary with the bit pattern
+ * 1 0* (64-bit count of bits processed, MSB-first)
+ */
+CAMLexport void caml_MD5Final(unsigned char *digest, struct MD5Context *ctx)
+{
+ unsigned count;
+ unsigned char *p;
+
+ /* Compute number of bytes mod 64 */
+ count = (ctx->bits[0] >> 3) & 0x3F;
+
+ /* Set the first char of padding to 0x80. This is safe since there is
+ always at least one byte free */
+ p = ctx->in + count;
+ *p++ = 0x80;
+
+ /* Bytes of padding needed to make 64 bytes */
+ count = 64 - 1 - count;
+
+ /* Pad out to 56 mod 64 */
+ if (count < 8) {
+ /* Two lots of padding: Pad the first block to 64 bytes */
+ memset(p, 0, count);
+ byteReverse(ctx->in, 16);
+ caml_MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+
+ /* Now fill the next block with 56 bytes */
+ memset(ctx->in, 0, 56);
+ } else {
+ /* Pad block to 56 bytes */
+ memset(p, 0, count - 8);
+ }
+ byteReverse(ctx->in, 14);
+
+ /* Append length in bits and transform */
+ ((uint32_t *) ctx->in)[14] = ctx->bits[0];
+ ((uint32_t *) ctx->in)[15] = ctx->bits[1];
+
+ caml_MD5Transform(ctx->buf, (uint32_t *) ctx->in);
+ byteReverse((unsigned char *) ctx->buf, 4);
+ memcpy(digest, ctx->buf, 16);
+ memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */
+}
+
+/* The four core functions - F1 is optimized somewhat */
+
+/* #define F1(x, y, z) (x & y | ~x & z) */
+#define F1(x, y, z) (z ^ (x & (y ^ z)))
+#define F2(x, y, z) F1(z, x, y)
+#define F3(x, y, z) (x ^ y ^ z)
+#define F4(x, y, z) (y ^ (x | ~z))
+
+/* This is the central step in the MD5 algorithm. */
+#define MD5STEP(f, w, x, y, z, data, s) \
+ ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
+
+/*
+ * The core of the MD5 algorithm, this alters an existing MD5 hash to
+ * reflect the addition of 16 longwords of new data. caml_MD5Update blocks
+ * the data and converts bytes into longwords for this routine.
+ */
+CAMLexport void caml_MD5Transform(uint32_t *buf, uint32_t *in)
+{
+ register uint32_t a, b, c, d;
+
+ a = buf[0];
+ b = buf[1];
+ c = buf[2];
+ d = buf[3];
+
+ MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
+ MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
+ MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
+ MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
+ MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
+ MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
+ MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
+ MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
+ MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
+ MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
+ MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
+ MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
+ MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
+ MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
+ MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
+ MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
+
+ MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
+ MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
+ MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
+ MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
+ MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
+ MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
+ MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
+ MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
+ MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
+ MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
+ MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
+ MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
+ MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
+ MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
+ MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
+ MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
+
+ MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
+ MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
+ MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
+ MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
+ MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
+ MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
+ MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
+ MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
+ MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
+ MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
+ MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
+ MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
+ MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
+ MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
+ MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
+ MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
+
+ MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
+ MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
+ MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
+ MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
+ MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
+ MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
+ MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
+ MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
+ MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
+ MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
+ MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
+ MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
+ MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
+ MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
+ MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
+ MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
+
+ buf[0] += a;
+ buf[1] += b;
+ buf[2] += c;
+ buf[3] += d;
+}
diff --git a/byterun/memory.c b/byterun/memory.c
new file mode 100644
index 0000000000..7e9d4ab209
--- /dev/null
+++ b/byterun/memory.c
@@ -0,0 +1,602 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+#include "caml/address_class.h"
+#include "caml/fail.h"
+#include "caml/freelist.h"
+#include "caml/gc.h"
+#include "caml/gc_ctrl.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/major_gc.h"
+#include "caml/minor_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/signals.h"
+
+extern uintnat caml_percent_free; /* major_gc.c */
+
+/* Page table management */
+
+#define Page(p) ((uintnat) (p) >> Page_log)
+#define Page_mask ((uintnat) -1 << Page_log)
+
+#ifdef ARCH_SIXTYFOUR
+
+/* 64-bit implementation:
+ The page table is represented sparsely as a hash table
+ with linear probing */
+
+struct page_table {
+ mlsize_t size; /* size == 1 << (wordsize - shift) */
+ int shift;
+ mlsize_t mask; /* mask == size - 1 */
+ mlsize_t occupancy;
+ uintnat * entries; /* [size] */
+};
+
+static struct page_table caml_page_table;
+
+/* Page table entries are the logical 'or' of
+ - the key: address of a page (low Page_log bits = 0)
+ - the data: a 8-bit integer */
+
+#define Page_entry_matches(entry,addr) \
+ ((((entry) ^ (addr)) & Page_mask) == 0)
+
+/* Multiplicative Fibonacci hashing
+ (Knuth, TAOCP vol 3, section 6.4, page 518).
+ HASH_FACTOR is (sqrt(5) - 1) / 2 * 2^wordsize. */
+#ifdef ARCH_SIXTYFOUR
+#define HASH_FACTOR 11400714819323198486UL
+#else
+#define HASH_FACTOR 2654435769UL
+#endif
+#define Hash(v) (((v) * HASH_FACTOR) >> caml_page_table.shift)
+
+int caml_page_table_lookup(void * addr)
+{
+ uintnat h, e;
+
+ h = Hash(Page(addr));
+ /* The first hit is almost always successful, so optimize for this case */
+ e = caml_page_table.entries[h];
+ if (Page_entry_matches(e, (uintnat)addr)) return e & 0xFF;
+ while(1) {
+ if (e == 0) return 0;
+ h = (h + 1) & caml_page_table.mask;
+ e = caml_page_table.entries[h];
+ if (Page_entry_matches(e, (uintnat)addr)) return e & 0xFF;
+ }
+}
+
+int caml_page_table_initialize(mlsize_t bytesize)
+{
+ uintnat pagesize = Page(bytesize);
+
+ caml_page_table.size = 1;
+ caml_page_table.shift = 8 * sizeof(uintnat);
+ /* Aim for initial load factor between 1/4 and 1/2 */
+ while (caml_page_table.size < 2 * pagesize) {
+ caml_page_table.size <<= 1;
+ caml_page_table.shift -= 1;
+ }
+ caml_page_table.mask = caml_page_table.size - 1;
+ caml_page_table.occupancy = 0;
+ caml_page_table.entries = calloc(caml_page_table.size, sizeof(uintnat));
+ if (caml_page_table.entries == NULL)
+ return -1;
+ else
+ return 0;
+}
+
+static int caml_page_table_resize(void)
+{
+ struct page_table old = caml_page_table;
+ uintnat * new_entries;
+ uintnat i, h;
+
+ caml_gc_message (0x08, "Growing page table to %lu entries\n",
+ caml_page_table.size);
+
+ new_entries = calloc(2 * old.size, sizeof(uintnat));
+ if (new_entries == NULL) {
+ caml_gc_message (0x08, "No room for growing page table\n", 0);
+ return -1;
+ }
+
+ caml_page_table.size = 2 * old.size;
+ caml_page_table.shift = old.shift - 1;
+ caml_page_table.mask = caml_page_table.size - 1;
+ caml_page_table.occupancy = old.occupancy;
+ caml_page_table.entries = new_entries;
+
+ for (i = 0; i < old.size; i++) {
+ uintnat e = old.entries[i];
+ if (e == 0) continue;
+ h = Hash(Page(e));
+ while (caml_page_table.entries[h] != 0)
+ h = (h + 1) & caml_page_table.mask;
+ caml_page_table.entries[h] = e;
+ }
+
+ free(old.entries);
+ return 0;
+}
+
+static int caml_page_table_modify(uintnat page, int toclear, int toset)
+{
+ uintnat h;
+
+ Assert ((page & ~Page_mask) == 0);
+
+ /* Resize to keep load factor below 1/2 */
+ if (caml_page_table.occupancy * 2 >= caml_page_table.size) {
+ if (caml_page_table_resize() != 0) return -1;
+ }
+ h = Hash(Page(page));
+ while (1) {
+ if (caml_page_table.entries[h] == 0) {
+ caml_page_table.entries[h] = page | toset;
+ caml_page_table.occupancy++;
+ break;
+ }
+ if (Page_entry_matches(caml_page_table.entries[h], page)) {
+ caml_page_table.entries[h] =
+ (caml_page_table.entries[h] & ~toclear) | toset;
+ break;
+ }
+ h = (h + 1) & caml_page_table.mask;
+ }
+ return 0;
+}
+
+#else
+
+/* 32-bit implementation:
+ The page table is represented as a 2-level array of unsigned char */
+
+CAMLexport unsigned char * caml_page_table[Pagetable1_size];
+static unsigned char caml_page_table_empty[Pagetable2_size] = { 0, };
+
+int caml_page_table_initialize(mlsize_t bytesize)
+{
+ int i;
+ for (i = 0; i < Pagetable1_size; i++)
+ caml_page_table[i] = caml_page_table_empty;
+ return 0;
+}
+
+static int caml_page_table_modify(uintnat page, int toclear, int toset)
+{
+ uintnat i = Pagetable_index1(page);
+ uintnat j = Pagetable_index2(page);
+
+ if (caml_page_table[i] == caml_page_table_empty) {
+ unsigned char * new_tbl = calloc(Pagetable2_size, 1);
+ if (new_tbl == 0) return -1;
+ caml_page_table[i] = new_tbl;
+ }
+ caml_page_table[i][j] = (caml_page_table[i][j] & ~toclear) | toset;
+ return 0;
+}
+
+#endif
+
+int caml_page_table_add(int kind, void * start, void * end)
+{
+ uintnat pstart = (uintnat) start & Page_mask;
+ uintnat pend = ((uintnat) end - 1) & Page_mask;
+ uintnat p;
+
+ for (p = pstart; p <= pend; p += Page_size)
+ if (caml_page_table_modify(p, 0, kind) != 0) return -1;
+ return 0;
+}
+
+int caml_page_table_remove(int kind, void * start, void * end)
+{
+ uintnat pstart = (uintnat) start & Page_mask;
+ uintnat pend = ((uintnat) end - 1) & Page_mask;
+ uintnat p;
+
+ for (p = pstart; p <= pend; p += Page_size)
+ if (caml_page_table_modify(p, kind, 0) != 0) return -1;
+ return 0;
+}
+
+/* Allocate a block of the requested size, to be passed to
+ [caml_add_to_heap] later.
+ [request] must be a multiple of [Page_size], it is a number of bytes.
+ [caml_alloc_for_heap] returns NULL if the request cannot be satisfied.
+ The returned pointer is a hp, but the header must be initialized by
+ the caller.
+*/
+char *caml_alloc_for_heap (asize_t request)
+{
+ char *mem;
+ void *block;
+ Assert (request % Page_size == 0);
+ mem = caml_aligned_malloc (request + sizeof (heap_chunk_head),
+ sizeof (heap_chunk_head), &block);
+ if (mem == NULL) return NULL;
+ mem += sizeof (heap_chunk_head);
+ Chunk_size (mem) = request;
+ Chunk_block (mem) = block;
+ return mem;
+}
+
+/* Use this function to free a block allocated with [caml_alloc_for_heap]
+ if you don't add it with [caml_add_to_heap].
+*/
+void caml_free_for_heap (char *mem)
+{
+ free (Chunk_block (mem));
+}
+
+/* Take a chunk of memory as argument, which must be the result of a
+ call to [caml_alloc_for_heap], and insert it into the heap chaining.
+ The contents of the chunk must be a sequence of valid blocks and
+ fragments: no space between blocks and no trailing garbage. If
+ some blocks are blue, they must be added to the free list by the
+ caller. All other blocks must have the color [caml_allocation_color(m)].
+ The caller must update [caml_allocated_words] if applicable.
+ Return value: 0 if no error; -1 in case of error.
+
+ See also: caml_compact_heap, which duplicates most of this function.
+*/
+int caml_add_to_heap (char *m)
+{
+ Assert (Chunk_size (m) % Page_size == 0);
+#ifdef DEBUG
+ /* Should check the contents of the block. */
+#endif /* debug */
+
+ caml_gc_message (0x04, "Growing heap to %luk bytes\n",
+ (Bsize_wsize (caml_stat_heap_wsz) + Chunk_size (m)) / 1024);
+
+ /* Register block in page table */
+ if (caml_page_table_add(In_heap, m, m + Chunk_size(m)) != 0)
+ return -1;
+
+ /* Chain this heap chunk. */
+ {
+ char **last = &caml_heap_start;
+ char *cur = *last;
+
+ while (cur != NULL && cur < m){
+ last = &(Chunk_next (cur));
+ cur = *last;
+ }
+ Chunk_next (m) = cur;
+ *last = m;
+
+ ++ caml_stat_heap_chunks;
+ }
+
+ caml_stat_heap_wsz += Wsize_bsize (Chunk_size (m));
+ if (caml_stat_heap_wsz > caml_stat_top_heap_wsz){
+ caml_stat_top_heap_wsz = caml_stat_heap_wsz;
+ }
+ return 0;
+}
+
+/* Allocate more memory from malloc for the heap.
+ Return a blue block of at least the requested size.
+ The blue block is chained to a sequence of blue blocks (through their
+ field 0); the last block of the chain is pointed by field 1 of the
+ first. There may be a fragment after the last block.
+ The caller must insert the blocks into the free list.
+ [request] is a number of words and must be less than or equal
+ to [Max_wosize].
+ Return NULL when out of memory.
+*/
+static value *expand_heap (mlsize_t request)
+{
+ /* these point to headers, but we do arithmetic on them, hence [value *]. */
+ value *mem, *hp, *prev;
+ asize_t over_request, malloc_request, remain;
+
+ Assert (request <= Max_wosize);
+ over_request = Whsize_wosize (request + request / 100 * caml_percent_free);
+ malloc_request = caml_round_heap_chunk_wsz (over_request);
+ mem = (value *) caml_alloc_for_heap (Bsize_wsize (malloc_request));
+ if (mem == NULL){
+ caml_gc_message (0x04, "No room for growing heap\n", 0);
+ return NULL;
+ }
+ remain = malloc_request;
+ prev = hp = mem;
+ /* FIXME find a way to do this with a call to caml_make_free_blocks */
+ while (Wosize_whsize (remain) > Max_wosize){
+ Hd_hp (hp) = Make_header (Max_wosize, 0, Caml_blue);
+#ifdef DEBUG
+ caml_set_fields (Val_hp (hp), 0, Debug_free_major);
+#endif
+ hp += Whsize_wosize (Max_wosize);
+ remain -= Whsize_wosize (Max_wosize);
+ Field (Val_hp (mem), 1) = Field (Val_hp (prev), 0) = Val_hp (hp);
+ prev = hp;
+ }
+ if (remain > 1){
+ Hd_hp (hp) = Make_header (Wosize_whsize (remain), 0, Caml_blue);
+#ifdef DEBUG
+ caml_set_fields (Val_hp (hp), 0, Debug_free_major);
+#endif
+ Field (Val_hp (mem), 1) = Field (Val_hp (prev), 0) = Val_hp (hp);
+ Field (Val_hp (hp), 0) = (value) NULL;
+ }else{
+ Field (Val_hp (prev), 0) = (value) NULL;
+ if (remain == 1) Hd_hp (hp) = Make_header (0, 0, Caml_white);
+ }
+ Assert (Wosize_hp (mem) >= request);
+ if (caml_add_to_heap ((char *) mem) != 0){
+ caml_free_for_heap ((char *) mem);
+ return NULL;
+ }
+ return Op_hp (mem);
+}
+
+/* Remove the heap chunk [chunk] from the heap and give the memory back
+ to [free].
+*/
+void caml_shrink_heap (char *chunk)
+{
+ char **cp;
+
+ /* Never deallocate the first chunk, because caml_heap_start is both the
+ first block and the base address for page numbers, and we don't
+ want to shift the page table, it's too messy (see above).
+ It will never happen anyway, because of the way compaction works.
+ (see compact.c)
+ XXX FIXME this has become false with the fix to PR#5389 (see compact.c)
+ */
+ if (chunk == caml_heap_start) return;
+
+ caml_stat_heap_wsz -= Wsize_bsize (Chunk_size (chunk));
+ caml_gc_message (0x04, "Shrinking heap to %luk words\n",
+ (unsigned long) caml_stat_heap_wsz / 1024);
+
+#ifdef DEBUG
+ {
+ mlsize_t i;
+ for (i = 0; i < Wsize_bsize (Chunk_size (chunk)); i++){
+ ((value *) chunk) [i] = Debug_free_shrink;
+ }
+ }
+#endif
+
+ -- caml_stat_heap_chunks;
+
+ /* Remove [chunk] from the list of chunks. */
+ cp = &caml_heap_start;
+ while (*cp != chunk) cp = &(Chunk_next (*cp));
+ *cp = Chunk_next (chunk);
+
+ /* Remove the pages of [chunk] from the page table. */
+ caml_page_table_remove(In_heap, chunk, chunk + Chunk_size (chunk));
+
+ /* Free the [malloc] block that contains [chunk]. */
+ caml_free_for_heap (chunk);
+}
+
+color_t caml_allocation_color (void *hp)
+{
+ if (caml_gc_phase == Phase_mark
+ || (caml_gc_phase == Phase_sweep && (addr)hp >= (addr)caml_gc_sweep_hp)){
+ return Caml_black;
+ }else{
+ Assert (caml_gc_phase == Phase_idle
+ || (caml_gc_phase == Phase_sweep
+ && (addr)hp < (addr)caml_gc_sweep_hp));
+ return Caml_white;
+ }
+}
+
+CAMLexport value caml_alloc_shr (mlsize_t wosize, tag_t tag)
+{
+ header_t *hp;
+ value *new_block;
+
+ if (wosize > Max_wosize) caml_raise_out_of_memory ();
+ hp = caml_fl_allocate (wosize);
+ if (hp == NULL){
+ new_block = expand_heap (wosize);
+ if (new_block == NULL) {
+ if (caml_in_minor_collection)
+ caml_fatal_error ("Fatal error: out of memory.\n");
+ else
+ caml_raise_out_of_memory ();
+ }
+ caml_fl_add_blocks ((value) new_block);
+ hp = caml_fl_allocate (wosize);
+ }
+
+ Assert (Is_in_heap (Val_hp (hp)));
+
+ /* Inline expansion of caml_allocation_color. */
+ if (caml_gc_phase == Phase_mark
+ || (caml_gc_phase == Phase_sweep && (addr)hp >= (addr)caml_gc_sweep_hp)){
+ Hd_hp (hp) = Make_header (wosize, tag, Caml_black);
+ }else{
+ Assert (caml_gc_phase == Phase_idle
+ || (caml_gc_phase == Phase_sweep
+ && (addr)hp < (addr)caml_gc_sweep_hp));
+ Hd_hp (hp) = Make_header (wosize, tag, Caml_white);
+ }
+ Assert (Hd_hp (hp) == Make_header (wosize, tag, caml_allocation_color (hp)));
+ caml_allocated_words += Whsize_wosize (wosize);
+ if (caml_allocated_words > caml_minor_heap_wsz){
+ caml_urge_major_slice ();
+ }
+#ifdef DEBUG
+ {
+ uintnat i;
+ for (i = 0; i < wosize; i++){
+ Field (Val_hp (hp), i) = Debug_uninit_major;
+ }
+ }
+#endif
+ return Val_hp (hp);
+}
+
+/* Dependent memory is all memory blocks allocated out of the heap
+ that depend on the GC (and finalizers) for deallocation.
+ For the GC to take dependent memory into account when computing
+ its automatic speed setting,
+ you must call [caml_alloc_dependent_memory] when you alloate some
+ dependent memory, and [caml_free_dependent_memory] when you
+ free it. In both cases, you pass as argument the size (in bytes)
+ of the block being allocated or freed.
+*/
+CAMLexport void caml_alloc_dependent_memory (mlsize_t nbytes)
+{
+ caml_dependent_size += nbytes / sizeof (value);
+ caml_dependent_allocated += nbytes / sizeof (value);
+}
+
+CAMLexport void caml_free_dependent_memory (mlsize_t nbytes)
+{
+ if (caml_dependent_size < nbytes / sizeof (value)){
+ caml_dependent_size = 0;
+ }else{
+ caml_dependent_size -= nbytes / sizeof (value);
+ }
+}
+
+/* Use this function to tell the major GC to speed up when you use
+ finalized blocks to automatically deallocate resources (other
+ than memory). The GC will do at least one cycle every [max]
+ allocated resources; [res] is the number of resources allocated
+ this time.
+ Note that only [res/max] is relevant. The units (and kind of
+ resource) can change between calls to [caml_adjust_gc_speed].
+*/
+CAMLexport void caml_adjust_gc_speed (mlsize_t res, mlsize_t max)
+{
+ if (max == 0) max = 1;
+ if (res > max) res = max;
+ caml_extra_heap_resources += (double) res / (double) max;
+ if (caml_extra_heap_resources > 1.0){
+ caml_extra_heap_resources = 1.0;
+ caml_urge_major_slice ();
+ }
+ if (caml_extra_heap_resources
+ > (double) caml_minor_heap_wsz / 2.0
+ / (double) caml_stat_heap_wsz) {
+ caml_urge_major_slice ();
+ }
+}
+
+/* You must use [caml_initialize] to store the initial value in a field of
+ a shared block, unless you are sure the value is not a young block.
+ A block value [v] is a shared block if and only if [Is_in_heap (v)]
+ is true.
+*/
+/* [caml_initialize] never calls the GC, so you may call it while a block is
+ unfinished (i.e. just after a call to [caml_alloc_shr].) */
+/* PR#6084 workaround: define it as a weak symbol */
+CAMLexport CAMLweakdef void caml_initialize (value *fp, value val)
+{
+ CAMLassert(Is_in_heap(fp));
+ *fp = val;
+ if (Is_block (val) && Is_young (val)) {
+ if (caml_ref_table.ptr >= caml_ref_table.limit){
+ caml_realloc_ref_table (&caml_ref_table);
+ }
+ *caml_ref_table.ptr++ = fp;
+ }
+}
+
+/* You must use [caml_modify] to change a field of an existing shared block,
+ unless you are sure the value being overwritten is not a shared block and
+ the value being written is not a young block. */
+/* [caml_modify] never calls the GC. */
+/* [caml_modify] can also be used to do assignment on data structures that are
+ in the minor heap instead of in the major heap. In this case, it
+ is a bit slower than simple assignment.
+ In particular, you can use [caml_modify] when you don't know whether the
+ block being changed is in the minor heap or the major heap. */
+/* PR#6084 workaround: define it as a weak symbol */
+
+CAMLexport CAMLweakdef void caml_modify (value *fp, value val)
+{
+ /* The write barrier implemented by [caml_modify] checks for the
+ following two conditions and takes appropriate action:
+ 1- a pointer from the major heap to the minor heap is created
+ --> add [fp] to the remembered set
+ 2- a pointer from the major heap to the major heap is overwritten,
+ while the GC is in the marking phase
+ --> call [caml_darken] on the overwritten pointer so that the
+ major GC treats it as an additional root.
+ */
+ value old;
+
+ if (Is_young((value)fp)) {
+ /* The modified object resides in the minor heap.
+ Conditions 1 and 2 cannot occur. */
+ *fp = val;
+ } else {
+ /* The modified object resides in the major heap. */
+ CAMLassert(Is_in_heap(fp));
+ old = *fp;
+ *fp = val;
+ if (Is_block(old)) {
+ /* If [old] is a pointer within the minor heap, we already
+ have a major->minor pointer and [fp] is already in the
+ remembered set. Conditions 1 and 2 cannot occur. */
+ if (Is_young(old)) return;
+ /* Here, [old] can be a pointer within the major heap.
+ Check for condition 2. */
+ if (caml_gc_phase == Phase_mark) caml_darken(old, NULL);
+ }
+ /* Check for condition 1. */
+ if (Is_block(val) && Is_young(val)) {
+ /* Add [fp] to remembered set */
+ if (caml_ref_table.ptr >= caml_ref_table.limit){
+ CAMLassert (caml_ref_table.ptr == caml_ref_table.limit);
+ caml_realloc_ref_table (&caml_ref_table);
+ }
+ *caml_ref_table.ptr++ = fp;
+ }
+ }
+}
+
+/* [sz] is a number of bytes */
+CAMLexport void * caml_stat_alloc (asize_t sz)
+{
+ void * result = malloc (sz);
+
+ /* malloc() may return NULL if size is 0 */
+ if (result == NULL && sz != 0) caml_raise_out_of_memory ();
+#ifdef DEBUG
+ memset (result, Debug_uninit_stat, sz);
+#endif
+ return result;
+}
+
+CAMLexport void caml_stat_free (void * blk)
+{
+ free (blk);
+}
+
+/* [sz] is a number of bytes */
+CAMLexport void * caml_stat_resize (void * blk, asize_t sz)
+{
+ void * result = realloc (blk, sz);
+
+ if (result == NULL) caml_raise_out_of_memory ();
+ return result;
+}
diff --git a/byterun/meta.c b/byterun/meta.c
new file mode 100644
index 0000000000..32cd6dd717
--- /dev/null
+++ b/byterun/meta.c
@@ -0,0 +1,223 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Primitives for the toplevel */
+
+#include <string.h>
+#include "caml/alloc.h"
+#include "caml/config.h"
+#include "caml/fail.h"
+#include "caml/fix_code.h"
+#include "caml/interp.h"
+#include "caml/intext.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/minor_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/prims.h"
+#include "caml/stacks.h"
+
+#ifndef NATIVE_CODE
+
+CAMLprim value caml_get_global_data(value unit)
+{
+ return caml_global_data;
+}
+
+char * caml_section_table = NULL;
+asize_t caml_section_table_size;
+
+CAMLprim value caml_get_section_table(value unit)
+{
+ if (caml_section_table == NULL) caml_raise_not_found();
+ return caml_input_value_from_block(caml_section_table,
+ caml_section_table_size);
+}
+
+CAMLprim value caml_reify_bytecode(value prog, value len)
+{
+ struct code_fragment * cf = caml_stat_alloc(sizeof(struct code_fragment));
+ value clos;
+
+ cf->code_start = (char *) prog;
+ cf->code_end = (char *) prog + Long_val(len);
+ cf->digest_computed = 0;
+ caml_ext_table_add(&caml_code_fragments_table, cf);
+
+#ifdef ARCH_BIG_ENDIAN
+ caml_fixup_endianness((code_t) prog, (asize_t) Long_val(len));
+#endif
+#ifdef THREADED_CODE
+ caml_thread_code((code_t) prog, (asize_t) Long_val(len));
+#endif
+ caml_prepare_bytecode((code_t) prog, (asize_t) Long_val(len));
+ clos = caml_alloc_small (1, Closure_tag);
+ Code_val(clos) = (code_t) prog;
+ return clos;
+}
+
+/* signal to the interpreter machinery that a bytecode is no more
+ needed (before freeing it) - this might be useful for a JIT
+ implementation */
+
+CAMLprim value caml_static_release_bytecode(value prog, value len)
+{
+ struct code_fragment * cf = NULL, * cfi;
+ int i;
+ for (i = 0; i < caml_code_fragments_table.size; i++) {
+ cfi = (struct code_fragment *) caml_code_fragments_table.contents[i];
+ if (cfi->code_start == (char *) prog &&
+ cfi->code_end == (char *) prog + Long_val(len)) {
+ cf = cfi;
+ break;
+ }
+ }
+
+ if (!cf) {
+ /* [cf] Not matched with a caml_reify_bytecode call; impossible. */
+ Assert (0);
+ } else {
+ caml_ext_table_remove(&caml_code_fragments_table, cf);
+ }
+
+#ifndef NATIVE_CODE
+ caml_release_bytecode((code_t) prog, (asize_t) Long_val(len));
+#else
+ caml_failwith("Meta.static_release_bytecode impossible with native code");
+#endif
+ return Val_unit;
+}
+
+CAMLprim value caml_register_code_fragment(value prog, value len, value digest)
+{
+ struct code_fragment * cf = caml_stat_alloc(sizeof(struct code_fragment));
+ cf->code_start = (char *) prog;
+ cf->code_end = (char *) prog + Long_val(len);
+ memcpy(cf->digest, String_val(digest), 16);
+ cf->digest_computed = 1;
+ caml_ext_table_add(&caml_code_fragments_table, cf);
+ return Val_unit;
+}
+
+CAMLprim value caml_realloc_global(value size)
+{
+ mlsize_t requested_size, actual_size, i;
+ value new_global_data;
+
+ requested_size = Long_val(size);
+ actual_size = Wosize_val(caml_global_data);
+ if (requested_size >= actual_size) {
+ requested_size = (requested_size + 0x100) & 0xFFFFFF00;
+ caml_gc_message (0x08, "Growing global data to %lu entries\n",
+ requested_size);
+ new_global_data = caml_alloc_shr(requested_size, 0);
+ for (i = 0; i < actual_size; i++)
+ caml_initialize(&Field(new_global_data, i), Field(caml_global_data, i));
+ for (i = actual_size; i < requested_size; i++){
+ Field (new_global_data, i) = Val_long (0);
+ }
+ caml_global_data = new_global_data;
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_get_current_environment(value unit)
+{
+ return *caml_extern_sp;
+}
+
+CAMLprim value caml_invoke_traced_function(value codeptr, value env, value arg)
+{
+ /* Stack layout on entry:
+ return frame into instrument_closure function
+ arg3 to call_original_code (arg)
+ arg2 to call_original_code (env)
+ arg1 to call_original_code (codeptr)
+ arg3 to call_original_code (arg)
+ arg2 to call_original_code (env)
+ saved env */
+
+ /* Stack layout on exit:
+ return frame into instrument_closure function
+ actual arg to code (arg)
+ pseudo return frame into codeptr:
+ extra_args = 0
+ environment = env
+ PC = codeptr
+ arg3 to call_original_code (arg) same 6 bottom words as
+ arg2 to call_original_code (env) on entrance, but
+ arg1 to call_original_code (codeptr) shifted down 4 words
+ arg3 to call_original_code (arg)
+ arg2 to call_original_code (env)
+ saved env */
+
+ value * osp, * nsp;
+ int i;
+
+ osp = caml_extern_sp;
+ caml_extern_sp -= 4;
+ nsp = caml_extern_sp;
+ for (i = 0; i < 6; i++) nsp[i] = osp[i];
+ nsp[6] = codeptr;
+ nsp[7] = env;
+ nsp[8] = Val_int(0);
+ nsp[9] = arg;
+ return Val_unit;
+}
+
+#else
+
+/* Dummy definitions to support compilation of ocamlc.opt */
+
+value caml_get_global_data(value unit)
+{
+ caml_invalid_argument("Meta.get_global_data");
+ return Val_unit; /* not reached */
+}
+
+value caml_get_section_table(value unit)
+{
+ caml_invalid_argument("Meta.get_section_table");
+ return Val_unit; /* not reached */
+}
+
+value caml_realloc_global(value size)
+{
+ caml_invalid_argument("Meta.realloc_global");
+ return Val_unit; /* not reached */
+}
+
+value caml_invoke_traced_function(value codeptr, value env, value arg)
+{
+ caml_invalid_argument("Meta.invoke_traced_function");
+ return Val_unit; /* not reached */
+}
+
+value caml_reify_bytecode(value prog, value len)
+{
+ caml_invalid_argument("Meta.reify_bytecode");
+ return Val_unit; /* not reached */
+}
+
+value * caml_stack_low;
+value * caml_stack_high;
+value * caml_stack_threshold;
+value * caml_extern_sp;
+value * caml_trapsp;
+int caml_callback_depth;
+int volatile caml_something_to_do;
+void (* volatile caml_async_action_hook)(void);
+struct longjmp_buffer * caml_external_raise;
+
+#endif
diff --git a/byterun/minor_gc.c b/byterun/minor_gc.c
new file mode 100644
index 0000000000..54bb473320
--- /dev/null
+++ b/byterun/minor_gc.c
@@ -0,0 +1,341 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include "caml/custom.h"
+#include "caml/config.h"
+#include "caml/fail.h"
+#include "caml/finalise.h"
+#include "caml/gc.h"
+#include "caml/gc_ctrl.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/minor_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/roots.h"
+#include "caml/signals.h"
+#include "caml/weak.h"
+
+asize_t caml_minor_heap_wsz;
+static void *caml_young_base = NULL;
+CAMLexport value *caml_young_start = NULL, *caml_young_end = NULL;
+CAMLexport value *caml_young_ptr = NULL, *caml_young_limit = NULL;
+
+CAMLexport struct caml_ref_table
+ caml_ref_table = { NULL, NULL, NULL, NULL, NULL, 0, 0},
+ caml_weak_ref_table = { NULL, NULL, NULL, NULL, NULL, 0, 0},
+ caml_finalize_table = { NULL, NULL, NULL, NULL, NULL, 0, 0};
+/* table of custom blocks containing finalizers in the minor heap */
+
+int caml_in_minor_collection = 0;
+
+#ifdef DEBUG
+static unsigned long minor_gc_counter = 0;
+#endif
+
+/* [sz] and [rsv] are numbers of entries */
+void caml_alloc_table (struct caml_ref_table *tbl, asize_t sz, asize_t rsv)
+{
+ value **new_table;
+
+ tbl->size = sz;
+ tbl->reserve = rsv;
+ new_table = (value **) caml_stat_alloc ((tbl->size + tbl->reserve)
+ * sizeof (value *));
+ if (tbl->base != NULL) caml_stat_free (tbl->base);
+ tbl->base = new_table;
+ tbl->ptr = tbl->base;
+ tbl->threshold = tbl->base + tbl->size;
+ tbl->limit = tbl->threshold;
+ tbl->end = tbl->base + tbl->size + tbl->reserve;
+}
+
+static void reset_table (struct caml_ref_table *tbl)
+{
+ tbl->size = 0;
+ tbl->reserve = 0;
+ if (tbl->base != NULL) caml_stat_free (tbl->base);
+ tbl->base = tbl->ptr = tbl->threshold = tbl->limit = tbl->end = NULL;
+}
+
+static void clear_table (struct caml_ref_table *tbl)
+{
+ tbl->ptr = tbl->base;
+ tbl->limit = tbl->threshold;
+}
+
+/* [size] is a number of bytes */
+void caml_set_minor_heap_size (asize_t size)
+{
+ char *new_heap;
+ void *new_heap_base;
+
+ Assert (size >= Bsize_wsize(Minor_heap_min));
+ Assert (size <= Bsize_wsize(Minor_heap_max));
+ Assert (size % sizeof (value) == 0);
+ if (caml_young_ptr != caml_young_end) caml_minor_collection ();
+ Assert (caml_young_ptr == caml_young_end);
+ new_heap = caml_aligned_malloc(size, 0, &new_heap_base);
+ if (new_heap == NULL) caml_raise_out_of_memory();
+ if (caml_page_table_add(In_young, new_heap, new_heap + size) != 0)
+ caml_raise_out_of_memory();
+
+ if (caml_young_start != NULL){
+ caml_page_table_remove(In_young, caml_young_start, caml_young_end);
+ free (caml_young_base);
+ }
+ caml_young_base = new_heap_base;
+ caml_young_start = (value *) new_heap;
+ caml_young_end = (value *) (new_heap + size);
+ caml_young_limit = caml_young_start;
+ caml_young_ptr = caml_young_end;
+ caml_minor_heap_wsz = Wsize_bsize (size);
+
+ reset_table (&caml_ref_table);
+ reset_table (&caml_weak_ref_table);
+}
+
+static value oldify_todo_list = 0;
+
+/* Note that the tests on the tag depend on the fact that Infix_tag,
+ Forward_tag, and No_scan_tag are contiguous. */
+
+void caml_oldify_one (value v, value *p)
+{
+ value result;
+ header_t hd;
+ mlsize_t sz, i;
+ tag_t tag;
+
+ tail_call:
+ if (Is_block (v) && Is_young (v)){
+ Assert ((value *) Hp_val (v) >= caml_young_ptr);
+ hd = Hd_val (v);
+ if (hd == 0){ /* If already forwarded */
+ *p = Field (v, 0); /* then forward pointer is first field. */
+ }else{
+ tag = Tag_hd (hd);
+ if (tag < Infix_tag){
+ value field0;
+
+ sz = Wosize_hd (hd);
+ result = caml_alloc_shr (sz, tag);
+ *p = result;
+ field0 = Field (v, 0);
+ Hd_val (v) = 0; /* Set forward flag */
+ Field (v, 0) = result; /* and forward pointer. */
+ if (sz > 1){
+ Field (result, 0) = field0;
+ Field (result, 1) = oldify_todo_list; /* Add this block */
+ oldify_todo_list = v; /* to the "to do" list. */
+ }else{
+ Assert (sz == 1);
+ p = &Field (result, 0);
+ v = field0;
+ goto tail_call;
+ }
+ }else if (tag >= No_scan_tag){
+ sz = Wosize_hd (hd);
+ result = caml_alloc_shr (sz, tag);
+ for (i = 0; i < sz; i++) Field (result, i) = Field (v, i);
+ Hd_val (v) = 0; /* Set forward flag */
+ Field (v, 0) = result; /* and forward pointer. */
+ *p = result;
+ }else if (tag == Infix_tag){
+ mlsize_t offset = Infix_offset_hd (hd);
+ caml_oldify_one (v - offset, p); /* Cannot recurse deeper than 1. */
+ *p += offset;
+ }else{
+ value f = Forward_val (v);
+ tag_t ft = 0;
+ int vv = 1;
+
+ Assert (tag == Forward_tag);
+ if (Is_block (f)){
+ if (Is_young (f)){
+ vv = 1;
+ ft = Tag_val (Hd_val (f) == 0 ? Field (f, 0) : f);
+ }else{
+ vv = Is_in_value_area(f);
+ if (vv){
+ ft = Tag_val (f);
+ }
+ }
+ }
+ if (!vv || ft == Forward_tag || ft == Lazy_tag || ft == Double_tag){
+ /* Do not short-circuit the pointer. Copy as a normal block. */
+ Assert (Wosize_hd (hd) == 1);
+ result = caml_alloc_shr (1, Forward_tag);
+ *p = result;
+ Hd_val (v) = 0; /* Set (GC) forward flag */
+ Field (v, 0) = result; /* and forward pointer. */
+ p = &Field (result, 0);
+ v = f;
+ goto tail_call;
+ }else{
+ v = f; /* Follow the forwarding */
+ goto tail_call; /* then oldify. */
+ }
+ }
+ }
+ }else{
+ *p = v;
+ }
+}
+
+/* Finish the work that was put off by [caml_oldify_one].
+ Note that [caml_oldify_one] itself is called by oldify_mopup, so we
+ have to be careful to remove the first entry from the list before
+ oldifying its fields. */
+void caml_oldify_mopup (void)
+{
+ value v, new_v, f;
+ mlsize_t i;
+
+ while (oldify_todo_list != 0){
+ v = oldify_todo_list; /* Get the head. */
+ Assert (Hd_val (v) == 0); /* It must be forwarded. */
+ new_v = Field (v, 0); /* Follow forward pointer. */
+ oldify_todo_list = Field (new_v, 1); /* Remove from list. */
+
+ f = Field (new_v, 0);
+ if (Is_block (f) && Is_young (f)){
+ caml_oldify_one (f, &Field (new_v, 0));
+ }
+ for (i = 1; i < Wosize_val (new_v); i++){
+ f = Field (v, i);
+ if (Is_block (f) && Is_young (f)){
+ caml_oldify_one (f, &Field (new_v, i));
+ }else{
+ Field (new_v, i) = f;
+ }
+ }
+ }
+}
+
+/* Make sure the minor heap is empty by performing a minor collection
+ if needed.
+*/
+void caml_empty_minor_heap (void)
+{
+ value **r;
+ uintnat prev_alloc_words;
+
+ if (caml_young_ptr != caml_young_end){
+ if (caml_minor_gc_begin_hook != NULL) (*caml_minor_gc_begin_hook) ();
+ prev_alloc_words = caml_allocated_words;
+ caml_in_minor_collection = 1;
+ caml_gc_message (0x02, "<", 0);
+ caml_oldify_local_roots();
+ for (r = caml_ref_table.base; r < caml_ref_table.ptr; r++){
+ caml_oldify_one (**r, *r);
+ }
+ caml_oldify_mopup ();
+ for (r = caml_weak_ref_table.base; r < caml_weak_ref_table.ptr; r++){
+ if (Is_block (**r) && Is_young (**r)){
+ if (Hd_val (**r) == 0){
+ **r = Field (**r, 0);
+ }else{
+ **r = caml_weak_none;
+ }
+ }
+ }
+ for (r = caml_finalize_table.base; r < caml_finalize_table.ptr; r++){
+ int hd = Hd_val ((value)*r);
+ if (hd != 0){ /* If not oldified the finalizer must be called */
+ void (*final_fun)(value) = Custom_ops_val((value)*r)->finalize;
+ final_fun((value)*r);
+ }
+ }
+ if (caml_young_ptr < caml_young_start) caml_young_ptr = caml_young_start;
+ caml_stat_minor_words += caml_young_end - caml_young_ptr;
+ caml_young_ptr = caml_young_end;
+ caml_young_limit = caml_young_start;
+ clear_table (&caml_ref_table);
+ clear_table (&caml_weak_ref_table);
+ clear_table (&caml_finalize_table);
+ caml_gc_message (0x02, ">", 0);
+ caml_in_minor_collection = 0;
+ caml_stat_promoted_words += caml_allocated_words - prev_alloc_words;
+ ++ caml_stat_minor_collections;
+ caml_final_empty_young ();
+ if (caml_minor_gc_end_hook != NULL) (*caml_minor_gc_end_hook) ();
+ }else{
+ caml_final_empty_young ();
+ }
+#ifdef DEBUG
+ {
+ value *p;
+ for (p = caml_young_start; p < caml_young_end; ++p){
+ *p = Debug_free_minor;
+ }
+ ++ minor_gc_counter;
+ }
+#endif
+}
+
+/* Do a minor collection and a slice of major collection, call finalisation
+ functions, etc.
+ Leave the minor heap empty.
+*/
+CAMLexport void caml_minor_collection (void)
+{
+ caml_empty_minor_heap ();
+
+ caml_major_collection_slice (0);
+ caml_force_major_slice = 0;
+
+ caml_final_do_calls ();
+
+ caml_empty_minor_heap ();
+}
+
+CAMLexport value caml_check_urgent_gc (value extra_root)
+{
+ CAMLparam1 (extra_root);
+ if (caml_force_major_slice) caml_minor_collection();
+ CAMLreturn (extra_root);
+}
+
+void caml_realloc_ref_table (struct caml_ref_table *tbl)
+{ Assert (tbl->ptr == tbl->limit);
+ Assert (tbl->limit <= tbl->end);
+ Assert (tbl->limit >= tbl->threshold);
+
+ if (tbl->base == NULL){
+ caml_alloc_table (tbl, caml_minor_heap_wsz / 8, 256);
+ }else if (tbl->limit == tbl->threshold){
+ caml_gc_message (0x08, "ref_table threshold crossed\n", 0);
+ tbl->limit = tbl->end;
+ caml_urge_major_slice ();
+ }else{ /* This will almost never happen with the bytecode interpreter. */
+ asize_t sz;
+ asize_t cur_ptr = tbl->ptr - tbl->base;
+ Assert (caml_force_major_slice);
+
+ tbl->size *= 2;
+ sz = (tbl->size + tbl->reserve) * sizeof (value *);
+ caml_gc_message (0x08, "Growing ref_table to %"
+ ARCH_INTNAT_PRINTF_FORMAT "dk bytes\n",
+ (intnat) sz/1024);
+ tbl->base = (value **) realloc ((char *) tbl->base, sz);
+ if (tbl->base == NULL){
+ caml_fatal_error ("Fatal error: ref_table overflow\n");
+ }
+ tbl->end = tbl->base + tbl->size + tbl->reserve;
+ tbl->threshold = tbl->base + tbl->size;
+ tbl->ptr = tbl->base + cur_ptr;
+ tbl->limit = tbl->end;
+ }
+}
diff --git a/byterun/misc.c b/byterun/misc.c
new file mode 100644
index 0000000000..f4738bbeea
--- /dev/null
+++ b/byterun/misc.c
@@ -0,0 +1,197 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+#include "caml/config.h"
+#include "caml/misc.h"
+#include "caml/memory.h"
+
+caml_timing_hook caml_major_slice_begin_hook = NULL;
+caml_timing_hook caml_major_slice_end_hook = NULL;
+caml_timing_hook caml_minor_gc_begin_hook = NULL;
+caml_timing_hook caml_minor_gc_end_hook = NULL;
+caml_timing_hook caml_finalise_begin_hook = NULL;
+caml_timing_hook caml_finalise_end_hook = NULL;
+
+#ifdef DEBUG
+
+int caml_failed_assert (char * expr, char * file, int line)
+{
+ fprintf (stderr, "file %s; line %d ### Assertion failed: %s\n",
+ file, line, expr);
+ fflush (stderr);
+ exit (100);
+}
+
+void caml_set_fields (value v, unsigned long start, unsigned long filler)
+{
+ mlsize_t i;
+ for (i = start; i < Wosize_val (v); i++){
+ Field (v, i) = (value) filler;
+ }
+}
+
+#endif /* DEBUG */
+
+uintnat caml_verb_gc = 0;
+
+void caml_gc_message (int level, char *msg, uintnat arg)
+{
+ if (level < 0 || (caml_verb_gc & level) != 0){
+ fprintf (stderr, msg, arg);
+ fflush (stderr);
+ }
+}
+
+CAMLexport void caml_fatal_error (char *msg)
+{
+ fprintf (stderr, "%s", msg);
+ exit(2);
+}
+
+CAMLexport void caml_fatal_error_arg (char *fmt, char *arg)
+{
+ fprintf (stderr, fmt, arg);
+ exit(2);
+}
+
+CAMLexport void caml_fatal_error_arg2 (char *fmt1, char *arg1,
+ char *fmt2, char *arg2)
+{
+ fprintf (stderr, fmt1, arg1);
+ fprintf (stderr, fmt2, arg2);
+ exit(2);
+}
+
+/* [size] and [modulo] are numbers of bytes */
+char *caml_aligned_malloc (asize_t size, int modulo, void **block)
+{
+ char *raw_mem;
+ uintnat aligned_mem;
+ Assert (modulo < Page_size);
+ raw_mem = (char *) malloc (size + Page_size);
+ if (raw_mem == NULL) return NULL;
+ *block = raw_mem;
+ raw_mem += modulo; /* Address to be aligned */
+ aligned_mem = (((uintnat) raw_mem / Page_size + 1) * Page_size);
+#ifdef DEBUG
+ {
+ uintnat *p;
+ uintnat *p0 = (void *) *block,
+ *p1 = (void *) (aligned_mem - modulo),
+ *p2 = (void *) (aligned_mem - modulo + size),
+ *p3 = (void *) ((char *) *block + size + Page_size);
+
+ for (p = p0; p < p1; p++) *p = Debug_filler_align;
+ for (p = p1; p < p2; p++) *p = Debug_uninit_align;
+ for (p = p2; p < p3; p++) *p = Debug_filler_align;
+ }
+#endif
+ return (char *) (aligned_mem - modulo);
+}
+
+void caml_ext_table_init(struct ext_table * tbl, int init_capa)
+{
+ tbl->size = 0;
+ tbl->capacity = init_capa;
+ tbl->contents = caml_stat_alloc(sizeof(void *) * init_capa);
+}
+
+int caml_ext_table_add(struct ext_table * tbl, void * data)
+{
+ int res;
+ if (tbl->size >= tbl->capacity) {
+ tbl->capacity *= 2;
+ tbl->contents =
+ caml_stat_resize(tbl->contents, sizeof(void *) * tbl->capacity);
+ }
+ res = tbl->size;
+ tbl->contents[res] = data;
+ tbl->size++;
+ return res;
+}
+
+void caml_ext_table_remove(struct ext_table * tbl, void * data)
+{
+ int i;
+ for (i = 0; i < tbl->size; i++) {
+ if (tbl->contents[i] == data) {
+ caml_stat_free(tbl->contents[i]);
+ memmove(&tbl->contents[i], &tbl->contents[i + 1],
+ (tbl->size - i - 1) * sizeof(void *));
+ tbl->size--;
+ }
+ }
+}
+
+void caml_ext_table_free(struct ext_table * tbl, int free_entries)
+{
+ int i;
+ if (free_entries)
+ for (i = 0; i < tbl->size; i++) caml_stat_free(tbl->contents[i]);
+ caml_stat_free(tbl->contents);
+}
+
+CAMLexport char * caml_strdup(const char * s)
+{
+ size_t slen = strlen(s);
+ char * res = caml_stat_alloc(slen + 1);
+ memcpy(res, s, slen + 1);
+ return res;
+}
+
+CAMLexport char * caml_strconcat(int n, ...)
+{
+ va_list args;
+ char * res, * p;
+ size_t len;
+ int i;
+
+ len = 0;
+ va_start(args, n);
+ for (i = 0; i < n; i++) {
+ const char * s = va_arg(args, const char *);
+ len += strlen(s);
+ }
+ va_end(args);
+ res = caml_stat_alloc(len + 1);
+ va_start(args, n);
+ p = res;
+ for (i = 0; i < n; i++) {
+ const char * s = va_arg(args, const char *);
+ size_t l = strlen(s);
+ memcpy(p, s, l);
+ p += l;
+ }
+ va_end(args);
+ *p = 0;
+ return res;
+}
+
+/* Runtime warnings */
+
+uintnat caml_runtime_warnings = 1;
+static int caml_runtime_warnings_first = 1;
+
+int caml_runtime_warnings_active(void)
+{
+ if (!caml_runtime_warnings) return 0;
+ if (caml_runtime_warnings_first) {
+ fprintf(stderr, "[ocaml] (use Sys.enable_runtime_warnings to control "
+ "these warnings)\n");
+ caml_runtime_warnings_first = 0;
+ }
+ return 1;
+}
diff --git a/byterun/obj.c b/byterun/obj.c
new file mode 100644
index 0000000000..27b50d9a3d
--- /dev/null
+++ b/byterun/obj.c
@@ -0,0 +1,250 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Operations on objects */
+
+#include <string.h>
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/gc.h"
+#include "caml/interp.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/minor_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/prims.h"
+
+/* [size] is a value encoding a number of bytes */
+CAMLprim value caml_static_alloc(value size)
+{
+ return (value) caml_stat_alloc((asize_t) Long_val(size));
+}
+
+CAMLprim value caml_static_free(value blk)
+{
+ caml_stat_free((void *) blk);
+ return Val_unit;
+}
+
+CAMLprim value caml_static_resize(value blk, value new_size)
+{
+ return (value) caml_stat_resize((char *) blk, (asize_t) Long_val(new_size));
+}
+
+CAMLprim value caml_obj_is_block(value arg)
+{
+ return Val_bool(Is_block(arg));
+}
+
+CAMLprim value caml_obj_tag(value arg)
+{
+ if (Is_long (arg)){
+ return Val_int (1000); /* int_tag */
+ }else if ((long) arg & (sizeof (value) - 1)){
+ return Val_int (1002); /* unaligned_tag */
+ }else if (Is_in_value_area (arg)){
+ return Val_int(Tag_val(arg));
+ }else{
+ return Val_int (1001); /* out_of_heap_tag */
+ }
+}
+
+CAMLprim value caml_obj_set_tag (value arg, value new_tag)
+{
+ Tag_val (arg) = Int_val (new_tag);
+ return Val_unit;
+}
+
+/* [size] is a value encoding a number of blocks */
+CAMLprim value caml_obj_block(value tag, value size)
+{
+ value res;
+ mlsize_t sz, i;
+ tag_t tg;
+
+ sz = Long_val(size);
+ tg = Long_val(tag);
+ if (sz == 0) return Atom(tg);
+ res = caml_alloc(sz, tg);
+ for (i = 0; i < sz; i++)
+ Field(res, i) = Val_long(0);
+
+ return res;
+}
+
+CAMLprim value caml_obj_dup(value arg)
+{
+ CAMLparam1 (arg);
+ CAMLlocal1 (res);
+ mlsize_t sz, i;
+ tag_t tg;
+
+ sz = Wosize_val(arg);
+ if (sz == 0) CAMLreturn (arg);
+ tg = Tag_val(arg);
+ if (tg >= No_scan_tag) {
+ res = caml_alloc(sz, tg);
+ memcpy(Bp_val(res), Bp_val(arg), sz * sizeof(value));
+ } else if (sz <= Max_young_wosize) {
+ res = caml_alloc_small(sz, tg);
+ for (i = 0; i < sz; i++) Field(res, i) = Field(arg, i);
+ } else {
+ res = caml_alloc_shr(sz, tg);
+ for (i = 0; i < sz; i++) caml_initialize(&Field(res, i), Field(arg, i));
+ }
+ CAMLreturn (res);
+}
+
+/* Shorten the given block to the given size and return void.
+ Raise Invalid_argument if the given size is less than or equal
+ to 0 or greater than the current size.
+
+ algorithm:
+ Change the length field of the header. Make up a white object
+ with the leftover part of the object: this is needed in the major
+ heap and harmless in the minor heap.
+
+ [newsize] is a value encoding a number of words.
+*/
+CAMLprim value caml_obj_truncate (value v, value newsize)
+{
+ mlsize_t new_wosize = Long_val (newsize);
+ header_t hd = Hd_val (v);
+ tag_t tag = Tag_hd (hd);
+ color_t color = Color_hd (hd);
+ mlsize_t wosize = Wosize_hd (hd);
+ mlsize_t i;
+
+ if (tag == Double_array_tag) new_wosize *= Double_wosize; /* PR#156 */
+
+ if (new_wosize <= 0 || new_wosize > wosize){
+ caml_invalid_argument ("Obj.truncate");
+ }
+ if (new_wosize == wosize) return Val_unit;
+ /* PR#61: since we're about to lose our references to the elements
+ beyond new_wosize in v, erase them explicitly so that the GC
+ can darken them as appropriate. */
+ if (tag < No_scan_tag) {
+ for (i = new_wosize; i < wosize; i++){
+ caml_modify(&Field(v, i), Val_unit);
+#ifdef DEBUG
+ Field (v, i) = Debug_free_truncate;
+#endif
+ }
+ }
+ /* We must use an odd tag for the header of the leftovers so it does not
+ look like a pointer because there may be some references to it in
+ ref_table. */
+ Field (v, new_wosize) =
+ Make_header (Wosize_whsize (wosize-new_wosize), 1, Caml_white);
+ Hd_val (v) = Make_header (new_wosize, tag, color);
+ return Val_unit;
+}
+
+CAMLprim value caml_obj_add_offset (value v, value offset)
+{
+ return v + (unsigned long) Int32_val (offset);
+}
+
+/* The following functions are used in stdlib/lazy.ml.
+ They are not written in OCaml because they must be atomic with respect
+ to the GC.
+ */
+
+CAMLprim value caml_lazy_follow_forward (value v)
+{
+ if (Is_block (v) && Is_in_value_area(v)
+ && Tag_val (v) == Forward_tag){
+ return Forward_val (v);
+ }else{
+ return v;
+ }
+}
+
+CAMLprim value caml_lazy_make_forward (value v)
+{
+ CAMLparam1 (v);
+ CAMLlocal1 (res);
+
+ res = caml_alloc_small (1, Forward_tag);
+ Field (res, 0) = v;
+ CAMLreturn (res);
+}
+
+/* For mlvalues.h and camlinternalOO.ml
+ See also GETPUBMET in interp.c
+ */
+
+CAMLprim value caml_get_public_method (value obj, value tag)
+{
+ value meths = Field (obj, 0);
+ int li = 3, hi = Field(meths,0), mi;
+ while (li < hi) {
+ mi = ((li+hi) >> 1) | 1;
+ if (tag < Field(meths,mi)) hi = mi-2;
+ else li = mi;
+ }
+ /* return 0 if tag is not there */
+ return (tag == Field(meths,li) ? Field (meths, li-1) : 0);
+}
+
+/* these two functions might be useful to an hypothetical JIT */
+
+#ifdef CAML_JIT
+#ifdef NATIVE_CODE
+#define MARK 1
+#else
+#define MARK 0
+#endif
+value caml_cache_public_method (value meths, value tag, value *cache)
+{
+ int li = 3, hi = Field(meths,0), mi;
+ while (li < hi) {
+ mi = ((li+hi) >> 1) | 1;
+ if (tag < Field(meths,mi)) hi = mi-2;
+ else li = mi;
+ }
+ *cache = (li-3)*sizeof(value) + MARK;
+ return Field (meths, li-1);
+}
+
+value caml_cache_public_method2 (value *meths, value tag, value *cache)
+{
+ value ofs = *cache & meths[1];
+ if (*(value*)(((char*)(meths+3)) + ofs - MARK) == tag)
+ return *(value*)(((char*)(meths+2)) + ofs - MARK);
+ {
+ int li = 3, hi = meths[0], mi;
+ while (li < hi) {
+ mi = ((li+hi) >> 1) | 1;
+ if (tag < meths[mi]) hi = mi-2;
+ else li = mi;
+ }
+ *cache = (li-3)*sizeof(value) + MARK;
+ return meths[li-1];
+ }
+}
+#endif /*CAML_JIT*/
+
+static value oo_last_id = Val_int(0);
+
+CAMLprim value caml_set_oo_id (value obj) {
+ Field(obj, 1) = oo_last_id;
+ oo_last_id += 2;
+ return obj;
+}
+
+CAMLprim value caml_int_as_pointer (value n) {
+ return n - 1;
+}
diff --git a/byterun/parsing.c b/byterun/parsing.c
new file mode 100644
index 0000000000..bd51a41eeb
--- /dev/null
+++ b/byterun/parsing.c
@@ -0,0 +1,300 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The PDA automaton for parsers generated by camlyacc */
+
+#include <stdio.h>
+#include <string.h>
+#include "caml/config.h"
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+#include "caml/alloc.h"
+
+#define ERRCODE 256
+
+struct parser_tables { /* Mirrors parse_tables in ../stdlib/parsing.mli */
+ value actions;
+ value transl_const;
+ value transl_block;
+ char * lhs;
+ char * len;
+ char * defred;
+ char * dgoto;
+ char * sindex;
+ char * rindex;
+ char * gindex;
+ value tablesize;
+ char * table;
+ char * check;
+ value error_function;
+ char * names_const;
+ char * names_block;
+};
+
+struct parser_env { /* Mirrors parser_env in ../stdlib/parsing.ml */
+ value s_stack;
+ value v_stack;
+ value symb_start_stack;
+ value symb_end_stack;
+ value stacksize;
+ value stackbase;
+ value curr_char;
+ value lval;
+ value symb_start;
+ value symb_end;
+ value asp;
+ value rule_len;
+ value rule_number;
+ value sp;
+ value state;
+ value errflag;
+};
+
+#if defined(ARCH_BIG_ENDIAN) || SIZEOF_SHORT != 2
+#define Short(tbl,n) \
+ (*((unsigned char *)((tbl) + (n) * 2)) + \
+ (*((signed char *)((tbl) + (n) * 2 + 1)) << 8))
+#else
+#define Short(tbl,n) (((short *)(tbl))[n])
+#endif
+
+int caml_parser_trace = 0;
+
+/* Input codes */
+/* Mirrors parser_input in ../stdlib/parsing.ml */
+#define START 0
+#define TOKEN_READ 1
+#define STACKS_GROWN_1 2
+#define STACKS_GROWN_2 3
+#define SEMANTIC_ACTION_COMPUTED 4
+#define ERROR_DETECTED 5
+
+/* Output codes */
+/* Mirrors parser_output in ../stdlib/parsing.ml */
+#define READ_TOKEN Val_int(0)
+#define RAISE_PARSE_ERROR Val_int(1)
+#define GROW_STACKS_1 Val_int(2)
+#define GROW_STACKS_2 Val_int(3)
+#define COMPUTE_SEMANTIC_ACTION Val_int(4)
+#define CALL_ERROR_FUNCTION Val_int(5)
+
+/* To preserve local variables when communicating with the ML code */
+
+#define SAVE \
+ env->sp = Val_int(sp), \
+ env->state = Val_int(state), \
+ env->errflag = Val_int(errflag)
+
+#define RESTORE \
+ sp = Int_val(env->sp), \
+ state = Int_val(env->state), \
+ errflag = Int_val(env->errflag)
+
+/* Auxiliary for printing token just read */
+
+static char * token_name(char * names, int number)
+{
+ for (/*nothing*/; number > 0; number--) {
+ if (names[0] == 0) return "<unknown token>";
+ names += strlen(names) + 1;
+ }
+ return names;
+}
+
+static void print_token(struct parser_tables *tables, int state, value tok)
+{
+ value v;
+
+ if (Is_long(tok)) {
+ fprintf(stderr, "State %d: read token %s\n",
+ state, token_name(tables->names_const, Int_val(tok)));
+ } else {
+ fprintf(stderr, "State %d: read token %s(",
+ state, token_name(tables->names_block, Tag_val(tok)));
+ v = Field(tok, 0);
+ if (Is_long(v))
+ fprintf(stderr, "%" ARCH_INTNAT_PRINTF_FORMAT "d", Long_val(v));
+ else if (Tag_val(v) == String_tag)
+ fprintf(stderr, "%s", String_val(v));
+ else if (Tag_val(v) == Double_tag)
+ fprintf(stderr, "%g", Double_val(v));
+ else
+ fprintf(stderr, "_");
+ fprintf(stderr, ")\n");
+ }
+}
+
+/* The pushdown automata */
+
+CAMLprim value caml_parse_engine(struct parser_tables *tables,
+ struct parser_env *env, value cmd, value arg)
+{
+ int state;
+ mlsize_t sp, asp;
+ int errflag;
+ int n, n1, n2, m, state1;
+
+ switch(Int_val(cmd)) {
+
+ case START:
+ state = 0;
+ sp = Int_val(env->sp);
+ errflag = 0;
+
+ loop:
+ n = Short(tables->defred, state);
+ if (n != 0) goto reduce;
+ if (Int_val(env->curr_char) >= 0) goto testshift;
+ SAVE;
+ return READ_TOKEN;
+ /* The ML code calls the lexer and updates */
+ /* symb_start and symb_end */
+ case TOKEN_READ:
+ RESTORE;
+ if (Is_block(arg)) {
+ env->curr_char = Field(tables->transl_block, Tag_val(arg));
+ caml_modify(&env->lval, Field(arg, 0));
+ } else {
+ env->curr_char = Field(tables->transl_const, Int_val(arg));
+ caml_modify(&env->lval, Val_long(0));
+ }
+ if (caml_parser_trace) print_token(tables, state, arg);
+
+ testshift:
+ n1 = Short(tables->sindex, state);
+ n2 = n1 + Int_val(env->curr_char);
+ if (n1 != 0 && n2 >= 0 && n2 <= Int_val(tables->tablesize) &&
+ Short(tables->check, n2) == Int_val(env->curr_char)) goto shift;
+ n1 = Short(tables->rindex, state);
+ n2 = n1 + Int_val(env->curr_char);
+ if (n1 != 0 && n2 >= 0 && n2 <= Int_val(tables->tablesize) &&
+ Short(tables->check, n2) == Int_val(env->curr_char)) {
+ n = Short(tables->table, n2);
+ goto reduce;
+ }
+ if (errflag > 0) goto recover;
+ SAVE;
+ return CALL_ERROR_FUNCTION;
+ /* The ML code calls the error function */
+ case ERROR_DETECTED:
+ RESTORE;
+ recover:
+ if (errflag < 3) {
+ errflag = 3;
+ while (1) {
+ state1 = Int_val(Field(env->s_stack, sp));
+ n1 = Short(tables->sindex, state1);
+ n2 = n1 + ERRCODE;
+ if (n1 != 0 && n2 >= 0 && n2 <= Int_val(tables->tablesize) &&
+ Short(tables->check, n2) == ERRCODE) {
+ if (caml_parser_trace)
+ fprintf(stderr, "Recovering in state %d\n", state1);
+ goto shift_recover;
+ } else {
+ if (caml_parser_trace){
+ fprintf(stderr, "Discarding state %d\n", state1);
+ }
+ if (sp <= Int_val(env->stackbase)) {
+ if (caml_parser_trace){
+ fprintf(stderr, "No more states to discard\n");
+ }
+ return RAISE_PARSE_ERROR; /* The ML code raises Parse_error */
+ }
+ sp--;
+ }
+ }
+ } else {
+ if (Int_val(env->curr_char) == 0)
+ return RAISE_PARSE_ERROR; /* The ML code raises Parse_error */
+ if (caml_parser_trace) fprintf(stderr, "Discarding last token read\n");
+ env->curr_char = Val_int(-1);
+ goto loop;
+ }
+
+ shift:
+ env->curr_char = Val_int(-1);
+ if (errflag > 0) errflag--;
+ shift_recover:
+ if (caml_parser_trace)
+ fprintf(stderr, "State %d: shift to state %d\n",
+ state, Short(tables->table, n2));
+ state = Short(tables->table, n2);
+ sp++;
+ if (sp < Long_val(env->stacksize)) goto push;
+ SAVE;
+ return GROW_STACKS_1;
+ /* The ML code resizes the stacks */
+ case STACKS_GROWN_1:
+ RESTORE;
+ push:
+ Field(env->s_stack, sp) = Val_int(state);
+ caml_modify(&Field(env->v_stack, sp), env->lval);
+ Store_field (env->symb_start_stack, sp, env->symb_start);
+ Store_field (env->symb_end_stack, sp, env->symb_end);
+ goto loop;
+
+ reduce:
+ if (caml_parser_trace)
+ fprintf(stderr, "State %d: reduce by rule %d\n", state, n);
+ m = Short(tables->len, n);
+ env->asp = Val_int(sp);
+ env->rule_number = Val_int(n);
+ env->rule_len = Val_int(m);
+ sp = sp - m + 1;
+ m = Short(tables->lhs, n);
+ state1 = Int_val(Field(env->s_stack, sp - 1));
+ n1 = Short(tables->gindex, m);
+ n2 = n1 + state1;
+ if (n1 != 0 && n2 >= 0 && n2 <= Int_val(tables->tablesize) &&
+ Short(tables->check, n2) == state1) {
+ state = Short(tables->table, n2);
+ } else {
+ state = Short(tables->dgoto, m);
+ }
+ if (sp < Long_val(env->stacksize)) goto semantic_action;
+ SAVE;
+ return GROW_STACKS_2;
+ /* The ML code resizes the stacks */
+ case STACKS_GROWN_2:
+ RESTORE;
+ semantic_action:
+ SAVE;
+ return COMPUTE_SEMANTIC_ACTION;
+ /* The ML code calls the semantic action */
+ case SEMANTIC_ACTION_COMPUTED:
+ RESTORE;
+ Field(env->s_stack, sp) = Val_int(state);
+ caml_modify(&Field(env->v_stack, sp), arg);
+ asp = Int_val(env->asp);
+ Store_field (env->symb_end_stack, sp, Field(env->symb_end_stack, asp));
+ if (sp > asp) {
+ /* This is an epsilon production. Take symb_start equal to symb_end. */
+ Store_field (env->symb_start_stack, sp, Field(env->symb_end_stack, asp));
+ }
+ goto loop;
+
+ default: /* Should not happen */
+ Assert(0);
+ return RAISE_PARSE_ERROR; /* Keeps gcc -Wall happy */
+ }
+
+}
+
+/* Control printing of debugging info */
+
+CAMLprim value caml_set_parser_trace(value flag)
+{
+ value oldflag = Val_bool(caml_parser_trace);
+ caml_parser_trace = Bool_val(flag);
+ return oldflag;
+}
diff --git a/byterun/printexc.c b/byterun/printexc.c
new file mode 100644
index 0000000000..7647b3a1fd
--- /dev/null
+++ b/byterun/printexc.c
@@ -0,0 +1,143 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Print an uncaught exception and abort */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "caml/backtrace.h"
+#include "caml/callback.h"
+#include "caml/debugger.h"
+#include "caml/fail.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/printexc.h"
+
+struct stringbuf {
+ char * ptr;
+ char * end;
+ char data[256];
+};
+
+static void add_char(struct stringbuf *buf, char c)
+{
+ if (buf->ptr < buf->end) *(buf->ptr++) = c;
+}
+
+static void add_string(struct stringbuf *buf, char *s)
+{
+ int len = strlen(s);
+ if (buf->ptr + len > buf->end) len = buf->end - buf->ptr;
+ if (len > 0) memmove(buf->ptr, s, len);
+ buf->ptr += len;
+}
+
+CAMLexport char * caml_format_exception(value exn)
+{
+ mlsize_t start, i;
+ value bucket, v;
+ struct stringbuf buf;
+ char intbuf[64];
+ char * res;
+
+ buf.ptr = buf.data;
+ buf.end = buf.data + sizeof(buf.data) - 1;
+ if (Tag_val(exn) == 0) {
+ add_string(&buf, String_val(Field(Field(exn, 0), 0)));
+ /* Check for exceptions in the style of Match_failure and Assert_failure */
+ if (Wosize_val(exn) == 2 &&
+ Is_block(Field(exn, 1)) &&
+ Tag_val(Field(exn, 1)) == 0 &&
+ caml_is_special_exception(Field(exn, 0))) {
+ bucket = Field(exn, 1);
+ start = 0;
+ } else {
+ bucket = exn;
+ start = 1;
+ }
+ add_char(&buf, '(');
+ for (i = start; i < Wosize_val(bucket); i++) {
+ if (i > start) add_string(&buf, ", ");
+ v = Field(bucket, i);
+ if (Is_long(v)) {
+ snprintf(intbuf, sizeof(intbuf),
+ "%" ARCH_INTNAT_PRINTF_FORMAT "d", Long_val(v));
+ add_string(&buf, intbuf);
+ } else if (Tag_val(v) == String_tag) {
+ add_char(&buf, '"');
+ add_string(&buf, String_val(v));
+ add_char(&buf, '"');
+ } else {
+ add_char(&buf, '_');
+ }
+ }
+ add_char(&buf, ')');
+ } else
+ add_string(&buf, String_val(Field(exn, 0)));
+
+ *buf.ptr = 0; /* Terminate string */
+ i = buf.ptr - buf.data + 1;
+ res = malloc(i);
+ if (res == NULL) return NULL;
+ memmove(res, buf.data, i);
+ return res;
+}
+
+
+#ifdef NATIVE_CODE
+# define DEBUGGER_IN_USE 0
+#else
+# define DEBUGGER_IN_USE caml_debugger_in_use
+#endif
+
+/* Default C implementation in case the OCaml one is not registered. */
+static void default_fatal_uncaught_exception(value exn)
+{
+ char * msg;
+ value * at_exit;
+ int saved_backtrace_active, saved_backtrace_pos;
+
+ /* Build a string representation of the exception */
+ msg = caml_format_exception(exn);
+ /* Perform "at_exit" processing, ignoring all exceptions that may
+ be triggered by this */
+ saved_backtrace_active = caml_backtrace_active;
+ saved_backtrace_pos = caml_backtrace_pos;
+ caml_backtrace_active = 0;
+ at_exit = caml_named_value("Pervasives.do_at_exit");
+ if (at_exit != NULL) caml_callback_exn(*at_exit, Val_unit);
+ caml_backtrace_active = saved_backtrace_active;
+ caml_backtrace_pos = saved_backtrace_pos;
+ /* Display the uncaught exception */
+ fprintf(stderr, "Fatal error: exception %s\n", msg);
+ free(msg);
+ /* Display the backtrace if available */
+ if (caml_backtrace_active && !DEBUGGER_IN_USE)
+ caml_print_exception_backtrace();
+}
+
+void caml_fatal_uncaught_exception(value exn)
+{
+ value *handle_uncaught_exception;
+
+ handle_uncaught_exception =
+ caml_named_value("Printexc.handle_uncaught_exception");
+ if (handle_uncaught_exception != NULL)
+ /* [Printexc.handle_uncaught_exception] does not raise exception. */
+ caml_callback2(*handle_uncaught_exception, exn, Val_bool(DEBUGGER_IN_USE));
+ else
+ default_fatal_uncaught_exception(exn);
+ /* Terminate the process */
+ exit(2);
+}
diff --git a/byterun/roots.c b/byterun/roots.c
new file mode 100644
index 0000000000..f812cd75af
--- /dev/null
+++ b/byterun/roots.c
@@ -0,0 +1,101 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* To walk the memory roots for garbage collection */
+
+#include "caml/finalise.h"
+#include "caml/globroots.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/minor_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/roots.h"
+#include "caml/stacks.h"
+
+CAMLexport struct caml__roots_block *caml_local_roots = NULL;
+
+CAMLexport void (*caml_scan_roots_hook) (scanning_action f) = NULL;
+
+/* FIXME should rename to [caml_oldify_young_roots] and synchronise with
+ asmrun/roots.c */
+/* Call [caml_oldify_one] on (at least) all the roots that point to the minor
+ heap. */
+void caml_oldify_local_roots (void)
+{
+ register value * sp;
+ struct caml__roots_block *lr;
+ intnat i, j;
+
+ /* The stack */
+ for (sp = caml_extern_sp; sp < caml_stack_high; sp++) {
+ caml_oldify_one (*sp, sp);
+ }
+ /* Local C roots */ /* FIXME do the old-frame trick ? */
+ for (lr = caml_local_roots; lr != NULL; lr = lr->next) {
+ for (i = 0; i < lr->ntables; i++){
+ for (j = 0; j < lr->nitems; j++){
+ sp = &(lr->tables[i][j]);
+ caml_oldify_one (*sp, sp);
+ }
+ }
+ }
+ /* Global C roots */
+ caml_scan_global_young_roots(&caml_oldify_one);
+ /* Finalised values */
+ caml_final_do_young_roots (&caml_oldify_one);
+ /* Hook */
+ if (caml_scan_roots_hook != NULL) (*caml_scan_roots_hook)(&caml_oldify_one);
+}
+
+/* Call [caml_darken] on all roots */
+
+void caml_darken_all_roots (void)
+{
+ caml_do_roots (caml_darken);
+}
+
+void caml_do_roots (scanning_action f)
+{
+ /* Global variables */
+ f(caml_global_data, &caml_global_data);
+ /* The stack and the local C roots */
+ caml_do_local_roots(f, caml_extern_sp, caml_stack_high, caml_local_roots);
+ /* Global C roots */
+ caml_scan_global_roots(f);
+ /* Finalised values */
+ caml_final_do_strong_roots (f);
+ /* Hook */
+ if (caml_scan_roots_hook != NULL) (*caml_scan_roots_hook)(f);
+}
+
+CAMLexport void caml_do_local_roots (scanning_action f, value *stack_low,
+ value *stack_high,
+ struct caml__roots_block *local_roots)
+{
+ register value * sp;
+ struct caml__roots_block *lr;
+ int i, j;
+
+ for (sp = stack_low; sp < stack_high; sp++) {
+ f (*sp, sp);
+ }
+ for (lr = local_roots; lr != NULL; lr = lr->next) {
+ for (i = 0; i < lr->ntables; i++){
+ for (j = 0; j < lr->nitems; j++){
+ sp = &(lr->tables[i][j]);
+ f (*sp, sp);
+ }
+ }
+ }
+}
diff --git a/byterun/signals.c b/byterun/signals.c
new file mode 100644
index 0000000000..e6ec7a518c
--- /dev/null
+++ b/byterun/signals.c
@@ -0,0 +1,332 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Signal handling, code common to the bytecode and native systems */
+
+#include <signal.h>
+#include <errno.h>
+#include "caml/alloc.h"
+#include "caml/callback.h"
+#include "caml/config.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/roots.h"
+#include "caml/signals.h"
+#include "caml/signals_machdep.h"
+#include "caml/sys.h"
+
+#ifndef NSIG
+#define NSIG 64
+#endif
+
+/* The set of pending signals (received but not yet processed) */
+
+CAMLexport intnat volatile caml_signals_are_pending = 0;
+CAMLexport intnat volatile caml_pending_signals[NSIG];
+
+/* Execute all pending signals */
+
+void caml_process_pending_signals(void)
+{
+ int i;
+
+ if (caml_signals_are_pending) {
+ caml_signals_are_pending = 0;
+ for (i = 0; i < NSIG; i++) {
+ if (caml_pending_signals[i]) {
+ caml_pending_signals[i] = 0;
+ caml_execute_signal(i, 0);
+ }
+ }
+ }
+}
+
+/* Record the delivery of a signal, and arrange for it to be processed
+ as soon as possible:
+ - in bytecode: via caml_something_to_do, processed in caml_process_event
+ - in native-code: by playing with the allocation limit, processed
+ in caml_garbage_collection
+*/
+
+void caml_record_signal(int signal_number)
+{
+ caml_pending_signals[signal_number] = 1;
+ caml_signals_are_pending = 1;
+#ifndef NATIVE_CODE
+ caml_something_to_do = 1;
+#else
+ caml_young_limit = caml_young_end;
+#endif
+}
+
+/* Management of blocking sections. */
+
+static intnat volatile caml_async_signal_mode = 0;
+
+static void caml_enter_blocking_section_default(void)
+{
+ Assert (caml_async_signal_mode == 0);
+ caml_async_signal_mode = 1;
+}
+
+static void caml_leave_blocking_section_default(void)
+{
+ Assert (caml_async_signal_mode == 1);
+ caml_async_signal_mode = 0;
+}
+
+static int caml_try_leave_blocking_section_default(void)
+{
+ intnat res;
+ Read_and_clear(res, caml_async_signal_mode);
+ return res;
+}
+
+CAMLexport void (*caml_enter_blocking_section_hook)(void) =
+ caml_enter_blocking_section_default;
+CAMLexport void (*caml_leave_blocking_section_hook)(void) =
+ caml_leave_blocking_section_default;
+CAMLexport int (*caml_try_leave_blocking_section_hook)(void) =
+ caml_try_leave_blocking_section_default;
+
+CAMLexport void caml_enter_blocking_section(void)
+{
+ while (1){
+ /* Process all pending signals now */
+ caml_process_pending_signals();
+ caml_enter_blocking_section_hook ();
+ /* Check again for pending signals.
+ If none, done; otherwise, try again */
+ if (! caml_signals_are_pending) break;
+ caml_leave_blocking_section_hook ();
+ }
+}
+
+CAMLexport void caml_leave_blocking_section(void)
+{
+ int saved_errno;
+ /* Save the value of errno (PR#5982). */
+ saved_errno = errno;
+ caml_leave_blocking_section_hook ();
+ caml_process_pending_signals();
+ errno = saved_errno;
+}
+
+/* Execute a signal handler immediately */
+
+static value caml_signal_handlers = 0;
+
+void caml_execute_signal(int signal_number, int in_signal_handler)
+{
+ value res;
+#ifdef POSIX_SIGNALS
+ sigset_t sigs;
+ /* Block the signal before executing the handler, and record in sigs
+ the original signal mask */
+ sigemptyset(&sigs);
+ sigaddset(&sigs, signal_number);
+ sigprocmask(SIG_BLOCK, &sigs, &sigs);
+#endif
+ res = caml_callback_exn(
+ Field(caml_signal_handlers, signal_number),
+ Val_int(caml_rev_convert_signal_number(signal_number)));
+#ifdef POSIX_SIGNALS
+ if (! in_signal_handler) {
+ /* Restore the original signal mask */
+ sigprocmask(SIG_SETMASK, &sigs, NULL);
+ } else if (Is_exception_result(res)) {
+ /* Restore the original signal mask and unblock the signal itself */
+ sigdelset(&sigs, signal_number);
+ sigprocmask(SIG_SETMASK, &sigs, NULL);
+ }
+#endif
+ if (Is_exception_result(res)) caml_raise(Extract_exception(res));
+}
+
+/* Arrange for a garbage collection to be performed as soon as possible */
+
+int volatile caml_force_major_slice = 0;
+
+void caml_urge_major_slice (void)
+{
+ caml_force_major_slice = 1;
+#ifndef NATIVE_CODE
+ caml_something_to_do = 1;
+#else
+ caml_young_limit = caml_young_end;
+ /* This is only moderately effective on ports that cache [caml_young_limit]
+ in a register, since [caml_modify] is called directly, not through
+ [caml_c_call], so it may take a while before the register is reloaded
+ from [caml_young_limit]. */
+#endif
+}
+
+/* OS-independent numbering of signals */
+
+#ifndef SIGABRT
+#define SIGABRT -1
+#endif
+#ifndef SIGALRM
+#define SIGALRM -1
+#endif
+#ifndef SIGFPE
+#define SIGFPE -1
+#endif
+#ifndef SIGHUP
+#define SIGHUP -1
+#endif
+#ifndef SIGILL
+#define SIGILL -1
+#endif
+#ifndef SIGINT
+#define SIGINT -1
+#endif
+#ifndef SIGKILL
+#define SIGKILL -1
+#endif
+#ifndef SIGPIPE
+#define SIGPIPE -1
+#endif
+#ifndef SIGQUIT
+#define SIGQUIT -1
+#endif
+#ifndef SIGSEGV
+#define SIGSEGV -1
+#endif
+#ifndef SIGTERM
+#define SIGTERM -1
+#endif
+#ifndef SIGUSR1
+#define SIGUSR1 -1
+#endif
+#ifndef SIGUSR2
+#define SIGUSR2 -1
+#endif
+#ifndef SIGCHLD
+#define SIGCHLD -1
+#endif
+#ifndef SIGCONT
+#define SIGCONT -1
+#endif
+#ifndef SIGSTOP
+#define SIGSTOP -1
+#endif
+#ifndef SIGTSTP
+#define SIGTSTP -1
+#endif
+#ifndef SIGTTIN
+#define SIGTTIN -1
+#endif
+#ifndef SIGTTOU
+#define SIGTTOU -1
+#endif
+#ifndef SIGVTALRM
+#define SIGVTALRM -1
+#endif
+#ifndef SIGPROF
+#define SIGPROF -1
+#endif
+#ifndef SIGBUS
+#define SIGBUS -1
+#endif
+#ifndef SIGPOLL
+#define SIGPOLL -1
+#endif
+#ifndef SIGSYS
+#define SIGSYS -1
+#endif
+#ifndef SIGTRAP
+#define SIGTRAP -1
+#endif
+#ifndef SIGURG
+#define SIGURG -1
+#endif
+#ifndef SIGXCPU
+#define SIGXCPU -1
+#endif
+#ifndef SIGXFSZ
+#define SIGXFSZ -1
+#endif
+
+static int posix_signals[] = {
+ SIGABRT, SIGALRM, SIGFPE, SIGHUP, SIGILL, SIGINT, SIGKILL, SIGPIPE,
+ SIGQUIT, SIGSEGV, SIGTERM, SIGUSR1, SIGUSR2, SIGCHLD, SIGCONT,
+ SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU, SIGVTALRM, SIGPROF, SIGBUS,
+ SIGPOLL, SIGSYS, SIGTRAP, SIGURG, SIGXCPU, SIGXFSZ
+};
+
+CAMLexport int caml_convert_signal_number(int signo)
+{
+ if (signo < 0 && signo >= -(sizeof(posix_signals) / sizeof(int)))
+ return posix_signals[-signo-1];
+ else
+ return signo;
+}
+
+CAMLexport int caml_rev_convert_signal_number(int signo)
+{
+ int i;
+ for (i = 0; i < sizeof(posix_signals) / sizeof(int); i++)
+ if (signo == posix_signals[i]) return -i - 1;
+ return signo;
+}
+
+/* Installation of a signal handler (as per [Sys.signal]) */
+
+CAMLprim value caml_install_signal_handler(value signal_number, value action)
+{
+ CAMLparam2 (signal_number, action);
+ CAMLlocal1 (res);
+ int sig, act, oldact;
+
+ sig = caml_convert_signal_number(Int_val(signal_number));
+ if (sig < 0 || sig >= NSIG)
+ caml_invalid_argument("Sys.signal: unavailable signal");
+ switch(action) {
+ case Val_int(0): /* Signal_default */
+ act = 0;
+ break;
+ case Val_int(1): /* Signal_ignore */
+ act = 1;
+ break;
+ default: /* Signal_handle */
+ act = 2;
+ break;
+ }
+ oldact = caml_set_signal_action(sig, act);
+ switch (oldact) {
+ case 0: /* was Signal_default */
+ res = Val_int(0);
+ break;
+ case 1: /* was Signal_ignore */
+ res = Val_int(1);
+ break;
+ case 2: /* was Signal_handle */
+ res = caml_alloc_small (1, 0);
+ Field(res, 0) = Field(caml_signal_handlers, sig);
+ break;
+ default: /* error in caml_set_signal_action */
+ caml_sys_error(NO_ARG);
+ }
+ if (Is_block(action)) {
+ if (caml_signal_handlers == 0) {
+ caml_signal_handlers = caml_alloc(NSIG, 0);
+ caml_register_global_root(&caml_signal_handlers);
+ }
+ caml_modify(&Field(caml_signal_handlers, sig), Field(action, 0));
+ }
+ caml_process_pending_signals();
+ CAMLreturn (res);
+}
diff --git a/byterun/signals_byt.c b/byterun/signals_byt.c
new file mode 100644
index 0000000000..f227ffa3ae
--- /dev/null
+++ b/byterun/signals_byt.c
@@ -0,0 +1,97 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 2007 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Signal handling, code specific to the bytecode interpreter */
+
+#include <signal.h>
+#include <errno.h>
+#include "caml/config.h"
+#include "caml/memory.h"
+#include "caml/osdeps.h"
+#include "caml/signals.h"
+#include "caml/signals_machdep.h"
+
+#ifndef NSIG
+#define NSIG 64
+#endif
+
+#ifdef _WIN32
+typedef void (*sighandler)(int sig);
+extern sighandler caml_win32_signal(int sig, sighandler action);
+#define signal(sig,act) caml_win32_signal(sig,act)
+#endif
+
+CAMLexport int volatile caml_something_to_do = 0;
+CAMLexport void (* volatile caml_async_action_hook)(void) = NULL;
+
+void caml_process_event(void)
+{
+ void (*async_action)(void);
+
+ caml_check_urgent_gc (Val_unit);
+ caml_process_pending_signals();
+ async_action = caml_async_action_hook;
+ if (async_action != NULL) {
+ caml_async_action_hook = NULL;
+ (*async_action)();
+ }
+}
+
+static void handle_signal(int signal_number)
+{
+ int saved_errno;
+ /* Save the value of errno (PR#5982). */
+ saved_errno = errno;
+#if !defined(POSIX_SIGNALS) && !defined(BSD_SIGNALS)
+ signal(signal_number, handle_signal);
+#endif
+ if (signal_number < 0 || signal_number >= NSIG) return;
+ if (caml_try_leave_blocking_section_hook()) {
+ caml_execute_signal(signal_number, 1);
+ caml_enter_blocking_section_hook();
+ }else{
+ caml_record_signal(signal_number);
+ }
+ errno = saved_errno;
+}
+
+int caml_set_signal_action(int signo, int action)
+{
+ void (*act)(int signo), (*oldact)(int signo);
+#ifdef POSIX_SIGNALS
+ struct sigaction sigact, oldsigact;
+#endif
+
+ switch (action) {
+ case 0: act = SIG_DFL; break;
+ case 1: act = SIG_IGN; break;
+ default: act = handle_signal; break;
+ }
+
+#ifdef POSIX_SIGNALS
+ sigact.sa_handler = act;
+ sigemptyset(&sigact.sa_mask);
+ sigact.sa_flags = 0;
+ if (sigaction(signo, &sigact, &oldsigact) == -1) return -1;
+ oldact = oldsigact.sa_handler;
+#else
+ oldact = signal(signo, act);
+ if (oldact == SIG_ERR) return -1;
+#endif
+ if (oldact == handle_signal)
+ return 2;
+ else if (oldact == SIG_IGN)
+ return 1;
+ else
+ return 0;
+}
diff --git a/byterun/stacks.c b/byterun/stacks.c
new file mode 100644
index 0000000000..94bff0b9f6
--- /dev/null
+++ b/byterun/stacks.c
@@ -0,0 +1,113 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* To initialize and resize the stacks */
+
+#include <string.h>
+#include "caml/config.h"
+#include "caml/fail.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/stacks.h"
+
+CAMLexport value * caml_stack_low;
+CAMLexport value * caml_stack_high;
+CAMLexport value * caml_stack_threshold;
+CAMLexport value * caml_extern_sp;
+CAMLexport value * caml_trapsp;
+CAMLexport value * caml_trap_barrier;
+value caml_global_data = 0;
+
+uintnat caml_max_stack_size; /* also used in gc_ctrl.c */
+
+void caml_init_stack (uintnat initial_max_size)
+{
+ caml_stack_low = (value *) caml_stat_alloc(Stack_size);
+ caml_stack_high = caml_stack_low + Stack_size / sizeof (value);
+ caml_stack_threshold = caml_stack_low + Stack_threshold / sizeof (value);
+ caml_extern_sp = caml_stack_high;
+ caml_trapsp = caml_stack_high;
+ caml_trap_barrier = caml_stack_high + 1;
+ caml_max_stack_size = initial_max_size;
+ caml_gc_message (0x08, "Initial stack limit: %luk bytes\n",
+ caml_max_stack_size / 1024 * sizeof (value));
+}
+
+void caml_realloc_stack(asize_t required_space)
+{
+ asize_t size;
+ value * new_low, * new_high, * new_sp;
+ value * p;
+
+ Assert(caml_extern_sp >= caml_stack_low);
+ size = caml_stack_high - caml_stack_low;
+ do {
+ if (size >= caml_max_stack_size) caml_raise_stack_overflow();
+ size *= 2;
+ } while (size < caml_stack_high - caml_extern_sp + required_space);
+ caml_gc_message (0x08, "Growing stack to %"
+ ARCH_INTNAT_PRINTF_FORMAT "uk bytes\n",
+ (uintnat) size * sizeof(value) / 1024);
+ new_low = (value *) caml_stat_alloc(size * sizeof(value));
+ new_high = new_low + size;
+
+#define shift(ptr) \
+ ((char *) new_high - ((char *) caml_stack_high - (char *) (ptr)))
+
+ new_sp = (value *) shift(caml_extern_sp);
+ memmove((char *) new_sp,
+ (char *) caml_extern_sp,
+ (caml_stack_high - caml_extern_sp) * sizeof(value));
+ caml_stat_free(caml_stack_low);
+ caml_trapsp = (value *) shift(caml_trapsp);
+ caml_trap_barrier = (value *) shift(caml_trap_barrier);
+ for (p = caml_trapsp; p < new_high; p = Trap_link(p))
+ Trap_link(p) = (value *) shift(Trap_link(p));
+ caml_stack_low = new_low;
+ caml_stack_high = new_high;
+ caml_stack_threshold = caml_stack_low + Stack_threshold / sizeof (value);
+ caml_extern_sp = new_sp;
+
+#undef shift
+}
+
+CAMLprim value caml_ensure_stack_capacity(value required_space)
+{
+ asize_t req = Long_val(required_space);
+ if (caml_extern_sp - req < caml_stack_low) caml_realloc_stack(req);
+ return Val_unit;
+}
+
+void caml_change_max_stack_size (uintnat new_max_size)
+{
+ asize_t size = caml_stack_high - caml_extern_sp
+ + Stack_threshold / sizeof (value);
+
+ if (new_max_size < size) new_max_size = size;
+ if (new_max_size != caml_max_stack_size){
+ caml_gc_message (0x08, "Changing stack limit to %luk bytes\n",
+ new_max_size * sizeof (value) / 1024);
+ }
+ caml_max_stack_size = new_max_size;
+}
+
+CAMLexport uintnat (*caml_stack_usage_hook)(void) = NULL;
+
+uintnat caml_stack_usage(void)
+{
+ uintnat sz;
+ sz = caml_stack_high - caml_extern_sp;
+ if (caml_stack_usage_hook != NULL)
+ sz += (*caml_stack_usage_hook)();
+ return sz;
+}
diff --git a/byterun/startup.c b/byterun/startup.c
new file mode 100644
index 0000000000..faa0e4a1f7
--- /dev/null
+++ b/byterun/startup.c
@@ -0,0 +1,459 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Start-up code */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include "caml/config.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#ifdef _WIN32
+#include <process.h>
+#endif
+#include "caml/alloc.h"
+#include "caml/backtrace.h"
+#include "caml/callback.h"
+#include "caml/custom.h"
+#include "caml/debugger.h"
+#include "caml/dynlink.h"
+#include "caml/exec.h"
+#include "caml/fail.h"
+#include "caml/fix_code.h"
+#include "caml/freelist.h"
+#include "caml/gc_ctrl.h"
+#include "caml/instrtrace.h"
+#include "caml/interp.h"
+#include "caml/intext.h"
+#include "caml/io.h"
+#include "caml/memory.h"
+#include "caml/minor_gc.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/osdeps.h"
+#include "caml/prims.h"
+#include "caml/printexc.h"
+#include "caml/reverse.h"
+#include "caml/signals.h"
+#include "caml/stacks.h"
+#include "caml/sys.h"
+#include "caml/startup.h"
+#include "caml/startup_aux.h"
+#include "caml/version.h"
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+#ifndef SEEK_END
+#define SEEK_END 2
+#endif
+
+/* Read the trailer of a bytecode file */
+
+static void fixup_endianness_trailer(uint32_t * p)
+{
+#ifndef ARCH_BIG_ENDIAN
+ Reverse_32(p, p);
+#endif
+}
+
+static int read_trailer(int fd, struct exec_trailer *trail)
+{
+ if (lseek(fd, (long) -TRAILER_SIZE, SEEK_END) == -1)
+ return BAD_BYTECODE;
+ if (read(fd, (char *) trail, TRAILER_SIZE) < TRAILER_SIZE)
+ return BAD_BYTECODE;
+ fixup_endianness_trailer(&trail->num_sections);
+ if (strncmp(trail->magic, EXEC_MAGIC, 12) == 0)
+ return 0;
+ else
+ return BAD_BYTECODE;
+}
+
+int caml_attempt_open(char **name, struct exec_trailer *trail,
+ int do_open_script)
+{
+ char * truename;
+ int fd;
+ int err;
+ char buf [2];
+
+ truename = caml_search_exe_in_path(*name);
+ *name = truename;
+ caml_gc_message(0x100, "Opening bytecode executable %s\n",
+ (uintnat) truename);
+ fd = open(truename, O_RDONLY | O_BINARY);
+ if (fd == -1) {
+ caml_gc_message(0x100, "Cannot open file\n", 0);
+ return FILE_NOT_FOUND;
+ }
+ if (!do_open_script) {
+ err = read (fd, buf, 2);
+ if (err < 2 || (buf [0] == '#' && buf [1] == '!')) {
+ close(fd);
+ caml_gc_message(0x100, "Rejected #! script\n", 0);
+ return BAD_BYTECODE;
+ }
+ }
+ err = read_trailer(fd, trail);
+ if (err != 0) {
+ close(fd);
+ caml_gc_message(0x100, "Not a bytecode executable\n", 0);
+ return err;
+ }
+ return fd;
+}
+
+/* Read the section descriptors */
+
+void caml_read_section_descriptors(int fd, struct exec_trailer *trail)
+{
+ int toc_size, i;
+
+ toc_size = trail->num_sections * 8;
+ trail->section = caml_stat_alloc(toc_size);
+ lseek(fd, - (long) (TRAILER_SIZE + toc_size), SEEK_END);
+ if (read(fd, (char *) trail->section, toc_size) != toc_size)
+ caml_fatal_error("Fatal error: cannot read section table\n");
+ /* Fixup endianness of lengths */
+ for (i = 0; i < trail->num_sections; i++)
+ fixup_endianness_trailer(&(trail->section[i].len));
+}
+
+/* Position fd at the beginning of the section having the given name.
+ Return the length of the section data in bytes, or -1 if no section
+ found with that name. */
+
+int32_t caml_seek_optional_section(int fd, struct exec_trailer *trail,
+ char *name)
+{
+ long ofs;
+ int i;
+
+ ofs = TRAILER_SIZE + trail->num_sections * 8;
+ for (i = trail->num_sections - 1; i >= 0; i--) {
+ ofs += trail->section[i].len;
+ if (strncmp(trail->section[i].name, name, 4) == 0) {
+ lseek(fd, -ofs, SEEK_END);
+ return trail->section[i].len;
+ }
+ }
+ return -1;
+}
+
+/* Position fd at the beginning of the section having the given name.
+ Return the length of the section data in bytes. */
+
+int32_t caml_seek_section(int fd, struct exec_trailer *trail, char *name)
+{
+ int32_t len = caml_seek_optional_section(fd, trail, name);
+ if (len == -1)
+ caml_fatal_error_arg("Fatal_error: section `%s' is missing\n", name);
+ return len;
+}
+
+/* Read and return the contents of the section having the given name.
+ Add a terminating 0. Return NULL if no such section. */
+
+static char * read_section(int fd, struct exec_trailer *trail, char *name)
+{
+ int32_t len;
+ char * data;
+
+ len = caml_seek_optional_section(fd, trail, name);
+ if (len == -1) return NULL;
+ data = caml_stat_alloc(len + 1);
+ if (read(fd, data, len) != len)
+ caml_fatal_error_arg("Fatal error: error reading section %s\n", name);
+ data[len] = 0;
+ return data;
+}
+
+/* Invocation of ocamlrun: 4 cases.
+
+ 1. runtime + bytecode
+ user types: ocamlrun [options] bytecode args...
+ arguments: ocamlrun [options] bytecode args...
+
+ 2. bytecode script
+ user types: bytecode args...
+ 2a (kernel 1) arguments: ocamlrun ./bytecode args...
+ 2b (kernel 2) arguments: bytecode bytecode args...
+
+ 3. concatenated runtime and bytecode
+ user types: composite args...
+ arguments: composite args...
+
+Algorithm:
+ 1- If argument 0 is a valid byte-code file that does not start with #!,
+ then we are in case 3 and we pass the same command line to the
+ OCaml program.
+ 2- In all other cases, we parse the command line as:
+ (whatever) [options] bytecode args...
+ and we strip "(whatever) [options]" from the command line.
+
+*/
+
+/* Parse options on the command line */
+
+static int parse_command_line(char **argv)
+{
+ int i, j;
+
+ for(i = 1; argv[i] != NULL && argv[i][0] == '-'; i++) {
+ switch(argv[i][1]) {
+ case 't':
+ ++ caml_trace_level; /* ignored unless DEBUG mode */
+ break;
+ case 'v':
+ if (!strcmp (argv[i], "-version")){
+ printf ("The OCaml runtime, version " OCAML_VERSION_STRING "\n");
+ exit (0);
+ }else if (!strcmp (argv[i], "-vnum")){
+ printf (OCAML_VERSION_STRING "\n");
+ exit (0);
+ }else{
+ caml_verb_gc = 0x001+0x004+0x008+0x010+0x020;
+ }
+ break;
+ case 'p':
+ for (j = 0; caml_names_of_builtin_cprim[j] != NULL; j++)
+ printf("%s\n", caml_names_of_builtin_cprim[j]);
+ exit(0);
+ break;
+ case 'b':
+ caml_record_backtrace(Val_true);
+ break;
+ case 'I':
+ if (argv[i + 1] != NULL) {
+ caml_ext_table_add(&caml_shared_libs_path, argv[i + 1]);
+ i++;
+ }
+ break;
+ default:
+ caml_fatal_error_arg("Unknown option %s.\n", argv[i]);
+ }
+ }
+ return i;
+}
+
+extern void caml_init_ieee_floats (void);
+
+#ifdef _WIN32
+extern void caml_signal_thread(void * lpParam);
+#endif
+
+#ifdef _MSC_VER
+
+/* PR 4887: avoid crash box of windows runtime on some system calls */
+extern void caml_install_invalid_parameter_handler();
+
+#endif
+
+/* Main entry point when loading code from a file */
+
+CAMLexport void caml_main(char **argv)
+{
+ int fd, pos;
+ struct exec_trailer trail;
+ struct channel * chan;
+ value res;
+ char * shared_lib_path, * shared_libs, * req_prims;
+ char * exe_name;
+ static char proc_self_exe[256];
+
+ /* Machine-dependent initialization of the floating-point hardware
+ so that it behaves as much as possible as specified in IEEE */
+ caml_init_ieee_floats();
+#ifdef _MSC_VER
+ caml_install_invalid_parameter_handler();
+#endif
+ caml_init_custom_operations();
+ caml_ext_table_init(&caml_shared_libs_path, 8);
+ caml_external_raise = NULL;
+ /* Determine options and position of bytecode file */
+#ifdef DEBUG
+ caml_verb_gc = 0xBF;
+#endif
+ caml_parse_ocamlrunparam();
+ pos = 0;
+
+ /* First, try argv[0] (when ocamlrun is called by a bytecode program) */
+ exe_name = argv[0];
+ fd = caml_attempt_open(&exe_name, &trail, 0);
+
+ /* Should we really do that at all? The current executable is ocamlrun
+ itself, it's never a bytecode program. */
+ if (fd < 0
+ && caml_executable_name(proc_self_exe, sizeof(proc_self_exe)) == 0) {
+ exe_name = proc_self_exe;
+ fd = caml_attempt_open(&exe_name, &trail, 0);
+ }
+
+ if (fd < 0) {
+ pos = parse_command_line(argv);
+ if (argv[pos] == 0)
+ caml_fatal_error("No bytecode file specified.\n");
+ exe_name = argv[pos];
+ fd = caml_attempt_open(&exe_name, &trail, 1);
+ switch(fd) {
+ case FILE_NOT_FOUND:
+ caml_fatal_error_arg("Fatal error: cannot find file '%s'\n", argv[pos]);
+ break;
+ case BAD_BYTECODE:
+ caml_fatal_error_arg(
+ "Fatal error: the file '%s' is not a bytecode executable file\n",
+ exe_name);
+ break;
+ }
+ }
+ /* Read the table of contents (section descriptors) */
+ caml_read_section_descriptors(fd, &trail);
+ /* Initialize the abstract machine */
+ caml_init_gc (caml_init_minor_heap_wsz, caml_init_heap_wsz,
+ caml_init_heap_chunk_sz, caml_init_percent_free,
+ caml_init_max_percent_free);
+ caml_init_stack (caml_init_max_stack_wsz);
+ caml_init_atom_table();
+ caml_init_backtrace();
+ /* Initialize the interpreter */
+ caml_interprete(NULL, 0);
+ /* Initialize the debugger, if needed */
+ caml_debugger_init();
+ /* Load the code */
+ caml_code_size = caml_seek_section(fd, &trail, "CODE");
+ caml_load_code(fd, caml_code_size);
+ caml_init_debug_info();
+ /* Build the table of primitives */
+ shared_lib_path = read_section(fd, &trail, "DLPT");
+ shared_libs = read_section(fd, &trail, "DLLS");
+ req_prims = read_section(fd, &trail, "PRIM");
+ if (req_prims == NULL) caml_fatal_error("Fatal error: no PRIM section\n");
+ caml_build_primitive_table(shared_lib_path, shared_libs, req_prims);
+ caml_stat_free(shared_lib_path);
+ caml_stat_free(shared_libs);
+ caml_stat_free(req_prims);
+ /* Load the globals */
+ caml_seek_section(fd, &trail, "DATA");
+ chan = caml_open_descriptor_in(fd);
+ caml_global_data = caml_input_val(chan);
+ caml_close_channel(chan); /* this also closes fd */
+ caml_stat_free(trail.section);
+ /* Ensure that the globals are in the major heap. */
+ caml_oldify_one (caml_global_data, &caml_global_data);
+ caml_oldify_mopup ();
+ /* Initialize system libraries */
+ caml_sys_init(exe_name, argv + pos);
+#ifdef _WIN32
+ /* Start a thread to handle signals */
+ if (getenv("CAMLSIGPIPE"))
+ _beginthread(caml_signal_thread, 4096, NULL);
+#endif
+ /* Execute the program */
+ caml_debugger(PROGRAM_START);
+ res = caml_interprete(caml_start_code, caml_code_size);
+ if (Is_exception_result(res)) {
+ caml_exn_bucket = Extract_exception(res);
+ if (caml_debugger_in_use) {
+ caml_extern_sp = &caml_exn_bucket; /* The debugger needs the
+ exception value.*/
+ caml_debugger(UNCAUGHT_EXC);
+ }
+ caml_fatal_uncaught_exception(caml_exn_bucket);
+ }
+}
+
+/* Main entry point when code is linked in as initialized data */
+
+CAMLexport void caml_startup_code(
+ code_t code, asize_t code_size,
+ char *data, asize_t data_size,
+ char *section_table, asize_t section_table_size,
+ char **argv)
+{
+ value res;
+ char * cds_file;
+ char * exe_name;
+ static char proc_self_exe[256];
+
+ caml_init_ieee_floats();
+#ifdef _MSC_VER
+ caml_install_invalid_parameter_handler();
+#endif
+ caml_init_custom_operations();
+#ifdef DEBUG
+ caml_verb_gc = 63;
+#endif
+ cds_file = getenv("CAML_DEBUG_FILE");
+ if (cds_file != NULL) {
+ caml_cds_file = caml_strdup(cds_file);
+ }
+ caml_parse_ocamlrunparam();
+ exe_name = argv[0];
+ if (caml_executable_name(proc_self_exe, sizeof(proc_self_exe)) == 0)
+ exe_name = proc_self_exe;
+ caml_external_raise = NULL;
+ /* Initialize the abstract machine */
+ caml_init_gc (caml_init_minor_heap_wsz, caml_init_heap_wsz,
+ caml_init_heap_chunk_sz, caml_init_percent_free,
+ caml_init_max_percent_free);
+ caml_init_stack (caml_init_max_stack_wsz);
+ caml_init_atom_table();
+ caml_init_backtrace();
+ /* Initialize the interpreter */
+ caml_interprete(NULL, 0);
+ /* Initialize the debugger, if needed */
+ caml_debugger_init();
+ /* Load the code */
+ caml_start_code = code;
+ caml_code_size = code_size;
+ caml_init_code_fragments();
+ caml_init_debug_info();
+ if (caml_debugger_in_use) {
+ int len, i;
+ len = code_size / sizeof(opcode_t);
+ caml_saved_code = (unsigned char *) caml_stat_alloc(len);
+ for (i = 0; i < len; i++) caml_saved_code[i] = caml_start_code[i];
+ }
+#ifdef THREADED_CODE
+ caml_thread_code(caml_start_code, code_size);
+#endif
+ /* Use the builtin table of primitives */
+ caml_build_primitive_table_builtin();
+ /* Load the globals */
+ caml_global_data = caml_input_value_from_block(data, data_size);
+ /* Ensure that the globals are in the major heap. */
+ caml_oldify_one (caml_global_data, &caml_global_data);
+ caml_oldify_mopup ();
+ /* Record the sections (for caml_get_section_table in meta.c) */
+ caml_section_table = section_table;
+ caml_section_table_size = section_table_size;
+ /* Initialize system libraries */
+ caml_sys_init(exe_name, argv);
+ /* Execute the program */
+ caml_debugger(PROGRAM_START);
+ res = caml_interprete(caml_start_code, caml_code_size);
+ if (Is_exception_result(res)) {
+ caml_exn_bucket = Extract_exception(res);
+ if (caml_debugger_in_use) {
+ caml_extern_sp = &caml_exn_bucket; /* The debugger needs the
+ exception value.*/
+ caml_debugger(UNCAUGHT_EXC);
+ }
+ caml_fatal_uncaught_exception(caml_exn_bucket);
+ }
+}
diff --git a/byterun/startup_aux.c b/byterun/startup_aux.c
new file mode 100644
index 0000000000..ea9a27f1ab
--- /dev/null
+++ b/byterun/startup_aux.c
@@ -0,0 +1,92 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Some runtime initialization functions that are common to bytecode
+ and native code. */
+
+#include <stdio.h>
+#include "caml/backtrace.h"
+#include "caml/memory.h"
+#include "caml/startup_aux.h"
+
+
+/* Initialize the atom table */
+
+CAMLexport header_t caml_atom_table[256];
+void caml_init_atom_table(void)
+{
+ int i;
+ for(i = 0; i < 256; i++) caml_atom_table[i] = Make_header(0, i, Caml_white);
+ if (caml_page_table_add(In_static_data,
+ caml_atom_table, caml_atom_table + 256) != 0) {
+ caml_fatal_error("Fatal error: not enough memory for initial page table");
+ }
+}
+
+
+/* Parse the OCAMLRUNPARAM environment variable. */
+
+uintnat caml_init_percent_free = Percent_free_def;
+uintnat caml_init_max_percent_free = Max_percent_free_def;
+uintnat caml_init_minor_heap_wsz = Minor_heap_def;
+uintnat caml_init_heap_chunk_sz = Heap_chunk_def;
+uintnat caml_init_heap_wsz = Init_heap_def;
+uintnat caml_init_max_stack_wsz = Max_stack_def;
+extern int caml_parser_trace;
+uintnat caml_trace_level = 0;
+
+
+static void scanmult (char *opt, uintnat *var)
+{
+ char mult = ' ';
+ unsigned int val = 1;
+ sscanf (opt, "=%u%c", &val, &mult);
+ sscanf (opt, "=0x%x%c", &val, &mult);
+ switch (mult) {
+ case 'k': *var = (uintnat) val * 1024; break;
+ case 'M': *var = (uintnat) val * (1024 * 1024); break;
+ case 'G': *var = (uintnat) val * (1024 * 1024 * 1024); break;
+ default: *var = (uintnat) val; break;
+ }
+}
+
+void caml_parse_ocamlrunparam(void)
+{
+ char *opt = getenv ("OCAMLRUNPARAM");
+ uintnat p;
+
+ if (opt == NULL) opt = getenv ("CAMLRUNPARAM");
+
+ if (opt != NULL){
+ while (*opt != '\0'){
+ switch (*opt++){
+ case 'a': scanmult (opt, &p); caml_set_allocation_policy (p); break;
+ case 'b': scanmult (opt, &p); caml_record_backtrace(Val_bool (p)); break;
+ case 'h': scanmult (opt, &caml_init_heap_wsz); break;
+ case 'i': scanmult (opt, &caml_init_heap_chunk_sz); break;
+ case 'l': scanmult (opt, &caml_init_max_stack_wsz); break;
+ case 'o': scanmult (opt, &caml_init_percent_free); break;
+ case 'O': scanmult (opt, &caml_init_max_percent_free); break;
+ case 'p': scanmult (opt, &p); caml_parser_trace = p; break;
+ case 'R': break; /* see stdlib/hashtbl.mli */
+ case 's': scanmult (opt, &caml_init_minor_heap_wsz); break;
+ case 't': scanmult (opt, &caml_trace_level); break;
+ case 'v': scanmult (opt, &caml_verb_gc); break;
+ case 'W': scanmult (opt, &caml_runtime_warnings); break;
+ }
+ while (*opt != '\0'){
+ if (*opt++ == ',') break;
+ }
+ }
+ }
+}
diff --git a/byterun/str.c b/byterun/str.c
new file mode 100644
index 0000000000..5ad4e29419
--- /dev/null
+++ b/byterun/str.c
@@ -0,0 +1,348 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Operations on strings */
+
+#include <string.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/mlvalues.h"
+#include "caml/misc.h"
+
+/* returns a number of bytes (chars) */
+CAMLexport mlsize_t caml_string_length(value s)
+{
+ mlsize_t temp;
+ temp = Bosize_val(s) - 1;
+ Assert (Byte (s, temp - Byte (s, temp)) == 0);
+ return temp - Byte (s, temp);
+}
+
+/* returns a value that represents a number of bytes (chars) */
+CAMLprim value caml_ml_string_length(value s)
+{
+ mlsize_t temp;
+ temp = Bosize_val(s) - 1;
+ Assert (Byte (s, temp - Byte (s, temp)) == 0);
+ return Val_long(temp - Byte (s, temp));
+}
+
+/* [len] is a value that represents a number of bytes (chars) */
+CAMLprim value caml_create_string(value len)
+{
+ mlsize_t size = Long_val(len);
+ if (size > Bsize_wsize (Max_wosize) - 1){
+ caml_invalid_argument("String.create");
+ }
+ return caml_alloc_string(size);
+}
+
+CAMLprim value caml_string_get(value str, value index)
+{
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx >= caml_string_length(str)) caml_array_bound_error();
+ return Val_int(Byte_u(str, idx));
+}
+
+CAMLprim value caml_string_set(value str, value index, value newval)
+{
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx >= caml_string_length(str)) caml_array_bound_error();
+ Byte_u(str, idx) = Int_val(newval);
+ return Val_unit;
+}
+
+CAMLprim value caml_string_get16(value str, value index)
+{
+ intnat res;
+ unsigned char b1, b2;
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx + 1 >= caml_string_length(str)) caml_array_bound_error();
+ b1 = Byte_u(str, idx);
+ b2 = Byte_u(str, idx + 1);
+#ifdef ARCH_BIG_ENDIAN
+ res = b1 << 8 | b2;
+#else
+ res = b2 << 8 | b1;
+#endif
+ return Val_int(res);
+}
+
+CAMLprim value caml_string_get32(value str, value index)
+{
+ intnat res;
+ unsigned char b1, b2, b3, b4;
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx + 3 >= caml_string_length(str)) caml_array_bound_error();
+ b1 = Byte_u(str, idx);
+ b2 = Byte_u(str, idx + 1);
+ b3 = Byte_u(str, idx + 2);
+ b4 = Byte_u(str, idx + 3);
+#ifdef ARCH_BIG_ENDIAN
+ res = b1 << 24 | b2 << 16 | b3 << 8 | b4;
+#else
+ res = b4 << 24 | b3 << 16 | b2 << 8 | b1;
+#endif
+ return caml_copy_int32(res);
+}
+
+CAMLprim value caml_string_get64(value str, value index)
+{
+ uint64_t res;
+ unsigned char b1, b2, b3, b4, b5, b6, b7, b8;
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx + 7 >= caml_string_length(str)) caml_array_bound_error();
+ b1 = Byte_u(str, idx);
+ b2 = Byte_u(str, idx + 1);
+ b3 = Byte_u(str, idx + 2);
+ b4 = Byte_u(str, idx + 3);
+ b5 = Byte_u(str, idx + 4);
+ b6 = Byte_u(str, idx + 5);
+ b7 = Byte_u(str, idx + 6);
+ b8 = Byte_u(str, idx + 7);
+#ifdef ARCH_BIG_ENDIAN
+ res = (uint64_t) b1 << 56 | (uint64_t) b2 << 48
+ | (uint64_t) b3 << 40 | (uint64_t) b4 << 32
+ | (uint64_t) b5 << 24 | (uint64_t) b6 << 16
+ | (uint64_t) b7 << 8 | (uint64_t) b8;
+#else
+ res = (uint64_t) b8 << 56 | (uint64_t) b7 << 48
+ | (uint64_t) b6 << 40 | (uint64_t) b5 << 32
+ | (uint64_t) b4 << 24 | (uint64_t) b3 << 16
+ | (uint64_t) b2 << 8 | (uint64_t) b1;
+#endif
+ return caml_copy_int64(res);
+}
+
+CAMLprim value caml_string_set16(value str, value index, value newval)
+{
+ unsigned char b1, b2;
+ intnat val;
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx + 1 >= caml_string_length(str)) caml_array_bound_error();
+ val = Long_val(newval);
+#ifdef ARCH_BIG_ENDIAN
+ b1 = 0xFF & val >> 8;
+ b2 = 0xFF & val;
+#else
+ b2 = 0xFF & val >> 8;
+ b1 = 0xFF & val;
+#endif
+ Byte_u(str, idx) = b1;
+ Byte_u(str, idx + 1) = b2;
+ return Val_unit;
+}
+
+CAMLprim value caml_string_set32(value str, value index, value newval)
+{
+ unsigned char b1, b2, b3, b4;
+ intnat val;
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx + 3 >= caml_string_length(str)) caml_array_bound_error();
+ val = Int32_val(newval);
+#ifdef ARCH_BIG_ENDIAN
+ b1 = 0xFF & val >> 24;
+ b2 = 0xFF & val >> 16;
+ b3 = 0xFF & val >> 8;
+ b4 = 0xFF & val;
+#else
+ b4 = 0xFF & val >> 24;
+ b3 = 0xFF & val >> 16;
+ b2 = 0xFF & val >> 8;
+ b1 = 0xFF & val;
+#endif
+ Byte_u(str, idx) = b1;
+ Byte_u(str, idx + 1) = b2;
+ Byte_u(str, idx + 2) = b3;
+ Byte_u(str, idx + 3) = b4;
+ return Val_unit;
+}
+
+CAMLprim value caml_string_set64(value str, value index, value newval)
+{
+ unsigned char b1, b2, b3, b4, b5, b6, b7, b8;
+ int64_t val;
+ intnat idx = Long_val(index);
+ if (idx < 0 || idx + 7 >= caml_string_length(str)) caml_array_bound_error();
+ val = Int64_val(newval);
+#ifdef ARCH_BIG_ENDIAN
+ b1 = 0xFF & val >> 56;
+ b2 = 0xFF & val >> 48;
+ b3 = 0xFF & val >> 40;
+ b4 = 0xFF & val >> 32;
+ b5 = 0xFF & val >> 24;
+ b6 = 0xFF & val >> 16;
+ b7 = 0xFF & val >> 8;
+ b8 = 0xFF & val;
+#else
+ b8 = 0xFF & val >> 56;
+ b7 = 0xFF & val >> 48;
+ b6 = 0xFF & val >> 40;
+ b5 = 0xFF & val >> 32;
+ b4 = 0xFF & val >> 24;
+ b3 = 0xFF & val >> 16;
+ b2 = 0xFF & val >> 8;
+ b1 = 0xFF & val;
+#endif
+ Byte_u(str, idx) = b1;
+ Byte_u(str, idx + 1) = b2;
+ Byte_u(str, idx + 2) = b3;
+ Byte_u(str, idx + 3) = b4;
+ Byte_u(str, idx + 4) = b5;
+ Byte_u(str, idx + 5) = b6;
+ Byte_u(str, idx + 6) = b7;
+ Byte_u(str, idx + 7) = b8;
+ return Val_unit;
+}
+
+CAMLprim value caml_string_equal(value s1, value s2)
+{
+ mlsize_t sz1, sz2;
+ value * p1, * p2;
+
+ if (s1 == s2) return Val_true;
+ sz1 = Wosize_val(s1);
+ sz2 = Wosize_val(s2);
+ if (sz1 != sz2) return Val_false;
+ for(p1 = Op_val(s1), p2 = Op_val(s2); sz1 > 0; sz1--, p1++, p2++)
+ if (*p1 != *p2) return Val_false;
+ return Val_true;
+}
+
+CAMLprim value caml_string_notequal(value s1, value s2)
+{
+ return Val_not(caml_string_equal(s1, s2));
+}
+
+CAMLprim value caml_string_compare(value s1, value s2)
+{
+ mlsize_t len1, len2;
+ int res;
+
+ if (s1 == s2) return Val_int(0);
+ len1 = caml_string_length(s1);
+ len2 = caml_string_length(s2);
+ res = memcmp(String_val(s1), String_val(s2), len1 <= len2 ? len1 : len2);
+ if (res < 0) return Val_int(-1);
+ if (res > 0) return Val_int(1);
+ if (len1 < len2) return Val_int(-1);
+ if (len1 > len2) return Val_int(1);
+ return Val_int(0);
+}
+
+CAMLprim value caml_string_lessthan(value s1, value s2)
+{
+ return caml_string_compare(s1, s2) < Val_int(0) ? Val_true : Val_false;
+}
+
+CAMLprim value caml_string_lessequal(value s1, value s2)
+{
+ return caml_string_compare(s1, s2) <= Val_int(0) ? Val_true : Val_false;
+}
+
+CAMLprim value caml_string_greaterthan(value s1, value s2)
+{
+ return caml_string_compare(s1, s2) > Val_int(0) ? Val_true : Val_false;
+}
+
+CAMLprim value caml_string_greaterequal(value s1, value s2)
+{
+ return caml_string_compare(s1, s2) >= Val_int(0) ? Val_true : Val_false;
+}
+
+CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2,
+ value n)
+{
+ memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n));
+ return Val_unit;
+}
+
+CAMLprim value caml_fill_string(value s, value offset, value len, value init)
+{
+ memset(&Byte(s, Long_val(offset)), Int_val(init), Long_val(len));
+ return Val_unit;
+}
+
+CAMLprim value caml_bitvect_test(value bv, value n)
+{
+ int pos = Int_val(n);
+ return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7)));
+}
+
+CAMLexport value caml_alloc_sprintf(const char * format, ...)
+{
+ va_list args;
+ char buf[64];
+ int n;
+ value res;
+
+#ifndef _WIN32
+ /* C99-compliant implementation */
+ va_start(args, format);
+ /* "vsnprintf(dest, sz, format, args)" writes at most "sz" characters
+ into "dest", including the terminating '\0'.
+ It returns the number of characters of the formatted string,
+ excluding the terminating '\0'. */
+ n = vsnprintf(buf, sizeof(buf), format, args);
+ va_end(args);
+ /* Allocate a Caml string with length "n" as computed by vsnprintf. */
+ res = caml_alloc_string(n);
+ if (n < sizeof(buf)) {
+ /* All output characters were written to buf, including the
+ terminating '\0'. Just copy them to the result. */
+ memcpy(String_val(res), buf, n);
+ } else {
+ /* Re-do the formatting, outputting directly in the Caml string.
+ Note that caml_alloc_string left room for a '\0' at position n,
+ so the size passed to vsnprintf is n+1. */
+ va_start(args, format);
+ vsnprintf(String_val(res), n + 1, format, args);
+ va_end(args);
+ }
+ return res;
+#else
+ /* Implementation specific to the Microsoft CRT library */
+ va_start(args, format);
+ /* "_vsnprintf(dest, sz, format, args)" writes at most "sz" characters
+ into "dest". Let "len" be the number of characters of the formatted
+ string.
+ If "len" < "sz", a null terminator was appended, and "len" is returned.
+ If "len" == "sz", no null termination, and "len" is returned.
+ If "len" > "sz", a negative value is returned. */
+ n = _vsnprintf(buf, sizeof(buf), format, args);
+ va_end(args);
+ if (n >= 0 && n <= sizeof(buf)) {
+ /* All output characters were written to buf.
+ "n" is the actual length of the output.
+ Copy the characters to a Caml string of length n. */
+ res = caml_alloc_string(n);
+ memcpy(String_val(res), buf, n);
+ } else {
+ /* Determine actual length of output, excluding final '\0' */
+ va_start(args, format);
+ n = _vscprintf(format, args);
+ va_end(args);
+ res = caml_alloc_string(n);
+ /* Re-do the formatting, outputting directly in the Caml string.
+ Note that caml_alloc_string left room for a '\0' at position n,
+ so the size passed to _vsnprintf is n+1. */
+ va_start(args, format);
+ _vsnprintf(String_val(res), n + 1, format, args);
+ va_end(args);
+ }
+ return res;
+#endif
+}
diff --git a/byterun/sys.c b/byterun/sys.c
new file mode 100644
index 0000000000..250d9683e0
--- /dev/null
+++ b/byterun/sys.c
@@ -0,0 +1,509 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Basic system calls */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#if _WIN32
+#include <io.h> /* for isatty */
+#else
+#include <sys/wait.h>
+#endif
+#include "caml/config.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#ifdef HAS_TIMES
+#include <sys/times.h>
+#endif
+#ifdef HAS_GETRUSAGE
+#include <sys/time.h>
+#include <sys/resource.h>
+#endif
+#ifdef HAS_GETTIMEOFDAY
+#include <sys/time.h>
+#endif
+#include "caml/alloc.h"
+#include "caml/debugger.h"
+#include "caml/fail.h"
+#include "caml/instruct.h"
+#include "caml/mlvalues.h"
+#include "caml/osdeps.h"
+#include "caml/signals.h"
+#include "caml/stacks.h"
+#include "caml/sys.h"
+#include "caml/gc_ctrl.h"
+#include "caml/io.h"
+
+static char * error_message(void)
+{
+ return strerror(errno);
+}
+
+#ifndef EAGAIN
+#define EAGAIN (-1)
+#endif
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK (-1)
+#endif
+
+CAMLexport void caml_sys_error(value arg)
+{
+ CAMLparam1 (arg);
+ char * err;
+ CAMLlocal1 (str);
+
+ err = error_message();
+ if (arg == NO_ARG) {
+ str = caml_copy_string(err);
+ } else {
+ int err_len = strlen(err);
+ int arg_len = caml_string_length(arg);
+ str = caml_alloc_string(arg_len + 2 + err_len);
+ memmove(&Byte(str, 0), String_val(arg), arg_len);
+ memmove(&Byte(str, arg_len), ": ", 2);
+ memmove(&Byte(str, arg_len + 2), err, err_len);
+ }
+ caml_raise_sys_error(str);
+ CAMLnoreturn;
+}
+
+CAMLexport void caml_sys_io_error(value arg)
+{
+ if (errno == EAGAIN || errno == EWOULDBLOCK) {
+ caml_raise_sys_blocked_io();
+ } else {
+ caml_sys_error(arg);
+ }
+}
+
+CAMLprim value caml_sys_exit(value retcode)
+{
+ if ((caml_verb_gc & 0x400) != 0) {
+ /* cf caml_gc_counters */
+ double minwords = caml_stat_minor_words
+ + (double) (caml_young_end - caml_young_ptr);
+ double prowords = caml_stat_promoted_words;
+ double majwords = caml_stat_major_words + (double) caml_allocated_words;
+ double allocated_words =
+ minwords + majwords - prowords;
+ caml_gc_message(0x400, "## Total allocated words: %ld\n",
+ (long)allocated_words);
+ }
+
+#ifndef NATIVE_CODE
+ caml_debugger(PROGRAM_EXIT);
+#endif
+ exit(Int_val(retcode));
+ return Val_unit;
+}
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+#ifndef O_TEXT
+#define O_TEXT 0
+#endif
+#ifndef O_NONBLOCK
+#ifdef O_NDELAY
+#define O_NONBLOCK O_NDELAY
+#else
+#define O_NONBLOCK 0
+#endif
+#endif
+
+static int sys_open_flags[] = {
+ O_RDONLY, O_WRONLY, O_APPEND | O_WRONLY, O_CREAT, O_TRUNC, O_EXCL,
+ O_BINARY, O_TEXT, O_NONBLOCK
+};
+
+CAMLprim value caml_sys_open(value path, value vflags, value vperm)
+{
+ CAMLparam3(path, vflags, vperm);
+ int fd, flags, perm;
+ char * p;
+
+ p = caml_strdup(String_val(path));
+ flags = caml_convert_flag_list(vflags, sys_open_flags);
+ perm = Int_val(vperm);
+ /* open on a named FIFO can block (PR#1533) */
+ caml_enter_blocking_section();
+ fd = open(p, flags, perm);
+ /* fcntl on a fd can block (PR#5069)*/
+#if defined(F_SETFD) && defined(FD_CLOEXEC)
+ if (fd != -1)
+ fcntl(fd, F_SETFD, FD_CLOEXEC);
+#endif
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (fd == -1) caml_sys_error(path);
+ CAMLreturn(Val_long(fd));
+}
+
+CAMLprim value caml_sys_close(value fd)
+{
+ caml_enter_blocking_section();
+ close(Int_val(fd));
+ caml_leave_blocking_section();
+ return Val_unit;
+}
+
+CAMLprim value caml_sys_file_exists(value name)
+{
+#ifdef _WIN32
+ struct _stati64 st;
+#else
+ struct stat st;
+#endif
+ char * p;
+ int ret;
+
+ p = caml_strdup(String_val(name));
+ caml_enter_blocking_section();
+#ifdef _WIN32
+ ret = _stati64(p, &st);
+#else
+ ret = stat(p, &st);
+#endif
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+
+ return Val_bool(ret == 0);
+}
+
+CAMLprim value caml_sys_is_directory(value name)
+{
+ CAMLparam1(name);
+#ifdef _WIN32
+ struct _stati64 st;
+#else
+ struct stat st;
+#endif
+ char * p;
+ int ret;
+
+ p = caml_strdup(String_val(name));
+ caml_enter_blocking_section();
+#ifdef _WIN32
+ ret = _stati64(p, &st);
+#else
+ ret = stat(p, &st);
+#endif
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+
+ if (ret == -1) caml_sys_error(name);
+#ifdef S_ISDIR
+ CAMLreturn(Val_bool(S_ISDIR(st.st_mode)));
+#else
+ CAMLreturn(Val_bool(st.st_mode & S_IFDIR));
+#endif
+}
+
+CAMLprim value caml_sys_remove(value name)
+{
+ CAMLparam1(name);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(name));
+ caml_enter_blocking_section();
+ ret = unlink(p);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret != 0) caml_sys_error(name);
+ CAMLreturn(Val_unit);
+}
+
+CAMLprim value caml_sys_rename(value oldname, value newname)
+{
+ char * p_old;
+ char * p_new;
+ int ret;
+ p_old = caml_strdup(String_val(oldname));
+ p_new = caml_strdup(String_val(newname));
+ caml_enter_blocking_section();
+ ret = rename(p_old, p_new);
+ caml_leave_blocking_section();
+ caml_stat_free(p_new);
+ caml_stat_free(p_old);
+ if (ret != 0)
+ caml_sys_error(NO_ARG);
+ return Val_unit;
+}
+
+CAMLprim value caml_sys_chdir(value dirname)
+{
+ CAMLparam1(dirname);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(dirname));
+ caml_enter_blocking_section();
+ ret = chdir(p);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret != 0) caml_sys_error(dirname);
+ CAMLreturn(Val_unit);
+}
+
+CAMLprim value caml_sys_getcwd(value unit)
+{
+ char buff[4096];
+#ifdef HAS_GETCWD
+ if (getcwd(buff, sizeof(buff)) == 0) caml_sys_error(NO_ARG);
+#else
+ if (getwd(buff) == 0) caml_sys_error(NO_ARG);
+#endif /* HAS_GETCWD */
+ return caml_copy_string(buff);
+}
+
+CAMLprim value caml_sys_getenv(value var)
+{
+ char * res;
+
+ res = getenv(String_val(var));
+ if (res == 0) caml_raise_not_found();
+ return caml_copy_string(res);
+}
+
+char * caml_exe_name;
+char ** caml_main_argv;
+
+CAMLprim value caml_sys_get_argv(value unit)
+{
+ CAMLparam0 (); /* unit is unused */
+ CAMLlocal3 (exe_name, argv, res);
+ exe_name = caml_copy_string(caml_exe_name);
+ argv = caml_copy_string_array((char const **) caml_main_argv);
+ res = caml_alloc_small(2, 0);
+ Field(res, 0) = exe_name;
+ Field(res, 1) = argv;
+ CAMLreturn(res);
+}
+
+void caml_sys_init(char * exe_name, char **argv)
+{
+ caml_exe_name = exe_name;
+ caml_main_argv = argv;
+}
+
+#ifdef _WIN32
+#define WIFEXITED(status) 1
+#define WEXITSTATUS(status) (status)
+#else
+#if !(defined(WIFEXITED) && defined(WEXITSTATUS))
+/* Assume old-style V7 status word */
+#define WIFEXITED(status) (((status) & 0xFF) == 0)
+#define WEXITSTATUS(status) (((status) >> 8) & 0xFF)
+#endif
+#endif
+
+CAMLprim value caml_sys_system_command(value command)
+{
+ CAMLparam1 (command);
+ int status, retcode;
+ char *buf;
+
+ buf = caml_strdup(String_val(command));
+ caml_enter_blocking_section ();
+ status = system(buf);
+ caml_leave_blocking_section ();
+ caml_stat_free(buf);
+ if (status == -1) caml_sys_error(command);
+ if (WIFEXITED(status))
+ retcode = WEXITSTATUS(status);
+ else
+ retcode = 255;
+ CAMLreturn (Val_int(retcode));
+}
+
+CAMLprim value caml_sys_time(value unit)
+{
+#ifdef HAS_GETRUSAGE
+ struct rusage ru;
+
+ getrusage (RUSAGE_SELF, &ru);
+ return caml_copy_double (ru.ru_utime.tv_sec + ru.ru_utime.tv_usec / 1e6
+ + ru.ru_stime.tv_sec + ru.ru_stime.tv_usec / 1e6);
+#else
+ #ifdef HAS_TIMES
+ #ifndef CLK_TCK
+ #ifdef HZ
+ #define CLK_TCK HZ
+ #else
+ #define CLK_TCK 60
+ #endif
+ #endif
+ struct tms t;
+ times(&t);
+ return caml_copy_double((double)(t.tms_utime + t.tms_stime) / CLK_TCK);
+ #else
+ /* clock() is standard ANSI C */
+ return caml_copy_double((double)clock() / CLOCKS_PER_SEC);
+ #endif
+#endif
+}
+
+#ifdef _WIN32
+extern int caml_win32_random_seed (intnat data[16]);
+#endif
+
+CAMLprim value caml_sys_random_seed (value unit)
+{
+ intnat data[16];
+ int n, i;
+ value res;
+#ifdef _WIN32
+ n = caml_win32_random_seed(data);
+#else
+ int fd;
+ n = 0;
+ /* Try /dev/urandom first */
+ fd = open("/dev/urandom", O_RDONLY, 0);
+ if (fd != -1) {
+ unsigned char buffer[12];
+ int nread = read(fd, buffer, 12);
+ close(fd);
+ while (nread > 0) data[n++] = buffer[--nread];
+ }
+ /* If the read from /dev/urandom fully succeeded, we now have 96 bits
+ of good random data and can stop here. Otherwise, complement
+ whatever we got (probably nothing) with some not-very-random data. */
+ if (n < 12) {
+#ifdef HAS_GETTIMEOFDAY
+ struct timeval tv;
+ gettimeofday(&tv, NULL);
+ data[n++] = tv.tv_usec;
+ data[n++] = tv.tv_sec;
+#else
+ data[n++] = time(NULL);
+#endif
+#ifdef HAS_UNISTD
+ data[n++] = getpid();
+ data[n++] = getppid();
+#endif
+ }
+#endif
+ /* Convert to an OCaml array of ints */
+ res = caml_alloc_small(n, 0);
+ for (i = 0; i < n; i++) Field(res, i) = Val_long(data[i]);
+ return res;
+}
+
+CAMLprim value caml_sys_const_big_endian(value unit)
+{
+#ifdef ARCH_BIG_ENDIAN
+ return Val_true;
+#else
+ return Val_false;
+#endif
+}
+
+/* returns a value that represents a number of bits */
+CAMLprim value caml_sys_const_word_size(value unit)
+{
+ return Val_long(8 * sizeof(value));
+}
+
+/* returns a value that represents a number of bits */
+CAMLprim value caml_sys_const_int_size(value unit)
+{
+ return Val_long(8 * sizeof(value) - 1) ;
+}
+
+/* returns a value that represents a number of words */
+CAMLprim value caml_sys_const_max_wosize(value unit)
+{
+ return Val_long(Max_wosize) ;
+}
+
+CAMLprim value caml_sys_const_ostype_unix(value unit)
+{
+ return Val_bool(0 == strcmp(OCAML_OS_TYPE,"Unix"));
+}
+
+CAMLprim value caml_sys_const_ostype_win32(value unit)
+{
+ return Val_bool(0 == strcmp(OCAML_OS_TYPE,"Win32"));
+}
+
+CAMLprim value caml_sys_const_ostype_cygwin(value unit)
+{
+ return Val_bool(0 == strcmp(OCAML_OS_TYPE,"Cygwin"));
+}
+
+CAMLprim value caml_sys_get_config(value unit)
+{
+ CAMLparam0 (); /* unit is unused */
+ CAMLlocal2 (result, ostype);
+
+ ostype = caml_copy_string(OCAML_OS_TYPE);
+ result = caml_alloc_small (3, 0);
+ Field(result, 0) = ostype;
+ Field(result, 1) = Val_long (8 * sizeof(value));
+#ifdef ARCH_BIG_ENDIAN
+ Field(result, 2) = Val_true;
+#else
+ Field(result, 2) = Val_false;
+#endif
+ CAMLreturn (result);
+}
+
+CAMLprim value caml_sys_read_directory(value path)
+{
+ CAMLparam1(path);
+ CAMLlocal1(result);
+ struct ext_table tbl;
+ char * p;
+ int ret;
+
+ caml_ext_table_init(&tbl, 50);
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = caml_read_directory(p, &tbl);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1){
+ caml_ext_table_free(&tbl, 1);
+ caml_sys_error(path);
+ }
+ caml_ext_table_add(&tbl, NULL);
+ result = caml_copy_string_array((char const **) tbl.contents);
+ caml_ext_table_free(&tbl, 1);
+ CAMLreturn(result);
+}
+
+/* Return true if the value is a filedescriptor (int) that is
+ * (presumably) open on an interactive terminal */
+CAMLprim value caml_sys_isatty(value chan)
+{
+ int fd;
+ value ret;
+
+ fd = (Channel(chan))->fd;
+#ifdef _WIN32
+ ret = Val_bool(_isatty(fd));
+ /* https://msdn.microsoft.com/en-us/library/f4s0ddew.aspx */
+#else
+ ret = Val_bool(isatty(fd));
+#endif
+
+ return ret;
+}
diff --git a/byterun/terminfo.c b/byterun/terminfo.c
new file mode 100644
index 0000000000..1d0fdc42d1
--- /dev/null
+++ b/byterun/terminfo.c
@@ -0,0 +1,130 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Read and output terminal commands */
+
+#include "caml/config.h"
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/io.h"
+#include "caml/mlvalues.h"
+
+#define Uninitialised (Val_int(0))
+#define Bad_term (Val_int(1))
+#define Good_term_tag 0
+
+#if defined (HAS_TERMCAP) && !defined (NATIVE_CODE)
+
+extern int tgetent (char * buffer, char * name);
+extern char * tgetstr (char * id, char ** area);
+extern int tgetnum (char * id);
+extern int tputs (char * str, int count, int (*outchar)(int c));
+
+static struct channel *chan;
+static char area [1024];
+static char *area_p = area;
+static int num_lines;
+static char *up = NULL;
+static char *down = NULL;
+static char *standout = NULL;
+static char *standend = NULL;
+
+CAMLprim value caml_terminfo_setup (value vchan)
+{
+ value result;
+ static char buffer[1024];
+ char *term;
+
+ chan = Channel (vchan);
+
+ term = getenv ("TERM");
+ if (term == NULL) return Bad_term;
+ if (tgetent(buffer, term) != 1) return Bad_term;
+
+ num_lines = tgetnum ("li");
+ up = tgetstr ("up", &area_p);
+ down = tgetstr ("do", &area_p);
+ standout = tgetstr ("us", &area_p);
+ standend = tgetstr ("ue", &area_p);
+ if (standout == NULL || standend == NULL){
+ standout = tgetstr ("so", &area_p);
+ standend = tgetstr ("se", &area_p);
+ }
+ Assert (area_p <= area + 1024);
+ if (num_lines == -1 || up == NULL || down == NULL
+ || standout == NULL || standend == NULL){
+ return Bad_term;
+ }
+ result = caml_alloc_small (1, Good_term_tag);
+ Field (result, 0) = Val_int (num_lines);
+ return result;
+}
+
+static int terminfo_putc (int c)
+{
+ putch (chan, c);
+ return c;
+}
+
+CAMLprim value caml_terminfo_backup (value lines)
+{
+ int i;
+
+ for (i = 0; i < Int_val (lines); i++){
+ tputs (up, 1, terminfo_putc);
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_terminfo_standout (value start)
+{
+ tputs (Bool_val (start) ? standout : standend, 1, terminfo_putc);
+ return Val_unit;
+}
+
+CAMLprim value caml_terminfo_resume (value lines)
+{
+ int i;
+
+ for (i = 0; i < Int_val (lines); i++){
+ tputs (down, 1, terminfo_putc);
+ }
+ return Val_unit;
+}
+
+#else /* defined (HAS_TERMCAP) && !defined (NATIVE_CODE) */
+
+CAMLexport value caml_terminfo_setup (value vchan)
+{
+ return Bad_term;
+}
+
+CAMLexport value caml_terminfo_backup (value lines)
+{
+ caml_invalid_argument("Terminfo.backup");
+ return Val_unit;
+}
+
+CAMLexport value caml_terminfo_standout (value start)
+{
+ caml_invalid_argument("Terminfo.standout");
+ return Val_unit;
+}
+
+CAMLexport value caml_terminfo_resume (value lines)
+{
+ caml_invalid_argument("Terminfo.resume");
+ return Val_unit;
+}
+
+#endif /* defined (HAS_TERMCAP) && !defined (NATIVE_CODE) */
diff --git a/byterun/unix.c b/byterun/unix.c
new file mode 100644
index 0000000000..38ddee0056
--- /dev/null
+++ b/byterun/unix.c
@@ -0,0 +1,321 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Unix-specific stuff */
+
+#define _GNU_SOURCE
+ /* Helps finding RTLD_DEFAULT in glibc */
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include "caml/config.h"
+#ifdef SUPPORT_DYNAMIC_LINKING
+#ifdef __CYGWIN__
+#include "flexdll.h"
+#else
+#include <dlfcn.h>
+#endif
+#endif
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#ifdef HAS_DIRENT
+#include <dirent.h>
+#else
+#include <sys/dir.h>
+#endif
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/osdeps.h"
+
+#ifndef S_ISREG
+#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
+#endif
+
+char * caml_decompose_path(struct ext_table * tbl, char * path)
+{
+ char * p, * q;
+ size_t n;
+
+ if (path == NULL) return NULL;
+ p = caml_strdup(path);
+ q = p;
+ while (1) {
+ for (n = 0; q[n] != 0 && q[n] != ':'; n++) /*nothing*/;
+ caml_ext_table_add(tbl, q);
+ q = q + n;
+ if (*q == 0) break;
+ *q = 0;
+ q += 1;
+ }
+ return p;
+}
+
+char * caml_search_in_path(struct ext_table * path, char * name)
+{
+ char * p, * dir, * fullname;
+ int i;
+ struct stat st;
+
+ for (p = name; *p != 0; p++) {
+ if (*p == '/') goto not_found;
+ }
+ for (i = 0; i < path->size; i++) {
+ dir = path->contents[i];
+ if (dir[0] == 0) dir = "."; /* empty path component = current dir */
+ fullname = caml_strconcat(3, dir, "/", name);
+ if (stat(fullname, &st) == 0 && S_ISREG(st.st_mode))
+ return fullname;
+ caml_stat_free(fullname);
+ }
+ not_found:
+ return caml_strdup(name);
+}
+
+#ifdef __CYGWIN__
+
+/* Cygwin needs special treatment because of the implicit ".exe" at the
+ end of executable file names */
+
+static int cygwin_file_exists(char * name)
+{
+ int fd;
+ /* Cannot use stat() here because it adds ".exe" implicitly */
+ fd = open(name, O_RDONLY);
+ if (fd == -1) return 0;
+ close(fd);
+ return 1;
+}
+
+static char * cygwin_search_exe_in_path(struct ext_table * path, char * name)
+{
+ char * p, * dir, * fullname;
+ int i;
+
+ for (p = name; *p != 0; p++) {
+ if (*p == '/' || *p == '\\') goto not_found;
+ }
+ for (i = 0; i < path->size; i++) {
+ dir = path->contents[i];
+ if (dir[0] == 0) dir = "."; /* empty path component = current dir */
+ fullname = caml_strconcat(3, dir, "/", name);
+ if (cygwin_file_exists(fullname)) return fullname;
+ caml_stat_free(fullname);
+ fullname = caml_strconcat(4, dir, "/", name, ".exe");
+ if (cygwin_file_exists(fullname)) return fullname;
+ caml_stat_free(fullname);
+ }
+ not_found:
+ if (cygwin_file_exists(name)) return caml_strdup(name);
+ fullname = caml_strconcat(2, name, ".exe");
+ if (cygwin_file_exists(fullname)) return fullname;
+ caml_stat_free(fullname);
+ return caml_strdup(name);
+}
+
+#endif
+
+char * caml_search_exe_in_path(char * name)
+{
+ struct ext_table path;
+ char * tofree;
+ char * res;
+
+ caml_ext_table_init(&path, 8);
+ tofree = caml_decompose_path(&path, getenv("PATH"));
+#ifndef __CYGWIN__
+ res = caml_search_in_path(&path, name);
+#else
+ res = cygwin_search_exe_in_path(&path, name);
+#endif
+ caml_stat_free(tofree);
+ caml_ext_table_free(&path, 0);
+ return res;
+}
+
+char * caml_search_dll_in_path(struct ext_table * path, char * name)
+{
+ char * dllname;
+ char * res;
+
+ dllname = caml_strconcat(2, name, ".so");
+ res = caml_search_in_path(path, dllname);
+ caml_stat_free(dllname);
+ return res;
+}
+
+#ifdef SUPPORT_DYNAMIC_LINKING
+#ifdef __CYGWIN__
+/* Use flexdll */
+
+void * caml_dlopen(char * libname, int for_execution, int global)
+{
+ int flags = (global ? FLEXDLL_RTLD_GLOBAL : 0);
+ if (!for_execution) flags |= FLEXDLL_RTLD_NOEXEC;
+ return flexdll_dlopen(libname, flags);
+}
+
+void caml_dlclose(void * handle)
+{
+ flexdll_dlclose(handle);
+}
+
+void * caml_dlsym(void * handle, char * name)
+{
+ return flexdll_dlsym(handle, name);
+}
+
+void * caml_globalsym(char * name)
+{
+ return flexdll_dlsym(flexdll_dlopen(NULL,0), name);
+}
+
+char * caml_dlerror(void)
+{
+ return flexdll_dlerror();
+}
+
+#else
+/* Use normal dlopen */
+
+#ifndef RTLD_GLOBAL
+#define RTLD_GLOBAL 0
+#endif
+#ifndef RTLD_LOCAL
+#define RTLD_LOCAL 0
+#endif
+#ifndef RTLD_NODELETE
+#define RTLD_NODELETE 0
+#endif
+
+void * caml_dlopen(char * libname, int for_execution, int global)
+{
+ return dlopen(libname, RTLD_NOW | (global ? RTLD_GLOBAL : RTLD_LOCAL)
+ | RTLD_NODELETE);
+ /* Could use RTLD_LAZY if for_execution == 0, but needs testing */
+}
+
+void caml_dlclose(void * handle)
+{
+ dlclose(handle);
+}
+
+void * caml_dlsym(void * handle, char * name)
+{
+#ifdef DL_NEEDS_UNDERSCORE
+ char _name[1000] = "_";
+ strncat (_name, name, 998);
+ name = _name;
+#endif
+ return dlsym(handle, name);
+}
+
+void * caml_globalsym(char * name)
+{
+#ifdef RTLD_DEFAULT
+ return caml_dlsym(RTLD_DEFAULT, name);
+#else
+ return NULL;
+#endif
+}
+
+char * caml_dlerror(void)
+{
+ return (char*) dlerror();
+}
+
+#endif
+#else
+
+void * caml_dlopen(char * libname, int for_execution, int global)
+{
+ return NULL;
+}
+
+void caml_dlclose(void * handle)
+{
+}
+
+void * caml_dlsym(void * handle, char * name)
+{
+ return NULL;
+}
+
+void * caml_globalsym(char * name)
+{
+ return NULL;
+}
+
+char * caml_dlerror(void)
+{
+ return "dynamic loading not supported on this platform";
+}
+
+#endif
+
+/* Add to [contents] the (short) names of the files contained in
+ the directory named [dirname]. No entries are added for [.] and [..].
+ Return 0 on success, -1 on error; set errno in the case of error. */
+
+int caml_read_directory(char * dirname, struct ext_table * contents)
+{
+ DIR * d;
+#ifdef HAS_DIRENT
+ struct dirent * e;
+#else
+ struct direct * e;
+#endif
+
+ d = opendir(dirname);
+ if (d == NULL) return -1;
+ while (1) {
+ e = readdir(d);
+ if (e == NULL) break;
+ if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) continue;
+ caml_ext_table_add(contents, caml_strdup(e->d_name));
+ }
+ closedir(d);
+ return 0;
+}
+
+/* Recover executable name from /proc/self/exe if possible */
+
+#ifdef __linux__
+
+int caml_executable_name(char * name, int name_len)
+{
+ int retcode;
+ struct stat st;
+
+ retcode = readlink("/proc/self/exe", name, name_len);
+ if (retcode == -1 || retcode >= name_len) return -1;
+ name[retcode] = 0;
+ /* Make sure that the contents of /proc/self/exe is a regular file.
+ (Old Linux kernels return an inode number instead.) */
+ if (stat(name, &st) != 0) return -1;
+ if (! S_ISREG(st.st_mode)) return -1;
+ return 0;
+}
+
+#else
+
+int caml_executable_name(char * name, int name_len)
+{
+ return -1;
+}
+
+#endif
diff --git a/byterun/weak.c b/byterun/weak.c
new file mode 100644
index 0000000000..3614d11cf8
--- /dev/null
+++ b/byterun/weak.c
@@ -0,0 +1,192 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Para, INRIA Rocquencourt */
+/* */
+/* Copyright 1997 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Operations on weak arrays */
+
+#include <string.h>
+
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "caml/major_gc.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+
+value caml_weak_list_head = 0;
+
+static value weak_dummy = 0;
+value caml_weak_none = (value) &weak_dummy;
+
+/* [len] is a value that represents a number of words (fields) */
+CAMLprim value caml_weak_create (value len)
+{
+ mlsize_t size, i;
+ value res;
+
+ size = Long_val (len) + 1;
+ if (size <= 0 || size > Max_wosize) caml_invalid_argument ("Weak.create");
+ res = caml_alloc_shr (size, Abstract_tag);
+ for (i = 1; i < size; i++) Field (res, i) = caml_weak_none;
+ Field (res, 0) = caml_weak_list_head;
+ caml_weak_list_head = res;
+ return res;
+}
+
+#define None_val (Val_int(0))
+#define Some_tag 0
+
+static void do_set (value ar, mlsize_t offset, value v)
+{
+ if (Is_block (v) && Is_young (v)){
+ /* modified version of Modify */
+ value old = Field (ar, offset);
+ Field (ar, offset) = v;
+ if (!(Is_block (old) && Is_young (old))){
+ if (caml_weak_ref_table.ptr >= caml_weak_ref_table.limit){
+ CAMLassert (caml_weak_ref_table.ptr == caml_weak_ref_table.limit);
+ caml_realloc_ref_table (&caml_weak_ref_table);
+ }
+ *caml_weak_ref_table.ptr++ = &Field (ar, offset);
+ }
+ }else{
+ Field (ar, offset) = v;
+ }
+}
+
+CAMLprim value caml_weak_set (value ar, value n, value el)
+{
+ mlsize_t offset = Long_val (n) + 1;
+ Assert (Is_in_heap (ar));
+ if (offset < 1 || offset >= Wosize_val (ar)){
+ caml_invalid_argument ("Weak.set");
+ }
+ if (el != None_val && Is_block (el)){
+ Assert (Wosize_val (el) == 1);
+ do_set (ar, offset, Field (el, 0));
+ }else{
+ Field (ar, offset) = caml_weak_none;
+ }
+ return Val_unit;
+}
+
+#define Setup_for_gc
+#define Restore_after_gc
+
+CAMLprim value caml_weak_get (value ar, value n)
+{
+ CAMLparam2 (ar, n);
+ mlsize_t offset = Long_val (n) + 1;
+ CAMLlocal2 (res, elt);
+ Assert (Is_in_heap (ar));
+ if (offset < 1 || offset >= Wosize_val (ar)){
+ caml_invalid_argument ("Weak.get");
+ }
+ if (Field (ar, offset) == caml_weak_none){
+ res = None_val;
+ }else{
+ elt = Field (ar, offset);
+ if (caml_gc_phase == Phase_mark && Is_block (elt) && Is_in_heap (elt)){
+ caml_darken (elt, NULL);
+ }
+ res = caml_alloc_small (1, Some_tag);
+ Field (res, 0) = elt;
+ }
+ CAMLreturn (res);
+}
+
+#undef Setup_for_gc
+#undef Restore_after_gc
+
+CAMLprim value caml_weak_get_copy (value ar, value n)
+{
+ CAMLparam2 (ar, n);
+ mlsize_t offset = Long_val (n) + 1;
+ CAMLlocal2 (res, elt);
+ value v; /* Caution: this is NOT a local root. */
+ Assert (Is_in_heap (ar));
+ if (offset < 1 || offset >= Wosize_val (ar)){
+ caml_invalid_argument ("Weak.get");
+ }
+
+ v = Field (ar, offset);
+ if (v == caml_weak_none) CAMLreturn (None_val);
+ if (Is_block (v) && Is_in_heap_or_young(v)) {
+ elt = caml_alloc (Wosize_val (v), Tag_val (v));
+ /* The GC may erase or move v during this call to caml_alloc. */
+ v = Field (ar, offset);
+ if (v == caml_weak_none) CAMLreturn (None_val);
+ if (Tag_val (v) < No_scan_tag){
+ mlsize_t i;
+ for (i = 0; i < Wosize_val (v); i++){
+ value f = Field (v, i);
+ if (caml_gc_phase == Phase_mark && Is_block (f) && Is_in_heap (f)){
+ caml_darken (f, NULL);
+ }
+ Modify (&Field (elt, i), f);
+ }
+ }else{
+ memmove (Bp_val (elt), Bp_val (v), Bosize_val (v));
+ }
+ }else{
+ elt = v;
+ }
+ res = caml_alloc_small (1, Some_tag);
+ Field (res, 0) = elt;
+
+ CAMLreturn (res);
+}
+
+CAMLprim value caml_weak_check (value ar, value n)
+{
+ mlsize_t offset = Long_val (n) + 1;
+ Assert (Is_in_heap (ar));
+ if (offset < 1 || offset >= Wosize_val (ar)){
+ caml_invalid_argument ("Weak.get");
+ }
+ return Val_bool (Field (ar, offset) != caml_weak_none);
+}
+
+CAMLprim value caml_weak_blit (value ars, value ofs,
+ value ard, value ofd, value len)
+{
+ mlsize_t offset_s = Long_val (ofs) + 1;
+ mlsize_t offset_d = Long_val (ofd) + 1;
+ mlsize_t length = Long_val (len);
+ long i;
+ Assert (Is_in_heap (ars));
+ Assert (Is_in_heap (ard));
+ if (offset_s < 1 || offset_s + length > Wosize_val (ars)){
+ caml_invalid_argument ("Weak.blit");
+ }
+ if (offset_d < 1 || offset_d + length > Wosize_val (ard)){
+ caml_invalid_argument ("Weak.blit");
+ }
+ if (caml_gc_phase == Phase_mark && caml_gc_subphase == Subphase_weak1){
+ for (i = 0; i < length; i++){
+ value v = Field (ars, offset_s + i);
+ if (v != caml_weak_none && Is_block (v) && Is_in_heap (v)
+ && Is_white_val (v)){
+ Field (ars, offset_s + i) = caml_weak_none;
+ }
+ }
+ }
+ if (offset_d < offset_s){
+ for (i = 0; i < length; i++){
+ do_set (ard, offset_d + i, Field (ars, offset_s + i));
+ }
+ }else{
+ for (i = length - 1; i >= 0; i--){
+ do_set (ard, offset_d + i, Field (ars, offset_s + i));
+ }
+ }
+ return Val_unit;
+}
diff --git a/byterun/win32.c b/byterun/win32.c
new file mode 100644
index 0000000000..f26caf8fd7
--- /dev/null
+++ b/byterun/win32.c
@@ -0,0 +1,536 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Win32-specific stuff */
+
+#include <windows.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <io.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <ctype.h>
+#include <errno.h>
+#include <string.h>
+#include <signal.h>
+#include "caml/address_class.h"
+#include "caml/fail.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/osdeps.h"
+#include "caml/signals.h"
+#include "caml/sys.h"
+
+#include <flexdll.h>
+
+#ifndef S_ISREG
+#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
+#endif
+
+char * caml_decompose_path(struct ext_table * tbl, char * path)
+{
+ char * p, * q;
+ int n;
+
+ if (path == NULL) return NULL;
+ p = caml_strdup(path);
+ q = p;
+ while (1) {
+ for (n = 0; q[n] != 0 && q[n] != ';'; n++) /*nothing*/;
+ caml_ext_table_add(tbl, q);
+ q = q + n;
+ if (*q == 0) break;
+ *q = 0;
+ q += 1;
+ }
+ return p;
+}
+
+char * caml_search_in_path(struct ext_table * path, char * name)
+{
+ char * p, * dir, * fullname;
+ int i;
+ struct stat st;
+
+ for (p = name; *p != 0; p++) {
+ if (*p == '/' || *p == '\\') goto not_found;
+ }
+ for (i = 0; i < path->size; i++) {
+ dir = path->contents[i];
+ if (dir[0] == 0) continue;
+ /* not sure what empty path components mean under Windows */
+ fullname = caml_strconcat(3, dir, "\\", name);
+ caml_gc_message(0x100, "Searching %s\n", (uintnat) fullname);
+ if (stat(fullname, &st) == 0 && S_ISREG(st.st_mode))
+ return fullname;
+ caml_stat_free(fullname);
+ }
+ not_found:
+ caml_gc_message(0x100, "%s not found in search path\n", (uintnat) name);
+ return caml_strdup(name);
+}
+
+CAMLexport char * caml_search_exe_in_path(char * name)
+{
+ char * fullname, * filepart;
+ size_t fullnamelen;
+ DWORD retcode;
+
+ fullnamelen = strlen(name) + 1;
+ if (fullnamelen < 256) fullnamelen = 256;
+ while (1) {
+ fullname = caml_stat_alloc(fullnamelen);
+ retcode = SearchPath(NULL, /* use system search path */
+ name,
+ ".exe", /* add .exe extension if needed */
+ fullnamelen,
+ fullname,
+ &filepart);
+ if (retcode == 0) {
+ caml_gc_message(0x100, "%s not found in search path\n",
+ (uintnat) name);
+ caml_stat_free(fullname);
+ return caml_strdup(name);
+ }
+ if (retcode < fullnamelen)
+ return fullname;
+ caml_stat_free(fullname);
+ fullnamelen = retcode + 1;
+ }
+}
+
+char * caml_search_dll_in_path(struct ext_table * path, char * name)
+{
+ char * dllname;
+ char * res;
+
+ dllname = caml_strconcat(2, name, ".dll");
+ res = caml_search_in_path(path, dllname);
+ caml_stat_free(dllname);
+ return res;
+}
+
+void * caml_dlopen(char * libname, int for_execution, int global)
+{
+ void *handle;
+ int flags = (global ? FLEXDLL_RTLD_GLOBAL : 0);
+ if (!for_execution) flags |= FLEXDLL_RTLD_NOEXEC;
+ handle = flexdll_dlopen(libname, flags);
+ if ((handle != NULL) && ((caml_verb_gc & 0x100) != 0)) {
+ flexdll_dump_exports(handle);
+ fflush(stdout);
+ }
+ return handle;
+}
+
+void caml_dlclose(void * handle)
+{
+ flexdll_dlclose(handle);
+}
+
+void * caml_dlsym(void * handle, char * name)
+{
+ return flexdll_dlsym(handle, name);
+}
+
+void * caml_globalsym(char * name)
+{
+ return flexdll_dlsym(flexdll_dlopen(NULL,0), name);
+}
+
+char * caml_dlerror(void)
+{
+ return flexdll_dlerror();
+}
+
+/* Proper emulation of signal(), including ctrl-C and ctrl-break */
+
+typedef void (*sighandler)(int sig);
+static int ctrl_handler_installed = 0;
+static volatile sighandler ctrl_handler_action = SIG_DFL;
+
+static BOOL WINAPI ctrl_handler(DWORD event)
+{
+ int saved_mode;
+
+ /* Only ctrl-C and ctrl-Break are handled */
+ if (event != CTRL_C_EVENT && event != CTRL_BREAK_EVENT) return FALSE;
+ /* Default behavior is to exit, which we get by not handling the event */
+ if (ctrl_handler_action == SIG_DFL) return FALSE;
+ /* Ignore behavior is to do nothing, which we get by claiming that we
+ have handled the event */
+ if (ctrl_handler_action == SIG_IGN) return TRUE;
+ /* Win32 doesn't like it when we do a longjmp() at this point
+ (it looks like we're running in a different thread than
+ the main program!). So, just record the signal. */
+ caml_record_signal(SIGINT);
+ /* We have handled the event */
+ return TRUE;
+}
+
+sighandler caml_win32_signal(int sig, sighandler action)
+{
+ sighandler oldaction;
+
+ if (sig != SIGINT) return signal(sig, action);
+ if (! ctrl_handler_installed) {
+ SetConsoleCtrlHandler(ctrl_handler, TRUE);
+ ctrl_handler_installed = 1;
+ }
+ oldaction = ctrl_handler_action;
+ ctrl_handler_action = action;
+ return oldaction;
+}
+
+/* Expansion of @responsefile and *? file patterns in the command line */
+
+static int argc;
+static char ** argv;
+static int argvsize;
+
+static void store_argument(char * arg);
+static void expand_argument(char * arg);
+static void expand_pattern(char * arg);
+
+static void out_of_memory(void)
+{
+ fprintf(stderr, "Out of memory while expanding command line\n");
+ exit(2);
+}
+
+static void store_argument(char * arg)
+{
+ if (argc + 1 >= argvsize) {
+ argvsize *= 2;
+ argv = (char **) realloc(argv, argvsize * sizeof(char *));
+ if (argv == NULL) out_of_memory();
+ }
+ argv[argc++] = arg;
+}
+
+static void expand_argument(char * arg)
+{
+ char * p;
+
+ for (p = arg; *p != 0; p++) {
+ if (*p == '*' || *p == '?') {
+ expand_pattern(arg);
+ return;
+ }
+ }
+ store_argument(arg);
+}
+
+static void expand_pattern(char * pat)
+{
+ char * prefix, * p, * name;
+ int handle;
+ struct _finddata_t ffblk;
+ size_t i;
+
+ handle = _findfirst(pat, &ffblk);
+ if (handle == -1) {
+ store_argument(pat); /* a la Bourne shell */
+ return;
+ }
+ prefix = caml_strdup(pat);
+ for (i = strlen(prefix); i > 0; i--) {
+ char c = prefix[i - 1];
+ if (c == '\\' || c == '/' || c == ':') { prefix[i] = 0; break; }
+ }
+ do {
+ name = caml_strconcat(2, prefix, ffblk.name);
+ store_argument(name);
+ } while (_findnext(handle, &ffblk) != -1);
+ _findclose(handle);
+ caml_stat_free(prefix);
+}
+
+
+CAMLexport void caml_expand_command_line(int * argcp, char *** argvp)
+{
+ int i;
+ argc = 0;
+ argvsize = 16;
+ argv = (char **) malloc(argvsize * sizeof(char *));
+ if (argv == NULL) out_of_memory();
+ for (i = 0; i < *argcp; i++) expand_argument((*argvp)[i]);
+ argv[argc] = NULL;
+ *argcp = argc;
+ *argvp = argv;
+}
+
+/* Add to [contents] the (short) names of the files contained in
+ the directory named [dirname]. No entries are added for [.] and [..].
+ Return 0 on success, -1 on error; set errno in the case of error. */
+
+int caml_read_directory(char * dirname, struct ext_table * contents)
+{
+ size_t dirnamelen;
+ char * template;
+#if _MSC_VER <= 1200
+ int h;
+#else
+ intptr_t h;
+#endif
+ struct _finddata_t fileinfo;
+
+ dirnamelen = strlen(dirname);
+ if (dirnamelen > 0 &&
+ (dirname[dirnamelen - 1] == '/'
+ || dirname[dirnamelen - 1] == '\\'
+ || dirname[dirnamelen - 1] == ':'))
+ template = caml_strconcat(2, dirname, "*.*");
+ else
+ template = caml_strconcat(2, dirname, "\\*.*");
+ h = _findfirst(template, &fileinfo);
+ if (h == -1) {
+ caml_stat_free(template);
+ return errno == ENOENT ? 0 : -1;
+ }
+ do {
+ if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) {
+ caml_ext_table_add(contents, caml_strdup(fileinfo.name));
+ }
+ } while (_findnext(h, &fileinfo) == 0);
+ _findclose(h);
+ caml_stat_free(template);
+ return 0;
+}
+
+#ifndef NATIVE_CODE
+
+/* Set up a new thread for control-C emulation and termination */
+
+void caml_signal_thread(void * lpParam)
+{
+ char *endptr;
+ HANDLE h;
+ /* Get an hexa-code raw handle through the environment */
+ h = (HANDLE) strtol(getenv("CAMLSIGPIPE"), &endptr, 16);
+ while (1) {
+ DWORD numread;
+ BOOL ret;
+ char iobuf[2];
+ /* This shall always return a single character */
+ ret = ReadFile(h, iobuf, 1, &numread, NULL);
+ if (!ret || numread != 1) caml_sys_exit(Val_int(2));
+ switch (iobuf[0]) {
+ case 'C':
+ caml_record_signal(SIGINT);
+ break;
+ case 'T':
+ raise(SIGTERM);
+ return;
+ }
+ }
+}
+
+#endif /* NATIVE_CODE */
+
+#if defined(NATIVE_CODE) && !defined(_WIN64)
+
+/* Handling of system stack overflow.
+ * Based on code provided by Olivier Andrieu.
+
+ * An EXCEPTION_STACK_OVERFLOW is signaled when the guard page at the
+ * end of the stack has been accessed. Windows clears the PAGE_GUARD
+ * protection (making it a regular PAGE_READWRITE) and then calls our
+ * exception handler. This means that although we're handling an "out
+ * of stack" condition, there is a bit of stack available to call
+ * functions and allocate temporaries.
+ *
+ * PAGE_GUARD is a one-shot access protection mechanism: we need to
+ * restore the PAGE_GUARD protection on this page otherwise the next
+ * stack overflow won't be detected and the program will abruptly exit
+ * with STATUS_ACCESS_VIOLATION.
+ *
+ * Visual Studio 2003 and later (_MSC_VER >= 1300) have a
+ * _resetstkoflw() function that resets this protection.
+ * Unfortunately, it cannot work when called directly from the
+ * exception handler because at this point we are using the page that
+ * is to be protected.
+ *
+ * A solution is to used an alternate stack when restoring the
+ * protection. However it's not possible to use _resetstkoflw() then
+ * since it determines the stack pointer by calling alloca(): it would
+ * try to protect the alternate stack.
+ *
+ * Finally, we call caml_raise_stack_overflow; it will either call
+ * caml_raise_exception which switches back to the normal stack, or
+ * call caml_fatal_uncaught_exception which terminates the program
+ * quickly.
+ *
+ * NB: The PAGE_GUARD protection is only available on WinNT, not
+ * Win9x. There is an equivalent mechanism on Win9x with
+ * PAGE_NOACCESS.
+ *
+ * Currently, does not work under Win64.
+ */
+
+static uintnat win32_alt_stack[0x80];
+
+static void caml_reset_stack (void *faulting_address)
+{
+ OSVERSIONINFO osi;
+ SYSTEM_INFO si;
+ DWORD page_size;
+ MEMORY_BASIC_INFORMATION mbi;
+ DWORD oldprot;
+
+ /* get the os version (Win9x or WinNT ?) */
+ osi.dwOSVersionInfoSize = sizeof osi;
+ if (! GetVersionEx (&osi))
+ goto failed;
+
+ /* get the system's page size. */
+ GetSystemInfo (&si);
+ page_size = si.dwPageSize;
+
+ /* get some information on the page the fault occurred */
+ if (! VirtualQuery (faulting_address, &mbi, sizeof mbi))
+ goto failed;
+
+ /* restore the PAGE_GUARD protection on this page */
+ switch (osi.dwPlatformId) {
+ case VER_PLATFORM_WIN32_NT:
+ VirtualProtect (mbi.BaseAddress, page_size,
+ mbi.Protect | PAGE_GUARD, &oldprot);
+ break;
+ case VER_PLATFORM_WIN32_WINDOWS:
+ VirtualProtect (mbi.BaseAddress, page_size,
+ PAGE_NOACCESS, &oldprot);
+ break;
+ }
+
+ failed:
+ caml_raise_stack_overflow();
+}
+
+CAMLextern int caml_is_in_code(void *);
+
+static LONG CALLBACK
+ caml_UnhandledExceptionFilter (EXCEPTION_POINTERS* exn_info)
+{
+ DWORD code = exn_info->ExceptionRecord->ExceptionCode;
+ CONTEXT *ctx = exn_info->ContextRecord;
+ DWORD *ctx_ip = &(ctx->Eip);
+ DWORD *ctx_sp = &(ctx->Esp);
+
+ if (code == EXCEPTION_STACK_OVERFLOW && Is_in_code_area (*ctx_ip))
+ {
+ uintnat faulting_address;
+ uintnat * alt_esp;
+
+ /* grab the address that caused the fault */
+ faulting_address = exn_info->ExceptionRecord->ExceptionInformation[1];
+
+ /* call caml_reset_stack(faulting_address) using the alternate stack */
+ alt_esp = win32_alt_stack + sizeof(win32_alt_stack) / sizeof(uintnat);
+ *--alt_esp = faulting_address;
+ *ctx_sp = (uintnat) (alt_esp - 1);
+ *ctx_ip = (uintnat) &caml_reset_stack;
+
+ return EXCEPTION_CONTINUE_EXECUTION;
+ }
+
+ return EXCEPTION_CONTINUE_SEARCH;
+}
+
+void caml_win32_overflow_detection()
+{
+ SetUnhandledExceptionFilter (caml_UnhandledExceptionFilter);
+}
+
+#endif
+
+/* Seeding of pseudo-random number generators */
+
+int caml_win32_random_seed (intnat data[16])
+{
+ /* For better randomness, consider:
+ http://msdn.microsoft.com/library/en-us/seccrypto/security/rtlgenrandom.asp
+ http://blogs.msdn.com/b/michael_howard/archive/2005/01/14/353379.aspx
+ */
+ FILETIME t;
+ LARGE_INTEGER pc;
+ GetSystemTimeAsFileTime(&t);
+ QueryPerformanceCounter(&pc); /* PR#6032 */
+ data[0] = t.dwLowDateTime;
+ data[1] = t.dwHighDateTime;
+ data[2] = GetCurrentProcessId();
+ data[3] = pc.LowPart;
+ data[4] = pc.HighPart;
+ return 5;
+}
+
+
+#ifdef _MSC_VER
+
+static void invalid_parameter_handler(const wchar_t* expression,
+ const wchar_t* function,
+ const wchar_t* file,
+ unsigned int line,
+ uintptr_t pReserved)
+{
+ /* no crash box */
+}
+
+
+void caml_install_invalid_parameter_handler()
+{
+ _set_invalid_parameter_handler(invalid_parameter_handler);
+}
+
+#endif
+
+
+/* Recover executable name */
+
+int caml_executable_name(char * name, int name_len)
+{
+ int retcode;
+
+ int ret = GetModuleFileName(NULL, name, name_len);
+ if (0 == ret || ret >= name_len) return -1;
+ return 0;
+}
+
+/* snprintf emulation */
+
+int caml_snprintf(char * buf, size_t size, const char * format, ...)
+{
+ int len;
+ va_list args;
+
+ if (size > 0) {
+ va_start(args, format);
+ len = _vsnprintf(buf, size, format, args);
+ va_end(args);
+ if (len >= 0 && len < size) {
+ /* [len] characters were stored in [buf],
+ a null-terminator was appended. */
+ return len;
+ }
+ /* [size] characters were stored in [buf], without null termination.
+ Put a null terminator, truncating the output. */
+ buf[size - 1] = 0;
+ }
+ /* Compute the actual length of output, excluding null terminator */
+ va_start(args, format);
+ len = _vscprintf(format, args);
+ va_end(args);
+ return len;
+}
diff --git a/compilerlibs/.gitignore b/compilerlibs/.gitignore
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/compilerlibs/.gitignore
diff --git a/config/.ignore b/config/.ignore
new file mode 100644
index 0000000000..259ce3f6e3
--- /dev/null
+++ b/config/.ignore
@@ -0,0 +1,3 @@
+m.h
+s.h
+Makefile
diff --git a/config/Makefile-templ b/config/Makefile-templ
new file mode 100644
index 0000000000..b9142c6608
--- /dev/null
+++ b/config/Makefile-templ
@@ -0,0 +1,228 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+### Compile-time configuration
+
+########## General configuration
+
+### Where to install the binaries
+BINDIR=/usr/local/bin
+
+### Where to install the standard library
+LIBDIR=/usr/local/lib/ocaml
+STUBLIBDIR=$(LIBDIR)/stublibs
+
+### Where to install the man pages
+# Man pages for commands go in $(MANDIR)/man$(MANEXT)
+# Man pages for the library go in $(MANDIR)/mano
+MANDIR=/usr/local/man
+MANEXT=1
+
+### Do #! scripts work on your system?
+### Beware: on some systems (e.g. SunOS 4), this will work only if
+### the string "#!$(BINDIR)/ocamlrun" is less than 32 characters long.
+### In doubt, set SHARPBANGSCRIPTS to false.
+SHARPBANGSCRIPTS=true
+#SHARPBANGSCRIPTS=false
+
+########## Configuration for the bytecode compiler
+
+### Which C compiler to use for the bytecode interpreter.
+### Performance of the bytecode interpreter is *much* improved
+### if Gnu CC version 2 is used.
+#BYTECC=gcc
+#BYTECC=cc
+
+### Additional compile-time options for $(BYTECC).
+# If using gcc on Intel x86:
+# (the -fno-defer-pop option circumvents a bug in certain versions of gcc)
+#BYTECCCOMPOPTS=-fno-defer-pop -Wall
+# If using gcc and being cautious:
+#BYTECCCOMPOPTS=-Wall
+# Otherwise:
+#BYTECCCOMPOPTS=
+
+### Additional link-time options for $(BYTECC)
+# To support dynamic loading of shared libraries (they need to look at
+# our own symbols):
+#BYTECCLINKOPTS=-Wl,-E
+# Otherwise:
+#BYTECCLINKOPTS=
+
+### Libraries needed
+# On most platforms:
+#CCLIBS=-lcurses -ltermcap -lm
+
+### How to invoke the C preprocessor
+# This is not needed anymore. Leave these lines commented out.
+# On most machines:
+#CPP=/lib/cpp -P
+# Under Solaris:
+#CPP=/usr/ccs/lib/cpp -P
+# Under FreeBSD:
+#CPP=cpp -P
+
+### Magic declarations for ocamlbuild -- leave unchanged
+#ml let syslib x = "-l"^x;;
+#ml let mklib out files opts = Printf.sprintf "ar rc %s %s %s; ranlib %s" out opts files out;;
+
+### How to invoke ranlib
+RANLIB=ranlib
+RANLIBCMD=ranlib
+
+# If ranlib is not needed:
+#RANLIB=ar rs
+#RANLIBCMD=
+
+### How to invoke ar
+#ARCMD=ar
+
+### Shared library support
+# Extension for shared libraries: so if supported, a if not supported
+#SO=so
+#SO=a
+# Set to nothing if shared libraries supported, and to -custom if not supported
+#CUSTOM_IF_NOT_SHARED=
+#CUSTOM_IF_NOT_SHARED=-custom
+# Options to $(BYTECC) to produce shared objects (e.g. PIC)
+#SHAREDCCCOMPOPTS=-fPIC
+# How to build a shared library, invoked with output .so as first arg
+# and object files as remaining args
+#MKSHAREDLIB=gcc -shared -o
+# Compile-time option to $(BYTECC) to add a directory to be searched
+# at run-time for shared libraries
+#BYTECCRPATH=-Wl,-rpath
+
+############# Configuration for the native-code compiler
+
+### Name of architecture for the native-code compiler
+### Currently supported:
+###
+### i386 Intel Pentium PCs under Linux, *BSD*, NextStep
+### sparc Sun Sparcstation under SunOS 4.1 or Solaris 2
+### power Macintosh under Mac OS X and Linux
+### arm ARM under Linux
+###
+### Set ARCH=none if your machine is not supported
+#ARCH=i386
+#ARCH=sparc
+#ARCH=power
+#ARCH=arm
+#ARCH=none
+
+### Name of architecture model for the native-code compiler.
+### Some architectures come in several slightly different flavors
+### that share a common code generator. This variable tailors the
+### behavior of the code generator to the particular flavor used.
+### Currently needed only if ARCH=power; leave MODEL=default for
+### other architectures.
+### If ARCH=power: set MODEL=ppc
+### For other architectures: leave MODEL=default
+###
+#MODEL=ppc
+#MODEL=default
+
+### Name of operating system family for the native-code compiler.
+#SYSTEM=solaris
+#SYSTEM=linux
+#SYSTEM=linux_elf
+#SYSTEM=bsd
+#SYSTEM=unknown
+
+### Which C compiler to use for the native-code compiler.
+#NATIVECC=cc
+#NATIVECC=gcc
+
+### Additional compile-time options for $(NATIVECC).
+# For gcc if cautious:
+#NATIVECCCOMPOPTS=-Wall
+
+### Additional link-time options for $(NATIVECC)
+#NATIVECCLINKOPTS=
+
+# Compile-time option to $(NATIVECC) to add a directory to be searched
+# at run-time for shared libraries
+#NATIVECCRPATH=-Wl,-rpath
+
+### Command and flags to use for assembling ocamlopt-generated code
+#ASM=as
+
+### Command and flags to use for assembling .S files (often with preprocessing)
+# If gcc is available:
+#ASPP=gcc -c
+# On Solaris:
+#ASPP=as -P
+
+### Extra flags to use for assembling .S files in profiling mode
+#ASPPPROFFLAGS=-DPROFILING
+
+### Whether profiling with gprof is supported
+# If yes: (e.g. x86/Linux, Sparc/Solaris):
+#PROFILING=prof
+# If no:
+#PROFILING=noprof
+
+### Option to give to the C compiler for profiling
+#CC_PROFILE=-pg
+#CC_PROFILE=-xpg
+
+### How to perform a partial link
+PARTIALLD=ld -r $(NATIVECCLINKOPTS)
+
+############# Configuration for the contributed libraries
+
+### Which libraries to compile and install
+# Currently available:
+# unix Unix system calls
+# str Regular expressions and high-level string processing
+# num Arbitrary-precision rational arithmetic
+# threads Lightweight concurrent processes
+# systhreads Same as threads, requires POSIX threads
+# graph Portable drawing primitives for X11
+# dynlink Dynamic linking of bytecode
+# bigarray Large, multidimensional numerical arrays
+
+OTHERLIBRARIES=unix str num threads graph dynlink bigarray
+
+### Name of the target architecture for the "num" library
+# Known targets:
+# generic (portable C, works everywhere)
+# ia32 (Intel x86)
+# amd64 (AMD Opteron, Athlon64)
+# ppc (Power PC)
+# sparc
+# If you don't know, leave BNG_ARCH=generic, which selects a portable
+# C implementation of these routines.
+BNG_ARCH=generic
+BNG_ASM_LEVEL=1
+
+### Link-time options to ocamlc or ocamlopt for linking with POSIX threads
+# Needed for the "systhreads" package
+# Usually:
+#PTHREAD_LINK=-cclib -lpthread
+# For Solaris:
+#PTHREAD_LINK=-cclib -lpthread -cclib -lposix4
+
+### -I options for finding the X11/*.h includes
+# Needed for the "graph" package
+# Usually:
+#X11_INCLUDES=-I/usr/X11R6/include
+# For SunOS with OpenLook:
+#X11_INCLUDES=/usr/openwin/include
+
+### Link-time options to ocamlc or ocamlopt for linking with X11 libraries
+# Needed for the "graph" package
+# Usually:
+#X11_LINK=-lX11
+# For SunOS with OpenLook:
+#X11_LINK=-L$(X11_LIB) -lX11
diff --git a/config/Makefile.mingw b/config/Makefile.mingw
new file mode 100644
index 0000000000..5b4658f71b
--- /dev/null
+++ b/config/Makefile.mingw
@@ -0,0 +1,177 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+# Configuration for Windows, Mingw compiler
+
+######### General configuration
+
+PREFIX=C:/ocamlmgw
+
+### Remove this to disable compiling ocamldebug
+WITH_DEBUGGER=ocamldebugger
+
+### Remove this to disable compiling ocamlbuild
+WITH_OCAMLBUILD=ocamlbuild
+
+### Remove this to disable compiling ocamldoc
+WITH_OCAMLDOC=ocamldoc
+
+### Where to install the binaries
+BINDIR=$(PREFIX)/bin
+
+### Where to install the standard library
+LIBDIR=$(PREFIX)/lib
+
+### Where to install the stub DLLs
+STUBLIBDIR=$(LIBDIR)/stublibs
+
+### Where to install the info files
+DISTRIB=$(PREFIX)
+
+### Where to install the man pages
+MANDIR=$(PREFIX)/man
+
+########## Toolchain and OS dependencies
+
+TOOLCHAIN=mingw
+
+### Toolchain prefix
+TARGET=i686-w64-mingw32
+HOST=i686-w64-mingw32
+
+TOOLPREF=$(TARGET)-
+
+CCOMPTYPE=cc
+O=o
+A=a
+S=s
+SO=s.o
+EXE=.exe
+EXT_DLL=.dll
+EXT_OBJ=.$(O)
+EXT_LIB=.$(A)
+EXT_ASM=.$(S)
+MANEXT=1
+SHARPBANGSCRIPTS=false
+PTHREAD_LINK=
+X11_INCLUDES=
+X11_LINK=
+BYTECCRPATH=
+SUPPORTS_SHARED_LIBRARIES=true
+SHAREDCCCOMPOPTS=-O
+MKSHAREDLIBRPATH=
+NATIVECCPROFOPTS=
+NATIVECCRPATH=
+ASM=$(TOOLPREF)as
+ASPP=$(TOOLPREF)gcc -c
+ASPPPROFFLAGS=
+PROFILING=noprof
+DYNLINKOPTS=
+CC_PROFILE=
+SYSTHREAD_SUPPORT=true
+EXTRALIBS=
+NATDYNLINK=true
+CMXS=cmxs
+RUNTIMED=noruntimed
+ASM_CFI_SUPPORTED=false
+UNIXLIB=win32unix
+GRAPHLIB=win32graph
+
+########## Configuration for the bytecode compiler
+
+### Which C compiler to use for the bytecode interpreter.
+BYTECC=$(TOOLPREF)gcc
+
+### Additional compile-time options for $(BYTECC). (For static linking.)
+BYTECCCOMPOPTS=-O -mms-bitfields -Wall -Wno-unused
+
+### Additional link-time options for $(BYTECC). (For static linking.)
+BYTECCLINKOPTS=
+
+### Additional compile-time options for $(BYTECC). (For building a DLL.)
+DLLCCCOMPOPTS=-O -mms-bitfields -Wall -Wno-unused -DCAML_DLL
+
+### Libraries needed
+BYTECCLIBS=-lws2_32
+NATIVECCLIBS=-lws2_32
+
+### How to invoke the C preprocessor
+CPP=$(BYTECC) -E
+
+### Flexlink
+FLEXLINK=flexlink -chain mingw -stack 16777216 -link -static-libgcc
+FLEXDIR:=$(shell $(FLEXLINK) -where)
+IFLEXDIR=-I"$(FLEXDIR)"
+MKDLL=$(FLEXLINK)
+MKEXE=$(FLEXLINK) -exe
+MKMAINDLL=$(FLEXLINK) -maindll
+
+### How to build a static library
+MKLIB=rm -f $(1); $(TOOLPREF)ar rc $(1) $(2); $(RANLIB) $(1)
+#ml let mklib out files opts = Printf.sprintf "rm -f %s && %sar rcs %s %s %s" out toolpref opts out files;;
+
+### Canonicalize the name of a system library
+SYSLIB=-l$(1)
+#ml let syslib x = "-l"^x;;
+
+### The ranlib command
+RANLIB=$(TOOLPREF)ranlib
+RANLIBCMD=$(TOOLPREF)ranlib
+
+### The ar command
+ARCMD=$(TOOLPREF)ar
+
+############# Configuration for the native-code compiler
+
+### Name of architecture for the native-code compiler
+ARCH=i386
+
+### Name of architecture model for the native-code compiler.
+MODEL=default
+
+### Name of operating system family for the native-code compiler.
+SYSTEM=mingw
+
+### Which C compiler to use for the native-code compiler.
+NATIVECC=$(BYTECC)
+
+### Additional compile-time options for $(NATIVECC).
+NATIVECCCOMPOPTS=-O -mms-bitfields -Wall -Wno-unused
+
+### Additional link-time options for $(NATIVECC)
+NATIVECCLINKOPTS=
+
+### Build partially-linked object file
+PACKLD=$(TOOLPREF)ld -r $(NATIVECCLINKOPTS) -o # must have a space after '-o'
+
+############# Configuration for the contributed libraries
+
+OTHERLIBRARIES=win32unix str num win32graph dynlink bigarray systhreads
+
+### Name of the target architecture for the "num" library
+BNG_ARCH=ia32
+BNG_ASM_LEVEL=1
+
+############# Aliases for common commands
+
+MAKEREC=$(MAKE) -f Makefile.nt
+MAKECMD=$(MAKE)
+
+############# for the testsuite makefiles
+#ml let topdir = "" and wintopdir = "";;
+OTOPDIR=$(WINTOPDIR)
+CTOPDIR=$(TOPDIR)
+CYGPATH=cygpath -m
+DIFF=diff -q --strip-trailing-cr
+CANKILL=false
+SET_LD_PATH=PATH="$(PATH):$(LD_PATH)"
diff --git a/config/Makefile.mingw64 b/config/Makefile.mingw64
new file mode 100644
index 0000000000..19a9b94376
--- /dev/null
+++ b/config/Makefile.mingw64
@@ -0,0 +1,177 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+# Configuration for Windows, Mingw compiler
+
+######### General configuration
+
+PREFIX=C:/ocamlmgw64
+
+### Remove this to disable compiling ocamldebug
+WITH_DEBUGGER=ocamldebugger
+
+### Remove this to disable compiling ocamlbuild
+WITH_OCAMLBUILD=ocamlbuild
+
+### Remove this to disable compiling ocamldoc
+WITH_OCAMLDOC=ocamldoc
+
+### Where to install the binaries
+BINDIR=$(PREFIX)/bin
+
+### Where to install the standard library
+LIBDIR=$(PREFIX)/lib
+
+### Where to install the stub DLLs
+STUBLIBDIR=$(LIBDIR)/stublibs
+
+### Where to install the info files
+DISTRIB=$(PREFIX)
+
+### Where to install the man pages
+MANDIR=$(PREFIX)/man
+
+########## Toolchain and OS dependencies
+
+TOOLCHAIN=mingw
+
+### Toolchain prefix
+TARGET=x86_64-w64-mingw32
+HOST=$(TARGET)
+
+TOOLPREF=$(TARGET)-
+
+CCOMPTYPE=cc
+O=o
+A=a
+S=s
+SO=s.o
+EXE=.exe
+EXT_DLL=.dll
+EXT_OBJ=.$(O)
+EXT_LIB=.$(A)
+EXT_ASM=.$(S)
+MANEXT=1
+SHARPBANGSCRIPTS=false
+PTHREAD_LINK=
+X11_INCLUDES=
+X11_LINK=
+BYTECCRPATH=
+SUPPORTS_SHARED_LIBRARIES=true
+SHAREDCCCOMPOPTS=-O
+MKSHAREDLIBRPATH=
+NATIVECCPROFOPTS=
+NATIVECCRPATH=
+ASM=$(TOOLPREF)as
+ASPP=$(TOOLPREF)gcc -c
+ASPPPROFFLAGS=
+PROFILING=noprof
+DYNLINKOPTS=
+CC_PROFILE=
+SYSTHREAD_SUPPORT=true
+EXTRALIBS=
+NATDYNLINK=true
+CMXS=cmxs
+RUNTIMED=noruntimed
+ASM_CFI_SUPPORTED=false
+UNIXLIB=win32unix
+GRAPHLIB=win32graph
+
+########## Configuration for the bytecode compiler
+
+### Which C compiler to use for the bytecode interpreter.
+BYTECC=$(TOOLPREF)gcc
+
+### Additional compile-time options for $(BYTECC). (For static linking.)
+BYTECCCOMPOPTS=-O -mms-bitfields -Wall -Wno-unused
+
+### Additional link-time options for $(BYTECC). (For static linking.)
+BYTECCLINKOPTS=
+
+### Additional compile-time options for $(BYTECC). (For building a DLL.)
+DLLCCCOMPOPTS=-O -mms-bitfields -Wall -Wno-unused -DCAML_DLL
+
+### Libraries needed
+BYTECCLIBS=-lws2_32
+NATIVECCLIBS=-lws2_32
+
+### How to invoke the C preprocessor
+CPP=$(BYTECC) -E
+
+### Flexlink
+FLEXLINK=flexlink -chain mingw64 -stack 33554432
+FLEXDIR:=$(shell $(FLEXLINK) -where)
+IFLEXDIR=-I"$(FLEXDIR)"
+MKDLL=$(FLEXLINK)
+MKEXE=$(FLEXLINK) -exe
+MKMAINDLL=$(FLEXLINK) -maindll
+
+### How to build a static library
+MKLIB=rm -f $(1); $(TOOLPREF)ar rc $(1) $(2); $(RANLIB) $(1)
+#ml let mklib out files opts = Printf.sprintf "rm -f %s && %sar rcs %s %s %s" out toolpref opts out files;;
+
+### Canonicalize the name of a system library
+SYSLIB=-l$(1)
+#ml let syslib x = "-l"^x;;
+
+### The ranlib command
+RANLIB=$(TOOLPREF)ranlib
+RANLIBCMD=$(TOOLPREF)ranlib
+
+### The ar command
+ARCMD=$(TOOLPREF)ar
+
+############# Configuration for the native-code compiler
+
+### Name of architecture for the native-code compiler
+ARCH=amd64
+
+### Name of architecture model for the native-code compiler.
+MODEL=default
+
+### Name of operating system family for the native-code compiler.
+SYSTEM=mingw64
+
+### Which C compiler to use for the native-code compiler.
+NATIVECC=$(BYTECC)
+
+### Additional compile-time options for $(NATIVECC).
+NATIVECCCOMPOPTS=-O -mms-bitfields -Wall -Wno-unused
+
+### Additional link-time options for $(NATIVECC)
+NATIVECCLINKOPTS=
+
+### Build partially-linked object file
+PACKLD=$(TOOLPREF)ld -r $(NATIVECCLINKOPTS) -o # must have a space after '-o'
+
+############# Configuration for the contributed libraries
+
+OTHERLIBRARIES=win32unix str num win32graph dynlink bigarray systhreads
+
+### Name of the target architecture for the "num" library
+BNG_ARCH=amd64
+BNG_ASM_LEVEL=1
+
+############# Aliases for common commands
+
+MAKEREC=$(MAKE) -f Makefile.nt
+MAKECMD=$(MAKE)
+
+############# for the testsuite makefiles
+#ml let topdir = "" and wintopdir = "";;
+OTOPDIR=$(WINTOPDIR)
+CTOPDIR=$(TOPDIR)
+CYGPATH=cygpath -m
+DIFF=diff -q --strip-trailing-cr
+CANKILL=false
+SET_LD_PATH=PATH="$(PATH):$(LD_PATH)"
diff --git a/config/Makefile.msvc b/config/Makefile.msvc
new file mode 100644
index 0000000000..4d399cf49b
--- /dev/null
+++ b/config/Makefile.msvc
@@ -0,0 +1,180 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+# Configuration for Windows, Visual C++ compiler
+
+######### General configuration
+
+PREFIX=C:/ocamlms
+
+### Where to install the binaries.
+BINDIR=$(PREFIX)/bin
+
+### Where to install the standard library
+LIBDIR=$(PREFIX)/lib
+
+### Where to install the stub DLLs
+STUBLIBDIR=$(LIBDIR)/stublibs
+
+### Where to install the info files
+DISTRIB=$(PREFIX)
+
+### Where to install the man pages
+MANDIR=$(PREFIX)/man
+
+########## Toolchain and OS dependencies
+
+TOOLCHAIN=msvc
+
+# It doesn't make much sense to set "TARGET" and "HOST" for msvc but it's needed
+# for the myocamlbuild config.
+# The only case these will be used currently is to check whether we're
+# cross-compiling or not so setting them to the same value is what matters.
+HOST=msvc
+TARGET=$(HOST)
+
+CCOMPTYPE=msvc
+O=obj
+A=lib
+S=asm
+SO=s.obj
+EXE=.exe
+EXT_DLL=.dll
+EXT_OBJ=.$(O)
+EXT_LIB=.$(A)
+EXT_ASM=.$(S)
+MANEXT=1
+SHARPBANGSCRIPTS=false
+PTHREAD_LINK=
+X11_INCLUDES=
+X11_LINK=
+BYTECCRPATH=
+SUPPORTS_SHARED_LIBRARIES=true
+SHAREDCCCOMPOPTS=-Ox
+NATIVECCPROFOPTS=
+NATIVECCRPATH=
+ASM=ml -nologo -coff -Cp -c -Fo
+ASPP=
+ASPPPROFFLAGS=
+PROFILING=noprof
+DYNLINKOPTS=
+CC_PROFILE=
+SYSTHREAD_SUPPORT=true
+EXTRALIBS=
+CMXS=cmxs
+NATDYNLINK=true
+RUNTIMED=noruntimed
+ASM_CFI_SUPPORTED=false
+UNIXLIB=win32unix
+GRAPHLIB=win32graph
+
+########## Configuration for the bytecode compiler
+
+### Which C compiler to use for the bytecode interpreter.
+BYTECC=cl -nologo -D_CRT_SECURE_NO_DEPRECATE
+
+### Additional compile-time options for $(BYTECC). (For static linking.)
+BYTECCCOMPOPTS=-O2 -Gy- -MD
+
+### Additional link-time options for $(BYTECC). (For static linking.)
+BYTECCLINKOPTS=
+
+### Additional compile-time options for $(BYTECC). (For building a DLL.)
+DLLCCCOMPOPTS=-O2 -Gy- -MD
+
+### Libraries needed
+BYTECCLIBS=advapi32.lib ws2_32.lib
+NATIVECCLIBS=advapi32.lib ws2_32.lib
+
+### How to invoke the C preprocessor
+CPP=cl -nologo -EP
+
+### Flexlink
+FLEXLINK=flexlink -merge-manifest -stack 16777216
+FLEXDIR:=$(shell $(FLEXLINK) -where)
+IFLEXDIR=-I"$(FLEXDIR)"
+MKDLL=$(FLEXLINK)
+MKEXE=$(FLEXLINK) -exe
+MKMAINDLL=$(FLEXLINK) -maindll
+
+### How to build a static library
+MKLIB=link -lib -nologo -out:$(1) $(2)
+#ml let mklib out files opts = Printf.sprintf "link -lib -nologo -out:%s %s %s" out opts files;;
+MKSHAREDLIBRPATH=
+
+### Canonicalize the name of a system library
+SYSLIB=$(1).lib
+#ml let syslib x = x ^ ".lib";;
+
+### The ranlib command
+RANLIB=echo
+RANLIBCMD=
+
+### The ar command
+ARCMD=
+
+############# Configuration for the native-code compiler
+
+### Name of architecture for the native-code compiler
+ARCH=i386
+
+### Name of architecture model for the native-code compiler.
+MODEL=default
+
+### Name of operating system family for the native-code compiler.
+SYSTEM=win32
+
+### Which C compiler to use for the native-code compiler.
+NATIVECC=cl -nologo -D_CRT_SECURE_NO_DEPRECATE
+
+### Additional compile-time options for $(NATIVECC).
+NATIVECCCOMPOPTS=-O2 -Gy- -MD
+
+### Additional link-time options for $(NATIVECC)
+NATIVECCLINKOPTS=
+
+### Build partially-linked object file
+PACKLD=link -lib -nologo -out:# there must be no space after this '-out:'
+
+### Clear this to disable compiling ocamldebug
+WITH_DEBUGGER=ocamldebugger
+
+### Clear this to disable compiling ocamlbuild
+WITH_OCAMLBUILD=ocamlbuild
+
+### Clear this to disable compiling ocamldoc
+WITH_OCAMLDOC=ocamldoc
+
+############# Configuration for the contributed libraries
+
+OTHERLIBRARIES=win32unix systhreads str num win32graph dynlink bigarray
+
+### Name of the target architecture for the "num" library
+BNG_ARCH=generic
+BNG_ASM_LEVEL=0
+
+############# Aliases for common commands
+
+MAKEREC=$(MAKE) -f Makefile.nt
+MAKECMD=$(MAKE)
+
+############# for the testsuite makefiles
+#ml let topdir = "" and wintopdir = "";;
+OTOPDIR=$(WINTOPDIR)
+CTOPDIR=$(WINTOPDIR)
+CYGPATH=cygpath -m
+DIFF=diff -q --strip-trailing-cr
+CANKILL=false
+FIND=/usr/bin/find
+SORT=/usr/bin/sort
+SET_LD_PATH=PATH="$(PATH):$(LD_PATH)"
diff --git a/config/Makefile.msvc64 b/config/Makefile.msvc64
new file mode 100644
index 0000000000..6a9650ba5e
--- /dev/null
+++ b/config/Makefile.msvc64
@@ -0,0 +1,184 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+# Configuration for Windows, Visual C++ compiler
+
+######### General configuration
+
+PREFIX=C:/ocamlms64
+
+### Where to install the binaries.
+BINDIR=$(PREFIX)/bin
+
+### Where to install the standard library
+LIBDIR=$(PREFIX)/lib
+
+### Where to install the stub DLLs
+STUBLIBDIR=$(LIBDIR)/stublibs
+
+### Where to install the info files
+DISTRIB=$(PREFIX)
+
+### Where to install the man pages
+MANDIR=$(PREFIX)/man
+
+########## Toolchain and OS dependencies
+
+TOOLCHAIN=msvc
+
+# It doesn't make much sense to set "TARGET" and "HOST" for msvc but it's needed
+# for the myocamlbuild config.
+# The only case these will be used currently is to check whether we're
+# cross-compiling or not so setting them to the same value is what matters.
+HOST=msvc64
+TARGET=$(HOST)
+
+CCOMPTYPE=msvc
+O=obj
+A=lib
+S=asm
+SO=s.obj
+EXE=.exe
+EXT_DLL=.dll
+EXT_OBJ=.$(O)
+EXT_LIB=.$(A)
+EXT_ASM=.$(S)
+MANEXT=1
+SHARPBANGSCRIPTS=false
+PTHREAD_LINK=
+X11_INCLUDES=
+X11_LINK=
+BYTECCRPATH=
+SUPPORTS_SHARED_LIBRARIES=true
+SHAREDCCCOMPOPTS=-Ox
+NATIVECCPROFOPTS=
+NATIVECCRPATH=
+ASM=ml64 -nologo -Cp -c -Fo
+ASPP=
+ASPPPROFFLAGS=
+PROFILING=noprof
+DYNLINKOPTS=
+CC_PROFILE=
+SYSTHREAD_SUPPORT=true
+CMXS=cmxs
+NATDYNLINK=true
+RUNTIMED=noruntimed
+ASM_CFI_SUPPORTED=false
+UNIXLIB=win32unix
+GRAPHLIB=win32graph
+
+########## Configuration for the bytecode compiler
+
+### Which C compiler to use for the bytecode interpreter.
+BYTECC=cl -nologo -D_CRT_SECURE_NO_DEPRECATE
+
+### Additional compile-time options for $(BYTECC). (For static linking.)
+BYTECCCOMPOPTS=-O2 -Gy- -MD
+
+### Additional compile-time options for $(BYTECC). (For debug version.)
+BYTECCDBGCOMPOPTS=-DDEBUG -Zi -W3 -Wp64
+
+### Additional link-time options for $(BYTECC). (For static linking.)
+BYTECCLINKOPTS=
+
+### Additional compile-time options for $(BYTECC). (For building a DLL.)
+DLLCCCOMPOPTS=-O2 -Gy- -MD
+
+### Libraries needed
+#EXTRALIBS=bufferoverflowu.lib # for the old PSDK compiler only
+EXTRALIBS=
+BYTECCLIBS=advapi32.lib ws2_32.lib $(EXTRALIBS)
+NATIVECCLIBS=advapi32.lib ws2_32.lib $(EXTRALIBS)
+
+### How to invoke the C preprocessor
+CPP=cl -nologo -EP
+
+### Flexlink
+FLEXLINK=flexlink -x64 -merge-manifest -stack 33554432
+FLEXDIR:=$(shell $(FLEXLINK) -where)
+IFLEXDIR=-I"$(FLEXDIR)"
+MKDLL=$(FLEXLINK)
+MKEXE=$(FLEXLINK) -exe
+MKMAINDLL=$(FLEXLINK) -maindll
+
+### How to build a static library
+MKLIB=link -lib -nologo -machine:AMD64 /out:$(1) $(2)
+#ml let mklib out files opts = Printf.sprintf "link -lib -nologo -machine:AMD64 -out:%s %s %s" out opts files;;
+MKSHAREDLIBRPATH=
+
+### Canonicalize the name of a system library
+SYSLIB=$(1).lib
+#ml let syslib x = x ^ ".lib";;
+
+### The ranlib command
+RANLIB=echo
+RANLIBCMD=
+
+### The ar command
+ARCMD=
+
+############# Configuration for the native-code compiler
+
+### Name of architecture for the native-code compiler
+ARCH=amd64
+
+### Name of architecture model for the native-code compiler.
+MODEL=default
+
+### Name of operating system family for the native-code compiler.
+SYSTEM=win64
+
+### Which C compiler to use for the native-code compiler.
+NATIVECC=cl -nologo
+
+### Additional compile-time options for $(NATIVECC).
+NATIVECCCOMPOPTS=-O2 -Gy- -MD
+
+### Additional link-time options for $(NATIVECC)
+NATIVECCLINKOPTS=
+
+### Build partially-linked object file
+PACKLD=link -lib -nologo -machine:AMD64 -out:# must have no space after '-out:'
+
+### Clear this to disable compiling ocamldebug
+WITH_DEBUGGER=ocamldebugger
+
+### Clear this to disable compiling ocamlbuild
+WITH_OCAMLBUILD=ocamlbuild
+
+### Clear this to disable compiling ocamldoc
+WITH_OCAMLDOC=ocamldoc
+
+############# Configuration for the contributed libraries
+
+OTHERLIBRARIES=win32unix systhreads str num win32graph dynlink bigarray
+
+### Name of the target architecture for the "num" library
+BNG_ARCH=generic
+BNG_ASM_LEVEL=0
+
+############# Aliases for common commands
+
+MAKEREC=$(MAKE) -f Makefile.nt
+MAKECMD=$(MAKE)
+
+############# for the testsuite makefiles
+#ml let topdir = "" and wintopdir = "";;
+OTOPDIR=$(WINTOPDIR)
+CTOPDIR=$(WINTOPDIR)
+CYGPATH=cygpath -m
+DIFF=diff -q --strip-trailing-cr
+CANKILL=false
+FIND=/usr/bin/find
+SORT=/usr/bin/sort
+SET_LD_PATH=PATH="$(PATH):$(LD_PATH)"
diff --git a/config/auto-aux/.ignore b/config/auto-aux/.ignore
new file mode 100644
index 0000000000..cb1ca8a9f0
--- /dev/null
+++ b/config/auto-aux/.ignore
@@ -0,0 +1 @@
+camlp4_config.ml
diff --git a/config/auto-aux/align.c b/config/auto-aux/align.c
new file mode 100644
index 0000000000..579db9c63e
--- /dev/null
+++ b/config/auto-aux/align.c
@@ -0,0 +1,101 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <signal.h>
+#include <setjmp.h>
+
+long foo;
+
+void access16(short int *p)
+{
+ foo = *p;
+}
+
+void access32(long int *p)
+{
+ foo = *p;
+}
+
+jmp_buf failure;
+
+void sig_handler(int dummy)
+{
+ longjmp(failure, 1);
+}
+
+int test(void (*fct) (/* ??? */), char *p)
+{
+ int res;
+
+ signal(SIGSEGV, sig_handler);
+ signal(SIGBUS, sig_handler);
+ if(setjmp(failure) == 0) {
+ fct(p);
+ res = 0;
+ } else {
+ res = 1;
+ }
+ signal(SIGSEGV, SIG_DFL);
+ signal(SIGBUS, SIG_DFL);
+ return res;
+}
+
+jmp_buf timer;
+
+void alarm_handler(int dummy)
+{
+ longjmp(timer, 1);
+}
+
+void use(int n)
+{
+ return;
+}
+
+int speedtest(char *p)
+{
+ int * q;
+ volatile int total;
+ int i;
+ volatile int sum;
+
+ signal(SIGALRM, alarm_handler);
+ sum = 0;
+ if (setjmp(timer) == 0) {
+ alarm(1);
+ total = 0;
+ while(1) {
+ for (q = (int *) p, i = 1000; i > 0; q++, i--)
+ sum += *q;
+ total++;
+ }
+ }
+ use(sum);
+ signal(SIGALRM, SIG_DFL);
+ return total;
+}
+
+main(void)
+{
+ long n[1001];
+ int speed_aligned, speed_unaligned;
+
+ if (test(access16, (char *) n + 1)) exit(1);
+ if (test(access32, (char *) n + 1)) exit(1);
+ if (test(access32, (char *) n + 2)) exit(1);
+ speed_aligned = speedtest((char *) n);
+ speed_unaligned = speedtest((char *) n + 1);
+ if (speed_aligned >= 3 * speed_unaligned) exit(1);
+ exit(0);
+}
diff --git a/config/auto-aux/ansi.c b/config/auto-aux/ansi.c
new file mode 100644
index 0000000000..a688509747
--- /dev/null
+++ b/config/auto-aux/ansi.c
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1997 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+int main()
+{
+#ifdef __STDC__
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+ return 0;
+#else
+ return 1;
+#endif
+#else
+ return 2;
+#endif
+}
diff --git a/config/auto-aux/async_io.c b/config/auto-aux/async_io.c
new file mode 100644
index 0000000000..3e2bb983a0
--- /dev/null
+++ b/config/auto-aux/async_io.c
@@ -0,0 +1,58 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include "s.h"
+
+int signalled;
+
+void sigio_handler(int arg)
+{
+ signalled = 1;
+}
+
+int main(void)
+{
+#if defined(SIGIO) && defined(FASYNC) && defined(F_SETFL) && defined(F_SETOWN)
+ int p[2];
+ int ret;
+#define OUT 0
+#define IN 1
+ if (socketpair(PF_UNIX, SOCK_STREAM, 0, p) == -1) return 1;
+ signalled = 0;
+ signal(SIGIO, sigio_handler);
+ ret = fcntl(p[OUT], F_GETFL, 0);
+ fcntl(p[OUT], F_SETFL, ret | FASYNC);
+ fcntl(p[OUT], F_SETOWN, getpid());
+ switch(fork()) {
+ case -1:
+ return 1;
+ case 0:
+ close(p[OUT]);
+ write(p[IN], "x", 1);
+ sleep(1);
+ exit(0);
+ default:
+ close(p[IN]);
+ while(wait(NULL) == -1 && errno == EINTR) /*nothing*/;
+ }
+ if (signalled) return 0; else return 1;
+#else
+ return 1;
+#endif
+}
diff --git a/config/auto-aux/cckind.c b/config/auto-aux/cckind.c
new file mode 100644
index 0000000000..2385a53bcb
--- /dev/null
+++ b/config/auto-aux/cckind.c
@@ -0,0 +1,28 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2015 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Determine vendor and version of C compiler */
+
+/* This file is to be preprocessed and its output examined. */
+/* It is not C source code to be executed. */
+/* This helps with cross-compilation. */
+
+#if defined(__INTEL_COMPILER)
+icc __INTEL_COMPILER
+#elif defined(__clang_major__) && defined(__clang_minor__)
+clang __clang_major __clang_minor__
+#elif defined(__GNUC__) && defined(__GNUC_MINOR__)
+gcc __GNUC__ __GNUC_MINOR__
+#else
+unknown
+#endif
diff --git a/config/auto-aux/cfi.S b/config/auto-aux/cfi.S
new file mode 100644
index 0000000000..acd052df0b
--- /dev/null
+++ b/config/auto-aux/cfi.S
@@ -0,0 +1,6 @@
+camlPervasives__loop_1128:
+ .file 1 "pervasives.ml"
+ .loc 1 193
+ .cfi_startproc
+ .cfi_adjust_cfa_offset 8
+ .cfi_endproc
diff --git a/config/auto-aux/dblalign.c b/config/auto-aux/dblalign.c
new file mode 100644
index 0000000000..f89c9b523a
--- /dev/null
+++ b/config/auto-aux/dblalign.c
@@ -0,0 +1,52 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <signal.h>
+#include <setjmp.h>
+
+volatile double foo;
+
+void access_double(volatile double *p)
+{
+ foo = *p;
+}
+
+jmp_buf failure;
+
+void sig_handler(int sig)
+{
+ longjmp(failure, 1);
+}
+
+int main(void)
+{
+ long n[10];
+ int res;
+ signal(SIGSEGV, sig_handler);
+#ifdef SIGBUS
+ signal(SIGBUS, sig_handler);
+#endif
+ if(setjmp(failure) == 0) {
+ access_double((volatile double *) n);
+ access_double((volatile double *) (n+1));
+ res = 0;
+ } else {
+ res = 1;
+ }
+ signal(SIGSEGV, SIG_DFL);
+#ifdef SIGBUS
+ signal(SIGBUS, SIG_DFL);
+#endif
+ return res;
+}
diff --git a/config/auto-aux/elf.c b/config/auto-aux/elf.c
new file mode 100644
index 0000000000..c7548ae4ad
--- /dev/null
+++ b/config/auto-aux/elf.c
@@ -0,0 +1,24 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1999 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+
+int main(int argc, char ** argv)
+{
+#ifdef __ELF__
+ printf("elf\n");
+#else
+ printf("aout\n");
+#endif
+ return 0;
+}
diff --git a/config/auto-aux/endian.c b/config/auto-aux/endian.c
new file mode 100644
index 0000000000..5dc623ab76
--- /dev/null
+++ b/config/auto-aux/endian.c
@@ -0,0 +1,40 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include "m.h"
+
+#ifndef ARCH_SIXTYFOUR
+long intval = 0x41424344L;
+char * bigendian = "ABCD";
+char * littleendian = "DCBA";
+#else
+long intval = 0x4142434445464748L;
+char * bigendian = "ABCDEFGH";
+char * littleendian = "HGFEDCBA";
+#endif
+
+int main(void)
+{
+ long n[2];
+ char * p;
+
+ n[0] = intval;
+ n[1] = 0;
+ p = (char *) n;
+ if (strcmp(p, bigendian) == 0)
+ return 0;
+ if (strcmp(p, littleendian) == 0)
+ return 1;
+ return 2;
+}
diff --git a/config/auto-aux/getgroups.c b/config/auto-aux/getgroups.c
new file mode 100644
index 0000000000..e3f73f52aa
--- /dev/null
+++ b/config/auto-aux/getgroups.c
@@ -0,0 +1,30 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <sys/types.h>
+#include <limits.h>
+
+#ifdef NGROUPS_MAX
+
+int main(void)
+{
+ int gidset[NGROUPS_MAX];
+ if (getgroups(NGROUPS_MAX, gidset) == -1) return 1;
+ return 0;
+}
+
+#else
+
+int main(void) { return 1; }
+
+#endif
diff --git a/config/auto-aux/gethostbyaddr.c b/config/auto-aux/gethostbyaddr.c
new file mode 100644
index 0000000000..f09d65a80b
--- /dev/null
+++ b/config/auto-aux/gethostbyaddr.c
@@ -0,0 +1,49 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef _REENTRANT
+/* This helps detection on Digital Unix... */
+#define _REENTRANT
+#endif
+
+#include <sys/types.h>
+#include <netdb.h>
+
+int main(int argc, char ** argv)
+{
+#if NUM_ARGS == 7
+ char * address;
+ int length;
+ int type;
+ struct hostent h;
+ char buffer[10];
+ int buflen;
+ int h_errnop;
+ struct hostent * hp;
+ hp = gethostbyaddr_r(address, length, type, &h,
+ buffer, buflen, &h_errnop);
+#elif NUM_ARGS == 8
+ char * address;
+ int length;
+ int type;
+ struct hostent h;
+ char buffer[10];
+ int buflen;
+ int h_errnop;
+ struct hostent * hp;
+ int rc;
+ rc = gethostbyaddr_r(address, length, type, &h,
+ buffer, buflen, &hp, &h_errnop);
+#endif
+ return 0;
+}
diff --git a/config/auto-aux/gethostbyname.c b/config/auto-aux/gethostbyname.c
new file mode 100644
index 0000000000..da52d89b4a
--- /dev/null
+++ b/config/auto-aux/gethostbyname.c
@@ -0,0 +1,39 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef _REENTRANT
+/* This helps detection on Digital Unix... */
+#define _REENTRANT
+#endif
+
+#include <sys/types.h>
+#include <netdb.h>
+
+int main(int argc, char ** argv)
+{
+#if NUM_ARGS == 5
+ struct hostent *hp;
+ struct hostent h;
+ char buffer[1000];
+ int h_errno;
+ hp = gethostbyname_r("www.caml.org", &h, buffer, 10, &h_errno);
+#elif NUM_ARGS == 6
+ struct hostent *hp;
+ struct hostent h;
+ char buffer[1000];
+ int h_errno;
+ int rc;
+ rc = gethostbyname_r("www.caml.org", &h, buffer, 10, &hp, &h_errno);
+#endif
+ return 0;
+}
diff --git a/config/auto-aux/hasgot b/config/auto-aux/hasgot
new file mode 100755
index 0000000000..384a2475b1
--- /dev/null
+++ b/config/auto-aux/hasgot
@@ -0,0 +1,42 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1995 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+opts=""
+libs="$cclibs"
+args=$*
+rm -f hasgot.c
+var="x"
+while : ; do
+ case "$1" in
+ -i) echo "#include <$2>" >> hasgot.c; shift;;
+ -t) echo "$2 $var;" >> hasgot.c; var="x$var"; shift;;
+ -l*|-L*|-F*) libs="$libs $1";;
+ -framework) libs="$libs $1 $2"; shift;;
+ -*) opts="$opts $1";;
+ *) break;;
+ esac
+ shift
+done
+
+(echo "int main() {"
+ for f in $*; do echo " $f();"; done
+ echo " return 0; }") >> hasgot.c
+
+if test "$verbose" = yes; then
+ echo "hasgot $args: $cc $opts -o tst hasgot.c $libs" >&2
+ exec $cc $opts -o tst hasgot.c $libs > /dev/null
+else
+ exec $cc $opts -o tst hasgot.c $libs > /dev/null 2>/dev/null
+fi
diff --git a/config/auto-aux/hasgot2 b/config/auto-aux/hasgot2
new file mode 100644
index 0000000000..ab969c6a8e
--- /dev/null
+++ b/config/auto-aux/hasgot2
@@ -0,0 +1,42 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2011 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+opts=""
+libs="$cclibs"
+args=$*
+rm -f hasgot.c
+var="x"
+while : ; do
+ case "$1" in
+ -i) echo "#include <$2>" >> hasgot.c; shift;;
+ -t) echo "$2 $var;" >> hasgot.c; var="x$var"; shift;;
+ -l*|-L*|-F*) libs="$libs $1";;
+ -framework) libs="$libs $1 $2"; shift;;
+ -*) opts="$opts $1";;
+ *) break;;
+ esac
+ shift
+done
+
+(echo "int main() {"
+ for f in $*; do echo " (void) & $f;"; done
+ echo " return 0; }") >> hasgot.c
+
+if test "$verbose" = yes; then
+ echo "hasgot2 $args: $cc $opts -o tst hasgot.c $libs" >&2
+ exec $cc $opts -o tst hasgot.c $libs > /dev/null
+else
+ exec $cc $opts -o tst hasgot.c $libs > /dev/null 2>/dev/null
+fi
diff --git a/config/auto-aux/ia32sse2.c b/config/auto-aux/ia32sse2.c
new file mode 100644
index 0000000000..47bafb60d6
--- /dev/null
+++ b/config/auto-aux/ia32sse2.c
@@ -0,0 +1,22 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Test whether IA32 assembler supports SSE2 instructions */
+
+int main()
+{
+ asm("pmuludq %mm1, %mm0");
+ asm("paddq %mm1, %mm0");
+ asm("psubq %mm1, %mm0");
+ return 0;
+}
diff --git a/config/auto-aux/initgroups.c b/config/auto-aux/initgroups.c
new file mode 100644
index 0000000000..0086e92a44
--- /dev/null
+++ b/config/auto-aux/initgroups.c
@@ -0,0 +1,24 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Stephane Glondu <steph@glondu.net> */
+/* */
+/* Copyright 2009 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+
+#include <sys/types.h>
+#include <limits.h>
+#include <grp.h>
+
+int main(void)
+{
+ if (initgroups("root", 0) == -1 && errno != EPERM) return 1;
+ return 0;
+}
diff --git a/config/auto-aux/int64align.c b/config/auto-aux/int64align.c
new file mode 100644
index 0000000000..d63d6f9192
--- /dev/null
+++ b/config/auto-aux/int64align.c
@@ -0,0 +1,63 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <signal.h>
+#include <setjmp.h>
+#include "m.h"
+
+#if defined(ARCH_INT64_TYPE)
+typedef ARCH_INT64_TYPE int64_t;
+#elif SIZEOF_LONG == 8
+typedef long int64_t;
+#elif SIZEOF_LONGLONG == 8
+typedef long long int64_t;
+#else
+#error "No 64-bit integer type available"
+#endif
+
+volatile int64_t foo;
+
+void access_int64(volatile int64_t *p)
+{
+ foo = *p;
+}
+
+jmp_buf failure;
+
+void sig_handler(int sig)
+{
+ longjmp(failure, 1);
+}
+
+int main(void)
+{
+ long n[10];
+ int res;
+ signal(SIGSEGV, sig_handler);
+#ifdef SIGBUS
+ signal(SIGBUS, sig_handler);
+#endif
+ if(setjmp(failure) == 0) {
+ access_int64((volatile int64_t *) n);
+ access_int64((volatile int64_t *) (n+1));
+ res = 0;
+ } else {
+ res = 1;
+ }
+ signal(SIGSEGV, SIG_DFL);
+#ifdef SIGBUS
+ signal(SIGBUS, SIG_DFL);
+#endif
+ return res;
+}
diff --git a/config/auto-aux/nanosecond_stat.c b/config/auto-aux/nanosecond_stat.c
new file mode 100644
index 0000000000..fc92e67b9c
--- /dev/null
+++ b/config/auto-aux/nanosecond_stat.c
@@ -0,0 +1,28 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Jeremie Dimino, Jane Street Group, LLC */
+/* */
+/* Copyright 2015 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#define _GNU_SOURCE
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "../../otherlibs/unix/nanosecond_stat.h"
+
+int main() {
+ struct stat *buf;
+ double a, m, c;
+ a = (double)NSEC(buf, a);
+ m = (double)NSEC(buf, m);
+ c = (double)NSEC(buf, c);
+ return 0;
+}
diff --git a/config/auto-aux/runtest b/config/auto-aux/runtest
new file mode 100755
index 0000000000..c8d7c435a4
--- /dev/null
+++ b/config/auto-aux/runtest
@@ -0,0 +1,22 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1995 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+if test "$verbose" = yes; then
+echo "runtest: $cc -o tst $* $cclibs" >&2
+$cc -o tst $* $cclibs || exit 100
+else
+$cc -o tst $* $cclibs 2> /dev/null || exit 100
+fi
+exec ./tst
diff --git a/config/auto-aux/searchpath b/config/auto-aux/searchpath
new file mode 100755
index 0000000000..e229ac921b
--- /dev/null
+++ b/config/auto-aux/searchpath
@@ -0,0 +1,32 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1996 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Find a program in the path
+
+doprint=false
+case $1 in
+ -p) shift; doprint=true;;
+ *) ;;
+esac
+
+IFS=':'
+for dir in $PATH; do
+ if test -z "$dir"; then dir=.; fi
+ if test -f $dir/$1 -a -x $dir/$1; then
+ if $doprint; then echo "$dir/$1"; fi
+ exit 0
+ fi
+done
+exit 1
diff --git a/config/auto-aux/setgroups.c b/config/auto-aux/setgroups.c
new file mode 100644
index 0000000000..4be3c1d7a6
--- /dev/null
+++ b/config/auto-aux/setgroups.c
@@ -0,0 +1,26 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Stephane Glondu <steph@glondu.net> */
+/* */
+/* Copyright 2009 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+
+#include <sys/types.h>
+#include <limits.h>
+#include <grp.h>
+
+int main(void)
+{
+ gid_t gidset[1];
+ gidset[0] = 0;
+ if (setgroups(1, gidset) == -1 && errno != EPERM) return 1;
+ return 0;
+}
diff --git a/config/auto-aux/sharpbang b/config/auto-aux/sharpbang
new file mode 100755
index 0000000000..eb447baa6e
--- /dev/null
+++ b/config/auto-aux/sharpbang
@@ -0,0 +1,2 @@
+#! /bin/cat
+exit 1
diff --git a/config/auto-aux/sharpbang2 b/config/auto-aux/sharpbang2
new file mode 100755
index 0000000000..3753096347
--- /dev/null
+++ b/config/auto-aux/sharpbang2
@@ -0,0 +1,2 @@
+#! /usr/bin/cat
+exit 1
diff --git a/config/auto-aux/signals.c b/config/auto-aux/signals.c
new file mode 100644
index 0000000000..ed84e98036
--- /dev/null
+++ b/config/auto-aux/signals.c
@@ -0,0 +1,66 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* To determine the semantics of signal handlers
+ (System V: signal is reset to default behavior on entrance to the handler
+ BSD: signal handler remains active). */
+
+#include <stdio.h>
+#include <signal.h>
+
+/* Find a signal that is ignored by default */
+
+#ifdef SIGCHLD
+#define IGNSIG SIGCHLD
+#else
+#ifdef SIGIO
+#define IGNSIG SIGIO
+#else
+#ifdef SIGCLD
+#define IGNSIG SIGCLD
+#else
+#ifdef SIGPWR
+#define IGNSIG SIGPWR
+#endif
+#endif
+#endif
+#endif
+
+#ifdef IGNSIG
+
+int counter;
+
+void sig_handler(int dummy)
+{
+ counter++;
+}
+
+int main(int argc, char **argv)
+{
+ signal(IGNSIG, sig_handler);
+ counter = 0;
+ kill(getpid(), IGNSIG);
+ kill(getpid(), IGNSIG);
+ return (counter == 2 ? 0 : 1);
+}
+
+#else
+
+/* If no suitable signal was found, assume System V */
+
+int main(int argc, char ** argv)
+{
+ return 1;
+}
+
+#endif
diff --git a/config/auto-aux/sizes.c b/config/auto-aux/sizes.c
new file mode 100644
index 0000000000..d756952f6c
--- /dev/null
+++ b/config/auto-aux/sizes.c
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+
+int main(int argc, char **argv)
+{
+ printf("%d %d %d %d %d\n",
+ (int) sizeof(int),
+ (int) sizeof(long),
+ (int) sizeof(long *),
+ (int) sizeof(short),
+ (int) sizeof(long long));
+ return 0;
+}
diff --git a/config/auto-aux/solaris-ld b/config/auto-aux/solaris-ld
new file mode 100644
index 0000000000..cc846a31b3
--- /dev/null
+++ b/config/auto-aux/solaris-ld
@@ -0,0 +1,21 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2001 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Determine if gcc calls the Solaris ld or the GNU ld
+# Exit code is 0 for Solaris ld, 1 for GNU ld
+
+echo "int main() { return 0; }" > hasgot.c
+$cc -v -o tst hasgot.c 2>&1 | grep -s '^ld:' > /dev/null
+exit $?
diff --git a/config/auto-aux/tryassemble b/config/auto-aux/tryassemble
new file mode 100644
index 0000000000..06b9b27c82
--- /dev/null
+++ b/config/auto-aux/tryassemble
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2012 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+if test "$verbose" = yes; then
+echo "tryassemble: $aspp -o tst $*" >&2
+$aspp -o tst $* || exit 100
+else
+$aspp -o tst $* 2> /dev/null || exit 100
+fi
+
+# test as also (if differs)
+if test "$aspp" != "$as"; then
+if test "$verbose" = yes; then
+echo "tryassemble: $as -o tst $*" >&2
+$as -o tst $* || exit 100
+else
+$as -o tst $* 2> /dev/null || exit 100
+fi
+fi
diff --git a/config/auto-aux/trycompile b/config/auto-aux/trycompile
new file mode 100755
index 0000000000..934a00a9b7
--- /dev/null
+++ b/config/auto-aux/trycompile
@@ -0,0 +1,21 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2002 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+if test "$verbose" = yes; then
+echo "trycompile: $cc -o tst $* $cclibs" >&2
+$cc -o tst $* $cclibs || exit 100
+else
+$cc -o tst $* $cclibs 2> /dev/null || exit 100
+fi
diff --git a/config/gnu/config.guess b/config/gnu/config.guess
new file mode 100755
index 0000000000..b79252d6b1
--- /dev/null
+++ b/config/gnu/config.guess
@@ -0,0 +1,1558 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+# Copyright 1992-2013 Free Software Foundation, Inc.
+
+timestamp='2013-06-10'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, see <http://www.gnu.org/licenses/>.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that
+# program. This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
+#
+# Originally written by Per Bothner.
+#
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+#
+# Please send patches with a ChangeLog entry to config-patches@gnu.org.
+
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright 1992-2013 Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit ;;
+ --version | -v )
+ echo "$version" ; exit ;;
+ --help | --h* | -h )
+ echo "$usage"; exit ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help" >&2
+ exit 1 ;;
+ * )
+ break ;;
+ esac
+done
+
+if test $# != 0; then
+ echo "$me: too many arguments$help" >&2
+ exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,) echo "int x;" > $dummy.c ;
+ for c in cc gcc c89 c99 ; do
+ if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+ CC_FOR_BUILD="$c"; break ;
+ fi ;
+ done ;
+ if test x"$CC_FOR_BUILD" = x ; then
+ CC_FOR_BUILD=no_compiler_found ;
+ fi
+ ;;
+ ,,*) CC_FOR_BUILD=$CC ;;
+ ,*,*) CC_FOR_BUILD=$HOST_CC ;;
+esac ; set_cc_for_build= ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi@noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+ PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+case "${UNAME_SYSTEM}" in
+Linux|GNU|GNU/*)
+ # If the system lacks a compiler, then just pick glibc.
+ # We could probably try harder.
+ LIBC=gnu
+
+ eval $set_cc_for_build
+ cat <<-EOF > $dummy.c
+ #include <features.h>
+ #if defined(__UCLIBC__)
+ LIBC=uclibc
+ #elif defined(__dietlibc__)
+ LIBC=dietlibc
+ #else
+ LIBC=gnu
+ #endif
+ EOF
+ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
+ ;;
+esac
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+ *:NetBSD:*:*)
+ # NetBSD (nbsd) targets should (where applicable) match one or
+ # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,
+ # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently
+ # switched to ELF, *-*-netbsd* would select the old
+ # object file format. This provides both forward
+ # compatibility and a consistent mechanism for selecting the
+ # object file format.
+ #
+ # Note: NetBSD doesn't particularly care about the vendor
+ # portion of the name. We always set it to "unknown".
+ sysctl="sysctl -n hw.machine_arch"
+ UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
+ /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+ case "${UNAME_MACHINE_ARCH}" in
+ armeb) machine=armeb-unknown ;;
+ arm*) machine=arm-unknown ;;
+ sh3el) machine=shl-unknown ;;
+ sh3eb) machine=sh-unknown ;;
+ sh5el) machine=sh5le-unknown ;;
+ *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+ esac
+ # The Operating System including object format, if it has switched
+ # to ELF recently, or will in the future.
+ case "${UNAME_MACHINE_ARCH}" in
+ arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+ eval $set_cc_for_build
+ if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ELF__
+ then
+ # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+ # Return netbsd for either. FIX?
+ os=netbsd
+ else
+ os=netbsdelf
+ fi
+ ;;
+ *)
+ os=netbsd
+ ;;
+ esac
+ # The OS release
+ # Debian GNU/NetBSD machines have a different userland, and
+ # thus, need a distinct triplet. However, they do not need
+ # kernel version information, so it can be replaced with a
+ # suitable tag, in the style of linux-gnu.
+ case "${UNAME_VERSION}" in
+ Debian*)
+ release='-gnu'
+ ;;
+ *)
+ release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+ ;;
+ esac
+ # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+ # contains redundant information, the shorter form:
+ # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+ echo "${machine}-${os}${release}"
+ exit ;;
+ *:Bitrig:*:*)
+ UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
+ echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE}
+ exit ;;
+ *:OpenBSD:*:*)
+ UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+ echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+ exit ;;
+ *:ekkoBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+ exit ;;
+ *:SolidBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+ exit ;;
+ macppc:MirBSD:*:*)
+ echo powerpc-unknown-mirbsd${UNAME_RELEASE}
+ exit ;;
+ *:MirBSD:*:*)
+ echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+ exit ;;
+ alpha:OSF1:*:*)
+ case $UNAME_RELEASE in
+ *4.0)
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+ ;;
+ *5.*)
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+ ;;
+ esac
+ # According to Compaq, /usr/sbin/psrinfo has been available on
+ # OSF/1 and Tru64 systems produced since 1995. I hope that
+ # covers most systems running today. This code pipes the CPU
+ # types through head -n 1, so we only detect the type of CPU 0.
+ ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+ case "$ALPHA_CPU_TYPE" in
+ "EV4 (21064)")
+ UNAME_MACHINE="alpha" ;;
+ "EV4.5 (21064)")
+ UNAME_MACHINE="alpha" ;;
+ "LCA4 (21066/21068)")
+ UNAME_MACHINE="alpha" ;;
+ "EV5 (21164)")
+ UNAME_MACHINE="alphaev5" ;;
+ "EV5.6 (21164A)")
+ UNAME_MACHINE="alphaev56" ;;
+ "EV5.6 (21164PC)")
+ UNAME_MACHINE="alphapca56" ;;
+ "EV5.7 (21164PC)")
+ UNAME_MACHINE="alphapca57" ;;
+ "EV6 (21264)")
+ UNAME_MACHINE="alphaev6" ;;
+ "EV6.7 (21264A)")
+ UNAME_MACHINE="alphaev67" ;;
+ "EV6.8CB (21264C)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.8AL (21264B)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.8CX (21264D)")
+ UNAME_MACHINE="alphaev68" ;;
+ "EV6.9A (21264/EV69A)")
+ UNAME_MACHINE="alphaev69" ;;
+ "EV7 (21364)")
+ UNAME_MACHINE="alphaev7" ;;
+ "EV7.9 (21364A)")
+ UNAME_MACHINE="alphaev79" ;;
+ esac
+ # A Pn.n version is a patched version.
+ # A Vn.n version is a released version.
+ # A Tn.n version is a released field test version.
+ # A Xn.n version is an unreleased experimental baselevel.
+ # 1.2 uses "1.2" for uname -r.
+ echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+ # Reset EXIT trap before exiting to avoid spurious non-zero exit code.
+ exitcode=$?
+ trap '' 0
+ exit $exitcode ;;
+ Alpha\ *:Windows_NT*:*)
+ # How do we know it's Interix rather than the generic POSIX subsystem?
+ # Should we change UNAME_MACHINE based on the output of uname instead
+ # of the specific Alpha model?
+ echo alpha-pc-interix
+ exit ;;
+ 21064:Windows_NT:50:3)
+ echo alpha-dec-winnt3.5
+ exit ;;
+ Amiga*:UNIX_System_V:4.0:*)
+ echo m68k-unknown-sysv4
+ exit ;;
+ *:[Aa]miga[Oo][Ss]:*:*)
+ echo ${UNAME_MACHINE}-unknown-amigaos
+ exit ;;
+ *:[Mm]orph[Oo][Ss]:*:*)
+ echo ${UNAME_MACHINE}-unknown-morphos
+ exit ;;
+ *:OS/390:*:*)
+ echo i370-ibm-openedition
+ exit ;;
+ *:z/VM:*:*)
+ echo s390-ibm-zvmoe
+ exit ;;
+ *:OS400:*:*)
+ echo powerpc-ibm-os400
+ exit ;;
+ arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+ echo arm-acorn-riscix${UNAME_RELEASE}
+ exit ;;
+ arm*:riscos:*:*|arm*:RISCOS:*:*)
+ echo arm-unknown-riscos
+ exit ;;
+ SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+ echo hppa1.1-hitachi-hiuxmpp
+ exit ;;
+ Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+ # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+ if test "`(/bin/universe) 2>/dev/null`" = att ; then
+ echo pyramid-pyramid-sysv3
+ else
+ echo pyramid-pyramid-bsd
+ fi
+ exit ;;
+ NILE*:*:*:dcosx)
+ echo pyramid-pyramid-svr4
+ exit ;;
+ DRS?6000:unix:4.0:6*)
+ echo sparc-icl-nx6
+ exit ;;
+ DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+ case `/usr/bin/uname -p` in
+ sparc) echo sparc-icl-nx7; exit ;;
+ esac ;;
+ s390x:SunOS:*:*)
+ echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4H:SunOS:5.*:*)
+ echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+ echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+ echo i386-pc-auroraux${UNAME_RELEASE}
+ exit ;;
+ i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+ eval $set_cc_for_build
+ SUN_ARCH="i386"
+ # If there is a compiler, see if it is configured for 64-bit objects.
+ # Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+ # This test works for both compilers.
+ if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+ if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+ grep IS_64BIT_ARCH >/dev/null
+ then
+ SUN_ARCH="x86_64"
+ fi
+ fi
+ echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:6*:*)
+ # According to config.sub, this is the proper way to canonicalize
+ # SunOS6. Hard to guess exactly what SunOS6 will be like, but
+ # it's likely to be more like Solaris than SunOS4.
+ echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ sun4*:SunOS:*:*)
+ case "`/usr/bin/arch -k`" in
+ Series*|S4*)
+ UNAME_RELEASE=`uname -v`
+ ;;
+ esac
+ # Japanese Language versions have a version number like `4.1.3-JL'.
+ echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+ exit ;;
+ sun3*:SunOS:*:*)
+ echo m68k-sun-sunos${UNAME_RELEASE}
+ exit ;;
+ sun*:*:4.2BSD:*)
+ UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+ test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+ case "`/bin/arch`" in
+ sun3)
+ echo m68k-sun-sunos${UNAME_RELEASE}
+ ;;
+ sun4)
+ echo sparc-sun-sunos${UNAME_RELEASE}
+ ;;
+ esac
+ exit ;;
+ aushp:SunOS:*:*)
+ echo sparc-auspex-sunos${UNAME_RELEASE}
+ exit ;;
+ # The situation for MiNT is a little confusing. The machine name
+ # can be virtually everything (everything which is not
+ # "atarist" or "atariste" at least should have a processor
+ # > m68000). The system name ranges from "MiNT" over "FreeMiNT"
+ # to the lowercase version "mint" (or "freemint"). Finally
+ # the system name "TOS" denotes a system which is actually not
+ # MiNT. But MiNT is downward compatible to TOS, so this should
+ # be no problem.
+ atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+ echo m68k-atari-mint${UNAME_RELEASE}
+ exit ;;
+ milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+ echo m68k-milan-mint${UNAME_RELEASE}
+ exit ;;
+ hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+ echo m68k-hades-mint${UNAME_RELEASE}
+ exit ;;
+ *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+ echo m68k-unknown-mint${UNAME_RELEASE}
+ exit ;;
+ m68k:machten:*:*)
+ echo m68k-apple-machten${UNAME_RELEASE}
+ exit ;;
+ powerpc:machten:*:*)
+ echo powerpc-apple-machten${UNAME_RELEASE}
+ exit ;;
+ RISC*:Mach:*:*)
+ echo mips-dec-mach_bsd4.3
+ exit ;;
+ RISC*:ULTRIX:*:*)
+ echo mips-dec-ultrix${UNAME_RELEASE}
+ exit ;;
+ VAX*:ULTRIX*:*:*)
+ echo vax-dec-ultrix${UNAME_RELEASE}
+ exit ;;
+ 2020:CLIX:*:* | 2430:CLIX:*:*)
+ echo clipper-intergraph-clix${UNAME_RELEASE}
+ exit ;;
+ mips:*:*:UMIPS | mips:*:*:RISCos)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h> /* for printf() prototype */
+ int main (int argc, char *argv[]) {
+#else
+ int main (argc, argv) int argc; char *argv[]; {
+#endif
+ #if defined (host_mips) && defined (MIPSEB)
+ #if defined (SYSTYPE_SYSV)
+ printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_SVR4)
+ printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+ printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+ #endif
+ #endif
+ exit (-1);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c &&
+ dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+ SYSTEM_NAME=`$dummy $dummyarg` &&
+ { echo "$SYSTEM_NAME"; exit; }
+ echo mips-mips-riscos${UNAME_RELEASE}
+ exit ;;
+ Motorola:PowerMAX_OS:*:*)
+ echo powerpc-motorola-powermax
+ exit ;;
+ Motorola:*:4.3:PL8-*)
+ echo powerpc-harris-powermax
+ exit ;;
+ Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+ echo powerpc-harris-powermax
+ exit ;;
+ Night_Hawk:Power_UNIX:*:*)
+ echo powerpc-harris-powerunix
+ exit ;;
+ m88k:CX/UX:7*:*)
+ echo m88k-harris-cxux7
+ exit ;;
+ m88k:*:4*:R4*)
+ echo m88k-motorola-sysv4
+ exit ;;
+ m88k:*:3*:R3*)
+ echo m88k-motorola-sysv3
+ exit ;;
+ AViiON:dgux:*:*)
+ # DG/UX returns AViiON for all architectures
+ UNAME_PROCESSOR=`/usr/bin/uname -p`
+ if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+ then
+ if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+ [ ${TARGET_BINARY_INTERFACE}x = x ]
+ then
+ echo m88k-dg-dgux${UNAME_RELEASE}
+ else
+ echo m88k-dg-dguxbcs${UNAME_RELEASE}
+ fi
+ else
+ echo i586-dg-dgux${UNAME_RELEASE}
+ fi
+ exit ;;
+ M88*:DolphinOS:*:*) # DolphinOS (SVR3)
+ echo m88k-dolphin-sysv3
+ exit ;;
+ M88*:*:R3*:*)
+ # Delta 88k system running SVR3
+ echo m88k-motorola-sysv3
+ exit ;;
+ XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+ echo m88k-tektronix-sysv3
+ exit ;;
+ Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+ echo m68k-tektronix-bsd
+ exit ;;
+ *:IRIX*:*:*)
+ echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+ exit ;;
+ ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+ echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id
+ exit ;; # Note that: echo "'`uname -s`'" gives 'AIX '
+ i*86:AIX:*:*)
+ echo i386-ibm-aix
+ exit ;;
+ ia64:AIX:*:*)
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+ fi
+ echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+ exit ;;
+ *:AIX:2:3)
+ if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <sys/systemcfg.h>
+
+ main()
+ {
+ if (!__power_pc())
+ exit(1);
+ puts("powerpc-ibm-aix3.2.5");
+ exit(0);
+ }
+EOF
+ if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+ then
+ echo "$SYSTEM_NAME"
+ else
+ echo rs6000-ibm-aix3.2.5
+ fi
+ elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+ echo rs6000-ibm-aix3.2.4
+ else
+ echo rs6000-ibm-aix3.2
+ fi
+ exit ;;
+ *:AIX:*:[4567])
+ IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+ if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+ IBM_ARCH=rs6000
+ else
+ IBM_ARCH=powerpc
+ fi
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+ fi
+ echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+ exit ;;
+ *:AIX:*:*)
+ echo rs6000-ibm-aix
+ exit ;;
+ ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+ echo romp-ibm-bsd4.4
+ exit ;;
+ ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
+ echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to
+ exit ;; # report: romp-ibm BSD 4.3
+ *:BOSX:*:*)
+ echo rs6000-bull-bosx
+ exit ;;
+ DPX/2?00:B.O.S.:*:*)
+ echo m68k-bull-sysv3
+ exit ;;
+ 9000/[34]??:4.3bsd:1.*:*)
+ echo m68k-hp-bsd
+ exit ;;
+ hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+ echo m68k-hp-bsd4.4
+ exit ;;
+ 9000/[34678]??:HP-UX:*:*)
+ HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+ case "${UNAME_MACHINE}" in
+ 9000/31? ) HP_ARCH=m68000 ;;
+ 9000/[34]?? ) HP_ARCH=m68k ;;
+ 9000/[678][0-9][0-9])
+ if [ -x /usr/bin/getconf ]; then
+ sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+ sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+ case "${sc_cpu_version}" in
+ 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+ 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+ 532) # CPU_PA_RISC2_0
+ case "${sc_kernel_bits}" in
+ 32) HP_ARCH="hppa2.0n" ;;
+ 64) HP_ARCH="hppa2.0w" ;;
+ '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20
+ esac ;;
+ esac
+ fi
+ if [ "${HP_ARCH}" = "" ]; then
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+
+ #define _HPUX_SOURCE
+ #include <stdlib.h>
+ #include <unistd.h>
+
+ int main ()
+ {
+ #if defined(_SC_KERNEL_BITS)
+ long bits = sysconf(_SC_KERNEL_BITS);
+ #endif
+ long cpu = sysconf (_SC_CPU_VERSION);
+
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+ case CPU_PA_RISC2_0:
+ #if defined(_SC_KERNEL_BITS)
+ switch (bits)
+ {
+ case 64: puts ("hppa2.0w"); break;
+ case 32: puts ("hppa2.0n"); break;
+ default: puts ("hppa2.0"); break;
+ } break;
+ #else /* !defined(_SC_KERNEL_BITS) */
+ puts ("hppa2.0"); break;
+ #endif
+ default: puts ("hppa1.0"); break;
+ }
+ exit (0);
+ }
+EOF
+ (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+ test -z "$HP_ARCH" && HP_ARCH=hppa
+ fi ;;
+ esac
+ if [ ${HP_ARCH} = "hppa2.0w" ]
+ then
+ eval $set_cc_for_build
+
+ # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+ # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler
+ # generating 64-bit code. GNU and HP use different nomenclature:
+ #
+ # $ CC_FOR_BUILD=cc ./config.guess
+ # => hppa2.0w-hp-hpux11.23
+ # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+ # => hppa64-hp-hpux11.23
+
+ if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+ grep -q __LP64__
+ then
+ HP_ARCH="hppa2.0w"
+ else
+ HP_ARCH="hppa64"
+ fi
+ fi
+ echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+ exit ;;
+ ia64:HP-UX:*:*)
+ HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+ echo ia64-hp-hpux${HPUX_REV}
+ exit ;;
+ 3050*:HI-UX:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #include <unistd.h>
+ int
+ main ()
+ {
+ long cpu = sysconf (_SC_CPU_VERSION);
+ /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+ true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct
+ results, however. */
+ if (CPU_IS_PA_RISC (cpu))
+ {
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+ default: puts ("hppa-hitachi-hiuxwe2"); break;
+ }
+ }
+ else if (CPU_IS_HP_MC68K (cpu))
+ puts ("m68k-hitachi-hiuxwe2");
+ else puts ("unknown-hitachi-hiuxwe2");
+ exit (0);
+ }
+EOF
+ $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+ { echo "$SYSTEM_NAME"; exit; }
+ echo unknown-hitachi-hiuxwe2
+ exit ;;
+ 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+ echo hppa1.1-hp-bsd
+ exit ;;
+ 9000/8??:4.3bsd:*:*)
+ echo hppa1.0-hp-bsd
+ exit ;;
+ *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+ echo hppa1.0-hp-mpeix
+ exit ;;
+ hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+ echo hppa1.1-hp-osf
+ exit ;;
+ hp8??:OSF1:*:*)
+ echo hppa1.0-hp-osf
+ exit ;;
+ i*86:OSF1:*:*)
+ if [ -x /usr/sbin/sysversion ] ; then
+ echo ${UNAME_MACHINE}-unknown-osf1mk
+ else
+ echo ${UNAME_MACHINE}-unknown-osf1
+ fi
+ exit ;;
+ parisc*:Lites*:*:*)
+ echo hppa1.1-hp-lites
+ exit ;;
+ C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+ echo c1-convex-bsd
+ exit ;;
+ C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit ;;
+ C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+ echo c34-convex-bsd
+ exit ;;
+ C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+ echo c38-convex-bsd
+ exit ;;
+ C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+ echo c4-convex-bsd
+ exit ;;
+ CRAY*Y-MP:*:*:*)
+ echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*[A-Z]90:*:*:*)
+ echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+ -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*TS:*:*:*)
+ echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*T3E:*:*:*)
+ echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*SV1:*:*:*)
+ echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ *:UNICOS/mp:*:*)
+ echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+ FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+ FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+ FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+ echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit ;;
+ 5000:UNIX_System_V:4.*:*)
+ FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+ FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+ echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit ;;
+ i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+ echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+ exit ;;
+ sparc*:BSD/OS:*:*)
+ echo sparc-unknown-bsdi${UNAME_RELEASE}
+ exit ;;
+ *:BSD/OS:*:*)
+ echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+ exit ;;
+ *:FreeBSD:*:*)
+ UNAME_PROCESSOR=`/usr/bin/uname -p`
+ case ${UNAME_PROCESSOR} in
+ amd64)
+ echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+ *)
+ echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+ esac
+ exit ;;
+ i*:CYGWIN*:*)
+ echo ${UNAME_MACHINE}-pc-cygwin
+ exit ;;
+ *:MINGW64*:*)
+ echo ${UNAME_MACHINE}-pc-mingw64
+ exit ;;
+ *:MINGW*:*)
+ echo ${UNAME_MACHINE}-pc-mingw32
+ exit ;;
+ i*:MSYS*:*)
+ echo ${UNAME_MACHINE}-pc-msys
+ exit ;;
+ i*:windows32*:*)
+ # uname -m includes "-pc" on this system.
+ echo ${UNAME_MACHINE}-mingw32
+ exit ;;
+ i*:PW*:*)
+ echo ${UNAME_MACHINE}-pc-pw32
+ exit ;;
+ *:Interix*:*)
+ case ${UNAME_MACHINE} in
+ x86)
+ echo i586-pc-interix${UNAME_RELEASE}
+ exit ;;
+ authenticamd | genuineintel | EM64T)
+ echo x86_64-unknown-interix${UNAME_RELEASE}
+ exit ;;
+ IA64)
+ echo ia64-unknown-interix${UNAME_RELEASE}
+ exit ;;
+ esac ;;
+ [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+ echo i${UNAME_MACHINE}-pc-mks
+ exit ;;
+ 8664:Windows_NT:*)
+ echo x86_64-pc-mks
+ exit ;;
+ i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+ # How do we know it's Interix rather than the generic POSIX subsystem?
+ # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+ # UNAME_MACHINE based on the output of uname instead of i386?
+ echo i586-pc-interix
+ exit ;;
+ i*:UWIN*:*)
+ echo ${UNAME_MACHINE}-pc-uwin
+ exit ;;
+ amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+ echo x86_64-unknown-cygwin
+ exit ;;
+ p*:CYGWIN*:*)
+ echo powerpcle-unknown-cygwin
+ exit ;;
+ prep*:SunOS:5.*:*)
+ echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+ exit ;;
+ *:GNU:*:*)
+ # the GNU system
+ echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+ exit ;;
+ *:GNU/*:*:*)
+ # other systems with GNU libc and userland
+ echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
+ exit ;;
+ i*86:Minix:*:*)
+ echo ${UNAME_MACHINE}-pc-minix
+ exit ;;
+ aarch64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ aarch64_be:Linux:*:*)
+ UNAME_MACHINE=aarch64_be
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ alpha:Linux:*:*)
+ case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+ EV5) UNAME_MACHINE=alphaev5 ;;
+ EV56) UNAME_MACHINE=alphaev56 ;;
+ PCA56) UNAME_MACHINE=alphapca56 ;;
+ PCA57) UNAME_MACHINE=alphapca56 ;;
+ EV6) UNAME_MACHINE=alphaev6 ;;
+ EV67) UNAME_MACHINE=alphaev67 ;;
+ EV68*) UNAME_MACHINE=alphaev68 ;;
+ esac
+ objdump --private-headers /bin/sh | grep -q ld.so.1
+ if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ arc:Linux:*:* | arceb:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ arm*:Linux:*:*)
+ eval $set_cc_for_build
+ if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ARM_EABI__
+ then
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ else
+ if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ARM_PCS_VFP
+ then
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
+ else
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
+ fi
+ fi
+ exit ;;
+ avr32*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ cris:Linux:*:*)
+ echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+ exit ;;
+ crisv32:Linux:*:*)
+ echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+ exit ;;
+ frv:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ hexagon:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ i*86:Linux:*:*)
+ echo ${UNAME_MACHINE}-pc-linux-${LIBC}
+ exit ;;
+ ia64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ m32r*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ m68*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ mips:Linux:*:* | mips64:Linux:*:*)
+ eval $set_cc_for_build
+ sed 's/^ //' << EOF >$dummy.c
+ #undef CPU
+ #undef ${UNAME_MACHINE}
+ #undef ${UNAME_MACHINE}el
+ #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+ CPU=${UNAME_MACHINE}el
+ #else
+ #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+ CPU=${UNAME_MACHINE}
+ #else
+ CPU=
+ #endif
+ #endif
+EOF
+ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
+ test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
+ ;;
+ or1k:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ or32:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ padre:Linux:*:*)
+ echo sparc-unknown-linux-${LIBC}
+ exit ;;
+ parisc64:Linux:*:* | hppa64:Linux:*:*)
+ echo hppa64-unknown-linux-${LIBC}
+ exit ;;
+ parisc:Linux:*:* | hppa:Linux:*:*)
+ # Look for CPU level
+ case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+ PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
+ PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
+ *) echo hppa-unknown-linux-${LIBC} ;;
+ esac
+ exit ;;
+ ppc64:Linux:*:*)
+ echo powerpc64-unknown-linux-${LIBC}
+ exit ;;
+ ppc:Linux:*:*)
+ echo powerpc-unknown-linux-${LIBC}
+ exit ;;
+ ppc64le:Linux:*:*)
+ echo powerpc64le-unknown-linux-${LIBC}
+ exit ;;
+ ppcle:Linux:*:*)
+ echo powerpcle-unknown-linux-${LIBC}
+ exit ;;
+ s390:Linux:*:* | s390x:Linux:*:*)
+ echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
+ exit ;;
+ sh64*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ sh*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ sparc:Linux:*:* | sparc64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ tile*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ vax:Linux:*:*)
+ echo ${UNAME_MACHINE}-dec-linux-${LIBC}
+ exit ;;
+ x86_64:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ xtensa*:Linux:*:*)
+ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+ exit ;;
+ i*86:DYNIX/ptx:4*:*)
+ # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+ # earlier versions are messed up and put the nodename in both
+ # sysname and nodename.
+ echo i386-sequent-sysv4
+ exit ;;
+ i*86:UNIX_SV:4.2MP:2.*)
+ # Unixware is an offshoot of SVR4, but it has its own version
+ # number series starting with 2...
+ # I am not positive that other SVR4 systems won't match this,
+ # I just have to hope. -- rms.
+ # Use sysv4.2uw... so that sysv4* matches it.
+ echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+ exit ;;
+ i*86:OS/2:*:*)
+ # If we were able to find `uname', then EMX Unix compatibility
+ # is probably installed.
+ echo ${UNAME_MACHINE}-pc-os2-emx
+ exit ;;
+ i*86:XTS-300:*:STOP)
+ echo ${UNAME_MACHINE}-unknown-stop
+ exit ;;
+ i*86:atheos:*:*)
+ echo ${UNAME_MACHINE}-unknown-atheos
+ exit ;;
+ i*86:syllable:*:*)
+ echo ${UNAME_MACHINE}-pc-syllable
+ exit ;;
+ i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
+ echo i386-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ i*86:*DOS:*:*)
+ echo ${UNAME_MACHINE}-pc-msdosdjgpp
+ exit ;;
+ i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+ UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+ if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+ echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+ else
+ echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+ fi
+ exit ;;
+ i*86:*:5:[678]*)
+ # UnixWare 7.x, OpenUNIX and OpenServer 6.
+ case `/bin/uname -X | grep "^Machine"` in
+ *486*) UNAME_MACHINE=i486 ;;
+ *Pentium) UNAME_MACHINE=i586 ;;
+ *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+ esac
+ echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+ exit ;;
+ i*86:*:3.2:*)
+ if test -f /usr/options/cb.name; then
+ UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+ echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+ elif /bin/uname -X 2>/dev/null >/dev/null ; then
+ UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+ (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+ (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+ && UNAME_MACHINE=i586
+ (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+ && UNAME_MACHINE=i686
+ (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+ && UNAME_MACHINE=i686
+ echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+ else
+ echo ${UNAME_MACHINE}-pc-sysv32
+ fi
+ exit ;;
+ pc:*:*:*)
+ # Left here for compatibility:
+ # uname -m prints for DJGPP always 'pc', but it prints nothing about
+ # the processor, so we play safe by assuming i586.
+ # Note: whatever this is, it MUST be the same as what config.sub
+ # prints for the "djgpp" host, or else GDB configury will decide that
+ # this is a cross-build.
+ echo i586-pc-msdosdjgpp
+ exit ;;
+ Intel:Mach:3*:*)
+ echo i386-pc-mach3
+ exit ;;
+ paragon:*:*:*)
+ echo i860-intel-osf1
+ exit ;;
+ i860:*:4.*:*) # i860-SVR4
+ if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+ echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+ else # Add other i860-SVR4 vendors below as they are discovered.
+ echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4
+ fi
+ exit ;;
+ mini*:CTIX:SYS*5:*)
+ # "miniframe"
+ echo m68010-convergent-sysv
+ exit ;;
+ mc68k:UNIX:SYSTEM5:3.51m)
+ echo m68k-convergent-sysv
+ exit ;;
+ M680?0:D-NIX:5.3:*)
+ echo m68k-diab-dnix
+ exit ;;
+ M68*:*:R3V[5678]*:*)
+ test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+ 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+ OS_REL=''
+ test -r /etc/.relid \
+ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+ 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4; exit; } ;;
+ NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+ OS_REL='.3'
+ test -r /etc/.relid \
+ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+ && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+ m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+ echo m68k-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ mc68030:UNIX_System_V:4.*:*)
+ echo m68k-atari-sysv4
+ exit ;;
+ TSUNAMI:LynxOS:2.*:*)
+ echo sparc-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ rs6000:LynxOS:2.*:*)
+ echo rs6000-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
+ echo powerpc-unknown-lynxos${UNAME_RELEASE}
+ exit ;;
+ SM[BE]S:UNIX_SV:*:*)
+ echo mips-dde-sysv${UNAME_RELEASE}
+ exit ;;
+ RM*:ReliantUNIX-*:*:*)
+ echo mips-sni-sysv4
+ exit ;;
+ RM*:SINIX-*:*:*)
+ echo mips-sni-sysv4
+ exit ;;
+ *:SINIX-*:*:*)
+ if uname -p 2>/dev/null >/dev/null ; then
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ echo ${UNAME_MACHINE}-sni-sysv4
+ else
+ echo ns32k-sni-sysv
+ fi
+ exit ;;
+ PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+ # says <Richard.M.Bartel@ccMail.Census.GOV>
+ echo i586-unisys-sysv4
+ exit ;;
+ *:UNIX_System_V:4*:FTX*)
+ # From Gerald Hewes <hewes@openmarket.com>.
+ # How about differentiating between stratus architectures? -djm
+ echo hppa1.1-stratus-sysv4
+ exit ;;
+ *:*:*:FTX*)
+ # From seanf@swdc.stratus.com.
+ echo i860-stratus-sysv4
+ exit ;;
+ i*86:VOS:*:*)
+ # From Paul.Green@stratus.com.
+ echo ${UNAME_MACHINE}-stratus-vos
+ exit ;;
+ *:VOS:*:*)
+ # From Paul.Green@stratus.com.
+ echo hppa1.1-stratus-vos
+ exit ;;
+ mc68*:A/UX:*:*)
+ echo m68k-apple-aux${UNAME_RELEASE}
+ exit ;;
+ news*:NEWS-OS:6*:*)
+ echo mips-sony-newsos6
+ exit ;;
+ R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+ if [ -d /usr/nec ]; then
+ echo mips-nec-sysv${UNAME_RELEASE}
+ else
+ echo mips-unknown-sysv${UNAME_RELEASE}
+ fi
+ exit ;;
+ BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
+ echo powerpc-be-beos
+ exit ;;
+ BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
+ echo powerpc-apple-beos
+ exit ;;
+ BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
+ echo i586-pc-beos
+ exit ;;
+ BePC:Haiku:*:*) # Haiku running on Intel PC compatible.
+ echo i586-pc-haiku
+ exit ;;
+ x86_64:Haiku:*:*)
+ echo x86_64-unknown-haiku
+ exit ;;
+ SX-4:SUPER-UX:*:*)
+ echo sx4-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-5:SUPER-UX:*:*)
+ echo sx5-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-6:SUPER-UX:*:*)
+ echo sx6-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-7:SUPER-UX:*:*)
+ echo sx7-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-8:SUPER-UX:*:*)
+ echo sx8-nec-superux${UNAME_RELEASE}
+ exit ;;
+ SX-8R:SUPER-UX:*:*)
+ echo sx8r-nec-superux${UNAME_RELEASE}
+ exit ;;
+ Power*:Rhapsody:*:*)
+ echo powerpc-apple-rhapsody${UNAME_RELEASE}
+ exit ;;
+ *:Rhapsody:*:*)
+ echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+ exit ;;
+ *:Darwin:*:*)
+ UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+ eval $set_cc_for_build
+ if test "$UNAME_PROCESSOR" = unknown ; then
+ UNAME_PROCESSOR=powerpc
+ fi
+ if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+ if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+ grep IS_64BIT_ARCH >/dev/null
+ then
+ case $UNAME_PROCESSOR in
+ i386) UNAME_PROCESSOR=x86_64 ;;
+ powerpc) UNAME_PROCESSOR=powerpc64 ;;
+ esac
+ fi
+ fi
+ echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+ exit ;;
+ *:procnto*:*:* | *:QNX:[0123456789]*:*)
+ UNAME_PROCESSOR=`uname -p`
+ if test "$UNAME_PROCESSOR" = "x86"; then
+ UNAME_PROCESSOR=i386
+ UNAME_MACHINE=pc
+ fi
+ echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+ exit ;;
+ *:QNX:*:4*)
+ echo i386-pc-qnx
+ exit ;;
+ NEO-?:NONSTOP_KERNEL:*:*)
+ echo neo-tandem-nsk${UNAME_RELEASE}
+ exit ;;
+ NSE-*:NONSTOP_KERNEL:*:*)
+ echo nse-tandem-nsk${UNAME_RELEASE}
+ exit ;;
+ NSR-?:NONSTOP_KERNEL:*:*)
+ echo nsr-tandem-nsk${UNAME_RELEASE}
+ exit ;;
+ *:NonStop-UX:*:*)
+ echo mips-compaq-nonstopux
+ exit ;;
+ BS2000:POSIX*:*:*)
+ echo bs2000-siemens-sysv
+ exit ;;
+ DS/*:UNIX_System_V:*:*)
+ echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+ exit ;;
+ *:Plan9:*:*)
+ # "uname -m" is not consistent, so use $cputype instead. 386
+ # is converted to i386 for consistency with other x86
+ # operating systems.
+ if test "$cputype" = "386"; then
+ UNAME_MACHINE=i386
+ else
+ UNAME_MACHINE="$cputype"
+ fi
+ echo ${UNAME_MACHINE}-unknown-plan9
+ exit ;;
+ *:TOPS-10:*:*)
+ echo pdp10-unknown-tops10
+ exit ;;
+ *:TENEX:*:*)
+ echo pdp10-unknown-tenex
+ exit ;;
+ KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+ echo pdp10-dec-tops20
+ exit ;;
+ XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+ echo pdp10-xkl-tops20
+ exit ;;
+ *:TOPS-20:*:*)
+ echo pdp10-unknown-tops20
+ exit ;;
+ *:ITS:*:*)
+ echo pdp10-unknown-its
+ exit ;;
+ SEI:*:*:SEIUX)
+ echo mips-sei-seiux${UNAME_RELEASE}
+ exit ;;
+ *:DragonFly:*:*)
+ echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+ exit ;;
+ *:*VMS:*:*)
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ case "${UNAME_MACHINE}" in
+ A*) echo alpha-dec-vms ; exit ;;
+ I*) echo ia64-dec-vms ; exit ;;
+ V*) echo vax-dec-vms ; exit ;;
+ esac ;;
+ *:XENIX:*:SysV)
+ echo i386-pc-xenix
+ exit ;;
+ i*86:skyos:*:*)
+ echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+ exit ;;
+ i*86:rdos:*:*)
+ echo ${UNAME_MACHINE}-pc-rdos
+ exit ;;
+ i*86:AROS:*:*)
+ echo ${UNAME_MACHINE}-pc-aros
+ exit ;;
+ x86_64:VMkernel:*:*)
+ echo ${UNAME_MACHINE}-unknown-esx
+ exit ;;
+esac
+
+eval $set_cc_for_build
+cat >$dummy.c <<EOF
+#ifdef _SEQUENT_
+# include <sys/types.h>
+# include <sys/utsname.h>
+#endif
+main ()
+{
+#if defined (sony)
+#if defined (MIPSEB)
+ /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed,
+ I don't know.... */
+ printf ("mips-sony-bsd\n"); exit (0);
+#else
+#include <sys/param.h>
+ printf ("m68k-sony-newsos%s\n",
+#ifdef NEWSOS4
+ "4"
+#else
+ ""
+#endif
+ ); exit (0);
+#endif
+#endif
+
+#if defined (__arm) && defined (__acorn) && defined (__unix)
+ printf ("arm-acorn-riscix\n"); exit (0);
+#endif
+
+#if defined (hp300) && !defined (hpux)
+ printf ("m68k-hp-bsd\n"); exit (0);
+#endif
+
+#if defined (NeXT)
+#if !defined (__ARCHITECTURE__)
+#define __ARCHITECTURE__ "m68k"
+#endif
+ int version;
+ version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
+ if (version < 4)
+ printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
+ else
+ printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
+ exit (0);
+#endif
+
+#if defined (MULTIMAX) || defined (n16)
+#if defined (UMAXV)
+ printf ("ns32k-encore-sysv\n"); exit (0);
+#else
+#if defined (CMU)
+ printf ("ns32k-encore-mach\n"); exit (0);
+#else
+ printf ("ns32k-encore-bsd\n"); exit (0);
+#endif
+#endif
+#endif
+
+#if defined (__386BSD__)
+ printf ("i386-pc-bsd\n"); exit (0);
+#endif
+
+#if defined (sequent)
+#if defined (i386)
+ printf ("i386-sequent-dynix\n"); exit (0);
+#endif
+#if defined (ns32000)
+ printf ("ns32k-sequent-dynix\n"); exit (0);
+#endif
+#endif
+
+#if defined (_SEQUENT_)
+ struct utsname un;
+
+ uname(&un);
+
+ if (strncmp(un.version, "V2", 2) == 0) {
+ printf ("i386-sequent-ptx2\n"); exit (0);
+ }
+ if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
+ printf ("i386-sequent-ptx1\n"); exit (0);
+ }
+ printf ("i386-sequent-ptx\n"); exit (0);
+
+#endif
+
+#if defined (vax)
+# if !defined (ultrix)
+# include <sys/param.h>
+# if defined (BSD)
+# if BSD == 43
+ printf ("vax-dec-bsd4.3\n"); exit (0);
+# else
+# if BSD == 199006
+ printf ("vax-dec-bsd4.3reno\n"); exit (0);
+# else
+ printf ("vax-dec-bsd\n"); exit (0);
+# endif
+# endif
+# else
+ printf ("vax-dec-bsd\n"); exit (0);
+# endif
+# else
+ printf ("vax-dec-ultrix\n"); exit (0);
+# endif
+#endif
+
+#if defined (alliant) && defined (i860)
+ printf ("i860-alliant-bsd\n"); exit (0);
+#endif
+
+ exit (1);
+}
+EOF
+
+$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` &&
+ { echo "$SYSTEM_NAME"; exit; }
+
+# Apollos put the system type in the environment.
+
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; }
+
+# Convex versions that predate uname can use getsysinfo(1)
+
+if [ -x /usr/convex/getsysinfo ]
+then
+ case `getsysinfo -f cpu_type` in
+ c1*)
+ echo c1-convex-bsd
+ exit ;;
+ c2*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit ;;
+ c34*)
+ echo c34-convex-bsd
+ exit ;;
+ c38*)
+ echo c38-convex-bsd
+ exit ;;
+ c4*)
+ echo c4-convex-bsd
+ exit ;;
+ esac
+fi
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+ http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+and
+ http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches@gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo = `(hostinfo) 2>/dev/null`
+/bin/universe = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/config/gnu/config.sub b/config/gnu/config.sub
new file mode 100755
index 0000000000..8b612ab89d
--- /dev/null
+++ b/config/gnu/config.sub
@@ -0,0 +1,1788 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+# Copyright 1992-2013 Free Software Foundation, Inc.
+
+timestamp='2013-04-24'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, see <http://www.gnu.org/licenses/>.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that
+# program. This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
+
+
+# Please send patches with a ChangeLog entry to config-patches@gnu.org.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support. The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+ $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright 1992-2013 Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit ;;
+ --version | -v )
+ echo "$version" ; exit ;;
+ --help | --h* | -h )
+ echo "$usage"; exit ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help"
+ exit 1 ;;
+
+ *local*)
+ # First pass through any local machine types.
+ echo $1
+ exit ;;
+
+ * )
+ break ;;
+ esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+ exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+ exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+ nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
+ linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
+ knetbsd*-gnu* | netbsd*-gnu* | \
+ kopensolaris*-gnu* | \
+ storm-chaos* | os2-emx* | rtmk-nova*)
+ os=-$maybe_os
+ basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+ ;;
+ android-linux)
+ os=-linux-android
+ basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
+ ;;
+ *)
+ basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+ if [ $basic_machine != $1 ]
+ then os=`echo $1 | sed 's/.*-/-/'`
+ else os=; fi
+ ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work. We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+ -sun*os*)
+ # Prevent following clause from handling this invalid input.
+ ;;
+ -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+ -apple | -axis | -knuth | -cray | -microblaze*)
+ os=
+ basic_machine=$1
+ ;;
+ -bluegene*)
+ os=-cnk
+ ;;
+ -sim | -cisco | -oki | -wec | -winbond)
+ os=
+ basic_machine=$1
+ ;;
+ -scout)
+ ;;
+ -wrs)
+ os=-vxworks
+ basic_machine=$1
+ ;;
+ -chorusos*)
+ os=-chorusos
+ basic_machine=$1
+ ;;
+ -chorusrdb)
+ os=-chorusrdb
+ basic_machine=$1
+ ;;
+ -hiux*)
+ os=-hiuxwe2
+ ;;
+ -sco6)
+ os=-sco5v6
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco5)
+ os=-sco3.2v5
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco4)
+ os=-sco3.2v4
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2.[4-9]*)
+ os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2v[4-9]*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco5v6*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco*)
+ os=-sco3.2v2
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -udk*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -isc)
+ os=-isc2.2
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -clix*)
+ basic_machine=clipper-intergraph
+ ;;
+ -isc*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -lynx*178)
+ os=-lynxos178
+ ;;
+ -lynx*5)
+ os=-lynxos5
+ ;;
+ -lynx*)
+ os=-lynxos
+ ;;
+ -ptx*)
+ basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+ ;;
+ -windowsnt*)
+ os=`echo $os | sed -e 's/windowsnt/winnt/'`
+ ;;
+ -psos*)
+ os=-psos
+ ;;
+ -mint | -mint[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+ # Recognize the basic CPU types without company name.
+ # Some are omitted here because they have special meanings below.
+ 1750a | 580 \
+ | a29k \
+ | aarch64 | aarch64_be \
+ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+ | am33_2.0 \
+ | arc | arceb \
+ | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
+ | avr | avr32 \
+ | be32 | be64 \
+ | bfin \
+ | c4x | clipper \
+ | d10v | d30v | dlx | dsp16xx \
+ | epiphany \
+ | fido | fr30 | frv \
+ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+ | hexagon \
+ | i370 | i860 | i960 | ia64 \
+ | ip2k | iq2000 \
+ | le32 | le64 \
+ | lm32 \
+ | m32c | m32r | m32rle | m68000 | m68k | m88k \
+ | maxq | mb | microblaze | microblazeel | mcore | mep | metag \
+ | mips | mipsbe | mipseb | mipsel | mipsle \
+ | mips16 \
+ | mips64 | mips64el \
+ | mips64octeon | mips64octeonel \
+ | mips64orion | mips64orionel \
+ | mips64r5900 | mips64r5900el \
+ | mips64vr | mips64vrel \
+ | mips64vr4100 | mips64vr4100el \
+ | mips64vr4300 | mips64vr4300el \
+ | mips64vr5000 | mips64vr5000el \
+ | mips64vr5900 | mips64vr5900el \
+ | mipsisa32 | mipsisa32el \
+ | mipsisa32r2 | mipsisa32r2el \
+ | mipsisa64 | mipsisa64el \
+ | mipsisa64r2 | mipsisa64r2el \
+ | mipsisa64sb1 | mipsisa64sb1el \
+ | mipsisa64sr71k | mipsisa64sr71kel \
+ | mipsr5900 | mipsr5900el \
+ | mipstx39 | mipstx39el \
+ | mn10200 | mn10300 \
+ | moxie \
+ | mt \
+ | msp430 \
+ | nds32 | nds32le | nds32be \
+ | nios | nios2 | nios2eb | nios2el \
+ | ns16k | ns32k \
+ | open8 \
+ | or1k | or32 \
+ | pdp10 | pdp11 | pj | pjl \
+ | powerpc | powerpc64 | powerpc64le | powerpcle \
+ | pyramid \
+ | rl78 | rx \
+ | score \
+ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+ | sh64 | sh64le \
+ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+ | spu \
+ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
+ | ubicom32 \
+ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+ | we32k \
+ | x86 | xc16x | xstormy16 | xtensa \
+ | z8k | z80)
+ basic_machine=$basic_machine-unknown
+ ;;
+ c54x)
+ basic_machine=tic54x-unknown
+ ;;
+ c55x)
+ basic_machine=tic55x-unknown
+ ;;
+ c6x)
+ basic_machine=tic6x-unknown
+ ;;
+ m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip)
+ basic_machine=$basic_machine-unknown
+ os=-none
+ ;;
+ m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+ ;;
+ ms1)
+ basic_machine=mt-unknown
+ ;;
+
+ strongarm | thumb | xscale)
+ basic_machine=arm-unknown
+ ;;
+ xgate)
+ basic_machine=$basic_machine-unknown
+ os=-none
+ ;;
+ xscaleeb)
+ basic_machine=armeb-unknown
+ ;;
+
+ xscaleel)
+ basic_machine=armel-unknown
+ ;;
+
+ # We use `pc' rather than `unknown'
+ # because (1) that's what they normally are, and
+ # (2) the word "unknown" tends to confuse beginning users.
+ i*86 | x86_64)
+ basic_machine=$basic_machine-pc
+ ;;
+ # Object if more than one company name word.
+ *-*-*)
+ echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+ exit 1
+ ;;
+ # Recognize the basic CPU types with company name.
+ 580-* \
+ | a29k-* \
+ | aarch64-* | aarch64_be-* \
+ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
+ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \
+ | avr-* | avr32-* \
+ | be32-* | be64-* \
+ | bfin-* | bs2000-* \
+ | c[123]* | c30-* | [cjt]90-* | c4x-* \
+ | clipper-* | craynv-* | cydra-* \
+ | d10v-* | d30v-* | dlx-* \
+ | elxsi-* \
+ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+ | h8300-* | h8500-* \
+ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+ | hexagon-* \
+ | i*86-* | i860-* | i960-* | ia64-* \
+ | ip2k-* | iq2000-* \
+ | le32-* | le64-* \
+ | lm32-* \
+ | m32c-* | m32r-* | m32rle-* \
+ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
+ | microblaze-* | microblazeel-* \
+ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+ | mips16-* \
+ | mips64-* | mips64el-* \
+ | mips64octeon-* | mips64octeonel-* \
+ | mips64orion-* | mips64orionel-* \
+ | mips64r5900-* | mips64r5900el-* \
+ | mips64vr-* | mips64vrel-* \
+ | mips64vr4100-* | mips64vr4100el-* \
+ | mips64vr4300-* | mips64vr4300el-* \
+ | mips64vr5000-* | mips64vr5000el-* \
+ | mips64vr5900-* | mips64vr5900el-* \
+ | mipsisa32-* | mipsisa32el-* \
+ | mipsisa32r2-* | mipsisa32r2el-* \
+ | mipsisa64-* | mipsisa64el-* \
+ | mipsisa64r2-* | mipsisa64r2el-* \
+ | mipsisa64sb1-* | mipsisa64sb1el-* \
+ | mipsisa64sr71k-* | mipsisa64sr71kel-* \
+ | mipsr5900-* | mipsr5900el-* \
+ | mipstx39-* | mipstx39el-* \
+ | mmix-* \
+ | mt-* \
+ | msp430-* \
+ | nds32-* | nds32le-* | nds32be-* \
+ | nios-* | nios2-* | nios2eb-* | nios2el-* \
+ | none-* | np1-* | ns16k-* | ns32k-* \
+ | open8-* \
+ | orion-* \
+ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+ | pyramid-* \
+ | rl78-* | romp-* | rs6000-* | rx-* \
+ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+ | sparclite-* \
+ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
+ | tahoe-* \
+ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+ | tile*-* \
+ | tron-* \
+ | ubicom32-* \
+ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
+ | vax-* \
+ | we32k-* \
+ | x86-* | x86_64-* | xc16x-* | xps100-* \
+ | xstormy16-* | xtensa*-* \
+ | ymp-* \
+ | z8k-* | z80-*)
+ ;;
+ # Recognize the basic CPU types without company name, with glob match.
+ xtensa*)
+ basic_machine=$basic_machine-unknown
+ ;;
+ # Recognize the various machine names and aliases which stand
+ # for a CPU type and a company and sometimes even an OS.
+ 386bsd)
+ basic_machine=i386-unknown
+ os=-bsd
+ ;;
+ 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+ basic_machine=m68000-att
+ ;;
+ 3b*)
+ basic_machine=we32k-att
+ ;;
+ a29khif)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ abacus)
+ basic_machine=abacus-unknown
+ ;;
+ adobe68k)
+ basic_machine=m68010-adobe
+ os=-scout
+ ;;
+ alliant | fx80)
+ basic_machine=fx80-alliant
+ ;;
+ altos | altos3068)
+ basic_machine=m68k-altos
+ ;;
+ am29k)
+ basic_machine=a29k-none
+ os=-bsd
+ ;;
+ amd64)
+ basic_machine=x86_64-pc
+ ;;
+ amd64-*)
+ basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ amdahl)
+ basic_machine=580-amdahl
+ os=-sysv
+ ;;
+ amiga | amiga-*)
+ basic_machine=m68k-unknown
+ ;;
+ amigaos | amigados)
+ basic_machine=m68k-unknown
+ os=-amigaos
+ ;;
+ amigaunix | amix)
+ basic_machine=m68k-unknown
+ os=-sysv4
+ ;;
+ apollo68)
+ basic_machine=m68k-apollo
+ os=-sysv
+ ;;
+ apollo68bsd)
+ basic_machine=m68k-apollo
+ os=-bsd
+ ;;
+ aros)
+ basic_machine=i386-pc
+ os=-aros
+ ;;
+ aux)
+ basic_machine=m68k-apple
+ os=-aux
+ ;;
+ balance)
+ basic_machine=ns32k-sequent
+ os=-dynix
+ ;;
+ blackfin)
+ basic_machine=bfin-unknown
+ os=-linux
+ ;;
+ blackfin-*)
+ basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ bluegene*)
+ basic_machine=powerpc-ibm
+ os=-cnk
+ ;;
+ c54x-*)
+ basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ c55x-*)
+ basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ c6x-*)
+ basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ c90)
+ basic_machine=c90-cray
+ os=-unicos
+ ;;
+ cegcc)
+ basic_machine=arm-unknown
+ os=-cegcc
+ ;;
+ convex-c1)
+ basic_machine=c1-convex
+ os=-bsd
+ ;;
+ convex-c2)
+ basic_machine=c2-convex
+ os=-bsd
+ ;;
+ convex-c32)
+ basic_machine=c32-convex
+ os=-bsd
+ ;;
+ convex-c34)
+ basic_machine=c34-convex
+ os=-bsd
+ ;;
+ convex-c38)
+ basic_machine=c38-convex
+ os=-bsd
+ ;;
+ cray | j90)
+ basic_machine=j90-cray
+ os=-unicos
+ ;;
+ craynv)
+ basic_machine=craynv-cray
+ os=-unicosmp
+ ;;
+ cr16 | cr16-*)
+ basic_machine=cr16-unknown
+ os=-elf
+ ;;
+ crds | unos)
+ basic_machine=m68k-crds
+ ;;
+ crisv32 | crisv32-* | etraxfs*)
+ basic_machine=crisv32-axis
+ ;;
+ cris | cris-* | etrax*)
+ basic_machine=cris-axis
+ ;;
+ crx)
+ basic_machine=crx-unknown
+ os=-elf
+ ;;
+ da30 | da30-*)
+ basic_machine=m68k-da30
+ ;;
+ decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+ basic_machine=mips-dec
+ ;;
+ decsystem10* | dec10*)
+ basic_machine=pdp10-dec
+ os=-tops10
+ ;;
+ decsystem20* | dec20*)
+ basic_machine=pdp10-dec
+ os=-tops20
+ ;;
+ delta | 3300 | motorola-3300 | motorola-delta \
+ | 3300-motorola | delta-motorola)
+ basic_machine=m68k-motorola
+ ;;
+ delta88)
+ basic_machine=m88k-motorola
+ os=-sysv3
+ ;;
+ dicos)
+ basic_machine=i686-pc
+ os=-dicos
+ ;;
+ djgpp)
+ basic_machine=i586-pc
+ os=-msdosdjgpp
+ ;;
+ dpx20 | dpx20-*)
+ basic_machine=rs6000-bull
+ os=-bosx
+ ;;
+ dpx2* | dpx2*-bull)
+ basic_machine=m68k-bull
+ os=-sysv3
+ ;;
+ ebmon29k)
+ basic_machine=a29k-amd
+ os=-ebmon
+ ;;
+ elxsi)
+ basic_machine=elxsi-elxsi
+ os=-bsd
+ ;;
+ encore | umax | mmax)
+ basic_machine=ns32k-encore
+ ;;
+ es1800 | OSE68k | ose68k | ose | OSE)
+ basic_machine=m68k-ericsson
+ os=-ose
+ ;;
+ fx2800)
+ basic_machine=i860-alliant
+ ;;
+ genix)
+ basic_machine=ns32k-ns
+ ;;
+ gmicro)
+ basic_machine=tron-gmicro
+ os=-sysv
+ ;;
+ go32)
+ basic_machine=i386-pc
+ os=-go32
+ ;;
+ h3050r* | hiux*)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ h8300hms)
+ basic_machine=h8300-hitachi
+ os=-hms
+ ;;
+ h8300xray)
+ basic_machine=h8300-hitachi
+ os=-xray
+ ;;
+ h8500hms)
+ basic_machine=h8500-hitachi
+ os=-hms
+ ;;
+ harris)
+ basic_machine=m88k-harris
+ os=-sysv3
+ ;;
+ hp300-*)
+ basic_machine=m68k-hp
+ ;;
+ hp300bsd)
+ basic_machine=m68k-hp
+ os=-bsd
+ ;;
+ hp300hpux)
+ basic_machine=m68k-hp
+ os=-hpux
+ ;;
+ hp3k9[0-9][0-9] | hp9[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k2[0-9][0-9] | hp9k31[0-9])
+ basic_machine=m68000-hp
+ ;;
+ hp9k3[2-9][0-9])
+ basic_machine=m68k-hp
+ ;;
+ hp9k6[0-9][0-9] | hp6[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k7[0-79][0-9] | hp7[0-79][0-9])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k78[0-9] | hp78[0-9])
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][13679] | hp8[0-9][13679])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][0-9] | hp8[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hppa-next)
+ os=-nextstep3
+ ;;
+ hppaosf)
+ basic_machine=hppa1.1-hp
+ os=-osf
+ ;;
+ hppro)
+ basic_machine=hppa1.1-hp
+ os=-proelf
+ ;;
+ i370-ibm* | ibm*)
+ basic_machine=i370-ibm
+ ;;
+ i*86v32)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv32
+ ;;
+ i*86v4*)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv4
+ ;;
+ i*86v)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-sysv
+ ;;
+ i*86sol2)
+ basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+ os=-solaris2
+ ;;
+ i386mach)
+ basic_machine=i386-mach
+ os=-mach
+ ;;
+ i386-vsta | vsta)
+ basic_machine=i386-unknown
+ os=-vsta
+ ;;
+ iris | iris4d)
+ basic_machine=mips-sgi
+ case $os in
+ -irix*)
+ ;;
+ *)
+ os=-irix4
+ ;;
+ esac
+ ;;
+ isi68 | isi)
+ basic_machine=m68k-isi
+ os=-sysv
+ ;;
+ m68knommu)
+ basic_machine=m68k-unknown
+ os=-linux
+ ;;
+ m68knommu-*)
+ basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ m88k-omron*)
+ basic_machine=m88k-omron
+ ;;
+ magnum | m3230)
+ basic_machine=mips-mips
+ os=-sysv
+ ;;
+ merlin)
+ basic_machine=ns32k-utek
+ os=-sysv
+ ;;
+ microblaze*)
+ basic_machine=microblaze-xilinx
+ ;;
+ mingw64)
+ basic_machine=x86_64-pc
+ os=-mingw64
+ ;;
+ mingw32)
+ basic_machine=i386-pc
+ os=-mingw32
+ ;;
+ mingw32ce)
+ basic_machine=arm-unknown
+ os=-mingw32ce
+ ;;
+ miniframe)
+ basic_machine=m68000-convergent
+ ;;
+ *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+ mips3*-*)
+ basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+ ;;
+ mips3*)
+ basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+ ;;
+ monitor)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ morphos)
+ basic_machine=powerpc-unknown
+ os=-morphos
+ ;;
+ msdos)
+ basic_machine=i386-pc
+ os=-msdos
+ ;;
+ ms1-*)
+ basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+ ;;
+ msys)
+ basic_machine=i386-pc
+ os=-msys
+ ;;
+ mvs)
+ basic_machine=i370-ibm
+ os=-mvs
+ ;;
+ nacl)
+ basic_machine=le32-unknown
+ os=-nacl
+ ;;
+ ncr3000)
+ basic_machine=i486-ncr
+ os=-sysv4
+ ;;
+ netbsd386)
+ basic_machine=i386-unknown
+ os=-netbsd
+ ;;
+ netwinder)
+ basic_machine=armv4l-rebel
+ os=-linux
+ ;;
+ news | news700 | news800 | news900)
+ basic_machine=m68k-sony
+ os=-newsos
+ ;;
+ news1000)
+ basic_machine=m68030-sony
+ os=-newsos
+ ;;
+ news-3600 | risc-news)
+ basic_machine=mips-sony
+ os=-newsos
+ ;;
+ necv70)
+ basic_machine=v70-nec
+ os=-sysv
+ ;;
+ next | m*-next )
+ basic_machine=m68k-next
+ case $os in
+ -nextstep* )
+ ;;
+ -ns2*)
+ os=-nextstep2
+ ;;
+ *)
+ os=-nextstep3
+ ;;
+ esac
+ ;;
+ nh3000)
+ basic_machine=m68k-harris
+ os=-cxux
+ ;;
+ nh[45]000)
+ basic_machine=m88k-harris
+ os=-cxux
+ ;;
+ nindy960)
+ basic_machine=i960-intel
+ os=-nindy
+ ;;
+ mon960)
+ basic_machine=i960-intel
+ os=-mon960
+ ;;
+ nonstopux)
+ basic_machine=mips-compaq
+ os=-nonstopux
+ ;;
+ np1)
+ basic_machine=np1-gould
+ ;;
+ neo-tandem)
+ basic_machine=neo-tandem
+ ;;
+ nse-tandem)
+ basic_machine=nse-tandem
+ ;;
+ nsr-tandem)
+ basic_machine=nsr-tandem
+ ;;
+ op50n-* | op60c-*)
+ basic_machine=hppa1.1-oki
+ os=-proelf
+ ;;
+ openrisc | openrisc-*)
+ basic_machine=or32-unknown
+ ;;
+ os400)
+ basic_machine=powerpc-ibm
+ os=-os400
+ ;;
+ OSE68000 | ose68000)
+ basic_machine=m68000-ericsson
+ os=-ose
+ ;;
+ os68k)
+ basic_machine=m68k-none
+ os=-os68k
+ ;;
+ pa-hitachi)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ paragon)
+ basic_machine=i860-intel
+ os=-osf
+ ;;
+ parisc)
+ basic_machine=hppa-unknown
+ os=-linux
+ ;;
+ parisc-*)
+ basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ pbd)
+ basic_machine=sparc-tti
+ ;;
+ pbb)
+ basic_machine=m68k-tti
+ ;;
+ pc532 | pc532-*)
+ basic_machine=ns32k-pc532
+ ;;
+ pc98)
+ basic_machine=i386-pc
+ ;;
+ pc98-*)
+ basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentium | p5 | k5 | k6 | nexgen | viac3)
+ basic_machine=i586-pc
+ ;;
+ pentiumpro | p6 | 6x86 | athlon | athlon_*)
+ basic_machine=i686-pc
+ ;;
+ pentiumii | pentium2 | pentiumiii | pentium3)
+ basic_machine=i686-pc
+ ;;
+ pentium4)
+ basic_machine=i786-pc
+ ;;
+ pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+ basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentiumpro-* | p6-* | 6x86-* | athlon-*)
+ basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+ basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pentium4-*)
+ basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ pn)
+ basic_machine=pn-gould
+ ;;
+ power) basic_machine=power-ibm
+ ;;
+ ppc | ppcbe) basic_machine=powerpc-unknown
+ ;;
+ ppc-* | ppcbe-*)
+ basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppcle | powerpclittle | ppc-le | powerpc-little)
+ basic_machine=powerpcle-unknown
+ ;;
+ ppcle-* | powerpclittle-*)
+ basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppc64) basic_machine=powerpc64-unknown
+ ;;
+ ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+ basic_machine=powerpc64le-unknown
+ ;;
+ ppc64le-* | powerpc64little-*)
+ basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ ps2)
+ basic_machine=i386-ibm
+ ;;
+ pw32)
+ basic_machine=i586-unknown
+ os=-pw32
+ ;;
+ rdos | rdos64)
+ basic_machine=x86_64-pc
+ os=-rdos
+ ;;
+ rdos32)
+ basic_machine=i386-pc
+ os=-rdos
+ ;;
+ rom68k)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ rm[46]00)
+ basic_machine=mips-siemens
+ ;;
+ rtpc | rtpc-*)
+ basic_machine=romp-ibm
+ ;;
+ s390 | s390-*)
+ basic_machine=s390-ibm
+ ;;
+ s390x | s390x-*)
+ basic_machine=s390x-ibm
+ ;;
+ sa29200)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ sb1)
+ basic_machine=mipsisa64sb1-unknown
+ ;;
+ sb1el)
+ basic_machine=mipsisa64sb1el-unknown
+ ;;
+ sde)
+ basic_machine=mipsisa32-sde
+ os=-elf
+ ;;
+ sei)
+ basic_machine=mips-sei
+ os=-seiux
+ ;;
+ sequent)
+ basic_machine=i386-sequent
+ ;;
+ sh)
+ basic_machine=sh-hitachi
+ os=-hms
+ ;;
+ sh5el)
+ basic_machine=sh5le-unknown
+ ;;
+ sh64)
+ basic_machine=sh64-unknown
+ ;;
+ sparclite-wrs | simso-wrs)
+ basic_machine=sparclite-wrs
+ os=-vxworks
+ ;;
+ sps7)
+ basic_machine=m68k-bull
+ os=-sysv2
+ ;;
+ spur)
+ basic_machine=spur-unknown
+ ;;
+ st2000)
+ basic_machine=m68k-tandem
+ ;;
+ stratus)
+ basic_machine=i860-stratus
+ os=-sysv4
+ ;;
+ strongarm-* | thumb-*)
+ basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
+ ;;
+ sun2)
+ basic_machine=m68000-sun
+ ;;
+ sun2os3)
+ basic_machine=m68000-sun
+ os=-sunos3
+ ;;
+ sun2os4)
+ basic_machine=m68000-sun
+ os=-sunos4
+ ;;
+ sun3os3)
+ basic_machine=m68k-sun
+ os=-sunos3
+ ;;
+ sun3os4)
+ basic_machine=m68k-sun
+ os=-sunos4
+ ;;
+ sun4os3)
+ basic_machine=sparc-sun
+ os=-sunos3
+ ;;
+ sun4os4)
+ basic_machine=sparc-sun
+ os=-sunos4
+ ;;
+ sun4sol2)
+ basic_machine=sparc-sun
+ os=-solaris2
+ ;;
+ sun3 | sun3-*)
+ basic_machine=m68k-sun
+ ;;
+ sun4)
+ basic_machine=sparc-sun
+ ;;
+ sun386 | sun386i | roadrunner)
+ basic_machine=i386-sun
+ ;;
+ sv1)
+ basic_machine=sv1-cray
+ os=-unicos
+ ;;
+ symmetry)
+ basic_machine=i386-sequent
+ os=-dynix
+ ;;
+ t3e)
+ basic_machine=alphaev5-cray
+ os=-unicos
+ ;;
+ t90)
+ basic_machine=t90-cray
+ os=-unicos
+ ;;
+ tile*)
+ basic_machine=$basic_machine-unknown
+ os=-linux-gnu
+ ;;
+ tx39)
+ basic_machine=mipstx39-unknown
+ ;;
+ tx39el)
+ basic_machine=mipstx39el-unknown
+ ;;
+ toad1)
+ basic_machine=pdp10-xkl
+ os=-tops20
+ ;;
+ tower | tower-32)
+ basic_machine=m68k-ncr
+ ;;
+ tpf)
+ basic_machine=s390x-ibm
+ os=-tpf
+ ;;
+ udi29k)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ ultra3)
+ basic_machine=a29k-nyu
+ os=-sym1
+ ;;
+ v810 | necv810)
+ basic_machine=v810-nec
+ os=-none
+ ;;
+ vaxv)
+ basic_machine=vax-dec
+ os=-sysv
+ ;;
+ vms)
+ basic_machine=vax-dec
+ os=-vms
+ ;;
+ vpp*|vx|vx-*)
+ basic_machine=f301-fujitsu
+ ;;
+ vxworks960)
+ basic_machine=i960-wrs
+ os=-vxworks
+ ;;
+ vxworks68)
+ basic_machine=m68k-wrs
+ os=-vxworks
+ ;;
+ vxworks29k)
+ basic_machine=a29k-wrs
+ os=-vxworks
+ ;;
+ w65*)
+ basic_machine=w65-wdc
+ os=-none
+ ;;
+ w89k-*)
+ basic_machine=hppa1.1-winbond
+ os=-proelf
+ ;;
+ xbox)
+ basic_machine=i686-pc
+ os=-mingw32
+ ;;
+ xps | xps100)
+ basic_machine=xps100-honeywell
+ ;;
+ xscale-* | xscalee[bl]-*)
+ basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
+ ;;
+ ymp)
+ basic_machine=ymp-cray
+ os=-unicos
+ ;;
+ z8k-*-coff)
+ basic_machine=z8k-unknown
+ os=-sim
+ ;;
+ z80-*-coff)
+ basic_machine=z80-unknown
+ os=-sim
+ ;;
+ none)
+ basic_machine=none-none
+ os=-none
+ ;;
+
+# Here we handle the default manufacturer of certain CPU types. It is in
+# some cases the only manufacturer, in others, it is the most popular.
+ w89k)
+ basic_machine=hppa1.1-winbond
+ ;;
+ op50n)
+ basic_machine=hppa1.1-oki
+ ;;
+ op60c)
+ basic_machine=hppa1.1-oki
+ ;;
+ romp)
+ basic_machine=romp-ibm
+ ;;
+ mmix)
+ basic_machine=mmix-knuth
+ ;;
+ rs6000)
+ basic_machine=rs6000-ibm
+ ;;
+ vax)
+ basic_machine=vax-dec
+ ;;
+ pdp10)
+ # there are many clones, so DEC is not a safe bet
+ basic_machine=pdp10-unknown
+ ;;
+ pdp11)
+ basic_machine=pdp11-dec
+ ;;
+ we32k)
+ basic_machine=we32k-att
+ ;;
+ sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
+ basic_machine=sh-unknown
+ ;;
+ sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
+ basic_machine=sparc-sun
+ ;;
+ cydra)
+ basic_machine=cydra-cydrome
+ ;;
+ orion)
+ basic_machine=orion-highlevel
+ ;;
+ orion105)
+ basic_machine=clipper-highlevel
+ ;;
+ mac | mpw | mac-mpw)
+ basic_machine=m68k-apple
+ ;;
+ pmac | pmac-mpw)
+ basic_machine=powerpc-apple
+ ;;
+ *-unknown)
+ # Make sure to match an already-canonicalized machine name.
+ ;;
+ *)
+ echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+ *-digital*)
+ basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+ ;;
+ *-commodore*)
+ basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+ ;;
+ *)
+ ;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+ # First match some system type aliases
+ # that might get confused with valid system types.
+ # -solaris* is a basic system type, with this one exception.
+ -auroraux)
+ os=-auroraux
+ ;;
+ -solaris1 | -solaris1.*)
+ os=`echo $os | sed -e 's|solaris1|sunos4|'`
+ ;;
+ -solaris)
+ os=-solaris2
+ ;;
+ -svr4*)
+ os=-sysv4
+ ;;
+ -unixware*)
+ os=-sysv4.2uw
+ ;;
+ -gnu/linux*)
+ os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+ ;;
+ # First accept the basic system types.
+ # The portable systems comes first.
+ # Each alternative MUST END IN A *, to match a version number.
+ # -sysv* is not here because it comes later, after sysvr4.
+ -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
+ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
+ | -sym* | -kopensolaris* | -plan9* \
+ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+ | -aos* | -aros* \
+ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+ | -bitrig* | -openbsd* | -solidbsd* \
+ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+ | -chorusos* | -chorusrdb* | -cegcc* \
+ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+ | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
+ | -linux-newlib* | -linux-musl* | -linux-uclibc* \
+ | -uxpv* | -beos* | -mpeix* | -udk* \
+ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
+ # Remember, each alternative MUST END IN *, to match a version number.
+ ;;
+ -qnx*)
+ case $basic_machine in
+ x86-* | i*86-*)
+ ;;
+ *)
+ os=-nto$os
+ ;;
+ esac
+ ;;
+ -nto-qnx*)
+ ;;
+ -nto*)
+ os=`echo $os | sed -e 's|nto|nto-qnx|'`
+ ;;
+ -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+ ;;
+ -mac*)
+ os=`echo $os | sed -e 's|mac|macos|'`
+ ;;
+ -linux-dietlibc)
+ os=-linux-dietlibc
+ ;;
+ -linux*)
+ os=`echo $os | sed -e 's|linux|linux-gnu|'`
+ ;;
+ -sunos5*)
+ os=`echo $os | sed -e 's|sunos5|solaris2|'`
+ ;;
+ -sunos6*)
+ os=`echo $os | sed -e 's|sunos6|solaris3|'`
+ ;;
+ -opened*)
+ os=-openedition
+ ;;
+ -os400*)
+ os=-os400
+ ;;
+ -wince*)
+ os=-wince
+ ;;
+ -osfrose*)
+ os=-osfrose
+ ;;
+ -osf*)
+ os=-osf
+ ;;
+ -utek*)
+ os=-bsd
+ ;;
+ -dynix*)
+ os=-bsd
+ ;;
+ -acis*)
+ os=-aos
+ ;;
+ -atheos*)
+ os=-atheos
+ ;;
+ -syllable*)
+ os=-syllable
+ ;;
+ -386bsd)
+ os=-bsd
+ ;;
+ -ctix* | -uts*)
+ os=-sysv
+ ;;
+ -nova*)
+ os=-rtmk-nova
+ ;;
+ -ns2 )
+ os=-nextstep2
+ ;;
+ -nsk*)
+ os=-nsk
+ ;;
+ # Preserve the version number of sinix5.
+ -sinix5.*)
+ os=`echo $os | sed -e 's|sinix|sysv|'`
+ ;;
+ -sinix*)
+ os=-sysv4
+ ;;
+ -tpf*)
+ os=-tpf
+ ;;
+ -triton*)
+ os=-sysv3
+ ;;
+ -oss*)
+ os=-sysv3
+ ;;
+ -svr4)
+ os=-sysv4
+ ;;
+ -svr3)
+ os=-sysv3
+ ;;
+ -sysvr4)
+ os=-sysv4
+ ;;
+ # This must come after -sysvr4.
+ -sysv*)
+ ;;
+ -ose*)
+ os=-ose
+ ;;
+ -es1800*)
+ os=-ose
+ ;;
+ -xenix)
+ os=-xenix
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ os=-mint
+ ;;
+ -aros*)
+ os=-aros
+ ;;
+ -zvmoe)
+ os=-zvmoe
+ ;;
+ -dicos*)
+ os=-dicos
+ ;;
+ -nacl*)
+ ;;
+ -none)
+ ;;
+ *)
+ # Get rid of the `-' at the beginning of $os.
+ os=`echo $os | sed 's/[^-]*-//'`
+ echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system. Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+ score-*)
+ os=-elf
+ ;;
+ spu-*)
+ os=-elf
+ ;;
+ *-acorn)
+ os=-riscix1.2
+ ;;
+ arm*-rebel)
+ os=-linux
+ ;;
+ arm*-semi)
+ os=-aout
+ ;;
+ c4x-* | tic4x-*)
+ os=-coff
+ ;;
+ hexagon-*)
+ os=-elf
+ ;;
+ tic54x-*)
+ os=-coff
+ ;;
+ tic55x-*)
+ os=-coff
+ ;;
+ tic6x-*)
+ os=-coff
+ ;;
+ # This must come before the *-dec entry.
+ pdp10-*)
+ os=-tops20
+ ;;
+ pdp11-*)
+ os=-none
+ ;;
+ *-dec | vax-*)
+ os=-ultrix4.2
+ ;;
+ m68*-apollo)
+ os=-domain
+ ;;
+ i386-sun)
+ os=-sunos4.0.2
+ ;;
+ m68000-sun)
+ os=-sunos3
+ ;;
+ m68*-cisco)
+ os=-aout
+ ;;
+ mep-*)
+ os=-elf
+ ;;
+ mips*-cisco)
+ os=-elf
+ ;;
+ mips*-*)
+ os=-elf
+ ;;
+ or1k-*)
+ os=-elf
+ ;;
+ or32-*)
+ os=-coff
+ ;;
+ *-tti) # must be before sparc entry or we get the wrong os.
+ os=-sysv3
+ ;;
+ sparc-* | *-sun)
+ os=-sunos4.1.1
+ ;;
+ *-be)
+ os=-beos
+ ;;
+ *-haiku)
+ os=-haiku
+ ;;
+ *-ibm)
+ os=-aix
+ ;;
+ *-knuth)
+ os=-mmixware
+ ;;
+ *-wec)
+ os=-proelf
+ ;;
+ *-winbond)
+ os=-proelf
+ ;;
+ *-oki)
+ os=-proelf
+ ;;
+ *-hp)
+ os=-hpux
+ ;;
+ *-hitachi)
+ os=-hiux
+ ;;
+ i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+ os=-sysv
+ ;;
+ *-cbm)
+ os=-amigaos
+ ;;
+ *-dg)
+ os=-dgux
+ ;;
+ *-dolphin)
+ os=-sysv3
+ ;;
+ m68k-ccur)
+ os=-rtu
+ ;;
+ m88k-omron*)
+ os=-luna
+ ;;
+ *-next )
+ os=-nextstep
+ ;;
+ *-sequent)
+ os=-ptx
+ ;;
+ *-crds)
+ os=-unos
+ ;;
+ *-ns)
+ os=-genix
+ ;;
+ i370-*)
+ os=-mvs
+ ;;
+ *-next)
+ os=-nextstep3
+ ;;
+ *-gould)
+ os=-sysv
+ ;;
+ *-highlevel)
+ os=-bsd
+ ;;
+ *-encore)
+ os=-bsd
+ ;;
+ *-sgi)
+ os=-irix
+ ;;
+ *-siemens)
+ os=-sysv4
+ ;;
+ *-masscomp)
+ os=-rtu
+ ;;
+ f30[01]-fujitsu | f700-fujitsu)
+ os=-uxpv
+ ;;
+ *-rom68k)
+ os=-coff
+ ;;
+ *-*bug)
+ os=-coff
+ ;;
+ *-apple)
+ os=-macos
+ ;;
+ *-atari*)
+ os=-mint
+ ;;
+ *)
+ os=-none
+ ;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer. We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+ *-unknown)
+ case $os in
+ -riscix*)
+ vendor=acorn
+ ;;
+ -sunos*)
+ vendor=sun
+ ;;
+ -cnk*|-aix*)
+ vendor=ibm
+ ;;
+ -beos*)
+ vendor=be
+ ;;
+ -hpux*)
+ vendor=hp
+ ;;
+ -mpeix*)
+ vendor=hp
+ ;;
+ -hiux*)
+ vendor=hitachi
+ ;;
+ -unos*)
+ vendor=crds
+ ;;
+ -dgux*)
+ vendor=dg
+ ;;
+ -luna*)
+ vendor=omron
+ ;;
+ -genix*)
+ vendor=ns
+ ;;
+ -mvs* | -opened*)
+ vendor=ibm
+ ;;
+ -os400*)
+ vendor=ibm
+ ;;
+ -ptx*)
+ vendor=sequent
+ ;;
+ -tpf*)
+ vendor=ibm
+ ;;
+ -vxsim* | -vxworks* | -windiss*)
+ vendor=wrs
+ ;;
+ -aux*)
+ vendor=apple
+ ;;
+ -hms*)
+ vendor=hitachi
+ ;;
+ -mpw* | -macos*)
+ vendor=apple
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ vendor=atari
+ ;;
+ -vos*)
+ vendor=stratus
+ ;;
+ esac
+ basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+ ;;
+esac
+
+echo $basic_machine$os
+exit
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/config/m-nt.h b/config/m-nt.h
new file mode 100644
index 0000000000..a80b0ac5e7
--- /dev/null
+++ b/config/m-nt.h
@@ -0,0 +1,43 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Machine configuration, Intel x86 processors, Win32,
+ Visual C++ or Mingw compiler */
+
+#ifdef _WIN64
+#define ARCH_SIXTYFOUR
+#else
+#undef ARCH_SIXTYFOUR
+#endif
+#undef ARCH_BIG_ENDIAN
+#undef ARCH_ALIGN_DOUBLE
+
+#define SIZEOF_INT 4
+#define SIZEOF_LONG 4
+#ifdef _WIN64
+#define SIZEOF_PTR 8
+#else
+#define SIZEOF_PTR 4
+#endif
+#define SIZEOF_SHORT 2
+
+#ifdef __MINGW32__
+#define ARCH_INT64_TYPE long long
+#define ARCH_UINT64_TYPE unsigned long long
+#else
+#define ARCH_INT64_TYPE __int64
+#define ARCH_UINT64_TYPE unsigned __int64
+#endif
+#define ARCH_INT64_PRINTF_FORMAT "I64"
+
+#undef NONSTANDARD_DIV_MOD
diff --git a/config/m-templ.h b/config/m-templ.h
new file mode 100644
index 0000000000..a5497b56b5
--- /dev/null
+++ b/config/m-templ.h
@@ -0,0 +1,81 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Processor dependencies */
+
+#define ARCH_SIXTYFOUR
+
+/* Define ARCH_SIXTYFOUR if the processor has a natural word size of 64 bits.
+ That is, sizeof(char *) = 8.
+ Otherwise, leave ARCH_SIXTYFOUR undefined.
+ This assumes sizeof(char *) = 4. */
+
+#define ARCH_BIG_ENDIAN
+
+/* Define ARCH_BIG_ENDIAN if the processor is big endian (the most
+ significant byte of an integer stored in memory comes first).
+ Leave ARCH_BIG_ENDIAN undefined if the processor is little-endian
+ (the least significant byte comes first).
+*/
+
+#define ARCH_ALIGN_DOUBLE
+
+/* Define ARCH_ALIGN_DOUBLE if the processor requires doubles to be
+ doubleword-aligned. Leave ARCH_ALIGN_DOUBLE undefined if the processor
+ supports word-aligned doubles. */
+
+#undef ARCH_CODE32
+
+/* Define ARCH_CODE32 if, on a 64-bit machine, code pointers fit in 32 bits,
+ i.e. the code segment resides in the low 4G of the addressing space.
+ ARCH_CODE32 is ignored on 32-bit machines. */
+
+#define SIZEOF_INT 4
+#define SIZEOF_LONG 4
+#define SIZEOF_PTR 4
+#define SIZEOF_SHORT 2
+
+/* Define SIZEOF_INT, SIZEOF_LONG, SIZEOF_PTR and SIZEOF_SHORT
+ to the sizes in bytes of the C types "int", "long", "char *" and "short",
+ respectively. */
+
+#define ARCH_INT64_TYPE long long
+#define ARCH_UINT64_TYPE unsigned long long
+
+/* Define ARCH_INT64_TYPE and ARCH_UINT64_TYPE to 64-bit integer types,
+ typically "long long" and "unsigned long long" on 32-bit platforms,
+ and "long" and "unsigned long" on 64-bit platforms.
+ If the C compiler doesn't support any 64-bit integer type,
+ leave both ARCH_INT64_TYPE and ARCH_UINT64_TYPE undefined. */
+
+#define ARCH_INT64_PRINTF_FORMAT "ll"
+
+/* Define ARCH_INT64_PRINTF_FORMAT to the printf format used for formatting
+ values of type ARCH_INT64_TYPE. This is usually "ll" on 32-bit
+ platforms and "l" on 64-bit platforms.
+ Leave undefined if ARCH_INT64_TYPE is undefined. */
+
+#define ARCH_ALIGN_INT64
+
+/* Define ARCH_ALIGN_INT64 if the processor requires 64-bit integers to be
+ doubleword-aligned. Leave ARCH_ALIGN_INT64 undefined if the processor
+ supports word-aligned 64-bit integers. Leave undefined if
+ 64-bit integers are not supported. */
+
+#undef NONSTANDARD_DIV_MOD
+
+/* Leave NONSTANDARD_DIV_MOD undefined if the C operators / and % implement
+ round-towards-zero semantics, as specified by ISO C 9x and implemented
+ by most contemporary processors. Otherwise, or if you don't know,
+ define NONSTANDARD_DIV_MOD: this will select a slower but correct
+ software emulation of division and modulus. */
diff --git a/config/s-nt.h b/config/s-nt.h
new file mode 100644
index 0000000000..ccf1bf4c57
--- /dev/null
+++ b/config/s-nt.h
@@ -0,0 +1,33 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Operating system dependencies, Intel x86 processors, Windows NT */
+
+#define OCAML_OS_TYPE "Win32"
+
+#ifdef __MINGW32__
+#define HAS_STDINT_H
+#endif
+#undef BSD_SIGNALS
+#define HAS_STRERROR
+#define HAS_SOCKETS
+#define HAS_GETCWD
+#define HAS_UTIME
+#define HAS_DUP2
+#define HAS_GETHOSTNAME
+#define HAS_MKTIME
+#define HAS_PUTENV
+#define HAS_LOCALE
+#define HAS_BROKEN_PRINTF
+#define HAS_IPV6
+#define HAS_NICE
diff --git a/config/s-templ.h b/config/s-templ.h
new file mode 100644
index 0000000000..383b401557
--- /dev/null
+++ b/config/s-templ.h
@@ -0,0 +1,218 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Operating system and standard library dependencies. */
+
+/* 0. Operating system type string. */
+
+#define OCAML_OS_TYPE "Unix"
+/* #define OCAML_OS_TYPE "Win32" */
+/* #define OCAML_OS_TYPE "MacOS" */
+
+/* 1. For the runtime system. */
+
+#define POSIX_SIGNALS
+
+/* Define POSIX_SIGNALS if signal handling is POSIX-compliant.
+ In particular, sigaction(), sigprocmask() and the operations on
+ sigset_t are provided. */
+
+#define BSD_SIGNALS
+
+/* Define BSD_SIGNALS if signal handlers have the BSD semantics: the handler
+ remains attached to the signal when the signal is received. Leave it
+ undefined if signal handlers have the System V semantics: the signal
+ resets the behavior to default. */
+
+#define HAS_SIGSETMASK
+
+/* Define HAS_SIGSETMASK if you have sigsetmask(), as in BSD. */
+
+#define HAS_TERMCAP
+
+/* Define HAS_TERMCAP if you have the termcap functions to read the
+ terminal database, e.g. tgetent(), tgetstr(), tgetnum(), tputs().
+ Also add the required libraries (e.g. -lcurses -ltermcap) to $(CCLIBS)
+ in ../Makefile.config */
+
+#define SUPPORT_DYNAMIC_LINKING
+
+/* Define SUPPORT_DYNAMIC_LINKING if dynamic loading of C stub code
+ via dlopen() is available. */
+
+#define HAS_C99_FLOAT_OPS
+
+/* Define HAS_C99_FLOAT_OPS if <math.h> conforms to ISO C99.
+ In particular, it should provide expm1(), log1p(), hypot(), copysign(). */
+
+/* 2. For the Unix library. */
+
+#define HAS_SOCKETS
+
+/* Define HAS_SOCKETS if you have BSD sockets. */
+
+#define HAS_SOCKLEN_T
+
+/* Define HAS_SOCKLEN_T if the type socklen_t is defined in
+ /usr/include/sys/socket.h. */
+
+#define HAS_UNISTD
+
+/* Define HAS_UNISTD if you have /usr/include/unistd.h. */
+
+#define HAS_DIRENT
+
+/* Define HAS_DIRENT if you have /usr/include/dirent.h and the result of
+ readdir() is of type struct dirent *.
+ Otherwise, we'll load /usr/include/sys/dir.h, and readdir() is expected to
+ return a struct direct *. */
+
+#define HAS_REWINDDIR
+
+/* Define HAS_REWINDDIR if you have rewinddir(). */
+
+#define HAS_LOCKF
+
+/* Define HAS_LOCKF if the library provides the lockf() function. */
+
+#define HAS_MKFIFO
+
+/* Define HAS_MKFIFO if the library provides the mkfifo() function. */
+
+#define HAS_GETCWD
+#define HAS_GETWD
+
+/* Define HAS_GETCWD if the library provides the getcwd() function. */
+/* Define HAS_GETWD if the library provides the getwd() function. */
+
+#define HAS_GETPRIORITY
+
+/* Define HAS_GETPRIORITY if the library provides getpriority() and
+ setpriority(). Otherwise, we'll use nice(). */
+
+#define HAS_UTIME
+#define HAS_UTIMES
+
+/* Define HAS_UTIME if you have /usr/include/utime.h and the library
+ provides utime(). Define HAS_UTIMES if the library provides utimes(). */
+
+#define HAS_DUP2
+
+/* Define HAS_DUP2 if you have dup2(). */
+
+#define HAS_FCHMOD
+
+/* Define HAS_FCHMOD if you have fchmod() and fchown(). */
+
+#define HAS_TRUNCATE
+
+/* Define HAS_TRUNCATE if you have truncate() and
+ ftruncate(). */
+
+#define HAS_SELECT
+
+/* Define HAS_SELECT if you have select(). */
+
+#define HAS_SYS_SELECT_H
+
+/* Define HAS_SYS_SELECT_H if /usr/include/sys/select.h exists
+ and should be included before using select(). */
+
+#define HAS_SYMLINK
+
+/* Define HAS_SYMLINK if you have symlink() and readlink() and lstat(). */
+
+#define HAS_WAIT4
+#define HAS_WAITPID
+
+/* Define HAS_WAIT4 if you have wait4().
+ Define HAS_WAITPID if you have waitpid(). */
+
+#define HAS_GETGROUPS
+
+/* Define HAS_GETGROUPS if you have getgroups(). */
+
+#define HAS_SETGROUPS
+
+/* Define HAS_SETGROUPS if you have setgroups(). */
+
+#define HAS_INITGROUPS
+
+/* Define HAS_INITGROUPS if you have initgroups(). */
+
+#define HAS_TERMIOS
+
+/* Define HAS_TERMIOS if you have /usr/include/termios.h and it is
+ Posix-compliant. */
+
+#define HAS_ASYNC_IO
+
+/* Define HAS_ASYNC_IO if BSD-style asynchronous I/O are supported
+ (the process can request to be sent a SIGIO signal when a descriptor
+ is ready for reading). */
+
+#define HAS_SETITIMER
+
+/* Define HAS_SETITIMER if you have setitimer(). */
+
+#define HAS_GETHOSTNAME
+
+/* Define HAS_GETHOSTNAME if you have gethostname(). */
+
+#define HAS_UNAME
+
+/* Define HAS_UNAME if you have uname(). */
+
+#define HAS_GETTIMEOFDAY
+
+/* Define HAS_GETTIMEOFDAY if you have gettimeofday(). */
+
+#define HAS_MKTIME
+
+/* Define HAS_MKTIME if you have mktime(). */
+
+#define HAS_SETSID
+
+/* Define HAS_SETSID if you have setsid(). */
+
+#define HAS_PUTENV
+
+/* Define HAS_PUTENV if you have putenv(). */
+
+#define HAS_LOCALE
+
+/* Define HAS_LOCALE if you have the include file <locale.h> and the
+ setlocale() function. */
+
+#define HAS_MMAP
+
+/* Define HAS_MMAP if you have the include file <sys/mman.h> and the
+ functions mmap() and munmap(). */
+
+#define HAS_GETHOSTBYNAME_R 6
+
+/* Define HAS_GETHOSTBYNAME_R if gethostbyname_r() is available.
+ The value of this symbol is the number of arguments of
+ gethostbyname_r(): either 5 or 6 depending on prototype.
+ (5 is the Solaris version, 6 is the Linux version). */
+
+#define HAS_GETHOSTBYADDR_R 8
+
+/* Define HAS_GETHOSTBYADDR_R if gethostbyname_r() is available.
+ The value of this symbol is the number of arguments of
+ gethostbyaddr_r(): either 7 or 8 depending on prototype.
+ (7 is the Solaris version, 8 is the Linux version). */
+
+#define HAS_NICE
+
+/* Define HAS_NICE if you have nice(). */
diff --git a/configure b/configure
new file mode 100755
index 0000000000..55965232e0
--- /dev/null
+++ b/configure
@@ -0,0 +1,1857 @@
+#! /bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file LICENSE. #
+# #
+#########################################################################
+
+ocamlversion=`head -1 VERSION`
+echo "Configuring OCaml version $ocamlversion"
+
+configure_options="$*"
+prefix=/usr/local
+bindir=''
+target_bindir=''
+libdir=''
+mandir=''
+manext=1
+host_type=unknown
+target_type=""
+ccoption=''
+asoption=''
+asppoption=''
+cclibs=''
+curseslibs=''
+mathlib='-lm'
+dllib=''
+x11_include_dir=''
+x11_lib_dir=''
+graph_wanted=yes
+pthread_wanted=yes
+dl_defs=''
+verbose=no
+with_curses=yes
+debugruntime=noruntimed
+with_sharedlibs=yes
+partialld="ld -r"
+with_debugger=ocamldebugger
+with_ocamldoc=ocamldoc
+with_ocamlbuild=ocamlbuild
+with_frame_pointers=false
+no_naked_pointers=false
+TOOLPREF=""
+with_cfi=true
+
+# Try to turn internationalization off, can cause config.guess to malfunction!
+unset LANG
+unset LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME
+
+# Turn off some MacOS X debugging stuff, same reason
+unset RC_TRACE_ARCHIVES RC_TRACE_DYLIBS RC_TRACE_PREBINDING_DISABLED
+
+# The inf(), wrn(), err() functions below can be used to provide a consistent
+# way to notify the user. The notification is always given to the stdout
+# descriptor.
+#
+# Their output is redirected to a file-descriptor "3" which is then redirected
+# to fd 1 at the level of the whole configure script. This is done to not
+# conflict with how values are returned from functions in shell script.
+# Consider the following where "It works!" would be mixed with "42".
+# do_foo() {
+# if some_command; then
+# inf "It works!"
+# echo "42"
+# fi
+# }
+inf() {
+ printf "%b\n" "$*" 1>&3
+}
+
+wrn() {
+ printf "[WARNING] %b\n" "$*" 1>&3
+}
+
+err() {
+ printf "[ERROR!] %b\n" "$*" 1>&3
+ exit 2
+}
+
+exec 3>&1
+
+# Parse command-line arguments
+
+while : ; do
+ case "$1" in
+ "") break;;
+ -prefix|--prefix)
+ prefix=$2; shift;;
+ -bindir|--bindir)
+ bindir=$2; shift;;
+ -target-bindir|--target-bindir)
+ target_bindir="$2"; shift;;
+ -libdir|--libdir)
+ libdir=$2; shift;;
+ -mandir|--mandir)
+ case "$2" in
+ */man[1-9ln])
+ mandir=`echo $2 | sed -e 's|^\(.*\)/man.$|\1|'`
+ manext=`echo $2 | sed -e 's/^.*\(.\)$/\1/'`;;
+ *)
+ mandir=$2
+ manext=1;;
+ esac
+ shift;;
+ -host*|--host*)
+ host_type=$2; shift;;
+ -target*|--target*)
+ target_type=$2; shift;;
+ -cc*)
+ ccoption="$2"; shift;;
+ -as)
+ asoption="$2"; shift;;
+ -aspp)
+ asppoption="$2"; shift;;
+ -lib*)
+ cclibs="$2 $cclibs"; shift;;
+ -no-curses|--no-curses)
+ with_curses=no;;
+ -no-shared-libs|--no-shared-libs)
+ with_sharedlibs=no;;
+ -x11include*|--x11include*)
+ x11_include_dir=$2; shift;;
+ -x11lib*|--x11lib*)
+ x11_lib_dir=$2; shift;;
+ -no-graph|--no-graph) graph_wanted=no;;
+ -with-pthread*|--with-pthread*)
+ ;; # Ignored for backward compatibility
+ -no-pthread*|--no-pthread*)
+ pthread_wanted=no;;
+ -partialld|--partialld)
+ partialld="$2"; shift;;
+ -dldefs*|--dldefs*)
+ dl_defs="$2"; shift;;
+ -dllibs*|--dllibs*)
+ dllib="$2"; shift;;
+ -verbose|--verbose)
+ verbose=yes;;
+ -with-debug-runtime|--with-debug-runtime)
+ debugruntime=runtimed;;
+ -no-debugger|--no-debugger)
+ with_debugger="";;
+ -no-ocamldoc|--no-ocamldoc)
+ with_ocamldoc="";;
+ -no-ocamlbuild|--no-ocamlbuild)
+ with_ocamlbuild="";;
+ -with-frame-pointers|--with-frame-pointers)
+ with_frame_pointers=true;;
+ -no-naked-pointers|--no-naked-pointers)
+ no_naked_pointers=true;;
+ -no-cfi|--no-cfi)
+ with_cfi=false;;
+ *) if echo "$1" | grep -q -e '^--\?[a-zA-Z0-9-]\+='; then
+ err "configure expects arguments of the form '-prefix /foo/bar'," \
+ "not '-prefix=/foo/bar' (note the '=')."
+ else
+ err "Unknown option \"$1\"."
+ fi;;
+ esac
+ shift
+done
+
+# Sanity checks
+
+case "$prefix" in
+ /*) ;;
+ *) err "The -prefix directory must be absolute.";;
+esac
+case "$bindir" in
+ /*) ;;
+ "") ;;
+ '$(PREFIX)/'*) ;;
+ *) err 'The -bindir directory must be absolute or relative to $(PREFIX).';;
+esac
+case "$libdir" in
+ /*) ;;
+ "") ;;
+ '$(PREFIX)/'*) ;;
+ *) err 'The -libdir directory must be absolute or relative to $(PREFIX).';;
+esac
+case "$mandir" in
+ /*) ;;
+ "") ;;
+ '$(PREFIX)/'*) ;;
+ *) err 'The -mandir directory must be absolute or relative to $(PREFIX).';;
+esac
+
+# Generate the files
+
+cd config/auto-aux
+rm -f s.h m.h Makefile
+touch s.h m.h Makefile
+
+# Write options to Makefile
+
+echo "# generated by ./configure $configure_options" >> Makefile
+
+# Where to install
+
+echo "PREFIX=$prefix" >> Makefile
+case "$bindir" in
+ "") echo 'BINDIR=$(PREFIX)/bin' >> Makefile
+ bindir="$prefix/bin";;
+ *) echo "BINDIR=$bindir" >> Makefile;;
+esac
+case "$libdir" in
+ "") echo 'LIBDIR=$(PREFIX)/lib/ocaml' >> Makefile
+ libdir="$prefix/lib/ocaml";;
+ *) echo "LIBDIR=$libdir" >> Makefile;;
+esac
+echo 'STUBLIBDIR=$(LIBDIR)/stublibs' >> Makefile
+case "$mandir" in
+ "") echo 'MANDIR=$(PREFIX)/man' >> Makefile
+ mandir="$prefix/man";;
+ *) echo "MANDIR=$mandir" >> Makefile;;
+esac
+echo "MANEXT=$manext" >> Makefile
+
+# Determine the system type
+
+if test "$host_type" = "unknown"; then
+ if host_type=`../gnu/config.guess`; then :; else
+ err "Cannot guess host type. You must specify one with the -host option."
+ fi
+fi
+if host=`../gnu/config.sub $host_type`; then :; else
+ err "Please specify the correct host type with the -host option"
+fi
+inf "Configuring for host $host ..."
+
+if test -n "$target_type"; then
+ target="$target_type"
+ TOOLPREF="${target}-"
+else
+ target="$host"
+fi
+inf "Configuring for target $target ..."
+
+if [ x"$host" = x"$target" ]; then
+ cross_compiler=false
+else
+ cross_compiler=true
+fi
+
+# Do we have gcc?
+
+if test -z "$ccoption"; then
+ if sh ./searchpath "${TOOLPREF}gcc"; then
+ cc="${TOOLPREF}gcc"
+ else
+ if $cross_compiler; then
+ err "No cross-compiler found for ${target}.\n" \
+ "It should be named ${TOOLPREF}gcc and be in the PATH."
+ else
+ cc="cc"
+ fi
+ fi
+else
+ cc="$ccoption"
+fi
+
+inf "Using compiler $cc."
+
+# Determine the C compiler family (GCC, Clang, etc)
+
+ccfamily=`$cc -E cckind.c | grep '^[a-z]' | tr -s ' ' '-'`
+case $? in
+ 0) inf "Compiler family and version: $ccfamily.";;
+ *) err "Unable to preprocess the test program.\n" \
+ "Make sure the C compiler $cc is properly installed.";;
+esac
+
+# Configure the bytecode compiler
+
+bytecc="$cc"
+mkexe="\$(BYTECC)"
+mkexedebugflag="-g"
+bytecccompopts=""
+bytecclinkopts=""
+dllccompopts=""
+ostype="Unix"
+exe=""
+iflexdir=""
+SO="so"
+TOOLCHAIN="cc"
+
+# Choose reasonable options based on compiler kind
+# We select high optimization levels, provided we can turn off:
+# - strict type-based aliasing analysis (too risky for the OCaml runtime)
+# - strict no-overflow conditions on signed integer arithmetic
+# (the OCaml runtime assumes Java-style behavior of signed integer arith.)
+# Concerning optimization level, -O3 is somewhat risky, so take -O2
+# Concerning language version, gnu99 is ISO C99 plus GNU extensions
+# that are often used in standard headers. GCC defaults to gnu89,
+# which is not C99. Clang defaults to gnu99 or gnu11, which is fine.
+
+case "$ocamlversion" in
+ *+dev*) gcc_warnings="-Wall -Werror";;
+ *) gcc_warnings="-Wall";;
+esac
+
+case "$ccfamily" in
+ clang-*)
+ bytecccompopts="-O2 -fno-strict-aliasing -fwrapv $gcc_warnings";;
+ gcc-[012]-*)
+ # Some versions known to miscompile OCaml, e,g, 2.7,2.1, some 2.96.
+ # Plus: C99 support unknown.
+ err "This version of GCC is too old. Please use GCC version 3 or above.";;
+ gcc-3-[0123])
+ # No -fwrapv option yet
+ bytecccompopts="-std=gnu99 -O $gcc_warnings";;
+ gcc-*)
+ bytecccompopts="-std=gnu99 -O2 -fno-strict-aliasing -fwrapv $gcc_warnings";;
+ *)
+ bytecccompopts="-O";;
+esac
+
+# Adjust according to target
+
+case "$bytecc,$target" in
+ cc,*-*-nextstep*)
+ # GNU C extensions disabled, but __GNUC__ still defined!
+ bytecccompopts="$bytecccompopts -U__GNUC__ -posix"
+ bytecclinkopts="-posix";;
+ *,*-*-rhapsody*)
+ # Almost the same as NeXTStep
+ bytecccompopts="$bytecccompopts -DSHRINKED_GNUC"
+ mathlib="";;
+ *,*-*-darwin*)
+ mathlib=""
+ mkexe="$mkexe -Wl,-no_compact_unwind"
+ # Tell gcc that we can use 32-bit code addresses for threaded code
+ # unless we are compiled for a shared library (-fPIC option)
+ echo "#ifndef __PIC__" >> m.h
+ echo "# define ARCH_CODE32" >> m.h
+ echo "#endif" >> m.h;;
+ *,*-*-haiku*)
+ # No -lm library
+ mathlib="";;
+ *,*-*-beos*)
+ # No -lm library
+ mathlib="";;
+ *gcc,alpha*-*-osf*)
+ if cc="$bytecc" sh ./hasgot -mieee; then
+ bytecccompopts="-mieee $bytecccompopts";
+ fi
+ # Put code and static data in lower 4GB
+ bytecclinkopts="-Wl,-T,12000000 -Wl,-D,14000000"
+ # Tell gcc that we can use 32-bit code addresses for threaded code
+ echo "#define ARCH_CODE32" >> m.h;;
+ cc,alpha*-*-osf*)
+ bytecccompopts="-std1 -ieee";;
+ *gcc*,alpha*-*-linux*)
+ if cc="$bytecc" sh ./hasgot -mieee; then
+ bytecccompopts="-mieee $bytecccompopts";
+ fi;;
+ *,mips-*-irix6*)
+ # Turn off warning "unused library"
+ bytecclinkopts="-n32 -Wl,-woff,84";;
+ *,alpha*-*-unicos*)
+ # For the Cray T3E
+ bytecccompopts="$bytecccompopts -DUMK";;
+ *,powerpc-*-aix*)
+ # Avoid name-space pollution by requiring Unix98-conformant includes
+ bytecccompopts="$bytecccompopts -D_XOPEN_SOURCE=500";;
+ *,*-*-cygwin*)
+ case $target in
+ i686-*) flavor=cygwin;;
+ x86_64-*) flavor=cygwin64;;
+ *) err "unknown cygwin variant";;
+ esac
+ bytecccompopts="$bytecccompopts -U_WIN32"
+ dllccompopts="-U_WIN32 -DCAML_DLL"
+ if test $with_sharedlibs = yes; then
+ flexlink="flexlink -chain $flavor -merge-manifest -stack 16777216"
+ flexdir=`$flexlink -where | dos2unix`
+ if test -z "$flexdir"; then
+ wrn "flexlink not found: native shared libraries won't be available."
+ with_sharedlibs=no
+ else
+ iflexdir="-I\"$flexdir\""
+ mkexe="$flexlink -exe"
+ mkexedebugflag="-link -g"
+ fi
+ fi
+ if test $with_sharedlibs = no; then
+ mkexe="$mkexe -Wl,--stack,16777216"
+ bytecclinkopts="-Wl,--stack,16777216"
+ fi
+ exe=".exe"
+ ostype="Cygwin";;
+ *,*-*-mingw*)
+ dllccompopt="-DCAML_DLL"
+ if test $with_sharedlibs = yes; then
+ case "$target" in
+ i686-*-*) flexlink_chain="mingw";;
+ x86_64-*-*) flexlink_chain="mingw64";;
+ esac
+ flexlink="flexlink -chain $flexlink_chain -merge-manifest -stack 16777216"
+ flexdir=`$flexlink -where`
+ if test -z "$flexdir"; then
+ wrn "flexlink not found: native shared libraries won't be available."
+ with_sharedlibs=no
+ else
+ iflexdir="-I\"$flexdir\""
+ mkexe="$flexlink -exe"
+ mkexedebugflag="-link -g"
+ fi
+ fi
+ exe=".exe"
+ ostype="Win32"
+ TOOLCHAIN="mingw"
+ SO="dll"
+ ;;
+ *,x86_64-*-linux*)
+ # Tell gcc that we can use 32-bit code addresses for threaded code
+ # unless we are compiled for a shared library (-fPIC option)
+ echo "#ifndef __PIC__" >> m.h
+ echo "# define ARCH_CODE32" >> m.h
+ echo "#endif" >> m.h;;
+esac
+
+# Configure compiler to use in further tests.
+
+cc="$bytecc $bytecclinkopts"
+export cc cclibs verbose
+
+# Check C compiler.
+
+cc="$bytecc $bytecccompopts $bytecclinkopts" sh ./runtest ansi.c
+case $? in
+ 0) inf "The C compiler is ISO C99 compliant." ;;
+ 1) wrn "The C compiler is ANSI / ISO C90 compliant, but not ISO C99" \
+ "compliant.";;
+ 2) err "The C compiler $cc is not ISO C compliant.\n" \
+ "You need an ISO C99 compiler to build OCaml.";;
+ *)
+ if $cross_compiler; then
+ wrn "Unable to compile the test program.\n" \
+ "This failure is expected for cross-compilation:\n" \
+ "we will assume the C compiler is ISO C99-compliant."
+ else
+ err "Unable to compile the test program.\n" \
+ "Make sure the C compiler $cc is properly installed."
+ fi;;
+esac
+
+# For cross-compilation, we need a host-based ocamlrun and ocamlyacc,
+# and the user must specify the target BINDIR
+if $cross_compiler; then
+ if ! sh ./searchpath ocamlrun; then
+ err "Cross-compilation requires an ocaml runtime environment\n" \
+ "(the ocamlrun binary). Moreover, its version must be the same\n" \
+ "as the one you're trying to build (`cut -f1 -d+ < ../../VERSION`)."
+ else
+ ocaml_system_version=`ocamlrun -version | sed 's/[^0-9]*\([0-9.]*\).*/\1/'`
+ ocaml_source_version=`sed -n '1 s/\([0-9\.]*\).*/\1/ p' < ../../VERSION`
+ if test x"$ocaml_system_version" != x"$ocaml_source_version"; then
+ err "While you have an ocaml runtime environment, its version\n" \
+ "($ocaml_system_version) doesn't match the version of these\n" \
+ "sources ($ocaml_source_version)."
+ else
+ echo "CAMLRUN=`./searchpath -p ocamlrun`" >> Makefile
+ fi
+ fi
+
+ if ! sh ./searchpath ocamlyacc; then
+ err "Cross-compilation requires an ocamlyacc binary."
+ else
+ ocamlyacc 2>/dev/null
+ if test "$?" -ne 1; then
+ err "While you have an ocamlyacc binary, it cannot be executed" \
+ "successfully."
+ else
+ echo "CAMLYACC=`./searchpath -p ocamlyacc`" >> Makefile
+ fi
+ fi
+
+ if [ -z "$target_bindir" ]; then
+ err "Cross-compilation requires -target-bindir."
+ else
+ echo "TARGET_BINDIR=$target_bindir" >> Makefile
+ fi
+fi # cross-compiler
+
+
+# Check the sizes of data types
+# OCaml needs a 32 or 64 bit architecture, a 32-bit integer type and
+# a 64-bit integer type
+
+inf "Checking the sizes of integers and pointers..."
+ret=`sh ./runtest sizes.c`
+# $1 = sizeof(int)
+# $2 = sizeof(long)
+# $3 = sizeof(pointers)
+# $4 = sizeof(short)
+# $5 = sizeof(long long)
+
+if test "$?" -eq 0; then
+ set $ret
+ case "$3" in
+ 4) inf "OK, this is a regular 32 bit architecture."
+ echo "#undef ARCH_SIXTYFOUR" >> m.h
+ arch64=false;;
+ 8) inf "Wow! A 64 bit architecture!"
+ echo "#define ARCH_SIXTYFOUR" >> m.h
+ arch64=true;;
+ *) err "This architecture seems to be neither 32 bits nor 64 bits.\n" \
+ "OCaml won't run on this architecture.";;
+ esac
+else
+ # For cross-compilation, runtest always fails: add special handling.
+ case "$target" in
+ i686-*-mingw*) inf "OK, this is a regular 32 bit architecture."
+ echo "#undef ARCH_SIXTYFOUR" >> m.h
+ set 4 4 4 2 8
+ arch64=false;;
+ x86_64-*-mingw*) inf "Wow! A 64 bit architecture!"
+ echo "#define ARCH_SIXTYFOUR" >> m.h
+ set 4 4 8 2 8
+ arch64=true;;
+ *) err "Since datatype sizes cannot be guessed when cross-compiling,\n" \
+ "a hardcoded list is used but your architecture isn't known yet.\n" \
+ "You need to determine the sizes yourself.\n" \
+ "Please submit a bug report in order to expand the list." ;;
+ esac
+fi
+
+if test $1 != 4 && test $2 != 4 && test $4 != 4; then
+ err "Sorry, we can't find a 32-bit integer type\n" \
+ "(sizeof(short) = $4, sizeof(int) = $1, sizeof(long) = $2)\n" \
+ "OCaml won't run on this architecture."
+fi
+
+if test $2 != 8 && test $5 != 8; then
+ err "Sorry, we can't find a 64-bit integer type\n" \
+ "(sizeof(long) = $2, sizeof(long long) = $5)\n" \
+ "OCaml won't run on this architecture."
+fi
+
+echo "#define SIZEOF_INT $1" >> m.h
+echo "#define SIZEOF_LONG $2" >> m.h
+echo "#define SIZEOF_PTR $3" >> m.h
+echo "#define SIZEOF_SHORT $4" >> m.h
+echo "#define SIZEOF_LONGLONG $5" >> m.h
+
+# Determine endianness
+
+sh ./runtest endian.c
+case $? in
+ 0) inf "This is a big-endian architecture."
+ echo "#define ARCH_BIG_ENDIAN" >> m.h;;
+ 1) inf "This is a little-endian architecture."
+ echo "#undef ARCH_BIG_ENDIAN" >> m.h;;
+ 2) err "This architecture seems to be neither big endian nor little" \
+ "endian.\n OCaml won't run on this architecture.";;
+ *) case $target in
+ *-*-mingw*) inf "This is a little-endian architecture."
+ echo "#undef ARCH_BIG_ENDIAN" >> m.h;;
+ *) wrn "Something went wrong during endianness determination.\n" \
+ "You will have to figure out endianness yourself\n" \
+ "(option ARCH_BIG_ENDIAN in m.h).";;
+ esac;;
+esac
+
+# Determine alignment constraints
+
+case "$target" in
+ sparc*-*-*|hppa*-*-*|arm*-*-*|mips*-*-*)
+ # On Sparc V9 with certain versions of gcc, determination of double
+ # alignment is not reliable (PR#1521), hence force it.
+ # Same goes for hppa.
+ # PR#5088 suggests same problem on ARM.
+ # PR#5280 reports same problem on MIPS.
+ # But there's a knack (PR#2572):
+ # if we're in 64-bit mode (sizeof(long) == 8),
+ # we must not doubleword-align floats...
+ if test $2 = 8; then
+ inf "Doubles can be word-aligned."
+ echo "#undef ARCH_ALIGN_DOUBLE" >> m.h
+ else
+ inf "Doubles must be doubleword-aligned."
+ echo "#define ARCH_ALIGN_DOUBLE" >> m.h
+ fi;;
+ *)
+ sh ./runtest dblalign.c
+ case $? in
+ 0) inf "Doubles can be word-aligned."
+ echo "#undef ARCH_ALIGN_DOUBLE" >> m.h;;
+ 1) inf "Doubles must be doubleword-aligned."
+ echo "#define ARCH_ALIGN_DOUBLE" >> m.h;;
+ *) case "$target" in
+ *-*-mingw*) inf "Doubles can be word-aligned."
+ echo "#undef ARCH_ALIGN_DOUBLE" >> m.h;;
+ *) wrn "Something went wrong during alignment determination for" \
+ "doubles.\n" \
+ "We will assume alignment constraints over doubles.\n" \
+ "That's a safe bet: OCaml will work even if\n" \
+ "this architecture actually has no alignment constraints."
+ echo "#define ARCH_ALIGN_DOUBLE" >> m.h;;
+ esac;;
+ esac;;
+esac
+
+case "$target" in
+ # PR#5088: autodetection is unreliable on ARM. PR#5280: also on MIPS.
+ sparc*-*-*|hppa*-*-*|arm*-*-*|mips*-*-*)
+ if test $2 = 8; then
+ inf "64-bit integers can be word-aligned."
+ echo "#undef ARCH_ALIGN_INT64" >> m.h
+ else
+ inf "64-bit integers must be doubleword-aligned."
+ echo "#define ARCH_ALIGN_INT64" >> m.h
+ fi;;
+ *-*-mingw*) true;; # Nothing is in config/m-nt.h so don't add anything.
+ *)
+ sh ./runtest int64align.c
+ case $? in
+ 0) inf "64-bit integers can be word-aligned."
+ echo "#undef ARCH_ALIGN_INT64" >> m.h;;
+ 1) inf "64-bit integers must be doubleword-aligned."
+ echo "#define ARCH_ALIGN_INT64" >> m.h;;
+ *) wrn "Something went wrong during alignment determination for\n" \
+ "64-bit integers. I'm going to assume this architecture has\n" \
+ "alignment constraints. That's a safe bet: OCaml will work\n" \
+ "even if this architecture has actually no alignment\n" \
+ "constraints." \
+ echo "#define ARCH_ALIGN_INT64" >> m.h;;
+ esac
+esac
+
+# Shared library support
+
+shared_libraries_supported=false
+dl_needs_underscore=false
+sharedcccompopts=''
+mksharedlib=''
+byteccrpath=''
+mksharedlibrpath=''
+natdynlinkopts=""
+
+if test $with_sharedlibs = "yes"; then
+ case "$target" in
+ *-*-cygwin*)
+ mksharedlib="$flexlink"
+ mkmaindll="$flexlink -maindll"
+ shared_libraries_supported=true;;
+ *-*-mingw*)
+ mksharedlib="$flexlink"
+ mkmaindll="$flexlink -maindll"
+ shared_libraries_supported=true;;
+ *-*-linux-gnu|*-*-linux|*-*-freebsd[3-9]*|*-*-freebsd[1-9][0-9]*\
+ |*-*-openbsd*|*-*-netbsd*|*-*-gnu*|*-*-haiku*)
+ sharedcccompopts="-fPIC"
+ mksharedlib="$bytecc -shared"
+ bytecclinkopts="$bytecclinkopts -Wl,-E"
+ byteccrpath="-Wl,-rpath,"
+ mksharedlibrpath="-Wl,-rpath,"
+ natdynlinkopts="-Wl,-E"
+ shared_libraries_supported=true;;
+ alpha*-*-osf*)
+ case "$bytecc" in
+ *gcc*)
+ sharedcccompopts="-fPIC"
+ mksharedlib="$bytecc -shared"
+ byteccrpath="-Wl,-rpath,"
+ mksharedlibrpath="-Wl,-rpath,"
+ shared_libraries_supported=true;;
+ cc*)
+ sharedcccompopts=""
+ mksharedlib="ld -shared -expect_unresolved '*'"
+ byteccrpath="-Wl,-rpath,"
+ mksharedlibrpath="-rpath "
+ shared_libraries_supported=true;;
+ esac;;
+ *-*-solaris2*)
+ case "$bytecc" in
+ *gcc*)
+ sharedcccompopts="-fPIC"
+ if sh ./solaris-ld; then
+ mksharedlib="$bytecc -shared"
+ byteccrpath="-R"
+ mksharedlibrpath="-R"
+ else
+ mksharedlib="$bytecc -shared"
+ bytecclinkopts="$bytecclinkopts -Wl,-E"
+ natdynlinkopts="-Wl,-E"
+ byteccrpath="-Wl,-rpath,"
+ mksharedlibrpath="-Wl,-rpath,"
+ fi
+ shared_libraries_supported=true;;
+ *)
+ sharedcccompopts="-KPIC"
+ byteccrpath="-R"
+ mksharedlibrpath="-R"
+ mksharedlib="/usr/ccs/bin/ld -G"
+ shared_libraries_supported=true;;
+ esac;;
+ mips*-*-irix[56]*)
+ case "$bytecc" in
+ cc*) sharedcccompopts="";;
+ *gcc*) sharedcccompopts="-fPIC";;
+ esac
+ mksharedlib="ld -shared -rdata_shared"
+ byteccrpath="-Wl,-rpath,"
+ mksharedlibrpath="-rpath "
+ shared_libraries_supported=true;;
+ i[3456]86-*-darwin[89].*)
+ mksharedlib="$bytecc -bundle -flat_namespace -undefined suppress \
+ -read_only_relocs suppress"
+ bytecccompopts="$dl_defs $bytecccompopts"
+ dl_needs_underscore=false
+ shared_libraries_supported=true;;
+ *-apple-darwin*)
+ mksharedlib="$bytecc -bundle -flat_namespace -undefined suppress \
+ -Wl,-no_compact_unwind"
+ bytecccompopts="$dl_defs $bytecccompopts"
+ dl_needs_underscore=false
+ shared_libraries_supported=true;;
+ m88k-*-openbsd*)
+ shared_libraries_supported=false;;
+ vax-*-openbsd*)
+ shared_libraries_supported=false;;
+ *-*-openbsd*)
+ sharedcccompopts="-fPIC"
+ mksharedlib="$bytecc -shared"
+ bytecclinkopts="$bytecclinkopts -Wl,-E"
+ natdynlinkopts="-Wl,-E"
+ byteccrpath="-Wl,-rpath,"
+ mksharedlibrpath="-Wl,-rpath,"
+ shared_libraries_supported=true;;
+ esac
+fi
+
+if test -z "$mkmaindll"; then
+ mkmaindll=$mksharedlib
+fi
+
+# Configure native dynlink
+
+natdynlink=false
+
+if test $with_sharedlibs = "yes"; then
+ case "$target" in
+ *-*-cygwin*) natdynlink=true;;
+ *-*-mingw*) natdynlink=true;;
+ i[3456]86-*-linux*) natdynlink=true;;
+ i[3456]86-*-gnu*) natdynlink=true;;
+ x86_64-*-linux*) natdynlink=true;;
+ i[3456]86-*-darwin[89].*) natdynlink=true;;
+ i[3456]86-*-darwin*)
+ if test $arch64 == true; then
+ natdynlink=true
+ fi;;
+ x86_64-*-darwin*) natdynlink=true;;
+ powerpc*-*-linux*) natdynlink=true;;
+ sparc*-*-linux*) natdynlink=true;;
+ i686-*-kfreebsd*) natdynlink=true;;
+ x86_64-*-kfreebsd*) natdynlink=true;;
+ i[3456]86-*-freebsd*) natdynlink=true;;
+ x86_64-*-freebsd*) natdynlink=true;;
+ i[3456]86-*-openbsd*) natdynlink=true;;
+ x86_64-*-openbsd*) natdynlink=true;;
+ i[3456]86-*-netbsd*) natdynlink=true;;
+ x86_64-*-netbsd*) natdynlink=true;;
+ i386-*-gnu0.3) natdynlink=true;;
+ i[3456]86-*-haiku*) natdynlink=true;;
+ arm*-*-linux*) natdynlink=true;;
+ arm*-*-freebsd*) natdynlink=true;;
+ aarch64-*-linux*) natdynlink=true;;
+ esac
+fi
+
+if test $natdynlink = "true"; then
+ cmxs="cmxs"
+else
+ cmxs="cmxa"
+fi
+
+
+# Configure the native-code compiler
+
+arch=none
+model=default
+system=unknown
+
+case "$target" in
+ sparc*-*-solaris2.*) arch=sparc; system=solaris;;
+ sparc*-*-*bsd*) arch=sparc; system=bsd;;
+ sparc*-*-linux*) arch=sparc; system=linux;;
+ sparc*-*-gnu*) arch=sparc; system=gnu;;
+ i[3456]86-*-linux*) arch=i386; system=linux_`sh ./runtest elf.c`;;
+ i[3456]86-*-*bsd*) arch=i386; system=bsd_`sh ./runtest elf.c`;;
+ i[3456]86-*-nextstep*) arch=i386; system=nextstep;;
+ i[3456]86-*-solaris*) if $arch64; then
+ arch=amd64; system=solaris
+ else
+ arch=i386; system=solaris
+ fi;;
+ i[3456]86-*-haiku*) arch=i386; system=beos;;
+ i[3456]86-*-beos*) arch=i386; system=beos;;
+ i[3456]86-*-cygwin*) arch=i386; system=cygwin;;
+ i[3456]86-*-darwin*) if $arch64; then
+ arch=amd64; system=macosx
+ else
+ arch=i386; system=macosx
+ fi;;
+ i[3456]86-*-gnu*) arch=i386; system=gnu;;
+ i[3456]86-*-mingw*) arch=i386; system=mingw;;
+ powerpc64le*-*-linux*) arch=power; model=ppc64le; system=elf;;
+ powerpc*-*-linux*) arch=power;
+ if $arch64; then model=ppc64; else model=ppc; fi
+ system=elf;;
+ powerpc-*-netbsd*) arch=power; model=ppc; system=elf;;
+ powerpc-*-openbsd*) arch=power; model=ppc; system=bsd_elf;;
+ armv6*-*-linux-gnueabihf) arch=arm; model=armv6; system=linux_eabihf;;
+ arm*-*-linux-gnueabihf) arch=arm; system=linux_eabihf;;
+ armv7*-*-linux-gnueabi) arch=arm; model=armv7; system=linux_eabi;;
+ armv6t2*-*-linux-gnueabi) arch=arm; model=armv6t2; system=linux_eabi;;
+ armv6*-*-linux-gnueabi) arch=arm; model=armv6; system=linux_eabi;;
+ armv6*-*-freebsd*) arch=arm; model=armv6; system=freebsd;;
+ armv5te*-*-linux-gnueabi) arch=arm; model=armv5te; system=linux_eabi;;
+ armv5*-*-linux-gnueabi) arch=arm; model=armv5; system=linux_eabi;;
+ arm*-*-linux-gnueabi) arch=arm; system=linux_eabi;;
+ arm*-*-openbsd*) arch=arm; system=bsd;;
+ zaurus*-*-openbsd*) arch=arm; system=bsd;;
+ x86_64-*-linux*) arch=amd64; system=linux;;
+ x86_64-*-gnu*) arch=amd64; system=gnu;;
+ x86_64-*-freebsd*) arch=amd64; system=freebsd;;
+ x86_64-*-netbsd*) arch=amd64; system=netbsd;;
+ x86_64-*-openbsd*) arch=amd64; system=openbsd;;
+ x86_64-*-darwin*) arch=amd64; system=macosx;;
+ x86_64-*-mingw*) arch=amd64; system=mingw;;
+ aarch64-*-linux*) arch=arm64; system=linux;;
+ x86_64-*-cygwin*) arch=amd64; system=cygwin;;
+esac
+
+# Some platforms exist both in 32-bit and 64-bit variants, not distinguished
+# by $target. Turn off native code compilation on platforms where 64-bit mode
+# is not supported (PR#4441).
+# Sometimes, it's 32-bit mode that is not supported (PR#6722).
+
+case "$arch64,$arch,$model" in
+ true,sparc,*|true,power,ppc|false,amd64,*)
+ arch=none; model=default; system=unknown;;
+esac
+
+if test -z "$ccoption"; then
+ nativecc="$bytecc"
+else
+ nativecc="$ccoption"
+fi
+
+nativecccompopts="$bytecccompopts"
+nativeccprofopts=''
+nativecclinkopts=''
+# FIXME the naming of nativecclinkopts is broken: these are options for
+# ld (for shared libs), not for cc
+nativeccrpath="$byteccrpath"
+
+case "$arch,$nativecc,$system,$model" in
+ *,*,nextstep,*) nativecclinkopts="-posix";;
+ *,*,rhapsody,*) if $arch64; then partialld="ld -r -arch ppc64"; fi;;
+ amd64,gcc*,macosx,*) partialld="ld -r -arch x86_64";;
+ amd64,gcc*,solaris,*) partialld="ld -r -m elf_x86_64";;
+ power,gcc*,elf,ppc) partialld="ld -r -m elf32ppclinux";;
+ power,gcc*,elf,ppc64) partialld="ld -r -m elf64ppc";;
+ power,gcc*,elf,ppc64le) partialld="ld -r -m elf64lppc";;
+esac
+
+asppprofflags='-DPROFILING'
+
+case "$arch,$system" in
+ amd64,macosx) if sh ./searchpath clang; then
+ as='clang -arch x86_64 -c'
+ aspp='clang -arch x86_64 -c'
+ else
+ as="${TOOLPREF}as -arch x86_64"
+ aspp="${TOOLPREF}gcc -arch x86_64 -c"
+ fi;;
+ amd64,solaris) as="${TOOLPREF}as --64"
+ aspp="${TOOLPREF}gcc -m64 -c";;
+ i386,solaris) as="${TOOLPREF}as"
+ aspp="/usr/ccs/bin/${TOOLPREF}as -P";;
+ power,elf) if $arch64; then
+ as="${TOOLPREF}as -a64 -mppc64"
+ aspp="${TOOLPREF}gcc -m64 -c"
+ else
+ as="${TOOLPREF}as -mppc"
+ aspp="${TOOLPREF}gcc -m32 -c"
+ fi;;
+ sparc,solaris) as="${TOOLPREF}as"
+ case "$cc" in
+ *gcc*) aspp="${TOOLPREF}gcc -c";;
+ *) aspp="${TOOLPREF}as -P";;
+ esac;;
+ arm,freebsd) as="${TOOLPREF}cc -c"
+ aspp="${TOOLPREF}cc -c";;
+ *,freebsd) as="${TOOLPREF}as"
+ aspp="${TOOLPREF}cc -c";;
+ amd64,*|arm,*|arm64,*|i386,*|power,bsd*|sparc,*)
+ as="${TOOLPREF}as"
+ aspp="${TOOLPREF}gcc -c";;
+esac
+
+if test -n "$asoption"; then as="$asoption"; fi
+if test -n "$asppoption"; then aspp="$asppoption"; fi
+
+cc_profile='-pg'
+case "$arch,$system" in
+ i386,linux_elf) profiling='prof';;
+ i386,gnu) profiling='prof';;
+ i386,bsd_elf) profiling='prof';;
+ amd64,macosx) profiling='prof';;
+ i386,macosx) profiling='prof';;
+ sparc,bsd) profiling='prof';;
+ sparc,solaris)
+ profiling='prof'
+ case "$nativecc" in gcc*) ;; *) cc_profile='-xpg';; esac;;
+ amd64,linux) profiling='prof';;
+ amd64,openbsd) profiling='prof';;
+ amd64,freebsd) profiling='prof';;
+ amd64,netbsd) profiling='prof';;
+ amd64,gnu) profiling='prof';;
+ arm,linux*) profiling='prof';;
+ power,elf) profiling='prof';;
+ power,bsd*) profiling='prof';;
+ *) profiling='noprof';;
+esac
+
+# Where is ranlib?
+
+if sh ./searchpath ${TOOLPREF}ranlib; then
+ inf "ranlib found"
+ echo "RANLIB=${TOOLPREF}ranlib" >> Makefile
+ echo "RANLIBCMD=${TOOLPREF}ranlib" >> Makefile
+else
+ inf "ranlib not used"
+ echo "RANLIB=${TOOLPREF}ar rs" >> Makefile
+ echo "RANLIBCMD=" >> Makefile
+fi
+
+echo "ARCMD=${TOOLPREF}ar" >> Makefile
+
+
+# Write the OS type (Unix or Cygwin)
+
+echo "#define OCAML_OS_TYPE \"$ostype\"" >> s.h
+echo "#define OCAML_STDLIB_DIR \"$libdir\"" >> s.h
+
+# Do #! scripts work?
+
+if (SHELL=/bin/sh; export SHELL; (./sharpbang || ./sharpbang2) >/dev/null); then
+ inf "#! appears to work in shell scripts."
+ case "$target" in
+ *-*-sunos*|*-*-unicos*)
+ wrn "We won't use it, though, because under SunOS and Unicos it breaks " \
+ "on pathnames longer than 30 characters"
+ echo "SHARPBANGSCRIPTS=false" >> Makefile;;
+ *-*-cygwin*)
+ wrn "We won't use it, though, because of conflicts with .exe extension " \
+ "under Cygwin"
+ echo "SHARPBANGSCRIPTS=false" >> Makefile;;
+ *-*-mingw*)
+ inf "We won't use it, though, because it's on the target platform " \
+ "it would be used and windows doesn't support it."
+ echo "SHARPBANGSCRIPTS=false" >> Makefile;;
+ *)
+ echo "SHARPBANGSCRIPTS=true" >> Makefile;;
+ esac
+else
+ inf "No support for #! in shell scripts"
+ echo "SHARPBANGSCRIPTS=false" >> Makefile
+fi
+
+# Use 64-bit file offset if possible
+
+bytecccompopts="$bytecccompopts -D_FILE_OFFSET_BITS=64"
+nativecccompopts="$nativecccompopts -D_FILE_OFFSET_BITS=64"
+
+# Check the semantics of signal handlers
+
+if sh ./hasgot sigaction sigprocmask; then
+ inf "POSIX signal handling found."
+ echo "#define POSIX_SIGNALS" >> s.h
+else
+ if sh ./runtest signals.c; then
+ inf "Signals have the BSD semantics."
+ echo "#define BSD_SIGNALS" >> s.h
+ else
+ inf "Signals have the System V semantics."
+ fi
+ if sh ./hasgot sigsetmask; then
+ inf "sigsetmask() found"
+ echo "#define HAS_SIGSETMASK" >> s.h
+ fi
+fi
+
+# For the Pervasives module
+
+if sh ./hasgot2 -i math.h $mathlib expm1 log1p hypot copysign; then
+ inf "expm1(), log1p(), hypot(), copysign() found."
+ echo "#define HAS_C99_FLOAT_OPS" >> s.h
+fi
+
+# For the Sys module
+
+if sh ./hasgot getrusage; then
+ inf "getrusage() found."
+ echo "#define HAS_GETRUSAGE" >> s.h
+fi
+
+if sh ./hasgot times; then
+ inf "times() found."
+ echo "#define HAS_TIMES" >> s.h
+fi
+
+# For the terminfo module
+
+if test "$with_curses" = "yes"; then
+ for libs in "" "-lcurses" "-ltermcap" "-lcurses -ltermcap" "-lncurses"; do
+ if sh ./hasgot $libs tgetent tgetstr tgetnum tputs; then
+ inf "termcap functions found (with libraries '$libs')"
+ echo "#define HAS_TERMCAP" >> s.h
+ curseslibs="${libs}"
+ break
+ fi
+ done
+fi
+
+# Configuration for the libraries
+
+case "$system" in
+ mingw) unix_or_win32="win32"; unixlib="win32unix"; graphlib="win32graph";;
+ *) unix_or_win32="unix"; unixlib="unix"; graphlib="graph";;
+esac
+
+echo "UNIX_OR_WIN32=$unix_or_win32" >> Makefile
+echo "UNIXLIB=$unixlib" >> Makefile
+echo "GRAPHLIB=$graphlib" >> Makefile
+
+otherlibraries="$unixlib str num dynlink bigarray"
+
+# For the Unix library
+
+has_sockets=no
+if sh ./hasgot socket socketpair bind listen accept connect; then
+ inf "You have BSD sockets."
+ echo "#define HAS_SOCKETS" >> s.h
+ has_sockets=yes
+elif sh ./hasgot -lnsl -lsocket socket socketpair bind listen accept connect
+then
+ inf "You have BSD sockets (with libraries '-lnsl -lsocket')"
+ cclibs="$cclibs -lnsl -lsocket"
+ echo "#define HAS_SOCKETS" >> s.h
+ has_sockets=yes
+elif sh ./hasgot -lnetwork socket socketpair bind listen accept connect; then
+ echo "You have BSD sockets (with library '-lnetwork')"
+ cclibs="$cclibs -lnetwork"
+ echo "#define HAS_SOCKETS" >> s.h
+ has_sockets=yes
+else
+ case "$target" in
+ *-*-mingw*)
+ inf "You have BSD sockets (with libraries '-lws2_32')"
+ cclibs="$cclibs -lws2_32"
+ echo "#define HAS_SOCKETS" >> s.h
+ has_sockets=yes ;;
+ *) ;;
+ esac
+fi
+
+if sh ./hasgot -i sys/socket.h -t socklen_t; then
+ inf "socklen_t is defined in <sys/socket.h>"
+ echo "#define HAS_SOCKLEN_T" >> s.h
+fi
+
+if sh ./hasgot inet_aton; then
+ inf "inet_aton() found."
+ echo "#define HAS_INET_ATON" >> s.h
+fi
+
+if sh ./hasgot -i sys/types.h -i sys/socket.h -i netinet/in.h \
+ -t 'struct sockaddr_in6' \
+&& sh ./hasgot getaddrinfo getnameinfo inet_pton inet_ntop; then
+ inf "IPv6 is supported."
+ echo "#define HAS_IPV6" >> s.h
+fi
+
+if sh ./hasgot -i stdint.h; then
+ inf "stdint.h found."
+ echo "#define HAS_STDINT_H" >> s.h
+fi
+
+if sh ./hasgot -i unistd.h; then
+ inf "unistd.h found."
+ echo "#define HAS_UNISTD" >> s.h
+fi
+
+if sh ./hasgot -i sys/types.h -t off_t; then
+ inf "off_t is defined in <sys/types.h>"
+ echo "#define HAS_OFF_T" >> s.h
+fi
+
+if sh ./hasgot -i sys/types.h -i dirent.h; then
+ inf "dirent.h found."
+ echo "#define HAS_DIRENT" >> s.h
+fi
+
+if sh ./hasgot rewinddir; then
+ inf "rewinddir() found."
+ echo "#define HAS_REWINDDIR" >> s.h
+fi
+
+if sh ./hasgot lockf; then
+ inf "lockf() found."
+ echo "#define HAS_LOCKF" >> s.h
+fi
+
+if sh ./hasgot mkfifo; then
+ inf "mkfifo() found."
+ echo "#define HAS_MKFIFO" >> s.h
+fi
+
+if sh ./hasgot getcwd; then
+ inf "getcwd() found."
+ echo "#define HAS_GETCWD" >> s.h
+fi
+
+if sh ./hasgot getwd; then
+ inf "getwd() found."
+ echo "#define HAS_GETWD" >> s.h
+fi
+
+if sh ./hasgot getpriority setpriority; then
+ inf "getpriority() found."
+ echo "#define HAS_GETPRIORITY" >> s.h
+fi
+
+if sh ./hasgot -i sys/types.h -i utime.h && sh ./hasgot utime; then
+ inf "utime() found."
+ echo "#define HAS_UTIME" >> s.h
+fi
+
+if sh ./hasgot utimes; then
+ inf "utimes() found."
+ echo "#define HAS_UTIMES" >> s.h
+fi
+
+if sh ./hasgot dup2; then
+ inf "dup2() found."
+ echo "#define HAS_DUP2" >> s.h
+fi
+
+if sh ./hasgot fchmod fchown; then
+ inf "fchmod() found."
+ echo "#define HAS_FCHMOD" >> s.h
+fi
+
+if sh ./hasgot truncate ftruncate; then
+ inf "truncate() found."
+ echo "#define HAS_TRUNCATE" >> s.h
+fi
+
+select_include=''
+if sh ./hasgot -i sys/types.h -i sys/select.h; then
+ inf "sys/select.h found."
+ echo "#define HAS_SYS_SELECT_H" >> s.h
+ select_include='-i sys/select.h'
+fi
+
+has_select=no
+if sh ./hasgot select && \
+ sh ./hasgot -i sys/types.h $select_include -t fd_set ; then
+ inf "select() found."
+ echo "#define HAS_SELECT" >> s.h
+ has_select=yes
+fi
+
+if sh ./hasgot symlink readlink lstat; then
+ inf "symlink() found."
+ echo "#define HAS_SYMLINK" >> s.h
+fi
+
+has_wait=no
+if sh ./hasgot waitpid; then
+ inf "waitpid() found."
+ echo "#define HAS_WAITPID" >> s.h
+ has_wait=yes
+fi
+
+if sh ./hasgot wait4; then
+ inf "wait4() found."
+ echo "#define HAS_WAIT4" >> s.h
+ has_wait=yes
+fi
+
+if sh ./hasgot -i limits.h && sh ./runtest getgroups.c; then
+ inf "getgroups() found."
+ echo "#define HAS_GETGROUPS" >> s.h
+fi
+
+if sh ./hasgot -i limits.h -i grp.h && sh ./runtest setgroups.c; then
+ inf "setgroups() found."
+ echo "#define HAS_SETGROUPS" >> s.h
+fi
+
+if sh ./hasgot -i limits.h -i grp.h && sh ./runtest initgroups.c; then
+ inf "initgroups() found."
+ echo "#define HAS_INITGROUPS" >> s.h
+fi
+
+if sh ./hasgot -i termios.h &&
+ sh ./hasgot tcgetattr tcsetattr tcsendbreak tcflush tcflow; then
+ inf "POSIX termios found."
+ echo "#define HAS_TERMIOS" >> s.h
+fi
+
+if sh ./runtest async_io.c; then
+ inf "Asynchronous I/O are supported."
+ echo "#define HAS_ASYNC_IO" >> s.h
+fi
+
+has_setitimer=no
+if sh ./hasgot setitimer; then
+ inf "setitimer() found."
+ echo "#define HAS_SETITIMER" >> s.h
+ has_setitimer="yes"
+fi
+
+if sh ./hasgot gethostname; then
+ inf "gethostname() found."
+ echo "#define HAS_GETHOSTNAME" >> s.h
+fi
+
+if sh ./hasgot -i sys/utsname.h && sh ./hasgot uname; then
+ inf "uname() found."
+ echo "#define HAS_UNAME" >> s.h
+fi
+
+has_gettimeofday=no
+if sh ./hasgot gettimeofday; then
+ inf "gettimeofday() found."
+ echo "#define HAS_GETTIMEOFDAY" >> s.h
+ has_gettimeofday="yes"
+fi
+
+if sh ./hasgot mktime; then
+ inf "mktime() found."
+ echo "#define HAS_MKTIME" >> s.h
+fi
+
+case "$target" in
+ *-*-cygwin*) ;; # setsid emulation under Cygwin breaks the debugger
+ *) if sh ./hasgot setsid; then
+ inf "setsid() found."
+ echo "#define HAS_SETSID" >> s.h
+ fi;;
+esac
+
+if sh ./hasgot putenv; then
+ inf "putenv() found."
+ echo "#define HAS_PUTENV" >> s.h
+fi
+
+if sh ./hasgot -i locale.h && sh ./hasgot setlocale; then
+ inf "setlocale() and <locale.h> found."
+ echo "#define HAS_LOCALE" >> s.h
+fi
+
+
+if sh ./hasgot $dllib dlopen; then
+ inf "dlopen() found."
+elif sh ./hasgot $dllib -ldl dlopen; then
+ inf "dlopen() found in -ldl."
+ dllib="$dllib -ldl"
+else
+ case "$target" in
+ *-*-mingw*) ;;
+ *) shared_libraries_supported=false
+ esac
+fi
+
+if $shared_libraries_supported; then
+ inf "Dynamic loading of shared libraries is supported."
+ echo "#define SUPPORT_DYNAMIC_LINKING" >> s.h
+ if $dl_needs_underscore; then
+ echo '#define DL_NEEDS_UNDERSCORE' >>s.h
+ fi
+fi
+
+if sh ./hasgot -i sys/types.h -i sys/mman.h && sh ./hasgot mmap munmap; then
+ inf "mmap() found."
+ echo "#define HAS_MMAP" >> s.h
+fi
+
+if sh ./hasgot pwrite; then
+ inf "pwrite() found"
+ echo "#define HAS_PWRITE" >> s.h
+fi
+
+nanosecond_stat=none
+for i in 1 2 3; do
+ if sh ./trycompile -DHAS_NANOSECOND_STAT=$i nanosecond_stat.c; then
+ nanosecond_stat=$i; break
+ fi
+done
+if test $nanosecond_stat != "none"; then
+ inf "stat() supports nanosecond precision."
+ echo "#define HAS_NANOSECOND_STAT $nanosecond_stat" >> s.h
+fi
+
+nargs=none
+for i in 5 6; do
+ if sh ./trycompile -DNUM_ARGS=${i} gethostbyname.c; then nargs=$i; break; fi
+done
+if test $nargs != "none"; then
+ inf "gethostbyname_r() found (with ${nargs} arguments)."
+ echo "#define HAS_GETHOSTBYNAME_R $nargs" >> s.h
+fi
+
+nargs=none
+for i in 7 8; do
+ if sh ./trycompile -DNUM_ARGS=${i} gethostbyaddr.c; then nargs=$i; break; fi
+done
+if test $nargs != "none"; then
+ inf "gethostbyaddr_r() found (with ${nargs} arguments)."
+ echo "#define HAS_GETHOSTBYADDR_R $nargs" >> s.h
+fi
+
+if sh ./hasgot mkstemp; then
+ inf "mkstemp() found"
+ echo "#define HAS_MKSTEMP" >> s.h
+fi
+
+if sh ./hasgot nice; then
+ inf "nice() found"
+ echo "#define HAS_NICE" >> s.h
+fi
+
+# Determine if the debugger is supported
+
+if test -n "$with_debugger"; then
+ if test "$has_sockets" = "yes"; then
+ inf "Replay debugger supported."
+ with_debugger="ocamldebugger"
+ else
+ inf "No replay debugger (missing system calls)"
+ with_debugger=""
+ fi
+fi
+
+# Determine if system stack overflows can be detected
+
+case "$arch,$system" in
+ i386,linux_elf|amd64,linux|power,rhapsody|amd64,macosx|i386,macosx \
+ |amd64,openbsd|i386,bsd_elf)
+ inf "System stack overflow can be detected."
+ echo "#define HAS_STACK_OVERFLOW_DETECTION" >> s.h;;
+ *)
+ inf "Cannot detect system stack overflow.";;
+esac
+
+# Determine the target architecture for the "num" library
+
+case "$arch" in
+ i386) bng_arch=ia32
+ if sh ./trycompile ia32sse2.c
+ then bng_asm_level=2
+ else bng_asm_level=1
+ fi;;
+ power) bng_arch=ppc; bng_asm_level=1;;
+ amd64) bng_arch=amd64; bng_asm_level=1;;
+ arm64) bng_arch=arm64; bng_asm_level=1;;
+ *) bng_arch=generic; bng_asm_level=0;;
+esac
+
+echo "BNG_ARCH=$bng_arch" >> Makefile
+echo "BNG_ASM_LEVEL=$bng_asm_level" >> Makefile
+
+# Determine if the POSIX threads library is supported
+
+systhread_support=false
+
+if test "$pthread_wanted" = "yes"; then
+ case "$target" in
+ *-*-solaris*) pthread_link="-lpthread -lposix4"
+ pthread_caml_link="-cclib -lpthread -cclib -lposix4";;
+ *-*-freebsd*) pthread_link="-pthread"
+ pthread_caml_link="-cclib -pthread";;
+ *-*-openbsd*) pthread_link="-pthread"
+ pthread_caml_link="-cclib -pthread";;
+ *-*-haiku*) pthread_link=""
+ pthread_caml_link="";;
+ *) pthread_link="-lpthread"
+ pthread_caml_link="-cclib -lpthread";;
+ esac
+ if sh ./hasgot -i pthread.h $pthread_link pthread_self; then
+ inf "POSIX threads library supported."
+ systhread_support=true
+ otherlibraries="$otherlibraries systhreads"
+ bytecccompopts="$bytecccompopts -D_REENTRANT"
+ nativecccompopts="$nativecccompopts -D_REENTRANT"
+ case "$target" in
+ *-*-freebsd*)
+ bytecccompopts="$bytecccompopts -D_THREAD_SAFE"
+ nativecccompopts="$nativecccompopts -D_THREAD_SAFE";;
+ *-*-openbsd*)
+ bytecccompopts="$bytecccompopts -pthread"
+ asppflags="$asppflags -pthread"
+ nativecccompopts="$nativecccompopts -pthread";;
+ esac
+ inf "Options for linking with POSIX threads: $pthread_link"
+ if sh ./hasgot $pthread_link sigwait; then
+ inf "sigwait() found"
+ echo "#define HAS_SIGWAIT" >> s.h
+ fi
+ else
+ inf "POSIX threads not found."
+ pthread_link=""
+ fi
+else
+ pthread_link=""
+fi
+echo "PTHREAD_LINK=$pthread_link" >> Makefile
+echo "PTHREAD_CAML_LINK=$pthread_caml_link" >> Makefile
+
+# Determine if the bytecode thread library is supported
+
+if test "$has_select" = "yes" \
+&& test "$has_setitimer" = "yes" \
+&& test "$has_gettimeofday" = "yes" \
+&& test "$has_wait" = "yes"; then
+ inf "Bytecode threads library supported."
+ otherlibraries="$otherlibraries threads"
+else
+ inf "Bytecode threads library not supported (missing system calls)"
+fi
+
+# Determine the location of X include files and libraries
+
+# If the user specified -x11include and/or -x11lib, these settings
+# are used. Otherwise, we check whether there is pkg-config, and take
+# the flags from there. Otherwise, we search the location.
+
+x11_include="not found"
+x11_link="not found"
+
+if test -z "$x11_include_dir" -a -z "$x11_lib_dir"; then
+ if pkg-config --exists x11 2>/dev/null; then
+ x11_include=`pkg-config --cflags x11`
+ x11_link=`pkg-config --libs x11`
+ fi
+fi
+
+if test "$x11_include" = "not found"; then
+ for dir in \
+ $x11_include_dir \
+ \
+ /usr/X11R7/include \
+ /usr/include/X11R7 \
+ /usr/local/X11R7/include \
+ /usr/local/include/X11R7 \
+ /opt/X11R7/include \
+ \
+ /usr/X11R6/include \
+ /usr/include/X11R6 \
+ /usr/local/X11R6/include \
+ /usr/local/include/X11R6 \
+ /opt/X11R6/include \
+ \
+ /usr/X11/include \
+ /usr/include/X11 \
+ /usr/local/X11/include \
+ /usr/local/include/X11 \
+ /opt/X11/include \
+ \
+ /usr/X11R5/include \
+ /usr/include/X11R5 \
+ /usr/local/X11R5/include \
+ /usr/local/include/X11R5 \
+ /usr/local/x11r5/include \
+ /opt/X11R5/include \
+ \
+ /usr/X11R4/include \
+ /usr/include/X11R4 \
+ /usr/local/X11R4/include \
+ /usr/local/include/X11R4 \
+ \
+ /usr/X386/include \
+ /usr/x386/include \
+ /usr/XFree86/include/X11 \
+ \
+ /usr/include \
+ /usr/local/include \
+ /usr/unsupported/include \
+ /usr/athena/include \
+ /usr/lpp/Xamples/include \
+ \
+ /usr/openwin/include \
+ /usr/openwin/share/include \
+ ; \
+ do
+ if test -f $dir/X11/X.h; then
+ x11_include_dir=$dir
+ x11_include="-I$dir"
+ break
+ fi
+ done
+
+ if test "$x11_include" = "not found"; then
+ x11_try_lib_dir=''
+ else
+ x11_try_lib_dir=`echo $x11_include_dir | sed -e 's|include|lib|'`
+ fi
+
+ for dir in \
+ $x11_lib_dir \
+ $x11_try_lib_dir \
+ \
+ /usr/X11R6/lib64 \
+ /usr/X11R6/lib \
+ /usr/lib/X11R6 \
+ /usr/local/X11R6/lib \
+ /usr/local/lib/X11R6 \
+ /opt/X11R6/lib \
+ \
+ /usr/X11/lib \
+ /usr/lib/X11 \
+ /usr/local/X11/lib \
+ /usr/local/lib/X11 \
+ /opt/X11/lib \
+ \
+ /usr/X11R5/lib \
+ /usr/lib/X11R5 \
+ /usr/local/X11R5/lib \
+ /usr/local/lib/X11R5 \
+ /usr/local/x11r5/lib \
+ /opt/X11R5/lib \
+ \
+ /usr/X11R4/lib \
+ /usr/lib/X11R4 \
+ /usr/local/X11R4/lib \
+ /usr/local/lib/X11R4 \
+ \
+ /usr/X386/lib \
+ /usr/x386/lib \
+ /usr/XFree86/lib/X11 \
+ \
+ /usr/lib64 \
+ /usr/lib \
+ /usr/local/lib \
+ /usr/unsupported/lib \
+ /usr/athena/lib \
+ /usr/lpp/Xamples/lib \
+ /lib/usr/lib/X11 \
+ \
+ /usr/openwin/lib \
+ /usr/openwin/share/lib \
+ \
+ /usr/lib/i386-linux-gnu \
+ /usr/lib/x86_64-linux-gnu \
+ ; \
+ do
+ if test -f $dir/libX11.a || \
+ test -f $dir/libX11.so || \
+ test -f $dir/libX11.dll.a || \
+ test -f $dir/libX11.dylib || \
+ test -f $dir/libX11.sa; then
+ if test $dir = /usr/lib; then
+ x11_link="-lX11"
+ else
+ x11_libs="-L$dir"
+ case "$target" in
+ *-kfreebsd*-gnu) x11_link="-L$dir -lX11";;
+ *-*-*bsd*) x11_link="-R$dir -L$dir -lX11";;
+ *) x11_link="-L$dir -lX11";;
+ esac
+ fi
+ break
+ fi
+ done
+fi
+
+if test "x11_include" != "not found"; then
+ if test "$x11_include" = "-I/usr/include"; then
+ x11_include=""
+ fi
+ if sh ./hasgot $x11_include $x11_link -i X11/Xlib.h XrmInitialize; then
+ inf "X11 works"
+ else
+ wrn "Cannot compile X11 program."
+ x11_include="not found"
+ fi
+fi
+
+has_graph=false
+if test "$x11_include" = "not found" || test "$x11_link" = "not found"
+then
+ wrn 'X11 not found, the "graph" library will not be supported.'
+ x11_include="not found"
+ x11_link="not found"
+else
+ inf "Options for compiling for X11: $x11_include"
+ inf "Options for linking with X11: $x11_link"
+ if test "$graph_wanted" = yes
+ then
+ has_graph=true
+ otherlibraries="$otherlibraries graph"
+ fi
+fi
+echo "X11_INCLUDES=$x11_include" >> Makefile
+echo "X11_LINK=$x11_link" >> Makefile
+
+# Look for BFD library
+
+if sh ./hasgot -DPACKAGE=ocaml -i bfd.h && \
+ sh ./hasgot -DPACKAGE=ocaml -lbfd -ldl -liberty -lz bfd_openr; then
+ inf "BFD library found."
+ echo "#define HAS_LIBBFD" >> s.h
+ echo "LIBBFD_LINK=-lbfd -ldl -liberty -lz" >> Makefile
+ echo LIBBFD_INCLUDE= >>Makefile
+elif sh ./hasgot -DPACKAGE=ocaml -I/opt/local/include -i bfd.h && \
+ sh ./hasgot -DPACKAGE=ocaml -L/opt/local/lib -lbfd -ldl \
+ -liberty -lz -lintl bfd_openr
+then
+ # MacOSX with binutils from MacPorts
+ inf "BFD library found."
+ echo "#define HAS_LIBBFD" >> s.h
+ echo "LIBBFD_LINK=-L/opt/local/lib -lbfd -ldl -liberty -lz -lintl" >> Makefile
+ echo LIBBFD_INCLUDE=-I/opt/local/include >>Makefile
+else
+ wrn "BFD library not found, 'objinfo' will be unable to display info" \
+ " on .cmxs files."
+ echo "LIBBFD_LINK=" >> Makefile
+ echo "LIBBFD_INCLUDE=" >> Makefile
+fi
+
+# Check whether assembler supports CFI directives
+
+asm_cfi_supported=false
+
+export as aspp
+
+if ! $with_cfi; then
+ echo "CFI support: disabled by command-line option -no-cfi"
+elif sh ./tryassemble cfi.S; then
+ echo "#define ASM_CFI_SUPPORTED" >> m.h
+ asm_cfi_supported=true
+ inf "Assembler supports CFI"
+else
+ inf "Assembler does not support CFI"
+fi
+
+if test "$with_frame_pointers" = "true"; then
+ case "$target,$cc" in
+ x86_64-*-linux*,gcc*)
+ nativecccompopts="$nativecccompopts -g -fno-omit-frame-pointer"
+ bytecccompopts="$bytecccompopts -g -fno-omit-frame-pointer"
+ nativecclinkopts="$nativecclinkopts -g"
+ echo "#define WITH_FRAME_POINTERS" >> m.h
+ ;;
+ *) err "Unsupported architecture with frame pointers";;
+ esac
+
+fi
+
+if $no_naked_pointers; then
+ echo "#define NO_NAKED_POINTERS" >> m.h
+fi
+
+# Finish generated files
+
+cclibs="$cclibs $mathlib"
+
+echo "BYTECC=$bytecc" >> Makefile
+echo "BYTECCCOMPOPTS=$bytecccompopts" >> Makefile
+echo "BYTECCLINKOPTS=$bytecclinkopts" >> Makefile
+echo "BYTECCLIBS=$cclibs $dllib $curseslibs $pthread_link" >> Makefile
+echo "BYTECCRPATH=$byteccrpath" >> Makefile
+echo "EXE=$exe" >> Makefile
+echo "SUPPORTS_SHARED_LIBRARIES=$shared_libraries_supported" >> Makefile
+echo "SHAREDCCCOMPOPTS=$sharedcccompopts" >> Makefile
+echo "MKSHAREDLIBRPATH=$mksharedlibrpath" >> Makefile
+echo "NATDYNLINKOPTS=$natdynlinkopts" >> Makefile
+cat >> Makefile <<EOF
+SYSLIB=-l\$(1)
+#ml let syslib x = "-l"^x;;
+
+### How to build a static library
+MKLIB=${TOOLPREF}ar rc \$(1) \$(2); ${TOOLPREF}ranlib \$(1)
+#ml let mklib out files opts =
+#ml Printf.sprintf "${TOOLPREF}ar rc %s %s %s;
+#ml ${TOOLPREF}ranlib %s" out opts files out;;
+EOF
+echo "ARCH=$arch" >> Makefile
+echo "MODEL=$model" >> Makefile
+echo "SYSTEM=$system" >> Makefile
+echo "NATIVECC=$nativecc" >> Makefile
+echo "NATIVECCCOMPOPTS=$nativecccompopts" >> Makefile
+echo "NATIVECCPROFOPTS=$nativeccprofopts" >> Makefile
+echo "NATIVECCLINKOPTS=$nativecclinkopts" >> Makefile
+echo "NATIVECCRPATH=$nativeccrpath" >> Makefile
+echo "NATIVECCLIBS=$cclibs $dllib" >> Makefile
+echo "ASM=$as" >> Makefile
+echo "ASPP=$aspp" >> Makefile
+echo "ASPPPROFFLAGS=$asppprofflags" >> Makefile
+echo "PROFILING=$profiling" >> Makefile
+echo "DYNLINKOPTS=$dllib" >> Makefile
+echo "OTHERLIBRARIES=$otherlibraries" >> Makefile
+echo "CC_PROFILE=$cc_profile" >> Makefile
+echo "SYSTHREAD_SUPPORT=$systhread_support" >> Makefile
+echo "PARTIALLD=$partialld" >> Makefile
+echo "PACKLD=\$(PARTIALLD) \$(NATIVECCLINKOPTS) -o " \
+ | sed -e 's/ $/\\ /' >> Makefile
+echo "DLLCCCOMPOPTS=$dllccompopts" >> Makefile
+echo "IFLEXDIR=$iflexdir" >> Makefile
+echo "O=o" >> Makefile
+echo "A=a" >> Makefile
+echo "SO=$SO" >> Makefile
+echo "EXT_OBJ=.o" >> Makefile
+echo "EXT_ASM=.s" >> Makefile
+echo "EXT_LIB=.a" >> Makefile
+echo "EXT_DLL=.$SO" >> Makefile
+echo "EXTRALIBS=" >> Makefile
+echo "CCOMPTYPE=cc" >> Makefile
+echo "TOOLCHAIN=$TOOLCHAIN" >> Makefile
+echo "NATDYNLINK=$natdynlink" >> Makefile
+echo "CMXS=$cmxs" >> Makefile
+echo "MKEXE=$mkexe" >> Makefile
+echo "MKEXEDEBUGFLAG=$mkexedebugflag" >> Makefile
+echo "MKDLL=$mksharedlib" >> Makefile
+echo "MKMAINDLL=$mkmaindll" >> Makefile
+echo "RUNTIMED=${debugruntime}" >>Makefile
+if $shared_libraries_supported; then
+ echo "SHARED=shared" >>Makefile
+else
+ echo "SHARED=noshared" >>Makefile
+fi
+echo "WITH_DEBUGGER=${with_debugger}" >>Makefile
+echo "WITH_OCAMLDOC=${with_ocamldoc}" >>Makefile
+echo "WITH_OCAMLBUILD=${with_ocamlbuild}" >>Makefile
+echo "ASM_CFI_SUPPORTED=$asm_cfi_supported" >> Makefile
+echo "WITH_FRAME_POINTERS=$with_frame_pointers" >> Makefile
+echo "TARGET=$target" >> Makefile
+echo "HOST=$host" >> Makefile
+if [ "$ostype" = Cygwin ]; then
+ echo "DIFF=diff -q --strip-trailing-cr" >>Makefile
+fi
+
+
+rm -f tst hasgot.c
+rm -f ../m.h ../s.h ../Makefile
+mv m.h s.h Makefile ..
+
+# Print a summary
+
+inf
+inf "** Configuration summary **"
+inf
+inf "Directories where OCaml will be installed:"
+inf " binaries.................. $bindir"
+inf " standard library.......... $libdir"
+inf " manual pages.............. $mandir (with extension .$manext)"
+
+inf "Configuration for the bytecode compiler:"
+inf " C compiler used........... $bytecc"
+inf " options for compiling..... $bytecccompopts"
+inf " options for linking....... $bytecclinkopts $cclibs $dllib" \
+ "$curseslibs $pthread_link"
+if $shared_libraries_supported; then
+inf " shared libraries are supported"
+inf " options for compiling..... $sharedcccompopts $bytecccompopts"
+inf " command for building...... $mksharedlib -o lib.so" \
+ "$mksharedlibrpath/a/path objs"
+else
+inf " shared libraries not supported"
+fi
+
+inf "Configuration for the native-code compiler:"
+if test "$arch" = "none"; then
+ inf " (not supported on this platform)"
+else
+ if test "$model" = "default"; then
+ inf " hardware architecture..... $arch"
+ else
+ inf " hardware architecture..... $arch ($model)"
+ fi
+ if test "$system" = "unknown"; then : ; else
+ inf " OS variant................ $system"
+ fi
+ inf " C compiler used........... $nativecc"
+ inf " options for compiling..... $nativecccompopts"
+ inf " options for linking....... $nativecclinkopts $cclibs"
+ inf " assembler ................ $as"
+ inf " preprocessed assembler ... $aspp"
+ if test "$asm_cfi_supported" = "true"; then
+ inf " assembler supports CFI ... yes"
+ else
+ inf " assembler supports CFI ... no"
+ fi
+ if test "$with_frame_pointers" = "true"; then
+ inf " with frame pointers....... yes"
+ else
+ inf " with frame pointers....... no"
+ fi
+ if $no_naked_pointers; then
+ inf " naked pointers forbidden.. yes"
+ else
+ inf " naked pointers forbidden.. no"
+ fi
+ inf " native dynlink ........... $natdynlink"
+ if test "$profiling" = "prof"; then
+ inf " profiling with gprof ..... supported"
+ else
+ inf " profiling with gprof ..... not supported"
+ fi
+fi
+
+if test "$with_debugger" = "ocamldebugger"; then
+ inf "Source-level replay debugger: supported"
+else
+ inf "Source-level replay debugger: not supported"
+fi
+
+if test "$debugruntime" = "runtimed"; then
+ inf "Debug runtime will be compiled and installed"
+fi
+
+inf "Additional libraries supported:"
+inf " $otherlibraries"
+
+inf "Configuration for the \"num\" library:"
+inf " target architecture ...... $bng_arch (asm level $bng_asm_level)"
+
+if $has_graph; then
+inf "Configuration for the \"graph\" library:"
+inf " options for compiling .... $x11_include"
+inf " options for linking ...... $x11_link"
+else
+inf "The \"graph\" library: not supported"
+fi
+
+inf
+inf "** OCaml configuration completed successfully **"
+inf
+
+if test ! -z "$MACOSX_DEPLOYMENT_TARGET"; then
+ wrn "The environment variable MACOSX_DEPLOYMENT_TARGET is set.\n" \
+ "This will probably prevent compiling the OCaml system."
+fi
diff --git a/debugger/.depend b/debugger/.depend
new file mode 100644
index 0000000000..c9a56ac144
--- /dev/null
+++ b/debugger/.depend
@@ -0,0 +1,215 @@
+breakpoints.cmi : primitives.cmi ../bytecomp/instruct.cmi
+checkpoints.cmi : primitives.cmi debugcom.cmi
+command_line.cmi :
+debugcom.cmi : primitives.cmi
+debugger_config.cmi :
+dynlink.cmi :
+eval.cmi : ../typing/types.cmi ../typing/path.cmi parser_aux.cmi \
+ ../parsing/longident.cmi ../bytecomp/instruct.cmi ../typing/ident.cmi \
+ ../typing/env.cmi debugcom.cmi
+events.cmi : ../bytecomp/instruct.cmi
+exec.cmi :
+frames.cmi : primitives.cmi ../bytecomp/instruct.cmi
+history.cmi :
+input_handling.cmi : primitives.cmi
+int64ops.cmi :
+lexer.cmi : parser.cmi
+loadprinter.cmi : ../parsing/longident.cmi dynlink.cmi
+parameters.cmi :
+parser_aux.cmi : primitives.cmi ../parsing/longident.cmi
+parser.cmi : parser_aux.cmi ../parsing/longident.cmi
+pattern_matching.cmi : ../typing/typedtree.cmi parser_aux.cmi debugcom.cmi
+pos.cmi : ../bytecomp/instruct.cmi
+primitives.cmi : $(UNIXDIR)/unix.cmi
+printval.cmi : ../typing/types.cmi ../typing/path.cmi parser_aux.cmi \
+ ../typing/env.cmi debugcom.cmi
+program_loading.cmi : primitives.cmi
+program_management.cmi :
+question.cmi :
+show_information.cmi : ../bytecomp/instruct.cmi
+show_source.cmi : ../bytecomp/instruct.cmi
+source.cmi :
+symbols.cmi : ../bytecomp/instruct.cmi
+time_travel.cmi : primitives.cmi
+trap_barrier.cmi :
+unix_tools.cmi : $(UNIXDIR)/unix.cmi
+breakpoints.cmo : symbols.cmi primitives.cmi pos.cmi \
+ ../bytecomp/instruct.cmi exec.cmi debugcom.cmi checkpoints.cmi \
+ breakpoints.cmi
+breakpoints.cmx : symbols.cmx primitives.cmx pos.cmx \
+ ../bytecomp/instruct.cmx exec.cmx debugcom.cmx checkpoints.cmx \
+ breakpoints.cmi
+checkpoints.cmo : primitives.cmi int64ops.cmi debugcom.cmi checkpoints.cmi
+checkpoints.cmx : primitives.cmx int64ops.cmx debugcom.cmx checkpoints.cmi
+command_line.cmo : unix_tools.cmi $(UNIXDIR)/unix.cmi \
+ ../typing/types.cmi time_travel.cmi symbols.cmi source.cmi \
+ show_source.cmi show_information.cmi question.cmi program_management.cmi \
+ program_loading.cmi printval.cmi primitives.cmi pos.cmi parser_aux.cmi \
+ parser.cmi parameters.cmi ../utils/misc.cmi ../parsing/longident.cmi \
+ ../parsing/location.cmi loadprinter.cmi lexer.cmi int64ops.cmi \
+ ../bytecomp/instruct.cmi input_handling.cmi history.cmi frames.cmi \
+ events.cmi eval.cmi ../typing/envaux.cmi ../typing/env.cmi \
+ debugger_config.cmi debugcom.cmi ../typing/ctype.cmi ../utils/config.cmi \
+ checkpoints.cmi breakpoints.cmi command_line.cmi
+command_line.cmx : unix_tools.cmx $(UNIXDIR)/unix.cmx \
+ ../typing/types.cmx time_travel.cmx symbols.cmx source.cmx \
+ show_source.cmx show_information.cmx question.cmx program_management.cmx \
+ program_loading.cmx printval.cmx primitives.cmx pos.cmx parser_aux.cmi \
+ parser.cmx parameters.cmx ../utils/misc.cmx ../parsing/longident.cmx \
+ ../parsing/location.cmx loadprinter.cmx lexer.cmx int64ops.cmx \
+ ../bytecomp/instruct.cmx input_handling.cmx history.cmx frames.cmx \
+ events.cmx eval.cmx ../typing/envaux.cmx ../typing/env.cmx \
+ debugger_config.cmx debugcom.cmx ../typing/ctype.cmx ../utils/config.cmx \
+ checkpoints.cmx breakpoints.cmx command_line.cmi
+debugcom.cmo : primitives.cmi ../utils/misc.cmi int64ops.cmi \
+ input_handling.cmi debugcom.cmi
+debugcom.cmx : primitives.cmx ../utils/misc.cmx int64ops.cmx \
+ input_handling.cmx debugcom.cmi
+debugger_config.cmo : int64ops.cmi debugger_config.cmi
+debugger_config.cmx : int64ops.cmx debugger_config.cmi
+dynlink.cmo : ../bytecomp/symtable.cmi ../bytecomp/opcodes.cmo \
+ ../utils/misc.cmi ../bytecomp/meta.cmi ../bytecomp/dll.cmi \
+ ../utils/consistbl.cmi ../utils/config.cmi ../bytecomp/cmo_format.cmi \
+ ../typing/cmi_format.cmi dynlink.cmi
+dynlink.cmx : ../bytecomp/symtable.cmx ../bytecomp/opcodes.cmx \
+ ../utils/misc.cmx ../bytecomp/meta.cmx ../bytecomp/dll.cmx \
+ ../utils/consistbl.cmx ../utils/config.cmx ../bytecomp/cmo_format.cmi \
+ ../typing/cmi_format.cmx dynlink.cmi
+eval.cmo : ../typing/types.cmi ../bytecomp/symtable.cmi ../typing/subst.cmi \
+ printval.cmi ../typing/printtyp.cmi ../typing/predef.cmi \
+ ../typing/path.cmi parser_aux.cmi ../utils/misc.cmi \
+ ../parsing/longident.cmi ../bytecomp/instruct.cmi ../typing/ident.cmi \
+ frames.cmi ../typing/env.cmi debugcom.cmi ../typing/ctype.cmi \
+ ../typing/btype.cmi eval.cmi
+eval.cmx : ../typing/types.cmx ../bytecomp/symtable.cmx ../typing/subst.cmx \
+ printval.cmx ../typing/printtyp.cmx ../typing/predef.cmx \
+ ../typing/path.cmx parser_aux.cmi ../utils/misc.cmx \
+ ../parsing/longident.cmx ../bytecomp/instruct.cmx ../typing/ident.cmx \
+ frames.cmx ../typing/env.cmx debugcom.cmx ../typing/ctype.cmx \
+ ../typing/btype.cmx eval.cmi
+events.cmo : ../parsing/location.cmi ../bytecomp/instruct.cmi events.cmi
+events.cmx : ../parsing/location.cmx ../bytecomp/instruct.cmx events.cmi
+exec.cmo : exec.cmi
+exec.cmx : exec.cmi
+frames.cmo : symbols.cmi ../utils/misc.cmi ../bytecomp/instruct.cmi \
+ events.cmi debugcom.cmi frames.cmi
+frames.cmx : symbols.cmx ../utils/misc.cmx ../bytecomp/instruct.cmx \
+ events.cmx debugcom.cmx frames.cmi
+history.cmo : primitives.cmi int64ops.cmi debugger_config.cmi \
+ checkpoints.cmi history.cmi
+history.cmx : primitives.cmx int64ops.cmx debugger_config.cmx \
+ checkpoints.cmx history.cmi
+input_handling.cmo : $(UNIXDIR)/unix.cmi primitives.cmi \
+ input_handling.cmi
+input_handling.cmx : $(UNIXDIR)/unix.cmx primitives.cmx \
+ input_handling.cmi
+int64ops.cmo : int64ops.cmi
+int64ops.cmx : int64ops.cmi
+lexer.cmo : parser.cmi lexer.cmi
+lexer.cmx : parser.cmx lexer.cmi
+loadprinter.cmo : ../typing/types.cmi ../bytecomp/symtable.cmi printval.cmi \
+ ../typing/printtyp.cmi ../typing/path.cmi ../utils/misc.cmi \
+ ../parsing/longident.cmi ../typing/ident.cmi ../typing/env.cmi \
+ dynlink.cmi ../typing/ctype.cmi ../utils/config.cmi loadprinter.cmi
+loadprinter.cmx : ../typing/types.cmx ../bytecomp/symtable.cmx printval.cmx \
+ ../typing/printtyp.cmx ../typing/path.cmx ../utils/misc.cmx \
+ ../parsing/longident.cmx ../typing/ident.cmx ../typing/env.cmx \
+ dynlink.cmx ../typing/ctype.cmx ../utils/config.cmx loadprinter.cmi
+main.cmo : unix_tools.cmi $(UNIXDIR)/unix.cmi time_travel.cmi \
+ show_information.cmi question.cmi program_management.cmi primitives.cmi \
+ parameters.cmi ../utils/misc.cmi input_handling.cmi frames.cmi exec.cmi \
+ ../typing/env.cmi debugger_config.cmi ../utils/config.cmi \
+ command_line.cmi ../typing/cmi_format.cmi ../utils/clflags.cmi \
+ checkpoints.cmi
+main.cmx : unix_tools.cmx $(UNIXDIR)/unix.cmx time_travel.cmx \
+ show_information.cmx question.cmx program_management.cmx primitives.cmx \
+ parameters.cmx ../utils/misc.cmx input_handling.cmx frames.cmx exec.cmx \
+ ../typing/env.cmx debugger_config.cmx ../utils/config.cmx \
+ command_line.cmx ../typing/cmi_format.cmx ../utils/clflags.cmx \
+ checkpoints.cmx
+parameters.cmo : primitives.cmi ../typing/envaux.cmi debugger_config.cmi \
+ ../utils/config.cmi parameters.cmi
+parameters.cmx : primitives.cmx ../typing/envaux.cmx debugger_config.cmx \
+ ../utils/config.cmx parameters.cmi
+parser.cmo : parser_aux.cmi ../parsing/longident.cmi int64ops.cmi \
+ input_handling.cmi parser.cmi
+parser.cmx : parser_aux.cmi ../parsing/longident.cmx int64ops.cmx \
+ input_handling.cmx parser.cmi
+pattern_matching.cmo : ../typing/typedtree.cmi parser_aux.cmi \
+ ../utils/misc.cmi debugger_config.cmi debugcom.cmi ../typing/ctype.cmi \
+ pattern_matching.cmi
+pattern_matching.cmx : ../typing/typedtree.cmx parser_aux.cmi \
+ ../utils/misc.cmx debugger_config.cmx debugcom.cmx ../typing/ctype.cmx \
+ pattern_matching.cmi
+pos.cmo : source.cmi primitives.cmi ../parsing/location.cmi \
+ ../bytecomp/instruct.cmi pos.cmi
+pos.cmx : source.cmx primitives.cmx ../parsing/location.cmx \
+ ../bytecomp/instruct.cmx pos.cmi
+primitives.cmo : $(UNIXDIR)/unix.cmi primitives.cmi
+primitives.cmx : $(UNIXDIR)/unix.cmx primitives.cmi
+printval.cmo : ../typing/types.cmi ../bytecomp/symtable.cmi \
+ ../typing/printtyp.cmi ../typing/path.cmi parser_aux.cmi \
+ ../typing/outcometree.cmi ../typing/oprint.cmi \
+ ../toplevel/genprintval.cmi debugcom.cmi printval.cmi
+printval.cmx : ../typing/types.cmx ../bytecomp/symtable.cmx \
+ ../typing/printtyp.cmx ../typing/path.cmx parser_aux.cmi \
+ ../typing/outcometree.cmi ../typing/oprint.cmx \
+ ../toplevel/genprintval.cmx debugcom.cmx printval.cmi
+program_loading.cmo : unix_tools.cmi $(UNIXDIR)/unix.cmi \
+ primitives.cmi parameters.cmi input_handling.cmi debugger_config.cmi \
+ program_loading.cmi
+program_loading.cmx : unix_tools.cmx $(UNIXDIR)/unix.cmx \
+ primitives.cmx parameters.cmx input_handling.cmx debugger_config.cmx \
+ program_loading.cmi
+program_management.cmo : unix_tools.cmi $(UNIXDIR)/unix.cmi \
+ time_travel.cmi symbols.cmi question.cmi program_loading.cmi \
+ primitives.cmi parameters.cmi int64ops.cmi input_handling.cmi history.cmi \
+ ../typing/envaux.cmi debugger_config.cmi ../utils/config.cmi \
+ breakpoints.cmi program_management.cmi
+program_management.cmx : unix_tools.cmx $(UNIXDIR)/unix.cmx \
+ time_travel.cmx symbols.cmx question.cmx program_loading.cmx \
+ primitives.cmx parameters.cmx int64ops.cmx input_handling.cmx history.cmx \
+ ../typing/envaux.cmx debugger_config.cmx ../utils/config.cmx \
+ breakpoints.cmx program_management.cmi
+question.cmo : primitives.cmi lexer.cmi input_handling.cmi question.cmi
+question.cmx : primitives.cmx lexer.cmx input_handling.cmx question.cmi
+show_information.cmo : symbols.cmi source.cmi show_source.cmi printval.cmi \
+ parameters.cmi ../utils/misc.cmi ../bytecomp/instruct.cmi frames.cmi \
+ events.cmi debugcom.cmi checkpoints.cmi breakpoints.cmi \
+ show_information.cmi
+show_information.cmx : symbols.cmx source.cmx show_source.cmx printval.cmx \
+ parameters.cmx ../utils/misc.cmx ../bytecomp/instruct.cmx frames.cmx \
+ events.cmx debugcom.cmx checkpoints.cmx breakpoints.cmx \
+ show_information.cmi
+show_source.cmo : source.cmi primitives.cmi parameters.cmi \
+ ../parsing/location.cmi ../bytecomp/instruct.cmi events.cmi \
+ debugger_config.cmi show_source.cmi
+show_source.cmx : source.cmx primitives.cmx parameters.cmx \
+ ../parsing/location.cmx ../bytecomp/instruct.cmx events.cmx \
+ debugger_config.cmx show_source.cmi
+source.cmo : primitives.cmi ../utils/misc.cmi debugger_config.cmi \
+ ../utils/config.cmi source.cmi
+source.cmx : primitives.cmx ../utils/misc.cmx debugger_config.cmx \
+ ../utils/config.cmx source.cmi
+symbols.cmo : ../bytecomp/symtable.cmi program_loading.cmi \
+ ../bytecomp/instruct.cmi events.cmi debugger_config.cmi debugcom.cmi \
+ checkpoints.cmi ../bytecomp/bytesections.cmi symbols.cmi
+symbols.cmx : ../bytecomp/symtable.cmx program_loading.cmx \
+ ../bytecomp/instruct.cmx events.cmx debugger_config.cmx debugcom.cmx \
+ checkpoints.cmx ../bytecomp/bytesections.cmx symbols.cmi
+time_travel.cmo : trap_barrier.cmi symbols.cmi question.cmi \
+ program_loading.cmi primitives.cmi ../utils/misc.cmi int64ops.cmi \
+ ../bytecomp/instruct.cmi input_handling.cmi exec.cmi events.cmi \
+ debugger_config.cmi debugcom.cmi checkpoints.cmi breakpoints.cmi \
+ time_travel.cmi
+time_travel.cmx : trap_barrier.cmx symbols.cmx question.cmx \
+ program_loading.cmx primitives.cmx ../utils/misc.cmx int64ops.cmx \
+ ../bytecomp/instruct.cmx input_handling.cmx exec.cmx events.cmx \
+ debugger_config.cmx debugcom.cmx checkpoints.cmx breakpoints.cmx \
+ time_travel.cmi
+trap_barrier.cmo : exec.cmi debugcom.cmi checkpoints.cmi trap_barrier.cmi
+trap_barrier.cmx : exec.cmx debugcom.cmx checkpoints.cmx trap_barrier.cmi
+unix_tools.cmo : $(UNIXDIR)/unix.cmi primitives.cmi ../utils/misc.cmi \
+ unix_tools.cmi
+unix_tools.cmx : $(UNIXDIR)/unix.cmx primitives.cmx ../utils/misc.cmx \
+ unix_tools.cmi
diff --git a/debugger/.ignore b/debugger/.ignore
new file mode 100644
index 0000000000..45eec7cceb
--- /dev/null
+++ b/debugger/.ignore
@@ -0,0 +1,7 @@
+lexer.ml
+parser.ml
+parser.mli
+ocamldebug
+ocamldebug.exe
+dynlink.ml
+dynlink.mli
diff --git a/debugger/Makefile b/debugger/Makefile
new file mode 100644
index 0000000000..75f4aa8ebd
--- /dev/null
+++ b/debugger/Makefile
@@ -0,0 +1,14 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+UNIXDIR=../otherlibs/$(UNIXLIB)
+include Makefile.shared
diff --git a/debugger/Makefile.nt b/debugger/Makefile.nt
new file mode 100644
index 0000000000..4182c7c77b
--- /dev/null
+++ b/debugger/Makefile.nt
@@ -0,0 +1,14 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+UNIXDIR=../otherlibs/win32unix
+include Makefile.shared
diff --git a/debugger/Makefile.shared b/debugger/Makefile.shared
new file mode 100644
index 0000000000..f3859c63d2
--- /dev/null
+++ b/debugger/Makefile.shared
@@ -0,0 +1,129 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+
+CAMLC=$(CAMLRUN) ../ocamlc -nostdlib -I ../stdlib
+COMPFLAGS=-warn-error A -safe-string $(INCLUDES)
+LINKFLAGS=-linkall -I $(UNIXDIR)
+YACCFLAGS=
+CAMLLEX=$(CAMLRUN) ../boot/ocamllex
+CAMLDEP=$(CAMLRUN) ../tools/ocamldep
+DEPFLAGS=$(INCLUDES)
+
+INSTALL_BINDIR=$(DESTDIR)$(BINDIR)
+
+INCLUDES=\
+ -I ../utils -I ../parsing -I ../typing -I ../bytecomp -I ../toplevel \
+ -I $(UNIXDIR)
+
+OTHEROBJS=\
+ $(UNIXDIR)/unix.cma \
+ ../utils/misc.cmo ../utils/config.cmo ../utils/tbl.cmo \
+ ../utils/clflags.cmo ../utils/consistbl.cmo ../utils/warnings.cmo \
+ ../parsing/location.cmo ../parsing/longident.cmo ../parsing/docstrings.cmo \
+ ../parsing/ast_helper.cmo ../parsing/ast_mapper.cmo \
+ ../typing/ident.cmo ../typing/path.cmo ../typing/types.cmo \
+ ../typing/btype.cmo ../typing/primitive.cmo ../typing/typedtree.cmo \
+ ../typing/subst.cmo ../typing/predef.cmo \
+ ../typing/datarepr.cmo ../typing/cmi_format.cmo ../typing/env.cmo \
+ ../typing/oprint.cmo \
+ ../typing/ctype.cmo ../typing/printtyp.cmo ../typing/mtype.cmo \
+ ../typing/envaux.cmo \
+ ../bytecomp/runtimedef.cmo ../bytecomp/bytesections.cmo \
+ ../bytecomp/dll.cmo ../bytecomp/meta.cmo ../bytecomp/symtable.cmo \
+ ../bytecomp/opcodes.cmo \
+ ../toplevel/genprintval.cmo
+
+
+OBJS=\
+ dynlink.cmo \
+ int64ops.cmo \
+ primitives.cmo \
+ unix_tools.cmo \
+ debugger_config.cmo \
+ parameters.cmo \
+ lexer.cmo \
+ input_handling.cmo \
+ question.cmo \
+ debugcom.cmo \
+ exec.cmo \
+ source.cmo \
+ pos.cmo \
+ checkpoints.cmo \
+ events.cmo \
+ program_loading.cmo \
+ symbols.cmo \
+ breakpoints.cmo \
+ trap_barrier.cmo \
+ history.cmo \
+ printval.cmo \
+ show_source.cmo \
+ time_travel.cmo \
+ program_management.cmo \
+ frames.cmo \
+ eval.cmo \
+ show_information.cmo \
+ loadprinter.cmo \
+ parser.cmo \
+ command_line.cmo \
+ main.cmo
+
+all: ocamldebug$(EXE)
+
+ocamldebug$(EXE): $(OBJS) $(OTHEROBJS)
+ $(CAMLC) $(LINKFLAGS) -o ocamldebug$(EXE) -linkall $(OTHEROBJS) $(OBJS)
+
+install:
+ cp ocamldebug$(EXE) $(INSTALL_BINDIR)/ocamldebug$(EXE)
+
+clean::
+ rm -f ocamldebug$(EXE)
+ rm -f *.cmo *.cmi
+
+.SUFFIXES:
+.SUFFIXES: .ml .cmo .mli .cmi
+
+.ml.cmo:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.mli.cmi:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+depend: beforedepend
+ $(CAMLDEP) $(DEPFLAGS) *.mli *.ml \
+ | sed -e 's,$(UNIXDIR)/,$$(UNIXDIR)/,' > .depend
+
+lexer.ml: lexer.mll
+ $(CAMLLEX) lexer.mll
+clean::
+ rm -f lexer.ml
+beforedepend:: lexer.ml
+
+parser.ml parser.mli: parser.mly
+ $(CAMLYACC) parser.mly
+clean::
+ rm -f parser.ml parser.mli
+beforedepend:: parser.ml parser.mli
+
+dynlink.ml: ../otherlibs/dynlink/dynlink.ml
+ grep -v 'REMOVE_ME for ../../debugger/dynlink.ml' \
+ ../otherlibs/dynlink/dynlink.ml >dynlink.ml
+dynlink.mli: ../otherlibs/dynlink/dynlink.mli
+ cp ../otherlibs/dynlink/dynlink.mli .
+clean::
+ rm -f dynlink.ml dynlink.mli
+beforedepend:: dynlink.ml dynlink.mli
+
+include .depend
diff --git a/debugger/breakpoints.ml b/debugger/breakpoints.ml
new file mode 100644
index 0000000000..de4c95bd5a
--- /dev/null
+++ b/debugger/breakpoints.ml
@@ -0,0 +1,225 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(******************************* Breakpoints ***************************)
+
+open Checkpoints
+open Debugcom
+open Instruct
+open Primitives
+open Printf
+
+(*** Debugging. ***)
+let debug_breakpoints = ref false
+
+(*** Data. ***)
+
+(* Number of the last added breakpoint. *)
+let breakpoint_number = ref 0
+
+(* Breakpoint number -> event. *)
+let breakpoints = ref ([] : (int * debug_event) list)
+
+(* Program counter -> breakpoint count. *)
+let positions = ref ([] : (int * int ref) list)
+
+(* Versions of the breakpoint list. *)
+let current_version = ref 0
+let max_version = ref 0
+
+(*** Miscellaneous. ***)
+
+(* Mark breakpoints as installed in current checkpoint. *)
+let copy_breakpoints () =
+ !current_checkpoint.c_breakpoints <- !positions;
+ !current_checkpoint.c_breakpoint_version <- !current_version
+
+(* Announce a new version of the breakpoint list. *)
+let new_version () =
+ incr max_version;
+ current_version := !max_version
+
+(*** Information about breakpoints. ***)
+
+let breakpoints_count () =
+ List.length !breakpoints
+
+(* List of breakpoints at `pc'. *)
+let rec breakpoints_at_pc pc =
+ begin try
+ let ev = Symbols.event_at_pc pc in
+ match ev.ev_repr with
+ Event_child {contents = pc'} -> breakpoints_at_pc pc'
+ | _ -> []
+ with Not_found ->
+ []
+ end
+ @
+ List.map fst (List.filter (function (_, {ev_pos = pos}) -> pos = pc)
+ !breakpoints)
+
+(* Is there a breakpoint at `pc' ? *)
+let breakpoint_at_pc pc =
+ breakpoints_at_pc pc <> []
+
+(*** Set and remove breakpoints ***)
+
+(* Remove all breakpoints. *)
+let remove_breakpoints pos =
+ if !debug_breakpoints then
+ (print_string "Removing breakpoints..."; print_newline ());
+ List.iter
+ (function (pos, _) ->
+ if !debug_breakpoints then begin
+ print_int pos;
+ print_newline()
+ end;
+ reset_instr pos;
+ Symbols.set_event_at_pc pos)
+ pos
+
+(* Set all breakpoints. *)
+let set_breakpoints pos =
+ if !debug_breakpoints then
+ (print_string "Setting breakpoints..."; print_newline ());
+ List.iter
+ (function (pos, _) ->
+ if !debug_breakpoints then begin
+ print_int pos;
+ print_newline()
+ end;
+ set_breakpoint pos)
+ pos
+
+(* Ensure the current version in installed in current checkpoint. *)
+let update_breakpoints () =
+ if !debug_breakpoints then begin
+ prerr_string "Updating breakpoints... ";
+ prerr_int !current_checkpoint.c_breakpoint_version;
+ prerr_string " ";
+ prerr_int !current_version;
+ prerr_endline ""
+ end;
+ if !current_checkpoint.c_breakpoint_version <> !current_version then
+ Exec.protect
+ (function () ->
+ remove_breakpoints !current_checkpoint.c_breakpoints;
+ set_breakpoints !positions;
+ copy_breakpoints ())
+
+let change_version version pos =
+ Exec.protect
+ (function () ->
+ current_version := version;
+ positions := pos)
+
+(* Execute given function with no breakpoint in current checkpoint. *)
+(* --- `goto' runs faster this way (does not stop on each breakpoint). *)
+let execute_without_breakpoints f =
+ let version = !current_version
+ and pos = !positions
+ in
+ change_version 0 [];
+ try
+ f ();
+ change_version version pos
+ with
+ x ->
+ change_version version pos
+
+(* Add a position in the position list. *)
+(* Change version if necessary. *)
+let insert_position pos =
+ try
+ incr (List.assoc pos !positions)
+ with
+ Not_found ->
+ positions := (pos, ref 1) :: !positions;
+ new_version ()
+
+(* Remove a position in the position list. *)
+(* Change version if necessary. *)
+let remove_position pos =
+ let count = List.assoc pos !positions in
+ decr count;
+ if !count = 0 then begin
+ positions := List.remove_assoc pos !positions;
+ new_version ()
+ end
+
+(* Insert a new breakpoint in lists. *)
+let rec new_breakpoint =
+ function
+ {ev_repr = Event_child pc} ->
+ new_breakpoint (Symbols.any_event_at_pc !pc)
+ | event ->
+ Exec.protect
+ (function () ->
+ incr breakpoint_number;
+ insert_position event.ev_pos;
+ breakpoints := (!breakpoint_number, event) :: !breakpoints);
+ printf "Breakpoint %d at %d: %s" !breakpoint_number event.ev_pos
+ (Pos.get_desc event);
+ print_newline ()
+
+(* Remove a breakpoint from lists. *)
+let remove_breakpoint number =
+ try
+ let ev = List.assoc number !breakpoints in
+ let pos = ev.ev_pos in
+ Exec.protect
+ (function () ->
+ breakpoints := List.remove_assoc number !breakpoints;
+ remove_position pos;
+ printf "Removed breakpoint %d at %d: %s" number ev.ev_pos
+ (Pos.get_desc ev);
+ print_newline ()
+ )
+ with
+ Not_found ->
+ prerr_endline ("No breakpoint number " ^ (string_of_int number) ^ ".");
+ raise Not_found
+
+let remove_all_breakpoints () =
+ List.iter (function (number, _) -> remove_breakpoint number) !breakpoints
+
+(*** Temporary breakpoints. ***)
+
+(* Temporary breakpoint position. *)
+let temporary_breakpoint_position = ref (None : int option)
+
+(* Execute `funct' with a breakpoint added at `pc'. *)
+(* --- Used by `finish'. *)
+let exec_with_temporary_breakpoint pc funct =
+ let previous_version = !current_version in
+ let remove () =
+ temporary_breakpoint_position := None;
+ current_version := previous_version;
+ let count = List.assoc pc !positions in
+ decr count;
+ if !count = 0 then begin
+ positions := List.remove_assoc pc !positions;
+ reset_instr pc;
+ Symbols.set_event_at_pc pc
+ end
+
+ in
+ Exec.protect (function () -> insert_position pc);
+ temporary_breakpoint_position := Some pc;
+ try
+ funct ();
+ Exec.protect remove
+ with
+ x ->
+ Exec.protect remove;
+ raise x
diff --git a/debugger/breakpoints.mli b/debugger/breakpoints.mli
new file mode 100644
index 0000000000..ef5188529c
--- /dev/null
+++ b/debugger/breakpoints.mli
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(******************************* Breakpoints ***************************)
+
+open Primitives
+open Instruct
+
+(*** Debugging. ***)
+val debug_breakpoints : bool ref
+
+(*** Information about breakpoints. ***)
+
+val breakpoints_count : unit -> int
+
+(* Breakpoint number -> debug_event_kind. *)
+val breakpoints : (int * debug_event) list ref
+
+(* Is there a breakpoint at `pc' ? *)
+val breakpoint_at_pc : int -> bool
+
+(* List of breakpoints at `pc'. *)
+val breakpoints_at_pc : int -> int list
+
+(*** Set and remove breakpoints ***)
+
+(* Ensure the current version in installed in current checkpoint. *)
+val update_breakpoints : unit -> unit
+
+(* Execute given function with no breakpoint in current checkpoint. *)
+(* --- `goto' run faster so (does not stop on each breakpoint). *)
+val execute_without_breakpoints : (unit -> unit) -> unit
+
+(* Insert a new breakpoint in lists. *)
+val new_breakpoint : debug_event -> unit
+
+(* Remove a breakpoint from lists. *)
+val remove_breakpoint : int -> unit
+
+val remove_all_breakpoints : unit -> unit
+
+(*** Temporary breakpoints. ***)
+
+(* Temporary breakpoint position. *)
+val temporary_breakpoint_position : int option ref
+
+(* Execute `funct' with a breakpoint added at `pc'. *)
+(* --- Used by `finish'. *)
+val exec_with_temporary_breakpoint : int -> (unit -> unit) -> unit
diff --git a/debugger/checkpoints.ml b/debugger/checkpoints.ml
new file mode 100644
index 0000000000..f0df238903
--- /dev/null
+++ b/debugger/checkpoints.ml
@@ -0,0 +1,83 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*************************** Checkpoints *******************************)
+
+open Int64ops
+open Debugcom
+open Primitives
+
+(*** A type for checkpoints. ***)
+
+type checkpoint_state =
+ C_stopped
+ | C_running of int64
+
+(* `c_valid' is true if and only if the corresponding
+ * process is connected to the debugger.
+ * `c_parent' is the checkpoint whose process is parent
+ * of the checkpoint one (`root' if no parent).
+ * c_pid = -2 for root pseudo-checkpoint.
+ * c_pid = 0 for ghost checkpoints.
+ * c_pid = -1 for kill checkpoints.
+ *)
+type checkpoint = {
+ mutable c_time : int64;
+ mutable c_pid : int;
+ mutable c_fd : io_channel;
+ mutable c_valid : bool;
+ mutable c_report : report option;
+ mutable c_state : checkpoint_state;
+ mutable c_parent : checkpoint;
+ mutable c_breakpoint_version : int;
+ mutable c_breakpoints : (int * int ref) list;
+ mutable c_trap_barrier : int
+ }
+
+(*** Pseudo-checkpoint `root'. ***)
+(* --- Parents of all checkpoints which have no parent. *)
+let rec root = {
+ c_time = _0;
+ c_pid = -2;
+ c_fd = std_io;
+ c_valid = false;
+ c_report = None;
+ c_state = C_stopped;
+ c_parent = root;
+ c_breakpoint_version = 0;
+ c_breakpoints = [];
+ c_trap_barrier = 0
+ }
+
+(*** Current state ***)
+let checkpoints =
+ ref ([] : checkpoint list)
+
+let current_checkpoint =
+ ref root
+
+let current_time () =
+ !current_checkpoint.c_time
+
+let current_report () =
+ !current_checkpoint.c_report
+
+let current_pc () =
+ match current_report () with
+ None | Some {rep_type = Exited | Uncaught_exc} -> None
+ | Some {rep_program_pointer = pc } -> Some pc
+
+let current_pc_sp () =
+ match current_report () with
+ None | Some {rep_type = Exited | Uncaught_exc} -> None
+ | Some {rep_program_pointer = pc; rep_stack_pointer = sp } -> Some (pc, sp)
diff --git a/debugger/checkpoints.mli b/debugger/checkpoints.mli
new file mode 100644
index 0000000000..95eaf1b088
--- /dev/null
+++ b/debugger/checkpoints.mli
@@ -0,0 +1,56 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(***************************** Checkpoints *****************************)
+
+open Primitives
+open Debugcom
+
+(*** A type for checkpoints. ***)
+
+type checkpoint_state =
+ C_stopped
+ | C_running of int64
+
+(* `c_valid' is true if and only if the corresponding
+ * process is connected to the debugger.
+ * `c_parent' is the checkpoint whose process is parent
+ * of the checkpoint one (`root' if no parent).
+ * c_pid = 2 for root pseudo-checkpoint.
+ * c_pid = 0 for ghost checkpoints.
+ * c_pid = -1 for kill checkpoints.
+ *)
+type checkpoint =
+ {mutable c_time : int64;
+ mutable c_pid : int;
+ mutable c_fd : io_channel;
+ mutable c_valid : bool;
+ mutable c_report : report option;
+ mutable c_state : checkpoint_state;
+ mutable c_parent : checkpoint;
+ mutable c_breakpoint_version : int;
+ mutable c_breakpoints : (int * int ref) list;
+ mutable c_trap_barrier : int}
+
+(*** Pseudo-checkpoint `root'. ***)
+(* --- Parents of all checkpoints which have no parent. *)
+val root : checkpoint
+
+(*** Current state ***)
+val checkpoints : checkpoint list ref
+val current_checkpoint : checkpoint ref
+
+val current_time : unit -> int64
+val current_report : unit -> report option
+val current_pc : unit -> int option
+val current_pc_sp : unit -> (int * int) option
diff --git a/debugger/command_line.ml b/debugger/command_line.ml
new file mode 100644
index 0000000000..4f79c12567
--- /dev/null
+++ b/debugger/command_line.ml
@@ -0,0 +1,1225 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(************************ Reading and executing commands ***************)
+
+open Int64ops
+open Format
+open Misc
+open Instruct
+open Unix
+open Debugger_config
+open Types
+open Primitives
+open Unix_tools
+open Parser
+open Parser_aux
+open Lexer
+open Input_handling
+open Question
+open Debugcom
+open Program_loading
+open Program_management
+open Lexing
+open Parameters
+open Show_source
+open Show_information
+open Time_travel
+open Events
+open Symbols
+open Source
+open Breakpoints
+open Checkpoints
+open Frames
+open Printval
+
+(** Instructions, variables and infos lists. **)
+type dbg_instruction =
+ { instr_name: string; (* Name of command *)
+ instr_prio: bool; (* Has priority *)
+ instr_action: formatter -> lexbuf -> unit;
+ (* What to do *)
+ instr_repeat: bool; (* Can be repeated *)
+ instr_help: string } (* Help message *)
+
+let instruction_list = ref ([] : dbg_instruction list)
+
+type dbg_variable =
+ { var_name: string; (* Name of variable *)
+ var_action: (lexbuf -> unit) * (formatter -> unit);
+ (* Reading, writing fns *)
+ var_help: string } (* Help message *)
+
+let variable_list = ref ([] : dbg_variable list)
+
+type dbg_info =
+ { info_name: string; (* Name of info *)
+ info_action: lexbuf -> unit; (* What to do *)
+ info_help: string } (* Help message *)
+
+let info_list = ref ([] : dbg_info list)
+
+(** Utilities. **)
+let error text =
+ eprintf "%s@." text;
+ raise Toplevel
+
+let check_not_windows feature =
+ match Sys.os_type with
+ | "Win32" ->
+ error ("\'"^feature^"\' feature not supported on Windows")
+ | _ ->
+ ()
+
+let eol =
+ end_of_line Lexer.lexeme
+
+let matching_elements list name instr =
+ List.filter (function a -> isprefix instr (name a)) !list
+
+let all_matching_instructions =
+ matching_elements instruction_list (fun i -> i.instr_name)
+
+(* itz 04-21-96 don't do priority completion in emacs mode *)
+(* XL 25-02-97 why? I find it very confusing. *)
+
+let matching_instructions instr =
+ let all = all_matching_instructions instr in
+ let prio = List.filter (fun i -> i.instr_prio) all in
+ if prio = [] then all else prio
+
+let matching_variables =
+ matching_elements variable_list (fun v -> v.var_name)
+
+let matching_infos =
+ matching_elements info_list (fun i -> i.info_name)
+
+let find_ident name matcher action alternative ppf lexbuf =
+ match identifier_or_eol Lexer.lexeme lexbuf with
+ | None -> alternative ppf
+ | Some ident ->
+ match matcher ident with
+ | [] -> error ("Unknown " ^ name ^ ".")
+ | [a] -> action a ppf lexbuf
+ | _ -> error ("Ambiguous " ^ name ^ ".")
+
+let find_variable action alternative ppf lexbuf =
+ find_ident "variable name" matching_variables action alternative ppf lexbuf
+
+let find_info action alternative ppf lexbuf =
+ find_ident "info command" matching_infos action alternative ppf lexbuf
+
+let add_breakpoint_at_pc pc =
+ try
+ new_breakpoint (any_event_at_pc pc)
+ with
+ | Not_found ->
+ eprintf "Can\'t add breakpoint at pc %i: no event there.@." pc;
+ raise Toplevel
+
+let add_breakpoint_after_pc pc =
+ let rec try_add n =
+ if n < 3 then begin
+ try
+ new_breakpoint (any_event_at_pc (pc + n * 4))
+ with
+ | Not_found ->
+ try_add (n+1)
+ end else begin
+ error
+ "Can\'t add breakpoint at beginning of function: no event there"
+ end
+ in try_add 0
+
+let module_of_longident id =
+ match id with
+ | Some x -> Some (String.concat "." (Longident.flatten x))
+ | None -> None
+
+let convert_module mdle =
+ match mdle with
+ | Some m ->
+ (* Strip .ml extension if any, and capitalize *)
+ String.capitalize_ascii(if Filename.check_suffix m ".ml"
+ then Filename.chop_suffix m ".ml"
+ else m)
+ | None ->
+ try
+ (get_current_event ()).ev_module
+ with
+ | Not_found ->
+ error "Not in a module."
+
+(** Toplevel. **)
+let current_line = ref ""
+
+let interprete_line ppf line =
+ current_line := line;
+ let lexbuf = Lexing.from_string line in
+ try
+ match identifier_or_eol Lexer.lexeme lexbuf with
+ | Some x ->
+ begin match matching_instructions x with
+ | [] ->
+ error "Unknown command."
+ | [i] ->
+ i.instr_action ppf lexbuf;
+ resume_user_input ();
+ i.instr_repeat
+ | l ->
+ error "Ambiguous command."
+ end
+ | None ->
+ resume_user_input ();
+ false
+ with
+ | Parsing.Parse_error ->
+ error "Syntax error."
+ | Failure "int_of_string" ->
+ error "Integer overflow"
+
+let line_loop ppf line_buffer =
+ resume_user_input ();
+ let previous_line = ref "" in
+ try
+ while true do
+ if !loaded then
+ History.add_current_time ();
+ let new_line = string_trim (line line_buffer) in
+ let line =
+ if new_line <> "" then
+ new_line
+ else
+ !previous_line
+ in
+ previous_line := "";
+ if interprete_line ppf line then
+ previous_line := line
+ done
+ with
+ | Exit ->
+ stop_user_input ()
+(* | Sys_error s ->
+ error ("System error: " ^ s) *)
+
+(** Instructions. **)
+let instr_cd ppf lexbuf =
+ let dir = argument_eol argument lexbuf in
+ if ask_kill_program () then
+ try
+ Sys.chdir (expand_path dir)
+ with
+ | Sys_error s ->
+ error s
+
+let instr_shell ppf lexbuf =
+ let cmdarg = argument_list_eol argument lexbuf in
+ let cmd = String.concat " " cmdarg in
+ (* perhaps we should use $SHELL -c ? *)
+ let err = Sys.command cmd in
+ if (err != 0) then
+ eprintf "Shell command %S failed with exit code %d\n%!" cmd err
+
+let instr_env ppf lexbuf =
+ let cmdarg = argument_list_eol argument lexbuf in
+ let cmdarg = string_trim (String.concat " " cmdarg) in
+ if cmdarg <> "" then
+ if ask_kill_program () then begin
+ try
+ let eqpos = String.index cmdarg '=' in
+ if eqpos = 0 then raise Not_found;
+ let name = String.sub cmdarg 0 eqpos in
+ let value =
+ String.sub cmdarg (eqpos + 1) (String.length cmdarg - eqpos - 1)
+ in
+ Debugger_config.environment :=
+ (name, value) :: List.remove_assoc name !Debugger_config.environment
+ with Not_found ->
+ eprintf "Environment variable must be in name=value format\n%!"
+ end
+ else
+ List.iter
+ (fun (vvar, vval) -> printf "%s=%s\n%!" vvar vval)
+ (List.rev !Debugger_config.environment)
+
+let instr_pwd ppf lexbuf =
+ eol lexbuf;
+ fprintf ppf "%s@." (Sys.getcwd ())
+
+let instr_dir ppf lexbuf =
+ let new_directory = argument_list_eol argument lexbuf in
+ if new_directory = [] then begin
+ if yes_or_no "Reinitialize directory list" then begin
+ Config.load_path := !default_load_path;
+ Envaux.reset_cache ();
+ Hashtbl.clear Debugger_config.load_path_for;
+ flush_buffer_list ()
+ end
+ end
+ else begin
+ let new_directory' = List.rev new_directory in
+ match new_directory' with
+ | mdl :: for_keyw :: tl
+ when String.lowercase_ascii for_keyw = "for" && List.length tl > 0 ->
+ List.iter (function x -> add_path_for mdl (expand_path x)) tl
+ | _ ->
+ List.iter (function x -> add_path (expand_path x)) new_directory'
+ end;
+ let print_dirs ppf l = List.iter (function x -> fprintf ppf "@ %s" x) l in
+ fprintf ppf "@[<2>Directories: %a@]@." print_dirs !Config.load_path;
+ Hashtbl.iter
+ (fun mdl dirs ->
+ fprintf ppf "@[<2>Source directories for %s: %a@]@." mdl print_dirs
+ dirs)
+ Debugger_config.load_path_for
+
+let instr_kill ppf lexbuf =
+ eol lexbuf;
+ if not !loaded then error "The program is not being run.";
+ if (yes_or_no "Kill the program being debugged") then begin
+ kill_program ();
+ show_no_point()
+ end
+
+let instr_pid ppf lexbuf =
+ eol lexbuf;
+ if not !loaded then error "The program is not being run.";
+ fprintf ppf "@[%d@]@." !current_checkpoint.c_pid
+
+let instr_run ppf lexbuf =
+ eol lexbuf;
+ ensure_loaded ();
+ reset_named_values ();
+ run ();
+ show_current_event ppf;;
+
+let instr_reverse ppf lexbuf =
+ eol lexbuf;
+ check_not_windows "reverse";
+ ensure_loaded ();
+ reset_named_values();
+ back_run ();
+ show_current_event ppf
+
+let instr_step ppf lexbuf =
+ let step_count =
+ match opt_signed_int64_eol Lexer.lexeme lexbuf with
+ | None -> _1
+ | Some x -> x
+ in
+ ensure_loaded ();
+ reset_named_values();
+ step step_count;
+ show_current_event ppf
+
+let instr_back ppf lexbuf =
+ let step_count =
+ match opt_signed_int64_eol Lexer.lexeme lexbuf with
+ | None -> _1
+ | Some x -> x
+ in
+ check_not_windows "backstep";
+ ensure_loaded ();
+ reset_named_values();
+ step (_0 -- step_count);
+ show_current_event ppf
+
+let instr_finish ppf lexbuf =
+ eol lexbuf;
+ ensure_loaded ();
+ reset_named_values();
+ finish ();
+ show_current_event ppf
+
+let instr_next ppf lexbuf =
+ let step_count =
+ match opt_integer_eol Lexer.lexeme lexbuf with
+ | None -> 1
+ | Some x -> x
+ in
+ ensure_loaded ();
+ reset_named_values();
+ next step_count;
+ show_current_event ppf
+
+let instr_start ppf lexbuf =
+ eol lexbuf;
+ check_not_windows "start";
+ ensure_loaded ();
+ reset_named_values();
+ start ();
+ show_current_event ppf
+
+let instr_previous ppf lexbuf =
+ let step_count =
+ match opt_integer_eol Lexer.lexeme lexbuf with
+ | None -> 1
+ | Some x -> x
+ in
+ check_not_windows "previous";
+ ensure_loaded ();
+ reset_named_values();
+ previous step_count;
+ show_current_event ppf
+
+let instr_goto ppf lexbuf =
+ let time = int64_eol Lexer.lexeme lexbuf in
+ ensure_loaded ();
+ reset_named_values();
+ go_to time;
+ show_current_event ppf
+
+let instr_quit _ =
+ raise Exit
+
+let print_variable_list ppf =
+ let pr_vars ppf = List.iter (fun v -> fprintf ppf "%s@ " v.var_name) in
+ fprintf ppf "List of variables: %a@." pr_vars !variable_list
+
+let print_info_list ppf =
+ let pr_infos ppf = List.iter (fun i -> fprintf ppf "%s@ " i.info_name) in
+ fprintf ppf "List of info commands: %a@." pr_infos !info_list
+
+let instr_complete ppf lexbuf =
+ let ppf = Format.err_formatter in
+ let rec print_list l =
+ try
+ eol lexbuf;
+ List.iter (function i -> fprintf ppf "%s@." i) l
+ with _ ->
+ remove_file !user_channel
+ and match_list lexbuf =
+ match identifier_or_eol Lexer.lexeme lexbuf with
+ | None ->
+ List.map (fun i -> i.instr_name) !instruction_list
+ | Some x ->
+ match matching_instructions x with
+ | [ {instr_name = ("set" | "show" as i_full)} ] ->
+ if x = i_full then begin
+ match identifier_or_eol Lexer.lexeme lexbuf with
+ | Some ident ->
+ begin match matching_variables ident with
+ | [v] -> if v.var_name = ident then [] else [v.var_name]
+ | l -> List.map (fun v -> v.var_name) l
+ end
+ | None ->
+ List.map (fun v -> v.var_name) !variable_list
+ end
+ else [i_full]
+ | [ {instr_name = "info"} ] ->
+ if x = "info" then begin
+ match identifier_or_eol Lexer.lexeme lexbuf with
+ | Some ident ->
+ begin match matching_infos ident with
+ | [i] -> if i.info_name = ident then [] else [i.info_name]
+ | l -> List.map (fun i -> i.info_name) l
+ end
+ | None ->
+ List.map (fun i -> i.info_name) !info_list
+ end
+ else ["info"]
+ | [ {instr_name = "help"} ] ->
+ if x = "help" then match_list lexbuf else ["help"]
+ | [ i ] ->
+ if x = i.instr_name then [] else [i.instr_name]
+ | l ->
+ List.map (fun i -> i.instr_name) l
+ in
+ print_list(match_list lexbuf)
+
+let instr_help ppf lexbuf =
+ let pr_instrs ppf =
+ List.iter (fun i -> fprintf ppf "%s@ " i.instr_name) in
+ match identifier_or_eol Lexer.lexeme lexbuf with
+ | Some x ->
+ let print_help nm hlp =
+ eol lexbuf;
+ fprintf ppf "%s: %s@." nm hlp in
+ begin match matching_instructions x with
+ | [] ->
+ eol lexbuf;
+ fprintf ppf "No matching command.@."
+ | [ {instr_name = "set"} ] ->
+ find_variable
+ (fun v _ _ ->
+ print_help ("set " ^ v.var_name) ("set " ^ v.var_help))
+ (fun ppf ->
+ print_help "set" "set debugger variable.";
+ print_variable_list ppf)
+ ppf
+ lexbuf
+ | [ {instr_name = "show"} ] ->
+ find_variable
+ (fun v _ _ ->
+ print_help ("show " ^ v.var_name) ("show " ^ v.var_help))
+ (fun v ->
+ print_help "show" "display debugger variable.";
+ print_variable_list ppf)
+ ppf
+ lexbuf
+ | [ {instr_name = "info"} ] ->
+ find_info
+ (fun i _ _ -> print_help ("info " ^ i.info_name) i.info_help)
+ (fun ppf ->
+ print_help "info"
+ "display infos about the program being debugged.";
+ print_info_list ppf)
+ ppf
+ lexbuf
+ | [i] ->
+ print_help i.instr_name i.instr_help
+ | l ->
+ eol lexbuf;
+ fprintf ppf "Ambiguous command \"%s\": %a@." x pr_instrs l
+ end
+ | None ->
+ fprintf ppf "List of commands: %a@." pr_instrs !instruction_list
+
+(* Printing values *)
+
+let print_expr depth ev env ppf expr =
+ try
+ let (v, ty) = Eval.expression ev env expr in
+ print_named_value depth expr env v ppf ty
+ with
+ | Eval.Error msg ->
+ Eval.report_error ppf msg;
+ raise Toplevel
+
+let env_of_event =
+ function
+ None -> Env.empty
+ | Some ev ->
+ Envaux.env_from_summary ev.Instruct.ev_typenv ev.Instruct.ev_typsubst
+
+let print_command depth ppf lexbuf =
+ let exprs = expression_list_eol Lexer.lexeme lexbuf in
+ ensure_loaded ();
+ let env =
+ try
+ env_of_event !selected_event
+ with
+ | Envaux.Error msg ->
+ Envaux.report_error ppf msg;
+ raise Toplevel
+ in
+ List.iter (print_expr depth !selected_event env ppf) exprs
+
+let instr_print ppf lexbuf = print_command !max_printer_depth ppf lexbuf
+
+let instr_display ppf lexbuf = print_command 1 ppf lexbuf
+
+let instr_address ppf lexbuf =
+ let exprs = expression_list_eol Lexer.lexeme lexbuf in
+ ensure_loaded ();
+ let env =
+ try
+ env_of_event !selected_event
+ with
+ | Envaux.Error msg ->
+ Envaux.report_error ppf msg;
+ raise Toplevel
+ in
+ let print_addr expr =
+ let (v, _ty) =
+ try Eval.expression !selected_event env expr
+ with Eval.Error msg ->
+ Eval.report_error ppf msg;
+ raise Toplevel
+ in
+ match Remote_value.pointer v with
+ | "" -> fprintf ppf "[not a remote value]@."
+ | s -> fprintf ppf "0x%s@." s
+ in
+ List.iter print_addr exprs
+
+(* Loading of command files *)
+
+let extract_filename arg =
+ (* Allow enclosing filename in quotes *)
+ let l = String.length arg in
+ let pos1 = if l > 0 && arg.[0] = '\"' then 1 else 0 in
+ let pos2 = if l > 0 && arg.[l-1] = '\"' then l-1 else l in
+ String.sub arg pos1 (pos2 - pos1)
+
+let instr_source ppf lexbuf =
+ let file = extract_filename(argument_eol argument lexbuf)
+ and old_state = !interactif
+ and old_channel = !user_channel in
+ let io_chan =
+ try
+ io_channel_of_descr
+ (openfile (find_in_path !Config.load_path (expand_path file))
+ [O_RDONLY] 0)
+ with
+ | Not_found -> error "Source file not found."
+ | (Unix_error _) as x -> Unix_tools.report_error x; raise Toplevel
+ in
+ try
+ interactif := false;
+ user_channel := io_chan;
+ line_loop ppf (Lexing.from_function read_user_input);
+ close_io io_chan;
+ interactif := old_state;
+ user_channel := old_channel
+ with
+ | x ->
+ stop_user_input ();
+ close_io io_chan;
+ interactif := old_state;
+ user_channel := old_channel;
+ raise x
+
+let instr_set =
+ find_variable
+ (fun {var_action = (funct, _)} ppf lexbuf -> funct lexbuf)
+ (function ppf -> error "Argument required.")
+
+let instr_show =
+ find_variable
+ (fun {var_action = (_, funct)} ppf lexbuf -> eol lexbuf; funct ppf)
+ (function ppf ->
+ List.iter
+ (function {var_name = nm; var_action = (_, funct)} ->
+ fprintf ppf "%s: " nm;
+ funct ppf)
+ !variable_list)
+
+let instr_info =
+ find_info
+ (fun i ppf lexbuf -> i.info_action lexbuf)
+ (function ppf ->
+ error "\"info\" must be followed by the name of an info command.")
+
+let instr_break ppf lexbuf =
+ let argument = break_argument_eol Lexer.lexeme lexbuf in
+ ensure_loaded ();
+ match argument with
+ | BA_none -> (* break *)
+ (match !selected_event with
+ | Some ev ->
+ new_breakpoint ev
+ | None ->
+ error "Can\'t add breakpoint at this point.")
+ | BA_pc pc -> (* break PC *)
+ add_breakpoint_at_pc pc
+ | BA_function expr -> (* break FUNCTION *)
+ let env =
+ try
+ env_of_event !selected_event
+ with
+ | Envaux.Error msg ->
+ Envaux.report_error ppf msg;
+ raise Toplevel
+ in
+ begin try
+ let (v, ty) = Eval.expression !selected_event env expr in
+ match (Ctype.repr ty).desc with
+ | Tarrow _ ->
+ add_breakpoint_after_pc (Remote_value.closure_code v)
+ | _ ->
+ eprintf "Not a function.@.";
+ raise Toplevel
+ with
+ | Eval.Error msg ->
+ Eval.report_error ppf msg;
+ raise Toplevel
+ end
+ | BA_pos1 (mdle, line, column) -> (* break @ [MODULE] LINE [COL] *)
+ let module_name = convert_module (module_of_longident mdle) in
+ new_breakpoint
+ (try
+ let ev = event_at_pos module_name 0 in
+ let ev_pos =
+ {Lexing.dummy_pos with
+ pos_fname = (Events.get_pos ev).pos_fname} in
+ let buffer =
+ try get_buffer ev_pos module_name with
+ | Not_found ->
+ eprintf "No source file for %s.@." module_name;
+ raise Toplevel
+ in
+ match column with
+ | None ->
+ event_at_pos module_name (fst (pos_of_line buffer line))
+ | Some col ->
+ event_near_pos module_name (point_of_coord buffer line col)
+ with
+ | Not_found -> (* event_at_pos / event_near pos *)
+ eprintf "Can\'t find any event there.@.";
+ raise Toplevel
+ | Out_of_range -> (* pos_of_line / point_of_coord *)
+ eprintf "Position out of range.@.";
+ raise Toplevel)
+ | BA_pos2 (mdle, position) -> (* break @ [MODULE] # POSITION *)
+ try
+ new_breakpoint
+ (event_near_pos (convert_module (module_of_longident mdle))
+ position)
+ with
+ | Not_found ->
+ eprintf "Can\'t find any event there.@."
+
+let instr_delete ppf lexbuf =
+ match integer_list_eol Lexer.lexeme lexbuf with
+ | [] ->
+ if breakpoints_count () <> 0 && yes_or_no "Delete all breakpoints"
+ then remove_all_breakpoints ()
+ | breakpoints ->
+ List.iter
+ (function x -> try remove_breakpoint x with | Not_found -> ())
+ breakpoints
+
+let instr_frame ppf lexbuf =
+ let frame_number =
+ match opt_integer_eol Lexer.lexeme lexbuf with
+ | None -> !current_frame
+ | Some x -> x
+ in
+ ensure_loaded ();
+ try
+ select_frame frame_number;
+ show_current_frame ppf true
+ with
+ | Not_found ->
+ error ("No frame number " ^ string_of_int frame_number ^ ".")
+
+let instr_backtrace ppf lexbuf =
+ let number =
+ match opt_signed_integer_eol Lexer.lexeme lexbuf with
+ | None -> 0
+ | Some x -> x in
+ ensure_loaded ();
+ match current_report() with
+ | None | Some {rep_type = Exited | Uncaught_exc} -> ()
+ | Some _ ->
+ let frame_counter = ref 0 in
+ let print_frame first_frame last_frame = function
+ | None ->
+ fprintf ppf
+ "(Encountered a function with no debugging information)@.";
+ false
+ | Some event ->
+ if !frame_counter >= first_frame then
+ show_one_frame !frame_counter ppf event;
+ incr frame_counter;
+ if !frame_counter >= last_frame then begin
+ fprintf ppf "(More frames follow)@."
+ end;
+ !frame_counter < last_frame in
+ fprintf ppf "Backtrace:@.";
+ if number = 0 then
+ do_backtrace (print_frame 0 max_int)
+ else if number > 0 then
+ do_backtrace (print_frame 0 number)
+ else begin
+ let num_frames = stack_depth() in
+ if num_frames < 0 then
+ fprintf ppf
+ "(Encountered a function with no debugging information)@."
+ else
+ do_backtrace (print_frame (num_frames + number) max_int)
+ end
+
+let instr_up ppf lexbuf =
+ let offset =
+ match opt_signed_integer_eol Lexer.lexeme lexbuf with
+ | None -> 1
+ | Some x -> x
+ in
+ ensure_loaded ();
+ try
+ select_frame (!current_frame + offset);
+ show_current_frame ppf true
+ with
+ | Not_found -> error "No such frame."
+
+let instr_down ppf lexbuf =
+ let offset =
+ match opt_signed_integer_eol Lexer.lexeme lexbuf with
+ | None -> 1
+ | Some x -> x
+ in
+ ensure_loaded ();
+ try
+ select_frame (!current_frame - offset);
+ show_current_frame ppf true
+ with
+ | Not_found -> error "No such frame."
+
+let instr_last ppf lexbuf =
+ let count =
+ match opt_signed_int64_eol Lexer.lexeme lexbuf with
+ | None -> _1
+ | Some x -> x
+ in
+ check_not_windows "last";
+ reset_named_values();
+ go_to (History.previous_time count);
+ show_current_event ppf
+
+let instr_list ppf lexbuf =
+ let (mo, beg, e) = list_arguments_eol Lexer.lexeme lexbuf in
+ let (curr_mod, line, column) =
+ try
+ selected_point ()
+ with
+ | Not_found ->
+ ("", -1, -1)
+ in
+ let mdle = convert_module (module_of_longident mo) in
+ let pos = Lexing.dummy_pos in
+ let buffer =
+ try get_buffer pos mdle with
+ | Not_found -> error ("No source file for " ^ mdle ^ ".") in
+ let point =
+ if column <> -1 then
+ (point_of_coord buffer line 1) + column
+ else
+ -1 in
+ let beginning =
+ match beg with
+ | None when (mo <> None) || (line = -1) ->
+ 1
+ | None ->
+ begin try
+ max 1 (line - 10)
+ with Out_of_range ->
+ 1
+ end
+ | Some x -> x
+ in
+ let en =
+ match e with
+ | None -> beginning + 20
+ | Some x -> x
+ in
+ if mdle = curr_mod then
+ show_listing pos mdle beginning en point
+ (current_event_is_before ())
+ else
+ show_listing pos mdle beginning en (-1) true
+
+(** Variables. **)
+let raw_variable kill name =
+ (function lexbuf ->
+ let argument = argument_eol argument lexbuf in
+ if (not kill) || ask_kill_program () then name := argument),
+ function ppf -> fprintf ppf "%s@." !name
+
+let raw_line_variable kill name =
+ (function lexbuf ->
+ let argument = argument_eol line_argument lexbuf in
+ if (not kill) || ask_kill_program () then name := argument),
+ function ppf -> fprintf ppf "%s@." !name
+
+let integer_variable kill min msg name =
+ (function lexbuf ->
+ let argument = integer_eol Lexer.lexeme lexbuf in
+ if argument < min then print_endline msg
+ else if (not kill) || ask_kill_program () then name := argument),
+ function ppf -> fprintf ppf "%i@." !name
+
+let int64_variable kill min msg name =
+ (function lexbuf ->
+ let argument = int64_eol Lexer.lexeme lexbuf in
+ if argument < min then print_endline msg
+ else if (not kill) || ask_kill_program () then name := argument),
+ function ppf -> fprintf ppf "%Li@." !name
+
+let boolean_variable kill name =
+ (function lexbuf ->
+ let argument =
+ match identifier_eol Lexer.lexeme lexbuf with
+ | "on" -> true
+ | "of" | "off" -> false
+ | _ -> error "Syntax error."
+ in
+ if (not kill) || ask_kill_program () then name := argument),
+ function ppf -> fprintf ppf "%s@." (if !name then "on" else "off")
+
+let path_variable kill name =
+ (function lexbuf ->
+ let argument = argument_eol argument lexbuf in
+ if (not kill) || ask_kill_program () then
+ name := make_absolute (expand_path argument)),
+ function ppf -> fprintf ppf "%s@." !name
+
+let loading_mode_variable ppf =
+ (find_ident
+ "loading mode"
+ (matching_elements (ref loading_modes) fst)
+ (fun (_, mode) ppf lexbuf ->
+ eol lexbuf; set_launching_function mode)
+ (function ppf -> error "Syntax error.")
+ ppf),
+ function ppf ->
+ let rec find = function
+ | [] -> ()
+ | (name, funct) :: l ->
+ if funct == !launching_func then fprintf ppf "%s" name else find l
+ in
+ find loading_modes;
+ fprintf ppf "@."
+
+let follow_fork_variable =
+ (function lexbuf ->
+ let mode =
+ match identifier_eol Lexer.lexeme lexbuf with
+ | "child" -> Fork_child
+ | "parent" -> Fork_parent
+ | _ -> error "Syntax error."
+ in
+ fork_mode := mode;
+ if !loaded then update_follow_fork_mode ()),
+ function ppf ->
+ fprintf ppf "%s@."
+ (match !fork_mode with
+ Fork_child -> "child"
+ | Fork_parent -> "parent")
+
+(** Infos. **)
+
+let pr_modules ppf mods =
+ let pr_mods ppf = List.iter (function x -> fprintf ppf "%s@ " x) in
+ fprintf ppf "Used modules: @.%a@?" pr_mods mods
+
+let info_modules ppf lexbuf =
+ eol lexbuf;
+ ensure_loaded ();
+ pr_modules ppf !modules
+(********
+ print_endline "Opened modules: ";
+ if !opened_modules_names = [] then
+ print_endline "(no module opened)."
+ else
+ (List.iter (function x -> print_string x;print_space) !opened_modules_names;
+ print_newline ())
+*********)
+
+let info_checkpoints ppf lexbuf =
+ eol lexbuf;
+ if !checkpoints = [] then fprintf ppf "No checkpoint.@."
+ else
+ (if !debug_breakpoints then
+ (prerr_endline " Time Pid Version";
+ List.iter
+ (function
+ {c_time = time; c_pid = pid; c_breakpoint_version = version} ->
+ Printf.printf "%19Ld %5d %d\n" time pid version)
+ !checkpoints)
+ else
+ (print_endline " Time Pid";
+ List.iter
+ (function
+ {c_time = time; c_pid = pid} ->
+ Printf.printf "%19Ld %5d\n" time pid)
+ !checkpoints))
+
+let info_one_breakpoint ppf (num, ev) =
+ fprintf ppf "%3d %10d %s@." num ev.ev_pos (Pos.get_desc ev);
+;;
+
+let info_breakpoints ppf lexbuf =
+ eol lexbuf;
+ if !breakpoints = [] then fprintf ppf "No breakpoints.@."
+ else begin
+ fprintf ppf "Num Address Where@.";
+ List.iter (info_one_breakpoint ppf) (List.rev !breakpoints);
+ end
+;;
+
+let info_events ppf lexbuf =
+ ensure_loaded ();
+ let mdle =
+ convert_module (module_of_longident (opt_longident_eol Lexer.lexeme lexbuf))
+ in
+ print_endline ("Module: " ^ mdle);
+ print_endline " Address Characters Kind Repr.";
+ List.iter
+ (function ev ->
+ let start_char, end_char =
+ try
+ let buffer = get_buffer (Events.get_pos ev) ev.ev_module in
+ (snd (start_and_cnum buffer ev.ev_loc.Location.loc_start)),
+ (snd (start_and_cnum buffer ev.ev_loc.Location.loc_end))
+ with _ ->
+ ev.ev_loc.Location.loc_start.Lexing.pos_cnum,
+ ev.ev_loc.Location.loc_end.Lexing.pos_cnum in
+ Printf.printf
+ "%10d %6d-%-6d %10s %10s\n"
+ ev.ev_pos
+ start_char
+ end_char
+ ((match ev.ev_kind with
+ Event_before -> "before"
+ | Event_after _ -> "after"
+ | Event_pseudo -> "pseudo")
+ ^
+ (match ev.ev_info with
+ Event_function -> "/fun"
+ | Event_return _ -> "/ret"
+ | Event_other -> ""))
+ (match ev.ev_repr with
+ Event_none -> ""
+ | Event_parent _ -> "(repr)"
+ | Event_child repr -> string_of_int !repr))
+ (events_in_module mdle)
+
+(** User-defined printers **)
+
+let instr_load_printer ppf lexbuf =
+ let filename = extract_filename(argument_eol argument lexbuf) in
+ try
+ Loadprinter.loadfile ppf filename
+ with Loadprinter.Error e ->
+ Loadprinter.report_error ppf e; raise Toplevel
+
+let instr_install_printer ppf lexbuf =
+ let lid = longident_eol Lexer.lexeme lexbuf in
+ try
+ Loadprinter.install_printer ppf lid
+ with Loadprinter.Error e ->
+ Loadprinter.report_error ppf e; raise Toplevel
+
+let instr_remove_printer ppf lexbuf =
+ let lid = longident_eol Lexer.lexeme lexbuf in
+ try
+ Loadprinter.remove_printer lid
+ with Loadprinter.Error e ->
+ Loadprinter.report_error ppf e; raise Toplevel
+
+(** Initialization. **)
+let init ppf =
+ instruction_list := [
+ { instr_name = "cd"; instr_prio = false;
+ instr_action = instr_cd; instr_repeat = true; instr_help =
+"set working directory to DIR for debugger and program being debugged." };
+ { instr_name = "complete"; instr_prio = false;
+ instr_action = instr_complete; instr_repeat = false; instr_help =
+"complete word at cursor according to context. Useful for Emacs." };
+ { instr_name = "pwd"; instr_prio = false;
+ instr_action = instr_pwd; instr_repeat = true; instr_help =
+"print working directory." };
+ { instr_name = "directory"; instr_prio = false;
+ instr_action = instr_dir; instr_repeat = false; instr_help =
+"add directory DIR to beginning of search path for source and\n\
+interface files.\n\
+Forget cached info on source file locations and line positions.\n\
+With no argument, reset the search path." };
+ { instr_name = "kill"; instr_prio = false;
+ instr_action = instr_kill; instr_repeat = true; instr_help =
+"kill the program being debugged." };
+ { instr_name = "pid"; instr_prio = false;
+ instr_action = instr_pid; instr_repeat = true; instr_help =
+"print the process ID of the current active process." };
+ { instr_name = "address"; instr_prio = false;
+ instr_action = instr_address; instr_repeat = true; instr_help =
+"print the raw address of a value." };
+ { instr_name = "help"; instr_prio = false;
+ instr_action = instr_help; instr_repeat = true; instr_help =
+"print list of commands." };
+ { instr_name = "quit"; instr_prio = false;
+ instr_action = instr_quit; instr_repeat = false; instr_help =
+"exit the debugger." };
+ { instr_name = "shell"; instr_prio = false;
+ instr_action = instr_shell; instr_repeat = true; instr_help =
+"Execute a given COMMAND thru the system shell." };
+ { instr_name = "environment"; instr_prio = false;
+ instr_action = instr_env; instr_repeat = false; instr_help =
+"environment variable to give to program being debugged when it is started." };
+ (* Displacements *)
+ { instr_name = "run"; instr_prio = true;
+ instr_action = instr_run; instr_repeat = true; instr_help =
+"run the program from current position." };
+ { instr_name = "reverse"; instr_prio = false;
+ instr_action = instr_reverse; instr_repeat = true; instr_help =
+"run the program backward from current position." };
+ { instr_name = "step"; instr_prio = true;
+ instr_action = instr_step; instr_repeat = true; instr_help =
+"step program until it reaches the next event.\n\
+Argument N means do this N times (or till program stops for another reason)." };
+ { instr_name = "backstep"; instr_prio = true;
+ instr_action = instr_back; instr_repeat = true; instr_help =
+"step program backward until it reaches the previous event.\n\
+Argument N means do this N times (or till program stops for another reason)." };
+ { instr_name = "goto"; instr_prio = false;
+ instr_action = instr_goto; instr_repeat = true; instr_help =
+"go to the given time." };
+ { instr_name = "finish"; instr_prio = true;
+ instr_action = instr_finish; instr_repeat = true; instr_help =
+"execute until topmost stack frame returns." };
+ { instr_name = "next"; instr_prio = true;
+ instr_action = instr_next; instr_repeat = true; instr_help =
+"step program until it reaches the next event.\n\
+Skip over function calls.\n\
+Argument N means do this N times (or till program stops for another reason)." };
+ { instr_name = "start"; instr_prio = false;
+ instr_action = instr_start; instr_repeat = true; instr_help =
+"execute backward until the current function is exited." };
+ { instr_name = "previous"; instr_prio = false;
+ instr_action = instr_previous; instr_repeat = true; instr_help =
+"step program until it reaches the previous event.\n\
+Skip over function calls.\n\
+Argument N means do this N times (or till program stops for another reason)." };
+ { instr_name = "print"; instr_prio = true;
+ instr_action = instr_print; instr_repeat = true; instr_help =
+"print value of expressions (deep printing)." };
+ { instr_name = "display"; instr_prio = true;
+ instr_action = instr_display; instr_repeat = true; instr_help =
+"print value of expressions (shallow printing)." };
+ { instr_name = "source"; instr_prio = false;
+ instr_action = instr_source; instr_repeat = true; instr_help =
+"read command from file FILE." };
+ (* Breakpoints *)
+ { instr_name = "break"; instr_prio = false;
+ instr_action = instr_break; instr_repeat = false; instr_help =
+"Set breakpoint at specified line or function.\
+\nSyntax: break function-name\
+\n break @ [module] linenum\
+\n break @ [module] # characternum" };
+ { instr_name = "delete"; instr_prio = false;
+ instr_action = instr_delete; instr_repeat = false; instr_help =
+"delete some breakpoints.\n\
+Arguments are breakpoint numbers with spaces in between.\n\
+To delete all breakpoints, give no argument." };
+ { instr_name = "set"; instr_prio = false;
+ instr_action = instr_set; instr_repeat = false; instr_help =
+"--unused--" };
+ { instr_name = "show"; instr_prio = false;
+ instr_action = instr_show; instr_repeat = true; instr_help =
+"--unused--" };
+ { instr_name = "info"; instr_prio = false;
+ instr_action = instr_info; instr_repeat = true; instr_help =
+"--unused--" };
+ (* Frames *)
+ { instr_name = "frame"; instr_prio = false;
+ instr_action = instr_frame; instr_repeat = true; instr_help =
+"select and print a stack frame.\n\
+With no argument, print the selected stack frame.\n\
+An argument specifies the frame to select." };
+ { instr_name = "backtrace"; instr_prio = false;
+ instr_action = instr_backtrace; instr_repeat = true; instr_help =
+"print backtrace of all stack frames, or innermost COUNT frames.\n\
+With a negative argument, print outermost -COUNT frames." };
+ { instr_name = "bt"; instr_prio = false;
+ instr_action = instr_backtrace; instr_repeat = true; instr_help =
+"print backtrace of all stack frames, or innermost COUNT frames.\n\
+With a negative argument, print outermost -COUNT frames." };
+ { instr_name = "up"; instr_prio = false;
+ instr_action = instr_up; instr_repeat = true; instr_help =
+"select and print stack frame that called this one.\n\
+An argument says how many frames up to go." };
+ { instr_name = "down"; instr_prio = false;
+ instr_action = instr_down; instr_repeat = true; instr_help =
+"select and print stack frame called by this one.\n\
+An argument says how many frames down to go." };
+ { instr_name = "last"; instr_prio = true;
+ instr_action = instr_last; instr_repeat = true; instr_help =
+"go back to previous time." };
+ { instr_name = "list"; instr_prio = false;
+ instr_action = instr_list; instr_repeat = true; instr_help =
+"list the source code." };
+ (* User-defined printers *)
+ { instr_name = "load_printer"; instr_prio = false;
+ instr_action = instr_load_printer; instr_repeat = false; instr_help =
+"load in the debugger a .cmo or .cma file containing printing functions." };
+ { instr_name = "install_printer"; instr_prio = false;
+ instr_action = instr_install_printer; instr_repeat = false; instr_help =
+"use the given function for printing values of its input type.\n\
+The code for the function must have previously been loaded in the debugger\n\
+using \"load_printer\"." };
+ { instr_name = "remove_printer"; instr_prio = false;
+ instr_action = instr_remove_printer; instr_repeat = false; instr_help =
+"stop using the given function for printing values of its input type." }
+];
+ variable_list := [
+ (* variable name, (writing, reading), help reading, help writing *)
+ { var_name = "arguments";
+ var_action = raw_line_variable true arguments;
+ var_help =
+"arguments to give program being debugged when it is started." };
+ { var_name = "program";
+ var_action = path_variable true program_name;
+ var_help =
+"name of program to be debugged." };
+ { var_name = "loadingmode";
+ var_action = loading_mode_variable ppf;
+ var_help =
+"mode of loading.\n\
+It can be either:\n\
+ direct: the program is directly called by the debugger.\n\
+ runtime: the debugger execute `ocamlrun programname arguments\'.\n\
+ manual: the program is not launched by the debugger,\n\
+ but manually by the user." };
+ { var_name = "processcount";
+ var_action = integer_variable false 1 "Must be >= 1."
+ checkpoint_max_count;
+ var_help =
+"maximum number of process to keep." };
+ { var_name = "checkpoints";
+ var_action = boolean_variable false make_checkpoints;
+ var_help =
+"whether to make checkpoints or not." };
+ { var_name = "bigstep";
+ var_action = int64_variable false _1 "Must be >= 1."
+ checkpoint_big_step;
+ var_help =
+"step between checkpoints during long displacements." };
+ { var_name = "smallstep";
+ var_action = int64_variable false _1 "Must be >= 1."
+ checkpoint_small_step;
+ var_help =
+"step between checkpoints during small displacements." };
+ { var_name = "socket";
+ var_action = raw_variable true socket_name;
+ var_help =
+"name of the socket used by communications debugger-runtime." };
+ { var_name = "history";
+ var_action = integer_variable false 0 "" history_size;
+ var_help =
+"history size." };
+ { var_name = "print_depth";
+ var_action = integer_variable false 1 "Must be at least 1"
+ max_printer_depth;
+ var_help =
+"maximal depth for printing of values." };
+ { var_name = "print_length";
+ var_action = integer_variable false 1 "Must be at least 1"
+ max_printer_steps;
+ var_help =
+"maximal number of value nodes printed." };
+ { var_name = "follow_fork_mode";
+ var_action = follow_fork_variable;
+ var_help =
+"process to follow after forking.\n\
+It can be either :
+ child: the newly created process.\n\
+ parent: the process that called fork.\n" }];
+
+ info_list :=
+ (* info name, function, help *)
+ [{ info_name = "modules";
+ info_action = info_modules ppf;
+ info_help = "list opened modules." };
+ { info_name = "checkpoints";
+ info_action = info_checkpoints ppf;
+ info_help = "list checkpoints." };
+ { info_name = "breakpoints";
+ info_action = info_breakpoints ppf;
+ info_help = "list breakpoints." };
+ { info_name = "events";
+ info_action = info_events ppf;
+ info_help = "list events in MODULE (default is current module)." }]
+
+let _ = init std_formatter
diff --git a/debugger/command_line.mli b/debugger/command_line.mli
new file mode 100644
index 0000000000..f7fb160573
--- /dev/null
+++ b/debugger/command_line.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(************************ Reading and executing commands ***************)
+
+open Lexing;;
+open Format;;
+
+val interprete_line : formatter -> string -> bool;;
+val line_loop : formatter -> lexbuf -> unit;;
diff --git a/debugger/debugcom.ml b/debugger/debugcom.ml
new file mode 100644
index 0000000000..a7512898ae
--- /dev/null
+++ b/debugger/debugcom.ml
@@ -0,0 +1,306 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Low-level communication with the debuggee *)
+
+open Int64ops
+open Primitives
+
+(* The current connection with the debuggee *)
+
+let conn = ref Primitives.std_io
+
+(* Set which process the debugger follows on fork. *)
+
+type follow_fork_mode =
+ Fork_child
+ | Fork_parent
+
+let fork_mode = ref Fork_parent
+
+let update_follow_fork_mode () =
+ let a = match !fork_mode with Fork_child -> 0 | Fork_parent -> 1 in
+ output_char !conn.io_out 'K';
+ output_binary_int !conn.io_out a
+
+(* Set the current connection, and update the fork mode in case it has
+ * changed. *)
+
+let set_current_connection io_chan =
+ conn := io_chan;
+ update_follow_fork_mode ()
+
+(* Modify the program code *)
+
+let set_event pos =
+ output_char !conn.io_out 'e';
+ output_binary_int !conn.io_out pos
+
+let set_breakpoint pos =
+ output_char !conn.io_out 'B';
+ output_binary_int !conn.io_out pos
+
+let reset_instr pos =
+ output_char !conn.io_out 'i';
+ output_binary_int !conn.io_out pos
+
+(* Basic commands for flow control *)
+
+type execution_summary =
+ Event
+ | Breakpoint
+ | Exited
+ | Trap_barrier
+ | Uncaught_exc
+
+type report = {
+ rep_type : execution_summary;
+ rep_event_count : int;
+ rep_stack_pointer : int;
+ rep_program_pointer : int
+}
+
+type checkpoint_report =
+ Checkpoint_done of int
+ | Checkpoint_failed
+
+(* Run the debuggee for N events *)
+
+let do_go_smallint n =
+ output_char !conn.io_out 'g';
+ output_binary_int !conn.io_out n;
+ flush !conn.io_out;
+ Input_handling.execute_with_other_controller
+ Input_handling.exit_main_loop
+ !conn
+ (function () ->
+ Input_handling.main_loop ();
+ let summary =
+ match input_char !conn.io_in with
+ 'e' -> Event
+ | 'b' -> Breakpoint
+ | 'x' -> Exited
+ | 's' -> Trap_barrier
+ | 'u' -> Uncaught_exc
+ | _ -> Misc.fatal_error "Debugcom.do_go" in
+ let event_counter = input_binary_int !conn.io_in in
+ let stack_pos = input_binary_int !conn.io_in in
+ let pc = input_binary_int !conn.io_in in
+ { rep_type = summary;
+ rep_event_count = event_counter;
+ rep_stack_pointer = stack_pos;
+ rep_program_pointer = pc })
+
+let rec do_go n =
+ assert (n >= _0);
+ if n > max_small_int then(
+ ignore (do_go_smallint max_int);
+ do_go (n -- max_small_int)
+ )else(
+ do_go_smallint (Int64.to_int n)
+ )
+;;
+
+(* Perform a checkpoint *)
+
+let do_checkpoint () =
+ match Sys.os_type with
+ "Win32" -> failwith "do_checkpoint"
+ | _ ->
+ output_char !conn.io_out 'c';
+ flush !conn.io_out;
+ let pid = input_binary_int !conn.io_in in
+ if pid = -1 then Checkpoint_failed else Checkpoint_done pid
+
+(* Kill the given process. *)
+let stop chan =
+ try
+ output_char chan.io_out 's';
+ flush chan.io_out
+ with
+ Sys_error _ | End_of_file -> ()
+
+(* Ask a process to wait for its child which has been killed. *)
+(* (so as to eliminate zombies). *)
+let wait_child chan =
+ try
+ output_char chan.io_out 'w'
+ with
+ Sys_error _ | End_of_file -> ()
+
+(* Move to initial frame (that of current function). *)
+(* Return stack position and current pc *)
+
+let initial_frame () =
+ output_char !conn.io_out '0';
+ flush !conn.io_out;
+ let stack_pos = input_binary_int !conn.io_in in
+ let pc = input_binary_int !conn.io_in in
+ (stack_pos, pc)
+
+let set_initial_frame () =
+ ignore(initial_frame ())
+
+(* Move up one frame *)
+(* Return stack position and current pc.
+ If there's no frame above, return (-1, 0). *)
+
+let up_frame stacksize =
+ output_char !conn.io_out 'U';
+ output_binary_int !conn.io_out stacksize;
+ flush !conn.io_out;
+ let stack_pos = input_binary_int !conn.io_in in
+ let pc = if stack_pos = -1 then 0 else input_binary_int !conn.io_in in
+ (stack_pos, pc)
+
+(* Get and set the current frame position *)
+
+let get_frame () =
+ output_char !conn.io_out 'f';
+ flush !conn.io_out;
+ let stack_pos = input_binary_int !conn.io_in in
+ let pc = input_binary_int !conn.io_in in
+ (stack_pos, pc)
+
+let set_frame stack_pos =
+ output_char !conn.io_out 'S';
+ output_binary_int !conn.io_out stack_pos
+
+(* Set the trap barrier to given stack position. *)
+
+let set_trap_barrier pos =
+ output_char !conn.io_out 'b';
+ output_binary_int !conn.io_out pos
+
+(* Handling of remote values *)
+
+let value_size = if 1 lsl 31 = 0 then 4 else 8
+
+let input_remote_value ic =
+ really_input_string ic value_size
+
+let output_remote_value ic v =
+ output_substring ic v 0 value_size
+
+exception Marshalling_error
+
+module Remote_value =
+ struct
+ type t = Remote of string | Local of Obj.t
+
+ let obj = function
+ | Local obj -> Obj.obj obj
+ | Remote v ->
+ output_char !conn.io_out 'M';
+ output_remote_value !conn.io_out v;
+ flush !conn.io_out;
+ try
+ input_value !conn.io_in
+ with End_of_file | Failure _ ->
+ raise Marshalling_error
+
+ let is_block = function
+ | Local obj -> Obj.is_block obj
+ | Remote v -> Obj.is_block (Array.unsafe_get (Obj.magic v : Obj.t array) 0)
+
+ let tag obj =
+ if not (is_block obj) then Obj.int_tag
+ else match obj with
+ | Local obj -> Obj.tag obj
+ | Remote v ->
+ output_char !conn.io_out 'H';
+ output_remote_value !conn.io_out v;
+ flush !conn.io_out;
+ let header = input_binary_int !conn.io_in in
+ header land 0xFF
+
+ let size = function
+ | Local obj -> Obj.size obj
+ | Remote v ->
+ output_char !conn.io_out 'H';
+ output_remote_value !conn.io_out v;
+ flush !conn.io_out;
+ let header = input_binary_int !conn.io_in in
+ if header land 0xFF = Obj.double_array_tag && Sys.word_size = 32
+ then header lsr 11
+ else header lsr 10
+
+ let field v n =
+ match v with
+ | Local obj -> Local(Obj.field obj n)
+ | Remote v ->
+ output_char !conn.io_out 'F';
+ output_remote_value !conn.io_out v;
+ output_binary_int !conn.io_out n;
+ flush !conn.io_out;
+ if input_byte !conn.io_in = 0 then
+ Remote(input_remote_value !conn.io_in)
+ else begin
+ let buf = really_input_string !conn.io_in 8 in
+ let floatbuf = float n (* force allocation of a new float *) in
+ String.unsafe_blit buf 0 (Obj.magic floatbuf) 0 8;
+ Local(Obj.repr floatbuf)
+ end
+
+ let of_int n =
+ Local(Obj.repr n)
+
+ let local pos =
+ output_char !conn.io_out 'L';
+ output_binary_int !conn.io_out pos;
+ flush !conn.io_out;
+ Remote(input_remote_value !conn.io_in)
+
+ let from_environment pos =
+ output_char !conn.io_out 'E';
+ output_binary_int !conn.io_out pos;
+ flush !conn.io_out;
+ Remote(input_remote_value !conn.io_in)
+
+ let global pos =
+ output_char !conn.io_out 'G';
+ output_binary_int !conn.io_out pos;
+ flush !conn.io_out;
+ Remote(input_remote_value !conn.io_in)
+
+ let accu () =
+ output_char !conn.io_out 'A';
+ flush !conn.io_out;
+ Remote(input_remote_value !conn.io_in)
+
+ let closure_code = function
+ | Local obj -> assert false
+ | Remote v ->
+ output_char !conn.io_out 'C';
+ output_remote_value !conn.io_out v;
+ flush !conn.io_out;
+ input_binary_int !conn.io_in
+
+ let same rv1 rv2 =
+ match (rv1, rv2) with
+ (Local obj1, Local obj2) -> obj1 == obj2
+ | (Remote v1, Remote v2) -> v1 = v2
+ (* string equality -> equality of remote pointers *)
+ | (_, _) -> false
+
+ let pointer rv =
+ match rv with
+ | Remote v ->
+ let bytes = ref [] in
+ String.iter (fun c -> bytes := c :: !bytes) v;
+ let obytes = if Sys.big_endian then List.rev !bytes else !bytes in
+ let to_hex c = Printf.sprintf "%02x" (Char.code c) in
+ String.concat "" (List.map to_hex obytes)
+ | Local _ -> ""
+
+ end
diff --git a/debugger/debugcom.mli b/debugger/debugcom.mli
new file mode 100644
index 0000000000..c37ce6fc6f
--- /dev/null
+++ b/debugger/debugcom.mli
@@ -0,0 +1,111 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Low-level communication with the debuggee *)
+
+type execution_summary =
+ Event
+ | Breakpoint
+ | Exited
+ | Trap_barrier
+ | Uncaught_exc
+
+type report =
+ { rep_type : execution_summary;
+ rep_event_count : int;
+ rep_stack_pointer : int;
+ rep_program_pointer : int }
+
+type checkpoint_report =
+ Checkpoint_done of int
+ | Checkpoint_failed
+
+type follow_fork_mode =
+ Fork_child
+ | Fork_parent
+
+(* Set the current connection with the debuggee *)
+val set_current_connection : Primitives.io_channel -> unit
+
+(* Put an event at given pc *)
+val set_event : int -> unit
+
+(* Put a breakpoint at given pc *)
+val set_breakpoint : int -> unit
+
+(* Remove breakpoint or event at given pc *)
+val reset_instr : int -> unit
+
+(* Create a new checkpoint (the current process forks). *)
+val do_checkpoint : unit -> checkpoint_report
+
+(* Step N events. *)
+val do_go : int64 -> report
+
+(* Tell given process to terminate *)
+val stop : Primitives.io_channel -> unit
+
+(* Tell given process to wait for its children *)
+val wait_child : Primitives.io_channel -> unit
+
+(* Move to initial frame (that of current function). *)
+(* Return stack position and current pc *)
+val initial_frame : unit -> int * int
+val set_initial_frame : unit -> unit
+
+(* Get the current frame position *)
+(* Return stack position and current pc *)
+val get_frame : unit -> int * int
+
+(* Set the current frame *)
+val set_frame : int -> unit
+
+(* Move up one frame *)
+(* Return stack position and current pc.
+ If there's no frame above, return (-1, 0). *)
+val up_frame : int -> int * int
+
+(* Set the trap barrier to given stack position. *)
+val set_trap_barrier : int -> unit
+
+(* Set whether the debugger follow the child or the parent process on fork *)
+val fork_mode : follow_fork_mode ref
+val update_follow_fork_mode : unit -> unit
+
+(* Handling of remote values *)
+
+exception Marshalling_error
+
+module Remote_value :
+ sig
+ type t
+
+ val obj : t -> 'a
+ val is_block : t -> bool
+ val tag : t -> int
+ val size : t -> int
+ val field : t -> int -> t
+ val same : t -> t -> bool
+
+ val of_int : int -> t
+
+ val local : int -> t
+ val from_environment : int -> t
+ val global : int -> t
+ val accu : unit -> t
+ val closure_code : t -> int
+
+ (* Returns a hexadecimal representation of the remote address,
+ or [""] if the value is local. *)
+ val pointer : t -> string
+ end
diff --git a/debugger/debugger_config.ml b/debugger/debugger_config.ml
new file mode 100644
index 0000000000..a16fdca232
--- /dev/null
+++ b/debugger/debugger_config.ml
@@ -0,0 +1,84 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(**************************** Configuration file ***********************)
+
+open Int64ops
+
+exception Toplevel
+
+(*** Miscellaneous parameters. ***)
+
+(*ISO 6429 color sequences
+00 to restore default color
+01 for brighter colors
+04 for underlined text
+05 for flashing text
+30 for black foreground
+31 for red foreground
+32 for green foreground
+33 for yellow (or brown) foreground
+34 for blue foreground
+35 for purple foreground
+36 for cyan foreground
+37 for white (or gray) foreground
+40 for black background
+41 for red background
+42 for green background
+43 for yellow (or brown) background
+44 for blue background
+45 for purple background
+46 for cyan background
+47 for white (or gray) background
+let debugger_prompt = "\027[1;04m(ocd)\027[0m "
+and event_mark_before = "\027[1;31m$\027[0m"
+and event_mark_after = "\027[1;34m$\027[0m"
+*)
+let debugger_prompt = "(ocd) "
+let event_mark_before = "<|b|>"
+let event_mark_after = "<|a|>"
+
+(* Name of shell used to launch the debuggee *)
+let shell =
+ match Sys.os_type with
+ "Win32" -> "cmd"
+ | _ -> "/bin/sh"
+
+(* Name of the OCaml runtime. *)
+let runtime_program = "ocamlrun"
+
+(* Time history size (for `last') *)
+let history_size = ref 30
+
+let load_path_for = Hashtbl.create 7
+
+(*** Time travel parameters. ***)
+
+(* Step between checkpoints for long displacements.*)
+let checkpoint_big_step = ref (~~ "10000")
+
+(* Idem for small ones. *)
+let checkpoint_small_step = ref (~~ "1000")
+
+(* Maximum number of checkpoints. *)
+let checkpoint_max_count = ref 15
+
+(* Whether to keep checkpoints or not. *)
+let make_checkpoints = ref
+ (match Sys.os_type with
+ "Win32" -> false
+ | _ -> true)
+
+(*** Environment variables for debugee. ***)
+
+let environment = ref []
diff --git a/debugger/debugger_config.mli b/debugger/debugger_config.mli
new file mode 100644
index 0000000000..ab935d9324
--- /dev/null
+++ b/debugger/debugger_config.mli
@@ -0,0 +1,37 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(********************** Configuration file *****************************)
+
+exception Toplevel
+
+(*** Miscellaneous parameters. ***)
+
+val debugger_prompt : string
+val event_mark_before : string
+val event_mark_after : string
+val shell : string
+val runtime_program : string
+val history_size : int ref
+val load_path_for : (string, string list) Hashtbl.t
+
+(*** Time travel paramaters. ***)
+
+val checkpoint_big_step : int64 ref
+val checkpoint_small_step : int64 ref
+val checkpoint_max_count : int ref
+val make_checkpoints : bool ref
+
+(*** Environment variables for debugee. ***)
+
+val environment : (string * string) list ref
diff --git a/debugger/eval.ml b/debugger/eval.ml
new file mode 100644
index 0000000000..1d1ab38865
--- /dev/null
+++ b/debugger/eval.ml
@@ -0,0 +1,208 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Misc
+open Path
+open Instruct
+open Types
+open Parser_aux
+
+type error =
+ Unbound_identifier of Ident.t
+ | Not_initialized_yet of Path.t
+ | Unbound_long_identifier of Longident.t
+ | Unknown_name of int
+ | Tuple_index of type_expr * int * int
+ | Array_index of int * int
+ | List_index of int * int
+ | String_index of string * int * int
+ | Wrong_item_type of type_expr * int
+ | Wrong_label of type_expr * string
+ | Not_a_record of type_expr
+ | No_result
+
+exception Error of error
+
+let abstract_type =
+ Btype.newgenty (Tconstr (Pident (Ident.create "<abstr>"), [], ref Mnil))
+
+let rec path event = function
+ Pident id ->
+ if Ident.global id then
+ try
+ Debugcom.Remote_value.global (Symtable.get_global_position id)
+ with Symtable.Error _ -> raise(Error(Unbound_identifier id))
+ else
+ begin match event with
+ Some ev ->
+ begin try
+ let pos = Ident.find_same id ev.ev_compenv.ce_stack in
+ Debugcom.Remote_value.local (ev.ev_stacksize - pos)
+ with Not_found ->
+ try
+ let pos = Ident.find_same id ev.ev_compenv.ce_heap in
+ Debugcom.Remote_value.from_environment pos
+ with Not_found ->
+ raise(Error(Unbound_identifier id))
+ end
+ | None ->
+ raise(Error(Unbound_identifier id))
+ end
+ | Pdot(root, fieldname, pos) ->
+ let v = path event root in
+ if not (Debugcom.Remote_value.is_block v) then
+ raise(Error(Not_initialized_yet root));
+ Debugcom.Remote_value.field v pos
+ | Papply(p1, p2) ->
+ fatal_error "Eval.path: Papply"
+
+let rec expression event env = function
+ E_ident lid ->
+ begin try
+ let (p, valdesc) = Env.lookup_value lid env in
+ (begin match valdesc.val_kind with
+ Val_ivar (_, cl_num) ->
+ let (p0, _) =
+ Env.lookup_value (Longident.Lident ("self-" ^ cl_num)) env
+ in
+ let v = path event p0 in
+ let i = path event p in
+ Debugcom.Remote_value.field v (Debugcom.Remote_value.obj i)
+ | _ ->
+ path event p
+ end,
+ Ctype.correct_levels valdesc.val_type)
+ with Not_found ->
+ raise(Error(Unbound_long_identifier lid))
+ end
+ | E_result ->
+ begin match event with
+ Some {ev_kind = Event_after ty; ev_typsubst = subst}
+ when !Frames.current_frame = 0 ->
+ (Debugcom.Remote_value.accu(), Subst.type_expr subst ty)
+ | _ ->
+ raise(Error(No_result))
+ end
+ | E_name n ->
+ begin try
+ Printval.find_named_value n
+ with Not_found ->
+ raise(Error(Unknown_name n))
+ end
+ | E_item(arg, n) ->
+ let (v, ty) = expression event env arg in
+ begin match (Ctype.repr(Ctype.expand_head_opt env ty)).desc with
+ Ttuple ty_list ->
+ if n < 1 || n > List.length ty_list
+ then raise(Error(Tuple_index(ty, List.length ty_list, n)))
+ else (Debugcom.Remote_value.field v (n-1), List.nth ty_list (n-1))
+ | Tconstr(path, [ty_arg], _) when Path.same path Predef.path_array ->
+ let size = Debugcom.Remote_value.size v in
+ if n >= size
+ then raise(Error(Array_index(size, n)))
+ else (Debugcom.Remote_value.field v n, ty_arg)
+ | Tconstr(path, [ty_arg], _) when Path.same path Predef.path_list ->
+ let rec nth pos v =
+ if not (Debugcom.Remote_value.is_block v) then
+ raise(Error(List_index(pos, n)))
+ else if pos = n then
+ (Debugcom.Remote_value.field v 0, ty_arg)
+ else
+ nth (pos + 1) (Debugcom.Remote_value.field v 1)
+ in nth 0 v
+ | Tconstr(path, [], _) when Path.same path Predef.path_string ->
+ let s = (Debugcom.Remote_value.obj v : string) in
+ if n >= String.length s
+ then raise(Error(String_index(s, String.length s, n)))
+ else (Debugcom.Remote_value.of_int(Char.code s.[n]),
+ Predef.type_char)
+ | _ ->
+ raise(Error(Wrong_item_type(ty, n)))
+ end
+ | E_field(arg, lbl) ->
+ let (v, ty) = expression event env arg in
+ begin match (Ctype.repr(Ctype.expand_head_opt env ty)).desc with
+ Tconstr(path, args, _) ->
+ let tydesc = Env.find_type path env in
+ begin match tydesc.type_kind with
+ Type_record(lbl_list, repr) ->
+ let (pos, ty_res) =
+ find_label lbl env ty path tydesc 0 lbl_list in
+ (Debugcom.Remote_value.field v pos, ty_res)
+ | _ -> raise(Error(Not_a_record ty))
+ end
+ | _ -> raise(Error(Not_a_record ty))
+ end
+
+and find_label lbl env ty path tydesc pos = function
+ [] ->
+ raise(Error(Wrong_label(ty, lbl)))
+ | {ld_id; ld_type} :: rem ->
+ if Ident.name ld_id = lbl then begin
+ let ty_res =
+ Btype.newgenty(Tconstr(path, tydesc.type_params, ref Mnil))
+ in
+ (pos,
+ try Ctype.apply env [ty_res] ld_type [ty] with Ctype.Cannot_apply ->
+ abstract_type)
+ end else
+ find_label lbl env ty path tydesc (pos + 1) rem
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Unbound_identifier id ->
+ fprintf ppf "@[Unbound identifier %s@]@." (Ident.name id)
+ | Not_initialized_yet path ->
+ fprintf ppf
+ "@[The module path %a is not yet initialized.@ \
+ Please run program forward@ \
+ until its initialization code is executed.@]@."
+ Printtyp.path path
+ | Unbound_long_identifier lid ->
+ fprintf ppf "@[Unbound identifier %a@]@." Printtyp.longident lid
+ | Unknown_name n ->
+ fprintf ppf "@[Unknown value name $%i@]@." n
+ | Tuple_index(ty, len, pos) ->
+ Printtyp.reset_and_mark_loops ty;
+ fprintf ppf
+ "@[Cannot extract field number %i from a %i-tuple of type@ %a@]@."
+ pos len Printtyp.type_expr ty
+ | Array_index(len, pos) ->
+ fprintf ppf
+ "@[Cannot extract element number %i from an array of length %i@]@."
+ pos len
+ | List_index(len, pos) ->
+ fprintf ppf
+ "@[Cannot extract element number %i from a list of length %i@]@."
+ pos len
+ | String_index(s, len, pos) ->
+ fprintf ppf
+ "@[Cannot extract character number %i@ \
+ from the following string of length %i:@ %S@]@."
+ pos len s
+ | Wrong_item_type(ty, pos) ->
+ fprintf ppf
+ "@[Cannot extract item number %i from a value of type@ %a@]@."
+ pos Printtyp.type_expr ty
+ | Wrong_label(ty, lbl) ->
+ fprintf ppf
+ "@[The record type@ %a@ has no label named %s@]@."
+ Printtyp.type_expr ty lbl
+ | Not_a_record ty ->
+ fprintf ppf
+ "@[The type@ %a@ is not a record type@]@." Printtyp.type_expr ty
+ | No_result ->
+ fprintf ppf "@[No result available at current program event@]@."
diff --git a/debugger/eval.mli b/debugger/eval.mli
new file mode 100644
index 0000000000..c5e04f3315
--- /dev/null
+++ b/debugger/eval.mli
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Types
+open Parser_aux
+open Format
+
+val expression :
+ Instruct.debug_event option -> Env.t -> expression ->
+ Debugcom.Remote_value.t * type_expr
+
+type error =
+ | Unbound_identifier of Ident.t
+ | Not_initialized_yet of Path.t
+ | Unbound_long_identifier of Longident.t
+ | Unknown_name of int
+ | Tuple_index of type_expr * int * int
+ | Array_index of int * int
+ | List_index of int * int
+ | String_index of string * int * int
+ | Wrong_item_type of type_expr * int
+ | Wrong_label of type_expr * string
+ | Not_a_record of type_expr
+ | No_result
+
+exception Error of error
+
+val report_error: formatter -> error -> unit
diff --git a/debugger/events.ml b/debugger/events.ml
new file mode 100644
index 0000000000..c622f67226
--- /dev/null
+++ b/debugger/events.ml
@@ -0,0 +1,46 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(********************************* Events ******************************)
+
+open Instruct
+
+let get_pos ev =
+ match ev.ev_kind with
+ | Event_before -> ev.ev_loc.Location.loc_start
+ | Event_after _ -> ev.ev_loc.Location.loc_end
+ | _ -> ev.ev_loc.Location.loc_start
+;;
+
+
+(*** Current events. ***)
+
+(* Event at current position *)
+let current_event =
+ ref (None : debug_event option)
+
+(* Current position in source. *)
+(* Raise `Not_found' if not on an event (beginning or end of program). *)
+let get_current_event () =
+ match !current_event with
+ | None -> raise Not_found
+ | Some ev -> ev
+
+let current_event_is_before () =
+ match !current_event with
+ None ->
+ raise Not_found
+ | Some {ev_kind = Event_before} ->
+ true
+ | _ ->
+ false
diff --git a/debugger/events.mli b/debugger/events.mli
new file mode 100644
index 0000000000..e593be03c4
--- /dev/null
+++ b/debugger/events.mli
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Instruct
+
+val get_pos : debug_event -> Lexing.position;;
+
+(** Current events. **)
+
+(* The event at current position. *)
+val current_event : debug_event option ref
+
+(* Current position in source. *)
+(* Raise `Not_found' if not on an event (beginning or end of program). *)
+val get_current_event : unit -> debug_event
+
+val current_event_is_before : unit -> bool
diff --git a/debugger/exec.ml b/debugger/exec.ml
new file mode 100644
index 0000000000..931c0a9199
--- /dev/null
+++ b/debugger/exec.ml
@@ -0,0 +1,51 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Handling of keyboard interrupts *)
+
+let interrupted = ref false
+
+let is_protected = ref false
+
+let break signum =
+ if !is_protected
+ then interrupted := true
+ else raise Sys.Break
+
+let _ =
+ match Sys.os_type with
+ "Win32" -> ()
+ | _ ->
+ Sys.set_signal Sys.sigint (Sys.Signal_handle break);
+ Sys.set_signal Sys.sigpipe (Sys.Signal_handle(fun _ -> raise End_of_file))
+
+let protect f =
+ if !is_protected then
+ f ()
+ else begin
+ is_protected := true;
+ if not !interrupted then
+ f ();
+ is_protected := false;
+ if !interrupted then begin interrupted := false; raise Sys.Break end
+ end
+
+let unprotect f =
+ if not !is_protected then
+ f ()
+ else begin
+ is_protected := false;
+ if !interrupted then begin interrupted := false; raise Sys.Break end;
+ f ();
+ is_protected := true
+ end
diff --git a/debugger/exec.mli b/debugger/exec.mli
new file mode 100644
index 0000000000..a820589b59
--- /dev/null
+++ b/debugger/exec.mli
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Handling of keyboard interrupts *)
+
+val protect : (unit -> unit) -> unit
+val unprotect : (unit -> unit) -> unit
diff --git a/debugger/frames.ml b/debugger/frames.ml
new file mode 100644
index 0000000000..d3456284d1
--- /dev/null
+++ b/debugger/frames.ml
@@ -0,0 +1,127 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(***************************** Frames **********************************)
+
+open Instruct
+open Debugcom
+open Events
+open Symbols
+
+(* Current frame number *)
+let current_frame = ref 0
+
+(* Event at selected position *)
+let selected_event = ref (None : debug_event option)
+
+(* Selected position in source. *)
+(* Raise `Not_found' if not on an event. *)
+let selected_point () =
+ match !selected_event with
+ None ->
+ raise Not_found
+ | Some ev ->
+ (ev.ev_module,
+ (Events.get_pos ev).Lexing.pos_lnum,
+ (Events.get_pos ev).Lexing.pos_cnum - (Events.get_pos ev).Lexing.pos_bol)
+
+let selected_event_is_before () =
+ match !selected_event with
+ None ->
+ raise Not_found
+ | Some {ev_kind = Event_before} ->
+ true
+ | _ ->
+ false
+
+(* Move up `frame_count' frames, assuming current frame pointer
+ corresponds to event `event'. Return event of final frame. *)
+
+let rec move_up frame_count event =
+ if frame_count <= 0 then event else begin
+ let (sp, pc) = up_frame event.ev_stacksize in
+ if sp < 0 then raise Not_found;
+ move_up (frame_count - 1) (any_event_at_pc pc)
+ end
+
+(* Select a frame. *)
+(* Raise `Not_found' if no such frame. *)
+(* --- Assume the current events have already been updated. *)
+let select_frame frame_number =
+ if frame_number < 0 then raise Not_found;
+ let (initial_sp, _) = get_frame() in
+ try
+ match !current_event with
+ None ->
+ raise Not_found
+ | Some curr_event ->
+ match !selected_event with
+ Some sel_event when frame_number >= !current_frame ->
+ selected_event :=
+ Some(move_up (frame_number - !current_frame) sel_event);
+ current_frame := frame_number
+ | _ ->
+ set_initial_frame();
+ selected_event := Some(move_up frame_number curr_event);
+ current_frame := frame_number
+ with Not_found ->
+ set_frame initial_sp;
+ raise Not_found
+
+(* Select a frame. *)
+(* Same as `select_frame' but raise no exception if the frame is not found. *)
+(* --- Assume the currents events have already been updated. *)
+let try_select_frame frame_number =
+ try
+ select_frame frame_number
+ with
+ Not_found ->
+ ()
+
+(* Return to default frame (frame 0). *)
+let reset_frame () =
+ set_initial_frame();
+ selected_event := !current_event;
+ current_frame := 0
+
+(* Perform a stack backtrace.
+ Call the given function with the events for each stack frame,
+ or None if we've encountered a stack frame with no debugging info
+ attached. Stop when the function returns false, or frame with no
+ debugging info reached, or top of stack reached. *)
+
+let do_backtrace action =
+ match !current_event with
+ None -> Misc.fatal_error "Frames.do_backtrace"
+ | Some curr_ev ->
+ let (initial_sp, _) = get_frame() in
+ set_initial_frame();
+ let event = ref curr_ev in
+ begin try
+ while action (Some !event) do
+ let (sp, pc) = up_frame !event.ev_stacksize in
+ if sp < 0 then raise Exit;
+ event := any_event_at_pc pc
+ done
+ with Exit -> ()
+ | Not_found -> ignore (action None)
+ end;
+ set_frame initial_sp
+
+(* Return the number of frames in the stack *)
+
+let stack_depth () =
+ let num_frames = ref 0 in
+ do_backtrace (function Some ev -> incr num_frames; true
+ | None -> num_frames := -1; false);
+ !num_frames
diff --git a/debugger/frames.mli b/debugger/frames.mli
new file mode 100644
index 0000000000..fa652b0ceb
--- /dev/null
+++ b/debugger/frames.mli
@@ -0,0 +1,53 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(****************************** Frames *********************************)
+
+open Instruct
+open Primitives
+
+(* Current frame number *)
+val current_frame : int ref
+
+(* Event at selected position. *)
+val selected_event : debug_event option ref
+
+(* Selected position in source (module, line, column). *)
+(* Raise `Not_found' if not on an event. *)
+val selected_point : unit -> string * int * int
+
+val selected_event_is_before : unit -> bool
+
+(* Select a frame. *)
+(* Raise `Not_found' if no such frame. *)
+(* --- Assume the currents events have already been updated. *)
+val select_frame : int -> unit
+
+(* Select a frame. *)
+(* Same as `select_frame' but raise no exception if the frame is not found. *)
+(* --- Assume the currents events have already been updated. *)
+val try_select_frame : int -> unit
+
+(* Return to default frame (frame 0). *)
+val reset_frame : unit -> unit
+
+(* Perform a stack backtrace.
+ Call the given function with the events for each stack frame,
+ or None if we've encountered a stack frame with no debugging info
+ attached. Stop when the function returns false, or frame with no
+ debugging info reached, or top of stack reached. *)
+val do_backtrace : (debug_event option -> bool) -> unit
+
+(* Return the number of frames in the stack, or (-1) if it can't be
+ determined because some frames have no debugging info. *)
+val stack_depth : unit -> int
diff --git a/debugger/history.ml b/debugger/history.ml
new file mode 100644
index 0000000000..4d08f587c8
--- /dev/null
+++ b/debugger/history.ml
@@ -0,0 +1,41 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Int64ops
+open Checkpoints
+open Primitives
+open Debugger_config
+
+let history = ref ([] : int64 list)
+
+let empty_history () =
+ history := []
+
+let add_current_time () =
+ let time = current_time () in
+ if !history = [] then
+ history := [time]
+ else if time <> List.hd !history then
+ history := list_truncate !history_size (time::!history)
+
+let previous_time_1 () =
+ match !history with
+ _::((time::_) as hist) ->
+ history := hist; time
+ | _ ->
+ prerr_endline "No more information."; raise Toplevel
+
+let rec previous_time n =
+ if n = _1
+ then previous_time_1()
+ else begin ignore(previous_time_1()); previous_time(pre64 n) end
diff --git a/debugger/history.mli b/debugger/history.mli
new file mode 100644
index 0000000000..121c732fb8
--- /dev/null
+++ b/debugger/history.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val empty_history : unit -> unit
+
+val add_current_time : unit -> unit
+
+val previous_time : int64 -> int64
diff --git a/debugger/input_handling.ml b/debugger/input_handling.ml
new file mode 100644
index 0000000000..f3bd57b633
--- /dev/null
+++ b/debugger/input_handling.ml
@@ -0,0 +1,113 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(**************************** Input control ****************************)
+
+open Unix
+open Primitives
+
+(*** Actives files. ***)
+
+(* List of the actives files. *)
+let active_files =
+ ref ([] : (file_descr * ((io_channel -> unit) * io_channel)) list)
+
+(* Add a file to the list of actives files. *)
+let add_file file controller =
+ active_files := (file.io_fd, (controller, file))::!active_files
+
+(* Remove a file from the list of actives files. *)
+let remove_file file =
+ active_files := List.remove_assoc file.io_fd !active_files
+
+(* Change the controller for the given file. *)
+let change_controller file controller =
+ remove_file file; add_file file controller
+
+(* Return the controller currently attached to the given file. *)
+let current_controller file =
+ fst (List.assoc file.io_fd !active_files)
+
+(* Execute a function with `controller' attached to `file'. *)
+(* ### controller file funct *)
+let execute_with_other_controller controller file funct =
+ let old_controller = current_controller file in
+ change_controller file controller;
+ try
+ let result = funct () in
+ change_controller file old_controller;
+ result
+ with
+ x ->
+ change_controller file old_controller;
+ raise x
+
+(*** The "Main Loop" ***)
+
+let continue_main_loop =
+ ref true
+
+let exit_main_loop _ =
+ continue_main_loop := false
+
+(* Handle active files until `continue_main_loop' is false. *)
+let main_loop () =
+ let old_state = !continue_main_loop in
+ try
+ continue_main_loop := true;
+ while !continue_main_loop do
+ try
+ let (input, _, _) =
+ select (List.map fst !active_files) [] [] (-1.)
+ in
+ List.iter
+ (function fd ->
+ let (funct, iochan) = (List.assoc fd !active_files) in
+ funct iochan)
+ input
+ with
+ Unix_error (EINTR, _, _) -> ()
+ done;
+ continue_main_loop := old_state
+ with
+ x ->
+ continue_main_loop := old_state;
+ raise x
+
+(*** Managing user inputs ***)
+
+(* Are we in interactive mode ? *)
+let interactif = ref true
+
+let current_prompt = ref ""
+
+(* Where the user input come from. *)
+let user_channel = ref std_io
+
+let read_user_input buffer length =
+ main_loop ();
+ input !user_channel.io_in buffer 0 length
+
+(* Stop reading user input. *)
+let stop_user_input () =
+ remove_file !user_channel
+
+(* Resume reading user input. *)
+let resume_user_input () =
+ if not (List.mem_assoc !user_channel.io_fd !active_files) then begin
+ if !interactif then begin
+ print_string !current_prompt;
+ flush Pervasives.stdout
+ end;
+ add_file !user_channel exit_main_loop
+ end
diff --git a/debugger/input_handling.mli b/debugger/input_handling.mli
new file mode 100644
index 0000000000..66db47f15f
--- /dev/null
+++ b/debugger/input_handling.mli
@@ -0,0 +1,58 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(***************************** Input control ***************************)
+
+open Primitives
+
+(*** Actives files. ***)
+
+(* Add a file to the list of active files. *)
+val add_file : io_channel -> (io_channel -> unit) -> unit
+
+(* Remove a file from the list of actives files. *)
+val remove_file : io_channel -> unit
+
+(* Return the controller currently attached to the given file. *)
+val current_controller : io_channel -> (io_channel -> unit)
+
+(* Execute a function with `controller' attached to `file'. *)
+(* ### controller file funct *)
+val execute_with_other_controller :
+ (io_channel -> unit) -> io_channel -> (unit -> 'a) -> 'a
+
+(*** The "Main Loop" ***)
+
+(* Call this function for exiting the main loop. *)
+val exit_main_loop : 'a -> unit
+
+(* Handle active files until `continue_main_loop' is false. *)
+val main_loop : unit -> unit
+
+(*** Managing user inputs ***)
+
+(* Are we in interactive mode ? *)
+val interactif : bool ref
+
+val current_prompt : string ref
+
+(* Where the user input come from. *)
+val user_channel : io_channel ref
+
+val read_user_input : bytes -> int -> int
+
+(* Stop reading user input. *)
+val stop_user_input : unit -> unit
+
+(* Resume reading user input. *)
+val resume_user_input : unit -> unit
diff --git a/debugger/int64ops.ml b/debugger/int64ops.ml
new file mode 100644
index 0000000000..527bdcef0f
--- /dev/null
+++ b/debugger/int64ops.ml
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocqencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(****************** arithmetic operators for Int64 *********************)
+
+let ( ++ ) = Int64.add;;
+let ( -- ) = Int64.sub;;
+let suc64 = Int64.succ;;
+let pre64 = Int64.pred;;
+let _0 = Int64.zero;;
+let _1 = Int64.one;;
+let _minus1 = Int64.minus_one;;
+let ( ~~ ) = Int64.of_string;;
+let max_small_int = Int64.of_int max_int;;
+let to_int = Int64.to_int;;
diff --git a/debugger/int64ops.mli b/debugger/int64ops.mli
new file mode 100644
index 0000000000..5491c8f702
--- /dev/null
+++ b/debugger/int64ops.mli
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocqencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(****************** arithmetic operators for Int64 *********************)
+
+val ( ++ ) : int64 -> int64 -> int64;;
+val ( -- ) : int64 -> int64 -> int64;;
+val suc64 : int64 -> int64;;
+val pre64 : int64 -> int64;;
+val _0 : int64;;
+val _1 : int64;;
+val _minus1 : int64;;
+val ( ~~ ) : string -> int64;;
+val max_small_int : int64;;
+val to_int : int64 -> int;;
diff --git a/debugger/lexer.mli b/debugger/lexer.mli
new file mode 100644
index 0000000000..7508bedd8f
--- /dev/null
+++ b/debugger/lexer.mli
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val line: Lexing.lexbuf -> string
+val lexeme: Lexing.lexbuf -> Parser.token
+val argument: Lexing.lexbuf -> Parser.token
+val line_argument: Lexing.lexbuf -> Parser.token
diff --git a/debugger/lexer.mll b/debugger/lexer.mll
new file mode 100644
index 0000000000..721645c856
--- /dev/null
+++ b/debugger/lexer.mll
@@ -0,0 +1,95 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+{
+
+open Parser
+
+}
+
+rule line = (* Read a whole line *)
+ parse
+ ([ ^ '\n' '\r' ]* as s) ('\n' | '\r' | "\r\n")
+ { s }
+ | [ ^ '\n' '\r' ]*
+ { Lexing.lexeme lexbuf }
+ | eof
+ { raise Exit }
+
+and argument = (* Read a raw argument *)
+ parse
+ [ ^ ' ' '\t' ]+
+ { ARGUMENT (Lexing.lexeme lexbuf) }
+ | [' ' '\t']+
+ { argument lexbuf }
+ | eof
+ { EOL }
+ | _
+ { raise Parsing.Parse_error }
+
+and line_argument =
+ parse
+ _ *
+ { ARGUMENT (Lexing.lexeme lexbuf) }
+ | eof
+ { EOL }
+
+and lexeme = (* Read a lexeme *)
+ parse
+ [' ' '\t'] +
+ { lexeme lexbuf }
+ | ['a'-'z' '\223'-'\246' '\248'-'\255' '_']
+ (['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255'
+ '\'' '0'-'9' ]) *
+ { LIDENT(Lexing.lexeme lexbuf) }
+ | ['A'-'Z' '\192'-'\214' '\216'-'\222' ]
+ (['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255'
+ '\'' '0'-'9' ]) *
+ { UIDENT(Lexing.lexeme lexbuf) }
+ | '"' [^ '"']* "\""
+ { let s = Lexing.lexeme lexbuf in
+ LIDENT(String.sub s 1 (String.length s - 2)) }
+ | ['0'-'9']+
+ | '0' ['x' 'X'] ['0'-'9' 'A'-'F' 'a'-'f']+
+ | '0' ['o' 'O'] ['0'-'7']+
+ | '0' ['b' 'B'] ['0'-'1']+
+ { INTEGER (Int64.of_string (Lexing.lexeme lexbuf)) }
+ | '*'
+ { STAR }
+ | "-"
+ { MINUS }
+ | "."
+ { DOT }
+ | "#"
+ { SHARP }
+ | "@"
+ { AT }
+ | "$"
+ { DOLLAR }
+ | "!"
+ { BANG }
+ | "("
+ { LPAREN }
+ | ")"
+ { RPAREN }
+ | "["
+ { LBRACKET }
+ | "]"
+ { RBRACKET }
+ | ['!' '?' '~' '=' '<' '>' '|' '&' '$' '@' '^' '+' '-' '*' '/' '%']
+ ['!' '$' '%' '&' '*' '+' '-' '.' '/' ':' '<' '=' '>' '?' '@' '^' '|' '~'] *
+ { OPERATOR (Lexing.lexeme lexbuf) }
+ | eof
+ { EOL }
+ | _
+ { raise Parsing.Parse_error }
diff --git a/debugger/loadprinter.ml b/debugger/loadprinter.ml
new file mode 100644
index 0000000000..16d6e9f2b4
--- /dev/null
+++ b/debugger/loadprinter.ml
@@ -0,0 +1,176 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Loading and installation of user-defined printer functions *)
+
+open Misc
+open Longident
+open Path
+open Types
+
+(* Error report *)
+
+type error =
+ | Load_failure of Dynlink.error
+ | Unbound_identifier of Longident.t
+ | Unavailable_module of string * Longident.t
+ | Wrong_type of Longident.t
+ | No_active_printer of Longident.t
+
+exception Error of error
+
+(* Symtable has global state, and normally holds the symbol table
+ for the debuggee. We need to switch it temporarily to the
+ symbol table for the debugger. *)
+
+let debugger_symtable = ref (None: Symtable.global_map option)
+
+let use_debugger_symtable fn arg =
+ let old_symtable = Symtable.current_state() in
+ begin match !debugger_symtable with
+ | None ->
+ Dynlink.init();
+ Dynlink.allow_unsafe_modules true;
+ debugger_symtable := Some(Symtable.current_state())
+ | Some st ->
+ Symtable.restore_state st
+ end;
+ try
+ let result = fn arg in
+ debugger_symtable := Some(Symtable.current_state());
+ Symtable.restore_state old_symtable;
+ result
+ with exn ->
+ Symtable.restore_state old_symtable;
+ raise exn
+
+(* Load a .cmo or .cma file *)
+
+open Format
+
+let rec loadfiles ppf name =
+ try
+ let filename = find_in_path !Config.load_path name in
+ use_debugger_symtable Dynlink.loadfile filename;
+ let d = Filename.dirname name in
+ if d <> Filename.current_dir_name then begin
+ if not (List.mem d !Config.load_path) then
+ Config.load_path := d :: !Config.load_path;
+ end;
+ fprintf ppf "File %s loaded@." filename;
+ true
+ with
+ | Dynlink.Error (Dynlink.Unavailable_unit unit) ->
+ loadfiles ppf (String.uncapitalize_ascii unit ^ ".cmo")
+ &&
+ loadfiles ppf name
+ | Not_found ->
+ fprintf ppf "Cannot find file %s@." name;
+ false
+ | Dynlink.Error e ->
+ raise(Error(Load_failure e))
+
+let loadfile ppf name =
+ ignore(loadfiles ppf name)
+
+(* Return the value referred to by a path (as in toplevel/topdirs) *)
+(* Note: evaluation proceeds in the debugger memory space, not in
+ the debuggee. *)
+
+let rec eval_path = function
+ Pident id -> Symtable.get_global_value id
+ | Pdot(p, s, pos) -> Obj.field (eval_path p) pos
+ | Papply(p1, p2) -> fatal_error "Loadprinter.eval_path"
+
+(* Install, remove a printer (as in toplevel/topdirs) *)
+
+(* since 4.00, "topdirs.cmi" is not in the same directory as the standard
+ libray, so we load it beforehand as it cannot be found in the search path. *)
+let () =
+ let compiler_libs =
+ Filename.concat Config.standard_library "compiler-libs" in
+ let topdirs =
+ Filename.concat compiler_libs "topdirs.cmi" in
+ ignore (Env.read_signature "Topdirs" topdirs)
+
+let match_printer_type desc typename =
+ let (printer_type, _) =
+ try
+ Env.lookup_type (Ldot(Lident "Topdirs", typename)) Env.empty
+ with Not_found ->
+ raise (Error(Unbound_identifier(Ldot(Lident "Topdirs", typename)))) in
+ Ctype.init_def(Ident.current_time());
+ Ctype.begin_def();
+ let ty_arg = Ctype.newvar() in
+ Ctype.unify Env.empty
+ (Ctype.newconstr printer_type [ty_arg])
+ (Ctype.instance Env.empty desc.val_type);
+ Ctype.end_def();
+ Ctype.generalize ty_arg;
+ ty_arg
+
+let find_printer_type lid =
+ try
+ let (path, desc) = Env.lookup_value lid Env.empty in
+ let (ty_arg, is_old_style) =
+ try
+ (match_printer_type desc "printer_type_new", false)
+ with Ctype.Unify _ ->
+ (match_printer_type desc "printer_type_old", true) in
+ (ty_arg, path, is_old_style)
+ with
+ | Not_found -> raise(Error(Unbound_identifier lid))
+ | Ctype.Unify _ -> raise(Error(Wrong_type lid))
+
+let install_printer ppf lid =
+ let (ty_arg, path, is_old_style) = find_printer_type lid in
+ let v =
+ try
+ use_debugger_symtable eval_path path
+ with Symtable.Error(Symtable.Undefined_global s) ->
+ raise(Error(Unavailable_module(s, lid))) in
+ let print_function =
+ if is_old_style then
+ (fun formatter repr -> Obj.obj v (Obj.obj repr))
+ else
+ (fun formatter repr -> Obj.obj v formatter (Obj.obj repr)) in
+ Printval.install_printer path ty_arg ppf print_function
+
+let remove_printer lid =
+ let (ty_arg, path, is_old_style) = find_printer_type lid in
+ try
+ Printval.remove_printer path
+ with Not_found ->
+ raise(Error(No_active_printer lid))
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Load_failure e ->
+ fprintf ppf "@[Error during code loading: %s@]@."
+ (Dynlink.error_message e)
+ | Unbound_identifier lid ->
+ fprintf ppf "@[Unbound identifier %a@]@."
+ Printtyp.longident lid
+ | Unavailable_module(md, lid) ->
+ fprintf ppf
+ "@[The debugger does not contain the code for@ %a.@ \
+ Please load an implementation of %s first.@]@."
+ Printtyp.longident lid md
+ | Wrong_type lid ->
+ fprintf ppf "@[%a has the wrong type for a printing function.@]@."
+ Printtyp.longident lid
+ | No_active_printer lid ->
+ fprintf ppf "@[%a is not currently active as a printing function.@]@."
+ Printtyp.longident lid
diff --git a/debugger/loadprinter.mli b/debugger/loadprinter.mli
new file mode 100644
index 0000000000..4851a4d521
--- /dev/null
+++ b/debugger/loadprinter.mli
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Loading and installation of user-defined printer functions *)
+
+open Format
+
+val loadfile : formatter -> string -> unit
+val install_printer : formatter -> Longident.t -> unit
+val remove_printer : Longident.t -> unit
+
+(* Error report *)
+
+type error =
+ | Load_failure of Dynlink.error
+ | Unbound_identifier of Longident.t
+ | Unavailable_module of string * Longident.t
+ | Wrong_type of Longident.t
+ | No_active_printer of Longident.t
+
+exception Error of error
+
+val report_error: formatter -> error -> unit
diff --git a/debugger/main.ml b/debugger/main.ml
new file mode 100644
index 0000000000..60cd96a89a
--- /dev/null
+++ b/debugger/main.ml
@@ -0,0 +1,232 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Input_handling
+open Question
+open Command_line
+open Debugger_config
+open Checkpoints
+open Time_travel
+open Parameters
+open Program_management
+open Frames
+open Show_information
+open Format
+open Primitives
+
+let line_buffer = Lexing.from_function read_user_input
+
+let rec loop ppf = line_loop ppf line_buffer
+
+let current_duration = ref (-1L)
+
+let rec protect ppf restart loop =
+ try
+ loop ppf
+ with
+ | End_of_file ->
+ protect ppf restart (function ppf ->
+ forget_process
+ !current_checkpoint.c_fd
+ !current_checkpoint.c_pid;
+ pp_print_flush ppf ();
+ stop_user_input ();
+ restart ppf)
+ | Toplevel ->
+ protect ppf restart (function ppf ->
+ pp_print_flush ppf ();
+ stop_user_input ();
+ restart ppf)
+ | Sys.Break ->
+ protect ppf restart (function ppf ->
+ fprintf ppf "Interrupted.@.";
+ Exec.protect (function () ->
+ stop_user_input ();
+ if !loaded then begin
+ try_select_frame 0;
+ show_current_event ppf;
+ end);
+ restart ppf)
+ | Current_checkpoint_lost ->
+ protect ppf restart (function ppf ->
+ fprintf ppf "Trying to recover...@.";
+ stop_user_input ();
+ recover ();
+ try_select_frame 0;
+ show_current_event ppf;
+ restart ppf)
+ | Current_checkpoint_lost_start_at (time, init_duration) ->
+ protect ppf restart (function ppf ->
+ let b =
+ if !current_duration = -1L then begin
+ let msg = sprintf "Restart from time %Ld and try to get \
+ closer of the problem" time in
+ stop_user_input ();
+ if yes_or_no msg then
+ (current_duration := init_duration; true)
+ else
+ false
+ end
+ else
+ true in
+ if b then
+ begin
+ go_to time;
+ current_duration := Int64.div !current_duration 10L;
+ if !current_duration > 0L then
+ while true do
+ step !current_duration
+ done
+ else begin
+ current_duration := -1L;
+ stop_user_input ();
+ show_current_event ppf;
+ restart ppf;
+ end
+ end
+ else
+ begin
+ recover ();
+ show_current_event ppf;
+ restart ppf
+ end)
+ | x ->
+ kill_program ();
+ raise x
+
+let execute_file_if_any () =
+ let buffer = Buffer.create 128 in
+ begin
+ try
+ let base = ".ocamldebug" in
+ let file =
+ if Sys.file_exists base then
+ base
+ else
+ Filename.concat (Sys.getenv "HOME") base in
+ let ch = open_in file in
+ fprintf Format.std_formatter "Executing file %s@." file;
+ while true do
+ let line = string_trim (input_line ch) in
+ if line <> "" && line.[0] <> '#' then begin
+ Buffer.add_string buffer line;
+ Buffer.add_char buffer '\n'
+ end
+ done;
+ with _ -> ()
+ end;
+ let len = Buffer.length buffer in
+ if len > 0 then
+ let commands = Buffer.sub buffer 0 (pred len) in
+ line_loop Format.std_formatter (Lexing.from_string commands)
+
+let toplevel_loop () =
+ interactif := false;
+ current_prompt := "";
+ execute_file_if_any ();
+ interactif := true;
+ current_prompt := debugger_prompt;
+ protect Format.std_formatter loop loop
+
+(* Parsing of command-line arguments *)
+
+exception Found_program_name
+
+let anonymous s =
+ program_name := Unix_tools.make_absolute s; raise Found_program_name
+let add_include d =
+ default_load_path :=
+ Misc.expand_directory Config.standard_library d :: !default_load_path
+let set_socket s =
+ socket_name := s
+let set_checkpoints n =
+ checkpoint_max_count := n
+let set_directory dir =
+ Sys.chdir dir
+let print_version () =
+ printf "The OCaml debugger, version %s@." Sys.ocaml_version;
+ exit 0;
+;;
+let print_version_num () =
+ printf "%s@." Sys.ocaml_version;
+ exit 0;
+;;
+
+let speclist = [
+ "-c", Arg.Int set_checkpoints,
+ "<count> Set max number of checkpoints kept";
+ "-cd", Arg.String set_directory,
+ "<dir> Change working directory";
+ "-emacs", Arg.Tuple [Arg.Set emacs; Arg.Set machine_readable],
+ "For running the debugger under emacs; implies -machine-readable";
+ "-I", Arg.String add_include,
+ "<dir> Add <dir> to the list of include directories";
+ "-machine-readable", Arg.Set machine_readable,
+ "Print information in a format more suitable for machines";
+ "-s", Arg.String set_socket,
+ "<filename> Set the name of the communication socket";
+ "-version", Arg.Unit print_version,
+ " Print version and exit";
+ "-vnum", Arg.Unit print_version_num,
+ " Print version number and exit";
+ ]
+
+let function_placeholder () =
+ raise Not_found
+
+let main () =
+ Callback.register "Debugger.function_placeholder" function_placeholder;
+ try
+ socket_name :=
+ (match Sys.os_type with
+ "Win32" ->
+ (Unix.string_of_inet_addr Unix.inet_addr_loopback)^
+ ":"^
+ (string_of_int (10000 + ((Unix.getpid ()) mod 10000)))
+ | _ -> Filename.concat (Filename.get_temp_dir_name ())
+ ("camldebug" ^ (string_of_int (Unix.getpid ())))
+ );
+ begin try
+ Arg.parse speclist anonymous "";
+ Arg.usage speclist
+ "No program name specified\n\
+ Usage: ocamldebug [options] <program> [arguments]\n\
+ Options are:";
+ exit 2
+ with Found_program_name ->
+ for j = !Arg.current + 1 to Array.length Sys.argv - 1 do
+ arguments := !arguments ^ " " ^ (Filename.quote Sys.argv.(j))
+ done
+ end;
+ printf "\tOCaml Debugger version %s@.@." Config.version;
+ Config.load_path := !default_load_path;
+ Clflags.recursive_types := true; (* Allow recursive types. *)
+ toplevel_loop (); (* Toplevel. *)
+ kill_program ();
+ exit 0
+ with
+ Toplevel ->
+ exit 2
+ | Env.Error e ->
+ eprintf "Debugger [version %s] environment error:@ @[@;" Config.version;
+ Env.report_error err_formatter e;
+ eprintf "@]@.";
+ exit 2
+ | Cmi_format.Error e ->
+ eprintf "Debugger [version %s] environment error:@ @[@;" Config.version;
+ Cmi_format.report_error err_formatter e;
+ eprintf "@]@.";
+ exit 2
+
+let _ =
+ Printexc.catch (Unix.handle_unix_error main) ()
diff --git a/debugger/parameters.ml b/debugger/parameters.ml
new file mode 100644
index 0000000000..d8c85efe00
--- /dev/null
+++ b/debugger/parameters.ml
@@ -0,0 +1,39 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Miscellaneous parameters *)
+
+open Primitives
+open Config
+open Debugger_config
+
+let program_loaded = ref false
+let program_name = ref ""
+let socket_name = ref ""
+let arguments = ref ""
+
+let default_load_path =
+ ref [ Filename.current_dir_name; Config.standard_library ]
+
+let add_path dir =
+ load_path := dir :: except dir !load_path;
+ Envaux.reset_cache()
+
+let add_path_for mdl dir =
+ let old = try Hashtbl.find load_path_for mdl with Not_found -> [] in
+ Hashtbl.replace load_path_for mdl (dir :: old)
+
+(* Used by emacs ? *)
+let emacs = ref false
+
+let machine_readable = ref false
diff --git a/debugger/parameters.mli b/debugger/parameters.mli
new file mode 100644
index 0000000000..44c850d5c7
--- /dev/null
+++ b/debugger/parameters.mli
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Miscellaneous parameters *)
+
+val program_name : string ref
+val socket_name : string ref
+val arguments : string ref
+val default_load_path : string list ref
+
+val add_path : string -> unit
+val add_path_for : string -> string -> unit
+
+(* Used by emacs ? *)
+val emacs : bool ref
+
+val machine_readable : bool ref
diff --git a/debugger/parser.mly b/debugger/parser.mly
new file mode 100644
index 0000000000..1d394e3452
--- /dev/null
+++ b/debugger/parser.mly
@@ -0,0 +1,253 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Jerome Vouillon, projet Cristal, INRIA Rocquencourt */
+/* OCaml port by John Malecki and Xavier Leroy */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+%{
+
+open Int64ops
+open Input_handling
+open Longident
+open Parser_aux
+
+%}
+
+%token <string> ARGUMENT
+%token <string> LIDENT
+%token <string> UIDENT
+%token <string> OPERATOR
+%token <int64> INTEGER
+%token STAR /* * */
+%token MINUS /* - */
+%token DOT /* . */
+%token SHARP /* # */
+%token AT /* @ */
+%token DOLLAR /* $ */
+%token BANG /* ! */
+%token LPAREN /* ( */
+%token RPAREN /* ) */
+%token LBRACKET /* [ */
+%token RBRACKET /* ] */
+%token EOL
+
+%right DOT
+%right BANG
+
+%start argument_list_eol
+%type <string list> argument_list_eol
+
+%start argument_eol
+%type <string> argument_eol
+
+%start integer_list_eol
+%type <int list> integer_list_eol
+
+%start integer_eol
+%type <int> integer_eol
+
+%start int64_eol
+%type <int64> int64_eol
+
+%start integer
+%type <int> integer
+
+%start opt_integer_eol
+%type <int option> opt_integer_eol
+
+%start opt_signed_integer_eol
+%type <int option> opt_signed_integer_eol
+
+%start opt_signed_int64_eol
+%type <int64 option> opt_signed_int64_eol
+
+%start identifier
+%type <string> identifier
+
+%start identifier_eol
+%type <string> identifier_eol
+
+%start identifier_or_eol
+%type <string option> identifier_or_eol
+
+%start opt_identifier
+%type <string option> opt_identifier
+
+%start opt_identifier_eol
+%type <string option> opt_identifier_eol
+
+%start expression_list_eol
+%type <Parser_aux.expression list> expression_list_eol
+
+%start break_argument_eol
+%type <Parser_aux.break_arg> break_argument_eol
+
+%start list_arguments_eol
+%type <Longident.t option * int option * int option> list_arguments_eol
+
+%start end_of_line
+%type <unit> end_of_line
+
+%start longident_eol
+%type <Longident.t> longident_eol
+
+%start opt_longident
+%type <Longident.t option> opt_longident
+
+%start opt_longident_eol
+%type <Longident.t option> opt_longident_eol
+
+%%
+
+/* Raw arguments */
+
+argument_list_eol :
+ ARGUMENT argument_list_eol
+ { $1::$2 }
+ | end_of_line
+ { [] };
+
+argument_eol :
+ ARGUMENT end_of_line
+ { $1 };
+
+/* Integer */
+
+integer_list_eol :
+ INTEGER integer_list_eol
+ { (to_int $1) :: $2 }
+ | end_of_line
+ { [] };
+
+integer_eol :
+ INTEGER end_of_line
+ { to_int $1 };
+
+int64_eol :
+ INTEGER end_of_line
+ { $1 };
+
+integer :
+ INTEGER
+ { to_int $1 };
+
+opt_integer_eol :
+ INTEGER end_of_line
+ { Some (to_int $1) }
+ | end_of_line
+ { None };
+
+opt_int64_eol :
+ INTEGER end_of_line
+ { Some $1 }
+ | end_of_line
+ { None };
+
+opt_signed_integer_eol :
+ MINUS integer_eol
+ { Some (- $2) }
+ | opt_integer_eol
+ { $1 };
+
+opt_signed_int64_eol :
+ MINUS int64_eol
+ { Some (Int64.neg $2) }
+ | opt_int64_eol
+ { $1 };
+
+/* Identifiers and long identifiers */
+
+longident :
+ LIDENT { Lident $1 }
+ | module_path DOT LIDENT { Ldot($1, $3) }
+ | OPERATOR { Lident $1 }
+ | module_path DOT OPERATOR { Ldot($1, $3) }
+ | module_path DOT LPAREN OPERATOR RPAREN { Ldot($1, $4) }
+;
+
+module_path :
+ UIDENT { Lident $1 }
+ | module_path DOT UIDENT { Ldot($1, $3) }
+;
+
+longident_eol :
+ longident end_of_line { $1 };
+
+opt_longident :
+ UIDENT { Some (Lident $1) }
+ | LIDENT { Some (Lident $1) }
+ | module_path DOT UIDENT { Some (Ldot($1, $3)) }
+ | { None };
+
+opt_longident_eol :
+ opt_longident end_of_line { $1 };
+
+identifier :
+ LIDENT { $1 }
+ | UIDENT { $1 };
+
+identifier_eol :
+ identifier end_of_line { $1 };
+
+identifier_or_eol :
+ identifier { Some $1 }
+ | end_of_line { None };
+
+opt_identifier :
+ identifier { Some $1 }
+ | { None };
+
+opt_identifier_eol :
+ opt_identifier end_of_line { $1 };
+
+/* Expressions */
+
+expression:
+ longident { E_ident $1 }
+ | STAR { E_result }
+ | DOLLAR INTEGER { E_name (to_int $2) }
+ | expression DOT INTEGER { E_item($1, (to_int $3)) }
+ | expression DOT LBRACKET INTEGER RBRACKET { E_item($1, (to_int $4)) }
+ | expression DOT LPAREN INTEGER RPAREN { E_item($1, (to_int $4)) }
+ | expression DOT LIDENT { E_field($1, $3) }
+ | BANG expression { E_field($2, "contents") }
+ | LPAREN expression RPAREN { $2 }
+;
+
+/* Lists of expressions */
+
+expression_list_eol :
+ expression expression_list_eol { $1::$2 }
+ | end_of_line { [] }
+;
+
+/* Arguments for breakpoint */
+
+break_argument_eol :
+ end_of_line { BA_none }
+ | integer_eol { BA_pc $1 }
+ | expression end_of_line { BA_function $1 }
+ | AT opt_longident INTEGER opt_integer_eol { BA_pos1 ($2, (to_int $3), $4)}
+ | AT opt_longident SHARP integer_eol { BA_pos2 ($2, $4) }
+;
+
+/* Arguments for list */
+
+list_arguments_eol :
+ opt_longident integer opt_integer_eol
+ { ($1, Some $2, $3) }
+ | opt_longident_eol
+ { ($1, None, None) };
+
+/* End of line */
+
+end_of_line :
+ EOL { stop_user_input () }
+;
diff --git a/debugger/parser_aux.mli b/debugger/parser_aux.mli
new file mode 100644
index 0000000000..542affbd04
--- /dev/null
+++ b/debugger/parser_aux.mli
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*open Globals*)
+
+open Primitives
+
+type expression =
+ E_ident of Longident.t (* x or Mod.x *)
+ | E_name of int (* $xxx *)
+ | E_item of expression * int (* x.1 x.[2] x.(3) *)
+ | E_field of expression * string (* x.lbl !x *)
+ | E_result
+
+type break_arg =
+ BA_none (* break *)
+ | BA_pc of int (* break PC *)
+ | BA_function of expression (* break FUNCTION *)
+ | BA_pos1 of Longident.t option * int * int option
+ (* break @ [MODULE] LINE [POS] *)
+ | BA_pos2 of Longident.t option * int (* break @ [MODULE] # OFFSET *)
diff --git a/debugger/pattern_matching.ml b/debugger/pattern_matching.ml
new file mode 100644
index 0000000000..7b297869d7
--- /dev/null
+++ b/debugger/pattern_matching.ml
@@ -0,0 +1,251 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(************************ Simple pattern matching **********************)
+
+open Debugger_config
+(*open Primitives*)
+open Misc
+(*open Const*)
+(*open Globals*)
+(*open Builtins*)
+open Typedtree
+(*open Modules*)
+(*open Symtable*)
+(*open Value*)
+open Parser_aux
+
+(*
+let rec find_constr tag = function
+ [] ->
+ fatal_error "find_constr: unknown constructor for this type"
+ | constr::rest ->
+ match constr.info.cs_tag with
+ ConstrRegular(t, _) ->
+ if t == tag then constr else find_constr tag rest
+ | ConstrExtensible _ ->
+ fatal_error "find_constr: extensible"
+
+let find_exception tag =
+ let (qualid, stamp) = get_exn_of_num tag in
+ let rec select_exn = function
+ [] ->
+ raise Not_found
+ | constr :: rest ->
+ match constr.info.cs_tag with
+ ConstrExtensible(_,st) ->
+ if st == stamp then constr else select_exn rest
+ | ConstrRegular(_,_) ->
+ fatal_error "find_exception: regular" in
+ select_exn(hashtbl__find_all (find_module qualid.qual).mod_constrs qualid.id)
+*)
+
+let error_matching () =
+ prerr_endline "Pattern matching failed";
+ raise Toplevel
+
+(*
+let same_name {qualid = name1} =
+ function
+ GRname name2 ->
+ (name2 = "") || (name1.id = name2)
+ | GRmodname name2 ->
+ name1 = name2
+
+let check_same_constr constr constr2 =
+ try
+ if not (same_name constr constr2) then
+ error_matching ()
+ with
+ Desc_not_found ->
+ prerr_endline "Undefined constructor.";
+ raise Toplevel
+*)
+
+let rec pattern_matching pattern obj ty =
+ match pattern with
+ P_dummy ->
+ []
+ | P_variable var ->
+ [var, obj, ty]
+ | _ ->
+ match (Ctype.repr ty).desc with
+ Tvar | Tarrow _ ->
+ error_matching ()
+ | Ttuple(ty_list) ->
+ (match pattern with
+ P_tuple pattern_list ->
+ pattern_matching_list pattern_list obj ty_list
+ | P_nth (n, patt) ->
+ if n >= List.length ty_list then
+ (prerr_endline "Out of range."; raise Toplevel);
+ pattern_matching patt (Debugcom.get_field obj n)
+ (List.nth ty_list n)
+ | _ ->
+ error_matching ())
+ | Tconstr(cstr, [ty_arg],_) when same_type_constr cstr constr_type_list ->
+ (match pattern with
+ P_list pattern_list ->
+ let (last, list) =
+ it_list
+ (fun (current, list) pattern ->
+ if value_tag current = 0 then error_matching ();
+ (Debugcom.get_field current 1,
+ (pattern, Debugcom.get_field current 0)::list))
+ (obj, [])
+ pattern_list
+ in
+ if value_tag last <> 0 then error_matching ();
+ flat_map
+ (function (x, y) -> pattern_matching x y ty_arg)
+ (rev list)
+ | P_nth (n, patt) ->
+ let rec find k current =
+ if value_tag current = 0 then
+ (prerr_endline "Out of range."; raise Toplevel);
+ if k = 0 then
+ pattern_matching patt (Debugcom.get_field current 0) ty_arg
+ else
+ find (k - 1) (Debugcom.get_field current 1)
+ in
+ find n obj
+ | P_concat (pattern1, pattern2) ->
+ if value_tag obj == 0 then error_matching ();
+ (pattern_matching pattern1 (Debugcom.get_field obj 0) ty_arg)
+ @ (pattern_matching pattern2 (Debugcom.get_field obj 1) ty)
+ | _ ->
+ error_matching ())
+ | Tconstr(cstr, [ty_arg]) when same_type_constr cstr constr_type_vect ->
+ (match pattern with
+ P_nth (n, patt) ->
+ if n >= value_size obj then
+ (prerr_endline "Out of range."; raise Toplevel);
+ pattern_matching patt (Debugcom.get_field obj n) ty_arg
+ | _ ->
+ error_matching ())
+ | Tconstr(cstr, ty_list) ->
+ (match cstr.info.ty_abbr with
+ Tabbrev(params, body) ->
+ pattern_matching pattern obj (expand_abbrev params body ty_list)
+ | _ ->
+ match_concrete_type pattern obj cstr ty ty_list)
+
+and match_concrete_type pattern obj cstr ty ty_list =
+ let typ_descr =
+ type_descr_of_type_constr cstr in
+ match typ_descr.info.ty_desc with
+ Abstract_type ->
+ error_matching ()
+ | Variant_type constr_list ->
+ let tag = value_tag obj in
+ (try
+ let constr =
+ if same_type_constr cstr constr_type_exn then
+ find_exception tag
+ else
+ find_constr tag constr_list
+ in
+ let (ty_res, ty_arg) =
+ type_pair_instance (constr.info.cs_res, constr.info.cs_arg)
+ in
+ filter (ty_res, ty);
+ match constr.info.cs_kind with
+ Constr_constant ->
+ error_matching ()
+ | Constr_regular ->
+ (match pattern with
+ P_constr (constr2, patt) ->
+ check_same_constr constr constr2;
+ pattern_matching patt (Debugcom.get_field obj 0) ty_arg
+ | _ ->
+ error_matching ())
+ | Constr_superfluous n ->
+ (match pattern with
+ P_constr (constr2, patt) ->
+ check_same_constr constr constr2;
+ (match patt with
+ P_tuple pattern_list ->
+ pattern_matching_list
+ pattern_list
+ obj
+ (filter_product n ty_arg)
+ | P_nth (n2, patt) ->
+ let ty_list = filter_product n ty_arg in
+ if n2 >= n then
+ (prerr_endline "Out of range.";
+ raise Toplevel);
+ pattern_matching
+ patt
+ (Debugcom.get_field obj n2)
+ (List.nth ty_list n2)
+ | P_variable var ->
+ [var,
+ obj,
+ {typ_desc = Tproduct (filter_product n ty_arg);
+ typ_level = generic}]
+ | P_dummy ->
+ []
+ | _ ->
+ error_matching ())
+ | _ ->
+ error_matching ())
+ with
+ Not_found ->
+ error_matching ()
+ | Unify ->
+ fatal_error "pattern_matching: types should match")
+ | Record_type label_list ->
+ let match_field (label, patt) =
+ let lbl =
+ try
+ primitives__find
+ (function l -> same_name l label)
+ label_list
+ with Not_found ->
+ prerr_endline "Label not found.";
+ raise Toplevel
+ in
+ let (ty_res, ty_arg) =
+ type_pair_instance (lbl.info.lbl_res, lbl.info.lbl_arg)
+ in
+ (try
+ filter (ty_res, ty)
+ with Unify ->
+ fatal_error "pattern_matching: types should match");
+ pattern_matching patt (Debugcom.get_field obj lbl.info.lbl_pos)
+ ty_arg
+ in
+ (match pattern with
+ P_record pattern_label_list ->
+ flat_map match_field pattern_label_list
+ | _ ->
+ error_matching ())
+ | Abbrev_type(_,_) ->
+ fatal_error "pattern_matching: abbrev type"
+
+and pattern_matching_list pattern_list obj ty_list =
+ let val_list =
+ try
+ pair__combine (pattern_list, ty_list)
+ with
+ Invalid_argument _ -> error_matching ()
+ in
+ flat_map
+ (function (x, y, z) -> pattern_matching x y z)
+ (rev
+ (snd
+ (it_list
+ (fun (num, list) (pattern, typ) ->
+ (num + 1, (pattern, Debugcom.get_field obj num, typ)::list))
+ (0, [])
+ val_list)))
diff --git a/debugger/pattern_matching.mli b/debugger/pattern_matching.mli
new file mode 100644
index 0000000000..71e88c0542
--- /dev/null
+++ b/debugger/pattern_matching.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(************************ Simple pattern matching **********************)
+
+open Parser_aux
+
+val pattern_matching :
+ pattern -> Debugcom.remote_value -> Typedtree.type_expr ->
+ (string * Debugcom.remote_value * Typedtree.type_expr) list;;
diff --git a/debugger/pos.ml b/debugger/pos.ml
new file mode 100644
index 0000000000..c9e93280d8
--- /dev/null
+++ b/debugger/pos.ml
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2003 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Instruct;;
+open Lexing;;
+open Location;;
+open Primitives;;
+open Source;;
+
+let get_desc ev =
+ let loc = ev.ev_loc in
+ Printf.sprintf "file %s, line %d, characters %d-%d"
+ loc.loc_start.pos_fname loc.loc_start.pos_lnum
+ (loc.loc_start.pos_cnum - loc.loc_start.pos_bol + 1)
+ (loc.loc_end.pos_cnum - loc.loc_start.pos_bol + 1)
+;;
diff --git a/debugger/pos.mli b/debugger/pos.mli
new file mode 100644
index 0000000000..4eacab788d
--- /dev/null
+++ b/debugger/pos.mli
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2003 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val get_desc : Instruct.debug_event -> string;;
diff --git a/debugger/primitives.ml b/debugger/primitives.ml
new file mode 100644
index 0000000000..8cbc5387cb
--- /dev/null
+++ b/debugger/primitives.ml
@@ -0,0 +1,136 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*********************** Basic functions and types *********************)
+
+(*** Miscellaneous ***)
+exception Out_of_range
+
+let nothing _ = ()
+
+(*** Operations on lists. ***)
+
+(* Remove an element from a list *)
+let except e l =
+ let rec except_e = function
+ [] -> []
+ | elem::l -> if e = elem then l else elem::except_e l
+ in except_e l
+
+(* Position of an element in a list. Head of list has position 0. *)
+let index a l =
+ let rec index_rec i = function
+ [] -> raise Not_found
+ | b::l -> if a = b then i else index_rec (i + 1) l
+ in index_rec 0 l
+
+(* Return the `n' first elements of `l' *)
+(* ### n l -> l' *)
+let rec list_truncate =
+ fun
+ p0 p1 -> match (p0,p1) with (0, _) -> []
+ | (_, []) -> []
+ | (n, (a::l)) -> a::(list_truncate (n - 1) l)
+
+(* Separe the `n' first elements of `l' and the others *)
+(* ### n list -> (first, last) *)
+let rec list_truncate2 =
+ fun
+ p0 p1 -> match (p0,p1) with (0, l) ->
+ ([], l)
+ | (_, []) ->
+ ([], [])
+ | (n, (a::l)) ->
+ let (first, last) = (list_truncate2 (n - 1) l) in
+ (a::first, last)
+
+(* Replace x by y in list l *)
+(* ### x y l -> l' *)
+let list_replace x y =
+ let rec repl =
+ function
+ [] -> []
+ | a::l ->
+ if a == x then y::l
+ else a::(repl l)
+ in repl
+
+(*** Operations on strings. ***)
+
+(* Remove blanks (spaces and tabs) at beginning and end of a string. *)
+let is_space = function
+ | ' ' | '\t' -> true | _ -> false
+
+let string_trim s =
+ let l = String.length s and i = ref 0 in
+ while
+ !i < l && is_space (String.get s !i)
+ do
+ incr i
+ done;
+ let j = ref (l - 1) in
+ while
+ !j >= !i && is_space (String.get s !j)
+ do
+ decr j
+ done;
+ String.sub s !i (!j - !i + 1)
+
+(* isprefix s1 s2 returns true if s1 is a prefix of s2. *)
+
+let isprefix s1 s2 =
+ let l1 = String.length s1 and l2 = String.length s2 in
+ (l1 = l2 && s1 = s2) || (l1 < l2 && s1 = String.sub s2 0 l1)
+
+(* Split a string at the given delimiter char *)
+
+let split_string sep str =
+ let rec split i j =
+ if j >= String.length str then
+ if i >= j then [] else [String.sub str i (j-i)]
+ else if str.[j] = sep then
+ if i >= j
+ then skip_sep (j+1)
+ else String.sub str i (j-i) :: skip_sep (j+1)
+ else
+ split i (j+1)
+ and skip_sep j =
+ if j < String.length str && str.[j] = sep
+ then skip_sep (j+1)
+ else split j j
+ in split 0 0
+
+(*** I/O channels ***)
+
+type io_channel = {
+ io_in : in_channel;
+ io_out : out_channel;
+ io_fd : Unix.file_descr
+ }
+
+let io_channel_of_descr fd = {
+ io_in = Unix.in_channel_of_descr fd;
+ io_out = Unix.out_channel_of_descr fd;
+ io_fd = fd
+ }
+
+let close_io io_channel =
+ close_out_noerr io_channel.io_out;
+ close_in_noerr io_channel.io_in;
+;;
+
+let std_io = {
+ io_in = stdin;
+ io_out = stdout;
+ io_fd = Unix.stdin
+ }
diff --git a/debugger/primitives.mli b/debugger/primitives.mli
new file mode 100644
index 0000000000..0e36b414da
--- /dev/null
+++ b/debugger/primitives.mli
@@ -0,0 +1,63 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(********************* Basic functions and types ***********************)
+
+(*** Miscellaneous ***)
+val nothing : 'a -> unit
+
+(*** Types and exceptions. ***)
+exception Out_of_range
+
+(*** Operations on lists. ***)
+
+(* Remove an element from a list *)
+val except : 'a -> 'a list -> 'a list
+
+(* Position of an element in a list. Head of list has position 0. *)
+val index : 'a -> 'a list -> int
+
+(* Return the `n' first elements of `l'. *)
+(* ### n l -> l' *)
+val list_truncate : int -> 'a list -> 'a list
+
+(* Separe the `n' first elements of `l' and the others. *)
+(* ### n list -> (first, last) *)
+val list_truncate2 : int -> 'a list -> 'a list * 'a list
+
+(* Replace x by y in list l *)
+(* ### x y l -> l' *)
+val list_replace : 'a -> 'a -> 'a list -> 'a list
+
+(*** Operations on strings. ***)
+
+(* Remove blanks (spaces and tabs) at beginning and end of a string. *)
+val string_trim : string -> string
+
+(* isprefix s1 s2 returns true if s1 is a prefix of s2. *)
+val isprefix : string -> string -> bool
+
+(* Split a string at the given delimiter char *)
+val split_string : char -> string -> string list
+
+(*** I/O channels ***)
+
+type io_channel = {
+ io_in : in_channel;
+ io_out : out_channel;
+ io_fd : Unix.file_descr
+ }
+
+val io_channel_of_descr : Unix.file_descr -> io_channel
+val close_io : io_channel -> unit
+val std_io : io_channel
diff --git a/debugger/printval.ml b/debugger/printval.ml
new file mode 100644
index 0000000000..5170ef3b24
--- /dev/null
+++ b/debugger/printval.ml
@@ -0,0 +1,106 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* To print values *)
+
+open Format
+open Parser_aux
+open Path
+open Types
+
+(* To name printed and ellipsed values *)
+
+let named_values =
+ (Hashtbl.create 29 : (int, Debugcom.Remote_value.t * type_expr) Hashtbl.t)
+let next_name = ref 1
+
+let reset_named_values () =
+ Hashtbl.clear named_values;
+ next_name := 1
+
+let name_value v ty =
+ let name = !next_name in
+ incr next_name;
+ Hashtbl.add named_values name (v, ty);
+ name
+
+let find_named_value name =
+ Hashtbl.find named_values name
+
+let check_depth ppf depth obj ty =
+ if depth <= 0 then begin
+ let n = name_value obj ty in
+ Some (Outcometree.Oval_stuff ("$" ^ string_of_int n))
+ end else None
+
+module EvalPath =
+ struct
+ type valu = Debugcom.Remote_value.t
+ exception Error
+ let rec eval_path env = function
+ Pident id ->
+ begin try
+ Debugcom.Remote_value.global (Symtable.get_global_position id)
+ with Symtable.Error _ ->
+ raise Error
+ end
+ | Pdot(root, fieldname, pos) ->
+ let v = eval_path env root in
+ if not (Debugcom.Remote_value.is_block v)
+ then raise Error
+ else Debugcom.Remote_value.field v pos
+ | Papply(p1, p2) ->
+ raise Error
+ let same_value = Debugcom.Remote_value.same
+ end
+
+module Printer = Genprintval.Make(Debugcom.Remote_value)(EvalPath)
+
+let install_printer path ty ppf fn =
+ Printer.install_printer path ty
+ (fun ppf remote_val ->
+ try
+ fn ppf (Obj.repr (Debugcom.Remote_value.obj remote_val))
+ with
+ Debugcom.Marshalling_error ->
+ fprintf ppf "<cannot fetch remote object>")
+
+let remove_printer = Printer.remove_printer
+
+let max_printer_depth = ref 20
+let max_printer_steps = ref 300
+
+let print_exception ppf obj =
+ let t = Printer.outval_of_untyped_exception obj in
+ !Oprint.out_value ppf t
+
+let print_value max_depth env obj (ppf : Format.formatter) ty =
+ let t =
+ Printer.outval_of_value !max_printer_steps max_depth
+ (check_depth ppf) env obj ty in
+ !Oprint.out_value ppf t
+
+let print_named_value max_depth exp env obj ppf ty =
+ let print_value_name ppf = function
+ | E_ident lid ->
+ Printtyp.longident ppf lid
+ | E_name n ->
+ fprintf ppf "$%i" n
+ | _ ->
+ let n = name_value obj ty in
+ fprintf ppf "$%i" n in
+ Printtyp.reset_and_mark_loops ty;
+ fprintf ppf "@[<2>%a:@ %a@ =@ %a@]@."
+ print_value_name exp
+ Printtyp.type_expr ty
+ (print_value max_depth env obj) ty
diff --git a/debugger/printval.mli b/debugger/printval.mli
new file mode 100644
index 0000000000..ba6c25ad48
--- /dev/null
+++ b/debugger/printval.mli
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+val max_printer_depth : int ref
+val max_printer_steps : int ref
+
+val print_exception: formatter -> Debugcom.Remote_value.t -> unit
+val print_named_value :
+ int -> Parser_aux.expression -> Env.t ->
+ Debugcom.Remote_value.t -> formatter -> Types.type_expr ->
+ unit
+
+val reset_named_values : unit -> unit
+val find_named_value : int -> Debugcom.Remote_value.t * Types.type_expr
+
+val install_printer :
+ Path.t -> Types.type_expr -> formatter ->
+ (formatter -> Obj.t -> unit) -> unit
+val remove_printer : Path.t -> unit
diff --git a/debugger/program_loading.ml b/debugger/program_loading.ml
new file mode 100644
index 0000000000..1ebbd1e821
--- /dev/null
+++ b/debugger/program_loading.ml
@@ -0,0 +1,187 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Program loading *)
+
+open Unix
+open Debugger_config
+open Parameters
+open Input_handling
+
+(*** Debugging. ***)
+
+let debug_loading = ref false
+
+(*** Load a program. ***)
+
+(* Function used for launching the program. *)
+let launching_func = ref (function () -> ())
+
+let load_program () =
+ !launching_func ();
+ main_loop ()
+
+(*** Launching functions. ***)
+
+(* Returns a command line prefix to set environment for the debuggee *)
+let get_unix_environment () =
+ let f (vname, vvalue) =
+ Printf.sprintf "%s=%s " vname (Filename.quote vvalue)
+ in
+ String.concat "" (List.map f !Debugger_config.environment)
+;;
+
+(* Notes:
+ 1. This quoting is not the same as [Filename.quote] because the "set"
+ command is a shell built-in and its quoting rules are different
+ from regular commands.
+ 2. Microsoft's documentation omits the double-quote from the list
+ of characters that need quoting, but that is a mistake (unquoted
+ quotes are included in the value, but they alter the quoting of
+ characters between them).
+ Reference: http://msdn.microsoft.com/en-us/library/bb490954.aspx
+ *)
+let quote_for_windows_shell s =
+ let b = Buffer.create (20 + String.length s) in
+ for i = 0 to String.length s - 1 do
+ begin match s.[i] with
+ | '<' | '>' | '|' | '&' | '^' | '\"' ->
+ Buffer.add_char b '^';
+ | _ -> ()
+ end;
+ Buffer.add_char b s.[i];
+ done;
+ Buffer.contents b
+;;
+
+(* Returns a command line prefix to set environment for the debuggee *)
+let get_win32_environment () =
+ (* Note: no space before the & or Windows will add it to the value *)
+ let f (vname, vvalue) =
+ Printf.sprintf "set %s=%s&" vname (quote_for_windows_shell vvalue)
+ in
+ String.concat "" (List.map f !Debugger_config.environment)
+
+(* A generic function for launching the program *)
+let generic_exec_unix cmdline = function () ->
+ if !debug_loading then
+ prerr_endline "Launching program...";
+ let child =
+ try
+ fork ()
+ with x ->
+ Unix_tools.report_error x;
+ raise Toplevel in
+ match child with
+ 0 ->
+ begin try
+ match fork () with
+ 0 -> (* Try to detach the process from the controlling terminal,
+ so that it does not receive SIGINT on ctrl-C. *)
+ begin try ignore(setsid()) with Invalid_argument _ -> () end;
+ execv shell [| shell; "-c"; cmdline() |]
+ | _ -> exit 0
+ with x ->
+ Unix_tools.report_error x;
+ exit 1
+ end
+ | _ ->
+ match wait () with
+ (_, WEXITED 0) -> ()
+ | _ -> raise Toplevel
+
+let generic_exec_win cmdline = function () ->
+ if !debug_loading then
+ prerr_endline "Launching program...";
+ try ignore(create_process "cmd.exe" [| "/C"; cmdline() |] stdin stdout stderr)
+ with x ->
+ Unix_tools.report_error x;
+ raise Toplevel
+
+let generic_exec =
+ match Sys.os_type with
+ "Win32" -> generic_exec_win
+ | _ -> generic_exec_unix
+
+(* Execute the program by calling the runtime explicitly *)
+let exec_with_runtime =
+ generic_exec
+ (function () ->
+ match Sys.os_type with
+ "Win32" ->
+ (* This would fail on a file name with spaces
+ but quoting is even worse because Unix.create_process
+ thinks each command line parameter is a file.
+ So no good solution so far *)
+ Printf.sprintf "%sset CAML_DEBUG_SOCKET=%s& %s %s %s"
+ (get_win32_environment ())
+ !socket_name
+ runtime_program
+ !program_name
+ !arguments
+ | _ ->
+ Printf.sprintf "%sCAML_DEBUG_SOCKET=%s %s %s %s"
+ (get_unix_environment ())
+ !socket_name
+ (Filename.quote runtime_program)
+ (Filename.quote !program_name)
+ !arguments)
+
+(* Excute the program directly *)
+let exec_direct =
+ generic_exec
+ (function () ->
+ match Sys.os_type with
+ "Win32" ->
+ (* See the comment above *)
+ Printf.sprintf "%sset CAML_DEBUG_SOCKET=%s& %s %s"
+ (get_win32_environment ())
+ !socket_name
+ !program_name
+ !arguments
+ | _ ->
+ Printf.sprintf "%sCAML_DEBUG_SOCKET=%s %s %s"
+ (get_unix_environment ())
+ !socket_name
+ (Filename.quote !program_name)
+ !arguments)
+
+(* Ask the user. *)
+let exec_manual =
+ function () ->
+ print_newline ();
+ print_string "Waiting for connection...";
+ print_string ("(the socket is " ^ !socket_name ^ ")");
+ print_newline ()
+
+(*** Selection of the launching function. ***)
+
+type launching_function = (unit -> unit)
+
+let loading_modes =
+ ["direct", exec_direct;
+ "runtime", exec_with_runtime;
+ "manual", exec_manual]
+
+let set_launching_function func =
+ launching_func := func
+
+(* Initialization *)
+
+let _ =
+ set_launching_function exec_direct
+
+(*** Connection. ***)
+
+let connection = ref Primitives.std_io
+let connection_opened = ref false
diff --git a/debugger/program_loading.mli b/debugger/program_loading.mli
new file mode 100644
index 0000000000..23ea47a600
--- /dev/null
+++ b/debugger/program_loading.mli
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*** Debugging. ***)
+
+val debug_loading : bool ref
+
+(*** Load program ***)
+
+(* Function used for launching the program. *)
+val launching_func : (unit -> unit) ref
+
+val load_program : unit -> unit
+
+type launching_function = (unit -> unit)
+
+val loading_modes : (string * launching_function) list
+val set_launching_function : launching_function -> unit
+
+(** Connection **)
+val connection : Primitives.io_channel ref
+val connection_opened : bool ref
diff --git a/debugger/program_management.ml b/debugger/program_management.ml
new file mode 100644
index 0000000000..48118573ee
--- /dev/null
+++ b/debugger/program_management.ml
@@ -0,0 +1,158 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Manage the loading of the program *)
+
+open Int64ops
+open Unix
+open Unix_tools
+open Debugger_config
+open Primitives
+open Parameters
+open Input_handling
+open Question
+open Program_loading
+open Time_travel
+
+(*** Connection opening and control. ***)
+
+(* Name of the file if the socket is in the unix domain.*)
+let file_name = ref (None : string option)
+
+(* Default connection handler. *)
+let buffer = Bytes.create 1024
+let control_connection pid fd =
+ if (read fd.io_fd buffer 0 1024) = 0 then
+ forget_process fd pid
+ else begin
+ prerr_string "Garbage data from process ";
+ prerr_int pid;
+ prerr_endline ""
+ end
+
+(* Accept a connection from another process. *)
+let accept_connection continue fd =
+ let (sock, _) = accept fd.io_fd in
+ let io_chan = io_channel_of_descr sock in
+ let pid = input_binary_int io_chan.io_in in
+ if pid = -1 then begin
+ let pid' = input_binary_int io_chan.io_in in
+ new_checkpoint pid' io_chan;
+ Input_handling.add_file io_chan (control_connection pid');
+ continue ()
+ end
+ else begin
+ if set_file_descriptor pid io_chan then
+ Input_handling.add_file io_chan (control_connection pid)
+ end
+
+(* Initialize the socket. *)
+let open_connection address continue =
+ try
+ let (sock_domain, sock_address) = convert_address address in
+ file_name :=
+ (match sock_address with
+ ADDR_UNIX file ->
+ Some file
+ | _ ->
+ None);
+ let sock = socket sock_domain SOCK_STREAM 0 in
+ (try
+ bind sock sock_address;
+ setsockopt sock SO_REUSEADDR true;
+ listen sock 3;
+ connection := io_channel_of_descr sock;
+ Input_handling.add_file !connection (accept_connection continue);
+ connection_opened := true
+ with x -> close sock; raise x)
+ with
+ Failure _ -> raise Toplevel
+ | (Unix_error _) as err -> report_error err; raise Toplevel
+
+(* Close the socket. *)
+let close_connection () =
+ if !connection_opened then begin
+ connection_opened := false;
+ Input_handling.remove_file !connection;
+ close_io !connection;
+ match !file_name with
+ Some file ->
+ unlink file
+ | None ->
+ ()
+ end
+
+(*** Kill program. ***)
+let loaded = ref false
+
+let kill_program () =
+ Breakpoints.remove_all_breakpoints ();
+ History.empty_history ();
+ kill_all_checkpoints ();
+ loaded := false;
+ close_connection ()
+
+let ask_kill_program () =
+ if not !loaded then
+ true
+ else
+ let answer = yes_or_no "A program is being debugged already. Kill it" in
+ if answer then
+ kill_program ();
+ answer
+
+(*** Program loading and initializations. ***)
+
+let initialize_loading () =
+ if !debug_loading then begin
+ prerr_endline "Loading debugging information...";
+ Printf.fprintf Pervasives.stderr "\tProgram: [%s]\n%!" !program_name;
+ end;
+ begin try access !program_name [F_OK]
+ with Unix_error _ ->
+ prerr_endline "Program not found.";
+ raise Toplevel;
+ end;
+ Symbols.read_symbols !program_name;
+ Config.load_path := !Config.load_path @ !Symbols.program_source_dirs;
+ Envaux.reset_cache ();
+ if !debug_loading then
+ prerr_endline "Opening a socket...";
+ open_connection !socket_name
+ (function () ->
+ go_to _0;
+ Symbols.set_all_events();
+ exit_main_loop ())
+
+(* Ensure the program is already loaded. *)
+let ensure_loaded () =
+ if not !loaded then begin
+ print_string "Loading program... ";
+ flush Pervasives.stdout;
+ if !program_name = "" then begin
+ prerr_endline "No program specified.";
+ raise Toplevel
+ end;
+ try
+ initialize_loading();
+ !launching_func ();
+ if !debug_loading then
+ prerr_endline "Waiting for connection...";
+ main_loop ();
+ loaded := true;
+ prerr_endline "done."
+ with
+ x ->
+ kill_program();
+ raise x
+ end
diff --git a/debugger/program_management.mli b/debugger/program_management.mli
new file mode 100644
index 0000000000..0b8a09b863
--- /dev/null
+++ b/debugger/program_management.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*** Program loading and initializations. ***)
+
+val loaded : bool ref
+val ensure_loaded : unit -> unit
+
+(*** Kill program. ***)
+val kill_program : unit -> unit
+
+(* Ask wether to kill the program or not. *)
+(* If yes, kill it. *)
+(* Return true iff the program has been killed. *)
+val ask_kill_program : unit -> bool
diff --git a/debugger/question.ml b/debugger/question.ml
new file mode 100644
index 0000000000..f17227b9be
--- /dev/null
+++ b/debugger/question.ml
@@ -0,0 +1,47 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Nicolas Pouillard, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2006 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Input_handling
+open Primitives
+
+(* Ask user a yes or no question. *)
+let yes_or_no message =
+ if !interactif then
+ let old_prompt = !current_prompt in
+ try
+ current_prompt := message ^ " ? (y or n) ";
+ let answer =
+ let rec ask () =
+ resume_user_input ();
+ let line =
+ string_trim (Lexer.line (Lexing.from_function read_user_input))
+ in
+ stop_user_input ();
+ match (if String.length line > 0 then line.[0] else ' ') with
+ 'y' -> true
+ | 'n' -> false
+ | _ ->
+ print_string "Please answer y or n.";
+ print_newline ();
+ ask ()
+ in
+ ask ()
+ in
+ current_prompt := old_prompt;
+ answer
+ with
+ x ->
+ current_prompt := old_prompt;
+ stop_user_input ();
+ raise x
+ else
+ false
diff --git a/debugger/question.mli b/debugger/question.mli
new file mode 100644
index 0000000000..d8e50ef9b8
--- /dev/null
+++ b/debugger/question.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Nicolas Pouillard, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2006 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Ask user a yes or no question. *)
+val yes_or_no : string -> bool
diff --git a/debugger/show_information.ml b/debugger/show_information.ml
new file mode 100644
index 0000000000..690645dfe2
--- /dev/null
+++ b/debugger/show_information.ml
@@ -0,0 +1,105 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Instruct
+open Format
+open Debugcom
+open Checkpoints
+open Events
+open Symbols
+open Frames
+open Source
+open Show_source
+open Breakpoints
+open Parameters
+
+(* Display information about the current event. *)
+let show_current_event ppf =
+ fprintf ppf "Time: %Li" (current_time ());
+ (match current_pc () with
+ | Some pc ->
+ fprintf ppf " - pc: %i" pc
+ | _ -> ());
+ update_current_event ();
+ reset_frame ();
+ match current_report () with
+ | None ->
+ fprintf ppf "@.Beginning of program.@.";
+ show_no_point ()
+ | Some {rep_type = (Event | Breakpoint); rep_program_pointer = pc} ->
+ let ev = get_current_event () in
+ fprintf ppf " - module %s@." ev.ev_module;
+ (match breakpoints_at_pc pc with
+ | [] ->
+ ()
+ | [breakpoint] ->
+ fprintf ppf "Breakpoint: %i@." breakpoint
+ | breakpoints ->
+ fprintf ppf "Breakpoints: %a@."
+ (fun ppf l ->
+ List.iter
+ (function x -> fprintf ppf "%i " x) l)
+ (List.sort compare breakpoints));
+ show_point ev true
+ | Some {rep_type = Exited} ->
+ fprintf ppf "@.Program exit.@.";
+ show_no_point ()
+ | Some {rep_type = Uncaught_exc} ->
+ fprintf ppf
+ "@.Program end.@.\
+ @[Uncaught exception:@ %a@]@."
+ Printval.print_exception (Debugcom.Remote_value.accu ());
+ show_no_point ()
+ | Some {rep_type = Trap_barrier} ->
+ (* Trap_barrier not visible outside *)
+ (* of module `time_travel'. *)
+ Misc.fatal_error "Show_information.show_current_event"
+
+(* Display short information about one frame. *)
+
+let show_one_frame framenum ppf event =
+ let pos = Events.get_pos event in
+ let cnum =
+ try
+ let buffer = get_buffer pos event.ev_module in
+ snd (start_and_cnum buffer pos)
+ with _ -> pos.Lexing.pos_cnum in
+ if !machine_readable then
+ fprintf ppf "#%i Pc: %i %s char %i@."
+ framenum event.ev_pos event.ev_module
+ cnum
+ else
+ fprintf ppf "#%i %s %s:%i:%i@."
+ framenum event.ev_module
+ pos.Lexing.pos_fname pos.Lexing.pos_lnum
+ (pos.Lexing.pos_cnum - pos.Lexing.pos_bol + 1)
+
+(* Display information about the current frame. *)
+(* --- `select frame' must have succeded before calling this function. *)
+let show_current_frame ppf selected =
+ match !selected_event with
+ | None ->
+ fprintf ppf "@.No frame selected.@."
+ | Some sel_ev ->
+ show_one_frame !current_frame ppf sel_ev;
+ begin match breakpoints_at_pc sel_ev.ev_pos with
+ | [] -> ()
+ | [breakpoint] ->
+ fprintf ppf "Breakpoint: %i@." breakpoint
+ | breakpoints ->
+ fprintf ppf "Breakpoints: %a@."
+ (fun ppf l ->
+ List.iter (function x -> fprintf ppf "%i " x) l)
+ (List.sort compare breakpoints);
+ end;
+ show_point sel_ev selected
diff --git a/debugger/show_information.mli b/debugger/show_information.mli
new file mode 100644
index 0000000000..45329be41d
--- /dev/null
+++ b/debugger/show_information.mli
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format;;
+
+(* Display information about the current event. *)
+val show_current_event : formatter -> unit;;
+
+(* Display information about the current frame. *)
+(* --- `select frame' must have succeded before calling this function. *)
+val show_current_frame : formatter -> bool -> unit;;
+
+(* Display short information about one frame. *)
+val show_one_frame : int -> formatter -> Instruct.debug_event -> unit
diff --git a/debugger/show_source.ml b/debugger/show_source.ml
new file mode 100644
index 0000000000..db2484f521
--- /dev/null
+++ b/debugger/show_source.ml
@@ -0,0 +1,86 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Debugger_config
+open Instruct
+open Parameters
+open Primitives
+open Printf
+open Source
+
+(* Print a line; return the beginning of the next line *)
+let print_line buffer line_number start point before =
+ let next = next_linefeed buffer start
+ and content = buffer_content buffer
+ in
+ printf "%i " line_number;
+ if point <= next && point >= start then
+ (print_string (String.sub content start (point - start));
+ print_string (if before then event_mark_before else event_mark_after);
+ print_string (String.sub content point (next - point)))
+ else
+ print_string (String.sub content start (next - start));
+ print_newline ();
+ next
+
+(* Tell Emacs we are nowhere in the source. *)
+let show_no_point () =
+ if !emacs then printf "\026\026H\n"
+
+(* Print the line containing the point *)
+let show_point ev selected =
+ let mdle = ev.ev_module in
+ let before = (ev.ev_kind = Event_before) in
+ if !emacs && selected then
+ begin try
+ let buffer = get_buffer (Events.get_pos ev) mdle in
+ let source = source_of_module ev.ev_loc.Location.loc_start mdle in
+ printf "\026\026M%s:%i:%i" source
+ (snd (start_and_cnum buffer ev.ev_loc.Location.loc_start))
+ (snd (start_and_cnum buffer ev.ev_loc.Location.loc_end));
+ printf "%s\n" (if before then ":before" else ":after")
+ with
+ Out_of_range -> (* point_of_coord *)
+ prerr_endline "Position out of range."
+ | Not_found -> (* Events.get_pos || get_buffer *)
+ prerr_endline ("No source file for " ^ mdle ^ ".");
+ show_no_point ()
+ end
+ else
+ begin try
+ let pos = Events.get_pos ev in
+ let buffer = get_buffer pos mdle in
+ let start, point = start_and_cnum buffer pos in
+ ignore(print_line buffer pos.Lexing.pos_lnum start point before)
+ with
+ Out_of_range -> (* point_of_coord *)
+ prerr_endline "Position out of range."
+ | Not_found -> (* Events.get_pos || get_buffer *)
+ prerr_endline ("No source file for " ^ mdle ^ ".")
+ end
+
+(* Display part of the source. *)
+let show_listing pos mdle start stop point before =
+ try
+ let buffer = get_buffer pos mdle in
+ let rec aff (line_start, line_number) =
+ if line_number <= stop then
+ aff (print_line buffer line_number line_start point before + 1,
+ line_number + 1)
+ in
+ aff (pos_of_line buffer start)
+ with
+ Out_of_range -> (* pos_of_line *)
+ prerr_endline "Position out of range."
+ | Not_found -> (* get_buffer *)
+ prerr_endline ("No source file for " ^ mdle ^ ".")
diff --git a/debugger/show_source.mli b/debugger/show_source.mli
new file mode 100644
index 0000000000..c1aa204efb
--- /dev/null
+++ b/debugger/show_source.mli
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Print the line containing the point *)
+val show_point : Instruct.debug_event -> bool -> unit;;
+
+(* Tell Emacs we are nowhere in the source. *)
+val show_no_point : unit -> unit;;
+
+(* Display part of the source. *)
+val show_listing :
+ Lexing.position -> string -> int -> int -> int -> bool -> unit
+;;
diff --git a/debugger/source.ml b/debugger/source.ml
new file mode 100644
index 0000000000..fa2b3c7e46
--- /dev/null
+++ b/debugger/source.ml
@@ -0,0 +1,190 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(************************ Source management ****************************)
+
+open Misc
+open Primitives
+
+let source_extensions = [".ml"]
+
+(*** Conversion function. ***)
+
+let source_of_module pos mdle =
+ let pos_fname = pos.Lexing.pos_fname in
+ if Sys.file_exists pos_fname then pos_fname else
+ let is_submodule m m' =
+ let len' = String.length m' in
+ try
+ (String.sub m 0 len') = m' && (String.get m len') = '.'
+ with
+ Invalid_argument _ -> false in
+ let path =
+ Hashtbl.fold
+ (fun mdl dirs acc ->
+ if is_submodule mdle mdl then
+ dirs
+ else
+ acc)
+ Debugger_config.load_path_for
+ !Config.load_path in
+ let fname = pos.Lexing.pos_fname in
+ if fname = "" then
+ let innermost_module =
+ try
+ let dot_index = String.rindex mdle '.' in
+ String.sub mdle (succ dot_index) (pred (String.length mdle - dot_index))
+ with Not_found -> mdle in
+ let rec loop =
+ function
+ | [] -> raise Not_found
+ | ext :: exts ->
+ try find_in_path_uncap path (innermost_module ^ ext)
+ with Not_found -> loop exts
+ in loop source_extensions
+ else if Filename.is_relative fname then
+ find_in_path_rel path fname
+ else if Sys.file_exists fname then fname
+ else raise Not_found
+
+(*** Buffer cache ***)
+
+(* Buffer and cache (to associate lines and positions in the buffer). *)
+type buffer = string * (int * int) list ref
+
+let buffer_max_count = ref 10
+
+let cache_size = 30
+
+let buffer_list =
+ ref ([] : (string * buffer) list)
+
+let flush_buffer_list () =
+ buffer_list := []
+
+let get_buffer pos mdle =
+ try List.assoc mdle !buffer_list with
+ Not_found ->
+ let inchan = open_in_bin (source_of_module pos mdle) in
+ let content = really_input_string inchan (in_channel_length inchan) in
+ let buffer = (content, ref []) in
+ buffer_list :=
+ (list_truncate !buffer_max_count ((mdle, buffer)::!buffer_list));
+ buffer
+
+let buffer_content =
+ (fst : buffer -> string)
+
+let buffer_length x =
+ String.length (buffer_content x)
+
+(*** Position conversions. ***)
+
+type position = int * int
+
+(* Insert a new pair (position, line) in the cache of the given buffer. *)
+let insert_pos buffer ((position, line) as pair) =
+ let rec new_list =
+ function
+ [] ->
+ [(position, line)]
+ | ((pos, lin) as a::l) as l' ->
+ if lin < line then
+ pair::l'
+ else if lin = line then
+ l'
+ else
+ a::(new_list l)
+ in
+ let buffer_cache = snd buffer in
+ buffer_cache := new_list !buffer_cache
+
+(* Position of the next linefeed after `pos'. *)
+(* Position just after the buffer end if no linefeed found. *)
+(* Raise `Out_of_range' if already there. *)
+let next_linefeed (buffer, _) pos =
+ let len = String.length buffer in
+ if pos >= len then
+ raise Out_of_range
+ else
+ let rec search p =
+ if p = len || String.get buffer p = '\n' then
+ p
+ else
+ search (succ p)
+ in
+ search pos
+
+(* Go to next line. *)
+let next_line buffer (pos, line) =
+ (next_linefeed buffer pos + 1, line + 1)
+
+(* Convert a position in the buffer to a line number. *)
+let line_of_pos buffer position =
+ let rec find =
+ function
+ | [] ->
+ if position < 0 then
+ raise Out_of_range
+ else
+ (0, 1)
+ | ((pos, line) as pair)::l ->
+ if pos > position then
+ find l
+ else
+ pair
+ and find_line previous =
+ let (pos, line) as next = next_line buffer previous in
+ if pos <= position then
+ find_line next
+ else
+ previous
+ in
+ let result = find_line (find !(snd buffer)) in
+ insert_pos buffer result;
+ result
+
+(* Convert a line number to a position. *)
+let pos_of_line buffer line =
+ let rec find =
+ function
+ [] ->
+ if line <= 0 then
+ raise Out_of_range
+ else
+ (0, 1)
+ | ((pos, lin) as pair)::l ->
+ if lin > line then
+ find l
+ else
+ pair
+ and find_pos previous =
+ let (_, lin) as next = next_line buffer previous in
+ if lin <= line then
+ find_pos next
+ else
+ previous
+ in
+ let result = find_pos (find !(snd buffer)) in
+ insert_pos buffer result;
+ result
+
+(* Convert a coordinate (line / column) into a position. *)
+(* --- The first line and column are line 1 and column 1. *)
+let point_of_coord buffer line column =
+ fst (pos_of_line buffer line) + (pred column)
+
+let start_and_cnum buffer pos =
+ let line_number = pos.Lexing.pos_lnum in
+ let start = point_of_coord buffer line_number 1 in
+ start, start + (pos.Lexing.pos_cnum - pos.Lexing.pos_bol)
diff --git a/debugger/source.mli b/debugger/source.mli
new file mode 100644
index 0000000000..640ebc858a
--- /dev/null
+++ b/debugger/source.mli
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(************************ Source management ****************************)
+
+(*** Conversion function. ***)
+
+val source_of_module: Lexing.position -> string -> string
+
+(*** buffer cache ***)
+
+type buffer
+
+val buffer_max_count : int ref
+
+val flush_buffer_list : unit -> unit
+
+val get_buffer : Lexing.position -> string -> buffer
+
+val buffer_content : buffer -> string
+val buffer_length : buffer -> int
+
+(*** Position conversions. ***)
+
+(* Pair (position, line) where `position' is the position in character of *)
+(* the beginning of the line (first character is 0) and `line' is its *)
+(* number (first line number is 1). *)
+type position = int * int
+
+(* Position of the next linefeed after `pos'. *)
+(* Position just after the buffer end if no linefeed found. *)
+(* Raise `Out_of_range' if already there. *)
+val next_linefeed : buffer -> int -> int
+
+(* Go to next line. *)
+val next_line : buffer -> position -> position
+
+(* Convert a position in the buffer to a line number. *)
+val line_of_pos : buffer -> int -> position
+
+(* Convert a line number to a position. *)
+val pos_of_line : buffer -> int -> position
+
+(* Convert a coordinate (line / column) into a position. *)
+(* --- The first line and column are line 1 and column 1. *)
+val point_of_coord : buffer -> int -> int -> int
+
+(* Return the offsets of both line start and cnum for the passed position. *)
+val start_and_cnum : buffer -> Lexing.position -> (int * int)
diff --git a/debugger/symbols.ml b/debugger/symbols.ml
new file mode 100644
index 0000000000..1be7253328
--- /dev/null
+++ b/debugger/symbols.ml
@@ -0,0 +1,209 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Handling of symbol tables (globals and events) *)
+
+open Instruct
+open Debugger_config (* Toplevel *)
+open Program_loading
+
+module StringSet = Set.Make(String)
+
+let modules =
+ ref ([] : string list)
+
+let program_source_dirs =
+ ref ([] : string list)
+
+let events =
+ ref ([] : debug_event list)
+let events_by_pc =
+ (Hashtbl.create 257 : (int, debug_event) Hashtbl.t)
+let events_by_module =
+ (Hashtbl.create 17 : (string, debug_event array) Hashtbl.t)
+let all_events_by_module =
+ (Hashtbl.create 17 : (string, debug_event list) Hashtbl.t)
+
+let relocate_event orig ev =
+ ev.ev_pos <- orig + ev.ev_pos;
+ match ev.ev_repr with
+ Event_parent repr -> repr := ev.ev_pos
+ | _ -> ()
+
+let read_symbols' bytecode_file =
+ let ic = open_in_bin bytecode_file in
+ begin try
+ Bytesections.read_toc ic;
+ ignore(Bytesections.seek_section ic "SYMB");
+ with Bytesections.Bad_magic_number | Not_found ->
+ prerr_string bytecode_file; prerr_endline " is not a bytecode file.";
+ raise Toplevel
+ end;
+ Symtable.restore_state (input_value ic);
+ begin try
+ ignore (Bytesections.seek_section ic "DBUG")
+ with Not_found ->
+ prerr_string bytecode_file; prerr_endline " has no debugging info.";
+ raise Toplevel
+ end;
+ let num_eventlists = input_binary_int ic in
+ let dirs = ref StringSet.empty in
+ let eventlists = ref [] in
+ for i = 1 to num_eventlists do
+ let orig = input_binary_int ic in
+ let evl = (input_value ic : debug_event list) in
+ (* Relocate events in event list *)
+ List.iter (relocate_event orig) evl;
+ eventlists := evl :: !eventlists;
+ dirs :=
+ List.fold_left (fun s e -> StringSet.add e s) !dirs (input_value ic)
+ done;
+ begin try
+ ignore (Bytesections.seek_section ic "CODE")
+ with Not_found ->
+ (* The file contains only debugging info,
+ loading mode is forced to "manual" *)
+ set_launching_function (List.assoc "manual" loading_modes)
+ end;
+ close_in_noerr ic;
+ !eventlists, !dirs
+
+let read_symbols bytecode_file =
+ let all_events, all_dirs = read_symbols' bytecode_file in
+
+ modules := []; events := [];
+ program_source_dirs := StringSet.elements all_dirs;
+ Hashtbl.clear events_by_pc; Hashtbl.clear events_by_module;
+ Hashtbl.clear all_events_by_module;
+
+ List.iter
+ (fun evl ->
+ List.iter
+ (fun ev ->
+ events := ev :: !events;
+ Hashtbl.add events_by_pc ev.ev_pos ev)
+ evl)
+ all_events;
+
+ List.iter
+ (function
+ [] -> ()
+ | ev :: _ as evl ->
+ let md = ev.ev_module in
+ let cmp ev1 ev2 = compare (Events.get_pos ev1).Lexing.pos_cnum
+ (Events.get_pos ev2).Lexing.pos_cnum
+ in
+ let sorted_evl = List.sort cmp evl in
+ modules := md :: !modules;
+ Hashtbl.add all_events_by_module md sorted_evl;
+ let real_evl =
+ List.filter
+ (function
+ {ev_kind = Event_pseudo} -> false
+ | _ -> true)
+ sorted_evl
+ in
+ Hashtbl.add events_by_module md (Array.of_list real_evl))
+ all_events
+
+let any_event_at_pc pc =
+ Hashtbl.find events_by_pc pc
+
+let event_at_pc pc =
+ let ev = any_event_at_pc pc in
+ match ev.ev_kind with
+ Event_pseudo -> raise Not_found
+ | _ -> ev
+
+let set_event_at_pc pc =
+ try ignore(event_at_pc pc); Debugcom.set_event pc
+ with Not_found -> ()
+
+(* List all events in module *)
+let events_in_module mdle =
+ try
+ Hashtbl.find all_events_by_module mdle
+ with Not_found ->
+ []
+
+(* Binary search of event at or just after char *)
+let find_event ev char =
+ let rec bsearch lo hi =
+ if lo >= hi then begin
+ if (Events.get_pos ev.(hi)).Lexing.pos_cnum < char
+ then raise Not_found
+ else hi
+ end else begin
+ let pivot = (lo + hi) / 2 in
+ let e = ev.(pivot) in
+ if char <= (Events.get_pos e).Lexing.pos_cnum
+ then bsearch lo pivot
+ else bsearch (pivot + 1) hi
+ end
+ in
+ bsearch 0 (Array.length ev - 1)
+
+(* Return first event after the given position. *)
+(* Raise [Not_found] if module is unknown or no event is found. *)
+let event_at_pos md char =
+ let ev = Hashtbl.find events_by_module md in
+ ev.(find_event ev char)
+
+(* Return event closest to given position *)
+(* Raise [Not_found] if module is unknown or no event is found. *)
+let event_near_pos md char =
+ let ev = Hashtbl.find events_by_module md in
+ try
+ let pos = find_event ev char in
+ (* Desired event is either ev.(pos) or ev.(pos - 1),
+ whichever is closest *)
+ if pos > 0 && char - (Events.get_pos ev.(pos - 1)).Lexing.pos_cnum
+ <= (Events.get_pos ev.(pos)).Lexing.pos_cnum - char
+ then ev.(pos - 1)
+ else ev.(pos)
+ with Not_found ->
+ let pos = Array.length ev - 1 in
+ if pos < 0 then raise Not_found;
+ ev.(pos)
+
+(* Flip "event" bit on all instructions *)
+let set_all_events () =
+ Hashtbl.iter
+ (fun pc ev ->
+ match ev.ev_kind with
+ Event_pseudo -> ()
+ | _ -> Debugcom.set_event ev.ev_pos)
+ events_by_pc
+
+
+(* Previous `pc'. *)
+(* Save time if `update_current_event' is called *)
+(* several times at the same point. *)
+let old_pc = ref (None : int option)
+
+(* Recompute the current event *)
+let update_current_event () =
+ match Checkpoints.current_pc () with
+ None ->
+ Events.current_event := None;
+ old_pc := None
+ | (Some pc) as opt_pc when opt_pc <> !old_pc ->
+ Events.current_event :=
+ begin try
+ Some (event_at_pc pc)
+ with Not_found ->
+ None
+ end;
+ old_pc := opt_pc
+ | _ ->
+ ()
diff --git a/debugger/symbols.mli b/debugger/symbols.mli
new file mode 100644
index 0000000000..883b81aa3e
--- /dev/null
+++ b/debugger/symbols.mli
@@ -0,0 +1,48 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Modules used by the program. *)
+val modules : string list ref
+
+(* Absolute directories containing source code on machine where source was
+ * compiled *)
+val program_source_dirs : string list ref
+
+(* Read debugging info from executable file *)
+val read_symbols : string -> unit
+
+(* Flip "event" bit on all instructions *)
+val set_all_events : unit -> unit
+
+(* Return event at given PC, or raise Not_found *)
+(* Can also return pseudo-event at beginning of functions *)
+val any_event_at_pc : int -> Instruct.debug_event
+
+(* Return event at given PC, or raise Not_found *)
+val event_at_pc : int -> Instruct.debug_event
+(* Set event at given PC *)
+val set_event_at_pc : int -> unit
+
+(* List the events in `module'. *)
+val events_in_module : string -> Instruct.debug_event list
+
+(* First event after the given position. *)
+(* --- Raise `Not_found' if no such event. *)
+val event_at_pos : string -> int -> Instruct.debug_event
+
+(* Closest event from given position. *)
+(* --- Raise `Not_found' if no such event. *)
+val event_near_pos : string -> int -> Instruct.debug_event
+
+(* Recompute the current event *)
+val update_current_event : unit -> unit
diff --git a/debugger/time_travel.ml b/debugger/time_travel.ml
new file mode 100644
index 0000000000..37bbe390dd
--- /dev/null
+++ b/debugger/time_travel.ml
@@ -0,0 +1,648 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(**************************** Time travel ******************************)
+
+open Int64ops
+open Instruct
+open Events
+open Debugcom
+open Primitives
+open Checkpoints
+open Breakpoints
+open Trap_barrier
+open Input_handling
+open Debugger_config
+open Program_loading
+open Question
+
+exception Current_checkpoint_lost
+exception Current_checkpoint_lost_start_at of int64 * int64
+
+let remove_1st key list =
+ let rec remove =
+ function
+ [] -> []
+ | a::l -> if a == key then l else a::(remove l)
+ in
+ remove list
+
+(*** Debugging. ***)
+
+let debug_time_travel = ref false
+
+(*** Internal utilities. ***)
+
+(* Insert a checkpoint in the checkpoint list.
+ * Raise `Exit' if there is already a checkpoint at the same time.
+ *)
+let insert_checkpoint ({c_time = time} as checkpoint) =
+ let rec traverse =
+ function
+ [] -> [checkpoint]
+ | (({c_time = t} as a)::l) as l' ->
+ if t > time then
+ a::(traverse l)
+ else if t = time then
+ raise Exit
+ else
+ checkpoint::l'
+ in
+ checkpoints := traverse !checkpoints
+
+(* Remove a checkpoint from the checkpoint list.
+ * --- No error if not found.
+ *)
+let remove_checkpoint checkpoint =
+ checkpoints := remove_1st checkpoint !checkpoints
+
+(* Wait for the process used by `checkpoint' to connect.
+ * --- Usually not called (the process is already connected).
+ *)
+let wait_for_connection checkpoint =
+ try
+ Exec.unprotect
+ (function () ->
+ let old_controller = Input_handling.current_controller !connection in
+ execute_with_other_controller
+ (function
+ fd ->
+ old_controller fd;
+ if checkpoint.c_valid = true then
+ exit_main_loop ())
+ !connection
+ main_loop)
+ with
+ Sys.Break ->
+ checkpoint.c_parent <- root;
+ remove_checkpoint checkpoint;
+ checkpoint.c_pid <- -1;
+ raise Sys.Break
+
+(* Select a checkpoint as current. *)
+let set_current_checkpoint checkpoint =
+ if !debug_time_travel then
+ prerr_endline ("Select: " ^ (string_of_int checkpoint.c_pid));
+ if not checkpoint.c_valid then
+ wait_for_connection checkpoint;
+ current_checkpoint := checkpoint;
+ set_current_connection checkpoint.c_fd
+
+(* Kill `checkpoint'. *)
+let kill_checkpoint checkpoint =
+ if !debug_time_travel then
+ prerr_endline ("Kill: " ^ (string_of_int checkpoint.c_pid));
+ if checkpoint.c_pid > 0 then (* Ghosts don't have to be killed ! *)
+ (if not checkpoint.c_valid then
+ wait_for_connection checkpoint;
+ stop checkpoint.c_fd;
+ if checkpoint.c_parent.c_pid > 0 then
+ wait_child checkpoint.c_parent.c_fd;
+ checkpoint.c_parent <- root;
+ close_io checkpoint.c_fd;
+ remove_file checkpoint.c_fd;
+ remove_checkpoint checkpoint);
+ checkpoint.c_pid <- -1 (* Don't exist anymore *)
+
+(*** Cleaning the checkpoint list. ***)
+
+(* Separe checkpoints before (<=) and after (>) `t'. *)
+(* ### t checkpoints -> (after, before) *)
+let cut t =
+ let rec cut_t =
+ function
+ [] -> ([], [])
+ | ({c_time = t'} as a::l) as l' ->
+ if t' <= t then
+ ([], l')
+ else
+ let (b, e) = cut_t l in
+ (a::b, e)
+ in
+ cut_t
+
+(* Partition the checkpoints list. *)
+let cut2 t0 t l =
+ let rec cut2_t0 t =
+ function
+ [] -> []
+ | l ->
+ let (after, before) = cut (t0 -- t -- _1) l in
+ let l = cut2_t0 (t ++ t) before in
+ after::l
+ in
+ let (after, before) = cut (t0 -- _1) l in
+ after::(cut2_t0 t before)
+
+(* Separe first elements and last element of a list of checkpoint. *)
+let chk_merge2 cont =
+ let rec chk_merge2_cont =
+ function
+ [] -> cont
+ | [a] ->
+ let (accepted, rejected) = cont in
+ (a::accepted, rejected)
+ | a::l ->
+ let (accepted, rejected) = chk_merge2_cont l in
+ (accepted, a::rejected)
+ in chk_merge2_cont
+
+(* Separe the checkpoint list. *)
+(* ### list -> accepted * rejected *)
+let rec chk_merge =
+ function
+ [] -> ([], [])
+ | l::tail ->
+ chk_merge2 (chk_merge tail) l
+
+let new_checkpoint_list checkpoint_count accepted rejected =
+ if List.length accepted >= checkpoint_count then
+ let (k, l) = list_truncate2 checkpoint_count accepted in
+ (k, l @ rejected)
+ else
+ let (k, l) =
+ list_truncate2 (checkpoint_count - List.length accepted) rejected
+ in
+ (List.merge (fun {c_time = t1} {c_time = t2} -> compare t2 t1) accepted k,
+ l)
+
+(* Clean the checkpoint list. *)
+(* Reference time is `time'. *)
+let clean_checkpoints time checkpoint_count =
+ let (after, before) = cut time !checkpoints in
+ let (accepted, rejected) =
+ chk_merge (cut2 time !checkpoint_small_step before)
+ in
+ let (kept, lost) =
+ new_checkpoint_list checkpoint_count accepted after
+ in
+ List.iter kill_checkpoint (lost @ rejected);
+ checkpoints := kept
+
+(*** Internal functions for moving. ***)
+
+(* Find the first checkpoint before (or at) `time'.
+ * Ask for reloading the program if necessary.
+ *)
+let find_checkpoint_before time =
+ let rec find =
+ function
+ [] ->
+ print_string "Can't go that far in the past !"; print_newline ();
+ if yes_or_no "Reload program" then begin
+ load_program ();
+ find !checkpoints
+ end
+ else
+ raise Toplevel
+ | { c_time = t } as a::l ->
+ if t > time then
+ find l
+ else
+ a
+ in find !checkpoints
+
+(* Make a copy of the current checkpoint and clean the checkpoint list. *)
+(* --- The new checkpoint in not put in the list. *)
+let duplicate_current_checkpoint () =
+ let checkpoint = !current_checkpoint in
+ if not checkpoint.c_valid then
+ wait_for_connection checkpoint;
+ let new_checkpoint = (* Ghost *)
+ {c_time = checkpoint.c_time;
+ c_pid = 0;
+ c_fd = checkpoint.c_fd;
+ c_valid = false;
+ c_report = checkpoint.c_report;
+ c_state = C_stopped;
+ c_parent = checkpoint;
+ c_breakpoint_version = checkpoint.c_breakpoint_version;
+ c_breakpoints = checkpoint.c_breakpoints;
+ c_trap_barrier = checkpoint.c_trap_barrier}
+ in
+ checkpoints := list_replace checkpoint new_checkpoint !checkpoints;
+ set_current_checkpoint checkpoint;
+ clean_checkpoints (checkpoint.c_time ++ _1) (!checkpoint_max_count - 1);
+ if new_checkpoint.c_pid = 0 then (* The ghost has not been killed *)
+ (match do_checkpoint () with (* Duplicate checkpoint *)
+ Checkpoint_done pid ->
+ (new_checkpoint.c_pid <- pid;
+ if !debug_time_travel then
+ prerr_endline ("Waiting for connection: " ^ string_of_int pid))
+ | Checkpoint_failed ->
+ prerr_endline
+ "A fork failed. Reducing maximum number of checkpoints.";
+ checkpoint_max_count := List.length !checkpoints - 1;
+ remove_checkpoint new_checkpoint)
+
+(* Was the movement interrupted ? *)
+(* --- An exception could have been used instead, *)
+(* --- but it is not clear where it should be caught. *)
+(* --- For instance, it should not be caught in `step' *)
+(* --- (as `step' is used in `next_1'). *)
+(* --- On the other side, other modules does not need to know *)
+(* --- about this exception. *)
+let interrupted = ref false
+
+(* Informations about last breakpoint encountered *)
+let last_breakpoint = ref None
+
+(* Ensure we stop on an event. *)
+let rec stop_on_event report =
+ match report with
+ {rep_type = Breakpoint; rep_program_pointer = pc;
+ rep_stack_pointer = sp} ->
+ last_breakpoint := Some (pc, sp);
+ Symbols.update_current_event ();
+ begin match !current_event with
+ None -> find_event ()
+ | Some _ -> ()
+ end
+ | {rep_type = Trap_barrier; rep_stack_pointer = trap_frame} ->
+ (* No event at current position. *)
+ find_event ()
+ | _ ->
+ ()
+
+and find_event () =
+ if !debug_time_travel then begin
+ print_string "Searching next event...";
+ print_newline ()
+ end;
+ let report = do_go _1 in
+ !current_checkpoint.c_report <- Some report;
+ stop_on_event report
+
+(* Internal function for running debugged program.
+ * Requires `duration > 0'.
+ *)
+let internal_step duration =
+ match current_report () with
+ Some {rep_type = Exited | Uncaught_exc} -> ()
+ | _ ->
+ Exec.protect
+ (function () ->
+ if !make_checkpoints then
+ duplicate_current_checkpoint ()
+ else
+ remove_checkpoint !current_checkpoint;
+ update_breakpoints ();
+ update_trap_barrier ();
+ !current_checkpoint.c_state <- C_running duration;
+ let report = do_go duration in
+ !current_checkpoint.c_report <- Some report;
+ !current_checkpoint.c_state <- C_stopped;
+ if report.rep_type = Event then begin
+ !current_checkpoint.c_time <-
+ !current_checkpoint.c_time ++ duration;
+ interrupted := false;
+ last_breakpoint := None
+ end
+ else begin
+ !current_checkpoint.c_time <-
+ !current_checkpoint.c_time ++ duration
+ -- (Int64.of_int report.rep_event_count) ++ _1;
+ interrupted := true;
+ last_breakpoint := None;
+ stop_on_event report
+ end;
+ (try
+ insert_checkpoint !current_checkpoint
+ with
+ Exit ->
+ kill_checkpoint !current_checkpoint;
+ set_current_checkpoint
+ (find_checkpoint_before (current_time ()))));
+ if !debug_time_travel then begin
+ print_string "Checkpoints: pid(time)"; print_newline ();
+ List.iter
+ (function {c_time = time; c_pid = pid; c_valid = valid} ->
+ Printf.printf "%d(%Ld)%s " pid time
+ (if valid then "" else "(invalid)"))
+ !checkpoints;
+ print_newline ()
+ end
+
+(*** Miscellaneous functions (exported). ***)
+
+(* Create a checkpoint at time 0 (new program). *)
+let new_checkpoint pid fd =
+ let new_checkpoint =
+ {c_time = _0;
+ c_pid = pid;
+ c_fd = fd;
+ c_valid = true;
+ c_report = None;
+ c_state = C_stopped;
+ c_parent = root;
+ c_breakpoint_version = 0;
+ c_breakpoints = [];
+ c_trap_barrier = 0}
+ in
+ insert_checkpoint new_checkpoint
+
+(* Set the file descriptor of a checkpoint *)
+(* (a new process has connected with the debugger). *)
+(* --- Return `true' on success (close the connection otherwise). *)
+let set_file_descriptor pid fd =
+ let rec find =
+ function
+ [] ->
+ prerr_endline "Unexpected connection";
+ close_io fd;
+ false
+ | ({c_pid = pid'} as checkpoint)::l ->
+ if pid <> pid' then
+ find l
+ else
+ (checkpoint.c_fd <- fd;
+ checkpoint.c_valid <- true;
+ true)
+ in
+ if !debug_time_travel then
+ prerr_endline ("New connection: " ^(string_of_int pid));
+ find (!current_checkpoint::!checkpoints)
+
+(* Kill all the checkpoints. *)
+let kill_all_checkpoints () =
+ List.iter kill_checkpoint (!current_checkpoint::!checkpoints)
+
+(* Kill a checkpoint without killing the process. *)
+(* (used when connection with the process is lost). *)
+(* --- Assume that the checkpoint is valid. *)
+let forget_process fd pid =
+ let checkpoint =
+ List.find (function c -> c.c_pid = pid) (!current_checkpoint::!checkpoints)
+ in
+ if pid > 0 then begin
+ Printf.eprintf "Lost connection with process %d" pid;
+ let kont =
+ if checkpoint == !current_checkpoint then begin
+ Printf.eprintf " (active process)\n";
+ match !current_checkpoint.c_state with
+ C_stopped ->
+ Printf.eprintf "at time %Ld" !current_checkpoint.c_time;
+ fun () -> raise Current_checkpoint_lost
+ | C_running duration ->
+ Printf.eprintf "between time %Ld and time %Ld"
+ !current_checkpoint.c_time
+ (!current_checkpoint.c_time ++ duration);
+ fun () -> raise (Current_checkpoint_lost_start_at
+ (!current_checkpoint.c_time, duration))
+ end
+ else ignore in
+ Printf.eprintf "\n"; flush stderr;
+ Input_handling.remove_file fd;
+ close_io checkpoint.c_fd;
+ remove_file checkpoint.c_fd;
+ remove_checkpoint checkpoint;
+ checkpoint.c_pid <- -1; (* Don't exist anymore *)
+ if checkpoint.c_parent.c_pid > 0 then
+ wait_child checkpoint.c_parent.c_fd;
+ kont ()
+ end
+
+(* Try to recover when the current checkpoint is lost. *)
+let recover () =
+ set_current_checkpoint
+ (find_checkpoint_before (current_time ()))
+
+(*** Simple movements. ***)
+
+(* Forward stepping. Requires `duration >= 0'. *)
+let rec step_forward duration =
+ if duration > !checkpoint_small_step then begin
+ let first_step =
+ if duration > !checkpoint_big_step then
+ !checkpoint_big_step
+ else
+ !checkpoint_small_step
+ in
+ internal_step first_step;
+ if not !interrupted then
+ step_forward (duration -- first_step)
+ end
+ else if duration != _0 then
+ internal_step duration
+
+(* Go to time `time' from current checkpoint (internal). *)
+let internal_go_to time =
+ let duration = time -- (current_time ()) in
+ if duration > _0 then
+ execute_without_breakpoints (function () -> step_forward duration)
+
+(* Move to a given time. *)
+let go_to time =
+ let checkpoint = find_checkpoint_before time in
+ set_current_checkpoint checkpoint;
+ internal_go_to time
+
+(* Return the time of the last breakpoint *)
+(* between current time and `max_time'. *)
+let rec find_last_breakpoint max_time =
+ let rec find break =
+ let time = current_time () in
+ step_forward (max_time -- time);
+ match !last_breakpoint, !temporary_breakpoint_position with
+ (Some _, _) when current_time () < max_time ->
+ find !last_breakpoint
+ | (Some (pc, _), Some pc') when pc = pc' ->
+ (max_time, !last_breakpoint)
+ | _ ->
+ (time, break)
+ in
+ find
+ (match current_pc_sp () with
+ (Some (pc, _)) as state when breakpoint_at_pc pc -> state
+ | _ -> None)
+
+
+(* Run from `time_max' back to `time'. *)
+(* --- Assume 0 <= time < time_max *)
+let rec back_to time time_max =
+ let
+ {c_time = t} = find_checkpoint_before (pre64 time_max)
+ in
+ go_to (max time t);
+ let (new_time, break) = find_last_breakpoint time_max in
+ if break <> None || (new_time <= time) then begin
+ go_to new_time;
+ interrupted := break <> None;
+ last_breakpoint := break
+ end else
+ back_to time new_time
+
+(* Backward stepping. *)
+(* --- Assume duration > 1 *)
+let step_backward duration =
+ let time = current_time () in
+ if time > _0 then
+ back_to (max _0 (time -- duration)) time
+
+(* Run the program from current time. *)
+(* Stop at the first breakpoint, or at the end of the program. *)
+let rec run () =
+ internal_step !checkpoint_big_step;
+ if not !interrupted then
+ run ()
+
+(* Run backward the program form current time. *)
+(* Stop at the first breakpoint, or at the beginning of the program. *)
+let back_run () =
+ if current_time () > _0 then
+ back_to _0 (current_time ())
+
+(* Step in any direction. *)
+(* Stop at the first brakpoint, or after `duration' steps. *)
+let step duration =
+ if duration >= _0 then
+ step_forward duration
+ else
+ step_backward (_0 -- duration)
+
+(*** Next, finish. ***)
+
+(* Finish current function. *)
+let finish () =
+ Symbols.update_current_event ();
+ match !current_event with
+ None ->
+ prerr_endline "`finish' not meaningful in outermost frame.";
+ raise Toplevel
+ | Some curr_event ->
+ set_initial_frame();
+ let (frame, pc) = up_frame curr_event.ev_stacksize in
+ if frame < 0 then begin
+ prerr_endline "`finish' not meaningful in outermost frame.";
+ raise Toplevel
+ end;
+ begin
+ try ignore(Symbols.any_event_at_pc pc)
+ with Not_found ->
+ prerr_endline "Calling function has no debugging information.";
+ raise Toplevel
+ end;
+ exec_with_trap_barrier
+ frame
+ (fun () ->
+ exec_with_temporary_breakpoint
+ pc
+ (fun () ->
+ while
+ run ();
+ match !last_breakpoint with
+ Some (pc', frame') when pc = pc' ->
+ interrupted := false;
+ frame <> frame'
+ | _ ->
+ false
+ do
+ ()
+ done))
+
+let next_1 () =
+ Symbols.update_current_event ();
+ match !current_event with
+ None -> (* Beginning of the program. *)
+ step _1
+ | Some event1 ->
+ let (frame1, pc1) = initial_frame() in
+ step _1;
+ if not !interrupted then begin
+ Symbols.update_current_event ();
+ match !current_event with
+ None -> ()
+ | Some event2 ->
+ let (frame2, pc2) = initial_frame() in
+ (* Call `finish' if we've entered a function. *)
+ if frame1 >= 0 && frame2 >= 0 &&
+ frame2 - event2.ev_stacksize > frame1 - event1.ev_stacksize
+ then finish()
+ end
+
+(* Same as `step' (forward) but skip over function calls. *)
+let rec next =
+ function
+ 0 -> ()
+ | n ->
+ next_1 ();
+ if not !interrupted then
+ next (n - 1)
+
+(* Run backward until just before current function. *)
+let start () =
+ Symbols.update_current_event ();
+ match !current_event with
+ None ->
+ prerr_endline "`start not meaningful in outermost frame.";
+ raise Toplevel
+ | Some curr_event ->
+ let (frame, _) = initial_frame() in
+ let (frame', pc) = up_frame curr_event.ev_stacksize in
+ if frame' < 0 then begin
+ prerr_endline "`start not meaningful in outermost frame.";
+ raise Toplevel
+ end;
+ let nargs =
+ match
+ try Symbols.any_event_at_pc pc with Not_found ->
+ prerr_endline "Calling function has no debugging information.";
+ raise Toplevel
+ with
+ {ev_info = Event_return nargs} -> nargs
+ | _ -> Misc.fatal_error "Time_travel.start"
+ in
+ let offset = if nargs < 4 then 1 else 2 in
+ let pc = pc - 4 * offset in
+ while
+ exec_with_temporary_breakpoint pc back_run;
+ match !last_breakpoint with
+ Some (pc', frame') when pc = pc' ->
+ step _minus1;
+ (not !interrupted)
+ &&
+ (frame' - nargs > frame - curr_event.ev_stacksize)
+ | _ ->
+ false
+ do
+ ()
+ done
+
+let previous_1 () =
+ Symbols.update_current_event ();
+ match !current_event with
+ None -> (* End of the program. *)
+ step _minus1
+ | Some event1 ->
+ let (frame1, pc1) = initial_frame() in
+ step _minus1;
+ if not !interrupted then begin
+ Symbols.update_current_event ();
+ match !current_event with
+ None -> ()
+ | Some event2 ->
+ let (frame2, pc2) = initial_frame() in
+ (* Call `start' if we've entered a function. *)
+ if frame1 >= 0 && frame2 >= 0 &&
+ frame2 - event2.ev_stacksize > frame1 - event1.ev_stacksize
+ then start()
+ end
+
+(* Same as `step' (backward) but skip over function calls. *)
+let rec previous =
+ function
+ 0 -> ()
+ | n ->
+ previous_1 ();
+ if not !interrupted then
+ previous (n - 1)
diff --git a/debugger/time_travel.mli b/debugger/time_travel.mli
new file mode 100644
index 0000000000..2d3523203a
--- /dev/null
+++ b/debugger/time_travel.mli
@@ -0,0 +1,35 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(**************************** Time travel ******************************)
+
+open Primitives
+
+exception Current_checkpoint_lost
+exception Current_checkpoint_lost_start_at of int64 * int64
+
+val new_checkpoint : int -> io_channel -> unit
+val set_file_descriptor : int -> io_channel -> bool
+val kill_all_checkpoints : unit -> unit
+val forget_process : io_channel -> int -> unit
+val recover : unit -> unit
+
+val go_to : int64 -> unit
+
+val run : unit -> unit
+val back_run : unit -> unit
+val step : int64 -> unit
+val finish : unit -> unit
+val next : int -> unit
+val start : unit -> unit
+val previous : int -> unit
diff --git a/debugger/trap_barrier.ml b/debugger/trap_barrier.ml
new file mode 100644
index 0000000000..ce5fe7625f
--- /dev/null
+++ b/debugger/trap_barrier.ml
@@ -0,0 +1,45 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(************************** Trap barrier *******************************)
+
+open Debugcom
+open Checkpoints
+
+let current_trap_barrier = ref 0
+
+let install_trap_barrier pos =
+ current_trap_barrier := pos
+
+let remove_trap_barrier () =
+ current_trap_barrier := 0
+
+(* Ensure the trap barrier state is up to date in current checkpoint. *)
+let update_trap_barrier () =
+ if !current_checkpoint.c_trap_barrier <> !current_trap_barrier then
+ Exec.protect
+ (function () ->
+ set_trap_barrier !current_trap_barrier;
+ !current_checkpoint.c_trap_barrier <- !current_trap_barrier)
+
+(* Execute `funct' with a trap barrier. *)
+(* --- Used by `finish'. *)
+let exec_with_trap_barrier trap_barrier funct =
+ try
+ install_trap_barrier trap_barrier;
+ funct ();
+ remove_trap_barrier ()
+ with
+ x ->
+ remove_trap_barrier ();
+ raise x
diff --git a/debugger/trap_barrier.mli b/debugger/trap_barrier.mli
new file mode 100644
index 0000000000..239c12a657
--- /dev/null
+++ b/debugger/trap_barrier.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(************************* Trap barrier ********************************)
+
+val install_trap_barrier : int -> unit
+
+val remove_trap_barrier : unit -> unit
+
+(* Ensure the trap barrier state is up to date in current checkpoint. *)
+val update_trap_barrier : unit -> unit
+
+(* Execute `funct' with a trap barrier. *)
+(* --- Used by `finish'. *)
+val exec_with_trap_barrier : int -> (unit -> unit) -> unit
diff --git a/debugger/unix_tools.ml b/debugger/unix_tools.ml
new file mode 100644
index 0000000000..8cefd37e0d
--- /dev/null
+++ b/debugger/unix_tools.ml
@@ -0,0 +1,142 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(****************** Tools for Unix *************************************)
+
+open Misc
+open Unix
+open Primitives
+
+(*** Convert a socket name into a socket address. ***)
+let convert_address address =
+ try
+ let n = String.index address ':' in
+ let host = String.sub address 0 n
+ and port = String.sub address (n + 1) (String.length address - n - 1)
+ in
+ (PF_INET,
+ ADDR_INET
+ ((try inet_addr_of_string host with Failure _ ->
+ try (gethostbyname host).h_addr_list.(0) with Not_found ->
+ prerr_endline ("Unknown host: " ^ host);
+ failwith "Can't convert address"),
+ (try int_of_string port with Failure _ ->
+ prerr_endline "The port number should be an integer";
+ failwith "Can't convert address")))
+ with Not_found ->
+ match Sys.os_type with
+ "Win32" -> failwith "Unix sockets not supported"
+ | _ -> (PF_UNIX, ADDR_UNIX address)
+
+(*** Report a unix error. ***)
+let report_error = function
+ | Unix_error (err, fun_name, arg) ->
+ prerr_string "Unix error: '";
+ prerr_string fun_name;
+ prerr_string "' failed";
+ if String.length arg > 0 then
+ (prerr_string " on '";
+ prerr_string arg;
+ prerr_string "'");
+ prerr_string ": ";
+ prerr_endline (error_message err)
+ | _ -> fatal_error "report_error: not a Unix error"
+
+(* Find program `name' in `PATH'. *)
+(* Return the full path if found. *)
+(* Raise `Not_found' otherwise. *)
+let search_in_path name =
+ Printf.fprintf Pervasives.stderr "search_in_path [%s]\n%!" name;
+ let check name =
+ try access name [X_OK]; name with Unix_error _ -> raise Not_found
+ in
+ if not (Filename.is_implicit name) then
+ check name
+ else
+ let path = Sys.getenv "PATH" in
+ let length = String.length path in
+ let rec traverse pointer =
+ if (pointer >= length) || (path.[pointer] = ':') then
+ pointer
+ else
+ traverse (pointer + 1)
+ in
+ let rec find pos =
+ let pos2 = traverse pos in
+ let directory = (String.sub path pos (pos2 - pos)) in
+ let fullname =
+ if directory = "" then name else directory ^ "/" ^ name
+ in
+ try check fullname with
+ | Not_found ->
+ if pos2 < length then find (pos2 + 1)
+ else raise Not_found
+ in
+ find 0
+
+(* Expand a path. *)
+(* ### path -> path' *)
+let rec expand_path ch =
+ let rec subst_variable ch =
+ try
+ let pos = String.index ch '$' in
+ if (pos + 1 < String.length ch) && (ch.[pos + 1] = '$') then
+ (String.sub ch 0 (pos + 1))
+ ^ (subst_variable
+ (String.sub ch (pos + 2) (String.length ch - pos - 2)))
+ else
+ (String.sub ch 0 pos)
+ ^ (subst2 (String.sub ch (pos + 1) (String.length ch - pos - 1)))
+ with Not_found ->
+ ch
+ and subst2 ch =
+ let suiv =
+ let i = ref 0 in
+ while !i < String.length ch &&
+ (let c = ch.[!i] in (c >= 'a' && c <= 'z')
+ || (c >= 'A' && c <= 'Z')
+ || (c >= '0' && c <= '9')
+ || c = '_')
+ do incr i done;
+ !i
+ in (Sys.getenv (String.sub ch 0 suiv))
+ ^ (subst_variable (String.sub ch suiv (String.length ch - suiv)))
+ in
+ let ch = subst_variable ch in
+ let concat_root nom ch2 =
+ try Filename.concat (getpwnam nom).pw_dir ch2
+ with Not_found ->
+ "~" ^ nom
+ in
+ if ch.[0] = '~' then
+ try
+ match String.index ch '/' with
+ 1 ->
+ (let tail = String.sub ch 2 (String.length ch - 2)
+ in
+ try Filename.concat (Sys.getenv "HOME") tail
+ with Not_found ->
+ concat_root (Sys.getenv "LOGNAME") tail)
+ | n -> concat_root
+ (String.sub ch 1 (n - 1))
+ (String.sub ch (n + 1) (String.length ch - n - 1))
+ with
+ Not_found ->
+ expand_path (ch ^ "/")
+ else ch
+
+let make_absolute name =
+ if Filename.is_relative name
+ then Filename.concat (getcwd ()) name
+ else name
+;;
diff --git a/debugger/unix_tools.mli b/debugger/unix_tools.mli
new file mode 100644
index 0000000000..b1ac62dbc5
--- /dev/null
+++ b/debugger/unix_tools.mli
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(**************************** Tools for Unix ***************************)
+
+open Unix
+
+(* Convert a socket name into a socket address. *)
+val convert_address : string -> socket_domain * sockaddr
+
+(* Report an unix error. *)
+val report_error : exn -> unit
+
+(* Find program `name' in `PATH'. *)
+(* Return the full path if found. *)
+(* Raise `Not_found' otherwise. *)
+val search_in_path : string -> string
+
+(* Path expansion. *)
+val expand_path : string -> string
+
+val make_absolute : string -> string
diff --git a/driver/compenv.ml b/driver/compenv.ml
new file mode 100644
index 0000000000..32d5f7e91c
--- /dev/null
+++ b/driver/compenv.ml
@@ -0,0 +1,311 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, EPI Gallium, INRIA Paris-Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Clflags
+
+let output_prefix name =
+ let oname =
+ match !output_name with
+ | None -> name
+ | Some n -> if !compile_only then (output_name := None; n) else name in
+ Misc.chop_extension_if_any oname
+
+let print_version_and_library compiler =
+ Printf.printf "The OCaml %s, version " compiler;
+ print_string Config.version; print_newline();
+ print_string "Standard library directory: ";
+ print_string Config.standard_library; print_newline();
+ exit 0
+
+let print_version_string () =
+ print_string Config.version; print_newline(); exit 0
+
+let print_standard_library () =
+ print_string Config.standard_library; print_newline(); exit 0
+
+let fatal err =
+ prerr_endline err;
+ exit 2
+
+let extract_output = function
+ | Some s -> s
+ | None ->
+ fatal "Please specify the name of the output file, using option -o"
+
+let default_output = function
+ | Some s -> s
+ | None -> Config.default_executable_name
+
+let implicit_modules = ref []
+let first_include_dirs = ref []
+let last_include_dirs = ref []
+let first_ccopts = ref []
+let last_ccopts = ref []
+let first_ppx = ref []
+let last_ppx = ref []
+let first_objfiles = ref []
+let last_objfiles = ref []
+
+(* Check validity of module name *)
+let is_unit_name name =
+ try
+ begin match name.[0] with
+ | 'A'..'Z' -> ()
+ | _ ->
+ raise Exit;
+ end;
+ for i = 1 to String.length name - 1 do
+ match name.[i] with
+ | 'A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '\'' -> ()
+ | _ ->
+ raise Exit;
+ done;
+ true
+ with Exit -> false
+;;
+
+let check_unit_name ppf filename name =
+ if not (is_unit_name name) then
+ Location.print_warning (Location.in_file filename) ppf
+ (Warnings.Bad_module_name name);;
+
+(* Compute name of module from output file name *)
+let module_of_filename ppf inputfile outputprefix =
+ let basename = Filename.basename outputprefix in
+ let name =
+ try
+ let pos = String.index basename '.' in
+ String.sub basename 0 pos
+ with Not_found -> basename
+ in
+ let name = String.capitalize_ascii name in
+ check_unit_name ppf inputfile name;
+ name
+;;
+
+
+type readenv_position =
+ Before_args | Before_compile | Before_link
+
+(* Syntax of OCAMLPARAM: (name=VALUE,)* _ (,name=VALUE)*
+ where VALUE should not contain ',' *)
+exception SyntaxError of string
+
+let parse_args s =
+ let args = Misc.split s ',' in
+ let rec iter is_after args before after =
+ match args with
+ [] ->
+ if not is_after then
+ raise (SyntaxError "no '_' separator found")
+ else
+ (List.rev before, List.rev after)
+ | "_" :: _ when is_after -> raise (SyntaxError "too many '_' separators")
+ | "_" :: tail -> iter true tail before after
+ | arg :: tail ->
+ let binding = try
+ Misc.cut_at arg '='
+ with Not_found ->
+ raise (SyntaxError ("missing '=' in " ^ arg))
+ in
+ if is_after then
+ iter is_after tail before (binding :: after)
+ else
+ iter is_after tail (binding :: before) after
+ in
+ iter false args [] []
+
+let setter ppf f name options s =
+ try
+ let bool = match s with
+ | "0" -> false
+ | "1" -> true
+ | _ -> raise Not_found
+ in
+ List.iter (fun b -> b := f bool) options
+ with Not_found ->
+ Location.print_warning Location.none ppf
+ (Warnings.Bad_env_variable ("OCAMLPARAM",
+ Printf.sprintf "bad value for %s" name))
+
+(* 'can-discard=' specifies which arguments can be discarded without warning
+ because they are not understood by some versions of OCaml. *)
+let can_discard = ref []
+
+let read_OCAMLPARAM ppf position =
+ try
+ let s = Sys.getenv "OCAMLPARAM" in
+ let (before, after) =
+ try
+ parse_args s
+ with SyntaxError s ->
+ Location.print_warning Location.none ppf
+ (Warnings.Bad_env_variable ("OCAMLPARAM", s));
+ [],[]
+ in
+ let set name options s = setter ppf (fun b -> b) name options s in
+ let clear name options s = setter ppf (fun b -> not b) name options s in
+ List.iter (fun (name, v) ->
+ match name with
+ | "g" -> set "g" [ Clflags.debug ] v
+ | "p" -> set "p" [ Clflags.gprofile ] v
+ | "bin-annot" -> set "bin-annot" [ Clflags.binary_annotations ] v
+ | "annot" -> set "annot" [ Clflags.annotations ] v
+ | "absname" -> set "absname" [ Location.absname ] v
+ | "compat-32" -> set "compat-32" [ bytecode_compatible_32 ] v
+ | "noassert" -> set "noassert" [ noassert ] v
+ | "noautolink" -> set "noautolink" [ no_auto_link ] v
+ | "nostdlib" -> set "nostdlib" [ no_std_include ] v
+ | "linkall" -> set "linkall" [ link_everything ] v
+ | "nolabels" -> set "nolabels" [ classic ] v
+ | "principal" -> set "principal" [ principal ] v
+ | "rectypes" -> set "rectypes" [ recursive_types ] v
+ | "safe-string" -> clear "safe-string" [ unsafe_string ] v
+ | "strict-sequence" -> set "strict-sequence" [ strict_sequence ] v
+ | "strict-formats" -> set "strict-formats" [ strict_formats ] v
+ | "thread" -> set "thread" [ use_threads ] v
+ | "unsafe" -> set "unsafe" [ fast ] v
+ | "verbose" -> set "verbose" [ verbose ] v
+ | "nopervasives" -> set "nopervasives" [ nopervasives ] v
+ | "slash" -> set "slash" [ force_slash ] v (* for ocamldep *)
+ | "keep-docs" -> set "keep-docs" [ Clflags.keep_docs ] v
+ | "keep-locs" -> set "keep-locs" [ Clflags.keep_locs ] v
+
+ | "compact" -> clear "compact" [ optimize_for_speed ] v
+ | "no-app-funct" -> clear "no-app-funct" [ applicative_functors ] v
+ | "nodynlink" -> clear "nodynlink" [ dlcode ] v
+ | "short-paths" -> clear "short-paths" [ real_paths ] v
+ | "trans-mod" -> set "trans-mod" [ transparent_modules ] v
+
+ | "pp" -> preprocessor := Some v
+ | "runtime-variant" -> runtime_variant := v
+ | "cc" -> c_compiler := Some v
+
+ (* assembly sources *)
+ | "s" ->
+ set "s" [ Clflags.keep_asm_file ; Clflags.keep_startup_file ] v
+ | "S" -> set "S" [ Clflags.keep_asm_file ] v
+ | "dstartup" -> set "dstartup" [ Clflags.keep_startup_file ] v
+
+ (* warn-errors *)
+ | "we" | "warn-error" -> Warnings.parse_options true v
+ (* warnings *)
+ | "w" -> Warnings.parse_options false v
+ (* warn-errors *)
+ | "wwe" -> Warnings.parse_options false v
+
+ (* inlining *)
+ | "inline" -> begin try
+ inline_threshold := 8 * int_of_string v
+ with _ ->
+ Location.print_warning Location.none ppf
+ (Warnings.Bad_env_variable ("OCAMLPARAM",
+ "non-integer parameter for \"inline\""))
+ end
+
+ (* color output *)
+ | "color" ->
+ begin match parse_color_setting v with
+ | None ->
+ Location.print_warning Location.none ppf
+ (Warnings.Bad_env_variable ("OCAMLPARAM",
+ "bad value for \"color\", \
+ (expected \"auto\", \"always\" or \"never\")"))
+ | Some setting -> color := setting
+ end
+
+ | "intf-suffix" -> Config.interface_suffix := v
+
+ | "I" -> begin
+ match position with
+ | Before_args -> first_include_dirs := v :: !first_include_dirs
+ | Before_link | Before_compile ->
+ last_include_dirs := v :: !last_include_dirs
+ end
+
+ | "cclib" ->
+ begin
+ match position with
+ | Before_compile -> ()
+ | Before_link | Before_args ->
+ ccobjs := Misc.rev_split_words v @ !ccobjs
+ end
+
+ | "ccopts" ->
+ begin
+ match position with
+ | Before_link | Before_compile ->
+ last_ccopts := v :: !last_ccopts
+ | Before_args ->
+ first_ccopts := v :: !first_ccopts
+ end
+
+ | "ppx" ->
+ begin
+ match position with
+ | Before_link | Before_compile ->
+ last_ppx := v :: !last_ppx
+ | Before_args ->
+ first_ppx := v :: !first_ppx
+ end
+
+
+ | "cmo" | "cma" ->
+ if not !native_code then
+ begin
+ match position with
+ | Before_link | Before_compile ->
+ last_objfiles := v ::! last_objfiles
+ | Before_args ->
+ first_objfiles := v :: !first_objfiles
+ end
+
+ | "cmx" | "cmxa" ->
+ if !native_code then
+ begin
+ match position with
+ | Before_link | Before_compile ->
+ last_objfiles := v ::! last_objfiles
+ | Before_args ->
+ first_objfiles := v :: !first_objfiles
+ end
+
+ | "pic" ->
+ if !native_code then
+ set "pic" [ pic_code ] v
+
+ | "can-discard" ->
+ can_discard := v ::!can_discard
+
+ | _ ->
+ if not (List.mem name !can_discard) then begin
+ can_discard := name :: !can_discard;
+ Printf.eprintf
+ "Warning: discarding value of variable %S in OCAMLPARAM\n%!"
+ name
+ end
+ ) (match position with
+ Before_args -> before
+ | Before_compile | Before_link -> after)
+ with Not_found -> ()
+
+let readenv ppf position =
+ last_include_dirs := [];
+ last_ccopts := [];
+ last_ppx := [];
+ last_objfiles := [];
+ read_OCAMLPARAM ppf position;
+ all_ccopts := !last_ccopts @ !first_ccopts;
+ all_ppx := !last_ppx @ !first_ppx
+
+let get_objfiles () =
+ List.rev (!last_objfiles @ !objfiles @ !first_objfiles)
diff --git a/driver/compenv.mli b/driver/compenv.mli
new file mode 100644
index 0000000000..59cd10124f
--- /dev/null
+++ b/driver/compenv.mli
@@ -0,0 +1,43 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, EPI Gallium, INRIA Paris-Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val module_of_filename : Format.formatter -> string -> string -> string
+
+val output_prefix : string -> string
+val extract_output : string option -> string
+val default_output : string option -> string
+
+val print_version_and_library : string -> 'a
+val print_version_string : unit -> 'a
+val print_standard_library : unit -> 'a
+val fatal : string -> 'a
+
+val first_ccopts : string list ref
+val first_ppx : string list ref
+val first_include_dirs : string list ref
+val last_include_dirs : string list ref
+val implicit_modules : string list ref
+
+(* return the list of objfiles, after OCAMLPARAM and List.rev *)
+val get_objfiles : unit -> string list
+
+type readenv_position =
+ Before_args | Before_compile | Before_link
+
+val readenv : Format.formatter -> readenv_position -> unit
+
+(* [is_unit_name name] returns true only if [name] can be used as a
+ correct module name *)
+val is_unit_name : string -> bool
+(* [check_unit_name ppf filename name] prints a warning in [filename]
+ on [ppf] if [name] should not be used as a module name. *)
+val check_unit_name : Format.formatter -> string -> string -> unit
diff --git a/driver/compile.ml b/driver/compile.ml
new file mode 100644
index 0000000000..b18e611a00
--- /dev/null
+++ b/driver/compile.ml
@@ -0,0 +1,104 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The batch compiler *)
+
+open Misc
+open Format
+open Typedtree
+open Compenv
+
+(* Compile a .mli file *)
+
+(* Keep in sync with the copy in optcompile.ml *)
+
+let tool_name = "ocamlc"
+
+let interface ppf sourcefile outputprefix =
+ Compmisc.init_path false;
+ let modulename = module_of_filename ppf sourcefile outputprefix in
+ Env.set_unit_name modulename;
+ let initial_env = Compmisc.initial_env () in
+ let ast = Pparse.parse_interface ~tool_name ppf sourcefile in
+ if !Clflags.dump_parsetree then fprintf ppf "%a@." Printast.interface ast;
+ if !Clflags.dump_source then fprintf ppf "%a@." Pprintast.signature ast;
+ let tsg = Typemod.type_interface initial_env ast in
+ if !Clflags.dump_typedtree then fprintf ppf "%a@." Printtyped.interface tsg;
+ let sg = tsg.sig_type in
+ if !Clflags.print_types then
+ Printtyp.wrap_printing_env initial_env (fun () ->
+ fprintf std_formatter "%a@."
+ Printtyp.signature (Typemod.simplify_signature sg));
+ ignore (Includemod.signatures initial_env sg sg);
+ Typecore.force_delayed_checks ();
+ Warnings.check_fatal ();
+ if not !Clflags.print_types then begin
+ let sg = Env.save_signature sg modulename (outputprefix ^ ".cmi") in
+ Typemod.save_signature modulename tsg outputprefix sourcefile
+ initial_env sg ;
+ end
+
+(* Compile a .ml file *)
+
+let print_if ppf flag printer arg =
+ if !flag then fprintf ppf "%a@." printer arg;
+ arg
+
+let (++) x f = f x
+
+let implementation ppf sourcefile outputprefix =
+ Compmisc.init_path false;
+ let modulename = module_of_filename ppf sourcefile outputprefix in
+ Env.set_unit_name modulename;
+ let env = Compmisc.initial_env() in
+ try
+ let (typedtree, coercion) =
+ Pparse.parse_implementation ~tool_name ppf sourcefile
+ ++ print_if ppf Clflags.dump_parsetree Printast.implementation
+ ++ print_if ppf Clflags.dump_source Pprintast.structure
+ ++ Typemod.type_implementation sourcefile outputprefix modulename env
+ ++ print_if ppf Clflags.dump_typedtree
+ Printtyped.implementation_with_coercion
+ in
+ if !Clflags.print_types then begin
+ Warnings.check_fatal ();
+ Stypes.dump (Some (outputprefix ^ ".annot"))
+ end else begin
+ let bytecode =
+ (typedtree, coercion)
+ ++ Translmod.transl_implementation modulename
+ ++ print_if ppf Clflags.dump_rawlambda Printlambda.lambda
+ ++ Simplif.simplify_lambda
+ ++ print_if ppf Clflags.dump_lambda Printlambda.lambda
+ ++ Bytegen.compile_implementation modulename
+ ++ print_if ppf Clflags.dump_instr Printinstr.instrlist
+ in
+ let objfile = outputprefix ^ ".cmo" in
+ let oc = open_out_bin objfile in
+ try
+ bytecode
+ ++ Emitcode.to_file oc modulename objfile;
+ Warnings.check_fatal ();
+ close_out oc;
+ Stypes.dump (Some (outputprefix ^ ".annot"))
+ with x ->
+ close_out oc;
+ remove_file objfile;
+ raise x
+ end
+ with x ->
+ Stypes.dump (Some (outputprefix ^ ".annot"));
+ raise x
+
+let c_file name =
+ Location.input_name := name;
+ if Ccomp.compile_file ~output_name:!Clflags.output_name name <> 0 then exit 2
diff --git a/driver/compile.mli b/driver/compile.mli
new file mode 100644
index 0000000000..00f9029a59
--- /dev/null
+++ b/driver/compile.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compile a .ml or .mli file *)
+
+open Format
+
+val interface: formatter -> string -> string -> unit
+val implementation: formatter -> string -> string -> unit
+val c_file: string -> unit
diff --git a/driver/compmisc.ml b/driver/compmisc.ml
new file mode 100644
index 0000000000..608683bbca
--- /dev/null
+++ b/driver/compmisc.ml
@@ -0,0 +1,60 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, EPI Gallium, INRIA Paris-Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Compenv
+
+(* Initialize the search path.
+ [dir] is always searched first (default: the current directory),
+ then the directories specified with the -I option (in command-line order),
+ then the standard library directory (unless the -nostdlib option is given).
+ *)
+
+let init_path ?(dir="") native =
+ let dirs =
+ if !Clflags.use_threads then "+threads" :: !Clflags.include_dirs
+ else if !Clflags.use_vmthreads && not native then
+ "+vmthreads" :: !Clflags.include_dirs
+ else
+ !last_include_dirs @
+ !Clflags.include_dirs @
+ !first_include_dirs
+ in
+ let exp_dirs =
+ List.map (Misc.expand_directory Config.standard_library) dirs in
+ Config.load_path := dir ::
+ List.rev_append exp_dirs (Clflags.std_include_dir ());
+ Env.reset_cache ()
+
+(* Return the initial environment in which compilation proceeds. *)
+
+(* Note: do not do init_path() in initial_env, this breaks
+ toplevel initialization (PR#1775) *)
+
+let open_implicit_module m env =
+ let open Asttypes in
+ let lid = {loc = Location.in_file "command line";
+ txt = Longident.Lident m } in
+ snd (Typemod.type_open_ Override env lid.loc lid)
+
+let initial_env () =
+ Ident.reinit();
+ let initial =
+ if !Clflags.unsafe_string then Env.initial_unsafe_string
+ else Env.initial_safe_string
+ in
+ let env =
+ if !Clflags.nopervasives then initial else
+ open_implicit_module "Pervasives" initial
+ in
+ List.fold_left (fun env m ->
+ open_implicit_module m env
+ ) env (!implicit_modules @ List.rev !Clflags.open_modules)
diff --git a/driver/compmisc.mli b/driver/compmisc.mli
new file mode 100644
index 0000000000..3087d544d2
--- /dev/null
+++ b/driver/compmisc.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, EPI Gallium, INRIA Paris-Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val init_path : ?dir:string -> bool -> unit
+val initial_env : unit -> Env.t
diff --git a/driver/errors.ml b/driver/errors.ml
new file mode 100644
index 0000000000..bda1a30ac8
--- /dev/null
+++ b/driver/errors.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* This module should be removed. We keep it for now, to avoid
+ breaking external tools depending on it. *)
+
+let report_error = Location.report_exception
diff --git a/driver/errors.mli b/driver/errors.mli
new file mode 100644
index 0000000000..c9f1ee95bb
--- /dev/null
+++ b/driver/errors.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Error report *)
+open Format
+
+val report_error: formatter -> exn -> unit
diff --git a/driver/main.ml b/driver/main.ml
new file mode 100644
index 0000000000..9421efaf6d
--- /dev/null
+++ b/driver/main.ml
@@ -0,0 +1,205 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Config
+open Clflags
+open Compenv
+
+let process_interface_file ppf name =
+ let opref = output_prefix name in
+ Compile.interface ppf name opref;
+ if !make_package then objfiles := (opref ^ ".cmi") :: !objfiles
+
+let process_implementation_file ppf name =
+ let opref = output_prefix name in
+ Compile.implementation ppf name opref;
+ objfiles := (opref ^ ".cmo") :: !objfiles
+
+let process_file ppf name =
+ if Filename.check_suffix name ".ml"
+ || Filename.check_suffix name ".mlt" then
+ process_implementation_file ppf name
+ else if Filename.check_suffix name !Config.interface_suffix then
+ process_interface_file ppf name
+ else if Filename.check_suffix name ".cmo"
+ || Filename.check_suffix name ".cma" then
+ objfiles := name :: !objfiles
+ else if Filename.check_suffix name ".cmi" && !make_package then
+ objfiles := name :: !objfiles
+ else if Filename.check_suffix name ext_obj
+ || Filename.check_suffix name ext_lib then
+ ccobjs := name :: !ccobjs
+ else if Filename.check_suffix name ext_dll then
+ dllibs := name :: !dllibs
+ else if Filename.check_suffix name ".c" then begin
+ Compile.c_file name;
+ ccobjs := (Filename.chop_suffix (Filename.basename name) ".c" ^ ext_obj)
+ :: !ccobjs
+ end
+ else
+ raise(Arg.Bad("don't know what to do with " ^ name))
+
+let usage = "Usage: ocamlc <options> <files>\nOptions are:"
+
+let ppf = Format.err_formatter
+
+(* Error messages to standard error formatter *)
+let anonymous filename =
+ readenv ppf Before_compile; process_file ppf filename;;
+let impl filename =
+ readenv ppf Before_compile; process_implementation_file ppf filename;;
+let intf filename =
+ readenv ppf Before_compile; process_interface_file ppf filename;;
+
+let show_config () =
+ Config.print_config stdout;
+ exit 0;
+;;
+
+module Options = Main_args.Make_bytecomp_options (struct
+ let set r () = r := true
+ let unset r () = r := false
+ let _a = set make_archive
+ let _absname = set Location.absname
+ let _annot = set annotations
+ let _binannot = set binary_annotations
+ let _c = set compile_only
+ let _cc s = c_compiler := Some s
+ let _cclib s = ccobjs := Misc.rev_split_words s @ !ccobjs
+ let _ccopt s = first_ccopts := s :: !first_ccopts
+ let _compat_32 = set bytecode_compatible_32
+ let _config = show_config
+ let _custom = set custom_runtime
+ let _no_check_prims = set no_check_prims
+ let _dllib s = dllibs := Misc.rev_split_words s @ !dllibs
+ let _dllpath s = dllpaths := !dllpaths @ [s]
+ let _for_pack s = for_package := Some s
+ let _g = set debug
+ let _i () = print_types := true; compile_only := true
+ let _I s = include_dirs := s :: !include_dirs
+ let _impl = impl
+ let _intf = intf
+ let _intf_suffix s = Config.interface_suffix := s
+ let _keep_docs = set keep_docs
+ let _keep_locs = set keep_locs
+ let _labels = unset classic
+ let _linkall = set link_everything
+ let _make_runtime () =
+ custom_runtime := true; make_runtime := true; link_everything := true
+ let _no_alias_deps = set transparent_modules
+ let _no_app_funct = unset applicative_functors
+ let _noassert = set noassert
+ let _nolabels = set classic
+ let _noautolink = set no_auto_link
+ let _nostdlib = set no_std_include
+ let _o s = output_name := Some s
+ let _open s = open_modules := s :: !open_modules
+ let _output_obj () = output_c_object := true; custom_runtime := true
+ let _output_complete_obj () =
+ output_c_object := true;
+ output_complete_object := true;
+ custom_runtime := true
+ let _pack = set make_package
+ let _pp s = preprocessor := Some s
+ let _ppx s = first_ppx := s :: !first_ppx
+ let _principal = set principal
+ let _rectypes = set recursive_types
+ let _runtime_variant s = runtime_variant := s
+ let _safe_string = unset unsafe_string
+ let _short_paths = unset real_paths
+ let _strict_sequence = set strict_sequence
+ let _strict_formats = set strict_formats
+ let _thread = set use_threads
+ let _vmthread = set use_vmthreads
+ let _unsafe = set fast
+ let _unsafe_string = set unsafe_string
+ let _use_prims s = use_prims := s
+ let _use_runtime s = use_runtime := s
+ let _v () = print_version_and_library "compiler"
+ let _version = print_version_string
+ let _vnum = print_version_string
+ let _w = (Warnings.parse_options false)
+ let _warn_error = (Warnings.parse_options true)
+ let _warn_help = Warnings.help_warnings
+ let _color option =
+ begin match Clflags.parse_color_setting option with
+ | None -> ()
+ | Some setting -> Clflags.color := setting
+ end
+ let _where = print_standard_library
+ let _verbose = set verbose
+ let _nopervasives = set nopervasives
+ let _dsource = set dump_source
+ let _dparsetree = set dump_parsetree
+ let _dtypedtree = set dump_typedtree
+ let _drawlambda = set dump_rawlambda
+ let _dlambda = set dump_lambda
+ let _dinstr = set dump_instr
+ let anonymous = anonymous
+end)
+
+let main () =
+ try
+ readenv ppf Before_args;
+ Arg.parse Options.list anonymous usage;
+ readenv ppf Before_link;
+ if
+ List.length (List.filter (fun x -> !x)
+ [make_archive;make_package;compile_only;output_c_object])
+ > 1
+ then
+ if !print_types then
+ fatal "Option -i is incompatible with -pack, -a, -output-obj"
+ else
+ fatal "Please specify at most one of -pack, -a, -c, -output-obj";
+ if !make_archive then begin
+ Compmisc.init_path false;
+
+ Bytelibrarian.create_archive ppf (Compenv.get_objfiles ())
+ (extract_output !output_name);
+ Warnings.check_fatal ();
+ end
+ else if !make_package then begin
+ Compmisc.init_path false;
+ let extracted_output = extract_output !output_name in
+ let revd = get_objfiles () in
+ Bytepackager.package_files ppf (Compmisc.initial_env ())
+ revd (extracted_output);
+ Warnings.check_fatal ();
+ end
+ else if not !compile_only && !objfiles <> [] then begin
+ let target =
+ if !output_c_object then
+ let s = extract_output !output_name in
+ if (Filename.check_suffix s Config.ext_obj
+ || Filename.check_suffix s Config.ext_dll
+ || Filename.check_suffix s ".c")
+ then s
+ else
+ fatal
+ (Printf.sprintf
+ "The extension of the output file must be .c, %s or %s"
+ Config.ext_obj Config.ext_dll
+ )
+ else
+ default_output !output_name
+ in
+ Compmisc.init_path false;
+ Bytelink.link ppf (get_objfiles ()) target;
+ Warnings.check_fatal ();
+ end;
+ exit 0
+ with x ->
+ Location.report_exception ppf x;
+ exit 2
+
+let _ = main ()
diff --git a/driver/main.mli b/driver/main.mli
new file mode 100644
index 0000000000..b2176ff92f
--- /dev/null
+++ b/driver/main.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*
+ this "empty" file is here to speed up garbage collection in ocamlc.opt
+*)
diff --git a/driver/main_args.ml b/driver/main_args.ml
new file mode 100644
index 0000000000..b44941f9f7
--- /dev/null
+++ b/driver/main_args.ml
@@ -0,0 +1,976 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let mk_a f =
+ "-a", Arg.Unit f, " Build a library"
+;;
+
+let mk_absname f =
+ "-absname", Arg.Unit f, " Show absolute filenames in error messages"
+;;
+
+let mk_annot f =
+ "-annot", Arg.Unit f, " Save information in <filename>.annot"
+;;
+
+let mk_binannot f =
+ "-bin-annot", Arg.Unit f, " Save typedtree in <filename>.cmt"
+;;
+
+let mk_c f =
+ "-c", Arg.Unit f, " Compile only (do not link)"
+;;
+
+let mk_cc f =
+ "-cc", Arg.String f, "<command> Use <command> as the C compiler and linker"
+;;
+
+let mk_cclib f =
+ "-cclib", Arg.String f, "<opt> Pass option <opt> to the C linker"
+;;
+
+let mk_ccopt f =
+ "-ccopt", Arg.String f,
+ "<opt> Pass option <opt> to the C compiler and linker"
+;;
+
+let mk_compact f =
+ "-compact", Arg.Unit f, " Optimize code size rather than speed"
+;;
+
+let mk_compat_32 f =
+ "-compat-32", Arg.Unit f,
+ " Check that generated bytecode can run on 32-bit platforms"
+;;
+
+let mk_config f =
+ "-config", Arg.Unit f, " Print configuration values and exit"
+;;
+
+let mk_custom f =
+ "-custom", Arg.Unit f, " Link in custom mode"
+;;
+
+let mk_dllib f =
+ "-dllib", Arg.String f, "<lib> Use the dynamically-loaded library <lib>"
+;;
+
+let mk_dllpath f =
+ "-dllpath", Arg.String f,
+ "<dir> Add <dir> to the run-time search path for shared libraries"
+;;
+
+let mk_dtypes f =
+ "-dtypes", Arg.Unit f, " (deprecated) same as -annot"
+;;
+
+let mk_for_pack_byt f =
+ "-for-pack", Arg.String f,
+ "<ident> Generate code that can later be `packed' with\n\
+ \ ocamlc -pack -o <ident>.cmo"
+;;
+
+let mk_for_pack_opt f =
+ "-for-pack", Arg.String f,
+ "<ident> Generate code that can later be `packed' with\n\
+ \ ocamlopt -pack -o <ident>.cmx"
+;;
+
+let mk_g_byt f =
+ "-g", Arg.Unit f, " Save debugging information"
+;;
+
+let mk_g_opt f =
+ "-g", Arg.Unit f, " Record debugging information for exception backtrace"
+;;
+
+let mk_i f =
+ "-i", Arg.Unit f, " Print inferred interface"
+;;
+
+let mk_I f =
+ "-I", Arg.String f, "<dir> Add <dir> to the list of include directories"
+;;
+
+let mk_impl f =
+ "-impl", Arg.String f, "<file> Compile <file> as a .ml file"
+;;
+
+let mk_init f =
+ "-init", Arg.String f, "<file> Load <file> instead of default init file"
+;;
+
+let mk_inline f =
+ "-inline", Arg.Int f, "<n> Set aggressiveness of inlining to <n>"
+;;
+
+let mk_intf f =
+ "-intf", Arg.String f, "<file> Compile <file> as a .mli file"
+;;
+
+let mk_intf_suffix f =
+ "-intf-suffix", Arg.String f,
+ "<string> Suffix for interface files (default: .mli)"
+;;
+
+let mk_intf_suffix_2 f =
+ "-intf_suffix", Arg.String f, "<string> (deprecated) same as -intf-suffix"
+;;
+
+let mk_keep_docs f =
+ "-keep-docs", Arg.Unit f, " Keep documentation strings in .cmi files"
+;;
+
+let mk_keep_locs f =
+ "-keep-locs", Arg.Unit f, " Keep locations in .cmi files"
+;;
+
+let mk_labels f =
+ "-labels", Arg.Unit f, " Use commuting label mode"
+;;
+
+let mk_linkall f =
+ "-linkall", Arg.Unit f, " Link all modules, even unused ones"
+;;
+
+let mk_make_runtime f =
+ "-make-runtime", Arg.Unit f,
+ " Build a runtime system with given C objects and libraries"
+;;
+
+let mk_make_runtime_2 f =
+ "-make_runtime", Arg.Unit f, " (deprecated) same as -make-runtime"
+;;
+
+let mk_modern f =
+ "-modern", Arg.Unit f, " (deprecated) same as -labels"
+;;
+
+let mk_no_alias_deps f =
+ "-no-alias-deps", Arg.Unit f,
+ " Do not record dependencies for module aliases"
+;;
+
+let mk_no_app_funct f =
+ "-no-app-funct", Arg.Unit f, " Deactivate applicative functors"
+;;
+
+let mk_no_check_prims f =
+ "-no-check-prims", Arg.Unit f, " Do not check runtime for primitives"
+;;
+
+let mk_no_float_const_prop f =
+ "-no-float-const-prop", Arg.Unit f,
+ " Deactivate constant propagation for floating-point operations"
+;;
+
+let mk_noassert f =
+ "-noassert", Arg.Unit f, " Do not compile assertion checks"
+;;
+
+let mk_noautolink_byt f =
+ "-noautolink", Arg.Unit f,
+ " Do not automatically link C libraries specified in .cma files"
+;;
+
+let mk_noautolink_opt f =
+ "-noautolink", Arg.Unit f,
+ " Do not automatically link C libraries specified in .cmxa files"
+;;
+
+let mk_nodynlink f =
+ "-nodynlink", Arg.Unit f,
+ " Enable optimizations for code that will not be dynlinked"
+;;
+
+let mk_noinit f =
+ "-noinit", Arg.Unit f,
+ " Do not load any init file"
+
+let mk_nolabels f =
+ "-nolabels", Arg.Unit f, " Ignore non-optional labels in types"
+;;
+
+let mk_noprompt f =
+ "-noprompt", Arg.Unit f, " Suppress all prompts"
+;;
+
+let mk_nopromptcont f =
+ "-nopromptcont", Arg.Unit f,
+ " Suppress prompts for continuation lines of multi-line inputs"
+;;
+
+let mk_nostdlib f =
+ "-nostdlib", Arg.Unit f,
+ " Do not add default directory to the list of include directories"
+;;
+
+let mk_o f =
+ "-o", Arg.String f, "<file> Set output file name to <file>"
+;;
+
+let mk_open f =
+ "-open", Arg.String f, "<module> Opens the module <module> before typing"
+
+let mk_output_obj f =
+ "-output-obj", Arg.Unit f, " Output an object file instead of an executable"
+;;
+
+let mk_output_complete_obj f =
+ "-output-complete-obj", Arg.Unit f,
+ " Output an object file, including runtime, instead of an executable"
+;;
+
+let mk_p f =
+ "-p", Arg.Unit f,
+ " Compile and link with profiling support for \"gprof\"\n\
+ \ (not supported on all platforms)"
+;;
+
+let mk_pack_byt f =
+ "-pack", Arg.Unit f, " Package the given .cmo files into one .cmo"
+;;
+
+let mk_pack_opt f =
+ "-pack", Arg.Unit f, " Package the given .cmx files into one .cmx"
+;;
+
+let mk_pp f =
+ "-pp", Arg.String f, "<command> Pipe sources through preprocessor <command>"
+;;
+
+let mk_ppx f =
+ "-ppx", Arg.String f,
+ "<command> Pipe abstract syntax trees through preprocessor <command>"
+;;
+
+let mk_principal f =
+ "-principal", Arg.Unit f, " Check principality of type inference"
+;;
+
+let mk_rectypes f =
+ "-rectypes", Arg.Unit f, " Allow arbitrary recursive types"
+;;
+
+let mk_runtime_variant f =
+ "-runtime-variant", Arg.String f,
+ "<str> Use the <str> variant of the run-time system"
+;;
+
+let mk_S f =
+ "-S", Arg.Unit f, " Keep intermediate assembly file"
+;;
+
+let mk_safe_string f =
+ "-safe-string", Arg.Unit f, " Make strings immutable"
+;;
+
+let mk_shared f =
+ "-shared", Arg.Unit f, " Produce a dynlinkable plugin"
+;;
+
+let mk_short_paths f =
+ "-short-paths", Arg.Unit f, " Shorten paths in types"
+;;
+
+let mk_stdin f =
+ "-stdin", Arg.Unit f, " Read script from standard input"
+;;
+
+let mk_strict_sequence f =
+ "-strict-sequence", Arg.Unit f,
+ " Left-hand part of a sequence must have type unit"
+;;
+
+let mk_thread f =
+ "-thread", Arg.Unit f,
+ " Generate code that supports the system threads library"
+;;
+
+let mk_unsafe f =
+ "-unsafe", Arg.Unit f,
+ " Do not compile bounds checking on array and string access"
+;;
+
+let mk_unsafe_string f =
+ "-unsafe-string", Arg.Unit f, " Make strings mutable (default)"
+;;
+
+let mk_use_runtime f =
+ "-use-runtime", Arg.String f,
+ "<file> Generate bytecode for the given runtime system"
+;;
+
+let mk_use_runtime_2 f =
+ "-use_runtime", Arg.String f,
+ "<file> (deprecated) same as -use-runtime"
+;;
+
+let mk_v f =
+ "-v", Arg.Unit f,
+ " Print compiler version and location of standard library and exit"
+;;
+
+let mk_verbose f =
+ "-verbose", Arg.Unit f, " Print calls to external commands"
+;;
+
+let mk_version f =
+ "-version", Arg.Unit f, " Print version and exit"
+;;
+
+let mk__version f =
+ "--version", Arg.Unit f, " Print version and exit"
+;;
+
+let mk_vmthread f =
+ "-vmthread", Arg.Unit f,
+ " Generate code that supports the threads library with VM-level\n\
+ \ scheduling"
+;;
+
+let mk_vnum f =
+ "-vnum", Arg.Unit f, " Print version number and exit"
+;;
+
+let mk_w f =
+ "-w", Arg.String f,
+ Printf.sprintf
+ "<list> Enable or disable warnings according to <list>:\n\
+ \ +<spec> enable warnings in <spec>\n\
+ \ -<spec> disable warnings in <spec>\n\
+ \ @<spec> enable warnings in <spec> and treat them as errors\n\
+ \ <spec> can be:\n\
+ \ <num> a single warning number\n\
+ \ <num1>..<num2> a range of consecutive warning numbers\n\
+ \ <letter> a predefined set\n\
+ \ default setting is %S" Warnings.defaults_w
+;;
+
+let mk_warn_error f =
+ "-warn-error", Arg.String f,
+ Printf.sprintf
+ "<list> Enable or disable error status for warnings according\n\
+ \ to <list>. See option -w for the syntax of <list>.\n\
+ \ Default setting is %S" Warnings.defaults_warn_error
+;;
+
+let mk_warn_help f =
+ "-warn-help", Arg.Unit f, " Show description of warning numbers"
+;;
+
+let mk_color f =
+ "-color", Arg.Symbol (["auto"; "always"; "never"], f),
+ Printf.sprintf
+ " Enable or disable colors in compiler messages\n\
+ \ The following settings are supported:\n\
+ \ auto use heuristics to enable colors only if supported\n\
+ \ always enable colors\n\
+ \ never disable colors\n\
+ \ The default setting is 'auto', and the current heuristic\n\
+ \ checks that the TERM environment variable exists and is\n\
+ \ not empty or \"dumb\", and that isatty(stderr) holds."
+;;
+
+let mk_where f =
+ "-where", Arg.Unit f, " Print location of standard library and exit"
+;;
+
+let mk_nopervasives f =
+ "-nopervasives", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_use_prims f =
+ "-use-prims", Arg.String f, "<file> (undocumented)"
+;;
+
+let mk_dparsetree f =
+ "-dparsetree", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dtypedtree f =
+ "-dtypedtree", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_drawlambda f =
+ "-drawlambda", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dsource f =
+ "-dsource", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dlambda f =
+ "-dlambda", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dclambda f =
+ "-dclambda", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dinstr f =
+ "-dinstr", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dcmm f =
+ "-dcmm", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dsel f =
+ "-dsel", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dcombine f =
+ "-dcombine", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dcse f =
+ "-dcse", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dlive f =
+ "-dlive", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dspill f =
+ "-dspill", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dsplit f =
+ "-dsplit", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dinterf f =
+ "-dinterf", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dprefer f =
+ "-dprefer", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dalloc f =
+ "-dalloc", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dreload f =
+ "-dreload", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dscheduling f =
+ "-dscheduling", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dlinear f =
+ "-dlinear", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_dstartup f =
+ "-dstartup", Arg.Unit f, " (undocumented)"
+;;
+
+let mk_opaque f =
+ "-opaque", Arg.Unit f,
+ " Does not generate cross-module optimization information\n\
+ \ (reduces necessary recompilation on module change)"
+;;
+
+let mk_strict_formats f =
+ "-strict-formats", Arg.Unit f,
+ " Reject invalid formats accepted by legacy implementations\n\
+ \ (Warning: Invalid formats may behave differently from\n\
+ \ previous OCaml versions, and will become always-rejected\n\
+ \ in future OCaml versions. You should use this flag\n\
+ \ to detect and fix invalid formats.)"
+;;
+
+let mk__ f =
+ "-", Arg.String f,
+ "<file> Treat <file> as a file name (even if it starts with `-')"
+;;
+
+module type Common_options = sig
+ val _absname : unit -> unit
+ val _I : string -> unit
+ val _labels : unit -> unit
+ val _no_alias_deps : unit -> unit
+ val _no_app_funct : unit -> unit
+ val _noassert : unit -> unit
+ val _nolabels : unit -> unit
+ val _nostdlib : unit -> unit
+ val _open : string -> unit
+ val _ppx : string -> unit
+ val _principal : unit -> unit
+ val _rectypes : unit -> unit
+ val _safe_string : unit -> unit
+ val _short_paths : unit -> unit
+ val _strict_sequence : unit -> unit
+ val _strict_formats : unit -> unit
+ val _unsafe : unit -> unit
+ val _unsafe_string : unit -> unit
+ val _version : unit -> unit
+ val _vnum : unit -> unit
+ val _w : string -> unit
+ val _warn_error : string -> unit
+ val _warn_help : unit -> unit
+
+ val _dsource : unit -> unit
+ val _dparsetree : unit -> unit
+ val _dtypedtree : unit -> unit
+ val _drawlambda : unit -> unit
+ val _dlambda : unit -> unit
+
+ val anonymous : string -> unit
+end;;
+
+module type Compiler_options = sig
+ val _a : unit -> unit
+ val _annot : unit -> unit
+ val _binannot : unit -> unit
+ val _c : unit -> unit
+ val _cc : string -> unit
+ val _cclib : string -> unit
+ val _ccopt : string -> unit
+ val _config : unit -> unit
+ val _for_pack : string -> unit
+ val _g : unit -> unit
+ val _i : unit -> unit
+ val _impl : string -> unit
+ val _intf : string -> unit
+ val _intf_suffix : string -> unit
+ val _keep_docs : unit -> unit
+ val _keep_locs : unit -> unit
+ val _linkall : unit -> unit
+ val _noautolink : unit -> unit
+ val _o : string -> unit
+ val _output_obj : unit -> unit
+ val _output_complete_obj : unit -> unit
+ val _pack : unit -> unit
+ val _pp : string -> unit
+ val _principal : unit -> unit
+ val _rectypes : unit -> unit
+ val _runtime_variant : string -> unit
+ val _safe_string : unit -> unit
+ val _short_paths : unit -> unit
+ val _thread : unit -> unit
+ val _v : unit -> unit
+ val _verbose : unit -> unit
+ val _where : unit -> unit
+ val _color : string -> unit
+
+ val _nopervasives : unit -> unit
+end
+;;
+
+module type Bytecomp_options = sig
+ include Common_options
+ include Compiler_options
+ val _compat_32 : unit -> unit
+ val _custom : unit -> unit
+ val _no_check_prims : unit -> unit
+ val _dllib : string -> unit
+ val _dllpath : string -> unit
+ val _make_runtime : unit -> unit
+ val _vmthread : unit -> unit
+ val _use_runtime : string -> unit
+
+ val _dinstr : unit -> unit
+
+ val _use_prims : string -> unit
+end;;
+
+module type Bytetop_options = sig
+ include Common_options
+ val _init : string -> unit
+ val _noinit : unit -> unit
+ val _noprompt : unit -> unit
+ val _nopromptcont : unit -> unit
+ val _stdin : unit -> unit
+
+ val _dinstr : unit -> unit
+end;;
+
+module type Optcommon_options = sig
+ val _compact : unit -> unit
+ val _inline : int -> unit
+
+ val _dclambda : unit -> unit
+ val _dcmm : unit -> unit
+ val _dsel : unit -> unit
+ val _dcombine : unit -> unit
+ val _dcse : unit -> unit
+ val _dlive : unit -> unit
+ val _dspill : unit -> unit
+ val _dsplit : unit -> unit
+ val _dinterf : unit -> unit
+ val _dprefer : unit -> unit
+ val _dalloc : unit -> unit
+ val _dreload : unit -> unit
+ val _dscheduling : unit -> unit
+ val _dlinear : unit -> unit
+ val _dstartup : unit -> unit
+end;;
+
+module type Optcomp_options = sig
+ include Common_options
+ include Compiler_options
+ include Optcommon_options
+ val _no_float_const_prop : unit -> unit
+ val _nodynlink : unit -> unit
+ val _p : unit -> unit
+ val _pp : string -> unit
+ val _S : unit -> unit
+ val _shared : unit -> unit
+ val _opaque : unit -> unit
+end;;
+
+module type Opttop_options = sig
+ include Common_options
+ include Optcommon_options
+ val _init : string -> unit
+ val _noinit : unit -> unit
+ val _noprompt : unit -> unit
+ val _nopromptcont : unit -> unit
+ val _S : unit -> unit
+ val _stdin : unit -> unit
+end;;
+
+module type Ocamldoc_options = sig
+ include Common_options
+ val _impl : string -> unit
+ val _intf : string -> unit
+ val _intf_suffix : string -> unit
+ val _pp : string -> unit
+ val _principal : unit -> unit
+ val _rectypes : unit -> unit
+ val _safe_string : unit -> unit
+ val _short_paths : unit -> unit
+ val _thread : unit -> unit
+ val _v : unit -> unit
+ val _verbose : unit -> unit
+ val _vmthread : unit -> unit
+end;;
+
+module type Arg_list = sig
+ val list : (string * Arg.spec * string) list
+end;;
+
+module Make_bytecomp_options (F : Bytecomp_options) =
+struct
+ let list = [
+ mk_a F._a;
+ mk_absname F._absname;
+ mk_annot F._annot;
+ mk_binannot F._binannot;
+ mk_c F._c;
+ mk_cc F._cc;
+ mk_cclib F._cclib;
+ mk_ccopt F._ccopt;
+ mk_color F._color;
+ mk_compat_32 F._compat_32;
+ mk_config F._config;
+ mk_custom F._custom;
+ mk_dllib F._dllib;
+ mk_dllpath F._dllpath;
+ mk_dtypes F._annot;
+ mk_for_pack_byt F._for_pack;
+ mk_g_byt F._g;
+ mk_i F._i;
+ mk_I F._I;
+ mk_impl F._impl;
+ mk_intf F._intf;
+ mk_intf_suffix F._intf_suffix;
+ mk_intf_suffix_2 F._intf_suffix;
+ mk_keep_docs F._keep_docs;
+ mk_keep_locs F._keep_locs;
+ mk_labels F._labels;
+ mk_linkall F._linkall;
+ mk_make_runtime F._make_runtime;
+ mk_make_runtime_2 F._make_runtime;
+ mk_modern F._labels;
+ mk_no_alias_deps F._no_alias_deps;
+ mk_no_app_funct F._no_app_funct;
+ mk_no_check_prims F._no_check_prims;
+ mk_noassert F._noassert;
+ mk_noautolink_byt F._noautolink;
+ mk_nolabels F._nolabels;
+ mk_nostdlib F._nostdlib;
+ mk_o F._o;
+ mk_open F._open;
+ mk_output_obj F._output_obj;
+ mk_output_complete_obj F._output_complete_obj;
+ mk_pack_byt F._pack;
+ mk_pp F._pp;
+ mk_ppx F._ppx;
+ mk_principal F._principal;
+ mk_rectypes F._rectypes;
+ mk_runtime_variant F._runtime_variant;
+ mk_safe_string F._safe_string;
+ mk_short_paths F._short_paths;
+ mk_strict_sequence F._strict_sequence;
+ mk_strict_formats F._strict_formats;
+ mk_thread F._thread;
+ mk_unsafe F._unsafe;
+ mk_unsafe_string F._unsafe_string;
+ mk_use_runtime F._use_runtime;
+ mk_use_runtime_2 F._use_runtime;
+ mk_v F._v;
+ mk_verbose F._verbose;
+ mk_version F._version;
+ mk__version F._version;
+ mk_vmthread F._vmthread;
+ mk_vnum F._vnum;
+ mk_w F._w;
+ mk_warn_error F._warn_error;
+ mk_warn_help F._warn_help;
+ mk_where F._where;
+ mk__ F.anonymous;
+
+ mk_nopervasives F._nopervasives;
+ mk_use_prims F._use_prims;
+ mk_dsource F._dsource;
+ mk_dparsetree F._dparsetree;
+ mk_dtypedtree F._dtypedtree;
+ mk_drawlambda F._drawlambda;
+ mk_dlambda F._dlambda;
+ mk_dinstr F._dinstr;
+ ]
+end;;
+
+module Make_bytetop_options (F : Bytetop_options) =
+struct
+ let list = [
+ mk_absname F._absname;
+ mk_I F._I;
+ mk_init F._init;
+ mk_labels F._labels;
+ mk_no_alias_deps F._no_alias_deps;
+ mk_no_app_funct F._no_app_funct;
+ mk_noassert F._noassert;
+ mk_noinit F._noinit;
+ mk_nolabels F._nolabels;
+ mk_noprompt F._noprompt;
+ mk_nopromptcont F._nopromptcont;
+ mk_nostdlib F._nostdlib;
+ mk_open F._open;
+ mk_ppx F._ppx;
+ mk_principal F._principal;
+ mk_rectypes F._rectypes;
+ mk_safe_string F._safe_string;
+ mk_short_paths F._short_paths;
+ mk_stdin F._stdin;
+ mk_strict_sequence F._strict_sequence;
+ mk_strict_formats F._strict_formats;
+ mk_unsafe F._unsafe;
+ mk_unsafe_string F._unsafe_string;
+ mk_version F._version;
+ mk__version F._version;
+ mk_vnum F._vnum;
+ mk_w F._w;
+ mk_warn_error F._warn_error;
+ mk_warn_help F._warn_help;
+ mk__ F.anonymous;
+
+ mk_dsource F._dsource;
+ mk_dparsetree F._dparsetree;
+ mk_dtypedtree F._dtypedtree;
+ mk_drawlambda F._drawlambda;
+ mk_dlambda F._dlambda;
+ mk_dinstr F._dinstr;
+ ]
+end;;
+
+module Make_optcomp_options (F : Optcomp_options) =
+struct
+ let list = [
+ mk_a F._a;
+ mk_absname F._absname;
+ mk_annot F._annot;
+ mk_binannot F._binannot;
+ mk_c F._c;
+ mk_cc F._cc;
+ mk_cclib F._cclib;
+ mk_ccopt F._ccopt;
+ mk_color F._color;
+ mk_compact F._compact;
+ mk_config F._config;
+ mk_dtypes F._annot;
+ mk_for_pack_opt F._for_pack;
+ mk_g_opt F._g;
+ mk_i F._i;
+ mk_I F._I;
+ mk_impl F._impl;
+ mk_inline F._inline;
+ mk_intf F._intf;
+ mk_intf_suffix F._intf_suffix;
+ mk_keep_docs F._keep_docs;
+ mk_keep_locs F._keep_locs;
+ mk_labels F._labels;
+ mk_linkall F._linkall;
+ mk_no_alias_deps F._no_alias_deps;
+ mk_no_app_funct F._no_app_funct;
+ mk_no_float_const_prop F._no_float_const_prop;
+ mk_noassert F._noassert;
+ mk_noautolink_opt F._noautolink;
+ mk_nodynlink F._nodynlink;
+ mk_nolabels F._nolabels;
+ mk_nostdlib F._nostdlib;
+ mk_o F._o;
+ mk_open F._open;
+ mk_output_obj F._output_obj;
+ mk_output_complete_obj F._output_complete_obj;
+ mk_p F._p;
+ mk_pack_opt F._pack;
+ mk_pp F._pp;
+ mk_ppx F._ppx;
+ mk_principal F._principal;
+ mk_rectypes F._rectypes;
+ mk_runtime_variant F._runtime_variant;
+ mk_S F._S;
+ mk_safe_string F._safe_string;
+ mk_shared F._shared;
+ mk_short_paths F._short_paths;
+ mk_strict_sequence F._strict_sequence;
+ mk_strict_formats F._strict_formats;
+ mk_thread F._thread;
+ mk_unsafe F._unsafe;
+ mk_unsafe_string F._unsafe_string;
+ mk_v F._v;
+ mk_verbose F._verbose;
+ mk_version F._version;
+ mk__version F._version;
+ mk_vnum F._vnum;
+ mk_w F._w;
+ mk_warn_error F._warn_error;
+ mk_warn_help F._warn_help;
+ mk_where F._where;
+ mk__ F.anonymous;
+
+ mk_nopervasives F._nopervasives;
+ mk_dsource F._dsource;
+ mk_dparsetree F._dparsetree;
+ mk_dtypedtree F._dtypedtree;
+ mk_drawlambda F._drawlambda;
+ mk_dlambda F._dlambda;
+ mk_dclambda F._dclambda;
+ mk_dcmm F._dcmm;
+ mk_dsel F._dsel;
+ mk_dcombine F._dcombine;
+ mk_dcse F._dcse;
+ mk_dlive F._dlive;
+ mk_dspill F._dspill;
+ mk_dsplit F._dsplit;
+ mk_dinterf F._dinterf;
+ mk_dprefer F._dprefer;
+ mk_dalloc F._dalloc;
+ mk_dreload F._dreload;
+ mk_dscheduling F._dscheduling;
+ mk_dlinear F._dlinear;
+ mk_dstartup F._dstartup;
+ mk_opaque F._opaque;
+ ]
+end;;
+
+module Make_opttop_options (F : Opttop_options) = struct
+ let list = [
+ mk_absname F._absname;
+ mk_compact F._compact;
+ mk_I F._I;
+ mk_init F._init;
+ mk_inline F._inline;
+ mk_labels F._labels;
+ mk_no_alias_deps F._no_alias_deps;
+ mk_no_app_funct F._no_app_funct;
+ mk_noassert F._noassert;
+ mk_noinit F._noinit;
+ mk_nolabels F._nolabels;
+ mk_noprompt F._noprompt;
+ mk_nopromptcont F._nopromptcont;
+ mk_nostdlib F._nostdlib;
+ mk_open F._open;
+ mk_ppx F._ppx;
+ mk_principal F._principal;
+ mk_rectypes F._rectypes;
+ mk_S F._S;
+ mk_safe_string F._safe_string;
+ mk_short_paths F._short_paths;
+ mk_stdin F._stdin;
+ mk_strict_sequence F._strict_sequence;
+ mk_strict_formats F._strict_formats;
+ mk_unsafe F._unsafe;
+ mk_unsafe_string F._unsafe_string;
+ mk_version F._version;
+ mk__version F._version;
+ mk_vnum F._vnum;
+ mk_w F._w;
+ mk_warn_error F._warn_error;
+ mk_warn_help F._warn_help;
+ mk__ F.anonymous;
+
+ mk_dsource F._dsource;
+ mk_dparsetree F._dparsetree;
+ mk_dtypedtree F._dtypedtree;
+ mk_drawlambda F._drawlambda;
+ mk_dclambda F._dclambda;
+ mk_dcmm F._dcmm;
+ mk_dsel F._dsel;
+ mk_dcombine F._dcombine;
+ mk_dcse F._dcse;
+ mk_dlive F._dlive;
+ mk_dspill F._dspill;
+ mk_dsplit F._dsplit;
+ mk_dinterf F._dinterf;
+ mk_dprefer F._dprefer;
+ mk_dalloc F._dalloc;
+ mk_dreload F._dreload;
+ mk_dscheduling F._dscheduling;
+ mk_dlinear F._dlinear;
+ mk_dstartup F._dstartup;
+ ]
+end;;
+
+module Make_ocamldoc_options (F : Ocamldoc_options) =
+struct
+ let list = [
+ mk_absname F._absname;
+ mk_I F._I;
+ mk_impl F._impl;
+ mk_intf F._intf;
+ mk_intf_suffix F._intf_suffix;
+ mk_intf_suffix_2 F._intf_suffix;
+ mk_labels F._labels;
+ mk_modern F._labels;
+ mk_no_alias_deps F._no_alias_deps;
+ mk_no_app_funct F._no_app_funct;
+ mk_noassert F._noassert;
+ mk_nolabels F._nolabels;
+ mk_nostdlib F._nostdlib;
+ mk_open F._open;
+ mk_pp F._pp;
+ mk_ppx F._ppx;
+ mk_principal F._principal;
+ mk_rectypes F._rectypes;
+ mk_safe_string F._safe_string;
+ mk_short_paths F._short_paths;
+ mk_strict_sequence F._strict_sequence;
+ mk_strict_formats F._strict_formats;
+ mk_thread F._thread;
+ mk_unsafe_string F._unsafe_string;
+ mk_v F._v;
+ mk_verbose F._verbose;
+ mk_version F._version;
+ mk__version F._version;
+ mk_vmthread F._vmthread;
+ mk_vnum F._vnum;
+ mk_w F._w;
+ mk__ F.anonymous;
+ ]
+end;;
diff --git a/driver/main_args.mli b/driver/main_args.mli
new file mode 100644
index 0000000000..04f0c6d713
--- /dev/null
+++ b/driver/main_args.mli
@@ -0,0 +1,186 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* ATTENTION ! When you add or modify a parsing or typing option, do not forget
+ to update ocamldoc options too, in odoc_args.ml. *)
+
+module type Common_options = sig
+ val _absname : unit -> unit
+ val _I : string -> unit
+ val _labels : unit -> unit
+ val _no_alias_deps : unit -> unit
+ val _no_app_funct : unit -> unit
+ val _noassert : unit -> unit
+ val _nolabels : unit -> unit
+ val _nostdlib : unit -> unit
+ val _open : string -> unit
+ val _ppx : string -> unit
+ val _principal : unit -> unit
+ val _rectypes : unit -> unit
+ val _safe_string : unit -> unit
+ val _short_paths : unit -> unit
+ val _strict_sequence : unit -> unit
+ val _strict_formats : unit -> unit
+ val _unsafe : unit -> unit
+ val _unsafe_string : unit -> unit
+ val _version : unit -> unit
+ val _vnum : unit -> unit
+ val _w : string -> unit
+ val _warn_error : string -> unit
+ val _warn_help : unit -> unit
+
+ val _dsource : unit -> unit
+ val _dparsetree : unit -> unit
+ val _dtypedtree : unit -> unit
+ val _drawlambda : unit -> unit
+ val _dlambda : unit -> unit
+
+ val anonymous : string -> unit
+end
+
+module type Compiler_options = sig
+ val _a : unit -> unit
+ val _annot : unit -> unit
+ val _binannot : unit -> unit
+ val _c : unit -> unit
+ val _cc : string -> unit
+ val _cclib : string -> unit
+ val _ccopt : string -> unit
+ val _config : unit -> unit
+ val _for_pack : string -> unit
+ val _g : unit -> unit
+ val _i : unit -> unit
+ val _impl : string -> unit
+ val _intf : string -> unit
+ val _intf_suffix : string -> unit
+ val _keep_docs : unit -> unit
+ val _keep_locs : unit -> unit
+ val _linkall : unit -> unit
+ val _noautolink : unit -> unit
+ val _o : string -> unit
+ val _output_obj : unit -> unit
+ val _output_complete_obj : unit -> unit
+ val _pack : unit -> unit
+ val _pp : string -> unit
+ val _principal : unit -> unit
+ val _rectypes : unit -> unit
+ val _runtime_variant : string -> unit
+ val _safe_string : unit -> unit
+ val _short_paths : unit -> unit
+ val _thread : unit -> unit
+ val _v : unit -> unit
+ val _verbose : unit -> unit
+ val _where : unit -> unit
+ val _color : string -> unit
+
+ val _nopervasives : unit -> unit
+end
+;;
+
+module type Bytecomp_options = sig
+ include Common_options
+ include Compiler_options
+ val _compat_32 : unit -> unit
+ val _custom : unit -> unit
+ val _no_check_prims : unit -> unit
+ val _dllib : string -> unit
+ val _dllpath : string -> unit
+ val _make_runtime : unit -> unit
+ val _vmthread : unit -> unit
+ val _use_runtime : string -> unit
+
+ val _dinstr : unit -> unit
+
+ val _use_prims : string -> unit
+end;;
+
+module type Bytetop_options = sig
+ include Common_options
+ val _init : string -> unit
+ val _noinit : unit -> unit
+ val _noprompt : unit -> unit
+ val _nopromptcont : unit -> unit
+ val _stdin : unit -> unit
+
+ val _dinstr : unit -> unit
+end;;
+
+module type Optcommon_options = sig
+ val _compact : unit -> unit
+ val _inline : int -> unit
+
+ val _dclambda : unit -> unit
+ val _dcmm : unit -> unit
+ val _dsel : unit -> unit
+ val _dcombine : unit -> unit
+ val _dcse : unit -> unit
+ val _dlive : unit -> unit
+ val _dspill : unit -> unit
+ val _dsplit : unit -> unit
+ val _dinterf : unit -> unit
+ val _dprefer : unit -> unit
+ val _dalloc : unit -> unit
+ val _dreload : unit -> unit
+ val _dscheduling : unit -> unit
+ val _dlinear : unit -> unit
+ val _dstartup : unit -> unit
+end;;
+
+module type Optcomp_options = sig
+ include Common_options
+ include Compiler_options
+ include Optcommon_options
+ val _no_float_const_prop : unit -> unit
+ val _nodynlink : unit -> unit
+ val _p : unit -> unit
+ val _pp : string -> unit
+ val _S : unit -> unit
+ val _shared : unit -> unit
+ val _opaque : unit -> unit
+end;;
+
+module type Opttop_options = sig
+ include Common_options
+ include Optcommon_options
+ val _init : string -> unit
+ val _noinit : unit -> unit
+ val _noprompt : unit -> unit
+ val _nopromptcont : unit -> unit
+ val _S : unit -> unit
+ val _stdin : unit -> unit
+end;;
+
+module type Ocamldoc_options = sig
+ include Common_options
+ val _impl : string -> unit
+ val _intf : string -> unit
+ val _intf_suffix : string -> unit
+ val _pp : string -> unit
+ val _principal : unit -> unit
+ val _rectypes : unit -> unit
+ val _safe_string : unit -> unit
+ val _short_paths : unit -> unit
+ val _thread : unit -> unit
+ val _v : unit -> unit
+ val _verbose : unit -> unit
+ val _vmthread : unit -> unit
+end
+
+module type Arg_list = sig
+ val list : (string * Arg.spec * string) list
+end;;
+
+module Make_bytecomp_options (F : Bytecomp_options) : Arg_list;;
+module Make_bytetop_options (F : Bytetop_options) : Arg_list;;
+module Make_optcomp_options (F : Optcomp_options) : Arg_list;;
+module Make_opttop_options (F : Opttop_options) : Arg_list;;
+module Make_ocamldoc_options (F : Ocamldoc_options) : Arg_list;;
diff --git a/driver/ocamlcomp.sh.in b/driver/ocamlcomp.sh.in
new file mode 100644
index 0000000000..fc0a8e113f
--- /dev/null
+++ b/driver/ocamlcomp.sh.in
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Jacques Garrigue, Kyoto University RIMS #
+# #
+# Copyright 2002 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+topdir=`dirname $0`
+
+exec @compiler@ -nostdlib -I $topdir/stdlib "$@"
diff --git a/driver/optcompile.ml b/driver/optcompile.ml
new file mode 100644
index 0000000000..b4265c0bff
--- /dev/null
+++ b/driver/optcompile.ml
@@ -0,0 +1,98 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The batch compiler *)
+
+open Misc
+open Config
+open Format
+open Typedtree
+open Compenv
+
+(* Compile a .mli file *)
+
+(* Keep in sync with the copy in compile.ml *)
+
+let tool_name = "ocamlopt"
+
+let interface ppf sourcefile outputprefix =
+ Compmisc.init_path false;
+ let modulename = module_of_filename ppf sourcefile outputprefix in
+ Env.set_unit_name modulename;
+ let initial_env = Compmisc.initial_env () in
+ let ast = Pparse.parse_interface ~tool_name ppf sourcefile in
+ if !Clflags.dump_parsetree then fprintf ppf "%a@." Printast.interface ast;
+ if !Clflags.dump_source then fprintf ppf "%a@." Pprintast.signature ast;
+ let tsg = Typemod.type_interface initial_env ast in
+ if !Clflags.dump_typedtree then fprintf ppf "%a@." Printtyped.interface tsg;
+ let sg = tsg.sig_type in
+ if !Clflags.print_types then
+ Printtyp.wrap_printing_env initial_env (fun () ->
+ fprintf std_formatter "%a@."
+ Printtyp.signature (Typemod.simplify_signature sg));
+ ignore (Includemod.signatures initial_env sg sg);
+ Typecore.force_delayed_checks ();
+ Warnings.check_fatal ();
+ if not !Clflags.print_types then begin
+ let sg = Env.save_signature sg modulename (outputprefix ^ ".cmi") in
+ Typemod.save_signature modulename tsg outputprefix sourcefile
+ initial_env sg ;
+ end
+
+(* Compile a .ml file *)
+
+let print_if ppf flag printer arg =
+ if !flag then fprintf ppf "%a@." printer arg;
+ arg
+
+let (++) x f = f x
+let (+++) (x, y) f = (x, f y)
+
+let implementation ppf sourcefile outputprefix =
+ Compmisc.init_path true;
+ let modulename = module_of_filename ppf sourcefile outputprefix in
+ Env.set_unit_name modulename;
+ let env = Compmisc.initial_env() in
+ Compilenv.reset ?packname:!Clflags.for_package modulename;
+ let cmxfile = outputprefix ^ ".cmx" in
+ let objfile = outputprefix ^ ext_obj in
+ let comp ast =
+ let (typedtree, coercion) =
+ ast
+ ++ print_if ppf Clflags.dump_parsetree Printast.implementation
+ ++ print_if ppf Clflags.dump_source Pprintast.structure
+ ++ Typemod.type_implementation sourcefile outputprefix modulename env
+ ++ print_if ppf Clflags.dump_typedtree
+ Printtyped.implementation_with_coercion
+ in
+ if not !Clflags.print_types then begin
+ (typedtree, coercion)
+ ++ Translmod.transl_store_implementation modulename
+ +++ print_if ppf Clflags.dump_rawlambda Printlambda.lambda
+ +++ Simplif.simplify_lambda
+ +++ print_if ppf Clflags.dump_lambda Printlambda.lambda
+ ++ Asmgen.compile_implementation outputprefix ppf;
+ Compilenv.save_unit_info cmxfile;
+ end;
+ Warnings.check_fatal ();
+ Stypes.dump (Some (outputprefix ^ ".annot"))
+ in
+ try comp (Pparse.parse_implementation ~tool_name ppf sourcefile)
+ with x ->
+ Stypes.dump (Some (outputprefix ^ ".annot"));
+ remove_file objfile;
+ remove_file cmxfile;
+ raise x
+
+let c_file name =
+ let output_name = !Clflags.output_name in
+ if Ccomp.compile_file ~output_name name <> 0 then exit 2
diff --git a/driver/optcompile.mli b/driver/optcompile.mli
new file mode 100644
index 0000000000..00f9029a59
--- /dev/null
+++ b/driver/optcompile.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compile a .ml or .mli file *)
+
+open Format
+
+val interface: formatter -> string -> string -> unit
+val implementation: formatter -> string -> string -> unit
+val c_file: string -> unit
diff --git a/driver/opterrors.ml b/driver/opterrors.ml
new file mode 100644
index 0000000000..bda1a30ac8
--- /dev/null
+++ b/driver/opterrors.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* This module should be removed. We keep it for now, to avoid
+ breaking external tools depending on it. *)
+
+let report_error = Location.report_exception
diff --git a/driver/opterrors.mli b/driver/opterrors.mli
new file mode 100644
index 0000000000..6267091bd1
--- /dev/null
+++ b/driver/opterrors.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Error report *)
+
+val report_error: Format.formatter -> exn -> unit
diff --git a/driver/optmain.ml b/driver/optmain.ml
new file mode 100644
index 0000000000..bef8d86b4f
--- /dev/null
+++ b/driver/optmain.ml
@@ -0,0 +1,224 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Config
+open Clflags
+open Compenv
+
+let process_interface_file ppf name =
+ let opref = output_prefix name in
+ Optcompile.interface ppf name opref;
+ if !make_package then objfiles := (opref ^ ".cmi") :: !objfiles
+
+let process_implementation_file ppf name =
+ let opref = output_prefix name in
+ Optcompile.implementation ppf name opref;
+ objfiles := (opref ^ ".cmx") :: !objfiles
+
+let cmxa_present = ref false;;
+
+let process_file ppf name =
+ if Filename.check_suffix name ".ml"
+ || Filename.check_suffix name ".mlt" then
+ process_implementation_file ppf name
+ else if Filename.check_suffix name !Config.interface_suffix then
+ process_interface_file ppf name
+ else if Filename.check_suffix name ".cmx" then
+ objfiles := name :: !objfiles
+ else if Filename.check_suffix name ".cmxa" then begin
+ cmxa_present := true;
+ objfiles := name :: !objfiles
+ end else if Filename.check_suffix name ".cmi" && !make_package then
+ objfiles := name :: !objfiles
+ else if Filename.check_suffix name ext_obj
+ || Filename.check_suffix name ext_lib then
+ ccobjs := name :: !ccobjs
+ else if Filename.check_suffix name ".c" then begin
+ Optcompile.c_file name;
+ ccobjs := (Filename.chop_suffix (Filename.basename name) ".c" ^ ext_obj)
+ :: !ccobjs
+ end
+ else
+ raise(Arg.Bad("don't know what to do with " ^ name))
+
+let usage = "Usage: ocamlopt <options> <files>\nOptions are:"
+
+let ppf = Format.err_formatter
+
+(* Error messages to standard error formatter *)
+let anonymous filename =
+ readenv ppf Before_compile; process_file ppf filename;;
+let impl filename =
+ readenv ppf Before_compile; process_implementation_file ppf filename;;
+let intf filename =
+ readenv ppf Before_compile; process_interface_file ppf filename;;
+
+let show_config () =
+ Config.print_config stdout;
+ exit 0;
+;;
+
+module Options = Main_args.Make_optcomp_options (struct
+ let set r () = r := true
+ let clear r () = r := false
+
+ let _a = set make_archive
+ let _absname = set Location.absname
+ let _annot = set annotations
+ let _binannot = set binary_annotations
+ let _c = set compile_only
+ let _cc s = c_compiler := Some s
+ let _cclib s = ccobjs := Misc.rev_split_words s @ !ccobjs
+ let _ccopt s = first_ccopts := s :: !first_ccopts
+ let _compact = clear optimize_for_speed
+ let _config () = show_config ()
+ let _for_pack s = for_package := Some s
+ let _g = set debug
+ let _i () = print_types := true; compile_only := true
+ let _I dir = include_dirs := dir :: !include_dirs
+ let _impl = impl
+ let _inline n = inline_threshold := n * 8
+ let _intf = intf
+ let _intf_suffix s = Config.interface_suffix := s
+ let _keep_docs = set keep_docs
+ let _keep_locs = set keep_locs
+ let _labels = clear classic
+ let _linkall = set link_everything
+ let _no_alias_deps = set transparent_modules
+ let _no_app_funct = clear applicative_functors
+ let _no_float_const_prop = clear float_const_prop
+ let _noassert = set noassert
+ let _noautolink = set no_auto_link
+ let _nodynlink = clear dlcode
+ let _nolabels = set classic
+ let _nostdlib = set no_std_include
+ let _o s = output_name := Some s
+ let _open s = open_modules := s :: !open_modules
+ let _output_obj = set output_c_object
+ let _output_complete_obj s =
+ set output_c_object s; set output_complete_object s
+ let _p = set gprofile
+ let _pack = set make_package
+ let _pp s = preprocessor := Some s
+ let _ppx s = first_ppx := s :: !first_ppx
+ let _principal = set principal
+ let _rectypes = set recursive_types
+ let _runtime_variant s = runtime_variant := s
+ let _safe_string = clear unsafe_string
+ let _short_paths = clear real_paths
+ let _strict_sequence = set strict_sequence
+ let _strict_formats = set strict_formats
+ let _shared () = shared := true; dlcode := true
+ let _S = set keep_asm_file
+ let _thread = set use_threads
+ let _unsafe = set fast
+ let _unsafe_string = set unsafe_string
+ let _v () = print_version_and_library "native-code compiler"
+ let _version () = print_version_string ()
+ let _vnum () = print_version_string ()
+ let _verbose = set verbose
+ let _w s = Warnings.parse_options false s
+ let _warn_error s = Warnings.parse_options true s
+ let _warn_help = Warnings.help_warnings
+ let _color option =
+ begin match Clflags.parse_color_setting option with
+ | None -> ()
+ | Some setting -> Clflags.color := setting
+ end
+ let _where () = print_standard_library ()
+
+ let _nopervasives = set nopervasives
+ let _dsource = set dump_source
+ let _dparsetree = set dump_parsetree
+ let _dtypedtree = set dump_typedtree
+ let _drawlambda = set dump_rawlambda
+ let _dlambda = set dump_lambda
+ let _dclambda = set dump_clambda
+ let _dcmm = set dump_cmm
+ let _dsel = set dump_selection
+ let _dcombine = set dump_combine
+ let _dcse = set dump_cse
+ let _dlive () = dump_live := true; Printmach.print_live := true
+ let _dspill = set dump_spill
+ let _dsplit = set dump_split
+ let _dinterf = set dump_interf
+ let _dprefer = set dump_prefer
+ let _dalloc = set dump_regalloc
+ let _dreload = set dump_reload
+ let _dscheduling = set dump_scheduling
+ let _dlinear = set dump_linear
+ let _dstartup = set keep_startup_file
+ let _opaque = set opaque
+
+ let anonymous = anonymous
+end);;
+
+let main () =
+ native_code := true;
+ let ppf = Format.err_formatter in
+ try
+ readenv ppf Before_args;
+ Arg.parse (Arch.command_line_options @ Options.list) anonymous usage;
+ readenv ppf Before_link;
+ if
+ List.length (List.filter (fun x -> !x)
+ [make_package; make_archive; shared;
+ compile_only; output_c_object]) > 1
+ then
+ fatal "Please specify at most one of -pack, -a, -shared, -c, -output-obj";
+ if !make_archive then begin
+ if !cmxa_present then
+ fatal "Option -a cannot be used with .cmxa input files.";
+ Compmisc.init_path true;
+ let target = extract_output !output_name in
+ Asmlibrarian.create_archive (get_objfiles ()) target;
+ Warnings.check_fatal ();
+ end
+ else if !make_package then begin
+ Compmisc.init_path true;
+ let target = extract_output !output_name in
+ Asmpackager.package_files ppf (Compmisc.initial_env ())
+ (get_objfiles ()) target;
+ Warnings.check_fatal ();
+ end
+ else if !shared then begin
+ Compmisc.init_path true;
+ let target = extract_output !output_name in
+ Asmlink.link_shared ppf (get_objfiles ()) target;
+ Warnings.check_fatal ();
+ end
+ else if not !compile_only && !objfiles <> [] then begin
+ let target =
+ if !output_c_object then
+ let s = extract_output !output_name in
+ if (Filename.check_suffix s Config.ext_obj
+ || Filename.check_suffix s Config.ext_dll)
+ then s
+ else
+ fatal
+ (Printf.sprintf
+ "The extension of the output file must be %s or %s"
+ Config.ext_obj Config.ext_dll
+ )
+ else
+ default_output !output_name
+ in
+ Compmisc.init_path true;
+ Asmlink.link ppf (get_objfiles ()) target;
+ Warnings.check_fatal ();
+ end;
+ exit 0
+ with x ->
+ Location.report_exception ppf x;
+ exit 2
+
+let _ = main ()
diff --git a/driver/optmain.mli b/driver/optmain.mli
new file mode 100644
index 0000000000..d43cb760fb
--- /dev/null
+++ b/driver/optmain.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*
+ this "empty" file is here to speed up garbage collection in ocamlopt.opt
+*)
diff --git a/driver/pparse.ml b/driver/pparse.ml
new file mode 100644
index 0000000000..b67c1805d3
--- /dev/null
+++ b/driver/pparse.ml
@@ -0,0 +1,202 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Daniel de Rauglaudre, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+type error =
+ | CannotRun of string
+ | WrongMagic of string
+
+exception Error of error
+
+(* Optionally preprocess a source file *)
+
+let call_external_preprocessor sourcefile pp =
+ let tmpfile = Filename.temp_file "ocamlpp" "" in
+ let comm = Printf.sprintf "%s %s > %s"
+ pp (Filename.quote sourcefile) tmpfile
+ in
+ if Ccomp.command comm <> 0 then begin
+ Misc.remove_file tmpfile;
+ raise (Error (CannotRun comm));
+ end;
+ tmpfile
+
+let preprocess sourcefile =
+ match !Clflags.preprocessor with
+ None -> sourcefile
+ | Some pp -> call_external_preprocessor sourcefile pp
+
+
+let remove_preprocessed inputfile =
+ match !Clflags.preprocessor with
+ None -> ()
+ | Some _ -> Misc.remove_file inputfile
+
+
+(* Note: some of the functions here should go to Ast_mapper instead,
+ which would encapsulate the "binary AST" protocol. *)
+
+let write_ast magic ast =
+ let fn = Filename.temp_file "camlppx" "" in
+ let oc = open_out_bin fn in
+ output_string oc magic;
+ output_value oc !Location.input_name;
+ output_value oc ast;
+ close_out oc;
+ fn
+
+let apply_rewriter magic fn_in ppx =
+ let fn_out = Filename.temp_file "camlppx" "" in
+ let comm =
+ Printf.sprintf "%s %s %s" ppx (Filename.quote fn_in) (Filename.quote fn_out)
+ in
+ let ok = Ccomp.command comm = 0 in
+ Misc.remove_file fn_in;
+ if not ok then begin
+ Misc.remove_file fn_out;
+ raise (Error (CannotRun comm));
+ end;
+ if not (Sys.file_exists fn_out) then
+ raise (Error (WrongMagic comm));
+ (* check magic before passing to the next ppx *)
+ let ic = open_in_bin fn_out in
+ let buffer =
+ try really_input_string ic (String.length magic) with End_of_file -> "" in
+ close_in ic;
+ if buffer <> magic then begin
+ Misc.remove_file fn_out;
+ raise (Error (WrongMagic comm));
+ end;
+ fn_out
+
+let read_ast magic fn =
+ let ic = open_in_bin fn in
+ try
+ let buffer = really_input_string ic (String.length magic) in
+ assert(buffer = magic); (* already checked by apply_rewriter *)
+ Location.input_name := input_value ic;
+ let ast = input_value ic in
+ close_in ic;
+ Misc.remove_file fn;
+ ast
+ with exn ->
+ close_in ic;
+ Misc.remove_file fn;
+ raise exn
+
+let rewrite magic ast ppxs =
+ read_ast magic
+ (List.fold_left (apply_rewriter magic) (write_ast magic ast)
+ (List.rev ppxs))
+
+let apply_rewriters_str ?(restore = true) ~tool_name ast =
+ match !Clflags.all_ppx with
+ | [] -> ast
+ | ppxs ->
+ let ast = Ast_mapper.add_ppx_context_str ~tool_name ast in
+ let ast = rewrite Config.ast_impl_magic_number ast ppxs in
+ Ast_mapper.drop_ppx_context_str ~restore ast
+
+let apply_rewriters_sig ?(restore = true) ~tool_name ast =
+ match !Clflags.all_ppx with
+ | [] -> ast
+ | ppxs ->
+ let ast = Ast_mapper.add_ppx_context_sig ~tool_name ast in
+ let ast = rewrite Config.ast_intf_magic_number ast ppxs in
+ Ast_mapper.drop_ppx_context_sig ~restore ast
+
+let apply_rewriters ?restore ~tool_name magic ast =
+ if magic = Config.ast_impl_magic_number then
+ Obj.magic (apply_rewriters_str ?restore ~tool_name (Obj.magic ast))
+ else if magic = Config.ast_intf_magic_number then
+ Obj.magic (apply_rewriters_sig ?restore ~tool_name (Obj.magic ast))
+ else
+ assert false
+
+(* Parse a file or get a dumped syntax tree from it *)
+
+exception Outdated_version
+
+let open_and_check_magic inputfile ast_magic =
+ let ic = open_in_bin inputfile in
+ let is_ast_file =
+ try
+ let buffer = really_input_string ic (String.length ast_magic) in
+ if buffer = ast_magic then true
+ else if String.sub buffer 0 9 = String.sub ast_magic 0 9 then
+ raise Outdated_version
+ else false
+ with
+ Outdated_version ->
+ Misc.fatal_error "OCaml and preprocessor have incompatible versions"
+ | _ -> false
+ in
+ (ic, is_ast_file)
+
+let file ppf ~tool_name inputfile parse_fun ast_magic =
+ let (ic, is_ast_file) = open_and_check_magic inputfile ast_magic in
+ let ast =
+ try
+ if is_ast_file then begin
+ if !Clflags.fast then
+ (* FIXME make this a proper warning *)
+ fprintf ppf "@[Warning: %s@]@."
+ "option -unsafe used with a preprocessor returning a syntax tree";
+ Location.input_name := input_value ic;
+ input_value ic
+ end else begin
+ seek_in ic 0;
+ Location.input_name := inputfile;
+ let lexbuf = Lexing.from_channel ic in
+ Location.init lexbuf inputfile;
+ parse_fun lexbuf
+ end
+ with x -> close_in ic; raise x
+ in
+ close_in ic;
+ apply_rewriters ~restore:false ~tool_name ast_magic ast
+
+
+let report_error ppf = function
+ | CannotRun cmd ->
+ fprintf ppf "Error while running external preprocessor@.\
+ Command line: %s@." cmd
+ | WrongMagic cmd ->
+ fprintf ppf "External preprocessor does not produce a valid file@.\
+ Command line: %s@." cmd
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
+
+let parse_all ~tool_name parse_fun magic ppf sourcefile =
+ Location.input_name := sourcefile;
+ let inputfile = preprocess sourcefile in
+ let ast =
+ try file ppf ~tool_name inputfile parse_fun magic
+ with exn ->
+ remove_preprocessed inputfile;
+ raise exn
+ in
+ remove_preprocessed inputfile;
+ ast
+
+let parse_implementation ppf ~tool_name sourcefile =
+ parse_all ~tool_name Parse.implementation
+ Config.ast_impl_magic_number ppf sourcefile
+let parse_interface ppf ~tool_name sourcefile =
+ parse_all ~tool_name Parse.interface
+ Config.ast_intf_magic_number ppf sourcefile
diff --git a/driver/pparse.mli b/driver/pparse.mli
new file mode 100644
index 0000000000..898f30f241
--- /dev/null
+++ b/driver/pparse.mli
@@ -0,0 +1,49 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Daniel de Rauglaudre, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+type error =
+ | CannotRun of string
+ | WrongMagic of string
+
+exception Error of error
+
+val preprocess : string -> string
+val remove_preprocessed : string -> unit
+val file :
+ formatter -> tool_name:string -> string -> (Lexing.lexbuf -> 'a) -> string ->
+ 'a
+val apply_rewriters: ?restore:bool -> tool_name:string -> string -> 'a -> 'a
+ (** If [restore = true] (the default), cookies set by external
+ rewriters will be kept for later calls. *)
+
+val apply_rewriters_str:
+ ?restore:bool -> tool_name:string -> Parsetree.structure ->
+ Parsetree.structure
+val apply_rewriters_sig:
+ ?restore:bool -> tool_name:string -> Parsetree.signature ->
+ Parsetree.signature
+
+
+val report_error : formatter -> error -> unit
+
+
+val parse_implementation:
+ formatter -> tool_name:string -> string -> Parsetree.structure
+val parse_interface:
+ formatter -> tool_name:string -> string -> Parsetree.signature
+
+(* [call_external_preprocessor sourcefile pp] *)
+val call_external_preprocessor : string -> string -> string
+val open_and_check_magic : string -> string -> in_channel * bool
+val read_ast : string -> string -> 'a
diff --git a/emacs/.ignore b/emacs/.ignore
new file mode 100644
index 0000000000..ba5f96cd34
--- /dev/null
+++ b/emacs/.ignore
@@ -0,0 +1,2 @@
+ocamltags
+*.elc
diff --git a/emacs/COPYING b/emacs/COPYING
new file mode 100644
index 0000000000..5b6e7c66c2
--- /dev/null
+++ b/emacs/COPYING
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/emacs/Makefile b/emacs/Makefile
new file mode 100644
index 0000000000..22b2a19bae
--- /dev/null
+++ b/emacs/Makefile
@@ -0,0 +1,82 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1997 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU General Public License. #
+# #
+#########################################################################
+
+include ../config/Makefile
+
+# Files to install
+FILES= caml-font.el caml-hilit.el caml.el camldebug.el \
+ inf-caml.el caml-compat.el caml-help.el caml-types.el \
+ caml-xemacs.el caml-emacs.el
+
+# Where to install. If empty, automatically determined.
+#EMACSDIR=
+
+# Name of Emacs executable
+EMACS=emacs
+
+# Where to install ocamltags script
+SCRIPTDIR = $(BINDIR)
+
+# Command for byte-compiling the files
+COMPILECMD=(progn \
+ (setq load-path (cons "." load-path)) \
+ (byte-compile-file "caml-xemacs.el") \
+ (byte-compile-file "caml-emacs.el") \
+ (byte-compile-file "caml.el") \
+ (byte-compile-file "inf-caml.el") \
+ (byte-compile-file "caml-help.el") \
+ (byte-compile-file "caml-types.el") \
+ (byte-compile-file "caml-font.el") \
+ (byte-compile-file "camldebug.el"))
+
+install:
+ @if test "$(EMACSDIR)" = ""; then \
+ $(EMACS) --batch --eval 't; see PR#5403'; \
+ set xxx `($(EMACS) --batch --eval "(mapcar 'print load-path)") \
+ 2>/dev/null | \
+ sed -n -e 's/^"\(.*\/site-lisp\).*/\1/gp' | \
+ sort -u`; \
+ if test "$$2" = "" -o "$$3" != ""; then \
+ echo "Cannot determine Emacs site-lisp directory:"; \
+ shift; while test "$$1" != ""; do echo "\t$$1"; shift; done; \
+ else \
+ $(MAKE) EMACSDIR="$$2" simple-install; \
+ fi; \
+ else \
+ $(MAKE) simple-install; \
+ fi
+
+# install the .el files, but do not compile them.
+install-el:
+ $(MAKE) NOCOMPILE=true install
+
+simple-install:
+ @echo "Installing in $(EMACSDIR)..."
+ if test -d $(EMACSDIR); then : ; else mkdir -p $(EMACSDIR); fi
+ cp $(FILES) $(EMACSDIR)
+ if [ -z "$(NOCOMPILE)" ]; then \
+ cd $(EMACSDIR); $(EMACS) --batch --eval '$(COMPILECMD)'; \
+ fi
+
+ocamltags: ocamltags.in
+ sed -e 's:@EMACS@:$(EMACS):' ocamltags.in >ocamltags
+ chmod a+x ocamltags
+
+install-ocamltags: ocamltags
+ cp ocamltags $(SCRIPTDIR)/ocamltags
+
+# This is for testing purposes
+compile-only:
+ $(EMACS) --batch --eval '$(COMPILECMD)'
+
+clean:
+ rm -f ocamltags *~ \#*# *.elc
diff --git a/emacs/README b/emacs/README
new file mode 100644
index 0000000000..9c30c8892d
--- /dev/null
+++ b/emacs/README
@@ -0,0 +1,209 @@
+ OCaml emacs mode, snapshot of $Date$
+
+The files in this archive define a caml-mode for emacs, for editing
+OCaml and Objective Label programs, as well as an
+inferior-caml-mode, to run a toplevel.
+
+Caml-mode supports indentation, compilation and error retrieving,
+sending phrases to the toplevel. Moreover support for hilit,
+font-lock and imenu was added.
+
+This package is based on the original caml-mode for caml-light by
+Xavier Leroy, extended with indentation by Ian Zimmerman. For details
+see README.itz, which is the README from Ian Zimmerman's package.
+
+To use it, just put the .el files in your emacs load path, and add the
+following lines in your .emacs.
+
+ (add-to-list 'auto-mode-alist '("\\.ml[iylp]?$" . caml-mode))
+ (autoload 'caml-mode "caml" "Major mode for editing OCaml code." t)
+ (autoload 'run-caml "inf-caml" "Run an inferior OCaml process." t)
+ (autoload 'camldebug "camldebug" "Run ocamldebug on program." t)
+ (add-to-list 'interpreter-mode-alist '("ocamlrun" . caml-mode))
+ (add-to-list 'interpreter-mode-alist '("ocaml" . caml-mode))
+
+or put the .el files in, eg. "/usr/share/emacs/site-lisp/caml-mode/"
+and add the following line in addtion to the four lines above:
+
+ (add-to-list 'load-path "/usr/share/emacs/site-lisp/caml-mode")
+
+To install the mode itself, edit the Makefile and do
+
+ % make install
+
+To install ocamltags, do
+
+ % make install-ocamltags
+
+To use highlighting capabilities, add ONE of the following two lines
+to your .emacs. The second one works better on recent versions of
+emacs.
+
+ (if window-system (require 'caml-hilit))
+ (if window-system (require 'caml-font))
+
+caml.el and inf-caml.el can be used collectively, but it might be a
+good idea to copy caml-hilit.el or caml-font.el to you own directory,
+and edit it to your taste and colors.
+
+Main key bindings:
+
+TAB indent current line
+M-C-q indent phrase
+M-C-h mark phrase
+C-c C-a switch between interface and implementation
+C-c C-c compile (usually make)
+C-x` goto next error (also mouse button 2 in the compilation log)
+
+Once you have started caml by M-x run-caml:
+
+M-C-x send phrase to inferior caml process
+C-c C-r send region to inferior caml process
+C-c C-s show inferior caml process
+C-c` goto error in expression sent by M-C-x
+
+For other bindings, see C-h b.
+
+Changes log:
+-----------
+Version 3.10.1:
+---------------
+* use caml-font.el from Olivier Andrieu
+ old version is left as caml-font-old.el for compatibility
+
+Version 3.07:
+-------------
+* support for showing type information <Damien Doligez>
+
+Version 3.05:
+-------------
+* improved interaction with inferior caml mode
+
+* access help from the source
+
+* fixes in indentation code
+
+Version 3.03:
+-------------
+* process ;; properly
+
+Version 3.00:
+-------------
+* adapt to new label syntax
+
+* intelligent indentation of parenthesis
+
+Version 2.02:
+-------------
+* improved ocamltags <ITZ and JG>
+
+* added support for multibyte characters in emacs 20
+
+Version 2.01+:
+--------------
+* corrected a bug in caml-font.el <Adam P. Jenkins>
+
+* corrected abbreviations and added ocamltags script <Ian T Zimmerman>
+
+Version 2.01:
+------------
+* code for interactive errors added by ITZ
+
+Version 2.00:
+------------
+* changed the algorithm to skip comments
+
+* adapted for the new object syntax
+
+Version 1.07:
+------------
+* next-error bug fix by John Malecki
+
+* camldebug.el modified by Xavier Leroy
+
+Version 1.06:
+------------
+* new keywords in Objective Caml 1.06
+
+* compatibility with GNU Emacs 20
+
+* changed from caml-imenu-disable to caml-imenu-enable (off by default)
+
+Version 1.05:
+------------
+* a few indentation bugs corrected. let, val ... are now indented
+ correctly even when you write them at the beginning of a line.
+
+* added a Caml menu, and Imenu support. Imenu menu can be disabled
+ by setting the variable caml-imenu-disable to t.
+ Xemacs support for the Menu, but no Imenu.
+
+* key bindings closer to lisp-mode.
+
+* O'Labl compatibility (":" is part of words) may be switched off by
+ setting caml-olabl-disable to t.
+
+* camldebug.el was updated by Xavier Leroy.
+
+Version 1.03b:
+-------------
+* many bugs corrected.
+
+* (partial) compatibility with Caml-Light added.
+ (setq caml-quote-char "`")
+ (setq inferior-caml-program "camllight")
+ Literals will be correctly understood and highlighted. However,
+ indentation rules are still OCaml's: this just happens to
+ work well in most cases, but is only intended for occasional use.
+
+* as many people asked for it, application is now indented. This seems
+ to work well: this time differences in indentation between the
+ compiler's source and this mode are really exceptionnal. On the
+ other hand, you may think that some special cases are strange. No
+ miracle.
+
+* nicer behaviour when sending a phrase/region to the inferior caml
+ process.
+
+Version 1.03:
+------------
+* support of OCaml and Objective Label.
+
+* an indentation very close to mine, which happens to be the same as
+ Xavier's, since the sources of the OCaml compiler do not
+ change if you indent them in this mode.
+
+* highlighting.
+
+Some remarks about the style supported:
+--------------------------------------
+
+Since OCaml's syntax is very liberal (more than 100
+shift-reduce conflicts with yacc), automatic indentation is far from
+easy. Moreover, you expect the indentation to be not purely syntactic,
+but also semantic: reflecting the meaning of your program.
+
+This mode tries to be intelligent. For instance some operators are
+indented differently in the middle and at the end of a line (thanks to
+Ian Zimmerman). Also, we do not indent after if .. then .. else, when
+else is on the same line, to reflect that this idiom is equivalent to
+a return instruction in a more imperative language, or after the in of
+let .. in, since you may see that as an assignment.
+
+However, you may want to use a different indentation style. This is
+made partly possible by a number of variables at the beginning of
+caml.el. Try to set them. However this only changes the size of
+indentations, not really the look of your program. This is enough to
+disable the two idioms above, but to do anything more you will have to
+edit the code... Enjoy!
+
+This mode does not force you to put ;; in your program. This means
+that we had to use a heuristic to decide where a phrase starts and
+stops, to speed up the code. A phrase starts when any of the keywords
+let, type, class, module, functor, exception, val, external, appears
+at the beginning of a line. Using the first column for such keywords
+in other cases may confuse the phrase selection function.
+
+Comments and bug reports to
+
+ Jacques Garrigue <garrigue@math.nagoya-u.ac.jp>
diff --git a/emacs/README.itz b/emacs/README.itz
new file mode 100644
index 0000000000..7bcc7aa05d
--- /dev/null
+++ b/emacs/README.itz
@@ -0,0 +1,177 @@
+DESCRIPTION:
+
+This directory contains files to help editing OCaml code, running a
+OCaml toplevel, and running the OCaml debugger under the Gnu Emacs editor.
+
+AUTHORS:
+
+Ian T Zimmerman <itz@rahul.net> added indentation to caml mode, beefed
+up camldebug to work much like gud/gdb.
+
+Xavier Leroy (Xavier.Leroy@inria.fr), Jerome Vouillon (Jerome.Vouillon@ens.fr).
+camldebug.el is derived from FSF code.
+
+CONTENTS:
+
+ caml.el A major mode for editing OCaml code in Gnu Emacs
+ inf-caml.el To run a OCaml toplevel under Emacs, with input and
+ output in an Emacs buffer.
+ camldebug.el To run the OCaml debugger under Emacs.
+
+
+NOTE FOR EMACS 18 USERS:
+
+This package will no longer work with Emacs 18.x. Sorry. You really
+should consider upgrading to Emacs 19.
+
+USAGE:
+
+Add the following lines to your .emacs file:
+
+(setq auto-mode-alist (cons '("\\.ml[iylp]?" . caml-mode) auto-mode-alist))
+(autoload 'caml-mode "caml" "Major mode for editing OCaml code." t)
+(autoload 'run-caml "inf-caml" "Run an inferior OCaml process." t)
+(autoload 'camldebug "camldebug" "Run the OCaml debugger." t)
+
+The Caml major mode is triggered by visiting a file with extension .ml,
+.mli, .mly. .mll or .mlp, or manually by M-x caml-mode. It gives you the
+correct syntax table for the OCaml language. For a brief description of
+the indentation capabilities, see below under NEWS.
+
+The Caml mode also allows you to run batch Caml compilations from
+Emacs (using M-x compile) and browse the errors (C-x `). Typing C-x `
+sets the point at the beginning of the erroneous program fragment, and
+the mark at the end. Under Emacs 19, the program fragment is
+temporarily highlighted.
+
+M-x run-caml starts an OCaml toplevel with input and output in an Emacs
+buffer named *inferior-caml*. This gives you the full power of Emacs
+to edit the input to the OCaml toplevel. This mode is based on comint
+so you get all the usual comint features, including command history.
+
+After M-x run-caml, typing C-c C-e or M-C-x in a buffer in Caml mode
+sends the current phrase (containing the point) to the OCaml toplevel,
+and evaluates it.
+
+M-x camldebug FILE starts the OCaml debugger camldebug on the executable
+FILE, with input and output in an Emacs buffer named *camldebug-FILE*.
+For a brief description of the commands available in this buffer, see
+NEWS below.
+
+NEWS:
+
+Ok, so this is the really important part of this file :-) I took the
+original package from the contrib subdirectory of the caml-light
+distribution, and hacked on it. First, I added real syntax dependent
+indentation to caml mode. Like Xavier has said, it was hard (and I
+knew it would be), but I refused to believe it was impossible, partly
+because I knew of a Standard ML mode with indentation (written by
+Matthew Morley).
+
+Indentation works pretty much like in other programming modes. C-j at
+the end of a line starts a new line properly indented. M-C-\ indents
+the current region (this may take a while :-)). I incorporated a
+slightly different TAB function, one that I use in other modes: if TAB
+is pressed while the point is not in line indentation, the line is
+indented to the column where point is (instead of just inserting a TAB
+character - you can always to that with C-q C-i). This way, you can
+indent a line any time, regardless of where the point lies, by hitting
+TAB twice in succession. If you don't like this behaviour (but you
+should), it's quite easy to add to your startup code like this:
+
+(defun caml-old-style-indent ()
+ (if (caml-in-indentation)
+ (caml-indent-command)
+ (insert "\t")))
+
+(add-hook 'caml-mode-hook
+ (function (lambda ()
+ (define-key 'caml-mode-map "\t"
+ caml-old-style-indent))))
+
+You can customize the appearance of your caml code by twiddling the
+variables listed at the start of caml.el. Good luck. :-)
+
+Other news in caml mode are the various caml-insert-*-form commands. I
+believe they are self-explanatory - just do a C-h m in a caml buffer
+to see what you've got.
+
+The ohter major news is that I changed camldebug mode considerably. I
+took many clues from the gud "Grand Unified Debugger" mode distributed
+with modern versions of Emacs. The main benefit here is that you can
+do debugger commands _from your caml source buffer_. Commands with the
+C-c prefix in the debugger buffer have counterparts which do the same
+thing (well, a similar thing) in the source buffer, with the C-x C-a
+prefix.
+
+I made the existing debugger commands smarter in that they now attempt
+to guess the correct parameter to the underlying camldebug command. A
+numeric argument will always override that guess. For example, the
+guess for C-c C-b (camldebug-break) is to set a breakpoint at the
+current event (which was the only behaviour provided with the old
+camldebug.el). But C-u 1 C-c C-b will now send "break 1" to the
+camldebug process, setting a break at code address 1.
+
+This also allowed me to add many more commands for which the
+underlying camldebug commands require a parameter. The best way to
+learn about them is to do C-h m in the camldebug buffer, and then C-h
+f for the commands you'll see listed.
+
+Finally, I added command completion. To use it, you'll have to apply
+the provided patch to the debugger itself
+(contrib/debugger/command_line_interpreter.ml), and recompile it
+(you'll get one warning from the compiler; it is safe to ignore
+it). Then hitting TAB in the following situation, for example:
+
+(cdb) pri_
+
+will complete the "pri" to "print".
+
+CAVEATS:
+
+I don't use X and haven't tested this stuff under the X mode of
+emacs. It is entirely possible (though not very probable) that I
+introduced some undesirable interaction between X (fontification,
+highlighting,...) and caml mode. I will welcome reports of such
+problems (see REPORTING below), but I won't be able to do much about
+them unless you also provide a patch.
+
+I don't know if the informational messages produced by camldebug are
+internationalized. If they are, the debugger mode won't work unless
+you set the language to English. The mode uses the messages to
+synchronize with camldebug, and looks for fixed Emacs regular
+expressions that match them. This may be fixed (if necessary) in a
+future release.
+
+BUGS:
+
+In the debugger buffer, it's possible to overflow your mental stack by
+asking for help on help on help on help on help on help on help on
+help...
+
+THANKS:
+
+Xavier Leroy <Xavier.Leroy@inria.fr> for Caml-light. Used together with the
+Emacs interface, it is about the most pleasant programming environment
+I've known on any platform.
+
+Eric Raymond <esr@thyrsus.com> for gud, which camldebug mode apes.
+
+Barry Warsaw <bwarsaw@cen.com> for elp, without which I wouldn't have
+been able to get the indentation code to perform acceptably.
+
+Gareth Rees <Gareth.Rees@cl.cam.ac.uk> for suggestions how to speed up
+Emacs regular expression search, even if I didn't use them in the end.
+
+Bill Dubuque <wgd@martigny.ai.mit.edu> for alerting me to the
+necessity of guarding against C-g inside Emacs code which modifies
+syntax tables.
+
+REPORTING:
+
+Bug reports (preferably with patches), suggestions, donations etc. to:
+
+Ian T Zimmerman +-------------------------------------------+
+Box 13445 I With so many executioners available, I
+Berkeley CA 94712 USA I suicide is a really foolish thing to do. I
+mailto:itz@rahul.net +-------------------------------------------+
diff --git a/emacs/caml-compat.el b/emacs/caml-compat.el
new file mode 100644
index 0000000000..a5cff879ea
--- /dev/null
+++ b/emacs/caml-compat.el
@@ -0,0 +1,39 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+;(* *)
+;(* Copyright 1998 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;; function definitions for old versions of emacs
+
+;; indent-line-to
+
+(if (not (fboundp 'indent-line-to))
+ (defun indent-line-to (column)
+ "Indent current line to COLUMN.
+
+This function removes or adds spaces and tabs at beginning of line
+only if necessary. It leaves point at end of indentation."
+ (if (= (current-indentation) column)
+ (back-to-indentation)
+ (beginning-of-line 1)
+ (delete-horizontal-space)
+ (indent-to column))))
+
+;; buffer-substring-no-properties
+
+(cond
+ ((fboundp 'buffer-substring-no-properties))
+ ((fboundp 'buffer-substring-without-properties)
+ (defalias 'buffer-substring-no-properties
+ 'buffer-substring-without-properties))
+ (t
+ (defalias 'buffer-substring-no-properties 'buffer-substring)))
+
+(provide 'caml-compat)
diff --git a/emacs/caml-emacs.el b/emacs/caml-emacs.el
new file mode 100644
index 0000000000..7166d1a878
--- /dev/null
+++ b/emacs/caml-emacs.el
@@ -0,0 +1,43 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Didier Remy, projet Cristal, INRIA Rocquencourt *)
+;(* *)
+;(* Copyright 2003 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;; for caml-help.el
+(defalias 'caml-info-other-window 'info-other-window)
+
+;; for caml-types.el
+
+(defalias 'caml-line-beginning-position 'line-beginning-position)
+
+(defalias 'caml-read-event 'read-event)
+(defalias 'caml-window-edges 'window-edges)
+(defun caml-mouse-vertical-position ()
+ (cddr (mouse-position)))
+(defalias 'caml-ignore-event-p 'integer-or-marker-p)
+(defalias 'caml-mouse-movement-p 'mouse-movement-p)
+(defalias 'caml-sit-for 'sit-for)
+
+(defalias 'caml-track-mouse 'track-mouse)
+
+(defun caml-event-window (e) (posn-window (event-start e)))
+(defun caml-event-point-start (e) (posn-point (event-start e)))
+(defun caml-event-point-end (e) (posn-point (event-end e)))
+
+(defun caml-release-event-p (original event)
+ (and (equal (event-basic-type original) (event-basic-type event))
+ (let ((modifiers (event-modifiers event)))
+ (or (member 'drag modifiers)
+ (member 'click modifiers)))))
+
+(defalias 'caml-string-to-int (if (fboundp 'string-to-number)
+ 'string-to-number 'string-to-int))
+
+(provide 'caml-emacs)
diff --git a/emacs/caml-font-old.el b/emacs/caml-font-old.el
new file mode 100644
index 0000000000..7456e8c583
--- /dev/null
+++ b/emacs/caml-font-old.el
@@ -0,0 +1,139 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Jacques Garrigue and Ian T Zimmerman *)
+;(* *)
+;(* Copyright 1997 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;; useful colors
+
+(cond
+ ((x-display-color-p)
+ (require 'font-lock)
+ (cond
+ ((not (boundp 'font-lock-type-face))
+ ; make the necessary faces
+ (make-face 'Firebrick)
+ (set-face-foreground 'Firebrick "Firebrick")
+ (make-face 'RosyBrown)
+ (set-face-foreground 'RosyBrown "RosyBrown")
+ (make-face 'Purple)
+ (set-face-foreground 'Purple "Purple")
+ (make-face 'MidnightBlue)
+ (set-face-foreground 'MidnightBlue "MidnightBlue")
+ (make-face 'DarkGoldenRod)
+ (set-face-foreground 'DarkGoldenRod "DarkGoldenRod")
+ (make-face 'DarkOliveGreen)
+ (set-face-foreground 'DarkOliveGreen "DarkOliveGreen4")
+ (make-face 'CadetBlue)
+ (set-face-foreground 'CadetBlue "CadetBlue")
+ ; assign them as standard faces
+ (setq font-lock-comment-face 'Firebrick)
+ (setq font-lock-string-face 'RosyBrown)
+ (setq font-lock-keyword-face 'Purple)
+ (setq font-lock-function-name-face 'MidnightBlue)
+ (setq font-lock-variable-name-face 'DarkGoldenRod)
+ (setq font-lock-type-face 'DarkOliveGreen)
+ (setq font-lock-reference-face 'CadetBlue)))
+ ; extra faces for documention
+ (make-face 'Stop)
+ (set-face-foreground 'Stop "White")
+ (set-face-background 'Stop "Red")
+ (make-face 'Doc)
+ (set-face-foreground 'Doc "Red")
+ (setq font-lock-stop-face 'Stop)
+ (setq font-lock-doccomment-face 'Doc)
+))
+
+; The same definition is in caml.el:
+; we don't know in which order they will be loaded.
+(defvar caml-quote-char "'"
+ "*Quote for character constants. \"'\" for OCaml, \"`\" for Caml-Light.")
+
+(defconst caml-font-lock-keywords
+ (list
+;stop special comments
+ '("\\(^\\|[^\"]\\)\\((\\*\\*/\\*\\*)\\)"
+ 2 font-lock-stop-face)
+;doccomments
+ '("\\(^\\|[^\"]\\)\\((\\*\\*[^*]*\\([^)*][^*]*\\*+\\)*)\\)"
+ 2 font-lock-doccomment-face)
+;comments
+ '("\\(^\\|[^\"]\\)\\((\\*[^*]*\\*+\\([^)*][^*]*\\*+\\)*)\\)"
+ 2 font-lock-comment-face)
+;character literals
+ (cons (concat caml-quote-char "\\(\\\\\\([ntbr" caml-quote-char "\\]\\|"
+ "[0-9][0-9][0-9]\\)\\|.\\)" caml-quote-char
+ "\\|\"[^\"\\]*\\(\\\\\\(.\\|\n\\)[^\"\\]*\\)*\"")
+ 'font-lock-string-face)
+;modules and constructors
+ '("`?\\<[A-Z][A-Za-z0-9_']*\\>" . font-lock-function-name-face)
+;definition
+ (cons (concat
+ "\\<\\(a\\(nd\\|s\\)\\|c\\(onstraint\\|lass\\)"
+ "\\|ex\\(ception\\|ternal\\)\\|fun\\(ct\\(ion\\|or\\)\\)?"
+ "\\|in\\(herit\\|itializer\\)?\\|let"
+ "\\|m\\(ethod\\|utable\\|odule\\)"
+ "\\|of\\|p\\(arser\\|rivate\\)\\|rec\\|type"
+ "\\|v\\(al\\|irtual\\)\\)\\>")
+ 'font-lock-type-face)
+;blocking
+ '("\\<\\(begin\\|end\\|object\\|s\\(ig\\|truct\\)\\)\\>"
+ . font-lock-keyword-face)
+;control
+ (cons (concat
+ "\\<\\(do\\(ne\\|wnto\\)?\\|else\\|for\\|i\\(f\\|gnore\\)"
+ "\\|lazy\\|match\\|new\\|or\\|t\\(hen\\|o\\|ry\\)"
+ "\\|w\\(h\\(en\\|ile\\)\\|ith\\)\\)\\>"
+ "\\|\|\\|->\\|&\\|#")
+ 'font-lock-reference-face)
+ '("\\<raise\\>" . font-lock-comment-face)
+;labels (and open)
+ '("\\(\\([~?]\\|\\<\\)[a-z][a-zA-Z0-9_']*:\\)[^:=]" 1
+ font-lock-variable-name-face)
+ '("\\<\\(assert\\|open\\|include\\)\\>\\|[~?][ (]*[a-z][a-zA-Z0-9_']*"
+ . font-lock-variable-name-face)))
+
+(defconst inferior-caml-font-lock-keywords
+ (append
+ (list
+;inferior
+ '("^[#-]" . font-lock-comment-face))
+ caml-font-lock-keywords))
+
+;; font-lock commands are similar for caml-mode and inferior-caml-mode
+(defun caml-mode-font-hook ()
+ (cond
+ ((fboundp 'global-font-lock-mode)
+ (make-local-variable 'font-lock-defaults)
+ (setq font-lock-defaults
+ '(caml-font-lock-keywords nil nil ((?' . "w") (?_ . "w")))))
+ (t
+ (setq font-lock-keywords caml-font-lock-keywords)))
+ (make-local-variable 'font-lock-keywords-only)
+ (setq font-lock-keywords-only t)
+ (font-lock-mode 1))
+
+(add-hook 'caml-mode-hook 'caml-mode-font-hook)
+
+(defun inferior-caml-mode-font-hook ()
+ (cond
+ ((fboundp 'global-font-lock-mode)
+ (make-local-variable 'font-lock-defaults)
+ (setq font-lock-defaults
+ '(inferior-caml-font-lock-keywords
+ nil nil ((?' . "w") (?_ . "w")))))
+ (t
+ (setq font-lock-keywords inferior-caml-font-lock-keywords)))
+ (make-local-variable 'font-lock-keywords-only)
+ (setq font-lock-keywords-only t)
+ (font-lock-mode 1))
+
+(add-hook 'inferior-caml-mode-hooks 'inferior-caml-mode-font-hook)
+
+(provide 'caml-font)
diff --git a/emacs/caml-font.el b/emacs/caml-font.el
new file mode 100644
index 0000000000..40bee0a3a8
--- /dev/null
+++ b/emacs/caml-font.el
@@ -0,0 +1,410 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Jacques Garrigue, Ian T Zimmerman, Damien Doligez *)
+;(* *)
+;(* Copyright 1997 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;; caml-font: font-lock support for OCaml files
+;; now with perfect parsing of comments and strings
+
+(require 'font-lock)
+
+(defvar caml-font-stop-face
+ (progn
+ (make-face 'caml-font-stop-face)
+ (set-face-foreground 'caml-font-stop-face "White")
+ (set-face-background 'caml-font-stop-face "Red")
+ 'caml-font-stop-face))
+
+(defvar caml-font-doccomment-face
+ (progn
+ (make-face 'caml-font-doccomment-face)
+ (set-face-foreground 'caml-font-doccomment-face "Red")
+ 'caml-font-doccomment-face))
+
+(unless (facep 'font-lock-preprocessor-face)
+ (defvar font-lock-preprocessor-face
+ (copy-face 'font-lock-builtin-face
+ 'font-lock-preprocessor-face)))
+
+(defconst caml-font-lock-keywords
+ `(
+;modules and constructors
+ ("`?\\<[A-Z][A-Za-z0-9_']*\\>" . font-lock-function-name-face)
+;definition
+ (,(regexp-opt '("and" "as" "constraint" "class"
+ "exception" "external" "fun" "function" "functor"
+ "in" "inherit" "initializer" "let"
+ "method" "mutable" "module" "of" "private" "rec"
+ "type" "val" "virtual")
+ 'words)
+ . font-lock-type-face)
+;blocking
+ (,(regexp-opt '("begin" "end" "object" "sig" "struct") 'words)
+ . font-lock-keyword-face)
+;linenums
+ ("# *[0-9]+" . font-lock-preprocessor-face)
+;infix operators
+ (,(regexp-opt '("asr" "land" "lor" "lsl" "lsr" "lxor" "mod") 'words)
+ . font-lock-builtin-face)
+;control
+ (,(concat "[|#&]\\|->\\|"
+ (regexp-opt '("do" "done" "downto" "else" "for" "if" "ignore"
+ "lazy" "match" "new" "or" "then" "to" "try"
+ "when" "while" "with")
+ 'words))
+ . font-lock-constant-face)
+ ("\\<raise\\|failwith\\|invalid_arg\\>"
+ . font-lock-comment-face)
+;labels (and open)
+ ("\\(\\([~?]\\|\\<\\)[a-z][a-zA-Z0-9_']*:\\)[^:=]"
+ 1 font-lock-variable-name-face)
+ ("\\<\\(assert\\|open\\|include\\)\\>\\|[~?][ (]*[a-z][a-zA-Z0-9_']*"
+ . font-lock-variable-name-face)))
+
+
+(defun caml-font-syntactic-face (s)
+ (let ((in-string (nth 3 s))
+ (in-comment (nth 4 s))
+ (start (nth 8 s)))
+ (cond
+ (in-string 'font-lock-string-face)
+ (in-comment
+ (save-excursion
+ (goto-char start)
+ (cond
+ ((looking-at "(\\*\\*/\\*\\*)") 'caml-font-stop-face)
+ ((looking-at "(\\*\\*[^*]") 'caml-font-doccomment-face)
+ (t 'font-lock-comment-face)))))))
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; In order to correctly fontify an OCaml buffer, it is necessary to
+; lex the buffer to tell what is a comment and what is a string.
+; We do this incrementally in a hook
+; (font-lock-extend-after-change-region-function), which is called
+; whenever the buffer changes. It sets the syntax-table property
+; on each beginning and end of chars, strings, and comments.
+
+; This mode handles correctly all the strange cases in the following
+; OCaml code.
+;
+; let l' _ = ();;
+; let _' _ = ();;
+; let l' = ();;
+; let b2_' = ();;
+; let a'a' = ();;
+; let f2 _ _ = ();;
+; let f3 _ _ _ = ();;
+; let f' _ _ _ _ _ = ();;
+; let hello = ();;
+;
+; (* ==== easy stuff ==== *)
+;
+; (* a comment *)
+; (* "a string" in a comment *)
+; (* "another string *)" in a comment *)
+; (* not a string '"' in a comment *)
+; "a string";;
+; '"';; (* not a string *)
+;
+; (* ==== hard stuff ==== *)
+;
+; l'"' not not a string ";;
+; _'"' also not not a string";;
+; f2 0l'"';; (* not not not a string *)
+; f2 0_'"';; (* also not not not a string *)
+; f3 0.0l'"' not not not not a string ";;
+; f3 0.0_'"';; (* not not not not not a string *)
+; f2 0b01_'"';; (* not not not a string *)
+; f3 0b2_'"' not not not not a string ";;
+; f3 0b02_'"';; (* not not not not not a string *)
+; '\'';; (* a char *)
+; '
+; ';; (* a char *)
+; '^M
+; ';; (* also a char [replace ^M with one CR character] *)
+; a'a';; (* not a char *)
+; type '
+; a' t = X;; (* also not a char *)
+;
+; (* ==== far-out stuff ==== *)
+;
+; f'"'" "*) print_endline "hello";;(* \"" ;;
+; (* f'"'" "*) print_endline "hello";;(* \"" ;; *)
+
+
+(defconst caml-font-ident-re
+ (concat "[A-Za-z_\300-\326\330-\366\370-\377]"
+ "[A-Za-z_\300-\326\330-\366\370-\377'0-9]*")
+)
+
+(defconst caml-font-int-re
+ (concat "\\(0[xX][0-9A-Fa-f][0-9A-Fa-f_]*\\|0[oO][0-7][0-7_]*"
+ "\\|0[bB][01][01_]*\\)[lLn]?")
+)
+
+; decimal integers are folded into the RE for floats to get longest-match
+; without using posix-looking-at
+(defconst caml-font-decimal-re
+ "[0-9][0-9_]*\\([lLn]\\|\\.[0-9_]*\\)?\\([eE][+-]?[0-9][0-9_]*\\)?"
+)
+
+; match any ident or numeral token
+(defconst caml-font-ident-or-num-re
+ (concat caml-font-ident-re "\\|" caml-font-int-re "\\|" caml-font-decimal-re)
+)
+
+; match any char token
+(defconst caml-font-char-re
+ (concat "'\\(\015\012\\|[^\\']\\|"
+ "\\(\\\\\\([\\'\"ntbr ]\\|[0-9][0-9][0-9]"
+ "\\|x[0-9A-Fa-f][0-9A-Fa-f]\\)\\)\\)'")
+)
+
+; match a quote followed by a newline
+(defconst caml-font-quote-newline-re
+ "'\\(\015\012\\|[\012\015]\\)"
+)
+
+; match any token or sequence of tokens that cannot contain a
+; quote, double quote, a start of comment, or a newline
+; note: this is only to go faster than one character at a time
+(defconst caml-font-other-re
+ "[^A-Za-z_0-9\012\015\300-\326\330-\366\370-\377'\"(]+"
+)
+
+; match any sequence of non-special characters in a comment
+; note: this is only to go faster than one character at a time
+(defconst caml-font-other-comment-re
+ "[^(*\"'\012\015]+"
+)
+
+; match any sequence of non-special characters in a string
+; note: this is only to go faster than one character at a time
+(defconst caml-font-other-string-re
+ "[^\\\"\012\015]"
+)
+
+; match a newline
+(defconst caml-font-newline-re
+ "\\(\015\012\\|[\012\015]\\)"
+)
+
+; Put the 'caml-font-state property with the given state on the
+; character before pos. Return nil if it was already there, t if not.
+(defun caml-font-put-state (pos state)
+ (if (equal state (get-text-property (1- pos) 'caml-font-state))
+ nil
+ (put-text-property (1- pos) pos 'caml-font-state state)
+ t)
+)
+
+; Same as looking-at, but erase properties 'caml-font-state and
+; 'syntax-table from the matched range
+(defun caml-font-looking-at (re)
+ (let ((result (looking-at re)))
+ (when result
+ (remove-text-properties (match-beginning 0) (match-end 0)
+ '(syntax-table nil caml-font-state nil)))
+ result)
+)
+
+; Annotate the buffer starting at point in state (st . depth)
+; Set the 'syntax-table property on beginnings and ends of:
+; - strings
+; - chars
+; - comments
+; Also set the 'caml-font-state property on each LF character that is
+; not preceded by a single quote. The property gives the state of the
+; lexer (nil or t) after reading that character.
+
+; Leave the point at a point where the pre-existing 'caml-font-state
+; property is consistent with the new parse, or at the end of the buffer.
+
+; depth is the depth of nested comments at this point
+; it must be a non-negative integer
+; st can be:
+; nil -- we are in the base state
+; t -- we are within a string
+
+(defun caml-font-annotate (st depth)
+ (let ((continue t))
+ (while (and continue (not (eobp)))
+ (cond
+ ((and (equal st nil) (= depth 0)) ; base state, outside comment
+ (cond
+ ((caml-font-looking-at caml-font-ident-or-num-re)
+ (goto-char (match-end 0)))
+ ((caml-font-looking-at caml-font-char-re)
+ (put-text-property (point) (1+ (point))
+ 'syntax-table (string-to-syntax "|"))
+ (put-text-property (1- (match-end 0)) (match-end 0)
+ 'syntax-table (string-to-syntax "|"))
+ (goto-char (match-end 0)))
+ ((caml-font-looking-at caml-font-quote-newline-re)
+ (goto-char (match-end 0)))
+ ((caml-font-looking-at "\"")
+ (put-text-property (point) (1+ (point))
+ 'syntax-table (string-to-syntax "|"))
+ (goto-char (match-end 0))
+ (setq st t))
+ ((caml-font-looking-at "(\\*")
+ (put-text-property (point) (1+ (point))
+ 'syntax-table (string-to-syntax "!"))
+ (goto-char (match-end 0))
+ (setq depth 1))
+ ((looking-at caml-font-newline-re)
+ (goto-char (match-end 0))
+ (setq continue (caml-font-put-state (match-end 0) '(nil . 0))))
+ ((caml-font-looking-at caml-font-other-re)
+ (goto-char (match-end 0)))
+ (t
+ (remove-text-properties (point) (1+ (point))
+ '(syntax-table nil caml-font-state nil))
+ (goto-char (1+ (point))))))
+ ((equal st nil) ; base state inside comment
+ (cond
+ ((caml-font-looking-at "(\\*")
+ (goto-char (match-end 0))
+ (setq depth (1+ depth)))
+ ((caml-font-looking-at "\\*)")
+ (goto-char (match-end 0))
+ (setq depth (1- depth))
+ (when (= depth 0)
+ (put-text-property (1- (point)) (point)
+ 'syntax-table (string-to-syntax "!"))))
+ ((caml-font-looking-at "\"")
+ (goto-char (match-end 0))
+ (setq st t))
+ ((caml-font-looking-at caml-font-char-re)
+ (goto-char (match-end 0)))
+ ((caml-font-looking-at caml-font-quote-newline-re)
+ (goto-char (match-end 0)))
+ ((caml-font-looking-at "''")
+ (goto-char (match-end 0)))
+ ((looking-at caml-font-newline-re)
+ (goto-char (match-end 0))
+ (setq continue (caml-font-put-state (match-end 0) (cons nil depth))))
+ ((caml-font-looking-at caml-font-other-comment-re)
+ (goto-char (match-end 0)))
+ (t
+ (remove-text-properties (point) (1+ (point))
+ '(syntax-table nil caml-font-state nil))
+ (goto-char (1+ (point))))))
+ (t ; string state inside or outside a comment
+ (cond
+ ((caml-font-looking-at "\"")
+ (when (= depth 0)
+ (put-text-property (point) (1+ (point))
+ 'syntax-table (string-to-syntax "|")))
+ (goto-char (1+ (point)))
+ (setq st nil))
+ ((caml-font-looking-at "\\\\[\"\\]")
+ (goto-char (match-end 0)))
+ ((looking-at caml-font-newline-re)
+ (goto-char (match-end 0))
+ (setq continue (caml-font-put-state (match-end 0) (cons t depth))))
+ ((caml-font-looking-at caml-font-other-string-re)
+ (goto-char (match-end 0)))
+ (t
+ (remove-text-properties (point) (1+ (point))
+ '(syntax-table nil caml-font-state nil))
+ (goto-char (1+ (point)))))))))
+)
+
+; This is the hook function for font-lock-extend-after-change-function
+; It finds the nearest saved state at the left of the changed text,
+; calls caml-font-annotate to set the 'caml-font-state and 'syntax-table
+; properties, then returns the range that was parsed by caml-font-annotate.
+(defun caml-font-extend-after-change (beg end &optional old-len)
+ (save-excursion
+ (save-match-data
+ (let ((caml-font-modified (buffer-modified-p))
+ start-at
+ end-at
+ state)
+ (remove-text-properties beg end '(syntax-table nil caml-font-state nil))
+ (setq start-at
+ (or (and (> beg (point-min))
+ (get-text-property (1- beg) 'caml-font-state)
+ beg)
+ (previous-single-property-change beg 'caml-font-state)
+ (point-min)))
+ (setq state (or (and (> start-at (point-min))
+ (get-text-property (1- start-at) 'caml-font-state))
+ (cons nil 0)))
+ (goto-char start-at)
+ (caml-font-annotate (car state) (cdr state))
+ (setq end-at (point))
+ (restore-buffer-modified-p caml-font-modified)
+ (cons start-at end-at))))
+)
+
+; We don't use the normal caml-mode syntax table because it contains an
+; approximation of strings and comments that interferes with our
+; annotations.
+(defconst caml-font-syntax-table
+ (let ((tbl (make-syntax-table)))
+ (modify-syntax-entry ?' "w" tbl)
+ (modify-syntax-entry ?_ "w" tbl)
+ (modify-syntax-entry ?\" "." tbl)
+ (let ((i 192))
+ (while (< i 256)
+ (or (= i 215) (= i 247) (modify-syntax-entry i "w" tbl))
+ (setq i (1+ i))))
+ tbl))
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;; font-lock commands are similar for caml-mode and inferior-caml-mode
+(defun caml-font-set-font-lock ()
+ (setq parse-sexp-lookup-properties t)
+ (setq font-lock-defaults
+ (list
+ 'caml-font-lock-keywords ; keywords
+ nil ; keywords-only
+ nil ; case-fold
+ nil ; syntax-alist
+ nil ; syntax-begin
+ (cons 'font-lock-syntax-table caml-font-syntax-table)
+ '(font-lock-extend-after-change-region-function
+ . caml-font-extend-after-change)
+ '(font-lock-syntactic-face-function . caml-font-syntactic-face)
+ ))
+ (caml-font-extend-after-change (point-min) (point-max) 0)
+ (font-lock-mode 1)
+)
+(add-hook 'caml-mode-hook 'caml-font-set-font-lock)
+
+
+
+(defconst inferior-caml-font-lock-keywords
+ `(("^[#-]" . font-lock-comment-face)
+ ,@caml-font-lock-keywords))
+
+(defun inferior-caml-set-font-lock ()
+ (setq parse-sexp-lookup-properties t)
+ (setq font-lock-defaults
+ (list
+ 'inferior-caml-font-lock-keywords ; keywords
+ nil ; keywords-only
+ nil ; case-fold
+ nil ; syntax-alist
+ nil ; syntax-begin
+ (cons 'font-lock-syntax-table caml-font-syntax-table)
+ '(font-lock-extend-after-change-region-function
+ . caml-font-extend-after-change)
+ '(font-lock-syntactic-face-function . caml-font-syntactic-face)
+ ))
+ (caml-font-extend-after-change (point-min) (point-max) 0)
+ (font-lock-mode 1)
+)
+(add-hook 'inferior-caml-mode-hooks 'inferior-caml-set-font-lock)
+
+(provide 'caml-font)
diff --git a/emacs/caml-help.el b/emacs/caml-help.el
new file mode 100644
index 0000000000..82defadc01
--- /dev/null
+++ b/emacs/caml-help.el
@@ -0,0 +1,854 @@
+;;; caml-help.el --- Contextual completion and help to caml-mode
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Didier Remy, projet Cristal, INRIA Rocquencourt *)
+;(* *)
+;(* Copyright 2001 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;; Author: Didier Remy, November 2001.
+
+;;; Commentary:
+
+;; This provides two functions: completion and help.
+;; Look for caml-complete and caml-help.
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;; This is a preliminary version.
+;;
+;; Possible improvements?
+;; - dump some databaes: Info, Lib, ...
+;; - accept a search path for local libraries instead of current dir
+;; (then distinguish between different modules lying in different
+;; directories)
+;; - improve the construction for info files.
+;;
+;; Abstract over
+;; - the viewing method and the database, so that the documentation for
+;; and identifier could be search in
+;; * info / html / man / mli's sources
+;; * viewed in Emacs or using an external previewer.
+;;
+;; Take all identifiers (labels, Constructors, exceptions, etc.)
+;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+;;; Code:
+
+(eval-and-compile
+ (if (featurep 'xemacs)
+ (require 'caml-xemacs)
+ (require 'caml-emacs)))
+
+;; Loading or building databases.
+;;
+
+;; variables to be customized
+
+(defvar ocaml-lib-path 'lazy
+ "Path list for ocaml lib sources (mli files).
+
+`lazy' means ask ocaml to find it for your at first use.")
+(defun ocaml-lib-path ()
+ "Compute if necessary and return the path for ocaml libs."
+ (if (listp ocaml-lib-path) nil
+ (setq ocaml-lib-path
+ (split-string
+ (shell-command-to-string
+ (or
+ (and (boundp 'inferior-caml-program)
+ (string-match "\\([^ ]*/ocaml\\)\\( \\|$\\)"
+ inferior-caml-program)
+ (let ((file
+ (concat (match-string 1 inferior-caml-program)
+ "c")))
+ (and (file-executable-p file)
+ (concat file " -where"))))
+ "ocamlc -where")))))
+ ocaml-lib-path)
+
+
+
+;; General purpose auxiliary functions
+
+(defun ocaml-capitalize (s)
+ (concat (capitalize (substring s 0 1)) (substring s 1)))
+
+(defun ocaml-uncapitalize (s)
+ (if (> (length s) 0)
+ (concat (downcase (substring s 0 1)) (substring s 1))
+ s))
+
+(defun ocaml-find-files (path filter &optional depth split)
+ (let* ((path-string
+ (if (stringp path)
+ (if (file-directory-p path) path nil)
+ (mapconcat (lambda (d) (if (file-directory-p d) d))
+ path " ")))
+ (command
+ (and path-string
+ (concat "find " path-string
+ " '(' " filter " ')' "
+ (if depth (concat " -maxdepth " (int-to-string depth)))
+ (if split nil " -printf '%\p '")
+ )))
+ (files
+ (and command (shell-command-to-string command))))
+ (if (and split (stringp files)) (split-string files "\n") files)
+ ))
+
+;; Specialized auxiliary functions
+
+
+;; Global table of modules contents of modules loaded lazily.
+
+(defvar ocaml-module-alist 'lazy
+ "A-list of modules with how and where to find help information.
+`delay' means non computed yet.")
+
+(defun ocaml-add-mli-modules (modules tag &optional path)
+ (let ((files
+ (ocaml-find-files (or path (ocaml-lib-path))
+ "-type f -name '*.mli'" 1 t)))
+ (while (consp files)
+ (if (string-match "\\([^/]*\\).mli" (car files))
+ (let* ((module (ocaml-capitalize (match-string 1 (car files))))
+ (dir (file-name-directory (car files)))
+ (dirp (member dir (ocaml-lib-path))))
+ (if (and (consp dirp) (string-equal dir (car dirp)))
+ (setq dir (car dirp)))
+ (if (assoc module modules) nil
+ (setq modules
+ (cons (cons module (cons (cons tag dir) 'lazy)) modules))
+ )))
+ (setq files (cdr files)))
+ modules))
+
+(defun ocaml-add-path (dir &optional path)
+ "Extend `ocaml-module-alist' with modules of DIR relative to PATH."
+ (interactive "D")
+ (let* ((old (ocaml-lib-path))
+ (new
+ (if (file-name-absolute-p dir) dir
+ (concat
+ (or (find-if (lambda (p) (file-directory-p (concat p "/" dir)))
+ (cons default-directory old))
+ (error "Directory not found"))
+ "/" dir))))
+ (setq ocaml-lib-path (cons (car old) (cons new (cdr old))))
+ (setq ocaml-module-alist
+ (ocaml-add-mli-modules (ocaml-module-alist) 'lib new))))
+
+(defun ocaml-module-alist ()
+ "Call by need value of variable `ocaml-module-alist'."
+ (if (listp ocaml-module-alist)
+ nil
+ ;; build list of mli files
+ (setq ocaml-module-alist (ocaml-add-mli-modules nil 'lib))
+ ;; dumping information ? TODO
+ )
+ ocaml-module-alist)
+
+(defun ocaml-get-or-make-module (module &optional tag)
+ (let ((info (assoc module (ocaml-module-alist))))
+ (if info nil
+ (setq info (cons module (cons (cons 'local default-directory) 'lazy)))
+ (setq ocaml-module-alist (cons info ocaml-module-alist))
+ )
+ info))
+
+;; Symbols of module are lazily computed
+
+(defun ocaml-module-filename (module)
+ (let ((module (ocaml-uncapitalize module)) (name))
+ (if (file-exists-p (setq name (concat module ".mli"))) nil
+ (let ((tmp (ocaml-lib-path)))
+ (while (consp tmp)
+ (setq name (concat (car tmp) "/" module ".mli"))
+ (if (file-exists-p name) (setq tmp nil)
+ (setq name nil)))))
+ name))
+
+(defun ocaml-module-symbols (module-info)
+ (let* ((module (car module-info))
+ (tail (and module-info (cdr module-info)))
+ (tag (caar tail))
+ (dir (cdar tail))
+ (file)
+ (alist))
+ (if (listp (cdr tail))
+ (cdr tail)
+ (if (equal tag 'info)
+ (setq dir (car ocaml-lib-path)) ; XXX to be fixed
+ )
+ (setq file (concat dir "/" (ocaml-uncapitalize module) ".mli"))
+ (message file)
+ (save-window-excursion
+ (set-buffer (get-buffer-create "*caml-help*"))
+ (if (and file (file-exists-p file))
+ (progn
+ (message "Scanning module %s" file)
+ (insert-file-contents file))
+ (message "Module %s not found" module))
+ (while (re-search-forward
+ "\\([ \t]*val\\|let\\|exception\\|external\\| [|]\\) \\([a-zA-Z_0-9'][a-zA-Z_0-9']*\\)\\|^ *[{]* \\([a-z_][A-Za-z_0-9]*\\) : [^;\n][^;\n]*;"
+ (point-max) 'move)
+ (pop-to-buffer (current-buffer))
+ (setq alist (cons (or (match-string 2) (match-string 3)) alist)))
+ (erase-buffer)
+ )
+ (setcdr tail alist)
+ alist)
+ ))
+
+;; Local list of visible modules.
+
+(defvar ocaml-visible-modules 'lazy
+ "A-list of open modules, local to every file.")
+(make-variable-buffer-local 'ocaml-visible-modules)
+(defun ocaml-visible-modules ()
+ (if (listp ocaml-visible-modules) nil
+ (progn
+ (setq ocaml-visible-modules
+ (list (ocaml-get-or-make-module "Pervasives")))
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward "^ *open *\\([A-Z][a-zA-Z'_0-9]*\\)"
+ (point-max) t)
+ (let ((module (match-string 1)))
+ (if (assoc module ocaml-visible-modules) nil
+ (setq ocaml-visible-modules
+ (cons (ocaml-get-or-make-module module)
+ ocaml-visible-modules)))))
+ )))
+ ocaml-visible-modules)
+
+(defun ocaml-open-module (arg)
+ "*Make module of name ARG visible whe ARG is a string.
+When call interactively, make completion over known modules."
+ (interactive "P")
+ (if (not (stringp arg))
+ (let ((modules (ocaml-module-alist)))
+ (setq arg
+ (completing-read "Open module: " modules))))
+ (if (and (stringp arg) (not (equal arg "")))
+ (progn
+ (if (assoc arg (ocaml-visible-modules))
+ (ocaml-close-module arg))
+ (setq ocaml-visible-modules
+ (cons (ocaml-get-or-make-module arg) (ocaml-visible-modules)))
+ ))
+ (message "%S" (mapcar 'car (ocaml-visible-modules))))
+
+(defun ocaml-close-module (arg)
+ "*Close module of name ARG when ARG is a string.
+When call interactively, make completion over visible modules.
+Otherwise if ARG is true, close all modules and reset to default."
+ (interactive "P")
+ (if (= (prefix-numeric-value arg) 4)
+ (setq ocaml-visible-modules 'lazy)
+ (let* ((modules (ocaml-visible-modules)))
+ (if (null modules) (error "No visible module to close"))
+ (unless (stringp arg)
+ (setq arg
+ (completing-read
+ (concat "Close module [" (caar modules) "] : ")
+ modules))
+ (if (equal arg "") (setq arg (caar modules))))
+ (setq ocaml-visible-modules
+ (remove-if (lambda (m) (equal (car m) arg))
+ ocaml-visible-modules))
+ ))
+ (message "%S" (mapcar 'car (ocaml-visible-modules))))
+
+
+;; Look for identifiers around point
+
+(defun ocaml-qualified-identifier (&optional show)
+ "Search for a qualified identifier (Path. entry) around point.
+
+Entry may be nil.
+Currently, the path may only be nil or a single Module.
+For paths is of the form Module.Path', it returns Module
+and always nil for entry.
+
+If defined Module and Entry are represented by a region in the buffer,
+and are nil otherwise.
+
+For debugging purposes, it returns the string Module.entry if called
+with an optional non-nil argument."
+ (save-excursion
+ (let ((module) (entry))
+ (if (looking-at "[ \n]") (skip-chars-backward " "))
+ (if (re-search-backward
+ "\\([^A-Za-z0-9_.']\\|\\`\\)\\([A-Za-z0-9_']*[.]\\)*[A-Za-z0-9_']*\\="
+ (- (point) 100) t)
+ (progn
+ (or (looking-at "\\`[A-Za-z)-9_.]") (forward-char 1))
+ (if (looking-at "\\<\\([A-Za-z_][A-Za-z0-9_']*\\)[.]")
+ (progn
+ (setq module (cons (match-beginning 1) (match-end 1)))
+ (goto-char (match-end 0))))
+ (if (looking-at "\\<\\([A-Za-z_][A-Za-z0-9_']*\\)\\>")
+ (setq entry (cons (match-beginning 1) (match-end 1))))))
+ (if show
+ (concat
+ (and module (buffer-substring (car module) (cdr module)))
+ "."
+ (and entry (buffer-substring (car entry) (cdr entry))))
+ (cons module entry))
+ )))
+
+;; completion around point
+
+(defun ocaml-completion (pattern module)
+ (let ((list
+ (or
+ (and module
+ (list
+ (or (assoc module (ocaml-module-alist))
+ (error "Unknown module %s" module))))
+ (ocaml-visible-modules))))
+ (message "Completion from %s" (mapconcat 'car list " "))
+ (if (null pattern)
+ (apply 'append (mapcar 'ocaml-module-symbols list))
+ (let ((pat (concat "^" (regexp-quote pattern))) (res))
+ (mapc
+ (lambda (l)
+ (mapc (lambda (x)
+ (if (string-match pat (car l))
+ (if (member x res) nil (setq res (cons x res)))))
+ (ocaml-module-symbols l)))
+ list)
+ res)
+ )))
+
+(defun caml-complete (arg)
+ "Does completion for OCaml identifiers qualified.
+
+It attemps to recognize an qualified identifier Module . entry
+around point using function \\[ocaml-qualified-identifier].
+
+If Module is defined, it does completion for identifier in Module.
+
+If Module is undefined, it does completion in visible modules.
+Then, if completion fails, it does completion among all modules
+where identifier is defined."
+ (interactive "p")
+ (let* ((module-entry (ocaml-qualified-identifier)) (entry)
+ (module)
+ (beg) (end) (pattern))
+ (if (car module-entry)
+ (progn
+ (setq module
+ (buffer-substring (caar module-entry) (cdar module-entry)))
+ (or (assoc module (ocaml-module-alist))
+ (and (setq module
+ (completing-read "Module: " (ocaml-module-alist)
+ nil nil module))
+ (save-excursion
+ (goto-char (caar module-entry))
+ (delete-region (caar module-entry) (cdar module-entry))
+ (insert module) t)
+ (setq module-entry (ocaml-qualified-identifier))
+ (car module-entry)
+ (progn (setq entry (cdr module-entry)) t))
+ (error "Unknown module %s" module))))
+ (if (consp (cdr module-entry))
+ (progn
+ (setq beg (cadr module-entry))
+ (setq end (cddr module-entry)))
+ (if (and module
+ (save-excursion
+ (goto-char (cdar module-entry))
+ (looking-at " *[.]")))
+ (progn
+ (setq beg (match-end 0))
+ (setq end beg))))
+ (if (not (and beg end))
+ (error "Did not find anything to complete around point")
+
+ (setq pattern (buffer-substring beg end))
+ (let* ((all-completions (ocaml-completion pattern module))
+ (completion
+ (try-completion pattern (mapcar 'list all-completions))))
+ (cond ((eq completion t))
+
+ ((null completion)
+ (let*
+ ((modules (ocaml-find-module pattern))
+ (visible (intersection modules (ocaml-visible-modules)))
+ (hist)
+ (module
+ (cond
+ ((null modules)
+ nil)
+ ((equal (length modules) 1)
+ (caar modules))
+ ((equal (length visible) 1)
+ (caar visible))
+ (t
+ (setq hist (mapcar 'car modules))
+ (completing-read "Module: " modules nil t
+ "" (cons hist 0)))
+ )))
+ (if (null module)
+ (error "Can't find completion for \"%s\"" pattern)
+ (message "Completion found in module %s" module)
+ (if (and (consp module-entry) (consp (cdr module-entry)))
+ (delete-region (caar module-entry) end)
+ (delete-region beg end))
+ (insert module "." pattern))))
+
+ ((not (string-equal pattern completion))
+ (delete-region beg end)
+ (goto-char beg)
+ (insert completion))
+
+ (t
+ (with-output-to-temp-buffer "*Completions*"
+ (display-completion-list all-completions))
+ ))
+ ))))
+
+
+;; Info files (only in ocamldoc style)
+
+
+(defvar ocaml-info-prefix "ocaml-lib"
+ "Prefix of ocaml info files describing library modules.
+Suffix .info will be added to info files.
+Additional suffix .gz may be added if info files are compressed.")
+;;
+
+(defun ocaml-hevea-info-add-entries (entries dir name)
+ (let*
+ ((filter
+ (concat "-type f -regex '.*/" name
+ "\\(.info\\|\\)\\(-[0-9]*\\|\\)\\([.]gz\\|\\)'"
+ ))
+ (section-regexp
+ "\\* \\(Section [1-9][0-9--]*\\)::[ \t][ \t]*Module *\\([A-Z][A-Za-z_0-9]*\\)")
+ (files (ocaml-find-files dir filter))
+ (command))
+ ;; scanning info files
+ (if (or (null files)
+ (not (stringp files))
+ (string-match files "^ *$"))
+ (message "No info file found: %s." (mapconcat 'identity files " "))
+ (message "Scanning info files %s." files)
+ (save-window-excursion
+ (set-buffer (get-buffer-create "*caml-help*"))
+ (setq command
+ (concat "zcat -f " files
+ " | grep -e '" section-regexp "'"))
+ (message "Scanning files with: %s" command)
+ (or (shell-command command (current-buffer))
+ (error "Error while scanning"))
+ (goto-char (point-min))
+ (while (re-search-forward section-regexp (point-max) t)
+ (let* ((module (match-string 2))
+ (section (match-string 1)))
+ ;; (message "%s %s" module section)
+ (if (assoc module entries) nil
+ (setq entries
+ (cons (cons module (concat "(" name ")" section))
+ entries))
+ )))
+ (let ((buf (get-buffer "*caml-help*")))
+ (if buf (kill-buffer buf)))))
+ entries))
+
+(defun ocaml-hevea-info ()
+ "The default way to create an info data base from the value
+of \\[Info-default-directory-list] and the base name \\[ocaml-info-name]
+of files to look for.
+
+This uses info files produced by HeVeA."
+ (let ((collect) (seen))
+ (mapc (lambda (d)
+ (if (member d seen) nil
+ (setq collect
+ (ocaml-hevea-info-add-entries
+ collect d ocaml-info-prefix))
+ (setq seen (cons d seen))))
+ Info-directory-list)
+ collect))
+
+(defun ocaml-ocamldoc-info-add-entries (entries dir name)
+ (let*
+ ((module-regexp "^Node: \\([A-Z][A-Za-z_0-9]*\\)[^ ]")
+ (command
+ (concat
+ "find " dir " -type f -regex '.*/" name
+ "\\(.info\\|\\)\\([.]gz\\|\\)' -print0"
+ " | xargs -0 zcat -f | grep '" module-regexp "'")))
+ (message "Scanning info files in %s" dir)
+ (save-window-excursion
+ (set-buffer (get-buffer-create "*caml-help*"))
+ (or (shell-command command (current-buffer))
+ (error "Could not run:%s" command))
+ (goto-char (point-min))
+ (while (re-search-forward module-regexp (point-max) t)
+ (if (equal (char-after (match-end 1)) 127)
+ (let* ((module (match-string 1)))
+ (if (assoc module entries) nil
+ (setq entries
+ (cons (cons module (concat "(" name ")" module))
+ entries))
+ ))))
+ ; (kill-buffer (current-buffer))
+ )
+ entries))
+
+(defun ocaml-ocamldoc-info ()
+ "The default way to create an info data base from the value
+of \\[Info-default-directory-list] and the base name \\[ocaml-info-name]
+of files to look for.
+
+This uses info files produced by ocamldoc."
+ (require 'info)
+ (let ((collect) (seen))
+ (mapc (lambda (d)
+ (if (member d seen) nil
+ (setq collect
+ (ocaml-ocamldoc-info-add-entries collect d
+ ocaml-info-prefix))
+ (setq seen (cons d seen))))
+ Info-directory-list)
+ collect))
+
+;; Continuing
+
+(defvar ocaml-info-alist 'ocaml-ocamldoc-info
+ "A-list binding module names to info entries:
+
+ nil means do not use info.
+
+ A function to build the list lazily (at the first call). The result of
+the function call will be assign permanently to this variable for future
+uses. We provide two default functions `ocaml-hevea-info'
+\(info produced by HeVeA is the default) and `ocaml-ocamldoc-info'
+\(info produced by ocamldoc).
+
+ Otherwise, this value should be an alist binding module names to info
+entries of the form to \"(entry)section\" be taken by the \\[info]
+command. An entry may be an info module or a complete file name."
+)
+
+(defun ocaml-info-alist ()
+ "Call by need value of variable `ocaml-info-alist'."
+ (cond
+ ((listp ocaml-info-alist))
+ ((functionp ocaml-info-alist)
+ (setq ocaml-info-alist (apply ocaml-info-alist nil)))
+ (t
+ (error "wrong type for ocaml-info-alist")))
+ ocaml-info-alist)
+
+;; help around point
+
+(defun ocaml-find-module (symbol &optional module-list)
+ (let ((list (or module-list (ocaml-module-alist)))
+ (collect))
+ (while (consp list)
+ (if (member symbol (ocaml-module-symbols (car list)))
+ (setq collect (cons (car list) collect)))
+ (setq list (cdr list)))
+ (nreverse collect)
+ ))
+
+(defun ocaml-buffer-substring (region)
+ (and region (buffer-substring-no-properties (car region) (cdr region))))
+
+;; Help function.
+
+(defvar view-return-to-alist)
+(defvar view-exit-action)
+
+(defun ocaml-goto-help (&optional module entry same-window)
+ "Search info manual for MODULE and ENTRY in MODULE.
+If unspecified, MODULE and ENTRY are inferred from the position in the
+current buffer using \\[ocaml-qualified-identifier]."
+ (interactive)
+ (let ((window (selected-window))
+ (info-section (assoc module (ocaml-info-alist))))
+ (if info-section
+ (caml-info-other-window (cdr info-section))
+ (ocaml-visible-modules)
+ (let* ((module-info
+ (or (assoc module (ocaml-module-alist))
+ (and (file-exists-p
+ (concat (ocaml-uncapitalize module) ".mli"))
+ (ocaml-get-or-make-module module))))
+ (location (cdr (cadr module-info))))
+ (cond
+ (location
+ (let ((file (concat location (ocaml-uncapitalize module) ".mli")))
+ (if (window-live-p same-window)
+ (progn (select-window same-window)
+ (view-mode-exit view-return-to-alist view-exit-action))
+ ;; (view-buffer (find-file-noselect file) 'view))
+ )
+ (view-file-other-window file)
+ (bury-buffer (current-buffer))))
+ (info-section (error "Aborted"))
+ (t (error "No help for module %s" module))))
+ )
+ (if (stringp entry)
+ (let ((here (point))
+ (regex (regexp-quote entry))
+ (case-fold-search nil))
+ (goto-char (point-min))
+ (if (or (re-search-forward
+ (concat "\\(val\\|exception\\|type\\|external\\|[|{;]\\) +"
+ regex)
+ ;; (concat "\\(val\\|exception\\|external\\) +\\("
+ ;; regex "\\|( *" regex " *)\\)")
+ (point-max) t)
+ (re-search-forward
+ (concat "type [^{]*{[^}]*" regex " :")
+ ;; (concat "\\(type\\|[|{;]\\) +" regex)
+ (point-max) t)
+ (progn
+ (if (window-live-p window) (select-window window))
+ (error "Entry %s not found in module %s"
+ entry module))
+ ;; (search-forward entry (point-max) t)
+ )
+ (ocaml-help-show -1)
+ (progn
+ (message "Help for entry %s not found in module %s"
+ entry module)
+ (goto-char here)))
+ ))
+ (ocaml-link-activate (cdr info-section))
+ (if (window-live-p window) (select-window window))
+ ))
+
+(defface ocaml-help-face
+ '((t :background "#88FF44"))
+ "Face to highlight expressions and types.")
+
+(defvar ocaml-help-ovl
+ (let ((ovl (make-overlay 1 1)))
+ (overlay-put ovl 'face 'ocaml-help-face)
+ ovl))
+
+(defun caml-help (arg)
+ "Find documentation for OCaml qualified identifiers.
+
+It attemps to recognize an qualified identifier of the form
+``Module . entry'' around point using function `ocaml-qualified-identifier'.
+
+If Module is undetermined it is temptatively guessed from the identifier name
+and according to visible modules. If this is still unsucessful, the user is
+then prompted for a Module name.
+
+The documentation for Module is first seach in the info manual if available,
+then in the ``module.mli'' source file. The entry is then searched in the
+documentation.
+
+Visible modules are computed only once, at the first call.
+Modules can be made visible explicitly with `ocaml-open-module' and
+hidden with `ocaml-close-module'.
+
+Prefix arg 0 forces recompilation of visible modules (and their content)
+from the file content.
+
+Prefix arg 4 prompts for Module and identifier instead of guessing values
+from the possition of point in the current buffer."
+ (interactive "p")
+ (delete-overlay ocaml-help-ovl)
+ (let ((module) (entry) (module-entry))
+ (cond
+ ((= arg 4)
+ (or (and
+ (setq module
+ (completing-read "Module: " (ocaml-module-alist)
+ nil t "" (cons 'hist 0)))
+ (not (string-equal module "")))
+ (error "Quit"))
+ (let ((symbols
+ (mapcar 'list
+ (ocaml-module-symbols
+ (assoc module (ocaml-module-alist))))))
+ (setq entry
+ (completing-read (format "Value: %s." module) symbols nil t)))
+ (if (string-equal entry "") (setq entry nil))
+ )
+ (t
+ (if (= arg 0) (setq ocaml-visible-modules 'lazy))
+ (setq module-entry (ocaml-qualified-identifier))
+ (setq entry (ocaml-buffer-substring (cdr module-entry)))
+ (setq module
+ (or (ocaml-buffer-substring (car module-entry))
+ (let ((modules
+ (or (ocaml-find-module entry (ocaml-visible-modules))
+ (ocaml-find-module entry)))
+ (hist) (default))
+ (cond
+ ((null modules)
+ (error "No module found for entry %s" entry))
+ ((equal (length modules) 1)
+ (caar modules))
+ (t
+ (setq hist (mapcar 'car modules))
+ (setq default (car hist))
+ (setq module
+ (completing-read
+ (concat "Module: "
+ (and default (concat "[" default "] ")))
+ modules nil t "" (cons 'hist 0)))
+ (if (string-equal module "") default module))
+ ))))
+ ))
+ (message "Help for %s%s%s" module (if entry "." "") (or entry ""))
+ (ocaml-goto-help module entry)
+ ))
+
+;; auto-links
+
+(defconst ocaml-link-regexp
+ "\\(type\\|and\\) \\('[a-z] +\\|(\\('[a-z], *\\)*'[a-z])\\|\\) *\\([a-zA-Z0-9_]*\\)\\( *$\\| =\\)")
+(defconst ocaml-longident-regexp
+ "\\([A-Z][a-zA-Z_0]*\\)[.]\\([a-zA-Z][A-Za-z0-9_]*\\)")
+
+(defvar ocaml-links nil
+ "Local links in the current of last info node or interface file.
+
+The car of the list is a key that indentifies the module to prevent
+recompilation when next help command is relative to the same module.
+The cdr is a list of elments, each of which is an string and a pair of
+buffer positions."
+)
+(make-variable-buffer-local 'ocaml-links)
+
+(defun ocaml-info-links (section)
+ (cdr
+ (if (and ocaml-links section (equal (car ocaml-links) section))
+ ocaml-links
+ (save-excursion
+ (goto-char (point-min))
+ (let ((regexp (concat (if (equal major-mode 'Info-mode) "^ - " "^")
+ ocaml-link-regexp))
+ (all))
+ (while (re-search-forward regexp (point-max) t)
+ (setq all
+ (cons (cons (match-string 4)
+ (cons (match-beginning 4)
+ (match-end 4)))
+ all)))
+ (setq ocaml-links (cons section all))
+ )))))
+
+(defvar ocaml-link-map
+ (let ((map (make-sparse-keymap)))
+ (define-key map [mouse-2] 'ocaml-link-goto)
+ map))
+
+(defun ocaml-help-show (arg)
+ (let ((right (point))
+ (left (progn (forward-word arg) (point))))
+ (goto-char right)
+ (move-overlay ocaml-help-ovl left right (current-buffer))
+ (recenter 1)
+ ))
+
+(defun ocaml-link-goto (click)
+ "Follow link at point."
+ (interactive "e")
+ (let* ((pos (caml-event-point-start click))
+ (win (caml-event-window click))
+ (buf (window-buffer win))
+ (window (selected-window))
+ (link))
+ (setq link
+ (with-current-buffer buf
+ (buffer-substring
+ (previous-single-property-change (+ pos 1) 'local-map
+ buf (- pos 100))
+ (next-single-property-change pos 'local-map
+ buf (+ pos 100)))))
+ (if (string-match (concat "^" ocaml-longident-regexp "$") link)
+ (ocaml-goto-help (match-string 1 link) (match-string 2 link) win)
+ (if (not (equal (window-buffer window) buf))
+ (switch-to-buffer-other-window buf))
+ (if (setq link (assoc link (cdr ocaml-links)))
+ (progn
+ (goto-char (cadr link))
+ (ocaml-help-show 1)))
+ (if (window-live-p window) (select-window window))
+ )))
+
+
+(defface ocaml-link-face
+ '((((class color)) :foreground "Purple"))
+ "Face to highlight hyperlinks.")
+
+(defun ocaml-link-activate (section)
+ (let ((links (ocaml-info-links section)))
+ (if links
+ (let ((regexp (concat "[^A-Za-z0-9'_]\\("
+ ocaml-longident-regexp "\\|"
+ (mapconcat 'car links "\\|")
+ "\\)[^A-Za-z0-9'_]"))
+ (case-fold-search nil))
+ (save-excursion
+ (goto-char (point-min))
+ (let ((buffer-read-only nil)
+ ;; use of dynamic scoping, need not be restored!
+ (modified-p (buffer-modified-p)))
+ (unwind-protect
+ (save-excursion
+ (goto-char (point-min))
+ (while (re-search-forward regexp (point-max) t)
+ (put-text-property (match-beginning 1) (match-end 1)
+ 'mouse-face 'highlight)
+ (put-text-property (match-beginning 1) (match-end 1)
+ 'local-map ocaml-link-map)
+ (if (x-display-color-p)
+ (put-text-property (match-beginning 1) (match-end 1)
+ 'face 'ocaml-link-face)))
+ )
+ ;; need to restore flag if buffer was unmodified.
+ (unless modified-p (set-buffer-modified-p nil))
+ ))
+ )))))
+
+
+
+;; bindings ---now in caml.el
+
+; (and
+; (boundp 'caml-mode-map)
+; (keymapp caml-mode-map)
+; (progn
+; (define-key caml-mode-map [?\C-c?i] 'ocaml-add-path)
+; (define-key caml-mode-map [?\C-c?]] 'ocaml-close-module)
+; (define-key caml-mode-map [?\C-c?[] 'ocaml-open-module)
+; (define-key caml-mode-map [?\C-c?\C-h] 'caml-help)
+; (define-key caml-mode-map [?\C-c?\t] 'caml-complete)
+; (let ((map (lookup-key caml-mode-map [menu-bar caml])))
+; (and
+; (keymapp map)
+; (progn
+; (define-key map [separator-help] '("---"))
+; (define-key map [open] '("Open add path" . ocaml-add-path ))
+; (define-key map [close]
+; '("Close module for help" . ocaml-close-module))
+; (define-key map [open] '("Open module for help" . ocaml-open-module))
+; (define-key map [help] '("Help for identifier" . caml-help))
+; (define-key map [complete] '("Complete identifier" . caml-complete))
+; )
+; ))))
+
+
+(provide 'caml-help)
+;;; caml-help.el ends here
diff --git a/emacs/caml-hilit.el b/emacs/caml-hilit.el
new file mode 100644
index 0000000000..13735594fd
--- /dev/null
+++ b/emacs/caml-hilit.el
@@ -0,0 +1,65 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Jacques Garrigue and Ian T Zimmerman *)
+;(* *)
+;(* Copyright 1997 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+; Highlighting patterns for hilit19 under caml-mode
+
+; defined also in caml.el
+(defvar caml-quote-char "'"
+ "*Quote for character constants. \"'\" for OCaml, \"`\" for Caml-Light.")
+
+(defconst caml-mode-patterns
+ (list
+;comments
+ '("\\(^\\|[^\"]\\)\\((\\*[^*]*\\*+\\([^)*][^*]*\\*+\\)*)\\)"
+ 2 comment)
+;string
+ (list 'hilit-string-find (string-to-char caml-quote-char) 'string)
+ (list (concat caml-quote-char "\\(\\\\\\([ntbr" caml-quote-char "\\]\\|"
+ "[0-9][0-9][0-9]\\)\\|.\\)" caml-quote-char)
+ nil
+ 'string)
+;labels
+ '("\\(\\([~?]\\|\\<\\)[a-z][a-zA-Z0-9_']*:\\)[^:=]" 1 brown)
+ '("[~?][ (]*[a-z][a-zA-Z0-9_']*" nil brown)
+;modules
+ '("\\<\\(assert\\|open\\|include\\)\\>" nil brown)
+ '("`?\\<[A-Z][A-Za-z0-9_\']*\\>" nil MidnightBlue)
+;definition
+ (list (concat
+ "\\<\\(a\\(nd\\|s\\)\\|c\\(onstraint\\|lass\\)"
+ "\\|ex\\(ception\\|ternal\\)\\|fun\\(ct\\(ion\\|or\\)\\)?"
+ "\\|in\\(herit\\)?\\|let\\|m\\(ethod\\|utable\\|odule\\)"
+ "\\|of\\|p\\(arser\\|rivate\\)\\|rec\\|type"
+ "\\|v\\(al\\|irtual\\)\\)\\>")
+ nil 'ForestGreen)
+;blocking
+ '("\\<\\(object\\|struct\\|sig\\|begin\\|end\\)\\>" 2 include)
+;control
+ (list (concat
+ "\\<\\(do\\(ne\\|wnto\\)?\\|else\\|for\\|i\\(f\\|gnore\\)"
+ "\\|lazy\\|match\\|new\\|or\\|t\\(hen\\|o\\|ry\\)"
+ "\\|w\\(h\\(en\\|ile\\)\\|ith\\)\\)\\>"
+ "\\|\|\\|->\\|&\\|#")
+ nil 'keyword)
+ '(";" nil struct))
+ "Hilit19 patterns used for OCaml mode")
+
+(hilit-set-mode-patterns 'caml-mode caml-mode-patterns)
+(hilit-set-mode-patterns
+ 'inferior-caml-mode
+ (append
+ (list
+;inferior
+ '("^[#-]" nil firebrick))
+ caml-mode-patterns))
+
+(provide 'caml-hilit)
diff --git a/emacs/caml-types.el b/emacs/caml-types.el
new file mode 100644
index 0000000000..0af667bdd2
--- /dev/null
+++ b/emacs/caml-types.el
@@ -0,0 +1,793 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+;(* *)
+;(* Copyright 2003 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+; An emacs-lisp complement to the "-annot" option of ocamlc and ocamlopt.
+
+;; XEmacs compatibility
+
+(eval-and-compile
+ (if (and (boundp 'running-xemacs) running-xemacs)
+ (require 'caml-xemacs)
+ (require 'caml-emacs)))
+
+
+(defvar caml-types-build-dirs '("_build" "_obuild")
+ "List of possible compilation directories created by build systems.
+It is expected that the files under `caml-types-build-dir' preserve
+the paths relative to the parent directory of `caml-types-build-dir'.")
+(make-variable-buffer-local 'caml-types-build-dir)
+
+(defvar caml-annot-dir nil
+ "A directory, generally relative to the file location, containing the
+.annot file. Intended to be set as a local variable in the .ml file.
+See \"Specifying File Variables\" in the Emacs info manual.")
+(make-variable-buffer-local 'caml-annot-dir)
+(put 'caml-annot-dir 'safe-local-variable #'stringp)
+
+(defvar caml-types-location-re nil "Regexp to parse *.annot files.
+
+Annotation files *.annot may be generated with the \"-annot\" option
+of ocamlc and ocamlopt.
+
+Their format is:
+
+ file ::= block *
+ block ::= position <SP> position <LF> annotation *
+ position ::= filename <SP> num <SP> num <SP> num
+ annotation ::= keyword open-paren <LF> <SP> <SP> data <LF> close-paren <LF>
+
+ <SP> is a space character (ASCII 0x20)
+ <LF> is a line-feed character (ASCII 0x0A)
+ num is a sequence of decimal digits
+ filename is a string with the lexical conventions of OCaml
+ open-paren is an open parenthesis (ASCII 0x28)
+ close-paren is a closed parenthesis (ASCII 0x29)
+ data is any sequence of characters where <LF> is always followed by
+ at least two space characters.
+
+- in each block, the two positions are respectively the start and the
+ end of the range described by the block.
+- in a position, the filename is the name of the file, the first num
+ is the line number, the second num is the offset of the beginning
+ of the line, the third num is the offset of the position itself.
+- the char number within the line is the difference between the third
+ and second nums.
+
+The current list of keywords is:
+type call ident"
+)
+
+(defvar caml-types-position-re nil)
+
+(let* ((caml-types-filename-re "\"\\(\\([^\\\"]\\|\\\\.\\)*\\)\"")
+ (caml-types-number-re "\\([0-9]*\\)"))
+ (setq caml-types-position-re
+ (concat caml-types-filename-re " "
+ caml-types-number-re " "
+ caml-types-number-re " "
+ caml-types-number-re))
+ (setq caml-types-location-re
+ (concat "^" caml-types-position-re " " caml-types-position-re)))
+
+(defvar caml-types-expr-ovl (make-overlay 1 1))
+(make-face 'caml-types-expr-face)
+(set-face-doc-string 'caml-types-expr-face
+ "face for hilighting expressions and types")
+(if (not (face-differs-from-default-p 'caml-types-expr-face))
+ (set-face-background 'caml-types-expr-face "#88FF44"))
+(overlay-put caml-types-expr-ovl 'face 'caml-types-expr-face)
+
+(defvar caml-types-typed-ovl (make-overlay 1 1))
+(make-face 'caml-types-typed-face)
+(set-face-doc-string 'caml-types-typed-face
+ "face for hilighting typed expressions")
+(if (not (face-differs-from-default-p 'caml-types-typed-face))
+ (set-face-background 'caml-types-typed-face "#FF8844"))
+(overlay-put caml-types-typed-ovl 'face 'caml-types-typed-face)
+
+(defvar caml-types-scope-ovl (make-overlay 1 1))
+(make-face 'caml-types-scope-face)
+(set-face-doc-string 'caml-types-scope-face
+ "face for hilighting variable scopes")
+(if (not (face-differs-from-default-p 'caml-types-scope-face))
+ (set-face-background 'caml-types-scope-face "#BBFFFF"))
+(overlay-put caml-types-scope-ovl 'face 'caml-types-scope-face)
+
+(defvar caml-types-def-ovl (make-overlay 1 1))
+(make-face 'caml-types-def-face)
+(set-face-doc-string 'caml-types-def-face
+ "face for hilighting binding occurrences")
+(if (not (face-differs-from-default-p 'caml-types-def-face))
+ (set-face-background 'caml-types-def-face "#FF4444"))
+(overlay-put caml-types-def-ovl 'face 'caml-types-def-face)
+
+(defvar caml-types-occ-ovl (make-overlay 1 1))
+(make-face 'caml-types-occ-face)
+(set-face-doc-string 'caml-types-occ-face
+ "face for hilighting variable occurrences")
+(if (not (face-differs-from-default-p 'caml-types-occ-face))
+ (set-face-background 'caml-types-occ-face "#44FF44"))
+(overlay-put caml-types-occ-ovl 'face 'caml-types-occ-face)
+
+
+(defvar caml-types-annotation-tree nil)
+(defvar caml-types-annotation-date nil)
+(make-variable-buffer-local 'caml-types-annotation-tree)
+(make-variable-buffer-local 'caml-types-annotation-date)
+
+(defvar caml-types-buffer-name "*caml-types*"
+ "Name of buffer for displaying caml types")
+(defvar caml-types-buffer nil
+ "buffer for displaying caml types")
+
+(defun caml-types-show-type (arg)
+ "Show the type of expression or pattern at point.
+ The smallest expression or pattern that contains point is
+ temporarily highlighted. Its type is highlighted in the .annot
+ file and the mark is set to the beginning of the type.
+ The type is also displayed in the mini-buffer.
+
+ Hints on using the type display:
+ . If you want the type of an identifier, put point within any
+ occurrence of this identifier.
+ . If you want the result type of a function application, put point
+ at the first space after the function name.
+ . If you want the type of a list, put point on a bracket, on a
+ semicolon, or on the :: constructor.
+ . Even if type checking fails, you can still look at the types
+ in the file, up to where the type checker failed.
+
+Types are also displayed in the buffer *caml-types*, which is
+displayed when the command is called with Prefix argument 4.
+
+See also `caml-types-explore' for exploration by mouse dragging.
+See `caml-types-location-re' for annotation file format.
+"
+ (interactive "p")
+ (let* ((target-buf (current-buffer))
+ (target-file (file-name-nondirectory (buffer-file-name)))
+ (target-line (1+ (count-lines (point-min)
+ (caml-line-beginning-position))))
+ (target-bol (caml-line-beginning-position))
+ (target-cnum (point)))
+ (caml-types-preprocess (buffer-file-name))
+ (setq caml-types-buffer (get-buffer-create caml-types-buffer-name))
+ (let* ((targ-loc (vector target-file target-line target-bol target-cnum))
+ (node (caml-types-find-location targ-loc "type" ()
+ caml-types-annotation-tree)))
+ (cond
+ ((null node)
+ (delete-overlay caml-types-expr-ovl)
+ (message "Point is not within a typechecked expression or pattern."))
+ (t
+ (let ((left (caml-types-get-pos target-buf (elt node 0)))
+ (right (caml-types-get-pos target-buf (elt node 1)))
+ (type (cdr (assoc "type" (elt node 2)))))
+ (move-overlay caml-types-expr-ovl left right target-buf)
+ (with-current-buffer caml-types-buffer
+ (erase-buffer)
+ (insert type)
+ (message (format "type: %s" type)))
+ ))))
+ (if (and (= arg 4)
+ (not (window-live-p (get-buffer-window caml-types-buffer))))
+ (display-buffer caml-types-buffer))
+ (unwind-protect
+ (caml-sit-for 60)
+ (delete-overlay caml-types-expr-ovl)
+ )))
+
+(defun caml-types-show-call (arg)
+ "Show the kind of call at point.
+ The smallest function call that contains point is
+ temporarily highlighted. Its kind is highlighted in the .annot
+ file and the mark is set to the beginning of the kind.
+ The kind is also displayed in the mini-buffer.
+
+The kind is also displayed in the buffer *caml-types*, which is
+displayed when the command is called with Prefix argument 4.
+
+See `caml-types-location-re' for annotation file format.
+"
+ (interactive "p")
+ (let* ((target-buf (current-buffer))
+ (target-file (file-name-nondirectory (buffer-file-name)))
+ (target-line (1+ (count-lines (point-min)
+ (caml-line-beginning-position))))
+ (target-bol (caml-line-beginning-position))
+ (target-cnum (point)))
+ (caml-types-preprocess (buffer-file-name))
+ (setq caml-types-buffer (get-buffer-create caml-types-buffer-name))
+ (let* ((targ-loc (vector target-file target-line target-bol target-cnum))
+ (node (caml-types-find-location targ-loc "call" ()
+ caml-types-annotation-tree)))
+ (cond
+ ((null node)
+ (delete-overlay caml-types-expr-ovl)
+ (message "Point is not within a function call."))
+ (t
+ (let ((left (caml-types-get-pos target-buf (elt node 0)))
+ (right (caml-types-get-pos target-buf (elt node 1)))
+ (kind (cdr (assoc "call" (elt node 2)))))
+ (move-overlay caml-types-expr-ovl left right target-buf)
+ (with-current-buffer caml-types-buffer
+ (erase-buffer)
+ (insert kind)
+ (message (format "%s call" kind)))
+ ))))
+ (if (and (= arg 4)
+ (not (window-live-p (get-buffer-window caml-types-buffer))))
+ (display-buffer caml-types-buffer))
+ (unwind-protect
+ (caml-sit-for 60)
+ (delete-overlay caml-types-expr-ovl)
+ )))
+
+(defun caml-types-show-ident (arg)
+ "Show the binding of identifier at point.
+ The identifier that contains point is
+ temporarily highlighted. Its binding is highlighted in the .annot
+ file and the mark is set to the beginning of the binding.
+ The binding is also displayed in the mini-buffer.
+
+The binding is also displayed in the buffer *caml-types*, which is
+displayed when the command is called with Prefix argument 4.
+
+See `caml-types-location-re' for annotation file format.
+"
+ (interactive "p")
+ (let* ((target-buf (current-buffer))
+ (target-file (file-name-nondirectory (buffer-file-name)))
+ (target-line (1+ (count-lines (point-min)
+ (caml-line-beginning-position))))
+ (target-bol (caml-line-beginning-position))
+ (target-cnum (point)))
+ (caml-types-preprocess (buffer-file-name))
+ (setq caml-types-buffer (get-buffer-create caml-types-buffer-name))
+ (let* ((targ-loc (vector target-file target-line target-bol target-cnum))
+ (node (caml-types-find-location targ-loc "ident" ()
+ caml-types-annotation-tree)))
+ (cond
+ ((null node)
+ (delete-overlay caml-types-expr-ovl)
+ (message "Point is not within an identifier."))
+ (t
+ (let ((left (caml-types-get-pos target-buf (elt node 0)))
+ (right (caml-types-get-pos target-buf (elt node 1)))
+ (kind (cdr (assoc "ident" (elt node 2)))))
+ (move-overlay caml-types-expr-ovl left right target-buf)
+ (let* ((loc-re (concat caml-types-position-re " "
+ caml-types-position-re))
+ (end-re (concat caml-types-position-re " --"))
+ (def-re (concat "def \\([^ ]*\\) " loc-re))
+ (def-end-re (concat "def \\([^ ]*\\) " end-re))
+ (internal-re (concat "int_ref \\([^ ]*\\) " loc-re))
+ (external-re "ext_ref \\(.*\\)"))
+ (cond
+ ((string-match def-re kind)
+ (let ((var-name (match-string 1 kind))
+ (l-file (file-name-nondirectory (match-string 2 kind)))
+ (l-line (caml-string-to-int (match-string 4 kind)))
+ (l-bol (caml-string-to-int (match-string 5 kind)))
+ (l-cnum (caml-string-to-int (match-string 6 kind)))
+ (r-file (file-name-nondirectory (match-string 7 kind)))
+ (r-line (caml-string-to-int (match-string 9 kind)))
+ (r-bol (caml-string-to-int (match-string 10 kind)))
+ (r-cnum (caml-string-to-int (match-string 11 kind))))
+ (let* ((lpos (vector l-file l-line l-bol l-cnum))
+ (rpos (vector r-file r-line r-bol r-cnum))
+ (left (caml-types-get-pos target-buf lpos))
+ (right (caml-types-get-pos target-buf rpos)))
+ (message (format "local variable %s is bound here" var-name))
+ (move-overlay caml-types-scope-ovl left right target-buf))))
+ ((string-match def-end-re kind)
+ (let ((var-name (match-string 1 kind))
+ (l-file (file-name-nondirectory (match-string 2 kind)))
+ (l-line (caml-string-to-int (match-string 4 kind)))
+ (l-bol (caml-string-to-int (match-string 5 kind)))
+ (l-cnum (caml-string-to-int (match-string 6 kind))))
+ (let* ((lpos (vector l-file l-line l-bol l-cnum))
+ (left (caml-types-get-pos target-buf lpos))
+ (right (buffer-size target-buf)))
+ (message (format "global variable %s is bound here" var-name))
+ (move-overlay caml-types-scope-ovl left right target-buf))))
+ ((string-match internal-re kind)
+ (let ((var-name (match-string 1 kind))
+ (l-file (file-name-nondirectory (match-string 2 kind)))
+ (l-line (caml-string-to-int (match-string 4 kind)))
+ (l-bol (caml-string-to-int (match-string 5 kind)))
+ (l-cnum (caml-string-to-int (match-string 6 kind)))
+ (r-file (file-name-nondirectory (match-string 7 kind)))
+ (r-line (caml-string-to-int (match-string 9 kind)))
+ (r-bol (caml-string-to-int (match-string 10 kind)))
+ (r-cnum (caml-string-to-int (match-string 11 kind))))
+ (let* ((lpos (vector l-file l-line l-bol l-cnum))
+ (rpos (vector r-file r-line r-bol r-cnum))
+ (left (caml-types-get-pos target-buf lpos))
+ (right (caml-types-get-pos target-buf rpos)))
+ (move-overlay caml-types-def-ovl left right target-buf)
+ (message (format "%s is bound at line %d char %d"
+ var-name l-line (- l-cnum l-bol))))))
+ ((string-match external-re kind)
+ (let ((fullname (match-string 1 kind)))
+ (with-current-buffer caml-types-buffer
+ (erase-buffer)
+ (insert fullname)
+ (message (format "external ident: %s" fullname)))))))
+ ))))
+ (if (and (= arg 4)
+ (not (window-live-p (get-buffer-window caml-types-buffer))))
+ (display-buffer caml-types-buffer))
+ (unwind-protect
+ (caml-sit-for 60)
+ (delete-overlay caml-types-expr-ovl)
+ (delete-overlay caml-types-def-ovl)
+ (delete-overlay caml-types-scope-ovl)
+ )))
+
+(defun caml-types-preprocess (target-path)
+ (let* ((type-path (caml-types-locate-type-file target-path))
+ (type-date (nth 5 (file-attributes (file-chase-links type-path))))
+ (target-date (nth 5 (file-attributes target-file))))
+ (unless (and caml-types-annotation-tree
+ type-date
+ caml-types-annotation-date
+ (not (caml-types-date< caml-types-annotation-date type-date)))
+ (if (and type-date target-date (caml-types-date< type-date target-date))
+ (error (format "`%s' is more recent than `%s'"
+ target-path type-path)))
+ (message "Reading annotation file...")
+ (let* ((type-buf (caml-types-find-file type-path))
+ (tree (with-current-buffer type-buf
+ (widen)
+ (goto-char (point-min))
+ (caml-types-build-tree
+ (file-name-nondirectory target-path)))))
+ (setq caml-types-annotation-tree tree
+ caml-types-annotation-date type-date)
+ (kill-buffer type-buf)
+ (message "done"))
+ )))
+
+(defun caml-types-parent-dir (d) (file-name-directory (directory-file-name d)))
+
+(defun caml-types-locate-type-file (target-path)
+ "Given the path to an OCaml file, this function tries to locate
+and return the corresponding .annot file."
+ (let ((sibling (concat (file-name-sans-extension target-path) ".annot")))
+ (if (file-exists-p sibling)
+ sibling
+ (let* ((dir (file-name-directory sibling)))
+ (if caml-annot-dir
+ ;; Use the relative path set by the user
+ (let* ((annot-dir (expand-file-name caml-annot-dir dir))
+ (fname (file-name-nondirectory sibling))
+ (path-fname (expand-file-name fname annot-dir)))
+ (if (file-exists-p path-fname)
+ path-fname
+ (error (concat "No annotation file in " caml-annot-dir
+ ". Compile with option \"-annot\"."))))
+ ;; Else, try to get the .annot from one of build dirs.
+ (let* ((is-build (regexp-opt caml-types-build-dirs))
+ (project-dir (locate-dominating-file
+ dir
+ (lambda(d) (directory-files d nil is-build))))
+ (annot
+ (if project-dir
+ (locate-file
+ (file-relative-name sibling project-dir)
+ (mapcar (lambda(d) (expand-file-name d project-dir))
+ caml-types-build-dirs)))))
+ (if annot
+ annot
+ (error (concat "No annotation file. Compile with option "
+ "\"-annot\" or set `caml-annot-dir'.")))))))))
+
+(defun caml-types-date< (date1 date2)
+ (or (< (car date1) (car date2))
+ (and (= (car date1) (car date2))
+ (< (nth 1 date1) (nth 1 date2)))))
+
+
+; we use an obarray for hash-consing the strings within each tree
+
+(defun caml-types-make-hash-table ()
+ (make-vector 255 0))
+
+(defun caml-types-hcons (elem table)
+ (symbol-name (intern elem table)))
+
+
+(defun next-annotation ()
+ (forward-char 1)
+ (if (re-search-forward "^[a-z\"]" () t)
+ (forward-char -1)
+ (goto-char (point-max)))
+ (looking-at "[a-z]")
+)
+
+; tree of intervals
+; each node is a vector
+; [ pos-left pos-right annotation child child child... ]
+; annotation is a list of:
+; (kind . info) where kind = "type" "call" etc.
+; and info = the contents of the annotation
+
+(defun caml-types-build-tree (target-file)
+ (let ((stack ())
+ (accu ())
+ (table (caml-types-make-hash-table))
+ (annotation ()))
+ (while (re-search-forward caml-types-location-re () t)
+ (let ((l-file (file-name-nondirectory (match-string 1)))
+ (l-line (caml-string-to-int (match-string 3)))
+ (l-bol (caml-string-to-int (match-string 4)))
+ (l-cnum (caml-string-to-int (match-string 5)))
+ (r-file (file-name-nondirectory (match-string 6)))
+ (r-line (caml-string-to-int (match-string 8)))
+ (r-bol (caml-string-to-int (match-string 9)))
+ (r-cnum (caml-string-to-int (match-string 10))))
+ (unless (caml-types-not-in-file l-file r-file target-file)
+ (setq annotation ())
+ (while (next-annotation)
+ (cond ((looking-at "^\\([a-z]+\\)(\n \\(\\(.*\n \\)*.*\\)\n)")
+ (let ((kind (caml-types-hcons (match-string 1) table))
+ (info (caml-types-hcons (match-string 2) table)))
+ (setq annotation (cons (cons kind info) annotation))))))
+ (setq accu ())
+ (while (and stack
+ (caml-types-pos-contains l-cnum r-cnum (car stack)))
+ (setq accu (cons (car stack) accu))
+ (setq stack (cdr stack)))
+ (let* ((left-pos (vector l-file l-line l-bol l-cnum))
+ (right-pos (vector r-file r-line r-bol r-cnum))
+ (node (caml-types-make-node left-pos right-pos annotation
+ accu)))
+ (setq stack (cons node stack))))))
+ (if (null stack)
+ (error "no annotations found for this source file")
+ (let* ((left-pos (elt (car (last stack)) 0))
+ (right-pos (elt (car stack) 1)))
+ (if (null (cdr stack))
+ (car stack)
+ (caml-types-make-node left-pos right-pos () (nreverse stack)))))))
+
+(defun caml-types-not-in-file (l-file r-file target-file)
+ (or (and (not (string= l-file target-file))
+ (not (string= l-file "")))
+ (and (not (string= r-file target-file))
+ (not (string= r-file "")))))
+
+(defun caml-types-make-node (left-pos right-pos annotation children)
+ (let ((result (make-vector (+ 3 (length children)) ()))
+ (i 3))
+ (aset result 0 left-pos)
+ (aset result 1 right-pos)
+ (aset result 2 annotation)
+ (while children
+ (aset result i (car children))
+ (setq children (cdr children))
+ (setq i (1+ i)))
+ result))
+
+(defun caml-types-pos-contains (l-cnum r-cnum node)
+ (and (<= l-cnum (elt (elt node 0) 3))
+ (>= r-cnum (elt (elt node 1) 3))))
+
+(defun caml-types-find-location (targ-pos kind curr node)
+ (if (not (caml-types-pos-inside targ-pos node))
+ curr
+ (if (and (elt node 2) (assoc kind (elt node 2)))
+ (setq curr node))
+ (let ((i (caml-types-search node targ-pos)))
+ (if (and (> i 3)
+ (caml-types-pos-inside targ-pos (elt node (1- i))))
+ (caml-types-find-location targ-pos kind curr (elt node (1- i)))
+ curr))))
+
+; trouve le premier fils qui commence apres la position
+; ou (length node) si tous commencent avant
+(defun caml-types-search (node pos)
+ (let ((min 3)
+ (max (length node))
+ med)
+ (while (< min max)
+ (setq med (/ (+ min max) 2))
+ (if (caml-types-pos<= (elt (elt node med) 0) pos)
+ (setq min (1+ med))
+ (setq max med)))
+ min))
+
+(defun caml-types-pos-inside (pos node)
+ (let ((left-pos (elt node 0))
+ (right-pos (elt node 1)))
+ (and (caml-types-pos<= left-pos pos)
+ (caml-types-pos> right-pos pos))))
+
+(defun caml-types-find-interval (buf targ-pos node)
+ (let ((nleft (elt node 0))
+ (nright (elt node 1))
+ (left ())
+ (right ())
+ i)
+ (cond
+ ((not (caml-types-pos-inside targ-pos node))
+ (if (not (caml-types-pos<= nleft targ-pos))
+ (setq right nleft))
+ (if (not (caml-types-pos> nright targ-pos))
+ (setq left nright)))
+ (t
+ (setq left nleft
+ right nright)
+ (setq i (caml-types-search node targ-pos))
+ (if (< i (length node))
+ (setq right (elt (elt node i) 0)))
+ (if (> i 3)
+ (setq left (elt (elt node (1- i)) 1)))))
+ (cons (if left
+ (caml-types-get-pos buf left)
+ (with-current-buffer buf (point-min)))
+ (if right
+ (caml-types-get-pos buf right)
+ (with-current-buffer buf (point-max))))))
+
+
+;; Warning: these comparison functions are not symmetric.
+;; The first argument determines the format:
+;; when its file component is empty, only the cnum is compared.
+
+(defun caml-types-pos<= (pos1 pos2)
+ (let ((file1 (elt pos1 0))
+ (line1 (elt pos1 1))
+ (bol1 (elt pos1 2))
+ (cnum1 (elt pos1 3))
+ (file2 (elt pos2 0))
+ (line2 (elt pos2 1))
+ (bol2 (elt pos2 2))
+ (cnum2 (elt pos2 3)))
+ (if (string= file1 "")
+ (<= cnum1 cnum2)
+ (and (string= file1 file2)
+ (or (< line1 line2)
+ (and (= line1 line2)
+ (<= (- cnum1 bol1) (- cnum2 bol2))))))))
+
+(defun caml-types-pos> (pos1 pos2)
+ (let ((file1 (elt pos1 0))
+ (line1 (elt pos1 1))
+ (bol1 (elt pos1 2))
+ (cnum1 (elt pos1 3))
+ (file2 (elt pos2 0))
+ (line2 (elt pos2 1))
+ (bol2 (elt pos2 2))
+ (cnum2 (elt pos2 3)))
+ (if (string= file1 "")
+ (> cnum1 cnum2)
+ (and (string= file1 file2)
+ (or (> line1 line2)
+ (and (= line1 line2)
+ (> (- cnum1 bol1) (- cnum2 bol2))))))))
+
+(defun caml-types-get-pos (buf pos)
+ (save-excursion
+ (set-buffer buf)
+ (goto-line (elt pos 1))
+ (forward-char (- (elt pos 3) (elt pos 2)))
+ (point)))
+
+; find-file-read-only-noselect seems to be missing from emacs...
+(defun caml-types-find-file (name)
+ (let (buf)
+ (cond
+ ((setq buf (get-file-buffer name))
+ (unless (verify-visited-file-modtime buf)
+ (if (buffer-modified-p buf)
+ (find-file-noselect name)
+ (with-current-buffer buf (revert-buffer t t)))
+ ))
+ ((and (file-readable-p name)
+ (setq buf (find-file-noselect name)))
+ (with-current-buffer buf (toggle-read-only 1))
+ )
+ (t
+ (error (format "Can't read the annotation file `%s'" name)))
+ )
+ buf))
+
+(defun caml-types-mouse-ignore (event)
+ (interactive "e")
+ nil)
+
+(defun caml-types-time ()
+ (let ((time (current-time)))
+ (+ (* (mod (cadr time) 1000) 1000)
+ (/ (cadr (cdr time)) 1000))))
+
+(defun caml-types-explore (event)
+ "Explore type annotations by mouse dragging.
+
+The expression under the mouse is highlighted and its type is displayed
+in the minibuffer, until the move is released, much as `caml-types-show-type'.
+The function uses two overlays.
+
+ . One overlay delimits the largest region whose all subnodes
+ are well-typed.
+ . Another overlay delimits the current node under the mouse (whose type
+ annotation is being displayed).
+"
+ (interactive "e")
+ (set-buffer (window-buffer (caml-event-window event)))
+ (let* ((target-buf (current-buffer))
+ (target-file (file-name-nondirectory (buffer-file-name)))
+ (target-line) (target-bol)
+ target-pos
+ Left Right limits cnum node mes type
+ region
+ (window (caml-event-window event))
+ target-tree
+ (speed 100)
+ (last-time (caml-types-time))
+ (original-event event)
+ )
+ (select-window window)
+ (unwind-protect
+ (progn
+ (caml-types-preprocess (buffer-file-name))
+ (setq target-tree caml-types-annotation-tree)
+ (setq caml-types-buffer (get-buffer-create caml-types-buffer-name))
+ ;; (message "Drag the mouse to explore types")
+ (unwind-protect
+ (caml-track-mouse
+ (while event
+ (cond
+ ;; we ignore non mouse events
+ ((caml-ignore-event-p event))
+ ;; we stop when the original button is released
+ ((caml-release-event-p original-event event)
+ (setq event nil))
+ ;; we scroll when the motion is outside the window
+ ((and (caml-mouse-movement-p event)
+ (not (and (equal window (caml-event-window event))
+ (integer-or-marker-p
+ (caml-event-point-end event)))))
+ (let* ((win (caml-window-edges window))
+ (top (nth 1 win))
+ (bottom (- (nth 3 win) 1))
+ mouse
+ time
+ )
+ (while (and
+ (caml-sit-for 0 (/ 500 speed))
+ (setq time (caml-types-time))
+ (> (- time last-time) (/ 500 speed))
+ (setq mouse (caml-mouse-vertical-position))
+ (or (< mouse top) (>= mouse bottom))
+ )
+ (setq last-time time)
+ (cond
+ ((< mouse top)
+ (setq speed (- top mouse))
+ (condition-case nil
+ (scroll-down 1)
+ (error (message "Beginning of buffer!"))))
+ ((>= mouse bottom)
+ (setq speed (+ 1 (- mouse bottom)))
+ (condition-case nil
+ (scroll-up 1)
+ (error (message "End of buffer!"))))
+ )
+ (setq speed (* speed speed))
+ )))
+ ;; main action, when the motion is inside the window
+ ;; or on orginal button down event
+ ((or (caml-mouse-movement-p event)
+ (equal original-event event))
+ (setq cnum (caml-event-point-end event))
+ (if (and region
+ (<= (car region) cnum) (< cnum (cdr region)))
+ ;; mouse remains in outer region
+ nil
+ ;; otherwise, reset the outer region
+ (setq region
+ (caml-types-typed-make-overlay
+ target-buf (caml-event-point-start event))))
+ (if
+ (and limits
+ (>= cnum (car limits)) (< cnum (cdr limits)))
+ ;; inner region is unchanged
+ nil
+ ;; recompute the inner region and type annotation
+ (setq target-bol
+ (save-excursion
+ (goto-char cnum) (caml-line-beginning-position))
+ target-line (1+ (count-lines (point-min)
+ target-bol))
+ target-pos
+ (vector target-file target-line target-bol cnum))
+ (save-excursion
+ (setq node (caml-types-find-location target-pos "type" ()
+ target-tree))
+ (set-buffer caml-types-buffer)
+ (erase-buffer)
+ (cond
+ ((null node)
+ (delete-overlay caml-types-expr-ovl)
+ (setq type "*no type information*")
+ (setq limits
+ (caml-types-find-interval
+ target-buf target-pos target-tree)))
+ (t
+ (let ((left
+ (caml-types-get-pos target-buf (elt node 0)))
+ (right
+ (caml-types-get-pos target-buf (elt node 1))))
+ (move-overlay
+ caml-types-expr-ovl left right target-buf)
+ (setq limits
+ (caml-types-find-interval target-buf
+ target-pos node)
+ type (cdr (assoc "type" (elt node 2))))
+ ))
+ )
+ (setq mes (format "type: %s" type))
+ (insert type)
+ ))
+ (message mes)
+ )
+ )
+ ;; we read next event, unless it is nil, and loop back.
+ (if event (setq event (caml-read-event)))
+ )
+ )
+ ;; delete overlays at end of exploration
+ (delete-overlay caml-types-expr-ovl)
+ (delete-overlay caml-types-typed-ovl)
+ ))
+ ;; When an error occurs, the mouse release event has not been read.
+ ;; We could wait for mouse release to prevent execution of
+ ;; a binding of mouse release, such as cut or paste.
+ ;; In most common cases, next event will be the mouse release.
+ ;; However, it could also be a key stroke before mouse release.
+ ;; Emacs does not allow to test whether mouse is up or down.
+ ;; Not sure it is robust to loop for mouse release after an error
+ ;; occured, as is done for exploration.
+ ;; So far, we just ignore next event. (Next line also be uncommenting.)
+ (if event (caml-read-event))
+ )))
+
+(defun caml-types-typed-make-overlay (target-buf pos)
+ (interactive "p")
+ (let ((start pos) (end pos) len node left right)
+ (setq len (length caml-types-annotation-tree))
+ (while (> len 3)
+ (setq len (- len 1))
+ (setq node (aref caml-types-annotation-tree len))
+ (if (and (equal target-buf (current-buffer))
+ (setq left (caml-types-get-pos target-buf (elt node 0))
+ right (caml-types-get-pos target-buf (elt node 1)))
+ (<= left pos) (> right pos)
+ )
+ (setq start (min start left)
+ end (max end right))
+ ))
+ (move-overlay caml-types-typed-ovl
+ (max (point-min) (- start 1))
+ (min (point-max) (+ end 1)) target-buf)
+ (cons start end)))
+
+(defun caml-types-version ()
+ "internal version number of caml-types.el"
+ (interactive)
+ (message "4")
+)
+
+(provide 'caml-types)
diff --git a/emacs/caml-xemacs.el b/emacs/caml-xemacs.el
new file mode 100644
index 0000000000..f74c883c8d
--- /dev/null
+++ b/emacs/caml-xemacs.el
@@ -0,0 +1,55 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Didier Remy, projet Cristal, INRIA Rocquencourt *)
+;(* *)
+;(* Copyright 2003 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+(require 'overlay)
+
+;; for caml-help.el
+(defun caml-info-other-window (arg)
+ (save-excursion (info arg))
+ (view-buffer-other-window "*info*"))
+
+;; for caml-types.el
+(defun caml-line-beginning-position ()
+ (save-excursion (beginning-of-line) (point)))
+
+(defalias 'caml-read-event 'next-event)
+(defalias 'caml-window-edges 'window-pixel-edges)
+(defun caml-mouse-vertical-position ()
+ (let ((e (mouse-position-as-motion-event)))
+ (and e (event-y-pixel e))))
+(defalias 'caml-mouse-movement-p 'motion-event-p)
+(defun caml-event-window (e)
+ (and (mouse-event-p e) (event-window e)))
+(defun caml-event-point-start (e) (event-closest-point e))
+(defun caml-event-point-end (e) (event-closest-point e))
+(defun caml-ignore-event-p (e)
+ (if (and (key-press-event-p e) (equal (key-binding e) 'keyboard-quit))
+ (keyboard-quit))
+ (not (mouse-event-p e)))
+
+
+(defun caml-sit-for (sec &optional mili)
+ (sit-for (+ sec (if mili (* 0.001 mili) 0))))
+
+
+
+(defmacro caml-track-mouse (&rest body) (cons 'progn body))
+
+(defun caml-release-event-p (original event)
+ (and (button-release-event-p event)
+ (equal (event-button original) (event-button event))))
+
+(if (fboundp 'string-to-number)
+ (defalias 'caml-string-to-int 'string-to-number)
+ (defalias 'caml-string-to-int 'string-to-int))
+
+(provide 'caml-xemacs)
diff --git a/emacs/caml.el b/emacs/caml.el
new file mode 100644
index 0000000000..6ad464ae2b
--- /dev/null
+++ b/emacs/caml.el
@@ -0,0 +1,1961 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Jacques Garrigue and Ian T Zimmerman *)
+;(* *)
+;(* Copyright 1997 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;;; caml.el --- OCaml code editing commands for Emacs
+
+;; Xavier Leroy, july 1993.
+
+;;indentation code is Copyright (C) 1996 by Ian T Zimmerman <itz@rahul.net>
+;;copying: covered by the current FSF General Public License.
+
+;; indentation code adapted for OCaml by Jacques Garrigue,
+;; july 1997. <garrigue@kurims.kyoto-u.ac.jp>
+
+;;user customizable variables
+(defvar caml-quote-char "'"
+ "*Quote for character constants. \"'\" for OCaml, \"`\" for Caml-Light.")
+
+(defvar caml-imenu-enable nil
+ "*Enable Imenu support.")
+
+(defvar caml-mode-indentation 2
+ "*Used for \\[caml-unindent-command].")
+
+(defvar caml-lookback-limit 5000
+ "*How far to look back for syntax things in caml mode.")
+
+(defvar caml-max-indent-priority 8
+ "*Bounds priority of operators permitted to affect caml indentation.
+
+Priorities are assigned to `interesting' caml operators as follows:
+
+ all keywords 0 to 7 8
+ type, val, ... + 0 7
+ :: ^ 6
+ @ 5
+ := <- 4
+ if 3
+ fun, let, match ... 2
+ module 1
+ opening keywords 0.")
+
+(defvar caml-apply-extra-indent 2
+ "*How many spaces to add to indentation for an application in caml mode.")
+(make-variable-buffer-local 'caml-apply-extra-indent)
+
+(defvar caml-begin-indent 2
+ "*How many spaces to indent from a begin keyword in caml mode.")
+(make-variable-buffer-local 'caml-begin-indent)
+
+(defvar caml-class-indent 2
+ "*How many spaces to indent from a class keyword in caml mode.")
+(make-variable-buffer-local 'caml-class-indent)
+
+(defvar caml-exception-indent 2
+ "*How many spaces to indent from a exception keyword in caml mode.")
+(make-variable-buffer-local 'caml-exception-indent)
+
+(defvar caml-for-indent 2
+ "*How many spaces to indent from a for keyword in caml mode.")
+(make-variable-buffer-local 'caml-for-indent)
+
+(defvar caml-fun-indent 2
+ "*How many spaces to indent from a fun keyword in caml mode.")
+(make-variable-buffer-local 'caml-fun-indent)
+
+(defvar caml-function-indent 4
+ "*How many spaces to indent from a function keyword in caml mode.")
+(make-variable-buffer-local 'caml-function-indent)
+
+(defvar caml-if-indent 2
+ "*How many spaces to indent from a if keyword in caml mode.")
+(make-variable-buffer-local 'caml-if-indent)
+
+(defvar caml-if-else-indent 0
+ "*How many spaces to indent from an if .. else line in caml mode.")
+(make-variable-buffer-local 'caml-if-else-indent)
+
+(defvar caml-inherit-indent 2
+ "*How many spaces to indent from a inherit keyword in caml mode.")
+(make-variable-buffer-local 'caml-inherit-indent)
+
+(defvar caml-initializer-indent 2
+ "*How many spaces to indent from a initializer keyword in caml mode.")
+(make-variable-buffer-local 'caml-initializer-indent)
+
+(defvar caml-include-indent 2
+ "*How many spaces to indent from a include keyword in caml mode.")
+(make-variable-buffer-local 'caml-include-indent)
+
+(defvar caml-let-indent 2
+ "*How many spaces to indent from a let keyword in caml mode.")
+(make-variable-buffer-local 'caml-let-indent)
+
+(defvar caml-let-in-indent 0
+ "*How many spaces to indent from a let .. in keyword in caml mode.")
+(make-variable-buffer-local 'caml-let-in-indent)
+
+(defvar caml-match-indent 2
+ "*How many spaces to indent from a match keyword in caml mode.")
+(make-variable-buffer-local 'caml-match-indent)
+
+(defvar caml-method-indent 2
+ "*How many spaces to indent from a method keyword in caml mode.")
+(make-variable-buffer-local 'caml-method-indent)
+
+(defvar caml-module-indent 2
+ "*How many spaces to indent from a module keyword in caml mode.")
+(make-variable-buffer-local 'caml-module-indent)
+
+(defvar caml-object-indent 2
+ "*How many spaces to indent from a object keyword in caml mode.")
+(make-variable-buffer-local 'caml-object-indent)
+
+(defvar caml-of-indent 2
+ "*How many spaces to indent from a of keyword in caml mode.")
+(make-variable-buffer-local 'caml-of-indent)
+
+(defvar caml-parser-indent 4
+ "*How many spaces to indent from a parser keyword in caml mode.")
+(make-variable-buffer-local 'caml-parser-indent)
+
+(defvar caml-sig-indent 2
+ "*How many spaces to indent from a sig keyword in caml mode.")
+(make-variable-buffer-local 'caml-sig-indent)
+
+(defvar caml-struct-indent 2
+ "*How many spaces to indent from a struct keyword in caml mode.")
+(make-variable-buffer-local 'caml-struct-indent)
+
+(defvar caml-try-indent 2
+ "*How many spaces to indent from a try keyword in caml mode.")
+(make-variable-buffer-local 'caml-try-indent)
+
+(defvar caml-type-indent 4
+ "*How many spaces to indent from a type keyword in caml mode.")
+(make-variable-buffer-local 'caml-type-indent)
+
+(defvar caml-val-indent 2
+ "*How many spaces to indent from a val keyword in caml mode.")
+(make-variable-buffer-local 'caml-val-indent)
+
+(defvar caml-while-indent 2
+ "*How many spaces to indent from a while keyword in caml mode.")
+(make-variable-buffer-local 'caml-while-indent)
+
+(defvar caml-::-indent 2
+ "*How many spaces to indent from a :: operator in caml mode.")
+(make-variable-buffer-local 'caml-::-indent)
+
+(defvar caml-@-indent 2
+ "*How many spaces to indent from a @ operator in caml mode.")
+(make-variable-buffer-local 'caml-@-indent)
+
+(defvar caml-:=-indent 2
+ "*How many spaces to indent from a := operator in caml mode.")
+(make-variable-buffer-local 'caml-:=-indent)
+
+(defvar caml-<--indent 2
+ "*How many spaces to indent from a <- operator in caml mode.")
+(make-variable-buffer-local 'caml-<--indent)
+
+(defvar caml-->-indent 2
+ "*How many spaces to indent from a -> operator in caml mode.")
+(make-variable-buffer-local 'caml-->-indent)
+
+(defvar caml-lb-indent 2
+ "*How many spaces to indent from a \[ operator in caml mode.")
+(make-variable-buffer-local 'caml-lb-indent)
+
+(defvar caml-lc-indent 2
+ "*How many spaces to indent from a \{ operator in caml mode.")
+(make-variable-buffer-local 'caml-lc-indent)
+
+(defvar caml-lp-indent 1
+ "*How many spaces to indent from a \( operator in caml mode.")
+(make-variable-buffer-local 'caml-lp-indent)
+
+(defvar caml-and-extra-indent nil
+ "*Extra indent for caml lines starting with the and keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-and-extra-indent)
+
+(defvar caml-do-extra-indent nil
+ "*Extra indent for caml lines starting with the do keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-do-extra-indent)
+
+(defvar caml-done-extra-indent nil
+ "*Extra indent for caml lines starting with the done keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-done-extra-indent)
+
+(defvar caml-else-extra-indent nil
+ "*Extra indent for caml lines starting with the else keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-else-extra-indent)
+
+(defvar caml-end-extra-indent nil
+ "*Extra indent for caml lines starting with the end keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-end-extra-indent)
+
+(defvar caml-in-extra-indent nil
+ "*Extra indent for caml lines starting with the in keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-in-extra-indent)
+
+(defvar caml-then-extra-indent nil
+ "*Extra indent for caml lines starting with the then keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-then-extra-indent)
+
+(defvar caml-to-extra-indent -1
+ "*Extra indent for caml lines starting with the to keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-to-extra-indent)
+
+(defvar caml-with-extra-indent nil
+ "*Extra indent for caml lines starting with the with keyword.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-with-extra-indent)
+
+(defvar caml-comment-indent 3
+ "*Indent inside comments.")
+(make-variable-buffer-local 'caml-comment-indent)
+
+(defvar caml-|-extra-indent -2
+ "*Extra indent for caml lines starting with the | operator.
+Usually negative. nil is align on master.")
+(make-variable-buffer-local 'caml-|-extra-indent)
+
+(defvar caml-rb-extra-indent -2
+ "*Extra indent for caml lines statring with ].
+Usually negative. nil is align on master.")
+
+(defvar caml-rc-extra-indent -2
+ "*Extra indent for caml lines starting with }.
+Usually negative. nil is align on master.")
+
+(defvar caml-rp-extra-indent -1
+ "*Extra indent for caml lines starting with ).
+Usually negative. nil is align on master.")
+
+(defvar caml-electric-indent t
+ "*Non-nil means electrically indent lines starting with |, ] or }.
+
+Many people find eletric keys irritating, so you can disable them if
+you are one.")
+
+(defvar caml-electric-close-vector t
+ "*Non-nil means electrically insert a | before a vector-closing ].
+
+Many people find eletric keys irritating, so you can disable them if
+you are one. You should probably have this on, though, if you also
+have caml-electric-indent on, which see.")
+
+;;code
+(if (or (not (fboundp 'indent-line-to))
+ (not (fboundp 'buffer-substring-no-properties)))
+ (require 'caml-compat))
+
+(defvar caml-shell-active nil
+ "Non nil when a subshell is running.")
+
+(defvar running-xemacs (string-match "XEmacs" emacs-version)
+ "Non-nil if we are running in the XEmacs environment.")
+
+(defvar caml-mode-map nil
+ "Keymap used in Caml mode.")
+(if caml-mode-map
+ ()
+ (setq caml-mode-map (make-sparse-keymap))
+ (define-key caml-mode-map "|" 'caml-electric-pipe)
+ (define-key caml-mode-map "}" 'caml-electric-pipe)
+ (define-key caml-mode-map "]" 'caml-electric-rb)
+ (define-key caml-mode-map "\t" 'caml-indent-command)
+ (define-key caml-mode-map [backtab] 'caml-unindent-command)
+
+;itz 04-21-96 instead of defining a new function, use defadvice
+;that way we get out effect even when we do \C-x` in compilation buffer
+; (define-key caml-mode-map "\C-x`" 'caml-next-error)
+
+ (if running-xemacs
+ (define-key caml-mode-map 'backspace 'backward-delete-char-untabify)
+ (define-key caml-mode-map "\177" 'backward-delete-char-untabify))
+
+ ;; caml-types
+ (define-key caml-mode-map [?\C-c?\C-t] 'caml-types-show-type) ; "type"
+ (define-key caml-mode-map [?\C-c?\C-f] 'caml-types-show-call) ; "function"
+ (define-key caml-mode-map [?\C-c?\C-l] 'caml-types-show-ident) ; "let"
+ ;; must be a mouse-down event. Can be any button and any prefix
+ (define-key caml-mode-map [?\C-c down-mouse-1] 'caml-types-explore)
+ ;; caml-help
+ (define-key caml-mode-map [?\C-c?i] 'ocaml-add-path)
+ (define-key caml-mode-map [?\C-c?]] 'ocaml-close-module)
+ (define-key caml-mode-map [?\C-c?[] 'ocaml-open-module)
+ (define-key caml-mode-map [?\C-c?\C-h] 'caml-help)
+ (define-key caml-mode-map [?\C-c?\t] 'caml-complete)
+ ;; others
+ (define-key caml-mode-map "\C-cb" 'caml-insert-begin-form)
+ (define-key caml-mode-map "\C-cf" 'caml-insert-for-form)
+ (define-key caml-mode-map "\C-ci" 'caml-insert-if-form)
+ (define-key caml-mode-map "\C-cl" 'caml-insert-let-form)
+ (define-key caml-mode-map "\C-cm" 'caml-insert-match-form)
+ (define-key caml-mode-map "\C-ct" 'caml-insert-try-form)
+ (define-key caml-mode-map "\C-cw" 'caml-insert-while-form)
+ (define-key caml-mode-map "\C-c`" 'caml-goto-phrase-error)
+ (define-key caml-mode-map "\C-c\C-a" 'caml-find-alternate-file)
+ (define-key caml-mode-map "\C-c\C-c" 'compile)
+ (define-key caml-mode-map "\C-c\C-e" 'caml-eval-phrase)
+ (define-key caml-mode-map "\C-c\C-\[" 'caml-backward-to-less-indent)
+ (define-key caml-mode-map "\C-c\C-\]" 'caml-forward-to-less-indent)
+ (define-key caml-mode-map "\C-c\C-q" 'caml-indent-phrase)
+ (define-key caml-mode-map "\C-c\C-r" 'caml-eval-region)
+ (define-key caml-mode-map "\C-c\C-s" 'caml-show-subshell)
+ (define-key caml-mode-map "\M-\C-h" 'caml-mark-phrase)
+ (define-key caml-mode-map "\M-\C-q" 'caml-indent-phrase)
+ (define-key caml-mode-map "\M-\C-x" 'caml-eval-phrase)
+
+ (if running-xemacs nil ; if not running xemacs
+ (let ((map (make-sparse-keymap "Caml"))
+ (forms (make-sparse-keymap "Forms")))
+ (define-key caml-mode-map "\C-c\C-d" 'caml-show-imenu)
+ (define-key caml-mode-map [menu-bar] (make-sparse-keymap))
+ (define-key caml-mode-map [menu-bar caml] (cons "Caml" map))
+ ;; caml-help
+
+ (define-key map [open] '("Open add path" . ocaml-add-path ))
+ (define-key map [close]
+ '("Close module for help" . ocaml-close-module))
+ (define-key map [open] '("Open module for help" . ocaml-open-module))
+ (define-key map [help] '("Help for identifier" . caml-help))
+ (define-key map [complete] '("Complete identifier" . caml-complete))
+ (define-key map [separator-help] '("---"))
+
+ ;; caml-types
+ (define-key map [show-type]
+ '("Show type at point" . caml-types-show-type ))
+ (define-key map [separator-types] '("---"))
+
+ ;; others
+ (define-key map [camldebug] '("Call debugger..." . camldebug))
+ (define-key map [run-caml] '("Start subshell..." . run-caml))
+ (define-key map [compile] '("Compile..." . compile))
+ (define-key map [switch-view]
+ '("Switch view" . caml-find-alternate-file))
+ (define-key map [separator-format] '("--"))
+ (define-key map [forms] (cons "Forms" forms))
+ (define-key map [show-imenu] '("Show index" . caml-show-imenu))
+ (put 'caml-show-imenu 'menu-enable '(not caml-imenu-shown))
+ (define-key map [show-subshell] '("Show subshell" . caml-show-subshell))
+ (put 'caml-show-subshell 'menu-enable 'caml-shell-active)
+ (define-key map [eval-phrase] '("Eval phrase" . caml-eval-phrase))
+ (put 'caml-eval-phrase 'menu-enable 'caml-shell-active)
+ (define-key map [indent-phrase] '("Indent phrase" . caml-indent-phrase))
+ (define-key forms [while]
+ '("while .. do .. done" . caml-insert-while-form))
+ (define-key forms [try] '("try .. with .." . caml-insert-try-form))
+ (define-key forms [match] '("match .. with .." . caml-insert-match-form))
+ (define-key forms [let] '("let .. in .." . caml-insert-let-form))
+ (define-key forms [if] '("if .. then .. else .." . caml-insert-if-form))
+ (define-key forms [begin] '("for .. do .. done" . caml-insert-for-form))
+ (define-key forms [begin] '("begin .. end" . caml-insert-begin-form)))))
+
+(defvar caml-mode-xemacs-menu
+ (if running-xemacs
+ '("Caml"
+ [ "Indent phrase" caml-indent-phrase :keys "C-M-q" ]
+ [ "Eval phrase" caml-eval-phrase
+ :active caml-shell-active :keys "C-M-x" ]
+ [ "Show subshell" caml-show-subshell caml-shell-active ]
+ ("Forms"
+ [ "while .. do .. done" caml-insert-while-form t]
+ [ "try .. with .." caml-insert-try-form t ]
+ [ "match .. with .." caml-insert-match-form t ]
+ [ "let .. in .." caml-insert-let-form t ]
+ [ "if .. then .. else .." caml-insert-if-form t ]
+ [ "for .. do .. done" caml-insert-for-form t ]
+ [ "begin .. end" caml-insert-begin-form t ])
+ "---"
+ [ "Switch view" caml-find-alternate-file t ]
+ [ "Compile..." compile t ]
+ [ "Start subshell..." run-caml t ]
+ "---"
+ [ "Show type at point" caml-types-show-type t ]
+ "---"
+ [ "Complete identifier" caml-complete t ]
+ [ "Help for identifier" caml-help t ]
+ [ "Add path for documentation" ocaml-add-path t ]
+ [ "Open module for documentation" ocaml-open t ]
+ [ "Close module for documentation" ocaml-close t ]
+ ))
+ "Menu to add to the menubar when running Xemacs")
+
+(defvar caml-mode-syntax-table nil
+ "Syntax table in use in Caml mode buffers.")
+(if caml-mode-syntax-table
+ ()
+ (let ((n (if (string-match "XEmacs" (emacs-version)) "" "n")))
+ (setq caml-mode-syntax-table (make-syntax-table))
+ ; backslash is an escape sequence
+ (modify-syntax-entry ?\\ "\\" caml-mode-syntax-table)
+ ; ( is first character of comment start
+ (modify-syntax-entry ?\( (concat "()1" n) caml-mode-syntax-table)
+ ; * is second character of comment start,
+ ; and first character of comment end
+ (modify-syntax-entry ?* (concat ". 23" n) caml-mode-syntax-table)
+ ; ) is last character of comment end
+ (modify-syntax-entry ?\) ")(4" caml-mode-syntax-table)
+ ; backquote was a string-like delimiter (for character literals)
+ ; (modify-syntax-entry ?` "\"" caml-mode-syntax-table)
+ ; quote and underscore are part of words
+ (modify-syntax-entry ?' "w" caml-mode-syntax-table)
+ (modify-syntax-entry ?_ "w" caml-mode-syntax-table)
+ ; ISO-latin accented letters and EUC kanjis are part of words
+ (let ((i 160))
+ (while (< i 256)
+ (modify-syntax-entry i "w" caml-mode-syntax-table)
+ (setq i (1+ i))))))
+
+(defvar caml-mode-abbrev-table nil
+ "Abbrev table used for Caml mode buffers.")
+(if caml-mode-abbrev-table nil
+ (setq caml-mode-abbrev-table (make-abbrev-table))
+ (define-abbrev caml-mode-abbrev-table "and" "and" 'caml-abbrev-hook)
+ (define-abbrev caml-mode-abbrev-table "do" "do" 'caml-abbrev-hook)
+ (define-abbrev caml-mode-abbrev-table "done" "done" 'caml-abbrev-hook)
+ (define-abbrev caml-mode-abbrev-table "else" "else" 'caml-abbrev-hook)
+ (define-abbrev caml-mode-abbrev-table "end" "end" 'caml-abbrev-hook)
+ (define-abbrev caml-mode-abbrev-table "in" "in" 'caml-abbrev-hook)
+ (define-abbrev caml-mode-abbrev-table "then" "then" 'caml-abbrev-hook)
+ (define-abbrev caml-mode-abbrev-table "with" "with" 'caml-abbrev-hook))
+
+;; Other internal variables
+
+(defvar caml-last-noncomment-pos nil
+ "Caches last buffer position determined not inside a caml comment.")
+(make-variable-buffer-local 'caml-last-noncomment-pos)
+
+;;last-noncomment-pos can be a simple position, because we nil it
+;;anyway whenever buffer changes upstream. last-comment-start and -end
+;;have to be markers, because we preserve them when the changes' end
+;;doesn't overlap with the comment's start.
+
+(defvar caml-last-comment-start nil
+ "A marker caching last determined caml comment start.")
+(make-variable-buffer-local 'caml-last-comment-start)
+
+(defvar caml-last-comment-end nil
+ "A marker caching last determined caml comment end.")
+(make-variable-buffer-local 'caml-last-comment-end)
+
+(make-variable-buffer-local 'before-change-function)
+
+(defvar caml-imenu-shown nil
+ "True if we have computed definition list.")
+(make-variable-buffer-local 'caml-imenu-shown)
+
+(defconst caml-imenu-search-regexp
+ (concat "\\<in\\>\\|"
+ "^[ \t]*\\(let\\|class\\|type\\|m\\(odule\\|ethod\\)"
+ "\\|functor\\|and\\|val\\)[ \t]+"
+ "\\(\\('[a-zA-Z0-9]+\\|([^)]+)"
+ "\\|mutable\\|private\\|rec\\|type\\)[ \t]+\\)?"
+ "\\([a-zA-Z][a-zA-Z0-9_']*\\)"))
+
+;;; The major mode
+(eval-when-compile
+ (if (and (boundp 'running-xemacs) running-xemacs) nil
+ (require 'imenu)))
+
+;;
+(defvar caml-mode-hook nil
+ "Hook for caml-mode")
+
+(defun caml-mode ()
+ "Major mode for editing OCaml code.
+
+\\{caml-mode-map}"
+
+ (interactive)
+ (kill-all-local-variables)
+ (setq major-mode 'caml-mode)
+ (setq mode-name "caml")
+ (use-local-map caml-mode-map)
+ (set-syntax-table caml-mode-syntax-table)
+ (setq local-abbrev-table caml-mode-abbrev-table)
+ (make-local-variable 'paragraph-start)
+ (setq paragraph-start (concat "^$\\|" page-delimiter))
+ (make-local-variable 'paragraph-separate)
+ (setq paragraph-separate paragraph-start)
+ (make-local-variable 'paragraph-ignore-fill-prefix)
+ (setq paragraph-ignore-fill-prefix t)
+ (make-local-variable 'require-final-newline)
+ (setq require-final-newline t)
+ (make-local-variable 'comment-start)
+ (setq comment-start "(*")
+ (make-local-variable 'comment-end)
+ (setq comment-end "*)")
+ (make-local-variable 'comment-column)
+ (setq comment-column 40)
+ (make-local-variable 'comment-start-skip)
+ (setq comment-start-skip "(\\*+ *")
+ (make-local-variable 'parse-sexp-ignore-comments)
+ (setq parse-sexp-ignore-comments nil)
+ (make-local-variable 'indent-line-function)
+ (setq indent-line-function 'caml-indent-command)
+ ;itz Fri Sep 25 13:23:49 PDT 1998
+ (make-local-variable 'add-log-current-defun-function)
+ (setq add-log-current-defun-function 'caml-current-defun)
+ ;itz 03-25-96
+ (setq before-change-function 'caml-before-change-function)
+ (setq caml-last-noncomment-pos nil)
+ (setq caml-last-comment-start (make-marker))
+ (setq caml-last-comment-end (make-marker))
+ ;garrigue 27-11-96
+ (setq case-fold-search nil)
+ ;garrigue july 97
+ (if running-xemacs ; from Xemacs lisp mode
+ (if (and (featurep 'menubar)
+ current-menubar)
+ (progn
+ ;; make a local copy of the menubar, so our modes don't
+ ;; change the global menubar
+ (set-buffer-menubar current-menubar)
+ (add-submenu nil caml-mode-xemacs-menu)))
+ ;imenu support (not for Xemacs)
+ (make-local-variable 'imenu-create-index-function)
+ (setq imenu-create-index-function 'caml-create-index-function)
+ (make-local-variable 'imenu-generic-expression)
+ (setq imenu-generic-expression caml-imenu-search-regexp)
+ (if (and caml-imenu-enable (< (buffer-size) 10000))
+ (caml-show-imenu)))
+ (run-hooks 'caml-mode-hook))
+
+
+;; Disabled because it assumes make and does not play well with ocamlbuild.
+;; See PR#4469 for details.
+
+;; (defun caml-set-compile-command ()
+;; "Hook to set compile-command locally, unless there is a Makefile or
+;; a _build directory or a _tags file in the current directory."
+;; (interactive)
+;; (unless (or (null buffer-file-name)
+;; (file-exists-p "makefile")
+;; (file-exists-p "Makefile")
+;; (file-exists-p "_build")
+;; (file-exists-p "_tags"))
+;; (let* ((filename (file-name-nondirectory buffer-file-name))
+;; (basename (file-name-sans-extension filename))
+;; (command nil))
+;; (cond
+;; ((string-match ".*\\.mli\$" filename)
+;; (setq command "ocamlc -c"))
+;; ((string-match ".*\\.ml\$" filename)
+;; (setq command "ocamlc -c") ; (concat "ocamlc -o " basename)
+;; )
+;; ((string-match ".*\\.mll\$" filename)
+;; (setq command "ocamllex"))
+;; ((string-match ".*\\.mll\$" filename)
+;; (setq command "ocamlyacc"))
+;; )
+;; (if command
+;; (progn
+;; (make-local-variable 'compile-command)
+;; (setq compile-command (concat command " " filename))))
+;; )))
+
+;; (add-hook 'caml-mode-hook 'caml-set-compile-command)
+
+
+;;; Auxiliary function. Garrigue 96-11-01.
+
+(defun caml-find-alternate-file ()
+ (interactive)
+ (let ((name (buffer-file-name)))
+ (if (string-match "^\\(.*\\)\\.\\(ml\\|mli\\)$" name)
+ (find-file
+ (concat
+ (caml-match-string 1 name)
+ (if (string= "ml" (caml-match-string 2 name)) ".mli" ".ml"))))))
+
+;;; subshell support
+
+(defun caml-eval-region (start end)
+ "Send the current region to the inferior OCaml process."
+ (interactive"r")
+ (require 'inf-caml)
+ (inferior-caml-eval-region start end))
+
+;; old version ---to be deleted later
+;
+; (defun caml-eval-phrase ()
+; "Send the current OCaml phrase to the inferior Caml process."
+; (interactive)
+; (save-excursion
+; (let ((bounds (caml-mark-phrase)))
+; (inferior-caml-eval-region (car bounds) (cdr bounds)))))
+
+(defun caml-eval-phrase (arg &optional min max)
+ "Send the phrase containing the point to the CAML process.
+With prefix-arg send as many phrases as its numeric value,
+If an error occurs during evalutaion, stop at this phrase and
+repport the error.
+
+Return nil if noerror and position of error if any.
+
+If arg's numeric value is zero or negative, evaluate the current phrase
+or as many as prefix arg, ignoring evaluation errors.
+This allows to jump other erroneous phrases.
+
+Optional arguments min max defines a region within which the phrase
+should lies."
+ (interactive "p")
+ (require 'inf-caml)
+ (inferior-caml-eval-phrase arg min max))
+
+(defun caml-eval-buffer (arg)
+ "Evaluate the buffer from the beginning to the phrase under the point.
+With prefix arg, evaluate past the whole buffer, no stopping at
+the current point."
+ (interactive "p")
+ (let ((here (point)) err)
+ (goto-char (point-min))
+ (setq err
+ (caml-eval-phrase 500 (point-min) (if arg (point-max) here)))
+ (if err (set-mark err))
+ (goto-char here)))
+
+(defun caml-show-subshell ()
+ (interactive)
+ (require 'inf-caml)
+ (inferior-caml-show-subshell))
+
+
+;;; Imenu support
+(defun caml-show-imenu ()
+ (interactive)
+ (require 'imenu)
+ (switch-to-buffer (current-buffer))
+ (imenu-add-to-menubar "Defs")
+ (setq caml-imenu-shown t))
+
+(defun caml-prev-index-position-function ()
+ (let (found data)
+ (while (and (setq found
+ (re-search-backward caml-imenu-search-regexp nil 'move))
+ (progn (setq data (match-data)) t)
+ (or (caml-in-literal-p)
+ (caml-in-comment-p)
+ (if (looking-at "in") (caml-find-in-match)))))
+ (set-match-data data)
+ found))
+(defun caml-create-index-function ()
+ (let (value-alist
+ type-alist
+ class-alist
+ method-alist
+ module-alist
+ and-alist
+ all-alist
+ menu-alist
+ (prev-pos (point-max))
+ index)
+ (goto-char prev-pos)
+ (imenu-progress-message prev-pos 0 t)
+ ;; collect definitions
+ (while (caml-prev-index-position-function)
+ (setq index (cons (caml-match-string 5) (point)))
+ (imenu-progress-message prev-pos nil t)
+ (setq all-alist (cons index all-alist))
+ (cond
+ ((looking-at "[ \t]*and")
+ (setq and-alist (cons index and-alist)))
+ ((looking-at "[ \t]*let")
+ (setq value-alist (cons index (append and-alist value-alist)))
+ (setq and-alist nil))
+ ((looking-at "[ \t]*type")
+ (setq type-alist (cons index (append and-alist type-alist)))
+ (setq and-alist nil))
+ ((looking-at "[ \t]*class")
+ (setq class-alist (cons index (append and-alist class-alist)))
+ (setq and-alist nil))
+ ((looking-at "[ \t]*val")
+ (setq value-alist (cons index value-alist)))
+ ((looking-at "[ \t]*\\(module\\|functor\\)")
+ (setq module-alist (cons index module-alist)))
+ ((looking-at "[ \t]*method")
+ (setq method-alist (cons index method-alist)))))
+ ;; build menu
+ (mapc
+ (lambda (pair)
+ (if (symbol-value (cdr pair))
+ (setq menu-alist
+ (cons
+ (cons (car pair)
+ (sort (symbol-value (cdr pair)) 'imenu--sort-by-name))
+ menu-alist))))
+ '(("Values" . value-alist)
+ ("Types" . type-alist)
+ ("Modules" . module-alist)
+ ("Methods" . method-alist)
+ ("Classes" . class-alist)))
+ (if all-alist (setq menu-alist (cons (cons "Index" all-alist) menu-alist)))
+ (imenu-progress-message prev-pos 100 t)
+ menu-alist))
+
+;;; Indentation stuff
+
+(defun caml-in-indentation ()
+ "Tests whether all characters between beginning of line and point
+are blanks."
+ (save-excursion
+ (skip-chars-backward " \t")
+ (bolp)))
+
+;;; The command
+;;; Sorry, I didn't like the previous behaviour... Garrigue 96/11/01
+
+(defun caml-indent-command (&optional p)
+ "Indent the current line in Caml mode.
+
+Compute new indentation based on caml syntax. If prefixed, indent
+the line all the way to where point is."
+
+ (interactive "*p")
+ (cond
+ ((and p (> p 1)) (indent-line-to (current-column)))
+ ((caml-in-indentation) (indent-line-to (caml-compute-final-indent)))
+ (t (save-excursion
+ (indent-line-to
+ (caml-compute-final-indent))))))
+
+(defun caml-unindent-command ()
+
+ "Decrease indentation by one level in Caml mode.
+
+Works only if the point is at the beginning of an indented line
+\(i.e. all characters between beginning of line and point are
+blanks\). Does nothing otherwise. The unindent size is given by the
+variable caml-mode-indentation."
+
+ (interactive "*")
+ (let* ((begline
+ (save-excursion
+ (beginning-of-line)
+ (point)))
+ (current-offset
+ (- (point) begline)))
+ (if (and (>= current-offset caml-mode-indentation)
+ (caml-in-indentation))
+ (backward-delete-char-untabify caml-mode-indentation))))
+
+;;;
+;;; Error processing
+;;;
+
+;; Error positions are given in bytes, not in characters
+;; This function switches to monobyte mode
+
+(if (not (fboundp 'char-bytes))
+ (defalias 'forward-byte 'forward-char)
+ (defun caml-char-bytes (ch)
+ (let ((l (char-bytes ch)))
+ (if (> l 1) (- l 1) l)))
+ (defun forward-byte (count)
+ (if (> count 0)
+ (while (> count 0)
+ (let ((char (char-after)))
+ (if (null char)
+ (setq count 0)
+ (setq count (- count (caml-char-bytes (char-after))))
+ (forward-char))))
+ (while (< count 0)
+ (let ((char (char-after)))
+ (if (null char)
+ (setq count 0)
+ (setq count (+ count (caml-char-bytes (char-before))))
+ (backward-char))))
+ )))
+
+(require 'compile)
+
+;; In Emacs 19, the regexps in compilation-error-regexp-alist do not
+;; match the error messages when the language is not English.
+;; Hence we add a regexp.
+;; FIXME do we (still) have i18n of error messages ???
+
+(defconst caml-error-regexp
+ "^[ A-\377]+ \"\\([^\"\n]+\\)\", [A-\377]+ \\([0-9]+\\)[-,:]"
+ "Regular expression matching the error messages produced by camlc.")
+
+;; Newer emacs versions support line/char ranges
+;; We will adapt OCaml to output error messages in a compatible format.
+;; In the meantime we add the new format here in addition to the old one.
+(defconst caml-error-regexp-newstyle
+ (concat "^[ A-\377]+ \"\\([^\"\n]+\\)\", line \\([0-9]+\\),"
+ "char \\([0-9]+\\) to line \\([0-9]+\\), char \\([0-9]+\\):")
+ "Regular expression matching the error messages produced by ocamlc/ocamlopt.")
+
+(if (boundp 'compilation-error-regexp-alist)
+ (progn
+ (or (assoc caml-error-regexp
+ compilation-error-regexp-alist)
+ (setq compilation-error-regexp-alist
+ (cons (list caml-error-regexp 1 2)
+ compilation-error-regexp-alist)))
+ (or (assoc caml-error-regexp-newstyle
+ compilation-error-regexp-alist)
+ (setq compilation-error-regexp-alist
+ (cons (list caml-error-regexp-newstyle 1 '(2 . 4) '(3 . 5))
+ compilation-error-regexp-alist)))))
+
+;; A regexp to extract the range info
+
+(defconst caml-error-chars-regexp
+ ".*, .*, [A-\377]+ \\([0-9]+\\)-\\([0-9]+\\):?"
+ "Regular expression extracting the character numbers
+from an error message produced by camlc.")
+
+;; Wrapper around next-error.
+
+(defvar caml-error-overlay nil)
+(defvar caml-next-error-skip-warnings-flag nil)
+
+(if (fboundp 'string-to-number)
+ (defalias 'caml-string-to-int 'string-to-number)
+ (defalias 'caml-string-to-int 'string-to-int))
+
+;;itz 04-21-96 somebody didn't get the documentation for next-error
+;;right. When the optional argument is a number n, it should move
+;;forward n errors, not reparse.
+
+;itz 04-21-96 instead of defining a new function, use defadvice
+;that way we get our effect even when we do \C-x` in compilation buffer
+
+(defadvice next-error (after caml-next-error activate)
+ "Reads the extra positional information provided by the OCaml compiler.
+
+Puts the point and the mark exactly around the erroneous program
+fragment. The erroneous fragment is also temporarily highlighted if
+possible."
+
+ (if (eq major-mode 'caml-mode)
+ (let (skip bol beg end)
+ (save-excursion
+ (set-buffer
+ (if (boundp 'compilation-last-buffer)
+ compilation-last-buffer ;Emacs 19
+ "*compilation*")) ;Emacs 18
+ (save-excursion
+ (goto-char (window-point (get-buffer-window (current-buffer))))
+ (if (looking-at caml-error-chars-regexp)
+ (setq beg
+ (caml-string-to-int
+ (buffer-substring (match-beginning 1) (match-end 1)))
+ end
+ (caml-string-to-int
+ (buffer-substring (match-beginning 2) (match-end 2)))))
+ (next-line)
+ (beginning-of-line)
+ (if (and (looking-at "Warning")
+ caml-next-error-skip-warnings-flag)
+ (setq skip 't))))
+ (cond
+ (skip (next-error))
+ (beg
+ (setq end (- end beg))
+ (beginning-of-line)
+ (forward-byte beg)
+ (setq beg (point))
+ (forward-byte end)
+ (setq end (point))
+ (goto-char beg)
+ (push-mark end t)
+ (cond ((fboundp 'make-overlay)
+ (if caml-error-overlay ()
+ (setq caml-error-overlay (make-overlay 1 1))
+ (overlay-put caml-error-overlay 'face 'region))
+ (unwind-protect
+ (progn
+ (move-overlay caml-error-overlay
+ beg end (current-buffer))
+ (sit-for 60))
+ (delete-overlay caml-error-overlay)))))))))
+
+(defun caml-next-error-skip-warnings (&rest args)
+ (let ((old-flag caml-next-error-skip-warnings-flag))
+ (unwind-protect
+ (progn (setq caml-next-error-skip-warnings-flag 't)
+ (apply 'next-error args))
+ (setq caml-next-error-skip-warnings-flag old-flag))))
+
+
+;; Usual match-string doesn't work properly with font-lock-mode
+;; on some emacs.
+
+(defun caml-match-string (num &optional string)
+
+ "Return string of text matched by last search, without properties.
+
+NUM specifies which parenthesized expression in the last regexp.
+Value is nil if NUMth pair didn't match, or there were less than NUM
+pairs. Zero means the entire text matched by the whole regexp or
+whole string."
+
+ (let* ((data (match-data))
+ (begin (nth (* 2 num) data))
+ (end (nth (1+ (* 2 num)) data)))
+ (if string (substring string begin end)
+ (buffer-substring-no-properties begin end))))
+
+;; itz Thu Sep 24 19:02:42 PDT 1998 this is to have some level of
+;; comfort when sending phrases to the toplevel and getting errors.
+(defun caml-goto-phrase-error ()
+ "Find the error location in current OCaml phrase."
+ (interactive)
+ (require 'inf-caml)
+ (let ((bounds (save-excursion (caml-mark-phrase))))
+ (inferior-caml-goto-error (car bounds) (cdr bounds))))
+
+;;; Phrases
+
+;itz the heuristics used to see if we're `between two phrases'
+;didn't seem right to me.
+
+(defconst caml-phrase-start-keywords
+ (concat "\\<\\(class\\|ex\\(ternal\\|ception\\)\\|functor"
+ "\\|let\\|module\\|open\\|type\\|val\\)\\>")
+ "Keywords starting phrases in files")
+
+;; a phrase starts when a toplevel keyword is at the beginning of a line
+(defun caml-at-phrase-start-p ()
+ (and (bolp)
+ (or (looking-at "#")
+ (looking-at caml-phrase-start-keywords))))
+
+(defun caml-skip-comments-forward ()
+ (skip-chars-forward " \n\t")
+ (while (or (looking-at comment-start-skip) (caml-in-comment-p))
+ (if (= (following-char) ?\)) (forward-char)
+ (search-forward comment-end))
+ (skip-chars-forward " \n\t")))
+
+(defun caml-skip-comments-backward ()
+ (skip-chars-backward " \n\t")
+ (while (and (eq (preceding-char) ?\)) (eq (char-after (- (point) 2)) ?*))
+ (backward-char)
+ (while (caml-in-comment-p) (search-backward comment-start))
+ (skip-chars-backward " \n\t")))
+
+(defconst caml-phrase-sep-keywords (concat ";;\\|" caml-phrase-start-keywords))
+
+(defun caml-find-phrase (&optional min-pos max-pos)
+ "Find the CAML phrase containing the point.
+Return the position of the beginning of the phrase, and move point
+to the end.
+"
+ (interactive)
+ (if (not min-pos) (setq min-pos (point-min)))
+ (if (not max-pos) (setq max-pos (point-max)))
+ (let (beg end use-semi kwop)
+ ;(caml-skip-comments-backward)
+ (cond
+ ; shall we have special processing for semicolons?
+ ;((and (eq (char-before (- (point) 1)) ?\;) (eq (char-before) ?\;))
+ ; (forward-char)
+ ; (caml-skip-comments-forward)
+ ; (setq beg (point))
+ ; (while (and (search-forward ";;" max-pos 'move)
+ ; (or (caml-in-comment-p) (caml-in-literal-p)))))
+ (t
+ (caml-skip-comments-forward)
+ (if (caml-at-phrase-start-p) (forward-char))
+ (while (and (cond
+ ((re-search-forward caml-phrase-sep-keywords max-pos 'move)
+ (goto-char (match-beginning 0)) t))
+ (or (not (or (bolp) (looking-at ";;")))
+ (caml-in-comment-p)
+ (caml-in-literal-p)))
+ (forward-char))
+ (setq end (+ (point) (if (looking-at ";;") 2 0)))
+ (while (and
+ (setq kwop (caml-find-kwop caml-phrase-sep-keywords min-pos))
+ (not (string= kwop ";;"))
+ (not (bolp))))
+ (if (string= kwop ";;") (forward-char 2))
+ (if (not kwop) (goto-char min-pos))
+ (caml-skip-comments-forward)
+ (setq beg (point))
+ (if (>= beg end) (error "no phrase before point"))
+ (goto-char end)))
+ (caml-skip-comments-forward)
+ beg))
+
+(defun caml-mark-phrase (&optional min-pos max-pos)
+ "Put mark at end of this OCaml phrase, point at beginning.
+"
+ (interactive)
+ (let* ((beg (caml-find-phrase min-pos max-pos)) (end (point)))
+ (push-mark)
+ (goto-char beg)
+ (cons beg end)))
+
+;;itz Fri Sep 25 12:58:13 PDT 1998 support for adding change-log entries
+(defun caml-current-defun ()
+ (save-excursion
+ (caml-mark-phrase)
+ (if (not (looking-at caml-phrase-start-keywords)) nil
+ (re-search-forward caml-phrase-start-keywords)
+ (let ((done nil))
+ (while (not done)
+ (cond
+ ((looking-at "\\s ")
+ (skip-syntax-forward " "))
+ ((char-equal (following-char) ?\( )
+ (forward-sexp 1))
+ ((char-equal (following-char) ?')
+ (skip-syntax-forward "w_"))
+ (t (setq done t)))))
+ (re-search-forward "\\(\\sw\\|\\s_\\)+")
+ (match-string 0))))
+
+(defun caml-overlap (b1 e1 b2 e2)
+ (<= (max b1 b2) (min e1 e2)))
+
+;this clears the last comment cache if necessary
+(defun caml-before-change-function (begin end)
+ (if (and caml-last-noncomment-pos
+ (> caml-last-noncomment-pos begin))
+ (setq caml-last-noncomment-pos nil))
+ (if (and (marker-position caml-last-comment-start)
+ (marker-position caml-last-comment-end)
+ (caml-overlap begin end
+ caml-last-comment-start
+ caml-last-comment-end))
+ (prog2
+ (set-marker caml-last-comment-start nil)
+ (set-marker caml-last-comment-end nil)))
+ (let ((orig-function (default-value 'before-change-function)))
+ (if orig-function (funcall orig-function begin end))))
+
+(defun caml-in-literal-p ()
+ "Returns non-nil if point is inside a caml literal."
+ (let* ((start-literal (concat "[\"" caml-quote-char "]"))
+ (char-literal
+ (concat "\\([^\\]\\|\\\\\\.\\|\\\\[0-9][0-9][0-9]\\)"
+ caml-quote-char))
+ (pos (point))
+ (eol (progn (end-of-line 1) (point)))
+ state in-str)
+ (beginning-of-line 1)
+ (while (and (not state)
+ (re-search-forward start-literal eol t)
+ (<= (point) pos))
+ (cond
+ ((string= (caml-match-string 0) "\"")
+ (setq in-str t)
+ (while (and in-str (not state)
+ (re-search-forward "\"\\|\\\\\"" eol t))
+ (if (> (point) pos) (setq state t))
+ (if (string= (caml-match-string 0) "\"") (setq in-str nil)))
+ (if in-str (setq state t)))
+ ((looking-at char-literal)
+ (if (and (>= pos (match-beginning 0)) (< pos (match-end 0)))
+ (setq state t)
+ (goto-char (match-end 0))))))
+ (goto-char pos)
+ state))
+
+(defun caml-forward-comment ()
+ "Skip one (eventually nested) comment."
+ (let ((count 1) match)
+ (while (> count 0)
+ (if (not (re-search-forward "(\\*\\|\\*)" nil 'move))
+ (setq count -1)
+ (setq match (caml-match-string 0))
+ (cond
+ ((caml-in-literal-p)
+ nil)
+ ((string= match comment-start)
+ (setq count (1+ count)))
+ (t
+ (setq count (1- count))))))
+ (= count 0)))
+
+(defun caml-backward-comment ()
+ "Skip one (eventually nested) comment."
+ (let ((count 1) match)
+ (while (> count 0)
+ (if (not (re-search-backward "(\\*\\|\\*)" nil 'move))
+ (setq count -1)
+ (setq match (caml-match-string 0))
+ (cond
+ ((caml-in-literal-p)
+ nil)
+ ((string= match comment-start)
+ (setq count (1- count)))
+ (t
+ (setq count (1+ count))))))
+ (= count 0)))
+
+(defun caml-in-comment-p ()
+ "Returns non-nil if point is inside a caml comment.
+Returns nil for the parenthesis openning a comment."
+ ;;we look for comments differently than literals. there are two
+ ;;reasons for this. first, caml has nested comments and it is not so
+ ;;clear that parse-partial-sexp supports them; second, if proper
+ ;;style is used, literals are never split across lines, so we don't
+ ;;have to worry about bogus phrase breaks inside literals, while we
+ ;;have to account for that possibility in comments.
+ (if caml-last-comment-start
+ (save-excursion
+ (let* ((cached-pos caml-last-noncomment-pos)
+ (cached-begin (marker-position caml-last-comment-start))
+ (cached-end (marker-position caml-last-comment-end)))
+ (cond
+ ((and cached-begin cached-end
+ (< cached-begin (point)) (< (point) cached-end)) t)
+ ((and cached-pos (= cached-pos (point))) nil)
+ ((and cached-pos (> cached-pos (point))
+ (< (abs (- cached-pos (point))) caml-lookback-limit))
+ (let (end found (here (point)))
+ ; go back to somewhere sure
+ (goto-char cached-pos)
+ (while (> (point) here)
+ ; look for the end of a comment
+ (while (and (if (search-backward comment-end (1- here) 'move)
+ (setq end (match-end 0))
+ (setq end nil))
+ (caml-in-literal-p)))
+ (if end (setq found (caml-backward-comment))))
+ (if (and found (= (point) here)) (setq end nil))
+ (if (not end)
+ (setq caml-last-noncomment-pos here)
+ (set-marker caml-last-comment-start (point))
+ (set-marker caml-last-comment-end end))
+ end))
+ (t
+ (let (begin found (here (point)))
+ ;; go back to somewhere sure (or far enough)
+ (goto-char
+ (if cached-pos cached-pos (- (point) caml-lookback-limit)))
+ (while (< (point) here)
+ ;; look for the beginning of a comment
+ (while (and (if (search-forward comment-start (1+ here) 'move)
+ (setq begin (match-beginning 0))
+ (setq begin nil))
+ (caml-in-literal-p)))
+ (if begin (setq found (caml-forward-comment))))
+ (if (and found (= (point) here)) (setq begin nil))
+ (if (not begin)
+ (setq caml-last-noncomment-pos here)
+ (set-marker caml-last-comment-start begin)
+ (set-marker caml-last-comment-end (point)))
+ begin)))))))
+
+;; Various constants and regexps
+
+(defconst caml-before-expr-prefix
+ (concat "\\<\\(asr\\|begin\\|class\\|do\\(wnto\\)?\\|else"
+ "\\|i\\(f\\|n\\(herit\\|itializer\\)?\\)"
+ "\\|f\\(or\\|un\\(ct\\(ion\\|or\\)\\)?\\)"
+ "\\|l\\(and\\|or\\|s[lr]\\|xor\\)\\|m\\(atch\\|od\\)"
+ "\\|o[fr]\\|parser\\|s\\(ig\\|truct\\)\\|t\\(hen\\|o\\|ry\\)"
+ "\\|w\\(h\\(en\\|ile\\)\\|ith\\)\\)\\>\\|:begin\\>"
+ "\\|[=<>@^|&+-*/$%][!$%*+-./:<=>?@^|~]*\\|:[:=]\\|[[({,;]")
+
+ "Keywords that may appear immediately before an expression.
+Used to distinguish it from toplevel let construct.")
+
+(defconst caml-matching-kw-regexp
+ (concat
+ "\\<\\(and\\|do\\(ne\\|wnto\\)?\\|e\\(lse\\|nd\\)\\|in\\|t\\(hen\\|o\\)"
+ "\\|with\\)\\>\\|[^[|]|")
+ "Regexp used in caml mode for skipping back over nested blocks.")
+
+(defconst caml-matching-kw-alist
+ '(("|" . caml-find-pipe-match)
+ (";" . caml-find-semi-match)
+ ("," . caml-find-comma-match)
+ ("end" . caml-find-end-match)
+ ("done" . caml-find-done-match)
+ ("in" . caml-find-in-match)
+ ("with" . caml-find-with-match)
+ ("else" . caml-find-else-match)
+ ("then" . caml-find-then-match)
+ ("to" . caml-find-done-match)
+ ("downto" . caml-find-done-match)
+ ("do" . caml-find-done-match)
+ ("and" . caml-find-and-match))
+
+ "Association list used in caml mode for skipping back over nested blocks.")
+
+(defconst caml-kwop-regexps (make-vector 9 nil)
+ "Array of regexps representing caml keywords of different priorities.")
+
+(defun caml-in-shebang-line ()
+ (save-excursion
+ (beginning-of-line)
+ (and (= 1 (point)) (looking-at "#!"))))
+
+(defun caml-in-expr-p ()
+ (let ((pos (point)) (in-expr t))
+ (caml-find-kwop
+ (concat caml-before-expr-prefix "\\|"
+ caml-matching-kw-regexp "\\|"
+ (aref caml-kwop-regexps caml-max-indent-priority)))
+ (cond
+ ; special case for #! at beginning of file
+ ((caml-in-shebang-line) (setq in-expr nil))
+ ; special case for ;;
+ ((and (> (point) 1) (= (preceding-char) ?\;) (= (following-char) ?\;))
+ (setq in-expr nil))
+ ((looking-at caml-before-expr-prefix)
+ (if (not (looking-at "(\\*")) (goto-char (match-end 0)))
+ (skip-chars-forward " \t\n")
+ (while (looking-at "(\\*")
+ (forward-char)
+ (caml-forward-comment)
+ (skip-chars-forward " \t\n"))
+ (if (<= pos (point)) (setq in-expr nil))))
+ (goto-char pos)
+ in-expr))
+
+(defun caml-at-sexp-close-p ()
+ (or (char-equal ?\) (following-char))
+ (char-equal ?\] (following-char))
+ (char-equal ?} (following-char))))
+
+(defun caml-find-kwop (kwop-regexp &optional min-pos)
+ "Look back for a caml keyword or operator matching KWOP-REGEXP.
+Second optional argument MIN-POS bounds the search.
+
+Ignore occurences inside literals. If found, return a list of two
+values: the actual text of the keyword or operator, and a boolean
+indicating whether the keyword was one we looked for explicitly
+{non-nil}, or on the other hand one of the block-terminating
+keywords."
+
+ (let ((start-literal (concat "[\"" caml-quote-char "]"))
+ found kwop)
+ (while (and (> (point) 1) (not found)
+ (re-search-backward kwop-regexp min-pos 'move))
+ (setq kwop (caml-match-string 0))
+ (cond
+ ((looking-at "(\\*")
+ (if (> (point) 1) (backward-char)))
+ ((caml-in-comment-p)
+ (search-backward "(" min-pos 'move))
+ ((looking-at start-literal))
+ ((caml-in-literal-p)
+ (re-search-backward start-literal min-pos 'move)) ;ugly hack
+ ((setq found t))))
+ (if found
+ (if (not (string-match "\\`[^|[]|[^]|]?\\'" kwop)) ;arrrrgh!!
+ kwop
+ (forward-char 1) "|") nil)))
+
+; Association list of indentation values based on governing keywords.
+;
+;Each element is of the form (KEYWORD OP-TYPE PRIO INDENT). OP-TYPE is
+;non-nil for operator-type nodes, which affect indentation in a
+;different way from keywords: subsequent lines are indented to the
+;actual occurrence of an operator, but relative to the indentation of
+;the line where the governing keyword occurs.
+
+(defconst caml-no-indent 0)
+
+(defconst caml-kwop-alist
+ '(("begin" nil 6 caml-begin-indent)
+ (":begin" nil 6 caml-begin-indent) ; hack
+ ("class" nil 0 caml-class-indent)
+ ("constraint" nil 0 caml-val-indent)
+ ("sig" nil 1 caml-sig-indent)
+ ("struct" nil 1 caml-struct-indent)
+ ("exception" nil 0 caml-exception-indent)
+ ("for" nil 6 caml-for-indent)
+ ("fun" nil 3 caml-fun-indent)
+ ("function" nil 3 caml-function-indent)
+ ("if" nil 6 caml-if-indent)
+ ("if-else" nil 6 caml-if-else-indent)
+ ("include" nil 0 caml-include-indent)
+ ("inherit" nil 0 caml-inherit-indent)
+ ("initializer" nil 0 caml-initializer-indent)
+ ("let" nil 6 caml-let-indent)
+ ("let-in" nil 6 caml-let-in-indent)
+ ("match" nil 6 caml-match-indent)
+ ("method" nil 0 caml-method-indent)
+ ("module" nil 0 caml-module-indent)
+ ("object" nil 6 caml-object-indent)
+ ("of" nil 7 caml-of-indent)
+ ("open" nil 0 caml-no-indent)
+ ("parser" nil 3 caml-parser-indent)
+ ("try" nil 6 caml-try-indent)
+ ("type" nil 0 caml-type-indent)
+ ("val" nil 0 caml-val-indent)
+ ("when" nil 2 caml-if-indent)
+ ("while" nil 6 caml-while-indent)
+ ("::" t 5 caml-::-indent)
+ ("@" t 4 caml-@-indent)
+ ("^" t 4 caml-@-indent)
+ (":=" nil 3 caml-:=-indent)
+ ("<-" nil 3 caml-<--indent)
+ ("->" nil 2 caml-->-indent)
+ ("\[" t 8 caml-lb-indent)
+ ("{" t 8 caml-lc-indent)
+ ("\(" t 8 caml-lp-indent)
+ ("|" nil 2 caml-no-indent)
+ (";;" nil 0 caml-no-indent))
+; if-else and let-in are not keywords but idioms
+; "|" is not in the regexps
+; all these 3 values correspond to hard-coded names
+
+"Association list of indentation values based on governing keywords.
+
+Each element is of the form (KEYWORD OP-TYPE PRIO INDENT). OP-TYPE is
+non-nil for operator-type nodes, which affect indentation in a
+different way from keywords: subsequent lines are indented to the
+actual occurrence of an operator, but relative to the indentation of
+the line where the governing keyword occurs.")
+
+;;Originally, we had caml-kwop-regexp create these at runtime, from an
+;;additional field in caml-kwop-alist. That proved way too slow,
+;;although I still can't understand why. itz
+
+(aset caml-kwop-regexps 0
+ (concat
+ "\\<\\(begin\\|object\\|for\\|s\\(ig\\|truct\\)\\|while\\)\\>"
+ "\\|:begin\\>\\|[[({]\\|;;"))
+(aset caml-kwop-regexps 1
+ (concat (aref caml-kwop-regexps 0) "\\|\\<\\(class\\|module\\)\\>"))
+(aset caml-kwop-regexps 2
+ (concat
+ (aref caml-kwop-regexps 1)
+ "\\|\\<\\(fun\\(ction\\)?\\|initializer\\|let\\|m\\(atch\\|ethod\\)"
+ "\\|parser\\|try\\|val\\)\\>\\|->"))
+(aset caml-kwop-regexps 3
+ (concat (aref caml-kwop-regexps 2) "\\|\\<if\\|when\\>"))
+(aset caml-kwop-regexps 4
+ (concat (aref caml-kwop-regexps 3) "\\|:=\\|<-"))
+(aset caml-kwop-regexps 5
+ (concat (aref caml-kwop-regexps 4) "\\|@"))
+(aset caml-kwop-regexps 6
+ (concat (aref caml-kwop-regexps 5) "\\|::\\|\\^"))
+(aset caml-kwop-regexps 7
+ (concat
+ (aref caml-kwop-regexps 0)
+ "\\|\\<\\(constraint\\|exception\\|in\\(herit\\|clude\\)"
+ "\\|o\\(f\\|pen\\)\\|type\\|val\\)\\>"))
+(aset caml-kwop-regexps 8
+ (concat (aref caml-kwop-regexps 6)
+ "\\|\\<\\(constraint\\|exception\\|in\\(herit\\|clude\\)"
+ "\\|o\\(f\\|pen\\)\\|type\\)\\>"))
+
+(defun caml-find-done-match ()
+ (let ((unbalanced 1) (kwop t))
+ (while (and (not (= 0 unbalanced)) kwop)
+ (setq kwop (caml-find-kwop "\\<\\(done\\|for\\|while\\)\\>"))
+ (cond
+ ((not kwop))
+ ((string= kwop "done") (setq unbalanced (1+ unbalanced)))
+ (t (setq unbalanced (1- unbalanced)))))
+ kwop))
+
+(defun caml-find-end-match ()
+ (let ((unbalanced 1) (kwop t))
+ (while (and (not (= 0 unbalanced)) kwop)
+ (setq kwop
+ (caml-find-kwop
+ "\\<\\(end\\|begin\\|object\\|s\\(ig\\|truct\\)\\)\\>\\|:begin\\>\\|;;"))
+ (cond
+ ((not kwop))
+ ((string= kwop ";;") (setq kwop nil) (forward-line 1))
+ ((string= kwop "end") (setq unbalanced (1+ unbalanced)))
+ ( t (setq unbalanced (1- unbalanced)))))
+ (if (string= kwop ":begin") "begin"
+ kwop)))
+
+(defun caml-find-in-match ()
+ (let ((unbalanced 1) (kwop t))
+ (while (and (not (= 0 unbalanced)) kwop)
+ (setq kwop (caml-find-kwop "\\<\\(in\\|let\\|end\\)\\>"))
+ (cond
+ ((not kwop))
+ ((string= kwop "end") (caml-find-end-match))
+ ((string= kwop "in") (setq unbalanced (1+ unbalanced)))
+ (t (setq unbalanced (1- unbalanced)))))
+ kwop))
+
+(defun caml-find-with-match ()
+ (let ((unbalanced 1) (kwop t))
+ (while (and (not (= 0 unbalanced)) kwop)
+ (setq kwop
+ (caml-find-kwop
+ "\\<\\(with\\|try\\|m\\(atch\\|odule\\)\\|functor\\)\\>\\|[{}()]"))
+ (cond
+ ((not kwop))
+ ((caml-at-sexp-close-p)
+ (caml-find-paren-match (following-char)))
+ ((string= kwop "with")
+ (setq unbalanced (1+ unbalanced)))
+ ((or (string= kwop "module")
+ (string= kwop "functor")
+ (string= kwop "{")
+ (string= kwop "("))
+ (setq unbalanced 0))
+ (t (setq unbalanced (1- unbalanced)))))
+ kwop))
+
+(defun caml-find-paren-match (close)
+ (let ((unbalanced 1)
+ (regexp (cond ((= close ?\)) "[()]")
+ ((= close ?\]) "[][]")
+ ((= close ?\}) "[{}]"))))
+ (while (and (> unbalanced 0)
+ (caml-find-kwop regexp))
+ (if (= close (following-char))
+ (setq unbalanced (1+ unbalanced))
+ (setq unbalanced (1- unbalanced))))))
+
+(defun caml-find-then-match (&optional from-else)
+ (let ((bol (if from-else
+ (save-excursion
+ (progn (beginning-of-line) (point)))))
+ kwop done matching-fun)
+ (while (not done)
+ (setq kwop
+ (caml-find-kwop
+ "\\<\\(e\\(nd\\|lse\\)\\|done\\|then\\|if\\|with\\)\\>\\|[])};]"))
+ (cond
+ ((not kwop) (setq done t))
+ ((caml-at-sexp-close-p)
+ (caml-find-paren-match (following-char)))
+ ((string= kwop "if") (setq done t))
+ ((string= kwop "then")
+ (if (not from-else) (setq kwop (caml-find-then-match))))
+ ((setq matching-fun (cdr-safe (assoc kwop caml-matching-kw-alist)))
+ (setq kwop (funcall matching-fun)))))
+ (if (and bol (>= (point) bol))
+ "if-else"
+ kwop)))
+
+(defun caml-find-pipe-match ()
+ (let ((done nil) (kwop)
+ (re (concat
+ "\\<\\(try\\|match\\|with\\|function\\|parser\\|type"
+ "\\|e\\(nd\\|lse\\)\\|done\\|then\\|in\\)\\>"
+ "\\|[^[|]|\\|[])}]")))
+ (while (not done)
+ (setq kwop (caml-find-kwop re))
+ (cond
+ ((not kwop) (setq done t))
+ ((looking-at "[^[|]\\(|\\)")
+ (goto-char (match-beginning 1))
+ (setq kwop "|")
+ (setq done t))
+ ((caml-at-sexp-close-p)
+ (caml-find-paren-match (following-char)))
+ ((string= kwop "with")
+ (setq kwop (caml-find-with-match))
+ (setq done t))
+ ((string= kwop "parser")
+ (if (re-search-backward "\\<with\\>" (- (point) 5) t)
+ (setq kwop (caml-find-with-match)))
+ (setq done t))
+ ((string= kwop "done") (caml-find-done-match))
+ ((string= kwop "end") (caml-find-end-match))
+ ((string= kwop "then") (caml-find-then-match))
+ ((string= kwop "else") (caml-find-else-match))
+ ((string= kwop "in") (caml-find-in-match))
+ (t (setq done t))))
+ kwop))
+
+(defun caml-find-and-match ()
+ (let ((done nil) (kwop))
+ (while (not done)
+ (setq kwop (caml-find-kwop
+ "\\<\\(object\\|exception\\|let\\|type\\|end\\|in\\)\\>"))
+ (cond
+ ((not kwop) (setq done t))
+ ((string= kwop "end") (caml-find-end-match))
+ ((string= kwop "in") (caml-find-in-match))
+ (t (setq done t))))
+ kwop))
+
+(defun caml-find-else-match ()
+ (caml-find-then-match t))
+
+(defun caml-find-semi-match ()
+ (caml-find-kwop-skipping-blocks 2))
+
+(defun caml-find-comma-match ()
+ (caml-find-kwop-skipping-blocks 3))
+
+(defun caml-find-kwop-skipping-blocks (prio)
+ "Look back for a caml keyword matching caml-kwop-regexps [PRIO].
+
+ Skip nested blocks."
+
+ (let ((done nil) (kwop nil) (matching-fun)
+ (kwop-list (aref caml-kwop-regexps prio)))
+ (while (not done)
+ (setq kwop (caml-find-kwop
+ (concat caml-matching-kw-regexp
+ (cond ((> prio 3) "\\|[])},;]\\|")
+ ((> prio 2) "\\|[])};]\\|")
+ (t "\\|[])}]\\|"))
+ kwop-list)))
+ (cond
+ ((not kwop) (setq done t))
+ ((caml-at-sexp-close-p)
+ (caml-find-paren-match (following-char)))
+ ((or (string= kwop ";;")
+ (and (string= kwop ";") (= (preceding-char) ?\;)))
+ (forward-line 1)
+ (setq kwop ";;")
+ (setq done t))
+ ((and (>= prio 2) (string= kwop "|")) (setq done t))
+ ((string= kwop "end") (caml-find-end-match))
+ ((string= kwop "done") (caml-find-done-match))
+ ((string= kwop "in")
+ (cond ((and (caml-find-in-match) (>= prio 2))
+ (setq kwop "let-in")
+ (setq done t))))
+ ((and (string= kwop "parser") (>= prio 2)
+ (re-search-backward "\\<with\\>" (- (point) 5) t))
+ (setq kwop (caml-find-with-match))
+ (setq done t))
+ ((setq matching-fun (cdr-safe (assoc kwop caml-matching-kw-alist)))
+ (setq kwop (funcall matching-fun))
+ (if (looking-at kwop-list) (setq done t)))
+ (t (let* ((kwop-info (assoc kwop caml-kwop-alist))
+ (is-op (and (nth 1 kwop-info)
+ ; check that we are not at beginning of line
+ (let ((pos (point)) bti)
+ (back-to-indentation)
+ (setq bti (point))
+ (goto-char pos)
+ (< bti pos)))))
+ (if (and is-op (looking-at
+ (concat (regexp-quote kwop)
+ "|?[ \t]*\\(\n\\|(\\*\\)")))
+ (setq kwop-list
+ (aref caml-kwop-regexps (nth 2 kwop-info)))
+ (setq done t))))))
+ kwop))
+
+(defun caml-compute-basic-indent (prio)
+ "Compute indent of current caml line, ignoring leading keywords.
+
+Find the `governing node' for current line. Compute desired
+indentation based on the node and the indentation alists.
+Assumes point is exactly at line indentation.
+Does not preserve point."
+
+ (let* (in-expr
+ (kwop (cond
+ ((looking-at ";;")
+ (beginning-of-line 1))
+ ((looking-at "|\\([^]|]\\|\\'\\)")
+ (caml-find-pipe-match))
+ ((and (looking-at caml-phrase-start-keywords)
+ (caml-in-expr-p))
+ (caml-find-end-match))
+ ((and (looking-at caml-matching-kw-regexp)
+ (assoc (caml-match-string 0) caml-matching-kw-alist))
+ (funcall (cdr-safe (assoc (caml-match-string 0)
+ caml-matching-kw-alist))))
+ ((looking-at
+ (aref caml-kwop-regexps caml-max-indent-priority))
+ (let* ((kwop (caml-match-string 0))
+ (kwop-info (assoc kwop caml-kwop-alist))
+ (prio (if kwop-info (nth 2 kwop-info)
+ caml-max-indent-priority)))
+ (if (and (looking-at (aref caml-kwop-regexps 0))
+ (not (looking-at "object"))
+ (caml-in-expr-p))
+ (setq in-expr t))
+ (caml-find-kwop-skipping-blocks prio)))
+ (t
+ (if (and (= prio caml-max-indent-priority) (caml-in-expr-p))
+ (setq in-expr t))
+ (caml-find-kwop-skipping-blocks prio))))
+ (kwop-info (assoc kwop caml-kwop-alist))
+ (indent-diff
+ (cond
+ ((not kwop-info) (beginning-of-line 1) 0)
+ ((looking-at "[[({][|<]?[ \t]*")
+ (length (caml-match-string 0)))
+ ((nth 1 kwop-info) (symbol-value (nth 3 kwop-info)))
+ (t
+ (let ((pos (point)))
+ (back-to-indentation)
+; (if (looking-at "\\<let\\>") (goto-char pos))
+ (- (symbol-value (nth 3 kwop-info))
+ (if (looking-at "|") caml-|-extra-indent 0))))))
+ (extra (if in-expr caml-apply-extra-indent 0)))
+ (+ indent-diff extra (current-column))))
+
+(defconst caml-leading-kwops-regexp
+ (concat
+ "\\<\\(and\\|do\\(ne\\|wnto\\)?\\|e\\(lse\\|nd\\)\\|in"
+ "\\|t\\(hen\\|o\\)\\|with\\)\\>\\|[]|})]")
+
+ "Regexp matching caml keywords which need special indentation.")
+
+(defconst caml-leading-kwops-alist
+ '(("and" caml-and-extra-indent 2)
+ ("do" caml-do-extra-indent 0)
+ ("done" caml-done-extra-indent 0)
+ ("else" caml-else-extra-indent 3)
+ ("end" caml-end-extra-indent 0)
+ ("in" caml-in-extra-indent 2)
+ ("then" caml-then-extra-indent 3)
+ ("to" caml-to-extra-indent 0)
+ ("downto" caml-to-extra-indent 0)
+ ("with" caml-with-extra-indent 2)
+ ("|" caml-|-extra-indent 2)
+ ("]" caml-rb-extra-indent 0)
+ ("}" caml-rc-extra-indent 0)
+ (")" caml-rp-extra-indent 0))
+
+ "Association list of special caml keyword indent values.
+
+Each member is of the form (KEYWORD EXTRA-INDENT PRIO) where
+EXTRA-INDENT is the variable holding extra indentation amount for
+KEYWORD (usually negative) and PRIO is upper bound on priority of
+matching nodes to determine KEYWORD's final indentation.")
+
+(defun caml-compute-final-indent ()
+ (save-excursion
+ (back-to-indentation)
+ (cond
+ ((and (bolp) (looking-at comment-start-skip)) (current-column))
+ ((caml-in-comment-p)
+ (let ((closing (looking-at "\\*)"))
+ (comment-mark (looking-at "\\*")))
+ (caml-backward-comment)
+ (looking-at comment-start-skip)
+ (+ (current-column)
+ (cond
+ (closing 1)
+ (comment-mark 1)
+ (t (- (match-end 0) (match-beginning 0)))))))
+ (t (let* ((leading (looking-at caml-leading-kwops-regexp))
+ (assoc-val (if leading (assoc (caml-match-string 0)
+ caml-leading-kwops-alist)))
+ (extra (if leading (symbol-value (nth 1 assoc-val)) 0))
+ (prio (if leading (nth 2 assoc-val)
+ caml-max-indent-priority))
+ (basic (caml-compute-basic-indent prio)))
+ (max 0 (if extra (+ extra basic) (current-column))))))))
+
+
+
+(defun caml-split-string ()
+ "Called whenever a line is broken inside a caml string literal."
+ (insert-before-markers "\"^\"")
+ (backward-char 1))
+
+(defadvice indent-new-comment-line (around
+ caml-indent-new-comment-line
+ activate)
+
+ "Handle multi-line strings in caml mode."
+
+;this advice doesn't make sense in other modes. I wish there were a
+;cleaner way to do this: I haven't found one.
+
+ (let ((hooked (and (eq major-mode 'caml-mode) (caml-in-literal-p)))
+ (split-mark))
+ (if (not hooked) nil
+ (setq split-mark (set-marker (make-marker) (point)))
+ (caml-split-string))
+ ad-do-it
+ (if (not hooked) nil
+ (goto-char split-mark)
+ (set-marker split-mark nil))))
+
+(defadvice newline-and-indent (around
+ caml-newline-and-indent
+ activate)
+
+ "Handle multi-line strings in caml mode."
+
+ (let ((hooked (and (eq major-mode 'caml-mode) (caml-in-literal-p)))
+ (split-mark))
+ (if (not hooked) nil
+ (setq split-mark (set-marker (make-marker) (point)))
+ (caml-split-string))
+ ad-do-it
+ (if (not hooked) nil
+ (goto-char split-mark)
+ (set-marker split-mark nil))))
+
+(defun caml-electric-pipe ()
+ "If inserting a | or } operator at beginning of line, reindent the line.
+
+Unfortunately there is a situation where this mechanism gets
+confused. It's when | is the first character of a |] sequence. This is
+a misfeature of caml syntax and cannot be fixed, however, as a
+workaround, the electric ] inserts | itself if the matching [ is
+followed by |."
+
+ (interactive "*")
+ (let ((electric (and caml-electric-indent
+ (caml-in-indentation)
+ (not (caml-in-comment-p)))))
+ (self-insert-command 1)
+ (if electric (save-excursion (caml-indent-command)))))
+
+(defun caml-electric-rb ()
+ "If inserting a ] operator at beginning of line, reindent the line.
+
+Also, if the matching [ is followed by a | and this ] is not preceded
+by |, insert one."
+
+ (interactive "*")
+ (let* ((prec (preceding-char))
+ (use-pipe (and caml-electric-close-vector
+ (not (caml-in-comment-p))
+ (not (caml-in-literal-p))
+ (or (not (numberp prec))
+ (not (char-equal ?| prec)))))
+ (electric (and caml-electric-indent
+ (caml-in-indentation)
+ (not (caml-in-comment-p)))))
+ (self-insert-command 1)
+ (if electric (save-excursion (caml-indent-command)))
+ (if (and use-pipe
+ (save-excursion
+ (condition-case nil
+ (prog2
+ (backward-list 1)
+ (looking-at "\\[|"))
+ (error ""))))
+ (save-excursion
+ (backward-char 1)
+ (insert "|")))))
+
+(defun caml-abbrev-hook ()
+ "If inserting a leading keyword at beginning of line, reindent the line."
+ ;itz unfortunately we need a special case
+ (if (and (not (caml-in-comment-p)) (not (= last-command-char ?_)))
+ (let* ((bol (save-excursion (beginning-of-line) (point)))
+ (kw (save-excursion
+ (and (re-search-backward "^[ \t]*\\(\\sw+\\)\\=" bol t)
+ (caml-match-string 1)))))
+ (if kw
+ (let ((indent (save-excursion
+ (goto-char (match-beginning 1))
+ (caml-indent-command)
+ (current-column)))
+ (abbrev-correct (if (= last-command-char ?\ ) 1 0)))
+ (indent-to (- indent
+ (or
+ (symbol-value
+ (nth 1
+ (assoc kw caml-leading-kwops-alist)))
+ 0)
+ abbrev-correct)))))))
+
+; (defun caml-indent-phrase ()
+; (interactive "*")
+; (let ((bounds (caml-mark-phrase)))
+; (indent-region (car bounds) (cdr bounds) nil)))
+
+;;; Additional commands by Didier to report errors in toplevel mode
+
+(defun caml-skip-blank-forward ()
+ (if (looking-at "[ \t\n]*\\((\\*\\([^*]\\|[^(]\\*[^)]\\)*\\*)[ \t\n]*\\)*")
+ (goto-char (match-end 0))))
+
+;; to mark phrases, so that repeated calls will take several of them
+;; knows little about OCaml except literals and comments, so it should work
+;; with other dialects as long as ;; marks the end of phrase.
+
+(defun caml-indent-phrase (arg)
+ "Indent current phrase
+with prefix arg, indent that many phrases starting with the current phrase."
+ (interactive "p")
+ (save-excursion
+ (let ((beg (caml-find-phrase)))
+ (while (progn (setq arg (- arg 1)) (> arg 0)) (caml-find-phrase))
+ (indent-region beg (point) nil))))
+
+(defun caml-indent-buffer ()
+ (interactive)
+ (indent-region (point-min) (point-max) nil))
+
+(defun caml-backward-to-less-indent (&optional n)
+ "Move cursor back N lines with less or same indentation."
+ (interactive "p")
+ (beginning-of-line 1)
+ (if (< n 0) (caml-forward-to-less-indent (- n))
+ (while (> n 0)
+ (let ((i (current-indentation)))
+ (forward-line -1)
+ (while (or (> (current-indentation) i)
+ (caml-in-comment-p)
+ (looking-at
+ (concat "[ \t]*\\(\n\\|" comment-start-skip "\\)")))
+ (forward-line -1)))
+ (setq n (1- n))))
+ (back-to-indentation))
+
+(defun caml-forward-to-less-indent (&optional n)
+ "Move cursor back N lines with less or same indentation."
+ (interactive "p")
+ (beginning-of-line 1)
+ (if (< n 0) (caml-backward-to-less-indent (- n))
+ (while (> n 0)
+ (let ((i (current-indentation)))
+ (forward-line 1)
+ (while (or (> (current-indentation) i)
+ (caml-in-comment-p)
+ (looking-at
+ (concat "[ \t]*\\(\n\\|" comment-start-skip "\\)")))
+ (forward-line 1)))
+ (setq n (1- n))))
+ (back-to-indentation))
+
+(defun caml-insert-begin-form ()
+ "Inserts a nicely formatted begin-end form, leaving a mark after end."
+ (interactive "*")
+ (let ((prec (preceding-char)))
+ (if (and (numberp prec) (not (char-equal ?\ (char-syntax prec))))
+ (insert " ")))
+ (let* ((c (current-indentation)) (i (+ caml-begin-indent c)))
+ (insert "begin\n\nend")
+ (push-mark)
+ (indent-line-to c)
+ (forward-line -1)
+ (indent-line-to i)))
+
+(defun caml-insert-for-form ()
+ "Inserts a nicely formatted for-do-done form, leaving a mark after do(ne)."
+ (interactive "*")
+ (let ((prec (preceding-char)))
+ (if (and (numberp prec) (not (char-equal ?\ (char-syntax prec))))
+ (insert " ")))
+ (let* ((c (current-indentation)) (i (+ caml-for-indent c)))
+ (insert "for do\n\ndone")
+ (push-mark)
+ (indent-line-to c)
+ (forward-line -1)
+ (indent-line-to i)
+ (push-mark)
+ (beginning-of-line 1)
+ (backward-char 4)))
+
+(defun caml-insert-if-form ()
+ "Insert nicely formatted if-then-else form leaving mark after then, else."
+ (interactive "*")
+ (let ((prec (preceding-char)))
+ (if (and (numberp prec) (not (char-equal ?\ (char-syntax prec))))
+ (insert " ")))
+ (let* ((c (current-indentation)) (i (+ caml-if-indent c)))
+ (insert "if\n\nthen\n\nelse\n")
+ (indent-line-to i)
+ (push-mark)
+ (forward-line -1)
+ (indent-line-to c)
+ (forward-line -1)
+ (indent-line-to i)
+ (push-mark)
+ (forward-line -1)
+ (indent-line-to c)
+ (forward-line -1)
+ (indent-line-to i)))
+
+(defun caml-insert-match-form ()
+ "Insert nicely formatted match-with form leaving mark after with."
+ (interactive "*")
+ (let ((prec (preceding-char)))
+ (if (and (numberp prec) (not (char-equal ?\ (char-syntax prec))))
+ (insert " ")))
+ (let* ((c (current-indentation)) (i (+ caml-match-indent c)))
+ (insert "match\n\nwith\n")
+ (indent-line-to i)
+ (push-mark)
+ (forward-line -1)
+ (indent-line-to c)
+ (forward-line -1)
+ (indent-line-to i)))
+
+(defun caml-insert-let-form ()
+ "Insert nicely formatted let-in form leaving mark after in."
+ (interactive "*")
+ (let ((prec (preceding-char)))
+ (if (and (numberp prec) (not (char-equal ?\ (char-syntax prec))))
+ (insert " ")))
+ (let* ((c (current-indentation)))
+ (insert "let in\n")
+ (indent-line-to c)
+ (push-mark)
+ (forward-line -1)
+ (forward-char (+ c 4))))
+
+(defun caml-insert-try-form ()
+ "Insert nicely formatted try-with form leaving mark after with."
+ (interactive "*")
+ (let ((prec (preceding-char)))
+ (if (and (numberp prec) (not (char-equal ?\ (char-syntax prec))))
+ (insert " ")))
+ (let* ((c (current-indentation)) (i (+ caml-try-indent c)))
+ (insert "try\n\nwith\n")
+ (indent-line-to i)
+ (push-mark)
+ (forward-line -1)
+ (indent-line-to c)
+ (forward-line -1)
+ (indent-line-to i)))
+
+(defun caml-insert-while-form ()
+ "Insert nicely formatted while-do-done form leaving mark after do, done."
+ (interactive "*")
+ (let ((prec (preceding-char)))
+ (if (and (numberp prec) (not (char-equal ?\ (char-syntax prec))))
+ (insert " ")))
+ (let* ((c (current-indentation)) (i (+ caml-if-indent c)))
+ (insert "while do\n\ndone")
+ (push-mark)
+ (indent-line-to c)
+ (forward-line -1)
+ (indent-line-to i)
+ (push-mark)
+ (beginning-of-line 1)
+ (backward-char 4)))
+
+(autoload 'run-caml "inf-caml" "Run an inferior OCaml process." t)
+
+(autoload 'caml-types-show-type "caml-types"
+ "Show the type of expression or pattern at point." t)
+(autoload 'caml-types-explore "caml-types"
+ "Explore type annotations by mouse dragging." t)
+
+(autoload 'caml-help "caml-help"
+ "Show documentation for qualilifed OCaml identifier." t)
+(autoload 'caml-complete "caml-help"
+ "Does completion for documented qualified OCaml identifier." t)
+(autoload 'ocaml-open-module "caml-help"
+ "Add module in documentation search path." t)
+(autoload 'ocaml-close-module "caml-help"
+ "Remove module from documentation search path." t)
+(autoload 'ocaml-add-path "caml-help"
+ "Add search path for documentation." t)
+
+;;; caml.el ends here
+
+(provide 'caml)
diff --git a/emacs/camldebug.el b/emacs/camldebug.el
new file mode 100644
index 0000000000..6e83bacccc
--- /dev/null
+++ b/emacs/camldebug.el
@@ -0,0 +1,793 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Jacques Garrigue and Ian T Zimmerman *)
+;(* *)
+;(* Copyright 1997 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;;; Run camldebug under Emacs
+;;; Derived from gdb.el.
+;;; gdb.el is Copyright (C) 1988 Free Software Foundation, Inc, and is part
+;;; of GNU Emacs
+;;; Modified by Jerome Vouillon, 1994.
+;;; Modified by Ian T. Zimmerman, 1996.
+;;; Modified by Xavier Leroy, 1997.
+
+;; This file is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 1, or (at your option)
+;; any later version.
+
+;; This file is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+;; GNU General Public License for more details.
+
+;;itz 04-06-96 I pondered basing this on gud. The potential advantages
+;;were: automatic bugfix , keymaps and menus propagation.
+;;Disadvantages: gud is not so clean itself, there is little common
+;;functionality it abstracts (most of the stuff is done in the
+;;debugger specific parts anyway), and, most seriously, gud sees it
+;;fit to add C-x C-a bindings to the _global_ map, so there would be a
+;;conflict between camldebug and gdb, for instance. While it's OK to
+;;assume that a sane person doesn't use gdb and dbx at the same time,
+;;it's not so OK (IMHO) for gdb and camldebug.
+
+;; Xavier Leroy, 21/02/97: adaptation to ocamldebug.
+
+(require 'comint)
+(require 'shell)
+(require 'caml)
+(require 'derived)
+(require 'thingatpt)
+
+;;; Variables.
+
+(defvar camldebug-last-frame)
+(defvar camldebug-delete-prompt-marker)
+(defvar camldebug-filter-accumulator nil)
+(defvar camldebug-last-frame-displayed-p)
+(defvar camldebug-filter-function)
+
+(defvar camldebug-prompt-pattern "^(ocd) *"
+ "A regexp to recognize the prompt for ocamldebug.")
+
+(defvar camldebug-overlay-event nil
+ "Overlay for displaying the current event.")
+(defvar camldebug-overlay-under nil
+ "Overlay for displaying the current event.")
+(defvar camldebug-event-marker nil
+ "Marker for displaying the current event.")
+
+(defvar camldebug-track-frame t
+ "*If non-nil, always display current frame position in another window.")
+
+(cond
+ (window-system
+ (make-face 'camldebug-event)
+ (make-face 'camldebug-underline)
+ (if (not (face-differs-from-default-p 'camldebug-event))
+ (invert-face 'camldebug-event))
+ (if (not (face-differs-from-default-p 'camldebug-underline))
+ (set-face-underline-p 'camldebug-underline t))
+ (setq camldebug-overlay-event (make-overlay 1 1))
+ (overlay-put camldebug-overlay-event 'face 'camldebug-event)
+ (setq camldebug-overlay-under (make-overlay 1 1))
+ (overlay-put camldebug-overlay-under 'face 'camldebug-underline))
+ (t
+ (setq camldebug-event-marker (make-marker))
+ (setq overlay-arrow-string "=>")))
+
+;;; Camldebug mode.
+
+(define-derived-mode camldebug-mode comint-mode "Inferior CDB"
+
+ "Major mode for interacting with an inferior ocamldebug process.
+
+The following commands are available:
+
+\\{camldebug-mode-map}
+
+\\[camldebug-display-frame] displays in the other window
+the last line referred to in the camldebug buffer.
+
+\\[camldebug-step], \\[camldebug-back] and \\[camldebug-next], in the camldebug
+window,call camldebug to step, backstep or next and then update the other window
+with the current file and position.
+
+If you are in a source file, you may select a point to break
+at, by doing \\[camldebug-break].
+
+Commands:
+Many commands are inherited from comint mode.
+Additionally we have:
+
+\\[camldebug-display-frame] display frames file in other window
+\\[camldebug-step] advance one line in program
+C-x SPACE sets break point at current line."
+
+ (mapcar 'make-local-variable
+ '(camldebug-last-frame-displayed-p camldebug-last-frame
+ camldebug-delete-prompt-marker camldebug-filter-function
+ camldebug-filter-accumulator paragraph-start))
+ (setq
+ camldebug-last-frame nil
+ camldebug-delete-prompt-marker (make-marker)
+ camldebug-filter-accumulator ""
+ camldebug-filter-function 'camldebug-marker-filter
+ comint-prompt-regexp camldebug-prompt-pattern
+ comint-dynamic-complete-functions (cons 'camldebug-complete
+ comint-dynamic-complete-functions)
+ paragraph-start comint-prompt-regexp
+ camldebug-last-frame-displayed-p t)
+ (make-local-variable 'shell-dirtrackp)
+ (setq shell-dirtrackp t)
+ (setq comint-input-sentinel 'shell-directory-tracker))
+
+;;; Keymaps.
+
+(defun camldebug-numeric-arg (arg)
+ (and arg (prefix-numeric-value arg)))
+
+(defmacro def-camldebug (name key &optional doc args)
+
+ "Define camldebug-NAME to be a command sending NAME ARGS and bound
+to KEY, with optional doc string DOC. Certain %-escapes in ARGS are
+interpreted specially if present. These are:
+
+ %m module name of current module.
+ %d directory of current source file.
+ %c number of current character position
+ %e text of the caml variable surrounding point.
+
+ The `current' source file is the file of the current buffer (if
+we're in a caml buffer) or the source file current at the last break
+or step (if we're in the camldebug buffer), and the `current' module
+name is the filename stripped of any *.ml* suffixes (this assumes the
+usual correspondence between module and file naming is observed). The
+`current' position is that of the current buffer (if we're in a source
+file) or the position of the last break or step (if we're in the
+camldebug buffer).
+
+If a numeric is present, it overrides any ARGS flags and its string
+representation is simply concatenated with the COMMAND."
+
+ (let* ((fun (intern (format "camldebug-%s" name))))
+ (list 'progn
+ (if doc
+ (list 'defun fun '(arg)
+ doc
+ '(interactive "P")
+ (list 'camldebug-call name args
+ '(camldebug-numeric-arg arg))))
+ (list 'define-key 'camldebug-mode-map
+ (concat "\C-c" key)
+ (list 'quote fun))
+ (list 'define-key 'caml-mode-map
+ (concat "\C-x\C-a" key)
+ (list 'quote fun)))))
+
+(def-camldebug "step" "\C-s" "Step one event forward.")
+(def-camldebug "backstep" "\C-k" "Step one event backward.")
+(def-camldebug "run" "\C-r" "Run the program.")
+(def-camldebug "reverse" "\C-v" "Run the program in reverse.")
+(def-camldebug "last" "\C-l" "Go to latest time in execution history.")
+(def-camldebug "backtrace" "\C-t" "Print the call stack.")
+(def-camldebug "finish" "\C-f" "Finish executing current function.")
+(def-camldebug "print" "\C-p" "Print value of symbol at point." "%e")
+(def-camldebug "display" "\C-d" "Display value of symbol at point." "%e")
+(def-camldebug "next" "\C-n" "Step one event forward (skip functions)")
+(def-camldebug "up" "<" "Go up N stack frames (numeric arg) with display")
+(def-camldebug "down" ">" "Go down N stack frames (numeric arg) with display")
+(def-camldebug "break" "\C-b" "Set breakpoint at current line."
+ "@ \"%m\" # %c")
+
+(defun camldebug-mouse-display (click)
+ "Display value of $NNN clicked on."
+ (interactive "e")
+ (let* ((start (event-start click))
+ (window (car start))
+ (pos (car (cdr start)))
+ symb)
+ (save-excursion
+ (select-window window)
+ (goto-char pos)
+ (setq symb (thing-at-point 'symbol))
+ (if (string-match "^\\$[0-9]+$" symb)
+ (camldebug-call "display" symb)))))
+
+(define-key camldebug-mode-map [mouse-2] 'camldebug-mouse-display)
+
+(defun camldebug-kill-filter (string)
+ ;gob up stupid questions :-)
+ (setq camldebug-filter-accumulator
+ (concat camldebug-filter-accumulator string))
+ (if (not (string-match "\\(.* \\)(y or n) "
+ camldebug-filter-accumulator)) nil
+ (setq camldebug-kill-output
+ (cons t (match-string 1 camldebug-filter-accumulator)))
+ (setq camldebug-filter-accumulator ""))
+ (if (string-match comint-prompt-regexp camldebug-filter-accumulator)
+ (let ((output (substring camldebug-filter-accumulator
+ (match-beginning 0))))
+ (setq camldebug-kill-output
+ (cons nil (substring camldebug-filter-accumulator 0
+ (1- (match-beginning 0)))))
+ (setq camldebug-filter-accumulator "")
+ output)
+ ""))
+
+(def-camldebug "kill" "\C-k")
+
+(defun camldebug-kill ()
+ "Kill the program."
+ (interactive)
+ (let ((camldebug-kill-output))
+ (save-excursion
+ (set-buffer current-camldebug-buffer)
+ (let ((proc (get-buffer-process (current-buffer)))
+ (camldebug-filter-function 'camldebug-kill-filter))
+ (camldebug-call "kill")
+ (while (not (and camldebug-kill-output
+ (zerop (length camldebug-filter-accumulator))))
+ (accept-process-output proc))))
+ (if (not (car camldebug-kill-output))
+ (error (cdr camldebug-kill-output))
+ (sit-for 0 300)
+ (camldebug-call-1 (if (y-or-n-p (cdr camldebug-kill-output)) "y" "n")))))
+;;FIXME: camldebug doesn't output the Hide marker on kill
+
+(defun camldebug-goto-filter (string)
+ ;accumulate onto previous output
+ (setq camldebug-filter-accumulator
+ (concat camldebug-filter-accumulator string))
+ (if (not (or (string-match (concat "\\(\n\\|\\`\\)[ \t]*\\([0-9]+\\)[ \t]+"
+ camldebug-goto-position
+ "-[0-9]+[ \t]*\\(before\\).*\n")
+ camldebug-filter-accumulator)
+ (string-match (concat "\\(\n\\|\\`\\)[ \t]*\\([0-9]+\\)"
+ "[ \t]+[0-9]+-"
+ camldebug-goto-position
+ "[ \t]*\\(after\\).*\n")
+ camldebug-filter-accumulator)))
+ nil
+ (setq camldebug-goto-output
+ (match-string 2 camldebug-filter-accumulator))
+ (setq camldebug-filter-accumulator
+ (substring camldebug-filter-accumulator (1- (match-end 0)))))
+ (if (not (string-match comint-prompt-regexp
+ camldebug-filter-accumulator)) nil
+ (setq camldebug-goto-output (or camldebug-goto-output 'fail))
+ (setq camldebug-filter-accumulator ""))
+ (if (string-match "\n\\(.*\\)\\'" camldebug-filter-accumulator)
+ (setq camldebug-filter-accumulator
+ (match-string 1 camldebug-filter-accumulator)))
+ "")
+
+(def-camldebug "goto" "\C-g")
+(defun camldebug-goto (&optional time)
+
+ "Go to the execution time TIME.
+
+Without TIME, the command behaves as follows: In the camldebug buffer,
+if the point at buffer end, goto time 0\; otherwise, try to obtain the
+time from context around point. In a caml mode buffer, try to find the
+time associated in execution history with the current point location.
+
+With a negative TIME, move that many lines backward in the camldebug
+buffer, then try to obtain the time from context around point."
+
+ (interactive "P")
+ (cond
+ (time
+ (let ((ntime (camldebug-numeric-arg time)))
+ (if (>= ntime 0) (camldebug-call "goto" nil ntime)
+ (save-selected-window
+ (select-window (get-buffer-window current-camldebug-buffer))
+ (save-excursion
+ (if (re-search-backward "^Time : [0-9]+ - pc : [0-9]+ "
+ nil t (- 1 ntime))
+ (camldebug-goto nil)
+ (error "I don't have %d times in my history"
+ (- 1 ntime))))))))
+ ((eq (current-buffer) current-camldebug-buffer)
+ (let ((time (cond
+ ((eobp) 0)
+ ((save-excursion
+ (beginning-of-line 1)
+ (looking-at "^Time : \\([0-9]+\\) - pc : [0-9]+ "))
+ (caml-string-to-int (match-string 1)))
+ ((caml-string-to-int (camldebug-format-command "%e"))))))
+ (camldebug-call "goto" nil time)))
+ (t
+ (let ((module (camldebug-module-name (buffer-file-name)))
+ (camldebug-goto-position (int-to-string (1- (point))))
+ (camldebug-goto-output) (address))
+ ;get a list of all events in the current module
+ (save-excursion
+ (set-buffer current-camldebug-buffer)
+ (let* ((proc (get-buffer-process (current-buffer)))
+ (camldebug-filter-function 'camldebug-goto-filter))
+ (camldebug-call-1 (concat "info events " module))
+ (while (not (and camldebug-goto-output
+ (zerop (length camldebug-filter-accumulator))))
+ (accept-process-output proc))
+ (setq address (if (eq camldebug-goto-output 'fail) nil
+ (re-search-backward
+ (concat "^Time : \\([0-9]+\\) - pc : "
+ camldebug-goto-output
+ " - module "
+ module "$") nil t)
+ (match-string 1)))))
+ (if address (camldebug-call "goto" nil (caml-string-to-int address))
+ (error "No time at %s at %s" module camldebug-goto-position))))))
+
+
+(defun camldebug-delete-filter (string)
+ (setq camldebug-filter-accumulator
+ (concat camldebug-filter-accumulator string))
+ (if (not (string-match
+ (concat "\\(\n\\|\\`\\)[ \t]*\\([0-9]+\\)[ \t]+[0-9]+[ \t]*in "
+ (regexp-quote camldebug-delete-file)
+ ", character "
+ camldebug-delete-position "\n")
+ camldebug-filter-accumulator)) nil
+ (setq camldebug-delete-output
+ (match-string 2 camldebug-filter-accumulator))
+ (setq camldebug-filter-accumulator
+ (substring camldebug-filter-accumulator (1- (match-end 0)))))
+ (if (not (string-match comint-prompt-regexp
+ camldebug-filter-accumulator)) nil
+ (setq camldebug-delete-output (or camldebug-delete-output 'fail))
+ (setq camldebug-filter-accumulator ""))
+ (if (string-match "\n\\(.*\\)\\'" camldebug-filter-accumulator)
+ (setq camldebug-filter-accumulator
+ (match-string 1 camldebug-filter-accumulator)))
+ "")
+
+
+(def-camldebug "delete" "\C-d")
+
+(defun camldebug-delete (&optional arg)
+ "Delete the breakpoint numbered ARG.
+
+Without ARG, the command behaves as follows: In the camldebug buffer,
+try to obtain the time from context around point. In a caml mode
+buffer, try to find the breakpoint associated with the current point
+location.
+
+With a negative ARG, look for the -ARGth breakpoint pattern in the
+camldebug buffer, then try to obtain the breakpoint info from context
+around point."
+
+ (interactive "P")
+ (cond
+ (arg
+ (let ((narg (camldebug-numeric-arg arg)))
+ (if (> narg 0) (camldebug-call "delete" nil narg)
+ (save-excursion
+ (set-buffer current-camldebug-buffer)
+ (if (re-search-backward "^Breakpoint [0-9]+ at [0-9]+ : file "
+ nil t (- 1 narg))
+ (camldebug-delete nil)
+ (error "I don't have %d breakpoints in my history"
+ (- 1 narg)))))))
+ ((eq (current-buffer) current-camldebug-buffer)
+ (let* ((bpline "^Breakpoint \\([0-9]+\\) at [0-9]+ : file ")
+ (arg (cond
+ ((eobp)
+ (save-excursion (re-search-backward bpline nil t))
+ (caml-string-to-int (match-string 1)))
+ ((save-excursion
+ (beginning-of-line 1)
+ (looking-at bpline))
+ (caml-string-to-int (match-string 1)))
+ ((caml-string-to-int (camldebug-format-command "%e"))))))
+ (camldebug-call "delete" nil arg)))
+ (t
+ (let ((camldebug-delete-file
+ (concat (camldebug-format-command "%m") ".ml"))
+ (camldebug-delete-position (camldebug-format-command "%c")))
+ (save-excursion
+ (set-buffer current-camldebug-buffer)
+ (let ((proc (get-buffer-process (current-buffer)))
+ (camldebug-filter-function 'camldebug-delete-filter)
+ (camldebug-delete-output))
+ (camldebug-call-1 "info break")
+ (while (not (and camldebug-delete-output
+ (zerop (length
+ camldebug-filter-accumulator))))
+ (accept-process-output proc))
+ (if (eq camldebug-delete-output 'fail)
+ (error "No breakpoint in %s at %s"
+ camldebug-delete-file
+ camldebug-delete-position)
+ (camldebug-call "delete" nil
+ (caml-string-to-int camldebug-delete-output)))))))))
+
+(defun camldebug-complete-filter (string)
+ (setq camldebug-filter-accumulator
+ (concat camldebug-filter-accumulator string))
+ (while (string-match "\\(\n\\|\\`\\)\\(.+\\)\n"
+ camldebug-filter-accumulator)
+ (setq camldebug-complete-list
+ (cons (match-string 2 camldebug-filter-accumulator)
+ camldebug-complete-list))
+ (setq camldebug-filter-accumulator
+ (substring camldebug-filter-accumulator
+ (1- (match-end 0)))))
+ (if (not (string-match comint-prompt-regexp
+ camldebug-filter-accumulator)) nil
+ (setq camldebug-complete-list
+ (or camldebug-complete-list 'fail))
+ (setq camldebug-filter-accumulator ""))
+ (if (string-match "\n\\(.*\\)\\'" camldebug-filter-accumulator)
+ (setq camldebug-filter-accumulator
+ (match-string 1 camldebug-filter-accumulator)))
+ "")
+
+(defun camldebug-complete ()
+
+ "Perform completion on the camldebug command preceding point."
+
+ (interactive)
+ (let* ((end (point))
+ (command (save-excursion
+ (beginning-of-line)
+ (and (looking-at comint-prompt-regexp)
+ (goto-char (match-end 0)))
+ (buffer-substring (point) end)))
+ (camldebug-complete-list nil) (command-word))
+
+ ;; Find the word break. This match will always succeed.
+ (string-match "\\(\\`\\| \\)\\([^ ]*\\)\\'" command)
+ (setq command-word (match-string 2 command))
+
+ ;itz 04-21-96 if we are trying to complete a word of nonzero
+ ;length, chop off the last character. This is a nasty hack, but it
+ ;works - in general, not just for this set of words: the comint
+ ;call below will weed out false matches - and it avoids further
+ ;mucking with camldebug's lexer.
+ (if (> (length command-word) 0)
+ (setq command (substring command 0 (1- (length command)))))
+
+ (let ((camldebug-filter-function 'camldebug-complete-filter))
+ (camldebug-call-1 (concat "complete " command))
+ (set-marker camldebug-delete-prompt-marker nil)
+ (while (not (and camldebug-complete-list
+ (zerop (length camldebug-filter-accumulator))))
+ (accept-process-output (get-buffer-process
+ (current-buffer)))))
+ (if (eq camldebug-complete-list 'fail)
+ (setq camldebug-complete-list nil))
+ (setq camldebug-complete-list
+ (sort camldebug-complete-list 'string-lessp))
+ (comint-dynamic-simple-complete command-word camldebug-complete-list)))
+
+(define-key camldebug-mode-map "\C-l" 'camldebug-refresh)
+(define-key camldebug-mode-map "\t" 'comint-dynamic-complete)
+(define-key camldebug-mode-map "\M-?" 'comint-dynamic-list-completions)
+
+(define-key caml-mode-map "\C-x " 'camldebug-break)
+
+
+(defvar current-camldebug-buffer nil)
+
+
+;;;###autoload
+(defvar camldebug-command-name "ocamldebug"
+ "*Pathname for executing camldebug.")
+
+;;;###autoload
+(defun camldebug (path)
+ "Run camldebug on program FILE in buffer *camldebug-FILE*.
+The directory containing FILE becomes the initial working directory
+and source-file directory for camldebug. If you wish to change this, use
+the camldebug commands `cd DIR' and `directory'."
+ (interactive "fRun ocamldebug on file: ")
+ (setq path (expand-file-name path))
+ (let ((file (file-name-nondirectory path)))
+ (pop-to-buffer (concat "*camldebug-" file "*"))
+ (setq default-directory (file-name-directory path))
+ (message "Current directory is %s" default-directory)
+ (make-comint (concat "camldebug-" file)
+ (substitute-in-file-name camldebug-command-name)
+ nil
+ "-emacs" "-cd" default-directory file)
+ (set-process-filter (get-buffer-process (current-buffer))
+ 'camldebug-filter)
+ (set-process-sentinel (get-buffer-process (current-buffer))
+ 'camldebug-sentinel)
+ (camldebug-mode)
+ (camldebug-set-buffer)))
+
+(defun camldebug-set-buffer ()
+ (if (eq major-mode 'camldebug-mode)
+ (setq current-camldebug-buffer (current-buffer))
+ (save-selected-window (pop-to-buffer current-camldebug-buffer))))
+
+;;; Filter and sentinel.
+
+(defun camldebug-marker-filter (string)
+ (setq camldebug-filter-accumulator
+ (concat camldebug-filter-accumulator string))
+ (let ((output "") (begin))
+ ;; Process all the complete markers in this chunk.
+ (while (setq begin
+ (string-match
+ "\032\032\\(H\\|M\\(.+\\):\\(.+\\):\\(.+\\):\\(before\\|after\\)\\)\n"
+ camldebug-filter-accumulator))
+ (setq camldebug-last-frame
+ (if (char-equal ?H (aref camldebug-filter-accumulator
+ (1+ (1+ begin)))) nil
+ (let ((isbefore
+ (string= "before"
+ (match-string 5 camldebug-filter-accumulator)))
+ (startpos (caml-string-to-int
+ (match-string 3 camldebug-filter-accumulator)))
+ (endpos (caml-string-to-int
+ (match-string 4 camldebug-filter-accumulator))))
+ (list (match-string 2 camldebug-filter-accumulator)
+ (if isbefore startpos endpos)
+ isbefore
+ startpos
+ endpos
+ )))
+ output (concat output
+ (substring camldebug-filter-accumulator
+ 0 begin))
+ ;; Set the accumulator to the remaining text.
+ camldebug-filter-accumulator (substring
+ camldebug-filter-accumulator
+ (match-end 0))
+ camldebug-last-frame-displayed-p nil))
+
+
+ ;; Does the remaining text look like it might end with the
+ ;; beginning of another marker? If it does, then keep it in
+ ;; camldebug-filter-accumulator until we receive the rest of it. Since we
+ ;; know the full marker regexp above failed, it's pretty simple to
+ ;; test for marker starts.
+ (if (string-match "\032.*\\'" camldebug-filter-accumulator)
+ (progn
+ ;; Everything before the potential marker start can be output.
+ (setq output (concat output (substring camldebug-filter-accumulator
+ 0 (match-beginning 0))))
+
+ ;; Everything after, we save, to combine with later input.
+ (setq camldebug-filter-accumulator
+ (substring camldebug-filter-accumulator (match-beginning 0))))
+
+ (setq output (concat output camldebug-filter-accumulator)
+ camldebug-filter-accumulator ""))
+
+ output))
+
+(defun camldebug-filter (proc string)
+ (let ((output))
+ (if (buffer-name (process-buffer proc))
+ (let ((process-window))
+ ;; it does not seem necessary to save excursion here,
+ ;; since set-buffer as a temporary effect.
+ ;; comint-output-filter explicitly avoids it.
+ ;; in version 23, it prevents the marker to stay at end of buffer
+ ;; (save-excursion
+ (set-buffer (process-buffer proc))
+ ;; If we have been so requested, delete the debugger prompt.
+ (if (marker-buffer camldebug-delete-prompt-marker)
+ (progn
+ (delete-region (process-mark proc)
+ camldebug-delete-prompt-marker)
+ (set-marker camldebug-delete-prompt-marker nil)))
+ (setq output (funcall camldebug-filter-function string))
+ ;; Don't display the specified file unless
+ ;; (1) point is at or after the position where output appears
+ ;; and (2) this buffer is on the screen.
+ (setq process-window (and camldebug-track-frame
+ (not camldebug-last-frame-displayed-p)
+ (>= (point) (process-mark proc))
+ (get-buffer-window (current-buffer))))
+ ;; Insert the text, moving the process-marker.
+ (comint-output-filter proc output)
+ ;; )
+ ;; this was the end of save-excursion.
+ ;; if save-excursion is used (comint-next-prompt 1) would be needed
+ ;; to move the mark past then next prompt, but this is not as good
+ ;; as solution.
+ (if process-window
+ (save-selected-window
+ (select-window process-window)
+ (camldebug-display-frame)))))))
+
+(defun camldebug-sentinel (proc msg)
+ (cond ((null (buffer-name (process-buffer proc)))
+ ;; buffer killed
+ ;; Stop displaying an arrow in a source file.
+ (camldebug-remove-current-event)
+ (set-process-buffer proc nil))
+ ((memq (process-status proc) '(signal exit))
+ ;; Stop displaying an arrow in a source file.
+ (camldebug-remove-current-event)
+ ;; Fix the mode line.
+ (setq mode-line-process
+ (concat ": "
+ (symbol-name (process-status proc))))
+ (let* ((obuf (current-buffer)))
+ ;; save-excursion isn't the right thing if
+ ;; process-buffer is current-buffer
+ (unwind-protect
+ (progn
+ ;; Write something in *compilation* and hack its mode line,
+ (set-buffer (process-buffer proc))
+ ;; Force mode line redisplay soon
+ (set-buffer-modified-p (buffer-modified-p))
+ (if (eobp)
+ (insert ?\n mode-name " " msg)
+ (save-excursion
+ (goto-char (point-max))
+ (insert ?\n mode-name " " msg)))
+ ;; If buffer and mode line will show that the process
+ ;; is dead, we can delete it now. Otherwise it
+ ;; will stay around until M-x list-processes.
+ (delete-process proc))
+ ;; Restore old buffer, but don't restore old point
+ ;; if obuf is the cdb buffer.
+ (set-buffer obuf))))))
+
+
+(defun camldebug-refresh (&optional arg)
+ "Fix up a possibly garbled display, and redraw the mark."
+ (interactive "P")
+ (camldebug-display-frame)
+ (recenter arg))
+
+(defun camldebug-display-frame ()
+ "Find, obey and delete the last filename-and-line marker from CDB.
+The marker looks like \\032\\032Mfilename:startchar:endchar:beforeflag\\n.
+Obeying it means displaying in another window the specified file and line."
+ (interactive)
+ (camldebug-set-buffer)
+ (if (not camldebug-last-frame)
+ (camldebug-remove-current-event)
+ (camldebug-display-line (nth 0 camldebug-last-frame)
+ (nth 3 camldebug-last-frame)
+ (nth 4 camldebug-last-frame)
+ (nth 2 camldebug-last-frame)))
+ (setq camldebug-last-frame-displayed-p t))
+
+;; Make sure the file named TRUE-FILE is in a buffer that appears on the screen
+;; and that its character CHARACTER is visible.
+;; Put the mark on this character in that buffer.
+
+(defun camldebug-display-line (true-file schar echar kind)
+ (let* ((pre-display-buffer-function nil) ; screw it, put it all in one screen
+ (pop-up-windows t)
+ (buffer (find-file-noselect true-file))
+ (window (display-buffer buffer t))
+ (spos) (epos) (pos))
+ (save-excursion
+ (set-buffer buffer)
+ (save-restriction
+ (widen)
+ (setq spos (+ (point-min) schar))
+ (setq epos (+ (point-min) echar))
+ (setq pos (if kind spos epos))
+ (camldebug-set-current-event spos epos (current-buffer) kind))
+ (cond ((or (< pos (point-min)) (> pos (point-max)))
+ (widen)
+ (goto-char pos))))
+ (set-window-point window pos)))
+
+;;; Events.
+
+(defun camldebug-remove-current-event ()
+ (if window-system
+ (progn
+ (delete-overlay camldebug-overlay-event)
+ (delete-overlay camldebug-overlay-under))
+ (setq overlay-arrow-position nil)))
+
+(defun camldebug-set-current-event (spos epos buffer before)
+ (if window-system
+ (if before
+ (progn
+ (move-overlay camldebug-overlay-event spos (1+ spos) buffer)
+ (move-overlay camldebug-overlay-under
+ (+ spos 1) epos buffer))
+ (move-overlay camldebug-overlay-event (1- epos) epos buffer)
+ (move-overlay camldebug-overlay-under spos (- epos 1) buffer))
+ (save-excursion
+ (set-buffer buffer)
+ (goto-char spos)
+ (beginning-of-line)
+ (move-marker camldebug-event-marker (point))
+ (setq overlay-arrow-position camldebug-event-marker))))
+
+;;; Miscellaneous.
+
+(defun camldebug-module-name (filename)
+ (substring filename (string-match "\\([^/]*\\)\\.ml$" filename)
+ (match-end 1)))
+
+;;; The camldebug-call function must do the right thing whether its
+;;; invoking keystroke is from the camldebug buffer itself (via
+;;; major-mode binding) or a caml buffer. In the former case, we want
+;;; to supply data from camldebug-last-frame. Here's how we do it:
+
+(defun camldebug-format-command (str)
+ (let* ((insource (not (eq (current-buffer) current-camldebug-buffer)))
+ (frame (if insource nil camldebug-last-frame)) (result))
+ (while (and str (string-match "\\([^%]*\\)%\\([mdcep]\\)" str))
+ (let ((key (string-to-char (substring str (match-beginning 2))))
+ (cmd (substring str (match-beginning 1) (match-end 1)))
+ (subst))
+ (setq str (substring str (match-end 2)))
+ (cond
+ ((eq key ?m)
+ (setq subst (camldebug-module-name
+ (if insource (buffer-file-name) (nth 0 frame)))))
+ ((eq key ?d)
+ (setq subst (file-name-directory
+ (if insource (buffer-file-name) (nth 0 frame)))))
+ ((eq key ?c)
+ (setq subst (int-to-string
+ (if insource (1- (point)) (nth 1 frame)))))
+ ((eq key ?e)
+ (setq subst (thing-at-point 'symbol))))
+ (setq result (concat result cmd subst))))
+ ;; There might be text left in STR when the loop ends.
+ (concat result str)))
+
+(defun camldebug-call (command &optional fmt arg)
+ "Invoke camldebug COMMAND displaying source in other window.
+
+Certain %-escapes in FMT are interpreted specially if present.
+These are:
+
+ %m module name of current module.
+ %d directory of current source file.
+ %c number of current character position
+ %e text of the caml variable surrounding point.
+
+ The `current' source file is the file of the current buffer (if
+we're in a caml buffer) or the source file current at the last break
+or step (if we're in the camldebug buffer), and the `current' module
+name is the filename stripped of any *.ml* suffixes (this assumes the
+usual correspondence between module and file naming is observed). The
+`current' position is that of the current buffer (if we're in a source
+file) or the position of the last break or step (if we're in the
+camldebug buffer).
+
+If ARG is present, it overrides any FMT flags and its string
+representation is simply concatenated with the COMMAND."
+
+ ;; Make sure debugger buffer is displayed in a window.
+ (camldebug-set-buffer)
+ (message "Command: %s" (camldebug-call-1 command fmt arg)))
+
+(defun camldebug-call-1 (command &optional fmt arg)
+
+ ;; Record info on the last prompt in the buffer and its position.
+ (save-excursion
+ (set-buffer current-camldebug-buffer)
+ (goto-char (process-mark (get-buffer-process current-camldebug-buffer)))
+ (let ((pt (point)))
+ (beginning-of-line)
+ (if (looking-at comint-prompt-regexp)
+ (set-marker camldebug-delete-prompt-marker (point)))))
+ (let ((cmd (cond
+ (arg (concat command " " (int-to-string arg)))
+ (fmt (camldebug-format-command
+ (concat command " " fmt)))
+ (command))))
+ (process-send-string (get-buffer-process current-camldebug-buffer)
+ (concat cmd "\n"))
+ cmd))
+
+
+(provide 'camldebug)
diff --git a/emacs/inf-caml.el b/emacs/inf-caml.el
new file mode 100644
index 0000000000..8a7757729a
--- /dev/null
+++ b/emacs/inf-caml.el
@@ -0,0 +1,362 @@
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Xavier Leroy and Jacques Garrigue *)
+;(* *)
+;(* Copyright 1997 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;;; inf-caml.el --- run the OCaml toplevel in an Emacs buffer
+
+;; Xavier Leroy, july 1993.
+
+;; modified by Jacques Garrigue, july 1997.
+
+(require 'comint)
+(require 'caml)
+
+;; User modifiable variables
+
+;; Whether you want the output buffer to be diplayed when you send a phrase
+
+(defvar caml-display-when-eval t
+ "*If true, display the inferior caml buffer when evaluating expressions.")
+
+
+;; End of User modifiable variables
+
+
+(defvar inferior-caml-mode-map nil)
+(if inferior-caml-mode-map nil
+ (setq inferior-caml-mode-map
+ (copy-keymap comint-mode-map)))
+
+;; Augment Caml mode, so you can process OCaml code in the source files.
+
+(defvar inferior-caml-program "ocaml"
+ "*Program name for invoking an inferior OCaml from Emacs.")
+
+(defun inferior-caml-mode ()
+ "Major mode for interacting with an inferior OCaml process.
+Runs an OCaml toplevel as a subprocess of Emacs, with I/O through an
+Emacs buffer. A history of input phrases is maintained. Phrases can
+be sent from another buffer in Caml mode.
+
+\\{inferior-caml-mode-map}"
+ (interactive)
+ (comint-mode)
+ (setq comint-prompt-regexp "^# ?")
+ (setq major-mode 'inferior-caml-mode)
+ (setq mode-name "Inferior Caml")
+ (make-local-variable 'paragraph-start)
+ (setq paragraph-start (concat "^$\\|" page-delimiter))
+ (make-local-variable 'paragraph-separate)
+ (setq paragraph-separate paragraph-start)
+ (make-local-variable 'paragraph-ignore-fill-prefix)
+ (setq paragraph-ignore-fill-prefix t)
+ (make-local-variable 'require-final-newline)
+ (setq require-final-newline t)
+ (make-local-variable 'comment-start)
+ (setq comment-start "(*")
+ (make-local-variable 'comment-end)
+ (setq comment-end "*)")
+ (make-local-variable 'comment-column)
+ (setq comment-column 40)
+ (make-local-variable 'comment-start-skip)
+ (setq comment-start-skip "(\\*+ *")
+ (make-local-variable 'parse-sexp-ignore-comments)
+ (setq parse-sexp-ignore-comments nil)
+ (use-local-map inferior-caml-mode-map)
+ (run-hooks 'inferior-caml-mode-hooks))
+
+
+(defconst inferior-caml-buffer-subname "inferior-caml")
+(defconst inferior-caml-buffer-name
+ (concat "*" inferior-caml-buffer-subname "*"))
+
+;; for compatibility with xemacs
+
+(defun caml-sit-for (second &optional mili redisplay)
+ (if (and (boundp 'running-xemacs) running-xemacs)
+ (sit-for (if mili (+ second (* mili 0.001)) second) redisplay)
+ (sit-for second mili redisplay)))
+
+;; To show result of evaluation at toplevel
+
+(defvar inferior-caml-output nil)
+(defun inferior-caml-signal-output (s)
+ (if (string-match "[^ ]" s) (setq inferior-caml-output t)))
+
+(defun inferior-caml-mode-output-hook ()
+ (set-variable 'comint-output-filter-functions
+ (list (function inferior-caml-signal-output))
+ t))
+(add-hook 'inferior-caml-mode-hooks 'inferior-caml-mode-output-hook)
+
+;; To launch ocaml whenever needed
+
+(defun caml-run-process-if-needed (&optional cmd)
+ (if (comint-check-proc inferior-caml-buffer-name) nil
+ (if (not cmd)
+ (if (comint-check-proc inferior-caml-buffer-name)
+ (setq cmd inferior-caml-program)
+ (setq cmd (read-from-minibuffer "OCaml toplevel to run: "
+ inferior-caml-program))))
+ (setq inferior-caml-program cmd)
+ (let ((cmdlist (inferior-caml-args-to-list cmd))
+ (process-connection-type nil))
+ (set-buffer (apply (function make-comint)
+ inferior-caml-buffer-subname
+ (car cmdlist) nil (cdr cmdlist)))
+ (inferior-caml-mode)
+ (display-buffer inferior-caml-buffer-name)
+ t)
+ (setq caml-shell-active t)
+ ))
+
+;; patched to from original run-caml sharing code with
+;; caml-run-process-when-needed
+
+(defun run-caml (&optional cmd)
+ "Run an inferior OCaml process.
+Input and output via buffer `*inferior-caml*'."
+ (interactive
+ (list (if (not (comint-check-proc inferior-caml-buffer-name))
+ (read-from-minibuffer "OCaml toplevel to run: "
+ inferior-caml-program))))
+ (caml-run-process-if-needed cmd)
+ (switch-to-buffer-other-window inferior-caml-buffer-name))
+
+
+(defun inferior-caml-args-to-list (string)
+ (let ((where (string-match "[ \t]" string)))
+ (cond ((null where) (list string))
+ ((not (= where 0))
+ (cons (substring string 0 where)
+ (inferior-caml-args-to-list (substring string (+ 1 where)
+ (length string)))))
+ (t (let ((pos (string-match "[^ \t]" string)))
+ (if (null pos)
+ nil
+ (inferior-caml-args-to-list (substring string pos
+ (length string)))))))))
+
+(defun inferior-caml-show-subshell ()
+ (interactive)
+ (caml-run-process-if-needed)
+ (display-buffer inferior-caml-buffer-name)
+ ; Added by Didier to move the point of inferior-caml to end of buffer
+ (let ((buf (current-buffer))
+ (caml-buf (get-buffer inferior-caml-buffer-name))
+ (count 0))
+ (while
+ (and (< count 10)
+ (not (equal (buffer-name (current-buffer))
+ inferior-caml-buffer-name)))
+ (next-multiframe-window)
+ (setq count (+ count 1)))
+ (if (equal (buffer-name (current-buffer))
+ inferior-caml-buffer-name)
+ (goto-char (point-max)))
+ (while
+ (> count 0)
+ (previous-multiframe-window)
+ (setq count (- count 1)))
+ )
+)
+
+;; patched by Didier to move cursor after evaluation
+
+(defun inferior-caml-eval-region (start end)
+ "Send the current region to the inferior OCaml process."
+ (interactive "r")
+ (save-excursion (caml-run-process-if-needed))
+ (save-excursion
+ (goto-char end)
+ (caml-skip-comments-backward)
+ (comint-send-region inferior-caml-buffer-name start (point))
+ ;; normally, ";;" are part of the region
+ (if (and (>= (point) 2)
+ (prog2 (backward-char 2) (looking-at ";;")))
+ (comint-send-string inferior-caml-buffer-name "\n")
+ (comint-send-string inferior-caml-buffer-name ";;\n"))
+ ;; the user may not want to see the output buffer
+ (if caml-display-when-eval
+ (display-buffer inferior-caml-buffer-name t))))
+
+;; jump to errors produced by ocaml compiler
+
+(defun inferior-caml-goto-error (start end)
+ "Jump to the location of the last error as indicated by inferior toplevel."
+ (interactive "r")
+ (let ((loc (+ start
+ (save-excursion
+ (set-buffer (get-buffer inferior-caml-buffer-name))
+ (re-search-backward
+ (concat comint-prompt-regexp
+ "[ \t]*Characters[ \t]+\\([0-9]+\\)-[0-9]+:$"))
+ (caml-string-to-int (match-string 1))))))
+ (goto-char loc)))
+
+
+;;; orgininal inf-caml.el ended here
+
+;; as eval-phrase, but ignores errors.
+
+(defun inferior-caml-just-eval-phrase (arg &optional min max)
+ "Send the phrase containing the point to the CAML process.
+With prefix-arg send as many phrases as its numeric value,
+ignoring possible errors during evaluation.
+
+Optional arguments min max defines a region within which the phrase
+should lies."
+ (interactive "p")
+ (let ((beg))
+ (while (> arg 0)
+ (setq arg (- arg 1))
+ (setq beg (caml-find-phrase min max))
+ (caml-eval-region beg (point)))
+ beg))
+
+(defvar caml-previous-output nil
+ "tells the beginning of output in the shell-output buffer, so that the
+output can be retreived later, asynchronously.")
+
+;; enriched version of eval-phrase, to repport errors.
+
+(defun inferior-caml-eval-phrase (arg &optional min max)
+ "Send the phrase containing the point to the CAML process.
+With prefix-arg send as many phrases as its numeric value,
+If an error occurs during evalutaion, stop at this phrase and
+repport the error.
+
+Return nil if noerror and position of error if any.
+
+If arg's numeric value is zero or negative, evaluate the current phrase
+or as many as prefix arg, ignoring evaluation errors.
+This allows to jump other erroneous phrases.
+
+Optional arguments min max defines a region within which the phrase
+should lies."
+ (interactive "p")
+ (if (save-excursion (caml-run-process-if-needed))
+ (progn
+ (setq inferior-caml-output nil)
+ (caml-wait-output 10 1)))
+ (if (< arg 1) (inferior-caml-just-eval-phrase (max 1 (- 0 arg)) min max)
+ (let ((proc (get-buffer-process inferior-caml-buffer-name))
+ (buf (current-buffer))
+ previous-output orig beg end err)
+ (save-window-excursion
+ (while (and (> arg 0) (not err))
+ (setq previous-output (marker-position (process-mark proc)))
+ (setq caml-previous-output previous-output)
+ (setq inferior-caml-output nil)
+ (setq orig (inferior-caml-just-eval-phrase 1 min max))
+ (caml-wait-output)
+ (switch-to-buffer inferior-caml-buffer-name nil)
+ (goto-char previous-output)
+ (cond ((re-search-forward
+ " *Characters \\([01-9][01-9]*\\)-\\([1-9][01-9]*\\):\n[^W]"
+ (point-max) t)
+ (setq beg (caml-string-to-int (caml-match-string 1)))
+ (setq end (caml-string-to-int (caml-match-string 2)))
+ (switch-to-buffer buf)
+ (goto-char orig)
+ (forward-byte end)
+ (setq end (point))
+ (goto-char orig)
+ (forward-byte beg)
+ (setq beg (point))
+ (setq err beg)
+ )
+ ((looking-at
+ "Toplevel input:\n[>]\\([^\n]*\\)\n[>]\\(\\( *\\)^*\\)\n")
+ (let ((expr (caml-match-string 1))
+ (column (- (match-end 3) (match-beginning 3)))
+ (width (- (match-end 2) (match-end 3))))
+ (if (string-match "^\\(.*\\)[<]EOF[>]$" expr)
+ (setq expr (substring expr (match-beginning 1)
+ (match-end 1))))
+ (switch-to-buffer buf)
+ (re-search-backward
+ (concat "^" (regexp-quote expr) "$")
+ (- orig 10))
+ (goto-char (+ (match-beginning 0) column))
+ (setq end (+ (point) width)))
+ (setq err beg))
+ ((looking-at
+ "Toplevel input:\n>[.]*\\([^.].*\n\\)\\([>].*\n\\)*[>]\\(.*[^.]\\)[.]*\n")
+ (let* ((e1 (caml-match-string 1))
+ (e2 (caml-match-string 3))
+ (expr
+ (concat
+ (regexp-quote e1) "\\(.*\n\\)*" (regexp-quote e2))))
+ (switch-to-buffer buf)
+ (re-search-backward expr orig 'move)
+ (setq end (match-end 0)))
+ (setq err beg))
+ (t
+ (switch-to-buffer buf)))
+ (setq arg (- arg 1))
+ )
+ (pop-to-buffer inferior-caml-buffer-name)
+ (if err
+ (goto-char (point-max))
+ (goto-char previous-output)
+ (goto-char (point-max)))
+ (pop-to-buffer buf))
+ (if err (progn (beep) (caml-overlay-region (point) end))
+ (if inferior-caml-output
+ (message "No error")
+ (message "No output yet...")
+ ))
+ err)))
+
+(defun caml-overlay-region (beg end &optional wait)
+ (interactive "%r")
+ (cond ((fboundp 'make-overlay)
+ (if caml-error-overlay ()
+ (setq caml-error-overlay (make-overlay 1 1))
+ (overlay-put caml-error-overlay 'face 'region))
+ (unwind-protect
+ (progn
+ (move-overlay caml-error-overlay beg end (current-buffer))
+ (beep) (if wait (read-event) (caml-sit-for 60)))
+ (delete-overlay caml-error-overlay)))))
+
+;; wait some amount for output, that is, until inferior-caml-output is set
+;; to true. Hence, interleaves sitting for shorts delays and checking the
+;; flag. Give up after some time. Typing into the source buffer will cancel
+;; waiting, i.e. may report 'No result yet'
+
+(defun caml-wait-output (&optional before after)
+ (let ((c 1))
+ (caml-sit-for 0 (or before 1))
+ (let ((c 1))
+ (while (and (not inferior-caml-output) (< c 99) (caml-sit-for 0 c t))
+ (setq c (+ c 1))))
+ (caml-sit-for (or after 0) 1)))
+
+;; To insert the last output from caml at point
+(defun caml-insert-last-output ()
+ "Insert the result of the evaluation of previous phrase"
+ (interactive)
+ (let ((pos (process-mark (get-buffer-process inferior-caml-buffer-name))))
+ (insert-buffer-substring inferior-caml-buffer-name
+ caml-previous-output (- pos 2))))
+
+;; additional bindings
+
+;(let ((map (lookup-key caml-mode-map [menu-bar caml])))
+; (define-key map [indent-buffer] '("Indent buffer" . caml-indent-buffer))
+; (define-key map [eval-buffer] '("Eval buffer" . caml-eval-buffer))
+;)
+;(define-key caml-mode-map "\C-c\C-b" 'caml-eval-buffer)
+
+
+(provide 'inf-caml)
diff --git a/emacs/ocamltags.in b/emacs/ocamltags.in
new file mode 100644
index 0000000000..7b1f41cf0c
--- /dev/null
+++ b/emacs/ocamltags.in
@@ -0,0 +1,139 @@
+":" ; @EMACS@ -batch -l $0 "$@" ; status=$? ; : '--*-Emacs-Lisp-*--' <<';'
+
+;(***********************************************************************)
+;(* *)
+;(* OCaml *)
+;(* *)
+;(* Jacques Garrigue and Ian T Zimmerman *)
+;(* *)
+;(* Copyright 1998 Institut National de Recherche en Informatique et *)
+;(* en Automatique. All rights reserved. This file is distributed *)
+;(* under the terms of the GNU General Public License. *)
+;(* *)
+;(***********************************************************************)
+
+;; Copyright (C) 1998 Ian Zimmerman <itz@transbay.net>
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2 of the
+;; License, or (at your option) any later version.
+
+;; This program is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+;; General Public License for more details.
+
+(require 'caml)
+
+;;itz Fri Oct 30 13:08:37 PST 1998 support for creating TAGS files
+;; itz Sun Dec 27 10:26:08 PST 1998 adapted very slightly from
+;; Jacques' caml-create-index-function
+(defun caml-tags-create-index-function ()
+ (let (all-alist index)
+ (goto-char (point-max))
+ ;; collect definitions
+ (while (caml-prev-index-position-function)
+ (if (looking-at "[ \t]*val") nil
+ (setq index (cons (caml-match-string 5) (point)))
+ (setq all-alist (cons index all-alist))))
+ all-alist))
+
+(defun caml-tags-file (filename)
+ (let* ((output-buffer (current-buffer))
+ (basename (file-name-nondirectory filename))
+ (backpatch (prog2
+ (insert " \n" basename)
+ (point))))
+ (find-file-read-only filename)
+ (caml-mode)
+ (let ((all-alist (caml-tags-create-index-function))
+ (done nil)
+ (current-line 1)
+ (last-point (point-min)))
+ (mapcar
+ (lambda (pair)
+ (let ((tag-name (car pair)) (tag-pos (cdr pair)))
+ (goto-char tag-pos)
+ (setq current-line
+ (+ current-line (count-lines last-point (point))))
+ (setq last-point (point))
+ (end-of-line 1)
+ (let ((output-line (format "%s%s%d,%d\n"
+ (buffer-substring last-point (point))
+ tag-name current-line tag-pos)))
+ (save-excursion
+ (set-buffer output-buffer)
+ (insert output-line)))))
+ all-alist))
+ (kill-buffer (current-buffer))
+ (set-buffer output-buffer)
+ (let ((index-size (- (point) backpatch)))
+ (goto-char backpatch)
+ (insert "," (int-to-string index-size) "\n")
+ (goto-char (point-max)))))
+
+(defsubst prefix-p (prefix str)
+ (and (<= (length prefix) (length str))
+ (string= prefix (substring str 0 (length prefix)))))
+
+(defsubst eat-args (n)
+ (setq command-line-args-left (nthcdr n command-line-args-left)))
+
+;; see Emacs source file print.c
+(defun print-error-message (data)
+ (let ((errname (car data)) errmsg is-file-error tail i)
+ (if (eq errname 'error)
+ (progn
+ (setq data (cdr data))
+ (if (not (consp data)) (setq data nil))
+ (setq errmsg (car data))
+ (setq is-file-error nil))
+ (setq errmsg (get errname 'error-message))
+ (setq is-file-error (memq 'file-error (get errname 'error-conditions))))
+ (setq tail (cdr-safe data))
+ (if (and is-file-error tail)
+ (setq errmsg (car tail) tail (cdr tail)))
+ (if (stringp errmsg) (princ errmsg)
+ (princ "peculiar error"))
+ (setq i 0)
+ (while (consp tail)
+ (princ (if (eq i 0) ": " ", "))
+ (if is-file-error (princ (car tail))
+ (prin1 (car tail)))
+ (setq tail (cdr tail) i (1+ i)))
+ (princ "\n")))
+
+
+(setq gc-cons-threshold 1000000)
+
+(setq output-file "TAGS")
+(setq append-flag nil)
+(setq status 0)
+
+(condition-case foobar
+ (progn
+ (while (and command-line-args-left
+ (let ((arg (car command-line-args-left)))
+ (cond
+ ((prefix-p arg "-output-file")
+ (setq output-file (nth 1 command-line-args-left))
+ (eat-args 2) t)
+ ((prefix-p arg "-append")
+ (setq append-flag t)
+ (eat-args 1) t)
+ (t nil)))))
+
+ (find-file output-file)
+ (if append-flag (goto-char (point-max))
+ (erase-buffer))
+ (while command-line-args-left
+ (caml-tags-file (car command-line-args-left))
+ (setq command-line-args-left (cdr command-line-args-left)))
+ (save-buffer 0))
+ (error (setq status 1) (print-error-message foobar)))
+
+(kill-emacs status)
+
+;
+
+":" ; exit $status
diff --git a/experimental/doligez/check-bounds.diff b/experimental/doligez/check-bounds.diff
new file mode 100644
index 0000000000..c2e0795212
--- /dev/null
+++ b/experimental/doligez/check-bounds.diff
@@ -0,0 +1,149 @@
+Patch taken from:
+ https://github.com/mshinwell/ocaml/commits/4.02-block-bounds
+
+diff --git a/asmcomp/cmmgen.ml b/asmcomp/cmmgen.ml
+index 01eff9c..b498b58 100644
+--- a/asmcomp/cmmgen.ml
++++ b/asmcomp/cmmgen.ml
+@@ -22,6 +22,13 @@ open Clambda
+ open Cmm
+ open Cmx_format
+
++let do_check_field_access = true
++(*
++ match try Some (Sys.getenv "BOUNDS") with Not_found -> None with
++ | None | Some "" -> false
++ | Some _ -> true
++*)
++
+ (* Local binding of complex expressions *)
+
+ let bind name arg fn =
+@@ -494,6 +501,35 @@ let get_tag ptr =
+ let get_size ptr =
+ Cop(Clsr, [header ptr; Cconst_int 10])
+
++(* Bounds checks upon field access, for debugging the compiler *)
++
++let check_field_access ptr field_index if_success =
++ if not do_check_field_access then
++ if_success
++ else
++ let field_index = Cconst_int field_index in
++ (* If [ptr] points at an infix header, we need to move it back to the "main"
++ [Closure_tag] header. *)
++ let ptr =
++ Cifthenelse (Cop (Ccmpi Cne, [get_tag ptr; Cconst_int Obj.infix_tag]),
++ ptr,
++ Cop (Csuba, [ptr;
++ Cop (Cmuli, [get_size ptr (* == Infix_offset_val(ptr) *);
++ Cconst_int size_addr])]))
++ in
++ let not_too_small = Cop (Ccmpi Cge, [field_index; Cconst_int 0]) in
++ let not_too_big = Cop (Ccmpi Clt, [field_index; get_size ptr]) in
++ let failure =
++ Cop (Cextcall ("caml_field_access_out_of_bounds_error", typ_addr, false,
++ Debuginfo.none),
++ [ptr; field_index])
++ in
++ Cifthenelse (not_too_small,
++ Cifthenelse (not_too_big,
++ if_success,
++ failure),
++ failure)
++
+ (* Array indexing *)
+
+ let log2_size_addr = Misc.log2 size_addr
+@@ -1550,13 +1586,18 @@ and transl_prim_1 p arg dbg =
+ return_unit(remove_unit (transl arg))
+ (* Heap operations *)
+ | Pfield n ->
+- get_field (transl arg) n
++ let ptr = transl arg in
++ let body = get_field ptr n in
++ check_field_access ptr n body
+ | Pfloatfield n ->
+ let ptr = transl arg in
+- box_float(
+- Cop(Cload Double_u,
+- [if n = 0 then ptr
+- else Cop(Cadda, [ptr; Cconst_int(n * size_float)])]))
++ let body =
++ box_float(
++ Cop(Cload Double_u,
++ [if n = 0 then ptr
++ else Cop(Cadda, [ptr; Cconst_int(n * size_float)])]))
++ in
++ check_field_access ptr n body
+ | Pint_as_pointer ->
+ Cop(Cadda, [transl arg; Cconst_int (-1)])
+ (* Exceptions *)
+@@ -1649,20 +1690,25 @@ and transl_prim_1 p arg dbg =
+ and transl_prim_2 p arg1 arg2 dbg =
+ match p with
+ (* Heap operations *)
+- Psetfield(n, ptr) ->
+- if ptr then
+- return_unit(Cop(Cextcall("caml_modify", typ_void, false,Debuginfo.none),
+- [field_address (transl arg1) n; transl arg2]))
+- else
+- return_unit(set_field (transl arg1) n (transl arg2))
++ Psetfield(n, is_ptr) ->
++ let ptr = transl arg1 in
++ let body =
++ if is_ptr then
++ Cop(Cextcall("caml_modify", typ_void, false,Debuginfo.none),
++ [field_address ptr n; transl arg2])
++ else
++ set_field ptr n (transl arg2)
++ in
++ check_field_access ptr n (return_unit body)
+ | Psetfloatfield n ->
+ let ptr = transl arg1 in
+- return_unit(
++ let body =
+ Cop(Cstore Double_u,
+ [if n = 0 then ptr
+ else Cop(Cadda, [ptr; Cconst_int(n * size_float)]);
+- transl_unbox_float arg2]))
+-
++ transl_unbox_float arg2])
++ in
++ check_field_access ptr n (return_unit body)
+ (* Boolean operations *)
+ | Psequand ->
+ Cifthenelse(test_bool(transl arg1), transl arg2, Cconst_int 1)
+diff --git a/asmrun/fail.c b/asmrun/fail.c
+index cb2c1cb..4f67c74 100644
+--- a/asmrun/fail.c
++++ b/asmrun/fail.c
+@@ -15,6 +15,7 @@
+
+ #include <stdio.h>
+ #include <signal.h>
++#include <assert.h>
+ #include "alloc.h"
+ #include "fail.h"
+ #include "io.h"
+@@ -180,3 +181,20 @@ int caml_is_special_exception(value exn) {
+ || exn == (value) caml_exn_Assert_failure
+ || exn == (value) caml_exn_Undefined_recursive_module;
+ }
++
++void caml_field_access_out_of_bounds_error(value v_block, intnat index)
++{
++ assert(Is_block(v_block));
++ fprintf(stderr, "Fatal error: out-of-bounds access to field %ld ", index);
++ fprintf(stderr, "of block at %p (%s, size %ld, tag %d)\n",
++ (void*) v_block,
++ Is_young(v_block) ? "in minor heap"
++ : Is_in_heap(v_block) ? "in major heap"
++ : Is_in_value_area(v_block) ? "in static data"
++ : "out-of-heap",
++ (long) Wosize_val(v_block), (int) Tag_val(v_block));
++ fflush(stderr);
++ /* This error may have occurred in places where it is not reasonable to
++ attempt to continue. */
++ abort();
++}
diff --git a/experimental/doligez/checkheaders b/experimental/doligez/checkheaders
new file mode 100755
index 0000000000..5de153292c
--- /dev/null
+++ b/experimental/doligez/checkheaders
@@ -0,0 +1,152 @@
+#!/bin/sh
+
+#######################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2011 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#######################################################################
+
+(
+case $# in
+ 0) find . -type f -print;;
+ *) echo $1;;
+esac
+) | \
+while read f; do
+awk -f - "$f" <<\EOF
+
+function checkline (x) {
+ return ( $0 ~ ("^.{0,4}" x) );
+}
+
+function hrule () {
+ return (checkline("[*#]{69}"));
+}
+
+function blank () {
+ return (checkline(" {69}"));
+}
+
+function ocaml () {
+ return (checkline(" {32}OCaml {32}") \
+ || checkline(" {35}OCaml {32}") \
+ || checkline(" ocamlbuild ") \
+ || checkline(" OCamldoc ") \
+ );
+}
+
+function any () {
+ return (checkline(".{69}"));
+}
+
+function copy1 () {
+ return (checkline(" Copyright +[-0-9]+ +Institut +National +de +Recherche +en +Informatique +et "));
+}
+
+function copy2 () {
+ return (checkline(" en Automatique"));
+}
+
+function err () {
+ printf ("File \"%s\", line %d:\n", FILENAME, FNR);
+ printf (" Error: line %d of header is wrong.\n", FNR + offset);
+ print $0;
+}
+
+function add_ignore_re (x) {
+ ignore_re[++ignore_re_index] = x;
+}
+
+function add_exception (x) {
+ exception[++exception_index] = x;
+}
+
+FNR == 1 {
+ offset = 0;
+ add_ignore_re("/\\.svn/");
+ add_ignore_re("/\\.depend(\\.nt)?$");
+ add_ignore_re("/\\.ignore$");
+ add_ignore_re("\\.gif$");
+ add_ignore_re("/[A-Z]*$");
+ add_ignore_re("/README\\.[^/]*$");
+ add_ignore_re("/Changes$");
+ add_ignore_re("\\.mlpack$");
+ add_ignore_re("\\.mllib$");
+ add_ignore_re("\\.mltop$");
+ add_ignore_re("\\.clib$");
+ add_ignore_re("\\.odocl$");
+ add_ignore_re("\\.itarget$");
+ add_ignore_re("^\\./boot/");
+ add_ignore_re("^\\./camlp4/test/");
+ add_ignore_re("^\\./camlp4/unmaintained/");
+ add_ignore_re("^\\./config/gnu/");
+ add_ignore_re("^\\./experimental/");
+ add_ignore_re("^\\./ocamlbuild/examples/");
+ add_ignore_re("^\\./ocamlbuild/test/");
+ add_ignore_re("^\\./testsuite/");
+ for (i in ignore_re){
+ if (FILENAME ~ ignore_re[i]) { nextfile; }
+ }
+ add_exception("./asmrun/m68k.S"); # obsolete
+ add_exception("./build/camlp4-bootstrap-recipe.txt");
+ add_exception("./build/new-build-system");
+ add_exception("./ocamlbuild/ChangeLog");
+ add_exception("./ocamlbuild/manual/myocamlbuild.ml"); # TeX input file ?
+ add_exception("./ocamlbuild/manual/trace.out"); # TeX input file
+ add_exception("./ocamldoc/Changes.txt");
+ add_exception("./ocamldoc/ocamldoc.sty"); # public domain
+ add_exception("./tools/objinfo_helper.c"); # non-INRIA
+ add_exception("./tools/magic"); # public domain ?
+ add_exception("./Upgrading");
+ add_exception("./win32caml/inriares.h"); # generated
+ add_exception("./win32caml/ocaml.rc"); # generated
+ add_exception("./win32caml/resource.h"); # generated
+ for (i in exception){
+ if (FILENAME == exception[i]) { nextfile; }
+ }
+}
+
+# 1 [!hrule] #!
+# 2 [!hrule] empty
+# 3 hrule
+# 4 [blank]
+# 5 ocaml title
+# 6 blank
+# 7 any author
+# 8 [!blank] author
+# 9 [!blank] author
+#10 blank
+#11 copy1 copyright
+#12 copy2 copyright
+#13 any copyright
+#14 [!blank] copyright
+#15 [!blank] copyright
+#16 blank
+#17 hrule
+
+FNR + offset == 1 && hrule() { ++offset; }
+FNR + offset == 2 && hrule() { ++offset; }
+FNR + offset == 3 && ! hrule() { err(); nextfile; }
+FNR + offset == 4 && ! blank() { ++offset; }
+FNR + offset == 5 && ! ocaml() { err(); nextfile; }
+FNR + offset == 6 && ! blank() { err(); nextfile; }
+FNR + offset == 7 && ! any() { err(); nextfile; }
+FNR + offset == 8 && blank() { ++offset; }
+FNR + offset == 9 && blank() { ++offset; }
+FNR + offset ==10 && ! blank() { err(); nextfile; }
+FNR + offset ==11 && ! copy1() { err(); nextfile; }
+FNR + offset ==12 && ! copy2() { err(); nextfile; }
+FNR + offset ==13 && ! any() { err(); nextfile; }
+FNR + offset ==14 && blank() { ++offset; }
+FNR + offset ==15 && blank() { ++offset; }
+FNR + offset ==16 && ! blank() { err(); nextfile; }
+FNR + offset ==17 && ! hrule() { err(); nextfile; }
+
+EOF
+done
diff --git a/experimental/frisch/Makefile b/experimental/frisch/Makefile
new file mode 100644
index 0000000000..89de11f087
--- /dev/null
+++ b/experimental/frisch/Makefile
@@ -0,0 +1,79 @@
+ROOT=../..
+OCAMLC=$(ROOT)/boot/ocamlrun $(ROOT)/ocamlc -I $(ROOT)/stdlib -I $(ROOT)/parsing -I $(ROOT)/utils -I $(ROOT)/tools -I $(ROOT)/typing -I $(ROOT)/driver -I $(ROOT)/toplevel -w A-4-9-42
+COMMON=$(ROOT)/compilerlibs/ocamlcommon.cma
+BYTECMP=$(ROOT)/compilerlibs/ocamlbytecomp.cma
+TOPLVL=$(ROOT)/compilerlibs/ocamltoplevel.cma
+
+clean:
+ rm -f *.exe *.cm* *~
+
+## Detecting unused exported values
+
+.PHONY: unused_exported_values
+unused_exported_values:
+ $(OCAMLC) -o unused_exported_values.exe $(COMMON) $(ROOT)/tools/tast_iter.cmo unused_exported_values.ml
+
+
+## Conditional compilation based on environment variables
+
+.PHONY: ifdef
+ifdef:
+ $(OCAMLC) -o ifdef.exe $(COMMON) ifdef.ml
+ $(OCAMLC) -o test_ifdef.exe -ppx ./ifdef.exe -dsource test_ifdef.ml
+ ./test_ifdef.exe
+
+## A proposal for replacing js_of_ocaml Camlp4 syntax extension with
+## a -ppx filter
+
+.PHONY: js_syntax
+js_syntax:
+ $(OCAMLC) -o js_syntax.exe $(COMMON) js_syntax.ml
+ $(OCAMLC) -o test_ifdef.exe -i -ppx ./js_syntax.exe test_js.ml
+
+
+## A "toy" ocamldoc clone based on .cmti files
+
+.PHONY: minidoc
+minidoc:
+ $(OCAMLC) -custom -o minidoc.exe $(COMMON) minidoc.ml
+ $(OCAMLC) -c -bin-annot testdoc.mli
+ ./minidoc.exe testdoc.cmti
+
+## Using the OCaml toplevel to evaluate expression during compilation
+
+.PHONY: eval
+eval:
+ $(OCAMLC) -linkall -o eval.exe $(COMMON) $(BYTECMP) $(TOPLVL) eval.ml
+ $(OCAMLC) -o test_eval.exe -ppx ./eval.exe test_eval.ml
+ ./test_eval.exe
+
+## Example of code generation based on type declarations
+
+.PHONY: ppx_builder
+ppx_builder:
+ $(OCAMLC) -linkall -o ppx_builder.exe $(COMMON) ppx_builder.ml
+ $(OCAMLC) -o test_builder.exe -ppx ./ppx_builder.exe -dsource test_builder.ml
+
+## Import type definitions from other source files (e.g. to avoid code
+## duplication between the .ml and .mli files)
+
+.PHONY: copy_typedef
+copy_typedef:
+ $(OCAMLC) -linkall -o copy_typedef.exe $(COMMON) copy_typedef.ml
+ $(OCAMLC) -c -ppx ./copy_typedef.exe test_copy_typedef.mli
+ $(OCAMLC) -o test_copy_typedef.exe -ppx ./copy_typedef.exe -dsource test_copy_typedef.ml
+
+
+## Create mli files from ml files
+
+.PHONY: nomli
+nomli:
+ $(OCAMLC) -linkall -o nomli.exe $(COMMON) $(BYTECMP) ../../tools/untypeast.cmo ../../tools/tast_iter.cmo nomli.ml
+ ./nomli.exe test_nomli.ml
+
+## A port of pa_matches
+
+.PHONY: matches
+matches:
+ $(OCAMLC) -linkall -o ppx_matches.exe $(COMMON) ppx_matches.ml
+ $(OCAMLC) -c -dsource -ppx ./ppx_matches.exe test_matches.ml
diff --git a/experimental/frisch/copy_typedef.ml b/experimental/frisch/copy_typedef.ml
new file mode 100644
index 0000000000..baf52de4d8
--- /dev/null
+++ b/experimental/frisch/copy_typedef.ml
@@ -0,0 +1,181 @@
+(*
+ A -ppx rewriter to copy type definitions from the interface into
+ the implementation.
+
+ In an .ml file, you can write:
+
+ type t = [%copy_typedef]
+
+ and the concrete definition will be copied from the corresponding .mli
+ file (looking for the type name in the same path).
+
+ The same is available for module types:
+
+ module type S = [%copy_typedef]
+
+ You can also import a definition from an arbitrary .ml/.mli file.
+ Example:
+
+ type loc = [%copy_typedef "../../parsing/location.mli" t]
+
+ Note: the definitions are imported textually without any substitution.
+*)
+
+module Main : sig end = struct
+ open Asttypes
+ open! Location
+ open Parsetree
+
+ let fatal loc s =
+ Location.print_error Format.err_formatter loc;
+ prerr_endline ("** copy_typedef: " ^ Printexc.to_string s);
+ exit 2
+
+ class maintain_path = object(this)
+ inherit Ast_mapper.mapper as super
+
+ val path = []
+
+ method! module_binding m = {< path = m.pmb_name.txt :: path >} # super_module_binding m
+ method super_module_binding = super # module_binding
+
+ method! module_declaration m = {< path = m.pmd_name.txt :: path >} # super_module_declaration m
+ method super_module_declaration = super # module_declaration
+
+ method! module_type_declaration m = {< path = m.pmtd_name.txt :: path >} # super_module_type_declaration m
+ method super_module_type_declaration = super # module_type_declaration
+
+ method! structure_item s =
+ let s =
+ match s.pstr_desc with
+ | Pstr_type tdecls -> {s with pstr_desc=Pstr_type (List.map (this # tydecl) tdecls)}
+ | Pstr_modtype mtd -> {s with pstr_desc=Pstr_modtype (this # mtydecl mtd)}
+ | _ -> s
+ in
+ super # structure_item s
+
+ method! signature_item s =
+ let s =
+ match s.psig_desc with
+ | Psig_type tdecls -> {s with psig_desc=Psig_type (List.map (this # tydecl) tdecls)}
+ | Psig_modtype mtd -> {s with psig_desc=Psig_modtype (this # mtydecl mtd)}
+ | _ -> s
+ in
+ super # signature_item s
+
+ method tydecl x = x
+ method mtydecl x = x
+ end
+
+ let memoize f =
+ let h = Hashtbl.create 16 in
+ fun x ->
+ try Hashtbl.find h x
+ with Not_found ->
+ let r = f x in
+ Hashtbl.add h x r;
+ r
+
+ let from_file file =
+ let types = Hashtbl.create 16 in
+ let mtypes = Hashtbl.create 16 in
+ let collect = object
+ inherit maintain_path
+ method! tydecl x =
+ Hashtbl.add types (path, x.ptype_name.txt) x;
+ x
+ method! mtydecl x =
+ Hashtbl.add mtypes (path, x.pmtd_name.txt) x;
+ x
+ end
+ in
+ let ic = open_in file in
+ let lexbuf = Lexing.from_channel ic in
+ if Filename.check_suffix file ".ml"
+ then ignore (collect # structure (Parse.implementation lexbuf))
+ else if Filename.check_suffix file ".mli"
+ then ignore (collect # signature (Parse.interface lexbuf))
+ else failwith (Printf.sprintf "Unknown extension for %s" file);
+ close_in ic;
+ object
+ method tydecl path name =
+ try Hashtbl.find types (path, name)
+ with Not_found ->
+ failwith
+ (Printf.sprintf "Cannot find type %s in file %s\n%!"
+ (String.concat "." (List.rev (name :: path))) file)
+
+ method mtydecl path name =
+ try Hashtbl.find mtypes (path, name)
+ with Not_found ->
+ failwith
+ (Printf.sprintf "Cannot find module type %s in file %s\n%!"
+ (String.concat "." (List.rev (name :: path))) file)
+ end
+
+ let from_file = memoize from_file
+
+ let copy = object(this)
+ inherit maintain_path as super
+
+ val mutable file = ""
+
+ method source name = function
+ | PStr [] ->
+ let file =
+ if Filename.check_suffix file ".ml"
+ then (Filename.chop_suffix file ".ml") ^ ".mli"
+ else if Filename.check_suffix file ".mli"
+ then (Filename.chop_suffix file ".mli") ^ ".ml"
+ else failwith "Unknown source extension"
+ in
+ file, path, name
+ | PStr [{pstr_desc=Pstr_eval
+ ({pexp_desc=Pexp_apply
+ ({pexp_desc=Pexp_constant(Const_string (file, _)); _},
+ ["", {pexp_desc=Pexp_ident{txt=lid;_}; _}]); _}, _); _}] ->
+ begin match List.rev (Longident.flatten lid) with
+ | [] -> assert false
+ | name :: path -> file, path, name
+ end
+ | _ ->
+ failwith "Cannot parse argument"
+
+ method! tydecl = function
+ | {ptype_kind = Ptype_abstract;
+ ptype_manifest =
+ Some{ptyp_desc=Ptyp_extension({txt="copy_typedef";_}, arg); _};
+ ptype_name = name; ptype_loc = loc; _
+ } ->
+ begin try
+ let (file, path, x) = this # source name.txt arg in
+ {((from_file file) # tydecl path x)
+ with ptype_name = name; ptype_loc = loc}
+ with exn -> fatal loc exn
+ end
+ | td -> td
+
+ method! mtydecl = function
+ | {pmtd_type = Some{pmty_desc=Pmty_extension({txt="copy_typedef";_}, arg);
+ pmty_loc=loc; _};
+ pmtd_name = name; _
+ } ->
+ begin try
+ let (file, path, x) = this # source name.txt arg in
+ {((from_file file) # mtydecl path x)
+ with pmtd_name = name}
+ with exn -> fatal loc exn
+ end
+ | td -> td
+
+ method! implementation f x =
+ file <- f;
+ super # implementation f x
+
+ method! interface f x =
+ file <- f;
+ super # interface f x
+ end
+
+ let () = Ast_mapper.main copy
+end
diff --git a/experimental/frisch/eval.ml b/experimental/frisch/eval.ml
new file mode 100644
index 0000000000..3940b7eac3
--- /dev/null
+++ b/experimental/frisch/eval.ml
@@ -0,0 +1,141 @@
+(* A -ppx rewriter which evaluates expressions at compile-time,
+ using the OCaml toplevel interpreter.
+
+ The following extensions are supported:
+
+ [%eval e] in expression context: the expression e will be evaluated
+ at compile time, and the resulting value will be inserted as a
+ constant literal.
+
+ [%%eval.start] as a structure item: forthcoming structure items
+ until the next [%%eval.stop] will be evaluated at compile time (the
+ result is ignored) only.
+
+ [%%eval.start both] as a structure item: forthcoming structure
+ items until the next [%%eval.stop] will be evaluated at compile
+ time (the result is ignored), but also kept in the compiled unit.
+
+ [%%eval.load "..."] as a structure item: load the specified
+ .cmo unit or .cma library, so that it can be used in the forthcoming
+ compile-time components.
+*)
+
+
+module Main : sig end = struct
+
+ open Location
+ open Parsetree
+ open Ast_helper
+ open Outcometree
+ open Ast_helper.Convenience
+
+ let rec lid_of_out_ident = function
+ | Oide_apply _ -> assert false
+ | Oide_dot (x, s) -> lid_of_out_ident x ^ "." ^ s
+ | Oide_ident s -> s
+
+ let rec exp_of_out_value = function
+ | Oval_string x -> str x
+ | Oval_int x -> int x
+ | Oval_char x -> char x
+ | Oval_float x -> Ast_helper.Convenience.float x
+ | Oval_list l -> list (List.map exp_of_out_value l)
+ | Oval_array l -> Exp.array (List.map exp_of_out_value l)
+ | Oval_constr (c, args) -> constr (lid_of_out_ident c) (List.map exp_of_out_value args)
+ | Oval_record l ->
+ record
+ (List.map
+ (fun (s, v) -> lid_of_out_ident s, exp_of_out_value v) l)
+ | v ->
+ Format.eprintf "[%%eval] cannot map value to expression:@.%a@."
+ !Toploop.print_out_value
+ v;
+ exit 2
+
+ let empty_str_item = Str.include_ (Mod.structure [])
+
+ let run phr =
+ try Toploop.execute_phrase true Format.err_formatter phr
+ with exn ->
+ Errors.report_error Format.err_formatter exn;
+ exit 2
+
+ let get_exp loc = function
+ | PStr [ {pstr_desc=Pstr_eval (e, _); _} ] -> e
+ | _ ->
+ Format.eprintf "%aExpression expected@."
+ Location.print_error loc;
+ exit 2
+
+ let eval _args =
+ let open Ast_mapper in
+ let eval_str_items = ref None in
+ let super = default_mapper in
+ let my_structure_item this i =
+ match i.pstr_desc with
+ | Pstr_extension(({txt="eval.load";loc}, e0), _) ->
+ let e0 = get_exp loc e0 in
+ let s =
+ match get_str e0 with
+ | Some s -> s
+ | None ->
+ Location.print_error Format.err_formatter e0.pexp_loc;
+ Format.eprintf "string literal expected";
+ exit 2
+ in
+ if not (Topdirs.load_file Format.err_formatter s) then begin
+ Location.print Format.err_formatter e0.pexp_loc;
+ exit 2;
+ end;
+ empty_str_item
+ | Pstr_extension(({txt="eval.start";_},
+ PStr [{pstr_desc=Pstr_eval (e, _);_}]
+ ), _) when get_lid e = Some "both" ->
+ eval_str_items := Some true;
+ empty_str_item
+ | Pstr_extension(({txt="eval.start";_}, PStr []), _) ->
+ eval_str_items := Some false;
+ empty_str_item
+ | Pstr_extension(({txt="eval.stop";_}, PStr []), _) ->
+ eval_str_items := None;
+ empty_str_item
+ | _ ->
+ let s = super.structure_item this i in
+ match !eval_str_items with
+ | None -> s
+ | Some both ->
+ if not (run (Ptop_def [s])) then begin
+ Location.print_error Format.err_formatter s.pstr_loc;
+ Format.eprintf "this structure item raised an exception@.";
+ exit 2
+ end;
+ if both then s else empty_str_item
+ in
+ let my_expr this e =
+ match e.pexp_desc with
+ | Pexp_extension({txt="eval";loc}, e0) ->
+ let e0 = get_exp loc e0 in
+ let last_result = ref None in
+ let pop = !Toploop.print_out_phrase in
+ Toploop.print_out_phrase := begin fun _ppf -> function
+ | Ophr_eval (v, _) -> last_result := Some v
+ | r ->
+ Location.print_error Format.err_formatter e.pexp_loc;
+ Format.eprintf "error while evaluating expression:@.%a@."
+ pop
+ r;
+ exit 2
+ end;
+ assert (run (Ptop_def [Str.eval e0]));
+ Toploop.print_out_phrase := pop;
+ let v = match !last_result with None -> assert false | Some v -> v in
+ with_default_loc e0.pexp_loc (fun () -> exp_of_out_value v)
+ | _ ->
+ super.expr this e
+ in
+ Toploop.initialize_toplevel_env ();
+ {super with expr = my_expr; structure_item = my_structure_item}
+
+
+ let () = Ast_mapper.run_main eval
+end
diff --git a/experimental/frisch/extension_points.txt b/experimental/frisch/extension_points.txt
new file mode 100644
index 0000000000..f9d4e774a0
--- /dev/null
+++ b/experimental/frisch/extension_points.txt
@@ -0,0 +1,740 @@
+This file describes the changes on the extension_points branch.
+
+
+=== Attributes
+
+Attributes are "decorations" of the syntax tree which are ignored by
+the type-checker. An attribute is made of an identifier (written id below)
+and a payload (written s below).
+
+ * The identifier 'id' can be a lowercase or uppercase identifier
+ (including OCaml keywords) or a sequence of such atomic identifiers
+ separated with a dots (whitespaces are allowed around the dots).
+ In the Parsetree, the identifier is represented as a single string
+ (without spaces).
+
+ * The payload 's' can be one of three things:
+
+ - An OCaml structure (i.e. a list of structure items). Note that a
+ structure can be empty or reduced to a single expression.
+
+ [@id]
+ [@id x + 3]
+ [@id type t = int]
+
+ - A type expression, prefixed with the ":" character.
+
+ [@id : TYP]
+
+ - A pattern, prefixed with the "?" character, and optionally followed
+ by a "when" clause:
+
+ [@id ? PAT]
+ [@id ? PAT when EXPR]
+
+
+Attributes on expressions, type expressions, module expressions, module type expressions,
+patterns, class expressions, class type expressions:
+
+ ... [@id s]
+
+The same syntax [@id s] is also available to add attributes on
+constructors and labels in type declarations:
+
+ type t =
+ | A [@id1]
+ | B [@id2] of int [@id3]
+
+Here, id1 (resp. id2) is attached to the constructor A (resp. B)
+and id3 is attached to the int type expression. Example on records:
+
+ type t =
+ {
+ x [@id1]: int;
+ mutable y [@id2] [@id3]: string [@id4];
+ }
+
+
+Attributes on items:
+
+ ... [@@id s]
+
+ Items designate:
+ - structure and signature items (for type declarations, recursive modules, class
+ declarations and class type declarations, each component has its own attributes)
+ - class fields and class type fields
+ - each binding in a let declaration (for let structure item, local let-bindings in
+ expression and class expressions)
+
+ For instance, consider:
+
+ type t1 = ... [@@id1] [@@id2] and t2 = ... [@@id3] [@@id4]
+
+ Here, the attributes on t1 are id1, id23; the attributes on
+ t2 are id3 and id4.
+
+ Similarly for:
+
+ let x1 = ... [@@id1] [@@id2] and x2 = ... [@@id3] [@@id4]
+
+
+Floating attributes:
+
+ The [@@@id s] form defines an attribute which stands as a
+ stand-alone signature or structure item (not attached to another
+ item).
+
+ Example:
+
+ module type S = sig
+ [@@id1]
+ type t
+ [@@id2]
+ [@@@id3] [@@@id4]
+ [@@@id5]
+ type s
+ [@@id6]
+ end
+
+ Here, id1, id3, id4, id5 are floating attributes, while
+ id2 is attached to the type t and id6 is attached to the type s.
+
+=== Extension nodes
+
+Extension nodes replace valid components in the syntax tree. They are
+normally interpreted and expanded by AST mapper. The type-checker
+fails when it encounters such an extension node. An extension node is
+made of an identifier (an "LIDENT", written id below) and an optional
+expression (written expr below).
+
+Two syntaxes exist for extension node:
+
+As expressions, type expressions, module expressions, module type expressions,
+patterns, class expressions, class type expressions:
+
+ [%id s]
+
+As structure item, signature item, class field, class type field:
+
+ [%%id s]
+
+As other structure item, signature item, class field or class type
+field, attributes can be attached to a [%%id s] extension node.
+
+
+
+=== Alternative syntax for attributes and extensions on specific kinds of nodes
+
+All expression constructions starting with a keyword (EXPR = KW REST) support an
+alternative syntax for attributes and/or extensions:
+
+ KW[@id s]...[@id s] REST
+ ---->
+ EXPR[@id s]...[@id s]
+
+ KW%id REST
+ ---->
+ [%id EXPR]
+
+ KW%id[@id s]...[@id s] REST
+ ---->
+ [%id EXPR[@id s]...[@id s]]
+
+
+where KW can stand for:
+ assert
+ begin
+ for
+ fun
+ function
+ if
+ lazy
+ let
+ let module
+ let open
+ match
+ new
+ object
+ try
+ while
+
+
+For instance:
+
+let[@foo] x = 2 in x + 1 ==== (let x = 2 in x + 1)[@foo]
+begin[@foo] ... end ==== (begin ... end)[@foo]
+match%foo e with ... ==== [%foo match e with ...]
+
+
+The let-binding form of structure items also supports this form:
+
+let%foo x = ... ==== [%%foo let x = ...]
+
+=== Quoted strings
+
+Quoted strings gives a different syntax to write string literals in
+OCaml code. This will typically be used to support embedding pieces
+of foreign syntax fragments (to be interpret by a -ppx filter or just
+a library) in OCaml code.
+
+The opening delimiter has the form {id| where id is a (possibly empty)
+sequence of lowercase letters. The corresponding closing delimiter is
+|id} (the same identifier). Contrary to regular OCaml string
+literals, quoted strings don't interpret any character in a special
+way.
+
+Example:
+
+String.length {|\"|} (* returns 2 *)
+String.length {foo|\"|foo} (* returns 2 *)
+
+
+The fact that a string literal comes from a quoted string is kept in
+the Parsetree representation. The Astypes.Const_string constructor is
+now defined as:
+
+ | Const_string of string * string option
+
+where the "string option" represents the delimiter (None for a string
+literal with the regular syntax).
+
+
+=== Representation of attributes in the Parsetree
+
+Attributes as standalone signature/structure items are represented
+by a new constructor:
+
+ | Psig_attribute of attribute
+ | Pstr_attribute of attribute
+
+Most other attributes are stored in an extra field in their record:
+
+and expression = {
+ ...
+ pexp_attributes: attribute list;
+ ...
+}
+and type_declaration = {
+ ...
+ ptype_attributes: attribute list;
+ ...
+}
+
+In a previous version, attributes on expressions (and types, patterns,
+etc) used to be stored as a new constructor. The current choice makes
+it easier to pattern match on structured AST fragments while ignoring
+attributes.
+
+For open/include signature/structure items and exception rebind
+structure item, the attributes are stored directly in the constructor
+of the item:
+
+ | Pstr_open of Longident.t loc * attribute list
+
+
+=== Attributes in the Typedtree
+
+The Typedtree representation has been updated to follow closely the
+Parsetree, and attributes are kept exactly as in the Parsetree. This
+can allow external tools to process .cmt/.cmti files and process
+attributes in them. An example of a mini-ocamldoc based on this
+technique is in experimental/frisch/minidoc.ml.
+
+
+=== Other changes to the parser and Parsetree
+
+--- Introducing Ast_helper module
+
+This module simplifies the creation of AST fragments, without having to
+touch the concrete type definitions of Parsetree. Record and sum types
+are encapsulated in builder functions, with some optional arguments, e.g.
+to represent attributes.
+
+--- Relaxing the syntax for signatures and structures
+
+It is now possible to start a signature or a structure with a ";;" token and to have two successive ";;" tokens.
+
+Rationale:
+ In an intermediate version of this branch, floating attributes shared
+ the same syntax as item attributes, with the constraints that they
+ had to appear either at the beginning of their structure or signature,
+ or after ";;". The relaxation above made is possible to always prefix
+ a floating attributes by ";;" independently of its context.
+
+ Floating attributes now have a custom syntax [@@@id], but this changes
+ is harmless, and the same argument holds for toplevel expressions:
+ it is always possile to write:
+
+ ;; print_endline "bla";;
+
+ without having to care about whether the previous structure item
+ ends with ";;" or not.
+
+
+-- Relaxing the syntax for exception declarations
+
+The parser now accepts the same syntax for exceptioon declarations as for constructor declarations,
+which permits the GADT syntax:
+
+ exception A : int -> foo
+
+The type-checker rejects this form. Note that it is also possible to
+define exception whose name is () or ::.
+
+Attributes can be put on the constructor or on the whole declaration:
+
+ exception A[@foo] of int [@@bar]
+
+Rationale:
+ One less notion in the Parsetree, more uniform parsing. Also
+ open the door to existentials in exception constructors.
+
+--- Relaxing the syntax for recursive modules
+
+Before:
+ module X1 : MT1 = M1 and ... and Xn : MTn = Mn
+
+Now:
+ module X1 = M1 and ... and Xn = Mn
+ (with the usual sugar that Xi = (Mi : MTi) can be written as Xi : MTi = Mi
+ which gives the old syntax)
+
+ The type-checker fails when a module expression is not of
+ the form (M : MT)
+
+
+Rationale:
+
+1. More uniform representation in the Parsetree.
+
+2. The type-checker can be made more clever in the future to support
+ other forms of module expressions (e.g. functions with an explicit
+ constraint on its result; or a structure with only type-level
+ components).
+
+
+--- Turning some tuple or n-ary constructors into records
+
+Before:
+
+ | Pstr_module of string loc * module_expr
+
+After:
+
+ | Pstr_module of module_binding
+...
+ and module_binding =
+ {
+ pmb_name: string loc;
+ pmb_expr: module_expr;
+ pmb_attributes: attribute list;
+ }
+
+
+
+Rationale:
+
+More self-documented, more robust to future additions (such as
+attributes), simplifies some code.
+
+
+--- Keeping names inside value_description and type_declaration
+
+Before:
+
+ | Psig_type of (string loc * type_declaration) list
+
+
+After:
+
+ | Psig_type of type_declaration list
+
+....
+and type_declaration =
+ { ptype_name: string loc;
+ ...
+ }
+
+Rationale:
+
+More self-documented, simplifies some code.
+
+
+--- Better representation of variance information on type parameters
+
+Introduced a new type Asttypes.variance to represent variance
+(Covariant/Contravariant/Invariant) and use it instead of bool * bool
+in Parsetree. Moreover, variance information is now attached
+directly to the parameters fields:
+
+ and type_declaration =
+ { ptype_name: string loc;
+- ptype_params: string loc option list;
++ ptype_params: (string loc option * variance) list;
+ ptype_cstrs: (core_type * core_type * Location.t) list;
+ ptype_kind: type_kind;
+ ptype_private: private_flag;
+ ptype_manifest: core_type option;
+- ptype_variance: (bool * bool) list;
+ ptype_attributes: attribute list;
+ ptype_loc: Location.t }
+
+
+--- Getting rid of 'Default' case in Astypes.rec_flag
+
+This constructor was used internally only during the compilation of
+default expression for optional arguments, in order to trigger a
+subsequent optimization (see PR#5975). This behavior is now
+implemented by creating an attribute internally (whose name "#default"
+cannot be used in real programs).
+
+Rationale:
+
+ - Attributes give a way to encode information local to the
+ type-checker without polluting the definition of the Parsetree.
+
+--- Simpler and more faithful representation of object types
+
+- | Ptyp_object of core_field_type list
++ | Ptyp_object of (string * core_type) list * closed_flag
+
+(and get rid of Parsetree.core_field_type)
+
+And same in the Typedtree.
+
+Rationale:
+
+ - More faithful representation of the syntax really supported
+ (i.e. the ".." can only be the last field).
+ - One less "concept" in the Parsetree.
+
+
+--- Do not require empty Ptyp_poly nodes in the Parsetree
+
+The type-checker automatically inserts Ptyp_poly node (with no
+variable) where needed. It is still allowed to put empty
+Ptyp_poly nodes in the Parsetree.
+
+Rationale:
+
+ - Less chance that Ast-related code forget to insert those nodes.
+
+To be discussed: should we segrate simple_poly_type from core_type in the
+Parsetree to prevent Ptyp_poly nodes to be inserted in the wrong place?
+
+
+--- Use constructor names closer to concrete syntax
+
+E.g. Pcf_cstr -> Pcf_constraint.
+
+Rationale:
+
+ - Make the Parsetree more self-documented.
+
+--- Merge concrete/virtual val and method constructors
+
+As in the Typedtree.
+
+- | Pcf_valvirt of (string loc * mutable_flag * core_type)
+- | Pcf_val of (string loc * mutable_flag * override_flag * expression)
+- | Pcf_virt of (string loc * private_flag * core_type)
+- | Pcf_meth of (string loc * private_flag * override_flag * expression)
++ | Pcf_val of (string loc * mutable_flag * class_field_kind)
++ | Pcf_method of (string loc * private_flag * class_field_kind
+...
++and class_field_kind =
++ | Cfk_virtual of core_type
++ | Cfk_concrete of override_flag * expression
++
+
+--- Explicit representation of "when" guards
+
+Replaced the "(pattern * expression) list" argument of Pexp_function, Pexp_match, Pexp_try
+with "case list", with case defined as:
+
+ {
+ pc_lhs: pattern;
+ pc_guard: expression option;
+ pc_rhs: expression;
+ }
+
+and get rid of Pexp_when. Idem in the Typedtree.
+
+Rationale:
+
+ - Make it explicit when the guard can appear.
+
+--- Get rid of "fun p when guard -> e"
+
+See #5939, #5936.
+
+
+--- Get rid of the location argument on pci_params
+
+It was only used for error messages, and we get better location using
+the location of each parameter variable.
+
+--- More faithful representation of "with constraint"
+
+All kinds of "with constraints" used to be represented together with a
+Longident.t denoting the constrained identifier. Now, each constraint
+keeps its own constrainted identifier, which allows us to express more
+invariants in the Parsetree (such as: := constraints cannot be on qualified
+identifiers). Also, we avoid mixing in a single Longident.t identifier
+which can be LIDENT or UIDENT.
+
+--- Get rid of the "#c [> `A]" syntax
+
+See #5936, #5983.
+
+--- Keep interval patterns in the Parsetree
+
+They used to be expanded into or-patterns by the parser. It is better to do
+the expansion in the type-checker to allow -ppx rewriters to see the interval
+patterns.
+
+Note: Camlp4 parsers still expand interval patterns themselves (TODO?).
+
+--- Get rid of Pexp_assertfalse
+
+Do not treat specially "assert false" in the parser any more, but
+instead in the type-checker. This simplifies the Parsetree and avoids
+a potential source of confusion. Moreove, this ensures that
+attributes can be put (and used by ppx rewriters) on the "false"
+expressions. This is also more robust, since it checks that the
+condition is the constructor "false" after type-checking the condition:
+
+ - if "false" is redefined (as a constructor of a different sum type),
+ an error will be reported;
+
+ - "extra" layers which are represented as exp_extra in the typedtree
+ won't break the detection of the "false", e.g. the following will
+ be recognized as "assert false":
+
+ assert(false : bool)
+ assert(let open X in false)
+
+Note: Camlp4's AST still has a special representation for "assert false".
+
+--- Get rid of the "explicit arity" flag on Pexp_construct/Ppat_construct
+
+This Boolean was used (only by camlp5?) to indicate that the tuple
+(expression/pattern) used as the argument was intended to correspond
+to the arity of an n-ary constructor. In particular, this allowed
+the revised syntax to distinguish "A x y" from "A (x, y)" (the second one
+being wrapped in an extra fake tuple) and get a proper error message
+if "A (x, y)" was used with a constructor expecting two arguments.
+
+The feature has been preserved, but the information that a
+Pexp_construct/Ppat_constructo node has an "exact arity" is now
+propagated used as am attribute "ocaml.explicit_arity" on that node.
+
+--- Split Pexp_function into Pexp_function/Pexp_fun
+
+This reflects more closely the concrete syntax and removes cases of
+Parsetree fragments which don't correspond to concrete syntax.
+
+Typedtree has not been changed.
+
+Note: Camlp4's AST has not been adapted.
+
+--- Split Pexp_constraint into Pexp_constraint/Pexp_coerce
+
+Idem in the Typedtree.
+
+This reflects more closely the concrete syntax.
+
+Note: Camlp4's AST has not been adapted.
+
+--- Accept abstract module type declaration in structures
+
+Previously, we could declare:
+
+ module type S
+
+in signatures, but not implementations. To make the syntax, the Parsetree
+and the type-checker more uniform, this is now also allowed in structures
+(altough this is probably useless in practice).
+
+=== More TODOs
+
+- Adapt pprintast to print attributes and extension nodes.
+- Adapt Camlp4 (both its parser(s) and its internal representation of OCaml ASTs).
+- Consider adding hooks to the type-checker so that custom extension expanders can be registered (a la OCaml Templates).
+- Make the Ast_helper module more user-friendly (e.g. with optional arguments and good default values) and/or
+ expose higher-level convenience functions.
+- Document Ast_helper modules.
+
+=== Use cases
+
+From https://github.com/gasche/ocaml-syntax-extension-discussion/wiki/Use-Cases
+
+-- Bisect
+
+ let f x =
+ match List.map foo [x; a x; b x] with
+ | [y1; y2; y3] -> tata
+ | _ -> assert false [@bisect VISIT]
+
+;;[@@bisect IGNORE-BEGIN]
+let unused = ()
+;;[@@bisect IGNORE-END]
+
+-- OCamldoc
+
+val stats : ('a, 'b) t -> statistics
+[@@doc
+ "[Hashtbl.stats tbl] returns statistics about the table [tbl]:
+ number of buckets, size of the biggest bucket, distribution of
+ buckets by size."
+]
+[@@since "4.00.0"]
+
+;;[@@doc section 6 "Functorial interface"]
+
+module type HashedType =
+ sig
+ type t
+ [@@doc "The type of the hashtable keys."]
+ val equal : t -> t -> bool
+ [@@doc "The equality predicate used to compare keys."]
+ end
+
+
+-- type-conv, deriving
+
+type t = {
+ x : int [@default 42];
+ y : int [@default 3] [@sexp_drop_default];
+ z : int [@default 3] [@sexp_drop_if z_test];
+} [@@sexp]
+
+
+type r1 = {
+ r1_l1 : int;
+ r1_l2 : int;
+} [@@deriving (Dump, Eq, Show, Typeable, Pickle, Functor)]
+
+-- camlp4 map/fold generators
+
+type variable = string
+ and term =
+ | Var of variable
+ | Lam of variable * term
+ | App of term * term
+
+
+class map = [%generate_map term]
+or:
+[%%generate_map map term]
+
+
+-- ocaml-rpc
+
+type t = { foo [@rpc "type"]: int; bar [@rpc "let"]: int }
+[@@ rpc]
+
+or:
+
+type t = { foo: int; bar: int }
+[@@ rpc ("foo" > "type"), ("bar" > "let")]
+
+
+
+-- pa_monad
+
+begin%monad
+ a <-- [1; 2; 3];
+ b <-- [3; 4; 5];
+ return (a + b)
+end
+
+-- pa_lwt
+
+let%lwt x = start_thread foo
+and y = start_other_thread foo in
+try%lwt
+ let%for_lwt (x, y) = waiting_threads in
+ compute blah
+with Killed -> bar
+
+-- Bolt
+
+let funct n =
+ [%log "funct(%d)" n LEVEL DEBUG];
+ for i = 1 to n do
+ print_endline "..."
+ done
+
+
+-- pre-polyrecord
+
+let r = [%polyrec x = 1; y = ref None]
+let () = [%polyrec r.y <- Some 2]
+
+-- orakuda
+
+function%regexp
+ | "$/^[0-9]+$/" as v -> `Int (int_of_string v#_0)
+ | "$/^[a-z][A-Za-z0-9_]*$" as v -> `Variable v#_0
+ | _ -> failwith "parse error"
+
+-- bitstring
+
+let bits = Bitstring.bitstring_of_file "/bin/ls" in
+match%bitstring bits with
+| [ 0x7f, 8; "ELF", 24, string; (* ELF magic number *)
+ e_ident, Mul(12,8), bitstring; (* ELF identifier *)
+ e_type, 16, littleendian; (* object file type *)
+ e_machine, 16, littleendian (* architecture *)
+ ] ->
+ printf "This is an ELF binary, type %d, arch %d\n"
+ e_type e_machine
+
+-- sedlex
+
+let rec token buf =
+ let%regexp ('a'..'z'|'A'..'Z') = letter in
+ match%sedlex buf with
+ | number -> Printf.printf "Number %s\n" (Sedlexing.Latin1.lexeme buf); token buf
+ | letter, Star ('A'..'Z' | 'a'..'z' | digit) -> Printf.printf "Ident %s\n" (Sedlexing.Latin1.lexeme buf); token buf
+ | Plus xml_blank -> token buf
+ | Plus (Chars "+*-/") -> Printf.printf "Op %s\n" (Sedlexing.Latin1.lexeme buf); token buf
+ | Range(128,255) -> print_endline "Non ASCII"
+ | eof -> print_endline "EOF"
+ | _ -> failwith "Unexpected character"
+
+
+-- cppo
+
+[%%ifdef DEBUG]
+[%%define debug(s) = Printf.eprintf "[%S %i] %s\n%!" __FILE__ __LINE__ s]
+[%%else]
+[%%define debug(s) = ()]
+[%%endif]
+
+debug("test")
+
+
+-- PG'OCaml
+
+let fetch_users dbh =
+ [%pgsql dbh "select id, name from users"]
+
+
+-- Macaque
+
+let names view = [%view {name = t.name}, t <- !view]"
+
+
+-- Cass
+
+let color1 = [%css{| black |}]
+let color2 = [%css{| gray |}]
+
+let button = [%css{|
+ .button {
+ $Css.gradient ~low:color2 ~high:color1$;
+ color: white;
+ $Css.top_rounded$;
+ |}]
diff --git a/experimental/frisch/ifdef.ml b/experimental/frisch/ifdef.ml
new file mode 100644
index 0000000000..6263b59a26
--- /dev/null
+++ b/experimental/frisch/ifdef.ml
@@ -0,0 +1,118 @@
+(* This filter implements the following extensions:
+
+ In structures:
+
+ [%%IFDEF X]
+ ... --> included if the environment variable X is defined
+ [%%ELSE]
+ ... --> included if the environment variable X is undefined
+ [%%END]
+
+
+ In expressions:
+
+ [%GETENV X] ---> the string literal representing the compile-time value
+ of environment variable X
+
+
+ In variant type declarations:
+
+ type t =
+ ..
+ | C [@IFDEF X] of ... --> the constructor is kept only if X is defined
+
+
+ In match clauses (function/match...with/try...with):
+
+
+ P when [%IFDEF X] -> E --> the case is kept only if X is defined
+
+*)
+
+open Ast_helper
+open! Asttypes
+open Parsetree
+open Longident
+
+let getenv loc arg =
+ match arg with
+ | PStr [{pstr_desc=Pstr_eval({pexp_desc = Pexp_construct ({txt = Lident sym; _}, None); _}, _); _}] ->
+ (try Sys.getenv sym with Not_found -> "")
+ | _ ->
+ Format.eprintf "%a** IFDEF: bad syntax."
+ Location.print_error loc;
+ exit 2
+
+let empty_str_item = Str.include_ (Mod.structure [])
+
+let ifdef _args =
+ let stack = ref [] in
+ let eval_attributes =
+ List.for_all
+ (function
+ | {txt="IFDEF"; loc}, arg -> getenv loc arg <> ""
+ | {txt="IFNDEF"; loc}, arg -> getenv loc arg = ""
+ | _ -> true)
+ in
+ let filter_constr cd = eval_attributes cd.pcd_attributes in
+ let open Ast_mapper in
+ let super = default_mapper in
+ {
+ super with
+
+ type_declaration =
+ (fun this td ->
+ let td =
+ match td with
+ | {ptype_kind = Ptype_variant cstrs; _} as td ->
+ {td
+ with ptype_kind = Ptype_variant(List.filter filter_constr cstrs)}
+ | td -> td
+ in
+ super.type_declaration this td
+ );
+
+ cases =
+ (fun this l ->
+ let l =
+ List.fold_right
+ (fun c rest ->
+ match c with
+ | {pc_guard=Some {pexp_desc=Pexp_extension({txt="IFDEF";loc}, arg); _}; _} ->
+ if getenv loc arg = "" then rest else {c with pc_guard=None} :: rest
+ | c -> c :: rest
+ ) l []
+ in
+ super.cases this l
+ );
+
+ structure_item =
+ (fun this i ->
+ match i.pstr_desc, !stack with
+ | Pstr_extension(({txt="IFDEF";loc}, arg), _), _ ->
+ stack := (getenv loc arg <> "") :: !stack;
+ empty_str_item
+ | Pstr_extension(({txt="ELSE";loc=_}, _), _), (hd :: tl) ->
+ stack := not hd :: tl;
+ empty_str_item
+ | Pstr_extension(({txt="END";loc=_}, _), _), _ :: tl ->
+ stack := tl;
+ empty_str_item
+ | Pstr_extension(({txt="ELSE"|"END";loc}, _), _), [] ->
+ Format.printf "%a** IFDEF: mo matching [%%%%IFDEF]"
+ Location.print_error loc;
+ exit 2
+ | _, (true :: _ | []) -> super.structure_item this i
+ | _, false :: _ -> empty_str_item
+ );
+
+ expr =
+ (fun this -> function
+ | {pexp_desc = Pexp_extension({txt="GETENV";loc=l}, arg);
+ pexp_loc = loc; _} ->
+ Exp.constant ~loc (Const_string (getenv l arg, None))
+ | x -> super.expr this x
+ );
+ }
+
+let () = Ast_mapper.run_main ifdef
diff --git a/experimental/frisch/js_syntax.ml b/experimental/frisch/js_syntax.ml
new file mode 100644
index 0000000000..fe11cb65ad
--- /dev/null
+++ b/experimental/frisch/js_syntax.ml
@@ -0,0 +1,112 @@
+(* This example shows how the AST mapping approach could be used
+ instead of Camlp4 in order to give a nice syntax for js_of_ocaml
+ (properties and method calls). The code below overloads regular
+ syntax for field projection and assignment for Javascript
+ properties, and (currified) method call for Javascript method
+ calls. This is enabled under the scope of the [%js ...] extension:
+
+ Get property: [%js o.x]
+ Set property: [%js o.x <- e]
+ Method call: [%js o#x e1 e2]
+ *)
+
+open Asttypes
+open! Location
+open Parsetree
+open Longident
+open Ast_helper
+open Ast_helper.Convenience
+
+(* A few local helper functions to simplify the creation of AST nodes. *)
+let apply_ f l = app (evar f) l
+let oobject l = Typ.object_ l Open
+let annot e t = Exp.constraint_ e t
+
+
+let rnd = Random.State.make [|0x513511d4|]
+let random_var () = Format.sprintf "a%08Lx" (Random.State.int64 rnd 0x100000000L : Int64.t)
+let fresh_type () = Typ.var (random_var ())
+
+let unescape lab =
+ assert (lab <> "");
+ let lab =
+ if lab.[0] = '_' then String.sub lab 1 (String.length lab - 1) else lab
+ in
+ try
+ let i = String.rindex lab '_' in
+ if i = 0 then raise Not_found;
+ String.sub lab 0 i
+ with Not_found ->
+ lab
+
+let method_literal meth = str (unescape meth)
+
+let access_object loc e m m_typ f =
+ let open Exp in
+ with_default_loc loc
+ (fun () ->
+ let x = random_var () in
+ let obj_type = random_var () in
+ let obj = annot e Typ.(tconstr "Js.t" [alias (oobject []) obj_type]) in
+ let y = random_var () in
+ let o = annot (evar y) (Typ.var obj_type) in
+ let constr = lam (pvar y) (annot (send o m) m_typ) in
+ let_in [Vb.mk (pvar x) obj; Vb.mk (Pat.any ()) constr] (f (evar x))
+ )
+
+let method_call loc obj meth args =
+ let args = List.map (fun e -> (e, fresh_type ())) args in
+ let ret_type = fresh_type () in
+ let method_type =
+ List.fold_right
+ (fun (_, arg_ty) rem_ty -> Typ.arrow "" arg_ty rem_ty)
+ args
+ (tconstr "Js.meth" [ret_type])
+ in
+ access_object loc obj meth method_type
+ (fun x ->
+ let args =
+ List.map (fun (e, t) -> apply_ "Js.Unsafe.inject" [annot e t]) args
+ in
+ annot (apply_ "Js.Unsafe.meth_call" [x; method_literal meth; Exp.array args]) ret_type
+ )
+
+
+let mapper _args =
+ let open Ast_mapper in
+ let rec mk ~js =
+ let super = default_mapper in
+ let expr this e =
+ let loc = e.pexp_loc in
+ match e.pexp_desc with
+ | Pexp_extension({txt="js";_}, PStr [{pstr_desc=Pstr_eval (e, _);_}]) ->
+ let this = mk ~js:true in this.expr this e
+
+ | Pexp_field (o, {txt = Lident meth; loc = _}) when js ->
+ let o = this.expr this o in
+ let prop_type = fresh_type () in
+ let meth_type = tconstr "Js.gen_prop" [oobject ["get", prop_type]] in
+ access_object loc o meth meth_type
+ (fun x -> annot (apply_ "Js.Unsafe.get" [x; method_literal meth]) prop_type)
+
+ | Pexp_setfield (o, {txt = Lident meth; loc = _}, e) when js ->
+ let o = this.expr this o and e = this.expr this e in
+ let prop_type = fresh_type () in
+ let meth_type = tconstr "Js.gen_prop" [oobject ["set", Typ.arrow "" prop_type (tconstr "unit" [])]] in
+ access_object loc o meth meth_type
+ (fun x -> apply_ "Js.Unsafe.set" [x; method_literal meth; annot e prop_type])
+
+ | Pexp_apply ({pexp_desc = Pexp_send (o, meth); pexp_loc = loc; _}, args) when js ->
+ method_call loc o meth (List.map (this.expr this) (List.map snd args))
+
+ | Pexp_send (o, meth) when js ->
+ method_call loc o meth []
+
+ | _ ->
+ super.expr this e
+ in
+ {super with expr}
+ in
+ mk ~js:false
+
+let () = Ast_mapper.run_main mapper
diff --git a/experimental/frisch/metaquot_test.ml b/experimental/frisch/metaquot_test.ml
new file mode 100644
index 0000000000..bbdfe24028
--- /dev/null
+++ b/experimental/frisch/metaquot_test.ml
@@ -0,0 +1,27 @@
+let loc1 = Location.in_file "111"
+let loc2 = Location.in_file "222"
+
+let x = [%expr foobar]
+let pat = [%pat? _ as x]
+
+let e = [%expr fun (x, [%p pat]) -> x + [%e x] + 1]
+let () = Format.printf "%a@." (Printast.expression 0) e
+
+;;[@@metaloc loc2]
+
+let e = [%expr fun (x, [%p pat]) -> x + [%e x] + 1] [@metaloc loc1]
+let () = Format.printf "%a@." (Printast.expression 0) e
+
+let e = [%expr fun (x, [%p pat]) -> x + [%e x] + 1]
+let () = Format.printf "%a@." (Printast.expression 0) e
+
+
+let mytype = [%type: int list]
+let s = [%str type t = A of [%t mytype] | B of string]
+let () = Format.printf "%a@." Printast.implementation s
+
+
+let f = function
+ | ([%expr [%e? x] + 1]
+ | [%expr 1 + [%e? x]]) as e0 -> [%expr succ [%e x]] [@metaloc e0.pexp_loc]
+ | e -> e
diff --git a/experimental/frisch/minidoc.ml b/experimental/frisch/minidoc.ml
new file mode 100644
index 0000000000..bf37a0123c
--- /dev/null
+++ b/experimental/frisch/minidoc.ml
@@ -0,0 +1,72 @@
+open Asttypes
+open Parsetree
+open Typedtree
+open Longident
+
+let pendings = ref []
+
+let doc ppf = function
+ | ({txt="doc";_}, PStr [{pstr_desc=Pstr_eval(e, _); _}]) ->
+ begin match e.pexp_desc with
+ | Pexp_constant(Const_string (s, _)) ->
+ Format.fprintf ppf " --> %s@." s
+ | Pexp_apply({pexp_desc=Pexp_ident{txt=Lident "section"}},
+ ["", {pexp_desc=Pexp_constant(Const_string (s, _))}]) ->
+ Format.fprintf ppf " ==== %s ====@." s
+ | _ -> ()
+ end
+ | _ -> ()
+
+let rec signature path ppf sg =
+ List.iter (signature_item path ppf) sg.sig_items
+
+and signature_item path ppf si =
+ match si.sig_desc with
+ | Tsig_value x ->
+ Format.fprintf ppf " val %s: %a@." x.val_name.txt Printtyp.type_expr x.val_desc.ctyp_type;
+ List.iter (doc ppf) x.val_attributes
+ | Tsig_module x ->
+ begin match x.md_type.mty_desc with
+ | Tmty_ident (_, {txt=lid}) ->
+ Format.fprintf ppf " module %s: %a@." x.md_name.txt Printtyp.longident lid
+ | Tmty_signature sg ->
+ pendings := `Module (path ^ "." ^ x.md_name.txt, sg) :: !pendings;
+ Format.fprintf ppf " module %s: ... (see below)@." x.md_name.txt;
+ | _ ->
+ Format.fprintf ppf " module %s: ...@." x.md_name.txt;
+ end;
+ List.iter (doc ppf) x.md_attributes
+ | Tsig_type l ->
+ List.iter (type_declaration ppf) l
+ | Tsig_attribute x ->
+ doc ppf x
+ | _ ->
+ ()
+
+and type_declaration ppf x =
+ Format.fprintf ppf " type %s@." x.typ_name.txt;
+ List.iter (doc ppf) x.typ_attributes
+
+let component = function
+ | `Module (path, sg) ->
+ Format.printf "[[[ Interface for %s ]]]@.%a@."
+ path (signature path) sg
+
+let () =
+ let open Cmt_format in
+ for i = 1 to Array.length Sys.argv - 1 do
+ let fn = Sys.argv.(i) in
+ try
+ let {cmt_annots; cmt_modname; _} = read_cmt fn in
+ begin match cmt_annots with
+ | Interface sg -> component (`Module (cmt_modname, sg))
+ | _ -> ()
+ end;
+ while !pendings <> [] do
+ let l = List.rev !pendings in
+ pendings := [];
+ List.iter component l
+ done
+ with exn ->
+ Format.printf "Cannot read '%s': %s@." fn (Printexc.to_string exn)
+ done
diff --git a/experimental/frisch/nomli.ml b/experimental/frisch/nomli.ml
new file mode 100644
index 0000000000..6cf34557bc
--- /dev/null
+++ b/experimental/frisch/nomli.ml
@@ -0,0 +1,114 @@
+(** Creates an mli from an annotated ml file. *)
+
+open Path
+open Location
+open Longident
+open Misc
+open Parsetree
+open Types
+open! Typedtree
+open Ast_helper
+
+let mli_attr l = Convenience.find_attr "mli" l
+
+let map_flatten f l =
+ List.flatten (List.map f l)
+
+let is_abstract = function
+ | PStr [{pstr_desc=Pstr_eval({pexp_desc=Pexp_ident{txt=Lident "abstract"}},_)}] -> true
+ | _ -> false
+
+let explicit_type_of_expr = function
+ | {pexp_desc=Pexp_constraint({pexp_desc=Pexp_ident{txt=Lident id}}, t)} -> [id, t]
+ | _ -> []
+
+let explicit_type = function
+ | PStr [{pstr_desc=Pstr_eval({pexp_desc=Pexp_tuple el},_)}] -> map_flatten explicit_type_of_expr el
+ | PStr [{pstr_desc=Pstr_eval(e,_)}] -> explicit_type_of_expr e
+ | _ -> []
+
+let rec structure l : Parsetree.signature =
+ map_flatten (structure_item l.str_final_env) l.str_items
+
+and structure_item final_env x : Parsetree.signature =
+ match x.str_desc with
+ | Tstr_module {mb_name; mb_expr} ->
+ begin match module_expr mb_expr with
+ | Some mty -> [Sig.module_ (Md.mk mb_name mty)]
+ | None -> []
+ end
+ | Tstr_type l ->
+ begin match map_flatten type_declaration l with
+ | [] -> []
+ | l -> [Sig.type_ l]
+ end
+ | Tstr_value (_, l) ->
+ map_flatten (value_binding final_env) l
+ | _ ->
+ []
+
+and module_expr x : Parsetree.module_type option =
+ match x.mod_desc with
+ | Tmod_structure l ->
+ (* No explicit signature: use [@@mli] attributes in the sub-structure to define exported components. *)
+ begin match structure l with
+ | [] -> None
+ | l -> Some (Mty.signature l)
+ end
+ | Tmod_constraint (_, _, Tmodtype_explicit mty, _) ->
+ (* Explicit signature: if non-empty, use it for the mli; if empty, drop the sub-module *)
+ begin match Untypeast.untype_module_type mty with
+ | {pmty_desc=Pmty_signature []} -> None
+ | pmty -> Some pmty
+ end
+ | _ ->
+ None
+
+and type_declaration x : Parsetree.type_declaration list =
+ match mli_attr x.typ_attributes with
+ | None -> []
+ | Some attrs ->
+ let pdecl = Untypeast.untype_type_declaration x in
+ (* If the declaration is marked with [@@mli abstract], make it abstract *)
+ let pdecl = if is_abstract attrs then {pdecl with ptype_kind=Ptype_abstract} else pdecl in
+ [pdecl]
+
+and value_binding final_env x : Parsetree.signature =
+ match mli_attr x.vb_attributes with
+ | None -> []
+ | Some attrs ->
+ match explicit_type attrs with
+ | [] ->
+ (* No explicit type, use the inferred type for bound identifiers *)
+ let ids = let_bound_idents [x] in
+ List.map
+ (fun id ->
+ let ty = typ (Env.find_value (Pident id) final_env).val_type in
+ Sig.value (Val.mk (mknoloc (Ident.name id)) ty)
+ ) ids
+ | l ->
+ (* Explicit type given with the syntax [@@mli (x1 : ty1), ..., (xn : tyn)] *)
+ List.map (fun (id, ty) -> Sig.value (Val.mk (mknoloc id) ty)) l
+
+and typ x : Parsetree.core_type =
+ (* print the inferred type and parse the result again *)
+ let t = Printtyp.type_scheme Format.str_formatter x in
+ let s = Format.flush_str_formatter t in
+ Parse.core_type (Lexing.from_string s)
+
+let mli_of_ml ppf sourcefile =
+ Location.input_name := sourcefile;
+ Compmisc.init_path false;
+ let file = chop_extension_if_any sourcefile in
+ let modulename = String.capitalize(Filename.basename file) in
+ Env.set_unit_name modulename;
+ let inputfile = Pparse.preprocess sourcefile in
+ let env = Compmisc.initial_env() in
+ let ast = Pparse.file ppf inputfile Parse.implementation Config.ast_impl_magic_number in
+ let (str, _coerc) = Typemod.type_implementation sourcefile file modulename env ast in
+ let sg = structure str in
+ Format.printf "%a@." Pprintast.signature sg
+
+let () =
+ mli_of_ml Format.err_formatter Sys.argv.(1)
+
diff --git a/experimental/frisch/ppx_builder.ml b/experimental/frisch/ppx_builder.ml
new file mode 100644
index 0000000000..cb866df8e2
--- /dev/null
+++ b/experimental/frisch/ppx_builder.ml
@@ -0,0 +1,100 @@
+(*
+ A toy -ppx rewriter which illustrates code generation based on type
+ declarations. Here, we create builder function from record and sum
+ type declarations annotated with attribute [@@builder]: one function
+ per record type, one function per constructor of a sum type.
+
+ We recognize some special attributes on record fields (or their associated
+ type) and on constructor argument types:
+
+ - [@label id]: specify a label for the parameter of the builder function
+ (for records, it is set automatically from the label name
+ but it can be overridden).
+
+ - [@opt]: the parameter is optional (this assume that the field/argument
+ has an option type).
+
+ - [@default expr]: the parameter is optional, with a default value
+ (cannot be used with [@opt]).
+*)
+
+module Main : sig end = struct
+ open Asttypes
+ open! Location
+ open Parsetree
+ open Ast_helper
+ open Ast_helper.Convenience
+
+ let fatal loc s =
+ Location.print_error Format.err_formatter loc;
+ prerr_endline s;
+ exit 2
+
+ let param named name loc attrs =
+ let default = find_attr_expr "default" attrs in
+ let opt = has_attr "opt" attrs in
+ let label =
+ match find_attr_expr "label" attrs with
+ | None -> if named then name else ""
+ | Some e ->
+ match get_lid e with
+ | Some s -> s
+ | None -> fatal e.pexp_loc "'label' attribute must be a string literal"
+ in
+ let label =
+ if default <> None || opt then
+ if label = "" then fatal loc "Optional arguments must be named" else "?" ^ label
+ else label
+ in
+ if default <> None && opt then fatal loc "Cannot have both 'opt' and 'default' attributes";
+ lam ~label ?default (pvar name), (name, evar name)
+
+ let gen_builder tdecl =
+ if has_attr "builder" tdecl.ptype_attributes then
+ match tdecl.ptype_kind with
+ | Ptype_record fields ->
+ let field pld =
+ param true pld.pld_name.txt pld.pld_loc (pld.pld_attributes @ pld.pld_type.ptyp_attributes)
+ in
+ let fields = List.map field fields in
+ let body = lam (punit()) (record (List.map snd fields)) in
+ let f = List.fold_right (fun (f, _) k -> f k) fields body in
+ let s = Str.value Nonrecursive [Vb.mk (pvar tdecl.ptype_name.txt) f] in
+ [s]
+ | Ptype_variant constrs ->
+ let constr {pcd_name={txt=name;_}; pcd_args=args; _} =
+ let arg i ty = param false (Printf.sprintf "x%i" i) ty.ptyp_loc ty.ptyp_attributes in
+ let args = List.mapi arg args in
+ let body = lam (punit()) (constr name (List.map (fun (_, (_, e)) -> e) args)) in
+ let f = List.fold_right (fun (f, _) k -> f k) args body in
+ let s = Str.value Nonrecursive [Vb.mk (pvar (tdecl.ptype_name.txt ^ "_" ^ name)) f] in
+ s
+ in
+ List.map constr constrs
+ | _ -> []
+ else
+ []
+
+ let gen_builder tdecl =
+ with_default_loc tdecl.ptype_loc (fun () -> gen_builder tdecl)
+
+ let builder _args =
+ let open Ast_mapper in
+ let super = default_mapper in
+ {super
+ with
+ structure =
+ (fun this l ->
+ List.flatten
+ (List.map
+ (function
+ | {pstr_desc = Pstr_type tdecls; _} as i ->
+ i :: (List.flatten (List.map gen_builder tdecls))
+ | i -> [this.structure_item this i]
+ ) l
+ )
+ )
+ }
+
+ let () = Ast_mapper.run_main builder
+end
diff --git a/experimental/frisch/ppx_matches.ml b/experimental/frisch/ppx_matches.ml
new file mode 100644
index 0000000000..f6d9534717
--- /dev/null
+++ b/experimental/frisch/ppx_matches.ml
@@ -0,0 +1,29 @@
+(*
+ Example : List.filter [%matches ? 'a' .. 'z' ] text
+ Output : List.filter (function 'a' .. 'z' -> true | _ -> false) text
+*)
+
+open Asttypes
+open Parsetree
+open Ast_helper
+
+let mapper _args =
+ let open Ast_mapper in
+ let super = default_mapper in
+ {super with
+ expr =
+ (fun this e ->
+ match e.pexp_desc with
+ | Pexp_extension({txt="matches";_}, PPat (p, guard)) ->
+ let p = this.pat this p in
+ let guard = Ast_mapper.map_opt (this.expr this) guard in
+ Exp.function_ ~loc:e.pexp_loc
+ [
+ Exp.case p ?guard (Convenience.constr "true" []);
+ Exp.case (Pat.any ()) (Convenience.constr "false" []);
+ ]
+ | _ -> super.expr this e
+ )
+ }
+
+let () = Ast_mapper.run_main mapper
diff --git a/experimental/frisch/test_builder.ml b/experimental/frisch/test_builder.ml
new file mode 100644
index 0000000000..254273090f
--- /dev/null
+++ b/experimental/frisch/test_builder.ml
@@ -0,0 +1,19 @@
+type t =
+ {
+ x: int;
+ y [@label foo]: int;
+ z [@default 3]: int;
+ } [@@builder]
+
+and s =
+ {
+ a: string;
+ b [@opt]: int option;
+ c: int [@default 2];
+ } [@@builder]
+
+and sum =
+ | A of int
+ | B of string * (string [@label str])
+ | C of (int [@label i] [@default 0]) * (string [@label s] [@default ""])
+ [@@builder]
diff --git a/experimental/frisch/test_copy_typedef.ml b/experimental/frisch/test_copy_typedef.ml
new file mode 100644
index 0000000000..cd774c6915
--- /dev/null
+++ b/experimental/frisch/test_copy_typedef.ml
@@ -0,0 +1,19 @@
+module type S = [%copy_typedef]
+
+module type T = sig
+ type t
+
+ module type M = [%copy_typedef]
+end
+
+module M = struct
+ type t = [%copy_typedef]
+end
+
+type t = [%copy_typedef]
+
+let _x = M.A
+let _y : t = [1; 2]
+
+
+type _loc = [%copy_typedef "../../parsing/location.mli" t]
diff --git a/experimental/frisch/test_copy_typedef.mli b/experimental/frisch/test_copy_typedef.mli
new file mode 100644
index 0000000000..8e137a7d2a
--- /dev/null
+++ b/experimental/frisch/test_copy_typedef.mli
@@ -0,0 +1,20 @@
+module type S = sig
+ type t
+ val x: int
+end
+
+module type T = sig
+ type t
+
+ module type M = sig
+ type t = A | B of t
+ end
+end
+
+module M : sig
+ type t =
+ | A
+ | B of string
+end
+
+type t = int list
diff --git a/experimental/frisch/test_eval.ml b/experimental/frisch/test_eval.ml
new file mode 100644
index 0000000000..c0dfc697f2
--- /dev/null
+++ b/experimental/frisch/test_eval.ml
@@ -0,0 +1,37 @@
+[%%eval.load "unix.cma"]
+
+[%%eval.start both]
+(* This type definition will be evaluated at compile time,
+ but it will be kept in the compiled unit as well. *)
+type t = A | B of string
+[%%eval.stop]
+
+[%%eval.start]
+(* This is going to be executed at compile time only. *)
+let () = print_endline "Now compiling..."
+[%%eval.stop]
+
+let () =
+ begin match [%eval B "x"] with
+ | A -> print_endline "A"
+ | B s -> Printf.printf "B %S\n%!" s
+ end;
+ Printf.printf "Home dir at compile time = %s\n" [%eval Sys.getenv "HOME"];
+ Printf.printf "Word-size = %i\n" [%eval Sys.word_size];
+ Array.iter (Printf.printf "%s;") [%eval Sys.readdir "."];
+ print_endline "";
+ [%eval print_endline "COUCOU"]
+
+let () =
+ let tm = [%eval Unix.(localtime (gettimeofday ()))] in
+ Printf.printf "This program was compiled in %i\n%!" (1900 + tm.Unix.tm_year)
+
+let () =
+ let debug =
+ [%eval try Some (Sys.getenv "DEBUG") with Not_found -> None]
+ in
+ match debug with
+ | Some x -> Printf.printf "DEBUG %s\n%!" x
+ | None -> Printf.printf "NODEBUG\n%!"
+
+
diff --git a/experimental/frisch/test_ifdef.ml b/experimental/frisch/test_ifdef.ml
new file mode 100644
index 0000000000..8a18cdaa5f
--- /dev/null
+++ b/experimental/frisch/test_ifdef.ml
@@ -0,0 +1,25 @@
+type t =
+ | A
+ | DBG [@IFDEF DEBUG] of string
+ | B
+
+[%%IFDEF DEBUG]
+let debug s = prerr_endline ([%GETENV DEBUG] ^ ":" ^ s)
+let x = DBG "xxx"
+[%%ELSE]
+let debug _ = ()
+let x = A
+[%%END]
+
+let f = function
+ | A -> "A"
+ | DBG s when [%IFDEF DEBUG] -> "DEBUG:" ^ s
+ | B -> "B"
+
+let () = debug "ABC"
+
+let () =
+ Printf.printf "compiled by user %s in directory %s\n%!"
+ [%GETENV USER]
+ [%GETENV PWD]
+
diff --git a/experimental/frisch/test_js.ml b/experimental/frisch/test_js.ml
new file mode 100644
index 0000000000..2582a0fba5
--- /dev/null
+++ b/experimental/frisch/test_js.ml
@@ -0,0 +1,22 @@
+module Js = struct
+ type +'a t
+ type +'a gen_prop
+ type +'a meth
+ module Unsafe = struct
+ type any
+ let get (_o : 'a t) (_meth : string) = assert false
+ let set (_o : 'a t) (_meth : string) (_v : 'b) = ()
+ let meth_call (_ : 'a) (_ : string) (_ : any array) : 'b = assert false
+ let inject _ : any = assert false
+ end
+end
+
+let foo1 o =
+ if [%js o.bar] then [%js o.foo1.foo2] else [%js o.foo2]
+
+let foo2 o =
+ [%js o.x <- o.x + 1]
+
+
+let foo3 o a =
+ [%js o#x] + [%js o#y 1 a]
diff --git a/experimental/frisch/test_matches.ml b/experimental/frisch/test_matches.ml
new file mode 100644
index 0000000000..a46a38baf6
--- /dev/null
+++ b/experimental/frisch/test_matches.ml
@@ -0,0 +1,3 @@
+let l = List.filter [%matches ? 'a'..'z'] ['a';'A';'X';'x']
+
+let f = [%matches ? Some i when i >= 0]
diff --git a/experimental/frisch/test_nomli.ml b/experimental/frisch/test_nomli.ml
new file mode 100644
index 0000000000..affa07678d
--- /dev/null
+++ b/experimental/frisch/test_nomli.ml
@@ -0,0 +1,30 @@
+type t = A | B
+ [@@mli]
+
+and s = C | D
+ [@@mli abstract]
+
+
+module X = struct
+ type t = X | Y
+ [@@mli]
+ and s
+
+ let id x = x
+ [@@mli]
+end
+
+module Y : sig type t type s end = struct
+ type t = X | Y
+ type s = A | B
+end
+
+let f x y = x + y
+ [@@mli]
+and g a b = (a, b)
+ [@@mli]
+and h a b = (a, b)
+ [@@mli (h : int -> int -> int * int)]
+
+let (x, y, z) = (1, 2, 3)
+ [@@mli (x : int), (y : int)]
diff --git a/experimental/frisch/testdoc.mli b/experimental/frisch/testdoc.mli
new file mode 100644
index 0000000000..c22307ae1d
--- /dev/null
+++ b/experimental/frisch/testdoc.mli
@@ -0,0 +1,29 @@
+[@@doc section "First section"]
+
+module M : sig
+ [@@doc section "Public definitions"]
+
+ type t =
+ | A
+ | B
+
+ [@@doc section "Internal definitions"]
+
+ val zero: int
+ [@@doc "A very important integer."]
+end
+ [@@doc "This is an internal module."]
+
+val incr: int -> int
+ [@@doc "This function returns the next integer."]
+
+[@@doc section "Second section"]
+
+val decr: int -> int
+ [@@doc "This function returns the previous integer."]
+
+val is_a: M.t -> bool
+ [@@doc "This function checks whether its argument is the A constructor."]
+
+module X: Hashtbl.HashedType
+ [@@doc "An internal module"]
diff --git a/experimental/frisch/unused_exported_values.ml b/experimental/frisch/unused_exported_values.ml
new file mode 100644
index 0000000000..7b2d2f90ed
--- /dev/null
+++ b/experimental/frisch/unused_exported_values.ml
@@ -0,0 +1,63 @@
+(* This tool reports values exported by .mli files but never used in any other module.
+ It assumes that .mli files are compiled with -keep-locs and .ml files with -bin-annot.
+ This can be enforced by setting:
+
+ OCAMLPARAM=bin-annot=1,keep-locs=1,_
+*)
+
+
+open Types
+open Typedtree
+
+let vds = ref [] (* all exported value declarations *)
+let references = Hashtbl.create 256 (* all value references *)
+
+let unit fn =
+ Filename.chop_extension (Filename.basename fn)
+
+let rec collect_export fn = function
+ | Sig_value (_, {Types.val_loc; _}) when not val_loc.Location.loc_ghost ->
+ (* a .cmi file can contain locations from other files.
+ For instance:
+ module M : Set.S with type elt = int
+ will create value definitions whole locations is in set.mli
+ *)
+ if unit fn = unit val_loc.Location.loc_start.Lexing.pos_fname then
+ vds := val_loc :: !vds
+ | Sig_module (_, {Types.md_type=Mty_signature sg; _}, _) -> List.iter (collect_export fn) sg
+ | _ -> ()
+
+let collect_references = object
+ inherit Tast_iter.iter as super
+ method! expression = function
+ | {exp_desc = Texp_ident (_, _, {Types.val_loc; _}); exp_loc} -> Hashtbl.add references val_loc exp_loc
+ | e -> super # expression e
+end
+
+let rec load_file fn =
+ if Filename.check_suffix fn ".cmi"
+ && Sys.file_exists (Filename.chop_suffix fn ".cmi" ^ ".mli") then
+ (* only consider module with an explicit interface *)
+ let open Cmi_format in
+(* Printf.eprintf "Scanning %s\n%!" fn; *)
+ List.iter (collect_export fn) (read_cmi fn).cmi_sign
+ else if Filename.check_suffix fn ".cmt" then
+ let open Cmt_format in
+(* Printf.eprintf "Scanning %s\n%!" fn; *)
+ match read fn with
+ | (_, Some {cmt_annots = Implementation x; _}) -> collect_references # structure x
+ | _ -> () (* todo: support partial_implementation? *)
+ else if (try Sys.is_directory fn with _ -> false) then
+ Array.iter (fun s -> load_file (Filename.concat fn s)) (Sys.readdir fn)
+
+let report loc =
+ if not (Hashtbl.mem references loc) then
+ Format.printf "%a: unused exported value@." Location.print_loc loc
+
+let () =
+ try
+ for i = 1 to Array.length Sys.argv - 1 do load_file Sys.argv.(i) done;
+ List.iter report !vds
+ with exn ->
+ Location.report_exception Format.err_formatter exn;
+ exit 2
diff --git a/experimental/garrigue/.cvsignore b/experimental/garrigue/.cvsignore
new file mode 100644
index 0000000000..4539eb6d09
--- /dev/null
+++ b/experimental/garrigue/.cvsignore
@@ -0,0 +1,2 @@
+*.out
+*.out2
diff --git a/experimental/garrigue/caml_set_oid.diff b/experimental/garrigue/caml_set_oid.diff
new file mode 100644
index 0000000000..aaaa160ef4
--- /dev/null
+++ b/experimental/garrigue/caml_set_oid.diff
@@ -0,0 +1,141 @@
+Index: byterun/intern.c
+===================================================================
+--- byterun/intern.c (revision 11929)
++++ byterun/intern.c (working copy)
+@@ -27,6 +27,7 @@
+ #include "memory.h"
+ #include "mlvalues.h"
+ #include "misc.h"
++#include "obj.h"
+ #include "reverse.h"
+
+ static unsigned char * intern_src;
+@@ -139,6 +140,14 @@
+ dest = (value *) (intern_dest + 1);
+ *intern_dest = Make_header(size, tag, intern_color);
+ intern_dest += 1 + size;
++ /* For objects, we need to freshen the oid */
++ if (tag == Object_tag) {
++ intern_rec(dest++);
++ intern_rec(dest++);
++ caml_set_oid((value)(dest-2));
++ size -= 2;
++ if (size == 0) return;
++ }
+ for(/*nothing*/; size > 1; size--, dest++)
+ intern_rec(dest);
+ goto tailcall;
+Index: byterun/obj.c
+===================================================================
+--- byterun/obj.c (revision 11929)
++++ byterun/obj.c (working copy)
+@@ -25,6 +25,7 @@
+ #include "minor_gc.h"
+ #include "misc.h"
+ #include "mlvalues.h"
++#include "obj.h"
+ #include "prims.h"
+
+ CAMLprim value caml_static_alloc(value size)
+@@ -212,6 +213,16 @@
+ return (tag == Field(meths,li) ? Field (meths, li-1) : 0);
+ }
+
++/* Generate ids on the C side, to avoid races */
++
++CAMLprim value caml_set_oid (value obj)
++{
++ static value last_oid = 1;
++ Field(obj,1) = last_oid;
++ last_oid += 2;
++ return obj;
++}
++
+ /* these two functions might be useful to an hypothetical JIT */
+
+ #ifdef CAML_JIT
+Index: byterun/obj.h
+===================================================================
+--- byterun/obj.h (revision 0)
++++ byterun/obj.h (revision 0)
+@@ -0,0 +1,28 @@
++/***********************************************************************/
++/* */
++/* OCaml */
++/* */
++/* Jacques Garrigue, projet Cristal, INRIA Rocquencourt */
++/* */
++/* Copyright 1996 Institut National de Recherche en Informatique et */
++/* en Automatique. All rights reserved. This file is distributed */
++/* under the terms of the GNU Library General Public License, with */
++/* the special exception on linking described in file ../LICENSE. */
++/* */
++/***********************************************************************/
++
++/* $Id$ */
++
++/* Primitives for the Obj and CamlinternalOO modules */
++
++#ifndef CAML_OBJ_H
++#define CAML_OBJ_H
++
++#include "misc.h"
++#include "mlvalues.h"
++
++/* Set the OID of an object to a fresh value */
++/* returns the same object as result */
++value caml_set_oid (value obj);
++
++#endif /* CAML_OBJ_H */
+Index: stdlib/camlinternalOO.ml
+===================================================================
+--- stdlib/camlinternalOO.ml (revision 11929)
++++ stdlib/camlinternalOO.ml (working copy)
+@@ -15,23 +15,15 @@
+
+ open Obj
+
+-(**** Object representation ****)
++(**** OID handling ****)
+
+-let last_id = ref 0
+-let new_id () =
+- let id = !last_id in incr last_id; id
++external set_oid : t -> t = "caml_set_oid" "noalloc"
+
+-let set_id o id =
+- let id0 = !id in
+- Array.unsafe_set (Obj.magic o : int array) 1 id0;
+- id := id0 + 1
+-
+ (**** Object copy ****)
+
+ let copy o =
+- let o = (Obj.obj (Obj.dup (Obj.repr o))) in
+- set_id o last_id;
+- o
++ let o = Obj.dup (Obj.repr o) in
++ Obj.obj (set_oid o)
+
+ (**** Compression options ****)
+ (* Parameters *)
+@@ -355,8 +347,7 @@
+ let obj = Obj.new_block Obj.object_tag table.size in
+ (* XXX Appel de [caml_modify] *)
+ Obj.set_field obj 0 (Obj.repr table.methods);
+- set_id obj last_id;
+- (Obj.obj obj)
++ Obj.obj (set_oid obj)
+
+ let create_object_opt obj_0 table =
+ if (Obj.magic obj_0 : bool) then obj_0 else begin
+@@ -364,8 +355,7 @@
+ let obj = Obj.new_block Obj.object_tag table.size in
+ (* XXX Appel de [caml_modify] *)
+ Obj.set_field obj 0 (Obj.repr table.methods);
+- set_id obj last_id;
+- (Obj.obj obj)
++ Obj.obj (set_oid obj)
+ end
+
+ let rec iter_f obj =
diff --git a/experimental/garrigue/coerce.diff b/experimental/garrigue/coerce.diff
new file mode 100644
index 0000000000..e90e1fc930
--- /dev/null
+++ b/experimental/garrigue/coerce.diff
@@ -0,0 +1,93 @@
+Index: typing/ctype.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/ctype.ml,v
+retrieving revision 1.201
+diff -u -r1.201 ctype.ml
+--- typing/ctype.ml 5 Apr 2006 02:28:13 -0000 1.201
++++ typing/ctype.ml 17 May 2006 23:48:22 -0000
+@@ -490,6 +490,31 @@
+ unmark_class_signature sign;
+ Some reason
+
++(* Variant for checking principality *)
++
++let rec free_nodes_rec ty =
++ let ty = repr ty in
++ if ty.level >= lowest_level then begin
++ if ty.level <= !current_level then raise Exit;
++ ty.level <- pivot_level - ty.level;
++ begin match ty.desc with
++ Tvar ->
++ raise Exit
++ | Tobject (ty, _) ->
++ free_nodes_rec ty
++ | Tfield (_, _, ty1, ty2) ->
++ free_nodes_rec ty1; free_nodes_rec ty2
++ | Tvariant row ->
++ let row = row_repr row in
++ iter_row free_nodes_rec {row with row_bound = []};
++ if not (static_row row) then free_nodes_rec row.row_more
++ | _ ->
++ iter_type_expr free_nodes_rec ty
++ end;
++ end
++
++let has_free_nodes ty =
++ try free_nodes_rec ty; false with Exit -> true
+
+ (**********************)
+ (* Type duplication *)
+Index: typing/ctype.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/ctype.mli,v
+retrieving revision 1.54
+diff -u -r1.54 ctype.mli
+--- typing/ctype.mli 5 Apr 2006 02:28:13 -0000 1.54
++++ typing/ctype.mli 17 May 2006 23:48:22 -0000
+@@ -228,6 +228,9 @@
+ val closed_class:
+ type_expr list -> class_signature -> closed_class_failure option
+ (* Check whether all type variables are bound *)
++val has_free_nodes: type_expr -> bool
++ (* Check whether there are free type variables, or nodes with
++ level lower or equal to !current_level *)
+
+ val unalias: type_expr -> type_expr
+ val signature_of_class_type: class_type -> class_signature
+Index: typing/typecore.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typecore.ml,v
+retrieving revision 1.181
+diff -u -r1.181 typecore.ml
+--- typing/typecore.ml 16 Apr 2006 23:28:22 -0000 1.181
++++ typing/typecore.ml 17 May 2006 23:48:22 -0000
+@@ -1183,12 +1183,29 @@
+ let (ty', force) =
+ Typetexp.transl_simple_type_delayed env sty'
+ in
++ if !Clflags.principal then begin_def ();
+ let arg = type_exp env sarg in
++ let has_fv =
++ if !Clflags.principal then begin
++ end_def ();
++ let b = has_free_nodes arg.exp_type in
++ Ctype.unify env arg.exp_type (newvar ());
++ b
++ end else
++ free_variables arg.exp_type <> []
++ in
+ begin match arg.exp_desc, !self_coercion, (repr ty').desc with
+ Texp_ident(_, {val_kind=Val_self _}), (path,r) :: _,
+ Tconstr(path',_,_) when Path.same path path' ->
+ r := sexp.pexp_loc :: !r;
+ force ()
++ | _ when not has_fv ->
++ begin try
++ let force' = subtype env arg.exp_type ty' in
++ force (); force' ()
++ with Subtype (tr1, tr2) ->
++ raise(Error(sexp.pexp_loc, Not_subtype(tr1, tr2)))
++ end
+ | _ ->
+ let ty, b = enlarge_type env ty' in
+ force ();
diff --git a/experimental/garrigue/countchars.ml b/experimental/garrigue/countchars.ml
new file mode 100644
index 0000000000..0f14d2fee8
--- /dev/null
+++ b/experimental/garrigue/countchars.ml
@@ -0,0 +1,16 @@
+let rec long_lines name n ic =
+ let l = input_line ic in
+ if String.length l > 80 then Printf.printf "%s: %d\n%!" name n;
+ long_lines name (n+1) ic
+
+let process_file name =
+ try
+ let ic = open_in name in
+ try long_lines name 1 ic
+ with End_of_file -> close_in ic
+ with _ ->()
+
+let () =
+ for i = 1 to Array.length Sys.argv - 1 do
+ process_file Sys.argv.(i)
+ done
diff --git a/experimental/garrigue/dirs_multimatch b/experimental/garrigue/dirs_multimatch
new file mode 100644
index 0000000000..3e44400046
--- /dev/null
+++ b/experimental/garrigue/dirs_multimatch
@@ -0,0 +1 @@
+parsing typing bytecomp driver toplevel
diff --git a/experimental/garrigue/dirs_poly b/experimental/garrigue/dirs_poly
new file mode 100644
index 0000000000..60cb39f170
--- /dev/null
+++ b/experimental/garrigue/dirs_poly
@@ -0,0 +1 @@
+bytecomp byterun driver parsing stdlib tools toplevel typing utils
diff --git a/experimental/garrigue/fixedtypes.ml b/experimental/garrigue/fixedtypes.ml
new file mode 100644
index 0000000000..aa6e530e78
--- /dev/null
+++ b/experimental/garrigue/fixedtypes.ml
@@ -0,0 +1,77 @@
+(* cvs update -r fixedtypes parsing typing *)
+
+(* recursive types *)
+class c = object (self) method m = 1 method s = self end
+module type S = sig type t = private #c end;;
+
+module M : S = struct type t = c end
+module type S' = S with type t = c;;
+
+class d = object inherit c method n = 2 end
+module type S2 = S with type t = private #d;;
+module M2 : S = struct type t = d end;;
+module M3 : S = struct type t = private #d end;;
+
+module T1 = struct
+ type ('a,'b) a = [`A of 'a | `B of 'b]
+ type ('a,'b) b = [`Z | ('a,'b) a]
+end
+module type T2 = sig
+ type a and b
+ val evala : a -> int
+ val evalb : b -> int
+end
+module type T3 = sig
+ type a0 = private [> (a0,b0) T1.a]
+ and b0 = private [> (a0,b0) T1.b]
+end
+module type T4 = sig
+ include T3
+ include T2 with type a = a0 and type b = b0
+end
+module F(X:T4) = struct
+ type a = X.a and b = X.b
+ let a = X.evala (`B `Z)
+ let b = X.evalb (`A(`B `Z))
+ let a2b (x : a) : b = `A x
+ let b2a (x : b) : a = `B x
+end
+module M4 = struct
+ type a = [`A of a | `B of b | `ZA]
+ and b = [`A of a | `B of b | `Z]
+ type a0 = a
+ type b0 = b
+ let rec eval0 = function
+ `A a -> evala a
+ | `B b -> evalb b
+ and evala : a -> int = function
+ #T1.a as x -> 1 + eval0 x
+ | `ZA -> 3
+ and evalb : b -> int = function
+ #T1.a as x -> 1 + eval0 x
+ | `Z -> 7
+end
+module M5 = F(M4)
+
+module M6 : sig
+ class ci : int ->
+ object
+ val x : int
+ method x : int
+ method move : int -> unit
+ end
+ type c = private #ci
+ val create : int -> c
+end = struct
+ class ci x = object
+ val mutable x : int = x
+ method x = x
+ method move d = x <- x+d
+ end
+ type c = ci
+ let create = new ci
+end
+let f (x : M6.c) = x#move 3; x#x;;
+
+module M : sig type t = private [> `A of bool] end =
+ struct type t = [`A of int] end
diff --git a/experimental/garrigue/gadt-escape-check.diff b/experimental/garrigue/gadt-escape-check.diff
new file mode 100644
index 0000000000..3e4a44e2b2
--- /dev/null
+++ b/experimental/garrigue/gadt-escape-check.diff
@@ -0,0 +1,519 @@
+Index: typing/env.ml
+===================================================================
+--- typing/env.ml (revision 11214)
++++ typing/env.ml (working copy)
+@@ -20,6 +20,7 @@
+ open Longident
+ open Path
+ open Types
++open Btype
+
+
+ type error =
+@@ -56,7 +57,7 @@
+ cltypes: (Path.t * cltype_declaration) Ident.tbl;
+ summary: summary;
+ local_constraints: bool;
+- level_map: (int * int) list;
++ gadt_instances: (int * TypeSet.t ref) list;
+ }
+
+ and module_components = module_components_repr Lazy.t
+@@ -96,7 +97,7 @@
+ modules = Ident.empty; modtypes = Ident.empty;
+ components = Ident.empty; classes = Ident.empty;
+ cltypes = Ident.empty;
+- summary = Env_empty; local_constraints = false; level_map = [] }
++ summary = Env_empty; local_constraints = false; gadt_instances = [] }
+
+ let diff_keys is_local tbl1 tbl2 =
+ let keys2 = Ident.keys tbl2 in
+@@ -286,13 +287,14 @@
+ (* the level is changed when updating newtype definitions *)
+ if !Clflags.principal then begin
+ match level, decl.type_newtype_level with
+- Some level, Some def_level when level < def_level -> raise Not_found
++ Some level, Some (_, exp_level) when level < exp_level -> raise Not_found
+ | _ -> ()
+ end;
+ match decl.type_manifest with
+ | Some body when decl.type_private = Public
+ || decl.type_kind <> Type_abstract
+- || Btype.has_constr_row body -> (decl.type_params, body)
++ || Btype.has_constr_row body ->
++ (decl.type_params, body, may_map snd decl.type_newtype_level)
+ (* The manifest type of Private abstract data types without
+ private row are still considered unknown to the type system.
+ Hence, this case is caught by the following clause that also handles
+@@ -308,7 +310,7 @@
+ match decl.type_manifest with
+ (* The manifest type of Private abstract data types can still get
+ an approximation using their manifest type. *)
+- | Some body -> (decl.type_params, body)
++ | Some body -> (decl.type_params, body, may_map snd decl.type_newtype_level)
+ | _ -> raise Not_found
+
+ let find_modtype_expansion path env =
+@@ -453,32 +455,42 @@
+ and lookup_cltype =
+ lookup (fun env -> env.cltypes) (fun sc -> sc.comp_cltypes)
+
+-(* Level handling *)
++(* GADT instance tracking *)
+
+-(* The level map is a list of pairs describing separate segments (lv,lv'),
+- lv < lv', organized in decreasing order.
+- The definition level is obtained by mapping a level in a segment to the
+- high limit of this segment.
+- The definition level of a newtype should be greater or equal to
+- the highest level of the newtypes in its manifest type.
+- *)
++let add_gadt_instance_level lv env =
++ {env with
++ gadt_instances = (lv, ref TypeSet.empty) :: env.gadt_instances}
+
+-let rec map_level lv = function
+- | [] -> lv
+- | (lv1, lv2) :: rem ->
+- if lv > lv2 then lv else
+- if lv >= lv1 then lv2 else map_level lv rem
++let is_Tlink = function {desc = Tlink _} -> true | _ -> false
+
+-let map_newtype_level env lv = map_level lv env.level_map
++let gadt_instance_level env t =
++ let rec find_instance = function
++ [] -> None
++ | (lv, r) :: rem ->
++ if TypeSet.exists is_Tlink !r then
++ r := TypeSet.fold (fun ty -> TypeSet.add (repr ty)) !r TypeSet.empty;
++ if TypeSet.mem t !r then Some lv else find_instance rem
++ in find_instance env.gadt_instances
+
+-(* precondition: lv < lv' *)
+-let rec add_level lv lv' = function
+- | [] -> [lv, lv']
+- | (lv1, lv2) :: rem as l ->
+- if lv2 < lv then (lv, lv') :: l else
+- if lv' < lv1 then (lv1, lv2) :: add_level lv lv' rem
+- else add_level (max lv lv1) (min lv' lv2) rem
++let add_gadt_instances env lv tl =
++ let r =
++ try List.assoc lv env.gadt_instances with Not_found -> assert false in
++ r := List.fold_right TypeSet.add tl !r
+
++(* Only use this after expand_head! *)
++let add_gadt_instance_chain env lv t =
++ let r =
++ try List.assoc lv env.gadt_instances with Not_found -> assert false in
++ let rec add_instance t =
++ let t = repr t in
++ if not (TypeSet.mem t !r) then begin
++ r := TypeSet.add t !r;
++ match t.desc with
++ Tconstr (p, _, memo) ->
++ may add_instance (find_expans Private p !memo)
++ | _ -> ()
++ end
++ in add_instance t
+
+ (* Expand manifest module type names at the top of the given module type *)
+
+@@ -497,7 +509,7 @@
+ let constructors_of_type ty_path decl =
+ let handle_variants cstrs =
+ Datarepr.constructor_descrs
+- (Btype.newgenty (Tconstr(ty_path, decl.type_params, ref Mnil)))
++ (newgenty (Tconstr(ty_path, decl.type_params, ref Mnil)))
+ cstrs decl.type_private
+ in
+ match decl.type_kind with
+@@ -510,7 +522,7 @@
+ match decl.type_kind with
+ Type_record(labels, rep) ->
+ Datarepr.label_descrs
+- (Btype.newgenty (Tconstr(ty_path, decl.type_params, ref Mnil)))
++ (newgenty (Tconstr(ty_path, decl.type_params, ref Mnil)))
+ labels rep decl.type_private
+ | Type_variant _ | Type_abstract -> []
+
+@@ -773,14 +785,13 @@
+ and add_cltype id ty env =
+ store_cltype id (Pident id) ty env
+
+-let add_local_constraint id info mlv env =
++let add_local_constraint id info elv env =
+ match info with
+- {type_manifest = Some ty; type_newtype_level = Some lv} ->
+- (* use the newtype level for this definition, lv is the old one *)
+- let env = add_type id {info with type_newtype_level = Some mlv} env in
+- let level_map =
+- if lv < mlv then add_level lv mlv env.level_map else env.level_map in
+- { env with local_constraints = true; level_map = level_map }
++ {type_manifest = Some ty; type_newtype_level = Some (lv, _)} ->
++ (* elv is the expansion level, lv is the definition level *)
++ let env =
++ add_type id {info with type_newtype_level = Some (lv, elv)} env in
++ { env with local_constraints = true }
+ | _ -> assert false
+
+ (* Insertion of bindings by name *)
+Index: typing/typecore.ml
+===================================================================
+--- typing/typecore.ml (revision 11214)
++++ typing/typecore.ml (working copy)
+@@ -1989,6 +1989,7 @@
+ end
+ | Pexp_newtype(name, sbody) ->
+ (* Create a fake abstract type declaration for name. *)
++ let level = get_current_level () in
+ let decl = {
+ type_params = [];
+ type_arity = 0;
+@@ -1996,7 +1997,7 @@
+ type_private = Public;
+ type_manifest = None;
+ type_variance = [];
+- type_newtype_level = Some (get_current_level ());
++ type_newtype_level = Some (level, level);
+ }
+ in
+ let ty = newvar () in
+@@ -2421,6 +2422,7 @@
+ begin_def ();
+ Ident.set_current_time (get_current_level ());
+ let lev = Ident.current_time () in
++ let env = Env.add_gadt_instance_level lev env in
+ Ctype.init_def (lev+1000);
+ if !Clflags.principal then begin_def (); (* propagation of the argument *)
+ let ty_arg' = newvar () in
+Index: typing/typedecl.ml
+===================================================================
+--- typing/typedecl.ml (revision 11214)
++++ typing/typedecl.ml (working copy)
+@@ -404,7 +404,7 @@
+ else if to_check path' && not (List.mem path' prev_exp) then begin
+ try
+ (* Attempt expansion *)
+- let (params0, body0) = Env.find_type_expansion path' env in
++ let (params0, body0, _) = Env.find_type_expansion path' env in
+ let (params, body) =
+ Ctype.instance_parameterized_type params0 body0 in
+ begin
+Index: typing/types.mli
+===================================================================
+--- typing/types.mli (revision 11214)
++++ typing/types.mli (working copy)
+@@ -144,9 +144,9 @@
+ type_manifest: type_expr option;
+ type_variance: (bool * bool * bool) list;
+ (* covariant, contravariant, weakly contravariant *)
+- type_newtype_level: int option }
++ type_newtype_level: (int * int) option }
++ (* definition level * expansion level *)
+
+-
+ and type_kind =
+ Type_abstract
+ | Type_record of
+Index: typing/ctype.ml
+===================================================================
+--- typing/ctype.ml (revision 11214)
++++ typing/ctype.ml (working copy)
+@@ -470,7 +470,7 @@
+ free_variables := (ty, real) :: !free_variables
+ | Tconstr (path, tl, _), Some env ->
+ begin try
+- let (_, body) = Env.find_type_expansion path env in
++ let (_, body, _) = Env.find_type_expansion path env in
+ if (repr body).level <> generic_level then
+ free_variables := (ty, real) :: !free_variables
+ with Not_found -> ()
+@@ -687,7 +687,7 @@
+ try
+ match (Env.find_type p env).type_newtype_level with
+ | None -> Path.binding_time p
+- | Some x -> x
++ | Some (x, _) -> x
+ with
+ | _ ->
+ (* no newtypes in predef *)
+@@ -696,9 +696,13 @@
+ let rec update_level env level ty =
+ let ty = repr ty in
+ if ty.level > level then begin
++ if !Clflags.principal && Env.has_local_constraints env then begin
++ match Env.gadt_instance_level env ty with
++ Some lv -> if level < lv then raise (Unify [(ty, newvar2 level)])
++ | None -> ()
++ end;
+ match ty.desc with
+- Tconstr(p, tl, abbrev)
+- when level < Env.map_newtype_level env (get_level env p) ->
++ Tconstr(p, tl, abbrev) when level < get_level env p ->
+ (* Try first to replace an abbreviation by its expansion. *)
+ begin try
+ (* if is_newtype env p then raise Cannot_expand; *)
+@@ -1025,7 +1029,7 @@
+ | Some (env, newtype_lev) ->
+ let existentials = List.map copy cstr.cstr_existentials in
+ let process existential =
+- let decl = new_declaration (Some newtype_lev) None in
++ let decl = new_declaration (Some (newtype_lev, newtype_lev)) None in
+ let (id, new_env) =
+ Env.enter_type (get_new_abstract_name ()) decl !env in
+ env := new_env;
+@@ -1271,7 +1275,7 @@
+ end;
+ ty
+ | None ->
+- let (params, body) =
++ let (params, body, lv) =
+ try find_type_expansion level path env with Not_found ->
+ raise Cannot_expand
+ in
+@@ -1284,6 +1288,15 @@
+ ty.desc <- Tvariant { row with row_name = Some (path, args) }
+ | _ -> ()
+ end;
++ (* For gadts, remember type as non exportable *)
++ if !Clflags.principal then begin
++ match lv with
++ Some lv -> Env.add_gadt_instances env lv [ty; ty']
++ | None ->
++ match Env.gadt_instance_level env ty with
++ Some lv -> Env.add_gadt_instances env lv [ty']
++ | None -> ()
++ end;
+ ty'
+ end
+ | _ ->
+@@ -1306,15 +1319,7 @@
+ let try_expand_once env ty =
+ let ty = repr ty in
+ match ty.desc with
+- Tconstr (p, _, _) ->
+- let ty' = repr (expand_abbrev env ty) in
+- if !Clflags.principal then begin
+- match (Env.find_type p env).type_newtype_level with
+- Some lv when ty.level < Env.map_newtype_level env lv ->
+- link_type ty ty'
+- | _ -> ()
+- end;
+- ty'
++ Tconstr (p, _, _) -> repr (expand_abbrev env ty)
+ | _ -> raise Cannot_expand
+
+ let _ = forward_try_expand_once := try_expand_once
+@@ -1324,11 +1329,16 @@
+ May raise Unify, if a recursion was hidden in the type. *)
+ let rec try_expand_head env ty =
+ let ty' = try_expand_once env ty in
+- begin try
+- try_expand_head env ty'
+- with Cannot_expand ->
+- ty'
+- end
++ let ty'' =
++ try try_expand_head env ty'
++ with Cannot_expand -> ty'
++ in
++ if !Clflags.principal then begin
++ match Env.gadt_instance_level env ty'' with
++ None -> ()
++ | Some lv -> Env.add_gadt_instance_chain env lv ty
++ end;
++ ty''
+
+ (* Expand once the head of a type *)
+ let expand_head_once env ty =
+@@ -1405,7 +1415,7 @@
+ *)
+ let generic_abbrev env path =
+ try
+- let (_, body) = Env.find_type_expansion path env in
++ let (_, body, _) = Env.find_type_expansion path env in
+ (repr body).level = generic_level
+ with
+ Not_found ->
+@@ -1742,7 +1752,7 @@
+ let reify env t =
+ let newtype_level = get_newtype_level () in
+ let create_fresh_constr lev row =
+- let decl = new_declaration (Some (newtype_level)) None in
++ let decl = new_declaration (Some (newtype_level, newtype_level)) None in
+ let name =
+ let name = get_new_abstract_name () in
+ if row then name ^ "#row" else name
+@@ -2065,7 +2075,7 @@
+ update_level !env t1.level t2;
+ link_type t1 t2
+ | (Tconstr (p1, [], a1), Tconstr (p2, [], a2))
+- when Path.same p1 p2 && actual_mode !env = Old
++ when Path.same p1 p2 (* && actual_mode !env = Old *)
+ (* This optimization assumes that t1 does not expand to t2
+ (and conversely), so we fall back to the general case
+ when any of the types has a cached expansion. *)
+@@ -2091,6 +2101,15 @@
+ if unify_eq !env t1' t2' then () else
+
+ let t1 = repr t1 and t2 = repr t2 in
++ if !Clflags.principal then begin
++ match Env.gadt_instance_level !env t1',Env.gadt_instance_level !env t2' with
++ Some lv1, Some lv2 ->
++ if lv1 > lv2 then Env.add_gadt_instance_chain !env lv1 t2 else
++ if lv2 > lv2 then Env.add_gadt_instance_chain !env lv2 t1
++ | Some lv1, None -> Env.add_gadt_instance_chain !env lv1 t2
++ | None, Some lv2 -> Env.add_gadt_instance_chain !env lv2 t1
++ | None, None -> ()
++ end;
+ if unify_eq !env t1 t1' || not (unify_eq !env t2 t2') then
+ unify3 env t1 t1' t2 t2'
+ else
+Index: typing/env.mli
+===================================================================
+--- typing/env.mli (revision 11214)
++++ typing/env.mli (working copy)
+@@ -33,14 +33,19 @@
+ val find_cltype: Path.t -> t -> cltype_declaration
+
+ val find_type_expansion:
+- ?use_local:bool -> ?level:int -> Path.t -> t -> type_expr list * type_expr
+-val find_type_expansion_opt: Path.t -> t -> type_expr list * type_expr
++ ?use_local:bool -> ?level:int -> Path.t -> t ->
++ type_expr list * type_expr * int option
++val find_type_expansion_opt:
++ Path.t -> t -> type_expr list * type_expr * int option
+ (* Find the manifest type information associated to a type for the sake
+ of the compiler's type-based optimisations. *)
+ val find_modtype_expansion: Path.t -> t -> Types.module_type
+
+ val has_local_constraints: t -> bool
+-val map_newtype_level: t -> int -> int
++val add_gadt_instance_level: int -> t -> t
++val gadt_instance_level: t -> type_expr -> int option
++val add_gadt_instances: t -> int -> type_expr list -> unit
++val add_gadt_instance_chain: t -> int -> type_expr -> unit
+
+ (* Lookup by long identifiers *)
+
+Index: typing/types.ml
+===================================================================
+--- typing/types.ml (revision 11214)
++++ typing/types.ml (working copy)
+@@ -146,8 +146,8 @@
+ type_private: private_flag;
+ type_manifest: type_expr option;
+ type_variance: (bool * bool * bool) list;
+- type_newtype_level: int option }
+ (* covariant, contravariant, weakly contravariant *)
++ type_newtype_level: (int * int) option }
+
+ and type_kind =
+ Type_abstract
+Index: testsuite/tests/typing-gadts/test.ml
+===================================================================
+--- testsuite/tests/typing-gadts/test.ml (revision 11214)
++++ testsuite/tests/typing-gadts/test.ml (working copy)
+@@ -159,17 +159,21 @@
+
+ let ky x y = ignore (x = y); x ;;
+
++let test : type a. a t -> a =
++ function Int -> ky (1 : a) 1
++;;
++
+ let test : type a. a t -> a = fun x ->
+- let r = match x with Int -> ky (1 : a) 1
++ let r = match x with Int -> ky (1 : a) 1 (* fails *)
+ in r
+ ;;
+ let test : type a. a t -> a = fun x ->
+- let r = match x with Int -> ky 1 (1 : a)
++ let r = match x with Int -> ky 1 (1 : a) (* fails *)
+ in r
+ ;;
+ let test : type a. a t -> a = fun x ->
+- let r = match x with Int -> (1 : a)
+- in r (* fails too *)
++ let r = match x with Int -> (1 : a) (* ok! *)
++ in r
+ ;;
+ let test : type a. a t -> a = fun x ->
+ let r : a = match x with Int -> 1
+@@ -178,7 +182,7 @@
+ let test2 : type a. a t -> a option = fun x ->
+ let r = ref None in
+ begin match x with Int -> r := Some (1 : a) end;
+- !r (* normalized to int option *)
++ !r (* ok *)
+ ;;
+ let test2 : type a. a t -> a option = fun x ->
+ let r : a option ref = ref None in
+@@ -190,19 +194,19 @@
+ let u = ref None in
+ begin match x with Int -> r := Some 1; u := !r end;
+ !u
+-;; (* fail *)
++;; (* ok (u non-ambiguous) *)
+ let test2 : type a. a t -> a option = fun x ->
+ let r : a option ref = ref None in
+ let u = ref None in
+ begin match x with Int -> u := Some 1; r := !u end;
+ !u
+-;; (* fail *)
++;; (* fails because u : (int | a) option ref *)
+ let test2 : type a. a t -> a option = fun x ->
+ let u = ref None in
+ let r : a option ref = ref None in
+ begin match x with Int -> r := Some 1; u := !r end;
+ !u
+-;; (* fail *)
++;; (* ok *)
+ let test2 : type a. a t -> a option = fun x ->
+ let u = ref None in
+ let a =
+@@ -210,32 +214,32 @@
+ begin match x with Int -> r := Some 1; u := !r end;
+ !u
+ in a
+-;; (* fail *)
++;; (* ok *)
+
+ (* Effect of external consraints *)
+
+ let f (type a) (x : a t) y =
+ ignore (y : a);
+- let r = match x with Int -> (y : a) in (* fails *)
++ let r = match x with Int -> (y : a) in (* ok *)
+ r
+ ;;
+ let f (type a) (x : a t) y =
+ let r = match x with Int -> (y : a) in
+- ignore (y : a); (* fails *)
++ ignore (y : a); (* ok *)
+ r
+ ;;
+ let f (type a) (x : a t) y =
+ ignore (y : a);
+- let r = match x with Int -> y in
++ let r = match x with Int -> y in (* ok *)
+ r
+ ;;
+ let f (type a) (x : a t) y =
+ let r = match x with Int -> y in
+- ignore (y : a);
++ ignore (y : a); (* ok *)
+ r
+ ;;
+ let f (type a) (x : a t) (y : a) =
+- match x with Int -> y (* should return an int! *)
++ match x with Int -> y (* returns 'a *)
+ ;;
+
+ (* Pattern matching *)
+@@ -307,4 +311,4 @@
+ | {left=TE TC; right=D [|1.0|]} -> 14
+ | {left=TA; right=D 0} -> -1
+ | {left=TA; right=D z} -> z
+-;; (* warn *)
++;; (* ok *)
diff --git a/experimental/garrigue/generative-functors.diff b/experimental/garrigue/generative-functors.diff
new file mode 100644
index 0000000000..c7786d11b6
--- /dev/null
+++ b/experimental/garrigue/generative-functors.diff
@@ -0,0 +1,1008 @@
+Index: boot/ocamlc
+===================================================================
+Cannot display: file marked as a binary type.
+svn:mime-type = application/octet-stream
+Index: boot/ocamldep
+===================================================================
+Cannot display: file marked as a binary type.
+svn:mime-type = application/octet-stream
+Index: boot/ocamllex
+===================================================================
+Cannot display: file marked as a binary type.
+svn:mime-type = application/octet-stream
+Index: camlp4/Camlp4/Struct/Camlp4Ast2OCamlAst.ml
+===================================================================
+--- camlp4/Camlp4/Struct/Camlp4Ast2OCamlAst.ml (revision 14301)
++++ camlp4/Camlp4/Struct/Camlp4Ast2OCamlAst.ml (working copy)
+@@ -979,7 +979,7 @@
+ [ <:module_type@loc<>> -> error loc "abstract/nil module type not allowed here"
+ | <:module_type@loc< $id:i$ >> -> mkmty loc (Pmty_ident (long_uident i))
+ | <:module_type@loc< functor ($n$ : $nt$) -> $mt$ >> ->
+- mkmty loc (Pmty_functor (with_loc n loc) (module_type nt) (module_type mt))
++ mkmty loc (Pmty_functor (with_loc n loc) (Some (module_type nt)) (module_type mt))
+ | <:module_type@loc< '$_$ >> -> error loc "module type variable not allowed here"
+ | <:module_type@loc< sig $sl$ end >> ->
+ mkmty loc (Pmty_signature (sig_item sl []))
+@@ -1051,7 +1051,7 @@
+ | <:module_expr@loc< $me1$ $me2$ >> ->
+ mkmod loc (Pmod_apply (module_expr me1) (module_expr me2))
+ | <:module_expr@loc< functor ($n$ : $mt$) -> $me$ >> ->
+- mkmod loc (Pmod_functor (with_loc n loc) (module_type mt) (module_expr me))
++ mkmod loc (Pmod_functor (with_loc n loc) (Some (module_type mt)) (module_expr me))
+ | <:module_expr@loc< struct $sl$ end >> ->
+ mkmod loc (Pmod_structure (str_item sl []))
+ | <:module_expr@loc< ($me$ : $mt$) >> ->
+Index: camlp4/Camlp4Top/Rprint.ml
+===================================================================
+--- camlp4/Camlp4Top/Rprint.ml (revision 14301)
++++ camlp4/Camlp4Top/Rprint.ml (working copy)
+@@ -362,7 +362,10 @@
+ | Omty_signature sg ->
+ fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]"
+ Toploop.print_out_signature.val sg
+- | Omty_functor name mty_arg mty_res ->
++ | Omty_functor _ None mty_res ->
++ fprintf ppf "@[<2>functor@ () ->@ %a@]"
++ print_out_module_type mty_res
++ | Omty_functor name (Some mty_arg) mty_res ->
+ fprintf ppf "@[<2>functor@ (%s : %a) ->@ %a@]" name
+ print_out_module_type mty_arg print_out_module_type mty_res
+ | Omty_abstract -> () ]
+Index: camlp4/boot/Camlp4.ml
+===================================================================
+--- camlp4/boot/Camlp4.ml (revision 14301)
++++ camlp4/boot/Camlp4.ml (working copy)
+@@ -15633,7 +15633,7 @@
+ | Ast.MtId (loc, i) -> mkmty loc (Pmty_ident (long_uident i))
+ | Ast.MtFun (loc, n, nt, mt) ->
+ mkmty loc
+- (Pmty_functor ((with_loc n loc), (module_type nt),
++ (Pmty_functor ((with_loc n loc), Some (module_type nt),
+ (module_type mt)))
+ | Ast.MtQuo (loc, _) ->
+ error loc "module type variable not allowed here"
+@@ -15775,7 +15775,7 @@
+ (Pmod_apply ((module_expr me1), (module_expr me2)))
+ | Ast.MeFun (loc, n, mt, me) ->
+ mkmod loc
+- (Pmod_functor ((with_loc n loc), (module_type mt),
++ (Pmod_functor ((with_loc n loc), Some (module_type mt),
+ (module_expr me)))
+ | Ast.MeStr (loc, sl) ->
+ mkmod loc (Pmod_structure (str_item sl []))
+Index: ocamldoc/odoc_ast.ml
+===================================================================
+--- ocamldoc/odoc_ast.ml (revision 14301)
++++ ocamldoc/odoc_ast.ml (working copy)
+@@ -1606,18 +1606,25 @@
+
+ | (Parsetree.Pmod_functor (_, pmodule_type, p_module_expr2),
+ Typedtree.Tmod_functor (ident, _, mtyp, tt_module_expr2)) ->
+- let loc_start = pmodule_type.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
+- let loc_end = pmodule_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
++ let loc = match pmodule_type with None -> Location.none
++ | Some pmty -> pmty.Parsetree.pmty_loc in
++ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
++ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let mp_type_code = get_string_of_file loc_start loc_end in
+ print_DEBUG (Printf.sprintf "mp_type_code=%s" mp_type_code);
+ let mp_name = Name.from_ident ident in
+- let mp_kind = Sig.analyse_module_type_kind env
+- current_module_name pmodule_type mtyp.mty_type
++ let mp_kind =
++ match pmodule_type, mtyp with
++ Some pmty, Some mty ->
++ Sig.analyse_module_type_kind env current_module_name pmty
++ mty.mty_type
++ | _ -> Module_type_struct []
+ in
+ let param =
+ {
+ mp_name = mp_name ;
+- mp_type = Odoc_env.subst_module_type env mtyp.mty_type ;
++ mp_type = Misc.may_map
++ (fun m -> Odoc_env.subst_module_type env m.mty_type) mtyp ;
+ mp_type_code = mp_type_code ;
+ mp_kind = mp_kind ;
+ }
+Index: ocamldoc/odoc_env.ml
+===================================================================
+--- ocamldoc/odoc_env.ml (revision 14301)
++++ ocamldoc/odoc_env.ml (working copy)
+@@ -223,7 +223,7 @@
+ | Types.Mty_signature _ ->
+ t
+ | Types.Mty_functor (id, mt1, mt2) ->
+- Types.Mty_functor (id, iter mt1, iter mt2)
++ Types.Mty_functor (id, Misc.may_map iter mt1, iter mt2)
+ in
+ iter t
+
+Index: ocamldoc/odoc_html.ml
+===================================================================
+--- ocamldoc/odoc_html.ml (revision 14301)
++++ ocamldoc/odoc_html.ml (working copy)
+@@ -1384,7 +1384,8 @@
+
+ (** Print html code to display the type of a module parameter.. *)
+ method html_of_module_parameter_type b m_name p =
+- self#html_of_module_type b m_name ~code: p.mp_type_code p.mp_type
++ match p.mp_type with None -> bs b "<code>()</code>"
++ | Some mty -> self#html_of_module_type b m_name ~code: p.mp_type_code mty
+
+ (** Generate a file containing the module type in the given file name. *)
+ method output_module_type in_title file mtyp =
+Index: ocamldoc/odoc_info.mli
+===================================================================
+--- ocamldoc/odoc_info.mli (revision 14301)
++++ ocamldoc/odoc_info.mli (working copy)
+@@ -434,7 +434,7 @@
+
+ and module_parameter = Odoc_module.module_parameter = {
+ mp_name : string ; (** the name *)
+- mp_type : Types.module_type ; (** the type *)
++ mp_type : Types.module_type option ; (** the type *)
+ mp_type_code : string ; (** the original code *)
+ mp_kind : module_type_kind ; (** the way the parameter was built *)
+ }
+Index: ocamldoc/odoc_man.ml
+===================================================================
+--- ocamldoc/odoc_man.ml (revision 14301)
++++ ocamldoc/odoc_man.ml (working copy)
+@@ -612,7 +612,7 @@
+ (fun (p, desc_opt) ->
+ bs b ".sp\n";
+ bs b ("\""^p.mp_name^"\"\n");
+- self#man_of_module_type b m_name p.mp_type;
++ Misc.may (self#man_of_module_type b m_name) p.mp_type;
+ bs b "\n";
+ (
+ match desc_opt with
+Index: ocamldoc/odoc_module.ml
+===================================================================
+--- ocamldoc/odoc_module.ml (revision 14301)
++++ ocamldoc/odoc_module.ml (working copy)
+@@ -46,7 +46,7 @@
+
+ and module_parameter = {
+ mp_name : string ; (** the name *)
+- mp_type : Types.module_type ; (** the type *)
++ mp_type : Types.module_type option ; (** the type *)
+ mp_type_code : string ; (** the original code *)
+ mp_kind : module_type_kind ; (** the way the parameter was built *)
+ }
+Index: ocamldoc/odoc_print.ml
+===================================================================
+--- ocamldoc/odoc_print.ml (revision 14301)
++++ ocamldoc/odoc_print.ml (working copy)
+@@ -62,7 +62,7 @@
+ | Some s -> raise (Use_code s)
+ )
+ | Types.Mty_functor (id, mt1, mt2) ->
+- Types.Mty_functor (id, iter mt1, iter mt2)
++ Types.Mty_functor (id, Misc.may_map iter mt1, iter mt2)
+ in
+ iter t
+
+Index: ocamldoc/odoc_sig.ml
+===================================================================
+--- ocamldoc/odoc_sig.ml (revision 14301)
++++ ocamldoc/odoc_sig.ml (working copy)
+@@ -1082,19 +1082,26 @@
+
+ | Parsetree.Pmty_functor (_, pmodule_type2, module_type2) ->
+ (
+- let loc_start = pmodule_type2.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
+- let loc_end = pmodule_type2.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
++ let loc = match pmodule_type2 with None -> Location.none
++ | Some pmty -> pmty.Parsetree.pmty_loc in
++ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
++ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let mp_type_code = get_string_of_file loc_start loc_end in
+ print_DEBUG (Printf.sprintf "mp_type_code=%s" mp_type_code);
+ match sig_module_type with
+ Types.Mty_functor (ident, param_module_type, body_module_type) ->
+- let mp_kind = analyse_module_type_kind env
+- current_module_name pmodule_type2 param_module_type
++ let mp_kind =
++ match pmodule_type2, param_module_type with
++ Some pmty, Some mty ->
++ analyse_module_type_kind env current_module_name pmty mty
++ | _ -> Module_type_struct []
+ in
+ let param =
+ {
+ mp_name = Name.from_ident ident ;
+- mp_type = Odoc_env.subst_module_type env param_module_type ;
++ mp_type =
++ Misc.may_map (Odoc_env.subst_module_type env)
++ param_module_type;
+ mp_type_code = mp_type_code ;
+ mp_kind = mp_kind ;
+ }
+@@ -1161,17 +1168,23 @@
+ (
+ match sig_module_type with
+ Types.Mty_functor (ident, param_module_type, body_module_type) ->
+- let loc_start = pmodule_type2.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
+- let loc_end = pmodule_type2.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
++ let loc = match pmodule_type2 with None -> Location.none
++ | Some pmty -> pmty.Parsetree.pmty_loc in
++ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
++ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let mp_type_code = get_string_of_file loc_start loc_end in
+ print_DEBUG (Printf.sprintf "mp_type_code=%s" mp_type_code);
+- let mp_kind = analyse_module_type_kind env
+- current_module_name pmodule_type2 param_module_type
++ let mp_kind =
++ match pmodule_type2, param_module_type with
++ Some pmty, Some mty ->
++ analyse_module_type_kind env current_module_name pmty mty
++ | _ -> Module_type_struct []
+ in
+ let param =
+ {
+ mp_name = Name.from_ident ident ;
+- mp_type = Odoc_env.subst_module_type env param_module_type ;
++ mp_type = Misc.may_map
++ (Odoc_env.subst_module_type env) param_module_type ;
+ mp_type_code = mp_type_code ;
+ mp_kind = mp_kind ;
+ }
+Index: ocamldoc/odoc_to_text.ml
+===================================================================
+--- ocamldoc/odoc_to_text.ml (revision 14301)
++++ ocamldoc/odoc_to_text.ml (working copy)
+@@ -428,8 +428,11 @@
+ List
+ (List.map
+ (fun (p, desc_opt) ->
+- [Code (p.mp_name^" : ")] @
+- (self#text_of_module_type p.mp_type) @
++ begin match p.mp_type with None -> [Raw ""]
++ | Some mty ->
++ [Code (p.mp_name^" : ")] @
++ (self#text_of_module_type mty)
++ end @
+ (match desc_opt with
+ None -> []
+ | Some t -> (Raw " ") :: t)
+Index: parsing/ast_helper.mli
+===================================================================
+--- parsing/ast_helper.mli (revision 14301)
++++ parsing/ast_helper.mli (working copy)
+@@ -145,7 +145,8 @@
+
+ val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_type
+ val signature: ?loc:loc -> ?attrs:attrs -> signature -> module_type
+- val functor_: ?loc:loc -> ?attrs:attrs -> str -> module_type -> module_type -> module_type
++ val functor_: ?loc:loc -> ?attrs:attrs ->
++ str -> module_type option -> module_type -> module_type
+ val with_: ?loc:loc -> ?attrs:attrs -> module_type -> with_constraint list -> module_type
+ val typeof_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_type
+@@ -159,7 +160,8 @@
+
+ val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_expr
+ val structure: ?loc:loc -> ?attrs:attrs -> structure -> module_expr
+- val functor_: ?loc:loc -> ?attrs:attrs -> str -> module_type -> module_expr -> module_expr
++ val functor_: ?loc:loc -> ?attrs:attrs ->
++ str -> module_type option -> module_expr -> module_expr
+ val apply: ?loc:loc -> ?attrs:attrs -> module_expr -> module_expr -> module_expr
+ val constraint_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type -> module_expr
+ val unpack: ?loc:loc -> ?attrs:attrs -> expression -> module_expr
+Index: parsing/ast_mapper.ml
+===================================================================
+--- parsing/ast_mapper.ml (revision 14301)
++++ parsing/ast_mapper.ml (working copy)
+@@ -161,7 +161,8 @@
+ | Pmty_ident s -> ident ~loc ~attrs (map_loc sub s)
+ | Pmty_signature sg -> signature ~loc ~attrs (sub.signature sub sg)
+ | Pmty_functor (s, mt1, mt2) ->
+- functor_ ~loc ~attrs (map_loc sub s) (sub.module_type sub mt1)
++ functor_ ~loc ~attrs (map_loc sub s)
++ (Misc.may_map (sub.module_type sub) mt1)
+ (sub.module_type sub mt2)
+ | Pmty_with (mt, l) ->
+ with_ ~loc ~attrs (sub.module_type sub mt)
+@@ -213,7 +214,8 @@
+ | Pmod_ident x -> ident ~loc ~attrs (map_loc sub x)
+ | Pmod_structure str -> structure ~loc ~attrs (sub.structure sub str)
+ | Pmod_functor (arg, arg_ty, body) ->
+- functor_ ~loc ~attrs (map_loc sub arg) (sub.module_type sub arg_ty)
++ functor_ ~loc ~attrs (map_loc sub arg)
++ (Misc.may_map (sub.module_type sub) arg_ty)
+ (sub.module_expr sub body)
+ | Pmod_apply (m1, m2) ->
+ apply ~loc ~attrs (sub.module_expr sub m1) (sub.module_expr sub m2)
+Index: parsing/parser.mly
+===================================================================
+--- parsing/parser.mly (revision 14301)
++++ parsing/parser.mly (working copy)
+@@ -541,9 +541,13 @@
+ | STRUCT structure error
+ { unclosed "struct" 1 "end" 3 }
+ | FUNCTOR LPAREN UIDENT COLON module_type RPAREN MINUSGREATER module_expr
+- { mkmod(Pmod_functor(mkrhs $3 3, $5, $8)) }
++ { mkmod(Pmod_functor(mkrhs $3 3, Some $5, $8)) }
++ | FUNCTOR LPAREN RPAREN MINUSGREATER module_expr
++ { mkmod(Pmod_functor(mkrhs "()" 3, None, $5)) }
+ | module_expr LPAREN module_expr RPAREN
+ { mkmod(Pmod_apply($1, $3)) }
++ | module_expr LPAREN RPAREN
++ { mkmod(Pmod_apply($1, mkmod (Pmod_structure []))) }
+ | module_expr LPAREN module_expr error
+ { unclosed "(" 2 ")" 4 }
+ | LPAREN module_expr COLON module_type RPAREN
+@@ -640,7 +644,9 @@
+ | COLON module_type EQUAL module_expr
+ { mkmod(Pmod_constraint($4, $2)) }
+ | LPAREN UIDENT COLON module_type RPAREN module_binding_body
+- { mkmod(Pmod_functor(mkrhs $2 2, $4, $6)) }
++ { mkmod(Pmod_functor(mkrhs $2 2, Some $4, $6)) }
++ | LPAREN RPAREN module_binding_body
++ { mkmod(Pmod_functor(mkrhs "()" 1, None, $3)) }
+ ;
+ module_bindings:
+ module_binding { [$1] }
+@@ -662,7 +668,10 @@
+ { unclosed "sig" 1 "end" 3 }
+ | FUNCTOR LPAREN UIDENT COLON module_type RPAREN MINUSGREATER module_type
+ %prec below_WITH
+- { mkmty(Pmty_functor(mkrhs $3 3, $5, $8)) }
++ { mkmty(Pmty_functor(mkrhs $3 3, Some $5, $8)) }
++ | FUNCTOR LPAREN RPAREN MINUSGREATER module_type
++ %prec below_WITH
++ { mkmty(Pmty_functor(mkrhs "()" 2, None, $5)) }
+ | module_type WITH with_constraints
+ { mkmty(Pmty_with($1, List.rev $3)) }
+ | MODULE TYPE OF module_expr %prec below_LBRACKETAT
+@@ -724,7 +733,9 @@
+ COLON module_type
+ { $2 }
+ | LPAREN UIDENT COLON module_type RPAREN module_declaration
+- { mkmty(Pmty_functor(mkrhs $2 2, $4, $6)) }
++ { mkmty(Pmty_functor(mkrhs $2 2, Some $4, $6)) }
++ | LPAREN RPAREN module_declaration
++ { mkmty(Pmty_functor(mkrhs "()" 1, None, $3)) }
+ ;
+ module_rec_declarations:
+ module_rec_declaration { [$1] }
+Index: parsing/parsetree.mli
+===================================================================
+--- parsing/parsetree.mli (revision 14301)
++++ parsing/parsetree.mli (working copy)
+@@ -543,7 +543,7 @@
+ (* S *)
+ | Pmty_signature of signature
+ (* sig ... end *)
+- | Pmty_functor of string loc * module_type * module_type
++ | Pmty_functor of string loc * module_type option * module_type
+ (* functor(X : MT1) -> MT2 *)
+ | Pmty_with of module_type * with_constraint list
+ (* MT with ... *)
+@@ -637,7 +637,7 @@
+ (* X *)
+ | Pmod_structure of structure
+ (* struct ... end *)
+- | Pmod_functor of string loc * module_type * module_expr
++ | Pmod_functor of string loc * module_type option * module_expr
+ (* functor(X : MT1) -> ME *)
+ | Pmod_apply of module_expr * module_expr
+ (* ME1(ME2) *)
+Index: parsing/pprintast.ml
+===================================================================
+--- parsing/pprintast.ml (revision 14301)
++++ parsing/pprintast.ml (working copy)
+@@ -834,7 +834,9 @@
+ | Pmty_signature (s) ->
+ pp f "@[<hv0>@[<hv2>sig@ %a@]@ end@]" (* "@[<hov>sig@ %a@ end@]" *)
+ (self#list self#signature_item ) s (* FIXME wrong indentation*)
+- | Pmty_functor (s, mt1, mt2) ->
++ | Pmty_functor (_, None, mt2) ->
++ pp f "@[<hov2>functor () ->@ %a@]" self#module_type mt2
++ | Pmty_functor (s, Some mt1, mt2) ->
+ pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" s.txt
+ self#module_type mt1 self#module_type mt2
+ | Pmty_with (mt, l) ->
+@@ -940,7 +942,9 @@
+ self#module_type mt
+ | Pmod_ident (li) ->
+ pp f "%a" self#longident_loc li;
+- | Pmod_functor (s, mt, me) ->
++ | Pmod_functor (_, None, me) ->
++ pp f "functor ()@;->@;%a" self#module_expr me
++ | Pmod_functor (s, Some mt, me) ->
+ pp f "functor@ (%s@ :@ %a)@;->@;%a"
+ s.txt self#module_type mt self#module_expr me
+ | Pmod_apply (me1, me2) ->
+@@ -1025,7 +1029,8 @@
+ | Pstr_module x ->
+ let rec module_helper me = match me.pmod_desc with
+ | Pmod_functor(s,mt,me) ->
+- pp f "(%s:%a)" s.txt self#module_type mt ;
++ if mt = None then pp f "()"
++ else Misc.may (pp f "(%s:%a)" s.txt self#module_type) mt;
+ module_helper me
+ | _ -> me in
+ pp f "@[<hov2>module %s%a@]"
+Index: parsing/printast.ml
+===================================================================
+--- parsing/printast.ml (revision 14301)
++++ parsing/printast.ml (working copy)
+@@ -576,7 +576,7 @@
+ signature i ppf s;
+ | Pmty_functor (s, mt1, mt2) ->
+ line i ppf "Pmty_functor %a\n" fmt_string_loc s;
+- module_type i ppf mt1;
++ Misc.may (module_type i ppf) mt1;
+ module_type i ppf mt2;
+ | Pmty_with (mt, l) ->
+ line i ppf "Pmty_with\n";
+@@ -670,7 +670,7 @@
+ structure i ppf s;
+ | Pmod_functor (s, mt, me) ->
+ line i ppf "Pmod_functor %a\n" fmt_string_loc s;
+- module_type i ppf mt;
++ Misc.may (module_type i ppf) mt;
+ module_expr i ppf me;
+ | Pmod_apply (me1, me2) ->
+ line i ppf "Pmod_apply\n";
+Index: tools/depend.ml
+===================================================================
+--- tools/depend.ml (revision 14301)
++++ tools/depend.ml (working copy)
+@@ -201,7 +201,8 @@
+ Pmty_ident l -> add bv l
+ | Pmty_signature s -> add_signature bv s
+ | Pmty_functor(id, mty1, mty2) ->
+- add_modtype bv mty1; add_modtype (StringSet.add id.txt bv) mty2
++ Misc.may (add_modtype bv) mty1;
++ add_modtype (StringSet.add id.txt bv) mty2
+ | Pmty_with(mty, cstrl) ->
+ add_modtype bv mty;
+ List.iter
+@@ -258,7 +259,7 @@
+ Pmod_ident l -> addmodule bv l
+ | Pmod_structure s -> ignore (add_structure bv s)
+ | Pmod_functor(id, mty, modl) ->
+- add_modtype bv mty;
++ Misc.may (add_modtype bv) mty;
+ add_module (StringSet.add id.txt bv) modl
+ | Pmod_apply(mod1, mod2) ->
+ add_module bv mod1; add_module bv mod2
+Index: tools/tast_iter.ml
+===================================================================
+--- tools/tast_iter.ml (revision 14301)
++++ tools/tast_iter.ml (working copy)
+@@ -193,7 +193,7 @@
+ | Tmty_ident (_path, _) -> ()
+ | Tmty_signature sg -> sub # signature sg
+ | Tmty_functor (_id, _, mtype1, mtype2) ->
+- sub # module_type mtype1; sub # module_type mtype2
++ Misc.may (sub # module_type) mtype1; sub # module_type mtype2
+ | Tmty_with (mtype, list) ->
+ sub # module_type mtype;
+ List.iter (fun (_, _, withc) -> sub # with_constraint withc) list
+@@ -212,7 +212,7 @@
+ | Tmod_ident (_p, _) -> ()
+ | Tmod_structure st -> sub # structure st
+ | Tmod_functor (_id, _, mtype, mexpr) ->
+- sub # module_type mtype;
++ Misc.may (sub # module_type) mtype;
+ sub # module_expr mexpr
+ | Tmod_apply (mexp1, mexp2, _) ->
+ sub # module_expr mexp1;
+Index: tools/untypeast.ml
+===================================================================
+--- tools/untypeast.ml (revision 14301)
++++ tools/untypeast.ml (working copy)
+@@ -376,7 +376,7 @@
+ Tmty_ident (_path, lid) -> Pmty_ident (lid)
+ | Tmty_signature sg -> Pmty_signature (untype_signature sg)
+ | Tmty_functor (_id, name, mtype1, mtype2) ->
+- Pmty_functor (name, untype_module_type mtype1,
++ Pmty_functor (name, Misc.may_map untype_module_type mtype1,
+ untype_module_type mtype2)
+ | Tmty_with (mtype, list) ->
+ Pmty_with (untype_module_type mtype,
+@@ -405,7 +405,7 @@
+ Tmod_ident (_p, lid) -> Pmod_ident (lid)
+ | Tmod_structure st -> Pmod_structure (untype_structure st)
+ | Tmod_functor (_id, name, mtype, mexpr) ->
+- Pmod_functor (name, untype_module_type mtype,
++ Pmod_functor (name, Misc.may_map untype_module_type mtype,
+ untype_module_expr mexpr)
+ | Tmod_apply (mexp1, mexp2, _) ->
+ Pmod_apply (untype_module_expr mexp1, untype_module_expr mexp2)
+Index: typing/btype.ml
+===================================================================
+--- typing/btype.ml (revision 14301)
++++ typing/btype.ml (working copy)
+@@ -56,6 +56,9 @@
+ let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false
+
+ let dummy_method = "*dummy method*"
++let default_mty = function
++ Some mty -> mty
++ | None -> Mty_signature []
+
+ (**** Representative of a type ****)
+
+Index: typing/btype.mli
+===================================================================
+--- typing/btype.mli (revision 14301)
++++ typing/btype.mli (working copy)
+@@ -39,9 +39,12 @@
+ (* Return a fresh marked generic variable *)
+ *)
+
++(**** Types ****)
++
+ val is_Tvar: type_expr -> bool
+ val is_Tunivar: type_expr -> bool
+ val dummy_method: label
++val default_mty: module_type option -> module_type
+
+ val repr: type_expr -> type_expr
+ (* Return the canonical representative of a type. *)
+Index: typing/env.ml
+===================================================================
+--- typing/env.ml (revision 14301)
++++ typing/env.ml (working copy)
+@@ -201,7 +201,7 @@
+
+ and functor_components = {
+ fcomp_param: Ident.t; (* Formal parameter *)
+- fcomp_arg: module_type; (* Argument signature *)
++ fcomp_arg: module_type option; (* Argument signature *)
+ fcomp_res: module_type; (* Result signature *)
+ fcomp_env: t; (* Environment in which the result signature makes sense *)
+ fcomp_subst: Subst.t; (* Prefixing substitution for the result signature *)
+@@ -522,7 +522,7 @@
+ let (p2, {md_type=mty2}) = lookup_module l2 env in
+ begin match EnvLazy.force !components_of_module_maker' desc1 with
+ Functor_comps f ->
+- !check_modtype_inclusion env mty2 p2 f.fcomp_arg;
++ Misc.may (!check_modtype_inclusion env mty2 p2) f.fcomp_arg;
+ (Papply(p1, p2), !components_of_functor_appl' f p1 p2)
+ | Structure_comps c ->
+ raise Not_found
+@@ -562,7 +562,7 @@
+ let p = Papply(p1, p2) in
+ begin match EnvLazy.force !components_of_module_maker' desc1 with
+ Functor_comps f ->
+- !check_modtype_inclusion env mty2 p2 f.fcomp_arg;
++ Misc.may (!check_modtype_inclusion env mty2 p2) f.fcomp_arg;
+ let mty =
+ Subst.modtype (Subst.add_module f.fcomp_param p2 f.fcomp_subst)
+ f.fcomp_res in
+@@ -1120,7 +1120,7 @@
+ fcomp_param = param;
+ (* fcomp_arg must be prefixed eagerly, because it is interpreted
+ in the outer environment, not in env *)
+- fcomp_arg = Subst.modtype sub ty_arg;
++ fcomp_arg = may_map (Subst.modtype sub) ty_arg;
+ (* fcomp_res is prefixed lazily, because it is interpreted in env *)
+ fcomp_res = ty_res;
+ fcomp_env = env;
+Index: typing/includemod.ml
+===================================================================
+--- typing/includemod.ml (revision 14301)
++++ typing/includemod.ml (working copy)
+@@ -168,7 +168,13 @@
+ try_modtypes2 env cxt mty1 (Subst.modtype subst mty2)
+ | (Mty_signature sig1, Mty_signature sig2) ->
+ signatures env cxt subst sig1 sig2
+- | (Mty_functor(param1, arg1, res1), Mty_functor(param2, arg2, res2)) ->
++ | (Mty_functor(param1, None, res1), Mty_functor(param2, None, res2)) ->
++ begin match modtypes env (Body param1::cxt) subst res1 res2 with
++ Tcoerce_none -> Tcoerce_none
++ | cc -> Tcoerce_functor (Tcoerce_none, cc)
++ end
++ | (Mty_functor(param1, Some arg1, res1),
++ Mty_functor(param2, Some arg2, res2)) ->
+ let arg2' = Subst.modtype subst arg2 in
+ let cc_arg = modtypes env (Arg param1::cxt) Subst.identity arg2' arg1 in
+ let cc_res =
+Index: typing/mtype.ml
+===================================================================
+--- typing/mtype.ml (revision 14301)
++++ typing/mtype.ml (working copy)
+@@ -34,7 +34,8 @@
+ match scrape env mty with
+ Mty_signature sg ->
+ Mty_signature(strengthen_sig env sg p)
+- | Mty_functor(param, arg, res) when !Clflags.applicative_functors ->
++ | Mty_functor(param, arg, res)
++ when !Clflags.applicative_functors && Ident.name param <> "*" ->
+ Mty_functor(param, arg, strengthen env res (Papply(p, Pident param)))
+ | mty ->
+ mty
+@@ -105,8 +106,9 @@
+ | Mty_functor(param, arg, res) ->
+ let var_inv =
+ match va with Co -> Contra | Contra -> Co | Strict -> Strict in
+- Mty_functor(param, nondep_mty env var_inv arg,
+- nondep_mty (Env.add_module param arg env) va res)
++ Mty_functor(param, Misc.may_map (nondep_mty env var_inv) arg,
++ nondep_mty
++ (Env.add_module param (Btype.default_mty arg) env) va res)
+
+ and nondep_sig env va = function
+ [] -> []
+@@ -228,3 +230,34 @@
+ no_code_needed_sig env rem
+ | (Sig_exception _ | Sig_class _) :: rem ->
+ false
++
++
++(* Check whether a module type may return types *)
++
++let rec contains_type env = function
++ Mty_ident path ->
++ (try Misc.may (contains_type env) (Env.find_modtype path env).mtd_type
++ with Not_found -> raise Exit)
++ | Mty_signature sg ->
++ contains_type_sig env sg
++ | Mty_functor (_, _, body) ->
++ contains_type env body
++
++and contains_type_sig env = List.iter (contains_type_item env)
++
++and contains_type_item env = function
++ Sig_type (_,({type_manifest = None} |
++ {type_kind = Type_abstract; type_private = Private}),_)
++ | Sig_modtype _ ->
++ raise Exit
++ | Sig_module (_, {md_type = mty}, _) ->
++ contains_type env mty
++ | Sig_value _
++ | Sig_type _
++ | Sig_exception _
++ | Sig_class _
++ | Sig_class_type _ ->
++ ()
++
++let contains_type env mty =
++ try contains_type env mty; false with Exit -> true
+Index: typing/mtype.mli
+===================================================================
+--- typing/mtype.mli (revision 14301)
++++ typing/mtype.mli (working copy)
+@@ -36,3 +36,4 @@
+ val enrich_modtype: Env.t -> Path.t -> module_type -> module_type
+ val enrich_typedecl: Env.t -> Path.t -> type_declaration -> type_declaration
+ val type_paths: Env.t -> Path.t -> module_type -> Path.t list
++val contains_type: Env.t -> module_type -> bool
+Index: typing/oprint.ml
+===================================================================
+--- typing/oprint.ml (revision 14301)
++++ typing/oprint.ml (working copy)
+@@ -344,7 +344,9 @@
+ let rec print_out_module_type ppf =
+ function
+ Omty_abstract -> ()
+- | Omty_functor (name, mty_arg, mty_res) ->
++ | Omty_functor (_, None, mty_res) ->
++ fprintf ppf "@[<2>functor@ () ->@ %a@]" print_out_module_type mty_res
++ | Omty_functor (name, Some mty_arg, mty_res) ->
+ fprintf ppf "@[<2>functor@ (%s : %a) ->@ %a@]" name
+ print_out_module_type mty_arg print_out_module_type mty_res
+ | Omty_ident id -> fprintf ppf "%a" print_ident id
+Index: typing/outcometree.mli
+===================================================================
+--- typing/outcometree.mli (revision 14301)
++++ typing/outcometree.mli (working copy)
+@@ -75,7 +75,7 @@
+
+ type out_module_type =
+ | Omty_abstract
+- | Omty_functor of string * out_module_type * out_module_type
++ | Omty_functor of string * out_module_type option * out_module_type
+ | Omty_ident of out_ident
+ | Omty_signature of out_sig_item list
+ and out_sig_item =
+Index: typing/printtyp.ml
+===================================================================
+--- typing/printtyp.ml (revision 14301)
++++ typing/printtyp.ml (working copy)
+@@ -1116,9 +1116,12 @@
+ | Mty_signature sg ->
+ Omty_signature (tree_of_signature sg)
+ | Mty_functor(param, ty_arg, ty_res) ->
+- Omty_functor
+- (Ident.name param, tree_of_modtype ty_arg,
+- wrap_env (Env.add_module param ty_arg) tree_of_modtype ty_res)
++ let res =
++ match ty_arg with None -> tree_of_modtype ty_res
++ | Some mty ->
++ wrap_env (Env.add_module param mty) tree_of_modtype ty_res
++ in
++ Omty_functor (Ident.name param, may_map tree_of_modtype ty_arg, res)
+
+ and tree_of_signature sg =
+ wrap_env (fun env -> env) (tree_of_signature_rec !printing_env) sg
+Index: typing/printtyped.ml
+===================================================================
+--- typing/printtyped.ml (revision 14301)
++++ typing/printtyped.ml (working copy)
+@@ -562,7 +562,7 @@
+ signature i ppf s;
+ | Tmty_functor (s, _, mt1, mt2) ->
+ line i ppf "Pmty_functor \"%a\"\n" fmt_ident s;
+- module_type i ppf mt1;
++ Misc.may (module_type i ppf) mt1;
+ module_type i ppf mt2;
+ | Tmty_with (mt, l) ->
+ line i ppf "Pmty_with\n";
+@@ -651,7 +651,7 @@
+ structure i ppf s;
+ | Tmod_functor (s, _, mt, me) ->
+ line i ppf "Pmod_functor \"%a\"\n" fmt_ident s;
+- module_type i ppf mt;
++ Misc.may (module_type i ppf) mt;
+ module_expr i ppf me;
+ | Tmod_apply (me1, me2, _) ->
+ line i ppf "Pmod_apply\n";
+Index: typing/subst.ml
+===================================================================
+--- typing/subst.ml (revision 14301)
++++ typing/subst.ml (working copy)
+@@ -327,8 +327,8 @@
+ Mty_signature(signature s sg)
+ | Mty_functor(id, arg, res) ->
+ let id' = Ident.rename id in
+- Mty_functor(id', modtype s arg,
+- modtype (add_module id (Pident id') s) res)
++ Mty_functor(id', may_map (modtype s) arg,
++ modtype (add_module id (Pident id') s) res)
+
+ and signature s sg =
+ (* Components of signature may be mutually recursive (e.g. type declarations
+Index: typing/typedtree.ml
+===================================================================
+--- typing/typedtree.ml (revision 14301)
++++ typing/typedtree.ml (working copy)
+@@ -187,7 +187,7 @@
+ and module_expr_desc =
+ Tmod_ident of Path.t * Longident.t loc
+ | Tmod_structure of structure
+- | Tmod_functor of Ident.t * string loc * module_type * module_expr
++ | Tmod_functor of Ident.t * string loc * module_type option * module_expr
+ | Tmod_apply of module_expr * module_expr * module_coercion
+ | Tmod_constraint of
+ module_expr * Types.module_type * module_type_constraint * module_coercion
+@@ -253,7 +253,7 @@
+ and module_type_desc =
+ Tmty_ident of Path.t * Longident.t loc
+ | Tmty_signature of signature
+- | Tmty_functor of Ident.t * string loc * module_type * module_type
++ | Tmty_functor of Ident.t * string loc * module_type option * module_type
+ | Tmty_with of module_type * (Path.t * Longident.t loc * with_constraint) list
+ | Tmty_typeof of module_expr
+
+Index: typing/typedtree.mli
+===================================================================
+--- typing/typedtree.mli (revision 14301)
++++ typing/typedtree.mli (working copy)
+@@ -186,7 +186,7 @@
+ and module_expr_desc =
+ Tmod_ident of Path.t * Longident.t loc
+ | Tmod_structure of structure
+- | Tmod_functor of Ident.t * string loc * module_type * module_expr
++ | Tmod_functor of Ident.t * string loc * module_type option * module_expr
+ | Tmod_apply of module_expr * module_expr * module_coercion
+ | Tmod_constraint of
+ module_expr * Types.module_type * module_type_constraint * module_coercion
+@@ -252,7 +252,7 @@
+ and module_type_desc =
+ Tmty_ident of Path.t * Longident.t loc
+ | Tmty_signature of signature
+- | Tmty_functor of Ident.t * string loc * module_type * module_type
++ | Tmty_functor of Ident.t * string loc * module_type option * module_type
+ | Tmty_with of module_type * (Path.t * Longident.t loc * with_constraint) list
+ | Tmty_typeof of module_expr
+
+Index: typing/typedtreeIter.ml
+===================================================================
+--- typing/typedtreeIter.ml (revision 14301)
++++ typing/typedtreeIter.ml (working copy)
+@@ -383,7 +383,7 @@
+ Tmty_ident (path, _) -> ()
+ | Tmty_signature sg -> iter_signature sg
+ | Tmty_functor (id, _, mtype1, mtype2) ->
+- iter_module_type mtype1; iter_module_type mtype2
++ Misc.may iter_module_type mtype1; iter_module_type mtype2
+ | Tmty_with (mtype, list) ->
+ iter_module_type mtype;
+ List.iter (fun (path, _, withc) ->
+@@ -412,7 +412,7 @@
+ Tmod_ident (p, _) -> ()
+ | Tmod_structure st -> iter_structure st
+ | Tmod_functor (id, _, mtype, mexpr) ->
+- iter_module_type mtype;
++ Misc.may iter_module_type mtype;
+ iter_module_expr mexpr
+ | Tmod_apply (mexp1, mexp2, _) ->
+ iter_module_expr mexp1;
+Index: typing/typedtreeMap.ml
+===================================================================
+--- typing/typedtreeMap.ml (revision 14301)
++++ typing/typedtreeMap.ml (working copy)
+@@ -426,7 +426,7 @@
+ Tmty_ident (path, lid) -> mty.mty_desc
+ | Tmty_signature sg -> Tmty_signature (map_signature sg)
+ | Tmty_functor (id, name, mtype1, mtype2) ->
+- Tmty_functor (id, name, map_module_type mtype1,
++ Tmty_functor (id, name, Misc.may_map map_module_type mtype1,
+ map_module_type mtype2)
+ | Tmty_with (mtype, list) ->
+ Tmty_with (map_module_type mtype,
+@@ -456,7 +456,7 @@
+ Tmod_ident (p, lid) -> mexpr.mod_desc
+ | Tmod_structure st -> Tmod_structure (map_structure st)
+ | Tmod_functor (id, name, mtype, mexpr) ->
+- Tmod_functor (id, name, map_module_type mtype,
++ Tmod_functor (id, name, Misc.may_map map_module_type mtype,
+ map_module_expr mexpr)
+ | Tmod_apply (mexp1, mexp2, coercion) ->
+ Tmod_apply (map_module_expr mexp1, map_module_expr mexp2, coercion)
+Index: typing/typemod.ml
+===================================================================
+--- typing/typemod.ml (revision 14301)
++++ typing/typemod.ml (working copy)
+@@ -39,6 +39,7 @@
+ | Scoping_pack of Longident.t * type_expr
+ | Extension of string
+ | Recursive_module_require_explicit_type
++ | Apply_generative
+
+ exception Error of Location.t * Env.t * error
+
+@@ -299,8 +300,9 @@
+ | Pmty_signature ssg ->
+ Mty_signature(approx_sig env ssg)
+ | Pmty_functor(param, sarg, sres) ->
+- let arg = approx_modtype env sarg in
+- let (id, newenv) = Env.enter_module param.txt arg env in
++ let arg = may_map (approx_modtype env) sarg in
++ let (id, newenv) =
++ Env.enter_module param.txt (Btype.default_mty arg) env in
+ let res = approx_modtype newenv sres in
+ Mty_functor(id, arg, res)
+ | Pmty_with(sbody, constraints) ->
+@@ -472,11 +474,13 @@
+ mkmty (Tmty_signature sg) (Mty_signature sg.sig_type) env loc
+ smty.pmty_attributes
+ | Pmty_functor(param, sarg, sres) ->
+- let arg = transl_modtype env sarg in
+- let (id, newenv) = Env.enter_module param.txt arg.mty_type env in
++ let arg = Misc.may_map (transl_modtype env) sarg in
++ let ty_arg = Misc.may_map (fun m -> m.mty_type) arg in
++ let (id, newenv) =
++ Env.enter_module param.txt (Btype.default_mty ty_arg) env in
+ let res = transl_modtype newenv sres in
+ mkmty (Tmty_functor (id, param, arg, res))
+- (Mty_functor(id, arg.mty_type, res.mty_type)) env loc
++ (Mty_functor(id, ty_arg, res.mty_type)) env loc
+ smty.pmty_attributes
+ | Pmty_with(sbody, constraints) ->
+ let body = transl_modtype env sbody in
+@@ -949,11 +953,14 @@
+ mod_attributes = smod.pmod_attributes;
+ mod_loc = smod.pmod_loc }
+ | Pmod_functor(name, smty, sbody) ->
+- let mty = transl_modtype env smty in
+- let (id, newenv) = Env.enter_module name.txt mty.mty_type env in
+- let body = type_module sttn true None newenv sbody in
++ let mty = may_map (transl_modtype env) smty in
++ let ty_arg = may_map (fun m -> m.mty_type) mty in
++ let (id, newenv), funct_body =
++ match ty_arg with None -> (Ident.create "*", env), false
++ | Some mty -> Env.enter_module name.txt mty env, true in
++ let body = type_module sttn funct_body None newenv sbody in
+ rm { mod_desc = Tmod_functor(id, name, mty, body);
+- mod_type = Mty_functor(id, mty.mty_type, body.mod_type);
++ mod_type = Mty_functor(id, ty_arg, body.mod_type);
+ mod_env = env;
+ mod_attributes = smod.pmod_attributes;
+ mod_loc = smod.pmod_loc }
+@@ -964,6 +971,14 @@
+ type_module (sttn && path <> None) funct_body None env sfunct in
+ begin match Mtype.scrape env funct.mod_type with
+ Mty_functor(param, mty_param, mty_res) as mty_functor ->
++ let generative, mty_param =
++ (mty_param = None, Btype.default_mty mty_param) in
++ if generative then begin
++ if sarg.pmod_desc <> Pmod_structure [] then
++ raise (Error (sfunct.pmod_loc, env, Apply_generative));
++ if funct_body && Mtype.contains_type env funct.mod_type then
++ raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body));
++ end;
+ let coercion =
+ try
+ Includemod.modtypes env arg.mod_type mty_param
+@@ -975,6 +990,7 @@
+ Subst.modtype (Subst.add_module param path Subst.identity)
+ mty_res
+ | None ->
++ if generative then mty_res else
+ try
+ Mtype.nondep_supertype
+ (Env.add_module param arg.mod_type env) param mty_res
+@@ -999,8 +1015,6 @@
+ }
+
+ | Pmod_unpack sexp ->
+- if funct_body then
+- raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body));
+ if !Clflags.principal then Ctype.begin_def ();
+ let exp = Typecore.type_exp env sexp in
+ if !Clflags.principal then begin
+@@ -1025,6 +1039,8 @@
+ | _ ->
+ raise (Error(smod.pmod_loc, env, Not_a_packed_module exp.exp_type))
+ in
++ if funct_body && Mtype.contains_type env mty then
++ raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body));
+ rm { mod_desc = Tmod_unpack(exp, mty);
+ mod_type = mty;
+ mod_env = env;
+@@ -1549,7 +1565,8 @@
+ Location.print_filename intf_name
+ | Not_allowed_in_functor_body ->
+ fprintf ppf
+- "This kind of expression is not allowed within the body of a functor."
++ "@[This expression creates fresh types.@ %s@]"
++ "It is not allowed inside applicative functors."
+ | With_need_typeconstr ->
+ fprintf ppf
+ "Only type constructors with identical parameters can be substituted."
+@@ -1570,6 +1587,8 @@
+ fprintf ppf "Uninterpreted extension '%s'." s
+ | Recursive_module_require_explicit_type ->
+ fprintf ppf "Recursive modules require an explicit module type."
++ | Apply_generative ->
++ fprintf ppf "This is a generative functor. It can only be applied to ()"
+
+ let report_error env ppf err =
+ Printtyp.wrap_printing_env env (fun () -> report_error ppf err)
+Index: typing/typemod.mli
+===================================================================
+--- typing/typemod.mli (revision 14301)
++++ typing/typemod.mli (working copy)
+@@ -60,6 +60,7 @@
+ | Scoping_pack of Longident.t * type_expr
+ | Extension of string
+ | Recursive_module_require_explicit_type
++ | Apply_generative
+
+ exception Error of Location.t * Env.t * error
+
+Index: typing/types.ml
+===================================================================
+--- typing/types.ml (revision 14301)
++++ typing/types.ml (working copy)
+@@ -264,7 +264,7 @@
+ type module_type =
+ Mty_ident of Path.t
+ | Mty_signature of signature
+- | Mty_functor of Ident.t * module_type * module_type
++ | Mty_functor of Ident.t * module_type option * module_type
+
+ and signature = signature_item list
+
+Index: typing/types.mli
+===================================================================
+--- typing/types.mli (revision 14301)
++++ typing/types.mli (working copy)
+@@ -251,7 +251,7 @@
+ type module_type =
+ Mty_ident of Path.t
+ | Mty_signature of signature
+- | Mty_functor of Ident.t * module_type * module_type
++ | Mty_functor of Ident.t * module_type option * module_type
+
+ and signature = signature_item list
+
diff --git a/experimental/garrigue/impure-functors.diff b/experimental/garrigue/impure-functors.diff
new file mode 100644
index 0000000000..fd8dba5782
--- /dev/null
+++ b/experimental/garrigue/impure-functors.diff
@@ -0,0 +1,223 @@
+Index: parsing/parser.mly
+===================================================================
+--- parsing/parser.mly (revision 14285)
++++ parsing/parser.mly (working copy)
+@@ -542,8 +542,12 @@
+ { unclosed "struct" 1 "end" 3 }
+ | FUNCTOR LPAREN UIDENT COLON module_type RPAREN MINUSGREATER module_expr
+ { mkmod(Pmod_functor(mkrhs $3 3, $5, $8)) }
++ | FUNCTOR LPAREN RPAREN MINUSGREATER module_expr
++ { mkmod(Pmod_functor(mkrhs "*" 3, mkmty (Pmty_signature []), $5)) }
+ | module_expr LPAREN module_expr RPAREN
+ { mkmod(Pmod_apply($1, $3)) }
++ | module_expr LPAREN RPAREN
++ { mkmod(Pmod_apply($1, mkmod (Pmod_structure []))) }
+ | module_expr LPAREN module_expr error
+ { unclosed "(" 2 ")" 4 }
+ | LPAREN module_expr COLON module_type RPAREN
+@@ -641,6 +645,8 @@
+ { mkmod(Pmod_constraint($4, $2)) }
+ | LPAREN UIDENT COLON module_type RPAREN module_binding_body
+ { mkmod(Pmod_functor(mkrhs $2 2, $4, $6)) }
++ | LPAREN RPAREN module_binding_body
++ { mkmod(Pmod_functor(mkrhs "*" 1, mkmty(Pmty_signature []), $3)) }
+ ;
+ module_bindings:
+ module_binding { [$1] }
+@@ -663,6 +669,9 @@
+ | FUNCTOR LPAREN UIDENT COLON module_type RPAREN MINUSGREATER module_type
+ %prec below_WITH
+ { mkmty(Pmty_functor(mkrhs $3 3, $5, $8)) }
++ | FUNCTOR LPAREN RPAREN MINUSGREATER module_type
++ %prec below_WITH
++ { mkmty(Pmty_functor(mkrhs "*" 2, mkmty(Pmty_signature []), $5)) }
+ | module_type WITH with_constraints
+ { mkmty(Pmty_with($1, List.rev $3)) }
+ | MODULE TYPE OF module_expr %prec below_LBRACKETAT
+@@ -725,6 +734,8 @@
+ { $2 }
+ | LPAREN UIDENT COLON module_type RPAREN module_declaration
+ { mkmty(Pmty_functor(mkrhs $2 2, $4, $6)) }
++ | LPAREN RPAREN module_declaration
++ { mkmty(Pmty_functor(mkrhs "*" 1, mkmty (Pmty_signature []), $3)) }
+ ;
+ module_rec_declarations:
+ module_rec_declaration { [$1] }
+Index: parsing/pprintast.ml
+===================================================================
+--- parsing/pprintast.ml (revision 14285)
++++ parsing/pprintast.ml (working copy)
+@@ -834,6 +834,8 @@
+ | Pmty_signature (s) ->
+ pp f "@[<hv0>@[<hv2>sig@ %a@]@ end@]" (* "@[<hov>sig@ %a@ end@]" *)
+ (self#list self#signature_item ) s (* FIXME wrong indentation*)
++ | Pmty_functor ({txt="*"}, mt1, mt2) ->
++ pp f "@[<hov2>functor () ->@ %a@]" self#module_type mt2
+ | Pmty_functor (s, mt1, mt2) ->
+ pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" s.txt
+ self#module_type mt1 self#module_type mt2
+@@ -940,6 +942,8 @@
+ self#module_type mt
+ | Pmod_ident (li) ->
+ pp f "%a" self#longident_loc li;
++ | Pmod_functor ({txt="*"}, mt, me) ->
++ pp f "functor ()@;->@;%a" self#module_expr me
+ | Pmod_functor (s, mt, me) ->
+ pp f "functor@ (%s@ :@ %a)@;->@;%a"
+ s.txt self#module_type mt self#module_expr me
+@@ -1025,7 +1029,8 @@
+ | Pstr_module x ->
+ let rec module_helper me = match me.pmod_desc with
+ | Pmod_functor(s,mt,me) ->
+- pp f "(%s:%a)" s.txt self#module_type mt ;
++ if s.txt = "*" then pp f "()"
++ else pp f "(%s:%a)" s.txt self#module_type mt ;
+ module_helper me
+ | _ -> me in
+ pp f "@[<hov2>module %s%a@]"
+Index: typing/includemod.ml
+===================================================================
+--- typing/includemod.ml (revision 14285)
++++ typing/includemod.ml (working copy)
+@@ -35,6 +35,7 @@
+ Ident.t * class_declaration * class_declaration *
+ Ctype.class_match_failure list
+ | Unbound_modtype_path of Path.t
++ | Impure_functor
+
+ type pos =
+ Module of Ident.t | Modtype of Ident.t | Arg of Ident.t | Body of Ident.t
+@@ -165,6 +166,8 @@
+ | (Mty_signature sig1, Mty_signature sig2) ->
+ signatures env cxt subst sig1 sig2
+ | (Mty_functor(param1, arg1, res1), Mty_functor(param2, arg2, res2)) ->
++ if Ident.name param1 = "*" && Ident.name param2 <> "*" then
++ raise (Error [cxt, env, Impure_functor]);
+ let arg2' = Subst.modtype subst arg2 in
+ let cc_arg = modtypes env (Arg param1::cxt) Subst.identity arg2' arg1 in
+ let cc_res =
+@@ -422,6 +425,8 @@
+ Includeclass.report_error reason
+ | Unbound_modtype_path path ->
+ fprintf ppf "Unbound module type %a" Printtyp.path path
++ | Impure_functor ->
++ fprintf ppf "An impure functor cannot be made applicative"
+
+ let rec context ppf = function
+ Module id :: rem ->
+Index: typing/includemod.mli
+===================================================================
+--- typing/includemod.mli (revision 14285)
++++ typing/includemod.mli (working copy)
+@@ -40,6 +40,7 @@
+ Ident.t * class_declaration * class_declaration *
+ Ctype.class_match_failure list
+ | Unbound_modtype_path of Path.t
++ | Impure_functor
+
+ type pos =
+ Module of Ident.t | Modtype of Ident.t | Arg of Ident.t | Body of Ident.t
+Index: typing/mtype.ml
+===================================================================
+--- typing/mtype.ml (revision 14285)
++++ typing/mtype.ml (working copy)
+@@ -34,7 +34,8 @@
+ match scrape env mty with
+ Mty_signature sg ->
+ Mty_signature(strengthen_sig env sg p)
+- | Mty_functor(param, arg, res) when !Clflags.applicative_functors ->
++ | Mty_functor(param, arg, res)
++ when !Clflags.applicative_functors && Ident.name param <> "*" ->
+ Mty_functor(param, arg, strengthen env res (Papply(p, Pident param)))
+ | mty ->
+ mty
+Index: typing/oprint.ml
+===================================================================
+--- typing/oprint.ml (revision 14285)
++++ typing/oprint.ml (working copy)
+@@ -344,6 +344,8 @@
+ let rec print_out_module_type ppf =
+ function
+ Omty_abstract -> ()
++ | Omty_functor ("*", _, mty_res) ->
++ fprintf ppf "@[<2>functor@ () ->@ %a@]" print_out_module_type mty_res
+ | Omty_functor (name, mty_arg, mty_res) ->
+ fprintf ppf "@[<2>functor@ (%s : %a) ->@ %a@]" name
+ print_out_module_type mty_arg print_out_module_type mty_res
+Index: typing/typemod.ml
+===================================================================
+--- typing/typemod.ml (revision 14285)
++++ typing/typemod.ml (working copy)
+@@ -39,6 +39,7 @@
+ | Scoping_pack of Longident.t * type_expr
+ | Extension of string
+ | Recursive_module_require_explicit_type
++ | Apply_impure
+
+ exception Error of Location.t * Env.t * error
+
+@@ -950,8 +951,10 @@
+ mod_loc = smod.pmod_loc }
+ | Pmod_functor(name, smty, sbody) ->
+ let mty = transl_modtype env smty in
+- let (id, newenv) = Env.enter_module name.txt mty.mty_type env in
+- let body = type_module sttn true None newenv sbody in
++ let (id, newenv), funct_body =
++ if name.txt = "*" then (Ident.create "*", env), false else
++ Env.enter_module name.txt mty.mty_type env, true in
++ let body = type_module sttn funct_body None newenv sbody in
+ rm { mod_desc = Tmod_functor(id, name, mty, body);
+ mod_type = Mty_functor(id, mty.mty_type, body.mod_type);
+ mod_env = env;
+@@ -964,6 +967,13 @@
+ type_module (sttn && path <> None) funct_body None env sfunct in
+ begin match Mtype.scrape env funct.mod_type with
+ Mty_functor(param, mty_param, mty_res) as mty_functor ->
++ let impure = Ident.name param = "*" in
++ if impure then begin
++ if sarg.pmod_desc <> Pmod_structure [] then
++ raise (Error (sfunct.pmod_loc, env, Apply_impure));
++ if funct_body then
++ raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body));
++ end;
+ let coercion =
+ try
+ Includemod.modtypes env arg.mod_type mty_param
+@@ -975,6 +985,7 @@
+ Subst.modtype (Subst.add_module param path Subst.identity)
+ mty_res
+ | None ->
++ if impure then mty_res else
+ try
+ Mtype.nondep_supertype
+ (Env.add_module param arg.mod_type env) param mty_res
+@@ -1549,7 +1560,7 @@
+ Location.print_filename intf_name
+ | Not_allowed_in_functor_body ->
+ fprintf ppf
+- "This kind of expression is not allowed within the body of a functor."
++ "This kind of expression is only allowed inside impure functors."
+ | With_need_typeconstr ->
+ fprintf ppf
+ "Only type constructors with identical parameters can be substituted."
+@@ -1570,6 +1581,8 @@
+ fprintf ppf "Uninterpreted extension '%s'." s
+ | Recursive_module_require_explicit_type ->
+ fprintf ppf "Recursive modules require an explicit module type."
++ | Apply_impure ->
++ fprintf ppf "This functor is impure. It can only be applied to ()"
+
+ let report_error env ppf err =
+ Printtyp.wrap_printing_env env (fun () -> report_error ppf err)
+Index: typing/typemod.mli
+===================================================================
+--- typing/typemod.mli (revision 14285)
++++ typing/typemod.mli (working copy)
+@@ -60,6 +60,7 @@
+ | Scoping_pack of Longident.t * type_expr
+ | Extension of string
+ | Recursive_module_require_explicit_type
++ | Apply_impure
+
+ exception Error of Location.t * Env.t * error
+
diff --git a/experimental/garrigue/marshal_objects.diff b/experimental/garrigue/marshal_objects.diff
new file mode 100644
index 0000000000..bb9b4dd714
--- /dev/null
+++ b/experimental/garrigue/marshal_objects.diff
@@ -0,0 +1,800 @@
+? bytecomp/alpha_eq.ml
+Index: bytecomp/lambda.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/lambda.ml,v
+retrieving revision 1.44
+diff -u -r1.44 lambda.ml
+--- bytecomp/lambda.ml 25 Aug 2005 15:35:16 -0000 1.44
++++ bytecomp/lambda.ml 2 Feb 2006 05:08:56 -0000
+@@ -287,9 +287,10 @@
+ let compare = compare
+ end)
+
+-let free_ids get l =
++let free_ids get used l =
+ let fv = ref IdentSet.empty in
+ let rec free l =
++ let old = !fv in
+ iter free l;
+ fv := List.fold_right IdentSet.add (get l) !fv;
+ match l with
+@@ -307,17 +308,20 @@
+ fv := IdentSet.remove v !fv
+ | Lassign(id, e) ->
+ fv := IdentSet.add id !fv
++ | Lifused(id, e) ->
++ if used && not (IdentSet.mem id old) then fv := IdentSet.remove id !fv
+ | Lvar _ | Lconst _ | Lapply _
+ | Lprim _ | Lswitch _ | Lstaticraise _
+ | Lifthenelse _ | Lsequence _ | Lwhile _
+- | Lsend _ | Levent _ | Lifused _ -> ()
++ | Lsend _ | Levent _ -> ()
+ in free l; !fv
+
+-let free_variables l =
+- free_ids (function Lvar id -> [id] | _ -> []) l
++let free_variables ?(ifused=false) l =
++ free_ids (function Lvar id -> [id] | _ -> []) ifused l
+
+ let free_methods l =
+- free_ids (function Lsend(Self, Lvar meth, obj, _) -> [meth] | _ -> []) l
++ free_ids (function Lsend(Self, Lvar meth, obj, _) -> [meth] | _ -> [])
++ false l
+
+ (* Check if an action has a "when" guard *)
+ let raise_count = ref 0
+Index: bytecomp/lambda.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/lambda.mli,v
+retrieving revision 1.42
+diff -u -r1.42 lambda.mli
+--- bytecomp/lambda.mli 25 Aug 2005 15:35:16 -0000 1.42
++++ bytecomp/lambda.mli 2 Feb 2006 05:08:56 -0000
+@@ -177,7 +177,7 @@
+
+ val iter: (lambda -> unit) -> lambda -> unit
+ module IdentSet: Set.S with type elt = Ident.t
+-val free_variables: lambda -> IdentSet.t
++val free_variables: ?ifused:bool -> lambda -> IdentSet.t
+ val free_methods: lambda -> IdentSet.t
+
+ val transl_path: Path.t -> lambda
+Index: bytecomp/translclass.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/translclass.ml,v
+retrieving revision 1.38
+diff -u -r1.38 translclass.ml
+--- bytecomp/translclass.ml 13 Aug 2005 20:59:37 -0000 1.38
++++ bytecomp/translclass.ml 2 Feb 2006 05:08:56 -0000
+@@ -46,6 +46,10 @@
+
+ let lfield v i = Lprim(Pfield i, [Lvar v])
+
++let ltuple l = Lprim(Pmakeblock(0,Immutable), l)
++
++let lprim name args = Lapply(oo_prim name, args)
++
+ let transl_label l = share (Const_immstring l)
+
+ let rec transl_meth_list lst =
+@@ -68,8 +72,8 @@
+ Lvar offset])])]))
+
+ let transl_val tbl create name =
+- Lapply (oo_prim (if create then "new_variable" else "get_variable"),
+- [Lvar tbl; transl_label name])
++ lprim (if create then "new_variable" else "get_variable")
++ [Lvar tbl; transl_label name]
+
+ let transl_vals tbl create vals rem =
+ List.fold_right
+@@ -82,7 +86,7 @@
+ (fun (nm, id) rem ->
+ try
+ (nm, id,
+- Lapply(oo_prim "get_method", [Lvar tbl; Lvar (Meths.find nm meths)]))
++ lprim "get_method" [Lvar tbl; Lvar (Meths.find nm meths)])
+ :: rem
+ with Not_found -> rem)
+ inh_meths []
+@@ -97,17 +101,15 @@
+ let (inh_init, obj_init, has_init) = init obj' in
+ if obj_init = lambda_unit then
+ (inh_init,
+- Lapply (oo_prim (if has_init then "create_object_and_run_initializers"
+- else"create_object_opt"),
+- [obj; Lvar cl]))
++ lprim (if has_init then "create_object_and_run_initializers"
++ else"create_object_opt")
++ [obj; Lvar cl])
+ else begin
+ (inh_init,
+- Llet(Strict, obj',
+- Lapply (oo_prim "create_object_opt", [obj; Lvar cl]),
++ Llet(Strict, obj', lprim "create_object_opt" [obj; Lvar cl],
+ Lsequence(obj_init,
+ if not has_init then Lvar obj' else
+- Lapply (oo_prim "run_initializers_opt",
+- [obj; Lvar obj'; Lvar cl]))))
++ lprim "run_initializers_opt" [obj; Lvar obj'; Lvar cl])))
+ end
+
+ let rec build_object_init cl_table obj params inh_init obj_init cl =
+@@ -203,14 +205,13 @@
+
+
+ let bind_method tbl lab id cl_init =
+- Llet(StrictOpt, id, Lapply (oo_prim "get_method_label",
+- [Lvar tbl; transl_label lab]),
++ Llet(StrictOpt, id, lprim "get_method_label" [Lvar tbl; transl_label lab],
+ cl_init)
+
+-let bind_methods tbl meths vals cl_init =
+- let methl = Meths.fold (fun lab id tl -> (lab,id) :: tl) meths [] in
++let bind_methods tbl methl vals cl_init =
+ let len = List.length methl and nvals = List.length vals in
+- if len < 2 && nvals = 0 then Meths.fold (bind_method tbl) meths cl_init else
++ if len < 2 && nvals = 0 then
++ List.fold_right (fun (n,i) -> bind_method tbl n i) methl cl_init else
+ if len = 0 && nvals < 2 then transl_vals tbl true vals cl_init else
+ let ids = Ident.create "ids" in
+ let i = ref len in
+@@ -229,21 +230,19 @@
+ vals' cl_init)
+ in
+ Llet(StrictOpt, ids,
+- Lapply (oo_prim getter,
+- [Lvar tbl; transl_meth_list (List.map fst methl)] @ names),
++ lprim getter
++ ([Lvar tbl; transl_meth_list (List.map fst methl)] @ names),
+ List.fold_right
+- (fun (lab,id) lam -> decr i; Llet(StrictOpt, id, lfield ids !i, lam))
++ (fun (lab,id) lam -> decr i; Llet(Alias, id, lfield ids !i, lam))
+ methl cl_init)
+
+ let output_methods tbl methods lam =
+ match methods with
+ [] -> lam
+ | [lab; code] ->
+- lsequence (Lapply(oo_prim "set_method", [Lvar tbl; lab; code])) lam
++ lsequence (lprim "set_method" [Lvar tbl; lab; code]) lam
+ | _ ->
+- lsequence (Lapply(oo_prim "set_methods",
+- [Lvar tbl; Lprim(Pmakeblock(0,Immutable), methods)]))
+- lam
++ lsequence (lprim "set_methods" [Lvar tbl; ltuple methods]) lam
+
+ let rec ignore_cstrs cl =
+ match cl.cl_desc with
+@@ -266,7 +265,8 @@
+ Llet (Strict, obj_init,
+ Lapply(Lprim(Pfield 1, [lpath]), Lvar cla ::
+ if top then [Lprim(Pfield 3, [lpath])] else []),
+- bind_super cla super cl_init))
++ bind_super cla super cl_init),
++ [], [])
+ | _ ->
+ assert false
+ end
+@@ -278,10 +278,11 @@
+ match field with
+ Cf_inher (cl, vals, meths) ->
+ let cl_init = output_methods cla methods cl_init in
+- let inh_init, cl_init =
++ let (inh_init, cl_init, meths', vals') =
+ build_class_init cla false
+ (vals, meths_super cla str.cl_meths meths)
+ inh_init cl_init msubst top cl in
++ let cl_init = bind_methods cla meths' vals' cl_init in
+ (inh_init, cl_init, [], values)
+ | Cf_val (name, id, exp) ->
+ (inh_init, cl_init, methods, (name, id)::values)
+@@ -304,29 +305,37 @@
+ (inh_init, cl_init, methods, vals @ values)
+ | Cf_init exp ->
+ (inh_init,
+- Lsequence(Lapply (oo_prim "add_initializer",
+- Lvar cla :: msubst false (transl_exp exp)),
++ Lsequence(lprim "add_initializer"
++ (Lvar cla :: msubst false (transl_exp exp)),
+ cl_init),
+ methods, values))
+ str.cl_field
+ (inh_init, cl_init, [], [])
+ in
+ let cl_init = output_methods cla methods cl_init in
+- (inh_init, bind_methods cla str.cl_meths values cl_init)
++ (* inh_init, bind_methods cla str.cl_meths values cl_init *)
++ let methods = Meths.fold (fun n i l -> (n,i)::l) str.cl_meths [] in
++ (inh_init, cl_init, methods, values)
+ | Tclass_fun (pat, vals, cl, _) ->
+- let (inh_init, cl_init) =
++ let (inh_init, cl_init, methods, values) =
+ build_class_init cla cstr super inh_init cl_init msubst top cl
+ in
++ let fv = free_variables ~ifused:true cl_init in
++ let vals = List.filter (fun (id,_) -> IdentSet.mem id fv) vals in
+ let vals = List.map (function (id, _) -> (Ident.name id, id)) vals in
+- (inh_init, transl_vals cla true vals cl_init)
++ (* inh_init, transl_vals cla true vals cl_init *)
++ (inh_init, cl_init, methods, vals @ values)
+ | Tclass_apply (cl, exprs) ->
+ build_class_init cla cstr super inh_init cl_init msubst top cl
+ | Tclass_let (rec_flag, defs, vals, cl) ->
+- let (inh_init, cl_init) =
++ let (inh_init, cl_init, methods, values) =
+ build_class_init cla cstr super inh_init cl_init msubst top cl
+ in
++ let fv = free_variables ~ifused:true cl_init in
++ let vals = List.filter (fun (id,_) -> IdentSet.mem id fv) vals in
+ let vals = List.map (function (id, _) -> (Ident.name id, id)) vals in
+- (inh_init, transl_vals cla true vals cl_init)
++ (* inh_init, transl_vals cla true vals cl_init *)
++ (inh_init, cl_init, methods, vals @ values)
+ | Tclass_constraint (cl, vals, meths, concr_meths) ->
+ let virt_meths =
+ List.filter (fun lab -> not (Concr.mem lab concr_meths)) meths in
+@@ -358,23 +367,34 @@
+ cl_init valids in
+ (inh_init,
+ Llet (Strict, inh,
+- Lapply(oo_prim "inherits", narrow_args @
+- [lpath; Lconst(Const_pointer(if top then 1 else 0))]),
++ lprim "inherits"
++ (narrow_args @
++ [lpath; Lconst(Const_pointer(if top then 1 else 0))]),
+ Llet(StrictOpt, obj_init, lfield inh 0,
+ Llet(Alias, inh_vals, lfield inh 1,
+- Llet(Alias, inh_meths, lfield inh 2, cl_init)))))
++ Llet(Alias, inh_meths, lfield inh 2, cl_init)))),
++ [], [])
+ | _ ->
+ let core cl_init =
+ build_class_init cla true super inh_init cl_init msubst top cl
+ in
+ if cstr then core cl_init else
+- let (inh_init, cl_init) =
+- core (Lsequence (Lapply (oo_prim "widen", [Lvar cla]), cl_init))
++ let (inh_init, cl_init, methods, values) =
++ core (Lsequence (lprim "widen" [Lvar cla], cl_init))
+ in
+- (inh_init,
+- Lsequence(Lapply (oo_prim "narrow", narrow_args), cl_init))
++ let cl_init = bind_methods cla methods values cl_init in
++ (inh_init, Lsequence(lprim "narrow" narrow_args, cl_init), [], [])
+ end
+
++let build_class_init cla env inh_init obj_init msubst top cl =
++ let inh_init = List.rev inh_init in
++ let (inh_init, cl_init, methods, values) =
++ build_class_init cla true ([],[]) inh_init obj_init msubst top cl in
++ assert (inh_init = []);
++ if IdentSet.mem env (free_variables ~ifused:true cl_init)
++ then bind_methods cla methods (("", env) :: values) cl_init
++ else Llet(Alias, env, lambda_unit, bind_methods cla methods values cl_init)
++
+ let rec build_class_lets cl =
+ match cl.cl_desc with
+ Tclass_let (rec_flag, defs, vals, cl) ->
+@@ -459,16 +479,16 @@
+ Strict, new_init, lfunction [obj_init] obj_init',
+ Llet(
+ Alias, cla, transl_path path,
+- Lprim(Pmakeblock(0, Immutable),
+- [Lapply(Lvar new_init, [lfield cla 0]);
+- lfunction [table]
+- (Llet(Strict, env_init,
+- Lapply(lfield cla 1, [Lvar table]),
+- lfunction [envs]
+- (Lapply(Lvar new_init,
+- [Lapply(Lvar env_init, [Lvar envs])]))));
+- lfield cla 2;
+- lfield cla 3])))
++ ltuple
++ [Lapply(Lvar new_init, [lfield cla 0]);
++ lfunction [table]
++ (Llet(Strict, env_init,
++ Lapply(lfield cla 1, [Lvar table]),
++ lfunction [envs]
++ (Lapply(Lvar new_init,
++ [Lapply(Lvar env_init, [Lvar envs])]))));
++ lfield cla 2;
++ lfield cla 3]))
+ with Exit ->
+ lambda_unit
+
+@@ -541,7 +561,7 @@
+ open CamlinternalOO
+ let builtin_meths arr self env env2 body =
+ let builtin, args = builtin_meths self env env2 body in
+- if not arr then [Lapply(oo_prim builtin, args)] else
++ if not arr then [lprim builtin args] else
+ let tag = match builtin with
+ "get_const" -> GetConst
+ | "get_var" -> GetVar
+@@ -599,7 +619,8 @@
+
+ (* Prepare for heavy environment handling *)
+ let tables = Ident.create (Ident.name cl_id ^ "_tables") in
+- let (top_env, req) = oo_add_class tables in
++ let table_init = ref None in
++ let (top_env, req) = oo_add_class tables table_init in
+ let top = not req in
+ let cl_env, llets = build_class_lets cl in
+ let new_ids = if top then [] else Env.diff top_env cl_env in
+@@ -633,6 +654,7 @@
+ begin try
+ (* Doesn't seem to improve size for bytecode *)
+ (* if not !Clflags.native_code then raise Not_found; *)
++ if !Clflags.debug then raise Not_found;
+ builtin_meths arr [self] env env2 (lfunction args body')
+ with Not_found ->
+ [lfunction (self :: args)
+@@ -665,15 +687,8 @@
+ build_object_init_0 cla [] cl copy_env subst_env top ids in
+ if not (Translcore.check_recursive_lambda ids obj_init) then
+ raise(Error(cl.cl_loc, Illegal_class_expr));
+- let inh_init' = List.rev inh_init in
+- let (inh_init', cl_init) =
+- build_class_init cla true ([],[]) inh_init' obj_init msubst top cl
+- in
+- assert (inh_init' = []);
+- let table = Ident.create "table"
+- and class_init = Ident.create (Ident.name cl_id ^ "_init")
+- and env_init = Ident.create "env_init"
+- and obj_init = Ident.create "obj_init" in
++ let cl_init = build_class_init cla env2 inh_init obj_init msubst top cl in
++ let obj_init = Ident.create "obj_init" in
+ let pub_meths =
+ List.sort
+ (fun s s' -> compare (Btype.hash_variant s) (Btype.hash_variant s'))
+@@ -685,42 +700,44 @@
+ let name' = List.assoc tag rev_map in
+ if name' <> name then raise(Error(cl.cl_loc, Tags(name, name'))))
+ tags pub_meths;
++ let pos = cl.cl_loc.Location.loc_end in
++ let filepos = [transl_label pos.Lexing.pos_fname;
++ Lconst(Const_base(Const_int pos.Lexing.pos_cnum))] in
+ let ltable table lam =
+- Llet(Strict, table,
+- Lapply (oo_prim "create_table", [transl_meth_list pub_meths]), lam)
++ Llet(Strict, table, lprim "create_table" [transl_meth_list pub_meths], lam)
+ and ldirect obj_init =
+ Llet(Strict, obj_init, cl_init,
+- Lsequence(Lapply (oo_prim "init_class", [Lvar cla]),
++ Lsequence(lprim "init_class_shared" (Lvar cla :: filepos),
+ Lapply(Lvar obj_init, [lambda_unit])))
+ in
+ (* Simplest case: an object defined at toplevel (ids=[]) *)
+ if top && ids = [] then llets (ltable cla (ldirect obj_init)) else
+
++ let table = Ident.create "table"
++ and class_init = Ident.create (Ident.name cl_id ^ "_init")
++ and env_init = Ident.create (Ident.name cl_id ^ "_env_init") in
++ let cl_init_fun = Lfunction(Curried, [cla], cl_init) in
+ let concrete =
+ ids = [] ||
+ Typeclass.virtual_methods (Ctype.signature_of_class_type cl.cl_type) = []
+- and lclass lam =
+- let cl_init = llets (Lfunction(Curried, [cla], cl_init)) in
++ and lclass cl_init lam =
+ Llet(Strict, class_init, cl_init, lam (free_variables cl_init))
+ and lbody fv =
+ if List.for_all (fun id -> not (IdentSet.mem id fv)) ids then
+- Lapply (oo_prim "make_class",[transl_meth_list pub_meths;
+- Lvar class_init])
++ lprim "make_class"
++ (transl_meth_list pub_meths :: Lvar class_init :: filepos)
+ else
+ ltable table (
+ Llet(
+ Strict, env_init, Lapply(Lvar class_init, [Lvar table]),
+- Lsequence(
+- Lapply (oo_prim "init_class", [Lvar table]),
+- Lprim(Pmakeblock(0, Immutable),
+- [Lapply(Lvar env_init, [lambda_unit]);
+- Lvar class_init; Lvar env_init; lambda_unit]))))
++ Lsequence(lprim "init_class_shared" (Lvar table :: filepos),
++ ltuple [Lapply(Lvar env_init, [lambda_unit]);
++ Lvar class_init; Lvar env_init; lambda_unit])))
+ and lbody_virt lenvs =
+- Lprim(Pmakeblock(0, Immutable),
+- [lambda_unit; Lfunction(Curried,[cla], cl_init); lambda_unit; lenvs])
++ ltuple [lambda_unit; cl_init_fun; lambda_unit; lenvs]
+ in
+ (* Still easy: a class defined at toplevel *)
+- if top && concrete then lclass lbody else
++ if top && concrete then lclass (llets cl_init_fun) lbody else
+ if top then llets (lbody_virt lambda_unit) else
+
+ (* Now for the hard stuff: prepare for table cacheing *)
+@@ -733,23 +750,16 @@
+ let lenv =
+ let menv =
+ if !new_ids_meths = [] then lambda_unit else
+- Lprim(Pmakeblock(0, Immutable),
+- List.map (fun id -> Lvar id) !new_ids_meths) in
++ ltuple (List.map (fun id -> Lvar id) !new_ids_meths) in
+ if !new_ids_init = [] then menv else
+- Lprim(Pmakeblock(0, Immutable),
+- menv :: List.map (fun id -> Lvar id) !new_ids_init)
++ ltuple (menv :: List.map (fun id -> Lvar id) !new_ids_init)
+ and linh_envs =
+ List.map (fun (_, p) -> Lprim(Pfield 3, [transl_path p]))
+ (List.rev inh_init)
+ in
+ let make_envs lam =
+ Llet(StrictOpt, envs,
+- (if linh_envs = [] then lenv else
+- Lprim(Pmakeblock(0, Immutable), lenv :: linh_envs)),
+- lam)
+- and def_ids cla lam =
+- Llet(StrictOpt, env2,
+- Lapply (oo_prim "new_variable", [Lvar cla; transl_label ""]),
++ (if linh_envs = [] then lenv else ltuple (lenv :: linh_envs)),
+ lam)
+ in
+ let inh_paths =
+@@ -757,46 +767,53 @@
+ (fun (_,path) -> List.mem (Path.head path) new_ids) inh_init in
+ let inh_keys =
+ List.map (fun (_,p) -> Lprim(Pfield 1, [transl_path p])) inh_paths in
+- let lclass lam =
+- Llet(Strict, class_init,
+- Lfunction(Curried, [cla], def_ids cla cl_init), lam)
++ let lclass_init lam =
++ Llet(Strict, class_init, cl_init_fun, lam)
+ and lcache lam =
+ if inh_keys = [] then Llet(Alias, cached, Lvar tables, lam) else
+- Llet(Strict, cached,
+- Lapply(oo_prim "lookup_tables",
+- [Lvar tables; Lprim(Pmakeblock(0, Immutable), inh_keys)]),
++ Llet(Strict, cached, lprim "lookup_tables" [Lvar tables; ltuple inh_keys],
+ lam)
+ and lset cached i lam =
+ Lprim(Psetfield(i, true), [Lvar cached; lam])
+ in
+- let ldirect () =
+- ltable cla
+- (Llet(Strict, env_init, def_ids cla cl_init,
+- Lsequence(Lapply (oo_prim "init_class", [Lvar cla]),
+- lset cached 0 (Lvar env_init))))
+- and lclass_virt () =
+- lset cached 0 (Lfunction(Curried, [cla], def_ids cla cl_init))
++ let ldirect prim pos =
++ ltable cla (
++ Llet(Strict, env_init, cl_init,
++ Lsequence(lprim prim (Lvar cla :: pos), Lvar env_init)))
++ and lclass_concrete cached =
++ ltuple [Lapply (lfield cached 0, [lenvs]);
++ lfield cached 1; lfield cached 0; lenvs]
+ in
++
+ llets (
+- lcache (
+- Lsequence(
+- Lifthenelse(lfield cached 0, lambda_unit,
+- if ids = [] then ldirect () else
+- if not concrete then lclass_virt () else
+- lclass (
+- Lapply (oo_prim "make_class_store",
+- [transl_meth_list pub_meths;
+- Lvar class_init; Lvar cached]))),
+ make_envs (
+- if ids = [] then Lapply(lfield cached 0, [lenvs]) else
+- Lprim(Pmakeblock(0, Immutable),
+- if concrete then
+- [Lapply(lfield cached 0, [lenvs]);
+- lfield cached 1;
+- lfield cached 0;
+- lenvs]
+- else [lambda_unit; lfield cached 0; lambda_unit; lenvs]
+- )))))
++ if inh_paths = [] && concrete then
++ if ids = [] then begin
++ table_init := Some (ldirect "init_class_shared" filepos);
++ Lapply (Lvar tables, [lenvs])
++ end else begin
++ let init =
++ lclass cl_init_fun (fun _ ->
++ lprim "make_class_env"
++ (transl_meth_list pub_meths :: Lvar class_init :: filepos))
++ in table_init := Some init;
++ lclass_concrete tables
++ end
++ else begin
++ lcache (
++ Lsequence(
++ Lifthenelse(lfield cached 0, lambda_unit,
++ if ids = [] then lset cached 0 (ldirect "init_class" []) else
++ if not concrete then lset cached 0 cl_init_fun else
++ lclass_init (
++ lprim "make_class_store"
++ [transl_meth_list pub_meths; Lvar class_init; Lvar cached])),
++ llets (
++ make_envs (
++ if ids = [] then Lapply(lfield cached 0, [lenvs]) else
++ if concrete then lclass_concrete cached else
++ ltuple [lambda_unit; lfield cached 0; lambda_unit; lenvs]))))
++ end))
+
+ (* Wrapper for class compilation *)
+
+Index: bytecomp/translobj.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/translobj.ml,v
+retrieving revision 1.9
+diff -u -r1.9 translobj.ml
+--- bytecomp/translobj.ml 26 May 2004 11:10:51 -0000 1.9
++++ bytecomp/translobj.ml 2 Feb 2006 05:08:56 -0000
+@@ -88,7 +88,6 @@
+
+ (* Insert labels *)
+
+-let string s = Lconst (Const_base (Const_string s))
+ let int n = Lconst (Const_base (Const_int n))
+
+ let prim_makearray =
+@@ -124,8 +123,8 @@
+ let top_env = ref Env.empty
+ let classes = ref []
+
+-let oo_add_class id =
+- classes := id :: !classes;
++let oo_add_class id init =
++ classes := (id, init) :: !classes;
+ (!top_env, !cache_required)
+
+ let oo_wrap env req f x =
+@@ -141,10 +140,12 @@
+ let lambda = f x in
+ let lambda =
+ List.fold_left
+- (fun lambda id ->
++ (fun lambda (id, init) ->
+ Llet(StrictOpt, id,
+- Lprim(Pmakeblock(0, Mutable),
+- [lambda_unit; lambda_unit; lambda_unit]),
++ (match !init with
++ Some lam -> lam
++ | None -> Lprim(Pmakeblock(0, Mutable),
++ [lambda_unit; lambda_unit; lambda_unit])),
+ lambda))
+ lambda !classes
+ in
+Index: bytecomp/translobj.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/translobj.mli,v
+retrieving revision 1.6
+diff -u -r1.6 translobj.mli
+--- bytecomp/translobj.mli 26 May 2004 11:10:51 -0000 1.6
++++ bytecomp/translobj.mli 2 Feb 2006 05:08:56 -0000
+@@ -25,4 +25,4 @@
+ Ident.t -> int -> ('a -> lambda) -> 'a -> int * lambda
+
+ val oo_wrap: Env.t -> bool -> ('a -> lambda) -> 'a -> lambda
+-val oo_add_class: Ident.t -> Env.t * bool
++val oo_add_class: Ident.t -> Lambda.lambda option ref -> Env.t * bool
+Index: byterun/compare.h
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/byterun/compare.h,v
+retrieving revision 1.2
+diff -u -r1.2 compare.h
+--- byterun/compare.h 31 Dec 2003 14:20:35 -0000 1.2
++++ byterun/compare.h 2 Feb 2006 05:08:56 -0000
+@@ -17,5 +17,6 @@
+ #define CAML_COMPARE_H
+
+ CAMLextern int caml_compare_unordered;
++CAMLextern value caml_compare(value, value);
+
+ #endif /* CAML_COMPARE_H */
+Index: byterun/extern.c
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/byterun/extern.c,v
+retrieving revision 1.59
+diff -u -r1.59 extern.c
+--- byterun/extern.c 4 Jan 2006 16:55:49 -0000 1.59
++++ byterun/extern.c 2 Feb 2006 05:08:56 -0000
+@@ -411,6 +411,22 @@
+ extern_record_location(v);
+ break;
+ }
++ case Object_tag: {
++ value field0;
++ mlsize_t i;
++ i = Wosize_val(Field(v, 0)) - 1;
++ field0 = Field(Field(v, 0),i);
++ if (Wosize_val(field0) > 0) {
++ writecode32(CODE_OBJECT, Wosize_hd (hd));
++ extern_record_location(v);
++ extern_rec(field0);
++ for (i = 1; i < sz - 1; i++) extern_rec(Field(v, i));
++ v = Field(v, i);
++ goto tailcall;
++ }
++ if (!extern_closures)
++ extern_invalid_argument("output_value: dynamic class");
++ } /* may fall through */
+ default: {
+ value field0;
+ mlsize_t i;
+Index: byterun/intern.c
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/byterun/intern.c,v
+retrieving revision 1.60
+diff -u -r1.60 intern.c
+--- byterun/intern.c 22 Sep 2005 14:21:50 -0000 1.60
++++ byterun/intern.c 2 Feb 2006 05:08:56 -0000
+@@ -28,6 +28,8 @@
+ #include "mlvalues.h"
+ #include "misc.h"
+ #include "reverse.h"
++#include "callback.h"
++#include "compare.h"
+
+ static unsigned char * intern_src;
+ /* Reading pointer in block holding input data. */
+@@ -98,6 +100,25 @@
+ #define readblock(dest,len) \
+ (memmove((dest), intern_src, (len)), intern_src += (len))
+
++static value get_method_table (value key)
++{
++ static value *classes = NULL;
++ value current;
++ if (classes == NULL) {
++ classes = caml_named_value("caml_oo_classes");
++ if (classes == NULL) return 0;
++ caml_register_global_root(classes);
++ }
++ for (current = Field(*classes, 0); Is_block(current);
++ current = Field(current, 1))
++ {
++ value head = Field(current, 0);
++ if (caml_compare(key, Field(head, 0)) == Val_int(0))
++ return Field(head, 1);
++ }
++ return 0;
++}
++
+ static void intern_cleanup(void)
+ {
+ if (intern_input_malloced) caml_stat_free(intern_input);
+@@ -315,6 +336,24 @@
+ Custom_ops_val(v) = ops;
+ intern_dest += 1 + size;
+ break;
++ case CODE_OBJECT:
++ size = read32u();
++ v = Val_hp(intern_dest);
++ *dest = v;
++ if (intern_obj_table != NULL) intern_obj_table[obj_counter++] = v;
++ dest = (value *) (intern_dest + 1);
++ *intern_dest = Make_header(size, Object_tag, intern_color);
++ intern_dest += 1 + size;
++ intern_rec(dest);
++ *dest = get_method_table(*dest);
++ if (*dest == 0) {
++ intern_cleanup();
++ caml_failwith("input_value: unknown class");
++ }
++ for(size--, dest++; size > 1; size--, dest++)
++ intern_rec(dest);
++ goto tailcall;
++
+ default:
+ intern_cleanup();
+ caml_failwith("input_value: ill-formed message");
+Index: byterun/intext.h
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/byterun/intext.h,v
+retrieving revision 1.32
+diff -u -r1.32 intext.h
+--- byterun/intext.h 22 Sep 2005 14:21:50 -0000 1.32
++++ byterun/intext.h 2 Feb 2006 05:08:56 -0000
+@@ -56,6 +56,7 @@
+ #define CODE_CODEPOINTER 0x10
+ #define CODE_INFIXPOINTER 0x11
+ #define CODE_CUSTOM 0x12
++#define CODE_OBJECT 0x14
+
+ #if ARCH_FLOAT_ENDIANNESS == 0x76543210
+ #define CODE_DOUBLE_NATIVE CODE_DOUBLE_BIG
+Index: stdlib/camlinternalOO.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/stdlib/camlinternalOO.ml,v
+retrieving revision 1.14
+diff -u -r1.14 camlinternalOO.ml
+--- stdlib/camlinternalOO.ml 25 Oct 2005 18:34:07 -0000 1.14
++++ stdlib/camlinternalOO.ml 2 Feb 2006 05:08:56 -0000
+@@ -305,10 +305,38 @@
+ public_methods;
+ table
+
++(*
++let create_table_variables pub_meths priv_meths vars =
++ let tbl = create_table pub_meths in
++ let pub_meths = to_array pub_meths
++ and priv_meths = to_array priv_meths
++ and vars = to_array vars in
++ let len = 2 + Array.length pub_meths + Array.length priv_meths in
++ let res = Array.create len tbl in
++ let mv = new_methods_variables tbl pub_meths vars in
++ Array.blit mv 0 res 1;
++ res
++*)
++
+ let init_class table =
+ inst_var_count := !inst_var_count + table.size - 1;
+ table.initializers <- List.rev table.initializers;
+- resize table (3 + magic table.methods.(1) * 16 / Sys.word_size)
++ let len = 3 + magic table.methods.(1) * 16 / Sys.word_size in
++ (* keep 1 more for extra info *)
++ let len = if len > Array.length table.methods then len else len+1 in
++ resize table len
++
++let classes = ref []
++let () = Callback.register "caml_oo_classes" classes
++
++let init_class_shared table (file : string) (pos : int) =
++ init_class table;
++ let rec unique_pos pos =
++ if List.mem_assoc (file, pos) !classes then unique_pos (pos + 0x100000)
++ else pos in
++ let pos = unique_pos pos in
++ table.methods.(Array.length table.methods - 1) <- Obj.magic (file, pos);
++ classes := ((file, pos), table.methods) :: !classes
+
+ let inherits cla vals virt_meths concr_meths (_, super, _, env) top =
+ narrow cla vals virt_meths concr_meths;
+@@ -319,12 +347,18 @@
+ Array.map (fun nm -> get_method cla (get_method_label cla nm))
+ (to_array concr_meths))
+
+-let make_class pub_meths class_init =
++let make_class pub_meths class_init file pos =
+ let table = create_table pub_meths in
+ let env_init = class_init table in
+- init_class table;
++ init_class_shared table file pos;
+ (env_init (Obj.repr 0), class_init, env_init, Obj.repr 0)
+
++let make_class_env pub_meths class_init file pos =
++ let table = create_table pub_meths in
++ let env_init = class_init table in
++ init_class_shared table file pos;
++ (env_init, class_init)
++
+ type init_table = { mutable env_init: t; mutable class_init: table -> t }
+
+ let make_class_store pub_meths class_init init_table =
+Index: stdlib/camlinternalOO.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/stdlib/camlinternalOO.mli,v
+retrieving revision 1.9
+diff -u -r1.9 camlinternalOO.mli
+--- stdlib/camlinternalOO.mli 25 Oct 2005 18:34:07 -0000 1.9
++++ stdlib/camlinternalOO.mli 2 Feb 2006 05:08:56 -0000
+@@ -43,14 +43,20 @@
+ val add_initializer : table -> (obj -> unit) -> unit
+ val dummy_table : table
+ val create_table : string array -> table
++(* val create_table_variables :
++ string array -> string array -> string array -> table *)
+ val init_class : table -> unit
++val init_class_shared : table -> string -> int -> unit
+ val inherits :
+ table -> string array -> string array -> string array ->
+ (t * (table -> obj -> Obj.t) * t * obj) -> bool ->
+ (Obj.t * int array * closure array)
+ val make_class :
+- string array -> (table -> Obj.t -> t) ->
++ string array -> (table -> Obj.t -> t) -> string -> int ->
+ (t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t)
++val make_class_env :
++ string array -> (table -> Obj.t -> t) -> string -> int ->
++ (Obj.t -> t) * (table -> Obj.t -> t)
+ type init_table
+ val make_class_store :
+ string array -> (table -> t) -> init_table -> unit
diff --git a/experimental/garrigue/module-errors.diff b/experimental/garrigue/module-errors.diff
new file mode 100644
index 0000000000..2f8c2bc282
--- /dev/null
+++ b/experimental/garrigue/module-errors.diff
@@ -0,0 +1,403 @@
+Index: typing/includemod.ml
+===================================================================
+--- typing/includemod.ml (revision 11161)
++++ typing/includemod.ml (working copy)
+@@ -19,7 +19,7 @@
+ open Types
+ open Typedtree
+
+-type error =
++type symptom =
+ Missing_field of Ident.t
+ | Value_descriptions of Ident.t * value_description * value_description
+ | Type_declarations of Ident.t * type_declaration
+@@ -38,6 +38,10 @@
+ Ctype.class_match_failure list
+ | Unbound_modtype_path of Path.t
+
++type pos =
++ Module of Ident.t | Modtype of Ident.t | Arg of Ident.t | Body of Ident.t
++type error = pos list * symptom
++
+ exception Error of error list
+
+ (* All functions "blah env x1 x2" check that x1 is included in x2,
+@@ -46,51 +50,52 @@
+
+ (* Inclusion between value descriptions *)
+
+-let value_descriptions env subst id vd1 vd2 =
++let value_descriptions env cxt subst id vd1 vd2 =
+ let vd2 = Subst.value_description subst vd2 in
+ try
+ Includecore.value_descriptions env vd1 vd2
+ with Includecore.Dont_match ->
+- raise(Error[Value_descriptions(id, vd1, vd2)])
++ raise(Error[cxt, Value_descriptions(id, vd1, vd2)])
+
+ (* Inclusion between type declarations *)
+
+-let type_declarations env subst id decl1 decl2 =
++let type_declarations env cxt subst id decl1 decl2 =
+ let decl2 = Subst.type_declaration subst decl2 in
+ let err = Includecore.type_declarations env id decl1 decl2 in
+- if err <> [] then raise(Error[Type_declarations(id, decl1, decl2, err)])
++ if err <> [] then raise(Error[cxt, Type_declarations(id, decl1, decl2, err)])
+
+ (* Inclusion between exception declarations *)
+
+-let exception_declarations env subst id decl1 decl2 =
++let exception_declarations env cxt subst id decl1 decl2 =
+ let decl2 = Subst.exception_declaration subst decl2 in
+ if Includecore.exception_declarations env decl1 decl2
+ then ()
+- else raise(Error[Exception_declarations(id, decl1, decl2)])
++ else raise(Error[cxt, Exception_declarations(id, decl1, decl2)])
+
+ (* Inclusion between class declarations *)
+
+-let class_type_declarations env subst id decl1 decl2 =
++let class_type_declarations env cxt subst id decl1 decl2 =
+ let decl2 = Subst.cltype_declaration subst decl2 in
+ match Includeclass.class_type_declarations env decl1 decl2 with
+ [] -> ()
+- | reason -> raise(Error[Class_type_declarations(id, decl1, decl2, reason)])
++ | reason ->
++ raise(Error[cxt, Class_type_declarations(id, decl1, decl2, reason)])
+
+-let class_declarations env subst id decl1 decl2 =
++let class_declarations env cxt subst id decl1 decl2 =
+ let decl2 = Subst.class_declaration subst decl2 in
+ match Includeclass.class_declarations env decl1 decl2 with
+ [] -> ()
+- | reason -> raise(Error[Class_declarations(id, decl1, decl2, reason)])
++ | reason -> raise(Error[cxt, Class_declarations(id, decl1, decl2, reason)])
+
+ (* Expand a module type identifier when possible *)
+
+ exception Dont_match
+
+-let expand_module_path env path =
++let expand_module_path env cxt path =
+ try
+ Env.find_modtype_expansion path env
+ with Not_found ->
+- raise(Error[Unbound_modtype_path path])
++ raise(Error[cxt, Unbound_modtype_path path])
+
+ (* Extract name, kind and ident from a signature item *)
+
+@@ -128,28 +133,29 @@
+ Return the restriction that transforms a value of the smaller type
+ into a value of the bigger type. *)
+
+-let rec modtypes env subst mty1 mty2 =
++let rec modtypes env cxt subst mty1 mty2 =
+ try
+- try_modtypes env subst mty1 mty2
++ try_modtypes env cxt subst mty1 mty2
+ with
+ Dont_match ->
+- raise(Error[Module_types(mty1, Subst.modtype subst mty2)])
++ raise(Error[cxt, Module_types(mty1, Subst.modtype subst mty2)])
+ | Error reasons ->
+- raise(Error(Module_types(mty1, Subst.modtype subst mty2) :: reasons))
++ raise(Error((cxt, Module_types(mty1, Subst.modtype subst mty2))
++ :: reasons))
+
+-and try_modtypes env subst mty1 mty2 =
++and try_modtypes env cxt subst mty1 mty2 =
+ match (mty1, mty2) with
+ (_, Tmty_ident p2) ->
+- try_modtypes2 env mty1 (Subst.modtype subst mty2)
++ try_modtypes2 env cxt mty1 (Subst.modtype subst mty2)
+ | (Tmty_ident p1, _) ->
+- try_modtypes env subst (expand_module_path env p1) mty2
++ try_modtypes env cxt subst (expand_module_path env cxt p1) mty2
+ | (Tmty_signature sig1, Tmty_signature sig2) ->
+- signatures env subst sig1 sig2
++ signatures env cxt subst sig1 sig2
+ | (Tmty_functor(param1, arg1, res1), Tmty_functor(param2, arg2, res2)) ->
+ let arg2' = Subst.modtype subst arg2 in
+- let cc_arg = modtypes env Subst.identity arg2' arg1 in
++ let cc_arg = modtypes env (Arg param1::cxt) Subst.identity arg2' arg1 in
+ let cc_res =
+- modtypes (Env.add_module param1 arg2' env)
++ modtypes (Env.add_module param1 arg2' env) (Body param1::cxt)
+ (Subst.add_module param2 (Pident param1) subst) res1 res2 in
+ begin match (cc_arg, cc_res) with
+ (Tcoerce_none, Tcoerce_none) -> Tcoerce_none
+@@ -158,19 +164,19 @@
+ | (_, _) ->
+ raise Dont_match
+
+-and try_modtypes2 env mty1 mty2 =
++and try_modtypes2 env cxt mty1 mty2 =
+ (* mty2 is an identifier *)
+ match (mty1, mty2) with
+ (Tmty_ident p1, Tmty_ident p2) when Path.same p1 p2 ->
+ Tcoerce_none
+ | (_, Tmty_ident p2) ->
+- try_modtypes env Subst.identity mty1 (expand_module_path env p2)
++ try_modtypes env cxt Subst.identity mty1 (expand_module_path env cxt p2)
+ | (_, _) ->
+ assert false
+
+ (* Inclusion between signatures *)
+
+-and signatures env subst sig1 sig2 =
++and signatures env cxt subst sig1 sig2 =
+ (* Environment used to check inclusion of components *)
+ let new_env =
+ Env.add_signature sig1 env in
+@@ -202,7 +208,7 @@
+ let rec pair_components subst paired unpaired = function
+ [] ->
+ begin match unpaired with
+- [] -> signature_components new_env subst (List.rev paired)
++ [] -> signature_components new_env cxt subst (List.rev paired)
+ | _ -> raise(Error unpaired)
+ end
+ | item2 :: rem ->
+@@ -234,7 +240,7 @@
+ ((item1, item2, pos1) :: paired) unpaired rem
+ with Not_found ->
+ let unpaired =
+- if report then Missing_field id2 :: unpaired else unpaired in
++ if report then (cxt, Missing_field id2) :: unpaired else unpaired in
+ pair_components subst paired unpaired rem
+ end in
+ (* Do the pairing and checking, and return the final coercion *)
+@@ -242,65 +248,67 @@
+
+ (* Inclusion between signature components *)
+
+-and signature_components env subst = function
++and signature_components env cxt subst = function
+ [] -> []
+ | (Tsig_value(id1, valdecl1), Tsig_value(id2, valdecl2), pos) :: rem ->
+- let cc = value_descriptions env subst id1 valdecl1 valdecl2 in
++ let cc = value_descriptions env cxt subst id1 valdecl1 valdecl2 in
+ begin match valdecl2.val_kind with
+- Val_prim p -> signature_components env subst rem
+- | _ -> (pos, cc) :: signature_components env subst rem
++ Val_prim p -> signature_components env cxt subst rem
++ | _ -> (pos, cc) :: signature_components env cxt subst rem
+ end
+ | (Tsig_type(id1, tydecl1, _), Tsig_type(id2, tydecl2, _), pos) :: rem ->
+- type_declarations env subst id1 tydecl1 tydecl2;
+- signature_components env subst rem
++ type_declarations env cxt subst id1 tydecl1 tydecl2;
++ signature_components env cxt subst rem
+ | (Tsig_exception(id1, excdecl1), Tsig_exception(id2, excdecl2), pos)
+ :: rem ->
+- exception_declarations env subst id1 excdecl1 excdecl2;
+- (pos, Tcoerce_none) :: signature_components env subst rem
++ exception_declarations env cxt subst id1 excdecl1 excdecl2;
++ (pos, Tcoerce_none) :: signature_components env cxt subst rem
+ | (Tsig_module(id1, mty1, _), Tsig_module(id2, mty2, _), pos) :: rem ->
+ let cc =
+- modtypes env subst (Mtype.strengthen env mty1 (Pident id1)) mty2 in
+- (pos, cc) :: signature_components env subst rem
++ modtypes env (Module id1::cxt) subst
++ (Mtype.strengthen env mty1 (Pident id1)) mty2 in
++ (pos, cc) :: signature_components env cxt subst rem
+ | (Tsig_modtype(id1, info1), Tsig_modtype(id2, info2), pos) :: rem ->
+- modtype_infos env subst id1 info1 info2;
+- signature_components env subst rem
++ modtype_infos env cxt subst id1 info1 info2;
++ signature_components env cxt subst rem
+ | (Tsig_class(id1, decl1, _), Tsig_class(id2, decl2, _), pos) :: rem ->
+- class_declarations env subst id1 decl1 decl2;
+- (pos, Tcoerce_none) :: signature_components env subst rem
++ class_declarations env cxt subst id1 decl1 decl2;
++ (pos, Tcoerce_none) :: signature_components env cxt subst rem
+ | (Tsig_cltype(id1, info1, _), Tsig_cltype(id2, info2, _), pos) :: rem ->
+- class_type_declarations env subst id1 info1 info2;
+- signature_components env subst rem
++ class_type_declarations env cxt subst id1 info1 info2;
++ signature_components env cxt subst rem
+ | _ ->
+ assert false
+
+ (* Inclusion between module type specifications *)
+
+-and modtype_infos env subst id info1 info2 =
++and modtype_infos env cxt subst id info1 info2 =
+ let info2 = Subst.modtype_declaration subst info2 in
++ let cxt' = Modtype id :: cxt in
+ try
+ match (info1, info2) with
+ (Tmodtype_abstract, Tmodtype_abstract) -> ()
+ | (Tmodtype_manifest mty1, Tmodtype_abstract) -> ()
+ | (Tmodtype_manifest mty1, Tmodtype_manifest mty2) ->
+- check_modtype_equiv env mty1 mty2
++ check_modtype_equiv env cxt' mty1 mty2
+ | (Tmodtype_abstract, Tmodtype_manifest mty2) ->
+- check_modtype_equiv env (Tmty_ident(Pident id)) mty2
++ check_modtype_equiv env cxt' (Tmty_ident(Pident id)) mty2
+ with Error reasons ->
+- raise(Error(Modtype_infos(id, info1, info2) :: reasons))
++ raise(Error((cxt, Modtype_infos(id, info1, info2)) :: reasons))
+
+-and check_modtype_equiv env mty1 mty2 =
++and check_modtype_equiv env cxt mty1 mty2 =
+ match
+- (modtypes env Subst.identity mty1 mty2,
+- modtypes env Subst.identity mty2 mty1)
++ (modtypes env cxt Subst.identity mty1 mty2,
++ modtypes env cxt Subst.identity mty2 mty1)
+ with
+ (Tcoerce_none, Tcoerce_none) -> ()
+- | (_, _) -> raise(Error [Modtype_permutation])
++ | (_, _) -> raise(Error [cxt, Modtype_permutation])
+
+ (* Simplified inclusion check between module types (for Env) *)
+
+ let check_modtype_inclusion env mty1 path1 mty2 =
+ try
+- ignore(modtypes env Subst.identity
++ ignore(modtypes env [] Subst.identity
+ (Mtype.strengthen env mty1 path1) mty2)
+ with Error reasons ->
+ raise Not_found
+@@ -312,16 +320,16 @@
+
+ let compunit impl_name impl_sig intf_name intf_sig =
+ try
+- signatures Env.initial Subst.identity impl_sig intf_sig
++ signatures Env.initial [] Subst.identity impl_sig intf_sig
+ with Error reasons ->
+- raise(Error(Interface_mismatch(impl_name, intf_name) :: reasons))
++ raise(Error(([], Interface_mismatch(impl_name, intf_name)) :: reasons))
+
+-(* Hide the substitution parameter to the outside world *)
++(* Hide the context and substitution parameters to the outside world *)
+
+-let modtypes env mty1 mty2 = modtypes env Subst.identity mty1 mty2
+-let signatures env sig1 sig2 = signatures env Subst.identity sig1 sig2
++let modtypes env mty1 mty2 = modtypes env [] Subst.identity mty1 mty2
++let signatures env sig1 sig2 = signatures env [] Subst.identity sig1 sig2
+ let type_declarations env id decl1 decl2 =
+- type_declarations env Subst.identity id decl1 decl2
++ type_declarations env [] Subst.identity id decl1 decl2
+
+ (* Error report *)
+
+@@ -384,9 +392,62 @@
+ | Unbound_modtype_path path ->
+ fprintf ppf "Unbound module type %a" Printtyp.path path
+
+-let report_error ppf = function
+- | [] -> ()
+- | err :: errs ->
+- let print_errs ppf errs =
+- List.iter (fun err -> fprintf ppf "@ %a" include_err err) errs in
+- fprintf ppf "@[<v>%a%a@]" include_err err print_errs errs
++let rec context ppf = function
++ Module id :: rem ->
++ fprintf ppf "@[<2>module %a%a@]" ident id args rem
++ | Modtype id :: rem ->
++ fprintf ppf "@[<2>module type %a =@ %a@]" ident id context_mty rem
++ | Body x :: rem ->
++ fprintf ppf "functor (%a) ->@ %a" ident x context_mty rem
++ | Arg x :: rem ->
++ fprintf ppf "functor (%a : %a) -> ..." ident x context_mty rem
++ | [] ->
++ fprintf ppf "<here>"
++and context_mty ppf = function
++ (Module _ | Modtype _) :: _ as rem ->
++ fprintf ppf "@[<2>sig@ %a@;<1 -2>end@]" context rem
++ | cxt -> context ppf cxt
++and args ppf = function
++ Body x :: rem ->
++ fprintf ppf "(%a)%a" ident x args rem
++ | Arg x :: rem ->
++ fprintf ppf "(%a :@ %a) : ..." ident x context_mty rem
++ | cxt ->
++ fprintf ppf " :@ %a" context_mty cxt
++
++let path_of_context = function
++ Module id :: rem ->
++ let rec subm path = function
++ [] -> path
++ | Module id :: rem -> subm (Pdot (path, Ident.name id, -1)) rem
++ | _ -> assert false
++ in subm (Pident id) rem
++ | _ -> assert false
++
++let context ppf cxt =
++ if cxt = [] then () else
++ if List.for_all (function Module _ -> true | _ -> false) cxt then
++ fprintf ppf "In module %a:@ " path (path_of_context cxt)
++ else
++ fprintf ppf "@[<hv 2>At position@ %a@]@ " context cxt
++
++let include_err ppf (cxt, err) =
++ fprintf ppf "@[<v>%a%a@]" context (List.rev cxt) include_err err
++
++let max_size = 500
++let buffer = String.create max_size
++let is_big obj =
++ try ignore (Marshal.to_buffer buffer 0 max_size obj []); false
++ with _ -> true
++
++let report_error ppf errs =
++ if errs = [] then () else
++ let (errs , err) = split_last errs in
++ let pe = ref true in
++ let include_err' ppf err =
++ if !Clflags.show_trace || not (is_big err) then
++ fprintf ppf "%a@ " include_err err
++ else if !pe then (fprintf ppf "...@ "; pe := false)
++ in
++ let print_errs ppf = List.iter (include_err' ppf) in
++ fprintf ppf "@[<v>%a%a@]" print_errs errs include_err err
+Index: typing/includemod.mli
+===================================================================
+--- typing/includemod.mli (revision 11161)
++++ typing/includemod.mli (working copy)
+@@ -24,7 +24,7 @@
+ val type_declarations:
+ Env.t -> Ident.t -> type_declaration -> type_declaration -> unit
+
+-type error =
++type symptom =
+ Missing_field of Ident.t
+ | Value_descriptions of Ident.t * value_description * value_description
+ | Type_declarations of Ident.t * type_declaration
+@@ -43,6 +43,10 @@
+ Ctype.class_match_failure list
+ | Unbound_modtype_path of Path.t
+
++type pos =
++ Module of Ident.t | Modtype of Ident.t | Arg of Ident.t | Body of Ident.t
++type error = pos list * symptom
++
+ exception Error of error list
+
+ val report_error: formatter -> error list -> unit
+Index: utils/clflags.ml
+===================================================================
+--- utils/clflags.ml (revision 11161)
++++ utils/clflags.ml (working copy)
+@@ -53,6 +53,7 @@
+ and dllpaths = ref ([] : string list) (* -dllpath *)
+ and make_package = ref false (* -pack *)
+ and for_package = ref (None: string option) (* -for-pack *)
++and show_trace = ref false (* -show-trace *)
+ let dump_parsetree = ref false (* -dparsetree *)
+ and dump_rawlambda = ref false (* -drawlambda *)
+ and dump_lambda = ref false (* -dlambda *)
+Index: utils/clflags.mli
+===================================================================
+--- utils/clflags.mli (revision 11161)
++++ utils/clflags.mli (working copy)
+@@ -50,6 +50,7 @@
+ val dllpaths : string list ref
+ val make_package : bool ref
+ val for_package : string option ref
++val show_trace : bool ref
+ val dump_parsetree : bool ref
+ val dump_rawlambda : bool ref
+ val dump_lambda : bool ref
diff --git a/experimental/garrigue/multimatch.diff b/experimental/garrigue/multimatch.diff
new file mode 100644
index 0000000000..6eb34b72e1
--- /dev/null
+++ b/experimental/garrigue/multimatch.diff
@@ -0,0 +1,1418 @@
+Index: parsing/lexer.mll
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/parsing/lexer.mll,v
+retrieving revision 1.73
+diff -u -r1.73 lexer.mll
+--- parsing/lexer.mll 11 Apr 2005 16:44:26 -0000 1.73
++++ parsing/lexer.mll 2 Feb 2006 06:28:32 -0000
+@@ -63,6 +63,8 @@
+ "match", MATCH;
+ "method", METHOD;
+ "module", MODULE;
++ "multifun", MULTIFUN;
++ "multimatch", MULTIMATCH;
+ "mutable", MUTABLE;
+ "new", NEW;
+ "object", OBJECT;
+Index: parsing/parser.mly
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/parsing/parser.mly,v
+retrieving revision 1.123
+diff -u -r1.123 parser.mly
+--- parsing/parser.mly 23 Mar 2005 03:08:37 -0000 1.123
++++ parsing/parser.mly 2 Feb 2006 06:28:32 -0000
+@@ -257,6 +257,8 @@
+ %token MINUSDOT
+ %token MINUSGREATER
+ %token MODULE
++%token MULTIFUN
++%token MULTIMATCH
+ %token MUTABLE
+ %token <nativeint> NATIVEINT
+ %token NEW
+@@ -325,7 +327,7 @@
+ %nonassoc SEMI /* below EQUAL ({lbl=...; lbl=...}) */
+ %nonassoc LET /* above SEMI ( ...; let ... in ...) */
+ %nonassoc below_WITH
+-%nonassoc FUNCTION WITH /* below BAR (match ... with ...) */
++%nonassoc FUNCTION WITH MULTIFUN /* below BAR (match ... with ...) */
+ %nonassoc AND /* above WITH (module rec A: SIG with ... and ...) */
+ %nonassoc THEN /* below ELSE (if ... then ...) */
+ %nonassoc ELSE /* (if ... then ... else ...) */
+@@ -804,8 +806,12 @@
+ { mkexp(Pexp_function("", None, List.rev $3)) }
+ | FUN labeled_simple_pattern fun_def
+ { let (l,o,p) = $2 in mkexp(Pexp_function(l, o, [p, $3])) }
++ | MULTIFUN opt_bar match_cases
++ { mkexp(Pexp_multifun(List.rev $3)) }
+ | MATCH seq_expr WITH opt_bar match_cases
+- { mkexp(Pexp_match($2, List.rev $5)) }
++ { mkexp(Pexp_match($2, List.rev $5, false)) }
++ | MULTIMATCH seq_expr WITH opt_bar match_cases
++ { mkexp(Pexp_match($2, List.rev $5, true)) }
+ | TRY seq_expr WITH opt_bar match_cases
+ { mkexp(Pexp_try($2, List.rev $5)) }
+ | TRY seq_expr WITH error
+@@ -1318,10 +1324,10 @@
+ | simple_core_type2 { Rinherit $1 }
+ ;
+ tag_field:
+- name_tag OF opt_ampersand amper_type_list
+- { Rtag ($1, $3, List.rev $4) }
+- | name_tag
+- { Rtag ($1, true, []) }
++ name_tag OF opt_ampersand amper_type_list amper_type_pair_list
++ { Rtag ($1, $3, List.rev $4, $5) }
++ | name_tag amper_type_pair_list
++ { Rtag ($1, true, [], $2) }
+ ;
+ opt_ampersand:
+ AMPERSAND { true }
+@@ -1331,6 +1337,11 @@
+ core_type { [$1] }
+ | amper_type_list AMPERSAND core_type { $3 :: $1 }
+ ;
++amper_type_pair_list:
++ AMPERSAND core_type EQUAL core_type amper_type_pair_list
++ { ($2, $4) :: $5 }
++ | /* empty */
++ { [] }
+ opt_present:
+ LBRACKETGREATER name_tag_list RBRACKET { List.rev $2 }
+ | /* empty */ { [] }
+Index: parsing/parsetree.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/parsing/parsetree.mli,v
+retrieving revision 1.42
+diff -u -r1.42 parsetree.mli
+--- parsing/parsetree.mli 23 Mar 2005 03:08:37 -0000 1.42
++++ parsing/parsetree.mli 2 Feb 2006 06:28:32 -0000
+@@ -43,7 +43,7 @@
+ | Pfield_var
+
+ and row_field =
+- Rtag of label * bool * core_type list
++ Rtag of label * bool * core_type list * (core_type * core_type) list
+ | Rinherit of core_type
+
+ (* XXX Type expressions for the class language *)
+@@ -86,7 +86,7 @@
+ | Pexp_let of rec_flag * (pattern * expression) list * expression
+ | Pexp_function of label * expression option * (pattern * expression) list
+ | Pexp_apply of expression * (label * expression) list
+- | Pexp_match of expression * (pattern * expression) list
++ | Pexp_match of expression * (pattern * expression) list * bool
+ | Pexp_try of expression * (pattern * expression) list
+ | Pexp_tuple of expression list
+ | Pexp_construct of Longident.t * expression option * bool
+@@ -111,6 +111,7 @@
+ | Pexp_lazy of expression
+ | Pexp_poly of expression * core_type option
+ | Pexp_object of class_structure
++ | Pexp_multifun of (pattern * expression) list
+
+ (* Value descriptions *)
+
+Index: parsing/printast.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/parsing/printast.ml,v
+retrieving revision 1.29
+diff -u -r1.29 printast.ml
+--- parsing/printast.ml 4 Jan 2006 16:55:50 -0000 1.29
++++ parsing/printast.ml 2 Feb 2006 06:28:32 -0000
+@@ -205,10 +205,14 @@
+ line i ppf "Pexp_apply\n";
+ expression i ppf e;
+ list i label_x_expression ppf l;
+- | Pexp_match (e, l) ->
++ | Pexp_match (e, l, b) ->
+ line i ppf "Pexp_match\n";
+ expression i ppf e;
+ list i pattern_x_expression_case ppf l;
++ bool i ppf b
++ | Pexp_multifun l ->
++ line i ppf "Pexp_multifun\n";
++ list i pattern_x_expression_case ppf l;
+ | Pexp_try (e, l) ->
+ line i ppf "Pexp_try\n";
+ expression i ppf e;
+@@ -653,7 +657,7 @@
+
+ and label_x_bool_x_core_type_list i ppf x =
+ match x with
+- Rtag (l, b, ctl) ->
++ Rtag (l, b, ctl, cstr) ->
+ line i ppf "Rtag \"%s\" %s\n" l (string_of_bool b);
+ list (i+1) core_type ppf ctl
+ | Rinherit (ct) ->
+Index: typing/btype.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/btype.ml,v
+retrieving revision 1.38
+diff -u -r1.38 btype.ml
+--- typing/btype.ml 4 Jan 2006 16:55:50 -0000 1.38
++++ typing/btype.ml 2 Feb 2006 06:28:32 -0000
+@@ -66,16 +66,16 @@
+ Clink r when !r <> Cunknown -> commu_repr !r
+ | c -> c
+
+-let rec row_field_repr_aux tl = function
+- Reither(_, tl', _, {contents = Some fi}) ->
+- row_field_repr_aux (tl@tl') fi
+- | Reither(c, tl', m, r) ->
+- Reither(c, tl@tl', m, r)
++let rec row_field_repr_aux tl tl2 = function
++ Reither(_, tl', _, tl2', {contents = Some fi}) ->
++ row_field_repr_aux (tl@tl') (tl2@tl2') fi
++ | Reither(c, tl', m, tl2', r) ->
++ Reither(c, tl@tl', m, tl2@tl2', r)
+ | Rpresent (Some _) when tl <> [] ->
+ Rpresent (Some (List.hd tl))
+ | fi -> fi
+
+-let row_field_repr fi = row_field_repr_aux [] fi
++let row_field_repr fi = row_field_repr_aux [] [] fi
+
+ let rec rev_concat l ll =
+ match ll with
+@@ -170,7 +170,8 @@
+ (fun (_, fi) ->
+ match row_field_repr fi with
+ | Rpresent(Some ty) -> f ty
+- | Reither(_, tl, _, _) -> List.iter f tl
++ | Reither(_, tl, _, tl2, _) ->
++ List.iter f tl; List.iter (fun (t1,t2) -> f t1; f t2) tl2
+ | _ -> ())
+ row.row_fields;
+ match (repr row.row_more).desc with
+@@ -208,15 +209,17 @@
+ (fun (l, fi) -> l,
+ match row_field_repr fi with
+ | Rpresent(Some ty) -> Rpresent(Some(f ty))
+- | Reither(c, tl, m, e) ->
++ | Reither(c, tl, m, tpl, e) ->
+ let e = if keep then e else ref None in
+ let m = if row.row_fixed then fixed else m in
+ let tl = List.map f tl in
++ let tl1 = List.map (fun (t1,_) -> repr (f t1)) tpl
++ and tl2 = List.map (fun (_,t2) -> repr (f t2)) tpl in
+ bound := List.filter
+ (function {desc=Tconstr(_,[],_)} -> false | _ -> true)
+- (List.map repr tl)
++ (List.map repr tl @ tl1 @ tl2)
+ @ !bound;
+- Reither(c, tl, m, e)
++ Reither(c, tl, m, List.combine tl1 tl2, e)
+ | _ -> fi)
+ row.row_fields in
+ let name =
+Index: typing/ctype.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/ctype.ml,v
+retrieving revision 1.200
+diff -u -r1.200 ctype.ml
+--- typing/ctype.ml 6 Jan 2006 02:16:24 -0000 1.200
++++ typing/ctype.ml 2 Feb 2006 06:28:32 -0000
+@@ -340,7 +340,7 @@
+ let fi = filter_row_fields erase fi in
+ match row_field_repr f with
+ Rabsent -> fi
+- | Reither(_,_,false,e) when erase -> set_row_field e Rabsent; fi
++ | Reither(_,_,false,_,e) when erase -> set_row_field e Rabsent; fi
+ | _ -> p :: fi
+
+ (**************************************)
+@@ -1286,6 +1286,10 @@
+
+ module TypeMap = Map.Make (TypeOps)
+
++
++(* A list of univars which may appear free in a type, but only if generic *)
++let allowed_univars = ref TypeSet.empty
++
+ (* Test the occurence of free univars in a type *)
+ (* that's way too expansive. Must do some kind of cacheing *)
+ let occur_univar env ty =
+@@ -1307,7 +1311,12 @@
+ then
+ match ty.desc with
+ Tunivar ->
+- if not (TypeSet.mem ty bound) then raise (Unify [ty, newgenvar()])
++ if TypeSet.mem ty bound then () else
++ if TypeSet.mem ty !allowed_univars &&
++ (ty.level = generic_level ||
++ ty.level = pivot_level - generic_level)
++ then ()
++ else raise (Unify [ty, newgenvar()])
+ | Tpoly (ty, tyl) ->
+ let bound = List.fold_right TypeSet.add (List.map repr tyl) bound in
+ occur_rec bound ty
+@@ -1393,6 +1402,7 @@
+ with exn -> univar_pairs := old_univars; raise exn
+
+ let univar_pairs = ref []
++let delayed_conditionals = ref []
+
+
+ (*****************)
+@@ -1691,9 +1701,11 @@
+ with Not_found -> (h,l)::hl)
+ (List.map (fun (l,_) -> (hash_variant l, l)) row1.row_fields)
+ (List.map fst r2));
++ let fixed1 = row1.row_fixed || rm1.desc <> Tvar
++ and fixed2 = row2.row_fixed || rm2.desc <> Tvar in
+ let more =
+- if row1.row_fixed then rm1 else
+- if row2.row_fixed then rm2 else
++ if fixed1 then rm1 else
++ if fixed2 then rm2 else
+ newgenvar ()
+ in update_level env (min rm1.level rm2.level) more;
+ let fixed = row1.row_fixed || row2.row_fixed
+@@ -1726,18 +1738,18 @@
+ let bound = row1.row_bound @ row2.row_bound in
+ let row0 = {row_fields = []; row_more = more; row_bound = bound;
+ row_closed = closed; row_fixed = fixed; row_name = name} in
+- let set_more row rest =
++ let set_more row row_fixed rest =
+ let rest =
+ if closed then
+ filter_row_fields row.row_closed rest
+ else rest in
+- if rest <> [] && (row.row_closed || row.row_fixed)
+- || closed && row.row_fixed && not row.row_closed then begin
++ if rest <> [] && (row.row_closed || row_fixed)
++ || closed && row_fixed && not row.row_closed then begin
+ let t1 = mkvariant [] true and t2 = mkvariant rest false in
+ raise (Unify [if row == row1 then (t1,t2) else (t2,t1)])
+ end;
+ let rm = row_more row in
+- if row.row_fixed then
++ if row_fixed then
+ if row0.row_more == rm then () else
+ if rm.desc = Tvar then link_type rm row0.row_more else
+ unify env rm row0.row_more
+@@ -1748,11 +1760,11 @@
+ in
+ let md1 = rm1.desc and md2 = rm2.desc in
+ begin try
+- set_more row1 r2;
+- set_more row2 r1;
++ set_more row1 fixed1 r2;
++ set_more row2 fixed2 r1;
+ List.iter
+ (fun (l,f1,f2) ->
+- try unify_row_field env row1.row_fixed row2.row_fixed l f1 f2
++ try unify_row_field env fixed1 fixed2 row1 row2 l f1 f2
+ with Unify trace ->
+ raise (Unify ((mkvariant [l,f1] true,
+ mkvariant [l,f2] true) :: trace)))
+@@ -1761,13 +1773,13 @@
+ log_type rm1; rm1.desc <- md1; log_type rm2; rm2.desc <- md2; raise exn
+ end
+
+-and unify_row_field env fixed1 fixed2 l f1 f2 =
++and unify_row_field env fixed1 fixed2 row1 row2 l f1 f2 =
+ let f1 = row_field_repr f1 and f2 = row_field_repr f2 in
+ if f1 == f2 then () else
+ match f1, f2 with
+ Rpresent(Some t1), Rpresent(Some t2) -> unify env t1 t2
+ | Rpresent None, Rpresent None -> ()
+- | Reither(c1, tl1, m1, e1), Reither(c2, tl2, m2, e2) ->
++ | Reither(c1, tl1, m1, tp1, e1), Reither(c2, tl2, m2, tp2, e2) ->
+ if e1 == e2 then () else
+ let redo =
+ (m1 || m2) &&
+@@ -1777,32 +1789,70 @@
+ List.iter (unify env t1) tl;
+ !e1 <> None || !e2 <> None
+ end in
+- if redo then unify_row_field env fixed1 fixed2 l f1 f2 else
++ let redo =
++ redo || begin
++ if tp1 = [] && fixed1 then unify_pairs env tp2;
++ if tp2 = [] && fixed2 then unify_pairs env tp1;
++ !e1 <> None || !e2 <> None
++ end
++ in
++ if redo then unify_row_field env fixed1 fixed2 row1 row2 l f1 f2 else
+ let tl1 = List.map repr tl1 and tl2 = List.map repr tl2 in
+ let rec remq tl = function [] -> []
+ | ty :: tl' ->
+ if List.memq ty tl then remq tl tl' else ty :: remq tl tl'
+ in
+ let tl2' = remq tl2 tl1 and tl1' = remq tl1 tl2 in
++ let repr_pairs = List.map (fun (t1,t2) -> repr t1, repr t2) in
++ let tp1 = repr_pairs tp1 and tp2 = repr_pairs tp2 in
++ let rec rempq tp = function [] -> []
++ | (t1,t2 as p) :: tp' ->
++ if List.exists (fun (t1',t2') -> t1==t1' && t2==t2') (tp@tp') then
++ rempq tp tp'
++ else p :: rempq tp tp'
++ in
++ let tp1' =
++ if fixed2 then begin
++ delayed_conditionals :=
++ (!univar_pairs, tp1, l, row2) :: !delayed_conditionals;
++ []
++ end else rempq tp2 tp1
++ and tp2' =
++ if fixed1 then begin
++ delayed_conditionals :=
++ (!univar_pairs, tp2, l, row1) :: !delayed_conditionals;
++ []
++ end else rempq tp1 tp2
++ in
+ let e = ref None in
+- let f1' = Reither(c1 || c2, tl1', m1 || m2, e)
+- and f2' = Reither(c1 || c2, tl2', m1 || m2, e) in
+- set_row_field e1 f1'; set_row_field e2 f2';
+- | Reither(_, _, false, e1), Rabsent -> set_row_field e1 f2
+- | Rabsent, Reither(_, _, false, e2) -> set_row_field e2 f1
++ let f1' = Reither(c1 || c2, tl1', m1 || m2, tp2', e)
++ and f2' = Reither(c1 || c2, tl2', m1 || m2, tp1', e) in
++ set_row_field e1 f1'; set_row_field e2 f2'
++ | Reither(_, _, false, _, e1), Rabsent -> set_row_field e1 f2
++ | Rabsent, Reither(_, _, false, _, e2) -> set_row_field e2 f1
+ | Rabsent, Rabsent -> ()
+- | Reither(false, tl, _, e1), Rpresent(Some t2) when not fixed1 ->
++ | Reither(false, tl, _, tp, e1), Rpresent(Some t2) when not fixed1 ->
+ set_row_field e1 f2;
+- (try List.iter (fun t1 -> unify env t1 t2) tl
++ begin try
++ List.iter (fun t1 -> unify env t1 t2) tl;
++ List.iter (fun (t1,t2) -> unify env t1 t2) tp
++ with exn -> e1 := None; raise exn
++ end
++ | Rpresent(Some t1), Reither(false, tl, _, tp, e2) when not fixed2 ->
++ set_row_field e2 f1;
++ begin try
++ List.iter (unify env t1) tl;
++ List.iter (fun (t1,t2) -> unify env t1 t2) tp
++ with exn -> e2 := None; raise exn
++ end
++ | Reither(true, [], _, tpl, e1), Rpresent None when not fixed1 ->
++ set_row_field e1 f2;
++ (try List.iter (fun (t1,t2) -> unify env t1 t2) tpl
+ with exn -> e1 := None; raise exn)
+- | Rpresent(Some t1), Reither(false, tl, _, e2) when not fixed2 ->
++ | Rpresent None, Reither(true, [], _, tpl, e2) when not fixed2 ->
+ set_row_field e2 f1;
+- (try List.iter (unify env t1) tl
++ (try List.iter (fun (t1,t2) -> unify env t1 t2) tpl
+ with exn -> e2 := None; raise exn)
+- | Reither(true, [], _, e1), Rpresent None when not fixed1 ->
+- set_row_field e1 f2
+- | Rpresent None, Reither(true, [], _, e2) when not fixed2 ->
+- set_row_field e2 f1
+ | _ -> raise (Unify [])
+
+
+@@ -1920,6 +1970,166 @@
+ (* Matching between type schemes *)
+ (***********************************)
+
++(* Forward declaration (order should be reversed...) *)
++let equal' = ref (fun _ -> failwith "Ctype.equal'")
++
++let make_generics_univars tyl =
++ let polyvars = ref TypeSet.empty in
++ let rec make_rec ty =
++ let ty = repr ty in
++ if ty.level = generic_level then begin
++ if ty.desc = Tvar then begin
++ log_type ty;
++ ty.desc <- Tunivar;
++ polyvars := TypeSet.add ty !polyvars
++ end
++ else if ty.desc = Tunivar then set_level ty (generic_level - 1);
++ ty.level <- pivot_level - generic_level;
++ iter_type_expr make_rec ty
++ end
++ in
++ List.iter make_rec tyl;
++ List.iter unmark_type tyl;
++ !polyvars
++
++(* New version of moregeneral, using unification *)
++
++let copy_cond (p,tpl,l,row) =
++ let row =
++ match repr (copy (newgenty (Tvariant row))) with
++ {desc=Tvariant row} -> row
++ | _ -> assert false
++ and pairs =
++ List.map (fun (t1,t2) -> copy t1, copy t2) tpl in
++ (p, pairs, l, row)
++
++let get_row_field l row =
++ try row_field_repr (List.assoc l (row_repr row).row_fields)
++ with Not_found -> Rabsent
++
++let rec check_conditional_list env cdtls pattvars tpls =
++ match cdtls with
++ [] ->
++ let finished =
++ List.for_all (fun (_,t1,t2) -> !equal' env false [t1] [t2]) tpls in
++ if not finished then begin
++ let polyvars = make_generics_univars pattvars in
++ delayed_conditionals := [];
++ allowed_univars := polyvars;
++ List.iter (fun (pairs, ty1, ty2) -> unify_pairs env ty1 ty2 pairs)
++ tpls;
++ check_conditionals env polyvars !delayed_conditionals
++ end
++ | (pairs, tpl1, l, row2 as cond) :: cdtls ->
++ let cont = check_conditional_list env cdtls pattvars in
++ let tpl1 =
++ List.filter (fun (t1,t2) -> not (!equal' env false [t1] [t2])) tpl1 in
++ let included =
++ List.for_all
++ (fun (t1,t2) ->
++ List.exists
++ (fun (_,t1',t2') -> !equal' env false [t1;t2] [t1';t2'])
++ tpls)
++ tpl1 in
++ if included then cont tpls else
++ match get_row_field l row2 with
++ Rpresent _ ->
++ cont (List.map (fun (t1,t2) -> (pairs,t1,t2)) tpl1 @ tpls)
++ | Rabsent -> cont tpls
++ | Reither (c, tl2, _, _, _) ->
++ cont tpls;
++ if c && tl2 <> [] then () (* cannot succeed *) else
++ let (pairs, tpl1, l, row2) = copy_cond cond
++ and tpls = List.map (fun (p,t1,t2) -> p, copy t1, copy t2) tpls
++ and pattvars = List.map copy pattvars
++ and cdtls = List.map copy_cond cdtls in
++ cleanup_types ();
++ let tl2, tpl2, e2 =
++ match get_row_field l row2 with
++ Reither (c, tl2, _, tpl2, e2) -> tl2, tpl2, e2
++ | _ -> assert false
++ in
++ let snap = Btype.snapshot () in
++ let ok =
++ try
++ begin match tl2 with
++ [] ->
++ set_row_field e2 (Rpresent None)
++ | t::tl ->
++ set_row_field e2 (Rpresent (Some t));
++ List.iter (unify env t) tl
++ end;
++ List.iter (fun (t1,t2) -> unify_pairs env t1 t2 pairs) tpl2;
++ true
++ with exn ->
++ Btype.backtrack snap;
++ false
++ in
++ (* This is not [cont] : types have been copied *)
++ if ok then
++ check_conditional_list env cdtls pattvars
++ (List.map (fun (t1,t2) -> (pairs,t1,t2)) tpl1 @ tpls)
++
++and check_conditionals env polyvars cdtls =
++ let cdtls = List.map copy_cond cdtls in
++ let pattvars = ref [] in
++ TypeSet.iter
++ (fun ty ->
++ let ty = repr ty in
++ match ty.desc with
++ Tsubst ty ->
++ let ty = repr ty in
++ begin match ty.desc with
++ Tunivar ->
++ log_type ty;
++ ty.desc <- Tvar;
++ pattvars := ty :: !pattvars
++ | Ttuple [tv;_] ->
++ if tv.desc = Tunivar then
++ (log_type tv; tv.desc <- Tvar; pattvars := ty :: !pattvars)
++ else if tv.desc <> Tvar then assert false
++ | Tvar -> ()
++ | _ -> assert false
++ end
++ | _ -> ())
++ polyvars;
++ cleanup_types ();
++ check_conditional_list env cdtls !pattvars []
++
++
++(* Must empty univar_pairs first *)
++let unify_poly env polyvars subj patt =
++ let old_level = !current_level in
++ current_level := generic_level;
++ delayed_conditionals := [];
++ allowed_univars := polyvars;
++ try
++ unify env subj patt;
++ check_conditionals env polyvars !delayed_conditionals;
++ current_level := old_level;
++ allowed_univars := TypeSet.empty;
++ delayed_conditionals := []
++ with exn ->
++ current_level := old_level;
++ allowed_univars := TypeSet.empty;
++ delayed_conditionals := [];
++ raise exn
++
++let moregeneral env _ subj patt =
++ let old_level = !current_level in
++ current_level := generic_level;
++ let subj = instance subj
++ and patt = instance patt in
++ let polyvars = make_generics_univars [patt] in
++ current_level := old_level;
++ let snap = Btype.snapshot () in
++ try
++ unify_poly env polyvars subj patt;
++ true
++ with Unify _ ->
++ Btype.backtrack snap;
++ false
++
+ (*
+ Update the level of [ty]. First check that the levels of generic
+ variables from the subject are not lowered.
+@@ -2072,35 +2282,101 @@
+ Rpresent(Some t1), Rpresent(Some t2) ->
+ moregen inst_nongen type_pairs env t1 t2
+ | Rpresent None, Rpresent None -> ()
+- | Reither(false, tl1, _, e1), Rpresent(Some t2) when not univ ->
++ | Reither(false, tl1, _, [], e1), Rpresent(Some t2) when not univ ->
+ set_row_field e1 f2;
+ List.iter (fun t1 -> moregen inst_nongen type_pairs env t1 t2) tl1
+- | Reither(c1, tl1, _, e1), Reither(c2, tl2, m2, e2) ->
++ | Reither(c1, tl1, _, tpl1, e1), Reither(c2, tl2, m2, tpl2, e2) ->
+ if e1 != e2 then begin
+ if c1 && not c2 then raise(Unify []);
+- set_row_field e1 (Reither (c2, [], m2, e2));
+- if List.length tl1 = List.length tl2 then
+- List.iter2 (moregen inst_nongen type_pairs env) tl1 tl2
+- else match tl2 with
+- t2 :: _ ->
++ let tpl' = if tpl1 = [] then tpl2 else [] in
++ set_row_field e1 (Reither (c2, [], m2, tpl', e2));
++ begin match tl2 with
++ [t2] ->
+ List.iter (fun t1 -> moregen inst_nongen type_pairs env t1 t2)
+ tl1
+- | [] ->
+- if tl1 <> [] then raise (Unify [])
++ | _ ->
++ if List.length tl1 <> List.length tl2 then raise (Unify []);
++ List.iter2 (moregen inst_nongen type_pairs env) tl1 tl2
++ end;
++ if tpl1 <> [] then
++ delayed_conditionals :=
++ (!univar_pairs, tpl1, l, row2) :: !delayed_conditionals
+ end
+- | Reither(true, [], _, e1), Rpresent None when not univ ->
++ | Reither(true, [], _, [], e1), Rpresent None when not univ ->
+ set_row_field e1 f2
+- | Reither(_, _, _, e1), Rabsent when not univ ->
++ | Reither(_, _, _, [], e1), Rabsent when not univ ->
+ set_row_field e1 f2
+ | Rabsent, Rabsent -> ()
+ | _ -> raise (Unify []))
+ pairs
+
++let check_conditional env (pairs, tpl1, l, row2) tpls cont =
++ let tpl1 =
++ List.filter (fun (t1,t2) -> not (!equal' env false [t1] [t2])) tpl1 in
++ let included =
++ List.for_all
++ (fun (t1,t2) ->
++ List.exists (fun (t1',t2') -> !equal' env false [t1;t2] [t1';t2'])
++ tpls)
++ tpl1 in
++ if tpl1 = [] || included then cont tpls else
++ match get_row_field l row2 with
++ Rpresent _ -> cont (tpl1 @ tpls)
++ | Rabsent -> cont tpls
++ | Reither (c, tl2, _, tpl2, e2) ->
++ if not c || tl2 = [] then begin
++ let snap = Btype.snapshot () in
++ let ok =
++ try
++ begin match tl2 with
++ [] ->
++ set_row_field e2 (Rpresent None)
++ | t::tl ->
++ set_row_field e2 (Rpresent (Some t));
++ List.iter (unify env t) tl
++ end;
++ List.iter (fun (t1,t2) -> unify_pairs env t1 t2 pairs) tpl2;
++ true
++ with Unify _ -> false
++ in
++ if ok then cont (tpl1 @ tpls);
++ Btype.backtrack snap
++ end;
++ cont tpls
++
++let rec check_conditionals inst_nongen env cdtls tpls =
++ match cdtls with
++ [] ->
++ let tpls =
++ List.filter (fun (t1,t2) -> not (!equal' env false [t1] [t2])) tpls in
++ if tpls = [] then () else begin
++ delayed_conditionals := [];
++ let tl1, tl2 = List.split tpls in
++ let type_pairs = TypePairs.create 13 in
++ List.iter2 (moregen false type_pairs env) tl2 tl1;
++ check_conditionals inst_nongen env !delayed_conditionals []
++ end
++ | cdtl :: cdtls ->
++ check_conditional env cdtl tpls
++ (check_conditionals inst_nongen env cdtls)
++
++
+ (* Must empty univar_pairs first *)
+ let moregen inst_nongen type_pairs env patt subj =
+ univar_pairs := [];
+- moregen inst_nongen type_pairs env patt subj
++ delayed_conditionals := [];
++ try
++ moregen inst_nongen type_pairs env patt subj;
++ check_conditionals inst_nongen env !delayed_conditionals [];
++ univar_pairs := [];
++ delayed_conditionals := []
++ with exn ->
++ univar_pairs := [];
++ delayed_conditionals := [];
++ raise exn
++
+
++(* old implementation
+ (*
+ Non-generic variable can be instanciated only if [inst_nongen] is
+ true. So, [inst_nongen] should be set to false if the subject might
+@@ -2128,6 +2404,7 @@
+ in
+ current_level := old_level;
+ res
++*)
+
+
+ (* Alternative approach: "rigidify" a type scheme,
+@@ -2296,30 +2573,36 @@
+ {desc=Tvariant row2} -> eqtype_row rename type_pairs subst env row1 row2
+ | _ -> raise Cannot_expand
+ with Cannot_expand ->
++ let eqtype_rec = eqtype rename type_pairs subst env in
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let r1, r2, pairs = merge_row_fields row1.row_fields row2.row_fields in
+ if row1.row_closed <> row2.row_closed
+ || not row1.row_closed && (r1 <> [] || r2 <> [])
+ || filter_row_fields false (r1 @ r2) <> []
+ then raise (Unify []);
+- if not (static_row row1) then
+- eqtype rename type_pairs subst env row1.row_more row2.row_more;
++ if not (static_row row1) then eqtype_rec row1.row_more row2.row_more;
+ List.iter
+ (fun (_,f1,f2) ->
+ match row_field_repr f1, row_field_repr f2 with
+ Rpresent(Some t1), Rpresent(Some t2) ->
+- eqtype rename type_pairs subst env t1 t2
+- | Reither(true, [], _, _), Reither(true, [], _, _) ->
+- ()
+- | Reither(false, t1::tl1, _, _), Reither(false, t2::tl2, _, _) ->
+- eqtype rename type_pairs subst env t1 t2;
++ eqtype_rec t1 t2
++ | Reither(true, [], _, tp1, _), Reither(true, [], _, tp2, _) ->
++ List.iter2
++ (fun (t1,t1') (t2,t2') -> eqtype_rec t1 t2; eqtype_rec t1' t2')
++ tp1 tp2
++ | Reither(false, t1::tl1, _, tpl1, _),
++ Reither(false, t2::tl2, _, tpl2, _) ->
++ eqtype_rec t1 t2;
++ List.iter2
++ (fun (t1,t1') (t2,t2') -> eqtype_rec t1 t2; eqtype_rec t1' t2')
++ tpl1 tpl2;
+ if List.length tl1 = List.length tl2 then
+ (* if same length allow different types (meaning?) *)
+- List.iter2 (eqtype rename type_pairs subst env) tl1 tl2
++ List.iter2 eqtype_rec tl1 tl2
+ else begin
+ (* otherwise everything must be equal *)
+- List.iter (eqtype rename type_pairs subst env t1) tl2;
+- List.iter (fun t1 -> eqtype rename type_pairs subst env t1 t2) tl1
++ List.iter (eqtype_rec t1) tl2;
++ List.iter (fun t1 -> eqtype_rec t1 t2) tl1
+ end
+ | Rpresent None, Rpresent None -> ()
+ | Rabsent, Rabsent -> ()
+@@ -2334,6 +2617,8 @@
+ with
+ Unify _ -> false
+
++let () = equal' := equal
++
+ (* Must empty univar_pairs first *)
+ let eqtype rename type_pairs subst env t1 t2 =
+ univar_pairs := [];
+@@ -2770,14 +3055,14 @@
+ (fun (l,f as orig) -> match row_field_repr f with
+ Rpresent None ->
+ if posi then
+- (l, Reither(true, [], false, ref None)), Unchanged
++ (l, Reither(true, [], false, [], ref None)), Unchanged
+ else
+ orig, Unchanged
+ | Rpresent(Some t) ->
+ let (t', c) = build_subtype env visited loops posi level' t in
+ if posi && level > 0 then begin
+ bound := t' :: !bound;
+- (l, Reither(false, [t'], false, ref None)), c
++ (l, Reither(false, [t'], false, [], ref None)), c
+ end else
+ (l, Rpresent(Some t')), c
+ | _ -> assert false)
+@@ -2960,11 +3245,11 @@
+ List.fold_left
+ (fun cstrs (_,f1,f2) ->
+ match row_field_repr f1, row_field_repr f2 with
+- (Rpresent None|Reither(true,_,_,_)), Rpresent None ->
++ (Rpresent None|Reither(true,_,_,[],_)), Rpresent None ->
+ cstrs
+ | Rpresent(Some t1), Rpresent(Some t2) ->
+ subtype_rec env ((t1, t2)::trace) t1 t2 cstrs
+- | Reither(false, t1::_, _, _), Rpresent(Some t2) ->
++ | Reither(false, t1::_, _, [], _), Rpresent(Some t2) ->
+ subtype_rec env ((t1, t2)::trace) t1 t2 cstrs
+ | Rabsent, _ -> cstrs
+ | _ -> raise Exit)
+@@ -2977,11 +3262,11 @@
+ (fun cstrs (_,f1,f2) ->
+ match row_field_repr f1, row_field_repr f2 with
+ Rpresent None, Rpresent None
+- | Reither(true,[],_,_), Reither(true,[],_,_)
++ | Reither(true,[],_,[],_), Reither(true,[],_,[],_)
+ | Rabsent, Rabsent ->
+ cstrs
+ | Rpresent(Some t1), Rpresent(Some t2)
+- | Reither(false,[t1],_,_), Reither(false,[t2],_,_) ->
++ | Reither(false,[t1],_,[],_), Reither(false,[t2],_,[],_) ->
+ subtype_rec env ((t1, t2)::trace) t1 t2 cstrs
+ | _ -> raise Exit)
+ cstrs pairs
+@@ -3079,16 +3364,26 @@
+ let fields = List.map
+ (fun (l,f) ->
+ let f = row_field_repr f in l,
+- match f with Reither(b, ty::(_::_ as tyl), m, e) ->
+- let tyl' =
+- List.fold_left
+- (fun tyl ty ->
+- if List.exists (fun ty' -> equal env false [ty] [ty']) tyl
+- then tyl else ty::tyl)
+- [ty] tyl
++ match f with Reither(b, tyl, m, tp, e) ->
++ let rem_dbl eq l =
++ List.rev
++ (List.fold_left
++ (fun xs x -> if List.exists (eq x) xs then xs else x::xs)
++ [] l)
++ in
++ let tyl' = rem_dbl (fun t1 t2 -> equal env false [t1] [t2]) tyl
++ and tp' =
++ List.filter
++ (fun (ty1,ty2) -> not (equal env false [ty1] [ty2])) tp
++ in
++ let tp' =
++ rem_dbl
++ (fun (t1,t2) (t1',t2') -> equal env false [t1;t2] [t1';t2'])
++ tp'
+ in
+- if List.length tyl' <= List.length tyl then
+- let f = Reither(b, List.rev tyl', m, ref None) in
++ if List.length tyl' < List.length tyl
++ || List.length tp' < List.length tp then
++ let f = Reither(b, tyl', m, tp', ref None) in
+ set_row_field e f;
+ f
+ else f
+@@ -3344,9 +3639,9 @@
+ List.iter
+ (fun (l,fi) ->
+ match row_field_repr fi with
+- Reither (c, t1::(_::_ as tl), m, e) ->
++ Reither (c, t1::(_::_ as tl), m, tp, e) ->
+ List.iter (unify env t1) tl;
+- set_row_field e (Reither (c, [t1], m, ref None))
++ set_row_field e (Reither (c, [t1], m, tp, ref None))
+ | _ ->
+ ())
+ row.row_fields;
+Index: typing/includecore.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/includecore.ml,v
+retrieving revision 1.32
+diff -u -r1.32 includecore.ml
+--- typing/includecore.ml 8 Aug 2005 05:40:52 -0000 1.32
++++ typing/includecore.ml 2 Feb 2006 06:28:32 -0000
+@@ -71,10 +71,10 @@
+ (fun (_, f1, f2) ->
+ match Btype.row_field_repr f1, Btype.row_field_repr f2 with
+ Rpresent(Some t1),
+- (Rpresent(Some t2) | Reither(false, [t2], _, _)) ->
++ (Rpresent(Some t2) | Reither(false,[t2],_,[],_)) ->
+ to_equal := (t1,t2) :: !to_equal; true
+- | Rpresent None, (Rpresent None | Reither(true, [], _, _)) -> true
+- | Reither(c1,tl1,_,_), Reither(c2,tl2,_,_)
++ | Rpresent None, (Rpresent None | Reither(true,[],_,[],_)) -> true
++ | Reither(c1,tl1,_,[],_), Reither(c2,tl2,_,[],_)
+ when List.length tl1 = List.length tl2 && c1 = c2 ->
+ to_equal := List.combine tl1 tl2 @ !to_equal; true
+ | Rabsent, (Reither _ | Rabsent) -> true
+Index: typing/oprint.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/oprint.ml,v
+retrieving revision 1.22
+diff -u -r1.22 oprint.ml
+--- typing/oprint.ml 23 Mar 2005 03:08:37 -0000 1.22
++++ typing/oprint.ml 2 Feb 2006 06:28:33 -0000
+@@ -223,14 +223,18 @@
+ print_fields rest ppf []
+ | (s, t) :: l ->
+ fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l
+-and print_row_field ppf (l, opt_amp, tyl) =
++and print_row_field ppf (l, opt_amp, tyl, tpl) =
+ let pr_of ppf =
+ if opt_amp then fprintf ppf " of@ &@ "
+ else if tyl <> [] then fprintf ppf " of@ "
+- else fprintf ppf ""
+- in
+- fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &")
+- tyl
++ and pr_tp ppf (t1,t2) =
++ fprintf ppf "@[<hv 2>%a =@ %a@]"
++ print_out_type t1
++ print_out_type t2
++ in
++ fprintf ppf "@[<hv 2>`%s%t%a%a@]" l pr_of
++ (print_typlist print_out_type " &") tyl
++ (print_list_init pr_tp (fun ppf -> fprintf ppf " &@ ")) tpl
+ and print_typlist print_elem sep ppf =
+ function
+ [] -> ()
+Index: typing/outcometree.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/outcometree.mli,v
+retrieving revision 1.14
+diff -u -r1.14 outcometree.mli
+--- typing/outcometree.mli 23 Mar 2005 03:08:37 -0000 1.14
++++ typing/outcometree.mli 2 Feb 2006 06:28:33 -0000
+@@ -61,7 +61,8 @@
+ bool * out_variant * bool * (string list) option
+ | Otyp_poly of string list * out_type
+ and out_variant =
+- | Ovar_fields of (string * bool * out_type list) list
++ | Ovar_fields of
++ (string * bool * out_type list * (out_type * out_type) list ) list
+ | Ovar_name of out_ident * out_type list
+
+ type out_class_type =
+Index: typing/parmatch.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/parmatch.ml,v
+retrieving revision 1.70
+diff -u -r1.70 parmatch.ml
+--- typing/parmatch.ml 24 Mar 2005 17:20:54 -0000 1.70
++++ typing/parmatch.ml 2 Feb 2006 06:28:33 -0000
+@@ -568,11 +568,11 @@
+ List.fold_left
+ (fun nm (tag,f) ->
+ match Btype.row_field_repr f with
+- | Reither(_, _, false, e) ->
++ | Reither(_, _, false, _, e) ->
+ (* m=false means that this tag is not explicitly matched *)
+ Btype.set_row_field e Rabsent;
+ None
+- | Rabsent | Reither (_, _, true, _) | Rpresent _ -> nm)
++ | Rabsent | Reither (_, _, true, _, _) | Rpresent _ -> nm)
+ row.row_name row.row_fields in
+ if not row.row_closed || nm != row.row_name then begin
+ (* this unification cannot fail *)
+@@ -605,8 +605,8 @@
+ List.for_all
+ (fun (tag,f) ->
+ match Btype.row_field_repr f with
+- Rabsent | Reither(_, _, false, _) -> true
+- | Reither (_, _, true, _)
++ Rabsent | Reither(_, _, false, _, _) -> true
++ | Reither (_, _, true, _, _)
+ (* m=true, do not discard matched tags, rather warn *)
+ | Rpresent _ -> List.mem tag fields)
+ row.row_fields
+@@ -739,7 +739,7 @@
+ match Btype.row_field_repr f with
+ Rabsent (* | Reither _ *) -> others
+ (* This one is called after erasing pattern info *)
+- | Reither (c, _, _, _) -> make_other_pat tag c :: others
++ | Reither (c, _, _, _, _) -> make_other_pat tag c :: others
+ | Rpresent arg -> make_other_pat tag (arg = None) :: others)
+ [] row.row_fields
+ with
+Index: typing/printtyp.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/printtyp.ml,v
+retrieving revision 1.140
+diff -u -r1.140 printtyp.ml
+--- typing/printtyp.ml 4 Jan 2006 16:55:50 -0000 1.140
++++ typing/printtyp.ml 2 Feb 2006 06:28:33 -0000
+@@ -157,9 +157,12 @@
+ and raw_field ppf = function
+ Rpresent None -> fprintf ppf "Rpresent None"
+ | Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
+- | Reither (c,tl,m,e) ->
+- fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,@[<1>ref%t@])@]" c
+- raw_type_list tl m
++ | Reither (c,tl,m,tpl,e) ->
++ fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,%a,@,@[<1>ref%t@])@]"
++ c raw_type_list tl m
++ (raw_list
++ (fun ppf (t1,t2) ->
++ fprintf ppf "@[%a,@,%a@]" raw_type t1 raw_type t2)) tpl
+ (fun ppf ->
+ match !e with None -> fprintf ppf " None"
+ | Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
+@@ -219,8 +222,9 @@
+ List.for_all
+ (fun (_, f) ->
+ match row_field_repr f with
+- | Reither(c, l, _, _) ->
+- row.row_closed && if c then l = [] else List.length l = 1
++ | Reither(c, l, _, pl, _) ->
++ row.row_closed && pl = [] &&
++ if c then l = [] else List.length l = 1
+ | _ -> true)
+ row.row_fields
+
+@@ -392,13 +396,16 @@
+
+ and tree_of_row_field sch (l, f) =
+ match row_field_repr f with
+- | Rpresent None | Reither(true, [], _, _) -> (l, false, [])
+- | Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
+- | Reither(c, tyl, _, _) ->
+- if c (* contradiction: un constructeur constant qui a un argument *)
+- then (l, true, tree_of_typlist sch tyl)
+- else (l, false, tree_of_typlist sch tyl)
+- | Rabsent -> (l, false, [] (* une erreur, en fait *))
++ | Rpresent None | Reither(true, [], _, [], _) -> (l, false, [], [])
++ | Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty], [])
++ | Reither(c, tyl, _, tpl, _) ->
++ let ttpl =
++ List.map
++ (fun (t1,t2) -> tree_of_typexp sch t1, tree_of_typexp sch t2)
++ tpl
++ in
++ (l, c && tpl = [], tree_of_typlist sch tyl, ttpl)
++ | Rabsent -> (l, false, [], [] (* une erreur, en fait *))
+
+ and tree_of_typlist sch tyl =
+ List.map (tree_of_typexp sch) tyl
+Index: typing/typeclass.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typeclass.ml,v
+retrieving revision 1.85
+diff -u -r1.85 typeclass.ml
+--- typing/typeclass.ml 22 Jul 2005 06:42:36 -0000 1.85
++++ typing/typeclass.ml 2 Feb 2006 06:28:33 -0000
+@@ -727,7 +727,7 @@
+ {pexp_loc = loc; pexp_desc =
+ Pexp_match({pexp_loc = loc; pexp_desc =
+ Pexp_ident(Longident.Lident"*opt*")},
+- scases)} in
++ scases, false)} in
+ let sfun =
+ {pcl_loc = scl.pcl_loc; pcl_desc =
+ Pcl_fun(l, None, {ppat_loc = loc; ppat_desc = Ppat_var"*opt*"},
+Index: typing/typecore.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typecore.ml,v
+retrieving revision 1.178
+diff -u -r1.178 typecore.ml
+--- typing/typecore.ml 6 Jan 2006 02:25:37 -0000 1.178
++++ typing/typecore.ml 2 Feb 2006 06:28:33 -0000
+@@ -156,15 +156,21 @@
+ let field = row_field tag row in
+ begin match field with
+ | Rabsent -> assert false
+- | Reither (true, [], _, e) when not row.row_closed ->
+- set_row_field e (Rpresent None)
+- | Reither (false, ty::tl, _, e) when not row.row_closed ->
++ | Reither (true, [], _, tpl, e) when not row.row_closed ->
++ set_row_field e (Rpresent None);
++ List.iter
++ (fun (t1,t2) -> unify_pat pat.pat_env {pat with pat_type=t1} t2)
++ tpl
++ | Reither (false, ty::tl, _, tpl, e) when not row.row_closed ->
+ set_row_field e (Rpresent (Some ty));
++ List.iter
++ (fun (t1,t2) -> unify_pat pat.pat_env {pat with pat_type=t1} t2)
++ tpl;
+ begin match opat with None -> assert false
+ | Some pat -> List.iter (unify_pat pat.pat_env pat) (ty::tl)
+ end
+- | Reither (c, l, true, e) when not row.row_fixed ->
+- set_row_field e (Reither (c, [], false, ref None))
++ | Reither (c, l, true, tpl, e) when not row.row_fixed ->
++ set_row_field e (Reither (c, [], false, [], ref None))
+ | _ -> ()
+ end;
+ (* Force check of well-formedness *)
+@@ -307,13 +313,13 @@
+ match row_field_repr f with
+ Rpresent None ->
+ (l,None) :: pats,
+- (l, Reither(true,[], true, ref None)) :: fields
++ (l, Reither(true,[], true, [], ref None)) :: fields
+ | Rpresent (Some ty) ->
+ bound := ty :: !bound;
+ (l, Some {pat_desc=Tpat_any; pat_loc=Location.none; pat_env=env;
+ pat_type=ty})
+ :: pats,
+- (l, Reither(false, [ty], true, ref None)) :: fields
++ (l, Reither(false, [ty], true, [], ref None)) :: fields
+ | _ -> pats, fields)
+ ([],[]) fields in
+ let row =
+@@ -337,6 +343,18 @@
+ pat pats in
+ rp { r with pat_loc = loc }
+
++let rec flatten_or_pat pat =
++ match pat.pat_desc with
++ Tpat_or (p1, p2, _) ->
++ flatten_or_pat p1 @ flatten_or_pat p2
++ | _ ->
++ [pat]
++
++let all_variants pat =
++ List.for_all
++ (function {pat_desc=Tpat_variant _} -> true | _ -> false)
++ (flatten_or_pat pat)
++
+ let rec find_record_qual = function
+ | [] -> None
+ | (Longident.Ldot (modname, _), _) :: _ -> Some modname
+@@ -423,7 +441,7 @@
+ let arg = may_map (type_pat env) sarg in
+ let arg_type = match arg with None -> [] | Some arg -> [arg.pat_type] in
+ let row = { row_fields =
+- [l, Reither(arg = None, arg_type, true, ref None)];
++ [l, Reither(arg = None, arg_type, true, [], ref None)];
+ row_bound = arg_type;
+ row_closed = false;
+ row_more = newvar ();
+@@ -788,7 +806,7 @@
+ newty (Tarrow(p, type_option (newvar ()), type_approx env e, Cok))
+ | Pexp_function (p,_,(_,e)::_) ->
+ newty (Tarrow(p, newvar (), type_approx env e, Cok))
+- | Pexp_match (_, (_,e)::_) -> type_approx env e
++ | Pexp_match (_, (_,e)::_, false) -> type_approx env e
+ | Pexp_try (e, _) -> type_approx env e
+ | Pexp_tuple l -> newty (Ttuple(List.map (type_approx env) l))
+ | Pexp_ifthenelse (_,e,_) -> type_approx env e
+@@ -939,17 +957,26 @@
+ exp_loc = sexp.pexp_loc;
+ exp_type = ty_res;
+ exp_env = env }
+- | Pexp_match(sarg, caselist) ->
++ | Pexp_match(sarg, caselist, multi) ->
+ let arg = type_exp env sarg in
+ let ty_res = newvar() in
+ let cases, partial =
+- type_cases env arg.exp_type ty_res (Some sexp.pexp_loc) caselist
++ type_cases env arg.exp_type ty_res (Some sexp.pexp_loc) caselist ~multi
+ in
+ re {
+ exp_desc = Texp_match(arg, cases, partial);
+ exp_loc = sexp.pexp_loc;
+ exp_type = ty_res;
+ exp_env = env }
++ | Pexp_multifun caselist ->
++ let ty_arg = newvar() and ty_res = newvar() in
++ let cases, partial =
++ type_cases env ty_arg ty_res (Some sexp.pexp_loc) caselist ~multi:true
++ in
++ { exp_desc = Texp_function (cases, partial);
++ exp_loc = sexp.pexp_loc;
++ exp_type = newty (Tarrow ("", ty_arg, ty_res, Cok));
++ exp_env = env }
+ | Pexp_try(sbody, caselist) ->
+ let body = type_exp env sbody in
+ let cases, _ =
+@@ -1758,7 +1785,7 @@
+ {pexp_loc = loc; pexp_desc =
+ Pexp_match({pexp_loc = loc; pexp_desc =
+ Pexp_ident(Longident.Lident"*opt*")},
+- scases)} in
++ scases, false)} in
+ let sfun =
+ {pexp_loc = sexp.pexp_loc; pexp_desc =
+ Pexp_function(l, None,[{ppat_loc = loc; ppat_desc = Ppat_var"*opt*"},
+@@ -1864,7 +1891,8 @@
+
+ (* Typing of match cases *)
+
+-and type_cases ?in_function env ty_arg ty_res partial_loc caselist =
++and type_cases ?in_function ?(multi=false)
++ env ty_arg ty_res partial_loc caselist =
+ let ty_arg' = newvar () in
+ let pattern_force = ref [] in
+ let pat_env_list =
+@@ -1898,10 +1926,64 @@
+ let cases =
+ List.map2
+ (fun (pat, ext_env) (spat, sexp) ->
+- let exp = type_expect ?in_function ext_env sexp ty_res in
+- (pat, exp))
+- pat_env_list caselist
+- in
++ let add_variant_case lab row ty_res ty_res' =
++ let fi = List.assoc lab (row_repr row).row_fields in
++ begin match row_field_repr fi with
++ Reither (c, _, m, _, e) ->
++ let row' =
++ { row_fields =
++ [lab, Reither(c,[],false,[ty_res,ty_res'], ref None)];
++ row_more = newvar (); row_bound = [ty_res; ty_res'];
++ row_closed = false; row_fixed = false; row_name = None }
++ in
++ unify_pat ext_env {pat with pat_type= newty (Tvariant row)}
++ (newty (Tvariant row'))
++ | _ ->
++ unify_exp ext_env
++ { exp_desc = Texp_tuple []; exp_type = ty_res;
++ exp_env = ext_env; exp_loc = sexp.pexp_loc }
++ ty_res'
++ end
++ in
++ pat,
++ match pat.pat_desc with
++ _ when multi && all_variants pat ->
++ let ty_res' = newvar () in
++ List.iter
++ (function {pat_desc=Tpat_variant(lab,_,row)} ->
++ add_variant_case lab row ty_res ty_res'
++ | _ -> assert false)
++ (flatten_or_pat pat);
++ type_expect ?in_function ext_env sexp ty_res'
++ | Tpat_alias (p, id) when multi && all_variants p ->
++ let vd = Env.find_value (Path.Pident id) ext_env in
++ let row' =
++ match repr vd.val_type with
++ {desc=Tvariant row'} -> row'
++ | _ -> assert false
++ in
++ begin_def ();
++ let tv = newvar () in
++ let env = Env.add_value id {vd with val_type=tv} ext_env in
++ let exp = type_exp env sexp in
++ end_def ();
++ generalize exp.exp_type;
++ generalize tv;
++ List.iter
++ (function {pat_desc=Tpat_variant(lab,_,row)}, [tv'; ty'] ->
++ let fi' = List.assoc lab (row_repr row').row_fields in
++ let row' =
++ {row' with row_fields=[lab,fi']; row_more=newvar()} in
++ unify_pat ext_env {pat with pat_type=tv'}
++ (newty (Tvariant row'));
++ add_variant_case lab row ty_res ty'
++ | _ -> assert false)
++ (List.map (fun p -> p, instance_list [tv; exp.exp_type])
++ (flatten_or_pat p));
++ {exp with exp_type = instance exp.exp_type}
++ | _ ->
++ type_expect ?in_function ext_env sexp ty_res)
++ pat_env_list caselist in
+ let partial =
+ match partial_loc with None -> Partial
+ | Some loc -> Parmatch.check_partial loc cases
+Index: typing/typedecl.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typedecl.ml,v
+retrieving revision 1.75
+diff -u -r1.75 typedecl.ml
+--- typing/typedecl.ml 16 Aug 2005 00:48:56 -0000 1.75
++++ typing/typedecl.ml 2 Feb 2006 06:28:33 -0000
+@@ -432,8 +432,10 @@
+ match Btype.row_field_repr f with
+ Rpresent (Some ty) ->
+ compute_same ty
+- | Reither (_, tyl, _, _) ->
+- List.iter compute_same tyl
++ | Reither (_, tyl, _, tpl, _) ->
++ List.iter compute_same tyl;
++ List.iter (compute_variance_rec true true true)
++ (List.map fst tpl @ List.map snd tpl)
+ | _ -> ())
+ row.row_fields;
+ compute_same row.row_more
+@@ -856,8 +858,8 @@
+ explain row.row_fields
+ (fun (l,f) -> match Btype.row_field_repr f with
+ Rpresent (Some t) -> t
+- | Reither (_,[t],_,_) -> t
+- | Reither (_,tl,_,_) -> Btype.newgenty (Ttuple tl)
++ | Reither (_,[t],_,_,_) -> t
++ | Reither (_,tl,_,_,_) -> Btype.newgenty (Ttuple tl)
+ | _ -> Btype.newgenty (Ttuple[]))
+ "case" (fun (lab,_) -> "`" ^ lab ^ " of ")
+ | _ -> trivial ty'
+Index: typing/types.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/types.ml,v
+retrieving revision 1.25
+diff -u -r1.25 types.ml
+--- typing/types.ml 9 Dec 2004 12:40:53 -0000 1.25
++++ typing/types.ml 2 Feb 2006 06:28:33 -0000
+@@ -48,7 +48,9 @@
+
+ and row_field =
+ Rpresent of type_expr option
+- | Reither of bool * type_expr list * bool * row_field option ref
++ | Reither of
++ bool * type_expr list * bool *
++ (type_expr * type_expr) list * row_field option ref
+ | Rabsent
+
+ and abbrev_memo =
+Index: typing/types.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/types.mli,v
+retrieving revision 1.25
+diff -u -r1.25 types.mli
+--- typing/types.mli 9 Dec 2004 12:40:53 -0000 1.25
++++ typing/types.mli 2 Feb 2006 06:28:33 -0000
+@@ -47,7 +47,9 @@
+
+ and row_field =
+ Rpresent of type_expr option
+- | Reither of bool * type_expr list * bool * row_field option ref
++ | Reither of
++ bool * type_expr list * bool *
++ (type_expr * type_expr) list * row_field option ref
+ (* 1st true denotes a constant constructor *)
+ (* 2nd true denotes a tag in a pattern matching, and
+ is erased later *)
+Index: typing/typetexp.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typetexp.ml,v
+retrieving revision 1.54
+diff -u -r1.54 typetexp.ml
+--- typing/typetexp.ml 22 Jul 2005 06:42:36 -0000 1.54
++++ typing/typetexp.ml 2 Feb 2006 06:28:33 -0000
+@@ -207,9 +207,9 @@
+ match Btype.row_field_repr f with
+ | Rpresent (Some ty) ->
+ bound := ty :: !bound;
+- Reither(false, [ty], false, ref None)
++ Reither(false, [ty], false, [], ref None)
+ | Rpresent None ->
+- Reither (true, [], false, ref None)
++ Reither (true, [], false, [], ref None)
+ | _ -> f)
+ row.row_fields
+ in
+@@ -273,13 +273,16 @@
+ (l, f) :: fields
+ in
+ let rec add_field fields = function
+- Rtag (l, c, stl) ->
++ Rtag (l, c, stl, stpl) ->
+ name := None;
+ let f = match present with
+ Some present when not (List.mem l present) ->
+- let tl = List.map (transl_type env policy) stl in
+- bound := tl @ !bound;
+- Reither(c, tl, false, ref None)
++ let transl_list = List.map (transl_type env policy) in
++ let tl = transl_list stl in
++ let stpl1, stpl2 = List.split stpl in
++ let tpl1 = transl_list stpl1 and tpl2 = transl_list stpl2 in
++ bound := tl @ tpl1 @ tpl2 @ !bound;
++ Reither(c, tl, false, List.combine tpl1 tpl2, ref None)
+ | _ ->
+ if List.length stl > 1 || c && stl <> [] then
+ raise(Error(styp.ptyp_loc, Present_has_conjunction l));
+@@ -311,9 +314,9 @@
+ begin match f with
+ Rpresent(Some ty) ->
+ bound := ty :: !bound;
+- Reither(false, [ty], false, ref None)
++ Reither(false, [ty], false, [], ref None)
+ | Rpresent None ->
+- Reither(true, [], false, ref None)
++ Reither(true, [], false, [], ref None)
+ | _ ->
+ assert false
+ end
+@@ -406,7 +409,8 @@
+ {row with row_fixed=true;
+ row_fields = List.map
+ (fun (s,f as p) -> match Btype.row_field_repr f with
+- Reither (c, tl, m, r) -> s, Reither (c, tl, true, r)
++ Reither (c, tl, m, tpl, r) ->
++ s, Reither (c, tl, true, tpl, r)
+ | _ -> p)
+ row.row_fields};
+ Btype.iter_row make_fixed_univars row
+Index: typing/unused_var.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/unused_var.ml,v
+retrieving revision 1.5
+diff -u -r1.5 unused_var.ml
+--- typing/unused_var.ml 4 Jan 2006 16:55:50 -0000 1.5
++++ typing/unused_var.ml 2 Feb 2006 06:28:33 -0000
+@@ -122,9 +122,11 @@
+ | Pexp_apply (e, lel) ->
+ expression ppf tbl e;
+ List.iter (fun (_, e) -> expression ppf tbl e) lel;
+- | Pexp_match (e, pel) ->
++ | Pexp_match (e, pel, _) ->
+ expression ppf tbl e;
+ match_pel ppf tbl pel;
++ | Pexp_multifun pel ->
++ match_pel ppf tbl pel;
+ | Pexp_try (e, pel) ->
+ expression ppf tbl e;
+ match_pel ppf tbl pel;
+Index: bytecomp/matching.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/matching.ml,v
+retrieving revision 1.67
+diff -u -r1.67 matching.ml
+--- bytecomp/matching.ml 7 Sep 2005 16:07:48 -0000 1.67
++++ bytecomp/matching.ml 2 Feb 2006 06:28:33 -0000
+@@ -1991,7 +1991,7 @@
+ List.iter
+ (fun (_, f) ->
+ match Btype.row_field_repr f with
+- Rabsent | Reither(true, _::_, _, _) -> ()
++ Rabsent | Reither(true, _::_, _, _, _) -> ()
+ | _ -> incr num_constr)
+ row.row_fields
+ else
+Index: toplevel/genprintval.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/toplevel/genprintval.ml,v
+retrieving revision 1.38
+diff -u -r1.38 genprintval.ml
+--- toplevel/genprintval.ml 13 Jun 2005 04:55:53 -0000 1.38
++++ toplevel/genprintval.ml 2 Feb 2006 06:28:33 -0000
+@@ -293,7 +293,7 @@
+ | (l, f) :: fields ->
+ if Btype.hash_variant l = tag then
+ match Btype.row_field_repr f with
+- | Rpresent(Some ty) | Reither(_,[ty],_,_) ->
++ | Rpresent(Some ty) | Reither(_,[ty],_,_,_) ->
+ let args =
+ tree_of_val (depth - 1) (O.field obj 1) ty in
+ Oval_variant (l, Some args)
diff --git a/experimental/garrigue/multimatch.ml b/experimental/garrigue/multimatch.ml
new file mode 100644
index 0000000000..7c9aa73f91
--- /dev/null
+++ b/experimental/garrigue/multimatch.ml
@@ -0,0 +1,158 @@
+(* Simple example *)
+let f x =
+ (multimatch x with `A -> 1 | `B -> true),
+ (multimatch x with `A -> 1. | `B -> "1");;
+
+(* OK *)
+module M : sig
+ val f :
+ [< `A & 'a = int & 'b = float | `B & 'b =string & 'a = bool] -> 'a * 'b
+end = struct let f = f end;;
+
+(* Bad *)
+module M : sig
+ val f :
+ [< `A & 'a = int & 'b = float | `B & 'b =string & 'a = int] -> 'a * 'b
+end = struct let f = f end;;
+
+(* Should be good! *)
+module M : sig
+ val f :
+ [< `A & 'a = int * float | `B & 'a = bool * string] -> 'a
+end = struct let f = f end;;
+
+let f = multifun `A|`B as x -> f x;;
+
+(* Two-level example *)
+let f = multifun
+ `A -> (multifun `C -> 1 | `D -> 1.)
+ | `B -> (multifun `C -> true | `D -> "1");;
+
+(* OK *)
+module M : sig
+ val f :
+ [< `A & 'b = [< `C & 'a = int | `D & 'a = float & 'c = bool] -> 'a
+ | `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
+end = struct let f = f end;;
+
+(* Bad *)
+module M : sig
+ val f :
+ [< `A & 'b = [< `C & 'a = int | `D & 'a = bool] -> 'a
+ | `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
+end = struct let f = f end;;
+
+module M : sig
+ val f :
+ [< `A & 'b = [< `C & 'a = int | `D] -> 'a
+ | `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
+end = struct let f = f end;;
+
+
+(* Examples with hidden sharing *)
+let r = ref []
+let f = multifun `A -> 1 | `B -> true
+let g x = r := [f x];;
+
+(* Bad! *)
+module M : sig
+ val g : [< `A & 'a = int | `B & 'a = bool] -> unit
+end = struct let g = g end;;
+
+let r = ref []
+let f = multifun `A -> r | `B -> ref [];;
+(* Now OK *)
+module M : sig
+ val f : [< `A & 'b = int list ref | `B & 'b = 'c list ref] -> 'b
+end = struct let f = f end;;
+(* Still OK *)
+let l : int list ref = r;;
+module M : sig
+ val f : [< `A & 'b = int list ref | `B & 'b = 'c list ref] -> 'b
+end = struct let f = f end;;
+
+
+(* Examples that would need unification *)
+let f = multifun `A -> (1, []) | `B -> (true, [])
+let g x = fst (f x);;
+(* Didn't work, now Ok *)
+module M : sig
+ val g : [< `A & 'a * 'b = int * bool | `B & 'a * 'b = bool * int] -> 'a
+end = struct let g = g end;;
+let g = multifun (`A|`B) as x -> g x;;
+
+(* Other examples *)
+
+let f x =
+ let a = multimatch x with `A -> 1 | `B -> "1" in
+ (multifun `A -> print_int | `B -> print_string) x a
+;;
+
+let f = multifun (`A|`B) as x -> f x;;
+
+type unit_op = [`Set of int | `Move of int]
+type int_op = [`Get]
+
+let op r =
+ multifun
+ `Get -> !r
+ | `Set x -> r := x
+ | `Move dx -> r := !r + dx
+;;
+
+let rec trace r = function
+ [] -> []
+ | op1 :: ops ->
+ multimatch op1 with
+ #int_op as op1 ->
+ let x = op r op1 in
+ x :: trace r ops
+ | #unit_op as op1 ->
+ op r op1;
+ trace r ops
+;;
+
+class point x = object
+ val mutable x : int = x
+ method get = x
+ method set y = x <- y
+ method move dx = x <- x + dx
+end;;
+
+let poly sort coeffs x =
+ let add, mul, zero =
+ multimatch sort with
+ `Int -> (+), ( * ), 0
+ | `Float -> (+.), ( *. ), 0.
+ in
+ let rec compute = function
+ [] -> zero
+ | c :: cs -> add c (mul x (compute cs))
+ in
+ compute coeffs
+;;
+
+module M : sig
+ val poly : [< `Int & 'a = int | `Float & 'a = float] -> 'a list -> 'a -> 'a
+end = struct let poly = poly end;;
+
+type ('a,'b) num_sort =
+ 'b constraint 'b = [< `Int & 'a = int | `Float & 'a = float]
+module M : sig
+ val poly : ('a,_) num_sort -> 'a list -> 'a -> 'a
+end = struct let poly = poly end;;
+
+
+(* type dispatch *)
+
+type num = [ `Int | `Float ]
+let print0 = multifun
+ `Int -> print_int
+ | `Float -> print_float
+;;
+let print1 = multifun
+ #num as x -> print0 x
+ | `List t -> List.iter (print0 t)
+ | `Pair(t1,t2) -> (fun (x,y) -> print0 t1 x; print0 t2 y)
+;;
+print1 (`Pair(`Int,`Float)) (1,1.0);;
diff --git a/experimental/garrigue/newlabels.ps b/experimental/garrigue/newlabels.ps
new file mode 100644
index 0000000000..01eac1945b
--- /dev/null
+++ b/experimental/garrigue/newlabels.ps
@@ -0,0 +1,1458 @@
+%!PS-Adobe-2.0
+%%Creator: dvipsk 5.78 p1.4 Copyright 1996-98 ASCII Corp.(www-ptex@ascii.co.jp)
+%%dvipsk 5.78 Copyright 1998 Radical Eye Software (www.radicaleye.com)
+%%Title: newlabels.dvi
+%%Pages: 2 0
+%%PageOrder: Ascend
+%%BoundingBox: 0 0 596 842
+%%EndComments
+%%BeginProcSet: PStoPS 1 15
+userdict begin
+[/showpage/erasepage/copypage]{dup where{pop dup load
+ type/operatortype eq{1 array cvx dup 0 3 index cvx put
+ bind def}{pop}ifelse}{pop}ifelse}forall
+[/letter/legal/executivepage/a4/a4small/b5/com10envelope
+ /monarchenvelope/c5envelope/dlenvelope/lettersmall/note
+ /folio/quarto/a5]{dup where{dup wcheck{exch{}put}
+ {pop{}def}ifelse}{pop}ifelse}forall
+/setpagedevice {pop}bind 1 index where{dup wcheck{3 1 roll put}
+ {pop def}ifelse}{def}ifelse
+/PStoPSmatrix matrix currentmatrix def
+/PStoPSxform matrix def/PStoPSclip{clippath}def
+/defaultmatrix{PStoPSmatrix exch PStoPSxform exch concatmatrix}bind def
+/initmatrix{matrix defaultmatrix setmatrix}bind def
+/initclip[{matrix currentmatrix PStoPSmatrix setmatrix
+ [{currentpoint}stopped{$error/newerror false put{newpath}}
+ {/newpath cvx 3 1 roll/moveto cvx 4 array astore cvx}ifelse]
+ {[/newpath cvx{/moveto cvx}{/lineto cvx}
+ {/curveto cvx}{/closepath cvx}pathforall]cvx exch pop}
+ stopped{$error/errorname get/invalidaccess eq{cleartomark
+ $error/newerror false put cvx exec}{stop}ifelse}if}bind aload pop
+ /initclip dup load dup type dup/operatortype eq{pop exch pop}
+ {dup/arraytype eq exch/packedarraytype eq or
+ {dup xcheck{exch pop aload pop}{pop cvx}ifelse}
+ {pop cvx}ifelse}ifelse
+ {newpath PStoPSclip clip newpath exec setmatrix} bind aload pop]cvx def
+/initgraphics{initmatrix newpath initclip 1 setlinewidth
+ 0 setlinecap 0 setlinejoin []0 setdash 0 setgray
+ 10 setmiterlimit}bind def
+end
+%%EndProcSet
+%DVIPSCommandLine: dvips -f newlabels
+%DVIPSParameters: dpi=300
+%DVIPSSource: TeX output 1999.10.26:1616
+%%BeginProcSet: tex.pro
+%!
+/TeXDict 300 dict def TeXDict begin /N{def}def /B{bind def}N /S{exch}N
+/X{S N}B /TR{translate}N /isls false N /vsize 11 72 mul N /hsize 8.5 72
+mul N /landplus90{false}def /@rigin{isls{[0 landplus90{1 -1}{-1 1}
+ifelse 0 0 0]concat}if 72 Resolution div 72 VResolution div neg scale
+isls{landplus90{VResolution 72 div vsize mul 0 exch}{Resolution -72 div
+hsize mul 0}ifelse TR}if Resolution VResolution vsize -72 div 1 add mul
+TR[matrix currentmatrix{dup dup round sub abs 0.00001 lt{round}if}
+forall round exch round exch]setmatrix}N /@landscape{/isls true N}B
+/@manualfeed{statusdict /manualfeed true put}B /@copies{/#copies X}B
+/FMat[1 0 0 -1 0 0]N /FBB[0 0 0 0]N /nn 0 N /IE 0 N /ctr 0 N /df-tail{
+/nn 8 dict N nn begin /FontType 3 N /FontMatrix fntrx N /FontBBox FBB N
+string /base X array /BitMaps X /BuildChar{CharBuilder}N /Encoding IE N
+end dup{/foo setfont}2 array copy cvx N load 0 nn put /ctr 0 N[}B /df{
+/sf 1 N /fntrx FMat N df-tail}B /dfs{div /sf X /fntrx[sf 0 0 sf neg 0 0]
+N df-tail}B /E{pop nn dup definefont setfont}B /ch-width{ch-data dup
+length 5 sub get}B /ch-height{ch-data dup length 4 sub get}B /ch-xoff{
+128 ch-data dup length 3 sub get sub}B /ch-yoff{ch-data dup length 2 sub
+get 127 sub}B /ch-dx{ch-data dup length 1 sub get}B /ch-image{ch-data
+dup type /stringtype ne{ctr get /ctr ctr 1 add N}if}B /id 0 N /rw 0 N
+/rc 0 N /gp 0 N /cp 0 N /G 0 N /sf 0 N /CharBuilder{save 3 1 roll S dup
+/base get 2 index get S /BitMaps get S get /ch-data X pop /ctr 0 N ch-dx
+0 ch-xoff ch-yoff ch-height sub ch-xoff ch-width add ch-yoff
+setcachedevice ch-width ch-height true[1 0 0 -1 -.1 ch-xoff sub ch-yoff
+.1 sub]{ch-image}imagemask restore}B /D{/cc X dup type /stringtype ne{]}
+if nn /base get cc ctr put nn /BitMaps get S ctr S sf 1 ne{dup dup
+length 1 sub dup 2 index S get sf div put}if put /ctr ctr 1 add N}B /I{
+cc 1 add D}B /bop{userdict /bop-hook known{bop-hook}if /SI save N @rigin
+0 0 moveto /V matrix currentmatrix dup 1 get dup mul exch 0 get dup mul
+add .99 lt{/QV}{/RV}ifelse load def pop pop}N /eop{SI restore userdict
+/eop-hook known{eop-hook}if showpage}N /@start{userdict /start-hook
+known{start-hook}if pop /VResolution X /Resolution X 1000 div /DVImag X
+/IE 256 array N 2 string 0 1 255{IE S dup 360 add 36 4 index cvrs cvn
+put}for pop 65781.76 div /vsize X 65781.76 div /hsize X}N /p{show}N
+/RMat[1 0 0 -1 0 0]N /BDot 260 string N /rulex 0 N /ruley 0 N /v{/ruley
+X /rulex X V}B /V{}B /RV statusdict begin /product where{pop false[
+(Display)(NeXT)(LaserWriter 16/600)]{dup length product length le{dup
+length product exch 0 exch getinterval eq{pop true exit}if}{pop}ifelse}
+forall}{false}ifelse end{{gsave TR -.1 .1 TR 1 1 scale rulex ruley false
+RMat{BDot}imagemask grestore}}{{gsave TR -.1 .1 TR rulex ruley scale 1 1
+false RMat{BDot}imagemask grestore}}ifelse B /QV{gsave newpath transform
+round exch round exch itransform moveto rulex 0 rlineto 0 ruley neg
+rlineto rulex neg 0 rlineto fill grestore}B /a{moveto}B /delta 0 N /tail
+{dup /delta X 0 rmoveto}B /M{S p delta add tail}B /b{S p tail}B /c{-4 M}
+B /d{-3 M}B /e{-2 M}B /f{-1 M}B /g{0 M}B /h{1 M}B /i{2 M}B /j{3 M}B /k{
+4 M}B /w{0 rmoveto}B /l{p -4 w}B /m{p -3 w}B /n{p -2 w}B /o{p -1 w}B /q{
+p 1 w}B /r{p 2 w}B /s{p 3 w}B /t{p 4 w}B /x{0 S rmoveto}B /y{3 2 roll p
+a}B /bos{/SS save N}B /eos{SS restore}B end
+
+%%EndProcSet
+TeXDict begin 39158280 55380996 1000 300 300 (newlabels.dvi)
+@start
+%DVIPSBitmapFont: Fa cmr6 6 2
+/Fa 2 51 df<187898181818181818181818181818FF08107D8F0F> 49
+D<1F00618040C08060C0600060006000C00180030006000C00102020207FC0FFC00B107F
+8F0F> I E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fb cmmi8 8 4
+/Fb 4 111 df<FFC0FF1C00181C00101C00101C00103800203800203800203800207000
+40700040700040700040E00080E00080E00080E00080E00100E00200E004006008003830
+000FC00018177E9618> 85 D<0300038003000000000000000000000000001C00240046
+0046008C000C0018001800180031003100320032001C0009177F960C> 105
+D<383C1E0044C6630047028100460301008E0703000C0603000C0603000C060300180C06
+00180C0620180C0C20180C0C40301804C0301807001B0E7F8D1F> 109
+D<383C0044C6004702004602008E06000C06000C06000C0600180C00180C401818401818
+80300980300E00120E7F8D15> I E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fc cmbx8 8 4
+/Fc 4 111 df<01800780FF80FF80078007800780078007800780078007800780078007
+800780078007800780FFF8FFF80D157D9414> 49 D<387C7C7C3800000000FCFC3C3C3C
+3C3C3C3C3C3C3C3CFFFF08187F970B> 105 D<FC7E0FC0FD8730E03E07C0F03E07C0F03C
+0780F03C0780F03C0780F03C0780F03C0780F03C0780F03C0780F03C0780F03C0780F0FF
+1FE3FCFF1FE3FC1E0F7E8E23> 109 D<FC7C00FD8E003E0F003E0F003C0F003C0F003C0F
+003C0F003C0F003C0F003C0F003C0F003C0F00FF3FC0FF3FC0120F7E8E17> I
+E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fd cmsy8 8 3
+/Fd 3 93 df<FFFFF0FFFFF014027D881B> 0 D<020002000200C218F2783AE00F800F80
+3AE0F278C2180200020002000D0E7E8E12> 3 D<03F8001FFF003C07806000C0C00060C0
+0060C00060C00060C00060C00060C00060C00060C00060C00060C00060C00060C00060C0
+006040002013137E9218> 92 D E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fe cmtt12 12 43
+/Fe 43 125 df<01818003C3C003C3C003C3C003C3C003C3C003C3C07FFFF0FFFFF8FFFF
+F87FFFF00787800787800787800F8F800F0F000F0F000F0F000F0F007FFFF0FFFFF8FFFF
+F87FFFF01E1E001E1E001E1E001E1E001E1E001E1E000C0C00151E7E9D1A> 35
+D<00E00003F00007F8000738000E1C000E1C000E1C000E1C000E38000E39FC0E71FC07F1
+FC07E1C007C1C00781C00783800F83801FC3803DC70078E70070EE00E07E00E07E00E03C
+08E03C1CE07E1C70FF1C7FE7F83FC3F80F00E0161E7F9D1A> 38
+D<0038007800F001E003C007800F000E001C001C0038003800700070007000E000E000E0
+00E000E000E000E000E000E000E000700070007000380038001C001C000E000F00078003
+C001E000F8007800380D2878A21A> 40 D<6000F00078003C001E000F000780038001C0
+01C000E000E0007000700070003800380038003800380038003800380038003800700070
+007000E000E001C001C0038007800F001E003C007800F00060000D287CA21A> I<7FFFC0
+FFFFE0FFFFE07FFFC013047D901A> 45 D<00C001C001C003C007C00FC07FC0FDC071C0
+01C001C001C001C001C001C001C001C001C001C001C001C001C001C001C001C001C001C0
+7FFF7FFF7FFF101E7B9D1A> 49 D<03F8000FFE001FFF803C07C07801E07000E0E00070
+F00070F000706000700000700000700000E00000E00001C00003C0000780000F00001E00
+003C0000780000F00003E00007C0000F00001E00703C00707FFFF0FFFFF07FFFF0141E7D
+9D1A> I<03FC000FFF003FFFC03C03E07800E07800707800700000700000700000E00001
+E00007C003FF8003FF0003FFC00003E00000E0000070000078000038000038600038F000
+38F00078E000707000E07E03E03FFFC00FFF0001FC00151E7E9D1A> I<01FC0007FF001F
+FFC01F07C03C01E07800F07000707000707000707800F03800E01E03C00FFF8003FE0007
+FF001F8FC03C01E07800F0700070E00038E00038E00038E00038F000787000707800F03E
+03E01FFFC007FF0001FC00151E7E9D1A> 56 D<01F00007FC001FFE003E0F0038078070
+03807001C0E001C0E001C0E001E0E000E0E000E0E001E07001E07803E03C0FE01FFFE00F
+FCE003F0E00001C00001C00001C0000380600380F00700F00F00F03E007FFC003FF0000F
+C000131E7D9D1A> I<3078FCFC78300000000000000000003078FCFC7830061576941A>
+I<183C7E7E3C18000000000000000000183C7E7E3E1E0E0E1C3CF8F060071C77941A> I<
+0000C00003E00007E0000FC0003F80007E0000FC0003F80007E0000FC0003F80007E0000
+FC0000FC00007E00003F80000FC00007E00003F80000FC00007E00003F80000FC00007E0
+0003E00000C0131A7D9B1A> I<7FFFF0FFFFF8FFFFF87FFFF00000000000000000000000
+007FFFF0FFFFF8FFFFF87FFFF0150C7E941A> I<600000F80000FC00007E00003F80000F
+C00007E00003F80000FC00007E00003F80000FC00007E00007E0000FC0003F80007E0000
+FC0003F80007E0000FC0003F80007E0000FC0000F80000600000131A7D9B1A> I<007C38
+01FF3807FFF80F83F81E00F81C0078380078380038700038700038700000E00000E00000
+E00000E00000E00000E00000E00000E000007000007000387000383800383800381C0070
+1E00F00F83E007FFC001FF80007C00151E7E9D1A> 67 D<FE03FEFF03FEFF03FE1D8070
+1D80701DC0701CC0701CC0701CE0701CE0701C60701C70701C70701C30701C38701C3870
+1C18701C1C701C1C701C0C701C0E701C0E701C06701C06701C07701C03701C0370FF81F0
+FF81F0FF80F0171E7F9D1A> 78 D<03F8E00FFEE01FFFE03C07E07801E0F001E0E000E0
+E000E0E000E0E000007000007800003F80001FF80007FF00007FC00007E00000F0000070
+000038000038600038E00038E00038E00070F000F0FE01E0FFFFC0EFFF80E1FE00151E7E
+9D1A> 83 D<7FFFFEFFFFFEFFFFFEE0380EE0380EE0380EE0380E003800003800003800
+003800003800003800003800003800003800003800003800003800003800003800003800
+00380000380000380000380000380003FF8003FF8003FF80171E7F9D1A> I<FFFCFFFCFF
+FCE000E000E000E000E000E000E000E000E000E000E000E000E000E000E000E000E000E0
+00E000E000E000E000E000E000E000E000E000E000E000E000E000E000E000FFFCFFFCFF
+FC0E2776A21A> 91 D<FFFCFFFCFFFC001C001C001C001C001C001C001C001C001C001C
+001C001C001C001C001C001C001C001C001C001C001C001C001C001C001C001C001C001C
+001C001C001C001C001CFFFCFFFCFFFC0E277FA21A> 93 D<1FF0003FFC007FFE00780F
+00300700000380000380007F8007FF801FFF803F8380780380700380E00380E00380E003
+80700780780F803FFFFC1FFDFC07F0FC16157D941A> 97 D<7E0000FE00007E00000E00
+000E00000E00000E00000E00000E00000E3E000EFF800FFFE00FC1F00F80700F00380E00
+380E001C0E001C0E001C0E001C0E001C0E001C0E001C0F00380F00780F80F00FC1E00FFF
+C00EFF80063E00161E7F9D1A> I<00FF8003FFC00FFFE01F01E03C00C078000070000070
+0000E00000E00000E00000E00000E000007000007000007800703C00701F01F00FFFE003
+FFC000FE0014157D941A> I<000FC0001FC0000FC00001C00001C00001C00001C00001C0
+0001C001F1C007FDC00FFFC01E0FC03C07C07803C07001C0E001C0E001C0E001C0E001C0
+E001C0E001C0E001C07003C07003C03807C03E0FC01FFFF807FDFC01F1F8161E7E9D1A>
+I<01F80007FF000FFF801E07C03C01C07800E07000E0E00070E00070FFFFF0FFFFF0FFFF
+F0E000007000007000007800703C00701F01F00FFFE003FF8000FE0014157D941A> I<00
+07E0001FF0003FF800787800F03000E00000E00000E00000E0007FFFF0FFFFF0FFFFF000
+E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000
+E00000E00000E0003FFF807FFFC03FFF80151E7F9D1A> I<7E0000FE00007E00000E0000
+0E00000E00000E00000E00000E00000E3E000EFF800FFFC00FC1C00F80E00F00E00E00E0
+0E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E07FC3FC
+FFE7FE7FC3FC171E7F9D1A> 104 D<00C00001E00001E00000C000000000000000000000
+0000000000000000007FE0007FE0007FE00000E00000E00000E00000E00000E00000E000
+00E00000E00000E00000E00000E00000E00000E00000E00000E0007FFF80FFFFC07FFF80
+121F7C9E1A> I<7FE000FFE0007FE00000E00000E00000E00000E00000E00000E00000E0
+0000E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000E0
+0000E00000E00000E00000E00000E0007FFFC0FFFFE07FFFC0131E7D9D1A> 108
+D<7CE0E000FFFBF8007FFFF8001F1F1C001E1E1C001E1E1C001C1C1C001C1C1C001C1C1C
+001C1C1C001C1C1C001C1C1C001C1C1C001C1C1C001C1C1C001C1C1C001C1C1C001C1C1C
+007F1F1F00FFBFBF807F1F1F00191580941A> I<7E3E00FEFF807FFFC00FC1C00F80E00F
+00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E
+00E07FC3FCFFE7FE7FC3FC17157F941A> I<01F00007FC001FFF003E0F803C07807803C0
+7001C0E000E0E000E0E000E0E000E0E000E0E000E0F001E07001C07803C03C07803E0F80
+1FFF0007FC0001F00013157D941A> I<7E3E00FEFF807FFFE00FC1F00F80700F00380E00
+380E001C0E001C0E001C0E001C0E001C0E001C0E001C0F00380F00780F80F00FC1E00FFF
+C00EFF800E3E000E00000E00000E00000E00000E00000E00000E00000E00007FC000FFE0
+007FC00016207F941A> I<7F81F8FF8FFC7F9FFE03FE1E03F80C03E00003E00003C00003
+80000380000380000380000380000380000380000380000380000380007FFF00FFFF007F
+FF0017157F941A> 114 D<07FB801FFF807FFF80780780E00380E00380E003807800007F
+C0001FFC0007FE00003F800007806001C0E001C0E001C0F003C0FC0780FFFF00EFFE00E3
+F80012157C941A> I<0180000380000380000380000380000380000380007FFFE0FFFFE0
+FFFFE0038000038000038000038000038000038000038000038000038000038000038070
+03807003807003807001C1E001FFE000FF80003F00141C7F9B1A> I<7E07E0FE0FE07E07
+E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00E00
+E00E00E00E01E00F03E007FFFC03FFFE00FCFC17157F941A> I<7F83FCFFC7FE7F83FC0E
+00E00E00E00E00E00701C00701C00701C003838003838003838001C70001C70001C70000
+EE0000EE0000EE00007C00007C0000380017157F941A> I<FF83FEFF83FEFF83FE380038
+3800381C00701C00701C00701C38701C7C701C7C700C6C600EEEE00EEEE00EEEE00EEEE0
+0EC6E006C6C007C7C00783C00783C017157F941A> I<7FC7F87FCFFC7FC7F80703C00383
+8003C70001EF0000FE00007C00007800003800007C0000EE0001EE0001C7000383800783
+C00F01C07FC7FCFFC7FE7FC7FC17157F941A> I<7F83FCFFC7FE7F83FC0E00E00E00E007
+00E00701C00701C00381C003838003C38001C38001C70000E70000E70000E60000660000
+6E00003C00003C00003C0000380000380000380000700000700030F00078E00071E0007F
+C0003F80001E000017207F941A> I<60F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0
+F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F060042775A21A> 124 D
+E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Ff cmr8 8 3
+/Ff 3 51 df<003000003000003000003000003000003000003000003000003000003000
+003000FFFFFCFFFFFC003000003000003000003000003000003000003000003000003000
+00300000300016187E931B> 43 D<06000E00FE000E000E000E000E000E000E000E000E
+000E000E000E000E000E000E000E000E000E00FFE00B157D9412> 49
+D<0F8030E040708030C038E0384038003800700070006000C00180030006000C08080810
+183FF07FF0FFF00D157E9412> I E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fg cmmi12 12 13
+/Fg 13 121 df<0FFFF81FFFFC3FFFF870200040200080200080600000600000600000C0
+0000C00000C00000C00001C0000180000180000380000380000380000700000300001615
+7E9415> 28 D<0000100000002000000020000000200000002000000040000000400000
+004000000040000000800000008000000080000000800000010000000FE00000711C0001
+C10600030203000E0203801C020180180201C0380401C0700401C0700401C0700401C0E0
+080380E0080380E00807006008070070100E0030101C00301038001C10E0000623800001
+FE0000002000000020000000400000004000000040000000400000008000000080000000
+800000008000001A2D7EA21D> 30 D<70F8F8F87005057C840E> 58
+D<70F8FCFC7404040404080810102040060F7C840E> I<00008000018000018000030000
+0300000300000600000600000600000C00000C00000C0000180000180000180000300000
+300000300000600000600000600000C00000C00000C00001800001800001800001800003
+00000300000300000600000600000600000C00000C00000C000018000018000018000030
+0000300000300000600000600000600000C00000C00000C0000011317DA418> 61
+D<00FFFC00000F8000000F0000000F0000001E0000001E0000001E0000001E0000003C00
+00003C0000003C0000003C00000078000000780000007800000078000000F0000000F000
+0000F0000000F0000001E0000001E0000001E0002001E0002003C0004003C0004003C000
+8003C0008007800180078001000780030007800F000F803E00FFFFFE001B227DA121> 76
+D<1FFFFFFE1E01E00E1801E0063001E0062003C0062003C0064003C0044003C004400780
+04800780048007800400078000000F0000000F0000000F0000000F0000001E0000001E00
+00001E0000001E0000003C0000003C0000003C0000003C00000078000000780000007800
+000078000000F0000000F0000000F0000000F0000001F000007FFFC0001F227EA11D> 84
+D<3FFE01FF8003C0003C0003C000300003C0001000078000200007800020000780002000
+07800020000F000040000F000040000F000040000F000040001E000080001E000080001E
+000080001E000080003C000100003C000100003C000100003C0001000078000200007800
+020000780002000078000200007000040000F000040000F0000800007000080000700010
+00007000200000380040000038008000001C01000000060600000001F800000021237DA1
+21> I<007E000381000700800E00801C0080380080780100700600FFF800F00000F00000
+E00000E00000E00000E00000E00080E000807003003004001838000FC00011157D9417>
+101 D<01E00FC001C001C001C0038003800380038007000700070007000E000E000E000E
+001C001C001C001C0038003800380038007000700070007080E100E100E100620062003C
+000B237EA20F> 108 D<03C0F004631C04740E08780E08700708700708700F00E00F00E0
+0F00E00F00E00F01C01E01C01E01C01E01C03C03803803803803C07003C0E0072180071E
+000700000700000E00000E00000E00000E00001C00001C00001C0000FF8000181F819418
+> 112 D<3C0F004630C04741C08783C08783C08701808700000E00000E00000E00000E00
+001C00001C00001C00001C000038000038000038000038000070000030000012157E9416
+> 114 D<01E0F006310C081A1C101A3C201C3C201C18201C000038000038000038000038
+0000700000700000700000700860E010F0E010F0E020E170404230803C1F0016157E941C
+> 120 D E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fh cmti12 12 22
+/Fh 22 122 df<FFF0FFF0FFE00C037C8B11> 45 D<70F8F8F0E005057A840F> I<00F8
+C00185C00705C00E03800E03801C03803C0380380700780700780700780700F00E00F00E
+00F00E00F00E10F01C20701C20703C20305C40308C400F078014157B9419> 97
+D<03C01F8003800380038007000700070007000E000E000E000E001C001CF81D0C1E0E3C
+0638073807380F700F700F700F700FE01EE01EE01EE03CE038E038607060E031C01F0010
+237BA216> I<007E0001C1000301800703800E07801C07803C0000380000780000780000
+780000F00000F00000F00000F00000F00100700100700200300C001830000FC00011157B
+9416> I<00003C0003F80000380000380000380000700000700000700000700000E00000
+E00000E00000E00001C000F9C00185C00705C00E03800E03801C03803C03803807007807
+00780700780700F00E00F00E00F00E00F00E10F01C20701C20703C20305C40308C400F07
+8016237BA219> I<00F803840E021C023C0238027804F018FFE0F000F000E000E000E000
+E000E002E0026004701830600F800F157A9416> I<00003E0000470000CF00018F000186
+000380000380000380000700000700000700000700000700000E0000FFF0000E00000E00
+000E00001C00001C00001C00001C00001C00003800003800003800003800003800007000
+00700000700000700000700000E00000E00000E00000E00000C00001C00001C000718000
+F18000F300006200003C0000182D82A20F> I<001F180030B800E0B801C07001C0700380
+700780700700E00F00E00F00E00F00E01E01C01E01C01E01C01E01C01E03800E03800E07
+80060B8006170001E700000700000700000E00000E00000E00701C00F01800F0300060E0
+003F8000151F7E9416> I<00C001E001C001C0000000000000000000000000000000001E
+002300430043008700870087000E000E001C001C001C0038003800384070807080708071
+0032001C000B217BA00F> 105 D<00F00007E00000E00000E00000E00001C00001C00001
+C00001C0000380000380000380000380000700000701E00702100704700E08F00E10F00E
+20600E40001D80001E00001FC0001C7000383800383800381C00381C2070384070384070
+3840701880E01880600F0014237DA216> 107 D<01E00FC001C001C001C0038003800380
+038007000700070007000E000E000E000E001C001C001C001C0038003800380038007000
+700070007100E200E200E200E200640038000B237CA20C> I<1C0F80F8002610C10C0047
+6066060087807807008780780700870070070087007007000E00E00E000E00E00E000E00
+E00E000E00E00E001C01C01C001C01C01C001C01C01C001C01C038203803803840380380
+70403803807080380380308070070031003003001E0023157B9428> I<380F804C30C04E
+40608E80708F00708E00708E00701C00E01C00E01C00E01C00E03801C03801C03801C038
+0384700388700308700708700310E003106001E016157B941B> I<007E0001C300038180
+0701C00E01C01C01E03C01E03801E07801E07801E07801E0F003C0F003C0F00380F00780
+700700700E00700C0030180018700007C00013157B9419> I<01C1F002621804741C0878
+0C08700E08700E08701E00E01E00E01E00E01E00E01E01C03C01C03C01C03C01C0780380
+7003807003C0E003C1C0072380071E000700000700000E00000E00000E00000E00001C00
+001C00001C0000FFC000171F7F9419> I<1C1F002620804741C08783C08703C087018087
+00000E00000E00000E00000E00001C00001C00001C00001C000038000038000038000038
+000070000030000012157B9415> 114 D<00FC000183000200800401800C03800C03000C
+00000F00000FF00007FC0003FE00003E00000F00000700700700F00600F00600E0040040
+08002030001FC00011157D9414> I<00C001C001C001C001C003800380038003800700FF
+F8070007000E000E000E000E001C001C001C001C00380038003800381070207020704070
+8031001E000D1F7C9E10> I<1E0060E02300E0F04380E1F04381C0F08381C0708701C030
+8701C030070380200E0380200E0380200E0380201C0700401C0700401C0700401C070080
+1C0700801C0701001C0F01000C0B02000613840003E0F8001C157B9420> 119
+D<03C1E0046210083470103CF02038F020386020380000700000700000700000700000E0
+0000E00000E00000E02061C040F1C040F1C080E2C100446200383C0014157D9416> I<1E
+00302300704380704380E08380E08700E08700E00701C00E01C00E01C00E01C01C03801C
+03801C03801C03801C07001C07001C07001C0F000C3E0003CE00000E00000E00001C0060
+1C00F03800F03000E0600080C0004380003E0000141F7B9418> I
+E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fi cmbx12 12 20
+/Fi 20 122 df<FFFFFF8000FFFFFFF00007F003FC0007F0007E0007F0003F0007F0001F
+8007F0000FC007F00007E007F00007E007F00007F007F00003F007F00003F007F00003F0
+07F00003F807F00003F807F00003F807F00003F807F00003F807F00003F807F00003F807
+F00003F807F00003F807F00003F007F00003F007F00003F007F00007E007F00007E007F0
+000FC007F0001F8007F0003F0007F0007E0007F003FC00FFFFFFF000FFFFFF800025227E
+A12B> 68 D<01FE0207FF861F01FE3C007E7C001E78000E78000EF80006F80006FC0006
+FC0000FF0000FFE0007FFF007FFFC03FFFF01FFFF80FFFFC03FFFE003FFE0003FE00007F
+00003F00003FC0001FC0001FC0001FE0001EE0001EF0003CFC003CFF00F8C7FFE080FF80
+18227DA11F> 83 D<7FFFFFFF807FFFFFFF807E03F80F807803F807807003F803806003
+F80180E003F801C0E003F801C0C003F800C0C003F800C0C003F800C0C003F800C00003F8
+00000003F800000003F800000003F800000003F800000003F800000003F800000003F800
+000003F800000003F800000003F800000003F800000003F800000003F800000003F80000
+0003F800000003F800000003F800000003F800000003F8000001FFFFF00001FFFFF00022
+227EA127> I<0FFC003FFF807E07C07E03E07E01E07E01F03C01F00001F00001F0003FF0
+03FDF01FC1F03F01F07E01F0FC01F0FC01F0FC01F0FC01F07E02F07E0CF81FF87F07E03F
+18167E951B> 97 D<FF000000FF0000001F0000001F0000001F0000001F0000001F0000
+001F0000001F0000001F0000001F0000001F0000001F0000001F0FE0001F3FF8001FE07C
+001F803E001F001F001F000F801F000F801F000FC01F000FC01F000FC01F000FC01F000F
+C01F000FC01F000FC01F000FC01F000F801F001F801F801F001FC03E001EE07C001C3FF8
+00180FC0001A237EA21F> I<00FF8007FFE00F83F01F03F03E03F07E03F07C01E07C0000
+FC0000FC0000FC0000FC0000FC0000FC00007C00007E00007E00003E00181F00300FC060
+07FFC000FF0015167E9519> I<00FE0007FF800F87C01E01E03E01F07C00F07C00F8FC00
+F8FC00F8FFFFF8FFFFF8FC0000FC0000FC00007C00007C00007E00003E00181F00300FC0
+7003FFC000FF0015167E951A> 101 D<001FC0007FE000F1F001E3F003E3F007C3F007C1
+E007C00007C00007C00007C00007C00007C000FFFE00FFFE0007C00007C00007C00007C0
+0007C00007C00007C00007C00007C00007C00007C00007C00007C00007C00007C00007C0
+0007C00007C0003FFC003FFC00142380A211> I<01FE0F0007FFBF800F87C7801F03E780
+1E01E0003E01F0003E01F0003E01F0003E01F0003E01F0001E01E0001F03E0000F87C000
+0FFF800009FE000018000000180000001C0000001FFFE0000FFFF80007FFFE001FFFFF00
+3C003F0078000F80F0000780F0000780F0000780F000078078000F003C001E001F007C00
+0FFFF80001FFC00019217F951C> I<1C003E007F007F007F003E001C0000000000000000
+00000000000000FF00FF001F001F001F001F001F001F001F001F001F001F001F001F001F
+001F001F001F001F001F00FFE0FFE00B247EA310> 105 D<FF00FF001F001F001F001F00
+1F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F00
+1F001F001F001F001F001F001F001F001F00FFE0FFE00B237EA210> 108
+D<FF07F007F000FF1FFC1FFC001F303E303E001F403E403E001F801F801F001F801F801F
+001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F
+001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F001F
+001F001F001F001F001F001F00FFE0FFE0FFE0FFE0FFE0FFE02B167E9530> I<FF07E000
+FF1FF8001F307C001F403C001F803E001F803E001F003E001F003E001F003E001F003E00
+1F003E001F003E001F003E001F003E001F003E001F003E001F003E001F003E001F003E00
+1F003E00FFE1FFC0FFE1FFC01A167E951F> I<00FE0007FFC00F83E01E00F03E00F87C00
+7C7C007C7C007CFC007EFC007EFC007EFC007EFC007EFC007EFC007E7C007C7C007C3E00
+F81F01F00F83E007FFC000FE0017167E951C> I<FF0FE000FF3FF8001FE07C001F803E00
+1F001F001F001F801F001F801F000FC01F000FC01F000FC01F000FC01F000FC01F000FC0
+1F000FC01F000FC01F001F801F001F801F803F001FC03E001FE0FC001F3FF8001F0FC000
+1F0000001F0000001F0000001F0000001F0000001F0000001F0000001F000000FFE00000
+FFE000001A207E951F> I<0FF3003FFF00781F00600700E00300E00300F00300FC00007F
+E0007FF8003FFE000FFF0001FF00000F80C00780C00380E00380E00380F00700FC0E00EF
+FC00C7F00011167E9516> 115 D<01800001800001800001800003800003800007800007
+80000F80003F8000FFFF00FFFF000F80000F80000F80000F80000F80000F80000F80000F
+80000F80000F80000F80000F81800F81800F81800F81800F81800F830007C30003FE0000
+F80011207F9F16> I<FF01FE00FF01FE001F003E001F003E001F003E001F003E001F003E
+001F003E001F003E001F003E001F003E001F003E001F003E001F003E001F003E001F003E
+001F003E001F007E001F00FE000F81BE0007FF3FC001FC3FC01A167E951F> I<FFE07FC0
+FFE07FC00F801C0007C0380003E0700003F0600001F8C00000F98000007F8000003F0000
+001F0000001F8000003FC0000037C0000063E00000C1F00001C0F8000380FC0007007E00
+0E003E00FF80FFE0FF80FFE01B167F951E> 120 D<FFE01FE0FFE01FE01F8007000F8006
+000FC00E0007C00C0007E00C0003E0180003E0180001F0300001F0300000F8600000F860
+00007CC000007CC000007FC000003F8000003F8000001F0000001F0000000E0000000E00
+00000C0000000C00000018000078180000FC380000FC300000FC60000069C000007F8000
+001F0000001B207F951E> I E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fj cmsy10 12 15
+/Fj 15 107 df<FFFFFFFCFFFFFFFC1E027C8C27> 0 D<03F0000FFC001FFE003FFF007F
+FF807FFF80FFFFC0FFFFC0FFFFC0FFFFC0FFFFC0FFFFC0FFFFC0FFFFC07FFF807FFF803F
+FF001FFE000FFC0003F00012147D9519> 15 D<000FFFFC007FFFFC01F0000003800000
+060000000C0000001800000030000000300000006000000060000000C0000000C0000000
+C0000000C0000000C0000000C0000000C0000000C0000000600000006000000030000000
+30000000180000000C000000060000000380000001E00000007FFFFC001FFFFC1E1E7C9A
+27> 26 D<00000001800000000001800000000001800000000001800000000000C00000
+000000C000000000006000000000003000000000003000000000001C00000000000E0000
+0000000700FFFFFFFFFFE0FFFFFFFFFFE0000000000700000000000E00000000001C0000
+000000300000000000300000000000600000000000C00000000000C00000000001800000
+00000180000000000180000000000180002B1A7D9832> 33 D<001FFF007FFF01E00003
+80000600000C0000180000300000300000600000600000600000C00000C00000FFFFFFFF
+FFFFC00000C000006000006000006000003000003000001800000C000006000003800001
+E000007FFF001FFF181E7C9A21> 50 D<00000300000300000600000600000C00000C00
+00180000180000300000300000600000600000C00000C00000C000018000018000030000
+0300000600000600000C00000C0000180000180000300000300000600000600000C00000
+C0000180000180000300000300000300000600000600000C00000C000018000018000030
+0000300000600000600000C00000400000183079A300> 54 D<C0C0C0C0C0C0C0C0E0E0
+C0C0C0C0C0C0C0C003127D9400> I<00008000018001F980070F000C0300180380180780
+3006C03006C0700CE0600C60600C60600C60E01870E01870E01870E03070E03070E03070
+E06070E06070E06070E06070E0C070E0C070E0C070E18070E180706180606300607300E0
+7300E03300C03600C01E01801E01800C03000F0E000DF800180000180000180000142A7E
+A519> 59 D<000100000003000000030000000300000003000000030000000300000003
+000000030000000300000003000000030000000300000003000000030000000300000003
+000000030000000300000003000000030000000300000003000000030000000300000003
+000000030000000300000003000000030000FFFFFFFEFFFFFFFE1F207C9F27> 63
+D<40000040C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000
+C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000
+C0C00000C0C00000C0C00000C0C00000C0C00000C0600001806000018030000300180006
+000E001C000780780001FFE000007F80001A1F7D9D21> 91 D<007F800001FFE0000780
+78000E001C0018000600300003006000018060000180C00000C0C00000C0C00000C0C000
+00C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C000
+00C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C00000C0C000
+00C0400000401A1F7D9D21> I<000C0000000C0000001E0000001E0000001E0000003300
+0000330000006180000061800000C0C00000C0C00000C0C0000180600001806000030030
+00030030000300300006001800060018000C000C000C000C000C000C0018000600180006
+003000030030000300600001806000018060000180C00000C0C00000401A1F7D9D21> 94
+D<0003C0001E0000380000700000E00000E00000E00000E00000E00000E00000E00000E0
+0000E00000E00000E00000E00000E00000E00000E00000E00000E00001C0000380000F00
+00F800000F000003800001C00000E00000E00000E00000E00000E00000E00000E00000E0
+0000E00000E00000E00000E00000E00000E00000E00000E00000E000007000003800001E
+000003C012317DA419> 102 D<F800000F000003800001C00000E00000E00000E00000E0
+0000E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000E0
+0000E000007000003800001E000003C0001E0000380000700000E00000E00000E00000E0
+0000E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000E00000E0
+0000E00001C0000380000F0000F8000012317DA419> I<C0C0C0C0C0C0C0C0C0C0C0C0C0
+C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0
+02317AA40E> 106 D E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fk cmr12 12 65
+/Fk 65 125 df<001FC1F00070371800C03E3C01807C3C0380783C070038000700380007
+003800070038000700380007003800070038000700380007003800FFFFFFC00700380007
+003800070038000700380007003800070038000700380007003800070038000700380007
+0038000700380007003800070038000700380007003800070038000700380007003C007F
+E1FFC01E2380A21C> 11 D<001FC0000070200000C01000018038000380780007007800
+0700300007000000070000000700000007000000070000000700000007000000FFFFF800
+070078000700380007003800070038000700380007003800070038000700380007003800
+070038000700380007003800070038000700380007003800070038000700380007003800
+070038007FE1FF80192380A21B> I<001FD8000070380000C07800018078000380780007
+0038000700380007003800070038000700380007003800070038000700380007003800FF
+FFF800070038000700380007003800070038000700380007003800070038000700380007
+003800070038000700380007003800070038000700380007003800070038000700380007
+003800070038007FF3FF80192380A21B> I<000FC07F00007031C08000E00B004001801E
+00E003803E01E007003C01E007001C00C007001C000007001C000007001C000007001C00
+0007001C000007001C000007001C0000FFFFFFFFE007001C01E007001C00E007001C00E0
+07001C00E007001C00E007001C00E007001C00E007001C00E007001C00E007001C00E007
+001C00E007001C00E007001C00E007001C00E007001C00E007001C00E007001C00E00700
+1C00E007001C00E07FF1FFCFFE272380A229> I<70F8FCFC740404040408081010204006
+0F7CA20E> 39 D<00200040008001000300060004000C000C0018001800300030003000
+7000600060006000E000E000E000E000E000E000E000E000E000E000E000E000E000E000
+6000600060007000300030003000180018000C000C000400060003000100008000400020
+0B327CA413> I<800040002000100018000C000400060006000300030001800180018001
+C000C000C000C000E000E000E000E000E000E000E000E000E000E000E000E000E000E000
+C000C000C001C0018001800180030003000600060004000C00180010002000400080000B
+327DA413> I<70F8FCFC7404040404080810102040060F7C840E> 44
+D<FFF8FFF80D02808B10> I<70F8F8F87005057C840E> I<01F000071C000C0600180300
+3803803803807001C07001C07001C07001C0F001E0F001E0F001E0F001E0F001E0F001E0
+F001E0F001E0F001E0F001E0F001E0F001E0F001E0F001E07001C07001C07001C07803C0
+3803803803801C07000C0600071C0001F00013227EA018> 48 D<008003800F80F38003
+800380038003800380038003800380038003800380038003800380038003800380038003
+800380038003800380038003800380038007C0FFFE0F217CA018> I<03F0000C1C001007
+002007804003C04003C08003E0F003E0F801E0F801E0F801E02003E00003E00003C00003
+C0000780000700000E00001C0000180000300000600000C0000180000100000200200400
+200800201800603000403FFFC07FFFC0FFFFC013217EA018> I<03F8000C1E00100F0020
+07804007C07807C07803C07807C03807C0000780000780000700000F00000C0000380003
+F000001C00000F000007800007800003C00003C00003E02003E07003E0F803E0F803E0F0
+03C04003C0400780200780100F000C1C0003F00013227EA018> I<000300000300000700
+000700000F00001700001700002700006700004700008700018700010700020700060700
+040700080700080700100700200700200700400700C00700FFFFF8000700000700000700
+000700000700000700000700000F80007FF015217FA018> I<70F8F8F870000000000000
+000000000070F8F8F87005157C940E> 58 D<FFFFFFFEFFFFFFFE000000000000000000
+0000000000000000000000000000000000000000000000FFFFFFFEFFFFFFFE1F0C7D9126
+> 61 D<07E01838201C400E800FF00FF00FF00F000F000E001C00380030006000C000C0
+00800080018001000100010001000100010000000000000000000000038007C007C007C0
+038010237DA217> 63 D<0001800000018000000180000003C0000003C0000003C00000
+05E0000005E0000009F0000008F0000008F00000107800001078000010780000203C0000
+203C0000203C0000401E0000401E0000C01F0000800F0000800F0001FFFF800100078001
+000780020003C0020003C0020003C0040001E0040001E0040001E0080000F01C0000F03E
+0001F8FF800FFF20237EA225> 65 D<FFFFF8000F800E0007800780078003C0078003E0
+078001E0078001F0078001F0078001F0078001F0078001F0078001E0078003E0078007C0
+07800F8007803E0007FFFE0007800780078003C0078001E0078001F0078000F0078000F8
+078000F8078000F8078000F8078000F8078000F8078001F0078001F0078003E0078007C0
+0F800F00FFFFFC001D227EA123> I<0007E0100038183000E0063001C00170038000F007
+0000F00E0000701E0000701C0000303C0000303C0000307C0000107800001078000010F8
+000000F8000000F8000000F8000000F8000000F8000000F8000000F80000007800000078
+0000107C0000103C0000103C0000101C0000201E0000200E000040070000400380008001
+C0010000E0020000381C000007E0001C247DA223> I<FFFFF0000F801E00078007000780
+0380078001C0078000E0078000F007800078078000780780007C0780003C0780003C0780
+003C0780003E0780003E0780003E0780003E0780003E0780003E0780003E0780003E0780
+003E0780003C0780003C0780007C0780007807800078078000F0078000E0078001E00780
+03C0078007000F801E00FFFFF0001F227EA125> I<FFFFFFC00F8007C0078001C0078000
+C00780004007800040078000600780002007800020078000200780202007802000078020
+0007802000078060000780E00007FFE0000780E000078060000780200007802000078020
+000780200007800000078000000780000007800000078000000780000007800000078000
+00078000000FC00000FFFE00001B227EA120> 70 D<0007F008003C0C1800E0021801C0
+01B8038000F8070000780F0000381E0000381E0000183C0000183C0000187C0000087800
+000878000008F8000000F8000000F8000000F8000000F8000000F8000000F8000000F800
+1FFF780000F8780000787C0000783C0000783C0000781E0000781E0000780F0000780700
+0078038000B801C000B800E00318003C0C080007F00020247DA226> I<FFFC3FFF0FC003
+F0078001E0078001E0078001E0078001E0078001E0078001E0078001E0078001E0078001
+E0078001E0078001E0078001E0078001E0078001E007FFFFE0078001E0078001E0078001
+E0078001E0078001E0078001E0078001E0078001E0078001E0078001E0078001E0078001
+E0078001E0078001E0078001E00FC003F0FFFC3FFF20227EA125> I<FFFC0FC007800780
+078007800780078007800780078007800780078007800780078007800780078007800780
+07800780078007800780078007800780078007800FC0FFFC0E227EA112> I<FFFC00FF80
+0FC0007C0007800030000780002000078000400007800080000780010000078002000007
+80040000078008000007801000000780200000078040000007808000000781C000000783
+E000000785E000000788F000000790F0000007A078000007C03C000007803C000007801E
+000007800F000007800F00000780078000078007C000078003C000078001E000078001E0
+00078000F000078000F8000FC000FC00FFFC07FF8021227EA126> 75
+D<FFFC001F80000F00000F00000F00000F00000F00000F00000F00000F00000F00000F00
+000F00000F00000F00000F00000F00000F00000F00000F00000F00000F00000F00010F00
+010F00010F00010F00030F00030F00020F00060F00060F001E1F007EFFFFFE18227DA11E
+> I<FF8007FF07C000F807C0007005E0002004F0002004F0002004780020047C0020043C
+0020041E0020041F0020040F002004078020040780200403C0200401E0200401E0200400
+F0200400F8200400782004003C2004003E2004001E2004000F2004000F20040007A00400
+03E0040003E0040001E0040001E0040000E00E0000601F000060FFE0002020227EA125>
+78 D<000FE00000783C0000E00E0003C00780078003C00F0001E00E0000E01E0000F03C
+0000783C0000787C00007C7C00007C7800003C7800003CF800003EF800003EF800003EF8
+00003EF800003EF800003EF800003EF800003EF800003E7800003C7C00007C7C00007C3C
+0000783E0000F81E0000F00F0001E00F0001E0078003C003C0078000E00E0000783C0000
+0FE0001F247DA226> I<FFFFF0000F803C0007800F0007800780078007C0078003C00780
+03E0078003E0078003E0078003E0078003E0078003E0078003C0078007C0078007800780
+0F0007803C0007FFF0000780000007800000078000000780000007800000078000000780
+0000078000000780000007800000078000000780000007800000078000000FC00000FFFC
+00001B227EA121> I<FFFFE000000F803C000007800E00000780078000078007C0000780
+03C000078003E000078003E000078003E000078003E000078003E000078003C000078007
+C000078007800007800E000007803C000007FFE000000780700000078038000007801C00
+0007801E000007800E000007800F000007800F000007800F000007800F000007800F8000
+07800F800007800F800007800F808007800FC080078007C0800FC003C100FFFC01E20000
+00007C0021237EA124> 82 D<03F0200C0C601802603001E07000E0600060E00060E000
+60E00020E00020E00020F00000F000007800007F00003FF0001FFE000FFF0003FF80003F
+C00007E00001E00000F00000F0000070800070800070800070800070C00060C00060E000
+C0F000C0C80180C6070081FC0014247DA21B> I<7FFFFFF8780780786007801840078008
+4007800840078008C007800C800780048007800480078004800780040007800000078000
+000780000007800000078000000780000007800000078000000780000007800000078000
+000780000007800000078000000780000007800000078000000780000007800000078000
+00078000000FC00001FFFE001E227EA123> I<FFF0007FC01F80001F000F00000C000F80
+000C000780000800078000080003C000100003C000100003C000100001E000200001E000
+200001F000600000F000400000F000400000780080000078008000007C008000003C0100
+00003C010000001E020000001E020000001E020000000F040000000F040000000F8C0000
+000788000000078800000003D000000003D000000003F000000001E000000001E0000000
+00C000000000C000000000C0000022237FA125> 86 D<FFF03FFC03FE1F8007E000F80F
+0003C000700F0003C000200F0001E00020078001E00040078001E00040078003F0004003
+C002F0008003C002F0008003C002F0008003E00478018001E00478010001E00478010001
+E0083C010000F0083C020000F0083C020000F0101E02000078101E04000078101E040000
+78200F0400003C200F0800003C200F0800003C600F8800001E40079000001E4007900000
+1E4007D000001F8003F000000F8003E000000F8003E000000F0001E00000070001C00000
+070001C00000060000C0000002000080002F237FA132> I<FEFEC0C0C0C0C0C0C0C0C0C0
+C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0FE
+FE07317BA40E> 91 D<FEFE060606060606060606060606060606060606060606060606
+060606060606060606060606060606060606060606FEFE07317FA40E> 93
+D<1FE000303800780C00780E0030070000070000070000070000FF0007C7001E07003C07
+00780700700700F00708F00708F00708F00F087817083C23900FC1E015157E9418> 97
+D<0E0000FE00001E00000E00000E00000E00000E00000E00000E00000E00000E00000E00
+000E00000E00000E1F000E61C00E80600F00300E00380E003C0E001C0E001E0E001E0E00
+1E0E001E0E001E0E001E0E001E0E001C0E003C0E00380F00700C80600C41C0083F001723
+7FA21B> I<01FE000703000C07801C0780380300780000700000F00000F00000F00000F0
+0000F00000F00000F000007000007800403800401C00800C010007060001F80012157E94
+16> I<0000E0000FE00001E00000E00000E00000E00000E00000E00000E00000E00000E0
+0000E00000E00000E001F8E00704E00C02E01C01E03800E07800E07000E0F000E0F000E0
+F000E0F000E0F000E0F000E0F000E07000E07800E03800E01801E00C02E0070CF001F0FE
+17237EA21B> I<01FC000707000C03801C01C03801C07801E07000E0F000E0FFFFE0F000
+00F00000F00000F00000F000007000007800203800201C00400E008007030000FC001315
+7F9416> I<003E0000E30001C78003878003078007000007000007000007000007000007
+0000070000070000070000FFF80007000007000007000007000007000007000007000007
+00000700000700000700000700000700000700000700000700000700000700000780007F
+F000112380A20F> I<00007003F1980E1E181C0E18380700380700780780780780780780
+7807803807003807001C0E001E1C0033F0002000002000003000003800003FFE001FFFC0
+0FFFE03000F0600030C00018C00018C00018C000186000306000303800E00E038003FE00
+15217F9518> I<0E0000FE00001E00000E00000E00000E00000E00000E00000E00000E00
+000E00000E00000E00000E00000E1F800E60C00E80E00F00700F00700E00700E00700E00
+700E00700E00700E00700E00700E00700E00700E00700E00700E00700E00700E00700E00
+70FFE7FF18237FA21B> I<1C003E003E003E001C00000000000000000000000000000000
+000E007E001E000E000E000E000E000E000E000E000E000E000E000E000E000E000E000E
+000E000E00FFC00A227FA10E> I<00E001F001F001F000E0000000000000000000000000
+00000000007007F000F00070007000700070007000700070007000700070007000700070
+00700070007000700070007000700070007000706070F0E0F0C061803F000C2C83A10F>
+I<0E0000FE00001E00000E00000E00000E00000E00000E00000E00000E00000E00000E00
+000E00000E00000E03FC0E01F00E01C00E01800E02000E04000E08000E10000E38000EF8
+000F1C000E1E000E0E000E07000E07800E03C00E01C00E01E00E00F00E00F8FFE3FE1723
+7FA21A> I<0E00FE001E000E000E000E000E000E000E000E000E000E000E000E000E000E
+000E000E000E000E000E000E000E000E000E000E000E000E000E000E000E000E000E000E
+00FFE00B237FA20E> I<0E1FC07F00FE60E183801E807201C00F003C00E00F003C00E00E
+003800E00E003800E00E003800E00E003800E00E003800E00E003800E00E003800E00E00
+3800E00E003800E00E003800E00E003800E00E003800E00E003800E00E003800E00E0038
+00E0FFE3FF8FFE27157F942A> I<0E1F80FE60C01E80E00F00700F00700E00700E00700E
+00700E00700E00700E00700E00700E00700E00700E00700E00700E00700E00700E00700E
+0070FFE7FF18157F941B> I<01FC000707000C01801800C03800E0700070700070F00078
+F00078F00078F00078F00078F00078F000787000707800F03800E01C01C00E0380070700
+01FC0015157F9418> I<0E1F00FE61C00E80600F00700E00380E003C0E003C0E001E0E00
+1E0E001E0E001E0E001E0E001E0E001E0E003C0E003C0E00380F00700E80E00E41C00E3F
+000E00000E00000E00000E00000E00000E00000E00000E00000E0000FFE000171F7F941B
+> I<01F8200704600E02601C01603801E07800E07800E0F000E0F000E0F000E0F000E0F0
+00E0F000E0F000E07800E07800E03801E01C01E00C02E0070CE001F0E00000E00000E000
+00E00000E00000E00000E00000E00000E00000E0000FFE171F7E941A> I<0E3CFE461E8F
+0F0F0F060F000E000E000E000E000E000E000E000E000E000E000E000E000E000F00FFF0
+10157F9413> I<0F8830786018C018C008C008E008F0007F003FE00FF001F8003C801C80
+0C800CC00CC008E018D0308FC00E157E9413> I<02000200020002000600060006000E00
+1E003E00FFFC0E000E000E000E000E000E000E000E000E000E000E000E040E040E040E04
+0E040E040708030801F00E1F7F9E13> I<0E0070FE07F01E00F00E00700E00700E00700E
+00700E00700E00700E00700E00700E00700E00700E00700E00700E00700E00F00E00F006
+017003827800FC7F18157F941B> I<FF80FE1E00781E00300E00200E0020070040070040
+0780C003808003808001C10001C10000E20000E20000E200007400007400003800003800
+00380000100017157F941A> I<FF8FF87F3E01E03C1C01C0181C01E0180E01E0100E0260
+100E027010070270200704302007043820038438400388184003881C4001C81C8001D00C
+8001D00E8000F00F0000E0070000E00700006006000040020020157F9423> I<FF83FE1F
+00F00E00C007008007810003830001C20000E400007800007800003800003C00004E0000
+8F000187000103800201C00401E00C00E03E01F0FF03FE17157F941A> I<FF80FE1E0078
+1E00300E00200E00200700400700400780C003808003808001C10001C10000E20000E200
+00E200007400007400003800003800003800001000001000002000002000002000004000
+F04000F08000F180004300003C0000171F7F941A> I<3FFFC0380380300780200700600E
+00401C00403C0040380000700000E00001E00001C0000380400700400F00400E00C01C00
+80380080780180700780FFFF8012157F9416> I<FFFFFFFFFFFF3001808C31> 124
+D E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fl cmbx12 14.4 19
+/Fl 19 118 df<00007FE0030007FFFC07001FFFFF0F007FF00F9F00FF0001FF01FC0000
+FF03F800007F07F000003F0FE000001F1FC000001F1FC000000F3F8000000F3F80000007
+7F800000077F800000077F00000000FF00000000FF00000000FF00000000FF00000000FF
+00000000FF00000000FF00000000FF00000000FF000000007F000000007F800000007F80
+0000073F800000073F800000071FC00000071FC000000E0FE000000E07F000001C03F800
+003C01FC00007800FF0001F0007FF007C0001FFFFF800007FFFE0000007FF00028297CA8
+31> 67 D<FFFFFC0000FFFFFC0000FFFFFC000003FC00000003FC00000003FC00000003
+FC00000003FC00000003FC00000003FC00000003FC00000003FC00000003FC00000003FC
+00000003FC00000003FC00000003FC00000003FC00000003FC00000003FC00000003FC00
+000003FC00000003FC00000003FC00000003FC0001C003FC0001C003FC0001C003FC0001
+C003FC0003C003FC00038003FC00038003FC00078003FC00078003FC000F8003FC000F80
+03FC001F8003FC007F8003FC01FF00FFFFFFFF00FFFFFFFF00FFFFFFFF0022297EA828>
+76 D<0000FFC00000000FFFFC0000003F807F000000FE001FC00001F80007E00003F000
+03F00007E00001F8000FE00001FC001FC00000FE001FC00000FE003F8000007F003F8000
+007F007F8000007F807F0000003F807F0000003F807F0000003F80FF0000003FC0FF0000
+003FC0FF0000003FC0FF0000003FC0FF0000003FC0FF0000003FC0FF0000003FC0FF0000
+003FC0FF0000003FC0FF0000003FC07F0000003F807F8000007F807F8000007F803F8000
+007F003F8000007F001FC00000FE001FC00000FE000FE00001FC0007F00003F80003F800
+07F00001FC000FE00000FE001FC000003FC0FF0000000FFFFC00000000FFC000002A297C
+A833> 79 D<FFFFF0007FFFFFFFF0007FFFFFFFF0007FFF03FE000001C001FE00000380
+01FE0000038001FF0000078000FF0000070000FF80000F00007F80000E00007FC0000E00
+003FC0001C00003FC0001C00003FE0003C00001FE0003800001FF0007800000FF0007000
+000FF80070000007F800E0000007F800E0000003FC01C0000003FC01C0000003FE03C000
+0001FE0380000001FF0780000000FF0700000000FF87000000007F8E000000007F8E0000
+00007FDE000000003FDC000000003FFC000000001FF8000000001FF8000000000FF00000
+00000FF0000000000FF00000000007E00000000007E00000000003C00000000003C00000
+30297FA833> 86 D<03FF80000FFFF0001F01FC003F80FE003F807F003F803F003F803F
+801F003F8000003F8000003F8000003F8000003F80003FFF8001FC3F800FE03F801F803F
+803F003F807E003F80FC003F80FC003F80FC003F80FC003F80FC005F807E00DF803F839F
+FC1FFE0FFC03FC03FC1E1B7E9A21> 97 D<FFE00000FFE00000FFE000000FE000000FE0
+00000FE000000FE000000FE000000FE000000FE000000FE000000FE000000FE000000FE0
+00000FE000000FE1FE000FEFFF800FFE07E00FF803F00FF001F80FE000FC0FE000FC0FE0
+007E0FE0007E0FE0007F0FE0007F0FE0007F0FE0007F0FE0007F0FE0007F0FE0007F0FE0
+007F0FE0007E0FE0007E0FE0007E0FE000FC0FE000FC0FF001F80FF803F00F9C0FE00F0F
+FF800E01FC00202A7EA925> I<00007FF000007FF000007FF0000007F0000007F0000007
+F0000007F0000007F0000007F0000007F0000007F0000007F0000007F0000007F0000007
+F0003F87F001FFF7F007F03FF00FC00FF01F8007F03F0007F03F0007F07E0007F07E0007
+F07E0007F0FE0007F0FE0007F0FE0007F0FE0007F0FE0007F0FE0007F0FE0007F0FE0007
+F07E0007F07E0007F03F0007F03F0007F01F800FF00FC01FF007E07FFF01FFE7FF007F87
+FF202A7EA925> 100 D<003FC00001FFF00003E07C000F803E001F801F001F001F003F00
+0F807E000F807E000FC07E000FC0FE0007C0FE0007C0FFFFFFC0FFFFFFC0FE000000FE00
+0000FE0000007E0000007E0000007F0000003F0001C01F0001C00F80038007C0070003F0
+1E0000FFFC00003FE0001A1B7E9A1F> I<0007F8003FFC007E3E01FC7F03F87F03F07F07
+F07F07F03E07F00007F00007F00007F00007F00007F00007F000FFFFC0FFFFC0FFFFC007
+F00007F00007F00007F00007F00007F00007F00007F00007F00007F00007F00007F00007
+F00007F00007F00007F00007F00007F00007F00007F00007F0007FFF807FFF807FFF8018
+2A7EA915> I<FFE00000FFE00000FFE000000FE000000FE000000FE000000FE000000FE0
+00000FE000000FE000000FE000000FE000000FE000000FE000000FE000000FE07E000FE1
+FF800FE30FC00FE40FE00FE807E00FF807F00FF007F00FF007F00FE007F00FE007F00FE0
+07F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE0
+07F00FE007F00FE007F00FE007F00FE007F0FFFE3FFFFFFE3FFFFFFE3FFF202A7DA925>
+104 D<07000F801FC03FE03FE03FE01FC00F8007000000000000000000000000000000FF
+E0FFE0FFE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00F
+E00FE00FE00FE00FE00FE0FFFEFFFEFFFE0F2B7EAA12> I<FFE0FFE0FFE00FE00FE00FE0
+0FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE0
+0FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE00FE0FFFEFFFEFFFE
+0F2A7EA912> 108 D<FFC07E00FFC1FF80FFC30FC00FC40FE00FC807E00FD807F00FD007
+F00FD007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007
+F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F0FFFE3F
+FFFFFE3FFFFFFE3FFF201B7D9A25> 110 D<003FE00001FFFC0003F07E000FC01F801F80
+0FC03F0007E03F0007E07E0003F07E0003F07E0003F0FE0003F8FE0003F8FE0003F8FE00
+03F8FE0003F8FE0003F8FE0003F8FE0003F87E0003F07E0003F03F0007E03F0007E01F80
+0FC00FC01F8007F07F0001FFFC00003FE0001D1B7E9A22> I<FFE1FE00FFEFFF80FFFE0F
+E00FF803F00FF001F80FE001FC0FE000FC0FE000FE0FE000FE0FE0007F0FE0007F0FE000
+7F0FE0007F0FE0007F0FE0007F0FE0007F0FE0007F0FE0007E0FE000FE0FE000FE0FE000
+FC0FE001FC0FF001F80FF807F00FFC0FE00FEFFF800FE1FC000FE000000FE000000FE000
+000FE000000FE000000FE000000FE000000FE000000FE00000FFFE0000FFFE0000FFFE00
+0020277E9A25> I<FFC1F0FFC7FCFFC63E0FCC7F0FD87F0FD07F0FD07F0FF03E0FE0000F
+E0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE0000F
+E0000FE0000FE000FFFF00FFFF00FFFF00181B7F9A1B> 114 D<03FE300FFFF03E03F078
+00F07000F0F00070F00070F80070FE0000FFE0007FFF007FFFC03FFFE01FFFF007FFF800
+FFF80007FC0000FCE0007CE0003CF0003CF00038F80038FC0070FF01E0E7FFC0C1FF0016
+1B7E9A1B> I<00E00000E00000E00000E00001E00001E00001E00003E00003E00007E000
+0FE0001FFFE0FFFFE0FFFFE00FE0000FE0000FE0000FE0000FE0000FE0000FE0000FE000
+0FE0000FE0000FE0000FE0000FE0000FE0700FE0700FE0700FE0700FE0700FE0700FE070
+07F0E003F0C001FF80007F0014267FA51A> I<FFE07FF0FFE07FF0FFE07FF00FE007F00F
+E007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00F
+E007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE007F00FE00FF00F
+E00FF007E017F003F067FF01FFC7FF007F87FF201B7D9A25> I E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fm cmr12 14.4 20
+/Fm 20 118 df<78FCFCFEFE7A02020202040404080810204007127B8510> 44
+D<00200000E00001E0000FE000FFE000F1E00001E00001E00001E00001E00001E00001E0
+0001E00001E00001E00001E00001E00001E00001E00001E00001E00001E00001E00001E0
+0001E00001E00001E00001E00001E00001E00001E00001E00001E00001E00001E00001E0
+0001E00003F000FFFFC0FFFFC012287BA71D> 49 D<01FC0007FF000C0FC01803E02001
+F06001F04000F84000F8F800FCFC00FCFC007CFC007CFC007C7800FC0000FC0000F80000
+F80001F00001F00003E00003C0000780000700000E00001C0000380000300000600000C0
+000180000300040200040400080800081000082000183FFFF87FFFF0FFFFF0FFFFF01628
+7DA71D> I<000FC0003FF000F01801C01803803C07007C0F007C0E00381E00003C00003C
+00003C0000780000780000780000F83F00F8C1C0F900E0FA0070FA0038FC003CFC001EFC
+001EF8001EF8001FF8001FF8001FF8001F78001F78001F78001F78001F3C001E3C001E1C
+003C1E003C0E007807007003C1E001FFC0007E0018297EA71D> 54
+D<007E0001FF800781C00F00E01E00703C00383C003878003C78003CF8001EF8001EF800
+1EF8001EF8001FF8001FF8001FF8001F78001F78003F78003F3C003F1C005F0E005F0700
+9F03831F00FC1F00001E00001E00001E00003E00003C00003C0000381C00783E00703E00
+E03C01C01803801C0F000FFE0003F80018297EA71D> 57 D<0000FF00100007FFE03000
+1FC07830003E000C7000F80006F001F00003F003E00001F007C00000F00F800000700F80
+0000701F000000303F000000303E000000303E000000107E000000107E000000107C0000
+0000FC00000000FC00000000FC00000000FC00000000FC00000000FC00000000FC000000
+00FC00000000FC0000FFFF7C0000FFFF7E000003F07E000001F03E000001F03E000001F0
+3F000001F01F000001F00F800001F00F800001F007C00001F003E00001F001F00002F000
+F80002F0003E000C70001FC038300007FFE0100000FF8000282B7DA92E> 71
+D<01FFFE01FFFE0007E00003E00003E00003E00003E00003E00003E00003E00003E00003
+E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003
+E00003E00003E00003E00003E00003E00003E00003E03003E07803E0FC03E0FC03E0FC03
+C0F807C0400780200F00300E000C3C0003F000172A7DA81E> 74
+D<0001FF0000000F01E000003C0078000078003C0000E0000E0001E0000F0003C0000780
+07800003C00F800003E01F000001F01F000001F03E000000F83E000000F87E000000FC7E
+000000FC7C0000007C7C0000007CFC0000007EFC0000007EFC0000007EFC0000007EFC00
+00007EFC0000007EFC0000007EFC0000007EFC0000007E7C0000007C7E000000FC7E0000
+00FC7E000000FC3E000000F83F000001F81F000001F01F000001F00F800003E007800003
+C007C00007C003E0000F8000F0001E000078003C00003C007800000F01E0000001FF0000
+272B7DA92E> 79 D<03FC00000C070000100380003C01C0003E01E0003E00F0001C00F0
+000800F0000000F0000000F0000000F000007FF00003E0F0000F80F0001E00F0003C00F0
+007C00F0007800F040F800F040F800F040F800F040F801F0407C01F0403C0278801E0C7F
+8007F01E001A1A7E991D> 97 D<0F000000FF000000FF0000001F0000000F0000000F00
+00000F0000000F0000000F0000000F0000000F0000000F0000000F0000000F0000000F00
+00000F0000000F07E0000F1838000F600E000F8007000F8007800F0003C00F0003C00F00
+01E00F0001E00F0001F00F0001F00F0001F00F0001F00F0001F00F0001F00F0001F00F00
+01E00F0001E00F0003E00F0003C00F0003800F8007800E800F000E401C000C303800080F
+C0001C2A7EA921> I<007F0001C0E00700100E00781E00F83C00F83C00707C0020780000
+F80000F80000F80000F80000F80000F80000F80000F800007800007C00003C00083C0008
+1E00100E002007006001C180007E00151A7E991A> I<00FC000387800701C00E01E01C00
+E03C00F03C00F0780078780078F80078F80078FFFFF8F80000F80000F80000F80000F800
+007800007800003C00083C00081E00100E002007004001C180007E00151A7E991A> 101
+D<00000F0001FC3080070743800E03C3801E03C1003C01E0003C01E0007C01F0007C01F0
+007C01F0007C01F0007C01F0003C01E0003C01E0001E03C0000E0380001707000011FC00
+0030000000300000003000000030000000180000001FFF80000FFFF00007FFF80018007C
+0030001E0070000E0060000700E0000700E0000700E0000700E000070070000E0070000E
+0038001C001C0038000781E00000FF000019287E9A1D> 103 D<1E003F003F003F003F00
+1E000000000000000000000000000000000000000F00FF00FF001F000F000F000F000F00
+0F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F00FFF0FFF0
+0C297EA811> 105 D<007E0003C3C00700E00E00701C00383C003C3C003C78001E78001E
+F8001FF8001FF8001FF8001FF8001FF8001FF8001FF8001F78001E78001E3C003C3C003C
+1C00380E00700700E003C3C0007E00181A7E991D> 111 D<003F010001E0830003804300
+0F0027001E0017001E001F003C000F007C000F007C000F0078000F00F8000F00F8000F00
+F8000F00F8000F00F8000F00F8000F00F8000F007C000F007C000F003C000F003E001F00
+1E001F000F002F0007804F0001C18F00007E0F0000000F0000000F0000000F0000000F00
+00000F0000000F0000000F0000000F0000000F0000000F000000FFF00000FFF01C267E99
+1F> 113 D<0F0F80FF11C0FF23E01F43E00F83E00F81C00F80000F00000F00000F00000F
+00000F00000F00000F00000F00000F00000F00000F00000F00000F00000F00000F00000F
+00000F8000FFFC00FFFC00131A7E9917> I<07F0801C0D80300380600180E00180E00080
+E00080F00080F800007E00007FE0003FFC001FFE0007FF00003F800007808003C08003C0
+8001C0C001C0C001C0E00180E00380F00300CC0E0083F800121A7E9917> I<0080000080
+000080000080000180000180000180000380000380000780000F80001FFF80FFFF800780
+000780000780000780000780000780000780000780000780000780000780000780000780
+0007804007804007804007804007804007804007804003C08001C08000E100003E001225
+7FA417> I<0F000F00FF00FF00FF00FF001F001F000F000F000F000F000F000F000F000F
+000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F
+000F000F000F000F000F000F000F001F000F001F0007002F0003804F8001C08FF0007F0F
+F01C1A7E9921> I E
+%EndDVIPSBitmapFont
+%DVIPSBitmapFont: Fn cmr17 20.74 18
+/Fn 18 119 df<000001FF00008000001FFFE0018000007F007801800001F8000E038000
+03E000070780000FC000018780001F000000CF80003E0000006F80007C0000003F8000F8
+0000003F8001F00000001F8003F00000000F8007E00000000F8007C000000007800FC000
+000007800FC000000007801F8000000003801F8000000003803F8000000003803F000000
+0001803F0000000001807F0000000001807F0000000001807E0000000000007E00000000
+0000FE000000000000FE000000000000FE000000000000FE000000000000FE0000000000
+00FE000000000000FE000000000000FE000000000000FE000000000000FE000000000000
+FE0000000000007E0000000000007E0000000000007F0000000000007F0000000001803F
+0000000001803F0000000001803F8000000001801F8000000001801F8000000003000FC0
+00000003000FC0000000030007E0000000060007E0000000060003F0000000060001F000
+00000C0000F80000001800007C0000001800003E0000003000001F0000006000000FC000
+01C0000003E0000380000001F8000E000000007F007C000000001FFFF00000000001FF00
+0000313D7CBB39> 67 D<FFFFFC000000FFFFFC00000003FE0000000001F80000000001
+F80000000001F80000000001F80000000001F80000000001F80000000001F80000000001
+F80000000001F80000000001F80000000001F80000000001F80000000001F80000000001
+F80000000001F80000000001F80000000001F80000000001F80000000001F80000000001
+F80000000001F80000000001F80000000001F80000000001F80000000001F80000000001
+F80000000001F80000000001F80000000001F80000000001F80000000001F80000000001
+F80000000001F80000000001F80000000001F80000006001F80000006001F80000006001
+F80000006001F80000006001F8000000E001F8000000C001F8000000C001F8000000C001
+F8000000C001F8000001C001F8000001C001F8000001C001F8000003C001F8000007C001
+F8000007C001F800000FC001F800003F8001F80000FF8003FC0007FF80FFFFFFFFFF80FF
+FFFFFFFF802B3B7CBA32> 76 D<000003FF00000000001E01E000000000F0003C000000
+03C0000F000000078000078000000F000003C000003E000001F000007C000000F80000F8
+0000007C0001F00000003E0001F00000003E0003E00000001F0007E00000001F8007C000
+00000F800FC00000000FC00F8000000007C01F8000000007E01F8000000007E03F000000
+0003F03F0000000003F03F0000000003F07F0000000003F87E0000000001F87E00000000
+01F87E0000000001F8FE0000000001FCFE0000000001FCFE0000000001FCFE0000000001
+FCFE0000000001FCFE0000000001FCFE0000000001FCFE0000000001FCFE0000000001FC
+FE0000000001FCFE0000000001FC7E0000000001F87F0000000003F87F0000000003F87F
+0000000003F87F0000000003F83F0000000003F03F8000000007F01F8000000007E01F80
+00000007E01FC00000000FE00FC00000000FC007C00000000F8007E00000001F8003E000
+00001F0001F00000003E0001F80000007E0000F80000007C00007C000000F800003E0000
+01F000000F000003C000000780000780000003E0001F00000000F8007C000000001E01E0
+0000000003FF000000363D7CBB3E> 79 D<003F80000001C0F0000003003C000004001E
+00000C000F000018000780001C0007C0003E0003C0003F0003E0003F0003E0003F0003E0
+001E0003E000000003E000000003E000000003E00000003FE000000FF3E000007E03E000
+01F803E00003E003E0000FC003E0001F8003E0003F0003E0003E0003E0007E0003E0007E
+0003E060FC0003E060FC0003E060FC0003E060FC0007E060FC0007E0607C000BE0607E00
+0BE0603E0011F0C01F0060F0C007C1807F8000FE003E0023257CA427> 97
+D<03E0000000FFE0000000FFE000000007E000000003E000000003E000000003E0000000
+03E000000003E000000003E000000003E000000003E000000003E000000003E000000003
+E000000003E000000003E000000003E000000003E000000003E000000003E000000003E0
+00000003E000000003E03FC00003E0E0780003E3001C0003E6000F0003E800078003F800
+03C003F00001E003E00001F003E00000F003E00000F803E00000F803E00000FC03E00000
+7C03E000007C03E000007E03E000007E03E000007E03E000007E03E000007E03E000007E
+03E000007E03E000007E03E000007E03E000007C03E000007C03E00000FC03E00000F803
+E00000F803E00001F003E00001E003F00003E003D80003C003C80007800384000E000383
+001C000381C0F00003003F8000273C7EBB2C> I<0007F800003C0E0000F0018001E000C0
+03C00060078000300F0000701F0000F81F0001F83E0001F83E0001F87E0000F07C000000
+7C000000FC000000FC000000FC000000FC000000FC000000FC000000FC000000FC000000
+FC0000007C0000007C0000007E0000003E0000003E00000C1F00000C1F0000180F800018
+0780003003C0006001E000C000F00180003C0E000007F8001E257DA423> I<0007F80000
+3C1E0000F0078001C003C003C001E0078000F00F0000F81F0000781E00007C3E00007C3E
+00007C7E00003E7C00003E7C00003EFC00003EFC00003EFFFFFFFEFC000000FC000000FC
+000000FC000000FC000000FC0000007C0000007C0000007E0000003E0000003E0000061F
+0000060F00000C0F80000C0780001803C0003000E00060007000C0001E07000003FC001F
+257EA423> 101 D<0000FC0000078300000E0380001C07C0003C0FC000780FC000F80FC0
+00F8078000F0000001F0000001F0000001F0000001F0000001F0000001F0000001F00000
+01F0000001F0000001F0000001F0000001F0000001F0000001F00000FFFFFC00FFFFFC00
+01F0000001F0000001F0000001F0000001F0000001F0000001F0000001F0000001F00000
+01F0000001F0000001F0000001F0000001F0000001F0000001F0000001F0000001F00000
+01F0000001F0000001F0000001F0000001F0000001F0000001F0000001F0000001F00000
+01F0000001F0000001F0000001F0000001F0000003F800007FFFE0007FFFE0001A3C7FBB
+18> I<07000F801FC01FC01FC00F80070000000000000000000000000000000000000000
+0000000000000007C0FFC0FFC00FC007C007C007C007C007C007C007C007C007C007C007
+C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007
+C007C00FE0FFFEFFFE0F397DB815> 105 D<0003800007C0000FE0000FE0000FE00007C0
+000380000000000000000000000000000000000000000000000000000000000000000000
+0000000000000007E000FFE000FFE0000FE00003E00003E00003E00003E00003E00003E0
+0003E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003E0
+0003E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003E0
+0003E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003E00003E0
+7803C0FC07C0FC0780FC0780FC0F00780E00381C000FE000134A82B818> I<07C0FFC0FF
+C00FC007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007
+C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007
+C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007C007
+C00FE0FFFEFFFE0F3C7DBB15> 108 D<03E01FE0003FC000FFE0607C00C0F800FFE0801E
+01003C0007E3000F06001E0003E4000F88001F0003E4000F88001F0003E8000790000F00
+03E80007D0000F8003F00007E0000F8003F00007E0000F8003E00007C0000F8003E00007
+C0000F8003E00007C0000F8003E00007C0000F8003E00007C0000F8003E00007C0000F80
+03E00007C0000F8003E00007C0000F8003E00007C0000F8003E00007C0000F8003E00007
+C0000F8003E00007C0000F8003E00007C0000F8003E00007C0000F8003E00007C0000F80
+03E00007C0000F8003E00007C0000F8003E00007C0000F8003E00007C0000F8003E00007
+C0000F8003E00007C0000F8003E00007C0000F8003E00007C0000F8003E00007C0000F80
+07F0000FE0001FC0FFFF81FFFF03FFFEFFFF81FFFF03FFFE3F257EA443> I<03E01FE000
+FFE0607C00FFE0801E0007E3000F0003E4000F8003E4000F8003E800078003E80007C003
+F00007C003F00007C003E00007C003E00007C003E00007C003E00007C003E00007C003E0
+0007C003E00007C003E00007C003E00007C003E00007C003E00007C003E00007C003E000
+07C003E00007C003E00007C003E00007C003E00007C003E00007C003E00007C003E00007
+C003E00007C003E00007C003E00007C003E00007C007F0000FE0FFFF81FFFFFFFF81FFFF
+28257EA42C> I<0007FC0000001C070000007001C00001E000F00003C00078000780003C
+000F00001E001F00001F001E00000F003E00000F803E00000F807C000007C07C000007C0
+7C000007C0FC000007E0FC000007E0FC000007E0FC000007E0FC000007E0FC000007E0FC
+000007E0FC000007E0FC000007E07C000007C07C000007C07E00000FC03E00000F803E00
+000F801E00000F001F00001F000F00001E000780003C0003C000780001E000F000007001
+C000001C0700000007FC000023257EA427> I<03E03E00FFE0C300FFE1078007E20FC003
+E40FC003E80FC003E8078003E8030003F0000003F0000003F0000003E0000003E0000003
+E0000003E0000003E0000003E0000003E0000003E0000003E0000003E0000003E0000003
+E0000003E0000003E0000003E0000003E0000003E0000003E0000003E0000003E0000003
+E0000003E0000003E0000007F00000FFFFC000FFFFC0001A257EA41E> 114
+D<00FF02000700C6000C002E0010001E0030001E0060000E0060000E00E0000600E00006
+00E0000600F0000600F8000600FC0000007F0000003FF000003FFF80000FFFE00007FFF0
+0001FFFC00003FFE000001FE0000003F00C0001F00C0000F80C0000780E0000380E00003
+80E0000380E0000380F0000300F0000300F8000700F8000600E4000C00E2001800C18070
+00807F800019257DA41F> I<003000000030000000300000003000000030000000300000
+0070000000700000007000000070000000F0000000F0000001F0000001F0000003F00000
+07F000001FFFFE00FFFFFE0001F0000001F0000001F0000001F0000001F0000001F00000
+01F0000001F0000001F0000001F0000001F0000001F0000001F0000001F0000001F00000
+01F0000001F0000001F0000001F0000001F0018001F0018001F0018001F0018001F00180
+01F0018001F0018001F0018001F0018000F0010000F8030000F8030000780200003C0400
+000E08000003F00019357FB41E> I<FFFE000FFFFFFE000FFF07F00007F803E00003E003
+E00001C001F00001C001F000018001F800018000F800030000F8000300007C000600007C
+000600007E000600003E000C00003E000C00003F001C00001F001800001F001800000F80
+3000000F803000000FC070000007C060000007C060000003E0C0000003E0C0000003F1C0
+000001F180000001F180000000FB00000000FB00000000FF000000007E000000007E0000
+00003C000000003C000000003C0000000018000028257FA42A> 118
+D E
+%EndDVIPSBitmapFont
+end
+%%EndProlog
+%%BeginSetup
+%%Feature: *Resolution 300dpi
+TeXDict begin
+%%PaperSize: a4
+
+userdict/PStoPSxform PStoPSmatrix matrix currentmatrix
+ matrix invertmatrix matrix concatmatrix
+ matrix invertmatrix put
+%%EndSetup
+%%Page: (0,1) 1
+userdict/PStoPSsaved save put
+PStoPSmatrix setmatrix
+595.000000 0.271378 translate
+90 rotate
+0.706651 dup scale
+userdict/PStoPSmatrix matrix currentmatrix put
+userdict/PStoPSclip{0 0 moveto
+ 595.000000 0 rlineto 0 842.000000 rlineto -595.000000 0 rlineto
+ closepath}put initclip
+/showpage{}def/copypage{}def/erasepage{}def
+PStoPSxform concat
+1 0 bop Fn 281 370 a(Cleaner) p 570 370 a(seman) n(tics) p
+927 370 a(for) p 1047 370 a(Ob) t(jectiv) n(e) p 1404
+370 a(Lab) r(el) p Fm 717 518 a(Jacques) p 934 518 a(Garrigue) 719
+634 y(Octob) r(er) p 945 634 a(26,) p 1040 634 a(1999) p
+Fl 11 836 a(Credits) p Fk 11 929 a(This) p 122 929 a(prop) q(osal) p
+319 929 a(con) o(tains) p 510 929 a(ideas) p 632 929
+a(from) p 747 929 a(Damien) p 928 929 a(Doligez) p 1101
+929 a(and) p 1196 929 a(Pierre) p 1340 929 a(W) l(eis.) p
+Fl 11 1073 a(Lab) r(els) p 221 1073 a(and) p 351 1073
+a(optionals) p Fk 11 1165 a(Lab) q(els) p 165 1165 a(and) p
+259 1165 a(optional) p 449 1165 a(argumen) o(ts) p 687
+1165 a(had) p 781 1165 a(t) o(w) o(o) p 873 1165 a(problems) p
+1082 1165 a(in) p 1139 1165 a(Ob) s(jectiv) o(e) p 1360
+1165 a(Lab) q(el.) p Fj 83 1280 a(\017) p Fk 133 1280
+a(They) p 259 1280 a(w) o(ere) p 372 1280 a(not) p 459
+1280 a(fully) p 570 1280 a(coheren) o(t) p 767 1280 a(with) p
+878 1280 a(the) p 963 1280 a(original) p 1139 1280 a(call-b) o(y-v) m
+(alue) p 1423 1280 a(seman) o(tics) p 1644 1280 a(of) p
+1700 1280 a(the) p 1784 1280 a(lan-) 133 1340 y(guage.) p
+303 1340 a(In) p 368 1340 a(some) p 495 1340 a(\(subtle\)) p
+681 1340 a(cases,) p 823 1340 a(a) p 868 1340 a(side-e\013ect) p
+1099 1340 a(migh) o(t) p 1243 1340 a(get) p 1329 1340
+a(dela) o(y) o(ed) p 1508 1340 a(more) p 1635 1340 a(than) p
+1753 1340 a(in) p 1814 1340 a(an) 133 1400 y(un) o(t) o(yp) q(ed) p
+322 1400 a(seman) o(tics.) p Fj 83 1502 a(\017) p Fk
+133 1502 a(F) l(or) p 220 1502 a(optional) p 410 1502
+a(argumen) o(ts,) p 660 1502 a(no) p 728 1502 a(un) o(t) o(yp) q(ed) p
+918 1502 a(seman) o(tics) p 1139 1502 a(existed.) 84
+1616 y(This) p 195 1616 a(new) p 295 1616 a(prop) q(osal) p
+492 1616 a(corrects) p 674 1616 a(these) p 799 1616 a(t) o(w) o(o) p
+891 1616 a(\015a) o(ws.) p Fi 11 1746 a(Syn) n(tax) p
+Fk 11 1838 a(W) l(e) p 95 1838 a(k) o(eep) p 206 1838
+a(Ob) s(jectiv) o(e) p 426 1838 a(Lab) q(el's) p 594
+1838 a(syn) o(tax,) p 764 1838 a(except) p 917 1838 a(for) p
+991 1838 a(default) p 1155 1838 a(v) m(alues) p 1301
+1838 a(in) p 1357 1838 a(optional) p 1547 1838 a(argumen) o(ts.) p
+Fh 329 1944 a(typ) n(expr) p Fk 528 1944 a(::=) p Fg
+634 1944 a(:) p 656 1944 a(:) p 678 1944 a(:) p Fj 579
+2004 a(j) p Fh 634 2004 a(typ) n(expr) p Fj 806 2004
+a(!) p Fh 870 2004 a(typ) n(expr) p Fj 579 2064 a(j) p
+Fk 634 2064 a([?]) p Fi(lab) r(el) p Fk 801 2064 a(:) p
+Fh(typ) n(expr) p Fj 987 2064 a(!) p Fh 1050 2064 a(typ) n(expr) 391
+2124 y(expr) p Fk 528 2124 a(::=) p Fg 634 2124 a(:) p
+656 2124 a(:) p 678 2124 a(:) p Fj 579 2185 a(j) p Fh
+634 2185 a(expr) p 746 2185 a(lab) n(ele) n(d-expr) p
+Ff 991 2163 a(+) p Fj 579 2245 a(j) p Fe 634 2245 a(fun) p
+Fj 728 2245 a(f) p Fh(lab) n(ele) n(d-simple-p) n(attern) p
+Fj 1209 2245 a(g) p Ff 1234 2227 a(+) p Fk 1280 2245
+a([) p Fe(when) p Fh 1412 2245 a(expr) p Fk 1507 2245
+a(]) p Fj 1535 2245 a(!) p Fh 1599 2245 a(expr) p Fj
+579 2305 a(j) p Fe 634 2305 a(function) p Fh 856 2305
+a(lab) n(ele) n(d-p) n(attern) p Fk 1177 2305 a([) p
+Fe(when) p Fh 1309 2305 a(expr) p Fk 1404 2305 a(]) p
+Fj 1432 2305 a(!) p Fh 1496 2305 a(expr) p Fj 785 2365
+a(f) p Fe(|) p Fh 851 2365 a(lab) n(ele) n(d-p) n(attern) p
+Fk 1172 2365 a([) p Fe(when) p Fg 1305 2365 a(expr) p
+Fk 1403 2365 a(]) p Fj 1430 2365 a(!) p Fh 1494 2365
+a(expr) p Fj 1589 2365 a(g) p Fd 1614 2347 a(\003) p
+Fh 242 2425 a(lab) n(ele) n(d-expr) p Fk 528 2425 a(::=) p
+634 2425 a([?]) p Fh(expr) p Fj 579 2486 a(j) p Fk 634
+2486 a([?]) p Fi(lab) r(el) p Fk 801 2486 a(:) p Fh(expr) 182
+2546 y(lab) n(ele) n(d-p) n(attern) p Fk 528 2546 a(::=) p
+Fh 634 2546 a(p) n(attern) p Fj 579 2606 a(j) p Fi 634
+2606 a(lab) r(el) p Fk 751 2606 a(:) p Fh(p) n(attern) p
+Fj 579 2666 a(j) p Fk 634 2666 a(?[) p Fe(\() p Fh(expr) p
+Fe(\)) p Fk(]) p Fi(lab) r(el) p Fk 943 2666 a(:) p Fh
+956 2666 a(p) n(attern) p Fk 926 2937 a(1) p eop
+PStoPSsaved restore
+userdict/PStoPSsaved save put
+PStoPSmatrix setmatrix
+595.000000 421.271378 translate
+90 rotate
+0.706651 dup scale
+userdict/PStoPSmatrix matrix currentmatrix put
+userdict/PStoPSclip{0 0 moveto
+ 595.000000 0 rlineto 0 842.000000 rlineto -595.000000 0 rlineto
+ closepath}put initclip
+PStoPSxform concat
+2 1 bop Fi 11 168 a(Dynamic) p 247 168 a(seman) n(tics) p
+Fj 11 261 a(;) p Fk 52 261 a(is) p 101 261 a(a) p 141
+261 a(notation) p 337 261 a(for) p 411 261 a(the) p 495
+261 a(empt) o(y) p 644 261 a(lab) q(el.) 86 366 y(\() p
+Fe(fun) p Fi 198 366 a(l) p Fc 214 373 a(i) p Fk 227
+366 a(:) p Fg(x) p Fj 282 366 a(!) p Fg 346 366 a(e) p
+Fk(\)) p Fi 404 366 a(l) p Fc 420 373 a(1) p Fk 442 366
+a(:) p Fg 455 366 a(e) p Ff 478 373 a(1) p Fg 506 366
+a(:) p 528 366 a(:) p 550 366 a(:) p Fi 571 366 a(l) p
+Fc 587 373 a(n) p Fk 612 366 a(:) p Fg 625 366 a(e) p
+Fb 648 373 a(n) p Fj 515 427 a(!) p Fk 579 427 a(\() p
+Fg(e) p Fk([) p Fg(e) p Fb 658 434 a(i) p Fg 671 427
+a(=x) p Fk(]) p Fi 752 427 a(l) p Fc 768 434 a(1) p Fk
+790 427 a(:) p Fg(e) p Ff 827 434 a(1) p Fg 855 427 a(:) p
+877 427 a(:) p 899 427 a(:) p Fi 920 427 a(l) p Fc 936
+434 a(i) p Fd(\000) p Fc(1) p Fk 997 427 a(:) p Fg 1010
+427 a(e) p Fb 1033 434 a(i) p Fd(\000) p Ff(1) p Fi 1108
+427 a(l) p Fc 1124 434 a(i) p Ff(+) p Fc(1) p Fk 1185
+427 a(:) p Fg(e) p Fb 1222 434 a(i) p Ff(+1) p Fg 1289
+427 a(:) p 1311 427 a(:) p 1333 427 a(:) p Fi 1354 427
+a(l) p Fc 1370 434 a(n) p Fk 1395 427 a(:) p Fg 1408
+427 a(e) p Fb 1431 434 a(n) p Fk 86 487 a(\() p Fe(fun) p
+Fk 198 487 a(?) p Fi(l) p Fc 237 494 a(i) p Fk 250 487
+a(:) p Fg(x) p Fj 305 487 a(!) p Fg 369 487 a(e) p Fk(\)) p
+Fi 427 487 a(l) p Fc 443 494 a(1) p Fk 465 487 a(:) p
+Fg 478 487 a(e) p Ff 501 494 a(1) p Fg 529 487 a(:) p
+551 487 a(:) p 573 487 a(:) p Fi 594 487 a(l) p Fc 610
+494 a(n) p Fk 635 487 a(:) p Fg 648 487 a(e) p Fb 671
+494 a(n) p Fj 515 547 a(!) p Fg 579 547 a(e) p Fk([) p
+Fe(Some) p Fk 717 547 a(\() p Fg(e) p Fb 759 554 a(i) p
+Fk 773 547 a(\)) p Fg(=x) p Fk(]) p Fi 874 547 a(l) p
+Fc 890 554 a(1) p Fk 912 547 a(:) p Fg 925 547 a(e) p
+Ff 948 554 a(1) p Fg 976 547 a(:) p 998 547 a(:) p 1020
+547 a(:) p Fi 1042 547 a(l) p Fc 1058 554 a(i) p Fd(\000) p
+Fc(1) p Fk 1118 547 a(:) p Fg(e) p Fb 1155 554 a(i) p
+Fd(\000) p Ff(1) p Fi 1230 547 a(l) p Fc 1246 554 a(i) p
+Ff(+) p Fc(1) p Fk 1307 547 a(:) p Fg 1320 547 a(e) p
+Fb 1343 554 a(i) p Ff(+1) p Fg 1410 547 a(:) p 1432 547
+a(:) p 1454 547 a(:) p Fi 1476 547 a(l) p Fc 1492 554
+a(n) p Fk 1516 547 a(:) p Fg(e) p Fb 1553 554 a(n) p
+Fk 86 607 a(\() p Fe(fun) p Fk 198 607 a(?) p Fi(l) p
+Fk(:) p Fg 250 607 a(x) p Fj 292 607 a(!) p Fg 356 607
+a(e) p Fk(\)) p Fi 413 607 a(l) p Fc 429 614 a(1) p Fk
+451 607 a(:) p Fg(e) p Ff 488 614 a(1) p Fg 516 607 a(:) p
+538 607 a(:) p 560 607 a(:) p Fi 581 607 a(l) p Fc 597
+614 a(n) p Fk 621 607 a(:) p Fg(e) p Fb 658 614 a(n) p
+Fk 1154 607 a(when) p Fi 1281 607 a(l) p Fc 1297 614
+a(i) p Fk 1324 607 a(=) p Fj 1376 607 a(;) p Fk 1417
+607 a(and) p Fg 1512 607 a(l) p Fj 1541 607 a(62) p 1588
+607 a(f) p Fi(l) p Fc 1629 614 a(1) p Fg 1660 607 a(:) p
+1682 607 a(:) p 1704 607 a(:) p Fi 1725 607 a(l) p Fc
+1741 614 a(n) p Fj 1765 607 a(g) 515 667 y(!) p Fg 579
+667 a(e) p Fk([) p Fe(None) p Fg 717 667 a(=x) p Fk(]) p
+Fi 799 667 a(l) p Fc 815 674 a(1) p Fk 837 667 a(:) p
+Fg(e) p Ff 874 674 a(1) p Fg 901 667 a(:) p 923 667 a(:) p
+945 667 a(:) p Fi 967 667 a(l) p Fc 983 674 a(n) p Fk
+1007 667 a(:) p Fg(e) p Fb 1044 674 a(n) p Fk 86 728
+a(\(\() p Fe(fun) p Fi 217 728 a(l) p Fk(:) p Fg 246
+728 a(x) p Fj 288 728 a(!) p Fg 352 728 a(e) p Fk(\)) p
+Fi 409 728 a(l) p Fc 425 735 a(1) p Fk 447 728 a(:) p
+Fg(e) p Ff 484 735 a(1) p Fg 511 728 a(:) p 533 728 a(:) p
+555 728 a(:) p Fi 577 728 a(l) p Fc 593 735 a(m) p Fk
+629 728 a(:) p Fg 642 728 a(e) p Fb 665 735 a(m) p Fk
+698 728 a(\)) p Fi 733 728 a(l) p Fc 749 735 a(m) p Ff(+) p
+Fc(1) p Fk 833 728 a(:) p Fg 846 728 a(e) p Fb 869 735
+a(m) p Ff(+1) p Fg 955 728 a(:) p 977 728 a(:) p 999
+728 a(:) p Fi 1021 728 a(l) p Fc 1037 735 a(n) p Fk 1061
+728 a(:) p Fg(e) p Fb 1098 735 a(n) p Fk 1373 728 a(when) p
+Fi 1501 728 a(l) p Fj 1530 728 a(62) p 1577 728 a(f) p
+Fi(l) p Fc 1618 735 a(1) p Fg 1648 728 a(:) p 1670 728
+a(:) p 1692 728 a(:) p Fi 1714 728 a(l) p Fc 1730 735
+a(m) p Fj 1765 728 a(g) 515 788 y(!) p Fk 579 788 a(\() p
+Fe(fun) p Fi 691 788 a(l) p Fk(:) p Fg 720 788 a(x) p
+Fj 761 788 a(!) p Fg 825 788 a(e) p Fk(\)) p Fi 883 788
+a(l) p Fc 899 795 a(1) p Fk 921 788 a(:) p Fg 934 788
+a(e) p Ff 957 795 a(1) p Fg 985 788 a(:) p 1007 788 a(:) p
+1029 788 a(:) p Fi 1051 788 a(l) p Fc 1067 795 a(n) p
+Fk 1091 788 a(:) p Fg 1104 788 a(e) p Fb 1127 795 a(n) p
+Fk 86 848 a(\(\() p Fe(fun) p Fk 217 848 a(?) p Fi(l) p
+Fk(:) p Fg 269 848 a(x) p Fj 311 848 a(!) p Fg 375 848
+a(e) p Fk(\)) p Fi 432 848 a(l) p Fc 448 855 a(1) p Fk
+470 848 a(:) p Fg(e) p Ff 507 855 a(1) p Fg 535 848 a(:) p
+557 848 a(:) p 579 848 a(:) p Fi 600 848 a(l) p Fc 616
+855 a(m) p Fk 652 848 a(:) p Fg 665 848 a(e) p Fb 688
+855 a(m) p Fk 721 848 a(\)) p Fi 756 848 a(l) p Fc 772
+855 a(m) p Ff(+) p Fc(1) p Fk 856 848 a(:) p Fg 869 848
+a(e) p Fb 892 855 a(m) p Ff(+1) p Fg 978 848 a(:) p 1000
+848 a(:) p 1022 848 a(:) p Fi 1044 848 a(l) p Fc 1060
+855 a(n) p Fk 1084 848 a(:) p Fg(e) p Fb 1121 855 a(n) p
+Fk 1261 848 a(when) p Fj 1388 848 a(f) p Fi(l) p Fg(;) p
+Fj 1451 848 a(;g) p 1530 848 a(6) m(\\) p 1577 848 a(f) p
+Fi(l) p Fc 1618 855 a(1) p Fg 1648 848 a(:) p 1670 848
+a(:) p 1692 848 a(:) p Fi 1714 848 a(l) p Fc 1730 855
+a(m) p Fj 1765 848 a(g) 515 908 y(!) p Fk 579 908 a(\() p
+Fe(fun) p Fk 691 908 a(?) p Fi(l) p Fk(:) p Fg 743 908
+a(x) p Fj 785 908 a(!) p Fg 848 908 a(e) p Fk(\)) p Fi
+906 908 a(l) p Fc 922 915 a(1) p Fk 944 908 a(:) p Fg(e) p
+Ff 981 915 a(1) p Fg 1008 908 a(:) p 1030 908 a(:) p
+1052 908 a(:) p Fi 1074 908 a(l) p Fc 1090 915 a(n) p
+Fk 1114 908 a(:) p Fg 1127 908 a(e) p Fb 1150 915 a(n) p
+Fi 11 1035 a(T) n(yping) p Fk 11 1127 a(Seman) o(tics) p
+240 1127 a(are) p 321 1127 a(k) o(ept) p 430 1127 a(throughout) p
+685 1127 a(compilation) p 950 1127 a(b) o(y) p 1018 1127
+a(disallo) o(wing) p 1269 1127 a(lab) q(el) p 1387 1127
+a(comm) o(utation) p 1684 1127 a(for) p 1759 1127 a(func-) 11
+1187 y(tion) p 116 1187 a(t) o(yp) q(es.) p 278 1187
+a(Ho) o(w) o(ev) o(er,) p 494 1187 a(the) p 583 1187
+a(original) p 764 1187 a(comfort) p 949 1187 a(of) p
+1009 1187 a(out-of-order) p 1283 1187 a(application) p
+1540 1187 a(is) p 1594 1187 a(reco) o(v) o(ered) p 1814
+1187 a(b) o(y) 11 1247 y(allo) o(wing) p 207 1247 a(argumen) o(t) p
+431 1247 a(reordering) p 670 1247 a(in) p 732 1247 a(application,) p
+1005 1247 a(when) p 1138 1247 a(the) p 1227 1247 a(function's) p
+1457 1247 a(t) o(yp) q(e) p 1572 1247 a(is) p Fh 1626
+1247 a(wel) r(l) p 1731 1247 a(known) p Fk 11 1308 a(\() p
+Fh(c.f.) p Fk 118 1308 a(p) q(olymorphic) p 400 1308
+a(metho) q(ds\).) p Fl 11 1452 a(V) p 56 1452 a(arian) n(ts) p
+Fk 11 1544 a(V) l(arian) o(t) p 187 1544 a(t) o(yping,) p
+355 1544 a(as) p 417 1544 a(it) p 468 1544 a(is) p 519
+1544 a(presen) o(ted) p 739 1544 a(in) p 798 1544 a(the) p
+884 1544 a(user's) p 1022 1544 a(man) o(ual,) p 1210
+1544 a(is) p 1261 1544 a(not) p 1350 1544 a(principal:) p
+1576 1544 a(in) p 1635 1544 a(some) p 1760 1544 a(cases) 11
+1605 y(t) o(ypabilit) o(y) p 239 1605 a(of) p 301 1605
+a(an) p 375 1605 a(expression) p 616 1605 a(ma) o(y) p
+728 1605 a(dep) q(end) p 904 1605 a(on) p 978 1605 a(the) p
+1069 1605 a(order) p 1202 1605 a(in) p 1265 1605 a(whic) o(h) p
+1411 1605 a(the) p 1502 1605 a(t) o(yping) p 1660 1605
+a(algorithm) 11 1665 y(pro) q(ceeds.) p Fe 133 1779 a(#) p
+184 1779 a(let) p 286 1779 a(f1) p 363 1779 a(\(x) p
+440 1779 a(:) p 491 1779 a([<) p 568 1779 a(a) p 620
+1779 a(b\(int\)]\)) p 850 1779 a(=) p 902 1779 a(\(\)) 184
+1839 y(let) p 286 1839 a(f2) p 363 1839 a(\(x) p 440
+1839 a(:) p 491 1839 a([<) p 568 1839 a(a]\)) p 671 1839
+a(=) p 722 1839 a(\(\)) 184 1899 y(let) p 286 1899 a(f3) p
+363 1899 a(\(x) p 440 1899 a(:) p 491 1899 a([<) p 568
+1899 a(a) p 620 1899 a(b\(bool\)]\)) p 876 1899 a(=) p
+927 1899 a(\(\);;) 133 1960 y(val) p 235 1960 a(f1) p
+312 1960 a(:) p 363 1960 a([<) p 440 1960 a(a) p 491
+1960 a(b\(int\)]) p 696 1960 a(->) p 773 1960 a(unit) p
+902 1960 a(=) p 953 1960 a(<fun>) 133 2020 y(val) p 235
+2020 a(f2) p 312 2020 a(:) p 363 2020 a([<) p 440 2020
+a(a]) p 517 2020 a(->) p 594 2020 a(unit) p 722 2020
+a(=) p 773 2020 a(<fun>) 133 2080 y(val) p 235 2080 a(f3) p
+312 2080 a(:) p 363 2080 a([<) p 440 2080 a(a) p 491
+2080 a(b\(bool\)]) p 722 2080 a(->) p 799 2080 a(unit) p
+927 2080 a(=) p 978 2080 a(<fun>) 133 2140 y(#) p 184
+2140 a(fun) p 286 2140 a(x) p 338 2140 a(->) p 414 2140
+a(f1) p 491 2140 a(x;) p 568 2140 a(f2) p 645 2140 a(x;) p
+722 2140 a(f3) p 799 2140 a(x;;) 133 2200 y(-) p 184
+2200 a(:) p 235 2200 a([<) p 312 2200 a(a]) p 389 2200
+a(->) p 466 2200 a(unit) p 594 2200 a(=) p 645 2200 a(<fun>) 133
+2260 y(#) p 184 2260 a(fun) p 286 2260 a(x) p 338 2260
+a(->) p 414 2260 a(f1) p 491 2260 a(x;) p 568 2260 a(f3) p
+645 2260 a(x;;) 133 2321 y(Character) o(s) p 414 2321
+a(18-19:) 133 2381 y(This) p 261 2381 a(expressio) o(n) p
+543 2381 a(has) p 645 2381 a(type) p 773 2381 a([<) p
+850 2381 a(a) p 902 2381 a(b\(int\)]) p 1107 2381 a(but) p
+1209 2381 a(is) p 1286 2381 a(here) p 1414 2381 a(used) p
+1542 2381 a(with) p 1670 2381 a(type) 184 2441 y([<) p
+261 2441 a(a) p 312 2441 a(b\(bool\)]) p Fk 84 2555 a(Here) p
+204 2555 a(the) p 292 2555 a(constrain) o(t) p 526 2555
+a(in) o(tro) q(duced) p 775 2555 a(b) o(y) p Fe 848 2555
+a(f2) p Fk 920 2555 a(hides) p 1049 2555 a(the) p 1138
+2555 a(constructor) p Fe 1401 2555 a(b) p Fk(,) p 1462
+2555 a(and) p 1562 2555 a(a) o(v) o(oids) p 1714 2555
+a(a) p 1760 2555 a(clash) 11 2615 y(b) q(et) o(w) o(een) p
+Fe 199 2615 a(int) p Fk 292 2615 a(and) p Fe 387 2615
+a(bool) p Fk(.) 84 2676 y(An) p 163 2676 a(easy) p 270
+2676 a(w) o(a) o(y) p 369 2676 a(to) p 428 2676 a(solv) o(e) p
+547 2676 a(this) p 642 2676 a(w) o(ould) p 784 2676 a(b) q(e) p
+850 2676 a(to) p 909 2676 a(restrict) p 1077 2676 a(hiding) p
+1226 2676 a(absen) o(t) p 1379 2676 a(lab) q(els) p 1515
+2676 a(to) p 1575 2676 a(generic) p 1739 2676 a(t) o(yp) q(es.) 11
+2736 y(This) p 124 2736 a(w) o(a) o(y) p 224 2736 a(the) p
+310 2736 a(second) p 469 2736 a(case) p 574 2736 a(w) o(ould) p
+718 2736 a(still) p 814 2736 a(fail,) p 913 2736 a(since) p
+Fe 1034 2736 a(x) p Fk 1077 2736 a(has) p 1166 2736 a(a) p
+1208 2736 a(monorphic) p 1451 2736 a(t) o(yp) q(e.) p
+1584 2736 a(This) p 1697 2736 a(solution) 11 2796 y(w) o(ould) p
+153 2796 a(b) q(e) p 219 2796 a(correct) p 382 2796 a(and) p
+477 2796 a(principal.) 926 2937 y(2) p eop
+PStoPSsaved restore
+%%Page: (2,3) 2
+userdict/PStoPSsaved save put
+PStoPSmatrix setmatrix
+595.000000 0.271378 translate
+90 rotate
+0.706651 dup scale
+userdict/PStoPSmatrix matrix currentmatrix put
+userdict/PStoPSclip{0 0 moveto
+ 595.000000 0 rlineto 0 842.000000 rlineto -595.000000 0 rlineto
+ closepath}put initclip
+/showpage{}def/copypage{}def/erasepage{}def
+PStoPSxform concat
+3 2 bop Fk 84 168 a(Ho) o(w) o(ev) o(er,) p 293 168 a(one) p
+382 168 a(can) p 472 168 a(easily) p 606 168 a(see) p
+684 168 a(that) p 789 168 a(this) p 884 168 a(solution) p
+1068 168 a(is) p 1117 168 a(coun) o(ter-in) o(tuitiv) o(e.) p
+1504 168 a(F) l(or) p 1591 168 a(the) p 1675 168 a(user,) p
+Fe 1791 168 a(b) p Fk 1833 168 a(is) 11 229 y(already) p
+183 229 a(an) p 250 229 a(imp) q(ossible) p 488 229 a(constructor,) p
+759 229 a(and) p 854 229 a(ha) o(ving) p 1011 229 a(a) p
+1052 229 a(clash) p 1174 229 a(on) p 1242 229 a(it) p
+1291 229 a(is) p 1340 229 a(hard) p 1453 229 a(to) p
+1513 229 a(understand.) 84 289 y(Another) p 277 289 a(solution) p
+463 289 a(is) p 514 289 a(to) p 575 289 a(go) p 642 289
+a(the) p 728 289 a(opp) q(osite) p 924 289 a(w) o(a) o(y) l(.) p
+1044 289 a(T) l(o) p 1117 289 a(accept) p 1271 289 a(more) p
+1395 289 a(programs.) p 1634 289 a(This) p 1747 289 a(is) p
+1798 289 a(the) 11 349 y(w) o(a) o(y) p 109 349 a(w) o(e) p
+181 349 a(explore) p 351 349 a(here,) p 470 349 a(with) p
+581 349 a(an) p 649 349 a(unc) o(hanged) p 891 349 a(syn) o(tax.) p
+Fi 11 479 a(T) n(yping) p Fk 11 571 a(The) p 114 571
+a(idea) p 220 571 a(is) p 273 571 a(to) p 336 571 a(dela) o(y) p
+466 571 a(uni\014cation) p 711 571 a(on) p 782 571 a(constructor) p
+1043 571 a(un) o(til) p 1161 571 a(they) p 1274 571 a(are) p
+1359 571 a(explicitely) p 1595 571 a(kno) o(wn) p 1753
+571 a(to) p 1816 571 a(b) q(e) 11 631 y(presen) o(t.) p
+199 631 a(W) l(e) p 280 631 a(k) o(eep) p 390 631 a(the) p
+472 631 a(\() p Fg(T) t(;) p 546 631 a(U;) p 601 631
+a(L) p Fk(\)) p 666 631 a(represen) o(tation) p 983 631
+a(of) p 1036 631 a(v) m(arian) o(t) p 1200 631 a(t) o(yp) q(es,) p
+1341 631 a(but) p Fg 1428 631 a(T) p Fk 1478 631 a(is) p
+1525 631 a(no) p 1591 631 a(longer) p 1735 631 a(a) p
+1774 631 a(map) 11 692 y(from) p 126 692 a(constructors) p
+403 692 a(to) p 462 692 a(t) o(yp) q(es,) p 605 692 a(but) p
+694 692 a(from) p 809 692 a(constructors) p 1086 692
+a(to) p 1146 692 a(sets) p 1241 692 a(of) p 1297 692
+a(t) o(yp) q(es.) 84 752 y(When) p 230 752 a(w) o(e) p
+307 752 a(unify) p 436 752 a(t) o(w) o(o) p 532 752 a(v) m(arian) o(t) p
+702 752 a(t) o(yp) q(es,) p 850 752 a(the) p 938 752
+a(\014rst) p 1043 752 a(step) p 1150 752 a(is) p 1204
+752 a(just) p 1305 752 a(to) p 1369 752 a(tak) o(e) p
+1479 752 a(the) p 1567 752 a(union) p 1707 752 a(of) p
+1767 752 a(b) q(oth) 11 812 y(t) o(yping) p 162 812 a(en) o(vironmen) o
+(ts,) p 476 812 a(dropping) p 682 812 a(unnecessary) p
+952 812 a(t) o(yp) q(es.) 204 932 y(\() p Fg(T) p Ff
+252 939 a(1) p Fg 272 932 a(;) p 294 932 a(U) p Ff 327
+939 a(1) p Fg 346 932 a(;) p 368 932 a(L) p Ff 401 939
+a(1) p Fk 421 932 a(\)) p Fj 451 932 a(^) p Fk 495 932
+a(\() p Fg(T) p Ff 543 939 a(2) p Fg 563 932 a(;) p 585
+932 a(U) p Ff 618 939 a(2) p Fg 637 932 a(;) p 659 932
+a(L) p Ff 692 939 a(2) p Fk 712 932 a(\)) p 745 932 a(=) p
+797 932 a(\(\() p Fg(T) p Ff 864 939 a(1) p Fj 883 932
+a(j) p Fb 897 939 a(U) p Fa 921 944 a(1) p Fd 938 939
+a(\\) p Fb(U) p Fa 986 944 a(2) p Fk 1005 932 a(\)) p
+Fj 1035 932 a([) p Fk 1079 932 a(\() p Fg(T) p Ff 1127
+939 a(2) p Fj 1146 932 a(j) p Fb 1160 939 a(U) p Fa 1184
+944 a(1) p Fd 1201 939 a(\\) p Fb(U) p Fa 1249 944 a(2) p
+Fk 1268 932 a(\)) p Fg(;) p 1309 932 a(U) p Ff 1342 939
+a(1) p Fj 1373 932 a(\\) p Fg 1417 932 a(U) p Ff 1450
+939 a(2) p Fg 1470 932 a(;) p 1492 932 a(L) p Ff 1525
+939 a(1) p Fj 1556 932 a([) p Fg 1600 932 a(L) p Ff 1633
+939 a(2) p Fk 1653 932 a(\)) 84 1042 y(Here) p 203 1042
+a(the) p 291 1042 a(union) p 431 1042 a(of) p 490 1042
+a(t) o(w) o(o) p 587 1042 a(t) o(yping) p 742 1042 a(en) o(vironmen) o
+(ts) p 1046 1042 a(is) p 1099 1042 a(the) p 1187 1042
+a(p) q(oin) o(t) o(wise) p 1407 1042 a(union) p 1547
+1042 a(of) p 1606 1042 a(their) p 1727 1042 a(sets) p
+1826 1042 a(of) 11 1102 y(t) o(yp) q(es) p 140 1102 a(for) p
+214 1102 a(eac) o(h) p 324 1102 a(constructor.) 84 1162
+y(This) p 195 1162 a(\014rst) p 296 1162 a(step) p 399
+1162 a(nev) o(er) p 529 1162 a(fails.) 84 1222 y(In) p
+145 1222 a(a) p 186 1222 a(second) p 343 1222 a(step,) p
+460 1222 a(structural) p 685 1222 a(constrain) o(ts) p
+934 1222 a(are) p 1015 1222 a(enforced) p 1209 1222 a(on) p
+1277 1222 a(the) p 1361 1222 a(resulting) p 1562 1222
+a(t) o(yp) q(e) p 1672 1222 a(\() p Fg(T) t(;) p 1746
+1222 a(U;) p 1801 1222 a(L) p Fk(\).) 11 1282 y(First,) p
+Fg 144 1282 a(L) p Fk 195 1282 a(should) p 351 1282 a(b) q(e) p
+418 1282 a(included) p 614 1282 a(in) p Fg 672 1282 a(U) p
+Fk 710 1282 a(.) p 749 1282 a(Then,) p 892 1282 a(for) p
+967 1282 a(all) p 1036 1282 a(constructors) p 1314 1282
+a(app) q(earing) p 1542 1282 a(in) p Fg 1600 1282 a(L) p
+Fk(,) p 1664 1282 a(the) p 1749 1282 a(set) p 1826 1282
+a(of) 11 1343 y(t) o(yp) q(es) p 136 1343 a(asso) q(ciated) p
+365 1343 a(with) p 472 1343 a(eac) o(h) p 578 1343 a(constructor) p
+833 1343 a(is) p 878 1343 a(collapsed) p 1084 1343 a(b) o(y) p
+1148 1343 a(uni\014cation.) p 1407 1343 a(This) p 1515
+1343 a(can) p 1600 1343 a(b) q(e) p 1663 1343 a(expressed) 11
+1403 y(b) o(y) p 78 1403 a(rewriting) p 287 1403 a(rules,) p
+417 1403 a(where) p Fg 558 1403 a(e) p Fk 597 1403 a(is) p
+646 1403 a(a) p 687 1403 a(m) o(ulti-equation) p 1015
+1403 a(and) p Fg 1109 1403 a(\036) p Fk 1155 1403 a(a) p
+1195 1403 a(set) p 1271 1403 a(of) p 1327 1403 a(m) o(ultiequations) 249
+1509 y(if) p Fg 294 1509 a(L) p Fj 341 1509 a(6\032) p
+Fg 393 1509 a(U) p Fk 448 1509 a(then) p 559 1509 a(\() p
+Fg(T) t(;) p 633 1509 a(U;) p 688 1509 a(L) p Fk(\)) p
+753 1509 a(=) p Fg 805 1509 a(e) p Fj 839 1509 a(^) p
+Fg 883 1509 a(\036) p Fj 926 1509 a(\000) p 956 1509
+a(!) p 1020 1509 a(?) p Fk 249 1629 a(if) p Fg 294 1629
+a(l) p Fj 323 1629 a(2) p Fg 370 1629 a(L) p Fk 420 1629
+a(and) p Fg 515 1629 a(T) p Fk 551 1629 a(\() p Fg(l) p
+Fk 586 1629 a(\)) p 617 1629 a(=) p Fj 669 1629 a(f) p
+Fg(\034) p Ff 715 1636 a(1) p Fg 735 1629 a(;) p 757
+1629 a(:) p 779 1629 a(:) p 801 1629 a(:) p 822 1629
+a(;) p 844 1629 a(\034) p Fb 865 1636 a(n) p Fj 889 1629
+a(g) p Fk 930 1629 a(then) 298 1689 y(\() p Fg(T) t(;) p
+372 1689 a(U;) p 427 1689 a(L) p Fk(\)) p 492 1689 a(=) p
+Fg 544 1689 a(e) p Fj 577 1689 a(^) p Fg 622 1689 a(\036) p
+Fj 664 1689 a(\000) p 695 1689 a(!) p Fk 759 1689 a(\() p
+Fg(T) p Fj 814 1689 a(f) p Fg(l) p Fj 867 1689 a(7!) p
+Fg 931 1689 a(\034) p Ff 952 1696 a(1) p Fj 972 1689
+a(g) p Fg(;) p 1019 1689 a(U;) p 1074 1689 a(L) p Fk(\)) p
+1139 1689 a(=) p Fg 1191 1689 a(e) p Fj 1225 1689 a(^) p
+Fg 1269 1689 a(\034) p Ff 1290 1696 a(1) p Fk 1324 1689
+a(=) p Fg 1376 1689 a(:) p 1398 1689 a(:) p 1420 1689
+a(:) p Fk 1447 1689 a(=) p Fg 1498 1689 a(\034) p Fb
+1519 1696 a(n) p Fj 1554 1689 a(^) p Fg 1598 1689 a(\036) p
+Fk 84 1796 a(Optionally) p 331 1796 a(one) p 425 1796
+a(can) p 519 1796 a(add) p 619 1796 a(rules) p 740 1796
+a(that) p 850 1796 a(remo) o(v) o(e) p 1022 1796 a(a) p
+1067 1796 a(constructor) p Fg 1329 1796 a(l) p Fk 1366
+1796 a(from) p Fg 1486 1796 a(U) p Fk 1545 1796 a(if) p
+1594 1796 a(the) p 1683 1796 a(equation) 11 1856 y(obtained) p
+211 1856 a(from) p Fg 326 1856 a(T) p Fk 362 1856 a(\() p
+Fg(l) p Fk 397 1856 a(\)) p 431 1856 a(has) p 518 1856
+a(no) p 586 1856 a(solution.) p 790 1856 a(Suc) o(h) p
+908 1856 a(rules) p 1024 1856 a(w) o(ould) p 1167 1856
+a(b) q(e) p 1233 1856 a(sound) p 1374 1856 a(and) p 1469
+1856 a(complete.) p Fi 11 1986 a(Syn) n(tax) p 198 1986
+a(of) p 262 1986 a(t) n(yp) r(es) p Fk 11 2078 a(Thanks) p
+188 2078 a(to) p 250 2078 a(the) p 336 2078 a(go) q(o) q(d) p
+458 2078 a(prop) q(erties) p 689 2078 a(of) p 747 2078
+a(these) p 874 2078 a(constrain) o(ts,) p 1139 2078 a(the) p
+1226 2078 a(surface) p 1392 2078 a(syn) o(tax) p 1551
+2078 a(of) p 1608 2078 a(t) o(yp) q(es) p 1740 2078 a(w) o(ould) 11
+2138 y(only) p 118 2138 a(ha) o(v) o(e) p 230 2138 a(to) p
+290 2138 a(b) q(e) p 356 2138 a(sligh) o(tly) p 527 2138
+a(extended.) p Fh 590 2244 a(tag-typ) n(e) p Fk 798 2244
+a(::=) p Fh 904 2244 a(ident) p Fj 849 2304 a(j) p Fh
+904 2304 a(ident) p Fe 1031 2304 a(\() p Fh(typ) n(expr-list) p
+Fe(\)) p Fh 523 2365 a(typ) n(expr-list) p Fk 798 2365
+a(::=) p Fh 904 2365 a(typ) n(expr) p Fj 849 2425 a(j) p
+Fh 904 2425 a(typ) n(expr) p Fe 1078 2425 a(&) p Fh 1120
+2425 a(typ) n(expr-list) p Fk 84 2531 a(Notice) p 234
+2531 a(that) p 336 2531 a(a) p 373 2531 a(0-ary) p 496
+2531 a(constructor) p 751 2531 a(and) p 842 2531 a(an) p
+907 2531 a(1-ary) p 1030 2531 a(construtor) p 1262 2531
+a(are) p 1340 2531 a(con) o(tradictory) l(,) p 1648 2531
+a(and) p 1740 2531 a(w) o(ould) 11 2592 y(result) p 146
+2592 a(in) p 203 2592 a(the) p 287 2592 a(absence) p
+466 2592 a(of) p 522 2592 a(this) p 617 2592 a(constructor.) 926
+2937 y(3) p eop
+PStoPSsaved restore
+userdict/PStoPSsaved save put
+PStoPSmatrix setmatrix
+595.000000 421.271378 translate
+90 rotate
+0.706651 dup scale
+userdict/PStoPSmatrix matrix currentmatrix put
+userdict/PStoPSclip{0 0 moveto
+ 595.000000 0 rlineto 0 842.000000 rlineto -595.000000 0 rlineto
+ closepath}put initclip
+PStoPSxform concat
+4 3 bop Fi 11 168 a(Discussion) p Fk 11 261 a(Suc) o(h) p
+133 261 a(a) p 179 261 a(c) o(hange) p 345 261 a(has) p
+436 261 a(the) p 525 261 a(ma) s(jor) p 672 261 a(adv) m(an) o(tage) p
+907 261 a(of) p 967 261 a(b) q(oth) p 1087 261 a(reco) o(v) o(ering) p
+1324 261 a(principalit) o(y) p 1589 261 a(and) p 1688
+261 a(a) o(v) o(oiding) 11 321 y(unin) o(tuitiv) o(e) p
+266 321 a(error) p 392 321 a(messages.) p 640 321 a(Constrain) o(ts) p
+909 321 a(created) p 1087 321 a(in) p 1152 321 a(suc) o(h) p
+1269 321 a(a) p 1317 321 a(w) o(a) o(y) p 1423 321 a(are) p
+1512 321 a(v) o(ery) p 1626 321 a(ligh) o(t:) p 1772
+321 a(they) 11 381 y(alw) o(a) o(ys) p 165 381 a(app) q(ear) p
+325 381 a(inside) p 463 381 a(a) p 502 381 a(v) m(arian) o(t) p
+666 381 a(t) o(yp) q(e,) p 788 381 a(and) p 882 381 a(if) p
+926 381 a(the) p 1008 381 a(v) m(arian) o(t) p 1172 381
+a(t) o(yp) q(e) p 1281 381 a(do) q(es) p 1390 381 a(not) p
+1475 381 a(app) q(ear) p 1635 381 a(in) p 1691 381 a(the) p
+1774 381 a(\014nal) 11 441 y(t) o(yp) q(e) p 120 441
+a(sc) o(heme,) p 301 441 a(then) p 412 441 a(the) p 496
+441 a(constrain) o(t) p 725 441 a(can) p 815 441 a(b) q(e) p
+881 441 a(discarded) p 1098 441 a(safely) l(.) 84 501
+y(On) p 165 501 a(the) p 249 501 a(other) p 376 501 a(hand,) p
+512 501 a(there) p 637 501 a(are) p 718 501 a(t) o(w) o(o) p
+810 501 a(dra) o(wbac) o(ks.) p Fj 83 616 a(\017) p Fk
+133 616 a(Some) p 259 616 a(errors) p 393 616 a(will) p
+482 616 a(b) q(e) p 544 616 a(dela) o(y) o(ed) p 715
+616 a(longer) p 858 616 a(than) p 968 616 a(no) o(w,) p
+1080 616 a(un) o(til) p 1191 616 a(a) p 1228 616 a(construtor) p
+1460 616 a(is) p 1505 616 a(actually) p 1687 616 a(included) 133
+676 y(in) p Fg 189 676 a(L) p Fk(.) p 258 676 a(It) p
+311 676 a(is) p 360 676 a(not) p 446 676 a(clear) p 563
+676 a(ho) o(w) p 665 676 a(damageable) p 930 676 a(it) p
+979 676 a(is.) p Fj 83 777 a(\017) p Fk 133 777 a(While) p
+272 777 a(t) o(yp) q(e) p 378 777 a(inference) p 579
+777 a(is) p 625 777 a(simple) p 774 777 a(and) p 865
+777 a(costless) p 1036 777 a(for) p 1108 777 a(this) p
+1200 777 a(extension,) p 1426 777 a(simpli\014cation) p
+1724 777 a(of) p 1776 777 a(con-) 133 838 y(strain) o(ts) p
+310 838 a(|marking) p 551 838 a(constructors) p 830 838
+a(with) p 943 838 a(unsolv) m(able) p 1182 838 a(constrain) o(ts) p
+1432 838 a(as) p 1494 838 a(absen) o(t,) p 1663 838 a(and) p
+1760 838 a(elim-) 133 898 y(inating) p 300 898 a(redundan) o(t) p
+536 898 a(t) o(yp) q(es) p 667 898 a(in) p 726 898 a(constrain) o(ts|) p
+1025 898 a(is) p 1076 898 a(a) p 1119 898 a(bit) p 1197
+898 a(more) p 1320 898 a(exp) q(ensiv) o(e.) p 1565 898
+a(Also,) p 1691 898 a(allo) o(wing) 133 958 y(suc) o(h) p
+244 958 a(constrained) p 506 958 a(t) o(yp) q(es) p 637
+958 a(inside) p 777 958 a(signatures) p 1010 958 a(w) o(ould) p
+1154 958 a(mean) p 1286 958 a(ha) o(ving) p 1444 958
+a(to) p 1506 958 a(solv) o(e) p 1627 958 a(a) p 1669
+958 a(matc) o(hing) 133 1018 y(problem,) p 333 1018 a(whic) o(h) p
+469 1018 a(is) p 514 1018 a(exp) q(onen) o(tial) p 772
+1018 a(in) p 825 1018 a(the) p 906 1018 a(n) o(um) o(b) q(er) p
+1080 1018 a(of) p 1132 1018 a(connected) p 1356 1018
+a(constrain) o(ts) p 1600 1018 a(inside) p 1735 1018
+a(a) p 1772 1018 a(t) o(yp) q(e) 133 1078 y(sc) o(heme.) 84
+1193 y(Reasonably) p 340 1193 a(e\016cien) o(t) p 516
+1193 a(algorithms) p 754 1193 a(exist) p 866 1193 a(to) p
+922 1193 a(solv) o(e) p 1038 1193 a(these) p 1159 1193
+a(problems,) p 1379 1193 a(so) p 1435 1193 a(the) p 1515
+1193 a(di\016cult) o(y) p 1715 1193 a(is) p 1760 1193
+a(more) 11 1253 y(in) p 67 1253 a(the) p 151 1253 a(increased) p
+363 1253 a(complexit) o(y) p 611 1253 a(of) p 667 1253
+a(the) p 751 1253 a(t) o(yp) q(e-c) o(hec) o(k) o(er) p
+1031 1253 a(than) p 1145 1253 a(in) p 1202 1253 a(run-time) p
+1402 1253 a(cost.) p Fl 11 1397 a(Other) p 205 1397 a(features) p
+Fk 11 1490 a(Ob) s(jectiv) o(e) p 238 1490 a(Lab) q(el) p
+380 1490 a(con) o(tains) p 579 1490 a(t) o(w) o(o) p
+678 1490 a(other) p 812 1490 a(features:) p 1029 1490
+a(p) q(olymorphic) p 1318 1490 a(metho) q(ds) p 1521
+1490 a(and) p 1623 1490 a(t) o(yp) q(e-driv) o(en) 11
+1550 y(access) p 153 1550 a(of) p 208 1550 a(records.) p
+394 1550 a(Both) p 514 1550 a(of) p 568 1550 a(them) p
+692 1550 a(use) p 775 1550 a(the) p 857 1550 a(same) p
+978 1550 a(metho) q(d) p 1154 1550 a(of) p 1209 1550
+a(enforcing) p 1417 1550 a(principalit) o(y) p 1676 1550
+a(of) p 1730 1550 a(t) o(yping) 11 1610 y(through) p
+191 1610 a(tracing) p 351 1610 a(user) p 450 1610 a(pro) o(vided) p
+647 1610 a(t) o(yp) q(e) p 752 1610 a(information.) p
+1034 1610 a(With) p 1155 1610 a(this) p 1246 1610 a(tracing,) p
+1422 1610 a(their) p 1534 1610 a(implem) o(en) n(tation) 11
+1670 y(is) p 60 1670 a(v) o(ery) p 167 1670 a(easy) l(,) p
+283 1670 a(but) p 373 1670 a(without) p 554 1670 a(it) p
+603 1670 a(they) p 713 1670 a(lo) q(ose) p 834 1670 a(principalit) o(y)
+l(.) 84 1730 y(While) p 229 1730 a(these) p 357 1730
+a(features) p 543 1730 a(pro) o(vide) p 720 1730 a(some) p
+845 1730 a(comfort) p 1029 1730 a(in) p 1089 1730 a(writing) p
+1260 1730 a(user) p 1366 1730 a(programs,) p 1598 1730
+a(they) p 1711 1730 a(are) p 1795 1730 a(not) 11 1791
+y(strictly) p 182 1791 a(necessary) p 403 1791 a(for) p
+482 1791 a(the) p 571 1791 a(v) m(arious) p 742 1791
+a(libraries) p 934 1791 a(coming) p 1107 1791 a(with) p
+1223 1791 a(O'Labl) p 1391 1791 a(\(LablTk,) p 1602 1791
+a(LablGL) p 1787 1791 a(and) 11 1851 y(LablGTK\).) 926
+2937 y(4) p eop
+PStoPSsaved restore
+%%Trailer
+end
+userdict /end-hook known{end-hook}if
+%%EOF
diff --git a/experimental/garrigue/nongeneral-let.diff b/experimental/garrigue/nongeneral-let.diff
new file mode 100644
index 0000000000..bcdc69e845
--- /dev/null
+++ b/experimental/garrigue/nongeneral-let.diff
@@ -0,0 +1,428 @@
+Index: camlp4/Camlp4/Struct/Grammar/Delete.ml
+===================================================================
+--- camlp4/Camlp4/Struct/Grammar/Delete.ml (revision 14037)
++++ camlp4/Camlp4/Struct/Grammar/Delete.ml (working copy)
+@@ -35,17 +35,17 @@
+ open Structure;
+
+ value raise_rule_not_found entry symbols =
+- let to_string f x =
++ let to_string : !'a. (_ -> 'a -> _) -> 'a -> _ = fun [f -> fun [x ->
+ let buff = Buffer.create 128 in
+ let ppf = Format.formatter_of_buffer buff in
+ do {
+ f ppf x;
+ Format.pp_print_flush ppf ();
+ Buffer.contents buff
+- } in
+- let entry = to_string Print.entry entry in
+- let symbols = to_string Print.print_rule symbols in
+- raise (Rule_not_found (symbols, entry))
++ }]] in
++ let entry = to_string Print.entry entry in
++ let symbols = to_string Print.print_rule symbols in
++ raise (Rule_not_found (symbols, entry))
+ ;
+
+ (* Deleting a rule *)
+Index: camlp4/boot/Camlp4.ml
+===================================================================
+--- camlp4/boot/Camlp4.ml (revision 14037)
++++ camlp4/boot/Camlp4.ml (working copy)
+@@ -18022,7 +18022,7 @@
+ open Structure
+
+ let raise_rule_not_found entry symbols =
+- let to_string f x =
++ let to_string : 'a. (_ -> 'a -> _) -> 'a -> _ = fun f x ->
+ let buff = Buffer.create 128 in
+ let ppf = Format.formatter_of_buffer buff
+ in
+Index: camlp4/Camlp4Filters/Camlp4FoldGenerator.ml
+===================================================================
+--- camlp4/Camlp4Filters/Camlp4FoldGenerator.ml (revision 14037)
++++ camlp4/Camlp4Filters/Camlp4FoldGenerator.ml (working copy)
+@@ -547,14 +547,18 @@
+
+ value processor =
+ let last = ref <:ctyp<>> in
+- let generate_class' generator default c s n =
++ let generate_class'
++ : !'a 'b. (_ -> 'a -> _ -> _ -> 'b) -> 'b -> 'a -> _ -> _ -> 'b =
++ fun generator default c s n ->
+ match s with
+ [ "Fold" -> generator Fold c last.val n
+ | "Map" -> generator Map c last.val n
+ | "FoldMap" -> generator Fold_map c last.val n
+ | _ -> default ]
+ in
+- let generate_class_from_module_name generator c default m =
++ let generate_class_from_module_name
++ : !'a 'b. (_ -> 'a -> _ -> _ -> 'b) -> 'a -> 'b -> _ -> 'b =
++ fun generator c default m ->
+ try Scanf.sscanf m "Camlp4%[^G]Generator" begin fun m' ->
+ try Scanf.sscanf m' "%[^0-9]%d" (generate_class' generator default c)
+ with [ End_of_file | Scanf.Scan_failure _ -> generate_class' generator default c m' 1 ]
+Index: stdlib/arg.ml
+===================================================================
+--- stdlib/arg.ml (revision 14037)
++++ stdlib/arg.ml (working copy)
+@@ -106,7 +106,7 @@
+ let l = Array.length argv in
+ let b = Buffer.create 200 in
+ let initpos = !current in
+- let stop error =
++ let stop : 'a. _ -> 'a = fun error ->
+ let progname = if initpos < l then argv.(initpos) else "(?)" in
+ begin match error with
+ | Unknown "-help" -> ()
+Index: stdlib/printf.ml
+===================================================================
+--- stdlib/printf.ml (revision 14037)
++++ stdlib/printf.ml (working copy)
+@@ -492,7 +492,7 @@
+ Don't do this at home, kids. *)
+ let scan_format fmt args n pos cont_s cont_a cont_t cont_f cont_m =
+
+- let get_arg spec n =
++ let get_arg : 'a. _ -> _ -> 'a = fun spec n ->
+ Obj.magic (args.(Sformat.int_of_index (get_index spec n))) in
+
+ let rec scan_positional n widths i =
+Index: stdlib/camlinternalOO.ml
+===================================================================
+--- stdlib/camlinternalOO.ml (revision 14037)
++++ stdlib/camlinternalOO.ml (working copy)
+@@ -349,7 +349,7 @@
+ init_table.env_init <- env_init
+
+ let dummy_class loc =
+- let undef = fun _ -> raise (Undefined_recursive_module loc) in
++ let undef : 'a 'b.'a -> 'b = fun _ -> raise (Undefined_recursive_module loc) in
+ (Obj.magic undef, undef, undef, Obj.repr 0)
+
+ (**** Objects ****)
+@@ -527,7 +527,7 @@
+ | Closure of closure
+
+ let method_impl table i arr =
+- let next () = incr i; magic arr.(!i) in
++ let next : 'a. unit -> 'a = fun () -> incr i; magic arr.(!i) in
+ match next() with
+ GetConst -> let x : t = next() in get_const x
+ | GetVar -> let n = next() in get_var n
+Index: stdlib/scanf.ml
+===================================================================
+--- stdlib/scanf.ml (revision 14037)
++++ stdlib/scanf.ml (working copy)
+@@ -1324,10 +1324,11 @@
+
+ let limr = Array.length rv - 1 in
+
+- let return v = Obj.magic v () in
+- let delay f x () = f x in
+- let stack f = delay (return f) in
+- let no_stack f _x = f in
++ let return : 'a 'b 'c. ('a -> 'b) -> 'c = fun v -> Obj.magic v () in
++ let delay : 'a 'b. ('a -> 'b) -> 'a -> unit -> 'b = fun f x () -> f x in
++ let stack : 'a 'b 'd 'e. ('a -> 'b) -> 'd -> unit -> 'e =
++ fun f -> delay (return f) in
++ let no_stack : 'a 'b. 'a -> 'b -> 'a = fun f _x -> f in
+
+ let rec scan fmt =
+
+@@ -1380,7 +1381,8 @@
+ scan_conversion skip width_opt prec_opt ir f i
+
+ and scan_conversion skip width_opt prec_opt ir f i =
+- let stack = if skip then no_stack else stack in
++ let stack : 'b 'd. (unit -> 'b) -> 'd -> unit -> 'b =
++ if skip then no_stack else stack in
+ let width = int_of_width_opt width_opt in
+ let prec = int_of_prec_opt prec_opt in
+ match Sformat.get fmt i with
+Index: typing/typemod.ml
+===================================================================
+--- typing/typemod.ml (revision 14037)
++++ typing/typemod.ml (working copy)
+@@ -420,7 +420,7 @@
+
+ (* let signature sg = List.map (fun item -> item.sig_type) sg *)
+
+-let rec transl_modtype env smty =
++let rec transl_modtype env smty : Typedtree.module_type =
+ let loc = smty.pmty_loc in
+ match smty.pmty_desc with
+ Pmty_ident lid ->
+@@ -609,7 +609,7 @@
+ List.fold_left
+ (fun env (id, _, mty) -> Env.add_module id mty.mty_type env)
+ env curr in
+- let transition env_c curr =
++ let transition : 'a. _ -> (_ * _ * 'a) list -> _ = fun env_c curr ->
+ List.map2
+ (fun (_,smty) (id,id_loc,mty) -> (id, id_loc, transl_modtype env_c smty))
+ sdecls curr in
+Index: typing/typecore.ml
+===================================================================
+--- typing/typecore.ml (revision 14037)
++++ typing/typecore.ml (working copy)
+@@ -1373,9 +1373,9 @@
+
+ let ty_arrow gty ty = newty (Tarrow ("", instance_def gty, ty, Cok)) in
+
+- let bad_conversion fmt i c =
++ let bad_conversion : 'a. string -> int -> char -> 'a = fun fmt i c ->
+ raise (Error (loc, Env.empty, Bad_conversion (fmt, i, c))) in
+- let incomplete_format fmt =
++ let incomplete_format : 'a. string -> 'a = fun fmt ->
+ raise (Error (loc, Env.empty, Incomplete_format fmt)) in
+
+ let rec type_in_format fmt =
+@@ -3238,7 +3238,7 @@
+
+ (* Typing of let bindings *)
+
+-and type_let ?(check = fun s -> Warnings.Unused_var s)
++and type_let ?(global=false) ?(check = fun s -> Warnings.Unused_var s)
+ ?(check_strict = fun s -> Warnings.Unused_var_strict s)
+ env rec_flag spat_sexp_list scope allow =
+ begin_def();
+@@ -3368,7 +3368,7 @@
+ )
+ pat_list
+ in
+- let exp_list =
++ let exp_gen_list =
+ List.map2
+ (fun (spat, sexp) (pat, slot) ->
+ let sexp =
+@@ -3386,9 +3386,12 @@
+ let exp = type_expect exp_env sexp ty' in
+ end_def ();
+ check_univars env true "definition" exp pat.pat_type vars;
+- {exp with exp_type = instance env exp.exp_type}
+- | _ -> type_expect exp_env sexp pat.pat_type)
++ {exp with exp_type = instance env exp.exp_type}, true
++ | _ ->
++ type_expect exp_env sexp pat.pat_type,
++ match sexp.pexp_desc with Pexp_ident _ -> true | _ -> false)
+ spat_sexp_list pat_slot_list in
++ let exp_list, gen_list = List.split exp_gen_list in
+ current_slot := None;
+ if is_recursive && not !rec_needed
+ && Warnings.is_active Warnings.Unused_rec_flag then
+@@ -3399,10 +3402,12 @@
+ pat_list exp_list;
+ end_def();
+ List.iter2
+- (fun pat exp ->
+- if not (is_nonexpansive exp) then
++ (fun pat (exp, gen) ->
++ if not (global || gen) then
++ iter_pattern (fun pat -> generalize_structure pat.pat_type) pat
++ else if not (is_nonexpansive exp) then
+ iter_pattern (fun pat -> generalize_expansive env pat.pat_type) pat)
+- pat_list exp_list;
++ pat_list exp_gen_list;
+ List.iter
+ (fun pat -> iter_pattern (fun pat -> generalize pat.pat_type) pat)
+ pat_list;
+@@ -3413,7 +3418,7 @@
+ let type_binding env rec_flag spat_sexp_list scope =
+ Typetexp.reset_type_variables();
+ let (pat_exp_list, new_env, unpacks) =
+- type_let
++ type_let ~global:true
+ ~check:(fun s -> Warnings.Unused_value_declaration s)
+ ~check_strict:(fun s -> Warnings.Unused_value_declaration s)
+ env rec_flag spat_sexp_list scope false
+Index: typing/includecore.ml
+===================================================================
+--- typing/includecore.ml (revision 14037)
++++ typing/includecore.ml (working copy)
+@@ -123,7 +123,8 @@
+ | Record_representation of bool
+
+ let report_type_mismatch0 first second decl ppf err =
+- let pr fmt = Format.fprintf ppf fmt in
++ let pr : 'a. ('a, Format.formatter, unit) format -> 'a
++ = fun fmt -> Format.fprintf ppf fmt in
+ match err with
+ Arity -> pr "They have different arities"
+ | Privacy -> pr "A private type would be revealed"
+Index: ocamldoc/odoc_html.ml
+===================================================================
+--- ocamldoc/odoc_html.ml (revision 14037)
++++ ocamldoc/odoc_html.ml (working copy)
+@@ -508,7 +508,7 @@
+ bs b "</table>\n"
+
+ method html_of_Index_list b =
+- let index_if_not_empty l url m =
++ let index_if_not_empty : 'a. 'a list -> _ = fun l url m ->
+ match l with
+ [] -> ()
+ | _ -> bp b "<li><a href=\"%s\">%s</a></li>\n" url m
+@@ -977,7 +977,7 @@
+ (** A function to build the header of pages. *)
+ method prepare_header module_list =
+ let f b ?(nav=None) ?(comments=[]) t =
+- let link_if_not_empty l m url =
++ let link_if_not_empty : 'a. 'a list -> _ = fun l m url ->
+ match l with
+ [] -> ()
+ | _ ->
+Index: bytecomp/translmod.ml
+===================================================================
+--- bytecomp/translmod.ml (revision 14037)
++++ bytecomp/translmod.ml (working copy)
+@@ -773,7 +773,8 @@
+ Lprim(Psetglobal target_name, [Lprim(Pmakeblock(0, Immutable), components)])
+
+ let transl_store_package component_names target_name coercion =
+- let rec make_sequence fn pos arg =
++ let rec make_sequence : 'a. (int -> 'a -> _) -> int -> 'a list -> _ =
++ fun fn pos arg ->
+ match arg with
+ [] -> lambda_unit
+ | hd :: tl -> Lsequence(fn pos hd, make_sequence fn (pos + 1) tl) in
+Index: otherlibs/labltk/jpf/jpf_font.ml
+===================================================================
+--- otherlibs/labltk/jpf/jpf_font.ml (revision 14037)
++++ otherlibs/labltk/jpf/jpf_font.ml (working copy)
+@@ -131,7 +131,7 @@
+ }
+
+ let string_of_pattern =
+- let pat f = function
++ let pat : 'a. ('a -> string) -> 'a option -> string = fun f -> function
+ Some x -> f x
+ | None -> "*"
+ in
+Index: otherlibs/labltk/browser/searchid.ml
+===================================================================
+--- otherlibs/labltk/browser/searchid.ml (revision 14037)
++++ otherlibs/labltk/browser/searchid.ml (working copy)
+@@ -396,7 +396,7 @@
+ let search_string_symbol text =
+ if text = "" then [] else
+ let lid = snd (longident_of_string text) [] in
+- let try_lookup f k =
++ let try_lookup : 'a. _ -> 'a -> (_ * 'a) list = fun f k ->
+ try let _ = f lid Env.initial in [lid, k]
+ with Not_found | Env.Error _ -> []
+ in
+Index: otherlibs/labltk/browser/setpath.ml
+===================================================================
+--- otherlibs/labltk/browser/setpath.ml (revision 14037)
++++ otherlibs/labltk/browser/setpath.ml (working copy)
+@@ -117,12 +117,12 @@
+ bind_space_toggle dirbox;
+ bind_space_toggle pathbox;
+
+- let add_paths _ =
++ let add_paths : 'a. 'a -> unit = fun _ ->
+ add_to_path pathbox ~base:!current_dir
+ ~dirs:(List.map (Listbox.curselection dirbox)
+ ~f:(fun x -> Listbox.get dirbox ~index:x));
+ Listbox.selection_clear dirbox ~first:(`Num 0) ~last:`End
+- and remove_paths _ =
++ and remove_paths : 'a. 'a -> unit = fun _ ->
+ remove_path pathbox
+ ~dirs:(List.map (Listbox.curselection pathbox)
+ ~f:(fun x -> Listbox.get pathbox ~index:x))
+Index: otherlibs/labltk/browser/viewer.ml
+===================================================================
+--- otherlibs/labltk/browser/viewer.ml (revision 14037)
++++ otherlibs/labltk/browser/viewer.ml (working copy)
+@@ -507,7 +507,8 @@
+ if i < 3 then Listbox.delete box ~first:(`Num 0) ~last:`End
+ else destroy fm
+ done;
+- let rec firsts n = function [] -> []
++ let rec firsts : 'a. int -> 'a list -> 'a list = fun n -> function
++ [] -> []
+ | a :: l -> if n > 0 then a :: firsts (pred n) l else [] in
+ shown_paths <- firsts (n-1) shown_paths;
+ boxes <- firsts (max 3 n) boxes
+Index: otherlibs/labltk/frx/frx_req.ml
+===================================================================
+--- otherlibs/labltk/frx/frx_req.ml (revision 14037)
++++ otherlibs/labltk/frx/frx_req.ml (working copy)
+@@ -40,7 +40,7 @@
+ let e =
+ Entry.create t [Relief Sunken; TextVariable memory; TextWidth len] in
+
+- let activate _ =
++ let activate : 'a. 'a -> unit = fun _ ->
+ let v = Entry.get e in
+ Grab.release t; (* because of wm *)
+ destroy t; (* so action can call open_simple *)
+@@ -77,7 +77,7 @@
+
+ let waiting = Textvariable.create_temporary t in
+
+- let activate _ =
++ let activate : 'a. 'a -> unit = fun _ ->
+ Grab.release t; (* because of wm *)
+ destroy t; (* so action can call open_simple *)
+ Textvariable.set waiting "1" in
+@@ -125,7 +125,7 @@
+ Listbox.insert lb End elements;
+
+ (* activation: we have to break() because we destroy the requester *)
+- let activate _ =
++ let activate : 'a. 'a -> unit = fun _ ->
+ let l = List.map (Listbox.get lb) (Listbox.curselection lb) in
+ Grab.release t;
+ destroy t;
+Index: otherlibs/labltk/support/rawwidget.ml
+===================================================================
+--- otherlibs/labltk/support/rawwidget.ml (revision 14037)
++++ otherlibs/labltk/support/rawwidget.ml (working copy)
+@@ -67,7 +67,7 @@
+ (* This one is always created by opentk *)
+ let default_toplevel =
+ let wname = "." in
+- let w = Typed (wname, "toplevel") in
++ let w : 'a. 'a raw_widget = Typed (wname, "toplevel") in
+ Hashtbl.add table wname w;
+ w
+
+@@ -145,7 +145,7 @@
+ then "." ^ name
+ else parentpath ^ "." ^ name
+ in
+- let w = Typed(path,clas) in
++ let w :'a. 'a raw_widget = Typed(path,clas) in
+ Hashtbl.add table path w;
+ w
+
+Index: ocamlbuild/rule.ml
+===================================================================
+--- ocamlbuild/rule.ml (revision 14037)
++++ ocamlbuild/rule.ml (working copy)
+@@ -260,7 +260,8 @@
+ which is deprecated and ignored."
+ name
+ in
+- let res_add import xs xopt =
++ let res_add : 'b. ('a -> 'b) -> 'a list -> 'a option -> 'b list =
++ fun import xs xopt ->
+ let init =
+ match xopt with
+ | None -> []
+Index: ocamlbuild/main.ml
+===================================================================
+--- ocamlbuild/main.ml (revision 14037)
++++ ocamlbuild/main.ml (working copy)
+@@ -50,7 +50,7 @@
+ let show_documentation () =
+ let rules = Rule.get_rules () in
+ let flags = Flags.get_flags () in
+- let pp fmt = Log.raw_dprintf (-1) fmt in
++ let pp : 'a. ('a,_,_) format -> 'a = fun fmt -> Log.raw_dprintf (-1) fmt in
+ List.iter begin fun rule ->
+ pp "%a@\n@\n" (Rule.pretty_print Resource.print_pattern) rule
+ end rules;
diff --git a/experimental/garrigue/objvariant.diff b/experimental/garrigue/objvariant.diff
new file mode 100644
index 0000000000..75deb24cd6
--- /dev/null
+++ b/experimental/garrigue/objvariant.diff
@@ -0,0 +1,354 @@
+? objvariants-3.09.1.diffs
+? objvariants.diffs
+Index: btype.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/btype.ml,v
+retrieving revision 1.37.4.1
+diff -u -r1.37.4.1 btype.ml
+--- btype.ml 5 Dec 2005 13:18:42 -0000 1.37.4.1
++++ btype.ml 16 Jan 2006 02:23:14 -0000
+@@ -177,7 +177,8 @@
+ Tvariant row -> iter_row f row
+ | Tvar | Tunivar | Tsubst _ | Tconstr _ ->
+ Misc.may (fun (_,l) -> List.iter f l) row.row_name;
+- List.iter f row.row_bound
++ List.iter f row.row_bound;
++ List.iter (fun (s,k,t) -> f t) row.row_object
+ | _ -> assert false
+
+ let iter_type_expr f ty =
+@@ -224,7 +225,9 @@
+ | Some (path, tl) -> Some (path, List.map f tl) in
+ { row_fields = fields; row_more = more;
+ row_bound = !bound; row_fixed = row.row_fixed && fixed;
+- row_closed = row.row_closed; row_name = name; }
++ row_closed = row.row_closed; row_name = name;
++ row_object = List.map (fun (s,k,t) -> (s,k,f t)) row.row_object;
++ }
+
+ let rec copy_kind = function
+ Fvar{contents = Some k} -> copy_kind k
+Index: ctype.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/ctype.ml,v
+retrieving revision 1.197.2.6
+diff -u -r1.197.2.6 ctype.ml
+--- ctype.ml 15 Dec 2005 02:28:38 -0000 1.197.2.6
++++ ctype.ml 16 Jan 2006 02:23:15 -0000
+@@ -1421,7 +1421,7 @@
+ newgenty
+ (Tvariant
+ {row_fields = fields; row_closed = closed; row_more = newvar();
+- row_bound = []; row_fixed = false; row_name = None })
++ row_bound = []; row_fixed = false; row_name = None; row_object=[]})
+
+ (**** Unification ****)
+
+@@ -1724,8 +1724,11 @@
+ else None
+ in
+ let bound = row1.row_bound @ row2.row_bound in
++ let opairs, _, miss2 = associate_fields row1.row_object row2.row_object in
++ let row_object = row1.row_object @ miss2 in
+ let row0 = {row_fields = []; row_more = more; row_bound = bound;
+- row_closed = closed; row_fixed = fixed; row_name = name} in
++ row_closed = closed; row_fixed = fixed; row_name = name;
++ row_object = row_object } in
+ let set_more row rest =
+ let rest =
+ if closed then
+@@ -1758,6 +1761,18 @@
+ raise (Unify ((mkvariant [l,f1] true,
+ mkvariant [l,f2] true) :: trace)))
+ pairs;
++ List.iter (fun (s,_,ty1,_,ty2) -> unify env ty1 ty2) opairs;
++ if row_object <> [] then begin
++ List.iter
++ (fun (l,f) ->
++ match row_field_repr f with
++ Rpresent (Some ty) ->
++ let fi = build_fields generic_level row_object (newgenvar()) in
++ unify env (newgenty (Tobject (fi, ref None))) ty
++ | Rpresent None -> raise (Unify [])
++ | _ -> ())
++ (row_repr row1).row_fields
++ end;
+ with exn ->
+ log_type rm1; rm1.desc <- md1; log_type rm2; rm2.desc <- md2; raise exn
+ end
+@@ -2789,7 +2804,8 @@
+ let row =
+ { row_fields = List.map fst fields; row_more = newvar();
+ row_bound = !bound; row_closed = posi; row_fixed = false;
+- row_name = if c > Unchanged then None else row.row_name }
++ row_name = if c > Unchanged then None else row.row_name;
++ row_object = [] }
+ in
+ (newty (Tvariant row), Changed)
+ | Tobject (t1, _) ->
+Index: oprint.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/oprint.ml,v
+retrieving revision 1.22
+diff -u -r1.22 oprint.ml
+--- oprint.ml 23 Mar 2005 03:08:37 -0000 1.22
++++ oprint.ml 16 Jan 2006 02:23:15 -0000
+@@ -185,7 +185,7 @@
+ fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields
+ | Otyp_stuff s -> fprintf ppf "%s" s
+ | Otyp_var (ng, s) -> fprintf ppf "'%s%s" (if ng then "_" else "") s
+- | Otyp_variant (non_gen, row_fields, closed, tags) ->
++ | Otyp_variant (non_gen, row_fields, closed, tags, obj) ->
+ let print_present ppf =
+ function
+ None | Some [] -> ()
+@@ -198,12 +198,17 @@
+ ppf fields
+ | Ovar_name (id, tyl) ->
+ fprintf ppf "@[%a%a@]" print_typargs tyl print_ident id
++ and print_object ppf obj =
++ if obj <> [] then
++ fprintf ppf "@ as @[<2>< %a >@]" (print_fields (Some false)) obj
+ in
+- fprintf ppf "%s[%s@[<hv>@[<hv>%a@]%a ]@]" (if non_gen then "_" else "")
++ fprintf ppf "%s[%s@[<hv>@[<hv>%a@]%a%a ]@]"
++ (if non_gen then "_" else "")
+ (if closed then if tags = None then " " else "< "
+ else if tags = None then "> " else "? ")
+ print_fields row_fields
+ print_present tags
++ print_object obj
+ | Otyp_alias _ | Otyp_poly _ | Otyp_arrow _ | Otyp_tuple _ as ty ->
+ fprintf ppf "@[<1>(%a)@]" print_out_type ty
+ | Otyp_abstract | Otyp_sum _ | Otyp_record _ | Otyp_manifest (_, _) -> ()
+Index: outcometree.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/outcometree.mli,v
+retrieving revision 1.14
+diff -u -r1.14 outcometree.mli
+--- outcometree.mli 23 Mar 2005 03:08:37 -0000 1.14
++++ outcometree.mli 16 Jan 2006 02:23:15 -0000
+@@ -59,6 +59,7 @@
+ | Otyp_var of bool * string
+ | Otyp_variant of
+ bool * out_variant * bool * (string list) option
++ * (string * out_type) list
+ | Otyp_poly of string list * out_type
+ and out_variant =
+ | Ovar_fields of (string * bool * out_type list) list
+Index: printtyp.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/printtyp.ml,v
+retrieving revision 1.139.2.2
+diff -u -r1.139.2.2 printtyp.ml
+--- printtyp.ml 7 Dec 2005 23:37:27 -0000 1.139.2.2
++++ printtyp.ml 16 Jan 2006 02:23:15 -0000
+@@ -244,7 +244,10 @@
+ visited_objects := px :: !visited_objects;
+ match row.row_name with
+ | Some(p, tyl) when namable_row row ->
+- List.iter (mark_loops_rec visited) tyl
++ List.iter (mark_loops_rec visited) tyl;
++ if not (static_row row) then
++ List.iter (fun (s,k,t) -> mark_loops_rec visited t)
++ row.row_object
+ | _ ->
+ iter_row (mark_loops_rec visited) {row with row_bound = []}
+ end
+@@ -343,25 +346,27 @@
+ | _ -> false)
+ fields in
+ let all_present = List.length present = List.length fields in
++ let static = row.row_closed && all_present in
++ let obj =
++ if static then [] else
++ List.map (fun (s,k,t) -> (s, tree_of_typexp sch t)) row.row_object
++ in
++ let tags = if all_present then None else Some (List.map fst present) in
+ begin match row.row_name with
+ | Some(p, tyl) when namable_row row ->
+ let id = tree_of_path p in
+ let args = tree_of_typlist sch tyl in
+- if row.row_closed && all_present then
++ if static then
+ Otyp_constr (id, args)
+ else
+ let non_gen = is_non_gen sch px in
+- let tags =
+- if all_present then None else Some (List.map fst present) in
+ Otyp_variant (non_gen, Ovar_name(tree_of_path p, args),
+- row.row_closed, tags)
++ row.row_closed, tags, obj)
+ | _ ->
+- let non_gen =
+- not (row.row_closed && all_present) && is_non_gen sch px in
++ let non_gen = not static && is_non_gen sch px in
+ let fields = List.map (tree_of_row_field sch) fields in
+- let tags =
+- if all_present then None else Some (List.map fst present) in
+- Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
++ Otyp_variant (non_gen, Ovar_fields fields, row.row_closed,
++ tags, obj)
+ end
+ | Tobject (fi, nm) ->
+ tree_of_typobject sch fi nm
+Index: typecore.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typecore.ml,v
+retrieving revision 1.176.2.2
+diff -u -r1.176.2.2 typecore.ml
+--- typecore.ml 11 Dec 2005 09:56:33 -0000 1.176.2.2
++++ typecore.ml 16 Jan 2006 02:23:15 -0000
+@@ -170,7 +170,8 @@
+ (* Force check of well-formedness *)
+ unify_pat pat.pat_env pat
+ (newty(Tvariant{row_fields=[]; row_more=newvar(); row_closed=false;
+- row_bound=[]; row_fixed=false; row_name=None}));
++ row_bound=[]; row_fixed=false; row_name=None;
++ row_object=[]}));
+ | _ -> ()
+
+ let rec iter_pattern f p =
+@@ -251,7 +252,7 @@
+ let ty = may_map (build_as_type env) p' in
+ newty (Tvariant{row_fields=[l, Rpresent ty]; row_more=newvar();
+ row_bound=[]; row_name=None;
+- row_fixed=false; row_closed=false})
++ row_fixed=false; row_closed=false; row_object=[]})
+ | Tpat_record lpl ->
+ let lbl = fst(List.hd lpl) in
+ if lbl.lbl_private = Private then p.pat_type else
+@@ -318,7 +319,8 @@
+ ([],[]) fields in
+ let row =
+ { row_fields = List.rev fields; row_more = newvar(); row_bound = !bound;
+- row_closed = false; row_fixed = false; row_name = Some (path, tyl) }
++ row_closed = false; row_fixed = false; row_name = Some (path, tyl);
++ row_object = [] }
+ in
+ let ty = newty (Tvariant row) in
+ let gloc = {loc with Location.loc_ghost=true} in
+@@ -428,7 +430,8 @@
+ row_closed = false;
+ row_more = newvar ();
+ row_fixed = false;
+- row_name = None } in
++ row_name = None;
++ row_object = [] } in
+ rp {
+ pat_desc = Tpat_variant(l, arg, row);
+ pat_loc = sp.ppat_loc;
+@@ -976,7 +979,8 @@
+ row_bound = [];
+ row_closed = false;
+ row_fixed = false;
+- row_name = None});
++ row_name = None;
++ row_object = []});
+ exp_env = env }
+ | Pexp_record(lid_sexp_list, opt_sexp) ->
+ let ty = newvar() in
+@@ -1261,8 +1265,30 @@
+ assert false
+ end
+ | _ ->
+- (Texp_send(obj, Tmeth_name met),
+- filter_method env met Public obj.exp_type)
++ let obj, met_ty =
++ match expand_head env obj.exp_type with
++ {desc = Tvariant _} ->
++ let exp_ty = newvar () in
++ let met_ty = filter_method env met Public exp_ty in
++ let row =
++ {row_fields=[]; row_more=newvar();
++ row_bound=[]; row_closed=false;
++ row_fixed=false; row_name=None;
++ row_object=[met, Fpresent, met_ty]} in
++ unify_exp env obj (newty (Tvariant row));
++ let prim = Primitive.parse_declaration 1 ["%field1"] in
++ let ty = newty(Tarrow("", obj.exp_type, exp_ty, Cok)) in
++ let vd = {val_type = ty; val_kind = Val_prim prim} in
++ let esnd =
++ {exp_desc=Texp_ident(Path.Pident(Ident.create"snd"), vd);
++ exp_loc = Location.none; exp_type = ty; exp_env = env}
++ in
++ ({obj with exp_type = exp_ty;
++ exp_desc = Texp_apply(esnd,[Some obj, Required])},
++ met_ty)
++ | _ -> (obj, filter_method env met Public obj.exp_type)
++ in
++ (Texp_send(obj, Tmeth_name met), met_ty)
+ in
+ if !Clflags.principal then begin
+ end_def ();
+Index: types.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/types.ml,v
+retrieving revision 1.25
+diff -u -r1.25 types.ml
+--- types.ml 9 Dec 2004 12:40:53 -0000 1.25
++++ types.ml 16 Jan 2006 02:23:15 -0000
+@@ -44,7 +44,9 @@
+ row_bound: type_expr list;
+ row_closed: bool;
+ row_fixed: bool;
+- row_name: (Path.t * type_expr list) option }
++ row_name: (Path.t * type_expr list) option;
++ row_object: (string * field_kind * type_expr) list;
++ }
+
+ and row_field =
+ Rpresent of type_expr option
+Index: types.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/types.mli,v
+retrieving revision 1.25
+diff -u -r1.25 types.mli
+--- types.mli 9 Dec 2004 12:40:53 -0000 1.25
++++ types.mli 16 Jan 2006 02:23:15 -0000
+@@ -43,7 +43,9 @@
+ row_bound: type_expr list;
+ row_closed: bool;
+ row_fixed: bool;
+- row_name: (Path.t * type_expr list) option }
++ row_name: (Path.t * type_expr list) option;
++ row_object: (string * field_kind * type_expr) list;
++ }
+
+ and row_field =
+ Rpresent of type_expr option
+Index: typetexp.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typetexp.ml,v
+retrieving revision 1.54
+diff -u -r1.54 typetexp.ml
+--- typetexp.ml 22 Jul 2005 06:42:36 -0000 1.54
++++ typetexp.ml 16 Jan 2006 02:23:15 -0000
+@@ -215,7 +215,8 @@
+ in
+ let row = { row_closed = true; row_fields = fields;
+ row_bound = !bound; row_name = Some (path, args);
+- row_fixed = false; row_more = newvar () } in
++ row_fixed = false; row_more = newvar ();
++ row_object = [] } in
+ let static = Btype.static_row row in
+ let row =
+ if static then row else
+@@ -262,7 +263,7 @@
+ let mkfield l f =
+ newty (Tvariant {row_fields=[l,f]; row_more=newvar();
+ row_bound=[]; row_closed=true;
+- row_fixed=false; row_name=None}) in
++ row_fixed=false; row_name=None; row_object=[]}) in
+ let add_typed_field loc l f fields =
+ try
+ let f' = List.assoc l fields in
+@@ -345,7 +346,7 @@
+ let row =
+ { row_fields = List.rev fields; row_more = newvar ();
+ row_bound = !bound; row_closed = closed;
+- row_fixed = false; row_name = !name } in
++ row_fixed = false; row_name = !name; row_object = [] } in
+ let static = Btype.static_row row in
+ let row =
+ if static then row else
diff --git a/experimental/garrigue/objvariant.ml b/experimental/garrigue/objvariant.ml
new file mode 100644
index 0000000000..3233e03c0c
--- /dev/null
+++ b/experimental/garrigue/objvariant.ml
@@ -0,0 +1,42 @@
+(* use with [cvs update -r objvariants typing] *)
+
+let f (x : [> ]) = x#m 3;;
+let o = object method m x = x+2 end;;
+f (`A o);;
+let l = [`A o; `B(object method m x = x -2 method y = 3 end)];;
+List.map f l;;
+let g = function `A x -> x#m 3 | `B x -> x#y;;
+List.map g l;;
+fun x -> ignore (x=f); List.map x l;;
+fun (x : [< `A of _ | `B of _] -> int) -> ignore (x=f); List.map x l;;
+
+
+class cvar name =
+ object
+ method name = name
+ method print ppf = Format.pp_print_string ppf name
+ end
+
+type var = [`Var of cvar]
+
+class cint n =
+ object
+ method n = n
+ method print ppf = Format.pp_print_int ppf n
+ end
+
+class ['a] cadd (e1 : 'a) (e2 : 'a) =
+ object
+ constraint 'a = [> ]
+ method e1 = e1
+ method e2 = e2
+ method print ppf = Format.fprintf ppf "(%t, %t)" e1#print e2#print
+ end
+
+type 'a expr = [var | `Int of cint | `Add of 'a cadd]
+
+type expr1 = expr1 expr
+
+let print = Format.printf "%t@."
+
+let e1 : expr1 = `Add (new cadd (`Var (new cvar "x")) (`Int (new cint 2)))
diff --git a/experimental/garrigue/parser-lessminus.diff b/experimental/garrigue/parser-lessminus.diff
new file mode 100644
index 0000000000..7b535307c6
--- /dev/null
+++ b/experimental/garrigue/parser-lessminus.diff
@@ -0,0 +1,77 @@
+Index: parsing/parser.mly
+===================================================================
+--- parsing/parser.mly (revision 11929)
++++ parsing/parser.mly (working copy)
+@@ -319,6 +319,11 @@
+ let polyvars, core_type = varify_constructors newtypes core_type in
+ (exp, ghtyp(Ptyp_poly(polyvars,core_type)))
+
++let no_lessminus =
++ List.map (fun (p,e,b) ->
++ match b with None -> (p,e)
++ | Some loc -> raise (Syntaxerr.Error (Syntaxerr.Other loc)))
++
+ %}
+
+ /* Tokens */
+@@ -597,8 +602,9 @@
+ structure_item:
+ LET rec_flag let_bindings
+ { match $3 with
+- [{ ppat_desc = Ppat_any; ppat_loc = _ }, exp] -> mkstr(Pstr_eval exp)
+- | _ -> mkstr(Pstr_value($2, List.rev $3)) }
++ [{ ppat_desc = Ppat_any; ppat_loc = _ }, exp, None] ->
++ mkstr(Pstr_eval exp)
++ | _ -> mkstr(Pstr_value($2, no_lessminus (List.rev $3))) }
+ | EXTERNAL val_ident COLON core_type EQUAL primitive_declaration
+ { mkstr(Pstr_primitive($2, {pval_type = $4; pval_prim = $6})) }
+ | TYPE type_declarations
+@@ -744,7 +750,7 @@
+ | class_simple_expr simple_labeled_expr_list
+ { mkclass(Pcl_apply($1, List.rev $2)) }
+ | LET rec_flag let_bindings IN class_expr
+- { mkclass(Pcl_let ($2, List.rev $3, $5)) }
++ { mkclass(Pcl_let ($2, no_lessminus (List.rev $3), $5)) }
+ ;
+ class_simple_expr:
+ LBRACKET core_type_comma_list RBRACKET class_longident
+@@ -981,9 +987,15 @@
+ | simple_expr simple_labeled_expr_list
+ { mkexp(Pexp_apply($1, List.rev $2)) }
+ | LET rec_flag let_bindings IN seq_expr
+- { mkexp(Pexp_let($2, List.rev $3, $5)) }
++ { match $3 with
++ | [pat, expr, Some loc] when $2 = Nonrecursive ->
++ mkexp(Pexp_apply(
++ {pexp_desc = Pexp_ident(Lident "bind"); pexp_loc = loc},
++ ["", expr; "", ghexp(Pexp_function("", None, [pat, $5]))]))
++ | bindings ->
++ mkexp(Pexp_let($2, no_lessminus (List.rev $3), $5)) }
+ | LET DOT simple_expr let_binding IN seq_expr
+- { let (pat, expr) = $4 in
++ { let (pat, expr, _) = $4 in
+ mkexp(Pexp_apply($3, ["", expr; "", ghexp(Pexp_function("", None, [pat, $6]))])) }
+ | LET MODULE UIDENT module_binding IN seq_expr
+ { mkexp(Pexp_letmodule($3, $4, $6)) }
+@@ -1197,14 +1209,17 @@
+ ;
+ let_binding:
+ val_ident fun_binding
+- { (mkpatvar $1 1, $2) }
++ { (mkpatvar $1 1, $2, None) }
+ | val_ident COLON typevar_list DOT core_type EQUAL seq_expr
+- { (ghpat(Ppat_constraint(mkpatvar $1 1, ghtyp(Ptyp_poly($3,$5)))), $7) }
++ { (ghpat(Ppat_constraint(mkpatvar $1 1, ghtyp(Ptyp_poly($3,$5)))), $7,
++ None) }
+ | val_ident COLON TYPE lident_list DOT core_type EQUAL seq_expr
+ { let exp, poly = wrap_type_annotation $4 $6 $8 in
+- (ghpat(Ppat_constraint(mkpatvar $1 1, poly)), exp) }
++ (ghpat(Ppat_constraint(mkpatvar $1 1, poly)), exp, None) }
+ | pattern EQUAL seq_expr
+- { ($1, $3) }
++ { ($1, $3, None) }
++ | pattern LESSMINUS seq_expr
++ { ($1, $3, Some (rhs_loc 2)) }
+ ;
+ fun_binding:
+ strict_binding
diff --git a/experimental/garrigue/pattern-local-types.diff b/experimental/garrigue/pattern-local-types.diff
new file mode 100644
index 0000000000..0e6f00a2ee
--- /dev/null
+++ b/experimental/garrigue/pattern-local-types.diff
@@ -0,0 +1,467 @@
+Index: typing/typecore.ml
+===================================================================
+--- typing/typecore.ml (revision 13003)
++++ typing/typecore.ml (working copy)
+@@ -61,6 +61,7 @@
+ | Not_a_packed_module of type_expr
+ | Recursive_local_constraint of (type_expr * type_expr) list
+ | Unexpected_existential
++ | Pattern_newtype_non_closed of string * type_expr
+
+ exception Error of Location.t * error
+
+@@ -121,7 +122,7 @@
+ | Pexp_function (_, eo, pel) ->
+ may expr eo; List.iter (fun (_, e) -> expr e) pel
+ | Pexp_apply (e, lel) -> expr e; List.iter (fun (_, e) -> expr e) lel
+- | Pexp_let (_, pel, e)
++ | Pexp_let (_, pel, e) -> expr e; List.iter (fun (_, e) -> expr e) pel
+ | Pexp_match (e, pel)
+ | Pexp_try (e, pel) -> expr e; List.iter (fun (_, e) -> expr e) pel
+ | Pexp_array el
+@@ -1454,7 +1455,7 @@
+
+ let duplicate_ident_types loc caselist env =
+ let caselist =
+- List.filter (fun (pat, _) -> contains_gadt env pat) caselist in
++ List.filter (fun ((_,pat), _) -> contains_gadt env pat) caselist in
+ let idents = all_idents (List.map snd caselist) in
+ List.fold_left
+ (fun env s ->
+@@ -1552,7 +1553,7 @@
+ exp_env = env }
+ | Pexp_let(Nonrecursive, [spat, sval], sbody) when contains_gadt env spat ->
+ type_expect ?in_function env
+- {sexp with pexp_desc = Pexp_match (sval, [spat, sbody])}
++ {sexp with pexp_desc = Pexp_match (sval, [([],spat), sbody])}
+ ty_expected
+ | Pexp_let(rec_flag, spat_sexp_list, sbody) ->
+ let scp =
+@@ -1572,20 +1573,21 @@
+ exp_env = env }
+ | Pexp_function (l, Some default, [spat, sbody]) ->
+ let default_loc = default.pexp_loc in
+- let scases = [
++ let scases = [([],
+ {ppat_loc = default_loc;
+ ppat_desc =
+ Ppat_construct
+ (mknoloc (Longident.(Ldot (Lident "*predef*", "Some"))),
+ Some {ppat_loc = default_loc;
+ ppat_desc = Ppat_var (mknoloc "*sth*")},
+- false)},
++ false)}),
+ {pexp_loc = default_loc;
+ pexp_desc = Pexp_ident(mknoloc (Longident.Lident "*sth*"))};
++ ([],
+ {ppat_loc = default_loc;
+ ppat_desc = Ppat_construct
+ (mknoloc (Longident.(Ldot (Lident "*predef*", "None"))),
+- None, false)},
++ None, false)}),
+ default;
+ ] in
+ let smatch = {
+@@ -1603,10 +1605,10 @@
+ pexp_desc =
+ Pexp_function (
+ l, None,
+- [ {ppat_loc = loc;
+- ppat_desc = Ppat_var (mknoloc "*opt*")},
++ [ ([], {ppat_loc = loc;
++ ppat_desc = Ppat_var (mknoloc "*opt*")}),
+ {pexp_loc = loc;
+- pexp_desc = Pexp_let(Default, [spat, smatch], sbody);
++ pexp_desc = Pexp_let(Default, [snd spat, smatch], sbody);
+ }
+ ]
+ )
+@@ -2733,10 +2735,10 @@
+ and type_cases ?in_function env ty_arg ty_res partial_flag loc caselist =
+ (* ty_arg is _fully_ generalized *)
+ let dont_propagate, has_gadts =
+- let patterns = List.map fst caselist in
++ let patterns = List.map (fun ((_,p),_) -> p) caselist in
+ List.exists contains_polymorphic_variant patterns,
+- List.exists (contains_gadt env) patterns in
+-(* prerr_endline ( if has_gadts then "contains gadt" else "no gadt"); *)
++ List.exists (contains_gadt env) patterns ||
++ List.exists (fun ((l,_),_) -> l <> []) caselist in
+ let ty_arg, ty_res, env =
+ if has_gadts && not !Clflags.principal then
+ correct_levels ty_arg, correct_levels ty_res,
+@@ -2761,9 +2763,21 @@
+ Printtyp.raw_type_expr ty_arg; *)
+ let pat_env_list =
+ List.map
+- (fun (spat, sexp) ->
++ (fun ((stypes,spat), sexp) ->
+ let loc = sexp.pexp_loc in
+ if !Clflags.principal then begin_def (); (* propagation of pattern *)
++ (* For local types *)
++ if stypes <> [] then begin_def ();
++ let lev' = get_current_level () in
++ let types = List.map (fun name -> name, newvar ~name ()) stypes in
++ let env =
++ List.fold_left (fun env (name, manifest) ->
++ (* "Vanishing" definition *)
++ let decl = new_declaration ~manifest (lev',lev') in
++ snd (Env.enter_type name decl env))
++ env types
++ in
++ (* Type the pattern itself *)
+ let scope = Some (Annot.Idef loc) in
+ let (pat, ext_env, force, unpacks) =
+ let partial =
+@@ -2773,14 +2787,42 @@
+ in type_pattern ~lev env spat scope ty_arg
+ in
+ pattern_force := force @ !pattern_force;
++ (* For local types *)
++ let ext_env =
++ List.fold_left (fun env (name, ty) ->
++ let ty = expand_head env ty in
++ match ty.desc with
++ Tconstr ((Path.Pident id as p), [], _) when
++ let decl = Env.find_type p env in
++ decl.type_newtype_level = Some (lev, lev) &&
++ decl.type_kind = Type_abstract ->
++ let (id', env) =
++ Env.enter_type name (new_declaration (lev, lev)) env in
++ let manifest = newconstr (Path.Pident id') [] in
++ (* Make previous existential "vanish" *)
++ Env.add_type id (new_declaration ~manifest (lev',lev')) env
++ | _ ->
++ if free_variables ty <> [] then
++ raise (Error (spat.ppat_loc,
++ Pattern_newtype_non_closed (name,ty)));
++ let manifest = correct_levels ty in
++ let decl = new_declaration ~manifest (lev, lev) in
++ snd (Env.enter_type name decl env))
++ ext_env types
++ in
++ if stypes <> [] then begin
++ end_def ();
++ iter_pattern (fun p -> unify_pat ext_env p (newvar())) pat;
++ end;
++ (* Principality *)
+ let pat =
+ if !Clflags.principal then begin
+ end_def ();
+ iter_pattern (fun {pat_type=t} -> generalize_structure t) pat;
+- { pat with pat_type = instance env pat.pat_type }
++ { pat with pat_type = instance ext_env pat.pat_type }
+ end else pat
+ in
+- unify_pat env pat ty_arg';
++ unify_pat ext_env pat ty_arg';
+ (pat, (ext_env, unpacks)))
+ caselist in
+ (* Check for polymorphic variants to close *)
+@@ -2802,7 +2844,7 @@
+ let in_function = if List.length caselist = 1 then in_function else None in
+ let cases =
+ List.map2
+- (fun (pat, (ext_env, unpacks)) (spat, sexp) ->
++ (fun (pat, (ext_env, unpacks)) ((stypes,spat), sexp) ->
+ let sexp = wrap_unpacks sexp unpacks in
+ let ty_res' =
+ if !Clflags.principal then begin
+@@ -2811,8 +2853,8 @@
+ end_def ();
+ generalize_structure ty; ty
+ end
+- else if contains_gadt env spat then correct_levels ty_res
+- else ty_res in
++ else if contains_gadt env spat || stypes <> []
++ then correct_levels ty_res else ty_res in
+ (* Format.printf "@[%i %i, ty_res' =@ %a@]@." lev (get_current_level())
+ Printtyp.raw_type_expr ty_res'; *)
+ let exp = type_expect ?in_function ext_env sexp ty_res' in
+@@ -3218,6 +3260,11 @@
+ | Unexpected_existential ->
+ fprintf ppf
+ "Unexpected existential"
++ | Pattern_newtype_non_closed (name, ty) ->
++ reset_and_mark_loops ty;
++ fprintf ppf
++ "@[In this pattern, local type %s has been inferred as@ %a@ %s@]"
++ name type_expr ty "It should not contain variables."
+
+ let () =
+ Env.add_delayed_check_forward := add_delayed_check
+Index: typing/ctype.mli
+===================================================================
+--- typing/ctype.mli (revision 13003)
++++ typing/ctype.mli (working copy)
+@@ -140,6 +140,9 @@
+ the parameters [pi] and returns the corresponding instance of
+ [t]. Exception [Cannot_apply] is raised in case of failure. *)
+
++val new_declaration:
++ ?manifest:type_expr -> ?loc:Location.t -> (int * int) -> type_declaration
++
+ val expand_head_once: Env.t -> type_expr -> type_expr
+ val expand_head: Env.t -> type_expr -> type_expr
+ val try_expand_once_opt: Env.t -> type_expr -> type_expr
+Index: typing/typeclass.ml
+===================================================================
+--- typing/typeclass.ml (revision 13003)
++++ typing/typeclass.ml (working copy)
+@@ -347,8 +347,8 @@
+ let mkid s = mkloc s self_loc in
+ { pexp_desc =
+ Pexp_function ("", None,
+- [mkpat (Ppat_alias (mkpat (Ppat_var (mkid "self-*")),
+- mkid ("self-" ^ cl_num))),
++ [([],mkpat (Ppat_alias (mkpat (Ppat_var (mkid "self-*")),
++ mkid ("self-" ^ cl_num)))),
+ expr]);
+ pexp_loc = expr.pexp_loc }
+
+@@ -836,15 +836,15 @@
+ | Pcl_fun (l, Some default, spat, sbody) ->
+ let loc = default.pexp_loc in
+ let scases =
+- [{ppat_loc = loc; ppat_desc = Ppat_construct (
++ [([], {ppat_loc = loc; ppat_desc = Ppat_construct (
+ mknoloc (Longident.(Ldot (Lident"*predef*", "Some"))),
+ Some{ppat_loc = loc; ppat_desc = Ppat_var (mknoloc "*sth*")},
+- false)},
++ false)}),
+ {pexp_loc = loc; pexp_desc =
+ Pexp_ident(mknoloc (Longident.Lident"*sth*"))};
+- {ppat_loc = loc; ppat_desc =
++ ([], {ppat_loc = loc; ppat_desc =
+ Ppat_construct(mknoloc (Longident.(Ldot (Lident"*predef*", "None"))),
+- None, false)},
++ None, false)}),
+ default] in
+ let smatch =
+ {pexp_loc = loc; pexp_desc =
+Index: typing/ctype.ml
+===================================================================
+--- typing/ctype.ml (revision 13003)
++++ typing/ctype.ml (working copy)
+@@ -696,6 +696,7 @@
+ Path.binding_time p
+
+ let rec update_level env level ty =
++ (* Format.eprintf "update_level %d %a@." level !Btype.print_raw ty; *)
+ let ty = repr ty in
+ if ty.level > level then begin
+ if Env.has_local_constraints env then begin
+@@ -1043,7 +1044,7 @@
+ reified_var_counter := Vars.add s index !reified_var_counter;
+ Printf.sprintf "%s#%d" s index
+
+-let new_declaration newtype manifest =
++let new_declaration ?manifest ?(loc=Location.none) newtype =
+ {
+ type_params = [];
+ type_arity = 0;
+@@ -1051,7 +1052,7 @@
+ type_private = Public;
+ type_manifest = manifest;
+ type_variance = [];
+- type_newtype_level = newtype;
++ type_newtype_level = Some newtype;
+ type_loc = Location.none;
+ }
+
+@@ -1060,7 +1061,7 @@
+ | None -> ()
+ | Some (env, newtype_lev) ->
+ let process existential =
+- let decl = new_declaration (Some (newtype_lev, newtype_lev)) None in
++ let decl = new_declaration (newtype_lev, newtype_lev) in
+ let name =
+ match repr existential with
+ {desc = Tvar (Some name)} -> name
+@@ -1808,7 +1809,7 @@
+ let reify env t =
+ let newtype_level = get_newtype_level () in
+ let create_fresh_constr lev name =
+- let decl = new_declaration (Some (newtype_level, newtype_level)) None in
++ let decl = new_declaration (newtype_level, newtype_level) in
+ let name = get_new_abstract_name name in
+ let (id, new_env) = Env.enter_type name decl !env in
+ let t = newty2 lev (Tconstr (Path.Pident id,[],ref Mnil)) in
+@@ -2039,7 +2040,7 @@
+ let add_gadt_equation env source destination =
+ let destination = duplicate_type destination in
+ let source_lev = find_newtype_level !env (Path.Pident source) in
+- let decl = new_declaration (Some source_lev) (Some destination) in
++ let decl = new_declaration ~manifest:destination source_lev in
+ let newtype_level = get_newtype_level () in
+ env := Env.add_local_constraint source decl newtype_level !env;
+ cleanup_abbrev ()
+Index: typing/typecore.mli
+===================================================================
+--- typing/typecore.mli (revision 13003)
++++ typing/typecore.mli (working copy)
+@@ -103,6 +103,7 @@
+ | Not_a_packed_module of type_expr
+ | Recursive_local_constraint of (type_expr * type_expr) list
+ | Unexpected_existential
++ | Pattern_newtype_non_closed of string * type_expr
+
+ exception Error of Location.t * error
+
+Index: testsuite/tests/typing-gadts/test.ml.reference
+===================================================================
+--- testsuite/tests/typing-gadts/test.ml.reference (revision 13003)
++++ testsuite/tests/typing-gadts/test.ml.reference (working copy)
+@@ -293,4 +293,18 @@
+ # type 'a ty = Int : int -> int ty
+ # val f : 'a ty -> 'a = <fun>
+ # val g : 'a ty -> 'a = <fun>
++# - : unit -> unit list = <fun>
++# - : unit list = []
++# Characters 17-19:
++ function type a. () -> ();; (* fail *)
++ ^^
++Error: In this pattern, local type a has been inferred as 'a
++ It should not contain variables.
++# type t = D : 'a * ('a -> int) -> t
++# val f : t -> int = <fun>
++# Characters 42-43:
++ let f = function type b. D ((x:b), f) -> (f:t->int) x;; (* fail *)
++ ^
++Error: This expression has type b -> int
++ but an expression was expected of type t -> int
+ #
+Index: testsuite/tests/typing-gadts/test.ml
+===================================================================
+--- testsuite/tests/typing-gadts/test.ml (revision 13003)
++++ testsuite/tests/typing-gadts/test.ml (working copy)
+@@ -512,3 +512,15 @@
+ let g : type a. a ty -> a =
+ let () = () in
+ fun x -> match x with Int y -> y;;
++
++(* Implicit type declarations in patterns *)
++
++(* alias *)
++function type a. (() : a) -> ([] : a list);;
++(function type a. (() : a) -> ([] : a list)) ();;
++function type a. () -> ();; (* fail *)
++
++(* existential *)
++type t = D : 'a * ('a -> int) -> t;;
++let f = function type b. D ((x:b), f) -> (f:b->int) x;;
++let f = function type b. D ((x:b), f) -> (f:t->int) x;; (* fail *)
+Index: testsuite/tests/typing-gadts/test.ml.principal.reference
+===================================================================
+--- testsuite/tests/typing-gadts/test.ml.principal.reference (revision 13003)
++++ testsuite/tests/typing-gadts/test.ml.principal.reference (working copy)
+@@ -306,4 +306,18 @@
+ # type 'a ty = Int : int -> int ty
+ # val f : 'a ty -> 'a = <fun>
+ # val g : 'a ty -> 'a = <fun>
++# - : unit -> unit list = <fun>
++# - : unit list = []
++# Characters 17-19:
++ function type a. () -> ();; (* fail *)
++ ^^
++Error: In this pattern, local type a has been inferred as 'a
++ It should not contain variables.
++# type t = D : 'a * ('a -> int) -> t
++# val f : t -> int = <fun>
++# Characters 42-43:
++ let f = function type b. D ((x:b), f) -> (f:t->int) x;; (* fail *)
++ ^
++Error: This expression has type b -> int
++ but an expression was expected of type t -> int
+ #
+Index: parsing/parser.mly
+===================================================================
+--- parsing/parser.mly (revision 13003)
++++ parsing/parser.mly (working copy)
+@@ -967,7 +967,7 @@
+ | FUNCTION opt_bar match_cases
+ { mkexp(Pexp_function("", None, List.rev $3)) }
+ | FUN labeled_simple_pattern fun_def
+- { let (l,o,p) = $2 in mkexp(Pexp_function(l, o, [p, $3])) }
++ { let (l,o,p) = $2 in mkexp(Pexp_function(l, o, [([],p), $3])) }
+ | FUN LPAREN TYPE LIDENT RPAREN fun_def
+ { mkexp(Pexp_newtype($4, $6)) }
+ | MATCH seq_expr WITH opt_bar match_cases
+@@ -1187,18 +1187,18 @@
+ EQUAL seq_expr
+ { $2 }
+ | labeled_simple_pattern fun_binding
+- { let (l, o, p) = $1 in ghexp(Pexp_function(l, o, [p, $2])) }
++ { let (l, o, p) = $1 in ghexp(Pexp_function(l, o, [([],p), $2])) }
+ | LPAREN TYPE LIDENT RPAREN fun_binding
+ { mkexp(Pexp_newtype($3, $5)) }
+ ;
+ match_cases:
+- pattern match_action { [$1, $2] }
+- | match_cases BAR pattern match_action { ($3, $4) :: $1 }
++ match_pattern match_action { [$1, $2] }
++ | match_cases BAR match_pattern match_action { ($3, $4) :: $1 }
+ ;
+ fun_def:
+ match_action { $1 }
+ | labeled_simple_pattern fun_def
+- { let (l,o,p) = $1 in ghexp(Pexp_function(l, o, [p, $2])) }
++ { let (l,o,p) = $1 in ghexp(Pexp_function(l, o, [([],p), $2])) }
+ | LPAREN TYPE LIDENT RPAREN fun_def
+ { mkexp(Pexp_newtype($3, $5)) }
+ ;
+@@ -1245,6 +1245,10 @@
+
+ /* Patterns */
+
++match_pattern:
++ pattern { [], $1 }
++ | TYPE lident_list DOT pattern { $2, $4 }
++;
+ pattern:
+ simple_pattern
+ { $1 }
+Index: parsing/parsetree.mli
+===================================================================
+--- parsing/parsetree.mli (revision 13003)
++++ parsing/parsetree.mli (working copy)
+@@ -90,10 +90,11 @@
+ Pexp_ident of Longident.t loc
+ | Pexp_constant of constant
+ | Pexp_let of rec_flag * (pattern * expression) list * expression
+- | Pexp_function of label * expression option * (pattern * expression) list
++ | Pexp_function of
++ label * expression option * ((string list * pattern) * expression) list
+ | Pexp_apply of expression * (label * expression) list
+- | Pexp_match of expression * (pattern * expression) list
+- | Pexp_try of expression * (pattern * expression) list
++ | Pexp_match of expression * ((string list * pattern) * expression) list
++ | Pexp_try of expression * ((string list * pattern) * expression) list
+ | Pexp_tuple of expression list
+ | Pexp_construct of Longident.t loc * expression option * bool
+ | Pexp_variant of label * expression option
+@@ -104,7 +105,8 @@
+ | Pexp_ifthenelse of expression * expression * expression option
+ | Pexp_sequence of expression * expression
+ | Pexp_while of expression * expression
+- | Pexp_for of string loc * expression * expression * direction_flag * expression
++ | Pexp_for of
++ string loc * expression * expression * direction_flag * expression
+ | Pexp_constraint of expression * core_type option * core_type option
+ | Pexp_when of expression * expression
+ | Pexp_send of expression * string
+Index: parsing/printast.ml
+===================================================================
+--- parsing/printast.ml (revision 13003)
++++ parsing/printast.ml (working copy)
+@@ -686,8 +686,9 @@
+ line i ppf "%a\n" fmt_longident li;
+ pattern (i+1) ppf p;
+
+-and pattern_x_expression_case i ppf (p, e) =
++and pattern_x_expression_case i ppf ((l,p), e) =
+ line i ppf "<case>\n";
++ list (i+1) string ppf l;
+ pattern (i+1) ppf p;
+ expression (i+1) ppf e;
+
diff --git a/experimental/garrigue/printers.ml b/experimental/garrigue/printers.ml
new file mode 100644
index 0000000000..c80c42d66c
--- /dev/null
+++ b/experimental/garrigue/printers.ml
@@ -0,0 +1,11 @@
+(* $Id$ *)
+
+open Types
+
+let ignore_abbrevs ppf ab =
+ let s = match ab with
+ Mnil -> "Mnil"
+ | Mlink _ -> "Mlink _"
+ | Mcons _ -> "Mcons _"
+ in
+ Format.pp_print_string ppf s
diff --git a/experimental/garrigue/propagation-to-patterns.diff b/experimental/garrigue/propagation-to-patterns.diff
new file mode 100644
index 0000000000..642d986fbb
--- /dev/null
+++ b/experimental/garrigue/propagation-to-patterns.diff
@@ -0,0 +1,212 @@
+Index: Changes
+===================================================================
+--- Changes (revision 13157)
++++ Changes (working copy)
+@@ -1,6 +1,11 @@
+ Next version
+ ------------
+
++Type system:
++- Propagate type information towards pattern-matching, even in the presence
++ of polymorphic variants (discarding only information about possibly-present
++ constructors)
++
+ Compilers:
+ - PR#5861: raise an error when multiple private keywords are used in type declarations
+ - PR#5634: parsetree rewriter (-ppx flag)
+Index: typing/typecore.ml
+===================================================================
+--- typing/typecore.ml (revision 13157)
++++ typing/typecore.ml (working copy)
+@@ -326,7 +326,7 @@
+ | _ -> assert false
+ in
+ begin match row_field tag row with
+- | Rabsent -> assert false
++ | Rabsent -> () (* assert false *)
+ | Reither (true, [], _, e) when not row.row_closed ->
+ set_row_field e (Rpresent None)
+ | Reither (false, ty::tl, _, e) when not row.row_closed ->
+@@ -1657,6 +1657,28 @@
+ sexp unpacks
+
+ (* Helpers for type_cases *)
++
++let contains_variant_either ty =
++ let rec loop ty =
++ let ty = repr ty in
++ if ty.level >= lowest_level then begin
++ mark_type_node ty;
++ match ty.desc with
++ Tvariant row ->
++ let row = row_repr row in
++ if not row.row_fixed then
++ List.iter
++ (fun (_,f) ->
++ match row_field_repr f with Reither _ -> raise Exit | _ -> ())
++ row.row_fields;
++ iter_row loop row
++ | _ ->
++ iter_type_expr loop ty
++ end
++ in
++ try loop ty; unmark_type ty; false
++ with Exit -> unmark_type ty; true
++
+ let iter_ppat f p =
+ match p.ppat_desc with
+ | Ppat_any | Ppat_var _ | Ppat_constant _
+@@ -1690,6 +1712,24 @@
+ in
+ try loop p; false with Exit -> true
+
++let check_absent_variant env =
++ iter_pattern
++ (function {pat_desc = Tpat_variant (s, arg, row)} as pat ->
++ let row = row_repr !row in
++ if List.exists (fun (s',fi) -> s = s' && row_field_repr fi <> Rabsent)
++ row.row_fields
++ then () else
++ let ty_arg =
++ match arg with None -> [] | Some p -> [correct_levels p.pat_type] in
++ let row' = {row_fields = [s, Reither(arg=None,ty_arg,true,ref None)];
++ row_more = newvar (); row_bound = ();
++ row_closed = false; row_fixed = false; row_name = None} in
++ (* Should fail *)
++ unify_pat env {pat with pat_type = newty (Tvariant row')}
++ (correct_levels pat.pat_type)
++ | _ -> ())
++
++
+ let dummy_expr = {pexp_desc = Pexp_tuple []; pexp_loc = Location.none}
+
+ (* Duplicate types of values in the environment *)
+@@ -3037,16 +3077,20 @@
+
+ and type_cases ?in_function env ty_arg ty_res partial_flag loc caselist =
+ (* ty_arg is _fully_ generalized *)
+- let dont_propagate, has_gadts =
+- let patterns = List.map fst caselist in
+- List.exists contains_polymorphic_variant patterns,
+- List.exists (contains_gadt env) patterns in
++ let patterns = List.map fst caselist in
++ let erase_either =
++ List.exists contains_polymorphic_variant patterns
++ && contains_variant_either ty_arg
++ and has_gadts = List.exists (contains_gadt env) patterns in
+ (* prerr_endline ( if has_gadts then "contains gadt" else "no gadt"); *)
+- let ty_arg, ty_res, env =
++ let ty_arg =
++ if (has_gadts || erase_either) && not !Clflags.principal
++ then correct_levels ty_arg else ty_arg
++ and ty_res, env =
+ if has_gadts && not !Clflags.principal then
+- correct_levels ty_arg, correct_levels ty_res,
+- duplicate_ident_types loc caselist env
+- else ty_arg, ty_res, env in
++ correct_levels ty_res, duplicate_ident_types loc caselist env
++ else ty_res, env
++ in
+ let lev, env =
+ if has_gadts then begin
+ (* raise level for existentials *)
+@@ -3072,10 +3116,10 @@
+ let scope = Some (Annot.Idef loc) in
+ let (pat, ext_env, force, unpacks) =
+ let partial =
+- if !Clflags.principal then Some false else None in
+- let ty_arg =
+- if dont_propagate then newvar () else instance ?partial env ty_arg
+- in type_pattern ~lev env spat scope ty_arg
++ if !Clflags.principal || erase_either
++ then Some false else None in
++ let ty_arg = instance ?partial env ty_arg in
++ type_pattern ~lev env spat scope ty_arg
+ in
+ pattern_force := force @ !pattern_force;
+ let pat =
+@@ -3134,7 +3178,11 @@
+ else
+ Partial
+ in
+- add_delayed_check (fun () -> Parmatch.check_unused env cases);
++ add_delayed_check
++ (fun () ->
++ List.iter (fun (pat, (env, _)) -> check_absent_variant env pat)
++ pat_env_list;
++ Parmatch.check_unused env cases);
+ if has_gadts then begin
+ end_def ();
+ (* Ensure that existential types do not escape *)
+Index: typing/ctype.ml
+===================================================================
+--- typing/ctype.ml (revision 13157)
++++ typing/ctype.ml (working copy)
+@@ -981,6 +981,25 @@
+ if keep then more else newty more.desc
+ | _ -> assert false
+ in
++ (* Open row if partial for pattern and contains Reither *)
++ let more', row =
++ match partial with
++ Some (free_univars, false) when row.row_closed
++ && not row.row_fixed && TypeSet.is_empty (free_univars ty) ->
++ let not_reither (_, f) =
++ match row_field_repr f with
++ Reither _ -> false
++ | _ -> true
++ in
++ if List.for_all not_reither row.row_fields
++ then (more', row) else
++ (newty2 (if keep then more.level else !current_level)
++ (Tvar None),
++ {row_fields = List.filter not_reither row.row_fields;
++ row_more = more; row_bound = ();
++ row_closed = false; row_fixed = false; row_name = None})
++ | _ -> (more', row)
++ in
+ (* Register new type first for recursion *)
+ more.desc <- Tsubst(newgenty(Ttuple[more';t]));
+ (* Return a new copy *)
+Index: testsuite/tests/typing-gadts/test.ml.reference
+===================================================================
+--- testsuite/tests/typing-gadts/test.ml.reference (revision 13157)
++++ testsuite/tests/typing-gadts/test.ml.reference (working copy)
+@@ -62,11 +62,11 @@
+ ^^^^^^^^
+ Error: This pattern matches values of type int t
+ but a pattern was expected which matches values of type s t
+-# Characters 224-237:
+- | `A, BoolLit _ -> ()
+- ^^^^^^^^^^^^^
+-Error: This pattern matches values of type ([? `A ] as 'a) * bool t
+- but a pattern was expected which matches values of type 'a * int t
++# module Polymorphic_variants :
++ sig
++ type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
++ val eval : [ `A ] * 's t -> unit
++ end
+ # module Propagation :
+ sig
+ type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
+Index: testsuite/tests/typing-gadts/test.ml.principal.reference
+===================================================================
+--- testsuite/tests/typing-gadts/test.ml.principal.reference (revision 13157)
++++ testsuite/tests/typing-gadts/test.ml.principal.reference (working copy)
+@@ -62,11 +62,11 @@
+ ^^^^^^^^
+ Error: This pattern matches values of type int t
+ but a pattern was expected which matches values of type s t
+-# Characters 224-237:
+- | `A, BoolLit _ -> ()
+- ^^^^^^^^^^^^^
+-Error: This pattern matches values of type ([? `A ] as 'a) * bool t
+- but a pattern was expected which matches values of type 'a * int t
++# module Polymorphic_variants :
++ sig
++ type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
++ val eval : [ `A ] * 's t -> unit
++ end
+ # Characters 299-300:
+ | BoolLit b -> b
+ ^
diff --git a/experimental/garrigue/show_types.diff b/experimental/garrigue/show_types.diff
new file mode 100644
index 0000000000..f59105ee96
--- /dev/null
+++ b/experimental/garrigue/show_types.diff
@@ -0,0 +1,419 @@
+Index: parsing/printast.mli
+===================================================================
+--- parsing/printast.mli (revision 13955)
++++ parsing/printast.mli (working copy)
+@@ -16,3 +16,4 @@
+ val interface : formatter -> signature_item list -> unit;;
+ val implementation : formatter -> structure_item list -> unit;;
+ val top_phrase : formatter -> toplevel_phrase -> unit;;
++val string_of_kind : ident_kind -> string;;
+Index: parsing/pprintast.ml
+===================================================================
+--- parsing/pprintast.ml (revision 13955)
++++ parsing/pprintast.ml (working copy)
+@@ -1192,8 +1192,10 @@
+ | Pdir_none -> ()
+ | Pdir_string (s) -> pp f "@ %S" s
+ | Pdir_int (i) -> pp f "@ %d" i
+- | Pdir_ident (li) -> pp f "@ %a" self#longident li
+- | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b))
++ | Pdir_ident {txt=li} -> pp f "@ %a" self#longident li
++ | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b)
++ | Pdir_show (k, {txt=li}) ->
++ pp f "@ %s %a" (Printast.string_of_kind k) self#longident li)
+
+ method toplevel_phrase f x =
+ match x with
+Index: parsing/parser.mly
+===================================================================
+--- parsing/parser.mly (revision 13955)
++++ parsing/parser.mly (working copy)
+@@ -516,9 +516,9 @@
+ | SEMISEMI EOF { [] }
+ | SEMISEMI seq_expr use_file_tail { Ptop_def[mkstrexp $2] :: $3 }
+ | SEMISEMI structure_item use_file_tail { Ptop_def[$2] :: $3 }
+- | SEMISEMI toplevel_directive use_file_tail { $2 :: $3 }
+ | structure_item use_file_tail { Ptop_def[$1] :: $2 }
+- | toplevel_directive use_file_tail { $1 :: $2 }
++ | SEMISEMI toplevel_directive SEMISEMI use_file_tail { $2 :: $4 }
++ | toplevel_directive SEMISEMI use_file_tail { $1 :: $3 }
+ ;
+
+ /* Module expressions */
+@@ -1779,16 +1779,26 @@
+ | FALSE { Lident "false" }
+ | TRUE { Lident "true" }
+ ;
++ident_kind:
++ VAL { Pkind_val }
++ | TYPE { Pkind_type }
++ | EXCEPTION { Pkind_exception }
++ | MODULE { Pkind_module }
++ | MODULE TYPE { Pkind_modtype }
++ | CLASS { Pkind_class }
++ | CLASS TYPE { Pkind_cltype }
++;
+
+ /* Toplevel directives */
+
+ toplevel_directive:
+- SHARP ident { Ptop_dir($2, Pdir_none) }
+- | SHARP ident STRING { Ptop_dir($2, Pdir_string $3) }
+- | SHARP ident INT { Ptop_dir($2, Pdir_int $3) }
+- | SHARP ident val_longident { Ptop_dir($2, Pdir_ident $3) }
+- | SHARP ident FALSE { Ptop_dir($2, Pdir_bool false) }
+- | SHARP ident TRUE { Ptop_dir($2, Pdir_bool true) }
++ SHARP ident { Ptop_dir($2, Pdir_none) }
++ | SHARP ident STRING { Ptop_dir($2, Pdir_string $3) }
++ | SHARP ident INT { Ptop_dir($2, Pdir_int $3) }
++ | SHARP ident val_longident { Ptop_dir($2, Pdir_ident (mkrhs $3 3)) }
++ | SHARP ident ident_kind any_longident { Ptop_dir($2, Pdir_show ($3, mkrhs $4 4)) }
++ | SHARP ident FALSE { Ptop_dir($2, Pdir_bool false) }
++ | SHARP ident TRUE { Ptop_dir($2, Pdir_bool true) }
+ ;
+
+ /* Miscellaneous */
+Index: parsing/parsetree.mli
+===================================================================
+--- parsing/parsetree.mli (revision 13955)
++++ parsing/parsetree.mli (working copy)
+@@ -294,6 +294,15 @@
+
+ (* Toplevel phrases *)
+
++type ident_kind =
++ Pkind_val
++ | Pkind_type
++ | Pkind_exception
++ | Pkind_module
++ | Pkind_modtype
++ | Pkind_class
++ | Pkind_cltype
++
+ type toplevel_phrase =
+ Ptop_def of structure
+ | Ptop_dir of string * directive_argument
+@@ -302,5 +311,6 @@
+ Pdir_none
+ | Pdir_string of string
+ | Pdir_int of int
+- | Pdir_ident of Longident.t
++ | Pdir_ident of Longident.t Location.loc
++ | Pdir_show of ident_kind * Longident.t Location.loc
+ | Pdir_bool of bool
+Index: parsing/printast.ml
+===================================================================
+--- parsing/printast.ml (revision 13955)
++++ parsing/printast.ml (working copy)
+@@ -737,6 +737,16 @@
+ core_type (i+1) ppf ct
+ ;;
+
++let string_of_kind = function
++ Pkind_val -> "val"
++ | Pkind_type -> "type"
++ | Pkind_exception -> "exception"
++ | Pkind_module -> "module"
++ | Pkind_modtype -> "module type"
++ | Pkind_class -> "class"
++ | Pkind_cltype -> "class type"
++;;
++
+ let rec toplevel_phrase i ppf x =
+ match x with
+ | Ptop_def (s) ->
+@@ -751,7 +761,9 @@
+ | Pdir_none -> line i ppf "Pdir_none\n"
+ | Pdir_string (s) -> line i ppf "Pdir_string \"%s\"\n" s;
+ | Pdir_int (i) -> line i ppf "Pdir_int %d\n" i;
+- | Pdir_ident (li) -> line i ppf "Pdir_ident %a\n" fmt_longident li;
++ | Pdir_ident {txt=li} -> line i ppf "Pdir_ident %a\n" fmt_longident li;
++ | Pdir_show (kind,{txt=li}) ->
++ line i ppf "Pdir_show %s %a\n" (string_of_kind kind) fmt_longident li;
+ | Pdir_bool (b) -> line i ppf "Pdir_bool %s\n" (string_of_bool b);
+ ;;
+
+Index: toplevel/opttoploop.ml
+===================================================================
+--- toplevel/opttoploop.ml (revision 13955)
++++ toplevel/opttoploop.ml (working copy)
+@@ -53,6 +53,7 @@
+ | Directive_string of (string -> unit)
+ | Directive_int of (int -> unit)
+ | Directive_ident of (Longident.t -> unit)
++ | Directive_show of (ident_kind -> Longident.t -> unit)
+ | Directive_bool of (bool -> unit)
+
+
+@@ -270,6 +271,7 @@
+ | (Directive_string f, Pdir_string s) -> f s; true
+ | (Directive_int f, Pdir_int n) -> f n; true
+ | (Directive_ident f, Pdir_ident lid) -> f lid; true
++ | (Directive_show f, Pdir_show (kind,lid)) -> f kind lid; true
+ | (Directive_bool f, Pdir_bool b) -> f b; true
+ | (_, _) ->
+ fprintf ppf "Wrong type of argument for directive `%s'.@." dir_name;
+Index: toplevel/topdirs.ml
+===================================================================
+--- toplevel/topdirs.ml (revision 13955)
++++ toplevel/topdirs.ml (working copy)
+@@ -15,6 +15,7 @@
+ open Format
+ open Misc
+ open Longident
++open Parsetree
+ open Types
+ open Cmo_format
+ open Trace
+@@ -191,9 +192,9 @@
+ Ctype.generalize ty_arg;
+ ty_arg
+
+-let find_printer_type ppf lid =
++let find_printer_type ppf {Location.loc; txt=lid} =
+ try
+- let (path, desc) = Env.lookup_value lid !toplevel_env in
++ let (path, desc) = Typetexp.find_value !toplevel_env loc lid in
+ let (ty_arg, is_old_style) =
+ try
+ (match_printer_type ppf desc "printer_type_new", false)
+@@ -201,12 +202,12 @@
+ (match_printer_type ppf desc "printer_type_old", true) in
+ (ty_arg, path, is_old_style)
+ with
+- | Not_found ->
+- fprintf ppf "Unbound value %a.@." Printtyp.longident lid;
++ Typetexp.Error _ as exn ->
++ Errors.report_error ppf exn;
+ raise Exit
+ | Ctype.Unify _ ->
+ fprintf ppf "%a has a wrong type for a printing function.@."
+- Printtyp.longident lid;
++ Printtyp.longident lid;
+ raise Exit
+
+ let dir_install_printer ppf lid =
+@@ -227,7 +228,7 @@
+ begin try
+ remove_printer path
+ with Not_found ->
+- fprintf ppf "No printer named %a.@." Printtyp.longident lid
++ fprintf ppf "No printer named %a.@." Printtyp.longident lid.Location.txt
+ end
+ with Exit -> ()
+
+@@ -244,9 +245,9 @@
+ get_code_pointer
+ (Obj.repr (fun arg -> Trace.print_trace (current_environment()) arg))
+
+-let dir_trace ppf lid =
++let dir_trace ppf {Location.loc; txt=lid} =
+ try
+- let (path, desc) = Env.lookup_value lid !toplevel_env in
++ let (path, desc) = Typetexp.find_value !toplevel_env loc lid in
+ (* Check if this is a primitive *)
+ match desc.val_kind with
+ | Val_prim p ->
+@@ -278,11 +279,11 @@
+ fprintf ppf "%a is now traced.@." Printtyp.longident lid
+ end else fprintf ppf "%a is not a function.@." Printtyp.longident lid
+ with
+- | Not_found -> fprintf ppf "Unbound value %a.@." Printtyp.longident lid
++ Typetexp.Error _ as exn -> Errors.report_error ppf exn
+
+-let dir_untrace ppf lid =
++let dir_untrace ppf {Location.loc; txt=lid} =
+ try
+- let (path, desc) = Env.lookup_value lid !toplevel_env in
++ let (path, desc) = Typetexp.find_value !toplevel_env loc lid in
+ let rec remove = function
+ | [] ->
+ fprintf ppf "%a was not traced.@." Printtyp.longident lid;
+@@ -295,7 +296,7 @@
+ end else f :: remove rem in
+ traced_functions := remove !traced_functions
+ with
+- | Not_found -> fprintf ppf "Unbound value %a.@." Printtyp.longident lid
++ Typetexp.Error _ as exn -> Errors.report_error ppf exn
+
+ let dir_untrace_all ppf () =
+ List.iter
+@@ -305,10 +306,74 @@
+ !traced_functions;
+ traced_functions := []
+
++(* Warnings *)
++
+ let parse_warnings ppf iserr s =
+ try Warnings.parse_options iserr s
+ with Arg.Bad err -> fprintf ppf "%s.@." err
+
++(* Typing information *)
++
++let rec trim_modtype = function
++ Mty_signature _ -> Mty_signature []
++ | Mty_functor (id, mty, mty') ->
++ Mty_functor (id, mty, trim_modtype mty')
++ | Mty_ident _ as mty -> mty
++
++let trim_signature = function
++ Mty_signature sg ->
++ Mty_signature
++ (List.map
++ (function
++ Sig_module (id, mty, rs) ->
++ Sig_module (id, trim_modtype mty, rs)
++ (*| Sig_modtype (id, Modtype_manifest mty) ->
++ Sig_modtype (id, Modtype_manifest (trim_modtype mty))*)
++ | item -> item)
++ sg)
++ | mty -> mty
++
++let dir_show ppf kind {Location.loc; txt=lid} =
++ let env = !Toploop.toplevel_env in
++ try
++ let id =
++ let s = match lid with
++ Longident.Lident s -> s
++ | Longident.Ldot (_,s) -> s
++ | Longident.Lapply _ -> failwith "invalid"
++ in Ident.create_persistent s
++ in
++ let item =
++ match kind with
++ Pkind_val ->
++ let path, desc = Typetexp.find_value env loc lid in
++ Sig_value (id, desc)
++ | Pkind_type ->
++ let path, desc = Typetexp.find_type env loc lid in
++ Sig_type (id, desc, Trec_not)
++ | Pkind_exception ->
++ let desc = Typetexp.find_constructor env loc lid in
++ Sig_exception (id, {exn_args=desc.cstr_args; exn_loc=Location.none})
++ | Pkind_module ->
++ let path, desc = Typetexp.find_module env loc lid in
++ Sig_module (id, trim_signature desc, Trec_not)
++ | Pkind_modtype ->
++ let path, desc = Typetexp.find_modtype env loc lid in
++ Sig_modtype (id, desc)
++ | Pkind_class ->
++ let path, desc = Typetexp.find_class env loc lid in
++ Sig_class (id, desc, Trec_not)
++ | Pkind_cltype ->
++ let path, desc = Typetexp.find_class_type env loc lid in
++ Sig_class_type (id, desc, Trec_not)
++ in
++ fprintf ppf "%a@." Printtyp.signature [item]
++ with
++ Not_found ->
++ fprintf ppf "Unknown %s.@." (Printast.string_of_kind kind)
++ | Failure "invalid" ->
++ fprintf ppf "Invalid path %a@." Printtyp.longident lid
++
+ let _ =
+ Hashtbl.add directive_table "trace" (Directive_ident (dir_trace std_out));
+ Hashtbl.add directive_table "untrace" (Directive_ident (dir_untrace std_out));
+@@ -337,4 +402,7 @@
+ (Directive_string (parse_warnings std_out false));
+
+ Hashtbl.add directive_table "warn_error"
+- (Directive_string (parse_warnings std_out true))
++ (Directive_string (parse_warnings std_out true));
++
++ Hashtbl.add directive_table "show"
++ (Directive_show (dir_show std_out))
+Index: toplevel/toploop.ml
+===================================================================
+--- toplevel/toploop.ml (revision 13955)
++++ toplevel/toploop.ml (working copy)
+@@ -25,7 +25,8 @@
+ | Directive_none of (unit -> unit)
+ | Directive_string of (string -> unit)
+ | Directive_int of (int -> unit)
+- | Directive_ident of (Longident.t -> unit)
++ | Directive_ident of (Longident.t Location.loc -> unit)
++ | Directive_show of (ident_kind -> Longident.t Location.loc -> unit)
+ | Directive_bool of (bool -> unit)
+
+ (* The table of toplevel value bindings and its accessors *)
+@@ -280,6 +281,7 @@
+ | (Directive_string f, Pdir_string s) -> f s; true
+ | (Directive_int f, Pdir_int n) -> f n; true
+ | (Directive_ident f, Pdir_ident lid) -> f lid; true
++ | (Directive_show f, Pdir_show (kind,lid)) -> f kind lid; true
+ | (Directive_bool f, Pdir_bool b) -> f b; true
+ | (_, _) ->
+ fprintf ppf "Wrong type of argument for directive `%s'.@." dir_name;
+Index: toplevel/topdirs.mli
+===================================================================
+--- toplevel/topdirs.mli (revision 13955)
++++ toplevel/topdirs.mli (working copy)
+@@ -20,11 +20,12 @@
+ val dir_cd : string -> unit
+ val dir_load : formatter -> string -> unit
+ val dir_use : formatter -> string -> unit
+-val dir_install_printer : formatter -> Longident.t -> unit
+-val dir_remove_printer : formatter -> Longident.t -> unit
+-val dir_trace : formatter -> Longident.t -> unit
+-val dir_untrace : formatter -> Longident.t -> unit
++val dir_install_printer : formatter -> Longident.t Location.loc -> unit
++val dir_remove_printer : formatter -> Longident.t Location.loc -> unit
++val dir_trace : formatter -> Longident.t Location.loc -> unit
++val dir_untrace : formatter -> Longident.t Location.loc -> unit
+ val dir_untrace_all : formatter -> unit -> unit
++val dir_show : formatter -> Parsetree.ident_kind -> Longident.t Location.loc -> unit
+
+ type 'a printer_type_new = Format.formatter -> 'a -> unit
+ type 'a printer_type_old = 'a -> unit
+Index: toplevel/toploop.mli
+===================================================================
+--- toplevel/toploop.mli (revision 13955)
++++ toplevel/toploop.mli (working copy)
+@@ -37,7 +37,8 @@
+ | Directive_none of (unit -> unit)
+ | Directive_string of (string -> unit)
+ | Directive_int of (int -> unit)
+- | Directive_ident of (Longident.t -> unit)
++ | Directive_ident of (Longident.t Location.loc -> unit)
++ | Directive_show of (Parsetree.ident_kind -> Longident.t Location.loc -> unit)
+ | Directive_bool of (bool -> unit)
+
+ val directive_table : (string, directive_fun) Hashtbl.t
+Index: tools/Makefile.shared
+===================================================================
+--- tools/Makefile.shared (revision 13955)
++++ tools/Makefile.shared (working copy)
+@@ -210,6 +210,7 @@
+ ../parsing/location.cmo \
+ ../parsing/longident.cmo \
+ ../parsing/lexer.cmo \
++ ../parsing/printast.cmo \
+ ../parsing/pprintast.cmo \
+ ../typing/ident.cmo \
+ ../typing/path.cmo \
+Index: camlp4/Camlp4/Struct/Camlp4Ast2OCamlAst.ml
+===================================================================
+--- camlp4/Camlp4/Struct/Camlp4Ast2OCamlAst.ml (revision 13955)
++++ camlp4/Camlp4/Struct/Camlp4Ast2OCamlAst.ml (working copy)
+@@ -1229,7 +1229,7 @@
+ | ExInt _ i -> Pdir_int (int_of_string i)
+ | <:expr< True >> -> Pdir_bool True
+ | <:expr< False >> -> Pdir_bool False
+- | e -> Pdir_ident (ident_noloc (ident_of_expr e)) ]
++ | e -> Pdir_ident (ident (ident_of_expr e)) ]
+ ;
+
+ value phrase =
+Index: camlp4/boot/Camlp4.ml
+===================================================================
+--- camlp4/boot/Camlp4.ml (revision 13955)
++++ camlp4/boot/Camlp4.ml (working copy)
+@@ -15686,7 +15686,7 @@
+ | ExInt (_, i) -> Pdir_int (int_of_string i)
+ | Ast.ExId (_, (Ast.IdUid (_, "True"))) -> Pdir_bool true
+ | Ast.ExId (_, (Ast.IdUid (_, "False"))) -> Pdir_bool false
+- | e -> Pdir_ident (ident_noloc (ident_of_expr e))
++ | e -> Pdir_ident (ident (ident_of_expr e))
+
+ let phrase =
+ function
diff --git a/experimental/garrigue/tests.ml b/experimental/garrigue/tests.ml
new file mode 100644
index 0000000000..c39d152fb2
--- /dev/null
+++ b/experimental/garrigue/tests.ml
@@ -0,0 +1,22 @@
+(* $Id$ *)
+
+let f1 = function `a x -> x=1 | `b -> true
+let f2 = function `a x -> x | `b -> true
+let f3 = function `b -> true
+let f x = f1 x && f2 x
+
+let sub s ?:pos{=0} ?:len{=String.length s - pos} () =
+ String.sub s pos len
+
+let cCAMLtoTKpack_options w = function
+ `After v1 -> "-after"
+ | `Anchor v1 -> "-anchor"
+ | `Before v1 -> "-before"
+ | `Expand v1 -> "-expand"
+ | `Fill v1 -> "-fill"
+ | `In v1 -> "-in"
+ | `Ipadx v1 -> "-ipadx"
+ | `Ipady v1 -> "-ipady"
+ | `Padx v1 -> "-padx"
+ | `Pady v1 -> "-pady"
+ | `Side v1 -> "-side"
diff --git a/experimental/garrigue/valvirt.diff b/experimental/garrigue/valvirt.diff
new file mode 100644
index 0000000000..2cf55742b0
--- /dev/null
+++ b/experimental/garrigue/valvirt.diff
@@ -0,0 +1,2349 @@
+Index: utils/warnings.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/utils/warnings.ml,v
+retrieving revision 1.23
+diff -u -r1.23 warnings.ml
+--- utils/warnings.ml 15 Sep 2005 03:09:26 -0000 1.23
++++ utils/warnings.ml 5 Apr 2006 02:25:59 -0000
+@@ -26,7 +26,7 @@
+ | Statement_type (* S *)
+ | Unused_match (* U *)
+ | Unused_pat
+- | Hide_instance_variable of string (* V *)
++ | Instance_variable_override of string (* V *)
+ | Illegal_backslash (* X *)
+ | Implicit_public_methods of string list
+ | Unerasable_optional_argument
+@@ -54,7 +54,7 @@
+ | Statement_type -> 's'
+ | Unused_match
+ | Unused_pat -> 'u'
+- | Hide_instance_variable _ -> 'v'
++ | Instance_variable_override _ -> 'v'
+ | Illegal_backslash
+ | Implicit_public_methods _
+ | Unerasable_optional_argument
+@@ -126,9 +126,9 @@
+ String.concat " "
+ ("the following methods are overridden \
+ by the inherited class:\n " :: slist)
+- | Hide_instance_variable lab ->
+- "this definition of an instance variable " ^ lab ^
+- " hides a previously\ndefined instance variable of the same name."
++ | Instance_variable_override lab ->
++ "the instance variable " ^ lab ^ " is overridden.\n" ^
++ "The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)"
+ | Partial_application ->
+ "this function application is partial,\n\
+ maybe some arguments are missing."
+Index: utils/warnings.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/utils/warnings.mli,v
+retrieving revision 1.16
+diff -u -r1.16 warnings.mli
+--- utils/warnings.mli 15 Sep 2005 03:09:26 -0000 1.16
++++ utils/warnings.mli 5 Apr 2006 02:25:59 -0000
+@@ -26,7 +26,7 @@
+ | Statement_type (* S *)
+ | Unused_match (* U *)
+ | Unused_pat
+- | Hide_instance_variable of string (* V *)
++ | Instance_variable_override of string (* V *)
+ | Illegal_backslash (* X *)
+ | Implicit_public_methods of string list
+ | Unerasable_optional_argument
+Index: parsing/parser.mly
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/parsing/parser.mly,v
+retrieving revision 1.123
+diff -u -r1.123 parser.mly
+--- parsing/parser.mly 23 Mar 2005 03:08:37 -0000 1.123
++++ parsing/parser.mly 5 Apr 2006 02:25:59 -0000
+@@ -623,6 +623,8 @@
+ { [] }
+ | class_fields INHERIT class_expr parent_binder
+ { Pcf_inher ($3, $4) :: $1 }
++ | class_fields VAL virtual_value
++ { Pcf_valvirt $3 :: $1 }
+ | class_fields VAL value
+ { Pcf_val $3 :: $1 }
+ | class_fields virtual_method
+@@ -638,14 +640,20 @@
+ AS LIDENT
+ { Some $2 }
+ | /* empty */
+- {None}
++ { None }
++;
++virtual_value:
++ MUTABLE VIRTUAL label COLON core_type
++ { $3, Mutable, $5, symbol_rloc () }
++ | VIRTUAL mutable_flag label COLON core_type
++ { $3, $2, $5, symbol_rloc () }
+ ;
+ value:
+- mutable_flag label EQUAL seq_expr
+- { $2, $1, $4, symbol_rloc () }
+- | mutable_flag label type_constraint EQUAL seq_expr
+- { $2, $1, (let (t, t') = $3 in ghexp(Pexp_constraint($5, t, t'))),
+- symbol_rloc () }
++ mutable_flag label EQUAL seq_expr
++ { $2, $1, $4, symbol_rloc () }
++ | mutable_flag label type_constraint EQUAL seq_expr
++ { $2, $1, (let (t, t') = $3 in ghexp(Pexp_constraint($5, t, t'))),
++ symbol_rloc () }
+ ;
+ virtual_method:
+ METHOD PRIVATE VIRTUAL label COLON poly_type
+@@ -711,8 +719,12 @@
+ | class_sig_fields CONSTRAINT constrain { Pctf_cstr $3 :: $1 }
+ ;
+ value_type:
+- mutable_flag label COLON core_type
+- { $2, $1, Some $4, symbol_rloc () }
++ VIRTUAL mutable_flag label COLON core_type
++ { $3, $2, Virtual, $5, symbol_rloc () }
++ | MUTABLE virtual_flag label COLON core_type
++ { $3, Mutable, $2, $5, symbol_rloc () }
++ | label COLON core_type
++ { $1, Immutable, Concrete, $3, symbol_rloc () }
+ ;
+ method_type:
+ METHOD private_flag label COLON poly_type
+Index: parsing/parsetree.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/parsing/parsetree.mli,v
+retrieving revision 1.42
+diff -u -r1.42 parsetree.mli
+--- parsing/parsetree.mli 23 Mar 2005 03:08:37 -0000 1.42
++++ parsing/parsetree.mli 5 Apr 2006 02:25:59 -0000
+@@ -152,7 +152,7 @@
+
+ and class_type_field =
+ Pctf_inher of class_type
+- | Pctf_val of (string * mutable_flag * core_type option * Location.t)
++ | Pctf_val of (string * mutable_flag * virtual_flag * core_type * Location.t)
+ | Pctf_virt of (string * private_flag * core_type * Location.t)
+ | Pctf_meth of (string * private_flag * core_type * Location.t)
+ | Pctf_cstr of (core_type * core_type * Location.t)
+@@ -179,6 +179,7 @@
+
+ and class_field =
+ Pcf_inher of class_expr * string option
++ | Pcf_valvirt of (string * mutable_flag * core_type * Location.t)
+ | Pcf_val of (string * mutable_flag * expression * Location.t)
+ | Pcf_virt of (string * private_flag * core_type * Location.t)
+ | Pcf_meth of (string * private_flag * expression * Location.t)
+Index: parsing/printast.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/parsing/printast.ml,v
+retrieving revision 1.29
+diff -u -r1.29 printast.ml
+--- parsing/printast.ml 4 Jan 2006 16:55:50 -0000 1.29
++++ parsing/printast.ml 5 Apr 2006 02:25:59 -0000
+@@ -353,10 +353,11 @@
+ | Pctf_inher (ct) ->
+ line i ppf "Pctf_inher\n";
+ class_type i ppf ct;
+- | Pctf_val (s, mf, cto, loc) ->
++ | Pctf_val (s, mf, vf, ct, loc) ->
+ line i ppf
+- "Pctf_val \"%s\" %a %a\n" s fmt_mutable_flag mf fmt_location loc;
+- option i core_type ppf cto;
++ "Pctf_val \"%s\" %a %a %a\n" s
++ fmt_mutable_flag mf fmt_virtual_flag vf fmt_location loc;
++ core_type (i+1) ppf ct;
+ | Pctf_virt (s, pf, ct, loc) ->
+ line i ppf
+ "Pctf_virt \"%s\" %a %a\n" s fmt_private_flag pf fmt_location loc;
+@@ -428,6 +429,10 @@
+ line i ppf "Pcf_inher\n";
+ class_expr (i+1) ppf ce;
+ option (i+1) string ppf so;
++ | Pcf_valvirt (s, mf, ct, loc) ->
++ line i ppf
++ "Pcf_valvirt \"%s\" %a %a\n" s fmt_mutable_flag mf fmt_location loc;
++ core_type (i+1) ppf ct;
+ | Pcf_val (s, mf, e, loc) ->
+ line i ppf
+ "Pcf_val \"%s\" %a %a\n" s fmt_mutable_flag mf fmt_location loc;
+Index: typing/btype.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/btype.ml,v
+retrieving revision 1.38
+diff -u -r1.38 btype.ml
+--- typing/btype.ml 4 Jan 2006 16:55:50 -0000 1.38
++++ typing/btype.ml 5 Apr 2006 02:25:59 -0000
+@@ -330,7 +330,7 @@
+
+ let unmark_class_signature sign =
+ unmark_type sign.cty_self;
+- Vars.iter (fun l (m, t) -> unmark_type t) sign.cty_vars
++ Vars.iter (fun l (m, v, t) -> unmark_type t) sign.cty_vars
+
+ let rec unmark_class_type =
+ function
+Index: typing/ctype.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/ctype.ml,v
+retrieving revision 1.200
+diff -u -r1.200 ctype.ml
+--- typing/ctype.ml 6 Jan 2006 02:16:24 -0000 1.200
++++ typing/ctype.ml 5 Apr 2006 02:25:59 -0000
+@@ -857,7 +857,7 @@
+ Tcty_signature
+ {cty_self = copy sign.cty_self;
+ cty_vars =
+- Vars.map (function (mut, ty) -> (mut, copy ty)) sign.cty_vars;
++ Vars.map (function (m, v, ty) -> (m, v, copy ty)) sign.cty_vars;
+ cty_concr = sign.cty_concr;
+ cty_inher =
+ List.map (fun (p,tl) -> (p, List.map copy tl)) sign.cty_inher}
+@@ -2354,10 +2354,11 @@
+ | CM_Val_type_mismatch of string * (type_expr * type_expr) list
+ | CM_Meth_type_mismatch of string * (type_expr * type_expr) list
+ | CM_Non_mutable_value of string
++ | CM_Non_concrete_value of string
+ | CM_Missing_value of string
+ | CM_Missing_method of string
+ | CM_Hide_public of string
+- | CM_Hide_virtual of string
++ | CM_Hide_virtual of string * string
+ | CM_Public_method of string
+ | CM_Private_method of string
+ | CM_Virtual_method of string
+@@ -2390,8 +2391,8 @@
+ end)
+ pairs;
+ Vars.iter
+- (fun lab (mut, ty) ->
+- let (mut', ty') = Vars.find lab sign1.cty_vars in
++ (fun lab (mut, v, ty) ->
++ let (mut', v', ty') = Vars.find lab sign1.cty_vars in
+ try moregen true type_pairs env ty' ty with Unify trace ->
+ raise (Failure [CM_Val_type_mismatch
+ (lab, expand_trace env trace)]))
+@@ -2437,7 +2438,7 @@
+ end
+ in
+ if Concr.mem lab sign1.cty_concr then err
+- else CM_Hide_virtual lab::err)
++ else CM_Hide_virtual ("method", lab) :: err)
+ miss1 []
+ in
+ let missing_method = List.map (fun (m, _, _) -> m) miss2 in
+@@ -2455,11 +2456,13 @@
+ in
+ let error =
+ Vars.fold
+- (fun lab (mut, ty) err ->
++ (fun lab (mut, vr, ty) err ->
+ try
+- let (mut', ty') = Vars.find lab sign1.cty_vars in
++ let (mut', vr', ty') = Vars.find lab sign1.cty_vars in
+ if mut = Mutable && mut' <> Mutable then
+ CM_Non_mutable_value lab::err
++ else if vr = Concrete && vr' <> Concrete then
++ CM_Non_concrete_value lab::err
+ else
+ err
+ with Not_found ->
+@@ -2467,6 +2470,14 @@
+ sign2.cty_vars error
+ in
+ let error =
++ Vars.fold
++ (fun lab (_,vr,_) err ->
++ if vr = Virtual && not (Vars.mem lab sign2.cty_vars) then
++ CM_Hide_virtual ("instance variable", lab) :: err
++ else err)
++ sign1.cty_vars error
++ in
++ let error =
+ List.fold_right
+ (fun e l ->
+ if List.mem e missing_method then l else CM_Virtual_method e::l)
+@@ -2516,8 +2527,8 @@
+ end)
+ pairs;
+ Vars.iter
+- (fun lab (mut, ty) ->
+- let (mut', ty') = Vars.find lab sign1.cty_vars in
++ (fun lab (_, _, ty) ->
++ let (_, _, ty') = Vars.find lab sign1.cty_vars in
+ try eqtype true type_pairs subst env ty ty' with Unify trace ->
+ raise (Failure [CM_Val_type_mismatch
+ (lab, expand_trace env trace)]))
+@@ -2554,7 +2565,7 @@
+ end
+ in
+ if Concr.mem lab sign1.cty_concr then err
+- else CM_Hide_virtual lab::err)
++ else CM_Hide_virtual ("method", lab) :: err)
+ miss1 []
+ in
+ let missing_method = List.map (fun (m, _, _) -> m) miss2 in
+@@ -2578,11 +2589,13 @@
+ in
+ let error =
+ Vars.fold
+- (fun lab (mut, ty) err ->
++ (fun lab (mut, vr, ty) err ->
+ try
+- let (mut', ty') = Vars.find lab sign1.cty_vars in
++ let (mut', vr', ty') = Vars.find lab sign1.cty_vars in
+ if mut = Mutable && mut' <> Mutable then
+ CM_Non_mutable_value lab::err
++ else if vr = Concrete && vr' <> Concrete then
++ CM_Non_concrete_value lab::err
+ else
+ err
+ with Not_found ->
+@@ -2590,6 +2603,14 @@
+ sign2.cty_vars error
+ in
+ let error =
++ Vars.fold
++ (fun lab (_,vr,_) err ->
++ if vr = Virtual && not (Vars.mem lab sign2.cty_vars) then
++ CM_Hide_virtual ("instance variable", lab) :: err
++ else err)
++ sign1.cty_vars error
++ in
++ let error =
+ List.fold_right
+ (fun e l ->
+ if List.mem e missing_method then l else CM_Virtual_method e::l)
+@@ -3279,7 +3300,7 @@
+ let nondep_class_signature env id sign =
+ { cty_self = nondep_type_rec env id sign.cty_self;
+ cty_vars =
+- Vars.map (function (m, t) -> (m, nondep_type_rec env id t))
++ Vars.map (function (m, v, t) -> (m, v, nondep_type_rec env id t))
+ sign.cty_vars;
+ cty_concr = sign.cty_concr;
+ cty_inher =
+Index: typing/ctype.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/ctype.mli,v
+retrieving revision 1.53
+diff -u -r1.53 ctype.mli
+--- typing/ctype.mli 9 Dec 2004 12:40:53 -0000 1.53
++++ typing/ctype.mli 5 Apr 2006 02:25:59 -0000
+@@ -170,10 +170,11 @@
+ | CM_Val_type_mismatch of string * (type_expr * type_expr) list
+ | CM_Meth_type_mismatch of string * (type_expr * type_expr) list
+ | CM_Non_mutable_value of string
++ | CM_Non_concrete_value of string
+ | CM_Missing_value of string
+ | CM_Missing_method of string
+ | CM_Hide_public of string
+- | CM_Hide_virtual of string
++ | CM_Hide_virtual of string * string
+ | CM_Public_method of string
+ | CM_Private_method of string
+ | CM_Virtual_method of string
+Index: typing/includeclass.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/includeclass.ml,v
+retrieving revision 1.7
+diff -u -r1.7 includeclass.ml
+--- typing/includeclass.ml 6 Mar 2000 22:11:57 -0000 1.7
++++ typing/includeclass.ml 5 Apr 2006 02:25:59 -0000
+@@ -78,14 +78,17 @@
+ | CM_Non_mutable_value lab ->
+ fprintf ppf
+ "@[The non-mutable instance variable %s cannot become mutable@]" lab
++ | CM_Non_concrete_value lab ->
++ fprintf ppf
++ "@[The virtual instance variable %s cannot become concrete@]" lab
+ | CM_Missing_value lab ->
+ fprintf ppf "@[The first class type has no instance variable %s@]" lab
+ | CM_Missing_method lab ->
+ fprintf ppf "@[The first class type has no method %s@]" lab
+ | CM_Hide_public lab ->
+ fprintf ppf "@[The public method %s cannot be hidden@]" lab
+- | CM_Hide_virtual lab ->
+- fprintf ppf "@[The virtual method %s cannot be hidden@]" lab
++ | CM_Hide_virtual (k, lab) ->
++ fprintf ppf "@[The virtual %s %s cannot be hidden@]" k lab
+ | CM_Public_method lab ->
+ fprintf ppf "@[The public method %s cannot become private" lab
+ | CM_Virtual_method lab ->
+Index: typing/oprint.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/oprint.ml,v
+retrieving revision 1.22
+diff -u -r1.22 oprint.ml
+--- typing/oprint.ml 23 Mar 2005 03:08:37 -0000 1.22
++++ typing/oprint.ml 5 Apr 2006 02:25:59 -0000
+@@ -291,8 +291,10 @@
+ fprintf ppf "@[<2>method %s%s%s :@ %a@]"
+ (if priv then "private " else "") (if virt then "virtual " else "")
+ name !out_type ty
+- | Ocsg_value (name, mut, ty) ->
+- fprintf ppf "@[<2>val %s%s :@ %a@]" (if mut then "mutable " else "")
++ | Ocsg_value (name, mut, vr, ty) ->
++ fprintf ppf "@[<2>val %s%s%s :@ %a@]"
++ (if mut then "mutable " else "")
++ (if vr then "virtual " else "")
+ name !out_type ty
+
+ let out_class_type = ref print_out_class_type
+Index: typing/outcometree.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/outcometree.mli,v
+retrieving revision 1.14
+diff -u -r1.14 outcometree.mli
+--- typing/outcometree.mli 23 Mar 2005 03:08:37 -0000 1.14
++++ typing/outcometree.mli 5 Apr 2006 02:25:59 -0000
+@@ -71,7 +71,7 @@
+ and out_class_sig_item =
+ | Ocsg_constraint of out_type * out_type
+ | Ocsg_method of string * bool * bool * out_type
+- | Ocsg_value of string * bool * out_type
++ | Ocsg_value of string * bool * bool * out_type
+
+ type out_module_type =
+ | Omty_abstract
+Index: typing/printtyp.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/printtyp.ml,v
+retrieving revision 1.140
+diff -u -r1.140 printtyp.ml
+--- typing/printtyp.ml 4 Jan 2006 16:55:50 -0000 1.140
++++ typing/printtyp.ml 5 Apr 2006 02:26:00 -0000
+@@ -650,7 +650,7 @@
+ Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
+ in
+ List.iter (fun met -> mark_loops (method_type met)) fields;
+- Vars.iter (fun _ (_, ty) -> mark_loops ty) sign.cty_vars
++ Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.cty_vars
+ | Tcty_fun (_, ty, cty) ->
+ mark_loops ty;
+ prepare_class_type params cty
+@@ -682,13 +682,15 @@
+ csil (tree_of_constraints params)
+ in
+ let all_vars =
+- Vars.fold (fun l (m, t) all -> (l, m, t) :: all) sign.cty_vars [] in
++ Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.cty_vars []
++ in
+ (* Consequence of PR#3607: order of Map.fold has changed! *)
+ let all_vars = List.rev all_vars in
+ let csil =
+ List.fold_left
+- (fun csil (l, m, t) ->
+- Ocsg_value (l, m = Mutable, tree_of_typexp sch t) :: csil)
++ (fun csil (l, m, v, t) ->
++ Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
++ :: csil)
+ csil all_vars
+ in
+ let csil =
+@@ -763,7 +765,9 @@
+ List.exists
+ (fun (lab, _, ty) ->
+ not (lab = dummy_method || Concr.mem lab sign.cty_concr))
+- fields in
++ fields
++ || Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.cty_vars false
++ in
+
+ Osig_class_type
+ (virt, Ident.name id,
+Index: typing/subst.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/subst.ml,v
+retrieving revision 1.49
+diff -u -r1.49 subst.ml
+--- typing/subst.ml 4 Jan 2006 16:55:50 -0000 1.49
++++ typing/subst.ml 5 Apr 2006 02:26:00 -0000
+@@ -178,7 +178,8 @@
+
+ let class_signature s sign =
+ { cty_self = typexp s sign.cty_self;
+- cty_vars = Vars.map (function (m, t) -> (m, typexp s t)) sign.cty_vars;
++ cty_vars =
++ Vars.map (function (m, v, t) -> (m, v, typexp s t)) sign.cty_vars;
+ cty_concr = sign.cty_concr;
+ cty_inher =
+ List.map (fun (p, tl) -> (type_path s p, List.map (typexp s) tl))
+Index: typing/typeclass.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typeclass.ml,v
+retrieving revision 1.85
+diff -u -r1.85 typeclass.ml
+--- typing/typeclass.ml 22 Jul 2005 06:42:36 -0000 1.85
++++ typing/typeclass.ml 5 Apr 2006 02:26:00 -0000
+@@ -24,7 +24,7 @@
+
+ type error =
+ Unconsistent_constraint of (type_expr * type_expr) list
+- | Method_type_mismatch of string * (type_expr * type_expr) list
++ | Field_type_mismatch of string * string * (type_expr * type_expr) list
+ | Structure_expected of class_type
+ | Cannot_apply of class_type
+ | Apply_wrong_label of label
+@@ -36,7 +36,7 @@
+ | Unbound_class_type_2 of Longident.t
+ | Abbrev_type_clash of type_expr * type_expr * type_expr
+ | Constructor_type_mismatch of string * (type_expr * type_expr) list
+- | Virtual_class of bool * string list
++ | Virtual_class of bool * string list * string list
+ | Parameter_arity_mismatch of Longident.t * int * int
+ | Parameter_mismatch of (type_expr * type_expr) list
+ | Bad_parameters of Ident.t * type_expr * type_expr
+@@ -49,6 +49,7 @@
+ | Non_collapsable_conjunction of
+ Ident.t * Types.class_declaration * (type_expr * type_expr) list
+ | Final_self_clash of (type_expr * type_expr) list
++ | Mutability_mismatch of string * mutable_flag
+
+ exception Error of Location.t * error
+
+@@ -90,7 +91,7 @@
+ generalize_class_type cty
+ | Tcty_signature {cty_self = sty; cty_vars = vars; cty_inher = inher} ->
+ Ctype.generalize sty;
+- Vars.iter (fun _ (_, ty) -> Ctype.generalize ty) vars;
++ Vars.iter (fun _ (_, _, ty) -> Ctype.generalize ty) vars;
+ List.iter (fun (_,tl) -> List.iter Ctype.generalize tl) inher
+ | Tcty_fun (_, ty, cty) ->
+ Ctype.generalize ty;
+@@ -152,7 +153,7 @@
+ | Tcty_signature sign ->
+ Ctype.closed_schema sign.cty_self
+ &&
+- Vars.fold (fun _ (_, ty) cc -> Ctype.closed_schema ty && cc)
++ Vars.fold (fun _ (_, _, ty) cc -> Ctype.closed_schema ty && cc)
+ sign.cty_vars
+ true
+ | Tcty_fun (_, ty, cty) ->
+@@ -172,7 +173,7 @@
+ limited_generalize rv cty
+ | Tcty_signature sign ->
+ Ctype.limited_generalize rv sign.cty_self;
+- Vars.iter (fun _ (_, ty) -> Ctype.limited_generalize rv ty)
++ Vars.iter (fun _ (_, _, ty) -> Ctype.limited_generalize rv ty)
+ sign.cty_vars;
+ List.iter (fun (_, tl) -> List.iter (Ctype.limited_generalize rv) tl)
+ sign.cty_inher
+@@ -201,11 +202,25 @@
+ Env.add_value id {val_type = ty; val_kind = Val_unbound} par_env)
+
+ (* Enter an instance variable in the environment *)
+-let enter_val cl_num vars lab mut ty val_env met_env par_env =
+- let (id, val_env, met_env, par_env) as result =
+- enter_met_env lab (Val_ivar (mut, cl_num)) ty val_env met_env par_env
++let enter_val cl_num vars inh lab mut virt ty val_env met_env par_env loc =
++ let (id, virt) =
++ try
++ let (id, mut', virt', ty') = Vars.find lab !vars in
++ if mut' <> mut then raise (Error(loc, Mutability_mismatch(lab, mut)));
++ Ctype.unify val_env (Ctype.instance ty) (Ctype.instance ty');
++ (if not inh then Some id else None),
++ (if virt' = Concrete then virt' else virt)
++ with
++ Ctype.Unify tr ->
++ raise (Error(loc, Field_type_mismatch("instance variable", lab, tr)))
++ | Not_found -> None, virt
++ in
++ let (id, _, _, _) as result =
++ match id with Some id -> (id, val_env, met_env, par_env)
++ | None ->
++ enter_met_env lab (Val_ivar (mut, cl_num)) ty val_env met_env par_env
+ in
+- vars := Vars.add lab (id, mut, ty) !vars;
++ vars := Vars.add lab (id, mut, virt, ty) !vars;
+ result
+
+ let inheritance self_type env concr_meths warn_meths loc parent =
+@@ -218,7 +233,7 @@
+ with Ctype.Unify trace ->
+ match trace with
+ _::_::_::({desc = Tfield(n, _, _, _)}, _)::rem ->
+- raise(Error(loc, Method_type_mismatch (n, rem)))
++ raise(Error(loc, Field_type_mismatch ("method", n, rem)))
+ | _ ->
+ assert false
+ end;
+@@ -243,7 +258,7 @@
+ in
+ let ty = transl_simple_type val_env false sty in
+ try Ctype.unify val_env ty ty' with Ctype.Unify trace ->
+- raise(Error(loc, Method_type_mismatch (lab, trace)))
++ raise(Error(loc, Field_type_mismatch ("method", lab, trace)))
+
+ let delayed_meth_specs = ref []
+
+@@ -253,7 +268,7 @@
+ in
+ let unif ty =
+ try Ctype.unify val_env ty ty' with Ctype.Unify trace ->
+- raise(Error(loc, Method_type_mismatch (lab, trace)))
++ raise(Error(loc, Field_type_mismatch ("method", lab, trace)))
+ in
+ match sty.ptyp_desc, priv with
+ Ptyp_poly ([],sty), Public ->
+@@ -279,6 +294,15 @@
+
+ (*******************************)
+
++let add_val env loc lab (mut, virt, ty) val_sig =
++ let virt =
++ try
++ let (mut', virt', ty') = Vars.find lab val_sig in
++ if virt' = Concrete then virt' else virt
++ with Not_found -> virt
++ in
++ Vars.add lab (mut, virt, ty) val_sig
++
+ let rec class_type_field env self_type meths (val_sig, concr_meths, inher) =
+ function
+ Pctf_inher sparent ->
+@@ -293,25 +317,12 @@
+ parent
+ in
+ let val_sig =
+- Vars.fold
+- (fun lab (mut, ty) val_sig -> Vars.add lab (mut, ty) val_sig)
+- cl_sig.cty_vars val_sig
+- in
++ Vars.fold (add_val env sparent.pcty_loc) cl_sig.cty_vars val_sig in
+ (val_sig, concr_meths, inher)
+
+- | Pctf_val (lab, mut, sty_opt, loc) ->
+- let (mut, ty) =
+- match sty_opt with
+- None ->
+- let (mut', ty) =
+- try Vars.find lab val_sig with Not_found ->
+- raise(Error(loc, Unbound_val lab))
+- in
+- (if mut = Mutable then mut' else Immutable), ty
+- | Some sty ->
+- mut, transl_simple_type env false sty
+- in
+- (Vars.add lab (mut, ty) val_sig, concr_meths, inher)
++ | Pctf_val (lab, mut, virt, sty, loc) ->
++ let ty = transl_simple_type env false sty in
++ (add_val env loc lab (mut, virt, ty) val_sig, concr_meths, inher)
+
+ | Pctf_virt (lab, priv, sty, loc) ->
+ declare_method env meths self_type lab priv sty loc;
+@@ -397,7 +408,7 @@
+
+ let rec class_field cl_num self_type meths vars
+ (val_env, met_env, par_env, fields, concr_meths, warn_meths,
+- inh_vals, inher) =
++ warn_vals, inher) =
+ function
+ Pcf_inher (sparent, super) ->
+ let parent = class_expr cl_num val_env par_env sparent in
+@@ -411,18 +422,23 @@
+ parent.cl_type
+ in
+ (* Variables *)
+- let (val_env, met_env, par_env, inh_vars, inh_vals) =
++ let (val_env, met_env, par_env, inh_vars, warn_vals) =
+ Vars.fold
+- (fun lab (mut, ty) (val_env, met_env, par_env, inh_vars, inh_vals) ->
++ (fun lab info (val_env, met_env, par_env, inh_vars, warn_vals) ->
++ let mut, vr, ty = info in
+ let (id, val_env, met_env, par_env) =
+- enter_val cl_num vars lab mut ty val_env met_env par_env
++ enter_val cl_num vars true lab mut vr ty val_env met_env par_env
++ sparent.pcl_loc
+ in
+- if StringSet.mem lab inh_vals then
+- Location.prerr_warning sparent.pcl_loc
+- (Warnings.Hide_instance_variable lab);
+- (val_env, met_env, par_env, (lab, id) :: inh_vars,
+- StringSet.add lab inh_vals))
+- cl_sig.cty_vars (val_env, met_env, par_env, [], inh_vals)
++ let warn_vals =
++ if vr = Virtual then warn_vals else
++ if StringSet.mem lab warn_vals then
++ (Location.prerr_warning sparent.pcl_loc
++ (Warnings.Instance_variable_override lab); warn_vals)
++ else StringSet.add lab warn_vals
++ in
++ (val_env, met_env, par_env, (lab, id) :: inh_vars, warn_vals))
++ cl_sig.cty_vars (val_env, met_env, par_env, [], warn_vals)
+ in
+ (* Inherited concrete methods *)
+ let inh_meths =
+@@ -443,11 +459,26 @@
+ in
+ (val_env, met_env, par_env,
+ lazy(Cf_inher (parent, inh_vars, inh_meths))::fields,
+- concr_meths, warn_meths, inh_vals, inher)
++ concr_meths, warn_meths, warn_vals, inher)
++
++ | Pcf_valvirt (lab, mut, styp, loc) ->
++ if !Clflags.principal then Ctype.begin_def ();
++ let ty = Typetexp.transl_simple_type val_env false styp in
++ if !Clflags.principal then begin
++ Ctype.end_def ();
++ Ctype.generalize_structure ty
++ end;
++ let (id, val_env, met_env', par_env) =
++ enter_val cl_num vars false lab mut Virtual ty
++ val_env met_env par_env loc
++ in
++ (val_env, met_env', par_env,
++ lazy(Cf_val (lab, id, None, met_env' == met_env)) :: fields,
++ concr_meths, warn_meths, StringSet.remove lab warn_vals, inher)
+
+ | Pcf_val (lab, mut, sexp, loc) ->
+- if StringSet.mem lab inh_vals then
+- Location.prerr_warning loc (Warnings.Hide_instance_variable lab);
++ if StringSet.mem lab warn_vals then
++ Location.prerr_warning loc (Warnings.Instance_variable_override lab);
+ if !Clflags.principal then Ctype.begin_def ();
+ let exp =
+ try type_exp val_env sexp with Ctype.Unify [(ty, _)] ->
+@@ -457,17 +488,19 @@
+ Ctype.end_def ();
+ Ctype.generalize_structure exp.exp_type
+ end;
+- let (id, val_env, met_env, par_env) =
+- enter_val cl_num vars lab mut exp.exp_type val_env met_env par_env
+- in
+- (val_env, met_env, par_env, lazy(Cf_val (lab, id, exp)) :: fields,
+- concr_meths, warn_meths, inh_vals, inher)
++ let (id, val_env, met_env', par_env) =
++ enter_val cl_num vars false lab mut Concrete exp.exp_type
++ val_env met_env par_env loc
++ in
++ (val_env, met_env', par_env,
++ lazy(Cf_val (lab, id, Some exp, met_env' == met_env)) :: fields,
++ concr_meths, warn_meths, StringSet.add lab warn_vals, inher)
+
+ | Pcf_virt (lab, priv, sty, loc) ->
+ virtual_method val_env meths self_type lab priv sty loc;
+ let warn_meths = Concr.remove lab warn_meths in
+ (val_env, met_env, par_env, fields, concr_meths, warn_meths,
+- inh_vals, inher)
++ warn_vals, inher)
+
+ | Pcf_meth (lab, priv, expr, loc) ->
+ let (_, ty) =
+@@ -493,7 +526,7 @@
+ end
+ | _ -> assert false
+ with Ctype.Unify trace ->
+- raise(Error(loc, Method_type_mismatch (lab, trace)))
++ raise(Error(loc, Field_type_mismatch ("method", lab, trace)))
+ end;
+ let meth_expr = make_method cl_num expr in
+ (* backup variables for Pexp_override *)
+@@ -510,12 +543,12 @@
+ Cf_meth (lab, texp)
+ end in
+ (val_env, met_env, par_env, field::fields,
+- Concr.add lab concr_meths, Concr.add lab warn_meths, inh_vals, inher)
++ Concr.add lab concr_meths, Concr.add lab warn_meths, warn_vals, inher)
+
+ | Pcf_cstr (sty, sty', loc) ->
+ type_constraint val_env sty sty' loc;
+ (val_env, met_env, par_env, fields, concr_meths, warn_meths,
+- inh_vals, inher)
++ warn_vals, inher)
+
+ | Pcf_let (rec_flag, sdefs, loc) ->
+ let (defs, val_env) =
+@@ -545,7 +578,7 @@
+ ([], met_env, par_env)
+ in
+ (val_env, met_env, par_env, lazy(Cf_let(rec_flag, defs, vals))::fields,
+- concr_meths, warn_meths, inh_vals, inher)
++ concr_meths, warn_meths, warn_vals, inher)
+
+ | Pcf_init expr ->
+ let expr = make_method cl_num expr in
+@@ -562,7 +595,7 @@
+ Cf_init texp
+ end in
+ (val_env, met_env, par_env, field::fields,
+- concr_meths, warn_meths, inh_vals, inher)
++ concr_meths, warn_meths, warn_vals, inher)
+
+ and class_structure cl_num final val_env met_env loc (spat, str) =
+ (* Environment for substructures *)
+@@ -616,7 +649,7 @@
+ Ctype.unify val_env self_type (Ctype.newvar ());
+ let sign =
+ {cty_self = public_self;
+- cty_vars = Vars.map (function (id, mut, ty) -> (mut, ty)) !vars;
++ cty_vars = Vars.map (fun (id, mut, vr, ty) -> (mut, vr, ty)) !vars;
+ cty_concr = concr_meths;
+ cty_inher = inher} in
+ let methods = get_methods self_type in
+@@ -628,7 +661,11 @@
+ be modified after this point *)
+ Ctype.close_object self_type;
+ let mets = virtual_methods {sign with cty_self = self_type} in
+- if mets <> [] then raise(Error(loc, Virtual_class(true, mets)));
++ let vals =
++ Vars.fold
++ (fun name (mut, vr, ty) l -> if vr = Virtual then name :: l else l)
++ sign.cty_vars [] in
++ if mets <> [] then raise(Error(loc, Virtual_class(true, mets, vals)));
+ let self_methods =
+ List.fold_right
+ (fun (lab,kind,ty) rem ->
+@@ -1135,9 +1172,14 @@
+ in
+
+ if cl.pci_virt = Concrete then begin
+- match virtual_methods (Ctype.signature_of_class_type typ) with
+- [] -> ()
+- | mets -> raise(Error(cl.pci_loc, Virtual_class(define_class, mets)))
++ let sign = Ctype.signature_of_class_type typ in
++ let mets = virtual_methods sign in
++ let vals =
++ Vars.fold
++ (fun name (mut, vr, ty) l -> if vr = Virtual then name :: l else l)
++ sign.cty_vars [] in
++ if mets <> [] || vals <> [] then
++ raise(Error(cl.pci_loc, Virtual_class(true, mets, vals)));
+ end;
+
+ (* Misc. *)
+@@ -1400,10 +1442,10 @@
+ Printtyp.report_unification_error ppf trace
+ (fun ppf -> fprintf ppf "Type")
+ (fun ppf -> fprintf ppf "is not compatible with type")
+- | Method_type_mismatch (m, trace) ->
++ | Field_type_mismatch (k, m, trace) ->
+ Printtyp.report_unification_error ppf trace
+ (function ppf ->
+- fprintf ppf "The method %s@ has type" m)
++ fprintf ppf "The %s %s@ has type" k m)
+ (function ppf ->
+ fprintf ppf "but is expected to have type")
+ | Structure_expected clty ->
+@@ -1451,15 +1493,20 @@
+ fprintf ppf "The expression \"new %s\" has type" c)
+ (function ppf ->
+ fprintf ppf "but is used with type")
+- | Virtual_class (cl, mets) ->
++ | Virtual_class (cl, mets, vals) ->
+ let print_mets ppf mets =
+ List.iter (function met -> fprintf ppf "@ %s" met) mets in
+ let cl_mark = if cl then "" else " type" in
++ let missings =
++ match mets, vals with
++ [], _ -> "variables"
++ | _, [] -> "methods"
++ | _ -> "methods and variables"
++ in
+ fprintf ppf
+- "@[This class%s should be virtual@ \
+- @[<2>The following methods are undefined :%a@]
+- @]"
+- cl_mark print_mets mets
++ "@[This class%s should be virtual.@ \
++ @[<2>The following %s are undefined :%a@]@]"
++ cl_mark missings print_mets (mets @ vals)
+ | Parameter_arity_mismatch(lid, expected, provided) ->
+ fprintf ppf
+ "@[The class constructor %a@ expects %i type argument(s),@ \
+@@ -1532,3 +1579,10 @@
+ fprintf ppf "This object is expected to have type")
+ (function ppf ->
+ fprintf ppf "but has actually type")
++ | Mutability_mismatch (lab, mut) ->
++ let mut1, mut2 =
++ if mut = Immutable then "mutable", "immutable"
++ else "immutable", "mutable" in
++ fprintf ppf
++ "@[The instance variable is %s,@ it cannot be redefined as %s@]"
++ mut1 mut2
+Index: typing/typeclass.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typeclass.mli,v
+retrieving revision 1.18
+diff -u -r1.18 typeclass.mli
+--- typing/typeclass.mli 1 Dec 2003 00:32:11 -0000 1.18
++++ typing/typeclass.mli 5 Apr 2006 02:26:00 -0000
+@@ -49,7 +49,7 @@
+
+ type error =
+ Unconsistent_constraint of (type_expr * type_expr) list
+- | Method_type_mismatch of string * (type_expr * type_expr) list
++ | Field_type_mismatch of string * string * (type_expr * type_expr) list
+ | Structure_expected of class_type
+ | Cannot_apply of class_type
+ | Apply_wrong_label of label
+@@ -61,7 +61,7 @@
+ | Unbound_class_type_2 of Longident.t
+ | Abbrev_type_clash of type_expr * type_expr * type_expr
+ | Constructor_type_mismatch of string * (type_expr * type_expr) list
+- | Virtual_class of bool * string list
++ | Virtual_class of bool * string list * string list
+ | Parameter_arity_mismatch of Longident.t * int * int
+ | Parameter_mismatch of (type_expr * type_expr) list
+ | Bad_parameters of Ident.t * type_expr * type_expr
+@@ -74,6 +74,7 @@
+ | Non_collapsable_conjunction of
+ Ident.t * Types.class_declaration * (type_expr * type_expr) list
+ | Final_self_clash of (type_expr * type_expr) list
++ | Mutability_mismatch of string * mutable_flag
+
+ exception Error of Location.t * error
+
+Index: typing/typecore.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typecore.ml,v
+retrieving revision 1.178
+diff -u -r1.178 typecore.ml
+--- typing/typecore.ml 6 Jan 2006 02:25:37 -0000 1.178
++++ typing/typecore.ml 5 Apr 2006 02:26:00 -0000
+@@ -611,11 +611,11 @@
+ List.for_all
+ (function
+ Cf_meth _ -> true
+- | Cf_val (_,_,e) -> incr count; is_nonexpansive e
++ | Cf_val (_,_,e,_) -> incr count; is_nonexpansive_opt e
+ | Cf_init e -> is_nonexpansive e
+ | Cf_inher _ | Cf_let _ -> false)
+ fields &&
+- Vars.fold (fun _ (mut,_) b -> decr count; b && mut = Immutable)
++ Vars.fold (fun _ (mut,_,_) b -> decr count; b && mut = Immutable)
+ vars true &&
+ !count = 0
+ | _ -> false
+@@ -1356,7 +1356,7 @@
+ (path_self, _) ->
+ let type_override (lab, snewval) =
+ begin try
+- let (id, _, ty) = Vars.find lab !vars in
++ let (id, _, _, ty) = Vars.find lab !vars in
+ (Path.Pident id, type_expect env snewval (instance ty))
+ with
+ Not_found ->
+Index: typing/typecore.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typecore.mli,v
+retrieving revision 1.37
+diff -u -r1.37 typecore.mli
+--- typing/typecore.mli 4 Mar 2005 14:51:31 -0000 1.37
++++ typing/typecore.mli 5 Apr 2006 02:26:00 -0000
+@@ -38,7 +38,8 @@
+ string -> type_expr -> Env.t -> Env.t -> Env.t -> Parsetree.pattern ->
+ Typedtree.pattern *
+ (Ident.t * type_expr) Meths.t ref *
+- (Ident.t * Asttypes.mutable_flag * type_expr) Vars.t ref *
++ (Ident.t * Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr)
++ Vars.t ref *
+ Env.t * Env.t * Env.t
+ val type_expect:
+ ?in_function:(Location.t * type_expr) ->
+Index: typing/typedtree.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typedtree.ml,v
+retrieving revision 1.36
+diff -u -r1.36 typedtree.ml
+--- typing/typedtree.ml 25 Nov 2003 09:20:43 -0000 1.36
++++ typing/typedtree.ml 5 Apr 2006 02:26:00 -0000
+@@ -106,7 +106,7 @@
+
+ and class_field =
+ Cf_inher of class_expr * (string * Ident.t) list * (string * Ident.t) list
+- | Cf_val of string * Ident.t * expression
++ | Cf_val of string * Ident.t * expression option * bool
+ | Cf_meth of string * expression
+ | Cf_let of rec_flag * (pattern * expression) list *
+ (Ident.t * expression) list
+@@ -140,7 +140,8 @@
+ | Tstr_recmodule of (Ident.t * module_expr) list
+ | Tstr_modtype of Ident.t * module_type
+ | Tstr_open of Path.t
+- | Tstr_class of (Ident.t * int * string list * class_expr) list
++ | Tstr_class of
++ (Ident.t * int * string list * class_expr * virtual_flag) list
+ | Tstr_cltype of (Ident.t * cltype_declaration) list
+ | Tstr_include of module_expr * Ident.t list
+
+Index: typing/typedtree.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typedtree.mli,v
+retrieving revision 1.34
+diff -u -r1.34 typedtree.mli
+--- typing/typedtree.mli 25 Nov 2003 09:20:43 -0000 1.34
++++ typing/typedtree.mli 5 Apr 2006 02:26:00 -0000
+@@ -107,7 +107,8 @@
+ and class_field =
+ Cf_inher of class_expr * (string * Ident.t) list * (string * Ident.t) list
+ (* Inherited instance variables and concrete methods *)
+- | Cf_val of string * Ident.t * expression
++ | Cf_val of string * Ident.t * expression option * bool
++ (* None = virtual, true = override *)
+ | Cf_meth of string * expression
+ | Cf_let of rec_flag * (pattern * expression) list *
+ (Ident.t * expression) list
+@@ -141,7 +142,8 @@
+ | Tstr_recmodule of (Ident.t * module_expr) list
+ | Tstr_modtype of Ident.t * module_type
+ | Tstr_open of Path.t
+- | Tstr_class of (Ident.t * int * string list * class_expr) list
++ | Tstr_class of
++ (Ident.t * int * string list * class_expr * virtual_flag) list
+ | Tstr_cltype of (Ident.t * cltype_declaration) list
+ | Tstr_include of module_expr * Ident.t list
+
+Index: typing/typemod.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/typemod.ml,v
+retrieving revision 1.73
+diff -u -r1.73 typemod.ml
+--- typing/typemod.ml 8 Aug 2005 09:41:51 -0000 1.73
++++ typing/typemod.ml 5 Apr 2006 02:26:00 -0000
+@@ -17,6 +17,7 @@
+ open Misc
+ open Longident
+ open Path
++open Asttypes
+ open Parsetree
+ open Types
+ open Typedtree
+@@ -667,8 +668,9 @@
+ let (classes, new_env) = Typeclass.class_declarations env cl in
+ let (str_rem, sig_rem, final_env) = type_struct new_env srem in
+ (Tstr_class
+- (List.map (fun (i, _,_,_,_,_,_,_, s, m, c) ->
+- (i, s, m, c)) classes) ::
++ (List.map (fun (i, d, _,_,_,_,_,_, s, m, c) ->
++ let vf = if d.cty_new = None then Virtual else Concrete in
++ (i, s, m, c, vf)) classes) ::
+ Tstr_cltype
+ (List.map (fun (_,_, i, d, _,_,_,_,_,_,_) -> (i, d)) classes) ::
+ Tstr_type
+Index: typing/types.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/types.ml,v
+retrieving revision 1.25
+diff -u -r1.25 types.ml
+--- typing/types.ml 9 Dec 2004 12:40:53 -0000 1.25
++++ typing/types.ml 5 Apr 2006 02:26:00 -0000
+@@ -90,7 +90,8 @@
+ | Val_prim of Primitive.description (* Primitive *)
+ | Val_ivar of mutable_flag * string (* Instance variable (mutable ?) *)
+ | Val_self of (Ident.t * type_expr) Meths.t ref *
+- (Ident.t * Asttypes.mutable_flag * type_expr) Vars.t ref *
++ (Ident.t * Asttypes.mutable_flag *
++ Asttypes.virtual_flag * type_expr) Vars.t ref *
+ string * type_expr
+ (* Self *)
+ | Val_anc of (string * Ident.t) list * string
+@@ -156,7 +157,8 @@
+
+ and class_signature =
+ { cty_self: type_expr;
+- cty_vars: (Asttypes.mutable_flag * type_expr) Vars.t;
++ cty_vars:
++ (Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t;
+ cty_concr: Concr.t;
+ cty_inher: (Path.t * type_expr list) list }
+
+Index: typing/types.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/types.mli,v
+retrieving revision 1.25
+diff -u -r1.25 types.mli
+--- typing/types.mli 9 Dec 2004 12:40:53 -0000 1.25
++++ typing/types.mli 5 Apr 2006 02:26:00 -0000
+@@ -91,7 +91,8 @@
+ | Val_prim of Primitive.description (* Primitive *)
+ | Val_ivar of mutable_flag * string (* Instance variable (mutable ?) *)
+ | Val_self of (Ident.t * type_expr) Meths.t ref *
+- (Ident.t * Asttypes.mutable_flag * type_expr) Vars.t ref *
++ (Ident.t * Asttypes.mutable_flag *
++ Asttypes.virtual_flag * type_expr) Vars.t ref *
+ string * type_expr
+ (* Self *)
+ | Val_anc of (string * Ident.t) list * string
+@@ -158,7 +159,8 @@
+
+ and class_signature =
+ { cty_self: type_expr;
+- cty_vars: (Asttypes.mutable_flag * type_expr) Vars.t;
++ cty_vars:
++ (Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t;
+ cty_concr: Concr.t;
+ cty_inher: (Path.t * type_expr list) list }
+
+Index: typing/unused_var.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/typing/unused_var.ml,v
+retrieving revision 1.5
+diff -u -r1.5 unused_var.ml
+--- typing/unused_var.ml 4 Jan 2006 16:55:50 -0000 1.5
++++ typing/unused_var.ml 5 Apr 2006 02:26:00 -0000
+@@ -245,7 +245,7 @@
+ match cf with
+ | Pcf_inher (ce, _) -> class_expr ppf tbl ce;
+ | Pcf_val (_, _, e, _) -> expression ppf tbl e;
+- | Pcf_virt _ -> ()
++ | Pcf_virt _ | Pcf_valvirt _ -> ()
+ | Pcf_meth (_, _, e, _) -> expression ppf tbl e;
+ | Pcf_cstr _ -> ()
+ | Pcf_let (recflag, pel, _) -> let_pel ppf tbl recflag pel None;
+Index: bytecomp/translclass.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/translclass.ml,v
+retrieving revision 1.38
+diff -u -r1.38 translclass.ml
+--- bytecomp/translclass.ml 13 Aug 2005 20:59:37 -0000 1.38
++++ bytecomp/translclass.ml 5 Apr 2006 02:26:00 -0000
+@@ -133,10 +133,10 @@
+ (fun _ -> lambda_unit) cl
+ in
+ (inh_init, lsequence obj_init' obj_init, true)
+- | Cf_val (_, id, exp) ->
++ | Cf_val (_, id, Some exp, _) ->
+ (inh_init, lsequence (set_inst_var obj id exp) obj_init,
+ has_init)
+- | Cf_meth _ ->
++ | Cf_meth _ | Cf_val _ ->
+ (inh_init, obj_init, has_init)
+ | Cf_init _ ->
+ (inh_init, obj_init, true)
+@@ -213,27 +213,17 @@
+ if len < 2 && nvals = 0 then Meths.fold (bind_method tbl) meths cl_init else
+ if len = 0 && nvals < 2 then transl_vals tbl true vals cl_init else
+ let ids = Ident.create "ids" in
+- let i = ref len in
+- let getter, names, cl_init =
+- match vals with [] -> "get_method_labels", [], cl_init
+- | (_,id0)::vals' ->
+- incr i;
+- let i = ref (List.length vals) in
+- "new_methods_variables",
+- [transl_meth_list (List.map fst vals)],
+- Llet(Strict, id0, lfield ids 0,
+- List.fold_right
+- (fun (name,id) rem ->
+- decr i;
+- Llet(Alias, id, Lprim(Poffsetint !i, [Lvar id0]), rem))
+- vals' cl_init)
++ let i = ref (len + nvals) in
++ let getter, names =
++ if nvals = 0 then "get_method_labels", [] else
++ "new_methods_variables", [transl_meth_list (List.map fst vals)]
+ in
+ Llet(StrictOpt, ids,
+ Lapply (oo_prim getter,
+ [Lvar tbl; transl_meth_list (List.map fst methl)] @ names),
+ List.fold_right
+ (fun (lab,id) lam -> decr i; Llet(StrictOpt, id, lfield ids !i, lam))
+- methl cl_init)
++ (methl @ vals) cl_init)
+
+ let output_methods tbl methods lam =
+ match methods with
+@@ -283,8 +273,9 @@
+ (vals, meths_super cla str.cl_meths meths)
+ inh_init cl_init msubst top cl in
+ (inh_init, cl_init, [], values)
+- | Cf_val (name, id, exp) ->
+- (inh_init, cl_init, methods, (name, id)::values)
++ | Cf_val (name, id, exp, over) ->
++ let values = if over then values else (name, id) :: values in
++ (inh_init, cl_init, methods, values)
+ | Cf_meth (name, exp) ->
+ let met_code = msubst true (transl_exp exp) in
+ let met_code =
+@@ -342,27 +333,24 @@
+ assert (Path.same path path');
+ let lpath = transl_path path in
+ let inh = Ident.create "inh"
+- and inh_vals = Ident.create "vals"
+- and inh_meths = Ident.create "meths"
++ and ofs = List.length vals + 1
+ and valids, methids = super in
+ let cl_init =
+ List.fold_left
+ (fun init (nm, id, _) ->
+- Llet(StrictOpt, id, lfield inh_meths (index nm concr_meths),
++ Llet(StrictOpt, id, lfield inh (index nm concr_meths + ofs),
+ init))
+ cl_init methids in
+ let cl_init =
+ List.fold_left
+ (fun init (nm, id) ->
+- Llet(StrictOpt, id, lfield inh_vals (index nm vals), init))
++ Llet(StrictOpt, id, lfield inh (index nm vals + 1), init))
+ cl_init valids in
+ (inh_init,
+ Llet (Strict, inh,
+ Lapply(oo_prim "inherits", narrow_args @
+ [lpath; Lconst(Const_pointer(if top then 1 else 0))]),
+- Llet(StrictOpt, obj_init, lfield inh 0,
+- Llet(Alias, inh_vals, lfield inh 1,
+- Llet(Alias, inh_meths, lfield inh 2, cl_init)))))
++ Llet(StrictOpt, obj_init, lfield inh 0, cl_init)))
+ | _ ->
+ let core cl_init =
+ build_class_init cla true super inh_init cl_init msubst top cl
+@@ -397,12 +385,16 @@
+ XXX Il devrait etre peu couteux d'ecrire des classes :
+ class c x y = d e f
+ *)
+-let rec transl_class_rebind obj_init cl =
++let rec transl_class_rebind obj_init cl vf =
+ match cl.cl_desc with
+ Tclass_ident path ->
++ if vf = Concrete then begin
++ try if (Env.find_class path cl.cl_env).cty_new = None then raise Exit
++ with Not_found -> raise Exit
++ end;
+ (path, obj_init)
+ | Tclass_fun (pat, _, cl, partial) ->
+- let path, obj_init = transl_class_rebind obj_init cl in
++ let path, obj_init = transl_class_rebind obj_init cl vf in
+ let build params rem =
+ let param = name_pattern "param" [pat, ()] in
+ Lfunction (Curried, param::params,
+@@ -414,14 +406,14 @@
+ Lfunction (Curried, params, rem) -> build params rem
+ | rem -> build [] rem)
+ | Tclass_apply (cl, oexprs) ->
+- let path, obj_init = transl_class_rebind obj_init cl in
++ let path, obj_init = transl_class_rebind obj_init cl vf in
+ (path, transl_apply obj_init oexprs)
+ | Tclass_let (rec_flag, defs, vals, cl) ->
+- let path, obj_init = transl_class_rebind obj_init cl in
++ let path, obj_init = transl_class_rebind obj_init cl vf in
+ (path, Translcore.transl_let rec_flag defs obj_init)
+ | Tclass_structure _ -> raise Exit
+ | Tclass_constraint (cl', _, _, _) ->
+- let path, obj_init = transl_class_rebind obj_init cl' in
++ let path, obj_init = transl_class_rebind obj_init cl' vf in
+ let rec check_constraint = function
+ Tcty_constr(path', _, _) when Path.same path path' -> ()
+ | Tcty_fun (_, _, cty) -> check_constraint cty
+@@ -430,21 +422,21 @@
+ check_constraint cl.cl_type;
+ (path, obj_init)
+
+-let rec transl_class_rebind_0 self obj_init cl =
++let rec transl_class_rebind_0 self obj_init cl vf =
+ match cl.cl_desc with
+ Tclass_let (rec_flag, defs, vals, cl) ->
+- let path, obj_init = transl_class_rebind_0 self obj_init cl in
++ let path, obj_init = transl_class_rebind_0 self obj_init cl vf in
+ (path, Translcore.transl_let rec_flag defs obj_init)
+ | _ ->
+- let path, obj_init = transl_class_rebind obj_init cl in
++ let path, obj_init = transl_class_rebind obj_init cl vf in
+ (path, lfunction [self] obj_init)
+
+-let transl_class_rebind ids cl =
++let transl_class_rebind ids cl vf =
+ try
+ let obj_init = Ident.create "obj_init"
+ and self = Ident.create "self" in
+ let obj_init0 = lapply (Lvar obj_init) [Lvar self] in
+- let path, obj_init' = transl_class_rebind_0 self obj_init0 cl in
++ let path, obj_init' = transl_class_rebind_0 self obj_init0 cl vf in
+ if not (Translcore.check_recursive_lambda ids obj_init') then
+ raise(Error(cl.cl_loc, Illegal_class_expr));
+ let id = (obj_init' = lfunction [self] obj_init0) in
+@@ -592,9 +584,9 @@
+ *)
+
+
+-let transl_class ids cl_id arity pub_meths cl =
++let transl_class ids cl_id arity pub_meths cl vflag =
+ (* First check if it is not only a rebind *)
+- let rebind = transl_class_rebind ids cl in
++ let rebind = transl_class_rebind ids cl vflag in
+ if rebind <> lambda_unit then rebind else
+
+ (* Prepare for heavy environment handling *)
+@@ -696,9 +688,7 @@
+ (* Simplest case: an object defined at toplevel (ids=[]) *)
+ if top && ids = [] then llets (ltable cla (ldirect obj_init)) else
+
+- let concrete =
+- ids = [] ||
+- Typeclass.virtual_methods (Ctype.signature_of_class_type cl.cl_type) = []
++ let concrete = (vflag = Concrete)
+ and lclass lam =
+ let cl_init = llets (Lfunction(Curried, [cla], cl_init)) in
+ Llet(Strict, class_init, cl_init, lam (free_variables cl_init))
+@@ -800,11 +790,11 @@
+
+ (* Wrapper for class compilation *)
+
+-let transl_class ids cl_id arity pub_meths cl =
+- oo_wrap cl.cl_env false (transl_class ids cl_id arity pub_meths) cl
++let transl_class ids cl_id arity pub_meths cl vf =
++ oo_wrap cl.cl_env false (transl_class ids cl_id arity pub_meths cl) vf
+
+ let () =
+- transl_object := (fun id meths cl -> transl_class [] id 0 meths cl)
++ transl_object := (fun id meths cl -> transl_class [] id 0 meths cl Concrete)
+
+ (* Error report *)
+
+Index: bytecomp/translclass.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/translclass.mli,v
+retrieving revision 1.11
+diff -u -r1.11 translclass.mli
+--- bytecomp/translclass.mli 12 Aug 2004 12:55:11 -0000 1.11
++++ bytecomp/translclass.mli 5 Apr 2006 02:26:00 -0000
+@@ -16,7 +16,8 @@
+ open Lambda
+
+ val transl_class :
+- Ident.t list -> Ident.t -> int -> string list -> class_expr -> lambda;;
++ Ident.t list -> Ident.t ->
++ int -> string list -> class_expr -> Asttypes.virtual_flag -> lambda;;
+
+ type error = Illegal_class_expr | Tags of string * string
+
+Index: bytecomp/translmod.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/bytecomp/translmod.ml,v
+retrieving revision 1.51
+diff -u -r1.51 translmod.ml
+--- bytecomp/translmod.ml 12 Aug 2004 12:55:11 -0000 1.51
++++ bytecomp/translmod.ml 5 Apr 2006 02:26:00 -0000
+@@ -317,10 +317,10 @@
+ | Tstr_open path :: rem ->
+ transl_structure fields cc rootpath rem
+ | Tstr_class cl_list :: rem ->
+- let ids = List.map (fun (i, _, _, _) -> i) cl_list in
++ let ids = List.map (fun (i, _, _, _, _) -> i) cl_list in
+ Lletrec(List.map
+- (fun (id, arity, meths, cl) ->
+- (id, transl_class ids id arity meths cl))
++ (fun (id, arity, meths, cl, vf) ->
++ (id, transl_class ids id arity meths cl vf))
+ cl_list,
+ transl_structure (List.rev ids @ fields) cc rootpath rem)
+ | Tstr_cltype cl_list :: rem ->
+@@ -414,11 +414,11 @@
+ | Tstr_open path :: rem ->
+ transl_store subst rem
+ | Tstr_class cl_list :: rem ->
+- let ids = List.map (fun (i, _, _, _) -> i) cl_list in
++ let ids = List.map (fun (i, _, _, _, _) -> i) cl_list in
+ let lam =
+ Lletrec(List.map
+- (fun (id, arity, meths, cl) ->
+- (id, transl_class ids id arity meths cl))
++ (fun (id, arity, meths, cl, vf) ->
++ (id, transl_class ids id arity meths cl vf))
+ cl_list,
+ store_idents ids) in
+ Lsequence(subst_lambda subst lam,
+@@ -485,7 +485,7 @@
+ | Tstr_modtype(id, decl) :: rem -> defined_idents rem
+ | Tstr_open path :: rem -> defined_idents rem
+ | Tstr_class cl_list :: rem ->
+- List.map (fun (i, _, _, _) -> i) cl_list @ defined_idents rem
++ List.map (fun (i, _, _, _, _) -> i) cl_list @ defined_idents rem
+ | Tstr_cltype cl_list :: rem -> defined_idents rem
+ | Tstr_include(modl, ids) :: rem -> ids @ defined_idents rem
+
+@@ -603,14 +603,14 @@
+ | Tstr_class cl_list ->
+ (* we need to use unique names for the classes because there might
+ be a value named identically *)
+- let ids = List.map (fun (i, _, _, _) -> i) cl_list in
++ let ids = List.map (fun (i, _, _, _, _) -> i) cl_list in
+ List.iter set_toplevel_unique_name ids;
+ Lletrec(List.map
+- (fun (id, arity, meths, cl) ->
+- (id, transl_class ids id arity meths cl))
++ (fun (id, arity, meths, cl, vf) ->
++ (id, transl_class ids id arity meths cl vf))
+ cl_list,
+ make_sequence
+- (fun (id, _, _, _) -> toploop_setvalue_id id)
++ (fun (id, _, _, _, _) -> toploop_setvalue_id id)
+ cl_list)
+ | Tstr_cltype cl_list ->
+ lambda_unit
+Index: driver/main_args.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/driver/main_args.ml,v
+retrieving revision 1.48
+diff -u -r1.48 main_args.ml
+--- driver/main_args.ml 4 Jan 2006 16:55:49 -0000 1.48
++++ driver/main_args.ml 5 Apr 2006 02:26:00 -0000
+@@ -136,11 +136,11 @@
+ \032 E/e enable/disable fragile match\n\
+ \032 F/f enable/disable partially applied function\n\
+ \032 L/l enable/disable labels omitted in application\n\
+- \032 M/m enable/disable overridden method\n\
++ \032 M/m enable/disable overridden methods\n\
+ \032 P/p enable/disable partial match\n\
+ \032 S/s enable/disable non-unit statement\n\
+ \032 U/u enable/disable unused match case\n\
+- \032 V/v enable/disable hidden instance variable\n\
++ \032 V/v enable/disable overridden instance variables\n\
+ \032 Y/y enable/disable suspicious unused variables\n\
+ \032 Z/z enable/disable all other unused variables\n\
+ \032 X/x enable/disable all other warnings\n\
+Index: driver/optmain.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/driver/optmain.ml,v
+retrieving revision 1.87
+diff -u -r1.87 optmain.ml
+--- driver/optmain.ml 4 Jan 2006 16:55:49 -0000 1.87
++++ driver/optmain.ml 5 Apr 2006 02:26:00 -0000
+@@ -173,7 +173,7 @@
+ \032 P/p enable/disable partial match\n\
+ \032 S/s enable/disable non-unit statement\n\
+ \032 U/u enable/disable unused match case\n\
+- \032 V/v enable/disable hidden instance variables\n\
++ \032 V/v enable/disable overridden instance variables\n\
+ \032 Y/y enable/disable suspicious unused variables\n\
+ \032 Z/z enable/disable all other unused variables\n\
+ \032 X/x enable/disable all other warnings\n\
+Index: stdlib/camlinternalOO.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/stdlib/camlinternalOO.ml,v
+retrieving revision 1.14
+diff -u -r1.14 camlinternalOO.ml
+--- stdlib/camlinternalOO.ml 25 Oct 2005 18:34:07 -0000 1.14
++++ stdlib/camlinternalOO.ml 5 Apr 2006 02:26:00 -0000
+@@ -206,7 +206,11 @@
+ (table.methods_by_name, table.methods_by_label, table.hidden_meths,
+ table.vars, virt_meth_labs, vars)
+ :: table.previous_states;
+- table.vars <- Vars.empty;
++ table.vars <-
++ Vars.fold
++ (fun lab info tvars ->
++ if List.mem lab vars then Vars.add lab info tvars else tvars)
++ table.vars Vars.empty;
+ let by_name = ref Meths.empty in
+ let by_label = ref Labs.empty in
+ List.iter2
+@@ -255,9 +259,11 @@
+ index
+
+ let new_variable table name =
+- let index = new_slot table in
+- table.vars <- Vars.add name index table.vars;
+- index
++ try Vars.find name table.vars
++ with Not_found ->
++ let index = new_slot table in
++ table.vars <- Vars.add name index table.vars;
++ index
+
+ let to_array arr =
+ if arr = Obj.magic 0 then [||] else arr
+@@ -265,16 +271,17 @@
+ let new_methods_variables table meths vals =
+ let meths = to_array meths in
+ let nmeths = Array.length meths and nvals = Array.length vals in
+- let index = new_variable table vals.(0) in
+- let res = Array.create (nmeths + 1) index in
+- for i = 1 to nvals - 1 do ignore (new_variable table vals.(i)) done;
++ let res = Array.create (nmeths + nvals) 0 in
+ for i = 0 to nmeths - 1 do
+- res.(i+1) <- get_method_label table meths.(i)
++ res.(i) <- get_method_label table meths.(i)
++ done;
++ for i = 0 to nvals - 1 do
++ res.(i+nmeths) <- new_variable table vals.(i)
+ done;
+ res
+
+ let get_variable table name =
+- Vars.find name table.vars
++ try Vars.find name table.vars with Not_found -> assert false
+
+ let get_variables table names =
+ Array.map (get_variable table) names
+@@ -315,9 +322,12 @@
+ let init =
+ if top then super cla env else Obj.repr (super cla) in
+ widen cla;
+- (init, Array.map (get_variable cla) (to_array vals),
+- Array.map (fun nm -> get_method cla (get_method_label cla nm))
+- (to_array concr_meths))
++ Array.concat
++ [[| repr init |];
++ magic (Array.map (get_variable cla) (to_array vals) : int array);
++ Array.map
++ (fun nm -> repr (get_method cla (get_method_label cla nm) : closure))
++ (to_array concr_meths) ]
+
+ let make_class pub_meths class_init =
+ let table = create_table pub_meths in
+Index: stdlib/camlinternalOO.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/stdlib/camlinternalOO.mli,v
+retrieving revision 1.9
+diff -u -r1.9 camlinternalOO.mli
+--- stdlib/camlinternalOO.mli 25 Oct 2005 18:34:07 -0000 1.9
++++ stdlib/camlinternalOO.mli 5 Apr 2006 02:26:00 -0000
+@@ -46,8 +46,7 @@
+ val init_class : table -> unit
+ val inherits :
+ table -> string array -> string array -> string array ->
+- (t * (table -> obj -> Obj.t) * t * obj) -> bool ->
+- (Obj.t * int array * closure array)
++ (t * (table -> obj -> Obj.t) * t * obj) -> bool -> Obj.t array
+ val make_class :
+ string array -> (table -> Obj.t -> t) ->
+ (t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t)
+@@ -79,6 +78,7 @@
+
+ (** {6 Builtins to reduce code size} *)
+
++(*
+ val get_const : t -> closure
+ val get_var : int -> closure
+ val get_env : int -> int -> closure
+@@ -103,6 +103,7 @@
+ val send_var : tag -> int -> int -> closure
+ val send_env : tag -> int -> int -> int -> closure
+ val send_meth : tag -> label -> int -> closure
++*)
+
+ type impl =
+ GetConst
+Index: stdlib/sys.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/stdlib/sys.ml,v
+retrieving revision 1.142
+diff -u -r1.142 sys.ml
+--- stdlib/sys.ml 22 Mar 2006 12:39:39 -0000 1.142
++++ stdlib/sys.ml 5 Apr 2006 02:26:00 -0000
+@@ -78,4 +78,4 @@
+
+ (* OCaml version string, must be in the format described in sys.mli. *)
+
+-let ocaml_version = "3.10+dev4 (2006-03-22)";;
++let ocaml_version = "3.10+dev5 (2006-04-05)";;
+Index: tools/depend.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/tools/depend.ml,v
+retrieving revision 1.9
+diff -u -r1.9 depend.ml
+--- tools/depend.ml 23 Mar 2005 03:08:37 -0000 1.9
++++ tools/depend.ml 5 Apr 2006 02:26:00 -0000
+@@ -87,7 +87,7 @@
+
+ and add_class_type_field bv = function
+ Pctf_inher cty -> add_class_type bv cty
+- | Pctf_val(_, _, oty, _) -> add_opt add_type bv oty
++ | Pctf_val(_, _, _, ty, _) -> add_type bv ty
+ | Pctf_virt(_, _, ty, _) -> add_type bv ty
+ | Pctf_meth(_, _, ty, _) -> add_type bv ty
+ | Pctf_cstr(ty1, ty2, _) -> add_type bv ty1; add_type bv ty2
+@@ -280,6 +280,7 @@
+ and add_class_field bv = function
+ Pcf_inher(ce, _) -> add_class_expr bv ce
+ | Pcf_val(_, _, e, _) -> add_expr bv e
++ | Pcf_valvirt(_, _, ty, _)
+ | Pcf_virt(_, _, ty, _) -> add_type bv ty
+ | Pcf_meth(_, _, e, _) -> add_expr bv e
+ | Pcf_cstr(ty1, ty2, _) -> add_type bv ty1; add_type bv ty2
+Index: tools/ocamlprof.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/tools/ocamlprof.ml,v
+retrieving revision 1.38
+diff -u -r1.38 ocamlprof.ml
+--- tools/ocamlprof.ml 24 Mar 2005 17:20:54 -0000 1.38
++++ tools/ocamlprof.ml 5 Apr 2006 02:26:00 -0000
+@@ -328,7 +328,7 @@
+ rewrite_patexp_list iflag spat_sexp_list
+ | Pcf_init sexp ->
+ rewrite_exp iflag sexp
+- | Pcf_virt _ | Pcf_cstr _ -> ()
++ | Pcf_valvirt _ | Pcf_virt _ | Pcf_cstr _ -> ()
+
+ and rewrite_class_expr iflag cexpr =
+ match cexpr.pcl_desc with
+Index: otherlibs/labltk/browser/searchpos.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/otherlibs/labltk/browser/searchpos.ml,v
+retrieving revision 1.48
+diff -u -r1.48 searchpos.ml
+--- otherlibs/labltk/browser/searchpos.ml 23 Mar 2005 03:08:37 -0000 1.48
++++ otherlibs/labltk/browser/searchpos.ml 5 Apr 2006 02:26:01 -0000
+@@ -141,9 +141,8 @@
+ List.iter cfl ~f:
+ begin function
+ Pctf_inher cty -> search_pos_class_type cty ~pos ~env
+- | Pctf_val (_, _, Some ty, loc) ->
++ | Pctf_val (_, _, _, ty, loc) ->
+ if in_loc loc ~pos then search_pos_type ty ~pos ~env
+- | Pctf_val _ -> ()
+ | Pctf_virt (_, _, ty, loc) ->
+ if in_loc loc ~pos then search_pos_type ty ~pos ~env
+ | Pctf_meth (_, _, ty, loc) ->
+@@ -675,7 +674,7 @@
+ | Tstr_modtype _ -> ()
+ | Tstr_open _ -> ()
+ | Tstr_class l ->
+- List.iter l ~f:(fun (id, _, _, cl) -> search_pos_class_expr cl ~pos)
++ List.iter l ~f:(fun (id, _, _, cl, _) -> search_pos_class_expr cl ~pos)
+ | Tstr_cltype _ -> ()
+ | Tstr_include (m, _) -> search_pos_module_expr m ~pos
+ end
+@@ -685,7 +684,8 @@
+ begin function
+ Cf_inher (cl, _, _) ->
+ search_pos_class_expr cl ~pos
+- | Cf_val (_, _, exp) -> search_pos_expr exp ~pos
++ | Cf_val (_, _, Some exp, _) -> search_pos_expr exp ~pos
++ | Cf_val _ -> ()
+ | Cf_meth (_, exp) -> search_pos_expr exp ~pos
+ | Cf_let (_, pel, iel) ->
+ List.iter pel ~f:
+Index: ocamldoc/Makefile
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/ocamldoc/Makefile,v
+retrieving revision 1.61
+diff -u -r1.61 Makefile
+--- ocamldoc/Makefile 4 Jan 2006 16:55:49 -0000 1.61
++++ ocamldoc/Makefile 5 Apr 2006 02:26:01 -0000
+@@ -31,7 +31,7 @@
+ MKDIR=mkdir -p
+ CP=cp -f
+ OCAMLDOC=ocamldoc
+-OCAMLDOC_RUN=sh ./runocamldoc $(SUPPORTS_SHARED_LIBRARIES)
++OCAMLDOC_RUN=./ocamldoc.opt #sh ./runocamldoc $(SUPPORTS_SHARED_LIBRARIES)
+ OCAMLDOC_OPT=$(OCAMLDOC).opt
+ OCAMLDOC_LIBCMA=odoc_info.cma
+ OCAMLDOC_LIBCMI=odoc_info.cmi
+@@ -188,12 +188,12 @@
+ ../otherlibs/num/num.mli
+
+ all: exe lib
+- $(MAKE) manpages
+
+ exe: $(OCAMLDOC)
+ lib: $(OCAMLDOC_LIBCMA) $(OCAMLDOC_LIBCMI) $(ODOC_TEST)
+
+ opt.opt: exeopt libopt
++ $(MAKE) manpages
+ exeopt: $(OCAMLDOC_OPT)
+ libopt: $(OCAMLDOC_LIBCMXA) $(OCAMLDOC_LIBCMI)
+ debug:
+Index: ocamldoc/odoc_ast.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/ocamldoc/odoc_ast.ml,v
+retrieving revision 1.27
+diff -u -r1.27 odoc_ast.ml
+--- ocamldoc/odoc_ast.ml 4 Jan 2006 16:55:49 -0000 1.27
++++ ocamldoc/odoc_ast.ml 5 Apr 2006 02:26:01 -0000
+@@ -88,7 +88,7 @@
+ ident_type_decl_list
+ | Typedtree.Tstr_class info_list ->
+ List.iter
+- (fun ((id,_,_,_) as ci) ->
++ (fun ((id,_,_,_,_) as ci) ->
+ Hashtbl.add table (C (Name.from_ident id))
+ (Typedtree.Tstr_class [ci]))
+ info_list
+@@ -146,7 +146,7 @@
+
+ let search_class_exp table name =
+ match Hashtbl.find table (C name) with
+- | (Typedtree.Tstr_class [(_,_,_,ce)]) ->
++ | (Typedtree.Tstr_class [(_,_,_,ce,_)]) ->
+ (
+ try
+ let type_decl = search_type_declaration table name in
+@@ -184,7 +184,7 @@
+ let rec iter = function
+ | [] ->
+ raise Not_found
+- | Typedtree.Cf_val (_, ident, exp) :: q
++ | Typedtree.Cf_val (_, ident, Some exp, _) :: q
+ when Name.from_ident ident = name ->
+ exp.Typedtree.exp_type
+ | _ :: q ->
+@@ -523,7 +523,8 @@
+ p_clexp.Parsetree.pcl_loc.Location.loc_end.Lexing.pos_cnum
+ q
+
+- | (Parsetree.Pcf_val (label, mutable_flag, expression, loc)) :: q ->
++ | (Parsetree.Pcf_val (label, mutable_flag, _, loc) |
++ Parsetree.Pcf_valvirt (label, mutable_flag, _, loc)) :: q ->
+ let complete_name = Name.concat current_class_name label in
+ let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let type_exp =
+Index: ocamldoc/odoc_sig.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/ocamldoc/odoc_sig.ml,v
+retrieving revision 1.37
+diff -u -r1.37 odoc_sig.ml
+--- ocamldoc/odoc_sig.ml 4 Jan 2006 16:55:50 -0000 1.37
++++ ocamldoc/odoc_sig.ml 5 Apr 2006 02:26:01 -0000
+@@ -107,7 +107,7 @@
+ | _ -> assert false
+
+ let search_attribute_type name class_sig =
+- let (_, type_expr) = Types.Vars.find name class_sig.Types.cty_vars in
++ let (_, _, type_expr) = Types.Vars.find name class_sig.Types.cty_vars in
+ type_expr
+
+ let search_method_type name class_sig =
+@@ -269,7 +269,7 @@
+ [] -> pos_limit
+ | ele2 :: _ ->
+ match ele2 with
+- Parsetree.Pctf_val (_, _, _, loc)
++ Parsetree.Pctf_val (_, _, _, _, loc)
+ | Parsetree.Pctf_virt (_, _, _, loc)
+ | Parsetree.Pctf_meth (_, _, _, loc)
+ | Parsetree.Pctf_cstr (_, _, loc) -> loc.Location.loc_start.Lexing.pos_cnum
+@@ -330,7 +330,7 @@
+ in
+ ([], ele_comments)
+
+- | Parsetree.Pctf_val (name, mutable_flag, _, loc) :: q ->
++ | Parsetree.Pctf_val (name, mutable_flag, _, _, loc) :: q ->
+ (* of (string * mutable_flag * core_type option * Location.t)*)
+ let (comment_opt, eles_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let complete_name = Name.concat current_class_name name in
+Index: camlp4/camlp4/ast2pt.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/camlp4/ast2pt.ml,v
+retrieving revision 1.36
+diff -u -r1.36 ast2pt.ml
+--- camlp4/camlp4/ast2pt.ml 29 Jun 2005 04:11:26 -0000 1.36
++++ camlp4/camlp4/ast2pt.ml 5 Apr 2006 02:26:01 -0000
+@@ -244,6 +244,7 @@
+ ;
+ value mkmutable m = if m then Mutable else Immutable;
+ value mkprivate m = if m then Private else Public;
++value mkvirtual m = if m then Virtual else Concrete;
+ value mktrecord (loc, n, m, t) =
+ (n, mkmutable m, ctyp (mkpolytype t), mkloc loc);
+ value mkvariant (loc, c, tl) = (c, List.map ctyp tl, mkloc loc);
+@@ -862,8 +863,8 @@
+ | CgInh loc ct -> [Pctf_inher (class_type ct) :: l]
+ | CgMth loc s pf t ->
+ [Pctf_meth (s, mkprivate pf, ctyp (mkpolytype t), mkloc loc) :: l]
+- | CgVal loc s b t ->
+- [Pctf_val (s, mkmutable b, Some (ctyp t), mkloc loc) :: l]
++ | CgVal loc s b v t ->
++ [Pctf_val (s, mkmutable b, mkvirtual v, ctyp t, mkloc loc) :: l]
+ | CgVir loc s b t ->
+ [Pctf_virt (s, mkprivate b, ctyp (mkpolytype t), mkloc loc) :: l] ]
+ and class_expr =
+@@ -907,7 +908,9 @@
+ [Pcf_meth (s, mkprivate b, e, mkloc loc) :: l]
+ | CrVal loc s b e -> [Pcf_val (s, mkmutable b, expr e, mkloc loc) :: l]
+ | CrVir loc s b t ->
+- [Pcf_virt (s, mkprivate b, ctyp (mkpolytype t), mkloc loc) :: l] ]
++ [Pcf_virt (s, mkprivate b, ctyp (mkpolytype t), mkloc loc) :: l]
++ | CrVvr loc s b t ->
++ [Pcf_valvirt (s, mkmutable b, ctyp t, mkloc loc) :: l] ]
+ ;
+
+ value interf ast = List.fold_right sig_item ast [];
+Index: camlp4/camlp4/mLast.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/camlp4/mLast.mli,v
+retrieving revision 1.18
+diff -u -r1.18 mLast.mli
+--- camlp4/camlp4/mLast.mli 29 Jun 2005 04:11:26 -0000 1.18
++++ camlp4/camlp4/mLast.mli 5 Apr 2006 02:26:01 -0000
+@@ -180,7 +180,7 @@
+ | CgDcl of loc and list class_sig_item
+ | CgInh of loc and class_type
+ | CgMth of loc and string and bool and ctyp
+- | CgVal of loc and string and bool and ctyp
++ | CgVal of loc and string and bool and bool and ctyp
+ | CgVir of loc and string and bool and ctyp ]
+ and class_expr =
+ [ CeApp of loc and class_expr and expr
+@@ -196,7 +196,8 @@
+ | CrIni of loc and expr
+ | CrMth of loc and string and bool and expr and option ctyp
+ | CrVal of loc and string and bool and expr
+- | CrVir of loc and string and bool and ctyp ]
++ | CrVir of loc and string and bool and ctyp
++ | CrVvr of loc and string and bool and ctyp ]
+ ;
+
+ external loc_of_ctyp : ctyp -> loc = "%field0";
+Index: camlp4/camlp4/reloc.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/camlp4/reloc.ml,v
+retrieving revision 1.18
+diff -u -r1.18 reloc.ml
+--- camlp4/camlp4/reloc.ml 29 Jun 2005 04:11:26 -0000 1.18
++++ camlp4/camlp4/reloc.ml 5 Apr 2006 02:26:01 -0000
+@@ -350,7 +350,7 @@
+ | CgDcl loc x1 -> let nloc = floc loc in CgDcl nloc (List.map (class_sig_item floc sh) x1)
+ | CgInh loc x1 -> let nloc = floc loc in CgInh nloc (class_type floc sh x1)
+ | CgMth loc x1 x2 x3 -> let nloc = floc loc in CgMth nloc x1 x2 (ctyp floc sh x3)
+- | CgVal loc x1 x2 x3 -> let nloc = floc loc in CgVal nloc x1 x2 (ctyp floc sh x3)
++ | CgVal loc x1 x2 x3 x4 -> let nloc = floc loc in CgVal nloc x1 x2 x3 (ctyp floc sh x4)
+ | CgVir loc x1 x2 x3 -> let nloc = floc loc in CgVir nloc x1 x2 (ctyp floc sh x3) ]
+ and class_expr floc sh =
+ self where rec self =
+@@ -377,5 +377,6 @@
+ | CrMth loc x1 x2 x3 x4 ->
+ let nloc = floc loc in CrMth nloc x1 x2 (expr floc sh x3) (option_map (ctyp floc sh) x4)
+ | CrVal loc x1 x2 x3 -> let nloc = floc loc in CrVal nloc x1 x2 (expr floc sh x3)
+- | CrVir loc x1 x2 x3 -> let nloc = floc loc in CrVir nloc x1 x2 (ctyp floc sh x3) ]
++ | CrVir loc x1 x2 x3 -> let nloc = floc loc in CrVir nloc x1 x2 (ctyp floc sh x3)
++ | CrVvr loc x1 x2 x3 -> let nloc = floc loc in CrVvr nloc x1 x2 (ctyp floc sh x3) ]
+ ;
+Index: camlp4/etc/pa_o.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/etc/pa_o.ml,v
+retrieving revision 1.66
+diff -u -r1.66 pa_o.ml
+--- camlp4/etc/pa_o.ml 29 Jun 2005 04:11:26 -0000 1.66
++++ camlp4/etc/pa_o.ml 5 Apr 2006 02:26:01 -0000
+@@ -1037,8 +1037,14 @@
+ class_str_item:
+ [ [ "inherit"; ce = class_expr; pb = OPT [ "as"; i = LIDENT -> i ] ->
+ <:class_str_item< inherit $ce$ $opt:pb$ >>
+- | "val"; mf = OPT "mutable"; lab = label; e = cvalue_binding ->
+- <:class_str_item< value $opt:o2b mf$ $lab$ = $e$ >>
++ | "val"; "mutable"; lab = label; e = cvalue_binding ->
++ <:class_str_item< value mutable $lab$ = $e$ >>
++ | "val"; lab = label; e = cvalue_binding ->
++ <:class_str_item< value $lab$ = $e$ >>
++ | "val"; "mutable"; "virtual"; lab = label; ":"; t = ctyp ->
++ <:class_str_item< value virtual mutable $lab$ : $t$ >>
++ | "val"; "virtual"; mf = OPT "mutable"; lab = label; ":"; t = ctyp ->
++ <:class_str_item< value virtual $opt:o2b mf$ $lab$ : $t$ >>
+ | "method"; "private"; "virtual"; l = label; ":"; t = poly_type ->
+ <:class_str_item< method virtual private $l$ : $t$ >>
+ | "method"; "virtual"; "private"; l = label; ":"; t = poly_type ->
+@@ -1087,8 +1093,9 @@
+ ;
+ class_sig_item:
+ [ [ "inherit"; cs = class_signature -> <:class_sig_item< inherit $cs$ >>
+- | "val"; mf = OPT "mutable"; l = label; ":"; t = ctyp ->
+- <:class_sig_item< value $opt:o2b mf$ $l$ : $t$ >>
++ | "val"; mf = OPT "mutable"; vf = OPT "virtual";
++ l = label; ":"; t = ctyp ->
++ <:class_sig_item< value $opt:o2b mf$ $opt:o2b vf$ $l$ : $t$ >>
+ | "method"; "private"; "virtual"; l = label; ":"; t = poly_type ->
+ <:class_sig_item< method virtual private $l$ : $t$ >>
+ | "method"; "virtual"; "private"; l = label; ":"; t = poly_type ->
+Index: camlp4/etc/pr_o.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/etc/pr_o.ml,v
+retrieving revision 1.51
+diff -u -r1.51 pr_o.ml
+--- camlp4/etc/pr_o.ml 5 Jan 2006 10:44:29 -0000 1.51
++++ camlp4/etc/pr_o.ml 5 Apr 2006 02:26:01 -0000
+@@ -1768,10 +1768,11 @@
+ [: `S LR "method"; private_flag pf; `label lab;
+ `S LR ":" :];
+ `ctyp t "" k :]
+- | MLast.CgVal _ lab mf t ->
++ | MLast.CgVal _ lab mf vf t ->
+ fun curr next dg k ->
+ [: `HVbox
+- [: `S LR "val"; mutable_flag mf; `label lab; `S LR ":" :];
++ [: `S LR "val"; mutable_flag mf; virtual_flag vf;
++ `label lab; `S LR ":" :];
+ `ctyp t "" k :]
+ | MLast.CgVir _ lab pf t ->
+ fun curr next dg k ->
+Index: camlp4/meta/pa_r.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/meta/pa_r.ml,v
+retrieving revision 1.64
+diff -u -r1.64 pa_r.ml
+--- camlp4/meta/pa_r.ml 29 Jun 2005 04:11:26 -0000 1.64
++++ camlp4/meta/pa_r.ml 5 Apr 2006 02:26:01 -0000
+@@ -658,7 +658,9 @@
+ | "inherit"; ce = class_expr; pb = OPT as_lident ->
+ <:class_str_item< inherit $ce$ $opt:pb$ >>
+ | "value"; mf = OPT "mutable"; lab = label; e = cvalue_binding ->
+- <:class_str_item< value $opt:o2b mf$ $lab$ = $e$ >>
++ <:class_str_item< value $opt:o2b mf$ $lab$ = $e$ >>
++ | "value"; "virtual"; mf = OPT "mutable"; l = label; ":"; t = ctyp ->
++ <:class_str_item< value virtual $opt:o2b mf$ $l$ : $t$ >>
+ | "method"; "virtual"; pf = OPT "private"; l = label; ":"; t = ctyp ->
+ <:class_str_item< method virtual $opt:o2b pf$ $l$ : $t$ >>
+ | "method"; pf = OPT "private"; l = label; topt = OPT polyt;
+@@ -701,8 +703,9 @@
+ [ [ "declare"; st = LIST0 [ s = class_sig_item; ";" -> s ]; "end" ->
+ <:class_sig_item< declare $list:st$ end >>
+ | "inherit"; cs = class_type -> <:class_sig_item< inherit $cs$ >>
+- | "value"; mf = OPT "mutable"; l = label; ":"; t = ctyp ->
+- <:class_sig_item< value $opt:o2b mf$ $l$ : $t$ >>
++ | "value"; mf = OPT "mutable"; vf = OPT "virtual";
++ l = label; ":"; t = ctyp ->
++ <:class_sig_item< value $opt:o2b mf$ $opt:o2b vf$ $l$ : $t$ >>
+ | "method"; "virtual"; pf = OPT "private"; l = label; ":"; t = ctyp ->
+ <:class_sig_item< method virtual $opt:o2b pf$ $l$ : $t$ >>
+ | "method"; pf = OPT "private"; l = label; ":"; t = ctyp ->
+Index: camlp4/meta/q_MLast.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/meta/q_MLast.ml,v
+retrieving revision 1.60
+diff -u -r1.60 q_MLast.ml
+--- camlp4/meta/q_MLast.ml 29 Jun 2005 04:11:26 -0000 1.60
++++ camlp4/meta/q_MLast.ml 5 Apr 2006 02:26:01 -0000
+@@ -947,6 +947,8 @@
+ Qast.Node "CrDcl" [Qast.Loc; st]
+ | "inherit"; ce = class_expr; pb = SOPT as_lident ->
+ Qast.Node "CrInh" [Qast.Loc; ce; pb]
++ | "value"; "virtual"; mf = SOPT "mutable"; l = label; ":"; t = ctyp ->
++ Qast.Node "CrVvr" [Qast.Loc; l; o2b mf; t]
+ | "value"; mf = SOPT "mutable"; lab = label; e = cvalue_binding ->
+ Qast.Node "CrVal" [Qast.Loc; lab; o2b mf; e]
+ | "method"; "virtual"; pf = SOPT "private"; l = label; ":"; t = ctyp ->
+@@ -992,8 +994,9 @@
+ [ [ "declare"; st = SLIST0 [ s = class_sig_item; ";" -> s ]; "end" ->
+ Qast.Node "CgDcl" [Qast.Loc; st]
+ | "inherit"; cs = class_type -> Qast.Node "CgInh" [Qast.Loc; cs]
+- | "value"; mf = SOPT "mutable"; l = label; ":"; t = ctyp ->
+- Qast.Node "CgVal" [Qast.Loc; l; o2b mf; t]
++ | "value"; mf = SOPT "mutable"; vf = SOPT "virtual";
++ l = label; ":"; t = ctyp ->
++ Qast.Node "CgVal" [Qast.Loc; l; o2b mf; o2b vf; t]
+ | "method"; "virtual"; pf = SOPT "private"; l = label; ":"; t = ctyp ->
+ Qast.Node "CgVir" [Qast.Loc; l; o2b pf; t]
+ | "method"; pf = SOPT "private"; l = label; ":"; t = ctyp ->
+Index: camlp4/ocaml_src/camlp4/ast2pt.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/ocaml_src/camlp4/ast2pt.ml,v
+retrieving revision 1.36
+diff -u -r1.36 ast2pt.ml
+--- camlp4/ocaml_src/camlp4/ast2pt.ml 29 Jun 2005 04:11:26 -0000 1.36
++++ camlp4/ocaml_src/camlp4/ast2pt.ml 5 Apr 2006 02:26:01 -0000
+@@ -227,6 +227,7 @@
+ ;;
+ let mkmutable m = if m then Mutable else Immutable;;
+ let mkprivate m = if m then Private else Public;;
++let mkvirtual m = if m then Virtual else Concrete;;
+ let mktrecord (loc, n, m, t) =
+ n, mkmutable m, ctyp (mkpolytype t), mkloc loc
+ ;;
+@@ -878,8 +879,8 @@
+ | CgInh (loc, ct) -> Pctf_inher (class_type ct) :: l
+ | CgMth (loc, s, pf, t) ->
+ Pctf_meth (s, mkprivate pf, ctyp (mkpolytype t), mkloc loc) :: l
+- | CgVal (loc, s, b, t) ->
+- Pctf_val (s, mkmutable b, Some (ctyp t), mkloc loc) :: l
++ | CgVal (loc, s, b, v, t) ->
++ Pctf_val (s, mkmutable b, mkvirtual v, ctyp t, mkloc loc) :: l
+ | CgVir (loc, s, b, t) ->
+ Pctf_virt (s, mkprivate b, ctyp (mkpolytype t), mkloc loc) :: l
+ and class_expr =
+@@ -923,6 +924,8 @@
+ | CrVal (loc, s, b, e) -> Pcf_val (s, mkmutable b, expr e, mkloc loc) :: l
+ | CrVir (loc, s, b, t) ->
+ Pcf_virt (s, mkprivate b, ctyp (mkpolytype t), mkloc loc) :: l
++ | CrVvr (loc, s, b, t) ->
++ Pcf_valvirt (s, mkmutable b, ctyp t, mkloc loc) :: l
+ ;;
+
+ let interf ast = List.fold_right sig_item ast [];;
+Index: camlp4/ocaml_src/camlp4/mLast.mli
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/ocaml_src/camlp4/mLast.mli,v
+retrieving revision 1.20
+diff -u -r1.20 mLast.mli
+--- camlp4/ocaml_src/camlp4/mLast.mli 29 Jun 2005 04:11:26 -0000 1.20
++++ camlp4/ocaml_src/camlp4/mLast.mli 5 Apr 2006 02:26:01 -0000
+@@ -180,7 +180,7 @@
+ | CgDcl of loc * class_sig_item list
+ | CgInh of loc * class_type
+ | CgMth of loc * string * bool * ctyp
+- | CgVal of loc * string * bool * ctyp
++ | CgVal of loc * string * bool * bool * ctyp
+ | CgVir of loc * string * bool * ctyp
+ and class_expr =
+ CeApp of loc * class_expr * expr
+@@ -197,6 +197,7 @@
+ | CrMth of loc * string * bool * expr * ctyp option
+ | CrVal of loc * string * bool * expr
+ | CrVir of loc * string * bool * ctyp
++ | CrVvr of loc * string * bool * ctyp
+ ;;
+
+ external loc_of_ctyp : ctyp -> loc = "%field0";;
+Index: camlp4/ocaml_src/camlp4/reloc.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/ocaml_src/camlp4/reloc.ml,v
+retrieving revision 1.20
+diff -u -r1.20 reloc.ml
+--- camlp4/ocaml_src/camlp4/reloc.ml 29 Jun 2005 04:11:26 -0000 1.20
++++ camlp4/ocaml_src/camlp4/reloc.ml 5 Apr 2006 02:26:01 -0000
+@@ -430,8 +430,8 @@
+ let nloc = floc loc in CgInh (nloc, class_type floc sh x1)
+ | CgMth (loc, x1, x2, x3) ->
+ let nloc = floc loc in CgMth (nloc, x1, x2, ctyp floc sh x3)
+- | CgVal (loc, x1, x2, x3) ->
+- let nloc = floc loc in CgVal (nloc, x1, x2, ctyp floc sh x3)
++ | CgVal (loc, x1, x2, x3, x4) ->
++ let nloc = floc loc in CgVal (nloc, x1, x2, x3, ctyp floc sh x4)
+ | CgVir (loc, x1, x2, x3) ->
+ let nloc = floc loc in CgVir (nloc, x1, x2, ctyp floc sh x3)
+ in
+@@ -478,6 +478,8 @@
+ let nloc = floc loc in CrVal (nloc, x1, x2, expr floc sh x3)
+ | CrVir (loc, x1, x2, x3) ->
+ let nloc = floc loc in CrVir (nloc, x1, x2, ctyp floc sh x3)
++ | CrVvr (loc, x1, x2, x3) ->
++ let nloc = floc loc in CrVvr (nloc, x1, x2, ctyp floc sh x3)
+ in
+ self
+ ;;
+Index: camlp4/ocaml_src/meta/pa_r.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/ocaml_src/meta/pa_r.ml,v
+retrieving revision 1.59
+diff -u -r1.59 pa_r.ml
+--- camlp4/ocaml_src/meta/pa_r.ml 29 Jun 2005 04:11:26 -0000 1.59
++++ camlp4/ocaml_src/meta/pa_r.ml 5 Apr 2006 02:26:01 -0000
+@@ -2161,6 +2161,15 @@
+ (fun (t : 'ctyp) _ (l : 'label) (pf : string option) _ _
+ (_loc : Lexing.position * Lexing.position) ->
+ (MLast.CrVir (_loc, l, o2b pf, t) : 'class_str_item));
++ [Gramext.Stoken ("", "value"); Gramext.Stoken ("", "virtual");
++ Gramext.Sopt (Gramext.Stoken ("", "mutable"));
++ Gramext.Snterm (Grammar.Entry.obj (label : 'label Grammar.Entry.e));
++ Gramext.Stoken ("", ":");
++ Gramext.Snterm (Grammar.Entry.obj (ctyp : 'ctyp Grammar.Entry.e))],
++ Gramext.action
++ (fun (t : 'ctyp) _ (l : 'label) (mf : string option) _ _
++ (_loc : Lexing.position * Lexing.position) ->
++ (MLast.CrVvr (_loc, l, o2b mf, t) : 'class_str_item));
+ [Gramext.Stoken ("", "value");
+ Gramext.Sopt (Gramext.Stoken ("", "mutable"));
+ Gramext.Snterm (Grammar.Entry.obj (label : 'label Grammar.Entry.e));
+@@ -2338,13 +2347,15 @@
+ (MLast.CgVir (_loc, l, o2b pf, t) : 'class_sig_item));
+ [Gramext.Stoken ("", "value");
+ Gramext.Sopt (Gramext.Stoken ("", "mutable"));
++ Gramext.Sopt (Gramext.Stoken ("", "virtual"));
+ Gramext.Snterm (Grammar.Entry.obj (label : 'label Grammar.Entry.e));
+ Gramext.Stoken ("", ":");
+ Gramext.Snterm (Grammar.Entry.obj (ctyp : 'ctyp Grammar.Entry.e))],
+ Gramext.action
+- (fun (t : 'ctyp) _ (l : 'label) (mf : string option) _
++ (fun (t : 'ctyp) _ (l : 'label) (vf : string option)
++ (mf : string option) _
+ (_loc : Lexing.position * Lexing.position) ->
+- (MLast.CgVal (_loc, l, o2b mf, t) : 'class_sig_item));
++ (MLast.CgVal (_loc, l, o2b mf, o2b vf, t) : 'class_sig_item));
+ [Gramext.Stoken ("", "inherit");
+ Gramext.Snterm
+ (Grammar.Entry.obj (class_type : 'class_type Grammar.Entry.e))],
+Index: camlp4/ocaml_src/meta/q_MLast.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/ocaml_src/meta/q_MLast.ml,v
+retrieving revision 1.65
+diff -u -r1.65 q_MLast.ml
+--- camlp4/ocaml_src/meta/q_MLast.ml 12 Jan 2006 08:54:21 -0000 1.65
++++ camlp4/ocaml_src/meta/q_MLast.ml 5 Apr 2006 02:26:01 -0000
+@@ -3152,9 +3152,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__17))])],
++ (Qast.Str x : 'e__18))])],
+ Gramext.action
+- (fun (a : 'e__17 option)
++ (fun (a : 'e__18 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3191,9 +3191,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__16))])],
++ (Qast.Str x : 'e__17))])],
+ Gramext.action
+- (fun (a : 'e__16 option)
++ (fun (a : 'e__17 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3216,9 +3216,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__15))])],
++ (Qast.Str x : 'e__16))])],
+ Gramext.action
+- (fun (a : 'e__15 option)
++ (fun (a : 'e__16 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3235,6 +3235,31 @@
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Node ("CrVal", [Qast.Loc; lab; o2b mf; e]) :
+ 'class_str_item));
++ [Gramext.Stoken ("", "value"); Gramext.Stoken ("", "virtual");
++ Gramext.srules
++ [[Gramext.Sopt
++ (Gramext.srules
++ [[Gramext.Stoken ("", "mutable")],
++ Gramext.action
++ (fun (x : string)
++ (_loc : Lexing.position * Lexing.position) ->
++ (Qast.Str x : 'e__15))])],
++ Gramext.action
++ (fun (a : 'e__15 option)
++ (_loc : Lexing.position * Lexing.position) ->
++ (Qast.Option a : 'a_opt));
++ [Gramext.Snterm
++ (Grammar.Entry.obj (a_opt : 'a_opt Grammar.Entry.e))],
++ Gramext.action
++ (fun (a : 'a_opt) (_loc : Lexing.position * Lexing.position) ->
++ (a : 'a_opt))];
++ Gramext.Snterm (Grammar.Entry.obj (label : 'label Grammar.Entry.e));
++ Gramext.Stoken ("", ":");
++ Gramext.Snterm (Grammar.Entry.obj (ctyp : 'ctyp Grammar.Entry.e))],
++ Gramext.action
++ (fun (t : 'ctyp) _ (l : 'label) (mf : 'a_opt) _ _
++ (_loc : Lexing.position * Lexing.position) ->
++ (Qast.Node ("CrVvr", [Qast.Loc; l; o2b mf; t]) : 'class_str_item));
+ [Gramext.Stoken ("", "inherit");
+ Gramext.Snterm
+ (Grammar.Entry.obj (class_expr : 'class_expr Grammar.Entry.e));
+@@ -3366,9 +3391,9 @@
+ Gramext.action
+ (fun _ (csf : 'class_sig_item)
+ (_loc : Lexing.position * Lexing.position) ->
+- (csf : 'e__18))])],
++ (csf : 'e__19))])],
+ Gramext.action
+- (fun (a : 'e__18 list)
++ (fun (a : 'e__19 list)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.List a : 'a_list));
+ [Gramext.Snterm
+@@ -3446,9 +3471,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__22))])],
++ (Qast.Str x : 'e__24))])],
+ Gramext.action
+- (fun (a : 'e__22 option)
++ (fun (a : 'e__24 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3471,9 +3496,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__21))])],
++ (Qast.Str x : 'e__23))])],
+ Gramext.action
+- (fun (a : 'e__21 option)
++ (fun (a : 'e__23 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3496,9 +3521,26 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__20))])],
++ (Qast.Str x : 'e__21))])],
+ Gramext.action
+- (fun (a : 'e__20 option)
++ (fun (a : 'e__21 option)
++ (_loc : Lexing.position * Lexing.position) ->
++ (Qast.Option a : 'a_opt));
++ [Gramext.Snterm
++ (Grammar.Entry.obj (a_opt : 'a_opt Grammar.Entry.e))],
++ Gramext.action
++ (fun (a : 'a_opt) (_loc : Lexing.position * Lexing.position) ->
++ (a : 'a_opt))];
++ Gramext.srules
++ [[Gramext.Sopt
++ (Gramext.srules
++ [[Gramext.Stoken ("", "virtual")],
++ Gramext.action
++ (fun (x : string)
++ (_loc : Lexing.position * Lexing.position) ->
++ (Qast.Str x : 'e__22))])],
++ Gramext.action
++ (fun (a : 'e__22 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3510,9 +3552,10 @@
+ Gramext.Stoken ("", ":");
+ Gramext.Snterm (Grammar.Entry.obj (ctyp : 'ctyp Grammar.Entry.e))],
+ Gramext.action
+- (fun (t : 'ctyp) _ (l : 'label) (mf : 'a_opt) _
++ (fun (t : 'ctyp) _ (l : 'label) (vf : 'a_opt) (mf : 'a_opt) _
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Node ("CgVal", [Qast.Loc; l; o2b mf; t]) : 'class_sig_item));
++ (Qast.Node ("CgVal", [Qast.Loc; l; o2b mf; o2b vf; t]) :
++ 'class_sig_item));
+ [Gramext.Stoken ("", "inherit");
+ Gramext.Snterm
+ (Grammar.Entry.obj (class_type : 'class_type Grammar.Entry.e))],
+@@ -3531,9 +3574,9 @@
+ Gramext.action
+ (fun _ (s : 'class_sig_item)
+ (_loc : Lexing.position * Lexing.position) ->
+- (s : 'e__19))])],
++ (s : 'e__20))])],
+ Gramext.action
+- (fun (a : 'e__19 list)
++ (fun (a : 'e__20 list)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.List a : 'a_list));
+ [Gramext.Snterm
+@@ -3556,9 +3599,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__23))])],
++ (Qast.Str x : 'e__25))])],
+ Gramext.action
+- (fun (a : 'e__23 option)
++ (fun (a : 'e__25 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3593,9 +3636,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__24))])],
++ (Qast.Str x : 'e__26))])],
+ Gramext.action
+- (fun (a : 'e__24 option)
++ (fun (a : 'e__26 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3713,9 +3756,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__25))])],
++ (Qast.Str x : 'e__27))])],
+ Gramext.action
+- (fun (a : 'e__25 option)
++ (fun (a : 'e__27 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -3922,9 +3965,9 @@
+ Gramext.action
+ (fun (x : string)
+ (_loc : Lexing.position * Lexing.position) ->
+- (Qast.Str x : 'e__26))])],
++ (Qast.Str x : 'e__28))])],
+ Gramext.action
+- (fun (a : 'e__26 option)
++ (fun (a : 'e__28 option)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.Option a : 'a_opt));
+ [Gramext.Snterm
+@@ -4390,9 +4433,9 @@
+ Gramext.action
+ (fun _ (e : 'expr)
+ (_loc : Lexing.position * Lexing.position) ->
+- (e : 'e__29))])],
++ (e : 'e__31))])],
+ Gramext.action
+- (fun (a : 'e__29 list)
++ (fun (a : 'e__31 list)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.List a : 'a_list));
+ [Gramext.Snterm
+@@ -4425,9 +4468,9 @@
+ Gramext.action
+ (fun _ (e : 'expr)
+ (_loc : Lexing.position * Lexing.position) ->
+- (e : 'e__28))])],
++ (e : 'e__30))])],
+ Gramext.action
+- (fun (a : 'e__28 list)
++ (fun (a : 'e__30 list)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.List a : 'a_list));
+ [Gramext.Snterm
+@@ -4454,9 +4497,9 @@
+ Gramext.action
+ (fun _ (e : 'expr)
+ (_loc : Lexing.position * Lexing.position) ->
+- (e : 'e__27))])],
++ (e : 'e__29))])],
+ Gramext.action
+- (fun (a : 'e__27 list)
++ (fun (a : 'e__29 list)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.List a : 'a_list));
+ [Gramext.Snterm
+@@ -4547,9 +4590,9 @@
+ Gramext.action
+ (fun _ (cf : 'class_str_item)
+ (_loc : Lexing.position * Lexing.position) ->
+- (cf : 'e__30))])],
++ (cf : 'e__32))])],
+ Gramext.action
+- (fun (a : 'e__30 list)
++ (fun (a : 'e__32 list)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.List a : 'a_list));
+ [Gramext.Snterm
+@@ -4592,9 +4635,9 @@
+ Gramext.action
+ (fun _ (csf : 'class_sig_item)
+ (_loc : Lexing.position * Lexing.position) ->
+- (csf : 'e__32))])],
++ (csf : 'e__34))])],
+ Gramext.action
+- (fun (a : 'e__32 list)
++ (fun (a : 'e__34 list)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.List a : 'a_list));
+ [Gramext.Snterm
+@@ -4623,9 +4666,9 @@
+ Gramext.action
+ (fun _ (csf : 'class_sig_item)
+ (_loc : Lexing.position * Lexing.position) ->
+- (csf : 'e__31))])],
++ (csf : 'e__33))])],
+ Gramext.action
+- (fun (a : 'e__31 list)
++ (fun (a : 'e__33 list)
+ (_loc : Lexing.position * Lexing.position) ->
+ (Qast.List a : 'a_list));
+ [Gramext.Snterm
+Index: camlp4/top/rprint.ml
+===================================================================
+RCS file: /net/yquem/devel/caml/repository/csl/camlp4/top/rprint.ml,v
+retrieving revision 1.18
+diff -u -r1.18 rprint.ml
+--- camlp4/top/rprint.ml 29 Jun 2005 04:11:26 -0000 1.18
++++ camlp4/top/rprint.ml 5 Apr 2006 02:26:01 -0000
+@@ -288,8 +288,9 @@
+ fprintf ppf "@[<2>method %s%s%s :@ %a;@]"
+ (if priv then "private " else "") (if virt then "virtual " else "")
+ name Toploop.print_out_type.val ty
+- | Ocsg_value name mut ty ->
+- fprintf ppf "@[<2>value %s%s :@ %a;@]" (if mut then "mutable " else "")
++ | Ocsg_value name mut virt ty ->
++ fprintf ppf "@[<2>value %s%s%s :@ %a;@]"
++ (if mut then "mutable " else "") (if virt then "virtual " else "")
+ name Toploop.print_out_type.val ty ]
+ ;
+
diff --git a/experimental/garrigue/variable-names-Tvar.diff b/experimental/garrigue/variable-names-Tvar.diff
new file mode 100644
index 0000000000..99ff6a2475
--- /dev/null
+++ b/experimental/garrigue/variable-names-Tvar.diff
@@ -0,0 +1,1656 @@
+Index: VERSION
+===================================================================
+--- VERSION (リビジョン 11207)
++++ VERSION (作業コピー)
+@@ -1,4 +1,4 @@
+-3.13.0+dev6 (2011-07-29)
++3.13.0+dev7 (2011-09-22)
+
+ # The version string is the first line of this file.
+ # It must be in the format described in stdlib/sys.mli
+Index: typing/typemod.ml
+===================================================================
+--- typing/typemod.ml (リビジョン 11207)
++++ typing/typemod.ml (作業コピー)
+@@ -764,7 +764,7 @@
+ Location.prerr_warning smod.pmod_loc
+ (Warnings.Not_principal "this module unpacking");
+ modtype_of_package env smod.pmod_loc p nl tl
+- | {desc = Tvar} ->
++ | {desc = Tvar _} ->
+ raise (Typecore.Error
+ (smod.pmod_loc, Typecore.Cannot_infer_signature))
+ | _ ->
+Index: typing/typetexp.ml
+===================================================================
+--- typing/typetexp.ml (リビジョン 11207)
++++ typing/typetexp.ml (作業コピー)
+@@ -150,7 +150,7 @@
+ if strict then raise Already_bound;
+ v
+ with Not_found ->
+- let v = new_global_var() in
++ let v = new_global_var ~name () in
+ type_variables := Tbl.add name v !type_variables;
+ v
+
+@@ -165,8 +165,8 @@
+ Tpoly _ -> ty
+ | _ -> Ctype.newty (Tpoly (ty, []))
+
+-let new_pre_univar () =
+- let v = newvar () in pre_univars := v :: !pre_univars; v
++let new_pre_univar ?name () =
++ let v = newvar ?name () in pre_univars := v :: !pre_univars; v
+
+ let rec swap_list = function
+ x :: y :: l -> y :: x :: swap_list l
+@@ -190,7 +190,8 @@
+ instance (fst(Tbl.find name !used_variables))
+ with Not_found ->
+ let v =
+- if policy = Univars then new_pre_univar () else newvar () in
++ if policy = Univars then new_pre_univar ~name () else newvar ~name ()
++ in
+ used_variables := Tbl.add name (v, styp.ptyp_loc) !used_variables;
+ v
+ end
+@@ -333,7 +334,14 @@
+ end_def ();
+ generalize_structure t;
+ end;
+- instance t
++ let t = instance t in
++ let px = Btype.proxy t in
++ begin match px.desc with
++ | Tvar None -> Btype.log_type px; px.desc <- Tvar (Some alias)
++ | Tunivar None -> Btype.log_type px; px.desc <- Tunivar (Some alias)
++ | _ -> ()
++ end;
++ t
+ end
+ | Ptyp_variant(fields, closed, present) ->
+ let name = ref None in
+@@ -388,7 +396,7 @@
+ {desc=Tvariant row}, _ when Btype.static_row row ->
+ let row = Btype.row_repr row in
+ row.row_fields
+- | {desc=Tvar}, Some(p, _) ->
++ | {desc=Tvar _}, Some(p, _) ->
+ raise(Error(sty.ptyp_loc, Unbound_type_constructor_2 p))
+ | _ ->
+ raise(Error(sty.ptyp_loc, Not_a_variant ty))
+@@ -431,7 +439,7 @@
+ newty (Tvariant row)
+ | Ptyp_poly(vars, st) ->
+ begin_def();
+- let new_univars = List.map (fun name -> name, newvar()) vars in
++ let new_univars = List.map (fun name -> name, newvar ~name ()) vars in
+ let old_univars = !univars in
+ univars := new_univars @ !univars;
+ let ty = transl_type env policy st in
+@@ -443,10 +451,12 @@
+ (fun tyl (name, ty1) ->
+ let v = Btype.proxy ty1 in
+ if deep_occur v ty then begin
+- if v.level <> Btype.generic_level || v.desc <> Tvar then
+- raise (Error (styp.ptyp_loc, Cannot_quantify (name, v)));
+- v.desc <- Tunivar;
+- v :: tyl
++ match v.desc with
++ Tvar name when v.level = Btype.generic_level ->
++ v.desc <- Tunivar name;
++ v :: tyl
++ | _ ->
++ raise (Error (styp.ptyp_loc, Cannot_quantify (name, v)))
+ end else tyl)
+ [] new_univars
+ in
+@@ -483,7 +493,7 @@
+ match ty.desc with
+ | Tvariant row ->
+ let row = Btype.row_repr row in
+- if (Btype.row_more row).desc = Tunivar then
++ if Btype.is_Tunivar (Btype.row_more row) then
+ ty.desc <- Tvariant
+ {row with row_fixed=true;
+ row_fields = List.map
+@@ -512,7 +522,7 @@
+ then try
+ r := (loc, v, Tbl.find name !type_variables) :: !r
+ with Not_found ->
+- if fixed && (repr ty).desc = Tvar then
++ if fixed && Btype.is_Tvar (repr ty) then
+ raise(Error(loc, Unbound_type_variable ("'"^name)));
+ let v2 = new_global_var () in
+ r := (loc, v, v2) :: !r;
+@@ -552,8 +562,10 @@
+ List.fold_left
+ (fun acc v ->
+ let v = repr v in
+- if v.level <> Btype.generic_level || v.desc <> Tvar then acc
+- else (v.desc <- Tunivar ; v :: acc))
++ match v.desc with
++ Tvar name when v.level = Btype.generic_level ->
++ v.desc <- Tunivar name; v :: acc
++ | _ -> acc)
+ [] !pre_univars
+ in
+ make_fixed_univars typ;
+@@ -635,8 +647,8 @@
+ fprintf ppf "The type variable name %s is not allowed in programs" name
+ | Cannot_quantify (name, v) ->
+ fprintf ppf "This type scheme cannot quantify '%s :@ %s." name
+- (if v.desc = Tvar then "it escapes this scope" else
+- if v.desc = Tunivar then "it is aliased to another variable"
++ (if Btype.is_Tvar v then "it escapes this scope" else
++ if Btype.is_Tunivar v then "it is aliased to another variable"
+ else "it is not a variable")
+ | Multiple_constraints_on_type s ->
+ fprintf ppf "Multiple constraints for type %s" s
+Index: typing/btype.ml
+===================================================================
+--- typing/btype.ml (リビジョン 11207)
++++ typing/btype.ml (作業コピー)
+@@ -35,9 +35,9 @@
+ let new_id = ref (-1)
+
+ let newty2 level desc =
+- incr new_id; { desc = desc; level = level; id = !new_id }
++ incr new_id; { desc; level; id = !new_id }
+ let newgenty desc = newty2 generic_level desc
+-let newgenvar () = newgenty Tvar
++let newgenvar ?name () = newgenty (Tvar name)
+ (*
+ let newmarkedvar level =
+ incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id }
+@@ -46,6 +46,11 @@
+ { desc = Tvar; level = pivot_level - generic_level; id = !new_id }
+ *)
+
++(**** Check some types ****)
++
++let is_Tvar = function {desc=Tvar _} -> true | _ -> false
++let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false
++
+ (**** Representative of a type ****)
+
+ let rec field_kind_repr =
+@@ -139,7 +144,7 @@
+ let rec proxy_obj ty =
+ match ty.desc with
+ Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty
+- | Tvar | Tunivar | Tconstr _ -> ty
++ | Tvar _ | Tunivar _ | Tconstr _ -> ty
+ | Tnil -> ty0
+ | _ -> assert false
+ in proxy_obj ty
+@@ -180,13 +185,13 @@
+ row.row_fields;
+ match (repr row.row_more).desc with
+ Tvariant row -> iter_row f row
+- | Tvar | Tunivar | Tsubst _ | Tconstr _ ->
++ | Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ ->
+ Misc.may (fun (_,l) -> List.iter f l) row.row_name
+ | _ -> assert false
+
+ let iter_type_expr f ty =
+ match ty.desc with
+- Tvar -> ()
++ Tvar _ -> ()
+ | Tarrow (_, ty1, ty2, _) -> f ty1; f ty2
+ | Ttuple l -> List.iter f l
+ | Tconstr (_, l, _) -> List.iter f l
+@@ -198,7 +203,7 @@
+ | Tnil -> ()
+ | Tlink ty -> f ty
+ | Tsubst ty -> f ty
+- | Tunivar -> ()
++ | Tunivar _ -> ()
+ | Tpoly (ty, tyl) -> f ty; List.iter f tyl
+ | Tpackage (_, _, l) -> List.iter f l
+
+@@ -239,13 +244,13 @@
+ encoding during substitution *)
+ let rec norm_univar ty =
+ match ty.desc with
+- Tunivar | Tsubst _ -> ty
++ Tunivar _ | Tsubst _ -> ty
+ | Tlink ty -> norm_univar ty
+ | Ttuple (ty :: _) -> norm_univar ty
+ | _ -> assert false
+
+ let rec copy_type_desc f = function
+- Tvar -> Tvar
++ Tvar _ -> Tvar None (* forget the name *)
+ | Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c)
+ | Ttuple l -> Ttuple (List.map f l)
+ | Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil)
+@@ -258,7 +263,7 @@
+ | Tnil -> Tnil
+ | Tlink ty -> copy_type_desc f ty.desc
+ | Tsubst ty -> assert false
+- | Tunivar -> Tunivar
++ | Tunivar _ as ty -> ty (* keep the name *)
+ | Tpoly (ty, tyl) ->
+ let tyl = List.map (fun x -> norm_univar (f x)) tyl in
+ Tpoly (f ty, tyl)
+@@ -447,7 +452,7 @@
+ | Cuniv of type_expr option ref * type_expr option
+
+ let undo_change = function
+- Ctype (ty, desc) -> ty.desc <- desc
++ Ctype (ty, desc) -> ty.desc <- desc
+ | Clevel (ty, level) -> ty.level <- level
+ | Cname (r, v) -> r := v
+ | Crow (r, v) -> r := v
+@@ -474,7 +479,22 @@
+
+ let log_type ty =
+ if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc))
+-let link_type ty ty' = log_type ty; ty.desc <- Tlink ty'
++let link_type ty ty' =
++ log_type ty;
++ let desc = ty.desc in
++ ty.desc <- Tlink ty';
++ (* Name is a user-supplied name for this unification variable (obtained
++ * through a type annotation for instance). *)
++ match desc, ty'.desc with
++ Tvar name, Tvar name' ->
++ begin match name, name' with
++ | Some _, None -> log_type ty'; ty'.desc <- Tvar name
++ | None, Some _ -> ()
++ | Some _, Some _ ->
++ if ty.level < ty'.level then (log_type ty'; ty'.desc <- Tvar name)
++ | None, None -> ()
++ end
++ | _ -> ()
+ (* ; assert (check_memorized_abbrevs ()) *)
+ (* ; check_expans [] ty' *)
+ let set_level ty level =
+Index: typing/typecore.ml
+===================================================================
+--- typing/typecore.ml (リビジョン 11207)
++++ typing/typecore.ml (作業コピー)
+@@ -633,7 +633,7 @@
+ List.iter generalize vars;
+ let instantiated tv =
+ let tv = expand_head !env tv in
+- tv.desc <> Tvar || tv.level <> generic_level in
++ not (is_Tvar tv) || tv.level <> generic_level in
+ if List.exists instantiated vars then
+ raise (Error(loc, Polymorphic_label (lid_of_label label)))
+ end;
+@@ -1126,7 +1126,7 @@
+ Tarrow (l, _, ty_res, _) ->
+ list_labels_aux env (ty::visited) (l::ls) ty_res
+ | _ ->
+- List.rev ls, ty.desc = Tvar
++ List.rev ls, is_Tvar ty
+
+ let list_labels env ty = list_labels_aux env [] [] ty
+
+@@ -1142,9 +1142,10 @@
+ (fun t ->
+ let t = repr t in
+ generalize t;
+- if t.desc = Tvar && t.level = generic_level then
+- (log_type t; t.desc <- Tunivar; true)
+- else false)
++ match t.desc with
++ Tvar name when t.level = generic_level ->
++ log_type t; t.desc <- Tunivar name; true
++ | _ -> false)
+ vars in
+ if List.length vars = List.length vars' then () else
+ let ty = newgenty (Tpoly(repr exp.exp_type, vars'))
+@@ -1158,7 +1159,7 @@
+ match (expand_head env exp.exp_type).desc with
+ | Tarrow _ ->
+ Location.prerr_warning exp.exp_loc Warnings.Partial_application
+- | Tvar -> ()
++ | Tvar _ -> ()
+ | Tconstr (p, _, _) when Path.same p Predef.path_unit -> ()
+ | _ ->
+ if statement then
+@@ -1742,7 +1743,7 @@
+ let (id, typ) =
+ filter_self_method env met Private meths privty
+ in
+- if (repr typ).desc = Tvar then
++ if is_Tvar (repr typ) then
+ Location.prerr_warning loc
+ (Warnings.Undeclared_virtual_method met);
+ (Texp_send(obj, Tmeth_val id), typ)
+@@ -1797,7 +1798,7 @@
+ Location.prerr_warning loc
+ (Warnings.Not_principal "this use of a polymorphic method");
+ snd (instance_poly false tl ty)
+- | {desc = Tvar} as ty ->
++ | {desc = Tvar _} as ty ->
+ let ty' = newvar () in
+ unify env (instance ty) (newty(Tpoly(ty',[])));
+ (* if not !Clflags.nolabels then
+@@ -1979,7 +1980,7 @@
+ end_def ();
+ check_univars env false "method" exp ty_expected vars;
+ re { exp with exp_type = instance ty }
+- | Tvar ->
++ | Tvar _ ->
+ let exp = type_exp env sbody in
+ let exp = {exp with exp_type = newty (Tpoly (exp.exp_type, []))} in
+ unify_exp env exp ty;
+@@ -2038,7 +2039,7 @@
+ Location.prerr_warning loc
+ (Warnings.Not_principal "this module packing");
+ (p, nl, tl)
+- | {desc = Tvar} ->
++ | {desc = Tvar _} ->
+ raise (Error (loc, Cannot_infer_signature))
+ | _ ->
+ raise (Error (loc, Not_a_packed_module ty_expected))
+@@ -2128,7 +2129,7 @@
+ ty_fun
+ | Tarrow (l,_,ty_res',_) when l = "" || !Clflags.classic ->
+ args, ty_fun, no_labels ty_res'
+- | Tvar -> args, ty_fun, false
++ | Tvar _ -> args, ty_fun, false
+ | _ -> [], texp.exp_type, false
+ in
+ let args, ty_fun', simple_res = make_args [] texp.exp_type in
+@@ -2192,7 +2193,7 @@
+ let (ty1, ty2) =
+ let ty_fun = expand_head env ty_fun in
+ match ty_fun.desc with
+- Tvar ->
++ Tvar _ ->
+ let t1 = newvar () and t2 = newvar () in
+ let not_identity = function
+ Texp_ident(_,{val_kind=Val_prim
+@@ -2335,7 +2336,7 @@
+ begin match (expand_head env exp.exp_type).desc with
+ | Tarrow _ ->
+ Location.prerr_warning exp.exp_loc Warnings.Partial_application
+- | Tvar ->
++ | Tvar _ ->
+ add_delayed_check (fun () -> check_application_result env false exp)
+ | _ -> ()
+ end;
+@@ -2404,9 +2405,9 @@
+ | Tarrow _ ->
+ Location.prerr_warning loc Warnings.Partial_application
+ | Tconstr (p, _, _) when Path.same p Predef.path_unit -> ()
+- | Tvar when ty.level > tv.level ->
++ | Tvar _ when ty.level > tv.level ->
+ Location.prerr_warning loc Warnings.Nonreturning_statement
+- | Tvar ->
++ | Tvar _ ->
+ add_delayed_check (fun () -> check_application_result env true exp)
+ | _ ->
+ Location.prerr_warning loc Warnings.Statement_type
+Index: typing/btype.mli
+===================================================================
+--- typing/btype.mli (リビジョン 11207)
++++ typing/btype.mli (作業コピー)
+@@ -23,7 +23,7 @@
+ (* Create a type *)
+ val newgenty: type_desc -> type_expr
+ (* Create a generic type *)
+-val newgenvar: unit -> type_expr
++val newgenvar: ?name:string -> unit -> type_expr
+ (* Return a fresh generic variable *)
+
+ (* Use Tsubst instead
+@@ -33,6 +33,9 @@
+ (* Return a fresh marked generic variable *)
+ *)
+
++val is_Tvar: type_expr -> bool
++val is_Tunivar: type_expr -> bool
++
+ val repr: type_expr -> type_expr
+ (* Return the canonical representative of a type. *)
+
+Index: typing/ctype.mli
+===================================================================
+--- typing/ctype.mli (リビジョン 11207)
++++ typing/ctype.mli (作業コピー)
+@@ -41,9 +41,10 @@
+ (* This pair of functions is only used in Typetexp *)
+
+ val newty: type_desc -> type_expr
+-val newvar: unit -> type_expr
++val newvar: ?name:string -> unit -> type_expr
++val newvar2: ?name:string -> int -> type_expr
+ (* Return a fresh variable *)
+-val new_global_var: unit -> type_expr
++val new_global_var: ?name:string -> unit -> type_expr
+ (* Return a fresh variable, bound at toplevel
+ (as type variables ['a] in type constraints). *)
+ val newobj: type_expr -> type_expr
+Index: typing/datarepr.ml
+===================================================================
+--- typing/datarepr.ml (リビジョン 11207)
++++ typing/datarepr.ml (作業コピー)
+@@ -28,7 +28,7 @@
+ if ty.level >= lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ match ty.desc with
+- | Tvar ->
++ | Tvar _ ->
+ ret := TypeSet.add ty !ret
+ | Tvariant row ->
+ let row = row_repr row in
+Index: typing/typeclass.ml
+===================================================================
+--- typing/typeclass.ml (リビジョン 11207)
++++ typing/typeclass.ml (作業コピー)
+@@ -532,7 +532,7 @@
+ (Typetexp.transl_simple_type val_env false sty) ty
+ end;
+ begin match (Ctype.repr ty).desc with
+- Tvar ->
++ Tvar _ ->
+ let ty' = Ctype.newvar () in
+ Ctype.unify val_env (Ctype.newty (Tpoly (ty', []))) ty;
+ Ctype.unify val_env (type_approx val_env sbody) ty'
+Index: typing/typedecl.ml
+===================================================================
+--- typing/typedecl.ml (リビジョン 11207)
++++ typing/typedecl.ml (作業コピー)
+@@ -111,7 +111,7 @@
+ | _ ->
+ raise (Error (loc, Bad_fixed_type "is not an object or variant"))
+ in
+- if rv.desc <> Tvar then
++ if not (Btype.is_Tvar rv) then
+ raise (Error (loc, Bad_fixed_type "has no row variable"));
+ rv.desc <- Tconstr (p, decl.type_params, ref Mnil)
+
+@@ -503,7 +503,7 @@
+ compute_same row.row_more
+ | Tpoly (ty, _) ->
+ compute_same ty
+- | Tvar | Tnil | Tlink _ | Tunivar -> ()
++ | Tvar _ | Tnil | Tlink _ | Tunivar _ -> ()
+ | Tpackage (_, _, tyl) ->
+ List.iter (compute_variance_rec true true true) tyl
+ end
+@@ -546,7 +546,7 @@
+ in
+ List.iter2
+ (fun (ty, co, cn, ct) (c, n) ->
+- if ty.desc <> Tvar then begin
++ if not (Btype.is_Tvar ty) then begin
+ co := c; cn := n; ct := n;
+ compute_variance env tvl2 c n n ty
+ end)
+@@ -571,7 +571,7 @@
+
+ let rec anonymous env ty =
+ match (Ctype.expand_head env ty).desc with
+- | Tvar -> false
++ | Tvar _ -> false
+ | Tobject (fi, _) ->
+ let _, rv = Ctype.flatten_fields fi in anonymous env rv
+ | Tvariant row ->
+Index: typing/types.mli
+===================================================================
+--- typing/types.mli (リビジョン 11207)
++++ typing/types.mli (作業コピー)
+@@ -24,7 +24,7 @@
+ mutable id: int }
+
+ and type_desc =
+- Tvar
++ Tvar of string option
+ | Tarrow of label * type_expr * type_expr * commutable
+ | Ttuple of type_expr list
+ | Tconstr of Path.t * type_expr list * abbrev_memo ref
+@@ -34,7 +34,7 @@
+ | Tlink of type_expr
+ | Tsubst of type_expr (* for copying *)
+ | Tvariant of row_desc
+- | Tunivar
++ | Tunivar of string option
+ | Tpoly of type_expr * type_expr list
+ | Tpackage of Path.t * string list * type_expr list
+
+Index: typing/ctype.ml
+===================================================================
+--- typing/ctype.ml (リビジョン 11207)
++++ typing/ctype.ml (作業コピー)
+@@ -153,9 +153,9 @@
+ let newty desc = newty2 !current_level desc
+ let new_global_ty desc = newty2 !global_level desc
+
+-let newvar () = newty2 !current_level Tvar
+-let newvar2 level = newty2 level Tvar
+-let new_global_var () = newty2 !global_level Tvar
++let newvar ?name () = newty2 !current_level (Tvar name)
++let newvar2 ?name level = newty2 level (Tvar name)
++let new_global_var ?name () = newty2 !global_level (Tvar name)
+
+ let newobj fields = newty (Tobject (fields, ref None))
+
+@@ -297,14 +297,12 @@
+
+ let opened_object ty =
+ match (object_row ty).desc with
+- | Tvar -> true
+- | Tunivar -> true
+- | Tconstr _ -> true
+- | _ -> false
++ | Tvar _ | Tunivar _ | Tconstr _ -> true
++ | _ -> false
+
+ let concrete_object ty =
+ match (object_row ty).desc with
+- | Tvar -> false
++ | Tvar _ -> false
+ | _ -> true
+
+ (**** Close an object ****)
+@@ -313,7 +311,7 @@
+ let rec close ty =
+ let ty = repr ty in
+ match ty.desc with
+- Tvar ->
++ Tvar _ ->
+ link_type ty (newty2 ty.level Tnil)
+ | Tfield(_, _, _, ty') -> close ty'
+ | _ -> assert false
+@@ -329,7 +327,7 @@
+ let ty = repr ty in
+ match ty.desc with
+ Tfield (_, _, _, ty) -> find ty
+- | Tvar -> ty
++ | Tvar _ -> ty
+ | _ -> assert false
+ in
+ match (repr ty).desc with
+@@ -434,7 +432,7 @@
+ let level = ty.level in
+ ty.level <- pivot_level - level;
+ match ty.desc with
+- Tvar when level <> generic_level ->
++ Tvar _ when level <> generic_level ->
+ raise Non_closed
+ | Tfield(_, kind, t1, t2) ->
+ if field_kind_repr kind = Fpresent then
+@@ -468,7 +466,7 @@
+ if ty.level >= lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ begin match ty.desc, !really_closed with
+- Tvar, _ ->
++ Tvar _, _ ->
+ free_variables := (ty, real) :: !free_variables
+ | Tconstr (path, tl, _), Some env ->
+ begin try
+@@ -639,7 +637,7 @@
+ let rec generalize_structure var_level ty =
+ let ty = repr ty in
+ if ty.level <> generic_level then begin
+- if ty.desc = Tvar && ty.level > var_level then
++ if is_Tvar ty && ty.level > var_level then
+ set_level ty var_level
+ else if ty.level > !current_level then begin
+ set_level ty generic_level;
+@@ -858,7 +856,7 @@
+ TypeHash.add node_univars inv.inv_type (ref(TypeSet.singleton univ));
+ List.iter (add_univar univ) inv.inv_parents
+ in
+- TypeHash.iter (fun ty inv -> if ty.desc = Tunivar then add_univar ty inv)
++ TypeHash.iter (fun ty inv -> if is_Tunivar ty then add_univar ty inv)
+ inverted;
+ fun ty ->
+ try !(TypeHash.find node_univars ty) with Not_found -> TypeSet.empty
+@@ -913,7 +911,7 @@
+ if keep then ty.level else !current_level
+ else generic_level
+ in
+- if forget <> generic_level then newty2 forget Tvar else
++ if forget <> generic_level then newty2 forget (Tvar None) else
+ let desc = ty.desc in
+ save_desc ty desc;
+ let t = newvar() in (* Stub *)
+@@ -959,7 +957,7 @@
+ | Tconstr _ ->
+ if keep then save_desc more more.desc;
+ copy more
+- | Tvar | Tunivar ->
++ | Tvar _ | Tunivar _ ->
+ save_desc more more.desc;
+ if keep then more else newty more.desc
+ | _ -> assert false
+@@ -1117,7 +1115,7 @@
+ t
+ else try
+ let t, bound_t = List.assq ty visited in
+- let dl = if ty.desc = Tunivar then [] else diff_list bound bound_t in
++ let dl = if is_Tunivar ty then [] else diff_list bound bound_t in
+ if dl <> [] && conflicts univars dl then raise Not_found;
+ t
+ with Not_found -> begin
+@@ -1134,14 +1132,14 @@
+ let row = row_repr row0 in
+ let more = repr row.row_more in
+ (* We shall really check the level on the row variable *)
+- let keep = more.desc = Tvar && more.level <> generic_level in
++ let keep = is_Tvar more && more.level <> generic_level in
+ let more' = copy_rec more in
+- let fixed' = fixed && (repr more').desc = Tvar in
++ let fixed' = fixed && is_Tvar (repr more') in
+ let row = copy_row copy_rec fixed' row keep more' in
+ Tvariant row
+ | Tpoly (t1, tl) ->
+ let tl = List.map repr tl in
+- let tl' = List.map (fun t -> newty Tunivar) tl in
++ let tl' = List.map (fun t -> newty t.desc) tl in
+ let bound = tl @ bound in
+ let visited =
+ List.map2 (fun ty t -> ty,(t,bound)) tl tl' @ visited in
+@@ -1395,7 +1393,7 @@
+ let rec full_expand env ty =
+ let ty = repr (expand_head env ty) in
+ match ty.desc with
+- Tobject (fi, {contents = Some (_, v::_)}) when (repr v).desc = Tvar ->
++ Tobject (fi, {contents = Some (_, v::_)}) when is_Tvar (repr v) ->
+ newty2 ty.level (Tobject (fi, ref None))
+ | _ ->
+ ty
+@@ -1570,8 +1568,8 @@
+ true
+ then
+ match ty.desc with
+- Tunivar ->
+- if not (TypeSet.mem ty bound) then raise (Unify [ty, newgenvar()])
++ Tunivar _ ->
++ if not (TypeSet.mem ty bound) then raise (Unify [ty, newgenvar ()])
+ | Tpoly (ty, tyl) ->
+ let bound = List.fold_right TypeSet.add (List.map repr tyl) bound in
+ occur_rec bound ty
+@@ -1620,7 +1618,7 @@
+ Tpoly (t, tl) ->
+ if List.exists (fun t -> TypeSet.mem (repr t) family) tl then ()
+ else occur t
+- | Tunivar ->
++ | Tunivar _ ->
+ if TypeSet.mem t family then raise Occur
+ | Tconstr (_, [], _) -> ()
+ | Tconstr (p, tl, _) ->
+@@ -1784,7 +1782,7 @@
+ t
+ end;
+ iter_type_expr (iterator visited) ty
+- | Tvar ->
++ | Tvar _ ->
+ let t = create_fresh_constr ty.level false in
+ link_type ty t
+ | _ ->
+@@ -1862,8 +1860,8 @@
+ let t2 = repr t2 in
+ if t1 == t2 then () else
+ match (t1.desc, t2.desc) with
+- | (Tvar, _)
+- | (_, Tvar) ->
++ | (Tvar _, _)
++ | (_, Tvar _) ->
+ fatal_error "types should not include variables"
+ | (Tconstr (p1, [], _), Tconstr (p2, [], _)) when Path.same p1 p2 ->
+ ()
+@@ -1877,7 +1875,7 @@
+ with Not_found ->
+ TypePairs.add type_pairs (t1', t2') ();
+ match (t1'.desc, t2'.desc) with
+- (Tvar, Tvar) ->
++ (Tvar _, Tvar _) ->
+ fatal_error "types should not include variables"
+ | (Tarrow (l1, t1, u1, _), Tarrow (l2, t2, u2, _)) when l1 = l2
+ || !Clflags.classic && not (is_optional l1 || is_optional l2) ->
+@@ -1903,7 +1901,7 @@
+ | (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
+ enter_poly env univar_pairs t1 tl1 t2 tl2
+ (mcomp type_pairs subst env)
+- | (Tunivar, Tunivar) ->
++ | (Tunivar _, Tunivar _) ->
+ unify_univar t1' t2' !univar_pairs
+ | (_, _) ->
+ raise (Unify [])
+@@ -2048,21 +2046,21 @@
+ try
+ type_changed := true;
+ match (t1.desc, t2.desc) with
+- (Tvar, Tconstr _) when deep_occur t1 t2 ->
++ (Tvar _, Tconstr _) when deep_occur t1 t2 ->
+ unify2 env t1 t2
+- | (Tconstr _, Tvar) when deep_occur t2 t1 ->
++ | (Tconstr _, Tvar _) when deep_occur t2 t1 ->
+ unify2 env t1 t2
+- | (Tvar, _) ->
++ | (Tvar _, _) ->
+ occur !env t1 t2;
+ occur_univar !env t2;
+ link_type t1 t2;
+ update_level !env t1.level t2
+- | (_, Tvar) ->
++ | (_, Tvar _) ->
+ occur !env t2 t1;
+ occur_univar !env t1;
+ link_type t2 t1;
+ update_level !env t2.level t1
+- | (Tunivar, Tunivar) ->
++ | (Tunivar _, Tunivar _) ->
+ unify_univar t1 t2 !univar_pairs;
+ update_level !env t1.level t2;
+ link_type t1 t2
+@@ -2104,7 +2102,7 @@
+ (* Assumes either [t1 == t1'] or [t2 != t2'] *)
+ let d1 = t1'.desc and d2 = t2'.desc in
+ match (d1, d2) with (* handle univars specially *)
+- (Tunivar, Tunivar) ->
++ (Tunivar _, Tunivar _) ->
+ unify_univar t1' t2' !univar_pairs;
+ update_level !env t1'.level t2';
+ link_type t1' t2'
+@@ -2127,12 +2125,12 @@
+ | Old -> f () (* old_link was already called *)
+ in
+ match d1, d2 with
+- | Tvar,_ ->
++ | Tvar _, _ ->
+ occur !env t1 t2';
+ occur_univar !env t2;
+ update_level !env t1'.level t2;
+ link_type t1' t2;
+- | _, Tvar ->
++ | _, Tvar _ ->
+ occur !env t2 t1';
+ occur_univar !env t1;
+ update_level !env t2'.level t1;
+@@ -2149,8 +2147,8 @@
+ add_type_equality t1' t2' end;
+ try
+ begin match (d1, d2) with
+- | (Tvar, _)
+- | (_, Tvar) ->
++ | (Tvar _, _)
++ | (_, Tvar _) ->
+ (* cases taken care of *)
+ assert false
+ | (Tarrow (l1, t1, u1, c1), Tarrow (l2, t2, u2, c2)) when l1 = l2
+@@ -2214,8 +2212,9 @@
+ (* Type [t2'] may have been instantiated by [unify_fields] *)
+ (* XXX One should do some kind of unification... *)
+ begin match (repr t2').desc with
+- Tobject (_, {contents = Some (_, va::_)})
+- when let va = repr va in List.mem va.desc [Tvar; Tunivar; Tnil] ->
++ Tobject (_, {contents = Some (_, va::_)}) when
++ (match (repr va).desc with
++ Tvar _|Tunivar _|Tnil -> true | _ -> false) ->
+ ()
+ | Tobject (_, nm2) ->
+ set_name nm2 !nm1
+@@ -2290,16 +2289,32 @@
+ raise (Unify []);
+ List.iter2 (unify env) tl1 tl2
+
++(* Build a fresh row variable for unification *)
++and make_rowvar level use1 rest1 use2 rest2 =
++ let set_name ty name =
++ match ty.desc with
++ Tvar None -> log_type ty; ty.desc <- Tvar name
++ | _ -> ()
++ in
++ let name =
++ match rest1.desc, rest2.desc with
++ Tvar (Some _ as name1), Tvar (Some _ as name2) ->
++ if rest1.level <= rest2.level then name1 else name2
++ | Tvar (Some _ as name), _ ->
++ if use2 then set_name rest2 name; name
++ | _, Tvar (Some _ as name) ->
++ if use1 then set_name rest2 name; name
++ | _ -> None
++ in
++ if use1 then rest1 else
++ if use2 then rest2 else newvar2 ?name level
++
+ and unify_fields env ty1 ty2 = (* Optimization *)
+ let (fields1, rest1) = flatten_fields ty1
+ and (fields2, rest2) = flatten_fields ty2 in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ let l1 = (repr ty1).level and l2 = (repr ty2).level in
+- let va =
+- if miss1 = [] then rest2
+- else if miss2 = [] then rest1
+- else newty2 (min l1 l2) Tvar
+- in
++ let va = make_rowvar (min l1 l2) (miss2=[]) rest1 (miss1=[]) rest2 in
+ let d1 = rest1.desc and d2 = rest2.desc in
+ try
+ unify env (build_fields l1 miss1 va) rest2;
+@@ -2390,7 +2405,7 @@
+ let rm = row_more row in
+ if row.row_fixed then
+ if row0.row_more == rm then () else
+- if rm.desc = Tvar then link_type rm row0.row_more else
++ if is_Tvar rm then link_type rm row0.row_more else
+ unify env rm row0.row_more
+ else
+ let ty = newty2 generic_level (Tvariant {row0 with row_fields = rest}) in
+@@ -2489,7 +2504,7 @@
+ let t1 = repr t1 and t2 = repr t2 in
+ if t1 == t2 then () else
+ match t1.desc with
+- Tvar ->
++ Tvar _ ->
+ begin try
+ occur env t1 t2;
+ update_level env t1.level t2;
+@@ -2527,7 +2542,7 @@
+ let rec filter_arrow env t l =
+ let t = expand_head_unif env t in
+ match t.desc with
+- Tvar ->
++ Tvar _ ->
+ let lv = t.level in
+ let t1 = newvar2 lv and t2 = newvar2 lv in
+ let t' = newty2 lv (Tarrow (l, t1, t2, Cok)) in
+@@ -2543,7 +2558,7 @@
+ let rec filter_method_field env name priv ty =
+ let ty = repr ty in
+ match ty.desc with
+- Tvar ->
++ Tvar _ ->
+ let level = ty.level in
+ let ty1 = newvar2 level and ty2 = newvar2 level in
+ let ty' = newty2 level (Tfield (name,
+@@ -2570,7 +2585,7 @@
+ let rec filter_method env name priv ty =
+ let ty = expand_head_unif env ty in
+ match ty.desc with
+- Tvar ->
++ Tvar _ ->
+ let ty1 = newvar () in
+ let ty' = newobj ty1 in
+ update_level env ty.level ty';
+@@ -2606,7 +2621,7 @@
+ let rec occur ty =
+ let ty = repr ty in
+ if ty.level > level then begin
+- if ty.desc = Tvar && ty.level >= generic_level - 1 then raise Occur;
++ if is_Tvar ty && ty.level >= generic_level - 1 then raise Occur;
+ ty.level <- pivot_level - ty.level;
+ match ty.desc with
+ Tvariant row when static_row row ->
+@@ -2636,7 +2651,7 @@
+
+ try
+ match (t1.desc, t2.desc) with
+- (Tvar, _) when may_instantiate inst_nongen t1 ->
++ (Tvar _, _) when may_instantiate inst_nongen t1 ->
+ moregen_occur env t1.level t2;
+ occur env t1 t2;
+ link_type t1 t2
+@@ -2653,7 +2668,7 @@
+ with Not_found ->
+ TypePairs.add type_pairs (t1', t2') ();
+ match (t1'.desc, t2'.desc) with
+- (Tvar, _) when may_instantiate inst_nongen t1' ->
++ (Tvar _, _) when may_instantiate inst_nongen t1' ->
+ moregen_occur env t1'.level t2;
+ link_type t1' t2
+ | (Tarrow (l1, t1, u1, _), Tarrow (l2, t2, u2, _)) when l1 = l2
+@@ -2684,7 +2699,7 @@
+ | (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
+ enter_poly env univar_pairs t1 tl1 t2 tl2
+ (moregen inst_nongen type_pairs env)
+- | (Tunivar, Tunivar) ->
++ | (Tunivar _, Tunivar _) ->
+ unify_univar t1' t2' !univar_pairs
+ | (_, _) ->
+ raise (Unify [])
+@@ -2725,7 +2740,7 @@
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let rm1 = repr row1.row_more and rm2 = repr row2.row_more in
+ if rm1 == rm2 then () else
+- let may_inst = rm1.desc = Tvar && may_instantiate inst_nongen rm1 in
++ let may_inst = is_Tvar rm1 && may_instantiate inst_nongen rm1 in
+ let r1, r2, pairs = merge_row_fields row1.row_fields row2.row_fields in
+ let r1, r2 =
+ if row2.row_closed then
+@@ -2735,9 +2750,9 @@
+ if r1 <> [] || row1.row_closed && (not row2.row_closed || r2 <> [])
+ then raise (Unify []);
+ begin match rm1.desc, rm2.desc with
+- Tunivar, Tunivar ->
++ Tunivar _, Tunivar _ ->
+ unify_univar rm1 rm2 !univar_pairs
+- | Tunivar, _ | _, Tunivar ->
++ | Tunivar _, _ | _, Tunivar _ ->
+ raise (Unify [])
+ | _ when static_row row1 -> ()
+ | _ when may_inst ->
+@@ -2828,13 +2843,13 @@
+ if ty.level >= lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ match ty.desc with
+- | Tvar ->
++ | Tvar _ ->
+ if not (List.memq ty !vars) then vars := ty :: !vars
+ | Tvariant row ->
+ let row = row_repr row in
+ let more = repr row.row_more in
+- if more.desc = Tvar && not row.row_fixed then begin
+- let more' = newty2 more.level Tvar in
++ if is_Tvar more && not row.row_fixed then begin
++ let more' = newty2 more.level more.desc in
+ let row' = {row with row_fixed=true; row_fields=[]; row_more=more'}
+ in link_type more (newty2 ty.level (Tvariant row'))
+ end;
+@@ -2857,7 +2872,7 @@
+ (fun ty ->
+ let ty = expand_head env ty in
+ if List.memq ty !tyl then false else
+- (tyl := ty :: !tyl; ty.desc = Tvar))
++ (tyl := ty :: !tyl; is_Tvar ty))
+ vars
+
+ let matches env ty ty' =
+@@ -2901,7 +2916,7 @@
+
+ try
+ match (t1.desc, t2.desc) with
+- (Tvar, Tvar) when rename ->
++ (Tvar _, Tvar _) when rename ->
+ begin try
+ normalize_subst subst;
+ if List.assq t1 !subst != t2 then raise (Unify [])
+@@ -2922,7 +2937,7 @@
+ with Not_found ->
+ TypePairs.add type_pairs (t1', t2') ();
+ match (t1'.desc, t2'.desc) with
+- (Tvar, Tvar) when rename ->
++ (Tvar _, Tvar _) when rename ->
+ begin try
+ normalize_subst subst;
+ if List.assq t1' !subst != t2' then raise (Unify [])
+@@ -2956,7 +2971,7 @@
+ | (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
+ enter_poly env univar_pairs t1 tl1 t2 tl2
+ (eqtype rename type_pairs subst env)
+- | (Tunivar, Tunivar) ->
++ | (Tunivar _, Tunivar _) ->
+ unify_univar t1' t2' !univar_pairs
+ | (_, _) ->
+ raise (Unify [])
+@@ -3405,7 +3420,7 @@
+ let rec build_subtype env visited loops posi level t =
+ let t = repr t in
+ match t.desc with
+- Tvar ->
++ Tvar _ ->
+ if posi then
+ try
+ let t' = List.assq t loops in
+@@ -3454,13 +3469,13 @@
+ as this occurence might break the occur check.
+ XXX not clear whether this correct anyway... *)
+ if List.exists (deep_occur ty) tl1 then raise Not_found;
+- ty.desc <- Tvar;
++ ty.desc <- Tvar None;
+ let t'' = newvar () in
+ let loops = (ty, t'') :: loops in
+ (* May discard [visited] as level is going down *)
+ let (ty1', c) =
+ build_subtype env [t'] loops posi (pred_enlarge level') ty1 in
+- assert (t''.desc = Tvar);
++ assert (is_Tvar t'');
+ let nm =
+ if c > Equiv || deep_occur ty ty1' then None else Some(p,tl1) in
+ t''.desc <- Tobject (ty1', ref nm);
+@@ -3559,7 +3574,7 @@
+ let (t1', c) = build_subtype env visited loops posi level t1 in
+ if c > Unchanged then (newty (Tpoly(t1', tl)), c)
+ else (t, Unchanged)
+- | Tunivar | Tpackage _ ->
++ | Tunivar _ | Tpackage _ ->
+ (t, Unchanged)
+
+ let enlarge_type env ty =
+@@ -3623,7 +3638,7 @@
+ with Not_found ->
+ TypePairs.add subtypes (t1, t2) ();
+ match (t1.desc, t2.desc) with
+- (Tvar, _) | (_, Tvar) ->
++ (Tvar _, _) | (_, Tvar _) ->
+ (trace, t1, t2, !univar_pairs)::cstrs
+ | (Tarrow(l1, t1, u1, _), Tarrow(l2, t2, u2, _)) when l1 = l2
+ || !Clflags.classic && not (is_optional l1 || is_optional l2) ->
+@@ -3659,7 +3674,7 @@
+ | (Tconstr(p1, tl1, _), _) when private_abbrev env p1 ->
+ subtype_rec env trace (expand_abbrev_opt env t1) t2 cstrs
+ | (Tobject (f1, _), Tobject (f2, _))
+- when (object_row f1).desc = Tvar && (object_row f2).desc = Tvar ->
++ when is_Tvar (object_row f1) && is_Tvar (object_row f2) ->
+ (* Same row variable implies same object. *)
+ (trace, t1, t2, !univar_pairs)::cstrs
+ | (Tobject (f1, _), Tobject (f2, _)) ->
+@@ -3731,7 +3746,7 @@
+ match more1.desc, more2.desc with
+ Tconstr(p1,_,_), Tconstr(p2,_,_) when Path.same p1 p2 ->
+ subtype_rec env ((more1,more2)::trace) more1 more2 cstrs
+- | (Tvar|Tconstr _), (Tvar|Tconstr _)
++ | (Tvar _|Tconstr _), (Tvar _|Tconstr _)
+ when row1.row_closed && r1 = [] ->
+ List.fold_left
+ (fun cstrs (_,f1,f2) ->
+@@ -3745,7 +3760,7 @@
+ | Rabsent, _ -> cstrs
+ | _ -> raise Exit)
+ cstrs pairs
+- | Tunivar, Tunivar
++ | Tunivar _, Tunivar _
+ when row1.row_closed = row2.row_closed && r1 = [] && r2 = [] ->
+ let cstrs =
+ subtype_rec env ((more1,more2)::trace) more1 more2 cstrs in
+@@ -3789,19 +3804,19 @@
+ match ty.desc with
+ Tfield (s, k, t1, t2) ->
+ newty2 ty.level (Tfield (s, k, t1, unalias_object t2))
+- | Tvar | Tnil ->
++ | Tvar _ | Tnil ->
+ newty2 ty.level ty.desc
+- | Tunivar ->
++ | Tunivar _ ->
+ ty
+ | Tconstr _ ->
+- newty2 ty.level Tvar
++ newvar2 ty.level
+ | _ ->
+ assert false
+
+ let unalias ty =
+ let ty = repr ty in
+ match ty.desc with
+- Tvar | Tunivar ->
++ Tvar _ | Tunivar _ ->
+ ty
+ | Tvariant row ->
+ let row = row_repr row in
+@@ -3875,7 +3890,7 @@
+ set_name nm None
+ else let v' = repr v in
+ begin match v'.desc with
+- | Tvar|Tunivar ->
++ | Tvar _ | Tunivar _ ->
+ if v' != v then set_name nm (Some (n, v' :: l))
+ | Tnil ->
+ log_type ty; ty.desc <- Tconstr (n, l, ref Mnil)
+@@ -3917,7 +3932,7 @@
+
+ let rec nondep_type_rec env id ty =
+ match ty.desc with
+- Tvar | Tunivar -> ty
++ Tvar _ | Tunivar _ -> ty
+ | Tlink ty -> nondep_type_rec env id ty
+ | _ -> try TypeHash.find nondep_hash ty
+ with Not_found ->
+@@ -3987,7 +4002,7 @@
+
+ let unroll_abbrev id tl ty =
+ let ty = repr ty and path = Path.Pident id in
+- if (ty.desc = Tvar) || (List.exists (deep_occur ty) tl)
++ if is_Tvar ty || (List.exists (deep_occur ty) tl)
+ || is_object_type path then
+ ty
+ else
+Index: typing/printtyp.ml
+===================================================================
+--- typing/printtyp.ml (リビジョン 11207)
++++ typing/printtyp.ml (作業コピー)
+@@ -109,6 +109,10 @@
+ | Mcons (priv, p, t1, t2, rem) -> p :: list_of_memo rem
+ | Mlink rem -> list_of_memo !rem
+
++let print_name ppf = function
++ None -> fprintf ppf "None"
++ | Some name -> fprintf ppf "\"%s\"" name
++
+ let visited = ref []
+ let rec raw_type ppf ty =
+ let ty = safe_repr [] ty in
+@@ -119,7 +123,7 @@
+ end
+ and raw_type_list tl = raw_list raw_type tl
+ and raw_type_desc ppf = function
+- Tvar -> fprintf ppf "Tvar"
++ Tvar name -> fprintf ppf "Tvar %a" print_name name
+ | Tarrow(l,t1,t2,c) ->
+ fprintf ppf "@[<hov1>Tarrow(%s,@,%a,@,%a,@,%s)@]"
+ l raw_type t1 raw_type t2
+@@ -143,7 +147,7 @@
+ | Tnil -> fprintf ppf "Tnil"
+ | Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
+ | Tsubst t -> fprintf ppf "@[<1>Tsubst@,%a@]" raw_type t
+- | Tunivar -> fprintf ppf "Tunivar"
++ | Tunivar name -> fprintf ppf "Tunivar %a" print_name name
+ | Tpoly (t, tl) ->
+ fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
+ raw_type t
+@@ -189,28 +193,61 @@
+
+ let names = ref ([] : (type_expr * string) list)
+ let name_counter = ref 0
++let named_vars = ref ([] : string list)
+
+-let reset_names () = names := []; name_counter := 0
++let reset_names () = names := []; name_counter := 0; named_vars := []
++let add_named_var ty =
++ match ty.desc with
++ Tvar (Some name) | Tunivar (Some name) ->
++ if List.mem name !named_vars then () else
++ named_vars := name :: !named_vars
++ | _ -> ()
+
+-let new_name () =
++let rec new_name () =
+ let name =
+ if !name_counter < 26
+ then String.make 1 (Char.chr(97 + !name_counter))
+ else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
+ string_of_int(!name_counter / 26) in
+ incr name_counter;
+- name
++ if List.mem name !named_vars
++ || List.exists (fun (_, name') -> name = name') !names
++ then new_name ()
++ else name
+
+ let name_of_type t =
++ (* We've already been through repr at this stage, so t is our representative
++ of the union-find class. *)
+ try List.assq t !names with Not_found ->
+- let name = new_name () in
++ let name =
++ match t.desc with
++ Tvar (Some name) | Tunivar (Some name) ->
++ (* Some part of the type we've already printed has assigned another
++ * unification variable to that name. We want to keep the name, so try
++ * adding a number until we find a name that's not taken. *)
++ let current_name = ref name in
++ let i = ref 0 in
++ while List.exists (fun (_, name') -> !current_name = name') !names do
++ current_name := name ^ (string_of_int !i);
++ i := !i + 1;
++ done;
++ !current_name
++ | _ ->
++ (* No name available, create a new one *)
++ new_name ()
++ in
+ names := (t, name) :: !names;
+ name
+
+ let check_name_of_type t = ignore(name_of_type t)
+
++let remove_names tyl =
++ let tyl = List.map repr tyl in
++ names := List.filter (fun (ty,_) -> not (List.memq ty tyl)) !names
++
++
+ let non_gen_mark sch ty =
+- if sch && ty.desc = Tvar && ty.level <> generic_level then "_" else ""
++ if sch && is_Tvar ty && ty.level <> generic_level then "_" else ""
+
+ let print_name_of_type sch ppf t =
+ fprintf ppf "'%s%s" (non_gen_mark sch t) (name_of_type t)
+@@ -225,9 +262,13 @@
+ let is_aliased ty = List.memq (proxy ty) !aliased
+ let add_alias ty =
+ let px = proxy ty in
+- if not (is_aliased px) then aliased := px :: !aliased
++ if not (is_aliased px) then begin
++ aliased := px :: !aliased;
++ add_named_var px
++ end
++
+ let aliasable ty =
+- match ty.desc with Tvar | Tunivar | Tpoly _ -> false | _ -> true
++ match ty.desc with Tvar _ | Tunivar _ | Tpoly _ -> false | _ -> true
+
+ let namable_row row =
+ row.row_name <> None &&
+@@ -245,7 +286,7 @@
+ if List.memq px visited && aliasable ty then add_alias px else
+ let visited = px :: visited in
+ match ty.desc with
+- | Tvar -> ()
++ | Tvar _ -> add_named_var ty
+ | Tarrow(_, ty1, ty2, _) ->
+ mark_loops_rec visited ty1; mark_loops_rec visited ty2
+ | Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
+@@ -290,7 +331,7 @@
+ | Tpoly (ty, tyl) ->
+ List.iter (fun t -> add_alias t) tyl;
+ mark_loops_rec visited ty
+- | Tunivar -> ()
++ | Tunivar _ -> add_named_var ty
+
+ let mark_loops ty =
+ normalize_type Env.empty ty;
+@@ -322,7 +363,7 @@
+
+ let pr_typ () =
+ match ty.desc with
+- | Tvar ->
++ | Tvar _ ->
+ Otyp_var (is_non_gen sch ty, name_of_type ty)
+ | Tarrow(l, ty1, ty2, _) ->
+ let pr_arrow l ty1 ty2 =
+@@ -387,16 +428,22 @@
+ | Tpoly (ty, []) ->
+ tree_of_typexp sch ty
+ | Tpoly (ty, tyl) ->
++ (*let print_names () =
++ List.iter (fun (_, name) -> prerr_string (name ^ " ")) !names;
++ prerr_string "; " in *)
+ let tyl = List.map repr tyl in
+- (* let tyl = List.filter is_aliased tyl in *)
+ if tyl = [] then tree_of_typexp sch ty else begin
+ let old_delayed = !delayed in
++ (* Make the names delayed, so that the real type is
++ printed once when used as proxy *)
+ List.iter add_delayed tyl;
+ let tl = List.map name_of_type tyl in
+ let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
++ (* Forget names when we leave scope *)
++ remove_names tyl;
+ delayed := old_delayed; tr
+ end
+- | Tunivar ->
++ | Tunivar _ ->
+ Otyp_var (false, name_of_type ty)
+ | Tpackage (p, n, tyl) ->
+ Otyp_module (Path.name p, n, tree_of_typlist sch tyl)
+@@ -446,13 +493,13 @@
+ end
+
+ and is_non_gen sch ty =
+- sch && ty.desc = Tvar && ty.level <> generic_level
++ sch && is_Tvar ty && ty.level <> generic_level
+
+ and tree_of_typfields sch rest = function
+ | [] ->
+ let rest =
+ match rest.desc with
+- | Tvar | Tunivar -> Some (is_non_gen sch rest)
++ | Tvar _ | Tunivar _ -> Some (is_non_gen sch rest)
+ | Tconstr _ -> Some false
+ | Tnil -> None
+ | _ -> fatal_error "typfields (1)"
+@@ -564,7 +611,7 @@
+ let vari =
+ List.map2
+ (fun ty (co,cn,ct) ->
+- if abstr || (repr ty).desc <> Tvar then (co,cn) else (true,true))
++ if abstr || not (is_Tvar (repr ty)) then (co,cn) else (true,true))
+ decl.type_params decl.type_variance
+ in
+ (Ident.name id,
+@@ -645,16 +692,18 @@
+
+ let method_type (_, kind, ty) =
+ match field_kind_repr kind, repr ty with
+- Fpresent, {desc=Tpoly(ty, _)} -> ty
+- | _ , ty -> ty
++ Fpresent, {desc=Tpoly(ty, tyl)} -> (ty, tyl)
++ | _ , ty -> (ty, [])
+
+ let tree_of_metho sch concrete csil (lab, kind, ty) =
+ if lab <> dummy_method then begin
+ let kind = field_kind_repr kind in
+ let priv = kind <> Fpresent in
+ let virt = not (Concr.mem lab concrete) in
+- let ty = method_type (lab, kind, ty) in
+- Ocsg_method (lab, priv, virt, tree_of_typexp sch ty) :: csil
++ let (ty, tyl) = method_type (lab, kind, ty) in
++ let tty = tree_of_typexp sch ty in
++ remove_names tyl;
++ Ocsg_method (lab, priv, virt, tty) :: csil
+ end
+ else csil
+
+@@ -662,7 +711,7 @@
+ | Tcty_constr (p, tyl, cty) ->
+ let sty = Ctype.self_type cty in
+ if List.memq (proxy sty) !visited_objects
+- || List.exists (fun ty -> (repr ty).desc <> Tvar) params
++ || not (List.for_all is_Tvar params)
+ || List.exists (deep_occur sty) tyl
+ then prepare_class_type params cty
+ else List.iter mark_loops tyl
+@@ -675,7 +724,7 @@
+ let (fields, _) =
+ Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
+ in
+- List.iter (fun met -> mark_loops (method_type met)) fields;
++ List.iter (fun met -> mark_loops (fst (method_type met))) fields;
+ Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.cty_vars
+ | Tcty_fun (_, ty, cty) ->
+ mark_loops ty;
+@@ -686,7 +735,7 @@
+ | Tcty_constr (p', tyl, cty) ->
+ let sty = Ctype.self_type cty in
+ if List.memq (proxy sty) !visited_objects
+- || List.exists (fun ty -> (repr ty).desc <> Tvar) params
++ || not (List.for_all is_Tvar params)
+ then
+ tree_of_class_type sch params cty
+ else
+@@ -743,7 +792,7 @@
+ (match tree_of_typexp true param with
+ Otyp_var (_, s) -> s
+ | _ -> "?"),
+- if (repr param).desc = Tvar then (true, true) else variance
++ if is_Tvar (repr param) then (true, true) else variance
+
+ let tree_of_class_params params =
+ let tyl = tree_of_typlist true params in
+@@ -890,7 +939,7 @@
+ | {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
+ newty2 t.level
+ (Tvariant {(row_repr row) with row_name = None;
+- row_more = newty2 (row_more row).level Tvar})
++ row_more = newvar2 (row_more row).level})
+ | _ -> t
+
+ let prepare_expansion (t, t') =
+@@ -913,9 +962,9 @@
+ let has_explanation unif t3 t4 =
+ match t3.desc, t4.desc with
+ Tfield _, _ | _, Tfield _
+- | Tunivar, Tvar | Tvar, Tunivar
++ | Tunivar _, Tvar _ | Tvar _, Tunivar _
+ | Tvariant _, Tvariant _ -> true
+- | Tconstr (p, _, _), Tvar | Tvar, Tconstr (p, _, _) ->
++ | Tconstr (p, _, _), Tvar _ | Tvar _, Tconstr (p, _, _) ->
+ unif && min t3.level t4.level < Path.binding_time p
+ | _ -> false
+
+@@ -931,21 +980,21 @@
+
+ let explanation unif t3 t4 ppf =
+ match t3.desc, t4.desc with
+- | Tfield _, Tvar | Tvar, Tfield _ ->
++ | Tfield _, Tvar _ | Tvar _, Tfield _ ->
+ fprintf ppf "@,Self type cannot escape its class"
+- | Tconstr (p, tl, _), Tvar
++ | Tconstr (p, tl, _), Tvar _
+ when unif && (tl = [] || t4.level < Path.binding_time p) ->
+ fprintf ppf
+ "@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
+ path p
+- | Tvar, Tconstr (p, tl, _)
++ | Tvar _, Tconstr (p, tl, _)
+ when unif && (tl = [] || t3.level < Path.binding_time p) ->
+ fprintf ppf
+ "@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
+ path p
+- | Tvar, Tunivar | Tunivar, Tvar ->
++ | Tvar _, Tunivar _ | Tunivar _, Tvar _ ->
+ fprintf ppf "@,The universal variable %a would escape its scope"
+- type_expr (if t3.desc = Tunivar then t3 else t4)
++ type_expr (if is_Tunivar t3 then t3 else t4)
+ | Tfield (lab, _, _, _), _
+ | _, Tfield (lab, _, _, _) when lab = dummy_method ->
+ fprintf ppf
+Index: typing/includecore.ml
+===================================================================
+--- typing/includecore.ml (リビジョン 11207)
++++ typing/includecore.ml (作業コピー)
+@@ -61,7 +61,7 @@
+ Tvariant row1, Tvariant row2 when is_absrow env (Btype.row_more row2) ->
+ let row1 = Btype.row_repr row1 and row2 = Btype.row_repr row2 in
+ Ctype.equal env true (ty1::params1) (row2.row_more::params2) &&
+- (match row1.row_more with {desc=Tvar|Tconstr _} -> true | _ -> false) &&
++ (match row1.row_more with {desc=Tvar _|Tconstr _} -> true | _ -> false) &&
+ let r1, r2, pairs =
+ Ctype.merge_row_fields row1.row_fields row2.row_fields in
+ (not row2.row_closed ||
+@@ -91,7 +91,7 @@
+ let (fields2,rest2) = Ctype.flatten_fields fi2 in
+ Ctype.equal env true (ty1::params1) (rest2::params2) &&
+ let (fields1,rest1) = Ctype.flatten_fields fi1 in
+- (match rest1 with {desc=Tnil|Tvar|Tconstr _} -> true | _ -> false) &&
++ (match rest1 with {desc=Tnil|Tvar _|Tconstr _} -> true | _ -> false) &&
+ let pairs, miss1, miss2 = Ctype.associate_fields fields1 fields2 in
+ miss2 = [] &&
+ let tl1, tl2 =
+@@ -251,7 +251,7 @@
+ let encode_val (mut, ty) rem =
+ begin match mut with
+ Asttypes.Mutable -> Predef.type_unit
+- | Asttypes.Immutable -> Btype.newgenty Tvar
++ | Asttypes.Immutable -> Btype.newgenvar ()
+ end
+ ::ty::rem
+
+Index: typing/subst.ml
+===================================================================
+--- typing/subst.ml (リビジョン 11207)
++++ typing/subst.ml (作業コピー)
+@@ -71,16 +71,19 @@
+ let reset_for_saving () = new_id := -1
+
+ let newpersty desc =
+- decr new_id; { desc = desc; level = generic_level; id = !new_id }
++ decr new_id;
++ { desc = desc; level = generic_level; id = !new_id }
+
+ (* Similar to [Ctype.nondep_type_rec]. *)
+ let rec typexp s ty =
+ let ty = repr ty in
+ match ty.desc with
+- Tvar | Tunivar ->
++ Tvar _ | Tunivar _ ->
+ if s.for_saving || ty.id < 0 then
++ let desc = match ty.desc with (* Tvar _ -> Tvar None *) | d -> d in
+ let ty' =
+- if s.for_saving then newpersty ty.desc else newty2 ty.level ty.desc
++ if s.for_saving then newpersty desc
++ else newty2 ty.level desc
+ in
+ save_desc ty ty.desc; ty.desc <- Tsubst ty'; ty'
+ else ty
+@@ -94,7 +97,7 @@
+ let desc = ty.desc in
+ save_desc ty desc;
+ (* Make a stub *)
+- let ty' = if s.for_saving then newpersty Tvar else newgenvar () in
++ let ty' = if s.for_saving then newpersty (Tvar None) else newgenvar () in
+ ty.desc <- Tsubst ty';
+ ty'.desc <-
+ begin match desc with
+@@ -127,10 +130,10 @@
+ match more.desc with
+ Tsubst ty -> ty
+ | Tconstr _ -> typexp s more
+- | Tunivar | Tvar ->
++ | Tunivar _ | Tvar _ ->
+ save_desc more more.desc;
+ if s.for_saving then newpersty more.desc else
+- if dup && more.desc <> Tunivar then newgenvar () else more
++ if dup && is_Tvar more then newgenty more.desc else more
+ | _ -> assert false
+ in
+ (* Register new type first for recursion *)
+Index: typing/types.ml
+===================================================================
+--- typing/types.ml (リビジョン 11207)
++++ typing/types.ml (作業コピー)
+@@ -25,7 +25,7 @@
+ mutable id: int }
+
+ and type_desc =
+- Tvar
++ Tvar of string option
+ | Tarrow of label * type_expr * type_expr * commutable
+ | Ttuple of type_expr list
+ | Tconstr of Path.t * type_expr list * abbrev_memo ref
+@@ -35,7 +35,7 @@
+ | Tlink of type_expr
+ | Tsubst of type_expr (* for copying *)
+ | Tvariant of row_desc
+- | Tunivar
++ | Tunivar of string option
+ | Tpoly of type_expr * type_expr list
+ | Tpackage of Path.t * string list * type_expr list
+
+Index: ocamldoc/odoc_str.ml
+===================================================================
+--- ocamldoc/odoc_str.ml (リビジョン 11207)
++++ ocamldoc/odoc_str.ml (作業コピー)
+@@ -31,7 +31,7 @@
+ | Types.Tlink t2 | Types.Tsubst t2 -> is_arrow_type t2
+ | Types.Ttuple _
+ | Types.Tconstr _
+- | Types.Tvar | Types.Tunivar | Types.Tobject _ | Types.Tpoly _
++ | Types.Tvar _ | Types.Tunivar _ | Types.Tobject _ | Types.Tpoly _
+ | Types.Tfield _ | Types.Tnil | Types.Tvariant _ | Types.Tpackage _ -> false
+
+ let raw_string_of_type_list sep type_list =
+@@ -43,7 +43,7 @@
+ | Types.Tlink t2 | Types.Tsubst t2 -> need_parent t2
+ | Types.Tconstr _ ->
+ false
+- | Types.Tvar | Types.Tunivar | Types.Tobject _ | Types.Tpoly _
++ | Types.Tvar _ | Types.Tunivar _ | Types.Tobject _ | Types.Tpoly _
+ | Types.Tfield _ | Types.Tnil | Types.Tvariant _ | Types.Tpackage _ -> false
+ in
+ let print_one_type variance t =
+Index: ocamldoc/odoc_value.ml
+===================================================================
+--- ocamldoc/odoc_value.ml (リビジョン 11207)
++++ ocamldoc/odoc_value.ml (作業コピー)
+@@ -77,13 +77,13 @@
+ | Types.Tsubst texp ->
+ iter texp
+ | Types.Tpoly (texp, _) -> iter texp
+- | Types.Tvar
++ | Types.Tvar _
+ | Types.Ttuple _
+ | Types.Tconstr _
+ | Types.Tobject _
+ | Types.Tfield _
+ | Types.Tnil
+- | Types.Tunivar
++ | Types.Tunivar _
+ | Types.Tpackage _
+ | Types.Tvariant _ ->
+ []
+Index: ocamldoc/odoc_misc.ml
+===================================================================
+--- ocamldoc/odoc_misc.ml (リビジョン 11207)
++++ ocamldoc/odoc_misc.ml (作業コピー)
+@@ -478,8 +478,8 @@
+ match t with
+ | Types.Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty.Types.desc
+ | Types.Tconstr _
+- | Types.Tvar
+- | Types.Tunivar
++ | Types.Tvar _
++ | Types.Tunivar _
+ | Types.Tpoly _
+ | Types.Tarrow _
+ | Types.Ttuple _
+Index: bytecomp/typeopt.ml
+===================================================================
+--- bytecomp/typeopt.ml (リビジョン 11207)
++++ bytecomp/typeopt.ml (作業コピー)
+@@ -50,7 +50,7 @@
+
+ let array_element_kind env ty =
+ match scrape env ty with
+- | Tvar | Tunivar ->
++ | Tvar _ | Tunivar _ ->
+ Pgenarray
+ | Tconstr(p, args, abbrev) ->
+ if Path.same p Predef.path_int || Path.same p Predef.path_char then
+Index: bytecomp/translcore.ml
+===================================================================
+--- bytecomp/translcore.ml (リビジョン 11207)
++++ bytecomp/translcore.ml (作業コピー)
+@@ -780,12 +780,13 @@
+ begin match e.exp_type.desc with
+ (* the following may represent a float/forward/lazy: need a
+ forward_tag *)
+- | Tvar | Tlink _ | Tsubst _ | Tunivar
++ | Tvar _ | Tlink _ | Tsubst _ | Tunivar _
+ | Tpoly(_,_) | Tfield(_,_,_,_) ->
+ Lprim(Pmakeblock(Obj.forward_tag, Immutable), [transl_exp e])
+ (* the following cannot be represented as float/forward/lazy:
+ optimize *)
+- | Tarrow(_,_,_,_) | Ttuple _ | Tpackage _ | Tobject(_,_) | Tnil | Tvariant _
++ | Tarrow(_,_,_,_) | Ttuple _ | Tpackage _ | Tobject(_,_) | Tnil
++ | Tvariant _
+ -> transl_exp e
+ (* optimize predefined types (excepted float) *)
+ | Tconstr(_,_,_) ->
+Index: testsuite/tests/lib-hashtbl/htbl.ml
+===================================================================
+--- testsuite/tests/lib-hashtbl/htbl.ml (リビジョン 11207)
++++ testsuite/tests/lib-hashtbl/htbl.ml (作業コピー)
+@@ -76,7 +76,7 @@
+ struct
+ type key = M.key
+ type 'a t = (key, 'a) Hashtbl.t
+- let create = Hashtbl.create
++ let create s = Hashtbl.create s
+ let clear = Hashtbl.clear
+ let copy = Hashtbl.copy
+ let add = Hashtbl.add
+Index: toplevel/genprintval.ml
+===================================================================
+--- toplevel/genprintval.ml (リビジョン 11207)
++++ toplevel/genprintval.ml (作業コピー)
+@@ -180,7 +180,7 @@
+ find_printer env ty obj
+ with Not_found ->
+ match (Ctype.repr ty).desc with
+- | Tvar ->
++ | Tvar _ | Tunivar _ ->
+ Oval_stuff "<poly>"
+ | Tarrow(_, ty1, ty2, _) ->
+ Oval_stuff "<fun>"
+@@ -327,8 +327,6 @@
+ fatal_error "Printval.outval_of_value"
+ | Tpoly (ty, _) ->
+ tree_of_val (depth - 1) obj ty
+- | Tunivar ->
+- Oval_stuff "<poly>"
+ | Tpackage _ ->
+ Oval_stuff "<module>"
+ end
+Index: otherlibs/labltk/browser/searchid.ml
+===================================================================
+--- otherlibs/labltk/browser/searchid.ml (リビジョン 11207)
++++ otherlibs/labltk/browser/searchid.ml (作業コピー)
+@@ -101,7 +101,7 @@
+
+ let rec equal ~prefix t1 t2 =
+ match (repr t1).desc, (repr t2).desc with
+- Tvar, Tvar -> true
++ Tvar _, Tvar _ -> true
+ | Tvariant row1, Tvariant row2 ->
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let fields1 = filter_row_fields false row1.row_fields
+@@ -144,7 +144,7 @@
+
+ let rec included ~prefix t1 t2 =
+ match (repr t1).desc, (repr t2).desc with
+- Tvar, _ -> true
++ Tvar _, _ -> true
+ | Tvariant row1, Tvariant row2 ->
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let fields1 = filter_row_fields false row1.row_fields
diff --git a/experimental/garrigue/variable-names.ml b/experimental/garrigue/variable-names.ml
new file mode 100644
index 0000000000..f3c7771a73
--- /dev/null
+++ b/experimental/garrigue/variable-names.ml
@@ -0,0 +1,4 @@
+let f (x : < a:int; .. > as 'me1) = (x : < b:bool; .. > as 'me2);;
+let f (x : < a:int; .. > as 'me1) = (x : < a:int; b:bool; .. > as 'me2);;
+let f (x : [> `A of int] as 'me1) = (x : [> `B of bool] as 'me2);;
+let f (x : [> `A of int] as 'me1) = (x : [`A of int | `B of 'me2] as 'me2);;
diff --git a/experimental/garrigue/varunion.ml b/experimental/garrigue/varunion.ml
new file mode 100644
index 0000000000..41dca65f2f
--- /dev/null
+++ b/experimental/garrigue/varunion.ml
@@ -0,0 +1,435 @@
+(* cvs update -r varunion parsing typing bytecomp toplevel *)
+
+type t = private [> ];;
+type u = private [> ] ~ [t];;
+type v = [t | u];;
+let f x = (x : t :> v);;
+
+(* bad *)
+module Mix(X: sig type t = private [> ] end)
+ (Y: sig type t = private [> ] end) =
+ struct type t = [X.t | Y.t] end;;
+
+(* bad *)
+module Mix(X: sig type t = private [> `A of int ] end)
+ (Y: sig type t = private [> `A of bool] ~ [X.t] end) =
+ struct type t = [X.t | Y.t] end;;
+
+(* ok *)
+module Mix(X: sig type t = private [> `A of int ] end)
+ (Y: sig type t = private [> `A of int] ~ [X.t] end) =
+ struct type t = [X.t | Y.t] end;;
+
+(* bad *)
+module Mix(X: sig type t = private [> `A of int ] end)
+ (Y: sig type t = private [> `B of bool] ~ [X.t] end) =
+ struct type t = [X.t | Y.t] end;;
+
+type 'a t = private [> `L of 'a] ~ [`L];;
+
+(* ok *)
+module Mix(X: sig type t = private [> `A of int ] ~ [`B] end)
+ (Y: sig type t = private [> `B of bool] ~ [X.t] end) =
+ struct type t = [X.t | Y.t] let is_t = function #t -> true | _ -> false end;;
+
+module Mix(X: sig type t = private [> `A of int ] ~ [`B] end)
+ (Y: sig type t = private [> `B of bool] ~ [X.t] end) =
+ struct
+ type t = [X.t | Y.t]
+ let which = function #X.t -> `X | #Y.t -> `Y
+ end;;
+
+module Mix(I: sig type t = private [> ] ~ [`A;`B] end)
+ (X: sig type t = private [> I.t | `A of int ] ~ [`B] end)
+ (Y: sig type t = private [> I.t | `B of bool] ~ [X.t] end) =
+ struct
+ type t = [X.t | Y.t]
+ let which = function #X.t -> `X | #Y.t -> `Y
+ end;;
+
+(* ok *)
+module M =
+ Mix(struct type t = [`C of char] end)
+ (struct type t = [`A of int | `C of char] end)
+ (struct type t = [`B of bool | `C of char] end);;
+
+(* bad *)
+module M =
+ Mix(struct type t = [`B of bool] end)
+ (struct type t = [`A of int | `B of bool] end)
+ (struct type t = [`B of bool | `C of char] end);;
+
+(* ok *)
+module M1 = struct type t = [`A of int | `C of char] end
+module M2 = struct type t = [`B of bool | `C of char] end
+module I = struct type t = [`C of char] end
+module M = Mix(I)(M1)(M2) ;;
+
+let c = (`C 'c' : M.t) ;;
+
+module M(X : sig type t = private [> `A] end) =
+ struct let f (#X.t as x) = x end;;
+
+(* code generation *)
+type t = private [> `A ] ~ [`B];;
+match `B with #t -> 1 | `B -> 2;;
+
+module M : sig type t = private [> `A of int | `B] ~ [`C] end =
+ struct type t = [`A of int | `B | `D of bool] end;;
+let f = function (`C | #M.t) -> 1+1 ;;
+let f = function (`A _ | `B #M.t) -> 1+1 ;;
+
+(* expression *)
+module Mix(X:sig type t = private [> ] val show: t -> string end)
+ (Y:sig type t = private [> ] ~ [X.t] val show: t -> string end) =
+ struct
+ type t = [X.t | Y.t]
+ let show : t -> string = function
+ #X.t as x -> X.show x
+ | #Y.t as y -> Y.show y
+ end;;
+
+module EStr = struct
+ type t = [`Str of string]
+ let show (`Str s) = s
+end
+module EInt = struct
+ type t = [`Int of int]
+ let show (`Int i) = string_of_int i
+end
+module M = Mix(EStr)(EInt);;
+
+module type T = sig type t = private [> ] val show: t -> string end
+module Mix(X:T)(Y:T with type t = private [> ] ~ [X.t]) :
+ T with type t = [X.t | Y.t] =
+ struct
+ type t = [X.t | Y.t]
+ let show = function
+ #X.t as x -> X.show x
+ | #Y.t as y -> Y.show y
+ end;;
+module M = Mix(EStr)(EInt);;
+
+(* deep *)
+module M : sig type t = private [> `A] end = struct type t = [`A] end
+module M' : sig type t = private [> ] end = struct type t = [M.t | `A] end;;
+
+(* bad *)
+type t = private [> ]
+type u = private [> `A of int] ~ [t] ;;
+
+(* ok *)
+type t = private [> `A of int]
+type u = private [> `A of int] ~ [t] ;;
+
+module F(X: sig
+ type t = private [> ] ~ [`A;`B;`C;`D]
+ type u = private [> `A|`B|`C] ~ [t; `D]
+end) : sig type v = private [< X.t | X.u | `D] end = struct
+ open X
+ let f = function #u -> 1 | #t -> 2 | `D -> 3
+ let g = function #u|#t|`D -> 2
+ type v = [t|u|`D]
+end
+
+(* ok *)
+module M = struct type t = private [> `A] end;;
+module M' : sig type t = private [> ] ~ [`A] end = M;;
+
+(* ok *)
+module type T = sig type t = private [> ] ~ [`A] end;;
+module type T' = T with type t = private [> `A];;
+
+(* ok *)
+type t = private [> ] ~ [`A]
+let f = function `A x -> x | #t -> 0
+type t' = private [< `A of int | t];;
+
+(* should be ok *)
+module F(X:sig end) :
+ sig type t = private [> ] type u = private [> ] ~ [t] end =
+ struct type t = [ `A] type u = [`B] end
+module M = F(String)
+let f = function #M.t -> 1 | #M.u -> 2
+let f = function #M.t -> 1 | _ -> 2
+type t = [M.t | M.u]
+let f = function #t -> 1 | _ -> 2;;
+module G(X : sig type t = private [> ] type u = private [> ] ~ [t] end) =
+ struct let f = function #X.t -> 1 | _ -> 2 end;;
+module M1 = G(struct module N = F(String) type t = N.t type u = N.u end) ;;
+module M1 = G(struct type t = M.t type u = M.u end) ;;
+(* bad *)
+let f = function #F(String).t -> 1 | _ -> 2;;
+type t = [F(String).t | M.u]
+let f = function #t -> 1 | _ -> 2;;
+module N : sig type t = private [> ] end =
+ struct type t = [F(String).t | M.u] end;;
+
+(* compatibility improvement *)
+type a = [`A of int | `B]
+type b = [`A of bool | `B]
+type c = private [> ] ~ [a;b]
+let f = function #c -> 1 | `A x -> truncate x
+type d = private [> ] ~ [a]
+let g = function #d -> 1 | `A x -> truncate x;;
+
+
+(* Expression Problem: functorial form *)
+
+type num = [ `Num of int ]
+
+module type Exp = sig
+ type t = private [> num]
+ val eval : t -> t
+ val show : t -> string
+end
+
+module Num(X : Exp) = struct
+ type t = num
+ let eval (`Num _ as x) : X.t = x
+ let show (`Num n) = string_of_int n
+end
+
+type 'a add = [ `Add of 'a * 'a ]
+
+module Add(X : Exp with type t = private [> num | 'a add] as 'a) = struct
+ type t = X.t add
+ let show (`Add(e1, e2) : t) = "("^ X.show e1 ^"+"^ X.show e2 ^")"
+ let eval (`Add(e1, e2) : t) =
+ let e1 = X.eval e1 and e2 = X.eval e2 in
+ match e1, e2 with
+ `Num n1, `Num n2 -> `Num (n1+n2)
+ | `Num 0, e | e, `Num 0 -> e
+ | e12 -> `Add e12
+end
+
+type 'a mul = [`Mul of 'a * 'a]
+
+module Mul(X : Exp with type t = private [> num | 'a mul] as 'a) = struct
+ type t = X.t mul
+ let show (`Mul(e1, e2) : t) = "("^ X.show e1 ^"*"^ X.show e2 ^")"
+ let eval (`Mul(e1, e2) : t) =
+ let e1 = X.eval e1 and e2 = X.eval e2 in
+ match e1, e2 with
+ `Num n1, `Num n2 -> `Num (n1*n2)
+ | `Num 0, e | e, `Num 0 -> `Num 0
+ | `Num 1, e | e, `Num 1 -> e
+ | e12 -> `Mul e12
+end
+
+module Ext(X : sig type t = private [> ] end)(Y : sig type t end) = struct
+ module type S =
+ sig
+ type t = private [> ] ~ [ X.t ]
+ val eval : t -> Y.t
+ val show : t -> string
+ end
+end
+
+module Dummy = struct type t = [`Dummy] end
+
+module Mix(E : Exp)(E1 : Ext(Dummy)(E).S)(E2 : Ext(E1)(E).S) =
+ struct
+ type t = [E1.t | E2.t]
+ let eval = function
+ #E1.t as x -> E1.eval x
+ | #E2.t as x -> E2.eval x
+ let show = function
+ #E1.t as x -> E1.show x
+ | #E2.t as x -> E2.show x
+ end
+
+module rec EAdd : (Exp with type t = [num | EAdd.t add]) =
+ Mix(EAdd)(Num(EAdd))(Add(EAdd))
+
+(* A bit heavy: one must pass E to everybody *)
+module rec E : Exp with type t = [num | E.t add | E.t mul] =
+ Mix(E)(Mix(E)(Num(E))(Add(E)))(Mul(E))
+
+let e = E.eval (`Add(`Mul(`Num 2,`Num 3),`Num 1))
+
+(* Alternatives *)
+(* Direct approach, no need of Mix *)
+module rec E : (Exp with type t = [num | E.t add | E.t mul]) =
+ struct
+ module E1 = Num(E)
+ module E2 = Add(E)
+ module E3 = Mul(E)
+ type t = E.t
+ let show = function
+ | #num as x -> E1.show x
+ | #add as x -> E2.show x
+ | #mul as x -> E3.show x
+ let eval = function
+ | #num as x -> E1.eval x
+ | #add as x -> E2.eval x
+ | #mul as x -> E3.eval x
+ end
+
+(* Do functor applications in Mix *)
+module type T = sig type t = private [> ] end
+module type Tnum = sig type t = private [> num] end
+
+module Ext(E : Tnum) = struct
+ module type S = functor (Y : Exp with type t = E.t) ->
+ sig
+ type t = private [> num]
+ val eval : t -> Y.t
+ val show : t -> string
+ end
+end
+
+module Ext'(E : Tnum)(X : T) = struct
+ module type S = functor (Y : Exp with type t = E.t) ->
+ sig
+ type t = private [> ] ~ [ X.t ]
+ val eval : t -> Y.t
+ val show : t -> string
+ end
+end
+
+module Mix(E : Exp)(F1 : Ext(E).S)(F2 : Ext'(E)(F1(E)).S) =
+ struct
+ module E1 = F1(E)
+ module E2 = F2(E)
+ type t = [E1.t | E2.t]
+ let eval = function
+ #E1.t as x -> E1.eval x
+ | #E2.t as x -> E2.eval x
+ let show = function
+ #E1.t as x -> E1.show x
+ | #E2.t as x -> E2.show x
+ end
+
+module Join(E : Exp)(F1 : Ext(E).S)(F2 : Ext'(E)(F1(E)).S)
+ (E' : Exp with type t = E.t) =
+ Mix(E)(F1)(F2)
+
+module rec EAdd : (Exp with type t = [num | EAdd.t add]) =
+ Mix(EAdd)(Num)(Add)
+
+module rec EMul : (Exp with type t = [num | EMul.t mul]) =
+ Mix(EMul)(Num)(Mul)
+
+module rec E : (Exp with type t = [num | E.t add | E.t mul]) =
+ Mix(E)(Join(E)(Num)(Add))(Mul)
+
+(* Linear extension by the end: not so nice *)
+module LExt(X : T) = struct
+ module type S =
+ sig
+ type t
+ val eval : t -> X.t
+ val show : t -> string
+ end
+end
+module LNum(E: Exp)(X : LExt(E).S with type t = private [> ] ~ [num]) =
+ struct
+ type t = [num | X.t]
+ let show = function
+ `Num n -> string_of_int n
+ | #X.t as x -> X.show x
+ let eval = function
+ #num as x -> x
+ | #X.t as x -> X.eval x
+ end
+module LAdd(E : Exp with type t = private [> num | 'a add] as 'a)
+ (X : LExt(E).S with type t = private [> ] ~ [add]) =
+ struct
+ type t = [E.t add | X.t]
+ let show = function
+ `Add(e1,e2) -> "("^ E.show e1 ^"+"^ E.show e2 ^")"
+ | #X.t as x -> X.show x
+ let eval = function
+ `Add(e1,e2) ->
+ let e1 = E.eval e1 and e2 = E.eval e2 in
+ begin match e1, e2 with
+ `Num n1, `Num n2 -> `Num (n1+n2)
+ | `Num 0, e | e, `Num 0 -> e
+ | e12 -> `Add e12
+ end
+ | #X.t as x -> X.eval x
+ end
+module LEnd = struct
+ type t = [`Dummy]
+ let show `Dummy = ""
+ let eval `Dummy = `Dummy
+end
+module rec L : Exp with type t = [num | L.t add | `Dummy] =
+ LAdd(L)(LNum(L)(LEnd))
+
+(* Back to first form, but add map *)
+
+module Num(X : Exp) = struct
+ type t = num
+ let map f x = x
+ let eval1 (`Num _ as x) : X.t = x
+ let show (`Num n) = string_of_int n
+end
+
+module Add(X : Exp with type t = private [> num | 'a add] as 'a) = struct
+ type t = X.t add
+ let show (`Add(e1, e2) : t) = "("^ X.show e1 ^"+"^ X.show e2 ^")"
+ let map f (`Add(e1, e2) : t) = `Add(f e1, f e2)
+ let eval1 (`Add(e1, e2) as e : t) =
+ match e1, e2 with
+ `Num n1, `Num n2 -> `Num (n1+n2)
+ | `Num 0, e | e, `Num 0 -> e
+ | _ -> e
+end
+
+module Mul(X : Exp with type t = private [> num | 'a mul] as 'a) = struct
+ type t = X.t mul
+ let show (`Mul(e1, e2) : t) = "("^ X.show e1 ^"*"^ X.show e2 ^")"
+ let map f (`Mul(e1, e2) : t) = `Mul(f e1, f e2)
+ let eval1 (`Mul(e1, e2) as e : t) =
+ match e1, e2 with
+ `Num n1, `Num n2 -> `Num (n1*n2)
+ | `Num 0, e | e, `Num 0 -> `Num 0
+ | `Num 1, e | e, `Num 1 -> e
+ | _ -> e
+end
+
+module Ext(X : sig type t = private [> ] end)(Y : sig type t end) = struct
+ module type S =
+ sig
+ type t = private [> ] ~ [ X.t ]
+ val map : (Y.t -> Y.t) -> t -> t
+ val eval1 : t -> Y.t
+ val show : t -> string
+ end
+end
+
+module Mix(E : Exp)(E1 : Ext(Dummy)(E).S)(E2 : Ext(E1)(E).S) =
+ struct
+ type t = [E1.t | E2.t]
+ let map f = function
+ #E1.t as x -> (E1.map f x : E1.t :> t)
+ | #E2.t as x -> (E2.map f x : E2.t :> t)
+ let eval1 = function
+ #E1.t as x -> E1.eval1 x
+ | #E2.t as x -> E2.eval1 x
+ let show = function
+ #E1.t as x -> E1.show x
+ | #E2.t as x -> E2.show x
+ end
+
+module type ET = sig
+ type t
+ val map : (t -> t) -> t -> t
+ val eval1 : t -> t
+ val show : t -> string
+end
+
+module Fin(E : ET) = struct
+ include E
+ let rec eval e = eval1 (map eval e)
+end
+
+module rec EAdd : (Exp with type t = [num | EAdd.t add]) =
+ Fin(Mix(EAdd)(Num(EAdd))(Add(EAdd)))
+
+module rec E : Exp with type t = [num | E.t add | E.t mul] =
+ Fin(Mix(E)(Mix(E)(Num(E))(Add(E)))(Mul(E)))
+
+let e = E.eval (`Add(`Mul(`Num 2,`Num 3),`Num 1))
diff --git a/experimental/garrigue/with-module-type.diff b/experimental/garrigue/with-module-type.diff
new file mode 100644
index 0000000000..2b99c1f9ed
--- /dev/null
+++ b/experimental/garrigue/with-module-type.diff
@@ -0,0 +1,530 @@
+Index: typing/typemod.ml
+===================================================================
+--- typing/typemod.ml (revision 13947)
++++ typing/typemod.ml (working copy)
+@@ -80,6 +80,9 @@
+ Typedtree.module_expr * Types.module_type) ref
+ = ref (fun env m -> assert false)
+
++let transl_modtype_fwd =
++ ref (fun env m -> (assert false : Typedtree.module_type))
++
+ (* Merge one "with" constraint in a signature *)
+
+ let rec add_rec_types env = function
+@@ -191,6 +194,21 @@
+ merge env (extract_sig env loc mty) namelist None in
+ (path_concat id path, lid, tcstr),
+ Sig_module(id, Mty_signature newsg, rs) :: rem
++ | (Sig_modtype(id, mtd) :: rem, [s], Pwith_modtype pmty)
++ when Ident.name id = s ->
++ let mty = !transl_modtype_fwd initial_env pmty in
++ let mtd' = Modtype_manifest mty.mty_type in
++ Includemod.modtype_declarations env id mtd' mtd;
++ (Pident id, lid, Twith_modtype (Tmodtype_manifest mty)),
++ Sig_modtype(id, mtd') :: rem
++ | (Sig_modtype(id, mtd) :: rem, [s], Pwith_modtypesubst pmty)
++ when Ident.name id = s ->
++ let mty = !transl_modtype_fwd initial_env pmty in
++ let mtd' = Modtype_manifest mty.mty_type in
++ Includemod.modtype_declarations env id mtd' mtd;
++ real_id := Some id;
++ (Pident id, lid, Twith_modtypesubst (Tmodtype_manifest mty)),
++ rem
+ | (item :: rem, _, _) ->
+ let (cstr, items) = merge (Env.add_item item env) rem namelist row_id
+ in
+@@ -233,6 +251,12 @@
+ let (path, _) = Typetexp.find_module initial_env loc lid.txt in
+ let sub = Subst.add_module id path Subst.identity in
+ Subst.signature sub sg
++ | [s], Pwith_modtypesubst pmty ->
++ let id =
++ match !real_id with None -> assert false | Some id -> id in
++ let mty = !transl_modtype_fwd initial_env pmty in
++ let sub = Subst.add_modtype id mty.mty_type Subst.identity in
++ Subst.signature sub sg
+ | _ ->
+ sg
+ in
+@@ -649,6 +673,8 @@
+ check_recmod_typedecls env2 sdecls dcl2;
+ (dcl2, env2)
+
++let () = transl_modtype_fwd := transl_modtype
++
+ (* Try to convert a module expression to a module path. *)
+
+ exception Not_a_path
+Index: typing/typedtreeMap.ml
+===================================================================
+--- typing/typedtreeMap.ml (revision 13947)
++++ typing/typedtreeMap.ml (working copy)
+@@ -457,6 +457,9 @@
+ | Twith_typesubst decl -> Twith_typesubst (map_type_declaration decl)
+ | Twith_module (path, lid) -> cstr
+ | Twith_modsubst (path, lid) -> cstr
++ | Twith_modtype decl -> Twith_modtype (map_modtype_declaration decl)
++ | Twith_modtypesubst decl ->
++ Twith_modtypesubst (map_modtype_declaration decl)
+ in
+ Map.leave_with_constraint cstr
+
+Index: typing/typedtree.ml
+===================================================================
+--- typing/typedtree.ml (revision 13947)
++++ typing/typedtree.ml (working copy)
+@@ -255,6 +255,8 @@
+ | Twith_module of Path.t * Longident.t loc
+ | Twith_typesubst of type_declaration
+ | Twith_modsubst of Path.t * Longident.t loc
++ | Twith_modtype of modtype_declaration
++ | Twith_modtypesubst of modtype_declaration
+
+ and core_type =
+ (* mutable because of [Typeclass.declare_method] *)
+Index: typing/typedtree.mli
+===================================================================
+--- typing/typedtree.mli (revision 13947)
++++ typing/typedtree.mli (working copy)
+@@ -254,6 +254,8 @@
+ | Twith_module of Path.t * Longident.t loc
+ | Twith_typesubst of type_declaration
+ | Twith_modsubst of Path.t * Longident.t loc
++ | Twith_modtype of modtype_declaration
++ | Twith_modtypesubst of modtype_declaration
+
+ and core_type =
+ (* mutable because of [Typeclass.declare_method] *)
+Index: typing/includemod.ml
+===================================================================
+--- typing/includemod.ml (revision 13947)
++++ typing/includemod.ml (working copy)
+@@ -346,10 +346,10 @@
+
+ (* Hide the context and substitution parameters to the outside world *)
+
+-let modtypes env mty1 mty2 = modtypes env [] Subst.identity mty1 mty2
+-let signatures env sig1 sig2 = signatures env [] Subst.identity sig1 sig2
+-let type_declarations env id decl1 decl2 =
+- type_declarations env [] Subst.identity id decl1 decl2
++let modtypes env = modtypes env [] Subst.identity
++let signatures env = signatures env [] Subst.identity
++let type_declarations env = type_declarations env [] Subst.identity
++let modtype_declarations env = modtype_infos env [] Subst.identity
+
+ (* Error report *)
+
+Index: typing/typedtreeIter.ml
+===================================================================
+--- typing/typedtreeIter.ml (revision 13947)
++++ typing/typedtreeIter.ml (working copy)
+@@ -408,6 +408,8 @@
+ | Twith_module _ -> ()
+ | Twith_typesubst decl -> iter_type_declaration decl
+ | Twith_modsubst _ -> ()
++ | Twith_modtype decl -> iter_modtype_declaration decl
++ | Twith_modtypesubst decl -> iter_modtype_declaration decl
+ end;
+ Iter.leave_with_constraint cstr;
+
+Index: typing/includemod.mli
+===================================================================
+--- typing/includemod.mli (revision 13947)
++++ typing/includemod.mli (working copy)
+@@ -21,6 +21,8 @@
+ val compunit: string -> signature -> string -> signature -> module_coercion
+ val type_declarations:
+ Env.t -> Ident.t -> type_declaration -> type_declaration -> unit
++val modtype_declarations:
++ Env.t -> Ident.t -> modtype_declaration -> modtype_declaration -> unit
+
+ type symptom =
+ Missing_field of Ident.t
+Index: typing/printtyped.ml
+===================================================================
+--- typing/printtyped.ml (revision 13947)
++++ typing/printtyped.ml (working copy)
+@@ -608,6 +608,12 @@
+ type_declaration (i+1) ppf td;
+ | Twith_module (li,_) -> line i ppf "Pwith_module %a\n" fmt_path li;
+ | Twith_modsubst (li,_) -> line i ppf "Pwith_modsubst %a\n" fmt_path li;
++ | Twith_modtype (td) ->
++ line i ppf "Pwith_modtype\n";
++ modtype_declaration (i+1) ppf td;
++ | Twith_modtypesubst (td) ->
++ line i ppf "Pwith_modtypesubst\n";
++ modtype_declaration (i+1) ppf td;
+
+ and module_expr i ppf x =
+ line i ppf "module_expr %a\n" fmt_location x.mod_loc;
+Index: experimental/garrigue/with-module-type.diffs
+===================================================================
+--- experimental/garrigue/with-module-type.diffs (revision 13947)
++++ experimental/garrigue/with-module-type.diffs (working copy)
+@@ -1,95 +1,53 @@
+-Index: parsing/parser.mly
+-===================================================================
+---- parsing/parser.mly (revision 12005)
+-+++ parsing/parser.mly (working copy)
+-@@ -1504,6 +1504,10 @@
+- { ($2, Pwith_module $4) }
+- | MODULE mod_longident COLONEQUAL mod_ext_longident
+- { ($2, Pwith_modsubst $4) }
+-+ | MODULE TYPE mod_longident EQUAL module_type
+-+ { ($3, Pwith_modtype $5) }
+-+ | MODULE TYPE mod_longident COLONEQUAL module_type
+-+ { ($3, Pwith_modtypesubst $5) }
+- ;
+- with_type_binder:
+- EQUAL { Public }
+-Index: parsing/parsetree.mli
+-===================================================================
+---- parsing/parsetree.mli (revision 12005)
+-+++ parsing/parsetree.mli (working copy)
+-@@ -239,6 +239,8 @@
+- | Pwith_module of Longident.t
+- | Pwith_typesubst of type_declaration
+- | Pwith_modsubst of Longident.t
+-+ | Pwith_modtype of module_type
+-+ | Pwith_modtypesubst of module_type
+-
+- (* Value expressions for the module language *)
+-
+-Index: parsing/printast.ml
+-===================================================================
+---- parsing/printast.ml (revision 12005)
+-+++ parsing/printast.ml (working copy)
+-@@ -575,6 +575,12 @@
+- type_declaration (i+1) ppf td;
+- | Pwith_module (li) -> line i ppf "Pwith_module %a\n" fmt_longident li;
+- | Pwith_modsubst (li) -> line i ppf "Pwith_modsubst %a\n" fmt_longident li;
+-+ | Pwith_modtype (mty) ->
+-+ line i ppf "Pwith_modtype\n";
+-+ module_type (i+1) ppf mty;
+-+ | Pwith_modtypesubst (mty) ->
+-+ line i ppf "Pwith_modtype\n";
+-+ module_type (i+1) ppf mty;
+-
+- and module_expr i ppf x =
+- line i ppf "module_expr %a\n" fmt_location x.pmod_loc;
+ Index: typing/typemod.ml
+ ===================================================================
+---- typing/typemod.ml (revision 12005)
++--- typing/typemod.ml (revision 13947)
+ +++ typing/typemod.ml (working copy)
+-@@ -74,6 +74,8 @@
+- : (Env.t -> Parsetree.module_expr -> module_type) ref
++@@ -80,6 +80,9 @@
++ Typedtree.module_expr * Types.module_type) ref
+ = ref (fun env m -> assert false)
+
+-+let transl_modtype_fwd = ref (fun env m -> assert false)
+++let transl_modtype_fwd =
+++ ref (fun env m -> (assert false : Typedtree.module_type))
+ +
+ (* Merge one "with" constraint in a signature *)
+
+ let rec add_rec_types env = function
+-@@ -163,6 +165,19 @@
+- ignore(Includemod.modtypes env newmty mty);
+- real_id := Some id;
+- make_next_first rs rem
+-+ | (Tsig_modtype(id, mtd) :: rem, [s], Pwith_modtype pmty)
++@@ -191,6 +194,21 @@
++ merge env (extract_sig env loc mty) namelist None in
++ (path_concat id path, lid, tcstr),
++ Sig_module(id, Mty_signature newsg, rs) :: rem
+++ | (Sig_modtype(id, mtd) :: rem, [s], Pwith_modtype pmty)
+ + when Ident.name id = s ->
+ + let mty = !transl_modtype_fwd initial_env pmty in
+-+ let mtd' = Tmodtype_manifest mty in
+++ let mtd' = Modtype_manifest mty.mty_type in
+ + Includemod.modtype_declarations env id mtd' mtd;
+-+ Tsig_modtype(id, mtd') :: rem
+-+ | (Tsig_modtype(id, mtd) :: rem, [s], Pwith_modtypesubst pmty)
+++ (Pident id, lid, Twith_modtype (Tmodtype_manifest mty)),
+++ Sig_modtype(id, mtd') :: rem
+++ | (Sig_modtype(id, mtd) :: rem, [s], Pwith_modtypesubst pmty)
+ + when Ident.name id = s ->
+ + let mty = !transl_modtype_fwd initial_env pmty in
+-+ let mtd' = Tmodtype_manifest mty in
+++ let mtd' = Modtype_manifest mty.mty_type in
+ + Includemod.modtype_declarations env id mtd' mtd;
+ + real_id := Some id;
+++ (Pident id, lid, Twith_modtypesubst (Tmodtype_manifest mty)),
+ + rem
+- | (Tsig_module(id, mty, rs) :: rem, s :: namelist, _)
+- when Ident.name id = s ->
+- let newsg = merge env (extract_sig env loc mty) namelist None in
+-@@ -200,6 +215,12 @@
+- let (path, _) = Typetexp.find_module initial_env loc lid in
++ | (item :: rem, _, _) ->
++ let (cstr, items) = merge (Env.add_item item env) rem namelist row_id
++ in
++@@ -233,6 +251,12 @@
++ let (path, _) = Typetexp.find_module initial_env loc lid.txt in
+ let sub = Subst.add_module id path Subst.identity in
+ Subst.signature sub sg
+ + | [s], Pwith_modtypesubst pmty ->
+ + let id =
+ + match !real_id with None -> assert false | Some id -> id in
+ + let mty = !transl_modtype_fwd initial_env pmty in
+-+ let sub = Subst.add_modtype id mty Subst.identity in
+++ let sub = Subst.add_modtype id mty.mty_type Subst.identity in
+ + Subst.signature sub sg
+ | _ ->
+- sg
+- with Includemod.Error explanation ->
+-@@ -499,6 +520,8 @@
++ sg
++ in
++@@ -649,6 +673,8 @@
+ check_recmod_typedecls env2 sdecls dcl2;
+ (dcl2, env2)
+
+@@ -98,11 +56,51 @@
+ (* Try to convert a module expression to a module path. *)
+
+ exception Not_a_path
++Index: typing/typedtreeMap.ml
++===================================================================
++--- typing/typedtreeMap.ml (revision 13947)
+++++ typing/typedtreeMap.ml (working copy)
++@@ -457,6 +457,9 @@
++ | Twith_typesubst decl -> Twith_typesubst (map_type_declaration decl)
++ | Twith_module (path, lid) -> cstr
++ | Twith_modsubst (path, lid) -> cstr
+++ | Twith_modtype decl -> Twith_modtype (map_modtype_declaration decl)
+++ | Twith_modtypesubst decl ->
+++ Twith_modtypesubst (map_modtype_declaration decl)
++ in
++ Map.leave_with_constraint cstr
++
++Index: typing/typedtree.ml
++===================================================================
++--- typing/typedtree.ml (revision 13947)
+++++ typing/typedtree.ml (working copy)
++@@ -255,6 +255,8 @@
++ | Twith_module of Path.t * Longident.t loc
++ | Twith_typesubst of type_declaration
++ | Twith_modsubst of Path.t * Longident.t loc
+++ | Twith_modtype of modtype_declaration
+++ | Twith_modtypesubst of modtype_declaration
++
++ and core_type =
++ (* mutable because of [Typeclass.declare_method] *)
++Index: typing/typedtree.mli
++===================================================================
++--- typing/typedtree.mli (revision 13947)
+++++ typing/typedtree.mli (working copy)
++@@ -254,6 +254,8 @@
++ | Twith_module of Path.t * Longident.t loc
++ | Twith_typesubst of type_declaration
++ | Twith_modsubst of Path.t * Longident.t loc
+++ | Twith_modtype of modtype_declaration
+++ | Twith_modtypesubst of modtype_declaration
++
++ and core_type =
++ (* mutable because of [Typeclass.declare_method] *)
+ Index: typing/includemod.ml
+ ===================================================================
+---- typing/includemod.ml (revision 12005)
++--- typing/includemod.ml (revision 13947)
+ +++ typing/includemod.ml (working copy)
+-@@ -326,10 +326,10 @@
++@@ -346,10 +346,10 @@
+
+ (* Hide the context and substitution parameters to the outside world *)
+
+@@ -117,11 +115,24 @@
+
+ (* Error report *)
+
++Index: typing/typedtreeIter.ml
++===================================================================
++--- typing/typedtreeIter.ml (revision 13947)
+++++ typing/typedtreeIter.ml (working copy)
++@@ -408,6 +408,8 @@
++ | Twith_module _ -> ()
++ | Twith_typesubst decl -> iter_type_declaration decl
++ | Twith_modsubst _ -> ()
+++ | Twith_modtype decl -> iter_modtype_declaration decl
+++ | Twith_modtypesubst decl -> iter_modtype_declaration decl
++ end;
++ Iter.leave_with_constraint cstr;
++
+ Index: typing/includemod.mli
+ ===================================================================
+---- typing/includemod.mli (revision 12005)
++--- typing/includemod.mli (revision 13947)
+ +++ typing/includemod.mli (working copy)
+-@@ -23,6 +23,8 @@
++@@ -21,6 +21,8 @@
+ val compunit: string -> signature -> string -> signature -> module_coercion
+ val type_declarations:
+ Env.t -> Ident.t -> type_declaration -> type_declaration -> unit
+@@ -130,53 +141,20 @@
+
+ type symptom =
+ Missing_field of Ident.t
+-Index: testsuite/tests/typing-modules/Test.ml.reference
++Index: typing/printtyped.ml
+ ===================================================================
+---- testsuite/tests/typing-modules/Test.ml.reference (revision 12005)
+-+++ testsuite/tests/typing-modules/Test.ml.reference (working copy)
+-@@ -6,4 +6,12 @@
+- # type -'a t
+- class type c = object method m : [ `A ] t end
+- # module M : sig val v : (#c as 'a) -> 'a end
+-+# module type S = sig module type T module F : functor (X : T) -> T end
+-+# module type T0 = sig type t end
+-+# module type S1 = sig module type T = T0 module F : functor (X : T) -> T end
+-+# module type S2 = sig module F : functor (X : T0) -> T0 end
+-+# module type S3 =
+-+ sig
+-+ module F : functor (X : sig type t = int end) -> sig type t = int end
+-+ end
+- #
+-Index: testsuite/tests/typing-modules/Test.ml.principal.reference
+-===================================================================
+---- testsuite/tests/typing-modules/Test.ml.principal.reference (revision 12005)
+-+++ testsuite/tests/typing-modules/Test.ml.principal.reference (working copy)
+-@@ -6,4 +6,12 @@
+- # type -'a t
+- class type c = object method m : [ `A ] t end
+- # module M : sig val v : (#c as 'a) -> 'a end
+-+# module type S = sig module type T module F : functor (X : T) -> T end
+-+# module type T0 = sig type t end
+-+# module type S1 = sig module type T = T0 module F : functor (X : T) -> T end
+-+# module type S2 = sig module F : functor (X : T0) -> T0 end
+-+# module type S3 =
+-+ sig
+-+ module F : functor (X : sig type t = int end) -> sig type t = int end
+-+ end
+- #
+-Index: testsuite/tests/typing-modules/Test.ml
+-===================================================================
+---- testsuite/tests/typing-modules/Test.ml (revision 12005)
+-+++ testsuite/tests/typing-modules/Test.ml (working copy)
+-@@ -9,3 +9,11 @@
+- class type c = object method m : [ `A ] t end;;
+- module M : sig val v : (#c as 'a) -> 'a end =
+- struct let v x = ignore (x :> c); x end;;
+-+
+-+(* with module type *)
+-+
+-+module type S = sig module type T module F(X:T) : T end;;
+-+module type T0 = sig type t end;;
+-+module type S1 = S with module type T = T0;;
+-+module type S2 = S with module type T := T0;;
+-+module type S3 = S with module type T := sig type t = int end;;
++--- typing/printtyped.ml (revision 13947)
+++++ typing/printtyped.ml (working copy)
++@@ -608,6 +608,12 @@
++ type_declaration (i+1) ppf td;
++ | Twith_module (li,_) -> line i ppf "Pwith_module %a\n" fmt_path li;
++ | Twith_modsubst (li,_) -> line i ppf "Pwith_modsubst %a\n" fmt_path li;
+++ | Twith_modtype (td) ->
+++ line i ppf "Pwith_modtype\n";
+++ modtype_declaration (i+1) ppf td;
+++ | Twith_modtypesubst (td) ->
+++ line i ppf "Pwith_modtypesubst\n";
+++ modtype_declaration (i+1) ppf td;
++
++ and module_expr i ppf x =
++ line i ppf "module_expr %a\n" fmt_location x.mod_loc;
+Index: parsing/pprintast.ml
+===================================================================
+--- parsing/pprintast.ml (revision 13947)
++++ parsing/pprintast.ml (working copy)
+@@ -847,18 +847,28 @@
+ (self#list self#type_var_option ~sep:"," ~first:"(" ~last:")")
+ ls self#longident_loc li self#type_declaration td
+ | Pwith_module (li2) ->
+- pp f "module %a =@ %a" self#longident_loc li self#longident_loc li2;
++ pp f "module %a =@ %a"
++ self#longident_loc li self#longident_loc li2
+ | Pwith_typesubst ({ptype_params=ls;_} as td) ->
+ pp f "type@ %a %a :=@ %a"
+ (self#list self#type_var_option ~sep:"," ~first:"(" ~last:")")
+ ls self#longident_loc li
+ self#type_declaration td
+ | Pwith_modsubst (li2) ->
+- pp f "module %a :=@ %a" self#longident_loc li self#longident_loc li2 in
++ pp f "module %a :=@ %a"
++ self#longident_loc li self#longident_loc li2
++ | Pwith_modtype mty ->
++ pp f "module type %a =@ %a"
++ self#longident_loc li self#module_type mty
++ | Pwith_modtypesubst mty ->
++ pp f "module type %a :=@ %a"
++ self#longident_loc li self#module_type mty
++ in
+ (match l with
+ | [] -> pp f "@[<hov2>%a@]" self#module_type mt
+ | _ -> pp f "@[<hov2>(%a@ with@ %a)@]"
+- self#module_type mt (self#list longident_x_with_constraint ~sep:"@ and@ ") l )
++ self#module_type mt
++ (self#list longident_x_with_constraint ~sep:"@ and@ ") l )
+ | Pmty_typeof me ->
+ pp f "@[<hov2>module@ type@ of@ %a@]"
+ self#module_expr me
+Index: parsing/parser.mly
+===================================================================
+--- parsing/parser.mly (revision 13947)
++++ parsing/parser.mly (working copy)
+@@ -1506,6 +1506,10 @@
+ { (mkrhs $2 2, Pwith_module (mkrhs $4 4)) }
+ | MODULE UIDENT COLONEQUAL mod_ext_longident
+ { (mkrhs (Lident $2) 2, Pwith_modsubst (mkrhs $4 4)) }
++ | MODULE TYPE mty_longident EQUAL module_type
++ { (mkrhs $3 3, Pwith_modtype $5) }
++ | MODULE TYPE ident COLONEQUAL module_type
++ { (mkrhs (Lident $3) 3, Pwith_modtypesubst $5) }
+ ;
+ with_type_binder:
+ EQUAL { Public }
+Index: parsing/ast_mapper.ml
+===================================================================
+--- parsing/ast_mapper.ml (revision 13947)
++++ parsing/ast_mapper.ml (working copy)
+@@ -164,6 +164,8 @@
+ | Pwith_module s -> Pwith_module (map_loc sub s)
+ | Pwith_typesubst d -> Pwith_typesubst (sub # type_declaration d)
+ | Pwith_modsubst s -> Pwith_modsubst (map_loc sub s)
++ | Pwith_modtype m -> Pwith_modtype (sub # module_type m)
++ | Pwith_modtypesubst m -> Pwith_modtypesubst (sub # module_type m)
+
+ let mk_item ?(loc = Location.none) x = {psig_desc = x; psig_loc = loc}
+
+Index: parsing/parsetree.mli
+===================================================================
+--- parsing/parsetree.mli (revision 13947)
++++ parsing/parsetree.mli (working copy)
+@@ -256,6 +256,8 @@
+ | Pwith_module of Longident.t loc
+ | Pwith_typesubst of type_declaration
+ | Pwith_modsubst of Longident.t loc
++ | Pwith_modtype of module_type
++ | Pwith_modtypesubst of module_type
+
+ (* Value expressions for the module language *)
+
+Index: parsing/printast.ml
+===================================================================
+--- parsing/printast.ml (revision 13947)
++++ parsing/printast.ml (working copy)
+@@ -590,6 +590,12 @@
+ type_declaration (i+1) ppf td;
+ | Pwith_module li -> line i ppf "Pwith_module %a\n" fmt_longident_loc li;
+ | Pwith_modsubst li -> line i ppf "Pwith_modsubst %a\n" fmt_longident_loc li;
++ | Pwith_modtype (mty) ->
++ line i ppf "Pwith_modtype\n";
++ module_type (i+1) ppf mty;
++ | Pwith_modtypesubst (mty) ->
++ line i ppf "Pwith_modtype\n";
++ module_type (i+1) ppf mty;
+
+ and module_expr i ppf x =
+ line i ppf "module_expr %a\n" fmt_location x.pmod_loc;
diff --git a/lex/.depend b/lex/.depend
new file mode 100644
index 0000000000..10f90c22c6
--- /dev/null
+++ b/lex/.depend
@@ -0,0 +1,34 @@
+common.cmi : syntax.cmi lexgen.cmi
+compact.cmi : lexgen.cmi
+cset.cmi :
+lexer.cmi : parser.cmi
+lexgen.cmi : syntax.cmi
+outputbis.cmi : syntax.cmi lexgen.cmi common.cmi
+output.cmi : syntax.cmi lexgen.cmi compact.cmi common.cmi
+parser.cmi : syntax.cmi
+syntax.cmi : cset.cmi
+table.cmi :
+common.cmo : syntax.cmi lexgen.cmi common.cmi
+common.cmx : syntax.cmx lexgen.cmx common.cmi
+compact.cmo : table.cmi lexgen.cmi compact.cmi
+compact.cmx : table.cmx lexgen.cmx compact.cmi
+cset.cmo : cset.cmi
+cset.cmx : cset.cmi
+lexer.cmo : syntax.cmi parser.cmi lexer.cmi
+lexer.cmx : syntax.cmx parser.cmx lexer.cmi
+lexgen.cmo : table.cmi syntax.cmi cset.cmi lexgen.cmi
+lexgen.cmx : table.cmx syntax.cmx cset.cmx lexgen.cmi
+main.cmo : syntax.cmi parser.cmi outputbis.cmi output.cmi lexgen.cmi \
+ lexer.cmi cset.cmi compact.cmi common.cmi
+main.cmx : syntax.cmx parser.cmx outputbis.cmx output.cmx lexgen.cmx \
+ lexer.cmx cset.cmx compact.cmx common.cmx
+outputbis.cmo : lexgen.cmi common.cmi outputbis.cmi
+outputbis.cmx : lexgen.cmx common.cmx outputbis.cmi
+output.cmo : lexgen.cmi compact.cmi common.cmi output.cmi
+output.cmx : lexgen.cmx compact.cmx common.cmx output.cmi
+parser.cmo : syntax.cmi cset.cmi parser.cmi
+parser.cmx : syntax.cmx cset.cmx parser.cmi
+syntax.cmo : cset.cmi syntax.cmi
+syntax.cmx : cset.cmx syntax.cmi
+table.cmo : table.cmi
+table.cmx : table.cmi
diff --git a/lex/.ignore b/lex/.ignore
new file mode 100644
index 0000000000..9f4f308da4
--- /dev/null
+++ b/lex/.ignore
@@ -0,0 +1,6 @@
+parser.ml
+parser.mli
+lexer.ml
+ocamllex
+ocamllex.opt
+parser.output
diff --git a/lex/Makefile b/lex/Makefile
new file mode 100644
index 0000000000..3691cb2b3f
--- /dev/null
+++ b/lex/Makefile
@@ -0,0 +1,74 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# The lexer generator
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+
+CAMLC=$(CAMLRUN) ../boot/ocamlc -strict-sequence -nostdlib -I ../boot
+CAMLOPT=$(CAMLRUN) ../ocamlopt -nostdlib -I ../stdlib
+COMPFLAGS=-w +33..39 -warn-error A -bin-annot -safe-string
+LINKFLAGS=
+YACCFLAGS=-v
+CAMLLEX=$(CAMLRUN) ../boot/ocamllex
+CAMLDEP=$(CAMLRUN) ../tools/ocamldep
+
+
+OBJS=cset.cmo syntax.cmo parser.cmo lexer.cmo table.cmo lexgen.cmo \
+ compact.cmo common.cmo output.cmo outputbis.cmo main.cmo
+
+all: ocamllex
+allopt: ocamllex.opt
+
+ocamllex: $(OBJS)
+ $(CAMLC) $(LINKFLAGS) -compat-32 -o ocamllex $(OBJS)
+
+ocamllex.opt: $(OBJS:.cmo=.cmx)
+ $(CAMLOPT) -o ocamllex.opt $(OBJS:.cmo=.cmx)
+
+clean::
+ rm -f ocamllex ocamllex.opt
+ rm -f *.cmo *.cmi *.cmx *.cmt *.cmti *.o *~
+
+parser.ml parser.mli: parser.mly
+ $(CAMLYACC) $(YACCFLAGS) parser.mly
+
+clean::
+ rm -f parser.ml parser.mli parser.output
+
+beforedepend:: parser.ml parser.mli
+
+lexer.ml: lexer.mll
+ $(CAMLLEX) lexer.mll
+
+clean::
+ rm -f lexer.ml
+
+beforedepend:: lexer.ml
+
+.SUFFIXES:
+.SUFFIXES: .ml .cmo .mli .cmi .cmx
+
+.ml.cmo:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.mli.cmi:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmx:
+ $(CAMLOPT) -c $(COMPFLAGS) $<
+
+depend: beforedepend
+ $(CAMLDEP) *.mli *.ml > .depend
+
+include .depend
diff --git a/lex/Makefile.nt b/lex/Makefile.nt
new file mode 100644
index 0000000000..6bd8560406
--- /dev/null
+++ b/lex/Makefile.nt
@@ -0,0 +1,75 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# The lexer generator
+
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+
+CAMLC=$(CAMLRUN) ../boot/ocamlc -I ../boot
+CAMLOPT=$(CAMLRUN) ../ocamlopt -I ../stdlib
+COMPFLAGS=-warn-error A
+LINKFLAGS=
+YACCFLAGS=-v
+CAMLLEX=$(CAMLRUN) ../boot/ocamllex
+CAMLDEP=$(CAMLRUN) ../tools/ocamldep
+DEPFLAGS=
+
+OBJS=cset.cmo syntax.cmo parser.cmo lexer.cmo table.cmo lexgen.cmo \
+ compact.cmo common.cmo output.cmo outputbis.cmo main.cmo
+
+all: ocamllex syntax.cmo
+allopt: ocamllex.opt
+
+ocamllex: $(OBJS)
+ $(CAMLC) $(LINKFLAGS) -compat-32 -o ocamllex $(OBJS)
+
+ocamllex.opt: $(OBJS:.cmo=.cmx)
+ $(CAMLOPT) -o ocamllex.opt $(OBJS:.cmo=.cmx)
+
+clean::
+ rm -f ocamllex ocamllex.opt
+ rm -f *.cmo *.cmi *.cmx *.$(O)
+
+parser.ml parser.mli: parser.mly
+ $(CAMLYACC) $(YACCFLAGS) parser.mly
+
+clean::
+ rm -f parser.ml parser.mli
+
+beforedepend:: parser.ml parser.mli
+
+lexer.ml: lexer.mll
+ $(CAMLLEX) lexer.mll
+
+clean::
+ rm -f lexer.ml
+
+beforedepend:: lexer.ml
+
+.SUFFIXES:
+.SUFFIXES: .ml .cmo .mli .cmi .cmx
+
+.ml.cmo:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.mli.cmi:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmx:
+ $(CAMLOPT) -c $(COMPFLAGS) $<
+
+depend: beforedepend
+ $(CAMLDEP) *.mli *.ml > .depend
+
+include .depend
diff --git a/lex/common.ml b/lex/common.ml
new file mode 100644
index 0000000000..9b86ba111f
--- /dev/null
+++ b/lex/common.ml
@@ -0,0 +1,171 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, projet Moscova, *)
+(* INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+open Syntax
+open Lexgen
+
+
+(* To copy the ML code fragments *)
+
+type line_tracker = {
+ file : string;
+ oc : out_channel;
+ ic : in_channel;
+ mutable cur_line : int;
+};;
+
+let open_tracker file oc = {
+ file = file;
+ oc = oc;
+ ic = open_in_bin file;
+ cur_line = 1;
+};;
+
+let close_tracker tr = close_in_noerr tr.ic;;
+
+let update_tracker tr =
+ fprintf tr.oc "\n";
+ flush tr.oc;
+ let cr_seen = ref false in
+ try while true do
+ match input_char tr.ic with
+ | '\010' when not !cr_seen -> tr.cur_line <- tr.cur_line + 1;
+ | '\013' -> cr_seen := true; tr.cur_line <- tr.cur_line + 1;
+ | _ -> cr_seen := false;
+ done with End_of_file ->
+ fprintf tr.oc "# %d \"%s\"\n" (tr.cur_line+1) tr.file;
+;;
+
+let copy_buffer = Bytes.create 1024
+
+let copy_chars_unix ic oc start stop =
+ let n = ref (stop - start) in
+ while !n > 0 do
+ let m = input ic copy_buffer 0 (min !n 1024) in
+ output oc copy_buffer 0 m;
+ n := !n - m
+ done
+
+let copy_chars_win32 ic oc start stop =
+ for _i = start to stop - 1 do
+ let c = input_char ic in
+ if c <> '\r' then output_char oc c
+ done
+
+let copy_chars =
+ match Sys.os_type with
+ "Win32" | "Cygwin" -> copy_chars_win32
+ | _ -> copy_chars_unix
+
+let copy_chunk ic oc trl loc add_parens =
+ if loc.start_pos < loc.end_pos || add_parens then begin
+ fprintf oc "# %d \"%s\"\n" loc.start_line loc.loc_file;
+ if add_parens then begin
+ for _i = 1 to loc.start_col - 1 do output_char oc ' ' done;
+ output_char oc '(';
+ end else begin
+ for _i = 1 to loc.start_col do output_char oc ' ' done;
+ end;
+ seek_in ic loc.start_pos;
+ copy_chars ic oc loc.start_pos loc.end_pos;
+ if add_parens then output_char oc ')';
+ update_tracker trl;
+ end
+
+(* Various memory actions *)
+
+let output_mem_access oc i = fprintf oc "lexbuf.Lexing.lex_mem.(%d)" i
+
+let output_memory_actions pref oc = function
+ | [] -> ()
+ | mvs ->
+ output_string oc "(* " ;
+ fprintf oc "L=%d " (List.length mvs) ;
+ List.iter
+ (fun mv -> match mv with
+ | Copy (tgt, src) ->
+ fprintf oc "[%d] <- [%d] ;" tgt src
+ | Set tgt ->
+ fprintf oc "[%d] <- p ; " tgt)
+ mvs ;
+ output_string oc " *)\n" ;
+ List.iter
+ (fun mv -> match mv with
+ | Copy (tgt, src) ->
+ fprintf oc
+ "%s%a <- %a ;\n"
+ pref output_mem_access tgt output_mem_access src
+ | Set tgt ->
+ fprintf oc "%s%a <- lexbuf.Lexing.lex_curr_pos ;\n"
+ pref output_mem_access tgt)
+ mvs
+
+let output_base_mem oc = function
+ | Mem i -> output_mem_access oc i
+ | Start -> fprintf oc "lexbuf.Lexing.lex_start_pos"
+ | End -> fprintf oc "lexbuf.Lexing.lex_curr_pos"
+
+let output_tag_access oc = function
+ | Sum (a,0) ->
+ output_base_mem oc a
+ | Sum (a,i) ->
+ fprintf oc "(%a + %d)" output_base_mem a i
+
+let output_env ic oc tr env =
+ let pref = ref "let" in
+ match env with
+ | [] -> ()
+ | _ ->
+ (* Probably, we are better with variables sorted
+ in apparition order *)
+ let env =
+ List.sort
+ (fun ((_,p1),_) ((_,p2),_) ->
+ Pervasives.compare p1.start_pos p2.start_pos)
+ env in
+
+ List.iter
+ (fun ((x,pos),v) ->
+ fprintf oc "%s\n" !pref ;
+ copy_chunk ic oc tr pos false ;
+ begin match v with
+ | Ident_string (o,nstart,nend) ->
+ fprintf oc
+ "= Lexing.sub_lexeme%s lexbuf %a %a"
+ (if o then "_opt" else "")
+ output_tag_access nstart output_tag_access nend
+ | Ident_char (o,nstart) ->
+ fprintf oc
+ "= Lexing.sub_lexeme_char%s lexbuf %a"
+ (if o then "_opt" else "")
+ output_tag_access nstart
+ end ;
+ pref := "\nand")
+ env ;
+ fprintf oc " in\n"
+
+(* Output the user arguments *)
+let output_args oc args =
+ List.iter (fun x -> (output_string oc x; output_char oc ' ')) args
+
+let output_refill_handler ic oc oci = function
+ | None -> false
+ | Some location ->
+ output_string oc "let __ocaml_lex_refill : \
+ (Lexing.lexbuf -> 'a) -> (Lexing.lexbuf -> 'a) =\n";
+ copy_chunk ic oc oci location true;
+ true
+
+(* quiet flag *)
+let quiet_mode = ref false;;
diff --git a/lex/common.mli b/lex/common.mli
new file mode 100644
index 0000000000..de23959cae
--- /dev/null
+++ b/lex/common.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type line_tracker;;
+val open_tracker : string -> out_channel -> line_tracker
+val close_tracker : line_tracker -> unit
+val copy_chunk :
+ in_channel -> out_channel -> line_tracker -> Syntax.location -> bool -> unit
+val output_mem_access : out_channel -> int -> unit
+val output_memory_actions :
+ string -> out_channel -> Lexgen.memory_action list -> unit
+val output_env :
+ in_channel -> out_channel -> line_tracker ->
+ (Lexgen.ident * Lexgen.ident_info) list -> unit
+val output_args : out_channel -> string list -> unit
+val output_refill_handler :
+ in_channel -> out_channel -> line_tracker -> Syntax.location option -> bool
+
+val quiet_mode : bool ref;;
diff --git a/lex/compact.ml b/lex/compact.ml
new file mode 100644
index 0000000000..f468a557d6
--- /dev/null
+++ b/lex/compact.ml
@@ -0,0 +1,229 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compaction of an automata *)
+
+open Lexgen
+
+(* Code for memory actions *)
+let code = Table.create 0
+
+(* instructions are 2 8-bits integers, a 0xff byte means return *)
+
+let emit_int i = Table.emit code i
+
+let ins_mem i c = match i with
+ | Copy (dst, src) -> dst::src::c
+ | Set dst -> dst::0xff::c
+
+
+let ins_tag i c = match i with
+ | SetTag (dst, src) -> dst::src::c
+ | EraseTag dst -> dst::0xff::c
+
+
+let do_emit_code c =
+ let r = Table.size code in
+ List.iter emit_int c ;
+ emit_int 0xff ;
+ r
+
+let memory = Hashtbl.create 101
+
+let mem_emit_code c =
+ try Hashtbl.find memory c with
+ | Not_found ->
+ let r = do_emit_code c in
+ Hashtbl.add memory c r ;
+ r
+
+(* Code address 0 is the empty code (ie do nothing) *)
+let _ = mem_emit_code []
+
+let emit_tag_code c = mem_emit_code (List.fold_right ins_tag c [])
+and emit_mem_code c =mem_emit_code (List.fold_right ins_mem c [])
+
+(*******************************************)
+(* Compact the transition and check arrays *)
+(*******************************************)
+
+
+(* Determine the integer occurring most frequently in an array *)
+
+let most_frequent_elt v =
+ let frequencies = Hashtbl.create 17 in
+ let max_freq = ref 0 in
+ let most_freq = ref (v.(0)) in
+ for i = 0 to Array.length v - 1 do
+ let e = v.(i) in
+ let r =
+ try
+ Hashtbl.find frequencies e
+ with Not_found ->
+ let r = ref 1 in Hashtbl.add frequencies e r; r in
+ incr r;
+ if !r > !max_freq then begin max_freq := !r; most_freq := e end
+ done;
+ !most_freq
+
+(* Transform an array into a list of (position, non-default element) *)
+
+let non_default_elements def v =
+ let rec nondef i =
+ if i >= Array.length v then [] else begin
+ let e = v.(i) in
+ if e = def then nondef(i+1) else (i, e) :: nondef(i+1)
+ end in
+ nondef 0
+
+
+type t_compact =
+ {mutable c_trans : int array ;
+ mutable c_check : int array ;
+ mutable c_last_used : int ; }
+
+let create_compact () =
+ { c_trans = Array.make 1024 0 ;
+ c_check = Array.make 1024 (-1) ;
+ c_last_used = 0 ; }
+
+let reset_compact c =
+ c.c_trans <- Array.make 1024 0 ;
+ c.c_check <- Array.make 1024 (-1) ;
+ c.c_last_used <- 0
+
+(* One compacted table for transitions, one other for memory actions *)
+let trans = create_compact ()
+and moves = create_compact ()
+
+
+let grow_compact c =
+ let old_trans = c.c_trans
+ and old_check = c.c_check in
+ let n = Array.length old_trans in
+ c.c_trans <- Array.make (2*n) 0;
+ Array.blit old_trans 0 c.c_trans 0 c.c_last_used;
+ c.c_check <- Array.make (2*n) (-1);
+ Array.blit old_check 0 c.c_check 0 c.c_last_used
+
+let do_pack state_num orig compact =
+ let default = most_frequent_elt orig in
+ let nondef = non_default_elements default orig in
+ let rec pack_from b =
+ while
+ b + 257 > Array.length compact.c_trans
+ do
+ grow_compact compact
+ done;
+ let rec try_pack = function
+ [] -> b
+ | (pos, v) :: rem ->
+ if compact.c_check.(b + pos) = -1 then
+ try_pack rem
+ else pack_from (b+1) in
+ try_pack nondef in
+ let base = pack_from 0 in
+ List.iter
+ (fun (pos, v) ->
+ compact.c_trans.(base + pos) <- v;
+ compact.c_check.(base + pos) <- state_num)
+ nondef;
+ if base + 257 > compact.c_last_used then
+ compact.c_last_used <- base + 257;
+ (base, default)
+
+let pack_moves state_num move_t =
+ let move_v = Array.make 257 0
+ and move_m = Array.make 257 0 in
+ for i = 0 to 256 do
+ let act,c = move_t.(i) in
+ move_v.(i) <- (match act with Backtrack -> -1 | Goto n -> n) ;
+ move_m.(i) <- emit_mem_code c
+ done ;
+ let pk_trans = do_pack state_num move_v trans
+ and pk_moves = do_pack state_num move_m moves in
+ pk_trans, pk_moves
+
+
+(* Build the tables *)
+
+type lex_tables =
+ { tbl_base: int array; (* Perform / Shift *)
+ tbl_backtrk: int array; (* No_remember / Remember *)
+ tbl_default: int array; (* Default transition *)
+ tbl_trans: int array; (* Transitions (compacted) *)
+ tbl_check: int array; (* Check (compacted) *)
+(* code addresses are managed in a similar fashion as transitions *)
+ tbl_base_code : int array; (* code ptr / base for Shift *)
+ tbl_backtrk_code : int array; (* nothing / code when Remember *)
+(* moves to execute before transitions (compacted) *)
+ tbl_default_code : int array;
+ tbl_trans_code : int array;
+ tbl_check_code : int array;
+(* byte code itself *)
+ tbl_code: int array;}
+
+
+let compact_tables state_v =
+ let n = Array.length state_v in
+ let base = Array.make n 0
+ and backtrk = Array.make n (-1)
+ and default = Array.make n 0
+ and base_code = Array.make n 0
+ and backtrk_code = Array.make n 0
+ and default_code = Array.make n 0 in
+ for i = 0 to n - 1 do
+ match state_v.(i) with
+ | Perform (n,c) ->
+ base.(i) <- -(n+1) ;
+ base_code.(i) <- emit_tag_code c
+ | Shift(trans, move) ->
+ begin match trans with
+ | No_remember -> ()
+ | Remember (n,c) ->
+ backtrk.(i) <- n ;
+ backtrk_code.(i) <- emit_tag_code c
+ end;
+ let (b_trans, d_trans),(b_moves,d_moves) = pack_moves i move in
+ base.(i) <- b_trans; default.(i) <- d_trans ;
+ base_code.(i) <- b_moves; default_code.(i) <- d_moves ;
+ done;
+ let code = Table.trim code in
+ let tables =
+ if Array.length code > 1 then
+ { tbl_base = base;
+ tbl_backtrk = backtrk;
+ tbl_default = default;
+ tbl_trans = Array.sub trans.c_trans 0 trans.c_last_used;
+ tbl_check = Array.sub trans.c_check 0 trans.c_last_used;
+ tbl_base_code = base_code ;
+ tbl_backtrk_code = backtrk_code;
+ tbl_default_code = default_code;
+ tbl_trans_code = Array.sub moves.c_trans 0 moves.c_last_used;
+ tbl_check_code = Array.sub moves.c_check 0 moves.c_last_used;
+ tbl_code = code}
+ else (* when no memory moves, do not emit related tables *)
+ { tbl_base = base;
+ tbl_backtrk = backtrk;
+ tbl_default = default;
+ tbl_trans = Array.sub trans.c_trans 0 trans.c_last_used;
+ tbl_check = Array.sub trans.c_check 0 trans.c_last_used;
+ tbl_base_code = [||] ;
+ tbl_backtrk_code = [||];
+ tbl_default_code = [||];
+ tbl_trans_code = [||];
+ tbl_check_code = [||];
+ tbl_code = [||]}
+ in
+ reset_compact trans ;
+ reset_compact moves ;
+ tables
diff --git a/lex/compact.mli b/lex/compact.mli
new file mode 100644
index 0000000000..90f2ed99c6
--- /dev/null
+++ b/lex/compact.mli
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compaction of an automata *)
+type lex_tables =
+ { tbl_base: int array; (* Perform / Shift *)
+ tbl_backtrk: int array; (* No_remember / Remember *)
+ tbl_default: int array; (* Default transition *)
+ tbl_trans: int array; (* Transitions (compacted) *)
+ tbl_check: int array; (* Check (compacted) *)
+(* code addresses are managed in a similar fashion as transitions *)
+ tbl_base_code : int array; (* code ptr / base for Shift *)
+ tbl_backtrk_code : int array; (* nothing / code when Remember *)
+(* moves to execute before transitions (compacted) *)
+ tbl_default_code : int array;
+ tbl_trans_code : int array;
+ tbl_check_code : int array;
+(* byte code itself *)
+ tbl_code: int array;}
+
+
+val compact_tables: Lexgen.automata array -> lex_tables
diff --git a/lex/cset.ml b/lex/cset.ml
new file mode 100644
index 0000000000..f4581ba374
--- /dev/null
+++ b/lex/cset.ml
@@ -0,0 +1,94 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, Jerome Vouillon projet Cristal, *)
+(* INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+exception Bad
+
+type t = (int * int) list
+
+
+let empty = []
+let is_empty = function
+ | [] -> true
+ | _ -> false
+
+let singleton c = [c,c]
+
+let interval c1 c2 =
+ if c1 <= c2 then [c1,c2]
+ else [c2,c1]
+
+
+let rec union s1 s2 = match s1,s2 with
+| [],_ -> s2
+| _,[] -> s1
+| (c1,d1) as p1::r1, (c2,d2)::r2 ->
+ if c1 > c2 then
+ union s2 s1
+ else begin (* c1 <= c2 *)
+ if d1+1 < c2 then
+ p1::union r1 s2
+ else if d1 < d2 then
+ union ((c1,d2)::r2) r1
+ else
+ union s1 r2
+ end
+
+let rec inter l l' = match l, l' with
+ _, [] -> []
+ | [], _ -> []
+ | (c1, c2)::r, (c1', c2')::r' ->
+ if c2 < c1' then
+ inter r l'
+ else if c2' < c1 then
+ inter l r'
+ else if c2 < c2' then
+ (max c1 c1', c2)::inter r l'
+ else
+ (max c1 c1', c2')::inter l r'
+
+let rec diff l l' = match l, l' with
+ _, [] -> l
+ | [], _ -> []
+ | (c1, c2)::r, (c1', c2')::r' ->
+ if c2 < c1' then
+ (c1, c2)::diff r l'
+ else if c2' < c1 then
+ diff l r'
+ else
+ let r'' = if c2' < c2 then (c2' + 1, c2) :: r else r in
+ if c1 < c1' then
+ (c1, c1' - 1)::diff r'' r'
+ else
+ diff r'' r'
+
+
+let eof = singleton 256
+and all_chars = interval 0 255
+and all_chars_eof = interval 0 256
+
+let complement s = diff all_chars s
+
+let env_to_array env = match env with
+| [] -> assert false
+| (_,x)::rem ->
+ let res = Array.make 257 x in
+ List.iter
+ (fun (c,y) ->
+ List.iter
+ (fun (i,j) ->
+ for k=i to j do
+ res.(k) <- y
+ done)
+ c)
+ rem ;
+ res
diff --git a/lex/cset.mli b/lex/cset.mli
new file mode 100644
index 0000000000..daad6e59f1
--- /dev/null
+++ b/lex/cset.mli
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, Jerome Vouillon projet Cristal, *)
+(* INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Set of characters encoded as list of intervals *)
+
+type t
+
+val empty : t
+val is_empty : t -> bool
+val all_chars : t
+exception Bad
+
+val all_chars_eof : t
+val eof : t
+val singleton : int -> t
+val interval : int -> int -> t
+val union : t -> t -> t
+val inter : t -> t -> t
+val diff : t -> t -> t
+val complement : t -> t
+val env_to_array : (t * 'a) list -> 'a array
diff --git a/lex/lexer.mli b/lex/lexer.mli
new file mode 100644
index 0000000000..ca8e4c490a
--- /dev/null
+++ b/lex/lexer.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val main: Lexing.lexbuf -> Parser.token
+
+exception Lexical_error of string * string * int * int
+
+(*n
+val line_num: int ref
+val line_start_pos: int ref
+*)
diff --git a/lex/lexer.mll b/lex/lexer.mll
new file mode 100644
index 0000000000..6424c34fd2
--- /dev/null
+++ b/lex/lexer.mll
@@ -0,0 +1,304 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexical analyzer for lexer definitions. Bootstrapped! *)
+
+{
+open Syntax
+open Parser
+
+(* Auxiliaries for the lexical analyzer *)
+
+let brace_depth = ref 0
+and comment_depth = ref 0
+
+let in_pattern () = !brace_depth = 0 && !comment_depth = 0
+
+exception Lexical_error of string * string * int * int
+
+let string_buff = Buffer.create 256
+
+let reset_string_buffer () = Buffer.clear string_buff
+
+let store_string_char c = Buffer.add_char string_buff c
+let store_string_chars s = Buffer.add_string string_buff s
+
+let get_stored_string () = Buffer.contents string_buff
+
+let char_for_backslash = function
+ 'n' -> '\010'
+ | 'r' -> '\013'
+ | 'b' -> '\008'
+ | 't' -> '\009'
+ | c -> c
+
+let raise_lexical_error lexbuf msg =
+ let p = Lexing.lexeme_start_p lexbuf in
+ raise (Lexical_error (msg,
+ p.Lexing.pos_fname,
+ p.Lexing.pos_lnum,
+ p.Lexing.pos_cnum - p.Lexing.pos_bol + 1))
+;;
+
+let handle_lexical_error fn lexbuf =
+ let p = Lexing.lexeme_start_p lexbuf in
+ let line = p.Lexing.pos_lnum
+ and column = p.Lexing.pos_cnum - p.Lexing.pos_bol + 1
+ and file = p.Lexing.pos_fname
+ in
+ try
+ fn lexbuf
+ with Lexical_error (msg, "", 0, 0) ->
+ raise(Lexical_error(msg, file, line, column))
+
+let get_input_name () = Sys.argv.(Array.length Sys.argv - 1)
+
+let warning lexbuf msg =
+ let p = Lexing.lexeme_start_p lexbuf in
+ Printf.eprintf "ocamllex warning:\nFile \"%s\", line %d, character %d: %s.\n"
+ p.Lexing.pos_fname p.Lexing.pos_lnum
+ (p.Lexing.pos_cnum - p.Lexing.pos_bol + 1) msg;
+ flush stderr
+
+let decimal_code c d u =
+ 100 * (Char.code c - 48) + 10 * (Char.code d - 48) + (Char.code u - 48)
+
+let char_for_hexadecimal_code d u =
+ let d1 = Char.code d in
+ let val1 = if d1 >= 97 then d1 - 87
+ else if d1 >= 65 then d1 - 55
+ else d1 - 48
+ in
+ let d2 = Char.code u in
+ let val2 = if d2 >= 97 then d2 - 87
+ else if d2 >= 65 then d2 - 55
+ else d2 - 48
+ in
+ Char.chr (val1 * 16 + val2)
+
+let incr_loc lexbuf delta =
+ let pos = lexbuf.Lexing.lex_curr_p in
+ lexbuf.Lexing.lex_curr_p <- { pos with
+ Lexing.pos_lnum = pos.Lexing.pos_lnum + 1;
+ Lexing.pos_bol = pos.Lexing.pos_cnum - delta;
+ }
+;;
+
+let update_loc lexbuf opt_file line =
+ let pos = lexbuf.Lexing.lex_curr_p in
+ let new_file = match opt_file with
+ | None -> pos.Lexing.pos_fname
+ | Some f -> f
+ in
+ lexbuf.Lexing.lex_curr_p <- { pos with
+ Lexing.pos_fname = new_file;
+ Lexing.pos_lnum = line;
+ Lexing.pos_bol = pos.Lexing.pos_cnum;
+ }
+;;
+
+}
+
+let identstart =
+ ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255']
+let identbody =
+ ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9']
+let backslash_escapes =
+ ['\\' '\'' '"' 'n' 't' 'b' 'r' ' ']
+
+rule main = parse
+ [' ' '\013' '\009' '\012' ] +
+ { main lexbuf }
+ | '\010'
+ { incr_loc lexbuf 0;
+ main lexbuf }
+ | "#" [' ' '\t']* (['0'-'9']+ as num) [' ' '\t']*
+ ('\"' ([^ '\010' '\013' '\"']* as name) '\"')?
+ [^ '\010' '\013']* '\010'
+ { update_loc lexbuf name (int_of_string num);
+ main lexbuf
+ }
+ | "(*"
+ { comment_depth := 1;
+ handle_lexical_error comment lexbuf;
+ main lexbuf }
+ | '_' { Tunderscore }
+ | identstart identbody *
+ { match Lexing.lexeme lexbuf with
+ "rule" -> Trule
+ | "parse" -> Tparse
+ | "shortest" -> Tparse_shortest
+ | "and" -> Tand
+ | "eof" -> Teof
+ | "let" -> Tlet
+ | "as" -> Tas
+ | "refill" -> Trefill
+ | s -> Tident s }
+ | '"'
+ { reset_string_buffer();
+ handle_lexical_error string lexbuf;
+ Tstring(get_stored_string()) }
+(* note: ''' is a valid character literal (by contrast with the compiler) *)
+ | "'" [^ '\\'] "'"
+ { Tchar(Char.code(Lexing.lexeme_char lexbuf 1)) }
+ | "'" '\\' backslash_escapes "'"
+ { Tchar(Char.code(char_for_backslash (Lexing.lexeme_char lexbuf 2))) }
+ | "'" '\\' (['0'-'9'] as c) (['0'-'9'] as d) (['0'-'9'] as u)"'"
+ { let v = decimal_code c d u in
+ if v > 255 then
+ raise_lexical_error lexbuf
+ (Printf.sprintf "illegal escape sequence \\%c%c%c" c d u)
+ else
+ Tchar v }
+ | "'" '\\' 'x'
+ (['0'-'9' 'a'-'f' 'A'-'F'] as d) (['0'-'9' 'a'-'f' 'A'-'F'] as u) "'"
+ { Tchar(Char.code(char_for_hexadecimal_code d u)) }
+ | "'" '\\' (_ as c)
+ { raise_lexical_error lexbuf
+ (Printf.sprintf "illegal escape sequence \\%c" c)
+ }
+ | '{'
+ { let p = Lexing.lexeme_end_p lexbuf in
+ let f = p.Lexing.pos_fname in
+ let n1 = p.Lexing.pos_cnum
+ and l1 = p.Lexing.pos_lnum
+ and s1 = p.Lexing.pos_bol in
+ brace_depth := 1;
+ let n2 = handle_lexical_error action lexbuf in
+ Taction({loc_file = f; start_pos = n1; end_pos = n2;
+ start_line = l1; start_col = n1 - s1}) }
+ | '=' { Tequal }
+ | '|' { Tor }
+ | '[' { Tlbracket }
+ | ']' { Trbracket }
+ | '*' { Tstar }
+ | '?' { Tmaybe }
+ | '+' { Tplus }
+ | '(' { Tlparen }
+ | ')' { Trparen }
+ | '^' { Tcaret }
+ | '-' { Tdash }
+ | '#' { Tsharp }
+ | eof { Tend }
+ | _
+ { raise_lexical_error lexbuf
+ ("illegal character " ^ String.escaped(Lexing.lexeme lexbuf))
+ }
+
+
+(* String parsing comes from the compiler lexer *)
+and string = parse
+ '"'
+ { () }
+ | '\\' ('\013'* '\010') ([' ' '\009'] * as spaces)
+ { incr_loc lexbuf (String.length spaces);
+ string lexbuf }
+ | '\\' (backslash_escapes as c)
+ { store_string_char(char_for_backslash c);
+ string lexbuf }
+ | '\\' (['0'-'9'] as c) (['0'-'9'] as d) (['0'-'9'] as u)
+ { let v = decimal_code c d u in
+ if in_pattern () && v > 255 then
+ warning lexbuf
+ (Printf.sprintf
+ "illegal backslash escape in string: '\\%c%c%c'" c d u) ;
+ store_string_char (Char.chr v);
+ string lexbuf }
+ | '\\' 'x' (['0'-'9' 'a'-'f' 'A'-'F'] as d) (['0'-'9' 'a'-'f' 'A'-'F'] as u)
+ { store_string_char (char_for_hexadecimal_code d u) ;
+ string lexbuf }
+ | '\\' (_ as c)
+ {if in_pattern () then
+ warning lexbuf
+ (Printf.sprintf "illegal backslash escape in string: '\\%c'" c) ;
+ store_string_char '\\' ;
+ store_string_char c ;
+ string lexbuf }
+ | eof
+ { raise(Lexical_error("unterminated string", "", 0, 0)) }
+ | '\013'* '\010' as s
+ { if !comment_depth = 0 then
+ warning lexbuf (Printf.sprintf "unescaped newline in string") ;
+ store_string_chars s;
+ incr_loc lexbuf 0;
+ string lexbuf }
+ | _ as c
+ { store_string_char c;
+ string lexbuf }
+
+(*
+ Lexers comment and action are quite similar,
+ they should lex both strings and characters,
+ in order not to be confused by what is inside then
+*)
+
+and comment = parse
+ "(*"
+ { incr comment_depth; comment lexbuf }
+ | "*)"
+ { decr comment_depth;
+ if !comment_depth = 0 then () else comment lexbuf }
+ | '"'
+ { reset_string_buffer();
+ string lexbuf;
+ reset_string_buffer();
+ comment lexbuf }
+ | "'"
+ { skip_char lexbuf ;
+ comment lexbuf }
+ | eof
+ { raise(Lexical_error("unterminated comment", "", 0, 0)) }
+ | '\010'
+ { incr_loc lexbuf 0;
+ comment lexbuf }
+ | _
+ { comment lexbuf }
+
+and action = parse
+ '{'
+ { incr brace_depth;
+ action lexbuf }
+ | '}'
+ { decr brace_depth;
+ if !brace_depth = 0 then Lexing.lexeme_start lexbuf else action lexbuf }
+ | '"'
+ { reset_string_buffer();
+ handle_lexical_error string lexbuf;
+ reset_string_buffer();
+ action lexbuf }
+ | "'"
+ { skip_char lexbuf ;
+ action lexbuf }
+ | "(*"
+ { comment_depth := 1;
+ comment lexbuf;
+ action lexbuf }
+ | eof
+ { raise (Lexical_error("unterminated action", "", 0, 0)) }
+ | '\010'
+ { incr_loc lexbuf 0;
+ action lexbuf }
+ | _
+ { action lexbuf }
+
+and skip_char = parse
+ | '\\'? '\010' "'"
+ { incr_loc lexbuf 1;
+ }
+ | [^ '\\' '\''] "'" (* regular character *)
+(* one character and numeric escape sequences *)
+ | '\\' _ "'"
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
+ | '\\' 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "'"
+ {()}
+(* A dieu va ! *)
+ | "" {()}
diff --git a/lex/lexgen.ml b/lex/lexgen.ml
new file mode 100644
index 0000000000..503b08fa49
--- /dev/null
+++ b/lex/lexgen.ml
@@ -0,0 +1,1194 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, *)
+(* Luc Maranget, projet Moscova, *)
+(* INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compiling a lexer definition *)
+
+open Syntax
+open Printf
+
+exception Memory_overflow
+
+(* Deep abstract syntax for regular expressions *)
+
+type ident = string * Syntax.location
+
+type tag_info = {id : string ; start : bool ; action : int}
+
+type regexp =
+ Empty
+ | Chars of int * bool
+ | Action of int
+ | Tag of tag_info
+ | Seq of regexp * regexp
+ | Alt of regexp * regexp
+ | Star of regexp
+
+type tag_base = Start | End | Mem of int
+type tag_addr = Sum of (tag_base * int)
+type ident_info =
+ | Ident_string of bool * tag_addr * tag_addr
+ | Ident_char of bool * tag_addr
+type t_env = (ident * ident_info) list
+
+type ('args,'action) lexer_entry =
+ { lex_name: string;
+ lex_regexp: regexp;
+ lex_mem_tags: int ;
+ lex_actions: (int * t_env * 'action) list }
+
+
+type automata =
+ Perform of int * tag_action list
+ | Shift of automata_trans * (automata_move * memory_action list) array
+
+and automata_trans =
+ No_remember
+ | Remember of int * tag_action list
+
+and automata_move =
+ Backtrack
+ | Goto of int
+
+and memory_action =
+ | Copy of int * int
+ | Set of int
+
+and tag_action = SetTag of int * int | EraseTag of int
+
+(* Representation of entry points *)
+
+type ('args,'action) automata_entry =
+ { auto_name: string;
+ auto_args: 'args ;
+ auto_mem_size : int ;
+ auto_initial_state: int * memory_action list;
+ auto_actions: (int * t_env * 'action) list }
+
+
+(* A lot of sets and map structures *)
+
+module Ints =
+ Set.Make(struct type t = int let compare (x:t) y = compare x y end)
+
+let id_compare (id1,_) (id2,_) = String.compare id1 id2
+
+let tag_compare t1 t2 = Pervasives.compare t1 t2
+
+module Tags = Set.Make(struct type t = tag_info let compare = tag_compare end)
+
+module TagMap =
+ Map.Make (struct type t = tag_info let compare = tag_compare end)
+
+module IdSet =
+ Set.Make (struct type t = ident let compare = id_compare end)
+
+module IdMap =
+ Map.Make (struct type t = ident let compare = id_compare end)
+
+(*********************)
+(* Variable cleaning *)
+(*********************)
+
+(* Silently eliminate nested variables *)
+
+let rec do_remove_nested to_remove = function
+ | Bind (e,x) ->
+ if IdSet.mem x to_remove then
+ do_remove_nested to_remove e
+ else
+ Bind (do_remove_nested (IdSet.add x to_remove) e, x)
+ | Epsilon|Eof|Characters _ as e -> e
+ | Sequence (e1, e2) ->
+ Sequence
+ (do_remove_nested to_remove e1, do_remove_nested to_remove e2)
+ | Alternative (e1, e2) ->
+ Alternative
+ (do_remove_nested to_remove e1, do_remove_nested to_remove e2)
+ | Repetition e ->
+ Repetition (do_remove_nested to_remove e)
+
+let remove_nested_as e = do_remove_nested IdSet.empty e
+
+(*********************)
+(* Variable analysis *)
+(*********************)
+
+(*
+ Optional variables.
+ A variable is optional when matching of regexp does not
+ implies it binds.
+ The typical case is:
+ ("" | 'a' as x) -> optional
+ ("" as x | 'a' as x) -> non-optional
+*)
+
+let stringset_delta s1 s2 =
+ IdSet.union
+ (IdSet.diff s1 s2)
+ (IdSet.diff s2 s1)
+
+let rec find_all_vars = function
+ | Characters _|Epsilon|Eof ->
+ IdSet.empty
+ | Bind (e,x) ->
+ IdSet.add x (find_all_vars e)
+ | Sequence (e1,e2)|Alternative (e1,e2) ->
+ IdSet.union (find_all_vars e1) (find_all_vars e2)
+ | Repetition e -> find_all_vars e
+
+
+let rec do_find_opt = function
+ | Characters _|Epsilon|Eof -> IdSet.empty, IdSet.empty
+ | Bind (e,x) ->
+ let opt,all = do_find_opt e in
+ opt, IdSet.add x all
+ | Sequence (e1,e2) ->
+ let opt1,all1 = do_find_opt e1
+ and opt2,all2 = do_find_opt e2 in
+ IdSet.union opt1 opt2, IdSet.union all1 all2
+ | Alternative (e1,e2) ->
+ let opt1,all1 = do_find_opt e1
+ and opt2,all2 = do_find_opt e2 in
+ IdSet.union
+ (IdSet.union opt1 opt2)
+ (stringset_delta all1 all2),
+ IdSet.union all1 all2
+ | Repetition e ->
+ let r = find_all_vars e in
+ r,r
+
+let find_optional e =
+ let r,_ = do_find_opt e in r
+
+(*
+ Double variables
+ A variable is double when it can be bound more than once
+ in a single matching
+ The typical case is:
+ (e1 as x) (e2 as x)
+
+*)
+
+let rec do_find_double = function
+ | Characters _|Epsilon|Eof -> IdSet.empty, IdSet.empty
+ | Bind (e,x) ->
+ let dbl,all = do_find_double e in
+ (if IdSet.mem x all then
+ IdSet.add x dbl
+ else
+ dbl),
+ IdSet.add x all
+ | Sequence (e1,e2) ->
+ let dbl1, all1 = do_find_double e1
+ and dbl2, all2 = do_find_double e2 in
+ IdSet.union
+ (IdSet.inter all1 all2)
+ (IdSet.union dbl1 dbl2),
+ IdSet.union all1 all2
+ | Alternative (e1,e2) ->
+ let dbl1, all1 = do_find_double e1
+ and dbl2, all2 = do_find_double e2 in
+ IdSet.union dbl1 dbl2,
+ IdSet.union all1 all2
+ | Repetition e ->
+ let r = find_all_vars e in
+ r,r
+
+let find_double e = do_find_double e
+
+(*
+ Type of variables:
+ A variable is bound to a char when all its occurences
+ bind a pattern of length 1.
+ The typical case is:
+ (_ as x) -> char
+*)
+
+let add_some x = function
+ | Some i -> Some (x+i)
+ | None -> None
+
+let add_some_some x y = match x,y with
+| Some i, Some j -> Some (i+j)
+| _,_ -> None
+
+let rec do_find_chars sz = function
+ | Epsilon|Eof -> IdSet.empty, IdSet.empty, sz
+ | Characters _ -> IdSet.empty, IdSet.empty, add_some 1 sz
+ | Bind (e,x) ->
+ let c,s,e_sz = do_find_chars (Some 0) e in
+ begin match e_sz with
+ | Some 1 ->
+ IdSet.add x c,s,add_some 1 sz
+ | _ ->
+ c, IdSet.add x s, add_some_some sz e_sz
+ end
+ | Sequence (e1,e2) ->
+ let c1,s1,sz1 = do_find_chars sz e1 in
+ let c2,s2,sz2 = do_find_chars sz1 e2 in
+ IdSet.union c1 c2,
+ IdSet.union s1 s2,
+ sz2
+ | Alternative (e1,e2) ->
+ let c1,s1,sz1 = do_find_chars sz e1
+ and c2,s2,sz2 = do_find_chars sz e2 in
+ IdSet.union c1 c2,
+ IdSet.union s1 s2,
+ (if sz1 = sz2 then sz1 else None)
+ | Repetition e -> do_find_chars None e
+
+
+
+let find_chars e =
+ let c,s,_ = do_find_chars (Some 0) e in
+ IdSet.diff c s
+
+(*******************************)
+(* From shallow to deep syntax *)
+(*******************************)
+
+let chars = ref ([] : Cset.t list)
+let chars_count = ref 0
+
+
+let rec encode_regexp char_vars act = function
+ Epsilon -> Empty
+ | Characters cl ->
+ let n = !chars_count in
+ chars := cl :: !chars;
+ incr chars_count;
+ Chars(n,false)
+ | Eof ->
+ let n = !chars_count in
+ chars := Cset.eof :: !chars;
+ incr chars_count;
+ Chars(n,true)
+ | Sequence(r1,r2) ->
+ let r1 = encode_regexp char_vars act r1 in
+ let r2 = encode_regexp char_vars act r2 in
+ Seq (r1, r2)
+ | Alternative(r1,r2) ->
+ let r1 = encode_regexp char_vars act r1 in
+ let r2 = encode_regexp char_vars act r2 in
+ Alt(r1, r2)
+ | Repetition r ->
+ let r = encode_regexp char_vars act r in
+ Star r
+ | Bind (r,((name,_) as x)) ->
+ let r = encode_regexp char_vars act r in
+ if IdSet.mem x char_vars then
+ Seq (Tag {id=name ; start=true ; action=act},r)
+ else
+ Seq (Tag {id=name ; start=true ; action=act},
+ Seq (r, Tag {id=name ; start=false ; action=act}))
+
+
+(* Optimisation,
+ Static optimization :
+ Replace tags by offsets relative to the beginning
+ or end of matched string.
+ Dynamic optimization:
+ Replace some non-optional, non-double tags by offsets w.r.t
+ a previous similar tag.
+*)
+
+let incr_pos = function
+ | None -> None
+ | Some i -> Some (i+1)
+
+let decr_pos = function
+ | None -> None
+ | Some i -> Some (i-1)
+
+
+let opt = true
+
+let mk_seq r1 r2 = match r1,r2 with
+| Empty,_ -> r2
+| _,Empty -> r1
+| _,_ -> Seq (r1,r2)
+
+let add_pos p i = match p with
+| Some (Sum (a,n)) -> Some (Sum (a,n+i))
+| None -> None
+
+let mem_name name id_set =
+ IdSet.exists (fun (id_name,_) -> name = id_name) id_set
+
+let opt_regexp all_vars char_vars optional_vars double_vars r =
+
+(* From removed tags to their addresses *)
+ let env = Hashtbl.create 17 in
+
+(* First static optimizations, from start position *)
+ let rec size_forward pos = function
+ | Empty|Chars (_,true)|Tag _ -> Some pos
+ | Chars (_,false) -> Some (pos+1)
+ | Seq (r1,r2) ->
+ begin match size_forward pos r1 with
+ | None -> None
+ | Some pos -> size_forward pos r2
+ end
+ | Alt (r1,r2) ->
+ let pos1 = size_forward pos r1
+ and pos2 = size_forward pos r2 in
+ if pos1=pos2 then pos1 else None
+ | Star _ -> None
+ | Action _ -> assert false in
+
+ let rec simple_forward pos r = match r with
+ | Tag n ->
+ if mem_name n.id double_vars then
+ r,Some pos
+ else begin
+ Hashtbl.add env (n.id,n.start) (Sum (Start, pos)) ;
+ Empty,Some pos
+ end
+ | Empty -> r, Some pos
+ | Chars (_,is_eof) ->
+ r,Some (if is_eof then pos else pos+1)
+ | Seq (r1,r2) ->
+ let r1,pos = simple_forward pos r1 in
+ begin match pos with
+ | None -> mk_seq r1 r2,None
+ | Some pos ->
+ let r2,pos = simple_forward pos r2 in
+ mk_seq r1 r2,pos
+ end
+ | Alt (r1,r2) ->
+ let pos1 = size_forward pos r1
+ and pos2 = size_forward pos r2 in
+ r,(if pos1=pos2 then pos1 else None)
+ | Star _ -> r,None
+ | Action _ -> assert false in
+
+(* Then static optimizations, from end position *)
+ let rec size_backward pos = function
+ | Empty|Chars (_,true)|Tag _ -> Some pos
+ | Chars (_,false) -> Some (pos-1)
+ | Seq (r1,r2) ->
+ begin match size_backward pos r2 with
+ | None -> None
+ | Some pos -> size_backward pos r1
+ end
+ | Alt (r1,r2) ->
+ let pos1 = size_backward pos r1
+ and pos2 = size_backward pos r2 in
+ if pos1=pos2 then pos1 else None
+ | Star _ -> None
+ | Action _ -> assert false in
+
+
+ let rec simple_backward pos r = match r with
+ | Tag n ->
+ if mem_name n.id double_vars then
+ r,Some pos
+ else begin
+ Hashtbl.add env (n.id,n.start) (Sum (End, pos)) ;
+ Empty,Some pos
+ end
+ | Empty -> r,Some pos
+ | Chars (_,is_eof) ->
+ r,Some (if is_eof then pos else pos-1)
+ | Seq (r1,r2) ->
+ let r2,pos = simple_backward pos r2 in
+ begin match pos with
+ | None -> mk_seq r1 r2,None
+ | Some pos ->
+ let r1,pos = simple_backward pos r1 in
+ mk_seq r1 r2,pos
+ end
+ | Alt (r1,r2) ->
+ let pos1 = size_backward pos r1
+ and pos2 = size_backward pos r2 in
+ r,(if pos1=pos2 then pos1 else None)
+ | Star _ -> r,None
+ | Action _ -> assert false in
+
+ let r =
+ if opt then
+ let r,_ = simple_forward 0 r in
+ let r,_ = simple_backward 0 r in
+ r
+ else
+ r in
+
+ let loc_count = ref 0 in
+ let get_tag_addr t =
+ try
+ Hashtbl.find env t
+ with
+ | Not_found ->
+ let n = !loc_count in
+ incr loc_count ;
+ Hashtbl.add env t (Sum (Mem n,0)) ;
+ Sum (Mem n,0) in
+
+ let rec alloc_exp pos r = match r with
+ | Tag n ->
+ if mem_name n.id double_vars then
+ r,pos
+ else begin match pos with
+ | Some a ->
+ Hashtbl.add env (n.id,n.start) a ;
+ Empty,pos
+ | None ->
+ let a = get_tag_addr (n.id,n.start) in
+ r,Some a
+ end
+
+ | Empty -> r,pos
+ | Chars (_,is_eof) -> r,(if is_eof then pos else add_pos pos 1)
+ | Seq (r1,r2) ->
+ let r1,pos = alloc_exp pos r1 in
+ let r2,pos = alloc_exp pos r2 in
+ mk_seq r1 r2,pos
+ | Alt (_,_) ->
+ let off = size_forward 0 r in
+ begin match off with
+ | Some i -> r,add_pos pos i
+ | None -> r,None
+ end
+ | Star _ -> r,None
+ | Action _ -> assert false in
+
+ let r,_ = alloc_exp None r in
+ let m =
+ IdSet.fold
+ (fun ((name,_) as x) r ->
+
+ let v =
+ if IdSet.mem x char_vars then
+ Ident_char
+ (IdSet.mem x optional_vars, get_tag_addr (name,true))
+ else
+ Ident_string
+ (IdSet.mem x optional_vars,
+ get_tag_addr (name,true),
+ get_tag_addr (name,false)) in
+ (x,v)::r)
+ all_vars [] in
+ m,r, !loc_count
+
+
+
+let encode_casedef casedef =
+ let r =
+ List.fold_left
+ (fun (reg,actions,count,ntags) (expr, act) ->
+ let expr = remove_nested_as expr in
+ let char_vars = find_chars expr in
+ let r = encode_regexp char_vars count expr
+ and opt_vars = find_optional expr
+ and double_vars,all_vars = find_double expr in
+ let m,r,loc_ntags =
+ opt_regexp all_vars char_vars opt_vars double_vars r in
+ Alt(reg, Seq(r, Action count)),
+ (count, m ,act) :: actions,
+ (succ count),
+ max loc_ntags ntags)
+ (Empty, [], 0, 0)
+ casedef in
+ r
+
+let encode_lexdef def =
+ chars := [];
+ chars_count := 0;
+ let entry_list =
+ List.map
+ (fun {name=entry_name; args=args; shortest=shortest; clauses=casedef} ->
+ let (re,actions,_,ntags) = encode_casedef casedef in
+ { lex_name = entry_name;
+ lex_regexp = re;
+ lex_mem_tags = ntags ;
+ lex_actions = List.rev actions },args,shortest)
+ def in
+ let chr = Array.of_list (List.rev !chars) in
+ chars := [];
+ (chr, entry_list)
+
+(* To generate directly a NFA from a regular expression.
+ Confer Aho-Sethi-Ullman, dragon book, chap. 3
+ Extension to tagged automata.
+ Confer
+ Ville Larikari
+ 'NFAs with Tagged Transitions, their Conversion to Deterministic
+ Automata and Application to Regular Expressions'.
+ Symposium on String Processing and Information Retrieval (SPIRE 2000),
+ http://kouli.iki.fi/~vlaurika/spire2000-tnfa.ps
+(See also)
+ http://kouli.iki.fi/~vlaurika/regex-submatch.ps.gz
+*)
+
+type t_transition =
+ OnChars of int
+ | ToAction of int
+
+type transition = t_transition * Tags.t
+
+let trans_compare (t1,tags1) (t2,tags2) =
+ match Pervasives.compare t1 t2 with
+ | 0 -> Tags.compare tags1 tags2
+ | r -> r
+
+
+module TransSet =
+ Set.Make(struct type t = transition let compare = trans_compare end)
+
+let rec nullable = function
+ | Empty|Tag _ -> true
+ | Chars (_,_)|Action _ -> false
+ | Seq(r1,r2) -> nullable r1 && nullable r2
+ | Alt(r1,r2) -> nullable r1 || nullable r2
+ | Star r -> true
+
+let rec emptymatch = function
+ | Empty | Chars (_,_) | Action _ -> Tags.empty
+ | Tag t -> Tags.add t Tags.empty
+ | Seq (r1,r2) -> Tags.union (emptymatch r1) (emptymatch r2)
+ | Alt(r1,r2) ->
+ if nullable r1 then
+ emptymatch r1
+ else
+ emptymatch r2
+ | Star r ->
+ if nullable r then
+ emptymatch r
+ else
+ Tags.empty
+
+let addtags transs tags =
+ TransSet.fold
+ (fun (t,tags_t) r -> TransSet.add (t, Tags.union tags tags_t) r)
+ transs TransSet.empty
+
+
+let rec firstpos = function
+ Empty|Tag _ -> TransSet.empty
+ | Chars (pos,_) -> TransSet.add (OnChars pos,Tags.empty) TransSet.empty
+ | Action act -> TransSet.add (ToAction act,Tags.empty) TransSet.empty
+ | Seq(r1,r2) ->
+ if nullable r1 then
+ TransSet.union (firstpos r1) (addtags (firstpos r2) (emptymatch r1))
+ else
+ firstpos r1
+ | Alt(r1,r2) -> TransSet.union (firstpos r1) (firstpos r2)
+ | Star r -> firstpos r
+
+
+(* Berry-sethi followpos *)
+let followpos size entry_list =
+ let v = Array.make size TransSet.empty in
+ let rec fill s = function
+ | Empty|Action _|Tag _ -> ()
+ | Chars (n,_) -> v.(n) <- s
+ | Alt (r1,r2) ->
+ fill s r1 ; fill s r2
+ | Seq (r1,r2) ->
+ fill
+ (if nullable r2 then
+ TransSet.union (firstpos r2) (addtags s (emptymatch r2))
+ else
+ (firstpos r2))
+ r1 ;
+ fill s r2
+ | Star r ->
+ fill (TransSet.union (firstpos r) s) r in
+ List.iter (fun (entry,_,_) -> fill TransSet.empty entry.lex_regexp)
+ entry_list;
+ v
+
+(************************)
+(* The algorithm itself *)
+(************************)
+
+let no_action = max_int
+
+module StateSet =
+ Set.Make (struct type t = t_transition let compare = Pervasives.compare end)
+
+
+module MemMap =
+ Map.Make (struct type t = int
+ let compare (x:t) y = Pervasives.compare x y end)
+
+type 'a dfa_state =
+ {final : int * ('a * int TagMap.t) ;
+ others : ('a * int TagMap.t) MemMap.t}
+
+
+let dtag oc t =
+ fprintf oc "%s<%s>" t.id (if t.start then "s" else "e")
+
+let dmem_map dp ds m =
+ MemMap.iter
+ (fun k x ->
+ eprintf "%d -> " k ; dp x ; ds ())
+ m
+
+and dtag_map dp ds m =
+ TagMap.iter
+ (fun t x ->
+ dtag stderr t ; eprintf " -> " ; dp x ; ds ())
+ m
+
+let dstate {final=(act,(_,m)) ; others=o} =
+ if act <> no_action then begin
+ eprintf "final=%d " act ;
+ dtag_map (fun x -> eprintf "%d" x) (fun () -> prerr_string " ,") m ;
+ prerr_endline ""
+ end ;
+ dmem_map
+ (fun (_,m) ->
+ dtag_map (fun x -> eprintf "%d" x) (fun () -> prerr_string " ,") m)
+ (fun () -> prerr_endline "")
+ o
+
+
+let dfa_state_empty =
+ {final=(no_action, (max_int,TagMap.empty)) ;
+ others=MemMap.empty}
+
+and dfa_state_is_empty {final=(act,_) ; others=o} =
+ act = no_action &&
+ o = MemMap.empty
+
+
+(* A key is an abstraction on a dfa state,
+ two states with the same key can be made the same by
+ copying some memory cells into others *)
+
+
+module StateSetSet =
+ Set.Make (struct type t = StateSet.t let compare = StateSet.compare end)
+
+type t_equiv = {tag:tag_info ; equiv:StateSetSet.t}
+
+module MemKey =
+ Set.Make
+ (struct
+ type t = t_equiv
+
+ let compare e1 e2 = match Pervasives.compare e1.tag e2.tag with
+ | 0 -> StateSetSet.compare e1.equiv e2.equiv
+ | r -> r
+ end)
+
+type dfa_key = {kstate : StateSet.t ; kmem : MemKey.t}
+
+(* Map a state to its key *)
+let env_to_class m =
+ let env1 =
+ MemMap.fold
+ (fun _ (tag,s) r ->
+ try
+ let ss = TagMap.find tag r in
+ let r = TagMap.remove tag r in
+ TagMap.add tag (StateSetSet.add s ss) r
+ with
+ | Not_found ->
+ TagMap.add tag (StateSetSet.add s StateSetSet.empty) r)
+ m TagMap.empty in
+ TagMap.fold
+ (fun tag ss r -> MemKey.add {tag=tag ; equiv=ss} r)
+ env1 MemKey.empty
+
+
+(* trans is nfa_state, m is associated memory map *)
+let inverse_mem_map trans m r =
+ TagMap.fold
+ (fun tag addr r ->
+ try
+ let otag,s = MemMap.find addr r in
+ assert (tag = otag) ;
+ let r = MemMap.remove addr r in
+ MemMap.add addr (tag,StateSet.add trans s) r
+ with
+ | Not_found ->
+ MemMap.add addr (tag,StateSet.add trans StateSet.empty) r)
+ m r
+
+let inverse_mem_map_other n (_,m) r = inverse_mem_map (OnChars n) m r
+
+let get_key {final=(act,(_,m_act)) ; others=o} =
+ let env =
+ MemMap.fold inverse_mem_map_other
+ o
+ (if act = no_action then MemMap.empty
+ else inverse_mem_map (ToAction act) m_act MemMap.empty) in
+ let state_key =
+ MemMap.fold (fun n _ r -> StateSet.add (OnChars n) r) o
+ (if act=no_action then StateSet.empty
+ else StateSet.add (ToAction act) StateSet.empty) in
+ let mem_key = env_to_class env in
+ {kstate = state_key ; kmem = mem_key}
+
+
+let key_compare k1 k2 = match StateSet.compare k1.kstate k2.kstate with
+| 0 -> MemKey.compare k1.kmem k2.kmem
+| r -> r
+
+(* Association dfa_state -> state_num *)
+
+module StateMap =
+ Map.Make(struct type t = dfa_key let compare = key_compare end)
+
+let state_map = ref (StateMap.empty : int StateMap.t)
+let todo = Stack.create()
+let next_state_num = ref 0
+let next_mem_cell = ref 0
+let temp_pending = ref false
+let tag_cells = Hashtbl.create 17
+let state_table = Table.create dfa_state_empty
+
+
+(* Initial reset of state *)
+let reset_state () =
+ Stack.clear todo;
+ next_state_num := 0 ;
+ let _ = Table.trim state_table in
+ ()
+
+(* Reset state before processing a given automata.
+ We clear both the memory mapping and
+ the state mapping, as state sharing beetween different
+ automata may lead to incorret estimation of the cell memory size
+ BUG ID 0004517 *)
+
+
+let reset_state_partial ntags =
+ next_mem_cell := ntags ;
+ Hashtbl.clear tag_cells ;
+ temp_pending := false ;
+ state_map := StateMap.empty
+
+let do_alloc_temp () =
+ temp_pending := true ;
+ let n = !next_mem_cell in
+ n
+
+let do_alloc_cell used t =
+ let available =
+ try Hashtbl.find tag_cells t with Not_found -> Ints.empty in
+ try
+ Ints.choose (Ints.diff available used)
+ with
+ | Not_found ->
+ temp_pending := false ;
+ let n = !next_mem_cell in
+ if n >= 255 then raise Memory_overflow ;
+ Hashtbl.replace tag_cells t (Ints.add n available) ;
+ incr next_mem_cell ;
+ n
+
+let is_old_addr a = a >= 0
+and is_new_addr a = a < 0
+
+let old_in_map m r =
+ TagMap.fold
+ (fun _ addr r ->
+ if is_old_addr addr then
+ Ints.add addr r
+ else
+ r)
+ m r
+
+let alloc_map used m mvs =
+ TagMap.fold
+ (fun tag a (r,mvs) ->
+ let a,mvs =
+ if is_new_addr a then
+ let a = do_alloc_cell used tag in
+ a,Ints.add a mvs
+ else a,mvs in
+ TagMap.add tag a r,mvs)
+ m (TagMap.empty,mvs)
+
+let create_new_state {final=(act,(_,m_act)) ; others=o} =
+ let used =
+ MemMap.fold (fun _ (_,m) r -> old_in_map m r)
+ o (old_in_map m_act Ints.empty) in
+
+ let new_m_act,mvs = alloc_map used m_act Ints.empty in
+ let new_o,mvs =
+ MemMap.fold (fun k (x,m) (r,mvs) ->
+ let m,mvs = alloc_map used m mvs in
+ MemMap.add k (x,m) r,mvs)
+ o (MemMap.empty,mvs) in
+ {final=(act,(0,new_m_act)) ; others=new_o},
+ Ints.fold (fun x r -> Set x::r) mvs []
+
+type new_addr_gen = {mutable count : int ; mutable env : int TagMap.t}
+
+let create_new_addr_gen () = {count = -1 ; env = TagMap.empty}
+
+let alloc_new_addr tag r =
+ try
+ TagMap.find tag r.env
+ with
+ | Not_found ->
+ let a = r.count in
+ r.count <- a-1 ;
+ r.env <- TagMap.add tag a r.env ;
+ a
+
+
+let create_mem_map tags gen =
+ Tags.fold
+ (fun tag r -> TagMap.add tag (alloc_new_addr tag gen) r)
+ tags TagMap.empty
+
+let create_init_state pos =
+ let gen = create_new_addr_gen () in
+ let st =
+ TransSet.fold
+ (fun (t,tags) st ->
+ match t with
+ | ToAction n ->
+ let on,otags = st.final in
+ if n < on then
+ {st with final = (n, (0,create_mem_map tags gen))}
+ else
+ st
+ | OnChars n ->
+ try
+ let _ = MemMap.find n st.others in assert false
+ with
+ | Not_found ->
+ {st with others =
+ MemMap.add n (0,create_mem_map tags gen) st.others})
+ pos dfa_state_empty in
+ st
+
+
+let get_map t st = match t with
+| ToAction _ -> let _,(_,m) = st.final in m
+| OnChars n ->
+ let (_,m) = MemMap.find n st.others in
+ m
+
+let dest = function | Copy (d,_) | Set d -> d
+and orig = function | Copy (_,o) -> o | Set _ -> -1
+
+let pmv oc mv = fprintf oc "%d <- %d" (dest mv) (orig mv)
+let pmvs oc mvs =
+ List.iter (fun mv -> fprintf oc "%a " pmv mv) mvs ;
+ output_char oc '\n' ; flush oc
+
+
+(* Topological sort << a la louche >> *)
+let sort_mvs mvs =
+ let rec do_rec r mvs = match mvs with
+ | [] -> r
+ | _ ->
+ let dests =
+ List.fold_left
+ (fun r mv -> Ints.add (dest mv) r)
+ Ints.empty mvs in
+ let rem,here =
+ List.partition
+ (fun mv -> Ints.mem (orig mv) dests)
+ mvs in
+ match here with
+ | [] ->
+ begin match rem with
+ | Copy (d,_)::_ ->
+ let d' = do_alloc_temp () in
+ Copy (d',d)::
+ do_rec r
+ (List.map
+ (fun mv ->
+ if orig mv = d then
+ Copy (dest mv,d')
+ else
+ mv)
+ rem)
+ | _ -> assert false
+ end
+ | _ -> do_rec (here@r) rem in
+ do_rec [] mvs
+
+let move_to mem_key src tgt =
+ let mvs =
+ MemKey.fold
+ (fun {tag=tag ; equiv=m} r ->
+ StateSetSet.fold
+ (fun s r ->
+ try
+ let t = StateSet.choose s in
+ let src = TagMap.find tag (get_map t src)
+ and tgt = TagMap.find tag (get_map t tgt) in
+ if src <> tgt then begin
+ if is_new_addr src then
+ Set tgt::r
+ else
+ Copy (tgt, src)::r
+ end else
+ r
+ with
+ | Not_found -> assert false)
+ m r)
+ mem_key [] in
+(* Moves are topologically sorted *)
+ sort_mvs mvs
+
+
+let get_state st =
+ let key = get_key st in
+ try
+ let num = StateMap.find key !state_map in
+ num,move_to key.kmem st (Table.get state_table num)
+ with Not_found ->
+ let num = !next_state_num in
+ incr next_state_num;
+ let st,mvs = create_new_state st in
+ Table.emit state_table st ;
+ state_map := StateMap.add key num !state_map;
+ Stack.push (st, num) todo;
+ num,mvs
+
+let map_on_all_states f old_res =
+ let res = ref old_res in
+ begin try
+ while true do
+ let (st, i) = Stack.pop todo in
+ let r = f st in
+ res := (r, i) :: !res
+ done
+ with Stack.Empty -> ()
+ end;
+ !res
+
+let goto_state st =
+ if
+ dfa_state_is_empty st
+ then
+ Backtrack,[]
+ else
+ let n,moves = get_state st in
+ Goto n,moves
+
+(****************************)
+(* compute reachable states *)
+(****************************)
+
+let add_tags_to_map gen tags m =
+ Tags.fold
+ (fun tag m ->
+ let m = TagMap.remove tag m in
+ TagMap.add tag (alloc_new_addr tag gen) m)
+ tags m
+
+let apply_transition gen r pri m = function
+ | ToAction n,tags ->
+ let on,(opri,_) = r.final in
+ if n < on || (on=n && pri < opri) then
+ let m = add_tags_to_map gen tags m in
+ {r with final=n,(pri,m)}
+ else r
+ | OnChars n,tags ->
+ try
+ let (opri,_) = MemMap.find n r.others in
+ if pri < opri then
+ let m = add_tags_to_map gen tags m in
+ {r with others=MemMap.add n (pri,m) (MemMap.remove n r.others)}
+ else
+ r
+ with
+ | Not_found ->
+ let m = add_tags_to_map gen tags m in
+ {r with others=MemMap.add n (pri,m) r.others}
+
+(* add transitions ts to new state r
+ transitions in ts start from state pri and memory map m
+*)
+let apply_transitions gen r pri m ts =
+ TransSet.fold
+ (fun t r -> apply_transition gen r pri m t)
+ ts r
+
+
+(* For a given nfa_state pos, refine char partition *)
+let rec split_env gen follow pos m s = function
+ | [] -> (* Can occur ! because of non-matching regexp ([^'\000'-'\255']) *)
+ []
+ | (s1,st1) as p::rem ->
+ let here = Cset.inter s s1 in
+ if Cset.is_empty here then
+ p::split_env gen follow pos m s rem
+ else
+ let rest = Cset.diff s here in
+ let rem =
+ if Cset.is_empty rest then
+ rem
+ else
+ split_env gen follow pos m rest rem
+ and new_st = apply_transitions gen st1 pos m follow in
+ let stay = Cset.diff s1 here in
+ if Cset.is_empty stay then
+ (here, new_st)::rem
+ else
+ (stay, st1)::(here, new_st)::rem
+
+
+(* For all nfa_state pos in a dfa state st *)
+let comp_shift gen chars follow st =
+ MemMap.fold
+ (fun pos (_,m) env -> split_env gen follow.(pos) pos m chars.(pos) env)
+ st [Cset.all_chars_eof,dfa_state_empty]
+
+
+let reachs chars follow st =
+ let gen = create_new_addr_gen () in
+(* build a association list (char set -> new state) *)
+ let env = comp_shift gen chars follow st in
+(* change it into (char set -> new state_num) *)
+ let env =
+ List.map
+ (fun (s,dfa_state) -> s,goto_state dfa_state) env in
+(* finally build the char indexed array -> new state num *)
+ let shift = Cset.env_to_array env in
+ shift
+
+
+let get_tag_mem n env t =
+ try
+ TagMap.find t env.(n)
+ with
+ | Not_found -> assert false
+
+let do_tag_actions n env m =
+
+ let used,r =
+ TagMap.fold (fun t m (used,r) ->
+ let a = get_tag_mem n env t in
+ Ints.add a used,SetTag (a,m)::r) m (Ints.empty,[]) in
+ let _,r =
+ TagMap.fold
+ (fun tag m (used,r) ->
+ if not (Ints.mem m used) && tag.start then
+ Ints.add m used, EraseTag m::r
+ else
+ used,r)
+ env.(n) (used,r) in
+ r
+
+
+let translate_state shortest_match tags chars follow st =
+ let (n,(_,m)) = st.final in
+ if MemMap.empty = st.others then
+ Perform (n,do_tag_actions n tags m)
+ else if shortest_match then begin
+ if n=no_action then
+ Shift (No_remember,reachs chars follow st.others)
+ else
+ Perform(n, do_tag_actions n tags m)
+ end else begin
+ Shift (
+ (if n = no_action then
+ No_remember
+ else
+ Remember (n,do_tag_actions n tags m)),
+ reachs chars follow st.others)
+ end
+
+let dtags chan tags =
+ Tags.iter
+ (fun t -> fprintf chan " %a" dtag t)
+ tags
+
+let dtransset s =
+ TransSet.iter
+ (fun trans -> match trans with
+ | OnChars i,tags ->
+ eprintf " (-> %d,%a)" i dtags tags
+ | ToAction i,tags ->
+ eprintf " ([%d],%a)" i dtags tags)
+ s
+
+let dfollow t =
+ eprintf "follow=[" ;
+ for i = 0 to Array.length t-1 do
+ eprintf "%d:" i ;
+ dtransset t.(i)
+ done ;
+ prerr_endline "]"
+
+
+let make_tag_entry id start act a r = match a with
+ | Sum (Mem m,0) ->
+ TagMap.add {id=id ; start=start ; action=act} m r
+ | _ -> r
+
+let extract_tags l =
+ let envs = Array.make (List.length l) TagMap.empty in
+ List.iter
+ (fun (act,m,_) ->
+ envs.(act) <-
+ List.fold_right
+ (fun ((name,_),v) r -> match v with
+ | Ident_char (_,t) -> make_tag_entry name true act t r
+ | Ident_string (_,t1,t2) ->
+ make_tag_entry name true act t1
+ (make_tag_entry name false act t2 r))
+ m TagMap.empty)
+ l ;
+ envs
+
+
+let make_dfa lexdef =
+ let (chars, entry_list) = encode_lexdef lexdef in
+ let follow = followpos (Array.length chars) entry_list in
+(*
+ dfollow follow ;
+*)
+ reset_state () ;
+ let r_states = ref [] in
+ let initial_states =
+ List.map
+ (fun (le,args,shortest) ->
+ let tags = extract_tags le.lex_actions in
+ reset_state_partial le.lex_mem_tags ;
+ let pos_set = firstpos le.lex_regexp in
+(*
+ prerr_string "trans={" ; dtransset pos_set ; prerr_endline "}" ;
+*)
+ let init_state = create_init_state pos_set in
+ let init_num = get_state init_state in
+ r_states :=
+ map_on_all_states
+ (translate_state shortest tags chars follow) !r_states ;
+ { auto_name = le.lex_name;
+ auto_args = args ;
+ auto_mem_size =
+ (if !temp_pending then !next_mem_cell+1 else !next_mem_cell) ;
+ auto_initial_state = init_num ;
+ auto_actions = le.lex_actions })
+ entry_list in
+ let states = !r_states in
+(*
+ prerr_endline "** states **" ;
+ for i = 0 to !next_state_num-1 do
+ eprintf "+++ %d +++\n" i ;
+ dstate (Table.get state_table i) ;
+ prerr_endline ""
+ done ;
+ eprintf "%d states\n" !next_state_num ;
+*)
+ let actions = Array.make !next_state_num (Perform (0,[])) in
+ List.iter (fun (act, i) -> actions.(i) <- act) states;
+(* Useless state reset, so as to restrict GC roots *)
+ reset_state () ;
+ reset_state_partial 0 ;
+ (initial_states, actions)
diff --git a/lex/lexgen.mli b/lex/lexgen.mli
new file mode 100644
index 0000000000..3fc8c905af
--- /dev/null
+++ b/lex/lexgen.mli
@@ -0,0 +1,57 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* raised when there are too many bindings (>= 254 memory cells) *)
+exception Memory_overflow
+
+
+(* Representation of automata *)
+
+
+type automata =
+ Perform of int * tag_action list
+ | Shift of automata_trans * (automata_move * memory_action list) array
+and automata_trans =
+ No_remember
+ | Remember of int * tag_action list
+and automata_move =
+ Backtrack
+ | Goto of int
+and memory_action =
+ | Copy of int * int
+ | Set of int
+
+and tag_action = SetTag of int * int | EraseTag of int
+
+type ident = string * Syntax.location
+
+(* Representation of entry points *)
+type tag_base = Start | End | Mem of int
+type tag_addr = Sum of (tag_base * int)
+type ident_info =
+ | Ident_string of bool * tag_addr * tag_addr
+ | Ident_char of bool * tag_addr
+
+type t_env = (ident * ident_info) list
+
+type ('args,'action) automata_entry =
+ { auto_name: string;
+ auto_args: 'args ;
+ auto_mem_size : int ;
+ auto_initial_state: int * memory_action list ;
+ auto_actions: (int * t_env * 'action) list }
+
+(* The entry point *)
+
+val make_dfa :
+ ('args, 'action) Syntax.entry list ->
+ ('args, 'action) automata_entry list * automata array
diff --git a/lex/main.ml b/lex/main.ml
new file mode 100644
index 0000000000..076873f103
--- /dev/null
+++ b/lex/main.ml
@@ -0,0 +1,122 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexer generator. Command-line parsing. *)
+
+open Syntax
+
+let ml_automata = ref false
+let source_name = ref None
+let output_name = ref None
+
+let usage = "usage: ocamllex [options] sourcefile"
+
+let print_version_string () =
+ print_string "The OCaml lexer generator, version ";
+ print_string Sys.ocaml_version ; print_newline();
+ exit 0
+
+let print_version_num () =
+ print_endline Sys.ocaml_version;
+ exit 0;
+;;
+
+let specs =
+ ["-ml", Arg.Set ml_automata,
+ " Output code that does not use the Lexing module built-in automata \
+ interpreter";
+ "-o", Arg.String (fun x -> output_name := Some x),
+ " <file> Set output file name to <file>";
+ "-q", Arg.Set Common.quiet_mode, " Do not display informational messages";
+ "-v", Arg.Unit print_version_string, " Print version and exit";
+ "-version", Arg.Unit print_version_string, " Print version and exit";
+ "-vnum", Arg.Unit print_version_num, " Print version number and exit";
+ ]
+
+let _ =
+ Arg.parse
+ specs
+ (fun name -> source_name := Some name)
+ usage
+
+
+let main () =
+
+ let source_name = match !source_name with
+ | None -> Arg.usage specs usage ; exit 2
+ | Some name -> name in
+ let dest_name = match !output_name with
+ | Some name -> name
+ | None ->
+ if Filename.check_suffix source_name ".mll" then
+ Filename.chop_suffix source_name ".mll" ^ ".ml"
+ else
+ source_name ^ ".ml" in
+
+ let ic = open_in_bin source_name in
+ let oc = open_out dest_name in
+ let tr = Common.open_tracker dest_name oc in
+ let lexbuf = Lexing.from_channel ic in
+ lexbuf.Lexing.lex_curr_p <-
+ {Lexing.pos_fname = source_name; Lexing.pos_lnum = 1;
+ Lexing.pos_bol = 0; Lexing.pos_cnum = 0};
+ try
+ let def = Parser.lexer_definition Lexer.main lexbuf in
+ let (entries, transitions) = Lexgen.make_dfa def.entrypoints in
+ if !ml_automata then begin
+ Outputbis.output_lexdef
+ source_name ic oc tr
+ def.header def.refill_handler entries transitions def.trailer
+ end else begin
+ let tables = Compact.compact_tables transitions in
+ Output.output_lexdef source_name ic oc tr
+ def.header def.refill_handler tables entries def.trailer
+ end;
+ close_in ic;
+ close_out oc;
+ Common.close_tracker tr;
+ with exn ->
+ close_in ic;
+ close_out oc;
+ Common.close_tracker tr;
+ Sys.remove dest_name;
+ begin match exn with
+ | Cset.Bad ->
+ let p = Lexing.lexeme_start_p lexbuf in
+ Printf.fprintf stderr
+ "File \"%s\", line %d, character %d: character set expected.\n"
+ p.Lexing.pos_fname p.Lexing.pos_lnum
+ (p.Lexing.pos_cnum - p.Lexing.pos_bol)
+ | Parsing.Parse_error ->
+ let p = Lexing.lexeme_start_p lexbuf in
+ Printf.fprintf stderr
+ "File \"%s\", line %d, character %d: syntax error.\n"
+ p.Lexing.pos_fname p.Lexing.pos_lnum
+ (p.Lexing.pos_cnum - p.Lexing.pos_bol)
+ | Lexer.Lexical_error(msg, file, line, col) ->
+ Printf.fprintf stderr
+ "File \"%s\", line %d, character %d: %s.\n"
+ file line col msg
+ | Lexgen.Memory_overflow ->
+ Printf.fprintf stderr
+ "File \"%s\":\n Position memory overflow, too many bindings\n"
+ source_name
+ | Output.Table_overflow ->
+ Printf.fprintf stderr
+ "File \"%s\":\ntransition table overflow, automaton is too big\n"
+ source_name
+ | _ ->
+ raise exn
+ end;
+ exit 3
+
+let _ = (* Printexc.catch *) main (); exit 0
diff --git a/lex/output.ml b/lex/output.ml
new file mode 100644
index 0000000000..638260c2b4
--- /dev/null
+++ b/lex/output.ml
@@ -0,0 +1,149 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Output the DFA tables and its entry points *)
+
+open Printf
+open Lexgen
+open Compact
+open Common
+
+(* To output an array of short ints, encoded as a string *)
+
+let output_byte oc b =
+ output_char oc '\\';
+ output_char oc (Char.chr(48 + b / 100));
+ output_char oc (Char.chr(48 + (b / 10) mod 10));
+ output_char oc (Char.chr(48 + b mod 10))
+
+let output_array oc v =
+ output_string oc " \"";
+ for i = 0 to Array.length v - 1 do
+ output_byte oc (v.(i) land 0xFF);
+ output_byte oc ((v.(i) asr 8) land 0xFF);
+ if i land 7 = 7 then output_string oc "\\\n "
+ done;
+ output_string oc "\""
+
+let output_byte_array oc v =
+ output_string oc " \"";
+ for i = 0 to Array.length v - 1 do
+ output_byte oc (v.(i) land 0xFF);
+ if i land 15 = 15 then output_string oc "\\\n "
+ done;
+ output_string oc "\""
+
+(* Output the tables *)
+
+let output_tables oc tbl =
+ output_string oc "let __ocaml_lex_tables = {\n";
+
+ fprintf oc " Lexing.lex_base = \n%a;\n" output_array tbl.tbl_base;
+ fprintf oc " Lexing.lex_backtrk = \n%a;\n" output_array tbl.tbl_backtrk;
+ fprintf oc " Lexing.lex_default = \n%a;\n" output_array tbl.tbl_default;
+ fprintf oc " Lexing.lex_trans = \n%a;\n" output_array tbl.tbl_trans;
+ fprintf oc " Lexing.lex_check = \n%a;\n" output_array tbl.tbl_check;
+ fprintf oc " Lexing.lex_base_code = \n%a;\n" output_array tbl.tbl_base_code;
+
+ fprintf oc " Lexing.lex_backtrk_code = \n%a;\n"
+ output_array tbl.tbl_backtrk_code;
+ fprintf oc " Lexing.lex_default_code = \n%a;\n"
+ output_array tbl.tbl_default_code;
+ fprintf oc " Lexing.lex_trans_code = \n%a;\n"
+ output_array tbl.tbl_trans_code;
+ fprintf oc " Lexing.lex_check_code = \n%a;\n"
+ output_array tbl.tbl_check_code;
+ fprintf oc " Lexing.lex_code = \n%a;\n" output_byte_array tbl.tbl_code;
+
+ output_string oc "}\n\n"
+
+
+(* Output the entries *)
+
+let output_entry sourcefile ic oc has_refill oci e =
+ let init_num, init_moves = e.auto_initial_state in
+ fprintf oc "%s %alexbuf =\
+\n %a%a __ocaml_lex_%s_rec %alexbuf %d\n"
+ e.auto_name
+ output_args e.auto_args
+ (fun oc x ->
+ if x > 0 then
+ fprintf oc "lexbuf.Lexing.lex_mem <- Array.make %d (-1) ; " x)
+ e.auto_mem_size
+ (output_memory_actions " ") init_moves
+ e.auto_name
+ output_args e.auto_args
+ init_num;
+ fprintf oc "and __ocaml_lex_%s_rec %alexbuf __ocaml_lex_state =\n"
+ e.auto_name output_args e.auto_args ;
+ fprintf oc " match Lexing.%sengine"
+ (if e.auto_mem_size == 0 then "" else "new_");
+ fprintf oc " __ocaml_lex_tables __ocaml_lex_state lexbuf with\n ";
+ List.iter
+ (fun (num, env, loc) ->
+ fprintf oc " | ";
+ fprintf oc "%d ->\n" num;
+ output_env ic oc oci env;
+ copy_chunk ic oc oci loc true;
+ fprintf oc "\n")
+ e.auto_actions;
+ if has_refill then
+ fprintf oc
+ " | __ocaml_lex_state -> __ocaml_lex_refill \
+ \n (fun lexbuf -> lexbuf.Lexing.refill_buff lexbuf; \
+ \n __ocaml_lex_%s_rec %alexbuf __ocaml_lex_state) lexbuf\n\n"
+ e.auto_name output_args e.auto_args
+ else
+ fprintf oc
+ " | __ocaml_lex_state -> lexbuf.Lexing.refill_buff lexbuf; \
+ \n __ocaml_lex_%s_rec %alexbuf __ocaml_lex_state\n\n"
+ e.auto_name output_args e.auto_args
+
+(* Main output function *)
+
+exception Table_overflow
+
+let output_lexdef sourcefile ic oc oci header rh tables entry_points trailer =
+ if not !Common.quiet_mode then
+ Printf.printf "%d states, %d transitions, table size %d bytes\n"
+ (Array.length tables.tbl_base)
+ (Array.length tables.tbl_trans)
+ (2 * (Array.length tables.tbl_base + Array.length tables.tbl_backtrk +
+ Array.length tables.tbl_default + Array.length tables.tbl_trans +
+ Array.length tables.tbl_check));
+ let size_groups =
+ (2 * (Array.length tables.tbl_base_code +
+ Array.length tables.tbl_backtrk_code +
+ Array.length tables.tbl_default_code +
+ Array.length tables.tbl_trans_code +
+ Array.length tables.tbl_check_code) +
+ Array.length tables.tbl_code) in
+ if size_groups > 0 && not !Common.quiet_mode then
+ Printf.printf "%d additional bytes used for bindings\n" size_groups ;
+ flush stdout;
+ if Array.length tables.tbl_trans > 0x8000 then raise Table_overflow;
+ copy_chunk ic oc oci header false;
+ let has_refill = output_refill_handler ic oc oci rh in
+ output_tables oc tables;
+ begin match entry_points with
+ [] -> ()
+ | entry1 :: entries ->
+ output_string oc "let rec ";
+ output_entry sourcefile ic oc has_refill oci entry1;
+ List.iter
+ (fun e ->
+ output_string oc "and ";
+ output_entry sourcefile ic oc has_refill oci e)
+ entries;
+ output_string oc ";;\n\n";
+ end;
+ copy_chunk ic oc oci trailer false
diff --git a/lex/output.mli b/lex/output.mli
new file mode 100644
index 0000000000..9d0bd9fc80
--- /dev/null
+++ b/lex/output.mli
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Output the DFA tables and its entry points *)
+
+val output_lexdef:
+ string -> in_channel -> out_channel -> Common.line_tracker ->
+ Syntax.location ->
+ Syntax.location option ->
+ Compact.lex_tables ->
+ (string list, Syntax.location) Lexgen.automata_entry list ->
+ Syntax.location ->
+ unit
+
+exception Table_overflow
diff --git a/lex/outputbis.ml b/lex/outputbis.ml
new file mode 100644
index 0000000000..709ec0eec8
--- /dev/null
+++ b/lex/outputbis.ml
@@ -0,0 +1,238 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Output the DFA tables and its entry points *)
+
+open Printf
+open Lexgen
+open Common
+
+let output_auto_defs oc has_refill =
+ output_string oc
+ "let __ocaml_lex_init_lexbuf lexbuf mem_size =\
+\n let pos = lexbuf.Lexing.lex_curr_pos in\
+\n lexbuf.Lexing.lex_mem <- Array.make mem_size (-1) ;\
+\n lexbuf.Lexing.lex_start_pos <- pos ;\
+\n lexbuf.Lexing.lex_last_pos <- pos ;\
+\n lexbuf.Lexing.lex_last_action <- -1\
+\n\n\
+" ;
+
+ if has_refill then
+ output_string oc
+ "let rec __ocaml_lex_next_char lexbuf state k =\
+\n if lexbuf.Lexing.lex_curr_pos >= lexbuf.Lexing.lex_buffer_len then begin\
+\n if lexbuf.Lexing.lex_eof_reached then\
+\n state lexbuf k 256\
+\n else begin\
+\n __ocaml_lex_refill (fun lexbuf ->
+\n lexbuf.Lexing.refill_buff lexbuf ;\
+\n __ocaml_lex_next_char lexbuf state k)\
+\n lexbuf\
+\n end\
+\n end else begin\
+\n let i = lexbuf.Lexing.lex_curr_pos in\
+\n let c = lexbuf.Lexing.lex_buffer.[i] in\
+\n lexbuf.Lexing.lex_curr_pos <- i+1 ;\
+\n state lexbuf k (Char.code c)\
+\n end\
+\n\n"
+ else
+ output_string oc
+ "let rec __ocaml_lex_next_char lexbuf =\
+\n if lexbuf.Lexing.lex_curr_pos >= lexbuf.Lexing.lex_buffer_len then begin\
+\n if lexbuf.Lexing.lex_eof_reached then\
+\n 256\
+\n else begin\
+\n lexbuf.Lexing.refill_buff lexbuf ;\
+\n __ocaml_lex_next_char lexbuf\
+\n end\
+\n end else begin\
+\n let i = lexbuf.Lexing.lex_curr_pos in\
+\n let c = lexbuf.Lexing.lex_buffer.[i] in\
+\n lexbuf.Lexing.lex_curr_pos <- i+1 ;\
+\n Char.code c\
+\n end\
+\n\n"
+
+
+let output_pats oc pats = List.iter (fun p -> fprintf oc "|%d" p) pats
+
+let output_action oc has_refill mems r =
+ output_memory_actions " " oc mems ;
+ match r with
+ | Backtrack ->
+ fprintf oc
+ " lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_last_pos ;\n" ;
+ if has_refill then
+ fprintf oc " k lexbuf lexbuf.Lexing.lex_last_action\n"
+ else
+ fprintf oc " lexbuf.Lexing.lex_last_action\n"
+ | Goto n ->
+ fprintf oc " __ocaml_lex_state%d lexbuf%s\n" n
+ (if has_refill then " k" else "")
+
+let output_pat oc i =
+ if i >= 256 then
+ fprintf oc "|eof"
+ else
+ fprintf oc "|'%s'" (Char.escaped (Char.chr i))
+
+let output_clause oc has_refill pats mems r =
+ fprintf oc "(* " ;
+ List.iter (output_pat oc) pats ;
+ fprintf oc " *)\n" ;
+ fprintf oc " %a ->\n" output_pats pats ;
+ output_action oc has_refill mems r
+
+let output_default_clause oc has_refill mems r =
+ fprintf oc " | _ ->\n" ; output_action oc has_refill mems r
+
+
+let output_moves oc has_refill moves =
+ let t = Hashtbl.create 17 in
+ let add_move i (m,mems) =
+ let mems,r = try Hashtbl.find t m with Not_found -> mems,[] in
+ Hashtbl.replace t m (mems,(i::r)) in
+
+ for i = 0 to 256 do
+ add_move i moves.(i)
+ done ;
+
+ let most_frequent = ref Backtrack
+ and most_mems = ref []
+ and size = ref 0 in
+ Hashtbl.iter
+ (fun m (mems,pats) ->
+ let size_m = List.length pats in
+ if size_m > !size then begin
+ most_frequent := m ;
+ most_mems := mems ;
+ size := size_m
+ end)
+ t ;
+ Hashtbl.iter
+ (fun m (mems,pats) ->
+ if m <> !most_frequent then
+ output_clause oc has_refill (List.rev pats) mems m)
+ t ;
+ output_default_clause oc has_refill !most_mems !most_frequent
+
+
+let output_tag_actions pref oc mvs =
+ output_string oc "(*" ;
+ List.iter
+ (fun i -> match i with
+ | SetTag (t,m) -> fprintf oc " t%d <- [%d] ;" t m
+ | EraseTag t -> fprintf oc " t%d <- -1 ;" t)
+ mvs ;
+ output_string oc " *)\n" ;
+ List.iter
+ (fun i -> match i with
+ | SetTag (t,m) ->
+ fprintf oc "%s%a <- %a ;\n"
+ pref output_mem_access t output_mem_access m
+ | EraseTag t ->
+ fprintf oc "%s%a <- -1 ;\n"
+ pref output_mem_access t)
+ mvs
+
+let output_trans pref oc has_refill i trans =
+ let entry = sprintf "__ocaml_lex_state%d" i in
+ fprintf oc "%s %s lexbuf %s= " pref entry
+ (if has_refill then "k " else "");
+ match trans with
+ | Perform (n,mvs) ->
+ output_tag_actions " " oc mvs ;
+ fprintf oc " %s%d\n"
+ (if has_refill then "k lexbuf " else "")
+ n
+ | Shift (trans, move) ->
+ begin match trans with
+ | Remember (n,mvs) ->
+ output_tag_actions " " oc mvs ;
+ fprintf oc
+ " lexbuf.Lexing.lex_last_pos <- lexbuf.Lexing.lex_curr_pos ;\n" ;
+ fprintf oc " lexbuf.Lexing.lex_last_action <- %d ;\n" n;
+ | No_remember -> ()
+ end;
+ if has_refill then
+ let next = entry ^ "_next" in
+ fprintf oc " __ocaml_lex_next_char lexbuf %s k\n" next;
+ fprintf oc "and %s lexbuf k = function " next
+ else
+ output_string oc "match __ocaml_lex_next_char lexbuf with\n";
+ output_moves oc has_refill move
+
+let output_automata oc has_refill auto =
+ output_auto_defs oc has_refill;
+ let n = Array.length auto in
+ output_trans "let rec" oc has_refill 0 auto.(0) ;
+ for i = 1 to n-1 do
+ output_trans "\nand" oc has_refill i auto.(i)
+ done ;
+ output_char oc '\n'
+
+
+(* Output the entries *)
+
+let output_entry sourcefile ic oc has_refill tr e =
+ let init_num, init_moves = e.auto_initial_state in
+ fprintf oc "%s %alexbuf =\n __ocaml_lex_init_lexbuf lexbuf %d; %a"
+ e.auto_name output_args e.auto_args
+ e.auto_mem_size
+ (output_memory_actions " ") init_moves;
+ fprintf oc
+ (if has_refill
+ then "\n __ocaml_lex_state%d lexbuf (fun lexbuf __ocaml_lex_result ->"
+ else "\n let __ocaml_lex_result = __ocaml_lex_state%d lexbuf in")
+ init_num;
+ output_string oc "\
+\n lexbuf.Lexing.lex_start_p <- lexbuf.Lexing.lex_curr_p;\
+\n lexbuf.Lexing.lex_curr_p <- {lexbuf.Lexing.lex_curr_p with\
+\n Lexing.pos_cnum = lexbuf.Lexing.lex_abs_pos+lexbuf.Lexing.lex_curr_pos};\
+\n match __ocaml_lex_result with\n";
+ List.iter
+ (fun (num, env, loc) ->
+ fprintf oc " | ";
+ fprintf oc "%d ->\n" num;
+ output_env ic oc tr env ;
+ copy_chunk ic oc tr loc true;
+ fprintf oc "\n")
+ e.auto_actions;
+ fprintf oc " | _ -> raise (Failure \"lexing: empty token\")\n";
+ if has_refill then
+ output_string oc " )\n\n"
+ else
+ output_string oc "\n\n"
+
+
+(* Main output function *)
+
+let output_lexdef sourcefile ic oc tr header rh
+ entry_points transitions trailer =
+
+ copy_chunk ic oc tr header false;
+ let has_refill = output_refill_handler ic oc tr rh in
+ output_automata oc has_refill transitions;
+ begin match entry_points with
+ [] -> ()
+ | entry1 :: entries ->
+ output_string oc "let rec ";
+ output_entry sourcefile ic oc has_refill tr entry1;
+ List.iter
+ (fun e -> output_string oc "and ";
+ output_entry sourcefile ic oc has_refill tr e)
+ entries;
+ output_string oc ";;\n\n";
+ end;
+ copy_chunk ic oc tr trailer false
diff --git a/lex/outputbis.mli b/lex/outputbis.mli
new file mode 100644
index 0000000000..fb51cdec7c
--- /dev/null
+++ b/lex/outputbis.mli
@@ -0,0 +1,21 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget projet Moscova INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val output_lexdef :
+ string ->
+ in_channel ->
+ out_channel ->
+ Common.line_tracker ->
+ Syntax.location ->
+ Syntax.location option ->
+ (string list, Syntax.location) Lexgen.automata_entry list ->
+ Lexgen.automata array -> Syntax.location -> unit
diff --git a/lex/parser.mly b/lex/parser.mly
new file mode 100644
index 0000000000..459b787077
--- /dev/null
+++ b/lex/parser.mly
@@ -0,0 +1,199 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* The grammar for lexer definitions */
+
+%{
+open Syntax
+
+(* Auxiliaries for the parser. *)
+
+let named_regexps =
+ (Hashtbl.create 13 : (string, regular_expression) Hashtbl.t)
+
+let regexp_for_string s =
+ let rec re_string n =
+ if n >= String.length s then Epsilon
+ else if succ n = String.length s then
+ Characters (Cset.singleton (Char.code s.[n]))
+ else
+ Sequence
+ (Characters(Cset.singleton (Char.code s.[n])),
+ re_string (succ n))
+ in re_string 0
+
+let rec remove_as = function
+ | Bind (e,_) -> remove_as e
+ | Epsilon|Eof|Characters _ as e -> e
+ | Sequence (e1, e2) -> Sequence (remove_as e1, remove_as e2)
+ | Alternative (e1, e2) -> Alternative (remove_as e1, remove_as e2)
+ | Repetition e -> Repetition (remove_as e)
+
+let as_cset = function
+ | Characters s -> s
+ | _ -> raise Cset.Bad
+
+%}
+
+%token <string> Tident
+%token <int> Tchar
+%token <string> Tstring
+%token <Syntax.location> Taction
+%token Trule Tparse Tparse_shortest Tand Tequal Tend Tor Tunderscore Teof
+ Tlbracket Trbracket Trefill
+%token Tstar Tmaybe Tplus Tlparen Trparen Tcaret Tdash Tlet Tas Tsharp
+
+%right Tas
+%left Tor
+%nonassoc CONCAT
+%nonassoc Tmaybe Tstar Tplus
+%left Tsharp
+%nonassoc Tident Tchar Tstring Tunderscore Teof Tlbracket Tlparen
+
+%start lexer_definition
+%type <Syntax.lexer_definition> lexer_definition
+
+%%
+
+lexer_definition:
+ header named_regexps refill_handler Trule definition other_definitions
+ header Tend
+ { {header = $1;
+ refill_handler = $3;
+ entrypoints = $5 :: List.rev $6;
+ trailer = $7} }
+;
+header:
+ Taction
+ { $1 }
+ | /*epsilon*/
+ { { loc_file = ""; start_pos = 0; end_pos = 0; start_line = 1;
+ start_col = 0 } }
+;
+named_regexps:
+ named_regexps Tlet Tident Tequal regexp
+ { Hashtbl.add named_regexps $3 $5 }
+ | /*epsilon*/
+ { () }
+;
+other_definitions:
+ other_definitions Tand definition
+ { $3::$1 }
+ | /*epsilon*/
+ { [] }
+;
+refill_handler:
+ | Trefill Taction { Some $2 }
+ | /*empty*/ { None }
+;
+definition:
+ Tident arguments Tequal Tparse entry
+ { {name=$1 ; shortest=false ; args=$2 ; clauses=$5} }
+ | Tident arguments Tequal Tparse_shortest entry
+ { {name=$1 ; shortest=true ; args=$2 ; clauses=$5} }
+;
+
+arguments:
+ Tident arguments { $1::$2 }
+| /*epsilon*/ { [] }
+;
+
+
+entry:
+ case rest_of_entry
+ { $1::List.rev $2 }
+| Tor case rest_of_entry
+ { $2::List.rev $3 }
+;
+
+rest_of_entry:
+ rest_of_entry Tor case
+ { $3::$1 }
+ |
+ { [] }
+;
+case:
+ regexp Taction
+ { ($1,$2) }
+;
+regexp:
+ Tunderscore
+ { Characters Cset.all_chars }
+ | Teof
+ { Eof }
+ | Tchar
+ { Characters (Cset.singleton $1) }
+ | Tstring
+ { regexp_for_string $1 }
+ | Tlbracket char_class Trbracket
+ { Characters $2 }
+ | regexp Tstar
+ { Repetition $1 }
+ | regexp Tmaybe
+ { Alternative(Epsilon, $1) }
+ | regexp Tplus
+ { Sequence(Repetition (remove_as $1), $1) }
+ | regexp Tsharp regexp
+ {
+ let s1 = as_cset $1
+ and s2 = as_cset $3 in
+ Characters (Cset.diff s1 s2)
+ }
+ | regexp Tor regexp
+ { Alternative($1,$3) }
+ | regexp regexp %prec CONCAT
+ { Sequence($1,$2) }
+ | Tlparen regexp Trparen
+ { $2 }
+ | Tident
+ { try
+ Hashtbl.find named_regexps $1
+ with Not_found ->
+ let p = Parsing.symbol_start_pos () in
+ Printf.eprintf "File \"%s\", line %d, character %d:\n\
+ Reference to unbound regexp name `%s'.\n"
+ p.Lexing.pos_fname p.Lexing.pos_lnum
+ (p.Lexing.pos_cnum - p.Lexing.pos_bol)
+ $1;
+ exit 2 }
+ | regexp Tas ident
+ {let p1 = Parsing.rhs_start_pos 3
+ and p2 = Parsing.rhs_end_pos 3 in
+ let p = {
+ loc_file = p1.Lexing.pos_fname ;
+ start_pos = p1.Lexing.pos_cnum ;
+ end_pos = p2.Lexing.pos_cnum ;
+ start_line = p1.Lexing.pos_lnum ;
+ start_col = p1.Lexing.pos_cnum - p1.Lexing.pos_bol ; } in
+ Bind ($1, ($3, p))}
+;
+
+ident:
+ Tident {$1}
+;
+
+char_class:
+ Tcaret char_class1
+ { Cset.complement $2 }
+ | char_class1
+ { $1 }
+;
+char_class1:
+ Tchar Tdash Tchar
+ { Cset.interval $1 $3 }
+ | Tchar
+ { Cset.singleton $1 }
+ | char_class1 char_class1 %prec CONCAT
+ { Cset.union $1 $2 }
+;
+
+%%
diff --git a/lex/syntax.ml b/lex/syntax.ml
new file mode 100644
index 0000000000..b2993eaa02
--- /dev/null
+++ b/lex/syntax.ml
@@ -0,0 +1,46 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* This apparently useless implementation file is in fact required
+ by the pa_ocamllex syntax extension *)
+
+(* The shallow abstract syntax *)
+
+type location = {
+ loc_file : string;
+ start_pos : int;
+ end_pos : int;
+ start_line : int;
+ start_col : int;
+}
+
+type regular_expression =
+ Epsilon
+ | Characters of Cset.t
+ | Eof
+ | Sequence of regular_expression * regular_expression
+ | Alternative of regular_expression * regular_expression
+ | Repetition of regular_expression
+ | Bind of regular_expression * (string * location)
+
+type ('arg,'action) entry =
+ {name:string ;
+ shortest : bool ;
+ args : 'arg ;
+ clauses : (regular_expression * 'action) list}
+
+type lexer_definition = {
+ header: location;
+ entrypoints: ((string list, location) entry) list;
+ trailer: location;
+ refill_handler : location option;
+}
diff --git a/lex/syntax.mli b/lex/syntax.mli
new file mode 100644
index 0000000000..6871dd118d
--- /dev/null
+++ b/lex/syntax.mli
@@ -0,0 +1,43 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The shallow abstract syntax *)
+
+type location = {
+ loc_file : string;
+ start_pos : int;
+ end_pos : int;
+ start_line : int;
+ start_col : int;
+}
+
+type regular_expression =
+ Epsilon
+ | Characters of Cset.t
+ | Eof
+ | Sequence of regular_expression * regular_expression
+ | Alternative of regular_expression * regular_expression
+ | Repetition of regular_expression
+ | Bind of regular_expression * (string * location)
+
+type ('arg,'action) entry =
+ {name:string ;
+ shortest : bool ;
+ args : 'arg ;
+ clauses : (regular_expression * 'action) list}
+
+type lexer_definition = {
+ header: location;
+ entrypoints: ((string list, location) entry) list;
+ trailer: location;
+ refill_handler : location option;
+}
diff --git a/lex/table.ml b/lex/table.ml
new file mode 100644
index 0000000000..715d90758d
--- /dev/null
+++ b/lex/table.ml
@@ -0,0 +1,56 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type 'a t = {mutable next : int ; mutable data : 'a array}
+
+let default_size = 32
+;;
+
+let create x = {next = 0 ; data = Array.make default_size x}
+and reset t = t.next <- 0
+;;
+
+let incr_table table new_size =
+ let t = Array.make new_size table.data.(0) in
+ Array.blit table.data 0 t 0 (Array.length table.data) ;
+ table.data <- t
+
+let emit table i =
+ let size = Array.length table.data in
+ if table.next >= size then
+ incr_table table (2*size);
+ table.data.(table.next) <- i ;
+ table.next <- table.next + 1
+;;
+
+
+exception Error
+
+let get t i =
+ if 0 <= i && i < t.next then
+ t.data.(i)
+ else
+ raise Error
+
+let trim t =
+ let r = Array.sub t.data 0 t.next in
+ reset t ;
+ r
+
+let iter t f =
+ let size = t.next
+ and data = t.data in
+ for i = 0 to size-1 do
+ f data.(i)
+ done
+
+let size t = t.next
diff --git a/lex/table.mli b/lex/table.mli
new file mode 100644
index 0000000000..8d9938cbff
--- /dev/null
+++ b/lex/table.mli
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Table used for code emission, ie extensible arrays *)
+type 'a t
+
+val create : 'a -> 'a t
+
+val emit : 'a t -> 'a -> unit
+
+val iter : 'a t -> ('a -> unit) -> unit
+
+val trim : 'a t -> 'a array
+
+
+exception Error
+
+val get : 'a t -> int -> 'a
+
+
+
+val size : 'a t -> int
diff --git a/man/Makefile b/man/Makefile
new file mode 100644
index 0000000000..c1c2df3752
--- /dev/null
+++ b/man/Makefile
@@ -0,0 +1,24 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+include ../config/Makefile
+
+INSTALL_DIR=$(DESTDIR)$(MANDIR)/man$(MANEXT)
+
+install:
+ for i in *.m; do cp $$i $(INSTALL_DIR)/`basename $$i .m`.$(MANEXT); done
+ echo '.so man$(MANEXT)/ocamlc.$(MANEXT)' \
+ > $(INSTALL_DIR)/ocamlc.opt.$(MANEXT)
+ echo '.so man$(MANEXT)/ocamlopt.$(MANEXT)' \
+ > $(INSTALL_DIR)/ocamlopt.opt.$(MANEXT)
+ echo '.so man$(MANEXT)/ocamlcp.$(MANEXT)' \
+ > $(INSTALL_DIR)/ocamloptp.$(MANEXT)
diff --git a/man/ocaml.m b/man/ocaml.m
new file mode 100644
index 0000000000..5c839ea61d
--- /dev/null
+++ b/man/ocaml.m
@@ -0,0 +1,255 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAML 1
+
+.SH NAME
+ocaml \- The OCaml interactive toplevel
+
+.SH SYNOPSIS
+.B ocaml
+[
+.I options
+]
+[
+.I object-files
+]
+[
+.I script-file
+]
+.SH DESCRIPTION
+
+The
+.BR ocaml (1)
+command is the toplevel system for OCaml,
+that permits interactive use of the OCaml system through a
+read-eval-print loop. In this mode, the system repeatedly reads OCaml
+phrases from the input, then typechecks, compiles and evaluates
+them, then prints the inferred type and result value, if any. The
+system prints a # (sharp) prompt before reading each phrase.
+
+A toplevel phrase can span several lines. It is terminated by ;; (a
+double-semicolon). The syntax of toplevel phrases is as follows.
+
+The toplevel system is started by the command
+.BR ocaml (1).
+Phrases are read on standard input, results are printed on standard
+output, errors on standard error. End-of-file on standard input
+terminates
+.BR ocaml (1).
+
+If one or more
+.I object-files
+(ending in .cmo or .cma) are given, they are loaded silently before
+starting the toplevel.
+
+If a
+.I script-file
+is given, phrases are read silently from the file, errors printed on
+standard error.
+.BR ocaml (1)
+exits after the execution of the last phrase.
+
+.SH OPTIONS
+
+The following command-line options are recognized by
+.BR ocaml (1).
+.TP
+.B \-absname
+Show absolute filenames in error messages.
+.TP
+.BI \-I \ directory
+Add the given directory to the list of directories searched for
+source and compiled files. By default, the current directory is
+searched first, then the standard library directory. Directories added
+with
+.B \-I
+are searched after the current directory, in the order in which they
+were given on the command line, but before the standard library
+directory.
+.IP
+If the given directory starts with
+.BR + ,
+it is taken relative to the
+standard library directory. For instance,
+.B \-I\ +compiler-libs
+adds the subdirectory
+.B compiler-libs
+of the standard library to the search path.
+.IP
+Directories can also be added to the search path once the toplevel
+is running with the
+.B #directory
+directive.
+.TP
+.BI \-init \ file
+Load the given file instead of the default initialization file.
+The default file is
+.B .ocamlinit
+in the current directory if it exists, otherwise
+.B .ocamlinit
+in the user's home directory.
+.TP
+.B \-labels
+Labels are not ignored in types, labels may be used in applications,
+and labelled parameters can be given in any order. This is the default.
+.TP
+.B \-no\-app\-funct
+Deactivates the applicative behaviour of functors. With this option,
+each functor application generates new types in its result and
+applying the same functor twice to the same argument yields two
+incompatible structures.
+.TP
+.B \-noassert
+Do not compile assertion checks. Note that the special form
+.B assert\ false
+is always compiled because it is typed specially.
+.TP
+.B \-nolabels
+Ignore non-optional labels in types. Labels cannot be used in
+applications, and parameter order becomes strict.
+.TP
+.B \-noprompt
+Do not display any prompt when waiting for input.
+.TP
+.B \-nopromptcont
+Do not display the secondary prompt when waiting for continuation lines in
+multi-line inputs. This should be used e.g. when running
+.BR ocaml (1)
+in an
+.BR emacs (1)
+window.
+.TP
+.B \-nostdlib
+Do not include the standard library directory in the list of
+directories searched for source and compiled files.
+.TP
+.BI \-open \ module
+Opens the given module before starting the toplevel. If several
+.B \-open
+options are given, they are processed in order, just as if
+the statements open! module1;; ... open! moduleN;; were input.
+.TP
+.BI \-ppx \ command
+After parsing, pipe the abstract syntax tree through the preprocessor
+.IR command .
+The module
+.BR Ast_mapper (3)
+implements the external interface of a preprocessor.
+.TP
+.B \-principal
+Check information path during type-checking, to make sure that all
+types are derived in a principal way. When using labelled arguments
+and/or polymorphic methods, this flag is required to ensure future
+versions of the compiler will be able to infer types correctly, even
+if internal algorithms change.
+All programs accepted in
+.B \-principal
+mode are also accepted in the
+default mode with equivalent types, but different binary signatures,
+and this may slow down type checking; yet it is a good idea to
+use it once before publishing source code.
+.TP
+.B \-rectypes
+Allow arbitrary recursive types during type-checking. By default,
+only recursive types where the recursion goes through an object type
+are supported.
+.TP
+.B \-safe\-string
+Enforce the separation between types
+.BR string \ and\ bytes ,
+thereby making strings read-only. This will become the default in
+a future version of OCaml.
+.TP
+.B \-short\-paths
+When a type is visible under several module-paths, use the shortest
+one when printing the type's name in inferred interfaces and error and
+warning messages.
+.TP
+.B \-stdin
+Read the standard input as a script file rather than starting an
+interactive session.
+.TP
+.B \-strict\-sequence
+Force the left-hand part of each sequence to have type unit.
+.TP
+.B \-unsafe
+Turn bound checking off on array and string accesses (the
+.BR v.(i) and s.[i]
+constructs). Programs compiled with
+.B \-unsafe
+are therefore slightly faster, but unsafe: anything can happen if the program
+accesses an array or string outside of its bounds.
+.TP
+.B \-unsafe\-string
+Identify the types
+.BR string \ and\ bytes ,
+thereby making strings writable. For reasons of backward compatibility,
+this is the default setting for the moment, but this will change in a future
+version of OCaml.
+.TP
+.B \-version
+Print version string and exit.
+.TP
+.B \-vnum
+Print short version number and exit.
+.TP
+.BI \-w \ warning\-list
+Enable or disable warnings according to the argument
+.IR warning-list .
+See
+.BR ocamlc (1)
+for the syntax of the
+.I warning\-list
+argument.
+.TP
+.BI \-warn\-error \ warning\-list
+Mark as fatal the warnings described by the argument
+.IR warning\-list .
+Note that a warning is not triggered (and does not trigger an error) if
+it is disabled by the
+.B \-w
+option. See
+.BR ocamlc (1)
+for the syntax of the
+.I warning\-list
+argument.
+.TP
+.B \-warn\-help
+Show the description of all available warning numbers.
+.TP
+.BI \- \ file
+Use
+.I file
+as a script file name, even when it starts with a hyphen (-).
+.TP
+.BR \-help \ or \ \-\-help
+Display a short usage summary and exit.
+
+.SH ENVIRONMENT VARIABLES
+.TP
+.B LC_CTYPE
+If set to iso_8859_1, accented characters (from the
+ISO Latin-1 character set) in string and character literals are
+printed as is; otherwise, they are printed as decimal escape sequences.
+.TP
+.B TERM
+When printing error messages, the toplevel system
+attempts to underline visually the location of the error. It
+consults the TERM variable to determines the type of output terminal
+and look up its capabilities in the terminal database.
+
+.SH SEE ALSO
+.BR ocamlc (1), \ ocamlopt (1), \ ocamlrun (1).
+.br
+.IR The\ OCaml\ user's\ manual ,
+chapter "The toplevel system".
diff --git a/man/ocamlc.m b/man/ocamlc.m
new file mode 100644
index 0000000000..adb280927f
--- /dev/null
+++ b/man/ocamlc.m
@@ -0,0 +1,953 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLC 1
+
+.SH NAME
+ocamlc \- The OCaml bytecode compiler
+
+.SH SYNOPSIS
+.B ocamlc
+[
+.I options
+]
+.I filename ...
+
+.B ocamlc.opt
+[
+.I options
+]
+.I filename ...
+
+.SH DESCRIPTION
+
+The OCaml bytecode compiler
+.BR ocamlc (1)
+compiles OCaml source files to bytecode object files and links
+these object files to produce standalone bytecode executable files.
+These executable files are then run by the bytecode interpreter
+.BR ocamlrun (1).
+
+The
+.BR ocamlc (1)
+command has a command-line interface similar to the one of
+most C compilers. It accepts several types of arguments and processes them
+sequentially:
+
+Arguments ending in .mli are taken to be source files for
+compilation unit interfaces. Interfaces specify the names exported by
+compilation units: they declare value names with their types, define
+public data types, declare abstract data types, and so on. From the
+file
+.IR x \&.mli,
+the
+.BR ocamlc (1)
+compiler produces a compiled interface
+in the file
+.IR x \&.cmi.
+
+Arguments ending in .ml are taken to be source files for compilation
+unit implementations. Implementations provide definitions for the
+names exported by the unit, and also contain expressions to be
+evaluated for their side-effects. From the file
+.IR x \&.ml,
+the
+.BR ocamlc (1)
+compiler produces compiled object bytecode in the file
+.IR x \&.cmo.
+
+If the interface file
+.IR x \&.mli
+exists, the implementation
+.IR x \&.ml
+is checked against the corresponding compiled interface
+.IR x \&.cmi,
+which is assumed to exist. If no interface
+.IR x \&.mli
+is provided, the compilation of
+.IR x \&.ml
+produces a compiled interface file
+.IR x \&.cmi
+in addition to the compiled object code file
+.IR x \&.cmo.
+The file
+.IR x \&.cmi
+produced
+corresponds to an interface that exports everything that is defined in
+the implementation
+.IR x \&.ml.
+
+Arguments ending in .cmo are taken to be compiled object bytecode. These
+files are linked together, along with the object files obtained
+by compiling .ml arguments (if any), and the OCaml standard
+library, to produce a standalone executable program. The order in
+which .cmo and.ml arguments are presented on the command line is
+relevant: compilation units are initialized in that order at
+run-time, and it is a link-time error to use a component of a unit
+before having initialized it. Hence, a given
+.IR x \&.cmo
+file must come before all .cmo files that refer to the unit
+.IR x .
+
+Arguments ending in .cma are taken to be libraries of object bytecode.
+A library of object bytecode packs in a single file a set of object
+bytecode files (.cmo files). Libraries are built with
+.B ocamlc\ \-a
+(see the description of the
+.B \-a
+option below). The object files
+contained in the library are linked as regular .cmo files (see above),
+in the order specified when the .cma file was built. The only
+difference is that if an object file
+contained in a library is not referenced anywhere in the program, then
+it is not linked in.
+
+Arguments ending in .c are passed to the C compiler, which generates
+a .o object file. This object file is linked with the program if the
+.B \-custom
+flag is set (see the description of
+.B \-custom
+below).
+
+Arguments ending in .o or .a are assumed to be C object files and
+libraries. They are passed to the C linker when linking in
+.B \-custom
+mode (see the description of
+.B \-custom
+below).
+
+Arguments ending in .so
+are assumed to be C shared libraries (DLLs). During linking, they are
+searched for external C functions referenced from the OCaml code,
+and their names are written in the generated bytecode executable.
+The run-time system
+.BR ocamlrun (1)
+then loads them dynamically at program start-up time.
+
+The output of the linking phase is a file containing compiled bytecode
+that can be executed by the OCaml bytecode interpreter:
+the command
+.BR ocamlrun (1).
+If
+.B caml.out
+is the name of the file produced by the linking phase, the command
+.B ocamlrun caml.out
+.IR arg1 \ \ arg2 \ ... \ argn
+executes the compiled code contained in
+.BR caml.out ,
+passing it as arguments the character strings
+.I arg1
+to
+.IR argn .
+(See
+.BR ocamlrun (1)
+for more details.)
+
+On most systems, the file produced by the linking
+phase can be run directly, as in:
+.B ./caml.out
+.IR arg1 \ \ arg2 \ ... \ argn .
+The produced file has the executable bit set, and it manages to launch
+the bytecode interpreter by itself.
+
+.B ocamlc.opt
+is the same compiler as
+.BR ocamlc ,
+but compiled with the native-code compiler
+.BR ocamlopt (1).
+Thus, it behaves exactly like
+.BR ocamlc ,
+but compiles faster.
+.B ocamlc.opt
+may not be available in all installations of OCaml.
+
+.SH OPTIONS
+
+The following command-line options are recognized by
+.BR ocamlc (1).
+.TP
+.B \-a
+Build a library (.cma file) with the object files (.cmo files) given
+on the command line, instead of linking them into an executable
+file. The name of the library must be set with the
+.B \-o
+option.
+.IP
+If
+.BR \-custom , \ \-cclib \ or \ \-ccopt
+options are passed on the command
+line, these options are stored in the resulting .cma library. Then,
+linking with this library automatically adds back the
+.BR \-custom , \ \-cclib \ and \ \-ccopt
+options as if they had been provided on the
+command line, unless the
+.B -noautolink
+option is given. Additionally, a substring
+.B $CAMLORIGIN
+inside a
+.BR \ \-ccopt
+options will be replaced by the full path to the .cma library,
+excluding the filename.
+.B \-absname
+Show absolute filenames in error messages.
+.TP
+.B \-annot
+Dump detailed information about the compilation (types, bindings,
+tail-calls, etc). The information for file
+.IR src .ml
+is put into file
+.IR src .annot.
+In case of a type error, dump all the information inferred by the
+type-checker before the error. The
+.IR src .annot
+file can be used with the emacs commands given in
+.B emacs/caml\-types.el
+to display types and other annotations interactively.
+.TP
+.B \-bin\-annot
+Dump detailed information about the compilation (types, bindings,
+tail-calls, etc) in binary format. The information for file
+.IR src .ml
+is put into file
+.IR src .cmt.
+In case of a type error, dump
+all the information inferred by the type-checker before the error.
+The annotation files produced by
+.B \-bin\-annot
+contain more information
+and are much more compact than the files produced by
+.BR \-annot .
+.TP
+.B \-c
+Compile only. Suppress the linking phase of the
+compilation. Source code files are turned into compiled files, but no
+executable file is produced. This option is useful to
+compile modules separately.
+.TP
+.BI \-cc \ ccomp
+Use
+.I ccomp
+as the C linker when linking in "custom runtime" mode (see the
+.B \-custom
+option) and as the C compiler for compiling .c source files.
+.TP
+.BI \-cclib\ -l libname
+Pass the
+.BI \-l libname
+option to the C linker when linking in "custom runtime" mode (see the
+.B \-custom
+option). This causes the given C library to be linked with the program.
+.TP
+.BI \-ccopt \ option
+Pass the given
+.I option
+to the C compiler and linker, when linking in
+"custom runtime" mode (see the
+.B \-custom
+option). For instance,
+.BI \-ccopt\ \-L dir
+causes the C linker to search for C libraries in
+directory
+.IR dir .
+.TP
+.B \-compat\-32
+Check that the generated bytecode executable can run on 32-bit
+platforms and signal an error if it cannot. This is useful when
+compiling bytecode on a 64-bit machine.
+.TP
+.B \-config
+Print the version number of
+.BR ocamlc (1)
+and a detailed summary of its configuration, then exit.
+.TP
+.B \-custom
+Link in "custom runtime" mode. In the default linking mode, the
+linker produces bytecode that is intended to be executed with the
+shared runtime system,
+.BR ocamlrun (1).
+In the custom runtime mode, the
+linker produces an output file that contains both the runtime system
+and the bytecode for the program. The resulting file is larger, but it
+can be executed directly, even if the
+.BR ocamlrun (1)
+command is not
+installed. Moreover, the "custom runtime" mode enables linking OCaml
+code with user-defined C functions.
+
+Never use the
+.BR strip (1)
+command on executables produced by
+.BR ocamlc\ \-custom ,
+this would remove the bytecode part of the executable.
+.TP
+.BI \-dllib\ \-l libname
+Arrange for the C shared library
+.BI dll libname .so
+to be loaded dynamically by the run-time system
+.BR ocamlrun (1)
+at program start-up time.
+.TP
+.BI \-dllpath \ dir
+Adds the directory
+.I dir
+to the run-time search path for shared
+C libraries. At link-time, shared libraries are searched in the
+standard search path (the one corresponding to the
+.B \-I
+option).
+The
+.B \-dllpath
+option simply stores
+.I dir
+in the produced
+executable file, where
+.BR ocamlrun (1)
+can find it and use it.
+.TP
+.BI \-for\-pack \ ident
+This option is accepted for compatibility with
+.BR ocamlopt (1)
+; it does nothing.
+.TP
+.B \-g
+Add debugging information while compiling and linking. This option is
+required in order to be able to debug the program with
+.BR ocamldebug (1)
+and to produce stack backtraces when
+the program terminates on an uncaught exception.
+.TP
+.B \-i
+Cause the compiler to print all defined names (with their inferred
+types or their definitions) when compiling an implementation (.ml
+file). No compiled files (.cmo and .cmi files) are produced.
+This can be useful to check the types inferred by the
+compiler. Also, since the output follows the syntax of interfaces, it
+can help in writing an explicit interface (.mli file) for a file: just
+redirect the standard output of the compiler to a .mli file, and edit
+that file to remove all declarations of unexported names.
+.TP
+.BI \-I \ directory
+Add the given directory to the list of directories searched for
+compiled interface files (.cmi), compiled object code files
+(.cmo), libraries (.cma), and C libraries specified with
+.BI \-cclib\ \-l xxx
+.RB .
+By default, the current directory is searched first, then the
+standard library directory. Directories added with
+.B \-I
+are searched
+after the current directory, in the order in which they were given on
+the command line, but before the standard library directory. See also
+option
+.BR \-nostdlib .
+
+If the given directory starts with
+.BR + ,
+it is taken relative to the
+standard library directory. For instance,
+.B \-I\ +compiler-libs
+adds the subdirectory
+.B compiler-libs
+of the standard library to the search path.
+.TP
+.BI \-impl \ filename
+Compile the file
+.I filename
+as an implementation file, even if its extension is not .ml.
+.TP
+.BI \-intf \ filename
+Compile the file
+.I filename
+as an interface file, even if its extension is not .mli.
+.TP
+.BI \-intf\-suffix \ string
+Recognize file names ending with
+.I string
+as interface files (instead of the default .mli).
+.TP
+.B \-keep-docs
+Keep documentation strings in generated .cmi files.
+.TP
+.B \-keep-locs
+Keep locations in generated .cmi files.
+.TP
+.B \-labels
+Labels are not ignored in types, labels may be used in applications,
+and labelled parameters can be given in any order. This is the default.
+.TP
+.B \-linkall
+Force all modules contained in libraries to be linked in. If this
+flag is not given, unreferenced modules are not linked in. When
+building a library (option
+.BR \-a ),
+setting the
+.B \-linkall
+option forces all subsequent links of programs involving that library
+to link all the modules contained in the library.
+.TP
+.B \-make\-runtime
+Build a custom runtime system (in the file specified by option
+.BR \-o )
+incorporating the C object files and libraries given on the command
+line. This custom runtime system can be used later to execute
+bytecode executables produced with the option
+.B ocamlc\ \-use\-runtime
+.IR runtime-name .
+.TP
+.B \-no-alias-deps
+Do not record dependencies for module aliases.
+.TP
+.B \-no\-app\-funct
+Deactivates the applicative behaviour of functors. With this option,
+each functor application generates new types in its result and
+applying the same functor twice to the same argument yields two
+incompatible structures.
+.TP
+.B \-noassert
+Do not compile assertion checks. Note that the special form
+.B assert\ false
+is always compiled because it is typed specially.
+This flag has no effect when linking already-compiled files.
+.TP
+.B \-noautolink
+When linking .cma libraries, ignore
+.BR \-custom , \ \-cclib \ and \ \-ccopt
+options potentially contained in the libraries (if these options were
+given when building the libraries). This can be useful if a library
+contains incorrect specifications of C libraries or C options; in this
+case, during linking, set
+.B \-noautolink
+and pass the correct C libraries and options on the command line.
+.TP
+.B \-nolabels
+Ignore non-optional labels in types. Labels cannot be used in
+applications, and parameter order becomes strict.
+.TP
+.B \-nostdlib
+Do not automatically add the standard library directory to the list of
+directories searched for compiled interface files (.cmi), compiled
+object code files (.cmo), libraries (.cma), and C libraries specified
+with
+.BI \-cclib\ \-l xxx
+.RB .
+See also option
+.BR \-I .
+.TP
+.BI \-o \ exec\-file
+Specify the name of the output file produced by the linker. The
+default output name is
+.BR a.out ,
+in keeping with the Unix tradition. If the
+.B \-a
+option is given, specify the name of the library
+produced. If the
+.B \-pack
+option is given, specify the name of the
+packed object file produced. If the
+.B \-output\-obj
+option is given,
+specify the name of the output file produced.
+This can also be used when compiling an interface or implementation
+file, without linking, in which case it sets the name of the cmi or
+cmo file, and also sets the module name to the file name up to the
+first dot.
+.TP
+.BI \-open \ module
+Opens the given module before processing the interface or
+implementation files. If several
+.B \-open
+options are given, they are processed in order, just as if
+the statements open! module1;; ... open! moduleN;; were added
+at the top of each file.
+.TP
+.B \-output\-obj
+Cause the linker to produce a C object file instead of a bytecode
+executable file. This is useful to wrap OCaml code as a C library,
+callable from any C program. The name of the output object file
+must be set with the
+.B \-o
+option. This
+option can also be used to produce a C source file (.c extension) or
+a compiled shared/dynamic library (.so extension).
+.TP
+.B \-pack
+Build a bytecode object file (.cmo file) and its associated compiled
+interface (.cmi) that combines the object
+files given on the command line, making them appear as sub-modules of
+the output .cmo file. The name of the output .cmo file must be
+given with the
+.B \-o
+option. For instance,
+.B ocamlc\ \-pack\ \-o\ p.cmo\ a.cmo\ b.cmo\ c.cmo
+generates compiled files p.cmo and p.cmi describing a compilation
+unit having three sub-modules A, B and C, corresponding to the
+contents of the object files a.cmo, b.cmo and c.cmo. These
+contents can be referenced as P.A, P.B and P.C in the remainder
+of the program.
+.TP
+.BI \-pp \ command
+Cause the compiler to call the given
+.I command
+as a preprocessor for each source file. The output of
+.I command
+is redirected to
+an intermediate file, which is compiled. If there are no compilation
+errors, the intermediate file is deleted afterwards. The name of this
+file is built from the basename of the source file with the
+extension .ppi for an interface (.mli) file and .ppo for an
+implementation (.ml) file.
+.TP
+.BI \-ppx \ command
+After parsing, pipe the abstract syntax tree through the preprocessor
+.IR command .
+The module
+.BR Ast_mapper (3)
+implements the external interface of a preprocessor.
+.TP
+.B \-principal
+Check information path during type-checking, to make sure that all
+types are derived in a principal way. When using labelled arguments
+and/or polymorphic methods, this flag is required to ensure future
+versions of the compiler will be able to infer types correctly, even
+if internal algorithms change.
+All programs accepted in
+.B \-principal
+mode are also accepted in the
+default mode with equivalent types, but different binary signatures,
+and this may slow down type checking; yet it is a good idea to
+use it once before publishing source code.
+.TP
+.B \-rectypes
+Allow arbitrary recursive types during type-checking. By default,
+only recursive types where the recursion goes through an object type
+are supported. Note that once you have created an interface using this
+flag, you must use it again for all dependencies.
+.TP
+.BI \-runtime\-variant \ suffix
+Add
+.I suffix
+to the name of the runtime library that will be used by the program.
+If OCaml was configured with option
+.BR \-with\-debug\-runtime ,
+then the
+.B d
+suffix is supported and gives a debug version of the runtime.
+.TP
+.B \-safe\-string
+Enforce the separation between types
+.BR string \ and\ bytes ,
+thereby making strings read-only. This will become the default in
+a future version of OCaml.
+.TP
+.B \-short\-paths
+When a type is visible under several module-paths, use the shortest
+one when printing the type's name in inferred interfaces and error and
+warning messages.
+.TP
+.B \-strict\-sequence
+Force the left-hand part of each sequence to have type unit.
+.TP
+.B \-thread
+Compile or link multithreaded programs, in combination with the
+system "threads" library described in
+.IR The\ OCaml\ user's\ manual .
+.TP
+.B \-unsafe
+Turn bound checking off for array and string accesses (the
+.BR v.(i) and s.[i]
+constructs). Programs compiled with
+.B \-unsafe
+are therefore
+slightly faster, but unsafe: anything can happen if the program
+accesses an array or string outside of its bounds.
+.TP
+.B \-unsafe\-string
+Identify the types
+.BR string \ and\ bytes ,
+thereby making strings writable. For reasons of backward compatibility,
+this is the default setting for the moment, but this will change in a future
+version of OCaml.
+.TP
+.BI \-use\-runtime \ runtime\-name
+Generate a bytecode executable file that can be executed on the custom
+runtime system
+.IR runtime\-name ,
+built earlier with
+.B ocamlc\ \-make\-runtime
+.IR runtime\-name .
+.TP
+.B \-v
+Print the version number of the compiler and the location of the
+standard library directory, then exit.
+.TP
+.B \-verbose
+Print all external commands before they are executed, in particular
+invocations of the C compiler and linker in
+.B \-custom
+mode. Useful to debug C library problems.
+.TP
+.B \-vmthread
+Compile or link multithreaded programs, in combination with the
+VM-level threads library described in
+.IR The\ OCaml\ user's\ manual .
+.TP
+.BR \-vnum \ or\ \-version
+Print the version number of the compiler in short form (e.g. "3.11.0"),
+then exit.
+.TP
+.BI \-w \ warning\-list
+Enable, disable, or mark as fatal the warnings specified by the argument
+.IR warning\-list .
+
+Each warning can be
+.IR enabled \ or\ disabled ,
+and each warning can be
+.IR fatal or
+.IR non-fatal .
+If a warning is disabled, it isn't displayed and doesn't affect
+compilation in any way (even if it is fatal). If a warning is enabled,
+it is displayed normally by the compiler whenever the source code
+triggers it. If it is enabled and fatal, the compiler will also stop
+with an error after displaying it.
+
+The
+.I warning\-list
+argument is a sequence of warning specifiers, with no separators
+between them. A warning specifier is one of the following:
+
+.BI + num
+\ \ Enable warning number
+.IR num .
+
+.BI \- num
+\ \ Disable warning number
+.IR num .
+
+.BI @ num
+\ \ Enable and mark as fatal warning number
+.IR num .
+
+.BI + num1 .. num2
+\ \ Enable all warnings between
+.I num1
+and
+.I num2
+(inclusive).
+
+.BI \- num1 .. num2
+\ \ Disable all warnings between
+.I num1
+and
+.I num2
+(inclusive).
+
+.BI @ num1 .. num2
+\ \ Enable and mark as fatal all warnings between
+.I num1
+and
+.I num2
+(inclusive).
+
+.BI + letter
+\ \ Enable the set of warnings corresponding to
+.IR letter .
+The letter may be uppercase or lowercase.
+
+.BI \- letter
+\ \ Disable the set of warnings corresponding to
+.IR letter .
+The letter may be uppercase or lowercase.
+
+.BI @ letter
+\ \ Enable and mark as fatal the set of warnings corresponding to
+.IR letter .
+The letter may be uppercase or lowercase.
+
+.I uppercase\-letter
+\ \ Enable the set of warnings corresponding to
+.IR uppercase\-letter .
+
+.I lowercase\-letter
+\ \ Disable the set of warnings corresponding to
+.IR lowercase\-letter .
+
+The warning numbers are as follows.
+
+1
+\ \ \ Suspicious-looking start-of-comment mark.
+
+2
+\ \ \ Suspicious-looking end-of-comment mark.
+
+3
+\ \ \ Deprecated feature.
+
+4
+\ \ \ Fragile pattern matching: matching that will remain
+complete even if additional constructors are added to one of the
+variant types matched.
+
+5
+\ \ \ Partially applied function: expression whose result has
+function type and is ignored.
+
+6
+\ \ \ Label omitted in function application.
+
+7
+\ \ \ Method overridden without using the "method!" keyword
+
+8
+\ \ \ Partial match: missing cases in pattern-matching.
+
+9
+\ \ \ Missing fields in a record pattern.
+
+10
+\ \ Expression on the left-hand side of a sequence that doesn't
+have type
+.B unit
+(and that is not a function, see warning number 5).
+
+11
+\ \ Redundant case in a pattern matching (unused match case).
+
+12
+\ \ Redundant sub-pattern in a pattern-matching.
+
+13
+\ \ Override of an instance variable.
+
+14
+\ \ Illegal backslash escape in a string constant.
+
+15
+\ \ Private method made public implicitly.
+
+16
+\ \ Unerasable optional argument.
+
+17
+\ \ Undeclared virtual method.
+
+18
+\ \ Non-principal type.
+
+19
+\ \ Type without principality.
+
+20
+\ \ Unused function argument.
+
+21
+\ \ Non-returning statement.
+
+22
+\ \ Preprocessor warning.
+
+23
+\ \ Useless record
+.B with
+clause.
+
+24
+\ \ Bad module name: the source file name is not a valid OCaml module name.
+
+25
+\ \ Pattern-matching with all clauses guarded.
+
+26
+\ \ Suspicious unused variable: unused variable that is bound with
+.BR let \ or \ as ,
+and doesn't start with an underscore (_) character.
+
+27
+\ \ Innocuous unused variable: unused variable that is not bound with
+.BR let \ nor \ as ,
+and doesn't start with an underscore (_) character.
+
+28
+\ \ A pattern contains a constant constructor applied to the underscore (_)
+pattern.
+
+29
+\ \ A non-escaped end-of-line was found in a string constant. This may
+cause portability problems between Unix and Windows.
+
+30
+\ \ Two labels or constructors of the same name are defined in two
+mutually recursive types.
+
+31
+\ \ A module is linked twice in the same executable.
+
+32
+\ \ Unused value declaration.
+
+33
+\ \ Unused open statement.
+
+34
+\ \ Unused type declaration.
+
+35
+\ \ Unused for-loop index.
+
+36
+\ \ Unused ancestor variable.
+
+37
+\ \ Unused constructor.
+
+38
+\ \ Unused extension constructor.
+
+39
+\ \ Unused rec flag.
+
+40
+\ \ Constructor or label name used out of scope.
+
+41
+\ \ Ambiguous constructor or label name.
+
+42
+\ \ Disambiguated constructor or label name.
+
+43
+\ \ Nonoptional label applied as optional.
+
+44
+\ \ Open statement shadows an already defined identifier.
+
+45
+\ \ Open statement shadows an already defined label or constructor.
+
+46
+\ \ Error in environment variable.
+
+47
+\ \ Illegal attribute payload.
+
+48
+\ \ Implicit elimination of optional arguments.
+
+49
+\ \ Missing cmi file when looking up module alias.
+
+50
+\ \ Unexpected documentation comment.
+
+The letters stand for the following sets of warnings. Any letter not
+mentioned here corresponds to the empty set.
+
+.B A
+\ all warnings
+
+.B C
+\ 1, 2
+
+.B D
+\ 3
+
+.B E
+\ 4
+
+.B F
+\ 5
+
+.B K
+\ 32, 33, 34, 35, 36, 37, 38, 39
+
+.B L
+\ 6
+
+.B M
+\ 7
+
+.B P
+\ 8
+
+.B R
+\ 9
+
+.B S
+\ 10
+
+.B U
+\ 11, 12
+
+.B V
+\ 13
+
+.B X
+\ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 30
+
+.B Y
+\ 26
+
+.B Z
+\ 27
+
+.IP
+The default setting is
+.BR \-w\ +a\-4\-6\-7\-9\-27\-29\-32..39\-41\-42\-44\-45\-48\-50 .
+Note that warnings
+.BR 5 \ and \ 10
+are not always triggered, depending on the internals of the type checker.
+.TP
+.BI \-warn\-error \ warning\-list
+Mark as errors the warnings specified in the argument
+.IR warning\-list .
+The compiler will stop with an error when one of these
+warnings is emitted. The
+.I warning\-list
+has the same meaning as for
+the
+.B \-w
+option: a
+.B +
+sign (or an uppercase letter) marks the corresponding warnings as fatal, a
+.B \-
+sign (or a lowercase letter) turns them back into non-fatal warnings, and a
+.B @
+sign both enables and marks as fatal the corresponding warnings.
+
+Note: it is not recommended to use the
+.B \-warn\-error
+option in production code, because it will almost certainly prevent
+compiling your program with later versions of OCaml when they add new
+warnings or modify existing warnings.
+
+The default setting is
+.B \-warn\-error \-a
+(all warnings are non-fatal).
+.TP
+.B \-warn\-help
+Show the description of all available warning numbers.
+.TP
+.B \-where
+Print the location of the standard library, then exit.
+.TP
+.BI \- \ file
+Process
+.I file
+as a file name, even if it starts with a dash (-) character.
+.TP
+.BR \-help \ or \ \-\-help
+Display a short usage summary and exit.
+
+.SH SEE ALSO
+.BR ocamlopt (1), \ ocamlrun (1), \ ocaml (1).
+.br
+.IR "The OCaml user's manual" ,
+chapter "Batch compilation".
diff --git a/man/ocamlcp.m b/man/ocamlcp.m
new file mode 100644
index 0000000000..7967f25d21
--- /dev/null
+++ b/man/ocamlcp.m
@@ -0,0 +1,139 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH "OCAMLCP" 1
+
+.SH NAME
+ocamlcp, ocamloptp \- The OCaml profiling compilers
+
+.SH SYNOPSIS
+.B ocamlcp
+[
+.I ocamlc options
+]
+[
+.BI \-P \ flags
+]
+.I filename ...
+
+.B ocamloptp
+[
+.I ocamlopt options
+]
+[
+.BI \-P \ flags
+]
+.I filename ...
+
+.SH DESCRIPTION
+The
+.B ocamlcp
+and
+.B ocamloptp
+commands are front-ends to
+.BR ocamlc (1)
+and
+.BR ocamlopt (1)
+that instrument the source code, adding code to record how many times
+functions are called, branches of conditionals are taken, etc.
+Execution of instrumented code produces an execution profile in the
+file ocamlprof.dump, which can be read using
+.BR ocamlprof (1).
+
+.B ocamlcp
+accepts the same arguments and options as
+.BR ocamlc (1)
+and
+.B ocamloptp
+accepts the same arguments and options as
+.BR ocamlopt (1).
+There is only one exception: in both cases, the
+.B \-pp
+option is not supported. If you need to preprocess your source files,
+you will have to do it separately before calling
+.B ocamlcp
+or
+.BR ocamloptp .
+
+.SH OPTIONS
+
+In addition to the
+.BR ocamlc (1)
+or
+.BR ocamlopt (1)
+options,
+.B ocamlcp
+and
+.B ocamloptp
+accept one option to control the kind of profiling information, the
+.BI \-P \ letters
+option. The
+.I letters
+indicate which parts of the program should be profiled:
+.TP
+.B a
+all options
+.TP
+.B f
+function calls : a count point is set at the beginning of each function body
+.TP
+.B i
+.BR if \ ... \ then \ ... \ else :
+count points are set in both
+.BR then \ and \ else
+branches
+.TP
+.B l
+.BR while , \ for
+loops: a count point is set at the beginning of the loop body
+.TP
+.B m
+.B match
+branches: a count point is set at the beginning of the
+body of each branch of a pattern-matching
+.TP
+.B t
+.BR try \ ... \ with
+branches: a count point is set at the beginning of the body of each
+branch of an exception catcher
+
+.PP
+For instance, compiling with
+.B ocamlcp \-P film
+profiles function calls,
+.BR if \ ... \ then \ ... \ else \ ...,
+loops, and pattern matching.
+
+Calling
+.BR ocamlcp (1)
+or
+.BR ocamloptp (1)
+without the
+.B \-P
+option defaults to
+.BR \-P\ fm ,
+meaning that only function calls and pattern matching are profiled.
+
+Note: for compatibility with previous versions,
+.BR ocamlcp (1)
+also accepts the option
+.B \-p
+with the same argument and meaning as
+.BR \-P .
+
+.SH SEE ALSO
+.BR ocamlc (1),
+.BR ocamlopt (1),
+.BR ocamlprof (1).
+.br
+.IR "The OCaml user's manual" ,
+chapter "Profiling".
diff --git a/man/ocamldebug.m b/man/ocamldebug.m
new file mode 100644
index 0000000000..50354d93c5
--- /dev/null
+++ b/man/ocamldebug.m
@@ -0,0 +1,105 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 2001 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLDEBUG 1
+
+.SH NAME
+ocamldebug \- the OCaml source-level replay debugger.
+.SH SYNOPSIS
+.B ocamldebug
+.RI [\ options \ ]\ program \ [\ arguments \ ]
+.SH DESCRIPTION
+.B ocamldebug
+is the OCaml source-level replay debugger.
+
+Before the debugger can be used, the program must be compiled and
+linked with the
+.B \-g
+option: all .cmo and .cma files that are part
+of the program should have been created with
+.BR ocamlc\ \-g ,
+and they must be linked together with
+.BR ocamlc\ \-g .
+
+Compiling with
+.B \-g
+entails no penalty on the running time of
+programs: object files and bytecode executable files are bigger and
+take longer to produce, but the executable files run at
+exactly the same speed as if they had been compiled without
+.BR \-g .
+
+.SH OPTIONS
+A summary of options are included below.
+For a complete description, see the html documentation in the ocaml-doc
+package.
+.TP
+.BI \-c \ count
+Set the maximum number of simultaneously live checkpoints to
+.IR count .
+.TP
+.BI \-cd \ dir
+Run the debugger program from the working directory
+.IR dir ,
+instead of the current working directory. (See also the
+.B cd
+command.)
+.TP
+.B \-emacs
+Tell the debugger it is executed under Emacs. (See
+.I "The OCaml user's manual"
+for information on how to run the debugger under Emacs.)
+Implies
+.BR \-machine-readable .
+.TP
+.BI \-I \ directory
+Add
+.I directory
+to the list of directories searched for source files and
+compiled files. (See also the
+.B directory
+command.)
+.TP
+.BI -machine-readable
+Print information in a format more suitable for machines instead of human
+operators where applicable. For example, when describing a location in a
+program, such as when printing a backtrace, print the program counter and
+character offset in a file instead of the filename, line number, and character
+offset in that line.
+.TP
+.BI \-s \ socket
+Use
+.I socket
+for communicating with the debugged program. See the description
+of the command
+.B set\ socket
+in
+.I "The OCaml user's manual"
+for the format of
+.IR socket .
+.TP
+.B \-version
+Print version string and exit.
+.TP
+.B \-vnum
+Print short version number and exit.
+.TP
+.BR \-help \ or \ \-\-help
+Display a short usage summary and exit.
+.SH SEE ALSO
+.BR ocamlc (1)
+.br
+.IR "The OCaml user's manual" ,
+chapter "The debugger".
+.SH AUTHOR
+This manual page was written by Sven LUTHER <luther@debian.org>,
+for the Debian GNU/Linux system (but may be used by others).
diff --git a/man/ocamldep.m b/man/ocamldep.m
new file mode 100644
index 0000000000..ba7ddb8c3c
--- /dev/null
+++ b/man/ocamldep.m
@@ -0,0 +1,138 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLDEP 1
+
+.SH NAME
+ocamldep \- Dependency generator for OCaml
+
+.SH SYNOPSIS
+.B ocamldep
+[
+.I options
+]
+.I filename ...
+
+.SH DESCRIPTION
+
+The
+.BR ocamldep (1)
+command scans a set of OCaml source files
+(.ml and .mli files) for references to external compilation units,
+and outputs dependency lines in a format suitable for the
+.BR make (1)
+utility. This ensures that make will compile the source files in the
+correct order, and recompile those files that need to when a source
+file is modified.
+
+The typical usage is:
+.P
+ocamldep
+.I options
+*.mli *.ml > .depend
+.P
+where .depend is the file that should contain the
+dependencies.
+
+Dependencies are generated both for compiling with the bytecode
+compiler
+.BR ocamlc (1)
+and with the native-code compiler
+.BR ocamlopt (1).
+
+.SH OPTIONS
+
+The following command-line options are recognized by
+.BR ocamldep (1).
+.TP
+.B \-absname
+Show absolute filenames in error messages.
+.TP
+.BI \-I \ directory
+Add the given directory to the list of directories searched for
+source files. If a source file foo.ml mentions an external
+compilation unit Bar, a dependency on that unit's interface
+bar.cmi is generated only if the source for bar is found in the
+current directory or in one of the directories specified with
+.BR \-I .
+Otherwise, Bar is assumed to be a module from the standard library,
+and no dependencies are generated. For programs that span multiple
+directories, it is recommended to pass
+.BR ocamldep (1)
+the same
+.B \-I
+options that are passed to the compiler.
+.TP
+.BI \-ml\-synonym \ .ext
+Consider the given extension (with leading dot) to be a synonym for .ml.
+.TP
+.BI \-mli\-synonym \ .ext
+Consider the given extension (with leading dot) to be a synonym for .mli.
+.TP
+.B \-modules
+Output raw dependencies of the form
+.IR filename : \ Module1\ Module2 \ ... \ ModuleN
+where
+.IR Module1 ,\ ..., \ ModuleN
+are the names of the compilation
+units referenced within the file
+.IR filename ,
+but these names are not
+resolved to source file names. Such raw dependencies cannot be used
+by
+.BR make (1),
+but can be post-processed by other tools such as
+.BR Omake (1).
+.TP
+.BI \-native
+Generate dependencies for a pure native-code program (no bytecode
+version). When an implementation file (.ml file) has no explicit
+interface file (.mli file),
+.BR ocamldep (1)
+generates dependencies on the
+bytecode compiled file (.cmo file) to reflect interface changes.
+This can cause unnecessary bytecode recompilations for programs that
+are compiled to native-code only. The flag
+.B \-native
+causes dependencies on native compiled files (.cmx) to be generated instead
+of on .cmo files. (This flag makes no difference if all source files
+have explicit .mli interface files.)
+.TP
+.BI \-pp \ command
+Cause
+.BR ocamldep (1)
+to call the given
+.I command
+as a preprocessor for each source file.
+.TP
+.BI \-ppx \ command
+Pipe abstract syntax tree through preprocessor
+.IR command .
+.TP
+.B \-slash
+Under Unix, this option does nothing.
+.TP
+.B \-version
+Print version string and exit.
+.TP
+.B \-vnum
+Print short version number and exit.
+.TP
+.BR \-help \ or \ \-\-help
+Display a short usage summary and exit.
+
+.SH SEE ALSO
+.BR ocamlc (1),
+.BR ocamlopt (1).
+.br
+.IR The\ OCaml\ user's\ manual ,
+chapter "Dependency generator".
diff --git a/man/ocamldoc.m b/man/ocamldoc.m
new file mode 100644
index 0000000000..ca0a233480
--- /dev/null
+++ b/man/ocamldoc.m
@@ -0,0 +1,459 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 2004 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLDOC 1
+
+\" .de Sh \" Subsection heading
+\" .br
+\" .if t .Sp
+\" .ne 5
+\" .PP
+\" \fB\\$1\fR
+\" .PP
+\" ..
+
+.SH NAME
+ocamldoc \- The OCaml documentation generator
+
+
+.SH SYNOPSIS
+.B ocamldoc
+[
+.I options
+]
+.IR filename \ ...
+
+.SH DESCRIPTION
+
+The OCaml documentation generator
+.BR ocamldoc (1)
+generates documentation from special comments embedded in source files. The
+comments used by
+.B ocamldoc
+are of the form
+.I (** ... *)
+and follow the format described in the
+.IR "The OCaml user's manual" .
+
+.B ocamldoc
+can produce documentation in various formats: HTML, LaTeX, TeXinfo,
+Unix man pages, and
+.BR dot (1)
+dependency graphs. Moreover, users can add their own
+custom generators.
+
+In this manpage, we use the word
+.I element
+to refer to any of the following parts of an OCaml source file: a type
+declaration, a value, a module, an exception, a module type, a type
+constructor, a record field, a class, a class type, a class method, a class
+value or a class inheritance clause.
+
+.SH OPTIONS
+
+The following command-line options determine the format for the generated
+documentation generated by
+.BR ocamldoc (1).
+.SS "Options for choosing the output format"
+.TP
+.B \-html
+Generate documentation in HTML default format. The generated HTML pages are
+stored in the current directory, or in the directory specified with the
+.B \-d
+option. You can customize the style of the generated pages by editing the
+generated
+.I style.css
+file, or by providing your own style sheet using option
+.BR \-css\-style .
+The file
+.I style.css
+is not generated if it already exists.
+.TP
+.B \-latex
+Generate documentation in LaTeX default format. The generated LaTeX document
+is saved in file
+.IR ocamldoc.out ,
+or in the file specified with the
+.B -o
+option. The document uses the style file
+.IR ocamldoc.sty .
+This file is generated when using the
+.B \-latex
+option, if it does not already exist. You can change this file to customize
+the style of your LaTeX documentation.
+.TP
+.B \-texi
+Generate documentation in TeXinfo default format. The generated LaTeX document
+is saved in file
+.IR ocamldoc.out ,
+or in the file specified with the
+.B -o
+option.
+.TP
+.B \-man
+Generate documentation as a set of Unix man pages. The generated pages are
+stored in the current directory, or in the directory specified with the
+.B \-d
+option.
+.TP
+.B \-dot
+Generate a dependency graph for the toplevel modules, in a format suitable for
+displaying and processing by
+.IR dot (1).
+The
+.IR dot (1)
+tool is available from
+.IR http://www.research.att.com/sw/tools/graphviz/ .
+The textual representation of the graph is written to the file
+.IR ocamldoc.out ,
+or to the file specified with the
+.B -o
+option. Use
+.BI dot \ ocamldoc.out
+to display it.
+.TP
+.BI \-g \ file
+Dynamically load the given file (which extension usually is .cmo or .cma),
+which defines a custom documentation generator.
+If the given file is a simple one and does not exist in
+the current directory, then
+.B ocamldoc
+looks for it in the custom
+generators default directory, and in the directories specified with the
+.B \-i
+option.
+.TP
+.BI \-customdir
+Display the custom generators default directory.
+.TP
+.BI \-i \ directory
+Add the given directory to the path where to look for custom generators.
+.SS "General options"
+.TP
+.BI \-d \ dir
+Generate files in directory
+.IR dir ,
+rather than the current directory.
+.TP
+.BI \-dump \ file
+Dump collected information into
+.IR file .
+This information can be read with the
+.B \-load
+option in a subsequent invocation of
+.BR ocamldoc (1).
+.TP
+.BI \-hide \ modules
+Hide the given complete module names in the generated documentation.
+.I modules
+is a list of complete module names are separated by commas (,),
+without blanks. For instance:
+.IR Pervasives,M2.M3 .
+.TP
+.B \-inv\-merge\-ml\-mli
+Reverse the precedence of implementations and interfaces when merging.
+All elements in implementation files are kept, and the
+.B \-m
+option indicates which parts of the comments in interface files are merged with
+the comments in implementation files.
+.TP
+.B \-keep\-code
+Always keep the source code for values, methods and instance variables, when
+available. The source code is always kept when a .ml
+file is given, but is by default discarded when a .mli
+is given. This option allows the source code to be always kept.
+.TP
+.BI \-load \ file
+Load information from
+.IR file ,
+which has been produced by
+.BR ocamldoc\ \-dump .
+Several
+.B -load
+options can be given.
+.TP
+.BI \-m \ flags
+Specify merge options between interfaces and implementations.
+.I flags
+can be one or several of the following characters:
+
+.B d
+merge description
+
+.B a
+merge @author
+
+.B v
+merge @version
+
+.B l
+merge @see
+
+.B s
+merge @since
+
+.B o
+merge @deprecated
+
+.B p
+merge @param
+
+.B e
+merge @raise
+
+.B r
+merge @return
+
+.B A
+merge everything
+.TP
+.B \-no\-custom\-tags
+Do not allow custom @-tags.
+.TP
+.B \-no\-stop
+Keep elements placed after the
+.B (**/**)
+special comment.
+.TP
+.BI \-o \ file
+Output the generated documentation to
+.I file
+instead of
+.IR ocamldoc.out .
+This option is meaningful only in conjunction with the
+.BR \-latex , \ \-texi ,\ or \ \-dot
+options.
+.TP
+.BI \-pp \ command
+Pipe sources through preprocessor
+.IR command .
+.TP
+.BI \-ppx \ command
+Pipe abstract syntax tree through preprocessor
+.IR command .
+.TP
+.B \-sort
+Sort the list of top-level modules before generating the documentation.
+.TP
+.B \-stars
+Remove blank characters until the first asterisk ('*') in each line of comments.
+.TP
+.BI \-t \ title
+Use
+.I title
+as the title for the generated documentation.
+.TP
+.BI \-intro \ file
+Use content of
+.I file
+as
+.B ocamldoc
+text to use as introduction (HTML, LaTeX and TeXinfo only).
+For HTML, the file is used to create the whole "index.html" file.
+.TP
+.B \-v
+Verbose mode. Display progress information.
+.TP
+.B \-version
+Print version string and exit.
+.TP
+.B \-vnum
+Print short version number and exit.
+.TP
+.B \-warn\-error
+Treat
+.B ocamldoc
+warnings as errors.
+.TP
+.B \-hide\-warnings
+Do not print
+.B ocamldoc
+warnings.
+.TP
+.BR \-help \ or \ \-\-help
+Display a short usage summary and exit.
+.SS "Type-checking options"
+.BR ocamldoc (1)
+calls the OCaml type-checker to obtain type information. The
+following options impact the type-checking phase. They have the same meaning
+as for the
+.BR ocamlc (1)\ and \ ocamlopt (1)
+commands.
+.TP
+.BI \-I \ directory
+Add
+.I directory
+to the list of directories search for compiled interface files (.cmi files).
+.TP
+.B \-nolabels
+Ignore non-optional labels in types.
+.TP
+.B \-rectypes
+ Allow arbitrary recursive types. (See the
+.B \-rectypes
+option to
+.BR ocamlc (1).)
+.SS "Options for generating HTML pages"
+The following options apply in conjunction with the
+.B \-html
+option:
+.TP
+.B \-all\-params
+Display the complete list of parameters for functions and methods.
+.TP
+.BI \-css\-style \ filename
+Use
+.I filename
+as the Cascading Style Sheet file.
+.TP
+.B \-colorize\-code
+Colorize the OCaml code enclosed in [ ] and \\{[ ]\\}, using colors to emphasize
+keywords, etc. If the code fragments are not syntactically correct, no color
+is added.
+.TP
+.B \-index\-only
+Generate only index files.
+.TP
+.B \-short\-functors
+Use a short form to display functors:
+.B "module M : functor (A:Module) -> functor (B:Module2) -> sig .. end"
+is displayed as
+.BR "module M (A:Module) (B:Module2) : sig .. end" .
+.SS "Options for generating LaTeX files"
+The following options apply in conjunction with the
+.B \-latex
+option:
+.TP
+.B \-latex\-value\-prefix prefix
+Give a prefix to use for the labels of the values in the generated LaTeX
+document. The default prefix is the empty string. You can also use the options
+.BR -latex-type-prefix ,
+.BR -latex-exception-prefix ,
+.BR -latex-module-prefix ,
+.BR -latex-module-type-prefix ,
+.BR -latex-class-prefix ,
+.BR -latex-class-type-prefix ,
+.BR -latex-attribute-prefix ,\ and
+.BR -latex-method-prefix .
+
+These options are useful when you have, for example, a type and a value
+with the same name. If you do not specify prefixes, LaTeX will complain about
+multiply defined labels.
+.TP
+.BI \-latextitle \ n,style
+Associate style number
+.I n
+to the given LaTeX sectioning command
+.IR style ,
+e.g.
+.BR section or subsection .
+(LaTeX only.) This is useful when including the generated document in another
+LaTeX document, at a given sectioning level. The default association is 1 for
+section, 2 for subsection, 3 for subsubsection, 4 for paragraph and 5 for
+subparagraph.
+.TP
+.B \-noheader
+Suppress header in generated documentation.
+.TP
+.B \-notoc
+Do not generate a table of contents.
+.TP
+.B \-notrailer
+Suppress trailer in generated documentation.
+.TP
+.B \-sepfiles
+Generate one .tex file per toplevel module, instead of the global
+.I ocamldoc.out
+file.
+.SS "Options for generating TeXinfo files"
+The following options apply in conjunction with the
+.B -texi
+option:
+.TP
+.B \-esc8
+Escape accented characters in Info files.
+.TP
+.B
+\-info\-entry
+Specify Info directory entry.
+.TP
+.B \-info\-section
+Specify section of Info directory.
+.TP
+.B \-noheader
+Suppress header in generated documentation.
+.TP
+.B \-noindex
+Do not build index for Info files.
+.TP
+.B \-notrailer
+Suppress trailer in generated documentation.
+.SS "Options for generating dot graphs"
+The following options apply in conjunction with the
+.B \-dot
+option:
+.TP
+.BI \-dot\-colors \ colors
+Specify the colors to use in the generated dot code. When generating module
+dependencies,
+.BR ocamldoc (1)
+uses different colors for modules, depending on the directories in which they
+reside. When generating types dependencies,
+.BR ocamldoc (1)
+uses different colors for types, depending on the modules in which they are
+defined.
+.I colors
+is a list of color names separated by commas (,), as in
+.BR Red,Blue,Green .
+The available colors are the ones supported by the
+.BR dot (1)
+tool.
+.TP
+.B \-dot\-include\-all
+Include all modules in the
+.BR dot (1)
+output, not only modules given on the command line or loaded with the
+.B \-load
+option.
+.TP
+.B \-dot\-reduce
+Perform a transitive reduction of the dependency graph before outputting the
+dot code. This can be useful if there are a lot of transitive dependencies
+that clutter the graph.
+.TP
+.B \-dot\-types
+Output dot code describing the type dependency graph instead of the module
+dependency graph.
+.SS "Options for generating man files"
+The following options apply in conjunction with the
+.B \-man
+option:
+.TP
+.B \-man\-mini
+Generate man pages only for modules, module types, classes and class types,
+instead of pages for all elements.
+.TP
+.BI \-man\-suffix \ suffix
+Set the suffix used for generated man filenames. Default is o, as in
+.IR List.o .
+.TP
+.BI \-man\-section \ section
+Set the section number used for generated man filenames. Default is 3.
+
+
+.SH SEE ALSO
+.BR ocaml (1),
+.BR ocamlc (1),
+.BR ocamlopt (1).
+.br
+.IR "The OCaml user's manual",
+chapter "The documentation generator".
diff --git a/man/ocamllex.m b/man/ocamllex.m
new file mode 100644
index 0000000000..d59755bab1
--- /dev/null
+++ b/man/ocamllex.m
@@ -0,0 +1,98 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLLEX 1
+
+.SH NAME
+ocamllex \- The OCaml lexer generator
+
+.SH SYNOPSIS
+.B ocamllex
+[
+.BI \-o \ output-file
+]
+[
+.B \-ml
+]
+.I filename.mll
+
+.SH DESCRIPTION
+
+The
+.BR ocamllex (1)
+command generates OCaml lexers from a set of regular
+expressions with associated semantic actions, in the style of
+.BR lex (1).
+
+Running
+.BR ocamllex (1)
+on the input file
+.IR lexer \&.mll
+produces OCaml code for a lexical analyzer in file
+.IR lexer \&.ml.
+
+This file defines one lexing function per entry point in the lexer
+definition. These functions have the same names as the entry
+points. Lexing functions take as argument a lexer buffer, and return
+the semantic attribute of the corresponding entry point.
+
+Lexer buffers are an abstract data type implemented in the standard
+library module Lexing. The functions Lexing.from_channel,
+Lexing.from_string and Lexing.from_function create
+lexer buffers that read from an input channel, a character string, or
+any reading function, respectively.
+
+When used in conjunction with a parser generated by
+.BR ocamlyacc (1),
+the semantic actions compute a value belonging to the type token defined
+by the generated parsing module.
+
+.SH OPTIONS
+
+The
+.BR ocamllex (1)
+command recognizes the following options:
+.TP
+.B \-ml
+Output code that does not use OCaml's built-in automata
+interpreter. Instead, the automaton is encoded by OCaml functions.
+This option is mainly useful for debugging
+.BR ocamllex (1),
+using it for production lexers is not recommended.
+.TP
+.BI \-o \ output\-file
+Specify the name of the output file produced by
+.BR ocamllex (1).
+The default is the input file name, with its extension replaced by .ml.
+.TP
+.B \-q
+Quiet mode.
+.BR ocamllex (1)
+normally outputs informational messages
+to standard output. They are suppressed if option
+.B \-q
+is used.
+.TP
+.BR \-v \ or \ \-version
+Print version string and exit.
+.TP
+.B \-vnum
+Print short version number and exit.
+.TP
+.BR \-help \ or \ \-\-help
+Display a short usage summary and exit.
+
+.SH SEE ALSO
+.BR ocamlyacc (1).
+.br
+.IR "The OCaml user's manual" ,
+chapter "Lexer and parser generators".
diff --git a/man/ocamlmktop.m b/man/ocamlmktop.m
new file mode 100644
index 0000000000..fd6aaa8231
--- /dev/null
+++ b/man/ocamlmktop.m
@@ -0,0 +1,94 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1999 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLMKTOP 1
+
+.SH NAME
+ocamlmktop \- Building custom toplevel systems
+
+.SH SYNOPSIS
+.B ocamlmktop
+[
+.BR \-v | \-version | \-vnum
+]
+[
+.BI \-cclib \ libname
+]
+[
+.BI \-ccopt \ option
+]
+[
+.B \-custom
+[
+.BI \-o \ exec-file
+]
+[
+.BI \-I \ lib-dir
+]
+.I filename ...
+
+.SH DESCRIPTION
+
+The
+.BR ocamlmktop (1)
+command builds OCaml toplevels that
+contain user code preloaded at start-up.
+The
+.BR ocamlmktop (1)
+command takes as argument a set of
+.IR x .cmo
+and
+.IR x .cma
+files, and links them with the object files that implement the
+OCaml toplevel. If the
+.B \-custom
+flag is given, C object files and libraries (.o and .a files) can also
+be given on the command line and are linked in the resulting toplevel.
+
+.SH OPTIONS
+
+The following command-line options are recognized by
+.BR ocamlmktop (1).
+.TP
+.B \-v
+Print the version string of the compiler and exit.
+.TP
+.BR \-vnum \ or\ \-version
+Print the version number of the compiler in short form and exit.
+.TP
+.BI \-cclib\ \-l libname
+Pass the
+.BI \-l libname
+option to the C linker when linking in
+``custom runtime'' mode (see the corresponding option for
+.BR ocamlc (1).
+.TP
+.B \-ccopt
+Pass the given option to the C compiler and linker, when linking in
+``custom runtime'' mode. See the corresponding option for
+.BR ocamlc (1).
+.TP
+.B \-custom
+Link in ``custom runtime'' mode. See the corresponding option for
+.BR ocamlc (1).
+.TP
+.BI \-I \ directory
+Add the given directory to the list of directories searched for
+compiled interface files (.cmo and .cma).
+.TP
+.BI \-o \ exec\-file
+Specify the name of the toplevel file produced by the linker.
+The default is is
+.BR a.out .
+
+.SH SEE ALSO
+.BR ocamlc (1).
diff --git a/man/ocamlopt.m b/man/ocamlopt.m
new file mode 100644
index 0000000000..a541e598d4
--- /dev/null
+++ b/man/ocamlopt.m
@@ -0,0 +1,707 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLOPT 1
+
+.SH NAME
+
+ocamlopt \- The OCaml native-code compiler
+
+.SH SYNOPSIS
+
+.B ocamlopt
+[
+.I options
+]
+.IR filename \ ...
+
+.B ocamlopt.opt
+(same options)
+
+.SH DESCRIPTION
+
+The OCaml high-performance
+native-code compiler
+.BR ocamlopt (1)
+compiles OCaml source files to native code object files and link these
+object files to produce standalone executables.
+
+The
+.BR ocamlopt (1)
+command has a command-line interface very close to that
+of
+.BR ocamlc (1).
+It accepts the same types of arguments and processes them
+sequentially:
+
+Arguments ending in .mli are taken to be source files for
+compilation unit interfaces. Interfaces specify the names exported by
+compilation units: they declare value names with their types, define
+public data types, declare abstract data types, and so on. From the
+file
+.IR x .mli,
+the
+.BR ocamlopt (1)
+compiler produces a compiled interface
+in the file
+.IR x .cmi.
+The interface produced is identical to that
+produced by the bytecode compiler
+.BR ocamlc (1).
+
+Arguments ending in .ml are taken to be source files for compilation
+unit implementations. Implementations provide definitions for the
+names exported by the unit, and also contain expressions to be
+evaluated for their side-effects. From the file
+.IR x .ml,
+the
+.BR ocamlopt (1)
+compiler produces two files:
+.IR x .o,
+containing native object code, and
+.IR x .cmx,
+containing extra information for linking and
+optimization of the clients of the unit. The compiled implementation
+should always be referred to under the name
+.IR x .cmx
+(when given a .o file,
+.BR ocamlopt (1)
+assumes that it contains code compiled from C, not from OCaml).
+
+The implementation is checked against the interface file
+.IR x .mli
+(if it exists) as described in the manual for
+.BR ocamlc (1).
+
+Arguments ending in .cmx are taken to be compiled object code. These
+files are linked together, along with the object files obtained
+by compiling .ml arguments (if any), and the OCaml standard
+library, to produce a native-code executable program. The order in
+which .cmx and .ml arguments are presented on the command line is
+relevant: compilation units are initialized in that order at
+run-time, and it is a link-time error to use a component of a unit
+before having initialized it. Hence, a given
+.IR x .cmx
+file must come
+before all .cmx files that refer to the unit
+.IR x .
+
+Arguments ending in .cmxa are taken to be libraries of object code.
+Such a library packs in two files
+.IR lib .cmxa
+and
+.IR lib .a
+a set of object files (.cmx/.o files). Libraries are build with
+.B ocamlopt \-a
+(see the description of the
+.B \-a
+option below). The object
+files contained in the library are linked as regular .cmx files (see
+above), in the order specified when the library was built. The only
+difference is that if an object file contained in a library is not
+referenced anywhere in the program, then it is not linked in.
+
+Arguments ending in .c are passed to the C compiler, which generates
+a .o object file. This object file is linked with the program.
+
+Arguments ending in .o or .a are assumed to be C object files and
+libraries. They are linked with the program.
+
+The output of the linking phase is a regular Unix executable file. It
+does not need
+.BR ocamlrun (1)
+to run.
+
+.B ocamlopt.opt
+is the same compiler as
+.BR ocamlopt ,
+but compiled with itself instead of with the bytecode compiler
+.BR ocamlc (1).
+Thus, it behaves exactly like
+.BR ocamlopt ,
+but compiles faster.
+.B ocamlopt.opt
+is not available in all installations of OCaml.
+
+.SH OPTIONS
+
+The following command-line options are recognized by
+.BR ocamlopt (1).
+.TP
+.B \-a
+Build a library (.cmxa/.a file) with the object files (.cmx/.o
+files) given on the command line, instead of linking them into an
+executable file. The name of the library must be set with the
+.B \-o
+option.
+
+If
+.BR \-cclib \ or \ \-ccopt
+options are passed on the command
+line, these options are stored in the resulting .cmxa library. Then,
+linking with this library automatically adds back the
+.BR \-cclib \ and \ \-ccopt
+options as if they had been provided on the
+command line, unless the
+.B \-noautolink
+option is given. Additionally, a substring
+.B $CAMLORIGIN
+inside a
+.BR \ \-ccopt
+options will be replaced by the full path to the .cma library,
+excluding the filename.
+.TP
+.B \-absname
+Show absolute filenames in error messages.
+.TP
+.B \-annot
+Dump detailed information about the compilation (types, bindings,
+tail-calls, etc). The information for file
+.IR src .ml
+is put into file
+.IR src .annot.
+In case of a type error, dump all the information inferred by the
+type-checker before the error. The
+.IR src .annot
+file can be used with the emacs commands given in
+.B emacs/caml\-types.el
+to display types and other annotations interactively.
+.TP
+.B \-bin\-annot
+Dump detailed information about the compilation (types, bindings,
+tail-calls, etc) in binary format. The information for file
+.IR src .ml
+is put into file
+.IR src .cmt.
+In case of a type error, dump
+all the information inferred by the type-checker before the error.
+The annotation files produced by
+.B \-bin\-annot
+contain more information
+and are much more compact than the files produced by
+.BR \-annot .
+.TP
+.B \-c
+Compile only. Suppress the linking phase of the
+compilation. Source code files are turned into compiled files, but no
+executable file is produced. This option is useful to
+compile modules separately.
+.TP
+.BI \-cc \ ccomp
+Use
+.I ccomp
+as the C linker called to build the final executable and as the C
+compiler for compiling .c source files.
+.TP
+.BI \-cclib\ \-l libname
+Pass the
+.BI \-l libname
+option to the linker. This causes the given C library to be linked
+with the program.
+.TP
+.BI \-ccopt \ option
+Pass the given option to the C compiler and linker. For instance,
+.BI \-ccopt\ \-L dir
+causes the C linker to search for C libraries in
+directory
+.IR dir .
+.TP
+.B \-compact
+Optimize the produced code for space rather than for time. This
+results in smaller but slightly slower programs. The default is to
+optimize for speed.
+.TP
+.B \-config
+Print the version number of
+.BR ocamlopt (1)
+and a detailed summary of its configuration, then exit.
+.TP
+.BI \-for\-pack \ module\-path
+Generate an object file (.cmx and .o files) that can later be included
+as a sub-module (with the given access path) of a compilation unit
+constructed with
+.BR \-pack .
+For instance,
+.B ocamlopt\ \-for\-pack\ P\ \-c\ A.ml
+will generate a.cmx and a.o files that can later be used with
+.BR "ocamlopt -pack -o P.cmx a.cmx" .
+.TP
+.B \-g
+Add debugging information while compiling and linking. This option is
+required in order to produce stack backtraces when
+the program terminates on an uncaught exception (see
+.BR ocamlrun (1)).
+.TP
+.B \-i
+Cause the compiler to print all defined names (with their inferred
+types or their definitions) when compiling an implementation (.ml
+file). No compiled files (.cmo and .cmi files) are produced.
+This can be useful to check the types inferred by the
+compiler. Also, since the output follows the syntax of interfaces, it
+can help in writing an explicit interface (.mli file) for a file:
+just redirect the standard output of the compiler to a .mli file,
+and edit that file to remove all declarations of unexported names.
+.TP
+.BI \-I \ directory
+Add the given directory to the list of directories searched for
+compiled interface files (.cmi), compiled object code files (.cmx),
+and libraries (.cmxa). By default, the current directory is searched
+first, then the standard library directory. Directories added with \-I
+are searched after the current directory, in the order in which they
+were given on the command line, but before the standard library
+directory. See also option
+.BR \-nostdlib .
+
+If the given directory starts with
+.BR + ,
+it is taken relative to the
+standard library directory. For instance,
+.B \-I\ +compiler-libs
+adds the subdirectory
+.B compiler-libs
+of the standard library to the search path.
+.TP
+.BI \-impl \ filename
+Compile the file
+.I filename
+as an implementation file, even if its extension is not .ml.
+.TP
+.BI \-inline \ n
+Set aggressiveness of inlining to
+.IR n ,
+where
+.I n
+is a positive
+integer. Specifying
+.B \-inline 0
+prevents all functions from being
+inlined, except those whose body is smaller than the call site. Thus,
+inlining causes no expansion in code size. The default aggressiveness,
+.BR \-inline\ 1 ,
+allows slightly larger functions to be inlined, resulting
+in a slight expansion in code size. Higher values for the
+.B \-inline
+option cause larger and larger functions to become candidate for
+inlining, but can result in a serious increase in code size.
+.TP
+.BI \-intf \ filename
+Compile the file
+.I filename
+as an interface file, even if its extension is not .mli.
+.TP
+.BI \-intf\-suffix \ string
+Recognize file names ending with
+.I string
+as interface files (instead of the default .mli).
+.TP
+.B \-keep-locs
+Keep documentation strings in generated .cmi files.
+.TP
+.B \-keep-locs
+Keep locations in generated .cmi files.
+.TP
+.B \-labels
+Labels are not ignored in types, labels may be used in applications,
+and labelled parameters can be given in any order. This is the default.
+.TP
+.B \-linkall
+Force all modules contained in libraries to be linked in. If this
+flag is not given, unreferenced modules are not linked in. When
+building a library
+.RB ( \-a
+flag), setting the
+.B \-linkall
+flag forces all
+subsequent links of programs involving that library to link all the
+modules contained in the library.
+.TP
+.B \-no-alias-deps
+Do not record dependencies for module aliases.
+.TP
+.B \-no\-app\-funct
+Deactivates the applicative behaviour of functors. With this option,
+each functor application generates new types in its result and
+applying the same functor twice to the same argument yields two
+incompatible structures.
+.TP
+.B \-noassert
+Do not compile assertion checks. Note that the special form
+.B assert\ false
+is always compiled because it is typed specially.
+This flag has no effect when linking already-compiled files.
+.TP
+.B \-noautolink
+When linking .cmxa libraries, ignore
+.BR \-cclib \ and \ \-ccopt
+options potentially contained in the libraries (if these options were
+given when building the libraries). This can be useful if a library
+contains incorrect specifications of C libraries or C options; in this
+case, during linking, set
+.B -noautolink
+and pass the correct C libraries and options on the command line.
+.TP
+.B \-nodynlink
+Allow the compiler to use some optimizations that are valid only for code
+that is never dynlinked.
+.TP
+.B -nostdlib
+Do not automatically add the standard library directory the list of
+directories searched for compiled interface files (.cmi), compiled
+object code files (.cmx), and libraries (.cmxa). See also option
+.BR \-I .
+.TP
+.B \-nolabels
+Ignore non-optional labels in types. Labels cannot be used in
+applications, and parameter order becomes strict.
+.TP
+.BI \-o \ exec\-file
+Specify the name of the output file produced by the linker. The
+default output name is a.out, in keeping with the Unix tradition. If the
+.B \-a
+option is given, specify the name of the library produced. If the
+.B \-pack
+option is given, specify the name of the packed object file produced.
+If the
+.B \-output\-obj
+option is given, specify the name of the output file produced. If the
+.B \-shared
+option is given, specify the name of plugin file produced.
+This can also be used when compiling an interface or implementation
+file, without linking, in which case it sets the name of the cmi or
+cmo file, and also sets the module name to the file name up to the
+first dot.
+.TP
+.BI \-open \ module
+Opens the given module before processing the interface or
+implementation files. If several
+.B \-open
+options are given, they are processed in order, just as if
+the statements open! module1;; ... open! moduleN;; were added
+at the top of each file.
+.TP
+.B \-output\-obj
+Cause the linker to produce a C object file instead of an executable
+file. This is useful to wrap OCaml code as a C library,
+callable from any C program. The name of the output object file
+must be set with the
+.B \-o
+option.
+This option can also be used to produce a compiled shared/dynamic
+library (.so extension).
+.TP
+.B \-p
+Generate extra code to write profile information when the program is
+executed. The profile information can then be examined with the
+analysis program
+.BR gprof (1).
+The
+.B \-p
+option must be given both at
+compile-time and at link-time. Linking object files not compiled with
+.B \-p
+is possible, but results in less precise profiling.
+
+See the
+.BR gprof (1)
+man page for more information about the profiles.
+
+Full support for
+.BR gprof (1)
+is only available for certain platforms
+(currently: Intel x86/Linux and Alpha/Digital Unix).
+On other platforms, the
+.B \-p
+option will result in a less precise
+profile (no call graph information, only a time profile).
+.TP
+.B \-pack
+Build an object file (.cmx and .o files) and its associated compiled
+interface (.cmi) that combines the .cmx object
+files given on the command line, making them appear as sub-modules of
+the output .cmx file. The name of the output .cmx file must be
+given with the
+.B \-o
+option. For instance,
+.B ocamlopt\ -pack\ -o\ P.cmx\ A.cmx\ B.cmx\ C.cmx
+generates compiled files P.cmx, P.o and P.cmi describing a
+compilation unit having three sub-modules A, B and C,
+corresponding to the contents of the object files A.cmx, B.cmx and
+C.cmx. These contents can be referenced as P.A, P.B and P.C
+in the remainder of the program.
+
+The .cmx object files being combined must have been compiled with
+the appropriate
+.B \-for\-pack
+option. In the example above,
+A.cmx, B.cmx and C.cmx must have been compiled with
+.BR ocamlopt\ \-for\-pack\ P .
+
+Multiple levels of packing can be achieved by combining
+.B \-pack
+with
+.BR \-for\-pack .
+See
+.IR "The OCaml user's manual" ,
+chapter "Native-code compilation" for more details.
+.TP
+.BI \-pp \ command
+Cause the compiler to call the given
+.I command
+as a preprocessor for each source file. The output of
+.I command
+is redirected to
+an intermediate file, which is compiled. If there are no compilation
+errors, the intermediate file is deleted afterwards.
+.TP
+.BI \-ppx \ command
+After parsing, pipe the abstract syntax tree through the preprocessor
+.IR command .
+The module
+.BR Ast_mapper (3)
+implements the external interface of a preprocessor.
+.TP
+.B \-principal
+Check information path during type-checking, to make sure that all
+types are derived in a principal way. All programs accepted in
+.B \-principal
+mode are also accepted in default mode with equivalent
+types, but different binary signatures.
+.TP
+.B \-rectypes
+Allow arbitrary recursive types during type-checking. By default,
+only recursive types where the recursion goes through an object type
+are supported. Note that once you have created an interface using this
+flag, you must use it again for all dependencies.
+.TP
+.BI \-runtime\-variant \ suffix
+Add
+.I suffix
+to the name of the runtime library that will be used by the program.
+If OCaml was configured with option
+.BR \-with\-debug\-runtime ,
+then the
+.B d
+suffix is supported and gives a debug version of the runtime.
+.TP
+.B \-S
+Keep the assembly code produced during the compilation. The assembly
+code for the source file
+.IR x .ml
+is saved in the file
+.IR x .s.
+.TP
+.B \-safe\-string
+Enforce the separation between types
+.BR string \ and\ bytes ,
+thereby making strings read-only. This will become the default in
+a future version of OCaml.
+.TP
+.B \-shared
+Build a plugin (usually .cmxs) that can be dynamically loaded with
+the
+.B Dynlink
+module. The name of the plugin must be
+set with the
+.B \-o
+option. A plugin can include a number of OCaml
+modules and libraries, and extra native objects (.o, .a files).
+Building native plugins is only supported for some
+operating system. Under some systems (currently,
+only Linux AMD 64), all the OCaml code linked in a plugin must have
+been compiled without the
+.B \-nodynlink
+flag. Some constraints might also
+apply to the way the extra native objects have been compiled (under
+Linux AMD 64, they must contain only position-independent code).
+.TP
+.B \-short\-paths
+When a type is visible under several module-paths, use the shortest
+one when printing the type's name in inferred interfaces and error and
+warning messages.
+.TP
+.B \-strict\-sequence
+The left-hand part of a sequence must have type unit.
+.TP
+.B \-thread
+Compile or link multithreaded programs, in combination with the
+system threads library described in
+.IR "The OCaml user's manual" .
+.TP
+.B \-unsafe
+Turn bound checking off for array and string accesses (the
+.BR v.(i) and s.[i]
+constructs). Programs compiled with
+.B \-unsafe
+are therefore
+faster, but unsafe: anything can happen if the program accesses an
+array or string outside of its bounds. Additionally, turn off the
+check for zero divisor in integer division and modulus operations.
+With
+.BR \-unsafe ,
+an integer division (or modulus) by zero can halt the
+program or continue with an unspecified result instead of raising a
+.B Division_by_zero
+exception.
+.TP
+.B \-unsafe\-string
+Identify the types
+.BR string \ and\ bytes ,
+thereby making strings writable. For reasons of backward compatibility,
+this is the default setting for the moment, but this will change in a future
+version of OCaml.
+.TP
+.B \-v
+Print the version number of the compiler and the location of the
+standard library directory, then exit.
+.TP
+.B \-verbose
+Print all external commands before they are executed, in particular
+invocations of the assembler, C compiler, and linker.
+.TP
+.BR \-version \ or\ \-vnum
+Print the version number of the compiler in short form (e.g. "3.11.0"),
+then exit.
+.TP
+.BI \-w \ warning\-list
+Enable, disable, or mark as fatal the warnings specified by the argument
+.IR warning\-list .
+See
+.BR ocamlc (1)
+for the syntax of
+.IR warning-list .
+.TP
+.BI \-warn\-error \ warning\-list
+Mark as fatal the warnings specified in the argument
+.IR warning\-list .
+The compiler will stop with an error when one of these
+warnings is emitted. The
+.I warning\-list
+has the same meaning as for
+the
+.B \-w
+option: a
+.B +
+sign (or an uppercase letter) marks the corresponding warnings as fatal, a
+.B \-
+sign (or a lowercase letter) turns them back into non-fatal warnings, and a
+.B @
+sign both enables and marks as fatal the corresponding warnings.
+
+Note: it is not recommended to use the
+.B \-warn\-error
+option in production code, because it will almost certainly prevent
+compiling your program with later versions of OCaml when they add new
+warnings or modify existing warnings.
+
+The default setting is
+.B \-warn\-error \-a
+(all warnings are non-fatal).
+.TP
+.B \-warn\-help
+Show the description of all available warning numbers.
+.TP
+.B \-where
+Print the location of the standard library, then exit.
+.TP
+.BI \- \ file
+Process
+.I file
+as a file name, even if it starts with a dash (-) character.
+.TP
+.BR \-help \ or \ \-\-help
+Display a short usage summary and exit.
+
+.SH OPTIONS FOR THE IA32 ARCHITECTURE
+
+The IA32 code generator (Intel Pentium, AMD Athlon) supports the
+following additional option:
+.TP
+.B \-ffast\-math
+Use the IA32 instructions to compute
+trigonometric and exponential functions, instead of calling the
+corresponding library routines. The functions affected are:
+.BR atan ,
+.BR atan2 ,
+.BR cos ,
+.BR log ,
+.BR log10 ,
+.BR sin ,
+.B sqrt
+and
+.BR tan .
+The resulting code runs faster, but the range of supported arguments
+and the precision of the result can be reduced. In particular,
+trigonometric operations
+.BR cos ,
+.BR sin ,
+.B tan
+have their range reduced to [\-2^64, 2^64].
+
+.SH OPTIONS FOR THE AMD64 ARCHITECTURE
+
+The AMD64 code generator (64-bit versions of Intel Pentium and AMD
+Athlon) supports the following additional options:
+.TP
+.B \-fPIC
+Generate position-independent machine code. This is the default.
+.TP
+.B \-fno\-PIC
+Generate position-dependent machine code.
+
+.SH OPTIONS FOR THE SPARC ARCHITECTURE
+The Sparc code generator supports the following additional options:
+.TP
+.B \-march=v8
+Generate SPARC version 8 code.
+.TP
+.B \-march=v9
+Generate SPARC version 9 code.
+.P
+The default is to generate code for SPARC version 7, which runs on all
+SPARC processors.
+
+.SH OPTIONS FOR THE ARM ARCHITECTURE
+The ARM code generator supports the following additional options:
+.TP
+.B \-farch=armv4|armv5|armv5te|armv6|armv6t2|armv7
+Select the ARM target architecture
+.TP
+.B \-ffpu=soft|vfpv2|vfpv3\-d16|vfpv3
+Select the floating-point hardware
+.TP
+.B \-fPIC
+Generate position-independent machine code.
+.TP
+.B \-fno\-PIC
+Generate position-dependent machine code. This is the default.
+.TP
+.B \-fthumb
+Enable Thumb/Thumb-2 code generation
+.TP
+.B \-fno\-thumb
+Disable Thumb/Thumb-2 code generation
+.P
+The default values for target architecture, floating-point hardware
+and thumb usage were selected at configure-time when building
+.B ocamlopt
+itself. This configuration can be inspected using
+.BR ocamlopt\ \-config .
+Target architecture depends on the "model" setting, while
+floating-point hardware and thumb support are determined from the ABI
+setting in "system" (
+.BR linux_eabi or linux_eabihf ).
+
+.SH SEE ALSO
+.BR ocamlc (1).
+.br
+.IR "The OCaml user's manual" ,
+chapter "Native-code compilation".
diff --git a/man/ocamlprof.m b/man/ocamlprof.m
new file mode 100644
index 0000000000..a3bac2c600
--- /dev/null
+++ b/man/ocamlprof.m
@@ -0,0 +1,84 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLPROF 1
+
+.SH NAME
+ocamlprof \- The OCaml profiler
+
+.SH SYNOPSIS
+.B ocamlprof
+[
+.I options
+]
+.I filename ...
+
+.SH DESCRIPTION
+The
+.B ocamlprof
+command prints execution counts gathered during the execution of a
+OCaml program instrumented with
+.BR ocamlcp (1).
+
+It produces a source listing of the program modules given as arguments
+where execution counts have been inserted as comments. For instance,
+
+.B ocamlprof foo.ml
+
+prints the source code for the foo module, with comments indicating
+how many times the functions in this module have been called. Naturally,
+this information is accurate only if the source file has not been modified
+since the profiling execution took place.
+
+.SH OPTIONS
+
+.TP
+.BI \-f \ dumpfile
+Specifies an alternate dump file of profiling information.
+.TP
+.BI \-F \ string
+Specifies an additional string to be output with profiling information.
+By default,
+.BR ocamlprof (1)
+will annotate programs with comments of the form
+.BI (* \ n \ *)
+where
+.I n
+is the counter value for a profiling point. With option
+.BI \-F \ s
+the annotation will be
+.BI (* \ sn \ *)
+.TP
+.BI \-impl \ filename
+Compile the file
+.I filename
+as an implementation file, even if its extension is not .ml.
+.TP
+.BI \-intf \ filename
+Compile the file
+.I filename
+as an interface file, even if its extension is not .mli.
+.TP
+.B \-version
+Print version string and exit.
+.TP
+.B \-vnum
+Print short version number and exit.
+.TP
+.BR \-help \ or \ \-\-help
+Display a short usage summary and exit.
+
+.SH SEE ALSO
+.BR ocamlcp (1).
+.br
+.IR "The OCaml user's manual" ,
+chapter "Profiling".
diff --git a/man/ocamlrun.m b/man/ocamlrun.m
new file mode 100644
index 0000000000..2882395e5a
--- /dev/null
+++ b/man/ocamlrun.m
@@ -0,0 +1,227 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLRUN 1
+
+.SH NAME
+ocamlrun \- The OCaml bytecode interpreter
+
+.SH SYNOPSIS
+.B ocamlrun
+[
+.I options
+]
+.I filename argument ...
+
+.SH DESCRIPTION
+The
+.BR ocamlrun (1)
+command executes bytecode files produced by the
+linking phase of the
+.BR ocamlc (1)
+command.
+
+The first non-option argument is taken to be the name of the file
+containing the executable bytecode. (That file is searched in the
+executable path as well as in the current directory.) The remaining
+arguments are passed to the OCaml program, in the string array
+.BR Sys.argv .
+Element 0 of this array is the name of the
+bytecode executable file; elements 1 to
+.I n
+are the remaining arguments.
+
+In most cases, the bytecode
+executable files produced by the
+.BR ocamlc (1)
+command are self-executable,
+and manage to launch the
+.BR ocamlrun (1)
+command on themselves automatically.
+
+.SH OPTIONS
+
+The following command-line options are recognized by
+.BR ocamlrun (1).
+.TP
+.B \-b
+When the program aborts due to an uncaught exception, print a detailed
+"back trace" of the execution, showing where the exception was
+raised and which function calls were outstanding at this point. The
+back trace is printed only if the bytecode executable contains
+debugging information, i.e. was compiled and linked with the
+.B \-g
+option to
+.BR ocamlc (1)
+set. This option is equivalent to setting the
+.B b
+flag in the OCAMLRUNPARAM environment variable (see below).
+.TP
+.BI \-I \ dir
+Search the directory
+.I dir
+for dynamically-loaded libraries, in addition to the standard search path.
+.TP
+.B \-p
+Print the names of the primitives known to this version of
+.BR ocamlrun (1)
+and exit.
+.TP
+.B \-v
+Direct the memory manager to print verbose messages on standard error.
+This is equivalent to setting
+.B v=63
+in the OCAMLRUNPARAM environment variable (see below).
+.TP
+.B \-version
+Print version string and exit.
+.TP
+.B \-vnum
+Print short version number and exit.
+
+.SH ENVIRONMENT VARIABLES
+
+The following environment variable are also consulted:
+.TP
+.B CAML_LD_LIBRARY_PATH
+Additional directories to search for dynamically-loaded libraries.
+.TP
+.B OCAMLLIB
+The directory containing the OCaml standard
+library. (If
+.B OCAMLLIB
+is not set,
+.B CAMLLIB
+will be used instead.) Used to locate the ld.conf configuration file for
+dynamic loading. If not set,
+default to the library directory specified when compiling OCaml.
+.TP
+.B OCAMLRUNPARAM
+Set the runtime system options and garbage collection parameters.
+(If OCAMLRUNPARAM is not set, CAMLRUNPARAM will be used instead.)
+This variable must be a sequence of parameter specifications separated
+by commas.
+A parameter specification is a letter, optionally followed by an =
+sign, a decimal number (or a hexadecimal number prefixed by
+.BR 0x ),
+and an optional multiplier. If the letter is followed by anything
+else, the corresponding option is set to 1. Unknown letters
+are ignored.
+The options are documented below; the
+last six correspond to the fields of the
+.B control
+record documented in
+.IR "The OCaml user's manual",
+chapter "Standard Library", section "Gc".
+.TP
+.B b
+Trigger the printing of a stack backtrace
+when an uncaught exception aborts the program.
+This option takes no argument.
+.TP
+.B p
+Turn on debugging support for
+.BR ocamlyacc -generated
+parsers. When this option is on,
+the pushdown automaton that executes the parsers prints a
+trace of its actions. This option takes no argument.
+.TP
+.BR R
+Turn on randomization of all hash tables by default (see the
+.B Hashtbl
+module of the standard library). This option takes no
+argument.
+.TP
+.BR h
+The initial size of the major heap (in words).
+.TP
+.BR a \ (allocation_policy)
+The policy used for allocating in the OCaml heap. Possible values
+are 0 for the next-fit policy, and 1 for the first-fit
+policy. Next-fit is usually faster, but first-fit is better for
+avoiding fragmentation and the associated heap compactions.
+.TP
+.BR s \ (minor_heap_size)
+The size of the minor heap (in words).
+.TP
+.BR i \ (major_heap_increment)
+The default size increment for the major heap (in words).
+.TP
+.BR o \ (space_overhead)
+The major GC speed setting.
+.TP
+.BR O \ (max_overhead)
+The heap compaction trigger setting.
+.TP
+.BR l \ (stack_limit)
+The limit (in words) of the stack size.
+.TP
+.BR v \ (verbose)
+What GC messages to print to stderr. This is a sum of values selected
+from the following:
+
+.B 0x001
+Start of major GC cycle.
+
+.B 0x002
+Minor collection and major GC slice.
+
+.B 0x004
+Growing and shrinking of the heap.
+
+.B 0x008
+Resizing of stacks and memory manager tables.
+
+.B 0x010
+Heap compaction.
+
+.BR 0x020
+Change of GC parameters.
+
+.BR 0x040
+Computation of major GC slice size.
+
+.BR 0x080
+Calling of finalisation functions.
+
+.BR 0x100
+Startup messages (loading the bytecode executable file, resolving
+shared libraries).
+
+.BR 0x200
+Computation of compaction-triggering condition.
+
+The multiplier is
+.BR k ,
+.BR M ,\ or
+.BR G ,
+for multiplication by 2^10, 2^20, and 2^30 respectively.
+For example, on a 32-bit machine under bash, the command
+.B export OCAMLRUNPARAM='s=256k,v=1'
+tells a subsequent
+.B ocamlrun
+to set its initial minor heap size to 1 megabyte and to print
+a message at the start of each major GC cycle.
+.TP
+.B CAMLRUNPARAM
+If OCAMLRUNPARAM is not found in the environment, then CAMLRUNPARAM
+will be used instead. If CAMLRUNPARAM is not found, then the default
+values will be used.
+.TP
+.B PATH
+List of directories searched to find the bytecode executable file.
+
+.SH SEE ALSO
+.BR ocamlc (1).
+.br
+.IR "The OCaml user's manual" ,
+chapter "Runtime system".
diff --git a/man/ocamlyacc.m b/man/ocamlyacc.m
new file mode 100644
index 0000000000..133994e206
--- /dev/null
+++ b/man/ocamlyacc.m
@@ -0,0 +1,106 @@
+.\"***********************************************************************
+.\"* *
+.\"* OCaml *
+.\"* *
+.\"* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+.\"* *
+.\"* Copyright 1996 Institut National de Recherche en Informatique et *
+.\"* en Automatique. All rights reserved. This file is distributed *
+.\"* under the terms of the Q Public License version 1.0. *
+.\"* *
+.\"***********************************************************************
+.\"
+.TH OCAMLYACC 1
+
+.SH NAME
+ocamlyacc \- The OCaml parser generator
+
+.SH SYNOPSIS
+.B ocamlyacc
+[
+.BI \-b prefix
+] [
+.B \-q
+] [
+.B \-v
+] [
+.B \-version
+] [
+.B \-vnum
+]
+.I filename.mly
+
+.SH DESCRIPTION
+
+The
+.BR ocamlyacc (1)
+command produces a parser from a LALR(1) context-free grammar
+specification with attached semantic actions, in the style of
+.BR yacc (1).
+Assuming the input file is
+.IR grammar \&.mly,
+running
+.B ocamlyacc
+produces OCaml code for a parser in the file
+.IR grammar \&.ml,
+and its interface in file
+.IR grammar \&.mli.
+
+The generated module defines one parsing function per entry point in
+the grammar. These functions have the same names as the entry points.
+Parsing functions take as arguments a lexical analyzer (a function
+from lexer buffers to tokens) and a lexer buffer, and return the
+semantic attribute of the corresponding entry point. Lexical analyzer
+functions are usually generated from a lexer specification by the
+.BR ocamllex (1)
+program. Lexer buffers are an abstract data type
+implemented in the standard library module Lexing. Tokens are values from
+the concrete type token, defined in the interface file
+.IR grammar \&.mli
+produced by
+.BR ocamlyacc (1).
+
+.SH OPTIONS
+
+The
+.BR ocamlyacc (1)
+command recognizes the following options:
+.TP
+.BI \-b prefix
+Name the output files
+.IR prefix \&.ml,
+.IR prefix \&.mli,
+.IR prefix \&.output,
+instead of the default naming convention.
+.TP
+.B \-q
+This option has no effect.
+.TP
+.B \-v
+Generate a description of the parsing tables and a report on conflicts
+resulting from ambiguities in the grammar. The description is put in
+file
+.IR grammar .output.
+.TP
+.B \-version
+Print version string and exit.
+.TP
+.B \-vnum
+Print short version number and exit.
+.TP
+.B \-
+Read the grammar specification from standard input. The default
+output file names are stdin.ml and stdin.mli.
+.TP
+.BI \-\- \ file
+Process
+.I file
+as the grammar specification, even if its name
+starts with a dash (-) character. This option must be the last on the
+command line.
+
+.SH SEE ALSO
+.BR ocamllex (1).
+.br
+.IR "The OCaml user's manual" ,
+chapter "Lexer and parser generators".
diff --git a/ocamlbuild/.depend b/ocamlbuild/.depend
new file mode 100644
index 0000000000..d6dda722ed
--- /dev/null
+++ b/ocamlbuild/.depend
@@ -0,0 +1,207 @@
+bool.cmi :
+command.cmi : tags.cmi signatures.cmi
+configuration.cmi : tags.cmi pathname.cmi loc.cmi
+digest_cache.cmi :
+discard_printf.cmi :
+display.cmi : tags.cmi
+exit_codes.cmi :
+fda.cmi : slurp.cmi
+findlib.cmi : signatures.cmi command.cmi
+flags.cmi : tags.cmi command.cmi
+glob_ast.cmi : bool.cmi
+glob_lexer.cmi : glob_ast.cmi
+glob.cmi : signatures.cmi glob_ast.cmi bool.cmi
+hooks.cmi :
+hygiene.cmi : slurp.cmi
+lexers.cmi : loc.cmi glob.cmi
+loc.cmi :
+log.cmi : tags.cmi signatures.cmi
+main.cmi :
+my_std.cmi : signatures.cmi
+my_unix.cmi :
+ocaml_arch.cmi : signatures.cmi command.cmi
+ocamlbuild_executor.cmi :
+ocamlbuildlight.cmi :
+ocamlbuild.cmi :
+ocamlbuild_plugin.cmi :
+ocamlbuild_unix_plugin.cmi :
+ocamlbuild_where.cmi :
+ocaml_compiler.cmi : tags.cmi rule.cmi pathname.cmi command.cmi
+ocaml_dependencies.cmi : pathname.cmi
+ocaml_specific.cmi :
+ocaml_tools.cmi : tags.cmi rule.cmi pathname.cmi command.cmi
+ocaml_utils.cmi : tags.cmi pathname.cmi command.cmi
+options.cmi : slurp.cmi signatures.cmi command.cmi
+param_tags.cmi : tags.cmi loc.cmi
+pathname.cmi : signatures.cmi
+plugin.cmi :
+ppcache.cmi :
+report.cmi : solver.cmi
+resource.cmi : slurp.cmi pathname.cmi my_std.cmi command.cmi
+rule.cmi : tags.cmi resource.cmi pathname.cmi my_std.cmi command.cmi
+shell.cmi :
+signatures.cmi :
+slurp.cmi : my_unix.cmi
+solver.cmi : pathname.cmi
+tags.cmi : signatures.cmi
+tools.cmi : tags.cmi pathname.cmi
+bool.cmo : bool.cmi
+bool.cmx : bool.cmi
+command.cmo : tags.cmi shell.cmi param_tags.cmi my_unix.cmi my_std.cmi \
+ log.cmi lexers.cmi const.cmo command.cmi
+command.cmx : tags.cmx shell.cmx param_tags.cmx my_unix.cmx my_std.cmx \
+ log.cmx lexers.cmx const.cmx command.cmi
+configuration.cmo : tags.cmi param_tags.cmi my_std.cmi log.cmi loc.cmi \
+ lexers.cmi glob.cmi const.cmo configuration.cmi
+configuration.cmx : tags.cmx param_tags.cmx my_std.cmx log.cmx loc.cmx \
+ lexers.cmx glob.cmx const.cmx configuration.cmi
+const.cmo :
+const.cmx :
+digest_cache.cmo : shell.cmi pathname.cmi options.cmi my_unix.cmi my_std.cmi \
+ digest_cache.cmi
+digest_cache.cmx : shell.cmx pathname.cmx options.cmx my_unix.cmx my_std.cmx \
+ digest_cache.cmi
+discard_printf.cmo : discard_printf.cmi
+discard_printf.cmx : discard_printf.cmi
+display.cmo : tags.cmi my_unix.cmi my_std.cmi discard_printf.cmi display.cmi
+display.cmx : tags.cmx my_unix.cmx my_std.cmx discard_printf.cmx display.cmi
+exit_codes.cmo : exit_codes.cmi
+exit_codes.cmx : exit_codes.cmi
+fda.cmo : pathname.cmi options.cmi log.cmi hygiene.cmi fda.cmi
+fda.cmx : pathname.cmx options.cmx log.cmx hygiene.cmx fda.cmi
+findlib.cmo : my_unix.cmi my_std.cmi lexers.cmi const.cmo command.cmi \
+ findlib.cmi
+findlib.cmx : my_unix.cmx my_std.cmx lexers.cmx const.cmx command.cmx \
+ findlib.cmi
+flags.cmo : tags.cmi param_tags.cmi log.cmi command.cmi bool.cmi flags.cmi
+flags.cmx : tags.cmx param_tags.cmx log.cmx command.cmx bool.cmx flags.cmi
+glob_ast.cmo : bool.cmi glob_ast.cmi
+glob_ast.cmx : bool.cmx glob_ast.cmi
+glob_lexer.cmo : glob_ast.cmi bool.cmi glob_lexer.cmi
+glob_lexer.cmx : glob_ast.cmx bool.cmx glob_lexer.cmi
+glob.cmo : my_std.cmi glob_lexer.cmi glob_ast.cmi bool.cmi glob.cmi
+glob.cmx : my_std.cmx glob_lexer.cmx glob_ast.cmx bool.cmx glob.cmi
+hooks.cmo : hooks.cmi
+hooks.cmx : hooks.cmi
+hygiene.cmo : slurp.cmi shell.cmi pathname.cmi options.cmi my_std.cmi \
+ log.cmi hygiene.cmi
+hygiene.cmx : slurp.cmx shell.cmx pathname.cmx options.cmx my_std.cmx \
+ log.cmx hygiene.cmi
+lexers.cmo : my_std.cmi loc.cmi glob_ast.cmi glob.cmi bool.cmi lexers.cmi
+lexers.cmx : my_std.cmx loc.cmx glob_ast.cmx glob.cmx bool.cmx lexers.cmi
+loc.cmo : loc.cmi
+loc.cmx : loc.cmi
+log.cmo : my_unix.cmi my_std.cmi display.cmi log.cmi
+log.cmx : my_unix.cmx my_std.cmx display.cmx log.cmi
+main.cmo : tools.cmi tags.cmi solver.cmi slurp.cmi shell.cmi rule.cmi \
+ resource.cmi report.cmi plugin.cmi pathname.cmi param_tags.cmi \
+ options.cmi ocaml_utils.cmi ocaml_specific.cmi ocaml_dependencies.cmi \
+ my_unix.cmi my_std.cmi log.cmi loc.cmi lexers.cmi hooks.cmi flags.cmi \
+ fda.cmi exit_codes.cmi digest_cache.cmi const.cmo configuration.cmi \
+ command.cmi main.cmi
+main.cmx : tools.cmx tags.cmx solver.cmx slurp.cmx shell.cmx rule.cmx \
+ resource.cmx report.cmx plugin.cmx pathname.cmx param_tags.cmx \
+ options.cmx ocaml_utils.cmx ocaml_specific.cmx ocaml_dependencies.cmx \
+ my_unix.cmx my_std.cmx log.cmx loc.cmx lexers.cmx hooks.cmx flags.cmx \
+ fda.cmx exit_codes.cmx digest_cache.cmx const.cmx configuration.cmx \
+ command.cmx main.cmi
+my_std.cmo : my_std.cmi
+my_std.cmx : my_std.cmi
+my_unix.cmo : my_std.cmi my_unix.cmi
+my_unix.cmx : my_std.cmx my_unix.cmi
+ocaml_arch.cmo : pathname.cmi my_std.cmi command.cmi ocaml_arch.cmi
+ocaml_arch.cmx : pathname.cmx my_std.cmx command.cmx ocaml_arch.cmi
+ocamlbuild_config.cmo :
+ocamlbuild_config.cmx :
+ocamlbuild_executor.cmo : ocamlbuild_executor.cmi
+ocamlbuild_executor.cmx : ocamlbuild_executor.cmi
+ocamlbuildlight.cmo : ocamlbuildlight.cmi
+ocamlbuildlight.cmx : ocamlbuildlight.cmi
+ocamlbuild.cmo : ocamlbuild_unix_plugin.cmi ocamlbuild.cmi
+ocamlbuild.cmx : ocamlbuild_unix_plugin.cmx ocamlbuild.cmi
+ocamlbuild_plugin.cmo : ocamlbuild_plugin.cmi
+ocamlbuild_plugin.cmx : ocamlbuild_plugin.cmi
+ocamlbuild_unix_plugin.cmo : ocamlbuild_executor.cmi my_unix.cmi my_std.cmi \
+ exit_codes.cmi ocamlbuild_unix_plugin.cmi
+ocamlbuild_unix_plugin.cmx : ocamlbuild_executor.cmx my_unix.cmx my_std.cmx \
+ exit_codes.cmx ocamlbuild_unix_plugin.cmi
+ocamlbuild_where.cmo : ocamlbuild_config.cmo ocamlbuild_where.cmi
+ocamlbuild_where.cmx : ocamlbuild_config.cmx ocamlbuild_where.cmi
+ocaml_compiler.cmo : tools.cmi tags.cmi rule.cmi resource.cmi pathname.cmi \
+ options.cmi ocaml_utils.cmi ocaml_dependencies.cmi ocaml_arch.cmi \
+ my_std.cmi log.cmi command.cmi ocaml_compiler.cmi
+ocaml_compiler.cmx : tools.cmx tags.cmx rule.cmx resource.cmx pathname.cmx \
+ options.cmx ocaml_utils.cmx ocaml_dependencies.cmx ocaml_arch.cmx \
+ my_std.cmx log.cmx command.cmx ocaml_compiler.cmi
+ocaml_dependencies.cmo : tools.cmi resource.cmi pathname.cmi ocaml_utils.cmi \
+ my_std.cmi log.cmi ocaml_dependencies.cmi
+ocaml_dependencies.cmx : tools.cmx resource.cmx pathname.cmx ocaml_utils.cmx \
+ my_std.cmx log.cmx ocaml_dependencies.cmi
+ocaml_specific.cmo : tools.cmi tags.cmi rule.cmi pathname.cmi options.cmi \
+ ocamlbuild_config.cmo ocaml_utils.cmi ocaml_tools.cmi ocaml_compiler.cmi \
+ my_std.cmi log.cmi flags.cmi findlib.cmi configuration.cmi command.cmi \
+ ocaml_specific.cmi
+ocaml_specific.cmx : tools.cmx tags.cmx rule.cmx pathname.cmx options.cmx \
+ ocamlbuild_config.cmx ocaml_utils.cmx ocaml_tools.cmx ocaml_compiler.cmx \
+ my_std.cmx log.cmx flags.cmx findlib.cmx configuration.cmx command.cmx \
+ ocaml_specific.cmi
+ocaml_tools.cmo : tools.cmi tags.cmi rule.cmi pathname.cmi options.cmi \
+ ocaml_utils.cmi ocaml_compiler.cmi my_std.cmi flags.cmi command.cmi \
+ ocaml_tools.cmi
+ocaml_tools.cmx : tools.cmx tags.cmx rule.cmx pathname.cmx options.cmx \
+ ocaml_utils.cmx ocaml_compiler.cmx my_std.cmx flags.cmx command.cmx \
+ ocaml_tools.cmi
+ocaml_utils.cmo : tools.cmi tags.cmi pathname.cmi param_tags.cmi options.cmi \
+ my_std.cmi log.cmi lexers.cmi flags.cmi const.cmo command.cmi \
+ ocaml_utils.cmi
+ocaml_utils.cmx : tools.cmx tags.cmx pathname.cmx param_tags.cmx options.cmx \
+ my_std.cmx log.cmx lexers.cmx flags.cmx const.cmx command.cmx \
+ ocaml_utils.cmi
+options.cmo : shell.cmi ocamlbuild_where.cmi ocamlbuild_config.cmo \
+ my_std.cmi log.cmi lexers.cmi const.cmo command.cmi options.cmi
+options.cmx : shell.cmx ocamlbuild_where.cmx ocamlbuild_config.cmx \
+ my_std.cmx log.cmx lexers.cmx const.cmx command.cmx options.cmi
+param_tags.cmo : tags.cmi my_std.cmi log.cmi loc.cmi lexers.cmi \
+ param_tags.cmi
+param_tags.cmx : tags.cmx my_std.cmx log.cmx loc.cmx lexers.cmx \
+ param_tags.cmi
+pathname.cmo : shell.cmi options.cmi my_unix.cmi my_std.cmi log.cmi glob.cmi \
+ pathname.cmi
+pathname.cmx : shell.cmx options.cmx my_unix.cmx my_std.cmx log.cmx glob.cmx \
+ pathname.cmi
+plugin.cmo : tools.cmi tags.cmi shell.cmi rule.cmi pathname.cmi \
+ param_tags.cmi options.cmi ocamlbuild_where.cmi my_unix.cmi my_std.cmi \
+ log.cmi const.cmo command.cmi plugin.cmi
+plugin.cmx : tools.cmx tags.cmx shell.cmx rule.cmx pathname.cmx \
+ param_tags.cmx options.cmx ocamlbuild_where.cmx my_unix.cmx my_std.cmx \
+ log.cmx const.cmx command.cmx plugin.cmi
+ppcache.cmo : shell.cmi pathname.cmi my_std.cmi log.cmi command.cmi \
+ ppcache.cmi
+ppcache.cmx : shell.cmx pathname.cmx my_std.cmx log.cmx command.cmx \
+ ppcache.cmi
+report.cmo : solver.cmi resource.cmi my_std.cmi log.cmi glob.cmi report.cmi
+report.cmx : solver.cmx resource.cmx my_std.cmx log.cmx glob.cmx report.cmi
+resource.cmo : slurp.cmi shell.cmi pathname.cmi options.cmi my_unix.cmi \
+ my_std.cmi log.cmi lexers.cmi glob_ast.cmi glob.cmi digest_cache.cmi \
+ const.cmo command.cmi resource.cmi
+resource.cmx : slurp.cmx shell.cmx pathname.cmx options.cmx my_unix.cmx \
+ my_std.cmx log.cmx lexers.cmx glob_ast.cmx glob.cmx digest_cache.cmx \
+ const.cmx command.cmx resource.cmi
+rule.cmo : shell.cmi resource.cmi pathname.cmi options.cmi my_std.cmi \
+ log.cmi digest_cache.cmi command.cmi rule.cmi
+rule.cmx : shell.cmx resource.cmx pathname.cmx options.cmx my_std.cmx \
+ log.cmx digest_cache.cmx command.cmx rule.cmi
+shell.cmo : tags.cmi my_unix.cmi my_std.cmi log.cmi shell.cmi
+shell.cmx : tags.cmx my_unix.cmx my_std.cmx log.cmx shell.cmi
+slurp.cmo : my_unix.cmi my_std.cmi slurp.cmi
+slurp.cmx : my_unix.cmx my_std.cmx slurp.cmi
+solver.cmo : rule.cmi resource.cmi pathname.cmi my_std.cmi log.cmi \
+ command.cmi solver.cmi
+solver.cmx : rule.cmx resource.cmx pathname.cmx my_std.cmx log.cmx \
+ command.cmx solver.cmi
+tags.cmo : tags.cmi
+tags.cmx : tags.cmi
+tools.cmo : tags.cmi rule.cmi pathname.cmi my_std.cmi log.cmi \
+ configuration.cmi tools.cmi
+tools.cmx : tags.cmx rule.cmx pathname.cmx my_std.cmx log.cmx \
+ configuration.cmx tools.cmi
diff --git a/ocamlbuild/AUTHORS b/ocamlbuild/AUTHORS
new file mode 100644
index 0000000000..0b27a5b1a8
--- /dev/null
+++ b/ocamlbuild/AUTHORS
@@ -0,0 +1,2 @@
+Nicolas Pouillard
+Berke Durak
diff --git a/ocamlbuild/ChangeLog b/ocamlbuild/ChangeLog
new file mode 100644
index 0000000000..183be58210
--- /dev/null
+++ b/ocamlbuild/ChangeLog
@@ -0,0 +1,3621 @@
+2007-03-22 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Allow to receive the build function in {custom,file}_rule.
+
+ * rule.ml,
+ * rule.mli,
+ * signatures.mli: Ditto.
+ * ocaml_specific.ml: Update.
+
+ * command.ml,
+ * command.mli: Add a function to get string and tags.
+
+ * ocamldep.ml,
+ * ocamldep.mli: Make tag based dependencies.
+
+ * ocaml_compiler.ml: Do the pack as one command to be sure running the
+ remove.
+
+ * test/test8/myocamlbuild.ml,
+ * test/good-output: Update.
+
+2007-03-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the previous fix.
+
+ * ocaml_compiler.ml: Remove the empty file.
+ * test/good-output: Update.
+
+2007-03-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ [native pack] use touch instead of mv and cmp.
+
+ * ocaml_compiler.ml: This version is will force ocamlopt to do the
+ right thing.
+ * test/good-output: Update.
+
+2007-03-20 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Two bugs, two fixes.
+
+ * ocaml_tools.ml: Add pp flags to interface inference.
+ * ocaml_specific.ml: Add a rule for packing with a cmi that already
+ exists.
+ * test/good-output: Update.
+ * Makefile: Change the default location.
+
+2007-03-13 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a bug in expand_module.
+
+ * ocaml_utils.ml: Handle correctly pathnames instead of just basenames.
+
+2007-03-13 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use sys_file_exists instead of Sys.file_exists.
+
+ * my_unix.ml: Since Sys.file_exists don't treat well captial letters.
+ * my_std.ml: Fix a bug.
+ * pathname.ml: Here is a an exception to the previous rule so, put a
+ comment.
+
+2007-03-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the List.union order.
+
+ * my_std.ml: Fix and improve List.union.
+ * pathname.ml: Use it and fix merge_include_dirs.
+ * test/good-output: Update since the union order was wrong.
+
+2007-03-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Re fix menhir and include dirs.
+
+ * ocaml_tools.ml: Specifiy ocamlc and -I with --ocamlc.
+
+2007-03-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a bug: Add include directories to menhir.
+
+ * ocaml_tools.ml: Ditto.
+ * my_std.ml,
+ * signatures.mli: Specification typo.
+
+2007-03-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Handle specially archives files during an import.
+
+ * shell.ml: Ditto.
+
+2007-03-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use cp -p in copy_rule, and fix some typos in the manual.
+
+ * manual/manual.tex: Typos.
+ * rule.ml,
+ * rule.mli: Add cp_p and use it for copy_rule.
+
+2007-03-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Relaxe executor on exception condition.
+
+ Patch from Berke.
+ * executor.ml: Ignore Not_found and exceptional conditions.
+ * TODO: Add an entry (needs to better understand POSIX).
+
+2007-03-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Split where in bindir and libdir.
+
+ * ocamlbuild_where.mli: Ditto.
+ * ocaml_specific.ml: Update.
+ * options.ml: Use bindir.
+ * plugin.ml: Update.
+ * start.sh: Update.
+
+2007-03-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Virtual solvers for ocaml tools.
+
+ * options.ml: Setup virtual command solver for commands like ocamlc,
+ ocamlopt... This allow to have full pathname but let also failback to
+ classic search path.
+ * ocaml_compiler.ml: Add a tag to differentiate dependencies at link
+ time.
+ * ocamlbuild-presentation.rslide: Add an item as suggested by a friend.
+
+2007-03-02 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Same thing for the second link function.
+
+ * ocaml_compiler.ml: Ignore stdlib.
+
+2007-03-02 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Move the stdlib hack.
+
+ * ocaml_compiler.ml: Should works better.
+
+2007-03-02 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Little fix about library linking.
+
+ * ocaml_utils.ml: Avoid linking twice in some cases.
+ * ocaml_compiler.ml: Handle specially the OCaml stdlib.
+
+2007-03-01 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Remove a rec.
+
+ * glob.ml: Parse is not rec.
+
+2007-03-01 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ true: traverse and FAQ.
+
+ * main.ml: Move the inital config upper to be loaded before the others
+ and hygiene.
+ * FAQ: New.
+
+2007-02-28 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Improve the glob dir handling.
+
+ * glob.ml: Extend the ast instead of parsing an extended string.
+
+2007-02-28 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Ensure that the whole boolean expression is only valid in the directory.
+
+ * glob.ml: Ditto.
+
+2007-02-28 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Put -g on link only for programs.
+
+ * ocaml_specific.ml: Ditto.
+
+2007-02-26 Berke Durak <berke.durak@inria.fr>
+
+ Added disclaimer to default rules table.
+
+ * manual/manual.tex: .
+
+2007-02-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add the -documentation option.
+
+ * main.ml: Implement it.
+ * flags.ml,
+ * flags.mli: Add get_flags.
+ * man/ocamlbuild.1: Update.
+ * signatures.mli,
+ * options.ml: Add show_documention.
+ * rule.ml,
+ * rule.mli: Add pretty_print.
+
+2007-02-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add the -dont-catch-errors option.
+
+ * main.ml: Implement it.
+ * options.ml: Parse it.
+ * signatures.mli: Declare it.
+ * _tags: Use debug.
+
+2007-02-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Deal with the camlp4 library name.
+
+ * ocaml_specific.ml: Introduce use_old_camlp4 for the old one.
+
+2007-02-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Minor `ocaml_lib' improvments.
+
+ * signatures.mli: Declare and doc it.
+ * ocamlbuild_plugin.ml: Export it.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Add some dirs to std libs.
+ Move the ocaml_lib implem to ...
+ * ocaml_utils.mli,
+ * ocaml_utils.ml: ... here. Improve it by adding the ~tag_name option.
+ * ocaml_compiler.ml: The hash now contains the tag.
+ * _tags: *.top use unix too.
+
+2007-02-22 Berke Durak <berke.durak@inria.fr>
+
+ Should use Log.eprintf for show_tags.
+
+ * main.ml: .
+
+2007-02-22 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ ( & ), sanitize.sh, and the manual...
+
+ * signatures.mli: Add ( & ).
+
+ * hygiene.ml: Also clean the sanitize.sh script itself.
+ * my_std.ml: Add ( & ).
+ * manual/manual.tex: Some fixes and a section that I wrote but that's
+ needs reflexion about what solution we want to support.
+
+2007-02-22 Berke Durak <berke.durak@inria.fr>
+
+ Implemented fixes suggested by Commissar Leroy.
+
+ * fda.ml: .
+ * hygiene.ml: .
+ * hygiene.mli: .
+ * man/ocamlbuild.1: .
+ * manual/manual.tex: .
+ * ocaml_specific.ml: .
+ * options.ml: .
+ * signatures.mli: .
+
+2007-02-20 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add -show-tags.
+
+ * hygiene.ml: Rewrap the error message.
+ * main.ml: Do the show_tags job. Move one hook.
+ * ocaml_specific.ml: Add -g also in native code.
+ * options.ml,
+ * signatures.mli: Add the -show-tags option.
+ * tags.ml: Fix print.
+ * TODO: Add a done entry.
+
+2007-02-16 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Relaxing plural options to spaces.
+
+ * lexers.mli,
+ * lexers.mll: Add comma_or_blank_sep_strings.
+ * options.ml: Use it.
+
+2007-02-16 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a plugin example.
+
+ * manual/myocamlbuild.ml: New.
+
+2007-02-16 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Typos.
+
+ * ocamlbuild-presentation.rslide: .
+ * manual/trace.out: .
+
+2007-02-16 Berke Durak <berke.durak@inria.fr>
+
+ Fixed a few typos and sentences.
+
+ * ocamlbuild-presentation.rslide: .
+
+2007-02-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Little changes...
+
+ * ocamlbuild-presentation.rslide: .
+
+2007-02-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Slides almost done...
+
+ * manual/trace.out: New. Of course you needed it.
+ * ocamlbuild-presentation.rslide: Ditto.
+
+2007-02-15 Berke Durak <berke.durak@inria.fr>
+
+ Improving slides.
+
+ * ocamlbuild-presentation.rslide: .
+
+2007-02-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Slides...
+
+ * ocamlbuild-presentation.rslide: .
+
+2007-02-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Working on slides...
+
+ * ocamlbuild-presentation.rslide: .
+
+2007-02-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ More slides...
+
+ * ocamlbuild-presentation.rslide: .
+
+2007-02-12 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Keep include dirs uniq.
+
+ * ocaml_compiler.ml: Ditto.
+
+2007-02-12 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Keep include dirs uniq.
+
+ * ocaml_compiler.ml: Ditto.
+
+2007-02-12 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add ocamlmktop support.
+
+ * ocamlbuild.mltop: New.
+ * main.ml: Handle .top as binaries.
+ * ocaml_compiler.ml,
+ * ocaml_specific.ml,
+ * ocaml_compiler.mli: Add mktop functions and rules.
+ * options.ml,
+ * signatures.mli: Add an ocamlmktop option.
+
+2007-02-09 Berke Durak <berke.durak@inria.fr>
+
+ Was attempting to link with threads.cmxa in byte mode.
+
+ * ocaml_specific.ml: .
+
+2007-02-09 Berke Durak <berke.durak@inria.fr>
+
+ Talking of sterilize.sh.
+
+ * manual/manual.tex: .
+
+2007-02-09 Berke Durak <berke.durak@inria.fr>
+
+ Rewrote some parts, filled the abstract, moved rantings to the appendix.
+
+ * manual/manual.tex: .
+ * .vcs: .
+
+2007-02-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add manual/manual.hva.
+
+ * manual/manual.hva: New.
+
+2007-02-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Changes done with Luc.
+
+ * manual/manual.tex: .
+ * manual/Makefile: .
+
+2007-02-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a bug found by Luc in hevea.
+
+ * ocaml_utils.ml,
+ * ocaml_utils.mli: Change keep_this_module into module_importance to
+ have a finer grain.
+ * ocaml_compiler.ml: Update to importance.
+ * ocamldep.ml,
+ * ocamldep.mli: We now try to also build stdlib modules but don't fail
+ if they don't exists.
+ * test/test5/stack.ml: New.
+ * test/test5/a.ml: A test case (from hevea).
+ * test/good-output: Update.
+
+2007-02-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Ocamldoc, extension:* tag ...
+
+ * ocaml_tools.mli,
+ * ocaml_tools.ml: The ocamldoc support now takes into account two modes
+ *d and -o.
+ * ocaml_specific.ml: Two more rules and many flags for some of the
+ standard behaviors.
+ * signatures.mli: Some comments.
+ * tools.ml: Add the extension:* tag.
+ * TODO: Update.
+
+2007-02-08 Berke Durak <berke.durak@inria.fr>
+
+ Hygiene generates sterilize.sh.
+
+ * fda.ml: .
+ * fda.mli: .
+ * hygiene.ml: .
+ * hygiene.mli: .
+ * main.ml: .
+ * options.ml: .
+ * signatures.mli: .
+
+2007-02-07 Berke Durak <berke.durak@inria.fr>
+
+ Updated section on ocamldoc.
+
+ * manual/manual.tex: .
+
+2007-02-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some minor manual and slides changes.
+
+ * ocamlbuild-presentation.rslide,
+ * manual/manual.tex: Ditto.
+
+2007-02-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Make links for the documentation.
+
+ * main.ml: Handle doc.
+ * test/good-output: Update.
+
+2007-02-07 Berke Durak <berke.durak@inria.fr>
+
+ Added manual section for ocamldoc.
+
+ * manual/manual.tex: .
+ * manual/Makefile: .
+
+2007-02-07 Berke Durak <berke.durak@inria.fr>
+
+ Fixed truncated display problem.
+
+ * executor.ml: .
+ * .vcs: .
+
+2007-02-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the bootstrap.
+
+ * start.sh: Swap lines.
+ * Makefile: -verbose.
+
+2007-02-07 Berke Durak <berke.durak@inria.fr>
+
+ TODO + Executor.
+
+ * manual/manual.tex: .
+ * TODO: .
+
+2007-02-06 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Make -a more static, to avoid some complications.
+
+ * ocaml_utils.ml,
+ * ocaml_compiler.ml,
+ * ocaml_compiler.ml,
+ * ocaml_specific.ml: Ditto.
+
+2007-02-06 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ A fix.
+
+ * ocaml_compiler.ml: Don't use these refs too early.
+ * ocamlbuild-presentation.rslide: .
+
+2007-02-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Plugin signature.
+
+ Somewhat a big patch, but that's just moving things around.
+
+ * signatures.mli: Add TAGS, OUTCOME, MISC, OPTIONS, ARCH and PLUGIN.
+ * ocamlbuild_plugin.mli: New.
+ * ocamlbuild_plugin.ml: Conform to the sig.
+
+ * command.ml,
+ * command.mli: Add a tags type.
+ * main.ml: Quit early if no targets.
+ * my_std.ml,
+ * my_std.mli: More things are in signatures.
+ * resource.ml,
+ * resource.mli: Remove the type t that was an Pathname.t alias.
+ * options.ml,
+ * options.mli: Add ext_lib, ext_obj, ext_dll.
+ * ocaml_compiler.ml: Update.
+ * ocaml_tools.ml: Update to Outcome.
+ * ocaml_specific.ml: Update.
+ * ocaml_utils.mli: Remove *ext_*.
+ * ocaml_arch.mli: Now in signatures.
+ * pathname.ml: Add readdir.
+ * slurp.ml: open Outcome.
+ * rule.ml,
+ * rule.mli,
+ * solver.ml,
+ * solver.mli: Update to Resource.t and Outcome.t.
+ * tags.mli: Now in Signatures.
+ * test/good-output: Update.
+ * test/test8/test.sh,
+ * test/test3/test.sh,
+ * test/test4/test.sh,
+ * test/test5/test.sh,
+ * test/test6/test.sh,
+ * test/test7/test.sh,
+ * test/test2/test.sh: Update to -verbose 0.
+
+2007-02-05 Berke Durak <berke.durak@inria.fr>
+
+ Continuing doc.
+
+ * manual/manual.tex: .
+ * .: .
+
+2007-02-05 Berke Durak <berke.durak@inria.fr>
+
+ Described display line.
+
+ * manual/manual.tex: .
+
+2007-02-05 Berke Durak <berke.durak@inria.fr>
+
+ Renamed -debug as -verbose. Authorized spaces etc. in flags. Continuing documentation.
+
+ * lexers.mll: .
+ * manual/manual.tex: .
+ * options.ml: .
+
+2007-02-05 Berke Durak <berke.durak@inria.fr>
+
+ Added man page.
+
+ * main.ml: .
+ * man: New.
+ * man/ocamlbuild.1: New.
+ * manual/manual.tex: .
+ * TODO: .
+
+2007-02-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Update start.sh.
+
+ * start.sh: Update.
+
+2007-02-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Typo s/Orignal/Original/g.
+
+2007-02-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Make signatures and std_signatures mliS.
+
+ * signatures.ml: Remove.
+ * std_signatures.ml: Remove.
+ * signatures.mli: New.
+ * std_signatures.mli: New.
+ * Makefile: Update.
+ * lexers.mll: Allow any prefix: for tags.
+
+2007-02-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ The beginning of a presentation.
+
+ * ocamlbuild-presentation.rslide: New.
+
+2007-02-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Also add who is the original author of the file.
+
+ * ocamlbuild.ml,
+ * ocamlbuild_plugin.ml,
+ * ocamlbuildlight.ml,
+ * ocamlbuild_where.mli,
+ * ocamlbuild.mli,
+ * ocamlbuildlight.mli,
+ * bool.ml,
+ * bool.mli,
+ * configuration.ml,
+ * configuration.mli,
+ * command.ml,
+ * command.mli,
+ * display.ml,
+ * discard_printf.ml,
+ * display.mli,
+ * discard_printf.mli,
+ * executor.ml,
+ * executor.mli,
+ * flags.ml,
+ * fda.ml,
+ * flags.mli,
+ * fda.mli,
+ * glob.ml,
+ * glob_ast.ml,
+ * glob_ast.mli,
+ * glob.mli,
+ * glob_lexer.mli,
+ * glob_lexer.mll,
+ * hygiene.ml,
+ * hooks.ml,
+ * hygiene.mli,
+ * hooks.mli,
+ * log.ml,
+ * lexers.mli,
+ * log.mli,
+ * lexers.mll,
+ * my_unix_with_unix.ml,
+ * main.ml,
+ * my_unix.ml,
+ * my_std.ml,
+ * my_unix_with_unix.mli,
+ * my_std.mli,
+ * my_unix.mli,
+ * main.mli,
+ * ocaml_utils.ml,
+ * ocaml_tools.ml,
+ * ocaml_arch.ml,
+ * ocaml_specific.ml,
+ * ocaml_compiler.ml,
+ * ocaml_dependencies.ml,
+ * ocaml_utils.mli,
+ * ocaml_specific.mli,
+ * ocaml_dependencies.mli,
+ * ocaml_tools.mli,
+ * ocaml_arch.mli,
+ * ocaml_compiler.mli,
+ * options.ml,
+ * options.mli,
+ * ocamldep.ml,
+ * ocamldep.mli,
+ * plugin.ml,
+ * ppcache.ml,
+ * pathname.ml,
+ * ppcache.mli,
+ * plugin.mli,
+ * pathname.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml,
+ * rule.mli,
+ * report.ml,
+ * report.mli,
+ * signatures.ml,
+ * slurp.ml,
+ * std_signatures.ml,
+ * solver.ml,
+ * shell.ml,
+ * shell.mli,
+ * slurp.mli,
+ * solver.mli,
+ * tags.ml,
+ * tools.ml,
+ * tags.mli,
+ * tools.mli: Ditto.
+
+2007-02-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add the header license.
+
+ * ocamlbuildlight.ml,
+ * ocamlbuild.ml,
+ * ocamlbuild_plugin.ml,
+ * ocamlbuild_where.mli,
+ * ocamlbuild.mli,
+ * ocamlbuildlight.mli,
+ * bool.ml,
+ * bool.mli,
+ * configuration.ml,
+ * configuration.mli,
+ * command.ml,
+ * command.mli,
+ * discard_printf.ml,
+ * display.ml,
+ * display.mli,
+ * discard_printf.mli,
+ * executor.ml,
+ * executor.mli,
+ * fda.ml,
+ * flags.ml,
+ * flags.mli,
+ * fda.mli,
+ * glob.ml,
+ * glob_ast.ml,
+ * glob.mli,
+ * glob_ast.mli,
+ * glob_lexer.mli,
+ * glob_lexer.mll,
+ * hygiene.ml,
+ * hooks.ml,
+ * hygiene.mli,
+ * hooks.mli,
+ * log.ml,
+ * lexers.mli,
+ * log.mli,
+ * lexers.mll,
+ * my_unix.ml,
+ * main.ml,
+ * my_std.ml,
+ * my_unix_with_unix.ml,
+ * misc/opentracer.ml,
+ * my_std.mli,
+ * main.mli,
+ * my_unix.mli,
+ * my_unix_with_unix.mli,
+ * ocaml_arch.ml,
+ * ocaml_compiler.ml,
+ * ocaml_specific.ml,
+ * ocaml_tools.ml,
+ * ocaml_utils.ml,
+ * ocaml_dependencies.ml,
+ * ocaml_utils.mli,
+ * ocaml_tools.mli,
+ * ocaml_dependencies.mli,
+ * ocaml_compiler.mli,
+ * ocaml_specific.mli,
+ * ocaml_arch.mli,
+ * options.ml,
+ * options.mli,
+ * ocamldep.ml,
+ * ocamldep.mli,
+ * plugin.ml,
+ * pathname.ml,
+ * ppcache.ml,
+ * plugin.mli,
+ * ppcache.mli,
+ * pathname.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml,
+ * rule.mli,
+ * report.ml,
+ * report.mli,
+ * slurp.ml,
+ * std_signatures.ml,
+ * signatures.ml,
+ * solver.ml,
+ * shell.ml,
+ * shell.mli,
+ * slurp.mli,
+ * solver.mli,
+ * tools.ml,
+ * tags.ml,
+ * tags.mli,
+ * tools.mli: Ditto.
+
+2007-02-03 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a bug in copy_file.
+
+ * my_std.ml: Also use the binary mode for the output channel.
+
+2007-02-03 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add nopervasives, and nolabels.
+
+ * ocaml_specific.ml: Ditto.
+
+2007-02-03 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Windows cannot use executor.
+
+ * shell.ml: As in command.ml use executor only in non-windows and
+ non-degraded mode.
+ * rule.ml: Update two error messages.
+
+2007-02-02 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some minor things for the ocaml myocamlbuild for instance.
+
+ * configuration.ml,
+ * configuration.mli: Add has_tag.
+ * my_std.ml,
+ * my_std.mli: Add getenv and copy_chan.
+ * ocaml_utils.ml,
+ * ocaml_utils.mli: Move some commands to rule.
+ * ocaml_specific.ml: Improve the menhir switching.
+ * options.ml,
+ * options.mli: Add -use-menhir and -menhir options.
+ * rule.ml,
+ * rule.mli: Add copy_rule and move some commands from ocaml_utils.
+ * signatures.ml: .
+
+2007-02-01 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Move main sigs in signatures.ml and std_signatures.ml.
+
+ * ocamlbuild_pack.mlpack: .
+ * ocamlbuildlib.mllib: .
+ * ocamlbuildlightlib.mllib: .
+ * ocamlbuild.odocl: .
+ * command.mli: .
+ * glob.mli: .
+ * log.mli: .
+ * my_unix_with_unix.ml: .
+ * my_std.ml: .
+ * my_std.mli: .
+ * ocaml_specific.ml: .
+ * pathname.mli: .
+ * std_signatures.ml: New.
+ * signatures.ml: New.
+ * start.sh: .
+ * tags.ml: .
+ * tags.mli: .
+ * test/test5/_tags: .
+ * Makefile: .
+ * _tags: .
+
+2007-02-01 Berke Durak <berke.durak@inria.fr>
+
+ Shell.run doesn't use execute_many in degraded mode.
+
+ * shell.ml: .
+
+2007-02-01 Berke Durak <berke.durak@inria.fr>
+
+ cp, rm -rf and mv-like commands use Executor to better play with display.
+
+ * display.ml: .
+ * my_unix.ml: .
+ * main.ml: .
+ * my_std.ml: .
+ * my_unix.mli: .
+ * shell.ml: .
+ * shell.mli: .
+ * start.sh: .
+ * _tags: .
+
+2007-02-01 Berke Durak <berke.durak@inria.fr>
+
+ Systematizing exit codes.
+
+ * executor.ml: .
+ * main.ml: .
+
+2007-02-01 Berke Durak <berke.durak@inria.fr>
+
+ Added automatic file: tag, changed flag syntax.
+
+ * lexers.mli: .
+ * lexers.mll: .
+ * main.ml: .
+ * ocamldep.ml: .
+ * ocamldep.mli: .
+ * tools.ml: .
+
+2007-01-31 Berke Durak <berke.durak@inria.fr>
+
+ Cleans up links to the _build directory.
+
+ * main.ml: .
+ * options.ml: .
+ * options.mli: .
+ * pathname.ml: .
+ * pathname.mli: .
+
+2007-01-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Restore the link to binary targets functionality.
+
+ * main.ml: Make it separate from target running.
+
+2007-01-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add an hygiene hook pair.
+
+ * ocamlbuild_plugin.ml,
+ * hooks.ml,
+ * hooks.mli,
+ * main.ml: Ditto.
+
+2007-01-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ The Killer feature about a fine grained dependency injection control.
+
+ * rule.ml,
+ * rule.mli: Add build_deps_of_tags and call it automatically before
+ * ocaml_compiler.ml,
+ * ocaml_compiler.mli: Rework tags, to have them when callinng
+ build_deps_of_tags.
+ executing a command.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Move the exception Exit_build_error to main and
+ remove the old dep function.
+ * ocamlbuild_plugin.ml: Export some new functions.
+ * test/test7/myocamlbuild.ml: Add a dep declaration.
+ * test/test7/cool_plugin.ml: New.
+ * test/test7/_tags: New.
+ * test/good-output: Update.
+ * flags.ml,
+ * command.ml,
+ * command.mli: Rename flags_of_tags as tag_handler.
+ * main.ml: Update error handling.
+ * TODO: Done.
+
+2007-01-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix and improve the new link/deps system.
+
+ * ocaml_dependencies.ml,
+ * ocaml_dependencies.mli: Some fixes and improvements.
+ * pathname.ml,
+ * pathname.mli: Add check_extension.
+ * ocaml_compiler.ml,
+ * ocaml_compiler.mli: Add support for hidden_packages and update.
+
+2007-01-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Reverse the last 2 patches, since there is fact no name clash.
+
+2007-01-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Shell -> Oshell second part.
+
+ * ocamlbuild.odocl: Ditto.
+ * test/good-output: Update.
+
+2007-01-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Rename the Shell module as Oshell to avoid a name clash with labltk.
+
+ * shell.ml: Remove.
+ * shell.mli: Remove.
+ * oshell.ml: New.
+ * oshell.mli: New.
+ * ocamlbuild_pack.mlpack,
+ * command.ml,
+ * display.ml,
+ * main.ml,
+ * options.ml,
+ * ppcache.ml,
+ * pathname.ml,
+ * plugin.ml,
+ * resource.ml,
+ * start.sh: Update.
+
+2007-01-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix 2 bugs.
+
+ * test/test9/testglob.ml: More tests.
+ * glob_lexer.mll: Fix "/**".
+ * _tags: Restore my warnings.
+ * executor.ml: Use the unused variable.
+
+2007-01-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Improve dprintf and update.
+
+ * log.ml, log.mli: dprintf now wraps the message between "@[<2>" and "@]@.".
+ * command.ml,
+ * display.ml,
+ * fda.ml,
+ * main.ml,
+ * ocaml_dependencies.ml,
+ * ocaml_compiler.ml,
+ * ocaml_utils.ml,
+ * ocamldep.ml,
+ * pathname.ml,
+ * resource.ml,
+ * rule.ml,
+ * solver.ml: Update the dprintf usage.
+
+2007-01-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add the new dependency linking system (plz test it !).
+
+ * ocamlbuild_pack.mlpack: Add a brand new module.
+ * ocaml_dependencies.ml: New.
+ * ocaml_dependencies.mli: New.
+ * ocaml_compiler.ml,
+ * ocaml_compiler.mli: Use this new module.
+ * resource.ml,
+ * resource.mli: Export a folding function on dependencies.
+ * TODO: Add something to do.
+ * start.sh: .
+ * main.ml: Update.
+
+2007-01-29 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Executor exit codes.
+
+ * executor.ml: Use the standard exit.
+ * main.ml: Some exit codes are reserved for Executor.
+
+2007-01-29 Berke Durak <berke.durak@inria.fr>
+
+ Executor returns finer-grained results.
+
+ * executor.ml: .
+ * manual/manual.tex: .
+
+2007-01-29 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Toward a working command execute feature :).
+
+ * executor.ml,
+ * executor.mli: FIXME.
+ * command.ml,
+ * command.mli: Update to the new signature and merge the degraded mode
+ to avoid duplication.
+ * my_unix.ml,
+ * my_unix.mli,
+ * ocaml_utils.ml,
+ * ocamldep.ml,
+ * plugin.ml,
+ * resource.ml,
+ * rule.ml,
+ * solver.ml,
+ * test/good-output: Update.
+
+2007-01-29 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Revert almost all of the 2 last patches.
+
+ * command.ml: .
+ * command.mli: .
+ * executor.ml: .
+ * executor.mli: .
+ * my_unix.ml: .
+ * my_unix.mli: .
+ * ocaml_utils.ml: .
+ * ocaml_specific.ml: .
+ * ocamldep.ml: .
+ * plugin.ml: .
+ * resource.ml: .
+ * rule.ml: .
+ * solver.ml: .
+
+2007-01-29 Berke Durak <berke.durak@inria.fr>
+
+ Fixing before/after thunks.
+
+ * command.ml: .
+ * command.mli: .
+ * ocaml_utils.ml: .
+ * ocamldep.ml: .
+ * plugin.ml: .
+ * resource.ml: .
+ * rule.ml: .
+ * solver.ml: .
+ * TODO: .
+
+2007-01-29 Berke Durak <berke.durak@inria.fr>
+
+ Adding before and after handlers to Executor.
+
+ * command.ml: .
+ * executor.ml: .
+ * executor.mli: .
+ * my_unix.ml: .
+ * my_unix.mli: .
+ * manual/manual.tex: .
+
+2007-01-29 Berke Durak <berke.durak@inria.fr>
+
+ Fixed multi-dir globbing.
+
+ * glob_lexer.mll: .
+ * manual/manual.tex: .
+
+2007-01-29 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add Rule.custom_rule and cleanup the ocamldep meta rule.
+
+ * ocamldep.ml,
+ * ocamldep.mli: Make it a meta rule (or a rule generator).
+ * rule.ml,
+ * rule.mli: Add custom_rule.
+ * ocaml_specific.ml: Update to Ocamldep.
+ * test/good-output: Minor update.
+
+2007-01-29 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ MakefileS...
+
+ * manual/Makefile: More things to remove (sometimes).
+ * Makefile: Use $(BUILDDIR) instead of _build.
+
+2007-01-26 Berke Durak <berke.durak@inria.fr>
+
+ Documenting glob expressions.
+
+ * glob_lexer.mll: Added negative character classes.
+ * manual/manual.tex: .
+
+2007-01-26 Berke Durak <berke.durak@inria.fr>
+
+ Started documenting glob syntax.
+
+ * manual/manual.tex: .
+
+2007-01-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ One other include dir fix.
+
+ * main.ml: Ditto.
+ * test/test9/testglob.ml: Add a failing test (request for feature).
+ * test/good-output: Update.
+
+2007-01-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Include dirs and Backtrace.
+
+ * main.ml: Fix -I, and restore the backtrace.
+ * report.ml,
+ * report.mli: Fix the backtrace and rename analyze to
+ print_backtrace_analyze.
+
+2007-01-25 Berke Durak <berke.durak@inria.fr>
+
+ Added cross-directory globbing.
+
+ * glob_ast.ml: .
+ * glob.ml: .
+ * glob_ast.mli: .
+ * glob_lexer.mll: .
+ * test/test9/testglob.ml: .
+
+2007-01-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Inlcude dirs trought tags.
+
+ * main.ml: Ditto.
+ * my_unix_with_unix.ml: Imrpove stat errors.
+ * my_std.ml,
+ * my_std.mli: .
+ * pathname.ml: bmla.
+ * slurp.ml,
+ * slurp.mli: Add force, fix bugs.
+
+2007-01-25 Berke Durak <berke.durak@inria.fr>
+
+ Fixed double display of error status.
+
+ * command.ml: .
+ * display.ml: .
+ * display.mli: .
+ * log.ml: .
+ * log.mli: .
+ * main.ml: .
+ * my_std.ml: .
+ * my_std.mli: .
+ * plugin.ml: .
+
+2007-01-25 Berke Durak <berke.durak@inria.fr>
+
+ Stupid bug.
+
+ * log.ml: .
+ * main.ml: .
+ * options.ml: .
+
+2007-01-25 Berke Durak <berke.durak@inria.fr>
+
+ Fixed interface, handling of -- with no argument.
+
+ * ocamlbuild_plugin.mli: Remove.
+ * manual/manual.tex: .
+ * options.ml: .
+
+2007-01-25 Berke Durak <berke.durak@inria.fr>
+
+ Updated start.sh.
+
+ * start.sh: .
+
+2007-01-25 Berke Durak <berke.durak@inria.fr>
+
+ Added .mlis.
+
+ * ocamlbuild_plugin.mli: New.
+ * fda.mli: New.
+ * main.ml: .
+ * ocaml_specific.ml: .
+ * plugin.ml: .
+ * plugin.mli: New.
+
+2007-01-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Cut down ocaml_specific in pieces.
+
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Split.
+ * ocamlbuild_plugin.ml: Update.
+ * ocamlbuild_pack.mlpack: Add new modules.
+ * my_std.ml,
+ * my_std.mli: Add good_outcome.
+ * ocaml_utils.ml: New.
+ * ocaml_tools.ml: New.
+ * ocaml_compiler.ml: New.
+ * ocaml_utils.mli: New.
+ * ocaml_compiler.mli: New.
+ * ocaml_tools.mli: New.
+ * ocamldep.ml: New.
+ * ocamldep.mli: New.
+ * start.sh: Update.
+ * TODO: Move things done.
+
+2007-01-25 Berke Durak <berke.durak@inria.fr>
+
+ Fixer return codes and error message flushing issues.
+
+ * display.ml: .
+ * log.ml: .
+ * log.mli: .
+ * main.ml: .
+ * report.ml: .
+ * report.mli: .
+
+2007-01-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a warning.
+
+ * ocaml_specific.ml: In -debug 1 mode there is a now a warning when
+ ocamlbuild skip a seliently a module, supposing that's an error of
+ ocamldep.
+
+2007-01-24 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ More hooks.
+
+ * ocamlbuild_plugin.ml,
+ * hooks.ml,
+ * hooks.mli,
+ * main.ml: Add {Before,After}_rules.
+
+2007-01-24 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Call these hooks.
+
+ * main.ml: Call these hooks.
+
+2007-01-24 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a first version of dispatch.
+
+ * ocamlbuild_plugin.ml: Export dispatch and the hooks type.
+ * ocamlbuild_pack.mlpack: Add Hooks.
+ * hooks.ml: New.
+ * hooks.mli: New.
+ * ocaml_specific.mli: New line.
+
+2007-01-24 Berke Durak <berke.durak@inria.fr>
+
+ Mini slurp bug.
+
+ * slurp.ml: .
+ * TODO: .
+
+2007-01-24 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix few more things.
+
+ * ocamlbuildlight.ml: .
+ * ocamlbuild_version.ml: Remove.
+ * ocamlbuild.ml: .
+ * ocamlbuild_pack.mlpack: .
+ * main.ml: .
+ * ocaml_specific.ml: .
+ * ocaml_specific.mli: .
+ * start.sh: .
+ * test/test2/toto.ml: .
+ * test/good-output: .
+
+2007-01-24 Berke Durak <berke.durak@inria.fr>
+
+ Read directories before files in Slurp.
+
+ * slurp.ml: .
+ * TODO: .
+
+2007-01-24 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix some bugs.
+
+ * ocamlbuild_version.ml: Remove.
+ * ocamlbuild.ml,
+ * ocamlbuildlight.ml: Main is now in the pack.
+ * ocamlbuild_pack.mlpack: more things.
+ * ocaml_specific.ml: One fix and one comment.
+ * start.sh: Update.
+
+2007-01-24 Berke Durak <berke.durak@inria.fr>
+
+ Splitting ocaml_specific into multiple files.
+
+ * ocamlbuildlight.ml: .
+ * ocamlbuild.ml: .
+ * ocamlbuild_version.ml: New.
+ * ocamlbuild.mli: .
+ * ocamlbuildlight.mli: .
+ * ocamlbuild_pack.mlpack: .
+ * command.ml: .
+ * fda.ml: New.
+ * hygiene.ml: .
+ * main.ml: New.
+ * my_std.ml: .
+ * my_std.mli: .
+ * main.mli: New.
+ * manual/manual.tex: .
+ * ocaml_specific.ml: .
+ * ocaml_specific.mli: .
+ * options.ml: .
+ * options.mli: .
+ * plugin.ml: New.
+ * rule.ml: .
+ * report.ml: .
+ * tools.ml: New.
+ * tools.mli: New.
+ * TODO: .
+ * _tags: .
+
+2007-01-24 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Minor changes.
+
+ * manual/manual.tex: Typo s/the the/the/g.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Add some function to deal with linking of a
+ module list. Add a better lib declaration function.
+ * TODO: Update.
+
+2007-01-17 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ A new pathname operator and a bug fix.
+
+ * pathname.ml,
+ * pathname.mli: add the ( -.- ) operator to add an extension to a
+ pathname.
+ * ocaml_specific.ml: Use that new operator.
+ * resource.ml: Fix a bug.
+
+2007-01-17 Berke Durak <berke.durak@inria.fr>
+
+ More examples.
+
+ * examples/example3/epoch.ml: .
+ * examples/example3/make.sh: New.
+ * manual/manual.tex: .
+ * TODO: .
+
+2007-01-17 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Infered mli's, and bug fixes.
+
+ * my_unix.ml: Fix a bug.
+ * my_std.mli: Doc.
+ * manual/manual.tex: Use \verb.
+ * ocaml_arch.ml: Don't always overide the forpack_flags_of_pathname
+ function reference.
+ * ocaml_arch.mli: Remove the reference.
+ * ocaml_specific.ml: Update for forpack and add infered mli's.
+ * pathname.ml,
+ * pathname.mli: Add is_directory.
+
+2007-01-17 Berke Durak <berke.durak@inria.fr>
+
+ More examples.
+
+ * examples/example3/epoch.ml: New.
+ * examples/example2/hello.ml: .
+ * examples/example2/greet.ml: New.
+ * examples/example3: New.
+ * examples/example2: New.
+ * manual/manual.tex: .
+ * TODO: .
+
+2007-01-17 Berke Durak <berke.durak@inria.fr>
+
+ Started examples.
+
+ * examples/example1/hello.ml: New.
+ * examples/example1: New.
+ * examples: New.
+ * manual/manual.tex: .
+ * .vcs: .
+ * TODO: .
+
+2007-01-17 Berke Durak <berke.durak@inria.fr>
+
+ Wrote limitations and features.
+
+ * manual/manual.tex: .
+
+2007-01-17 Berke Durak <berke.durak@inria.fr>
+
+ Wrote motivations.
+
+ * manual/manual.tex: .
+ * _tags: .
+
+2007-01-17 Berke Durak <berke.durak@inria.fr>
+
+ Started manual.
+
+ * manual/Makefile: New.
+ * manual/manual.tex: New.
+ * manual: New.
+
+2007-01-17 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Bugs, menhir, path variables.
+
+ * display.ml: Fix a bug.
+ * glob.mli: Fix a typo.
+ * lexers.mli,
+ * lexers.mll: Extend ocamldep_output lexer and meta_path lexer.
+ * my_std.ml,
+ * my_std.mli: Add memo and String.rev.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Better rules for C lib linking and menhir rules.
+ * resource.ml,
+ * resource.mli: Handle naively some multiple variables.
+ * rule.ml,
+ * rule.mli: Update.
+ * start.sh: Update.
+
+2007-01-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Integrate dprintf to the display.
+
+ * display.ml,
+ * display.mli: Add dprintf and log_level.
+ * log.ml,
+ * log.mli: Add dprintf and level.
+ * debug.ml: Remove.
+ * debug.mli: Remove.
+ * options.ml: Update.
+ * command.ml, ocaml_specific.ml, my_std.ml,
+ * pathname.ml, ppcache.ml, resource.ml,
+ * rule.ml, report.ml, slurp.ml, solver.ml,
+ * configuration.ml, tags.ml: Update to Log.
+ * ocamlbuild.odocl: Add Log, remove Debug.
+ * ocamlbuild_pack.mlpack: Remove Debug.
+ * bool.ml: Remove the debug dependency.
+
+2007-01-10 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Execute and windows...
+
+ * command.ml: Test windows here.
+ * my_unix_with_unix.ml: Revert a little.
+
+2007-01-10 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Don't use executor on windows.
+
+ * my_unix_with_unix.ml: Since at least set_nonblock does not works on
+ windows.
+
+2007-01-10 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add the -no-log option and fix a log bug.
+
+ * log.mli,
+ * log.ml: Log is now a lazy to have the good setup order.
+ * options.ml: Add the -no-log option.
+
+2007-01-10 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a bug with quoting of the nil string.
+
+ * shell.ml: Quote the nil string.
+
+2007-01-09 Berke Durak <berke.durak@inria.fr>
+
+ Documented the interface of the glob module.
+
+ * glob.mli: .
+
+2007-01-09 Berke Durak <berke.durak@inria.fr>
+
+ Continuing to document interfaces.
+
+ * bool.mli: .
+ * debug.mli: .
+ * discard_printf.mli: .
+ * executor.mli: .
+ * hygiene.mli: .
+ * my_std.mli: .
+ * slurp.mli: .
+ * Makefile: .
+
+2007-01-09 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a bug with directory links to build dir.
+
+ * ocaml_specific.ml,
+ * options.ml,
+ * options.mli: Keep the Slurp.entry instead of a set.
+ * pathname.ml: Clean the entry instead of the set, that more precise.
+ * Makefile: Add doc phonny rules.
+
+2007-01-09 Berke Durak <berke.durak@inria.fr>
+
+ Doc for Configuration.
+
+ * ocamlbuild_plugin.ml: .
+ * bool.mli: .
+ * configuration.ml: .
+ * configuration.mli: .
+ * command.mli: .
+ * doc: New.
+ * glob.ml: .
+ * ocaml_specific.ml: .
+ * Makefile: .
+
+2007-01-09 Berke Durak <berke.durak@inria.fr>
+
+ Started documentation.
+
+ * bool.mli: .
+ * command.ml: .
+ * command.mli: .
+
+2007-01-09 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Export the doc.
+
+ * Makefile: Use a link.
+ * _tags: Don't spend times in that dir.
+
+2007-01-09 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Put the log file in the source dir and not when building plugin.
+
+ * log.ml,
+ * log.mli: Use an optional.
+ * options.ml: Update.
+ * pathname.mli: Export in_source_dir.
+ * .vcs: Add _log.
+
+2007-01-09 Berke Durak <berke.durak@inria.fr>
+
+ Added doc target.
+
+ * report.ml: .
+ * Makefile: .
+ * TODO: .
+
+2007-01-09 Berke Durak <berke.durak@inria.fr>
+
+ Writes tags to log file.
+
+ * display.ml: .
+
+2007-01-09 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add the Log module.
+
+ * ocamlbuild_pack.mlpack: Add Log.
+ * command.ml,
+ * command.mli: Use Log.
+ * log.ml: New.
+ * log.mli: New.
+ * options.ml: Use Log.
+ * start.sh: Update.
+
+2007-01-09 Berke Durak <berke.durak@inria.fr>
+
+ Added -log option.
+
+ * command.ml: .
+ * command.mli: .
+ * display.ml: .
+ * display.mli: .
+ * executor.mli: .
+ * options.ml: .
+ * _tags: .
+
+2007-01-09 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Make usable the ocamldoc support.
+
+ * ocaml_specific.ml: Add rules for ocamldoc.
+ * ocamlbuild.odocl: New.
+ * test/test3/proj.odocl: New.
+ * test/good-output: Update.
+ * test/test3/test.sh: Add a odoc test.
+
+2007-01-09 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some cleanups.
+
+ * ocamlbuild_plugin.ml: Add tag_file that simule one simple line in the
+ _tags file.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Add ln_s, touch, chmod.
+ * pathname.ml,
+ * pathname.mli: Remove map_extension*, split_extension* and compiled
+ files hack skipping.
+ * rule.ml: Improve logging.
+ * solver.ml: Use another level.
+
+2007-01-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a bug with debug rules.
+
+ * ocaml_specific.ml: Move %.cmi from prods to deps.
+ * test/good-output: Update.
+
+2007-01-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add debugging rules.
+ To get a ocamlbuild with debugging info you can
+ call `make debug' that will produce ocamlbuild.d.byte
+ and x.d.cmo files.
+
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Add debugging rules, reorder warnings flag to
+ have 'A' and 'a' before others.
+ * Makefile: Add the debug target.
+ * _tags: Cleanup (remove the debug tag that was set by default).
+
+2007-01-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add profiling support directly in rules.
+ This means that you can now request for building a target such as
+ my_main.p.native or my_lib.p.cmxa, that will create %.p.cmx
+ intermediate files that do not interfer with non-profiling ones.
+
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Add rules and functions for native link and
+ comilation in profiling mode.
+ * Makefile: Add a profile target (require a fixed ocamlopt w.r.t pack).
+ * _tags: Take care also of .p.cmx files.
+ * glob.ml: IS.print is equivalent to print_is.
+ * my_std.ml: Fix a bug.
+
+2007-01-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add some functions...
+
+ * glob.ml: Extract is_suffix and is_prefix.
+ * my_std.ml,
+ * my_std.mli: Add String.{is_suffix,is_prefix,first_chars,last_chars}
+ and List.union.
+ * pathname.ml,
+ * pathname.mli: Add get_extensions, remove_extensions,
+ update_extensions, map_extensions that treat all extensions instead of
+ just the last.
+ * tags.ml,
+ * tags.mli: Add +++ and --- that treat optional tags.
+
+2007-01-06 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Change the default display in degraded mode.
+
+ * command.ml: Ditto.
+
+2007-01-06 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Cleanup Makefile options.
+
+ * Makefile: Ditto.
+
+2007-01-06 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a simple opened files tracer.
+
+ * misc/opentracer.ml: New.
+ Just support ktrace for now. A strace one will be appreciated the
+ interface to follow is quite simple anyway.
+ * misc: New.
+
+2007-01-06 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Handle better commands without Px atom.
+
+ * command.ml: Display the whole command if no Px is found.
+ * display.mli: No longer export these strings.
+
+2007-01-06 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Handle myocamlbuild_config.mli.
+
+ * ocaml_specific.ml: Add support for an interface to the config.
+
+2007-01-06 Berke Durak <berke.durak@inria.fr>
+
+ Improved language of explanations in Report.
+
+ * report.ml: .
+
+2007-01-06 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Factor and fix the plugin building.
+
+ * ocamlbuildlight.mli: New.
+ * executor.ml: Call cleanup, add a fixme.
+ * ocaml_specific.ml: Factor and fix plugin stuffs.
+ * start.sh: Update.
+ * Makefile: Update.
+ * TODO: Update.
+ * _tags: No longer do favors to some modules.
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix plugins.
+
+ * ocamlbuildlib.mllib: Add missing modules.
+ * ocamlbuildlightlib.mllib: New.
+ * Makefile: Update.
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Change the my_unix system.
+
+ * ocamlbuildlight.ml: Just call the main.
+ * ocamlbuild.ml: Setup my_unix_with_unix.
+ * ocamlbuildlib.mllib: Remove executor and exit_codes for the lib.
+ * ocamlbuild_pack.mlpack: Remove my_std and my_unix.
+ * exit_codes.ml: Remove. Put them directly in executor.
+ * executor.ml: Add exitcodes.
+ * my_unix.ml: New. Default implem.
+ * my_unix_with_unix.ml: Extend the default implem.
+ * my_unix_without_unix.ml: Remove.
+ * my_unix.mli: Add the implem type and val.
+ * my_unix_with_unix.mli: New.
+ * ocaml_specific.ml,
+ * pathname.ml,
+ * slurp.ml,
+ * Makefile,
+ * command.ml,
+ * _tags: Update.
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Don't use executor for the myocamlbuild call.
+
+ * ocaml_specific.ml: Use sys_command directly.
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a stupid bug.
+
+ * command.ml: That cause to have reversed sequences.
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some libs and ocamldoc changes.
+
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Improve ocaml_lib_flag, add fews libs.
+ Fix ocamldoc support update tags, and use Px only once.
+
+2007-01-05 Berke Durak <berke.durak@inria.fr>
+
+ Started ocamldoc support.
+
+ * ocaml_specific.ml: .
+ * options.ml: .
+ * options.mli: .
+
+2007-01-05 Berke Durak <berke.durak@inria.fr>
+
+ Pretend option didn't work.
+
+ * command.ml: .
+
+2007-01-05 Berke Durak <berke.durak@inria.fr>
+
+ TODO + typo.
+
+ * options.ml: .
+ * TODO: .
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Really call executor all time.
+
+ * command.ml,
+ * command.mli: Remove normalization.
+ And execute_many, it's now execute that do all the job.
+ In degraded mode it's execute_degraded.
+ * my_unix_without_unix.ml: Update.
+ * ocaml_specific.ml,
+ * resource.ml,
+ * rule.ml,
+ * solver.ml: Update to Command.execute type.
+
+2007-01-05 Berke Durak <berke.durak@inria.fr>
+
+ Isatty detection logic.
+
+ * command.ml: .
+ * executor.ml: .
+ * my_unix_with_unix.ml: .
+ * my_unix_without_unix.ml: .
+ * my_unix.mli: .
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Always call executor.
+
+ * command.ml: Unless in degraded mode.
+
+2007-01-05 Berke Durak <berke.durak@inria.fr>
+
+ Removed debugging output, added period argument for ticker.
+
+ * display.ml: .
+ * executor.ml: .
+ * executor.mli: .
+ * my_unix.mli: .
+
+2007-01-05 Berke Durak <berke.durak@inria.fr>
+
+ Somewhat slow but executor seems to work.
+
+ * executor.ml: .
+
+2007-01-05 Berke Durak <berke.durak@inria.fr>
+
+ Added an Exit_codes module. Fixing Executor...
+
+ * ocamlbuild.ml: .
+ * ocamlbuildlib.mllib: .
+ * executor.ml: .
+ * exit_codes.ml: New.
+ * solver.ml: .
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the max_jobs argument passing.
+
+ * command.ml: Use an optional argument.
+
+2007-01-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Subway changes...
+
+ * my_unix_without_unix.ml,
+ * my_unix_with_unix.ml,
+ * my_unix.mli,
+ * command.ml: Call the new execute_many.
+ * executor.ml,
+ * executor.mli: Handle command sequences.
+
+2007-01-04 Berke Durak <berke.durak@inria.fr>
+
+ Added Display.update.
+
+ * display.ml: .
+ * display.mli: .
+ * executor.ml: .
+
+2007-01-04 Berke Durak <berke.durak@inria.fr>
+
+ Added display function, indentation, language.
+
+ * display.ml: .
+ * display.mli: .
+ * hygiene.ml: .
+
+2007-01-04 Berke Durak <berke.durak@inria.fr>
+
+ Fixing interface of Executor.
+
+ * executor.ml: .
+ * executor.mli: .
+ * my_unix_with_unix.ml: .
+
+2007-01-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add attributes to entries. Add the -byte-plugin option.
+
+ * slurp.ml,
+ * slurp.mli: Add an attribute field, add map, rename fold_pathnames to
+ fold and filter_on_names to filter.
+ * hygiene.ml,
+ * hygiene.mli: Perform hygiene only on entries with a true attribute.
+ * options.ml,
+ * options.mli: Add the native_plugin reference and the -byte-plugin
+ option.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Exclude files tagged not_hygienic or precious
+ from hygiene.
+
+2007-01-04 Berke Durak <berke.durak@inria.fr>
+
+ Fixed pack issues.
+
+ * ocamlbuild.ml: .
+ * executor.ml: .
+ * executor.mli: New.
+ * _tags: .
+
+2007-01-04 Berke Durak <berke.durak@inria.fr>
+
+ Started executor module.
+
+ * executor.ml: New.
+ * hygiene.ml: .
+ * my_unix_with_unix.ml: .
+
+2007-01-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add virtual commands.
+
+ * command.ml,
+ * command.mli: Add the V constructor for virtual commands that
+ will query a virtual command solver to use the best implementation
+ of that virtual command.
+
+2007-01-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Mainly, prepare for parallel display.
+
+ * ocamlbuild_plugin.ml: Export file_rule.
+ * command.ml,
+ * command.mli: Some cleanup and preparation.
+ * lexers.mll: Remove the dirty hack.
+ * my_std.ml,
+ * my_std.mli: Move search_in_path to Command and add ( @:= ).
+ * my_unix_with_unix.ml,
+ * my_unix_without_unix.ml,
+ * my_unix.mli: Change the execute_many_using_fork type.
+ * ocaml_specific.ml: Use the nopervasives tag for
+ pervasives dependencies.
+ * start.sh: Update.
+ * test/test8/myocamlbuild.ml: Update.
+ * test/good-output: Update.
+ * Makefile: Update.
+
+2007-01-03 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ I don't like microbes.
+
+ * hygiene.ml: Reverse the bool.
+
+2007-01-03 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the stat problem.
+
+ * ocaml_specific.ml: Use the filtered entry for source_dir_path_set.
+
+2007-01-03 Berke Durak <berke.durak@inria.fr>
+
+ Hygiene filters cleaned out microbes.
+
+ * hygiene.ml: .
+ * hygiene.mli: .
+ * ocaml_specific.ml: .
+ * ocaml_specific.mli: .
+ * slurp.ml: .
+ * slurp.mli: .
+
+2007-01-03 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Filename concat cleanup.
+
+ * my_std.ml,
+ * my_std.mli: Add filename_concat.
+ * glob.ml,
+ * hygiene.ml,
+ * lexers.mll,
+ * pathname.ml,
+ * resource.ml,
+ * report.ml,
+ * solver.ml,
+ * slurp.ml,
+ * solver.mli:
+ Use filename_concat.
+ * flags.ml: FIXME.
+
+2007-01-03 Berke Durak <berke.durak@inria.fr>
+
+ Revert to old.
+
+ * slurp.ml: .
+
+2007-01-03 Berke Durak <berke.durak@inria.fr>
+
+ Debugging tags for myocamlbuild.ml.
+
+ * ocaml_specific.ml: .
+ * slurp.ml: .
+
+2007-01-02 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Another atempt to fix the slurp bug and lazy.
+
+ * slurp.ml: Ditto.
+
+2007-01-02 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix slurp w.r.t lazyness: keep the cwd.
+
+ * slurp.ml: Ditto.
+
+2007-01-02 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ My_unix, slurp in degraded mode, _tags in subdirs, fix the bug with -j...
+
+ * ocamlbuild_version.mli: Remove.
+ * ocamlbuild_where.mli: New.
+ * display.mli: New.
+ * shell.ml: New.
+ * shell.mli: New.
+ * glob.ml,
+ * glob.mli,
+ * configuration.ml,
+ * lexers.mli,
+ * lexers.mll,
+ * configuration.mli: Honor _tags files in subdirs.
+ * my_unix_with_unix.ml,
+ * command.ml,
+ * command.mli,
+ * resource.ml,
+ * resource.mli,
+ * solver.ml: Fix the bug with the -j option.
+ * slurp.ml,
+ * slurp.mli: New degraded mode using the find command.
+ Use lazy values to avoid computing useless directories.
+ * options.ml,
+ * options.mli: Update -version and -where.
+ * pathname.ml,
+ * pathname.mli: Remove the init section.
+ * rule.ml,
+ * rule.mli: Add file_rule useful for rules that don't run a command but
+ just write a file.
+ * ocaml_specific.ml: Fix some plugin bugs. Remove -I to ocamldep.
+ Handle msvc .obj,.lib instead of .o,.a.
+ * my_unix_without_unix.ml: Make works link stuffs running the readlink
+ command.
+ * display.ml,
+ * hygiene.ml,
+ * my_std.ml,
+ * my_unix.mli,
+ * my_std.mli,
+ * start.sh,
+ * test/test5/test.sh,
+ * test/good-output,
+ * test/test6/test.sh,
+ * test/test7/test.sh,
+ * test/test4/test.sh,
+ * test/test8/test.sh,
+ * test/test3/test.sh,
+ * test/test2/test.sh,
+ * Makefile,
+ * _tags,
+ * ocamlbuild_pack.mlpack: Update.
+
+2007-01-02 Berke Durak <berke.durak@inria.fr>
+
+ Fixed ticker.
+
+ * display.ml: .
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Cosmetic.
+
+ * command.ml: .
+ * display.ml: .
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Computing display length.
+
+ * display.ml: .
+
+2006-12-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add -classic-display.
+
+ * command.ml,
+ * command.mli: Provide a way to use the classic display.
+ * options.ml: Add the -classic-display option.
+ * Makefile: Remove ppcache form the default.
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Finish display only once ; display number of jobs cached.
+
+ * command.ml: .
+ * display.ml: .
+
+2006-12-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Oops fix a bug.
+
+ * command.ml: Add begin .. end.
+
+2006-12-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some display fixes.
+
+ * command.ml: Select the display mode and remove the assert false.
+ * display.ml: Change the print function to have a more compact one.
+ * start.sh: Update.
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Error support in Display.finish.
+
+ * display.ml: .
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Support for cache.
+
+ * display.ml: .
+
+2006-12-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Integrate display mode.
+
+ * ocamlbuild_pack.mlpack: Add display.
+ * command.mli: Add Px to indicate to highligth this pathname.
+ * command.ml: Support Px and call Display.
+ * display.ml: Fix minor bugs.
+ * ocaml_specific.ml: Declare some Px, and quiet ocamlyacc, ocamllex.
+ * options.ml: Add quiet to default tags.
+ * ppcache.ml: Detect more accuratly ocamlrun.
+ * pathname.ml: Improve concat.
+ * _tags: No profile.
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Added pretend.
+
+ * display.ml: .
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Added ticker.
+
+ * display.ml: .
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Display module.
+
+ * display.ml: .
+ * my_unix_with_unix.ml: .
+ * my_unix_without_unix.ml: .
+ * my_unix.mli: .
+ * test/test10/test.sh: New.
+ * test/test10: New.
+ * test/test10/dbdi: New.
+
+2006-12-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use a better init order, and fix a Filename.concat usage.
+
+ * ocaml_specific.ml: The plugin should act before any initialization.
+ * ocaml_arch.ml: Use Pathname.(/).
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Started user-friendly display module.
+
+ * display.ml: New.
+
+2006-12-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix init order.
+
+ * ocaml_specific.ml: Config must be available for plugin building.
+
+2006-12-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some fixes.
+
+ * command.ml: Quote if needed.
+ * my_std.mli: Comment String.contains_string.
+ * resource.ml: Remove a useless separator.
+ * test/good-output: Update.
+
+2006-12-21 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Plugin config file and profile mode.
+
+ * ocaml_specific.ml: Fix a bug due to the lazyness of &&.
+ * ocaml_specific.mli: Move some functions.
+
+2006-12-21 Berke Durak <berke.durak@inria.fr>
+
+ Now compiles patterns for fast matching. Removed regexp support.
+
+ * glob_ast.ml: .
+ * glob.ml: .
+ * glob_lexer.mli: .
+ * glob_ast.mli: .
+ * glob_lexer.mll: .
+ * test/test9/testglob.ml: .
+ * test/test9/dbgl: New.
+
+2006-12-20 Berke Durak <berke.durak@inria.fr>
+
+ Pattern matching seems to start to work.
+
+ * glob.ml: .
+
+2006-12-20 Berke Durak <berke.durak@inria.fr>
+
+ Started faster pattern matching code.
+
+ * ocaml_specific.ml: .
+ * _tags: .
+
+2006-12-20 Berke Durak <berke.durak@inria.fr>
+
+ myocamlbuild is rebuilt only as needed.
+
+ * hygiene.ml: .
+ * ocaml_specific.ml: .
+ * pathname.ml: .
+ * pathname.mli: .
+ * resource.ml: .
+
+2006-12-20 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some changes mainly for windows support.
+
+ * command.ml,
+ * command.mli: Add the Quote constructor to help quoting building in
+ commands.
+ * my_unix_with_unix.ml,
+ * my_unix_without_unix.ml,
+ * glob.ml: Commented reslash mode.
+ * my_std.ml,
+ * my_std.mli: Some new functions.
+ * my_unix.mli: Export sys_command.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Update and windows support.
+ * options.ml,
+ * options.mli: Remove the ocamlmklib option.
+ * ppcache.ml: Fix a bug.
+ * pathname.ml: Add more dirseps. Use a custom Filename.concat (for now).
+ * resource.ml,
+ * rule.ml,
+ * Makefile,
+ * _tags: Update.
+
+2006-12-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Update start order.
+
+ * start.sh: Ditto.
+
+2006-12-11 Berke Durak <berke.durak@inria.fr>
+
+ Added -custom, fixed paths for installation.
+
+ * ocaml_specific.ml: .
+ * Makefile: .
+
+2006-12-11 Berke Durak <berke.durak@inria.fr>
+
+ Typo.
+
+ * report.ml: .
+
+2006-12-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a basic ocamlmklib support.
+
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Use ocamlmklib to make libraries if enabled.
+ * options.ml,
+ * options.mli: Add -ocamlmklib and -use-ocamlmklib.
+
+2006-12-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Export more references of options.
+
+ * command.ml,
+ * command.mli: Add ?quiet to execute.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Update to options.
+ * options.ml,
+ * options.mli: Move ocamlc, ocamlopt... to references on command specs.
+ * solver.ml: Update.
+ * Makefile: Use _ocamldistr to avoid hygiene.
+ * .vcs: Use _ocamldistr.
+
+2006-12-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ OCaml distrib stuffs.
+
+ * command.ml,
+ * command.mli: Add a normalization callback.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Add a more complete interface.
+ * options.ml,
+ * options.mli: Add nostdlib.
+ * pathname.ml: Add mkdir -p to import in build.
+ * rule.ml,
+ * rule.mli: Call normalization of commands for digest.
+ * report.ml: Add ignore.
+ * start.sh: Add report.ml*.
+ * Makefile: Add distrib exportation (make a link).
+ * .vcs: Unmask ocamldistrib link.
+
+2006-12-07 Berke Durak <berke.durak@inria.fr>
+
+ Added TODO item.
+
+ * .vcs: .
+ * TODO: .
+
+2006-12-07 Berke Durak <berke.durak@inria.fr>
+
+ Added TODO file.
+
+ * TODO: New.
+
+2006-12-07 Berke Durak <berke.durak@inria.fr>
+
+ Very rudimentary report analysis.
+
+ * report.ml: .
+ * _tags: .
+
+2006-12-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Update tests to run ocamlbuild correctly.
+
+ * test/test2/test.sh,
+ * test/test3/test.sh,
+ * test/test4/test.sh,
+ * test/test5/test.sh,
+ * test/test6/test.sh,
+ * test/test7/test.sh,
+ * test/test8/test.sh,
+ * test/test9/test.sh: Ditto.
+ * test/good-output: Update.
+
+2006-12-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Make test9 independant.
+
+ * test/test9/test.sh: Ditto.
+
+2006-12-07 Berke Durak <berke.durak@inria.fr>
+
+ Rewrote globbing engine, adding {,} ; moved reporting functions to Report.
+
+ * ocamlbuild_pack.mlpack: .
+ * command.ml: .
+ * glob_ast.ml: .
+ * glob.ml: .
+ * glob_ast.mli: .
+ * glob_lexer.mll: .
+ * ocaml_specific.ml: .
+ * report.ml: New.
+ * report.mli: New.
+ * solver.ml: .
+ * solver.mli: .
+ * start.sh: .
+ * test/test9/testglob.ml: .
+ * test/test9/test.sh: .
+ * test/test3/test.sh: .
+ * _tags: .
+
+2006-12-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Degraded mode...
+
+ * ocamlbuildlight.ml: New.
+ * ocamlbuild_pack.mlpack: Include new modules.
+ * bool.ml: Fake dependency.
+ * configuration.ml: Adapt to the glob parser.
+ * command.ml: Export the fork usage.
+ * glob.ml: Use Str through My_unix.
+ * glob_lexer.mli: New.
+ * glob_lexer.mll: Add slashs to valid character patterns.
+ * lexers.mli,
+ * lexers.mll: Use the glob parser.
+ * my_std.ml: Use My_unix.
+ * my_unix_with_unix.ml: New.
+ * my_unix_without_unix.ml: New.
+ * my_unix.mli: New.
+ * my_std.mli: Add search_in_path and change lazy force to ( !* ).
+ * ocaml_specific.ml: Some updates.
+ * options.ml,
+ * options.mli: Add -ocamlrun.
+ * pathname.ml: Adapt to an optional slurp.
+ * ppcache.ml: Use search_in_path of my_std.
+ * resource.ml: Update to ( !* ).
+ * solver.ml: Export Unix errors reporting.
+ * slurp.ml,
+ * slurp.mli: Use My_unix.
+ * start.sh: Update.
+ * test/test9/testglob.ml: Test a constant.
+ * test/test5/_tags,
+ * test/test3/_tags,
+ * test/test4/_tags: Don't use regexp.
+ * test/good-output: Add test9.
+ * test/test9/test.sh: Remove the parent usage.
+ * Makefile: Add the light mode.
+ * .vcs: Update.
+ * _tags: Update.
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Extra tests for globbing.
+
+ * test/test9/testglob.ml: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ First draft of pattern matching.
+
+ * glob_ast.ml: .
+ * glob.ml: .
+ * glob_ast.mli: .
+ * glob_lexer.mll: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ More hard-wired but common cases for globbing.
+
+ * glob.ml: .
+ * test/test9/testglob.ml: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Hidden interface in globber.
+
+ * glob.mli: .
+ * test/test9/testglob.ml: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Basic globbing works.
+
+ * glob.ml: .
+ * glob.mli: .
+ * test/test9/testglob.ml: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Improved interface.
+
+ * glob.ml: .
+ * glob_ast.ml: New.
+ * glob_ast.mli: New.
+ * glob.mli: New.
+ * glob_lexer.mll: .
+ * test/test9/testglob.ml: .
+ * _tags: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Added test9.
+
+ * test/test9/testglob.ml: New.
+ * test/test9/parent: New.
+ * test/runtest.sh: .
+ * test/test9: New.
+ * test/test9/test.sh: New.
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Parser seems to work.
+
+ * glob.ml: .
+ * glob_lexer.mll: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Removed eof_char.
+
+ * glob.ml: .
+ * glob_lexer.mll: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Interface seems to be OK.
+
+ * glob.ml: .
+ * glob_lexer.mll: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Adding files for the globbing module.
+
+ * bool.ml: New.
+ * bool.mli: New.
+ * glob.ml: New.
+ * glob_lexer.mll: New.
+ * _tags: .
+
+2006-12-06 Berke Durak <berke.durak@inria.fr>
+
+ Replaced numeric escapes.
+
+ * lexers.mll: .
+
+2006-12-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Remove most of the Str usage by using ocamllex.
+
+ * ocamlbuild_pack.mlpack: Remove Re, add Lexers.
+ * configuration.ml: Use Lexers.
+ * command.ml: Don't use Re.
+ * lexers.mli: New.
+ * lexers.mll: New.
+ * my_std.ml,
+ * my_std.mli: Add String.before and String.after.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Use Lexers but also provide tags for warnings.
+ * resource.ml,
+ * rule.ml,
+ * options.ml,
+ * ppcache.ml,
+ * pathname.ml: Use Lexers.
+ * re.ml: Remove.
+ * re.mli: Remove.
+ * start.sh: Update.
+ * Makefile: Igonre _build... and gives -ml to ocamllex.
+ * _tags: Warnings for lexers.
+
+2006-12-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use Sys instead of Unix for readdir.
+
+ * my_std.ml,
+ * my_std.mli: Supress a Unix usage.
+
+2006-12-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add an option to disable the link creation.
+
+ * ocaml_specific.ml: Honor this option.
+ * options.ml: Declare it.
+ * options.mli: Define it.
+
+2006-12-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Don't import compiled files...
+
+ * pathname.ml: For the OCaml compilation itself I need to exclude some
+ dirs that contains compiled files but I want to use some of them with
+ ocamlbuild.
+
+2006-12-05 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Support flags for ocamlyacc and ocamllex.
+
+ * ocaml_specific.ml,
+ * options.ml,
+ * options.mli: Add these options.
+
+2006-12-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Two fixes (hygiene and libraries)...
+
+ * hygiene.ml: Exit 0 if sterilize removes some files (since source
+ files are cached in a rather persistent data structure I prefer let the
+ user start on a fresh setup).
+ * ocaml_specific.ml: Use the dirname if there is no directory named by
+ removing the extension.
+
+2006-12-04 Berke Durak <berke.durak@inria.fr>
+
+ Small bug in hygiene.
+
+ * hygiene.ml: .
+
+2006-12-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add postition specifications to rules.
+
+ * rule.ml,
+ * rule.mli: Add a way to specifie where to put a new rule
+ (top,bottom,before another,after another).
+ * flags.ml: Reorder.
+ * my_std.ml,
+ * my_std.mli: Add mv, fix an error handling.
+ * ocaml_specific.ml: Better error message for circular dependencies.
+ * ppcache.ml: Handle errors better.
+
+2006-11-29 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a working multiple job support.
+
+ * command.ml,
+ * command.mli: Add different versions of execute_many including a
+ version that use forks.
+ * options.ml,
+ * options.mli: Restore the -j option.
+ * solver.ml: Call Command.execute_many.
+ * test/runtest.sh: Pass $@ to sub tests.
+ * test/good-output: Update.
+
+2006-11-28 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the link order.
+
+ * start.sh: Fix the link order.
+
+2006-11-28 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ One step toward multiple jobs: Add the support for suspended building.
+
+ * resource.ml,
+ * resource.mli: Add the notion of suspended building.
+ This represent a resource that is fully ready for evaluation, it's just
+ a command and a function to apply after.
+ * rule.ml: Do not really execute rules that can be safely suspended.
+ * solver.ml: Play with suspended rules to collect as many as possible
+ to get closer to a pararllel execution.
+
+2006-11-27 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the makefile.
+
+ * Makefile: Fix deps.
+
+2006-11-27 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Activates more warnings, and prepare the -j feature.
+
+ * hygiene.ml: Consolidates fragile patterns.
+ * my_std.ml: Likewise.
+ * ocaml_specific.ml: Mainly update to the new builder prototype.
+ * pathname.ml,
+ * pathname.mli: Kick a useless parameter.
+ * resource.ml: Remove dead code and update.
+ * rule.ml,
+ * rule.mli: The bulider now takes a list of resource lists, it will
+ try to make in parallel the first level of commands.
+ * solver.ml: Update to builder without parallelism.
+ * test/good-output: Update.
+ * Makefile: Warnings are now set to -w A -warn-error A.
+
+2006-11-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix packages... again.
+
+ * ocaml_specific.ml: Ditto.
+
+2006-11-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix packages.
+
+ * ocaml_specific.ml: Try to handle better packages during link.
+ * Makefile: Add the try_bootstrap rule.
+
+2006-11-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add -tag, -tags to options.
+
+ * ocaml_specific.ml: Append default tags from options.
+ * options.ml,
+ * options.mli: Add -tag and -tags.
+ * tags.mli: Indent.
+
+2006-11-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix a bug and update tests.
+
+ * resource.ml: Use Hashtbl.replace of course instead of Hashtbl.add to
+ avoid a nasty bug.
+ * test/test7/test.sh,
+ * test/test8/test.sh,
+ * test/test2/test.sh,
+ * test/test6/test.sh,
+ * test/test4/test.sh,
+ * test/test5/test.sh,
+ * test/test3/test.sh: Extract program options to be sure that
+ the -nothing-should-be-rebuilt option is before the -- one.
+ * test/good-output: Update.
+
+2006-11-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use a hashtbl for digests.
+
+ * resource.ml: Ditto.
+ * ocaml_specific.ml: Remove dead code.
+
+2006-11-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use lists instead of sets for rule deps & prods.
+
+ * ocaml_specific.ml: Move the mli dep first.
+ * resource.ml,
+ * resource.mli: No more provide digest_resources but digest_resource.
+ * rule.ml,
+ * rule.mli: Use list instead of sets for deps and prods, since they are
+ not heavily updated and the order matter.
+ * solver.ml: Adapt.
+ * test/good-output: Yeah!
+
+2006-11-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ One more fix for libraries.
+
+ * ocaml_specific.ml: Improve the link_exception handling.
+ * test/good-output: Update.
+
+2006-11-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the library linking.
+
+ * ocaml_specific.ml: The test7 is specially made to check that feature.
+
+2006-11-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Remove list_set.
+
+ * ocamlbuild_pack.mlpack: Remove list_set
+ * list_set.ml: Remove.
+ * list_set.mli: Remove.
+ * start.sh: Remove list_set.
+ * test/good-output: Regen.
+
+2006-11-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the C rule when dirname = '.'.
+
+ * ocaml_specific.ml: Don't move the output when it's useless.
+
+2006-11-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Ignore ocamlbuild_version.ml.
+
+2006-11-25 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ New transitive closure.
+
+ * ocamlbuild_version.ml: Remove.
+ * my_std.ml,
+ * my_std.mli: Add a debug mode for digests and run_and_read.
+ * ocaml_specific.ml: New transitive closure.
+ * pathname.ml,
+ * pathname.mli: Export also parent_dir_name and fix same_contents.
+ * resource.ml,
+ * resource.mli: Add dependencies.
+ * rule.ml: Adapt.
+ * test/good-output: Regen.
+ * Makefile: Improve install.
+ * .vcs: Ignore other _build dirs.
+
+2006-11-20 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Rule definition shortcut and C files.
+
+ * rule.ml,
+ * rule.mli: Allow to pass ~prod and ~dep when there is just one file.
+ * ocaml_specific.ml: Add a rule for C files and use the previous
+ shortcut.
+
+2006-11-18 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ No more extend Format.
+
+ * command.ml,
+ * my_std.ml,
+ * my_std.mli: Put directly ksbprintf and sbprintf in My_std.
+
+2006-11-18 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Clean up and consistent use of Pathname instead of Filename.
+
+ * command.ml,
+ * my_std.ml,
+ * my_std.mli,
+ * ocaml_specific.ml,
+ * pathname.ml,
+ * ppcache.ml,
+ * pathname.mli,
+ * resource.ml: That's it.
+
+2006-11-18 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Restore List_set.
+
+ * ocamlbuild_pack.mlpack,
+ * list_set.ml,
+ * list_set.mli,
+ * resource.ml,
+ * start.sh: Ditto.
+
+2006-11-18 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Remove List_set and List_map.
+
+ * ocamlbuild_pack.mlpack: No more in the pack.
+ * list_set.ml: Remove.
+ * list_map.ml: Remove.
+ * list_map.mli: Remove.
+ * list_set.mli: Remove.
+ * resource.ml: Use a Set.
+ * start.sh: Adapt.
+
+2006-11-18 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Huge speed up, worth updating.
+
+ * resource.ml,
+ * resource.mli: Use a hash instead of map, remove the percent type.
+ * rule.ml,
+ * rule.mli: Remove the function for rule names. Use an exception to
+ choose matching rules.
+
+2006-11-18 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Speedup rule calling.
+
+ * rule.ml,
+ * rule.mli: No more call the code rule twice to compute the digest.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Adapt to Rule.
+ * test/test8/myocamlbuild.ml: Use the exception.
+ * test/good-output: Update.
+ * boot: Update svn:ignore.
+
+2006-11-16 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Remove phony resources and include dependencies.
+
+ * ocaml_specific.ml,
+ * options.ml,
+ * options.mli,
+ * pathname.ml,
+ * pathname.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml,
+ * rule.mli,
+ * solver.ml,
+ * test/test8/myocamlbuild.ml: Simplify a lot the code.
+
+2006-11-16 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some improvements...
+
+ * ocamlbuild.ml: .
+ * ocamlbuild_version.ml: New.
+ * ocamlbuild_plugin.ml: New.
+ * ocamlbuild_version.mli: New.
+ * ocamlbuildlib.mllib: .
+ * ocamlbuild.sh: Remove.
+ * ocamlbuild_pack.mlpack: New.
+ * boot: .
+ * ocaml_specific.ml: .
+ * ocaml_specific.mli: .
+ * options.ml: .
+ * options.mli: .
+ * rule.ml: .
+ * rule.mli: .
+ * start.sh: .
+ * test/test8/a.ml: New.
+ * test/test7/a2.ml: .
+ * test/test7/a3.ml: New.
+ * test/test8/myocamlbuild.ml: New.
+ * test/test7/myocamlbuild.ml: New.
+ * test/test8: New.
+ * test/test8/test.sh: New.
+ * test/runtest.sh: .
+ * test/test7/test.sh: .
+ * test/good-output: .
+ * Makefile: .
+ * _tags: .
+
+2006-11-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add support for libraries.
+
+ * ocamlbuildlib.ml: Remove.
+ * ocamlbuildlib.mllib: New.
+ * ocaml_specific.ml: Rules and actions for libraries.
+ * rule.ml: Improve explanations.
+ * start.sh: Don't make ocamlbuildlib.
+ * test/test7/a.mli: New.
+ * test/runtest.sh: Add test7.
+ * test/test7/test.sh: Add reverts for a.ml.
+ * test/good-output: Update.
+ * Makefile: Remove junk lines.
+
+2006-11-14 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a tests for libraries.
+
+ * test/test7/e.ml: New.
+ * test/test7/d.ml: New.
+ * test/test7/a.ml: New.
+ * test/test7/b.ml: New.
+ * test/test7/a2.ml: New.
+ * test/test7/c.ml: New.
+ * test/test7/test.sh: New.
+ * test/test7/ablib.mllib: New.
+ * test/test7: New.
+
+2006-11-14 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Simplify dependency rules.
+
+ * ocaml_specific.ml: No more use bytelinkdeps...
+ * rule.ml,
+ * rule.mli: Add a dyndeps set.
+ * ocamlbuild.sh,
+ * pathname.ml,
+ * Makefile: Update.
+
+2006-11-14 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Update tests...
+
+ * test/test2/vivi3.ml: .
+ * test/good-output: .
+
+2006-11-10 Berke Durak <berke.durak@inria.fr>
+
+ Added -sterilize option.
+
+ * hygiene.ml: ditto
+ * hygiene.mli: ditto
+ * ocaml_specific.ml: ditto
+ * options.ml: ditto
+ * options.mli: ditto
+
+2006-11-10 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ View the context dir in first.
+
+ * pathname.ml: Ditto.
+
+2006-11-10 Berke Durak <berke.durak@inria.fr>
+
+ Added thread and profile tags.
+
+ * ocaml_specific.ml: ditto.
+
+2006-11-10 Berke Durak <berke.durak@inria.fr>
+
+ Added law for leftover dependency files.
+
+ * ocaml_specific.ml: ditto.
+
+2006-11-10 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Reverse the ignore_auto default value.
+
+ * options.ml: Add -no-skip, remove -ignore-auto, add -Is and -Xs.
+ * test/test2/test.sh,
+ * test/test5/test.sh,
+ * test/test6/test.sh,
+ * test/test4/test.sh,
+ * test/test3/test.sh,
+ * Makefile: Revert flags.
+
+2006-11-10 Berke Durak <berke.durak@inria.fr>
+
+ Added install target to Makefile.
+
+ * Makefile: .
+
+2006-11-10 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Deal with for-pack flags...
+
+ * ocaml_arch.ml: Define a hook.
+ * ocaml_arch.mli: Declare it.
+ * ocaml_specific.ml: Use it.
+ * test/test6: Ignore main.byte.
+
+2006-11-09 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix start.sh and remove dead code.
+
+ * ocaml_specific.ml: Remove dead code about ignore_auto.
+ * start.sh: Swap two modules.
+ * test/test6/main.byte: Remove.
+
+2006-11-09 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Pack now works great...
+
+ * ocamlbuild.sh: Use ocamlopt.
+ * command.ml: Reset filesys cache.
+ * my_std.ml,
+ * my_std.mli: Add a filesys cache for
+ case sensitive file_exists and digest over files.
+ * ocaml_specific.ml: Work on link and packs.
+ * ppcache.ml: Exit 2 is for unix.
+ * pathname.ml,
+ * resource.ml,
+ * rule.ml,
+ * rule.mli,
+ * slurp.ml,
+ * solver.ml,
+ * solver.mli,
+ * test/test5: Update.
+
+2006-11-07 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Too lazy to fill this up :).
+
+ * ocamlbuild.sh,
+ * configuration.ml,
+ * command.ml,
+ * debug.ml,
+ * debug.mli,
+ * my_std.ml,
+ * my_std.mli,
+ * ocaml_specific.ml,
+ * ocaml_specific.mli,
+ * options.ml,
+ * options.mli,
+ * pathname.ml,
+ * ppcache.ml,ew.
+ * ppcache.mli,ew.
+ * pathname.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml,
+ * rule.mli,
+ * slurp.ml,
+ * solver.ml,
+ * solver.mli,
+ * slurp.mli,
+ * start.sh,
+ * tags.ml,
+ * test/test5/test.sh,
+ * test/test4/test.sh,
+ * test/test3/test.sh,
+ * test/good-output,
+ * test/test2/test.sh,
+ * test/test6/test.sh,
+ * Makefile,
+ * _tags: This too.
+
+2006-11-04 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some pack,dirs stuffs.
+
+ * ocamlbuild.ml,
+ * ocamlbuildlib.ml,ew.
+ * ocamlbuild.sh,ew.
+ * configuration.ml,
+ * my_std.ml,
+ * my_std.mli,
+ * ocaml_arch.ml,ew.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli,
+ * ocaml_arch.mli,ew.
+ * options.ml,
+ * options.mli,
+ * pathname.ml,
+ * pathname.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml,
+ * solver.ml,
+ * test/good-output,
+ * Makefile,
+ * _tags: That's it.
+
+2006-10-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Remove the dirty thing about cmi's.
+
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Moves of files are no more needed.
+ * test/good-output: Update.
+
+2006-10-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Some renaming and cleanup...
+
+ * ocamlbuild.ml,
+ * configuration.ml,
+ * configuration.mli,
+ * list_set.ml,
+ * ocaml_specific.ml,
+ * resource.ml,
+ * test/good-output,
+ * test/test6/test.sh: Do that.
+
+2006-10-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use the nothing-should-be-rebuilt for tests and update the output.
+
+ * test/test2,
+ * test/test2/test.sh,
+ * test/test3/test.sh,
+ * test/test4/test.sh,
+ * test/test5/test.sh,
+ * test/test6/test.sh,
+ * test/good-output: Do that.
+
+2006-10-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a mode usefull for tests.
+
+ * options.ml, options.mli, rule.ml:
+ This new mode fails when something needs to be rebuilt.
+
+2006-10-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Improve the ocaml rule set.
+
+ * ocaml_specific.ml: Yipee!
+
+2006-10-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add scripts to run tests.
+
+ * test/test2/vivi1.ml: New.
+ * test/test2/vivi2.ml: New.
+ * test/test2/vivi3.ml: New.
+ * test/test2/vivi.ml: .
+ * test/test4/test.sh: New.
+ * test/test5/test.sh: New.
+ * test/test2/test.sh: New.
+ * test/test6/test.sh: .
+ * test/good-output: New.
+ * test/test3/test.sh: New.
+ * test/runtest.sh: New.
+
+2006-10-31 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Restore some recursivity for includes.
+
+ * resource.ml,
+ * resource.mli: Remove the digest field.
+ * rule.ml: .
+ * test/test6/test.sh: .
+
+2006-10-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Remove the arbitrary deep dependencies.
+
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: No more implicit transitives deps.
+ * resource.ml,
+ * resource.mli: Remove as many things as possible.
+ * rule.ml,
+ * rule.mli,
+ * solver.ml: Simplify.
+ * command.ml: Fix newlines and flush.
+
+2006-10-30 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Separated preprocessing, total order over rules...
+
+ * ocamlbuild.ml,
+ * my_std.ml,
+ * my_std.mli,
+ * ocaml_specific.ml,
+ * ocaml_specific.mli,
+ * options.ml,
+ * options.mli,
+ * pathname.ml,
+ * pathname.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml,
+ * rule.mli,
+ * solver.ml,
+ * test/test2/tutu.ml,
+ * tags.ml,
+ * test/test2/tyty.mli,ew.
+ * test/test6/test.sh,
+ * test/test6,
+ * test/test5/_tags,
+ * test/test5: Update.
+
+2006-10-27 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add options: -ocamlc,-ocamlopt,-ocamldep,-ocamlyacc,-ocamllex.
+
+ * options.ml,
+ * options.mli: Declare them.
+ * ocaml_specific.ml: Use them.
+
+2006-10-27 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix start.sh.
+
+ * start.sh: Fix the output.
+
+2006-10-27 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Regen start.sh.
+
+ * start.sh: Regen.
+
+2006-10-27 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use the list based implems and fix many bugs.
+
+ * ocamlbuild.ml: Rename some dependency files.
+ * boot: Ignore boot/ocamlbuild.byte.save.* files.
+ * command.ml: Fix command printing.
+ * my_std.ml,
+ * my_std.mli: Add List.equal, use the cp command in Shell.cp.
+ * ocaml_specific.ml,
+ * ocaml_specific.mli: Many things.
+ * pathname.ml, pathname.mli: Make compare obselete prefer equal.
+ * resource.ml, resource.mli: Add print_cache and use list based
+ sets and maps.
+ * Makefile: Add the bootstrap rule.
+
+2006-10-27 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a test for fine-grained dependencies.
+
+ * test/test6/main.ml: New.
+ * test/test6/d.ml: New.
+ * test/test6/b.ml: New.
+ * test/test6/a.ml: New.
+ * test/test6/main.mli: New.
+ * test/test6/a.mli: New.
+ * test/test6/d.mli: New.
+ * test/test6/b.mli: New.
+ * test/test6/b.mli.v2: New.
+ * test/test6/main.byte: New.
+ * test/test6/d.mli.v1: New.
+ * test/test6/test.sh: New.
+ * test/test6/d.mli.v2: New.
+ * test/test6/b.mli.v1: New.
+ * test/test6: New.
+
+2006-10-26 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Dummy implementations for set and map using lists.
+ The main advantage is to only rely on the equal function that is simpler
+ to maintain correct in an imperative setting.
+
+ * list_map.ml: New.
+ * list_set.ml: New.
+ * list_map.mli: New.
+ * list_set.mli: New.
+
+2006-10-24 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fixes and improvment.
+
+ * ocamlbuild.ml,
+ * my_std.ml,
+ * my_std.mli,
+ * ocaml_specific.ml,
+ * ocaml_specific.mli,
+ * pathname.ml,
+ * resource.ml,
+ * rule.ml,
+ * rule.mli,
+ * solver.ml,
+ * solver.mli: The previous version was somwhat unstable.
+
+2006-10-24 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Many things...
+
+ * ocamlbuild.ml,
+ * command.ml,
+ * command.mli,
+ * ocaml_specific.ml,
+ * ocaml_specific.mli,
+ * options.ml,
+ * options.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml,
+ * rule.mli,
+ * solver.ml,
+ * solver.mli:
+ Simplify the whole solver by removing the value type.
+ Rule code now returns a resource set, that is injected as dependencies.
+ So rule code always returns unit. But can raise exceptions.
+ Add -ignore, and -ignore-auto options to workaround ocamldep
+ approximations without igonring errors.
+ * Makefile: Add backup and restore targets.
+
+2006-10-23 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Compute digests of dependencies recursively.
+
+ * ocamlbuild.ml,
+ * ocaml_specific.ml,
+ * options.ml,
+ * options.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml: Ditto.
+
+2006-10-23 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ One step toward a parallelisable system.
+
+ * boot,
+ * command.ml,
+ * ocaml_specific.ml,
+ * ocaml_specific.mli,
+ * options.ml,
+ * options.mli,
+ * rule.ml,
+ * rule.mli,
+ * solver.ml: Update.
+ * value.ml: Remove.
+ * value.mli: Remove.
+
+2006-10-20 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add vcs config file to setup a good default setup.
+
+ * .vcs: New.
+
+2006-10-20 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Simplify the bootstrap by introducing a shell script.
+
+ * boot/ocamlbuild.byte: Remove. Useless in distribution mode
+ but will be created, the first time. So the devel is not
+ disturbed.
+ * start.sh: New.
+ * Makefile: Remove the old one to use start.sh.
+
+2006-10-20 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Take command line in account for the digest computation.
+
+ * command.ml,
+ * command.mli,
+ * debug.ml,
+ * ocaml_specific.ml,
+ * ocaml_specific.mli,
+ * resource.ml,
+ * resource.mli,
+ * rule.ml,
+ * rule.mli,
+ * solver.ml,
+ * value.ml,
+ * value.mli: Update.
+
+2006-10-19 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ New pathname representation.
+
+ * pathname.ml, pathname.mli: This new representation should
+ avoids "fix" problems.
+
+2006-10-17 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Change the cache implem -> now really fast at link time.
+
+ * ocamlbuild.ml,
+ * boot/ocamlbuild.byte,
+ * my_std.ml,
+ * ocaml_specific.ml,
+ * pathname.ml,
+ * resource.ml,
+ * resource.mli,
+ * solver.ml: By replacing various sets by a map of records and
+ remember that something has not changed, or cannot be built;
+ there is a real speedup. In particular to detect that the link is
+ not necessary to do.
+
+2006-10-17 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a basic support for a digest based cache verification.
+
+ * resource.ml, resource.mli: Add have_digest and store_digest.
+ * rule.ml: Use these digests but don't include the command for
+ now.
+ * test/test2/vivi.ml, test/test2/tata.mli: Dummy updates.
+
+2006-10-16 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Split in many files.
+
+ * ocamlbuild.ml: Splitted.
+ * boot/ocamlbuild.byte: Updated.
+ * configuration.ml: New.
+ * configuration.mli: New.
+ * command.ml: New.
+ * command.mli: New.
+ * debug.ml: New.
+ * debug.mli: New.
+ * flags.ml: New.
+ * flags.mli: New.
+ * my_std.ml: New.
+ * my_std.mli: New.
+ * ocaml_specific.ml: New.
+ * ocaml_specific.mli: New.
+ * options.ml: New.
+ * options.mli: New.
+ * pathname.ml: New.
+ * pathname.mli: New.
+ * re.ml: New.
+ * re.mli: New.
+ * resource.ml: New.
+ * resource.mli: New.
+ * rule.ml: New.
+ * rule.mli: New.
+ * solver.ml: New.
+ * solver.mli: New.
+ * test/test5/d.ml: New.
+ * tags.ml: New.
+ * test/test5/b.ml: New.
+ * test/test5/a.ml: New.
+ * tags.mli: New.
+ * test/test5/a.mli: New.
+ * test/test5/c.mlpack: New.
+ * test/test5/_tags: New.
+ * test/test5: New.
+ * value.ml: New.
+ * value.mli: New.
+ * Makefile: .
+
+2006-10-16 Berke Durak <berke.durak@inria.fr>
+
+ Various useful changes.
+
+ * ocamlbuild.ml: Hygiene to true.
+ * slurp.ml: Remove debugging
+ * Makefile: Clean annot and object files.
+
+2006-10-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Bootstrap it ;).
+
+ * ocamlbuild.ml: Add support for -g, -dtypes, and -rectypes in
+ four lines.
+ * _tags: New. Specify how to build ocamlbuild itself.
+ * boot: New.
+ * boot/ocamlbuild.byte: New. A bytecode version needed to
+ bootstrap
+ * Makefile: By default make it a wrapper over ocamlbuild in boot.
+
+2006-10-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Little fix...
+
+ * ocamlbuild.ml: Don't assoc over pathnames since the default
+ compare is wrong and slow use the string repr.
+
+2006-10-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Allow to control flags, and libraries by tags.
+
+ * ocamlbuild.ml: In the _tags file you can add or remove flags
+ using a colon flag_name:flag_value.
+ * test/test2/vivi.ml,
+ * test/test3/f.ml,
+ * test/test4/b/bb.ml: Dummy updates.
+ * test/test3/_tags: New.
+ * test/test4/_tags: New.
+
+2006-10-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add a tag based flag system.
+
+ * test/test2/vivi.ml: An example.
+ * test/test2/_tags: New.
+ * ocamlbuild.ml: Now a command can request for flags by giving a
+ set of tags these tags include file specific tags this allow to
+ tweak flags by just providing a _tags file.
+
+2006-10-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add -lib,-libs options remove -P.
+
+ * ocamlbuild.ml: -P Is useless due to the fact that we now
+ have the same directory structure in the _build directory.
+ Add -lib,-libs that allows one to specify -lib unix without
+ its extension in order to request for native and byte
+ compilations.
+
+2006-10-15 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Multi directories now works ;).
+
+ * ocamlbuild.ml: Solve the whole problem by improving the
+ Pathname module. Pathnames are now symbolic values that
+ can include variable names. These variable names represent
+ still ambiguous pathnames /a/b/(c|d as x1)/e.ml but variables
+ can be shared, so discovering that /a/b/(c|d as x1)/e.ml is in
+ fact /a/b/c/e.ml will make /a/b/(c|d as x1)/e.cmo automatically
+ take this value /a/b/c/e.cmo cause it shares the x1 variable.
+
+2006-10-13 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ I prefer capitalized names.
+
+ * AUTHORS
+
+2006-10-13 Berke Durak <berke.durak@inria.fr>
+
+ Added an AUTHORS file.
+
+ * AUTHORS: New.
+
+2006-10-13 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add the vcs dir.
+
+ * vcs: New.
+ * vcs/ocamlbuild.rb: New.
+
+2006-10-13 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ * ocamlbuild.ml: Restore dependencies.
+
+2006-10-13 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix the makefile.
+
+ * Makefile, discard_printf.ml: Ditto.
+
+2006-10-13 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Improve the directory handling.
+
+ * ocamlbuild.ml: Ditto, but there is still a problem with native.
+ * Makefile: Update.
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix native dependencies.
+
+ * ocamlbuild.ml: By default due to inlining the cmx dependencies
+ are needed to build a cmx.
+ * Makefile: Add native support.
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use phony for linkdeps.
+
+ * ocamlbuild.ml: Ditto.
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix exit on multiple targets.
+
+ * ocamlbuild.ml: Ditto.
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ More flags -lflags,-lflag...
+
+ * ocamlbuild.ml: Add plrual form options for those that use
+ comma separated lists.
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use phony resources for .cmo.linkdeps.
+
+ * ocamlbuild.ml: Also restore the command running if "--"
+ is specified
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Remove Include_string_list resources, add Phony resources.
+
+ * ocamlbuild.ml: Also fix some rules.
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Shift debug levels.
+
+ * ocamlbuild.ml: Add -quiet.
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Use str more intensively.
+
+ * ocamlbuild.ml: Also clean up useless functions.
+
+2006-10-11 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Fix link dependencies.
+
+ * ocamlbuild.ml: Force to consider recursivly Include_ tagged
+ resources for their full contents. Alas it takes more time to
+ know if we need to recompute the link.
+ * test/test2/vivi.ml: Update.
+
+2006-10-10 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Support multiple directories, it can compile the OCaml compiler :).
+
+ * ocamlbuild.ml: Add directory handling but also start
+ the tags config files handling.
+ * Makefile: Use str.cma.
+
+2006-10-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ Add library support.
+
+ * ocamlbuild.ml: Deduce basic set of tags form the target
+ extension.
+
+2006-10-08 Nicolas Pouillard <nicolas.pouillard@gmail.com>
+
+ More customisable flags, and cycle detection.
+
+ * ocamlbuild.ml: Add some flags -lflag, -ppflag, -cflag, --.
+ Also add a detection mechanism for dependencies.
+ * discard_printf.ml, Makefile: Update.
diff --git a/ocamlbuild/FAQ b/ocamlbuild/FAQ
new file mode 100644
index 0000000000..b71516b9e3
--- /dev/null
+++ b/ocamlbuild/FAQ
@@ -0,0 +1,35 @@
+Q: I've a directory with examples and I want build all of them easily?
+
+R:
+
+ You can use an .itarget file listing all products that you want.
+
+ $ cat examples.itarget
+ examples/a.byte
+ examples/b.byte
+
+ $ ocamlbuild examples.otarget
+
+ You can also have a dynamic rule that read the examples directory:
+
+ $ cat myocamlbuild.ml
+ open Ocamlbuild_plugin;;
+
+ dispatch begin function
+ | After_rules ->
+ let examples =
+ Array.fold_right begin fun f acc ->
+ if Pathname.get_extension f = "ml" then
+ ("examples" / Pathname.update_extension "byte" f) :: acc
+ else
+ acc
+ end (Pathname.readdir "examples") []
+ in
+ rule "All examples"
+ ~prod:"examples.otarget"
+ ~deps:examples
+ (fun _ _ -> Command.Nop)
+ | _ -> ()
+ end
+
+ $ ocamlbuild examples.otarget
diff --git a/ocamlbuild/Makefile b/ocamlbuild/Makefile
new file mode 100644
index 0000000000..2173de7f4f
--- /dev/null
+++ b/ocamlbuild/Makefile
@@ -0,0 +1,214 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+
+ROOTDIR = ..
+OCAMLC = $(CAMLRUN) $(ROOTDIR)/ocamlc -nostdlib -I $(ROOTDIR)/stdlib
+OCAMLOPT = $(CAMLRUN) $(ROOTDIR)/ocamlopt -nostdlib -I $(ROOTDIR)/stdlib
+OCAMLDEP = $(CAMLRUN) $(ROOTDIR)/tools/ocamldep
+OCAMLLEX = $(CAMLRUN) $(ROOTDIR)/boot/ocamllex
+CP = cp
+COMPFLAGS= -warn-error A -w L -w R -w Z -I ../otherlibs/$(UNIXLIB) -safe-string
+LINKFLAGS= -I ../otherlibs/$(UNIXLIB)
+
+PACK_CMO=\
+ const.cmo \
+ loc.cmo \
+ discard_printf.cmo \
+ signatures.cmi \
+ my_std.cmo \
+ my_unix.cmo \
+ tags.cmo \
+ display.cmo \
+ log.cmo \
+ shell.cmo \
+ bool.cmo \
+ glob_ast.cmo \
+ glob_lexer.cmo \
+ glob.cmo \
+ lexers.cmo \
+ param_tags.cmo \
+ command.cmo \
+ ocamlbuild_config.cmo \
+ ocamlbuild_where.cmo \
+ slurp.cmo \
+ options.cmo \
+ pathname.cmo \
+ configuration.cmo \
+ flags.cmo \
+ hygiene.cmo \
+ digest_cache.cmo \
+ resource.cmo \
+ rule.cmo \
+ solver.cmo \
+ report.cmo \
+ tools.cmo \
+ fda.cmo \
+ findlib.cmo \
+ ocaml_arch.cmo \
+ ocaml_utils.cmo \
+ ocaml_dependencies.cmo \
+ ocaml_compiler.cmo \
+ ocaml_tools.cmo \
+ ocaml_specific.cmo \
+ plugin.cmo \
+ exit_codes.cmo \
+ hooks.cmo \
+ main.cmo
+
+EXTRA_CMO=\
+ ocamlbuild_plugin.cmo \
+ ocamlbuild_executor.cmo \
+ ocamlbuild_unix_plugin.cmo
+
+PACK_CMX=$(PACK_CMO:.cmo=.cmx)
+EXTRA_CMX=$(EXTRA_CMO:.cmo=.cmx)
+EXTRA_CMI=$(EXTRA_CMO:.cmo=.cmi)
+
+INSTALL_LIB=\
+ ocamlbuildlib.cma \
+ ocamlbuild.cmo \
+ ocamlbuild_pack.cmi \
+ $(EXTRA_CMO:.cmo=.cmi)
+
+INSTALL_LIB_OPT=\
+ ocamlbuildlib.cmxa ocamlbuildlib.$(A) \
+ ocamlbuild.cmx ocamlbuild.$(O) \
+ ocamlbuild_pack.cmx \
+ $(EXTRA_CMO:.cmo=.cmx) $(EXTRA_CMO:.cmo=.$(O))
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)/ocamlbuild
+INSTALL_BINDIR=$(DESTDIR)$(BINDIR)
+
+all: ocamlbuild.byte ocamlbuildlib.cma
+ # ocamlbuildlight.byte ocamlbuildlightlib.cma
+allopt: ocamlbuild.native ocamlbuildlib.cmxa
+
+# The executables
+
+ocamlbuild.byte: ocamlbuild_pack.cmo $(EXTRA_CMO) ocamlbuild.cmo
+ $(OCAMLC) $(LINKFLAGS) -o ocamlbuild.byte \
+ unix.cma ocamlbuild_pack.cmo $(EXTRA_CMO) ocamlbuild.cmo
+
+ocamlbuildlight.byte: ocamlbuild_pack.cmo ocamlbuildlight.cmo
+ $(OCAMLC) $(LINKFLAGS) -o ocamlbuildlight.byte \
+ ocamlbuild_pack.cmo ocamlbuildlight.cmo
+
+ocamlbuild.native: ocamlbuild_pack.cmx $(EXTRA_CMX) ocamlbuild.cmx
+ $(OCAMLOPT) $(LINKFLAGS) -o ocamlbuild.native \
+ unix.cmxa ocamlbuild_pack.cmx $(EXTRA_CMX) ocamlbuild.cmx
+
+# The libraries
+
+ocamlbuildlib.cma: ocamlbuild_pack.cmo $(EXTRA_CMO)
+ $(OCAMLC) -a -o ocamlbuildlib.cma \
+ ocamlbuild_pack.cmo $(EXTRA_CMO)
+
+ocamlbuildlightlib.cma: ocamlbuild_pack.cmo ocamlbuildlight.cmo
+ $(OCAMLC) -a -o ocamlbuildlightlib.cma \
+ ocamlbuild_pack.cmo ocamlbuildlight.cmo
+
+ocamlbuildlib.cmxa: ocamlbuild_pack.cmx $(EXTRA_CMX)
+ $(OCAMLOPT) -a -o ocamlbuildlib.cmxa \
+ ocamlbuild_pack.cmx $(EXTRA_CMX)
+
+# The packs
+
+ocamlbuild_pack.cmo: $(PACK_CMO)
+ $(OCAMLC) -pack $(PACK_CMO) -o ocamlbuild_pack.cmo
+
+ocamlbuild_pack.cmi: ocamlbuild_pack.cmo
+
+ocamlbuild_pack.cmx: $(PACK_CMX)
+ $(OCAMLOPT) -pack $(PACK_CMX) -o ocamlbuild_pack.cmx
+
+# The config file
+
+ocamlbuild_config.ml: ../config/Makefile
+ (echo 'let bindir = "$(BINDIR)"'; \
+ echo 'let libdir = "$(LIBDIR)"'; \
+ echo 'let supports_shared_libraries = $(SUPPORTS_SHARED_LIBRARIES)';\
+ echo 'let a = "$(A)"'; \
+ echo 'let o = "$(O)"'; \
+ echo 'let so = "$(SO)"'; \
+ echo 'let ext_dll = "$(EXT_DLL)"'; \
+ echo 'let exe = "$(EXE)"'; \
+ ) > ocamlbuild_config.ml
+clean::
+ rm -f ocamlbuild_config.ml
+beforedepend:: ocamlbuild_config.ml
+
+# The lexers
+
+lexers.ml: lexers.mll
+ $(OCAMLLEX) lexers.mll
+clean::
+ rm -f lexers.ml
+beforedepend:: lexers.ml
+
+glob_lexer.ml: glob_lexer.mll
+ $(OCAMLLEX) glob_lexer.mll
+clean::
+ rm -f glob_lexer.ml
+beforedepend:: glob_lexer.ml
+
+# Installation
+
+install:
+ $(CP) ocamlbuild.byte $(INSTALL_BINDIR)/ocamlbuild$(EXE)
+ $(CP) ocamlbuild.byte $(INSTALL_BINDIR)/ocamlbuild.byte$(EXE)
+ mkdir -p $(INSTALL_LIBDIR)
+ $(CP) $(INSTALL_LIB) $(INSTALL_LIBDIR)/
+
+installopt:
+ if test -f ocamlbuild.native; then $(MAKE) installopt_really; fi
+
+installopt_really:
+ $(CP) ocamlbuild.native $(INSTALL_BINDIR)/ocamlbuild$(EXE)
+ $(CP) ocamlbuild.native $(INSTALL_BINDIR)/ocamlbuild.native$(EXE)
+ mkdir -p $(INSTALL_LIBDIR)
+ $(CP) $(INSTALL_LIB_OPT) $(INSTALL_LIBDIR)/
+
+# The generic rules
+
+.SUFFIXES: .ml .mli .cmo .cmi .cmx
+
+.ml.cmo:
+ $(OCAMLC) $(COMPFLAGS) -c $<
+
+.mli.cmi:
+ $(OCAMLC) $(COMPFLAGS) -c $<
+
+.ml.cmx:
+ $(OCAMLOPT) -for-pack Ocamlbuild_pack $(COMPFLAGS) -c $<
+
+clean::
+ rm -f *.cm? *.$(O) *.cmxa *.$(A)
+ rm -f *.byte *.native
+
+# The dependencies
+
+depend: beforedepend
+ $(OCAMLDEP) *.mli *.ml > .depend
+
+$(EXTRA_CMI): ocamlbuild_pack.cmi
+$(EXTRA_CMO): ocamlbuild_pack.cmo ocamlbuild_pack.cmi
+$(EXTRA_CMX): ocamlbuild_pack.cmx ocamlbuild_pack.cmi
+
+include .depend
+
+.PHONY: all allopt clean beforedepend
+.PHONY: install installopt installopt_really depend
diff --git a/ocamlbuild/TODO b/ocamlbuild/TODO
new file mode 100644
index 0000000000..fd7ef2c94b
--- /dev/null
+++ b/ocamlbuild/TODO
@@ -0,0 +1,38 @@
+To do:
+* Add rules for producing .recdepends from .ml, .mli, .mllib, .mlpack
+* Produce a dependency subgraph when failing on circular deps (e.g. "A: B C\nB: D")
+* Executor: exceptional conditions and Not_found
+* Fix report
+* Design a nice, friendly, future-proof plugin (myocamlbuild) API
+* Ocamlbuild should keep track of files removed from the source directory, e.g.,
+removing a .mli should be mirrored in the _build directory.
+
+Being done:
+* Write doc
+
+Almost done:
+* Fine control for hygiene using a glob pattern (command line option + tag)
+ => the command line option is todo.
+ -tag "<glob1> or <glob2> ..." "tag1, -tag2, ..."
+
+Won't fix:
+* Config file for options => no since myocamlbuild is sufficent
+* Optimize MD5 (Daemon ? Dnotify ?) : too much hassle for little gain
+
+Done:
+* Fix uncaught exception handler to play well with the Display module
+* Finish display before executing target
+* Slurp: in a directory read files, before subdirs (to have _tags before foo/_tags)
+* Add a -clean option
+* Add ocamldoc rules (use .odoc extension)
+* Add .inferred.mli target rules
+* -- with no args does not call the executable
+* Complain when used with -- and no target
+* dep ["ocaml"; "link"; "use_foo"] ["foo/foo.o"] tags for adding targets
+* Ensure that _build and _log are not created if not needed (with -help for
+ instance)
+* Display: should display nothing (even when finish is called) when no real
+ event as occured.
+* Have some option to draw tags/rules that applies on a target (it's -show-tags).
+* rm sanitize.sh during -clean
+* rm sanitize.sh when running ocamlbuild
diff --git a/ocamlbuild/_tags b/ocamlbuild/_tags
new file mode 100644
index 0000000000..c60b33005a
--- /dev/null
+++ b/ocamlbuild/_tags
@@ -0,0 +1,23 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+# OCamlbuild tags file
+true: debug
+<*.ml> or <*.mli>: warn_L, warn_R, warn_Z, annot
+"discard_printf.ml": rectypes
+"ocamlbuildlib.cma" or "ocamlbuildlightlib.cma": linkall
+<*.byte> or <*.native> or <*.top>: use_unix
+"ocamlbuildlight.byte": -use_unix, nopervasives
+<*.cmx>: for-pack(Ocamlbuild_pack)
+<{ocamlbuild_{pack,unix_plugin,plugin,executor},ppcache}{,.p}.cmx>: -for-pack(Ocamlbuild_pack)
+"doc": not_hygienic
diff --git a/ocamlbuild/bool.ml b/ocamlbuild/bool.ml
new file mode 100644
index 0000000000..a5f119fda1
--- /dev/null
+++ b/ocamlbuild/bool.ml
@@ -0,0 +1,40 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Bool *)
+
+type 'a boolean = And of 'a boolean list | Or of 'a boolean list | Not of 'a boolean | Atom of 'a | True | False;;
+
+let rec eval f = function
+ | And l -> List.for_all (eval f) l
+ | Or l -> List.exists (eval f) l
+ | Not x -> not (eval f x)
+ | Atom a -> f a
+ | True -> true
+ | False -> false
+;;
+let rec iter f = function
+ | (And l|Or l) -> List.iter (iter f) l
+ | Not x -> iter f x
+ | Atom a -> f a
+ | True|False -> ()
+;;
+let rec map f = function
+ | And l -> And(List.map (map f) l)
+ | Or l -> Or(List.map (map f) l)
+ | Not x -> Not(map f x)
+ | Atom a -> Atom(f a)
+ | (True|False) as b -> b
+;;
diff --git a/ocamlbuild/bool.mli b/ocamlbuild/bool.mli
new file mode 100644
index 0000000000..95d6ac3b2a
--- /dev/null
+++ b/ocamlbuild/bool.mli
@@ -0,0 +1,36 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Bool *)
+
+(** Provides a datatype for representing boolean formulas and evaluation,
+ iteration and map functions. *)
+
+(** Public type for generic boolean formulas. An empty conjunction [And[]] is true and
+ an empty disjunction [Or[]] is false. *)
+type 'a boolean =
+ And of 'a boolean list
+ | Or of 'a boolean list
+ | Not of 'a boolean
+ | Atom of 'a
+ | True
+ | False
+
+val eval : ('a -> bool) -> 'a boolean -> bool
+(** [eval g f] evaluates the boolean formula [f] using the values returned by [g] for the atoms. *)
+val iter : ('a -> unit) -> 'a boolean -> unit
+(** [iter g f] calls [g] over every atom of [f]. *)
+val map : ('a -> 'b) -> 'a boolean -> 'b boolean
+(** [map g f] replaces every atom of [f] by its image by [g]. *)
diff --git a/ocamlbuild/command.ml b/ocamlbuild/command.ml
new file mode 100644
index 0000000000..7aa570ce69
--- /dev/null
+++ b/ocamlbuild/command.ml
@@ -0,0 +1,423 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Command *)
+
+open My_std
+open Log
+
+type tags = Tags.t
+type pathname = string
+
+let jobs = ref 1
+
+type t =
+| Seq of t list
+| Cmd of spec
+| Echo of string list * pathname
+| Nop
+and spec =
+| N (* nop or nil *)
+| S of spec list
+| A of string
+| P of pathname
+| Px of pathname
+| Sh of string
+| T of Tags.t
+| V of string
+| Quote of spec
+
+(*type v = [ `Seq of v list | `Cmd of vspec | `Nop ]
+and vspec =
+ [ `N
+ | `S of vspec list
+ | `A of string
+ | `P of pathname
+ | `Px of pathname
+ | `Sh of string
+ | `Quote of vspec ]
+
+let rec spec_of_vspec =
+ function
+ | `N -> N
+ | `S vspecs -> S (List.map spec_of_vspec vspecs)
+ | `A s -> A s
+ | `P s -> P s
+ | `Px s -> Px s
+ | `Sh s -> Sh s
+ | `Quote vspec -> Quote (spec_of_vspec vspec)
+
+let rec vspec_of_spec =
+ function
+ | N -> `N
+ | S specs -> `S (List.map vspec_of_spec specs)
+ | A s -> `A s
+ | P s -> `P s
+ | Px s -> `Px s
+ | Sh s -> `Sh s
+ | T _ -> invalid_arg "vspec_of_spec: T not supported"
+ | Quote spec -> `Quote (vspec_of_spec spec)
+
+let rec t_of_v =
+ function
+ | `Nop -> Nop
+ | `Cmd vspec -> Cmd (spec_of_vspec vspec)
+ | `Seq cmds -> Seq (List.map t_of_v cmds)
+
+let rec v_of_t =
+ function
+ | Nop -> `Nop
+ | Cmd spec -> `Cmd (vspec_of_spec spec)
+ | Seq cmds -> `Seq (List.map v_of_t cmds)*)
+
+let no_tag_handler _ = failwith "no_tag_handler"
+
+let tag_handler = ref no_tag_handler
+
+(*** atomize *)
+let atomize l = S(List.map (fun x -> A x) l)
+let atomize_paths l = S(List.map (fun x -> P x) l)
+(* ***)
+
+let env_path = lazy begin
+ let path_var = Sys.getenv "PATH" in
+ let parse_path =
+ if Sys.os_type = "Win32" then
+ Lexers.parse_environment_path_w
+ else
+ Lexers.parse_environment_path
+ in
+ let paths =
+ parse_path Const.Source.path (Lexing.from_string path_var) in
+ let norm_current_dir_name path =
+ if path = "" then Filename.current_dir_name else path
+ in
+ List.map norm_current_dir_name paths
+end
+
+let virtual_solvers = Hashtbl.create 32
+let setup_virtual_command_solver virtual_command solver =
+ Hashtbl.replace virtual_solvers virtual_command solver
+let virtual_solver virtual_command =
+ let solver =
+ try
+ Hashtbl.find virtual_solvers virtual_command
+ with Not_found ->
+ failwith (sbprintf "no solver for the virtual command %S \
+ (setup one with Command.setup_virtual_command_solver)"
+ virtual_command)
+ in
+ try solver ()
+ with Not_found ->
+ failwith (Printf.sprintf "the solver for the virtual command %S \
+ has failed finding a valid command" virtual_command)
+
+(* On Windows, we need to also check for the ".exe" version of the file. *)
+let file_or_exe_exists file =
+ sys_file_exists file || ((Sys.win32 || Sys.cygwin) && sys_file_exists (file ^ ".exe"))
+
+let search_in_path cmd =
+ (* Try to find [cmd] in path [path]. *)
+ let try_path path =
+ (* Don't know why we're trying to be subtle here... *)
+ if path = Filename.current_dir_name then file_or_exe_exists cmd
+ else file_or_exe_exists (filename_concat path cmd)
+ in
+ if Filename.is_implicit cmd then
+ let path = List.find try_path !*env_path in
+ (* We're not trying to append ".exe" here because all windows shells are
+ * capable of understanding the command without the ".exe" suffix. *)
+ filename_concat path cmd
+ else
+ cmd
+
+(*** string_of_command_spec{,_with_calls *)
+let rec string_of_command_spec_with_calls call_with_tags call_with_target resolve_virtuals spec =
+ let self = string_of_command_spec_with_calls call_with_tags call_with_target resolve_virtuals in
+ let b = Buffer.create 256 in
+ (* The best way to prevent bash from switching to its windows-style
+ * quote-handling is to prepend an empty string before the command name. *)
+ if Sys.os_type = "Win32" then
+ Buffer.add_string b "''";
+ let first = ref true in
+ let put_space () =
+ if !first then
+ first := false
+ else
+ Buffer.add_char b ' '
+ in
+ let put_filename p =
+ Buffer.add_string b (Shell.quote_filename_if_needed p)
+ in
+ let rec do_spec = function
+ | N -> ()
+ | A u -> put_space (); put_filename u
+ | Sh u -> put_space (); Buffer.add_string b u
+ | P p -> put_space (); put_filename p
+ | Px u -> put_space (); put_filename u; call_with_target u
+ | V v -> if resolve_virtuals then do_spec (virtual_solver v)
+ else (put_space (); Printf.bprintf b "<virtual %s>" (Shell.quote_filename_if_needed v))
+ | S l -> List.iter do_spec l
+ | T tags -> call_with_tags tags; do_spec (!tag_handler tags)
+ | Quote s -> put_space (); put_filename (self s)
+ in
+ do_spec spec;
+ Buffer.contents b
+
+let string_of_command_spec x = string_of_command_spec_with_calls ignore ignore false x
+
+let string_target_and_tags_of_command_spec spec =
+ let rtags = ref Tags.empty in
+ let rtarget = ref "" in
+ let union_rtags tags = rtags := Tags.union !rtags tags in
+ let s = string_of_command_spec_with_calls union_rtags ((:=) rtarget) true spec in
+ let target = if !rtarget = "" then s else !rtarget in
+ s, target, !rtags
+
+let string_print_of_command_spec spec quiet pretend =
+ let s, target, tags = string_target_and_tags_of_command_spec spec in
+ fun () -> if not quiet then Log.event ~pretend s target tags; s
+(* ***)
+
+let print_escaped_string f = Format.fprintf f "%S"
+
+let rec print f =
+ function
+ | Cmd spec -> Format.pp_print_string f (string_of_command_spec spec)
+ | Seq seq -> List.print print f seq
+ | Nop -> Format.pp_print_string f "nop"
+ | Echo(texts, dest_path) ->
+ Format.fprintf f "@[<2>Echo(%a,@ %a)@]"
+ (List.print print_escaped_string) texts print_escaped_string dest_path
+
+let to_string x = sbprintf "%a" print x
+
+let add_parallel_stat, dump_parallel_stats =
+ let xmin = ref max_int in
+ let xmax = ref 0 in
+ let xsum = ref 0 in
+ let xsumall = ref 0 in
+ let xcount = ref 0 in
+ let xcountall = ref 0 in
+ let add_parallel_stat x =
+ if x > 0 then begin
+ incr xcountall;
+ xsumall := x + !xsumall;
+ end;
+ if x > 1 then begin
+ incr xcount;
+ xsum := x + !xsum;
+ xmax := max !xmax x;
+ xmin := min !xmin x;
+ end
+ in
+ let dump_parallel_stats () =
+ if !jobs <> 1 then
+ if !xcount = 0 then
+ dprintf 1 "# No parallelism done"
+ else
+ let xaverage = float_of_int !xsumall /. float_of_int !xcountall in
+ let xaveragepara = float_of_int !xsum /. float_of_int !xcount in
+ dprintf 1 "# Parallel statistics: { count(total): %d(%d), max: %d, min: %d, average(total): %.3f(%.3f) }"
+ !xcount !xcountall !xmax !xmin xaveragepara xaverage
+ in
+ add_parallel_stat, dump_parallel_stats
+
+module Primitives = struct
+ let do_echo texts dest_path =
+ with_output_file dest_path begin fun oc ->
+ List.iter (output_string oc) texts
+ end
+ let echo x y () = (* no print here yet *) do_echo x y; ""
+end
+
+let rec list_rev_iter f =
+ function
+ | [] -> ()
+ | x :: xs -> list_rev_iter f xs; f x
+
+let flatten_commands quiet pretend cmd =
+ let rec loop acc =
+ function
+ | [] -> acc
+ | Nop :: xs -> loop acc xs
+ | Cmd spec :: xs -> loop (string_print_of_command_spec spec quiet pretend :: acc) xs
+ | Echo(texts, dest_path) :: xs -> loop (Primitives.echo texts dest_path :: acc) xs
+ | Seq l :: xs -> loop (loop acc l) xs
+ in List.rev (loop [] [cmd])
+
+let execute_many ?(quiet=false) ?(pretend=false) cmds =
+ add_parallel_stat (List.length cmds);
+ let degraded = !*My_unix.is_degraded || Sys.os_type = "Win32" in
+ let jobs = !jobs in
+ if jobs < 0 then invalid_arg "jobs < 0";
+ let max_jobs = if jobs = 0 then None else Some jobs in
+
+ let ticker = Log.update in
+ let display = Log.display in
+
+ if cmds = [] then
+ None
+ else
+ begin
+ let konts = List.map (flatten_commands quiet pretend) cmds in
+ if pretend then
+ begin
+ List.iter (List.iter (fun f -> ignore (f ()))) konts;
+ None
+ end
+ else
+ begin
+ reset_filesys_cache ();
+ if degraded then
+ let res, opt_exn =
+ List.fold_left begin fun (acc_res, acc_exn) cmds ->
+ match acc_exn with
+ | None ->
+ begin try
+ List.iter begin fun action ->
+ let cmd = action () in
+ let rc = sys_command cmd in
+ if rc <> 0 then begin
+ if not quiet then
+ eprintf "Exit code %d while executing this \
+ command:@\n%s" rc cmd;
+ raise (Exit_with_code rc)
+ end
+ end cmds;
+ true :: acc_res, None
+ with e -> false :: acc_res, Some e
+ end
+ | Some _ -> false :: acc_res, acc_exn
+ end ([], None) konts
+ in match opt_exn with
+ | Some(exn) -> Some(List.rev res, exn)
+ | None -> None
+ else
+ My_unix.execute_many ~ticker ?max_jobs ~display konts
+ end
+ end
+;;
+
+let execute ?quiet ?pretend cmd =
+ match execute_many ?quiet ?pretend [cmd] with
+ | Some(_, exn) -> raise exn
+ | _ -> ()
+
+let iter_tags f x =
+ let rec spec x =
+ match x with
+ | N | A _ | Sh _ | P _ | Px _ | V _ | Quote _ -> ()
+ | S l -> List.iter spec l
+ | T tags -> f tags
+ in
+ let rec cmd x =
+ match x with
+ | Nop | Echo _ -> ()
+ | Cmd(s) -> spec s
+ | Seq(s) -> List.iter cmd s in
+ cmd x
+
+let fold_pathnames f x =
+ let rec spec = function
+ | N | A _ | Sh _ | V _ | Quote _ | T _ -> fun acc -> acc
+ | P p | Px p -> f p
+ | S l -> List.fold_right spec l
+ in
+ let rec cmd = function
+ | Nop -> fun acc -> acc
+ | Echo(_, p) -> f p
+ | Cmd(s) -> spec s
+ | Seq(s) -> List.fold_right cmd s in
+ cmd x
+
+let rec reduce x =
+ let rec self x acc =
+ match x with
+ | N -> acc
+ | A _ | Sh _ | P _ | Px _ | V _ -> x :: acc
+ | S l -> List.fold_right self l acc
+ | T tags -> self (!tag_handler tags) acc
+ | Quote s -> Quote (reduce s) :: acc in
+ match self x [] with
+ | [] -> N
+ | [x] -> x
+ | xs -> S xs
+
+let digest =
+ let list = List.fold_right in
+ let text x acc = Digest.string x :: acc in
+ let rec cmd =
+ function
+ | Cmd spec -> fun acc -> string_of_command_spec spec :: acc
+ | Seq seq -> list cmd seq
+ | Nop -> fun acc -> acc
+ | Echo(texts, dest_path) -> list text (dest_path :: texts)
+ in
+ fun x ->
+ match cmd x [] with
+ | [x] -> x
+ | xs -> Digest.string ("["^String.concat ";" xs^"]")
+
+let all_deps_of_tags = ref []
+
+let cons deps acc =
+ List.rev&
+ List.fold_left begin fun acc dep ->
+ if List.mem dep acc then acc else dep :: acc
+ end acc deps
+
+let deps_of_tags tags =
+ List.fold_left begin fun acc (xtags, xdeps) ->
+ if Tags.does_match tags xtags then cons xdeps acc
+ else acc
+ end [] !all_deps_of_tags
+
+let set_deps_of_tags tags deps =
+ all_deps_of_tags := (tags, deps) :: !all_deps_of_tags
+
+let dep tags deps = set_deps_of_tags (Tags.of_list tags) deps
+
+let pdep tags ptag deps =
+ Param_tags.declare ptag
+ (fun param -> dep (Param_tags.make ptag param :: tags) (deps param))
+
+let list_all_deps () =
+ !all_deps_of_tags
+
+(*
+let to_string_for_digest x =
+ let rec cmd_of_spec =
+ function
+ | [] -> None
+ | N :: xs -> cmd_of_spec xs
+ | (A x | P x | P x) :: _ -> Some x
+ | Sh x :: _ ->
+ if Shell.is_simple_filename x then Some x
+ else None (* Sh"ocamlfind ocamlc" for example will not be digested. *)
+ | S specs1 :: specs2 -> cmd_of_spec (specs1 @ specs2)
+ | (T _ | Quote _) :: _ -> assert false in
+ let rec cmd_of_cmds =
+ function
+ | Nop | Seq [] -> None
+ | Cmd spec -> cmd_of_spec [spec]
+ | Seq (cmd :: _) -> cmd_of_cmds cmd in
+ let s = to_string x in
+ match cmd_of_cmds x with
+ | Some x ->
+ if sys_file_exists x then sprintf "(%S,%S)" s (Digest.file x)
+ else s
+ | None -> s
+*)
diff --git a/ocamlbuild/command.mli b/ocamlbuild/command.mli
new file mode 100644
index 0000000000..e0706ec2ad
--- /dev/null
+++ b/ocamlbuild/command.mli
@@ -0,0 +1,52 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Command *)
+
+(** Provides an abstract type for easily building complex shell commands without making
+ quotation mistakes. *)
+include Signatures.COMMAND with type tags = Tags.t and type pathname = string
+
+(** {6 For system use only, not for the casual user} *)
+
+val string_target_and_tags_of_command_spec : spec -> string * string * Tags.t
+
+val iter_tags : (Tags.t -> unit) -> t -> unit
+
+val fold_pathnames : (pathname -> 'a -> 'a) -> t -> 'a -> 'a
+
+(** Digest the given command. *)
+val digest : t -> Digest.t
+
+(** Maximum number of parallel jobs. *)
+val jobs : int ref
+
+(** Hook here the function that maps a set of tags to appropriate command
+ options. It also build the dependencies that matches the tags. *)
+val tag_handler : (Tags.t -> spec) ref
+
+(** For system use only *)
+val dump_parallel_stats : unit -> unit
+
+val deps_of_tags : Tags.t -> pathname list
+
+(** [dep tags deps] Will build [deps] when [tags] will be activated. *)
+val dep : Tags.elt list -> pathname list -> unit
+
+val pdep : Tags.elt list -> Tags.elt -> (string -> pathname list) -> unit
+
+val list_all_deps : unit -> (Tags.t * pathname list) list
+
+val file_or_exe_exists: string -> bool
diff --git a/ocamlbuild/configuration.ml b/ocamlbuild/configuration.ml
new file mode 100644
index 0000000000..a209df54e1
--- /dev/null
+++ b/ocamlbuild/configuration.ml
@@ -0,0 +1,96 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Log
+open Lexers
+
+type t = Lexers.conf
+
+let acknowledge_config source config =
+ let ack (tag, loc) = Param_tags.acknowledge source (Some loc) tag in
+ List.iter (fun (_, config) -> List.iter ack config.plus_tags) config
+
+let cache = Hashtbl.create 107
+let (configs, add_config) =
+ let configs = ref [] in
+ (fun () -> !configs),
+ (fun source config ->
+ acknowledge_config source config;
+ configs := config :: !configs;
+ Hashtbl.clear cache)
+
+let parse_lexbuf ?dir source lexbuf =
+ let conf = Lexers.conf_lines dir source lexbuf in
+ add_config source conf
+
+let parse_string ?source s =
+ let source = match source with
+ | Some source -> source
+ | None -> Const.Source.configuration
+ in
+ parse_lexbuf source (lexbuf_of_string s)
+
+let parse_file ?dir file =
+ with_input_file file begin fun ic ->
+ let lexbuf = Lexing.from_channel ic in
+ set_lexbuf_fname file lexbuf;
+ parse_lexbuf ?dir Const.Source.file lexbuf
+ end
+
+let key_match = Glob.eval
+
+let apply_config s (config : t) init =
+ let add (tag, _loc) = Tags.add tag in
+ let remove (tag, _loc) = Tags.remove tag in
+ List.fold_left begin fun tags (key, v) ->
+ if key_match key s then
+ List.fold_right add v.plus_tags (List.fold_right remove v.minus_tags tags)
+ else tags
+ end init config
+
+let apply_configs s = List.fold_right (apply_config s) (configs ()) Tags.empty
+
+let tags_of_filename s =
+ try Hashtbl.find cache s
+ with Not_found ->
+ let res = apply_configs s in
+ let () = Hashtbl.replace cache s res in
+ res
+
+let global_tags () = tags_of_filename ""
+let has_tag tag = Tags.mem tag (global_tags ())
+
+let tag_file file tags =
+ if tags <> [] then parse_string (Printf.sprintf "%S: %s" file (String.concat ", " tags));;
+
+let tag_any tags =
+ if tags <> [] then parse_string (Printf.sprintf "true: %s" (String.concat ", " tags));;
+
+let check_tags_usage useful_tags =
+ let check_tag (tag, loc) =
+ if not (Tags.mem tag useful_tags) then
+
+ Log.eprintf "%aWarning: the tag %S is not used in any flag or dependency \
+ declaration, so it will have no effect; it may be a typo. \
+ Otherwise you can use `mark_tag_used` in your myocamlbuild.ml \
+ to disable this warning."
+ Loc.print_loc loc tag
+ in
+ let check_conf (_, values) =
+ List.iter check_tag values.plus_tags;
+ List.iter check_tag values.minus_tags;
+ in
+ List.iter (List.iter check_conf) (configs ())
diff --git a/ocamlbuild/configuration.mli b/ocamlbuild/configuration.mli
new file mode 100644
index 0000000000..678cf4e14e
--- /dev/null
+++ b/ocamlbuild/configuration.mli
@@ -0,0 +1,45 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Configuration *)
+
+(** Handles the "_tags" file mechanism. *)
+
+(** Incorporate a newline-separated configuration string into the current configuration.
+ Will usually raising an [Invalid_arg] with an appropriately explicit message in case of error. *)
+val parse_string : ?source:Loc.source -> string -> unit
+
+(** [parse_file ?dir fn] incorporates the configuration file named [fn], prefixing its glob patterns
+ with [dir] if given. *)
+val parse_file : ?dir:string -> string -> unit
+
+(** Return the set of tags that apply to a given filename under the current configuration. *)
+val tags_of_filename : string -> Tags.t
+
+val has_tag : string -> bool
+
+(** [tag_file filename tag_list] Tag the given filename with all given tags. *)
+val tag_file : Pathname.t -> Tags.elt list -> unit
+
+(** [tag_any tag_list] Tag anything with all given tags. *)
+val tag_any : Tags.elt list -> unit
+
+(** the tags that apply to any file *)
+val global_tags : unit -> Tags.t
+
+(** Given the list of all tags that are really used by an existing
+ flagset, traverse existing configuration files and warns on tags
+ that will never get used. *)
+val check_tags_usage : Tags.t -> unit
diff --git a/ocamlbuild/const.ml b/ocamlbuild/const.ml
new file mode 100644
index 0000000000..dac8778908
--- /dev/null
+++ b/ocamlbuild/const.ml
@@ -0,0 +1,11 @@
+module Source = struct
+ let file = "file"
+ let command_line = "command-line"
+ let path = "path"
+ let ocamlfind_query = "ocamlfind query"
+ let ocamldep = "ocamldep"
+ let target_pattern = "target pattern"
+ let builtin = "builtin configuration"
+ let configuration = "configuration"
+ let plugin_tag = "plugin tag"
+end
diff --git a/ocamlbuild/digest_cache.ml b/ocamlbuild/digest_cache.ml
new file mode 100644
index 0000000000..dac770fc1f
--- /dev/null
+++ b/ocamlbuild/digest_cache.ml
@@ -0,0 +1,43 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Original author: Nicolas Pouillard *)
+
+open My_std
+open Pathname.Operators
+
+let digests = Hashtbl.create 103
+
+let get = Hashtbl.find digests
+
+let put = Hashtbl.replace digests
+
+let _digests = lazy (!Options.build_dir / (Pathname.mk "_digests"))
+
+let finalize () =
+ with_output_file !*_digests begin fun oc ->
+ Hashtbl.iter begin fun name digest ->
+ Printf.fprintf oc "%S: %S\n" name digest
+ end digests
+ end
+
+let init () =
+ Shell.chdir !Options.build_dir;
+ if Pathname.exists !*_digests then
+ with_input_file !*_digests begin fun ic ->
+ try while true do
+ let l = input_line ic in
+ Scanf.sscanf l "%S: %S" put
+ done with End_of_file -> ()
+ end;
+ My_unix.at_exit_once finalize
diff --git a/ocamlbuild/digest_cache.mli b/ocamlbuild/digest_cache.mli
new file mode 100644
index 0000000000..82aa7f99eb
--- /dev/null
+++ b/ocamlbuild/digest_cache.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Original author: Nicolas Pouillard *)
+
+val init : unit -> unit
+
+val get : string -> string
+val put : string -> string -> unit
diff --git a/ocamlbuild/discard_printf.ml b/ocamlbuild/discard_printf.ml
new file mode 100644
index 0000000000..10bd64065f
--- /dev/null
+++ b/ocamlbuild/discard_printf.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+
+let discard_printf fmt = Format.ifprintf Format.std_formatter fmt;;
diff --git a/ocamlbuild/discard_printf.mli b/ocamlbuild/discard_printf.mli
new file mode 100644
index 0000000000..cf2b8cc272
--- /dev/null
+++ b/ocamlbuild/discard_printf.mli
@@ -0,0 +1,21 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Discard_printf *)
+
+(** This module compiled with [-rectypes] allows one to write functions
+ taking formatters as arguments. *)
+open Format
+val discard_printf: ('a, formatter, unit) format -> 'a
diff --git a/ocamlbuild/display.ml b/ocamlbuild/display.ml
new file mode 100644
index 0000000000..8ea5781aa7
--- /dev/null
+++ b/ocamlbuild/display.ml
@@ -0,0 +1,396 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Display *)
+open My_std;;
+
+open My_unix;;
+
+let fp = Printf.fprintf;;
+
+(*** ANSI *)
+module ANSI =
+ struct
+ let up oc n = fp oc "\027[%dA" n;;
+ let clear_to_eol oc () = fp oc "\027[K";;
+ let bol oc () = fp oc "\r";;
+ let get_columns () =
+ if Sys.os_type = "Unix" then
+ try
+ int_of_string (String.chomp (My_unix.run_and_read "tput cols"))
+ with
+ | Failure _ -> 80
+ else 80
+ end
+;;
+(* ***)
+(*** tagline_description *)
+type tagline_description = (string * char) list;;
+(* ***)
+(*** sophisticated_display *)
+type sophisticated_display = {
+ ds_channel : out_channel; (** Channel for writing *)
+ ds_start_time : float; (** When was compilation started *)
+ mutable ds_last_update : float; (** When was the display last updated *)
+ mutable ds_last_target : string; (** Last target built *)
+ mutable ds_last_cached : bool; (** Was the last target cached or really built ? *)
+ mutable ds_last_tags : Tags.t; (** Tags of the last command *)
+ mutable ds_changed : bool; (** Does the tag line need recomputing ? *)
+ ds_update_interval : float; (** Minimum interval between updates *)
+ ds_columns : int; (** Number of columns in dssplay *)
+ mutable ds_jobs : int; (** Number of jobs launched or cached *)
+ mutable ds_jobs_cached : int; (** Number of jobs cached *)
+ ds_tagline : bytes; (** Current tagline *)
+ mutable ds_seen_tags : Tags.t; (** Tags that we have encountered *)
+ ds_pathname_length : int; (** How much space for displaying pathnames ? *)
+ ds_tld : tagline_description; (** Description for the tagline *)
+};;
+(* ***)
+(*** display_line, display *)
+type display_line =
+| Classic
+| Sophisticated of sophisticated_display
+
+type display = {
+ di_log_level : int;
+ mutable di_log_channel : (Format.formatter * out_channel) option;
+ di_channel : out_channel;
+ di_formatter : Format.formatter;
+ di_display_line : display_line;
+ mutable di_finished : bool;
+}
+;;
+(* ***)
+(*** various defaults *)
+let default_update_interval = 0.05;;
+let default_tagline_description = [
+ "ocaml", 'O';
+ "native", 'N';
+ "byte", 'B';
+ "program", 'P';
+ "pp", 'R';
+ "debug", 'D';
+ "interf", 'I';
+ "link", 'L';
+];;
+
+(* NOT including spaces *)
+let countdown_chars = 8;;
+let jobs_chars = 3;;
+let jobs_cached_chars = 5;;
+let dots = "...";;
+let start_target = "STARTING";;
+let finish_target = "FINISHED";;
+let ticker_chars = 3;;
+let ticker_period = 0.25;;
+let ticker_animation = [|
+ "\\";
+ "|";
+ "/";
+ "-";
+|];;
+let cached = "*";;
+let uncached = " ";;
+let cache_chars = 1;;
+(* ***)
+(*** create_tagline *)
+let create_tagline description = Bytes.make (List.length description) '-';;
+(* ***)
+(*** create *)
+let create
+ ?(channel=stdout)
+ ?(mode:[`Classic|`Sophisticated] = `Sophisticated)
+ ?columns:(_columns=75)
+ ?(description = default_tagline_description)
+ ?log_file
+ ?(log_level=1)
+ ()
+ =
+ let log_channel =
+ match log_file with
+ | None -> None
+ | Some fn ->
+ let oc = open_out_gen [Open_text; Open_wronly; Open_creat; Open_trunc] 0o666 fn in
+ let f = Format.formatter_of_out_channel oc in
+ Format.fprintf f "### Starting build.\n";
+ Some (f, oc)
+ in
+
+ let display_line =
+ match mode with
+ | `Classic -> Classic
+ | `Sophisticated ->
+ (* We assume Unix is not degraded. *)
+ let n = ANSI.get_columns () in
+ let tag_chars = List.length description in
+ Sophisticated
+ { ds_channel = stdout;
+ ds_start_time = gettimeofday ();
+ ds_last_update = 0.0;
+ ds_last_target = start_target;
+ ds_last_tags = Tags.empty;
+ ds_last_cached = false;
+ ds_changed = false;
+ ds_update_interval = default_update_interval;
+ ds_columns = n;
+ ds_jobs = 0;
+ ds_jobs_cached = 0;
+ ds_tagline = create_tagline description;
+ ds_seen_tags = Tags.empty;
+ ds_pathname_length = n -
+ (countdown_chars + 1 + jobs_chars + 1 + jobs_cached_chars + 1 +
+ cache_chars + 1 + tag_chars + 1 + ticker_chars + 2);
+ ds_tld = description }
+ in
+ { di_log_level = log_level;
+ di_log_channel = log_channel;
+ di_channel = channel;
+ di_formatter = Format.formatter_of_out_channel channel;
+ di_display_line = display_line;
+ di_finished = false }
+;;
+(* ***)
+(*** print_time *)
+let print_time oc t =
+ let t = int_of_float t in
+ let s = t mod 60 in
+ let m = (t / 60) mod 60 in
+ let h = t / 3600 in
+ fp oc "%02d:%02d:%02d" h m s
+;;
+(* ***)
+(*** print_shortened_pathname *)
+let print_shortened_pathname length oc u =
+ assert(length >= 3);
+ let m = String.length u in
+ if m <= length then
+ begin
+ output_string oc u;
+ fp oc "%*s" (length - m) ""
+ end
+ else
+ begin
+ let n = String.length dots in
+ let k = length - n in
+ output_string oc dots;
+ output_substring oc u (m - k) k;
+ end
+(* ***)
+(*** Layout
+
+00000000001111111111222222222233333333334444444444555555555566666666667777777777
+01234567890123456789012345678901234567890123456789012345678901234567890123456789
+HH MM SS XXXX PATHNAME
+00:12:31 32 ( 26) ...lp4Filters/Camlp4LocationStripper.cmo * OBn-------------
+| | | | | \ tags
+| | | \ last target built \ cached ?
+| | |
+| | \ number of jobs cached
+| \ number of jobs
+\ elapsed time
+cmo mllib
+***)
+(*** redraw_sophisticated *)
+let redraw_sophisticated ds =
+ let t = gettimeofday () in
+ let oc = ds.ds_channel in
+ let dt = t -. ds.ds_start_time in
+ ds.ds_last_update <- t;
+ fp oc "%a" ANSI.bol ();
+ let ticker_phase = (abs (int_of_float (ceil (dt /. ticker_period)))) mod (Array.length ticker_animation) in
+ let ticker = ticker_animation.(ticker_phase) in
+ fp oc "%a %-4d (%-4d) %a %s %s %s"
+ print_time dt
+ ds.ds_jobs
+ ds.ds_jobs_cached
+ (print_shortened_pathname ds.ds_pathname_length) ds.ds_last_target
+ (if ds.ds_last_cached then cached else uncached)
+ (Bytes.to_string ds.ds_tagline)
+ ticker;
+ fp oc "%a%!" ANSI.clear_to_eol ()
+;;
+(* ***)
+(*** redraw *)
+let redraw = function
+ | Classic -> ()
+ | Sophisticated ds -> redraw_sophisticated ds
+;;
+(* ***)
+(*** finish_sophisticated *)
+let finish_sophisticated ?(how=`Success) ds =
+ let t = gettimeofday () in
+ let oc = ds.ds_channel in
+ let dt = t -. ds.ds_start_time in
+ match how with
+ | `Success|`Error ->
+ fp oc "%a" ANSI.bol ();
+ fp oc "%s %d target%s (%d cached) in %a."
+ (if how = `Error then
+ "Compilation unsuccessful after building"
+ else
+ "Finished,")
+ ds.ds_jobs
+ (if ds.ds_jobs = 1 then "" else "s")
+ ds.ds_jobs_cached
+ print_time dt;
+ fp oc "%a\n%!" ANSI.clear_to_eol ()
+ | `Quiet ->
+ fp oc "%a%a%!" ANSI.bol () ANSI.clear_to_eol ();
+;;
+(* ***)
+(*** sophisticated_display *)
+let sophisticated_display ds f =
+ fp ds.ds_channel "%a%a%!" ANSI.bol () ANSI.clear_to_eol ();
+ f ds.ds_channel
+;;
+(* ***)
+(*** call_if *)
+let call_if log_channel f =
+ match log_channel with
+ | None -> ()
+ | Some x -> f x
+;;
+(* ***)
+(*** display *)
+let display di f =
+ call_if di.di_log_channel (fun (_, oc) -> f oc);
+ match di.di_display_line with
+ | Classic -> f di.di_channel
+ | Sophisticated ds -> sophisticated_display ds f
+;;
+(* ***)
+(*** finish *)
+let finish ?(how=`Success) di =
+ if not di.di_finished then begin
+ di.di_finished <- true;
+ call_if di.di_log_channel
+ begin fun (fmt, oc) ->
+ Format.fprintf fmt "# Compilation %ssuccessful.@." (if how = `Error then "un" else "");
+ close_out oc;
+ di.di_log_channel <- None
+ end;
+ match di.di_display_line with
+ | Classic -> ()
+ | Sophisticated ds -> finish_sophisticated ~how ds
+ end
+;;
+(* ***)
+(*** update_tagline_from_tags *)
+let update_tagline_from_tags ds =
+ let tagline = ds.ds_tagline in
+ let tags = ds.ds_last_tags in
+ let rec loop i = function
+ | [] ->
+ for j = i to Bytes.length tagline - 1 do
+ Bytes.set tagline j '-'
+ done
+ | (tag, c) :: rest ->
+ if Tags.mem tag tags then
+ Bytes.set tagline i (Char.uppercase_ascii c)
+ else
+ if Tags.mem tag ds.ds_seen_tags then
+ Bytes.set tagline i (Char.lowercase_ascii c)
+ else
+ Bytes.set tagline i '-';
+ loop (i + 1) rest
+ in
+ loop 0 ds.ds_tld;
+;;
+(* ***)
+(*** update_sophisticated *)
+let update_sophisticated ds =
+ let t = gettimeofday () in
+ let dt = t -. ds.ds_last_update in
+ if dt > ds.ds_update_interval then
+ begin
+ if ds.ds_changed then
+ begin
+ update_tagline_from_tags ds;
+ ds.ds_changed <- false
+ end;
+ redraw_sophisticated ds
+ end
+ else
+ ()
+;;
+(* ***)
+(*** set_target_sophisticated *)
+let set_target_sophisticated ds target tags cached =
+ ds.ds_changed <- true;
+ ds.ds_last_target <- target;
+ ds.ds_last_tags <- tags;
+ ds.ds_jobs <- 1 + ds.ds_jobs;
+ if cached then ds.ds_jobs_cached <- 1 + ds.ds_jobs_cached;
+ ds.ds_last_cached <- cached;
+ ds.ds_seen_tags <- Tags.union ds.ds_seen_tags ds.ds_last_tags;
+ update_sophisticated ds
+;;
+
+let print_tags f tags =
+ let first = ref true in
+ Tags.iter begin fun tag ->
+ if !first then begin
+ first := false;
+ Format.fprintf f "%s" tag
+ end else Format.fprintf f ", %s" tag
+ end tags
+;;
+(* ***)
+(*** update *)
+let update di =
+ match di.di_display_line with
+ | Classic -> ()
+ | Sophisticated ds -> update_sophisticated ds
+;;
+(* ***)
+(*** event *)
+let event di ?(pretend=false) command target tags =
+ call_if di.di_log_channel
+ (fun (fmt, _) ->
+ Format.fprintf fmt "# Target: %s, tags: { %a }\n" target print_tags tags;
+ Format.fprintf fmt "%s%s@." command (if pretend then " # cached" else ""));
+ match di.di_display_line with
+ | Classic ->
+ if pretend then
+ begin
+ (* This should work, even on Windows *)
+ let command = Filename.basename command in
+ if di.di_log_level >= 2 then Format.fprintf di.di_formatter "[cache hit] %s\n%!" command
+ end
+ else
+ (if di.di_log_level >= 1 then Format.fprintf di.di_formatter "%s\n%!" command)
+ | Sophisticated ds ->
+ set_target_sophisticated ds target tags pretend;
+ update_sophisticated ds
+;;
+(* ***)
+(*** dprintf *)
+let is_logging di log_level = log_level <= di.di_log_level
+let dprintf ?(raw=false) ?(log_level=1) di fmt =
+ if log_level > di.di_log_level then Discard_printf.discard_printf fmt else
+ let fmt = if raw then fmt else "@[<2>"^^fmt^^"@]@." in
+ match di.di_display_line with
+ | Classic -> Format.fprintf di.di_formatter fmt
+ | Sophisticated _ ->
+ if log_level < 0 then
+ begin
+ display di ignore;
+ Format.fprintf di.di_formatter fmt
+ end
+ else
+ match di.di_log_channel with
+ | Some (f, _) -> Format.fprintf f fmt
+ | None -> Discard_printf.discard_printf fmt
+(* ***)
diff --git a/ocamlbuild/display.mli b/ocamlbuild/display.mli
new file mode 100644
index 0000000000..b00cd17d5b
--- /dev/null
+++ b/ocamlbuild/display.mli
@@ -0,0 +1,36 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Display *)
+
+type display
+type tagline_description = (string * char) list
+
+val create :
+ ?channel:out_channel ->
+ ?mode:[ `Classic | `Sophisticated ] ->
+ ?columns:int ->
+ ?description:tagline_description ->
+ ?log_file:string ->
+ ?log_level:int ->
+ unit ->
+ display
+
+val finish : ?how:[`Success|`Error|`Quiet] -> display -> unit
+val event : display -> ?pretend:bool -> string -> string -> Tags.t -> unit
+val display : display -> (out_channel -> unit) -> unit
+val update : display -> unit
+val is_logging : display -> int -> bool
+val dprintf : ?raw:bool -> ?log_level:int -> display -> ('a, Format.formatter, unit) format -> 'a
diff --git a/ocamlbuild/examples/example1/hello.ml b/ocamlbuild/examples/example1/hello.ml
new file mode 100644
index 0000000000..18e871c535
--- /dev/null
+++ b/ocamlbuild/examples/example1/hello.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let _ =
+ Printf.printf "Hello, %s ! My name is %s\n"
+ (if Array.length Sys.argv > 1 then Sys.argv.(1) else "stranger")
+ Sys.argv.(0)
+;;
diff --git a/ocamlbuild/examples/example2/greet.ml b/ocamlbuild/examples/example2/greet.ml
new file mode 100644
index 0000000000..10e3f78454
--- /dev/null
+++ b/ocamlbuild/examples/example2/greet.ml
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type how = Nicely | Badly;;
+
+let greet how who =
+ match how with Nicely -> Printf.printf "Hello, %s !\n" who
+ | Badly -> Printf.printf "Oh, here is that %s again.\n" who
+;;
diff --git a/ocamlbuild/examples/example2/hello.ml b/ocamlbuild/examples/example2/hello.ml
new file mode 100644
index 0000000000..c7a3c075b2
--- /dev/null
+++ b/ocamlbuild/examples/example2/hello.ml
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Greet
+
+let _ =
+ let name =
+ if Array.length Sys.argv > 1 then
+ Sys.argv.(1)
+ else
+ "stranger"
+ in
+ greet
+ (if name = "Caesar" then Nicely else Badly)
+ name;
+ Printf.printf "My name is %s\n" Sys.argv.(0)
+;;
diff --git a/ocamlbuild/examples/example3/epoch.ml b/ocamlbuild/examples/example3/epoch.ml
new file mode 100644
index 0000000000..c487c6fa37
--- /dev/null
+++ b/ocamlbuild/examples/example3/epoch.ml
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let _ =
+ let s = Num.num_of_string (Printf.sprintf "%.0f" (Unix.gettimeofday ())) in
+ let ps = Num.mult_num (Num.num_of_string "1000000000000") s in
+ Printf.printf "%s picoseconds have passed since January 1st, 1970.\n"
+ (Num.string_of_num ps)
+;;
diff --git a/ocamlbuild/examples/example3/make.sh b/ocamlbuild/examples/example3/make.sh
new file mode 100755
index 0000000000..e64152e11b
--- /dev/null
+++ b/ocamlbuild/examples/example3/make.sh
@@ -0,0 +1,44 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+set -e
+
+TARGET=epoch
+FLAGS="-libs unix,nums"
+OCAMLBUILD=ocamlbuild
+
+ocb()
+{
+ $OCAMLBUILD $FLAGS $*
+}
+
+rule() {
+ case $1 in
+ clean) ocb -clean;;
+ native) ocb $TARGET.native;;
+ byte) ocb $TARGET.byte;;
+ all) ocb $TARGET.native $TARGET.byte;;
+ depend) echo "Not needed.";;
+ *) echo "Unknown action $1";;
+ esac;
+}
+
+if [ $# -eq 0 ]; then
+ rule all
+else
+ while [ $# -gt 0 ]; do
+ rule $1;
+ shift
+ done
+fi
diff --git a/ocamlbuild/exit_codes.ml b/ocamlbuild/exit_codes.ml
new file mode 100644
index 0000000000..f4d440b445
--- /dev/null
+++ b/ocamlbuild/exit_codes.ml
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let rc_ok = 0
+let rc_usage = 1
+let rc_failure = 2
+let rc_invalid_argument = 3
+let rc_system_error = 4
+let rc_hygiene = 1
+let rc_circularity = 5
+let rc_solver_failed = 6
+let rc_ocamldep_error = 7
+let rc_lexing_error = 8
+let rc_build_error = 9
+let rc_executor_subcommand_failed = 10
+let rc_executor_subcommand_got_signal = 11
+let rc_executor_io_error = 12
+let rc_executor_excetptional_condition = 13
diff --git a/ocamlbuild/exit_codes.mli b/ocamlbuild/exit_codes.mli
new file mode 100644
index 0000000000..84d393edd3
--- /dev/null
+++ b/ocamlbuild/exit_codes.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val rc_ok : int
+val rc_usage : int
+val rc_failure : int
+val rc_invalid_argument : int
+val rc_system_error : int
+val rc_hygiene : int
+val rc_circularity : int
+val rc_solver_failed : int
+val rc_ocamldep_error : int
+val rc_lexing_error : int
+val rc_build_error : int
+val rc_executor_subcommand_failed : int
+val rc_executor_subcommand_got_signal : int
+val rc_executor_io_error : int
+val rc_executor_excetptional_condition : int
diff --git a/ocamlbuild/fda.ml b/ocamlbuild/fda.ml
new file mode 100644
index 0000000000..aeaa906634
--- /dev/null
+++ b/ocamlbuild/fda.ml
@@ -0,0 +1,83 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* FDA *)
+
+open Log
+open Hygiene
+;;
+
+exception Exit_hygiene_failed
+;;
+
+let laws =
+ [
+ { law_name = "Leftover OCaml compilation files";
+ law_rules = [Not ".cmo"; Not ".cmi"; Not ".cmx"; Not ".cma"; Not ".cmxa"];
+ law_penalty = Fail };
+ { law_name = "Leftover OCaml type annotation files";
+ law_rules = [Not ".annot"];
+ law_penalty = Warn };
+ { law_name = "Leftover object files";
+ law_rules = [Not ".o"; Not ".a"; Not ".so"; Not ".obj"; Not ".lib"; Not ".dll"];
+ law_penalty = Fail };
+ { law_name = "Leftover ocamlyacc-generated files";
+ law_rules = [Implies_not(".mly",".ml"); Implies_not(".mly",".mli")];
+ law_penalty = Fail };
+ { law_name = "Leftover ocamllex-generated files";
+ law_rules = [Implies_not(".mll",".ml")];
+ law_penalty = Fail };
+ { law_name = "Leftover dependency files";
+ law_rules = [Not ".ml.depends"; Not ".mli.depends"];
+ law_penalty = Fail }
+ ]
+
+let inspect entry =
+ dprintf 5 "Doing sanity checks";
+ let evil = ref false in
+ match Hygiene.check
+ ?sanitize:
+ begin
+ if !Options.sanitize then
+ Some(Pathname.concat !Options.build_dir !Options.sanitization_script)
+ else
+ None
+ end
+ laws entry
+ with
+ | [] -> ()
+ | stuff ->
+ List.iter
+ begin fun (law, msgs) ->
+ Printf.printf "%s: %s:\n"
+ (match law.law_penalty with
+ | Warn -> "Warning"
+ | Fail ->
+ if not !evil then
+ begin
+ Printf.printf "IMPORTANT: I cannot work with leftover compiled files.\n%!";
+ evil := true
+ end;
+ "ERROR")
+ law.law_name;
+ List.iter
+ begin fun msg ->
+ Printf.printf " %s\n" msg
+ end
+ msgs
+ end
+ stuff;
+ if !evil then raise Exit_hygiene_failed;
+;;
diff --git a/ocamlbuild/fda.mli b/ocamlbuild/fda.mli
new file mode 100644
index 0000000000..6b9cc05c63
--- /dev/null
+++ b/ocamlbuild/fda.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Fda *)
+
+exception Exit_hygiene_failed
+
+val inspect : bool Slurp.entry -> unit
diff --git a/ocamlbuild/findlib.ml b/ocamlbuild/findlib.ml
new file mode 100644
index 0000000000..648283f953
--- /dev/null
+++ b/ocamlbuild/findlib.ml
@@ -0,0 +1,199 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Romain Bardou *)
+
+open My_std
+open My_unix
+open Command
+
+type command_spec = Command.spec
+
+type error =
+ | Cannot_run_ocamlfind
+ | Dependency_not_found of string * string (* package, dependency *)
+ | Package_not_found of string
+ | Cannot_parse_query of string * string (* package, explaination *)
+
+exception Findlib_error of error
+
+let error x = raise (Findlib_error x)
+
+let string_of_error = function
+ | Cannot_run_ocamlfind ->
+ "Cannot run Ocamlfind."
+ | Dependency_not_found(p, d) ->
+ Printf.sprintf
+ "Ocamlfind returned \"%s\" as a dependency for package \"%s\" but does \
+not know this dependency." d p
+ | Package_not_found p ->
+ Printf.sprintf "Findlib package not found: \"%s\"." p
+ | Cannot_parse_query(p, e) ->
+ Printf.sprintf "Cannot parse Ocamlfind query for package \"%s\": %s" p e
+
+let report_error e =
+ prerr_endline (string_of_error e);
+ exit 2
+
+let ocamlfind = "ocamlfind"
+
+type package = {
+ name: string;
+ description: string;
+ version: string;
+ archives_byte: string;
+ archives_native: string;
+ link_options: string;
+ location: string;
+ dependencies: package list;
+}
+
+let packages = Hashtbl.create 42
+
+let run_and_parse lexer command =
+ Printf.ksprintf
+ (fun command -> lexer & Lexing.from_string & run_and_read command)
+ command
+
+let run_and_read command =
+ Printf.ksprintf run_and_read command
+
+let rec query name =
+ try
+ Hashtbl.find packages name
+ with Not_found ->
+ try
+ let n, d, v, a_byte, lo, l =
+ run_and_parse
+ (Lexers.ocamlfind_query Const.Source.ocamlfind_query)
+ "%s query -l -predicates byte %s" ocamlfind name
+ in
+ let a_native =
+ run_and_parse
+ (Lexers.trim_blanks Const.Source.ocamlfind_query)
+ "%s query -a-format -predicates native %s" ocamlfind name
+ in
+ let deps =
+ run_and_parse
+ (Lexers.blank_sep_strings Const.Source.ocamlfind_query)
+ "%s query -r -p-format %s" ocamlfind name
+ in
+ let deps = List.filter ((<>) n) deps in
+ let deps =
+ try
+ List.map query deps
+ with Findlib_error (Package_not_found dep_name) ->
+ (* Ocamlfind cannot find a package which it returned as a dependency.
+ This should not happen. *)
+ error (Dependency_not_found (name, dep_name))
+ in
+ let package = {
+ name = n;
+ description = d;
+ version = v;
+ archives_byte = a_byte;
+ archives_native = a_native;
+ link_options = lo;
+ location = l;
+ dependencies = deps;
+ } in
+ Hashtbl.add packages n package;
+ package
+ with
+ | Failure _ ->
+ (* TODO: Improve to differenciate whether ocamlfind cannot be
+ run or is not installed *)
+ error Cannot_run_ocamlfind
+ | Lexers.Error (s,_) ->
+ error (Cannot_parse_query (name, s))
+
+let split_nl s =
+ let x = ref [] in
+ let rec go s =
+ let pos = String.index s '\n' in
+ x := (String.before s pos)::!x;
+ go (String.after s (pos + 1))
+ in
+ try
+ go s
+ with Not_found -> !x
+
+let before_space s =
+ try
+ String.before s (String.index s ' ')
+ with Not_found -> s
+
+let list () =
+ List.map before_space (split_nl & run_and_read "%s list" ocamlfind)
+
+(* The closure algorithm is easy because the dependencies are already closed
+and sorted for each package. We only have to make the union. We could also
+make another ocamlfind query such as:
+ ocamlfind query -p-format -r package1 package2 ... *)
+let topological_closure l =
+ let add l x = if List.mem x l then l else x :: l in
+ let l = List.fold_left begin fun acc p ->
+ add (List.fold_left add acc p.dependencies) p
+ end [] l in
+ List.rev l
+
+module SSet = Set.Make(String)
+
+let add_atom a l = match a, l with
+ | A "", _ -> l
+ | _ -> a :: l
+
+let include_flags l =
+ let pkgs = topological_closure l in
+ let locations = List.fold_left begin fun acc p ->
+ SSet.add p.location acc
+ end SSet.empty pkgs in
+ let flags = [] in
+ (* includes *)
+ let flags =
+ List.fold_left begin fun acc l ->
+ add_atom (P l) (add_atom (A "-I") acc)
+ end flags (SSet.elements locations)
+ in
+ S (List.rev flags)
+let compile_flags_byte = include_flags
+let compile_flags_native = include_flags
+
+let link_flags f l =
+ let pkgs = topological_closure l in
+ let locations = List.fold_left begin fun acc p ->
+ SSet.add p.location acc
+ end SSet.empty pkgs in
+ let flags = [] in
+ (* includes *)
+ let flags =
+ List.fold_left begin fun acc l ->
+ add_atom (P l) (add_atom (A "-I") acc)
+ end flags (SSet.elements locations)
+ in
+ (* special link options *)
+ let flags =
+ List.fold_left begin fun acc x ->
+ add_atom (A x.link_options) acc
+ end flags pkgs
+ in
+ (* archives *)
+ let flags =
+ List.fold_left begin fun acc x ->
+ add_atom (A (f x)) acc
+ end flags pkgs
+ in
+ S (List.rev flags)
+let link_flags_byte = link_flags (fun x -> x.archives_byte)
+let link_flags_native = link_flags (fun x -> x.archives_native)
diff --git a/ocamlbuild/findlib.mli b/ocamlbuild/findlib.mli
new file mode 100644
index 0000000000..1065e6ee84
--- /dev/null
+++ b/ocamlbuild/findlib.mli
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Romain Bardou *)
+
+include Signatures.FINDLIB with type command_spec = Command.spec
diff --git a/ocamlbuild/flags.ml b/ocamlbuild/flags.ml
new file mode 100644
index 0000000000..b590918617
--- /dev/null
+++ b/ocamlbuild/flags.ml
@@ -0,0 +1,79 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open Command
+open Bool (* FIXME remove me *)
+open Tags.Operators
+
+type decl = {
+ tags: Tags.t;
+ flags: Command.spec;
+ deprecated: bool;
+}
+let flags_of_decl { flags; _ } = flags
+let tags_of_decl { tags; _ } = tags
+
+let all_decls = ref []
+
+let of_tags matched_tags =
+ S begin
+ List.fold_left begin fun acc { tags; flags; _ } ->
+ if Tags.does_match matched_tags tags then flags :: acc
+ else acc
+ end [] !all_decls
+ end
+
+let () = Command.tag_handler := of_tags
+
+let of_tag_list x = of_tags (Tags.of_list x)
+
+let add_decl decl =
+ all_decls := decl :: !all_decls
+
+let flag ?(deprecated=false) tags flags =
+ let tags = Tags.of_list tags in
+ add_decl { tags; flags; deprecated }
+
+let pflag tags ptag flags =
+ Param_tags.declare ptag
+ (fun param -> flag (Param_tags.make ptag param :: tags) (flags param))
+
+let add x xs = x :: xs
+let remove me = List.filter (fun x -> me <> x)
+
+let pretty_print { tags; flags; deprecated } =
+ let sflag = Command.string_of_command_spec flags in
+ let header = if deprecated then "deprecated flag" else "flag" in
+ let pp fmt = Log.raw_dprintf (-1) fmt in
+ pp "@[<2>%s@ {. %a .}@ %S@]@\n@\n" header Tags.print tags sflag
+
+let show_documentation () =
+ List.iter
+ (fun decl -> if not decl.deprecated then pretty_print decl)
+ !all_decls;
+ List.iter
+ (fun decl -> if decl.deprecated then pretty_print decl)
+ !all_decls;
+ let pp fmt = Log.raw_dprintf (-1) fmt in
+ pp "@."
+
+let used_tags = ref Tags.empty
+
+let mark_tag_used tag =
+ used_tags := Tags.add tag !used_tags
+
+let get_used_tags () =
+ List.fold_left (fun acc decl -> Tags.union acc decl.tags)
+ !used_tags !all_decls
diff --git a/ocamlbuild/flags.mli b/ocamlbuild/flags.mli
new file mode 100644
index 0000000000..d3738c3013
--- /dev/null
+++ b/ocamlbuild/flags.mli
@@ -0,0 +1,41 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+val of_tags : Tags.t -> Command.spec
+val of_tag_list : Tags.elt list -> Command.spec
+
+(* The ?deprecated parameter marks the flag declaration as deprecated,
+ because it is superseded by a different, better way to express the
+ same thing (eg. a parametrized tag). So far, it is only used when
+ showing documentation.
+
+ This flag is not exported in OCamlbuild_plugin interface for now. It
+ would make sense to let plugin authors deprecate their own flags,
+ but it has to be balanced again the simplicity of the plugin
+ interface exposed. If you're reading this as a plugin author that
+ has a real need for deprecation, drop us a note on the bugtracker. *)
+val flag : ?deprecated:bool -> Tags.elt list -> Command.spec -> unit
+
+val pflag : Tags.elt list -> string -> (string -> Command.spec) -> unit
+val add : 'a -> 'a list -> 'a list
+val remove : 'a -> 'a list -> 'a list
+
+val show_documentation : unit -> unit
+
+(** "useful" tags: they are used by a tag declaration, or have been
+ explicitly added with [mark_as_used] *)
+val get_used_tags : unit -> Tags.t
+
+val mark_tag_used : Tags.elt -> unit
diff --git a/ocamlbuild/glob.ml b/ocamlbuild/glob.ml
new file mode 100644
index 0000000000..7b1d61807a
--- /dev/null
+++ b/ocamlbuild/glob.ml
@@ -0,0 +1,414 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Glob *)
+open My_std;;
+open Bool;;
+include Glob_ast;;
+open Glob_lexer;;
+
+let sf = Printf.sprintf;;
+
+let brute_limit = 10;;
+
+(*** string_of_token *)
+let string_of_token = function
+| ATOM _ -> "ATOM"
+| AND -> "AND"
+| OR -> "OR"
+| NOT -> "NOT"
+| LPAR -> "LPAR"
+| RPAR -> "RPAR"
+| TRUE -> "TRUE"
+| FALSE -> "FALSE"
+| EOF -> "EOF"
+;;
+(* ***)
+(*** match_character_class *)
+let match_character_class cl c =
+ Bool.eval
+ begin function (c1,c2) ->
+ c1 <= c && c <= c2
+ end
+ cl
+;;
+(* ***)
+(*** NFA *)
+module NFA =
+ struct
+ type transition =
+ | QCLASS of character_class
+ | QEPSILON
+ ;;
+
+ module IS = Set.Make(struct type t = int let compare (x:t) y = compare x y let print = Format.pp_print_int end);;
+ module ISM = Map.Make(struct type t = IS.t let compare = IS.compare let print = IS.print end);;
+
+ type machine = {
+ mc_qi : IS.t;
+ mc_table : (character_class * IS.t) list array;
+ mc_qf : int;
+ mc_power_table : (char, IS.t ISM.t) Hashtbl.t
+ }
+
+ (*** build' *)
+ let build' p =
+ let count = ref 0 in
+ let transitions = ref [] in
+ let epsilons : (int * int) list ref = ref [] in
+ let state () = let id = !count in incr count; id in
+ let ( --> ) q1 t q2 =
+ match t with
+ | QEPSILON -> epsilons := (q1,q2) :: !epsilons; q1
+ | QCLASS cl -> transitions := (q1,cl,q2) :: !transitions; q1
+ in
+ (* Construit les transitions correspondant au motif donne et arrivant
+ * sur l'etat qf. Retourne l'etat d'origine. *)
+ let rec loop qf = function
+ | Epsilon -> qf
+ | Word u ->
+ let m = String.length u in
+ let q0 = state () in
+ let rec loop q i =
+ if i = m then
+ q0
+ else
+ begin
+ let q' =
+ if i = m - 1 then
+ qf
+ else
+ state ()
+ in
+ let _ = (q --> QCLASS(Atom(u.[i], u.[i]))) q' in
+ loop q' (i + 1)
+ end
+ in
+ loop q0 0
+ | Class cl ->
+ let q1 = state () in
+ (q1 --> QCLASS cl) qf
+ | Star p ->
+ (* The fucking Kleene star *)
+ let q2 = state () in
+ let q1 = loop q2 p in (* q1 -{p}-> q2 *)
+ let _ = (q1 --> QEPSILON) qf in
+ let _ = (q2 --> QEPSILON) q1 in
+ let _ = (q2 --> QEPSILON) q1 in
+ q1
+ | Concat(p1,p2) ->
+ let q12 = state () in
+ let q1 = loop q12 p1 in (* q1 -{p1}-> q12 *)
+ let q2 = loop qf p2 in (* q2 -{p2}-> qf *)
+ let _ = (q12 --> QEPSILON) q2 in
+ q1
+ | Union pl ->
+ let qi = state () in
+ List.iter
+ begin fun p ->
+ let q = loop qf p in (* q -{p2}-> qf *)
+ let _ = (qi --> QEPSILON) q in (* qi -{}---> q *)
+ ()
+ end
+ pl;
+ qi
+ in
+ let qf = state () in
+ let qi = loop qf p in
+ let m = !count in
+
+ (* Compute epsilon closure *)
+ let graph = Array.make m IS.empty in
+ List.iter
+ begin fun (q,q') ->
+ graph.(q) <- IS.add q' graph.(q)
+ end
+ !epsilons;
+
+ let closure = Array.make m IS.empty in
+ let rec transitive past = function
+ | [] -> past
+ | q :: future ->
+ let past' = IS.add q past in
+ let future' =
+ IS.fold
+ begin fun q' future' ->
+ (* q -{}--> q' *)
+ if IS.mem q' past' then
+ future'
+ else
+ q' :: future'
+ end
+ graph.(q)
+ future
+ in
+ transitive past' future'
+ in
+ for i = 0 to m - 1 do
+ closure.(i) <- transitive IS.empty [i] (* O(n^2), I know *)
+ done;
+
+ (* Finally, build the table *)
+ let table = Array.make m [] in
+ List.iter
+ begin fun (q,t,q') ->
+ table.(q) <- (t, closure.(q')) :: table.(q)
+ end
+ !transitions;
+
+ (graph, closure,
+ { mc_qi = closure.(qi);
+ mc_table = table;
+ mc_qf = qf;
+ mc_power_table = Hashtbl.create 37 })
+ ;;
+ let build x = let (_,_, machine) = build' x in machine;;
+ (* ***)
+ (*** run *)
+ let run ?(trace=false) machine u =
+ let m = String.length u in
+ let apply qs c =
+ try
+ let t = Hashtbl.find machine.mc_power_table c in
+ ISM.find qs t
+ with
+ | Not_found ->
+ let qs' =
+ IS.fold
+ begin fun q qs' ->
+ List.fold_left
+ begin fun qs' (cl,qs'') ->
+ if match_character_class cl c then
+ IS.union qs' qs''
+ else
+ qs'
+ end
+ qs'
+ machine.mc_table.(q)
+ end
+ qs
+ IS.empty
+ in
+ let t =
+ try
+ Hashtbl.find machine.mc_power_table c
+ with
+ | Not_found -> ISM.empty
+ in
+ Hashtbl.replace machine.mc_power_table c (ISM.add qs qs' t);
+ qs'
+ in
+ let rec loop qs i =
+ if IS.is_empty qs then
+ false
+ else
+ begin
+ if i = m then
+ IS.mem machine.mc_qf qs
+ else
+ begin
+ let c = u.[i] in
+ if trace then
+ begin
+ Printf.printf "%d %C {" i c;
+ IS.iter (fun q -> Printf.printf " %d" q) qs;
+ Printf.printf " }\n%!"
+ end;
+ let qs' = apply qs c in
+ loop qs' (i + 1)
+ end
+ end
+ in
+ loop machine.mc_qi 0
+ ;;
+ (* ***)
+ end
+;;
+(* ***)
+(*** Brute *)
+module Brute =
+ struct
+ exception Succeed;;
+ exception Fail;;
+ exception Too_hard;;
+
+ (*** match_pattern *)
+ let match_pattern counter p u =
+ let m = String.length u in
+ (** [loop i n p] returns [true] iff the word [u.(i .. i + n - 1)] is in the
+ ** language generated by the pattern [p].
+ ** We must have 0 <= i and i + n <= m *)
+ let rec loop (i,n,p) =
+ assert (0 <= i && 0 <= n && i + n <= m);
+ incr counter;
+ if !counter >= brute_limit then raise Too_hard;
+ match p with
+ | Word v ->
+ String.length v = n &&
+ begin
+ let rec check j = j = n || (v.[j] = u.[i + j] && check (j + 1))
+ in
+ check 0
+ end
+ | Epsilon -> n = 0
+ | Star(Class True) -> true
+ | Star(Class cl) ->
+ let rec check k =
+ if k = n then
+ true
+ else
+ (match_character_class cl u.[i + k]) && check (k + 1)
+ in
+ check 0
+ | Star _ -> raise Too_hard
+ | Class cl -> n = 1 && match_character_class cl u.[i]
+ | Concat(p1,p2) ->
+ let rec scan j =
+ j <= n && ((loop (i,j,p1) && loop (i+j, n - j,p2)) || scan (j + 1))
+ in
+ scan 0
+ | Union pl -> List.exists (fun p' -> loop (i,n,p')) pl
+ in
+ loop (0,m,p)
+ ;;
+ (* ***)
+end
+;;
+(* ***)
+(*** fast_pattern_contents, fast_pattern, globber *)
+type fast_pattern_contents =
+| Brute of int ref * pattern
+| Machine of NFA.machine
+;;
+type fast_pattern = fast_pattern_contents ref;;
+type globber = fast_pattern atom Bool.boolean;;
+(* ***)
+(*** fast_pattern_of_pattern *)
+let fast_pattern_of_pattern p = ref (Brute(ref 0, p));;
+(* ***)
+(*** add_dir *)
+let add_dir dir x =
+ match dir with
+ | None -> x
+ | Some(dir) ->
+ match x with
+ | Constant(s) ->
+ Constant(My_std.filename_concat dir s)
+ | Pattern(p) ->
+ Pattern(Concat(Word(My_std.filename_concat dir ""), p))
+;;
+(* ***)
+(*** add_ast_dir *)
+let add_ast_dir dir x =
+ match dir with
+ | None -> x
+ | Some dir ->
+ let slash = Class(Atom('/','/')) in
+ let any = Class True in
+ let q = Union[Epsilon; Concat(slash, Star any)] in (* ( /** )? *)
+ And[Atom(Pattern(ref (Brute(ref 0, Concat(Word dir, q))))); x]
+;;
+(* ***)
+(*** parse *)
+let parse ?dir u =
+ let l = Lexing.from_string u in
+ let tok = ref None in
+ let f =
+ fun () ->
+ match !tok with
+ | None -> token l
+ | Some x ->
+ tok := None;
+ x
+ in
+ let g t =
+ match !tok with
+ | None -> tok := Some t
+ | Some t' ->
+ raise (Parse_error(sf "Trying to unput token %s while %s is active" (string_of_token t) (string_of_token t')))
+ in
+ let read x =
+ let y = f () in
+ if x = y then
+ ()
+ else
+ raise (Parse_error(sf "Unexpected token, expecting %s, got %s" (string_of_token x) (string_of_token y)))
+ in
+ let rec atomizer continuation = match f () with
+ | NOT -> atomizer (fun x -> continuation (Not x))
+ | ATOM x ->
+ begin
+ let a =
+ match add_dir dir x with
+ | Constant u -> Constant u
+ | Pattern p -> Pattern(fast_pattern_of_pattern p)
+ in
+ continuation (Atom a)
+ end
+ | TRUE -> continuation True
+ | FALSE -> continuation False
+ | LPAR ->
+ let y = parse_s () in
+ read RPAR;
+ continuation y
+ | t -> raise (Parse_error(sf "Unexpected token %s in atomizer" (string_of_token t)))
+ and parse_s1 x = match f () with
+ | OR -> let y = parse_s () in Or[x; y]
+ | AND -> parse_t x
+ | t -> g t; x
+ and parse_t1 x y = match f () with
+ | OR -> let z = parse_s () in Or[And[x;y]; z]
+ | AND -> parse_t (And[x;y])
+ | t -> g t; And[x;y]
+ and parse_s () = atomizer parse_s1
+ and parse_t x = atomizer (parse_t1 x)
+ in
+ let x = parse_s () in
+ read EOF;
+ add_ast_dir dir x
+;;
+(* ***)
+(*** eval *)
+let eval g u =
+ Bool.eval
+ begin function
+ | Constant v -> u = v
+ | Pattern kind ->
+ match !kind with
+ | Brute(count, p) ->
+ begin
+ let do_nfa () =
+ let m = NFA.build p in
+ kind := Machine m;
+ NFA.run m u
+ in
+ if !count >= brute_limit then
+ do_nfa ()
+ else
+ try
+ Brute.match_pattern count p u
+ with
+ | Brute.Too_hard -> do_nfa ()
+ end
+ | Machine m -> NFA.run m u
+ end
+ g
+(* ***)
+(*** Debug *)
+(*let (Atom(Pattern x)) = parse "<{a,b}>";;
+#install_printer IS.print;;
+#install_printer ISM.print;;
+let (graph, closure, machine) = build' x;;*)
+(* ***)
diff --git a/ocamlbuild/glob.mli b/ocamlbuild/glob.mli
new file mode 100644
index 0000000000..eda8100a44
--- /dev/null
+++ b/ocamlbuild/glob.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Glob *)
+
+(** The type representing fast patterns. Do not attempt to compare them, as they get on-the-fly optimizations. *)
+type fast_pattern
+
+(** A self-contained module implementing extended shell glob patterns who have an expressive power
+ equal to boolean combinations of regular expressions. *)
+include Signatures.GLOB with type globber = fast_pattern Glob_ast.atom Bool.boolean
+
+val fast_pattern_of_pattern : Glob_ast.pattern -> fast_pattern
diff --git a/ocamlbuild/glob_ast.ml b/ocamlbuild/glob_ast.ml
new file mode 100644
index 0000000000..1d0f5533b3
--- /dev/null
+++ b/ocamlbuild/glob_ast.ml
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Glob_ast *)
+
+exception Parse_error of string;;
+
+type pattern =
+| Epsilon
+| Star of pattern (* The fucking Kleene star *)
+| Class of character_class
+| Concat of pattern * pattern
+| Union of pattern list
+| Word of string
+and character_class = (char * char) Bool.boolean
+;;
+
+type 'pattern atom =
+| Constant of string
+| Pattern of 'pattern
+;;
diff --git a/ocamlbuild/glob_ast.mli b/ocamlbuild/glob_ast.mli
new file mode 100644
index 0000000000..49e8c39d19
--- /dev/null
+++ b/ocamlbuild/glob_ast.mli
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Glob_ast *)
+
+exception Parse_error of string
+type pattern =
+| Epsilon
+| Star of pattern
+| Class of character_class
+| Concat of pattern * pattern
+| Union of pattern list
+| Word of string
+and character_class = (char * char) Bool.boolean
+type 'pattern atom = Constant of string | Pattern of 'pattern
diff --git a/ocamlbuild/glob_lexer.mli b/ocamlbuild/glob_lexer.mli
new file mode 100644
index 0000000000..4bbcf4a538
--- /dev/null
+++ b/ocamlbuild/glob_lexer.mli
@@ -0,0 +1,29 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+open Glob_ast
+
+type token =
+| ATOM of pattern atom
+| AND
+| OR
+| NOT
+| LPAR
+| RPAR
+| TRUE
+| FALSE
+| EOF
+
+val token : Lexing.lexbuf -> token
diff --git a/ocamlbuild/glob_lexer.mll b/ocamlbuild/glob_lexer.mll
new file mode 100644
index 0000000000..0cbef8a9b5
--- /dev/null
+++ b/ocamlbuild/glob_lexer.mll
@@ -0,0 +1,118 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Glob *)
+{
+open Bool;;
+open Glob_ast;;
+
+type token =
+| ATOM of pattern atom
+| AND
+| OR
+| NOT
+| LPAR
+| RPAR
+| TRUE
+| FALSE
+| EOF
+;;
+
+let sf = Printf.sprintf;;
+
+let concat_patterns p1 p2 =
+ match (p1,p2) with
+ | (Epsilon,_) -> p2
+ | (_,Epsilon) -> p1
+ | (_,_) -> Concat(p1,p2)
+;;
+
+let slash = Class(Atom('/','/'));;
+let not_slash = Class(Not(Atom('/','/')));;
+let any = Class True;;
+}
+
+let pattern_chars = ['a'-'z']|['A'-'Z']|'_'|'-'|['0'-'9']|'.'
+let space_chars = [' ' '\t' '\n' '\r' '\012']
+
+rule token = parse
+| '<' { ATOM(Pattern(let (p,_) = parse_pattern ['>'] Epsilon lexbuf in p)) }
+| '"' { ATOM(Constant(parse_string (Buffer.create 32) lexbuf)) }
+| "and"|"AND"|"&" { AND }
+| "or"|"OR"|"|" { OR }
+| "not"|"NOT"|"~" { NOT }
+| "true"|"1" { TRUE }
+| "false"|"0" { FALSE }
+| "(" { LPAR }
+| ")" { RPAR }
+| space_chars+ { token lexbuf }
+| eof { EOF }
+
+and parse_pattern eof_chars p = parse
+| (pattern_chars+ as u) { parse_pattern eof_chars (concat_patterns p (Word u)) lexbuf }
+| '{'
+ {
+ let rec loop pl =
+ let (p',c) = parse_pattern ['}';','] Epsilon lexbuf in
+ let pl = p' :: pl in
+ if c = ',' then
+ loop pl
+ else
+ parse_pattern eof_chars (concat_patterns p (Union pl)) lexbuf
+ in
+ loop []
+ }
+| "[^"
+ {
+ let cl = Not(Or(parse_class [] lexbuf)) in
+ parse_pattern eof_chars (concat_patterns p (Class cl)) lexbuf
+ }
+| '['
+ {
+ let cl = Or(parse_class [] lexbuf) in
+ parse_pattern eof_chars (concat_patterns p (Class cl)) lexbuf
+ }
+(* Random thought... **/* seems to be equal to True *)
+| "/**/" (* / | /\Sigma^*/ *)
+ { let q = Union[slash; Concat(slash, Concat(Star any, slash)) ] in
+ parse_pattern eof_chars (concat_patterns p q) lexbuf }
+| "/**" (* \varepsilon | /\Sigma^* *)
+ { let q = Union[Epsilon; Concat(slash, Star any)] in
+ parse_pattern eof_chars (concat_patterns p q) lexbuf }
+| "**/" (* \varepsilon | \Sigma^*/ *)
+ { let q = Union[Epsilon; Concat(Star any, slash)] in
+ parse_pattern eof_chars (concat_patterns p q) lexbuf }
+| "**" { raise (Parse_error("Ambiguous ** pattern not allowed unless surrounded by one or more slashes")) }
+| '*' { parse_pattern eof_chars (concat_patterns p (Star not_slash)) lexbuf }
+| '/' { parse_pattern eof_chars (concat_patterns p slash) lexbuf }
+| '?' { parse_pattern eof_chars (concat_patterns p not_slash) lexbuf }
+| _ as c
+ { if List.mem c eof_chars then
+ (p,c)
+ else
+ raise (Parse_error(sf "Unexpected character %C in glob pattern" c))
+ }
+
+and parse_string b = parse
+| "\"" { Buffer.contents b }
+| "\\\"" { Buffer.add_char b '"'; parse_string b lexbuf }
+| [^'"' '\\']+ as u { Buffer.add_string b u; parse_string b lexbuf }
+| _ as c { raise (Parse_error(sf "Unexpected character %C in string" c)) }
+
+and parse_class cl = parse
+| ']' { cl }
+| "-]" { ((Atom('-','-'))::cl) }
+| (_ as c1) '-' (_ as c2) { parse_class ((Atom(c1,c2))::cl) lexbuf }
+| _ as c { parse_class ((Atom(c,c))::cl) lexbuf }
diff --git a/ocamlbuild/hooks.ml b/ocamlbuild/hooks.ml
new file mode 100644
index 0000000000..94013c532d
--- /dev/null
+++ b/ocamlbuild/hooks.ml
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+type message =
+ | Before_hygiene
+ | After_hygiene
+ | Before_options
+ | After_options
+ | Before_rules
+ | After_rules
+
+let hooks = ref ignore
+
+let setup_hooks f = hooks := f
+
+let call_hook m = !hooks m
diff --git a/ocamlbuild/hooks.mli b/ocamlbuild/hooks.mli
new file mode 100644
index 0000000000..0027790251
--- /dev/null
+++ b/ocamlbuild/hooks.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+type message =
+ | Before_hygiene
+ | After_hygiene
+ | Before_options
+ | After_options
+ | Before_rules
+ | After_rules
+
+val setup_hooks : (message -> unit) -> unit
+val call_hook : message -> unit
diff --git a/ocamlbuild/hygiene.ml b/ocamlbuild/hygiene.ml
new file mode 100644
index 0000000000..f1febdee04
--- /dev/null
+++ b/ocamlbuild/hygiene.ml
@@ -0,0 +1,177 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Hygiene *)
+open My_std
+open Slurp
+
+exception Exit_hygiene_violations
+
+type rule =
+| Implies_not of pattern * pattern
+| Not of pattern
+and pattern = suffix
+and suffix = string
+
+type penalty = Warn | Fail
+
+type law = {
+ law_name : string;
+ law_rules : rule list;
+ law_penalty : penalty
+}
+
+let list_collect f l =
+ let rec loop result = function
+ | [] -> List.rev result
+ | x :: rest ->
+ match f x with
+ | None -> loop result rest
+ | Some y -> loop (y :: result) rest
+ in
+ loop [] l
+
+let list_none_for_all f l =
+ let rec loop = function
+ | [] -> None
+ | x :: rest ->
+ match f x with
+ | None -> loop rest
+ | y -> y
+ in
+ loop l
+
+let sf = Printf.sprintf
+
+module SS = Set.Make(String);;
+
+let check ?sanitize laws entry =
+ let penalties = ref [] in
+ let microbes = ref SS.empty in
+ let () =
+ match sanitize with
+ | Some fn -> if sys_file_exists fn then sys_remove fn
+ | None -> ()
+ in
+ let remove path name =
+ if sanitize <> None then
+ microbes := SS.add (filename_concat path name) !microbes
+ in
+ let check_rule = fun entries -> function
+ | Not suffix ->
+ list_collect
+ begin function
+ | File(path, name, _, true) ->
+ if Filename.check_suffix name suffix
+ && not ( Pathname.link_to_dir (filename_concat path name) !Options.build_dir ) then
+ begin
+ remove path name;
+ Some(sf "File %s in %s has suffix %s" name path suffix)
+ end
+ else
+ None
+ | File _ | Dir _| Error _ | Nothing -> None
+ end
+ entries
+ | Implies_not(suffix1, suffix2) ->
+ list_collect
+ begin function
+ | File(path, name, _, true) ->
+ if Filename.check_suffix name suffix1 then
+ begin
+ let base = Filename.chop_suffix name suffix1 in
+ let name' = base ^ suffix2 in
+ if List.exists
+ begin function
+ | File(_, name'', _, true) -> name' = name''
+ | File _ | Dir _ | Error _ | Nothing -> false
+ end
+ entries
+ then
+ begin
+ remove path name';
+ Some(sf "Files %s and %s should not be together in %s" name name' path)
+ end
+ else
+ None
+ end
+ else
+ None
+ | File _ | Dir _ | Error _ | Nothing -> None
+ end
+ entries
+ in
+ let rec check_entry = function
+ | Dir(_,_,_,true,entries) ->
+ List.iter
+ begin fun law ->
+ match List.concat (List.map (check_rule !*entries) law.law_rules) with
+ | [] -> ()
+ | explanations ->
+ penalties := (law, explanations) :: !penalties
+ end
+ laws;
+ List.iter check_entry !*entries
+ | Dir _ | File _ | Error _ | Nothing -> ()
+ in
+ check_entry entry;
+ begin
+ let microbes = !microbes in
+ if not (SS.is_empty microbes) then
+ begin
+ match sanitize with
+ | None ->
+ Log.eprintf "sanitize: the following are files that should probably not be in your\n\
+ source tree:\n";
+ SS.iter
+ begin fun fn ->
+ Log.eprintf " %s" fn
+ end
+ microbes;
+ Log.eprintf "Remove them manually, don't use the -no-sanitize option, use -no-hygiene, or\n\
+ define hygiene exceptions using the tags or plugin mechanism.\n";
+ raise Exit_hygiene_violations
+ | Some fn ->
+ let m = SS.cardinal microbes in
+ Log.eprintf
+ "@[<hov 2>SANITIZE:@ a@ total@ of@ %d@ file%s@ that@ should@ probably\
+ @ not@ be@ in@ your@ source@ tree@ has@ been@ found.\
+ @ A@ script@ shell@ file@ %S@ is@ being@ created.\
+ @ Check@ this@ script@ and@ run@ it@ to@ remove@ unwanted@ files\
+ @ or@ use@ other@ options@ (such@ as@ defining@ hygiene@ exceptions\
+ @ or@ using@ the@ -no-hygiene@ option).@]"
+ m (if m = 1 then "" else "s") fn;
+ let oc = open_out_gen [Open_wronly; Open_creat; Open_trunc; Open_binary] 0o777 fn in
+ (* See PR #5338: under mingw, one produces a shell script, which must follow
+ Unix eol convention; hence Open_binary. *)
+ let fp = Printf.fprintf in
+ fp oc "#!/bin/sh\n\
+ # File generated by ocamlbuild\n\
+ \n\
+ cd %s\n\
+ \n" (Shell.quote_filename_if_needed Pathname.pwd);
+ SS.iter
+ begin fun fn ->
+ fp oc "rm -f %s\n" (Shell.quote_filename_if_needed fn)
+ end
+ microbes;
+ (* Also clean itself *)
+ fp oc "# Also clean the script itself\n";
+ fp oc "rm -f %s\n" (Shell.quote_filename_if_needed fn);
+ close_out oc
+ end;
+ !penalties
+ end
+;;
diff --git a/ocamlbuild/hygiene.mli b/ocamlbuild/hygiene.mli
new file mode 100644
index 0000000000..a818a3d5b3
--- /dev/null
+++ b/ocamlbuild/hygiene.mli
@@ -0,0 +1,48 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Hygiene *)
+
+(** Module for checking that the source tree is not polluted by object files. *)
+
+(** Sanity rules to abide. Not to be confused with compilation rules. *)
+type rule =
+ Implies_not of pattern * pattern (** The rule [Implies_not(".mll",".ml")] is broken if there is a file [foo.mll]
+ together with a file [foo.ml] int the same directory. The second file can
+ get sanitized. *)
+| Not of pattern (* No files with suffix [pattern] will be tolerated. *)
+
+(** Suffix matching is enough for the purpose of this module. *)
+and pattern = suffix
+
+(** And a suffix is a string. *)
+and suffix = string
+
+(** A warning is simply displayed. A failures stops the compilation. *)
+type penalty = Warn | Fail
+
+(** This type is used to encode laws that will be checked by this module. *)
+type law = {
+ law_name : string; (** The name of the law that will be printed when it is violated. *)
+ law_rules : rule list; (** Breaking any of these rules is breaking this law. *)
+ law_penalty : penalty; (** Breaking the law gives you either a warning or a failure. *)
+}
+
+(** [check ~sanitize laws entry] will scan the directory tree [entry] for violation to the given [laws].
+ Any warnings or errors will be printed on the [stdout]. If [sanitize] is [Some fn], a shell script will be written
+ into the file [fn] with commands to delete the offending files. The command will return a pair [(fatal, penalties)]
+ where [fatal] is [true] when serious hygiene violations have been spotted, and [penalties] is a list of laws and
+ messages describing the offenses. *)
+val check : ?sanitize:string -> law list -> bool Slurp.entry -> (law * string list) list
diff --git a/ocamlbuild/lexers.mli b/ocamlbuild/lexers.mli
new file mode 100644
index 0000000000..800e0faaa1
--- /dev/null
+++ b/ocamlbuild/lexers.mli
@@ -0,0 +1,49 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+exception Error of (string * Loc.location)
+
+type conf_values =
+ { plus_tags : (string * Loc.location) list;
+ minus_tags : (string * Loc.location) list }
+
+type conf = (Glob.globber * conf_values) list
+
+val ocamldep_output : Loc.source -> Lexing.lexbuf -> (string * string list) list
+val space_sep_strings : Loc.source -> Lexing.lexbuf -> string list
+val blank_sep_strings : Loc.source -> Lexing.lexbuf -> string list
+val comma_sep_strings : Loc.source -> Lexing.lexbuf -> string list
+val comma_or_blank_sep_strings : Loc.source -> Lexing.lexbuf -> string list
+val trim_blanks : Loc.source -> Lexing.lexbuf -> string
+
+(* Parse an environment path (i.e. $PATH).
+ This is a colon separated string.
+ Note: successive colons means an empty string.
+ Example:
+ ":aaa:bbb:::ccc:" -> [""; "aaa"; "bbb"; ""; ""; "ccc"; ""] *)
+val parse_environment_path : Loc.source -> Lexing.lexbuf -> string list
+(* Same one, for Windows (PATH is ;-separated) *)
+val parse_environment_path_w : Loc.source -> Lexing.lexbuf -> string list
+
+val conf_lines : string option -> Loc.source -> Lexing.lexbuf -> conf
+val path_scheme : bool -> Loc.source -> Lexing.lexbuf ->
+ [ `Word of string
+ | `Var of (string * Glob.globber)
+ ] list
+
+val ocamlfind_query : Loc.source -> Lexing.lexbuf ->
+ string * string * string * string * string * string
+
+val tag_gen : Loc.source -> Lexing.lexbuf -> string * string option
diff --git a/ocamlbuild/lexers.mll b/ocamlbuild/lexers.mll
new file mode 100644
index 0000000000..b34231f076
--- /dev/null
+++ b/ocamlbuild/lexers.mll
@@ -0,0 +1,192 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+{
+exception Error of (string * Loc.location)
+
+let error source lexbuf fmt =
+ Printf.ksprintf (fun s ->
+ raise (Error (s, Loc.of_lexbuf source lexbuf))
+ ) fmt
+
+open Glob_ast
+
+type conf_values =
+ { plus_tags : (string * Loc.location) list;
+ minus_tags : (string * Loc.location) list }
+
+type conf = (Glob.globber * conf_values) list
+
+let empty = { plus_tags = []; minus_tags = [] }
+
+let locate source lexbuf txt =
+ (txt, Loc.of_lexbuf source lexbuf)
+
+let sublex lexer s = lexer (Lexing.from_string s)
+}
+
+let newline = ('\n' | '\r' | "\r\n")
+let space = [' ' '\t' '\012']
+let space_or_esc_nl = (space | '\\' newline)
+let sp = space_or_esc_nl
+let blank = newline | space
+let not_blank = [^' ' '\t' '\012' '\n' '\r']
+let not_space_nor_comma = [^' ' '\t' '\012' ',']
+let not_newline = [^ '\n' '\r' ]
+let not_newline_nor_colon = [^ '\n' '\r' ':' ]
+let normal_flag_value = [^ '(' ')' '\n' '\r']
+let normal = [^ ':' ',' '(' ')' ''' ' ' '\n' '\r']
+let tag = normal+ | ( normal+ ':' normal+ ) | normal+ '(' [^ ')' ]* ')'
+let variable = [ 'a'-'z' 'A'-'Z' '_' '-' '0'-'9' ]*
+let pattern = ([^ '(' ')' '\\' ] | '\\' [ '(' ')' ])*
+
+rule ocamldep_output source = parse
+ | ([^ ':' '\n' '\r' ]+ as k) ':' { let x = (k, space_sep_strings_nl source lexbuf) in x :: ocamldep_output source lexbuf }
+ | eof { [] }
+ | _ { error source lexbuf "Expecting colon followed by space-separated module name list" }
+
+and space_sep_strings_nl source = parse
+ | space* (not_blank+ as word) { word :: space_sep_strings_nl source lexbuf }
+ | space* newline { Lexing.new_line lexbuf; [] }
+ | _ { error source lexbuf "Expecting space-separated strings terminated with newline" }
+
+and space_sep_strings source = parse
+ | space* (not_blank+ as word) { word :: space_sep_strings source lexbuf }
+ | space* newline? eof { [] }
+ | _ { error source lexbuf "Expecting space-separated strings" }
+
+and blank_sep_strings source = parse
+ | blank* '#' not_newline* newline { blank_sep_strings source lexbuf }
+ | blank* '#' not_newline* eof { [] }
+ | blank* (not_blank+ as word) { word :: blank_sep_strings source lexbuf }
+ | blank* eof { [] }
+ | _ { error source lexbuf "Expecting blank-separated strings" }
+
+and comma_sep_strings source = parse
+ | space* (not_space_nor_comma+ as word) space* eof { [word] }
+ | space* (not_space_nor_comma+ as word) { word :: comma_sep_strings_aux source lexbuf }
+ | space* eof { [] }
+ | _ { error source lexbuf "Expecting comma-separated strings (1)" }
+and comma_sep_strings_aux source = parse
+ | space* ',' space* (not_space_nor_comma+ as word) { word :: comma_sep_strings_aux source lexbuf }
+ | space* eof { [] }
+ | _ { error source lexbuf "Expecting comma-separated strings (2)" }
+
+and comma_or_blank_sep_strings source = parse
+ | space* (not_space_nor_comma+ as word) space* eof { [word] }
+ | space* (not_space_nor_comma+ as word) { word :: comma_or_blank_sep_strings_aux source lexbuf }
+ | space* eof { [] }
+ | _ { error source lexbuf "Expecting (comma|blank)-separated strings (1)" }
+and comma_or_blank_sep_strings_aux source = parse
+ | space* ',' space* (not_space_nor_comma+ as word) { word :: comma_or_blank_sep_strings_aux source lexbuf }
+ | space* (not_space_nor_comma+ as word) { word :: comma_or_blank_sep_strings_aux source lexbuf }
+ | space* eof { [] }
+ | _ { error source lexbuf "Expecting (comma|blank)-separated strings (2)" }
+
+and parse_environment_path_w source = parse
+ | ([^ ';']* as word) { word :: parse_environment_path_aux_w source lexbuf }
+ | ';' ([^ ';']* as word) { "" :: word :: parse_environment_path_aux_w source lexbuf }
+ | eof { [] }
+and parse_environment_path_aux_w source = parse
+ | ';' ([^ ';']* as word) { word :: parse_environment_path_aux_w source lexbuf }
+ | eof { [] }
+ | _ { error source lexbuf "Impossible: expecting colon-separated strings" }
+
+and parse_environment_path source = parse
+ | ([^ ':']* as word) { word :: parse_environment_path_aux source lexbuf }
+ | ':' ([^ ':']* as word) { "" :: word :: parse_environment_path_aux source lexbuf }
+ | eof { [] }
+and parse_environment_path_aux source = parse
+ | ':' ([^ ':']* as word) { word :: parse_environment_path_aux source lexbuf }
+ | eof { [] }
+ | _ { error source lexbuf "Impossible: expecting colon-separated strings" }
+
+and conf_lines dir source = parse
+ | space* '#' not_newline* newline { Lexing.new_line lexbuf; conf_lines dir source lexbuf }
+ | space* '#' not_newline* eof { [] }
+ | space* newline { Lexing.new_line lexbuf; conf_lines dir source lexbuf }
+ | space* eof { [] }
+ | space* (not_newline_nor_colon+ as k) (sp* as s1) ':' (sp* as s2)
+ {
+ let bexpr =
+ try Glob.parse ?dir k
+ with exn -> error source lexbuf "Invalid globbing pattern %S" k (Printexc.to_string exn)
+ in
+ sublex (count_lines lexbuf) s1; sublex (count_lines lexbuf) s2;
+ let v1 = conf_value empty source lexbuf in
+ let v2 = conf_values v1 source lexbuf in
+ let rest = conf_lines dir source lexbuf in (bexpr,v2) :: rest
+ }
+ | _ { error source lexbuf "Invalid line syntax" }
+
+and conf_value x source = parse
+ | '-' (tag as tag) { { (x) with minus_tags = locate source lexbuf tag :: x.minus_tags } }
+ | '+'? (tag as tag) { { (x) with plus_tags = locate source lexbuf tag :: x.plus_tags } }
+ | (_ | eof) { error source lexbuf "Invalid tag modifier only '+ or '-' are allowed as prefix for tag" }
+
+and conf_values x source = parse
+ | (sp* as s1) ',' (sp* as s2) {
+ sublex (count_lines lexbuf) s1; sublex (count_lines lexbuf) s2;
+ conf_values (conf_value x source lexbuf) source lexbuf
+ }
+ | newline { Lexing.new_line lexbuf; x }
+ | eof { x }
+ | _ { error source lexbuf "Only ',' separated tags are alllowed" }
+
+and path_scheme patt_allowed source = parse
+ | ([^ '%' ]+ as prefix)
+ { `Word prefix :: path_scheme patt_allowed source lexbuf }
+ | "%(" (variable as var) ')'
+ { `Var (var, Bool.True) :: path_scheme patt_allowed source lexbuf }
+ | "%(" (variable as var) ':' (pattern as patt) ')'
+ { if patt_allowed then
+ let patt = My_std.String.implode (unescape (Lexing.from_string patt)) in
+ `Var (var, Glob.parse patt) :: path_scheme patt_allowed source lexbuf
+ else
+ error source lexbuf "Patterns are not allowed in this pathname (%%(%s:%s) only in ~prod)" var patt }
+ | '%'
+ { `Var ("", Bool.True) :: path_scheme patt_allowed source lexbuf }
+ | eof
+ { [] }
+ | _ { error source lexbuf "Bad pathanme scheme" }
+
+and unescape = parse
+ | '\\' (['(' ')'] as c) { c :: unescape lexbuf }
+ | _ as c { c :: unescape lexbuf }
+ | eof { [] }
+
+and ocamlfind_query source = parse
+ | newline*
+ "package:" space* (not_newline* as n) newline+
+ "description:" space* (not_newline* as d) newline+
+ "version:" space* (not_newline* as v) newline+
+ "archive(s):" space* (not_newline* as a) newline+
+ "linkopts:" space* (not_newline* as lo) newline+
+ "location:" space* (not_newline* as l) newline+
+ { n, d, v, a, lo, l }
+ | _ { error source lexbuf "Bad ocamlfind query" }
+
+and trim_blanks source = parse
+ | blank* (not_blank* as word) blank* { word }
+ | _ { error source lexbuf "Bad input for trim_blanks" }
+
+and tag_gen source = parse
+ | (normal+ as name) ('(' ([^')']* as param) ')')? { name, param }
+ | _ { error source lexbuf "Not a valid parametrized tag" }
+
+and count_lines lb = parse
+ | space* { count_lines lb lexbuf }
+ | '\\' newline { Lexing.new_line lb; count_lines lb lexbuf }
+ | eof { () }
diff --git a/ocamlbuild/loc.ml b/ocamlbuild/loc.ml
new file mode 100644
index 0000000000..c5ef9398d5
--- /dev/null
+++ b/ocamlbuild/loc.ml
@@ -0,0 +1,35 @@
+(* it's not worth adding a dependency on parsing/location.ml(i) or
+ compilerlibs just to support location printing, so we re-implement
+ that here *)
+
+open Lexing
+
+(* We use a loosely structural type so that this bit of code can be
+ easily reused by project that would wish it, without introducing
+ any type-compatibility burden. *)
+type source = string (* "file", "environment variable", "command-line option" ... *)
+type location = source * position * position
+
+let file loc = loc.pos_fname
+let line loc = loc.pos_lnum
+let char loc = loc.pos_cnum - loc.pos_bol
+
+let print_loc ppf (source, start, end_) =
+ let open Format in
+ let print one_or_two ppf (start_num, end_num) =
+ if one_or_two then fprintf ppf " %d" start_num
+ else fprintf ppf "s %d-%d" start_num end_num in
+ fprintf ppf "%s %S, line%a, character%a:@."
+ (String.capitalize_ascii source)
+ (file start)
+ (print (line start = line end_))
+ (line start, line end_)
+ (print (line start = line end_ && char start = char end_))
+ (char start, char end_)
+
+let of_lexbuf source lexbuf =
+ (source, lexbuf.lex_start_p, lexbuf.lex_curr_p)
+
+let print_loc_option ppf = function
+ | None -> ()
+ | Some loc -> print_loc ppf loc
diff --git a/ocamlbuild/loc.mli b/ocamlbuild/loc.mli
new file mode 100644
index 0000000000..c5768bc1ce
--- /dev/null
+++ b/ocamlbuild/loc.mli
@@ -0,0 +1,7 @@
+type source = string
+type location = source * Lexing.position * Lexing.position
+
+val print_loc : Format.formatter -> location -> unit
+val print_loc_option : Format.formatter -> location option -> unit
+
+val of_lexbuf : source -> Lexing.lexbuf -> location
diff --git a/ocamlbuild/log.ml b/ocamlbuild/log.ml
new file mode 100644
index 0000000000..61aa10aefa
--- /dev/null
+++ b/ocamlbuild/log.ml
@@ -0,0 +1,81 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+
+module Debug = struct
+let mode _ = true
+end
+include Debug
+
+let level = ref 1
+
+let classic_display = ref false
+let internal_display = ref None
+let failsafe_display = lazy (Display.create ~mode:`Classic ~log_level:!level ())
+
+let ( !- ) r =
+ match !r with
+ | None -> !*failsafe_display
+ | Some x -> x
+
+let init log_file =
+ let mode =
+ if !classic_display || !*My_unix.is_degraded || !level <= 0 || not (My_unix.stdout_isatty ()) then
+ `Classic
+ else
+ `Sophisticated
+ in
+ internal_display := Some (Display.create ~mode ?log_file ~log_level:!level ())
+
+let raw_dprintf log_level = Display.dprintf ~raw:true ~log_level !-internal_display
+let dprintf log_level fmt = Display.dprintf ~log_level !-internal_display fmt
+let is_logging log_level = Display.is_logging !-internal_display log_level
+let eprintf fmt = dprintf (-1) fmt
+
+let update () = Display.update !-internal_display
+let event ?pretend x = Display.event !-internal_display ?pretend x
+let display x = Display.display !-internal_display x
+
+let do_at_end = Queue.create ()
+let already_asked = Hashtbl.create 10
+
+let at_end_always ~name thunk =
+ if not (Hashtbl.mem already_asked name) then begin
+ Hashtbl.add already_asked name ();
+ Queue.add thunk do_at_end;
+ end
+
+let at_end ~name thunk = at_end_always ~name (function
+ | `Quiet -> ()
+ | `Success | `Error -> thunk `Error)
+let at_failure ~name thunk = at_end_always ~name (function
+ | `Success | `Quiet -> ()
+ | `Error -> thunk `Error)
+
+let finish ?how () =
+ while not (Queue.is_empty do_at_end) do
+ let actions = Queue.copy do_at_end in
+ Queue.clear do_at_end;
+ (* calling a thunk may add new actions again, hence the loop *)
+ Queue.iter (fun thunk ->
+ thunk (match how with None -> `Quiet | Some how -> how)
+ ) actions;
+ done;
+ match !internal_display with
+ | None -> ()
+ | Some d -> Display.finish ?how d
+
+(*let () = My_unix.at_exit_once finish*)
diff --git a/ocamlbuild/log.mli b/ocamlbuild/log.mli
new file mode 100644
index 0000000000..5a3b6e6e8e
--- /dev/null
+++ b/ocamlbuild/log.mli
@@ -0,0 +1,45 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Log *)
+
+(** Module for modulating the logging output with the logging level. *)
+include Signatures.LOG
+
+(** Turn it to true to have a classic display of commands. *)
+val classic_display : bool ref
+
+(** See {Display.event}. *)
+val event : ?pretend:bool -> string -> string -> Tags.t -> unit
+
+(**/**)
+
+(** Initialize the Log module given a log file name. *)
+val init : string option -> unit
+
+val finish : ?how:[`Success|`Error|`Quiet] -> unit -> unit
+val display : (out_channel -> unit) -> unit
+val update : unit -> unit
+val mode : string -> bool
+
+(** Wrap logging event so that only fire at the end of the compilation
+ process, possibly depending on the termination status.
+
+ The name is used to avoid printing the same hint/warning twice,
+ even if [at_end] is called several times. Use different names for
+ distinct events.
+*)
+val at_end : name:string -> ([> `Error | `Quiet ] -> unit) -> unit
+val at_failure : name:string -> ([> `Error ] -> unit) -> unit
diff --git a/ocamlbuild/main.ml b/ocamlbuild/main.ml
new file mode 100644
index 0000000000..f64a4ba281
--- /dev/null
+++ b/ocamlbuild/main.ml
@@ -0,0 +1,359 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+open My_std
+open Log
+open Pathname.Operators
+open Command
+open Tools
+open Ocaml_specific
+open Format
+;;
+
+exception Exit_build_error of string
+exception Exit_silently
+
+let clean () =
+ Shell.rm_rf !Options.build_dir;
+ if !Options.make_links then begin
+ let entry =
+ Slurp.map (fun _ _ _ -> true)
+ (Slurp.slurp Filename.current_dir_name)
+ in
+ Slurp.force (Resource.clean_up_links entry)
+ end;
+ Log.finish ();
+ raise Exit_silently
+;;
+
+let show_tags () =
+ if List.length !Options.show_tags > 0 then
+ Log.eprintf "Warning: the following tags do not include \
+ dynamically-generated tags, such as link, compile, pack, byte, native, c, \
+ pdf... (this list is by no means exhaustive).\n";
+ List.iter begin fun path ->
+ Log.eprintf "@[<2>Tags for %S:@ {. %a .}@]" path Tags.print (tags_of_pathname path)
+ end !Options.show_tags
+;;
+
+let show_documentation () =
+ Rule.show_documentation ();
+ Flags.show_documentation ();
+;;
+
+(* these tags are used in an ad-hoc way by the ocamlbuild implementation;
+ this means that even if they were not part of any flag declaration,
+ they should be marked as useful, to avoid the "unused tag" warning. *)
+let builtin_useful_tags =
+ Tags.of_list [
+ "include"; "traverse"; "not_hygienic"; "precious";
+ "pack"; "ocamlmklib"; "native"; "thread";
+ "nopervasives"; "use_menhir"; "ocamldep";
+ "thread";
+ ]
+;;
+
+let proceed () =
+ Hooks.call_hook Hooks.Before_options;
+ Options.init ();
+ Options.include_dirs := List.map Pathname.normalize !Options.include_dirs;
+ Options.exclude_dirs := List.map Pathname.normalize !Options.exclude_dirs;
+ if !Options.must_clean then clean ();
+ Hooks.call_hook Hooks.After_options;
+ let options_wd = Sys.getcwd () in
+ let first_run_for_plugin =
+ (* If we are in the first run before launching the plugin, we
+ should skip the user-visible operations (hygiene) that may need
+ information from the plugin to run as the user expects it.
+
+ Note that we don't need to disable the [Hooks] call as they are
+ no-ops anyway, before any plugin has registered hooks. *)
+ Plugin.we_need_a_plugin () && not !Options.just_plugin in
+
+ let target_dirs = List.union [] (List.map Pathname.dirname !Options.targets) in
+
+ Configuration.parse_string ~source:Const.Source.builtin
+ "<**/*.ml> or <**/*.mli> or <**/*.mlpack> or <**/*.ml.depends>: ocaml\n\
+ <**/*.byte>: ocaml, byte, program\n\
+ <**/*.odoc>: ocaml, doc\n\
+ <**/*.native>: ocaml, native, program\n\
+ <**/*.cma>: ocaml, byte, library\n\
+ <**/*.cmxa>: ocaml, native, library\n\
+ <**/*.cmo>: ocaml, byte\n\
+ <**/*.cmi>: ocaml, byte, native\n\
+ <**/*.cmx>: ocaml, native\n\
+ <**/*.mly>: infer\n\
+ <**/.svn>|\".bzr\"|\".hg\"|\".git\"|\"_darcs\": -traverse\n\
+ ";
+
+ List.iter
+ (Configuration.parse_string ~source:Const.Source.command_line)
+ !Options.tag_lines;
+
+ Configuration.tag_any !Options.tags;
+ if !Options.recursive || Options.ocamlbuild_project_heuristic ()
+ then Configuration.tag_any ["traverse"];
+
+ (* options related to findlib *)
+ if !Options.use_ocamlfind then
+ List.iter
+ (fun pkg ->
+ let tag = Param_tags.make "package" pkg in
+ Configuration.tag_any [tag])
+ !Options.ocaml_pkgs;
+
+ begin match !Options.ocaml_syntax with
+ | Some syntax -> Configuration.tag_any [Param_tags.make "syntax" syntax]
+ | None -> () end;
+
+ let newpwd = Sys.getcwd () in
+ Sys.chdir Pathname.pwd;
+ let entry_include_dirs = ref [] in
+ let entry =
+ Slurp.filter
+ begin fun path name () ->
+ let dir =
+ if path = Filename.current_dir_name then
+ None
+ else
+ Some path
+ in
+ let path_name = path/name in
+
+ if name = "_tags" then begin
+ let tags_path =
+ (* PR#6482: remember that this code is run lazily by the Slurp command,
+ and may run only after the working directory has been changed.
+
+ On the other hand, always using the absolute path makes
+ error messages longer and more frigthening in case of
+ syntax error in the _tags file. So we use the absolute
+ path only when necessary -- the working directory has
+ changed. *)
+ if Sys.getcwd () = Pathname.pwd then path_name
+ else Pathname.pwd / path_name in
+ ignore (Configuration.parse_file ?dir tags_path);
+ end;
+
+ (List.mem name ["_oasis"] || (String.length name > 0 && name.[0] <> '_'))
+ && (name <> !Options.build_dir && not (List.mem name !Options.exclude_dirs))
+ && begin
+ not (path_name <> Filename.current_dir_name && Pathname.is_directory path_name)
+ || begin
+ let tags = tags_of_pathname path_name in
+ (if Tags.mem "include" tags
+ || List.mem path_name !Options.include_dirs then
+ (entry_include_dirs := path_name :: !entry_include_dirs; true)
+ else
+ Tags.mem "traverse" tags
+ || List.exists (Pathname.is_prefix path_name) !Options.include_dirs
+ || List.exists (Pathname.is_prefix path_name) target_dirs)
+ && ((* beware: !Options.build_dir is an absolute directory *)
+ Pathname.normalize !Options.build_dir
+ <> Pathname.normalize (Pathname.pwd/path_name))
+ end
+ end
+ end
+ (Slurp.slurp Filename.current_dir_name)
+ in
+ Hooks.call_hook Hooks.Before_hygiene;
+ let hygiene_entry =
+ Slurp.map begin fun path name () ->
+ let tags = tags_of_pathname (path/name) in
+ not (Tags.mem "not_hygienic" tags) && not (Tags.mem "precious" tags)
+ end entry in
+ Slurp.force hygiene_entry;
+ if !Options.hygiene && not first_run_for_plugin then
+ Fda.inspect hygiene_entry;
+ let entry = hygiene_entry in
+ Hooks.call_hook Hooks.After_hygiene;
+ Options.include_dirs := Pathname.current_dir_name :: List.rev !entry_include_dirs;
+ dprintf 3 "include directories are:@ %a" print_string_list !Options.include_dirs;
+ Options.entry := Some entry;
+
+ Hooks.call_hook Hooks.Before_rules;
+ Ocaml_specific.init ();
+ Hooks.call_hook Hooks.After_rules;
+
+ Sys.chdir options_wd;
+ Plugin.execute_plugin_if_needed ();
+
+ (* [Param_tags.init ()] is called *after* the plugin is executed, as
+ some of the parametrized tags present in the _tags files parsed
+ will be declared by the plugin, and would therefore result in
+ "tag X does not expect a parameter" warnings if initialized
+ before. Note that [Plugin.rebuild_plugin_if_needed] is careful to
+ partially initialize the tags that it uses for plugin compilation. *)
+ Param_tags.init ();
+
+ Sys.chdir newpwd;
+ (*let () = dprintf 0 "source_dir_path_set:@ %a" StringSet.print source_dir_path_set*)
+
+ if !Options.show_documentation then begin
+ show_documentation ();
+ raise Exit_silently
+ end;
+
+ let all_tags =
+ let builtin = builtin_useful_tags in
+ let used_in_flags = Flags.get_used_tags () in
+ let used_in_deps =
+ List.fold_left (fun acc (tags, _deps) -> Tags.union acc tags)
+ Tags.empty (Command.list_all_deps ())
+ in
+ Tags.union builtin (Tags.union used_in_flags used_in_deps) in
+ Configuration.check_tags_usage all_tags;
+
+ Digest_cache.init ();
+
+ Sys.catch_break true;
+
+ show_tags ();
+
+ let targets =
+ List.map begin fun starget ->
+ let starget = Resource.import starget in
+ let target = path_and_context_of_string starget in
+ let ext = Pathname.get_extension starget in
+ (target, starget, ext)
+ end !Options.targets in
+
+ try
+ let targets =
+ List.map begin fun (target, starget, ext) ->
+ Shell.mkdir_p (Pathname.dirname starget);
+ let target = Solver.solve_target starget target in
+ (target, ext)
+ end targets in
+
+ Command.dump_parallel_stats ();
+
+ Log.finish ();
+
+ Shell.chdir Pathname.pwd;
+
+ let call spec = sys_command (Command.string_of_command_spec spec) in
+
+ let cmds =
+ List.fold_right begin fun (target, ext) acc ->
+ let cmd = !Options.build_dir/target in
+ let link x =
+ if !Options.make_links then
+ ignore (call (S [A"ln"; A"-sf"; P x; A Pathname.pwd]))
+ in
+ match ext with
+ | "byte" | "native" | "top" ->
+ link cmd; cmd :: acc
+ | "html" ->
+ link (Pathname.dirname cmd); acc
+ | _ ->
+ if !Options.program_to_execute then
+ eprintf "Warning: Won't execute %s whose extension is neither .byte nor .native" cmd;
+ acc
+ end targets [] in
+
+ if !Options.program_to_execute then
+ begin
+ match List.rev cmds with
+ | [] -> raise (Exit_usage "Using -- requires one target");
+ | cmd :: rest ->
+ if rest <> [] then dprintf 0 "Warning: Using -- only run the last target";
+ let cmd_spec = S [P cmd; atomize !Options.program_args] in
+ dprintf 3 "Running the user command:@ %a" Pathname.print cmd;
+ raise (Exit_with_code (call cmd_spec)) (* Exit with the exit code of the called command *)
+ end
+ else
+ ()
+ with
+ | Ocaml_dependencies.Circular_dependencies(cycle, p) ->
+ raise
+ (Exit_build_error
+ (sbprintf "@[<2>Circular dependencies: %S already seen in@ %a@]@." p pp_l cycle))
+;;
+
+open Exit_codes;;
+
+let main () =
+ let exit rc =
+ Log.finish ~how:(if rc <> 0 then `Error else `Success) ();
+ Pervasives.exit rc
+ in
+ try
+ proceed ()
+ with e ->
+ if !Options.catch_errors then
+ try raise e with
+ | Exit_OK -> exit rc_ok
+ | Fda.Exit_hygiene_failed ->
+ Log.eprintf "Exiting due to hygiene violations.";
+ exit rc_hygiene
+ | Exit_usage u ->
+ Log.eprintf "Usage:@ %s." u;
+ exit rc_usage
+ | Exit_system_error msg ->
+ Log.eprintf "System error:@ %s." msg;
+ exit rc_system_error
+ | Exit_with_code rc ->
+ exit rc
+ | Exit_silently ->
+ Log.finish ~how:`Quiet ();
+ Pervasives.exit rc_ok
+ | Exit_silently_with_code rc ->
+ Log.finish ~how:`Quiet ();
+ Pervasives.exit rc
+ | Solver.Failed backtrace ->
+ Log.raw_dprintf (-1) "@[<v0>@[<2>Solver failed:@ %a@]@."
+ Report.print_backtrace_analyze backtrace;
+ Log.raw_dprintf 1 "@[<v2>Backtrace:%a@]@]@."
+ Report.print_backtrace backtrace;
+ exit rc_solver_failed
+ | Failure s ->
+ Log.eprintf "Failure:@ %s." s;
+ exit rc_failure
+ | Solver.Circular(r, rs) ->
+ Log.eprintf "Circular build detected@ (%a already seen in %a)"
+ Resource.print r (List.print Resource.print) rs;
+ exit rc_circularity
+ | Invalid_argument s ->
+ Log.eprintf
+ "INTERNAL ERROR: Invalid argument %s\n\
+ This is likely to be a bug, please report this to the ocamlbuild\n\
+ developers." s;
+ exit rc_invalid_argument
+ | Ocaml_utils.Ocamldep_error msg ->
+ Log.eprintf "Ocamldep error: %s" msg;
+ exit rc_ocamldep_error
+ | Lexers.Error (msg,loc) ->
+ Log.eprintf "%aLexing error: %s." Loc.print_loc loc msg;
+ exit rc_lexing_error
+ | Arg.Bad msg ->
+ Log.eprintf "%s" msg;
+ exit rc_usage
+ | Exit_build_error msg ->
+ Log.eprintf "%s" msg;
+ exit rc_build_error
+ | Arg.Help msg ->
+ Log.eprintf "%s" msg;
+ exit rc_ok
+ | e ->
+ try
+ Log.eprintf "%a" My_unix.report_error e;
+ exit 100
+ with
+ | e ->
+ Log.eprintf "Exception@ %s." (Printexc.to_string e);
+ exit 100
+ else raise e
+;;
diff --git a/ocamlbuild/main.mli b/ocamlbuild/main.mli
new file mode 100644
index 0000000000..f64640fab1
--- /dev/null
+++ b/ocamlbuild/main.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+val main : unit -> unit
diff --git a/ocamlbuild/man/ocamlbuild.1 b/ocamlbuild/man/ocamlbuild.1
new file mode 100644
index 0000000000..b02d340b70
--- /dev/null
+++ b/ocamlbuild/man/ocamlbuild.1
@@ -0,0 +1,268 @@
+.\"***********************************************************************)
+.\"* *)
+.\"* ocamlbuild *)
+.\"* *)
+.\"* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+.\"* *)
+.\"* Copyright 2007 Institut National de Recherche en Informatique et *)
+.\"* en Automatique. All rights reserved. This file is distributed *)
+.\"* under the terms of the Q Public License version 1.0. *)
+.\"* *)
+.\"***********************************************************************)
+.\"
+.TH OCAMLBUILD 1
+
+.SH NAME
+ocamlbuild \- The OCaml project compilation tool
+
+
+.SH SYNOPSIS
+.B ocamlbuild
+[
+.B \-Is \ dir1,...
+]
+[
+.BI \-libs \ lib1,...
+]
+[
+.BI \-lflags \ flag1,...
+]
+[
+.BI \-pp \ flags
+]
+[
+.BI \-tags \ tag1,...
+]
+[
+.B \-j \ parallel-jobs
+]
+.I target.native
+[
+.B \-\- arg1 arg2 ...
+]
+
+.I (same options)
+
+.SH DESCRIPTION
+
+.BR ocamlbuild (1)
+orchestrates the compilation process of your OCaml project. It is similar
+in function to
+.BR make (1)
+except that it is tailor-made to automatically compile most OCaml projects
+with very little user input.
+
+.BR ocamlbuild
+should be invoked in the root of a clean project tree (e.g., with no leftover
+compilation files). Given one or more targets to compile, it scans the required
+subdirectories to gather information about the various files present, running
+tools such as
+.BR ocamldep (1)
+to extract dependency information, and gathering optional files that fine-tune
+its behaviour.
+Target names are very significant.
+
+.SH TARGET NAMES
+.BR ocamlbuild
+uses a set of target naming conventions to select the kind of objects to
+produce. Target names are of the form
+.BR base.extension
+where
+.BR base
+is usually the name of the underlying OCaml module and
+.BR extension
+denotes the kind of object to produce from that file -- a byte code executable,
+a native executable, documentation...
+Of course extensions such as
+.BR .cmo,
+.BR .cma,
+.BR .cmi...
+map to their usual counterparts. Here is a list of the most important
+.BR ocamlbuild \&-specific
+extensions:
+
+.TP 2i
+.B .native
+Native code executable
+
+.TP 2i
+.B .byte
+Byte code executable
+
+.TP 2i
+.B .inferred.mli
+Interface inferred with
+.BR ocamlc -i
+
+.TP 2i
+.B .docdir/index.html
+HTML documentation generated with
+.BR ocamldoc
+
+.PP
+
+.SH OPTIONS
+
+The following command-line options are recognized by
+.BR ocamlbuild (1).
+
+.TP
+\fB\-version\fR
+Display the version
+.TP
+\fB\-quiet\fR
+Make as quiet as possible
+.TP
+\fB\-verbose\fR <level>
+Set the verbose level
+.TP
+\fB\-documentation\fR
+Show rules and flags
+.TP
+\fB\-log\fR <file>
+Set log file
+.TP
+\fB\-no\-log\fR
+No log file
+.TP
+\fB\-clean\fR
+Remove build directory and other files, then exit
+.TP
+\fB\-I\fR <path>
+Add to include directories
+.TP
+\fB\-Is\fR <path,...>
+(same as above, but accepts a comma\-separated list)
+.TP
+\fB\-X\fR <path>
+Directory to ignore
+.TP
+\fB\-Xs\fR <path,...>
+(idem)
+.TP
+\fB\-lib\fR <flag>
+Link to this ocaml library
+.TP
+\fB\-libs\fR <flag,...>
+(idem)
+.TP
+\fB\-lflag\fR <flag>
+Add to ocamlc link flags
+.TP
+\fB\-lflags\fR <flag,...>
+(idem)
+.TP
+\fB\-cflag\fR <flag>
+Add to ocamlc compile flags
+.TP
+\fB\-cflags\fR <flag,...>
+(idem)
+.TP
+\fB\-yaccflag\fR <flag>
+Add to ocamlyacc flags
+.TP
+\fB\-yaccflags\fR <flag,...>
+(idem)
+.TP
+\fB\-lexflag\fR <flag>
+Add to ocamllex flags
+.TP
+\fB\-lexflags\fR <flag,...>
+(idem)
+.TP
+\fB\-ppflag\fR <flag>
+Add to ocaml preprocessing flags
+.TP
+\fB\-pp\fR <flag,...>
+(idem)
+.TP
+\fB\-tag\fR <tag>
+Add to default tags
+.TP
+\fB\-tags\fR <tag,...>
+(idem)
+.TP
+\fB\-ignore\fR <module,...>
+Don't try to build these modules
+.TP
+\fB\-no\-links\fR
+Don't make links of produced final targets
+.TP
+\fB\-no\-skip\fR
+Don't skip modules that are requested by ocamldep but cannot be built
+.TP
+\fB\-no\-hygiene\fR
+Don't apply sanity\-check rules
+.TP
+\fB\-no\-plugin\fR
+Don't build myocamlbuild.ml
+.TP
+\fB\-no\-stdlib\fR
+Don't ignore stdlib modules
+.TP
+\fB\-just\-plugin\fR
+Just build myocamlbuild.ml
+.TP
+\fB\-byte\-plugin\fR
+Don't use a native plugin but bytecode
+.TP
+\fB\-no-sanitize\fR
+Do not enforce sanity\-check rules
+.TP
+\fB\-nothing\-should\-be\-rebuilt\fR
+Fail if something needs to be rebuilt
+.TP
+\fB\-classic\-display\fR
+Display executed commands the old\-fashioned way
+.TP
+\fB\-j\fR <N>
+Allow N jobs at once (0 for unlimited)
+.TP
+\fB\-build\-dir\fR <path>
+Set build directory
+.TP
+\fB\-install\-dir\fR <path>
+Set the install directory
+.TP
+\fB\-where\fR
+Display the install directory
+.TP
+\fB\-ocamlc\fR <command>
+Set the OCaml bytecode compiler
+.TP
+\fB\-ocamlopt\fR <command>
+Set the OCaml native compiler
+.TP
+\fB\-ocamldep\fR <command>
+Set the OCaml dependency tool
+.TP
+\fB\-ocamldoc\fR <command>
+Set the OCaml documentation generator
+.TP
+\fB\-ocamlyacc\fR <command>
+Set the ocamlyacc tool
+.TP
+\fB\-ocamllex\fR <command>
+Set the ocamllex tool
+.TP
+\fB\-ocamlrun\fR <command>
+Set the ocamlrun tool
+.TP
+\fB\-\-\fR
+Stop argument processing, remaining arguments are given to the user program
+.TP
+\fB\-help\fR
+Display the list of options
+.TP
+\fB\-\-help\fR
+Display the list of options
+.PP
+
+.SH SEE ALSO
+The
+.BR ocamlbuild
+manual,
+.BR ocaml (1),
+.BR make (1).
+.br
+.I The OCaml user's manual, chapter "Batch compilation".
diff --git a/ocamlbuild/misc/opentracer.ml b/ocamlbuild/misc/opentracer.ml
new file mode 100644
index 0000000000..4a977a580d
--- /dev/null
+++ b/ocamlbuild/misc/opentracer.ml
@@ -0,0 +1,103 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+open My_std
+
+module type TRACER = sig
+ (** Call the given command using the tracer, it returns the exit status. *)
+ val call : string -> string list -> StringSet.t * Unix.process_status
+end
+
+module Ktrace = struct
+ let process_line line (wait_a_string, set) =
+ let strings = Lexers.space_sep_strings (Lexing.from_string line) in
+ if wait_a_string then
+ match strings with
+ | [_; _; "NAMI"; file] -> false, StringSet.add file set
+ | _ -> failwith (Printf.sprintf "unexpected ktrace output line (%S)" line)
+ else
+ match strings with
+ | [_; _; "CALL"; fct] ->
+ (String.length fct > 5 && String.sub fct 0 5 = "open("), set
+ | _ -> false, set
+
+ let call cmd args =
+ let tmp = Filename.temp_file "ktrace" "out" in
+ match Unix.fork () with
+ | 0 -> Unix.execvp "ktrace" (Array.of_list("-d"::"-i"::"-t"::"nc"::"-f"::tmp::cmd::args))
+ | pid ->
+ let _, st = Unix.waitpid [] pid in
+ let ic = Unix.open_process_in (Printf.sprintf "kdump -f %s" (Filename.quote tmp)) in
+ let close () = ignore (Unix.close_process_in ic); Sys.remove tmp in
+ let set =
+ try
+ let rec loop acc =
+ match try Some (input_line ic) with End_of_file -> None with
+ | Some line -> loop (process_line line acc)
+ | None -> acc in
+ let _, set = loop (false, StringSet.empty) in
+ close ();
+ set
+ with e -> (close (); raise e)
+ in set, st
+
+end
+
+module Driver (T : TRACER) = struct
+ let usage () =
+ Printf.eprintf "Usage: %s [-a <authorized_file>]* <cmd> <args>*\n%!" Sys.argv.(0);
+ exit 2
+
+ let main () =
+ let log = "opentracer.log" in
+ let oc =
+ if sys_file_exists log then
+ open_out_gen [Open_wronly;Open_append;Open_text] 0 log
+ else
+ let oc = open_out log in
+ let () = output_string oc "---\n" in
+ oc in
+ let rec loop acc =
+ function
+ | "-a" :: file :: rest -> loop (StringSet.add file acc) rest
+ | "-a" :: _ -> usage ()
+ | "--" :: cmd :: args -> acc, cmd, args
+ | cmd :: args -> acc, cmd, args
+ | [] -> usage () in
+ let authorized_files, cmd, args =
+ loop StringSet.empty (List.tl (Array.to_list Sys.argv)) in
+ let opened_files, st = T.call cmd args in
+ let forbidden_files = StringSet.diff opened_files authorized_files in
+
+ if not (StringSet.is_empty forbidden_files) then begin
+ Printf.fprintf oc "- cmd: %s\n args:\n%!" cmd;
+ let pp = Printf.fprintf oc " - %s\n%!" in
+ List.iter pp args;
+ Printf.fprintf oc " forbidden_files:\n%!";
+ StringSet.iter pp forbidden_files;
+ end;
+ close_out oc;
+ match st with
+ | Unix.WEXITED st -> exit st
+ | Unix.WSIGNALED s | Unix.WSTOPPED s -> Unix.kill (Unix.getpid ()) s
+end
+
+let main =
+ (* match os with *)
+ (* | "macos" -> *)
+ let module M = Driver(Ktrace) in M.main
+ (* | "linux" -> *)
+ (* let module M = Driver(Strace) in M.main *)
+
+let () = main ()
diff --git a/ocamlbuild/my_std.ml b/ocamlbuild/my_std.ml
new file mode 100644
index 0000000000..7e708774ae
--- /dev/null
+++ b/ocamlbuild/my_std.ml
@@ -0,0 +1,432 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open Format
+
+exception Exit_OK
+exception Exit_usage of string
+exception Exit_system_error of string
+exception Exit_with_code of int
+exception Exit_silently_with_code of int
+
+module Outcome = struct
+ type ('a,'b) t =
+ | Good of 'a
+ | Bad of 'b
+
+ let ignore_good =
+ function
+ | Good _ -> ()
+ | Bad e -> raise e
+
+ let good =
+ function
+ | Good x -> x
+ | Bad exn -> raise exn
+
+ let wrap f x =
+ try Good (f x) with e -> Bad e
+
+end
+
+let opt_print elt ppf =
+ function
+ | Some x -> fprintf ppf "@[<2>Some@ %a@]" elt x
+ | None -> pp_print_string ppf "None"
+
+open Format
+let ksbprintf g fmt =
+ let buff = Buffer.create 42 in
+ let f = formatter_of_buffer buff in
+ kfprintf (fun f -> (pp_print_flush f (); g (Buffer.contents buff))) f fmt
+let sbprintf fmt = ksbprintf (fun x -> x) fmt
+
+(** Some extensions of the standard library *)
+module Set = struct
+
+ module type OrderedTypePrintable = sig
+ include Set.OrderedType
+ val print : formatter -> t -> unit
+ end
+
+ module type S = sig
+ include Set.S
+ val find_elt : (elt -> bool) -> t -> elt
+ val map : (elt -> elt) -> t -> t
+ val of_list : elt list -> t
+ val print : formatter -> t -> unit
+ end
+
+ module Make (M : OrderedTypePrintable) : S with type elt = M.t = struct
+ include Set.Make(M)
+ exception Found of elt
+ let find_elt p set =
+ try
+ iter begin fun elt ->
+ if p elt then raise (Found elt)
+ end set; raise Not_found
+ with Found elt -> elt
+ let map f set = fold (fun x -> add (f x)) set empty
+ let of_list l = List.fold_right add l empty
+ let print f s =
+ let () = fprintf f "@[<hv0>@[<hv2>{.@ " in
+ let _ =
+ fold begin fun elt first ->
+ if not first then fprintf f ",@ ";
+ M.print f elt;
+ false
+ end s true in
+ fprintf f "@]@ .}@]"
+ end
+end
+
+module List = struct
+ include List
+ let print pp_elt f ls =
+ fprintf f "@[<2>[@ ";
+ let _ =
+ fold_left begin fun first elt ->
+ if not first then fprintf f ";@ ";
+ pp_elt f elt;
+ false
+ end true ls in
+ fprintf f "@ ]@]"
+
+ let filter_opt f xs =
+ List.fold_right begin fun x acc ->
+ match f x with
+ | Some x -> x :: acc
+ | None -> acc
+ end xs []
+
+ let rec rev_append_uniq acc =
+ function
+ | [] -> acc
+ | x :: xs ->
+ if mem x acc then rev_append_uniq acc xs
+ else rev_append_uniq (x :: acc) xs
+
+ let union a b =
+ rev (rev_append_uniq (rev_append_uniq [] a) b)
+
+ let ordered_unique (type el) (lst : el list) =
+ let module Set = Set.Make(struct
+ type t = el
+ let compare = Pervasives.compare
+ let print _ _ = ()
+ end)
+ in
+ let _, lst =
+ List.fold_left (fun (set,acc) el ->
+ if Set.mem el set
+ then set, acc
+ else Set.add el set, el :: acc) (Set.empty,[]) lst
+ in
+ List.rev lst
+
+end
+
+module String = struct
+ include String
+
+ let print f s = fprintf f "%S" s
+
+ let chomp s =
+ let is_nl_char = function '\n' | '\r' -> true | _ -> false in
+ let rec cut n =
+ if n = 0 then 0 else if is_nl_char s.[n-1] then cut (n-1) else n
+ in
+ let ls = length s in
+ let n = cut ls in
+ if n = ls then s else sub s 0 n
+
+ let before s pos = sub s 0 pos
+ let after s pos = sub s pos (length s - pos)
+ let first_chars s n = sub s 0 n
+ let last_chars s n = sub s (length s - n) n
+
+ let rec eq_sub_strings s1 p1 s2 p2 len =
+ if len > 0 then s1.[p1] = s2.[p2] && eq_sub_strings s1 (p1+1) s2 (p2+1) (len-1)
+ else true
+
+ let rec contains_string s1 p1 s2 =
+ let ls1 = length s1 in
+ let ls2 = length s2 in
+ try let pos = index_from s1 p1 s2.[0] in
+ if ls1 - pos < ls2 then None
+ else if eq_sub_strings s1 pos s2 0 ls2 then
+ Some pos else contains_string s1 (pos + 1) s2
+ with Not_found -> None
+
+ let subst patt repl s =
+ let lpatt = length patt in
+ let lrepl = length repl in
+ let rec loop s from =
+ match contains_string s from patt with
+ | Some pos ->
+ loop (before s pos ^ repl ^ after s (pos + lpatt)) (pos + lrepl)
+ | None -> s
+ in loop s 0
+
+ let tr patt subst text =
+ String.map (fun c -> if c = patt then subst else c) text
+
+ (*** is_prefix : is u a prefix of v ? *)
+ let is_prefix u v =
+ let m = String.length u
+ and n = String.length v
+ in
+ m <= n &&
+ let rec loop i = i = m || u.[i] = v.[i] && loop (i + 1) in
+ loop 0
+ (* ***)
+
+ (*** is_suffix : is v a suffix of u ? *)
+ let is_suffix u v =
+ let m = String.length u
+ and n = String.length v
+ in
+ n <= m &&
+ let rec loop i = i = n || u.[m - 1 - i] = v.[n - 1 - i] && loop (i + 1) in
+ loop 0
+ (* ***)
+
+ let rev s =
+ let sl = String.length s in
+ let s' = Bytes.create sl in
+ for i = 0 to sl - 1 do
+ Bytes.set s' i s.[sl - i - 1]
+ done;
+ Bytes.to_string s';;
+
+ let implode l =
+ match l with
+ | [] -> ""
+ | cs ->
+ let r = Bytes.create (List.length cs) in
+ let pos = ref 0 in
+ List.iter begin fun c ->
+ Bytes.unsafe_set r !pos c;
+ incr pos
+ end cs;
+ Bytes.to_string r
+
+ let explode s =
+ let sl = String.length s in
+ let rec go pos =
+ if pos >= sl then [] else unsafe_get s pos :: go (pos + 1)
+ in go 0
+end
+
+module StringSet = Set.Make(String)
+
+let sys_readdir, reset_readdir_cache, reset_readdir_cache_for =
+ let cache = Hashtbl.create 103 in
+ let sys_readdir dir =
+ try Hashtbl.find cache dir with Not_found ->
+ let res = Outcome.wrap Sys.readdir dir in
+ (Hashtbl.add cache dir res; res)
+ and reset_readdir_cache () =
+ Hashtbl.clear cache
+ and reset_readdir_cache_for dir =
+ Hashtbl.remove cache dir in
+ (sys_readdir, reset_readdir_cache, reset_readdir_cache_for)
+
+let sys_file_exists x =
+ let dirname = Filename.dirname x in
+ let basename = Filename.basename x in
+ match sys_readdir dirname with
+ | Outcome.Bad _ -> false
+ | Outcome.Good a ->
+ if basename = Filename.current_dir_name then true else
+ try Array.iter (fun x -> if x = basename then raise Exit) a; false
+ with Exit -> true
+
+let sys_command =
+ match Sys.os_type with
+ | "Win32" -> fun cmd ->
+ if cmd = "" then 0 else
+ let cmd = "bash --norc -c "^Filename.quote cmd in
+ Sys.command cmd
+ | _ -> fun cmd -> if cmd = "" then 0 else Sys.command cmd
+
+(* FIXME warning fix and use Filename.concat *)
+let filename_concat x y =
+ if x = Filename.current_dir_name || x = "" then y else
+ if Sys.os_type = "Win32" && (x.[String.length x - 1] = '\\') || x.[String.length x - 1] = '/' then
+ if y = "" then x
+ else x ^ y
+ else
+ x ^ "/" ^ y
+
+(* let reslash =
+ match Sys.os_type with
+ | "Win32" -> tr '\\' '/'
+ | _ -> (fun x -> x) *)
+
+open Format
+
+let invalid_arg' fmt = ksbprintf invalid_arg fmt
+
+let the = function Some x -> x | None -> invalid_arg "the: expect Some not None"
+
+let getenv ?default var =
+ try Sys.getenv var
+ with Not_found ->
+ match default with
+ | Some x -> x
+ | None -> failwith (sprintf "This command must have %S in his environment" var);;
+
+let with_input_file ?(bin=false) x f =
+ let ic = (if bin then open_in_bin else open_in) x in
+ try let res = f ic in close_in ic; res with e -> (close_in ic; raise e)
+
+let with_output_file ?(bin=false) x f =
+ reset_readdir_cache_for (Filename.dirname x);
+ let oc = (if bin then open_out_bin else open_out) x in
+ try let res = f oc in close_out oc; res with e -> (close_out oc; raise e)
+
+let read_file x =
+ with_input_file ~bin:true x begin fun ic ->
+ let len = in_channel_length ic in
+ really_input_string ic len
+ end
+
+let copy_chan ic oc =
+ let m = in_channel_length ic in
+ let m = (m lsr 12) lsl 12 in
+ let m = max 16384 (min Sys.max_string_length m) in
+ let buf = Bytes.create m in
+ let rec loop () =
+ let len = input ic buf 0 m in
+ if len > 0 then begin
+ output oc buf 0 len;
+ loop ()
+ end
+ in loop ()
+
+let copy_file src dest =
+ reset_readdir_cache_for (Filename.dirname dest);
+ with_input_file ~bin:true src begin fun ic ->
+ with_output_file ~bin:true dest begin fun oc ->
+ copy_chan ic oc
+ end
+ end
+
+let ( !* ) = Lazy.force
+
+let ( @:= ) ref list = ref := !ref @ list
+
+let ( & ) f x = f x
+
+let ( |> ) x f = f x
+
+let print_string_list = List.print String.print
+
+module Digest = struct
+ include Digest
+(* USEFUL FOR DIGEST DEBUGING
+ let digest_log_hash = Hashtbl.create 103;;
+ let digest_log = "digest.log";;
+ let digest_log_oc = open_out_gen [Open_append;Open_wronly;Open_text;Open_creat] 0o666 digest_log;;
+ let my_to_hex x = to_hex x ^ ";";;
+ if sys_file_exists digest_log then
+ with_input_file digest_log begin fun ic ->
+ try while true do
+ let l = input_line ic in
+ Scanf.sscanf l "%S: %S" (Hashtbl.replace digest_log_hash)
+ done with End_of_file -> ()
+ end;;
+ let string s =
+ let res = my_to_hex (string s) in
+ if try let x = Hashtbl.find digest_log_hash res in s <> x with Not_found -> true then begin
+ Hashtbl.replace digest_log_hash res s;
+ Printf.fprintf digest_log_oc "%S: %S\n%!" res s
+ end;
+ res
+ let file f = my_to_hex (file f)
+ let to_hex x = x
+*)
+
+ let digest_cache = Hashtbl.create 103
+ let reset_digest_cache () = Hashtbl.clear digest_cache
+ let reset_digest_cache_for file = Hashtbl.remove digest_cache file
+ let file f =
+ try Hashtbl.find digest_cache f
+ with Not_found ->
+ let res = file f in
+ (Hashtbl.add digest_cache f res; res)
+end
+
+let reset_filesys_cache () =
+ Digest.reset_digest_cache ();
+ reset_readdir_cache ()
+
+let reset_filesys_cache_for_file file =
+ Digest.reset_digest_cache_for file;
+ reset_readdir_cache_for (Filename.dirname file)
+
+let sys_remove x =
+ reset_filesys_cache_for_file x;
+ Sys.remove x
+
+let with_temp_file pre suf fct =
+ let tmp = Filename.temp_file pre suf in
+ (* Sys.remove is used instead of sys_remove since we know that the tempfile is not that important *)
+ try let res = fct tmp in Sys.remove tmp; res
+ with e -> (Sys.remove tmp; raise e)
+
+let memo f =
+ let cache = Hashtbl.create 103 in
+ fun x ->
+ try Hashtbl.find cache x
+ with Not_found ->
+ let res = f x in
+ (Hashtbl.add cache x res; res)
+
+let memo2 f =
+ let cache = Hashtbl.create 103 in
+ fun x y ->
+ try Hashtbl.find cache (x,y)
+ with Not_found ->
+ let res = f x y in
+ (Hashtbl.add cache (x,y) res; res)
+
+let memo3 f =
+ let cache = Hashtbl.create 103 in
+ fun x y z ->
+ try Hashtbl.find cache (x,y,z)
+ with Not_found ->
+ let res = f x y z in
+ (Hashtbl.add cache (x,y,z) res; res)
+
+let set_lexbuf_fname fname lexbuf =
+ let open Lexing in
+ lexbuf.lex_start_p <- { lexbuf.lex_start_p with pos_fname = fname };
+ lexbuf.lex_curr_p <- { lexbuf.lex_curr_p with pos_fname = fname };
+ ()
+
+let lexbuf_of_string ?name content =
+ let lexbuf = Lexing.from_string content in
+ let fname = match name with
+ | Some name -> name
+ | None ->
+ (* 40: hope the location will fit one line of 80 chars *)
+ if String.length content < 40 && not (String.contains content '\n') then
+ String.escaped content
+ else ""
+ in
+ set_lexbuf_fname fname lexbuf;
+ lexbuf
diff --git a/ocamlbuild/my_std.mli b/ocamlbuild/my_std.mli
new file mode 100644
index 0000000000..0362181c08
--- /dev/null
+++ b/ocamlbuild/my_std.mli
@@ -0,0 +1,68 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* My_std *)
+
+(** Generic utility functions, and system-independent glue. *)
+
+exception Exit_OK
+exception Exit_usage of string
+exception Exit_system_error of string
+exception Exit_with_code of int
+exception Exit_silently_with_code of int
+
+module Outcome : Signatures.OUTCOME
+
+val ksbprintf : (string -> 'a) -> ('b, Format.formatter, unit, 'a) format4 -> 'b
+val sbprintf : ('a, Format.formatter, unit, string) format4 -> 'a
+
+module Set : sig
+ module type OrderedTypePrintable = Signatures.OrderedTypePrintable
+ module type S = Signatures.SET
+ module Make (M : OrderedTypePrintable) : S with type elt = M.t
+end
+
+module List : Signatures.LIST
+
+module String : Signatures.STRING
+
+module Digest : sig
+ type t = string
+ val string : string -> t
+ val substring : string -> int -> int -> t
+ external channel : in_channel -> int -> t = "caml_md5_chan"
+ val file : string -> t
+ val output : out_channel -> t -> unit
+ val input : in_channel -> t
+ val to_hex : t -> string
+end
+
+module StringSet : Set.S with type elt = String.t
+
+val sys_readdir : string -> (string array, exn) Outcome.t
+val sys_remove : string -> unit
+val reset_readdir_cache : unit -> unit
+val reset_filesys_cache : unit -> unit
+val reset_filesys_cache_for_file : string -> unit
+val sys_file_exists : string -> bool
+val sys_command : string -> int
+val filename_concat : string -> string -> string
+
+val invalid_arg' : ('a, Format.formatter, unit, 'b) format4 -> 'a
+
+include Signatures.MISC
+
+val set_lexbuf_fname : string -> Lexing.lexbuf -> unit
+val lexbuf_of_string : ?name:string -> string -> Lexing.lexbuf
diff --git a/ocamlbuild/my_unix.ml b/ocamlbuild/my_unix.ml
new file mode 100644
index 0000000000..fd9603001f
--- /dev/null
+++ b/ocamlbuild/my_unix.ml
@@ -0,0 +1,147 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+
+type file_kind =
+| FK_dir
+| FK_file
+| FK_link
+| FK_other
+
+type stats =
+ {
+ stat_file_kind : file_kind;
+ stat_key : string
+ }
+
+type implem =
+ {
+ mutable is_degraded : bool;
+ mutable is_link : string -> bool;
+ mutable run_and_open : 'a . string -> (in_channel -> 'a) -> 'a;
+ mutable readlink : string -> string;
+ mutable execute_many : ?max_jobs:int ->
+ ?ticker:(unit -> unit) ->
+ ?period:float ->
+ ?display:((out_channel -> unit) -> unit) ->
+ ((unit -> string) list list) ->
+ (bool list * exn) option;
+ mutable report_error : Format.formatter -> exn -> unit;
+ mutable at_exit_once : (unit -> unit) -> unit;
+ mutable gettimeofday : unit -> float;
+ mutable stdout_isatty : unit -> bool;
+ mutable stat : string -> stats;
+ mutable lstat : string -> stats;
+ }
+
+let is_degraded = true
+
+let stat f =
+ { stat_key = f;
+ stat_file_kind =
+ if sys_file_exists f then
+ if Sys.is_directory f then
+ FK_dir
+ else
+ FK_file
+ else let _ = with_input_file f input_char in assert false }
+
+let run_and_open s kont =
+ with_temp_file "ocamlbuild" "out" begin fun tmp ->
+ let s = Printf.sprintf "%s > '%s'" s tmp in
+ let st = sys_command s in
+ if st <> 0 then failwith (Printf.sprintf "Error while running: %s" s);
+ with_input_file tmp kont
+ end
+
+exception Not_a_link
+exception No_such_file
+exception Link_to_directories_not_supported
+
+let readlinkcmd =
+ let cache = Hashtbl.create 32 in
+ fun x ->
+ try Hashtbl.find cache x
+ with Not_found ->
+ run_and_open (Printf.sprintf "readlink %s" (Filename.quote x)) begin fun ic ->
+ let y = String.chomp (input_line ic) in
+ Hashtbl.replace cache x y; y
+ end
+
+let rec readlink x =
+ if sys_file_exists x then
+ try
+ let y = readlinkcmd x in
+ let y =
+ if Filename.is_relative y then
+ Filename.concat (Filename.dirname x) y
+ else
+ y
+ in
+ if (lstat y).stat_file_kind = FK_dir then raise Link_to_directories_not_supported else y
+ with Failure(_) -> raise Not_a_link
+ else raise No_such_file
+
+and is_link x =
+ try ignore(readlink x); true with
+ | No_such_file | Not_a_link -> false
+
+and lstat x =
+ if is_link x then { stat_key = x; stat_file_kind = FK_link } else stat x
+
+let implem =
+ {
+ is_degraded = true;
+
+ stat = stat;
+ lstat = lstat;
+ readlink = readlink;
+ is_link = is_link;
+ run_and_open = run_and_open;
+
+ (* at_exit_once is at_exit in the degraded mode since fork is not accessible in this mode *)
+ at_exit_once = at_exit;
+ report_error = (fun _ -> raise);
+ gettimeofday = (fun () -> assert false);
+ stdout_isatty = (fun () -> false);
+ execute_many = (fun ?max_jobs:(_) ?ticker:(_) ?period:(_) ?display:(_) _ -> assert false)
+ }
+
+let is_degraded = lazy implem.is_degraded
+let stat x = implem.stat x
+let lstat x = implem.lstat x
+let readlink x = implem.readlink x
+let is_link x = implem.is_link x
+let run_and_open x = implem.run_and_open x
+let at_exit_once x = implem.at_exit_once x
+let report_error x = implem.report_error x
+let gettimeofday x = implem.gettimeofday x
+let stdout_isatty x = implem.stdout_isatty x
+let execute_many ?max_jobs = implem.execute_many ?max_jobs
+
+let run_and_read cmd =
+ let bufsiz = 2048 in
+ let buf = Bytes.create bufsiz in
+ let totalbuf = Buffer.create 4096 in
+ implem.run_and_open cmd begin fun ic ->
+ let rec loop pos =
+ let len = input ic buf 0 bufsiz in
+ if len > 0 then begin
+ Buffer.add_subbytes totalbuf buf 0 len;
+ loop (pos + len)
+ end
+ in loop 0; Buffer.contents totalbuf
+ end
diff --git a/ocamlbuild/my_unix.mli b/ocamlbuild/my_unix.mli
new file mode 100644
index 0000000000..d9cd7d00de
--- /dev/null
+++ b/ocamlbuild/my_unix.mli
@@ -0,0 +1,75 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+type file_kind =
+| FK_dir
+| FK_file
+| FK_link
+| FK_other
+
+type stats =
+ {
+ stat_file_kind : file_kind;
+ stat_key : string
+ }
+
+val is_degraded : bool Lazy.t
+
+val is_link : string -> bool
+val run_and_open : string -> (in_channel -> 'a) -> 'a
+val readlink : string -> string
+val run_and_read : string -> string
+
+(** See [Ocamlbuild_executor.execute] *)
+val execute_many :
+ ?max_jobs:int ->
+ ?ticker:(unit -> unit) ->
+ ?period:float ->
+ ?display:((out_channel -> unit) -> unit) ->
+ ((unit -> string) list list) ->
+ (bool list * exn) option
+
+val report_error : Format.formatter -> exn -> unit
+val at_exit_once : (unit -> unit) -> unit
+
+val gettimeofday : unit -> float
+
+val stdout_isatty : unit -> bool
+
+val stat : string -> stats
+val lstat : string -> stats
+
+(** internal usage only *)
+type implem =
+ {
+ mutable is_degraded : bool;
+ mutable is_link : string -> bool;
+ mutable run_and_open : 'a . string -> (in_channel -> 'a) -> 'a;
+ mutable readlink : string -> string;
+ mutable execute_many : ?max_jobs:int ->
+ ?ticker:(unit -> unit) ->
+ ?period:float ->
+ ?display:((out_channel -> unit) -> unit) ->
+ ((unit -> string) list list) ->
+ (bool list * exn) option;
+ mutable report_error : Format.formatter -> exn -> unit;
+ mutable at_exit_once : (unit -> unit) -> unit;
+ mutable gettimeofday : unit -> float;
+ mutable stdout_isatty : unit -> bool;
+ mutable stat : string -> stats;
+ mutable lstat : string -> stats;
+ }
+
+val implem : implem
diff --git a/ocamlbuild/ocaml_arch.ml b/ocamlbuild/ocaml_arch.ml
new file mode 100644
index 0000000000..0441983a85
--- /dev/null
+++ b/ocamlbuild/ocaml_arch.ml
@@ -0,0 +1,137 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Command
+open Pathname.Operators
+
+type 'a arch =
+ | Arch_dir of string * 'a * 'a arch list
+ | Arch_dir_pack of string * 'a * 'a arch list
+ | Arch_file of string * 'a
+
+let dir name contents = Arch_dir(name, (), contents)
+let dir_pack name contents = Arch_dir_pack(name, (), contents)
+let file name = Arch_file(name, ())
+
+type info =
+{
+ current_path : string;
+ include_dirs : string list;
+ for_pack : string;
+}
+
+let join_pack parent base =
+ if parent = "" then base else parent ^ "." ^ base
+
+let annotate arch =
+ let rec self arch acc =
+ match arch with
+ | Arch_dir_pack(name, _, contents) ->
+ let acc = { (acc) with for_pack = join_pack acc.for_pack name } in
+ let (_, _, i, new_contents) = self_contents name contents acc in
+ ([], Arch_dir_pack(name, i, List.rev new_contents))
+ | Arch_dir(name, _, contents) ->
+ let (current_path, include_dirs, i, new_contents) = self_contents name contents acc in
+ (current_path :: include_dirs, Arch_dir(name, i, List.rev new_contents))
+ | Arch_file(name, _) ->
+ ([], Arch_file(name, acc))
+ and self_contents name contents acc =
+ let current_path = acc.current_path/name in
+ let include_dirs = if current_path = "" then acc.include_dirs else current_path :: acc.include_dirs in
+ let i = { (acc) with current_path = current_path; include_dirs = include_dirs } in
+ let (include_dirs, new_contents) =
+ List.fold_left begin fun (include_dirs, new_contents) x ->
+ let j = { (i) with include_dirs = include_dirs @ i.include_dirs } in
+ let (include_dirs', x') = self x j in
+ (include_dirs @ include_dirs', x' :: new_contents)
+ end ([], []) contents in
+ (current_path, include_dirs, i, new_contents) in
+ let init = { current_path = ""; include_dirs = []; for_pack = "" } in
+ snd (self arch init)
+
+let rec print print_info f =
+ let rec print_contents f =
+ function
+ | [] -> ()
+ | x :: xs -> Format.fprintf f "@ %a%a" (print print_info) x print_contents xs in
+ function
+ | Arch_dir(name, info, contents) ->
+ Format.fprintf f "@[<v2>dir %S%a%a@]" name print_info info print_contents contents
+ | Arch_dir_pack(name, info, contents) ->
+ Format.fprintf f "@[<v2>dir_pack %S%a%a@]" name print_info info print_contents contents
+ | Arch_file(name, info) ->
+ Format.fprintf f "@[<2>file %S%a@]" name print_info info
+
+let print_include_dirs = List.print String.print
+
+let print_info f i =
+ Format.fprintf f "@ @[<v2>{ @[<2>current_path =@ %S@];@\
+ \ @[<2>include_dirs =@ %a@];@\
+ \ @[<2>for_pack =@ %S@] }@]"
+ i.current_path print_include_dirs i.include_dirs i.for_pack
+
+let rec iter_info f =
+ function
+ | Arch_dir_pack(_, i, xs) | Arch_dir(_, i, xs) ->
+ f i; List.iter (iter_info f) xs
+ | Arch_file(_, i) -> f i
+
+let rec fold_info f arch acc =
+ match arch with
+ | Arch_dir_pack(_, i, xs) | Arch_dir(_, i, xs) ->
+ List.fold_right (fold_info f) xs (f i acc)
+ | Arch_file(_, i) -> f i acc
+
+module SS = Set.Make(String)
+
+let iter_include_dirs arch =
+ let set = fold_info (fun i -> List.fold_right SS.add i.include_dirs) arch SS.empty in
+ fun f -> SS.iter f set
+
+let forpack_flags_of_pathname = ref (fun _ -> N)
+
+let print_table print_value f table =
+ Format.fprintf f "@[<hv0>{:@[<hv0>";
+ Hashtbl.iter begin fun k v ->
+ if k <> "" then
+ Format.fprintf f "@ @[<2>%S =>@ %a@];" k print_value v;
+ end table;
+ Format.fprintf f "@]@ :}@]"
+
+let print_tables f (include_dirs_table, for_pack_table) =
+ Format.fprintf f "@[<2>@[<2>include_dirs_table:@ %a@];@ @[<2>for_pack_table: %a@]@]"
+ (print_table (List.print String.print)) include_dirs_table
+ (print_table String.print) for_pack_table
+
+let mk_tables arch =
+ let include_dirs_table = Hashtbl.create 17
+ and for_pack_table = Hashtbl.create 17 in
+ iter_info begin fun i ->
+ Hashtbl.replace include_dirs_table i.current_path i.include_dirs;
+ Hashtbl.replace for_pack_table i.current_path i.for_pack
+ end arch;
+ let previous_forpack_flags_of_pathname = !forpack_flags_of_pathname in
+ forpack_flags_of_pathname := begin fun m ->
+ let m' = Pathname.dirname m in
+ try
+ let for_pack = Hashtbl.find for_pack_table m' in
+ if for_pack = "" then N else S[A"-for-pack"; A for_pack]
+ with Not_found -> previous_forpack_flags_of_pathname m
+ end;
+ (* Format.eprintf "@[<2>%a@]@." print_tables (include_dirs_table, for_pack_table); *)
+ (include_dirs_table, for_pack_table)
+
+let forpack_flags_of_pathname m = !forpack_flags_of_pathname m
diff --git a/ocamlbuild/ocaml_arch.mli b/ocamlbuild/ocaml_arch.mli
new file mode 100644
index 0000000000..aa396f1a97
--- /dev/null
+++ b/ocamlbuild/ocaml_arch.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+
+include Signatures.ARCH
+val forpack_flags_of_pathname : string -> Command.spec
diff --git a/ocamlbuild/ocaml_compiler.ml b/ocamlbuild/ocaml_compiler.ml
new file mode 100644
index 0000000000..e6d5becf7c
--- /dev/null
+++ b/ocamlbuild/ocaml_compiler.ml
@@ -0,0 +1,433 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Format
+open Log
+open Pathname.Operators
+open Tools
+open Command
+open Rule
+open Tags.Operators
+open Ocaml_utils
+open Rule.Common_commands
+open Outcome
+
+let forpack_flags arg tags =
+ if Tags.mem "pack" tags then
+ Ocaml_arch.forpack_flags_of_pathname arg
+ else N
+
+let ocamlc_c tags arg out =
+ let tags = tags++"ocaml"++"byte" in
+ Cmd (S [!Options.ocamlc; A"-c"; T(tags++"compile");
+ ocaml_ppflags tags; ocaml_include_flags arg; A"-o"; Px out; P arg])
+
+let ocamlc_link flag tags deps out =
+ Cmd (S [!Options.ocamlc; flag; T tags;
+ atomize_paths deps; A"-o"; Px out])
+
+let ocamlc_link_lib = ocamlc_link (A"-a")
+let ocamlc_link_prog = ocamlc_link N
+
+let ocamlmklib tags deps out =
+ Cmd (S [!Options.ocamlmklib; T tags;
+ atomize_paths deps; A"-o"; Px (Pathname.remove_extensions out)])
+
+let ocamlmktop tags deps out =
+ Cmd( S [!Options.ocamlmktop; T (tags++"mktop");
+ atomize_paths deps; A"-o"; Px out])
+
+let byte_lib_linker tags =
+ if Tags.mem "ocamlmklib" tags then
+ ocamlmklib tags
+ else
+ ocamlc_link_lib tags
+
+let byte_lib_linker_tags tags = tags++"ocaml"++"link"++"byte"++"library"
+
+let ocamlc_p tags deps out =
+ Cmd (S [!Options.ocamlc; A"-pack"; T tags;
+ atomize_paths deps; A"-o"; Px out])
+
+let ocamlopt_c tags arg out =
+ let tags = tags++"ocaml"++"native" in
+ Cmd (S [!Options.ocamlopt; A"-c"; Ocaml_arch.forpack_flags_of_pathname arg;
+ T(tags++"compile"); ocaml_ppflags tags; ocaml_include_flags arg;
+ A"-o"; Px out (* FIXME ocamlopt bug -o cannot be after the input file *); P arg])
+
+let ocamlopt_link flag tags deps out =
+ Cmd (S [!Options.ocamlopt; flag; forpack_flags out tags; T tags;
+ atomize_paths deps; A"-o"; Px out])
+
+let ocamlopt_link_lib = ocamlopt_link (A"-a")
+let ocamlopt_link_shared_lib = ocamlopt_link (A"-shared")
+let ocamlopt_link_prog = ocamlopt_link N
+
+let ocamlopt_p tags deps out =
+ let dirnames = List.union [] (List.map Pathname.dirname deps) in
+ let include_flags = List.fold_right ocaml_add_include_flag dirnames [] in
+ let mli = Pathname.update_extensions "mli" out in
+ let cmd =
+ S [!Options.ocamlopt; A"-pack"; forpack_flags out tags; T tags;
+ S include_flags; atomize_paths deps;
+ A"-o"; Px out] in
+ if (*FIXME true ||*) Pathname.exists mli then Cmd cmd
+ else
+ let rm = S[A"rm"; A"-f"; P mli] in
+ Cmd(S[A"touch"; P mli; Sh" ; if "; cmd; Sh" ; then "; rm; Sh" ; else ";
+ rm; Sh" ; exit 1; fi"])
+
+let native_lib_linker tags =
+ if Tags.mem "ocamlmklib" tags then
+ ocamlmklib tags
+ else
+ ocamlopt_link_lib tags
+
+let native_shared_lib_linker tags =
+(* ocamlmklib seems to not support -shared, is this OK?
+ if Tags.mem "ocamlmklib" tags then
+ ocamlmklib tags
+ else
+*)
+ ocamlopt_link_shared_lib tags
+
+let native_lib_linker_tags tags = tags++"ocaml"++"link"++"native"++"library"
+
+
+let prepare_compile build ml =
+ let dir = Pathname.dirname ml in
+ let include_dirs = Pathname.include_dirs_of dir in
+ let modules = path_dependencies_of ml in
+ let results =
+ build (List.map (fun (_, x) -> expand_module include_dirs x ["cmi"]) modules) in
+ List.iter2 begin fun (mandatory, name) res ->
+ match mandatory, res with
+ | _, Good _ -> ()
+ | `mandatory, Bad exn ->
+ if not !Options.ignore_auto then raise exn;
+ dprintf 3
+ "Warning: Failed to build the module %s requested by ocamldep."
+ name;
+ if not (!Options.recursive || Options.ocamlbuild_project_heuristic ())
+ then Log.at_failure ~name:"a module failed to build,
+ while recursive traversal was disabled by fragile heuristic;
+ hint that having a _tags or myocamlbuild.ml would maybe solve
+ the build error"
+ (fun `Error ->
+ eprintf "Hint:@ Recursive@ traversal@ of@ subdirectories@ \
+ was@ not@ enabled@ for@ this@ build,@ as@ the@ working@ \
+ directory does@ not@ look@ like@ an@ ocamlbuild@ project@ \
+ (no@ '_tags'@ or@ 'myocamlbuild.ml'@ file).@ \
+ If@ you@ have@ modules@ in@ subdirectories,@ you@ should@ add@ \
+ the@ option@ \"-r\"@ or@ create@ an@ empty@ '_tags'@ file.@\n\
+ @\n\
+ To@ enable@ recursive@ traversal@ for@ some@ subdirectories@ \
+ only,@ you@ can@ use@ the@ following@ '_tags'@ file:@\n\
+ @[<v 4>@,\
+ true: -traverse@,\
+ <dir1> or <dir2>: traverse@,\
+ @]"
+ );
+ | `just_try, Bad _ -> ()
+ end modules results
+
+let byte_compile_ocaml_interf mli cmi env build =
+ let mli = env mli and cmi = env cmi in
+ prepare_compile build mli;
+ ocamlc_c (tags_of_pathname mli++"interf") mli cmi
+
+(* given that .cmi can be built from either ocamlc and ocamlopt, this
+ "agnostic" rule chooses either compilers depending on whether the
+ "native" tag is present. This was requested during PR#4613 as way
+ to enable using ocamlbuild in environments where only ocamlopt is
+ available, not ocamlc. *)
+let compile_ocaml_interf mli cmi env build =
+ let mli = env mli and cmi = env cmi in
+ prepare_compile build mli;
+ let tags = tags_of_pathname mli++"interf" in
+ let comp_c = if Tags.mem "native" tags then ocamlopt_c else ocamlc_c in
+ comp_c tags mli cmi
+
+let byte_compile_ocaml_implem ?tag ml cmo env build =
+ let ml = env ml and cmo = env cmo in
+ prepare_compile build ml;
+ ocamlc_c (Tags.union (tags_of_pathname ml) (tags_of_pathname cmo)++"implem"+++tag) ml cmo
+
+let cache_prepare_link = Hashtbl.create 107
+let rec prepare_link tag cmx extensions build =
+ let key = (tag, cmx, extensions) in
+ let dir = Pathname.dirname cmx in
+ let include_dirs = Pathname.include_dirs_of dir in
+ let ml = Pathname.update_extensions "ml" cmx in
+ let mli = Pathname.update_extensions "mli" cmx in
+ let modules =
+ List.union
+ (if Pathname.exists (ml-.-"depends") then path_dependencies_of ml else [])
+ (if Pathname.exists (mli-.-"depends") then path_dependencies_of mli else [])
+ in
+ let modules =
+ if (modules = []) && (Pathname.exists (ml^"pack")) then
+ List.map (fun s -> (`mandatory, s)) (string_list_of_file (ml^"pack"))
+ else
+ modules
+ in
+ if modules <> [] && not (Hashtbl.mem cache_prepare_link key) then
+ let () = Hashtbl.add cache_prepare_link key true in
+ let modules' = List.map (fun (_, x) -> expand_module include_dirs x extensions) modules in
+ List.iter2 begin fun (mandatory, _) result ->
+ match mandatory, result with
+ | _, Good p -> prepare_link tag p extensions build
+ | `mandatory, Bad exn -> if not !Options.ignore_auto then raise exn
+ | `just_try, Bad _ -> ()
+ end modules (build modules')
+
+let native_compile_ocaml_implem ?tag ?(cmx_ext="cmx") ml env build =
+ let ml = env ml in
+ let cmi = Pathname.update_extensions "cmi" ml in
+ let cmx = Pathname.update_extensions cmx_ext ml in
+ prepare_link cmx cmi [cmx_ext; "cmi"] build;
+ ocamlopt_c (Tags.union (tags_of_pathname ml) (tags_of_pathname cmx)++"implem"+++tag) ml cmx
+
+let libs_of_use_lib tags =
+ Tags.fold begin fun tag acc ->
+ try let libpath, extern = Hashtbl.find info_libraries tag in
+ if extern then acc else libpath :: acc
+ with Not_found -> acc
+ end tags []
+
+let prepare_libs cma_ext a_ext out build =
+ let out_no_ext = Pathname.remove_extension out in
+ let libs1 = List.union (libraries_of out_no_ext) (libs_of_use_lib (tags_of_pathname out)) in
+ let () = dprintf 10 "prepare_libs: %S -> %a" out pp_l libs1 in
+ let libs = List.map (fun x -> x-.-cma_ext) libs1 in
+ let libs2 = List.map (fun lib -> [lib-.-a_ext]) libs1 in
+ List.iter ignore_good (build libs2); libs
+
+let library_index = Hashtbl.create 32
+let package_index = Hashtbl.create 32
+let hidden_packages = ref []
+
+let hide_package_contents package = hidden_packages := package :: !hidden_packages
+
+module Ocaml_dependencies_input = struct
+ let fold_dependencies = Resource.Cache.fold_dependencies
+ let fold_libraries f = Hashtbl.fold f library_index
+ let fold_packages f = Hashtbl.fold f package_index
+end
+module Ocaml_dependencies = Ocaml_dependencies.Make(Ocaml_dependencies_input)
+
+let caml_transitive_closure = Ocaml_dependencies.caml_transitive_closure
+
+let link_one_gen linker tagger cmX out env _build =
+ let cmX = env cmX and out = env out in
+ let tags = tagger (tags_of_pathname out) in
+ linker tags [cmX] out
+
+let link_gen cmX_ext cma_ext a_ext extensions linker tagger cmX out env build =
+ let cmX = env cmX and out = env out in
+ let tags = tagger (tags_of_pathname out) in
+ let dyndeps = Rule.build_deps_of_tags build (tags++"link_with") in
+ let cmi = Pathname.update_extensions "cmi" cmX in
+ prepare_link cmX cmi extensions build;
+ let libs = prepare_libs cma_ext a_ext out build in
+ let hidden_packages = List.map (fun x -> x-.-cmX_ext) !hidden_packages in
+ let deps =
+ caml_transitive_closure
+ ~caml_obj_ext:cmX_ext ~caml_lib_ext:cma_ext
+ ~used_libraries:libs ~hidden_packages (cmX :: dyndeps) in
+ let deps = (List.filter (fun l -> not (List.mem l deps)) libs) @ deps in
+
+ (* Hack to avoid linking twice with the standard library. *)
+ let stdlib = "stdlib/stdlib"-.-cma_ext in
+ let is_not_stdlib x = x <> stdlib in
+ let deps = List.filter is_not_stdlib deps in
+
+ if deps = [] then failwith "Link list cannot be empty";
+ let () = dprintf 6 "link: %a -o %a" print_string_list deps Pathname.print out in
+ linker (tags++"dont_link_with") deps out
+
+let byte_link_gen = link_gen "cmo" "cma" "cma" ["cmo"; "cmi"]
+
+let byte_link = byte_link_gen ocamlc_link_prog
+ (fun tags -> tags++"ocaml"++"link"++"byte"++"program")
+
+let byte_output_obj = byte_link_gen ocamlc_link_prog
+ (fun tags -> tags++"ocaml"++"link"++"byte"++"output_obj")
+
+let byte_output_shared = byte_link_gen ocamlc_link_prog
+ (fun tags -> tags++"ocaml"++"link"++"byte"++"output_obj"++"output_shared")
+
+let byte_library_link = byte_link_gen byte_lib_linker byte_lib_linker_tags
+
+let byte_debug_link_gen =
+ link_gen "d.cmo" "d.cma" "d.cma" ["d.cmo"; "cmi"]
+
+let byte_debug_link = byte_debug_link_gen ocamlc_link_prog
+ (fun tags -> tags++"ocaml"++"link"++"byte"++"debug"++"program")
+
+let byte_debug_library_link = byte_debug_link_gen byte_lib_linker
+ (fun tags -> byte_lib_linker_tags tags++"debug")
+
+let native_link_gen linker =
+ link_gen "cmx" "cmxa" !Options.ext_lib [!Options.ext_obj; "cmi"] linker
+
+let native_link x = native_link_gen ocamlopt_link_prog
+ (fun tags -> tags++"ocaml"++"link"++"native"++"program") x
+
+let native_output_obj x = native_link_gen ocamlopt_link_prog
+ (fun tags -> tags++"ocaml"++"link"++"native"++"output_obj") x
+
+let native_output_shared x = native_link_gen ocamlopt_link_prog
+ (fun tags -> tags++"ocaml"++"link"++"native"++"output_obj"++"output_shared") x
+
+let native_library_link x =
+ native_link_gen native_lib_linker native_lib_linker_tags x
+
+let native_profile_link_gen linker =
+ link_gen "p.cmx" "p.cmxa" ("p" -.- !Options.ext_lib) ["p" -.- !Options.ext_obj; "cmi"] linker
+
+let native_profile_link x = native_profile_link_gen ocamlopt_link_prog
+ (fun tags -> tags++"ocaml"++"link"++"native"++"profile"++"program") x
+
+let native_profile_library_link x = native_profile_link_gen native_lib_linker
+ (fun tags -> native_lib_linker_tags tags++"profile") x
+
+let link_units table extensions cmX_ext cma_ext a_ext linker tagger contents_list cmX env build =
+ let cmX = env cmX in
+ let tags = tagger (tags_of_pathname cmX) in
+ let _ = Rule.build_deps_of_tags build tags in
+ let dir =
+ let dir1 = Pathname.remove_extensions cmX in
+ if Resource.exists_in_source_dir dir1 then dir1
+ else Pathname.dirname cmX in
+ let include_dirs = Pathname.include_dirs_of dir in
+ let extension_keys = List.map fst extensions in
+ let libs = prepare_libs cma_ext a_ext cmX build in
+ let results =
+ build begin
+ List.map begin fun module_name ->
+ expand_module include_dirs module_name extension_keys
+ end contents_list
+ end in
+ let module_paths =
+ List.map begin function
+ | Good p ->
+ let extension_values = List.assoc (Pathname.get_extensions p) extensions in
+ List.iter begin fun ext ->
+ List.iter ignore_good (build [[Pathname.update_extensions ext p]])
+ end extension_values; p
+ | Bad exn -> raise exn
+ end results in
+ Hashtbl.replace table cmX module_paths;
+ let hidden_packages = List.map (fun x -> x-.-cmX_ext) !hidden_packages in
+ let deps =
+ caml_transitive_closure
+ ~caml_obj_ext:cmX_ext ~caml_lib_ext:cma_ext
+ ~hidden_packages ~pack_mode:true module_paths in
+ let full_contents = libs @ module_paths in
+ let deps = List.filter (fun x -> List.mem x full_contents) deps in
+ let deps = (List.filter (fun l -> not (List.mem l deps)) libs) @ deps in
+
+ (* Hack to avoid linking twice with the standard library. *)
+ let stdlib = "stdlib/stdlib"-.-cma_ext in
+ let is_not_stdlib x = x <> stdlib in
+ let deps = List.filter is_not_stdlib deps in
+
+ linker tags deps cmX
+
+let link_modules = link_units library_index
+let pack_modules = link_units package_index
+
+let link_from_file link modules_file cmX env build =
+ let modules_file = env modules_file in
+ let contents_list = string_list_of_file modules_file in
+ link contents_list cmX env build
+
+let byte_library_link_modules =
+ link_modules [("cmo",[])] "cmo" "cma" "cma" byte_lib_linker byte_lib_linker_tags
+
+let byte_library_link_mllib = link_from_file byte_library_link_modules
+
+let byte_toplevel_link_modules =
+ link_modules [("cmo",[])] "cmo" "cma" "cma" ocamlmktop
+ (fun tags -> tags++"ocaml"++"link"++"byte"++"toplevel")
+
+let byte_toplevel_link_mltop = link_from_file byte_toplevel_link_modules
+
+let byte_debug_library_link_modules =
+ link_modules [("d.cmo",[])] "d.cmo" "d.cma" "d.cma" byte_lib_linker
+ (fun tags -> byte_lib_linker_tags tags++"debug")
+
+let byte_debug_library_link_mllib = link_from_file byte_debug_library_link_modules
+
+let byte_pack_modules =
+ pack_modules [("cmo",["cmi"]); ("cmi",[])] "cmo" "cma" "cma" ocamlc_p
+ (fun tags -> tags++"ocaml"++"pack"++"byte")
+
+let byte_pack_mlpack = link_from_file byte_pack_modules
+
+let byte_debug_pack_modules =
+ pack_modules [("d.cmo",["cmi"]); ("cmi",[])] "d.cmo" "d.cma" "d.cma" ocamlc_p
+ (fun tags -> tags++"ocaml"++"pack"++"byte"++"debug")
+
+let byte_debug_pack_mlpack = link_from_file byte_debug_pack_modules
+
+let native_pack_modules x =
+ pack_modules [("cmx",["cmi"; !Options.ext_obj]); ("cmi",[])] "cmx" "cmxa" !Options.ext_lib ocamlopt_p
+ (fun tags -> tags++"ocaml"++"pack"++"native") x
+
+let native_pack_mlpack = link_from_file native_pack_modules
+
+let native_profile_pack_modules x =
+ pack_modules [("p.cmx",["cmi"; "p" -.- !Options.ext_obj]); ("cmi",[])] "p.cmx" "p.cmxa"
+ ("p" -.- !Options.ext_lib) ocamlopt_p
+ (fun tags -> tags++"ocaml"++"pack"++"native"++"profile") x
+
+let native_profile_pack_mlpack = link_from_file native_profile_pack_modules
+
+let native_library_link_modules x =
+ link_modules [("cmx",[!Options.ext_obj])] "cmx" "cmxa"
+ !Options.ext_lib native_lib_linker native_lib_linker_tags x
+
+let native_shared_library_link_modules x =
+ link_modules [("cmx",[!Options.ext_obj])] "cmx" "cmxa"
+ !Options.ext_lib native_shared_lib_linker
+ (fun tags -> native_lib_linker_tags tags++"shared") x
+
+let native_library_link_mllib = link_from_file native_library_link_modules
+
+let native_shared_library_link_mldylib = link_from_file native_shared_library_link_modules
+
+let native_shared_library_tags tags basetags =
+ List.fold_left (++) (basetags++"ocaml"++"link"++"native"++"shared"++"library") tags
+
+let native_shared_library_link ?(tags = []) x =
+ link_one_gen native_shared_lib_linker
+ (native_shared_library_tags tags) x
+
+let native_profile_library_link_modules x =
+ link_modules [("p.cmx",["p" -.- !Options.ext_obj])] "p.cmx" "p.cmxa"
+ ("p" -.- !Options.ext_lib) native_lib_linker
+ (fun tags -> native_lib_linker_tags tags++"profile") x
+
+let native_profile_shared_library_link_modules x =
+ link_modules [("p.cmx",["p" -.- !Options.ext_obj])] "p.cmx" "p.cmxa"
+ ("p" -.- !Options.ext_lib) native_shared_lib_linker
+ (fun tags -> native_lib_linker_tags tags++"shared"++"profile") x
+
+let native_profile_library_link_mllib = link_from_file native_profile_library_link_modules
+
+let native_profile_shared_library_link_mldylib = link_from_file native_profile_shared_library_link_modules
diff --git a/ocamlbuild/ocaml_compiler.mli b/ocamlbuild/ocaml_compiler.mli
new file mode 100644
index 0000000000..445955958e
--- /dev/null
+++ b/ocamlbuild/ocaml_compiler.mli
@@ -0,0 +1,97 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+
+val forpack_flags : string -> Tags.t -> Command.spec
+val ocamlc_c : Tags.t -> Pathname.t -> Pathname.t -> Command.t
+val ocamlc_link_lib : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val ocamlc_link_prog : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val ocamlc_p : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val ocamlopt_c : Tags.t -> Pathname.t -> Pathname.t -> Command.t
+val ocamlopt_link_lib : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val ocamlopt_link_shared_lib : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val ocamlopt_link_prog : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val ocamlopt_p : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val ocamlmklib : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val ocamlmktop : Tags.t -> Pathname.t list -> Pathname.t -> Command.t
+val prepare_compile : Rule.builder -> Pathname.t -> unit
+val compile_ocaml_interf : string -> string -> Rule.action
+val byte_compile_ocaml_interf : string -> string -> Rule.action
+val byte_compile_ocaml_implem : ?tag:string -> string -> string -> Rule.action
+val prepare_link :
+ Pathname.t -> Pathname.t ->
+ string list -> Rule.builder -> unit
+val native_compile_ocaml_implem : ?tag:string -> ?cmx_ext:string -> string -> Rule.action
+val prepare_libs :
+ string -> string -> Pathname.t ->
+ Rule.builder -> Pathname.t list
+val link_gen :
+ string -> string -> string -> string list ->
+ (Tags.t -> Pathname.t list -> Pathname.t -> Command.t) ->
+ (Tags.t -> Tags.t) ->
+ string -> string -> Rule.action
+val byte_link : string -> string -> Rule.action
+val byte_output_obj : string -> string -> Rule.action
+val byte_output_shared : string -> string -> Rule.action
+val byte_library_link : string -> string -> Rule.action
+val byte_debug_link : string -> string -> Rule.action
+val byte_debug_library_link : string -> string -> Rule.action
+val native_link : string -> string -> Rule.action
+val native_output_obj : string -> string -> Rule.action
+val native_output_shared : string -> string -> Rule.action
+val native_library_link : string -> string -> Rule.action
+val native_shared_library_link : ?tags:(string list) -> string -> string -> Rule.action
+val native_profile_link : string -> string -> Rule.action
+val native_profile_library_link : string -> string -> Rule.action
+val link_modules :
+ (Pathname.t * string list) list ->
+ string -> string ->
+ string -> (Tags.t -> Pathname.t list -> Pathname.t -> Command.t) ->
+ (Tags.t -> Tags.t) ->
+ string list -> string -> Rule.action
+val pack_modules :
+ (Pathname.t * string list) list ->
+ string -> string ->
+ string -> (Tags.t -> Pathname.t list -> Pathname.t -> Command.t) ->
+ (Tags.t -> Tags.t) ->
+ string list -> string -> Rule.action
+val byte_library_link_modules : string list -> string -> Rule.action
+val byte_library_link_mllib : string -> string -> Rule.action
+val byte_debug_library_link_modules : string list -> string -> Rule.action
+val byte_debug_library_link_mllib : string -> string -> Rule.action
+val byte_pack_modules : string list -> string -> Rule.action
+val byte_pack_mlpack : string -> string -> Rule.action
+val byte_debug_pack_modules : string list -> string -> Rule.action
+val byte_debug_pack_mlpack : string -> string -> Rule.action
+val byte_toplevel_link_modules : string list -> string -> Rule.action
+val byte_toplevel_link_mltop : string -> string -> Rule.action
+val native_pack_modules : string list -> string -> Rule.action
+val native_pack_mlpack : string -> string -> Rule.action
+val native_library_link_modules : string list -> string -> Rule.action
+val native_library_link_mllib : string -> string -> Rule.action
+val native_shared_library_link_modules : string list -> string -> Rule.action
+val native_shared_library_link_mldylib : string -> string -> Rule.action
+val native_profile_pack_modules : string list -> string -> Rule.action
+val native_profile_pack_mlpack : string -> string -> Rule.action
+val native_profile_library_link_modules : string list -> string -> Rule.action
+val native_profile_library_link_mllib : string -> string -> Rule.action
+val native_profile_shared_library_link_modules : string list -> string -> Rule.action
+val native_profile_shared_library_link_mldylib : string -> string -> Rule.action
+
+(** [hide_package_contents pack_name]
+ Don't treat the given package as an open package.
+ So a module will not be replaced during linking by
+ this package even if it contains that module. *)
+val hide_package_contents : string -> unit
diff --git a/ocamlbuild/ocaml_dependencies.ml b/ocamlbuild/ocaml_dependencies.ml
new file mode 100644
index 0000000000..c623937581
--- /dev/null
+++ b/ocamlbuild/ocaml_dependencies.ml
@@ -0,0 +1,263 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Log
+open Tools
+open Ocaml_utils
+
+let mydprintf fmt = dprintf 10 fmt
+
+exception Circular_dependencies of string list * string
+
+module type INPUT = sig
+ val fold_dependencies : (string -> string -> 'a -> 'a) -> 'a -> 'a
+ val fold_libraries : (string -> string list -> 'a -> 'a) -> 'a -> 'a
+ val fold_packages : (string -> string list -> 'a -> 'a) -> 'a -> 'a
+end
+
+module Make (I : INPUT) = struct
+ open I
+
+ module SMap = Map.Make(String)
+
+ module Resources = Resource.Resources
+
+ module Utils = struct
+ let add = SMap.add
+
+ let empty = SMap.empty
+
+ let find_all_set x acc =
+ try SMap.find x acc with Not_found -> Resources.empty
+
+ let smap_add_set src dst acc =
+ SMap.add src (Resources.add dst (find_all_set src acc)) acc
+
+ let print_smap pp f smap =
+ Format.fprintf f "@[<hv0>{:@[<hv2>";
+ SMap.iter begin fun k v ->
+ Format.fprintf f "@ @[<2>%S =>@ %a@];" k pp v
+ end smap;
+ Format.fprintf f "@]@,:}@]"
+
+ let print_smap_list = print_smap pp_l
+
+ let print_smap_set = print_smap Resources.print
+
+ let print_lazy pp f l = pp f !*l
+
+ let find_all_list x acc =
+ try SMap.find x acc with Not_found -> []
+
+ let find_all_rec xs map =
+ let visited = Hashtbl.create 32 in
+ let rec self x acc =
+ try
+ Hashtbl.find visited x; acc
+ with Not_found ->
+ Hashtbl.replace visited x ();
+ let acc = Resources.add x acc in
+ try Resources.fold self (SMap.find x map) acc
+ with Not_found -> acc
+ in List.fold_right self xs Resources.empty
+
+ let mkindex fold filter =
+ fold begin fun name contents acc ->
+ if filter name then
+ List.fold_right begin fun elt acc ->
+ add elt (name :: (find_all_list elt acc)) acc
+ end contents acc
+ else
+ acc
+ end empty
+
+ end
+ open Utils
+
+ let caml_transitive_closure
+ ?(caml_obj_ext="cmo")
+ ?(caml_lib_ext="cma")
+ ?(pack_mode=false)
+ ?(used_libraries=[])
+ ?(hidden_packages=[]) fns =
+
+ let valid_link_exts =
+ if pack_mode then [caml_obj_ext; "cmi"]
+ else [caml_obj_ext; caml_lib_ext] in
+
+ mydprintf "caml_transitive_closure@ ~caml_obj_ext:%S@ ~pack_mode:%b@ ~used_libraries:%a@ %a"
+ caml_obj_ext pack_mode pp_l used_libraries pp_l fns;
+
+ let packages = fold_packages (fun name _ -> Resources.add name) Resources.empty in
+ mydprintf "packages:@ %a" Resources.print packages;
+
+ let caml_obj_ext_of_cmi x =
+ if Filename.check_suffix x ".cmi" then
+ Pathname.update_extensions caml_obj_ext x
+ else x in
+
+ let maybe_caml_obj_ext_of_cmi x =
+ if pack_mode then
+ if Filename.check_suffix x ".cmi" then
+ let caml_obj = Pathname.update_extensions caml_obj_ext x in
+ if Resource.exists_in_build_dir caml_obj then
+ caml_obj
+ else
+ x
+ else
+ x
+ else
+ if Filename.check_suffix x ".cmi" then
+ Pathname.update_extensions caml_obj_ext x
+ else x in
+
+ let not_linkable x =
+ not (List.exists (Pathname.check_extension x) valid_link_exts) in
+
+ let dependency_map =
+ fold_dependencies begin fun x y acc ->
+ let x = maybe_caml_obj_ext_of_cmi x
+ and y = maybe_caml_obj_ext_of_cmi y in
+ if x = y || not_linkable x || not_linkable y then acc
+ else smap_add_set x y acc
+ end SMap.empty in
+ mydprintf "dependency_map:@ %a" print_smap_set dependency_map;
+
+ let used_files = find_all_rec fns dependency_map in
+ mydprintf "used_files:@ %a" Resources.print used_files;
+
+ let open_packages =
+ Resources.fold begin fun file acc ->
+ if Resources.mem file packages && not (List.mem file hidden_packages)
+ then file :: acc else acc
+ end used_files [] in
+ mydprintf "open_packages:@ %a" pp_l open_packages;
+
+ let index_filter ext list x =
+ Pathname.check_extension x ext && List.mem x list in
+
+ let lib_index =
+ lazy (mkindex fold_libraries (index_filter caml_lib_ext used_libraries)) in
+ mydprintf "lib_index:@ %a" (print_lazy print_smap_list) lib_index;
+
+ let package_index =
+ lazy (mkindex fold_packages (index_filter caml_obj_ext open_packages)) in
+
+ let rec resolve_packages x =
+ match find_all_list x !*package_index with
+ | [] -> x
+ | [x] -> resolve_packages x
+ | pkgs ->
+ failwith (sbprintf "the file %S is included in more than one active open package (%a)"
+ x pp_l pkgs) in
+
+ let libs_of x = find_all_list x !*lib_index in
+
+ let lib_of x =
+ match libs_of x with
+ | [] -> None
+ | [lib] -> Some(lib)
+ | libs ->
+ failwith (sbprintf "the file %S is included in more than one active library (%a)"
+ x pp_l libs) in
+
+ let convert_dependency src dst acc =
+ let src = resolve_packages src in
+ let dst = resolve_packages dst in
+ let add_if_diff x y = if x = y then acc else smap_add_set x y acc in
+ match (lib_of src, lib_of dst) with
+ | None, None -> add_if_diff src dst
+ | Some(liba), Some(libb) -> add_if_diff liba libb
+ | Some(lib), None -> add_if_diff lib dst
+ | None, Some(lib) -> add_if_diff src lib in
+
+ let dependencies = lazy begin
+ SMap.fold begin fun k ->
+ Resources.fold (convert_dependency k)
+ end dependency_map empty
+ end in
+
+ mydprintf "dependencies:@ %a" (print_lazy print_smap_set) dependencies;
+
+ let dependencies_of x =
+ try SMap.find x !*dependencies with Not_found -> Resources.empty in
+
+ let refine_cycle files starting_file =
+ (* We are looking for a cycle starting from [fn], included in
+ [files]; we'll simply use a DFS which builds a path until it
+ finds a circularity.
+
+ Note that if there is at least one cycle going through [fn],
+ calling [dfs path fn] will return it no matter what [path] is
+ (it may just not be the shortest possible cycle). This means
+ that if [dfs path fn] returns [None], [fn] is a dead-end that
+ should never be explored again.
+ *)
+ let dead_ends = ref Resources.empty in
+ let rec dfs path fn =
+ let through_dep f = function
+ | Some _ as cycle -> cycle
+ | None ->
+ if List.mem f path
+ then (* we have found a cycle *)
+ Some (List.rev path)
+ else if not (Resources.mem f files)
+ then
+ (* the neighbor is not in the set of paths known to have a cycle *)
+ None
+ else
+ (* look for cycles going through this neighbor *)
+ dfs (f :: path) f
+ in
+ if Resources.mem fn !dead_ends then None
+ else match Resources.fold through_dep (dependencies_of fn) None with
+ | Some _ as cycle -> cycle
+ | None -> dead_ends := Resources.add fn !dead_ends; None
+ in
+ match dfs [] starting_file with
+ | None -> Resources.elements files
+ | Some cycle -> cycle
+ in
+
+ let needed_in_order = ref [] in
+ let needed = ref Resources.empty in
+ let seen = ref Resources.empty in
+ let rec aux fn =
+ if sys_file_exists fn && not (Resources.mem fn !needed) then begin
+ if Resources.mem fn !seen then
+ raise (Circular_dependencies (refine_cycle !seen fn, fn));
+ seen := Resources.add fn !seen;
+ Resources.iter begin fun f ->
+ if sys_file_exists f then
+ if Filename.check_suffix f ".cmi" then
+ let f' = caml_obj_ext_of_cmi f in
+ if f' <> fn then
+ if sys_file_exists f' then aux f'
+ else if pack_mode then aux f else ()
+ else ()
+ else aux f
+ end (dependencies_of fn);
+ needed := Resources.add fn !needed;
+ needed_in_order := fn :: !needed_in_order
+ end
+ in
+ List.iter aux fns;
+ mydprintf "caml_transitive_closure:@ %a ->@ %a"
+ pp_l fns pp_l !needed_in_order;
+ List.rev !needed_in_order
+
+
+end
diff --git a/ocamlbuild/ocaml_dependencies.mli b/ocamlbuild/ocaml_dependencies.mli
new file mode 100644
index 0000000000..345e8d8288
--- /dev/null
+++ b/ocamlbuild/ocaml_dependencies.mli
@@ -0,0 +1,45 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(** OCaml dependencies *)
+
+exception Circular_dependencies of string list * string
+
+(** Give to this module a way to access libraries, packages,
+ and dependencies between files. *)
+module type INPUT = sig
+ val fold_dependencies : (string -> string -> 'a -> 'a) -> 'a -> 'a
+ val fold_libraries : (string -> string list -> 'a -> 'a) -> 'a -> 'a
+ val fold_packages : (string -> string list -> 'a -> 'a) -> 'a -> 'a
+end
+
+(** Wait an [INPUT] module and gives a function to compute the
+ transitive closure of caml file takeing in account libraries and packages. *)
+module Make (I : INPUT) : sig
+
+ (** [caml_transitive_closure] takes a list of root ocaml compiled files and returns
+ the list of files that must be given to a linker. Optionally you can change the
+ extension of caml object/library files (cmo/cma by default); use the pack mode
+ (false by default) to include only root files (just sort them); and gives the
+ list of used libraries (empty by default). *)
+ val caml_transitive_closure :
+ ?caml_obj_ext:string ->
+ ?caml_lib_ext:string ->
+ ?pack_mode:bool ->
+ ?used_libraries:string list ->
+ ?hidden_packages:string list ->
+ Pathname.t list -> Pathname.t list
+
+end
diff --git a/ocamlbuild/ocaml_specific.ml b/ocamlbuild/ocaml_specific.ml
new file mode 100644
index 0000000000..b902810ad7
--- /dev/null
+++ b/ocamlbuild/ocaml_specific.ml
@@ -0,0 +1,806 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Format
+open Log
+open Pathname.Operators
+open Tags.Operators
+open Rule
+open Tools
+open Rule.Common_commands
+open Outcome
+open Command;;
+
+open Ocaml_utils
+
+module C_tools = struct
+ let link_C_library clib a libname env build =
+ let clib = env clib and a = env a and libname = env libname in
+ let objs = string_list_of_file clib in
+ let include_dirs = Pathname.include_dirs_of (Pathname.dirname a) in
+ let obj_of_o x =
+ if Filename.check_suffix x ".o" && !Options.ext_obj <> "o" then
+ Pathname.update_extension !Options.ext_obj x
+ else x in
+ let resluts = build (List.map (fun o -> List.map (fun dir -> dir / obj_of_o o) include_dirs) objs) in
+ let objs = List.map begin function
+ | Good o -> o
+ | Bad exn -> raise exn
+ end resluts in
+ Cmd(S[!Options.ocamlmklib; A"-o"; Px libname; T(tags_of_pathname a++"c"++"ocamlmklib"); atomize objs]);;
+end
+
+open Flags
+open Command
+open Rule
+
+let init () = let module M = struct
+
+let ext_lib = !Options.ext_lib;;
+let ext_obj = !Options.ext_obj;;
+let ext_dll = !Options.ext_dll;;
+let x_o = "%"-.-ext_obj;;
+let x_a = "%"-.-ext_lib;;
+let x_dll = "%"-.-ext_dll;;
+let x_p_o = "%.p"-.-ext_obj;;
+let x_p_a = "%.p"-.-ext_lib;;
+let x_p_dll = "%.p"-.-ext_dll;;
+
+(* -output-obj targets *)
+let x_byte_c = "%.byte.c";;
+let x_byte_o = "%.byte"-.-ext_obj;;
+let x_byte_so = "%.byte"-.-ext_dll;;
+let x_native_o = "%.native"-.-ext_obj;;
+let x_native_so = "%.native"-.-ext_dll;;
+
+rule "target files"
+ ~dep:"%.itarget"
+ ~stamp:"%.otarget"
+ ~doc:"If foo.itarget contains a list of ocamlbuild targets, \
+ asking ocamlbuild to produce foo.otarget will \
+ build each of those targets in turn."
+ begin fun env build ->
+ let itarget = env "%.itarget" in
+ let targets =
+ let dir = Pathname.dirname itarget in
+ let files = string_list_of_file itarget in
+ List.map (fun file -> [Pathname.concat dir file]) files
+ in
+ let results = List.map Outcome.good (build targets) in
+ let link_command result =
+ Cmd (S [A "ln"; A "-sf";
+ P (Pathname.concat !Options.build_dir result);
+ A Pathname.pwd])
+ in
+ if not !Options.make_links
+ then Nop
+ else Seq (List.map link_command results)
+ end;;
+
+rule "ocaml: mli -> cmi"
+ ~prod:"%.cmi"
+ ~deps:["%.mli"; "%.mli.depends"]
+ (Ocaml_compiler.compile_ocaml_interf "%.mli" "%.cmi");;
+
+rule "ocaml: mlpack & d.cmo* -> d.cmo & cmi"
+ ~prods:["%.d.cmo"]
+ ~deps:["%.mlpack"; "%.cmi"]
+ (Ocaml_compiler.byte_debug_pack_mlpack "%.mlpack" "%.d.cmo");;
+
+rule "ocaml: mlpack & cmo* & cmi -> cmo"
+ ~prod:"%.cmo"
+ ~deps:["%.mli"; "%.cmi"; "%.mlpack"]
+ ~doc:"If foo.mlpack contains a list of capitalized module names, \
+ the target foo.cmo will produce a packed module containing \
+ those modules as submodules. You can also have a foo.mli file \
+ to restrict the interface of the resulting module.
+
+\
+ Warning: to produce a native foo.cmx out of a foo.mlpack, you must \
+ manually tag the included compilation units with for-pack(foo). \
+ See the documentation of the corresponding rules for more details.
+
+\
+ The modules named in the .mlpack \
+ will be dynamic dependencies of the compilation action. \
+ You cannot give the .mlpack the same name as one of the module \
+ it contains, as this would create a circular dependency."
+ (Ocaml_compiler.byte_pack_mlpack "%.mlpack" "%.cmo");;
+
+rule "ocaml: mlpack & cmo* -> cmo & cmi"
+ ~prods:["%.cmo"; "%.cmi"]
+ ~dep:"%.mlpack"
+ (Ocaml_compiler.byte_pack_mlpack "%.mlpack" "%.cmo");;
+
+rule "ocaml: ml & cmi -> d.cmo"
+ ~prod:"%.d.cmo"
+ ~deps:["%.mli"(* This one is inserted to force this rule to be skiped when
+ a .ml is provided without a .mli *); "%.ml"; "%.ml.depends"; "%.cmi"]
+ ~doc:"The foo.d.cmo target compiles foo.ml with the 'debug' tag enabled (-g).\
+ See also foo.d.byte.
+
+\
+ For technical reason, .d.cmx and .d.native are not yet supported, \
+ so you should explicitly add the 'debug' tag \
+ to native targets (both compilation and linking)."
+ (Ocaml_compiler.byte_compile_ocaml_implem ~tag:"debug" "%.ml" "%.d.cmo");;
+
+rule "ocaml: ml & cmi -> cmo"
+ ~prod:"%.cmo"
+ ~deps:["%.mli"(* This one is inserted to force this rule to be skiped when
+ a .ml is provided without a .mli *); "%.ml"; "%.ml.depends"; "%.cmi"]
+ (Ocaml_compiler.byte_compile_ocaml_implem "%.ml" "%.cmo");;
+
+rule "ocaml: mlpack & cmi & p.cmx* & p.o* -> p.cmx & p.o"
+ ~prods:["%.p.cmx"; x_p_o
+ (* no cmi here you must make the byte version to have it *)]
+ ~deps:["%.mlpack"; "%.cmi"]
+ (Ocaml_compiler.native_profile_pack_mlpack "%.mlpack" "%.p.cmx");;
+
+rule "ocaml: mlpack & cmi & cmx* & o* -> cmx & o"
+ ~prods:["%.cmx"; x_o
+ (* no cmi here you must make the byte version to have it *)]
+ ~deps:["%.mlpack"; "%.cmi"]
+ ~doc:"If foo.mlpack contains a list of capitalized module names, \
+ the target foo.cmx will produce a packed module containing \
+ those modules as submodules.
+
+\
+ Warning: The .cmx files that will be included must be manually tagged \
+ with the tag \"for-pack(foo)\". This means that you cannot include \
+ the same bar.cmx in several .mlpack files, and that you should not \
+ use an included .cmx as a separate module on its own.
+
+\
+ This requirement comes from a technical limitation of \
+ native module packing: ocamlopt needs the -for-pack argument to be passed \
+ ahead of time, when compiling each included submodule, \
+ because there is no reliable, portable way to rewrite \
+ native object files afterwards."
+ (Ocaml_compiler.native_pack_mlpack "%.mlpack" "%.cmx");;
+
+rule "ocaml: ml & cmi -> p.cmx & p.o"
+ ~prods:["%.p.cmx"; x_p_o]
+ ~deps:["%.ml"; "%.ml.depends"; "%.cmi"]
+ ~doc:"The foo.p.cmx target compiles foo.ml with the 'profile' \
+ tag enabled (-p). Note that ocamlbuild provides no support \
+ for the bytecode profiler, which works completely differently."
+ (Ocaml_compiler.native_compile_ocaml_implem ~tag:"profile" ~cmx_ext:"p.cmx" "%.ml");;
+
+rule "ocaml: ml & cmi -> cmx & o"
+ ~prods:["%.cmx"; x_o]
+ ~deps:["%.ml"; "%.ml.depends"; "%.cmi"]
+ (Ocaml_compiler.native_compile_ocaml_implem "%.ml");;
+
+rule "ocaml: ml -> d.cmo & cmi"
+ ~prods:["%.d.cmo"]
+ ~deps:["%.ml"; "%.ml.depends"; "%.cmi"]
+ (Ocaml_compiler.byte_compile_ocaml_implem ~tag:"debug" "%.ml" "%.d.cmo");;
+
+rule "ocaml: ml -> cmo & cmi"
+ ~prods:["%.cmo"; "%.cmi"]
+ ~deps:["%.ml"; "%.ml.depends"]
+ ~doc:"This rule allows to produce a .cmi from a .ml file \
+ when the corresponding .mli is missing.
+
+\
+ Note: you are strongly encourage to have a .mli file \
+ for each of your .ml module, as it is a good development \
+ practice which also simplifies the way build systems work, \
+ as it avoids producing .cmi files as a silent side-effect of \
+ another compilation action."
+ (Ocaml_compiler.byte_compile_ocaml_implem "%.ml" "%.cmo");;
+
+rule "ocaml: d.cmo* -> d.byte"
+ ~prod:"%.d.byte"
+ ~dep:"%.d.cmo"
+ ~doc:"The target foo.d.byte will build a bytecode executable \
+ with debug information enabled."
+ (Ocaml_compiler.byte_debug_link "%.d.cmo" "%.d.byte");;
+
+rule "ocaml: cmo* -> byte"
+ ~prod:"%.byte"
+ ~dep:"%.cmo"
+ (Ocaml_compiler.byte_link "%.cmo" "%.byte");;
+
+rule "ocaml: cmo* -> byte.(o|obj)"
+ ~prod:x_byte_o
+ ~dep:"%.cmo"
+ ~doc:"The foo.byte.o target, or foo.byte.obj under Windows, \
+ will produce an object file by passing the -output-obj option \
+ to the OCaml compiler. See also foo.byte.c, and foo.native.{o,obj}."
+ (Ocaml_compiler.byte_output_obj "%.cmo" x_byte_o);;
+
+rule "ocaml: cmo* -> byte.c"
+ ~prod:x_byte_c
+ ~dep:"%.cmo"
+ (Ocaml_compiler.byte_output_obj "%.cmo" x_byte_c);;
+
+rule "ocaml: cmo* -> byte.(so|dll|dylib)"
+ ~prod:x_byte_so
+ ~dep:"%.cmo"
+ ~doc:"The foo.byte.so target, or foo.byte.dll under Windows, \
+ or foo.byte.dylib under Mac OS X will produce a shared library file
+ by passing the -output-obj and -cclib -shared options \
+ to the OCaml compiler. See also foo.native.{so,dll,dylib}."
+ (Ocaml_compiler.byte_output_shared "%.cmo" x_byte_so);;
+
+rule "ocaml: p.cmx* & p.o* -> p.native"
+ ~prod:"%.p.native"
+ ~deps:["%.p.cmx"; x_p_o]
+ ~doc:"The foo.p.native target builds the native executable \
+ with the 'profile' tag (-p) enabled throughout compilation and linking."
+ (Ocaml_compiler.native_profile_link "%.p.cmx" "%.p.native");;
+
+rule "ocaml: cmx* & o* -> native"
+ ~prod:"%.native"
+ ~deps:["%.cmx"; x_o]
+ ~doc:"Builds a native executable"
+ (Ocaml_compiler.native_link "%.cmx" "%.native");;
+
+rule "ocaml: cmx* & o* -> native.(o|obj)"
+ ~prod:x_native_o
+ ~deps:["%.cmx"; x_o]
+ (Ocaml_compiler.native_output_obj "%.cmx" x_native_o);;
+
+rule "ocaml: cmx* & o* -> native.(so|dll|dylib)"
+ ~prod:x_native_so
+ ~deps:["%.cmx"; x_o]
+ (Ocaml_compiler.native_output_shared "%.cmx" x_native_so);;
+
+rule "ocaml: mllib & d.cmo* -> d.cma"
+ ~prod:"%.d.cma"
+ ~dep:"%.mllib"
+ (Ocaml_compiler.byte_debug_library_link_mllib "%.mllib" "%.d.cma");;
+
+rule "ocaml: mllib & cmo* -> cma"
+ ~prod:"%.cma"
+ ~dep:"%.mllib"
+ ~doc:"Build a .cma archive file (bytecode library) containing \
+ the list of modules given in the .mllib file of the same name. \
+ Note that the .cma archive will contain exactly the modules listed, \
+ so it may not be self-contained if some dependencies are missing."
+ (Ocaml_compiler.byte_library_link_mllib "%.mllib" "%.cma");;
+
+rule "ocaml: d.cmo* -> d.cma"
+ ~prod:"%.d.cma"
+ ~dep:"%.d.cmo"
+ (Ocaml_compiler.byte_debug_library_link "%.d.cmo" "%.d.cma");;
+
+rule "ocaml: cmo* -> cma"
+ ~prod:"%.cma"
+ ~dep:"%.cmo"
+ ~doc:"The preferred way to build a .cma archive is to create a .mllib file \
+ with a list of modules to include. It is however possible to build one \
+ from a .cmo of the same name; the archive will include this module and \
+ the local modules it depends upon, transitively."
+ (Ocaml_compiler.byte_library_link "%.cmo" "%.cma");;
+
+rule "ocaml C stubs: clib & (o|obj)* -> (a|lib) & (so|dll)"
+ ~prods:(["%(path:<**/>)lib%(libname:<*> and not <*.*>)"-.-ext_lib] @
+ if Ocamlbuild_config.supports_shared_libraries then
+ ["%(path:<**/>)dll%(libname:<*> and not <*.*>)"-.-ext_dll]
+ else
+ [])
+ ~dep:"%(path)lib%(libname).clib"
+ ?doc:None (* TODO document *)
+ (C_tools.link_C_library "%(path)lib%(libname).clib" ("%(path)lib%(libname)"-.-ext_lib) "%(path)%(libname)");;
+
+rule "ocaml: mllib & p.cmx* & p.o* -> p.cmxa & p.a"
+ ~prods:["%.p.cmxa"; x_p_a]
+ ~dep:"%.mllib"
+ (Ocaml_compiler.native_profile_library_link_mllib "%.mllib" "%.p.cmxa");;
+
+rule "ocaml: mllib & cmx* & o* -> cmxa & a"
+ ~prods:["%.cmxa"; x_a]
+ ~dep:"%.mllib"
+ ~doc:"Creates a native archive file .cmxa, using the .mllib file \
+ as the .cma rule above. Note that whereas bytecode .cma can \
+ be used both for static and dynamic linking, .cmxa only support \
+ static linking. For an archive usable with Dynlink, \
+ see the rule producing a .cmxs from a .mldylib."
+ (Ocaml_compiler.native_library_link_mllib "%.mllib" "%.cmxa");;
+
+rule "ocaml: p.cmx & p.o -> p.cmxa & p.a"
+ ~prods:["%.p.cmxa"; x_p_a]
+ ~deps:["%.p.cmx"; x_p_o]
+ (Ocaml_compiler.native_profile_library_link "%.p.cmx" "%.p.cmxa");;
+
+rule "ocaml: cmx & o -> cmxa & a"
+ ~prods:["%.cmxa"; x_a]
+ ~deps:["%.cmx"; x_o]
+ ~doc:"Just as you can build a .cma from a .cmo in absence of .mllib file, \
+ you can build a .cmxa (native archive file for static linking only) \
+ from a .cmx, which will include the local modules it depends upon, \
+ transitivitely."
+ (Ocaml_compiler.native_library_link "%.cmx" "%.cmxa");;
+
+rule "ocaml: mldylib & p.cmx* & p.o* -> p.cmxs & p.so"
+ ~prods:["%.p.cmxs"; x_p_dll]
+ ~dep:"%.mldylib"
+ (Ocaml_compiler.native_profile_shared_library_link_mldylib "%.mldylib" "%.p.cmxs");;
+
+rule "ocaml: mldylib & cmx* & o* -> cmxs & so"
+ ~prods:["%.cmxs"; x_dll]
+ ~dep:"%.mldylib"
+ ~doc:"Builds a .cmxs (native archive for dynamic linking) containing exactly \
+ the modules listed in the corresponding .mldylib file."
+ (Ocaml_compiler.native_shared_library_link_mldylib "%.mldylib" "%.cmxs");;
+
+rule "ocaml: p.cmx & p.o -> p.cmxs & p.so"
+ ~prods:["%.p.cmxs"; x_p_dll]
+ ~deps:["%.p.cmx"; x_p_o]
+ (Ocaml_compiler.native_shared_library_link ~tags:["profile"] "%.p.cmx" "%.p.cmxs");;
+
+rule "ocaml: p.cmxa & p.a -> p.cmxs & p.so"
+ ~prods:["%.p.cmxs"; x_p_dll]
+ ~deps:["%.p.cmxa"; x_p_a]
+ (Ocaml_compiler.native_shared_library_link ~tags:["profile";"linkall"] "%.p.cmxa" "%.p.cmxs");;
+
+rule "ocaml: cmx & o -> cmxs"
+ ~prods:["%.cmxs"]
+ ~deps:["%.cmx"; x_o]
+ ~doc:"If you have not created a foo.mldylib file for a compilation unit \
+ foo.cmx, the target foo.cmxs will produce a .cmxs file containing \
+ exactly the .cmx.
+
+\
+ Note: this differs from the behavior of .cmxa targets \
+ with no .mllib, as the dependencies of the modules will not be \
+ included: generally, the modules compiled as dynamic plugins depend \
+ on library modules that will be already linked in the executable, \
+ and that the .cmxs should therefore not duplicate."
+ (Ocaml_compiler.native_shared_library_link "%.cmx" "%.cmxs");;
+
+rule "ocaml: cmx & o -> cmxs & so"
+ ~prods:["%.cmxs"; x_dll]
+ ~deps:["%.cmx"; x_o]
+ (Ocaml_compiler.native_shared_library_link "%.cmx" "%.cmxs");;
+
+rule "ocaml: cmxa & a -> cmxs & so"
+ ~prods:["%.cmxs"; x_dll]
+ ~deps:["%.cmxa"; x_a]
+ ~doc:"This rule allows to build a .cmxs from a .cmxa, to avoid having \
+ to duplicate a .mllib file into a .mldylib."
+ (Ocaml_compiler.native_shared_library_link ~tags:["linkall"] "%.cmxa" "%.cmxs");;
+
+rule "ocaml dependencies ml"
+ ~prod:"%.ml.depends"
+ ~dep:"%.ml"
+ ~doc:"OCamlbuild will use ocamldep to approximate dependencies \
+ of a source file. The ocamldep tool being purely syntactic, \
+ it only computes an over-approximation of the dependencies.
+
+\
+ If you manipulate a module Foo that is in fact a submodule Bar.Foo \
+ (after 'open Bar'), ocamldep may believe that your module depends \
+ on foo.ml -- when such a file also exists in your project. This can \
+ lead to spurious circular dependencies. In that case, you can use \
+ OCamlbuild_plugin.non_dependency in your myocamlbuild.ml \
+ to manually remove the spurious dependency. See the plugins API."
+ (Ocaml_tools.ocamldep_command "%.ml" "%.ml.depends");;
+
+rule "ocaml dependencies mli"
+ ~prod:"%.mli.depends"
+ ~dep:"%.mli"
+ (Ocaml_tools.ocamldep_command "%.mli" "%.mli.depends");;
+
+rule "ocamllex"
+ ~prod:"%.ml"
+ ~dep:"%.mll"
+ (Ocaml_tools.ocamllex "%.mll");;
+
+rule "ocaml: mli -> odoc"
+ ~prod:"%.odoc"
+ ~deps:["%.mli"; "%.mli.depends"]
+ ~doc:".odoc are intermediate files storing the result of ocamldoc processing \
+ on a source file. See the various .docdir/... targets for ocamldoc."
+ (Ocaml_tools.document_ocaml_interf "%.mli" "%.odoc");;
+
+rule "ocaml: ml -> odoc"
+ ~prod:"%.odoc"
+ ~deps:["%.ml"; "%.ml.depends"]
+ (Ocaml_tools.document_ocaml_implem "%.ml" "%.odoc");;
+
+rule "ocamldoc: document ocaml project odocl & *odoc -> docdir (html)"
+ ~prod:"%.docdir/index.html"
+ ~stamp:"%.docdir/html.stamp"
+ ~dep:"%.odocl"
+ ~doc:"If you put a list of capitalized module names in a foo.odocl file, \
+ the target foo.docdir/index.html will call ocamldoc to produce \
+ the html documentation for these modules. \
+ See also the max|latex|doc target below."
+ (Ocaml_tools.document_ocaml_project
+ ~ocamldoc:Ocaml_tools.ocamldoc_l_dir "%.odocl" "%.docdir/index.html" "%.docdir");;
+
+rule "ocamldoc: document ocaml project odocl & *odoc -> docdir (man)"
+ ~prod:"%.docdir/man"
+ ~stamp:"%.docdir/man.stamp"
+ ~dep:"%.odocl"
+ ?doc:None (* TODO document *)
+ (Ocaml_tools.document_ocaml_project
+ ~ocamldoc:Ocaml_tools.ocamldoc_l_dir "%.odocl" "%.docdir/man" "%.docdir");;
+
+rule "ocamldoc: document ocaml project odocl & *odoc -> man|latex|dot..."
+ ~prod:"%(dir).docdir/%(file)"
+ ~dep:"%(dir).odocl"
+ ?doc:None (* TODO document *)
+ (Ocaml_tools.document_ocaml_project
+ ~ocamldoc:Ocaml_tools.ocamldoc_l_file "%(dir).odocl" "%(dir).docdir/%(file)" "%(dir).docdir");;
+
+(* To use menhir give the -use-menhir option at command line,
+ Or put true: use_menhir in your tag file. *)
+if !Options.use_menhir || Configuration.has_tag "use_menhir" then begin
+ (* Automatic handling of menhir modules, given a
+ description file %.mlypack *)
+ rule "ocaml: modular menhir (mlypack)"
+ ~prods:["%.mli" ; "%.ml"]
+ ~deps:["%.mlypack"]
+ ~doc:"Menhir supports building a parser by composing several .mly files \
+ together, containing different parts of the grammar description. \
+ To use that feature with ocamlbuild, you should create a .mlypack \
+ file with the same syntax as .mllib or .mlpack files: \
+ a whitespace-separated list of the capitalized module names \
+ of the .mly files you want to combine together."
+ (Ocaml_tools.menhir_modular "%" "%.mlypack" "%.mlypack.depends");
+
+ rule "ocaml: menhir modular dependencies"
+ ~prod:"%.mlypack.depends"
+ ~dep:"%.mlypack"
+ (Ocaml_tools.menhir_modular_ocamldep_command "%.mlypack" "%.mlypack.depends");
+
+ rule "ocaml: menhir"
+ ~prods:["%.ml"; "%.mli"]
+ ~deps:["%.mly"; "%.mly.depends"]
+ ~doc:"Invokes menhir to build the .ml and .mli files derived from a .mly \
+ grammar. If you want to use ocamlyacc instead, you must disable the \
+ -use-menhir option that was passed to ocamlbuild."
+ (Ocaml_tools.menhir "%.mly");
+
+ rule "ocaml: menhir dependencies"
+ ~prod:"%.mly.depends"
+ ~dep:"%.mly"
+ (Ocaml_tools.menhir_ocamldep_command "%.mly" "%.mly.depends");
+
+end else
+ rule "ocamlyacc"
+ ~prods:["%.ml"; "%.mli"]
+ ~dep:"%.mly"
+ ~doc:"By default, ocamlbuild will use ocamlyacc to produce a .ml and .mly \
+ from a .mly file of the same name. You can also enable the \
+ -use-menhir option to use menhir instead. Menhir is a recommended \
+ replacement for ocamlyacc, that supports more feature, lets you \
+ write more readable grammars, and helps you understand conflicts."
+ (Ocaml_tools.ocamlyacc "%.mly");;
+
+rule "ocaml C stubs: c -> o"
+ ~prod:x_o
+ ~dep:"%.c"
+ ?doc:None (* TODO document *)
+ begin fun env _build ->
+ let c = env "%.c" in
+ let o = env x_o in
+ let comp = if Tags.mem "native" (tags_of_pathname c) then !Options.ocamlopt else !Options.ocamlc in
+ Cmd(S[comp; T(tags_of_pathname c++"c"++"compile"); A"-c"; A"-o"; P o; Px c])
+ end;;
+
+rule "ocaml: ml & ml.depends & *cmi -> .inferred.mli"
+ ~prod:"%.inferred.mli"
+ ~deps:["%.ml"; "%.ml.depends"]
+ ~doc:"The target foo.inferred.mli will produce a .mli that exposes all the \
+ declarations in foo.ml, as obtained by direct invocation of `ocamlc -i`."
+ (Ocaml_tools.infer_interface "%.ml" "%.inferred.mli");;
+
+rule "ocaml: mltop -> top"
+ ~prod:"%.top"
+ ~dep:"%.mltop"
+ ?doc:None (* TODO document *)
+ (Ocaml_compiler.byte_toplevel_link_mltop "%.mltop" "%.top");;
+
+rule "preprocess: ml -> pp.ml"
+ ~dep:"%.ml"
+ ~prod:"%.pp.ml"
+ ~doc:"The target foo.pp.ml should generate a source file equivalent \
+ to foo.ml after syntactic preprocessors (camlp4, etc.) have been \
+ applied.
+
+\
+ Warning: This option is currently known to malfunction \
+ when used together with -use-ocamlfind (for syntax extensions \
+ coming from ocamlfind packages). Direct compilation of the \
+ corresponding file to produce a .cmx or .cmo will still work well."
+ (Ocaml_tools.camlp4 "pp.ml" "%.ml" "%.pp.ml");;
+
+flag ["ocaml"; "pp"] begin
+ S (List.fold_right (fun x acc -> Sh x :: acc) !Options.ocaml_ppflags [])
+end;;
+
+flag ["ocaml"; "compile"] begin
+ atomize !Options.ocaml_cflags
+end;;
+
+flag ["c"; "compile"] begin
+ atomize !Options.ocaml_cflags
+end;;
+
+flag ["ocaml"; "link"] begin
+ atomize !Options.ocaml_lflags
+end;;
+
+flag ["c"; "link"] begin
+ atomize !Options.ocaml_lflags
+end;;
+
+flag ["ocaml"; "ocamlyacc"] (atomize !Options.ocaml_yaccflags);;
+flag ["ocaml"; "menhir"] (atomize !Options.ocaml_yaccflags);;
+flag ["ocaml"; "doc"] (atomize !Options.ocaml_docflags);;
+flag ["ocaml"; "ocamllex"] (atomize !Options.ocaml_lexflags);;
+
+(* Tell menhir to explain conflicts *)
+flag [ "ocaml" ; "menhir" ; "explain" ] (S[A "--explain"]);;
+flag [ "ocaml" ; "menhir" ; "infer" ] (S[A "--infer"]);;
+
+(* Define two ocamlbuild flags [only_tokens] and [external_tokens(Foo)]
+ which correspond to menhir's [--only-tokens] and [--external-tokens Foo].
+ When they are used, these flags should be passed both to [menhir] and to
+ [menhir --raw-depend]. *)
+let () =
+ List.iter begin fun mode ->
+ flag [ mode; "only_tokens" ] (S[A "--only-tokens"]);
+ pflag [ mode ] "external_tokens" (fun name ->
+ S[A "--external-tokens"; A name]);
+ end [ "menhir"; "menhir_ocamldep" ];;
+
+(* Tell ocamllex to generate ml code *)
+flag [ "ocaml" ; "ocamllex" ; "generate_ml" ] (S[A "-ml"]);;
+
+flag ["ocaml"; "byte"; "link"] begin
+ S (List.map (fun x -> A (x^".cma")) !Options.ocaml_libs)
+end;;
+
+flag ["ocaml"; "native"; "link"] begin
+ S (List.map (fun x -> A (x^".cmxa")) !Options.ocaml_libs)
+end;;
+
+flag ["ocaml"; "byte"; "link"] begin
+ S (List.map (fun x -> A (x^".cmo")) !Options.ocaml_mods)
+end;;
+
+flag ["ocaml"; "native"; "link"] begin
+ S (List.map (fun x -> A (x^".cmx")) !Options.ocaml_mods)
+end;;
+
+(* findlib *)
+let () =
+ if !Options.use_ocamlfind then begin
+ (* Ocamlfind will link the archives for us. *)
+ flag ["ocaml"; "link"; "program"] & A"-linkpkg";
+ flag ["ocaml"; "link"; "toplevel"] & A"-linkpkg";
+ flag ["ocaml"; "link"; "output_obj"] & A"-linkpkg";
+
+ (* "program" will make sure that -linkpkg is passed when compiling
+ whole-programs (.byte and .native); but it is occasionally
+ useful to pass -linkpkg when building archives for example
+ (.cma and .cmxa); the "linkpkg" flag allows user to request it
+ explicitly. *)
+ flag ["ocaml"; "link"; "linkpkg"] & A"-linkpkg";
+ pflag ["ocaml"; "link"] "dontlink" (fun pkg -> S[A"-dontlink"; A pkg]);
+
+ let all_tags = [
+ ["ocaml"; "byte"; "compile"];
+ ["ocaml"; "native"; "compile"];
+ ["ocaml"; "byte"; "link"];
+ ["ocaml"; "native"; "link"];
+ ["ocaml"; "ocamldep"];
+ ["ocaml"; "doc"];
+ ["ocaml"; "mktop"];
+ ["ocaml"; "infer_interface"];
+ (* PR#6794: ocamlbuild should pass -package flags when building C files *)
+ ["c"; "compile"];
+ ] in
+
+ (* tags package(X), predicate(X) and syntax(X) *)
+ List.iter begin fun tags ->
+ pflag tags "package" (fun pkg -> S [A "-package"; A pkg]);
+ if not (List.mem "ocamldep" tags) then
+ (* PR#6184: 'ocamlfind ocamldep' does not support -predicate *)
+ pflag tags "predicate" (fun pkg -> S [A "-predicates"; A pkg]);
+ if List.mem "ocaml" tags then
+ pflag tags "syntax" (fun pkg -> S [A "-syntax"; A pkg])
+ end all_tags
+ end else begin
+ try
+ (* Note: if there is no -pkg option, ocamlfind won't be called *)
+ let pkgs = List.map Findlib.query !Options.ocaml_pkgs in
+ flag ["ocaml"; "byte"; "compile"] (Findlib.compile_flags_byte pkgs);
+ flag ["ocaml"; "native"; "compile"] (Findlib.compile_flags_native pkgs);
+ flag ["ocaml"; "byte"; "link"] (Findlib.link_flags_byte pkgs);
+ flag ["ocaml"; "native"; "link"] (Findlib.link_flags_native pkgs);
+ (* PR#6794: ocamlbuild should pass -package flags when building C files *)
+ flag ["c"; "compile"] (Findlib.include_flags pkgs)
+ with Findlib.Findlib_error e ->
+ Findlib.report_error e
+ end
+
+(* parameterized tags *)
+let () =
+ pflag ["ocaml"; "native"; "compile"] "for-pack"
+ (fun param -> S [A "-for-pack"; A param]);
+ pflag ["ocaml"; "native"; "pack"] "for-pack"
+ (fun param -> S [A "-for-pack"; A param]);
+ pflag ["ocaml"; "native"; "compile"] "inline"
+ (fun param -> S [A "-inline"; A param]);
+ pflag ["ocaml"; "compile"] "color" (fun setting -> S[A "-color"; A setting]);
+ List.iter (fun pp ->
+ pflag ["ocaml"; "compile"] pp
+ (fun param -> S [A ("-" ^ pp); A param]);
+ pflag ["ocaml"; "ocamldep"] pp
+ (fun param -> S [A ("-" ^ pp); A param]);
+ pflag ["ocaml"; "doc"] pp
+ (fun param -> S [A ("-" ^ pp); A param]);
+ pflag ["ocaml"; "infer_interface"] pp
+ (fun param -> S [A ("-" ^ pp); A param])
+ ) ["pp"; "ppx"];
+ pflag ["ocaml";"compile";] "warn"
+ (fun param -> S [A "-w"; A param]);
+ pflag ["ocaml";"compile";] "warn_error"
+ (fun param -> S [A "-warn-error"; A param]);
+ pflag ["ocaml"; "ocamldep"] "open"
+ (fun param -> S [A "-open"; A param]);
+ pflag ["ocaml"; "compile"] "open"
+ (fun param -> S [A "-open"; A param]);
+ pflag ["ocaml"; "link"] "runtime_variant"
+ (fun param -> S [A "-runtime-variant"; A param]);
+ ()
+
+let camlp4_flags camlp4s =
+ List.iter begin fun camlp4 ->
+ flag ["ocaml"; "pp"; camlp4] (A camlp4)
+ end camlp4s;;
+
+let p4_series = ["camlp4o"; "camlp4r"; "camlp4of"; "camlp4rf"; "camlp4orf"; "camlp4oof"];;
+let p4_opt_series = List.map (fun f -> f ^ ".opt") p4_series;;
+
+camlp4_flags p4_series;;
+camlp4_flags p4_opt_series;;
+
+let camlp4_flags' camlp4s =
+ List.iter begin fun (camlp4, flags) ->
+ flag ["ocaml"; "pp"; camlp4] flags
+ end camlp4s;;
+
+camlp4_flags' ["camlp4orr", S[A"camlp4of"; A"-parser"; A"reloaded"];
+ "camlp4rrr", S[A"camlp4rf"; A"-parser"; A"reloaded"]];;
+
+flag ["ocaml"; "pp"; "camlp4:no_quot"] (A"-no_quot");;
+
+ocaml_lib ~extern:true "dynlink";;
+ocaml_lib ~extern:true "unix";;
+ocaml_lib ~extern:true "str";;
+ocaml_lib ~extern:true "bigarray";;
+ocaml_lib ~extern:true "nums";;
+ocaml_lib ~extern:true "dbm";;
+ocaml_lib ~extern:true "graphics";;
+ocaml_lib ~extern:true ~tag_name:"use_toplevel" "toplevellib";;
+ocaml_lib ~extern:true ~dir:"+ocamldoc" "ocamldoc";;
+ocaml_lib ~extern:true ~dir:"+ocamlbuild" ~tag_name:"use_ocamlbuild" "ocamlbuildlib";;
+
+ocaml_lib ~extern:true ~dir:"+camlp4" ~tag_name:"use_camlp4" "camlp4lib";;
+ocaml_lib ~extern:true ~dir:"+camlp4" ~tag_name:"use_old_camlp4" "camlp4";;
+ocaml_lib ~extern:true ~dir:"+camlp4" ~tag_name:"use_camlp4_full" "camlp4fulllib";;
+flag ["ocaml"; "compile"; "use_camlp4_full"]
+ (S[A"-I"; A"+camlp4/Camlp4Parsers";
+ A"-I"; A"+camlp4/Camlp4Printers";
+ A"-I"; A"+camlp4/Camlp4Filters"]);;
+flag ["ocaml"; "use_camlp4_bin"; "link"; "byte"] (A"+camlp4/Camlp4Bin.cmo");;
+flag ["ocaml"; "use_camlp4_bin"; "link"; "native"] (A"+camlp4/Camlp4Bin.cmx");;
+
+flag ["ocaml"; "debug"; "compile"; "byte"] (A "-g");;
+flag ["ocaml"; "debug"; "link"; "byte"; "program"] (A "-g");;
+flag ["ocaml"; "debug"; "pack"; "byte"] (A "-g");;
+flag ["ocaml"; "debug"; "compile"; "native"] (A "-g");;
+flag ["ocaml"; "debug"; "link"; "native"; "program"] (A "-g");;
+flag ["ocaml"; "debug"; "pack"; "native"] (A "-g");;
+flag ["c"; "debug"; "compile"] (A "-g");
+flag ["c"; "debug"; "link"] (A "-g");
+flag ["ocaml"; "link"; "native"; "output_obj"] (A"-output-obj");;
+flag ["ocaml"; "link"; "byte"; "output_obj"] (A"-output-obj");;
+flag ["ocaml"; "link"; "output_shared"] & (S[A"-cclib"; A"-shared"]);;
+flag ["ocaml"; "dtypes"; "compile"] (A "-dtypes");;
+flag ["ocaml"; "annot"; "compile"] (A "-annot");;
+flag ["ocaml"; "annot"; "pack"] (A "-annot");;
+flag ["ocaml"; "bin_annot"; "compile"] (A "-bin-annot");;
+flag ["ocaml"; "bin_annot"; "pack"] (A "-bin-annot");;
+flag ["ocaml"; "safe_string"; "compile"] (A "-safe-string");;
+flag ["ocaml"; "safe_string"; "infer_interface"] (A "-safe-string");;
+flag ["ocaml"; "unsafe_string"; "compile"] (A "-unsafe-string");;
+flag ["ocaml"; "unsafe_string"; "infer_interface"] (A "-unsafe-string");;
+flag ["ocaml"; "short_paths"; "compile"] (A "-short-paths");;
+flag ["ocaml"; "short_paths"; "infer_interface"] (A "-short-paths");;
+flag ["ocaml"; "rectypes"; "compile"] (A "-rectypes");;
+flag ["ocaml"; "rectypes"; "infer_interface"] (A "-rectypes");;
+flag ["ocaml"; "rectypes"; "doc"] (A "-rectypes");;
+flag ["ocaml"; "rectypes"; "pack"] (A "-rectypes");;
+flag ["ocaml"; "principal"; "compile"] (A "-principal");;
+flag ["ocaml"; "principal"; "infer_interface"] (A "-principal");;
+flag ["ocaml"; "linkall"; "link"] (A "-linkall");;
+flag ["ocaml"; "link"; "profile"; "native"] (A "-p");;
+flag ["ocaml"; "link"; "program"; "custom"; "byte"] (A "-custom");;
+flag ["ocaml"; "link"; "library"; "custom"; "byte"] (A "-custom");;
+flag ["ocaml"; "compile"; "profile"; "native"] (A "-p");;
+flag ["ocaml"; "compile"; "no_alias_deps";] (A "-no-alias-deps");;
+flag ["ocaml"; "compile"; "strict_formats";] (A "-strict-formats");;
+flag ["ocaml"; "native"; "compile"; "opaque";] (A "-opaque");;
+flag ["ocaml"; "native"; "compile"; "no_float_const_prop";] (A "-no-float-const-prop");
+flag ["ocaml"; "compile"; "keep_docs";] (A "-keep-docs");
+flag ["ocaml"; "compile"; "keep_locs";] (A "-keep-locs");
+flag ["ocaml"; "absname"; "compile"] (A "-absname");;
+flag ["ocaml"; "absname"; "infer_interface"] (A "-absname");;
+flag ["ocaml"; "byte"; "compile"; "compat_32";] (A "-compat-32");;
+flag ["ocaml";"compile";"native";"asm"] & S [A "-S"];;
+
+
+(* threads, with or without findlib *)
+flag ["ocaml"; "compile"; "thread"] (A "-thread");;
+flag ["ocaml"; "link"; "thread"] (A "-thread");;
+if !Options.use_ocamlfind then
+ (* PR#6794: Needed as we pass -package when compiling C files *)
+ flag ["c"; "compile"; "thread"] (A "-thread")
+else begin
+ flag ["ocaml"; "doc"; "thread"] (S[A"-I"; A"+threads"]);
+ flag ["ocaml"; "link"; "thread"; "native"; "program"] (A "threads.cmxa");
+ flag ["ocaml"; "link"; "thread"; "byte"; "program"] (A "threads.cma");
+ flag ["ocaml"; "link"; "thread"; "native"; "toplevel"] (A "threads.cmxa");
+ flag ["ocaml"; "link"; "thread"; "byte"; "toplevel"] (A "threads.cma");
+end;;
+
+flag ["ocaml"; "compile"; "nopervasives"] (A"-nopervasives");;
+flag ["ocaml"; "compile"; "nolabels"] (A"-nolabels");;
+
+(*flag ["ocaml"; "ocamlyacc"; "quiet"] (A"-q");;*)
+flag ["ocaml"; "ocamllex"; "quiet"] (A"-q");;
+
+let ocaml_warn_flag c =
+ flag ~deprecated:true
+ ["ocaml"; "compile"; sprintf "warn_%c" (Char.uppercase_ascii c)]
+ (S[A"-w"; A (sprintf "%c" (Char.uppercase_ascii c))]);
+ flag ~deprecated:true
+ ["ocaml"; "compile"; sprintf "warn_error_%c" (Char.uppercase_ascii c)]
+ (S[A"-warn-error"; A (sprintf "%c" (Char.uppercase_ascii c))]);
+ flag ~deprecated:true
+ ["ocaml"; "compile"; sprintf "warn_%c" (Char.lowercase_ascii c)]
+ (S[A"-w"; A (sprintf "%c" (Char.lowercase_ascii c))]);
+ flag ~deprecated:true
+ ["ocaml"; "compile"; sprintf "warn_error_%c" (Char.lowercase_ascii c)]
+ (S[A"-warn-error"; A (sprintf "%c" (Char.lowercase_ascii c))]);;
+
+List.iter ocaml_warn_flag ['A'; 'C'; 'D'; 'E'; 'F'; 'K'; 'L'; 'M'; 'P'; 'R'; 'S'; 'U'; 'V'; 'X'; 'Y'; 'Z'];;
+
+flag ~deprecated:true
+ ["ocaml"; "compile"; "strict-sequence"] (A "-strict-sequence");;
+flag ["ocaml"; "compile"; "strict_sequence"] (A "-strict-sequence");;
+
+flag ["ocaml"; "doc"; "docdir"; "extension:html"] (A"-html");;
+flag ["ocaml"; "doc"; "docdir"; "manpage"] (A"-man");;
+flag ["ocaml"; "doc"; "docfile"; "extension:dot"] (A"-dot");;
+flag ["ocaml"; "doc"; "docfile"; "extension:tex"] (A"-latex");;
+flag ["ocaml"; "doc"; "docfile"; "extension:ltx"] (A"-latex");;
+flag ["ocaml"; "doc"; "docfile"; "extension:texi"] (A"-texi");;
+
+ocaml_lib "ocamlbuildlib";;
+ocaml_lib "ocamlbuildlightlib";;
+
+end in ()
diff --git a/ocamlbuild/ocaml_specific.mli b/ocamlbuild/ocaml_specific.mli
new file mode 100644
index 0000000000..bf32663107
--- /dev/null
+++ b/ocamlbuild/ocaml_specific.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+
+(* Original author: Nicolas Pouillard *)
+
+val init : unit -> unit
diff --git a/ocamlbuild/ocaml_tools.ml b/ocamlbuild/ocaml_tools.ml
new file mode 100644
index 0000000000..b2ebcd1c54
--- /dev/null
+++ b/ocamlbuild/ocaml_tools.ml
@@ -0,0 +1,164 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Pathname.Operators
+open Tags.Operators
+open Tools
+open Command
+open Ocaml_utils
+
+let add_suffix s = List.map (fun x -> x -.- s) ;;
+
+let ocamldep_command' tags =
+ let tags' = tags++"ocaml"++"ocamldep" in
+ S [!Options.ocamldep; T tags'; ocaml_ppflags (tags++"pp:dep"); A "-modules"]
+
+let menhir_ocamldep_command' tags ~menhir_spec out =
+ let menhir = if !Options.ocamlyacc = N then V"MENHIR" else !Options.ocamlyacc in
+ Cmd(S[menhir; T tags; A"--raw-depend";
+ A"--ocamldep"; Quote (ocamldep_command' Tags.empty);
+ menhir_spec ; Sh ">"; Px out])
+
+let menhir_ocamldep_command arg out env _build =
+ let arg = env arg and out = env out in
+ let tags = tags_of_pathname arg++"ocaml"++"menhir_ocamldep" in
+ menhir_ocamldep_command' tags ~menhir_spec:(P arg) out
+
+let import_mlypack build mlypack =
+ let tags1 = tags_of_pathname mlypack in
+ let files = string_list_of_file mlypack in
+ let include_dirs = Pathname.include_dirs_of (Pathname.dirname mlypack) in
+ let files_alternatives =
+ List.map begin fun module_name ->
+ expand_module include_dirs module_name ["mly"]
+ end files
+ in
+ let files = List.map Outcome.good (build files_alternatives) in
+ let tags2 =
+ List.fold_right
+ (fun file -> Tags.union (tags_of_pathname file))
+ files tags1
+ in
+ (tags2, files)
+
+let menhir_modular_ocamldep_command mlypack out env build =
+ let mlypack = env mlypack and out = env out in
+ let (tags,files) = import_mlypack build mlypack in
+ let tags = tags++"ocaml"++"menhir_ocamldep" in
+ let menhir_base = Pathname.remove_extensions mlypack in
+ let menhir_spec = S[A "--base" ; P menhir_base ; atomize_paths files] in
+ menhir_ocamldep_command' tags ~menhir_spec out
+
+let menhir_modular menhir_base mlypack mlypack_depends env build =
+ let menhir = if !Options.ocamlyacc = N then V"MENHIR" else !Options.ocamlyacc in
+ let menhir_base = env menhir_base in
+ let mlypack = env mlypack in
+ let mlypack_depends = env mlypack_depends in
+ let (tags,files) = import_mlypack build mlypack in
+ let () = List.iter Outcome.ignore_good (build [[mlypack_depends]]) in
+ Ocaml_compiler.prepare_compile build mlypack;
+ let ocamlc_tags = tags++"ocaml"++"byte"++"compile" in
+ let tags = tags++"ocaml"++"parser"++"menhir" in
+ Cmd(S[menhir ;
+ A "--ocamlc"; Quote(S[!Options.ocamlc; T ocamlc_tags; ocaml_include_flags mlypack]);
+ T tags ; A "--base" ; Px menhir_base ; atomize_paths files])
+
+let ocamldep_command arg out env _build =
+ let arg = env arg and out = env out in
+ let tags = tags_of_pathname arg in
+ Cmd(S[ocamldep_command' tags; P arg; Sh ">"; Px out])
+
+let ocamlyacc mly env _build =
+ let mly = env mly in
+ let ocamlyacc = if !Options.ocamlyacc = N then V"OCAMLYACC" else !Options.ocamlyacc in
+ Cmd(S[ocamlyacc; T(tags_of_pathname mly++"ocaml"++"parser"++"ocamlyacc"); Px mly])
+
+let ocamllex mll env _build =
+ let mll = env mll in
+ Cmd(S[!Options.ocamllex; T(tags_of_pathname mll++"ocaml"++"lexer"++"ocamllex"); Px mll])
+
+let infer_interface ml mli env build =
+ let ml = env ml and mli = env mli in
+ let tags = tags_of_pathname ml++"ocaml" in
+ Ocaml_compiler.prepare_compile build ml;
+ Cmd(S[!Options.ocamlc; ocaml_ppflags tags; ocaml_include_flags ml; A"-i";
+ (if Tags.mem "thread" tags then A"-thread" else N);
+ T(tags++"infer_interface"); P ml; Sh">"; Px mli])
+
+let menhir mly env build =
+ let mly = env mly in
+ let ml = Pathname.update_extension "ml" mly in
+ let menhir = if !Options.ocamlyacc = N then V"MENHIR" else !Options.ocamlyacc in
+ let ocamlc_tags = tags_of_pathname ml ++"ocaml"++"byte"++"compile" in
+ let menhir_tags = tags_of_pathname mly ++"ocaml"++"parser"++"menhir" in
+ Ocaml_compiler.prepare_compile build mly;
+ Cmd(S[menhir;
+ A"--ocamlc"; Quote(S[!Options.ocamlc; T ocamlc_tags; ocaml_include_flags mly]);
+ T menhir_tags; Px mly])
+
+let ocamldoc_c tags arg odoc =
+ let tags = tags++"ocaml" in
+ Cmd (S [!Options.ocamldoc; A"-dump"; Px odoc; T(tags++"doc");
+ ocaml_ppflags (tags++"pp:doc");
+ ocaml_include_flags arg; P arg])
+
+let ocamldoc_l_dir tags deps _docout docdir =
+ Seq[Cmd (S[A"rm"; A"-rf"; Px docdir]);
+ Cmd (S[A"mkdir"; A"-p"; Px docdir]);
+ Cmd (S [!Options.ocamldoc;
+ S(List.map (fun a -> S[A"-load"; P a]) deps);
+ T(tags++"doc"++"docdir"); A"-d"; Px docdir])]
+
+let ocamldoc_l_file tags deps docout _docdir =
+ Seq[Cmd (S[A"rm"; A"-rf"; Px docout]);
+ Cmd (S[A"mkdir"; A"-p"; Px (Pathname.dirname docout)]);
+ Cmd (S [!Options.ocamldoc;
+ S(List.map (fun a -> S[A"-load"; P a]) deps);
+ T(tags++"doc"++"docfile"); A"-o"; Px docout])]
+
+let document_ocaml_interf mli odoc env build =
+ let mli = env mli and odoc = env odoc in
+ Ocaml_compiler.prepare_compile build mli;
+ ocamldoc_c (tags_of_pathname mli++"interf") mli odoc
+
+let document_ocaml_implem ml odoc env build =
+ let ml = env ml and odoc = env odoc in
+ Ocaml_compiler.prepare_compile build ml;
+ ocamldoc_c (tags_of_pathname ml++"implem") ml odoc
+
+let document_ocaml_project ?(ocamldoc=ocamldoc_l_file) odocl docout docdir env build =
+ let odocl = env odocl and docout = env docout and docdir = env docdir in
+ let contents = string_list_of_file odocl in
+ let include_dirs = Pathname.include_dirs_of (Pathname.dirname odocl) in
+ let to_build =
+ List.map begin fun module_name ->
+ expand_module include_dirs module_name ["odoc"]
+ end contents in
+ let module_paths = List.map Outcome.good (build to_build) in
+ let tags = (Tags.union (tags_of_pathname docout) (tags_of_pathname docdir))++"ocaml" in
+ ocamldoc tags module_paths docout docdir
+
+let camlp4 ?(default=A"camlp4o") tag i o env build =
+ let ml = env i and pp_ml = env o in
+ let tags = tags_of_pathname ml++"ocaml"++"pp"++tag in
+ let _ = Rule.build_deps_of_tags build tags in
+ let pp = Command.reduce (Flags.of_tags tags) in
+ let pp =
+ match pp with
+ | N -> default
+ | _ -> pp
+ in
+ Cmd(S[pp; P ml; A"-printer"; A"o"; A"-o"; Px pp_ml])
diff --git a/ocamlbuild/ocaml_tools.mli b/ocamlbuild/ocaml_tools.mli
new file mode 100644
index 0000000000..74434b34df
--- /dev/null
+++ b/ocamlbuild/ocaml_tools.mli
@@ -0,0 +1,35 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+
+val ocamldoc_c : Tags.t -> string -> string -> Command.t
+val ocamldoc_l_dir : Tags.t -> string list -> string -> string -> Command.t
+val ocamldoc_l_file : Tags.t -> string list -> string -> string -> Command.t
+
+val ocamldep_command : string -> string -> Rule.action
+val menhir_ocamldep_command : string -> string -> Rule.action
+val menhir_modular_ocamldep_command : string -> string -> Rule.action
+val menhir_modular : string -> string -> string -> Rule.action
+val ocamlyacc : string -> Rule.action
+val ocamllex : string -> Rule.action
+val menhir : string -> Rule.action
+val infer_interface : string -> string -> Rule.action
+val document_ocaml_interf : string -> string -> Rule.action
+val document_ocaml_implem : string -> string -> Rule.action
+val document_ocaml_project :
+ ?ocamldoc:(Tags.t -> string list -> string -> string -> Command.t) ->
+ string -> string -> string -> Rule.action
+
+val camlp4 : ?default:Command.spec -> Tags.elt -> Pathname.t -> Pathname.t -> Rule.action
diff --git a/ocamlbuild/ocaml_utils.ml b/ocamlbuild/ocaml_utils.ml
new file mode 100644
index 0000000000..3ba233d8e0
--- /dev/null
+++ b/ocamlbuild/ocaml_utils.ml
@@ -0,0 +1,179 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Format
+open Log
+open Pathname.Operators
+open Tags.Operators
+open Tools
+open Flags
+open Command;;
+
+
+module S = Set.Make(String)
+
+let flag_and_dep tags cmd_spec =
+ flag tags cmd_spec;
+ let ps = Command.fold_pathnames (fun p ps -> p :: ps) (Cmd cmd_spec) [] in
+ dep tags ps
+
+let stdlib_dir = lazy begin
+ let ocamlc_where = !Options.build_dir / (Pathname.mk "ocamlc.where") in
+ let () = Command.execute ~quiet:true (Cmd(S[!Options.ocamlc; A"-where"; Sh">"; P ocamlc_where])) in
+ String.chomp (read_file ocamlc_where)
+end
+
+let pflag_and_dep tags ptag cmd_spec =
+ Param_tags.declare ptag
+ (fun param ->
+ flag_and_dep (Param_tags.make ptag param :: tags) (cmd_spec param))
+
+let module_name_of_filename f = String.capitalize_ascii (Pathname.remove_extensions f)
+let module_name_of_pathname x =
+ module_name_of_filename (Pathname.to_string (Pathname.basename x))
+
+let ignore_stdlib x =
+ if !Options.nostdlib then false
+ else
+ let x' = !*stdlib_dir/((String.uncapitalize_ascii x)-.-"cmi") in
+ Pathname.exists x'
+
+let non_dependencies = ref []
+let non_dependency m1 m2 =
+ (* non_dependency was not supposed to accept pathnames without extension. *)
+ if String.length (Pathname.get_extensions m1) = 0 then
+ invalid_arg "non_dependency: no extension";
+ non_dependencies := (m1, m2) :: !non_dependencies
+
+let path_importance path x =
+ if List.mem (path, x) !non_dependencies
+ || (List.mem x !Options.ignore_list) then begin
+ let () = dprintf 3 "This module (%s) is ignored by %s" x path in
+ `ignored
+ end
+ else if ignore_stdlib x then `just_try else `mandatory
+
+let expand_module =
+ memo3 (fun include_dirs module_name exts ->
+ let dirname = Pathname.dirname module_name in
+ let basename = Pathname.basename module_name in
+ let module_name_cap = dirname/(String.capitalize_ascii basename) in
+ let module_name_uncap = dirname/(String.uncapitalize_ascii basename) in
+ List.fold_right begin fun include_dir ->
+ List.fold_right begin fun ext acc ->
+ include_dir/(module_name_uncap-.-ext) ::
+ include_dir/(module_name_cap-.-ext) :: acc
+ end exts
+ end include_dirs [])
+
+let string_list_of_file file =
+ with_input_file file begin fun ic ->
+ Lexers.blank_sep_strings
+ Const.Source.file (Lexing.from_channel ic)
+ end
+let print_path_list = Pathname.print_path_list
+
+let ocaml_ppflags tags =
+ let flags = Flags.of_tags (tags++"ocaml"++"pp") in
+ let reduced = Command.reduce flags in
+ if reduced = N then N else S[A"-pp"; Quote reduced]
+
+let ocaml_add_include_flag x acc =
+ if x = Pathname.current_dir_name then acc else A"-I" :: A x :: acc
+
+let ocaml_include_flags path =
+ S (List.fold_right ocaml_add_include_flag (Pathname.include_dirs_of (Pathname.dirname path)) [])
+
+let info_libraries = Hashtbl.create 103
+
+let libraries = Hashtbl.create 103
+let libraries_of m =
+ try Hashtbl.find libraries m with Not_found -> []
+let use_lib m lib = Hashtbl.replace libraries m (lib :: libraries_of m)
+
+let ocaml_lib ?(extern=false) ?(byte=true) ?(native=true) ?dir ?tag_name libpath =
+ let add_dir x =
+ match dir with
+ | Some dir -> S[A"-I"; P dir; x]
+ | None -> x
+ in
+ let tag_name =
+ match tag_name with
+ | Some x -> x
+ | None -> "use_" ^ Pathname.basename libpath
+ in
+ let flag_and_dep tags lib =
+ flag tags (add_dir (A lib));
+ if not extern then dep tags [lib] (* cannot happen? *)
+ in
+ Hashtbl.replace info_libraries tag_name (libpath, extern);
+ (* adding [tag_name] to [info_libraries] will make this tag
+ affect include-dir lookups, so it is used even if not
+ mentioned explicitly in any rule. *)
+ Flags.mark_tag_used tag_name;
+ if extern then begin
+ if byte then
+ flag_and_dep ["ocaml"; tag_name; "link"; "byte"] (libpath^".cma");
+ if native then
+ flag_and_dep ["ocaml"; tag_name; "link"; "native"] (libpath^".cmxa");
+ end else begin
+ if not byte && not native then
+ invalid_arg "ocaml_lib: ~byte:false or ~native:false only works with ~extern:true";
+ end;
+ match dir with
+ | None -> ()
+ | Some dir ->
+ List.iter
+ (fun x -> flag ["ocaml"; tag_name; x] (S[A"-I"; P dir]))
+ ["compile"; "doc"; "infer_interface"]
+
+let cmi_of = Pathname.update_extensions "cmi"
+
+exception Ocamldep_error of string
+
+let read_path_dependencies =
+ let path_dependencies = Hashtbl.create 103 in
+ let read path =
+ let module_name = module_name_of_pathname path in
+ let depends = path-.-"depends" in
+ with_input_file depends begin fun ic ->
+ let ocamldep_output =
+ try Lexers.ocamldep_output
+ Const.Source.ocamldep (Lexing.from_channel ic)
+ with Lexers.Error (msg,_) -> raise (Ocamldep_error(Printf.sprintf "Ocamldep.ocamldep: bad output (%s)" msg)) in
+ let deps =
+ List.fold_right begin fun (path, deps) acc ->
+ let module_name' = module_name_of_pathname path in
+ if module_name' = module_name
+ then List.union deps acc
+ else raise (Ocamldep_error(Printf.sprintf "Ocamldep.ocamldep: multiple files in ocamldep output (%s not expected)" path))
+ end ocamldep_output [] in
+ let deps =
+ if !Options.nostdlib && not (Tags.mem "nopervasives" (tags_of_pathname path)) then
+ "Pervasives" :: deps
+ else deps in
+ let deps' = List.fold_right begin fun dep acc ->
+ match path_importance path dep with
+ | `ignored -> acc
+ | (`just_try | `mandatory) as importance -> (importance, dep) :: acc
+ end deps [] in
+ Hashtbl.replace path_dependencies path
+ (List.union (try Hashtbl.find path_dependencies path with Not_found -> []) deps');
+ deps'
+ end
+ in read
+
+let path_dependencies_of = memo read_path_dependencies
diff --git a/ocamlbuild/ocaml_utils.mli b/ocamlbuild/ocaml_utils.mli
new file mode 100644
index 0000000000..8d985b043c
--- /dev/null
+++ b/ocamlbuild/ocaml_utils.mli
@@ -0,0 +1,47 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+val stdlib_dir : Pathname.t Lazy.t
+val module_name_of_filename : Pathname.t -> string
+val module_name_of_pathname : Pathname.t -> string
+val ignore_stdlib : string -> bool
+val non_dependency : string -> string -> unit
+val expand_module :
+ Pathname.t list -> Pathname.t -> string list -> Pathname.t list
+val string_list_of_file : string -> string list
+val ocaml_ppflags : Tags.t -> Command.spec
+val ocaml_include_flags : Pathname.t -> Command.spec
+val libraries_of : Pathname.t -> Pathname.t list
+val use_lib : Pathname.t -> Pathname.t -> unit
+val cmi_of : Pathname.t -> Pathname.t
+val ocaml_add_include_flag : string -> Command.spec list -> Command.spec list
+val flag_and_dep : Tags.elt list -> Command.spec -> unit
+val pflag_and_dep : Tags.elt list -> Tags.elt -> (string -> Command.spec) ->
+ unit
+
+exception Ocamldep_error of string
+
+(* Takes a path and returns a list of modules *)
+val path_dependencies_of : Pathname.t -> ([ `mandatory | `just_try ] * string) list
+
+val info_libraries : (string, string * bool) Hashtbl.t
+
+val ocaml_lib :
+ ?extern:bool ->
+ ?byte:bool ->
+ ?native:bool ->
+ ?dir:Pathname.t ->
+ ?tag_name:string ->
+ Pathname.t -> unit
diff --git a/ocamlbuild/ocamlbuild.ml b/ocamlbuild/ocamlbuild.ml
new file mode 100644
index 0000000000..a0c31c4f30
--- /dev/null
+++ b/ocamlbuild/ocamlbuild.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+Ocamlbuild_unix_plugin.setup ();
+Ocamlbuild_pack.Main.main ()
diff --git a/ocamlbuild/ocamlbuild.mli b/ocamlbuild/ocamlbuild.mli
new file mode 100644
index 0000000000..b2e489dce8
--- /dev/null
+++ b/ocamlbuild/ocamlbuild.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(** Nothing to export for now *)
diff --git a/ocamlbuild/ocamlbuild.mltop b/ocamlbuild/ocamlbuild.mltop
new file mode 100644
index 0000000000..41c1afb01f
--- /dev/null
+++ b/ocamlbuild/ocamlbuild.mltop
@@ -0,0 +1,3 @@
+Ocamlbuild_pack
+Ocamlbuild_plugin
+Ocamlbuild_unix_plugin
diff --git a/ocamlbuild/ocamlbuild.odocl b/ocamlbuild/ocamlbuild.odocl
new file mode 100644
index 0000000000..fe0c1730b7
--- /dev/null
+++ b/ocamlbuild/ocamlbuild.odocl
@@ -0,0 +1,41 @@
+Log
+My_unix
+My_std
+Signatures
+Shell
+Display
+Command
+Configuration
+Discard_printf
+Flags
+Hygiene
+Options
+Pathname
+Report
+Resource
+Rule
+Slurp
+Solver
+Tags
+Tools
+Fda
+Ocaml_specific
+Ocaml_arch
+Ocamlbuild_where
+Ocamlbuild_Myocamlbuild_config
+Lexers
+Glob
+Bool
+Glob_ast
+Glob_lexer
+Plugin
+Main
+Hooks
+Ocaml_utils
+Ocaml_tools
+Ocaml_compiler
+Ocaml_dependencies
+Exit_codes
+Digest_cache
+Ocamlbuild_plugin
+Findlib
diff --git a/ocamlbuild/ocamlbuild_executor.ml b/ocamlbuild/ocamlbuild_executor.ml
new file mode 100644
index 0000000000..01394d03c1
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_executor.ml
@@ -0,0 +1,351 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Ocamlbuild_executor *)
+
+open Unix;;
+
+type error =
+ | Subcommand_failed
+ | Subcommand_got_signal
+ | Io_error
+ | Exceptionl_condition
+
+type task = unit -> string;;
+
+type job = {
+ job_id : int * int;
+ job_command : string;
+ job_next : task list;
+ job_result : bool ref; (* Result of this sequence group *)
+ job_stdout : in_channel;
+ job_stdin : out_channel;
+ job_stderr : in_channel;
+ job_buffer : Buffer.t;
+ mutable job_dying : bool;
+};;
+
+module JS = Set.Make(struct type t = job let compare = compare end);;
+module FDM = Map.Make(struct type t = file_descr let compare = compare end);;
+
+let sf = Printf.sprintf;;
+let fp = Printf.fprintf;;
+
+(*** print_unix_status *)
+(* FIXME never called *)
+let print_unix_status oc = function
+ | WEXITED x -> fp oc "exit %d" x
+ | WSIGNALED i -> fp oc "signal %d" i
+ | WSTOPPED i -> fp oc "stop %d" i
+;;
+(* ***)
+(*** print_job_id *)
+let print_job_id oc (x,y) = fp oc "%d.%d" x y;;
+(* ***)
+(*** output_lines *)
+let output_lines prefix oc buffer =
+ let u = Buffer.contents buffer in
+ let m = String.length u in
+ let output_line i j =
+ output_string oc prefix;
+ output_substring oc u i (j - i);
+ output_char oc '\n'
+ in
+ let rec loop i =
+ if i < m then
+ let j =
+ try String.index_from u i '\n'
+ with Not_found -> m
+ in
+ output_line i j;
+ loop (j + 1)
+ else
+ ()
+ in
+ loop 0
+;;
+(* ***)
+(*** execute *)
+(* XXX: Add test for non reentrancy *)
+let execute
+ ?(max_jobs=max_int)
+ ?(ticker=ignore)
+ ?(period=0.1)
+ ?(display=(fun f -> f Pervasives.stdout))
+ ~exit
+ (commands : task list list)
+ =
+ let batch_id = ref 0 in
+ let env = environment () in
+ let jobs = ref JS.empty in
+ let jobs_active = ref 0 in
+ let jobs_to_terminate = Queue.create () in
+ let commands_to_execute = Queue.create () in
+ let all_ok = ref true in
+ let results =
+ List.map (fun tasks ->
+ let result = ref false in
+ Queue.add (tasks, result) commands_to_execute;
+ result)
+ commands
+ in
+ let outputs = ref FDM.empty in
+ let doi = descr_of_in_channel in
+ let doo = descr_of_out_channel in
+ (*** compute_fds *)
+ let compute_fds =
+ let fds = ref ([], [], []) in
+ let prev_jobs = ref JS.empty in
+ fun () ->
+ if not (!prev_jobs == !jobs) then
+ begin
+ prev_jobs := !jobs;
+ fds :=
+ JS.fold
+ begin fun job (rfds, wfds, xfds) ->
+ let ofd = doi job.job_stdout
+ and ifd = doo job.job_stdin
+ and efd = doi job.job_stderr
+ in
+ (ofd :: efd :: rfds, wfds, ofd :: ifd :: efd :: xfds)
+ end
+ !jobs
+ ([], [], [])
+ end;
+ !fds
+ in
+ (* ***)
+ (*** add_job *)
+ let add_job cmd rest result id =
+ (*display begin fun oc -> fp oc "Job %a is %s\n%!" print_job_id id cmd; end;*)
+ let (stdout', stdin', stderr') = open_process_full cmd env in
+ incr jobs_active;
+ set_nonblock (doi stdout');
+ set_nonblock (doi stderr');
+ let job =
+ { job_id = id;
+ job_command = cmd;
+ job_next = rest;
+ job_result = result;
+ job_stdout = stdout';
+ job_stdin = stdin';
+ job_stderr = stderr';
+ job_buffer = Buffer.create 1024;
+ job_dying = false }
+ in
+ outputs := FDM.add (doi stdout') job (FDM.add (doi stderr') job !outputs);
+ jobs := JS.add job !jobs;
+ in
+ (* ***)
+ (*** skip_empty_tasks *)
+ let rec skip_empty_tasks = function
+ | [] -> None
+ | task :: tasks ->
+ let cmd = task () in
+ if cmd = "" then skip_empty_tasks tasks else Some(cmd, tasks)
+ in
+ (* ***)
+ (*** add_some_jobs *)
+ let add_some_jobs () =
+ let (tasks, result) = Queue.take commands_to_execute in
+ match skip_empty_tasks tasks with
+ | None -> result := false
+ | Some(cmd, rest) ->
+ let b_id = !batch_id in
+ incr batch_id;
+ add_job cmd rest result (b_id, 0)
+ in
+ (* ***)
+ (*** terminate *)
+ let terminate ?(continue=true) job =
+ if not job.job_dying then
+ begin
+ job.job_dying <- true;
+ Queue.add (job, continue) jobs_to_terminate
+ end
+ else
+ ()
+ in
+ (* ***)
+ (*** add_more_jobs_if_possible *)
+ let add_more_jobs_if_possible () =
+ while !jobs_active < max_jobs && not (Queue.is_empty commands_to_execute) do
+ add_some_jobs ()
+ done
+ in
+ (* ***)
+ (*** do_read *)
+ let do_read =
+ let u = Bytes.create 4096 in
+ fun ?(loop=false) fd job ->
+ (*if job.job_dying then
+ ()
+ else*)
+ try
+ let rec iteration () =
+ let m =
+ try
+ read fd u 0 (Bytes.length u)
+ with
+ | Unix.Unix_error(e,_,_) ->
+ let msg = error_message e in
+ display (fun oc -> fp oc
+ "Error while reading stdout/stderr: %s\n" msg);
+ 0
+ in
+ if m = 0 then
+ if job.job_dying then
+ ()
+ else
+ terminate job
+ else
+ begin
+ Buffer.add_subbytes job.job_buffer u 0 m;
+ if loop then
+ iteration ()
+ else
+ ()
+ end
+ in
+ iteration ()
+ with
+ | x ->
+ display
+ begin fun oc ->
+ fp oc "Exception %s while reading output of command %S\n%!" job.job_command
+ (Printexc.to_string x);
+ end;
+ exit Io_error
+ in
+ (* ***)
+ (*** process_jobs_to_terminate *)
+ let process_jobs_to_terminate () =
+ while not (Queue.is_empty jobs_to_terminate) do
+ ticker ();
+ let (job, continue) = Queue.take jobs_to_terminate in
+
+ (*display begin fun oc -> fp oc "Terminating job %a\n%!" print_job_id job.job_id; end;*)
+
+ decr jobs_active;
+
+ (* PR#5371: we would get EAGAIN below otherwise *)
+ clear_nonblock (doi job.job_stdout);
+ clear_nonblock (doi job.job_stderr);
+
+ do_read ~loop:true (doi job.job_stdout) job;
+ do_read ~loop:true (doi job.job_stderr) job;
+ outputs := FDM.remove (doi job.job_stdout) (FDM.remove (doi job.job_stderr) !outputs);
+ jobs := JS.remove job !jobs;
+ let status = close_process_full (job.job_stdout, job.job_stdin, job.job_stderr) in
+
+ let shown = ref false in
+
+ let show_command () =
+ if !shown then
+ ()
+ else
+ display
+ begin fun oc ->
+ shown := true;
+ fp oc "+ %s\n" job.job_command;
+ output_lines "" oc job.job_buffer
+ end
+ in
+ if Buffer.length job.job_buffer > 0 then show_command ();
+ begin
+ match status with
+ | Unix.WEXITED 0 ->
+ begin
+ if continue then
+ begin
+ match skip_empty_tasks job.job_next with
+ | None -> job.job_result := true
+ | Some(cmd, rest) ->
+ let (b_id, s_id) = job.job_id in
+ add_job cmd rest job.job_result (b_id, s_id + 1)
+ end
+ else
+ all_ok := false;
+ end
+ | Unix.WEXITED rc ->
+ show_command ();
+ display (fun oc -> fp oc "Command exited with code %d.\n" rc);
+ all_ok := false;
+ exit Subcommand_failed
+ | Unix.WSTOPPED s | Unix.WSIGNALED s ->
+ show_command ();
+ all_ok := false;
+ display (fun oc -> fp oc "Command got signal %d.\n" s);
+ exit Subcommand_got_signal
+ end
+ done
+ in
+ (* ***)
+ (*** terminate_all_jobs *)
+ let terminate_all_jobs () =
+ JS.iter (terminate ~continue:false) !jobs
+ in
+ (* ***)
+ (*** loop *)
+ let rec loop () =
+ (*display (fun oc -> fp oc "Total %d jobs\n" !jobs_active);*)
+ process_jobs_to_terminate ();
+ add_more_jobs_if_possible ();
+ if JS.is_empty !jobs then
+ ()
+ else
+ begin
+ let (rfds, wfds, xfds) = compute_fds () in
+ ticker ();
+ let (chrfds, chwfds, chxfds) = select rfds wfds xfds period in
+ List.iter
+ begin fun (fdlist, hook) ->
+ List.iter
+ begin fun fd ->
+ try
+ let job = FDM.find fd !outputs in
+ ticker ();
+ hook fd job
+ with
+ | Not_found -> () (* XXX *)
+ end
+ fdlist
+ end
+ [chrfds, do_read ~loop:false;
+ chwfds, (fun _ _ -> ());
+ chxfds,
+ begin fun _ _job ->
+ (*display (fun oc -> fp oc "Exceptional condition on command %S\n%!" job.job_command);
+ exit Exceptional_condition*)
+ () (* FIXME *)
+ end];
+ loop ()
+ end
+ in
+ try
+ loop ();
+ None
+ with
+ | x ->
+ begin
+ try
+ terminate_all_jobs ()
+ with
+ | x' ->
+ display (fun oc -> fp oc "Extra exception %s\n%!" (Printexc.to_string x'))
+ end;
+ Some(List.map (!) results, x)
+;;
+(* ***)
diff --git a/ocamlbuild/ocamlbuild_executor.mli b/ocamlbuild/ocamlbuild_executor.mli
new file mode 100644
index 0000000000..746aaf0a54
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_executor.mli
@@ -0,0 +1,56 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Ocamlbuild_executor *)
+
+(** UNIX-specific module for running tasks in parallel and properly multiplexing their outputs. *)
+
+type error =
+ | Subcommand_failed
+ | Subcommand_got_signal
+ | Io_error
+ | Exceptionl_condition
+
+(** [execute ~ticker ~period ~display ~exit commands] will execute the commands
+ in [commands] in parallel, correctly multiplexing their outputs.
+
+ A command is a function that given a unit [()] returns the shell command
+ string to execute, commands are functions in order to do some job just
+ before executing the command. These functions will be called once. If
+ specified, it will call [ticker] at least every [period] seconds. If
+ specified, it will call [display f] when it wishes to print something;
+ [display] should then call [f] with then channel on which [f] should
+ print.
+
+ Note that if the shell command to execute is the empty string [""], it's
+ considered as a no-op.
+
+ Note that [f] must be idempotent as it may well be called twice, once for
+ the log file, once for the actual output.
+
+ If one of the commands fails, it will exit with an appropriate error code,
+ calling [cleanup] before.
+
+ All exits are done trough the call to the given [exit] function, if not
+ supplied Pervasives.exit is used.
+*)
+val execute :
+ ?max_jobs:int ->
+ ?ticker:(unit -> unit) ->
+ ?period:float ->
+ ?display:((out_channel -> unit) -> unit) ->
+ exit:(error -> unit) ->
+ ((unit -> string) list list) ->
+ (bool list * exn) option
diff --git a/ocamlbuild/ocamlbuild_pack.mlpack b/ocamlbuild/ocamlbuild_pack.mlpack
new file mode 100644
index 0000000000..450592f539
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_pack.mlpack
@@ -0,0 +1,43 @@
+Const
+Loc
+Log
+My_unix
+My_std
+Signatures
+Shell
+Display
+Command
+Configuration
+Discard_printf
+Flags
+Hygiene
+Options
+Pathname
+Report
+Resource
+Rule
+Slurp
+Solver
+Tags
+Tools
+Fda
+Ocaml_specific
+Ocaml_arch
+Ocamlbuild_where
+Ocamlbuild_Myocamlbuild_config
+Lexers
+Glob
+Bool
+Glob_ast
+Glob_lexer
+Plugin
+Main
+Hooks
+Ocaml_utils
+Ocaml_tools
+Ocaml_compiler
+Ocaml_dependencies
+Exit_codes
+Digest_cache
+Findlib
+Param_tags
diff --git a/ocamlbuild/ocamlbuild_plugin.ml b/ocamlbuild/ocamlbuild_plugin.ml
new file mode 100644
index 0000000000..126eecd094
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_plugin.ml
@@ -0,0 +1,64 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+
+open Ocamlbuild_pack
+include Ocamlbuild_pack.My_std
+module Arch = Ocamlbuild_pack.Ocaml_arch
+module Command = Ocamlbuild_pack.Command
+module Pathname = Ocamlbuild_pack.Pathname
+module Tags = Ocamlbuild_pack.Tags
+include Pathname.Operators
+include Tags.Operators
+module Rule = Ocamlbuild_pack.Rule
+module Options = Ocamlbuild_pack.Options
+module Findlib = Ocamlbuild_pack.Findlib
+type command = Command.t = Seq of command list | Cmd of spec | Echo of string list * string | Nop
+and spec = Command.spec =
+ | N | S of spec list | A of string | P of string | Px of string
+ | Sh of string | T of Tags.t | V of string | Quote of spec
+include Rule.Common_commands
+type env = Pathname.t -> Pathname.t
+type builder = Pathname.t list list -> (Pathname.t, exn) Ocamlbuild_pack.My_std.Outcome.t list
+type action = env -> builder -> Command.t
+let rule = Rule.rule
+let clear_rules = Rule.clear_rules
+let dep = Command.dep
+let pdep = Command.pdep
+let copy_rule = Rule.copy_rule
+let ocaml_lib = Ocamlbuild_pack.Ocaml_utils.ocaml_lib
+let flag = Ocamlbuild_pack.Flags.flag ?deprecated:None
+let pflag = Ocamlbuild_pack.Flags.pflag
+let mark_tag_used = Ocamlbuild_pack.Flags.mark_tag_used
+let flag_and_dep = Ocamlbuild_pack.Ocaml_utils.flag_and_dep
+let pflag_and_dep = Ocamlbuild_pack.Ocaml_utils.pflag_and_dep
+let non_dependency = Ocamlbuild_pack.Ocaml_utils.non_dependency
+let use_lib = Ocamlbuild_pack.Ocaml_utils.use_lib
+let module_name_of_pathname = Ocamlbuild_pack.Ocaml_utils.module_name_of_pathname
+let string_list_of_file = Ocamlbuild_pack.Ocaml_utils.string_list_of_file
+let expand_module = Ocamlbuild_pack.Ocaml_utils.expand_module
+let tags_of_pathname = Ocamlbuild_pack.Tools.tags_of_pathname
+let hide_package_contents = Ocamlbuild_pack.Ocaml_compiler.hide_package_contents
+let tag_file = Ocamlbuild_pack.Configuration.tag_file
+let tag_any = Ocamlbuild_pack.Configuration.tag_any
+let run_and_read = Ocamlbuild_pack.My_unix.run_and_read
+type hook = Ocamlbuild_pack.Hooks.message =
+ | Before_hygiene
+ | After_hygiene
+ | Before_options
+ | After_options
+ | Before_rules
+ | After_rules
+let dispatch = Ocamlbuild_pack.Hooks.setup_hooks
diff --git a/ocamlbuild/ocamlbuild_plugin.mli b/ocamlbuild/ocamlbuild_plugin.mli
new file mode 100644
index 0000000000..b03afa74b3
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_plugin.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+include Ocamlbuild_pack.Signatures.PLUGIN
+ with module Pathname = Ocamlbuild_pack.Pathname
+ and module Outcome = Ocamlbuild_pack.My_std.Outcome
+ and module Tags = Ocamlbuild_pack.Tags
+ and module Command = Ocamlbuild_pack.Command
diff --git a/ocamlbuild/ocamlbuild_unix_plugin.ml b/ocamlbuild/ocamlbuild_unix_plugin.ml
new file mode 100644
index 0000000000..092347347b
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_unix_plugin.ml
@@ -0,0 +1,96 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open Format
+open Ocamlbuild_pack
+open My_unix
+
+let report_error f =
+ function
+ | Unix.Unix_error(err, fun_name, arg) ->
+ fprintf f "%s: %S failed" Sys.argv.(0) fun_name;
+ if String.length arg > 0 then
+ fprintf f " on %S" arg;
+ fprintf f ": %s" (Unix.error_message err)
+ | exn -> raise exn
+
+let mkstat unix_stat x =
+ let st =
+ try unix_stat x
+ with Unix.Unix_error _ as e -> raise (Sys_error (My_std.sbprintf "%a" report_error e))
+ in
+ { stat_key = sprintf "(%d,%d)" st.Unix.st_dev st.Unix.st_ino;
+ stat_file_kind =
+ match st.Unix.st_kind with
+ | Unix.S_LNK -> FK_link
+ | Unix.S_DIR -> FK_dir
+ | Unix.S_CHR | Unix.S_BLK | Unix.S_FIFO | Unix.S_SOCK -> FK_other
+ | Unix.S_REG -> FK_file }
+
+let is_link s = (Unix.lstat s).Unix.st_kind = Unix.S_LNK
+
+let at_exit_once callback =
+ let pid = Unix.getpid () in
+ at_exit begin fun () ->
+ if pid = Unix.getpid () then callback ()
+ end
+
+let run_and_open s kont =
+ let ic = Unix.open_process_in s in
+ let close () =
+ match Unix.close_process_in ic with
+ | Unix.WEXITED 0 -> ()
+ | Unix.WEXITED _ | Unix.WSIGNALED _ | Unix.WSTOPPED _ ->
+ failwith (Printf.sprintf "Error while running: %s" s) in
+ let res = try
+ kont ic
+ with e -> (close (); raise e)
+ in close (); res
+
+let stdout_isatty () =
+ Unix.isatty Unix.stdout &&
+ try Unix.getenv "TERM" <> "dumb" with Not_found -> true
+
+let execute_many =
+ let exit i = raise (My_std.Exit_with_code i) in
+ let exit = function
+ | Ocamlbuild_executor.Subcommand_failed -> exit Exit_codes.rc_executor_subcommand_failed
+ | Ocamlbuild_executor.Subcommand_got_signal -> exit Exit_codes.rc_executor_subcommand_got_signal
+ | Ocamlbuild_executor.Io_error -> exit Exit_codes.rc_executor_io_error
+ | Ocamlbuild_executor.Exceptionl_condition -> exit Exit_codes.rc_executor_excetptional_condition
+ in
+ Ocamlbuild_executor.execute ~exit
+
+(* Ocamlbuild code assumes throughout that [readlink] will return a file name
+ relative to the current directory. Let's make it so. *)
+let myunixreadlink x =
+ let y = Unix.readlink x in
+ if Filename.is_relative y then
+ Filename.concat (Filename.dirname x) y
+ else
+ y
+
+let setup () =
+ implem.is_degraded <- false;
+ implem.stdout_isatty <- stdout_isatty;
+ implem.gettimeofday <- Unix.gettimeofday;
+ implem.report_error <- report_error;
+ implem.execute_many <- execute_many;
+ implem.readlink <- myunixreadlink;
+ implem.run_and_open <- run_and_open;
+ implem.at_exit_once <- at_exit_once;
+ implem.is_link <- is_link;
+ implem.stat <- mkstat Unix.stat;
+ implem.lstat <- mkstat Unix.lstat;;
diff --git a/ocamlbuild/ocamlbuild_unix_plugin.mli b/ocamlbuild/ocamlbuild_unix_plugin.mli
new file mode 100644
index 0000000000..521d464353
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_unix_plugin.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+val setup : unit -> unit
diff --git a/ocamlbuild/ocamlbuild_where.ml b/ocamlbuild/ocamlbuild_where.ml
new file mode 100644
index 0000000000..cb8b846227
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_where.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let bindir = ref Ocamlbuild_config.bindir;;
+let libdir = ref begin
+ Filename.concat
+ (try Sys.getenv "OCAMLLIB"
+ with Not_found -> Ocamlbuild_config.libdir)
+ "ocamlbuild"
+end;;
diff --git a/ocamlbuild/ocamlbuild_where.mli b/ocamlbuild/ocamlbuild_where.mli
new file mode 100644
index 0000000000..621eff493e
--- /dev/null
+++ b/ocamlbuild/ocamlbuild_where.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+
+(* Original author: Nicolas Pouillard *)
+
+val bindir : string ref
+val libdir : string ref
diff --git a/ocamlbuild/ocamlbuildlib.mllib b/ocamlbuild/ocamlbuildlib.mllib
new file mode 100644
index 0000000000..767ed32c6c
--- /dev/null
+++ b/ocamlbuild/ocamlbuildlib.mllib
@@ -0,0 +1,4 @@
+Ocamlbuild_pack
+Ocamlbuild_plugin
+Ocamlbuild_unix_plugin
+Ocamlbuild_executor
diff --git a/ocamlbuild/ocamlbuildlight.ml b/ocamlbuild/ocamlbuildlight.ml
new file mode 100644
index 0000000000..fc90994b84
--- /dev/null
+++ b/ocamlbuild/ocamlbuildlight.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+Ocamlbuild_pack.Main.main ();;
diff --git a/ocamlbuild/ocamlbuildlight.mli b/ocamlbuild/ocamlbuildlight.mli
new file mode 100644
index 0000000000..5cd73796bb
--- /dev/null
+++ b/ocamlbuild/ocamlbuildlight.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Nothing *)
diff --git a/ocamlbuild/ocamlbuildlightlib.mllib b/ocamlbuild/ocamlbuildlightlib.mllib
new file mode 100644
index 0000000000..dc38da3dc4
--- /dev/null
+++ b/ocamlbuild/ocamlbuildlightlib.mllib
@@ -0,0 +1,2 @@
+Ocamlbuild_pack
+Ocamlbuild_plugin
diff --git a/ocamlbuild/options.ml b/ocamlbuild/options.ml
new file mode 100644
index 0000000000..2cc234b431
--- /dev/null
+++ b/ocamlbuild/options.ml
@@ -0,0 +1,374 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+
+let version = "ocamlbuild "^(Sys.ocaml_version);;
+
+type command_spec = Command.spec
+
+open My_std
+open Arg
+open Format
+open Command
+
+let entry = ref None
+let project_root_dir = ref None
+let build_dir = ref (Filename.concat (Sys.getcwd ()) "_build")
+let include_dirs = ref []
+let exclude_dirs = ref []
+let nothing_should_be_rebuilt = ref false
+let sanitize = ref true
+let sanitization_script = ref "sanitize.sh"
+let hygiene = ref true
+let ignore_auto = ref true
+let plugin = ref true
+let just_plugin = ref false
+let native_plugin = ref true
+let make_links = ref true
+let nostdlib = ref false
+let use_menhir = ref false
+let catch_errors = ref true
+let use_ocamlfind = ref false
+
+(* Currently only ocamlfind and menhir is defined as no-core tool,
+ perhaps later we need something better *)
+let is_core_tool = function "ocamlfind" | "menhir" -> false | _ -> true
+
+let find_tool cmd =
+ let dir = Ocamlbuild_where.bindir in
+ let core_tool = is_core_tool cmd in
+ let opt = cmd ^ ".opt" in
+ let search_in_path = memo Command.search_in_path in
+ if sys_file_exists !dir then
+ let long = filename_concat !dir cmd in
+ let long_opt = long ^ ".opt" in
+ (* This defines how the command will be found *)
+ let choices =
+ [(fun () -> if file_or_exe_exists long_opt then Some long_opt else None);
+ (fun () -> if file_or_exe_exists long then Some long else None)] in
+ (* For non core tool the preference is too look at PATH first *)
+ let choices' =
+ [fun () ->
+ try let _ = search_in_path opt in Some opt
+ with Not_found -> Some cmd]
+ in
+ let choices = if core_tool then choices @ choices' else choices' @ choices in
+ try
+ match (List.find (fun choice -> not (choice () = None)) choices) () with
+ Some cmd -> cmd
+ | None -> raise Not_found
+ with Not_found -> failwith (Printf.sprintf "Can't find tool: %s" cmd)
+ else
+ try let _ = search_in_path opt in opt
+ with Not_found -> cmd
+
+let mk_virtual_solvers =
+ List.iter begin fun cmd ->
+ let solver () =
+ A (find_tool cmd)
+ in Command.setup_virtual_command_solver (String.uppercase_ascii cmd) solver
+ end
+
+let () =
+ mk_virtual_solvers
+ ["ocamlc"; "ocamlopt"; "ocamldep"; "ocamldoc";
+ "ocamlyacc"; "menhir"; "ocamllex"; "ocamlmklib"; "ocamlmktop"; "ocamlfind"]
+let ocamlc = ref (V"OCAMLC")
+let ocamlopt = ref (V"OCAMLOPT")
+let ocamldep = ref (V"OCAMLDEP")
+let ocamldoc = ref (V"OCAMLDOC")
+let ocamlyacc = ref N
+let ocamllex = ref (V"OCAMLLEX")
+let ocamlmklib = ref (V"OCAMLMKLIB")
+let ocamlmktop = ref (V"OCAMLMKTOP")
+let ocamlrun = ref N
+let ocamlfind_cmd = ref (V"OCAMLFIND")
+let ocamlfind arg = S[!ocamlfind_cmd; arg]
+let program_to_execute = ref false
+let must_clean = ref false
+let show_documentation = ref false
+let recursive = ref false
+let ext_lib = ref Ocamlbuild_config.a
+let ext_obj = ref Ocamlbuild_config.o
+let ext_dll =
+ let s = Ocamlbuild_config.ext_dll in
+ ref (String.sub s 1 (String.length s - 1))
+let exe = ref Ocamlbuild_config.exe
+
+let targets_internal = ref []
+let ocaml_libs_internal = ref []
+let ocaml_mods_internal = ref []
+let ocaml_pkgs_internal = ref []
+let ocaml_syntax = ref None
+let ocaml_lflags_internal = ref []
+let ocaml_cflags_internal = ref []
+let ocaml_docflags_internal = ref []
+let ocaml_ppflags_internal = ref []
+let ocaml_yaccflags_internal = ref []
+let ocaml_lexflags_internal = ref []
+let program_args_internal = ref []
+let ignore_list_internal = ref []
+let tags_internal = ref [["quiet"]]
+let tag_lines_internal = ref []
+let show_tags_internal = ref []
+let plugin_tags_internal = ref []
+let log_file_internal = ref "_log"
+
+let my_include_dirs = ref [[Filename.current_dir_name]]
+let my_exclude_dirs = ref [[".svn"; "CVS"]]
+
+let dummy = "*invalid-dummy-string*";; (* Dummy string for delimiting the latest argument *)
+
+(* The JoCaml support will be in a plugin when the plugin system will support
+ * multiple/installed plugins *)
+let use_jocaml () =
+ ocamlc := A "jocamlc";
+ ocamlopt := A "jocamlopt";
+ ocamldep := A "jocamldep";
+ ocamlyacc := A "jocamlyacc";
+ ocamllex := A "jocamllex";
+ ocamlmklib := A "jocamlmklib";
+ ocamlmktop := A "jocamlmktop";
+ ocamlrun := A "jocamlrun";
+;;
+
+let add_to rxs x =
+ let xs = Lexers.comma_or_blank_sep_strings
+ Const.Source.command_line (Lexing.from_string x) in
+ rxs := xs :: !rxs
+let add_to' rxs x =
+ if x <> dummy then
+ rxs := [x] :: !rxs
+ else
+ ()
+let set_cmd rcmd = String (fun s -> rcmd := Sh s)
+let set_build_dir s =
+ make_links := false;
+ if Filename.is_relative s then
+ build_dir := Filename.concat (Sys.getcwd ()) s
+ else
+ build_dir := s
+let spec = ref (
+ Arg.align
+ [
+ "-version", Unit (fun () -> print_endline version; raise Exit_OK), " Display the version";
+ "-vnum", Unit (fun () -> print_endline Sys.ocaml_version; raise Exit_OK),
+ " Display the version number";
+ "-quiet", Unit (fun () -> Log.level := 0), " Make as quiet as possible";
+ "-verbose", Int (fun i -> Log.classic_display := true; Log.level := i + 2), "<level> Set the verbosity level";
+ "-documentation", Set show_documentation, " Show rules and flags";
+ "-log", Set_string log_file_internal, "<file> Set log file";
+ "-no-log", Unit (fun () -> log_file_internal := ""), " No log file";
+ "-clean", Set must_clean, " Remove build directory and other files, then exit";
+ "-r", Set recursive, " Traverse directories by default (true: traverse)";
+
+ "-I", String (add_to' my_include_dirs), "<path> Add to include directories";
+ "-Is", String (add_to my_include_dirs), "<path,...> (same as above, but accepts a (comma or blank)-separated list)";
+ "-X", String (add_to' my_exclude_dirs), "<path> Directory to ignore";
+ "-Xs", String (add_to my_exclude_dirs), "<path,...> (idem)";
+
+ "-lib", String (add_to' ocaml_libs_internal), "<flag> Link to this ocaml library";
+ "-libs", String (add_to ocaml_libs_internal), "<flag,...> (idem)";
+ "-mod", String (add_to' ocaml_mods_internal), "<module> Link to this ocaml module";
+ "-mods", String (add_to ocaml_mods_internal), "<module,...> (idem)";
+ "-pkg", String (add_to' ocaml_pkgs_internal), "<package> Link to this ocaml findlib package";
+ "-pkgs", String (add_to ocaml_pkgs_internal), "<package,...> (idem)";
+ "-package", String (add_to' ocaml_pkgs_internal), "<package> (idem)";
+ "-syntax", String (fun syntax -> ocaml_syntax := Some syntax), "<syntax> Specify syntax using ocamlfind";
+ "-lflag", String (add_to' ocaml_lflags_internal), "<flag> Add to ocamlc link flags";
+ "-lflags", String (add_to ocaml_lflags_internal), "<flag,...> (idem)";
+ "-cflag", String (add_to' ocaml_cflags_internal), "<flag> Add to ocamlc compile flags";
+ "-cflags", String (add_to ocaml_cflags_internal), "<flag,...> (idem)";
+ "-docflag", String (add_to' ocaml_docflags_internal), "<flag> Add to ocamldoc flags";
+ "-docflags", String (add_to ocaml_docflags_internal), "<flag,...> (idem)";
+ "-yaccflag", String (add_to' ocaml_yaccflags_internal), "<flag> Add to ocamlyacc flags";
+ "-yaccflags", String (add_to ocaml_yaccflags_internal), "<flag,...> (idem)";
+ "-lexflag", String (add_to' ocaml_lexflags_internal), "<flag> Add to ocamllex flags";
+ "-lexflags", String (add_to ocaml_lexflags_internal), "<flag,...> (idem)";
+ "-ppflag", String (add_to' ocaml_ppflags_internal), "<flag> Add to ocaml preprocessing flags";
+ "-pp", String (add_to ocaml_ppflags_internal), "<flag,...> (idem)";
+ "-tag", String (add_to' tags_internal), "<tag> Add to default tags";
+ "-tags", String (add_to tags_internal), "<tag,...> (idem)";
+ "-plugin-tag", String (add_to' plugin_tags_internal), "<tag> Use this tag when compiling the myocamlbuild.ml plugin";
+ "-plugin-tags", String (add_to plugin_tags_internal), "<tag,...> (idem)";
+ "-tag-line", String (add_to' tag_lines_internal), "<tag> Use this line of tags (as in _tags)";
+ "-show-tags", String (add_to' show_tags_internal), "<path> Show tags that applies on that pathname";
+
+ "-ignore", String (add_to ignore_list_internal), "<module,...> Don't try to build these modules";
+ "-no-links", Clear make_links, " Don't make links of produced final targets";
+ "-no-skip", Clear ignore_auto, " Don't skip modules that are requested by ocamldep but cannot be built";
+ "-no-hygiene", Clear hygiene, " Don't apply sanity-check rules";
+ "-no-plugin", Clear plugin, " Don't build myocamlbuild.ml";
+ "-no-stdlib", Set nostdlib, " Don't ignore stdlib modules";
+ "-dont-catch-errors", Clear catch_errors, " Don't catch and display exceptions (useful to display the call stack)";
+ "-just-plugin", Set just_plugin, " Just build myocamlbuild.ml";
+ "-byte-plugin", Clear native_plugin, " Don't use a native plugin but bytecode";
+ "-plugin-option", String ignore, " Use the option only when plugin is run";
+ "-sanitization-script", Set_string sanitization_script, " Change the file name for the generated sanitization script";
+ "-no-sanitize", Clear sanitize, " Do not generate sanitization script";
+ "-nothing-should-be-rebuilt", Set nothing_should_be_rebuilt, " Fail if something needs to be rebuilt";
+ "-classic-display", Set Log.classic_display, " Display executed commands the old-fashioned way";
+ "-use-menhir", Set use_menhir, " Use menhir instead of ocamlyacc";
+ "-use-jocaml", Unit use_jocaml, " Use jocaml compilers instead of ocaml ones";
+ "-use-ocamlfind", Set use_ocamlfind, " Use the 'ocamlfind' wrapper instead of \
+ using Findlib directly to determine command-line arguments. \
+ Use -no-ocamlfind to disable.";
+ "-no-ocamlfind", Clear use_ocamlfind, " Don't use ocamlfind.";
+
+ "-j", Set_int Command.jobs, "<N> Allow N jobs at once (0 for unlimited)";
+
+ "-build-dir", String set_build_dir, "<path> Set build directory (implies no-links)";
+ "-install-lib-dir", Set_string Ocamlbuild_where.libdir, "<path> Set the install library directory";
+ "-install-bin-dir", Set_string Ocamlbuild_where.bindir, "<path> Set the install binary directory";
+ "-where", Unit (fun () -> print_endline !Ocamlbuild_where.libdir; raise Exit_OK), " Display the install library directory";
+ "-which", String (fun cmd -> print_endline (find_tool cmd); raise Exit_OK), "<command> Display path to the tool command";
+ "-ocamlc", set_cmd ocamlc, "<command> Set the OCaml bytecode compiler";
+ "-ocamlopt", set_cmd ocamlopt, "<command> Set the OCaml native compiler";
+ "-ocamldep", set_cmd ocamldep, "<command> Set the OCaml dependency tool";
+ "-ocamldoc", set_cmd ocamldoc, "<command> Set the OCaml documentation generator";
+ "-ocamlyacc", set_cmd ocamlyacc, "<command> Set the ocamlyacc tool";
+ "-menhir", set_cmd ocamlyacc, "<command> Set the menhir tool (use it after -use-menhir)";
+ "-ocamllex", set_cmd ocamllex, "<command> Set the ocamllex tool";
+ "-ocamlmklib", set_cmd ocamlmklib, "<command> Set the ocamlmklib tool";
+ "-ocamlmktop", set_cmd ocamlmktop, "<command> Set the ocamlmktop tool";
+ "-ocamlrun", set_cmd ocamlrun, "<command> Set the ocamlrun tool";
+
+ "--", Rest (fun x -> program_to_execute := true; add_to' program_args_internal x),
+ " Stop argument processing, remaining arguments are given to the user program";
+ ])
+
+let add x =
+ spec := !spec @ [x]
+
+let targets = ref []
+let ocaml_libs = ref []
+let ocaml_mods = ref []
+let ocaml_pkgs = ref []
+let ocaml_lflags = ref []
+let ocaml_cflags = ref []
+let ocaml_ppflags = ref []
+let ocaml_docflags = ref []
+let ocaml_yaccflags = ref []
+let ocaml_lexflags = ref []
+let program_args = ref []
+let ignore_list = ref []
+let tags = ref []
+let tag_lines = ref []
+let show_tags = ref []
+let plugin_tags = ref []
+
+let init () =
+ let anon_fun = add_to' targets_internal in
+ let usage_msg = sprintf "Usage %s [options] <target>" Sys.argv.(0) in
+ let argv' = Array.concat [Sys.argv; [|dummy|]] in
+ parse_argv argv' !spec anon_fun usage_msg;
+ Shell.mkdir_p !build_dir;
+
+ project_root_dir := Some (Sys.getcwd ());
+
+ let () =
+ let log = !log_file_internal in
+ if log = "" then Log.init None
+ else if not (Filename.is_implicit log) then
+ failwith
+ (sprintf "Bad log file name: the file name must be implicit (not %S)" log)
+ else
+ let log = filename_concat !build_dir log in
+ Shell.mkdir_p (Filename.dirname log);
+ Shell.rm_f log;
+ let log = if !Log.level > 0 then Some log else None in
+ Log.init log
+ in
+
+ if !use_ocamlfind then begin
+ begin try ignore(Command.search_in_path "ocamlfind")
+ with Not_found ->
+ failwith "ocamlfind not found on path, but -no-ocamlfind not used"
+ end;
+
+ let with_ocamlfind (command_name, command_ref) =
+ command_ref := match !command_ref with
+ | Sh user_command ->
+ (* this command has been set by the user
+ using an -ocamlc, -ocamlopt, etc. flag;
+
+ not all such combinations make sense (eg. "ocamlfind
+ /my/special/path/to/ocamlc" will make ocamlfind choke),
+ but the user will see the error and hopefully fix the
+ flags. *)
+ ocamlfind & (Sh user_command);
+ | _ -> ocamlfind & A command_name
+ in
+ (* Note that plugins can still modify these variables After_options.
+ This design decision can easily be changed. *)
+ List.iter with_ocamlfind [
+ "ocamlc", ocamlc;
+ "ocamlopt", ocamlopt;
+ "ocamldep", ocamldep;
+ "ocamldoc", ocamldoc;
+ "ocamlmklib", ocamlmklib;
+ "ocamlmktop", ocamlmktop;
+ ]
+ end;
+
+ let reorder x y = x := !x @ (List.concat (List.rev !y)) in
+ reorder targets targets_internal;
+ reorder ocaml_libs ocaml_libs_internal;
+ reorder ocaml_mods ocaml_mods_internal;
+ reorder ocaml_pkgs ocaml_pkgs_internal;
+ reorder ocaml_cflags ocaml_cflags_internal;
+ reorder ocaml_lflags ocaml_lflags_internal;
+ reorder ocaml_ppflags ocaml_ppflags_internal;
+ reorder ocaml_docflags ocaml_docflags_internal;
+ reorder ocaml_yaccflags ocaml_yaccflags_internal;
+ reorder ocaml_lexflags ocaml_lexflags_internal;
+ reorder program_args program_args_internal;
+ reorder tags tags_internal;
+ reorder tag_lines tag_lines_internal;
+ reorder ignore_list ignore_list_internal;
+ reorder show_tags show_tags_internal;
+ reorder plugin_tags plugin_tags_internal;
+
+ let check_dir dir =
+ if Filename.is_implicit dir then
+ sys_file_exists dir
+ else
+ failwith
+ (sprintf "Included or excluded directories must be implicit (not %S)" dir)
+ in
+ let dir_reorder my dir =
+ let d = !dir in
+ reorder dir my;
+ dir := List.filter check_dir (!dir @ d)
+ in
+ dir_reorder my_include_dirs include_dirs;
+ dir_reorder my_exclude_dirs exclude_dirs;
+
+ ignore_list := List.map String.capitalize_ascii !ignore_list
+;;
+
+(* The current heuristic: we know we are in an ocamlbuild project if
+ either _tags or myocamlbuild.ml are present at the root. This
+ heuristic has been documented and explained to users, so it should
+ not be changed. *)
+let ocamlbuild_project_heuristic () =
+ let root_dir = match !project_root_dir with
+ | None -> Sys.getcwd ()
+ | Some dir -> dir in
+ let at_root file = Filename.concat root_dir file in
+ Sys.file_exists (* authorized since we're not in build *)
+ (at_root "_tags")
+ || Sys.file_exists (* authorized since we're not in build *)
+ (at_root "myocamlbuild.ml")
diff --git a/ocamlbuild/options.mli b/ocamlbuild/options.mli
new file mode 100644
index 0000000000..63ff762979
--- /dev/null
+++ b/ocamlbuild/options.mli
@@ -0,0 +1,35 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+
+include Signatures.OPTIONS with type command_spec = Command.spec
+
+(* This option is not in Signatures.OPTIONS yet because adding tags to
+ the compilation of the plugin is a recent feature that may still be
+ subject to change, so the interface may not be stable; besides,
+ there is obviously little to gain from tweaking that option from
+ inside the plugin itself... *)
+val plugin_tags : string list ref
+
+(* Returns 'true' if we heuristically infer that we are run from an
+ ocamlbuild projet (either _tags or myocamlbuild.ml are present).
+
+ This information is used to decide whether to enable recursive
+ traversal of subdirectories by default.
+*)
+val ocamlbuild_project_heuristic : unit -> bool
+
+val entry : bool Slurp.entry option ref
+val init : unit -> unit
diff --git a/ocamlbuild/param_tags.ml b/ocamlbuild/param_tags.ml
new file mode 100644
index 0000000000..4abf860ad0
--- /dev/null
+++ b/ocamlbuild/param_tags.ml
@@ -0,0 +1,63 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open My_std
+
+(* Original author: Romain Bardou *)
+
+module StringSet = Set.Make(String)
+
+(* tag name -> tag action (string -> unit) *)
+let declared_tags = Hashtbl.create 17
+
+let acknowledged_tags = ref []
+
+let only_once f =
+ let instances = ref StringSet.empty in
+ fun param ->
+ if StringSet.mem param !instances then ()
+ else begin
+ instances := StringSet.add param !instances;
+ f param
+ end
+
+let declare name action =
+ Hashtbl.add declared_tags name (only_once action)
+
+let parse source tag = Lexers.tag_gen source (lexbuf_of_string tag)
+
+let acknowledge source maybe_loc tag =
+ acknowledged_tags := (parse source tag, maybe_loc) :: !acknowledged_tags
+
+let really_acknowledge ?(quiet=false) ((name, param), maybe_loc) =
+ match param with
+ | None ->
+ if Hashtbl.mem declared_tags name && not quiet then
+ Log.eprintf "%aWarning: tag %S expects a parameter"
+ Loc.print_loc_option maybe_loc name
+ | Some param ->
+ let actions = List.rev (Hashtbl.find_all declared_tags name) in
+ if actions = [] && not quiet then
+ Log.eprintf "%aWarning: tag %S does not expect a parameter, \
+ but is used with parameter %S"
+ Loc.print_loc_option maybe_loc name param;
+ List.iter (fun f -> f param) actions
+
+let partial_init ?quiet source tags =
+ let parse_noloc tag = (parse source tag, None) in
+ Tags.iter (fun tag -> really_acknowledge ?quiet (parse_noloc tag)) tags
+
+let init () =
+ List.iter really_acknowledge (My_std.List.ordered_unique !acknowledged_tags)
+
+let make = Printf.sprintf "%s(%s)"
diff --git a/ocamlbuild/param_tags.mli b/ocamlbuild/param_tags.mli
new file mode 100644
index 0000000000..96609af25d
--- /dev/null
+++ b/ocamlbuild/param_tags.mli
@@ -0,0 +1,51 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Romain Bardou *)
+
+val declare: string -> (string -> unit) -> unit
+ (** Declare a parameterized tag.
+
+[declare "name" action]: [action "param"] will be executed (once) by [init]
+if a tag of the form [name(param)] is [acknowledge]d.
+
+A given tag may be declared several times with different actions. All actions
+will be executed, in the order they were declared. *)
+
+val acknowledge: Loc.source -> Loc.location option -> string -> unit
+ (** Acknowledge a tag.
+
+If the tag is of the form [X(Y)], and have been declared using [declare],
+then the actions given using [declare] will be executed with [Y] as parameter
+when [init] is executed. The action will only be called once per
+acknowledged parameter. *)
+
+val init: unit -> unit
+ (** Initialize parameterized tags.
+
+This will make effective all instantiations [foo(bar)] such that the
+parametrized tag [foo] has been [declare]d and [foo(bar)] has been
+[acknowledge]d after the last [init] call. *)
+
+val partial_init: ?quiet:bool -> Loc.source -> Tags.t -> unit
+(** Initialize a list of tags
+
+This will make effective the instances [foo(bar)] appearing
+in the given tag list, instead of those that have been
+[acknowledged] previously. This is for system use only. *)
+
+val make: Tags.elt -> string -> Tags.elt
+ (** Make a parameterized tag instance.
+
+Example: [make "package" "unix"]: return the tag ["package(unix)"] *)
diff --git a/ocamlbuild/pathname.ml b/ocamlbuild/pathname.ml
new file mode 100644
index 0000000000..779d461111
--- /dev/null
+++ b/ocamlbuild/pathname.ml
@@ -0,0 +1,160 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Format
+open Log
+
+type t = string
+
+include Filename
+
+let print_strings = List.print String.print
+
+let concat = filename_concat
+
+let compare (x:t) y = compare x y
+
+let print = pp_print_string
+
+let mk s = s
+
+let pwd = Sys.getcwd ()
+
+let add_extension ext x = x ^ "." ^ ext
+
+let check_extension x ext =
+ let lx = String.length x and lext = String.length ext in
+ lx > lext + 1 && x.[lx - lext - 1] = '.' && String.is_suffix x ext
+
+module Operators = struct
+ let ( / ) = concat
+ let ( -.- ) file ext = add_extension ext file
+end
+open Operators
+
+let equal x y = x = y
+
+let to_string x = x
+
+let is_link = Shell.is_link
+let readlink = Shell.readlink
+let is_directory x =
+ try (My_unix.stat x).My_unix.stat_file_kind = My_unix.FK_dir
+ with Sys_error _ -> false
+let readdir x = Outcome.good (sys_readdir x)
+
+let dir_seps = ['/';'\\'] (* FIXME add more *)
+let not_normal_form_re = Glob.parse "<**/{,.,..}/**>"
+
+let parent x = concat parent_dir_name x
+
+let split p =
+ let rec go p acc =
+ let dir = dirname p in
+ if dir = p then dir, acc
+ else go dir (basename p :: acc)
+ in go p []
+
+let join root paths =
+ let root = if root = current_dir_name then "" else root in
+ List.fold_left (/) root paths
+
+let _H1 = assert (current_dir_name = ".")
+let _H2 = assert (parent_dir_name = "..")
+
+(* Use H1, H2 *)
+let rec normalize_list = function
+ | [] -> []
+ | "." :: xs -> normalize_list xs
+ | ".." :: _ -> failwith "Pathname.normalize_list: .. is forbidden here"
+ | _ :: ".." :: xs -> normalize_list xs
+ | x :: xs -> x :: normalize_list xs
+
+let normalize x =
+ if Glob.eval not_normal_form_re x then
+ let root, paths = split x in
+ join root (normalize_list paths)
+ else x
+
+(* [is_prefix x y] is [x] a pathname prefix of [y] *)
+let is_prefix x y =
+ let lx = String.length x and ly = String.length y in
+ if lx = ly then x = (String.before y lx)
+ else if lx < ly then x = (String.before y lx) && List.mem y.[lx] dir_seps
+ else false
+
+let link_to_dir p dir = is_link p && is_prefix dir (readlink p)
+
+let remove_extension x =
+ try chop_extension x
+ with Invalid_argument _ -> x
+let get_extension x =
+ try
+ let pos = String.rindex x '.' in
+ String.after x (pos + 1)
+ with Not_found -> ""
+let update_extension ext x =
+ add_extension ext (chop_extension x)
+
+let chop_extensions x =
+ let dirname = dirname x and basename = basename x in
+ try
+ let pos = String.index basename '.' in
+ dirname / (String.before basename pos)
+ with Not_found -> invalid_arg "chop_extensions: no extensions"
+let remove_extensions x =
+ try chop_extensions x
+ with Invalid_argument _ -> x
+let get_extensions x =
+ let basename = basename x in
+ try
+ let pos = String.index basename '.' in
+ String.after basename (pos + 1)
+ with Not_found -> ""
+let update_extensions ext x =
+ add_extension ext (chop_extensions x)
+
+let exists = sys_file_exists
+
+let copy = Shell.cp
+let remove = Shell.rm
+let try_remove x = if exists x then Shell.rm x
+let read = read_file
+
+let with_input_file = with_input_file
+
+let with_output_file = with_output_file
+
+let print_path_list = List.print print
+
+let context_table = Hashtbl.create 107
+
+let rec include_dirs_of dir =
+ try Hashtbl.find context_table dir
+ with Not_found -> dir :: List.filter (fun dir' -> dir <> dir') !Options.include_dirs
+
+(*
+let include_dirs_of s =
+ let res = include_dirs_of s in
+ let () = dprintf 0 "include_dirs_of %S ->@ %a" s (List.print print) res
+ in res
+*)
+
+let define_context dir context =
+ let dir = if dir = "" then current_dir_name else dir in
+ Hashtbl.replace context_table dir& List.union context& include_dirs_of dir
+
+let same_contents x y = Digest.file x = Digest.file y
diff --git a/ocamlbuild/pathname.mli b/ocamlbuild/pathname.mli
new file mode 100644
index 0000000000..7934e4079a
--- /dev/null
+++ b/ocamlbuild/pathname.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+include Signatures.PATHNAME
+val link_to_dir : t -> t -> bool
+val normalize : t -> t
diff --git a/ocamlbuild/plugin.ml b/ocamlbuild/plugin.ml
new file mode 100644
index 0000000000..aad9468835
--- /dev/null
+++ b/ocamlbuild/plugin.ml
@@ -0,0 +1,263 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Format
+open Log
+open Pathname.Operators
+open Tags.Operators
+open Rule
+open Tools
+open Command
+;;
+
+
+let plugin = "myocamlbuild"
+let plugin_file = plugin^".ml"
+let plugin_config_file = plugin^"_config.ml"
+let plugin_config_file_interface = plugin^"_config.mli"
+let we_need_a_plugin () = !Options.plugin && sys_file_exists plugin_file
+let we_have_a_plugin () = sys_file_exists ((!Options.build_dir/plugin)^(!Options.exe))
+let we_have_a_config_file () = sys_file_exists plugin_config_file
+let we_have_a_config_file_interface () = sys_file_exists plugin_config_file_interface
+
+module Make(U:sig end) =
+ struct
+ let we_need_a_plugin = we_need_a_plugin ()
+ let we_have_a_plugin = we_have_a_plugin ()
+ let we_have_a_config_file = we_have_a_config_file ()
+ let we_have_a_config_file_interface = we_have_a_config_file_interface ()
+ let up_to_date_or_copy fn =
+ let fn' = !Options.build_dir/fn in
+ Pathname.exists fn &&
+ begin
+ Pathname.exists fn' && Pathname.same_contents fn fn' ||
+ begin
+ Shell.cp fn fn';
+ false
+ end
+ end
+
+ let rebuild_plugin_if_needed () =
+ let a = up_to_date_or_copy plugin_file in
+ let b = (not we_have_a_config_file) || up_to_date_or_copy plugin_config_file in
+ let c = (not we_have_a_config_file_interface) || up_to_date_or_copy plugin_config_file_interface in
+ if a && b && c && we_have_a_plugin then
+ () (* Up to date *)
+ (* FIXME: remove ocamlbuild_config.ml in _build/ if removed in parent *)
+ else begin
+ if !Options.native_plugin
+ && not (sys_file_exists ((!Ocamlbuild_where.libdir)/"ocamlbuildlib.cmxa")) then
+ begin
+ Options.native_plugin := false;
+ eprintf "Warning: Won't be able to compile a native plugin"
+ end;
+ let plugin_config =
+ if we_have_a_config_file then
+ if we_have_a_config_file_interface then
+ S[P plugin_config_file_interface; P plugin_config_file]
+ else P plugin_config_file
+ else N in
+
+ let cma, cmo, compiler, byte_or_native =
+ if !Options.native_plugin then
+ "cmxa", "cmx", !Options.ocamlopt, "native"
+ else
+ "cma", "cmo", !Options.ocamlc, "byte"
+ in
+
+
+ let (unix_spec, ocamlbuild_lib_spec, ocamlbuild_module_spec) =
+
+ let use_light_mode =
+ not !Options.native_plugin && !*My_unix.is_degraded in
+ let use_ocamlfind_pkgs =
+ !Options.use_ocamlfind && !Options.plugin_tags <> [] in
+ (* The plugin has the following dependencies that must be
+ included during compilation:
+
+ - unix.cmxa, if it is available
+ - ocamlbuildlib.cm{a,xa}, the library part of ocamlbuild
+ - ocamlbuild.cm{o,x}, the module that performs the
+ initialization work of the ocamlbuild executable, using
+ modules of ocamlbuildlib.cmxa
+
+ We pass all this stuff to the compilation command for the
+ plugin, with two independent important details to handle:
+
+ (1) ocamlbuild is designed to still work in environments
+ where Unix is not available for some reason; in this
+ case, we should not link unix, and use the
+ "ocamlbuildlight.cmo" initialization module, which runs
+ a "light" version of ocamlbuild without unix. There is
+ also an ocamlbuildlightlib.cma archive to be used in that
+ case.
+
+ The boolean variable [use_light_mode] tells us whether we
+ are in this unix-deprived scenario.
+
+ (2) there are risks of compilation error due to
+ double-linking of native modules when the user passes its
+ own tags to the plugin compilation process (as was added
+ to support modular construction of
+ ocamlbuild plugins). Indeed, if we hard-code linking to
+ unix.cmxa in all cases, and the user
+ enables -use-ocamlfind and
+ passes -plugin-tag "package(unix)" (or package(foo) for
+ any foo which depends on unix), the command-line finally
+ executed will be
+
+ ocamlfind ocamlopt unix.cmxa -package unix myocamlbuild.ml
+
+ which fails with a compilation error due to doubly-passed
+ native modules.
+
+ To sanest way to solve this problem at the ocamlbuild level
+ is to pass "-package unix" instead of unix.cmxa when we
+ detect that such a situation may happen. OCamlfind will see
+ that the same package is demanded twice, and only request
+ it once to the compiler. Similarly, we use "-package
+ ocamlbuild" instead of linking ocamlbuildlib.cmxa[1].
+
+ We switch to this behavior when two conditions, embodied in
+ the boolean variable [use_ocamlfind_pkgs], are met:
+ (a) use-ocamlfind is enabled
+ (b) the user is passing some plugin tags
+
+ Condition (a) is overly conservative as the double-linking
+ issue may also happen in non-ocamlfind situations, such as
+ "-plugin-tags use_unix" -- but it's unclear how one would
+ avoid the issue in that case, except by documenting that
+ people should not do that, or getting rid of the
+ hard-linking logic entirely, with the corresponding risks
+ of regression.
+
+ Condition (b) should not be necessary (we expect using
+ ocamlfind packages to work whenever ocamlfind
+ is available), but allows the behavior in absence
+ of -plugin-tags to be completely unchanged, to reassure us
+ about potential regressions introduced by this option.
+
+ [1]: we may wonder whether to use "-package ocamlbuildlight"
+ in unix-deprived situations, but currently ocamlfind
+ doesn't know about the ocamlbuildlight library. As
+ a compromise we always use "-package ocamlbuild" when
+ use_ocamlfind_pkgs is set. An ocamlfind and -plugin-tags
+ user in unix-deprived environment may want to mutate the
+ META of ocamlbuild to point to ocamlbuildlightlib instead
+ of ocamlbuildlib.
+ *)
+
+ let unix_lib =
+ if use_ocamlfind_pkgs then `Package "unix"
+ else if use_light_mode then `Nothing
+ else `Lib "unix" in
+
+ let ocamlbuild_lib =
+ if use_ocamlfind_pkgs then `Package "ocamlbuild"
+ else if use_light_mode then `Local_lib "ocamlbuildlightlib"
+ else `Local_lib "ocamlbuildlib" in
+
+ let ocamlbuild_module =
+ if use_light_mode then `Local_mod "ocamlbuildlight"
+ else `Local_mod "ocamlbuild" in
+
+ let dir = !Ocamlbuild_where.libdir in
+ let dir = if Pathname.is_implicit dir then Pathname.pwd/dir else dir in
+
+ let in_dir file =
+ let path = dir/file in
+ if not (sys_file_exists path) then failwith
+ (sprintf "Cannot find %S in ocamlbuild -where directory" file);
+ path in
+
+ let spec = function
+ | `Nothing -> N
+ | `Package pkg -> S[A "-package"; A pkg]
+ | `Lib lib -> P (lib -.- cma)
+ | `Local_lib llib -> S [A "-I"; A dir; P (in_dir (llib -.- cma))]
+ | `Local_mod lmod -> P (in_dir (lmod -.- cmo)) in
+
+ (spec unix_lib, spec ocamlbuild_lib, spec ocamlbuild_module)
+ in
+
+ let plugin_tags =
+ Tags.of_list !Options.plugin_tags
+ ++ "ocaml" ++ "program" ++ "link" ++ byte_or_native in
+
+ (* The plugin is compiled before [Param_tags.init()] is called
+ globally, which means that parametrized tags have not been
+ made effective yet. The [partial_init] calls below initializes
+ precisely those that will be used during the compilation of
+ the plugin, and no more.
+ *)
+ Param_tags.partial_init Const.Source.plugin_tag plugin_tags;
+
+ let cmd =
+ (* The argument order is important: we carefully put the
+ plugin source files before the ocamlbuild.cm{o,x} module
+ doing the main initialization, so that user global
+ side-effects (setting options, installing flags..) are
+ performed brefore ocamlbuild's main routine. This is
+ a fragile thing to rely upon and we insist that our users
+ use the more robust [dispatch] registration instead, but
+ we still aren't going to break that now.
+
+ For the same reason we place the user plugin-tags after
+ the plugin libraries (in case a tag would, say, inject
+ a .cmo that also relies on them), but before the main
+ plugin source file and ocamlbuild's initialization. *)
+ Cmd(S[compiler;
+ unix_spec; ocamlbuild_lib_spec;
+ T plugin_tags;
+ plugin_config; P plugin_file;
+ ocamlbuild_module_spec;
+ A"-o"; Px (plugin^(!Options.exe))])
+ in
+ Shell.chdir !Options.build_dir;
+ Shell.rm_f (plugin^(!Options.exe));
+ Command.execute cmd;
+ if !Options.just_plugin then begin
+ Log.finish ();
+ raise Exit_OK;
+ end;
+ end
+
+ let execute_plugin_if_needed () =
+ if we_need_a_plugin then
+ begin
+ rebuild_plugin_if_needed ();
+ Shell.chdir Pathname.pwd;
+ let runner = if !Options.native_plugin then N else !Options.ocamlrun in
+ let argv = List.tl (Array.to_list Sys.argv) in
+ let passed_argv = List.filter (fun s -> s <> "-plugin-option") argv in
+ let spec = S[runner; P(!Options.build_dir/plugin^(!Options.exe));
+ A"-no-plugin"; atomize passed_argv] in
+ Log.finish ();
+ let rc = sys_command (Command.string_of_command_spec spec) in
+ raise (Exit_silently_with_code rc);
+ end
+ else if not (sys_file_exists plugin_file) && !Options.plugin_tags <> [] then
+ eprintf "Warning: option -plugin-tag(s) has no effect \
+ in absence of plugin file %S" plugin_file
+ else
+ ()
+ end
+;;
+
+let execute_plugin_if_needed () =
+ let module P = Make(struct end) in
+ P.execute_plugin_if_needed ()
+;;
diff --git a/ocamlbuild/plugin.mli b/ocamlbuild/plugin.mli
new file mode 100644
index 0000000000..a3937a32f4
--- /dev/null
+++ b/ocamlbuild/plugin.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Plugin *)
+
+val execute_plugin_if_needed : unit -> unit
+val we_need_a_plugin : unit -> bool
diff --git a/ocamlbuild/ppcache.ml b/ocamlbuild/ppcache.ml
new file mode 100644
index 0000000000..be3f5c9d1e
--- /dev/null
+++ b/ocamlbuild/ppcache.ml
@@ -0,0 +1,92 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Command
+open Pathname.Operators
+let () = Log.level := -1000
+
+let usage () =
+ Format.eprintf "Usage: %s <preprocess-command> <preprocess-args>@." Sys.argv.(0);
+ exit 4
+
+let () = if Array.length Sys.argv < 2 then usage ()
+
+let args = List.tl (Array.to_list Sys.argv)
+
+let buf = Buffer.create 2048
+
+let digest_file file =
+ Buffer.add_string buf (Digest.file file)
+let digest_string string =
+ Buffer.add_string buf (Digest.string string)
+
+let search_in_path x =
+ if Sys.file_exists x then x else
+ try search_in_path x
+ with Not_found -> (Format.eprintf "Command not found %s@." x; exit 3)
+
+let cmd =
+ match args with
+ | ocamlrun :: x :: _ when String.contains_string ocamlrun 0 "ocamlrun" <> None ->
+ digest_file (search_in_path ocamlrun); x
+ | x :: _ -> x
+ | _ -> usage ()
+
+let output = ref ""
+
+let () = digest_file (search_in_path cmd)
+
+let rec loop =
+ function
+ | [] -> Digest.string (Buffer.contents buf)
+ | ("-impl"|"-intf") :: x :: xs ->
+ digest_string x; digest_file x; loop xs
+ | "-o" :: x :: xs ->
+ output := x; loop xs
+ | x :: xs ->
+ let ext = Pathname.get_extension x in
+ digest_string x;
+ (match ext with
+ | "cmo" | "cma" | "ml" | "mli" -> digest_file x
+ | _ -> ());
+ loop xs
+
+let digest = loop args;;
+
+let cache_dir = "/tmp/ppcache";; (* FIXME *)
+
+let () = Shell.mkdir_p cache_dir;;
+
+let path = cache_dir/(Digest.to_hex digest);;
+
+let cat path = with_input_file ~bin:true path (fun ic -> copy_chan ic stdout);;
+
+if sys_file_exists path then
+ if !output = "" then
+ cat path
+ else
+ Shell.cp path !output
+else
+ let cmd = atomize args in
+ if !output = "" then begin
+ let tmp = path^".tmp" in
+ Command.execute (Cmd(S[cmd; Sh ">"; A tmp]));
+ Shell.mv tmp path;
+ cat path
+ end else begin
+ Command.execute (Cmd cmd);
+ Shell.cp !output path
+ end
diff --git a/ocamlbuild/ppcache.mli b/ocamlbuild/ppcache.mli
new file mode 100644
index 0000000000..cfb879f549
--- /dev/null
+++ b/ocamlbuild/ppcache.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* nothing to export *)
diff --git a/ocamlbuild/report.ml b/ocamlbuild/report.ml
new file mode 100644
index 0000000000..c51ea71dd5
--- /dev/null
+++ b/ocamlbuild/report.ml
@@ -0,0 +1,63 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Report *)
+
+open My_std
+open Log
+open Format
+open Solver
+
+let sources_glob = Glob.parse "<*.ml> or <*.mli> or <*.c> or <*.h>";;
+
+let rec analyze f bt =
+ match bt with
+ | Leaf r ->
+ fprintf f "Ocamlbuild knows of no rules that apply to a target named %a. \
+ This can happen if you ask Ocamlbuild to build a target with the \
+ wrong extension (e.g. .opt instead of .native) or if the source \
+ files live in directories that have not been specified as \
+ include directories."
+ Resource.print r;
+ false
+ | Depth(r, bt) ->
+ if Glob.eval sources_glob r then
+ begin
+ fprintf f "Ocamlbuild cannot find or build %a. A file with such a name would \
+ usually be a source file. I suspect you have given a wrong target \
+ name to Ocamlbuild."
+ Resource.print r;
+ false
+ end
+ else
+ analyze f bt
+ | Choice bl -> List.for_all (analyze f) bl
+ | Target(_, bt) -> analyze f bt
+
+let rec print_backtrace f =
+ function
+ | Target (name, backtrace) ->
+ fprintf f "@\n- @[<2>Failed to build the target %s%a@]" name print_backtrace backtrace
+ | Leaf r ->
+ fprintf f "@\n- @[<2>Building %a@]" Resource.print r
+ | Depth (r, backtrace) ->
+ fprintf f "@\n- @[<v2>Building %a:%a@]" Resource.print r print_backtrace backtrace
+ | Choice [backtrace] -> print_backtrace f backtrace
+ | Choice backtraces ->
+ fprintf f "@\n- @[<v2>Failed to build all of these:";
+ List.iter (print_backtrace f) backtraces;
+ fprintf f "@]"
+
+let print_backtrace_analyze f bt = ignore (analyze f bt)
diff --git a/ocamlbuild/report.mli b/ocamlbuild/report.mli
new file mode 100644
index 0000000000..e82538f9a5
--- /dev/null
+++ b/ocamlbuild/report.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Report *)
+
+val print_backtrace_analyze : Format.formatter -> Solver.backtrace -> unit
+
+val print_backtrace : Format.formatter -> Solver.backtrace -> unit
diff --git a/ocamlbuild/resource.ml b/ocamlbuild/resource.ml
new file mode 100644
index 0000000000..2a9cdf36d6
--- /dev/null
+++ b/ocamlbuild/resource.ml
@@ -0,0 +1,403 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Format
+open Log
+open Pathname.Operators
+
+
+type t = Pathname.t
+module Resources = Set.Make(Pathname)
+
+let print = Pathname.print
+
+let equal = (=)
+let compare = compare
+
+let in_source_dir p =
+ if Pathname.is_implicit p then Pathname.pwd/p else invalid_arg (Printf.sprintf "in_source_dir: %S" p)
+
+let in_build_dir p =
+ if Pathname.is_relative p then p
+ else invalid_arg (Printf.sprintf "in_build_dir: %S" p)
+
+let clean_up_links entry =
+ if not !Options.make_links then entry else
+ Slurp.filter begin fun path name _ ->
+ let pathname = in_source_dir (path/name) in
+ if Pathname.link_to_dir pathname !Options.build_dir then
+ let z = Pathname.readlink pathname in
+ (* Here is one exception where one can use Sys.file_exists directly *)
+ (if not (Sys.file_exists z) then
+ Shell.rm pathname; false)
+ else true
+ end entry
+
+let clean_up_link_to_build () =
+ Options.entry := Some(clean_up_links (the !Options.entry))
+
+let source_dir_path_set_without_links_to_build =
+ lazy begin
+ clean_up_link_to_build ();
+ Slurp.fold (fun path name _ -> StringSet.add (path/name))
+ (the !Options.entry) StringSet.empty
+ end
+
+let clean_links () =
+ if !*My_unix.is_degraded then
+ ()
+ else
+ ignore (clean_up_link_to_build ())
+
+let exists_in_source_dir p =
+ if !*My_unix.is_degraded then sys_file_exists (in_source_dir p)
+ else StringSet.mem p !*source_dir_path_set_without_links_to_build
+
+let clean p = Shell.rm_f p
+
+module Cache = struct
+
+ let clean () = Shell.chdir Pathname.pwd; Shell.rm_rf !Options.build_dir
+
+ type knowledge =
+ | Yes
+ | No
+ | Unknown
+
+ type suspension = (Command.t * (unit -> unit))
+
+ type build_status =
+ | Bbuilt
+ | Bcannot_be_built
+ | Bnot_built_yet
+ | Bsuspension of suspension
+
+ type cache_entry =
+ { mutable built : build_status;
+ mutable changed : knowledge;
+ mutable dependencies : Resources.t }
+
+ let empty () =
+ { built = Bnot_built_yet;
+ changed = Unknown;
+ dependencies = Resources.empty }
+
+ let print_knowledge f =
+ function
+ | Yes -> pp_print_string f "Yes"
+ | No -> pp_print_string f "No"
+ | Unknown -> pp_print_string f "Unknown"
+
+ let print_build_status f =
+ function
+ | Bbuilt -> pp_print_string f "Bbuilt"
+ | Bnot_built_yet -> pp_print_string f "Bnot_built_yet"
+ | Bcannot_be_built -> pp_print_string f "Bcannot_be_built"
+ | Bsuspension(cmd, _) ->
+ fprintf f "@[<2>Bsuspension(%a,@ (<fun> : unit -> unit))@]" Command.print cmd
+
+ let print_cache_entry f e =
+ fprintf f "@[<2>{ @[<2>built =@ %a@];@ @[<2>changed =@ %a@];@ @[<2>dependencies =@ %a@]@ }@]"
+ print_build_status e.built print_knowledge e.changed Resources.print e.dependencies
+
+ module Hashtbl = Hashtbl.Make(struct type t = Pathname.t let hash = Hashtbl.hash let equal (x:string) y = x = y end)
+
+ let cache = Hashtbl.create 103
+
+ let get r =
+ try Hashtbl.find cache r
+ with Not_found ->
+ let cache_entry = empty () in
+ Hashtbl.add cache r cache_entry; cache_entry
+
+ let fold_cache f x = Hashtbl.fold f cache x
+
+ let print_cache f () =
+ fprintf f "@[<hv0>@[<hv2>{:";
+ fold_cache begin fun k v () ->
+ fprintf f "@ @[<2>%a =>@ %a@];" print k print_cache_entry v
+ end ();
+ fprintf f "@]:}@]"
+
+ let print_graph f () =
+ fprintf f "@[<hv0>@[<hv2>{:";
+ fold_cache begin fun k v () ->
+ if not (Resources.is_empty v.dependencies) then
+ fprintf f "@ @[<2>%a =>@ %a@];" print k Resources.print v.dependencies
+ end ();
+ fprintf f "@]@ :}@]"
+
+ let resource_changed r =
+ dprintf 10 "resource_changed:@ %a" print r;
+ (get r).changed <- Yes
+
+ let external_is_up_to_date absolute_path =
+ let key = "Resource: " ^ absolute_path in
+ let digest = Digest.file absolute_path in
+ let is_up_to_date =
+ try
+ let digest' = Digest_cache.get key in
+ digest = digest'
+ with Not_found ->
+ false
+ in
+ is_up_to_date || (Digest_cache.put key digest; false)
+
+ let source_is_up_to_date r_in_source_dir r_in_build_dir =
+ let key = "Resource: " ^ r_in_source_dir in
+ let digest = Digest.file r_in_source_dir in
+ let r_is_up_to_date =
+ Pathname.exists r_in_build_dir &&
+ try
+ let digest' = Digest_cache.get key in
+ digest = digest'
+ with Not_found ->
+ false
+ in
+ r_is_up_to_date || (Digest_cache.put key digest; false)
+
+ let prod_is_up_to_date p =
+ let x = in_build_dir p in
+ not (exists_in_source_dir p) || Pathname.exists x && Pathname.same_contents x (in_source_dir p)
+
+ let rec resource_has_changed r =
+ let cache_entry = get r in
+ match cache_entry.changed with
+ | Yes -> true
+ | No -> false
+ | Unknown ->
+ let res =
+ match cache_entry.built with
+ | Bbuilt -> false
+ | Bsuspension _ -> assert false
+ | Bcannot_be_built -> false
+ | Bnot_built_yet -> not (prod_is_up_to_date r) in
+ let () = cache_entry.changed <- if res then Yes else No in res
+
+ let resource_state r = (get r).built
+
+ let resource_built r = (get r).built <- Bbuilt
+
+ let resource_failed r = (get r).built <- Bcannot_be_built
+
+ let import_in_build_dir r =
+ let cache_entry = get r in
+ let r_in_build_dir = in_build_dir r in
+ let r_in_source_dir = in_source_dir r in
+ if source_is_up_to_date r_in_source_dir r_in_build_dir then begin
+ dprintf 5 "%a exists and up to date" print r;
+ end else begin
+ dprintf 5 "%a exists in source dir -> import it" print r;
+ Shell.mkdir_p (Pathname.dirname r);
+ Pathname.copy r_in_source_dir r_in_build_dir;
+ cache_entry.changed <- Yes;
+ end;
+ cache_entry.built <- Bbuilt
+
+ let suspend_resource r cmd kont prods =
+ let cache_entry = get r in
+ match cache_entry.built with
+ | Bsuspension _ -> ()
+ | Bbuilt -> ()
+ | Bcannot_be_built -> assert false
+ | Bnot_built_yet ->
+ let kont = begin fun () ->
+ kont ();
+ List.iter begin fun prod ->
+ (get prod).built <- Bbuilt
+ end prods
+ end in cache_entry.built <- Bsuspension(cmd, kont)
+
+ let resume_suspension (cmd, kont) =
+ Command.execute cmd;
+ kont ()
+
+ let resume_resource r =
+ let cache_entry = get r in
+ match cache_entry.built with
+ | Bsuspension(s) -> resume_suspension s
+ | Bbuilt -> ()
+ | Bcannot_be_built -> ()
+ | Bnot_built_yet -> ()
+
+ let get_optional_resource_suspension r =
+ match (get r).built with
+ | Bsuspension cmd_kont -> Some cmd_kont
+ | Bbuilt | Bcannot_be_built | Bnot_built_yet -> None
+
+ let clear_resource_failed r = (get r).built <- Bnot_built_yet
+
+ let dependencies r = (get r).dependencies
+
+ let fold_dependencies f =
+ fold_cache (fun k v -> Resources.fold (f k) v.dependencies)
+
+ let add_dependency r s =
+ let cache_entry = get r in
+ cache_entry.dependencies <- Resources.add s cache_entry.dependencies
+
+ let print_dependencies = print_graph
+
+end
+
+let digest p =
+ let f = Pathname.to_string (in_build_dir p) in
+ let buf = Buffer.create 1024 in
+ Buffer.add_string buf f;
+ (if sys_file_exists f then Buffer.add_string buf (Digest.file f));
+ Digest.string (Buffer.contents buf)
+
+let exists_in_build_dir p = Pathname.exists (in_build_dir p)
+
+(*
+type env = string
+
+let split_percent s =
+ try
+ let pos = String.index s '%' in
+ Some (String.before s pos, String.after s (pos + 1))
+ with Not_found -> None
+
+let extract prefix suffix s =
+ let lprefix = String.length prefix in
+ let lsuffix = String.length suffix in
+ let ls = String.length s in
+ if lprefix + lsuffix > ls then None else
+ let s' = String.sub s lprefix (ls - lsuffix - lprefix) in
+ if equal (prefix ^ s' ^ suffix) s then Some s' else None
+
+let matchit r1 r2 =
+ match split_percent r1 with
+ | Some (x, y) -> extract x y r2
+ | _ -> if equal r1 r2 then Some "" else None
+
+let rec subst percent r =
+ match split_percent r with
+ | Some (x, y) -> x ^ percent ^ y
+ | _ -> r
+
+let print_env = pp_print_string
+*)
+
+(* Should normalize *)
+let import x = Pathname.normalize x
+
+module MetaPath : sig
+
+ type t
+ type env
+
+ val mk : (bool * string) -> t
+ val matchit : t -> string -> env option
+ val subst : env -> t -> string
+ val print_env : Format.formatter -> env -> unit
+
+end = struct
+ open Glob_ast
+
+ type atoms = A of string | V of string * Glob.globber
+ type t = atoms list
+ type env = (string * string) list
+
+ exception No_solution
+
+ let mk (pattern_allowed, s) = List.map begin function
+ | `Var(var_name, globber) -> V(var_name, globber)
+ | `Word s -> A s
+ end (Lexers.path_scheme pattern_allowed
+ Const.Source.target_pattern (lexbuf_of_string s))
+
+ let mk = memo mk
+
+ let match_prefix s pos prefix =
+ match String.contains_string s pos prefix with
+ | Some(pos') -> if pos = pos' then pos' + String.length prefix else raise No_solution
+ | None -> raise No_solution
+
+ let matchit p s =
+ let sl = String.length s in
+ let rec loop xs pos acc delta =
+ match xs with
+ | [] -> if pos = sl then acc else raise No_solution
+ | A prefix :: xs -> loop xs (match_prefix s pos prefix) acc 0
+ | V(var, patt) :: A s2 :: xs' ->
+ begin match String.contains_string s (pos + delta) s2 with
+ | Some(pos') ->
+ let matched = String.sub s pos (pos' - pos) in
+ if Glob.eval patt matched
+ then
+ try loop xs' (pos' + String.length s2) ((var, matched) :: acc) 0
+ with No_solution -> loop xs pos acc (pos' - pos + 1)
+ else loop xs pos acc (pos' - pos + 1)
+ | None -> raise No_solution
+ end
+ | [V(var, patt)] ->
+ let matched = String.sub s pos (sl - pos) in
+ if Glob.eval patt matched then (var, matched) :: acc else raise No_solution
+ | V _ :: _ -> assert false
+ in
+ try Some (loop p 0 [] 0)
+ with No_solution -> None
+
+ let pp_opt pp_elt f =
+ function
+ | None -> pp_print_string f "None"
+ | Some x -> Format.fprintf f "Some(%a)" pp_elt x
+
+ let print_env f env =
+ List.iter begin fun (k, v) ->
+ if k = "" then Format.fprintf f "%%=%s " v
+ else Format.fprintf f "%%(%s)=%s " k v
+ end env
+
+ (* let matchit p s =
+ let res = matchit p s in
+ Format.eprintf "matchit %S %S = %a@." p s (pp_opt print_env) res;
+ res
+
+ let _ = begin
+ assert (matchit "%(path)lib%(libname).a" "libfoo.a" <> None);
+ assert (matchit "%(path)lib%(libname).a" "path/libfoo.a" <> None);
+ assert (matchit "libfoo.a" "libfoo.a" <> None);
+ assert (matchit "lib%(libname).a" "libfoo.a" <> None);
+ assert (matchit "%(path)libfoo.a" "path/libfoo.a" <> None);
+ assert (matchit "foo%" "foobar" <> None);
+ exit 42
+ end;; *)
+
+ let subst env s =
+ String.concat "" begin
+ List.map begin fun x ->
+ match x with
+ | A atom -> atom
+ | V(var, _) -> try List.assoc var env with Not_found -> (* unbound variable *) ""
+ end s
+ end
+end
+
+type env = MetaPath.env
+type resource_pattern = (Pathname.t * MetaPath.t)
+
+let print_pattern f (x, _) = Pathname.print f x
+
+let import_pattern x = x, MetaPath.mk (true, x)
+let matchit (_, p) x = MetaPath.matchit p x
+
+let subst env s = MetaPath.subst env (MetaPath.mk (false, s))
+let subst_any env s = MetaPath.subst env (MetaPath.mk (true, s))
+let subst_pattern env (_, p) = MetaPath.subst env p
+
+let print_env = MetaPath.print_env
diff --git a/ocamlbuild/resource.mli b/ocamlbuild/resource.mli
new file mode 100644
index 0000000000..9ba9dadfcd
--- /dev/null
+++ b/ocamlbuild/resource.mli
@@ -0,0 +1,78 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+
+open Pathname
+type resource_pattern
+type env
+
+type t = Pathname.t
+module Resources : Set.S with type elt = t
+
+module Cache :
+ sig
+ type cache_entry
+ type suspension
+
+ type build_status =
+ | Bbuilt
+ | Bcannot_be_built
+ | Bnot_built_yet
+ | Bsuspension of suspension
+
+ val clean : unit -> unit
+ val resource_state : t -> build_status
+ val resource_changed : t -> unit
+ val resource_has_changed : t -> bool
+ val resource_built : t -> unit
+ val resource_failed : t -> unit
+ val import_in_build_dir : t -> unit
+ val suspend_resource : t -> Command.t -> (unit -> unit) -> t list -> unit
+ val resume_resource : t -> unit
+ val resume_suspension : suspension -> unit
+ val get_optional_resource_suspension : t -> (Command.t * (unit -> unit)) option
+ val clear_resource_failed : t -> unit
+ val add_dependency : t -> t -> unit
+ val fold_dependencies : (string -> string -> 'a -> 'a) -> 'a -> 'a
+ val external_is_up_to_date : t -> bool
+
+ (* These are not currently used by others modules. *)
+ val dependencies : t -> Resources.t
+ val print_cache : Format.formatter -> unit -> unit
+ val print_dependencies : Format.formatter -> unit -> unit
+ end
+
+val digest : t -> string
+val exists_in_source_dir : t -> bool
+val exists_in_build_dir : t -> bool
+val in_build_dir : t -> t
+val in_source_dir : t -> t
+
+val clean_up_links : bool Slurp.entry -> bool Slurp.entry
+
+val compare : t -> t -> int
+val print : Format.formatter -> t -> unit
+val print_pattern : Format.formatter -> resource_pattern -> unit
+val clean : t -> unit
+val import : string -> t
+val import_pattern : string -> resource_pattern
+
+val matchit : resource_pattern -> t -> env option
+val subst : env -> t -> t
+val subst_any : env -> t -> t
+val subst_pattern : env -> resource_pattern -> t
+(* val is_up_to_date : t -> bool *)
+val print_env : Format.formatter -> env -> unit
diff --git a/ocamlbuild/rule.ml b/ocamlbuild/rule.ml
new file mode 100644
index 0000000000..d059ef3640
--- /dev/null
+++ b/ocamlbuild/rule.ml
@@ -0,0 +1,339 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Format
+open Log
+open Outcome
+module Resources = Resource.Resources
+
+exception Exit_rule_error of string
+exception Failed
+
+type env = Pathname.t -> Pathname.t
+type builder = Pathname.t list list -> (Pathname.t, exn) Outcome.t list
+type action = env -> builder -> Command.t
+
+type digest_command = { digest : string; command : Command.t }
+
+type 'a gen_rule =
+ { name : string;
+ deps : Pathname.t list; (* These pathnames must be normalized *)
+ prods : 'a list; (* Note that prods also contains stamp *)
+ stamp : 'a option;
+ doc : string option;
+ code : env -> builder -> digest_command }
+
+type rule = Pathname.t gen_rule
+type rule_scheme = Resource.resource_pattern gen_rule
+
+let name_of_rule r = r.name
+let deps_of_rule r = r.deps
+let prods_of_rule r = r.prods
+let stamp_of_rule r = r.stamp
+let doc_of_rule r = r.doc
+
+type 'a rule_printer = (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a gen_rule -> unit
+
+let compare _ _ = assert false
+
+let print_rule_name f r = pp_print_string f r.name
+
+let print_resource_list = List.print Resource.print
+
+let print_rule_contents ppelt f r =
+ fprintf f "@[<v2>{@ @[<2>name =@ %S@];@ @[<2>deps =@ %a@];@ @[<2>prods = %a@];@ @[<2>code = <fun>@];@ @[<hov 2> doc = %s@]@]@ }"
+ r.name print_resource_list r.deps (List.print ppelt)
+ r.prods
+ (match r.doc with
+ | None -> "None"
+ | Some doc -> sprintf "Some %S" doc)
+
+let pretty_print ppelt f r =
+ fprintf f "@[<hv2>rule %S@ ~deps:%a@ ~prods:%a@ "
+ r.name print_resource_list r.deps (List.print ppelt) r.prods;
+ begin match r.doc with
+ | None -> ()
+ | Some doc -> fprintf f "~doc:\"@[<hov>%a@]\"@ " pp_print_text doc
+ end;
+ fprintf f "<fun>@]"
+
+let print = print_rule_name
+
+let subst env rule =
+ let subst_resources = List.map (Resource.subst env) in
+ let subst_resource_patterns = List.map (Resource.subst_pattern env) in
+ let finder next_finder p = next_finder (Resource.subst_any env p) in
+ let stamp = match rule.stamp with None -> None | Some x -> Some (Resource.subst_pattern env x) in
+ let prods = subst_resource_patterns rule.prods in
+ { name = sbprintf "%s (%a)" rule.name Resource.print_env env;
+ prods = prods;
+ deps =
+ (* The substition should preserve normalization of pathnames *)
+ subst_resources rule.deps;
+ stamp = stamp;
+ doc = rule.doc;
+ code = (fun env -> rule.code (finder env)) }
+
+exception Can_produce of rule
+
+let can_produce target rule =
+ try
+ List.iter begin fun resource ->
+ match Resource.matchit resource target with
+ | Some env -> raise (Can_produce (subst env rule))
+ | None -> ()
+ end rule.prods; None
+ with Can_produce r -> Some r
+
+let digest_prods r =
+ List.fold_right begin fun p acc ->
+ let f = Pathname.to_string (Resource.in_build_dir p) in
+ if sys_file_exists f then (f, Digest.file f) :: acc else acc
+ end r.prods []
+
+let digest_deps r dyndeps =
+ let buf = Buffer.create 1024 in
+ let add_resource r = Buffer.add_string buf (Digest.to_hex (Resource.digest r)) in
+ Buffer.add_string buf "deps:";
+ List.iter add_resource r.deps;
+ Buffer.add_string buf "dyndeps:";
+ Resources.iter add_resource dyndeps;
+ Digest.to_hex (Digest.string (Buffer.contents buf))
+
+let digest_rule r dyndeps action =
+ let buf = Buffer.create 1024 in
+ Buffer.add_string buf action.digest;
+ let add_resource r = Buffer.add_string buf (Resource.digest r) in
+ Buffer.add_string buf "prods:";
+ List.iter add_resource r.prods;
+ Buffer.add_string buf "deps:";
+ List.iter add_resource r.deps;
+ Buffer.add_string buf "dyndeps:";
+ Resources.iter add_resource dyndeps;
+ Digest.string (Buffer.contents buf)
+
+let cached_digest r =
+ try Some (Digest_cache.get ("Rule: " ^ r.name))
+ with Not_found -> None
+
+let store_digest r digest = Digest_cache.put ("Rule: " ^ r.name) digest
+
+let print_digest f x = pp_print_string f (Digest.to_hex x)
+
+let exists2 find p rs =
+ try Some (find p rs) with Not_found -> None
+
+let build_deps_of_tags builder tags =
+ match Command.deps_of_tags tags with
+ | [] -> []
+ | deps -> List.map Outcome.good (builder (List.map (fun x -> [x]) deps))
+
+let build_deps_of_tags_on_cmd builder =
+ Command.iter_tags begin fun tags ->
+ match Command.deps_of_tags tags with
+ | [] -> ()
+ | deps -> List.iter ignore_good (builder (List.map (fun x -> [x]) deps))
+ end
+
+let call builder r =
+ let dyndeps = ref Resources.empty in
+ let builder rs =
+ let results = builder rs in
+ List.map begin fun res ->
+ match res with
+ | Good res' ->
+ let () = dprintf 10 "new dyndep for %S(%a): %S" r.name print_resource_list r.prods res' in
+ dyndeps := Resources.add res' !dyndeps;
+ List.iter (fun x -> Resource.Cache.add_dependency x res') r.prods;
+ res
+ | Bad _ -> res
+ end results in
+ let () = dprintf 5 "start rule %a" print r in
+ let action = r.code (fun x -> x) builder in
+ build_deps_of_tags_on_cmd builder action.command;
+ let dyndeps = !dyndeps in
+ let () = dprintf 10 "dyndeps: %a" Resources.print dyndeps in
+ let (reason, cached) =
+ match exists2 List.find (fun r -> not (Resource.exists_in_build_dir r)) r.prods with
+ | Some r -> (`cache_miss_missing_prod r, false)
+ | _ ->
+ begin match exists2 List.find Resource.Cache.resource_has_changed r.deps with
+ | Some r -> (`cache_miss_changed_dep r, false)
+ | _ ->
+ begin match exists2 Resources.find_elt Resource.Cache.resource_has_changed dyndeps with
+ | Some r -> (`cache_miss_changed_dyn_dep r, false)
+ | _ ->
+ begin match cached_digest r with
+ | None -> (`cache_miss_no_digest, false)
+ | Some d ->
+ let rule_digest = digest_rule r dyndeps action in
+ if d = rule_digest then (`cache_hit, true)
+ else (`cache_miss_digest_changed(d, rule_digest), false)
+ end
+ end
+ end
+ in
+ let explain_reason l =
+ raw_dprintf (l+1) "mid rule %a: " print r;
+ match reason with
+ | `cache_miss_missing_prod r ->
+ dprintf l "cache miss: a product is not in build dir (%a)" Resource.print r
+ | `cache_miss_changed_dep r ->
+ dprintf l "cache miss: a dependency has changed (%a)" Resource.print r
+ | `cache_miss_changed_dyn_dep r ->
+ dprintf l "cache miss: a dynamic dependency has changed (%a)" Resource.print r
+ | `cache_miss_no_digest ->
+ dprintf l "cache miss: no digest found for %S (the command, a dependency, or a product)"
+ r.name
+ | `cache_hit -> dprintf (l+1) "cache hit"
+ | `cache_miss_digest_changed(old_d, new_d) ->
+ dprintf l "cache miss: the digest has changed for %S (the command, a dependency, or a product: %a <> %a)"
+ r.name print_digest old_d print_digest new_d
+ in
+ let prod_digests = digest_prods r in
+ (if not cached then List.iter Resource.clean r.prods);
+ (if !Options.nothing_should_be_rebuilt && not cached then
+ (explain_reason (-1);
+ let msg = sbprintf "Need to rebuild %a through the rule `%a'" print_resource_list r.prods print r in
+ raise (Exit_rule_error msg)));
+ explain_reason 3;
+ let thunk () =
+ try
+ if cached then Command.execute ~pretend:true action.command
+ else
+ begin match r.stamp with
+ | Some stamp ->
+ reset_filesys_cache ();
+ let digest_deps = digest_deps r dyndeps in
+ with_output_file stamp (fun oc -> output_string oc digest_deps)
+ | None -> ()
+ end;
+ List.iter (fun r -> Resource.Cache.resource_built r) r.prods;
+ (if not cached then
+ let new_rule_digest = digest_rule r dyndeps action in
+ let new_prod_digests = digest_prods r in
+ let () = store_digest r new_rule_digest in
+ List.iter begin fun p ->
+ let f = Pathname.to_string (Resource.in_build_dir p) in
+ (try let digest = List.assoc f prod_digests in
+ let new_digest = List.assoc f new_prod_digests in
+ if digest <> new_digest then raise Not_found
+ with Not_found -> Resource.Cache.resource_changed p)
+ end r.prods);
+ dprintf 5 "end rule %a" print r
+ with exn -> (List.iter Resource.clean r.prods; raise exn)
+ in
+ if cached
+ then thunk ()
+ else List.iter (fun x -> Resource.Cache.suspend_resource x action.command thunk r.prods) r.prods
+
+let (get_rules, add_rule, clear_rules) =
+ let rules = ref [] in
+ (fun () -> !rules),
+ begin fun pos r ->
+ try
+ let _ = List.find (fun x -> x.name = r.name) !rules in
+ raise (Exit_rule_error (sbprintf "Rule.add_rule: already exists: (%a)" print r))
+ with Not_found ->
+ match pos with
+ | `bottom -> rules := !rules @ [r]
+ | `top -> rules := r :: !rules
+ | `after s ->
+ rules :=
+ List.fold_right begin fun x acc ->
+ if x.name = s then x :: r :: acc else x :: acc
+ end !rules []
+ | `before s ->
+ rules :=
+ List.fold_right begin fun x acc ->
+ if x.name = s then r :: x :: acc else x :: acc
+ end !rules []
+ end,
+ (fun () -> rules := [])
+
+let rule name ?tags ?(prods=[]) ?(deps=[]) ?prod ?dep ?stamp ?(insert = `bottom) ?doc code =
+ let () =
+ match tags with
+ | None -> ()
+ | Some _ ->
+ Log.eprintf "Warning: your ocamlbuild rule %S uses the ~tags parameter,
+ which is deprecated and ignored."
+ name
+ in
+ let res_add import xs xopt =
+ let init =
+ match xopt with
+ | None -> []
+ | Some r -> [import r]
+ in
+ List.fold_right begin fun x acc ->
+ let r = import x in
+ if List.mem r acc then
+ failwith (sprintf "in rule %s, multiple occurrences of the resource %s" name x)
+ else r :: acc
+ end xs init
+ in
+ if prods = [] && prod = None && stamp = None then raise (Exit_rule_error "Can't make a rule that produces nothing");
+ let stamp, prods =
+ match stamp with
+ | None -> None, prods
+ | Some stamp ->
+ Some (Resource.import_pattern stamp), stamp :: prods
+ in
+ let prods = res_add Resource.import_pattern prods prod in
+ let code env build =
+ let cmd = code env build in
+ { digest = Command.digest cmd
+ ; command = cmd }
+ in
+ add_rule insert
+ { name = name;
+ deps = res_add Resource.import (* should normalize *) deps dep;
+ stamp = stamp;
+ doc = doc;
+ prods = prods;
+ code = code }
+
+module Common_commands = struct
+ open Command
+ let mv src dest = Cmd (S [A"mv"; P src; Px dest])
+ let cp src dest = Cmd (S [A"cp"; P src; Px dest])
+ let cp_p src dest = Cmd (S [A"cp"; A"-p"; P src; Px dest])
+ let ln_f pointed pointer = Cmd (S [A"ln"; A"-f"; P pointed; Px pointer])
+ let ln_s pointed pointer = Cmd (S[A"ln"; A"-s"; P pointed; Px pointer])
+ let rm_f x = Cmd (S [A"rm"; A"-f"; Px x])
+ let chmod opts file = Cmd (S[A"chmod"; opts; Px file])
+ let cmp a b = Cmd (S[A"cmp"; P a; Px b])
+end
+open Common_commands
+
+let copy_rule name ?insert src dest =
+ rule name ?insert ~prod:dest ~dep:src
+ begin fun env _ ->
+ let src = env src and dest = env dest in
+ Shell.mkdir_p (Pathname.dirname dest);
+ cp_p src dest
+ end
+
+let show_documentation () =
+ let pp fmt = Log.raw_dprintf (-1) fmt in
+ let rules = get_rules () in
+ List.iter
+ (fun rule -> pp "%a@\n@\n" (pretty_print Resource.print_pattern) rule)
+ rules;
+ pp "@."
+
+
diff --git a/ocamlbuild/rule.mli b/ocamlbuild/rule.mli
new file mode 100644
index 0000000000..df5a0e34df
--- /dev/null
+++ b/ocamlbuild/rule.mli
@@ -0,0 +1,86 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Resource
+
+type env = Pathname.t -> Pathname.t
+type builder = Pathname.t list list -> (Pathname.t, exn) Outcome.t list
+type action = env -> builder -> Command.t
+
+type 'a gen_rule
+
+type rule = Pathname.t gen_rule
+type rule_scheme = resource_pattern gen_rule
+
+type 'a rule_printer = (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a gen_rule -> unit
+
+(** This exception can be raised inside the action of a rule to make the
+ algorithm skip this rule. *)
+exception Failed
+
+val name_of_rule : 'a gen_rule -> string
+val deps_of_rule : 'a gen_rule -> Pathname.t list
+val prods_of_rule : 'a gen_rule -> 'a list
+val doc_of_rule : 'a gen_rule -> string option
+
+val rule : string ->
+ ?tags:string list ->
+ ?prods:string list ->
+ ?deps:string list ->
+ ?prod:string ->
+ ?dep:string ->
+ ?stamp:string ->
+ ?insert:[`top | `before of string | `after of string | `bottom] ->
+ ?doc:string ->
+ action -> unit
+
+(** [copy_rule name ?insert source destination] *)
+val copy_rule : string ->
+ ?insert:[`top | `before of string | `after of string | `bottom] ->
+ string -> string -> unit
+
+module Common_commands : sig
+ val mv : Pathname.t -> Pathname.t -> Command.t
+ val cp : Pathname.t -> Pathname.t -> Command.t
+ val cp_p : Pathname.t -> Pathname.t -> Command.t
+ val ln_f : Pathname.t -> Pathname.t -> Command.t
+ val ln_s : Pathname.t -> Pathname.t -> Command.t
+ val rm_f : Pathname.t -> Command.t
+ val chmod : Command.spec -> Pathname.t -> Command.t
+ val cmp : Pathname.t -> Pathname.t -> Command.t
+end
+
+val print : Format.formatter -> rule -> unit
+val pretty_print : 'a rule_printer
+
+(** For system use only *)
+
+val subst : Resource.env -> rule_scheme -> rule
+val can_produce : Pathname.t -> rule_scheme -> rule option
+(* val tags_matches : Tags.t -> t -> t option *)
+val compare : 'a gen_rule -> 'a gen_rule -> int
+
+val print_rule_name : Format.formatter -> 'a gen_rule -> unit
+val print_rule_contents : 'a rule_printer
+
+val get_rules : unit -> rule_scheme list
+val clear_rules : unit -> unit
+
+val call : builder -> rule -> unit
+
+val build_deps_of_tags : builder -> Tags.t -> Pathname.t list
+
+val show_documentation : unit -> unit
diff --git a/ocamlbuild/shell.ml b/ocamlbuild/shell.ml
new file mode 100644
index 0000000000..a4194bf42b
--- /dev/null
+++ b/ocamlbuild/shell.ml
@@ -0,0 +1,89 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+
+let is_simple_filename s =
+ let ls = String.length s in
+ ls <> 0 &&
+ let rec loop pos =
+ if pos >= ls then true else
+ match s.[pos] with
+ | 'a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '-' | '/' | '_' | ':' | '@' | '+' | ',' -> loop (pos + 1)
+ | _ -> false in
+ loop 0
+let quote_filename_if_needed s =
+ if is_simple_filename s then s
+ (* We should probably be using [Filename.unix_quote] except that function
+ * isn't exported. Users on Windows will have to live with not being able to
+ * install OCaml into c:\o'caml. Too bad. *)
+ else if Sys.os_type = "Win32" then Printf.sprintf "'%s'" s
+ else Filename.quote s
+let chdir dir =
+ reset_filesys_cache ();
+ Sys.chdir dir
+let run args target =
+ reset_readdir_cache ();
+ let cmd = String.concat " " (List.map quote_filename_if_needed args) in
+ if !*My_unix.is_degraded || Sys.os_type = "Win32" then
+ begin
+ Log.event cmd target Tags.empty;
+ let st = sys_command cmd in
+ if st <> 0 then
+ failwith (Printf.sprintf "Error during command `%s'.\nExit code %d.\n" cmd st)
+ else
+ ()
+ end
+ else
+ match My_unix.execute_many ~ticker:Log.update ~display:Log.display [[(fun () -> cmd)]] with
+ | None -> ()
+ | Some(_, x) ->
+ failwith (Printf.sprintf "Error during command %S: %s" cmd (Printexc.to_string x))
+let rm = sys_remove
+let rm_f x =
+ if sys_file_exists x then rm x
+let mkdir dir =
+ reset_filesys_cache_for_file dir;
+ (*Sys.mkdir dir (* MISSING in ocaml *) *)
+ run ["mkdir"; dir] dir
+let try_mkdir dir = if not (sys_file_exists dir) then mkdir dir
+let rec mkdir_p dir =
+ if sys_file_exists dir then ()
+ else (mkdir_p (Filename.dirname dir); mkdir dir)
+
+let cp_pf src dest =
+ reset_filesys_cache_for_file dest;
+ run["cp";"-pf";src;dest] dest
+
+(* L'Arrete du 2007-03-07 prend en consideration
+ differement les archives. Pour les autres fichiers
+ le decret du 2007-02-01 est toujours valable :-) *)
+let cp src dst =
+ if Filename.check_suffix src ".a"
+ && Filename.check_suffix dst ".a"
+ then cp_pf src dst
+ (* try to make a hard link *)
+ else copy_file src dst
+
+let readlink = My_unix.readlink
+let is_link = My_unix.is_link
+let rm_rf x =
+ reset_filesys_cache ();
+ run["rm";"-Rf";x] x
+let mv src dest =
+ reset_filesys_cache_for_file src;
+ reset_filesys_cache_for_file dest;
+ run["mv"; src; dest] dest
+ (*Sys.rename src dest*)
diff --git a/ocamlbuild/shell.mli b/ocamlbuild/shell.mli
new file mode 100644
index 0000000000..8f47b3be5f
--- /dev/null
+++ b/ocamlbuild/shell.mli
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Original author: Nicolas Pouillard *)
+
+val is_simple_filename : string -> bool
+
+val quote_filename_if_needed : string -> string
+(** This will quote using Unix conventions, even on Windows, because commands are
+ * always run through bash -c on Windows. *)
+
+val chdir : string -> unit
+val rm : string -> unit
+val rm_f : string -> unit
+val rm_rf : string -> unit
+val mkdir : string -> unit
+val try_mkdir : string -> unit
+val mkdir_p : string -> unit
+val cp : string -> string -> unit
+val mv : string -> string -> unit
+val readlink : string -> string
+val is_link : string -> bool
diff --git a/ocamlbuild/signatures.mli b/ocamlbuild/signatures.mli
new file mode 100644
index 0000000000..c75ca2a6eb
--- /dev/null
+++ b/ocamlbuild/signatures.mli
@@ -0,0 +1,886 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(** This module contains all module signatures that the user
+ could use to build an ocamlbuild plugin. *)
+
+module type OrderedTypePrintable = sig
+ type t
+ val compare : t -> t -> int
+ val print : Format.formatter -> t -> unit
+end
+
+module type SET = sig
+ include Set.S
+ val find_elt : (elt -> bool) -> t -> elt
+ val map : (elt -> elt) -> t -> t
+ val of_list : elt list -> t
+ val print : Format.formatter -> t -> unit
+end
+
+module type LIST = sig
+ (* Added functions *)
+ val print : (Format.formatter -> 'a -> 'b) -> Format.formatter -> 'a list -> unit
+ val filter_opt : ('a -> 'b option) -> 'a list -> 'b list
+ val union : 'a list -> 'a list -> 'a list
+ val ordered_unique : 'a list -> 'a list
+ (* Original functions *)
+ include module type of List
+end
+
+module type STRING = sig
+ val print : Format.formatter -> string -> unit
+ val chomp : string -> string
+
+ (** [before s n] returns the substring of all characters of [s]
+ that precede position [n] (excluding the character at
+ position [n]).
+ This is the same function as {!Str.string_before}. *)
+ val before : string -> int -> string
+
+ (** [after s n] returns the substring of all characters of [s]
+ that follow position [n] (including the character at
+ position [n]).
+ This is the same function as {!Str.string_after}. *)
+ val after : string -> int -> string
+
+ val first_chars : string -> int -> string
+ (** [first_chars s n] returns the first [n] characters of [s].
+ This is the same function as {!before} ant {!Str.first_chars}. *)
+
+ val last_chars : string -> int -> string
+ (** [last_chars s n] returns the last [n] characters of [s].
+ This is the same function as {!Str.last_chars}. *)
+
+ val eq_sub_strings : string -> int -> string -> int -> int -> bool
+
+ (** [is_prefix u v] is u a prefix of v ? *)
+ val is_prefix : string -> string -> bool
+ (** [is_suffix u v] : is v a suffix of u ? *)
+ val is_suffix : string -> string -> bool
+
+ (** [contains_string s1 p2 s2] Search in [s1] starting from [p1] if it
+ contains the [s2] string. Returns [Some position] where [position]
+ is the begining of the string [s2] in [s1], [None] otherwise. *)
+ val contains_string : string -> int -> string -> int option
+
+ (** [subst patt repl text] *)
+ val subst : string -> string -> string -> string
+
+ (** [tr patt repl text] *)
+ val tr : char -> char -> string -> string
+
+ val rev : string -> string
+
+ (* Convert a character list into a character string *)
+ val implode : char list -> string
+
+ (* Convert a character string into a character list *)
+ val explode : string -> char list
+
+ (** The following are original functions from the [String] module. *)
+ include module type of String
+end
+
+module type TAGS = sig
+ include Set.S with type elt = string
+ (** [Tags.elt] represents a tag, which is simply a string, usually
+ lowercase, for example "ocaml" or "native". The set of tags
+ attached to a file is computed by applying the tagging rules to
+ the filename. Tagging rules are defined in _tags files in any
+ parent directory of a file, up to the main project directory. *)
+
+ val of_list : string list -> t
+ val print : Format.formatter -> t -> unit
+ val does_match : t -> t -> bool
+ module Operators : sig
+ val ( ++ ) : t -> elt -> t
+ val ( -- ) : t -> elt -> t
+ val ( +++ ) : t -> elt option -> t
+ val ( --- ) : t -> elt option -> t
+ end
+end
+
+module type PATHNAME = sig
+ type t = string
+ val concat : t -> t -> t
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ val exists : t -> bool
+ val mk : string -> t
+ val define_context : string -> string list -> unit
+ val include_dirs_of : string -> string list
+ val copy : t -> t -> unit
+ val to_string : t -> string
+ val print : Format.formatter -> t -> unit
+ val current_dir_name : t
+ val parent_dir_name : t
+ val read : t -> string
+ val same_contents : t -> t -> bool
+ val basename : t -> t
+ val dirname : t -> t
+ val is_relative : t -> bool
+ val readlink : t -> t
+ val readdir : t -> t array
+ val is_link : t -> bool
+ val is_directory : t -> bool
+
+ val add_extension : string -> t -> t
+ val check_extension : t -> string -> bool
+
+ val get_extension : t -> string
+ val remove_extension : t -> t
+ val update_extension : string -> t -> t
+
+ val get_extensions : t -> string
+ val remove_extensions : t -> t
+ val update_extensions : string -> t -> t
+
+ val print_path_list : Format.formatter -> t list -> unit
+ val pwd : t
+ val parent : t -> t
+ (** [is_prefix x y] is [x] a pathname prefix of [y] *)
+ val is_prefix : t -> t -> bool
+ val is_implicit : t -> bool
+ module Operators : sig
+ val ( / ) : t -> t -> t
+ val ( -.- ) : t -> string -> t
+ end
+end
+
+(** Provides an abstract type for easily building complex shell
+ commands without making quotation mistakes. *)
+module type COMMAND = sig
+ type tags
+ type pathname
+
+ (** The type [t] provides some basic combinators and command primitives.
+ Other commands can be made of command specifications ([spec]). *)
+ type t =
+ | Seq of t list (** A sequence of commands (like the `;' in shell) *)
+ | Cmd of spec (** A command is made of command specifications ([spec]) *)
+ | Echo of string list * pathname
+ (** Write the given strings (w/ any formatting) to the given file *)
+ | Nop (** The command that does nothing *)
+
+ (** The type for command specifications. That is pieces of command. *)
+ and spec =
+ | N (** No operation. *)
+ | S of spec list (** A sequence. This gets flattened in the last stages *)
+ | A of string (** An atom. *)
+ | P of pathname (** A pathname. *)
+ | Px of pathname (** A pathname, that will also be given to the
+ call_with_target hook. *)
+ | Sh of string (** A bit of raw shell code, that will not be escaped. *)
+ | T of tags (** A set of tags, that describe properties and
+ some semantics information about the
+ command, afterward these tags will be
+ replaced by command [spec]s (flags for
+ instance). *)
+ | V of string (** A virtual command, that will be resolved at
+ execution using [resolve_virtuals] *)
+ | Quote of spec (** A string that should be quoted like a
+ filename but isn't really one. *)
+
+ (*type v = [ `Seq of v list | `Cmd of vspec | `Nop ]
+ and vspec =
+ [ `N
+ | `S of vspec list
+ | `A of string
+ | `P of pathname
+ | `Px of pathname
+ | `Sh of string
+ | `Quote of vspec ]
+
+ val spec_of_vspec : vspec -> spec
+ val vspec_of_spec : spec -> vspec
+ val t_of_v : v -> t
+ val v_of_t : t -> v*)
+
+ (** Will convert a string list to a list of atoms by adding [A] constructors. *)
+ val atomize : string list -> spec
+
+ (** Will convert a string list to a list of paths by adding [P] constructors. *)
+ val atomize_paths : string list -> spec
+
+ (** Run the command. *)
+ val execute : ?quiet:bool -> ?pretend:bool -> t -> unit
+
+ (** Run the commands in the given list, if possible in parallel.
+ See the module [Ocamlbuild_executor]. *)
+ val execute_many : ?quiet:bool -> ?pretend:bool -> t list -> (bool list * exn) option
+
+ (** [setup_virtual_command_solver virtual_command solver]
+ the given solver can raise Not_found if it fails to find a valid
+ command for this virtual command. *)
+ val setup_virtual_command_solver : string -> (unit -> spec) -> unit
+
+ (** Search the given command in the command path and return its absolute
+ pathname. *)
+ val search_in_path : string -> string
+
+ (** Simplify a command by flattening the sequences and resolving the tags
+ into command-line options. *)
+ val reduce : spec -> spec
+
+ (** Print a command (the format is not suitable to running the command). *)
+ val print : Format.formatter -> t -> unit
+
+ (** Convert a command to a string (same format as print). *)
+ val to_string : t -> string
+
+ (** Build a string representation of a command that can be passed to the
+ system calls. *)
+ val string_of_command_spec : spec -> string
+end
+
+(** A self-contained module implementing extended shell glob patterns who have an expressive power
+ equal to boolean combinations of regular expressions. *)
+module type GLOB = sig
+
+ (** A globber is a boolean combination of basic expressions indented to work on
+ pathnames. Known operators
+ are [or], [and] and [not], which may also be written [|], [&] and [~]. There are
+ also constants [true] and [false] (or [1] and [0]). Expression can be grouped
+ using parentheses.
+ - [true] matches anything,
+ - [false] matches nothing,
+ - {i basic} [or] {i basic} matches strings matching either one of the basic expressions,
+ - {i basic} [and] {i basic} matches strings matching both basic expressions,
+ - not {i basic} matches string that don't match the basic expression,
+ - {i basic} matches strings that match the basic expression.
+
+ A basic expression can be a constant string enclosed in double quotes, in which
+ double quotes must be preceded by backslashes, or a glob pattern enclosed between a [<] and a [>],
+ - ["]{i string}["] matches the literal string {i string},
+ - [<]{i glob}[>] matches the glob pattern {i glob}.
+
+ A glob pattern is an anchored regular expression in a shell-like syntax. Most characters stand for themselves.
+ Character ranges are given in usual shell syntax between brackets. The star [*] stands for any sequence of
+ characters. The joker '?' stands for exactly one, unspecified character. Alternation is achieved using braces [{].
+ - {i glob1}{i glob2} matches strings who have a prefix matching {i glob1} and the corresponding suffix
+ matching {i glob2}.
+ - [a] matches the string consisting of the single letter [a].
+ - [{]{i glob1},{i glob2}[}] matches strings matching {i glob1} or {i glob2}.
+ - [?] any one-letter string, excluding the slash.
+ - [*] matches all strings not containing a slash, including the empty one.
+ - [**/] the empty string, or any string ending with a slash.
+ - [/**] any string starting with a slash, or the empty string.
+ - [/**/] any string starting and ending with a slash.
+ - [\[]{i c1}-{i c2}{i c3}-{i c4}...[\]] matches characters in the range {i c1} to {i c2} inclusive,
+ or in the range {i c3} to {i c4} inclusive. For instance [\[a-fA-F0-9\]] matches hexadecimal digits.
+ To match the dash, put it at the end.
+ *)
+
+ (** The type representing globbers. Do not attempt to compare them, as they get on-the-fly optimizations. *)
+ type globber
+
+ (** [parse ~dir pattern] will parse the globber pattern [pattern], optionally prefixing its patterns with [dir]. *)
+ val parse : ?dir:string -> string -> globber
+
+ (** A descriptive exception raised when an invalid glob pattern description is given. *)
+ exception Parse_error of string
+
+ (** [eval g u] returns [true] if and only if the string [u] matches the given glob expression. Avoid reparsing
+ the same pattern, since the automaton implementing the pattern is optimized on the fly. The first few evaluations
+ are done using a time-inefficient but memory-efficient algorithm. It then compiles the pattern into an efficient
+ but more memory-hungry data structure. *)
+ val eval : globber -> string -> bool
+end
+
+(** Module for modulating the logging output with the logging level. *)
+module type LOG = sig
+ (** Current logging (debugging) level. *)
+ val level : int ref
+
+ (** [dprintf level fmt args...] formats the logging information [fmt]
+ with the arguments [args...] on the logging output if the logging
+ level is greater than or equal to [level]. The default level is 1.
+ More obscure debugging information should have a higher logging
+ level. Youre formats are wrapped inside these two formats
+ ["@\[<2>"] and ["@\]@."]. *)
+ val dprintf : int -> ('a, Format.formatter, unit) format -> 'a
+
+ (** @return whether logging at this level will print anything *)
+ val is_logging : int -> bool
+
+ (** Equivalent to calling [dprintf] with a level [< 0]. *)
+ val eprintf : ('a, Format.formatter, unit) format -> 'a
+
+ (** Same as dprintf but without the format wrapping. *)
+ val raw_dprintf : int -> ('a, Format.formatter, unit) format -> 'a
+end
+
+module type OUTCOME = sig
+ type ('a,'b) t =
+ | Good of 'a
+ | Bad of 'b
+
+ val wrap : ('a -> 'b) -> 'a -> ('b, exn) t
+ val ignore_good : ('a, exn) t -> unit
+ val good : ('a, exn) t -> 'a
+end
+
+module type MISC = sig
+ val opt_print :
+ (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit
+ val the : 'a option -> 'a
+ val getenv : ?default:string -> string -> string
+ val with_input_file : ?bin:bool -> string -> (in_channel -> 'a) -> 'a
+ val with_output_file : ?bin:bool -> string -> (out_channel -> 'a) -> 'a
+ val with_temp_file : string -> string -> (string -> 'a) -> 'a
+ val read_file : string -> string
+ val copy_chan : in_channel -> out_channel -> unit
+ val copy_file : string -> string -> unit
+ val print_string_list : Format.formatter -> string list -> unit
+
+ (** A shortcut to force lazy value (See {Lazy.force}). *)
+ val ( !* ) : 'a Lazy.t -> 'a
+
+ (** The right associative application.
+ Useful when writing to much parentheses:
+ << f (g x ... t) >> becomes << f& g x ... t >>
+ << f (g (h x)) >> becomes << f& g& h x >> *)
+ val ( & ) : ('a -> 'b) -> 'a -> 'b
+
+ (** The reversed application combinator.
+ Useful to describe some operations chaining.
+ << f x (g y (h z)) >> becomes << z |> h |> g y |> f x >> *)
+ val ( |> ) : 'a -> ('a -> 'b) -> 'b
+
+ (** [r @:= l] is equivalent to [r := !r @ l] *)
+ val ( @:= ) : 'a list ref -> 'a list -> unit
+
+ val memo : ('a -> 'b) -> ('a -> 'b)
+
+ val memo2 : ('a -> 'b -> 'c) -> ('a -> 'b -> 'c)
+
+ val memo3 : ('a -> 'b -> 'c -> 'd) -> ('a -> 'b -> 'c -> 'd)
+end
+
+module type OPTIONS = sig
+ type command_spec
+
+ val build_dir : string ref
+ val include_dirs : string list ref
+ val exclude_dirs : string list ref
+ val nothing_should_be_rebuilt : bool ref
+ val ocamlc : command_spec ref
+ val ocamlopt : command_spec ref
+ val ocamldep : command_spec ref
+ val ocamldoc : command_spec ref
+ val ocamlyacc : command_spec ref
+ val ocamllex : command_spec ref
+ val ocamlrun : command_spec ref
+ val ocamlmklib : command_spec ref
+ val ocamlmktop : command_spec ref
+ val hygiene : bool ref
+ val sanitize : bool ref
+ val sanitization_script : string ref
+ val ignore_auto : bool ref
+ val plugin : bool ref
+ val just_plugin : bool ref
+ val native_plugin : bool ref
+ val make_links : bool ref
+ val nostdlib : bool ref
+ val program_to_execute : bool ref
+ val must_clean : bool ref
+ val catch_errors : bool ref
+ val use_menhir : bool ref
+ val show_documentation : bool ref
+ val recursive : bool ref
+ val use_ocamlfind : bool ref
+
+ val targets : string list ref
+ val ocaml_libs : string list ref
+ val ocaml_mods : string list ref
+ val ocaml_pkgs : string list ref
+ val ocaml_syntax : string option ref
+ val ocaml_cflags : string list ref
+ val ocaml_lflags : string list ref
+ val ocaml_ppflags : string list ref
+ val ocaml_docflags : string list ref
+ val ocaml_yaccflags : string list ref
+ val ocaml_lexflags : string list ref
+ val program_args : string list ref
+ val ignore_list : string list ref
+ val tags : string list ref
+ val tag_lines : string list ref
+ val show_tags : string list ref
+
+ val ext_obj : string ref
+ val ext_lib : string ref
+ val ext_dll : string ref
+ val exe : string ref
+
+ val add : string * Arg.spec * string -> unit
+end
+
+module type ARCH = sig
+ type 'a arch = private
+ | Arch_dir of string * 'a * 'a arch list
+ | Arch_dir_pack of string * 'a * 'a arch list
+ | Arch_file of string * 'a
+
+ val dir : string -> unit arch list -> unit arch
+ val dir_pack : string -> unit arch list -> unit arch
+ val file : string -> unit arch
+
+ type info = private {
+ current_path : string;
+ include_dirs : string list;
+ for_pack : string;
+ }
+
+ val annotate : 'a arch -> info arch
+
+ val print : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a arch -> unit
+ val print_include_dirs : Format.formatter -> string list -> unit
+ val print_info : Format.formatter -> info -> unit
+
+ val iter_info : ('a -> unit) -> 'a arch -> unit
+ val fold_info : ('a -> 'b -> 'b) -> 'a arch -> 'b -> 'b
+
+ val iter_include_dirs : info arch -> (string -> unit) -> unit
+
+ val mk_tables :
+ info arch -> (string, string list) Hashtbl.t * (string, string) Hashtbl.t
+ val print_table :
+ (Format.formatter -> 'a -> unit) -> Format.formatter -> (string, 'a) Hashtbl.t -> unit
+end
+
+module type FINDLIB = sig
+ (** Findlib / Ocamlfind tools. *)
+
+ type command_spec
+
+ type error =
+ | Cannot_run_ocamlfind
+ | Dependency_not_found of string * string (* package, dependency *)
+ | Package_not_found of string
+ | Cannot_parse_query of string * string (* package, explaination *)
+
+ exception Findlib_error of error
+
+ val string_of_error: error -> string
+ (** Return a string message describing an error. *)
+
+ val report_error: error -> 'a
+ (** Report an error on the standard error and exit with code 2. *)
+
+ type package = {
+ name: string;
+ description: string;
+ version: string;
+ archives_byte: string;
+ (** Archive names, with the .cma extension, but without the directory. *)
+ archives_native: string;
+ (** Archive names, with the .cmxa extension, but without the directory. *)
+ link_options: string;
+ location: string;
+ dependencies: package list;
+ (** Transitive closure, as returned by [ocamlfind query -r]. *)
+ }
+ (** Package information. *)
+
+ val query: string -> package
+ (** Query information about a package, given its name. May raise
+[Not_found]. *)
+
+ val list: unit -> string list
+ (** Return the names of all known packages. *)
+
+ val topological_closure: package list -> package list
+ (** Computes the transitive closure of a list of
+packages and sort them in topological order.
+Given any list of package [l], [topological_closure l] returns a list of
+packages including [l] and their dependencies, in an order where any element
+may only depend on the previous ones. *)
+
+ val include_flags: package list -> command_spec
+ (** Return the list of include directories. *)
+
+ val compile_flags_byte: package list -> command_spec
+ (** Return the flags to add when compiling in byte mode (include
+directories). *)
+
+ val compile_flags_native: package list -> command_spec
+ (** Same as [compile_flags_byte] but for native mode. *)
+
+ val link_flags_byte: package list -> command_spec
+ (** Return the flags to add when linking in byte mode. It includes:
+include directories, libraries and special link options. *)
+
+ val link_flags_native: package list -> command_spec
+ (** Same as [link_flags_byte] but for native mode. *)
+end
+
+(** This module contains the functions and values that can be used by
+ plugins. *)
+module type PLUGIN = sig
+ module Pathname : PATHNAME
+ module Tags : TAGS
+ module Command : COMMAND with type tags = Tags.t and type pathname = Pathname.t
+ module Outcome : OUTCOME
+ module String : STRING
+ module List : LIST
+ module StringSet : Set.S with type elt = String.t
+ module Options : OPTIONS with type command_spec = Command.spec
+ module Arch : ARCH
+ module Findlib : FINDLIB with type command_spec = Command.spec
+ include MISC
+
+ (** See {!COMMAND.t} for the description of this type. *)
+ type command = Command.t =
+ | Seq of command list
+ | Cmd of spec
+ | Echo of string list * Pathname.t
+ | Nop
+
+ (** See {!COMMAND.spec} for the description of this type. *)
+ and spec = Command.spec =
+ | N | S of spec list | A of string | P of string | Px of string
+ | Sh of string | T of Tags.t | V of string | Quote of spec
+
+ (** [path1/path2] Join the given path names. *)
+ val ( / ) : Pathname.t -> Pathname.t -> Pathname.t
+
+ (** [path-.-extension] Add the given extension to the given pathname. *)
+ val ( -.- ) : Pathname.t -> string -> Pathname.t
+
+ (** [tags++tag] Add the given tag to the given set of tags. *)
+ val ( ++ ) : Tags.t -> Tags.elt -> Tags.t
+
+ (** [tags--tag] Remove the given tag to the given set of tags. *)
+ val ( -- ) : Tags.t -> Tags.elt -> Tags.t
+
+ (** [tags+++optional_tag] Add the given optional tag to the given set of tags
+ if the given option is Some. *)
+ val ( +++ ) : Tags.t -> Tags.elt option -> Tags.t
+
+ (** [tags---optional_tag] Remove the given optional tag to the given
+ set of tags if the given option is Some. *)
+ val ( --- ) : Tags.t -> Tags.elt option -> Tags.t
+
+ (** Targets and dependencies in rules are patterns, which are
+ matched by the actual targets requested by the user. For
+ example, if a rule explains how to build "%.cmo" from "%.ml", it
+ will be fired if the user tries to build "foo.cmo".
+
+ The environment records the value of the pattern variables
+ (here "%") in this matching. In the context of our example, the
+ environment will be a function substituting "%" by "foo";
+ calling it on "%.cmo" will return "foo.cmo", and calling it on
+ "%.ml" will return "foo.ml".
+
+ For a typical example of use of the environment, see the
+ [ocamldep_ml_command] example in the documentation of {!action}
+ below. *)
+ type env = Pathname.t -> Pathname.t
+
+ (** A builder is a function that waits for conjonction of alternative targets.
+ The alternatives are here to support some choices, for instance for an
+ OCaml module an alternatives can be foo.cmo, foo.cmi, Foo.cmo, Foo.cmi.
+ Conjonctions are here to help making parallelism, indeed commands that are
+ independant will be run concurently.
+
+ For an example of use of a builder function, see the [targets]
+ function given as an example in the documentation of the
+ {!action} type below.
+ *)
+ type builder = Pathname.t list list -> (Pathname.t, exn) Outcome.t list
+
+ (** This is the type for rule actions. An action receive as argument, the
+ environment lookup function (see {!env}), and a function to dynamically
+ build more targets (see {!builder}). An action should return the command
+ to run in order to build the rule productions using the rule dependencies.
+
+ For example, here is an action to build an [ocamldep] command,
+ for use in the example of rule given in the documentation of
+ {!rule} below:
+{[
+let ocamldep_ml_command env _build =
+ let arg = env "%.ml" and out = env "%.ml.depends" in
+ let tags = tags_of_pathname arg ++ "ocaml" ++ "ocamldep" in
+ Cmd(S[A "ocamldep"; T tags; A "-modules"; P arg; Sh ">"; Px out])
+]}
+
+ In the example above, the build function is not used, as there
+ are no dynamic dependencies. There are in the example below: we
+ build a list of targets dynamically read from a "foo.itarget"
+ file. The final command returned by the action links each of
+ them in the current directory.
+
+{[
+let target_list env build =
+ let itarget = env "%.itarget" in
+ let targets =
+ let dir = Pathname.dirname itarget in
+ let files = string_list_of_file itarget in
+ List.map (fun file -> [Pathname.concat dir file]) files
+ in
+ let results = List.map Outcome.good (build targets) in
+ let link_command result =
+ Cmd (S [A "ln"; A "-sf";
+ P (Pathname.concat !Options.build_dir result);
+ A Pathname.pwd])
+ in
+ Seq (List.map link_command results)
+]}
+ *)
+ type action = env -> builder -> Command.t
+
+ (** This is the main function for adding a rule to the ocamlbuild engine.
+ - The first argument is the name of the rule (should be unique).
+ - It takes files that the rule produces.
+ Use [~prod] for one file, [~prods] for list of files.
+ - It also takes files that the rule uses.
+ Use [~dep] for one file, [~deps] for list of files.
+ - It finally takes the action to perform in order to produce the
+ productions files using the dependencies (see [action]).
+
+ There are some more optional parameters:
+ - The [~insert] argument allows to insert the rules precisely between other
+ rules.
+ - The [~stamp] argument specifies the name of a file that will be
+ automatically produced by ocamlbuild. This file can serve as a virtual
+ target (or phony target), since it will be filled up by a digest of
+ it dependencies.
+ - The [~tags] argument in deprecated, don't use it.
+
+ Finally, the optional [~doc] argument allows to give an informal
+ explanation of the rule purpose and behavior, that will be
+ displayed by [ocamlbuild -documentation]. For example, it is
+ a good place to specify the commands that will be called, any
+ new tags introduced by the rule, and dynamic dependencies.
+
+ For example, here is how a rule producing [foo.ml.depends] from
+ [foo.ml] (calling [ocamldep]) is defined, slightly simplified from
+ the built-in definition.
+
+{[
+rule "ocaml dependencies ml"
+ ~prod:"%.ml.depends"
+ ~dep:"%.ml"
+ (ocamldep_ml_command)
+]}
+
+ The rule that builds a list of targets from a [%.itarget] file is
+ an example of use of the [?stamp] argument. It uses the
+ [target_list] action provided in the documentation of {!action}
+ above. Besides the targets listed in the [%.itarget] file, this
+ command will also produce a [%.otarget] file (the "stamp") that
+ contains the digest of all the [%.itarget] dependencies. This stamp
+ file is the name to use when you want to ask OCamlbuild to build
+ the targets listed: invoking [ocamlbuild foo.otarget] will build
+ the the targets listed in [foo.itarget]. Similarly, new rules
+ that would depend on that list of targets should depend on
+ [%.otarget] (output), not [%.itarget] (input).
+
+{[
+rule "target files"
+ ~dep:"%.itarget"
+ ~stamp:"%.otarget"
+ ~doc:"If foo.itarget contains a list of ocamlbuild targets, \
+ asking ocamlbuild to produce foo.otarget will \
+ build each of those targets in turn."
+ target_list
+]}
+ *)
+ val rule : string ->
+ ?tags:string list ->
+ ?prods:string list ->
+ ?deps:string list ->
+ ?prod:string ->
+ ?dep:string ->
+ ?stamp:string ->
+ ?insert:[`top | `before of string | `after of string | `bottom] ->
+ ?doc:string ->
+ action -> unit
+
+ (** [copy_rule name ?insert source destination] *)
+ val copy_rule : string ->
+ ?insert:[`top | `before of string | `after of string | `bottom] ->
+ string -> string -> unit
+
+ (** Empties the list of rules of the ocamlbuild engine. *)
+ val clear_rules : unit -> unit
+
+ (** [dep tags deps] Will build [deps] when all [tags] will be activated.
+ If you do not know which tags to use, have a look to the file
+ _build/_log after trying to compile your code. *)
+ val dep : Tags.elt list -> Pathname.t list -> unit
+
+ (** [pdep tags ptag deps] is equivalent to [dep tags deps], with an
+ additional parameterized tag [ptag]. [deps] is now a function
+ which takes the parameter of the tag [ptag] as an argument.
+
+ Example:
+ [pdep ["ocaml"; "compile"] "autodep" (fun param -> param)]
+ says that the tag [autodep(file)] can now be used to automatically
+ add [file] as a dependency when compiling an OCaml program. *)
+ val pdep : Tags.elt list -> Tags.elt -> (string -> Pathname.t list) -> unit
+
+ (** [flag tags command_spec] Will inject the given piece of command
+ ([command_spec]) when all [tags] will be activated.
+ If you do not know which tags to use, have a look to the file
+ _build/_log after trying to compile your code. *)
+ val flag : Tags.elt list -> Command.spec -> unit
+
+ (** Allows to use [flag] with a parametrized tag (as [pdep] for [dep]).
+
+ Example:
+ [pflag ["ocaml"; "compile"] "inline"
+ (fun count -> S [A "-inline"; A count])]
+ says that command line option ["-inline 42"] should be added
+ when compiling OCaml modules tagged with ["inline(42)"]. *)
+ val pflag : Tags.elt list -> Tags.elt -> (string -> Command.spec) -> unit
+
+ (** [flag_and_dep tags command_spec]
+ Combines [flag] and [dep] function.
+ Basically it calls [flag tags command_spec], and calls [dep tags files]
+ where [files] is the list of all pathnames in [command_spec].
+ Pathnames selected are those in the constructor [P] or [Px], or the
+ pathname argument of builtins like [Echo]. *)
+ val flag_and_dep : Tags.elt list -> Command.spec -> unit
+
+ (** Allows to use [flag_and_dep] with a parameterized tag
+ (as [pdep] for [dep]). *)
+ val pflag_and_dep : Tags.elt list -> Tags.elt ->
+ (string -> Command.spec) -> unit
+
+ (** manually mark the tag as "useful" to silence the warning about
+ tags that are not part of any flag declaration.
+
+ This is useful,
+ for example, if the tag is used in a flag declaration that is
+ only perfored in a conditional branch:
+ [if we_are_on_Windows then flag ["libfoo"] (A "bar");]
+
+ When [we_are_on_Windows] is not true, you could get a warning about
+ "libfoo" not used in any flag declaration.
+ *)
+ val mark_tag_used : Tags.elt -> unit
+
+ (** [non_dependency module_path module_name]
+ Example:
+ [non_dependency "foo/bar/baz" "Goo"]
+ Says that the module [Baz] in the file [foo/bar/baz.*] does
+ not depend on [Goo]. *)
+ val non_dependency : Pathname.t -> string -> unit
+
+ (** [use_lib module_path lib_path]*)
+ val use_lib : Pathname.t -> Pathname.t -> unit
+
+ (** [ocaml_lib <options> library_pathname] Declare an ocaml library.
+ This informs ocamlbuild and produce tags to use the library;
+ they are named by default use_#{library_name}.
+
+ Example: [ocaml_lib "foo/bar"] will setup the tag use_bar.
+ At link time it will include:
+ foo/bar.cma or foo/bar.cmxa
+ @param dir supply the [~dir:"boo"] option to add '-I boo'
+ at link and compile time.
+ @param extern use ~extern:true for non-ocamlbuild handled libraries.
+ Set this to add libraries whose sources are not in your project.
+ @param byte use ~byte:false to disable byte mode.
+ @param native use ~native:false to disable native mode.
+ @param tag_name Use ~tag_name:"usebar" to override the default
+ tag name. *)
+ val ocaml_lib :
+ ?extern:bool ->
+ ?byte:bool ->
+ ?native:bool ->
+ ?dir:Pathname.t ->
+ ?tag_name:string ->
+ Pathname.t -> unit
+
+ (** [expand_module include_dirs module_name extensions]
+ Example:
+ [expand_module ["a";"b";"c"] "Foo" ["cmo";"cmi"] =
+ ["a/foo.cmo"; "a/Foo.cmo"; "a/foo.cmi"; "a/Foo.cmi";
+ "b/foo.cmo"; "b/Foo.cmo"; "b/foo.cmi"; "b/Foo.cmi";
+ "c/foo.cmo"; "c/Foo.cmo"; "c/foo.cmi"; "c/Foo.cmi"]] *)
+ val expand_module :
+ Pathname.t list -> Pathname.t -> string list -> Pathname.t list
+
+ (** Reads the given file, parse it has list of words separated by blanks.
+ It ignore lines that begins with a '#' character. *)
+ val string_list_of_file : Pathname.t -> string list
+
+ (** Takes a pathname and returns an OCaml module name. Basically it will
+ remove directories and extensions, and then capitalize the string. *)
+ val module_name_of_pathname : Pathname.t -> string
+
+ (** The Unix mv command. *)
+ val mv : Pathname.t -> Pathname.t -> Command.t
+
+ (** The Unix cp command. *)
+ val cp : Pathname.t -> Pathname.t -> Command.t
+
+ (** The Unix ln -f command. *)
+ val ln_f : Pathname.t -> Pathname.t -> Command.t
+
+ (** The Unix ln -s command. *)
+ val ln_s : Pathname.t -> Pathname.t -> Command.t
+
+ (** The Unix rm -f command. *)
+ val rm_f : Pathname.t -> Command.t
+
+ (** The Unix chmod command (almost deprecated). *)
+ val chmod : Command.spec -> Pathname.t -> Command.t
+
+ (** The Unix cmp command (almost deprecated). *)
+ val cmp : Pathname.t -> Pathname.t -> Command.t
+
+ (** [hide_package_contents pack_name]
+ Don't treat the given package as an open package.
+ So a module will not be replaced during linking by
+ this package even if it contains that module. *)
+ val hide_package_contents : string -> unit
+
+ (** [tag_file filename tag_list] Tag the given filename with all
+ given tags. Prefix a tag with the minus sign to remove it.
+ This is usually used as an [After_rules] hook.
+ For example [tag_file "bla.ml" ["use_unix"]] tags the file
+ "bla.ml" with "use_unix" and [tag_file "bla.ml" ["-use_unix"]]
+ removes the tag "use_unix" from the file "bla.ml". *)
+ val tag_file : Pathname.t -> Tags.elt list -> unit
+
+ (** [tag_any tag_list] Tag anything with all given tags. *)
+ val tag_any : Tags.elt list -> unit
+
+ (** Returns the set of tags that applies to the given pathname. *)
+ val tags_of_pathname : Pathname.t -> Tags.t
+
+ (** Run the given command and returns it's output as a string. *)
+ val run_and_read : string -> string
+
+ (** Here is the list of hooks that the dispatch function have to handle.
+ Generally one responds to one or two hooks (like After_rules) and do
+ nothing in the default case. *)
+ type hook =
+ | Before_hygiene
+ | After_hygiene
+ | Before_options
+ | After_options
+ | Before_rules
+ | After_rules
+
+ (** [dispatch hook_handler] Is the entry point for ocamlbuild plugins. Every
+ plugin must call it with a [hook_handler] where all calls to plugin
+ functions lives. *)
+ val dispatch : (hook -> unit) -> unit
+end
diff --git a/ocamlbuild/slurp.ml b/ocamlbuild/slurp.ml
new file mode 100644
index 0000000000..c1cb049afc
--- /dev/null
+++ b/ocamlbuild/slurp.ml
@@ -0,0 +1,189 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Slurp *)
+open My_std
+open Outcome
+
+type 'a entry =
+ | Dir of string * string * My_unix.stats Lazy.t * 'a * 'a entry list Lazy.t
+ | File of string * string * My_unix.stats Lazy.t * 'a
+ | Error of exn
+ | Nothing
+
+let (/) = filename_concat
+
+let rec filter predicate = function
+ | Dir(path, name, st, attr, entries) ->
+ if predicate path name attr then
+ Dir(path, name, st, attr, lazy (List.map (filter predicate) !*entries))
+ else
+ Nothing
+ | File(path, name, _, attr) as f ->
+ if predicate path name attr then
+ f
+ else
+ Nothing
+ | Nothing -> Nothing
+ | Error _ as e -> e
+
+let real_slurp path =
+ let cwd = Sys.getcwd () in
+ let abs x = if Filename.is_implicit x || Filename.is_relative x then cwd/x else x in
+ let visited = Hashtbl.create 1024 in
+ let rec scandir path names =
+ let (file_acc, dir_acc) =
+ Array.fold_left begin fun ((file_acc, dir_acc) as acc) name ->
+ match do_entry true path name with
+ | None -> acc
+ | Some((Dir _|Error _) as entry) -> (file_acc, entry :: dir_acc)
+ | Some((File _) as entry) -> (entry :: file_acc, dir_acc)
+ | Some Nothing -> acc
+ end
+ ([], [])
+ names
+ in
+ file_acc @ dir_acc
+ and do_entry link_mode path name =
+ let fn = path/name in
+ let absfn = abs fn in
+ match
+ try
+ Good(if link_mode then My_unix.lstat absfn else My_unix.stat absfn)
+ with
+ | x -> Bad x
+ with
+ | Bad x -> Some(Error x)
+ | Good st ->
+ let key = st.My_unix.stat_key in
+ if try Hashtbl.find visited key with Not_found -> false
+ then None
+ else
+ begin
+ Hashtbl.add visited key true;
+ let res =
+ match st.My_unix.stat_file_kind with
+ | My_unix.FK_link ->
+ let fn' = My_unix.readlink absfn in
+ if sys_file_exists (abs fn') then
+ do_entry false path name
+ else
+ Some(File(path, name, lazy st, ()))
+ | My_unix.FK_dir ->
+ (match sys_readdir absfn with
+ | Good names -> Some(Dir(path, name, lazy st, (), lazy (scandir fn names)))
+ | Bad exn -> Some(Error exn))
+ | My_unix.FK_other -> None
+ | My_unix.FK_file -> Some(File(path, name, lazy st, ())) in
+ Hashtbl.replace visited key false;
+ res
+ end
+ in
+ match do_entry true "" path with
+ | None -> raise Not_found
+ | Some entry -> entry
+
+let split path =
+ let rec aux path =
+ if path = Filename.current_dir_name then []
+ else (Filename.basename path) :: aux (Filename.dirname path)
+ in List.rev (aux path)
+
+let rec join =
+ function
+ | [] -> assert false
+ | [x] -> x
+ | x :: xs -> x/(join xs)
+
+let rec add root path entries =
+ match path, entries with
+ | [], _ -> entries
+ | xpath :: xspath, (Dir(dpath, dname, dst, dattr, dentries) as d) :: entries ->
+ if xpath = dname then
+ Dir(dpath, dname, dst, dattr, lazy (add (root/xpath) xspath !*dentries)) :: entries
+ else d :: add root path entries
+ | [xpath], [] ->
+ [File(root, xpath, lazy (My_unix.stat (root/xpath)), ())]
+ | xpath :: xspath, [] ->
+ [Dir(root/(join xspath), xpath,
+ lazy (My_unix.stat (root/(join path))), (),
+ lazy (add (root/xpath) xspath []))]
+ | _, Nothing :: entries -> add root path entries
+ | _, Error _ :: _ -> entries
+ | [xpath], (File(_, fname, _, _) as f) :: entries' ->
+ if xpath = fname then entries
+ else f :: add root path entries'
+ | xpath :: xspath, (File(fpath, fname, fst, fattr) as f) :: entries' ->
+ if xpath = fname then
+ Dir(fpath, fname, fst, fattr, lazy (add (root/xpath) xspath [])) :: entries'
+ else f :: add root path entries'
+
+let slurp_with_find path =
+ let find_cmd = try Sys.getenv "OCAMLBUILD_FIND" with _ -> "find" in
+ let lines =
+ My_unix.run_and_open (Printf.sprintf "%s %s" find_cmd (Filename.quote path)) begin fun ic ->
+ let acc = ref [] in
+ try while true do acc := input_line ic :: !acc done; []
+ with End_of_file -> !acc
+ end in
+ let res =
+ List.fold_right begin fun line acc ->
+ add path (split line) acc
+ end lines [] in
+ match res with
+ | [] -> Nothing
+ | [entry] -> entry
+ | entries -> Dir(path, Filename.basename path, lazy (My_unix.stat path), (), lazy entries)
+
+let slurp x = if !*My_unix.is_degraded then slurp_with_find x else real_slurp x
+
+let rec print print_attr f entry =
+ match entry with
+ | Dir(path, name, _, attr, entries) ->
+ Format.fprintf f "@[<2>Dir(%S,@ %S,@ _,@ %a,@ %a)@]"
+ path name print_attr attr (List.print (print print_attr)) !*entries
+ | File(path, name, _, attr) ->
+ Format.fprintf f "@[<2>File(%S,@ %S,@ _,@ %a)@]" path name print_attr attr
+ | Nothing ->
+ Format.fprintf f "Nothing"
+ | Error(_) ->
+ Format.fprintf f "Error(_)"
+
+let rec fold f entry acc =
+ match entry with
+ | Dir(path, name, _, attr, contents) ->
+ f path name attr (List.fold_right (fold f) !*contents acc)
+ | File(path, name, _, attr) ->
+ f path name attr acc
+ | Nothing | Error _ -> acc
+
+let map f entry =
+ let rec self entry =
+ match entry with
+ | Dir(path, name, st, attr, contents) ->
+ Dir(path, name, st, f path name attr, lazy (List.map self !*contents))
+ | File(path, name, st, attr) ->
+ File(path, name, st, f path name attr)
+ | Nothing -> Nothing
+ | Error e -> Error e
+ in self entry
+
+let rec force =
+ function
+ | Dir(_, _, st, _, contents) ->
+ let _ = !*st in List.iter force !*contents
+ | File(_, _, st, _) ->
+ ignore !*st
+ | Nothing | Error _ -> ()
diff --git a/ocamlbuild/slurp.mli b/ocamlbuild/slurp.mli
new file mode 100644
index 0000000000..e3b27932bd
--- /dev/null
+++ b/ocamlbuild/slurp.mli
@@ -0,0 +1,50 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Berke Durak *)
+(* Slurp *)
+
+(** Scans a directory lazily to build a tree that can be user-decorated. *)
+
+type 'a entry =
+ Dir of string * string * My_unix.stats Lazy.t * 'a * 'a entry list Lazy.t
+ (** [Dir(path, name, lst, decoration, lentries)] is a directory named [name] whose path is [path].
+ Its stat is lazily stored in [lst] and its entries are lazily scanned in [lentries]. [decoration]
+ is of type 'a. *)
+ | File of string * string * My_unix.stats Lazy.t * 'a
+ (** [File(path, name, lst, decoration)] is a file named [name] whose path is [path].
+ Its stat is lazily stored in [lst]. [decoration] is of type 'a. *)
+ | Error of exn
+ (** [Error x] means that the exception [x] was raised while scanning or statting an entry. *)
+ | Nothing
+ (** Convenient when filtering out entries. *)
+
+(** Recursively scan the filesystem starting at the given directory. *)
+val slurp : string -> unit entry
+
+(** [filter f entry] only retains from [entry] the nodes for which
+ [f path name] returns [true]. *)
+val filter : (string -> string -> 'a -> bool) -> 'a entry -> 'a entry
+
+(** [map f entries] changes the decoration in [entries] by applying
+ [f] to them. [f] is called as [f path name decoration]. *)
+val map : (string -> string -> 'a -> 'b) -> 'a entry -> 'b entry
+
+(** [fold f entry x] iterates [f] over the entries and an accumulator
+ initially containing [x]; at each iteration, [f] gets the current
+ value of the accumulator and returns its new value. *)
+val fold : (string -> string -> 'b -> 'a -> 'a) -> 'b entry -> 'a -> 'a
+
+(** Force the evaluation of the whole entry. *)
+val force : 'a entry -> unit
diff --git a/ocamlbuild/solver.ml b/ocamlbuild/solver.ml
new file mode 100644
index 0000000000..27ca8dbdc6
--- /dev/null
+++ b/ocamlbuild/solver.ml
@@ -0,0 +1,135 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+open My_std
+open Log
+open Format
+open Outcome
+
+type backtrace =
+ | Leaf of Pathname.t
+ | Choice of backtrace list
+ | Depth of Pathname.t * backtrace
+ | Target of string * backtrace
+exception Failed of backtrace
+exception Circular of Pathname.t * Pathname.t list
+
+let failed target backtrace =
+ Resource.Cache.resource_failed target;
+ raise (Failed backtrace)
+
+let rec pp_repeat f (n, s) =
+ if n > 0 then (pp_print_string f s; pp_repeat f (n - 1, s))
+
+(* Targets must be normalized pathnames.
+ * Recursive calls are either on input targets
+ * or dependencies of these targets (returned by Rule.deps_of_rule).
+ *)
+let rec self depth on_the_go_orig target =
+ let rules = Rule.get_rules () in
+ let on_the_go = target :: on_the_go_orig in
+
+ (* skip allocating fmt on a hot path *)
+ if is_logging 4 then dprintf 4 "==%a> %a" pp_repeat (depth, "==") Resource.print target;
+ if List.mem target on_the_go_orig then raise (Circular(target, on_the_go_orig));
+ match Resource.Cache.resource_state target with
+ | Resource.Cache.Bbuilt ->
+ (if is_logging 5 then dprintf 5 "%a already built" Resource.print target)
+ | Resource.Cache.Bcannot_be_built ->
+ (if is_logging 5 then dprintf 5 "%a already failed" Resource.print target; failed target (Leaf target))
+ | Resource.Cache.Bsuspension(s) ->
+ (if is_logging 5 then dprintf 5 "%a was suspended -> resuming" Resource.print target;
+ Resource.Cache.resume_suspension s)
+ | Resource.Cache.Bnot_built_yet ->
+ if not (Pathname.is_relative target) && Pathname.exists target then
+ if Resource.Cache.external_is_up_to_date target then ()
+ else (* perhaps the error can be refined *) failed target (Leaf target)
+ else
+ if Resource.exists_in_source_dir target then
+ Resource.Cache.import_in_build_dir target
+ else
+ match List.filter_opt (Rule.can_produce target) rules with
+ | [] -> failed target (Leaf target)
+ | matching_rules ->
+ let rec until_works rs backtraces =
+ match rs with
+ | [] -> assert false
+ | r :: rs ->
+ try
+ List.iter (force_self (depth + 1) on_the_go) (Rule.deps_of_rule r);
+ try
+ Rule.call (self_firsts (depth + 1) on_the_go) r
+ with Rule.Failed -> raise (Failed (Leaf target))
+ with Failed backtrace ->
+ if rs = [] then failed target (Depth (target, Choice (backtrace :: backtraces)))
+ else
+ let () =
+ match backtrace with
+ | Depth (top_prod, _) -> Resource.Cache.clear_resource_failed top_prod
+ | Target _ | Choice _ | Leaf _ -> ()
+ in until_works rs (backtrace :: backtraces)
+ in until_works matching_rules []
+
+(* Build the first target that is buildable *)
+and self_first depth on_the_go already_failed rs =
+ match rs with
+ | [] -> Bad (Failed (Choice already_failed))
+ | r :: rs ->
+ try self depth on_the_go r; Good r
+ with Failed backtrace -> self_first depth on_the_go (backtrace :: already_failed) rs
+
+(* This variant is the one (once partially applied) called the 'build'
+ * function in the rule actions.
+ *
+ * This one takes a list of list of pathnames to build.
+ * This is a parallel conjonction of sequential alternatives.
+ * This means that in each sublist of pathnames, the first
+ * target that is buildable will be picked. The outer list
+ * denotes that one can build each target in parallel.
+ *)
+and self_firsts depth on_the_go rss =
+ let results = List.map (self_first depth on_the_go []) rss in
+ let cmds, thunks =
+ List.fold_right begin fun res ((acc1, acc2) as acc) ->
+ match res with
+ | Bad _ -> acc
+ | Good res ->
+ match Resource.Cache.get_optional_resource_suspension res with
+ | None -> acc
+ | Some (cmd, thunk) -> (cmd :: acc1, thunk :: acc2)
+ end results ([], []) in
+ let count = List.length cmds in
+ let job_debug = if !Command.jobs = 1 then 10 else 5 in
+ (* skip allocating fmt on a hot path *)
+ if is_logging job_debug && count > 1 then dprintf job_debug ">>> PARALLEL: %d" count;
+ let opt_exn = Command.execute_many cmds in
+ if is_logging job_debug && count > 1 then dprintf job_debug "<<< PARALLEL";
+ begin match opt_exn with
+ | Some(res, exn) ->
+ List.iter2 (fun res thunk -> if res then thunk ()) res thunks;
+ Log.finish ~how:`Error ();
+ raise exn
+ | None ->
+ List.iter (fun thunk -> thunk ()) thunks
+ end;
+ results
+and force_self depth on_the_go x = self depth on_the_go x; Resource.Cache.resume_resource x
+
+let solve = force_self 0 []
+let solve_target name rs =
+ match self_first 0 [] [] rs with
+ | Good res -> Resource.Cache.resume_resource res; res
+ | Bad (Failed backtrace) -> raise (Failed (Target (name, backtrace)))
+ | Bad exn -> raise exn
diff --git a/ocamlbuild/solver.mli b/ocamlbuild/solver.mli
new file mode 100644
index 0000000000..182e78dced
--- /dev/null
+++ b/ocamlbuild/solver.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+type backtrace = private
+ | Leaf of Pathname.t
+ | Choice of backtrace list
+ | Depth of Pathname.t * backtrace
+ | Target of string * backtrace
+exception Failed of backtrace
+exception Circular of Pathname.t * Pathname.t list
+
+val solve : Pathname.t -> unit
+val solve_target : string -> Pathname.t list -> Pathname.t
diff --git a/ocamlbuild/start.sh b/ocamlbuild/start.sh
new file mode 100755
index 0000000000..e4450d550c
--- /dev/null
+++ b/ocamlbuild/start.sh
@@ -0,0 +1,121 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+
+
+set -e
+set -x
+rm -rf _start
+mkdir _start
+cp *.ml* _start
+cd _start
+cat >> ocamlbuild_Myocamlbuild_config.ml <<EOF
+let bindir = "<start>";;
+let libdir = bindir;;
+let a = "a";;
+let o = "o";;
+let so = "so";;
+let exe = "";;
+EOF
+ocamlc -c signatures.mli
+ocamlc -c tags.mli
+ocamlc -c ocamlbuild_Myocamlbuild_config.ml
+ocamlc -c ocamlbuild_where.mli
+ocamlc -c ocamlbuild_where.ml
+ocamlc -c my_unix.mli
+ocamlc -c my_std.mli
+ocamlc -c display.mli
+ocamlc -c shell.mli
+ocamlc -c log.mli
+ocamlc -c bool.mli
+ocamlc -c glob_ast.mli
+ocamlc -c glob_lexer.mli
+ocamlc -c glob.mli
+ocamlc -c lexers.mli
+ocamlc -c slurp.mli
+ocamlc -c pathname.mli
+ocamlc -c discard_printf.mli
+ocamlc -c command.mli
+ocamlc -c digest_cache.mli
+ocamlc -c resource.mli
+ocamlc -c rule.mli
+ocamlc -c hygiene.mli
+ocamlc -c options.mli
+ocamlc -c tools.mli
+ocamlc -c exit_codes.mli
+ocamlc -c main.mli
+ocamlc -c ocaml_utils.mli
+ocamlc -c ocaml_tools.mli
+ocamlc -c ocaml_compiler.mli
+ocamlc -c ocaml_dependencies.mli
+ocamlc -c hooks.mli
+ocamlc -c ocaml_specific.mli
+ocamlc -c configuration.mli
+ocamlc -c flags.mli
+ocamlc -c ocaml_arch.mli
+ocamlc -c solver.mli
+ocamlc -c report.mli
+ocamlc -c ocamlbuild_where.ml
+ocamlc -c fda.mli
+ocamlc -c fda.ml
+ocamlc -c tools.ml
+ocamlc -c plugin.mli
+ocamlc -c plugin.ml
+ocamlc -c ocaml_dependencies.ml
+ocamlc -c exit_codes.ml
+ocamllex lexers.mll
+ocamlc -c lexers.ml
+ocamlc -c param_tags.mli
+ocamlc -c param_tags.ml
+ocamlc -c main.ml
+ocamlc -c findlib.mli
+ocamlc -c findlib.ml
+ocamlc -c ocaml_specific.ml
+ocamlc -c display.ml
+ocamlc -c command.ml
+ocamlc -c -rectypes discard_printf.ml
+ocamlc -c my_std.ml
+ocamlc -c shell.ml
+ocamlc -c my_unix.ml
+ocamlc -c log.ml
+ocamlc -c pathname.ml
+ocamlc -c options.ml
+ocamlc -c slurp.ml
+ocamlc -c ocaml_utils.ml
+ocamlc -c ocaml_tools.ml
+ocamlc -c ocaml_compiler.ml
+ocamlc -c hooks.ml
+ocamllex glob_lexer.mll
+ocamlc -c glob_lexer.ml
+ocamlc -c bool.ml
+ocamlc -c glob_ast.ml
+ocamlc -c glob.ml
+ocamlc -c tags.ml
+ocamlc -c configuration.ml
+ocamlc -c flags.ml
+ocamlc -c hygiene.ml
+ocamlc -c ocaml_arch.ml
+ocamlc -c digest_cache.ml
+ocamlc -c resource.ml
+ocamlc -c rule.ml
+ocamlc -c report.ml
+ocamlc -c solver.ml
+ocamlc -c ocamlbuildlight.mli
+ocamlc -pack ocamlbuild_Myocamlbuild_config.cmo discard_printf.cmo my_std.cmo bool.cmo glob_ast.cmo glob_lexer.cmo glob.cmo lexers.cmo my_unix.cmo tags.cmo display.cmo log.cmo param_tags.cmo shell.cmo slurp.cmo ocamlbuild_where.cmo command.cmo options.cmo pathname.cmo digest_cache.cmo resource.cmo rule.cmo flags.cmo solver.cmo report.cmo ocaml_arch.cmo hygiene.cmo configuration.cmo tools.cmo fda.cmo plugin.cmo ocaml_utils.cmo ocaml_dependencies.cmo ocaml_compiler.cmo ocaml_tools.cmo hooks.cmo findlib.cmo ocaml_specific.cmo exit_codes.cmo main.cmo -o ocamlbuild_pack.cmo
+ocamlc -c ocamlbuildlight.ml
+ocamlc ocamlbuild_pack.cmo ocamlbuildlight.cmo -o ../ocamlbuild.byte.start
+cd ..
+rm -rf _start
+echo ocamlbuild.byte.start: Sucessfully built.
diff --git a/ocamlbuild/tags.ml b/ocamlbuild/tags.ml
new file mode 100644
index 0000000000..0889c4216a
--- /dev/null
+++ b/ocamlbuild/tags.ml
@@ -0,0 +1,45 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+include Set.Make(String)
+
+(**
+ does_match {foo, bar, baz} {foo} => ok
+ does_match {foo, bar, baz} {foo, boo} => ko
+ does_match {foo, bar, baz} {} => ok
+ does_match {foo, bar, baz} {foo, bar, baz} => ok
+*)
+let does_match x y = subset y x
+
+let of_list l = List.fold_right add l empty
+
+open Format
+
+let print f s =
+ let () = fprintf f "@[<0>" in
+ let _ =
+ fold begin fun elt first ->
+ if not first then fprintf f ",@ ";
+ pp_print_string f elt;
+ false
+ end s true in
+ fprintf f "@]"
+
+module Operators = struct
+ let ( ++ ) x y = add y x
+ let ( -- ) x y = remove y x
+ let ( +++ ) x = function Some y -> add y x | None -> x
+ let ( --- ) x = function Some y -> remove y x | None -> x
+end
diff --git a/ocamlbuild/tags.mli b/ocamlbuild/tags.mli
new file mode 100644
index 0000000000..a425c2714f
--- /dev/null
+++ b/ocamlbuild/tags.mli
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+
+include Signatures.TAGS
diff --git a/ocamlbuild/test/good-output b/ocamlbuild/test/good-output
new file mode 100644
index 0000000000..b140dab380
--- /dev/null
+++ b/ocamlbuild/test/good-output
@@ -0,0 +1,1473 @@
+ _____ _ ____
+|_ _|__ ___| |_|___ \
+ | |/ _ \/ __| __| __) |
+ | | __/\__ \ |_ / __/
+ |_|\___||___/\__|_____|
+
+ocamldep.opt -modules toto.ml > toto.ml.depends
+ocamldep.opt -modules tata.mli > tata.mli.depends
+ocamldep.opt -modules titi.ml > titi.ml.depends
+ocamldep.opt -modules tutu.mli > tutu.mli.depends
+ocamlc.opt -c -o tata.cmi tata.mli
+ocamlc.opt -c -o titi.cmo titi.ml
+ocamlc.opt -c -o tutu.cmi tutu.mli
+ocamlc.opt -c -o toto.cmo toto.ml
+ocamldep.opt -modules tata.ml > tata.ml.depends
+ocamldep.opt -modules tutu.ml > tutu.ml.depends
+ocamldep.opt -modules tyty.mli > tyty.mli.depends
+ocamldep.opt -pp camlp4o.opt -modules vivi.ml > vivi.ml.depends
+ocamlc.opt -c -o tyty.cmi tyty.mli
+ocamlc.opt -c -pp camlp4o.opt -o vivi.cmo vivi.ml
+ocamlc.opt -c -o tata.cmo tata.ml
+ocamlc.opt -c -o tutu.cmo tutu.ml
+ocamlc.opt tata.cmo titi.cmo vivi.cmo tutu.cmo toto.cmo -o toto.byte
+ocamlopt.opt -c -pp camlp4o.opt -o vivi.cmx vivi.ml
+ocamlopt.opt -c -o tata.cmx tata.ml
+ocamlopt.opt -c -o titi.cmx titi.ml
+ocamlopt.opt -c -o tutu.cmx tutu.ml
+ocamlopt.opt -c -o toto.cmx toto.ml
+ocamlopt.opt tata.cmx titi.cmx vivi.cmx tutu.cmx toto.cmx -o toto.native
+Warning: Using -- only run the last target
+toto.native: /home/danmey/src/ocaml-trunk/ocamlbuild/test/test2/_build/toto.native: Hello world!!!
+Tutu.tutu => 1
+Tata.tata => "TATA2"
+[cache hit] ocamldep.opt -modules toto.ml > toto.ml.depends
+[cache hit] ocamldep.opt -modules tata.mli > tata.mli.depends
+[cache hit] ocamlc.opt -c -o tata.cmi tata.mli
+[cache hit] ocamldep.opt -modules titi.ml > titi.ml.depends
+[cache hit] ocamlc.opt -c -o titi.cmo titi.ml
+[cache hit] ocamldep.opt -modules tutu.mli > tutu.mli.depends
+[cache hit] ocamlc.opt -c -o tutu.cmi tutu.mli
+[cache hit] ocamlc.opt -c -o toto.cmo toto.ml
+[cache hit] ocamldep.opt -modules tata.ml > tata.ml.depends
+[cache hit] ocamlc.opt -c -o tata.cmo tata.ml
+[cache hit] ocamldep.opt -modules tutu.ml > tutu.ml.depends
+[cache hit] ocamldep.opt -modules tyty.mli > tyty.mli.depends
+[cache hit] ocamlc.opt -c -o tyty.cmi tyty.mli
+[cache hit] ocamldep.opt -pp camlp4o.opt -modules vivi.ml > vivi.ml.depends
+[cache hit] ocamlc.opt -c -pp camlp4o.opt -o vivi.cmo vivi.ml
+[cache hit] ocamlc.opt -c -o tutu.cmo tutu.ml
+[cache hit] ocamlc.opt tata.cmo titi.cmo vivi.cmo tutu.cmo toto.cmo -o toto.byte
+[cache hit] ocamlopt.opt -c -o tata.cmx tata.ml
+[cache hit] ocamlopt.opt -c -o titi.cmx titi.ml
+[cache hit] ocamlopt.opt -c -pp camlp4o.opt -o vivi.cmx vivi.ml
+[cache hit] ocamlopt.opt -c -o tutu.cmx tutu.ml
+[cache hit] ocamlopt.opt -c -o toto.cmx toto.ml
+[cache hit] ocamlopt.opt tata.cmx titi.cmx vivi.cmx tutu.cmx toto.cmx -o toto.native
+Warning: Using -- only run the last target
+toto.native: /home/danmey/src/ocaml-trunk/ocamlbuild/test/test2/_build/toto.native: Hello world!!!
+Tutu.tutu => 1
+Tata.tata => "TATA2"
+ocamldep.opt -pp camlp4o.opt -modules vivi.ml > vivi.ml.depends
+ocamlc.opt -c -pp camlp4o.opt -o vivi.cmo vivi.ml
+ocamlc.opt tata.cmo titi.cmo vivi.cmo tutu.cmo toto.cmo -o toto.byte
+ocamlopt.opt -c -pp camlp4o.opt -o vivi.cmx vivi.ml
+ocamlopt.opt tata.cmx titi.cmx vivi.cmx tutu.cmx toto.cmx -o toto.native
+Warning: Using -- only run the last target
+toto.native: /home/danmey/src/ocaml-trunk/ocamlbuild/test/test2/_build/toto.native: Hello world!!!
+Tutu.tutu => 1
+Tata.tata => "TATA2"
+[cache hit] ocamldep.opt -modules toto.ml > toto.ml.depends
+[cache hit] ocamldep.opt -modules tata.mli > tata.mli.depends
+[cache hit] ocamlc.opt -c -o tata.cmi tata.mli
+[cache hit] ocamldep.opt -modules titi.ml > titi.ml.depends
+[cache hit] ocamlc.opt -c -o titi.cmo titi.ml
+[cache hit] ocamldep.opt -modules tutu.mli > tutu.mli.depends
+[cache hit] ocamlc.opt -c -o tutu.cmi tutu.mli
+[cache hit] ocamlc.opt -c -o toto.cmo toto.ml
+[cache hit] ocamldep.opt -modules tata.ml > tata.ml.depends
+[cache hit] ocamlc.opt -c -o tata.cmo tata.ml
+[cache hit] ocamldep.opt -modules tutu.ml > tutu.ml.depends
+[cache hit] ocamldep.opt -modules tyty.mli > tyty.mli.depends
+[cache hit] ocamlc.opt -c -o tyty.cmi tyty.mli
+[cache hit] ocamldep.opt -pp camlp4o.opt -modules vivi.ml > vivi.ml.depends
+[cache hit] ocamlc.opt -c -pp camlp4o.opt -o vivi.cmo vivi.ml
+[cache hit] ocamlc.opt -c -o tutu.cmo tutu.ml
+[cache hit] ocamlc.opt tata.cmo titi.cmo vivi.cmo tutu.cmo toto.cmo -o toto.byte
+[cache hit] ocamlopt.opt -c -o tata.cmx tata.ml
+[cache hit] ocamlopt.opt -c -o titi.cmx titi.ml
+[cache hit] ocamlopt.opt -c -pp camlp4o.opt -o vivi.cmx vivi.ml
+[cache hit] ocamlopt.opt -c -o tutu.cmx tutu.ml
+[cache hit] ocamlopt.opt -c -o toto.cmx toto.ml
+[cache hit] ocamlopt.opt tata.cmx titi.cmx vivi.cmx tutu.cmx toto.cmx -o toto.native
+Warning: Using -- only run the last target
+toto.native: /home/danmey/src/ocaml-trunk/ocamlbuild/test/test2/_build/toto.native: Hello world!!!
+Tutu.tutu => 1
+Tata.tata => "TATA2"
+ocamldep.opt -pp camlp4o.opt -modules vivi.ml > vivi.ml.depends
+ocamlc.opt -c -pp camlp4o.opt -o vivi.cmo vivi.ml
+ocamlc.opt -c -o tutu.cmo tutu.ml
+ocamlc.opt tata.cmo titi.cmo vivi.cmo tutu.cmo toto.cmo -o toto.byte
+ocamlopt.opt -c -pp camlp4o.opt -o vivi.cmx vivi.ml
+ocamlopt.opt -c -o tutu.cmx tutu.ml
+ocamlopt.opt -c -o toto.cmx toto.ml
+ocamlopt.opt tata.cmx titi.cmx vivi.cmx tutu.cmx toto.cmx -o toto.native
+Warning: Using -- only run the last target
+toto.native: /home/danmey/src/ocaml-trunk/ocamlbuild/test/test2/_build/toto.native: Hello world!!!
+Tutu.tutu => 2
+Tata.tata => "TATA2"
+[cache hit] ocamldep.opt -modules toto.ml > toto.ml.depends
+[cache hit] ocamldep.opt -modules tata.mli > tata.mli.depends
+[cache hit] ocamlc.opt -c -o tata.cmi tata.mli
+[cache hit] ocamldep.opt -modules titi.ml > titi.ml.depends
+[cache hit] ocamlc.opt -c -o titi.cmo titi.ml
+[cache hit] ocamldep.opt -modules tutu.mli > tutu.mli.depends
+[cache hit] ocamlc.opt -c -o tutu.cmi tutu.mli
+[cache hit] ocamlc.opt -c -o toto.cmo toto.ml
+[cache hit] ocamldep.opt -modules tata.ml > tata.ml.depends
+[cache hit] ocamlc.opt -c -o tata.cmo tata.ml
+[cache hit] ocamldep.opt -modules tutu.ml > tutu.ml.depends
+[cache hit] ocamldep.opt -modules tyty.mli > tyty.mli.depends
+[cache hit] ocamlc.opt -c -o tyty.cmi tyty.mli
+[cache hit] ocamldep.opt -pp camlp4o.opt -modules vivi.ml > vivi.ml.depends
+[cache hit] ocamlc.opt -c -pp camlp4o.opt -o vivi.cmo vivi.ml
+[cache hit] ocamlc.opt -c -o tutu.cmo tutu.ml
+[cache hit] ocamlc.opt tata.cmo titi.cmo vivi.cmo tutu.cmo toto.cmo -o toto.byte
+[cache hit] ocamlopt.opt -c -o tata.cmx tata.ml
+[cache hit] ocamlopt.opt -c -o titi.cmx titi.ml
+[cache hit] ocamlopt.opt -c -pp camlp4o.opt -o vivi.cmx vivi.ml
+[cache hit] ocamlopt.opt -c -o tutu.cmx tutu.ml
+[cache hit] ocamlopt.opt -c -o toto.cmx toto.ml
+[cache hit] ocamlopt.opt tata.cmx titi.cmx vivi.cmx tutu.cmx toto.cmx -o toto.native
+Warning: Using -- only run the last target
+toto.native: /home/danmey/src/ocaml-trunk/ocamlbuild/test/test2/_build/toto.native: Hello world!!!
+Tutu.tutu => 2
+Tata.tata => "TATA2"
+ _____ _ _____
+|_ _|__ ___| |_|___ /
+ | |/ _ \/ __| __| |_ \
+ | | __/\__ \ |_ ___) |
+ |_|\___||___/\__|____/
+
+ocamldep.opt -modules a.mli > a.mli.depends
+ocamlc.opt -c -o a.cmi a.mli
+ocamldep.opt -modules a.ml > a.ml.depends
+ocamldep.opt -modules b.mli > b.mli.depends
+ocamlc.opt -c -o b.cmi b.mli
+ocamlc.opt -c -o a.cmo a.ml
+ocamldep.opt -modules b.ml > b.ml.depends
+ocamldep.opt -modules c.mli > c.mli.depends
+ocamlc.opt -c -o c.cmi c.mli
+ocamlc.opt -c -o b.cmo b.ml
+ocamldep.opt -modules c.ml > c.ml.depends
+ocamldep.opt -modules d.mli > d.mli.depends
+ocamlc.opt -c -o d.cmi d.mli
+ocamlc.opt -c -o c.cmo c.ml
+ocamldep.opt -modules d.ml > d.ml.depends
+ocamldep.opt -modules e.mli > e.mli.depends
+ocamlc.opt -c -o e.cmi e.mli
+ocamlc.opt -c -o d.cmo d.ml
+ocamldep.opt -modules e.ml > e.ml.depends
+ocamldep.opt -modules f.mli > f.mli.depends
+ocamlc.opt -c -o f.cmi f.mli
+ocamlc.opt -c -o e.cmo e.ml
+ocamldep.opt -modules f.ml > f.ml.depends
+ocamlc.opt -c -o f.cmo f.ml
+ocamlc.opt unix.cma f.cmo e.cmo d.cmo c.cmo b.cmo a.cmo -o a.byte
+ocamlopt.opt -c -o f.cmx f.ml
+ocamlopt.opt -c -o e.cmx e.ml
+ocamlopt.opt -c -o d.cmx d.ml
+ocamlopt.opt -c -o c.cmx c.ml
+ocamlopt.opt -c -o b.cmx b.ml
+ocamlopt.opt -c -o a.cmx a.ml
+ocamlopt.opt unix.cmxa f.cmx e.cmx d.cmx c.cmx b.cmx a.cmx -o a.native
+ocamldoc.opt -dump a.odoc a.mli
+ocamldoc.opt -dump b.odoc b.mli
+ocamldoc.opt -dump c.odoc c.mli
+ocamldoc.opt -dump d.odoc d.mli
+ocamldoc.opt -dump e.odoc e.mli
+ocamldoc.opt -dump f.odoc f.mli
+rm -rf proj.docdir
+mkdir -p proj.docdir
+ocamldoc.opt -load a.odoc -load b.odoc -load c.odoc -load d.odoc -load e.odoc -load f.odoc -html -d proj.docdir
+[cache hit] ocamldep.opt -modules a.mli > a.mli.depends
+[cache hit] ocamlc.opt -c -o a.cmi a.mli
+[cache hit] ocamldep.opt -modules a.ml > a.ml.depends
+[cache hit] ocamldep.opt -modules b.mli > b.mli.depends
+[cache hit] ocamlc.opt -c -o b.cmi b.mli
+[cache hit] ocamlc.opt -c -o a.cmo a.ml
+[cache hit] ocamldep.opt -modules b.ml > b.ml.depends
+[cache hit] ocamldep.opt -modules c.mli > c.mli.depends
+[cache hit] ocamlc.opt -c -o c.cmi c.mli
+[cache hit] ocamlc.opt -c -o b.cmo b.ml
+[cache hit] ocamldep.opt -modules c.ml > c.ml.depends
+[cache hit] ocamldep.opt -modules d.mli > d.mli.depends
+[cache hit] ocamlc.opt -c -o d.cmi d.mli
+[cache hit] ocamlc.opt -c -o c.cmo c.ml
+[cache hit] ocamldep.opt -modules d.ml > d.ml.depends
+[cache hit] ocamldep.opt -modules e.mli > e.mli.depends
+[cache hit] ocamlc.opt -c -o e.cmi e.mli
+[cache hit] ocamlc.opt -c -o d.cmo d.ml
+[cache hit] ocamldep.opt -modules e.ml > e.ml.depends
+[cache hit] ocamldep.opt -modules f.mli > f.mli.depends
+[cache hit] ocamlc.opt -c -o f.cmi f.mli
+[cache hit] ocamlc.opt -c -o e.cmo e.ml
+[cache hit] ocamldep.opt -modules f.ml > f.ml.depends
+[cache hit] ocamlc.opt -c -o f.cmo f.ml
+[cache hit] ocamlc.opt unix.cma f.cmo e.cmo d.cmo c.cmo b.cmo a.cmo -o a.byte
+[cache hit] ocamlopt.opt -c -o f.cmx f.ml
+[cache hit] ocamlopt.opt -c -o e.cmx e.ml
+[cache hit] ocamlopt.opt -c -o d.cmx d.ml
+[cache hit] ocamlopt.opt -c -o c.cmx c.ml
+[cache hit] ocamlopt.opt -c -o b.cmx b.ml
+[cache hit] ocamlopt.opt -c -o a.cmx a.ml
+[cache hit] ocamlopt.opt unix.cmxa f.cmx e.cmx d.cmx c.cmx b.cmx a.cmx -o a.native
+[cache hit] ocamldoc.opt -dump a.odoc a.mli
+[cache hit] ocamldoc.opt -dump b.odoc b.mli
+[cache hit] ocamldoc.opt -dump c.odoc c.mli
+[cache hit] ocamldoc.opt -dump d.odoc d.mli
+[cache hit] ocamldoc.opt -dump e.odoc e.mli
+[cache hit] ocamldoc.opt -dump f.odoc f.mli
+[cache hit] rm -rf proj.docdir
+[cache hit] mkdir -p proj.docdir
+[cache hit] ocamldoc.opt -load a.odoc -load b.odoc -load c.odoc -load d.odoc -load e.odoc -load f.odoc -html -d proj.docdir
+ _____ _ _ _
+|_ _|__ ___| |_| || |
+ | |/ _ \/ __| __| || |_
+ | | __/\__ \ |_|__ _|
+ |_|\___||___/\__| |_|
+
+aa.mli.depends
+aa.mli
+aa.ml.depends
+bb.ml.depends
+bb.ml
+aa.ml
+aa.byte
+bb.ml
+aa.ml
+aa.native
+[cache hit] aa.mli.depends
+[cache hit] aa.mli
+[cache hit] aa.ml.depends
+[cache hit] bb.ml.depends
+[cache hit] bb.ml
+[cache hit] aa.ml
+[cache hit] aa.byte
+[cache hit] bb.ml
+[cache hit] aa.ml
+[cache hit] aa.native
+ _____ _ ____
+|_ _|__ ___| |_| ___|
+ | |/ _ \/ __| __|___ \
+ | | __/\__ \ |_ ___) |
+ |_|\___||___/\__|____/
+
+ocamldep.opt -modules d.ml > d.ml.depends
+ocamldep.opt -modules a.mli > a.mli.depends
+ocamlc.opt -c -o a.cmi a.mli
+ocamldep.opt -modules a.ml > a.ml.depends
+ocamldep.opt -modules stack.ml > stack.ml.depends
+ocamlc.opt -c -o stack.cmo stack.ml
+ocamldep.opt -modules b.ml > b.ml.depends
+ocamlc.opt -c -o a.cmo a.ml
+ocamlc.opt -c -o b.cmo b.ml
+ocamlc.opt -pack a.cmo b.cmo -o c.cmo
+ocamlc.opt -c -o d.cmo d.ml
+ocamlc.opt stack.cmo c.cmo d.cmo -o d.byte
++ /home/danmey/src/ocaml-trunk/bin/ocamlc.opt stack.cmo c.cmo d.cmo -o d.byte
+File "stack.cmo", line 1:
+Warning 31: files stack.cmo and /home/danmey/src/ocaml-trunk/lib/ocaml/stdlib.cma(Stack) both define a module named Stack
+ocamlopt.opt -c -o stack.cmx stack.ml
+ocamlopt.opt -c -for-pack C -o a.cmx a.ml
+ocamlopt.opt -c -for-pack C -o b.cmx b.ml
+ocamlopt.opt -pack a.cmx b.cmx -o c.cmx ; then rm -f c.mli ; else rm -f c.mli ; exit 1; fi
+ocamlopt.opt -c -o d.cmx d.ml
+ocamlopt.opt stack.cmx c.cmx d.cmx -o d.native
+[cache hit] ocamldep.opt -modules d.ml > d.ml.depends
+[cache hit] ocamldep.opt -modules a.mli > a.mli.depends
+[cache hit] ocamlc.opt -c -o a.cmi a.mli
+[cache hit] ocamldep.opt -modules a.ml > a.ml.depends
+[cache hit] ocamldep.opt -modules stack.ml > stack.ml.depends
+[cache hit] ocamlc.opt -c -o stack.cmo stack.ml
+[cache hit] ocamlc.opt -c -o a.cmo a.ml
+[cache hit] ocamldep.opt -modules b.ml > b.ml.depends
+[cache hit] ocamlc.opt -c -o b.cmo b.ml
+[cache hit] ocamlc.opt -pack a.cmo b.cmo -o c.cmo
+[cache hit] ocamlc.opt -c -o d.cmo d.ml
+[cache hit] ocamlc.opt stack.cmo c.cmo d.cmo -o d.byte
+[cache hit] ocamlopt.opt -c -o stack.cmx stack.ml
+[cache hit] ocamlopt.opt -c -for-pack C -o a.cmx a.ml
+[cache hit] ocamlopt.opt -c -for-pack C -o b.cmx b.ml
+[cache hit] ocamlopt.opt -pack a.cmx b.cmx -o c.cmx ; then rm -f c.mli ; else rm -f c.mli ; exit 1; fi
+[cache hit] ocamlopt.opt -c -o d.cmx d.ml
+[cache hit] ocamlopt.opt stack.cmx c.cmx d.cmx -o d.native
+ _____ _ __
+|_ _|__ ___| |_ / /_
+ | |/ _ \/ __| __| '_ \
+ | | __/\__ \ |_| (_) |
+ |_|\___||___/\__|\___/
+
+ocamldep.opt -modules main.mli > main.mli.depends
+ocamlc.opt -c -o main.cmi main.mli
+ocamldep.opt -modules main.ml > main.ml.depends
+ocamldep.opt -modules a.mli > a.mli.depends
+ocamldep.opt -modules d.mli > d.mli.depends
+ocamlc.opt -c -o a.cmi a.mli
+ocamlc.opt -c -o d.cmi d.mli
+ocamlc.opt -c -o main.cmo main.ml
+ocamldep.opt -modules a.ml > a.ml.depends
+ocamldep.opt -modules b.mli > b.mli.depends
+ocamlc.opt -c -o b.cmi b.mli
+ocamldep.opt -modules d.ml > d.ml.depends
+ocamlc.opt -c -o a.cmo a.ml
+ocamlc.opt -c -o d.cmo d.ml
+ocamldep.opt -modules b.ml > b.ml.depends
+ocamlc.opt -c -o b.cmo b.ml
+ocamlc.opt d.cmo b.cmo a.cmo main.cmo -o main.byte
+[cache hit] ocamldep.opt -modules main.mli > main.mli.depends
+[cache hit] ocamlc.opt -c -o main.cmi main.mli
+[cache hit] ocamldep.opt -modules main.ml > main.ml.depends
+[cache hit] ocamldep.opt -modules a.mli > a.mli.depends
+[cache hit] ocamlc.opt -c -o a.cmi a.mli
+[cache hit] ocamldep.opt -modules d.mli > d.mli.depends
+[cache hit] ocamlc.opt -c -o d.cmi d.mli
+[cache hit] ocamlc.opt -c -o main.cmo main.ml
+[cache hit] ocamldep.opt -modules a.ml > a.ml.depends
+[cache hit] ocamldep.opt -modules b.mli > b.mli.depends
+[cache hit] ocamlc.opt -c -o b.cmi b.mli
+[cache hit] ocamlc.opt -c -o a.cmo a.ml
+[cache hit] ocamldep.opt -modules d.ml > d.ml.depends
+[cache hit] ocamlc.opt -c -o d.cmo d.ml
+[cache hit] ocamldep.opt -modules b.ml > b.ml.depends
+[cache hit] ocamlc.opt -c -o b.cmo b.ml
+[cache hit] ocamlc.opt d.cmo b.cmo a.cmo main.cmo -o main.byte
+ocamldep.opt -modules d.mli > d.mli.depends
+ocamlc.opt -c -o d.cmi d.mli
+ocamlc.opt -c -o main.cmo main.ml
+ocamldep.opt -modules b.mli > b.mli.depends
++ /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules b.mli > b.mli.depends
+File "b.mli", line 13, characters 0-2:
+Error: Syntax error
+Command exited with code 2.
+ocamldep.opt -modules b.mli > b.mli.depends
+ocamlc.opt -c -o b.cmi b.mli
+ocamlc.opt -c -o d.cmo d.ml
+ocamlc.opt -c -o b.cmo b.ml
+ocamlc.opt d.cmo b.cmo a.cmo main.cmo -o main.byte
+[cache hit] ocamldep.opt -modules main.mli > main.mli.depends
+[cache hit] ocamlc.opt -c -o main.cmi main.mli
+[cache hit] ocamldep.opt -modules main.ml > main.ml.depends
+[cache hit] ocamldep.opt -modules a.mli > a.mli.depends
+[cache hit] ocamlc.opt -c -o a.cmi a.mli
+[cache hit] ocamldep.opt -modules d.mli > d.mli.depends
+[cache hit] ocamlc.opt -c -o d.cmi d.mli
+[cache hit] ocamlc.opt -c -o main.cmo main.ml
+[cache hit] ocamldep.opt -modules a.ml > a.ml.depends
+[cache hit] ocamldep.opt -modules b.mli > b.mli.depends
+[cache hit] ocamlc.opt -c -o b.cmi b.mli
+[cache hit] ocamlc.opt -c -o a.cmo a.ml
+[cache hit] ocamldep.opt -modules d.ml > d.ml.depends
+[cache hit] ocamlc.opt -c -o d.cmo d.ml
+[cache hit] ocamldep.opt -modules b.ml > b.ml.depends
+[cache hit] ocamlc.opt -c -o b.cmo b.ml
+[cache hit] ocamlc.opt d.cmo b.cmo a.cmo main.cmo -o main.byte
+PASS
+ _____ _ _____
+|_ _|__ ___| ||___ |
+ | |/ _ \/ __| __| / /
+ | | __/\__ \ |_ / /
+ |_|\___||___/\__/_/
+
+ocamlbuild.cmx -o myocamlbuild
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.mli > bb.mli.depends
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmi bb.mli
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.ml > bb.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cc.ml > cc.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules aa.ml > aa.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.mli > c2.mli.depends
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o aa.cmo aa.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmi c2.mli
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmo bb.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cc.cmo cc.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -a bb.cmo cc.cmo -o bbcc.cma
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules main.ml > main.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c3.ml > c3.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c3.cmo c3.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o main.cmo main.ml
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cool_plugin.ml > cool_plugin.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cool_plugin.cmo cool_plugin.ml
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.ml > c2.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmo c2.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt aa.cmo c2.cmo bbcc.cma c3.cmo main.cmo cool_plugin.cmo -o main.byte
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o bb.cmx bb.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o aa.cmx aa.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c2.cmx c2.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o cc.cmx cc.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -a bb.cmx cc.cmx -o bbcc.cmxa
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c3.cmx c3.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o main.cmx main.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt aa.cmx c2.cmx bbcc.cmxa c3.cmx main.cmx -o main.native
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.mli > bb.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmi bb.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.ml > bb.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmo bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cc.ml > cc.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules aa.ml > aa.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o aa.cmo aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.mli > c2.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmi c2.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cc.cmo cc.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -a bb.cmo cc.cmo -o bbcc.cma
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules main.ml > main.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c3.ml > c3.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c3.cmo c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o main.cmo main.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cool_plugin.ml > cool_plugin.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cool_plugin.cmo cool_plugin.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.ml > c2.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmo c2.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt aa.cmo c2.cmo bbcc.cma c3.cmo main.cmo cool_plugin.cmo -o main.byte
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o bb.cmx bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o aa.cmx aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c2.cmx c2.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o cc.cmx cc.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -a bb.cmx cc.cmx -o bbcc.cmxa
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c3.cmx c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o main.cmx main.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt aa.cmx c2.cmx bbcc.cmxa c3.cmx main.cmx -o main.native
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.mli > bb.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmi bb.mli
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.ml > bb.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cc.ml > cc.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules aa.ml > aa.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o aa.cmo aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.mli > c2.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmi c2.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cc.cmo cc.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmo bb.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -a bb.cmo cc.cmo -o bbcc.cma
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules main.ml > main.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c3.ml > c3.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c3.cmo c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o main.cmo main.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cool_plugin.ml > cool_plugin.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cool_plugin.cmo cool_plugin.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.ml > c2.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmo c2.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt aa.cmo c2.cmo bbcc.cma c3.cmo main.cmo cool_plugin.cmo -o main.byte
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o aa.cmx aa.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o bb.cmx bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c2.cmx c2.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o cc.cmx cc.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -a bb.cmx cc.cmx -o bbcc.cmxa
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c3.cmx c3.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o main.cmx main.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt aa.cmx c2.cmx bbcc.cmxa c3.cmx main.cmx -o main.native
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.mli > bb.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmi bb.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.ml > bb.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmo bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cc.ml > cc.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules aa.ml > aa.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o aa.cmo aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.mli > c2.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmi c2.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cc.cmo cc.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -a bb.cmo cc.cmo -o bbcc.cma
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules main.ml > main.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c3.ml > c3.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c3.cmo c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o main.cmo main.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cool_plugin.ml > cool_plugin.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cool_plugin.cmo cool_plugin.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.ml > c2.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmo c2.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt aa.cmo c2.cmo bbcc.cma c3.cmo main.cmo cool_plugin.cmo -o main.byte
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o bb.cmx bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o aa.cmx aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c2.cmx c2.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o cc.cmx cc.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -a bb.cmx cc.cmx -o bbcc.cmxa
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c3.cmx c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o main.cmx main.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt aa.cmx c2.cmx bbcc.cmxa c3.cmx main.cmx -o main.native
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.mli > bb.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmi bb.mli
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.ml > bb.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cc.ml > cc.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules aa.ml > aa.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o aa.cmo aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.mli > c2.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmi c2.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cc.cmo cc.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmo bb.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -a bb.cmo cc.cmo -o bbcc.cma
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules main.ml > main.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c3.ml > c3.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c3.cmo c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o main.cmo main.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cool_plugin.ml > cool_plugin.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cool_plugin.cmo cool_plugin.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.ml > c2.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmo c2.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt aa.cmo c2.cmo bbcc.cma c3.cmo main.cmo cool_plugin.cmo -o main.byte
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o aa.cmx aa.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o bb.cmx bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c2.cmx c2.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o cc.cmx cc.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -a bb.cmx cc.cmx -o bbcc.cmxa
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c3.cmx c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o main.cmx main.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt aa.cmx c2.cmx bbcc.cmxa c3.cmx main.cmx -o main.native
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.mli > bb.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmi bb.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules bb.ml > bb.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o bb.cmo bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cc.ml > cc.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules aa.ml > aa.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o aa.cmo aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.mli > c2.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmi c2.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cc.cmo cc.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -a bb.cmo cc.cmo -o bbcc.cma
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules main.ml > main.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c3.ml > c3.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c3.cmo c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o main.cmo main.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules cool_plugin.ml > cool_plugin.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o cool_plugin.cmo cool_plugin.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules c2.ml > c2.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o c2.cmo c2.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt aa.cmo c2.cmo bbcc.cma c3.cmo main.cmo cool_plugin.cmo -o main.byte
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o bb.cmx bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o aa.cmx aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c2.cmx c2.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o cc.cmx cc.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -a bb.cmx cc.cmx -o bbcc.cmxa
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o c3.cmx c3.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o main.cmx main.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt aa.cmx c2.cmx bbcc.cmxa c3.cmx main.cmx -o main.native
+ _____ _ ___
+|_ _|__ ___| |_( _ )
+ | |/ _ \/ __| __/ _ \
+ | | __/\__ \ || (_) |
+ |_|\___||___/\__\___/
+
+ocamlbuild.cmx -o myocamlbuild
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules a.ml > a.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules myconfig.ml > myconfig.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o myconfig.cmo myconfig.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o a.cmo a.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt myconfig.cmo a.cmo -o a.byte
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o myconfig.cmx myconfig.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o a.cmx a.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt myconfig.cmx a.cmx -o a.native
+cp -p a.byte a
+cp -p a.native a.opt
+cp -p a.byte bin/a.byte
+cp -p bin/a.byte bin/a
+cp -p a.native bin/a.native
+cp -p bin/a.native bin/a.opt
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules a.ml > a.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules myconfig.ml > myconfig.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o myconfig.cmo myconfig.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -o a.cmo a.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt myconfig.cmo a.cmo -o a.byte
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o myconfig.cmx myconfig.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -o a.cmx a.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt myconfig.cmx a.cmx -o a.native
+[cache hit] cp -p a.byte a
+[cache hit] cp -p a.native a.opt
+[cache hit] cp -p a.byte bin/a.byte
+[cache hit] cp -p bin/a.byte bin/a
+[cache hit] cp -p a.native bin/a.native
+[cache hit] cp -p bin/a.native bin/a.opt
+ _____ _ ___
+|_ _|__ ___| |_ / _ \
+ | |/ _ \/ __| __| (_) |
+ | | __/\__ \ |_ \__, |
+ |_|\___||___/\__| /_/
+
+Globexp for "\"hello\"" OK
+Globexp for "<hello>" OK
+Globexp for "<hel*lo>" OK
+Globexp for "<a> and <b> or <c>" OK
+Globexp for "<a> titi" OK
+Glob.eval "<[a]>" "a" = true OK
+Glob.eval "<[a]>" "b" = false OK
+Glob.eval "<[a]>" "a" = true OK
+Glob.eval "<[a]>" "b" = false OK
+Glob.eval "<[a]>" "a" = true OK
+Glob.eval "<[a]>" "b" = false OK
+Glob.eval "<[a-z]>" "a" = true OK
+Glob.eval "<[a-z]>" "e" = true OK
+Glob.eval "<[a-z]>" "k" = true OK
+Glob.eval "<[a-z]>" "z" = true OK
+Glob.eval "<[a-z]>" "0" = false OK
+Glob.eval "<[a-z]>" "A" = false OK
+Glob.eval "<[a-z]>" "~" = false OK
+Glob.eval "<[a-z]>" "a" = true OK
+Glob.eval "<[a-z]>" "e" = true OK
+Glob.eval "<[a-z]>" "k" = true OK
+Glob.eval "<[a-z]>" "z" = true OK
+Glob.eval "<[a-z]>" "0" = false OK
+Glob.eval "<[a-z]>" "A" = false OK
+Glob.eval "<[a-z]>" "~" = false OK
+Glob.eval "<[a-z]>" "a" = true OK
+Glob.eval "<[a-z]>" "e" = true OK
+Glob.eval "<[a-z]>" "k" = true OK
+Glob.eval "<[a-z]>" "z" = true OK
+Glob.eval "<[a-z]>" "0" = false OK
+Glob.eval "<[a-z]>" "A" = false OK
+Glob.eval "<[a-z]>" "~" = false OK
+Glob.eval "<[a-z][0-9]>" "a0" = true OK
+Glob.eval "<[a-z][0-9]>" "b9" = true OK
+Glob.eval "<[a-z][0-9]>" "a00" = false OK
+Glob.eval "<[a-z][0-9]>" "a0a" = false OK
+Glob.eval "<[a-z][0-9]>" "b0a" = false OK
+Glob.eval "<[a-z][0-9]>" "isduis" = false OK
+Glob.eval "<[a-z][0-9]>" "" = false OK
+Glob.eval "<[a-z][0-9]>" "a0" = true OK
+Glob.eval "<[a-z][0-9]>" "b9" = true OK
+Glob.eval "<[a-z][0-9]>" "a00" = false OK
+Glob.eval "<[a-z][0-9]>" "a0a" = false OK
+Glob.eval "<[a-z][0-9]>" "b0a" = false OK
+Glob.eval "<[a-z][0-9]>" "isduis" = false OK
+Glob.eval "<[a-z][0-9]>" "" = false OK
+Glob.eval "<[a-z][0-9]>" "a0" = true OK
+Glob.eval "<[a-z][0-9]>" "b9" = true OK
+Glob.eval "<[a-z][0-9]>" "a00" = false OK
+Glob.eval "<[a-z][0-9]>" "a0a" = false OK
+Glob.eval "<[a-z][0-9]>" "b0a" = false OK
+Glob.eval "<[a-z][0-9]>" "isduis" = false OK
+Glob.eval "<[a-z][0-9]>" "" = false OK
+Glob.eval "<hello>" "hello" = true OK
+Glob.eval "<hello>" "helli" = false OK
+Glob.eval "<hello>" "hello" = true OK
+Glob.eval "<hello>" "helli" = false OK
+Glob.eval "<hello>" "hello" = true OK
+Glob.eval "<hello>" "helli" = false OK
+Glob.eval "\"hello\"" "hello" = true OK
+Glob.eval "\"hello\"" "heidi" = false OK
+Glob.eval "\"hello\"" "hello" = true OK
+Glob.eval "\"hello\"" "heidi" = false OK
+Glob.eval "\"hello\"" "hello" = true OK
+Glob.eval "\"hello\"" "heidi" = false OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "ax" = true OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "ax" = true OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "ax" = true OK
+Glob.eval "<a*b>" "ab" = true OK
+Glob.eval "<a*b>" "acb" = true OK
+Glob.eval "<a*b>" "axxxxxb" = true OK
+Glob.eval "<a*b>" "ababbababb" = true OK
+Glob.eval "<a*b>" "abx" = false OK
+Glob.eval "<a*b>" "xxxxxab" = false OK
+Glob.eval "<a*b>" "xab" = false OK
+Glob.eval "<a*b>" "ab" = true OK
+Glob.eval "<a*b>" "acb" = true OK
+Glob.eval "<a*b>" "axxxxxb" = true OK
+Glob.eval "<a*b>" "ababbababb" = true OK
+Glob.eval "<a*b>" "abx" = false OK
+Glob.eval "<a*b>" "xxxxxab" = false OK
+Glob.eval "<a*b>" "xab" = false OK
+Glob.eval "<a*b>" "ab" = true OK
+Glob.eval "<a*b>" "acb" = true OK
+Glob.eval "<a*b>" "axxxxxb" = true OK
+Glob.eval "<a*b>" "ababbababb" = true OK
+Glob.eval "<a*b>" "abx" = false OK
+Glob.eval "<a*b>" "xxxxxab" = false OK
+Glob.eval "<a*b>" "xab" = false OK
+Glob.eval "<*.ml>" "hello.ml" = true OK
+Glob.eval "<*.ml>" ".ml" = true OK
+Glob.eval "<*.ml>" "ml" = false OK
+Glob.eval "<*.ml>" "" = false OK
+Glob.eval "<*.ml>" "toto.mli" = false OK
+Glob.eval "<*.ml>" "hello.ml" = true OK
+Glob.eval "<*.ml>" ".ml" = true OK
+Glob.eval "<*.ml>" "ml" = false OK
+Glob.eval "<*.ml>" "" = false OK
+Glob.eval "<*.ml>" "toto.mli" = false OK
+Glob.eval "<*.ml>" "hello.ml" = true OK
+Glob.eval "<*.ml>" ".ml" = true OK
+Glob.eval "<*.ml>" "ml" = false OK
+Glob.eval "<*.ml>" "" = false OK
+Glob.eval "<*.ml>" "toto.mli" = false OK
+Glob.eval "<a>" "a" = true OK
+Glob.eval "<a>" "" = false OK
+Glob.eval "<a>" "aa" = false OK
+Glob.eval "<a>" "ba" = false OK
+Glob.eval "<a>" "ab" = false OK
+Glob.eval "<a>" "abaa" = false OK
+Glob.eval "<a>" "a" = true OK
+Glob.eval "<a>" "" = false OK
+Glob.eval "<a>" "aa" = false OK
+Glob.eval "<a>" "ba" = false OK
+Glob.eval "<a>" "ab" = false OK
+Glob.eval "<a>" "abaa" = false OK
+Glob.eval "<a>" "a" = true OK
+Glob.eval "<a>" "" = false OK
+Glob.eval "<a>" "aa" = false OK
+Glob.eval "<a>" "ba" = false OK
+Glob.eval "<a>" "ab" = false OK
+Glob.eval "<a>" "abaa" = false OK
+Glob.eval "<ab>" "ab" = true OK
+Glob.eval "<ab>" "" = false OK
+Glob.eval "<ab>" "abab" = false OK
+Glob.eval "<ab>" "aba" = false OK
+Glob.eval "<ab>" "abx" = false OK
+Glob.eval "<ab>" "ab" = true OK
+Glob.eval "<ab>" "" = false OK
+Glob.eval "<ab>" "abab" = false OK
+Glob.eval "<ab>" "aba" = false OK
+Glob.eval "<ab>" "abx" = false OK
+Glob.eval "<ab>" "ab" = true OK
+Glob.eval "<ab>" "" = false OK
+Glob.eval "<ab>" "abab" = false OK
+Glob.eval "<ab>" "aba" = false OK
+Glob.eval "<ab>" "abx" = false OK
+Glob.eval "<ab?c>" "abac" = true OK
+Glob.eval "<ab?c>" "abxc" = true OK
+Glob.eval "<ab?c>" "abab" = false OK
+Glob.eval "<ab?c>" "ababab" = false OK
+Glob.eval "<ab?c>" "ababa" = false OK
+Glob.eval "<ab?c>" "abac" = true OK
+Glob.eval "<ab?c>" "abxc" = true OK
+Glob.eval "<ab?c>" "abab" = false OK
+Glob.eval "<ab?c>" "ababab" = false OK
+Glob.eval "<ab?c>" "ababa" = false OK
+Glob.eval "<ab?c>" "abac" = true OK
+Glob.eval "<ab?c>" "abxc" = true OK
+Glob.eval "<ab?c>" "abab" = false OK
+Glob.eval "<ab?c>" "ababab" = false OK
+Glob.eval "<ab?c>" "ababa" = false OK
+Glob.eval "<*ab?cd*>" "123abecd345" = true OK
+Glob.eval "<*ab?cd*>" "abccd" = true OK
+Glob.eval "<*ab?cd*>" "abccd345" = true OK
+Glob.eval "<*ab?cd*>" "ababcababccdab" = true OK
+Glob.eval "<*ab?cd*>" "abcd" = false OK
+Glob.eval "<*ab?cd*>" "aaaaabcdababcd" = false OK
+Glob.eval "<*ab?cd*>" "123abecd345" = true OK
+Glob.eval "<*ab?cd*>" "abccd" = true OK
+Glob.eval "<*ab?cd*>" "abccd345" = true OK
+Glob.eval "<*ab?cd*>" "ababcababccdab" = true OK
+Glob.eval "<*ab?cd*>" "abcd" = false OK
+Glob.eval "<*ab?cd*>" "aaaaabcdababcd" = false OK
+Glob.eval "<*ab?cd*>" "123abecd345" = true OK
+Glob.eval "<*ab?cd*>" "abccd" = true OK
+Glob.eval "<*ab?cd*>" "abccd345" = true OK
+Glob.eval "<*ab?cd*>" "ababcababccdab" = true OK
+Glob.eval "<*ab?cd*>" "abcd" = false OK
+Glob.eval "<*ab?cd*>" "aaaaabcdababcd" = false OK
+Glob.eval "<*this*is*a*test*>" "this is a test" = true OK
+Glob.eval "<*this*is*a*test*>" "You know this is a test really" = true OK
+Glob.eval "<*this*is*a*test*>" "thisisatest" = true OK
+Glob.eval "<*this*is*a*test*>" "thisatest" = false OK
+Glob.eval "<*this*is*a*test*>" "this is a test" = true OK
+Glob.eval "<*this*is*a*test*>" "You know this is a test really" = true OK
+Glob.eval "<*this*is*a*test*>" "thisisatest" = true OK
+Glob.eval "<*this*is*a*test*>" "thisatest" = false OK
+Glob.eval "<*this*is*a*test*>" "this is a test" = true OK
+Glob.eval "<*this*is*a*test*>" "You know this is a test really" = true OK
+Glob.eval "<*this*is*a*test*>" "thisisatest" = true OK
+Glob.eval "<*this*is*a*test*>" "thisatest" = false OK
+Glob.eval "<b*>" "bxx" = true OK
+Glob.eval "<b*>" "bx" = true OK
+Glob.eval "<b*>" "aaab" = false OK
+Glob.eval "<b*>" "" = false OK
+Glob.eval "<b*>" "bxx" = true OK
+Glob.eval "<b*>" "bx" = true OK
+Glob.eval "<b*>" "aaab" = false OK
+Glob.eval "<b*>" "" = false OK
+Glob.eval "<b*>" "bxx" = true OK
+Glob.eval "<b*>" "bx" = true OK
+Glob.eval "<b*>" "aaab" = false OK
+Glob.eval "<b*>" "" = false OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "aaa" = true OK
+Glob.eval "<*>" "aaaaa" = true OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "aaa" = true OK
+Glob.eval "<*>" "aaaaa" = true OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "aaa" = true OK
+Glob.eval "<*>" "aaaaa" = true OK
+Glob.eval "<?>" "a" = true OK
+Glob.eval "<?>" "" = false OK
+Glob.eval "<?>" "aaa" = false OK
+Glob.eval "<?>" "aaaaa" = false OK
+Glob.eval "<?>" "a" = true OK
+Glob.eval "<?>" "" = false OK
+Glob.eval "<?>" "aaa" = false OK
+Glob.eval "<?>" "aaaaa" = false OK
+Glob.eval "<?>" "a" = true OK
+Glob.eval "<?>" "" = false OK
+Glob.eval "<?>" "aaa" = false OK
+Glob.eval "<?>" "aaaaa" = false OK
+Glob.eval "<{a,b}>" "a" = true OK
+Glob.eval "<{a,b}>" "b" = true OK
+Glob.eval "<{a,b}>" "" = false OK
+Glob.eval "<{a,b}>" "aa" = false OK
+Glob.eval "<{a,b}>" "ab" = false OK
+Glob.eval "<{a,b}>" "ba" = false OK
+Glob.eval "<{a,b}>" "bb" = false OK
+Glob.eval "<{a,b}>" "c" = false OK
+Glob.eval "<{a,b}>" "a" = true OK
+Glob.eval "<{a,b}>" "b" = true OK
+Glob.eval "<{a,b}>" "" = false OK
+Glob.eval "<{a,b}>" "aa" = false OK
+Glob.eval "<{a,b}>" "ab" = false OK
+Glob.eval "<{a,b}>" "ba" = false OK
+Glob.eval "<{a,b}>" "bb" = false OK
+Glob.eval "<{a,b}>" "c" = false OK
+Glob.eval "<{a,b}>" "a" = true OK
+Glob.eval "<{a,b}>" "b" = true OK
+Glob.eval "<{a,b}>" "" = false OK
+Glob.eval "<{a,b}>" "aa" = false OK
+Glob.eval "<{a,b}>" "ab" = false OK
+Glob.eval "<{a,b}>" "ba" = false OK
+Glob.eval "<{a,b}>" "bb" = false OK
+Glob.eval "<{a,b}>" "c" = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.ml" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto.mli" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto." = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.mll" = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.ml" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto.mli" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto." = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.mll" = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.ml" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto.mli" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto." = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.mll" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aeg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "beg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "afg" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "af" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aee" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aeg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "beg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "afg" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "af" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aee" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aeg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "beg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "afg" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "af" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aee" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "b.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "hello.ml" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli.x" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "b.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "hello.ml" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli.x" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "b.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "hello.ml" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli.x" = false OK
+Glob.eval "<*>" "alpha" = true OK
+Glob.eval "<*>" "beta" = true OK
+Glob.eval "<*>" "alpha/beta" = false OK
+Glob.eval "<*>" "gamma/delta" = false OK
+Glob.eval "<*>" "alpha" = true OK
+Glob.eval "<*>" "beta" = true OK
+Glob.eval "<*>" "alpha/beta" = false OK
+Glob.eval "<*>" "gamma/delta" = false OK
+Glob.eval "<*>" "alpha" = true OK
+Glob.eval "<*>" "beta" = true OK
+Glob.eval "<*>" "alpha/beta" = false OK
+Glob.eval "<*>" "gamma/delta" = false OK
+Glob.eval "<alpha/**/beta>" "alpha/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/delta/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha" = false OK
+Glob.eval "<alpha/**/beta>" "beta" = false OK
+Glob.eval "<alpha/**/beta>" "gamma/delta" = false OK
+Glob.eval "<alpha/**/beta>" "alpha/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/delta/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha" = false OK
+Glob.eval "<alpha/**/beta>" "beta" = false OK
+Glob.eval "<alpha/**/beta>" "gamma/delta" = false OK
+Glob.eval "<alpha/**/beta>" "alpha/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/delta/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha" = false OK
+Glob.eval "<alpha/**/beta>" "beta" = false OK
+Glob.eval "<alpha/**/beta>" "gamma/delta" = false OK
+Glob.eval "<**/*.ml>" "toto.ml" = true OK
+Glob.eval "<**/*.ml>" "toto/tata.ml" = true OK
+Glob.eval "<**/*.ml>" "alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<**/*.ml>" "toto.mli" = false OK
+Glob.eval "<**/*.ml>" "toto.ml" = true OK
+Glob.eval "<**/*.ml>" "toto/tata.ml" = true OK
+Glob.eval "<**/*.ml>" "alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<**/*.ml>" "toto.mli" = false OK
+Glob.eval "<**/*.ml>" "toto.ml" = true OK
+Glob.eval "<**/*.ml>" "toto/tata.ml" = true OK
+Glob.eval "<**/*.ml>" "alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<**/*.ml>" "toto.mli" = false OK
+Glob.eval "<toto/**>" "toto/" = true OK
+Glob.eval "<toto/**>" "toto/tata" = true OK
+Glob.eval "<toto/**>" "toto/alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<toto/**>" "toto" = true OK
+Glob.eval "<toto/**>" "toto2/tata" = false OK
+Glob.eval "<toto/**>" "tata/titi" = false OK
+Glob.eval "<toto/**>" "toto/" = true OK
+Glob.eval "<toto/**>" "toto/tata" = true OK
+Glob.eval "<toto/**>" "toto/alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<toto/**>" "toto" = true OK
+Glob.eval "<toto/**>" "toto2/tata" = false OK
+Glob.eval "<toto/**>" "tata/titi" = false OK
+Glob.eval "<toto/**>" "toto/" = true OK
+Glob.eval "<toto/**>" "toto/tata" = true OK
+Glob.eval "<toto/**>" "toto/alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<toto/**>" "toto" = true OK
+Glob.eval "<toto/**>" "toto2/tata" = false OK
+Glob.eval "<toto/**>" "tata/titi" = false OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/bar/libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibs/unix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibsliblib/unlibix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/libfoo/boo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "bar" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libbar/foo.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.b.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/bar/libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibs/unix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibsliblib/unlibix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/libfoo/boo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "bar" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libbar/foo.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.b.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/bar/libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibs/unix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibsliblib/unlibix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/libfoo/boo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "bar" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libbar/foo.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.b.a" = None OK
+ _____ _ _ ___
+|_ _|__ ___| |_/ |/ _ \
+ | |/ _ \/ __| __| | | | |
+ | | __/\__ \ |_| | |_| |
+ |_|\___||___/\__|_|\___/
+
+Globexp for "\"hello\"" OK
+Globexp for "<hello>" OK
+Globexp for "<hel*lo>" OK
+Globexp for "<a> and <b> or <c>" OK
+Globexp for "<a> titi" OK
+Glob.eval "<[a]>" "a" = true OK
+Glob.eval "<[a]>" "b" = false OK
+Glob.eval "<[a]>" "a" = true OK
+Glob.eval "<[a]>" "b" = false OK
+Glob.eval "<[a]>" "a" = true OK
+Glob.eval "<[a]>" "b" = false OK
+Glob.eval "<[a-z]>" "a" = true OK
+Glob.eval "<[a-z]>" "e" = true OK
+Glob.eval "<[a-z]>" "k" = true OK
+Glob.eval "<[a-z]>" "z" = true OK
+Glob.eval "<[a-z]>" "0" = false OK
+Glob.eval "<[a-z]>" "A" = false OK
+Glob.eval "<[a-z]>" "~" = false OK
+Glob.eval "<[a-z]>" "a" = true OK
+Glob.eval "<[a-z]>" "e" = true OK
+Glob.eval "<[a-z]>" "k" = true OK
+Glob.eval "<[a-z]>" "z" = true OK
+Glob.eval "<[a-z]>" "0" = false OK
+Glob.eval "<[a-z]>" "A" = false OK
+Glob.eval "<[a-z]>" "~" = false OK
+Glob.eval "<[a-z]>" "a" = true OK
+Glob.eval "<[a-z]>" "e" = true OK
+Glob.eval "<[a-z]>" "k" = true OK
+Glob.eval "<[a-z]>" "z" = true OK
+Glob.eval "<[a-z]>" "0" = false OK
+Glob.eval "<[a-z]>" "A" = false OK
+Glob.eval "<[a-z]>" "~" = false OK
+Glob.eval "<[a-z][0-9]>" "a0" = true OK
+Glob.eval "<[a-z][0-9]>" "b9" = true OK
+Glob.eval "<[a-z][0-9]>" "a00" = false OK
+Glob.eval "<[a-z][0-9]>" "a0a" = false OK
+Glob.eval "<[a-z][0-9]>" "b0a" = false OK
+Glob.eval "<[a-z][0-9]>" "isduis" = false OK
+Glob.eval "<[a-z][0-9]>" "" = false OK
+Glob.eval "<[a-z][0-9]>" "a0" = true OK
+Glob.eval "<[a-z][0-9]>" "b9" = true OK
+Glob.eval "<[a-z][0-9]>" "a00" = false OK
+Glob.eval "<[a-z][0-9]>" "a0a" = false OK
+Glob.eval "<[a-z][0-9]>" "b0a" = false OK
+Glob.eval "<[a-z][0-9]>" "isduis" = false OK
+Glob.eval "<[a-z][0-9]>" "" = false OK
+Glob.eval "<[a-z][0-9]>" "a0" = true OK
+Glob.eval "<[a-z][0-9]>" "b9" = true OK
+Glob.eval "<[a-z][0-9]>" "a00" = false OK
+Glob.eval "<[a-z][0-9]>" "a0a" = false OK
+Glob.eval "<[a-z][0-9]>" "b0a" = false OK
+Glob.eval "<[a-z][0-9]>" "isduis" = false OK
+Glob.eval "<[a-z][0-9]>" "" = false OK
+Glob.eval "<hello>" "hello" = true OK
+Glob.eval "<hello>" "helli" = false OK
+Glob.eval "<hello>" "hello" = true OK
+Glob.eval "<hello>" "helli" = false OK
+Glob.eval "<hello>" "hello" = true OK
+Glob.eval "<hello>" "helli" = false OK
+Glob.eval "\"hello\"" "hello" = true OK
+Glob.eval "\"hello\"" "heidi" = false OK
+Glob.eval "\"hello\"" "hello" = true OK
+Glob.eval "\"hello\"" "heidi" = false OK
+Glob.eval "\"hello\"" "hello" = true OK
+Glob.eval "\"hello\"" "heidi" = false OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "ax" = true OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "ax" = true OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "ax" = true OK
+Glob.eval "<a*b>" "ab" = true OK
+Glob.eval "<a*b>" "acb" = true OK
+Glob.eval "<a*b>" "axxxxxb" = true OK
+Glob.eval "<a*b>" "ababbababb" = true OK
+Glob.eval "<a*b>" "abx" = false OK
+Glob.eval "<a*b>" "xxxxxab" = false OK
+Glob.eval "<a*b>" "xab" = false OK
+Glob.eval "<a*b>" "ab" = true OK
+Glob.eval "<a*b>" "acb" = true OK
+Glob.eval "<a*b>" "axxxxxb" = true OK
+Glob.eval "<a*b>" "ababbababb" = true OK
+Glob.eval "<a*b>" "abx" = false OK
+Glob.eval "<a*b>" "xxxxxab" = false OK
+Glob.eval "<a*b>" "xab" = false OK
+Glob.eval "<a*b>" "ab" = true OK
+Glob.eval "<a*b>" "acb" = true OK
+Glob.eval "<a*b>" "axxxxxb" = true OK
+Glob.eval "<a*b>" "ababbababb" = true OK
+Glob.eval "<a*b>" "abx" = false OK
+Glob.eval "<a*b>" "xxxxxab" = false OK
+Glob.eval "<a*b>" "xab" = false OK
+Glob.eval "<*.ml>" "hello.ml" = true OK
+Glob.eval "<*.ml>" ".ml" = true OK
+Glob.eval "<*.ml>" "ml" = false OK
+Glob.eval "<*.ml>" "" = false OK
+Glob.eval "<*.ml>" "toto.mli" = false OK
+Glob.eval "<*.ml>" "hello.ml" = true OK
+Glob.eval "<*.ml>" ".ml" = true OK
+Glob.eval "<*.ml>" "ml" = false OK
+Glob.eval "<*.ml>" "" = false OK
+Glob.eval "<*.ml>" "toto.mli" = false OK
+Glob.eval "<*.ml>" "hello.ml" = true OK
+Glob.eval "<*.ml>" ".ml" = true OK
+Glob.eval "<*.ml>" "ml" = false OK
+Glob.eval "<*.ml>" "" = false OK
+Glob.eval "<*.ml>" "toto.mli" = false OK
+Glob.eval "<a>" "a" = true OK
+Glob.eval "<a>" "" = false OK
+Glob.eval "<a>" "aa" = false OK
+Glob.eval "<a>" "ba" = false OK
+Glob.eval "<a>" "ab" = false OK
+Glob.eval "<a>" "abaa" = false OK
+Glob.eval "<a>" "a" = true OK
+Glob.eval "<a>" "" = false OK
+Glob.eval "<a>" "aa" = false OK
+Glob.eval "<a>" "ba" = false OK
+Glob.eval "<a>" "ab" = false OK
+Glob.eval "<a>" "abaa" = false OK
+Glob.eval "<a>" "a" = true OK
+Glob.eval "<a>" "" = false OK
+Glob.eval "<a>" "aa" = false OK
+Glob.eval "<a>" "ba" = false OK
+Glob.eval "<a>" "ab" = false OK
+Glob.eval "<a>" "abaa" = false OK
+Glob.eval "<ab>" "ab" = true OK
+Glob.eval "<ab>" "" = false OK
+Glob.eval "<ab>" "abab" = false OK
+Glob.eval "<ab>" "aba" = false OK
+Glob.eval "<ab>" "abx" = false OK
+Glob.eval "<ab>" "ab" = true OK
+Glob.eval "<ab>" "" = false OK
+Glob.eval "<ab>" "abab" = false OK
+Glob.eval "<ab>" "aba" = false OK
+Glob.eval "<ab>" "abx" = false OK
+Glob.eval "<ab>" "ab" = true OK
+Glob.eval "<ab>" "" = false OK
+Glob.eval "<ab>" "abab" = false OK
+Glob.eval "<ab>" "aba" = false OK
+Glob.eval "<ab>" "abx" = false OK
+Glob.eval "<ab?c>" "abac" = true OK
+Glob.eval "<ab?c>" "abxc" = true OK
+Glob.eval "<ab?c>" "abab" = false OK
+Glob.eval "<ab?c>" "ababab" = false OK
+Glob.eval "<ab?c>" "ababa" = false OK
+Glob.eval "<ab?c>" "abac" = true OK
+Glob.eval "<ab?c>" "abxc" = true OK
+Glob.eval "<ab?c>" "abab" = false OK
+Glob.eval "<ab?c>" "ababab" = false OK
+Glob.eval "<ab?c>" "ababa" = false OK
+Glob.eval "<ab?c>" "abac" = true OK
+Glob.eval "<ab?c>" "abxc" = true OK
+Glob.eval "<ab?c>" "abab" = false OK
+Glob.eval "<ab?c>" "ababab" = false OK
+Glob.eval "<ab?c>" "ababa" = false OK
+Glob.eval "<*ab?cd*>" "123abecd345" = true OK
+Glob.eval "<*ab?cd*>" "abccd" = true OK
+Glob.eval "<*ab?cd*>" "abccd345" = true OK
+Glob.eval "<*ab?cd*>" "ababcababccdab" = true OK
+Glob.eval "<*ab?cd*>" "abcd" = false OK
+Glob.eval "<*ab?cd*>" "aaaaabcdababcd" = false OK
+Glob.eval "<*ab?cd*>" "123abecd345" = true OK
+Glob.eval "<*ab?cd*>" "abccd" = true OK
+Glob.eval "<*ab?cd*>" "abccd345" = true OK
+Glob.eval "<*ab?cd*>" "ababcababccdab" = true OK
+Glob.eval "<*ab?cd*>" "abcd" = false OK
+Glob.eval "<*ab?cd*>" "aaaaabcdababcd" = false OK
+Glob.eval "<*ab?cd*>" "123abecd345" = true OK
+Glob.eval "<*ab?cd*>" "abccd" = true OK
+Glob.eval "<*ab?cd*>" "abccd345" = true OK
+Glob.eval "<*ab?cd*>" "ababcababccdab" = true OK
+Glob.eval "<*ab?cd*>" "abcd" = false OK
+Glob.eval "<*ab?cd*>" "aaaaabcdababcd" = false OK
+Glob.eval "<*this*is*a*test*>" "this is a test" = true OK
+Glob.eval "<*this*is*a*test*>" "You know this is a test really" = true OK
+Glob.eval "<*this*is*a*test*>" "thisisatest" = true OK
+Glob.eval "<*this*is*a*test*>" "thisatest" = false OK
+Glob.eval "<*this*is*a*test*>" "this is a test" = true OK
+Glob.eval "<*this*is*a*test*>" "You know this is a test really" = true OK
+Glob.eval "<*this*is*a*test*>" "thisisatest" = true OK
+Glob.eval "<*this*is*a*test*>" "thisatest" = false OK
+Glob.eval "<*this*is*a*test*>" "this is a test" = true OK
+Glob.eval "<*this*is*a*test*>" "You know this is a test really" = true OK
+Glob.eval "<*this*is*a*test*>" "thisisatest" = true OK
+Glob.eval "<*this*is*a*test*>" "thisatest" = false OK
+Glob.eval "<b*>" "bxx" = true OK
+Glob.eval "<b*>" "bx" = true OK
+Glob.eval "<b*>" "aaab" = false OK
+Glob.eval "<b*>" "" = false OK
+Glob.eval "<b*>" "bxx" = true OK
+Glob.eval "<b*>" "bx" = true OK
+Glob.eval "<b*>" "aaab" = false OK
+Glob.eval "<b*>" "" = false OK
+Glob.eval "<b*>" "bxx" = true OK
+Glob.eval "<b*>" "bx" = true OK
+Glob.eval "<b*>" "aaab" = false OK
+Glob.eval "<b*>" "" = false OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "aaa" = true OK
+Glob.eval "<*>" "aaaaa" = true OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "aaa" = true OK
+Glob.eval "<*>" "aaaaa" = true OK
+Glob.eval "<*>" "" = true OK
+Glob.eval "<*>" "a" = true OK
+Glob.eval "<*>" "aaa" = true OK
+Glob.eval "<*>" "aaaaa" = true OK
+Glob.eval "<?>" "a" = true OK
+Glob.eval "<?>" "" = false OK
+Glob.eval "<?>" "aaa" = false OK
+Glob.eval "<?>" "aaaaa" = false OK
+Glob.eval "<?>" "a" = true OK
+Glob.eval "<?>" "" = false OK
+Glob.eval "<?>" "aaa" = false OK
+Glob.eval "<?>" "aaaaa" = false OK
+Glob.eval "<?>" "a" = true OK
+Glob.eval "<?>" "" = false OK
+Glob.eval "<?>" "aaa" = false OK
+Glob.eval "<?>" "aaaaa" = false OK
+Glob.eval "<{a,b}>" "a" = true OK
+Glob.eval "<{a,b}>" "b" = true OK
+Glob.eval "<{a,b}>" "" = false OK
+Glob.eval "<{a,b}>" "aa" = false OK
+Glob.eval "<{a,b}>" "ab" = false OK
+Glob.eval "<{a,b}>" "ba" = false OK
+Glob.eval "<{a,b}>" "bb" = false OK
+Glob.eval "<{a,b}>" "c" = false OK
+Glob.eval "<{a,b}>" "a" = true OK
+Glob.eval "<{a,b}>" "b" = true OK
+Glob.eval "<{a,b}>" "" = false OK
+Glob.eval "<{a,b}>" "aa" = false OK
+Glob.eval "<{a,b}>" "ab" = false OK
+Glob.eval "<{a,b}>" "ba" = false OK
+Glob.eval "<{a,b}>" "bb" = false OK
+Glob.eval "<{a,b}>" "c" = false OK
+Glob.eval "<{a,b}>" "a" = true OK
+Glob.eval "<{a,b}>" "b" = true OK
+Glob.eval "<{a,b}>" "" = false OK
+Glob.eval "<{a,b}>" "aa" = false OK
+Glob.eval "<{a,b}>" "ab" = false OK
+Glob.eval "<{a,b}>" "ba" = false OK
+Glob.eval "<{a,b}>" "bb" = false OK
+Glob.eval "<{a,b}>" "c" = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.ml" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto.mli" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto." = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.mll" = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.ml" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto.mli" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto." = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.mll" = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.ml" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto.mli" = true OK
+Glob.eval "<toto.{ml,mli}>" "toto." = false OK
+Glob.eval "<toto.{ml,mli}>" "toto.mll" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aeg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "beg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "afg" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "af" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aee" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aeg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "beg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "afg" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "af" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aee" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "acg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "adg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aeg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bcg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdf" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bdg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "bef" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "beg" = true OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "afg" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "af" = false OK
+Glob.eval "<{a,b}{c,[de]}{f,g}>" "aee" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "b.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "hello.ml" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli.x" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "b.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "hello.ml" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli.x" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "b.ml" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli" = true OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "hello.ml" = false OK
+Glob.eval "(<*.ml> or <*.mli>) and not \"hello.ml\"" "a.mli.x" = false OK
+Glob.eval "<*>" "alpha" = true OK
+Glob.eval "<*>" "beta" = true OK
+Glob.eval "<*>" "alpha/beta" = false OK
+Glob.eval "<*>" "gamma/delta" = false OK
+Glob.eval "<*>" "alpha" = true OK
+Glob.eval "<*>" "beta" = true OK
+Glob.eval "<*>" "alpha/beta" = false OK
+Glob.eval "<*>" "gamma/delta" = false OK
+Glob.eval "<*>" "alpha" = true OK
+Glob.eval "<*>" "beta" = true OK
+Glob.eval "<*>" "alpha/beta" = false OK
+Glob.eval "<*>" "gamma/delta" = false OK
+Glob.eval "<alpha/**/beta>" "alpha/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/delta/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha" = false OK
+Glob.eval "<alpha/**/beta>" "beta" = false OK
+Glob.eval "<alpha/**/beta>" "gamma/delta" = false OK
+Glob.eval "<alpha/**/beta>" "alpha/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/delta/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha" = false OK
+Glob.eval "<alpha/**/beta>" "beta" = false OK
+Glob.eval "<alpha/**/beta>" "gamma/delta" = false OK
+Glob.eval "<alpha/**/beta>" "alpha/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha/gamma/delta/beta" = true OK
+Glob.eval "<alpha/**/beta>" "alpha" = false OK
+Glob.eval "<alpha/**/beta>" "beta" = false OK
+Glob.eval "<alpha/**/beta>" "gamma/delta" = false OK
+Glob.eval "<**/*.ml>" "toto.ml" = true OK
+Glob.eval "<**/*.ml>" "toto/tata.ml" = true OK
+Glob.eval "<**/*.ml>" "alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<**/*.ml>" "toto.mli" = false OK
+Glob.eval "<**/*.ml>" "toto.ml" = true OK
+Glob.eval "<**/*.ml>" "toto/tata.ml" = true OK
+Glob.eval "<**/*.ml>" "alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<**/*.ml>" "toto.mli" = false OK
+Glob.eval "<**/*.ml>" "toto.ml" = true OK
+Glob.eval "<**/*.ml>" "toto/tata.ml" = true OK
+Glob.eval "<**/*.ml>" "alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<**/*.ml>" "toto.mli" = false OK
+Glob.eval "<toto/**>" "toto/" = true OK
+Glob.eval "<toto/**>" "toto/tata" = true OK
+Glob.eval "<toto/**>" "toto/alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<toto/**>" "toto" = true OK
+Glob.eval "<toto/**>" "toto2/tata" = false OK
+Glob.eval "<toto/**>" "tata/titi" = false OK
+Glob.eval "<toto/**>" "toto/" = true OK
+Glob.eval "<toto/**>" "toto/tata" = true OK
+Glob.eval "<toto/**>" "toto/alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<toto/**>" "toto" = true OK
+Glob.eval "<toto/**>" "toto2/tata" = false OK
+Glob.eval "<toto/**>" "tata/titi" = false OK
+Glob.eval "<toto/**>" "toto/" = true OK
+Glob.eval "<toto/**>" "toto/tata" = true OK
+Glob.eval "<toto/**>" "toto/alpha/gamma/delta/beta.ml" = true OK
+Glob.eval "<toto/**>" "toto" = true OK
+Glob.eval "<toto/**>" "toto2/tata" = false OK
+Glob.eval "<toto/**>" "tata/titi" = false OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/bar/libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibs/unix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibsliblib/unlibix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/libfoo/boo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "bar" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libbar/foo.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.b.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/bar/libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibs/unix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibsliblib/unlibix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/libfoo/boo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "bar" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libbar/foo.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.b.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/bar/libfoo.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibs/unix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "otherlibsliblib/unlibix/libunix.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "src/libfoo/boo/libbar.a" OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "bar" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libbar/foo.a" = None OK
+Resource.matchit "%(path:<**/>)lib%(libname:<*> and not <*.*>).a" "libfoo.b.a" = None OK
+ _____ _ _ _
+|_ _|__ ___| |_/ / |
+ | |/ _ \/ __| __| | |
+ | | __/\__ \ |_| | |
+ |_|\___||___/\__|_|_|
+
+ocamlbuild.cmx -o myocamlbuild
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules a/aa.mli > a/aa.mli.depends
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -I a -I b -o a/aa.cmi a/aa.mli
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules a/aa.ml > a/aa.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules b/bb.ml > b/bb.ml.depends
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -I b -I a -o b/bb.cmo b/bb.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -I a -I b -o a/aa.cmo a/aa.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt -a b/bb.cmo -o b/libb.cma
+/home/danmey/src/ocaml-trunk/bin/ocamlc.opt b/libb.cma a/aa.cmo -o a/aa.byte
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -I b -I a -o b/bb.cmx b/bb.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -I a -I b -o a/aa.cmx a/aa.ml
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -a b/bb.cmx -o b/libb.cmxa
+/home/danmey/src/ocaml-trunk/bin/ocamlopt.opt b/libb.cmxa a/aa.cmx -o a/aa.native
+looks if libs are there
+_build/b/libb.a
+_build/b/libb.cma
+_build/b/libb.cmxa
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules a/aa.mli > a/aa.mli.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -I a -I b -o a/aa.cmi a/aa.mli
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules a/aa.ml > a/aa.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamldep.opt -modules b/bb.ml > b/bb.ml.depends
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -I b -I a -o b/bb.cmo b/bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -c -I a -I b -o a/aa.cmo a/aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt -a b/bb.cmo -o b/libb.cma
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlc.opt b/libb.cma a/aa.cmo -o a/aa.byte
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -I b -I a -o b/bb.cmx b/bb.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -c -I a -I b -o a/aa.cmx a/aa.ml
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt -a b/bb.cmx -o b/libb.cmxa
+[cache hit] /home/danmey/src/ocaml-trunk/bin/ocamlopt.opt b/libb.cmxa a/aa.cmx -o a/aa.native
+ _____ _ _ ____
+|_ _|__ ___| |_/ |___ \
+ | |/ _ \/ __| __| | __) |
+ | | __/\__ \ |_| |/ __/
+ |_|\___||___/\__|_|_____|
+
+ocamldep.opt -modules Main.ml > Main.ml.depends
+Packed.ml.depends
+Lib.mli.depends
+Lib.mli
+Packed.ml
+Packed.cmo -o Pack.cmo
+ocamlc.opt -c -I lib -o Main.cmo Main.ml
+Lib.ml.depends
+Lib.ml
+Packed.ml
+Packed.cmx -o Pack.cmx ; then rm -f Pack.mli ; else rm -f Pack.mli ; exit 1; fi
+ocamlopt.opt -c -I lib -o Main.cmx Main.ml
+Lib.cmx Pack.cmx Main.cmx -o Main.native
+Lib.ml
+Lib.cmo Pack.cmo Main.cmo -o Main.byte
+looks if executable are there
+_build/Main.byte
+_build/Main.byte
+_build/Main.native
+ _____ _ __ ___ _ _
+|_ _|__ ___| |_ \ \ / (_)_ __| |_ _ _ __ _| |
+ | |/ _ \/ __| __| \ \ / /| | '__| __| | | |/ _` | |
+ | | __/\__ \ |_ \ V / | | | | |_| |_| | (_| | |
+ |_|\___||___/\__| \_/ |_|_| \__|\__,_|\__,_|_|
+
+ _____ _
+|_ _|_ _ _ __ __ _ ___| |_ ___
+ | |/ _` | '__/ _` |/ _ \ __/ __|
+ | | (_| | | | (_| | __/ |_\__ \
+ |_|\__,_|_| \__, |\___|\__|___/
+ |___/
diff --git a/ocamlbuild/test/runtest.sh b/ocamlbuild/test/runtest.sh
new file mode 100755
index 0000000000..600f4232f9
--- /dev/null
+++ b/ocamlbuild/test/runtest.sh
@@ -0,0 +1,56 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+set -e
+cd `dirname $0`
+
+export OCB=$PWD/../../_build/ocamlbuild/ocamlbuild.native
+
+myfiglet() {
+ figlet $@ | sed 's/ *$//'
+}
+
+if figlet ""; then
+ BANNER=myfiglet
+else
+ echo "Install figlet to have a better output, press enter to continue with echo"
+ read
+ BANNER=echo
+fi
+
+HERE=`pwd`
+
+$BANNER Test2
+./test2/test.sh $@
+$BANNER Test3
+./test3/test.sh $@
+$BANNER Test4
+./test4/test.sh $@
+$BANNER Test5
+./test5/test.sh $@
+$BANNER Test6
+./test6/test.sh $@
+$BANNER Test7
+./test7/test.sh $@
+$BANNER Test8
+./test8/test.sh $@
+$BANNER Test9
+./test9/test.sh $@
+$BANNER Test10
+./test10/test.sh $@
+$BANNER Test11
+./test11/test.sh $@
+$BANNER Test12
+./test12/test.sh $@
+$BANNER Test Virtual Targets
+./test_virtual/test.sh $@
diff --git a/ocamlbuild/test/test1/foo.ml b/ocamlbuild/test/test1/foo.ml
new file mode 100644
index 0000000000..795ff9d065
--- /dev/null
+++ b/ocamlbuild/test/test1/foo.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+module MA1 = A1
diff --git a/ocamlbuild/test/test10/dbdi b/ocamlbuild/test/test10/dbdi
new file mode 100644
index 0000000000..a6b9972867
--- /dev/null
+++ b/ocamlbuild/test/test10/dbdi
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+#load "discard_printf.cmo";;
+#load "debug.cmo";;
+#load "unix.cma";;
+#load "str.cma";;
+#load "my_unix.cmo";;
+#load "bool.cmo";;
+#load "glob_ast.cmo";;
+#load "glob_lexer.cmo";;
+#load "glob.cmo";;
+#load "lexers.cmo";;
+#load "my_std.cmo";;
+#load "tags.cmo";;
diff --git a/ocamlbuild/test/test10/test.sh b/ocamlbuild/test/test10/test.sh
new file mode 100755
index 0000000000..2ff2340466
--- /dev/null
+++ b/ocamlbuild/test/test10/test.sh
@@ -0,0 +1,18 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+set -e
+set -x
+cd `dirname $0`/../..
+$OCB -quiet -build-dir _buildtest -no-links test/test9/testglob.native
+./_buildtest/test/test9/testglob.native
diff --git a/ocamlbuild/test/test11/_tags b/ocamlbuild/test/test11/_tags
new file mode 100644
index 0000000000..8238743251
--- /dev/null
+++ b/ocamlbuild/test/test11/_tags
@@ -0,0 +1,14 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# a comment
+"a/aa.byte" or "a/aa.native": use_libb
diff --git a/ocamlbuild/test/test11/a/aa.ml b/ocamlbuild/test/test11/a/aa.ml
new file mode 100644
index 0000000000..80743d641c
--- /dev/null
+++ b/ocamlbuild/test/test11/a/aa.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let bar = 3 + List.length Bb.foo
diff --git a/ocamlbuild/test/test11/a/aa.mli b/ocamlbuild/test/test11/a/aa.mli
new file mode 100644
index 0000000000..37f2be3d29
--- /dev/null
+++ b/ocamlbuild/test/test11/a/aa.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val bar : int
diff --git a/ocamlbuild/test/test11/b/bb.ml b/ocamlbuild/test/test11/b/bb.ml
new file mode 100644
index 0000000000..a1aaf7048e
--- /dev/null
+++ b/ocamlbuild/test/test11/b/bb.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let foo = [2.2]
diff --git a/ocamlbuild/test/test11/b/libb.mllib b/ocamlbuild/test/test11/b/libb.mllib
new file mode 100644
index 0000000000..d0acbb7049
--- /dev/null
+++ b/ocamlbuild/test/test11/b/libb.mllib
@@ -0,0 +1 @@
+Bb
diff --git a/ocamlbuild/test/test11/myocamlbuild.ml b/ocamlbuild/test/test11/myocamlbuild.ml
new file mode 100644
index 0000000000..49c4c47776
--- /dev/null
+++ b/ocamlbuild/test/test11/myocamlbuild.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Ocamlbuild_plugin;;
+dispatch begin function
+| After_rules -> ocaml_lib "b/libb"
+| _ -> ()
+end
diff --git a/ocamlbuild/test/test11/test.sh b/ocamlbuild/test/test11/test.sh
new file mode 100755
index 0000000000..989d051d59
--- /dev/null
+++ b/ocamlbuild/test/test11/test.sh
@@ -0,0 +1,25 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -e
+set -x
+CMDOTPS="" # -- command args
+BUILD="$OCB -I a -I b aa.byte aa.native -no-skip -classic-display $@"
+BUILD1="$BUILD $CMDOPTS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDOPTS"
+rm -rf _build
+$BUILD1
+echo looks if libs are there
+ls _build/b/libb.cma _build/b/libb.cmxa _build/b/libb.a
+$BUILD2
diff --git a/ocamlbuild/test/test2/_tags b/ocamlbuild/test/test2/_tags
new file mode 100644
index 0000000000..5db645057e
--- /dev/null
+++ b/ocamlbuild/test/test2/_tags
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+"vivi.ml": camlp4o
+
+# , some_useless_tag, \ more_useless_tags
diff --git a/ocamlbuild/test/test2/tata.ml b/ocamlbuild/test/test2/tata.ml
new file mode 100644
index 0000000000..6dfbc15cff
--- /dev/null
+++ b/ocamlbuild/test/test2/tata.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let tata = "TATA2"
diff --git a/ocamlbuild/test/test2/tata.mli b/ocamlbuild/test/test2/tata.mli
new file mode 100644
index 0000000000..9c7a359dab
--- /dev/null
+++ b/ocamlbuild/test/test2/tata.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* a comment *)
+val tata : string
diff --git a/ocamlbuild/test/test2/test.sh b/ocamlbuild/test/test2/test.sh
new file mode 100755
index 0000000000..0843ce42e8
--- /dev/null
+++ b/ocamlbuild/test/test2/test.sh
@@ -0,0 +1,30 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -e
+set -x
+CMDOPTS="-- -help"
+BUILD="$OCB toto.byte toto.native -no-skip -classic-display $@"
+BUILD1="$BUILD $CMDOPTS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDOPTS"
+rm -rf _build
+cp vivi1.ml vivi.ml
+$BUILD1
+$BUILD2
+cp vivi2.ml vivi.ml
+$BUILD1
+$BUILD2
+cp vivi3.ml vivi.ml
+$BUILD1
+$BUILD2
diff --git a/ocamlbuild/test/test2/titi.ml b/ocamlbuild/test/test2/titi.ml
new file mode 100644
index 0000000000..5fda26b5ec
--- /dev/null
+++ b/ocamlbuild/test/test2/titi.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let titi = []
diff --git a/ocamlbuild/test/test2/toto.ml b/ocamlbuild/test/test2/toto.ml
new file mode 100644
index 0000000000..5068ece013
--- /dev/null
+++ b/ocamlbuild/test/test2/toto.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let i = Tutu.tutu + 10
+let s = Tata.tata ^ ".ml"
+let l = 3 :: Titi.titi
+let () = Format.printf "toto.native: %s: Hello world!!!@." Sys.argv.(0)
+let () = Format.printf "Tutu.tutu => %d@.Tata.tata => %S@." Tutu.tutu Tata.tata
diff --git a/ocamlbuild/test/test2/tutu.ml b/ocamlbuild/test/test2/tutu.ml
new file mode 100644
index 0000000000..a0d5b7b06f
--- /dev/null
+++ b/ocamlbuild/test/test2/tutu.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let tutu = (Array.length Vivi.vivi : Tyty.t)
+let tutu' = 2.0 +. float_of_int tutu
diff --git a/ocamlbuild/test/test2/tutu.mli b/ocamlbuild/test/test2/tutu.mli
new file mode 100644
index 0000000000..20ce76f510
--- /dev/null
+++ b/ocamlbuild/test/test2/tutu.mli
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* a comment *)
+val tutu : int
+val tutu' : float
diff --git a/ocamlbuild/test/test2/tyty.mli b/ocamlbuild/test/test2/tyty.mli
new file mode 100644
index 0000000000..52d1609ae3
--- /dev/null
+++ b/ocamlbuild/test/test2/tyty.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type t = int
diff --git a/ocamlbuild/test/test2/vivi1.ml b/ocamlbuild/test/test2/vivi1.ml
new file mode 100644
index 0000000000..3faa2b54dc
--- /dev/null
+++ b/ocamlbuild/test/test2/vivi1.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let rec p i = [< '1; '2; p (i + 1) >]
+let vivi = [|2|]
diff --git a/ocamlbuild/test/test2/vivi2.ml b/ocamlbuild/test/test2/vivi2.ml
new file mode 100644
index 0000000000..c0b69eaf34
--- /dev/null
+++ b/ocamlbuild/test/test2/vivi2.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let rec p i = [< '1; '2; p (i + 1) >]
+let vivi = [|3|]
diff --git a/ocamlbuild/test/test2/vivi3.ml b/ocamlbuild/test/test2/vivi3.ml
new file mode 100644
index 0000000000..a79d1a24f5
--- /dev/null
+++ b/ocamlbuild/test/test2/vivi3.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let rec p i = [< '1; '2; p (i + 1) >]
+let vivi = [|2.1; 1.1|]
diff --git a/ocamlbuild/test/test3/_tags b/ocamlbuild/test/test3/_tags
new file mode 100644
index 0000000000..b2018471f8
--- /dev/null
+++ b/ocamlbuild/test/test3/_tags
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+"a.byte" or "a.native": use_unix
diff --git a/ocamlbuild/test/test3/a.ml b/ocamlbuild/test/test3/a.ml
new file mode 100644
index 0000000000..5ffc0f5344
--- /dev/null
+++ b/ocamlbuild/test/test3/a.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+module X = B
diff --git a/ocamlbuild/test/test3/a.mli b/ocamlbuild/test/test3/a.mli
new file mode 100644
index 0000000000..233331b956
--- /dev/null
+++ b/ocamlbuild/test/test3/a.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Nothing *)
diff --git a/ocamlbuild/test/test3/b.ml b/ocamlbuild/test/test3/b.ml
new file mode 100644
index 0000000000..3fec55f039
--- /dev/null
+++ b/ocamlbuild/test/test3/b.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+module X = C
diff --git a/ocamlbuild/test/test3/b.mli b/ocamlbuild/test/test3/b.mli
new file mode 100644
index 0000000000..e42c41ecc9
--- /dev/null
+++ b/ocamlbuild/test/test3/b.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* nothing *)
diff --git a/ocamlbuild/test/test3/c.ml b/ocamlbuild/test/test3/c.ml
new file mode 100644
index 0000000000..15fadc4474
--- /dev/null
+++ b/ocamlbuild/test/test3/c.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+module X = D
diff --git a/ocamlbuild/test/test3/c.mli b/ocamlbuild/test/test3/c.mli
new file mode 100644
index 0000000000..e42c41ecc9
--- /dev/null
+++ b/ocamlbuild/test/test3/c.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* nothing *)
diff --git a/ocamlbuild/test/test3/d.ml b/ocamlbuild/test/test3/d.ml
new file mode 100644
index 0000000000..a5caf20272
--- /dev/null
+++ b/ocamlbuild/test/test3/d.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+module X = E
diff --git a/ocamlbuild/test/test3/d.mli b/ocamlbuild/test/test3/d.mli
new file mode 100644
index 0000000000..e42c41ecc9
--- /dev/null
+++ b/ocamlbuild/test/test3/d.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* nothing *)
diff --git a/ocamlbuild/test/test3/e.ml b/ocamlbuild/test/test3/e.ml
new file mode 100644
index 0000000000..e2456c0e06
--- /dev/null
+++ b/ocamlbuild/test/test3/e.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+module X = F
diff --git a/ocamlbuild/test/test3/e.mli b/ocamlbuild/test/test3/e.mli
new file mode 100644
index 0000000000..e42c41ecc9
--- /dev/null
+++ b/ocamlbuild/test/test3/e.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* nothing *)
diff --git a/ocamlbuild/test/test3/f.ml b/ocamlbuild/test/test3/f.ml
new file mode 100644
index 0000000000..d7b7d6d523
--- /dev/null
+++ b/ocamlbuild/test/test3/f.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* nothing *)
+let _ = Unix.stat
diff --git a/ocamlbuild/test/test3/f.mli b/ocamlbuild/test/test3/f.mli
new file mode 100644
index 0000000000..e42c41ecc9
--- /dev/null
+++ b/ocamlbuild/test/test3/f.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* nothing *)
diff --git a/ocamlbuild/test/test3/proj.odocl b/ocamlbuild/test/test3/proj.odocl
new file mode 100644
index 0000000000..532c720382
--- /dev/null
+++ b/ocamlbuild/test/test3/proj.odocl
@@ -0,0 +1 @@
+A B C D E F
diff --git a/ocamlbuild/test/test3/test.sh b/ocamlbuild/test/test3/test.sh
new file mode 100755
index 0000000000..d3b28526a2
--- /dev/null
+++ b/ocamlbuild/test/test3/test.sh
@@ -0,0 +1,23 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -e
+set -x
+CMDOTPS="" # -- command args
+BUILD="$OCB a.byte a.native proj.docdir/index.html -no-skip -classic-display $@"
+BUILD1="$BUILD $CMDOPTS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDOPTS"
+rm -rf _build
+$BUILD1
+$BUILD2
diff --git a/ocamlbuild/test/test4/_tags b/ocamlbuild/test/test4/_tags
new file mode 100644
index 0000000000..f381c675c3
--- /dev/null
+++ b/ocamlbuild/test/test4/_tags
@@ -0,0 +1,14 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# a comment
+"a/aa.byte" or "a/aa.native": use_str
diff --git a/ocamlbuild/test/test4/a/aa.ml b/ocamlbuild/test/test4/a/aa.ml
new file mode 100644
index 0000000000..80743d641c
--- /dev/null
+++ b/ocamlbuild/test/test4/a/aa.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let bar = 3 + List.length Bb.foo
diff --git a/ocamlbuild/test/test4/a/aa.mli b/ocamlbuild/test/test4/a/aa.mli
new file mode 100644
index 0000000000..37f2be3d29
--- /dev/null
+++ b/ocamlbuild/test/test4/a/aa.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val bar : int
diff --git a/ocamlbuild/test/test4/b/bb.ml b/ocamlbuild/test/test4/b/bb.ml
new file mode 100644
index 0000000000..c0d8f16b2b
--- /dev/null
+++ b/ocamlbuild/test/test4/b/bb.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let r = Str.regexp "r"
+let foo = [2.2]
diff --git a/ocamlbuild/test/test4/test.sh b/ocamlbuild/test/test4/test.sh
new file mode 100755
index 0000000000..46b7129db4
--- /dev/null
+++ b/ocamlbuild/test/test4/test.sh
@@ -0,0 +1,23 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -e
+set -x
+CMDOTPS="" # -- command args
+BUILD="$OCB -I a -I b aa.byte aa.native -no-skip -classic-display $@"
+BUILD1="$BUILD $CMDOPTS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDOPTS"
+rm -rf _build
+$BUILD1
+$BUILD2
diff --git a/ocamlbuild/test/test5/_tags b/ocamlbuild/test/test5/_tags
new file mode 100644
index 0000000000..daa80725fc
--- /dev/null
+++ b/ocamlbuild/test/test5/_tags
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+"a.cmx" or "b.cmx": for-pack(C)
diff --git a/ocamlbuild/test/test5/a.ml b/ocamlbuild/test/test5/a.ml
new file mode 100644
index 0000000000..7df1aae824
--- /dev/null
+++ b/ocamlbuild/test/test5/a.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let a = 42 + Stack.stack
diff --git a/ocamlbuild/test/test5/a.mli b/ocamlbuild/test/test5/a.mli
new file mode 100644
index 0000000000..d91e2c24c7
--- /dev/null
+++ b/ocamlbuild/test/test5/a.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val a : int
diff --git a/ocamlbuild/test/test5/b.ml b/ocamlbuild/test/test5/b.ml
new file mode 100644
index 0000000000..d7e1afcead
--- /dev/null
+++ b/ocamlbuild/test/test5/b.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let b = A.a + 1
diff --git a/ocamlbuild/test/test5/c.mlpack b/ocamlbuild/test/test5/c.mlpack
new file mode 100644
index 0000000000..5decc2b6a1
--- /dev/null
+++ b/ocamlbuild/test/test5/c.mlpack
@@ -0,0 +1 @@
+A B
diff --git a/ocamlbuild/test/test5/d.ml b/ocamlbuild/test/test5/d.ml
new file mode 100644
index 0000000000..fcb8108266
--- /dev/null
+++ b/ocamlbuild/test/test5/d.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+Format.printf "C.B.b = %d@." C.B.b
diff --git a/ocamlbuild/test/test5/stack.ml b/ocamlbuild/test/test5/stack.ml
new file mode 100644
index 0000000000..d7cea9194a
--- /dev/null
+++ b/ocamlbuild/test/test5/stack.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let stack = 42
diff --git a/ocamlbuild/test/test5/test.sh b/ocamlbuild/test/test5/test.sh
new file mode 100755
index 0000000000..30bba5ced4
--- /dev/null
+++ b/ocamlbuild/test/test5/test.sh
@@ -0,0 +1,23 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -e
+set -x
+CMDOPTS="" # -- command args
+BUILD="$OCB d.byte d.native -no-skip -classic-display $@"
+BUILD1="$BUILD $CMDOPTS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDOPTS"
+rm -rf _build
+$BUILD1
+$BUILD2
diff --git a/ocamlbuild/test/test6/a.ml b/ocamlbuild/test/test6/a.ml
new file mode 100644
index 0000000000..704730cef8
--- /dev/null
+++ b/ocamlbuild/test/test6/a.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let a = B.b
diff --git a/ocamlbuild/test/test6/a.mli b/ocamlbuild/test/test6/a.mli
new file mode 100644
index 0000000000..7d4c14febc
--- /dev/null
+++ b/ocamlbuild/test/test6/a.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val a : 'a -> 'a
diff --git a/ocamlbuild/test/test6/b.ml b/ocamlbuild/test/test6/b.ml
new file mode 100644
index 0000000000..5f207c88b7
--- /dev/null
+++ b/ocamlbuild/test/test6/b.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let b = D.d
diff --git a/ocamlbuild/test/test6/b.mli b/ocamlbuild/test/test6/b.mli
new file mode 100644
index 0000000000..1a3cf3f769
--- /dev/null
+++ b/ocamlbuild/test/test6/b.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val b : 'a -> 'a
diff --git a/ocamlbuild/test/test6/b.mli.v1 b/ocamlbuild/test/test6/b.mli.v1
new file mode 100644
index 0000000000..1a3cf3f769
--- /dev/null
+++ b/ocamlbuild/test/test6/b.mli.v1
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val b : 'a -> 'a
diff --git a/ocamlbuild/test/test6/b.mli.v2 b/ocamlbuild/test/test6/b.mli.v2
new file mode 100644
index 0000000000..5eaf77b602
--- /dev/null
+++ b/ocamlbuild/test/test6/b.mli.v2
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+....
+val b : 'a -> 'a
diff --git a/ocamlbuild/test/test6/d.ml b/ocamlbuild/test/test6/d.ml
new file mode 100644
index 0000000000..e8d7072906
--- /dev/null
+++ b/ocamlbuild/test/test6/d.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type t
+let d x = x
diff --git a/ocamlbuild/test/test6/d.mli b/ocamlbuild/test/test6/d.mli
new file mode 100644
index 0000000000..9cedf8dc4d
--- /dev/null
+++ b/ocamlbuild/test/test6/d.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val d : 'a -> 'a
diff --git a/ocamlbuild/test/test6/d.mli.v1 b/ocamlbuild/test/test6/d.mli.v1
new file mode 100644
index 0000000000..59d6c1a9b0
--- /dev/null
+++ b/ocamlbuild/test/test6/d.mli.v1
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type t
+val d : 'a -> 'a
diff --git a/ocamlbuild/test/test6/d.mli.v2 b/ocamlbuild/test/test6/d.mli.v2
new file mode 100644
index 0000000000..9cedf8dc4d
--- /dev/null
+++ b/ocamlbuild/test/test6/d.mli.v2
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val d : 'a -> 'a
diff --git a/ocamlbuild/test/test6/main.ml b/ocamlbuild/test/test6/main.ml
new file mode 100644
index 0000000000..8fada0a9a0
--- /dev/null
+++ b/ocamlbuild/test/test6/main.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+A.a 2. +. D.d 1.
diff --git a/ocamlbuild/test/test6/main.mli b/ocamlbuild/test/test6/main.mli
new file mode 100644
index 0000000000..e42c41ecc9
--- /dev/null
+++ b/ocamlbuild/test/test6/main.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* nothing *)
diff --git a/ocamlbuild/test/test6/test.sh b/ocamlbuild/test/test6/test.sh
new file mode 100755
index 0000000000..8fb2e67ef3
--- /dev/null
+++ b/ocamlbuild/test/test6/test.sh
@@ -0,0 +1,37 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -x
+rm -rf _build
+CMDOPTS="" # -- command args
+BUILD="$OCB -no-skip main.byte -classic-display $@"
+BUILD1="$BUILD $CMDOPTS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDOPTS"
+cp b.mli.v1 b.mli
+cp d.mli.v1 d.mli
+$BUILD1
+$BUILD2
+cp b.mli.v2 b.mli
+cp d.mli.v2 d.mli
+$BUILD1
+cp b.mli.v1 b.mli
+if $BUILD1; then
+ if $BUILD2; then
+ echo PASS
+ else
+ echo "FAIL (-nothing-should-be-rebuilt)"
+ fi
+else
+ echo FAIL
+fi
diff --git a/ocamlbuild/test/test7/_tags b/ocamlbuild/test/test7/_tags
new file mode 100644
index 0000000000..ec07803c1c
--- /dev/null
+++ b/ocamlbuild/test/test7/_tags
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+"main.byte": my_cool_plugin
diff --git a/ocamlbuild/test/test7/aa.ml b/ocamlbuild/test/test7/aa.ml
new file mode 100644
index 0000000000..bc3936a5ff
--- /dev/null
+++ b/ocamlbuild/test/test7/aa.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let aa = "aa"
diff --git a/ocamlbuild/test/test7/bb.mli b/ocamlbuild/test/test7/bb.mli
new file mode 100644
index 0000000000..a6c660bee5
--- /dev/null
+++ b/ocamlbuild/test/test7/bb.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val bb : int
diff --git a/ocamlbuild/test/test7/bb1.ml b/ocamlbuild/test/test7/bb1.ml
new file mode 100644
index 0000000000..1a0b5b2395
--- /dev/null
+++ b/ocamlbuild/test/test7/bb1.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let bb = 43
diff --git a/ocamlbuild/test/test7/bb2.ml b/ocamlbuild/test/test7/bb2.ml
new file mode 100644
index 0000000000..7ae282463e
--- /dev/null
+++ b/ocamlbuild/test/test7/bb2.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let bb = 43
+let f x = x + 1
+let () = incr (ref 0)
diff --git a/ocamlbuild/test/test7/bb3.ml b/ocamlbuild/test/test7/bb3.ml
new file mode 100644
index 0000000000..f852d37e3f
--- /dev/null
+++ b/ocamlbuild/test/test7/bb3.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let bb = 43
+let f x = x + 1
+let () = incr (ref 1)
diff --git a/ocamlbuild/test/test7/bbcc.mllib b/ocamlbuild/test/test7/bbcc.mllib
new file mode 100644
index 0000000000..a97a0e6c2a
--- /dev/null
+++ b/ocamlbuild/test/test7/bbcc.mllib
@@ -0,0 +1 @@
+Bb Cc
diff --git a/ocamlbuild/test/test7/c2.ml b/ocamlbuild/test/test7/c2.ml
new file mode 100644
index 0000000000..a593545ff6
--- /dev/null
+++ b/ocamlbuild/test/test7/c2.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let c2 = 12
diff --git a/ocamlbuild/test/test7/c2.mli b/ocamlbuild/test/test7/c2.mli
new file mode 100644
index 0000000000..0cf2d5a094
--- /dev/null
+++ b/ocamlbuild/test/test7/c2.mli
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val c2 : int
diff --git a/ocamlbuild/test/test7/c3.ml b/ocamlbuild/test/test7/c3.ml
new file mode 100644
index 0000000000..cc5bf85184
--- /dev/null
+++ b/ocamlbuild/test/test7/c3.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let c3 = Bb.bb + 13
diff --git a/ocamlbuild/test/test7/cc.ml b/ocamlbuild/test/test7/cc.ml
new file mode 100644
index 0000000000..e8c9088ab8
--- /dev/null
+++ b/ocamlbuild/test/test7/cc.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let cc = (String.length Aa.aa) + Bb.bb + C2.c2
diff --git a/ocamlbuild/test/test7/cool_plugin.ml b/ocamlbuild/test/test7/cool_plugin.ml
new file mode 100644
index 0000000000..b40e56ffd0
--- /dev/null
+++ b/ocamlbuild/test/test7/cool_plugin.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+print_endline "I am a cool plugin"
diff --git a/ocamlbuild/test/test7/main.ml b/ocamlbuild/test/test7/main.ml
new file mode 100644
index 0000000000..0907dbe4bb
--- /dev/null
+++ b/ocamlbuild/test/test7/main.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let main = String.length Aa.aa - Bb.bb - C3.c3 - Cc.cc - 1
diff --git a/ocamlbuild/test/test7/myocamlbuild.ml b/ocamlbuild/test/test7/myocamlbuild.ml
new file mode 100644
index 0000000000..77b4385062
--- /dev/null
+++ b/ocamlbuild/test/test7/myocamlbuild.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Ocamlbuild_plugin;;
+dispatch begin function
+| After_rules ->
+ use_lib "main" "bbcc";
+ dep ["ocaml"; "link"; "byte"; "my_cool_plugin"] ["cool_plugin.cmo"];
+| _ -> ()
+end
diff --git a/ocamlbuild/test/test7/test.sh b/ocamlbuild/test/test7/test.sh
new file mode 100755
index 0000000000..1d4eb1b595
--- /dev/null
+++ b/ocamlbuild/test/test7/test.sh
@@ -0,0 +1,30 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -e
+set -x
+CMDOPTS="" # -- command args
+BUILD="$OCB bbcc.cma main.byte bbcc.cmxa main.native -no-skip -classic-display $@"
+BUILD1="$BUILD $CMDARGS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDARGS"
+rm -rf _build
+cp bb1.ml bb.ml
+$BUILD1
+$BUILD2
+cp bb2.ml bb.ml
+$BUILD1 -verbose 0
+$BUILD2
+cp bb3.ml bb.ml
+$BUILD1 -verbose 0
+$BUILD2
diff --git a/ocamlbuild/test/test8/a.ml b/ocamlbuild/test/test8/a.ml
new file mode 100644
index 0000000000..3cd87f4013
--- /dev/null
+++ b/ocamlbuild/test/test8/a.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+print_endline Myconfig.version;;
diff --git a/ocamlbuild/test/test8/myocamlbuild.ml b/ocamlbuild/test/test8/myocamlbuild.ml
new file mode 100644
index 0000000000..9441a286c2
--- /dev/null
+++ b/ocamlbuild/test/test8/myocamlbuild.ml
@@ -0,0 +1,29 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Ocamlbuild_plugin;;
+let version = "0.1";;
+dispatch begin function
+ | After_rules ->
+ rule "myconfig.ml"
+ ~prod:"myconfig.ml"
+ begin fun _ _ ->
+ Echo(["let version = \""; version; "\";;\n"], "myconfig.ml")
+ end;
+
+ copy_rule "copy byte-code executables" "%(path).byte" "%(path:not <**/*.*>)";
+ copy_rule "copy native executables" "%(path).native" "%(path:not <**/*.*>).opt";
+ copy_rule "copy binaries to bin" "%(basename).%(extension)"
+ "bin/%(basename).%(extension:<{byte,native}>)";
+ | _ -> ()
+end
diff --git a/ocamlbuild/test/test8/test.sh b/ocamlbuild/test/test8/test.sh
new file mode 100755
index 0000000000..9b57933c65
--- /dev/null
+++ b/ocamlbuild/test/test8/test.sh
@@ -0,0 +1,23 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -e
+set -x
+CMDOPTS="" # -- command args
+BUILD="$OCB a.byte a.native a a.opt bin/a bin/a.opt -no-skip -classic-display $@"
+BUILD1="$BUILD $CMDOPTS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDOPTS"
+rm -rf _build
+$BUILD1
+$BUILD2
diff --git a/ocamlbuild/test/test9/dbgl b/ocamlbuild/test/test9/dbgl
new file mode 100644
index 0000000000..78290948e0
--- /dev/null
+++ b/ocamlbuild/test/test9/dbgl
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+#load "unix.cma";;
+#load "str.cma";;
+#load "discard_printf.cmo";;
+#load "debug.cmo";;
+#load "bool.cmo";;
+#load "glob_ast.cmo";;
+#load "glob_lexer.cmo";;
+#load "my_unix.cmo";;
+#use "glob.ml";;
+#install_printer print_is;;
diff --git a/ocamlbuild/test/test9/test.sh b/ocamlbuild/test/test9/test.sh
new file mode 100755
index 0000000000..aaed954c29
--- /dev/null
+++ b/ocamlbuild/test/test9/test.sh
@@ -0,0 +1,18 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+set -e
+set -x
+cd `dirname $0`/../..
+$OCB -quiet -build-dir _buildtest -no-links test/test9/testglob.native $@
+./_buildtest/test/test9/testglob.native
diff --git a/ocamlbuild/test/test9/testglob.ml b/ocamlbuild/test/test9/testglob.ml
new file mode 100644
index 0000000000..092ba9fe36
--- /dev/null
+++ b/ocamlbuild/test/test9/testglob.ml
@@ -0,0 +1,147 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Testglob *)
+
+open Bool;;
+open Glob;;
+
+let yep f x =
+ try
+ ignore (f x);
+ true
+ with
+ | _ -> false
+;;
+
+let tests1 = [
+ "\"hello\"", true;
+ "<hello>", true;
+ "<hel*lo>", true;
+ "<a> and <b> or <c>", true;
+ "<a> titi", false
+];;
+
+let tests2 = [
+ "<[a]>", ["a"], ["b"];
+ "<[a-z]>", ["a";"e";"k";"z"], ["0";"A";"~"];
+ "<[a-z][0-9]>", ["a0";"b9"], ["a00";"a0a";"b0a";"isduis";""];
+ "<hello>", ["hello"], ["helli"];
+ "\"hello\"", ["hello"], ["heidi"];
+ "<*>", ["";"a";"ax"], [];
+ "<a*b>", ["ab";"acb";"axxxxxb";"ababbababb"], ["abx";"xxxxxab";"xab"];
+ "<*.ml>", ["hello.ml";".ml"], ["ml"; ""; "toto.mli"];
+ "<a>", ["a"], ["";"aa";"ba";"ab";"abaa"];
+ "<ab>", ["ab"], ["";"abab";"aba";"abx"];
+ "<ab?c>", ["abac";"abxc"], ["abab";"ababab";"ababa"];
+ "<*ab?cd*>", ["123abecd345";"abccd";"abccd345";"ababcababccdab"], ["abcd";"aaaaabcdababcd"];
+ "<*this*is*a*test*>", ["this is a test";"You know this is a test really";"thisisatest"], ["thisatest"];
+ "<b*>", ["bxx";"bx"], ["aaab";""];
+ "<*>", ["";"a";"aaa";"aaaaa"], [];
+ "<?>", ["a"],["";"aaa";"aaaaa"];
+ "<{a,b}>", ["a";"b"],["";"aa";"ab";"ba";"bb";"c"];
+ "<toto.{ml,mli}>", ["toto.ml";"toto.mli"],["toto.";"toto.mll"];
+ "<{a,b}{c,[de]}{f,g}>", ["acf";"acg";"adf";"adg";"aef";"aeg";"bcf";"bcg";"bdf";"bdg";"bef";"beg"],
+ ["afg";"af";"aee"];
+ "(<*.ml> or <*.mli>) and not \"hello.ml\"",
+ ["a.ml"; "b.ml"; "a.mli"],
+ ["hello.ml"; "a.mli.x"];
+ "<*>", ["alpha";"beta"], ["alpha/beta";"gamma/delta"];
+ "<alpha/**/beta>", ["alpha/beta";"alpha/gamma/beta";"alpha/gamma/delta/beta"],
+ ["alpha";"beta";"gamma/delta"];
+ "<**/*.ml>", ["toto.ml";"toto/tata.ml";"alpha/gamma/delta/beta.ml"],
+ ["toto.mli"];
+ "<toto/**>", ["toto/";"toto/tata";"toto/alpha/gamma/delta/beta.ml";"toto"],
+ ["toto2/tata"; "tata/titi"]
+];;
+
+let tests3 = [
+ "%(path:<**/>)lib%(libname:<*> and not <*.*>).a",
+ ["libfoo.a","","foo";
+ "src/bar/libfoo.a","src/bar/","foo";
+ "otherlibs/unix/libunix.a","otherlibs/unix/","unix";
+ "otherlibsliblib/unlibix/libunix.a","otherlibsliblib/unlibix/","unix";
+ "libfoo/libbar.a","libfoo/","bar";
+ "src/libfoo/boo/libbar.a","src/libfoo/boo/","bar";
+ ],
+ ["bar"; "libbar/foo.a"; "libfoo.b.a"]
+];;
+
+let _ =
+ let times = 3 in
+ List.iter
+ begin fun (str, ast) ->
+ let ast' = yep Glob.parse str in
+ if ast <> ast' then
+ begin
+ Printf.printf "Globexp parsing failed for %S.\n%!" str;
+ exit 1
+ end
+ else
+ Printf.printf "Globexp for %S OK\n%!" str
+ end
+ tests1;
+ List.iter
+ begin fun (gstr, yes, no) ->
+ let globber = Glob.parse gstr in
+ let check polarity =
+ List.iter
+ begin fun y ->
+ if Glob.eval globber y = polarity then
+ Printf.printf "Glob.eval %S %S = %b OK\n%!" gstr y polarity
+ else
+ begin
+ Printf.printf "Glob.eval %S %S = %b FAIL\n%!" gstr y (not polarity);
+ exit 1
+ end
+ end
+ in
+ for k = 1 to times do
+ check true yes;
+ check false no
+ done
+ end
+ tests2;
+ List.iter begin fun (str, yes, no) ->
+ let resource = Resource.import_pattern str in
+ for k = 1 to times do
+ List.iter begin fun (y, path, libname) ->
+ let resource' = Resource.import y in
+ match Resource.matchit resource resource' with
+ | Some env ->
+ let path' = Resource.subst env "%(path)" in
+ let libname' = Resource.subst env "%(libname)" in
+ if path' = path && libname = libname' then
+ Printf.printf "Resource.matchit %S %S OK\n%!" str y
+ else begin
+ Printf.printf "Resource.matchit %S %S FAIL\n%!" str y;
+ exit 1
+ end
+ | None ->
+ begin
+ Printf.printf "Resource.matchit %S %S = None FAIL\n%!" str y;
+ exit 1
+ end
+ end yes;
+ List.iter begin fun y ->
+ let resource' = Resource.import y in
+ if Resource.matchit resource resource' = None then
+ Printf.printf "Resource.matchit %S %S = None OK\n%!" str y
+ else begin
+ Printf.printf "Resource.matchit %S %S <> None FAIL\n%!" str y;
+ exit 1
+ end
+ end no
+ done
+ end tests3
+;;
diff --git a/ocamlbuild/test/test_virtual/foo.itarget b/ocamlbuild/test/test_virtual/foo.itarget
new file mode 100644
index 0000000000..257cc5642c
--- /dev/null
+++ b/ocamlbuild/test/test_virtual/foo.itarget
@@ -0,0 +1 @@
+foo
diff --git a/ocamlbuild/test/test_virtual/foo1 b/ocamlbuild/test/test_virtual/foo1
new file mode 100644
index 0000000000..1715acd6a5
--- /dev/null
+++ b/ocamlbuild/test/test_virtual/foo1
@@ -0,0 +1 @@
+foo1
diff --git a/ocamlbuild/test/test_virtual/foo2 b/ocamlbuild/test/test_virtual/foo2
new file mode 100644
index 0000000000..54b060eee9
--- /dev/null
+++ b/ocamlbuild/test/test_virtual/foo2
@@ -0,0 +1 @@
+foo2
diff --git a/ocamlbuild/test/test_virtual/myocamlbuild.ml b/ocamlbuild/test/test_virtual/myocamlbuild.ml
new file mode 100644
index 0000000000..8d00602d4a
--- /dev/null
+++ b/ocamlbuild/test/test_virtual/myocamlbuild.ml
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Ocamlbuild_plugin;;
+dispatch begin function
+ | After_rules ->
+ rule "copy foo"
+ ~prod:"bar"
+ ~dep:"foo.otarget"
+ begin fun _env _build ->
+ cp "foo" "bar"
+ end
+ | _ -> ()
+end
diff --git a/ocamlbuild/test/test_virtual/test.sh b/ocamlbuild/test/test_virtual/test.sh
new file mode 100755
index 0000000000..9960c83f47
--- /dev/null
+++ b/ocamlbuild/test/test_virtual/test.sh
@@ -0,0 +1,28 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2007 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+#!/bin/sh
+cd `dirname $0`
+set -e
+set -x
+CMDOPTS="" # -- command args
+BUILD="$OCB bar -no-skip -classic-display $@"
+BUILD1="$BUILD $CMDOPTS"
+BUILD2="$BUILD -verbose 0 -nothing-should-be-rebuilt $CMDOPTS"
+rm -rf _build
+cp foo1 foo
+$BUILD1
+$BUILD2
+cp foo2 foo
+$BUILD1 -verbose 0
+$BUILD2
+rm foo
diff --git a/ocamlbuild/testsuite/README b/ocamlbuild/testsuite/README
new file mode 100644
index 0000000000..08e68d908b
--- /dev/null
+++ b/ocamlbuild/testsuite/README
@@ -0,0 +1,13 @@
+The organization of tests is the following:
+
+- internal.ml contains the tests that should be runnable from a bare
+ OCaml installation -- always passing the -no-ocamlfind option.
+
+- findlibonly.ml contains the tests that should be runnable from a bare
+ OCaml installation, with only ocamlfind/findlib on top. The only
+ ocamlfind packages it relies over are those of the OCaml
+ distribution.
+
+- external.ml contains the tests that rely on other findlib packages
+ or external tools to run. Each test will only run if the findlib
+ package it depends on is present. \ No newline at end of file
diff --git a/ocamlbuild/testsuite/external.ml b/ocamlbuild/testsuite/external.ml
new file mode 100644
index 0000000000..ce8dc9e7c5
--- /dev/null
+++ b/ocamlbuild/testsuite/external.ml
@@ -0,0 +1,22 @@
+#use "internal_test_header.ml";;
+#use "findlibonly_test_header.ml";;
+#use "external_test_header.ml";;
+
+let () = test "SubtoolOptions"
+ ~description:"Options that come from tags that needs to be spliced \
+ to the subtool invocation (PR#5763)"
+ (* testing for the 'menhir' executable directly
+ is too hard to do in a portable way; test the ocamlfind package instead *)
+ ~requirements:(package_exists "menhirLib")
+ ~options:[`use_ocamlfind; `use_menhir; `tags["package\\(camlp4.fulllib\\)"]]
+ ~tree:[T.f "parser.mly"
+ ~content:"%{ %}
+ %token DUMMY
+ %start<Camlp4.PreCast.Syntax.Ast.expr option> test
+ %%
+ test: {None}"]
+ ~matching:[M.f "parser.native"; M.f "parser.byte"]
+ ~targets:("parser.native",["parser.byte"])
+ ();;
+
+run ~root:"_test_external";;
diff --git a/ocamlbuild/testsuite/external_test_header.ml b/ocamlbuild/testsuite/external_test_header.ml
new file mode 100644
index 0000000000..2b890e35e2
--- /dev/null
+++ b/ocamlbuild/testsuite/external_test_header.ml
@@ -0,0 +1,7 @@
+(* Fullfilled and Missing are defined in ocamlbuild_test.ml
+ Findlib was loaded in findlibonly_test_header.ml *)
+let package_exists package =
+ let open Findlib in
+ try ignore (package_directory package); Fullfilled
+ with No_such_package _ ->
+ Missing (Printf.sprintf "the ocamlfind package %s" package)
diff --git a/ocamlbuild/testsuite/findlibonly.ml b/ocamlbuild/testsuite/findlibonly.ml
new file mode 100644
index 0000000000..d159ad47b4
--- /dev/null
+++ b/ocamlbuild/testsuite/findlibonly.ml
@@ -0,0 +1,42 @@
+#use "internal_test_header.ml";;
+#use "findlibonly_test_header.ml";;
+
+let () = test "camlp4.opt"
+ ~description:"Fixes PR#5652"
+ ~options:[`package "camlp4.macro";`tags ["camlp4o.opt"; "syntax\\(camp4o\\)"];
+ `ppflag "camlp4o.opt"; `ppflag "-parser"; `ppflag "macro";
+ `ppflag "-DTEST"]
+ ~tree:[T.f "dummy.ml"
+ ~content:"IFDEF TEST THEN\nprint_endline \"Hello\";;\nENDIF;;"]
+ ~matching:[M.x "dummy.native" ~output:"Hello"]
+ ~targets:("dummy.native",[]) ();;
+
+let () = test "ThreadAndArchive"
+ ~description:"Fixes PR#6058"
+ ~options:[`use_ocamlfind; `package "threads"; `tag "thread"]
+ ~tree:[T.f "t.ml" ~content:""]
+ ~matching:[M.f "_build/t.cma"]
+ ~targets:("t.cma",[]) ();;
+
+let () = test "SyntaxFlag"
+ ~options:[`use_ocamlfind; `package "camlp4.macro"; `syntax "camlp4o"]
+ ~description:"-syntax for ocamlbuild"
+ ~tree:[T.f "dummy.ml" ~content:"IFDEF TEST THEN\nprint_endline \"Hello\";;\nENDIF;;"]
+ ~matching:[M.f "dummy.native"]
+ ~targets:("dummy.native",[]) ();;
+
+let () = test "PredicateFlag"
+ ~description:"ocamlfind ocamldep does not support the -predicate option"
+ ~options:[`use_ocamlfind; `tag "\"predicate(byte)\""]
+ ~tree:[T.f "test.ml" ~content:"let x = List.map"]
+ ~matching:[_build [M.f "test.ml.depends"]]
+ ~targets:("test.ml.depends", []) ();;
+
+let () = test "ToolsFlagsConflict"
+ ~description:"PR#6300: conflicts between -ocamlc and -use-ocamlfind options"
+ ~options:[`use_ocamlfind; `ocamlc "\"ocamlc -annot\""]
+ ~tree:[T.f "test.ml" ~content:"let x = 1"]
+ ~matching:[_build [M.f "test.annot"; M.f "test.byte"]]
+ ~targets:("test.byte", []) ();;
+
+run ~root:"_test_findlibonly";;
diff --git a/ocamlbuild/testsuite/findlibonly_test_header.ml b/ocamlbuild/testsuite/findlibonly_test_header.ml
new file mode 100644
index 0000000000..5b147820a0
--- /dev/null
+++ b/ocamlbuild/testsuite/findlibonly_test_header.ml
@@ -0,0 +1,9 @@
+match Sys.command "ocamlfind ocamlc" with
+ | 0 -> ()
+ | _ ->
+ prerr_endline "Having ocamlfind installed is a prerequisite \
+ for running these tests. Aborting.";
+ exit 1;
+;;
+
+#use "topfind";;
diff --git a/ocamlbuild/testsuite/internal.ml b/ocamlbuild/testsuite/internal.ml
new file mode 100644
index 0000000000..9b48af5273
--- /dev/null
+++ b/ocamlbuild/testsuite/internal.ml
@@ -0,0 +1,324 @@
+#use "internal_test_header.ml";;
+
+let () = test "BasicNativeTree"
+ ~options:[`no_ocamlfind]
+ ~description:"Output tree for native compilation"
+ ~tree:[T.f "dummy.ml"]
+ ~matching:[M.Exact
+ (_build
+ (M.lf
+ ["_digests";
+ "dummy.cmi";
+ "dummy.cmo";
+ "dummy.cmx";
+ "dummy.ml";
+ "dummy.ml.depends";
+ "dummy.native";
+ "dummy.o";
+ "_log"]))]
+ ~targets:("dummy.native",[]) ();;
+
+let () = test "BasicByteTree"
+ ~options:[`no_ocamlfind]
+ ~description:"Output tree for byte compilation"
+ ~tree:[T.f "dummy.ml"]
+ ~matching:[M.Exact
+ (_build
+ (M.lf
+ ["_digests";
+ "dummy.cmi";
+ "dummy.cmo";
+ "dummy.ml";
+ "dummy.ml.depends";
+ "dummy.byte";
+ "_log"]))]
+ ~targets:("dummy.byte",[]) ();;
+
+let () = test "SeveralTargets"
+ ~options:[`no_ocamlfind]
+ ~description:"Several targets"
+ ~tree:[T.f "dummy.ml"]
+ ~matching:[_build (M.lf ["dummy.byte"; "dummy.native"])]
+ ~targets:("dummy.byte",["dummy.native"]) ();;
+
+let alt_build_dir = "BuIlD2";;
+
+let () = test "BuildDir"
+ ~options:[`no_ocamlfind; `build_dir alt_build_dir]
+ ~description:"Different build directory"
+ ~tree:[T.f "dummy.ml"]
+ ~matching:[M.d alt_build_dir (M.lf ["dummy.byte"])]
+ ~targets:("dummy.byte",[]) ();;
+
+let tag_pat_msgs =
+ ["*:a", "File \"_tags\", line 1, characters 0-2:\n\
+ Lexing error: Invalid globbing pattern \"*\".";
+
+ "\n<*{>:a", "File \"_tags\", line 2, characters 0-5:\n\
+ Lexing error: Invalid globbing pattern \"<*{>\".";
+
+ "<*>: ~@a,# ~a", "File \"_tags\", line 1, characters 10-11:\n\
+ Lexing error: Only ',' separated tags are alllowed."];;
+
+List.iteri (fun i (content,failing_msg) ->
+ let () = test (Printf.sprintf "TagsErrorMessage_%d" (i+1))
+ ~options:[`no_ocamlfind]
+ ~description:"Confirm relevance of an error message due to erronous _tags"
+ ~failing_msg
+ ~tree:[T.f "_tags" ~content; T.f "dummy.ml"]
+ ~targets:("dummy.native",[]) ()
+ in ()) tag_pat_msgs;;
+
+let () = test "Itarget"
+ ~options:[`no_ocamlfind]
+ ~description:".itarget building with dependencies between the modules (PR#5686)"
+ ~tree:[T.f "foo.itarget" ~content:"a.cma\nb.byte\n"; T.f "a.ml"; T.f "b.ml" ~content:"open A\n"]
+ ~matching:[M.f "a.cma"; M.f "b.byte"]
+ ~targets:("foo.otarget",[]) ();;
+
+let () = test "PackAcross"
+ ~options:[`no_ocamlfind]
+ ~description:"Pack using a module from the other tree (PR#4592)"
+ ~tree:[T.f "main.ml" ~content:"let _ = Pack.Packed.g ()\n";
+ T.f "Pack.mlpack" ~content:"pack/Packed";
+ T.f "_tags" ~content:"<lib>: include\n<pack/*.cmx>: for-pack(Pack)\n";
+ T.d "lib" [T.f "Lib.ml" ~content:"let f()=()";
+ T.f "Lib.mli" ~content:"val f : unit -> unit"];
+ T.d "pack" [T.f "Packed.ml" ~content:"let g() = Lib.f ()"]]
+ ~matching:[M.f "main.byte"; M.f "main.native"]
+ ~targets:("main.byte", ["main.native"])
+ ();;
+
+let () = test "PackAcross2"
+ ~options:[`no_ocamlfind]
+ ~description:"Pack using a module from the other tree (PR#4592)"
+ ~tree:[T.f "a2.mli" ~content:"val f : unit -> unit";
+ T.f "a2.ml" ~content:"let f _ = ()";
+ T.f "lib.ml" ~content:"module A = A2";
+ T.f "b.ml" ~content:"let g = Lib.A.f";
+ T.f "sup.mlpack" ~content:"B";
+ T.f "prog.ml" ~content:"Sup.B.g"]
+ ~matching:[M.f "prog.byte"]
+ ~targets:("prog.byte",[]) ();;
+
+let () = test "PackAcross3"
+ ~options:[`no_ocamlfind]
+ ~description:"Pack using a module from the other tree (PR#4592)"
+ ~tree:[T.d "foo" [ T.f "bar.ml" ~content:"let baz = Quux.xyzzy"];
+ T.f "foo.mlpack" ~content:"foo/Bar";
+ T.f "main.ml" ~content:"prerr_endline Foo.Bar.baz";
+ T.f "myocamlbuild.ml";
+ T.f "quux.ml" ~content:"let xyzzy = \"xyzzy\"";
+ T.f "quux.mli" ~content:"val xyzzy : string"]
+ ~matching:[M.f "main.byte"]
+ ~targets:("main.byte",[]) ();;
+
+let () = test "NativeMliCmi"
+ ~options:[`no_ocamlfind; `ocamlc "toto" (*using ocamlc would fail*);
+ `tags["native"]]
+ ~description:"check that ocamlopt is used for .mli->.cmi \
+ when tag 'native' is set (part of PR#4613)"
+ ~tree:[T.f "foo.mli" ~content:"val bar : int"]
+ ~matching:[_build [M.f "foo.cmi"]]
+ ~targets:("foo.cmi",[]) ();;
+
+let () = test "NoIncludeNoHygiene1"
+ ~options:[`no_ocamlfind]
+ ~description:"check that hygiene checks are only done in traversed directories\
+ (PR#4502)"
+ ~tree:[T.d "must_ignore" [ T.f "dirty.mli" ~content:"val bug : int"];
+ T.f "hello.ml" ~content:"print_endline \"Hello, World!\"";
+ T.f "_tags" ~content:"<must_ignore>: -traverse"]
+ ~pre_cmd:"ocamlc -c must_ignore/dirty.mli"
+ (* will make hygiene fail if must_ignore/ is checked *)
+ ~targets:("hello.byte",[]) ();;
+
+let () = test "NoIncludeNoHygiene2"
+ ~options:[`no_ocamlfind; `build_dir "must_ignore"]
+ ~description:"check that hygiene checks are not done on the -build-dir \
+ (PR#4502)"
+ ~tree:[T.d "must_ignore" [ T.f "dirty.mli" ~content:"val bug : int"];
+ T.f "hello.ml" ~content:"print_endline \"Hello, World!\"";
+ T.f "_tags" ~content:""]
+ ~pre_cmd:"ocamlc -c must_ignore/dirty.mli"
+ (* will make hygiene fail if must_ignore/ is checked *)
+ ~targets:("hello.byte",[]) ();;
+
+let () = test "NoIncludeNoHygiene3"
+ ~options:[`no_ocamlfind; `X "must_ignore"]
+ ~description:"check that hygiene checks are not done on excluded dirs (PR#4502)"
+ ~tree:[T.d "must_ignore" [ T.f "dirty.mli" ~content:"val bug : int"];
+ T.f "hello.ml" ~content:"print_endline \"Hello, World!\"";
+ T.f "_tags" ~content:""]
+ ~pre_cmd:"ocamlc -c must_ignore/dirty.mli"
+ (* will make hygiene fail if must_ignore/ is checked *)
+ ~targets:("hello.byte",[]) ();;
+
+let () = test "OutputObj"
+ ~options:[`no_ocamlfind]
+ ~description:"output_obj targets for native and bytecode (PR #6049)"
+ ~tree:[T.f "hello.ml" ~content:"print_endline \"Hello, World!\""]
+ ~targets:("hello.byte.o",["hello.byte.c";"hello.native.o"]) ();;
+
+let () = test "OutputShared"
+ ~options:[`no_ocamlfind]
+ ~description:"output_shared targets for native and bytecode (PR #6733)"
+ ~tree:[T.f "hello.ml" ~content:"print_endline \"Hello, World!\"";
+ T.f "_tags" ~content:"<*.so>: runtime_variant(_pic)"]
+ ~targets:("hello.byte.so",["hello.native.so"]) ();;
+
+let () = test "StrictSequenceFlag"
+ ~options:[`no_ocamlfind; `quiet]
+ ~description:"strict_sequence tag"
+ ~tree:[T.f "hello.ml" ~content:"let () = 1; ()";
+ T.f "_tags" ~content:"true: strict_sequence\n"]
+ ~failing_msg:"File \"hello.ml\", line 1, characters 9-10:
+Error: This expression has type int but an expression was expected of type
+ unit\nCommand exited with code 2."
+ ~targets:("hello.byte",[]) ();;
+
+let () = test "StrictFormatsFlag"
+ ~options:[`no_ocamlfind; `quiet]
+ ~description:"strict_format tag"
+ ~tree:[T.f "hello.ml" ~content:"let _ = Printf.printf \"%.10s\"";
+ T.f "_tags" ~content:"true: strict_formats\n"]
+ ~failing_msg:"File \"hello.ml\", line 1, characters 22-29:
+Error: invalid format \"%.10s\": at character number 0, \
+`precision' is incompatible with 's' in sub-format \"%.10s\"
+Command exited with code 2."
+ ~targets:("hello.byte",[]) ();;
+
+let () = test "PrincipalFlag"
+ ~options:[`no_ocamlfind; `quiet]
+ ~description:"-principal tag"
+ ~tree:[T.f "hello.ml"
+ ~content:"type s={foo:int;bar:unit} type t={foo:int}
+ let f x = (x.bar; x.foo)";
+ T.f "_tags" ~content:"true: principal\n"]
+ ~failing_msg:"File \"hello.ml\", line 2, characters 42-45:
+Warning 18: this type-based field disambiguation is not principal."
+ ~targets:("hello.byte",[]) ();;
+
+let () = test "ModularPlugin1"
+ ~description:"test a plugin with dependency on external libraries"
+ ~options:[`no_ocamlfind; `quiet; `plugin_tag "use_str"]
+ ~tree:[T.f "main.ml" ~content:"let x = 1";
+ T.f "myocamlbuild.ml" ~content:"ignore (Str.quote \"\");;"]
+ ~matching:[M.f "main.byte"]
+ ~targets:("main.byte",[]) ();;
+
+let () = test "ModularPlugin2"
+ ~description:"check that parametrized tags defined by the plugin \
+ do not warn at plugin-compilation time"
+ ~options:[`no_ocamlfind; `quiet]
+ ~tree:[T.f "main.ml" ~content:"let x = 1";
+ T.f "_tags" ~content:"<main.*>: toto(-g)";
+ T.f "myocamlbuild.ml"
+ ~content:"open Ocamlbuild_plugin;;
+ pflag [\"link\"] \"toto\" (fun arg -> A arg);;"]
+ ~failing_msg:""
+ ~matching:[M.f "main.byte"]
+ ~targets:("main.byte",[]) ();;
+
+let () = test "ModularPlugin3"
+ ~description:"check that unknown parametrized tags encountered \
+ during plugin compilation still warn"
+ ~options:[`no_ocamlfind; `quiet; `plugin_tag "'toto(-g)'"]
+ ~tree:[T.f "main.ml" ~content:"let x = 1";
+ T.f "myocamlbuild.ml"
+ ~content:"open Ocamlbuild_plugin;;
+ pflag [\"link\"] \"toto\" (fun arg -> A arg);;"]
+ ~failing_msg:"Warning: tag \"toto\" does not expect a parameter, \
+ but is used with parameter \"-g\""
+ ~matching:[M.f "main.byte"]
+ ~targets:("main.byte",[]) ();;
+
+let () = test "PluginCompilation1"
+ ~description:"check that the plugin is not compiled when -no-plugin is passed"
+ ~options:[`no_ocamlfind; `no_plugin]
+ ~tree:[T.f "main.ml" ~content:"let x = 1";
+ T.f "myocamlbuild.ml" ~content:"prerr_endline \"foo\";;"]
+ ~matching:[_build [M.Not (M.f "myocamlbuild")]]
+ ~targets:("main.byte",[]) ();;
+
+let () = test "PluginCompilation2"
+ ~description:"check that the plugin is compiled when -just-plugin is passed"
+ ~options:[`no_ocamlfind; `just_plugin]
+ ~tree:[T.f "main.ml" ~content:"let x = 1";
+ T.f "myocamlbuild.ml" ~content:"print_endline \"foo\";;"]
+ ~matching:[_build [M.f "myocamlbuild"]]
+ ~targets:("", []) ();;
+
+let () = test "PluginCompilation3"
+ ~description:"check that the plugin is not executed \
+ when -just-plugin is passed"
+ ~options:[`no_ocamlfind; `quiet; `just_plugin]
+ ~tree:[T.f "main.ml" ~content:"let x = 1";
+ T.f "myocamlbuild.ml" ~content:"print_endline \"foo\";;"]
+ (* if the plugin were executed we'd get "foo" in failing_msg *)
+ ~failing_msg:""
+ ~targets:("main.byte", []) ();;
+
+let () = test "PluginTagsWarning"
+ ~description:"check that a warning is raised if -plugin-tags \
+ is used without a plugin file"
+ ~options:[`no_ocamlfind; `plugin_tag "use_str"]
+ ~tree:[T.f "main.ml" ~content:""]
+ ~matching:[_build [M.f "main.cmo"]]
+ ~failing_msg:"Warning: option -plugin-tag(s) has no effect \
+ in absence of plugin file \"myocamlbuild.ml\""
+ ~targets:("main.ml", []) ();;
+
+let () = test "TagsInNonHygienic"
+ ~description:"Regression test for PR#6482, where a _tags \
+ in a non-traversed directory would cause \
+ ocamlbuild to abort"
+ ~options:[`no_ocamlfind]
+ ~tree:[
+ T.f "main.ml" ~content:"";
+ T.d "deps" [T.f "_tags" ~content:""];
+ T.f "_tags" ~content:"<deps>: not_hygienic\n";
+ ]
+ ~matching:[M.f "main.byte"]
+ ~targets:("main.byte",[]) ();;
+
+let () = test "TagsNewlines"
+ ~description:"Regression test for PR#6087 about placement \
+ of newline-escaping backslashes"
+ ~options:[`no_ocamlfind]
+ ~tree:[
+ T.f "main.ml" ~content:"";
+ T.f "_tags" ~content:
+"<foo>: debug,\\
+rectypes
+<bar>: \\
+debug, rectypes
+<baz>\\
+: debug, rectypes
+";
+ ]
+ ~matching:[M.f "main.byte"]
+ ~targets:("main.byte",[]) ();;
+
+let () = test "OpenTag"
+ ~description:"Test the parametrized tag for the new -open feature"
+ ~options:[`no_ocamlfind]
+ ~tree:[
+ T.f "test.ml" ~content:"let _ = map rev [ []; [3;2] ]";
+ T.f "_tags" ~content: "<test.*>: open(List)";
+ ]
+ ~matching:[M.f "test.byte"]
+ ~targets:("test.byte",[]) ();;
+
+let () = test "OpenDependencies"
+ ~description:"Test dependency computation for the new -open feature (PR#6584)"
+ ~options:[`no_ocamlfind]
+ ~tree:[
+ T.f "a.ml" ~content:"let x = 1";
+ T.f "b.ml" ~content:"print_int x; print_newline ()";
+ T.f "_tags" ~content: "<b.*>: open(A)";
+ ]
+ ~matching:[M.f "b.byte"]
+ ~targets:("b.byte",[]) ();;
+
+run ~root:"_test_internal";;
diff --git a/ocamlbuild/testsuite/internal_test_header.ml b/ocamlbuild/testsuite/internal_test_header.ml
new file mode 100644
index 0000000000..da78c72618
--- /dev/null
+++ b/ocamlbuild/testsuite/internal_test_header.ml
@@ -0,0 +1,10 @@
+#load "unix.cma";;
+
+let ocamlbuild = try Sys.getenv "OCAMLBUILD" with Not_found -> "ocamlbuild";;
+
+#use "ocamlbuild_test.ml";;
+
+module M = Match;;
+module T = Tree;;
+
+let _build = M.d "_build";;
diff --git a/ocamlbuild/testsuite/ocamlbuild_test.ml b/ocamlbuild/testsuite/ocamlbuild_test.ml
new file mode 100644
index 0000000000..a45f08357b
--- /dev/null
+++ b/ocamlbuild/testsuite/ocamlbuild_test.ml
@@ -0,0 +1,537 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Wojciech Meyer *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+external (|>) : 'a -> ('a -> 'b) -> 'b = "%revapply"
+
+let print_list ~sep f ppf = function
+| [] -> ()
+| x :: [] -> f ppf x
+| x :: xs -> f ppf x; List.iter (fun x -> sep ppf (); f ppf x) xs
+
+let print_list_com f =
+ print_list ~sep:(fun ppf () -> pp_print_string ppf ",") f
+let print_list_blank f =
+ print_list ~sep:(fun ppf () -> pp_print_string ppf " ") f
+
+let print_string_list = print_list_com pp_print_string
+let print_string_list_com = print_list_com pp_print_string
+let print_string_list_blank = print_list_blank pp_print_string
+
+let exists filename =
+ try ignore(Unix.stat filename); true
+ with Unix.Unix_error ((Unix.ENOENT),_,_) -> false
+
+let execute cmd =
+ let ic = Unix.open_process_in cmd and lst = ref [] in
+ try while true do lst := input_line ic :: !lst done; assert false
+ with End_of_file ->
+ let ret_code = Unix.close_process_in ic
+ in ret_code, List.rev !lst
+
+let rm f =
+ if exists f then
+ ignore(Sys.command (Printf.sprintf "rm -r %s" f))
+
+module Match = struct
+
+ type atts = unit
+
+ (* File consists of file attribute and name *)
+ type file = atts * string
+
+ (* Result is an outcome of execution, if consists of returned exit code,
+ and stream from stdout *)
+ type result = int * string
+
+ type t =
+ (* Represents file in the tree *)
+ | F of file
+ (* Directory, consists of name and sub entries *)
+ | D of file * t list
+ (* Like file, but will be executed, and the result will compared *)
+ | X of file * result
+ (* Symlink; currently not supported *)
+ (* | L of file * file *)
+ (* We request that everything below should match exactly *)
+ | Exact of t
+ (* Here we want just the tree contained entities but we allow some
+ other stuff to be there too *)
+ | Contains of t
+ (* matching on Empty always fail *)
+ | Empty
+ (* matches the negation of its argument: fails when it succeeds
+ and vice versa; Any can be expressed as (Not Empty) *)
+ | Not of t
+
+ (* Type of error, we either expect something or something is un-expected *)
+ type error =
+ Expected of string
+ | Unexpected of string
+ | Structure of string * string list
+ | Output of string * string * string
+
+ (* This will print the tree *)
+ let print ppf tree =
+ let rec lines ppf lst =
+ List.iter (fun line -> pp_print_space ppf (); item ppf line) lst
+ and item ppf = function
+ | F (_, name) -> fprintf ppf "@[<h>%s@]" name
+ | D ((_, name), children) ->
+ fprintf ppf "@[<v 1>@[<h>%s/@]%a@]" name lines children
+ | X ((_,name), _) -> fprintf ppf "@[<h>%s@]" name
+ (* | L ((_,src), (_,dst)) -> fprintf ppf "@[<h>%s->%s@]@" src dst *)
+ | Exact content -> fprintf ppf "{%a}" item content
+ | Contains content -> fprintf ppf "<%a>" item content
+ | Empty -> pp_print_char ppf '#'
+ | Not t -> fprintf ppf "not(@[%a@])" item t
+ in
+ pp_open_vbox ppf 0;
+ item ppf tree;
+ pp_close_box ppf ()
+
+ let f ?(atts=()) name = F (atts, name)
+ let d ?(atts=()) name children = D ((atts, name), children)
+ let lf ?(atts=()) lst = List.map (fun nm -> F (atts,nm)) lst
+ let x ?(atts=()) name ~output = X ((atts,name), (0,output))
+
+ let match_with_fs ~root m =
+ let rec visit ~exact ~successes ~errors path m =
+ let string_of_path path = "./" ^ String.concat "/" (List.rev path) in
+ let file name = string_of_path (name :: path) in
+ let push li x = li := x :: !li in
+ let exists_assert filename =
+ push (if exists filename then successes else errors) (Expected filename)
+ in
+ let rec take_name = function
+ | F (_, name)
+ | D ((_, name), _)
+ | X ((_, name), _) -> [name]
+ | Exact sub
+ | Contains sub
+ | Not sub -> take_name sub
+ | Empty -> []
+ in
+ match m with
+ | F ((),name) ->
+ exists_assert (file name)
+ | D (((),name), sub) ->
+ exists_assert (file name);
+ let lst = List.flatten (List.map take_name sub) in
+ let lst' = Sys.readdir name |> Array.to_list in
+ let lst' = List.filter (fun x -> not (List.mem x lst)) lst' in
+ (if exact && lst' <> [] then
+ errors := Structure ((file name), lst') :: !errors);
+ List.iter (visit ~exact ~successes ~errors (name :: path)) sub
+ | X (((), name), (retcode, output)) ->
+ let _,output' = execute (file name) in
+ let output' = String.concat "\n" output' in
+ push (if output <> output' then errors else successes)
+ (Output (file name, output, output'));
+ | Exact sub -> visit ~exact:true ~successes ~errors path sub
+ | Contains sub -> visit ~exact:false ~successes ~errors path sub
+ | Empty -> push errors (Unexpected (string_of_path path))
+ | Not sub -> visit ~exact ~errors:successes ~successes:errors path sub
+ in
+ let dir = Sys.getcwd () in
+ Unix.chdir root;
+ let successes = ref [] in
+ let errors = ref [] in
+ visit ~exact:false ~successes ~errors [] m;
+ Unix.chdir dir;
+ List.rev !errors
+
+ let string_of_error = function
+ | Expected s -> Printf.sprintf "expected '%s' on a file system" s
+ | Unexpected s -> Printf.sprintf "un-expected '%s' on a file system" s
+ | Structure (s,l) ->
+ Printf.sprintf "directory structure '%s' has un-expected files %s"
+ s (String.concat ", " l)
+ | Output (s, e, p) ->
+ Printf.sprintf "executable %s expected output %S but got %S"
+ s e p
+end
+
+module Option = struct
+
+ type flag = string
+ type path = string
+ type level = int
+ type package = string
+ type file = string
+ type command = string
+ type _module = string
+ type tag = string
+
+ type t =
+ [ `version
+ | `vnum
+ | `quiet
+ | `verbose of level
+ | `documentation
+ | `log of file
+ | `no_log
+ | `clean
+ | `r
+ | `I of path
+ | `Is of path list
+ | `X of path
+ | `Xs of path list
+ | `lib of flag
+ | `libs of flag list
+ | `_mod of _module
+ | `mods of _module list
+ | `pkg of package
+ | `pkgs of package list
+ | `package of package
+ | `syntax of string
+ | `lflag of flag
+ | `lflags of flag list
+ | `cflag of flag
+ | `cflags of flag list
+ | `docflag of flag
+ | `docflags of flag list
+ | `yaccflag of flag
+ | `yaccflags of flag list
+ | `lexflag of flag
+ | `lexflags of flag list
+ | `ppflag of flag
+ | `pp of flag list
+ | `tag of tag
+ | `tags of tag list
+ | `plugin_tag of tag
+ | `plugin_tags of tag list
+ | `tag_line of tag
+ | `show_tags of path
+ | `ignore of _module list
+ | `no_links
+ | `no_skip
+ | `no_hygiene
+ | `no_ocamlfind
+ | `no_plugin
+ | `no_stdlib
+ | `dont_catch_errors
+ | `just_plugin
+ | `byte_plugin
+ | `plugin_option
+ | `sanitization_script
+ | `no_sanitize
+ | `nothing_should_be_rebuilt
+ | `classic_display
+ | `use_menhir
+ | `use_jocaml
+ | `use_ocamlfind
+ | `j of level
+ | `build_dir of path
+ | `install_lib_dir of path
+ | `install_bin_dir of path
+ | `where
+ | `ocamlc of command
+ | `ocamlopt of command
+ | `ocamldep of command
+ | `ocamldoc of command
+ | `ocamlyacc of command
+ | `menhir of command
+ | `ocamllex of command
+ | `ocamlmktop of command
+ | `ocamlrun of command
+ | `help ]
+
+ type arg = string * string list
+
+ let print_level = pp_print_int
+ let print_flag = pp_print_string
+ let print_package = pp_print_string
+ let print_tag = pp_print_string
+ let print_tags = print_string_list_com
+ let print_path = pp_print_string
+ let print_paths = print_string_list_com
+ let print_flags = print_string_list_com
+ let print_module = pp_print_string
+ let print_modules = print_string_list_com
+ let print_packages = print_string_list_com
+ let print_command = pp_print_string
+
+ let print_opt ppf o =
+ fprintf ppf "-";
+ match o with
+ | `version -> fprintf ppf "version"
+ | `vnum -> fprintf ppf "vnum"
+ | `quiet -> fprintf ppf "quiet"
+ | `verbose level -> fprintf ppf "verbose %a" print_level level
+ | `documentation -> fprintf ppf "documentation"
+ | `log file -> fprintf ppf "log"
+ | `no_log -> fprintf ppf "no-log"
+ | `clean -> fprintf ppf "clean"
+ | `r -> fprintf ppf "r"
+ | `I path -> fprintf ppf "I %a" print_path path
+ | `Is paths -> fprintf ppf "Is %a" print_paths paths
+ | `X path -> fprintf ppf "X %a" print_path path
+ | `Xs paths -> fprintf ppf "Xs %a" print_paths paths
+ | `lib flag -> fprintf ppf "lib %a" print_flag flag
+ | `libs flags -> fprintf ppf "libs %a" print_flags flags
+ | `_mod _module -> fprintf ppf "mod %a" print_module _module
+ | `mods _modules -> fprintf ppf "mods %a" print_modules _modules
+ | `pkg package -> fprintf ppf "pkg %a" print_package package
+ | `pkgs packages -> fprintf ppf "pkgs %a" print_packages packages
+ | `package package -> fprintf ppf "package %a" print_package package
+ | `syntax syntax -> fprintf ppf "syntax %a" pp_print_string syntax
+ | `lflag flag -> fprintf ppf "lflag %a" print_flag flag
+ | `lflags flags -> fprintf ppf "lflags %a" print_flags flags
+ | `cflag flag -> fprintf ppf "cflag %a" print_flag flag
+ | `cflags flags -> fprintf ppf "cflags %a" print_flags flags
+ | `docflag flag -> fprintf ppf "docflag %a" print_flag flag
+ | `docflags flags -> fprintf ppf "docflags %a" print_flags flags
+ | `yaccflag flag -> fprintf ppf "yaccflag %a" print_flag flag
+ | `yaccflags flags -> fprintf ppf "yaccflags %a" print_flags flags
+ | `lexflag flag -> fprintf ppf "lexflag %a" print_flag flag
+ | `lexflags flags -> fprintf ppf "lexflags %a" print_flags flags
+ | `ppflag flag -> fprintf ppf "ppflag %a" print_flag flag
+ | `pp flags -> fprintf ppf "pp %a" print_flags flags
+ | `tag tag -> fprintf ppf "tag %a" print_tag tag
+ | `tags tags -> fprintf ppf "tags %a" print_tags tags
+ | `plugin_tag tag -> fprintf ppf "plugin-tag %a" print_tag tag
+ | `plugin_tags tags -> fprintf ppf "plugin-tags %a" print_tags tags
+ | `tag_line tag -> fprintf ppf "tag-line %a" print_tag tag
+ | `show_tags path -> fprintf ppf "show-tags %a" print_path path
+ | `ignore _modules -> fprintf ppf "ignore %a" print_modules _modules
+ | `no_links -> fprintf ppf "no-links"
+ | `no_skip -> fprintf ppf "no-skip"
+ | `no_hygiene -> fprintf ppf "no-hygiene"
+ | `no_ocamlfind -> fprintf ppf "no-ocamlfind"
+ | `no_plugin -> fprintf ppf "no-plugin"
+ | `no_stdlib -> fprintf ppf "no-stdlib"
+ | `dont_catch_errors -> fprintf ppf "dont"
+ | `just_plugin -> fprintf ppf "just-plugin"
+ | `byte_plugin -> fprintf ppf "byte-plugin"
+ | `plugin_option -> fprintf ppf "plugin-option"
+ | `sanitization_script -> fprintf ppf "sanitization-script"
+ | `no_sanitize -> fprintf ppf "no-sanitze"
+ | `nothing_should_be_rebuilt -> fprintf ppf "nothing_should_be_rebuilt"
+ | `classic_display -> fprintf ppf "classic-display"
+ | `use_menhir -> fprintf ppf "use-menhir"
+ | `use_jocaml -> fprintf ppf "use-jocaml"
+ | `use_ocamlfind -> fprintf ppf "use-ocamlfind"
+ | `j level -> fprintf ppf "j %a" print_level level
+ | `build_dir path -> fprintf ppf "build-dir %a" print_path path
+ | `install_lib_dir path -> fprintf ppf "install %a" print_path path
+ | `install_bin_dir path -> fprintf ppf "install %a" print_path path
+ | `where -> fprintf ppf "where"
+ | `ocamlc command -> fprintf ppf "ocamlc %a" print_command command
+ | `ocamlopt command -> fprintf ppf "ocamlopt %a" print_command command
+ | `ocamldep command -> fprintf ppf "ocamldep %a" print_command command
+ | `ocamldoc command -> fprintf ppf "ocamldoc %a" print_command command
+ | `ocamlyacc command -> fprintf ppf "ocamlyacc %a" print_command command
+ | `menhir command -> fprintf ppf "menhir %a" print_command command
+ | `ocamllex command -> fprintf ppf "ocamllex %a" print_command command
+ | `ocamlmktop command -> fprintf ppf "ocamlmktop %a" print_command command
+ | `ocamlrun command -> fprintf ppf "ocamlrun %a" print_command command
+ | `help -> fprintf ppf "help"
+
+end
+
+module Tree = struct
+
+ type name = string
+ type content = string
+
+ type t =
+ F of name * content
+ | D of name * t list
+ | E
+
+ let f ?(content="") name = F (name, content)
+ let d name children = D (name, children)
+
+ let create_on_fs ~root f =
+
+ let rec visit path f =
+ let file name =
+ List.rev (name :: path)
+ |> String.concat "/"
+ in
+ match f with
+ | F (name, content) ->
+ let ch = file name |> open_out in
+ output_string ch content;
+ close_out ch
+ | D (name, sub) ->
+ (* print_endline ("mking " ^ (file name)); *)
+ Unix.mkdir (file name) 0o750;
+ List.iter (visit (name :: path)) sub
+ | E -> ()
+ in
+
+ let dir = Sys.getcwd () in
+ Unix.chdir root;
+ visit [] f;
+ Unix.chdir dir
+
+end
+
+type content = string
+type filename = string
+type run = filename * content
+
+type requirements = Fullfilled | Missing of string
+
+type test = { name : string
+ ; description : string
+ ; requirements : requirements option
+ ; tree : Tree.t list
+ ; matching : Match.t list
+ ; options : Option.t list
+ ; targets : string * string list
+ ; pre_cmd : string option
+ ; failing_msg : string option
+ ; run : run list }
+
+let tests = ref []
+
+let test name
+ ~description
+ ?requirements
+ ?(options=[]) ?(run=[]) ?pre_cmd ?failing_msg
+ ?(tree=[])
+ ?(matching=[])
+ ~targets ()
+ =
+ tests := !tests @ [{
+ name;
+ description;
+ requirements;
+ tree;
+ matching;
+ options;
+ targets;
+ pre_cmd;
+ failing_msg;
+ run;
+ }]
+
+let print_colored header_color header name body_color body =
+ let color_code = function
+ | `Red -> "31"
+ | `Green -> "32"
+ | `Yellow -> "33"
+ | `Blue -> "34"
+ | `Magenta -> "35"
+ | `Cyan -> "36"
+ in
+ Printf.printf "\x1b[0;%sm\x1b[1m[%s]\x1b[0m \
+ \x1b[1m%-20s\x1b[0;%sm%s.\n\x1b[m%!"
+ (color_code header_color) header name
+ (color_code body_color) body
+
+let run ~root =
+ let dir = Sys.getcwd () in
+ let root = dir ^ "/" ^ root in
+ rm root;
+ Unix.mkdir root 0o750;
+
+ let command opts args =
+ let b = Buffer.create 127 in
+ let f = Format.formatter_of_buffer b in
+ fprintf f "%s %a %a" ocamlbuild (print_list_blank Option.print_opt) opts (print_list_blank pp_print_string) args;
+ Format.pp_print_flush f ();
+ Buffer.contents b
+ in
+
+ let one_test
+ { name
+ ; description
+ ; requirements
+ ; tree
+ ; matching
+ ; options
+ ; targets
+ ; failing_msg
+ ; pre_cmd
+ ; run } =
+
+ let full_name = root ^ "/" ^ name in
+ rm full_name;
+ Unix.mkdir full_name 0o750;
+ List.iter (Tree.create_on_fs ~root:full_name) tree;
+ Unix.chdir full_name;
+
+ match requirements with
+ | Some (Missing req) ->
+ print_colored `Yellow "SKIPPED" name `Yellow
+ (Printf.sprintf "%s is required and missing" req)
+
+ | Some Fullfilled | None -> begin
+
+ (match pre_cmd with
+ | None -> ()
+ | Some str -> ignore(Sys.command str));
+
+ let log_name = full_name ^ ".log" in
+
+ let cmd = command options (fst targets :: snd targets) in
+ let allow_failure = failing_msg <> None in
+
+ let open Unix in
+
+ match execute cmd with
+ | WEXITED n,lines
+ | WSIGNALED n,lines
+ | WSTOPPED n,lines when allow_failure || n <> 0 ->
+ begin match failing_msg with
+ | None ->
+ let ch = open_out log_name in
+ List.iter
+ (fun l -> output_string ch l; output_string ch "\n")
+ lines;
+ close_out ch;
+ print_colored `Red "FAILED" name `Yellow
+ (Printf.sprintf "Command '%s' with error code %n \
+ output written to %s" cmd n log_name);
+ | Some failing_msg ->
+ let starts_with_plus s = String.length s > 0 && s.[0] = '+' in
+ let lines =
+ (* filter out -classic-display output *)
+ List.filter (fun s -> not (starts_with_plus s)) lines in
+ let msg = String.concat "\n" lines in
+ if failing_msg = msg then
+ print_colored `Green "PASSED" name `Cyan description
+ else
+ print_colored `Red "FAILED" name `Yellow
+ ((Printf.sprintf "Failure with not matching message:\n\
+ %s\n!=\n%s\n") msg failing_msg)
+ end;
+ | _ ->
+ let errors =
+ List.concat
+ (List.map (Match.match_with_fs ~root:full_name) matching) in
+ begin if errors == [] then
+ print_colored `Green "PASSED" name `Cyan description
+ else begin
+ let ch = open_out log_name in
+ output_string ch ("Run '" ^ cmd ^ "'\n");
+ List.iter
+ (fun e ->
+ output_string ch (Match.string_of_error e);
+ output_string ch ".\n")
+ errors;
+ close_out ch;
+ print_colored `Red "FAILED" name `Yellow
+ (Printf.sprintf "Some system checks failed, \
+ output written to %s"
+ log_name)
+ end
+ end
+ end
+
+ in List.iter one_test !tests
diff --git a/ocamlbuild/tools.ml b/ocamlbuild/tools.ml
new file mode 100644
index 0000000000..830c4b983e
--- /dev/null
+++ b/ocamlbuild/tools.ml
@@ -0,0 +1,47 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Tools *)
+
+open My_std
+open Format
+open Log
+open Pathname.Operators
+open Tags.Operators
+open Rule
+
+let pp_l = List.print String.print
+
+let tags_of_pathname p =
+ Configuration.tags_of_filename (Pathname.to_string p)
+ ++("file:"^p)
+ ++("extension:"^Pathname.get_extension p)
+
+let opt_print elt ppf =
+ function
+ | Some x -> fprintf ppf "@[<2>Some@ %a@]" elt x
+ | None -> pp_print_string ppf "None"
+
+let path_and_context_of_string s =
+ if Pathname.is_implicit s then
+ let b = Pathname.basename s in
+ let d = Pathname.dirname s in
+ if d <> Pathname.current_dir_name then
+ let () = Pathname.define_context d [d] in
+ [s]
+ else
+ let include_dirs = Pathname.include_dirs_of d in
+ List.map (fun include_dir -> include_dir/b) include_dirs
+ else [s]
diff --git a/ocamlbuild/tools.mli b/ocamlbuild/tools.mli
new file mode 100644
index 0000000000..c65d4b1349
--- /dev/null
+++ b/ocamlbuild/tools.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* ocamlbuild *)
+(* *)
+(* Nicolas Pouillard, Berke Durak, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+
+(* Original author: Nicolas Pouillard *)
+(* Tools *)
+
+val tags_of_pathname : Pathname.t -> Tags.t
+val path_and_context_of_string : Pathname.t -> Pathname.t list
+val pp_l : Format.formatter -> string list -> unit
diff --git a/ocamldoc/.depend b/ocamldoc/.depend
new file mode 100644
index 0000000000..ec461d73de
--- /dev/null
+++ b/ocamldoc/.depend
@@ -0,0 +1,269 @@
+odoc_analyse.cmo : ../utils/warnings.cmi ../typing/types.cmi \
+ ../typing/typemod.cmi ../typing/typedtree.cmi ../parsing/syntaxerr.cmi \
+ ../driver/pparse.cmi ../parsing/parse.cmi odoc_types.cmi odoc_text.cmi \
+ odoc_sig.cmi odoc_module.cmo odoc_misc.cmi odoc_messages.cmo \
+ odoc_merge.cmi odoc_global.cmi odoc_dep.cmo odoc_cross.cmi \
+ odoc_comments.cmi odoc_class.cmo odoc_ast.cmi ../utils/misc.cmi \
+ ../parsing/location.cmi ../typing/env.cmi ../utils/config.cmi \
+ ../utils/clflags.cmi odoc_analyse.cmi
+odoc_analyse.cmx : ../utils/warnings.cmx ../typing/types.cmx \
+ ../typing/typemod.cmx ../typing/typedtree.cmx ../parsing/syntaxerr.cmx \
+ ../driver/pparse.cmx ../parsing/parse.cmx odoc_types.cmx odoc_text.cmx \
+ odoc_sig.cmx odoc_module.cmx odoc_misc.cmx odoc_messages.cmx \
+ odoc_merge.cmx odoc_global.cmx odoc_dep.cmx odoc_cross.cmx \
+ odoc_comments.cmx odoc_class.cmx odoc_ast.cmx ../utils/misc.cmx \
+ ../parsing/location.cmx ../typing/env.cmx ../utils/config.cmx \
+ ../utils/clflags.cmx odoc_analyse.cmi
+odoc_args.cmo : ../utils/warnings.cmi odoc_types.cmi odoc_texi.cmo \
+ odoc_messages.cmo odoc_man.cmo odoc_latex.cmo odoc_html.cmo \
+ odoc_global.cmi odoc_gen.cmi odoc_dot.cmo odoc_config.cmi \
+ ../utils/misc.cmi ../driver/main_args.cmi ../parsing/location.cmi \
+ ../utils/config.cmi ../driver/compenv.cmi ../utils/clflags.cmi \
+ odoc_args.cmi
+odoc_args.cmx : ../utils/warnings.cmx odoc_types.cmx odoc_texi.cmx \
+ odoc_messages.cmx odoc_man.cmx odoc_latex.cmx odoc_html.cmx \
+ odoc_global.cmx odoc_gen.cmx odoc_dot.cmx odoc_config.cmx \
+ ../utils/misc.cmx ../driver/main_args.cmx ../parsing/location.cmx \
+ ../utils/config.cmx ../driver/compenv.cmx ../utils/clflags.cmx \
+ odoc_args.cmi
+odoc_ast.cmo : ../typing/types.cmi ../typing/typedtree.cmi \
+ ../typing/predef.cmi ../typing/path.cmi ../parsing/parsetree.cmi \
+ odoc_value.cmo odoc_types.cmi odoc_type.cmo odoc_sig.cmi \
+ odoc_parameter.cmo odoc_name.cmi odoc_module.cmo odoc_messages.cmo \
+ odoc_global.cmi odoc_extension.cmo odoc_exception.cmo odoc_env.cmi \
+ odoc_class.cmo ../utils/misc.cmi ../parsing/location.cmi \
+ ../typing/ident.cmi ../parsing/asttypes.cmi odoc_ast.cmi
+odoc_ast.cmx : ../typing/types.cmx ../typing/typedtree.cmx \
+ ../typing/predef.cmx ../typing/path.cmx ../parsing/parsetree.cmi \
+ odoc_value.cmx odoc_types.cmx odoc_type.cmx odoc_sig.cmx \
+ odoc_parameter.cmx odoc_name.cmx odoc_module.cmx odoc_messages.cmx \
+ odoc_global.cmx odoc_extension.cmx odoc_exception.cmx odoc_env.cmx \
+ odoc_class.cmx ../utils/misc.cmx ../parsing/location.cmx \
+ ../typing/ident.cmx ../parsing/asttypes.cmi odoc_ast.cmi
+odoc_class.cmo : ../typing/types.cmi odoc_value.cmo odoc_types.cmi \
+ odoc_parameter.cmo odoc_name.cmi
+odoc_class.cmx : ../typing/types.cmx odoc_value.cmx odoc_types.cmx \
+ odoc_parameter.cmx odoc_name.cmx
+odoc_comments_global.cmo : odoc_comments_global.cmi
+odoc_comments_global.cmx : odoc_comments_global.cmi
+odoc_comments.cmo : odoc_types.cmi odoc_text.cmi odoc_see_lexer.cmo \
+ odoc_parser.cmi odoc_misc.cmi odoc_messages.cmo odoc_merge.cmi \
+ odoc_lexer.cmo odoc_global.cmi odoc_cross.cmi odoc_comments_global.cmi \
+ odoc_comments.cmi
+odoc_comments.cmx : odoc_types.cmx odoc_text.cmx odoc_see_lexer.cmx \
+ odoc_parser.cmx odoc_misc.cmx odoc_messages.cmx odoc_merge.cmx \
+ odoc_lexer.cmx odoc_global.cmx odoc_cross.cmx odoc_comments_global.cmx \
+ odoc_comments.cmi
+odoc_config.cmo : ../utils/config.cmi odoc_config.cmi
+odoc_config.cmx : ../utils/config.cmx odoc_config.cmi
+odoc_control.cmo :
+odoc_control.cmx :
+odoc_cross.cmo : odoc_value.cmo odoc_types.cmi odoc_type.cmo odoc_search.cmi \
+ odoc_scan.cmo odoc_parameter.cmo odoc_name.cmi odoc_module.cmo \
+ odoc_misc.cmi odoc_messages.cmo odoc_global.cmi odoc_extension.cmo \
+ odoc_exception.cmo odoc_class.cmo odoc_cross.cmi
+odoc_cross.cmx : odoc_value.cmx odoc_types.cmx odoc_type.cmx odoc_search.cmx \
+ odoc_scan.cmx odoc_parameter.cmx odoc_name.cmx odoc_module.cmx \
+ odoc_misc.cmx odoc_messages.cmx odoc_global.cmx odoc_extension.cmx \
+ odoc_exception.cmx odoc_class.cmx odoc_cross.cmi
+odoc_dag2html.cmo : odoc_info.cmi odoc_dag2html.cmi
+odoc_dag2html.cmx : odoc_info.cmx odoc_dag2html.cmi
+odoc_dep.cmo : ../parsing/parsetree.cmi odoc_type.cmo odoc_print.cmi \
+ odoc_module.cmo ../tools/depend.cmi
+odoc_dep.cmx : ../parsing/parsetree.cmi odoc_type.cmx odoc_print.cmx \
+ odoc_module.cmx ../tools/depend.cmx
+odoc_dot.cmo : odoc_messages.cmo odoc_info.cmi
+odoc_dot.cmx : odoc_messages.cmx odoc_info.cmx
+odoc_env.cmo : ../typing/types.cmi ../typing/printtyp.cmi \
+ ../typing/predef.cmi ../typing/path.cmi odoc_name.cmi ../utils/misc.cmi \
+ ../typing/btype.cmi odoc_env.cmi
+odoc_env.cmx : ../typing/types.cmx ../typing/printtyp.cmx \
+ ../typing/predef.cmx ../typing/path.cmx odoc_name.cmx ../utils/misc.cmx \
+ ../typing/btype.cmx odoc_env.cmi
+odoc_exception.cmo : ../typing/types.cmi odoc_types.cmi odoc_type.cmo \
+ odoc_name.cmi
+odoc_exception.cmx : ../typing/types.cmx odoc_types.cmx odoc_type.cmx \
+ odoc_name.cmx
+odoc_extension.cmo : ../typing/types.cmi odoc_types.cmi odoc_type.cmo \
+ odoc_name.cmi ../parsing/asttypes.cmi
+odoc_extension.cmx : ../typing/types.cmx odoc_types.cmx odoc_type.cmx \
+ odoc_name.cmx ../parsing/asttypes.cmi
+odoc_gen.cmo : odoc_texi.cmo odoc_module.cmo odoc_man.cmo odoc_latex.cmo \
+ odoc_html.cmo odoc_dot.cmo odoc_gen.cmi
+odoc_gen.cmx : odoc_texi.cmx odoc_module.cmx odoc_man.cmx odoc_latex.cmx \
+ odoc_html.cmx odoc_dot.cmx odoc_gen.cmi
+odoc_global.cmo : odoc_types.cmi odoc_messages.cmo odoc_config.cmi \
+ ../utils/clflags.cmi odoc_global.cmi
+odoc_global.cmx : odoc_types.cmx odoc_messages.cmx odoc_config.cmx \
+ ../utils/clflags.cmx odoc_global.cmi
+odoc_html.cmo : odoc_text.cmi odoc_ocamlhtml.cmo odoc_messages.cmo \
+ odoc_info.cmi odoc_global.cmi odoc_dag2html.cmi ../parsing/asttypes.cmi
+odoc_html.cmx : odoc_text.cmx odoc_ocamlhtml.cmx odoc_messages.cmx \
+ odoc_info.cmx odoc_global.cmx odoc_dag2html.cmx ../parsing/asttypes.cmi
+odoc_info.cmo : ../typing/printtyp.cmi odoc_value.cmo odoc_types.cmi \
+ odoc_type.cmo odoc_text.cmi odoc_str.cmi odoc_search.cmi odoc_scan.cmo \
+ odoc_print.cmi odoc_parameter.cmo odoc_name.cmi odoc_module.cmo \
+ odoc_misc.cmi odoc_global.cmi odoc_extension.cmo odoc_exception.cmo \
+ odoc_dep.cmo odoc_config.cmi odoc_comments.cmi odoc_class.cmo \
+ odoc_analyse.cmi ../parsing/location.cmi odoc_info.cmi
+odoc_info.cmx : ../typing/printtyp.cmx odoc_value.cmx odoc_types.cmx \
+ odoc_type.cmx odoc_text.cmx odoc_str.cmx odoc_search.cmx odoc_scan.cmx \
+ odoc_print.cmx odoc_parameter.cmx odoc_name.cmx odoc_module.cmx \
+ odoc_misc.cmx odoc_global.cmx odoc_extension.cmx odoc_exception.cmx \
+ odoc_dep.cmx odoc_config.cmx odoc_comments.cmx odoc_class.cmx \
+ odoc_analyse.cmx ../parsing/location.cmx odoc_info.cmi
+odoc_inherit.cmo :
+odoc_inherit.cmx :
+odoc_latex.cmo : odoc_to_text.cmo odoc_messages.cmo odoc_latex_style.cmo \
+ odoc_info.cmi ../parsing/asttypes.cmi
+odoc_latex.cmx : odoc_to_text.cmx odoc_messages.cmx odoc_latex_style.cmx \
+ odoc_info.cmx ../parsing/asttypes.cmi
+odoc_latex_style.cmo :
+odoc_latex_style.cmx :
+odoc_lexer.cmo : odoc_parser.cmi odoc_messages.cmo odoc_global.cmi \
+ odoc_comments_global.cmi
+odoc_lexer.cmx : odoc_parser.cmx odoc_messages.cmx odoc_global.cmx \
+ odoc_comments_global.cmx
+odoc_man.cmo : odoc_str.cmi odoc_print.cmi odoc_misc.cmi odoc_messages.cmo \
+ odoc_info.cmi ../utils/misc.cmi ../parsing/asttypes.cmi
+odoc_man.cmx : odoc_str.cmx odoc_print.cmx odoc_misc.cmx odoc_messages.cmx \
+ odoc_info.cmx ../utils/misc.cmx ../parsing/asttypes.cmi
+odoc_merge.cmo : odoc_value.cmo odoc_types.cmi odoc_type.cmo \
+ odoc_parameter.cmo odoc_name.cmi odoc_module.cmo odoc_messages.cmo \
+ odoc_global.cmi odoc_extension.cmo odoc_exception.cmo odoc_class.cmo \
+ odoc_merge.cmi
+odoc_merge.cmx : odoc_value.cmx odoc_types.cmx odoc_type.cmx \
+ odoc_parameter.cmx odoc_name.cmx odoc_module.cmx odoc_messages.cmx \
+ odoc_global.cmx odoc_extension.cmx odoc_exception.cmx odoc_class.cmx \
+ odoc_merge.cmi
+odoc_messages.cmo : ../utils/config.cmi
+odoc_messages.cmx : ../utils/config.cmx
+odoc_misc.cmo : ../typing/types.cmi ../typing/predef.cmi ../typing/path.cmi \
+ odoc_types.cmi odoc_messages.cmo ../parsing/longident.cmi \
+ ../typing/ctype.cmi ../typing/btype.cmi odoc_misc.cmi
+odoc_misc.cmx : ../typing/types.cmx ../typing/predef.cmx ../typing/path.cmx \
+ odoc_types.cmx odoc_messages.cmx ../parsing/longident.cmx \
+ ../typing/ctype.cmx ../typing/btype.cmx odoc_misc.cmi
+odoc.cmo : ../typing/typedtree.cmi odoc_messages.cmo odoc_info.cmi \
+ odoc_global.cmi odoc_gen.cmi odoc_config.cmi odoc_args.cmi \
+ odoc_analyse.cmi ../utils/misc.cmi ../utils/config.cmi \
+ ../utils/clflags.cmi
+odoc.cmx : ../typing/typedtree.cmx odoc_messages.cmx odoc_info.cmx \
+ odoc_global.cmx odoc_gen.cmx odoc_config.cmx odoc_args.cmx \
+ odoc_analyse.cmx ../utils/misc.cmx ../utils/config.cmx \
+ ../utils/clflags.cmx
+odoc_module.cmo : ../typing/types.cmi odoc_value.cmo odoc_types.cmi \
+ odoc_type.cmo odoc_name.cmi odoc_extension.cmo odoc_exception.cmo \
+ odoc_class.cmo
+odoc_module.cmx : ../typing/types.cmx odoc_value.cmx odoc_types.cmx \
+ odoc_type.cmx odoc_name.cmx odoc_extension.cmx odoc_exception.cmx \
+ odoc_class.cmx
+odoc_name.cmo : ../typing/path.cmi odoc_misc.cmi ../typing/ident.cmi \
+ odoc_name.cmi
+odoc_name.cmx : ../typing/path.cmx odoc_misc.cmx ../typing/ident.cmx \
+ odoc_name.cmi
+odoc_ocamlhtml.cmo :
+odoc_ocamlhtml.cmx :
+odoc_parameter.cmo : ../typing/types.cmi odoc_types.cmi
+odoc_parameter.cmx : ../typing/types.cmx odoc_types.cmx
+odoc_parser.cmo : odoc_types.cmi odoc_comments_global.cmi odoc_parser.cmi
+odoc_parser.cmx : odoc_types.cmx odoc_comments_global.cmx odoc_parser.cmi
+odoc_print.cmo : ../typing/types.cmi ../typing/printtyp.cmi \
+ ../utils/misc.cmi odoc_print.cmi
+odoc_print.cmx : ../typing/types.cmx ../typing/printtyp.cmx \
+ ../utils/misc.cmx odoc_print.cmi
+odoc_scan.cmo : odoc_value.cmo odoc_types.cmi odoc_type.cmo odoc_module.cmo \
+ odoc_extension.cmo odoc_exception.cmo odoc_class.cmo
+odoc_scan.cmx : odoc_value.cmx odoc_types.cmx odoc_type.cmx odoc_module.cmx \
+ odoc_extension.cmx odoc_exception.cmx odoc_class.cmx
+odoc_search.cmo : odoc_value.cmo odoc_types.cmi odoc_type.cmo \
+ odoc_parameter.cmo odoc_name.cmi odoc_module.cmo odoc_extension.cmo \
+ odoc_exception.cmo odoc_class.cmo odoc_search.cmi
+odoc_search.cmx : odoc_value.cmx odoc_types.cmx odoc_type.cmx \
+ odoc_parameter.cmx odoc_name.cmx odoc_module.cmx odoc_extension.cmx \
+ odoc_exception.cmx odoc_class.cmx odoc_search.cmi
+odoc_see_lexer.cmo : odoc_parser.cmi
+odoc_see_lexer.cmx : odoc_parser.cmx
+odoc_sig.cmo : ../typing/types.cmi ../typing/typedtree.cmi \
+ ../typing/path.cmi ../parsing/parsetree.cmi odoc_value.cmo odoc_types.cmi \
+ odoc_type.cmo odoc_parameter.cmo odoc_name.cmi odoc_module.cmo \
+ odoc_misc.cmi odoc_messages.cmo odoc_merge.cmi odoc_global.cmi \
+ odoc_extension.cmo odoc_exception.cmo odoc_env.cmi odoc_class.cmo \
+ ../utils/misc.cmi ../parsing/location.cmi ../typing/ident.cmi \
+ ../typing/ctype.cmi ../typing/btype.cmi ../parsing/asttypes.cmi \
+ odoc_sig.cmi
+odoc_sig.cmx : ../typing/types.cmx ../typing/typedtree.cmx \
+ ../typing/path.cmx ../parsing/parsetree.cmi odoc_value.cmx odoc_types.cmx \
+ odoc_type.cmx odoc_parameter.cmx odoc_name.cmx odoc_module.cmx \
+ odoc_misc.cmx odoc_messages.cmx odoc_merge.cmx odoc_global.cmx \
+ odoc_extension.cmx odoc_exception.cmx odoc_env.cmx odoc_class.cmx \
+ ../utils/misc.cmx ../parsing/location.cmx ../typing/ident.cmx \
+ ../typing/ctype.cmx ../typing/btype.cmx ../parsing/asttypes.cmi \
+ odoc_sig.cmi
+odoc_str.cmo : ../typing/types.cmi ../typing/printtyp.cmi odoc_value.cmo \
+ odoc_type.cmo odoc_print.cmi odoc_name.cmi odoc_misc.cmi \
+ odoc_messages.cmo odoc_extension.cmo odoc_exception.cmo odoc_class.cmo \
+ ../parsing/asttypes.cmi odoc_str.cmi
+odoc_str.cmx : ../typing/types.cmx ../typing/printtyp.cmx odoc_value.cmx \
+ odoc_type.cmx odoc_print.cmx odoc_name.cmx odoc_misc.cmx \
+ odoc_messages.cmx odoc_extension.cmx odoc_exception.cmx odoc_class.cmx \
+ ../parsing/asttypes.cmi odoc_str.cmi
+odoc_test.cmo : odoc_info.cmi odoc_gen.cmi odoc_args.cmi
+odoc_test.cmx : odoc_info.cmx odoc_gen.cmx odoc_args.cmx
+odoc_texi.cmo : ../typing/types.cmi odoc_to_text.cmo odoc_messages.cmo \
+ odoc_info.cmi ../parsing/asttypes.cmi
+odoc_texi.cmx : ../typing/types.cmx odoc_to_text.cmx odoc_messages.cmx \
+ odoc_info.cmx ../parsing/asttypes.cmi
+odoc_text_lexer.cmo : odoc_text_parser.cmi odoc_misc.cmi
+odoc_text_lexer.cmx : odoc_text_parser.cmx odoc_misc.cmx
+odoc_text.cmo : odoc_types.cmi odoc_text_parser.cmi odoc_text_lexer.cmo \
+ odoc_text.cmi
+odoc_text.cmx : odoc_types.cmx odoc_text_parser.cmx odoc_text_lexer.cmx \
+ odoc_text.cmi
+odoc_text_parser.cmo : odoc_types.cmi odoc_misc.cmi odoc_text_parser.cmi
+odoc_text_parser.cmx : odoc_types.cmx odoc_misc.cmx odoc_text_parser.cmi
+odoc_to_text.cmo : odoc_module.cmo odoc_messages.cmo odoc_info.cmi
+odoc_to_text.cmx : odoc_module.cmx odoc_messages.cmx odoc_info.cmx
+odoc_type.cmo : ../typing/types.cmi odoc_types.cmi odoc_name.cmi \
+ ../parsing/asttypes.cmi
+odoc_type.cmx : ../typing/types.cmx odoc_types.cmx odoc_name.cmx \
+ ../parsing/asttypes.cmi
+odoc_types.cmo : odoc_messages.cmo ../parsing/location.cmi odoc_types.cmi
+odoc_types.cmx : odoc_messages.cmx ../parsing/location.cmx odoc_types.cmi
+odoc_value.cmo : ../typing/types.cmi ../typing/printtyp.cmi odoc_types.cmi \
+ odoc_parameter.cmo odoc_name.cmi odoc_misc.cmi ../parsing/asttypes.cmi
+odoc_value.cmx : ../typing/types.cmx ../typing/printtyp.cmx odoc_types.cmx \
+ odoc_parameter.cmx odoc_name.cmx odoc_misc.cmx ../parsing/asttypes.cmi
+odoc_analyse.cmi : odoc_module.cmo odoc_global.cmi
+odoc_args.cmi : odoc_gen.cmi
+odoc_ast.cmi : ../typing/types.cmi ../typing/typedtree.cmi \
+ ../parsing/parsetree.cmi odoc_sig.cmi odoc_name.cmi odoc_module.cmo
+odoc_comments_global.cmi :
+odoc_comments.cmi : odoc_types.cmi odoc_module.cmo
+odoc_config.cmi :
+odoc_cross.cmi : odoc_types.cmi odoc_module.cmo
+odoc_dag2html.cmi : odoc_info.cmi
+odoc_env.cmi : ../typing/types.cmi odoc_name.cmi
+odoc_gen.cmi : odoc_texi.cmo odoc_module.cmo odoc_man.cmo odoc_latex.cmo \
+ odoc_html.cmo odoc_dot.cmo
+odoc_global.cmi : odoc_types.cmi
+odoc_info.cmi : ../typing/types.cmi odoc_value.cmo odoc_types.cmi \
+ odoc_type.cmo odoc_search.cmi odoc_parameter.cmo odoc_module.cmo \
+ odoc_global.cmi odoc_extension.cmo odoc_exception.cmo odoc_class.cmo \
+ ../parsing/location.cmi ../parsing/asttypes.cmi
+odoc_merge.cmi : odoc_types.cmi odoc_module.cmo
+odoc_misc.cmi : ../typing/types.cmi odoc_types.cmi ../parsing/longident.cmi \
+ ../parsing/asttypes.cmi
+odoc_name.cmi : ../typing/path.cmi ../parsing/longident.cmi \
+ ../typing/ident.cmi
+odoc_parser.cmi : odoc_types.cmi
+odoc_print.cmi : ../typing/types.cmi
+odoc_search.cmi : odoc_value.cmo odoc_types.cmi odoc_type.cmo \
+ odoc_module.cmo odoc_extension.cmo odoc_exception.cmo odoc_class.cmo
+odoc_sig.cmi : ../typing/types.cmi ../parsing/parsetree.cmi odoc_types.cmi \
+ odoc_type.cmo odoc_name.cmi odoc_module.cmo odoc_env.cmi odoc_class.cmo
+odoc_str.cmi : ../typing/types.cmi odoc_value.cmo odoc_type.cmo \
+ odoc_extension.cmo odoc_exception.cmo odoc_class.cmo
+odoc_text.cmi : odoc_types.cmi
+odoc_text_parser.cmi : odoc_types.cmi
+odoc_types.cmi : ../parsing/location.cmi
diff --git a/ocamldoc/.ignore b/ocamldoc/.ignore
new file mode 100644
index 0000000000..720ee641a5
--- /dev/null
+++ b/ocamldoc/.ignore
@@ -0,0 +1,16 @@
+ocamldoc
+ocamldoc.opt
+odoc_crc.ml
+odoc_lexer.ml
+odoc_ocamlhtml.ml
+odoc_parser.ml
+odoc_parser.mli
+odoc_see_lexer.ml
+odoc_text_lexer.ml
+odoc_text_parser.ml
+odoc_text_parser.mli
+stdlib_man
+*.output
+test_stdlib
+test_latex
+test
diff --git a/ocamldoc/Changes.txt b/ocamldoc/Changes.txt
new file mode 100644
index 0000000000..49ed84d24d
--- /dev/null
+++ b/ocamldoc/Changes.txt
@@ -0,0 +1,209 @@
+TODO:
+ - need to fix display of type parameters for inherited classes/class types
+ - need to add an environment while generating to print correct links:
+ file foo.mli:
+ type u
+ module type M = sig type u end
+ module N : sig include M val f: u -> unit end
+ Here, in html for example, f in displayed being of type Foo.u instead of Foo.M.u
+ - latex: types variant polymorphes depassent de la page quand ils sont trop longs
+ - utilisation nouvelles infos de Xavier: "debut de rec", etc.
+ - xml generator
+
+=====
+Release > 3.11.0:
+- option -g also for native code version (loading custom generators)
+
+=====
+Release 3.09.3:
+- mod: PR#4017 new option -short-functors to use a short form to display
+ functors in html generator
+- fix: PR#4016 (using modtype constraint to filter module elements displayed in doc)
+- fix: PR#4066 (missing crossref in text from intro files)
+- fix: PR#4007 (error in merging of top dependencies of modules)
+- fix: PR#3981 (-dot-colors has no effect)
+- mod: name resolution in cross-referencing: {!name} if name is not
+ found, then it is searched in the parent module/class, and in the parent
+ of the parent, and so on until it is found.
+
+=====
+Release 3.09.1:
+ - fix: remove .TP for generated man pages, use .sp instead
+ (.TP caused a lot of odd margins)
+ - fix: html generator now output DOCTYPE and character encoding information.
+ - add: m_text_only field in Module.t_module, to separate real modules
+ from text files handled as modules.
+ - fix: display only text for "text modules"
+ - extensible {foo } syntax
+ - user can give .txt files on the command line, containing ocamldoc formatted
+ text, to be able to include bigger texts out of source files
+ - -o option is now used by the html generator to indicate the prefix
+ of generated index files (to avoid conflict when a Index module exists
+ on case-insensitive file systems).
+
+=====
+Release 3.08.4:
+ - some improvements in html display
+ - better error messages for misplaced variant constructors comments
+ - some fixes in man page generation (escaping characters)
+
+=====
+Release 3.08.2:
+ - fix: error "Lexing: empty token" (PR#3173)
+
+=====
+Release 3.08.1:
+ - add: new -intf and -impl options supported (PR#3036)
+ - fix: display of class parameters in HTML and LaTeX (PR#2994)
+ - fix: display of link to class page in html (PR#2994)
+
+=====
+Release 3.08.0:
+ - fix: method parameters names in signature are now retrieved correctly
+ (fix of Odoc_value.parameter_list_from_arrows to handle Tpoly for methods)
+ - ajout a la doc de Module_list et Index_list (utilise dans le html seulement)
+ - ajout a la doc: fichier de l'option -intro utilise pour l'index en html
+ - fix: create a Module_with instead of a Module_alias when we encounter
+ module A : Foo in a signature
+ - latex: style latex pour indenter dans les module kind et les class kind
+ - latex: il manque la generation des parametres de classe
+ - parse des {!modules: } et {!indexlist}
+ - gestion des Module_list et Index_list
+ - no need to Dynlink.add_available_units any more
+ - generate html from module_kind rather than from module_type
+ + same for classes and class types
+ - add the kind to module parameters (the way the parameter was build in the parsetree)
+ - fix: the generated ocamldoc.sty is more robust for paragraphs in
+ ocamldocdescription environment
+ - fix: when generating separated files in latex, generate them in
+ the same directory than the main file, (the one specified by -o)
+ - mod: one section per to module in latex output + improve latex output
+ - mod: odoc_latex: use buffers instead of string concatenation
+ - add: new ocamldoc man page, thanks to Samuel Mimram
+ - fix: useless parenthesis around agruments of arguments of a type constructor in
+ type definitions, and aournd arguments of exceptions in exception definitions.
+ - fix: blank lines in verbatim, latex, code pre, code and ele ref modes
+ are now accepted
+ - fix: html generator: included module names were displayed with their simple
+ name rather than their fully qualified name
+ - fix: use a formatter from a buffer rather Format.str_formatter in
+ Odoc_mist.sting_of_module_type, to avoid too much blanks
+ - new module odoc_print, will work when Format.pp_print_flush is fixed
+ - odoc_html: use buffers instead of string concatenation
+ - odoc_man: use buffers instead of string concatenation
+ - odoc_cross.ml: use hash tables modified on the fly to resolve
+ (module | module type | exception) name aliases
+ - odoc_html: replace some calls to Str. by specific functions on strings
+ - odoc_cross.ml: use a Map to associate a complete name to
+ the known elements with this name, instead of searching each time
+ through the whole list of modules -> a gain of more than 90% in speed
+ for cross-referencing (Odoc_cross.associate)
+ - fix: Odoc_name.cut printed a '(' instead of a '.'
+ - add: new option -customdir
+ - add: new option -i (to add a path to the directory where
+ to look for custom generators)
+ - add: add odoc_config.ml{,i}
+ - add: keep_code in Odoc_info.Args interface
+ - add: m_code_intf and m_code fields for modules, fit when the
+ Odoc_args.keep_code option is set, and fit for all modules, not
+ only toplevel ones
+ - fix: bug preventing to get the code in a .mli
+ - fix: missing spaces after carriage return in types (Odoc_misc.string_of_type_expr)
+ - fixes: some bugs in the text parser
+ ( ]} meaning end of code and somehting else instead of end of precode)
+ - add: in Odoc_info: text_of_string, text_string_of_text, info_of_string
+ - fix: better output of titles in html (use more the style)
+ - add: -intro option to use a file content as ocamldoc comment to use as
+ introduction for LaTeX document and HTML index page
+ - add: the HTML generator generates the code of the module if available
+ - add: field m_code for modules, to keep the code of top modules
+ - fix: display "include Foo" instead of "include module Foo" in Latex, Man, Texi
+ - fix: not display comments associated to include directives
+ - fix: bad display of type parameters for class and class types
+
+======
+
+Release 3.05 :
+ - added link tags in html header to reference sections and subsections
+ in each page (for browser which handle those tags)
+ - no titles nor lists in first sentence of text in indexes and latex titles
+ - only one table for the titles in HTML output
+ - fix of bad comment association for types in .ml files
+ - dumps now contain a magic number, checked when dumps are loaded
+ - new option -o to use with texi, latex and dot generators
+ - new .code CSS class used
+ - better output for classes and modules, with their type
+ - added texinfo generator, by Olivier Andrieu
+ - removed iso generator, which became the odoc_check custom generator
+ - link syntax {{:url}text} added to the manual
+ - (** comments in code is colorized in ocaml code html pages
+ - new class .code in style
+ - new generator : -dot . Output dot code to display
+ modules or types dependencies.
+ - new option -inv-merge-ml-mli to inverse the priority of
+ .ml and .mli when merging
+ - option -werr becomes -warn-error
+ - possibility to define and reference section labels
+ Exemple:
+ (** {2:mysectionlabel My title bla bla bla} *)
+ in module Foo
+
+ This section is referenced with {!Foo.mysectionlabel} in
+ a comment.
+
+Pre-release 4 :
+ - new option -werr to treat ocamldoc warnings as errors
+ - new option -hide to remove some modules from complete names,
+ (e.g., print ref instead of Pervasives.ref)
+ - HTML doc in classic style only contain indexes to existing element kinds
+ (i.e. there is no class index if the doc does not contain any class.)
+ - First description sentence now stops at the first period followed by a blank,
+ or at the first blank line.
+ - update of user manual
+ - check report generator added (options -iso and -iso-{val|ty|cl|ex|mod})
+ - Odoc_info.Scan.scanner base class added
+ - support for custom tags (@xxx with xxx not a predefined tag), see manual
+ - new classes info in Odoc_html, Odoc_to_text, Odoc_latex, and Odoc_man, which
+ contains the functions for printing info structures
+ - replacement of modules Odoc_html.Text and Odoc_latex.Text by
+ classes Odoc_html.text and Odoc_latex.text to allow the redefinition
+ of their methods in custom generators
+ - bug fix : a shortcut list can be pu after a blank line
+ - improved display of variant constructors, record fields and
+ their comments in classic HTML
+ - blank lines in comments become <p> in HTML instead of <br>
+ - bug fix : there can be blanks between the last item
+ and the ending } of a list
+ - new option -latextitles
+ - number of errors encountered is displayed
+ - if at least one error occurs, exit code is not 0
+ - more precise error messages
+ - bug fix : \n and other blanks are accepted after, for example, {i
+
+Pre-release 3 :
+ - option -stars
+ - complete paths of executables in the generated Makefile
+ - names of executables changed to ocamldoc and ocamldoc.opt
+ - better LaTeX output
+ - option -sepfiles for LaTeX
+ - ocamldoc.sty used by the generated LaTeX
+ - ocamldoc.hva added to use Hevea on the generated LaTeX
+ - user manual updated
+ - {[ ]} marks to put pre-formatted code on more than one line
+ - {!Toto.tutu} to add cross references between elements
+ - some bug fixes
+
+Rep-release 2 :
+- generator of texinfo files : odoc_texi.cma
+- use of CSS in generated html
+- new option -css-style to provide a different style sheet
+- improved html
+- added more precise titles in generated html pages
+- no more links to unknown elements
+- added indexes
+- simple html : added <LINK ...> in <HEAD> : compliant
+ browsers should display quick access to modules and indexes in
+ their navigation bar (for example, mozilla 0.9.5 is compliant)
+- '{bone}' doesn't work any more ; a space is required as in '{b one}'.
+ Same for {e, {i, and some others marks. Check the manual
+- bug fixes
diff --git a/ocamldoc/Makefile b/ocamldoc/Makefile
new file mode 100644
index 0000000000..9ae4a085be
--- /dev/null
+++ b/ocamldoc/Makefile
@@ -0,0 +1,357 @@
+#(***********************************************************************)
+#(* *)
+#(* OCamldoc *)
+#(* *)
+#(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+#(* *)
+#(* Copyright 2001 Institut National de Recherche en Informatique et *)
+#(* en Automatique. All rights reserved. This file is distributed *)
+#(* under the terms of the Q Public License version 1.0. *)
+#(* *)
+#(***********************************************************************)
+
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+
+# Various commands and dir
+##########################
+ROOTDIR = ..
+OCAMLC = $(CAMLRUN) $(ROOTDIR)/ocamlc -nostdlib -I $(ROOTDIR)/stdlib
+OCAMLOPT = $(CAMLRUN) $(ROOTDIR)/ocamlopt -nostdlib -I $(ROOTDIR)/stdlib
+OCAMLDEP = $(CAMLRUN) $(ROOTDIR)/tools/ocamldep
+OCAMLLEX = $(CAMLRUN) $(ROOTDIR)/boot/ocamllex
+OCAMLLIB = $(LIBDIR)
+OCAMLBIN = $(BINDIR)
+
+OCAMLPP=-pp './remove_DEBUG'
+
+# For installation
+##############
+MKDIR=mkdir -p
+CP=cp -f
+OCAMLDOC=ocamldoc
+OCAMLDOC_RUN=sh ./runocamldoc $(SUPPORTS_SHARED_LIBRARIES)
+OCAMLDOC_OPT=$(OCAMLDOC).opt
+OCAMLDOC_LIBCMA=odoc_info.cma
+OCAMLDOC_LIBCMI=odoc_info.cmi
+OCAMLDOC_LIBCMXA=odoc_info.cmxa
+OCAMLDOC_LIBA=odoc_info.$(A)
+INSTALL_LIBDIR=$(DESTDIR)$(OCAMLLIB)/ocamldoc
+INSTALL_CUSTOMDIR=$(INSTALL_LIBDIR)/custom
+INSTALL_BINDIR=$(DESTDIR)$(OCAMLBIN)
+#MANO: man ocamldoc
+INSTALL_MANODIR=$(DESTDIR)$(MANDIR)/man3
+
+INSTALL_MLIS=odoc_info.mli
+INSTALL_CMIS=$(INSTALL_MLIS:.mli=.cmi)
+
+ODOC_TEST=odoc_test.cmo
+
+GENERATORS_CMOS= \
+ generators/odoc_todo.cmo \
+ generators/odoc_literate.cmo
+true = $(GENERATORS_CMOS:.cmo=.cmxs)
+false =
+GENERATORS_CMXS := $($(NATDYNLINK))
+
+
+# Compilation
+#############
+OCAMLSRCDIR=..
+INCLUDES_DEP=-I $(OCAMLSRCDIR)/parsing \
+ -I $(OCAMLSRCDIR)/utils \
+ -I $(OCAMLSRCDIR)/typing \
+ -I $(OCAMLSRCDIR)/driver \
+ -I $(OCAMLSRCDIR)/bytecomp \
+ -I $(OCAMLSRCDIR)/tools \
+ -I $(OCAMLSRCDIR)/toplevel/
+
+INCLUDES_NODEP= -I $(OCAMLSRCDIR)/stdlib \
+ -I $(OCAMLSRCDIR)/otherlibs/str \
+ -I $(OCAMLSRCDIR)/otherlibs/dynlink \
+ -I $(OCAMLSRCDIR)/otherlibs/$(UNIXLIB) \
+ -I $(OCAMLSRCDIR)/otherlibs/num \
+ -I $(OCAMLSRCDIR)/otherlibs/$(GRAPHLIB)
+
+INCLUDES=$(INCLUDES_DEP) $(INCLUDES_NODEP)
+
+COMPFLAGS=$(INCLUDES) -warn-error A -safe-string
+LINKFLAGS=$(INCLUDES) -nostdlib
+
+CMOFILES= odoc_config.cmo \
+ odoc_messages.cmo\
+ odoc_global.cmo\
+ odoc_types.cmo\
+ odoc_misc.cmo\
+ odoc_text_parser.cmo\
+ odoc_text_lexer.cmo\
+ odoc_text.cmo\
+ odoc_name.cmo\
+ odoc_parameter.cmo\
+ odoc_value.cmo\
+ odoc_type.cmo\
+ odoc_extension.cmo\
+ odoc_exception.cmo\
+ odoc_class.cmo\
+ odoc_module.cmo\
+ odoc_print.cmo \
+ odoc_str.cmo\
+ odoc_comments_global.cmo\
+ odoc_parser.cmo\
+ odoc_lexer.cmo\
+ odoc_see_lexer.cmo\
+ odoc_env.cmo\
+ odoc_merge.cmo\
+ odoc_sig.cmo\
+ odoc_ast.cmo\
+ odoc_control.cmo\
+ odoc_inherit.cmo\
+ odoc_search.cmo\
+ odoc_scan.cmo\
+ odoc_cross.cmo\
+ odoc_comments.cmo\
+ odoc_dep.cmo\
+ odoc_analyse.cmo\
+ odoc_info.cmo
+
+
+CMXFILES= $(CMOFILES:.cmo=.cmx)
+CMIFILES= $(CMOFILES:.cmo=.cmi)
+
+EXECMOFILES=$(CMOFILES) \
+ odoc_dag2html.cmo \
+ odoc_to_text.cmo \
+ odoc_ocamlhtml.cmo \
+ odoc_html.cmo \
+ odoc_man.cmo \
+ odoc_latex_style.cmo \
+ odoc_latex.cmo \
+ odoc_texi.cmo \
+ odoc_dot.cmo \
+ odoc_gen.cmo \
+ odoc_args.cmo \
+ odoc.cmo
+
+EXECMXFILES= $(EXECMOFILES:.cmo=.cmx)
+EXECMIFILES= $(EXECMOFILES:.cmo=.cmi)
+
+LIBCMOFILES=$(CMOFILES)
+LIBCMXFILES= $(LIBCMOFILES:.cmo=.cmx)
+LIBCMIFILES= $(LIBCMOFILES:.cmo=.cmi)
+
+# Les cmo et cmx de la distrib OCAML
+OCAMLCMOFILES= \
+ $(OCAMLSRCDIR)/tools/depend.cmo
+
+OCAMLCMXFILES=$(OCAMLCMOFILES:.cmo=.cmx)
+
+
+STDLIB_MLIS=../stdlib/*.mli \
+ ../parsing/*.mli \
+ ../otherlibs/$(UNIXLIB)/unix.mli \
+ ../otherlibs/str/str.mli \
+ ../otherlibs/bigarray/bigarray.mli \
+ ../otherlibs/num/num.mli
+
+all:
+ $(MAKE) exe
+ $(MAKE) lib
+ $(MAKE) generators
+ $(MAKE) manpages
+
+exe: $(OCAMLDOC)
+lib: $(OCAMLDOC_LIBCMA) $(OCAMLDOC_LIBCMI) $(ODOC_TEST)
+generators: $(GENERATORS_CMOS)
+
+opt.opt: exeopt libopt generatorsopt
+exeopt: $(OCAMLDOC_OPT)
+libopt: $(OCAMLDOC_LIBCMXA) $(OCAMLDOC_LIBCMI)
+generatorsopt: $(GENERATORS_CMXS)
+
+debug:
+ $(MAKE) OCAMLPP=""
+
+$(OCAMLDOC): $(EXECMOFILES)
+ $(OCAMLC) -o $@ -linkall unix.cma str.cma dynlink.cma \
+ $(OCAMLSRCDIR)/compilerlibs/ocamlcommon.cma \
+ $(LINKFLAGS) $(OCAMLCMOFILES) $(EXECMOFILES)
+$(OCAMLDOC_OPT): $(EXECMXFILES)
+ $(OCAMLOPT) -o $@ -linkall unix.cmxa str.cmxa dynlink.cmxa \
+ $(OCAMLSRCDIR)/compilerlibs/ocamlcommon.cmxa \
+ $(LINKFLAGS) $(OCAMLCMXFILES) $(EXECMXFILES)
+
+$(OCAMLDOC_LIBCMA): $(LIBCMOFILES)
+ $(OCAMLC) -a -o $@ $(LINKFLAGS) $(OCAMLSRCDIR)/tools/depend.cmo \
+ $(LIBCMOFILES)
+$(OCAMLDOC_LIBCMXA): $(LIBCMXFILES)
+ $(OCAMLOPT) -a -o $@ $(LINKFLAGS) $(OCAMLSRCDIR)/tools/depend.cmx \
+ $(LIBCMXFILES)
+
+manpages: stdlib_man/Pervasives.3o
+html_doc: stdlib_html/Pervasives.html
+
+dot: $(EXECMOFILES)
+ $(OCAMLDOC_RUN) -dot -dot-reduce -o ocamldoc.dot $(INCLUDES) \
+ odoc*.ml
+
+# Parsers and lexers dependencies :
+###################################
+odoc_text_parser.ml: odoc_text_parser.mly
+odoc_text_parser.mli: odoc_text_parser.mly
+
+odoc_parser.ml: odoc_parser.mly
+odoc_parser.mli:odoc_parser.mly
+
+odoc_text_lexer.ml: odoc_text_lexer.mll
+
+odoc_lexer.ml:odoc_lexer.mll
+
+odoc_ocamlhtml.ml: odoc_ocamlhtml.mll
+
+odoc_see_lexer.ml: odoc_see_lexer.mll
+
+
+# generic rules :
+#################
+
+.SUFFIXES: .mll .mly .ml .mli .cmo .cmi .cmx .cmxs
+
+.ml.cmo:
+ $(OCAMLC) $(OCAMLPP) $(COMPFLAGS) -c $<
+
+.mli.cmi:
+ $(OCAMLC) $(OCAMLPP) $(COMPFLAGS) -c $<
+
+.ml.cmx:
+ $(OCAMLOPT) $(OCAMLPP) $(COMPFLAGS) -c $<
+
+.ml.cmxs:
+ $(OCAMLOPT) -shared -o $@ $(OCAMLPP) $(COMPFLAGS) $<
+
+.mll.ml:
+ $(OCAMLLEX) $<
+
+.mly.ml:
+ $(CAMLYACC) -v $<
+
+.mly.mli:
+ $(CAMLYACC) -v $<
+
+# Installation targets
+######################
+install: dummy
+ if test -d $(INSTALL_BINDIR); then : ; else $(MKDIR) $(INSTALL_BINDIR); fi
+ if test -d $(INSTALL_LIBDIR); then : ; else $(MKDIR) $(INSTALL_LIBDIR); fi
+ if test -d $(INSTALL_CUSTOMDIR); then : ; else $(MKDIR) $(INSTALL_CUSTOMDIR); fi
+ $(CP) $(OCAMLDOC) $(INSTALL_BINDIR)/$(OCAMLDOC)$(EXE)
+ $(CP) ocamldoc.hva *.cmi $(OCAMLDOC_LIBCMA) $(INSTALL_LIBDIR)
+ $(CP) $(INSTALL_MLIS) $(INSTALL_CMIS) $(INSTALL_LIBDIR)
+ if test -d $(INSTALL_MANODIR); then : ; else $(MKDIR) $(INSTALL_MANODIR); fi
+ if test -d stdlib_man; then $(CP) stdlib_man/* $(INSTALL_MANODIR); else : ; fi
+
+installopt:
+ if test -f $(OCAMLDOC_OPT); then $(MAKE) installopt_really ; fi
+
+installopt_really:
+ if test -d $(INSTALL_BINDIR); then : ; else $(MKDIR) $(INSTALL_BINDIR); fi
+ if test -d $(INSTALL_LIBDIR); then : ; else $(MKDIR) $(INSTALL_LIBDIR); fi
+ $(CP) $(OCAMLDOC_OPT) $(INSTALL_BINDIR)/$(OCAMLDOC_OPT)$(EXE)
+ $(CP) ocamldoc.hva $(OCAMLDOC_LIBA) $(OCAMLDOC_LIBCMXA) $(INSTALL_LIBDIR)
+ $(CP) $(INSTALL_MLIS) $(INSTALL_CMIS) $(INSTALL_LIBDIR)
+
+# Testing :
+###########
+test: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -html -colorize-code -sort -d $@ $(INCLUDES) -dump $@/ocamldoc.odoc odoc*.ml odoc*.mli -v
+ $(MKDIR) $@-custom
+ $(OCAMLDOC_RUN) -colorize-code -sort -d $@-custom $(INCLUDES) \
+ -g generators/odoc_literate.cmo -g generators/odoc_todo.cmo \
+ -load $@/ocamldoc.odoc -v
+
+test_stdlib: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -html -colorize-code -sort -d $@ $(INCLUDES) -dump $@/stdlib.odoc -keep-code \
+ ../stdlib/pervasives.ml ../stdlib/*.mli \
+ ../otherlibs/$(UNIXLIB)/unix.mli \
+ ../otherlibs/str/str.mli
+
+test_stdlib_code: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -html -colorize-code -sort -d $@ $(INCLUDES) -dump $@/stdlib.odoc -keep-code \
+ `ls ../stdlib/*.ml | grep -v Labels` \
+ ../otherlibs/$(UNIXLIB)/unix.ml \
+ ../otherlibs/str/str.ml
+
+test_framed: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -g odoc_fhtml.cmo -sort -colorize-code -d $@ $(INCLUDES) odoc*.ml odoc*.mli
+
+test_latex: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -latex -sort -o $@/test.tex -d $@ $(INCLUDES) odoc*.ml \
+ odoc*.mli test2.txt ../stdlib/*.mli ../otherlibs/unix/unix.mli
+
+test_latex_simple: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -latex -sort -o $@/test.tex -d $@ $(INCLUDES) \
+ -latextitle 6,subsection -latextitle 7,subsubection \
+ ../stdlib/hashtbl.mli \
+ ../stdlib/arg.mli \
+ ../otherlibs/$(UNIXLIB)/unix.mli \
+ ../stdlib/map.mli
+
+test_man: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -man -sort -d $@ $(INCLUDES) odoc*.ml odoc*.mli
+
+test_texi: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -texi -sort -d $@ $(INCLUDES) odoc*.ml odoc*.mli
+
+stdlib_man/Pervasives.3o: $(STDLIB_MLIS)
+ $(MKDIR) stdlib_man
+ $(OCAMLDOC_RUN) -man -d stdlib_man $(INCLUDES) \
+ -t "OCaml library" -man-mini \
+ $(STDLIB_MLIS)
+
+stdlib_html/Pervasives.html: $(STDLIB_MLIS)
+ $(MKDIR) stdlib_html
+ $(OCAMLDOC_RUN) -d stdlib_html -html $(INCLUDES) \
+ -t "OCaml library" \
+ $(STDLIB_MLIS)
+
+
+autotest_stdlib: dummy
+ $(MKDIR) $@
+ $(OCAMLDOC_RUN) -g autotest/odoc_test.cmo\
+ $(INCLUDES) -keep-code \
+ ../stdlib/pervasives.ml ../stdlib/*.mli \
+ ../otherlibs/$(UNIXLIB)/unix.mli \
+ ../otherlibs/str/str.mli
+
+# backup, clean and depend :
+############################
+
+clean:: dummy
+ @rm -f *~ \#*\#
+ @rm -f $(OCAMLDOC) $(OCAMLDOC_OPT) *.cma *.cmxa *.cmo *.cmi *.cmx *.$(A) *.$(O)
+ @rm -f odoc_parser.output odoc_text_parser.output
+ @rm -f odoc_lexer.ml odoc_text_lexer.ml odoc_see_lexer.ml odoc_ocamlhtml.ml
+ @rm -f odoc_parser.ml odoc_parser.mli odoc_text_parser.ml odoc_text_parser.mli
+ @rm -rf stdlib_man
+ @rm -f generators/*.cm[aiox] generators/*.$(A) generators/*.$(O) generators/*.cmx[as]
+
+depend::
+ $(CAMLYACC) odoc_text_parser.mly
+ $(CAMLYACC) odoc_parser.mly
+ $(OCAMLLEX) odoc_text_lexer.mll
+ $(OCAMLLEX) odoc_lexer.mll
+ $(OCAMLLEX) odoc_ocamlhtml.mll
+ $(OCAMLLEX) odoc_see_lexer.mll
+ $(OCAMLDEP) $(INCLUDES_DEP) *.mll *.mly *.ml *.mli > .depend
+
+dummy:
+
+include .depend
diff --git a/ocamldoc/Makefile.nt b/ocamldoc/Makefile.nt
new file mode 100644
index 0000000000..9c009596be
--- /dev/null
+++ b/ocamldoc/Makefile.nt
@@ -0,0 +1,253 @@
+#(***********************************************************************)
+#(* *)
+#(* OCamldoc *)
+#(* *)
+#(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+#(* *)
+#(* Copyright 2001 Institut National de Recherche en Informatique et *)
+#(* en Automatique. All rights reserved. This file is distributed *)
+#(* under the terms of the Q Public License version 1.0. *)
+#(* *)
+#(***********************************************************************)
+
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+
+# Various commands and dir
+##########################
+ROOTDIR = ..
+OCAMLC = $(CAMLRUN) $(ROOTDIR)/ocamlc -nostdlib -I $(ROOTDIR)/stdlib
+OCAMLOPT = $(CAMLRUN) $(ROOTDIR)/ocamlopt -nostdlib -I $(ROOTDIR)/stdlib
+OCAMLDEP = $(CAMLRUN) $(ROOTDIR)/tools/ocamldep
+OCAMLLEX = $(CAMLRUN) $(ROOTDIR)/boot/ocamllex
+OCAMLLIB = $(LIBDIR)
+OCAMLBIN = $(BINDIR)
+
+OCAMLPP=-pp "grep -v DEBUG"
+
+# For installation
+##############
+MKDIR=mkdir
+CP=cp
+OCAMLDOC=ocamldoc
+OCAMLDOC_RUN=$(CAMLRUN) $(OCAMLDOC)
+OCAMLDOC_OPT=$(OCAMLDOC).opt
+OCAMLDOC_LIBCMA=odoc_info.cma
+OCAMLDOC_LIBCMI=odoc_info.cmi
+OCAMLDOC_LIBCMXA=odoc_info.cmxa
+OCAMLDOC_LIBA=odoc_info.$(A)
+INSTALL_LIBDIR=$(DESTDIR)$(OCAMLLIB)/ocamldoc
+INSTALL_CUSTOMDIR=$(INSTALL_LIBDIR)/custom
+INSTALL_BINDIR=$(DESTDIR)$(OCAMLBIN)
+
+INSTALL_MLIS=odoc_info.mli
+INSTALL_CMIS=$(INSTALL_MLIS:.mli=.cmi)
+
+# Compilation
+#############
+OCAMLSRCDIR=..
+INCLUDES_DEP=-I $(OCAMLSRCDIR)/parsing \
+ -I $(OCAMLSRCDIR)/utils \
+ -I $(OCAMLSRCDIR)/typing \
+ -I $(OCAMLSRCDIR)/driver \
+ -I $(OCAMLSRCDIR)/bytecomp \
+ -I $(OCAMLSRCDIR)/tools \
+ -I $(OCAMLSRCDIR)/toplevel/
+
+INCLUDES_NODEP= -I $(OCAMLSRCDIR)/stdlib \
+ -I $(OCAMLSRCDIR)/otherlibs/str \
+ -I $(OCAMLSRCDIR)/otherlibs/dynlink \
+ -I $(OCAMLSRCDIR)/otherlibs/$(UNIXLIB) \
+ -I $(OCAMLSRCDIR)/otherlibs/num \
+ -I $(OCAMLSRCDIR)/otherlibs/$(GRAPHLIB)
+
+INCLUDES=$(INCLUDES_DEP) $(INCLUDES_NODEP)
+
+COMPFLAGS=$(INCLUDES) -warn-error A -safe-string
+LINKFLAGS=$(INCLUDES) -nostdlib
+
+CMOFILES= odoc_config.cmo \
+ odoc_messages.cmo\
+ odoc_global.cmo\
+ odoc_types.cmo\
+ odoc_misc.cmo\
+ odoc_text_parser.cmo\
+ odoc_text_lexer.cmo\
+ odoc_text.cmo\
+ odoc_name.cmo\
+ odoc_parameter.cmo\
+ odoc_value.cmo\
+ odoc_type.cmo\
+ odoc_extension.cmo\
+ odoc_exception.cmo\
+ odoc_class.cmo\
+ odoc_module.cmo\
+ odoc_print.cmo \
+ odoc_str.cmo\
+ odoc_comments_global.cmo\
+ odoc_parser.cmo\
+ odoc_lexer.cmo\
+ odoc_see_lexer.cmo\
+ odoc_env.cmo\
+ odoc_merge.cmo\
+ odoc_sig.cmo\
+ odoc_ast.cmo\
+ odoc_control.cmo\
+ odoc_inherit.cmo\
+ odoc_search.cmo\
+ odoc_scan.cmo\
+ odoc_cross.cmo\
+ odoc_comments.cmo\
+ odoc_dep.cmo\
+ odoc_analyse.cmo\
+ odoc_info.cmo
+
+
+CMXFILES= $(CMOFILES:.cmo=.cmx)
+CMIFILES= $(CMOFILES:.cmo=.cmi)
+
+EXECMOFILES=$(CMOFILES) \
+ odoc_dag2html.cmo \
+ odoc_to_text.cmo \
+ odoc_ocamlhtml.cmo \
+ odoc_html.cmo \
+ odoc_man.cmo \
+ odoc_latex_style.cmo \
+ odoc_latex.cmo \
+ odoc_texi.cmo \
+ odoc_dot.cmo \
+ odoc_gen.cmo \
+ odoc_args.cmo \
+ odoc.cmo
+
+EXECMXFILES= $(EXECMOFILES:.cmo=.cmx)
+EXECMIFILES= $(EXECMOFILES:.cmo=.cmi)
+
+LIBCMOFILES=$(CMOFILES)
+LIBCMXFILES= $(LIBCMOFILES:.cmo=.cmx)
+LIBCMIFILES= $(LIBCMOFILES:.cmo=.cmi)
+
+# Les cmo et cmx de la distrib OCAML
+OCAMLCMOFILES= \
+ $(OCAMLSRCDIR)/tools/depend.cmo
+
+OCAMLCMXFILES=$(OCAMLCMOFILES:.cmo=.cmx)
+
+all:
+ $(MAKEREC) exe
+ $(MAKEREC) lib
+
+exe: $(OCAMLDOC)
+lib: $(OCAMLDOC_LIBCMA) $(OCAMLDOC_LIBCMI)
+
+opt.opt: exeopt libopt
+exeopt: $(OCAMLDOC_OPT)
+libopt: $(OCAMLDOC_LIBCMXA) $(OCAMLDOC_LIBCMI)
+
+debug:
+ $(MAKEREC) OCAMLPP=""
+
+$(OCAMLDOC): $(EXECMOFILES)
+ $(OCAMLC) -o $@ -linkall unix.cma str.cma dynlink.cma \
+ $(OCAMLSRCDIR)/compilerlibs/ocamlcommon.cma \
+ $(LINKFLAGS) $(OCAMLCMOFILES) $(EXECMOFILES)
+$(OCAMLDOC_OPT): $(EXECMXFILES)
+ $(OCAMLOPT) -o $@ -linkall unix.cmxa str.cmxa dynlink.cmxa \
+ $(OCAMLSRCDIR)/compilerlibs/ocamlcommon.cmxa \
+ $(LINKFLAGS) $(OCAMLCMXFILES) $(EXECMXFILES)
+
+$(OCAMLDOC_LIBCMA): $(LIBCMOFILES)
+ $(OCAMLC) -a -o $@ $(LINKFLAGS) $(OCAMLSRCDIR)/tools/depend.cmo \
+ $(LIBCMOFILES)
+$(OCAMLDOC_LIBCMXA): $(LIBCMXFILES)
+ $(OCAMLOPT) -a -o $@ $(LINKFLAGS) $(OCAMLSRCDIR)/tools/depend.cmx \
+ $(LIBCMXFILES)
+
+# Parsers and lexers dependencies :
+###################################
+odoc_text_parser.ml: odoc_text_parser.mly
+odoc_text_parser.mli: odoc_text_parser.mly
+
+odoc_parser.ml: odoc_parser.mly
+odoc_parser.mli:odoc_parser.mly
+
+odoc_text_lexer.ml: odoc_text_lexer.mll
+
+odoc_lexer.ml:odoc_lexer.mll
+
+odoc_ocamlhtml.ml: odoc_ocamlhtml.mll
+
+odoc_see_lexer.ml: odoc_see_lexer.mll
+
+
+# generic rules :
+#################
+
+.SUFFIXES: .mll .mly .ml .mli .cmo .cmi .cmx .cmxs
+
+.ml.cmo:
+ $(OCAMLC) $(OCAMLPP) $(COMPFLAGS) -c $<
+
+.mli.cmi:
+ $(OCAMLC) $(OCAMLPP) $(COMPFLAGS) -c $<
+
+.ml.cmx:
+ $(OCAMLOPT) $(OCAMLPP) $(COMPFLAGS) -c $<
+
+.ml.cmxs:
+ $(OCAMLOPT) -shared -o $@ $(OCAMLPP) $(COMPFLAGS) $<
+
+.mll.ml:
+ $(OCAMLLEX) $<
+
+.mly.ml:
+ $(CAMLYACC) -v $<
+
+.mly.mli:
+ $(CAMLYACC) -v $<
+
+# Installation targets
+######################
+install: dummy
+ $(MKDIR) -p $(INSTALL_BINDIR)
+ $(MKDIR) -p $(INSTALL_LIBDIR)
+ $(CP) $(OCAMLDOC) $(INSTALL_BINDIR)/$(OCAMLDOC)$(EXE)
+ $(CP) ocamldoc.hva *.cmi $(OCAMLDOC_LIBCMA) $(INSTALL_LIBDIR)
+ $(CP) $(INSTALL_MLIS) $(INSTALL_CMIS) $(INSTALL_LIBDIR)
+
+installopt:
+ if test -f $(OCAMLDOC_OPT); then $(MAKEREC) installopt_really; fi
+
+installopt_really:
+ $(MKDIR) -p $(INSTALL_BINDIR)
+ $(MKDIR) -p $(INSTALL_LIBDIR)
+ $(CP) $(OCAMLDOC_OPT) $(INSTALL_BINDIR)/$(OCAMLDOC_OPT)$(EXE)
+ $(CP) ocamldoc.hva $(OCAMLDOC_LIBA) $(OCAMLDOC_LIBCMXA) $(INSTALL_LIBDIR)
+ $(CP) $(INSTALL_MLIS) $(INSTALL_CMIS) $(INSTALL_LIBDIR)
+
+
+# backup, clean and depend :
+############################
+
+clean:: dummy
+ @rm -f *~ \#*\#
+ @rm -f $(OCAMLDOC) $(OCAMLDOC_OPT) *.cma *.cmxa *.cmo *.cmi *.cmx *.$(A) *.$(O)
+ @rm -f odoc_parser.output odoc_text_parser.output
+ @rm -f odoc_lexer.ml odoc_text_lexer.ml odoc_see_lexer.ml odoc_ocamlhtml.ml
+ @rm -f odoc_parser.ml odoc_parser.mli odoc_text_parser.ml odoc_text_parser.mli
+ @rm -rf stdlib_man
+ @rm -f generators/*.cm[aiox] generators/*.$(A) generators/*.$(O) generators/*.cmx[as]
+
+depend::
+ $(CAMLYACC) odoc_text_parser.mly
+ $(CAMLYACC) odoc_parser.mly
+ $(OCAMLLEX) odoc_text_lexer.mll
+ $(OCAMLLEX) odoc_lexer.mll
+ $(OCAMLLEX) odoc_ocamlhtml.mll
+ $(OCAMLLEX) odoc_see_lexer.mll
+ $(OCAMLDEP) $(INCLUDES_DEP) *.mll *.mly *.ml *.mli > .depend
+
+dummy:
+
+include .depend
diff --git a/ocamldoc/generators/odoc_literate.ml b/ocamldoc/generators/odoc_literate.ml
new file mode 100644
index 0000000000..94b99f0593
--- /dev/null
+++ b/ocamldoc/generators/odoc_literate.ml
@@ -0,0 +1,213 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Odoc_info
+module Naming = Odoc_html.Naming
+open Odoc_info.Value
+open Odoc_info.Module
+
+let p = Printf.bprintf
+let bp = Printf.bprintf
+let bs = Buffer.add_string
+
+module Html =
+ (val
+ (
+ match !Odoc_args.current_generator with
+ None -> (module Odoc_html.Generator : Odoc_html.Html_generator)
+ | Some (Odoc_gen.Html m) -> m
+ | _ ->
+ failwith
+ "A non-html generator is already set. Cannot install the Todo-list html generator"
+ ) : Odoc_html.Html_generator)
+;;
+
+module Generator =
+struct
+class html =
+ object (self)
+ inherit Html.html as html
+
+ method private html_of_module_comment b text =
+ let br1, br2 =
+ match text with
+ [(Odoc_info.Title (n, l_opt, t))] -> false, false
+ | (Odoc_info.Title (n, l_opt, t)) :: _ -> false, true
+ | _ -> true, true
+ in
+ if br1 then p b "<br/>";
+ self#html_of_text b text;
+ if br2 then p b "<br/><br/>\n"
+
+ method private html_of_Title b n l_opt t =
+ let label1 = self#create_title_label (n, l_opt, t) in
+ p b "<a name=\"%s\"></a>\n" (Naming.label_target label1);
+ p b "<h%d>" n;
+ self#html_of_text b t;
+ p b "</h%d>" n
+
+ val mutable code_id = 0
+ method private code_block b code =
+ code_id <- code_id + 1;
+ Printf.bprintf b
+ "<span class=\"code_expand\" onclick=\"\
+ if(document.getElementById('code%d').style.display=='none') {\
+ document.getElementById('code%d').style.display='block';\
+ } else {\
+ document.getElementById('code%d').style.display='none';\
+ }\">\
+ <img src=\"expand_collapse.png\" alt=\"+/-\"/></span>"
+ code_id code_id code_id;
+ Printf.bprintf b "<div id=\"code%d\" class=\"codeblock\">" code_id;
+ self#html_of_code b code;
+ Printf.bprintf b "</div>"
+
+ (** Print html code for a value. *)
+ method private html_of_value b v =
+ Odoc_info.reset_type_names ();
+ self#html_of_info b v.val_info;
+ bs b "<pre>";
+ bs b (self#keyword "val");
+ bs b " ";
+ (* html mark *)
+ bp b "<a name=\"%s\"></a>" (Naming.value_target v);
+ bs b (self#escape (Name.simple v.val_name));
+ bs b " : ";
+ self#html_of_type_expr b (Name.father v.val_name) v.val_type;
+ bs b "</pre>";
+ (
+ if !Odoc_html.with_parameter_list then
+ self#html_of_parameter_list b (Name.father v.val_name) v.val_parameters
+ else
+ self#html_of_described_parameter_list b (Name.father v.val_name) v.val_parameters
+ );
+ (
+ match v.val_code with
+ None -> ()
+ | Some code ->
+ self#code_block b code
+ )
+(*
+ (** Print html code for a module. *)
+ method private html_of_module b ?(info=true) ?(complete=true) ?(with_link=true) m =
+ let (html_file, _) = Naming.html_files m.m_name in
+ let father = Name.father m.m_name in
+ bs b "<pre>";
+ bs b ((self#keyword "module")^" ");
+ (
+ if with_link then
+ bp b "<a href=\"%s\">%s</a>" html_file (Name.simple m.m_name)
+ else
+ bs b (Name.simple m.m_name)
+ );
+(* A remettre quand on compilera avec ocaml 3.10
+ (
+ match m.m_kind with
+ Module_functor _ when !Odoc_info.Args.html_short_functors ->
+ ()
+
+ | _ -> *) bs b ": ";
+ (*
+ );
+ *)
+ self#html_of_module_kind b father ~modu: m m.m_kind;
+ bs b "</pre>";
+ if info && complete then
+ self#html_of_info ~indent: false b m.m_info
+
+*)
+ initializer
+ default_style_options <-
+ ["a:visited {color : #416DFF; text-decoration : none; }" ;
+ "a:link {color : #416DFF; text-decoration : none;}" ;
+ "a:hover {color : Red; text-decoration : none; background-color: #5FFF88}" ;
+ "a:active {color : Red; text-decoration : underline; }" ;
+ ".keyword { font-weight : bold ; color : Red }" ;
+ ".keywordsign { color : #C04600 }" ;
+ ".superscript { font-size : 0.6em }" ;
+ ".subscript { font-size : 0.6em }" ;
+ ".comment { color : Green }" ;
+ ".constructor { color : Blue }" ;
+ ".type { color : #5C6585 }" ;
+ ".string { color : Maroon }" ;
+ ".warning { color : Red ; font-weight : bold }" ;
+ ".info { margin-top: 8px; }";
+ ".param_info { margin-top: 4px; margin-left : 3em; margin-right : 3em }" ;
+ ".code { color : #465F91 ; }" ;
+ "h1 { font-size : 20pt ; text-align: center; }" ;
+
+ "h2 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90BDFF ;"^
+ "padding: 2px; }" ;
+
+ "h3 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90DDFF ;"^
+ "padding: 2px; }" ;
+
+ "h4 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90EDFF ;"^
+ "padding: 2px; }" ;
+
+ "h5 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90FDFF ;"^
+ "padding: 2px; }" ;
+
+ "h6 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #C0FFFF ; "^
+ "padding: 2px; }" ;
+
+ "div.h7 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #E0FFFF ; "^
+ "padding: 2px; }" ;
+
+ "div.h8 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #F0FFFF ; "^
+ "padding: 2px; }" ;
+
+ "div.h9 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #FFFFFF ; "^
+ "padding: 2px; }" ;
+
+ ".typetable { border-style : hidden }" ;
+ ".indextable { border-style : hidden }" ;
+ ".paramstable { border-style : hidden ; padding: 5pt 5pt}" ;
+ "body { background-color : White }" ;
+ "tr { background-color : White }" ;
+ "td.typefieldcomment { background-color : #FFFFFF ; font-size: smaller ;}" ;
+ "pre { margin-bottom: 4px ; margin-left: 1em; "^
+ "border-color: #27408b; border-style: solid; "^
+ "border-width: 1px 1px 1px 3px; "^
+ "padding: 4px; }" ;
+ "div.sig_block {margin-left: 2em}" ;
+
+ "div.codeblock { "^
+ "margin-left: 2em; margin-right: 1em; padding: 6px; "^
+ "margin-bottom: 8px; display: none; "^
+ "border-width: 1px 1px 1px 3px; border-style: solid; border-color: grey; }" ;
+
+ "span.code_expand { color: blue; text-decoration: underline; cursor: pointer; "^
+ "margin-left: 1em ; } ";
+ ];
+ end
+end
+
+let _ = Odoc_args.set_generator
+ (Odoc_gen.Html (module Generator : Odoc_html.Html_generator))
+ ;;
diff --git a/ocamldoc/generators/odoc_todo.ml b/ocamldoc/generators/odoc_todo.ml
new file mode 100644
index 0000000000..9dbf9f3759
--- /dev/null
+++ b/ocamldoc/generators/odoc_todo.ml
@@ -0,0 +1,232 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2010 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** An OCamldoc generator to retrieve information in "todo" tags and
+ generate an html page with all todo items. *)
+
+open Odoc_info
+module Naming = Odoc_html.Naming
+open Odoc_info.Value
+open Odoc_info.Module
+open Odoc_info.Type
+open Odoc_info.Extension
+open Odoc_info.Exception
+open Odoc_info.Class
+
+let p = Printf.bprintf
+
+module Html =
+ (val
+ (
+ match !Odoc_args.current_generator with
+ None -> (module Odoc_html.Generator : Odoc_html.Html_generator)
+ | Some (Odoc_gen.Html m) -> m
+ | _ ->
+ failwith
+ "A non-html generator is already set. Cannot install the Todo-list html generator"
+ ) : Odoc_html.Html_generator)
+;;
+
+module Generator =
+struct
+ class scanner html =
+ object (self)
+ inherit Odoc_info.Scan.scanner
+
+ val b = Buffer.create 256
+ method buffer = b
+
+ method private gen_if_tag name target info_opt =
+ match info_opt with
+ None -> ()
+ | Some i ->
+ let l =
+ List.fold_left
+ (fun acc (t, text) ->
+ match t with
+ "todo" ->
+ begin
+ match text with
+ (Odoc_info.Code s) :: q ->
+ (
+ try
+ let n = int_of_string s in
+ let head =
+ Odoc_info.Code (Printf.sprintf "[%d] " n)
+ in
+ (Some n, head::q) :: acc
+ with _ -> (None, text) :: acc
+ )
+ | _ -> (None, text) :: acc
+
+ end
+ | _ -> acc
+ )
+ []
+ i.i_custom
+ in
+ match l with
+ [] -> ()
+ | _ ->
+ let l = List.sort
+ (fun a b ->
+ match a, b with
+ (None, _), _ -> -1
+ | _, (None, _) -> 1
+ | (Some n1, _), (Some n2, _) -> compare n1 n2
+ )
+ l
+ in
+ p b "<pre><a href=\"%s\">%s</a></pre><div class=\"info\">"
+ target name;
+ let col = function
+ None -> "#000000"
+ | Some 1 -> "#FF0000"
+ | Some 2 -> "#AA5555"
+ | Some 3 -> "#44BB00"
+ | Some n -> Printf.sprintf "#%2x0000" (0xAA - (n * 0x10))
+ in
+ List.iter
+ (fun (n, e) ->
+ Printf.bprintf b "<span style=\"color: %s\">" (col n);
+ html#html_of_text b e;
+ p b "</span><br/>\n";
+ )
+ l;
+ p b "</div>"
+
+ method scan_value v =
+ self#gen_if_tag
+ v.val_name
+ (Odoc_html.Naming.complete_value_target v)
+ v.val_info
+
+ method scan_type t =
+ self#gen_if_tag
+ t.ty_name
+ (Odoc_html.Naming.complete_type_target t)
+ t.ty_info
+
+ method scan_extension_constructor x =
+ self#gen_if_tag
+ x.xt_name
+ (Odoc_html.Naming.complete_extension_target x)
+ x.xt_type_extension.te_info
+
+ method scan_exception e =
+ self#gen_if_tag
+ e.ex_name
+ (Odoc_html.Naming.complete_exception_target e)
+ e.ex_info
+
+ method scan_attribute a =
+ self#gen_if_tag
+ a.att_value.val_name
+ (Odoc_html.Naming.complete_attribute_target a)
+ a.att_value.val_info
+
+ method scan_method m =
+ self#gen_if_tag
+ m.met_value.val_name
+ (Odoc_html.Naming.complete_method_target m)
+ m.met_value.val_info
+
+ (** This method scan the elements of the given module. *)
+ method scan_module_elements m =
+ List.iter
+ (fun ele ->
+ match ele with
+ Odoc_module.Element_module m -> self#scan_module m
+ | Odoc_module.Element_module_type mt -> self#scan_module_type mt
+ | Odoc_module.Element_included_module im -> self#scan_included_module im
+ | Odoc_module.Element_class c -> self#scan_class c
+ | Odoc_module.Element_class_type ct -> self#scan_class_type ct
+ | Odoc_module.Element_value v -> self#scan_value v
+ | Odoc_module.Element_type_extension te -> self#scan_type_extension te
+ | Odoc_module.Element_exception e -> self#scan_exception e
+ | Odoc_module.Element_type t -> self#scan_type t
+ | Odoc_module.Element_module_comment t -> self#scan_module_comment t
+ )
+ (Odoc_module.module_elements ~trans: false m)
+
+ method scan_included_module _ = ()
+
+ method scan_class_pre c =
+ self#gen_if_tag
+ c.cl_name
+ (fst (Odoc_html.Naming.html_files c.cl_name))
+ c.cl_info;
+ true
+
+ method scan_class_type_pre ct =
+ self#gen_if_tag
+ ct.clt_name
+ (fst (Odoc_html.Naming.html_files ct.clt_name))
+ ct.clt_info;
+ true
+
+ method scan_module_pre m =
+ self#gen_if_tag
+ m.m_name
+ (fst (Odoc_html.Naming.html_files m.m_name))
+ m.m_info;
+ true
+
+ method scan_module_type_pre mt =
+ self#gen_if_tag
+ mt.mt_name
+ (fst (Odoc_html.Naming.html_files mt.mt_name))
+ mt.mt_info;
+ true
+ end
+
+ class html : Html.html =
+ object (self)
+ inherit Html.html as html
+
+ (** we have to hack a little because we cannot inherit from
+ scanner, since public method cannot be hidden and
+ our html class must respect the type of the default
+ html generator class *)
+ val mutable scanner = new scanner (new Html.html )
+
+ method generate modules =
+ (* prevent having the 'todo' tag signaled as not handled *)
+ tag_functions <- ("todo", (fun _ -> "")) :: tag_functions;
+ (* generate doc as usual *)
+ html#generate modules;
+ (* then retrieve the todo tags and generate the todo.html page *)
+ let title =
+ match !Odoc_info.Global.title with
+ None -> ""
+ | Some s -> s
+ in
+ let b = Buffer.create 512 in
+ p b "<html>";
+ self#print_header b title ;
+ p b "<body><h1>%s</h1>" title;
+ scanner#scan_module_list modules;
+ Buffer.add_buffer b scanner#buffer;
+ let oc = open_out
+ (Filename.concat !Odoc_info.Global.target_dir "todo.html")
+ in
+ Buffer.output_buffer oc b;
+ close_out oc
+
+ initializer
+ scanner <- new scanner self
+ end
+end
+
+let _ = Odoc_args.set_generator
+ (Odoc_gen.Html (module Generator : Odoc_html.Html_generator))
+ ;;
diff --git a/ocamldoc/ocamldoc.hva b/ocamldoc/ocamldoc.hva
new file mode 100644
index 0000000000..1fb271ade3
--- /dev/null
+++ b/ocamldoc/ocamldoc.hva
@@ -0,0 +1,31 @@
+%(***********************************************************************)
+%(* *)
+%(* OCamldoc *)
+%(* *)
+%(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+%(* *)
+%(* Copyright 2001 Institut National de Recherche en Informatique et *)
+%(* en Automatique. All rights reserved. This file is distributed *)
+%(* under the terms of the Q Public License version 1.0. *)
+%(* *)
+%(***********************************************************************)
+
+\usepackage{alltt}
+\newenvironment{ocamldoccode}{\begin{alltt}}{\end{alltt}}
+\newenvironment{ocamldocdescription}{\begin{quote}}{\end{quote}}
+\newenvironment{ocamldoccomment}{\begin{quote}}{\end{quote}}
+\newcommand\textbar{|}
+\newcommand\textbackslash{\begin{rawhtml}\\end{rawhtml}}
+\newcommand\textasciicircum{\^{}}
+\newcommand\sharp{#}
+
+\let\ocamldocvspace\vspace
+\newenvironment{ocamldocindent}{\list{}{}\item\relax}{\endlist}
+\newenvironment{ocamldocsigend}
+ {\noindent\quad\texttt{sig}\ocamldocindent}
+ {\endocamldocindent\vskip -\lastskip
+ \noindent\quad\texttt{end}\medskip}
+\newenvironment{ocamldocobjectend}
+ {\noindent\quad\texttt{object}\ocamldocindent}
+ {\endocamldocindent\vskip -\lastskip
+ \noindent\quad\texttt{end}\medskip}
diff --git a/ocamldoc/ocamldoc.sty b/ocamldoc/ocamldoc.sty
new file mode 100644
index 0000000000..6a8ef1e959
--- /dev/null
+++ b/ocamldoc/ocamldoc.sty
@@ -0,0 +1,58 @@
+%% Support macros for LaTeX documentation generated by ocamldoc.
+%% This file is in the public domain; do what you want with it.
+
+\NeedsTeXFormat{LaTeX2e}
+\ProvidesPackage{ocamldoc}
+ [2001/12/04 v1.0 ocamldoc support]
+
+\newenvironment{ocamldoccode}{%
+ \bgroup
+ \leftskip\@totalleftmargin
+ \rightskip\z@skip
+ \parindent\z@
+ \parfillskip\@flushglue
+ \parskip\z@skip
+ %\noindent
+ \@@par\smallskip
+ \@tempswafalse
+ \def\par{%
+ \if@tempswa
+ \leavevmode\null\@@par\penalty\interlinepenalty
+ \else
+ \@tempswatrue
+ \ifhmode\@@par\penalty\interlinepenalty\fi
+ \fi}
+ \obeylines
+ \verbatim@font
+ \let\org@prime~%
+ \@noligs
+ \let\org@dospecials\dospecials
+ \g@remfrom@specials{\\}
+ \g@remfrom@specials{\{}
+ \g@remfrom@specials{\}}
+ \let\do\@makeother
+ \dospecials
+ \let\dospecials\org@dospecials
+ \frenchspacing\@vobeyspaces
+ \everypar \expandafter{\the\everypar \unpenalty}}
+{\egroup\par}
+
+\def\g@remfrom@specials#1{%
+ \def\@new@specials{}
+ \def\@remove##1{%
+ \ifx##1#1\else
+ \g@addto@macro\@new@specials{\do ##1}\fi}
+ \let\do\@remove\dospecials
+ \let\dospecials\@new@specials
+ }
+
+\newenvironment{ocamldocdescription}
+{\list{}{\rightmargin0pt \topsep0pt}\raggedright\item\relax}
+{\endlist\medskip}
+
+\newenvironment{ocamldoccomment}
+{\list{}{\leftmargin 2\leftmargini \rightmargin0pt \topsep0pt}\raggedright\item\relax}
+{\endlist}
+
+\let\ocamldocvspace\vspace
+\endinput
diff --git a/ocamldoc/odoc.ml b/ocamldoc/odoc.ml
new file mode 100644
index 0000000000..483db75fe8
--- /dev/null
+++ b/ocamldoc/odoc.ml
@@ -0,0 +1,136 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Main module for bytecode.
+@todo coucou le todo*)
+
+open Config
+open Clflags
+open Misc
+open Format
+open Typedtree
+
+module M = Odoc_messages
+
+let print_DEBUG s = print_string s ; print_newline ()
+
+(* we check if we must load a module given on the command line *)
+let arg_list = Array.to_list Sys.argv
+let (plugins, paths) =
+ let rec iter (files, incs) = function
+ [] | _ :: [] -> (List.rev files, List.rev incs)
+ | "-g" :: file :: q when
+ ((Filename.check_suffix file "cmo") ||
+ (Filename.check_suffix file "cma") ||
+ (Filename.check_suffix file "cmxs")) ->
+ iter (file :: files, incs) q
+ | "-i" :: dir :: q ->
+ iter (files, dir :: incs) q
+ | _ :: q ->
+ iter (files, incs) q
+ in
+ iter ([], []) arg_list
+
+let _ = print_DEBUG "Fin analyse des arguments pour le dynamic load"
+
+(** Return the real name of the file to load,
+ searching it in the paths if it is
+ a simple name and not in the current directory. *)
+let get_real_filename name =
+ if Filename.basename name <> name then
+ name
+ else
+ (
+ let paths = Filename.current_dir_name :: paths @ [Odoc_config.custom_generators_path] in
+ try
+ let d = List.find
+ (fun d -> Sys.file_exists (Filename.concat d name))
+ paths
+ in
+ Filename.concat d name
+ with
+ Not_found ->
+ failwith (M.file_not_found_in_paths paths name)
+ )
+
+let load_plugin file =
+ let file = Dynlink.adapt_filename file in
+ Dynlink.allow_unsafe_modules true;
+ try
+ let real_file = get_real_filename file in
+ ignore(Dynlink.loadfile real_file)
+ with
+ Dynlink.Error e ->
+ prerr_endline (Odoc_messages.load_file_error file (Dynlink.error_message e)) ;
+ exit 1
+ | Not_found ->
+ prerr_endline (Odoc_messages.load_file_error file "Not_found");
+ exit 1
+ | Sys_error s
+ | Failure s ->
+ prerr_endline (Odoc_messages.load_file_error file s);
+ exit 1
+;;
+List.iter load_plugin plugins;;
+
+let () = print_DEBUG "Fin du chargement dynamique eventuel"
+
+let () = Odoc_args.parse ()
+
+
+let loaded_modules =
+ List.flatten
+ (List.map
+ (fun f ->
+ Odoc_info.verbose (Odoc_messages.loading f);
+ try
+ let l = Odoc_analyse.load_modules f in
+ Odoc_info.verbose Odoc_messages.ok;
+ l
+ with Failure s ->
+ prerr_endline s ;
+ incr Odoc_global.errors ;
+ []
+ )
+ !Odoc_global.load
+ )
+
+let modules = Odoc_analyse.analyse_files ~init: loaded_modules !Odoc_global.files
+
+let _ =
+ match !Odoc_global.dump with
+ None -> ()
+ | Some f ->
+ try Odoc_analyse.dump_modules f modules
+ with Failure s ->
+ prerr_endline s ;
+ incr Odoc_global.errors
+
+
+let _ =
+ match !Odoc_args.current_generator with
+ None ->
+ ()
+ | Some gen ->
+ let generator = Odoc_gen.get_minimal_generator gen in
+ Odoc_info.verbose Odoc_messages.generating_doc;
+ generator#generate modules;
+ Odoc_info.verbose Odoc_messages.ok
+
+let _ =
+ if !Odoc_global.errors > 0 then
+ (
+ prerr_endline (Odoc_messages.errors_occured !Odoc_global.errors) ;
+ exit 1
+ )
+ else
+ exit 0
diff --git a/ocamldoc/odoc_analyse.ml b/ocamldoc/odoc_analyse.ml
new file mode 100644
index 0000000000..a5ce18cba0
--- /dev/null
+++ b/ocamldoc/odoc_analyse.ml
@@ -0,0 +1,466 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Analysis of source files. This module is strongly inspired from
+ driver/main.ml :-) *)
+
+let print_DEBUG s = print_string s ; print_newline ()
+
+open Config
+open Clflags
+open Misc
+open Format
+open Typedtree
+
+
+(** Initialize the search path.
+ The current directory is always searched first,
+ then the directories specified with the -I option (in command-line order),
+ then the standard library directory. *)
+let init_path () =
+ load_path :=
+ "" :: List.rev (Config.standard_library :: !Clflags.include_dirs);
+ Env.reset_cache ()
+
+(** Return the initial environment in which compilation proceeds. *)
+let initial_env () =
+ let initial =
+ if !Clflags.unsafe_string then Env.initial_unsafe_string
+ else Env.initial_safe_string
+ in
+ try
+ if !Clflags.nopervasives then initial else
+ Env.open_pers_signature "Pervasives" initial
+ with Not_found ->
+ fatal_error "cannot open pervasives.cmi"
+
+(** Optionally preprocess a source file *)
+let preprocess sourcefile =
+ try
+ Pparse.preprocess sourcefile
+ with Pparse.Error err ->
+ Format.eprintf "Preprocessing error@.%a@."
+ Pparse.report_error err;
+ exit 2
+
+let (++) x f = f x
+
+(** Analysis of an implementation file. Returns (Some typedtree) if
+ no error occured, else None and an error message is printed.*)
+
+let tool_name = "ocamldoc"
+
+let process_implementation_file ppf sourcefile =
+ init_path ();
+ let prefixname = Filename.chop_extension sourcefile in
+ let modulename = String.capitalize_ascii(Filename.basename prefixname) in
+ Env.set_unit_name modulename;
+ let inputfile = preprocess sourcefile in
+ let env = initial_env () in
+ try
+ let parsetree =
+ Pparse.file ~tool_name Format.err_formatter inputfile
+ Parse.implementation ast_impl_magic_number
+ in
+ let typedtree =
+ Typemod.type_implementation
+ sourcefile prefixname modulename env parsetree
+ in
+ (Some (parsetree, typedtree), inputfile)
+ with
+ e ->
+ match e with
+ Syntaxerr.Error err ->
+ fprintf Format.err_formatter "@[%a@]@."
+ Syntaxerr.report_error err;
+ None, inputfile
+ | Failure s ->
+ prerr_endline s;
+ incr Odoc_global.errors ;
+ None, inputfile
+ | e ->
+ raise e
+
+(** Analysis of an interface file. Returns (Some signature) if
+ no error occured, else None and an error message is printed.*)
+let process_interface_file ppf sourcefile =
+ init_path ();
+ let prefixname = Filename.chop_extension sourcefile in
+ let modulename = String.capitalize_ascii(Filename.basename prefixname) in
+ Env.set_unit_name modulename;
+ let inputfile = preprocess sourcefile in
+ let ast =
+ Pparse.file ~tool_name Format.err_formatter inputfile
+ Parse.interface ast_intf_magic_number
+ in
+ let sg = Typemod.type_interface (initial_env()) ast in
+ Warnings.check_fatal ();
+ (ast, sg, inputfile)
+
+(** The module used to analyse the parsetree and signature of an implementation file.*)
+module Ast_analyser = Odoc_ast.Analyser (Odoc_comments.Basic_info_retriever)
+
+(** The module used to analyse the parse tree and typed tree of an interface file.*)
+module Sig_analyser = Odoc_sig.Analyser (Odoc_comments.Basic_info_retriever)
+
+(** Handle an error. *)
+
+let process_error exn =
+ match Location.error_of_exn exn with
+ | Some err ->
+ fprintf Format.err_formatter "@[%a@]@." Location.report_error err
+ | None ->
+ fprintf Format.err_formatter
+ "Compilation error(%s). Use the OCaml compiler to get more details.@."
+ (Printexc.to_string exn)
+
+(** Process the given file, according to its extension. Return the Module.t created, if any.*)
+let process_file ppf sourcefile =
+ if !Odoc_global.verbose then
+ (
+ let f = match sourcefile with
+ Odoc_global.Impl_file f
+ | Odoc_global.Intf_file f -> f
+ | Odoc_global.Text_file f -> f
+ in
+ print_string (Odoc_messages.analysing f) ;
+ print_newline ();
+ );
+ match sourcefile with
+ Odoc_global.Impl_file file ->
+ (
+ Location.input_name := file;
+ try
+ let (parsetree_typedtree_opt, input_file) = process_implementation_file ppf file in
+ match parsetree_typedtree_opt with
+ None ->
+ None
+ | Some (parsetree, typedtree) ->
+ let file_module = Ast_analyser.analyse_typed_tree file
+ !Location.input_name parsetree typedtree
+ in
+ file_module.Odoc_module.m_top_deps <- Odoc_dep.impl_dependencies parsetree ;
+
+ if !Odoc_global.verbose then
+ (
+ print_string Odoc_messages.ok;
+ print_newline ()
+ );
+ Pparse.remove_preprocessed input_file;
+ Some file_module
+ with
+ | Sys_error s
+ | Failure s ->
+ prerr_endline s ;
+ incr Odoc_global.errors ;
+ None
+ | e ->
+ process_error e ;
+ incr Odoc_global.errors ;
+ None
+ )
+ | Odoc_global.Intf_file file ->
+ (
+ Location.input_name := file;
+ try
+ let (ast, signat, input_file) = process_interface_file ppf file in
+ let file_module = Sig_analyser.analyse_signature file
+ !Location.input_name ast signat.sig_type
+ in
+
+ file_module.Odoc_module.m_top_deps <- Odoc_dep.intf_dependencies ast ;
+
+ if !Odoc_global.verbose then
+ (
+ print_string Odoc_messages.ok;
+ print_newline ()
+ );
+ Pparse.remove_preprocessed input_file;
+ Some file_module
+ with
+ | Sys_error s
+ | Failure s ->
+ prerr_endline s;
+ incr Odoc_global.errors ;
+ None
+ | e ->
+ process_error e ;
+ incr Odoc_global.errors ;
+ None
+ )
+ | Odoc_global.Text_file file ->
+ Location.input_name := file;
+ try
+ let mod_name =
+ let s =
+ try Filename.chop_extension file
+ with _ -> file
+ in
+ String.capitalize_ascii (Filename.basename s)
+ in
+ let txt =
+ try Odoc_text.Texter.text_of_string (Odoc_misc.input_file_as_string file)
+ with Odoc_text.Text_syntax (l, c, s) ->
+ raise (Failure (Odoc_messages.text_parse_error l c s))
+ in
+ let m =
+ {
+ Odoc_module.m_name = mod_name ;
+ Odoc_module.m_type = Types.Mty_signature [] ;
+ Odoc_module.m_info = None ;
+ Odoc_module.m_is_interface = true ;
+ Odoc_module.m_file = file ;
+ Odoc_module.m_kind = Odoc_module.Module_struct
+ [Odoc_module.Element_module_comment txt] ;
+ Odoc_module.m_loc =
+ { Odoc_types.loc_impl = None ;
+ Odoc_types.loc_inter = Some (Location.in_file file) } ;
+ Odoc_module.m_top_deps = [] ;
+ Odoc_module.m_code = None ;
+ Odoc_module.m_code_intf = None ;
+ Odoc_module.m_text_only = true ;
+ }
+ in
+ Some m
+ with
+ | Sys_error s
+ | Failure s ->
+ prerr_endline s;
+ incr Odoc_global.errors ;
+ None
+ | e ->
+ process_error e ;
+ incr Odoc_global.errors ;
+ None
+
+(** Remove the class elements between the stop special comments. *)
+let rec remove_class_elements_between_stop keep eles =
+ match eles with
+ [] -> []
+ | ele :: q ->
+ match ele with
+ Odoc_class.Class_comment [ Odoc_types.Raw "/*" ] ->
+ remove_class_elements_between_stop (not keep) q
+ | Odoc_class.Class_attribute _
+ | Odoc_class.Class_method _
+ | Odoc_class.Class_comment _ ->
+ if keep then
+ ele :: (remove_class_elements_between_stop keep q)
+ else
+ remove_class_elements_between_stop keep q
+
+(** Remove the class elements between the stop special comments in a class kind. *)
+let rec remove_class_elements_between_stop_in_class_kind k =
+ match k with
+ Odoc_class.Class_structure (inher, l) ->
+ Odoc_class.Class_structure (inher, remove_class_elements_between_stop true l)
+ | Odoc_class.Class_apply _ -> k
+ | Odoc_class.Class_constr _ -> k
+ | Odoc_class.Class_constraint (k1, ctk) ->
+ Odoc_class.Class_constraint (remove_class_elements_between_stop_in_class_kind k1,
+ remove_class_elements_between_stop_in_class_type_kind ctk)
+
+(** Remove the class elements beetween the stop special comments in a class type kind. *)
+and remove_class_elements_between_stop_in_class_type_kind tk =
+ match tk with
+ Odoc_class.Class_signature (inher, l) ->
+ Odoc_class.Class_signature (inher, remove_class_elements_between_stop true l)
+ | Odoc_class.Class_type _ -> tk
+
+
+(** Remove the module elements between the stop special comments. *)
+let rec remove_module_elements_between_stop keep eles =
+ let f = remove_module_elements_between_stop in
+ match eles with
+ [] -> []
+ | ele :: q ->
+ match ele with
+ Odoc_module.Element_module_comment [ Odoc_types.Raw "/*" ] ->
+ f (not keep) q
+ | Odoc_module.Element_module_comment _ ->
+ if keep then
+ ele :: (f keep q)
+ else
+ f keep q
+ | Odoc_module.Element_module m ->
+ if keep then
+ (
+ m.Odoc_module.m_kind <- remove_module_elements_between_stop_in_module_kind m.Odoc_module.m_kind ;
+ (Odoc_module.Element_module m) :: (f keep q)
+ )
+ else
+ f keep q
+ | Odoc_module.Element_module_type mt ->
+ if keep then
+ (
+ mt.Odoc_module.mt_kind <- Odoc_misc.apply_opt
+ remove_module_elements_between_stop_in_module_type_kind mt.Odoc_module.mt_kind ;
+ (Odoc_module.Element_module_type mt) :: (f keep q)
+ )
+ else
+ f keep q
+ | Odoc_module.Element_included_module _ ->
+ if keep then
+ ele :: (f keep q)
+ else
+ f keep q
+ | Odoc_module.Element_class c ->
+ if keep then
+ (
+ c.Odoc_class.cl_kind <- remove_class_elements_between_stop_in_class_kind c.Odoc_class.cl_kind ;
+ (Odoc_module.Element_class c) :: (f keep q)
+ )
+ else
+ f keep q
+ | Odoc_module.Element_class_type ct ->
+ if keep then
+ (
+ ct.Odoc_class.clt_kind <- remove_class_elements_between_stop_in_class_type_kind ct.Odoc_class.clt_kind ;
+ (Odoc_module.Element_class_type ct) :: (f keep q)
+ )
+ else
+ f keep q
+ | Odoc_module.Element_value _
+ | Odoc_module.Element_type_extension _
+ | Odoc_module.Element_exception _
+ | Odoc_module.Element_type _ ->
+ if keep then
+ ele :: (f keep q)
+ else
+ f keep q
+
+
+(** Remove the module elements between the stop special comments, in the given module kind. *)
+and remove_module_elements_between_stop_in_module_kind k =
+ match k with
+ | Odoc_module.Module_struct l -> Odoc_module.Module_struct (remove_module_elements_between_stop true l)
+ | Odoc_module.Module_alias _ -> k
+ | Odoc_module.Module_functor (params, k2) ->
+ Odoc_module.Module_functor (params, remove_module_elements_between_stop_in_module_kind k2)
+ | Odoc_module.Module_apply (k1, k2) ->
+ Odoc_module.Module_apply (remove_module_elements_between_stop_in_module_kind k1,
+ remove_module_elements_between_stop_in_module_kind k2)
+ | Odoc_module.Module_with (mtkind, s) ->
+ Odoc_module.Module_with (remove_module_elements_between_stop_in_module_type_kind mtkind, s)
+ | Odoc_module.Module_constraint (k2, mtkind) ->
+ Odoc_module.Module_constraint (remove_module_elements_between_stop_in_module_kind k2,
+ remove_module_elements_between_stop_in_module_type_kind mtkind)
+ | Odoc_module.Module_typeof _ -> k
+ | Odoc_module.Module_unpack _ -> k
+
+(** Remove the module elements between the stop special comment, in the given module type kind. *)
+and remove_module_elements_between_stop_in_module_type_kind tk =
+ match tk with
+ | Odoc_module.Module_type_struct l -> Odoc_module.Module_type_struct (remove_module_elements_between_stop true l)
+ | Odoc_module.Module_type_functor (params, tk2) ->
+ Odoc_module.Module_type_functor (params, remove_module_elements_between_stop_in_module_type_kind tk2)
+ | Odoc_module.Module_type_alias _ -> tk
+ | Odoc_module.Module_type_with (tk2, s) ->
+ Odoc_module.Module_type_with (remove_module_elements_between_stop_in_module_type_kind tk2, s)
+ | Odoc_module.Module_type_typeof _ -> tk
+
+(** Remove elements between the stop special comment. *)
+let remove_elements_between_stop module_list =
+ List.map
+ (fun m ->
+ m.Odoc_module.m_kind <- remove_module_elements_between_stop_in_module_kind m.Odoc_module.m_kind;
+ m
+ )
+ module_list
+
+(** This function builds the modules from the given list of source files. *)
+let analyse_files ?(init=[]) files =
+ let modules_pre =
+ init @
+ (List.fold_left
+ (fun acc -> fun file ->
+ try
+ match process_file Format.err_formatter file with
+ None ->
+ acc
+ | Some m ->
+ acc @ [ m ]
+ with
+ Failure s ->
+ prerr_endline s ;
+ incr Odoc_global.errors ;
+ acc
+ )
+ []
+ files
+ )
+ in
+ (* Remove elements between the stop special comments, if needed. *)
+ let modules =
+ if !Odoc_global.no_stop then
+ modules_pre
+ else
+ remove_elements_between_stop modules_pre
+ in
+
+
+ if !Odoc_global.verbose then
+ (
+ print_string Odoc_messages.merging;
+ print_newline ()
+ );
+ let merged_modules = Odoc_merge.merge !Odoc_global.merge_options modules in
+ if !Odoc_global.verbose then
+ (
+ print_string Odoc_messages.ok;
+ print_newline ();
+ );
+ let modules_list =
+ (List.fold_left
+ (fun acc -> fun m -> acc @ (Odoc_module.module_all_submodules ~trans: false m))
+ merged_modules
+ merged_modules
+ )
+ in
+ if !Odoc_global.verbose then
+ (
+ print_string Odoc_messages.cross_referencing;
+ print_newline ()
+ );
+ let _ = Odoc_cross.associate modules_list in
+
+ if !Odoc_global.verbose then
+ (
+ print_string Odoc_messages.ok;
+ print_newline ();
+ );
+
+ if !Odoc_global.sort_modules then
+ List.sort (fun m1 m2 -> compare m1.Odoc_module.m_name m2.Odoc_module.m_name) merged_modules
+ else
+ merged_modules
+
+let dump_modules file (modules : Odoc_module.t_module list) =
+ try
+ let chanout = open_out_bin file in
+ let dump = Odoc_types.make_dump modules in
+ output_value chanout dump;
+ close_out chanout
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+let load_modules file =
+ try
+ let chanin = open_in_bin file in
+ let dump = input_value chanin in
+ close_in chanin ;
+ let (l : Odoc_module.t_module list) = Odoc_types.open_dump dump in
+ l
+ with
+ Sys_error s ->
+ raise (Failure s)
diff --git a/ocamldoc/odoc_analyse.mli b/ocamldoc/odoc_analyse.mli
new file mode 100644
index 0000000000..c155e81af9
--- /dev/null
+++ b/ocamldoc/odoc_analyse.mli
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Analysis of source files. *)
+
+(** This function builds the top modules from the analysis of the
+ given list of source files.
+ @param init is the list of modules already known from a previous analysis.
+*)
+val analyse_files :
+ ?init: Odoc_module.t_module list ->
+ Odoc_global.source_file list ->
+ Odoc_module.t_module list
+
+(** Dump of a list of modules into a file.
+ @raise Failure if an error occurs.*)
+val dump_modules : string -> Odoc_module.t_module list -> unit
+
+(** Load of a list of modules from a file.
+ @raise Failure if an error occurs.*)
+val load_modules : string -> Odoc_module.t_module list
diff --git a/ocamldoc/odoc_args.ml b/ocamldoc/odoc_args.ml
new file mode 100644
index 0000000000..77b59025b4
--- /dev/null
+++ b/ocamldoc/odoc_args.ml
@@ -0,0 +1,395 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Command-line arguments. *)
+
+module M = Odoc_messages
+
+let current_generator = ref (None : Odoc_gen.generator option)
+
+let get_html_generator () =
+ match !current_generator with
+ None -> (module Odoc_html.Generator : Odoc_html.Html_generator)
+ | Some (Odoc_gen.Html m) -> m
+ | Some _ -> failwith (M.current_generator_is_not "html")
+;;
+
+let get_latex_generator () =
+ match !current_generator with
+ None -> (module Odoc_latex.Generator : Odoc_latex.Latex_generator)
+ | Some (Odoc_gen.Latex m) -> m
+ | Some _ -> failwith (M.current_generator_is_not "latex")
+;;
+
+let get_texi_generator () =
+ match !current_generator with
+ None -> (module Odoc_texi.Generator : Odoc_texi.Texi_generator)
+ | Some (Odoc_gen.Texi m) -> m
+ | Some _ -> failwith (M.current_generator_is_not "texi")
+;;
+
+let get_man_generator () =
+ match !current_generator with
+ None -> (module Odoc_man.Generator : Odoc_man.Man_generator)
+ | Some (Odoc_gen.Man m) -> m
+ | Some _ -> failwith (M.current_generator_is_not "man")
+;;
+
+let get_dot_generator () =
+ match !current_generator with
+ None -> (module Odoc_dot.Generator : Odoc_dot.Dot_generator)
+ | Some (Odoc_gen.Dot m) -> m
+ | Some _ -> failwith (M.current_generator_is_not "dot")
+;;
+
+let get_base_generator () =
+ match !current_generator with
+ None -> (module Odoc_gen.Base_generator : Odoc_gen.Base)
+ | Some (Odoc_gen.Base m) -> m
+ | Some _ -> failwith (M.current_generator_is_not "base")
+;;
+
+let extend_html_generator f =
+ let current = get_html_generator () in
+ let module Current = (val current : Odoc_html.Html_generator) in
+ let module F = (val f : Odoc_gen.Html_functor) in
+ let module M = F(Current) in
+ current_generator := Some (Odoc_gen.Html (module M : Odoc_html.Html_generator))
+;;
+
+let extend_latex_generator f =
+ let current = get_latex_generator () in
+ let module Current = (val current : Odoc_latex.Latex_generator) in
+ let module F = (val f : Odoc_gen.Latex_functor) in
+ let module M = F(Current) in
+ current_generator := Some(Odoc_gen.Latex (module M : Odoc_latex.Latex_generator))
+;;
+
+let extend_texi_generator f =
+ let current = get_texi_generator () in
+ let module Current = (val current : Odoc_texi.Texi_generator) in
+ let module F = (val f : Odoc_gen.Texi_functor) in
+ let module M = F(Current) in
+ current_generator := Some(Odoc_gen.Texi (module M : Odoc_texi.Texi_generator))
+;;
+
+let extend_man_generator f =
+ let current = get_man_generator () in
+ let module Current = (val current : Odoc_man.Man_generator) in
+ let module F = (val f : Odoc_gen.Man_functor) in
+ let module M = F(Current) in
+ current_generator := Some(Odoc_gen.Man (module M : Odoc_man.Man_generator))
+;;
+
+let extend_dot_generator f =
+ let current = get_dot_generator () in
+ let module Current = (val current : Odoc_dot.Dot_generator) in
+ let module F = (val f : Odoc_gen.Dot_functor) in
+ let module M = F(Current) in
+ current_generator := Some (Odoc_gen.Dot (module M : Odoc_dot.Dot_generator))
+;;
+
+let extend_base_generator f =
+ let current = get_base_generator () in
+ let module Current = (val current : Odoc_gen.Base) in
+ let module F = (val f : Odoc_gen.Base_functor) in
+ let module M = F(Current) in
+ current_generator := Some (Odoc_gen.Base (module M : Odoc_gen.Base))
+;;
+
+(** Analysis of a string defining options. Return the list of
+ options according to the list giving associations between
+ [(character, _)] and a list of options. *)
+let analyse_option_string l s =
+ List.fold_left
+ (fun acc -> fun ((c,_), v) ->
+ if String.contains s c then
+ acc @ v
+ else
+ acc)
+ []
+ l
+
+(** Analysis of a string defining the merge options to be used.
+ Returns the list of options specified.*)
+let analyse_merge_options s =
+ let l = [
+ (M.merge_description, [Odoc_types.Merge_description]) ;
+ (M.merge_author, [Odoc_types.Merge_author]) ;
+ (M.merge_version, [Odoc_types.Merge_version]) ;
+ (M.merge_see, [Odoc_types.Merge_see]) ;
+ (M.merge_since, [Odoc_types.Merge_since]) ;
+ (M.merge_before, [Odoc_types.Merge_before]) ;
+ (M.merge_deprecated, [Odoc_types.Merge_deprecated]) ;
+ (M.merge_param, [Odoc_types.Merge_param]) ;
+ (M.merge_raised_exception, [Odoc_types.Merge_raised_exception]) ;
+ (M.merge_return_value, [Odoc_types.Merge_return_value]) ;
+ (M.merge_custom, [Odoc_types.Merge_custom]) ;
+ (M.merge_all, Odoc_types.all_merge_options)
+ ]
+ in
+ analyse_option_string l s
+
+
+let f_latex_title s =
+ try
+ let pos = String.index s ',' in
+ let n = int_of_string (String.sub s 0 pos) in
+ let len = String.length s in
+ let command = String.sub s (pos + 1) (len - pos - 1) in
+ Odoc_latex.latex_titles := List.remove_assoc n !Odoc_latex.latex_titles ;
+ Odoc_latex.latex_titles := (n, command) :: !Odoc_latex.latex_titles
+ with
+ Not_found
+ | Invalid_argument _ ->
+ incr Odoc_global.errors ;
+ prerr_endline (M.wrong_format s)
+
+let add_hidden_modules s =
+ let l = Str.split (Str.regexp ",") s in
+ List.iter
+ (fun n ->
+ let name = Str.global_replace (Str.regexp "[ \n\r\t]+") "" n in
+ match name with
+ "" -> ()
+ | _ ->
+ match name.[0] with
+ 'A'..'Z' -> Odoc_global.hidden_modules := name :: !Odoc_global.hidden_modules
+ | _ ->
+ incr Odoc_global.errors;
+ prerr_endline (M.not_a_module_name name)
+ )
+ l
+
+let set_generator (g : Odoc_gen.generator) = current_generator := Some g
+
+let anonymous f =
+ let sf =
+ if Filename.check_suffix f "ml" then
+ Odoc_global.Impl_file f
+ else
+ if Filename.check_suffix f !Config.interface_suffix then
+ Odoc_global.Intf_file f
+ else
+ if Filename.check_suffix f "txt" then
+ Odoc_global.Text_file f
+ else
+ failwith (Odoc_messages.unknown_extension f)
+ in
+ Odoc_global.files := !Odoc_global.files @ [sf]
+
+module Options = Main_args.Make_ocamldoc_options(struct
+ let set r () = r := true
+ let unset r () = r := false
+ let _absname = set Location.absname
+ let _I s = Odoc_global.include_dirs :=
+ (Misc.expand_directory Config.standard_library s) :: !Odoc_global.include_dirs
+ let _impl s = Odoc_global.files := !Odoc_global.files @ [Odoc_global.Impl_file s]
+ let _intf s = Odoc_global.files := !Odoc_global.files @ [Odoc_global.Intf_file s]
+ let _intf_suffix s = Config.interface_suffix := s
+ let _labels = unset Clflags.classic
+ let _no_alias_deps = set Clflags.transparent_modules
+ let _no_app_funct = unset Clflags.applicative_functors
+ let _noassert = set Clflags.noassert
+ let _nolabels = set Clflags.classic
+ let _nostdlib = set Clflags.no_std_include
+ let _open s = Clflags.open_modules := s :: !Clflags.open_modules
+ let _pp s = Clflags.preprocessor := Some s
+ let _ppx s = Clflags.all_ppx := s :: !Clflags.all_ppx
+ let _principal = set Clflags.principal
+ let _rectypes = set Clflags.recursive_types
+ let _safe_string = unset Clflags.unsafe_string
+ let _short_paths = unset Clflags.real_paths
+ let _strict_sequence = set Clflags.strict_sequence
+ let _strict_formats = set Clflags.strict_formats
+ let _thread = set Clflags.use_threads
+ let _vmthread = set Clflags.use_vmthreads
+ let _unsafe () = assert false
+ let _unsafe_string = set Clflags.unsafe_string
+ let _v () = Compenv.print_version_and_library "documentation generator"
+ let _version = Compenv.print_version_string
+ let _vnum = Compenv.print_version_string
+ let _w = (Warnings.parse_options false)
+ let _warn_error _ = assert false
+ let _warn_help _ = assert false
+ let _where = Compenv.print_standard_library
+ let _verbose = set Clflags.verbose
+ let _nopervasives = set Clflags.nopervasives
+ let _dsource = set Clflags.dump_source
+ let _dparsetree = set Clflags.dump_parsetree
+ let _dtypedtree = set Clflags.dump_typedtree
+ let _drawlambda = set Clflags.dump_rawlambda
+ let _dlambda = set Clflags.dump_lambda
+ let _dinstr = set Clflags.dump_instr
+ let anonymous = anonymous
+end)
+
+(** The default option list *)
+let default_options = Options.list @
+[
+ "-text", Arg.String (fun s ->
+ Odoc_global.files := !Odoc_global.files @ [Odoc_global.Text_file s]),
+ M.option_text ;
+ "-warn-error", Arg.Set Odoc_global.warn_error, M.werr ;
+ "-hide-warnings", Arg.Clear Odoc_config.print_warnings, M.hide_warnings ;
+ "-o", Arg.String (fun s -> Odoc_global.out_file := s), M.out_file ;
+ "-d", Arg.String (fun s -> Odoc_global.target_dir := s), M.target_dir ;
+ "-sort", Arg.Unit (fun () -> Odoc_global.sort_modules := true), M.sort_modules ;
+ "-no-stop", Arg.Set Odoc_global.no_stop, M.no_stop ;
+ "-no-custom-tags", Arg.Set Odoc_global.no_custom_tags, M.no_custom_tags ;
+ "-stars", Arg.Set Odoc_global.remove_stars, M.remove_stars ;
+ "-inv-merge-ml-mli", Arg.Set Odoc_global.inverse_merge_ml_mli, M.inverse_merge_ml_mli ;
+ "-no-module-constraint-filter", Arg.Clear Odoc_global.filter_with_module_constraints,
+ M.no_filter_with_module_constraints ;
+
+ "-keep-code", Arg.Set Odoc_global.keep_code, M.keep_code^"\n" ;
+
+ "-dump", Arg.String (fun s -> Odoc_global.dump := Some s), M.dump ;
+ "-load", Arg.String (fun s -> Odoc_global.load := !Odoc_global.load @ [s]), M.load^"\n" ;
+
+ "-t", Arg.String (fun s -> Odoc_global.title := Some s), M.option_title ;
+ "-intro", Arg.String (fun s -> Odoc_global.intro_file := Some s), M.option_intro ;
+ "-hide", Arg.String add_hidden_modules, M.hide_modules ;
+ "-m", Arg.String (fun s -> Odoc_global.merge_options := !Odoc_global.merge_options @ (analyse_merge_options s)),
+ M.merge_options ^
+ "\n\n *** choosing a generator ***\n";
+
+(* generators *)
+ "-html", Arg.Unit (fun () -> set_generator
+ (Odoc_gen.Html (module Odoc_html.Generator : Odoc_html.Html_generator))),
+ M.generate_html ;
+ "-latex", Arg.Unit (fun () -> set_generator
+ (Odoc_gen.Latex (module Odoc_latex.Generator : Odoc_latex.Latex_generator))),
+ M.generate_latex ;
+ "-texi", Arg.Unit (fun () -> set_generator
+ (Odoc_gen.Texi (module Odoc_texi.Generator : Odoc_texi.Texi_generator))),
+ M.generate_texinfo ;
+ "-man", Arg.Unit (fun () -> set_generator
+ (Odoc_gen.Man (module Odoc_man.Generator : Odoc_man.Man_generator))),
+ M.generate_man ;
+ "-dot", Arg.Unit (fun () -> set_generator
+ (Odoc_gen.Dot (module Odoc_dot.Generator : Odoc_dot.Dot_generator))),
+ M.generate_dot ;
+ "-customdir", Arg.Unit (fun () -> Printf.printf "%s\n" Odoc_config.custom_generators_path; exit 0),
+ M.display_custom_generators_dir ;
+ "-i", Arg.String (fun s -> ()), M.add_load_dir ;
+ "-g", Arg.String (fun s -> ()), M.load_file ^
+ "\n\n *** HTML options ***\n";
+
+(* html only options *)
+ "-all-params", Arg.Set Odoc_html.with_parameter_list, M.with_parameter_list ;
+ "-css-style", Arg.String (fun s -> Odoc_html.css_style := Some s), M.css_style ;
+ "-index-only", Arg.Set Odoc_html.index_only, M.index_only ;
+ "-colorize-code", Arg.Set Odoc_html.colorize_code, M.colorize_code ;
+ "-short-functors", Arg.Set Odoc_html.html_short_functors, M.html_short_functors ;
+ "-charset", Arg.Set_string Odoc_html.charset, (M.charset !Odoc_html.charset)^
+ "\n\n *** LaTeX options ***\n";
+
+(* latex only options *)
+ "-noheader", Arg.Unit (fun () -> Odoc_global.with_header := false), M.no_header ;
+ "-notrailer", Arg.Unit (fun () -> Odoc_global.with_trailer := false), M.no_trailer ;
+ "-sepfiles", Arg.Set Odoc_latex.separate_files, M.separate_files ;
+ "-latextitle", Arg.String f_latex_title, M.latex_title Odoc_latex.latex_titles ;
+ "-latex-value-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_value_prefix := s), M.latex_value_prefix ;
+ "-latex-type-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_type_prefix := s), M.latex_type_prefix ;
+ "-latex-exception-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_exception_prefix := s), M.latex_exception_prefix ;
+ "-latex-attribute-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_attribute_prefix := s), M.latex_attribute_prefix ;
+ "-latex-method-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_method_prefix := s), M.latex_method_prefix ;
+ "-latex-module-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_module_prefix := s), M.latex_module_prefix ;
+ "-latex-module-type-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_module_type_prefix := s), M.latex_module_type_prefix ;
+ "-latex-class-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_class_prefix := s), M.latex_class_prefix ;
+ "-latex-class-type-prefix",
+ Arg.String (fun s -> Odoc_latex.latex_class_type_prefix := s), M.latex_class_type_prefix ;
+ "-notoc", Arg.Unit (fun () -> Odoc_global.with_toc := false), M.no_toc ^
+ "\n\n *** texinfo options ***\n";
+
+(* texi only options *)
+ "-noindex", Arg.Clear Odoc_global.with_index, M.no_index ;
+ "-esc8", Arg.Set Odoc_texi.esc_8bits, M.esc_8bits ;
+ "-info-section", Arg.String ((:=) Odoc_texi.info_section), M.info_section ;
+ "-info-entry", Arg.String (fun s -> Odoc_texi.info_entry := !Odoc_texi.info_entry @ [ s ]),
+ M.info_entry ^
+ "\n\n *** dot options ***\n";
+
+(* dot only options *)
+ "-dot-colors", Arg.String (fun s -> Odoc_dot.dot_colors := Str.split (Str.regexp_string ",") s), M.dot_colors ;
+ "-dot-include-all", Arg.Set Odoc_dot.dot_include_all, M.dot_include_all ;
+ "-dot-types", Arg.Set Odoc_dot.dot_types, M.dot_types ;
+ "-dot-reduce", Arg.Set Odoc_dot.dot_reduce, M.dot_reduce^
+ "\n\n *** man pages options ***\n";
+
+(* man only options *)
+ "-man-mini", Arg.Set Odoc_man.man_mini, M.man_mini ;
+ "-man-suffix", Arg.String (fun s -> Odoc_man.man_suffix := s), M.man_suffix ;
+ "-man-section", Arg.String (fun s -> Odoc_man.man_section := s), M.man_section ;
+
+]
+
+let options = ref default_options
+
+let modified_options () =
+ !options != default_options
+
+let append_last_doc suffix =
+ match List.rev !options with
+ | (key, spec, doc) :: tl ->
+ options := List.rev ((key, spec, doc ^ suffix) :: tl)
+ | [] -> ()
+
+(** The help option list, overriding the default ones from the Arg module *)
+let help_options = ref []
+let help_action () =
+ let msg =
+ Arg.usage_string
+ (!options @ !help_options)
+ (M.usage ^ M.options_are) in
+ print_string msg
+let () =
+ help_options := [
+ "-help", Arg.Unit help_action, M.help ;
+ "--help", Arg.Unit help_action, M.help
+]
+
+let add_option o =
+ if not (modified_options ()) then
+ append_last_doc "\n *** custom generator options ***\n";
+ let (s,_,_) = o in
+ let rec iter = function
+ [] -> [o]
+ | (s2,f,m) :: q ->
+ if s = s2 then
+ o :: q
+ else
+ (s2,f,m) :: (iter q)
+ in
+ options := iter !options
+
+let parse () =
+ if modified_options () then append_last_doc "\n";
+ let options = !options @ !help_options in
+ let _ = Arg.parse (Arg.align ~limit:13 options)
+ anonymous
+ (M.usage^M.options_are)
+ in
+ (* we sort the hidden modules by name, to be sure that for example,
+ A.B is before A, so we will match against A.B before A in
+ Odoc_name.hide_modules.*)
+ Odoc_global.hidden_modules :=
+ List.sort (fun a -> fun b -> - (compare a b)) !Odoc_global.hidden_modules
diff --git a/ocamldoc/odoc_args.mli b/ocamldoc/odoc_args.mli
new file mode 100644
index 0000000000..c348dfa09f
--- /dev/null
+++ b/ocamldoc/odoc_args.mli
@@ -0,0 +1,50 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Analysis of the command line arguments. *)
+
+(** The current module defining the generator to use. *)
+val current_generator : Odoc_gen.generator option ref
+
+(** To set the documentation generator. *)
+val set_generator : Odoc_gen.generator -> unit
+
+(** Extend current HTML generator.
+ @raise Failure if another kind of generator is already set.*)
+val extend_html_generator : (module Odoc_gen.Html_functor) -> unit
+
+(** Extend current LaTeX generator.
+ @raise Failure if another kind of generator is already set.*)
+val extend_latex_generator : (module Odoc_gen.Latex_functor) -> unit
+
+(** Extend current Texi generator.
+ @raise Failure if another kind of generator is already set.*)
+val extend_texi_generator : (module Odoc_gen.Texi_functor) -> unit
+
+(** Extend current man generator.
+ @raise Failure if another kind of generator is already set.*)
+val extend_man_generator : (module Odoc_gen.Man_functor) -> unit
+
+(** Extend current dot generator.
+ @raise Failure if another kind of generator is already set.*)
+val extend_dot_generator : (module Odoc_gen.Dot_functor) -> unit
+
+(** Extend current base generator.
+ @raise Failure if another kind of generator is already set.*)
+val extend_base_generator : (module Odoc_gen.Base_functor) -> unit
+
+(** Add an option specification. *)
+val add_option : string * Arg.spec * string -> unit
+
+(** Parse the args.
+ [byte] indicate if we are in bytecode mode (default is [true]).*)
+val parse : unit -> unit
diff --git a/ocamldoc/odoc_ast.ml b/ocamldoc/odoc_ast.ml
new file mode 100644
index 0000000000..3ccdce5cb9
--- /dev/null
+++ b/ocamldoc/odoc_ast.ml
@@ -0,0 +1,1932 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Analysis of implementation files. *)
+open Misc
+open Asttypes
+open Types
+open Typedtree
+
+let print_DEBUG3 s = print_string s ; print_newline ();;
+let print_DEBUG s = print_string s ; print_newline ();;
+
+type typedtree = (Typedtree.structure * Typedtree.module_coercion)
+
+module Name = Odoc_name
+open Odoc_parameter
+open Odoc_value
+open Odoc_type
+open Odoc_extension
+open Odoc_exception
+open Odoc_class
+open Odoc_module
+open Odoc_types
+
+(** This variable contains the regular expression representing a blank.*)
+let blank = "[ \010\013\009\012']"
+
+(** This variable contains the regular expression representing a blank but not a '\n'.*)
+let simple_blank = "[ \013\009\012]"
+
+(** This module is used to search for structure items by name in a Typedtree.structure.
+ One function creates two hash tables, which can then be used to search for elements.
+ Class elements do not use tables.
+*)
+module Typedtree_search =
+ struct
+ type ele =
+ | M of string
+ | MT of string
+ | T of string
+ | C of string
+ | CT of string
+ | X of string
+ | E of string
+ | P of string
+ | IM of string
+
+ type tab = (ele, Typedtree.structure_item_desc) Hashtbl.t
+ type tab_values = (Odoc_module.Name.t, Typedtree.pattern * Typedtree.expression) Hashtbl.t
+
+ let iter_val_pattern = function
+ | Typedtree.Tpat_any -> None
+ | Typedtree.Tpat_var (name, _) -> Some (Name.from_ident name)
+ | Typedtree.Tpat_tuple _ -> None (* A VOIR quand on traitera les tuples *)
+ | _ -> None
+
+ let add_to_hashes table table_values tt =
+ match tt with
+ | Typedtree.Tstr_module mb ->
+ Hashtbl.add table (M (Name.from_ident mb.mb_id)) tt
+ | Typedtree.Tstr_recmodule mods ->
+ List.iter
+ (fun mb ->
+ Hashtbl.add table (M (Name.from_ident mb.mb_id))
+ (Typedtree.Tstr_module mb)
+ )
+ mods
+ | Typedtree.Tstr_modtype mtd ->
+ Hashtbl.add table (MT (Name.from_ident mtd.mtd_id)) tt
+ | Typedtree.Tstr_typext te -> begin
+ match te.tyext_constructors with
+ [] -> assert false
+ | ext :: _ -> Hashtbl.add table (X (Name.from_ident ext.ext_id)) tt
+ end
+ | Typedtree.Tstr_exception ext ->
+ Hashtbl.add table (E (Name.from_ident ext.ext_id)) tt
+ | Typedtree.Tstr_type (rf, ident_type_decl_list) ->
+ List.iter
+ (fun td ->
+ Hashtbl.add table (T (Name.from_ident td.typ_id))
+ (Typedtree.Tstr_type (rf, [td])))
+ ident_type_decl_list
+ | Typedtree.Tstr_class info_list ->
+ List.iter
+ (fun (ci, s) ->
+ Hashtbl.add table (C (Name.from_ident ci.ci_id_class))
+ (Typedtree.Tstr_class [ci, s]))
+ info_list
+ | Typedtree.Tstr_class_type info_list ->
+ List.iter
+ (fun ((id,id_loc,_) as ci) ->
+ Hashtbl.add table
+ (CT (Name.from_ident id))
+ (Typedtree.Tstr_class_type [ci]))
+ info_list
+ | Typedtree.Tstr_value (_, pat_exp_list) ->
+ List.iter
+ (fun {vb_pat=pat; vb_expr=exp} ->
+ match iter_val_pattern pat.Typedtree.pat_desc with
+ None -> ()
+ | Some n -> Hashtbl.add table_values n (pat,exp)
+ )
+ pat_exp_list
+ | Typedtree.Tstr_primitive vd ->
+ Hashtbl.add table (P (Name.from_ident vd.val_id)) tt
+ | Typedtree.Tstr_open _ -> ()
+ | Typedtree.Tstr_include _ -> ()
+ | Typedtree.Tstr_eval _ -> ()
+ | Typedtree.Tstr_attribute _ -> ()
+
+ let tables typedtree =
+ let t = Hashtbl.create 13 in
+ let t_values = Hashtbl.create 13 in
+ List.iter (fun str -> add_to_hashes t t_values str.str_desc) typedtree;
+ (t, t_values)
+
+ let search_module table name =
+ match Hashtbl.find table (M name) with
+ (Typedtree.Tstr_module mb) -> mb.mb_expr
+ | _ -> assert false
+
+ let search_module_type table name =
+ match Hashtbl.find table (MT name) with
+ | (Typedtree.Tstr_modtype mtd) -> mtd
+ | _ -> assert false
+
+ let search_extension table name =
+ match Hashtbl.find table (X name) with
+ | (Typedtree.Tstr_typext tyext) -> tyext
+ | _ -> assert false
+
+ let search_exception table name =
+ match Hashtbl.find table (E name) with
+ | (Typedtree.Tstr_exception ext) -> ext
+ | _ -> assert false
+
+ let search_type_declaration table name =
+ match Hashtbl.find table (T name) with
+ | (Typedtree.Tstr_type (_, [td])) -> td
+ | _ -> assert false
+
+ let search_class_exp table name =
+ match Hashtbl.find table (C name) with
+ | (Typedtree.Tstr_class [(ci, _ )]) ->
+ let ce = ci.ci_expr in
+ (
+ try
+ let type_decl = search_type_declaration table name in
+ (ce, type_decl.typ_type.Types.type_params)
+ with
+ Not_found ->
+ (ce, [])
+ )
+ | _ -> assert false
+
+ let search_class_type_declaration table name =
+ match Hashtbl.find table (CT name) with
+ | (Typedtree.Tstr_class_type [(_,_,cltype_decl)]) -> cltype_decl
+ | _ -> assert false
+
+ let search_value table name = Hashtbl.find table name
+
+ let search_primitive table name =
+ match Hashtbl.find table (P name) with
+ Tstr_primitive vd -> vd.val_val.Types.val_type
+ | _ -> assert false
+
+ let get_nth_inherit_class_expr cls n =
+ let rec iter cpt = function
+ | [] ->
+ raise Not_found
+ | { cf_desc = Typedtree.Tcf_inherit (_, clexp, _, _, _) } :: q ->
+ if n = cpt then clexp else iter (cpt+1) q
+ | _ :: q ->
+ iter cpt q
+ in
+ iter 0 cls.Typedtree.cstr_fields
+
+ let search_attribute_type cls name =
+ let rec iter = function
+ | [] ->
+ raise Not_found
+ | { cf_desc = Typedtree.Tcf_val (_, _, ident, Tcfk_concrete (_, exp), _) } :: q
+ when Name.from_ident ident = name ->
+ exp.Typedtree.exp_type
+ | { cf_desc = Typedtree.Tcf_val (_, _, ident, Tcfk_virtual typ, _) } :: q
+ when Name.from_ident ident = name ->
+ typ.Typedtree.ctyp_type
+ | _ :: q ->
+ iter q
+ in
+ iter cls.Typedtree.cstr_fields
+
+ let class_sig_of_cltype_decl =
+ let rec iter = function
+ Types.Cty_constr (_, _, cty) -> iter cty
+ | Types.Cty_signature s -> s
+ | Types.Cty_arrow (_,_, cty) -> iter cty
+ in
+ fun ct_decl -> iter ct_decl.Types.clty_type
+
+ let search_method_expression cls name =
+ let rec iter = function
+ | [] ->
+ raise Not_found
+ | { cf_desc = Typedtree.Tcf_method (label, _, Tcfk_concrete (_, exp)) } :: q when label.txt = name ->
+ exp
+ | _ :: q ->
+ iter q
+ in
+ iter cls.Typedtree.cstr_fields
+ end
+
+module Analyser =
+ functor (My_ir : Odoc_sig.Info_retriever) ->
+
+ struct
+ module Sig = Odoc_sig.Analyser (My_ir)
+
+ (** This variable is used to load a file as a string and retrieve characters from it.*)
+ let file = Sig.file
+
+ (** The name of the analysed file. *)
+ let file_name = Sig.file_name
+
+ (** This function takes two indexes (start and end) and return the string
+ corresponding to the indexes in the file global variable. The function
+ prepare_file must have been called to fill the file global variable.*)
+ let get_string_of_file = Sig.get_string_of_file
+
+ (** This function loads the given file in the file global variable.
+ and sets file_name.*)
+ let prepare_file = Sig.prepare_file
+
+ (** The function used to get the comments in a class. *)
+ let get_comments_in_class = Sig.get_comments_in_class
+
+ (** The function used to get the comments in a module. *)
+ let get_comments_in_module = Sig.get_comments_in_module
+
+ (** This function takes a parameter pattern and builds the
+ corresponding [parameter] structure. The f_desc function
+ is used to retrieve a parameter description, if any, from
+ a parameter name.
+ *)
+ let tt_param_info_from_pattern env f_desc pat =
+ let rec iter_pattern pat =
+ match pat.pat_desc with
+ Typedtree.Tpat_var (ident, _) ->
+ let name = Name.from_ident ident in
+ Simple_name { sn_name = name ;
+ sn_text = f_desc name ;
+ sn_type = Odoc_env.subst_type env pat.pat_type
+ }
+
+ | Typedtree.Tpat_alias (pat, _, _) ->
+ iter_pattern pat
+
+ | Typedtree.Tpat_tuple patlist ->
+ Tuple
+ (List.map iter_pattern patlist,
+ Odoc_env.subst_type env pat.pat_type)
+
+ | Typedtree.Tpat_construct (_, cons_desc, _) when
+ (* we give a name to the parameter only if it unit *)
+ (match cons_desc.cstr_res.desc with
+ Tconstr (p, _, _) ->
+ Path.same p Predef.path_unit
+ | _ ->
+ false)
+ ->
+ (* a () argument, it never has description *)
+ Simple_name { sn_name = "()" ;
+ sn_text = None ;
+ sn_type = Odoc_env.subst_type env pat.pat_type
+ }
+
+ | _ ->
+ (* implicit pattern matching -> anonymous parameter *)
+ Simple_name { sn_name = "()" ;
+ sn_text = None ;
+ sn_type = Odoc_env.subst_type env pat.pat_type
+ }
+ in
+ iter_pattern pat
+
+ (** Analysis of the parameter of a function. Return a list of t_parameter created from
+ the (pattern, expression) structures encountered. *)
+ let rec tt_analyse_function_parameters env current_comment_opt pat_exp_list =
+ match pat_exp_list with
+ [] ->
+ (* This case means we have a 'function' without pattern, that's impossible *)
+ raise (Failure "tt_analyse_function_parameters: 'function' without pattern")
+
+ | {c_lhs=pattern_param} :: second_ele :: q ->
+ (* implicit pattern matching -> anonymous parameter and no more parameter *)
+ (* A VOIR : le label ? *)
+ let parameter = Odoc_parameter.Tuple ([], Odoc_env.subst_type env pattern_param.pat_type) in
+ [ parameter ]
+
+ | {c_lhs=pattern_param; c_rhs=func_body} :: [] ->
+ let parameter =
+ tt_param_info_from_pattern
+ env
+ (Odoc_parameter.desc_from_info_opt current_comment_opt)
+ pattern_param
+
+ in
+ (* For optional parameters with a default value, a special treatment is required *)
+ (* we look if the name of the parameter we just add is "*opt*", which means
+ that there is a let param_name = ... in ... just right now *)
+ let (p, next_exp) =
+ match parameter with
+ Simple_name { sn_name = "*opt*" } ->
+ (
+ (
+ match func_body.exp_desc with
+ Typedtree.Texp_let (_, {vb_pat={pat_desc = Typedtree.Tpat_var (id, _) };
+ vb_expr=exp} :: _, func_body2) ->
+ let name = Name.from_ident id in
+ let new_param = Simple_name
+ { sn_name = name ;
+ sn_text = Odoc_parameter.desc_from_info_opt current_comment_opt name ;
+ sn_type = Odoc_env.subst_type env exp.exp_type
+ }
+ in
+ (new_param, func_body2)
+ | _ ->
+ print_DEBUG3 "Pas le bon filtre pour le parametre optionnel avec valeur par defaut.";
+ (parameter, func_body)
+ )
+ )
+ | _ ->
+ (parameter, func_body)
+ in
+ (* continue if the body is still a function *)
+ match next_exp.exp_desc with
+ Texp_function (_, pat_exp_list, _) ->
+ p :: (tt_analyse_function_parameters env current_comment_opt pat_exp_list)
+ | _ ->
+ (* something else ; no more parameter *)
+ [ p ]
+
+ (** Analysis of a Tstr_value from the typedtree. Create and return a list of [t_value].
+ @raise Failure if an error occurs.*)
+ let tt_analyse_value env current_module_name comment_opt loc pat_exp rec_flag =
+ let (pat, exp) = pat_exp in
+ match (pat.pat_desc, exp.exp_desc) with
+ (Typedtree.Tpat_var (ident, _), Typedtree.Texp_function (_, pat_exp_list2, partial)) ->
+ (* a new function is defined *)
+ let name_pre = Name.from_ident ident in
+ let name = Name.parens_if_infix name_pre in
+ let complete_name = Name.concat current_module_name name in
+ let code =
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum
+ loc.Location.loc_end.Lexing.pos_cnum)
+ else
+ None
+ in
+ (* create the value *)
+ let new_value = {
+ val_name = complete_name ;
+ val_info = comment_opt ;
+ val_type = Odoc_env.subst_type env pat.Typedtree.pat_type ;
+ val_recursive = rec_flag = Asttypes.Recursive ;
+ val_parameters = tt_analyse_function_parameters env comment_opt pat_exp_list2 ;
+ val_code = code ;
+ val_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ }
+ in
+ [ new_value ]
+
+ | (Typedtree.Tpat_var (ident, _), _) ->
+ (* a new value is defined *)
+ let name_pre = Name.from_ident ident in
+ let name = Name.parens_if_infix name_pre in
+ let complete_name = Name.concat current_module_name name in
+ let code =
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum
+ loc.Location.loc_end.Lexing.pos_cnum)
+ else
+ None
+ in
+ let new_value = {
+ val_name = complete_name ;
+ val_info = comment_opt ;
+ val_type = Odoc_env.subst_type env pat.Typedtree.pat_type ;
+ val_recursive = rec_flag = Asttypes.Recursive ;
+ val_parameters = [] ;
+ val_code = code ;
+ val_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ }
+ in
+ [ new_value ]
+
+ | (Typedtree.Tpat_tuple lpat, _) ->
+ (* new identifiers are defined *)
+ (* A VOIR : by now we don't accept to have global variables defined in tuples *)
+ []
+
+ | _ ->
+ (* something else, we don't care ? A VOIR *)
+ []
+
+ (** This function takes a Typedtree.class_expr and returns a string which can stand for the class name.
+ The name can be "object ... end" if the class expression is not an ident or a class constraint or a class apply. *)
+ let rec tt_name_of_class_expr clexp =
+(*
+ (
+ match clexp.Typedtree.cl_desc with
+ Tclass_ident _ -> prerr_endline "Tclass_ident"
+ | Tclass_structure _ -> prerr_endline "Tclass_structure"
+ | Tclass_fun _ -> prerr_endline "Tclass_fun"
+ | Tclass_apply _ -> prerr_endline "Tclass_apply"
+ | Tclass_let _ -> prerr_endline "Tclass_let"
+ | Tclass_constraint _ -> prerr_endline "Tclass_constraint"
+ );
+*)
+ match clexp.Typedtree.cl_desc with
+ Typedtree.Tcl_ident (p, _, _) -> Name.from_path p
+ | Typedtree.Tcl_constraint (class_expr, _, _, _, _)
+ | Typedtree.Tcl_apply (class_expr, _) -> tt_name_of_class_expr class_expr
+(*
+ | Typedtree.Tclass_fun (_, _, class_expr, _) -> tt_name_of_class_expr class_expr
+ | Typedtree.Tclass_let (_,_,_, class_expr) -> tt_name_of_class_expr class_expr
+*)
+ | _ -> Odoc_messages.object_end
+
+ (** Analysis of a method expression to get the method parameters.
+ @param first indicates if we're analysing the method for
+ the first time ; in that case we must not keep the first parameter,
+ which is "self-*", the object itself.
+ *)
+ let rec tt_analyse_method_expression env current_method_name comment_opt ?(first=true) exp =
+ match exp.Typedtree.exp_desc with
+ Typedtree.Texp_function (_, pat_exp_list, _) ->
+ (
+ match pat_exp_list with
+ [] ->
+ (* it is not a function since there are no parameters *)
+ (* we can't get here normally *)
+ raise (Failure (Odoc_messages.bad_tree^" "^(Odoc_messages.method_without_param current_method_name)))
+ | l ->
+ match l with
+ [] ->
+ (* cas impossible, on l'a filtre avant *)
+ assert false
+ | {c_lhs=pattern_param} :: second_ele :: q ->
+ (* implicit pattern matching -> anonymous parameter *)
+ (* Note : We can't match this pattern if it is the first call to the function. *)
+ let new_param = Simple_name
+ { sn_name = "??" ; sn_text = None;
+ sn_type = Odoc_env.subst_type env pattern_param.Typedtree.pat_type }
+ in
+ [ new_param ]
+
+ | {c_lhs=pattern_param; c_rhs=body} :: [] ->
+ (* if this is the first call to the function, this is the first parameter and we skip it *)
+ if not first then
+ (
+ let parameter =
+ tt_param_info_from_pattern
+ env
+ (Odoc_parameter.desc_from_info_opt comment_opt)
+ pattern_param
+ in
+ (* For optional parameters with a default value, a special treatment is required. *)
+ (* We look if the name of the parameter we just add is "*opt*", which means
+ that there is a let param_name = ... in ... just right now. *)
+ let (current_param, next_exp) =
+ match parameter with
+ Simple_name { sn_name = "*opt*"} ->
+ (
+ (
+ match body.exp_desc with
+ Typedtree.Texp_let (_, {vb_pat={pat_desc = Typedtree.Tpat_var (id, _) };
+ vb_expr=exp} :: _, body2) ->
+ let name = Name.from_ident id in
+ let new_param = Simple_name
+ { sn_name = name ;
+ sn_text = Odoc_parameter.desc_from_info_opt comment_opt name ;
+ sn_type = Odoc_env.subst_type env exp.Typedtree.exp_type ;
+ }
+ in
+ (new_param, body2)
+ | _ ->
+ print_DEBUG3 "Pas le bon filtre pour le parametre optionnel avec valeur par defaut.";
+ (parameter, body)
+ )
+ )
+ | _ ->
+ (* no *opt* parameter, we add the parameter then continue *)
+ (parameter, body)
+ in
+ current_param :: (tt_analyse_method_expression env current_method_name comment_opt ~first: false next_exp)
+ )
+ else
+ tt_analyse_method_expression env current_method_name comment_opt ~first: false body
+ )
+ | _ ->
+ (* no more parameter *)
+ []
+
+ (** Analysis of a [Parsetree.class_struture] and a [Typedtree.class_structure] to get a couple
+ (inherited classes, class elements). *)
+ let analyse_class_structure env current_class_name tt_class_sig last_pos pos_limit p_cls tt_cls table =
+ let rec iter acc_inher acc_fields last_pos = function
+ | [] ->
+ let s = get_string_of_file last_pos pos_limit in
+ let (_, ele_coms) = My_ir.all_special !file_name s in
+ let ele_comments =
+ List.fold_left
+ (fun acc -> fun sc ->
+ match sc.Odoc_types.i_desc with
+ None ->
+ acc
+ | Some t ->
+ acc @ [Class_comment t])
+ []
+ ele_coms
+ in
+ (acc_inher, acc_fields @ ele_comments)
+ | item :: q ->
+ let loc = item.Parsetree.pcf_loc in
+ match item.Parsetree.pcf_desc with
+ | (Parsetree.Pcf_inherit (_, p_clexp, _)) ->
+ let tt_clexp =
+ let n = List.length acc_inher in
+ try Typedtree_search.get_nth_inherit_class_expr tt_cls n
+ with Not_found ->
+ raise (Failure (
+ Odoc_messages.inherit_classexp_not_found_in_typedtree n))
+ in
+ let (info_opt, ele_comments) =
+ get_comments_in_class last_pos
+ p_clexp.Parsetree.pcl_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let text_opt =
+ match info_opt with None -> None
+ | Some i -> i.Odoc_types.i_desc in
+ let name = tt_name_of_class_expr tt_clexp in
+ let inher =
+ {
+ ic_name = Odoc_env.full_class_or_class_type_name env name ;
+ ic_class = None ;
+ ic_text = text_opt ;
+ }
+ in
+ iter (acc_inher @ [ inher ]) (acc_fields @ ele_comments)
+ p_clexp.Parsetree.pcl_loc.Location.loc_end.Lexing.pos_cnum
+ q
+
+ | Parsetree.Pcf_val ({ txt = label }, mutable_flag, k) ->
+ let virt = match k with Parsetree.Cfk_virtual _ -> true | Parsetree.Cfk_concrete _ -> false in
+ let complete_name = Name.concat current_class_name label in
+ let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let type_exp =
+ try Typedtree_search.search_attribute_type tt_cls label
+ with Not_found ->
+ raise (Failure (Odoc_messages.attribute_not_found_in_typedtree complete_name))
+ in
+ let code =
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum
+ loc.Location.loc_end.Lexing.pos_cnum)
+ else
+ None
+ in
+ let att =
+ {
+ att_value = { val_name = complete_name ;
+ val_info = info_opt ;
+ val_type = Odoc_env.subst_type env type_exp ;
+ val_recursive = false ;
+ val_parameters = [] ;
+ val_code = code ;
+ val_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ } ;
+ att_mutable = mutable_flag = Asttypes.Mutable ;
+ att_virtual = virt ;
+ }
+ in
+ iter acc_inher (acc_fields @ ele_comments @ [ Class_attribute att ]) loc.Location.loc_end.Lexing.pos_cnum q
+
+ | (Parsetree.Pcf_method ({ txt = label }, private_flag, Parsetree.Cfk_virtual _)) ->
+ let complete_name = Name.concat current_class_name label in
+ let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let met_type =
+ try Odoc_sig.Signature_search.search_method_type label tt_class_sig
+ with Not_found -> raise (Failure (Odoc_messages.method_type_not_found current_class_name label))
+ in
+ let real_type =
+ match met_type.Types.desc with
+ Tarrow (_, _, t, _) ->
+ t
+ | _ ->
+ (* ?!? : not an arrow type ! return the original type *)
+ met_type
+ in
+ let code =
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum
+ loc.Location.loc_end.Lexing.pos_cnum)
+ else
+ None
+ in
+ let met =
+ {
+ met_value = {
+ val_name = complete_name ;
+ val_info = info_opt ;
+ val_type = Odoc_env.subst_type env real_type ;
+ val_recursive = false ;
+ val_parameters = [] ;
+ val_code = code ;
+ val_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ } ;
+ met_private = private_flag = Asttypes.Private ;
+ met_virtual = true ;
+ }
+ in
+ (* update the parameter description *)
+ Odoc_value.update_value_parameters_text met.met_value;
+
+ iter acc_inher (acc_fields @ ele_comments @ [ Class_method met ]) loc.Location.loc_end.Lexing.pos_cnum q
+
+ | (Parsetree.Pcf_method ({ txt = label }, private_flag, Parsetree.Cfk_concrete _)) ->
+ let complete_name = Name.concat current_class_name label in
+ let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let exp =
+ try Typedtree_search.search_method_expression tt_cls label
+ with Not_found -> raise (Failure (Odoc_messages.method_not_found_in_typedtree complete_name))
+ in
+ let real_type =
+ match exp.exp_type.desc with
+ Tarrow (_, _, t,_) ->
+ t
+ | _ ->
+ (* ?!? : not an arrow type ! return the original type *)
+ exp.Typedtree.exp_type
+ in
+ let code =
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum
+ loc.Location.loc_end.Lexing.pos_cnum)
+ else
+ None
+ in
+ let met =
+ {
+ met_value = { val_name = complete_name ;
+ val_info = info_opt ;
+ val_type = Odoc_env.subst_type env real_type ;
+ val_recursive = false ;
+ val_parameters = tt_analyse_method_expression env complete_name info_opt exp ;
+ val_code = code ;
+ val_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ } ;
+ met_private = private_flag = Asttypes.Private ;
+ met_virtual = false ;
+ }
+ in
+ (* update the parameter description *)
+ Odoc_value.update_value_parameters_text met.met_value;
+
+ iter acc_inher (acc_fields @ ele_comments @ [ Class_method met ]) loc.Location.loc_end.Lexing.pos_cnum q
+
+ | Parsetree.Pcf_constraint (_, _) ->
+ (* don't give a $*%@ ! *)
+ iter acc_inher acc_fields loc.Location.loc_end.Lexing.pos_cnum q
+
+ | (Parsetree.Pcf_initializer exp) ->
+ iter acc_inher acc_fields exp.Parsetree.pexp_loc.Location.loc_end.Lexing.pos_cnum q
+
+ | Parsetree.Pcf_attribute _ ->
+ iter acc_inher acc_fields loc.Location.loc_end.Lexing.pos_cnum q
+
+ | Parsetree.Pcf_extension _ -> assert false
+ in
+ iter [] [] last_pos (p_cls.Parsetree.pcstr_fields)
+
+ (** Analysis of a [Parsetree.class_expr] and a [Typedtree.class_expr] to get a a couple (class parameters, class kind). *)
+ let rec analyse_class_kind env current_class_name comment_opt last_pos p_class_expr tt_class_exp table =
+ match (p_class_expr.Parsetree.pcl_desc, tt_class_exp.Typedtree.cl_desc) with
+ (Parsetree.Pcl_constr (lid, _), tt_class_exp_desc ) ->
+ let name =
+ match tt_class_exp_desc with
+ Typedtree.Tcl_ident (p,_,_) -> Name.from_path p
+ | _ ->
+ (* we try to get the name from the environment. *)
+ (* A VOIR : dommage qu'on n'ait pas un Tclass_ident :-( meme quand on a class tutu = toto *)
+ Name.from_longident lid.txt
+ in
+ (* On n'a pas ici les parametres de type sous forme de Types.type_expr,
+ par contre on peut les trouver dans le class_type *)
+ let params =
+ match tt_class_exp.Typedtree.cl_type with
+ Types.Cty_constr (p2, type_exp_list, cltyp) ->
+ (* cltyp is the class type for [type_exp_list] p *)
+ type_exp_list
+ | _ ->
+ []
+ in
+ ([],
+ Class_constr
+ {
+ cco_name = Odoc_env.full_class_name env name ;
+ cco_class = None ;
+ cco_type_parameters = List.map (Odoc_env.subst_type env) params ;
+ } )
+
+ | (Parsetree.Pcl_structure p_class_structure, Typedtree.Tcl_structure tt_class_structure) ->
+ (* we need the class signature to get the type of methods in analyse_class_structure *)
+ let tt_class_sig =
+ match tt_class_exp.Typedtree.cl_type with
+ Types.Cty_signature class_sig -> class_sig
+ | _ -> raise (Failure "analyse_class_kind: no class signature for a class structure.")
+ in
+ let (inherited_classes, class_elements) = analyse_class_structure
+ env
+ current_class_name
+ tt_class_sig
+ last_pos
+ p_class_expr.Parsetree.pcl_loc.Location.loc_end.Lexing.pos_cnum
+ p_class_structure
+ tt_class_structure
+ table
+ in
+ ([],
+ Class_structure (inherited_classes, class_elements) )
+
+ | (Parsetree.Pcl_fun (label, expression_opt, pattern, p_class_expr2),
+ Typedtree.Tcl_fun (_, pat, ident_exp_list, tt_class_expr2, partial)) ->
+ (* we check that this is not an optional parameter with
+ a default value. In this case, we look for the good parameter pattern *)
+ let (parameter, next_tt_class_exp) =
+ match pat.Typedtree.pat_desc with
+ Typedtree.Tpat_var (ident, _) when Name.from_ident ident = "*opt*" ->
+ (
+ (* there must be a Tcl_let just after *)
+ match tt_class_expr2.Typedtree.cl_desc with
+ Typedtree.Tcl_let (_, {vb_pat={pat_desc = Typedtree.Tpat_var (id,_) };
+ vb_expr=exp} :: _, _, tt_class_expr3) ->
+ let name = Name.from_ident id in
+ let new_param = Simple_name
+ { sn_name = name ;
+ sn_text = Odoc_parameter.desc_from_info_opt comment_opt name ;
+ sn_type = Odoc_env.subst_type env exp.exp_type
+ }
+ in
+ (new_param, tt_class_expr3)
+ | _ ->
+ (* strange case *)
+ (* we create the parameter and add it to the class *)
+ raise (Failure "analyse_class_kind: strange case")
+ )
+ | _ ->
+ (* no optional parameter with default value, we create the parameter *)
+ let new_param =
+ tt_param_info_from_pattern
+ env
+ (Odoc_parameter.desc_from_info_opt comment_opt)
+ pat
+ in
+ (new_param, tt_class_expr2)
+ in
+ let (params, k) = analyse_class_kind
+ env current_class_name comment_opt last_pos p_class_expr2
+ next_tt_class_exp table
+ in
+ (parameter :: params, k)
+
+ | (Parsetree.Pcl_apply (p_class_expr2, _), Tcl_apply (tt_class_expr2, exp_opt_optional_list)) ->
+ let applied_name =
+ (* we want an ident, or else the class applied will appear in the form object ... end,
+ because if the class applied has no name, the code is kinda ugly, isn't it ? *)
+ match tt_class_expr2.Typedtree.cl_desc with
+ Typedtree.Tcl_ident (p,_,_) -> Name.from_path p (* A VOIR : obtenir le nom complet *)
+ | _ ->
+ (* A VOIR : dommage qu'on n'ait pas un Tclass_ident :-( meme quand on a class tutu = toto *)
+ match p_class_expr2.Parsetree.pcl_desc with
+ Parsetree.Pcl_constr (lid, _) ->
+ (* we try to get the name from the environment. *)
+ Name.from_longident lid.txt
+ | _ ->
+ Odoc_messages.object_end
+ in
+ let param_exps = List.fold_left
+ (fun acc -> fun (_, exp_opt, _) ->
+ match exp_opt with
+ None -> acc
+ | Some e -> acc @ [e])
+ []
+ exp_opt_optional_list
+ in
+ let param_types = List.map (fun e -> e.Typedtree.exp_type) param_exps in
+ let params_code =
+ List.map
+ (fun e -> get_string_of_file
+ e.exp_loc.Location.loc_start.Lexing.pos_cnum
+ e.exp_loc.Location.loc_end.Lexing.pos_cnum)
+ param_exps
+ in
+ ([],
+ Class_apply
+ { capp_name = Odoc_env.full_class_name env applied_name ;
+ capp_class = None ;
+ capp_params = param_types ;
+ capp_params_code = params_code ;
+ } )
+
+ | (Parsetree.Pcl_let (_, _, p_class_expr2), Typedtree.Tcl_let (_, _, _, tt_class_expr2)) ->
+ (* we don't care about these lets *)
+ analyse_class_kind
+ env current_class_name comment_opt last_pos p_class_expr2
+ tt_class_expr2 table
+
+ | (Parsetree.Pcl_constraint (p_class_expr2, p_class_type2),
+ Typedtree.Tcl_constraint (tt_class_expr2, _, _, _, _)) ->
+ let (l, class_kind) = analyse_class_kind
+ env current_class_name comment_opt last_pos p_class_expr2
+ tt_class_expr2 table
+ in
+ (* A VOIR : analyse du class type ? on n'a pas toutes les infos. cf. Odoc_sig.analyse_class_type_kind *)
+ let class_type_kind =
+ (*Sig.analyse_class_type_kind
+ env
+ ""
+ p_class_type2.Parsetree.pcty_loc.Location.loc_start.Lexing.pos_cnum
+ p_class_type2
+ tt_class_expr2.Typedtree.cl_type
+ *)
+ Class_type { cta_name = Odoc_messages.object_end ;
+ cta_class = None ; cta_type_parameters = [] }
+ in
+ (l, Class_constraint (class_kind, class_type_kind))
+
+ | _ ->
+ raise (Failure "analyse_class_kind: Parsetree and typedtree don't match.")
+
+ (** Analysis of a [Parsetree.class_declaration] and a [Typedtree.class_expr] to return a [t_class].*)
+ let analyse_class env current_module_name comment_opt p_class_decl tt_type_params tt_class_exp table =
+ let name = p_class_decl.Parsetree.pci_name in
+ let complete_name = Name.concat current_module_name name.txt in
+ let loc = p_class_decl.Parsetree.pci_expr.Parsetree.pcl_loc in
+ let pos_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let type_parameters = tt_type_params in
+ let virt = p_class_decl.Parsetree.pci_virt = Asttypes.Virtual in
+ let cltype = Odoc_env.subst_class_type env tt_class_exp.Typedtree.cl_type in
+ let (parameters, kind) = analyse_class_kind
+ env
+ complete_name
+ comment_opt
+ pos_start
+ p_class_decl.Parsetree.pci_expr
+ tt_class_exp
+ table
+ in
+ let cl =
+ {
+ cl_name = complete_name ;
+ cl_info = comment_opt ;
+ cl_type = cltype ;
+ cl_virtual = virt ;
+ cl_type_parameters = type_parameters ;
+ cl_kind = kind ;
+ cl_parameters = parameters ;
+ cl_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ }
+ in
+ cl
+
+ (** Get a name from a module expression, or "struct ... end" if the module expression
+ is not an ident of a constraint on an ident. *)
+ let rec tt_name_from_module_expr mod_expr =
+ match mod_expr.Typedtree.mod_desc with
+ Typedtree.Tmod_ident (p,_) -> Name.from_path p
+ | Typedtree.Tmod_constraint (m_exp, _, _, _) -> tt_name_from_module_expr m_exp
+ | Typedtree.Tmod_structure _
+ | Typedtree.Tmod_functor _
+ | Typedtree.Tmod_apply _
+ | Typedtree.Tmod_unpack _ ->
+ Odoc_messages.struct_end
+
+ (** Get the list of included modules in a module structure of a typed tree. *)
+ let tt_get_included_module_list tt_structure =
+ let f acc item =
+ match item.str_desc with
+ Typedtree.Tstr_include incl ->
+ acc @ [
+ { (* A VOIR : chercher dans les modules et les module types, avec quel env ? *)
+ im_name = tt_name_from_module_expr incl.incl_mod ;
+ im_module = None ;
+ im_info = None ;
+ }
+ ]
+ | _ ->
+ acc
+ in
+ List.fold_left f [] tt_structure.str_items
+
+ (** This function takes a [module element list] of a module and replaces the "dummy" included modules with
+ the ones found in typed tree structure of the module. *)
+ let replace_dummy_included_modules module_elements included_modules =
+ let rec f = function
+ | ([], _) ->
+ []
+ | ((Element_included_module im) :: q, (im_repl :: im_q)) ->
+ (Element_included_module { im_repl with im_info = im.im_info })
+ :: (f (q, im_q))
+ | ((Element_included_module im) :: q, []) ->
+ (Element_included_module im) :: q
+ | (ele :: q, l) ->
+ ele :: (f (q, l))
+ in
+ f (module_elements, included_modules)
+
+ (** This function removes the elements of the module which does not
+ belong to the given module type, if the module type is expanded
+ and the module has a "structure" kind. *)
+ let rec filter_module_with_module_type_constraint m mt =
+ match m.m_kind, mt with
+ Module_struct l, Types.Mty_signature lsig ->
+ m.m_kind <- Module_struct (filter_module_elements_with_module_type_constraint l lsig);
+ m.m_type <- mt;
+ | _ -> ()
+
+ (** This function removes the elements of the module type which does not
+ belong to the given module type, if the module type is expanded
+ and the module type has a "structure" kind. *)
+ and filter_module_type_with_module_type_constraint mtyp mt =
+ match mtyp.mt_kind, mt with
+ Some Module_type_struct l, Types.Mty_signature lsig ->
+ mtyp.mt_kind <- Some (Module_type_struct (filter_module_elements_with_module_type_constraint l lsig));
+ mtyp.mt_type <- Some mt;
+ | _ -> ()
+
+ and filter_module_elements_with_module_type_constraint l lsig =
+ let pred ele =
+ let f = match ele with
+ Element_module m ->
+ (function
+ Types.Sig_module (ident,md,_) ->
+ let n1 = Name.simple m.m_name
+ and n2 = Ident.name ident in
+ (
+ match n1 = n2 with
+ true -> filter_module_with_module_type_constraint m md.md_type; true
+ | false -> false
+ )
+ | _ -> false)
+ | Element_module_type mt ->
+ (function
+ Types.Sig_modtype (ident,{Types.mtd_type=Some t}) ->
+ let n1 = Name.simple mt.mt_name
+ and n2 = Ident.name ident in
+ (
+ match n1 = n2 with
+ true -> filter_module_type_with_module_type_constraint mt t; true
+ | false -> false
+ )
+ | _ -> false)
+ | Element_value v ->
+ (function
+ Types.Sig_value (ident,_) ->
+ let n1 = Name.simple v.val_name
+ and n2 = Ident.name ident in
+ n1 = n2
+ | _ -> false)
+ | Element_type t ->
+ (function
+ Types.Sig_type (ident,_,_) ->
+ (* A VOIR: il est possible que le detail du type soit cache *)
+ let n1 = Name.simple t.ty_name
+ and n2 = Ident.name ident in
+ n1 = n2
+ | _ -> false)
+ | Element_type_extension te ->
+ let l =
+ filter_extension_constructors_with_module_type_constraint
+ te.te_constructors lsig
+ in
+ te.te_constructors <- l;
+ if l <> [] then (fun _ -> true)
+ else (fun _ -> false)
+ | Element_exception e ->
+ (function
+ Types.Sig_typext (ident,_,_) ->
+ let n1 = Name.simple e.ex_name
+ and n2 = Ident.name ident in
+ n1 = n2
+ | _ -> false)
+ | Element_class c ->
+ (function
+ Types.Sig_class (ident,_,_) ->
+ let n1 = Name.simple c.cl_name
+ and n2 = Ident.name ident in
+ n1 = n2
+ | _ -> false)
+ | Element_class_type ct ->
+ (function
+ Types.Sig_class_type (ident,_,_) ->
+ let n1 = Name.simple ct.clt_name
+ and n2 = Ident.name ident in
+ n1 = n2
+ | _ -> false)
+ | Element_module_comment _ -> fun _ -> true
+ | Element_included_module _ -> fun _ -> true
+ in
+ List.exists f lsig
+ in
+ List.filter pred l
+
+ and filter_extension_constructors_with_module_type_constraint l lsig =
+ let pred xt =
+ List.exists
+ (function
+ Types.Sig_typext (ident, _, _) ->
+ let n1 = Name.simple xt.xt_name
+ and n2 = Ident.name ident in
+ n1 = n2
+ | _ -> false)
+ lsig
+ in
+ List.filter pred l
+
+ (** Analysis of a parse tree structure with a typed tree, to return module elements.*)
+ let rec analyse_structure env current_module_name last_pos pos_limit parsetree typedtree =
+ print_DEBUG "Odoc_ast:analyse_struture";
+ let (table, table_values) = Typedtree_search.tables typedtree.str_items in
+ let rec iter env last_pos = function
+ [] ->
+ let s = get_string_of_file last_pos pos_limit in
+ let (_, ele_coms) = My_ir.all_special !file_name s in
+ let ele_comments =
+ List.fold_left
+ (fun acc -> fun sc ->
+ match sc.Odoc_types.i_desc with
+ None ->
+ acc
+ | Some t ->
+ acc @ [Element_module_comment t])
+ []
+ ele_coms
+ in
+ ele_comments
+ | item :: q ->
+ let (comment_opt, ele_comments) =
+ get_comments_in_module last_pos item.Parsetree.pstr_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let pos_limit2 =
+ match q with
+ [] -> pos_limit
+ | item2 :: _ -> item2.Parsetree.pstr_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let (maybe_more, new_env, elements) = analyse_structure_item
+ env
+ current_module_name
+ item.Parsetree.pstr_loc
+ pos_limit2
+ comment_opt
+ item.Parsetree.pstr_desc
+ typedtree
+ table
+ table_values
+ in
+ ele_comments @ elements @ (iter new_env (item.Parsetree.pstr_loc.Location.loc_end.Lexing.pos_cnum + maybe_more) q)
+ in
+ iter env last_pos parsetree
+
+ (** Analysis of a parse tree structure item to obtain a new environment and a list of elements.*)
+ and analyse_structure_item env current_module_name loc pos_limit comment_opt parsetree_item_desc typedtree
+ table table_values =
+ print_DEBUG "Odoc_ast:analyse_struture_item";
+ match parsetree_item_desc with
+ Parsetree.Pstr_eval _ ->
+ (* don't care *)
+ (0, env, [])
+ | Parsetree.Pstr_attribute _
+ | Parsetree.Pstr_extension _ ->
+ (0, env, [])
+ | Parsetree.Pstr_value (rec_flag, pat_exp_list) ->
+ (* of rec_flag * (pattern * expression) list *)
+ (* For each value, look for the value name, then look in the
+ typedtree for the corresponding information,
+ at last analyse this information to build the value *)
+ let rec iter_pat = function
+ | Parsetree.Ppat_any -> None
+ | Parsetree.Ppat_var name -> Some name
+ | Parsetree.Ppat_tuple _ -> None (* A VOIR quand on traitera les tuples *)
+ | Parsetree.Ppat_constraint (pat, _) -> iter_pat pat.Parsetree.ppat_desc
+ | _ -> None
+ in
+ let rec iter ?(first=false) last_pos acc_env acc p_e_list =
+ match p_e_list with
+ [] ->
+ (acc_env, acc)
+ | {Parsetree.pvb_pat=pat; pvb_expr=exp} :: q ->
+ let value_name_opt = iter_pat pat.Parsetree.ppat_desc in
+ let new_last_pos = exp.Parsetree.pexp_loc.Location.loc_end.Lexing.pos_cnum in
+ match value_name_opt with
+ None ->
+ iter new_last_pos acc_env acc q
+ | Some name ->
+ try
+ let pat_exp = Typedtree_search.search_value table_values name.txt in
+ let (info_opt, ele_comments) =
+ (* we already have the optional comment for the first value. *)
+ if first then
+ (comment_opt, [])
+ else
+ get_comments_in_module
+ last_pos
+ pat.Parsetree.ppat_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let l_values = tt_analyse_value
+ env
+ current_module_name
+ info_opt
+ loc
+ pat_exp
+ rec_flag
+ in
+ let new_env = List.fold_left
+ (fun e -> fun v ->
+ Odoc_env.add_value e v.val_name
+ )
+ acc_env
+ l_values
+ in
+ let l_ele = List.map (fun v -> Element_value v) l_values in
+ iter
+ new_last_pos
+ new_env
+ (acc @ ele_comments @ l_ele)
+ q
+ with
+ Not_found ->
+ iter new_last_pos acc_env acc q
+ in
+ let (new_env, l_ele) = iter ~first: true loc.Location.loc_start.Lexing.pos_cnum env [] pat_exp_list in
+ (0, new_env, l_ele)
+
+ | Parsetree.Pstr_primitive val_desc ->
+ let name_pre = val_desc.Parsetree.pval_name.txt in
+ (* of string * value_description *)
+ print_DEBUG ("Parsetree.Pstr_primitive ("^name_pre^", ["^(String.concat ", " val_desc.Parsetree.pval_prim)^"]");
+ let typ = Typedtree_search.search_primitive table name_pre in
+ let name = Name.parens_if_infix name_pre in
+ let complete_name = Name.concat current_module_name name in
+ let code =
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum
+ loc.Location.loc_end.Lexing.pos_cnum)
+ else
+ None
+ in
+ let new_value = {
+ val_name = complete_name ;
+ val_info = comment_opt ;
+ val_type = Odoc_env.subst_type env typ ;
+ val_recursive = false ;
+ val_parameters = [] ;
+ val_code = code ;
+ val_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ }
+ in
+ let new_env = Odoc_env.add_value env new_value.val_name in
+ (0, new_env, [Element_value new_value])
+
+ | Parsetree.Pstr_type (rf, name_typedecl_list) ->
+ (* of (string * type_declaration) list *)
+ let extended_env =
+ List.fold_left
+ (fun acc_env {Parsetree.ptype_name = { txt = name }} ->
+ let complete_name = Name.concat current_module_name name in
+ Odoc_env.add_type acc_env complete_name
+ )
+ env
+ name_typedecl_list
+ in
+ let env =
+ match rf with
+ | Recursive -> extended_env
+ | Nonrecursive -> env
+ in
+ let rec f ?(first=false) maybe_more_acc last_pos name_type_decl_list =
+ match name_type_decl_list with
+ [] -> (maybe_more_acc, [])
+ | type_decl :: q ->
+ let name = type_decl.Parsetree.ptype_name.txt in
+ let complete_name = Name.concat current_module_name name in
+ let loc = type_decl.Parsetree.ptype_loc in
+ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let pos_limit2 =
+ match q with
+ [] -> pos_limit
+ | td :: _ -> td.Parsetree.ptype_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let (maybe_more, name_comment_list) =
+ Sig.name_comment_from_type_decl loc_end pos_limit2 type_decl
+ in
+ let tt_type_decl =
+ try Typedtree_search.search_type_declaration table name
+ with Not_found -> raise (Failure (Odoc_messages.type_not_found_in_typedtree complete_name))
+ in
+ let tt_type_decl = tt_type_decl.Typedtree.typ_type in
+ let (com_opt, ele_comments) = (* the comment for the first type was already retrieved *)
+ if first then
+ (comment_opt , [])
+ else
+ get_comments_in_module last_pos loc_start
+ in
+ let kind = Sig.get_type_kind
+ env name_comment_list
+ tt_type_decl.Types.type_kind
+ in
+ let new_end = loc_end + maybe_more in
+ let t =
+ {
+ ty_name = complete_name ;
+ ty_info = com_opt ;
+ ty_parameters =
+ List.map2
+ (fun p v ->
+ let (co, cn) = Types.Variance.get_upper v in
+ (Odoc_env.subst_type env p, co, cn))
+ tt_type_decl.Types.type_params
+ tt_type_decl.Types.type_variance ;
+ ty_kind = kind ;
+ ty_private = tt_type_decl.Types.type_private;
+ ty_manifest =
+ (match tt_type_decl.Types.type_manifest with
+ None -> None
+ | Some t ->
+ Some (Sig.manifest_structure env name_comment_list t));
+ ty_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ ty_code =
+ (
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc_start new_end)
+ else
+ None
+ ) ;
+ }
+ in
+ let (maybe_more2, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file new_end pos_limit2)
+ in
+ t.ty_info <- Sig.merge_infos t.ty_info info_after_opt ;
+ let (maybe_more3, eles) = f (maybe_more + maybe_more2) (new_end + maybe_more2) q in
+ (maybe_more3, ele_comments @ ((Element_type t) :: eles))
+ in
+ let (maybe_more, eles) = f ~first: true 0 loc.Location.loc_start.Lexing.pos_cnum name_typedecl_list in
+ (maybe_more, extended_env, eles)
+
+ | Parsetree.Pstr_typext tyext ->
+ (* we get the extension declaration in the typed tree *)
+ let tt_tyext =
+ match tyext.Parsetree.ptyext_constructors with
+ [] -> assert false
+ | ext :: _ ->
+ try
+ Typedtree_search.search_extension table ext.Parsetree.pext_name.txt
+ with Not_found ->
+ raise (Failure
+ (Odoc_messages.extension_not_found_in_typedtree
+ (Name.concat current_module_name ext.Parsetree.pext_name.txt)))
+ in
+ let new_env =
+ List.fold_left
+ (fun acc_env -> fun {Parsetree.pext_name = { txt = name }} ->
+ let complete_name = Name.concat current_module_name name in
+ Odoc_env.add_extension acc_env complete_name
+ )
+ env
+ tyext.Parsetree.ptyext_constructors
+ in
+ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let new_te =
+ {
+ te_info = comment_opt;
+ te_type_name =
+ Odoc_env.full_type_name new_env (Name.from_path tt_tyext.tyext_path);
+ te_type_parameters =
+ List.map (fun (ctyp, _) -> Odoc_env.subst_type new_env ctyp.ctyp_type) tt_tyext.tyext_params;
+ te_private = tt_tyext.tyext_private;
+ te_constructors = [];
+ te_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ te_code =
+ (
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc_start loc_end)
+ else
+ None
+ ) ;
+ }
+ in
+ let rec analyse_extension_constructors maybe_more exts_acc tt_ext_list =
+ match tt_ext_list with
+ [] -> (maybe_more, List.rev exts_acc)
+ | tt_ext :: q ->
+ let complete_name = Name.concat current_module_name tt_ext.ext_name.txt in
+ let ext_loc_end = tt_ext.ext_loc.Location.loc_end.Lexing.pos_cnum in
+ let new_xt =
+ match tt_ext.ext_kind with
+ Text_decl(args, ret_type) ->
+ let xt_args =
+ match args with
+ | Cstr_tuple l -> Cstr_tuple (List.map (fun ctyp -> Odoc_env.subst_type new_env ctyp.ctyp_type) l)
+ | Cstr_record _ -> assert false
+ in
+ {
+ xt_name = complete_name;
+ xt_args;
+ xt_ret =
+ may_map (fun ctyp -> Odoc_env.subst_type new_env ctyp.ctyp_type) ret_type;
+ xt_type_extension = new_te;
+ xt_alias = None;
+ xt_loc = { loc_impl = Some tt_ext.ext_loc ; loc_inter = None } ;
+ xt_text = None;
+ }
+ | Text_rebind(path, _) ->
+ {
+ xt_name = complete_name;
+ xt_args = Cstr_tuple [];
+ xt_ret = None;
+ xt_type_extension = new_te;
+ xt_alias =
+ Some {
+ xa_name = Odoc_env.full_extension_constructor_name env (Name.from_path path);
+ xa_xt = None;
+ };
+ xt_loc = { loc_impl = Some tt_ext.ext_loc ; loc_inter = None } ;
+ xt_text = None;
+ }
+ in
+ let pos_limit2 =
+ match q with
+ [] -> pos_limit
+ | next :: _ ->
+ next.ext_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let s = get_string_of_file ext_loc_end pos_limit2 in
+ let (maybe_more, comment_opt) = My_ir.just_after_special !file_name s in
+ new_xt.xt_text <- comment_opt;
+ analyse_extension_constructors maybe_more (new_xt :: exts_acc) q
+ in
+ let (maybe_more, exts) = analyse_extension_constructors 0 [] tt_tyext.tyext_constructors in
+ new_te.te_constructors <- exts;
+ (maybe_more, new_env, [ Element_type_extension new_te ])
+
+ | Parsetree.Pstr_exception ext ->
+ let name = ext.Parsetree.pext_name in
+ (* a new exception is defined *)
+ let complete_name = Name.concat current_module_name name.txt in
+ (* we get the exception declaration in the typed tree *)
+ let tt_ext =
+ try Typedtree_search.search_exception table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.exception_not_found_in_typedtree complete_name))
+ in
+ let new_env = Odoc_env.add_extension env complete_name in
+ let new_ext =
+ match tt_ext.ext_kind with
+ Text_decl(tt_args, tt_ret_type) ->
+ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let ex_args =
+ match tt_args with
+ | Cstr_tuple l -> Cstr_tuple (List.map (fun c -> Odoc_env.subst_type env c.ctyp_type) l)
+ | Cstr_record l -> assert false (* TODO *)
+ in
+ {
+ ex_name = complete_name ;
+ ex_info = comment_opt ;
+ ex_args;
+ ex_ret =
+ Misc.may_map
+ (fun ctyp -> Odoc_env.subst_type new_env ctyp.ctyp_type)
+ tt_ret_type;
+ ex_alias = None ;
+ ex_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ ex_code =
+ (
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc_start loc_end)
+ else
+ None
+ ) ;
+ }
+ | Text_rebind(tt_path, _) ->
+ {
+ ex_name = complete_name ;
+ ex_info = comment_opt ;
+ ex_args = Cstr_tuple [] ;
+ ex_ret = None ;
+ ex_alias =
+ Some { ea_name =
+ Odoc_env.full_extension_constructor_name
+ env (Name.from_path tt_path) ;
+ ea_ex = None ; } ;
+ ex_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ ex_code = None ;
+ }
+ in
+ (0, new_env, [ Element_exception new_ext ])
+
+ | Parsetree.Pstr_module {Parsetree.pmb_name=name; pmb_expr=module_expr} ->
+ (
+ (* of string * module_expr *)
+ try
+ let tt_module_expr = Typedtree_search.search_module table name.txt in
+ let new_module_pre = analyse_module
+ env
+ current_module_name
+ name.txt
+ comment_opt
+ module_expr
+ tt_module_expr
+ in
+ let code =
+ if !Odoc_global.keep_code then
+ let loc = module_expr.Parsetree.pmod_loc in
+ let st = loc.Location.loc_start.Lexing.pos_cnum in
+ let en = loc.Location.loc_end.Lexing.pos_cnum in
+ Some (get_string_of_file st en)
+ else
+ None
+ in
+ let new_module =
+ { new_module_pre with m_code = code }
+ in
+ let new_env = Odoc_env.add_module env new_module.m_name in
+ let new_env2 =
+ match new_module.m_type with
+ (* A VOIR : cela peut-il etre Tmty_ident ? dans ce cas, on aurait pas la signature *)
+ Types.Mty_signature s ->
+ Odoc_env.add_signature new_env new_module.m_name
+ ~rel: (Name.simple new_module.m_name) s
+ | _ ->
+ new_env
+ in
+ (0, new_env2, [ Element_module new_module ])
+ with
+ Not_found ->
+ let complete_name = Name.concat current_module_name name.txt in
+ raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
+ )
+
+ | Parsetree.Pstr_recmodule mods ->
+ (* A VOIR ICI pb: pas de lien avec les module type
+ dans les contraintes sur les modules *)
+ let new_env =
+ List.fold_left
+ (fun acc_env {Parsetree.pmb_name=name;pmb_expr=mod_exp} ->
+ let complete_name = Name.concat current_module_name name.txt in
+ let e = Odoc_env.add_module acc_env complete_name in
+ let tt_mod_exp =
+ try Typedtree_search.search_module table name.txt
+ with Not_found -> raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
+ in
+ let new_module = analyse_module
+ e
+ current_module_name
+ name.txt
+ None
+ mod_exp
+ tt_mod_exp
+ in
+ match new_module.m_type with
+ Types.Mty_signature s ->
+ Odoc_env.add_signature e new_module.m_name
+ ~rel: (Name.simple new_module.m_name) s
+ | _ ->
+ e
+ )
+ env
+ mods
+ in
+ let rec f ?(first=false) last_pos name_mod_exp_list =
+ match name_mod_exp_list with
+ [] -> []
+ | {Parsetree.pmb_name=name;pmb_expr=mod_exp} :: q ->
+ let complete_name = Name.concat current_module_name name.txt in
+ let loc_start = mod_exp.Parsetree.pmod_loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = mod_exp.Parsetree.pmod_loc.Location.loc_end.Lexing.pos_cnum in
+ let tt_mod_exp =
+ try Typedtree_search.search_module table name.txt
+ with Not_found -> raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
+ in
+ let (com_opt, ele_comments) = (* the comment for the first type was already retrieved *)
+ if first then
+ (comment_opt, [])
+ else
+ get_comments_in_module last_pos loc_start
+ in
+ let new_module = analyse_module
+ new_env
+ current_module_name
+ name.txt
+ com_opt
+ mod_exp
+ tt_mod_exp
+ in
+ let eles = f loc_end q in
+ ele_comments @ ((Element_module new_module) :: eles)
+ in
+ let eles = f ~first: true loc.Location.loc_start.Lexing.pos_cnum mods in
+ (0, new_env, eles)
+
+ | Parsetree.Pstr_modtype {Parsetree.pmtd_name=name; pmtd_type=modtype} ->
+ let complete_name = Name.concat current_module_name name.txt in
+ let tt_module_type =
+ try Typedtree_search.search_module_type table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.module_type_not_found_in_typedtree complete_name))
+ in
+ let kind, sig_mtype =
+ match modtype, tt_module_type.mtd_type with
+ | Some modtype, Some mty_type ->
+ Some (Sig.analyse_module_type_kind env complete_name
+ modtype mty_type.mty_type),
+ Some mty_type.mty_type
+ | _ -> None, None
+ in
+ let mt =
+ {
+ mt_name = complete_name ;
+ mt_info = comment_opt ;
+ mt_type = sig_mtype ;
+ mt_is_interface = false ;
+ mt_file = !file_name ;
+ mt_kind = kind ;
+ mt_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ }
+ in
+ let new_env = Odoc_env.add_module_type env mt.mt_name in
+ let new_env2 =
+ match sig_mtype with
+ (* A VOIR : cela peut-il etre Tmty_ident ? dans ce cas, on n'aurait pas la signature *)
+ Some (Types.Mty_signature s) ->
+ Odoc_env.add_signature new_env mt.mt_name ~rel: (Name.simple mt.mt_name) s
+ | _ ->
+ new_env
+ in
+ (0, new_env2, [ Element_module_type mt ])
+
+ | Parsetree.Pstr_open _ ->
+ (* A VOIR : enrichir l'environnement quand open ? *)
+ let ele_comments = match comment_opt with
+ None -> []
+ | Some i ->
+ match i.i_desc with
+ None -> []
+ | Some t -> [Element_module_comment t]
+ in
+ (0, env, ele_comments)
+
+ | Parsetree.Pstr_class class_decl_list ->
+ (* we start by extending the environment *)
+ let new_env =
+ List.fold_left
+ (fun acc_env -> fun class_decl ->
+ let complete_name = Name.concat current_module_name class_decl.Parsetree.pci_name.txt in
+ Odoc_env.add_class acc_env complete_name
+ )
+ env
+ class_decl_list
+ in
+ let rec f ?(first=false) last_pos class_decl_list =
+ match class_decl_list with
+ [] ->
+ []
+ | class_decl :: q ->
+ let (tt_class_exp, tt_type_params) =
+ try Typedtree_search.search_class_exp table class_decl.Parsetree.pci_name.txt
+ with Not_found ->
+ let complete_name = Name.concat current_module_name class_decl.Parsetree.pci_name.txt in
+ raise (Failure (Odoc_messages.class_not_found_in_typedtree complete_name))
+ in
+ let (com_opt, ele_comments) =
+ if first then
+ (comment_opt, [])
+ else
+ get_comments_in_module last_pos class_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let last_pos2 = class_decl.Parsetree.pci_loc.Location.loc_end.Lexing.pos_cnum in
+ let new_class = analyse_class
+ new_env
+ current_module_name
+ com_opt
+ class_decl
+ tt_type_params
+ tt_class_exp
+ table
+ in
+ ele_comments @ ((Element_class new_class) :: (f last_pos2 q))
+ in
+ (0, new_env, f ~first: true loc.Location.loc_start.Lexing.pos_cnum class_decl_list)
+
+ | Parsetree.Pstr_class_type class_type_decl_list ->
+ (* we start by extending the environment *)
+ let new_env =
+ List.fold_left
+ (fun acc_env -> fun class_type_decl ->
+ let complete_name = Name.concat current_module_name class_type_decl.Parsetree.pci_name.txt in
+ Odoc_env.add_class_type acc_env complete_name
+ )
+ env
+ class_type_decl_list
+ in
+ let rec f ?(first=false) last_pos class_type_decl_list =
+ match class_type_decl_list with
+ [] ->
+ []
+ | class_type_decl :: q ->
+ let name = class_type_decl.Parsetree.pci_name in
+ let complete_name = Name.concat current_module_name name.txt in
+ let virt = class_type_decl.Parsetree.pci_virt = Asttypes.Virtual in
+ let tt_cltype_declaration =
+ try Typedtree_search.search_class_type_declaration table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.class_type_not_found_in_typedtree complete_name))
+ in
+ let tt_cltype_declaration = tt_cltype_declaration.ci_type_decl in
+ let type_params = tt_cltype_declaration.Types.clty_params in
+ let kind = Sig.analyse_class_type_kind
+ new_env
+ complete_name
+ class_type_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ class_type_decl.Parsetree.pci_expr
+ tt_cltype_declaration.Types.clty_type
+ in
+ let (com_opt, ele_comments) =
+ if first then
+ (comment_opt, [])
+ else
+ get_comments_in_module last_pos class_type_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let last_pos2 = class_type_decl.Parsetree.pci_loc.Location.loc_end.Lexing.pos_cnum in
+ let new_ele =
+ Element_class_type
+ {
+ clt_name = complete_name ;
+ clt_info = com_opt ;
+ clt_type = Odoc_env.subst_class_type env tt_cltype_declaration.Types.clty_type ;
+ clt_type_parameters = List.map (Odoc_env.subst_type new_env) type_params ;
+ clt_virtual = virt ;
+ clt_kind = kind ;
+ clt_loc = { loc_impl = Some loc ;
+ loc_inter = None } ;
+ }
+ in
+ ele_comments @ (new_ele :: (f last_pos2 q))
+ in
+ (0, new_env, f ~first: true loc.Location.loc_start.Lexing.pos_cnum class_type_decl_list)
+
+ | Parsetree.Pstr_include incl ->
+ (* we add a dummy included module which will be replaced by a correct
+ one at the end of the module analysis,
+ to use the Path.t of the included modules in the typdtree. *)
+ let im =
+ {
+ im_name = "dummy" ;
+ im_module = None ;
+ im_info = comment_opt ;
+ }
+ in
+ (0, env, [ Element_included_module im ]) (* A VOIR : etendre l'environnement ? avec quoi ? *)
+
+ (** Analysis of a [Parsetree.module_expr] and a name to return a [t_module].*)
+ and analyse_module env current_module_name module_name comment_opt p_module_expr tt_module_expr =
+ let complete_name = Name.concat current_module_name module_name in
+ let loc = p_module_expr.Parsetree.pmod_loc in
+ let pos_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let pos_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let modtype =
+ (* A VOIR : Odoc_env.subst_module_type env ? *)
+ tt_module_expr.Typedtree.mod_type
+ in
+ let m_code_intf =
+ match p_module_expr.Parsetree.pmod_desc with
+ Parsetree.Pmod_constraint (_, pmodule_type) ->
+ let loc_start = pmodule_type.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = pmodule_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
+ Some (get_string_of_file loc_start loc_end)
+ | _ ->
+ None
+ in
+ let m_base =
+ {
+ m_name = complete_name ;
+ m_type = modtype ;
+ m_info = comment_opt ;
+ m_is_interface = false ;
+ m_file = !file_name ;
+ m_kind = Module_struct [] ;
+ m_loc = { loc_impl = Some loc ; loc_inter = None } ;
+ m_top_deps = [] ;
+ m_code = None ; (* code is set by the caller, after the module is created *)
+ m_code_intf = m_code_intf ;
+ m_text_only = false ;
+ }
+ in
+ match (p_module_expr.Parsetree.pmod_desc, tt_module_expr.Typedtree.mod_desc) with
+ (Parsetree.Pmod_ident longident, Typedtree.Tmod_ident (path, _))
+ | (Parsetree.Pmod_ident longident,
+ Typedtree.Tmod_constraint
+ ({Typedtree.mod_desc = Typedtree.Tmod_ident (path, _)}, _, _, _))
+ ->
+ let alias_name = Odoc_env.full_module_name env (Name.from_path path) in
+ { m_base with m_kind = Module_alias { ma_name = alias_name ;
+ ma_module = None ; } }
+
+ | (Parsetree.Pmod_structure p_structure, Typedtree.Tmod_structure tt_structure) ->
+ let elements = analyse_structure env complete_name pos_start pos_end p_structure tt_structure in
+ (* we must complete the included modules *)
+ let included_modules_from_tt = tt_get_included_module_list tt_structure in
+ let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
+ { m_base with m_kind = Module_struct elements2 }
+
+ | (Parsetree.Pmod_functor (_, pmodule_type, p_module_expr2),
+ Typedtree.Tmod_functor (ident, _, mtyp, tt_module_expr2)) ->
+ let loc = match pmodule_type with None -> Location.none
+ | Some pmty -> pmty.Parsetree.pmty_loc in
+ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let mp_type_code = get_string_of_file loc_start loc_end in
+ print_DEBUG (Printf.sprintf "mp_type_code=%s" mp_type_code);
+ let mp_name = Name.from_ident ident in
+ let mp_kind =
+ match pmodule_type, mtyp with
+ Some pmty, Some mty ->
+ Sig.analyse_module_type_kind env current_module_name pmty
+ mty.mty_type
+ | _ -> Module_type_struct []
+ in
+ let param =
+ {
+ mp_name = mp_name ;
+ mp_type = Misc.may_map
+ (fun m -> Odoc_env.subst_module_type env m.mty_type) mtyp ;
+ mp_type_code = mp_type_code ;
+ mp_kind = mp_kind ;
+ }
+ in
+ let dummy_complete_name = (*Name.concat "__"*) param.mp_name in
+ (* TODO: A VOIR CE __ *)
+ let new_env = Odoc_env.add_module env dummy_complete_name in
+ let m_base2 = analyse_module
+ new_env
+ current_module_name
+ module_name
+ None
+ p_module_expr2
+ tt_module_expr2
+ in
+ let kind = m_base2.m_kind in
+ { m_base with m_kind = Module_functor (param, kind) }
+
+ | (Parsetree.Pmod_apply (p_module_expr1, p_module_expr2),
+ Typedtree.Tmod_apply (tt_module_expr1, tt_module_expr2, _))
+ | (Parsetree.Pmod_apply (p_module_expr1, p_module_expr2),
+ Typedtree.Tmod_constraint
+ ({ Typedtree.mod_desc = Typedtree.Tmod_apply (tt_module_expr1, tt_module_expr2, _)}, _,
+ _, _)
+ ) ->
+ let m1 = analyse_module
+ env
+ current_module_name
+ module_name
+ None
+ p_module_expr1
+ tt_module_expr1
+ in
+ let m2 = analyse_module
+ env
+ current_module_name
+ module_name
+ None
+ p_module_expr2
+ tt_module_expr2
+ in
+ { m_base with m_kind = Module_apply (m1.m_kind, m2.m_kind) }
+
+ | (Parsetree.Pmod_constraint (p_module_expr2, p_modtype),
+ Typedtree.Tmod_constraint (tt_module_expr2, tt_modtype, _, _)) ->
+ print_DEBUG ("Odoc_ast: case Parsetree.Pmod_constraint + Typedtree.Tmod_constraint "^module_name);
+ let m_base2 = analyse_module
+ env
+ current_module_name
+ module_name
+ None
+ p_module_expr2
+ tt_module_expr2
+ in
+ let mtkind = Sig.analyse_module_type_kind env
+ (Name.concat current_module_name "??")
+ p_modtype tt_modtype
+ in
+ let tt_modtype = Odoc_env.subst_module_type env tt_modtype in
+ if !Odoc_global.filter_with_module_constraints then
+ filter_module_with_module_type_constraint m_base2 tt_modtype;
+ {
+ m_base with
+ m_type = tt_modtype ;
+ m_kind = Module_constraint (m_base2.m_kind, mtkind) ;
+ }
+
+ | (Parsetree.Pmod_structure p_structure,
+ Typedtree.Tmod_constraint
+ ({ Typedtree.mod_desc = Typedtree.Tmod_structure tt_structure},
+ tt_modtype, _, _)
+ ) ->
+ (* needed for recursive modules *)
+
+ print_DEBUG ("Odoc_ast: case Parsetree.Pmod_structure + Typedtree.Tmod_constraint "^module_name);
+ let elements = analyse_structure env complete_name pos_start pos_end p_structure tt_structure in
+ (* we must complete the included modules *)
+ let included_modules_from_tt = tt_get_included_module_list tt_structure in
+ let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
+ { m_base with
+ m_type = Odoc_env.subst_module_type env tt_modtype ;
+ m_kind = Module_struct elements2 ;
+ }
+
+ | (Parsetree.Pmod_unpack p_exp,
+ Typedtree.Tmod_unpack (t_exp, tt_modtype)) ->
+ print_DEBUG ("Odoc_ast: case Parsetree.Pmod_unpack + Typedtree.Tmod_unpack "^module_name);
+ let code =
+ let loc = p_module_expr.Parsetree.pmod_loc in
+ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let exp_loc = p_exp.Parsetree.pexp_loc in
+ let exp_loc_end = exp_loc.Location.loc_end.Lexing.pos_cnum in
+ let s = get_string_of_file exp_loc_end loc_end in
+ Printf.sprintf "(val ...%s" s
+ in
+ (* let name = Odoc_env.full_module_type_name env (Name.from_path (fst pkg_type)) in *)
+ let name =
+ match tt_modtype with
+ | Mty_ident p ->
+ Odoc_env.full_module_type_name env (Name.from_path p)
+ | _ -> ""
+ in
+ let alias = { mta_name = name ; mta_module = None } in
+ { m_base with
+ m_type = Odoc_env.subst_module_type env tt_modtype ;
+ m_kind = Module_unpack (code, alias) ;
+ }
+
+ | (parsetree, typedtree) ->
+ (*DEBUG*)let s_parse =
+ (*DEBUG*) match parsetree with
+ (*DEBUG*) Parsetree.Pmod_ident _ -> "Pmod_ident"
+ (*DEBUG*) | Parsetree.Pmod_structure _ -> "Pmod_structure"
+ (*DEBUG*) | Parsetree.Pmod_functor _ -> "Pmod_functor"
+ (*DEBUG*) | Parsetree.Pmod_apply _ -> "Pmod_apply"
+ (*DEBUG*) | Parsetree.Pmod_constraint _ -> "Pmod_constraint"
+ (*DEBUG*) | Parsetree.Pmod_unpack _ -> "Pmod_unpack"
+ (*DEBUG*) | Parsetree.Pmod_extension _ -> "Pmod_extension"
+ (*DEBUG*)in
+ (*DEBUG*)let s_typed =
+ (*DEBUG*) match typedtree with
+ (*DEBUG*) Typedtree.Tmod_ident _ -> "Tmod_ident"
+ (*DEBUG*) | Typedtree.Tmod_structure _ -> "Tmod_structure"
+ (*DEBUG*) | Typedtree.Tmod_functor _ -> "Tmod_functor"
+ (*DEBUG*) | Typedtree.Tmod_apply _ -> "Tmod_apply"
+ (*DEBUG*) | Typedtree.Tmod_constraint _ -> "Tmod_constraint"
+ (*DEBUG*) | Typedtree.Tmod_unpack _ -> "Tmod_unpack"
+ (*DEBUG*)in
+ (*DEBUG*)let code = get_string_of_file pos_start pos_end in
+ print_DEBUG (Printf.sprintf "code=%s\ns_parse=%s\ns_typed=%s\n" code s_parse s_typed);
+
+ raise (Failure "analyse_module: parsetree and typedtree don't match.")
+
+ let analyse_typed_tree source_file input_file
+ (parsetree : Parsetree.structure) (typedtree : typedtree) =
+ let (tree_structure, _) = typedtree in
+ let complete_source_file =
+ try
+ let curdir = Sys.getcwd () in
+ let (dirname, basename) = (Filename.dirname source_file, Filename.basename source_file) in
+ Sys.chdir dirname ;
+ let complete = Filename.concat (Sys.getcwd ()) basename in
+ Sys.chdir curdir ;
+ complete
+ with
+ Sys_error s ->
+ prerr_endline s ;
+ incr Odoc_global.errors ;
+ source_file
+ in
+ prepare_file complete_source_file input_file;
+ (* We create the t_module for this file. *)
+ let mod_name = String.capitalize_ascii (Filename.basename (Filename.chop_extension source_file)) in
+ let (len,info_opt) = My_ir.first_special !file_name !file in
+
+ (* we must complete the included modules *)
+ let elements = analyse_structure Odoc_env.empty mod_name len (String.length !file) parsetree tree_structure in
+ let included_modules_from_tt = tt_get_included_module_list tree_structure in
+ let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
+ let kind = Module_struct elements2 in
+ {
+ m_name = mod_name ;
+ m_type = Types.Mty_signature [] ;
+ m_info = info_opt ;
+ m_is_interface = false ;
+ m_file = !file_name ;
+ m_kind = kind ;
+ m_loc = { loc_impl = Some (Location.in_file !file_name) ; loc_inter = None } ;
+ m_top_deps = [] ;
+ m_code = (if !Odoc_global.keep_code then Some !file else None) ;
+ m_code_intf = None ;
+ m_text_only = false ;
+ }
+ end
diff --git a/ocamldoc/odoc_ast.mli b/ocamldoc/odoc_ast.mli
new file mode 100644
index 0000000000..c3db304ea7
--- /dev/null
+++ b/ocamldoc/odoc_ast.mli
@@ -0,0 +1,98 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The module for analysing the typed abstract syntax tree and source code and creating modules, classes, ..., elements.*)
+
+type typedtree = Typedtree.structure * Typedtree.module_coercion
+
+(** This module is used to search for structure items by name in a [Typedtree.structure]. *)
+module Typedtree_search :
+ sig
+ type ele
+
+ type tab = (ele, Typedtree.structure_item_desc) Hashtbl.t
+ type tab_values = (Odoc_name.t, Typedtree.pattern * Typedtree.expression) Hashtbl.t
+
+ (** Create hash tables used to search by some of the functions below. *)
+ val tables : Typedtree.structure_item list -> tab * tab_values
+
+ (** This function returns the [Typedtree.module_expr] associated to the given module name,
+ in the given table.
+ @raise Not_found if the module was not found.*)
+ val search_module : tab -> string -> Typedtree.module_expr
+
+ (** This function returns the [Typedtree.module_type] associated to the given module type name,
+ in the given table.
+ @raise Not_found if the module type was not found.*)
+ val search_module_type : tab -> string -> Typedtree.module_type_declaration
+
+ (** This function returns the [Typedtree.type_extension] associated to the given extension name,
+ in the given table.
+ @raise Not_found if the extension was not found.*)
+ val search_extension : tab -> string -> Typedtree.type_extension
+
+ (** This function returns the [Typedtree.type_declaration] associated to the given type name,
+ in the given table.
+ @raise Not_found if the type was not found. *)
+ val search_type_declaration : tab -> string -> Typedtree.type_declaration
+
+ (** This function returns the [Typedtree.class_expr] and type parameters
+ associated to the given class name, in the given table.
+ @raise Not_found if the class was not found. *)
+ val search_class_exp : tab -> string -> (Typedtree.class_expr * (Types.type_expr list))
+
+ (** This function returns the [Typedtree.class_type_declaration] associated to the given class type name,
+ in the given table.
+ @raise Not_found if the class type was not found. *)
+ val search_class_type_declaration : tab -> string -> Typedtree.class_type_declaration
+
+ (** This function returns the couple (pat, exp) for the given value name, in the
+ given table of values.
+ @raise Not found if no value matches the name.*)
+ val search_value : tab_values -> string -> Typedtree.pattern * Typedtree.expression
+
+ (** This function returns the [type_expr] for the given primitive name, in the
+ given table.
+ @raise Not found if no value matches the name.*)
+ val search_primitive : tab -> string -> Types.type_expr
+
+ (** This function returns the [Typedtree.class_expr] associated to
+ the n'th inherit in the given class structure of typed tree.
+ @raise Not_found if the class expression could not be found.*)
+ val get_nth_inherit_class_expr :
+ Typedtree.class_structure -> int -> Typedtree.class_expr
+
+ (** This function returns the [Types.type_expr] of the attribute
+ whose name is given, in a given class structure.
+ @raise Not_found if the class attribute could not be found.*)
+ val search_attribute_type :
+ Typedtree.class_structure -> string -> Types.type_expr
+
+ (** This function returns the [Types.expression] of the method whose name is given, in a given class structure.
+ @raise Not_found if the class method could not be found.*)
+ val search_method_expression :
+ Typedtree.class_structure -> string -> Typedtree.expression
+ end
+
+(** The module which performs the analysis of a typed tree.
+ The module uses the module {!Odoc_sig.Analyser}.
+ @param My_ir The module used to retrieve comments and special comments.*)
+module Analyser :
+ functor (My_ir : Odoc_sig.Info_retriever) ->
+ sig
+ (** This function takes a file name, a file containg the code and
+ the typed tree obtained from the compiler.
+ It goes through the tree, creating values for encountered
+ functions, modules, ..., and looking in the source file for comments.*)
+ val analyse_typed_tree :
+ string -> string -> Parsetree.structure -> typedtree -> Odoc_module.t_module
+ end
diff --git a/ocamldoc/odoc_class.ml b/ocamldoc/odoc_class.ml
new file mode 100644
index 0000000000..ce9902eb6e
--- /dev/null
+++ b/ocamldoc/odoc_class.ml
@@ -0,0 +1,249 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation and manipulation of classes and class types.*)
+
+module Name = Odoc_name
+
+(** To keep the order of elements in a class *)
+type class_element =
+ Class_attribute of Odoc_value.t_attribute
+ | Class_method of Odoc_value.t_method
+ | Class_comment of Odoc_types.text
+
+(** Used when we can reference t_class or t_class_type. *)
+type cct =
+ Cl of t_class
+ | Cltype of t_class_type * Types.type_expr list (** class type and type parameters *)
+
+and inherited_class = {
+ ic_name : Name.t ; (** Complete name of the inherited class *)
+ mutable ic_class : cct option ; (** The associated t_class or t_class_type *)
+ ic_text : Odoc_types.text option ; (** The inheritance comment, if any *)
+ }
+
+and class_apply = {
+ capp_name : Name.t ; (** The complete name of the applied class *)
+ mutable capp_class : t_class option; (** The associated t_class if we found it *)
+ capp_params : Types.type_expr list; (** The type of expressions the class is applied to *)
+ capp_params_code : string list ; (** The code of these expressions *)
+ }
+
+and class_constr = {
+ cco_name : Name.t ; (** The complete name of the applied class *)
+ mutable cco_class : cct option; (** The associated class ot class type if we found it *)
+ cco_type_parameters : Types.type_expr list; (** The type parameters of the class, if needed *)
+ }
+
+
+and class_kind =
+ Class_structure of inherited_class list * class_element list
+ (** an explicit class structure, used in implementation and interface *)
+ | Class_apply of class_apply (** application/alias of a class, used in implementation only *)
+ | Class_constr of class_constr (** a class used to give the type of the defined class,
+ instead of a structure, used in interface only.
+ For example, it will be used with the name "M1.M2....tutu"
+ when the class to is defined like this :
+ class toto : int -> tutu *)
+ | Class_constraint of class_kind * class_type_kind
+ (** A class definition with a constraint. *)
+
+(** Representation of a class. *)
+and t_class = {
+ cl_name : Name.t ; (** Name of the class *)
+ mutable cl_info : Odoc_types.info option ; (** The optional associated user information *)
+ cl_type : Types.class_type ;
+ cl_type_parameters : Types.type_expr list ; (** Type parameters *)
+ cl_virtual : bool ; (** true = virtual *)
+ mutable cl_kind : class_kind ;
+ mutable cl_parameters : Odoc_parameter.parameter list ;
+ mutable cl_loc : Odoc_types.location ;
+ }
+
+and class_type_alias = {
+ cta_name : Name.t ;
+ mutable cta_class : cct option ; (** we can have a t_class or a t_class_type *)
+ cta_type_parameters : Types.type_expr list ; (** the type parameters *)
+ }
+
+and class_type_kind =
+ Class_signature of inherited_class list * class_element list
+ | Class_type of class_type_alias (** a class type eventually applied to type args *)
+
+(** Representation of a class type. *)
+and t_class_type = {
+ clt_name : Name.t ;
+ mutable clt_info : Odoc_types.info option ; (** The optional associated user information *)
+ clt_type : Types.class_type ;
+ clt_type_parameters : Types.type_expr list ; (** type parameters *)
+ clt_virtual : bool ; (** true = virtual *)
+ mutable clt_kind : class_type_kind ;
+ mutable clt_loc : Odoc_types.location ;
+ }
+
+
+(** {2 Functions} *)
+
+(** Returns the text associated to the given parameter label
+ in the given class, or None. *)
+let class_parameter_text_by_name cl label =
+ match cl.cl_info with
+ None -> None
+ | Some i ->
+ try
+ let t = List.assoc label i.Odoc_types.i_params in
+ Some t
+ with
+ Not_found ->
+ None
+
+(** Returns the list of elements of a t_class. *)
+let rec class_elements ?(trans=true) cl =
+ let rec iter_kind k =
+ match k with
+ Class_structure (_, elements) -> elements
+ | Class_constraint (c_kind, ct_kind) ->
+ iter_kind c_kind
+ (* A VOIR : utiliser le c_kind ou le ct_kind ?
+ Pour l'instant, comme le ct_kind n'est pas analyse,
+ on cherche dans le c_kind
+ class_type_elements ~trans: trans
+ { clt_name = "" ; clt_info = None ;
+ clt_type_parameters = [] ;
+ clt_virtual = false ;
+ clt_kind = ct_kind }
+ *)
+ | Class_apply capp ->
+ (
+ match capp.capp_class with
+ Some c when trans -> class_elements ~trans: trans c
+ | _ -> []
+ )
+ | Class_constr cco ->
+ (
+ match cco.cco_class with
+ Some (Cl c) when trans -> class_elements ~trans: trans c
+ | Some (Cltype (ct,_)) when trans -> class_type_elements ~trans: trans ct
+ | _ -> []
+ )
+ in
+ iter_kind cl.cl_kind
+
+(** Returns the list of elements of a t_class_type. *)
+and class_type_elements ?(trans=true) clt =
+ match clt.clt_kind with
+ Class_signature (_, elements) -> elements
+ | Class_type { cta_class = Some (Cltype (ct, _)) } when trans ->
+ class_type_elements ~trans ct
+ | Class_type { cta_class = Some (Cl c) } when trans ->
+ class_elements ~trans c
+ | Class_type _ ->
+ []
+
+(** Returns the attributes of a t_class. *)
+let class_attributes ?(trans=true) cl =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Class_attribute a ->
+ acc @ [ a ]
+ | _ ->
+ acc
+ )
+ []
+ (class_elements ~trans cl)
+
+(** Returns the methods of a t_class. *)
+let class_methods ?(trans=true) cl =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Class_method m ->
+ acc @ [ m ]
+ | _ ->
+ acc
+ )
+ []
+ (class_elements ~trans cl)
+
+(** Returns the comments in a t_class. *)
+let class_comments ?(trans=true) cl =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Class_comment t ->
+ acc @ [ t ]
+ | _ ->
+ acc
+ )
+ []
+ (class_elements ~trans cl)
+
+
+(** Update the parameters text of a t_class, according to the cl_info field. *)
+let class_update_parameters_text cl =
+ let f p =
+ Odoc_parameter.update_parameter_text (class_parameter_text_by_name cl) p
+ in
+ List.iter f cl.cl_parameters
+
+(** Returns the attributes of a t_class_type. *)
+let class_type_attributes ?(trans=true) clt =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Class_attribute a ->
+ acc @ [ a ]
+ | _ ->
+ acc
+ )
+ []
+ (class_type_elements ~trans clt)
+
+(** Returns the methods of a t_class_type. *)
+let class_type_methods ?(trans=true) clt =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Class_method m ->
+ acc @ [ m ]
+ | _ ->
+ acc
+ )
+ []
+ (class_type_elements ~trans clt)
+
+(** Returns the comments in a t_class_type. *)
+let class_type_comments ?(trans=true) clt =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Class_comment m ->
+ acc @ [ m ]
+ | _ ->
+ acc
+ )
+ []
+ (class_type_elements ~trans clt)
+
+(** Returns the text associated to the given parameter label
+ in the given class type, or None. *)
+let class_type_parameter_text_by_name clt label =
+ match clt.clt_info with
+ None -> None
+ | Some i ->
+ try
+ let t = List.assoc label i.Odoc_types.i_params in
+ Some t
+ with
+ Not_found ->
+ None
diff --git a/ocamldoc/odoc_comments.ml b/ocamldoc/odoc_comments.ml
new file mode 100644
index 0000000000..c39cb51bf9
--- /dev/null
+++ b/ocamldoc/odoc_comments.ml
@@ -0,0 +1,347 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Analysis of comments. *)
+
+open Odoc_types
+
+let print_DEBUG s = print_string s ; print_newline ();;
+
+(** This variable contains the regular expression representing a blank but not a '\n'.*)
+let simple_blank = "[ \013\009\012]"
+
+module type Texter =
+ sig
+ (** Return a text structure from a string. *)
+ val text_of_string : string -> text
+ end
+
+module Info_retriever =
+ functor (MyTexter : Texter) ->
+ struct
+ let create_see s =
+ try
+ let lexbuf = Lexing.from_string s in
+ let (see_ref, s) = Odoc_parser.see_info Odoc_see_lexer.main lexbuf in
+ (see_ref, MyTexter.text_of_string s)
+ with
+ | Odoc_text.Text_syntax (l, c, s) ->
+ raise (Failure (Odoc_messages.text_parse_error l c s))
+ | _ ->
+ raise (Failure ("Unknown error while parsing @see tag: "^s))
+
+ let retrieve_info fun_lex file (s : string) =
+ try
+ let _ = Odoc_comments_global.init () in
+ Odoc_lexer.comments_level := 0;
+ let lexbuf = Lexing.from_string s in
+ match Odoc_parser.main fun_lex lexbuf with
+ None ->
+ (0, None)
+ | Some (desc, remain_opt) ->
+ let mem_nb_chars = !Odoc_comments_global.nb_chars in
+ let _ =
+ match remain_opt with
+ None ->
+ ()
+ | Some s ->
+ (*DEBUG*)print_string ("remain: "^s); print_newline();
+ let lexbuf2 = Lexing.from_string s in
+ Odoc_parser.info_part2 Odoc_lexer.elements lexbuf2
+ in
+ (mem_nb_chars,
+ Some
+ {
+ i_desc = (match desc with "" -> None | _ -> Some (MyTexter.text_of_string desc));
+ i_authors = !Odoc_comments_global.authors;
+ i_version = !Odoc_comments_global.version;
+ i_sees = (List.map create_see !Odoc_comments_global.sees) ;
+ i_since = !Odoc_comments_global.since;
+ i_before = Odoc_merge.merge_before_tags
+ (List.map (fun (n, s) ->
+ (n, MyTexter.text_of_string s)) !Odoc_comments_global.before)
+ ;
+ i_deprecated =
+ (match !Odoc_comments_global.deprecated with
+ None -> None | Some s -> Some (MyTexter.text_of_string s));
+ i_params =
+ (List.map (fun (n, s) ->
+ (n, MyTexter.text_of_string s)) !Odoc_comments_global.params);
+ i_raised_exceptions =
+ (List.map (fun (n, s) ->
+ (n, MyTexter.text_of_string s)) !Odoc_comments_global.raised_exceptions);
+ i_return_value =
+ (match !Odoc_comments_global.return_value with
+ None -> None | Some s -> Some (MyTexter.text_of_string s)) ;
+ i_custom = (List.map
+ (fun (tag, s) -> (tag, MyTexter.text_of_string s))
+ !Odoc_comments_global.customs)
+ }
+ )
+ with
+ Failure s ->
+ incr Odoc_global.errors ;
+ Printf.eprintf "File %S, line %d:\n%s\n%!" file (!Odoc_lexer.line_number + 1) s;
+ (0, None)
+ | Odoc_text.Text_syntax (l, c, s) ->
+ incr Odoc_global.errors ;
+ prerr_endline (file^" : "^(Odoc_messages.text_parse_error l c s));
+ (0, None)
+ | _ ->
+ incr Odoc_global.errors ;
+ prerr_endline (file^" : "^Odoc_messages.parse_error^"\n");
+ (0, None)
+
+ (** This function takes a string where a simple comment may has been found. It returns
+ false if there is a blank line or the first comment is a special one, or if there is
+ no comment if the string.*)
+ let nothing_before_simple_comment s =
+ (* get the position of the first "(*" *)
+ try
+ print_DEBUG ("comment_is_attached: "^s);
+ let pos = Str.search_forward (Str.regexp "(\\*") s 0 in
+ let next_char = if (String.length s) >= (pos + 1) then s.[pos + 2] else '_' in
+ (next_char <> '*') &&
+ (
+ (* there is no special comment between the constructor and the coment we got *)
+ let s2 = String.sub s 0 pos in
+ print_DEBUG ("s2="^s2);
+ try
+ let _ = Str.search_forward (Str.regexp ("['\n']"^simple_blank^"*['\n']")) s2 0 in
+ (* a blank line was before the comment *)
+ false
+ with
+ Not_found ->
+ true
+ )
+ with
+ Not_found ->
+ false
+
+ (** Return true if the given string contains a blank line. *)
+ let blank_line s =
+ try
+ let _ = Str.search_forward (Str.regexp ("['\n']"^simple_blank^"*['\n']")) s 0 in
+ (* a blank line was before the comment *)
+ true
+ with
+ Not_found ->
+ false
+
+ let retrieve_info_special file (s : string) =
+ retrieve_info Odoc_lexer.main file s
+
+ let retrieve_info_simple file (s : string) =
+ let _ = Odoc_comments_global.init () in
+ Odoc_lexer.comments_level := 0;
+ let lexbuf = Lexing.from_string s in
+ match Odoc_parser.main Odoc_lexer.simple lexbuf with
+ None ->
+ (0, None)
+ | Some (desc, remain_opt) ->
+ (!Odoc_comments_global.nb_chars, Some Odoc_types.dummy_info)
+
+ (** Return true if the given string contains a blank line outside a simple comment. *)
+ let blank_line_outside_simple file s =
+ let rec iter s2 =
+ match retrieve_info_simple file s2 with
+ (_, None) ->
+ blank_line s2
+ | (len, Some _) ->
+ try
+ let pos = Str.search_forward (Str.regexp_string "(*") s2 0 in
+ let s_before = String.sub s2 0 pos in
+ let s_after = String.sub s2 len ((String.length s2) - len) in
+ (blank_line s_before) || (iter s_after)
+ with
+ Not_found ->
+ (* we shouldn't get here *)
+ false
+ in
+ iter s
+
+ (** This function returns the first simple comment in
+ the given string. If strict is [true] then no
+ comment is returned if a blank line or a special
+ comment is found before the simple comment. *)
+ let retrieve_first_info_simple ?(strict=true) file (s : string) =
+ match retrieve_info_simple file s with
+ (_, None) ->
+ (0, None)
+ | (len, Some d) ->
+ (* we check if the comment we got was really attached to the constructor,
+ i.e. that there was no blank line or any special comment "(**" before *)
+ if (not strict) || (nothing_before_simple_comment s) then
+ (* ok, we attach the comment to the constructor *)
+ (len, Some d)
+ else
+ (* a blank line or special comment was before the comment,
+ so we must not attach this comment to the constructor. *)
+ (0, None)
+
+ let retrieve_last_info_simple file (s : string) =
+ print_DEBUG ("retrieve_last_info_simple:"^s);
+ let rec f cur_len cur_d =
+ try
+ let s2 = String.sub s cur_len ((String.length s) - cur_len) in
+ print_DEBUG ("retrieve_last_info_simple.f:"^s2);
+ match retrieve_info_simple file s2 with
+ (len, None) ->
+ print_DEBUG "retrieve_last_info_simple: None";
+ (cur_len + len, cur_d)
+ | (len, Some d) ->
+ print_DEBUG "retrieve_last_info_simple: Some";
+ f (len + cur_len) (Some d)
+ with
+ _ ->
+ print_DEBUG "retrieve_last_info_simple : Erreur String.sub";
+ (cur_len, cur_d)
+ in
+ f 0 None
+
+ let retrieve_last_special_no_blank_after file (s : string) =
+ print_DEBUG ("retrieve_last_special_no_blank_after:"^s);
+ let rec f cur_len cur_d =
+ try
+ let s2 = String.sub s cur_len ((String.length s) - cur_len) in
+ print_DEBUG ("retrieve_last_special_no_blank_after.f:"^s2);
+ match retrieve_info_special file s2 with
+ (len, None) ->
+ print_DEBUG "retrieve_last_special_no_blank_after: None";
+ (cur_len + len, cur_d)
+ | (len, Some d) ->
+ print_DEBUG "retrieve_last_special_no_blank_after: Some";
+ f (len + cur_len) (Some d)
+ with
+ _ ->
+ print_DEBUG "retrieve_last_special_no_blank_after : Erreur String.sub";
+ (cur_len, cur_d)
+ in
+ f 0 None
+
+ let all_special file s =
+ print_DEBUG ("all_special: "^s);
+ let rec iter acc n s2 =
+ match retrieve_info_special file s2 with
+ (_, None) ->
+ (n, acc)
+ | (n2, Some i) ->
+ print_DEBUG ("all_special: avant String.sub new_s="^s2);
+ print_DEBUG ("n2="^(string_of_int n2)) ;
+ print_DEBUG ("len(s2)="^(string_of_int (String.length s2))) ;
+ let new_s = String.sub s2 n2 ((String.length s2) - n2) in
+ print_DEBUG ("all_special: apres String.sub new_s="^new_s);
+ iter (acc @ [i]) (n + n2) new_s
+ in
+ let res = iter [] 0 s in
+ print_DEBUG ("all_special: end");
+ res
+
+ let just_after_special file s =
+ print_DEBUG ("just_after_special: "^s);
+ let res = match retrieve_info_special file s with
+ (_, None) ->
+ (0, None)
+ | (len, Some d) ->
+ (* we must not have a simple comment or a blank line before. *)
+ match retrieve_info_simple file (String.sub s 0 len) with
+ (_, None) ->
+ (
+ try
+ (* if the special comment is the stop comment (**/**),
+ then we must not associate it. *)
+ let pos = Str.search_forward (Str.regexp_string "(**") s 0 in
+ if blank_line (String.sub s 0 pos) ||
+ d.Odoc_types.i_desc = Some [Odoc_types.Raw "/*"]
+ then
+ (0, None)
+ else
+ (len, Some d)
+ with
+ Not_found ->
+ (* should not occur *)
+ (0, None)
+ )
+ | (len2, Some d2) ->
+ (0, None)
+ in
+ print_DEBUG ("just_after_special:end");
+ res
+
+ let first_special file s =
+ retrieve_info_special file s
+
+ let get_comments f_create_ele file s =
+ let (assoc_com, ele_coms) =
+ (* get the comments *)
+ let (len, special_coms) = all_special file s in
+ (* if there is no blank line after the special comments, and
+ if the last special comment is not the stop special comment, then the
+ last special comments must be associated to the element. *)
+ match List.rev special_coms with
+ [] ->
+ (None, [])
+ | h :: q ->
+ if (blank_line_outside_simple file
+ (String.sub s len ((String.length s) - len)) )
+ || h.Odoc_types.i_desc = Some [Odoc_types.Raw "/*"]
+ then
+ (None, special_coms)
+ else
+ (Some h, List.rev q)
+ in
+ let ele_comments =
+ List.fold_left
+ (fun acc -> fun sc ->
+ match sc.Odoc_types.i_desc with
+ None ->
+ acc
+ | Some t ->
+ acc @ [f_create_ele t])
+ []
+ ele_coms
+ in
+ (assoc_com, ele_comments)
+ end
+
+module Basic_info_retriever = Info_retriever (Odoc_text.Texter)
+
+let info_of_string s =
+ let dummy =
+ {
+ i_desc = None ;
+ i_authors = [] ;
+ i_version = None ;
+ i_sees = [] ;
+ i_since = None ;
+ i_before = [] ;
+ i_deprecated = None ;
+ i_params = [] ;
+ i_raised_exceptions = [] ;
+ i_return_value = None ;
+ i_custom = [] ;
+ }
+ in
+ let s2 = Printf.sprintf "(** %s *)" s in
+ let (_, i_opt) = Basic_info_retriever.first_special "-" s2 in
+ match i_opt with
+ None -> dummy
+ | Some i -> i
+
+let info_of_comment_file modlist f =
+ try
+ let s = Odoc_misc.input_file_as_string f in
+ let i = info_of_string s in
+ Odoc_cross.assoc_comments_info "" modlist i
+ with
+ Sys_error s ->
+ failwith s
diff --git a/ocamldoc/odoc_comments.mli b/ocamldoc/odoc_comments.mli
new file mode 100644
index 0000000000..6aeb91ded2
--- /dev/null
+++ b/ocamldoc/odoc_comments.mli
@@ -0,0 +1,73 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Analysis of comments. *)
+
+val simple_blank : string
+
+(** The type of modules in argument to Info_retriever *)
+module type Texter =
+ sig
+ (** Return a text structure from a string. *)
+ val text_of_string : string -> Odoc_types.text
+ end
+
+(** The basic module for special comments analysis.*)
+module Basic_info_retriever :
+ sig
+ (** Return true if the given string contains a blank line. *)
+ val blank_line_outside_simple :
+ string -> string -> bool
+
+ (** This function retrieves all the special comments in the given string. *)
+ val all_special : string -> string -> int * Odoc_types.info list
+
+ (** [just_after_special file str] return the pair ([length], [info_opt])
+ where [info_opt] is the first optional special comment found
+ in [str], without any blank line before. [length] is the number
+ of chars from the beginning of [str] to the end of the special comment. *)
+ val just_after_special :
+ string -> string -> int * Odoc_types.info option
+
+ (** [first_special file str] return the pair ([length], [info_opt])
+ where [info_opt] is the first optional special comment found
+ in [str]. [length] is the number of chars from the beginning of
+ [str] to the end of the special comment. *)
+ val first_special :
+ string -> string -> int * Odoc_types.info option
+
+ (** Return a pair [(comment_opt, element_comment_list)], where [comment_opt] is the last special
+ comment found in the given string and not followed by a blank line,
+ and [element_comment_list] the list of values built from the other
+ special comments found and the given function. *)
+ val get_comments :
+ (Odoc_types.text -> 'a) ->
+ string -> string -> Odoc_types.info option * 'a list
+
+ end
+
+(** [info_of_string s] parses the given string
+ like a regular ocamldoc comment and return an
+ {!Odoc_types.info} structure.
+ @return an empty structure if there was a syntax error. TODO: change this
+*)
+val info_of_string : string -> Odoc_types.info
+
+(** [info_of_comment_file file] parses the given file
+ and return an {!Odoc_types.info} structure. The content of the
+ file must have the same syntax as the content of a special comment.
+ The given module list is used for cross reference.
+ @raise Failure is the file could not be opened or there is a
+ syntax error.
+*)
+val info_of_comment_file :
+ Odoc_module.t_module list -> string -> Odoc_types.info
diff --git a/ocamldoc/odoc_comments_global.ml b/ocamldoc/odoc_comments_global.ml
new file mode 100644
index 0000000000..5fbe6406b5
--- /dev/null
+++ b/ocamldoc/odoc_comments_global.ml
@@ -0,0 +1,48 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The global variables used by the special comment parser.*)
+
+let nb_chars = ref 0
+
+let authors = ref ([] : string list)
+
+let version = ref (None : string option)
+
+let sees = ref ([] : string list)
+
+let since = ref (None : string option)
+
+let before = ref []
+
+let deprecated = ref (None : string option)
+
+let params = ref ([] : (string * string) list)
+
+let raised_exceptions = ref ([] : (string * string) list)
+
+let return_value = ref (None : string option)
+
+let customs = ref []
+
+let init () =
+ nb_chars := 0;
+ authors := [];
+ version := None;
+ sees := [];
+ since := None;
+ before := [];
+ deprecated := None;
+ params := [];
+ raised_exceptions := [];
+ return_value := None ;
+ customs := []
diff --git a/ocamldoc/odoc_comments_global.mli b/ocamldoc/odoc_comments_global.mli
new file mode 100644
index 0000000000..291673c076
--- /dev/null
+++ b/ocamldoc/odoc_comments_global.mli
@@ -0,0 +1,49 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The global variables used by the special comment parser.*)
+
+(** the number of chars used in the lexer. *)
+val nb_chars : int ref
+
+(** the authors list *)
+val authors : string list ref
+
+(** the version string *)
+val version : string option ref
+
+(** the see references *)
+val sees : string list ref
+
+(** the since string *)
+val since : string option ref
+
+(** the before tag information *)
+val before : (string * string) list ref
+
+(** the deprecated flag *)
+val deprecated : string option ref
+
+(** parameters, with name and description *)
+val params : (string * string) list ref
+
+(** the raised exceptions, with name and description *)
+val raised_exceptions : (string * string) list ref
+
+(** the description of the return value *)
+val return_value : string option ref
+
+(** the strings associated to custom tags. *)
+val customs : (string * string) list ref
+
+(** this function inits the variables filled by the parser. *)
+val init : unit -> unit
diff --git a/ocamldoc/odoc_config.ml b/ocamldoc/odoc_config.ml
new file mode 100644
index 0000000000..4250f514cd
--- /dev/null
+++ b/ocamldoc/odoc_config.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let custom_generators_path =
+ Filename.concat Config.standard_library
+ (Filename.concat "ocamldoc" "custom")
+
+let print_warnings = ref true
diff --git a/ocamldoc/odoc_config.mli b/ocamldoc/odoc_config.mli
new file mode 100644
index 0000000000..59ffc09888
--- /dev/null
+++ b/ocamldoc/odoc_config.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Ocamldoc configuration contants. *)
+
+(** Default path to search for custom generators and to install them. *)
+val custom_generators_path : string
+
+(** A flag to indicate whether to print ocamldoc warnings or not. *)
+val print_warnings : bool ref
diff --git a/ocamldoc/odoc_control.ml b/ocamldoc/odoc_control.ml
new file mode 100644
index 0000000000..30a1f393d8
--- /dev/null
+++ b/ocamldoc/odoc_control.ml
@@ -0,0 +1,11 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
diff --git a/ocamldoc/odoc_cross.ml b/ocamldoc/odoc_cross.ml
new file mode 100644
index 0000000000..156651f58e
--- /dev/null
+++ b/ocamldoc/odoc_cross.ml
@@ -0,0 +1,1103 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Cross referencing. *)
+
+module Name = Odoc_name
+open Odoc_module
+open Odoc_class
+open Odoc_extension
+open Odoc_exception
+open Odoc_types
+open Odoc_value
+open Odoc_type
+open Odoc_parameter
+
+(*** Replacements of aliases : if e1 = e2 and e2 = e3, then replace e2 by e3 to have e1 = e3,
+ in order to associate the element with complete information. *)
+
+(** The module used to keep what refs were modified. *)
+module S = Set.Make
+ (
+ struct type t = string * ref_kind option
+ let compare = Pervasives.compare
+ end
+ )
+
+let verified_refs = ref S.empty
+
+let add_verified v = verified_refs := S.add v !verified_refs
+let was_verified v = S.mem v !verified_refs
+
+(** The module with the predicates used to get the aliased modules, classes and exceptions. *)
+module P_alias =
+ struct
+ type t = int
+
+ let p_module m _ =
+ (true,
+ match m.m_kind with
+ Module_alias _ -> true
+ | _ -> false
+ )
+ let p_module_type mt _ =
+ (true,
+ match mt.mt_kind with
+ Some (Module_type_alias _) -> true
+ | _ -> false
+ )
+ let p_class c _ = (false, false)
+ let p_class_type ct _ = (false, false)
+ let p_value v _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type t _ = (false, false)
+ let p_extension x _ = x.xt_alias <> None
+ let p_exception e _ = e.ex_alias <> None
+ let p_attribute a _ = false
+ let p_method m _ = false
+ let p_section s _ = false
+ end
+
+(** The module used to get the aliased elements. *)
+module Search_alias = Odoc_search.Search (P_alias)
+
+type alias_state =
+ Alias_resolved
+ | Alias_to_resolve
+
+(** Couples of module name aliases. *)
+let (module_aliases : (Name.t, Name.t * alias_state) Hashtbl.t) = Hashtbl.create 13 ;;
+
+(** Couples of module or module type name aliases. *)
+let module_and_modtype_aliases = Hashtbl.create 13;;
+
+(** Couples of extension name aliases. *)
+let extension_aliases = Hashtbl.create 13;;
+
+(** Couples of exception name aliases. *)
+let exception_aliases = Hashtbl.create 13;;
+
+let rec build_alias_list = function
+ [] -> ()
+ | (Odoc_search.Res_module m) :: q ->
+ (
+ match m.m_kind with
+ Module_alias ma ->
+ Hashtbl.add module_aliases m.m_name (ma.ma_name, Alias_to_resolve);
+ Hashtbl.add module_and_modtype_aliases m.m_name (ma.ma_name, Alias_to_resolve)
+ | _ -> ()
+ );
+ build_alias_list q
+ | (Odoc_search.Res_module_type mt) :: q ->
+ (
+ match mt.mt_kind with
+ Some (Module_type_alias mta) ->
+ Hashtbl.add module_and_modtype_aliases
+ mt.mt_name (mta.mta_name, Alias_to_resolve)
+ | _ -> ()
+ );
+ build_alias_list q
+ | (Odoc_search.Res_extension x) :: q ->
+ (
+ match x.xt_alias with
+ None -> ()
+ | Some xa ->
+ Hashtbl.add extension_aliases
+ x.xt_name (xa.xa_name,Alias_to_resolve)
+ );
+ build_alias_list q
+ | (Odoc_search.Res_exception e) :: q ->
+ (
+ match e.ex_alias with
+ None -> ()
+ | Some ea ->
+ Hashtbl.add exception_aliases
+ e.ex_name (ea.ea_name,Alias_to_resolve)
+ );
+ build_alias_list q
+ | _ :: q ->
+ build_alias_list q
+
+(** Retrieve the aliases for modules, module types and exceptions
+ and put them in global hash tables. *)
+let get_alias_names module_list =
+ Hashtbl.clear module_aliases;
+ Hashtbl.clear module_and_modtype_aliases;
+ Hashtbl.clear extension_aliases;
+ Hashtbl.clear exception_aliases;
+ build_alias_list (Search_alias.search module_list 0)
+
+exception Found of string
+let name_alias =
+ let rec f t name =
+ try
+ match Hashtbl.find t name with
+ (s, Alias_resolved) -> s
+ | (s, Alias_to_resolve) -> f t s
+ with
+ Not_found ->
+ try
+ Hashtbl.iter
+ (fun n2 (n3, _) ->
+ if Name.prefix n2 name then
+ let ln2 = String.length n2 in
+ let s = n3^(String.sub name ln2 ((String.length name) - ln2)) in
+ raise (Found s)
+ )
+ t ;
+ Hashtbl.replace t name (name, Alias_resolved);
+ name
+ with
+ Found s ->
+ let s2 = f t s in
+ Hashtbl.replace t s2 (s2, Alias_resolved);
+ s2
+ in
+ fun name alias_tbl ->
+ f alias_tbl name
+
+
+module Map_ord =
+ struct
+ type t = string
+ let compare (x:t) y = Pervasives.compare x y
+ end
+
+module Ele_map = Map.Make (Map_ord)
+
+let known_elements = ref Ele_map.empty
+let add_known_element name k =
+ try
+ let l = Ele_map.find name !known_elements in
+ let s = Ele_map.remove name !known_elements in
+ known_elements := Ele_map.add name (k::l) s
+ with
+ Not_found ->
+ known_elements := Ele_map.add name [k] !known_elements
+
+let rec get_known_elements name =
+ try Ele_map.find name !known_elements
+ with Not_found -> []
+
+let kind_name_exists kind =
+ let pred =
+ match kind with
+ RK_module -> (fun e -> match e with Odoc_search.Res_module _ -> true | _ -> false)
+ | RK_module_type -> (fun e -> match e with Odoc_search.Res_module_type _ -> true | _ -> false)
+ | RK_class -> (fun e -> match e with Odoc_search.Res_class _ -> true | _ -> false)
+ | RK_class_type -> (fun e -> match e with Odoc_search.Res_class_type _ -> true | _ -> false)
+ | RK_value -> (fun e -> match e with Odoc_search.Res_value _ -> true | _ -> false)
+ | RK_type -> (fun e -> match e with Odoc_search.Res_type _ -> true | _ -> false)
+ | RK_extension -> (fun e -> match e with Odoc_search.Res_extension _ -> true | _ -> false)
+ | RK_exception -> (fun e -> match e with Odoc_search.Res_exception _ -> true | _ -> false)
+ | RK_attribute -> (fun e -> match e with Odoc_search.Res_attribute _ -> true | _ -> false)
+ | RK_method -> (fun e -> match e with Odoc_search.Res_method _ -> true | _ -> false)
+ | RK_section _ -> assert false
+ | RK_recfield -> (fun e -> match e with Odoc_search.Res_recfield _ -> true | _ -> false)
+ | RK_const -> (fun e -> match e with Odoc_search.Res_const _ -> true | _ -> false)
+ in
+ fun name ->
+ try List.exists pred (get_known_elements name)
+ with Not_found -> false
+
+let module_exists = kind_name_exists RK_module
+let module_type_exists = kind_name_exists RK_module_type
+let class_exists = kind_name_exists RK_class
+let class_type_exists = kind_name_exists RK_class_type
+let value_exists = kind_name_exists RK_value
+let type_exists = kind_name_exists RK_type
+let extension_exists = kind_name_exists RK_extension
+let exception_exists = kind_name_exists RK_exception
+let attribute_exists = kind_name_exists RK_attribute
+let method_exists = kind_name_exists RK_method
+let recfield_exists = kind_name_exists RK_recfield
+let const_exists = kind_name_exists RK_const
+
+let lookup_module name =
+ match List.find
+ (fun k -> match k with Odoc_search.Res_module _ -> true | _ -> false)
+ (get_known_elements name)
+ with
+ | Odoc_search.Res_module m -> m
+ | _ -> assert false
+
+let lookup_module_type name =
+ match List.find
+ (fun k -> match k with Odoc_search.Res_module_type _ -> true | _ -> false)
+ (get_known_elements name)
+ with
+ | Odoc_search.Res_module_type m -> m
+ | _ -> assert false
+
+let lookup_class name =
+ match List.find
+ (fun k -> match k with Odoc_search.Res_class _ -> true | _ -> false)
+ (get_known_elements name)
+ with
+ | Odoc_search.Res_class c -> c
+ | _ -> assert false
+
+let lookup_class_type name =
+ match List.find
+ (fun k -> match k with Odoc_search.Res_class_type _ -> true | _ -> false)
+ (get_known_elements name)
+ with
+ | Odoc_search.Res_class_type c -> c
+ | _ -> assert false
+
+let lookup_extension name =
+ match List.find
+ (fun k -> match k with Odoc_search.Res_extension _ -> true | _ -> false)
+ (get_known_elements name)
+ with
+ | Odoc_search.Res_extension x -> x
+ | _ -> assert false
+
+let lookup_exception name =
+ match List.find
+ (fun k -> match k with Odoc_search.Res_exception _ -> true | _ -> false)
+ (get_known_elements name)
+ with
+ | Odoc_search.Res_exception e -> e
+ | _ -> assert false
+
+class scan =
+ object
+ inherit Odoc_scan.scanner
+ method! scan_value v =
+ add_known_element v.val_name (Odoc_search.Res_value v)
+ method! scan_type_recfield t f =
+ add_known_element
+ (Printf.sprintf "%s.%s" t.ty_name f.rf_name)
+ (Odoc_search.Res_recfield (t, f))
+ method! scan_type_const t f =
+ add_known_element
+ (Printf.sprintf "%s.%s" t.ty_name f.vc_name)
+ (Odoc_search.Res_const (t, f))
+ method! scan_type_pre t =
+ add_known_element t.ty_name (Odoc_search.Res_type t);
+ true
+ method! scan_extension_constructor x =
+ add_known_element x.xt_name (Odoc_search.Res_extension x)
+ method! scan_exception e =
+ add_known_element e.ex_name (Odoc_search.Res_exception e)
+ method! scan_attribute a =
+ add_known_element a.att_value.val_name
+ (Odoc_search.Res_attribute a)
+ method! scan_method m =
+ add_known_element m.met_value.val_name
+ (Odoc_search.Res_method m)
+ method! scan_class_pre c =
+ add_known_element c.cl_name (Odoc_search.Res_class c);
+ true
+ method! scan_class_type_pre c =
+ add_known_element c.clt_name (Odoc_search.Res_class_type c);
+ true
+ method! scan_module_pre m =
+ add_known_element m.m_name (Odoc_search.Res_module m);
+ true
+ method! scan_module_type_pre m =
+ add_known_element m.mt_name (Odoc_search.Res_module_type m);
+ true
+
+ end
+
+let init_known_elements_map module_list =
+ let c = new scan in
+ c#scan_module_list module_list
+
+
+(** The type to describe the names not found. *)
+type not_found_name =
+ NF_m of Name.t
+ | NF_mt of Name.t
+ | NF_mmt of Name.t
+ | NF_c of Name.t
+ | NF_ct of Name.t
+ | NF_cct of Name.t
+ | NF_xt of Name.t
+ | NF_ex of Name.t
+
+(** Functions to find and associate aliases elements. *)
+
+let rec associate_in_module module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) m =
+ let rec iter_kind (acc_b, acc_inc, acc_names) k =
+ match k with
+ Module_struct elements ->
+ List.fold_left
+ (associate_in_module_element module_list m.m_name)
+ (acc_b, acc_inc, acc_names)
+ elements
+
+ | Module_alias ma ->
+ (
+ match ma.ma_module with
+ Some _ ->
+ (acc_b, acc_inc, acc_names)
+ | None ->
+ let mmt_opt =
+ try Some (Mod (lookup_module ma.ma_name))
+ with Not_found ->
+ try Some (Modtype (lookup_module_type ma.ma_name))
+ with Not_found -> None
+ in
+ match mmt_opt with
+ None -> (acc_b, (Name.head m.m_name) :: acc_inc,
+ (* we don't want to output warning messages for
+ "sig ... end" or "struct ... end" modules not found *)
+ (if ma.ma_name = Odoc_messages.struct_end ||
+ ma.ma_name = Odoc_messages.sig_end then
+ acc_names
+ else
+ (NF_mmt ma.ma_name) :: acc_names)
+ )
+ | Some mmt ->
+ ma.ma_module <- Some mmt ;
+ (true, acc_inc, acc_names)
+ )
+
+ | Module_functor (_, k) ->
+ iter_kind (acc_b, acc_inc, acc_names) k
+
+ | Module_with (tk, _) ->
+ associate_in_module_type module_list (acc_b, acc_inc, acc_names)
+ { mt_name = "" ; mt_info = None ; mt_type = None ;
+ mt_is_interface = false ; mt_file = ""; mt_kind = Some tk ;
+ mt_loc = Odoc_types.dummy_loc }
+
+ | Module_apply (k1, k2) ->
+ let (acc_b2, acc_inc2, acc_names2) = iter_kind (acc_b, acc_inc, acc_names) k1 in
+ iter_kind (acc_b2, acc_inc2, acc_names2) k2
+
+ | Module_constraint (k, tk) ->
+ let (acc_b2, acc_inc2, acc_names2) = iter_kind (acc_b, acc_inc, acc_names) k in
+ associate_in_module_type module_list (acc_b2, acc_inc2, acc_names2)
+ { mt_name = "" ; mt_info = None ; mt_type = None ;
+ mt_is_interface = false ; mt_file = "" ; mt_kind = Some tk ;
+ mt_loc = Odoc_types.dummy_loc }
+
+ | Module_typeof _ ->
+ (acc_b, acc_inc, acc_names)
+
+ | Module_unpack (code, mta) ->
+ begin
+ match mta.mta_module with
+ Some _ ->
+ (acc_b, acc_inc, acc_names)
+ | None ->
+ let mt_opt =
+ try Some (lookup_module_type mta.mta_name)
+ with Not_found -> None
+ in
+ match mt_opt with
+ None -> (acc_b, (Name.head m.m_name) :: acc_inc,
+ (* we don't want to output warning messages for
+ "sig ... end" or "struct ... end" modules not found *)
+ (if mta.mta_name = Odoc_messages.struct_end ||
+ mta.mta_name = Odoc_messages.sig_end then
+ acc_names
+ else
+ (NF_mt mta.mta_name) :: acc_names)
+ )
+ | Some mt ->
+ mta.mta_module <- Some mt ;
+ (true, acc_inc, acc_names)
+ end
+ in
+ iter_kind (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) m.m_kind
+
+and associate_in_module_type module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) mt =
+ let rec iter_kind (acc_b, acc_inc, acc_names) k =
+ match k with
+ Module_type_struct elements ->
+ List.fold_left
+ (associate_in_module_element module_list mt.mt_name)
+ (acc_b, acc_inc, acc_names)
+ elements
+
+ | Module_type_functor (_, k) ->
+ iter_kind (acc_b, acc_inc, acc_names) k
+
+ | Module_type_with (k, _) ->
+ iter_kind (acc_b, acc_inc, acc_names) k
+
+ | Module_type_alias mta ->
+ begin
+ match mta.mta_module with
+ Some _ ->
+ (acc_b, acc_inc, acc_names)
+ | None ->
+ let mt_opt =
+ try Some (lookup_module_type mta.mta_name)
+ with Not_found -> None
+ in
+ match mt_opt with
+ None -> (acc_b, (Name.head mt.mt_name) :: acc_inc,
+ (* we don't want to output warning messages for
+ "sig ... end" or "struct ... end" modules not found *)
+ (if mta.mta_name = Odoc_messages.struct_end ||
+ mta.mta_name = Odoc_messages.sig_end then
+ acc_names
+ else
+ (NF_mt mta.mta_name) :: acc_names)
+ )
+ | Some mt ->
+ mta.mta_module <- Some mt ;
+ (true, acc_inc, acc_names)
+ end
+ | Module_type_typeof _ ->
+ (acc_b, acc_inc, acc_names)
+ in
+ match mt.mt_kind with
+ None -> (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ | Some k -> iter_kind (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) k
+
+and associate_in_module_element module_list m_name (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) element =
+ match element with
+ Element_module m -> associate_in_module module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) m
+ | Element_module_type mt ->
+ associate_in_module_type module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) mt
+ | Element_included_module im ->
+ (
+ match im.im_module with
+ Some _ -> (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ | None ->
+ let mmt_opt =
+ try Some (Mod (lookup_module im.im_name))
+ with Not_found ->
+ try Some (Modtype (lookup_module_type im.im_name))
+ with Not_found -> None
+ in
+ match mmt_opt with
+ None -> (acc_b_modif, (Name.head m_name) :: acc_incomplete_top_module_names,
+ (* we don't want to output warning messages for
+ "sig ... end" or "struct ... end" modules not found *)
+ (if im.im_name = Odoc_messages.struct_end ||
+ im.im_name = Odoc_messages.sig_end then
+ acc_names_not_found
+ else
+ (NF_mmt im.im_name) :: acc_names_not_found)
+ )
+ | Some mmt ->
+ im.im_module <- Some mmt ;
+ (true, acc_incomplete_top_module_names, acc_names_not_found)
+ )
+ | Element_class cl -> associate_in_class module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) cl
+ | Element_class_type ct ->
+ associate_in_class_type module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) ct
+ | Element_value _ -> (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ | Element_type_extension te ->
+ associate_in_type_extension module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) te
+ | Element_exception ex ->
+ (
+ match ex.ex_alias with
+ None -> (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ | Some ea ->
+ match ea.ea_ex with
+ Some _ ->
+ (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ | None ->
+ let ex_opt =
+ try Some (lookup_exception ea.ea_name)
+ with Not_found -> None
+ in
+ match ex_opt with
+ None -> (acc_b_modif,
+ (Name.head m_name) :: acc_incomplete_top_module_names,
+ (NF_ex ea.ea_name) :: acc_names_not_found)
+ | Some e ->
+ ea.ea_ex <- Some e ;
+ (true, acc_incomplete_top_module_names, acc_names_not_found)
+ )
+ | Element_type _ -> (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ | Element_module_comment _ -> (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+
+and associate_in_class module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) c =
+ let rec iter_kind (acc_b, acc_inc, acc_names) k =
+ match k with
+ Class_structure (inher_l, _) ->
+ let f (acc_b2, acc_inc2, acc_names2) ic =
+ match ic.ic_class with
+ Some _ -> (acc_b2, acc_inc2, acc_names2)
+ | None ->
+ let cct_opt =
+ try Some (Cl (lookup_class ic.ic_name))
+ with Not_found ->
+ try Some (Cltype (lookup_class_type ic.ic_name, []))
+ with Not_found -> None
+ in
+ match cct_opt with
+ None -> (acc_b2, (Name.head c.cl_name) :: acc_inc2,
+ (* we don't want to output warning messages for "object ... end" classes not found *)
+ (if ic.ic_name = Odoc_messages.object_end then acc_names2 else (NF_cct ic.ic_name) :: acc_names2))
+ | Some cct ->
+ ic.ic_class <- Some cct ;
+ (true, acc_inc2, acc_names2)
+ in
+ List.fold_left f (acc_b, acc_inc, acc_names) inher_l
+
+ | Class_apply capp ->
+ (
+ match capp.capp_class with
+ Some _ -> (acc_b, acc_inc, acc_names)
+ | None ->
+ let cl_opt =
+ try Some (lookup_class capp.capp_name)
+ with Not_found -> None
+ in
+ match cl_opt with
+ None -> (acc_b, (Name.head c.cl_name) :: acc_inc,
+ (* we don't want to output warning messages for "object ... end" classes not found *)
+ (if capp.capp_name = Odoc_messages.object_end then acc_names else (NF_c capp.capp_name) :: acc_names))
+ | Some c ->
+ capp.capp_class <- Some c ;
+ (true, acc_inc, acc_names)
+ )
+
+ | Class_constr cco ->
+ (
+ match cco.cco_class with
+ Some _ -> (acc_b, acc_inc, acc_names)
+ | None ->
+ let cl_opt =
+ try Some (lookup_class cco.cco_name)
+ with Not_found -> None
+ in
+ match cl_opt with
+ None ->
+ (
+ let clt_opt =
+ try Some (lookup_class_type cco.cco_name)
+ with Not_found -> None
+ in
+ match clt_opt with
+ None ->
+ (acc_b, (Name.head c.cl_name) :: acc_inc,
+ (* we don't want to output warning messages for "object ... end" classes not found *)
+ (if cco.cco_name = Odoc_messages.object_end then acc_names else (NF_cct cco.cco_name) :: acc_names))
+ | Some ct ->
+ cco.cco_class <- Some (Cltype (ct, [])) ;
+ (true, acc_inc, acc_names)
+ )
+ | Some c ->
+ cco.cco_class <- Some (Cl c) ;
+ (true, acc_inc, acc_names)
+ )
+ | Class_constraint (ckind, ctkind) ->
+ let (acc_b2, acc_inc2, acc_names2) = iter_kind (acc_b, acc_inc, acc_names) ckind in
+ associate_in_class_type module_list (acc_b2, acc_inc2, acc_names2)
+ { clt_name = "" ; clt_info = None ;
+ clt_type = c.cl_type ; (* should be ok *)
+ clt_type_parameters = [] ;
+ clt_virtual = false ;
+ clt_kind = ctkind ;
+ clt_loc = Odoc_types.dummy_loc }
+ in
+ iter_kind (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) c.cl_kind
+
+and associate_in_class_type module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) ct =
+ let rec iter_kind (acc_b, acc_inc, acc_names) k =
+ match k with
+ Class_signature (inher_l, _) ->
+ let f (acc_b2, acc_inc2, acc_names2) ic =
+ match ic.ic_class with
+ Some _ -> (acc_b2, acc_inc2, acc_names2)
+ | None ->
+ let cct_opt =
+ try Some (Cltype (lookup_class_type ic.ic_name, []))
+ with Not_found ->
+ try Some (Cl (lookup_class ic.ic_name))
+ with Not_found -> None
+ in
+ match cct_opt with
+ None -> (acc_b2, (Name.head ct.clt_name) :: acc_inc2,
+ (* we don't want to output warning messages for "object ... end" class types not found *)
+ (if ic.ic_name = Odoc_messages.object_end then acc_names2 else (NF_cct ic.ic_name) :: acc_names2))
+ | Some cct ->
+ ic.ic_class <- Some cct ;
+ (true, acc_inc2, acc_names2)
+ in
+ List.fold_left f (acc_b, acc_inc, acc_names) inher_l
+
+ | Class_type cta ->
+ (
+ match cta.cta_class with
+ Some _ -> (acc_b, acc_inc, acc_names)
+ | None ->
+ let cct_opt =
+ try Some (Cltype (lookup_class_type cta.cta_name, []))
+ with Not_found ->
+ try Some (Cl (lookup_class cta.cta_name))
+ with Not_found -> None
+ in
+ match cct_opt with
+ None -> (acc_b, (Name.head ct.clt_name) :: acc_inc,
+ (* we don't want to output warning messages for "object ... end" class types not found *)
+ (if cta.cta_name = Odoc_messages.object_end then acc_names else (NF_cct cta.cta_name) :: acc_names))
+ | Some c ->
+ cta.cta_class <- Some c ;
+ (true, acc_inc, acc_names)
+ )
+ in
+ iter_kind (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) ct.clt_kind
+
+and associate_in_type_extension module_list (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) te =
+ List.fold_left
+ (fun (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found) xt ->
+ match xt.xt_alias with
+ None -> (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ | Some xa ->
+ match xa.xa_xt with
+ Some _ ->
+ (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ | None ->
+ let xt_opt =
+ try Some (lookup_extension xa.xa_name)
+ with Not_found -> None
+ in
+ match xt_opt with
+ None -> (acc_b_modif,
+ (Name.head xt.xt_name) :: acc_incomplete_top_module_names,
+ (NF_xt xa.xa_name) :: acc_names_not_found)
+ | Some x ->
+ xa.xa_xt <- Some x ;
+ (true, acc_incomplete_top_module_names, acc_names_not_found))
+ (acc_b_modif, acc_incomplete_top_module_names, acc_names_not_found)
+ te.te_constructors
+
+
+(*************************************************************)
+(** Association of types to elements referenced in comments .*)
+
+let ao = Odoc_misc.apply_opt
+
+let not_found_of_kind kind name =
+ (match kind with
+ RK_module -> Odoc_messages.cross_module_not_found
+ | RK_module_type -> Odoc_messages.cross_module_type_not_found
+ | RK_class -> Odoc_messages.cross_class_not_found
+ | RK_class_type -> Odoc_messages.cross_class_type_not_found
+ | RK_value -> Odoc_messages.cross_value_not_found
+ | RK_type -> Odoc_messages.cross_type_not_found
+ | RK_extension -> Odoc_messages.cross_extension_not_found
+ | RK_exception -> Odoc_messages.cross_exception_not_found
+ | RK_attribute -> Odoc_messages.cross_attribute_not_found
+ | RK_method -> Odoc_messages.cross_method_not_found
+ | RK_section _ -> Odoc_messages.cross_section_not_found
+ | RK_recfield -> Odoc_messages.cross_recfield_not_found
+ | RK_const -> Odoc_messages.cross_const_not_found
+ ) name
+
+let rec assoc_comments_text_elements parent_name module_list t_ele =
+ match t_ele with
+ | Raw _
+ | Code _
+ | CodePre _
+ | Latex _
+ | Verbatim _ -> t_ele
+ | Bold t -> Bold (assoc_comments_text parent_name module_list t)
+ | Italic t -> Italic (assoc_comments_text parent_name module_list t)
+ | Center t -> Center (assoc_comments_text parent_name module_list t)
+ | Left t -> Left (assoc_comments_text parent_name module_list t)
+ | Right t -> Right (assoc_comments_text parent_name module_list t)
+ | Emphasize t -> Emphasize (assoc_comments_text parent_name module_list t)
+ | List l -> List (List.map (assoc_comments_text parent_name module_list) l)
+ | Enum l -> Enum (List.map (assoc_comments_text parent_name module_list) l)
+ | Newline -> Newline
+ | Block t -> Block (assoc_comments_text parent_name module_list t)
+ | Superscript t -> Superscript (assoc_comments_text parent_name module_list t)
+ | Subscript t -> Subscript (assoc_comments_text parent_name module_list t)
+ | Title (n, l_opt, t) -> Title (n, l_opt, (assoc_comments_text parent_name module_list t))
+ | Link (s, t) -> Link (s, (assoc_comments_text parent_name module_list t))
+ | Ref (initial_name, None, text_option) ->
+ (
+ let rec iter_parent ?parent_name name =
+ let name = Odoc_name.normalize_name name in
+ let res =
+ match get_known_elements name with
+ [] ->
+ (
+ try
+ let re = Str.regexp ("^"^(Str.quote name)^"$") in
+ let t = Odoc_search.find_section module_list re in
+ let v2 = (name, Some (RK_section t)) in
+ add_verified v2 ;
+ (name, Some (RK_section t))
+ with
+ Not_found ->
+ (name, None)
+ )
+ | ele :: _ ->
+ (* we look for the first element with this name *)
+ let (name, kind) =
+ match ele with
+ Odoc_search.Res_module m -> (m.m_name, RK_module)
+ | Odoc_search.Res_module_type mt -> (mt.mt_name, RK_module_type)
+ | Odoc_search.Res_class c -> (c.cl_name, RK_class)
+ | Odoc_search.Res_class_type ct -> (ct.clt_name, RK_class_type)
+ | Odoc_search.Res_value v -> (v.val_name, RK_value)
+ | Odoc_search.Res_type t -> (t.ty_name, RK_type)
+ | Odoc_search.Res_extension x -> (x.xt_name, RK_extension)
+ | Odoc_search.Res_exception e -> (e.ex_name, RK_exception)
+ | Odoc_search.Res_attribute a -> (a.att_value.val_name, RK_attribute)
+ | Odoc_search.Res_method m -> (m.met_value.val_name, RK_method)
+ | Odoc_search.Res_section (_ ,t)-> assert false
+ | Odoc_search.Res_recfield (t, f) ->
+ (Printf.sprintf "%s.%s" t.ty_name f.rf_name, RK_recfield)
+ | Odoc_search.Res_const (t, f) ->
+ (Printf.sprintf "%s.%s" t.ty_name f.vc_name, RK_const)
+ in
+ add_verified (name, Some kind) ;
+ (name, Some kind)
+ in
+ match res with
+ | (name, Some k) -> Ref (name, Some k, text_option)
+ | (_, None) ->
+ match parent_name with
+ None ->
+ Odoc_global.pwarning (Odoc_messages.cross_element_not_found initial_name);
+ Ref (initial_name, None, text_option)
+ | Some p ->
+ let parent_name =
+ match Name.father p with
+ "" -> None
+ | s -> Some s
+ in
+ iter_parent ?parent_name (Name.concat p initial_name)
+ in
+ iter_parent ~parent_name initial_name
+ )
+ | Ref (initial_name, Some kind, text_option) ->
+ (
+ let rec iter_parent ?parent_name name =
+ let v = (name, Some kind) in
+ if was_verified v then
+ Ref (name, Some kind, text_option)
+ else
+ let res =
+ match kind with
+ | RK_section _ ->
+ (
+ (** we just verify that we find an element of this kind with this name *)
+ try
+ let re = Str.regexp ("^"^(Str.quote name)^"$") in
+ let t = Odoc_search.find_section module_list re in
+ let v2 = (name, Some (RK_section t)) in
+ add_verified v2 ;
+ (name, Some (RK_section t))
+ with
+ Not_found ->
+ (name, None)
+ )
+ | _ ->
+ let f =
+ match kind with
+ RK_module -> module_exists
+ | RK_module_type -> module_type_exists
+ | RK_class -> class_exists
+ | RK_class_type -> class_type_exists
+ | RK_value -> value_exists
+ | RK_type -> type_exists
+ | RK_extension -> extension_exists
+ | RK_exception -> exception_exists
+ | RK_attribute -> attribute_exists
+ | RK_method -> method_exists
+ | RK_section _ -> assert false
+ | RK_recfield -> recfield_exists
+ | RK_const -> const_exists
+ in
+ if f name then
+ (
+ add_verified v ;
+ (name, Some kind)
+ )
+ else
+ (name, None)
+ in
+ match res with
+ | (name, Some k) -> Ref (name, Some k, text_option)
+ | (_, None) ->
+ match parent_name with
+ None ->
+ Odoc_global.pwarning (not_found_of_kind kind initial_name);
+ Ref (initial_name, None, text_option)
+ | Some p ->
+ let parent_name =
+ match Name.father p with
+ "" -> None
+ | s -> Some s
+ in
+ iter_parent ?parent_name (Name.concat p initial_name)
+ in
+ iter_parent ~parent_name initial_name
+ )
+ | Module_list l ->
+ Module_list l
+ | Index_list ->
+ Index_list
+ | Custom (s,t) -> Custom (s, (assoc_comments_text parent_name module_list t))
+ | Target (target, code) -> Target (target, code)
+
+and assoc_comments_text parent_name module_list text =
+ List.map (assoc_comments_text_elements parent_name module_list) text
+
+and assoc_comments_info parent_name module_list i =
+ let ft = assoc_comments_text parent_name module_list in
+ {
+ i with
+ i_desc = ao ft i.i_desc ;
+ i_sees = List.map (fun (sr, t) -> (sr, ft t)) i.i_sees;
+ i_deprecated = ao ft i.i_deprecated ;
+ i_params = List.map (fun (name, t) -> (name, ft t)) i.i_params;
+ i_raised_exceptions = List.map (fun (name, t) -> (name, ft t)) i.i_raised_exceptions;
+ i_return_value = ao ft i.i_return_value ;
+ i_custom = List.map (fun (tag, t) -> (tag, ft t)) i.i_custom ;
+ }
+
+
+let rec assoc_comments_module_element parent_name module_list m_ele =
+ match m_ele with
+ Element_module m ->
+ Element_module (assoc_comments_module module_list m)
+ | Element_module_type mt ->
+ Element_module_type (assoc_comments_module_type module_list mt)
+ | Element_included_module _ ->
+ m_ele (* don't go down into the aliases *)
+ | Element_class c ->
+ Element_class (assoc_comments_class module_list c)
+ | Element_class_type ct ->
+ Element_class_type (assoc_comments_class_type module_list ct)
+ | Element_value v ->
+ Element_value (assoc_comments_value module_list v)
+ | Element_type_extension te ->
+ Element_type_extension (assoc_comments_type_extension parent_name module_list te)
+ | Element_exception e ->
+ Element_exception (assoc_comments_exception module_list e)
+ | Element_type t ->
+ Element_type (assoc_comments_type module_list t)
+ | Element_module_comment t ->
+ Element_module_comment (assoc_comments_text parent_name module_list t)
+
+and assoc_comments_class_element parent_name module_list c_ele =
+ match c_ele with
+ Class_attribute a ->
+ Class_attribute (assoc_comments_attribute module_list a)
+ | Class_method m ->
+ Class_method (assoc_comments_method module_list m)
+ | Class_comment t ->
+ Class_comment (assoc_comments_text parent_name module_list t)
+
+and assoc_comments_module_kind parent_name module_list mk =
+ match mk with
+ | Module_struct eles ->
+ Module_struct
+ (List.map (assoc_comments_module_element parent_name module_list) eles)
+ | Module_alias _
+ | Module_functor _ ->
+ mk
+ | Module_apply (mk1, mk2) ->
+ Module_apply (assoc_comments_module_kind parent_name module_list mk1,
+ assoc_comments_module_kind parent_name module_list mk2)
+ | Module_with (mtk, s) ->
+ Module_with (assoc_comments_module_type_kind parent_name module_list mtk, s)
+ | Module_constraint (mk1, mtk) ->
+ Module_constraint
+ (assoc_comments_module_kind parent_name module_list mk1,
+ assoc_comments_module_type_kind parent_name module_list mtk)
+ | Module_typeof _ -> mk
+ | Module_unpack _ -> mk
+
+and assoc_comments_module_type_kind parent_name module_list mtk =
+ match mtk with
+ | Module_type_struct eles ->
+ Module_type_struct
+ (List.map (assoc_comments_module_element parent_name module_list) eles)
+ | Module_type_functor (params, mtk1) ->
+ Module_type_functor
+ (params, assoc_comments_module_type_kind parent_name module_list mtk1)
+ | Module_type_alias _ ->
+ mtk
+ | Module_type_with (mtk1, s) ->
+ Module_type_with
+ (assoc_comments_module_type_kind parent_name module_list mtk1, s)
+ | Module_type_typeof _ -> mtk
+
+and assoc_comments_class_kind parent_name module_list ck =
+ match ck with
+ Class_structure (inher, eles) ->
+ let inher2 =
+ List.map
+ (fun ic ->
+ { ic with
+ ic_text = ao (assoc_comments_text parent_name module_list) ic.ic_text })
+ inher
+ in
+ Class_structure
+ (inher2, List.map (assoc_comments_class_element parent_name module_list) eles)
+
+ | Class_apply _
+ | Class_constr _ -> ck
+ | Class_constraint (ck1, ctk) ->
+ Class_constraint (assoc_comments_class_kind parent_name module_list ck1,
+ assoc_comments_class_type_kind parent_name module_list ctk)
+
+and assoc_comments_class_type_kind parent_name module_list ctk =
+ match ctk with
+ Class_signature (inher, eles) ->
+ let inher2 =
+ List.map
+ (fun ic -> { ic with
+ ic_text = ao (assoc_comments_text parent_name module_list) ic.ic_text })
+ inher
+ in
+ Class_signature (inher2, List.map (assoc_comments_class_element parent_name module_list) eles)
+
+ | Class_type _ -> ctk
+
+
+and assoc_comments_module module_list m =
+ m.m_info <- ao (assoc_comments_info m.m_name module_list) m.m_info ;
+ m.m_kind <- assoc_comments_module_kind m.m_name module_list m.m_kind ;
+ m
+
+and assoc_comments_module_type module_list mt =
+ mt.mt_info <- ao (assoc_comments_info mt.mt_name module_list) mt.mt_info ;
+ mt.mt_kind <- ao (assoc_comments_module_type_kind mt.mt_name module_list) mt.mt_kind ;
+ mt
+
+and assoc_comments_class module_list c =
+ c.cl_info <- ao (assoc_comments_info c.cl_name module_list) c.cl_info ;
+ c.cl_kind <- assoc_comments_class_kind c.cl_name module_list c.cl_kind ;
+ assoc_comments_parameter_list c.cl_name module_list c.cl_parameters;
+ c
+
+and assoc_comments_class_type module_list ct =
+ ct.clt_info <- ao (assoc_comments_info ct.clt_name module_list) ct.clt_info ;
+ ct.clt_kind <- assoc_comments_class_type_kind ct.clt_name module_list ct.clt_kind ;
+ ct
+
+and assoc_comments_parameter parent_name module_list p =
+ match p with
+ Simple_name sn ->
+ sn.sn_text <- ao (assoc_comments_text parent_name module_list) sn.sn_text
+ | Tuple (l, t) ->
+ List.iter (assoc_comments_parameter parent_name module_list) l
+
+and assoc_comments_parameter_list parent_name module_list pl =
+ List.iter (assoc_comments_parameter parent_name module_list) pl
+
+and assoc_comments_value module_list v =
+ let parent = Name.father v.val_name in
+ v.val_info <- ao (assoc_comments_info parent module_list) v.val_info ;
+ assoc_comments_parameter_list parent module_list v.val_parameters;
+ v
+
+and assoc_comments_extension_constructor module_list x =
+ let parent = Name.father x.xt_name in
+ x.xt_text <- ao (assoc_comments_info parent module_list) x.xt_text
+
+and assoc_comments_type_extension parent_name module_list te =
+ te.te_info <- ao (assoc_comments_info parent_name module_list) te.te_info;
+ List.iter (assoc_comments_extension_constructor module_list) te.te_constructors;
+ te
+
+and assoc_comments_exception module_list e =
+ let parent = Name.father e.ex_name in
+ e.ex_info <- ao (assoc_comments_info parent module_list) e.ex_info ;
+ e
+
+and assoc_comments_type module_list t =
+ let parent = Name.father t.ty_name in
+ t.ty_info <- ao (assoc_comments_info parent module_list) t.ty_info ;
+ (match t.ty_kind with
+ Type_abstract -> ()
+ | Type_variant vl ->
+ List.iter
+ (fun vc -> vc.vc_text <- ao (assoc_comments_info parent module_list) vc.vc_text)
+ vl
+ | Type_record fl ->
+ List.iter
+ (fun rf -> rf.rf_text <- ao (assoc_comments_info parent module_list) rf.rf_text)
+ fl
+ | Type_open -> ()
+ );
+ t
+
+and assoc_comments_attribute module_list a =
+ let _ = assoc_comments_value module_list a.att_value in
+ a
+
+and assoc_comments_method module_list m =
+ let parent_name = Name.father m.met_value.val_name in
+ let _ = assoc_comments_value module_list m.met_value in
+ assoc_comments_parameter_list parent_name module_list m.met_value.val_parameters;
+ m
+
+
+let associate_type_of_elements_in_comments module_list =
+ List.map (assoc_comments_module module_list) module_list
+
+
+(***********************************************************)
+(** The function which performs all the cross referencing. *)
+let associate module_list =
+ get_alias_names module_list ;
+ init_known_elements_map module_list;
+ let rec remove_doubles acc = function
+ [] -> acc
+ | h :: q ->
+ if List.mem h acc then remove_doubles acc q
+ else remove_doubles (h :: acc) q
+ in
+ let rec iter incomplete_modules =
+ let (b_modif, remaining_inc_modules, acc_names_not_found) =
+ List.fold_left (associate_in_module module_list) (false, [], []) incomplete_modules
+ in
+ let remaining_no_doubles = remove_doubles [] remaining_inc_modules in
+ let remaining_modules = List.filter
+ (fun m -> List.mem m.m_name remaining_no_doubles)
+ incomplete_modules
+ in
+ if b_modif then
+ (* we may be able to associate something else *)
+ iter remaining_modules
+ else
+ (* nothing changed, we won't be able to associate any more *)
+ acc_names_not_found
+ in
+ let names_not_found = iter module_list in
+ (
+ match names_not_found with
+ [] ->
+ ()
+ | l ->
+ List.iter
+ (fun nf ->
+ Odoc_global.pwarning
+ (
+ match nf with
+ NF_m n -> Odoc_messages.cross_module_not_found n
+ | NF_mt n -> Odoc_messages.cross_module_type_not_found n
+ | NF_mmt n -> Odoc_messages.cross_module_or_module_type_not_found n
+ | NF_c n -> Odoc_messages.cross_class_not_found n
+ | NF_ct n -> Odoc_messages.cross_class_type_not_found n
+ | NF_cct n -> Odoc_messages.cross_class_or_class_type_not_found n
+ | NF_xt n -> Odoc_messages.cross_extension_not_found n
+ | NF_ex n -> Odoc_messages.cross_exception_not_found n
+ );
+ )
+ l
+ ) ;
+
+ (* Find a type for each name of element which is referenced in comments. *)
+ ignore (associate_type_of_elements_in_comments module_list)
diff --git a/ocamldoc/odoc_cross.mli b/ocamldoc/odoc_cross.mli
new file mode 100644
index 0000000000..57fff65784
--- /dev/null
+++ b/ocamldoc/odoc_cross.mli
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Cross-referencing. *)
+
+val associate : Odoc_module.t_module list -> unit
+
+val assoc_comments_info :
+ string -> Odoc_module.t_module list ->
+ Odoc_types.info -> Odoc_types.info
diff --git a/ocamldoc/odoc_dag2html.ml b/ocamldoc/odoc_dag2html.ml
new file mode 100644
index 0000000000..74119e6e8b
--- /dev/null
+++ b/ocamldoc/odoc_dag2html.ml
@@ -0,0 +1,1749 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The types and functions to create a html table representing a dag. Thanks to Daniel De Rauglaudre. *)
+
+type 'a dag = { mutable dag : 'a node array }
+and 'a node =
+ { mutable pare : idag list; valu : 'a; mutable chil : idag list }
+and idag = int
+;;
+
+external int_of_idag : idag -> int = "%identity";;
+external idag_of_int : int -> idag = "%identity";;
+
+type 'a table = { mutable table : 'a data array array }
+and 'a data = { mutable elem : 'a elem; mutable span : span_id }
+and 'a elem = Elem of 'a | Ghost of ghost_id | Nothing
+and span_id
+and ghost_id
+;;
+
+external span_id_of_int : int -> span_id = "%identity";;
+external int_of_span_id : span_id -> int = "%identity";;
+external ghost_id_of_int : int -> ghost_id = "%identity";;
+external int_of_ghost_id : ghost_id -> int = "%identity";;
+
+let new_span_id = let i = ref 0 in fun () -> incr i; span_id_of_int !i;;
+
+let new_ghost_id = let i = ref 0 in fun () -> incr i; ghost_id_of_int !i;;
+
+(** creating the html table structure *)
+
+type align = LeftA | CenterA | RightA;;
+type table_data = TDstring of string | TDhr of align;;
+type html_table = (int * align * table_data) array array;;
+
+let html_table_struct indi_txt phony d t =
+ let phony =
+ function
+ Elem e -> phony d.dag.(int_of_idag e)
+ | Ghost _ -> false
+ | Nothing -> true
+ in
+ let elem_txt =
+ function
+ Elem e -> indi_txt d.dag.(int_of_idag e)
+ | Ghost _ -> "|"
+ | Nothing -> "&nbsp;"
+ in
+ let bar_txt =
+ function
+ Elem _ | Ghost _ -> "|"
+ | Nothing -> "&nbsp;"
+ in
+ let all_empty i =
+ let rec loop j =
+ if j = Array.length t.table.(i) then true
+ else
+ match t.table.(i).(j).elem with
+ Nothing -> loop (j + 1)
+ | e -> if phony e then loop (j + 1) else false
+ in
+ loop 0
+ in
+ let line_elem_txt i =
+ let les =
+ let rec loop les j =
+ if j = Array.length t.table.(i) then les
+ else
+ let x = t.table.(i).(j) in
+ let next_j =
+ let rec loop j =
+ if j = Array.length t.table.(i) then j
+ else if t.table.(i).(j) = x then loop (j + 1)
+ else j
+ in
+ loop (j + 1)
+ in
+ let colspan = 3 * (next_j - j) in
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in
+ let les =
+ let s =
+ if t.table.(i).(j).elem = Nothing then "&nbsp;"
+ else elem_txt t.table.(i).(j).elem
+ in
+ (colspan - 2, CenterA, TDstring s) :: les
+ in
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in loop les next_j
+ in
+ loop [] 0
+ in
+ Array.of_list (List.rev les)
+ in
+ let vbars_txt k i =
+ let les =
+ let rec loop les j =
+ if j = Array.length t.table.(i) then les
+ else
+ let x = t.table.(i).(j) in
+ let next_j =
+ let rec loop j =
+ if j = Array.length t.table.(i) then j
+ else if t.table.(i).(j) = x then loop (j + 1)
+ else j
+ in
+ loop (j + 1)
+ in
+ let colspan = 3 * (next_j - j) in
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in
+ let les =
+ let s =
+ if k > 0 && t.table.(k - 1).(j).elem = Nothing ||
+ t.table.(k).(j).elem = Nothing then
+ "&nbsp;"
+ else if phony t.table.(i).(j).elem then "&nbsp;"
+ else bar_txt t.table.(i).(j).elem
+ in
+ (colspan - 2, CenterA, TDstring s) :: les
+ in
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in loop les next_j
+ in
+ loop [] 0
+ in
+ Array.of_list (List.rev les)
+ in
+ let alone_bar_txt i =
+ let les =
+ let rec loop les j =
+ if j = Array.length t.table.(i) then les
+ else
+ let next_j =
+ let x = t.table.(i).(j).span in
+ let rec loop j =
+ if j = Array.length t.table.(i) then j
+ else if t.table.(i).(j).span = x then loop (j + 1)
+ else j
+ in
+ loop (j + 1)
+ in
+ let colspan = 3 * (next_j - j) - 2 in
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in
+ let les =
+ if t.table.(i).(j).elem = Nothing ||
+ t.table.(i + 1).(j).elem = Nothing then
+ (colspan, LeftA, TDstring "&nbsp;") :: les
+ else
+ let s =
+ let all_ph =
+ let rec loop j =
+ if j = next_j then true
+ else if phony t.table.(i + 1).(j).elem then loop (j + 1)
+ else false
+ in
+ loop j
+ in
+ if all_ph then "&nbsp;" else "|"
+ in
+ (colspan, CenterA, TDstring s) :: les
+ in
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in loop les next_j
+ in
+ loop [] 0
+ in
+ Array.of_list (List.rev les)
+ in
+ let exist_several_branches i k =
+ let rec loop j =
+ if j = Array.length t.table.(i) then false
+ else
+ let x = t.table.(i).(j).span in
+ let e = t.table.(k).(j).elem in
+ let rec loop1 j =
+ if j = Array.length t.table.(i) then false
+ else if t.table.(i).(j).elem = Nothing then loop j
+ else if t.table.(i).(j).span <> x then loop j
+ else if t.table.(k).(j).elem <> e then true
+ else loop1 (j + 1)
+ in
+ loop1 (j + 1)
+ in
+ loop 0
+ in
+ let hbars_txt i k =
+ let les =
+ let rec loop les j =
+ if j = Array.length t.table.(i) then les
+ else
+ let next_j =
+ let e = t.table.(i).(j).elem in
+ let x = t.table.(i).(j).span in
+ let rec loop j =
+ if j = Array.length t.table.(i) then j
+ else if e = Nothing && t.table.(i).(j).elem = Nothing then
+ loop (j + 1)
+ else if t.table.(i).(j).span = x then loop (j + 1)
+ else j
+ in
+ loop (j + 1)
+ in
+ let rec loop1 les l =
+ if l = next_j then loop les next_j
+ else
+ let next_l =
+ let y = t.table.(k).(l) in
+ match y.elem with
+ Elem _ | Ghost _ ->
+ let rec loop l =
+ if l = Array.length t.table.(i) then l
+ else if t.table.(k).(l) = y then loop (l + 1)
+ else l
+ in
+ loop (l + 1)
+ | _ -> l + 1
+ in
+ if next_l > next_j then
+ begin
+ Printf.eprintf
+ "assert false i %d k %d l %d next_l %d next_j %d\n" i k l
+ next_l next_j;
+ flush stderr
+ end;
+ let next_l = min next_l next_j in
+ let colspan = 3 * (next_l - l) - 2 in
+ let les =
+ match t.table.(i).(l).elem, t.table.(i + 1).(l).elem with
+ Nothing, _ | _, Nothing ->
+ (colspan + 2, LeftA, TDstring "&nbsp;") :: les
+ | _ ->
+ let ph s =
+ if phony t.table.(k).(l).elem then TDstring "&nbsp;"
+ else s
+ in
+ if l = j && next_l = next_j then
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in
+ let s = ph (TDstring "|") in
+ let les = (colspan, CenterA, s) :: les in
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in les
+ else if l = j then
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in
+ let s = ph (TDhr RightA) in
+ let les = (colspan, RightA, s) :: les in
+ let s = ph (TDhr CenterA) in
+ let les = (1, LeftA, s) :: les in les
+ else if next_l = next_j then
+ let s = ph (TDhr CenterA) in
+ let les = (1, LeftA, s) :: les in
+ let s = ph (TDhr LeftA) in
+ let les = (colspan, LeftA, s) :: les in
+ let les = (1, LeftA, TDstring "&nbsp;") :: les in les
+ else
+ let s = ph (TDhr CenterA) in
+ (colspan + 2, LeftA, s) :: les
+ in
+ loop1 les next_l
+ in
+ loop1 les j
+ in
+ loop [] 0
+ in
+ Array.of_list (List.rev les)
+ in
+ let hts =
+ let rec loop hts i =
+ if i = Array.length t.table then hts
+ else if i = Array.length t.table - 1 && all_empty i then hts
+ else
+ let hts = line_elem_txt i :: hts in
+ let hts =
+ if i < Array.length t.table - 1 then
+ let hts = vbars_txt (i + 1) i :: hts in
+ let hts =
+ if exist_several_branches i i then
+ alone_bar_txt i :: hbars_txt i i :: hts
+ else hts
+ in
+ let hts =
+ if exist_several_branches i (i + 1) &&
+ (i < Array.length t.table - 2 ||
+ not (all_empty (i + 1))) then
+ vbars_txt (i + 1) (i + 1) :: hbars_txt i (i + 1) :: hts
+ else hts
+ in
+ hts
+ else hts
+ in
+ loop hts (i + 1)
+ in
+ loop [] 0
+ in
+ Array.of_list (List.rev hts)
+;;
+
+(** transforming dag into table *)
+
+let ancestors d =
+ let rec loop i =
+ if i = Array.length d.dag then []
+ else
+ let n = d.dag.(i) in
+ if n.pare = [] then idag_of_int i :: loop (i + 1) else loop (i + 1)
+ in
+ loop 0
+;;
+
+let get_children d parents =
+ let rec merge_children children el =
+ List.fold_right
+ (fun (x, _) children ->
+ match x with
+ Elem e ->
+ let e = d.dag.(int_of_idag e) in
+ List.fold_right
+ (fun c children ->
+ if List.mem c children then children else c :: children)
+ e.chil children
+ | _ -> [])
+ el children
+ in
+ merge_children [] parents
+;;
+
+let rec get_block t i j =
+ if j = Array.length t.table.(i) then None
+ else if j = Array.length t.table.(i) - 1 then
+ let x = t.table.(i).(j) in Some ([x.elem, 1], 1, x.span)
+ else
+ let x = t.table.(i).(j) in
+ let y = t.table.(i).(j + 1) in
+ if y.span = x.span then
+ match get_block t i (j + 1) with
+ Some ((x1, c1) :: list, mpc, span) ->
+ let (list, mpc) =
+ if x1 = x.elem then (x1, c1 + 1) :: list, max mpc (c1 + 1)
+ else (x.elem, 1) :: (x1, c1) :: list, max mpc c1
+ in
+ Some (list, mpc, span)
+ | _ -> assert false
+ else Some ([x.elem, 1], 1, x.span)
+;;
+
+let group_by_common_children d list =
+ let module O = struct type t = idag;; let compare (x:t) y = compare x y;; end
+ in
+ let module S = Set.Make (O)
+ in
+ let nlcsl =
+ List.map
+ (fun id ->
+ let n = d.dag.(int_of_idag id) in
+ let cs = List.fold_right S.add n.chil S.empty in [id], cs)
+ list
+ in
+ let nlcsl =
+ let rec loop =
+ function
+ [] -> []
+ | (nl, cs) :: rest ->
+ let rec loop1 beg =
+ function
+ (nl1, cs1) :: rest1 ->
+ if S.is_empty (S.inter cs cs1) then
+ loop1 ((nl1, cs1) :: beg) rest1
+ else
+ loop ((nl @ nl1, S.union cs cs1) :: (List.rev beg @ rest1))
+ | [] -> (nl, cs) :: loop rest
+ in
+ loop1 [] rest
+ in
+ loop nlcsl
+ in
+ List.fold_right
+ (fun (nl, _) a ->
+ let span = new_span_id () in
+ List.fold_right (fun n a -> {elem = Elem n; span = span} :: a) nl a)
+ nlcsl []
+;;
+
+let copy_data d = {elem = d.elem; span = d.span};;
+
+let insert_columns t nb j =
+ let t1 = Array.make (Array.length t.table) [| |] in
+ for i = 0 to Array.length t.table - 1 do
+ let line = t.table.(i) in
+ let line1 = Array.make (Array.length line + nb) line.(0) in
+ t1.(i) <- line1;
+ let rec loop k =
+ if k = Array.length line then ()
+ else
+ begin
+ if k < j then line1.(k) <- copy_data line.(k)
+ else if k = j then
+ for r = 0 to nb do line1.(k + r) <- copy_data line.(k) done
+ else line1.(k + nb) <- copy_data line.(k);
+ loop (k + 1)
+ end
+ in
+ loop 0
+ done;
+ {table = t1}
+;;
+
+let rec gcd a b =
+ if a < b then gcd b a else if b = 0 then a else gcd b (a mod b)
+;;
+
+let treat_new_row d t =
+ let i = Array.length t.table - 1 in
+ let rec loop t i j =
+ match get_block t i j with
+ Some (parents, max_parent_colspan, span) ->
+ let children = get_children d parents in
+ let children =
+ if children = [] then [{elem = Nothing; span = new_span_id ()}]
+ else
+ List.map (fun n -> {elem = Elem n; span = new_span_id ()})
+ children
+ in
+ let simple_parents_colspan =
+ List.fold_left (fun x (_, c) -> x + c) 0 parents
+ in
+ if simple_parents_colspan mod List.length children = 0 then
+ let j = j + simple_parents_colspan in
+ let children =
+ let cnt = simple_parents_colspan / List.length children in
+ List.fold_right
+ (fun d list ->
+ let rec loop cnt list =
+ if cnt = 1 then d :: list
+ else copy_data d :: loop (cnt - 1) list
+ in
+ loop cnt list)
+ children []
+ in
+ let (t, children_rest) = loop t i j in t, children @ children_rest
+ else
+ let parent_colspan =
+ List.fold_left
+ (fun scm (_, c) -> let g = gcd scm c in scm / g * c)
+ max_parent_colspan parents
+ in
+ let (t, parents, _) =
+ List.fold_left
+ (fun (t, parents, j) (x, c) ->
+ let to_add = parent_colspan / c - 1 in
+ let t =
+ let rec loop cc t j =
+ if cc = 0 then t
+ else
+ let t = insert_columns t to_add j in
+ loop (cc - 1) t (j + to_add + 1)
+ in
+ loop c t j
+ in
+ t, (x, parent_colspan) :: parents, j + parent_colspan)
+ (t, [], j) parents
+ in
+ let parents = List.rev parents in
+ let parents_colspan = parent_colspan * List.length parents in
+ let children_colspan = List.length children in
+ let g = gcd parents_colspan children_colspan in
+ let (t, j) =
+ let cnt = children_colspan / g in
+ List.fold_left
+ (fun (t, j) (_, c) ->
+ let rec loop cc t j =
+ if cc = 0 then t, j
+ else
+ let t = insert_columns t (cnt - 1) j in
+ let j = j + cnt in loop (cc - 1) t j
+ in
+ loop c t j)
+ (t, j) parents
+ in
+ let children =
+ let cnt = parents_colspan / g in
+ List.fold_right
+ (fun d list ->
+ let rec loop cnt list =
+ if cnt = 0 then list else d :: loop (cnt - 1) list
+ in
+ loop cnt list)
+ children []
+ in
+ let (t, children_rest) = loop t i j in t, children @ children_rest
+ | None -> t, []
+ in
+ loop t i 0
+;;
+
+let down_it t i k y =
+ t.table.(Array.length t.table - 1).(k) <- t.table.(i).(k);
+ for r = i to Array.length t.table - 2 do
+ t.table.(r).(k) <- {elem = Ghost (new_ghost_id ()); span = new_span_id ()}
+ done
+;;
+
+(* equilibrate:
+ in the last line, for all elem A, make fall all As, which are located at
+ its right side above, to its line,
+ A |
+ i.e. transform all . into |
+ A....... A......A
+*)
+
+let equilibrate t =
+ let ilast = Array.length t.table - 1 in
+ let last = t.table.(ilast) in
+ let len = Array.length last in
+ let rec loop j =
+ if j = len then ()
+ else
+ match last.(j).elem with
+ Elem x ->
+ let rec loop1 i =
+ if i = ilast then loop (j + 1)
+ else
+ let rec loop2 k =
+ if k = len then loop1 (i + 1)
+ else
+ match t.table.(i).(k).elem with
+ Elem y when x = y -> down_it t i k y; loop 0
+ | _ -> loop2 (k + 1)
+ in
+ loop2 0
+ in
+ loop1 0
+ | _ -> loop (j + 1)
+ in
+ loop 0
+;;
+
+(* group_elem:
+ transform all x y into x x
+ A A A A *)
+
+let group_elem t =
+ for i = 0 to Array.length t.table - 2 do
+ for j = 1 to Array.length t.table.(0) - 1 do
+ match t.table.(i + 1).(j - 1).elem, t.table.(i + 1).(j).elem with
+ Elem x, Elem y when x = y ->
+ t.table.(i).(j).span <- t.table.(i).(j - 1).span
+ | _ -> ()
+ done
+ done
+;;
+
+(* group_ghost:
+ x x x x |a |a |a |a
+ transform all |a |b into |a |a and all x y into x x
+ y z y y A A A A *)
+
+let group_ghost t =
+ for i = 0 to Array.length t.table - 2 do
+ for j = 1 to Array.length t.table.(0) - 1 do
+ begin match t.table.(i + 1).(j - 1).elem, t.table.(i + 1).(j).elem with
+ Ghost x, Ghost _ ->
+ if t.table.(i).(j - 1).span = t.table.(i).(j).span then
+ t.table.(i + 1).(j) <-
+ {elem = Ghost x; span = t.table.(i + 1).(j - 1).span}
+ | _ -> ()
+ end;
+ match t.table.(i).(j - 1).elem, t.table.(i).(j).elem with
+ Ghost x, Ghost _ ->
+ if t.table.(i + 1).(j - 1).elem = t.table.(i + 1).(j).elem then
+ begin
+ t.table.(i).(j) <-
+ {elem = Ghost x; span = t.table.(i).(j - 1).span};
+ if i > 0 then
+ t.table.(i - 1).(j).span <- t.table.(i - 1).(j - 1).span
+ end
+ | _ -> ()
+ done
+ done
+;;
+
+(* group_children:
+ transform all A A into A A
+ x y x x *)
+
+let group_children t =
+ for i = 0 to Array.length t.table - 1 do
+ let line = t.table.(i) in
+ let len = Array.length line in
+ for j = 1 to len - 1 do
+ if line.(j).elem = line.(j - 1).elem && line.(j).elem <> Nothing then
+ line.(j).span <- line.(j - 1).span
+ done
+ done
+;;
+
+(* group_span_by_common_children:
+ in the last line, transform all
+ A B into A B
+ x y x x
+ if A and B have common children *)
+
+let group_span_by_common_children d t =
+ let module O = struct type t = idag;; let compare (x:t) y = compare x y;; end
+ in
+ let module S = Set.Make (O)
+ in
+ let i = Array.length t.table - 1 in
+ let line = t.table.(i) in
+ let rec loop j cs =
+ if j = Array.length line then ()
+ else
+ match line.(j).elem with
+ Elem id ->
+ let n = d.dag.(int_of_idag id) in
+ let curr_cs = List.fold_right S.add n.chil S.empty in
+ if S.is_empty (S.inter cs curr_cs) then loop (j + 1) curr_cs
+ else
+ begin
+ line.(j).span <- line.(j - 1).span;
+ loop (j + 1) (S.union cs curr_cs)
+ end
+ | _ -> loop (j + 1) S.empty
+ in
+ loop 0 S.empty
+;;
+
+let find_same_parents t i j1 j2 j3 j4 =
+ let rec loop i j1 j2 j3 j4 =
+ if i = 0 then i, j1, j2, j3, j4
+ else
+ let x1 = t.(i - 1).(j1) in
+ let x2 = t.(i - 1).(j2) in
+ let x3 = t.(i - 1).(j3) in
+ let x4 = t.(i - 1).(j4) in
+ if x1.span = x4.span then i, j1, j2, j3, j4
+ else
+ let j1 =
+ let rec loop j =
+ if j < 0 then 0
+ else if t.(i - 1).(j).span = x1.span then loop (j - 1)
+ else j + 1
+ in
+ loop (j1 - 1)
+ in
+ let j2 =
+ let rec loop j =
+ if j >= Array.length t.(i) then j - 1
+ else if t.(i - 1).(j).span = x2.span then loop (j + 1)
+ else j - 1
+ in
+ loop (j2 + 1)
+ in
+ let j3 =
+ let rec loop j =
+ if j < 0 then 0
+ else if t.(i - 1).(j).span = x3.span then loop (j - 1)
+ else j + 1
+ in
+ loop (j3 - 1)
+ in
+ let j4 =
+ let rec loop j =
+ if j >= Array.length t.(i) then j - 1
+ else if t.(i - 1).(j).span = x4.span then loop (j + 1)
+ else j - 1
+ in
+ loop (j4 + 1)
+ in
+ loop (i - 1) j1 j2 j3 j4
+ in
+ loop i j1 j2 j3 j4
+;;
+
+let find_linked_children t i j1 j2 j3 j4 =
+ let rec loop i j1 j2 j3 j4 =
+ if i = Array.length t - 1 then j1, j2, j3, j4
+ else
+ let x1 = t.(i).(j1) in
+ let x2 = t.(i).(j2) in
+ let x3 = t.(i).(j3) in
+ let x4 = t.(i).(j4) in
+ let j1 =
+ let rec loop j =
+ if j < 0 then 0
+ else if t.(i).(j).span = x1.span then loop (j - 1)
+ else j + 1
+ in
+ loop (j1 - 1)
+ in
+ let j2 =
+ let rec loop j =
+ if j >= Array.length t.(i) then j - 1
+ else if t.(i).(j).span = x2.span then loop (j + 1)
+ else j - 1
+ in
+ loop (j2 + 1)
+ in
+ let j3 =
+ let rec loop j =
+ if j < 0 then 0
+ else if t.(i).(j).span = x3.span then loop (j - 1)
+ else j + 1
+ in
+ loop (j3 - 1)
+ in
+ let j4 =
+ let rec loop j =
+ if j >= Array.length t.(i) then j - 1
+ else if t.(i).(j).span = x4.span then loop (j + 1)
+ else j - 1
+ in
+ loop (j4 + 1)
+ in
+ loop (i + 1) j1 j2 j3 j4
+ in
+ loop i j1 j2 j3 j4
+;;
+
+let mirror_block t i1 i2 j1 j2 =
+ for i = i1 to i2 do
+ let line = t.(i) in
+ let rec loop j1 j2 =
+ if j1 >= j2 then ()
+ else
+ let v = line.(j1) in
+ line.(j1) <- line.(j2); line.(j2) <- v; loop (j1 + 1) (j2 - 1)
+ in
+ loop j1 j2
+ done
+;;
+
+let exch_blocks t i1 i2 j1 j2 j3 j4 =
+ for i = i1 to i2 do
+ let line = t.(i) in
+ let saved = Array.copy line in
+ for j = j1 to j2 do line.(j4 - j2 + j) <- saved.(j) done;
+ for j = j3 to j4 do line.(j1 - j3 + j) <- saved.(j) done
+ done
+;;
+
+let find_block_with_parents t i jj1 jj2 jj3 jj4 =
+ let rec loop ii jj1 jj2 jj3 jj4 =
+ let (nii, njj1, njj2, njj3, njj4) =
+ find_same_parents t i jj1 jj2 jj3 jj4
+ in
+ if nii <> ii || njj1 <> jj1 || njj2 <> jj2 || njj3 <> jj3 ||
+ njj4 <> jj4 then
+ let nii = min ii nii in
+ let (jj1, jj2, jj3, jj4) =
+ find_linked_children t nii njj1 njj2 njj3 njj4
+ in
+ if njj1 <> jj1 || njj2 <> jj2 || njj3 <> jj3 || njj4 <> jj4 then
+ loop nii jj1 jj2 jj3 jj4
+ else nii, jj1, jj2, jj3, jj4
+ else ii, jj1, jj2, jj3, jj4
+ in
+ loop i jj1 jj2 jj3 jj4
+;;
+
+let push_to_right d t i j1 j2 =
+ let line = t.(i) in
+ let rec loop j =
+ if j = j2 then j - 1
+ else
+ let ini_jj1 =
+ match line.(j - 1).elem with
+ Nothing -> j - 1
+ | x ->
+ let rec same_value j =
+ if j < 0 then 0
+ else if line.(j).elem = x then same_value (j - 1)
+ else j + 1
+ in
+ same_value (j - 2)
+ in
+ let jj1 = ini_jj1 in
+ let jj2 = j - 1 in
+ let jj3 = j in
+ let jj4 =
+ match line.(j).elem with
+ Nothing -> j
+ | x ->
+ let rec same_value j =
+ if j >= Array.length line then j - 1
+ else if line.(j).elem = x then same_value (j + 1)
+ else j - 1
+ in
+ same_value (j + 1)
+ in
+ let (ii, jj1, jj2, jj3, jj4) =
+ find_block_with_parents t i jj1 jj2 jj3 jj4
+ in
+ if jj4 < j2 && jj2 < jj3 then
+ begin exch_blocks t ii i jj1 jj2 jj3 jj4; loop (jj4 + 1) end
+ else if jj4 < j2 && jj1 = ini_jj1 && jj2 <= jj4 then
+ begin mirror_block t ii i jj1 jj4; loop (jj4 + 1) end
+ else j - 1
+ in
+ loop (j1 + 1)
+;;
+
+let push_to_left d t i j1 j2 =
+ let line = t.(i) in
+ let rec loop j =
+ if j = j1 then j + 1
+ else
+ let jj1 =
+ match line.(j).elem with
+ Nothing -> j
+ | x ->
+ let rec same_value j =
+ if j < 0 then 0
+ else if line.(j).elem = x then same_value (j - 1)
+ else j + 1
+ in
+ same_value (j - 1)
+ in
+ let jj2 = j in
+ let jj3 = j + 1 in
+ let ini_jj4 =
+ match line.(j + 1).elem with
+ Nothing -> j + 1
+ | x ->
+ let rec same_value j =
+ if j >= Array.length line then j - 1
+ else if line.(j).elem = x then same_value (j + 1)
+ else j - 1
+ in
+ same_value (j + 2)
+ in
+ let jj4 = ini_jj4 in
+ let (ii, jj1, jj2, jj3, jj4) =
+ find_block_with_parents t i jj1 jj2 jj3 jj4
+ in
+ if jj1 > j1 && jj2 < jj3 then
+ begin exch_blocks t ii i jj1 jj2 jj3 jj4; loop (jj1 - 1) end
+ else if jj1 > j1 && jj4 = ini_jj4 && jj3 >= jj1 then
+ begin mirror_block t ii i jj1 jj4; loop (jj1 - 1) end
+ else j + 1
+ in
+ loop (j2 - 1)
+;;
+
+let fill_gap d t i j1 j2 =
+ let t1 =
+ let t1 = Array.copy t.table in
+ for i = 0 to Array.length t.table - 1 do
+ t1.(i) <- Array.copy t.table.(i);
+ for j = 0 to Array.length t1.(i) - 1 do
+ t1.(i).(j) <- copy_data t.table.(i).(j)
+ done
+ done;
+ t1
+ in
+ let j2 = push_to_left d t1 i j1 j2 in
+ let j1 = push_to_right d t1 i j1 j2 in
+ if j1 = j2 - 1 then
+ let line = t1.(i - 1) in
+ let x = line.(j1).span in
+ let y = line.(j2).span in
+ let rec loop y j =
+ if j >= Array.length line then ()
+ else if line.(j).span = y || t1.(i).(j).elem = t1.(i).(j - 1).elem then
+ let y = line.(j).span in
+ line.(j).span <- x;
+ if i > 0 then t1.(i - 1).(j).span <- t1.(i - 1).(j - 1).span;
+ loop y (j + 1)
+ in
+ loop y j2; Some ({table = t1}, true)
+ else None
+;;
+
+let treat_gaps d t =
+ let i = Array.length t.table - 1 in
+ let rec loop t j =
+ let line = t.table.(i) in
+ if j = Array.length line then t
+ else
+ match line.(j).elem with
+ Elem _ as y ->
+ if y = line.(j - 1).elem then loop t (j + 1)
+ else
+ let rec loop1 t j1 =
+ if j1 < 0 then loop t (j + 1)
+ else if y = line.(j1).elem then
+ match fill_gap d t i j1 j with
+ Some (t, ok) -> if ok then loop t 2 else loop t (j + 1)
+ | None -> loop t (j + 1)
+ else loop1 t (j1 - 1)
+ in
+ loop1 t (j - 2)
+ | _ -> loop t (j + 1)
+ in
+ if Array.length t.table.(i) = 1 then t else loop t 2
+;;
+
+let group_span_last_row t =
+ let row = t.table.(Array.length t.table - 1) in
+ let rec loop i =
+ if i >= Array.length row then ()
+ else
+ begin
+ begin match row.(i).elem with
+ Elem _ | Ghost _ as x ->
+ if x = row.(i - 1).elem then row.(i).span <- row.(i - 1).span
+ | _ -> ()
+ end;
+ loop (i + 1)
+ end
+ in
+ loop 1
+;;
+
+let has_phony_children phony d t =
+ let line = t.table.(Array.length t.table - 1) in
+ let rec loop j =
+ if j = Array.length line then false
+ else
+ match line.(j).elem with
+ Elem x -> if phony d.dag.(int_of_idag x) then true else loop (j + 1)
+ | _ -> loop (j + 1)
+ in
+ loop 0
+;;
+
+let tablify phony no_optim no_group d =
+ let a = ancestors d in
+ let r = group_by_common_children d a in
+ let t = {table = [| Array.of_list r |]} in
+ let rec loop t =
+ let (t, new_row) = treat_new_row d t in
+ if List.for_all (fun x -> x.elem = Nothing) new_row then t
+ else
+ let t = {table = Array.append t.table [| Array.of_list new_row |]} in
+ let t =
+ if no_group && not (has_phony_children phony d t) then t
+ else
+ let _ = if no_optim then () else equilibrate t in
+ let _ = group_elem t in
+ let _ = group_ghost t in
+ let _ = group_children t in
+ let _ = group_span_by_common_children d t in
+ let t = if no_optim then t else treat_gaps d t in
+ let _ = group_span_last_row t in t
+ in
+ loop t
+ in
+ loop t
+;;
+
+let fall d t =
+ for i = 1 to Array.length t.table - 1 do
+ let line = t.table.(i) in
+ let rec loop j =
+ if j = Array.length line then ()
+ else
+ match line.(j).elem with
+ Ghost x ->
+ let j2 =
+ let rec loop j =
+ if j = Array.length line then j - 1
+ else
+ match line.(j).elem with
+ Ghost y when y = x -> loop (j + 1)
+ | _ -> j - 1
+ in
+ loop (j + 1)
+ in
+ let i1 =
+ let rec loop i =
+ if i < 0 then i + 1
+ else
+ let line = t.table.(i) in
+ if (j = 0 || line.(j - 1).span <> line.(j).span) &&
+ (j2 = Array.length line - 1 ||
+ line.(j2 + 1).span <> line.(j2).span) then
+ loop (i - 1)
+ else i + 1
+ in
+ loop (i - 1)
+ in
+ let i1 =
+ if i1 = i then i1
+ else if i1 = 0 then i1
+ else if t.table.(i1).(j).elem = Nothing then i1
+ else i
+ in
+ if i1 < i then
+ begin
+ for k = i downto i1 + 1 do
+ for j = j to j2 do
+ t.table.(k).(j).elem <- t.table.(k - 1).(j).elem;
+ if k < i then
+ t.table.(k).(j).span <- t.table.(k - 1).(j).span
+ done
+ done;
+ for l = j to j2 do
+ if i1 = 0 || t.table.(i1 - 1).(l).elem = Nothing then
+ t.table.(i1).(l).elem <- Nothing
+ else
+ t.table.(i1).(l) <-
+ if l = j ||
+ t.table.(i1 - 1).(l - 1).span <>
+ t.table.(i1 - 1).(l).span then
+ {elem = Ghost (new_ghost_id ());
+ span = new_span_id ()}
+ else copy_data t.table.(i1).(l - 1)
+ done
+ end;
+ loop (j2 + 1)
+ | _ -> loop (j + 1)
+ in
+ loop 0
+ done
+;;
+
+let fall2_cool_right t i1 i2 i3 j1 j2 =
+ let span = t.table.(i2 - 1).(j1).span in
+ for i = i2 - 1 downto 0 do
+ for j = j1 to j2 - 1 do
+ t.table.(i).(j) <-
+ if i - i2 + i1 >= 0 then t.table.(i - i2 + i1).(j)
+ else {elem = Nothing; span = new_span_id ()}
+ done
+ done;
+ for i = Array.length t.table - 1 downto 0 do
+ for j = j2 to Array.length t.table.(i) - 1 do
+ t.table.(i).(j) <-
+ if i - i2 + i1 >= 0 then t.table.(i - i2 + i1).(j)
+ else {elem = Nothing; span = new_span_id ()}
+ done
+ done;
+ let old_span = t.table.(i2 - 1).(j1).span in
+ let rec loop j =
+ if j = Array.length t.table.(i2 - 1) then ()
+ else if t.table.(i2 - 1).(j).span = old_span then
+ begin t.table.(i2 - 1).(j).span <- span; loop (j + 1) end
+ in
+ loop j1
+;;
+
+let fall2_cool_left t i1 i2 i3 j1 j2 =
+ let span = t.table.(i2 - 1).(j2).span in
+ for i = i2 - 1 downto 0 do
+ for j = j1 + 1 to j2 do
+ t.table.(i).(j) <-
+ if i - i2 + i1 >= 0 then t.table.(i - i2 + i1).(j)
+ else {elem = Nothing; span = new_span_id ()}
+ done
+ done;
+ for i = Array.length t.table - 1 downto 0 do
+ for j = j1 downto 0 do
+ t.table.(i).(j) <-
+ if i - i2 + i1 >= 0 then t.table.(i - i2 + i1).(j)
+ else {elem = Nothing; span = new_span_id ()}
+ done
+ done;
+ let old_span = t.table.(i2 - 1).(j2).span in
+ let rec loop j =
+ if j < 0 then ()
+ else if t.table.(i2 - 1).(j).span = old_span then
+ begin t.table.(i2 - 1).(j).span <- span; loop (j - 1) end
+ in
+ loop j2
+;;
+
+let do_fall2_right t i1 i2 j1 j2 =
+ let i3 =
+ let rec loop_i i =
+ if i < 0 then 0
+ else
+ let rec loop_j j =
+ if j = Array.length t.table.(i) then loop_i (i - 1)
+ else
+ match t.table.(i).(j).elem with
+ Nothing -> loop_j (j + 1)
+ | _ -> i + 1
+ in
+ loop_j j2
+ in
+ loop_i (Array.length t.table - 1)
+ in
+ let new_height = i3 + i2 - i1 in
+ let t =
+ if new_height > Array.length t.table then
+ let rec loop cnt t =
+ if cnt = 0 then t
+ else
+ let new_line =
+ Array.init (Array.length t.table.(0))
+ (fun i -> {elem = Nothing; span = new_span_id ()})
+ in
+ let t = {table = Array.append t.table [| new_line |]} in
+ loop (cnt - 1) t
+ in
+ loop (new_height - Array.length t.table) t
+ else t
+ in
+ fall2_cool_right t i1 i2 i3 j1 j2; t
+;;
+
+let do_fall2_left t i1 i2 j1 j2 =
+ let i3 =
+ let rec loop_i i =
+ if i < 0 then 0
+ else
+ let rec loop_j j =
+ if j < 0 then loop_i (i - 1)
+ else
+ match t.table.(i).(j).elem with
+ Nothing -> loop_j (j - 1)
+ | _ -> i + 1
+ in
+ loop_j j1
+ in
+ loop_i (Array.length t.table - 1)
+ in
+ let new_height = i3 + i2 - i1 in
+ let t =
+ if new_height > Array.length t.table then
+ let rec loop cnt t =
+ if cnt = 0 then t
+ else
+ let new_line =
+ Array.init (Array.length t.table.(0))
+ (fun i -> {elem = Nothing; span = new_span_id ()})
+ in
+ let t = {table = Array.append t.table [| new_line |]} in
+ loop (cnt - 1) t
+ in
+ loop (new_height - Array.length t.table) t
+ else t
+ in
+ fall2_cool_left t i1 i2 i3 j1 j2; t
+;;
+
+let do_shorten_too_long t i1 j1 j2 =
+ for i = i1 to Array.length t.table - 2 do
+ for j = j1 to j2 - 1 do t.table.(i).(j) <- t.table.(i + 1).(j) done
+ done;
+ let i = Array.length t.table - 1 in
+ for j = j1 to j2 - 1 do
+ t.table.(i).(j) <- {elem = Nothing; span = new_span_id ()}
+ done;
+ t
+;;
+
+let try_fall2_right t i j =
+ match t.table.(i).(j).elem with
+ Ghost _ ->
+ let i1 =
+ let rec loop i =
+ if i < 0 then 0
+ else
+ match t.table.(i).(j).elem with
+ Ghost _ -> loop (i - 1)
+ | _ -> i + 1
+ in
+ loop (i - 1)
+ in
+ let separated1 =
+ let rec loop i =
+ if i < 0 then true
+ else if
+ j > 0 && t.table.(i).(j - 1).span = t.table.(i).(j).span then
+ false
+ else loop (i - 1)
+ in
+ loop (i1 - 1)
+ in
+ let j2 =
+ let x = t.table.(i).(j).span in
+ let rec loop j2 =
+ if j2 = Array.length t.table.(i) then j2
+ else
+ match t.table.(i).(j2) with
+ {elem = Ghost _; span = y} when y = x -> loop (j2 + 1)
+ | _ -> j2
+ in
+ loop (j + 1)
+ in
+ let separated2 =
+ let rec loop i =
+ if i = Array.length t.table then true
+ else if j2 = Array.length t.table.(i) then false
+ else if t.table.(i).(j2 - 1).span = t.table.(i).(j2).span then false
+ else loop (i + 1)
+ in
+ loop (i + 1)
+ in
+ if not separated1 || not separated2 then None
+ else Some (do_fall2_right t i1 (i + 1) j j2)
+ | _ -> None
+;;
+
+let try_fall2_left t i j =
+ match t.table.(i).(j).elem with
+ Ghost _ ->
+ let i1 =
+ let rec loop i =
+ if i < 0 then 0
+ else
+ match t.table.(i).(j).elem with
+ Ghost _ -> loop (i - 1)
+ | _ -> i + 1
+ in
+ loop (i - 1)
+ in
+ let separated1 =
+ let rec loop i =
+ if i < 0 then true
+ else if
+ j < Array.length t.table.(i) - 1 &&
+ t.table.(i).(j).span = t.table.(i).(j + 1).span then
+ false
+ else loop (i - 1)
+ in
+ loop (i1 - 1)
+ in
+ let j1 =
+ let x = t.table.(i).(j).span in
+ let rec loop j1 =
+ if j1 < 0 then j1
+ else
+ match t.table.(i).(j1) with
+ {elem = Ghost _; span = y} when y = x -> loop (j1 - 1)
+ | _ -> j1
+ in
+ loop (j - 1)
+ in
+ let separated2 =
+ let rec loop i =
+ if i = Array.length t.table then true
+ else if j1 < 0 then false
+ else if t.table.(i).(j1).span = t.table.(i).(j1 + 1).span then false
+ else loop (i + 1)
+ in
+ loop (i + 1)
+ in
+ if not separated1 || not separated2 then None
+ else Some (do_fall2_left t i1 (i + 1) j1 j)
+ | _ -> None
+;;
+
+let try_shorten_too_long t i j =
+ match t.table.(i).(j).elem with
+ Ghost _ ->
+ let j2 =
+ let x = t.table.(i).(j).span in
+ let rec loop j2 =
+ if j2 = Array.length t.table.(i) then j2
+ else
+ match t.table.(i).(j2) with
+ {elem = Ghost _; span = y} when y = x -> loop (j2 + 1)
+ | _ -> j2
+ in
+ loop (j + 1)
+ in
+ let i1 =
+ let rec loop i =
+ if i = Array.length t.table then i
+ else
+ match t.table.(i).(j).elem with
+ Elem _ -> loop (i + 1)
+ | _ -> i
+ in
+ loop (i + 1)
+ in
+ let i2 =
+ let rec loop i =
+ if i = Array.length t.table then i
+ else
+ match t.table.(i).(j).elem with
+ Nothing -> loop (i + 1)
+ | _ -> i
+ in
+ loop i1
+ in
+ let separated_left =
+ let rec loop i =
+ if i = i2 then true
+ else if
+ j > 0 && t.table.(i).(j).span = t.table.(i).(j - 1).span then
+ false
+ else loop (i + 1)
+ in
+ loop i
+ in
+ let separated_right =
+ let rec loop i =
+ if i = i2 then true
+ else if
+ j2 < Array.length t.table.(i) &&
+ t.table.(i).(j2 - 1).span = t.table.(i).(j2).span then
+ false
+ else loop (i + 1)
+ in
+ loop i
+ in
+ if not separated_left || not separated_right then None
+ else if i2 < Array.length t.table then None
+ else Some (do_shorten_too_long t i j j2)
+ | _ -> None
+;;
+
+let fall2_right t =
+ let rec loop_i i t =
+ if i <= 0 then t
+ else
+ let rec loop_j j t =
+ if j < 0 then loop_i (i - 1) t
+ else
+ match try_fall2_right t i j with
+ Some t -> loop_i (Array.length t.table - 1) t
+ | None -> loop_j (j - 1) t
+ in
+ loop_j (Array.length t.table.(i) - 2) t
+ in
+ loop_i (Array.length t.table - 1) t
+;;
+
+let fall2_left t =
+ let rec loop_i i t =
+ if i <= 0 then t
+ else
+ let rec loop_j j t =
+ if j >= Array.length t.table.(i) then loop_i (i - 1) t
+ else
+ match try_fall2_left t i j with
+ Some t -> loop_i (Array.length t.table - 1) t
+ | None -> loop_j (j + 1) t
+ in
+ loop_j 1 t
+ in
+ loop_i (Array.length t.table - 1) t
+;;
+
+let shorten_too_long t =
+ let rec loop_i i t =
+ if i <= 0 then t
+ else
+ let rec loop_j j t =
+ if j >= Array.length t.table.(i) then loop_i (i - 1) t
+ else
+ match try_shorten_too_long t i j with
+ Some t -> loop_i (Array.length t.table - 1) t
+ | None -> loop_j (j + 1) t
+ in
+ loop_j 1 t
+ in
+ loop_i (Array.length t.table - 1) t
+;;
+
+(* top_adjust:
+ deletes all empty rows that might have appeared on top of the table
+ after the falls *)
+
+let top_adjust t =
+ let di =
+ let rec loop i =
+ if i = Array.length t.table then i
+ else
+ let rec loop_j j =
+ if j = Array.length t.table.(i) then loop (i + 1)
+ else if t.table.(i).(j).elem <> Nothing then i
+ else loop_j (j + 1)
+ in
+ loop_j 0
+ in
+ loop 0
+ in
+ if di > 0 then
+ begin
+ for i = 0 to Array.length t.table - 1 - di do
+ t.table.(i) <- t.table.(i + di)
+ done;
+ {table = Array.sub t.table 0 (Array.length t.table - di)}
+ end
+ else t
+;;
+
+(* bottom_adjust:
+ deletes all empty rows that might have appeared on bottom of the table
+ after the falls *)
+
+let bottom_adjust t =
+ let last_i =
+ let rec loop i =
+ if i < 0 then i
+ else
+ let rec loop_j j =
+ if j = Array.length t.table.(i) then loop (i - 1)
+ else if t.table.(i).(j).elem <> Nothing then i
+ else loop_j (j + 1)
+ in
+ loop_j 0
+ in
+ loop (Array.length t.table - 1)
+ in
+ if last_i < Array.length t.table - 1 then
+ {table = Array.sub t.table 0 (last_i + 1)}
+ else t
+;;
+
+(* invert *)
+
+let invert_dag d =
+ let d = {dag = Array.copy d.dag} in
+ for i = 0 to Array.length d.dag - 1 do
+ let n = d.dag.(i) in
+ d.dag.(i) <-
+ {pare = List.map (fun x -> x) n.chil; valu = n.valu;
+ chil = List.map (fun x -> x) n.pare}
+ done;
+ d
+;;
+
+let invert_table t =
+ let t' = {table = Array.copy t.table} in
+ let len = Array.length t.table in
+ for i = 0 to len - 1 do
+ t'.table.(i) <-
+ Array.init (Array.length t.table.(0))
+ (fun j ->
+ let d = t.table.(len - 1 - i).(j) in
+ {elem = d.elem; span = d.span});
+ if i < len - 1 then
+ for j = 0 to Array.length t'.table.(i) - 1 do
+ t'.table.(i).(j).span <- t.table.(len - 2 - i).(j).span
+ done
+ done;
+ t'
+;;
+
+(* main *)
+
+let table_of_dag phony no_optim invert no_group d =
+ let d = if invert then invert_dag d else d in
+ let t = tablify phony no_optim no_group d in
+ let t = if invert then invert_table t else t in
+ let _ = fall () t in
+ let t = fall2_right t in
+ let t = fall2_left t in
+ let t = shorten_too_long t in
+ let t = top_adjust t in let t = bottom_adjust t in t
+;;
+
+
+let version = "1.01";;
+
+(* input dag *)
+
+let strip_spaces str =
+ let start =
+ let rec loop i =
+ if i == String.length str then i
+ else
+ match str.[i] with
+ ' ' | '\013' | '\n' | '\t' -> loop (i + 1)
+ | _ -> i
+ in
+ loop 0
+ in
+ let stop =
+ let rec loop i =
+ if i == -1 then i + 1
+ else
+ match str.[i] with
+ ' ' | '\013' | '\n' | '\t' -> loop (i - 1)
+ | _ -> i + 1
+ in
+ loop (String.length str - 1)
+ in
+ if start == 0 && stop == String.length str then str
+ else if start > stop then ""
+ else String.sub str start (stop - start)
+;;
+
+let rec get_line ic =
+ try
+ let line = input_line ic in
+ if String.length line > 0 && line.[0] = '#' then get_line ic
+ else Some (strip_spaces line)
+ with
+ End_of_file -> None
+;;
+
+let input_dag ic =
+ let rec find cnt s =
+ function
+ n :: nl ->
+ if n.valu = s then n, idag_of_int cnt else find (cnt - 1) s nl
+ | [] -> raise Not_found
+ in
+ let add_node pl cl nl cnt =
+ let cl = List.rev cl in
+ let pl = List.rev pl in
+ let (pl, pnl, nl, cnt) =
+ List.fold_left
+ (fun (pl, pnl, nl, cnt) p ->
+ try
+ let (n, p) = find (cnt - 1) p nl in p :: pl, n :: pnl, nl, cnt
+ with
+ Not_found ->
+ let n = {pare = []; valu = p; chil = []} in
+ let p = idag_of_int cnt in p :: pl, n :: pnl, n :: nl, cnt + 1)
+ ([], [], nl, cnt) pl
+ in
+ let pl = List.rev pl in
+ let (cl, nl, cnt) =
+ List.fold_left
+ (fun (cl, nl, cnt) c ->
+ try
+ let (n, c) = find (cnt - 1) c nl in
+ n.pare <- n.pare @ pl; c :: cl, nl, cnt
+ with
+ Not_found ->
+ let n = {pare = pl; valu = c; chil = []} in
+ let c = idag_of_int cnt in c :: cl, n :: nl, cnt + 1)
+ ([], nl, cnt) cl
+ in
+ let cl = List.rev cl in
+ List.iter (fun p -> p.chil <- p.chil @ cl) pnl; nl, cnt
+ in
+ let rec input_parents nl pl cnt =
+ function
+ Some "" -> input_parents nl pl cnt (get_line ic)
+ | Some line ->
+ begin match line.[0] with
+ 'o' ->
+ let p =
+ strip_spaces (String.sub line 1 (String.length line - 1))
+ in
+ if p = "" then failwith line
+ else input_parents nl (p :: pl) cnt (get_line ic)
+ | '-' ->
+ if pl = [] then failwith line
+ else input_children nl pl [] cnt (Some line)
+ | _ -> failwith line
+ end
+ | None -> if pl = [] then nl, cnt else failwith "end of file 1"
+ and input_children nl pl cl cnt =
+ function
+ Some "" -> input_children nl pl cl cnt (get_line ic)
+ | Some line ->
+ begin match line.[0] with
+ 'o' ->
+ if cl = [] then failwith line
+ else
+ let (nl, cnt) = add_node pl cl nl cnt in
+ input_parents nl [] cnt (Some line)
+ | '-' ->
+ let c =
+ strip_spaces (String.sub line 1 (String.length line - 1))
+ in
+ if c = "" then failwith line
+ else input_children nl pl (c :: cl) cnt (get_line ic)
+ | _ -> failwith line
+ end
+ | None ->
+ if cl = [] then failwith "end of file 2" else add_node pl cl nl cnt
+ in
+ let (nl, _) = input_parents [] [] 0 (get_line ic) in
+ {dag = Array.of_list (List.rev nl)}
+;;
+
+(* testing *)
+
+let map_dag f d =
+ let a =
+ Array.map (fun d -> {pare = d.pare; valu = f d.valu; chil = d.chil}) d.dag
+ in
+ {dag = a}
+;;
+
+let tag_dag d =
+ let c = ref 'A' in
+ map_dag
+ (fun v ->
+ let v = !c in
+ c :=
+ if !c = 'Z' then 'a'
+ else if !c = 'z' then '1'
+ else Char.chr (Char.code !c + 1);
+ String.make 1 v)
+ d
+;;
+
+(* *)
+
+let phony _ = false;;
+let indi_txt n = n.valu;;
+
+let string_table border hts =
+ let buf = Buffer.create 30 in
+ Printf.bprintf buf "<center><table border=%d" border;
+ Printf.bprintf buf " cellspacing=0 cellpadding=0>\n";
+ for i = 0 to Array.length hts - 1 do
+ Printf.bprintf buf "<tr>\n";
+ for j = 0 to Array.length hts.(i) - 1 do
+ let (colspan, align, td) = hts.(i).(j) in
+ Printf.bprintf buf "<td";
+ if colspan = 1 && (td = TDstring "&nbsp;" || td = TDhr CenterA) then ()
+ else Printf.bprintf buf " colspan=%d" colspan;
+ begin match align, td with
+ LeftA, TDhr LeftA -> Printf.bprintf buf " align=left"
+ | LeftA, _ -> ()
+ | CenterA, _ -> Printf.bprintf buf " align=center"
+ | RightA, _ -> Printf.bprintf buf " align=right"
+ end;
+ Printf.bprintf buf ">";
+ begin match td with
+ TDstring s -> Printf.bprintf buf "%s" s
+ | TDhr align ->
+ Printf.bprintf buf "<hr noshade size=1";
+ begin match align with
+ LeftA -> Printf.bprintf buf " width=\"50%%\" align=left"
+ | RightA -> Printf.bprintf buf " width=\"50%%\" align=right"
+ | _ -> ()
+ end;
+ Printf.bprintf buf ">";
+ ()
+ end;
+ Printf.bprintf buf "</td>\n";
+ ()
+ done
+ done;
+ Printf.bprintf buf "</table></center>\n";
+ Buffer.contents buf
+;;
+
+let fname = ref "";;
+let invert = ref false;;
+let char = ref false;;
+let border = ref 0;;
+let no_optim = ref false;;
+let no_group = ref false;;
+
+let html_of_dag d =
+ let t = table_of_dag phony !no_optim !invert !no_group d in
+ let hts = html_table_struct indi_txt phony d t in
+ string_table !border hts
+;;
+
+
+(********************************* Max's code **********************************)
+(** This function takes a list of classes and a list of class types
+ and create the associate dag. *)
+let create_class_dag cl_list clt_list =
+ let module M = Odoc_info.Class in
+ (* the list of all the classes concerned *)
+ let cl_list2 = List.map (fun c -> (c.M.cl_name, Some (M.Cl c))) cl_list in
+ let clt_list2 = List.map (fun ct -> (ct.M.clt_name, Some (M.Cltype (ct, [])))) clt_list in
+ let list = cl_list2 @ clt_list2 in
+ let all_classes =
+ let rec iter list2 =
+ List.fold_left
+ (fun acc -> fun (name, cct_opt) ->
+ let l =
+ match cct_opt with
+ None -> []
+ | Some (M.Cl c) ->
+ iter
+ (List.map
+ (fun inh ->(inh.M.ic_name, inh.M.ic_class))
+ (match c.M.cl_kind with
+ M.Class_structure (inher_l, _) ->
+ inher_l
+ | _ ->
+ []
+ )
+ )
+ | Some (M.Cltype (ct, _)) ->
+ iter
+ (List.map
+ (fun inh ->(inh.M.ic_name, inh.M.ic_class))
+ (match ct.M.clt_kind with
+ M.Class_signature (inher_l, _) ->
+ inher_l
+ | _ ->
+ []
+ )
+ )
+ in
+ (name, cct_opt) :: (acc @ l)
+ )
+ []
+ list2
+ in
+ iter list
+ in
+ let rec distinct acc = function
+ [] ->
+ acc
+ | (name, cct_opt) :: q ->
+ if List.exists (fun (name2, _) -> name = name2) acc then
+ distinct acc q
+ else
+ distinct ((name, cct_opt) :: acc) q
+ in
+ let distinct_classes = distinct [] all_classes in
+ let liste_index =
+ let rec f n = function
+ [] -> []
+ | (name, _) :: q -> (name, n) :: (f (n+1) q)
+ in
+ f 0 distinct_classes
+ in
+ let array1 = Array.of_list distinct_classes in
+ (* create the dag array, filling parents and values *)
+ let fmap (name, cct_opt) =
+ { pare = List.map
+ (fun inh -> List.assoc inh.M.ic_name liste_index )
+ (match cct_opt with
+ None -> []
+ | Some (M.Cl c) ->
+ (match c.M.cl_kind with
+ M.Class_structure (inher_l, _) ->
+ inher_l
+ | _ ->
+ []
+ )
+ | Some (M.Cltype (ct, _)) ->
+ (match ct.M.clt_kind with
+ M.Class_signature (inher_l, _) ->
+ inher_l
+ | _ ->
+ []
+ )
+ );
+ valu = (name, cct_opt) ;
+ chil = []
+ }
+ in
+ let dag = { dag = Array.map fmap array1 } in
+ (* fill the children *)
+ let fiter i node =
+ let l = Array.to_list dag.dag in
+ let l2 = List.map (fun n -> n.valu)
+ (List.filter (fun n -> List.mem i n.pare) l)
+ in
+ node.chil <- List.map (fun (name,_) -> List.assoc name liste_index) l2
+ in
+ Array.iteri fiter dag.dag;
+ dag
diff --git a/ocamldoc/odoc_dag2html.mli b/ocamldoc/odoc_dag2html.mli
new file mode 100644
index 0000000000..d59148c767
--- /dev/null
+++ b/ocamldoc/odoc_dag2html.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The types and functions to create a html table representing a dag.
+ Thanks to Daniel de Rauglaudre. *)
+
+type 'a dag = { mutable dag : 'a node array }
+and 'a node =
+ { mutable pare : idag list; valu : 'a; mutable chil : idag list }
+and idag = int
+
+(** This function returns the html code to represent the given dag. *)
+val html_of_dag : string dag -> string
+
+(** This function takes a list of classes and a list of class types and creates the associate dag. *)
+val create_class_dag :
+ Odoc_info.Class.t_class list ->
+ Odoc_info.Class.t_class_type list ->
+ (Odoc_info.Name.t * Odoc_info.Class.cct option) dag
diff --git a/ocamldoc/odoc_dep.ml b/ocamldoc/odoc_dep.ml
new file mode 100644
index 0000000000..b0393fe860
--- /dev/null
+++ b/ocamldoc/odoc_dep.ml
@@ -0,0 +1,219 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Top modules dependencies. *)
+
+module StrS = Depend.StringSet
+module Module = Odoc_module
+module Type = Odoc_type
+
+let set_to_list s =
+ let l = ref [] in
+ StrS.iter (fun e -> l := e :: !l) s;
+ !l
+
+let impl_dependencies ast =
+ Depend.free_structure_names := StrS.empty;
+ Depend.add_use_file StrS.empty [Parsetree.Ptop_def ast];
+ set_to_list !Depend.free_structure_names
+
+let intf_dependencies ast =
+ Depend.free_structure_names := StrS.empty;
+ Depend.add_signature StrS.empty ast;
+ set_to_list !Depend.free_structure_names
+
+
+module Dep =
+ struct
+ type id = string
+
+ module S = Set.Make (struct
+ type t = string
+ let compare (x:t) y = compare x y
+ end)
+
+ let set_to_list s =
+ let l = ref [] in
+ S.iter (fun e -> l := e :: !l) s;
+ !l
+
+ type node = {
+ id : id ;
+ mutable near : S.t ; (** fils directs *)
+ mutable far : (id * S.t) list ; (** fils indirects, par quel fils *)
+ reflex : bool ; (** reflexive or not, we keep
+ information here to remove the node itself from its direct children *)
+ }
+
+ type graph = node list
+
+ let make_node s children =
+ let set = List.fold_right
+ S.add
+ children
+ S.empty
+ in
+ { id = s;
+ near = S.remove s set ;
+ far = [] ;
+ reflex = List.mem s children ;
+ }
+
+ let get_node graph s =
+ try List.find (fun n -> n.id = s) graph
+ with Not_found ->
+ make_node s []
+
+ let rec trans_closure graph acc n =
+ if S.mem n.id acc then
+ acc
+ else
+ (* optimisation plus tard : utiliser le champ far si non vide ? *)
+ S.fold
+ (fun child -> fun acc2 ->
+ trans_closure graph acc2 (get_node graph child))
+ n.near
+ (S.add n.id acc)
+
+ let node_trans_closure graph n =
+ let far = List.map
+ (fun child ->
+ let set = trans_closure graph S.empty (get_node graph child) in
+ (child, set)
+ )
+ (set_to_list n.near)
+ in
+ n.far <- far
+
+ let compute_trans_closure graph =
+ List.iter (node_trans_closure graph) graph
+
+ let prune_node graph node =
+ S.iter
+ (fun child ->
+ let set_reachables = List.fold_left
+ (fun acc -> fun (ch, reachables) ->
+ if child = ch then
+ acc
+ else
+ S.union acc reachables
+ )
+ S.empty
+ node.far
+ in
+ let set = S.remove node.id set_reachables in
+ if S.exists (fun n2 -> S.mem child (get_node graph n2).near) set then
+ (
+ node.near <- S.remove child node.near ;
+ node.far <- List.filter (fun (ch,_) -> ch <> child) node.far
+ )
+ else
+ ()
+ )
+ node.near;
+ if node.reflex then
+ node.near <- S.add node.id node.near
+ else
+ ()
+
+ let kernel graph =
+ (* compute transitive closure *)
+ compute_trans_closure graph ;
+
+ (* remove edges to keep a transitive kernel *)
+ List.iter (prune_node graph) graph;
+
+ graph
+
+ end
+
+(** [type_deps t] returns the list of fully qualified type names
+ [t] depends on. *)
+let type_deps t =
+ let module T = Odoc_type in
+ let l = ref [] in
+ let re = Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([a-z][a-zA-Z_'0-9]*\\)" in
+ let f s =
+ let s2 = Str.matched_string s in
+ l := s2 :: !l ;
+ s2
+ in
+ let ty t =
+ let s = Odoc_print.string_of_type_expr t in
+ ignore (Str.global_substitute re f s)
+ in
+ (match t.T.ty_kind with
+ T.Type_abstract -> ()
+ | T.Type_variant cl ->
+ List.iter
+ (fun c ->
+ match c.T.vc_args with
+ | T.Cstr_tuple l -> List.iter ty l
+ | T.Cstr_record l -> List.iter (fun r -> ty r.T.rf_type) l
+ )
+ cl
+ | T.Type_record rl ->
+ List.iter (fun r -> ty r.T.rf_type) rl
+ | T.Type_open -> ()
+ );
+
+ (match t.T.ty_manifest with
+ None -> ()
+ | Some (T.Object_type fields) ->
+ List.iter (fun r -> ty r.T.of_type) fields
+ | Some (T.Other e) ->
+ ty e
+ );
+
+ !l
+
+(** Modify the modules depencies of the given list of modules,
+ to get the minimum transitivity kernel. *)
+let kernel_deps_of_modules modules =
+ let graph = List.map
+ (fun m -> Dep.make_node m.Module.m_name m.Module.m_top_deps)
+ modules
+ in
+ let k = Dep.kernel graph in
+ List.iter
+ (fun m ->
+ let node = Dep.get_node k m.Module.m_name in
+ m.Module.m_top_deps <-
+ List.filter (fun m2 -> Dep.S.mem m2 node.Dep.near) m.Module.m_top_deps)
+ modules
+
+(** Return the list of dependencies between the given types,
+ in the form of a list [(type, names of types it depends on)].
+ @param kernel indicates if we must keep only the transitivity kernel
+ of the dependencies. Default is [false].
+*)
+let deps_of_types ?(kernel=false) types =
+ let deps_pre = List.map (fun t -> (t, type_deps t)) types in
+ let deps =
+ if kernel then
+ (
+ let graph = List.map
+ (fun (t, names) -> Dep.make_node t.Type.ty_name names)
+ deps_pre
+ in
+ let k = Dep.kernel graph in
+ List.map
+ (fun t ->
+ let node = Dep.get_node k t.Type.ty_name in
+ (t, Dep.set_to_list node.Dep.near)
+ )
+ types
+ )
+ else
+ deps_pre
+ in
+ deps
diff --git a/ocamldoc/odoc_dot.ml b/ocamldoc/odoc_dot.ml
new file mode 100644
index 0000000000..60d6cd7e91
--- /dev/null
+++ b/ocamldoc/odoc_dot.ml
@@ -0,0 +1,144 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Definition of a class which outputs a dot file showing
+ top modules dependencies.*)
+
+open Odoc_info
+
+module F = Format
+
+let dot_include_all = ref false
+
+let dot_types = ref false
+
+let dot_reduce = ref false
+
+let dot_colors = ref (List.flatten Odoc_messages.default_dot_colors)
+
+module Generator =
+struct
+
+(** This class generates a dot file showing the top modules dependencies. *)
+class dot =
+ object (self)
+
+ (** To store the colors associated to locations of modules. *)
+ val mutable loc_colors = []
+
+ (** the list of modules we know. *)
+ val mutable modules = []
+
+ (** Colors to use when finding new locations of modules. *)
+ val mutable colors = !dot_colors
+
+ (** Graph header. *)
+ method header =
+ "digraph G {\n"^
+ " size=\"10,7.5\";\n"^
+ " ratio=\"fill\";\n"^
+ " rotate=90;\n"^
+ " fontsize=\"12pt\";\n"^
+ " rankdir = TB ;\n"
+
+ method get_one_color =
+ match colors with
+ [] -> None
+ | h :: q ->
+ colors <- q ;
+ Some h
+
+ method node_color s =
+ try Some (List.assoc s loc_colors)
+ with
+ Not_found ->
+ match self#get_one_color with
+ None -> None
+ | Some c ->
+ loc_colors <- (s, c) :: loc_colors ;
+ Some c
+
+ method print_module_atts fmt m =
+ match self#node_color (Filename.dirname m.Module.m_file) with
+ None -> ()
+ | Some col -> F.fprintf fmt "\"%s\" [style=filled, color=%s];\n" m.Module.m_name col
+
+ method print_type_atts fmt t =
+ match self#node_color (Name.father t.Type.ty_name) with
+ None -> ()
+ | Some col -> F.fprintf fmt "\"%s\" [style=filled, color=%s];\n" t.Type.ty_name col
+
+ method print_one_dep fmt src dest =
+ F.fprintf fmt "\"%s\" -> \"%s\";\n" src dest
+
+ method generate_for_module fmt m =
+ let l = List.filter
+ (fun n ->
+ !dot_include_all ||
+ (List.exists (fun m -> m.Module.m_name = n) modules))
+ m.Module.m_top_deps
+ in
+ self#print_module_atts fmt m;
+ List.iter (self#print_one_dep fmt m.Module.m_name) l
+
+ method generate_for_type fmt (t, l) =
+ self#print_type_atts fmt t;
+ List.iter
+ (self#print_one_dep fmt t.Type.ty_name)
+ l
+
+ method generate_types types =
+ try
+ let oc = open_out !Global.out_file in
+ let fmt = F.formatter_of_out_channel oc in
+ F.fprintf fmt "%s" self#header;
+ let graph = Odoc_info.Dep.deps_of_types
+ ~kernel: !dot_reduce
+ types
+ in
+ List.iter (self#generate_for_type fmt) graph;
+ F.fprintf fmt "}\n" ;
+ F.pp_print_flush fmt ();
+ close_out oc
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ method generate_modules modules_list =
+ try
+ modules <- modules_list ;
+ let oc = open_out !Global.out_file in
+ let fmt = F.formatter_of_out_channel oc in
+ F.fprintf fmt "%s" self#header;
+
+ if !dot_reduce then
+ Odoc_info.Dep.kernel_deps_of_modules modules_list;
+
+ List.iter (self#generate_for_module fmt) modules_list;
+ F.fprintf fmt "}\n" ;
+ F.pp_print_flush fmt ();
+ close_out oc
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ (** Generate the dot code in the file {!Odoc_info.Args.out_file}. *)
+ method generate (modules_list : Odoc_info.Module.t_module list) =
+ colors <- !dot_colors;
+ if !dot_types then
+ self#generate_types (Odoc_info.Search.types modules_list)
+ else
+ self#generate_modules modules_list
+ end
+end
+
+module type Dot_generator = module type of Generator
diff --git a/ocamldoc/odoc_env.ml b/ocamldoc/odoc_env.ml
new file mode 100644
index 0000000000..3e05905856
--- /dev/null
+++ b/ocamldoc/odoc_env.ml
@@ -0,0 +1,247 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Environment for finding complete names from relative names. *)
+
+let print_DEBUG s = print_string s ; print_newline ();;
+
+module Name = Odoc_name
+
+(** relative name * complete name *)
+type env_element = Name.t * Name.t
+
+type env = {
+ env_values : env_element list ;
+ env_types : env_element list ;
+ env_class_types : env_element list ;
+ env_classes : env_element list ;
+ env_modules : env_element list ;
+ env_module_types : env_element list ;
+ env_extensions : env_element list ;
+ }
+
+let empty = {
+ env_values = [] ;
+ env_types = [] ;
+ env_class_types = [] ;
+ env_classes = [] ;
+ env_modules = [] ;
+ env_module_types = [] ;
+ env_extensions = [] ;
+ }
+
+(** Add a signature to an environment. *)
+let rec add_signature env root ?rel signat =
+ let qualify id = Name.concat root (Name.from_ident id) in
+ let rel_name id =
+ let n = Name.from_ident id in
+ match rel with
+ None -> n
+ | Some r -> Name.concat r n
+ in
+ let f env item =
+ match item with
+ Types.Sig_value (ident, _) -> { env with env_values = (rel_name ident, qualify ident) :: env.env_values }
+ | Types.Sig_type (ident,_,_) -> { env with env_types = (rel_name ident, qualify ident) :: env.env_types }
+ | Types.Sig_typext (ident, _, _) -> { env with env_extensions = (rel_name ident, qualify ident) :: env.env_extensions }
+ | Types.Sig_module (ident, md, _) ->
+ let env2 =
+ match md.Types.md_type with (* A VOIR : le cas ou c'est un identificateur, dans ce cas on n'a pas de signature *)
+ Types.Mty_signature s -> add_signature env (qualify ident) ~rel: (rel_name ident) s
+ | _ -> env
+ in
+ { env2 with env_modules = (rel_name ident, qualify ident) :: env2.env_modules }
+ | Types.Sig_modtype (ident, modtype_decl) ->
+ let env2 =
+ match modtype_decl.Types.mtd_type with
+ None ->
+ env
+ | Some modtype ->
+ match modtype with
+ (* A VOIR : le cas ou c'est un identificateur, dans ce cas on n'a pas de signature *)
+ Types.Mty_signature s -> add_signature env (qualify ident) ~rel: (rel_name ident) s
+ | _ -> env
+ in
+ { env2 with env_module_types = (rel_name ident, qualify ident) :: env2.env_module_types }
+ | Types.Sig_class (ident, _, _) -> { env with env_classes = (rel_name ident, qualify ident) :: env.env_classes }
+ | Types.Sig_class_type (ident, _, _) -> { env with env_class_types = (rel_name ident, qualify ident) :: env.env_class_types }
+ in
+ List.fold_left f env signat
+
+let add_extension env full_name =
+ let simple_name = Name.simple full_name in
+ { env with env_extensions = (simple_name, full_name) :: env.env_extensions }
+
+let add_type env full_name =
+ let simple_name = Name.simple full_name in
+ { env with env_types = (simple_name, full_name) :: env.env_types }
+
+let add_value env full_name =
+ let simple_name = Name.simple full_name in
+ { env with env_values = (simple_name, full_name) :: env.env_values }
+
+let add_module env full_name =
+ let simple_name = Name.simple full_name in
+ { env with env_modules = (simple_name, full_name) :: env.env_modules }
+
+let add_module_type env full_name =
+ let simple_name = Name.simple full_name in
+ { env with env_module_types = (simple_name, full_name) :: env.env_module_types }
+
+let add_class env full_name =
+ let simple_name = Name.simple full_name in
+ { env with
+ env_classes = (simple_name, full_name) :: env.env_classes ;
+ (* we also add a type 'cause the class name may appear as a type *)
+ env_types = (simple_name, full_name) :: env.env_types
+ }
+
+let add_class_type env full_name =
+ let simple_name = Name.simple full_name in
+ { env with
+ env_class_types = (simple_name, full_name) :: env.env_class_types ;
+ (* we also add a type 'cause the class type name may appear as a type *)
+ env_types = (simple_name, full_name) :: env.env_types
+ }
+
+let full_module_name env n =
+ try List.assoc n env.env_modules
+ with Not_found ->
+ print_DEBUG ("Module "^n^" not found with env=");
+ List.iter (fun (sn, fn) -> print_DEBUG ("("^sn^", "^fn^")")) env.env_modules;
+ n
+
+let full_module_type_name env n =
+ try List.assoc n env.env_module_types
+ with Not_found ->
+ print_DEBUG ("Module "^n^" not found with env=");
+ List.iter (fun (sn, fn) -> print_DEBUG ("("^sn^", "^fn^")")) env.env_modules;
+ n
+
+let full_module_or_module_type_name env n =
+ try List.assoc n env.env_modules
+ with Not_found -> full_module_type_name env n
+
+let full_type_name env n =
+ try
+ let full = List.assoc n env.env_types in
+(** print_string ("type "^n^" is "^full);
+ print_newline ();*)
+ full
+ with Not_found ->
+(** print_string ("type "^n^" not found");
+ print_newline ();*)
+ n
+
+let full_value_name env n =
+ try List.assoc n env.env_values
+ with Not_found -> n
+
+let full_extension_constructor_name env n =
+ try List.assoc n env.env_extensions
+ with Not_found ->
+ print_DEBUG ("Extension "^n^" not found with env=");
+ List.iter (fun (sn, fn) -> print_DEBUG ("("^sn^", "^fn^")")) env.env_extensions;
+ n
+
+let full_class_name env n =
+ try List.assoc n env.env_classes
+ with Not_found ->
+ print_DEBUG ("Class "^n^" not found with env=");
+ List.iter (fun (sn, fn) -> print_DEBUG ("("^sn^", "^fn^")")) env.env_classes;
+ n
+
+let full_class_type_name env n =
+ try List.assoc n env.env_class_types
+ with Not_found ->
+ print_DEBUG ("Class type "^n^" not found with env=");
+ List.iter (fun (sn, fn) -> print_DEBUG ("("^sn^", "^fn^")")) env.env_class_types;
+ n
+
+let full_class_or_class_type_name env n =
+ try List.assoc n env.env_classes
+ with Not_found -> full_class_type_name env n
+
+let print_env_types env =
+ List.iter (fun (s1,s2) -> Printf.printf "%s = %s\n" s1 s2) env.env_types
+
+let subst_type env t =
+(*
+ print_string "Odoc_env.subst_type\n";
+ print_env_types env ;
+ print_newline ();
+*)
+ Printtyp.mark_loops t;
+ let deja_vu = ref [] in
+ let rec iter t =
+ if List.memq t !deja_vu then () else begin
+ deja_vu := t :: !deja_vu;
+ Btype.iter_type_expr iter t;
+ match t.Types.desc with
+ | Types.Tconstr (p, [ty], a) when Path.same p Predef.path_option ->
+ ()
+ | Types.Tconstr (p, l, a) ->
+ let new_p =
+ Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
+ t.Types.desc <- Types.Tconstr (new_p, l, a)
+ | Types.Tpackage (p, n, l) ->
+ let new_p =
+ Odoc_name.to_path (full_module_type_name env (Odoc_name.from_path p)) in
+ t.Types.desc <- Types.Tpackage (new_p, n, l)
+ | Types.Tobject (_, ({contents=Some(p,tyl)} as r)) ->
+ let new_p =
+ Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
+ r := Some (new_p, tyl)
+ | Types.Tvariant ({Types.row_name=Some(p, tyl)} as row) ->
+ let new_p =
+ Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
+ t.Types.desc <-
+ Types.Tvariant {row with Types.row_name=Some(new_p, tyl)}
+ | _ ->
+ ()
+ end
+ in
+ iter t;
+ t
+
+
+let subst_module_type env t =
+ let rec iter t =
+ match t with
+ Types.Mty_ident p ->
+ let new_p = Odoc_name.to_path (full_module_type_name env (Odoc_name.from_path p)) in
+ Types.Mty_ident new_p
+ | Types.Mty_alias _
+ | Types.Mty_signature _ ->
+ t
+ | Types.Mty_functor (id, mt1, mt2) ->
+ Types.Mty_functor (id, Misc.may_map iter mt1, iter mt2)
+ in
+ iter t
+
+let subst_class_type env t =
+ let rec iter t =
+ match t with
+ Types.Cty_constr (p,texp_list,ct) ->
+ let new_p = Odoc_name.to_path (full_type_name env (Odoc_name.from_path p)) in
+ let new_texp_list = List.map (subst_type env) texp_list in
+ let new_ct = iter ct in
+ Types.Cty_constr (new_p, new_texp_list, new_ct)
+ | Types.Cty_signature cs ->
+ (* on ne s'occupe pas des vals et methods *)
+ t
+ | Types.Cty_arrow (l, texp, ct) ->
+ let new_texp = subst_type env texp in
+ let new_ct = iter ct in
+ Types.Cty_arrow (l, new_texp, new_ct)
+ in
+ iter t
diff --git a/ocamldoc/odoc_env.mli b/ocamldoc/odoc_env.mli
new file mode 100644
index 0000000000..4e1e8606d7
--- /dev/null
+++ b/ocamldoc/odoc_env.mli
@@ -0,0 +1,75 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Environment for finding complete names from relative names. *)
+
+(** An environment of known names,
+ from simple name to complete name. *)
+type env
+
+(** The empty environment. *)
+val empty : env
+
+(** Extending an environment *)
+
+val add_signature : env -> string -> ?rel:string -> Types.signature -> env
+val add_extension : env -> Odoc_name.t -> env
+val add_type : env -> Odoc_name.t -> env
+val add_value : env -> Odoc_name.t -> env
+val add_module : env -> Odoc_name.t -> env
+val add_module_type : env -> Odoc_name.t -> env
+val add_class : env -> Odoc_name.t -> env
+val add_class_type : env -> Odoc_name.t -> env
+
+(** Retrieving fully qualified names from an environment *)
+
+(** Get the fully qualified module name from a name.*)
+val full_module_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Get the fully qualified module type name from a name.*)
+val full_module_type_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Get the fully qualified module or module type name from a name.
+ We look for a module type if we don't find a module.*)
+val full_module_or_module_type_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Get the fully qualified type name from a name.*)
+val full_type_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Get the fully qualified value name from a name.*)
+val full_value_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Get the fully qualified extension name from a name.*)
+val full_extension_constructor_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Get the fully qualified class name from a name.*)
+val full_class_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Get the fully qualified class type name from a name.*)
+val full_class_type_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Get the fully qualified class or class type name from a name.*)
+val full_class_or_class_type_name : env -> Odoc_name.t -> Odoc_name.t
+
+(** Substitutions *)
+
+(** Replace the [Path.t] by a complete [Path.t] in a [Types.type_expr].*)
+val subst_type : env -> Types.type_expr -> Types.type_expr
+
+(** Replace the [Path.t] by a complete [Path.t] in a [Types.module_type].*)
+val subst_module_type : env -> Types.module_type -> Types.module_type
+
+(** Replace the [Path.t] by a complete [Path.t] in a [Types.class_type].
+ Also empty the structures to get only [object end] when the type
+ is printed.
+*)
+val subst_class_type : env -> Types.class_type -> Types.class_type
diff --git a/ocamldoc/odoc_exception.ml b/ocamldoc/odoc_exception.ml
new file mode 100644
index 0000000000..c65f384e55
--- /dev/null
+++ b/ocamldoc/odoc_exception.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation and manipulation of exceptions. *)
+
+module Name = Odoc_name
+
+type exception_alias = {
+ ea_name : Name.t ;
+ mutable ea_ex : t_exception option ;
+ }
+
+and t_exception = {
+ ex_name : Name.t ;
+ mutable ex_info : Odoc_types.info option ; (** optional user information *)
+ ex_args : Odoc_type.constructor_args ; (** the types of the parameters *)
+ ex_ret: Types.type_expr option ; (** the optional return type *)
+ ex_alias : exception_alias option ;
+ mutable ex_loc : Odoc_types.location ;
+ mutable ex_code : string option ;
+ }
diff --git a/ocamldoc/odoc_extension.ml b/ocamldoc/odoc_extension.ml
new file mode 100644
index 0000000000..c649c3c7d2
--- /dev/null
+++ b/ocamldoc/odoc_extension.ml
@@ -0,0 +1,45 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation and manipulation of type extensions. *)
+
+module Name = Odoc_name
+
+type private_flag = Asttypes.private_flag =
+ Private | Public
+
+type extension_alias = {
+ xa_name : Name.t ;
+ mutable xa_xt : t_extension_constructor option ;
+ }
+
+and t_extension_constructor = {
+ xt_name : Name.t ;
+ xt_args: Odoc_type.constructor_args;
+ xt_ret: Types.type_expr option ; (** the optional return type of the extension *)
+ xt_type_extension: t_type_extension ; (** the type extension containing this constructor *)
+ xt_alias: extension_alias option ;
+ mutable xt_loc: Odoc_types.location ;
+ mutable xt_text: Odoc_types.info option ; (** optional user description *)
+ }
+
+and t_type_extension = {
+ mutable te_info : Odoc_types.info option ; (** optional user information *)
+ te_type_name : Name.t;
+ te_type_parameters : Types.type_expr list;
+ te_private : private_flag;
+ mutable te_constructors: t_extension_constructor list;
+ mutable te_loc : Odoc_types.location ;
+ mutable te_code : string option ;
+ }
+
+let extension_constructors te = te.te_constructors
diff --git a/ocamldoc/odoc_gen.ml b/ocamldoc/odoc_gen.ml
new file mode 100644
index 0000000000..a36ffbea2e
--- /dev/null
+++ b/ocamldoc/odoc_gen.ml
@@ -0,0 +1,61 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2010 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** *)
+
+class type doc_generator =
+ object method generate : Odoc_module.t_module list -> unit end;;
+
+module type Base = sig
+ class generator : doc_generator
+ end;;
+
+module Base_generator : Base = struct
+ class generator : doc_generator = object method generate l = () end
+ end;;
+
+module type Base_functor = functor (G: Base) -> Base
+module type Html_functor = functor (G: Odoc_html.Html_generator) -> Odoc_html.Html_generator
+module type Latex_functor = functor (G: Odoc_latex.Latex_generator) -> Odoc_latex.Latex_generator
+module type Texi_functor = functor (G: Odoc_texi.Texi_generator) -> Odoc_texi.Texi_generator
+module type Man_functor = functor (G: Odoc_man.Man_generator) -> Odoc_man.Man_generator
+module type Dot_functor = functor (G: Odoc_dot.Dot_generator) -> Odoc_dot.Dot_generator
+
+type generator =
+ | Html of (module Odoc_html.Html_generator)
+ | Latex of (module Odoc_latex.Latex_generator)
+ | Texi of (module Odoc_texi.Texi_generator)
+ | Man of (module Odoc_man.Man_generator)
+ | Dot of (module Odoc_dot.Dot_generator)
+ | Base of (module Base)
+;;
+
+let get_minimal_generator = function
+ Html m ->
+ let module M = (val m : Odoc_html.Html_generator) in
+ (new M.html :> doc_generator)
+| Latex m ->
+ let module M = (val m : Odoc_latex.Latex_generator) in
+ (new M.latex :> doc_generator)
+| Man m ->
+ let module M = (val m : Odoc_man.Man_generator) in
+ (new M.man :> doc_generator)
+| Texi m ->
+ let module M = (val m : Odoc_texi.Texi_generator) in
+ (new M.texi :> doc_generator)
+| Dot m ->
+ let module M = (val m : Odoc_dot.Dot_generator) in
+ (new M.dot :> doc_generator)
+| Base m ->
+ let module M = (val m : Base) in
+ new M.generator
+ ;;
diff --git a/ocamldoc/odoc_gen.mli b/ocamldoc/odoc_gen.mli
new file mode 100644
index 0000000000..04987cf011
--- /dev/null
+++ b/ocamldoc/odoc_gen.mli
@@ -0,0 +1,43 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2010 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The types of generators. *)
+
+(** The minimal class type of documentation generators. *)
+class type doc_generator =
+ object method generate : Odoc_module.t_module list -> unit end;;
+
+(** The module type of minimal generators. *)
+module type Base = sig
+ class generator : doc_generator
+ end;;
+
+module Base_generator : Base
+
+module type Base_functor = functor (P: Base) -> Base
+module type Html_functor = functor (G: Odoc_html.Html_generator) -> Odoc_html.Html_generator
+module type Latex_functor = functor (G: Odoc_latex.Latex_generator) -> Odoc_latex.Latex_generator
+module type Texi_functor = functor (G: Odoc_texi.Texi_generator) -> Odoc_texi.Texi_generator
+module type Man_functor = functor (G: Odoc_man.Man_generator) -> Odoc_man.Man_generator
+module type Dot_functor = functor (G: Odoc_dot.Dot_generator) -> Odoc_dot.Dot_generator
+
+(** Various ways to create a generator. *)
+type generator =
+ | Html of (module Odoc_html.Html_generator)
+ | Latex of (module Odoc_latex.Latex_generator)
+ | Texi of (module Odoc_texi.Texi_generator)
+ | Man of (module Odoc_man.Man_generator)
+ | Dot of (module Odoc_dot.Dot_generator)
+ | Base of (module Base)
+;;
+
+val get_minimal_generator : generator -> doc_generator
diff --git a/ocamldoc/odoc_global.ml b/ocamldoc/odoc_global.ml
new file mode 100644
index 0000000000..9c3efb9824
--- /dev/null
+++ b/ocamldoc/odoc_global.ml
@@ -0,0 +1,77 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Global variables. *)
+
+(* Tell ocaml compiler not to generate files. *)
+let _ = Clflags.dont_write_files := true
+
+open Clflags
+
+type source_file =
+ Impl_file of string
+ | Intf_file of string
+ | Text_file of string
+
+let include_dirs = Clflags.include_dirs
+
+let errors = ref 0
+
+let warn_error = ref false
+
+let pwarning s =
+ if !Odoc_config.print_warnings then prerr_endline (Odoc_messages.warning^": "^s);
+ if !warn_error then incr errors
+
+let merge_options = ref ([] : Odoc_types.merge_option list)
+
+let classic = Clflags.classic
+
+let dump = ref (None : string option)
+
+let load = ref ([] : string list)
+
+let sort_modules = ref false
+
+let no_custom_tags = ref false
+
+let no_stop = ref false
+
+let remove_stars = ref false
+
+let keep_code = ref false
+
+let inverse_merge_ml_mli = ref false
+
+let filter_with_module_constraints = ref true
+
+let hidden_modules = ref ([] : string list)
+
+let files = ref []
+
+let out_file = ref Odoc_messages.default_out_file
+
+let verbose = Clflags.verbose
+
+let target_dir = ref Filename.current_dir_name
+
+let title = ref (None : string option)
+
+let intro_file = ref (None : string option)
+
+let with_header = ref true
+
+let with_trailer = ref true
+
+let with_toc = ref true
+
+let with_index = ref true
diff --git a/ocamldoc/odoc_global.mli b/ocamldoc/odoc_global.mli
new file mode 100644
index 0000000000..641d40c0bc
--- /dev/null
+++ b/ocamldoc/odoc_global.mli
@@ -0,0 +1,97 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Global variables. *)
+
+(** The kind of source file in arguments. *)
+type source_file =
+ Impl_file of string
+ | Intf_file of string
+ | Text_file of string
+
+(** The include_dirs in the OCaml compiler. *)
+val include_dirs : string list ref
+
+(** The merge options to be used. *)
+val merge_options : Odoc_types.merge_option list ref
+
+(** Classic mode or not. *)
+val classic : bool ref
+
+(** The optional file name to dump the collected information into.*)
+val dump : string option ref
+
+(** The list of information files to load. *)
+val load : string list ref
+
+(** We must sort the list of top modules or not.*)
+val sort_modules : bool ref
+
+(** We must not stop at the stop special comments. Default is false (we stop).*)
+val no_stop : bool ref
+
+(** We must raise an exception when we find an unknown @-tag. *)
+val no_custom_tags : bool ref
+
+(** We must remove the the first characters of each comment line, until the first asterisk '*'. *)
+val remove_stars : bool ref
+
+(** To keep the code while merging, when we have both .ml and .mli files for a module. *)
+val keep_code : bool ref
+
+(** To inverse implementation and interface files when merging. *)
+val inverse_merge_ml_mli : bool ref
+
+(** To filter module elements according to module type constraints. *)
+val filter_with_module_constraints : bool ref
+
+(** The list of module names to hide. *)
+val hidden_modules : string list ref
+
+(** The files to be analysed. *)
+val files : source_file list ref
+(** A counter for errors. *)
+val errors : int ref
+
+(** Indicate if a warning is an error. *)
+val warn_error : bool ref
+
+(** Print the given warning, adding it to the list of {!errors}
+if {!warn_error} is [true]. *)
+val pwarning : string -> unit
+
+(** The file used by the generators outputting only one file. *)
+val out_file : string ref
+
+(** Verbose mode or not. *)
+val verbose : bool ref
+
+(** The optional file whose content can be used as intro text. *)
+val intro_file : string option ref
+
+(** The optional title to use in the generated documentation. *)
+val title : string option ref
+
+(** The directory where files have to be generated. *)
+val target_dir : string ref
+
+(** The flag which indicates if we must generate a table of contents. *)
+val with_toc : bool ref
+
+(** The flag which indicates if we must generate an index. *)
+val with_index : bool ref
+
+(** The flag which indicates if we must generate a header.*)
+val with_header : bool ref
+
+(** The flag which indicates if we must generate a trailer.*)
+val with_trailer : bool ref
diff --git a/ocamldoc/odoc_html.ml b/ocamldoc/odoc_html.ml
new file mode 100644
index 0000000000..28f49c4abd
--- /dev/null
+++ b/ocamldoc/odoc_html.ml
@@ -0,0 +1,2810 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Generation of html documentation.*)
+
+let print_DEBUG s = print_string s ; print_newline ()
+
+open Odoc_info
+open Parameter
+open Value
+open Type
+open Extension
+open Exception
+open Class
+open Module
+
+let with_parameter_list = ref false
+let css_style = ref None
+let index_only = ref false
+let colorize_code = ref false
+let html_short_functors = ref false
+let charset = ref "iso-8859-1"
+
+
+(** The functions used for naming files and html marks.*)
+module Naming =
+ struct
+ (** The prefix for types marks. *)
+ let mark_type = "TYPE"
+
+ (** The prefix for types elements (record fields or constructors). *)
+ let mark_type_elt = "TYPEELT"
+
+ (** The prefix for functions marks. *)
+ let mark_function = "FUN"
+
+ (** The prefix for extensions marks. *)
+ let mark_extension = "EXTENSION"
+
+ (** The prefix for exceptions marks. *)
+ let mark_exception = "EXCEPTION"
+
+ (** The prefix for values marks. *)
+ let mark_value = "VAL"
+
+ (** The prefix for attributes marks. *)
+ let mark_attribute = "ATT"
+
+ (** The prefix for methods marks. *)
+ let mark_method = "METHOD"
+
+ (** The prefix for code files.. *)
+ let code_prefix = "code_"
+
+ (** The prefix for type files.. *)
+ let type_prefix = "type_"
+
+ (** Return the two html files names for the given module or class name.*)
+ let html_files name =
+ let qual =
+ try
+ let i = String.rindex name '.' in
+ match name.[i + 1] with
+ | 'A'..'Z' -> ""
+ | _ -> "-c"
+ with Not_found -> ""
+ in
+ let prefix = name^qual in
+ let html_file = prefix^".html" in
+ let html_frame_file = prefix^"-frame.html" in
+ (html_file, html_frame_file)
+
+ (** Return the target for the given prefix and simple name. *)
+ let target pref simple_name = pref^simple_name
+
+ (** Return the complete link target (file#target) for the given prefix string and complete name.*)
+ let complete_target pref complete_name =
+ let simple_name = Name.simple complete_name in
+ let module_name =
+ let s = Name.father complete_name in
+ if s = "" then simple_name else s
+ in
+ let (html_file, _) = html_files module_name in
+ html_file^"#"^(target pref simple_name)
+
+ (** Return the link target for the given type. *)
+ let type_target t = target mark_type (Name.simple t.ty_name)
+
+ (** Return the link target for the given variant constructor. *)
+ let const_target t f =
+ let name = Printf.sprintf "%s.%s" (Name.simple t.ty_name) f.vc_name in
+ target mark_type_elt name
+
+ (** Return the link target for the given record field. *)
+ let recfield_target t f = target mark_type_elt
+ (Printf.sprintf "%s.%s" (Name.simple t.ty_name) f.rf_name)
+
+ (** Return the link target for the given object field. *)
+ let objfield_target t f = target mark_type_elt
+ (Printf.sprintf "%s.%s" (Name.simple t.ty_name) f.of_name)
+
+ (** Return the complete link target for the given type. *)
+ let complete_type_target t = complete_target mark_type t.ty_name
+
+ let complete_recfield_target name =
+ let typ = Name.father name in
+ let field = Name.simple name in
+ Printf.sprintf "%s.%s" (complete_target mark_type_elt typ) field
+
+ let complete_const_target = complete_recfield_target
+
+ (** Return the link target for the given extension. *)
+ let extension_target x = target mark_extension (Name.simple x.xt_name)
+
+ (** Return the complete link target for the given extension. *)
+ let complete_extension_target x = complete_target mark_extension x.xt_name
+
+ (** Return the link target for the given exception. *)
+ let exception_target e = target mark_exception (Name.simple e.ex_name)
+
+ (** Return the complete link target for the given exception. *)
+ let complete_exception_target e = complete_target mark_exception e.ex_name
+
+ (** Return the link target for the given value. *)
+ let value_target v = target mark_value (Name.simple v.val_name)
+
+ (** Return the given value name where symbols accepted in infix values
+ are replaced by strings, to avoid clashes with the filesystem.*)
+ let subst_infix_symbols name =
+ let len = String.length name in
+ let buf = Buffer.create len in
+ let ch c = Buffer.add_char buf c in
+ let st s = Buffer.add_string buf s in
+ for i = 0 to len - 1 do
+ match name.[i] with
+ | '|' -> st "_pipe_"
+ | '<' -> st "_lt_"
+ | '>' -> st "_gt_"
+ | '@' -> st "_at_"
+ | '^' -> st "_exp_"
+ | '&' -> st "_amp_"
+ | '+' -> st "_plus_"
+ | '-' -> st "_minus_"
+ | '*' -> st "_star_"
+ | '/' -> st "_slash_"
+ | '$' -> st "_dollar_"
+ | '%' -> st "_percent_"
+ | '=' -> st "_equal_"
+ | ':' -> st "_column_"
+ | '~' -> st "_tilde_"
+ | '!' -> st "_bang_"
+ | '?' -> st "_questionmark_"
+ | c -> ch c
+ done;
+ Buffer.contents buf
+
+ (** Return the complete link target for the given value. *)
+ let complete_value_target v = complete_target mark_value v.val_name
+
+ (** Return the complete filename for the code of the given value. *)
+ let file_code_value_complete_target v =
+ let f = code_prefix^mark_value^(subst_infix_symbols v.val_name)^".html" in
+ f
+
+ (** Return the link target for the given attribute. *)
+ let attribute_target a = target mark_attribute (Name.simple a.att_value.val_name)
+
+ (** Return the complete link target for the given attribute. *)
+ let complete_attribute_target a = complete_target mark_attribute a.att_value.val_name
+
+ (** Return the complete filename for the code of the given attribute. *)
+ let file_code_attribute_complete_target a =
+ let f = code_prefix^mark_attribute^a.att_value.val_name^".html" in
+ f
+
+ (** Return the link target for the given method. *)
+ let method_target m = target mark_method (Name.simple m.met_value.val_name)
+
+ (** Return the complete link target for the given method. *)
+ let complete_method_target m = complete_target mark_method m.met_value.val_name
+
+ (** Return the complete filename for the code of the given method. *)
+ let file_code_method_complete_target m =
+ let f = code_prefix^mark_method^m.met_value.val_name^".html" in
+ f
+
+ (** Return the link target for the given label section. *)
+ let label_target l = target "" l
+
+ (** Return the complete link target for the given section label. *)
+ let complete_label_target l = complete_target "" l
+
+ (** Return the complete filename for the code of the type of the
+ given module or module type name. *)
+ let file_type_module_complete_target name =
+ let f = type_prefix^name^".html" in
+ f
+
+ (** Return the complete filename for the code of the
+ given module name. *)
+ let file_code_module_complete_target name =
+ let f = code_prefix^name^".html" in
+ f
+
+ (** Return the complete filename for the code of the type of the
+ given class or class type name. *)
+ let file_type_class_complete_target name =
+ let f = type_prefix^name^".html" in
+ f
+ end
+
+module StringSet = Set.Make (struct
+ type t = string
+ let compare (x:t) y = compare x y
+end)
+
+(** A class with a method to colorize a string which represents OCaml code. *)
+class ocaml_code =
+ object(self)
+ method html_of_code b ?(with_pre=true) code =
+ Odoc_ocamlhtml.html_of_code b ~with_pre: with_pre code
+ end
+
+let new_buf () = Buffer.create 1024
+let bp = Printf.bprintf
+let bs = Buffer.add_string
+
+
+(** Generation of html code from text structures. *)
+class virtual text =
+ object (self)
+ (** We want to display colorized code. *)
+ inherit ocaml_code
+
+ (** Escape the strings which would clash with html syntax, and
+ make some replacements (double newlines replaced by <br>). *)
+ method escape s = Odoc_ocamlhtml.escape_base s
+
+ method keep_alpha_num s =
+ let len = String.length s in
+ let buf = Buffer.create len in
+ for i = 0 to len - 1 do
+ match s.[i] with
+ 'a'..'z' | 'A'..'Z' | '0'..'9' -> Buffer.add_char buf s.[i]
+ | _ -> ()
+ done;
+ Buffer.contents buf
+
+ (** Return a label created from the first sentence of a text. *)
+ method label_of_text t=
+ let t2 = Odoc_info.first_sentence_of_text t in
+ let s = Odoc_info.string_of_text t2 in
+ let s2 = self#keep_alpha_num s in
+ s2
+
+ (** Create a label for the associated title.
+ Return the label specified by the user or a label created
+ from the title level and the first sentence of the title. *)
+ method create_title_label (n,label_opt,t) =
+ match label_opt with
+ Some s -> s
+ | None -> Printf.sprintf "%d_%s" n (self#label_of_text t)
+
+ (** Print the html code corresponding to the [text] parameter. *)
+ method html_of_text b t =
+ List.iter (self#html_of_text_element b) t
+
+ (** Print the html code for the [text_element] in parameter. *)
+ method html_of_text_element b txt =
+ print_DEBUG "text::html_of_text_element";
+ match txt with
+ | Odoc_info.Raw s -> self#html_of_Raw b s
+ | Odoc_info.Code s -> self#html_of_Code b s
+ | Odoc_info.CodePre s -> self#html_of_CodePre b s
+ | Odoc_info.Verbatim s -> self#html_of_Verbatim b s
+ | Odoc_info.Bold t -> self#html_of_Bold b t
+ | Odoc_info.Italic t -> self#html_of_Italic b t
+ | Odoc_info.Emphasize t -> self#html_of_Emphasize b t
+ | Odoc_info.Center t -> self#html_of_Center b t
+ | Odoc_info.Left t -> self#html_of_Left b t
+ | Odoc_info.Right t -> self#html_of_Right b t
+ | Odoc_info.List tl -> self#html_of_List b tl
+ | Odoc_info.Enum tl -> self#html_of_Enum b tl
+ | Odoc_info.Newline -> self#html_of_Newline b
+ | Odoc_info.Block t -> self#html_of_Block b t
+ | Odoc_info.Title (n, l_opt, t) -> self#html_of_Title b n l_opt t
+ | Odoc_info.Latex s -> self#html_of_Latex b s
+ | Odoc_info.Link (s, t) -> self#html_of_Link b s t
+ | Odoc_info.Ref (name, ref_opt, text_opt) ->
+ self#html_of_Ref b name ref_opt text_opt
+ | Odoc_info.Superscript t -> self#html_of_Superscript b t
+ | Odoc_info.Subscript t -> self#html_of_Subscript b t
+ | Odoc_info.Module_list l -> self#html_of_Module_list b l
+ | Odoc_info.Index_list -> self#html_of_Index_list b
+ | Odoc_info.Custom (s,t) -> self#html_of_custom_text b s t
+ | Odoc_info.Target (target, code) -> self#html_of_Target b ~target ~code
+
+ method html_of_custom_text b s t = ()
+
+ method html_of_Target b ~target ~code =
+ if String.lowercase_ascii target = "html" then bs b code else ()
+
+ method html_of_Raw b s = bs b (self#escape s)
+
+ method html_of_Code b s =
+ if !colorize_code then
+ self#html_of_code b ~with_pre: false s
+ else
+ (
+ bs b "<code class=\"";
+ bs b Odoc_ocamlhtml.code_class ;
+ bs b "\">";
+ bs b (self#escape s);
+ bs b "</code>"
+ )
+
+ method html_of_CodePre =
+ let remove_useless_newlines s =
+ let len = String.length s in
+ let rec iter_first n =
+ if n >= len then
+ None
+ else
+ match s.[n] with
+ | '\n' -> iter_first (n+1)
+ | _ -> Some n
+ in
+ match iter_first 0 with
+ None -> ""
+ | Some first ->
+ let rec iter_last n =
+ if n <= first then
+ None
+ else
+ match s.[n] with
+ '\t' -> iter_last (n-1)
+ | _ -> Some n
+ in
+ match iter_last (len-1) with
+ None -> String.sub s first 1
+ | Some last -> String.sub s first ((last-first)+1)
+ in
+ fun b s ->
+ if !colorize_code then
+ (
+ bs b "<pre class=\"codepre\">";
+ self#html_of_code b (remove_useless_newlines s);
+ bs b "</pre>"
+ )
+ else
+ (
+ bs b "<pre class=\"codepre\"><code class=\"";
+ bs b Odoc_ocamlhtml.code_class;
+ bs b "\">" ;
+ bs b (self#escape (remove_useless_newlines s));
+ bs b "</code></pre>"
+ )
+
+ method html_of_Verbatim b s =
+ bs b "<pre class=\"verbatim\">";
+ bs b (self#escape s);
+ bs b "</pre>"
+
+ method html_of_Bold b t =
+ bs b "<b>";
+ self#html_of_text b t;
+ bs b "</b>"
+
+ method html_of_Italic b t =
+ bs b "<i>" ;
+ self#html_of_text b t;
+ bs b "</i>"
+
+ method html_of_Emphasize b t =
+ bs b "<em>" ;
+ self#html_of_text b t ;
+ bs b "</em>"
+
+ method html_of_Center b t =
+ bs b "<center>";
+ self#html_of_text b t;
+ bs b "</center>"
+
+ method html_of_Left b t =
+ bs b "<div align=left>";
+ self#html_of_text b t;
+ bs b "</div>"
+
+ method html_of_Right b t =
+ bs b "<div align=right>";
+ self#html_of_text b t;
+ bs b "</div>"
+
+ method html_of_List b tl =
+ bs b "<ul>\n";
+ List.iter
+ (fun t -> bs b "<li>"; self#html_of_text b t; bs b "</li>\n")
+ tl;
+ bs b "</ul>\n"
+
+ method html_of_Enum b tl =
+ bs b "<OL>\n";
+ List.iter
+ (fun t -> bs b "<li>"; self#html_of_text b t; bs b"</li>\n")
+ tl;
+ bs b "</OL>\n"
+
+ method html_of_Newline b = bs b "\n<p>\n"
+
+ method html_of_Block b t =
+ bs b "<blockquote>\n";
+ self#html_of_text b t;
+ bs b "</blockquote>\n"
+
+ method html_of_Title b n label_opt t =
+ let label1 = self#create_title_label (n, label_opt, t) in
+ let (tag_o, tag_c) =
+ if n > 6 then
+ (Printf.sprintf "div class=\"h%d\"" n, "div")
+ else
+ let t = Printf.sprintf "h%d" n in (t, t)
+ in
+ bs b "<";
+ bp b "%s id=\"%s\"" tag_o (Naming.label_target label1);
+ bs b ">";
+ self#html_of_text b t;
+ bs b "</";
+ bs b tag_c;
+ bs b ">"
+
+ method html_of_Latex b _ = ()
+ (* don't care about LaTeX stuff in HTML. *)
+
+ method html_of_Link b s t =
+ bs b "<a href=\"";
+ bs b s ;
+ bs b "\">";
+ self#html_of_text b t;
+ bs b "</a>"
+
+ method html_of_Ref b name ref_opt text_opt =
+ match ref_opt with
+ None ->
+ let text =
+ match text_opt with
+ None -> [Odoc_info.Code name]
+ | Some t -> t
+ in
+ self#html_of_text b text
+ | Some kind ->
+ let h name = Odoc_info.Code (Odoc_info.use_hidden_modules name) in
+ let (target, text) =
+ match kind with
+ Odoc_info.RK_module
+ | Odoc_info.RK_module_type
+ | Odoc_info.RK_class
+ | Odoc_info.RK_class_type ->
+ let (html_file, _) = Naming.html_files name in
+ (html_file, h name)
+ | Odoc_info.RK_value -> (Naming.complete_target Naming.mark_value name, h name)
+ | Odoc_info.RK_type -> (Naming.complete_target Naming.mark_type name, h name)
+ | Odoc_info.RK_extension -> (Naming.complete_target Naming.mark_extension name, h name)
+ | Odoc_info.RK_exception -> (Naming.complete_target Naming.mark_exception name, h name)
+ | Odoc_info.RK_attribute -> (Naming.complete_target Naming.mark_attribute name, h name)
+ | Odoc_info.RK_method -> (Naming.complete_target Naming.mark_method name, h name)
+ | Odoc_info.RK_section t -> (Naming.complete_label_target name,
+ Odoc_info.Italic [Raw (Odoc_info.string_of_text t)])
+ | Odoc_info.RK_recfield -> (Naming.complete_recfield_target name, h name)
+ | Odoc_info.RK_const -> (Naming.complete_const_target name, h name)
+ in
+ let text =
+ match text_opt with
+ None -> [text]
+ | Some text -> text
+ in
+ bs b ("<a href=\""^target^"\">");
+ self#html_of_text b text;
+ bs b "</a>"
+
+ method html_of_Superscript b t =
+ bs b "<sup class=\"superscript\">";
+ self#html_of_text b t;
+ bs b "</sup>"
+
+ method html_of_Subscript b t =
+ bs b "<sub class=\"subscript\">";
+ self#html_of_text b t;
+ bs b "</sub>"
+
+ method virtual html_of_info_first_sentence : _
+
+ method html_of_Module_list b l =
+ bs b "<br>\n<table class=\"indextable\">\n";
+ List.iter
+ (fun name ->
+ bs b "<tr><td class=\"module\">";
+ (
+ try
+ let m =
+ List.find (fun m -> m.m_name = name) self#list_modules
+ in
+ let (html, _) = Naming.html_files m.m_name in
+ bp b "<a href=\"%s\">%s</a></td>" html m.m_name;
+ bs b "<td>";
+ self#html_of_info_first_sentence b m.m_info;
+ with
+ Not_found ->
+ Odoc_global.pwarning (Odoc_messages.cross_module_not_found name);
+ bp b "%s</td><td>" name
+ );
+ bs b "</td></tr>\n"
+ )
+ l;
+ bs b "</table>\n"
+
+ method html_of_Index_list b =
+ let index_if_not_empty l url m =
+ match l with
+ [] -> ()
+ | _ -> bp b "<li><a href=\"%s\">%s</a></li>\n" url m
+ in
+ bp b "<ul class=\"indexlist\">\n";
+ index_if_not_empty self#list_types self#index_types Odoc_messages.index_of_types;
+ index_if_not_empty self#list_extensions self#index_extensions Odoc_messages.index_of_extensions;
+ index_if_not_empty self#list_exceptions self#index_exceptions Odoc_messages.index_of_exceptions;
+ index_if_not_empty self#list_values self#index_values Odoc_messages.index_of_values;
+ index_if_not_empty self#list_attributes self#index_attributes Odoc_messages.index_of_attributes;
+ index_if_not_empty self#list_methods self#index_methods Odoc_messages.index_of_methods;
+ index_if_not_empty self#list_classes self#index_classes Odoc_messages.index_of_classes;
+ index_if_not_empty self#list_class_types self#index_class_types Odoc_messages.index_of_class_types;
+ index_if_not_empty self#list_modules self#index_modules Odoc_messages.index_of_modules;
+ index_if_not_empty self#list_module_types self#index_module_types Odoc_messages.index_of_module_types;
+ bp b "</ul>\n"
+
+ method virtual list_types : Odoc_info.Type.t_type list
+ method virtual index_types : string
+ method virtual list_extensions : Odoc_info.Extension.t_extension_constructor list
+ method virtual index_extensions : string
+ method virtual list_exceptions : Odoc_info.Exception.t_exception list
+ method virtual index_exceptions : string
+ method virtual list_values : Odoc_info.Value.t_value list
+ method virtual index_values : string
+ method virtual list_attributes : Odoc_info.Value.t_attribute list
+ method virtual index_attributes : string
+ method virtual list_methods : Odoc_info.Value.t_method list
+ method virtual index_methods : string
+ method virtual list_classes : Odoc_info.Class.t_class list
+ method virtual index_classes : string
+ method virtual list_class_types : Odoc_info.Class.t_class_type list
+ method virtual index_class_types : string
+ method virtual list_modules : Odoc_info.Module.t_module list
+ method virtual index_modules : string
+ method virtual list_module_types : Odoc_info.Module.t_module_type list
+ method virtual index_module_types : string
+
+ end
+
+(** A class used to generate html code for info structures. *)
+class virtual info =
+ object (self)
+ (** The list of pairs [(tag, f)] where [f] is a function taking
+ the [text] associated to [tag] and returning html code.
+ Add a pair here to handle a tag.*)
+ val mutable tag_functions = ([] : (string * (Odoc_info.text -> string)) list)
+
+ (** The method used to get html code from a [text]. *)
+ method virtual html_of_text : Buffer.t -> Odoc_info.text -> unit
+
+ (** Print html for an author list. *)
+ method html_of_author_list b l =
+ match l with
+ [] -> ()
+ | _ ->
+ bp b "<b>%s:</b> " Odoc_messages.authors;
+ self#html_of_text b [Raw (String.concat ", " l)];
+ bs b "<br>\n"
+
+ (** Print html code for the given optional version information.*)
+ method html_of_version_opt b v_opt =
+ match v_opt with
+ None -> ()
+ | Some v ->
+ bp b "<b>%s:</b> " Odoc_messages.version;
+ self#html_of_text b [Raw v];
+ bs b "<br>\n"
+
+ (** Print html code for the given optional since information.*)
+ method html_of_since_opt b s_opt =
+ match s_opt with
+ None -> ()
+ | Some s ->
+ bp b "<b>%s</b> " Odoc_messages.since;
+ self#html_of_text b [Raw s];
+ bs b "<br>\n"
+
+ (** Print html code for the given "before" information.*)
+ method html_of_before b l =
+ let f (v, text) =
+ bp b "<b>%s " Odoc_messages.before;
+ self#html_of_text b [Raw v];
+ bs b " </b> ";
+ self#html_of_text b text;
+ bs b "<br>\n"
+ in
+ List.iter f l
+
+ (** Print html code for the given list of raised exceptions.*)
+ method html_of_raised_exceptions b l =
+ match l with
+ [] -> ()
+ | (s, t) :: [] ->
+ bp b "<b>%s</b> <code>%s</code> "
+ Odoc_messages.raises
+ s;
+ self#html_of_text b t;
+ bs b "<br>\n"
+ | _ ->
+ bp b "<b>%s</b><ul>" Odoc_messages.raises;
+ List.iter
+ (fun (ex, desc) ->
+ bp b "<li><code>%s</code> " ex ;
+ self#html_of_text b desc;
+ bs b "</li>\n"
+ )
+ l;
+ bs b "</ul>\n"
+
+ (** Print html code for the given "see also" reference. *)
+ method html_of_see b (see_ref, t) =
+ let t_ref =
+ match see_ref with
+ Odoc_info.See_url s -> [ Odoc_info.Link (s, t) ]
+ | Odoc_info.See_file s -> (Odoc_info.Code s) :: (Odoc_info.Raw " ") :: t
+ | Odoc_info.See_doc s -> (Odoc_info.Italic [Odoc_info.Raw s]) :: (Odoc_info.Raw " ") :: t
+ in
+ self#html_of_text b t_ref
+
+ (** Print html code for the given list of "see also" references.*)
+ method html_of_sees b l =
+ match l with
+ [] -> ()
+ | see :: [] ->
+ bp b "<b>%s</b> " Odoc_messages.see_also;
+ self#html_of_see b see;
+ bs b "<br>\n"
+ | _ ->
+ bp b "<b>%s</b><ul>" Odoc_messages.see_also;
+ List.iter
+ (fun see ->
+ bs b "<li>" ;
+ self#html_of_see b see;
+ bs b "</li>\n"
+ )
+ l;
+ bs b "</ul>\n"
+
+ (** Print html code for the given optional return information.*)
+ method html_of_return_opt b return_opt =
+ match return_opt with
+ None -> ()
+ | Some s ->
+ bp b "<b>%s</b> " Odoc_messages.returns;
+ self#html_of_text b s;
+ bs b "<br>\n"
+
+ (** Print html code for the given list of custom tagged texts. *)
+ method html_of_custom b l =
+ List.iter
+ (fun (tag, text) ->
+ try
+ let f = List.assoc tag tag_functions in
+ Buffer.add_string b (f text)
+ with
+ Not_found ->
+ Odoc_info.warning (Odoc_messages.tag_not_handled tag)
+ )
+ l
+
+ (** Print html code for a description, except for the [i_params] field.
+ @param indent can be specified not to use the style of info comments;
+ default is [true].
+ *)
+ method html_of_info ?(cls="") ?(indent=true) b info_opt =
+ match info_opt with
+ None ->
+ ()
+ | Some info ->
+ let module M = Odoc_info in
+ if indent then bs b ("<div class=\"info "^cls^"\">\n");
+ (
+ match info.M.i_deprecated with
+ None -> ()
+ | Some d ->
+ bs b "<span class=\"warning\">";
+ bs b Odoc_messages.deprecated ;
+ bs b "</span>" ;
+ self#html_of_text b d;
+ bs b "<br>\n"
+ );
+ (
+ match info.M.i_desc with
+ None -> ()
+ | Some d when d = [Odoc_info.Raw ""] -> ()
+ | Some d -> self#html_of_text b d; bs b "<br>\n"
+ );
+ self#html_of_author_list b info.M.i_authors;
+ self#html_of_version_opt b info.M.i_version;
+ self#html_of_before b info.M.i_before;
+ self#html_of_since_opt b info.M.i_since;
+ self#html_of_raised_exceptions b info.M.i_raised_exceptions;
+ self#html_of_return_opt b info.M.i_return_value;
+ self#html_of_sees b info.M.i_sees;
+ self#html_of_custom b info.M.i_custom;
+ if indent then bs b "</div>\n"
+
+ (** Print html code for the first sentence of a description.
+ The titles and lists in this first sentence has been removed.*)
+ method html_of_info_first_sentence b info_opt =
+ match info_opt with
+ None -> ()
+ | Some info ->
+ let module M = Odoc_info in
+ let dep = info.M.i_deprecated <> None in
+ bs b "<div class=\"info\">\n";
+ if dep then bs b "<span class=\"deprecated\">";
+ (
+ match info.M.i_desc with
+ None -> ()
+ | Some d when d = [Odoc_info.Raw ""] -> ()
+ | Some d ->
+ self#html_of_text b
+ (Odoc_info.text_no_title_no_list
+ (Odoc_info.first_sentence_of_text d));
+ bs b "\n"
+ );
+ if dep then bs b "</span>";
+ bs b "</div>\n"
+
+ end
+
+
+
+let opt = Odoc_info.apply_opt
+
+let print_concat b sep f =
+ let rec iter = function
+ [] -> ()
+ | [c] -> f c
+ | c :: q ->
+ f c;
+ bs b sep;
+ iter q
+ in
+ iter
+
+let newline_to_indented_br s =
+ let len = String.length s in
+ let b = Buffer.create len in
+ for i = 0 to len - 1 do
+ match s.[i] with
+ '\n' -> Buffer.add_string b "<br> "
+ | c -> Buffer.add_char b c
+ done;
+ Buffer.contents b
+
+module Generator =
+ struct
+(** This class is used to create objects which can generate a simple html documentation. *)
+class html =
+ object (self)
+ inherit text
+ inherit info
+
+ val mutable doctype =
+ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
+ method character_encoding () =
+ Printf.sprintf
+ "<meta content=\"text/html; charset=%s\" http-equiv=\"Content-Type\">\n"
+ !charset
+
+ (** The default style options. *)
+ val mutable default_style_options =
+ [ ".keyword { font-weight : bold ; color : Red }" ;
+ ".keywordsign { color : #C04600 }" ;
+ ".superscript { font-size : 4 }" ;
+ ".subscript { font-size : 4 }" ;
+ ".comment { color : Green }" ;
+ ".constructor { color : Blue }" ;
+ ".type { color : #5C6585 }" ;
+ ".string { color : Maroon }" ;
+ ".warning { color : Red ; font-weight : bold }" ;
+ ".info { margin-left : 3em; margin-right: 3em }" ;
+ ".param_info { margin-top: 4px; margin-left : 3em; margin-right : 3em }" ;
+ ".code { color : #465F91 ; }" ;
+ ".typetable { border-style : hidden }" ;
+ ".paramstable { border-style : hidden ; padding: 5pt 5pt}" ;
+ "tr { background-color : White }" ;
+ "td.typefieldcomment { background-color : #FFFFFF ; font-size: smaller ;}" ;
+ "div.sig_block {margin-left: 2em}" ;
+ "*:target { background: yellow; }" ;
+
+ "body {font: 13px sans-serif; color: black; text-align: left; padding: 5px; margin: 0}";
+
+ "h1 { font-size : 20pt ; text-align: center; }" ;
+
+ "h2 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90BDFF ;"^
+ "padding: 2px; }" ;
+
+ "h3 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90DDFF ;"^
+ "padding: 2px; }" ;
+
+ "h4 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90EDFF ;"^
+ "padding: 2px; }" ;
+
+ "h5 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90FDFF ;"^
+ "padding: 2px; }" ;
+
+ "h6 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #90BDFF ; "^
+ "padding: 2px; }" ;
+
+ "div.h7 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #E0FFFF ; "^
+ "padding: 2px; }" ;
+
+ "div.h8 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #F0FFFF ; "^
+ "padding: 2px; }" ;
+
+ "div.h9 { font-size : 20pt ; border: 1px solid #000000; "^
+ "margin-top: 5px; margin-bottom: 2px;"^
+ "text-align: center; background-color: #FFFFFF ; "^
+ "padding: 2px; }" ;
+
+ "a {color: #416DFF; text-decoration: none}";
+ "a:hover {background-color: #ddd; text-decoration: underline}";
+ "pre { margin-bottom: 4px; font-family: monospace; }" ;
+ "pre.verbatim, pre.codepre { }";
+
+ ".indextable {border: 1px #ddd solid; border-collapse: collapse}";
+ ".indextable td, .indextable th {border: 1px #ddd solid; min-width: 80px}";
+ ".indextable td.module {background-color: #eee ; padding-left: 2px; padding-right: 2px}";
+ ".indextable td.module a {color: 4E6272; text-decoration: none; display: block; width: 100%}";
+ ".indextable td.module a:hover {text-decoration: underline; background-color: transparent}";
+ ".deprecated {color: #888; font-style: italic}" ;
+
+ ".indextable tr td div.info { margin-left: 2px; margin-right: 2px }" ;
+
+ "ul.indexlist { margin-left: 0; padding-left: 0;}";
+ "ul.indexlist li { list-style-type: none ; margin-left: 0; padding-left: 0; }";
+ ]
+
+ (** The style file for all pages. *)
+ val mutable style_file = "style.css"
+
+ (** The code to import the style. Initialized in [init_style]. *)
+ val mutable style = ""
+
+ (** The known types names.
+ Used to know if we must create a link to a type
+ when printing a type. *)
+ val mutable known_types_names = StringSet.empty
+
+ (** The known class and class type names.
+ Used to know if we must create a link to a class
+ or class type or not when printing a type. *)
+ val mutable known_classes_names = StringSet.empty
+
+ (** The known modules and module types names.
+ Used to know if we must create a link to a type or not
+ when printing a module type. *)
+ val mutable known_modules_names = StringSet.empty
+
+ method index_prefix =
+ if !Odoc_global.out_file = Odoc_messages.default_out_file then
+ "index"
+ else
+ Filename.basename !Odoc_global.out_file
+
+ (** The main file. *)
+ method index =
+ let p = self#index_prefix in
+ Printf.sprintf "%s.html" p
+
+ (** The file for the index of values. *)
+ method index_values = Printf.sprintf "%s_values.html" self#index_prefix
+ (** The file for the index of types. *)
+ method index_types = Printf.sprintf "%s_types.html" self#index_prefix
+ (** The file for the index of extensions. *)
+ method index_extensions = Printf.sprintf "%s_extensions.html" self#index_prefix
+ (** The file for the index of exceptions. *)
+ method index_exceptions = Printf.sprintf "%s_exceptions.html" self#index_prefix
+ (** The file for the index of attributes. *)
+ method index_attributes = Printf.sprintf "%s_attributes.html" self#index_prefix
+ (** The file for the index of methods. *)
+ method index_methods = Printf.sprintf "%s_methods.html" self#index_prefix
+ (** The file for the index of classes. *)
+ method index_classes = Printf.sprintf "%s_classes.html" self#index_prefix
+ (** The file for the index of class types. *)
+ method index_class_types = Printf.sprintf "%s_class_types.html" self#index_prefix
+ (** The file for the index of modules. *)
+ method index_modules = Printf.sprintf "%s_modules.html" self#index_prefix
+ (** The file for the index of module types. *)
+ method index_module_types = Printf.sprintf "%s_module_types.html" self#index_prefix
+
+
+ (** The list of attributes. Filled in the [generate] method. *)
+ val mutable list_attributes = []
+ method list_attributes = list_attributes
+ (** The list of methods. Filled in the [generate] method. *)
+ val mutable list_methods = []
+ method list_methods = list_methods
+ (** The list of values. Filled in the [generate] method. *)
+ val mutable list_values = []
+ method list_values = list_values
+ (** The list of extensions. Filled in the [generate] method. *)
+ val mutable list_extensions = []
+ method list_extensions = list_extensions
+ (** The list of exceptions. Filled in the [generate] method. *)
+ val mutable list_exceptions = []
+ method list_exceptions = list_exceptions
+ (** The list of types. Filled in the [generate] method. *)
+ val mutable list_types = []
+ method list_types = list_types
+ (** The list of modules. Filled in the [generate] method. *)
+ val mutable list_modules = []
+ method list_modules = list_modules
+ (** The list of module types. Filled in the [generate] method. *)
+ val mutable list_module_types = []
+ method list_module_types = list_module_types
+ (** The list of classes. Filled in the [generate] method. *)
+ val mutable list_classes = []
+ method list_classes = list_classes
+ (** The list of class types. Filled in the [generate] method. *)
+ val mutable list_class_types = []
+ method list_class_types = list_class_types
+
+ (** The header of pages. Must be prepared by the [prepare_header] method.*)
+ val mutable header = fun b -> fun ?(nav=None) -> fun ?(comments=[]) -> fun _ -> ()
+
+ (** Init the style. *)
+ method init_style =
+ (match !css_style with
+ None ->
+ let default_style = String.concat "\n" default_style_options in
+ (
+ try
+ let file = Filename.concat !Global.target_dir style_file in
+ if Sys.file_exists file then
+ Odoc_info.verbose (Odoc_messages.file_exists_dont_generate file)
+ else
+ (
+ let chanout = open_out file in
+ output_string chanout default_style ;
+ flush chanout ;
+ close_out chanout;
+ Odoc_info.verbose (Odoc_messages.file_generated file)
+ )
+ with
+ Sys_error s ->
+ prerr_endline s ;
+ incr Odoc_info.errors ;
+ )
+ | Some f ->
+ style_file <- f
+ );
+ style <- "<link rel=\"stylesheet\" href=\""^style_file^"\" type=\"text/css\">\n"
+
+ (** Get the title given by the user *)
+ method title = match !Global.title with None -> "" | Some t -> self#escape t
+
+ (** Get the title given by the user completed with the given subtitle. *)
+ method inner_title s =
+ (match self#title with "" -> "" | t -> t^" : ")^
+ (self#escape s)
+
+ (** Get the page header. *)
+ method print_header b ?nav ?comments title = header b ?nav ?comments title
+
+ (** A function to build the header of pages. *)
+ method prepare_header module_list =
+ let f b ?(nav=None) ?(comments=[]) t =
+ let link_if_not_empty l m url =
+ match l with
+ [] -> ()
+ | _ ->
+ bp b "<link title=\"%s\" rel=Appendix href=\"%s\">\n" m url
+ in
+ bs b "<head>\n";
+ bs b style;
+ bs b (self#character_encoding ()) ;
+ bs b "<link rel=\"Start\" href=\"";
+ bs b self#index;
+ bs b "\">\n" ;
+ (
+ match nav with
+ None -> ()
+ | Some (pre_opt, post_opt, name) ->
+ (match pre_opt with
+ None -> ()
+ | Some name ->
+ bp b "<link rel=\"previous\" href=\"%s\">\n"
+ (fst (Naming.html_files name));
+ );
+ (match post_opt with
+ None -> ()
+ | Some name ->
+ bp b "<link rel=\"next\" href=\"%s\">\n"
+ (fst (Naming.html_files name));
+ );
+ (
+ let father = Name.father name in
+ let href = if father = "" then self#index else fst (Naming.html_files father) in
+ bp b "<link rel=\"Up\" href=\"%s\">\n" href
+ )
+ );
+ link_if_not_empty self#list_types Odoc_messages.index_of_types self#index_types;
+ link_if_not_empty self#list_extensions Odoc_messages.index_of_extensions self#index_extensions;
+ link_if_not_empty self#list_exceptions Odoc_messages.index_of_exceptions self#index_exceptions;
+ link_if_not_empty self#list_values Odoc_messages.index_of_values self#index_values;
+ link_if_not_empty self#list_attributes Odoc_messages.index_of_attributes self#index_attributes;
+ link_if_not_empty self#list_methods Odoc_messages.index_of_methods self#index_methods;
+ link_if_not_empty self#list_classes Odoc_messages.index_of_classes self#index_classes;
+ link_if_not_empty self#list_class_types Odoc_messages.index_of_class_types self#index_class_types;
+ link_if_not_empty self#list_modules Odoc_messages.index_of_modules self#index_modules;
+ link_if_not_empty self#list_module_types Odoc_messages.index_of_module_types self#index_module_types;
+ let print_one m =
+ let html_file = fst (Naming.html_files m.m_name) in
+ bp b "<link title=\"%s\" rel=\"Chapter\" href=\"%s\">"
+ m.m_name html_file
+ in
+ print_concat b "\n" print_one module_list;
+ self#html_sections_links b comments;
+ bs b "<title>";
+ bs b t ;
+ bs b "</title>\n</head>\n"
+ in
+ header <- f
+
+ (** Build the html code for the link tags in the header, defining section and
+ subsections for the titles found in the given comments.*)
+ method html_sections_links b comments =
+ let titles = List.flatten (List.map Odoc_info.get_titles_in_text comments) in
+ let levels =
+ let rec iter acc l =
+ match l with
+ [] -> acc
+ | (n,_,_) :: q ->
+ if List.mem n acc
+ then iter acc q
+ else iter (n::acc) q
+ in
+ iter [] titles
+ in
+ let sorted_levels = List.sort compare levels in
+ let (section_level, subsection_level) =
+ match sorted_levels with
+ [] -> (None, None)
+ | [n] -> (Some n, None)
+ | n :: m :: _ -> (Some n, Some m)
+ in
+ let titles_per_level level_opt =
+ match level_opt with
+ None -> []
+ | Some n -> List.filter (fun (m,_,_) -> m = n) titles
+ in
+ let section_titles = titles_per_level section_level in
+ let subsection_titles = titles_per_level subsection_level in
+ let print_lines s_rel titles =
+ List.iter
+ (fun (n,lopt,t) ->
+ let s = Odoc_info.string_of_text t in
+ let label = self#create_title_label (n,lopt,t) in
+ bp b "<link title=\"%s\" rel=\"%s\" href=\"#%s\">\n" s s_rel label
+ )
+ titles
+ in
+ print_lines "Section" section_titles ;
+ print_lines "Subsection" subsection_titles
+
+
+ (** Html code for navigation bar.
+ @param pre optional name for optional previous module/class
+ @param post optional name for optional next module/class
+ @param name name of current module/class *)
+ method print_navbar b pre post name =
+ bs b "<div class=\"navbar\">";
+ (
+ match pre with
+ None -> ()
+ | Some name ->
+ bp b "<a class=\"pre\" href=\"%s\" title=\"%s\">%s</a>\n"
+ (fst (Naming.html_files name))
+ name
+ Odoc_messages.previous
+ );
+ bs b "&nbsp;";
+ let father = Name.father name in
+ let href = if father = "" then self#index else fst (Naming.html_files father) in
+ let father_name = if father = "" then "Index" else father in
+ bp b "<a class=\"up\" href=\"%s\" title=\"%s\">%s</a>\n" href father_name Odoc_messages.up;
+ bs b "&nbsp;";
+ (
+ match post with
+ None -> ()
+ | Some name ->
+ bp b "<a class=\"post\" href=\"%s\" title=\"%s\">%s</a>\n"
+ (fst (Naming.html_files name))
+ name
+ Odoc_messages.next
+ );
+ bs b "</div>\n"
+
+ (** Return html code with the given string in the keyword style.*)
+ method keyword s =
+ "<span class=\"keyword\">"^s^"</span>"
+
+ (** Return html code with the given string in the constructor style. *)
+ method constructor s = "<span class=\"constructor\">"^s^"</span>"
+
+ (** Output the given ocaml code to the given file name. *)
+ method private output_code in_title file code =
+ try
+ let chanout = open_out file in
+ let b = new_buf () in
+ bs b "<html>";
+ self#print_header b (self#inner_title in_title);
+ bs b"<body>\n";
+ self#html_of_code b code;
+ bs b "</body></html>";
+ Buffer.output_buffer chanout b;
+ close_out chanout
+ with
+ Sys_error s ->
+ incr Odoc_info.errors ;
+ prerr_endline s
+
+ (** Take a string and return the string where fully qualified
+ type (or class or class type) idents
+ have been replaced by links to the type referenced by the ident.*)
+ method create_fully_qualified_idents_links m_name s =
+ let f str_t =
+ let match_s = Str.matched_string str_t in
+ let rel = Name.get_relative m_name match_s in
+ let s_final = Odoc_info.apply_if_equal
+ Odoc_info.use_hidden_modules
+ match_s
+ rel
+ in
+ if StringSet.mem match_s known_types_names then
+ "<a href=\""^(Naming.complete_target Naming.mark_type match_s)^"\">"^
+ s_final^
+ "</a>"
+ else
+ if StringSet.mem match_s known_classes_names then
+ let (html_file, _) = Naming.html_files match_s in
+ "<a href=\""^html_file^"\">"^s_final^"</a>"
+ else
+ s_final
+ in
+ let s2 = Str.global_substitute
+ (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([a-z][a-zA-Z_'0-9]*\\)")
+ f
+ s
+ in
+ s2
+
+ (** Take a string and return the string where fully qualified module idents
+ have been replaced by links to the module referenced by the ident.*)
+ method create_fully_qualified_module_idents_links m_name s =
+ let f str_t =
+ let match_s = Str.matched_string str_t in
+ let rel = Name.get_relative m_name match_s in
+ let s_final = Odoc_info.apply_if_equal
+ Odoc_info.use_hidden_modules
+ match_s
+ rel
+ in
+ if StringSet.mem match_s known_modules_names then
+ let (html_file, _) = Naming.html_files match_s in
+ "<a href=\""^html_file^"\">"^s_final^"</a>"
+ else
+ s_final
+ in
+ let s2 = Str.global_substitute
+ (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\)\\(\\.[A-Z][a-zA-Z_'0-9]*\\)*")
+ f
+ s
+ in
+ s2
+
+ (** Print html code to display a [Types.type_expr]. *)
+ method html_of_type_expr b m_name t =
+ let s = Odoc_info.remove_ending_newline (Odoc_info.string_of_type_expr t) in
+ let s2 = newline_to_indented_br s in
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_idents_links m_name s2);
+ bs b "</code>"
+
+ (** Print html code to display a [Types.type_expr list]. *)
+ method html_of_cstr_args ?par b m_name sep l =
+ print_DEBUG "html#html_of_cstr_args";
+ let s =
+ match l with
+ | Cstr_tuple l ->
+ Odoc_info.string_of_type_list ?par sep l
+ | Cstr_record l ->
+ Odoc_info.string_of_record l
+ in
+ print_DEBUG "html#html_of_cstr_args: 1";
+ let s2 = newline_to_indented_br s in
+ print_DEBUG "html#html_of_cstr_args: 2";
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_idents_links m_name s2);
+ bs b "</code>"
+
+ (** Print html code to display a [Types.type_expr list] as type parameters
+ of a class of class type. *)
+ method html_of_class_type_param_expr_list b m_name l =
+ let s = Odoc_info.string_of_class_type_param_list l in
+ let s2 = newline_to_indented_br s in
+ bs b "<code class=\"type\">[";
+ bs b (self#create_fully_qualified_idents_links m_name s2);
+ bs b "]</code>"
+
+ method html_of_class_parameter_list b father c =
+ let s = Odoc_info.string_of_class_params c in
+ let s = Odoc_info.remove_ending_newline s in
+ let s2 = newline_to_indented_br s in
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_idents_links father s2);
+ bs b "</code>"
+
+ (** Print html code to display a list of type parameters for the given type.*)
+ method html_of_type_expr_param_list b m_name t =
+ let s = Odoc_info.string_of_type_param_list t in
+ let s2 = newline_to_indented_br s in
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_idents_links m_name s2);
+ bs b "</code>"
+
+ (** Print html code to display a [Types.module_type]. *)
+ method html_of_module_type b ?code m_name t =
+ let s = Odoc_info.remove_ending_newline (Odoc_info.string_of_module_type ?code t) in
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_module_idents_links m_name s);
+ bs b "</code>"
+
+ (** Print html code to display the given module kind. *)
+ method html_of_module_kind b father ?modu kind =
+ match kind with
+ Module_struct eles ->
+ self#html_of_text b [Code "sig"];
+ (
+ match modu with
+ None ->
+ bs b "<div class=\"sig_block\">";
+ List.iter (self#html_of_module_element b father) eles;
+ bs b "</div>"
+ | Some m ->
+ let (html_file, _) = Naming.html_files m.m_name in
+ bp b " <a href=\"%s\">..</a> " html_file
+ );
+ self#html_of_text b [Code "end"]
+ | Module_alias a ->
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_module_idents_links father a.ma_name);
+ bs b "</code>"
+ | Module_functor (p, k) ->
+ if !html_short_functors then
+ bs b " "
+ else
+ bs b "<div class=\"sig_block\">";
+ self#html_of_module_parameter b father p;
+ (
+ match k with
+ Module_functor _ -> ()
+ | _ when !html_short_functors ->
+ bs b ": "
+ | _ -> ()
+ );
+ self#html_of_module_kind b father ?modu k;
+ if not !html_short_functors then
+ bs b "</div>"
+ | Module_apply (k1, k2) ->
+ (* TODO: l'application n'est pas correcte dans un .mli.
+ Que faire ? -> afficher le module_type du typedtree *)
+ self#html_of_module_kind b father k1;
+ self#html_of_text b [Code "("];
+ self#html_of_module_kind b father k2;
+ self#html_of_text b [Code ")"]
+ | Module_with (k, s) ->
+ (* TODO: modify when Module_with will be more detailed *)
+ self#html_of_module_type_kind b father ?modu k;
+ bs b "<code class=\"type\"> ";
+ bs b (self#create_fully_qualified_module_idents_links father s);
+ bs b "</code>"
+ | Module_constraint (k, tk) ->
+ (* TODO: on affiche quoi ? *)
+ self#html_of_module_kind b father ?modu k
+ | Module_typeof s ->
+ bs b "<code class=\"type\">module type of ";
+ bs b (self#create_fully_qualified_module_idents_links father s);
+ bs b "</code>"
+ | Module_unpack (code, mta) ->
+ bs b "<code class=\"type\">";
+ begin
+ match mta.mta_module with
+ None ->
+ bs b (self#create_fully_qualified_module_idents_links father (self#escape code))
+ | Some mt ->
+ let (html_file, _) = Naming.html_files mt.mt_name in
+ bp b " <a href=\"%s\">%s</a> " html_file (self#escape code)
+ end;
+ bs b "</code>"
+
+
+ method html_of_module_parameter b father p =
+ let (s_functor,s_arrow) =
+ if !html_short_functors then
+ "", ""
+ else
+ "functor ", "-> "
+ in
+ self#html_of_text b
+ [
+ Code (s_functor^"(");
+ Code p.mp_name ;
+ Code " : ";
+ ] ;
+ self#html_of_module_type_kind b father p.mp_kind;
+ self#html_of_text b [ Code (") "^s_arrow)]
+
+ method html_of_module_element b m_name ele =
+ match ele with
+ Element_module m ->
+ self#html_of_module b ~complete: false m
+ | Element_module_type mt ->
+ self#html_of_modtype b ~complete: false mt
+ | Element_included_module im ->
+ self#html_of_included_module b im
+ | Element_class c ->
+ self#html_of_class b ~complete: false c
+ | Element_class_type ct ->
+ self#html_of_class_type b ~complete: false ct
+ | Element_value v ->
+ self#html_of_value b v
+ | Element_type_extension te ->
+ self#html_of_type_extension b m_name te
+ | Element_exception e ->
+ self#html_of_exception b e
+ | Element_type t ->
+ self#html_of_type b t
+ | Element_module_comment text ->
+ self#html_of_module_comment b text
+
+ (** Print html code to display the given module type kind. *)
+ method html_of_module_type_kind b father ?modu ?mt kind =
+ match kind with
+ Module_type_struct eles ->
+ self#html_of_text b [Code "sig"];
+ (
+ match mt with
+ None ->
+ (
+ match modu with
+ None ->
+ bs b "<div class=\"sig_block\">";
+ List.iter (self#html_of_module_element b father) eles;
+ bs b "</div>"
+ | Some m ->
+ let (html_file, _) = Naming.html_files m.m_name in
+ bp b " <a href=\"%s\">..</a> " html_file
+ )
+ | Some mt ->
+ let (html_file, _) = Naming.html_files mt.mt_name in
+ bp b " <a href=\"%s\">..</a> " html_file
+ );
+ self#html_of_text b [Code "end"]
+ | Module_type_functor (p, k) ->
+ self#html_of_module_parameter b father p;
+ self#html_of_module_type_kind b father ?modu ?mt k
+ | Module_type_alias a ->
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_module_idents_links father a.mta_name);
+ bs b "</code>"
+ | Module_type_with (k, s) ->
+ self#html_of_module_type_kind b father ?modu ?mt k;
+ bs b "<code class=\"type\"> ";
+ bs b (self#create_fully_qualified_module_idents_links father s);
+ bs b "</code>"
+ | Module_type_typeof s ->
+ bs b "<code class=\"type\">module type of ";
+ bs b (self#create_fully_qualified_module_idents_links father s);
+ bs b "</code>"
+
+ (** Print html code to display the type of a module parameter.. *)
+ method html_of_module_parameter_type b m_name p =
+ match p.mp_type with None -> bs b "<code>()</code>"
+ | Some mty -> self#html_of_module_type b m_name ~code: p.mp_type_code mty
+
+ (** Generate a file containing the module type in the given file name. *)
+ method output_module_type in_title file mtyp =
+ let s = Odoc_info.remove_ending_newline (Odoc_info.string_of_module_type ~complete: true mtyp) in
+ self#output_code in_title file s
+
+ (** Generate a file containing the class type in the given file name. *)
+ method output_class_type in_title file ctyp =
+ let s = Odoc_info.remove_ending_newline (Odoc_info.string_of_class_type ~complete: true ctyp) in
+ self#output_code in_title file s
+
+ (** Print html code for a value. *)
+ method html_of_value b v =
+ Odoc_info.reset_type_names ();
+ bs b "\n<pre>" ;
+ bp b "<span id=\"%s\">" (Naming.value_target v);
+ bs b (self#keyword "val");
+ bs b " ";
+ (
+ match v.val_code with
+ None -> bs b (self#escape (Name.simple v.val_name))
+ | Some c ->
+ let file = Naming.file_code_value_complete_target v in
+ self#output_code v.val_name (Filename.concat !Global.target_dir file) c;
+ bp b "<a href=\"%s\">%s</a>" file (self#escape (Name.simple v.val_name))
+ );
+ bs b "</span>";
+ bs b " : ";
+ self#html_of_type_expr b (Name.father v.val_name) v.val_type;
+ bs b "</pre>";
+ self#html_of_info b v.val_info;
+ (
+ if !with_parameter_list then
+ self#html_of_parameter_list b (Name.father v.val_name) v.val_parameters
+ else
+ self#html_of_described_parameter_list b (Name.father v.val_name) v.val_parameters
+ )
+
+ (** Print html code for a type extension. *)
+ method html_of_type_extension b m_name te =
+ Odoc_info.reset_type_names ();
+ bs b "<pre><code>";
+ bs b ((self#keyword "type")^" ");
+ let s = Odoc_info.string_of_type_extension_param_list te in
+ let s2 = newline_to_indented_br s in
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_idents_links m_name s2);
+ bs b "</code>";
+ (match te.te_type_parameters with [] -> () | _ -> bs b " ");
+ bs b (self#create_fully_qualified_idents_links m_name te.te_type_name);
+ bs b " += ";
+ if te.te_private = Asttypes.Private then bs b "private ";
+ bs b "</code></pre>";
+ bs b "<table class=\"typetable\">\n";
+ let print_one x =
+ let father = Name.father x.xt_name in
+ bs b "<tr>\n<td align=\"left\" valign=\"top\" >\n";
+ bs b "<code>";
+ bs b (self#keyword "|");
+ bs b "</code></td>\n<td align=\"left\" valign=\"top\" >\n";
+ bs b "<code>";
+ bp b "<span id=\"%s\">%s</span>"
+ (Naming.extension_target x)
+ (Name.simple x.xt_name);
+ (
+ match x.xt_args, x.xt_ret with
+ Cstr_tuple [], None -> ()
+ | l,None ->
+ bs b (" " ^ (self#keyword "of") ^ " ");
+ self#html_of_cstr_args ~par: false b father " * " l;
+ | Cstr_tuple [],Some r ->
+ bs b (" " ^ (self#keyword ":") ^ " ");
+ self#html_of_type_expr b father r;
+ | l,Some r ->
+ bs b (" " ^ (self#keyword ":") ^ " ");
+ self#html_of_cstr_args ~par: false b father " * " l;
+ bs b (" " ^ (self#keyword "->") ^ " ");
+ self#html_of_type_expr b father r;
+ );
+ (
+ match x.xt_alias with
+ None -> ()
+ | Some xa ->
+ bs b " = ";
+ (
+ match xa.xa_xt with
+ None -> bs b xa.xa_name
+ | Some x ->
+ bp b "<a href=\"%s\">%s</a>" (Naming.complete_extension_target x) x.xt_name
+ )
+ );
+ bs b "</code></td>\n";
+ (
+ match x.xt_text with
+ None -> ()
+ | Some t ->
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"top\" >";
+ bs b "<code>";
+ bs b "(*";
+ bs b "</code></td>";
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"top\" >";
+ self#html_of_info b (Some t);
+ bs b "</td>";
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"bottom\" >";
+ bs b "<code>";
+ bs b "*)";
+ bs b "</code></td>";
+ );
+ bs b "\n</tr>"
+ in
+ print_concat b "\n" print_one te.te_constructors;
+ bs b "</table>\n";
+ bs b "\n";
+ self#html_of_info b te.te_info;
+ bs b "\n"
+
+ (** Print html code for an exception. *)
+ method html_of_exception b e =
+ Odoc_info.reset_type_names ();
+ bs b "\n<pre>";
+ bp b "<span id=\"%s\">" (Naming.exception_target e);
+ bs b (self#keyword "exception");
+ bs b " ";
+ bs b (Name.simple e.ex_name);
+ bs b "</span>";
+ (
+ match e.ex_args, e.ex_ret with
+ Cstr_tuple [], None -> ()
+ | l,None ->
+ bs b (" "^(self#keyword "of")^" ");
+ self#html_of_cstr_args
+ ~par: false b (Name.father e.ex_name) " * " e.ex_args
+ | Cstr_tuple [],Some r ->
+ bs b (" " ^ (self#keyword ":") ^ " ");
+ self#html_of_type_expr b (Name.father e.ex_name) r;
+ | l,Some r ->
+ bs b (" " ^ (self#keyword ":") ^ " ");
+ self#html_of_cstr_args
+ ~par: false b (Name.father e.ex_name) " * " l;
+ bs b (" " ^ (self#keyword "->") ^ " ");
+ self#html_of_type_expr b (Name.father e.ex_name) r;
+ );
+ (
+ match e.ex_alias with
+ None -> ()
+ | Some ea ->
+ bs b " = ";
+ (
+ match ea.ea_ex with
+ None -> bs b ea.ea_name
+ | Some e ->
+ bp b "<a href=\"%s\">%s</a>" (Naming.complete_exception_target e) e.ex_name
+ )
+ );
+ bs b "</pre>\n";
+ self#html_of_info b e.ex_info
+
+ (** Print html code for a type. *)
+ method html_of_type b t =
+ Odoc_info.reset_type_names ();
+ let father = Name.father t.ty_name in
+ let print_field_prefix () =
+ bs b "<tr>\n<td align=\"left\" valign=\"top\" >\n";
+ bs b "<code>&nbsp;&nbsp;</code>";
+ bs b "</td>\n<td align=\"left\" valign=\"top\" >\n";
+ bs b "<code>";
+ in
+ let print_field_comment = function
+ | None -> ()
+ | Some t ->
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"top\" >";
+ bs b "<code>";
+ bs b "(*";
+ bs b "</code></td>";
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"top\" >";
+ self#html_of_info b (Some t);
+ bs b "</td><td class=\"typefieldcomment\" align=\"left\" valign=\"bottom\" >";
+ bs b "<code>*)</code></td>"
+ in
+ bs b
+ (match t.ty_manifest, t.ty_kind with
+ None, Type_abstract
+ | None, Type_open -> "\n<pre>"
+ | None, Type_variant _
+ | None, Type_record _ -> "\n<pre><code>"
+ | Some _, Type_abstract
+ | Some _, Type_open -> "\n<pre>"
+ | Some _, Type_variant _
+ | Some _, Type_record _ -> "\n<pre>"
+ );
+ bp b "<span id=\"%s\">" (Naming.type_target t);
+ bs b ((self#keyword "type")^" ");
+ self#html_of_type_expr_param_list b father t;
+ (match t.ty_parameters with [] -> () | _ -> bs b " ");
+ bs b (Name.simple t.ty_name);
+ bs b "</span> ";
+ let priv = t.ty_private = Asttypes.Private in
+ (
+ match t.ty_manifest with
+ None -> ()
+ | Some (Object_type fields) ->
+ bs b "= ";
+ if priv then bs b "private ";
+ bs b "&lt;</pre>";
+ bs b "<table class=\"typetable\">\n" ;
+ let print_one f =
+ print_field_prefix () ;
+ bp b "<span id=\"%s\">%s</span>&nbsp;: "
+ (Naming.objfield_target t f)
+ f.of_name;
+ self#html_of_type_expr b father f.of_type;
+ bs b ";</code></td>\n";
+ print_field_comment f.of_text ;
+ bs b "\n</tr>"
+ in
+ print_concat b "\n" print_one fields;
+ bs b "</table>\n>\n";
+ bs b " "
+ | Some (Other typ) ->
+ bs b "= ";
+ if priv then bs b "private ";
+ self#html_of_type_expr b father typ;
+ bs b " "
+ );
+ (match t.ty_kind with
+ Type_abstract -> bs b "</pre>"
+ | Type_variant l ->
+ bs b "= ";
+ if priv then bs b "private ";
+ bs b
+ (
+ match t.ty_manifest with
+ None -> "</code></pre>"
+ | Some _ -> "</pre>"
+ );
+ bs b "<table class=\"typetable\">\n";
+ let print_one constr =
+ bs b "<tr>\n<td align=\"left\" valign=\"top\" >\n";
+ bs b "<code>";
+ bs b (self#keyword "|");
+ bs b "</code></td>\n<td align=\"left\" valign=\"top\" >\n";
+ bs b "<code>";
+ bp b "<span id=\"%s\">%s</span>"
+ (Naming.const_target t constr)
+ (self#constructor constr.vc_name);
+ (
+ match constr.vc_args, constr.vc_ret with
+ Cstr_tuple [], None -> ()
+ | l,None ->
+ bs b (" " ^ (self#keyword "of") ^ " ");
+ self#html_of_cstr_args ~par: false b father " * " l;
+ | Cstr_tuple [],Some r ->
+ bs b (" " ^ (self#keyword ":") ^ " ");
+ self#html_of_type_expr b father r;
+ | l,Some r ->
+ bs b (" " ^ (self#keyword ":") ^ " ");
+ self#html_of_cstr_args ~par: false b father " * " l;
+ bs b (" " ^ (self#keyword "->") ^ " ");
+ self#html_of_type_expr b father r;
+ );
+ bs b "</code></td>\n";
+ (
+ match constr.vc_text with
+ None -> ()
+ | Some t ->
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"top\" >";
+ bs b "<code>";
+ bs b "(*";
+ bs b "</code></td>";
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"top\" >";
+ self#html_of_info b (Some t);
+ bs b "</td>";
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"bottom\" >";
+ bs b "<code>";
+ bs b "*)";
+ bs b "</code></td>";
+ );
+ bs b "\n</tr>"
+ in
+ print_concat b "\n" print_one l;
+ bs b "</table>\n"
+
+ | Type_record l ->
+ bs b "= ";
+ if priv then bs b "private " ;
+ bs b "{";
+ bs b
+ (
+ match t.ty_manifest with
+ None -> "</code></pre>"
+ | Some _ -> "</pre>"
+ );
+ bs b "<table class=\"typetable\">\n" ;
+ let print_one r =
+ bs b "<tr>\n<td align=\"left\" valign=\"top\" >\n";
+ bs b "<code>&nbsp;&nbsp;</code>";
+ bs b "</td>\n<td align=\"left\" valign=\"top\" >\n";
+ bs b "<code>";
+ if r.rf_mutable then bs b (self#keyword "mutable&nbsp;") ;
+ bp b "<span id=\"%s\">%s</span>&nbsp;: "
+ (Naming.recfield_target t r)
+ r.rf_name;
+ self#html_of_type_expr b father r.rf_type;
+ bs b ";</code></td>\n";
+ (
+ match r.rf_text with
+ None -> ()
+ | Some t ->
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"top\" >";
+ bs b "<code>";
+ bs b "(*";
+ bs b "</code></td>";
+ bs b "<td class=\"typefieldcomment\" align=\"left\" valign=\"top\" >";
+ self#html_of_info b (Some t);
+ bs b "</td><td class=\"typefieldcomment\" align=\"left\" valign=\"bottom\" >";
+ bs b "<code>*)</code></td>";
+ );
+ bs b "\n</tr>"
+ in
+ print_concat b "\n" print_one l;
+ bs b "</table>\n}\n"
+ | Type_open ->
+ bs b "= ..";
+ bs b "</pre>"
+ );
+ bs b "\n";
+ self#html_of_info b t.ty_info;
+ bs b "\n"
+
+ (** Print html code for a class attribute. *)
+ method html_of_attribute b a =
+ let module_name = Name.father (Name.father a.att_value.val_name) in
+ bs b "\n<pre>" ;
+ bp b "<span id=\"%s\">" (Naming.attribute_target a);
+ bs b (self#keyword "val");
+ bs b " ";
+ (
+ if a.att_virtual then
+ bs b ((self#keyword "virtual")^ " ")
+ else
+ ()
+ );
+ (
+ if a.att_mutable then
+ bs b ((self#keyword Odoc_messages.mutab)^ " ")
+ else
+ ()
+ );(
+ match a.att_value.val_code with
+ None -> bs b (Name.simple a.att_value.val_name)
+ | Some c ->
+ let file = Naming.file_code_attribute_complete_target a in
+ self#output_code a.att_value.val_name (Filename.concat !Global.target_dir file) c;
+ bp b "<a href=\"%s\">%s</a>" file (Name.simple a.att_value.val_name);
+ );
+ bs b "</span>";
+ bs b " : ";
+ self#html_of_type_expr b module_name a.att_value.val_type;
+ bs b "</pre>";
+ self#html_of_info b a.att_value.val_info
+
+ (** Print html code for a class method. *)
+ method html_of_method b m =
+ let module_name = Name.father (Name.father m.met_value.val_name) in
+ bs b "\n<pre>";
+ (* html mark *)
+ bp b "<span id=\"%s\">" (Naming.method_target m);
+ bs b ((self#keyword "method")^" ");
+ if m.met_private then bs b ((self#keyword "private")^" ");
+ if m.met_virtual then bs b ((self#keyword "virtual")^" ");
+ (
+ match m.met_value.val_code with
+ None -> bs b (Name.simple m.met_value.val_name)
+ | Some c ->
+ let file = Naming.file_code_method_complete_target m in
+ self#output_code m.met_value.val_name (Filename.concat !Global.target_dir file) c;
+ bp b "<a href=\"%s\">%s</a>" file (Name.simple m.met_value.val_name);
+ );
+ bs b "</span>";
+ bs b " : ";
+ self#html_of_type_expr b module_name m.met_value.val_type;
+ bs b "</pre>";
+ self#html_of_info b m.met_value.val_info;
+ (
+ if !with_parameter_list then
+ self#html_of_parameter_list b
+ module_name m.met_value.val_parameters
+ else
+ self#html_of_described_parameter_list b
+ module_name m.met_value.val_parameters
+ )
+
+ (** Print html code for the description of a function parameter. *)
+ method html_of_parameter_description b p =
+ match Parameter.names p with
+ [] ->
+ ()
+ | name :: [] ->
+ (
+ (* Only one name, no need for label for the description. *)
+ match Parameter.desc_by_name p name with
+ None -> ()
+ | Some t -> self#html_of_text b t
+ )
+ | l ->
+ (* A list of names, we display those with a description. *)
+ let l2 = List.filter
+ (fun n -> (Parameter.desc_by_name p n) <> None)
+ l
+ in
+ let print_one n =
+ match Parameter.desc_by_name p n with
+ None -> ()
+ | Some t ->
+ bs b "<code>";
+ bs b n;
+ bs b "</code> : ";
+ self#html_of_text b t
+ in
+ print_concat b "<br>\n" print_one l2
+
+ (** Print html code for a list of parameters. *)
+ method html_of_parameter_list b m_name l =
+ match l with
+ [] -> ()
+ | _ ->
+ bs b "<div class=\"param_info\">";
+ bs b "<table border=\"0\" cellpadding=\"3\" width=\"100%\">\n";
+ bs b "<tr>\n<td align=\"left\" valign=\"top\" width=\"1%\">";
+ bs b "<b>";
+ bs b Odoc_messages.parameters;
+ bs b ": </b></td>\n" ;
+ bs b "<td>\n<table class=\"paramstable\">\n";
+ let print_one p =
+ bs b "<tr>\n<td align=\"center\" valign=\"top\" width=\"15%\" class=\"code\">\n";
+ bs b
+ (
+ match Parameter.complete_name p with
+ "" -> "?"
+ | s -> s
+ );
+ bs b "</td>\n<td align=\"center\" valign=\"top\">:</td>\n";
+ bs b "<td>";
+ self#html_of_type_expr b m_name (Parameter.typ p);
+ bs b "<br>\n";
+ self#html_of_parameter_description b p;
+ bs b "\n</tr>\n";
+ in
+ List.iter print_one l;
+ bs b "</table>\n</td>\n</tr>\n</table></div>\n"
+
+ (** Print html code for the parameters which have a name and description. *)
+ method html_of_described_parameter_list b m_name l =
+ (* get the params which have a name, and at least one name described. *)
+ let l2 = List.filter
+ (fun p ->
+ List.exists
+ (fun n -> (Parameter.desc_by_name p n) <> None)
+ (Parameter.names p))
+ l
+ in
+ let f p =
+ bs b "<div class=\"param_info\"><code class=\"code\">";
+ bs b (Parameter.complete_name p);
+ bs b "</code> : " ;
+ self#html_of_parameter_description b p;
+ bs b "</div>\n"
+ in
+ List.iter f l2
+
+ (** Print html code for a list of module parameters. *)
+ method html_of_module_parameter_list b m_name l =
+ match l with
+ [] ->
+ ()
+ | _ ->
+ bs b "<table border=\"0\" cellpadding=\"3\" width=\"100%\">\n";
+ bs b "<tr>\n";
+ bs b "<td align=\"left\" valign=\"top\" width=\"1%%\"><b>";
+ bs b Odoc_messages.parameters ;
+ bs b ": </b></td>\n<td>\n";
+ bs b "<table class=\"paramstable\">\n";
+ List.iter
+ (fun (p, desc_opt) ->
+ bs b "<tr>\n";
+ bs b "<td align=\"center\" valign=\"top\" width=\"15%\">\n<code>" ;
+ bs b p.mp_name;
+ bs b "</code></td>\n" ;
+ bs b "<td align=\"center\" valign=\"top\">:</td>\n";
+ bs b "<td>" ;
+ self#html_of_module_parameter_type b m_name p;
+ bs b "\n";
+ (
+ match desc_opt with
+ None -> ()
+ | Some t ->
+ bs b "<br>";
+ self#html_of_text b t;
+ bs b "\n</tr>\n" ;
+ )
+ )
+ l;
+ bs b "</table>\n</td>\n</tr>\n</table>\n"
+
+ (** Print html code for a module. *)
+ method html_of_module b ?(info=true) ?(complete=true) ?(with_link=true) m =
+ let (html_file, _) = Naming.html_files m.m_name in
+ let father = Name.father m.m_name in
+ bs b "\n<pre>";
+ bs b ((self#keyword "module")^" ");
+ (
+ if with_link then
+ bp b "<a href=\"%s\">%s</a>" html_file (Name.simple m.m_name)
+ else
+ bs b (Name.simple m.m_name)
+ );
+ (
+ match m.m_kind with
+ Module_functor _ when !html_short_functors ->
+ ()
+ | _ -> bs b ": "
+ );
+ self#html_of_module_kind b father ~modu: m m.m_kind;
+ bs b "</pre>";
+ if info then
+ (
+ if complete then
+ self#html_of_info ~cls: "module top" ~indent: true
+ else
+ self#html_of_info_first_sentence
+ ) b m.m_info
+ else
+ ()
+
+ (** Print html code for a module type. *)
+ method html_of_modtype b ?(info=true) ?(complete=true) ?(with_link=true) mt =
+ let (html_file, _) = Naming.html_files mt.mt_name in
+ let father = Name.father mt.mt_name in
+ bs b "\n<pre>";
+ bs b ((self#keyword "module type")^" ");
+ (
+ if with_link then
+ bp b "<a href=\"%s\">%s</a>" html_file (Name.simple mt.mt_name)
+ else
+ bs b (Name.simple mt.mt_name)
+ );
+ (match mt.mt_kind with
+ None -> ()
+ | Some k ->
+ bs b " = ";
+ self#html_of_module_type_kind b father ~mt k
+ );
+ bs b "</pre>";
+ if info then
+ (
+ if complete then
+ self#html_of_info ~cls: "modtype top" ~indent: true
+ else
+ self#html_of_info_first_sentence
+ ) b mt.mt_info
+ else
+ ()
+
+ (** Print html code for an included module. *)
+ method html_of_included_module b im =
+ bs b "\n<pre>";
+ bs b ((self#keyword "include")^" ");
+ (
+ match im.im_module with
+ None ->
+ bs b im.im_name
+ | Some mmt ->
+ let (file, name) =
+ match mmt with
+ Mod m ->
+ let (html_file, _) = Naming.html_files m.m_name in
+ (html_file, m.m_name)
+ | Modtype mt ->
+ let (html_file, _) = Naming.html_files mt.mt_name in
+ (html_file, mt.mt_name)
+ in
+ bp b "<a href=\"%s\">%s</a>" file name
+ );
+ bs b "</pre>\n";
+ self#html_of_info b im.im_info
+
+ method html_of_class_element b element =
+ match element with
+ Class_attribute a ->
+ self#html_of_attribute b a
+ | Class_method m ->
+ self#html_of_method b m
+ | Class_comment t ->
+ self#html_of_class_comment b t
+
+ method html_of_class_kind b father ?cl kind =
+ match kind with
+ Class_structure (inh, eles) ->
+ self#html_of_text b [Code "object"];
+ (
+ match cl with
+ None ->
+ bs b "\n";
+ (
+ match inh with
+ [] -> ()
+ | _ ->
+ self#generate_inheritance_info b inh
+ );
+ List.iter (self#html_of_class_element b) eles;
+ | Some cl ->
+ let (html_file, _) = Naming.html_files cl.cl_name in
+ bp b " <a href=\"%s\">..</a> " html_file
+ );
+ self#html_of_text b [Code "end"]
+
+ | Class_apply capp ->
+ (* TODO: display final type from typedtree *)
+ self#html_of_text b [Raw "class application not handled yet"]
+
+ | Class_constr cco ->
+ (
+ match cco.cco_type_parameters with
+ [] -> ()
+ | l ->
+ self#html_of_class_type_param_expr_list b father l;
+ bs b " "
+ );
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_idents_links father cco.cco_name);
+ bs b "</code>"
+
+ | Class_constraint (ck, ctk) ->
+ self#html_of_text b [Code "( "] ;
+ self#html_of_class_kind b father ck;
+ self#html_of_text b [Code " : "] ;
+ self#html_of_class_type_kind b father ctk;
+ self#html_of_text b [Code " )"]
+
+ method html_of_class_type_kind b father ?ct kind =
+ match kind with
+ Class_type cta ->
+ (
+ match cta.cta_type_parameters with
+ [] -> ()
+ | l ->
+ self#html_of_class_type_param_expr_list b father l;
+ bs b " "
+ );
+ bs b "<code class=\"type\">";
+ bs b (self#create_fully_qualified_idents_links father cta.cta_name);
+ bs b "</code>"
+
+ | Class_signature (inh, eles) ->
+ self#html_of_text b [Code "object"];
+ (
+ match ct with
+ None ->
+ bs b "\n";
+ (
+ match inh with
+ [] -> ()
+ | _ -> self#generate_inheritance_info b inh
+ );
+ List.iter (self#html_of_class_element b) eles
+ | Some ct ->
+ let (html_file, _) = Naming.html_files ct.clt_name in
+ bp b " <a href=\"%s\">..</a> " html_file
+ );
+ self#html_of_text b [Code "end"]
+
+ (** Print html code for a class. *)
+ method html_of_class b ?(complete=true) ?(with_link=true) c =
+ let father = Name.father c.cl_name in
+ Odoc_info.reset_type_names ();
+ let (html_file, _) = Naming.html_files c.cl_name in
+ bs b "\n<pre>";
+ (* we add a html id, the same as for a type so we can
+ go directly here when the class name is used as a type name *)
+ bp b "<span name=\"%s\">"
+ (Naming.type_target
+ { ty_name = c.cl_name ;
+ ty_info = None ; ty_parameters = [] ;
+ ty_kind = Type_abstract ; ty_private = Asttypes.Public; ty_manifest = None ;
+ ty_loc = Odoc_info.dummy_loc ;
+ ty_code = None ;
+ }
+ );
+ bs b ((self#keyword "class")^" ");
+ print_DEBUG "html#html_of_class : virtual or not" ;
+ if c.cl_virtual then bs b ((self#keyword "virtual")^" ");
+ (
+ match c.cl_type_parameters with
+ [] -> ()
+ | l ->
+ self#html_of_class_type_param_expr_list b father l;
+ bs b " "
+ );
+ print_DEBUG "html#html_of_class : with link or not" ;
+ (
+ if with_link then
+ bp b "<a href=\"%s\">%s</a>" html_file (Name.simple c.cl_name)
+ else
+ bs b (Name.simple c.cl_name)
+ );
+ bs b "</span>";
+ bs b " : " ;
+ self#html_of_class_parameter_list b father c ;
+ self#html_of_class_kind b father ~cl: c c.cl_kind;
+ bs b "</pre>" ;
+ print_DEBUG "html#html_of_class : info" ;
+ (
+ if complete then
+ self#html_of_info ~cls: "class top" ~indent: true
+ else
+ self#html_of_info_first_sentence
+ ) b c.cl_info
+
+ (** Print html code for a class type. *)
+ method html_of_class_type b ?(complete=true) ?(with_link=true) ct =
+ Odoc_info.reset_type_names ();
+ let father = Name.father ct.clt_name in
+ let (html_file, _) = Naming.html_files ct.clt_name in
+ bs b "\n<pre>";
+ (* we add a html id, the same as for a type so we can
+ go directly here when the class type name is used as a type name *)
+ bp b "<span id=\"%s\">"
+ (Naming.type_target
+ { ty_name = ct.clt_name ;
+ ty_info = None ; ty_parameters = [] ;
+ ty_kind = Type_abstract ; ty_private = Asttypes.Public; ty_manifest = None ;
+ ty_loc = Odoc_info.dummy_loc ;
+ ty_code = None ;
+ }
+ );
+ bs b ((self#keyword "class type")^" ");
+ if ct.clt_virtual then bs b ((self#keyword "virtual")^" ");
+ (
+ match ct.clt_type_parameters with
+ [] -> ()
+ | l ->
+ self#html_of_class_type_param_expr_list b father l;
+ bs b " "
+ );
+
+ if with_link then
+ bp b "<a href=\"%s\">%s</a>" html_file (Name.simple ct.clt_name)
+ else
+ bs b (Name.simple ct.clt_name);
+
+ bs b "</span>";
+ bs b " = ";
+ self#html_of_class_type_kind b father ~ct ct.clt_kind;
+ bs b "</pre>";
+ (
+ if complete then
+ self#html_of_info ~cls: "classtype top" ~indent: true
+ else
+ self#html_of_info_first_sentence
+ ) b ct.clt_info
+
+ (** Return html code to represent a dag, represented as in Odoc_dag2html. *)
+ method html_of_dag dag =
+ let f n =
+ let (name, cct_opt) = n.Odoc_dag2html.valu in
+ (* if we have a c_opt = Some class then we take its information
+ because we are sure the name is complete. *)
+ let (name2, html_file) =
+ match cct_opt with
+ None -> (name, fst (Naming.html_files name))
+ | Some (Cl c) -> (c.cl_name, fst (Naming.html_files c.cl_name))
+ | Some (Cltype (ct, _)) -> (ct.clt_name, fst (Naming.html_files ct.clt_name))
+ in
+ let new_v =
+ "<table border=1>\n<tr><td>"^
+ "<a href=\""^html_file^"\">"^name2^"</a>"^
+ "</td></tr>\n</table>\n"
+ in
+ { n with Odoc_dag2html.valu = new_v }
+ in
+ let a = Array.map f dag.Odoc_dag2html.dag in
+ Odoc_dag2html.html_of_dag { Odoc_dag2html.dag = a }
+
+ (** Print html code for a module comment.*)
+ method html_of_module_comment b text =
+ bs b "<br>\n";
+ self#html_of_text b text;
+ bs b "<br>\n"
+
+ (** Print html code for a class comment.*)
+ method html_of_class_comment b text =
+ (* Add some style if there is no style for the first part of the text. *)
+ let text2 =
+ match text with
+ | (Odoc_info.Raw s) :: q ->
+ (Odoc_info.Title (2, None, [Odoc_info.Raw s])) :: q
+ | _ -> text
+ in
+ self#html_of_text b text2
+
+ (** Generate html code for the given list of inherited classes.*)
+ method generate_inheritance_info b inher_l =
+ let f inh =
+ match inh.ic_class with
+ None -> (* we can't make the link. *)
+ (Odoc_info.Code inh.ic_name) ::
+ (match inh.ic_text with
+ None -> []
+ | Some t -> (Odoc_info.Raw " ") :: t)
+ | Some cct ->
+ (* we can create the link. *)
+ let real_name = (* even if it should be the same *)
+ match cct with
+ Cl c -> c.cl_name
+ | Cltype (ct, _) -> ct.clt_name
+ in
+ let (class_file, _) = Naming.html_files real_name in
+ (Odoc_info.Link (class_file, [Odoc_info.Code real_name])) ::
+ (match inh.ic_text with
+ None -> []
+ | Some t -> (Odoc_info.Raw " ") :: t)
+ in
+ let text = [
+ Odoc_info.Bold [Odoc_info.Raw Odoc_messages.inherits] ;
+ Odoc_info.List (List.map f inher_l)
+ ]
+ in
+ self#html_of_text b text
+
+ (** Generate html code for the inherited classes of the given class. *)
+ method generate_class_inheritance_info b cl =
+ let rec iter_kind k =
+ match k with
+ Class_structure ([], _) ->
+ ()
+ | Class_structure (l, _) ->
+ self#generate_inheritance_info b l
+ | Class_constraint (k, ct) ->
+ iter_kind k
+ | Class_apply _
+ | Class_constr _ ->
+ ()
+ in
+ iter_kind cl.cl_kind
+
+ (** Generate html code for the inherited classes of the given class type. *)
+ method generate_class_type_inheritance_info b clt =
+ match clt.clt_kind with
+ Class_signature ([], _) ->
+ ()
+ | Class_signature (l, _) ->
+ self#generate_inheritance_info b l
+ | Class_type _ ->
+ ()
+
+ (** A method to create index files. *)
+ method generate_elements_index :
+ 'a.
+ 'a list ->
+ ('a -> Odoc_info.Name.t) ->
+ ('a -> Odoc_info.info option) ->
+ ('a -> string) -> string -> string -> unit =
+ fun elements name info target title simple_file ->
+ try
+ let chanout = open_out (Filename.concat !Global.target_dir simple_file) in
+ let b = new_buf () in
+ bs b "<html>\n";
+ self#print_header b (self#inner_title title);
+ bs b "<body>\n";
+ self#print_navbar b None None "";
+ bs b "<h1>";
+ bs b title;
+ bs b "</h1>\n" ;
+
+ let sorted_elements = List.sort
+ (fun e1 e2 -> compare (Name.simple (name e1)) (Name.simple (name e2)))
+ elements
+ in
+ let groups = Odoc_info.create_index_lists sorted_elements (fun e -> Name.simple (name e)) in
+ let f_ele e =
+ let simple_name = Name.simple (name e) in
+ let father_name = Name.father (name e) in
+ bp b "<tr><td><a href=\"%s\">%s</a> " (target e) (self#escape simple_name);
+ if simple_name <> father_name && father_name <> "" then
+ bp b "[<a href=\"%s\">%s</a>]" (fst (Naming.html_files father_name)) father_name;
+ bs b "</td>\n<td>";
+ self#html_of_info_first_sentence b (info e);
+ bs b "</td></tr>\n";
+ in
+ let f_group l =
+ match l with
+ [] -> ()
+ | e :: _ ->
+ let s =
+ match (Char.uppercase_ascii (Name.simple (name e)).[0]) with
+ 'A'..'Z' as c -> String.make 1 c
+ | _ -> ""
+ in
+ bs b "<tr><td align=\"left\"><br>";
+ bs b s ;
+ bs b "</td></tr>\n" ;
+ List.iter f_ele l
+ in
+ bs b "<table>\n";
+ List.iter f_group groups ;
+ bs b "</table>\n" ;
+ bs b "</body>\n</html>";
+ Buffer.output_buffer chanout b;
+ close_out chanout
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ (** A method to generate a list of module/class files. *)
+ method generate_elements :
+ 'a. ('a option -> 'a option -> 'a -> unit) -> 'a list -> unit =
+ fun f_generate l ->
+ let rec iter pre_opt = function
+ [] -> ()
+ | ele :: [] -> f_generate pre_opt None ele
+ | ele1 :: ele2 :: q ->
+ f_generate pre_opt (Some ele2) ele1 ;
+ iter (Some ele1) (ele2 :: q)
+ in
+ iter None l
+
+ (** Generate the code of the html page for the given class.*)
+ method generate_for_class pre post cl =
+ Odoc_info.reset_type_names ();
+ let (html_file, _) = Naming.html_files cl.cl_name in
+ let type_file = Naming.file_type_class_complete_target cl.cl_name in
+ try
+ let chanout = open_out (Filename.concat !Global.target_dir html_file) in
+ let b = new_buf () in
+ let pre_name = opt (fun c -> c.cl_name) pre in
+ let post_name = opt (fun c -> c.cl_name) post in
+ bs b doctype ;
+ bs b "<html>\n";
+ self#print_header b
+ ~nav: (Some (pre_name, post_name, cl.cl_name))
+ ~comments: (Class.class_comments cl)
+ (self#inner_title cl.cl_name);
+ bs b "<body>\n";
+ self#print_navbar b pre_name post_name cl.cl_name;
+ bs b "<h1>";
+ bs b (Odoc_messages.clas^" ");
+ if cl.cl_virtual then bs b "virtual " ;
+ bp b "<a href=\"%s\">%s</a>" type_file cl.cl_name;
+ bs b "</h1>\n";
+ self#html_of_class b ~with_link: false cl;
+ (* parameters *)
+ self#html_of_described_parameter_list b
+ (Name.father cl.cl_name) cl.cl_parameters;
+ (* class inheritance *)
+ self#generate_class_inheritance_info b cl;
+ (* a horizontal line *)
+ bs b "<hr width=\"100%\">\n";
+ (* the various elements *)
+ List.iter (self#html_of_class_element b)
+ (Class.class_elements ~trans:false cl);
+ bs b "</body></html>";
+ Buffer.output_buffer chanout b;
+ close_out chanout;
+
+ (* generate the file with the complete class type *)
+ self#output_class_type
+ cl.cl_name
+ (Filename.concat !Global.target_dir type_file)
+ cl.cl_type
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ (** Generate the code of the html page for the given class type.*)
+ method generate_for_class_type pre post clt =
+ Odoc_info.reset_type_names ();
+ let (html_file, _) = Naming.html_files clt.clt_name in
+ let type_file = Naming.file_type_class_complete_target clt.clt_name in
+ try
+ let chanout = open_out (Filename.concat !Global.target_dir html_file) in
+ let b = new_buf () in
+ let pre_name = opt (fun ct -> ct.clt_name) pre in
+ let post_name = opt (fun ct -> ct.clt_name) post in
+ bs b doctype ;
+ bs b "<html>\n";
+ self#print_header b
+ ~nav: (Some (pre_name, post_name, clt.clt_name))
+ ~comments: (Class.class_type_comments clt)
+ (self#inner_title clt.clt_name);
+
+ bs b "<body>\n";
+ self#print_navbar b pre_name post_name clt.clt_name;
+ bs b "<h1>";
+ bs b (Odoc_messages.class_type^" ");
+ if clt.clt_virtual then bs b "virtual ";
+ bp b "<a href=\"%s\">%s</a>" type_file clt.clt_name;
+ bs b "</h1>\n";
+ self#html_of_class_type b ~with_link: false clt;
+
+ (* class inheritance *)
+ self#generate_class_type_inheritance_info b clt;
+ (* a horizontal line *)
+ bs b "<hr width=\"100%\">\n";
+ (* the various elements *)
+ List.iter (self#html_of_class_element b)
+ (Class.class_type_elements ~trans: false clt);
+ bs b "</body></html>";
+ Buffer.output_buffer chanout b;
+ close_out chanout;
+
+ (* generate the file with the complete class type *)
+ self#output_class_type
+ clt.clt_name
+ (Filename.concat !Global.target_dir type_file)
+ clt.clt_type
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ (** Generate the html file for the given module type.
+ @raise Failure if an error occurs.*)
+ method generate_for_module_type pre post mt =
+ try
+ let (html_file, _) = Naming.html_files mt.mt_name in
+ let type_file = Naming.file_type_module_complete_target mt.mt_name in
+ let chanout = open_out (Filename.concat !Global.target_dir html_file) in
+ let b = new_buf () in
+ let pre_name = opt (fun mt -> mt.mt_name) pre in
+ let post_name = opt (fun mt -> mt.mt_name) post in
+ bs b doctype ;
+ bs b "<html>\n";
+ self#print_header b
+ ~nav: (Some (pre_name, post_name, mt.mt_name))
+ ~comments: (Module.module_type_comments mt)
+ (self#inner_title mt.mt_name);
+ bs b "<body>\n";
+ self#print_navbar b pre_name post_name mt.mt_name;
+ bp b "<h1>";
+ bs b (Odoc_messages.module_type^" ");
+ (
+ match mt.mt_type with
+ Some _ -> bp b "<a href=\"%s\">%s</a>" type_file mt.mt_name
+ | None-> bs b mt.mt_name
+ );
+ bs b "</h1>\n" ;
+ self#html_of_modtype b ~with_link: false mt;
+
+ (* parameters for functors *)
+ self#html_of_module_parameter_list b
+ (Name.father mt.mt_name)
+ (Module.module_type_parameters mt);
+ (* a horizontal line *)
+ bs b "<hr width=\"100%\">\n";
+ (* module elements *)
+ List.iter
+ (self#html_of_module_element b mt.mt_name)
+ (Module.module_type_elements mt);
+
+ bs b "</body></html>";
+ Buffer.output_buffer chanout b;
+ close_out chanout;
+
+ (* generate html files for submodules *)
+ self#generate_elements self#generate_for_module (Module.module_type_modules mt);
+ (* generate html files for module types *)
+ self#generate_elements self#generate_for_module_type (Module.module_type_module_types mt);
+ (* generate html files for classes *)
+ self#generate_elements self#generate_for_class (Module.module_type_classes mt);
+ (* generate html files for class types *)
+ self#generate_elements self#generate_for_class_type (Module.module_type_class_types mt);
+
+ (* generate the file with the complete module type *)
+ (
+ match mt.mt_type with
+ None -> ()
+ | Some mty ->
+ self#output_module_type
+ mt.mt_name
+ (Filename.concat !Global.target_dir type_file)
+ mty
+ )
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ (** Generate the html file for the given module.
+ @raise Failure if an error occurs.*)
+ method generate_for_module pre post modu =
+ try
+ Odoc_info.verbose ("Generate for module "^modu.m_name);
+ let (html_file, _) = Naming.html_files modu.m_name in
+ let type_file = Naming.file_type_module_complete_target modu.m_name in
+ let code_file = Naming.file_code_module_complete_target modu.m_name in
+ let chanout = open_out (Filename.concat !Global.target_dir html_file) in
+ let b = new_buf () in
+ let pre_name = opt (fun m -> m.m_name) pre in
+ let post_name = opt (fun m -> m.m_name) post in
+ bs b doctype ;
+ bs b "<html>\n";
+ self#print_header b
+ ~nav: (Some (pre_name, post_name, modu.m_name))
+ ~comments: (Module.module_comments modu)
+ (self#inner_title modu.m_name);
+ bs b "<body>\n" ;
+ self#print_navbar b pre_name post_name modu.m_name ;
+ bs b "<h1>";
+ if modu.m_text_only then
+ bs b modu.m_name
+ else
+ (
+ bs b
+ (
+ if Module.module_is_functor modu then
+ Odoc_messages.functo
+ else
+ Odoc_messages.modul
+ );
+ bp b " <a href=\"%s\">%s</a>" type_file modu.m_name;
+ (
+ match modu.m_code with
+ None -> ()
+ | Some _ -> bp b " (<a href=\"%s\">.ml</a>)" code_file
+ )
+ );
+ bs b "</h1>\n";
+
+ if not modu.m_text_only then self#html_of_module b ~with_link: false modu;
+
+ (* parameters for functors *)
+ self#html_of_module_parameter_list b
+ (Name.father modu.m_name)
+ (Module.module_parameters modu);
+
+ (* a horizontal line *)
+ if not modu.m_text_only then bs b "<hr width=\"100%\">\n";
+
+ (* module elements *)
+ List.iter
+ (self#html_of_module_element b modu.m_name)
+ (Module.module_elements modu);
+
+ bs b "</body></html>";
+ Buffer.output_buffer chanout b;
+ close_out chanout;
+
+ (* generate html files for submodules *)
+ self#generate_elements self#generate_for_module (Module.module_modules modu);
+ (* generate html files for module types *)
+ self#generate_elements self#generate_for_module_type (Module.module_module_types modu);
+ (* generate html files for classes *)
+ self#generate_elements self#generate_for_class (Module.module_classes modu);
+ (* generate html files for class types *)
+ self#generate_elements self#generate_for_class_type (Module.module_class_types modu);
+
+ (* generate the file with the complete module type *)
+ self#output_module_type
+ modu.m_name
+ (Filename.concat !Global.target_dir type_file)
+ modu.m_type;
+
+ match modu.m_code with
+ None -> ()
+ | Some code ->
+ self#output_code
+ modu.m_name
+ (Filename.concat !Global.target_dir code_file)
+ code
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ (** Generate the [<index_prefix>.html] file corresponding to the given module list.
+ @raise Failure if an error occurs.*)
+ method generate_index module_list =
+ try
+ let chanout = open_out (Filename.concat !Global.target_dir self#index) in
+ let b = new_buf () in
+ let title = match !Global.title with None -> "" | Some t -> self#escape t in
+ bs b doctype ;
+ bs b "<html>\n";
+ self#print_header b self#title;
+ bs b "<body>\n";
+
+ bs b "<h1>";
+ bs b title;
+ bs b "</h1>\n" ;
+ let info = Odoc_info.apply_opt
+ (Odoc_info.info_of_comment_file module_list)
+ !Odoc_info.Global.intro_file
+ in
+ (
+ match info with
+ None ->
+ self#html_of_Index_list b;
+ bs b "<br/>";
+ self#html_of_Module_list b
+ (List.map (fun m -> m.m_name) module_list);
+ | Some i -> self#html_of_info ~indent: false b info
+ );
+ bs b "</body>\n</html>";
+ Buffer.output_buffer chanout b;
+ close_out chanout
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ (** Generate the values index in the file [index_values.html]. *)
+ method generate_values_index module_list =
+ self#generate_elements_index
+ self#list_values
+ (fun v -> v.val_name)
+ (fun v -> v.val_info)
+ Naming.complete_value_target
+ Odoc_messages.index_of_values
+ self#index_values
+
+ (** Generate the extensions index in the file [index_extensions.html]. *)
+ method generate_extensions_index module_list =
+ self#generate_elements_index
+ self#list_extensions
+ (fun x -> x.xt_name)
+ (fun x -> x.xt_type_extension.te_info)
+ (fun x -> Naming.complete_extension_target x)
+ Odoc_messages.index_of_extensions
+ self#index_extensions
+
+ (** Generate the exceptions index in the file [index_exceptions.html]. *)
+ method generate_exceptions_index module_list =
+ self#generate_elements_index
+ self#list_exceptions
+ (fun e -> e.ex_name)
+ (fun e -> e.ex_info)
+ Naming.complete_exception_target
+ Odoc_messages.index_of_exceptions
+ self#index_exceptions
+
+ (** Generate the types index in the file [index_types.html]. *)
+ method generate_types_index module_list =
+ self#generate_elements_index
+ self#list_types
+ (fun t -> t.ty_name)
+ (fun t -> t.ty_info)
+ Naming.complete_type_target
+ Odoc_messages.index_of_types
+ self#index_types
+
+ (** Generate the attributes index in the file [index_attributes.html]. *)
+ method generate_attributes_index module_list =
+ self#generate_elements_index
+ self#list_attributes
+ (fun a -> a.att_value.val_name)
+ (fun a -> a.att_value.val_info)
+ Naming.complete_attribute_target
+ Odoc_messages.index_of_attributes
+ self#index_attributes
+
+ (** Generate the methods index in the file [index_methods.html]. *)
+ method generate_methods_index module_list =
+ self#generate_elements_index
+ self#list_methods
+ (fun m -> m.met_value.val_name)
+ (fun m -> m.met_value.val_info)
+ Naming.complete_method_target
+ Odoc_messages.index_of_methods
+ self#index_methods
+
+ (** Generate the classes index in the file [index_classes.html]. *)
+ method generate_classes_index module_list =
+ self#generate_elements_index
+ self#list_classes
+ (fun c -> c.cl_name)
+ (fun c -> c.cl_info)
+ (fun c -> fst (Naming.html_files c.cl_name))
+ Odoc_messages.index_of_classes
+ self#index_classes
+
+ (** Generate the class types index in the file [index_class_types.html]. *)
+ method generate_class_types_index module_list =
+ self#generate_elements_index
+ self#list_class_types
+ (fun ct -> ct.clt_name)
+ (fun ct -> ct.clt_info)
+ (fun ct -> fst (Naming.html_files ct.clt_name))
+ Odoc_messages.index_of_class_types
+ self#index_class_types
+
+ (** Generate the modules index in the file [index_modules.html]. *)
+ method generate_modules_index module_list =
+ self#generate_elements_index
+ self#list_modules
+ (fun m -> m.m_name)
+ (fun m -> m.m_info)
+ (fun m -> fst (Naming.html_files m.m_name))
+ Odoc_messages.index_of_modules
+ self#index_modules
+
+ (** Generate the module types index in the file [index_module_types.html]. *)
+ method generate_module_types_index module_list =
+ self#generate_elements_index
+ self#list_module_types
+ (fun mt -> mt.mt_name)
+ (fun mt -> mt.mt_info)
+ (fun mt -> fst (Naming.html_files mt.mt_name))
+ Odoc_messages.index_of_module_types
+ self#index_module_types
+
+ (** Generate all the html files from a module list. The main
+ file is [<index_prefix>.html]. *)
+ method generate module_list =
+ (* init the style *)
+ self#init_style ;
+ (* init the lists of elements *)
+ list_values <- Odoc_info.Search.values module_list ;
+ list_extensions <- Odoc_info.Search.extensions module_list ;
+ list_exceptions <- Odoc_info.Search.exceptions module_list ;
+ list_types <- Odoc_info.Search.types module_list ;
+ list_attributes <- Odoc_info.Search.attributes module_list ;
+ list_methods <- Odoc_info.Search.methods module_list ;
+ list_classes <- Odoc_info.Search.classes module_list ;
+ list_class_types <- Odoc_info.Search.class_types module_list ;
+ list_modules <- Odoc_info.Search.modules module_list ;
+ list_module_types <- Odoc_info.Search.module_types module_list ;
+
+ (* prepare the page header *)
+ self#prepare_header module_list ;
+ (* Get the names of all known types. *)
+ let types = Odoc_info.Search.types module_list in
+ known_types_names <-
+ List.fold_left
+ (fun acc t -> StringSet.add t.ty_name acc)
+ known_types_names
+ types ;
+ (* Get the names of all class and class types. *)
+ let classes = Odoc_info.Search.classes module_list in
+ let class_types = Odoc_info.Search.class_types module_list in
+ known_classes_names <-
+ List.fold_left
+ (fun acc c -> StringSet.add c.cl_name acc)
+ known_classes_names
+ classes ;
+ known_classes_names <-
+ List.fold_left
+ (fun acc ct -> StringSet.add ct.clt_name acc)
+ known_classes_names
+ class_types ;
+ (* Get the names of all known modules and module types. *)
+ let module_types = Odoc_info.Search.module_types module_list in
+ let modules = Odoc_info.Search.modules module_list in
+ known_modules_names <-
+ List.fold_left
+ (fun acc m -> StringSet.add m.m_name acc)
+ known_modules_names
+ modules ;
+ known_modules_names <-
+ List.fold_left
+ (fun acc mt -> StringSet.add mt.mt_name acc)
+ known_modules_names
+ module_types ;
+ (* generate html for each module *)
+ if not !index_only then
+ self#generate_elements self#generate_for_module module_list ;
+
+ try
+ self#generate_index module_list;
+ self#generate_values_index module_list ;
+ self#generate_extensions_index module_list ;
+ self#generate_exceptions_index module_list ;
+ self#generate_types_index module_list ;
+ self#generate_attributes_index module_list ;
+ self#generate_methods_index module_list ;
+ self#generate_classes_index module_list ;
+ self#generate_class_types_index module_list ;
+ self#generate_modules_index module_list ;
+ self#generate_module_types_index module_list ;
+ with
+ Failure s ->
+ prerr_endline s ;
+ incr Odoc_info.errors
+
+ initializer
+ Odoc_ocamlhtml.html_of_comment :=
+ (fun s ->
+ let b = new_buf () in
+ self#html_of_text b (Odoc_text.Texter.text_of_string s);
+ Buffer.contents b
+ )
+ end
+end
+
+module type Html_generator = module type of Generator
diff --git a/ocamldoc/odoc_info.ml b/ocamldoc/odoc_info.ml
new file mode 100644
index 0000000000..0fadbd4821
--- /dev/null
+++ b/ocamldoc/odoc_info.ml
@@ -0,0 +1,335 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Interface for analysing documented OCaml source files and to the collected information. *)
+
+type ref_kind = Odoc_types.ref_kind =
+ RK_module
+ | RK_module_type
+ | RK_class
+ | RK_class_type
+ | RK_value
+ | RK_type
+ | RK_extension
+ | RK_exception
+ | RK_attribute
+ | RK_method
+ | RK_section of text
+ | RK_recfield
+ | RK_const
+
+and text_element = Odoc_types.text_element =
+ | Raw of string
+ | Code of string
+ | CodePre of string
+ | Verbatim of string
+ | Bold of text
+ | Italic of text
+ | Emphasize of text
+ | Center of text
+ | Left of text
+ | Right of text
+ | List of text list
+ | Enum of text list
+ | Newline
+ | Block of text
+ | Title of int * string option * text
+ | Latex of string
+ | Link of string * text
+ | Ref of string * ref_kind option * text option
+ | Superscript of text
+ | Subscript of text
+ | Module_list of string list
+ | Index_list
+ | Custom of string * text
+ | Target of string * string
+
+and text = text_element list
+
+exception Text_syntax = Odoc_text.Text_syntax
+
+type see_ref = Odoc_types.see_ref =
+ See_url of string
+ | See_file of string
+ | See_doc of string
+
+type see = see_ref * text
+
+type param = (string * text)
+
+type raised_exception = (string * text)
+
+type info = Odoc_types.info = {
+ i_desc : text option;
+ i_authors : string list;
+ i_version : string option;
+ i_sees : see list;
+ i_since : string option;
+ i_before : (string * text) list ;
+ i_deprecated : text option;
+ i_params : param list;
+ i_raised_exceptions : raised_exception list;
+ i_return_value : text option ;
+ i_custom : (string * text) list ;
+ }
+
+type location = Odoc_types.location = {
+ loc_impl : Location.t option ;
+ loc_inter : Location.t option ;
+ }
+
+let dummy_loc = { loc_impl = None ; loc_inter = None }
+
+module Name = Odoc_name
+module Parameter = Odoc_parameter
+module Extension = Odoc_extension
+module Exception = Odoc_exception
+module Type = Odoc_type
+module Value = Odoc_value
+module Class = Odoc_class
+module Module = Odoc_module
+
+
+let analyse_files
+ ?(merge_options=([] : Odoc_types.merge_option list))
+ ?(include_dirs=([] : string list))
+ ?(labels=false)
+ ?(sort_modules=false)
+ ?(no_stop=false)
+ ?(init=[])
+ files =
+ Odoc_global.merge_options := merge_options;
+ Odoc_global.include_dirs := include_dirs;
+ Odoc_global.classic := not labels;
+ Odoc_global.sort_modules := sort_modules;
+ Odoc_global.no_stop := no_stop;
+ Odoc_analyse.analyse_files ~init: init files
+
+let dump_modules = Odoc_analyse.dump_modules
+
+let load_modules = Odoc_analyse.load_modules
+
+let reset_type_names = Printtyp.reset
+
+let string_of_variance t (co,cn) = Odoc_str.string_of_variance t (co, cn)
+
+let string_of_type_expr t = Odoc_print.string_of_type_expr t
+
+let string_of_class_params = Odoc_str.string_of_class_params
+
+let string_of_type_list ?par sep type_list = Odoc_str.string_of_type_list ?par sep type_list
+
+let string_of_type_param_list t = Odoc_str.string_of_type_param_list t
+
+let string_of_type_extension_param_list te = Odoc_str.string_of_type_extension_param_list te
+
+let string_of_class_type_param_list l = Odoc_str.string_of_class_type_param_list l
+
+let string_of_module_type = Odoc_print.string_of_module_type
+
+let string_of_class_type = Odoc_print.string_of_class_type
+
+let string_of_text t = Odoc_misc.string_of_text t
+
+let string_of_info i = Odoc_misc.string_of_info i
+
+let string_of_type t = Odoc_str.string_of_type t
+let string_of_record t = Odoc_str.string_of_record t
+
+let string_of_type_extension te = Odoc_str.string_of_type_extension te
+
+let string_of_exception e = Odoc_str.string_of_exception e
+
+let string_of_value v = Odoc_str.string_of_value v
+
+let string_of_attribute att = Odoc_str.string_of_attribute att
+
+let string_of_method m = Odoc_str.string_of_method m
+
+let first_sentence_of_text = Odoc_misc.first_sentence_of_text
+
+let first_sentence_and_rest_of_text = Odoc_misc.first_sentence_and_rest_of_text
+
+let text_no_title_no_list = Odoc_misc.text_no_title_no_list
+
+let text_concat = Odoc_misc.text_concat
+
+let get_titles_in_text = Odoc_misc.get_titles_in_text
+
+let create_index_lists = Odoc_misc.create_index_lists
+
+let remove_ending_newline = Odoc_misc.remove_ending_newline
+
+let remove_option = Odoc_misc.remove_option
+
+let is_optional = Odoc_misc.is_optional
+
+let label_name = Odoc_misc.label_name
+
+let use_hidden_modules n =
+ Odoc_name.hide_given_modules !Odoc_global.hidden_modules n
+
+let verbose s =
+ if !Odoc_global.verbose then
+ (print_string s ; print_newline ())
+ else
+ ()
+
+let warning s = Odoc_global.pwarning s
+let print_warnings = Odoc_config.print_warnings
+
+let errors = Odoc_global.errors
+
+let apply_opt = Odoc_misc.apply_opt
+
+let apply_if_equal f v1 v2 =
+ if v1 = v2 then
+ f v1
+ else
+ v2
+
+let text_of_string = Odoc_text.Texter.text_of_string
+
+let text_string_of_text = Odoc_text.Texter.string_of_text
+
+
+let escape_arobas s =
+ let len = String.length s in
+ let b = Buffer.create len in
+ for i = 0 to len - 1 do
+ match s.[i] with
+ '@' -> Buffer.add_string b "\\@"
+ | c -> Buffer.add_char b c
+ done;
+ Buffer.contents b
+
+let info_string_of_info i =
+ let b = Buffer.create 256 in
+ let p = Printf.bprintf in
+ (
+ match i.i_desc with
+ None -> ()
+ | Some t -> p b "%s" (escape_arobas (text_string_of_text t))
+ );
+ List.iter
+ (fun s -> p b "\n@@author %s" (escape_arobas s))
+ i.i_authors;
+ (
+ match i.i_version with
+ None -> ()
+ | Some s -> p b "\n@@version %s" (escape_arobas s)
+ );
+ (
+ (* TODO: escape characters ? *)
+ let f_see_ref = function
+ See_url s -> Printf.sprintf "<%s>" s
+ | See_file s -> Printf.sprintf "'%s'" s
+ | See_doc s -> Printf.sprintf "\"%s\"" s
+ in
+ List.iter
+ (fun (sref, t) ->
+ p b "\n@@see %s %s"
+ (escape_arobas (f_see_ref sref))
+ (escape_arobas (text_string_of_text t))
+ )
+ i.i_sees
+ );
+ (
+ match i.i_since with
+ None -> ()
+ | Some s -> p b "\n@@since %s" (escape_arobas s)
+ );
+ (
+ match i.i_deprecated with
+ None -> ()
+ | Some t ->
+ p b "\n@@deprecated %s"
+ (escape_arobas (text_string_of_text t))
+ );
+ List.iter
+ (fun (s, t) ->
+ p b "\n@@param %s %s"
+ (escape_arobas s)
+ (escape_arobas (text_string_of_text t))
+ )
+ i.i_params;
+ List.iter
+ (fun (s, t) ->
+ p b "\n@@raise %s %s"
+ (escape_arobas s)
+ (escape_arobas (text_string_of_text t))
+ )
+ i.i_raised_exceptions;
+ (
+ match i.i_return_value with
+ None -> ()
+ | Some t ->
+ p b "\n@@return %s"
+ (escape_arobas (text_string_of_text t))
+ );
+ List.iter
+ (fun (s, t) ->
+ p b "\n@@%s %s" s
+ (escape_arobas (text_string_of_text t))
+ )
+ i.i_custom;
+
+ Buffer.contents b
+
+let info_of_string = Odoc_comments.info_of_string
+let info_of_comment_file = Odoc_comments.info_of_comment_file
+
+module Search =
+ struct
+ type result_element = Odoc_search.result_element =
+ Res_module of Module.t_module
+ | Res_module_type of Module.t_module_type
+ | Res_class of Class.t_class
+ | Res_class_type of Class.t_class_type
+ | Res_value of Value.t_value
+ | Res_type of Type.t_type
+ | Res_extension of Extension.t_extension_constructor
+ | Res_exception of Exception.t_exception
+ | Res_attribute of Value.t_attribute
+ | Res_method of Value.t_method
+ | Res_section of string * text
+ | Res_recfield of Type.t_type * Type.record_field
+ | Res_const of Type.t_type * Type.variant_constructor
+
+ type search_result = result_element list
+
+ let search_by_name = Odoc_search.Search_by_name.search
+
+ let values = Odoc_search.values
+ let extensions = Odoc_search.extensions
+ let exceptions = Odoc_search.exceptions
+ let types = Odoc_search.types
+ let attributes = Odoc_search.attributes
+ let methods = Odoc_search.methods
+ let classes = Odoc_search.classes
+ let class_types = Odoc_search.class_types
+ let modules = Odoc_search.modules
+ let module_types = Odoc_search.module_types
+ end
+
+module Scan =
+ struct
+ class scanner = Odoc_scan.scanner
+ end
+
+module Dep =
+ struct
+ let kernel_deps_of_modules = Odoc_dep.kernel_deps_of_modules
+ let deps_of_types = Odoc_dep.deps_of_types
+ end
+
+module Global = Odoc_global
diff --git a/ocamldoc/odoc_info.mli b/ocamldoc/odoc_info.mli
new file mode 100644
index 0000000000..451315543a
--- /dev/null
+++ b/ocamldoc/odoc_info.mli
@@ -0,0 +1,1087 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Interface to the information collected in source files. *)
+
+(** The differents kinds of element references. *)
+type ref_kind = Odoc_types.ref_kind =
+ RK_module
+ | RK_module_type
+ | RK_class
+ | RK_class_type
+ | RK_value
+ | RK_type
+ | RK_extension
+ | RK_exception
+ | RK_attribute
+ | RK_method
+ | RK_section of text
+ | RK_recfield
+ | RK_const
+
+and text_element = Odoc_types.text_element =
+ | Raw of string (** Raw text. *)
+ | Code of string (** The string is source code. *)
+ | CodePre of string (** The string is pre-formatted source code. *)
+ | Verbatim of string (** String 'as is'. *)
+ | Bold of text (** Text in bold style. *)
+ | Italic of text (** Text in italic. *)
+ | Emphasize of text (** Emphasized text. *)
+ | Center of text (** Centered text. *)
+ | Left of text (** Left alignment. *)
+ | Right of text (** Right alignment. *)
+ | List of text list (** A list. *)
+ | Enum of text list (** An enumerated list. *)
+ | Newline (** To force a line break. *)
+ | Block of text (** Like html's block quote. *)
+ | Title of int * string option * text
+ (** Style number, optional label, and text. *)
+ | Latex of string (** A string for latex. *)
+ | Link of string * text (** A reference string and the link text. *)
+ | Ref of string * ref_kind option * text option
+ (** A reference to an element. Complete name and kind.
+ An optional text can be given to display this text instead
+ of the element name.*)
+ | Superscript of text (** Superscripts. *)
+ | Subscript of text (** Subscripts. *)
+ | Module_list of string list
+ (** The table of the given modules with their abstract. *)
+ | Index_list (** The links to the various indexes (values, types, ...) *)
+ | Custom of string * text (** to extend \{foo syntax *)
+ | Target of string * string (** (target, code) : to specify code specific to a target format *)
+
+(** A text is a list of [text_element]. The order matters. *)
+and text = text_element list
+
+(** The different forms of references in \@see tags. *)
+type see_ref = Odoc_types.see_ref =
+ See_url of string
+ | See_file of string
+ | See_doc of string
+
+(** Raised when parsing string to build a {!Odoc_info.text}
+ structure. [(line, char, string)] *)
+exception Text_syntax of int * int * string
+
+(** The information in a \@see tag. *)
+type see = see_ref * text
+
+(** Parameter name and description. *)
+type param = (string * text)
+
+(** Raised exception name and description. *)
+type raised_exception = (string * text)
+
+(** Information in a special comment
+@before 3.12.0 \@before information was not present.
+*)
+type info = Odoc_types.info = {
+ i_desc : text option; (** The description text. *)
+ i_authors : string list; (** The list of authors in \@author tags. *)
+ i_version : string option; (** The string in the \@version tag. *)
+ i_sees : see list; (** The list of \@see tags. *)
+ i_since : string option; (** The string in the \@since tag. *)
+ i_before : (string * text) list ; (** the version number and text in \@before tag *)
+ i_deprecated : text option; (** The of the \@deprecated tag. *)
+ i_params : param list; (** The list of parameter descriptions. *)
+ i_raised_exceptions : raised_exception list; (** The list of raised exceptions. *)
+ i_return_value : text option; (** The description text of the return value. *)
+ i_custom : (string * text) list ; (** A text associated to a custom @-tag. *)
+ }
+
+(** Location of elements in implementation and interface files. *)
+type location = Odoc_types.location = {
+ loc_impl : Location.t option ; (** implementation location *)
+ loc_inter : Location.t option ; (** interface location *)
+ }
+
+(** A dummy location. *)
+val dummy_loc : location
+
+(** Representation of element names. *)
+module Name :
+ sig
+ type t = string
+
+ (** Access to the simple name. *)
+ val simple : t -> t
+
+ (** [concat t1 t2] returns the concatenation of [t1] and [t2].*)
+ val concat : t -> t -> t
+
+ (** Return the depth of the name, i.e. the numer of levels to the root.
+ Example : [depth "Toto.Tutu.name"] = [3]. *)
+ val depth : t -> int
+
+ (** Take two names n1 and n2 = n3.n4 and return n4 if n3=n1 or else n2. *)
+ val get_relative : t -> t -> t
+
+ (** Return the name of the 'father' (like [dirname] for a file name).*)
+ val father : t -> t
+ end
+
+(** Representation and manipulation of method / function / class / module parameters.*)
+module Parameter :
+ sig
+ (** {3 Types} *)
+ (** Representation of a simple parameter name *)
+ type simple_name = Odoc_parameter.simple_name =
+ {
+ sn_name : string ;
+ sn_type : Types.type_expr ;
+ mutable sn_text : text option ;
+ }
+
+ (** Representation of parameter names. We need it to represent parameter names in tuples.
+ The value [Tuple ([], t)] stands for an anonymous parameter.*)
+ type param_info = Odoc_parameter.param_info =
+ Simple_name of simple_name
+ | Tuple of param_info list * Types.type_expr
+
+ (** A parameter is just a param_info.*)
+ type parameter = param_info
+
+ (** {3 Functions} *)
+ (** Acces to the name as a string. For tuples, parenthesis and commas are added. *)
+ val complete_name : parameter -> string
+
+ (** Access to the complete type. *)
+ val typ : parameter -> Types.type_expr
+
+ (** Access to the list of names ; only one for a simple parameter, or
+ a list for a tuple. *)
+ val names : parameter -> string list
+
+ (** Access to the description of a specific name.
+ @raise Not_found if no description is associated to the given name. *)
+ val desc_by_name : parameter -> string -> text option
+
+ (** Access to the type of a specific name.
+ @raise Not_found if no type is associated to the given name. *)
+ val type_by_name : parameter -> string -> Types.type_expr
+ end
+
+(** Representation and manipulation of extensions. *)
+module Extension :
+ sig
+ type private_flag = Odoc_extension.private_flag =
+ Private | Public
+
+ (** Used when the extension is a rebind of another extension,
+ when we have [extension Xt = Target_xt].*)
+ type extension_alias = Odoc_extension.extension_alias =
+ {
+ xa_name : Name.t ; (** The complete name of the target extension. *)
+ mutable xa_xt : t_extension_constructor option ; (** The target extension, if we found it.*)
+ }
+
+ and t_extension_constructor = Odoc_extension.t_extension_constructor =
+ {
+ xt_name : Name.t ;
+ xt_args: Odoc_type.constructor_args;
+ xt_ret: Types.type_expr option ; (** the optional return type of the extension *)
+ xt_type_extension: t_type_extension ; (** the type extension containing this constructor *)
+ xt_alias: extension_alias option ; (** [None] when the extension is not a rebind. *)
+ mutable xt_loc: Odoc_types.location ;
+ mutable xt_text: Odoc_types.info option ; (** optional user description *)
+ }
+
+ and t_type_extension = Odoc_extension.t_type_extension =
+ {
+ mutable te_info : info option ; (** Information found in the optional associated comment. *)
+ te_type_name : Name.t ; (** The type of the extension *)
+ te_type_parameters : Types.type_expr list;
+ te_private : private_flag ;
+ mutable te_constructors: t_extension_constructor list;
+ mutable te_loc : location ;
+ mutable te_code : string option ;
+ }
+
+ (** Access to the extensions in a group. *)
+ val extension_constructors : t_type_extension -> t_extension_constructor list
+
+ end
+
+(** Representation and manipulation of exceptions. *)
+module Exception :
+ sig
+ (** Used when the exception is a rebind of another exception,
+ when we have [exception Ex = Target_ex].*)
+ type exception_alias = Odoc_exception.exception_alias =
+ {
+ ea_name : Name.t ; (** The complete name of the target exception. *)
+ mutable ea_ex : t_exception option ; (** The target exception, if we found it.*)
+ }
+
+ and t_exception = Odoc_exception.t_exception =
+ {
+ ex_name : Name.t ;
+ mutable ex_info : info option ; (** Information found in the optional associated comment. *)
+ ex_args : Odoc_type.constructor_args;
+ ex_ret : Types.type_expr option ; (** The the optional return type of the exception. *)
+ ex_alias : exception_alias option ; (** [None] when the exception is not a rebind. *)
+ mutable ex_loc : location ;
+ mutable ex_code : string option ;
+ }
+ end
+
+(** Representation and manipulation of types.*)
+module Type :
+ sig
+ type private_flag = Odoc_type.private_flag =
+ Private | Public
+
+ (** Description of a record type field. *)
+ type record_field = Odoc_type.record_field =
+ {
+ rf_name : string ; (** Name of the field. *)
+ rf_mutable : bool ; (** [true] if mutable. *)
+ rf_type : Types.type_expr ; (** Type of the field. *)
+ mutable rf_text : info option ; (** Optional description in the associated comment.*)
+ }
+
+ (** Description of a variant type constructor. *)
+ type constructor_args = Odoc_type.constructor_args =
+ | Cstr_record of record_field list
+ | Cstr_tuple of Types.type_expr list
+
+ type variant_constructor = Odoc_type.variant_constructor =
+ {
+ vc_name : string ; (** Name of the constructor. *)
+ vc_args : constructor_args;
+ vc_ret : Types.type_expr option ;
+ mutable vc_text : info option ; (** Optional description in the associated comment. *)
+ }
+
+ (** The various kinds of a type. *)
+ type type_kind = Odoc_type.type_kind =
+ Type_abstract (** Type is abstract, for example [type t]. *)
+ | Type_variant of variant_constructor list
+ (** constructors *)
+ | Type_record of record_field list
+ (** fields *)
+ | Type_open (** Type is open *)
+
+ type object_field = Odoc_type.object_field = {
+ of_name : string ;
+ of_type : Types.type_expr ;
+ mutable of_text : Odoc_types.info option ; (** optional user description *)
+ }
+
+ type type_manifest = Odoc_type.type_manifest =
+ | Other of Types.type_expr (** Type manifest directly taken from Typedtre. *)
+ | Object_type of object_field list
+
+ (** Representation of a type. *)
+ type t_type = Odoc_type.t_type =
+ {
+ ty_name : Name.t ; (** Complete name of the type. *)
+ mutable ty_info : info option ; (** Information found in the optional associated comment. *)
+ ty_parameters : (Types.type_expr * bool * bool) list ;
+ (** type parameters: (type, covariant, contravariant) *)
+ ty_kind : type_kind; (** Type kind. *)
+ ty_private : private_flag; (** Private or public type. *)
+ ty_manifest : type_manifest option ;
+ mutable ty_loc : location ;
+ mutable ty_code : string option;
+ }
+
+ end
+
+(** Representation and manipulation of values, class attributes and class methods. *)
+module Value :
+ sig
+ (** Representation of a value. *)
+ type t_value = Odoc_value.t_value =
+ {
+ val_name : Name.t ; (** Complete name of the value. *)
+ mutable val_info : info option ; (** Information found in the optional associated comment. *)
+ val_type : Types.type_expr ; (** Type of the value. *)
+ val_recursive : bool ; (** [true] if the value is recursive. *)
+ mutable val_parameters : Odoc_parameter.parameter list ; (** The parameters, if any. *)
+ mutable val_code : string option ; (** The code of the value, if we had the only the implementation file. *)
+ mutable val_loc : location ;
+ }
+
+ (** Representation of a class attribute. *)
+ type t_attribute = Odoc_value.t_attribute =
+ {
+ att_value : t_value ; (** an attribute has almost all the same information as a value *)
+ att_mutable : bool ; (** [true] if the attribute is mutable. *)
+ att_virtual : bool ; (** [true] if the attribute is virtual. *)
+ }
+
+ (** Representation of a class method. *)
+ type t_method = Odoc_value.t_method =
+ {
+ met_value : t_value ; (** a method has almost all the same information as a value *)
+ met_private : bool ; (** [true] if the method is private.*)
+ met_virtual : bool ; (** [true] if the method is virtual. *)
+ }
+
+ (** Return [true] if the value is a function, i.e. it has a functional type. *)
+ val is_function : t_value -> bool
+
+ (** Access to the description associated to the given parameter name.*)
+ val value_parameter_text_by_name : t_value -> string -> text option
+ end
+
+(** Representation and manipulation of classes and class types.*)
+module Class :
+ sig
+ (** {3 Types} *)
+ (** To keep the order of elements in a class. *)
+ type class_element = Odoc_class.class_element =
+ Class_attribute of Value.t_attribute
+ | Class_method of Value.t_method
+ | Class_comment of text
+
+ (** Used when we can reference a t_class or a t_class_type. *)
+ type cct = Odoc_class.cct =
+ Cl of t_class
+ | Cltype of t_class_type * Types.type_expr list (** Class type and type parameters. *)
+
+ and inherited_class = Odoc_class.inherited_class =
+ {
+ ic_name : Name.t ; (** Complete name of the inherited class. *)
+ mutable ic_class : cct option ; (** The associated t_class or t_class_type. *)
+ ic_text : text option ; (** The inheritance description, if any. *)
+ }
+
+ and class_apply = Odoc_class.class_apply =
+ {
+ capp_name : Name.t ; (** The complete name of the applied class. *)
+ mutable capp_class : t_class option; (** The associated t_class if we found it. *)
+ capp_params : Types.type_expr list; (** The type of expressions the class is applied to. *)
+ capp_params_code : string list ; (** The code of these exprssions. *)
+ }
+
+ and class_constr = Odoc_class.class_constr =
+ {
+ cco_name : Name.t ; (** The complete name of the applied class. *)
+ mutable cco_class : cct option;
+ (** The associated class or class type if we found it. *)
+ cco_type_parameters : Types.type_expr list; (** The type parameters of the class, if needed. *)
+ }
+
+ and class_kind = Odoc_class.class_kind =
+ Class_structure of inherited_class list * class_element list
+ (** An explicit class structure, used in implementation and interface. *)
+ | Class_apply of class_apply
+ (** Application/alias of a class, used in implementation only. *)
+ | Class_constr of class_constr
+ (** A class used to give the type of the defined class,
+ instead of a structure, used in interface only.
+ For example, it will be used with the name [M1.M2....bar]
+ when the class foo is defined like this :
+ [class foo : int -> bar] *)
+ | Class_constraint of class_kind * class_type_kind
+ (** A class definition with a constraint. *)
+
+ (** Representation of a class. *)
+ and t_class = Odoc_class.t_class =
+ {
+ cl_name : Name.t ; (** Complete name of the class. *)
+ mutable cl_info : info option ; (** Information found in the optional associated comment. *)
+ cl_type : Types.class_type ; (** Type of the class. *)
+ cl_type_parameters : Types.type_expr list ; (** Type parameters. *)
+ cl_virtual : bool ; (** [true] when the class is virtual. *)
+ mutable cl_kind : class_kind ; (** The way the class is defined. *)
+ mutable cl_parameters : Parameter.parameter list ; (** The parameters of the class. *)
+ mutable cl_loc : location ;
+ }
+
+ and class_type_alias = Odoc_class.class_type_alias =
+ {
+ cta_name : Name.t ; (** Complete name of the target class type. *)
+ mutable cta_class : cct option ; (** The target t_class or t_class_type, if we found it.*)
+ cta_type_parameters : Types.type_expr list ; (** The type parameters. A VOIR : mettre des string ? *)
+ }
+
+ and class_type_kind = Odoc_class.class_type_kind =
+ Class_signature of inherited_class list * class_element list
+ | Class_type of class_type_alias (** A class type eventually applied to type args. *)
+
+ (** Representation of a class type. *)
+ and t_class_type = Odoc_class.t_class_type =
+ {
+ clt_name : Name.t ; (** Complete name of the type. *)
+ mutable clt_info : info option ; (** Information found in the optional associated comment. *)
+ clt_type : Types.class_type ;
+ clt_type_parameters : Types.type_expr list ; (** Type parameters. *)
+ clt_virtual : bool ; (** [true] if the class type is virtual *)
+ mutable clt_kind : class_type_kind ; (** The way the class type is defined. *)
+ mutable clt_loc : location ;
+ }
+
+ (** {3 Functions} *)
+
+ (** Access to the elements of a class. *)
+ val class_elements : ?trans:bool -> t_class -> class_element list
+
+ (** Access to the list of class attributes. *)
+ val class_attributes : ?trans:bool -> t_class -> Value.t_attribute list
+
+ (** Access to the description associated to the given class parameter name. *)
+ val class_parameter_text_by_name : t_class -> string -> text option
+
+ (** Access to the methods of a class. *)
+ val class_methods : ?trans:bool -> t_class -> Value.t_method list
+
+ (** Access to the comments of a class. *)
+ val class_comments : ?trans:bool -> t_class -> text list
+
+ (** Access to the elements of a class type. *)
+ val class_type_elements : ?trans:bool -> t_class_type -> class_element list
+
+ (** Access to the list of class type attributes. *)
+ val class_type_attributes : ?trans:bool -> t_class_type -> Value.t_attribute list
+
+ (** Access to the description associated to the given class type parameter name. *)
+ val class_type_parameter_text_by_name : t_class_type -> string -> text option
+
+ (** Access to the methods of a class type. *)
+ val class_type_methods : ?trans:bool -> t_class_type -> Value.t_method list
+
+ (** Access to the comments of a class type. *)
+ val class_type_comments : ?trans:bool -> t_class_type -> text list
+ end
+
+(** Representation and manipulation of modules and module types. *)
+module Module :
+ sig
+ (** {3 Types} *)
+ (** To keep the order of elements in a module. *)
+ type module_element = Odoc_module.module_element =
+ Element_module of t_module
+ | Element_module_type of t_module_type
+ | Element_included_module of included_module
+ | Element_class of Class.t_class
+ | Element_class_type of Class.t_class_type
+ | Element_value of Value.t_value
+ | Element_type_extension of Extension.t_type_extension
+ | Element_exception of Exception.t_exception
+ | Element_type of Type.t_type
+ | Element_module_comment of text
+
+ (** Used where we can reference t_module or t_module_type. *)
+ and mmt = Odoc_module.mmt =
+ | Mod of t_module
+ | Modtype of t_module_type
+
+ and included_module = Odoc_module.included_module =
+ {
+ im_name : Name.t ; (** Complete name of the included module. *)
+ mutable im_module : mmt option ; (** The included module or module type, if we found it. *)
+ mutable im_info : Odoc_types.info option ; (** comment associated to the includ directive *)
+ }
+
+ and module_alias = Odoc_module.module_alias =
+ {
+ ma_name : Name.t ; (** Complete name of the target module. *)
+ mutable ma_module : mmt option ; (** The real module or module type if we could associate it. *)
+ }
+
+ and module_parameter = Odoc_module.module_parameter = {
+ mp_name : string ; (** the name *)
+ mp_type : Types.module_type option ; (** the type *)
+ mp_type_code : string ; (** the original code *)
+ mp_kind : module_type_kind ; (** the way the parameter was built *)
+ }
+
+ (** Different kinds of a module. *)
+ and module_kind = Odoc_module.module_kind =
+ | Module_struct of module_element list (** A complete module structure. *)
+ | Module_alias of module_alias (** Complete name and corresponding module if we found it *)
+ | Module_functor of module_parameter * module_kind
+ (** A functor, with its parameter and the rest of its definition *)
+ | Module_apply of module_kind * module_kind
+ (** A module defined by application of a functor. *)
+ | Module_with of module_type_kind * string
+ (** A module whose type is a with ... constraint.
+ Should appear in interface files only. *)
+ | Module_constraint of module_kind * module_type_kind
+ (** A module constraint by a module type. *)
+ | Module_typeof of string (** by now only the code of the module expression *)
+ | Module_unpack of string * module_type_alias (** code of the expression and module type alias *)
+
+ (** Representation of a module. *)
+ and t_module = Odoc_module.t_module =
+ {
+ m_name : Name.t ; (** Complete name of the module. *)
+ mutable m_type : Types.module_type ; (** The type of the module. *)
+ mutable m_info : info option ; (** Information found in the optional associated comment. *)
+ m_is_interface : bool ; (** [true] for modules read from interface files *)
+ m_file : string ; (** The file the module is defined in. *)
+ mutable m_kind : module_kind ; (** The way the module is defined. *)
+ mutable m_loc : location ;
+ mutable m_top_deps : Name.t list ; (** The toplevels module names this module depends on. *)
+ mutable m_code : string option ; (** The whole code of the module *)
+ mutable m_code_intf : string option ; (** The whole code of the interface of the module *)
+ m_text_only : bool ; (** [true] if the module comes from a text file *)
+ }
+
+ and module_type_alias = Odoc_module.module_type_alias =
+ {
+ mta_name : Name.t ; (** Complete name of the target module type. *)
+ mutable mta_module : t_module_type option ; (** The real module type if we could associate it. *)
+ }
+
+ (** Different kinds of module type. *)
+ and module_type_kind = Odoc_module.module_type_kind =
+ | Module_type_struct of module_element list (** A complete module signature. *)
+ | Module_type_functor of module_parameter * module_type_kind
+ (** A functor, with its parameter and the rest of its definition *)
+ | Module_type_alias of module_type_alias
+ (** Complete alias name and corresponding module type if we found it. *)
+ | Module_type_with of module_type_kind * string
+ (** The module type kind and the code of the with constraint. *)
+ | Module_type_typeof of string
+ (** by now only the code of the module expression *)
+
+ (** Representation of a module type. *)
+ and t_module_type = Odoc_module.t_module_type =
+ {
+ mt_name : Name.t ; (** Complete name of the module type. *)
+ mutable mt_info : info option ; (** Information found in the optional associated comment. *)
+ mutable mt_type : Types.module_type option ; (** [None] means that the module type is abstract. *)
+ mt_is_interface : bool ; (** [true] for modules read from interface files. *)
+ mt_file : string ; (** The file the module type is defined in. *)
+ mutable mt_kind : module_type_kind option ;
+ (** The way the module is defined. [None] means that module type is abstract.
+ It is always [None] when the module type was extracted from the implementation file.
+ That means module types are only analysed in interface files. *)
+ mutable mt_loc : location ;
+ }
+
+ (** {3 Functions for modules} *)
+
+ (** Access to the elements of a module. *)
+ val module_elements : ?trans:bool -> t_module -> module_element list
+
+ (** Access to the submodules of a module. *)
+ val module_modules : ?trans:bool -> t_module -> t_module list
+
+ (** Access to the module types of a module. *)
+ val module_module_types : ?trans:bool -> t_module -> t_module_type list
+
+ (** Access to the included modules of a module. *)
+ val module_included_modules : ?trans:bool-> t_module -> included_module list
+
+ (** Access to the type extensions of a module. *)
+ val module_type_extensions : ?trans:bool-> t_module -> Extension.t_type_extension list
+
+ (** Access to the exceptions of a module. *)
+ val module_exceptions : ?trans:bool-> t_module -> Exception.t_exception list
+
+ (** Access to the types of a module. *)
+ val module_types : ?trans:bool-> t_module -> Type.t_type list
+
+ (** Access to the values of a module. *)
+ val module_values : ?trans:bool -> t_module -> Value.t_value list
+
+ (** Access to functional values of a module. *)
+ val module_functions : ?trans:bool-> t_module -> Value.t_value list
+
+ (** Access to non-functional values of a module. *)
+ val module_simple_values : ?trans:bool-> t_module -> Value.t_value list
+
+ (** Access to the classes of a module. *)
+ val module_classes : ?trans:bool-> t_module -> Class.t_class list
+
+ (** Access to the class types of a module. *)
+ val module_class_types : ?trans:bool-> t_module -> Class.t_class_type list
+
+ (** The list of classes defined in this module and all its submodules and functors. *)
+ val module_all_classes : ?trans:bool-> t_module -> Class.t_class list
+
+ (** [true] if the module is functor. *)
+ val module_is_functor : t_module -> bool
+
+ (** The list of couples (module parameter, optional description). *)
+ val module_parameters : ?trans:bool-> t_module -> (module_parameter * text option) list
+
+ (** The list of module comments. *)
+ val module_comments : ?trans:bool-> t_module -> text list
+
+ (** {3 Functions for module types} *)
+
+ (** Access to the elements of a module type. *)
+ val module_type_elements : ?trans:bool-> t_module_type -> module_element list
+
+ (** Access to the submodules of a module type. *)
+ val module_type_modules : ?trans:bool-> t_module_type -> t_module list
+
+ (** Access to the module types of a module type. *)
+ val module_type_module_types : ?trans:bool-> t_module_type -> t_module_type list
+
+ (** Access to the included modules of a module type. *)
+ val module_type_included_modules : ?trans:bool-> t_module_type -> included_module list
+
+ (** Access to the exceptions of a module type. *)
+ val module_type_exceptions : ?trans:bool-> t_module_type -> Exception.t_exception list
+
+ (** Access to the types of a module type. *)
+ val module_type_types : ?trans:bool-> t_module_type -> Type.t_type list
+
+ (** Access to the values of a module type. *)
+ val module_type_values : ?trans:bool-> t_module_type -> Value.t_value list
+
+ (** Access to functional values of a module type. *)
+ val module_type_functions : ?trans:bool-> t_module_type -> Value.t_value list
+
+ (** Access to non-functional values of a module type. *)
+ val module_type_simple_values : ?trans:bool-> t_module_type -> Value.t_value list
+
+ (** Access to the classes of a module type. *)
+ val module_type_classes : ?trans:bool-> t_module_type -> Class.t_class list
+
+ (** Access to the class types of a module type. *)
+ val module_type_class_types : ?trans:bool-> t_module_type -> Class.t_class_type list
+
+ (** The list of classes defined in this module type and all its submodules and functors. *)
+ val module_type_all_classes : ?trans:bool-> t_module_type -> Class.t_class list
+
+ (** [true] if the module type is functor. *)
+ val module_type_is_functor : t_module_type -> bool
+
+ (** The list of couples (module parameter, optional description). *)
+ val module_type_parameters : ?trans:bool-> t_module_type -> (module_parameter * text option) list
+
+ (** The list of module comments. *)
+ val module_type_comments : ?trans:bool-> t_module_type -> text list
+ end
+
+
+(** {3 Getting strings from values} *)
+
+(** This function is used to reset the names of type variables.
+ It must be called when printing the whole type of a function,
+ but not when printing the type of its parameters. Same for
+ classes (call it) and methods and attributes (don't call it).*)
+val reset_type_names : unit -> unit
+
+(** [string_of_variance t (covariant, invariant)] returns ["+"] if
+ the given information means "covariant", ["-"] if the it means
+ "contravariant", orelse [""], and always [""] if the given
+ type is not an abstract type with no manifest (i.e. no need
+ for the variance to be printed.*)
+val string_of_variance : Type.t_type -> (bool * bool) -> string
+
+(** This function returns a string representing a Types.type_expr. *)
+val string_of_type_expr : Types.type_expr -> string
+
+(** @return a string to display the parameters of the given class,
+ in the same form as the compiler. *)
+val string_of_class_params : Class.t_class -> string
+
+(** This function returns a string to represent the given list of types,
+ with a given separator. *)
+val string_of_type_list : ?par: bool -> string -> Types.type_expr list -> string
+
+(** This function returns a string to represent the list of type parameters
+ for the given type. *)
+val string_of_type_param_list : Type.t_type -> string
+
+(** This function returns a string to represent the list of type parameters
+ for the given type extension. *)
+val string_of_type_extension_param_list : Extension.t_type_extension -> string
+
+(** This function returns a string to represent the given list of
+ type parameters of a class or class type,
+ with a given separator. *)
+val string_of_class_type_param_list : Types.type_expr list -> string
+
+(** This function returns a string representing a [Types.module_type].
+ @param complete indicates if we must print complete signatures
+ or just [sig end]. Default if [false].
+ @param code if [complete = false] and the type contains something else
+ than identificators and functors, then the given code is used.
+*)
+val string_of_module_type : ?code: string -> ?complete: bool -> Types.module_type -> string
+
+(** This function returns a string representing a [Types.class_type].
+ @param complete indicates if we must print complete signatures
+ or just [object end]. Default if [false].
+*)
+val string_of_class_type : ?complete: bool -> Types.class_type -> string
+
+
+(** Get a string from a text. *)
+val string_of_text : text -> string
+
+(** Get a string from an info structure. *)
+val string_of_info : info -> string
+
+(** @return a string to describe the given type. *)
+val string_of_type : Type.t_type -> string
+
+val string_of_record : Type.record_field list -> string
+
+(** @return a string to describe the given type extension. *)
+val string_of_type_extension : Extension.t_type_extension -> string
+
+(** @return a string to describe the given exception. *)
+val string_of_exception : Exception.t_exception -> string
+
+(** @return a string to describe the given value. *)
+val string_of_value : Value.t_value -> string
+
+(** @return a string to describe the given attribute. *)
+val string_of_attribute : Value.t_attribute -> string
+
+(** @return a string to describe the given method. *)
+val string_of_method : Value.t_method -> string
+
+(** {3 Miscelaneous functions} *)
+
+(** Return the first sentence (until the first dot followed by a blank
+ or the first blank line) of a text.
+ Don't stop in the middle of [Code], [CodePre], [Verbatim], [List], [Enum],
+ [Latex], [Link], [Ref], [Subscript] or [Superscript]. *)
+val first_sentence_of_text : text -> text
+
+(** Return the first sentence (until the first dot followed by a blank
+ or the first blank line) of a text, and the remaining text after.
+ Don't stop in the middle of [Code], [CodePre], [Verbatim], [List], [Enum],
+ [Latex], [Link], [Ref], [Subscript] or [Superscript].*)
+val first_sentence_and_rest_of_text : text -> text * text
+
+(** Return the given [text] without any title or list. *)
+val text_no_title_no_list : text -> text
+
+(** [concat sep l] concats the given list of text [l], each separated with
+ the text [sep]. *)
+val text_concat : Odoc_types.text -> Odoc_types.text list -> Odoc_types.text
+
+(** Return the list of titles in a [text].
+ A title is a title level, an optional label and a text.*)
+val get_titles_in_text : text -> (int * string option * text) list
+
+(** Take a sorted list of elements, a function to get the name
+ of an element and return the list of list of elements,
+ where each list group elements beginning by the same letter.
+ Since the original list is sorted, elements whose name does not
+ begin with a letter should be in the first returned list.*)
+val create_index_lists : 'a list -> ('a -> string) -> 'a list list
+
+(** Take a type and remove the option top constructor. This is
+ useful when printing labels, we we then remove the top option contructor
+ for optional labels.*)
+val remove_option : Types.type_expr -> Types.type_expr
+
+(** Return [true] if the given label is optional.*)
+val is_optional : Asttypes.arg_label -> bool
+
+(** Return the label name for the given label,
+ i.e. removes the beginning '?' if present.*)
+val label_name : Asttypes.arg_label -> string
+
+(** Return the given name where the module name or
+ part of it was removed, according to the list of modules
+ which must be hidden (cf {!Odoc_args.hidden_modules})*)
+val use_hidden_modules : Name.t -> Name.t
+
+(** Print the given string if the verbose mode is activated. *)
+val verbose : string -> unit
+
+(** Print a warning message to stderr.
+ If warnings must be treated as errors, then the
+ error counter is incremented. *)
+val warning : string -> unit
+
+(** A flag to indicate whether ocamldoc warnings must be printed or not. *)
+val print_warnings : bool ref
+
+(** Increment this counter when an error is encountered.
+ The ocamldoc tool will print the number of errors
+ encountered exit with code 1 if this number is greater
+ than 0. *)
+val errors : int ref
+
+(** Apply a function to an optional value. *)
+val apply_opt : ('a -> 'b) -> 'a option -> 'b option
+
+(** Apply a function to a first value if it is
+ not different from a second value. If the two values
+ are different, return the second one.*)
+val apply_if_equal : ('a -> 'a) -> 'a -> 'a -> 'a
+
+(** [text_of_string s] returns the text structure from the
+ given string.
+ @raise Text_syntax if a syntax error is encountered. *)
+val text_of_string : string -> text
+
+(** [text_string_of_text text] returns the string representing
+ the given [text]. This string can then be parsed again
+ by {!Odoc_info.text_of_string}.*)
+val text_string_of_text : text -> string
+
+(** [info_of_string s] parses the given string
+ like a regular ocamldoc comment and return an
+ {!Odoc_info.info} structure.
+ @return an empty structure if there was a syntax error. TODO: change this
+*)
+val info_of_string : string -> info
+
+(** [info_string_of_info info] returns the string representing
+ the given [info]. This string can then be parsed again
+ by {!Odoc_info.info_of_string}.*)
+val info_string_of_info : info -> string
+
+(** [info_of_comment_file file] parses the given file
+ and return an {!Odoc_info.info} structure. The content of the
+ file must have the same syntax as the content of a special comment.
+ The given module list is used for cross reference.
+ @raise Failure is the file could not be opened or there is a
+ syntax error.
+*)
+val info_of_comment_file : Module.t_module list -> string -> info
+
+(** [remove_ending_newline s] returns [s] without the optional ending newline. *)
+val remove_ending_newline : string -> string
+
+(** Research in elements *)
+module Search :
+ sig
+ type result_element = Odoc_search.result_element =
+ Res_module of Module.t_module
+ | Res_module_type of Module.t_module_type
+ | Res_class of Class.t_class
+ | Res_class_type of Class.t_class_type
+ | Res_value of Value.t_value
+ | Res_type of Type.t_type
+ | Res_extension of Extension.t_extension_constructor
+ | Res_exception of Exception.t_exception
+ | Res_attribute of Value.t_attribute
+ | Res_method of Value.t_method
+ | Res_section of string * text
+ | Res_recfield of Type.t_type * Type.record_field
+ | Res_const of Type.t_type * Type.variant_constructor
+
+ (** The type representing a research result.*)
+ type search_result = result_element list
+
+ (** Research of the elements whose name matches the given regular expression.*)
+ val search_by_name : Module.t_module list -> Str.regexp -> search_result
+
+ (** A function to search all the values in a list of modules. *)
+ val values : Module.t_module list -> Value.t_value list
+
+ (** A function to search all the extensions in a list of modules. *)
+ val extensions : Module.t_module list -> Extension.t_extension_constructor list
+
+ (** A function to search all the exceptions in a list of modules. *)
+ val exceptions : Module.t_module list -> Exception.t_exception list
+
+ (** A function to search all the types in a list of modules. *)
+ val types : Module.t_module list -> Type.t_type list
+
+ (** A function to search all the class attributes in a list of modules. *)
+ val attributes : Module.t_module list -> Value.t_attribute list
+
+ (** A function to search all the class methods in a list of modules. *)
+ val methods : Module.t_module list -> Value.t_method list
+
+ (** A function to search all the classes in a list of modules. *)
+ val classes : Module.t_module list -> Class.t_class list
+
+ (** A function to search all the class types in a list of modules. *)
+ val class_types : Module.t_module list -> Class.t_class_type list
+
+ (** A function to search all the modules in a list of modules. *)
+ val modules : Module.t_module list -> Module.t_module list
+
+ (** A function to search all the module types in a list of modules. *)
+ val module_types : Module.t_module list -> Module.t_module_type list
+
+ end
+
+(** Scanning of collected information *)
+module Scan :
+ sig
+ class scanner :
+ object
+ (** Scan of 'leaf elements'. *)
+
+ method scan_value : Value.t_value -> unit
+
+ method scan_type_pre : Type.t_type -> bool
+ method scan_type_const : Type.t_type -> Type.variant_constructor -> unit
+ method scan_type_recfield : Type.t_type -> Type.record_field -> unit
+ method scan_type : Type.t_type -> unit
+ method scan_extension_constructor : Extension.t_extension_constructor -> unit
+ method scan_exception : Exception.t_exception -> unit
+ method scan_attribute : Value.t_attribute -> unit
+ method scan_method : Value.t_method -> unit
+ method scan_included_module : Module.included_module -> unit
+
+ (** Scan of a type extension *)
+
+ (** Overide this method to perform controls on the extension's type,
+ private and info. This method is called before scanning the
+ extension's constructors.
+ @return true if the extension's constructors must be scanned.*)
+ method scan_type_extension_pre : Extension.t_type_extension -> bool
+
+ (** This method scans the constructors of the given type extension. *)
+ method scan_type_extension_constructors : Extension.t_type_extension -> unit
+
+ (** Scan of a type extension. Should not be overridden. It calls [scan_type_extension_pre]
+ and if [scan_type_extension_pre] returns [true], then it calls scan_type_extension_constructors.*)
+ method scan_type_extension : Extension.t_type_extension -> unit
+
+ (** Scan of a class. *)
+
+ (** Scan of a comment inside a class. *)
+ method scan_class_comment : text -> unit
+
+ (** Override this method to perform controls on the class comment
+ and params. This method is called before scanning the class elements.
+ @return true if the class elements must be scanned.*)
+ method scan_class_pre : Class.t_class -> bool
+
+ (** This method scan the elements of the given class. *)
+ method scan_class_elements : Class.t_class -> unit
+
+ (** Scan of a class. Should not be overridden. It calls [scan_class_pre]
+ and if [scan_class_pre] returns [true], then it calls scan_class_elements.*)
+ method scan_class : Class.t_class -> unit
+
+ (** Scan of a class type. *)
+
+ (** Scan of a comment inside a class type. *)
+ method scan_class_type_comment : text -> unit
+
+ (** Override this method to perform controls on the class type comment
+ and form. This method is called before scanning the class type elements.
+ @return true if the class type elements must be scanned.*)
+ method scan_class_type_pre : Class.t_class_type -> bool
+
+ (** This method scan the elements of the given class type. *)
+ method scan_class_type_elements : Class.t_class_type -> unit
+
+ (** Scan of a class type. Should not be overridden. It calls [scan_class_type_pre]
+ and if [scan_class_type_pre] returns [true], then it calls scan_class_type_elements.*)
+ method scan_class_type : Class.t_class_type -> unit
+
+ (** Scan of modules. *)
+
+ (** Scan of a comment inside a module. *)
+ method scan_module_comment : text -> unit
+
+ (** Override this method to perform controls on the module comment
+ and form. This method is called before scanning the module elements.
+ @return true if the module elements must be scanned.*)
+ method scan_module_pre : Module.t_module -> bool
+
+ (** This method scan the elements of the given module. *)
+ method scan_module_elements : Module.t_module -> unit
+
+ (** Scan of a module. Should not be overridden. It calls [scan_module_pre]
+ and if [scan_module_pre] returns [true], then it calls scan_module_elements.*)
+ method scan_module : Module.t_module -> unit
+
+ (** Scan of module types. *)
+
+ (** Scan of a comment inside a module type. *)
+ method scan_module_type_comment : text -> unit
+
+ (** Override this method to perform controls on the module type comment
+ and form. This method is called before scanning the module type elements.
+ @return true if the module type elements must be scanned. *)
+ method scan_module_type_pre : Module.t_module_type -> bool
+
+ (** This method scan the elements of the given module type. *)
+ method scan_module_type_elements : Module.t_module_type -> unit
+
+ (** Scan of a module type. Should not be overridden. It calls [scan_module_type_pre]
+ and if [scan_module_type_pre] returns [true], then it calls scan_module_type_elements.*)
+ method scan_module_type : Module.t_module_type -> unit
+
+ (** Main scanning method. *)
+
+ (** Scan a list of modules. *)
+ method scan_module_list : Module.t_module list -> unit
+ end
+ end
+
+(** Computation of dependencies. *)
+module Dep :
+ sig
+ (** Modify the modules depencies of the given list of modules,
+ to get the minimum transitivity kernel. *)
+ val kernel_deps_of_modules : Module.t_module list -> unit
+
+ (** Return the list of dependencies between the given types,
+ in the form of a list [(type name, names of types it depends on)].
+ @param kernel indicates if we must keep only the transitivity kernel
+ of the dependencies. Default is [false].
+ *)
+ val deps_of_types : ?kernel: bool -> Type.t_type list -> (Type.t_type * (Name.t list)) list
+ end
+
+(** {2 Some global variables} *)
+
+module Global :
+ sig
+ val errors : int ref
+ val warn_error : bool ref
+
+ (** The file used by the generators outputting only one file. *)
+ val out_file : string ref
+
+ (** Verbose mode or not. *)
+ val verbose : bool ref
+
+ (** The directory where files have to be generated. *)
+ val target_dir : string ref
+
+ (** The optional title to use in the generated documentation. *)
+ val title : string option ref
+
+ (** The optional file whose content can be used as intro text. *)
+ val intro_file : string option ref
+
+ (** The flag which indicates if we must generate a table of contents. *)
+ val with_toc : bool ref
+
+ (** The flag which indicates if we must generate an index. *)
+ val with_index : bool ref
+
+ (** The flag which indicates if we must generate a header.*)
+ val with_header : bool ref
+
+ (** The flag which indicates if we must generate a trailer.*)
+ val with_trailer : bool ref
+end
+
+(** Analysis of the given source files.
+ @param init is the list of modules already known from a previous analysis.
+ @return the list of analysed top modules. *)
+val analyse_files :
+ ?merge_options:Odoc_types.merge_option list ->
+ ?include_dirs:string list ->
+ ?labels:bool ->
+ ?sort_modules:bool ->
+ ?no_stop:bool ->
+ ?init: Odoc_module.t_module list ->
+ Odoc_global.source_file list ->
+ Module.t_module list
+
+(** Dump of a list of modules into a file.
+ @raise Failure if an error occurs.*)
+val dump_modules : string -> Odoc_module.t_module list -> unit
+
+(** Load of a list of modules from a file.
+ @raise Failure if an error occurs.*)
+val load_modules : string -> Odoc_module.t_module list
diff --git a/ocamldoc/odoc_inherit.ml b/ocamldoc/odoc_inherit.ml
new file mode 100644
index 0000000000..30a1f393d8
--- /dev/null
+++ b/ocamldoc/odoc_inherit.ml
@@ -0,0 +1,11 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
diff --git a/ocamldoc/odoc_latex.ml b/ocamldoc/odoc_latex.ml
new file mode 100644
index 0000000000..2273a6d0ab
--- /dev/null
+++ b/ocamldoc/odoc_latex.ml
@@ -0,0 +1,1334 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Generation of LaTeX documentation. *)
+
+let print_DEBUG s = print_string s ; print_newline ()
+
+open Odoc_info
+open Parameter
+open Value
+open Type
+open Extension
+open Exception
+open Class
+open Module
+
+
+
+let separate_files = ref false
+
+let latex_titles = ref [
+ 1, "section" ;
+ 2, "subsection" ;
+ 3, "subsubsection" ;
+ 4, "paragraph" ;
+ 5, "subparagraph" ;
+]
+
+let latex_value_prefix = ref Odoc_messages.default_latex_value_prefix
+let latex_type_prefix = ref Odoc_messages.default_latex_type_prefix
+let latex_type_elt_prefix = ref Odoc_messages.default_latex_type_elt_prefix
+let latex_extension_prefix = ref Odoc_messages.default_latex_extension_prefix
+let latex_exception_prefix = ref Odoc_messages.default_latex_exception_prefix
+let latex_module_prefix = ref Odoc_messages.default_latex_module_prefix
+let latex_module_type_prefix = ref Odoc_messages.default_latex_module_type_prefix
+let latex_class_prefix = ref Odoc_messages.default_latex_class_prefix
+let latex_class_type_prefix = ref Odoc_messages.default_latex_class_type_prefix
+let latex_attribute_prefix = ref Odoc_messages.default_latex_attribute_prefix
+let latex_method_prefix = ref Odoc_messages.default_latex_method_prefix
+
+let new_buf () = Buffer.create 1024
+let new_fmt () =
+ let b = new_buf () in
+ let fmt = Format.formatter_of_buffer b in
+ (fmt,
+ fun () ->
+ Format.pp_print_flush fmt ();
+ let s = Buffer.contents b in
+ Buffer.reset b;
+ s
+ )
+
+let p = Format.fprintf
+let ps f s = Format.fprintf f "%s" s
+
+
+let bp = Printf.bprintf
+let bs = Buffer.add_string
+
+let print_concat fmt sep f =
+ let rec iter = function
+ [] -> ()
+ | [c] -> f c
+ | c :: q ->
+ f c;
+ ps fmt sep;
+ iter q
+ in
+ iter
+
+(** Generation of LaTeX code from text structures. *)
+class text =
+ object (self)
+ (** Return latex code to make a sectionning according to the given level,
+ and with the given latex code. *)
+ method section_style level s =
+ try
+ let sec = List.assoc level !latex_titles in
+ "\\"^sec^"{"^s^"}\n"
+ with Not_found -> s
+
+ (** Associations of strings to substitute in latex code. *)
+ val subst_strings = List.map (fun (x, y) -> (Str.regexp x, y))
+ [
+ "\001", "\001\002";
+ "\\\\", "\001b";
+
+ "{", "\\\\{";
+ "}", "\\\\}";
+ "\\$", "\\\\$";
+ "\\^", "{\\\\textasciicircum}";
+ "\xE0", "\\\\`a";
+ "\xE2", "\\\\^a";
+ "\xE9", "\\\\'e";
+ "\xE8", "\\\\`e";
+ "\xEA", "\\\\^e";
+ "\xEB", "\\\\\"e";
+ "\xE7", "\\\\c{c}";
+ "\xF4", "\\\\^o";
+ "\xF6", "\\\\\"o";
+ "\xEE", "\\\\^i";
+ "\xEF", "\\\\\"i";
+ "\xF9", "\\\\`u";
+ "\xFB", "\\\\^u";
+ "%", "\\\\%";
+ "_", "\\\\_";
+ "~", "\\\\~{}";
+ "#", "{\\char35}";
+ "->", "$\\\\rightarrow$";
+ "<-", "$\\\\leftarrow$";
+ ">=", "$\\\\geq$";
+ "<=", "$\\\\leq$";
+ ">", "$>$";
+ "<", "$<$";
+ "=", "$=$";
+ "|", "{\\\\textbar}";
+ "\\.\\.\\.", "$\\\\ldots$";
+ "&", "\\\\&";
+
+ "\001b", "{\\\\char92}";
+ "\001\002", "\001";
+ ]
+
+ val subst_strings_simple = List.map (fun (x, y) -> (Str.regexp x, y))
+ [
+ "\001", "\001\002";
+ "\\\\", "\001b";
+ "{", "\001l";
+
+ "}", "{\\\\char125}";
+ "'", "{\\\\textquotesingle}";
+ "`", "{\\\\textasciigrave}";
+
+ "\001b", "{\\\\char92}";
+ "\001l", "{\\\\char123}";
+ "\001\002", "\001";
+ ]
+
+ val subst_strings_code = List.map (fun (x, y) -> (Str.regexp x, y))
+ [
+ "\001", "\001\002";
+ "\\\\", "\001b";
+ "{", "\001l";
+
+ "}", "{\\\\char125}";
+ "'", "{\\\\textquotesingle}";
+ "`", "{\\\\textasciigrave}";
+ "%", "\\\\%";
+ "_", "\\\\_";
+ "~", "{\\\\char126}";
+ "#", "{\\\\char35}";
+ "&", "\\\\&";
+ "\\$", "\\\\$";
+ "\\^", "{\\\\char94}";
+
+ "\001b", "{\\\\char92}";
+ "\001l", "{\\\\char123}";
+ "\001\002", "\001";
+ ]
+
+ method subst l s =
+ List.fold_left (fun acc (re, st) -> Str.global_replace re st acc) s l
+
+ (** Escape the strings which would clash with LaTeX syntax. *)
+ method escape s = self#subst subst_strings s
+
+ (** Escape the ['\'], ['{'] and ['}'] characters. *)
+ method escape_simple s = self#subst subst_strings_simple s
+
+ (** Escape some characters for the code style. *)
+ method escape_code s = self#subst subst_strings_code s
+
+ (** Make a correct latex label from a name. *)
+ (* The following characters are forbidden in LaTeX \index:
+ \ { } $ & # ^ _ % ~ ! " @ | (" to close the double quote)
+ The following characters are forbidden in LaTeX \label:
+ \ { } $ & # ^ _ % ~
+ So we will use characters not forbidden in \index if no_ = true.
+ *)
+ method label ?(no_=true) name =
+ let len = String.length name in
+ let buf = Buffer.create len in
+ for i = 0 to len - 1 do
+ let (s_no_, s) =
+ match name.[i] with
+ '_' -> ("-underscore", "_")
+ | '~' -> ("-tilde", "~")
+ | '%' -> ("-percent", "%")
+ | '@' -> ("-at", "\"@")
+ | '!' -> ("-bang", "\"!")
+ | '|' -> ("-pipe", "\"|")
+ | '<' -> ("-lt", "<")
+ | '>' -> ("-gt", ">")
+ | '^' -> ("-exp", "^")
+ | '&' -> ("-ampersand", "&")
+ | '+' -> ("-plus", "+")
+ | '-' -> ("-minus", "-")
+ | '*' -> ("-star", "*")
+ | '/' -> ("-slash", "/")
+ | '$' -> ("-dollar", "$")
+ | '=' -> ("-equal", "=")
+ | ':' -> ("-colon", ":")
+ | c -> (String.make 1 c, String.make 1 c)
+ in
+ Buffer.add_string buf (if no_ then s_no_ else s)
+ done;
+ Buffer.contents buf
+
+ (** Make a correct label from a value name. *)
+ method value_label ?no_ name = !latex_value_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from an attribute name. *)
+ method attribute_label ?no_ name = !latex_attribute_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from a method name. *)
+ method method_label ?no_ name = !latex_method_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from a class name. *)
+ method class_label ?no_ name = !latex_class_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from a class type name. *)
+ method class_type_label ?no_ name = !latex_class_type_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from a module name. *)
+ method module_label ?no_ name = !latex_module_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from a module type name. *)
+ method module_type_label ?no_ name = !latex_module_type_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from an extension name. *)
+ method extension_label ?no_ name = !latex_extension_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from an exception name. *)
+ method exception_label ?no_ name = !latex_exception_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from a type name. *)
+ method type_label ?no_ name = !latex_type_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from a record field. *)
+ method recfield_label ?no_ name = !latex_type_elt_prefix^(self#label ?no_ name)
+
+ (** Make a correct label from a variant constructor. *)
+ method const_label ?no_ name = !latex_type_elt_prefix^(self#label ?no_ name)
+
+ (** Return latex code for the label of a given label. *)
+ method make_label label = "\\label{"^label^"}"
+
+ (** Return latex code for the ref to a given label. *)
+ method make_ref label = "\\ref{"^label^"}"
+
+ (** Print the LaTeX code corresponding to the [text] parameter.*)
+ method latex_of_text fmt t =
+ List.iter (self#latex_of_text_element fmt) t
+
+ (** Print the LaTeX code for the [text_element] in parameter. *)
+ method latex_of_text_element fmt txt =
+ match txt with
+ | Odoc_info.Raw s -> self#latex_of_Raw fmt s
+ | Odoc_info.Code s -> self#latex_of_Code fmt s
+ | Odoc_info.CodePre s -> self#latex_of_CodePre fmt s
+ | Odoc_info.Verbatim s -> self#latex_of_Verbatim fmt s
+ | Odoc_info.Bold t -> self#latex_of_Bold fmt t
+ | Odoc_info.Italic t -> self#latex_of_Italic fmt t
+ | Odoc_info.Emphasize t -> self#latex_of_Emphasize fmt t
+ | Odoc_info.Center t -> self#latex_of_Center fmt t
+ | Odoc_info.Left t -> self#latex_of_Left fmt t
+ | Odoc_info.Right t -> self#latex_of_Right fmt t
+ | Odoc_info.List tl -> self#latex_of_List fmt tl
+ | Odoc_info.Enum tl -> self#latex_of_Enum fmt tl
+ | Odoc_info.Newline -> self#latex_of_Newline fmt
+ | Odoc_info.Block t -> self#latex_of_Block fmt t
+ | Odoc_info.Title (n, l_opt, t) -> self#latex_of_Title fmt n l_opt t
+ | Odoc_info.Latex s -> self#latex_of_Latex fmt s
+ | Odoc_info.Link (s, t) -> self#latex_of_Link fmt s t
+ | Odoc_info.Ref (name, ref_opt, text_opt) ->
+ self#latex_of_Ref fmt name ref_opt text_opt
+ | Odoc_info.Superscript t -> self#latex_of_Superscript fmt t
+ | Odoc_info.Subscript t -> self#latex_of_Subscript fmt t
+ | Odoc_info.Module_list _ -> ()
+ | Odoc_info.Index_list -> ()
+ | Odoc_info.Custom (s,t) -> self#latex_of_custom_text fmt s t
+ | Odoc_info.Target (target, code) -> self#latex_of_Target fmt ~target ~code
+
+ method latex_of_custom_text fmt s t = ()
+
+ method latex_of_Target fmt ~target ~code =
+ if String.lowercase_ascii target = "latex" then
+ self#latex_of_Latex fmt code
+ else
+ ()
+
+ method latex_of_Raw fmt s =
+ ps fmt (self#escape s)
+
+ method latex_of_Code fmt s =
+ let s2 = self#escape_code s in
+ let s3 = Str.global_replace (Str.regexp "\n") ("\\\\\n") s2 in
+ p fmt "{\\tt{%s}}" s3
+
+ method latex_of_CodePre fmt s =
+ ps fmt "\\begin{ocamldoccode}\n";
+ ps fmt (self#escape_simple s);
+ ps fmt "\n\\end{ocamldoccode}\n"
+
+ method latex_of_Verbatim fmt s =
+ ps fmt "\n\\begin{verbatim}\n";
+ ps fmt s;
+ ps fmt "\n\\end{verbatim}\n"
+
+ method latex_of_Bold fmt t =
+ ps fmt "{\\bf ";
+ self#latex_of_text fmt t;
+ ps fmt "}"
+
+ method latex_of_Italic fmt t =
+ ps fmt "{\\it ";
+ self#latex_of_text fmt t;
+ ps fmt "}"
+
+ method latex_of_Emphasize fmt t =
+ ps fmt "{\\em ";
+ self#latex_of_text fmt t;
+ ps fmt "}"
+
+ method latex_of_Center fmt t =
+ ps fmt "\\begin{center}\n";
+ self#latex_of_text fmt t;
+ ps fmt "\\end{center}\n"
+
+ method latex_of_Left fmt t =
+ ps fmt "\\begin{flushleft}\n";
+ self#latex_of_text fmt t;
+ ps fmt "\\end{flushleft}\n"
+
+ method latex_of_Right fmt t =
+ ps fmt "\\begin{flushright}\n";
+ self#latex_of_text fmt t;
+ ps fmt "\\end{flushright}\n"
+
+ method latex_of_List fmt tl =
+ ps fmt "\\begin{itemize}\n";
+ List.iter
+ (fun t ->
+ ps fmt "\\item ";
+ self#latex_of_text fmt t;
+ ps fmt "\n"
+ )
+ tl;
+ ps fmt "\\end{itemize}\n"
+
+ method latex_of_Enum fmt tl =
+ ps fmt "\\begin{enumerate}\n";
+ List.iter
+ (fun t ->
+ ps fmt "\\item ";
+ self#latex_of_text fmt t;
+ ps fmt "\n"
+ )
+ tl;
+ ps fmt "\\end{enumerate}\n"
+
+ method latex_of_Newline fmt = ps fmt "\n\n"
+
+ method latex_of_Block fmt t =
+ ps fmt "\\begin{ocamldocdescription}\n";
+ self#latex_of_text fmt t;
+ ps fmt "\n\\end{ocamldocdescription}\n"
+
+ method latex_of_Title fmt n label_opt t =
+ let (fmt2, flush) = new_fmt () in
+ self#latex_of_text fmt2 t;
+ let s_title2 = self#section_style n (flush ()) in
+ ps fmt s_title2;
+ (
+ match label_opt with
+ None -> ()
+ | Some l ->
+ ps fmt (self#make_label (self#label ~no_: false l))
+ )
+
+ method latex_of_Latex fmt s = ps fmt s
+
+ method latex_of_Link fmt s t =
+ self#latex_of_text fmt t ;
+ ps fmt "[\\url{";
+ ps fmt s ;
+ ps fmt "}]"
+
+ method latex_of_Ref fmt name ref_opt text_opt =
+ match ref_opt with
+ None ->
+ self#latex_of_text fmt
+ (match text_opt with
+ None ->
+ [Odoc_info.Code (Odoc_info.use_hidden_modules name)]
+ | Some t -> t
+ )
+ | Some (RK_section _) ->
+ self#latex_of_text_element fmt
+ (Latex ("["^(self#make_ref (self#label ~no_:false (Name.simple name)))^"]"))
+ | Some kind ->
+ let f_label =
+ match kind with
+ Odoc_info.RK_module -> self#module_label
+ | Odoc_info.RK_module_type -> self#module_type_label
+ | Odoc_info.RK_class -> self#class_label
+ | Odoc_info.RK_class_type -> self#class_type_label
+ | Odoc_info.RK_value -> self#value_label
+ | Odoc_info.RK_type -> self#type_label
+ | Odoc_info.RK_extension -> self#extension_label
+ | Odoc_info.RK_exception -> self#exception_label
+ | Odoc_info.RK_attribute -> self#attribute_label
+ | Odoc_info.RK_method -> self#method_label
+ | Odoc_info.RK_section _ -> assert false
+ | Odoc_info.RK_recfield -> self#recfield_label
+ | Odoc_info.RK_const -> self#const_label
+ in
+ let text =
+ match text_opt with
+ None -> [Odoc_info.Code (Odoc_info.use_hidden_modules name)]
+ | Some t -> t
+ in
+ self#latex_of_text fmt
+ (text @ [Latex ("["^(self#make_ref (f_label name))^"]")])
+
+ method latex_of_Superscript fmt t =
+ ps fmt "$^{";
+ self#latex_of_text fmt t;
+ ps fmt "}$"
+
+ method latex_of_Subscript fmt t =
+ ps fmt "$_{";
+ self#latex_of_text fmt t;
+ ps fmt "}$"
+
+ end
+
+(** A class used to generate LaTeX code for info structures. *)
+class virtual info =
+ object (self)
+ (** The method used to get LaTeX code from a [text]. *)
+ method virtual latex_of_text : Format.formatter -> Odoc_info.text -> unit
+
+ (** The method used to get a [text] from an optionel info structure. *)
+ method virtual text_of_info : ?block: bool -> Odoc_info.info option -> Odoc_info.text
+
+ (** Print LaTeX code for a description, except for the [i_params] field. *)
+ method latex_of_info fmt ?(block=false) info_opt =
+ self#latex_of_text fmt
+ (self#text_of_info ~block info_opt)
+ end
+
+module Generator =
+struct
+(** This class is used to create objects which can generate a simple LaTeX documentation. *)
+class latex =
+ object (self)
+ inherit text
+ inherit Odoc_to_text.to_text as to_text
+ inherit info
+
+ (** Get the first sentence and the rest of a description,
+ from an optional [info] structure. The first sentence
+ can be empty if it would not appear right in a title.
+ In the first sentence, the titles and lists has been removed,
+ since it is used in LaTeX titles and would make LaTeX complain
+ if we has two nested \section commands.
+ *)
+ method first_and_rest_of_info i_opt =
+ match i_opt with
+ None -> ([], [])
+ | Some i ->
+ match i.Odoc_info.i_desc with
+ None -> ([], self#text_of_info ~block: true i_opt)
+ | Some t ->
+ let (first,_) = Odoc_info.first_sentence_and_rest_of_text t in
+ let (_, rest) = Odoc_info.first_sentence_and_rest_of_text (self#text_of_info ~block: false i_opt) in
+ (Odoc_info.text_no_title_no_list first, rest)
+
+ (** Print LaTeX code for a value. *)
+ method latex_of_value fmt v =
+ Odoc_info.reset_type_names () ;
+ let label = self#value_label v.val_name in
+ let latex = self#make_label label in
+ self#latex_of_text fmt
+ ((Latex latex) ::
+ (to_text#text_of_value v))
+
+ (** Print LaTeX code for a class attribute. *)
+ method latex_of_attribute fmt a =
+ self#latex_of_text fmt
+ ((Latex (self#make_label (self#attribute_label a.att_value.val_name))) ::
+ (to_text#text_of_attribute a))
+
+ (** Print LaTeX code for a class method. *)
+ method latex_of_method fmt m =
+ self#latex_of_text fmt
+ ((Latex (self#make_label (self#method_label m.met_value.val_name))) ::
+ (to_text#text_of_method m))
+
+ (** Print LaTeX code for the parameters of a type. *)
+ method latex_of_type_params fmt m_name t =
+ let print_one (p, co, cn) =
+ ps fmt (Odoc_info.string_of_variance t (co,cn));
+ ps fmt (self#normal_type m_name p)
+ in
+ match t.ty_parameters with
+ [] -> ()
+ | [(p,co,cn)] -> print_one (p, co, cn)
+ | l ->
+ ps fmt "(";
+ print_concat fmt ", " print_one t.ty_parameters;
+ ps fmt ")"
+
+ method latex_of_class_parameter_list fmt father c =
+ self#latex_of_text fmt
+ (self#text_of_class_params father c)
+
+ (** Print LaTeX code for a type. *)
+ method latex_of_type fmt t =
+ let s_name = Name.simple t.ty_name in
+ let text =
+ let (fmt2, flush2) = new_fmt () in
+ Odoc_info.reset_type_names () ;
+ let mod_name = Name.father t.ty_name in
+ Format.fprintf fmt2 "@[<h 2>type ";
+ self#latex_of_type_params fmt2 mod_name t;
+ (match t.ty_parameters with [] -> () | _ -> ps fmt2 " ");
+ ps fmt2 s_name;
+ let priv = t.ty_private = Asttypes.Private in
+ (
+ match t.ty_manifest with
+ | Some (Other typ) ->
+ p fmt2 " = %s%s" (if priv then "private " else "") (self#normal_type mod_name typ)
+ | _ -> ()
+ );
+ let s_type3 =
+ p fmt2
+ " %s"
+ (
+ match t.ty_kind with
+ Type_abstract ->
+ begin match t.ty_manifest with
+ | Some (Object_type _) ->
+ "= " ^ (if priv then "private" else "") ^ " <"
+ | _ -> ""
+ end
+ | Type_variant _ -> "="^(if priv then " private" else "")
+ | Type_record _ -> "= "^(if priv then "private " else "")^"{"
+ | Type_open -> "= .."
+ ) ;
+ flush2 ()
+ in
+
+ let defs =
+ let entry_comment = function
+ | None -> []
+ | Some t ->
+ let s =
+ ps fmt2 "\\begin{ocamldoccomment}\n";
+ self#latex_of_info fmt2 (Some t);
+ ps fmt2 "\n\\end{ocamldoccomment}\n";
+ flush2 ()
+ in
+ [ Latex s]
+ in
+ match t.ty_kind with
+ | Type_abstract ->
+ begin match t.ty_manifest with
+ | Some (Object_type l) ->
+ let fields =
+ List.map (fun r ->
+ let s_field =
+ p fmt2
+ "@[<h 6> %s :@ %s ;"
+ r.of_name
+ (self#normal_type mod_name r.of_type);
+ flush2 ()
+ in
+ [ CodePre s_field ] @ (entry_comment r.of_text)
+ ) l
+ in
+ List.flatten fields @ [ CodePre ">" ]
+
+ | None | Some (Other _) -> []
+ end
+ | Type_variant l ->
+ let constructors =
+ List.map (fun constr ->
+ let s_cons =
+ p fmt2 "@[<h 6> | %s" constr.vc_name ;
+ begin match constr.vc_args, constr.vc_ret with
+ | Cstr_tuple [], None -> ()
+ | l, None ->
+ p fmt2 " of@ %s"
+ (self#normal_cstr_args ~par: false mod_name l)
+ | Cstr_tuple [], Some r ->
+ p fmt2 " :@ %s"
+ (self#normal_type mod_name r)
+ | l, Some r ->
+ p fmt2 " :@ %s@ %s@ %s"
+ (self#normal_cstr_args ~par: false mod_name l)
+ "->"
+ (self#normal_type mod_name r)
+ end ;
+ flush2 ()
+ in
+ [ CodePre s_cons ] @ (entry_comment constr.vc_text)
+ ) l
+ in
+ List.flatten constructors
+ | Type_record l ->
+ let fields =
+ List.map (fun r ->
+ let s_field =
+ p fmt2
+ "@[<h 6> %s%s :@ %s ;"
+ (if r.rf_mutable then "mutable " else "")
+ r.rf_name
+ (self#normal_type mod_name r.rf_type);
+ flush2 ()
+ in
+ [ CodePre s_field ] @ (entry_comment r.rf_text)
+ ) l
+ in
+ List.flatten fields @ [ CodePre "}" ]
+ | Type_open ->
+ (* FIXME ? *)
+ []
+ in
+ let defs2 = (CodePre s_type3) :: defs in
+ let rec iter = function
+ [] -> []
+ | [e] -> [e]
+ | (CodePre s1) :: (CodePre s2) :: q ->
+ iter ((CodePre (s1^"\n"^s2)) :: q)
+ | e :: q ->
+ e :: (iter q)
+ in
+ (iter defs2) @
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @
+ (self#text_of_info t.ty_info)
+ in
+ self#latex_of_text fmt
+ ((Latex (self#make_label (self#type_label t.ty_name))) :: text)
+
+ (** Print LaTeX code for a type extension. *)
+ method latex_of_type_extension mod_name fmt te =
+ let text =
+ let (fmt2, flush2) = new_fmt () in
+ Odoc_info.reset_type_names () ;
+ Format.fprintf fmt2 "@[<h 2>type ";
+ (
+ match te.te_type_parameters with
+ [] -> ()
+ | [p] ->
+ ps fmt2 (self#normal_type mod_name p);
+ ps fmt2 " "
+ | l ->
+ ps fmt2 "(";
+ print_concat fmt2 ", " (fun p -> ps fmt2 (self#normal_type mod_name p)) l;
+ ps fmt2 ") "
+ );
+ ps fmt2 (self#relative_idents mod_name te.te_type_name);
+ p fmt2 " +=%s" (if te.te_private = Asttypes.Private then " private" else "") ;
+ let s_type3 = flush2 () in
+ let defs =
+ (List.flatten
+ (List.map
+ (fun x ->
+ let father = Name.father x.xt_name in
+ let s_cons =
+ p fmt2 "@[<h 6> | %s" (Name.simple x.xt_name);
+ (
+ match x.xt_args, x.xt_ret with
+ Cstr_tuple [], None -> ()
+ | l, None ->
+ p fmt2 " %s@ %s"
+ "of"
+ (self#normal_cstr_args ~par: false father l)
+ | Cstr_tuple [], Some r ->
+ p fmt2 " %s@ %s"
+ ":"
+ (self#normal_type father r)
+ | l, Some r ->
+ p fmt2 " %s@ %s@ %s@ %s"
+ ":"
+ (self#normal_cstr_args ~par: false father l)
+ "->"
+ (self#normal_type father r)
+ );
+ (
+ match x.xt_alias with
+ None -> ()
+ | Some xa ->
+ p fmt2 " = %s"
+ (
+ match xa.xa_xt with
+ None -> xa.xa_name
+ | Some x -> x.xt_name
+ )
+ );
+ flush2 ()
+ in
+ [ Latex (self#make_label (self#extension_label x.xt_name));
+ CodePre s_cons ] @
+ (match x.xt_text with
+ None -> []
+ | Some t ->
+ let s =
+ ps fmt2 "\\begin{ocamldoccomment}\n";
+ self#latex_of_info fmt2 (Some t);
+ ps fmt2 "\n\\end{ocamldoccomment}\n";
+ flush2 ()
+ in
+ [ Latex s]
+ )
+ )
+ te.te_constructors
+ )
+ )
+ in
+ let defs2 = (CodePre s_type3) :: defs in
+ let rec iter = function
+ [] -> []
+ | [e] -> [e]
+ | (CodePre s1) :: (CodePre s2) :: q ->
+ iter ((CodePre (s1^"\n"^s2)) :: q)
+ | e :: q ->
+ e :: (iter q)
+ in
+ (iter defs2) @
+ (self#text_of_info te.te_info)
+ in
+ self#latex_of_text fmt text
+
+ (** Print LaTeX code for an exception. *)
+ method latex_of_exception fmt e =
+ Odoc_info.reset_type_names () ;
+ self#latex_of_text fmt
+ ((Latex (self#make_label (self#exception_label e.ex_name))) ::
+ (to_text#text_of_exception e))
+
+ method latex_of_module_parameter fmt m_name p =
+ self#latex_of_text fmt
+ [
+ Code "functor (";
+ Code p.mp_name ;
+ Code " : ";
+ ] ;
+ self#latex_of_module_type_kind fmt m_name p.mp_kind;
+ self#latex_of_text fmt [ Code ") -> "]
+
+
+ method latex_of_module_type_kind fmt father kind =
+ match kind with
+ Module_type_struct eles ->
+ self#latex_of_text fmt [Latex "\\begin{ocamldocsigend}\n"];
+ List.iter (self#latex_of_module_element fmt father) eles;
+ self#latex_of_text fmt [Latex "\\end{ocamldocsigend}\n"]
+ | Module_type_functor (p, k) ->
+ self#latex_of_module_parameter fmt father p;
+ self#latex_of_module_type_kind fmt father k
+ | Module_type_alias a ->
+ self#latex_of_text fmt
+ [Code (self#relative_module_idents father a.mta_name)]
+ | Module_type_with (k, s) ->
+ self#latex_of_module_type_kind fmt father k;
+ self#latex_of_text fmt
+ [ Code " ";
+ Code (self#relative_idents father s);
+ ]
+ | Module_type_typeof s ->
+ self#latex_of_text fmt
+ [ Code "module type of ";
+ Code (self#relative_idents father s);
+ ]
+
+ method latex_of_module_kind fmt father kind =
+ match kind with
+ Module_struct eles ->
+ self#latex_of_text fmt [Latex "\\begin{ocamldocsigend}\n"];
+ List.iter (self#latex_of_module_element fmt father) eles;
+ self#latex_of_text fmt [Latex "\\end{ocamldocsigend}\n"]
+ | Module_alias a ->
+ self#latex_of_text fmt
+ [Code (self#relative_module_idents father a.ma_name)]
+ | Module_functor (p, k) ->
+ self#latex_of_module_parameter fmt father p;
+ self#latex_of_module_kind fmt father k
+ | Module_apply (k1, k2) ->
+ (* TODO: l'application n'est pas correcte dans un .mli.
+ Que faire ? -> afficher le module_type du typedtree *)
+ self#latex_of_module_kind fmt father k1;
+ self#latex_of_text fmt [Code "("];
+ self#latex_of_module_kind fmt father k2;
+ self#latex_of_text fmt [Code ")"]
+ | Module_with (k, s) ->
+ (* TODO: a modifier quand Module_with sera plus detaille *)
+ self#latex_of_module_type_kind fmt father k;
+ self#latex_of_text fmt
+ [ Code " ";
+ Code (self#relative_idents father s) ;
+ ]
+ | Module_constraint (k, tk) ->
+ (* TODO: on affiche quoi ? *)
+ self#latex_of_module_kind fmt father k
+ | Module_typeof s ->
+ self#latex_of_text fmt
+ [ Code "module type of ";
+ Code (self#relative_idents father s);
+ ]
+ | Module_unpack (s, _) ->
+ self#latex_of_text fmt
+ [
+ Code (self#relative_idents father s);
+ ]
+
+ method latex_of_class_kind fmt father kind =
+ match kind with
+ Class_structure (inh, eles) ->
+ self#latex_of_text fmt [Latex "\\begin{ocamldocobjectend}\n"];
+ self#generate_inheritance_info fmt inh;
+ List.iter (self#latex_of_class_element fmt father) eles;
+ self#latex_of_text fmt [Latex "\\end{ocamldocobjectend}\n"]
+
+ | Class_apply capp ->
+ (* TODO: afficher le type final a partir du typedtree *)
+ self#latex_of_text fmt [Raw "class application not handled yet"]
+
+ | Class_constr cco ->
+ (
+ match cco.cco_type_parameters with
+ [] -> ()
+ | l ->
+ self#latex_of_text fmt
+ (
+ Code "[" ::
+ (self#text_of_class_type_param_expr_list father l) @
+ [Code "] "]
+ )
+ );
+ self#latex_of_text fmt
+ [Code (self#relative_idents father cco.cco_name)]
+
+ | Class_constraint (ck, ctk) ->
+ self#latex_of_text fmt [Code "( "] ;
+ self#latex_of_class_kind fmt father ck;
+ self#latex_of_text fmt [Code " : "] ;
+ self#latex_of_class_type_kind fmt father ctk;
+ self#latex_of_text fmt [Code " )"]
+
+ method latex_of_class_type_kind fmt father kind =
+ match kind with
+ Class_type cta ->
+ (
+ match cta.cta_type_parameters with
+ [] -> ()
+ | l ->
+ self#latex_of_text fmt
+ (Code "[" ::
+ (self#text_of_class_type_param_expr_list father l) @
+ [Code "] "]
+ )
+ );
+ self#latex_of_text fmt
+ [Code (self#relative_idents father cta.cta_name)]
+
+ | Class_signature (inh, eles) ->
+ self#latex_of_text fmt [Latex "\\begin{ocamldocobjectend}\n"];
+ self#generate_inheritance_info fmt inh;
+ List.iter (self#latex_of_class_element fmt father) eles;
+ self#latex_of_text fmt [Latex "\\end{ocamldocobjectend}\n"]
+
+ method latex_for_module_index fmt m =
+ let s_name = Name.simple m.m_name in
+ self#latex_of_text fmt
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
+ (self#label ~no_:false s_name)^"`}\n"
+ )
+ ]
+
+ method latex_for_module_type_index fmt mt =
+ let s_name = Name.simple mt.mt_name in
+ self#latex_of_text fmt
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
+ (self#label ~no_:false (Name.simple s_name))^"`}\n"
+ )
+ ]
+
+ method latex_for_module_label fmt m =
+ ps fmt (self#make_label (self#module_label m.m_name))
+
+ method latex_for_module_type_label fmt mt =
+ ps fmt (self#make_label (self#module_type_label mt.mt_name))
+
+
+ method latex_for_class_index fmt c =
+ let s_name = Name.simple c.cl_name in
+ self#latex_of_text fmt
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
+ (self#label ~no_:false s_name)^"`}\n"
+ )
+ ]
+
+ method latex_for_class_type_index fmt ct =
+ let s_name = Name.simple ct.clt_name in
+ self#latex_of_text fmt
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
+ (self#label ~no_:false s_name)^"`}\n"
+ )
+ ]
+
+ method latex_for_class_label fmt c =
+ ps fmt (self#make_label (self#class_label c.cl_name))
+
+ method latex_for_class_type_label fmt ct =
+ ps fmt (self#make_label (self#class_type_label ct.clt_name))
+
+ (** Print the LaTeX code for the given module. *)
+ method latex_of_module fmt m =
+ let father = Name.father m.m_name in
+ let t =
+ [
+ Latex "\\begin{ocamldoccode}\n" ;
+ Code "module ";
+ Code (Name.simple m.m_name);
+ Code " : ";
+ ]
+ in
+ self#latex_of_text fmt t;
+ self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
+ self#latex_for_module_label fmt m;
+ self#latex_for_module_index fmt m;
+ p fmt "@[<h 4>";
+ self#latex_of_module_kind fmt father m.m_kind;
+ (
+ match Module.module_is_functor m with
+ false -> ()
+ | true ->
+ self#latex_of_text fmt [Newline];
+ (
+ match List.filter (fun (_,d) -> d <> None)
+ (module_parameters ~trans: false m)
+ with
+ [] -> ()
+ | l ->
+ let t =
+ [ Bold [Raw "Parameters: "];
+ List
+ (List.map
+ (fun (p,text_opt) ->
+ let t = match text_opt with None -> [] | Some t -> t in
+ ( Raw p.mp_name :: Raw ": " :: t)
+ )
+ l
+ )
+ ]
+ in
+ self#latex_of_text fmt t
+ );
+ );
+ self#latex_of_text fmt [Newline];
+ self#latex_of_info fmt ~block: true m.m_info;
+ p fmt "@]";
+
+
+ (** Print the LaTeX code for the given module type. *)
+ method latex_of_module_type fmt mt =
+ let father = Name.father mt.mt_name in
+ let t =
+ [
+ Latex "\\begin{ocamldoccode}\n" ;
+ Code "module type " ;
+ Code (Name.simple mt.mt_name);
+ ]
+ in
+ self#latex_of_text fmt t;
+ (
+ match mt.mt_type, mt.mt_kind with
+ | Some mtyp, Some kind ->
+ self#latex_of_text fmt [ Code " = " ];
+ self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
+ self#latex_for_module_type_label fmt mt;
+ self#latex_for_module_type_index fmt mt;
+ p fmt "@[<h 4>";
+ self#latex_of_module_type_kind fmt father kind
+ | _ ->
+ self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
+ self#latex_for_module_type_index fmt mt;
+ p fmt "@[<h 4>";
+ );
+ (
+ match Module.module_type_is_functor mt with
+ false -> ()
+ | true ->
+ self#latex_of_text fmt [Newline];
+ (
+ match List.filter (fun (_,d) -> d <> None)
+ (module_type_parameters ~trans: false mt)
+ with
+ [] -> ()
+ | l ->
+ let t =
+ [ Bold [Raw "Parameters: "];
+ List
+ (List.map
+ (fun (p,text_opt) ->
+ let t = match text_opt with None -> [] | Some t -> t in
+ ( Raw p.mp_name :: Raw ": " :: t)
+ )
+ l
+ )
+ ]
+ in
+ self#latex_of_text fmt t
+ );
+ );
+ self#latex_of_text fmt [Newline];
+ self#latex_of_info fmt ~block: true mt.mt_info;
+ p fmt "@]";
+
+ (** Print the LaTeX code for the given included module. *)
+ method latex_of_included_module fmt im =
+ self#latex_of_text fmt
+ ((Code "include ") ::
+ (Code
+ (match im.im_module with
+ None -> im.im_name
+ | Some (Mod m) -> m.m_name
+ | Some (Modtype mt) -> mt.mt_name)
+ ) ::
+ (self#text_of_info im.im_info)
+ )
+
+ (** Print the LaTeX code for the given class. *)
+ method latex_of_class fmt c =
+ Odoc_info.reset_type_names () ;
+ let father = Name.father c.cl_name in
+ let type_params =
+ match c.cl_type_parameters with
+ [] -> ""
+ | l -> (self#normal_class_type_param_list father l)^" "
+ in
+ let t =
+ [
+ Latex "\\begin{ocamldoccode}\n" ;
+ Code (Printf.sprintf
+ "class %s%s%s : "
+ (if c.cl_virtual then "virtual " else "")
+ type_params
+ (Name.simple c.cl_name)
+ )
+ ]
+ in
+ self#latex_of_text fmt t;
+ self#latex_of_class_parameter_list fmt father c;
+ (* avoid a big gap if the kind is a consrt *)
+ (
+ match c.cl_kind with
+ Class.Class_constr _ ->
+ self#latex_of_class_kind fmt father c.cl_kind
+ | _ ->
+ ()
+ );
+ self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
+ self#latex_for_class_label fmt c;
+ self#latex_for_class_index fmt c;
+ p fmt "@[<h 4>";
+ (match c.cl_kind with
+ Class.Class_constr _ -> ()
+ | _ -> self#latex_of_class_kind fmt father c.cl_kind
+ );
+ self#latex_of_text fmt [Newline];
+ self#latex_of_info fmt ~block: true c.cl_info;
+ p fmt "@]"
+
+ (** Print the LaTeX code for the given class type. *)
+ method latex_of_class_type fmt ct =
+ Odoc_info.reset_type_names () ;
+ let father = Name.father ct.clt_name in
+ let type_params =
+ match ct.clt_type_parameters with
+ [] -> ""
+ | l -> (self#normal_class_type_param_list father l)^" "
+ in
+ let t =
+ [
+ Latex "\\begin{ocamldoccode}\n" ;
+ Code (Printf.sprintf
+ "class type %s%s%s = "
+ (if ct.clt_virtual then "virtual " else "")
+ type_params
+ (Name.simple ct.clt_name)
+ )
+ ]
+ in
+ self#latex_of_text fmt t;
+
+ self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
+ self#latex_for_class_type_label fmt ct;
+ self#latex_for_class_type_index fmt ct;
+ p fmt "@[<h 4>";
+ self#latex_of_class_type_kind fmt father ct.clt_kind;
+ self#latex_of_text fmt [Newline];
+ self#latex_of_info fmt ~block: true ct.clt_info;
+ p fmt "@]"
+
+ (** Print the LaTeX code for the given class element. *)
+ method latex_of_class_element fmt class_name class_ele =
+ self#latex_of_text fmt [Newline];
+ match class_ele with
+ Class_attribute att -> self#latex_of_attribute fmt att
+ | Class_method met -> self#latex_of_method fmt met
+ | Class_comment t ->
+ match t with
+ | [] -> ()
+ | (Title (_,_,_)) :: _ -> self#latex_of_text fmt t
+ | _ -> self#latex_of_text fmt [ Title ((Name.depth class_name) + 2, None, t) ]
+
+ (** Print the LaTeX code for the given module element. *)
+ method latex_of_module_element fmt module_name module_ele =
+ self#latex_of_text fmt [Newline];
+ match module_ele with
+ Element_module m -> self#latex_of_module fmt m
+ | Element_module_type mt -> self#latex_of_module_type fmt mt
+ | Element_included_module im -> self#latex_of_included_module fmt im
+ | Element_class c -> self#latex_of_class fmt c
+ | Element_class_type ct -> self#latex_of_class_type fmt ct
+ | Element_value v -> self#latex_of_value fmt v
+ | Element_type_extension te -> self#latex_of_type_extension module_name fmt te
+ | Element_exception e -> self#latex_of_exception fmt e
+ | Element_type t -> self#latex_of_type fmt t
+ | Element_module_comment t -> self#latex_of_text fmt t
+
+ (** Generate the LaTeX code for the given list of inherited classes.*)
+ method generate_inheritance_info fmt inher_l =
+ let f inh =
+ match inh.ic_class with
+ None -> (* we can't make the reference *)
+ Newline ::
+ Code ("inherit "^inh.ic_name) ::
+ (match inh.ic_text with
+ None -> []
+ | Some t -> Newline :: t
+ )
+ | Some cct ->
+ let label =
+ match cct with
+ Cl _ -> self#class_label inh.ic_name
+ | Cltype _ -> self#class_type_label inh.ic_name
+ in
+ (* we can create the reference *)
+ Newline ::
+ Odoc_info.Code ("inherit "^inh.ic_name) ::
+ (Odoc_info.Latex (" ["^(self#make_ref label)^"]")) ::
+ (match inh.ic_text with
+ None -> []
+ | Some t -> Newline :: t
+ )
+ in
+ List.iter (self#latex_of_text fmt) (List.map f inher_l)
+
+ (** Generate the LaTeX code for the inherited classes of the given class. *)
+ method generate_class_inheritance_info fmt cl =
+ let rec iter_kind k =
+ match k with
+ Class_structure ([], _) ->
+ ()
+ | Class_structure (l, _) ->
+ self#generate_inheritance_info fmt l
+ | Class_constraint (k, _) ->
+ iter_kind k
+ | Class_apply _
+ | Class_constr _ ->
+ ()
+ in
+ iter_kind cl.cl_kind
+
+ (** Generate the LaTeX code for the inherited classes of the given class type. *)
+ method generate_class_type_inheritance_info fmt clt =
+ match clt.clt_kind with
+ Class_signature ([], _) ->
+ ()
+ | Class_signature (l, _) ->
+ self#generate_inheritance_info fmt l
+ | Class_type _ ->
+ ()
+
+ (** Generate the LaTeX code for the given top module, in the given buffer. *)
+ method generate_for_top_module fmt m =
+ let (first_t, rest_t) = self#first_and_rest_of_info m.m_info in
+ let text =
+ if m.m_text_only then
+ [ Title (1, None, [Raw m.m_name] @
+ (match first_t with
+ [] -> []
+ | t -> (Raw " : ") :: t)
+ ) ;
+ ]
+ else
+ [ Title (1, None,
+ [ Raw (Odoc_messages.modul^" ") ; Code m.m_name ] @
+ (match first_t with
+ [] -> []
+ | t -> (Raw " : ") :: t)) ;
+ ]
+ in
+ self#latex_of_text fmt text;
+ self#latex_for_module_label fmt m;
+ self#latex_for_module_index fmt m;
+ self#latex_of_text fmt rest_t ;
+
+ self#latex_of_text fmt [ Newline ] ;
+ if not m.m_text_only then ps fmt "\\ocamldocvspace{0.5cm}\n\n";
+ List.iter
+ (fun ele ->
+ self#latex_of_module_element fmt m.m_name ele;
+ ps fmt "\n\n"
+ )
+ (Module.module_elements ~trans: false m)
+
+ (** Print the header of the TeX document. *)
+ method latex_header fmt module_list =
+ ps fmt "\\documentclass[11pt]{article} \n";
+ ps fmt "\\usepackage[latin1]{inputenc} \n";
+ ps fmt "\\usepackage[T1]{fontenc} \n";
+ ps fmt "\\usepackage{textcomp}\n";
+ ps fmt "\\usepackage{fullpage} \n";
+ ps fmt "\\usepackage{url} \n";
+ ps fmt "\\usepackage{ocamldoc}\n";
+ (
+ match !Global.title with
+ None -> ()
+ | Some s ->
+ ps fmt "\\title{";
+ ps fmt (self#escape s);
+ ps fmt "}\n"
+ );
+ ps fmt "\\begin{document}\n";
+ (match !Global.title with
+ None -> () |
+ Some _ -> ps fmt "\\maketitle\n"
+ );
+ if !Global.with_toc then ps fmt "\\tableofcontents\n";
+ (
+ let info = Odoc_info.apply_opt
+ (Odoc_info.info_of_comment_file module_list)
+ !Odoc_info.Global.intro_file
+ in
+ (match info with None -> () | Some _ -> ps fmt "\\vspace{0.2cm}");
+ self#latex_of_info fmt info;
+ (match info with None -> () | Some _ -> ps fmt "\n\n")
+ )
+
+
+ (** Generate the LaTeX style file, if it does not exists. *)
+ method generate_style_file =
+ try
+ let dir = Filename.dirname !Global.out_file in
+ let file = Filename.concat dir "ocamldoc.sty" in
+ if Sys.file_exists file then
+ Odoc_info.verbose (Odoc_messages.file_exists_dont_generate file)
+ else
+ (
+ let chanout = open_out file in
+ output_string chanout Odoc_latex_style.content ;
+ flush chanout ;
+ close_out chanout;
+ Odoc_info.verbose (Odoc_messages.file_generated file)
+ )
+ with
+ Sys_error s ->
+ prerr_endline s ;
+ incr Odoc_info.errors ;
+
+ (** Generate the LaTeX file from a module list, in the {!Odoc_info.Global.out_file} file. *)
+ method generate module_list =
+ self#generate_style_file ;
+ let main_file = !Global.out_file in
+ let dir = Filename.dirname main_file in
+ if !separate_files then
+ (
+ let f m =
+ try
+ let chanout =
+ open_out ((Filename.concat dir (Name.simple m.m_name))^".tex")
+ in
+ let fmt = Format.formatter_of_out_channel chanout in
+ self#generate_for_top_module fmt m ;
+ Format.pp_print_flush fmt ();
+ close_out chanout
+ with
+ Failure s
+ | Sys_error s ->
+ prerr_endline s ;
+ incr Odoc_info.errors
+ in
+ List.iter f module_list
+ );
+
+ try
+ let chanout = open_out main_file in
+ let fmt = Format.formatter_of_out_channel chanout in
+ if !Global.with_header then self#latex_header fmt module_list;
+ List.iter
+ (fun m ->
+ if !separate_files then
+ ps fmt ("\\input{"^((Name.simple m.m_name))^".tex}\n")
+ else
+ self#generate_for_top_module fmt m
+ )
+ module_list ;
+ if !Global.with_trailer then ps fmt "\\end{document}";
+ Format.pp_print_flush fmt ();
+ close_out chanout
+ with
+ Failure s
+ | Sys_error s ->
+ prerr_endline s ;
+ incr Odoc_info.errors
+ end
+end
+
+module type Latex_generator = module type of Generator
diff --git a/ocamldoc/odoc_latex_style.ml b/ocamldoc/odoc_latex_style.ml
new file mode 100644
index 0000000000..713e72e813
--- /dev/null
+++ b/ocamldoc/odoc_latex_style.ml
@@ -0,0 +1,90 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The content of the LaTeX style to generate when generating LaTeX code. *)
+
+let content ="\
+\n%% Support macros for LaTeX documentation generated by ocamldoc.\
+\n%% This file is in the public domain; do what you want with it.\
+\n\
+\n\\NeedsTeXFormat{LaTeX2e}\
+\n\\ProvidesPackage{ocamldoc}\
+\n [2001/12/04 v1.0 ocamldoc support]\
+\n\
+\n\\newenvironment{ocamldoccode}{%\
+\n \\bgroup\
+\n \\leftskip\\@totalleftmargin\
+\n \\rightskip\\z@skip\
+\n \\parindent\\z@\
+\n \\parfillskip\\@flushglue\
+\n \\parskip\\z@skip\
+\n %\\noindent\
+\n \\@@par\\smallskip\
+\n \\@tempswafalse\
+\n \\def\\par{%\
+\n \\if@tempswa\
+\n \\leavevmode\\null\\@@par\\penalty\\interlinepenalty\
+\n \\else\
+\n \\@tempswatrue\
+\n \\ifhmode\\@@par\\penalty\\interlinepenalty\\fi\
+\n \\fi}\
+\n \\obeylines\
+\n \\verbatim@font\
+\n \\let\\org@prime~%\
+\n \\@noligs\
+\n \\let\\org@dospecials\\dospecials\
+\n \\g@remfrom@specials{\\\\}\
+\n \\g@remfrom@specials{\\{}\
+\n \\g@remfrom@specials{\\}}\
+\n \\let\\do\\@makeother\
+\n \\dospecials\
+\n \\let\\dospecials\\org@dospecials\
+\n \\frenchspacing\\@vobeyspaces\
+\n \\everypar \\expandafter{\\the\\everypar \\unpenalty}}\
+\n{\\egroup\\par}\
+\n\
+\n\\def\\g@remfrom@specials#1{%\
+\n \\def\\@new@specials{}\
+\n \\def\\@remove##1{%\
+\n \\ifx##1#1\\else\
+\n \\g@addto@macro\\@new@specials{\\do ##1}\\fi}\
+\n \\let\\do\\@remove\\dospecials\
+\n \\let\\dospecials\\@new@specials\
+\n }\
+\n\
+\n\\newenvironment{ocamldocdescription}\
+\n{\\list{}{\\rightmargin0pt \\topsep0pt}\\raggedright\\item\\noindent\\relax\\ignorespaces}\
+\n{\\endlist\\medskip}\
+\n\
+\n\\newenvironment{ocamldoccomment}\
+\n{\\list{}{\\leftmargin 2\\leftmargini \\rightmargin0pt \\topsep0pt}\\raggedright\\item\\noindent\\relax}\
+\n{\\endlist}\
+\n\
+\n\\let \\ocamldocparagraph \\paragraph\
+\n\\def \\paragraph #1{\\ocamldocparagraph {#1}\\noindent}\
+\n\\let \\ocamldocsubparagraph \\subparagraph\
+\n\\def \\subparagraph #1{\\ocamldocsubparagraph {#1}\\noindent}\
+\n\
+\n\\let\\ocamldocvspace\\vspace\
+\n\
+\n\\newenvironment{ocamldocindent}{\\list{}{}\\item\\relax}{\\endlist}\
+\n\\newenvironment{ocamldocsigend}\
+\n {\\noindent\\quad\\texttt{sig}\\ocamldocindent}\
+\n {\\endocamldocindent\\vskip -\\lastskip\
+\n \\noindent\\quad\\texttt{end}\\medskip}\
+\n\\newenvironment{ocamldocobjectend}\
+\n {\\noindent\\quad\\texttt{object}\\ocamldocindent}\
+\n {\\endocamldocindent\\vskip -\\lastskip\
+\n \\noindent\\quad\\texttt{end}\\medskip}\
+\n\
+\n\\endinput\
+\n"
diff --git a/ocamldoc/odoc_lexer.mll b/ocamldoc/odoc_lexer.mll
new file mode 100644
index 0000000000..998d31bd16
--- /dev/null
+++ b/ocamldoc/odoc_lexer.mll
@@ -0,0 +1,419 @@
+{
+(***********************************************************************)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The lexer for special comments. *)
+
+open Lexing
+open Odoc_parser
+
+let line_number = ref 0
+
+
+let string_buffer = Buffer.create 32
+
+(** Fonction de remise a zero de la chaine de caracteres tampon *)
+let reset_string_buffer () = Buffer.reset string_buffer
+
+(** Fonction d'ajout d'un caractere dans la chaine de caracteres tampon *)
+let ajout_char_string = Buffer.add_char string_buffer
+
+(** Add a string to the buffer. *)
+let ajout_string = Buffer.add_string string_buffer
+
+let lecture_string () = Buffer.contents string_buffer
+
+(** The variable which will contain the description string.
+ Is initialized when we encounter the start of a special comment. *)
+let description = ref ""
+
+let blank = "[ \013\009\012]"
+
+(** The nested comments level. *)
+let comments_level = ref 0
+
+let print_DEBUG2 s = print_string s; print_newline ()
+
+(** This function returns the given string without the leading and trailing blanks.*)
+let remove_blanks s =
+ print_DEBUG2 ("remove_blanks "^s);
+ let l = Str.split_delim (Str.regexp "\n") s in
+ let l2 =
+ let rec iter liste =
+ match liste with
+ h :: q ->
+ let h2 = Str.global_replace (Str.regexp ("^"^blank^"+")) "" h in
+ if h2 = "" then
+ (
+ print_DEBUG2 (h^" n'a que des blancs");
+ (* we remove this line and must remove leading blanks of the next one *)
+ iter q
+ )
+ else
+ (* we don't remove leading blanks in the remaining lines *)
+ h2 :: q
+ | _ ->
+ []
+ in iter l
+ in
+ let l3 =
+ let rec iter liste =
+ match liste with
+ h :: q ->
+ let h2 = Str.global_replace (Str.regexp (blank^"+$")) "" h in
+ if h2 = "" then
+ (
+ print_DEBUG2 (h^" n'a que des blancs");
+ (* we remove this line and must remove trailing blanks of the next one *)
+ iter q
+ )
+ else
+ (* we don't remove trailing blanks in the remaining lines *)
+ h2 :: q
+ | _ ->
+ []
+ in
+ List.rev (iter (List.rev l2))
+ in
+ String.concat "\n" l3
+
+(** Remove first blank characters of each line of a string, until the first '*' *)
+let remove_stars s =
+ let s2 = Str.global_replace (Str.regexp ("^"^blank^"*\\*")) "" s in
+ s2
+}
+
+let lowercase = ['a'-'z' '\223'-'\246' '\248'-'\255' '_']
+let uppercase = ['A'-'Z' '\192'-'\214' '\216'-'\222']
+let identchar =
+ ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9']
+
+rule main = parse
+ [' ' '\013' '\009' '\012'] +
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ main lexbuf
+ }
+
+ | [ '\010' ]
+ {
+ incr line_number;
+ incr Odoc_comments_global.nb_chars;
+ main lexbuf
+ }
+ | "(**)"
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ Description ("", None)
+ }
+
+ | "(**"("*"+)")"
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ main lexbuf
+ }
+
+ | "(***"
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ incr comments_level;
+ main lexbuf
+ }
+
+ | "(**"
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ incr comments_level;
+ if !comments_level = 1 then
+ (
+ reset_string_buffer ();
+ description := "";
+ special_comment lexbuf
+ )
+ else
+ main lexbuf
+ }
+
+ | eof
+ { EOF }
+
+ | "*)"
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ decr comments_level ;
+ main lexbuf
+ }
+
+ | "(*"
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ incr comments_level ;
+ main lexbuf
+ }
+
+ | _
+ {
+ incr Odoc_comments_global.nb_chars;
+ main lexbuf
+ }
+
+and special_comment = parse
+ | "*)"
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ if !comments_level = 1 then
+ (
+ (* there is just a description *)
+ let s2 = lecture_string () in
+ let s3 = remove_blanks s2 in
+ let s4 =
+ if !Odoc_global.remove_stars then
+ remove_stars s3
+ else
+ s3
+ in
+ Description (s4, None)
+ )
+ else
+ (
+ ajout_string s;
+ decr comments_level;
+ special_comment lexbuf
+ )
+ }
+
+ | "(*"
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ incr comments_level ;
+ ajout_string s;
+ special_comment lexbuf
+ }
+
+ | "\\@"
+ {
+ let s = Lexing.lexeme lexbuf in
+ let c = (Lexing.lexeme_char lexbuf 1) in
+ ajout_char_string c;
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ special_comment lexbuf
+ }
+
+ | "@"lowercase+
+ {
+ (* we keep the description before we go further *)
+ let s = lecture_string () in
+ description := remove_blanks s;
+ reset_string_buffer ();
+ let len = String.length (Lexing.lexeme lexbuf) in
+ lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_curr_pos - len;
+ lexbuf.Lexing.lex_curr_p <-
+ { lexbuf.Lexing.lex_curr_p with
+ pos_cnum = lexbuf.Lexing.lex_curr_p.pos_cnum - len
+ } ;
+ (* we don't increment the Odoc_comments_global.nb_chars *)
+ special_comment_part2 lexbuf
+ }
+
+ | _
+ {
+ let c = (Lexing.lexeme_char lexbuf 0) in
+ ajout_char_string c;
+ if c = '\010' then incr line_number;
+ incr Odoc_comments_global.nb_chars;
+ special_comment lexbuf
+ }
+
+and special_comment_part2 = parse
+ | "*)"
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ if !comments_level = 1 then
+ (* finally we return the description we kept *)
+ let desc =
+ if !Odoc_global.remove_stars then
+ remove_stars !description
+ else
+ !description
+ in
+ let remain = lecture_string () in
+ let remain2 =
+ if !Odoc_global.remove_stars then
+ remove_stars remain
+ else
+ remain
+ in
+ Description (desc, Some remain2)
+ else
+ (
+ ajout_string s ;
+ decr comments_level ;
+ special_comment_part2 lexbuf
+ )
+ }
+
+ | "(*"
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ ajout_string s;
+ incr comments_level ;
+ special_comment_part2 lexbuf
+ }
+
+ | _
+ {
+ let c = (Lexing.lexeme_char lexbuf 0) in
+ ajout_char_string c;
+ if c = '\010' then incr line_number;
+ incr Odoc_comments_global.nb_chars;
+ special_comment_part2 lexbuf
+ }
+
+and elements = parse
+ | [' ' '\013' '\009' '\012'] +
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ elements lexbuf
+ }
+
+ | [ '\010' ]
+ { incr line_number;
+ incr Odoc_comments_global.nb_chars;
+ print_DEBUG2 "newline";
+ elements lexbuf }
+ | "@"
+ {
+ raise (Failure (Odoc_messages.should_escape_at_sign))
+ }
+
+ | "@"lowercase+
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ let s2 = String.sub s 1 ((String.length s) - 1) in
+ print_DEBUG2 s2;
+ match s2 with
+ "param" ->
+ T_PARAM
+ | "author" ->
+ T_AUTHOR
+ | "version" ->
+ T_VERSION
+ | "see" ->
+ T_SEE
+ | "since" ->
+ T_SINCE
+ | "before" ->
+ T_BEFORE
+ | "deprecated" ->
+ T_DEPRECATED
+ | "raise" ->
+ T_RAISES
+ | "return" ->
+ T_RETURN
+ | s ->
+ if !Odoc_global.no_custom_tags then
+ raise (Failure (Odoc_messages.not_a_valid_tag s))
+ else
+ T_CUSTOM s
+ }
+
+ | ("\\@" | [^'@'])+
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ let s = Lexing.lexeme lexbuf in
+ let s = Str.global_replace (Str.regexp_string "\\@") "@" s in
+ let s = remove_blanks s in
+ print_DEBUG2 ("Desc "^s);
+ Desc s
+ }
+ | eof
+ {
+ EOF
+ }
+ | _ {
+ let s = Lexing.lexeme lexbuf in
+ failwith ("Unexpected character '"^s^"'")
+ }
+
+
+and simple = parse
+ [' ' '\013' '\009' '\012'] +
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ simple lexbuf
+ }
+
+ | [ '\010' ]
+ { incr line_number;
+ incr Odoc_comments_global.nb_chars;
+ simple lexbuf
+ }
+
+ | "(**"("*"+)
+ {
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length (Lexing.lexeme lexbuf));
+ incr comments_level;
+ simple lexbuf
+ }
+
+ | "(*"("*"+)")"
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ simple lexbuf
+ }
+ | "(**"
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ incr comments_level;
+ simple lexbuf
+ }
+
+ | "(*"
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ incr comments_level;
+ if !comments_level = 1 then
+ (
+ reset_string_buffer ();
+ description := "";
+ special_comment lexbuf
+ )
+ else
+ (
+ ajout_string s;
+ simple lexbuf
+ )
+ }
+
+ | eof
+ { EOF }
+
+ | "*)"
+ {
+ let s = Lexing.lexeme lexbuf in
+ Odoc_comments_global.nb_chars := !Odoc_comments_global.nb_chars + (String.length s);
+ decr comments_level ;
+ simple lexbuf
+ }
+
+ | _
+ {
+ incr Odoc_comments_global.nb_chars;
+ simple lexbuf
+ }
diff --git a/ocamldoc/odoc_man.ml b/ocamldoc/odoc_man.ml
new file mode 100644
index 0000000000..effe6c83b3
--- /dev/null
+++ b/ocamldoc/odoc_man.ml
@@ -0,0 +1,1316 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The man pages generator. *)
+open Odoc_info
+open Parameter
+open Value
+open Type
+open Extension
+open Exception
+open Class
+open Module
+open Search
+
+let man_suffix = ref Odoc_messages.default_man_suffix
+let man_section = ref Odoc_messages.default_man_section
+
+let man_mini = ref false
+
+let new_buf () = Buffer.create 1024
+let bp = Printf.bprintf
+let bs = Buffer.add_string
+
+let linebreak = "\n.sp\n";;
+
+(** A class used to get a [text] for info structures. *)
+class virtual info =
+ object (self)
+ (** The list of pairs [(tag, f)] where [f] is a function taking
+ the [text] associated to [tag] and returning man code.
+ Add a pair here to handle a tag.*)
+ val mutable tag_functions = ([] : (string * (Odoc_info.text -> string)) list)
+
+ (** Return man code for a [text]. *)
+ method virtual man_of_text : Buffer.t -> Odoc_info.text -> unit
+
+ method str_man_of_text t =
+ let b = Buffer.create 256 in
+ self#man_of_text b t ;
+ Buffer.contents b
+
+ (** Print groff string for an author list. *)
+ method str_man_of_author_list l =
+ match l with
+ [] -> ""
+ | _ ->
+ let b = Buffer.create 256 in
+ bs b ".B \"";
+ bs b Odoc_messages.authors;
+ bs b "\"\n:\n";
+ bs b (String.concat ", " l);
+ bs b "\n";
+ (*bs b "\n.sp\n"*)
+ Buffer.contents b
+
+ (** Print groff string for the given optional version information.*)
+ method str_man_of_version_opt v_opt =
+ match v_opt with
+ None -> ""
+ | Some v ->
+ let b = Buffer.create 256 in
+ bs b ".B \"";
+ bs b Odoc_messages.version;
+ bs b "\"\n:\n";
+ bs b v;
+ bs b "\n";
+ (*".sp\n"*)
+ Buffer.contents b
+
+ (** Printf groff string for the \@before information. *)
+ method str_man_of_before = function
+ [] -> ""
+ | l ->
+ let b = Buffer.create 256 in
+ let rec iter = function
+ [] -> ()
+ | (v, text) :: q ->
+ bp b ".B \"%s" Odoc_messages.before;
+ bs b v;
+ bs b "\"\n";
+ self#man_of_text b text;
+ bs b "\n";
+ bs b "\n";
+ match q with
+ [] -> ()
+ | _ -> bs b linebreak ; iter q
+ in
+ iter l;
+ Buffer.contents b
+
+ (** Print groff string for the given optional since information.*)
+ method str_man_of_since_opt s_opt =
+ match s_opt with
+ None -> ""
+ | Some s ->
+ let b = Buffer.create 256 in
+ bs b ".B \"";
+ bs b Odoc_messages.since;
+ bs b "\"\n";
+ bs b s;
+ bs b "\n";(*".sp\n"*)
+ Buffer.contents b
+
+ (** Print groff string for the given list of raised exceptions.*)
+ method str_man_of_raised_exceptions l =
+ match l with
+ [] -> ""
+ | _ ->
+ let b = Buffer.create 256 in
+ let rec iter = function
+ [] -> ()
+ | (s, t) :: q ->
+ bs b ".B \"";
+ bs b Odoc_messages.raises;
+ bs b (" "^s^"\"\n");
+ self#man_of_text b t;
+ bs b "\n";
+ match q with
+ [] -> ()
+ | _ -> bs b linebreak; iter q
+ in
+ iter l;
+ Buffer.contents b
+
+ (** Print groff string for the given "see also" reference. *)
+ method str_man_of_see (see_ref, t) =
+ let t_ref =
+ match see_ref with
+ Odoc_info.See_url s -> [ Odoc_info.Link (s, t) ]
+ | Odoc_info.See_file s -> (Odoc_info.Code s) :: (Odoc_info.Raw " ") :: t
+ | Odoc_info.See_doc s -> (Odoc_info.Italic [Odoc_info.Raw s]) :: (Odoc_info.Raw " ") :: t
+ in
+ self#str_man_of_text t_ref
+
+ (** Print groff string for the given list of "see also" references.*)
+ method str_man_of_sees l =
+ match l with
+ [] -> ""
+ | _ ->
+ let b = Buffer.create 256 in
+ let rec iter = function
+ [] -> ()
+ | see :: q ->
+ bs b ".B \"";
+ bs b Odoc_messages.see_also;
+ bs b "\"\n";
+ bs b (self#str_man_of_see see);
+ bs b "\n";
+ match q with
+ [] -> ()
+ | _ -> bs b linebreak; iter q
+ in
+ iter l;
+ Buffer.contents b
+
+ (** Print groff string for the given optional return information.*)
+ method str_man_of_return_opt return_opt =
+ match return_opt with
+ None -> ""
+ | Some s ->
+ let b = Buffer.create 256 in
+ bs b ".B ";
+ bs b Odoc_messages.returns;
+ bs b "\n";
+ self#man_of_text b s;
+ bs b "\n";
+ Buffer.contents b
+
+ (** Print man code for the given list of custom tagged texts. *)
+ method str_man_of_custom l =
+ List.fold_left
+ (fun acc (tag, text) ->
+ try
+ let f = List.assoc tag tag_functions in
+ let buf = Buffer.create 50 in
+ Buffer.add_string buf (f text);
+ (Buffer.contents buf) :: acc
+ with
+ Not_found ->
+ Odoc_info.warning (Odoc_messages.tag_not_handled tag);
+ acc
+ )
+ [] l
+
+ (** Print the groff string to display an optional info structure. *)
+ method man_of_info ?(margin=0) b info_opt =
+ match info_opt with
+ None -> ()
+ | Some info ->
+ let module M = Odoc_info in
+ let l =
+ (
+ match info.M.i_deprecated with
+ None -> []
+ | Some d ->
+ let b = Buffer.create 256 in
+ bs b ".B \"";
+ bs b Odoc_messages.deprecated;
+ bs b "\"\n";
+ self#man_of_text b d;
+ bs b "\n";
+ [ Buffer.contents b ]
+ ) @
+ (
+ match info.M.i_desc with
+ None -> []
+ | Some d when d = [Odoc_info.Raw ""] -> []
+ | Some d ->
+ [ (self#str_man_of_text d)^"\n" ]
+ ) @
+ [
+ self#str_man_of_author_list info.M.i_authors;
+ self#str_man_of_version_opt info.M.i_version;
+ self#str_man_of_before info.M.i_before;
+ self#str_man_of_since_opt info.M.i_since;
+ self#str_man_of_raised_exceptions info.M.i_raised_exceptions;
+ self#str_man_of_return_opt info.M.i_return_value;
+ self#str_man_of_sees info.M.i_sees;
+ ] @
+ (self#str_man_of_custom info.M.i_custom)
+ in
+ let l = List.filter ((<>) "") l in
+ Buffer.add_string b (String.concat "\n.sp\n" l)
+ end
+
+module Generator =
+struct
+
+(** This class is used to create objects which can generate a simple html documentation. *)
+class man =
+ let re_slash = Str.regexp_string "/" in
+ object (self)
+ inherit info
+
+ (** Get a file name from a complete name. *)
+ method file_name name =
+ let s = Printf.sprintf "%s.%s" name !man_suffix in
+ Str.global_replace re_slash "slash" s
+
+ (** Escape special sequences of characters in a string. *)
+ method escape (s : string) =
+ let len = String.length s in
+ let b = Buffer.create len in
+ for i = 0 to len - 1 do
+ match s.[i] with
+ '\\' -> Buffer.add_string b "\\(rs"
+ | '.' -> Buffer.add_string b "\\&."
+ | '\'' -> Buffer.add_string b "\\&'"
+ | '-' -> Buffer.add_string b "\\-"
+ | c -> Buffer.add_char b c
+ done;
+ Buffer.contents b
+
+ (** Open a file for output. Add the target directory.*)
+ method open_out file =
+ let f = Filename.concat !Global.target_dir file in
+ open_out f
+
+ (** Print groff string for a text, without correction of blanks. *)
+ method private man_of_text2 b t =
+ List.iter (self#man_of_text_element b) t
+
+ (** Print the groff string for a text, with blanks corrected. *)
+ method man_of_text b t =
+ let b2 = new_buf () in
+ self#man_of_text2 b2 t ;
+ let s = Buffer.contents b2 in
+ let s2 = Str.global_replace (Str.regexp "\n[ ]*") "\n" s in
+ bs b (Str.global_replace (Str.regexp "\n\n") "\n" s2)
+
+ (** Return the given string without no newlines. *)
+ method remove_newlines s =
+ Str.global_replace (Str.regexp "[ ]*\n[ ]*") " " s
+
+ (** Print the groff string for a text element. *)
+ method man_of_text_element b txt =
+ match txt with
+ | Odoc_info.Raw s -> bs b (self#escape s)
+ | Odoc_info.Code s ->
+ bs b "\n.B ";
+ bs b ((Str.global_replace (Str.regexp "\n") "\n.B " (self#escape s))^"\n")
+ | Odoc_info.CodePre s ->
+ bs b "\n.B ";
+ bs b ((Str.global_replace (Str.regexp "\n") "\n.B " (self#escape s))^"\n")
+ | Odoc_info.Verbatim s ->
+ bs b (self#escape s)
+ | Odoc_info.Bold t
+ | Odoc_info.Italic t
+ | Odoc_info.Emphasize t
+ | Odoc_info.Center t
+ | Odoc_info.Left t
+ | Odoc_info.Right t ->
+ self#man_of_text2 b t
+ | Odoc_info.List tl ->
+ List.iter
+ (fun t -> bs b "\n.sp\n \\-"; self#man_of_text2 b t; bs b "\n")
+ tl;
+ bs b "\n"
+ | Odoc_info.Enum tl ->
+ List.iter
+ (fun t -> bs b "\n.sp\n \\-"; self#man_of_text2 b t; bs b "\n")
+ tl;
+ bs b "\n"
+ | Odoc_info.Newline ->
+ bs b "\n.sp\n"
+ | Odoc_info.Block t ->
+ bs b "\n.sp\n";
+ self#man_of_text2 b t;
+ bs b "\n.sp\n"
+ | Odoc_info.Title (n, l_opt, t) ->
+ self#man_of_text2 b [Odoc_info.Code (Odoc_info.string_of_text t)]
+ | Odoc_info.Latex _ ->
+ (* don't care about LaTeX stuff in HTML. *)
+ ()
+ | Odoc_info.Link (s, t) ->
+ self#man_of_text2 b t
+ | Odoc_info.Ref (name, _, _) ->
+ self#man_of_text_element b
+ (Odoc_info.Code (Odoc_info.use_hidden_modules name))
+ | Odoc_info.Superscript t ->
+ bs b "^{"; self#man_of_text2 b t
+ | Odoc_info.Subscript t ->
+ bs b "_{"; self#man_of_text2 b t
+ | Odoc_info.Module_list _ ->
+ ()
+ | Odoc_info.Index_list ->
+ ()
+ | Odoc_info.Custom (s,t) -> self#man_of_custom_text b s t
+ | Odoc_info.Target (target, code) -> self#man_of_Target b ~target ~code
+
+ method man_of_custom_text b s t = ()
+
+ method man_of_Target b ~target ~code =
+ if String.lowercase_ascii target = "man" then bs b code else ()
+
+ (** Print groff string to display code. *)
+ method man_of_code b s = self#man_of_text b [ Code s ]
+
+ (** Take a string and return the string where fully qualified idents
+ have been replaced by idents relative to the given module name.*)
+ method relative_idents m_name s =
+ let f str_t =
+ let match_s = Str.matched_string str_t in
+ Odoc_info.apply_if_equal
+ Odoc_info.use_hidden_modules
+ match_s
+ (Name.get_relative m_name match_s)
+ in
+ let s2 = Str.global_substitute
+ (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([a-z][a-zA-Z_'0-9]*\\)")
+ f
+ s
+ in
+ s2
+
+ (** Print groff string to display a [Types.type_expr].*)
+ method man_of_type_expr b m_name t =
+ let s = String.concat "\n"
+ (Str.split (Str.regexp "\n") (Odoc_print.string_of_type_expr t))
+ in
+ let s2 = Str.global_replace (Str.regexp "\n") "\n.B " s in
+ bs b "\n.B ";
+ bs b (self#relative_idents m_name s2);
+ bs b "\n"
+
+ (** Print groff string to display a [Types.class_type].*)
+ method man_of_class_type_expr b m_name t =
+ let s = String.concat "\n"
+ (Str.split (Str.regexp "\n") (Odoc_print.string_of_class_type t))
+ in
+ let s2 = Str.global_replace (Str.regexp "\n") "\n.B " s in
+ bs b "\n.B ";
+ bs b (self#relative_idents m_name s2);
+ bs b "\n"
+
+ (** Print groff string to display a [Types.type_expr list].*)
+ method man_of_cstr_args ?par b m_name sep l =
+ let s =
+ match l with
+ | Cstr_tuple l ->
+ Odoc_str.string_of_type_list ?par sep l
+ | Cstr_record l ->
+ Odoc_str.string_of_record l
+ in
+ let s2 = Str.global_replace (Str.regexp "\n") "\n.B " s in
+ bs b "\n.B ";
+ bs b (self#relative_idents m_name s2);
+ bs b "\n"
+
+ (** Print groff string to display the parameters of a type.*)
+ method man_of_type_expr_param_list b m_name t =
+ match t.ty_parameters with
+ [] -> ()
+ | l ->
+ let s = Odoc_str.string_of_type_param_list t in
+ let s2 = Str.global_replace (Str.regexp "\n") "\n.B " s in
+ bs b "\n.B ";
+ bs b (self#relative_idents m_name s2);
+ bs b "\n"
+
+ (** Print groff string to display a [Types.module_type]. *)
+ method man_of_module_type b m_name t =
+ let s = String.concat "\n"
+ (Str.split (Str.regexp "\n") (Odoc_print.string_of_module_type t))
+ in
+ let s2 = Str.global_replace (Str.regexp "\n") "\n.B " s in
+ bs b "\n.B ";
+ bs b (self#relative_idents m_name s2);
+ bs b "\n"
+
+ (** Print groff string code for a value. *)
+ method man_of_value b v =
+ Odoc_info.reset_type_names () ;
+ bs b "\n.I val ";
+ bs b (Name.simple v.val_name);
+ bs b " \n: ";
+ self#man_of_type_expr b (Name.father v.val_name) v.val_type;
+ bs b ".sp\n";
+ self#man_of_info b v.val_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string code for a type extension. *)
+ method man_of_type_extension b m_name te =
+ Odoc_info.reset_type_names () ;
+ bs b ".I type ";
+ (
+ match te.te_type_parameters with
+ [] -> ()
+ | l ->
+ let s = Odoc_str.string_of_type_extension_param_list te in
+ let s2 = Str.global_replace (Str.regexp "\n") "\n.B " s in
+ bs b "\n.B ";
+ bs b (self#relative_idents m_name s2);
+ bs b "\n";
+ bs b ".I "
+ );
+ bs b (self#relative_idents m_name te.te_type_name);
+ bs b " \n";
+ bs b "+=";
+ if te.te_private = Asttypes.Private then bs b " private";
+ bs b "\n ";
+ List.iter
+ (fun x ->
+ let father = Name.father x.xt_name in
+ bs b ("| "^(Name.simple x.xt_name));
+ (
+ match x.xt_args, x.xt_ret with
+ | Cstr_tuple [], None -> bs b "\n"
+ | l, None ->
+ bs b "\n.B of ";
+ self#man_of_cstr_args ~par: false b father " * " l;
+ | Cstr_tuple [], Some r ->
+ bs b "\n.B : ";
+ self#man_of_type_expr b father r;
+ | l, Some r ->
+ bs b "\n.B : ";
+ self#man_of_cstr_args ~par: false b father " * " l;
+ bs b ".B -> ";
+ self#man_of_type_expr b father r;
+ );
+ (
+ match x.xt_alias with
+ None -> ()
+ | Some xa ->
+ bs b ".B = ";
+ bs b
+ (
+ match xa.xa_xt with
+ None -> xa.xa_name
+ | Some x -> x.xt_name
+ );
+ bs b "\n"
+ );
+ (
+ match x.xt_text with
+ None ->
+ bs b " "
+ | Some t ->
+ bs b ".I \" \"\n";
+ bs b "(* ";
+ self#man_of_info b (Some t);
+ bs b " *)\n "
+ )
+ )
+ te.te_constructors;
+ bs b "\n.sp\n";
+ self#man_of_info b te.te_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string code for an exception. *)
+ method man_of_exception b e =
+ Odoc_info.reset_type_names () ;
+ bs b "\n.I exception ";
+ bs b (Name.simple e.ex_name);
+ bs b " \n";
+ (
+ match e.ex_args, e.ex_ret with
+ | Cstr_tuple [], None -> ()
+ | l, None ->
+ bs b ".B of ";
+ self#man_of_cstr_args
+ ~par: false
+ b (Name.father e.ex_name) " * " e.ex_args
+ | Cstr_tuple [], Some r ->
+ bs b ".B : ";
+ self#man_of_type_expr b (Name.father e.ex_name) r
+ | l, Some r ->
+ bs b ".B : ";
+ self#man_of_cstr_args
+ ~par: false
+ b (Name.father e.ex_name) " * " l;
+ bs b ".B -> ";
+ self#man_of_type_expr b (Name.father e.ex_name) r
+ );
+ (
+ match e.ex_alias with
+ None -> ()
+ | Some ea ->
+ bs b " = ";
+ bs b
+ (
+ match ea.ea_ex with
+ None -> ea.ea_name
+ | Some e -> e.ex_name
+ )
+ );
+ bs b "\n.sp\n";
+ self#man_of_info b e.ex_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string for a type. *)
+ method man_of_type b t =
+ Odoc_info.reset_type_names () ;
+ let father = Name.father t.ty_name in
+ let field_comment = function
+ | None -> ()
+ | Some t ->
+ bs b " (* ";
+ self#man_of_info b (Some t);
+ bs b " *) "
+ in
+ bs b ".I type ";
+ self#man_of_type_expr_param_list b father t;
+ (
+ match t.ty_parameters with
+ [] -> ()
+ | _ -> bs b ".I "
+ );
+ bs b (Name.simple t.ty_name);
+ bs b " \n";
+ let priv = t.ty_private = Asttypes.Private in
+ (
+ match t.ty_manifest with
+ None -> ()
+ | Some (Object_type l) ->
+ bs b "= ";
+ if priv then bs b "private ";
+ bs b "<";
+ List.iter (fun r ->
+ bs b (r.of_name^" : ");
+ self#man_of_type_expr b father r.of_type;
+ bs b ";";
+ field_comment r.of_text ;
+ ) l;
+ bs b "\n >\n"
+ | Some (Other typ) ->
+ bs b "= ";
+ if priv then bs b "private ";
+ self#man_of_type_expr b father typ
+ );
+ (
+ match t.ty_kind with
+ Type_abstract -> ()
+ | Type_variant l ->
+ bs b "=";
+ if priv then bs b " private";
+ bs b "\n ";
+ List.iter (fun constr ->
+ bs b ("| "^constr.vc_name);
+ let print_text t =
+ bs b " (* ";
+ self#man_of_info b (Some t);
+ bs b " *)\n "
+ in
+ match constr.vc_args, constr.vc_text,constr.vc_ret with
+ | Cstr_tuple [], None, None -> bs b "\n "
+ | Cstr_tuple [], (Some t), None ->
+ print_text t
+ | l, None, None ->
+ bs b "\n.B of ";
+ self#man_of_cstr_args ~par: false b father " * " l;
+ bs b " "
+ | l, (Some t), None ->
+ bs b "\n.B of ";
+ self#man_of_cstr_args ~par: false b father " * " l;
+ bs b ".I \" \"\n";
+ print_text t
+ | Cstr_tuple [], None, Some r ->
+ bs b "\n.B : ";
+ self#man_of_type_expr b father r;
+ bs b " "
+ | Cstr_tuple [], (Some t), Some r ->
+ bs b "\n.B : ";
+ self#man_of_type_expr b father r;
+ bs b ".I \" \"\n";
+ print_text t
+ | l, None, Some r ->
+ bs b "\n.B : ";
+ self#man_of_cstr_args ~par: false b father " * " l;
+ bs b ".B -> ";
+ self#man_of_type_expr b father r;
+ bs b " "
+ | l, (Some t), Some r ->
+ bs b "\n.B of ";
+ self#man_of_cstr_args ~par: false b father " * " l;
+ bs b ".B -> ";
+ self#man_of_type_expr b father r;
+ bs b ".I \" \"\n";
+ print_text t
+ ) l
+
+ | Type_record l ->
+ bs b "= ";
+ if priv then bs b "private ";
+ bs b "{";
+ List.iter (fun r ->
+ bs b (if r.rf_mutable then "\n\n.B mutable \n" else "\n ");
+ bs b (r.rf_name^" : ");
+ self#man_of_type_expr b father r.rf_type;
+ bs b ";";
+ field_comment r.rf_text ;
+ ) l;
+ bs b "\n }\n"
+ | Type_open ->
+ bs b "= ..";
+ bs b "\n"
+ );
+ bs b "\n.sp\n";
+ self#man_of_info b t.ty_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string for a class attribute. *)
+ method man_of_attribute b a =
+ bs b ".I val ";
+ if a.att_virtual then bs b ("virtual ");
+ if a.att_mutable then bs b (Odoc_messages.mutab^" ");
+ bs b ((Name.simple a.att_value.val_name)^" : ");
+ self#man_of_type_expr b (Name.father a.att_value.val_name) a.att_value.val_type;
+ bs b "\n.sp\n";
+ self#man_of_info b a.att_value.val_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string for a class method. *)
+ method man_of_method b m =
+ bs b ".I method ";
+ if m.met_private then bs b "private ";
+ if m.met_virtual then bs b "virtual ";
+ bs b ((Name.simple m.met_value.val_name)^" : ");
+ self#man_of_type_expr b
+ (Name.father m.met_value.val_name) m.met_value.val_type;
+ bs b "\n.sp\n";
+ self#man_of_info b m.met_value.val_info;
+ bs b "\n.sp\n"
+
+ (** Groff for a list of parameters. *)
+ method man_of_parameter_list b m_name l =
+ match l with
+ [] -> ()
+ | _ ->
+ bs b "\n.B ";
+ bs b Odoc_messages.parameters;
+ bs b ": \n";
+ List.iter
+ (fun p ->
+ bs b ".sp\n";
+ bs b "\"";
+ bs b (Parameter.complete_name p);
+ bs b "\"\n";
+ self#man_of_type_expr b m_name (Parameter.typ p);
+ bs b "\n";
+ self#man_of_parameter_description b p;
+ bs b "\n"
+ )
+ l;
+ bs b "\n"
+
+ (** Groff for the description of a function parameter. *)
+ method man_of_parameter_description b p =
+ match Parameter.names p with
+ [] -> ()
+ | name :: [] ->
+ (
+ (* Only one name, no need for label for the description. *)
+ match Parameter.desc_by_name p name with
+ None -> ()
+ | Some t -> bs b "\n "; self#man_of_text b t
+ )
+ | l ->
+ (* A list of names, we display those with a description. *)
+ List.iter
+ (fun n ->
+ match Parameter.desc_by_name p n with
+ None -> ()
+ | Some t ->
+ self#man_of_code b (n^" : ");
+ self#man_of_text b t
+ )
+ l
+
+ (** Print groff string for a list of module parameters. *)
+ method man_of_module_parameter_list b m_name l =
+ match l with
+ [] -> ()
+ | _ ->
+ bs b ".B \"";
+ bs b Odoc_messages.parameters;
+ bs b ":\"\n";
+ List.iter
+ (fun (p, desc_opt) ->
+ bs b ".sp\n";
+ bs b ("\""^p.mp_name^"\"\n");
+ Misc.may (self#man_of_module_type b m_name) p.mp_type;
+ bs b "\n";
+ (
+ match desc_opt with
+ None -> ()
+ | Some t -> self#man_of_text b t
+ );
+ bs b "\n"
+ )
+ l;
+ bs b "\n\n"
+
+ (** Print groff string for a class. *)
+ method man_of_class b c =
+ Odoc_info.reset_type_names () ;
+ let father = Name.father c.cl_name in
+ bs b ".I class ";
+ if c.cl_virtual then bs b "virtual ";
+ (
+ match c.cl_type_parameters with
+ [] -> ()
+ | l ->
+ bs b (Odoc_str.string_of_class_type_param_list l);
+ bs b " "
+ );
+ bs b (Name.simple c.cl_name);
+ bs b " : " ;
+ self#man_of_class_type_expr b father c.cl_type;
+ bs b "\n.sp\n";
+ self#man_of_info b c.cl_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string for a class type. *)
+ method man_of_class_type b ct =
+ Odoc_info.reset_type_names () ;
+ bs b ".I class type ";
+ if ct.clt_virtual then bs b "virtual " ;
+ (
+ match ct.clt_type_parameters with
+ [] -> ()
+ | l ->
+ bs b (Odoc_str.string_of_class_type_param_list l);
+ bs b " "
+ );
+ bs b (Name.simple ct.clt_name);
+ bs b " = " ;
+ self#man_of_class_type_expr b (Name.father ct.clt_name) ct.clt_type;
+ bs b "\n.sp\n";
+ self#man_of_info b ct.clt_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string for a module. *)
+ method man_of_module b m =
+ bs b ".I module ";
+ bs b (Name.simple m.m_name);
+ bs b " : ";
+ self#man_of_module_type b (Name.father m.m_name) m.m_type;
+ bs b "\n.sp\n";
+ self#man_of_info b m.m_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string for a module type. *)
+ method man_of_modtype b mt =
+ bs b ".I module type ";
+ bs b (Name.simple mt.mt_name);
+ bs b " = ";
+ (match mt.mt_type with
+ None -> ()
+ | Some t ->
+ self#man_of_module_type b (Name.father mt.mt_name) t
+ );
+ bs b "\n.sp\n";
+ self#man_of_info b mt.mt_info;
+ bs b "\n.sp\n"
+
+ (** Print groff string for a module comment.*)
+ method man_of_module_comment b text =
+ bs b "\n.PP\n";
+ self#man_of_text b [Code ("=== "^(Odoc_misc.string_of_text text)^" ===")];
+ bs b "\n.PP\n"
+
+ (** Print groff string for a class comment.*)
+ method man_of_class_comment b text =
+ bs b "\n.PP\n";
+ self#man_of_text b [Code ("=== "^(Odoc_misc.string_of_text text)^" ===")];
+ bs b "\n.PP\n"
+
+ method man_of_recfield b modname f =
+ bs b ".I ";
+ if f.rf_mutable then bs b (Odoc_messages.mutab^" ");
+ bs b (f.rf_name^" : ");
+ self#man_of_type_expr b modname f.rf_type;
+ bs b "\n.sp\n";
+ self#man_of_info b f.rf_text;
+ bs b "\n.sp\n"
+
+ method man_of_const b modname c =
+ bs b ".I ";
+ bs b (c.vc_name^" ");
+ (match c.vc_args with
+ | Cstr_tuple [] -> ()
+ | Cstr_tuple (h::q) ->
+ bs b "of ";
+ self#man_of_type_expr b modname h;
+ List.iter
+ (fun ty ->
+ bs b " * ";
+ self#man_of_type_expr b modname ty)
+ q
+ | Cstr_record _ -> bs b "{ ... }"
+ );
+ bs b "\n.sp\n";
+ self#man_of_info b c.vc_text;
+ bs b "\n.sp\n"
+
+ (** Print groff string for an included module. *)
+ method man_of_included_module b m_name im =
+ bs b ".I include ";
+ (
+ match im.im_module with
+ None -> bs b im.im_name
+ | Some mmt ->
+ let name =
+ match mmt with
+ Mod m -> m.m_name
+ | Modtype mt -> mt.mt_name
+ in
+ bs b (self#relative_idents m_name name)
+ );
+ bs b "\n.sp\n";
+ self#man_of_info b im.im_info;
+ bs b "\n.sp\n"
+
+ (** Generate the man page for the given class.*)
+ method generate_for_class cl =
+ Odoc_info.reset_type_names () ;
+ let date = Unix.time () in
+ let file = self#file_name cl.cl_name in
+ try
+ let chanout = self#open_out file in
+ let b = new_buf () in
+ bs b (".TH \""^cl.cl_name^"\" ");
+ bs b !man_section ;
+ bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+ bs b "OCamldoc ";
+ bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");
+
+ let abstract =
+ match cl.cl_info with
+ None | Some { i_desc = None } -> "no description"
+ | Some { i_desc = Some t } ->
+ let s = Odoc_info.string_of_text (Odoc_info.first_sentence_of_text t) in
+ self#remove_newlines s
+ in
+
+ bs b ".SH NAME\n";
+ bs b (cl.cl_name^" \\- "^abstract^"\n");
+ bs b (".SH "^Odoc_messages.clas^"\n");
+ bs b (Odoc_messages.clas^" "^cl.cl_name^"\n");
+ bs b (".SH "^Odoc_messages.documentation^"\n");
+ bs b ".sp\n";
+ self#man_of_class b cl;
+
+ (* parameters *)
+ self#man_of_parameter_list b "" cl.cl_parameters;
+ (* a large blank *)
+ bs b "\n.sp\n.sp\n";
+
+(*
+ (* class inheritance *)
+ self#generate_class_inheritance_info chanout cl;
+*)
+ (* the various elements *)
+ List.iter
+ (fun element ->
+ match element with
+ Class_attribute a ->
+ self#man_of_attribute b a
+ | Class_method m ->
+ self#man_of_method b m
+ | Class_comment t ->
+ self#man_of_class_comment b t
+ )
+ (Class.class_elements cl);
+
+ Buffer.output_buffer chanout b;
+ close_out chanout
+ with
+ Sys_error s ->
+ incr Odoc_info.errors ;
+ prerr_endline s
+
+ (** Generate the man page for the given class type.*)
+ method generate_for_class_type ct =
+ Odoc_info.reset_type_names () ;
+ let date = Unix.time () in
+ let file = self#file_name ct.clt_name in
+ try
+ let chanout = self#open_out file in
+ let b = new_buf () in
+ bs b (".TH \""^ct.clt_name^"\" ");
+ bs b !man_section ;
+ bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+ bs b "OCamldoc ";
+ bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");
+
+ let abstract =
+ match ct.clt_info with
+ None | Some { i_desc = None } -> "no description"
+ | Some { i_desc = Some t } ->
+ let s = Odoc_info.string_of_text (Odoc_info.first_sentence_of_text t) in
+ self#remove_newlines s
+ in
+
+ bs b ".SH NAME\n";
+ bs b (ct.clt_name^" \\- "^abstract^"\n");
+ bs b (".SH "^Odoc_messages.class_type^"\n");
+ bs b (Odoc_messages.class_type^" "^ct.clt_name^"\n");
+ bs b (".SH "^Odoc_messages.documentation^"\n");
+ bs b ".sp\n";
+
+ self#man_of_class_type b ct;
+
+ (* a large blank *)
+ bs b "\n.sp\n.sp\n";
+(*
+ (* class inheritance *)
+ self#generate_class_inheritance_info chanout cl;
+*)
+ (* the various elements *)
+ List.iter
+ (fun element ->
+ match element with
+ Class_attribute a ->
+ self#man_of_attribute b a
+ | Class_method m ->
+ self#man_of_method b m
+ | Class_comment t ->
+ self#man_of_class_comment b t
+ )
+ (Class.class_type_elements ct);
+
+ Buffer.output_buffer chanout b;
+ close_out chanout
+ with
+ Sys_error s ->
+ incr Odoc_info.errors ;
+ prerr_endline s
+
+ method man_of_module_type_body b mt =
+ self#man_of_info b mt.mt_info;
+ bs b "\n.sp\n";
+
+ (* parameters for functors *)
+ self#man_of_module_parameter_list b "" (Module.module_type_parameters mt);
+ (* a large blank *)
+ bs b "\n.sp\n.sp\n";
+
+ (* module elements *)
+ List.iter
+ (fun ele ->
+ match ele with
+ Element_module m ->
+ self#man_of_module b m
+ | Element_module_type mt ->
+ self#man_of_modtype b mt
+ | Element_included_module im ->
+ self#man_of_included_module b mt.mt_name im
+ | Element_class c ->
+ self#man_of_class b c
+ | Element_class_type ct ->
+ self#man_of_class_type b ct
+ | Element_value v ->
+ self#man_of_value b v
+ | Element_type_extension te ->
+ self#man_of_type_extension b mt.mt_name te
+ | Element_exception e ->
+ self#man_of_exception b e
+ | Element_type t ->
+ self#man_of_type b t
+ | Element_module_comment text ->
+ self#man_of_module_comment b text
+ )
+ (Module.module_type_elements mt);
+
+ (** Generate the man file for the given module type.
+ @raise Failure if an error occurs.*)
+ method generate_for_module_type mt =
+ let date = Unix.time () in
+ let file = self#file_name mt.mt_name in
+ try
+ let chanout = self#open_out file in
+ let b = new_buf () in
+ bs b (".TH \""^mt.mt_name^"\" ");
+ bs b !man_section ;
+ bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+ bs b "OCamldoc ";
+ bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");
+
+ let abstract =
+ match mt.mt_info with
+ None | Some { i_desc = None } -> "no description"
+ | Some { i_desc = Some t } ->
+ let s = Odoc_info.string_of_text (Odoc_info.first_sentence_of_text t) in
+ self#remove_newlines s
+ in
+ bs b ".SH NAME\n";
+ bs b (mt.mt_name^" \\- "^abstract^"\n");
+ bs b (".SH "^Odoc_messages.module_type^"\n");
+ bs b (Odoc_messages.module_type^" "^mt.mt_name^"\n");
+ bs b (".SH "^Odoc_messages.documentation^"\n");
+ bs b ".sp\n";
+ bs b (Odoc_messages.module_type^"\n");
+ bs b (".BI \""^(Name.simple mt.mt_name)^"\"\n");
+ bs b " = ";
+ (
+ match mt.mt_type with
+ None -> ()
+ | Some t ->
+ self#man_of_module_type b (Name.father mt.mt_name) t
+ );
+ bs b "\n.sp\n";
+ self#man_of_module_type_body b mt;
+
+ Buffer.output_buffer chanout b;
+ close_out chanout
+
+ with
+ Sys_error s ->
+ incr Odoc_info.errors ;
+ prerr_endline s
+
+ method man_of_module_body b m =
+ self#man_of_info b m.m_info;
+ bs b "\n.sp\n";
+
+ (* parameters for functors *)
+ self#man_of_module_parameter_list b "" (Module.module_parameters m);
+ (* a large blank *)
+ bs b "\n.sp\n.sp\n";
+
+ (* module elements *)
+ List.iter
+ (fun ele ->
+ match ele with
+ Element_module m ->
+ self#man_of_module b m
+ | Element_module_type mt ->
+ self#man_of_modtype b mt
+ | Element_included_module im ->
+ self#man_of_included_module b m.m_name im
+ | Element_class c ->
+ self#man_of_class b c
+ | Element_class_type ct ->
+ self#man_of_class_type b ct
+ | Element_value v ->
+ self#man_of_value b v
+ | Element_type_extension te ->
+ self#man_of_type_extension b m.m_name te
+ | Element_exception e ->
+ self#man_of_exception b e
+ | Element_type t ->
+ self#man_of_type b t
+ | Element_module_comment text ->
+ self#man_of_module_comment b text
+ )
+ (Module.module_elements m);
+
+ (** Generate the man file for the given module.
+ @raise Failure if an error occurs.*)
+ method generate_for_module m =
+ let date = Unix.time () in
+ let file = self#file_name m.m_name in
+ try
+ let chanout = self#open_out file in
+ let b = new_buf () in
+ bs b (".TH \""^m.m_name^"\" ");
+ bs b !man_section ;
+ bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+ bs b "OCamldoc ";
+ bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");
+
+ let abstract =
+ match m.m_info with
+ None | Some { i_desc = None } -> "no description"
+ | Some { i_desc = Some t } ->
+ let s = Odoc_info.string_of_text (Odoc_info.first_sentence_of_text t) in
+ self#remove_newlines s
+ in
+
+ bs b ".SH NAME\n";
+ bs b (m.m_name^" \\- "^abstract^"\n");
+ bs b (".SH "^Odoc_messages.modul^"\n");
+ bs b (Odoc_messages.modul^" "^m.m_name^"\n");
+ bs b (".SH "^Odoc_messages.documentation^"\n");
+ bs b ".sp\n";
+ bs b (Odoc_messages.modul^"\n");
+ bs b (".BI \""^(Name.simple m.m_name)^"\"\n");
+ bs b " : ";
+ self#man_of_module_type b (Name.father m.m_name) m.m_type;
+ bs b "\n.sp\n";
+ self#man_of_module_body b m;
+ Buffer.output_buffer chanout b;
+ close_out chanout
+
+ with
+ Sys_error s ->
+ raise (Failure s)
+
+ (** Create the groups of elements to generate pages for. *)
+ method create_groups mini module_list =
+ let name res_ele =
+ match res_ele with
+ Res_module m -> m.m_name
+ | Res_module_type mt -> mt.mt_name
+ | Res_class c -> c.cl_name
+ | Res_class_type ct -> ct.clt_name
+ | Res_value v -> Name.simple v.val_name
+ | Res_type t -> Name.simple t.ty_name
+ | Res_extension x -> Name.simple x.xt_name
+ | Res_exception e -> Name.simple e.ex_name
+ | Res_attribute a -> Name.simple a.att_value.val_name
+ | Res_method m -> Name.simple m.met_value.val_name
+ | Res_section _ -> assert false
+ | Res_recfield (_,f) -> f.rf_name
+ | Res_const (_,f) -> f.vc_name
+ in
+ let all_items_pre = Odoc_info.Search.search_by_name module_list (Str.regexp ".*") in
+ let all_items = List.filter
+ (fun r ->
+ match r with
+ Res_section _ -> false
+ | Res_module _ | Res_module_type _
+ | Res_class _ | Res_class_type _ -> true
+ | _ -> not mini
+ )
+ all_items_pre
+ in
+ let sorted_items = List.sort (fun e1 -> fun e2 -> compare (name e1) (name e2)) all_items in
+ let rec f acc1 acc2 l =
+ match l with
+ [] -> acc2 :: acc1
+ | h :: q ->
+ match acc2 with
+ [] -> f acc1 [h] q
+ | h2 :: q2 ->
+ if (name h) = (name h2) then
+ if List.mem h acc2 then
+ f acc1 acc2 q
+ else
+ f acc1 (acc2 @ [h]) q
+ else
+ f (acc2 :: acc1) [h] q
+ in
+ f [] [] sorted_items
+
+ (** Generate a man page for a group of elements with the same name.
+ A group must not be empty.*)
+ method generate_for_group l =
+ let name =
+ Name.simple
+ (
+ match List.hd l with
+ Res_module m -> m.m_name
+ | Res_module_type mt -> mt.mt_name
+ | Res_class c -> c.cl_name
+ | Res_class_type ct -> ct.clt_name
+ | Res_value v -> v.val_name
+ | Res_type t -> t.ty_name
+ | Res_extension x -> x.xt_name
+ | Res_exception e -> e.ex_name
+ | Res_attribute a -> a.att_value.val_name
+ | Res_method m -> m.met_value.val_name
+ | Res_section (s,_) -> s
+ | Res_recfield (_,f) -> f.rf_name
+ | Res_const (_,f) -> f.vc_name
+ )
+ in
+ let date = Unix.time () in
+ let file = self#file_name name in
+ try
+ let chanout = self#open_out file in
+ let b = new_buf () in
+ bs b (".TH \""^name^"\" ");
+ bs b !man_section ;
+ bs b (" "^(Odoc_misc.string_of_date ~hour: false date)^" ");
+ bs b "OCamldoc ";
+ bs b ("\""^(match !Global.title with Some t -> t | None -> "")^"\"\n");
+ bs b ".SH NAME\n";
+ bs b (name^" \\- all "^name^" elements\n\n");
+
+ let f ele =
+ match ele with
+ Res_value v ->
+ bs b ("\n.SH "^Odoc_messages.modul^" "^(Name.father v.val_name)^"\n");
+ self#man_of_value b v
+ | Res_type t ->
+ bs b ("\n.SH "^Odoc_messages.modul^" "^(Name.father t.ty_name)^"\n");
+ self#man_of_type b t
+ | Res_extension x ->
+ bs b ("\n.SH "^Odoc_messages.modul^" "^(Name.father x.xt_name)^"\n");
+ self#man_of_type_extension b (Name.father x.xt_name) x.xt_type_extension
+ | Res_exception e ->
+ bs b ("\n.SH "^Odoc_messages.modul^" "^(Name.father e.ex_name)^"\n");
+ self#man_of_exception b e
+ | Res_attribute a ->
+ bs b ("\n.SH "^Odoc_messages.clas^" "^(Name.father a.att_value.val_name)^"\n");
+ self#man_of_attribute b a
+ | Res_method m ->
+ bs b ("\n.SH "^Odoc_messages.clas^" "^(Name.father m.met_value.val_name)^"\n");
+ self#man_of_method b m
+ | Res_class c ->
+ bs b ("\n.SH "^Odoc_messages.modul^" "^(Name.father c.cl_name)^"\n");
+ self#man_of_class b c
+ | Res_class_type ct ->
+ bs b ("\n.SH "^Odoc_messages.modul^" "^(Name.father ct.clt_name)^"\n");
+ self#man_of_class_type b ct
+ | Res_recfield (ty,f) ->
+ bs b ("\n.SH Type "^(ty.ty_name)^"\n");
+ self#man_of_recfield b (Name.father ty.ty_name) f
+ | Res_const (ty,c) ->
+ bs b ("\n.SH Type "^(ty.ty_name)^"\n");
+ self#man_of_const b (Name.father ty.ty_name) c
+ | Res_module m ->
+ if Name.father m.m_name <> "" then
+ begin
+ bs b ("\n.SH "^Odoc_messages.modul^" "^(Name.father m.m_name)^"\n");
+ bs b (Odoc_messages.modul^"\n");
+ bs b (".BI \""^(Name.simple m.m_name)^"\"\n");
+ bs b " : ";
+ self#man_of_module_type b (Name.father m.m_name) m.m_type;
+ end
+ else
+ begin
+ bs b ("\n.SH "^Odoc_messages.modul^" "^m.m_name^"\n");
+ bs b " : ";
+ self#man_of_module_type b (Name.father m.m_name) m.m_type;
+ end;
+ bs b "\n.sp\n";
+ self#man_of_module_body b m
+
+ | Res_module_type mt ->
+ bs b ("\n.SH "^Odoc_messages.modul^" "^(Name.father mt.mt_name)^"\n");
+ bs b (Odoc_messages.module_type^"\n");
+ bs b (".BI \""^(Name.simple mt.mt_name)^"\"\n");
+ bs b " = ";
+ (
+ match mt.mt_type with
+ None -> ()
+ | Some t ->
+ self#man_of_module_type b (Name.father mt.mt_name) t
+ );
+ bs b "\n.sp\n";
+ self#man_of_module_type_body b mt
+
+ | Res_section _ ->
+ (* normalement on ne peut pas avoir de module ici. *)
+ ()
+ in
+ List.iter f l;
+ Buffer.output_buffer chanout b;
+ close_out chanout
+ with
+ Sys_error s ->
+ incr Odoc_info.errors ;
+ prerr_endline s
+
+ (** Generate all the man pages from a module list. *)
+ method generate module_list =
+ let sorted_module_list = List.sort (fun m1 m2 -> compare m1.m_name m2.m_name) module_list in
+ let groups = self#create_groups !man_mini sorted_module_list in
+ let f group =
+ match group with
+ [] ->
+ ()
+ | [Res_module m] -> self#generate_for_module m
+ | [Res_module_type mt] -> self#generate_for_module_type mt
+ | [Res_class cl] -> self#generate_for_class cl
+ | [Res_class_type ct] -> self#generate_for_class_type ct
+ | l -> self#generate_for_group l
+ in
+ List.iter f groups
+ end
+end
+
+module type Man_generator = module type of Generator
diff --git a/ocamldoc/odoc_merge.ml b/ocamldoc/odoc_merge.ml
new file mode 100644
index 0000000000..443cc3d8a5
--- /dev/null
+++ b/ocamldoc/odoc_merge.ml
@@ -0,0 +1,1085 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Merge of information from [.ml] and [.mli] for a module.*)
+
+open Odoc_types
+
+module Name = Odoc_name
+open Odoc_parameter
+open Odoc_value
+open Odoc_type
+open Odoc_extension
+open Odoc_exception
+open Odoc_class
+open Odoc_module
+
+let merge_before_tags l =
+ let rec iter acc = function
+ [] -> List.rev acc
+ | (v, text) :: q ->
+ let (l1, l2) = List.partition
+ (fun (v2,_) -> v = v2) q
+ in
+ let acc =
+ let text =
+ List.fold_left
+ (fun acc t -> acc @ [Raw " "] @ t)
+ text (List.map snd l1)
+ in
+ (v, text) :: acc
+ in
+ iter acc l2
+ in
+ iter [] l
+;;
+
+let version_separators = Str.regexp "[\\.\\+]";;
+
+(** Merge two Odoctypes.info struture, completing the information of
+ the first one with the information in the second one.
+ The merge treatment depends on a given merge_option list.
+ @return the new info structure.*)
+let merge_info merge_options (m1 : info) (m2 : info) =
+ let new_desc_opt =
+ match m1.i_desc, m2.i_desc with
+ None, None -> None
+ | None, Some d
+ | Some d, None -> Some d
+ | Some d1, Some d2 ->
+ if List.mem Merge_description merge_options then
+ Some (d1 @ (Newline :: d2))
+ else
+ Some d1
+ in
+ let new_authors =
+ match m1.i_authors, m2.i_authors with
+ [], [] -> []
+ | l, []
+ | [], l -> l
+ | l1, l2 ->
+ if List.mem Merge_author merge_options then
+ l1 @ l2
+ else
+ l1
+ in
+ let new_version =
+ match m1.i_version , m2.i_version with
+ None, None -> None
+ | Some v, None
+ | None, Some v -> Some v
+ | Some v1, Some v2 ->
+ if List.mem Merge_version merge_options then
+ Some (v1^" "^v2)
+ else
+ Some v1
+ in
+ let new_sees =
+ match m1.i_sees, m2.i_sees with
+ [], [] -> []
+ | l, []
+ | [], l -> l
+ | l1, l2 ->
+ if List.mem Merge_see merge_options then
+ l1 @ l2
+ else
+ l1
+ in
+ let new_since =
+ match m1.i_since, m2.i_since with
+ None, None -> None
+ | Some v, None
+ | None, Some v -> Some v
+ | Some v1, Some v2 ->
+ if List.mem Merge_since merge_options then
+ Some (v1^" "^v2)
+ else
+ Some v1
+ in
+ let new_before =
+ match m1.i_before, m2.i_before with
+ [], [] -> []
+ | l, []
+ | [], l -> l
+ | l1, l2 ->
+ if List.mem Merge_before merge_options then
+ merge_before_tags (m1.i_before @ m2.i_before)
+ else
+ l1 in
+ let new_before = List.map (fun (v, t) -> (Str.split version_separators v, v, t)) new_before in
+ let new_before = List.sort Pervasives.compare new_before in
+ let new_before = List.map (fun (_, v, t) -> (v, t)) new_before in
+ let new_dep =
+ match m1.i_deprecated, m2.i_deprecated with
+ None, None -> None
+ | None, Some t
+ | Some t, None -> Some t
+ | Some t1, Some t2 ->
+ if List.mem Merge_deprecated merge_options then
+ Some (t1 @ (Newline :: t2))
+ else
+ Some t1
+ in
+ let new_params =
+ match m1.i_params, m2.i_params with
+ [], [] -> []
+ | l, []
+ | [], l -> l
+ | l1, l2 ->
+ if List.mem Merge_param merge_options then
+ (
+ let l_in_m1_and_m2, l_in_m2_only = List.partition
+ (fun (param2, _) -> List.mem_assoc param2 l1)
+ l2
+ in
+ let rec iter = function
+ [] -> []
+ | (param2, desc2) :: q ->
+ let desc1 = List.assoc param2 l1 in
+ (param2, desc1 @ (Newline :: desc2)) :: (iter q)
+ in
+ let l1_completed = iter l_in_m1_and_m2 in
+ l1_completed @ l_in_m2_only
+ )
+ else
+ l1
+ in
+ let new_raised_exceptions =
+ match m1.i_raised_exceptions, m2.i_raised_exceptions with
+ [], [] -> []
+ | l, []
+ | [], l -> l
+ | l1, l2 ->
+ if List.mem Merge_raised_exception merge_options then
+ (
+ let l_in_m1_and_m2, l_in_m2_only = List.partition
+ (fun (exc2, _) -> List.mem_assoc exc2 l1)
+ l2
+ in
+ let rec iter = function
+ [] -> []
+ | (exc2, desc2) :: q ->
+ let desc1 = List.assoc exc2 l1 in
+ (exc2, desc1 @ (Newline :: desc2)) :: (iter q)
+ in
+ let l1_completed = iter l_in_m1_and_m2 in
+ l1_completed @ l_in_m2_only
+ )
+ else
+ l1
+ in
+ let new_rv =
+ match m1.i_return_value, m2.i_return_value with
+ None, None -> None
+ | None, Some t
+ | Some t, None -> Some t
+ | Some t1, Some t2 ->
+ if List.mem Merge_return_value merge_options then
+ Some (t1 @ (Newline :: t2))
+ else
+ Some t1
+ in
+ let new_custom =
+ match m1.i_custom, m2.i_custom with
+ [], [] -> []
+ | [], l
+ | l, [] -> l
+ | l1, l2 ->
+ if List.mem Merge_custom merge_options then
+ l1 @ l2
+ else
+ l1
+ in
+ {
+ Odoc_types.i_desc = new_desc_opt ;
+ Odoc_types.i_authors = new_authors ;
+ Odoc_types.i_version = new_version ;
+ Odoc_types.i_sees = new_sees ;
+ Odoc_types.i_since = new_since ;
+ Odoc_types.i_before = new_before ;
+ Odoc_types.i_deprecated = new_dep ;
+ Odoc_types.i_params = new_params ;
+ Odoc_types.i_raised_exceptions = new_raised_exceptions ;
+ Odoc_types.i_return_value = new_rv ;
+ Odoc_types.i_custom = new_custom ;
+ }
+
+(** Merge of two optional info structures. *)
+let merge_info_opt merge_options mli_opt ml_opt =
+ match mli_opt, ml_opt with
+ None, Some i -> Some i
+ | Some i, None -> Some i
+ | None, None -> None
+ | Some i1, Some i2 -> Some (merge_info merge_options i1 i2)
+
+(** merge of two t_type, one for a .mli, another for the .ml.
+ The .mli type is completed with the information in the .ml type. *)
+let merge_types merge_options mli ml =
+ mli.ty_info <- merge_info_opt merge_options mli.ty_info ml.ty_info;
+ mli.ty_loc <- { mli.ty_loc with loc_impl = ml.ty_loc.loc_impl } ;
+ mli.ty_code <- (match mli.ty_code with None -> ml.ty_code | _ -> mli.ty_code) ;
+
+ match mli.ty_kind, ml.ty_kind with
+ Type_abstract, _ ->
+ ()
+
+ | Type_variant l1, Type_variant l2 ->
+ let f cons =
+ try
+ let cons2 = List.find
+ (fun c2 -> c2.vc_name = cons.vc_name)
+ l2
+ in
+ let new_desc =
+ match cons.vc_text, cons2.vc_text with
+ None, None -> None
+ | Some d, None
+ | None, Some d -> Some d
+ | Some d1, Some d2 ->
+ if List.mem Merge_description merge_options then
+ Some (merge_info merge_options d1 d2)
+ else
+ Some d1
+ in
+ cons.vc_text <- new_desc
+ with
+ Not_found ->
+ if !Odoc_global.inverse_merge_ml_mli then
+ ()
+ else
+ raise (Failure (Odoc_messages.different_types mli.ty_name))
+ in
+ List.iter f l1
+
+ | Type_record l1, Type_record l2 ->
+ let f record =
+ try
+ let record2= List.find
+ (fun r -> r.rf_name = record.rf_name)
+ l2
+ in
+ let new_desc =
+ match record.rf_text, record2.rf_text with
+ None, None -> None
+ | Some d, None
+ | None, Some d -> Some d
+ | Some d1, Some d2 ->
+ if List.mem Merge_description merge_options then
+ Some (merge_info merge_options d1 d2)
+ else
+ Some d1
+ in
+ record.rf_text <- new_desc
+ with
+ Not_found ->
+ if !Odoc_global.inverse_merge_ml_mli then
+ ()
+ else
+ raise (Failure (Odoc_messages.different_types mli.ty_name))
+ in
+ List.iter f l1
+
+ | Type_open, Type_open ->
+ ()
+
+ | _ ->
+ if !Odoc_global.inverse_merge_ml_mli then
+ ()
+ else
+ raise (Failure (Odoc_messages.different_types mli.ty_name))
+
+(** merge of two t_type_extension, one for a .mli, another for the .ml.
+ The .mli type is completed with the information in the .ml type.
+ Information for the extension constructors is merged separately
+ by [merge_extension_constructor]. *)
+let merge_type_extension merge_options mli ml =
+ mli.te_info <- merge_info_opt merge_options mli.te_info ml.te_info;
+ mli.te_loc <- { mli.te_loc with loc_impl = ml.te_loc.loc_impl } ;
+ mli.te_code <- (match mli.te_code with None -> ml.te_code | _ -> mli.te_code)
+
+(** merge of two t_extension_constructor, one for a .mli, another for the .ml.
+ The .mli type is completed with the information in the .ml type. *)
+let merge_extension_constructor merge_options mli ml =
+ let new_desc =
+ match mli.xt_text, ml.xt_text with
+ None, None -> None
+ | Some d, None
+ | None, Some d -> Some d
+ | Some d1, Some d2 ->
+ if List.mem Merge_description merge_options then
+ Some (merge_info merge_options d1 d2)
+ else
+ Some d1
+ in
+ mli.xt_text <- new_desc
+
+
+(** Merge of two param_info, one from a .mli, one from a .ml.
+ The text fields are not handled but will be recreated from the
+ i_params field of the info structure.
+ Here, if a parameter in the .mli has no name, we take the one
+ from the .ml. When two parameters have two different forms,
+ we take the one from the .mli. *)
+let rec merge_param_info pi_mli pi_ml =
+ match (pi_mli, pi_ml) with
+ (Simple_name sn_mli, Simple_name sn_ml) ->
+ if sn_mli.sn_name = "" then
+ Simple_name { sn_mli with sn_name = sn_ml.sn_name }
+ else
+ pi_mli
+ | (Simple_name _, Tuple _) ->
+ pi_mli
+ | (Tuple (_, t_mli), Simple_name sn_ml) ->
+ (* if we're here, then the tuple in the .mli has no parameter names ;
+ then we take the name of the parameter of the .ml and the type of the .mli. *)
+ Simple_name { sn_ml with sn_type = t_mli }
+
+ | (Tuple (l_mli, t_mli), Tuple (l_ml, _)) ->
+ (* if the two tuples have different lengths
+ (which should not occurs), we return the pi_mli,
+ without further investigation.*)
+ if (List.length l_mli) <> (List.length l_ml) then
+ pi_mli
+ else
+ let new_l = List.map2 merge_param_info l_mli l_ml in
+ Tuple (new_l, t_mli)
+
+(** Merge of the parameters of two functions/methods/classes, one for a .mli, another for a .ml.
+ The prameters in the .mli are completed by the name in the .ml.*)
+let rec merge_parameters param_mli param_ml =
+ match (param_mli, param_ml) with
+ ([], []) -> []
+ | (l, []) | ([], l) -> l
+ | ((pi_mli :: li), (pi_ml :: l)) ->
+ (merge_param_info pi_mli pi_ml) :: merge_parameters li l
+
+(** Merge of two t_class, one for a .mli, another for the .ml.
+ The .mli class is completed with the information in the .ml class. *)
+let merge_classes merge_options mli ml =
+ mli.cl_info <- merge_info_opt merge_options mli.cl_info ml.cl_info;
+ mli.cl_loc <- { mli.cl_loc with loc_impl = ml.cl_loc.loc_impl } ;
+ mli.cl_parameters <- merge_parameters mli.cl_parameters ml.cl_parameters;
+
+ (* we must reassociate comments in @param to the the corresponding
+ parameters because the associated comment of a parameter may have been changed y the merge.*)
+ Odoc_class.class_update_parameters_text mli;
+
+ (* merge values *)
+ List.iter
+ (fun a ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Class_attribute a2 ->
+ if a2.att_value.val_name = a.att_value.val_name then
+ (
+ a.att_value.val_info <- merge_info_opt merge_options
+ a.att_value.val_info a2.att_value.val_info;
+ a.att_value.val_loc <- { a.att_value.val_loc with loc_impl = a2.att_value.val_loc.loc_impl } ;
+ if !Odoc_global.keep_code then
+ a.att_value.val_code <- a2.att_value.val_code;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last attribute with this name defined in the implementation *)
+ (List.rev (Odoc_class.class_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_class.class_attributes mli);
+ (* merge methods *)
+ List.iter
+ (fun m ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Class_method m2 ->
+ if m2.met_value.val_name = m.met_value.val_name then
+ (
+ m.met_value.val_info <- merge_info_opt
+ merge_options m.met_value.val_info m2.met_value.val_info;
+ m.met_value.val_loc <- { m.met_value.val_loc with loc_impl = m2.met_value.val_loc.loc_impl } ;
+ (* merge the parameter names *)
+ m.met_value.val_parameters <- (merge_parameters
+ m.met_value.val_parameters
+ m2.met_value.val_parameters) ;
+ (* we must reassociate comments in @param to the corresponding
+ parameters because the associated comment of a parameter may have been changed by the merge.*)
+ Odoc_value.update_value_parameters_text m.met_value;
+
+ if !Odoc_global.keep_code then
+ m.met_value.val_code <- m2.met_value.val_code;
+
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last method with this name defined in the implementation *)
+ (List.rev (Odoc_class.class_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_class.class_methods mli)
+
+(** merge of two t_class_type, one for a .mli, another for the .ml.
+ The .mli class is completed with the information in the .ml class. *)
+let merge_class_types merge_options mli ml =
+ mli.clt_info <- merge_info_opt merge_options mli.clt_info ml.clt_info;
+ mli.clt_loc <- { mli.clt_loc with loc_impl = ml.clt_loc.loc_impl } ;
+ (* merge values *)
+ List.iter
+ (fun a ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Class_attribute a2 ->
+ if a2.att_value.val_name = a.att_value.val_name then
+ (
+ a.att_value.val_info <- merge_info_opt merge_options
+ a.att_value.val_info a2.att_value.val_info;
+ a.att_value.val_loc <- { a.att_value.val_loc with loc_impl = a2.att_value.val_loc.loc_impl } ;
+ if !Odoc_global.keep_code then
+ a.att_value.val_code <- a2.att_value.val_code;
+
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last attribute with this name defined in the implementation *)
+ (List.rev (Odoc_class.class_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_class.class_type_attributes mli);
+ (* merge methods *)
+ List.iter
+ (fun m ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Class_method m2 ->
+ if m2.met_value.val_name = m.met_value.val_name then
+ (
+ m.met_value.val_info <- merge_info_opt
+ merge_options m.met_value.val_info m2.met_value.val_info;
+ m.met_value.val_loc <- { m.met_value.val_loc with loc_impl = m2.met_value.val_loc.loc_impl } ;
+ m.met_value.val_parameters <- (merge_parameters
+ m.met_value.val_parameters
+ m2.met_value.val_parameters) ;
+ (* we must reassociate comments in @param to the the corresponding
+ parameters because the associated comment of a parameter may have been changed y the merge.*)
+ Odoc_value.update_value_parameters_text m.met_value;
+
+ if !Odoc_global.keep_code then
+ m.met_value.val_code <- m2.met_value.val_code;
+
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last method with this name defined in the implementation *)
+ (List.rev (Odoc_class.class_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_class.class_type_methods mli)
+
+
+(** merge of two t_module_type, one for a .mli, another for the .ml.
+ The .mli module is completed with the information in the .ml module. *)
+let rec merge_module_types merge_options mli ml =
+ mli.mt_info <- merge_info_opt merge_options mli.mt_info ml.mt_info;
+ mli.mt_loc <- { mli.mt_loc with loc_impl = ml.mt_loc.loc_impl } ;
+ (* merge type extensions *)
+ List.iter
+ (fun te ->
+ let rec f exts elems =
+ match exts, elems with
+ [], _
+ | _, [] -> ()
+ | _, (Element_type_extension te2 :: rest) ->
+ let merge_ext xt =
+ try
+ let xt2 =
+ List.find (fun xt2 -> xt.xt_name = xt2.xt_name)
+ te2.te_constructors
+ in
+ merge_extension_constructor merge_options xt xt2;
+ true
+ with Not_found -> false
+ in
+ let merged, unmerged = List.partition merge_ext exts in
+ if merged <> [] then merge_type_extension merge_options te te2;
+ f unmerged rest
+ | _, (_ :: rest) -> f exts rest
+ in
+ (* we look for the extensions in reverse order *)
+ f te.te_constructors (List.rev (Odoc_module.module_type_elements ml))
+ )
+ (Odoc_module.module_type_type_extensions mli);
+ (* merge exceptions *)
+ List.iter
+ (fun ex ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_exception ex2 ->
+ if ex2.ex_name = ex.ex_name then
+ (
+ ex.ex_info <- merge_info_opt merge_options ex.ex_info ex2.ex_info;
+ ex.ex_loc <- { ex.ex_loc with loc_impl = ex2.ex_loc.loc_impl } ;
+ ex.ex_code <- (match ex.ex_code with None -> ex2.ex_code | _ -> ex.ex_code) ;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last exception with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_type_exceptions mli);
+ (* merge types *)
+ List.iter
+ (fun ty ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_type ty2 ->
+ if ty2.ty_name = ty.ty_name then
+ (
+ merge_types merge_options ty ty2;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last type with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_type_types mli);
+ (* merge submodules *)
+ List.iter
+ (fun m ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_module m2 ->
+ if m2.m_name = m.m_name then
+ (
+ ignore (merge_modules merge_options m m2);
+(*
+ m.m_info <- merge_info_opt merge_options m.m_info m2.m_info;
+ m.m_loc <- { m.m_loc with loc_impl = m2.m_loc.loc_impl } ;
+*)
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last module with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_type_modules mli);
+
+ (* merge module types *)
+ List.iter
+ (fun m ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_module_type m2 ->
+ if m2.mt_name = m.mt_name then
+ (
+ merge_module_types merge_options m m2;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last module with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_type_module_types mli);
+
+ (* A VOIR : merge included modules ? *)
+
+ (* merge values *)
+ List.iter
+ (fun v ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_value v2 ->
+ if v2.val_name = v.val_name then
+ (
+ v.val_info <- merge_info_opt merge_options v.val_info v2.val_info ;
+ v.val_loc <- { v.val_loc with loc_impl = v2.val_loc.loc_impl } ;
+ (* in the .mli we don't know any parameters so we add the ones in the .ml *)
+ v.val_parameters <- (merge_parameters
+ v.val_parameters
+ v2.val_parameters) ;
+ (* we must reassociate comments in @param to the the corresponding
+ parameters because the associated comment of a parameter may have been changed y the merge.*)
+ Odoc_value.update_value_parameters_text v;
+
+ if !Odoc_global.keep_code then
+ v.val_code <- v2.val_code;
+
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last value with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_type_values mli);
+
+ (* merge classes *)
+ List.iter
+ (fun c ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_class c2 ->
+ if c2.cl_name = c.cl_name then
+ (
+ merge_classes merge_options c c2;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last value with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_type_classes mli);
+
+ (* merge class types *)
+ List.iter
+ (fun c ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_class_type c2 ->
+ if c2.clt_name = c.clt_name then
+ (
+ merge_class_types merge_options c c2;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last value with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_type_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_type_class_types mli)
+
+(** merge of two t_module, one for a .mli, another for the .ml.
+ The .mli module is completed with the information in the .ml module. *)
+and merge_modules merge_options mli ml =
+ mli.m_info <- merge_info_opt merge_options mli.m_info ml.m_info;
+ mli.m_loc <- { mli.m_loc with loc_impl = ml.m_loc.loc_impl } ;
+ let rec remove_doubles acc = function
+ [] -> acc
+ | h :: q ->
+ if List.mem h acc then remove_doubles acc q
+ else remove_doubles (h :: acc) q
+ in
+ mli.m_top_deps <- remove_doubles mli.m_top_deps ml.m_top_deps ;
+
+ let code =
+ if !Odoc_global.keep_code then
+ match mli.m_code, ml.m_code with
+ Some s, _ -> Some s
+ | _, Some s -> Some s
+ | _ -> None
+ else
+ None
+ in
+ let code_intf =
+ if !Odoc_global.keep_code then
+ match mli.m_code_intf, ml.m_code_intf with
+ Some s, _ -> Some s
+ | _, Some s -> Some s
+ | _ -> None
+ else
+ None
+ in
+ mli.m_code <- code;
+ mli.m_code_intf <- code_intf;
+
+ (* merge type extensions *)
+ List.iter
+ (fun te ->
+ let rec f exts elems =
+ match exts, elems with
+ [], _
+ | _, [] -> ()
+ | _, (Element_type_extension te2 :: rest) ->
+ let merge_ext xt =
+ try
+ let xt2 =
+ List.find (fun xt2 -> xt.xt_name = xt2.xt_name)
+ te2.te_constructors
+ in
+ merge_extension_constructor merge_options xt xt2;
+ true
+ with Not_found -> false
+ in
+ let merged, unmerged = List.partition merge_ext exts in
+ if merged <> [] then merge_type_extension merge_options te te2;
+ f unmerged rest
+ | _, (_ :: rest) -> f exts rest
+ in
+ (* we look for the extensions in reverse order *)
+ f te.te_constructors (List.rev (Odoc_module.module_elements ml))
+ )
+ (Odoc_module.module_type_extensions mli);
+ (* merge exceptions *)
+ List.iter
+ (fun ex ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_exception ex2 ->
+ if ex2.ex_name = ex.ex_name then
+ (
+ ex.ex_info <- merge_info_opt merge_options ex.ex_info ex2.ex_info;
+ ex.ex_loc <- { ex.ex_loc with loc_impl = ex.ex_loc.loc_impl } ;
+ ex.ex_code <- (match ex.ex_code with None -> ex2.ex_code | _ -> ex.ex_code) ;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last exception with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_exceptions mli);
+ (* merge types *)
+ List.iter
+ (fun ty ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_type ty2 ->
+ if ty2.ty_name = ty.ty_name then
+ (
+ merge_types merge_options ty ty2;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last type with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_types mli);
+ (* merge submodules *)
+ List.iter
+ (fun m ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_module m2 ->
+ if m2.m_name = m.m_name then
+ (
+ ignore (merge_modules merge_options m m2);
+(*
+ m.m_info <- merge_info_opt merge_options m.m_info m2.m_info;
+ m.m_loc <- { m.m_loc with loc_impl = m2.m_loc.loc_impl } ;
+*)
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last module with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_modules mli);
+
+ (* merge module types *)
+ List.iter
+ (fun m ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_module_type m2 ->
+ if m2.mt_name = m.mt_name then
+ (
+ merge_module_types merge_options m m2;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last module with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_module_types mli);
+
+ (* A VOIR : merge included modules ? *)
+
+ (* merge values *)
+ List.iter
+ (fun v ->
+ try
+ let _ = List.find
+ (fun v2 ->
+ if v2.val_name = v.val_name then
+ (
+ v.val_info <- merge_info_opt merge_options v.val_info v2.val_info ;
+ v.val_loc <- { v.val_loc with loc_impl = v2.val_loc.loc_impl } ;
+ (* in the .mli we don't know any parameters so we add the ones in the .ml *)
+ v.val_parameters <- (merge_parameters
+ v.val_parameters
+ v2.val_parameters) ;
+ (* we must reassociate comments in @param to the the corresponding
+ parameters because the associated comment of a parameter may have been changed y the merge.*)
+ Odoc_value.update_value_parameters_text v;
+
+ if !Odoc_global.keep_code then
+ v.val_code <- v2.val_code;
+ true
+ )
+ else
+ false
+ )
+ (* we look for the last value with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_values ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_values mli);
+
+ (* merge classes *)
+ List.iter
+ (fun c ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_class c2 ->
+ if c2.cl_name = c.cl_name then
+ (
+ merge_classes merge_options c c2;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last value with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_classes mli);
+
+ (* merge class types *)
+ List.iter
+ (fun c ->
+ try
+ let _ = List.find
+ (fun ele ->
+ match ele with
+ Element_class_type c2 ->
+ if c2.clt_name = c.clt_name then
+ (
+ merge_class_types merge_options c c2;
+ true
+ )
+ else
+ false
+ | _ ->
+ false
+ )
+ (* we look for the last value with this name defined in the implementation *)
+ (List.rev (Odoc_module.module_elements ml))
+ in
+ ()
+ with
+ Not_found ->
+ ()
+ )
+ (Odoc_module.module_class_types mli);
+
+ mli
+
+let merge merge_options modules_list =
+ let rec iter = function
+ [] -> []
+ | m :: q ->
+ (* look for another module with the same name *)
+ let (l_same, l_others) = List.partition
+ (fun m2 -> m.m_name = m2.m_name)
+ q
+ in
+ match l_same with
+ [] ->
+ (* no other module to merge with *)
+ m :: (iter l_others)
+ | m2 :: [] ->
+ (
+ (* we can merge m with m2 if there is an implementation
+ and an interface.*)
+ let f b = if !Odoc_global.inverse_merge_ml_mli then not b else b in
+ match f m.m_is_interface, f m2.m_is_interface with
+ true, false -> (merge_modules merge_options m m2) :: (iter l_others)
+ | false, true -> (merge_modules merge_options m2 m) :: (iter l_others)
+ | false, false ->
+ if !Odoc_global.inverse_merge_ml_mli then
+ (* two Module.ts for the .mli ! *)
+ raise (Failure (Odoc_messages.two_interfaces m.m_name))
+ else
+ (* two Module.t for the .ml ! *)
+ raise (Failure (Odoc_messages.two_implementations m.m_name))
+ | true, true ->
+ if !Odoc_global.inverse_merge_ml_mli then
+ (* two Module.t for the .ml ! *)
+ raise (Failure (Odoc_messages.two_implementations m.m_name))
+ else
+ (* two Module.ts for the .mli ! *)
+ raise (Failure (Odoc_messages.two_interfaces m.m_name))
+ )
+ | _ ->
+ (* too many Module.t ! *)
+ raise (Failure (Odoc_messages.too_many_module_objects m.m_name))
+
+ in
+ iter modules_list
diff --git a/ocamldoc/odoc_merge.mli b/ocamldoc/odoc_merge.mli
new file mode 100644
index 0000000000..2b6b857b88
--- /dev/null
+++ b/ocamldoc/odoc_merge.mli
@@ -0,0 +1,34 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Merge of information from [.ml] and [.mli] for a module.*)
+
+(** Merging \@before tags. *)
+val merge_before_tags :
+ (string * Odoc_types.text) list -> (string * Odoc_types.text) list
+
+(** Merge of two optional info structures.
+ Used to merge a comment before and a comment after
+ an element in [Odoc_sig.Analyser.analyse_signature_item_desc]. *)
+val merge_info_opt :
+ Odoc_types.merge_option list ->
+ Odoc_types.info option ->
+ Odoc_types.info option ->
+ Odoc_types.info option
+
+(** Merge of modules which represent the same OCaml module, in a list of t_module.
+ There must be at most two t_module for the same OCaml module, one for a .mli, another for the .ml.
+ The function returns the list of t_module where same modules have been merged, according
+ to the given merge_option list.*)
+val merge :
+ Odoc_types.merge_option list ->
+ Odoc_module.t_module list -> Odoc_module.t_module list
diff --git a/ocamldoc/odoc_messages.ml b/ocamldoc/odoc_messages.ml
new file mode 100644
index 0000000000..f2a6dbe6b5
--- /dev/null
+++ b/ocamldoc/odoc_messages.ml
@@ -0,0 +1,393 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The messages of the application. *)
+
+let ok = "Ok"
+let software = "OCamldoc"
+let config_version = Config.version
+let magic = config_version^""
+
+(** Messages for command line *)
+
+let usage = "Usage: "^(Sys.argv.(0))^" [options] <files>\n"
+let options_are = "Options are:"
+let latex_only = "(LaTeX only)"
+let texi_only = "(TeXinfo only)"
+let latex_texi_only = "(LaTeX and TeXinfo only)"
+let html_only = "(HTML only)"
+let html_latex_only = "(HTML and LaTeX only)"
+let html_latex_texi_only = "(HTML, LaTeX and TeXinfo only)"
+let man_only = "(man only)"
+let option_impl ="<file> Consider <file> as a .ml file"
+let option_intf ="<file> Consider <file> as a .mli file"
+let option_text ="<file> Consider <file> as a .txt file"
+let display_custom_generators_dir = "Display custom generators standard directory and exit"
+let add_load_dir = "<dir> Add the given directory to the search path for custom\n"^
+ "\t\tgenerators"
+let load_file = "<file.cm[o|a|xs]> Load file defining a new documentation generator"
+let werr = " Treat ocamldoc warnings as errors"
+let hide_warnings = " do not print ocamldoc warnings"
+let target_dir = "<dir> Generate files in directory <dir>, rather than in current\n"^
+ "\t\tdirectory (for man and HTML generators)"
+let dump = "<file> Dump collected information into <file>"
+let load = "<file> Load information from <file> ; may be used several times"
+let css_style = "<file> Use content of <file> as CSS style definition "^html_only
+let index_only = " Generate index files only "^html_only
+let colorize_code = " Colorize code even in documentation pages "^html_only
+let html_short_functors = " Use short form to display functor types "^html_only
+let charset c = Printf.sprintf
+ "<s> Add information about character encoding being s\n\t\t(default is %s)"
+ c
+let generate_html = " Generate HTML documentation"
+let generate_latex = " Generate LaTeX documentation"
+let generate_texinfo = " Generate TeXinfo documentation"
+let generate_man = " Generate man pages"
+let generate_dot = " Generate dot code of top modules dependencies"
+
+let option_not_in_native_code op = "Option "^op^" not available in native code version."
+
+let default_out_file = "ocamldoc.out"
+let out_file =
+ "<file> Set the output file name, used by texi, latex and dot generators\n"^
+ "\t\t(default is "^default_out_file^")\n"^
+ "\t\tor the prefix of index files for the HTML generator\n"^
+ "\t\t(default is index)"
+
+let dot_include_all =
+ " Include all modules in the dot output, not only the\n"^
+ "\t\tmodules given on the command line"
+let dot_types = " Generate dependency graph for types instead of modules"
+let default_dot_colors =
+ [ [ "darkturquoise" ; "darkgoldenrod2" ; "cyan" ; "green" ; ] ;
+ [ "magenta" ; "yellow" ; "burlywood1" ; "aquamarine" ; "floralwhite" ; "lightpink" ] ;
+ [ "lightblue" ; "mediumturquoise" ; "salmon" ; "slategray3"] ;
+ ]
+
+let dot_colors =
+ " <c1,c2,...,cn>\n"^
+ "\t\tUse colors c1,c1,...,cn in the dot output\n"^
+ "\t\t(default list is "^
+ (String.concat ",\n\t\t" (List.map (String.concat ",") default_dot_colors))^")"
+
+let dot_reduce =
+ " Perform a transitive reduction on the selected dependency graph\n"^
+ "\t\tbefore the dot output"
+
+let man_mini = " Generate man pages only for modules, module types, classes\n"^
+ "\t\tand class types "^man_only
+let default_man_section = "3"
+let man_section = "<section> Use <section> in man page files "^
+ "(default is "^default_man_section^") "^man_only^"\n"
+
+let default_man_suffix = default_man_section^"o"
+let man_suffix = "<suffix> Use <suffix> for man page files "^
+ "(default is "^default_man_suffix^") "^man_only^"\n"
+
+let option_title = "<title> Use <title> as title for the generated documentation"
+let option_intro =
+ "<file> Use content of <file> as ocamldoc text to use as introduction\n"^
+ "\t\t"^(html_latex_texi_only)
+let with_parameter_list = " Display the complete list of parameters for functions and\n"^
+ "\t\tmethods "^html_only
+let hide_modules = "<M1,M2.M3,...> Hide the given complete module names in generated doc"
+let no_header = " Suppress header in generated documentation\n\t\t"^latex_texi_only
+let no_trailer = " Suppress trailer in generated documentation\n\t\t"^latex_texi_only
+let separate_files = " Generate one file per toplevel module "^latex_only
+let latex_title ref_titles =
+ "n,style Associate {n } to the given sectionning style\n"^
+ "\t\t(e.g. 'section') in the latex output "^latex_only^"\n"^
+ "\t\tDefault sectionning is:\n\t\t"^
+ (String.concat "\n\t\t"
+ (List.map (fun (n,t) -> Printf.sprintf " %d -> %s" n t) !ref_titles))
+
+let default_latex_value_prefix = "val:"
+let latex_value_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of values.\n"^
+ "\t\t(default is \""^default_latex_value_prefix^"\")"
+
+let default_latex_type_prefix = "type:"
+let latex_type_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of types.\n"^
+ "\t\t(default is \""^default_latex_type_prefix^"\")"
+
+let default_latex_type_elt_prefix = "typeelt:"
+let latex_type_elt_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of type elements.\n"^
+ "\t\t(default is \""^default_latex_type_elt_prefix^"\")"
+
+let default_latex_extension_prefix = "extension:"
+let latex_extension_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of extensions.\n"^
+ "\t\t(default is \""^default_latex_extension_prefix^"\")"
+
+let default_latex_exception_prefix = "exception:"
+let latex_exception_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of exceptions.\n"^
+ "\t\t(default is \""^default_latex_exception_prefix^"\")"
+
+let default_latex_module_prefix = "module:"
+let latex_module_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of modules.\n"^
+ "\t\t(default is \""^default_latex_module_prefix^"\")"
+
+let default_latex_module_type_prefix = "moduletype:"
+let latex_module_type_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of module types.\n"^
+ "\t\t(default is \""^default_latex_module_type_prefix^"\")"
+
+let default_latex_class_prefix = "class:"
+let latex_class_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of classes.\n"^
+ "\t\t(default is \""^default_latex_class_prefix^"\")"
+
+let default_latex_class_type_prefix = "classtype:"
+let latex_class_type_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of class types.\n"^
+ "\t\t(default is \""^default_latex_class_type_prefix^"\")"
+
+let default_latex_attribute_prefix = "val:"
+let latex_attribute_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of attributes.\n"^
+ "\t\t(default is \""^default_latex_attribute_prefix^"\")"
+
+let default_latex_method_prefix = "method:"
+let latex_method_prefix =
+ "<string>\n"^
+ "\t\tUse <string> as prefix for the LaTeX labels of methods.\n"^
+ "\t\t(default is \""^default_latex_method_prefix^"\")"
+
+let no_toc = " Do not generate table of contents "^latex_only
+let sort_modules = " Sort the list of top modules before generating the documentation"
+let no_stop = " Do not stop at (**/**) comments"
+let no_custom_tags = " Do not allow custom @-tags"
+let remove_stars = " Remove beginning blanks of comment lines, until the first '*'"
+let keep_code = " Always keep code when available"
+let inverse_merge_ml_mli = " Inverse implementations and interfaces when merging"
+let no_filter_with_module_constraints = "Do not filter module elements using module type constraints"
+let merge_description = ('d', "merge description")
+let merge_author = ('a', "merge @author")
+let merge_version = ('v', "merge @version")
+let merge_see = ('l', "merge @see")
+let merge_since = ('s', "merge @since")
+let merge_before = ('b', "merge @before")
+let merge_deprecated = ('o', "merge @deprecated")
+let merge_param = ('p', "merge @param")
+let merge_raised_exception = ('e', "merge @raise")
+let merge_return_value = ('r', "merge @return")
+let merge_custom = ('c', "merge custom @-tags")
+let merge_all = ('A', "merge all")
+
+let no_index = " Do not build index for Info files "^texi_only
+let esc_8bits = " Escape accentuated characters in Info files "^texi_only
+let info_section = " Specify section of Info directory "^texi_only
+let info_entry = " Specify Info directory entry "^texi_only
+
+let options_can_be = "<options> can be one or more of the following characters:"
+let string_of_options_list l =
+ List.fold_left (fun acc -> fun (c, m) -> acc^"\n\t\t"^(String.make 1 c)^" "^m)
+ ""
+ l
+
+let merge_options =
+ "<options> specify merge options between .mli and .ml\n\t\t"^
+ options_can_be^
+ (string_of_options_list
+ [ merge_description ;
+ merge_author ;
+ merge_version ;
+ merge_see ;
+ merge_since ;
+ merge_before ;
+ merge_deprecated ;
+ merge_param ;
+ merge_raised_exception ;
+ merge_return_value ;
+ merge_custom ;
+ merge_all ]
+ )
+
+let help = " Display this list of options"
+
+
+(** Error and warning messages *)
+
+let warning = "Warning"
+
+let bad_magic_number =
+ "Bad magic number for this ocamldoc dump!\n"^
+ "This dump was not created by this version of OCamldoc."
+
+let not_a_module_name s = s^" is not a valid module name"
+let load_file_error f e = "Error while loading file "^f^":\n"^e
+let wrong_format s = "Wrong format for \""^s^"\""
+let errors_occured n = (string_of_int n)^" error(s) encountered"
+let parse_error = "Parse error"
+let text_parse_error l c s =
+ let lines = Str.split (Str.regexp_string "\n") s in
+ "Syntax error in text:\n"^s^"\n"^
+ "line "^(string_of_int l)^", character "^(string_of_int c)^":\n"^
+ (List.nth lines l)^"\n"^
+ (String.make c ' ')^"^"
+
+let file_not_found_in_paths paths name =
+ Printf.sprintf "No file %s found in the load paths: \n%s"
+ name
+ (String.concat "\n" paths)
+
+let tag_not_handled tag = "Tag @"^tag^" not handled by this generator"
+let should_escape_at_sign = "The character @ has a special meaning in ocamldoc comments, for commands such as @raise or @since. \
+If you want to write a single @, you must escape it as \\@."
+let bad_tree = "Incorrect tree structure."
+let not_a_valid_tag s = s^" is not a valid tag."
+let fun_without_param f = "Function "^f^" has no parameter.";;
+let method_without_param f = "Method "^f^" has no parameter.";;
+let anonymous_parameters f = "Function "^f^" has anonymous parameters."
+let function_colon f = "Function "^f^": "
+let implicit_match_in_parameter = "Parameters contain implicit pattern matching."
+let unknown_extension f = "Unknown extension for file "^f^"."
+let two_implementations name = "There are two implementations of module "^name^"."
+let two_interfaces name = "There are two interfaces of module "^name^"."
+let too_many_module_objects name = "There are too many interfaces/implementation of module "^name^"."
+let extension_not_found_in_implementation ext m = "Extension "^ext^" was not found in implementation of module "^m^"."
+let exception_not_found_in_implementation exc m = "Exception "^exc^" was not found in implementation of module "^m^"."
+let type_not_found_in_implementation exc m = "Type "^exc^" was not found in implementation of module "^m^"."
+let module_not_found_in_implementation m m2 = "Module "^m^" was not found in implementation of module "^m2^"."
+let value_not_found_in_implementation v m = "Value "^v^" was not found in implementation of module "^m^"."
+let class_not_found_in_implementation c m = "Class "^c^" was not found in implementation of module "^m^"."
+let attribute_not_found_in_implementation a c = "Attribute "^a^" was not found in implementation of class "^c^"."
+let method_not_found_in_implementation m c = "Method "^m^" was not found in implementation of class "^c^"."
+let different_types t = "Definition of type "^t^" doesn't match from interface to implementation."
+let attribute_type_not_found cl att = "The type of the attribute "^att^" could not be found in the signature of class "^cl^"."
+let method_type_not_found cl met = "The type of the method "^met^" could not be found in the signature of class "^cl^"."
+let module_not_found m m2 = "The module "^m2^" could not be found in the signature of module "^m^"."
+let module_type_not_found m mt = "The module type "^mt^" could not be found in the signature of module "^m^"."
+let value_not_found m v = "The value "^v^" could not be found in the signature of module "^m^"."
+let extension_not_found m e = "The extension "^e^" could not be found in the signature of module "^m^"."
+let exception_not_found m e = "The exception "^e^" could not be found in the signature of module "^m^"."
+let type_not_found m t = "The type "^t^" could not be found in the signature of module "^m^"."
+let class_not_found m c = "The class "^c^" could not be found in the signature of module "^m^"."
+let class_type_not_found m c = "The class type "^c^" could not be found in the signature of module "^m^"."
+let type_not_found_in_typedtree t = "Type "^t^" was not found in typed tree."
+let extension_not_found_in_typedtree x = "Extension "^x^" was not found in typed tree."
+let exception_not_found_in_typedtree e = "Exception "^e^" was not found in typed tree."
+let module_type_not_found_in_typedtree mt = "Module type "^mt^" was not found in typed tree."
+let module_not_found_in_typedtree m = "Module "^m^" was not found in typed tree."
+let class_not_found_in_typedtree c = "Class "^c^" was not found in typed tree."
+let class_type_not_found_in_typedtree ct = "Class type "^ct^" was not found in typed tree."
+let inherit_classexp_not_found_in_typedtree n =
+ "Inheritance class expression number "^(string_of_int n)^" was not found in typed tree."
+let attribute_not_found_in_typedtree att = "Class attribute "^att^" was not found in typed tree."
+let method_not_found_in_typedtree met = "Class method "^met^" was not found in typed tree."
+let misplaced_comment file pos =
+ Printf.sprintf "Misplaced special comment in file %s, character %d." file pos
+
+let cross_module_not_found n = "Module "^n^" not found"
+let cross_module_type_not_found n = "Module type "^n^" not found"
+let cross_module_or_module_type_not_found n = "Module or module type "^n^" not found"
+let cross_class_not_found n = "Class "^n^" not found"
+let cross_class_type_not_found n = "class type "^n^" not found"
+let cross_class_or_class_type_not_found n = "Class or class type "^n^" not found"
+let cross_extension_not_found n = "Extension "^n^" not found"
+let cross_exception_not_found n = "Exception "^n^" not found"
+let cross_element_not_found n = "Element "^n^" not found"
+let cross_method_not_found n = "Method "^n^" not found"
+let cross_attribute_not_found n = "Attribute "^n^" not found"
+let cross_section_not_found n = "Section "^n^" not found"
+let cross_value_not_found n = "Value "^n^" not found"
+let cross_type_not_found n = "Type "^n^" not found"
+let cross_recfield_not_found n = Printf.sprintf "Record field %s not found" n
+let cross_const_not_found n = Printf.sprintf "Constructor %s not found" n
+
+let object_end = "object ... end"
+let struct_end = "struct ... end"
+let sig_end = "sig ... end"
+
+let current_generator_is_not kind =
+ Printf.sprintf "Current generator is not a %s generator" kind
+;;
+
+(** Messages for verbose mode. *)
+
+let analysing f = "Analysing file "^f^"..."
+let merging = "Merging..."
+let cross_referencing = "Cross referencing..."
+let generating_doc = "Generating documentation..."
+let loading f = "Loading "^f^"..."
+let file_generated f = "File "^f^" generated."
+let file_exists_dont_generate f =
+ "File "^f^" exists, we don't generate it."
+
+(** Messages for documentation generation.*)
+
+let modul = "Module"
+let modules = "Modules"
+let functors = "Functors"
+let values = "Simple values"
+let types = "Types"
+let extensions = "Extensions"
+let exceptions = "Exceptions"
+let record = "Record"
+let variant = "Variant"
+let mutab = "mutable"
+let functions = "Functions"
+let parameters = "Parameters"
+let abstract = "Abstract"
+let functo = "Functor"
+let clas = "Class"
+let classes = "Classes"
+let attributes = "Attributes"
+let methods = "Methods"
+let authors = "Author(s)"
+let version = "Version"
+let since = "Since"
+let before = "Before"
+let deprecated = "Deprecated."
+let raises = "Raises"
+let returns = "Returns"
+let inherits = "Inherits"
+let inheritance = "Inheritance"
+let privat = "private"
+let module_type = "Module type"
+let class_type = "Class type"
+let description = "Description"
+let interface = "Interface"
+let type_parameters = "Type parameters"
+let class_types = "Class types"
+let module_types = "Module types"
+let see_also = "See also"
+let documentation = "Documentation"
+let index_of = "Index of"
+let top = "Top"
+let index_of_values = index_of^" values"
+let index_of_extensions = index_of^" extensions"
+let index_of_exceptions = index_of^" exceptions"
+let index_of_types = index_of^" types"
+let index_of_attributes = index_of^" class attributes"
+let index_of_methods = index_of^" class methods"
+let index_of_classes = index_of^" classes"
+let index_of_class_types = index_of^" class types"
+let index_of_modules = index_of^" modules"
+let index_of_module_types = index_of^" module types"
+let previous = "Previous"
+let next = "Next"
+let up = "Up"
diff --git a/ocamldoc/odoc_misc.ml b/ocamldoc/odoc_misc.ml
new file mode 100644
index 0000000000..0bc9ade459
--- /dev/null
+++ b/ocamldoc/odoc_misc.ml
@@ -0,0 +1,493 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let no_blanks s =
+ let len = String.length s in
+ let buf = Buffer.create len in
+ for i = 0 to len - 1 do
+ match s.[i] with
+ ' ' | '\n' | '\t' | '\r' -> ()
+ | c -> Buffer.add_char buf c
+ done;
+ Buffer.contents buf
+
+let input_file_as_string nom =
+ let chanin = open_in_bin nom in
+ let len = 1024 in
+ let s = Bytes.create len in
+ let buf = Buffer.create len in
+ let rec iter () =
+ try
+ let n = input chanin s 0 len in
+ if n = 0 then
+ ()
+ else
+ (
+ Buffer.add_subbytes buf s 0 n;
+ iter ()
+ )
+ with
+ End_of_file -> ()
+ in
+ iter ();
+ close_in chanin;
+ Buffer.contents buf
+
+let split_string s chars =
+ let len = String.length s in
+ let rec iter acc pos =
+ if pos >= len then
+ match acc with
+ "" -> []
+ | _ -> [acc]
+ else
+ if List.mem s.[pos] chars then
+ match acc with
+ "" -> iter "" (pos + 1)
+ | _ -> acc :: (iter "" (pos + 1))
+ else
+ iter (Printf.sprintf "%s%c" acc s.[pos]) (pos + 1)
+ in
+ iter "" 0
+
+let split_with_blanks s = split_string s [' ' ; '\n' ; '\r' ; '\t' ]
+
+let list_concat sep =
+ let rec iter = function
+ [] -> []
+ | [h] -> [h]
+ | h :: q -> h :: sep :: q
+ in
+ iter
+
+let rec string_of_longident li =
+ match li with
+ | Longident.Lident s -> s
+ | Longident.Ldot(li, s) -> string_of_longident li ^ "." ^ s
+ | Longident.Lapply(l1, l2) ->
+ string_of_longident l1 ^ "(" ^ string_of_longident l2 ^ ")"
+
+let get_fields type_expr =
+ let (fields, _) = Ctype.flatten_fields (Ctype.object_fields type_expr) in
+ List.fold_left
+ (fun acc -> fun (label, field_kind, typ) ->
+ match field_kind with
+ Types.Fabsent ->
+ acc
+ | _ ->
+ if label = "*dummy method*" then
+ acc
+ else
+ acc @ [label, typ]
+ )
+ []
+ fields
+
+let rec string_of_text t =
+ let rec iter t_ele =
+ match t_ele with
+ | Odoc_types.Raw s
+ | Odoc_types.Code s
+ | Odoc_types.CodePre s
+ | Odoc_types.Verbatim s -> s
+ | Odoc_types.Bold t
+ | Odoc_types.Italic t
+ | Odoc_types.Center t
+ | Odoc_types.Left t
+ | Odoc_types.Right t
+ | Odoc_types.Emphasize t -> string_of_text t
+ | Odoc_types.List l ->
+ (String.concat ""
+ (List.map (fun t -> "\n- "^(string_of_text t)) l))^
+ "\n"
+ | Odoc_types.Enum l ->
+ let rec f n = function
+ [] -> "\n"
+ | t :: q ->
+ "\n"^(string_of_int n)^". "^(string_of_text t)^
+ (f (n + 1) q)
+ in
+ f 1 l
+ | Odoc_types.Newline -> "\n"
+ | Odoc_types.Block t -> "\t"^(string_of_text t)^"\n"
+ | Odoc_types.Title (_, _, t) -> "\n"^(string_of_text t)^"\n"
+ | Odoc_types.Latex s -> "{% "^s^" %}"
+ | Odoc_types.Link (s, t) ->
+ "["^s^"]"^(string_of_text t)
+ | Odoc_types.Ref (name, _, Some text) ->
+ Printf.sprintf "[%s]" (string_of_text text)
+ | Odoc_types.Ref (name, _, None) ->
+ iter (Odoc_types.Code name)
+ | Odoc_types.Superscript t ->
+ "^{"^(string_of_text t)^"}"
+ | Odoc_types.Subscript t ->
+ "^{"^(string_of_text t)^"}"
+ | Odoc_types.Module_list l ->
+ string_of_text
+ (list_concat (Odoc_types.Raw ", ")
+ (List.map (fun s -> Odoc_types.Code s) l)
+ )
+ | Odoc_types.Index_list ->
+ ""
+ | Odoc_types.Custom (_, t) -> string_of_text t
+ | Odoc_types.Target _ -> ""
+ in
+ String.concat "" (List.map iter t)
+
+let string_of_author_list l =
+ match l with
+ [] ->
+ ""
+ | _ ->
+ "* "^Odoc_messages.authors^":\n"^
+ (String.concat ", " l)^
+ "\n"
+
+let string_of_version_opt v_opt =
+ match v_opt with
+ None -> ""
+ | Some v -> Odoc_messages.version^": "^v^"\n"
+
+let string_of_since_opt s_opt =
+ match s_opt with
+ None -> ""
+ | Some s -> Odoc_messages.since^" "^s^"\n"
+
+let string_of_raised_exceptions l =
+ match l with
+ [] -> ""
+ | (s, t) :: [] -> Odoc_messages.raises^" "^s^" "^(string_of_text t)^"\n"
+ | _ ->
+ Odoc_messages.raises^"\n"^
+ (String.concat ""
+ (List.map
+ (fun (ex, desc) -> "- "^ex^" "^(string_of_text desc)^"\n")
+ l
+ )
+ )^"\n"
+
+let string_of_see (see_ref, t) =
+ let t_ref =
+ match see_ref with
+ Odoc_types.See_url s -> [ Odoc_types.Link (s, t) ]
+ | Odoc_types.See_file s -> (Odoc_types.Code s) :: (Odoc_types.Raw " ") :: t
+ | Odoc_types.See_doc s -> (Odoc_types.Italic [Odoc_types.Raw s]) :: (Odoc_types.Raw " ") :: t
+ in
+ string_of_text t_ref
+
+let string_of_sees l =
+ match l with
+ [] -> ""
+ | see :: [] -> Odoc_messages.see_also^" "^(string_of_see see)^" \n"
+ | _ ->
+ Odoc_messages.see_also^"\n"^
+ (String.concat ""
+ (List.map
+ (fun see -> "- "^(string_of_see see)^"\n")
+ l
+ )
+ )^"\n"
+
+let string_of_return_opt return_opt =
+ match return_opt with
+ None -> ""
+ | Some s -> Odoc_messages.returns^" "^(string_of_text s)^"\n"
+
+let string_of_info i =
+ let module M = Odoc_types in
+ (match i.M.i_deprecated with
+ None -> ""
+ | Some d -> Odoc_messages.deprecated^"! "^(string_of_text d)^"\n")^
+ (match i.M.i_desc with
+ None -> ""
+ | Some d when d = [Odoc_types.Raw ""] -> ""
+ | Some d -> (string_of_text d)^"\n"
+ )^
+ (string_of_author_list i.M.i_authors)^
+ (string_of_version_opt i.M.i_version)^
+ (string_of_since_opt i.M.i_since)^
+ (string_of_raised_exceptions i.M.i_raised_exceptions)^
+ (string_of_return_opt i.M.i_return_value)
+
+let apply_opt f v_opt =
+ match v_opt with
+ None -> None
+ | Some v -> Some (f v)
+
+let string_of_date ?(hour=true) d =
+ let add_0 s = if String.length s < 2 then "0"^s else s in
+ let t = Unix.localtime d in
+ (string_of_int (t.Unix.tm_year + 1900))^"-"^
+ (add_0 (string_of_int (t.Unix.tm_mon + 1)))^"-"^
+ (add_0 (string_of_int t.Unix.tm_mday))^
+ (
+ if hour then
+ " "^
+ (add_0 (string_of_int t.Unix.tm_hour))^":"^
+ (add_0 (string_of_int t.Unix.tm_min))
+ else
+ ""
+ )
+
+
+let rec text_list_concat sep l =
+ match l with
+ [] -> []
+ | [t] -> t
+ | t :: q ->
+ t @ (sep :: (text_list_concat sep q))
+
+let rec text_no_title_no_list t =
+ let rec iter t_ele =
+ match t_ele with
+ | Odoc_types.Title (_,_,t) -> text_no_title_no_list t
+ | Odoc_types.List l
+ | Odoc_types.Enum l ->
+ (Odoc_types.Raw " ") ::
+ (text_list_concat
+ (Odoc_types.Raw ", ")
+ (List.map text_no_title_no_list l))
+ | Odoc_types.Raw _
+ | Odoc_types.Code _
+ | Odoc_types.CodePre _
+ | Odoc_types.Verbatim _
+ | Odoc_types.Ref _
+ | Odoc_types.Target _ -> [t_ele]
+ | Odoc_types.Newline -> [Odoc_types.Newline]
+ | Odoc_types.Block t -> [Odoc_types.Block (text_no_title_no_list t)]
+ | Odoc_types.Bold t -> [Odoc_types.Bold (text_no_title_no_list t)]
+ | Odoc_types.Italic t -> [Odoc_types.Italic (text_no_title_no_list t)]
+ | Odoc_types.Center t -> [Odoc_types.Center (text_no_title_no_list t)]
+ | Odoc_types.Left t -> [Odoc_types.Left (text_no_title_no_list t)]
+ | Odoc_types.Right t -> [Odoc_types.Right (text_no_title_no_list t)]
+ | Odoc_types.Emphasize t -> [Odoc_types.Emphasize (text_no_title_no_list t)]
+ | Odoc_types.Latex s -> [Odoc_types.Latex s]
+ | Odoc_types.Link (s, t) -> [Odoc_types.Link (s, (text_no_title_no_list t))]
+ | Odoc_types.Superscript t -> [Odoc_types.Superscript (text_no_title_no_list t)]
+ | Odoc_types.Subscript t -> [Odoc_types.Subscript (text_no_title_no_list t)]
+ | Odoc_types.Module_list l ->
+ list_concat (Odoc_types.Raw ", ")
+ (List.map
+ (fun s -> Odoc_types.Ref (s, Some Odoc_types.RK_module, None))
+ l
+ )
+ | Odoc_types.Index_list -> []
+ | Odoc_types.Custom (s,t) -> [Odoc_types.Custom (s, text_no_title_no_list t)]
+ in
+ List.flatten (List.map iter t)
+
+let get_titles_in_text t =
+ let l = ref [] in
+ let rec iter_ele ele =
+ match ele with
+ | Odoc_types.Title (n,lopt,t) -> l := (n,lopt,t) :: !l
+ | Odoc_types.List l
+ | Odoc_types.Enum l -> List.iter iter_text l
+ | Odoc_types.Raw _
+ | Odoc_types.Code _
+ | Odoc_types.CodePre _
+ | Odoc_types.Verbatim _
+ | Odoc_types.Ref _ -> ()
+ | Odoc_types.Newline -> ()
+ | Odoc_types.Block t
+ | Odoc_types.Bold t
+ | Odoc_types.Italic t
+ | Odoc_types.Center t
+ | Odoc_types.Left t
+ | Odoc_types.Right t
+ | Odoc_types.Emphasize t -> iter_text t
+ | Odoc_types.Latex s -> ()
+ | Odoc_types.Link (_, t)
+ | Odoc_types.Superscript t
+ | Odoc_types.Subscript t -> iter_text t
+ | Odoc_types.Module_list _ -> ()
+ | Odoc_types.Index_list -> ()
+ | Odoc_types.Custom (_, t) -> iter_text t
+ | Odoc_types.Target _ -> ()
+ and iter_text txt =
+ List.iter iter_ele txt
+ in
+ iter_text t;
+ List.rev !l
+
+let text_concat (sep : Odoc_types.text) l =
+ let rec iter = function
+ [] -> []
+ | [last] -> last
+ | h :: q -> h @ sep @ (iter q)
+ in
+ iter l
+
+(*********************************************************)
+let rec get_before_dot s =
+ try
+ let len = String.length s in
+ let n = String.index s '.' in
+ if n + 1 >= len then
+ (* le point est le dernier caractere *)
+ (true, s, "")
+ else
+ match s.[n+1] with
+ ' ' | '\n' | '\r' | '\t' ->
+ (true, String.sub s 0 (n+1),
+ String.sub s (n+1) (len - n - 1))
+ | _ ->
+ let b, s2, s_after = get_before_dot (String.sub s (n + 1) (len - n - 1)) in
+ (b, (String.sub s 0 (n+1))^s2, s_after)
+ with
+ Not_found -> (false, s, "")
+
+let rec first_sentence_text t =
+ match t with
+ [] -> (false, [], [])
+ | ele :: q ->
+ let (stop, ele2, ele3_opt) = first_sentence_text_ele ele in
+ if stop then
+ (stop, [ele2],
+ match ele3_opt with None -> q | Some e -> e :: q)
+ else
+ let (stop2, q2, rest) = first_sentence_text q in
+ (stop2, ele2 :: q2, rest)
+
+
+and first_sentence_text_ele text_ele =
+ match text_ele with
+ | Odoc_types.Raw s ->
+ let b, s2, s_after = get_before_dot s in
+ (b, Odoc_types.Raw s2, Some (Odoc_types.Raw s_after))
+ | Odoc_types.Code _
+ | Odoc_types.CodePre _
+ | Odoc_types.Verbatim _ -> (false, text_ele, None)
+ | Odoc_types.Bold t ->
+ let (b, t2, t3) = first_sentence_text t in
+ (b, Odoc_types.Bold t2, Some (Odoc_types.Bold t3))
+ | Odoc_types.Italic t ->
+ let (b, t2, t3) = first_sentence_text t in
+ (b, Odoc_types.Italic t2, Some (Odoc_types.Italic t3))
+ | Odoc_types.Center t ->
+ let (b, t2, t3) = first_sentence_text t in
+ (b, Odoc_types.Center t2, Some (Odoc_types.Center t3))
+ | Odoc_types.Left t ->
+ let (b, t2, t3) = first_sentence_text t in
+ (b, Odoc_types.Left t2, Some (Odoc_types.Left t3))
+ | Odoc_types.Right t ->
+ let (b, t2, t3) = first_sentence_text t in
+ (b, Odoc_types.Right t2, Some (Odoc_types.Right t3))
+ | Odoc_types.Emphasize t ->
+ let (b, t2, t3) = first_sentence_text t in
+ (b, Odoc_types.Emphasize t2, Some (Odoc_types.Emphasize t3))
+ | Odoc_types.Block t ->
+ let (b, t2, t3) = first_sentence_text t in
+ (b, Odoc_types.Block t2, Some (Odoc_types.Block t3))
+ | Odoc_types.Title (n, l_opt, t) ->
+ let (b, t2, t3) = first_sentence_text t in
+ (b,
+ Odoc_types.Title (n, l_opt, t2),
+ Some (Odoc_types.Title (n, l_opt, t3)))
+ | Odoc_types.Newline ->
+ (true, Odoc_types.Raw "", Some Odoc_types.Newline)
+ | Odoc_types.List _
+ | Odoc_types.Enum _
+ | Odoc_types.Latex _
+ | Odoc_types.Link _
+ | Odoc_types.Ref _
+ | Odoc_types.Superscript _
+ | Odoc_types.Subscript _
+ | Odoc_types.Module_list _
+ | Odoc_types.Index_list -> (false, text_ele, None)
+ | Odoc_types.Custom _
+ | Odoc_types.Target _ -> (false, text_ele, None)
+
+
+let first_sentence_of_text t =
+ let (_,t2,_) = first_sentence_text t in
+ t2
+
+let first_sentence_and_rest_of_text t =
+ let (_,t1, t2) = first_sentence_text t in
+ (t1, t2)
+
+let remove_ending_newline s =
+ let len = String.length s in
+ if len <= 0 then
+ s
+ else
+ match s.[len-1] with
+ '\n' -> String.sub s 0 (len-1)
+ | _ -> s
+
+let search_string_backward ~pat =
+ let lenp = String.length pat in
+ let rec iter s =
+ let len = String.length s in
+ match compare len lenp with
+ -1 -> raise Not_found
+ | 0 -> if pat = s then 0 else raise Not_found
+ | _ ->
+ let pos = len - lenp in
+ let s2 = String.sub s pos lenp in
+ if s2 = pat then
+ pos
+ else
+ iter (String.sub s 0 pos)
+ in
+ fun ~s -> iter s
+
+
+
+(*********************************************************)
+
+let create_index_lists elements string_of_ele =
+ let rec f current acc0 acc1 acc2 = function
+ [] -> (acc0 :: acc1) @ [acc2]
+ | ele :: q ->
+ let s = string_of_ele ele in
+ match s with
+ "" -> f current acc0 acc1 (acc2 @ [ele]) q
+ | _ ->
+ let first = Char.uppercase_ascii s.[0] in
+ match first with
+ 'A' .. 'Z' ->
+ if current = first then
+ f current acc0 acc1 (acc2 @ [ele]) q
+ else
+ f first acc0 (acc1 @ [acc2]) [ele] q
+ | _ ->
+ f current (acc0 @ [ele]) acc1 acc2 q
+ in
+ f '_' [] [] [] elements
+
+
+(*** for labels *)
+
+let is_optional = Btype.is_optional
+let label_name = Btype.label_name
+
+let remove_option typ =
+ let rec iter t =
+ match t with
+ | Types.Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty.Types.desc
+ | Types.Tconstr _
+ | Types.Tvar _
+ | Types.Tunivar _
+ | Types.Tpoly _
+ | Types.Tarrow _
+ | Types.Ttuple _
+ | Types.Tobject _
+ | Types.Tfield _
+ | Types.Tnil
+ | Types.Tvariant _
+ | Types.Tpackage _ -> t
+ | Types.Tlink t2
+ | Types.Tsubst t2 -> iter t2.Types.desc
+ in
+ { typ with Types.desc = iter typ.Types.desc }
diff --git a/ocamldoc/odoc_misc.mli b/ocamldoc/odoc_misc.mli
new file mode 100644
index 0000000000..dd5a7fcb9b
--- /dev/null
+++ b/ocamldoc/odoc_misc.mli
@@ -0,0 +1,114 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Miscellaneous functions *)
+
+(** [no_blanks s] returns the given string without any blank
+ characters, i.e. '\n' '\r' ' ' '\t'.
+*)
+val no_blanks : string -> string
+
+(** This function returns a file in the form of one string.*)
+val input_file_as_string : string -> string
+
+(** [split_with_blanks s] splits the given string [s] according to blanks. *)
+val split_with_blanks : string -> string list
+
+(** This function creates a string from a Longident.t .*)
+val string_of_longident : Longident.t -> string
+
+(** This function returns the list of (label, type_expr) describing
+ the methods of a type_expr in a Tobject.*)
+val get_fields : Types.type_expr -> (string * Types.type_expr) list
+
+(** get a string from a text *)
+val string_of_text : Odoc_types.text -> string
+
+(** @return a string for an authors list. *)
+val string_of_author_list : string list -> string
+
+(** @return a string for the given optional version information.*)
+val string_of_version_opt : string option -> string
+
+(** @return a string for the given optional since information.*)
+val string_of_since_opt : string option -> string
+
+(** @return a string for the given list of raised exceptions.*)
+val string_of_raised_exceptions : (string * Odoc_types.text) list -> string
+
+(** @return a string for the given "see also" reference.*)
+val string_of_see : Odoc_types.see_ref * Odoc_types.text -> string
+
+(** @return a string for the given list of "see also" references.*)
+val string_of_sees : (Odoc_types.see_ref * Odoc_types.text) list -> string
+
+(** @return a string for the given optional return information.*)
+val string_of_return_opt : Odoc_types.text option -> string
+
+(** get a string from a Odoc_info.info structure *)
+val string_of_info : Odoc_types.info -> string
+
+(** Apply a function to an optional value. *)
+val apply_opt : ('a -> 'b) -> 'a option -> 'b option
+
+(** Return a string representing a date given as a number of seconds
+ since 1970. The hour is optionnaly displayed. *)
+val string_of_date : ?hour:bool -> float -> string
+
+(** Return the first sentence (until the first dot) of a text.
+ Don't stop in the middle of [Code], [Verbatim], [List], [Lnum],
+ [Latex], [Link], or [Ref]. *)
+val first_sentence_of_text : Odoc_types.text -> Odoc_types.text
+
+(** Return the first sentence (until the first dot) of a text,
+ and the remaining text after.
+ Don't stop in the middle of [Code], [Verbatim], [List], [Lnum],
+ [Latex], [Link], or [Ref]. *)
+val first_sentence_and_rest_of_text :
+ Odoc_types.text -> Odoc_types.text * Odoc_types.text
+
+(** Return the given [text] without any title or list. *)
+val text_no_title_no_list : Odoc_types.text -> Odoc_types.text
+
+(** [concat sep l] concats the given list of text [l], each separated with
+ the text [sep]. *)
+val text_concat : Odoc_types.text -> Odoc_types.text list -> Odoc_types.text
+
+(** Return the list of titles in a [text].
+ A title is a title level, an optional label and a text.*)
+val get_titles_in_text : Odoc_types.text -> (int * string option * Odoc_types.text) list
+
+(** Take a sorted list of elements, a function to get the name
+ of an element and return the list of list of elements,
+ where each list group elements beginning by the same letter.
+ Since the original list is sorted, elements whose name does not
+ begin with a letter should be in the first returned list.*)
+val create_index_lists : 'a list -> ('a -> string) -> 'a list list
+
+(** [remove_ending_newline s] returns [s] without the optional ending newline. *)
+val remove_ending_newline : string -> string
+
+(** [search_string_backward pat s] searches backward string [pat] in string [s].
+ Return position in string [s] where [pat] appears, orelse raise [Not_found]. *)
+val search_string_backward : pat: string -> s: string -> int
+
+(** Take a type and remove the option top constructor. This is
+ useful when printing labels, we we then remove the top option contructor
+ for optional labels.*)
+val remove_option : Types.type_expr -> Types.type_expr
+
+(** Return [true] if the given label is optional.*)
+val is_optional : Asttypes.arg_label -> bool
+
+(** Return the label name for the given label,
+ i.e. removes the beginning '?' if present.*)
+val label_name : Asttypes.arg_label -> string
diff --git a/ocamldoc/odoc_module.ml b/ocamldoc/odoc_module.ml
new file mode 100644
index 0000000000..9ed2b17717
--- /dev/null
+++ b/ocamldoc/odoc_module.ml
@@ -0,0 +1,554 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation and manipulation of modules and module types. *)
+
+let print_DEBUG s = print_string s ; print_newline ()
+
+module Name = Odoc_name
+
+(** To keep the order of elements in a module. *)
+type module_element =
+ Element_module of t_module
+ | Element_module_type of t_module_type
+ | Element_included_module of included_module
+ | Element_class of Odoc_class.t_class
+ | Element_class_type of Odoc_class.t_class_type
+ | Element_value of Odoc_value.t_value
+ | Element_type_extension of Odoc_extension.t_type_extension
+ | Element_exception of Odoc_exception.t_exception
+ | Element_type of Odoc_type.t_type
+ | Element_module_comment of Odoc_types.text
+
+(** Used where we can reference t_module or t_module_type *)
+and mmt =
+ | Mod of t_module
+ | Modtype of t_module_type
+
+and included_module = {
+ im_name : Name.t ; (** the name of the included module *)
+ mutable im_module : mmt option ; (** the included module or module type *)
+ mutable im_info : Odoc_types.info option ; (** comment associated to the includ directive *)
+ }
+
+and module_alias = {
+ ma_name : Name.t ;
+ mutable ma_module : mmt option ; (** the real module or module type if we could associate it *)
+ }
+
+and module_parameter = {
+ mp_name : string ; (** the name *)
+ mp_type : Types.module_type option ; (** the type *)
+ mp_type_code : string ; (** the original code *)
+ mp_kind : module_type_kind ; (** the way the parameter was built *)
+ }
+
+(** Different kinds of module. *)
+and module_kind =
+ | Module_struct of module_element list
+ | Module_alias of module_alias (** complete name and corresponding module if we found it *)
+ | Module_functor of module_parameter * module_kind
+ | Module_apply of module_kind * module_kind
+ | Module_with of module_type_kind * string
+ | Module_constraint of module_kind * module_type_kind
+ | Module_typeof of string (** by now only the code of the module expression *)
+ | Module_unpack of string * module_type_alias (** code of the expression and module type alias *)
+
+(** Representation of a module. *)
+and t_module = {
+ m_name : Name.t ;
+ mutable m_type : Types.module_type ;
+ mutable m_info : Odoc_types.info option ;
+ m_is_interface : bool ; (** true for modules read from interface files *)
+ m_file : string ; (** the file the module is defined in. *)
+ mutable m_kind : module_kind ;
+ mutable m_loc : Odoc_types.location ;
+ mutable m_top_deps : Name.t list ; (** The toplevels module names this module depends on. *)
+ mutable m_code : string option ; (** The whole code of the module *)
+ mutable m_code_intf : string option ; (** The whole code of the interface of the module *)
+ m_text_only : bool ; (** [true] if the module comes from a text file *)
+ }
+
+and module_type_alias = {
+ mta_name : Name.t ;
+ mutable mta_module : t_module_type option ; (** the real module type if we could associate it *)
+ }
+
+(** Different kinds of module type. *)
+and module_type_kind =
+ | Module_type_struct of module_element list
+ | Module_type_functor of module_parameter * module_type_kind
+ | Module_type_alias of module_type_alias (** complete name and corresponding module type if we found it *)
+ | Module_type_with of module_type_kind * string (** the module type kind and the code of the with constraint *)
+ | Module_type_typeof of string (** by now only the code of the module expression *)
+
+(** Representation of a module type. *)
+and t_module_type = {
+ mt_name : Name.t ;
+ mutable mt_info : Odoc_types.info option ;
+ mutable mt_type : Types.module_type option ; (** [None] = abstract module type *)
+ mt_is_interface : bool ; (** true for modules read from interface files *)
+ mt_file : string ; (** the file the module type is defined in. *)
+ mutable mt_kind : module_type_kind option ; (** [None] = abstract module type if mt_type = None ;
+ Always [None] when the module type was extracted from the implementation file. *)
+ mutable mt_loc : Odoc_types.location ;
+ }
+
+
+(** {2 Functions} *)
+
+(** Returns the list of values from a list of module_element. *)
+let values l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_value v -> acc @ [v]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of types from a list of module_element. *)
+let types l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_type t -> acc @ [t]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of type extensions from a list of module_element. *)
+let type_extensions l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_type_extension x -> acc @ [x]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of exceptions from a list of module_element. *)
+let exceptions l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_exception e -> acc @ [e]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of classes from a list of module_element. *)
+let classes l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_class c -> acc @ [c]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of class types from a list of module_element. *)
+let class_types l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_class_type ct -> acc @ [ct]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of modules from a list of module_element. *)
+let modules l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_module m -> acc @ [m]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of module types from a list of module_element. *)
+let mod_types l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_module_type mt -> acc @ [mt]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of module comment from a list of module_element. *)
+let comments l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_module_comment t -> acc @ [t]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of included modules from a list of module_element. *)
+let included_modules l =
+ List.fold_left
+ (fun acc -> fun ele ->
+ match ele with
+ Element_included_module m -> acc @ [m]
+ | _ -> acc
+ )
+ []
+ l
+
+(** Returns the list of elements of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let rec module_elements ?(trans=true) m =
+ let rec iter_kind = function
+ Module_struct l ->
+ print_DEBUG "Odoc_module.module_element: Module_struct";
+ l
+ | Module_alias ma ->
+ print_DEBUG "Odoc_module.module_element: Module_alias";
+ if trans then
+ match ma.ma_module with
+ None -> []
+ | Some (Mod m) -> module_elements m
+ | Some (Modtype mt) -> module_type_elements mt
+ else
+ []
+ | Module_functor (_, k)
+ | Module_apply (k, _) ->
+ print_DEBUG "Odoc_module.module_element: Module_functor ou Module_apply";
+ iter_kind k
+ | Module_with (tk,_) ->
+ print_DEBUG "Odoc_module.module_element: Module_with";
+ module_type_elements ~trans: trans
+ { mt_name = "" ; mt_info = None ; mt_type = None ;
+ mt_is_interface = false ; mt_file = "" ; mt_kind = Some tk ;
+ mt_loc = Odoc_types.dummy_loc ;
+ }
+ | Module_constraint (k, tk) ->
+ print_DEBUG "Odoc_module.module_element: Module_constraint";
+ (* A VOIR : utiliser k ou tk ? *)
+ module_elements ~trans: trans
+ { m_name = "" ;
+ m_info = None ;
+ m_type = Types.Mty_signature [] ;
+ m_is_interface = false ; m_file = "" ; m_kind = k ;
+ m_loc = Odoc_types.dummy_loc ;
+ m_top_deps = [] ;
+ m_code = None ;
+ m_code_intf = None ;
+ m_text_only = false ;
+ }
+ | Module_typeof _ -> []
+ | Module_unpack _ -> []
+(*
+ module_type_elements ~trans: trans
+ { mt_name = "" ; mt_info = None ; mt_type = None ;
+ mt_is_interface = false ; mt_file = "" ; mt_kind = Some tk ;
+ mt_loc = Odoc_types.dummy_loc }
+*)
+ in
+ iter_kind m.m_kind
+
+(** Returns the list of elements of a module type.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+and module_type_elements ?(trans=true) mt =
+ let rec iter_kind = function
+ | None -> []
+ | Some (Module_type_struct l) -> l
+ | Some (Module_type_functor (_, k)) -> iter_kind (Some k)
+ | Some (Module_type_with (k, _)) ->
+ if trans then
+ iter_kind (Some k)
+ else
+ []
+ | Some (Module_type_alias mta) ->
+ if trans then
+ match mta.mta_module with
+ None -> []
+ | Some mt -> module_type_elements mt
+ else
+ []
+ | Some (Module_type_typeof _) -> []
+ in
+ iter_kind mt.mt_kind
+
+(** Returns the list of values of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_values ?(trans=true) m = values (module_elements ~trans m)
+
+(** Returns the list of functional values of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_functions ?(trans=true) m =
+ List.filter
+ (fun v -> Odoc_value.is_function v)
+ (values (module_elements ~trans m))
+
+(** Returns the list of non-functional values of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_simple_values ?(trans=true) m =
+ List.filter
+ (fun v -> not (Odoc_value.is_function v))
+ (values (module_elements ~trans m))
+
+(** Returns the list of types of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_types ?(trans=true) m = types (module_elements ~trans m)
+
+(** Returns the list of type extensions of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_extensions ?(trans=true) m = type_extensions (module_elements ~trans m)
+
+(** Returns the list of exceptions of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_exceptions ?(trans=true) m = exceptions (module_elements ~trans m)
+
+(** Returns the list of classes of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_classes ?(trans=true) m = classes (module_elements ~trans m)
+
+(** Returns the list of class types of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_class_types ?(trans=true) m = class_types (module_elements ~trans m)
+
+(** Returns the list of modules of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_modules ?(trans=true) m = modules (module_elements ~trans m)
+
+(** Returns the list of module types of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_module_types ?(trans=true) m = mod_types (module_elements ~trans m)
+
+(** Returns the list of included module of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_included_modules ?(trans=true) m = included_modules (module_elements ~trans m)
+
+(** Returns the list of comments of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_comments ?(trans=true) m = comments (module_elements ~trans m)
+
+(** Access to the parameters, for a functor type.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let rec module_type_parameters ?(trans=true) mt =
+ let rec iter k =
+ match k with
+ Some (Module_type_functor (p, k2)) ->
+ let param =
+ (* we create the couple (parameter, description opt), using
+ the description of the parameter if we can find it in the comment.*)
+ match mt.mt_info with
+ None -> (p, None)
+ | Some i ->
+ try
+ let d = List.assoc p.mp_name i.Odoc_types.i_params in
+ (p, Some d)
+ with
+ Not_found ->
+ (p, None)
+ in
+ param :: (iter (Some k2))
+ | Some (Module_type_alias mta) ->
+ if trans then
+ match mta.mta_module with
+ None -> []
+ | Some mt2 -> module_type_parameters ~trans mt2
+ else
+ []
+ | Some (Module_type_with (k, _)) ->
+ if trans then
+ iter (Some k)
+ else
+ []
+ | Some (Module_type_struct _) ->
+ []
+ | Some (Module_type_typeof _) -> []
+ | None ->
+ []
+ in
+ iter mt.mt_kind
+
+(** Access to the parameters, for a functor.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+and module_parameters ?(trans=true) m =
+ let rec iter = function
+ Module_functor (p, k) ->
+ let param =
+ (* we create the couple (parameter, description opt), using
+ the description of the parameter if we can find it in the comment.*)
+ match m.m_info with
+ None ->(p, None)
+ | Some i ->
+ try
+ let d = List.assoc p.mp_name i.Odoc_types.i_params in
+ (p, Some d)
+ with
+ Not_found ->
+ (p, None)
+ in
+ param :: (iter k)
+
+ | Module_alias ma ->
+ if trans then
+ match ma.ma_module with
+ None -> []
+ | Some (Mod m) -> module_parameters ~trans m
+ | Some (Modtype mt) -> module_type_parameters ~trans mt
+ else
+ []
+ | Module_constraint (k, tk) ->
+ module_type_parameters ~trans: trans
+ { mt_name = "" ; mt_info = None ; mt_type = None ;
+ mt_is_interface = false ; mt_file = "" ; mt_kind = Some tk ;
+ mt_loc = Odoc_types.dummy_loc }
+ | Module_struct _
+ | Module_apply _
+ | Module_with _
+ | Module_typeof _
+ | Module_unpack _ -> []
+ in
+ iter m.m_kind
+
+(** access to all submodules and sudmobules of submodules ... of the given module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let rec module_all_submodules ?(trans=true) m =
+ let l = module_modules ~trans m in
+ List.fold_left
+ (fun acc -> fun m -> acc @ (module_all_submodules ~trans m))
+ l
+ l
+
+(** The module type is a functor if is defined as a functor or if it is an alias for a functor. *)
+let rec module_type_is_functor mt =
+ let rec iter k =
+ match k with
+ Some (Module_type_functor _) -> true
+ | Some (Module_type_alias mta) ->
+ (
+ match mta.mta_module with
+ None -> false
+ | Some mtyp -> module_type_is_functor mtyp
+ )
+ | Some (Module_type_with (k, _)) ->
+ iter (Some k)
+ | Some (Module_type_struct _)
+ | Some (Module_type_typeof _)
+ | None -> false
+ in
+ iter mt.mt_kind
+
+(** The module is a functor if is defined as a functor or if it is an alias for a functor. *)
+let module_is_functor m =
+ let rec iter = function
+ Module_functor _ -> true
+ | Module_alias ma ->
+ (
+ match ma.ma_module with
+ None -> false
+ | Some (Mod mo) -> iter mo.m_kind
+ | Some (Modtype mt) -> module_type_is_functor mt
+ )
+ | Module_constraint (k, _) ->
+ iter k
+ | _ -> false
+ in
+ iter m.m_kind
+
+(** Returns the list of values of a module type.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_values ?(trans=true) m = values (module_type_elements ~trans m)
+
+(** Returns the list of types of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_types ?(trans=true) m = types (module_type_elements ~trans m)
+
+(** Returns the list of type extensions of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_type_extensions ?(trans=true) m = type_extensions (module_type_elements ~trans m)
+
+(** Returns the list of exceptions of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_exceptions ?(trans=true) m = exceptions (module_type_elements ~trans m)
+
+(** Returns the list of classes of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_classes ?(trans=true) m = classes (module_type_elements ~trans m)
+
+(** Returns the list of class types of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_class_types ?(trans=true) m = class_types (module_type_elements ~trans m)
+
+(** Returns the list of modules of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_modules ?(trans=true) m = modules (module_type_elements ~trans m)
+
+(** Returns the list of module types of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_module_types ?(trans=true) m = mod_types (module_type_elements ~trans m)
+
+(** Returns the list of included module of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_included_modules ?(trans=true) m = included_modules (module_type_elements ~trans m)
+
+(** Returns the list of comments of a module.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_comments ?(trans=true) m = comments (module_type_elements ~trans m)
+
+(** Returns the list of functional values of a module type.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_functions ?(trans=true) mt =
+ List.filter
+ (fun v -> Odoc_value.is_function v)
+ (values (module_type_elements ~trans mt))
+
+(** Returns the list of non-functional values of a module type.
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let module_type_simple_values ?(trans=true) mt =
+ List.filter
+ (fun v -> not (Odoc_value.is_function v))
+ (values (module_type_elements ~trans mt))
+
+(** {2 Functions for modules and module types} *)
+
+(** The list of classes defined in this module and all its modules, functors, ....
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+let rec module_all_classes ?(trans=true) m =
+ List.fold_left
+ (fun acc -> fun m -> acc @ (module_all_classes ~trans m))
+ (
+ List.fold_left
+ (fun acc -> fun mtyp -> acc @ (module_type_all_classes ~trans mtyp))
+ (module_classes ~trans m)
+ (module_module_types ~trans m)
+ )
+ (module_modules ~trans m)
+
+(** The list of classes defined in this module type and all its modules, functors, ....
+ @param trans indicates if, for aliased modules, we must perform a transitive search.*)
+and module_type_all_classes ?(trans=true) mt =
+ List.fold_left
+ (fun acc -> fun m -> acc @ (module_all_classes ~trans m))
+ (
+ List.fold_left
+ (fun acc -> fun mtyp -> acc @ (module_type_all_classes ~trans mtyp))
+ (module_type_classes ~trans mt)
+ (module_type_module_types ~trans mt)
+ )
+ (module_type_modules ~trans mt)
diff --git a/ocamldoc/odoc_name.ml b/ocamldoc/odoc_name.ml
new file mode 100644
index 0000000000..9824101bea
--- /dev/null
+++ b/ocamldoc/odoc_name.ml
@@ -0,0 +1,224 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation of element names. *)
+
+let infix_chars = [ '|' ;
+ '<' ;
+ '>' ;
+ '@' ;
+ '^' ;
+ '&' ;
+ '+' ;
+ '-' ;
+ '*' ;
+ '/' ;
+ '$' ;
+ '%' ;
+ '=' ;
+ ':' ;
+ '~' ;
+ '!' ;
+ '.' ;
+ '#' ;
+ ]
+
+type t = string
+
+let strip_string s =
+ let len = String.length s in
+ let rec iter_first n =
+ if n >= len then
+ None
+ else
+ match s.[n] with
+ ' ' | '\t' | '\n' | '\r' -> iter_first (n+1)
+ | _ -> Some n
+ in
+ match iter_first 0 with
+ None -> ""
+ | Some first ->
+ let rec iter_last n =
+ if n <= first then
+ None
+ else
+ match s.[n] with
+ ' ' | '\t' | '\n' | '\r' -> iter_last (n-1)
+ | _ -> Some n
+ in
+ match iter_last (len-1) with
+ None -> String.sub s first 1
+ | Some last -> String.sub s first ((last-first)+1)
+
+let parens_if_infix name =
+ match strip_string name with
+ | "" -> ""
+ | s when s.[0] = '*' || s.[String.length s - 1] = '*' -> "( " ^ s ^ " )"
+ | s when List.mem s.[0] infix_chars -> "(" ^ s ^ ")"
+ | "or" | "mod" | "land" | "lor" | "lxor" | "lsl" | "lsr" | "asr" ->
+ "(" ^ name ^ ")"
+ | name -> name
+;;
+
+let cut name =
+ match name with
+ "" -> ("", "")
+ | s ->
+ let len = String.length s in
+ match s.[len-1] with
+ ')' ->
+ (
+ let j = ref 0 in
+ let buf = [|Buffer.create len ; Buffer.create len |] in
+ for i = 0 to len - 1 do
+ match s.[i] with
+ '.' when !j = 0 ->
+ if i < len - 1 then
+ match s.[i+1] with
+ '(' ->
+ j := 1
+ | _ ->
+ Buffer.add_char buf.(!j) '.'
+ else
+ Buffer.add_char buf.(!j) s.[i]
+ | c ->
+ Buffer.add_char buf.(!j) c
+ done;
+ (Buffer.contents buf.(0), Buffer.contents buf.(1))
+ )
+ | _ ->
+ match List.rev (Str.split (Str.regexp_string ".") s) with
+ [] -> ("", "")
+ | h :: q ->
+ (String.concat "." (List.rev q), h)
+
+let simple name = snd (cut name)
+let father name = fst (cut name)
+
+let concat n1 n2 = n1^"."^n2
+
+let normalize_name name =
+ let (p,s) = cut name in
+ let len = String.length s in
+ let s =
+ if len >= 2 &&
+ s.[0] = '(' && s.[len - 1] = ')'
+ then
+ parens_if_infix (strip_string (String.sub s 1 (len - 2)))
+ else
+ s
+ in
+ match p with
+ "" -> s
+ | p -> concat p s
+ ;;
+
+let head_and_tail n =
+ try
+ let pos = String.index n '.' in
+ if pos > 0 then
+ let h = String.sub n 0 pos in
+ try
+ ignore (String.index h '(');
+ (n, "")
+ with
+ Not_found ->
+ let len = String.length n in
+ if pos >= (len - 1) then
+ (h, "")
+ else
+ (h, String.sub n (pos + 1) (len - pos - 1))
+ else
+ (n, "")
+ with
+ Not_found -> (n, "")
+
+let head n = fst (head_and_tail n)
+let tail n = snd (head_and_tail n)
+
+let depth name =
+ try
+ List.length (Str.split (Str.regexp "\\.") name)
+ with
+ _ -> 1
+
+let prefix n1 n2 =
+ (n1 <> n2) &&
+ (try
+ let len1 = String.length n1 in
+ ((String.sub n2 0 len1) = n1) &&
+ (n2.[len1] = '.')
+ with _ -> false)
+
+let rec get_relative_raw n1 n2 =
+ let (f1,s1) = head_and_tail n1 in
+ let (f2,s2) = head_and_tail n2 in
+ if f1 = f2 then
+ if f2 = s2 || s2 = "" then
+ s2
+ else
+ if f1 = s1 || s1 = "" then
+ s2
+ else
+ get_relative_raw s1 s2
+ else
+ n2
+
+let get_relative n1 n2 =
+ if prefix n1 n2 then
+ let len1 = String.length n1 in
+ try
+ String.sub n2 (len1+1) ((String.length n2) - len1 - 1)
+ with
+ _ -> n2
+ else
+ n2
+
+let hide_given_modules l s =
+ let rec iter = function
+ [] -> s
+ | h :: q ->
+ let s2 = get_relative h s in
+ if s = s2 then
+ iter q
+ else
+ s2
+ in
+ iter l
+
+let qualified name = String.contains name '.'
+
+let from_ident ident = Ident.name ident
+
+
+let from_path path = Path.name path
+
+let to_path n =
+ match
+ List.fold_left
+ (fun acc_opt -> fun s ->
+ match acc_opt with
+ None -> Some (Path.Pident (Ident.create s))
+ | Some acc -> Some (Path.Pdot (acc, s, 0)))
+ None
+ (Str.split (Str.regexp "\\.") n)
+ with
+ None -> raise (Failure "to_path")
+ | Some p -> p
+
+let from_longident = Odoc_misc.string_of_longident
+
+module Set = Set.Make (struct
+ type z = t
+ type t = z
+ let compare = String.compare
+end)
diff --git a/ocamldoc/odoc_name.mli b/ocamldoc/odoc_name.mli
new file mode 100644
index 0000000000..9c0e51ecf4
--- /dev/null
+++ b/ocamldoc/odoc_name.mli
@@ -0,0 +1,71 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation of element names. *)
+
+type t = string
+
+(** Add parenthesis to the given simple name if needed. *)
+val parens_if_infix : t -> t
+
+(** Return a simple name from a name.*)
+val simple : t -> t
+
+(** Return the name of the 'father' (like dirname for a file name).*)
+val father : t -> t
+
+(** Concatenates two names. *)
+val concat : t -> t -> t
+
+(** Normalize the given name by removing the beginning and ending spaces
+ of the simple name and adding parenthesis if needed. *)
+val normalize_name : t -> t
+
+(** Returns the head of a name. *)
+val head : t -> t
+
+(** Returns the depth of the name, i.e. the numer of levels to the root.
+ Example : [Toto.Tutu.name] has depth 3. *)
+val depth : t -> int
+
+(** Returns true if the first name is a prefix of the second name.
+ If the two names are equals, then if is false (strict prefix).*)
+val prefix : t -> t -> bool
+
+(** Take two names n1 and n2 = n3.n4 and return n4 if n3=n1 or else n2. *)
+val get_relative : t -> t -> t
+
+(** Take two names n1=n3.n4 and n2 = n5.n6 and return n6 if n3=n5 or else n2. *)
+val get_relative_raw : t -> t -> t
+
+(** Take a list of module names to hide and a name,
+ and return the name when the module name (or part of it)
+ was removed, according to the list of module names to hide.*)
+val hide_given_modules : t list -> t -> t
+
+(** Indicate if a name if qualified or not. *)
+val qualified : t -> bool
+
+(** Get a name from an [Ident.t]. *)
+val from_ident : Ident.t -> t
+
+(** Get a name from a [Path.t]. *)
+val from_path : Path.t -> t
+
+(** Get a [Path.t] from a name.*)
+val to_path : t -> Path.t
+
+(** Get a name from a [Longident.t].*)
+val from_longident : Longident.t -> t
+
+(** Set of Name.t *)
+module Set : Set.S with type elt = t
diff --git a/ocamldoc/odoc_ocamlhtml.mll b/ocamldoc/odoc_ocamlhtml.mll
new file mode 100644
index 0000000000..9b3ad2da18
--- /dev/null
+++ b/ocamldoc/odoc_ocamlhtml.mll
@@ -0,0 +1,542 @@
+
+{
+(***********************************************************************)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Generation of html code to display OCaml code. *)
+open Lexing
+
+exception Fatal_error
+
+let fatal_error msg =
+ prerr_string ">> Fatal error: "; prerr_endline msg; raise Fatal_error
+
+type error =
+ | Illegal_character of char
+ | Unterminated_comment
+ | Unterminated_string
+ | Unterminated_string_in_comment
+ | Keyword_as_label of string
+;;
+
+exception Error of error * int * int
+
+let base_escape_strings = [
+ ("&", "&amp;") ;
+ ("<", "&lt;") ;
+ (">", "&gt;") ;
+]
+
+let pre_escape_strings = [
+ (" ", "&nbsp;") ;
+ ("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;") ;
+ ]
+
+
+let pre = ref false
+let fmt = ref Format.str_formatter
+
+(** Escape the strings which would clash with html syntax,
+ and some other strings if we want to get a PRE style.*)
+let escape s =
+ List.fold_left
+ (fun acc -> fun (s, s2) -> Str.global_replace (Str.regexp s) s2 acc)
+ s
+ (if !pre then base_escape_strings @ pre_escape_strings else base_escape_strings)
+
+(** Escape the strings which would clash with html syntax. *)
+let escape_base s =
+ List.fold_left
+ (fun acc -> fun (s, s2) -> Str.global_replace (Str.regexp s) s2 acc)
+ s
+ base_escape_strings
+
+(** The output functions *)
+
+let print ?(esc=true) s =
+ Format.pp_print_string !fmt (if esc then escape s else s)
+;;
+
+let print_class ?(esc=true) cl s =
+ print ~esc: false ("<span class=\""^cl^"\">"^
+ (if esc then escape s else s)^
+ "</span>")
+;;
+
+(** The table of keywords with colors *)
+let create_hashtable size init =
+ let tbl = Hashtbl.create size in
+ List.iter (fun (key, data) -> Hashtbl.add tbl key data) init;
+ tbl
+
+(** The function used to return html code for the given comment body. *)
+let html_of_comment = ref
+ (fun (s : string) -> "<b>Odoc_ocamlhtml.html_of_comment not initialized</b>")
+
+let keyword_table =
+ create_hashtable 149 [
+ "and", "keyword" ;
+ "as", "keyword" ;
+ "assert", "keyword" ;
+ "begin", "keyword" ;
+ "class", "keyword" ;
+ "constraint", "keyword" ;
+ "do", "keyword" ;
+ "done", "keyword" ;
+ "downto", "keyword" ;
+ "else", "keyword" ;
+ "end", "keyword" ;
+ "exception", "keyword" ;
+ "external", "keyword" ;
+ "false", "keyword" ;
+ "for", "keyword" ;
+ "fun", "keyword" ;
+ "function", "keyword" ;
+ "functor", "keyword" ;
+ "if", "keyword" ;
+ "in", "keyword" ;
+ "include", "keyword" ;
+ "inherit", "keyword" ;
+ "initializer", "keyword" ;
+ "lazy", "keyword" ;
+ "let", "keyword" ;
+ "match", "keyword" ;
+ "method", "keyword" ;
+ "module", "keyword" ;
+ "mutable", "keyword" ;
+ "new", "keyword" ;
+ "object", "keyword" ;
+ "of", "keyword" ;
+ "open", "keyword" ;
+ "or", "keyword" ;
+ "parser", "keyword" ;
+ "private", "keyword" ;
+ "rec", "keyword" ;
+ "sig", "keyword" ;
+ "struct", "keyword" ;
+ "then", "keyword" ;
+ "to", "keyword" ;
+ "true", "keyword" ;
+ "try", "keyword" ;
+ "type", "keyword" ;
+ "val", "keyword" ;
+ "virtual", "keyword" ;
+ "when", "keyword" ;
+ "while", "keyword" ;
+ "with", "keyword" ;
+
+ "mod", "keyword" ;
+ "land", "keyword" ;
+ "lor", "keyword" ;
+ "lxor", "keyword" ;
+ "lsl", "keyword" ;
+ "lsr", "keyword" ;
+ "asr", "keyword" ;
+]
+
+let kwsign_class = "keywordsign"
+let constructor_class = "constructor"
+let comment_class = "comment"
+let string_class = "string"
+let code_class = "code"
+
+
+(** To buffer and print comments *)
+
+
+let margin = ref 0
+
+let comment_buffer = Buffer.create 32
+let reset_comment_buffer () = Buffer.reset comment_buffer
+let store_comment_char = Buffer.add_char comment_buffer
+let add_comment_string = Buffer.add_string comment_buffer
+
+let make_margin () =
+ let rec iter n =
+ if n <= 0 then ""
+ else "&nbsp;"^(iter (n-1))
+ in
+ iter !margin
+
+let print_comment () =
+ let s = Buffer.contents comment_buffer in
+ let len = String.length s in
+ let code =
+ if len < 1 then
+ "<span class=\""^comment_class^"\">(*"^(escape s)^"*)</span>"
+ else
+ match s.[0] with
+ '*' ->
+ (
+ try
+ let html = !html_of_comment (String.sub s 1 (len-1)) in
+ "</code><table><tr><td>"^(make_margin ())^"</td><td>"^
+ "<span class=\""^comment_class^"\">"^
+ "(**"^html^"*)"^
+ "</span></td></tr></table><code class=\""^code_class^"\">"
+ with
+ e ->
+ prerr_endline (Printexc.to_string e);
+ "<span class=\""^comment_class^"\">(*"^(escape s)^"*)</span>"
+ )
+ | _ ->
+ "<span class=\""^comment_class^"\">(*"^(escape s)^"*)</span>"
+ in
+ print ~esc: false code
+
+(** To buffer string literals *)
+
+let string_buffer = Buffer.create 32
+let reset_string_buffer () = Buffer.reset string_buffer
+let store_string_char = Buffer.add_char string_buffer
+let get_stored_string () =
+ let s = Buffer.contents string_buffer in
+ s
+
+(** To translate escape sequences *)
+
+let char_for_backslash = function
+ | 'n' -> '\010'
+ | 'r' -> '\013'
+ | 'b' -> '\008'
+ | 't' -> '\009'
+ | c -> c
+
+let char_for_decimal_code lexbuf i =
+ let c = 100 * (Char.code(Lexing.lexeme_char lexbuf i) - 48) +
+ 10 * (Char.code(Lexing.lexeme_char lexbuf (i+1)) - 48) +
+ (Char.code(Lexing.lexeme_char lexbuf (i+2)) - 48) in
+ Char.chr(c land 0xFF)
+
+let char_for_hexa_code lexbuf i =
+ let c = 16 * (Char.code(Lexing.lexeme_char lexbuf i) - 48) +
+ (Char.code(Lexing.lexeme_char lexbuf (i+1)) - 48) in
+ Char.chr(c land 0xFF)
+
+(** To store the position of the beginning of a string and comment *)
+let string_start_pos = ref 0;;
+let comment_start_pos = ref [];;
+let in_comment () = !comment_start_pos <> [];;
+
+(** Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Illegal_character c ->
+ fprintf ppf "Illegal character (%s)" (Char.escaped c)
+ | Unterminated_comment ->
+ fprintf ppf "Comment not terminated"
+ | Unterminated_string ->
+ fprintf ppf "String literal not terminated"
+ | Unterminated_string_in_comment ->
+ fprintf ppf "This comment contains an unterminated string literal"
+ | Keyword_as_label kwd ->
+ fprintf ppf "`%s' is a keyword, it cannot be used as label name" kwd
+;;
+
+}
+
+let blank = [' ' '\010' '\013' '\009' '\012']
+let lowercase = ['a'-'z' '\223'-'\246' '\248'-'\255' '_']
+let uppercase = ['A'-'Z' '\192'-'\214' '\216'-'\222']
+let identchar =
+ ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9']
+let symbolchar =
+ ['!' '$' '%' '&' '*' '+' '-' '.' '/' ':' '<' '=' '>' '?' '@' '^' '|' '~']
+let decimal_literal = ['0'-'9']+
+let hex_literal = '0' ['x' 'X'] ['0'-'9' 'A'-'F' 'a'-'f']+
+let oct_literal = '0' ['o' 'O'] ['0'-'7']+
+let bin_literal = '0' ['b' 'B'] ['0'-'1']+
+let float_literal =
+ ['0'-'9']+ ('.' ['0'-'9']* )? (['e' 'E'] ['+' '-']? ['0'-'9']+)?
+
+rule token = parse
+ blank
+ {
+ let s = Lexing.lexeme lexbuf in
+ (
+ match s with
+ " " -> incr margin
+ | "\t" -> margin := !margin + 8
+ | "\n" -> margin := 0
+ | _ -> ()
+ );
+ print s;
+ token lexbuf
+ }
+ | "_"
+ { print "_" ; token lexbuf }
+ | "~" { print "~" ; token lexbuf }
+ | "~" lowercase identchar * ':'
+ { let s = Lexing.lexeme lexbuf in
+ let name = String.sub s 1 (String.length s - 2) in
+ if Hashtbl.mem keyword_table name then
+ raise (Error(Keyword_as_label name, Lexing.lexeme_start lexbuf,
+ Lexing.lexeme_end lexbuf));
+ print s ; token lexbuf }
+ | "?" { print "?" ; token lexbuf }
+ | "?" lowercase identchar * ':'
+ { let s = Lexing.lexeme lexbuf in
+ let name = String.sub s 1 (String.length s - 2) in
+ if Hashtbl.mem keyword_table name then
+ raise (Error(Keyword_as_label name, Lexing.lexeme_start lexbuf,
+ Lexing.lexeme_end lexbuf));
+ print s ; token lexbuf }
+ | lowercase identchar *
+ { let s = Lexing.lexeme lexbuf in
+ try
+ let cl = Hashtbl.find keyword_table s in
+ (print_class cl s ; token lexbuf )
+ with Not_found ->
+ (print s ; token lexbuf )}
+ | uppercase identchar *
+ { print_class constructor_class (Lexing.lexeme lexbuf) ; token lexbuf } (* No capitalized keywords *)
+ | decimal_literal | hex_literal | oct_literal | bin_literal
+ { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | float_literal
+ { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "\""
+ { reset_string_buffer();
+ let string_start = Lexing.lexeme_start lexbuf in
+ string_start_pos := string_start;
+ string lexbuf;
+ lexbuf.Lexing.lex_start_pos <-
+ string_start - lexbuf.Lexing.lex_abs_pos;
+ print_class string_class ("\""^(get_stored_string())^"\"") ;
+ token lexbuf }
+ | "'" [^ '\\' '\''] "'"
+ { print_class string_class (Lexing.lexeme lexbuf) ;
+ token lexbuf }
+ | "'" '\\' ['\\' '\'' 'n' 't' 'b' 'r'] "'"
+ { print_class string_class (Lexing.lexeme lexbuf ) ;
+ token lexbuf }
+ | "'" '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
+ { print_class string_class (Lexing.lexeme lexbuf ) ;
+ token lexbuf }
+ | "(*"
+ {
+ reset_comment_buffer ();
+ comment_start_pos := [Lexing.lexeme_start lexbuf];
+ comment lexbuf ;
+ print_comment ();
+ token lexbuf }
+ | "(*)"
+ { reset_comment_buffer ();
+ comment_start_pos := [Lexing.lexeme_start lexbuf];
+ comment lexbuf ;
+ print_comment ();
+ token lexbuf
+ }
+ | "*)"
+ { lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_curr_pos - 1;
+ lexbuf.Lexing.lex_curr_p <-
+ { lexbuf.Lexing.lex_curr_p with
+ pos_cnum = lexbuf.Lexing.lex_curr_p.pos_cnum - 1
+ } ;
+ print (Lexing.lexeme lexbuf) ;
+ token lexbuf
+ }
+ | "#" [' ' '\t']* ['0'-'9']+ [^ '\n' '\r'] * ('\n' | '\r' | "\r\n")
+ (* # linenum ... *)
+ {
+ print (Lexing.lexeme lexbuf);
+ token lexbuf
+ }
+ | "#" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "&" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "&&" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "`" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "'" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "(" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ")" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "*" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "," { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "??" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "->" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "." { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ".." { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ":" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "::" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ":=" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ":>" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ";" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ";;" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "<" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "<-" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "=" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "[" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "[|" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "[<" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "]" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "{" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "{<" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "|" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "||" { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "|]" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ">" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ">]" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "}" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ">}" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+
+ | "!=" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "+" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "-" { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "-." { print (Lexing.lexeme lexbuf) ; token lexbuf }
+
+ | "!" symbolchar *
+ { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ['~' '?'] symbolchar +
+ { print_class kwsign_class (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ['=' '<' '>' '|' '&' '$'] symbolchar *
+ { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ['@' '^'] symbolchar *
+ { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ['+' '-'] symbolchar *
+ { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | "**" symbolchar *
+ { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | ['*' '/' '%'] symbolchar *
+ { print (Lexing.lexeme lexbuf) ; token lexbuf }
+ | eof { () }
+ | _
+ { raise (Error(Illegal_character ((Lexing.lexeme lexbuf).[0]),
+ Lexing.lexeme_start lexbuf, Lexing.lexeme_end lexbuf)) }
+
+and comment = parse
+ "(*"
+ { comment_start_pos := Lexing.lexeme_start lexbuf :: !comment_start_pos;
+ store_comment_char '(';
+ store_comment_char '*';
+ comment lexbuf;
+ }
+ | "*)"
+ { match !comment_start_pos with
+ | [] -> assert false
+ | [x] -> comment_start_pos := []
+ | _ :: l ->
+ store_comment_char '*';
+ store_comment_char ')';
+ comment_start_pos := l;
+ comment lexbuf;
+ }
+(* These filters are useless
+ | "\""
+ { reset_string_buffer();
+ string_start_pos := Lexing.lexeme_start lexbuf;
+ store_comment_char '"';
+ begin
+ try string lexbuf; add_comment_string ((get_stored_string()^"\""))
+ with Error (Unterminated_string, _, _) ->
+ let st = List.hd !comment_start_pos in
+ raise (Error (Unterminated_string_in_comment, st, st + 2))
+ end;
+ comment lexbuf }
+ | "'" [^ '\\' '\''] "'"
+ {
+ store_comment_char '\'';
+ store_comment_char (Lexing.lexeme_char lexbuf 1);
+ store_comment_char '\'';
+ comment lexbuf }
+ | "'\\" ['\\' '\'' 'n' 't' 'b' 'r'] "'"
+ {
+ store_comment_char '\'';
+ store_comment_char '\\';
+ store_comment_char(char_for_backslash(Lexing.lexeme_char lexbuf 1)) ;
+ store_comment_char '\'';
+ comment lexbuf }
+ | "\\" ['0'-'9'] ['0'-'9'] ['0'-'9']
+ {
+ store_comment_char(char_for_decimal_code lexbuf 1);
+ comment lexbuf }
+ | "\\x" ['0'-'9' 'A'-'Z' 'a'-'z' ] ['0'-'9' 'A'-'Z' 'a'-'z']
+ {
+ store_comment_char(char_for_hexa_code lexbuf 2);
+ string lexbuf }
+ | "''"
+ {
+ store_comment_char '\'';
+ store_comment_char '\'';
+ comment lexbuf }
+*)
+ | eof
+ { let st = List.hd !comment_start_pos in
+ raise (Error (Unterminated_comment, st, st + 2));
+ }
+ | _
+ { store_comment_char(Lexing.lexeme_char lexbuf 0);
+ comment lexbuf }
+
+and string = parse
+ '"'
+ { () }
+ | '\\' ("\010" | "\013" | "\013\010") [' ' '\009'] *
+ { string lexbuf }
+ | '\\' ['\\' '"' 'n' 't' 'b' 'r' ]
+ { Buffer.add_string string_buffer (Lexing.lexeme lexbuf) ;
+ string lexbuf }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9']
+ {
+ Buffer.add_string string_buffer (Lexing.lexeme lexbuf) ;
+ string lexbuf
+ }
+ | '\\' 'x' ['0'-'9' 'A'-'Z' 'a'-'z' ] ['0'-'9' 'A'-'Z' 'a'-'z']
+ { Buffer.add_string string_buffer (Lexing.lexeme lexbuf) ;
+ string lexbuf }
+ | eof
+ { raise (Error (Unterminated_string,
+ !string_start_pos, !string_start_pos+1)) }
+ | _
+ { store_string_char(Lexing.lexeme_char lexbuf 0);
+ string lexbuf }
+{
+
+let html_of_code b ?(with_pre=true) code =
+ let old_pre = !pre in
+ let old_margin = !margin in
+ let old_comment_buffer = Buffer.contents comment_buffer in
+ let old_string_buffer = Buffer.contents string_buffer in
+ let buf = Buffer.create 256 in
+ let old_fmt = !fmt in
+ fmt := Format.formatter_of_buffer buf ;
+ pre := with_pre;
+ margin := 0;
+
+ let start = "<code class=\""^code_class^"\">" in
+ let ending = "</code>" in
+ let html =
+ (
+ try
+ print ~esc: false start ;
+ let lexbuf = Lexing.from_string code in
+ let _ = token lexbuf in
+ print ~esc: false ending ;
+ Format.pp_print_flush !fmt () ;
+ Buffer.contents buf
+ with
+ _ ->
+ (* flush str_formatter because we already output
+ something in it *)
+ Format.pp_print_flush !fmt () ;
+ start^code^ending
+ )
+ in
+ pre := old_pre;
+ margin := old_margin ;
+ Buffer.reset comment_buffer;
+ Buffer.add_string comment_buffer old_comment_buffer ;
+ Buffer.reset string_buffer;
+ Buffer.add_string string_buffer old_string_buffer ;
+ fmt := old_fmt ;
+
+ Buffer.add_string b html
+
+}
diff --git a/ocamldoc/odoc_parameter.ml b/ocamldoc/odoc_parameter.ml
new file mode 100644
index 0000000000..be98ef41c1
--- /dev/null
+++ b/ocamldoc/odoc_parameter.ml
@@ -0,0 +1,122 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation and manipulation of method / function / class parameters. *)
+
+let print_DEBUG s = print_string s ; print_newline ()
+
+(** Types *)
+
+(** Representation of a simple parameter name *)
+type simple_name = {
+ sn_name : string ;
+ sn_type : Types.type_expr ;
+ mutable sn_text : Odoc_types.text option ;
+ }
+
+(** Representation of parameter names. We need it to represent parameter names in tuples.
+ The value [Tuple ([], t)] stands for an anonymous parameter.*)
+type param_info =
+ | Simple_name of simple_name
+ | Tuple of param_info list * Types.type_expr
+
+(** A parameter is just a param_info.*)
+type parameter = param_info
+
+(** Functions *)
+
+(** acces to the name as a string. For tuples, parenthesis and commas are added. *)
+let complete_name p =
+ let rec iter pi =
+ match pi with
+ Simple_name sn ->
+ sn.sn_name
+ | Tuple ([], _) -> (* anonymous parameter *)
+ "??"
+ | Tuple (pi_list, _) ->
+ "("^(String.concat "," (List.map iter pi_list))^")"
+ in
+ iter p
+
+(** access to the complete type *)
+let typ pi =
+ match pi with
+ Simple_name sn -> sn.sn_type
+ | Tuple (_, typ) -> typ
+
+(** Update the text of a parameter using a function returning
+ the optional text associated to a parameter name.*)
+let update_parameter_text f p =
+ let rec iter pi =
+ match pi with
+ Simple_name sn ->
+ sn.sn_text <- f sn.sn_name
+ | Tuple (l, _) ->
+ List.iter iter l
+ in
+ iter p
+
+(** access to the description of a specific name.
+ @raise Not_found if no description is associated to the given name. *)
+let desc_by_name pi name =
+ let rec iter acc pi =
+ match pi with
+ Simple_name sn ->
+ (sn.sn_name, sn.sn_text) :: acc
+ | Tuple (pi_list, _) ->
+ List.fold_left iter acc pi_list
+ in
+ let l = iter [] pi in
+ List.assoc name l
+
+
+(** acces to the list of names ; only one for a simple parameter, or
+ a list for tuples. *)
+let names pi =
+ let rec iter acc pi =
+ match pi with
+ Simple_name sn ->
+ sn.sn_name :: acc
+ | Tuple (pi_list, _) ->
+ List.fold_left iter acc pi_list
+ in
+ iter [] pi
+
+(** access to the type of a specific name.
+ @raise Not_found if no type is associated to the given name. *)
+let type_by_name pi name =
+ let rec iter acc pi =
+ match pi with
+ Simple_name sn ->
+ (sn.sn_name, sn.sn_type) :: acc
+ | Tuple (pi_list, _) ->
+ List.fold_left iter acc pi_list
+ in
+ let l = iter [] pi in
+ List.assoc name l
+
+(** access to the optional description of a parameter name from an optional info structure.*)
+let desc_from_info_opt info_opt s =
+ print_DEBUG "desc_from_info_opt";
+ match info_opt with
+ None -> None
+ | Some i ->
+ match s with
+ "" -> None
+ | _ ->
+ try
+ Some (List.assoc s i.Odoc_types.i_params)
+ with
+ Not_found ->
+ print_DEBUG ("desc_from_info_opt "^s^" not found in\n");
+ List.iter (fun (s, _) -> print_DEBUG s) i.Odoc_types.i_params;
+ None
diff --git a/ocamldoc/odoc_parser.mly b/ocamldoc/odoc_parser.mly
new file mode 100644
index 0000000000..ea7d9a5705
--- /dev/null
+++ b/ocamldoc/odoc_parser.mly
@@ -0,0 +1,174 @@
+%{
+(***********************************************************************)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Odoc_types
+open Odoc_comments_global
+
+let uppercase = "[A-Z\192-\214\216-\222]"
+let identchar =
+ "[A-Za-z_\192-\214\216-\246\248-\255'0-9]"
+let blank = "[ \010\013\009\012]"
+
+let print_DEBUG s = print_string s; print_newline ()
+%}
+
+%token <string * (string option)> Description
+
+%token <string> See_url
+%token <string> See_file
+%token <string> See_doc
+
+%token T_PARAM
+%token T_AUTHOR
+%token T_VERSION
+%token T_SEE
+%token T_SINCE
+%token T_BEFORE
+%token T_DEPRECATED
+%token T_RAISES
+%token T_RETURN
+%token <string> T_CUSTOM
+
+%token EOF
+
+%token <string> Desc
+
+/* Start Symbols */
+%start main info_part2 see_info
+%type <(string * (string option)) option> main
+%type <unit> info_part2
+%type <Odoc_types.see_ref * string> see_info
+
+
+%%
+see_info:
+ see_ref Desc { ($1, $2) }
+;
+
+see_ref:
+ See_url { Odoc_types.See_url $1 }
+| See_file { Odoc_types.See_file $1 }
+| See_doc { Odoc_types.See_doc $1 }
+;
+
+main:
+ Description { Some $1 }
+| EOF { None }
+;
+
+info_part2:
+ element_list EOF { () }
+;
+
+element_list:
+ element { () }
+| element element_list { () }
+;
+
+element:
+| param { () }
+| author { () }
+| version { () }
+| see { () }
+| since { () }
+| before { () }
+| deprecated { () }
+| raise_exc { () }
+| return { () }
+| custom { () }
+;
+
+param:
+ T_PARAM Desc
+ {
+ (* isolate the identificator *)
+ (* we only look for simple id, no pattern nor tuples *)
+ let s = $2 in
+ match Str.split (Str.regexp (blank^"+")) s with
+ []
+ | _ :: [] ->
+ raise (Failure "usage: @param id description")
+ | id :: _ ->
+ print_DEBUG ("Identificator "^id);
+ let reg = identchar^"+" in
+ print_DEBUG ("reg="^reg);
+ if Str.string_match (Str.regexp reg) id 0 then
+ let remain = String.sub s (String.length id) ((String.length s) - (String.length id)) in
+ print_DEBUG ("T_PARAM Desc remain="^remain);
+ let remain2 = Str.replace_first (Str.regexp ("^"^blank^"+")) "" remain in
+ params := !params @ [(id, remain2)]
+ else
+ raise (Failure (id^" is not a valid parameter identificator in \"@param "^s^"\""))
+ }
+;
+author:
+ T_AUTHOR Desc { authors := !authors @ [ $2 ] }
+;
+version:
+ T_VERSION Desc { version := Some $2 }
+;
+see:
+ T_SEE Desc { sees := !sees @ [$2] }
+;
+since:
+ T_SINCE Desc { since := Some $2 }
+;
+before:
+ T_BEFORE Desc
+ {
+ (* isolate the version name *)
+ let s = $2 in
+ match Str.split (Str.regexp (blank^"+")) s with
+ []
+ | _ :: [] ->
+ raise (Failure "usage: @before version description")
+ | id :: _ ->
+ print_DEBUG ("version "^id);
+ let remain = String.sub s (String.length id) ((String.length s) - (String.length id)) in
+ let remain2 = Str.replace_first (Str.regexp ("^"^blank^"+")) "" remain in
+ before := !before @ [(id, remain2)]
+ }
+;
+deprecated:
+ T_DEPRECATED Desc { deprecated := Some $2 }
+;
+raise_exc:
+ T_RAISES Desc
+ {
+ (* isolate the exception construtor name *)
+ let s = $2 in
+ match Str.split (Str.regexp (blank^"+")) s with
+ []
+ | _ :: [] ->
+ raise (Failure "usage: @raise Exception description")
+ | id :: _ ->
+ print_DEBUG ("exception "^id);
+ let reg = uppercase^identchar^"*"^"\\(\\."^uppercase^identchar^"*\\)*" in
+ print_DEBUG ("reg="^reg);
+ if Str.string_match (Str.regexp reg) id 0 then
+ let remain = String.sub s (String.length id) ((String.length s) - (String.length id)) in
+ let remain2 = Str.replace_first (Str.regexp ("^"^blank^"+")) "" remain in
+ raised_exceptions := !raised_exceptions @ [(id, remain2)]
+ else
+ raise (Failure (id^" is not a valid exception constructor in \"@raise "^s^"\""))
+ }
+;
+return:
+ T_RETURN Desc { return_value := Some $2 }
+;
+
+custom:
+ T_CUSTOM Desc { customs := !customs @ [($1, $2)] }
+;
+
+
+%%
diff --git a/ocamldoc/odoc_print.ml b/ocamldoc/odoc_print.ml
new file mode 100644
index 0000000000..56a85e5fda
--- /dev/null
+++ b/ocamldoc/odoc_print.ml
@@ -0,0 +1,100 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+let new_fmt () =
+ let buf = Buffer.create 512 in
+ let fmt = formatter_of_buffer buf in
+ let flush () =
+ pp_print_flush fmt ();
+ let s = Buffer.contents buf in
+ Buffer.reset buf ;
+ s
+ in
+ (fmt, flush)
+
+let (type_fmt, flush_type_fmt) = new_fmt ()
+let _ =
+ let outfuns = pp_get_formatter_out_functions type_fmt () in
+ pp_set_formatter_out_functions type_fmt
+ {outfuns with out_newline = fun () -> outfuns.out_string "\n " 0 3}
+
+let (modtype_fmt, flush_modtype_fmt) = new_fmt ()
+
+
+
+
+let string_of_type_expr t =
+ Printtyp.mark_loops t;
+ Printtyp.type_scheme_max ~b_reset_names: false type_fmt t;
+ flush_type_fmt ()
+
+exception Use_code of string
+
+(** Return the given module type where methods and vals have been removed
+ from the signatures. Used when we don't want to print a too long module type.
+ @param code when the code is given, we raise the [Use_code] exception is we
+ encouter a signature, to that the calling function can use the code rather
+ than the "emptied" type.
+*)
+let simpl_module_type ?code t =
+ let rec iter t =
+ match t with
+ Types.Mty_ident p -> t
+ | Types.Mty_alias p -> t
+ | Types.Mty_signature _ ->
+ (
+ match code with
+ None -> Types.Mty_signature []
+ | Some s -> raise (Use_code s)
+ )
+ | Types.Mty_functor (id, mt1, mt2) ->
+ Types.Mty_functor (id, Misc.may_map iter mt1, iter mt2)
+ in
+ iter t
+
+let string_of_module_type ?code ?(complete=false) t =
+ try
+ let t2 = if complete then t else simpl_module_type ?code t in
+ Printtyp.modtype modtype_fmt t2;
+ flush_modtype_fmt ()
+ with
+ Use_code s -> s
+
+(** Return the given class type where methods and vals have been removed
+ from the signatures. Used when we don't want to print a too long class type.*)
+let simpl_class_type t =
+ let rec iter t =
+ match t with
+ Types.Cty_constr (p,texp_list,ct) -> t
+ | Types.Cty_signature cs ->
+ (* on vire les vals et methods pour ne pas qu'elles soient imprimees
+ quand on affichera le type *)
+ let tnil = { Types.desc = Types.Tnil ; Types.level = 0; Types.id = 0 } in
+ Types.Cty_signature { Types.csig_self = { cs.Types.csig_self with
+ Types.desc = Types.Tobject (tnil, ref None) };
+ csig_vars = Types.Vars.empty ;
+ csig_concr = Types.Concr.empty ;
+ csig_inher = []
+ }
+ | Types.Cty_arrow (l, texp, ct) ->
+ let new_ct = iter ct in
+ Types.Cty_arrow (l, texp, new_ct)
+ in
+ iter t
+
+let string_of_class_type ?(complete=false) t =
+ let t2 = if complete then t else simpl_class_type t in
+ (* A VOIR : ma propre version de Printtyp.class_type pour ne pas faire reset_names *)
+ Printtyp.class_type modtype_fmt t2;
+ flush_modtype_fmt ()
diff --git a/ocamldoc/odoc_print.mli b/ocamldoc/odoc_print.mli
new file mode 100644
index 0000000000..f7c5901395
--- /dev/null
+++ b/ocamldoc/odoc_print.mli
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Printing functions. *)
+
+(** This function takes a Types.type_expr and returns a string.
+ It writes in and flushes [Format.str_formatter].*)
+val string_of_type_expr : Types.type_expr -> string
+
+(** This function returns a string representing a [Types.module_type].
+ @param complete indicates if we must print complete signatures
+ or just [sig end]. Default if [false].
+ @param code if [complete = false] and the type contains something else
+ than identificators and functors, then the given code is used.
+*)
+val string_of_module_type : ?code: string -> ?complete: bool -> Types.module_type -> string
+
+(** This function returns a string representing a [Types.class_type].
+ @param complete indicates if we must print complete signatures
+ or just [object end]. Default if [false].
+*)
+val string_of_class_type : ?complete: bool -> Types.class_type -> string
diff --git a/ocamldoc/odoc_scan.ml b/ocamldoc/odoc_scan.ml
new file mode 100644
index 0000000000..e6c19f29d4
--- /dev/null
+++ b/ocamldoc/odoc_scan.ml
@@ -0,0 +1,188 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Scanning of modules and elements.
+
+ The class scanner defined in this module can be used to
+ develop generators which perform controls on the elements
+ and their comments.
+*)
+
+open Odoc_types
+
+(** Class which defines the scanning of a list of modules and their
+ elements. Inherit this class to develop your own scanner, by
+ overriding some methods.*)
+class scanner =
+ object (self)
+ (** Scan of 'leaf elements'. *)
+
+ method scan_value (v : Odoc_value.t_value) = ()
+
+ method scan_type_pre (t : Odoc_type.t_type) = true
+
+ method scan_type_recfield t (f : Odoc_type.record_field) = ()
+ method scan_type_const t (f : Odoc_type.variant_constructor) = ()
+ method scan_type (t : Odoc_type.t_type) =
+ if self#scan_type_pre t then
+ match t.Odoc_type.ty_kind with
+ Odoc_type.Type_abstract -> ()
+ | Odoc_type.Type_variant l -> List.iter (self#scan_type_const t) l
+ | Odoc_type.Type_record l -> List.iter (self#scan_type_recfield t) l
+ | Odoc_type.Type_open -> ()
+
+ method scan_extension_constructor (e : Odoc_extension.t_extension_constructor) = ()
+ method scan_exception (e : Odoc_exception.t_exception) = ()
+ method scan_attribute (a : Odoc_value.t_attribute) = ()
+ method scan_method (m : Odoc_value.t_method) = ()
+ method scan_included_module (im : Odoc_module.included_module) = ()
+
+ (** Scan of a type extension *)
+
+ (** Overide this method to perform controls on the extension's type,
+ private and info. This method is called before scanning the
+ extensions's constructors.
+ @return true if the extension's constructors must be scanned.*)
+ method scan_type_extension_pre (x: Odoc_extension.t_type_extension) = true
+
+ (** This method scans the constructors of the given type extension. *)
+ method scan_type_extension_constructors (x: Odoc_extension.t_type_extension) =
+ List.iter self#scan_extension_constructor (Odoc_extension.extension_constructors x)
+
+ (** Scan of a type extension. Should not be overridden. It calls [scan_type_extension_pre]
+ and if [scan_type_extension_pre] returns [true], then it calls scan_type_extension_constructors.*)
+ method scan_type_extension (x: Odoc_extension.t_type_extension) =
+ if self#scan_type_extension_pre x then self#scan_type_extension_constructors x
+
+
+ (** Scan of a class. *)
+
+ (** Scan of a comment inside a class. *)
+ method scan_class_comment (t : text) = ()
+
+ (** Override this method to perform controls on the class comment
+ and params. This method is called before scanning the class elements.
+ @return true if the class elements must be scanned.*)
+ method scan_class_pre (c : Odoc_class.t_class) = true
+
+ (** This method scan the elements of the given class.
+ A VOIR : scan des classes heritees.*)
+ method scan_class_elements c =
+ List.iter
+ (fun ele ->
+ match ele with
+ Odoc_class.Class_attribute a -> self#scan_attribute a
+ | Odoc_class.Class_method m -> self#scan_method m
+ | Odoc_class.Class_comment t -> self#scan_class_comment t
+ )
+ (Odoc_class.class_elements c)
+
+ (** Scan of a class. Should not be overridden. It calls [scan_class_pre]
+ and if [scan_class_pre] returns [true], then it calls scan_class_elements.*)
+ method scan_class c = if self#scan_class_pre c then self#scan_class_elements c
+
+ (** Scan of a class type. *)
+
+ (** Scan of a comment inside a class type. *)
+ method scan_class_type_comment (t : text) = ()
+
+ (** Override this method to perform controls on the class type comment
+ and form. This method is called before scanning the class type elements.
+ @return true if the class type elements must be scanned.*)
+ method scan_class_type_pre (ct : Odoc_class.t_class_type) = true
+
+ (** This method scan the elements of the given class type.
+ A VOIR : scan des classes heritees.*)
+ method scan_class_type_elements ct =
+ List.iter
+ (fun ele ->
+ match ele with
+ Odoc_class.Class_attribute a -> self#scan_attribute a
+ | Odoc_class.Class_method m -> self#scan_method m
+ | Odoc_class.Class_comment t -> self#scan_class_type_comment t
+ )
+ (Odoc_class.class_type_elements ct)
+
+ (** Scan of a class type. Should not be overridden. It calls [scan_class_type_pre]
+ and if [scan_class_type_pre] returns [true], then it calls scan_class_type_elements.*)
+ method scan_class_type ct = if self#scan_class_type_pre ct then self#scan_class_type_elements ct
+
+ (** Scan of modules. *)
+
+ (** Scan of a comment inside a module. *)
+ method scan_module_comment (t : text) = ()
+
+ (** Override this method to perform controls on the module comment
+ and form. This method is called before scanning the module elements.
+ @return true if the module elements must be scanned.*)
+ method scan_module_pre (m : Odoc_module.t_module) = true
+
+ (** This method scan the elements of the given module. *)
+ method scan_module_elements m =
+ List.iter
+ (fun ele ->
+ match ele with
+ Odoc_module.Element_module m -> self#scan_module m
+ | Odoc_module.Element_module_type mt -> self#scan_module_type mt
+ | Odoc_module.Element_included_module im -> self#scan_included_module im
+ | Odoc_module.Element_class c -> self#scan_class c
+ | Odoc_module.Element_class_type ct -> self#scan_class_type ct
+ | Odoc_module.Element_value v -> self#scan_value v
+ | Odoc_module.Element_type_extension x -> self#scan_type_extension x
+ | Odoc_module.Element_exception e -> self#scan_exception e
+ | Odoc_module.Element_type t -> self#scan_type t
+ | Odoc_module.Element_module_comment t -> self#scan_module_comment t
+ )
+ (Odoc_module.module_elements m)
+
+ (** Scan of a module. Should not be overridden. It calls [scan_module_pre]
+ and if [scan_module_pre] returns [true], then it calls scan_module_elements.*)
+ method scan_module m = if self#scan_module_pre m then self#scan_module_elements m
+
+ (** Scan of module types. *)
+
+ (** Scan of a comment inside a module type. *)
+ method scan_module_type_comment (t : text) = ()
+
+ (** Override this method to perform controls on the module type comment
+ and form. This method is called before scanning the module type elements.
+ @return true if the module type elements must be scanned. *)
+ method scan_module_type_pre (mt : Odoc_module.t_module_type) = true
+
+ (** This method scan the elements of the given module type. *)
+ method scan_module_type_elements mt =
+ List.iter
+ (fun ele ->
+ match ele with
+ Odoc_module.Element_module m -> self#scan_module m
+ | Odoc_module.Element_module_type mt -> self#scan_module_type mt
+ | Odoc_module.Element_included_module im -> self#scan_included_module im
+ | Odoc_module.Element_class c -> self#scan_class c
+ | Odoc_module.Element_class_type ct -> self#scan_class_type ct
+ | Odoc_module.Element_value v -> self#scan_value v
+ | Odoc_module.Element_type_extension x -> self#scan_type_extension x
+ | Odoc_module.Element_exception e -> self#scan_exception e
+ | Odoc_module.Element_type t -> self#scan_type t
+ | Odoc_module.Element_module_comment t -> self#scan_module_comment t
+ )
+ (Odoc_module.module_type_elements mt)
+
+ (** Scan of a module type. Should not be overridden. It calls [scan_module_type_pre]
+ and if [scan_module_type_pre] returns [true], then it calls scan_module_type_elements.*)
+ method scan_module_type mt =
+ if self#scan_module_type_pre mt then self#scan_module_type_elements mt
+
+ (** Main scanning method. *)
+
+ (** Scan a list of modules. *)
+ method scan_module_list l = List.iter self#scan_module l
+ end
diff --git a/ocamldoc/odoc_search.ml b/ocamldoc/odoc_search.ml
new file mode 100644
index 0000000000..763b71602d
--- /dev/null
+++ b/ocamldoc/odoc_search.ml
@@ -0,0 +1,752 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Research of elements through modules. *)
+
+module Name = Odoc_name
+open Odoc_parameter
+open Odoc_value
+open Odoc_type
+open Odoc_extension
+open Odoc_exception
+open Odoc_class
+open Odoc_module
+
+type result_element =
+ Res_module of t_module
+ | Res_module_type of t_module_type
+ | Res_class of t_class
+ | Res_class_type of t_class_type
+ | Res_value of t_value
+ | Res_type of t_type
+ | Res_extension of t_extension_constructor
+ | Res_exception of t_exception
+ | Res_attribute of t_attribute
+ | Res_method of t_method
+ | Res_section of string * Odoc_types.text
+ | Res_recfield of t_type * record_field
+ | Res_const of t_type * variant_constructor
+
+type result = result_element list
+
+module type Predicates =
+ sig
+ type t
+ val p_module : t_module -> t -> bool * bool
+ val p_module_type : t_module_type -> t -> bool * bool
+ val p_class : t_class -> t -> bool * bool
+ val p_class_type : t_class_type -> t -> bool * bool
+ val p_value : t_value -> t -> bool
+ val p_recfield : t_type -> record_field -> t -> bool
+ val p_const : t_type -> variant_constructor -> t -> bool
+ val p_type : t_type -> t -> (bool * bool)
+ val p_extension : t_extension_constructor -> t -> bool
+ val p_exception : t_exception -> t -> bool
+ val p_attribute : t_attribute -> t -> bool
+ val p_method : t_method -> t -> bool
+ val p_section : string -> t -> bool
+ end
+
+module Search =
+ functor (P : Predicates) ->
+ struct
+ let search_section t s v = if P.p_section s v then [Res_section (s,t)] else []
+
+ let rec search_text root t v =
+ List.flatten (List.map (fun e -> search_text_ele root e v) t)
+
+ and search_text_ele root e v =
+ let module T = Odoc_types in
+ match e with
+ | T.Raw _
+ | T.Code _
+ | T.CodePre _
+ | T.Latex _
+ | T.Verbatim _
+ | T.Ref (_, _, _) -> []
+ | T.Bold t
+ | T.Italic t
+ | T.Center t
+ | T.Left t
+ | T.Right t
+ | T.Emphasize t
+ | T.Block t
+ | T.Superscript t
+ | T.Subscript t
+ | T.Custom (_,t)
+ | T.Link (_, t) -> search_text root t v
+ | T.List l
+ | T.Enum l -> List.flatten (List.map (fun t -> search_text root t v) l)
+ | T.Newline
+ | T.Module_list _
+ | T.Index_list -> []
+ | T.Target _ -> []
+ | T.Title (n, l_opt, t) ->
+ (match l_opt with
+ None -> []
+ | Some s -> search_section t (Name.concat root s) v) @
+ (search_text root t v)
+
+ let search_value va v = if P.p_value va v then [Res_value va] else []
+
+ let search_recfield t f v =
+ if P.p_recfield t f v then [Res_recfield (t,f)] else []
+
+ let search_const t f v =
+ if P.p_const t f v then [Res_const (t,f)] else []
+
+ let search_type t v =
+ let (go_deeper, ok) = P.p_type t v in
+ let l =
+ match go_deeper with
+ false -> []
+ | true ->
+ match t.ty_kind with
+ Type_abstract -> []
+ | Type_record l ->
+ List.flatten (List.map (fun rf -> search_recfield t rf v) l)
+ | Type_variant l ->
+ List.flatten (List.map (fun rf -> search_const t rf v) l)
+ | Type_open -> []
+ in
+ if ok then (Res_type t) :: l else l
+
+ let search_extension_constructor xt v =
+ if P.p_extension xt v then [Res_extension xt] else []
+
+ let search_type_extension te v =
+ List.fold_left
+ (fun acc -> fun xt -> acc @ (search_extension_constructor xt v))
+ []
+ (Odoc_extension.extension_constructors te)
+
+ let search_exception e v = if P.p_exception e v then [Res_exception e] else []
+
+ let search_attribute a v = if P.p_attribute a v then [Res_attribute a] else []
+
+ let search_method m v = if P.p_method m v then [Res_method m] else []
+
+ let search_class c v =
+ let (go_deeper, ok) = P.p_class c v in
+ let l =
+ if go_deeper then
+ let res_att =
+ List.fold_left
+ (fun acc -> fun att -> acc @ (search_attribute att v))
+ []
+ (Odoc_class.class_attributes c)
+ in
+ let res_met =
+ List.fold_left
+ (fun acc -> fun m -> acc @ (search_method m v))
+ []
+ (Odoc_class.class_methods c)
+ in
+ let res_sec =
+ List.fold_left
+ (fun acc -> fun t -> acc @ (search_text c.cl_name t v))
+ []
+ (Odoc_class.class_comments c)
+ in
+ let l = res_att @ res_met @ res_sec in
+ l
+ else
+ []
+ in
+ if ok then
+ (Res_class c) :: l
+ else
+ l
+
+ let search_class_type ct v =
+ let (go_deeper, ok) = P.p_class_type ct v in
+ let l =
+ if go_deeper then
+ let res_att =
+ List.fold_left
+ (fun acc -> fun att -> acc @ (search_attribute att v))
+ []
+ (Odoc_class.class_type_attributes ct)
+ in
+ let res_met =
+ List.fold_left
+ (fun acc -> fun m -> acc @ (search_method m v))
+ []
+ (Odoc_class.class_type_methods ct)
+ in
+ let res_sec =
+ List.fold_left
+ (fun acc -> fun t -> acc @ (search_text ct.clt_name t v))
+ []
+ (Odoc_class.class_type_comments ct)
+ in
+ let l = res_att @ res_met @ res_sec in
+ l
+ else
+ []
+ in
+ if ok then
+ (Res_class_type ct) :: l
+ else
+ l
+
+ let rec search_module_type mt v =
+ let (go_deeper, ok) = P.p_module_type mt v in
+ let l =
+ if go_deeper then
+ let res_val =
+ List.fold_left
+ (fun acc -> fun va -> acc @ (search_value va v))
+ []
+ (Odoc_module.module_type_values mt)
+ in
+ let res_typ =
+ List.fold_left
+ (fun acc -> fun t -> acc @ (search_type t v))
+ []
+ (Odoc_module.module_type_types mt)
+ in
+ let res_ext =
+ List.fold_left
+ (fun acc -> fun te -> acc @ (search_type_extension te v))
+ []
+ (Odoc_module.module_type_type_extensions mt)
+ in
+ let res_exc =
+ List.fold_left
+ (fun acc -> fun e -> acc @ (search_exception e v))
+ []
+ (Odoc_module.module_type_exceptions mt)
+ in
+ let res_mod = search (Odoc_module.module_type_modules mt) v in
+ let res_modtyp =
+ List.fold_left
+ (fun acc -> fun mt -> acc @ (search_module_type mt v))
+ []
+ (Odoc_module.module_type_module_types mt)
+ in
+ let res_cl =
+ List.fold_left
+ (fun acc -> fun cl -> acc @ (search_class cl v))
+ []
+ (Odoc_module.module_type_classes mt)
+ in
+ let res_cltyp =
+ List.fold_left
+ (fun acc -> fun clt -> acc @ (search_class_type clt v))
+ []
+ (Odoc_module.module_type_class_types mt)
+ in
+ let res_sec =
+ List.fold_left
+ (fun acc -> fun t -> acc @ (search_text mt.mt_name t v))
+ []
+ (Odoc_module.module_type_comments mt)
+ in
+ let l = res_val @ res_typ @ res_ext @ res_exc @ res_mod @
+ res_modtyp @ res_cl @ res_cltyp @ res_sec
+ in
+ l
+ else
+ []
+ in
+ if ok then
+ (Res_module_type mt) :: l
+ else
+ l
+
+ and search_module m v =
+ let (go_deeper, ok) = P.p_module m v in
+ let l =
+ if go_deeper then
+ let res_val =
+ List.fold_left
+ (fun acc -> fun va -> acc @ (search_value va v))
+ []
+ (Odoc_module.module_values m)
+ in
+ let res_typ =
+ List.fold_left
+ (fun acc -> fun t -> acc @ (search_type t v))
+ []
+ (Odoc_module.module_types m)
+ in
+ let res_ext =
+ List.fold_left
+ (fun acc -> fun te -> acc @ (search_type_extension te v))
+ []
+ (Odoc_module.module_type_extensions m)
+ in
+ let res_exc =
+ List.fold_left
+ (fun acc -> fun e -> acc @ (search_exception e v))
+ []
+ (Odoc_module.module_exceptions m)
+ in
+ let res_mod = search (Odoc_module.module_modules m) v in
+ let res_modtyp =
+ List.fold_left
+ (fun acc -> fun mt -> acc @ (search_module_type mt v))
+ []
+ (Odoc_module.module_module_types m)
+ in
+ let res_cl =
+ List.fold_left
+ (fun acc -> fun cl -> acc @ (search_class cl v))
+ []
+ (Odoc_module.module_classes m)
+ in
+ let res_cltyp =
+ List.fold_left
+ (fun acc -> fun clt -> acc @ (search_class_type clt v))
+ []
+ (Odoc_module.module_class_types m)
+ in
+ let res_sec =
+ List.fold_left
+ (fun acc -> fun t -> acc @ (search_text m.m_name t v))
+ []
+ (Odoc_module.module_comments m)
+ in
+ let l = res_val @ res_typ @ res_ext @ res_exc @ res_mod @
+ res_modtyp @ res_cl @ res_cltyp @ res_sec
+ in
+ l
+ else
+ []
+ in
+ if ok then
+ (Res_module m) :: l
+ else
+ l
+
+ and search module_list v =
+ List.fold_left
+ (fun acc -> fun m ->
+ List.fold_left
+ (fun acc2 -> fun ele ->
+ if List.mem ele acc2 then acc2 else acc2 @ [ele]
+ )
+ acc
+ (search_module m v)
+ )
+ []
+ module_list
+ end
+
+module P_name =
+ struct
+ type t = Str.regexp
+ let (=~) name regexp = Str.string_match regexp name 0
+ let p_module m r = (true, m.m_name =~ r)
+ let p_module_type mt r = (true, mt.mt_name =~ r)
+ let p_class c r = (true, c.cl_name =~ r)
+ let p_class_type ct r = (true, ct.clt_name =~ r)
+ let p_value v r = v.val_name =~ r
+ let p_recfield t f r =
+ let name = Printf.sprintf "%s.%s" t.ty_name f.rf_name in
+ name =~ r
+ let p_const t f r =
+ let name = Printf.sprintf "%s.%s" t.ty_name f.vc_name in
+ name =~ r
+ let p_type t r = (true, t.ty_name =~ r)
+ let p_extension x r = x.xt_name =~ r
+ let p_exception e r = e.ex_name =~ r
+ let p_attribute a r = a.att_value.val_name =~ r
+ let p_method m r = m.met_value.val_name =~ r
+ let p_section s r = s =~ r
+ end
+
+module Search_by_name = Search ( P_name )
+
+module P_values =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (false, false)
+ let p_class_type _ _ = (false, false)
+ let p_value _ _ = true
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = false
+ let p_exception _ _ = false
+ let p_attribute _ _ = false
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_values = Search ( P_values )
+let values l =
+ let l_ele = Search_values.search l () in
+ let p v1 v2 = v1.val_name = v2.val_name in
+ let rec iter acc = function
+ (Res_value v) :: q -> if List.exists (p v) acc then iter acc q else iter (v :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_extensions =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (false, false)
+ let p_class_type _ _ = (false, false)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = true
+ let p_exception _ _ = false
+ let p_attribute _ _ = false
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_extensions = Search ( P_extensions )
+let extensions l =
+ let l_ele = Search_extensions.search l () in
+ let p x1 x2 = x1.xt_name = x2.xt_name in
+ let rec iter acc = function
+ (Res_extension x) :: q -> if List.exists (p x) acc then iter acc q else iter (x :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_exceptions =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (false, false)
+ let p_class_type _ _ = (false, false)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = false
+ let p_exception _ _ = true
+ let p_attribute _ _ = false
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_exceptions = Search ( P_exceptions )
+let exceptions l =
+ let l_ele = Search_exceptions.search l () in
+ let p e1 e2 = e1.ex_name = e2.ex_name in
+ let rec iter acc = function
+ (Res_exception t) :: q -> if List.exists (p t) acc then iter acc q else iter (t :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_types =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (false, false)
+ let p_class_type _ _ = (false, false)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, true)
+ let p_extension _ _ = false
+ let p_exception _ _ = false
+ let p_attribute _ _ = false
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_types = Search ( P_types )
+let types l =
+ let l_ele = Search_types.search l () in
+ let p t1 t2 = t1.ty_name = t2.ty_name in
+ let rec iter acc = function
+ (Res_type t) :: q -> if List.exists (p t) acc then iter acc q else iter (t :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_attributes =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (true, false)
+ let p_class_type _ _ = (true, false)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = false
+ let p_exception _ _ = false
+ let p_attribute _ _ = true
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_attributes = Search ( P_attributes )
+let attributes l =
+ let l_ele = Search_attributes.search l () in
+ let p a1 a2 = a1.att_value.val_name = a2.att_value.val_name in
+ let rec iter acc = function
+ (Res_attribute t) :: q -> if List.exists (p t) acc then iter acc q else iter (t :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_methods =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (true, false)
+ let p_class_type _ _ = (true, false)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = false
+ let p_exception _ _ = false
+ let p_attribute _ _ = false
+ let p_method _ _ = true
+ let p_section _ _ = true
+ end
+module Search_methods = Search ( P_methods )
+let methods l =
+ let l_ele = Search_methods.search l () in
+ let p m1 m2 = m1.met_value.val_name = m2.met_value.val_name in
+ let rec iter acc = function
+ (Res_method t) :: q -> if List.exists (p t) acc then iter acc q else iter (t :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_classes =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (false, true)
+ let p_class_type _ _ = (false, false)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = false
+ let p_exception _ _ = false
+ let p_attribute _ _ = false
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_classes = Search ( P_classes )
+let classes l =
+ let l_ele = Search_classes.search l () in
+ let p c1 c2 = c1.cl_name = c2.cl_name in
+ let rec iter acc = function
+ (Res_class c) :: q -> if List.exists (p c) acc then iter acc q else iter (c :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_class_types =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (false, false)
+ let p_class_type _ _ = (false, true)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = false
+ let p_exception _ _ = false
+ let p_attribute _ _ = false
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_class_types = Search ( P_class_types )
+let class_types l =
+ let l_ele = Search_class_types.search l () in
+ let p c1 c2 = c1.clt_name = c2.clt_name in
+ let rec iter acc = function
+ (Res_class_type c) :: q -> if List.exists (p c) acc then iter acc q else iter (c :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_modules =
+ struct
+ type t = unit
+ let p_module _ _ = (true, true)
+ let p_module_type _ _ = (true, false)
+ let p_class _ _ = (false, false)
+ let p_class_type _ _ = (false, false)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = false
+ let p_exception _ _ = false
+ let p_attribute _ _ = false
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_modules = Search ( P_modules )
+let modules l =
+ let l_ele = Search_modules.search l () in
+ let p m1 m2 = m1.m_name = m2.m_name in
+ let rec iter acc = function
+ (Res_module m) :: q -> if List.exists (p m) acc then iter acc q else iter (m :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+module P_module_types =
+ struct
+ type t = unit
+ let p_module _ _ = (true, false)
+ let p_module_type _ _ = (true, true)
+ let p_class _ _ = (false, false)
+ let p_class_type _ _ = (false, false)
+ let p_value _ _ = false
+ let p_recfield _ _ _ = false
+ let p_const _ _ _ = false
+ let p_type _ _ = (false, false)
+ let p_extension _ _ = false
+ let p_exception _ _ = false
+ let p_attribute _ _ = false
+ let p_method _ _ = false
+ let p_section _ _ = false
+ end
+module Search_module_types = Search ( P_module_types )
+let module_types l =
+ let l_ele = Search_module_types.search l () in
+ let p m1 m2 = m1.mt_name = m2.mt_name in
+ let rec iter acc = function
+ (Res_module_type m) :: q -> if List.exists (p m) acc then iter acc q else iter (m :: acc) q
+ | _ :: q -> iter acc q
+ | [] -> acc
+ in
+ iter [] l_ele
+
+let type_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_type _ -> true
+ | _ -> false
+ )
+ l
+
+let value_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_value _ -> true
+ | _ -> false
+ )
+ l
+
+let class_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_class _ -> true
+ | _ -> false
+ )
+ l
+
+let class_type_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_class_type _ -> true
+ | _ -> false
+ )
+ l
+
+let module_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_module _ -> true
+ | _ -> false
+ )
+ l
+
+let module_type_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_module_type _ -> true
+ | _ -> false
+ )
+ l
+
+let extension_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_extension _ -> true
+ | _ -> false
+ )
+ l
+
+let exception_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_exception _ -> true
+ | _ -> false
+ )
+ l
+
+let attribute_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_attribute _ -> true
+ | _ -> false
+ )
+ l
+
+let method_exists mods regexp =
+ let l = Search_by_name.search mods regexp in
+ List.exists
+ (function
+ Res_method _ -> true
+ | _ -> false
+ )
+ l
+
+let find_section mods regexp =
+ let l = Search_by_name.search mods regexp in
+ match
+ List.find
+ (function
+ Res_section _ -> true
+ | _ -> false
+ )
+ l
+ with
+ Res_section (_,t) -> t
+ | _ -> assert false
diff --git a/ocamldoc/odoc_search.mli b/ocamldoc/odoc_search.mli
new file mode 100644
index 0000000000..e0d9f2c27a
--- /dev/null
+++ b/ocamldoc/odoc_search.mli
@@ -0,0 +1,239 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Research of elements through modules. *)
+
+(** The type for an element of the result of a research. *)
+type result_element =
+ Res_module of Odoc_module.t_module
+ | Res_module_type of Odoc_module.t_module_type
+ | Res_class of Odoc_class.t_class
+ | Res_class_type of Odoc_class.t_class_type
+ | Res_value of Odoc_value.t_value
+ | Res_type of Odoc_type.t_type
+ | Res_extension of Odoc_extension.t_extension_constructor
+ | Res_exception of Odoc_exception.t_exception
+ | Res_attribute of Odoc_value.t_attribute
+ | Res_method of Odoc_value.t_method
+ | Res_section of string * Odoc_types.text
+ | Res_recfield of Odoc_type.t_type * Odoc_type.record_field
+ | Res_const of Odoc_type.t_type * Odoc_type.variant_constructor
+
+(** The type representing a research result.*)
+type result = result_element list
+
+(** The type of modules which contain the predicates used during the research.
+ Some functions return a couple of booleans ; the first indicates if we
+ must go deeper in the analysed element, the second if the element satisfies
+ the predicate.
+*)
+module type Predicates =
+ sig
+ type t
+ val p_module : Odoc_module.t_module -> t -> bool * bool
+ val p_module_type : Odoc_module.t_module_type -> t -> bool * bool
+ val p_class : Odoc_class.t_class -> t -> bool * bool
+ val p_class_type : Odoc_class.t_class_type -> t -> bool * bool
+ val p_value : Odoc_value.t_value -> t -> bool
+ val p_recfield : Odoc_type.t_type -> Odoc_type.record_field -> t -> bool
+ val p_const : Odoc_type.t_type -> Odoc_type.variant_constructor -> t -> bool
+ val p_type : Odoc_type.t_type -> t -> (bool * bool)
+ val p_extension :
+ Odoc_extension.t_extension_constructor -> t -> bool
+ val p_exception : Odoc_exception.t_exception -> t -> bool
+ val p_attribute : Odoc_value.t_attribute -> t -> bool
+ val p_method : Odoc_value.t_method -> t -> bool
+ val p_section : string -> t -> bool
+ end
+
+(** Search for elements verifying the predicates in the module in parameter.*)
+module Search :
+ functor (P : Predicates) ->
+ sig
+ (** search in a section title *)
+ val search_section : Odoc_types.text -> string -> P.t -> result_element list
+
+ (** search in a value *)
+ val search_value : Odoc_value.t_value -> P.t -> result_element list
+
+ (** search in a record field *)
+ val search_recfield :
+ Odoc_type.t_type -> Odoc_type.record_field -> P.t -> result_element list
+
+ (** search in a variant constructor *)
+ val search_const :
+ Odoc_type.t_type -> Odoc_type.variant_constructor -> P.t -> result_element list
+
+ (** search in a type *)
+ val search_type : Odoc_type.t_type -> P.t -> result_element list
+
+ (** search in an extension constructor *)
+ val search_extension_constructor :
+ Odoc_extension.t_extension_constructor -> P.t -> result_element list
+
+ (** search in a type extension *)
+ val search_type_extension :
+ Odoc_extension.t_type_extension -> P.t -> result_element list
+
+ (** search in an exception *)
+ val search_exception :
+ Odoc_exception.t_exception -> P.t -> result_element list
+
+ (** search in an attribute *)
+ val search_attribute :
+ Odoc_value.t_attribute -> P.t -> result_element list
+
+ (** search in a method *)
+ val search_method : Odoc_value.t_method -> P.t -> result_element list
+
+ (** search in a class *)
+ val search_class : Odoc_class.t_class -> P.t -> result_element list
+
+ (** search in a class type *)
+ val search_class_type :
+ Odoc_class.t_class_type -> P.t -> result_element list
+
+ (** search in a module type *)
+ val search_module_type :
+ Odoc_module.t_module_type -> P.t -> result_element list
+
+ (** search in a module *)
+ val search_module : Odoc_module.t_module -> P.t -> result_element list
+
+ (** search in a list of modules *)
+ val search : Odoc_module.t_module list -> P.t -> result_element list
+ end
+
+(** A module of predicates to search elements by name (and accepting regexps).*)
+module P_name :
+ sig
+ type t = Str.regexp
+ val ( =~ ) : string -> Str.regexp -> bool
+ val p_module : Odoc_module.t_module -> Str.regexp -> bool * bool
+ val p_module_type :
+ Odoc_module.t_module_type -> Str.regexp -> bool * bool
+ val p_class : Odoc_class.t_class -> Str.regexp -> bool * bool
+ val p_class_type : Odoc_class.t_class_type -> Str.regexp -> bool * bool
+ val p_value : Odoc_value.t_value -> Str.regexp -> bool
+ val p_recfield : Odoc_type.t_type -> Odoc_type.record_field -> Str.regexp -> bool
+ val p_const : Odoc_type.t_type -> Odoc_type.variant_constructor -> Str.regexp -> bool
+ val p_type : Odoc_type.t_type -> Str.regexp -> (bool * bool)
+ val p_extension :
+ Odoc_extension.t_extension_constructor -> Str.regexp -> bool
+ val p_exception : Odoc_exception.t_exception -> Str.regexp -> bool
+ val p_attribute : Odoc_value.t_attribute -> Str.regexp -> bool
+ val p_method : Odoc_value.t_method -> Str.regexp -> bool
+ end
+
+(** A module to search elements by name. *)
+module Search_by_name :
+ sig
+ val search_section : Odoc_types.text -> string -> P_name.t -> result_element list
+ val search_value : Odoc_value.t_value -> P_name.t -> result_element list
+ val search_recfield : Odoc_type.t_type -> Odoc_type.record_field -> P_name.t -> result_element list
+ val search_const : Odoc_type.t_type -> Odoc_type.variant_constructor -> P_name.t -> result_element list
+ val search_type : Odoc_type.t_type -> P_name.t -> result_element list
+ val search_extension_constructor :
+ Odoc_extension.t_extension_constructor -> P_name.t -> result_element list
+ val search_type_extension :
+ Odoc_extension.t_type_extension -> P_name.t -> result_element list
+ val search_exception :
+ Odoc_exception.t_exception -> P_name.t -> result_element list
+ val search_attribute :
+ Odoc_value.t_attribute -> P_name.t -> result_element list
+ val search_method :
+ Odoc_value.t_method -> P_name.t -> result_element list
+ val search_class : Odoc_class.t_class -> P_name.t -> result_element list
+ val search_class_type :
+ Odoc_class.t_class_type -> P_name.t -> result_element list
+ val search_module_type :
+ Odoc_module.t_module_type -> P_name.t -> result_element list
+ val search_module :
+ Odoc_module.t_module -> P_name.t -> result_element list
+ val search : Odoc_module.t_module list -> P_name.t -> result_element list
+ end
+
+(** A function to search all the values in a list of modules. *)
+val values : Odoc_module.t_module list -> Odoc_value.t_value list
+
+(** A function to search all the extension constructors in a list of modules. *)
+val extensions :
+ Odoc_module.t_module list -> Odoc_extension.t_extension_constructor list
+
+(** A function to search all the exceptions in a list of modules. *)
+val exceptions : Odoc_module.t_module list -> Odoc_exception.t_exception list
+
+(** A function to search all the types in a list of modules. *)
+val types : Odoc_module.t_module list -> Odoc_type.t_type list
+
+(** A function to search all the class attributes in a list of modules. *)
+val attributes : Odoc_module.t_module list -> Odoc_value.t_attribute list
+
+(** A function to search all the class methods in a list of modules. *)
+val methods : Odoc_module.t_module list -> Odoc_value.t_method list
+
+(** A function to search all the classes in a list of modules. *)
+val classes : Odoc_module.t_module list -> Odoc_class.t_class list
+
+(** A function to search all the class types in a list of modules. *)
+val class_types : Odoc_module.t_module list -> Odoc_class.t_class_type list
+
+(** A function to search all the modules in a list of modules. *)
+val modules : Odoc_module.t_module list -> Odoc_module.t_module list
+
+(** A function to search all the module types in a list of modules. *)
+val module_types : Odoc_module.t_module list -> Odoc_module.t_module_type list
+
+(** Return [true] if a type with the given complete name (regexp) exists
+ in the given module list.*)
+val type_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if a value with the given complete name (regexp) exists
+ in the given module list.*)
+val value_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if a module with the given complete name (regexp) exists
+ in the given module list.*)
+val module_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if a module type with the given complete name (regexp) exists
+ in the given module list.*)
+val module_type_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if a class with the given complete name (regexp) exists
+ in the given module list.*)
+val class_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if a class type with the given complete name (regexp) exists
+ in the given module list.*)
+val class_type_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if an extension with the given complete name (regexp) exists
+ in the given module list.*)
+val extension_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if a exception with the given complete name (regexp) exists
+ in the given module list.*)
+val exception_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if an attribute with the given complete name (regexp) exists
+ in the given module list.*)
+val attribute_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return [true] if a method with the given complete name (regexp) exists
+ in the given module list.*)
+val method_exists : Odoc_module.t_module list -> Str.regexp -> bool
+
+(** Return the [text] of the section with the given complete name (regexp)
+ in the given module list.
+ @raise Not_found if the section was not found.*)
+val find_section : Odoc_module.t_module list -> Str.regexp -> Odoc_types.text
diff --git a/ocamldoc/odoc_see_lexer.mll b/ocamldoc/odoc_see_lexer.mll
new file mode 100644
index 0000000000..59ffc93712
--- /dev/null
+++ b/ocamldoc/odoc_see_lexer.mll
@@ -0,0 +1,100 @@
+{
+(***********************************************************************)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let print_DEBUG2 s = print_string s ; print_newline ()
+
+(** the lexer for special comments. *)
+
+open Lexing
+open Odoc_parser
+
+let buf = Buffer.create 32
+
+}
+
+rule main = parse
+ [' ' '\013' '\009' '\012'] +
+ {
+ print_DEBUG2 "[' ' '\013' '\009' '\012'] +";
+ main lexbuf
+ }
+
+ | [ '\010' ]
+ {
+ print_DEBUG2 " [ '\010' ] ";
+ main lexbuf
+ }
+
+ | "<"
+ {
+ print_DEBUG2 "call url lexbuf" ;
+ url lexbuf
+ }
+
+ | "\""
+ {
+ print_DEBUG2 "call doc lexbuf" ;
+ doc lexbuf
+ }
+
+
+ | '\''
+ {
+ print_DEBUG2 "call file lexbuf" ;
+ file lexbuf
+ }
+
+ | eof
+ {
+ print_DEBUG2 "EOF";
+ EOF
+ }
+
+ | _
+ {
+ Buffer.reset buf ;
+ Buffer.add_string buf (Lexing.lexeme lexbuf);
+ desc lexbuf
+ }
+
+and url = parse
+ | ([^'>'] | '\n')+">"
+ {
+ let s = Lexing.lexeme lexbuf in
+ print_DEBUG2 ("([^'>'] | '\n')+ \">\" with "^s) ;
+ See_url (String.sub s 0 ((String.length s) -1))
+ }
+
+
+and doc = parse
+ | ([^'"'] | '\n' | "\\'")* "\""
+ {
+ let s = Lexing.lexeme lexbuf in
+ See_doc (String.sub s 0 ((String.length s) -1))
+ }
+
+and file = parse
+ | ([^'\''] | '\n' | "\\\"")* "'"
+ {
+ let s = Lexing.lexeme lexbuf in
+ See_file (String.sub s 0 ((String.length s) -1))
+ }
+
+
+and desc = parse
+ eof
+ { Desc (Buffer.contents buf) }
+ | _
+ {
+ Buffer.add_string buf (Lexing.lexeme lexbuf);
+ desc lexbuf
+ }
diff --git a/ocamldoc/odoc_sig.ml b/ocamldoc/odoc_sig.ml
new file mode 100644
index 0000000000..8a77d48509
--- /dev/null
+++ b/ocamldoc/odoc_sig.ml
@@ -0,0 +1,1562 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Analysis of interface files. *)
+
+open Misc
+open Asttypes
+open Types
+open Typedtree
+open Path
+
+let print_DEBUG s = print_string s ; print_newline ();;
+
+module Name = Odoc_name
+open Odoc_parameter
+open Odoc_value
+open Odoc_type
+open Odoc_extension
+open Odoc_exception
+open Odoc_class
+open Odoc_module
+open Odoc_types
+
+module Signature_search =
+ struct
+ type ele =
+ | M of string
+ | MT of string
+ | V of string
+ | T of string
+ | C of string
+ | CT of string
+ | X of string
+ | P of string
+
+ type tab = (ele, Types.signature_item) Hashtbl.t
+
+ let add_to_hash table signat =
+ match signat with
+ Types.Sig_value (ident, _) ->
+ Hashtbl.add table (V (Name.from_ident ident)) signat
+ | Types.Sig_typext (ident, _, _) ->
+ Hashtbl.add table (X (Name.from_ident ident)) signat
+ | Types.Sig_type (ident, _, _) ->
+ Hashtbl.add table (T (Name.from_ident ident)) signat
+ | Types.Sig_class (ident, _, _) ->
+ Hashtbl.add table (C (Name.from_ident ident)) signat
+ | Types.Sig_class_type (ident, _, _) ->
+ Hashtbl.add table (CT (Name.from_ident ident)) signat
+ | Types.Sig_module (ident, _, _) ->
+ Hashtbl.add table (M (Name.from_ident ident)) signat
+ | Types.Sig_modtype (ident,_) ->
+ Hashtbl.add table (MT (Name.from_ident ident)) signat
+
+ let table signat =
+ let t = Hashtbl.create 13 in
+ List.iter (add_to_hash t) signat;
+ t
+
+ let search_value table name =
+ match Hashtbl.find table (V name) with
+ | (Types.Sig_value (_, val_desc)) -> val_desc.Types.val_type
+ | _ -> assert false
+
+ let search_extension table name =
+ match Hashtbl.find table (X name) with
+ | (Types.Sig_typext (_, ext, _)) -> ext
+ | _ -> assert false
+
+ let search_type table name =
+ match Hashtbl.find table (T name) with
+ | (Types.Sig_type (_, type_decl, _)) -> type_decl
+ | _ -> assert false
+
+ let search_class table name =
+ match Hashtbl.find table (C name) with
+ | (Types.Sig_class (_, class_decl, _)) -> class_decl
+ | _ -> assert false
+
+ let search_class_type table name =
+ match Hashtbl.find table (CT name) with
+ | (Types.Sig_class_type (_, cltype_decl, _)) -> cltype_decl
+ | _ -> assert false
+
+ let search_module table name =
+ match Hashtbl.find table (M name) with
+ | (Types.Sig_module (ident, md, _)) -> md.Types.md_type
+ | _ -> assert false
+
+ let search_module_type table name =
+ match Hashtbl.find table (MT name) with
+ | (Types.Sig_modtype (_, {Types.mtd_type = Some module_type})) ->
+ Some module_type
+ | (Types.Sig_modtype (_, {Types.mtd_type = None})) ->
+ None
+ | _ -> assert false
+
+ let search_attribute_type name class_sig =
+ let (_, _, type_expr) = Types.Vars.find name class_sig.Types.csig_vars in
+ type_expr
+
+ let search_method_type name class_sig =
+ let fields = Odoc_misc.get_fields class_sig.Types.csig_self in
+ List.assoc name fields
+ end
+
+module type Info_retriever =
+ sig
+ val all_special : string -> string -> int * (Odoc_types.info list)
+ val blank_line_outside_simple : string -> string -> bool
+ val just_after_special : string -> string -> (int * Odoc_types.info option)
+ val first_special : string -> string -> (int * Odoc_types.info option)
+ val get_comments :
+ (Odoc_types.text -> 'a) -> string -> string -> (Odoc_types.info option * 'a list)
+ end
+
+module Analyser =
+ functor (My_ir : Info_retriever) ->
+ struct
+ (** This variable is used to load a file as a string and retrieve characters from it.*)
+ let file = ref ""
+ (** The name of the analysed file. *)
+ let file_name = ref ""
+
+ (** This function takes two indexes (start and end) and return the string
+ corresponding to the indexes in the file global variable. The function
+ prepare_file must have been called to fill the file global variable.*)
+ let get_string_of_file the_start the_end =
+ try
+ let s = String.sub !file the_start (the_end-the_start) in
+ s
+ with
+ Invalid_argument _ ->
+ ""
+
+ (** This function loads the given file in the file global variable,
+ and sets file_name.*)
+ let prepare_file f input_f =
+ try
+ let s = Odoc_misc.input_file_as_string input_f in
+ file := s;
+ file_name := f
+ with
+ e ->
+ file := "";
+ raise e
+
+ (** The function used to get the comments in a class. *)
+ let get_comments_in_class pos_start pos_end =
+ My_ir.get_comments (fun t -> Class_comment t)
+ !file_name
+ (get_string_of_file pos_start pos_end)
+
+ (** The function used to get the comments in a module. *)
+ let get_comments_in_module pos_start pos_end =
+ My_ir.get_comments (fun t -> Element_module_comment t)
+ !file_name
+ (get_string_of_file pos_start pos_end)
+
+ let merge_infos = Odoc_merge.merge_info_opt Odoc_types.all_merge_options
+
+ let name_comment_from_type_decl pos_end pos_limit ty_decl =
+ match ty_decl.Parsetree.ptype_kind with
+ | Parsetree.Ptype_abstract ->
+ let open Parsetree in
+ begin match ty_decl.ptype_manifest with
+ | None -> (0, [])
+ | Some core_ty ->
+ begin match core_ty.ptyp_desc with
+ | Ptyp_object (fields, _) ->
+ let rec f = function
+ | [] -> []
+ | ("",_,_) :: _ ->
+ (* Fields with no name have been eliminated previously. *)
+ assert false
+
+ | (name, _atts, ct) :: [] ->
+ let pos = ct.Parsetree.ptyp_loc.Location.loc_end.Lexing.pos_cnum in
+ let s = get_string_of_file pos pos_end in
+ let (_,comment_opt) = My_ir.just_after_special !file_name s in
+ [name, comment_opt]
+ | (name, _atts, ct) :: ((name2, _atts2, ct2) as ele2) :: q ->
+ let pos = ct.Parsetree.ptyp_loc.Location.loc_end.Lexing.pos_cnum in
+ let pos2 = ct2.Parsetree.ptyp_loc.Location.loc_start.Lexing.pos_cnum in
+ let s = get_string_of_file pos pos2 in
+ let (_,comment_opt) = My_ir.just_after_special !file_name s in
+ (name, comment_opt) :: (f (ele2 :: q))
+ in
+ let is_named_field field =
+ match field with
+ | ("",_,_) -> false
+ | _ -> true
+ in
+ (0, f @@ List.filter is_named_field fields)
+
+ | _ -> (0, [])
+ end
+ end
+
+ | Parsetree.Ptype_variant cons_core_type_list_list ->
+ let rec f acc cons_core_type_list_list =
+ let open Parsetree in
+ match cons_core_type_list_list with
+ [] ->
+ (0, acc)
+ | pcd :: [] ->
+ let s = get_string_of_file
+ pcd.pcd_loc.Location.loc_end.Lexing.pos_cnum
+ pos_limit
+ in
+ let (len, comment_opt) = My_ir.just_after_special !file_name s in
+ (len, acc @ [ (pcd.pcd_name.txt, comment_opt) ])
+ | pcd :: (pcd2 :: _ as q) ->
+ (* TODO: support annotations on fields for inline records *)
+ let pos_end_first = pcd.pcd_loc.Location.loc_end.Lexing.pos_cnum in
+ let pos_start_second = pcd2.pcd_loc.Location.loc_start.Lexing.pos_cnum in
+ let s = get_string_of_file pos_end_first pos_start_second in
+ let (_,comment_opt) = My_ir.just_after_special !file_name s in
+ f (acc @ [pcd.pcd_name.txt, comment_opt]) q
+ in
+ f [] cons_core_type_list_list
+
+ | Parsetree.Ptype_record name_mutable_type_list (* of (string * mutable_flag * core_type) list*) ->
+ let open Parsetree in
+ let rec f = function
+ [] ->
+ []
+ | {pld_name=name; pld_type=ct} :: [] ->
+ let pos = ct.Parsetree.ptyp_loc.Location.loc_end.Lexing.pos_cnum in
+ let s = get_string_of_file pos pos_end in
+ let (_,comment_opt) = My_ir.just_after_special !file_name s in
+ [name.txt, comment_opt]
+ | {pld_name=name; pld_type=ct} :: ({pld_name=name2; pld_type=ct2} as ele2) :: q ->
+ let pos = ct.Parsetree.ptyp_loc.Location.loc_end.Lexing.pos_cnum in
+ let pos2 = ct2.Parsetree.ptyp_loc.Location.loc_start.Lexing.pos_cnum in
+ let s = get_string_of_file pos pos2 in
+ let (_,comment_opt) = My_ir.just_after_special !file_name s in
+ (name.txt, comment_opt) :: (f (ele2 :: q))
+ in
+ (0, f name_mutable_type_list)
+ | Parsetree.Ptype_open ->
+ (0, [])
+
+
+ let manifest_structure env name_comment_list type_expr =
+ match type_expr.desc with
+ | Tobject (fields, _) ->
+ let f (field_name, _, type_expr) =
+ let comment_opt =
+ try List.assoc field_name name_comment_list
+ with Not_found -> None
+ in {
+ of_name = field_name ;
+ of_type = Odoc_env.subst_type env type_expr ;
+ of_text = comment_opt ;
+ }
+ in
+ Object_type (List.map f @@ fst @@ Ctype.flatten_fields fields)
+ | _ -> Other (Odoc_env.subst_type env type_expr)
+
+ let get_field env name_comment_list {Types.ld_id=field_name;ld_mutable=mutable_flag;ld_type=type_expr} =
+ let field_name = Ident.name field_name in
+ let comment_opt =
+ try List.assoc field_name name_comment_list
+ with Not_found -> None
+ in
+ {
+ rf_name = field_name ;
+ rf_mutable = mutable_flag = Mutable ;
+ rf_type = Odoc_env.subst_type env type_expr ;
+ rf_text = comment_opt
+ }
+
+ let get_type_kind env name_comment_list type_kind =
+ match type_kind with
+ Types.Type_abstract ->
+ Odoc_type.Type_abstract
+ | Types.Type_variant l ->
+ let f {Types.cd_id=constructor_name;cd_args;cd_res=ret_type} =
+ let constructor_name = Ident.name constructor_name in
+ let comment_opt =
+ try List.assoc constructor_name name_comment_list
+ with Not_found -> None
+ in
+ let vc_args =
+ match cd_args with
+ | Cstr_tuple l -> Cstr_tuple (List.map (Odoc_env.subst_type env) l)
+ | Cstr_record l -> Cstr_record (List.map (get_field env []) l)
+ in
+ {
+ vc_name = constructor_name ;
+ vc_args;
+ vc_ret = may_map (Odoc_env.subst_type env) ret_type;
+ vc_text = comment_opt
+ }
+ in
+ Odoc_type.Type_variant (List.map f l)
+
+ | Types.Type_record (l, _) ->
+ Odoc_type.Type_record (List.map (get_field env name_comment_list) l)
+
+ | Types.Type_open ->
+ Odoc_type.Type_open
+
+
+ let erased_names_of_constraints constraints acc =
+ List.fold_right (fun constraint_ acc ->
+ match constraint_ with
+ | Parsetree.Pwith_type _ | Parsetree.Pwith_module _ -> acc
+ | Parsetree.Pwith_typesubst {Parsetree.ptype_name=s}
+ | Parsetree.Pwith_modsubst (s, _) ->
+ Name.Set.add s.txt acc)
+ constraints acc
+
+ let filter_out_erased_items_from_signature erased signature =
+ if Name.Set.is_empty erased then signature
+ else List.fold_right (fun sig_item acc ->
+ let take_item psig_desc = { sig_item with Parsetree.psig_desc } :: acc in
+ match sig_item.Parsetree.psig_desc with
+ | Parsetree.Psig_attribute _
+ | Parsetree.Psig_extension _
+ | Parsetree.Psig_value _
+ | Parsetree.Psig_typext _
+ | Parsetree.Psig_exception _
+ | Parsetree.Psig_open _
+ | Parsetree.Psig_include _
+ | Parsetree.Psig_class _
+ | Parsetree.Psig_class_type _ as tp -> take_item tp
+ | Parsetree.Psig_type (rf, types) ->
+ (match List.filter (fun td -> not (Name.Set.mem td.Parsetree.ptype_name.txt erased)) types with
+ | [] -> acc
+ | types -> take_item (Parsetree.Psig_type (rf, types)))
+ | Parsetree.Psig_module {Parsetree.pmd_name=name}
+ | Parsetree.Psig_modtype {Parsetree.pmtd_name=name} as m ->
+ if Name.Set.mem name.txt erased then acc else take_item m
+ | Parsetree.Psig_recmodule mods ->
+ (match List.filter (fun pmd -> not (Name.Set.mem pmd.Parsetree.pmd_name.txt erased)) mods with
+ | [] -> acc
+ | mods -> take_item (Parsetree.Psig_recmodule mods)))
+ signature []
+
+ (** Analysis of the elements of a class, from the information in the parsetree and in the class
+ signature. @return the couple (inherited_class list, elements).*)
+ let analyse_class_elements env current_class_name last_pos pos_limit
+ class_type_field_list class_signature =
+ let get_pos_limit2 q =
+ match q with
+ [] -> pos_limit
+ | ele2 :: _ ->
+ let loc = ele2.Parsetree.pctf_loc in
+ match ele2.Parsetree.pctf_desc with
+ Parsetree.Pctf_val (_, _, _, _)
+ | Parsetree.Pctf_method (_, _, _, _)
+ | Parsetree.Pctf_constraint (_, _)
+ | Parsetree.Pctf_attribute _ -> loc.Location.loc_start.Lexing.pos_cnum
+ | Parsetree.Pctf_inherit class_type ->
+ class_type.Parsetree.pcty_loc.Location.loc_start.Lexing.pos_cnum
+ | Parsetree.Pctf_extension _ -> assert false
+ in
+ let get_method name comment_opt private_flag loc q =
+ let complete_name = Name.concat current_class_name name in
+ let typ =
+ try Signature_search.search_method_type name class_signature
+ with Not_found ->
+ raise (Failure (Odoc_messages.method_type_not_found current_class_name name))
+ in
+ let subst_typ = Odoc_env.subst_type env typ in
+ let met =
+ {
+ met_value =
+ {
+ val_name = complete_name ;
+ val_info = comment_opt ;
+ val_type = subst_typ ;
+ val_recursive = false ;
+ val_parameters = Odoc_value.dummy_parameter_list subst_typ ;
+ val_code = None ;
+ val_loc = { loc_impl = None ; loc_inter = Some loc };
+ } ;
+ met_private = private_flag = Asttypes.Private ;
+ met_virtual = false ;
+ }
+ in
+ let pos_limit2 = get_pos_limit2 q in
+ let pos_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end pos_limit2)
+ in
+ met.met_value.val_info <- merge_infos met.met_value.val_info info_after_opt ;
+ (* update the parameter description *)
+ Odoc_value.update_value_parameters_text met.met_value;
+ (met, maybe_more)
+ in
+ let rec f last_pos class_type_field_list =
+ match class_type_field_list with
+ [] ->
+ let s = get_string_of_file last_pos pos_limit in
+ let (_, ele_coms) = My_ir.all_special !file_name s in
+ let ele_comments =
+ List.fold_left
+ (fun acc -> fun sc ->
+ match sc.Odoc_types.i_desc with
+ None ->
+ acc
+ | Some t ->
+ acc @ [Class_comment t])
+ []
+ ele_coms
+ in
+ ([], ele_comments)
+
+ | item :: q ->
+ let loc = item.Parsetree.pctf_loc in
+ match item.Parsetree.pctf_desc with
+
+ | Parsetree.Pctf_val (name, mutable_flag, virtual_flag, _) ->
+ (* of (string * mutable_flag * core_type option * Location.t)*)
+ let (comment_opt, eles_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let complete_name = Name.concat current_class_name name in
+ let typ =
+ try Signature_search.search_attribute_type name class_signature
+ with Not_found ->
+ raise (Failure (Odoc_messages.attribute_type_not_found current_class_name name))
+ in
+ let subst_typ = Odoc_env.subst_type env typ in
+ let att =
+ {
+ att_value =
+ {
+ val_name = complete_name ;
+ val_info = comment_opt ;
+ val_type = subst_typ;
+ val_recursive = false ;
+ val_parameters = [] ;
+ val_code = None ;
+ val_loc = { loc_impl = None ; loc_inter = Some loc} ;
+ } ;
+ att_mutable = mutable_flag = Asttypes.Mutable ;
+ att_virtual = virtual_flag = Asttypes.Virtual ;
+ }
+ in
+ let pos_limit2 = get_pos_limit2 q in
+ let pos_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end pos_limit2)
+ in
+ att.att_value.val_info <- merge_infos att.att_value.val_info info_after_opt ;
+ let (inher_l, eles) = f (pos_end + maybe_more) q in
+ (inher_l, eles_comments @ ((Class_attribute att) :: eles))
+
+ | Parsetree.Pctf_method (name, private_flag, virtual_flag, _) ->
+ (* of (string * private_flag * virtual_flag * core_type) *)
+ let (comment_opt, eles_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let (met, maybe_more) = get_method name comment_opt private_flag loc q in
+ let met2 =
+ match virtual_flag with
+ | Concrete -> met
+ | Virtual -> { met with met_virtual = true }
+ in
+ let (inher_l, eles) = f (loc.Location.loc_end.Lexing.pos_cnum + maybe_more) q in
+ (inher_l, eles_comments @ ((Class_method met2) :: eles))
+
+ | (Parsetree.Pctf_constraint (_, _)) ->
+ (* of (core_type * core_type) *)
+ (* A VOIR : cela correspond aux contraintes, non ? on ne les garde pas pour l'instant *)
+ let (comment_opt, eles_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let (inher_l, eles) = f loc.Location.loc_end.Lexing.pos_cnum q in
+ (inher_l, eles_comments @ eles)
+
+ | Parsetree.Pctf_inherit class_type ->
+ let loc = class_type.Parsetree.pcty_loc in
+ let (comment_opt, eles_comments) =
+ get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let pos_limit2 = get_pos_limit2 q in
+ let pos_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end pos_limit2)
+ in
+ let comment_opt2 = merge_infos comment_opt info_after_opt in
+ let text_opt = match comment_opt2 with None -> None | Some i -> i.Odoc_types.i_desc in
+ let inh =
+ match class_type.Parsetree.pcty_desc with
+ Parsetree.Pcty_constr (longident, _) ->
+ (*of Longident.t * core_type list*)
+ let name = Name.from_longident longident.txt in
+ let ic =
+ {
+ ic_name = Odoc_env.full_class_or_class_type_name env name ;
+ ic_class = None ;
+ ic_text = text_opt ;
+ }
+ in
+ ic
+
+ | Parsetree.Pcty_signature _
+ | Parsetree.Pcty_arrow _ ->
+ (* we don't have a name for the class signature, so we call it "object ... end" *)
+ {
+ ic_name = Odoc_messages.object_end ;
+ ic_class = None ;
+ ic_text = text_opt ;
+ }
+ | Parsetree.Pcty_extension _ -> assert false
+ in
+ let (inher_l, eles) = f (pos_end + maybe_more) q in
+ (inh :: inher_l , eles_comments @ eles)
+ | Parsetree.Pctf_attribute _ ->
+ let (comment_opt, eles_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
+ let (inher_l, eles) = f loc.Location.loc_end.Lexing.pos_cnum q in
+ (inher_l, eles_comments @ eles)
+
+ | Parsetree.Pctf_extension _ -> assert false
+ in
+ f last_pos class_type_field_list
+
+ (** Analyse of a .mli parse tree, to get the corresponding elements.
+ last_pos is the position of the first character which may be used to look for special comments.
+ *)
+ let rec analyse_parsetree env signat current_module_name last_pos pos_limit sig_item_list =
+ let table = Signature_search.table signat in
+ (* we look for the comment of each item then analyse the item *)
+ let rec f acc_eles acc_env last_pos = function
+ [] ->
+ let s = get_string_of_file last_pos pos_limit in
+ let (_, ele_coms) = My_ir.all_special !file_name s in
+ let ele_comments =
+ List.fold_left
+ (fun acc -> fun sc ->
+ match sc.Odoc_types.i_desc with
+ None ->
+ acc
+ | Some t ->
+ acc @ [Element_module_comment t])
+ []
+ ele_coms
+ in
+ acc_eles @ ele_comments
+
+ | ele :: q ->
+ let (assoc_com, ele_comments) = get_comments_in_module
+ last_pos
+ ele.Parsetree.psig_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let (maybe_more, new_env, elements) = analyse_signature_item_desc
+ acc_env
+ signat
+ table
+ current_module_name
+ ele.Parsetree.psig_loc
+ ele.Parsetree.psig_loc.Location.loc_start.Lexing.pos_cnum
+ ele.Parsetree.psig_loc.Location.loc_end.Lexing.pos_cnum
+ (match q with
+ [] -> pos_limit
+ | ele2 :: _ -> ele2.Parsetree.psig_loc.Location.loc_start.Lexing.pos_cnum
+ )
+ assoc_com
+ ele.Parsetree.psig_desc
+ in
+ let new_pos =
+ match ele.Parsetree.psig_desc with
+ | Parsetree.Psig_attribute ({Asttypes.txt = "ocaml.text"}, _) -> last_pos
+ (* This "signature item" is actually a doc comment; the item is ignored
+ but don't skip the comment. *)
+ | _ ->
+ (ele.Parsetree.psig_loc.Location.loc_end.Lexing.pos_cnum + maybe_more)
+ (* for the comments of constructors in types,
+ which are after the constructor definition and can
+ go beyond ele.Parsetree.psig_loc.Location.loc_end.Lexing.pos_cnum *)
+ in
+ f (acc_eles @ (ele_comments @ elements))
+ new_env
+ new_pos
+ q
+ in
+ f [] env last_pos sig_item_list
+
+ (** Analyse the given signature_item_desc to create the corresponding module element
+ (with the given attached comment).*)
+ and analyse_signature_item_desc env signat table current_module_name
+ sig_item_loc pos_start_ele pos_end_ele pos_limit comment_opt sig_item_desc =
+ match sig_item_desc with
+ Parsetree.Psig_value value_desc ->
+ let name_pre = value_desc.Parsetree.pval_name in
+ let type_expr =
+ try Signature_search.search_value table name_pre.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.value_not_found current_module_name name_pre.txt))
+ in
+ let name = Name.parens_if_infix name_pre.txt in
+ let subst_typ = Odoc_env.subst_type env type_expr in
+ let v =
+ {
+ val_name = Name.concat current_module_name name ;
+ val_info = comment_opt ;
+ val_type = subst_typ ;
+ val_recursive = false ;
+ val_parameters = Odoc_value.dummy_parameter_list subst_typ ;
+ val_code = None ;
+ val_loc = { loc_impl = None ; loc_inter = Some sig_item_loc } ;
+ }
+ in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end_ele pos_limit)
+ in
+ v.val_info <- merge_infos v.val_info info_after_opt ;
+ (* update the parameter description *)
+ Odoc_value.update_value_parameters_text v;
+
+ let new_env = Odoc_env.add_value env v.val_name in
+ (maybe_more, new_env, [ Element_value v ])
+
+ | Parsetree.Psig_typext tyext ->
+ let new_env, types_ext_list, last_ext =
+ List.fold_left
+ (fun (env_acc, exts_acc, _) -> fun {Parsetree.pext_name = { txt = name }} ->
+ let complete_name = Name.concat current_module_name name in
+ let env_acc = Odoc_env.add_extension env_acc complete_name in
+ let types_ext =
+ try Signature_search.search_extension table name
+ with Not_found ->
+ raise (Failure (Odoc_messages.extension_not_found current_module_name name))
+ in
+ env_acc, ((name, types_ext) :: exts_acc), Some types_ext
+ )
+ (env, [], None)
+ tyext.Parsetree.ptyext_constructors
+ in
+ let ty_path, ty_params, priv =
+ match last_ext with
+ None -> assert false
+ | Some ext -> ext.ext_type_path, ext.ext_type_params, ext.ext_private
+ in
+ let new_te =
+ {
+ te_info = comment_opt;
+ te_type_name =
+ Odoc_env.full_type_name new_env (Name.from_path ty_path);
+ te_type_parameters =
+ List.map (Odoc_env.subst_type new_env) ty_params;
+ te_private = priv;
+ te_constructors = [];
+ te_loc = { loc_impl = None ; loc_inter = Some sig_item_loc} ;
+ te_code =
+ (
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file pos_start_ele pos_end_ele)
+ else
+ None
+ ) ;
+ }
+ in
+ let rec analyse_extension_constructors maybe_more exts_acc types_ext_list =
+ match types_ext_list with
+ [] -> (maybe_more, List.rev exts_acc)
+ | (name, types_ext) :: q ->
+ let ext_loc_end = types_ext.Types.ext_loc.Location.loc_end.Lexing.pos_cnum in
+ let xt_args =
+ match types_ext.ext_args with
+ | Cstr_tuple l -> Cstr_tuple (List.map (Odoc_env.subst_type new_env) l)
+ | Cstr_record l -> Cstr_record (List.map (get_field new_env []) l)
+ in
+ let new_x =
+ {
+ xt_name = Name.concat current_module_name name ;
+ xt_args;
+ xt_ret = may_map (Odoc_env.subst_type new_env) types_ext.ext_ret_type ;
+ xt_type_extension = new_te;
+ xt_alias = None ;
+ xt_loc = { loc_impl = None ; loc_inter = Some types_ext.Types.ext_loc} ;
+ xt_text = None;
+ }
+ in
+ let pos_limit2 =
+ match q with
+ [] -> pos_limit
+ | (_, next) :: _ -> next.Types.ext_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let s = get_string_of_file ext_loc_end pos_limit2 in
+ let (maybe_more, comment_opt) = My_ir.just_after_special !file_name s in
+ new_x.xt_text <- comment_opt;
+ analyse_extension_constructors maybe_more (new_x :: exts_acc) q
+ in
+ let (maybe_more, exts) = analyse_extension_constructors 0 [] types_ext_list in
+ new_te.te_constructors <- exts;
+ let (maybe_more2, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file (pos_end_ele + maybe_more) pos_limit)
+ in
+ new_te.te_info <- merge_infos new_te.te_info info_after_opt ;
+ (maybe_more + maybe_more2, new_env, [ Element_type_extension new_te ])
+
+ | Parsetree.Psig_exception ext ->
+ let name = ext.Parsetree.pext_name in
+ let types_ext =
+ try Signature_search.search_extension table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.exception_not_found current_module_name name.txt))
+ in
+ let ex_args =
+ match types_ext.ext_args with
+ | Cstr_tuple l -> Cstr_tuple (List.map (Odoc_env.subst_type env) l)
+ | Cstr_record l -> Cstr_record (List.map (get_field env []) l)
+ in
+ let e =
+ {
+ ex_name = Name.concat current_module_name name.txt ;
+ ex_info = comment_opt ;
+ ex_args;
+ ex_ret = may_map (Odoc_env.subst_type env) types_ext.ext_ret_type ;
+ ex_alias = None ;
+ ex_loc = { loc_impl = None ; loc_inter = Some sig_item_loc } ;
+ ex_code =
+ (
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file pos_start_ele pos_end_ele)
+ else
+ None
+ ) ;
+ }
+ in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end_ele pos_limit)
+ in
+ e.ex_info <- merge_infos e.ex_info info_after_opt ;
+ let new_env = Odoc_env.add_extension env e.ex_name in
+ (maybe_more, new_env, [ Element_exception e ])
+
+ | Parsetree.Psig_type (rf, name_type_decl_list) ->
+ let extended_env =
+ List.fold_left
+ (fun acc_env td ->
+ let complete_name = Name.concat current_module_name td.Parsetree.ptype_name.txt in
+ Odoc_env.add_type acc_env complete_name
+ )
+ env
+ name_type_decl_list
+ in
+ let env =
+ match rf with
+ | Recursive -> extended_env
+ | Nonrecursive -> env
+ in
+ let rec f ?(first=false) acc_maybe_more last_pos name_type_decl_list =
+ match name_type_decl_list with
+ [] ->
+ (acc_maybe_more, [])
+ | type_decl :: q ->
+ let name = type_decl.Parsetree.ptype_name in
+ let (assoc_com, ele_comments) =
+ if first then
+ (comment_opt, [])
+ else
+ get_comments_in_module
+ last_pos
+ type_decl.Parsetree.ptype_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let pos_limit2 =
+ match q with
+ [] -> pos_limit
+ | td :: _ -> td.Parsetree.ptype_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let (maybe_more, name_comment_list) =
+ name_comment_from_type_decl
+ type_decl.Parsetree.ptype_loc.Location.loc_end.Lexing.pos_cnum
+ pos_limit2
+ type_decl
+ in
+ print_DEBUG ("Type "^name.txt^" : "^(match assoc_com with None -> "sans commentaire" | Some c -> Odoc_misc.string_of_info c));
+ let f_DEBUG (name, c_opt) = print_DEBUG ("constructor/field "^name^": "^(match c_opt with None -> "sans commentaire" | Some c -> Odoc_misc.string_of_info c)) in
+ List.iter f_DEBUG name_comment_list;
+ (* get the information for the type in the signature *)
+ let sig_type_decl =
+ try Signature_search.search_type table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.type_not_found current_module_name name.txt))
+ in
+ (* get the type kind with the associated comments *)
+ let type_kind = get_type_kind env name_comment_list sig_type_decl.Types.type_kind in
+ let loc_start = type_decl.Parsetree.ptype_loc.Location.loc_start.Lexing.pos_cnum in
+ let new_end = type_decl.Parsetree.ptype_loc.Location.loc_end.Lexing.pos_cnum + maybe_more in
+ (* associate the comments to each constructor and build the [Type.t_type] *)
+ let new_type =
+ {
+ ty_name = Name.concat current_module_name name.txt ;
+ ty_info = assoc_com ;
+ ty_parameters =
+ List.map2 (fun p v ->
+ let (co, cn) = Types.Variance.get_upper v in
+ (Odoc_env.subst_type env p,co, cn))
+ sig_type_decl.Types.type_params
+ sig_type_decl.Types.type_variance;
+ ty_kind = type_kind;
+ ty_private = sig_type_decl.Types.type_private;
+ ty_manifest =
+ begin match sig_type_decl.Types.type_manifest with
+ | None -> None
+ | Some t ->
+ Some (manifest_structure env name_comment_list t)
+ end ;
+ ty_loc = { loc_impl = None ; loc_inter = Some sig_item_loc } ;
+ ty_code =
+ (
+ if !Odoc_global.keep_code then
+ Some (get_string_of_file loc_start new_end)
+ else
+ None
+ ) ;
+ }
+ in
+ let (maybe_more2, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file new_end pos_limit2)
+ in
+ new_type.ty_info <- merge_infos new_type.ty_info info_after_opt ;
+ let (new_maybe_more, eles) = f
+ (maybe_more + maybe_more2)
+ (new_end + maybe_more2)
+ q
+ in
+ (new_maybe_more, (ele_comments @ [Element_type new_type]) @ eles)
+ in
+ let (maybe_more, types) = f ~first: true 0 pos_start_ele name_type_decl_list in
+ (maybe_more, extended_env, types)
+
+ | Parsetree.Psig_open _ -> (* A VOIR *)
+ let ele_comments = match comment_opt with
+ None -> []
+ | Some i ->
+ match i.i_desc with
+ None -> []
+ | Some t -> [Element_module_comment t]
+ in
+ (0, env, ele_comments)
+
+ | Parsetree.Psig_module {Parsetree.pmd_name=name; pmd_type=module_type} ->
+ let complete_name = Name.concat current_module_name name.txt in
+ (* get the the module type in the signature by the module name *)
+ let sig_module_type =
+ try Signature_search.search_module table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.module_not_found current_module_name name.txt))
+ in
+ let module_kind = analyse_module_kind env complete_name module_type sig_module_type in
+ let code_intf =
+ if !Odoc_global.keep_code then
+ let loc = module_type.Parsetree.pmty_loc in
+ let st = loc.Location.loc_start.Lexing.pos_cnum in
+ let en = loc.Location.loc_end.Lexing.pos_cnum in
+ Some (get_string_of_file st en)
+ else
+ None
+ in
+ let new_module =
+ {
+ m_name = complete_name ;
+ m_type = sig_module_type;
+ m_info = comment_opt ;
+ m_is_interface = true ;
+ m_file = !file_name ;
+ m_kind = module_kind ;
+ m_loc = { loc_impl = None ; loc_inter = Some sig_item_loc } ;
+ m_top_deps = [] ;
+ m_code = None ;
+ m_code_intf = code_intf ;
+ m_text_only = false ;
+ }
+ in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end_ele pos_limit)
+ in
+ new_module.m_info <- merge_infos new_module.m_info info_after_opt ;
+ let new_env = Odoc_env.add_module env new_module.m_name in
+ let new_env2 =
+ match new_module.m_type with (* A VOIR : cela peut-il etre Tmty_ident ? dans ce cas, on aurait pas la signature *)
+ Types.Mty_signature s -> Odoc_env.add_signature new_env new_module.m_name ~rel: (Name.simple new_module.m_name) s
+ | _ -> new_env
+ in
+ (maybe_more, new_env2, [ Element_module new_module ])
+
+ | Parsetree.Psig_recmodule decls ->
+ (* we start by extending the environment *)
+ let new_env =
+ List.fold_left
+ (fun acc_env {Parsetree.pmd_name={txt=name}} ->
+ let complete_name = Name.concat current_module_name name in
+ let e = Odoc_env.add_module acc_env complete_name in
+ (* get the information for the module in the signature *)
+ let sig_module_type =
+ try Signature_search.search_module table name
+ with Not_found ->
+ raise (Failure (Odoc_messages.module_not_found current_module_name name))
+ in
+ match sig_module_type with
+ (* A VOIR : cela peut-il etre Tmty_ident ? dans ce cas, on aurait pas la signature *)
+ Types.Mty_signature s ->
+ Odoc_env.add_signature e complete_name ~rel: name s
+ | _ ->
+ print_DEBUG "not a Tmty_signature";
+ e
+ )
+ env
+ decls
+ in
+ let rec f ?(first=false) acc_maybe_more last_pos name_mtype_list =
+ match name_mtype_list with
+ [] ->
+ (acc_maybe_more, [])
+ | {Parsetree.pmd_name=name; pmd_type=modtype} :: q ->
+ let complete_name = Name.concat current_module_name name.txt in
+ let loc = modtype.Parsetree.pmty_loc in
+ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let (assoc_com, ele_comments) =
+ if first then
+ (comment_opt, [])
+ else
+ get_comments_in_module
+ last_pos
+ loc_start
+ in
+ let pos_limit2 =
+ match q with
+ [] -> pos_limit
+ | _ :: _ -> loc.Location.loc_start.Lexing.pos_cnum
+ in
+ (* get the information for the module in the signature *)
+ let sig_module_type =
+ try Signature_search.search_module table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.module_not_found current_module_name name.txt))
+ in
+ (* associate the comments to each constructor and build the [Type.t_type] *)
+ let module_kind = analyse_module_kind new_env complete_name modtype sig_module_type in
+ let code_intf =
+ if !Odoc_global.keep_code then
+ let st = loc.Location.loc_start.Lexing.pos_cnum in
+ let en = loc.Location.loc_end.Lexing.pos_cnum in
+ Some (get_string_of_file st en)
+ else
+ None
+ in
+ let new_module =
+ {
+ m_name = complete_name ;
+ m_type = sig_module_type;
+ m_info = assoc_com ;
+ m_is_interface = true ;
+ m_file = !file_name ;
+ m_kind = module_kind ;
+ m_loc = { loc_impl = None ; loc_inter = Some loc } ;
+ m_top_deps = [] ;
+ m_code = None ;
+ m_code_intf = code_intf ;
+ m_text_only = false ;
+ }
+ in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file loc_end pos_limit2)
+ in
+ new_module.m_info <- merge_infos new_module.m_info info_after_opt ;
+
+ let (maybe_more2, eles) = f
+ maybe_more
+ (loc_end + maybe_more)
+ q
+ in
+ (maybe_more2, (ele_comments @ [Element_module new_module]) @ eles)
+ in
+ let (maybe_more, mods) = f ~first: true 0 pos_start_ele decls in
+ (maybe_more, new_env, mods)
+
+ | Parsetree.Psig_modtype {Parsetree.pmtd_name=name; pmtd_type=pmodtype_decl} ->
+ let complete_name = Name.concat current_module_name name.txt in
+ let sig_mtype =
+ try Signature_search.search_module_type table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.module_type_not_found current_module_name name.txt))
+ in
+ let module_type_kind =
+ match pmodtype_decl with
+ None -> None
+ | Some module_type ->
+ match sig_mtype with
+ | Some sig_mtype -> Some (analyse_module_type_kind env complete_name module_type sig_mtype)
+ | None -> None
+ in
+
+ let mt =
+ {
+ mt_name = complete_name ;
+ mt_info = comment_opt ;
+ mt_type = sig_mtype ;
+ mt_is_interface = true ;
+ mt_file = !file_name ;
+ mt_kind = module_type_kind ;
+ mt_loc = { loc_impl = None ; loc_inter = Some sig_item_loc } ;
+ }
+ in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end_ele pos_limit)
+ in
+ mt.mt_info <- merge_infos mt.mt_info info_after_opt ;
+ let new_env = Odoc_env.add_module_type env mt.mt_name in
+ let new_env2 =
+ match sig_mtype with (* A VOIR : cela peut-il etre Tmty_ident ? dans ce cas, on aurait pas la signature *)
+ Some (Types.Mty_signature s) -> Odoc_env.add_signature new_env mt.mt_name ~rel: (Name.simple mt.mt_name) s
+ | _ -> new_env
+ in
+ (maybe_more, new_env2, [ Element_module_type mt ])
+
+ | Parsetree.Psig_include incl ->
+ let rec f = function
+ Parsetree.Pmty_ident longident ->
+ Name.from_longident longident.txt
+ | Parsetree.Pmty_alias longident ->
+ Name.from_longident longident.txt
+ | Parsetree.Pmty_signature _ ->
+ "??"
+ | Parsetree.Pmty_functor _ ->
+ "??"
+ | Parsetree.Pmty_with (mt, _) ->
+ f mt.Parsetree.pmty_desc
+ | Parsetree.Pmty_typeof mexpr ->
+ begin match mexpr.Parsetree.pmod_desc with
+ Parsetree.Pmod_ident longident -> Name.from_longident longident.txt
+ | _ -> "??"
+ end
+ | Parsetree.Pmty_extension _ -> assert false
+ in
+ let name = f incl.Parsetree.pincl_mod.Parsetree.pmty_desc in
+ let full_name = Odoc_env.full_module_or_module_type_name env name in
+ let im =
+ {
+ im_name = full_name ;
+ im_module = None ;
+ im_info = comment_opt;
+ }
+ in
+ (0, env, [ Element_included_module im ]) (* A VOIR : etendre l'environnement ? avec quoi ? *)
+
+ | Parsetree.Psig_class class_description_list ->
+ (* we start by extending the environment *)
+ let new_env =
+ List.fold_left
+ (fun acc_env -> fun class_desc ->
+ let complete_name = Name.concat current_module_name class_desc.Parsetree.pci_name.txt in
+ Odoc_env.add_class acc_env complete_name
+ )
+ env
+ class_description_list
+ in
+ let rec f ?(first=false) acc_maybe_more last_pos class_description_list =
+ match class_description_list with
+ [] ->
+ (acc_maybe_more, [])
+ | class_desc :: q ->
+ let (assoc_com, ele_comments) =
+ if first then
+ (comment_opt, [])
+ else
+ get_comments_in_module
+ last_pos
+ class_desc.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let pos_end = class_desc.Parsetree.pci_loc.Location.loc_end.Lexing.pos_cnum in
+ let pos_limit2 =
+ match q with
+ [] -> pos_limit
+ | cd :: _ -> cd.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let name = class_desc.Parsetree.pci_name in
+ let complete_name = Name.concat current_module_name name.txt in
+ let sig_class_decl =
+ try Signature_search.search_class table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.class_not_found current_module_name name.txt))
+ in
+ let sig_class_type = sig_class_decl.Types.cty_type in
+ let (parameters, class_kind) =
+ analyse_class_kind
+ new_env
+ complete_name
+ class_desc.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ class_desc.Parsetree.pci_expr
+ sig_class_type
+ in
+ let new_class =
+ {
+ cl_name = complete_name ;
+ cl_info = assoc_com ;
+ cl_type = Odoc_env.subst_class_type env sig_class_type ;
+ cl_type_parameters = sig_class_decl.Types.cty_params;
+ cl_virtual = class_desc.Parsetree.pci_virt = Asttypes.Virtual ;
+ cl_kind = class_kind ;
+ cl_parameters = parameters ;
+ cl_loc = { loc_impl = None ; loc_inter = Some class_desc.Parsetree.pci_loc } ;
+ }
+ in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end pos_limit2)
+ in
+ new_class.cl_info <- merge_infos new_class.cl_info info_after_opt ;
+ Odoc_class.class_update_parameters_text new_class ;
+ let (new_maybe_more, eles) =
+ f maybe_more (pos_end + maybe_more) q
+ in
+ (new_maybe_more,
+ ele_comments @ (( Element_class new_class ) :: eles))
+ in
+ let (maybe_more, eles) =
+ f ~first: true 0 pos_start_ele class_description_list
+ in
+ (maybe_more, new_env, eles)
+
+ | Parsetree.Psig_class_type class_type_declaration_list ->
+ (* we start by extending the environment *)
+ let new_env =
+ List.fold_left
+ (fun acc_env -> fun class_type_decl ->
+ let complete_name = Name.concat current_module_name class_type_decl.Parsetree.pci_name.txt in
+ Odoc_env.add_class_type acc_env complete_name
+ )
+ env
+ class_type_declaration_list
+ in
+ let rec f ?(first=false) acc_maybe_more last_pos class_type_description_list =
+ match class_type_description_list with
+ [] ->
+ (acc_maybe_more, [])
+ | ct_decl :: q ->
+ let (assoc_com, ele_comments) =
+ if first then
+ (comment_opt, [])
+ else
+ get_comments_in_module
+ last_pos
+ ct_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let pos_end = ct_decl.Parsetree.pci_loc.Location.loc_end.Lexing.pos_cnum in
+ let pos_limit2 =
+ match q with
+ [] -> pos_limit
+ | ct_decl2 :: _ -> ct_decl2.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ in
+ let name = ct_decl.Parsetree.pci_name in
+ let complete_name = Name.concat current_module_name name.txt in
+ let sig_cltype_decl =
+ try Signature_search.search_class_type table name.txt
+ with Not_found ->
+ raise (Failure (Odoc_messages.class_type_not_found current_module_name name.txt))
+ in
+ let sig_class_type = sig_cltype_decl.Types.clty_type in
+ let kind = analyse_class_type_kind
+ new_env
+ complete_name
+ ct_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
+ ct_decl.Parsetree.pci_expr
+ sig_class_type
+ in
+ let ct =
+ {
+ clt_name = complete_name ;
+ clt_info = assoc_com ;
+ clt_type = Odoc_env.subst_class_type env sig_class_type ;
+ clt_type_parameters = sig_cltype_decl.clty_params ;
+ clt_virtual = ct_decl.Parsetree.pci_virt = Asttypes.Virtual ;
+ clt_kind = kind ;
+ clt_loc = { loc_impl = None ; loc_inter = Some ct_decl.Parsetree.pci_loc } ;
+ }
+ in
+ let (maybe_more, info_after_opt) =
+ My_ir.just_after_special
+ !file_name
+ (get_string_of_file pos_end pos_limit2)
+ in
+ ct.clt_info <- merge_infos ct.clt_info info_after_opt ;
+ let (new_maybe_more, eles) =
+ f maybe_more (pos_end + maybe_more) q
+ in
+ (new_maybe_more,
+ ele_comments @ (( Element_class_type ct) :: eles))
+ in
+ let (maybe_more, eles) =
+ f ~first: true 0 pos_start_ele class_type_declaration_list
+ in
+ (maybe_more, new_env, eles)
+ | Parsetree.Psig_attribute _
+ | Parsetree.Psig_extension _ ->
+ (0, env, [])
+
+ (** Return a module_type_kind from a Parsetree.module_type and a Types.module_type *)
+ and analyse_module_type_kind
+ ?(erased = Name.Set.empty) env current_module_name module_type sig_module_type =
+ match module_type.Parsetree.pmty_desc with
+ Parsetree.Pmty_ident longident ->
+ let name =
+ match sig_module_type with
+ Types.Mty_ident path -> Name.from_path path
+ | _ -> Name.from_longident longident.txt
+ (* A VOIR cela arrive quand on fait module type F : functor ... -> Toto, Toto n'est pas un ident mais une structure *)
+ in
+ Module_type_alias { mta_name = Odoc_env.full_module_type_name env name ;
+ mta_module = None }
+
+ | Parsetree.Pmty_alias longident ->
+ let name =
+ match sig_module_type with
+ Types.Mty_alias path -> Name.from_path path
+ | _ -> Name.from_longident longident.txt
+ in
+ (* Wrong naming... *)
+ Module_type_alias { mta_name = Odoc_env.full_module_name env name ;
+ mta_module = None }
+
+ | Parsetree.Pmty_signature ast ->
+ (
+ let ast = filter_out_erased_items_from_signature erased ast in
+ (* we must have a signature in the module type *)
+ match sig_module_type with
+ Types.Mty_signature signat ->
+ let pos_start = module_type.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
+ let pos_end = module_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
+ let elements = analyse_parsetree env signat current_module_name pos_start pos_end ast in
+ Module_type_struct elements
+ | _ ->
+ raise (Failure "Parsetree.Pmty_signature signature but not Types.Mty_signature signat")
+ )
+
+ | Parsetree.Pmty_functor (_, pmodule_type2, module_type2) ->
+ (
+ let loc = match pmodule_type2 with None -> Location.none
+ | Some pmty -> pmty.Parsetree.pmty_loc in
+ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let mp_type_code = get_string_of_file loc_start loc_end in
+ print_DEBUG (Printf.sprintf "mp_type_code=%s" mp_type_code);
+ match sig_module_type with
+ Types.Mty_functor (ident, param_module_type, body_module_type) ->
+ let mp_kind =
+ match pmodule_type2, param_module_type with
+ Some pmty, Some mty ->
+ analyse_module_type_kind env current_module_name pmty mty
+ | _ -> Module_type_struct []
+ in
+ let param =
+ {
+ mp_name = Name.from_ident ident ;
+ mp_type =
+ Misc.may_map (Odoc_env.subst_module_type env)
+ param_module_type;
+ mp_type_code = mp_type_code ;
+ mp_kind = mp_kind ;
+ }
+ in
+ let k = analyse_module_type_kind ~erased env
+ current_module_name
+ module_type2
+ body_module_type
+ in
+ Module_type_functor (param, k)
+
+ | _ ->
+ (* if we're here something's wrong *)
+ raise (Failure "Parsetree.Pmty_functor _ but not Types.Mty_functor _")
+ )
+
+ | Parsetree.Pmty_with (module_type2, constraints) ->
+ (* of module_type * (Longident.t * with_constraint) list *)
+ (
+ let loc_start = module_type2.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
+ let loc_end = module_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
+ let s = get_string_of_file loc_start loc_end in
+ let erased = erased_names_of_constraints constraints erased in
+ let k = analyse_module_type_kind ~erased env current_module_name module_type2 sig_module_type in
+
+ Module_type_with (k, s)
+ )
+
+ | Parsetree.Pmty_typeof module_expr ->
+ let loc_start = module_expr.Parsetree.pmod_loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = module_expr.Parsetree.pmod_loc.Location.loc_end.Lexing.pos_cnum in
+ let s = get_string_of_file loc_start loc_end in
+ Module_type_typeof s
+
+ | Parsetree.Pmty_extension _ -> assert false
+
+ (** analyse of a Parsetree.module_type and a Types.module_type.*)
+ and analyse_module_kind
+ ?(erased = Name.Set.empty) env current_module_name module_type sig_module_type =
+ match module_type.Parsetree.pmty_desc with
+ | Parsetree.Pmty_ident longident ->
+ let k = analyse_module_type_kind env current_module_name module_type sig_module_type in
+ Module_with ( k, "" )
+ | Parsetree.Pmty_alias longident ->
+ begin
+ match sig_module_type with
+ Types.Mty_alias path ->
+ let alias_name = Odoc_env.full_module_name env (Name.from_path path) in
+ let ma = { ma_name = alias_name ; ma_module = None } in
+ Module_alias ma
+ | _ ->
+ raise (Failure "Parsetree.Pmty_alias _ but not Types.Mty_alias _")
+ end
+ | Parsetree.Pmty_signature signature ->
+ (
+ let signature = filter_out_erased_items_from_signature erased signature in
+ match sig_module_type with
+ Types.Mty_signature signat ->
+ Module_struct
+ (analyse_parsetree
+ env
+ signat
+ current_module_name
+ module_type.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum
+ module_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum
+ signature
+ )
+ | _ ->
+ (* if we're here something's wrong *)
+ raise (Failure "Parsetree.Pmty_signature signature but not Types.Mty_signature signat")
+ )
+ | Parsetree.Pmty_functor (_, pmodule_type2,module_type2) (* of string * module_type * module_type *) ->
+ (
+ match sig_module_type with
+ Types.Mty_functor (ident, param_module_type, body_module_type) ->
+ let loc = match pmodule_type2 with None -> Location.none
+ | Some pmty -> pmty.Parsetree.pmty_loc in
+ let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
+ let mp_type_code = get_string_of_file loc_start loc_end in
+ print_DEBUG (Printf.sprintf "mp_type_code=%s" mp_type_code);
+ let mp_kind =
+ match pmodule_type2, param_module_type with
+ Some pmty, Some mty ->
+ analyse_module_type_kind env current_module_name pmty mty
+ | _ -> Module_type_struct []
+ in
+ let param =
+ {
+ mp_name = Name.from_ident ident ;
+ mp_type = Misc.may_map
+ (Odoc_env.subst_module_type env) param_module_type ;
+ mp_type_code = mp_type_code ;
+ mp_kind = mp_kind ;
+ }
+ in
+ let k = analyse_module_kind ~erased env
+ current_module_name
+ module_type2
+ body_module_type
+ in
+ Module_functor (param, k)
+
+ | _ ->
+ (* if we're here something's wrong *)
+ raise (Failure "Parsetree.Pmty_functor _ but not Types.Mty_functor _")
+ )
+ | Parsetree.Pmty_with (module_type2, constraints) ->
+ (*of module_type * (Longident.t * with_constraint) list*)
+ (
+ let loc_start = module_type2.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
+ let loc_end = module_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
+ let s = get_string_of_file loc_start loc_end in
+ let erased = erased_names_of_constraints constraints erased in
+ let k = analyse_module_type_kind ~erased env current_module_name module_type2 sig_module_type in
+ Module_with (k, s)
+ )
+ | Parsetree.Pmty_typeof module_expr ->
+ let loc_start = module_expr.Parsetree.pmod_loc.Location.loc_start.Lexing.pos_cnum in
+ let loc_end = module_expr.Parsetree.pmod_loc.Location.loc_end.Lexing.pos_cnum in
+ let s = get_string_of_file loc_start loc_end in
+ Module_typeof s
+
+ | Parsetree.Pmty_extension _ -> assert false
+
+
+ (** Analyse of a Parsetree.class_type and a Types.class_type to return a couple
+ (class parameters, class_kind).*)
+ and analyse_class_kind env current_class_name last_pos parse_class_type sig_class_type =
+ match parse_class_type.Parsetree.pcty_desc, sig_class_type with
+ (Parsetree.Pcty_constr (_, _) (*of Longident.t * core_type list *),
+ Types.Cty_constr (p, typ_list, _) (*of Path.t * type_expr list * class_type*)) ->
+ print_DEBUG "Cty_constr _";
+ let path_name = Name.from_path p in
+ let name = Odoc_env.full_class_or_class_type_name env path_name in
+ let k =
+ Class_constr
+ {
+ cco_name = name ;
+ cco_class = None ;
+ cco_type_parameters = List.map (Odoc_env.subst_type env) typ_list
+ }
+ in
+ ([], k)
+
+ | (Parsetree.Pcty_signature { Parsetree.pcsig_fields = class_type_field_list }, Types.Cty_signature class_signature) ->
+ (* we get the elements of the class in class_type_field_list *)
+ let (inher_l, ele) = analyse_class_elements env current_class_name
+ last_pos
+ parse_class_type.Parsetree.pcty_loc.Location.loc_end.Lexing.pos_cnum
+ class_type_field_list
+ class_signature
+ in
+ ([], Class_structure (inher_l, ele))
+
+ | (Parsetree.Pcty_arrow (parse_label, _, pclass_type), Types.Cty_arrow (label, type_expr, class_type)) ->
+ (* label = string. Dans les signatures, pas de nom de parametres a l'interieur des tuples *)
+ (* si label = "", pas de label. ici on a l'information pour savoir si on a un label explicite. *)
+ if parse_label = label then
+ (
+ let new_param = Simple_name
+ {
+ sn_name = Btype.label_name label ;
+ sn_type = Odoc_env.subst_type env type_expr ;
+ sn_text = None ; (* will be updated when the class will be created *)
+ }
+ in
+ let (l, k) = analyse_class_kind env current_class_name last_pos pclass_type class_type in
+ ( (new_param :: l), k )
+ )
+ else
+ (
+ raise (Failure "Parsetree.Pcty_arrow (parse_label, _, pclass_type), labels differents")
+ )
+
+ | _ ->
+ raise (Failure "analyse_class_kind pas de correspondance dans le match")
+
+ (** Analyse of a Parsetree.class_type and a Types.class_type to return a class_type_kind.*)
+ and analyse_class_type_kind env current_class_name last_pos parse_class_type sig_class_type =
+ match parse_class_type.Parsetree.pcty_desc, sig_class_type with
+ (Parsetree.Pcty_constr (_, _) (*of Longident.t * core_type list *),
+ Types.Cty_constr (p, typ_list, _) (*of Path.t * type_expr list * class_type*)) ->
+ print_DEBUG "Cty_constr _";
+ let k =
+ Class_type
+ {
+ cta_name = Odoc_env.full_class_or_class_type_name env (Name.from_path p) ;
+ cta_class = None ;
+ cta_type_parameters = List.map (Odoc_env.subst_type env) typ_list
+ }
+ in
+ k
+
+ | (Parsetree.Pcty_signature {
+ Parsetree.pcsig_fields = class_type_field_list;
+ }, Types.Cty_signature class_signature) ->
+ (* we get the elements of the class in class_type_field_list *)
+ let (inher_l, ele) = analyse_class_elements env current_class_name
+ last_pos
+ parse_class_type.Parsetree.pcty_loc.Location.loc_end.Lexing.pos_cnum
+ class_type_field_list
+ class_signature
+ in
+ Class_signature (inher_l, ele)
+
+ | (Parsetree.Pcty_arrow (parse_label, _, pclass_type), Types.Cty_arrow (label, type_expr, class_type)) ->
+ raise (Failure "analyse_class_type_kind : Parsetree.Pcty_arrow (...) with Types.Cty_arrow (...)")
+(*
+ | (Parsetree.Pcty_constr (longident, _) (*of Longident.t * core_type list *),
+ Types.Cty_signature class_signature) ->
+ (* A VOIR : c'est pour le cas des contraintes de classes :
+ class type cons = object
+ method m : int
+ end
+
+ class ['a] maxou x =
+ (object
+ val a = (x : 'a)
+ method m = a
+ end : cons )
+ ^^^^^^
+ *)
+ let k =
+ Class_type
+ {
+ cta_name = Odoc_env.full_class_name env (Name.from_longident longident) ;
+ cta_class = None ;
+ cta_type_parameters = List.map (Odoc_env.subst_type env) typ_list (* ?? *)
+ }
+ in
+ ([], k)
+*)
+ | _ ->
+ raise (Failure "analyse_class_type_kind pas de correspondance dans le match")
+
+ let analyse_signature source_file input_file
+ (ast : Parsetree.signature) (signat : Types.signature) =
+ let complete_source_file =
+ try
+ let curdir = Sys.getcwd () in
+ let (dirname, basename) = (Filename.dirname source_file, Filename.basename source_file) in
+ Sys.chdir dirname ;
+ let complete = Filename.concat (Sys.getcwd ()) basename in
+ Sys.chdir curdir ;
+ complete
+ with
+ Sys_error s ->
+ prerr_endline s ;
+ incr Odoc_global.errors ;
+ source_file
+ in
+ prepare_file complete_source_file input_file;
+ (* We create the t_module for this file. *)
+ let mod_name = String.capitalize_ascii
+ (Filename.basename (try Filename.chop_extension source_file with _ -> source_file))
+ in
+ let (len,info_opt) = My_ir.first_special !file_name !file in
+ let elements =
+ analyse_parsetree Odoc_env.empty signat mod_name len (String.length !file) ast
+ in
+ let code_intf =
+ if !Odoc_global.keep_code then
+ Some !file
+ else
+ None
+ in
+ {
+ m_name = mod_name ;
+ m_type = Types.Mty_signature signat ;
+ m_info = info_opt ;
+ m_is_interface = true ;
+ m_file = !file_name ;
+ m_kind = Module_struct elements ;
+ m_loc = { loc_impl = None ; loc_inter = Some (Location.in_file !file_name) } ;
+ m_top_deps = [] ;
+ m_code = None ;
+ m_code_intf = code_intf ;
+ m_text_only = false ;
+ }
+
+ end
diff --git a/ocamldoc/odoc_sig.mli b/ocamldoc/odoc_sig.mli
new file mode 100644
index 0000000000..5dc4b4c8c0
--- /dev/null
+++ b/ocamldoc/odoc_sig.mli
@@ -0,0 +1,182 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The module for analysing a signature and source code and creating modules, classes, ..., elements.*)
+
+(** The functions used to retrieve information from a signature. *)
+module Signature_search :
+ sig
+ type ele
+ type tab = (ele, Types.signature_item) Hashtbl.t
+
+ (** Create a table from a signature. This table is used by some
+ of the search functions below. *)
+ val table : Types.signature -> tab
+
+ (** This function returns the type expression for the value whose name is given,
+ in the given signature.
+ @raise Not_found if error.*)
+ val search_value : tab -> string -> Types.type_expr
+
+ (** This function returns the Types.extension_constructor for the extension whose name is given,
+ in the given table.
+ @raise Not_found if error.*)
+ val search_extension : tab -> string -> Types.extension_constructor
+
+ (** This function returns the Types.type_declaration for the type whose name is given,
+ in the given table.
+ @raise Not_found if error.*)
+ val search_type : tab -> string -> Types.type_declaration
+
+ (** This function returns the Types.class_declaration for the class whose name is given,
+ in the given table.
+ @raise Not_found if error.*)
+ val search_class : tab -> string -> Types.class_declaration
+
+ (** This function returns the Types.class_type_declaration for the class type whose name is given,
+ in the given table.
+ @raise Not_found if error.*)
+ val search_class_type : tab -> string -> Types.class_type_declaration
+
+ (** This function returns the Types.module_type for the module whose name is given,
+ in the given table.
+ @raise Not_found if error.*)
+ val search_module : tab -> string -> Types.module_type
+
+ (** This function returns the optional Types.module_type for the module type whose name is given,
+ in the given table.
+ @raise Not_found if error.*)
+ val search_module_type : tab -> string -> Types.module_type option
+
+ (** This function returns the Types.type_expr for the given val name
+ in the given class signature.
+ @raise Not_found if error.*)
+ val search_attribute_type :
+ Types.Vars.key -> Types.class_signature -> Types.type_expr
+
+ (** This function returns the Types.type_expr for the given method name
+ in the given class signature.
+ @raise Not_found if error.*)
+ val search_method_type :
+ string -> Types.class_signature -> Types.type_expr
+ end
+
+(** Functions to retrieve simple and special comments from strings. *)
+module type Info_retriever =
+ sig
+ (** Return the couple [(n, list)] where [n] is the number of
+ characters read to retrieve [list], which is the list
+ of special comments found in the string. *)
+ val all_special :
+ string -> string -> int * Odoc_types.info list
+
+ (** Return true if the given string contains a blank line. *)
+ val blank_line_outside_simple :
+ string -> string -> bool
+
+ (** [just_after_special file str] return the pair ([length], [info_opt])
+ where [info_opt] is the first optional special comment found
+ in [str], without any blank line before. [length] is the number
+ of chars from the beginning of [str] to the end of the special comment. *)
+ val just_after_special :
+ string -> string -> (int * Odoc_types.info option)
+
+ (** [first_special file str] return the pair ([length], [info_opt])
+ where [info_opt] is the first optional special comment found
+ in [str]. [length] is the number of chars from the beginning of [str]
+ to the end of the special comment. *)
+ val first_special :
+ string -> string -> (int * Odoc_types.info option)
+
+ (** Return a pair [(comment_opt, element_comment_list)], where [comment_opt] is the last special
+ comment found in the given string and not followed by a blank line,
+ and [element_comment_list] the list of values built from the other
+ special comments found and the given function. *)
+ val get_comments :
+ (Odoc_types.text -> 'a) -> string -> string -> (Odoc_types.info option * 'a list)
+
+ end
+
+module Analyser :
+ functor (My_ir : Info_retriever) ->
+ sig
+ (** This variable is used to load a file as a string and retrieve characters from it.*)
+ val file : string ref
+
+ (** The name of the analysed file. *)
+ val file_name : string ref
+
+ (** This function takes two indexes (start and end) and return the string
+ corresponding to the indexes in the file global variable. The function
+ prepare_file must have been called to fill the file global variable.*)
+ val get_string_of_file : int -> int -> string
+
+ (** [prepare_file f input_f] sets [file_name] with [f] and loads the file
+ [input_f] into [file].*)
+ val prepare_file : string -> string -> unit
+
+ (** The function used to get the comments in a class. *)
+ val get_comments_in_class : int -> int ->
+ (Odoc_types.info option * Odoc_class.class_element list)
+
+ (** The function used to get the comments in a module. *)
+ val get_comments_in_module : int -> int ->
+ (Odoc_types.info option * Odoc_module.module_element list)
+
+ (** [name_comment_from_type_kind pos_end pos_limit type_kind].
+ This function takes a [Parsetree.type_kind] and returns the list of
+ (name, optional comment) for the various fields/constructors of the type,
+ or an empty list for an abstract type.
+ [pos_end] is last char of the complete type definition.
+ [pos_limit] is the position of the last char we could use to look for a comment,
+ i.e. usually the beginning on the next element.*)
+ val name_comment_from_type_decl :
+ int -> int -> Parsetree.type_declaration -> int * (string * Odoc_types.info option) list
+
+ (** This function converts a [Types.type_expr] into a [Odoc_type.type_kind],
+ by associating the comment found in the parstree of each object field, if any. *)
+ val manifest_structure :
+ Odoc_env.env -> (string * Odoc_types.info option) list ->
+ Types.type_expr -> Odoc_type.type_manifest
+
+ (** This function converts a [Types.type_kind] into a [Odoc_type.type_kind],
+ by associating the comment found in the parsetree of each constructor/field, if any.*)
+ val get_type_kind :
+ Odoc_env.env -> (string * Odoc_types.info option) list ->
+ Types.type_kind -> Odoc_type.type_kind
+
+ (** This function merge two optional info structures. *)
+ val merge_infos :
+ Odoc_types.info option -> Odoc_types.info option ->
+ Odoc_types.info option
+
+ (** Return a module_type_kind from a Parsetree.module_type and a Types.module_type *)
+ val analyse_module_type_kind :
+ ?erased:Odoc_name.Set.t -> Odoc_env.env -> Odoc_name.t ->
+ Parsetree.module_type -> Types.module_type ->
+ Odoc_module.module_type_kind
+
+ (** Analysis of a Parsetree.class_type and a Types.class_type to
+ return a class_type_kind.*)
+ val analyse_class_type_kind : Odoc_env.env ->
+ Odoc_name.t -> int -> Parsetree.class_type -> Types.class_type ->
+ Odoc_class.class_type_kind
+
+ (** This function takes an interface file name, a file containg the code, a parse tree
+ and the signature obtained from the compiler.
+ It goes through the parse tree, creating values for encountered
+ functions, modules, ..., looking in the source file for comments,
+ and in the signature for types information. *)
+ val analyse_signature :
+ string -> string ->
+ Parsetree.signature -> Types.signature -> Odoc_module.t_module
+ end
diff --git a/ocamldoc/odoc_str.ml b/ocamldoc/odoc_str.ml
new file mode 100644
index 0000000000..281496bb31
--- /dev/null
+++ b/ocamldoc/odoc_str.ml
@@ -0,0 +1,385 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The functions to get a string from different kinds of elements (types, modules, ...). *)
+
+module Name = Odoc_name
+
+let string_of_variance t (co,cn) =
+ if ( t.Odoc_type.ty_kind = Odoc_type.Type_abstract ||
+ t.Odoc_type.ty_kind = Odoc_type.Type_open ) &&
+ t.Odoc_type.ty_manifest = None
+ then
+ match (co, cn) with
+ (true, false) -> "+"
+ | (false, true) -> "-"
+ | _ -> ""
+ else
+ ""
+let rec is_arrow_type t =
+ match t.Types.desc with
+ Types.Tarrow _ -> true
+ | Types.Tlink t2 | Types.Tsubst t2 -> is_arrow_type t2
+ | Types.Ttuple _
+ | Types.Tconstr _
+ | Types.Tvar _ | Types.Tunivar _ | Types.Tobject _ | Types.Tpoly _
+ | Types.Tfield _ | Types.Tnil | Types.Tvariant _ | Types.Tpackage _ -> false
+
+let raw_string_of_type_list sep type_list =
+ let buf = Buffer.create 256 in
+ let fmt = Format.formatter_of_buffer buf in
+ let rec need_parent t =
+ match t.Types.desc with
+ Types.Tarrow _ | Types.Ttuple _ -> true
+ | Types.Tlink t2 | Types.Tsubst t2 -> need_parent t2
+ | Types.Tconstr _ ->
+ false
+ | Types.Tvar _ | Types.Tunivar _ | Types.Tobject _ | Types.Tpoly _
+ | Types.Tfield _ | Types.Tnil | Types.Tvariant _ | Types.Tpackage _ -> false
+ in
+ let print_one_type variance t =
+ Printtyp.mark_loops t;
+ if need_parent t then
+ (
+ Format.fprintf fmt "(%s" variance;
+ Printtyp.type_scheme_max ~b_reset_names: false fmt t;
+ Format.fprintf fmt ")"
+ )
+ else
+ (
+ Format.fprintf fmt "%s" variance;
+ Printtyp.type_scheme_max ~b_reset_names: false fmt t
+ )
+ in
+ begin match type_list with
+ [] -> ()
+ | [(variance, ty)] -> print_one_type variance ty
+ | (variance, ty) :: tyl ->
+ Format.fprintf fmt "@[<hov 2>";
+ print_one_type variance ty;
+ List.iter
+ (fun (variance, t) ->
+ Format.fprintf fmt "@,%s" sep;
+ print_one_type variance t
+ )
+ tyl;
+ Format.fprintf fmt "@]"
+ end;
+ Format.pp_print_flush fmt ();
+ Buffer.contents buf
+
+let string_of_type_list ?par sep type_list =
+ let par =
+ match par with
+ | Some b -> b
+ | None ->
+ match type_list with
+ [] | [_] -> false
+ | _ -> true
+ in
+ Printf.sprintf "%s%s%s"
+ (if par then "(" else "")
+ (raw_string_of_type_list sep (List.map (fun t -> ("", t)) type_list))
+ (if par then ")" else "")
+
+let string_of_type_param_list t =
+ let par =
+ match t.Odoc_type.ty_parameters with
+ [] | [_] -> false
+ | _ -> true
+ in
+ Printf.sprintf "%s%s%s"
+ (if par then "(" else "")
+ (raw_string_of_type_list ", "
+ (List.map
+ (fun (typ, co, cn) -> (string_of_variance t (co, cn), typ))
+ t.Odoc_type.ty_parameters
+ )
+ )
+ (if par then ")" else "")
+
+let string_of_type_extension_param_list te =
+ let par =
+ match te.Odoc_extension.te_type_parameters with
+ [] | [_] -> false
+ | _ -> true
+ in
+ Printf.sprintf "%s%s%s"
+ (if par then "(" else "")
+ (raw_string_of_type_list ", "
+ (List.map
+ (fun typ -> ("", typ))
+ te.Odoc_extension.te_type_parameters
+ )
+ )
+ (if par then ")" else "")
+
+
+let string_of_class_type_param_list l =
+ let par =
+ match l with
+ [] | [_] -> false
+ | _ -> true
+ in
+ Printf.sprintf "%s%s%s"
+ (if par then "[" else "")
+ (raw_string_of_type_list ", "
+ (List.map
+ (fun typ -> ("", typ))
+ l
+ )
+ )
+ (if par then "]" else "")
+
+let string_of_class_params c =
+ let b = Buffer.create 256 in
+ let rec iter = function
+ Types.Cty_arrow (label, t, ctype) ->
+ let parent = is_arrow_type t in
+ Printf.bprintf b "%s%s%s%s -> "
+ (
+ match label with
+ Asttypes.Nolabel -> ""
+ | s -> Printtyp.string_of_label s ^":"
+ )
+ (if parent then "(" else "")
+ (Odoc_print.string_of_type_expr
+ (if Odoc_misc.is_optional label then
+ Odoc_misc.remove_option t
+ else
+ t
+ )
+ )
+ (if parent then ")" else "");
+ iter ctype
+ | Types.Cty_signature _
+ | Types.Cty_constr _ -> ()
+ in
+ iter c.Odoc_class.cl_type;
+ Buffer.contents b
+
+let bool_of_private = function
+ | Asttypes.Private -> true
+ | _ -> false
+
+let field_doc_str = function
+ | None -> ""
+ | Some t -> Printf.sprintf "(* %s *)" (Odoc_misc.string_of_info t)
+
+let string_of_record l =
+ let module M = Odoc_type in
+ let module P = Printf in
+ P.sprintf "{\n%s\n}" (
+ String.concat "\n" (
+ List.map (fun field ->
+ P.sprintf " %s%s : %s;%s"
+ (if field.M.rf_mutable then "mutable " else "") field.M.rf_name
+ (Odoc_print.string_of_type_expr field.M.rf_type)
+ (field_doc_str field.M.rf_text)
+ ) l
+ )
+ )
+
+let string_of_type t =
+ let module M = Odoc_type in
+ let module P = Printf in
+ let priv = bool_of_private t.M.ty_private in
+ let parameters_str =
+ String.concat " " (
+ List.map (fun (p, co, cn) ->
+ (string_of_variance t (co, cn)) ^ (Odoc_print.string_of_type_expr p)
+ ) t.M.ty_parameters
+ )
+ in
+ let manifest_str =
+ match t.M.ty_manifest with
+ | None -> ""
+ | Some (M.Object_type fields) ->
+ P.sprintf "= %s<\n%s\n>\n" (if priv then "private " else "") (
+ String.concat "\n" (
+ List.map (fun field ->
+ P.sprintf " %s : %s;%s" field.M.of_name
+ (Odoc_print.string_of_type_expr field.M.of_type)
+ (field_doc_str field.M.of_text)
+ ) fields
+ )
+ )
+ | Some (M.Other typ) ->
+ "= " ^ (if priv then "private " else "" ) ^
+ (Odoc_print.string_of_type_expr typ) ^ " "
+ in
+ let type_kind_str =
+ match t.M.ty_kind with
+ | M.Type_abstract -> ""
+ | M.Type_variant l ->
+ P.sprintf "=%s\n%s\n" (if priv then " private" else "") (
+ String.concat "\n" (
+ List.map (fun cons ->
+ let comment =
+ match cons.M.vc_text with
+ | None -> ""
+ | Some t -> P.sprintf "(* %s *)" (Odoc_misc.string_of_info t)
+ in
+ let string_of_parameters = function
+ | M.Cstr_tuple l ->
+ String.concat " * " (
+ List.map (fun t -> "("^Odoc_print.string_of_type_expr t^")") l
+ )
+ | M.Cstr_record l ->
+ string_of_record l
+ in
+ P.sprintf " | %s%s%s" cons.M.vc_name (
+ match cons.M.vc_args, cons.M.vc_ret with
+ | M.Cstr_tuple [], None -> ""
+ | li, None -> " of " ^ (string_of_parameters li)
+ | M.Cstr_tuple [], Some r -> " : " ^ Odoc_print.string_of_type_expr r
+ | li, Some r ->
+ P.sprintf " : %s -> %s" (string_of_parameters li)
+ (Odoc_print.string_of_type_expr r)
+ ) comment
+ ) l
+ )
+ )
+
+ | M.Type_open ->
+ "= .." (* FIXME MG: when introducing new constuctors next time,
+ thanks to setup a minimal correct output *)
+ | M.Type_record l ->
+ P.sprintf "= %s{\n%s\n}\n" (if priv then "private " else "")
+ (string_of_record l)
+ in
+ P.sprintf "type %s %s %s%s%s" parameters_str (Name.simple t.M.ty_name)
+ manifest_str type_kind_str
+ (match t.M.ty_info with
+ | None -> ""
+ | Some info -> Odoc_misc.string_of_info info)
+
+let string_of_type_extension te =
+ let module M = Odoc_extension in
+ let module T = Odoc_type in
+ "type "
+ ^(String.concat ""
+ (List.map
+ (fun p -> (Odoc_print.string_of_type_expr p)^" ")
+ te.M.te_type_parameters
+ ))
+ ^te.M.te_type_name
+ ^" += "
+ ^(if (bool_of_private te.M.te_private) then "private " else "")
+ ^"\n"
+ ^(String.concat ""
+ (List.map
+ (fun x ->
+ " | "
+ ^(Name.simple x.M.xt_name)
+ ^(match x.M.xt_args, x.M.xt_ret with
+ | T.Cstr_tuple [], None -> ""
+ | T.Cstr_tuple l, None ->
+ " of " ^
+ (String.concat " * "
+ (List.map
+ (fun t -> "("^Odoc_print.string_of_type_expr t^")") l))
+ | T.Cstr_tuple [], Some r -> " : " ^ Odoc_print.string_of_type_expr r
+ | T.Cstr_tuple l, Some r ->
+ " : " ^
+ (String.concat " * "
+ (List.map
+ (fun t -> "("^Odoc_print.string_of_type_expr t^")") l))
+ ^ " -> " ^ Odoc_print.string_of_type_expr r
+ | T.Cstr_record _, _ ->
+ assert false
+ )
+ ^(match x.M.xt_alias with
+ None -> ""
+ | Some xa ->
+ " = "^
+ (match xa.M.xa_xt with
+ None -> xa.M.xa_name
+ | Some x2 -> x2.M.xt_name
+ )
+ )
+ ^(match x.M.xt_text with
+ None ->
+ ""
+ | Some t ->
+ "(* "^(Odoc_misc.string_of_info t)^" *)"
+ )^"\n"
+ )
+ te.M.te_constructors))
+ ^(match te.M.te_info with
+ None -> ""
+ | Some i -> Odoc_misc.string_of_info i
+ )
+
+let string_of_exception e =
+ let module T = Odoc_type in
+ let module M = Odoc_exception in
+ "exception "^(Name.simple e.M.ex_name)^
+ (match e.M.ex_args, e.M.ex_ret with
+ T.Cstr_tuple [], None -> ""
+ | T.Cstr_tuple l,None ->
+ " of "^
+ (String.concat " * "
+ (List.map (fun t -> "("^(Odoc_print.string_of_type_expr t)^")") l))
+ | T.Cstr_tuple [],Some r ->
+ " : "^
+ (Odoc_print.string_of_type_expr r)
+ | T.Cstr_tuple l,Some r ->
+ " : "^
+ (String.concat " * "
+ (List.map (fun t -> "("^(Odoc_print.string_of_type_expr t)^")") l))^
+ " -> "^
+ (Odoc_print.string_of_type_expr r)
+ | T.Cstr_record _, _ ->
+ assert false
+ )^
+ (match e.M.ex_alias with
+ None -> ""
+ | Some ea ->
+ " = "^
+ (match ea.M.ea_ex with
+ None -> ea.M.ea_name
+ | Some e2 -> e2.M.ex_name
+ )
+ )^"\n"^
+ (match e.M.ex_info with
+ None -> ""
+ | Some i -> Odoc_misc.string_of_info i)
+
+let string_of_value v =
+ let module M = Odoc_value in
+ "val "^(Name.simple v.M.val_name)^" : "^
+ (Odoc_print.string_of_type_expr v.M.val_type)^"\n"^
+ (match v.M.val_info with
+ None -> ""
+ | Some i -> Odoc_misc.string_of_info i)
+
+let string_of_attribute a =
+ let module M = Odoc_value in
+ "val "^
+ (if a.M.att_virtual then "virtual " else "")^
+ (if a.M.att_mutable then Odoc_messages.mutab^" " else "")^
+ (Name.simple a.M.att_value.M.val_name)^" : "^
+ (Odoc_print.string_of_type_expr a.M.att_value.M.val_type)^"\n"^
+ (match a.M.att_value.M.val_info with
+ None -> ""
+ | Some i -> Odoc_misc.string_of_info i)
+
+let string_of_method m =
+ let module M = Odoc_value in
+ "method "^
+ (if m.M.met_private then Odoc_messages.privat^" " else "")^
+ (Name.simple m.M.met_value.M.val_name)^" : "^
+ (Odoc_print.string_of_type_expr m.M.met_value.M.val_type)^"\n"^
+ (match m.M.met_value.M.val_info with
+ None -> ""
+ | Some i -> Odoc_misc.string_of_info i)
diff --git a/ocamldoc/odoc_str.mli b/ocamldoc/odoc_str.mli
new file mode 100644
index 0000000000..925deddad6
--- /dev/null
+++ b/ocamldoc/odoc_str.mli
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The functions to get a string from different kinds of elements (types, modules, ...). *)
+
+(** @return the variance string for the given type and (covariant, contravariant) information. *)
+val string_of_variance : Odoc_type.t_type -> (bool * bool) -> string
+
+(** This function returns a string to represent the given list of types,
+ with a given separator.
+ @param par can be used to force the addition or not of parentheses around the returned string.
+*)
+val string_of_type_list : ?par: bool -> string -> Types.type_expr list -> string
+
+(** This function returns a string to represent the list of type parameters
+ for the given type. *)
+val string_of_type_param_list : Odoc_type.t_type -> string
+
+(** This function returns a string to represent the list of type parameters
+ for the given type extension. *)
+val string_of_type_extension_param_list : Odoc_extension.t_type_extension -> string
+
+(** This function returns a string to represent the given list of
+ type parameters of a class or class type,
+ with a given separator. *)
+val string_of_class_type_param_list : Types.type_expr list -> string
+
+(** @return a string to describe the given type. *)
+val string_of_type : Odoc_type.t_type -> string
+
+val string_of_record : Odoc_type.record_field list -> string
+
+(** @return a string to display the parameters of the given class,
+ in the same form as the compiler. *)
+val string_of_class_params : Odoc_class.t_class -> string
+
+(** @return a string to describe the given type extension. *)
+val string_of_type_extension : Odoc_extension.t_type_extension -> string
+
+(** @return a string to describe the given exception. *)
+val string_of_exception : Odoc_exception.t_exception -> string
+
+(** @return a string to describe the given value. *)
+val string_of_value : Odoc_value.t_value -> string
+
+(** @return a string to describe the given attribute. *)
+val string_of_attribute : Odoc_value.t_attribute -> string
+
+(** @return a string to describe the given method. *)
+val string_of_method : Odoc_value.t_method -> string
diff --git a/ocamldoc/odoc_test.ml b/ocamldoc/odoc_test.ml
new file mode 100644
index 0000000000..c68e853267
--- /dev/null
+++ b/ocamldoc/odoc_test.ml
@@ -0,0 +1,123 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2004 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Custom generator to perform test on ocamldoc. *)
+
+open Odoc_info
+open Odoc_info.Module
+open Odoc_info.Type
+
+type test_kind =
+ Types_display
+
+let p = Format.fprintf
+
+module Generator (G : Odoc_gen.Base) =
+struct
+ class string_gen =
+ object(self)
+ inherit Odoc_info.Scan.scanner
+
+
+ val mutable test_kinds = []
+ val mutable fmt = Format.str_formatter
+
+ method must_display_types = List.mem Types_display test_kinds
+
+ method set_test_kinds_from_module m =
+ test_kinds <- List.fold_left
+ (fun acc (s, _) ->
+ match s with
+ "test_types_display" -> Types_display :: acc
+ | _ -> acc
+ )
+ []
+ (
+ match m.m_info with
+ None -> []
+ | Some i -> i.i_custom
+ )
+ method! scan_type t =
+ match test_kinds with
+ [] -> ()
+ | _ ->
+ p fmt "# type %s:\n" t.ty_name;
+ if self#must_display_types then
+ (
+ p fmt "# manifest :\n<[%s]>\n"
+ (match t.ty_manifest with
+ None -> "None"
+ | Some (Object_type _fields) -> "< object type >" (* TODO *)
+ | Some (Other e) -> Odoc_info.string_of_type_expr e
+ );
+ );
+
+
+ method! scan_module_pre m =
+ p fmt "#\n# module %s:\n" m.m_name ;
+ if self#must_display_types then
+ (
+ p fmt "# Odoc_info.string_of_module_type:\n<[%s]>\n"
+ (Odoc_info.string_of_module_type m.m_type);
+ p fmt "# Odoc_info.string_of_module_type ~complete: true :\n<[%s]>\n"
+ (Odoc_info.string_of_module_type ~complete: true m.m_type);
+ );
+ true
+
+ method! scan_module_type_pre m =
+ p fmt "#\n# module type %s:\n" m.mt_name ;
+ if self#must_display_types then
+ (
+ p fmt "# Odoc_info.string_of_module_type:\n<[%s]>\n"
+ (match m.mt_type with
+ None -> "None"
+ | Some t -> Odoc_info.string_of_module_type t
+ );
+ p fmt "# Odoc_info.string_of_module_type ~complete: true :\n<[%s]>\n"
+ (match m.mt_type with
+ None -> "None"
+ | Some t -> Odoc_info.string_of_module_type ~complete: true t
+ );
+ );
+ true
+
+ method generate (module_list: Odoc_info.Module.t_module list) =
+ let oc = open_out !Odoc_info.Global.out_file in
+ fmt <- Format.formatter_of_out_channel oc;
+ (
+ try
+ List.iter
+ (fun m ->
+ self#set_test_kinds_from_module m;
+ self#scan_module_list [m];
+ )
+ module_list
+ with
+ e ->
+ prerr_endline (Printexc.to_string e)
+ );
+ Format.pp_print_flush fmt ();
+ close_out oc
+ end
+
+ class generator =
+ let g = new string_gen in
+ object
+ inherit G.generator as base
+
+ method generate l =
+ base#generate l;
+ g#generate l
+ end
+end;;
+
+let _ = Odoc_args.extend_base_generator (module Generator : Odoc_gen.Base_functor);;
diff --git a/ocamldoc/odoc_texi.ml b/ocamldoc/odoc_texi.ml
new file mode 100644
index 0000000000..77489ec90b
--- /dev/null
+++ b/ocamldoc/odoc_texi.ml
@@ -0,0 +1,1313 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Olivier Andrieu, base sur du code de Maxence Guesdon *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Generation of Texinfo documentation. *)
+
+open Odoc_info
+open Parameter
+open Value
+open Type
+open Extension
+open Exception
+open Class
+open Module
+
+let esc_8bits = ref false
+
+let info_section = ref "OCaml"
+
+let info_entry = ref []
+
+(** {2 Some small helper functions} *)
+
+let puts_nl chan s =
+ output_string chan s ;
+ output_char chan '\n'
+let puts chan s =
+ output_string chan s
+let nl chan =
+ output_char chan '\n'
+
+let is = function
+ | None -> false
+ | Some _ -> true
+
+let pad_to n s =
+ let len = String.length s in
+ if len < n then s ^ String.make (n - len) ' ' else s
+
+let indent nb_sp s =
+ let c = ref 0 in
+ let len = pred (String.length s) in
+ for i = 0 to len do if s.[i] = '\n' then incr c done ;
+ let s' = Bytes.make (succ len + (succ !c) * nb_sp ) ' ' in
+ c := nb_sp ;
+ for i = 0 to len do
+ Bytes.set s' !c s.[i] ;
+ if s.[i] = '\n' then c := !c + nb_sp ;
+ incr c
+ done ;
+ Bytes.to_string s'
+
+type subparts = [
+ | `Module of Odoc_info.Module.t_module
+ | `Module_type of Odoc_info.Module.t_module_type
+ | `Class of Odoc_info.Class.t_class
+ | `Class_type of Odoc_info.Class.t_class_type
+ ]
+
+type menu_data = [
+ | subparts
+ | `Blank
+ | `Comment of string
+ | `Texi of string
+ | `Index of string
+] list
+
+let nothing = Verbatim ""
+
+let module_subparts =
+ let rec iter acc = function
+ | [] -> List.rev acc
+ (* skip aliases *)
+ | Element_module { m_kind = Module_alias _ } :: n ->
+ iter acc n
+ | Element_module_type { mt_kind = Some (Module_type_alias _) } :: n ->
+ iter acc n
+ (* keep modules, module types, classes and class types *)
+ | Element_module m :: n ->
+ iter (`Module m :: acc) n
+ | Element_module_type mt :: n ->
+ iter (`Module_type mt :: acc) n
+ | Element_class c :: n ->
+ iter (`Class c :: acc) n
+ | Element_class_type ct :: n ->
+ iter (`Class_type ct :: acc) n
+ (* forget the rest *)
+ | _ :: n -> iter acc n
+ in
+ iter []
+
+type indices = [
+ | `Type
+ | `Extension
+ | `Exception
+ | `Value
+ | `Class_att
+ | `Method
+ | `Class
+ | `Class_type
+ | `Module
+ | `Module_type
+]
+
+let indices = function
+ | `Type -> "ty"
+ | `Extension -> "xt"
+ | `Exception -> "ex"
+ | `Value -> "va"
+ | `Class_att -> "ca"
+ | `Method -> "me"
+ | `Class -> "cl"
+ | `Class_type -> "ct"
+ | `Module -> "mo"
+ | `Module_type -> "mt"
+
+let indices_names = [
+ "Types" , "ty" ;
+ "Extensions" , "xt" ;
+ "Exceptions" , "ex" ;
+ "Values" , "va" ;
+ "Class attributes", "ca" ;
+ "Methods" , "me" ;
+ "Classes" , "cl" ;
+ "Class types" , "ct" ;
+ "Modules" , "mo" ;
+ "Module types" , "mt" ; ]
+
+
+
+(** Module for generating various Texinfo things (menus, xrefs, ...) *)
+module Texi =
+struct
+ (** Associations of strings to subsitute in Texinfo code. *)
+ let subst_strings = [
+ (Str.regexp "@", "@@") ;
+ (Str.regexp "{", "@{") ;
+ (Str.regexp "}", "@}") ;
+ (Str.regexp "\\.\\.\\.", "@dots{}") ;
+ ] @
+ (if !esc_8bits
+ then [
+ (Str.regexp "\xE0", "@`a") ;
+ (Str.regexp "\xE2", "@^a") ;
+ (Str.regexp "\xE9", "@'e") ;
+ (Str.regexp "\xE8", "@`e") ;
+ (Str.regexp "\xEA", "@^e") ;
+ (Str.regexp "\xEB", "@\"e") ;
+ (Str.regexp "\xF7", "@,{c}") ;
+ (Str.regexp "\xF4", "@^o") ;
+ (Str.regexp "\xF6", "@\"o") ;
+ (Str.regexp "\xEE", "@^i") ;
+ (Str.regexp "\xEF", "@\"i") ;
+ (Str.regexp "\xF9", "@`u") ;
+ (Str.regexp "\xFB", "@^u") ;
+ (Str.regexp "\xE6", "@ae{}" ) ;
+ (Str.regexp "\xC6", "@AE{}" ) ;
+ (Str.regexp "\xDF", "@ss{}" ) ;
+ (Str.regexp "\xA9", "@copyright{}" ) ;
+ ]
+ else [])
+
+ (** Escape the strings which would clash with Texinfo syntax. *)
+ let escape s =
+ List.fold_left
+ (fun acc (p, r) -> Str.global_replace p r acc)
+ s subst_strings
+
+ (** Removes dots (no good for a node name). *)
+ let fix_nodename s =
+ Str.global_replace (Str.regexp "\\.") "/" (escape s)
+
+ (** Generates a Texinfo menu. *)
+ let generate_menu chan subpart_list =
+ if subpart_list <> []
+ then begin
+ let menu_line part_qual name =
+ let sname = Name.simple name in
+ if sname = name
+ then (
+ puts chan (pad_to 35
+ ("* " ^ sname ^ ":: ")) ;
+ puts_nl chan part_qual )
+ else (
+ puts chan (pad_to 35
+ ("* " ^ sname ^ ": " ^ (fix_nodename name) ^ ". " )) ;
+ puts_nl chan part_qual )
+ in
+ puts_nl chan "@menu" ;
+ List.iter
+ (function
+ | `Module { m_name = name } ->
+ menu_line Odoc_messages.modul name
+ | `Module_type { mt_name = name } ->
+ menu_line Odoc_messages.module_type name
+ | `Class { cl_name = name } ->
+ menu_line Odoc_messages.clas name
+ | `Class_type { clt_name = name } ->
+ menu_line Odoc_messages.class_type name
+ | `Blank -> nl chan
+ | `Comment c -> puts_nl chan (escape c)
+ | `Texi t -> puts_nl chan t
+ | `Index ind -> Printf.fprintf chan "* %s::\n" ind)
+ subpart_list ;
+ puts_nl chan "@end menu"
+ end
+
+ (** cross reference to node [name] *)
+ let xref ?xname name =
+ "@xref{" ^ (fix_nodename name) ^
+ (match xname with | None -> "" | Some s -> "," ^ s) ^
+ "}."
+
+ (** enclose the string between [\@ifinfo] tags *)
+ let ifinfo s =
+ String.concat "\n"
+ [ "@ifinfo" ; s ; "@end ifinfo" ; "" ]
+
+ (** [install-info] information *)
+ let dirsection sec =
+ "@dircategory " ^ (escape sec)
+
+ let direntry ent =
+ [ "@direntry" ] @
+ (List.map escape ent) @
+ [ "@end direntry" ]
+end
+
+
+
+
+
+(** {2 Generation of Texinfo code} *)
+
+(** This class generates Texinfo code from text structures *)
+class text =
+ object(self)
+
+ (** Associations between a title number and texinfo code. *)
+ val titles = [
+ 1, "@chapter " ;
+ 2, "@section " ;
+ 3, "@subsection " ;
+ 4, "@subsubsection " ;
+ ]
+
+ val fallback_title =
+ "@unnumberedsubsubsec "
+
+ val headings = [
+ 1, "@majorheading " ;
+ 2, "@heading " ;
+ 3, "@subheading " ;
+ 4, "@subsubheading " ;
+ ]
+
+ val fallback_heading =
+ "@subsubheading "
+
+ method escape =
+ Texi.escape
+
+ (** this method is not used here but is virtual
+ in a class we will inherit later *)
+ method label ?(no_ : bool option) (_ : string) : string =
+ failwith "gni"
+
+ (** Return the Texinfo code corresponding to the [text] parameter.*)
+ method texi_of_text t =
+ String.concat ""
+ (List.map self#texi_of_text_element t)
+
+
+ (** {3 Conversion methods}
+ [texi_of_????] converts a [text_element] to a Texinfo string. *)
+
+ (** Return the Texinfo code for the [text_element] in parameter. *)
+ method texi_of_text_element = function
+ | Verbatim s | Latex s -> self#texi_of_Verbatim s
+ | Raw s -> self#texi_of_Raw s
+ | Code s -> self#texi_of_Code s
+ | CodePre s -> self#texi_of_CodePre s
+ | Bold t -> self#texi_of_Bold t
+ | Italic t -> self#texi_of_Italic t
+ | Emphasize t -> self#texi_of_Emphasize t
+ | Center t -> self#texi_of_Center t
+ | Left t -> self#texi_of_Left t
+ | Right t -> self#texi_of_Right t
+ | List tl -> self#texi_of_List tl
+ | Enum tl -> self#texi_of_Enum tl
+ | Newline -> self#texi_of_Newline
+ | Block t -> self#texi_of_Block t
+ | Title (n, _, t) -> self#texi_of_Title n t
+ | Link (s, t) -> self#texi_of_Link s t
+ | Ref (name, kind, _) ->self#texi_of_Ref name kind
+ | Superscript t -> self#texi_of_Superscript t
+ | Subscript t -> self#texi_of_Subscript t
+ | Odoc_info.Module_list _ -> ""
+ | Odoc_info.Index_list -> ""
+ | Odoc_info.Custom (s,t) -> self#texi_of_custom_text s t
+ | Odoc_info.Target (target, code) -> self#texi_of_Target ~target ~code
+
+ method texi_of_custom_text s t = ""
+
+ method texi_of_Target ~target ~code =
+ if String.lowercase_ascii target = "texi" then code else ""
+
+ method texi_of_Verbatim s = s
+ method texi_of_Raw s = self#escape s
+ method texi_of_Code s = "@code{" ^ (self#escape s) ^ "}"
+ method texi_of_CodePre s =
+ String.concat "\n"
+ [ "" ; "@example" ; self#escape s ; "@end example" ; "" ]
+ method texi_of_Bold t = "@strong{" ^ (self#texi_of_text t) ^ "}"
+ method texi_of_Italic t = "@i{" ^ (self#texi_of_text t) ^ "}"
+ method texi_of_Emphasize t = "@emph{" ^ (self#texi_of_text t) ^ "}"
+ method texi_of_Center t =
+ let sl = Str.split (Str.regexp "\n") (self#texi_of_text t) in
+ String.concat ""
+ ((List.map (fun s -> "\n@center "^s) sl) @ [ "\n" ])
+ method texi_of_Left t =
+ String.concat "\n"
+ [ "" ; "@flushleft" ; self#texi_of_text t ; "@end flushleft" ; "" ]
+ method texi_of_Right t =
+ String.concat "\n"
+ [ "" ; "@flushright" ; self#texi_of_text t ; "@end flushright"; "" ]
+ method texi_of_List tl =
+ String.concat "\n"
+ ( [ "" ; "@itemize" ] @
+ (List.map (fun t -> "@item\n" ^ (self#texi_of_text t)) tl) @
+ [ "@end itemize"; "" ] )
+ method texi_of_Enum tl =
+ String.concat "\n"
+ ( [ "" ; "@enumerate" ] @
+ (List.map (fun t -> "@item\n" ^ (self#texi_of_text t)) tl) @
+ [ "@end enumerate"; "" ] )
+ method texi_of_Newline = "\n"
+ method texi_of_Block t =
+ String.concat "\n"
+ [ "@format" ; self#texi_of_text t ; "@end format" ; "" ]
+ method texi_of_Title n t =
+ let t_begin =
+ try List.assoc n titles
+ with Not_found -> fallback_title in
+ t_begin ^ (self#texi_of_text t) ^ "\n"
+ method texi_of_Link s t =
+ String.concat ""
+ [ "@uref{" ; s ; "," ; self#texi_of_text t ; "}" ]
+ method texi_of_Ref name kind =
+ let xname =
+ match kind with
+ | Some RK_module ->
+ Odoc_messages.modul ^ " " ^ (Name.simple name)
+ | Some RK_module_type ->
+ Odoc_messages.module_type ^ " " ^ (Name.simple name)
+ | Some RK_class ->
+ Odoc_messages.clas ^ " " ^ (Name.simple name)
+ | Some RK_class_type ->
+ Odoc_messages.class_type ^ " " ^ (Name.simple name)
+ | _ -> ""
+ in
+ if xname = "" then self#escape name else Texi.xref ~xname name
+ method texi_of_Superscript t =
+ "^@{" ^ (self#texi_of_text t) ^ "@}"
+ method texi_of_Subscript t =
+ "_@{" ^ (self#texi_of_text t) ^ "@}"
+
+ method heading n t =
+ let f =
+ try List.assoc n headings
+ with Not_found -> fallback_heading
+ in
+ f ^ (self#texi_of_text t) ^ "\n"
+
+ method fixedblock t =
+ Block ( ( Verbatim "@t{" :: t ) @ [ Verbatim "}" ] )
+
+ end
+
+exception Aliased_node
+
+module Generator =
+struct
+
+(** This class is used to create objects which can generate a simple
+ Texinfo documentation. *)
+class texi =
+ object (self)
+ inherit text as to_texi
+ inherit Odoc_to_text.to_text as to_text
+
+ (** {3 Small helper stuff.} *)
+
+ val maxdepth = 4
+
+ val bullet = Verbatim " @bullet{} "
+ val minus = Verbatim " @minus{} "
+ val linebreak = Verbatim "@*\n"
+
+ val mutable indices_to_build = [ `Module ]
+
+ (** Keep a set of nodes we create. If we try to create one
+ a second time, that means it is some kind of alias, so
+ don't do it, just link to the previous one *)
+ val node_tbl = Hashtbl.create 37
+
+ method node depth name =
+ if Hashtbl.mem node_tbl name
+ then raise Aliased_node ;
+ Hashtbl.add node_tbl name () ;
+ if depth <= maxdepth
+ then Verbatim ("@node " ^ (Texi.fix_nodename name) ^ ",\n")
+ else nothing
+
+ method index (ind : indices) ent =
+ Verbatim
+ (if !Global.with_index
+ then (assert(List.mem ind indices_to_build) ;
+ String.concat ""
+ [ "@" ; indices ind ; "index " ;
+ Texi.escape (Name.simple ent) ; "\n" ])
+ else "")
+
+
+ (** Two hacks to fix linebreaks in the descriptions.*)
+ method private fix_linebreaks =
+ let re = Str.regexp "\n[ \t]*" in
+ fun t ->
+ List.map
+ (function
+ | Newline -> Raw "\n"
+ | Raw s -> Raw (Str.global_replace re "\n" s)
+ | List tel -> List (List.map self#fix_linebreaks tel)
+ | Enum tel -> Enum (List.map self#fix_linebreaks tel)
+ | txt -> txt) t
+
+ method private soft_fix_linebreaks =
+ let re = Str.regexp "\n[ \t]*" in
+ fun ind t ->
+ let rep = "\n" ^ String.make ind ' ' in
+ List.map
+ (function
+ | Raw s -> Raw (Str.global_replace re rep s)
+ | txt -> txt) t
+
+ (** {3 [text] values generation}
+ Generates [text] values out of description parts.
+ Redefines some of methods of {! Odoc_to_text.to_text}. *)
+
+ method text_of_desc = function
+ | None -> []
+ | Some [ Raw "" ] -> []
+ | Some t -> (self#fix_linebreaks t) @ [ Newline ]
+
+ method text_of_sees_opt see_l =
+ List.concat
+ (List.map
+ (function
+ | (See_url s, t) ->
+ [ linebreak ; Bold [ Raw Odoc_messages.see_also ] ;
+ Raw " " ; Link (s, t) ; Newline ]
+ | (See_file s, t)
+ | (See_doc s, t) ->
+ [ linebreak ; Bold [ Raw Odoc_messages.see_also ] ;
+ Raw " " ; Raw s ] @ t @ [ Newline ])
+ see_l)
+
+ method text_of_before l =
+ List.flatten
+ (List.map
+ (fun x -> linebreak :: (to_text#text_of_before [x])) l)
+
+ method text_of_params params_list =
+ List.concat
+ (List.map
+ (fun (s, t) ->
+ [ linebreak ;
+ Bold [ Raw Odoc_messages.parameters ] ;
+ Raw " " ; Raw s ; Raw ": " ] @ t @ [ Newline ] )
+ params_list)
+
+ method! text_of_raised_exceptions = function
+ | [] -> []
+ | (s, t) :: [] ->
+ [ linebreak ;
+ Bold [ Raw Odoc_messages.raises ] ;
+ Raw " " ; Code s ; Raw " " ]
+ @ t @ [ Newline ]
+ | l ->
+ [ linebreak ;
+ Bold [ Raw Odoc_messages.raises ] ;
+ Raw " :" ;
+ List
+ (List.map
+ (fun (ex, desc) ->(Code ex) :: (Raw " ") :: desc ) l ) ;
+ Newline ]
+
+ method! text_of_return_opt = function
+ | None -> []
+ | Some t ->
+ (Bold [Raw Odoc_messages.returns ]) :: Raw " " :: t @ [ Newline ]
+
+ method! text_of_custom c_l =
+ List.flatten
+ (List.rev
+ (List.fold_left
+ (fun acc -> fun (tag, text) ->
+ try
+ let f = List.assoc tag tag_functions in
+ ( linebreak :: (f text) @ [ Newline ] ) :: acc
+ with
+ Not_found ->
+ Odoc_info.warning (Odoc_messages.tag_not_handled tag) ;
+ acc
+ ) [] c_l))
+
+ method! text_of_info ?(block=false) = function
+ | None -> []
+ | Some info ->
+ let t =
+ List.concat
+ [ ( match info.i_deprecated with
+ | None -> []
+ | Some t ->
+ (Raw (Odoc_messages.deprecated ^ " ")) ::
+ (self#fix_linebreaks t)
+ @ [ Newline ; Newline ] ) ;
+ self#text_of_desc info.i_desc ;
+ if info.i_authors <> []
+ then ( linebreak ::
+ self#text_of_author_list info.i_authors )
+ else [] ;
+ if is info.i_version
+ then ( linebreak ::
+ self#text_of_version_opt info.i_version )
+ else [] ;
+ self#text_of_sees_opt info.i_sees ;
+ self#text_of_before info.i_before ;
+ if is info.i_since
+ then ( linebreak ::
+ self#text_of_since_opt info.i_since )
+ else [] ;
+ self#text_of_params info.i_params ;
+ self#text_of_raised_exceptions info.i_raised_exceptions ;
+ if is info.i_return_value
+ then ( linebreak ::
+ self#text_of_return_opt info.i_return_value )
+ else [] ;
+ self#text_of_custom info.i_custom ;
+ ] in
+ if block
+ then [ Block t ]
+ else (t @ [ Newline ] )
+
+ method texi_of_info i =
+ self#texi_of_text (self#text_of_info i)
+
+ (** {3 Conversion of [module_elements] into Texinfo strings}
+ The following functions convert [module_elements] and their
+ description to [text] values then to Texinfo strings using the
+ functions above. *)
+
+ method text_el_of_type_expr m_name typ =
+ Raw (indent 5
+ (self#relative_idents m_name
+ (Odoc_info.string_of_type_expr typ)))
+
+ method! text_of_short_type_expr m_name typ =
+ [ Raw (self#normal_type m_name typ) ]
+
+ (** Return Texinfo code for a value. *)
+ method texi_of_value v =
+ Odoc_info.reset_type_names () ;
+ let t = [ self#fixedblock
+ [ Newline ; minus ;
+ Raw ("val " ^ (Name.simple v.val_name) ^ " :\n") ;
+ self#text_el_of_type_expr
+ (Name.father v.val_name) v.val_type ] ;
+ self#index `Value v.val_name ; Newline ] @
+ (self#text_of_info v.val_info) in
+ self#texi_of_text t
+
+
+ (** Return Texinfo code for a class attribute. *)
+ method texi_of_attribute a =
+ Odoc_info.reset_type_names () ;
+ let t = [ self#fixedblock
+ [ Newline ; minus ;
+ Raw "val " ;
+ Raw (if a.att_virtual then "virtual " else "") ;
+ Raw (if a.att_mutable then "mutable " else "") ;
+ Raw (Name.simple a.att_value.val_name) ;
+ Raw " :\n" ;
+ self#text_el_of_type_expr
+ (Name.father a.att_value.val_name)
+ a.att_value.val_type ] ;
+ self#index `Class_att a.att_value.val_name ; Newline ] @
+ (self#text_of_info a.att_value.val_info) in
+ self#texi_of_text t
+
+
+ (** Return Texinfo code for a class method. *)
+ method texi_of_method m =
+ Odoc_info.reset_type_names () ;
+ let t = [ self#fixedblock
+ [ Newline ; minus ; Raw "method " ;
+ Raw (if m.met_private then "private " else "") ;
+ Raw (if m.met_virtual then "virtual " else "") ;
+ Raw (Name.simple m.met_value.val_name) ;
+ Raw " :\n" ;
+ self#text_el_of_type_expr
+ (Name.father m.met_value.val_name)
+ m.met_value.val_type ] ;
+ self#index `Method m.met_value.val_name ; Newline ] @
+ (self#text_of_info m.met_value.val_info) in
+ self#texi_of_text t
+
+
+ method string_of_type_parameters t =
+ let f (tp, co, cn) =
+ Printf.sprintf "%s%s"
+ (Odoc_info.string_of_variance t (co, cn))
+ (Odoc_info.string_of_type_expr tp)
+ in
+ match t.ty_parameters with
+ | [] -> ""
+ | [ (tp, co, cn) ] ->
+ (f (tp, co, cn))^" "
+ | l ->
+ Printf.sprintf "(%s) "
+ (String.concat ", " (List.map f l))
+
+ method string_of_type_args (args:constructor_args) (ret:Types.type_expr option) =
+ let f = function
+ | Cstr_tuple l -> Odoc_info.string_of_type_list " * " l
+ | Cstr_record l -> Odoc_info.string_of_record l
+ in
+ match args, ret with
+ | Cstr_tuple [], None -> ""
+ | args, None -> " of " ^ (f args)
+ | Cstr_tuple [], Some r -> " : " ^ (Odoc_info.string_of_type_expr r)
+ | args, Some r -> " : " ^ (f args) ^
+ " -> " ^ (Odoc_info.string_of_type_expr r)
+
+ (** Return Texinfo code for a type. *)
+ method texi_of_type ty =
+ Odoc_info.reset_type_names () ;
+ let entry_doc = function
+ | None -> [ Newline ]
+ | Some t ->
+ (Raw (indent 5 "\n(*\n") :: (self#soft_fix_linebreaks 8 (self#text_of_info (Some t))))
+ @ [ Raw " *)" ; Newline ]
+ in
+ let t =
+ [ self#fixedblock (
+ [ Newline ; minus ; Raw "type " ;
+ Raw (self#string_of_type_parameters ty) ;
+ Raw (Name.simple ty.ty_name) ] @
+ let priv = ty.ty_private = Asttypes.Private in
+ ( match ty.ty_manifest with
+ | None -> []
+ | Some (Other typ) ->
+ (Raw " = ") ::
+ (Raw (if priv then "private " else "")) ::
+ (self#text_of_short_type_expr (Name.father ty.ty_name) typ)
+ | Some (Object_type l) ->
+ (Raw (" = "^(if priv then "private " else "")^"{\n")) ::
+ (List.flatten
+ (List.map
+ (fun r ->
+ [ Raw (" " ^ r.of_name ^ " : ") ] @
+ (self#text_of_short_type_expr
+ (Name.father r.of_name)
+ r.of_type) @
+ [ Raw " ;" ] @
+ (entry_doc r.of_text))
+ l ) )
+ @ [ Raw " }" ]
+ ) @
+ (
+ match ty.ty_kind with
+ | Type_abstract -> [ Newline ]
+ | Type_variant l ->
+ (Raw (" ="^(if priv then " private" else "")^"\n")) ::
+ (List.flatten
+ (List.map
+ (fun constr ->
+ (Raw (" | " ^ constr.vc_name)) ::
+ (Raw (self#string_of_type_args
+ constr.vc_args constr.vc_ret)) ::
+ (entry_doc constr.vc_text)
+ ) l ) )
+ | Type_record l ->
+ (Raw (" = "^(if priv then "private " else "")^"{\n")) ::
+ (List.flatten
+ (List.map
+ (fun r ->
+ [ Raw (" " ^ r.rf_name ^ " : ") ] @
+ (self#text_of_short_type_expr
+ (Name.father r.rf_name)
+ r.rf_type) @
+ [ Raw " ;" ] @
+ (entry_doc r.rf_text)
+ )
+ l ) )
+ @ [ Raw " }" ]
+ | Type_open -> [ Raw " = .." ; Newline ]
+ ) ) ;
+ self#index `Type ty.ty_name ; Newline ] @
+ (self#text_of_info ty.ty_info) in
+ self#texi_of_text t
+
+ (** Return Texinfo code for a type extension. *)
+ method texi_of_type_extension m_name te =
+ Odoc_info.reset_type_names () ;
+ let t =
+ ( self#fixedblock (
+ [ Newline ; minus ;
+ Raw "type " ;
+ Raw (match te.te_type_parameters with
+ | [] -> ""
+ | [ tp ] ->
+ Printf.sprintf "%s "
+ (Odoc_info.string_of_type_expr tp)
+ | l ->
+ Printf.sprintf "(%s) "
+ (String.concat ", "
+ (List.map Odoc_info.string_of_type_expr l))) ;
+ Raw (self#relative_idents m_name te.te_type_name) ;
+ Raw (" +=" ^
+ (if te.te_private = Asttypes.Private
+ then " private" else "")^"\n") ] @
+ (List.flatten
+ (List.map
+ (fun x ->
+ (Raw (" | " ^ (Name.simple x.xt_name))) ::
+ (Raw (self#string_of_type_args
+ x.xt_args x.xt_ret)) ::
+ (match x.xt_alias with
+ | None -> []
+ | Some xa ->
+ [ Raw " = " ;
+ Raw ( match xa.xa_xt with
+ | None -> xa.xa_name
+ | Some x -> x.xt_name ) ]) @
+ (match x.xt_text with
+ | None -> [ Newline ]
+ | Some t ->
+ (Raw (indent 5 "\n(* ") ::
+ self#soft_fix_linebreaks 8
+ (self#text_of_info (Some t))) @
+ [ Raw " *)" ; Newline ] ) @
+ [self#index `Extension x.xt_name ] )
+ te.te_constructors ) ) ) ) ::
+ (self#text_of_info te.te_info) in
+ self#texi_of_text t
+
+ (** Return Texinfo code for an exception. *)
+ method texi_of_exception e =
+ Odoc_info.reset_type_names () ;
+ let t =
+ [ self#fixedblock
+ ( [ Newline ; minus ; Raw "exception " ;
+ Raw (Name.simple e.ex_name) ;
+ Raw (self#string_of_type_args e.ex_args e.ex_ret) ] @
+ (match e.ex_alias with
+ | None -> []
+ | Some ea -> [ Raw " = " ; Raw
+ ( match ea.ea_ex with
+ | None -> ea.ea_name
+ | Some e -> e.ex_name ) ; ]
+ ) ) ;
+ self#index `Exception e.ex_name ; Newline ] @
+ (self#text_of_info e.ex_info) in
+ self#texi_of_text t
+
+
+ (** Return the Texinfo code for the given module. *)
+ method texi_of_module m =
+ let is_alias = function
+ | { m_kind = Module_alias _ } -> true
+ | _ -> false in
+ let is_alias_there = function
+ | { m_kind = Module_alias { ma_module = None } } -> false
+ | _ -> true in
+ let resolve_alias_name = function
+ | { m_kind = Module_alias { ma_name = name } } -> name
+ | { m_name = name } -> name in
+ let t =
+ [ [ self#fixedblock
+ [ Newline ; minus ; Raw "module " ;
+ Raw (Name.simple m.m_name) ;
+ Raw (if is_alias m
+ then " = " ^ (resolve_alias_name m)
+ else "" ) ] ] ;
+ ( if is_alias_there m
+ then [ Ref (resolve_alias_name m, Some RK_module, None) ;
+ Newline ; ]
+ else [] ) ;
+ ( if is_alias m
+ then [ self#index `Module m.m_name ; Newline ]
+ else [ Newline ] ) ;
+ self#text_of_info m.m_info ]
+ in
+ self#texi_of_text (List.flatten t)
+
+ (** Return the Texinfo code for the given module type. *)
+ method texi_of_module_type mt =
+ let is_alias = function
+ | { mt_kind = Some (Module_type_alias _) } -> true
+ | _ -> false in
+ let is_alias_there = function
+ | { mt_kind = Some (Module_type_alias { mta_module = None }) } -> false
+ | _ -> true in
+ let resolve_alias_name = function
+ | { mt_kind = Some (Module_type_alias { mta_name = name }) } -> name
+ | { mt_name = name } -> name in
+ let t =
+ [ [ self#fixedblock
+ [ Newline ; minus ; Raw "module type " ;
+ Raw (Name.simple mt.mt_name) ;
+ Raw (if is_alias mt
+ then " = " ^ (resolve_alias_name mt)
+ else "" ) ] ] ;
+ ( if is_alias_there mt
+ then [ Ref (resolve_alias_name mt, Some RK_module_type, None) ;
+ Newline ; ]
+ else [] ) ;
+ ( if is_alias mt
+ then [ self#index `Module_type mt.mt_name ; Newline ]
+ else [ Newline ] ) ;
+ self#text_of_info mt.mt_info ]
+ in
+ self#texi_of_text (List.flatten t)
+
+ (** Return the Texinfo code for the given included module. *)
+ method texi_of_included_module im =
+ let t = [ self#fixedblock
+ ( Newline :: minus :: (Raw "include ") ::
+ ( match im.im_module with
+ | None ->
+ [ Raw im.im_name ]
+ | Some (Mod { m_name = name }) ->
+ [ Raw name ; Raw "\n " ;
+ Ref (name, Some RK_module, None) ]
+ | Some (Modtype { mt_name = name }) ->
+ [ Raw name ; Raw "\n " ;
+ Ref (name, Some RK_module_type, None) ]
+ ) @
+ [ Newline ] @
+ (self#text_of_info im.im_info)
+ )
+ ]
+ in
+ self#texi_of_text t
+
+ (** Return the Texinfo code for the given class. *)
+ method texi_of_class c =
+ Odoc_info.reset_type_names () ;
+ let t = [ self#fixedblock
+ [ Newline ; minus ; Raw "class " ;
+ Raw (Name.simple c.cl_name) ] ;
+ Ref (c.cl_name, Some RK_class, None) ; Newline ;
+ Newline ] @ (self#text_of_info c.cl_info) in
+ self#texi_of_text t
+
+ (** Return the Texinfo code for the given class type. *)
+ method texi_of_class_type ct =
+ Odoc_info.reset_type_names () ;
+ let t = [ self#fixedblock
+ [ Newline ; minus ; Raw "class type " ;
+ Raw (Name.simple ct.clt_name) ] ;
+ Ref (ct.clt_name, Some RK_class_type, None) ; Newline ;
+ Newline ] @ (self#text_of_info ct.clt_info) in
+ self#texi_of_text t
+
+ (** Return the Texinfo code for the given class element. *)
+ method texi_of_class_element class_name class_ele =
+ match class_ele with
+ | Class_attribute att -> self#texi_of_attribute att
+ | Class_method met -> self#texi_of_method met
+ | Class_comment t -> self#texi_of_text t
+
+ (** Return the Texinfo code for the given module element. *)
+ method texi_of_module_element module_name module_ele =
+ (match module_ele with
+ | Element_module m -> self#texi_of_module m
+ | Element_module_type mt -> self#texi_of_module_type mt
+ | Element_included_module im -> self#texi_of_included_module im
+ | Element_class c -> self#texi_of_class c
+ | Element_class_type ct -> self#texi_of_class_type ct
+ | Element_value v -> self#texi_of_value v
+ | Element_type_extension te -> self#texi_of_type_extension module_name te
+ | Element_exception e -> self#texi_of_exception e
+ | Element_type t -> self#texi_of_type t
+ | Element_module_comment t ->
+ self#texi_of_text (Newline :: t @ [Newline])
+ )
+
+ (** {3 Generating methods }
+ These methods write Texinfo code to an [out_channel] *)
+
+ (** Generate the Texinfo code for the given list of inherited classes.*)
+ method generate_inheritance_info chanout inher_l =
+ let f inh =
+ match inh.ic_class with
+ | None -> (* we can't make the reference *)
+ (Code inh.ic_name) ::
+ (match inh.ic_text with
+ | None -> []
+ | Some t -> Newline :: t)
+ | Some cct -> (* we can create the reference *)
+ let kind =
+ match cct with
+ | Cl _ -> Some RK_class
+ | Cltype _ -> Some RK_class_type in
+ (Code inh.ic_name) ::
+ (Ref (inh.ic_name, kind, None)) ::
+ ( match inh.ic_text with
+ | None -> []
+ | Some t -> Newline :: t)
+ in
+ let text = [
+ Bold [ Raw Odoc_messages.inherits ] ;
+ List (List.map f inher_l) ; Newline ]
+ in
+ puts chanout (self#texi_of_text text)
+
+
+
+ (** Generate the Texinfo code for the inherited classes
+ of the given class. *)
+ method generate_class_inheritance_info chanout cl =
+ let rec iter_kind = function
+ | Class_structure ([], _) -> ()
+ | Class_structure (l, _) ->
+ self#generate_inheritance_info chanout l
+ | Class_constraint (k, _) -> iter_kind k
+ | Class_apply _
+ | Class_constr _ -> ()
+ in
+ iter_kind cl.cl_kind
+
+
+
+ (** Generate the Texinfo code for the inherited classes
+ of the given class type. *)
+ method generate_class_type_inheritance_info chanout clt =
+ match clt.clt_kind with
+ | Class_signature ([], _) ->
+ ()
+ | Class_signature (l, _) ->
+ self#generate_inheritance_info chanout l
+ | Class_type _ ->
+ ()
+
+ (** Generate the Texinfo code for the given class,
+ in the given out channel. *)
+ method generate_for_class chanout c =
+ try
+ Odoc_info.reset_type_names () ;
+ let depth = Name.depth c.cl_name in
+ let title = [
+ self#node depth c.cl_name ;
+ Title (depth, None, [ Raw (Odoc_messages.clas ^ " ") ;
+ Code c.cl_name ]) ;
+ self#index `Class c.cl_name ] in
+ puts chanout (self#texi_of_text title) ;
+
+ if is c.cl_info
+ then begin
+ let descr = [ Title (succ depth, None,
+ [ Raw Odoc_messages.description ]) ] in
+ puts chanout (self#texi_of_text descr) ;
+ puts chanout (self#texi_of_info c.cl_info)
+ end ;
+
+ let intf = [ Title (succ depth, None,
+ [ Raw Odoc_messages.interface]) ] in
+ puts chanout (self#texi_of_text intf);
+ self#generate_class_inheritance_info chanout c ;
+ List.iter
+ (fun ele -> puts chanout
+ (self#texi_of_class_element c.cl_name ele))
+ (Class.class_elements ~trans:false c)
+ with Aliased_node -> ()
+
+
+ (** Generate the Texinfo code for the given class type,
+ in the given out channel. *)
+ method generate_for_class_type chanout ct =
+ try
+ Odoc_info.reset_type_names () ;
+ let depth = Name.depth ct.clt_name in
+ let title = [
+ self#node depth ct.clt_name ;
+ Title (depth, None, [ Raw (Odoc_messages.class_type ^ " ") ;
+ Code ct.clt_name ]) ;
+ self#index `Class_type ct.clt_name ] in
+ puts chanout (self#texi_of_text title) ;
+
+ if is ct.clt_info
+ then begin
+ let descr = [ Title (succ depth, None,
+ [ Raw Odoc_messages.description ]) ] in
+ puts chanout (self#texi_of_text descr) ;
+ puts chanout (self#texi_of_info ct.clt_info)
+ end ;
+
+ let intf = [ Title (succ depth, None,
+ [ Raw Odoc_messages.interface ]) ] in
+ puts chanout (self#texi_of_text intf) ;
+ self#generate_class_type_inheritance_info chanout ct;
+ List.iter
+ (fun ele -> puts chanout
+ (self#texi_of_class_element ct.clt_name ele))
+ (Class.class_type_elements ~trans:false ct)
+ with Aliased_node -> ()
+
+
+ (** Generate the Texinfo code for the given module type,
+ in the given out channel. *)
+ method generate_for_module_type chanout mt =
+ try
+ let depth = Name.depth mt.mt_name in
+ let title = [
+ self#node depth mt.mt_name ;
+ Title (depth, None, [ Raw (Odoc_messages.module_type ^ " ") ;
+ Code mt.mt_name ]) ;
+ self#index `Module_type mt.mt_name ; Newline ] in
+ puts chanout (self#texi_of_text title) ;
+
+ if is mt.mt_info
+ then begin
+ let descr = [ Title (succ depth, None,
+ [ Raw Odoc_messages.description ]) ] in
+ puts chanout (self#texi_of_text descr) ;
+ puts chanout (self#texi_of_info mt.mt_info)
+ end ;
+
+ let mt_ele = Module.module_type_elements ~trans:true mt in
+ let subparts = module_subparts mt_ele in
+ if depth < maxdepth && subparts <> []
+ then begin
+ let menu = Texi.ifinfo
+ ( self#heading (succ depth) [ Raw "Subparts" ]) in
+ puts chanout menu ;
+ Texi.generate_menu chanout (subparts :> menu_data)
+ end ;
+
+ let intf = [ Title (succ depth, None,
+ [ Raw Odoc_messages.interface ]) ] in
+ puts chanout (self#texi_of_text intf) ;
+ List.iter
+ (fun ele -> puts chanout
+ (self#texi_of_module_element mt.mt_name ele))
+ mt_ele ;
+
+ (* create sub parts for modules, module types, classes and class types *)
+ List.iter
+ (function
+ | `Module m -> self#generate_for_module chanout m
+ | `Module_type mt -> self#generate_for_module_type chanout mt
+ | `Class c -> self#generate_for_class chanout c
+ | `Class_type ct -> self#generate_for_class_type chanout ct)
+ subparts
+ with Aliased_node -> ()
+
+ (** Generate the Texinfo code for the given module,
+ in the given out channel. *)
+ method generate_for_module chanout m =
+ try
+ Odoc_info.verbose ("Generate for module " ^ m.m_name) ;
+ let depth = Name.depth m.m_name in
+ let title = [
+ self#node depth m.m_name ;
+ Title (depth, None,
+ if m.m_text_only then
+ [ Raw m.m_name ]
+ else
+ [ Raw (Odoc_messages.modul ^ " ") ;
+ Code m.m_name ]
+ ) ;
+ self#index `Module m.m_name ; Newline ] in
+ puts chanout (self#texi_of_text title) ;
+
+ if is m.m_info
+ then begin
+ let descr = [ Title (succ depth, None,
+ [ Raw Odoc_messages.description ]) ] in
+ puts chanout (self#texi_of_text descr) ;
+ puts chanout (self#texi_of_info m.m_info)
+ end ;
+
+ let m_ele = Module.module_elements ~trans:true m in
+ let subparts = module_subparts m_ele in
+ if depth < maxdepth && subparts <> []
+ then begin
+ let menu = Texi.ifinfo
+ ( self#heading (succ depth) [ Raw "Subparts" ]) in
+ puts chanout menu ;
+ Texi.generate_menu chanout (subparts :> menu_data)
+ end ;
+
+ let intf = [ Title (succ depth, None,
+ [ Raw Odoc_messages.interface]) ] in
+ puts chanout (self#texi_of_text intf) ;
+
+ List.iter
+ (fun ele -> puts chanout
+ (self#texi_of_module_element m.m_name ele))
+ m_ele ;
+
+ (* create sub nodes for modules, module types, classes and class types *)
+ List.iter
+ (function
+ | `Module m -> self#generate_for_module chanout m
+ | `Module_type mt -> self#generate_for_module_type chanout mt
+ | `Class c -> self#generate_for_class chanout c
+ | `Class_type ct -> self#generate_for_class_type chanout ct )
+ subparts
+ with Aliased_node -> ()
+
+
+ (** Writes the header of the TeXinfo document. *)
+ method generate_texi_header chan texi_filename m_list =
+ let title = match !Global.title with
+ | None -> ""
+ | Some s -> self#escape s in
+ let filename =
+ if texi_filename <> "ocamldoc.texi"
+ then
+ let fn = Filename.basename texi_filename in
+ (if Filename.check_suffix fn ".texi"
+ then Filename.chop_suffix fn ".texi"
+ else fn) ^ ".info"
+ else
+ if title <> ""
+ then title ^ ".info"
+ else "doc.info"
+ in
+ (* write a standard Texinfo header *)
+ List.iter
+ (puts_nl chan)
+ (List.flatten
+ [ [ "\\input texinfo @c -*-texinfo-*-" ;
+ "@c %**start of header" ;
+ "@setfilename " ^ filename ;
+ "@settitle " ^ title ;
+ "@c %**end of header" ; ] ;
+
+ (if !Global.with_index then
+ List.map
+ (fun ind ->
+ "@defcodeindex " ^ (indices ind))
+ indices_to_build
+ else []) ;
+
+ [ Texi.dirsection !info_section ] ;
+
+ Texi.direntry
+ (if !info_entry <> []
+ then !info_entry
+ else [ Printf.sprintf "* %s: (%s)."
+ title
+ (Filename.chop_suffix filename ".info") ]) ;
+
+ [ "@ifinfo" ;
+ "This file was generated by Ocamldoc using the Texinfo generator." ;
+ "@end ifinfo" ;
+
+ "@c no titlepage." ;
+
+ "@node Top, , , (dir)" ;
+ "@top "^ title ; ]
+ ] ) ;
+
+ (* insert the intro file *)
+ begin
+ match !Odoc_info.Global.intro_file with
+ | None when title <> "" ->
+ puts_nl chan "@ifinfo" ;
+ puts_nl chan ("Documentation for " ^ title) ;
+ puts_nl chan "@end ifinfo"
+ | None ->
+ puts_nl chan "@c no title given"
+ | Some f ->
+ nl chan ;
+ puts_nl chan
+ (self#texi_of_info
+ (Some (Odoc_info.info_of_comment_file m_list f)))
+ end ;
+
+ (* write a top menu *)
+ Texi.generate_menu chan
+ ((List.map (fun m -> `Module m) m_list) @
+ (if !Global.with_index then
+ let indices_names_to_build = List.map indices indices_to_build in
+ List.rev
+ (List.fold_left
+ (fun acc ->
+ function (longname, shortname)
+ when List.mem shortname indices_names_to_build ->
+ (`Index (longname ^ " index")) :: acc
+ | _ -> acc)
+ [ `Comment "Indices :" ; `Blank ]
+ indices_names )
+ else [] ))
+
+
+ (** Writes the trailer of the TeXinfo document. *)
+ method generate_texi_trailer chan =
+ nl chan ;
+ if !Global.with_index
+ then
+ let indices_names_to_build = List.map indices indices_to_build in
+ List.iter (puts_nl chan)
+ (List.flatten
+ (List.map
+ (fun (longname, shortname) ->
+ if List.mem shortname indices_names_to_build
+ then [ "@node " ^ longname ^ " index," ;
+ "@unnumbered " ^ longname ^ " index" ;
+ "@printindex " ^ shortname ; ]
+ else [])
+ indices_names )) ;
+ if !Global.with_toc
+ then puts_nl chan "@contents" ;
+ puts_nl chan "@bye"
+
+
+ method do_index it =
+ if not (List.mem it indices_to_build)
+ then indices_to_build <- it :: indices_to_build
+
+ (** Scan the whole module information to know which indices need to be build *)
+ method scan_for_index : subparts -> unit = function
+ | `Module m ->
+ let m_ele = Module.module_elements ~trans:true m in
+ List.iter self#scan_for_index_in_mod m_ele
+ | `Module_type mt ->
+ let m_ele = Module.module_type_elements ~trans:true mt in
+ List.iter self#scan_for_index_in_mod m_ele
+ | `Class c ->
+ let c_ele = Class.class_elements ~trans:true c in
+ List.iter self#scan_for_index_in_class c_ele
+ | `Class_type ct ->
+ let c_ele = Class.class_type_elements ~trans:true ct in
+ List.iter self#scan_for_index_in_class c_ele
+
+ method scan_for_index_in_mod = function
+ (* no recursion *)
+ | Element_value _ -> self#do_index `Value
+ | Element_type_extension _ -> self#do_index `Extension
+ | Element_exception _ -> self#do_index `Exception
+ | Element_type _ -> self#do_index `Type
+ | Element_included_module _
+ | Element_module_comment _ -> ()
+ (* recursion *)
+ | Element_module m -> self#do_index `Module ;
+ self#scan_for_index (`Module m)
+ | Element_module_type mt -> self#do_index `Module_type ;
+ self#scan_for_index (`Module_type mt)
+ | Element_class c -> self#do_index `Class ;
+ self#scan_for_index (`Class c)
+ | Element_class_type ct -> self#do_index `Class_type ;
+ self#scan_for_index (`Class_type ct)
+
+ method scan_for_index_in_class = function
+ | Class_attribute _ -> self#do_index `Class_att
+ | Class_method _ -> self#do_index `Method
+ | Class_comment _ -> ()
+
+
+ (** Generate the Texinfo file from a module list,
+ in the {!Odoc_info.Global.out_file} file. *)
+ method generate module_list =
+ Hashtbl.clear node_tbl ;
+ let filename =
+ if !Global.out_file = Odoc_messages.default_out_file
+ then "ocamldoc.texi"
+ else !Global.out_file in
+ if !Global.with_index
+ then List.iter self#scan_for_index
+ (List.map (fun m -> `Module m) module_list) ;
+ try
+ let chanout = open_out
+ (Filename.concat !Global.target_dir filename) in
+ if !Global.with_header
+ then self#generate_texi_header chanout filename module_list ;
+ List.iter
+ (self#generate_for_module chanout)
+ module_list ;
+ if !Global.with_trailer
+ then self#generate_texi_trailer chanout ;
+ close_out chanout
+ with
+ | Failure s
+ | Sys_error s ->
+ prerr_endline s ;
+ incr Odoc_info.errors
+ end
+end
+
+module type Texi_generator = module type of Generator
diff --git a/ocamldoc/odoc_text.ml b/ocamldoc/odoc_text.ml
new file mode 100644
index 0000000000..eb3c562691
--- /dev/null
+++ b/ocamldoc/odoc_text.ml
@@ -0,0 +1,166 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+exception Text_syntax of int * int * string (* line, char, string *)
+
+open Odoc_types
+
+module Texter =
+ struct
+ (* builds a text structure from a string. *)
+ let text_of_string s =
+ let lexbuf = Lexing.from_string s in
+ try
+ Odoc_text_lexer.init ();
+ Odoc_text_parser.main Odoc_text_lexer.main lexbuf
+ with
+ _ ->
+ raise (Text_syntax (!Odoc_text_lexer.line_number,
+ !Odoc_text_lexer.char_number,
+ s)
+ )
+
+ let count s c =
+ let count = ref 0 in
+ for i = 0 to String.length s - 1 do
+ if s.[i] = c then incr count
+ done;
+ !count
+
+ let escape_n s c n =
+ let remain = ref n in
+ let len = String.length s in
+ let b = Buffer.create (len + n) in
+ for i = 0 to len - 1 do
+ if s.[i] = c && !remain > 0 then
+ (
+ Printf.bprintf b "\\%c" c;
+ decr remain
+ )
+ else
+ Buffer.add_char b s.[i]
+ done;
+ Buffer.contents b
+
+ let escape_code s =
+ let open_brackets = count s '[' in
+ let close_brackets = count s ']' in
+ if open_brackets > close_brackets then
+ escape_n s '[' (open_brackets - close_brackets)
+ else
+ if close_brackets > open_brackets then
+ escape_n s ']' (close_brackets - open_brackets)
+ else
+ s
+
+ let escape_raw s =
+ let len = String.length s in
+ let b = Buffer.create len in
+ for i = 0 to len - 1 do
+ match s.[i] with
+ '[' | ']' | '{' | '}' ->
+ Printf.bprintf b "\\%c" s.[i]
+ | c ->
+ Buffer.add_char b c
+ done;
+ Buffer.contents b
+
+ let p = Printf.bprintf
+
+ let rec p_text b t =
+ List.iter (p_text_element b) t
+
+ and p_list b l =
+ List.iter
+ (fun t -> p b "{- " ; p_text b t ; p b "}\n")
+ l
+
+ and p_text_element b = function
+ | Raw s -> p b "%s" (escape_raw s)
+ | Code s -> p b "[%s]" (escape_code s)
+ | CodePre s -> p b "{[%s]}" s
+ | Verbatim s -> p b "{v %s v}" s
+ | Bold t -> p b "{b " ; p_text b t ; p b "}"
+ | Italic t -> p b "{i " ; p_text b t ; p b "}"
+ | Emphasize t -> p b "{e " ; p_text b t ; p b "}"
+ | Center t -> p b "{C " ; p_text b t ; p b "}"
+ | Left t -> p b "{L " ; p_text b t ; p b "}"
+ | Right t -> p b "{R " ; p_text b t ; p b "}"
+ | List l -> p b "{ul\n"; p_list b l; p b "}"
+ | Enum l -> p b "{ol\n"; p_list b l; p b "}"
+ | Newline -> p b "\n"
+ | Block t -> p_text b t
+ | Title (n, l_opt, t) ->
+ p b "{%d%s "
+ n
+ (match l_opt with
+ None -> ""
+ | Some s -> ":"^s
+ );
+ p_text b t ;
+ p b "}"
+ | Latex s -> p b "{%% %s%%}" s
+ | Link (s,t) ->
+ p b "{{:%s}" s;
+ p_text b t ;
+ p b "}"
+ | Ref (name, kind_opt, text_opt) ->
+ begin
+ p b "%s{!%s%s}"
+ (match text_opt with None -> "" | Some _ -> "{")
+ (match kind_opt with
+ None -> ""
+ | Some k ->
+ let s =
+ match k with
+ RK_module -> "module"
+ | RK_module_type -> "modtype"
+ | RK_class -> "class"
+ | RK_class_type -> "classtype"
+ | RK_value -> "val"
+ | RK_type -> "type"
+ | RK_extension -> "extension"
+ | RK_exception -> "exception"
+ | RK_attribute -> "attribute"
+ | RK_method -> "method"
+ | RK_section _ -> "section"
+ | RK_recfield -> "recfield"
+ | RK_const -> "const"
+ in
+ s^":"
+ )
+ name;
+ match text_opt with
+ None -> ()
+ | Some t -> p_text b t; p b "}"
+ end
+ | Superscript t -> p b "{^" ; p_text b t ; p b "}"
+ | Subscript t -> p b "{_" ; p_text b t ; p b "}"
+ | Module_list l ->
+ p b "{!modules:";
+ List.iter (fun s -> p b " %s" s) l;
+ p b "}"
+ | Index_list ->
+ p b "{!indexlist}"
+ | Custom (s,t) ->
+ p b "{%s " s;
+ p_text b t;
+ p b "}"
+ | Target (target, code) ->
+ p b "{%%%s: %s}" target (escape_raw code)
+
+ let string_of_text s =
+ let b = Buffer.create 256 in
+ p_text b s;
+ Buffer.contents b
+
+ end
diff --git a/ocamldoc/odoc_text.mli b/ocamldoc/odoc_text.mli
new file mode 100644
index 0000000000..fc4f33064a
--- /dev/null
+++ b/ocamldoc/odoc_text.mli
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** A module with a function to parse strings to obtain a [Odoc_types.text] value. *)
+
+(** Syntax error in a text. *)
+exception Text_syntax of int * int * string (* line, char, string *)
+
+(** Transformation of strings to text structures. *)
+module Texter :
+ sig
+ val text_of_string : string -> Odoc_types.text
+ val string_of_text : Odoc_types.text -> string
+ end
diff --git a/ocamldoc/odoc_text_lexer.mll b/ocamldoc/odoc_text_lexer.mll
new file mode 100644
index 0000000000..fd1735419c
--- /dev/null
+++ b/ocamldoc/odoc_text_lexer.mll
@@ -0,0 +1,854 @@
+{
+(***********************************************************************)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The lexer for string to build text structures. *)
+
+open Lexing
+open Odoc_text_parser
+
+let line_number = ref 0
+let char_number = ref 0
+
+let string_buffer = Buffer.create 32
+
+(** Fonction de remise a zero de la chaine de caracteres tampon *)
+let reset_string_buffer () = Buffer.reset string_buffer
+
+(** Fonction d'ajout d'un caractere dans la chaine de caracteres tampon *)
+let ajout_char_string = Buffer.add_char string_buffer
+
+(** Add a string to the buffer. *)
+let ajout_string = Buffer.add_string string_buffer
+
+let lecture_string () = Buffer.contents string_buffer
+
+
+(** the variable which will contain the description string.
+ Is initialized when we encounter the start of a special comment. *)
+
+let description = ref ""
+
+let blank = "[ \013\009\012]"
+
+
+let print_DEBUG s = print_string s; print_newline ()
+
+(** this flag indicates whether we're in a string between begin_code and end_code tokens, to
+ remember the number of open '[' and handle ']' correctly. *)
+let open_brackets = ref 0
+
+(** this flag indicates if we're in verbatim mode or not, to handle any special expression
+ like a string when we're in verbatim mode.*)
+let verb_mode = ref false
+
+(** this flag indicates if we're in "target format" mode or not, to handle any special expression
+ like a string when we're in this mode.*)
+let target_mode = ref false
+
+(** this flag indicates if we're in shortcut list mode or not, to handle end_shortcut_list correctly.*)
+let shortcut_list_mode = ref false
+
+(** this flag indicates if we're in an element reference. *)
+let ele_ref_mode = ref false
+
+(** this flag indicates if we're in a preformatted code string. *)
+let code_pre_mode = ref false
+
+let init () =
+ open_brackets := 0;
+ verb_mode := false;
+ target_mode := false;
+ shortcut_list_mode := false;
+ ele_ref_mode := false ;
+ code_pre_mode := false ;
+ line_number := 0 ;
+ char_number := 0
+
+let incr_cpts lexbuf =
+ let s = Lexing.lexeme lexbuf in
+ let l = Str.split_delim (Str.regexp_string "\n") s in
+ match List.rev l with
+ [] -> () (* should not occur *)
+ | [s2] -> (* no newline *)
+ char_number := !char_number + (String.length s2)
+ | s2 :: _ ->
+ line_number := !line_number + ((List.length l) - 1) ;
+ char_number := String.length s2
+
+}
+
+(** html marks, to use as alternative possible special strings *)
+
+let html_bold = "<"('b'|'B')">"
+let html_end_bold = "</"('b'|'B')">"
+let html_italic = "<"('i'|'I')">"
+let html_end_italic = "</"('i'|'I')">"
+let html_title = "<"('h'|'H')(['0'-'9'])+">"
+let html_end_title = "</"('h'|'H')(['0'-'9'])+">"
+let html_list = "<"('u'|'U')('l'|'L')">"
+let html_end_list = "</"('u'|'U')('l'|'L')">"
+let html_enum = "<"('o'|'O')('l'|'L')">"
+let html_end_enum = "</"('o'|'O')('l'|'L')">"
+let html_item = "<"('l'|'L')('i'|'I')">"
+let html_end_item = "</"('l'|'L')('i'|'I')">"
+let html_code = "<"('c'|'C')('o'|'O')('d'|'D')('e'|'E')">"
+let html_end_code = "</"('c'|'C')('o'|'O')('d'|'D')('e'|'E')">"
+let html_center = "<"('c'|'C')('e'|'E')('n'|'N')('t'|'T')('e'|'E')('r'|'R')">"
+let html_end_center = "</"('c'|'C')('e'|'E')('n'|'N')('t'|'T')('e'|'E')('r'|'R')">"
+let html_left = "<"('l'|'L')('e'|'E')('f'|'F')('t'|'T')">"
+let html_end_left = "</"('l'|'L')('e'|'E')('f'|'F')('t'|'T')">"
+let html_right = "<"('r'|'R')('i'|'I')('g'|'G')('h'|'H')('t'|'T')">"
+let html_end_right = "</"('r'|'R')('i'|'I')('g'|'G')('h'|'H')('t'|'T')">"
+
+
+let blank = [' ' '\013' '\009' '\012']
+let blank_nl = [' ' '\013' '\009' '\012' '\010']
+let label = ['a'-'z']+['a'-'z' 'A'-'Z' '0'-'9' '_']*
+
+(** special strings *)
+
+let end = "}"
+ | html_end_bold
+ | html_end_italic
+ | html_end_title
+ | html_end_list
+ | html_end_enum
+ | html_end_item
+ | html_end_center
+let begin_title =
+ ("{" ['0'-'9']+(":"label)? blank_nl)
+ | html_title
+
+let begin_bold = "{b"blank_nl | html_bold
+let begin_emp = "{e"blank_nl
+let begin_center = "{C"blank_nl | html_center
+let begin_left = "{L"blank_nl
+let begin_right = "{R"blank_nl
+let begin_italic = "{i"blank_nl | html_italic
+let begin_list = "{ul"blank_nl? | html_list
+let begin_enum = "{ol"blank_nl? | html_enum
+let begin_item = "{li"blank_nl | "{- " | html_item
+let begin_link = "{{:"
+let begin_target = "{%"['a'-'z''A'-'Z''0'-'9''-''_']+":"blank_nl?
+let begin_latex = "{%"blank_nl
+let end_target = "%}"
+let begin_code = "[" | html_code
+let end_code = "]" | html_end_code
+let begin_code_pre = "{["
+let end_code_pre = "]}"
+let begin_verb = "{v"blank_nl
+let end_verb = blank_nl"v}"
+
+let begin_ele_ref = "{!"blank_nl | "{!"
+let begin_val_ref = "{!val:"blank_nl | "{!val:"
+let begin_typ_ref = "{!type:"blank_nl | "{!type:"
+let begin_ext_ref = "{!extension:"blank_nl | "{!extension:"
+let begin_exc_ref = "{!exception:"blank_nl | "{!exception:"
+let begin_mod_ref = "{!module:"blank_nl | "{!module:"
+let begin_modt_ref = "{!modtype:"blank_nl | "{!modtype:"
+let begin_cla_ref = "{!class:"blank_nl | "{!class:"
+let begin_clt_ref = "{!classtype:"blank_nl | "{!classtype:"
+let begin_att_ref = "{!attribute:"blank_nl | "{!attribute:"
+let begin_met_ref = "{!method:"blank_nl | "{!method:"
+let begin_sec_ref = "{!section:"blank_nl | "{!section:"
+let begin_recf_ref = "{!recfield:"blank_nl | "{!recfield:"
+let begin_const_ref = "{!const:"blank_nl | "{!const:"
+let begin_mod_list_ref = "{!modules:"blank_nl | "{!modules:"
+let index_list = "{!indexlist}"
+let begin_custom = "{"['a'-'z''A'-'Z']['a'-'z''A'-'Z''0'-'9']*
+let begin_superscript = "{^"blank_nl | "{^"
+let begin_subscript = "{_"blank_nl | "{_"
+
+let shortcut_list_item = '\n'blank*"- "
+let shortcut_enum_item = '\n'blank*"+ "
+let end_shortcut_list = '\n'(blank*'\n')+
+
+rule main = parse
+| "\\{"
+| "\\}"
+| "\\["
+| "\\]"
+ {
+ incr_cpts lexbuf ;
+ let s = Lexing.lexeme lexbuf in
+ Char (String.sub s 1 1)
+ }
+
+| end
+ {
+ print_DEBUG "end";
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) then
+ Char (Lexing.lexeme lexbuf)
+ else
+ let _ =
+ if !ele_ref_mode then
+ ele_ref_mode := false
+ in
+ END
+ }
+| begin_title
+ {
+ print_DEBUG "begin_title";
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ let s = Lexing.lexeme lexbuf in
+ try
+ (* chech if the "{..." or html_title mark was used. *)
+ if s.[0] = '<' then
+ let (n, l) = (2, (String.length s - 3)) in
+ let s2 = String.sub s n l in
+ Title (int_of_string s2, None)
+ else
+ let (n, l) = (1, (String.length s - 2)) in
+ let s2 = String.sub s n l in
+ try
+ let i = String.index s2 ':' in
+ let s_n = String.sub s2 0 i in
+ let s_label = String.sub s2 (i+1) (l-i-1) in
+ Title (int_of_string s_n, Some s_label)
+ with
+ Not_found ->
+ Title (int_of_string s2, None)
+ with
+ _ ->
+ Title (1, None)
+ }
+| begin_bold
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ BOLD
+ }
+| begin_italic
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ ITALIC
+ }
+| begin_link
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ LINK
+ }
+| begin_emp
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ EMP
+ }
+| begin_superscript
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ SUPERSCRIPT
+ }
+| begin_subscript
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ SUBSCRIPT
+ }
+| begin_center
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ CENTER
+ }
+| begin_left
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ LEFT
+ }
+| begin_right
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode
+ || (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ RIGHT
+ }
+| begin_list
+ {
+ print_DEBUG "LIST";
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ LIST
+ }
+| begin_enum
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ ENUM
+ }
+| begin_item
+ {
+ print_DEBUG "ITEM";
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ ITEM
+ }
+| begin_target
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ (
+ let s = Lexing.lexeme lexbuf in
+ let fmt =
+ let p1 = String.index s '%' in
+ let p2 = String.index s ':' in
+ String.sub s (p1 + 1) (p2 - p1 - 1)
+ in
+ target_mode := true;
+ Target fmt
+ )
+ }
+| begin_latex
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ (
+ target_mode := true;
+ LATEX
+ )
+ }
+| end_target
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || (!open_brackets >= 1) || !code_pre_mode ||
+ !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ (
+ target_mode := false;
+ END_TARGET
+ )
+ }
+| begin_code end_code
+ {
+ incr_cpts lexbuf ;
+ Char (Lexing.lexeme lexbuf)
+ }
+
+| begin_code
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if !open_brackets <= 0 then
+ (
+ open_brackets := 1;
+ CODE
+ )
+ else
+ (
+ incr open_brackets;
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+| end_code
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if !open_brackets > 1 then
+ (
+ decr open_brackets;
+ Char "]"
+ )
+ else
+ (
+ open_brackets := 0;
+ END_CODE
+ )
+ }
+
+| begin_code_pre end_code_pre
+ {
+ incr_cpts lexbuf ;
+ Char (Lexing.lexeme lexbuf)
+ }
+
+| begin_code_pre
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ (
+ code_pre_mode := true;
+ CODE_PRE
+ )
+ }
+| end_code_pre
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if !open_brackets >= 1 then
+ (
+ lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_curr_pos - 1;
+ lexbuf.Lexing.lex_curr_p <-
+ { lexbuf.Lexing.lex_curr_p with
+ pos_cnum = lexbuf.Lexing.lex_curr_p.pos_cnum - 1
+ } ;
+ decr char_number ;
+ if !open_brackets > 1 then
+ (
+ decr open_brackets;
+ Char "]"
+ )
+ else
+ (
+ open_brackets := 0;
+ END_CODE
+ )
+ )
+ else
+ if !code_pre_mode then
+ (
+ code_pre_mode := false;
+ END_CODE_PRE
+ )
+ else
+ Char (Lexing.lexeme lexbuf)
+ }
+
+| begin_ele_ref end
+ {
+ incr_cpts lexbuf ;
+ Char (Lexing.lexeme lexbuf)
+ }
+
+| begin_ele_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ ELE_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+
+| begin_val_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ VAL_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_typ_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ TYP_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_ext_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ EXT_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_exc_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ EXC_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_mod_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ MOD_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_modt_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ MODT_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_cla_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ CLA_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_clt_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ CLT_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_att_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ ATT_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_met_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ MET_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| begin_sec_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ SEC_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+| begin_recf_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ RECF_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+| begin_const_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ CONST_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+| begin_mod_list_ref
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ (
+ ele_ref_mode := true;
+ MOD_LIST_REF
+ )
+ else
+ (
+ Char (Lexing.lexeme lexbuf)
+ )
+ }
+
+| index_list
+ {
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode || !open_brackets >= 1 then
+ Char (Lexing.lexeme lexbuf)
+ else
+ if not !ele_ref_mode then
+ INDEX_LIST
+ else
+ Char (Lexing.lexeme lexbuf)
+ }
+
+| begin_verb
+ {
+ incr_cpts lexbuf ;
+ if !target_mode || (!open_brackets >= 1) || !code_pre_mode || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ (
+ verb_mode := true;
+ VERB
+ )
+ }
+| end_verb
+ {
+ incr_cpts lexbuf ;
+ if !target_mode || (!open_brackets >= 1) || !code_pre_mode || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ (
+ verb_mode := false;
+ END_VERB
+ )
+ }
+
+| shortcut_list_item
+ {
+ incr_cpts lexbuf ;
+ if !target_mode || (!open_brackets >= 1) || !code_pre_mode
+ || !ele_ref_mode || !verb_mode then
+ Char (Lexing.lexeme lexbuf)
+ else if !shortcut_list_mode then
+ (
+ SHORTCUT_LIST_ITEM
+ )
+ else
+ (
+ shortcut_list_mode := true;
+ BEGIN_SHORTCUT_LIST_ITEM
+ )
+ }
+
+| shortcut_enum_item
+ {
+ incr_cpts lexbuf ;
+ if !target_mode || (!open_brackets >= 1) || !code_pre_mode
+ || !ele_ref_mode || !verb_mode then
+ Char (Lexing.lexeme lexbuf)
+ else if !shortcut_list_mode then
+ SHORTCUT_ENUM_ITEM
+ else
+ (
+ shortcut_list_mode := true;
+ BEGIN_SHORTCUT_ENUM_ITEM
+ )
+ }
+| end_shortcut_list
+ {
+ incr_cpts lexbuf ;
+ lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_curr_pos - 1;
+ lexbuf.Lexing.lex_curr_p <-
+ { lexbuf.Lexing.lex_curr_p with
+ pos_cnum = lexbuf.Lexing.lex_curr_p.pos_cnum - 1 ;
+ } ;
+ decr line_number ;
+ if !shortcut_list_mode then
+ (
+ shortcut_list_mode := false;
+ (* go back one char to re-use the last '\n', so we can
+ restart another shortcut-list with a single blank line,
+ and not two.*)
+ END_SHORTCUT_LIST
+ )
+ else
+ if !target_mode || (!open_brackets >= 1) || !code_pre_mode || !ele_ref_mode || !verb_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ BLANK_LINE
+ }
+
+| eof { EOF }
+
+| begin_custom
+ {
+ print_DEBUG "begin_custom";
+ incr_cpts lexbuf ;
+ if !verb_mode || !target_mode || !code_pre_mode ||
+ (!open_brackets >= 1) || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ let s = Lexing.lexeme lexbuf in
+ let len = String.length s in
+ (* remove this starting '{' *)
+ let tag = Odoc_misc.no_blanks (String.sub s 1 (len - 1)) in
+ CUSTOM tag
+ }
+
+| "{"
+ {
+ incr_cpts lexbuf ;
+ if !target_mode || (!open_brackets >= 1) || !code_pre_mode || !ele_ref_mode then
+ Char (Lexing.lexeme lexbuf)
+ else
+ LBRACE
+ }
+| '\r' { main lexbuf }
+| _
+ {
+ incr_cpts lexbuf ;
+ Char (Lexing.lexeme lexbuf)
+ }
diff --git a/ocamldoc/odoc_text_parser.mly b/ocamldoc/odoc_text_parser.mly
new file mode 100644
index 0000000000..b4118c4f21
--- /dev/null
+++ b/ocamldoc/odoc_text_parser.mly
@@ -0,0 +1,212 @@
+%{
+(***********************************************************************)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Odoc_types
+
+let identchar =
+ "[A-Z a-z_\192-\214\216-\246\248-\255'0-9]"
+let blank = "[ \010\013\009\012]"
+
+let remove_beginning_blanks s =
+ Str.global_replace (Str.regexp ("^"^blank^"+")) "" s
+
+let remove_trailing_blanks s =
+ Str.global_replace (Str.regexp (blank^"+$")) "" s
+
+let print_DEBUG s = print_string s; print_newline ()
+%}
+
+%token END
+%token <int * string option> Title
+%token BOLD
+%token EMP
+%token CENTER
+%token LEFT
+%token RIGHT
+%token ITALIC
+%token <string> CUSTOM
+%token LIST
+%token ENUM
+%token ITEM
+%token LINK
+%token CODE
+%token END_CODE
+%token CODE_PRE
+%token END_CODE_PRE
+%token VERB
+%token END_VERB
+%token LATEX
+%token <string> Target
+%token END_TARGET
+%token LBRACE
+
+%token ELE_REF
+%token VAL_REF
+%token TYP_REF
+%token EXT_REF
+%token EXC_REF
+%token MOD_REF
+%token MODT_REF
+%token CLA_REF
+%token CLT_REF
+%token ATT_REF
+%token MET_REF
+%token SEC_REF
+%token RECF_REF
+%token CONST_REF
+%token MOD_LIST_REF
+%token INDEX_LIST
+
+%token SUPERSCRIPT
+%token SUBSCRIPT
+
+%token BEGIN_SHORTCUT_LIST_ITEM
+%token BEGIN_SHORTCUT_ENUM_ITEM
+%token SHORTCUT_LIST_ITEM
+%token SHORTCUT_ENUM_ITEM
+%token END_SHORTCUT_LIST
+
+%token BLANK_LINE
+
+%token EOF
+%token <string> Char
+
+/* Start Symbols */
+%start main located_element_list
+%type <Odoc_types.text> main
+%type <(int * int * Odoc_types.text_element) list> located_element_list
+
+%%
+main:
+ text EOF { $1 }
+| EOF { [Raw ""] }
+;
+
+text:
+ text_element_list { $1 }
+;
+
+text_element_list:
+ text_element { [ $1 ] }
+| text_element text_element_list { $1 :: $2 }
+;
+
+located_element_list:
+ located_element { [ $1 ] }
+| located_element located_element_list { $1 :: $2 }
+;
+
+located_element:
+ text_element { Parsing.symbol_start (), Parsing.symbol_end (), $1}
+;
+
+
+ele_ref_kind:
+ ELE_REF { None }
+| VAL_REF { Some RK_value }
+| TYP_REF { Some RK_type }
+| EXT_REF { Some RK_extension }
+| EXC_REF { Some RK_exception }
+| MOD_REF { Some RK_module }
+| MODT_REF { Some RK_module_type }
+| CLA_REF { Some RK_class }
+| CLT_REF { Some RK_class_type }
+| ATT_REF { Some RK_attribute }
+| MET_REF { Some RK_method }
+| SEC_REF { Some (RK_section [])}
+| RECF_REF { Some RK_recfield }
+| CONST_REF { Some RK_const }
+;
+
+text_element:
+ Title text END { let n, l_opt = $1 in Title (n, l_opt, $2) }
+| BOLD text END { Bold $2 }
+| ITALIC text END { Italic $2 }
+| CUSTOM text END { Custom ($1, $2) }
+| EMP text END { Emphasize $2 }
+| SUPERSCRIPT text END { Superscript $2 }
+| SUBSCRIPT text END { Subscript $2 }
+| CENTER text END { Center $2 }
+| LEFT text END { Left $2 }
+| RIGHT text END { Right $2 }
+| LIST list END { List $2 }
+| ENUM list END { Enum $2 }
+| CODE string END_CODE { Code $2 }
+| CODE_PRE string END_CODE_PRE { CodePre $2 }
+| ele_ref_kind string END {
+ let s2 = remove_beginning_blanks $2 in
+ let s3 = remove_trailing_blanks s2 in
+ Ref (s3, $1, None)
+ }
+| LBRACE ele_ref_kind string END text END {
+ let s2 = remove_beginning_blanks $3 in
+ let s3 = remove_trailing_blanks s2 in
+ Ref (s3, $2, Some $5)
+ }
+
+| MOD_LIST_REF string END {
+ let s2 = remove_beginning_blanks $2 in
+ let s3 = remove_trailing_blanks s2 in
+ let l = Odoc_misc.split_with_blanks s3 in
+ Module_list l
+ }
+| INDEX_LIST { Index_list }
+| VERB string END_VERB { Verbatim $2 }
+| LATEX string END_TARGET { Latex $2 }
+| Target string END_TARGET { Target ($1, $2) }
+| LINK string END text END { Link ($2, $4) }
+| BLANK_LINE { Newline }
+| BEGIN_SHORTCUT_LIST_ITEM shortcut_list END_SHORTCUT_LIST { List $2 }
+| BEGIN_SHORTCUT_LIST_ITEM shortcut_list EOF { List $2 }
+| BEGIN_SHORTCUT_ENUM_ITEM shortcut_enum END_SHORTCUT_LIST { Enum $2 }
+| BEGIN_SHORTCUT_ENUM_ITEM shortcut_enum EOF { Enum $2 }
+| string { Raw $1 }
+;
+
+list:
+| string { [] (* A VOIR : un test pour voir qu'il n'y a que des blancs *) }
+| string list { $2 }
+| list string { $1 }
+| item { [ $1 ] }
+| item list { $1 :: $2 }
+
+;
+
+item:
+ ITEM text END { $2 }
+;
+
+shortcut_list:
+ text shortcut_list2 { $1 :: $2 }
+| text { [ $1 ] }
+;
+
+shortcut_list2:
+| SHORTCUT_LIST_ITEM shortcut_list { $2 }
+;
+
+shortcut_enum:
+ text shortcut_enum2 { $1 :: $2 }
+| text { [ $1 ] }
+;
+
+shortcut_enum2:
+| SHORTCUT_ENUM_ITEM shortcut_enum { $2 }
+;
+
+
+string:
+ Char { $1 }
+| Char string { $1^$2 }
+;
+
+%%
diff --git a/ocamldoc/odoc_to_text.ml b/ocamldoc/odoc_to_text.ml
new file mode 100644
index 0000000000..ce328b0dae
--- /dev/null
+++ b/ocamldoc/odoc_to_text.ml
@@ -0,0 +1,618 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Text generation.
+
+ This module contains the class [to_text] with methods used to transform
+ information about elements to a [text] structure.*)
+
+open Odoc_info
+open Exception
+open Type
+open Value
+open Module
+open Class
+open Parameter
+
+(** A class used to get a [text] for info structures. *)
+class virtual info =
+ object (self)
+ (** The list of pairs [(tag, f)] where [f] is a function taking
+ the [text] associated to [tag] and returning a [text].
+ Add a pair here to handle a tag.*)
+ val mutable tag_functions = ([] : (string * (Odoc_info.text -> Odoc_info.text)) list)
+
+ (** @return [etxt] value for an authors list. *)
+ method text_of_author_list l =
+ match l with
+ [] ->
+ []
+ | _ ->
+ [ Bold [Raw (Odoc_messages.authors^": ")] ;
+ Raw (String.concat ", " l) ;
+ Newline
+ ]
+
+ (** @return [text] value for the given optional version information.*)
+ method text_of_version_opt v_opt =
+ match v_opt with
+ None -> []
+ | Some v -> [ Bold [Raw (Odoc_messages.version^": ")] ;
+ Raw v ;
+ Newline
+ ]
+
+ (** @return [text] value for the given optional since information.*)
+ method text_of_since_opt s_opt =
+ match s_opt with
+ None -> []
+ | Some s -> [ Bold [Raw (Odoc_messages.since^": ")] ;
+ Raw s ;
+ Newline
+ ]
+
+ (** @return [text] value to represent the list of "before" information. *)
+ method text_of_before = function
+ [] -> []
+ | l ->
+ let f (v, text) =
+ (Bold [Raw (Printf.sprintf "%s %s " Odoc_messages.before v) ]) ::
+ text @
+ [Newline]
+ in
+ List.flatten (List.map f l)
+
+ (** @return [text] value for the given list of raised exceptions.*)
+ method text_of_raised_exceptions l =
+ match l with
+ [] -> []
+ | (s, t) :: [] ->
+ [ Bold [ Raw Odoc_messages.raises ] ;
+ Raw " " ;
+ Code s ;
+ Raw " "
+ ]
+ @ t
+ @ [ Newline ]
+ | _ ->
+ [ Bold [ Raw Odoc_messages.raises ] ;
+ Raw " " ;
+ List
+ (List.map
+ (fun (ex, desc) ->(Code ex) :: (Raw " ") :: desc )
+ l
+ ) ;
+ Newline
+ ]
+
+ (** Return [text] value for the given "see also" reference. *)
+ method text_of_see (see_ref, t) =
+ let t_ref =
+ match see_ref with
+ Odoc_info.See_url s -> [ Odoc_info.Link (s, t) ]
+ | Odoc_info.See_file s -> (Odoc_info.Code s) :: (Odoc_info.Raw " ") :: t
+ | Odoc_info.See_doc s -> (Odoc_info.Italic [Odoc_info.Raw s]) :: (Odoc_info.Raw " ") :: t
+ in
+ t_ref
+
+ (** Return [text] value for the given list of "see also" references.*)
+ method text_of_sees l =
+ match l with
+ [] -> []
+ | see :: [] ->
+ (Bold [ Raw Odoc_messages.see_also ]) ::
+ (Raw " ") ::
+ (self#text_of_see see) @ [ Newline ]
+ | _ ->
+ (Bold [ Raw Odoc_messages.see_also ]) ::
+ [ List
+ (List.map
+ (fun see -> self#text_of_see see)
+ l
+ );
+ Newline
+ ]
+
+ (** @return [text] value for the given optional return information.*)
+ method text_of_return_opt return_opt =
+ match return_opt with
+ None -> []
+ | Some t -> (Bold [Raw (Odoc_messages.returns^" ")]) :: t @ [ Newline ]
+
+ (** Return a [text] for the given list of custom tagged texts. *)
+ method text_of_custom l =
+ List.fold_left
+ (fun acc -> fun (tag, text) ->
+ try
+ let f = List.assoc tag tag_functions in
+ match acc with
+ [] -> f text
+ | _ -> acc @ (Newline :: (f text))
+ with
+ Not_found ->
+ Odoc_info.warning (Odoc_messages.tag_not_handled tag) ;
+ acc
+ )
+ []
+ l
+
+ (** @return [text] value for a description, except for the i_params field. *)
+ method text_of_info ?(block=true) info_opt =
+ match info_opt with
+ None ->
+ []
+ | Some info ->
+ let t =
+ (match info.i_deprecated with
+ None -> []
+ | Some t -> ( Italic [Raw (Odoc_messages.deprecated^" ")] ) :: t
+ ) @
+ (match info.i_desc with
+ None -> []
+ | Some t when t = [Odoc_info.Raw ""] -> []
+ | Some t -> t @ [ Newline ]
+ ) @
+ (self#text_of_author_list info.i_authors) @
+ (self#text_of_version_opt info.i_version) @
+ (self#text_of_before info.i_before) @
+ (self#text_of_since_opt info.i_since) @
+ (self#text_of_raised_exceptions info.i_raised_exceptions) @
+ (self#text_of_return_opt info.i_return_value) @
+ (self#text_of_sees info.i_sees) @
+ (self#text_of_custom info.i_custom)
+ in
+ if block then
+ [Block t]
+ else
+ t
+ end
+
+(** This class defines methods to generate a [text] structure from elements. *)
+class virtual to_text =
+ object (self)
+ inherit info
+
+ method virtual label : ?no_: bool -> string -> string
+
+ (** Take a string and return the string where fully qualified idents
+ have been replaced by idents relative to the given module name.
+ Also remove the "hidden modules".*)
+ method relative_idents m_name s =
+ let f str_t =
+ let match_s = Str.matched_string str_t in
+ let rel = Name.get_relative m_name match_s in
+ Odoc_info.apply_if_equal Odoc_info.use_hidden_modules match_s rel
+ in
+ let s2 = Str.global_substitute
+ (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([a-z][a-zA-Z_'0-9]*\\)")
+ f
+ s
+ in
+ s2
+
+ (** Take a string and return the string where fully qualified idents
+ have been replaced by idents relative to the given module name.
+ Also remove the "hidden modules".*)
+ method relative_module_idents m_name s =
+ let f str_t =
+ let match_s = Str.matched_string str_t in
+ let rel = Name.get_relative m_name match_s in
+ Odoc_info.apply_if_equal Odoc_info.use_hidden_modules match_s rel
+ in
+ let s2 = Str.global_substitute
+ (Str.regexp "\\([A-Z]\\([a-zA-Z_'0-9]\\)*\\.\\)+\\([A-Z][a-zA-Z_'0-9]*\\)")
+ f
+ s
+ in
+ s2
+
+ (** Get a string for a [Types.class_type] where all idents are relative. *)
+ method normal_class_type m_name t =
+ self#relative_idents m_name (Odoc_info.string_of_class_type t)
+
+ (** Get a string for a [Types.module_type] where all idents are relative. *)
+ method normal_module_type ?code m_name t =
+ self#relative_module_idents m_name (Odoc_info.string_of_module_type ?code t)
+
+ (** Get a string for a type where all idents are relative. *)
+ method normal_type m_name t =
+ self#relative_idents m_name (Odoc_info.string_of_type_expr t)
+
+ (** Get a string for a list of types where all idents are relative. *)
+ method normal_type_list ?par m_name sep t =
+ self#relative_idents m_name (Odoc_info.string_of_type_list ?par sep t)
+
+ method normal_cstr_args ?par m_name = function
+ | Cstr_tuple l -> self#normal_type_list ?par m_name " * " l
+ | Cstr_record _ -> "{...}" (* TODO *)
+
+ (** Get a string for a list of class or class type type parameters
+ where all idents are relative. *)
+ method normal_class_type_param_list m_name t =
+ self#relative_idents m_name (Odoc_info.string_of_class_type_param_list t)
+
+ (** Get a string for the parameters of a class (with arrows) where all idents are relative. *)
+ method normal_class_params m_name c =
+ let s = Odoc_info.string_of_class_params c in
+ self#relative_idents m_name
+ (Odoc_info.remove_ending_newline s)
+
+ (** @return [text] value to represent a [Types.type_expr].*)
+ method text_of_type_expr module_name t =
+ let t = List.flatten
+ (List.map
+ (fun s -> [Code s ; Newline ])
+ (Str.split (Str.regexp "\n")
+ (self#normal_type module_name t))
+ )
+ in
+ t
+
+ (** Return [text] value for a given short [Types.type_expr].*)
+ method text_of_short_type_expr module_name t =
+ [ Code (self#normal_type module_name t) ]
+
+ (** Return [text] value or the given list of [Types.type_expr], with
+ the given separator. *)
+ method text_of_type_expr_list module_name sep l =
+ [ Code (self#normal_type_list module_name sep l) ]
+
+ (** Return [text] value or the given list of [Types.type_expr],
+ as type parameters of a class of class type. *)
+ method text_of_class_type_param_expr_list module_name l =
+ [ Code (self#normal_class_type_param_list module_name l) ]
+
+ (** @return [text] value to represent parameters of a class (with arraows).*)
+ method text_of_class_params module_name c =
+ let t = Odoc_info.text_concat
+ [Newline]
+ (List.map
+ (fun s -> [Code s])
+ (Str.split (Str.regexp "\n")
+ (self#normal_class_params module_name c))
+ )
+ in
+ t
+
+ (** @return [text] value to represent a [Types.module_type]. *)
+ method text_of_module_type t =
+ let s = String.concat "\n"
+ (Str.split (Str.regexp "\n") (Odoc_info.string_of_module_type t))
+ in
+ [ Code s ]
+
+ (** @return [text] value for a value. *)
+ method text_of_value v =
+ let name = v.val_name in
+ let s_name = Name.simple name in
+ let s =
+ Format.fprintf Format.str_formatter "@[<hov 2>val %s :@ %s"
+ s_name
+ (self#normal_type (Name.father v.val_name) v.val_type);
+ Format.flush_str_formatter ()
+ in
+ [ CodePre s ] @
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @
+ (self#text_of_info v.val_info)
+
+ (** @return [text] value for a class attribute. *)
+ method text_of_attribute a =
+ let s_name = Name.simple a.att_value.val_name in
+ let mod_name = Name.father a.att_value.val_name in
+ let s =
+ Format.fprintf Format.str_formatter "@[<hov 2>val %s%s%s :@ %s"
+ (if a.att_virtual then "virtual " else "")
+ (if a.att_mutable then "mutable " else "")
+ s_name
+ (self#normal_type mod_name a.att_value.val_type);
+ Format.flush_str_formatter ()
+ in
+ (CodePre s) ::
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @
+ (self#text_of_info a.att_value.val_info)
+
+ (** @return [text] value for a class method. *)
+ method text_of_method m =
+ let s_name = Name.simple m.met_value.val_name in
+ let mod_name = Name.father m.met_value.val_name in
+ let s =
+ Format.fprintf Format.str_formatter "@[<hov 2>method %s%s%s :@ %s"
+ (if m.met_private then "private " else "")
+ (if m.met_virtual then "virtual " else "")
+ s_name
+ (self#normal_type mod_name m.met_value.val_type);
+ Format.flush_str_formatter ()
+ in
+ (CodePre s) ::
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @
+ (self#text_of_info m.met_value.val_info)
+
+
+ (** @return [text] value for an exception. *)
+ method text_of_exception e =
+ let s_name = Name.simple e.ex_name in
+ let father = Name.father e.ex_name in
+ Format.fprintf Format.str_formatter "@[<hov 2>exception %s" s_name ;
+ (match e.ex_args, e.ex_ret with
+ Cstr_tuple [], None -> ()
+ | Cstr_tuple l, None ->
+ Format.fprintf Format.str_formatter " %s@ %s"
+ "of"
+ (self#normal_type_list ~par: false father " * " l)
+ | Cstr_tuple [], Some r ->
+ Format.fprintf Format.str_formatter " %s@ %s"
+ ":"
+ (self#normal_type father r)
+ | Cstr_tuple l, Some r ->
+ Format.fprintf Format.str_formatter " %s@ %s@ %s@ %s"
+ ":"
+ (self#normal_type_list ~par: false father " * " l)
+ "->"
+ (self#normal_type father r)
+ | Cstr_record _, _ ->
+ assert false
+ );
+ (match e.ex_alias with
+ None -> ()
+ | Some ea ->
+ Format.fprintf Format.str_formatter " = %s"
+ (
+ match ea.ea_ex with
+ None -> ea.ea_name
+ | Some e -> e.ex_name
+ )
+ );
+ let s2 = Format.flush_str_formatter () in
+ [ CodePre s2 ] @
+ [Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @
+ (self#text_of_info e.ex_info)
+
+ (** Return [text] value for the description of a function parameter. *)
+ method text_of_parameter_description p =
+ match Parameter.names p with
+ [] -> []
+ | name :: [] ->
+ (
+ (* Only one name, no need for label for the description. *)
+ match Parameter.desc_by_name p name with
+ None -> []
+ | Some t -> t
+ )
+ | l ->
+ (* A list of names, we display those with a description. *)
+ let l2 = List.filter (fun n -> (Parameter.desc_by_name p n) <> None) l in
+ match l2 with
+ [] -> []
+ | _ ->
+ [List
+ (List.map
+ (fun n ->
+ match Parameter.desc_by_name p n with
+ None -> [] (* should not occur *)
+ | Some t -> [Code (n^" ") ; Raw ": "] @ t
+ )
+ l2
+ )
+ ]
+
+
+ (** Return [text] value for a list of parameters. *)
+ method text_of_parameter_list m_name l =
+ match l with
+ [] ->
+ []
+ | _ ->
+ [ Bold [Raw Odoc_messages.parameters] ;
+ Raw ":" ;
+ List
+ (List.map
+ (fun p ->
+ (match Parameter.complete_name p with
+ "" -> Code "?"
+ | s -> Code s
+ ) ::
+ [Code " : "] @
+ (self#text_of_short_type_expr m_name (Parameter.typ p)) @
+ [Newline] @
+ (self#text_of_parameter_description p)
+ )
+ l
+ )
+ ]
+
+ (** Return [text] value for a list of module parameters. *)
+ method text_of_module_parameter_list l =
+ match l with
+ [] ->
+ []
+ | _ ->
+ [ Newline ;
+ Bold [Raw Odoc_messages.parameters] ;
+ Raw ":" ;
+ List
+ (List.map
+ (fun (p, desc_opt) ->
+ begin match p.mp_type with None -> [Raw ""]
+ | Some mty ->
+ [Code (p.mp_name^" : ")] @
+ (self#text_of_module_type mty)
+ end @
+ (match desc_opt with
+ None -> []
+ | Some t -> (Raw " ") :: t)
+ )
+ l
+ )
+ ]
+
+(**/**)
+
+ (** Return [text] value for the given [class_kind].*)
+ method text_of_class_kind father ckind =
+ match ckind with
+ Class_structure _ ->
+ [Code Odoc_messages.object_end]
+
+ | Class_apply capp ->
+ [Code
+ (
+ (
+ match capp.capp_class with
+ None -> capp.capp_name
+ | Some cl -> cl.cl_name
+ )^
+ " "^
+ (String.concat " "
+ (List.map
+ (fun s -> "("^s^")")
+ capp.capp_params_code))
+ )
+ ]
+
+ | Class_constr cco ->
+ (
+ match cco.cco_type_parameters with
+ [] -> []
+ | l ->
+ (Code "[")::
+ (self#text_of_type_expr_list father ", " l)@
+ [Code "] "]
+ )@
+ [Code (
+ match cco.cco_class with
+ None -> cco.cco_name
+ | Some (Cl cl) -> Name.get_relative father cl.cl_name
+ | Some (Cltype (clt,_)) -> Name.get_relative father clt.clt_name
+ )
+ ]
+
+ | Class_constraint (ck, ctk) ->
+ [Code "( "] @
+ (self#text_of_class_kind father ck) @
+ [Code " : "] @
+ (self#text_of_class_type_kind father ctk) @
+ [Code " )"]
+
+
+ (** Return [text] value for the given [class_type_kind].*)
+ method text_of_class_type_kind father ctkind =
+ match ctkind with
+ Class_type cta ->
+ (
+ match cta.cta_type_parameters with
+ [] -> []
+ | l ->
+ (Code "[") ::
+ (self#text_of_class_type_param_expr_list father l) @
+ [Code "] "]
+ ) @
+ (
+ match cta.cta_class with
+ None -> [ Code cta.cta_name ]
+ | Some (Cltype (clt, _)) ->
+ let rel = Name.get_relative father clt.clt_name in
+ [Code rel]
+ | Some (Cl cl) ->
+ let rel = Name.get_relative father cl.cl_name in
+ [Code rel]
+ )
+ | Class_signature _ ->
+ [Code Odoc_messages.object_end]
+
+ (** Return [text] value for a [module_kind]. *)
+ method text_of_module_kind ?(with_def_syntax=true) k =
+ match k with
+ Module_alias m_alias ->
+ (match m_alias.ma_module with
+ None ->
+ [Code ((if with_def_syntax then " = " else "")^m_alias.ma_name)]
+ | Some (Mod m) ->
+ [Code ((if with_def_syntax then " = " else "")^m.m_name)]
+ | Some (Modtype mt) ->
+ [Code ((if with_def_syntax then " = " else "")^mt.mt_name)]
+ )
+ | Module_apply (k1, k2) ->
+ (if with_def_syntax then [Code " = "] else []) @
+ (self#text_of_module_kind ~with_def_syntax: false k1) @
+ [Code " ( "] @
+ (self#text_of_module_kind ~with_def_syntax: false k2) @
+ [Code " ) "]
+
+ | Module_with (tk, code) ->
+ (if with_def_syntax then [Code " : "] else []) @
+ (self#text_of_module_type_kind ~with_def_syntax: false tk) @
+ [Code code]
+
+ | Module_constraint (k, tk) ->
+ (if with_def_syntax then [Code " : "] else []) @
+ [Code "( "] @
+ (self#text_of_module_kind ~with_def_syntax: false k) @
+ [Code " : "] @
+ (self#text_of_module_type_kind ~with_def_syntax: false tk) @
+ [Code " )"]
+
+ | Module_struct _ ->
+ [Code ((if with_def_syntax then " : " else "")^
+ Odoc_messages.struct_end^" ")]
+
+ | Module_functor (p, k) ->
+ (if with_def_syntax then [Code " : "] else []) @
+ [Code "functor ... "] @
+ [Code " -> "] @
+ (self#text_of_module_kind ~with_def_syntax: false k)
+
+ | Module_typeof s ->
+ let code = Printf.sprintf "%smodule type of %s"
+ (if with_def_syntax then " : " else "")
+ s
+ in
+ [Code code]
+ | Module_unpack (code, _) ->
+ let code = Printf.sprintf "%s%s"
+ (if with_def_syntax then " : " else "")
+ code
+ in
+ [Code code]
+
+ (** Return html code for a [module_type_kind].*)
+ method text_of_module_type_kind ?(with_def_syntax=true) tk =
+ match tk with
+ | Module_type_struct _ ->
+ [Code ((if with_def_syntax then " = " else "")^Odoc_messages.sig_end)]
+
+ | Module_type_functor (p, k) ->
+ let t1 =
+ [Code ("("^p.mp_name^" : ")] @
+ (self#text_of_module_type_kind p.mp_kind) @
+ [Code ") -> "]
+ in
+ let t2 = self#text_of_module_type_kind ~with_def_syntax: false k in
+ (if with_def_syntax then [Code " = "] else []) @ t1 @ t2
+
+ | Module_type_with (tk2, code) ->
+ let t = self#text_of_module_type_kind ~with_def_syntax: false tk2 in
+ (if with_def_syntax then [Code " = "] else []) @
+ t @ [Code code]
+
+ | Module_type_alias mt_alias ->
+ [Code ((if with_def_syntax then " = " else "")^
+ (match mt_alias.mta_module with
+ None -> mt_alias.mta_name
+ | Some mt -> mt.mt_name))
+ ]
+
+ | Odoc_module.Module_type_typeof s ->
+ let code = Printf.sprintf "%smodule type of %s"
+ (if with_def_syntax then " = " else "") s
+ in
+ [ Code code ]
+ end
diff --git a/ocamldoc/odoc_type.ml b/ocamldoc/odoc_type.ml
new file mode 100644
index 0000000000..f9bd9cda1c
--- /dev/null
+++ b/ocamldoc/odoc_type.ml
@@ -0,0 +1,70 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation and manipulation of a type, but not class nor module type.*)
+
+module Name = Odoc_name
+
+type private_flag = Asttypes.private_flag =
+ Private | Public
+
+(** Description of a record type field. *)
+type record_field = {
+ rf_name : string ;
+ rf_mutable : bool ; (** true if mutable *)
+ rf_type : Types.type_expr ;
+ mutable rf_text : Odoc_types.info option ; (** optional user description *)
+ }
+
+type constructor_args =
+ | Cstr_record of record_field list
+ | Cstr_tuple of Types.type_expr list
+
+(** Description of a variant type constructor. *)
+type variant_constructor = {
+ vc_name : string ;
+ vc_args : constructor_args ;
+ vc_ret : Types.type_expr option ;
+ mutable vc_text : Odoc_types.info option ; (** optional user description *)
+ }
+
+(** The various kinds of type. *)
+type type_kind =
+ Type_abstract
+ | Type_variant of variant_constructor list
+ (** constructors *)
+ | Type_record of record_field list
+ (** fields *)
+ | Type_open
+
+type object_field = {
+ of_name : string ;
+ of_type : Types.type_expr ;
+ mutable of_text : Odoc_types.info option ; (** optional user description *)
+}
+
+type type_manifest =
+ | Other of Types.type_expr (** Type manifest directly taken from Typedtre. *)
+ | Object_type of object_field list
+
+(** Representation of a type. *)
+type t_type = {
+ ty_name : Name.t ;
+ mutable ty_info : Odoc_types.info option ; (** optional user information *)
+ ty_parameters : (Types.type_expr * bool * bool) list ;
+ (** type parameters: (type, covariant, contravariant) *)
+ ty_kind : type_kind ;
+ ty_private : private_flag;
+ ty_manifest : type_manifest option;
+ mutable ty_loc : Odoc_types.location ;
+ mutable ty_code : string option;
+ }
diff --git a/ocamldoc/odoc_types.ml b/ocamldoc/odoc_types.ml
new file mode 100644
index 0000000000..9d7824aae1
--- /dev/null
+++ b/ocamldoc/odoc_types.ml
@@ -0,0 +1,140 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type ref_kind =
+ RK_module
+ | RK_module_type
+ | RK_class
+ | RK_class_type
+ | RK_value
+ | RK_type
+ | RK_extension
+ | RK_exception
+ | RK_attribute
+ | RK_method
+ | RK_section of text
+ | RK_recfield
+ | RK_const
+
+and text_element =
+ | Raw of string
+ | Code of string
+ | CodePre of string
+ | Verbatim of string
+ | Bold of text
+ | Italic of text
+ | Emphasize of text
+ | Center of text
+ | Left of text
+ | Right of text
+ | List of text list
+ | Enum of text list
+ | Newline
+ | Block of text
+ | Title of int * string option * text
+ | Latex of string
+ | Link of string * text
+ | Ref of string * ref_kind option * text option
+ | Superscript of text
+ | Subscript of text
+ | Module_list of string list
+ | Index_list
+ | Custom of string * text
+ | Target of string * string
+
+and text = text_element list
+
+type see_ref =
+ See_url of string
+ | See_file of string
+ | See_doc of string
+
+type see = see_ref * text
+
+type param = (string * text)
+
+type raised_exception = (string * text)
+
+type info = {
+ i_desc : text option;
+ i_authors : string list;
+ i_version : string option;
+ i_sees : see list;
+ i_since : string option;
+ i_before : (string * text) list;
+ i_deprecated : text option;
+ i_params : param list;
+ i_raised_exceptions : raised_exception list;
+ i_return_value : text option ;
+ i_custom : (string * text) list ;
+ }
+
+let dummy_info = {
+ i_desc = None ;
+ i_authors = [] ;
+ i_version = None ;
+ i_sees = [] ;
+ i_since = None ;
+ i_before = [] ;
+ i_deprecated = None ;
+ i_params = [] ;
+ i_raised_exceptions = [] ;
+ i_return_value = None ;
+ i_custom = [] ;
+}
+
+type location = {
+ loc_impl : Location.t option ;
+ loc_inter : Location.t option ;
+ }
+
+let dummy_loc = { loc_impl = None ; loc_inter = None }
+
+type merge_option =
+ | Merge_description
+ | Merge_author
+ | Merge_version
+ | Merge_see
+ | Merge_since
+ | Merge_before
+ | Merge_deprecated
+ | Merge_param
+ | Merge_raised_exception
+ | Merge_return_value
+ | Merge_custom
+
+let all_merge_options = [
+ Merge_description ;
+ Merge_author ;
+ Merge_version ;
+ Merge_see ;
+ Merge_since ;
+ Merge_before ;
+ Merge_deprecated ;
+ Merge_param ;
+ Merge_raised_exception ;
+ Merge_return_value ;
+ Merge_custom ;
+]
+
+type magic = string
+
+let magic = Odoc_messages.magic
+
+type 'a dump = Dump of magic * 'a
+
+let make_dump a = Dump (magic, a)
+
+let open_dump = function
+ Dump (m, a) ->
+ if m = magic then a
+ else raise (Failure Odoc_messages.bad_magic_number)
diff --git a/ocamldoc/odoc_types.mli b/ocamldoc/odoc_types.mli
new file mode 100644
index 0000000000..f9456ccd85
--- /dev/null
+++ b/ocamldoc/odoc_types.mli
@@ -0,0 +1,139 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Types for the information collected in comments. *)
+
+(** The differents kinds of element references. *)
+type ref_kind =
+ RK_module
+ | RK_module_type
+ | RK_class
+ | RK_class_type
+ | RK_value
+ | RK_type
+ | RK_extension
+ | RK_exception
+ | RK_attribute
+ | RK_method
+ | RK_section of text
+ | RK_recfield
+ | RK_const
+
+and text_element =
+ | Raw of string (** Raw text. *)
+ | Code of string (** The string is source code. *)
+ | CodePre of string (** The string is pre-formatted source code. *)
+ | Verbatim of string (** String 'as is'. *)
+ | Bold of text (** Text in bold style. *)
+ | Italic of text (** Text in italic. *)
+ | Emphasize of text (** Emphasized text. *)
+ | Center of text (** Centered text. *)
+ | Left of text (** Left alignment. *)
+ | Right of text (** Right alignment. *)
+ | List of text list (** A list. *)
+ | Enum of text list (** An enumerated list. *)
+ | Newline (** To force a line break. *)
+ | Block of text (** Like html's block quote. *)
+ | Title of int * string option * text
+ (** Style number, optional label, and text. *)
+ | Latex of string (** A string for latex. *)
+ | Link of string * text (** A reference string and the link text. *)
+ | Ref of string * ref_kind option * text option
+ (** A reference to an element. Complete name and kind. An optional
+ text can be given to display this text instead of the element name.*)
+ | Superscript of text (** Superscripts. *)
+ | Subscript of text (** Subscripts. *)
+ | Module_list of string list
+ (** The table of the given modules with their abstract; *)
+ | Index_list (** The links to the various indexes (values, types, ...) *)
+ | Custom of string * text (** to extend \{foo syntax *)
+ | Target of string * string (** (target, code) : to specify code for a specific target format *)
+
+(** [text] is a list of text_elements. The order matters. *)
+and text = text_element list
+
+(** The different forms of references in \@see tags. *)
+type see_ref =
+ See_url of string
+ | See_file of string
+ | See_doc of string
+
+(** The information in a \@see tag. *)
+type see = see_ref * text
+
+(** Parameter name and description. *)
+type param = (string * text)
+
+(** Raised exception name and description. *)
+type raised_exception = (string * text)
+
+(** Information in a special comment. *)
+type info = {
+ i_desc : text option; (** The description text. *)
+ i_authors : string list; (** The list of authors in \@author tags. *)
+ i_version : string option; (** The string in the \@version tag. *)
+ i_sees : see list; (** The list of \@see tags. *)
+ i_since : string option; (** The string in the \@since tag. *)
+ i_before : (string * text) list; (** the version number and text in \@before tag *)
+ i_deprecated : text option; (** The of the \@deprecated tag. *)
+ i_params : param list; (** The list of parameter descriptions. *)
+ i_raised_exceptions : raised_exception list; (** The list of raised exceptions. *)
+ i_return_value : text option ; (** The description text of the return value. *)
+ i_custom : (string * text) list ; (** A text associated to a custom @-tag. *)
+ }
+
+(** An empty info structure. *)
+val dummy_info : info
+
+(** Location of elements in implementation and interface files. *)
+type location = {
+ loc_impl : Location.t option ; (** implementation location *)
+ loc_inter : Location.t option ; (** interface location *)
+ }
+
+(** A dummy location. *)
+val dummy_loc : location
+
+(** The information to merge from two elements when they both have some information. *)
+type merge_option =
+ | Merge_description (** Descriptions are concatenated. *)
+ | Merge_author (** Lists of authors are concatenated. *)
+ | Merge_version (** Versions are concatenated. *)
+ | Merge_see (** See references are concatenated. *)
+ | Merge_since (** Since information are concatenated. *)
+ | Merge_before (** Before information are concatenated. *)
+ | Merge_deprecated (** Deprecated information are concatenated. *)
+ | Merge_param (** Information on each parameter is concatenated,
+ and all parameters are kept. *)
+ | Merge_raised_exception (** Information on each raised_exception is concatenated,
+ and all raised exceptions are kept. *)
+ | Merge_return_value (** Information on return value are concatenated. *)
+ | Merge_custom (** Merge custom tags (all pairs (tag, text) are kept). *)
+
+(** The list with all merge options. *)
+val all_merge_options : merge_option list
+
+(** Type of magic numbers. *)
+type magic
+
+(** The magic number for the dumps of this version of ocamldoc. *)
+val magic : magic
+
+(** A dump of a structure. *)
+type 'a dump
+
+(** Create a dump structure. *)
+val make_dump : 'a -> 'a dump
+
+(** Verify that a dump has the correct magic number
+ and return its content. *)
+val open_dump : 'a dump -> 'a
diff --git a/ocamldoc/odoc_value.ml b/ocamldoc/odoc_value.ml
new file mode 100644
index 0000000000..7caedb3600
--- /dev/null
+++ b/ocamldoc/odoc_value.ml
@@ -0,0 +1,137 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Representation and manipulation of values, class attributes and class methods. *)
+
+module Name = Odoc_name
+
+(** Types *)
+
+(** Representation of a value. *)
+type t_value = {
+ val_name : Name.t ;
+ mutable val_info : Odoc_types.info option ;
+ val_type : Types.type_expr ;
+ val_recursive : bool ;
+ mutable val_parameters : Odoc_parameter.parameter list ;
+ mutable val_code : string option ;
+ mutable val_loc : Odoc_types.location ;
+ }
+
+(** Representation of a class attribute. *)
+type t_attribute = {
+ att_value : t_value ; (** an attribute has almost all the same information
+ as a value *)
+ att_mutable : bool ;
+ att_virtual : bool ;
+ }
+
+(** Representation of a class method. *)
+type t_method = {
+ met_value : t_value ; (** a method has almost all the same information
+ as a value *)
+ met_private : bool ;
+ met_virtual : bool ;
+ }
+
+(** Functions *)
+
+(** Returns the text associated to the given parameter name
+ in the given value, or None. *)
+let value_parameter_text_by_name v name =
+ match v.val_info with
+ None -> None
+ | Some i ->
+ try
+ let t = List.assoc name i.Odoc_types.i_params in
+ Some t
+ with
+ Not_found ->
+ None
+
+(** Update the parameters text of a t_value, according to the val_info field. *)
+let update_value_parameters_text v =
+ let f p =
+ Odoc_parameter.update_parameter_text (value_parameter_text_by_name v) p
+ in
+ List.iter f v.val_parameters
+
+(** Create a list of (parameter name, typ) from a type, according to the arrows.
+ [parameter_list_from_arrows t = [ a ; b ]] if t = a -> b -> c.*)
+let parameter_list_from_arrows typ =
+ let rec iter t =
+ match t.Types.desc with
+ Types.Tarrow (l, t1, t2, _) ->
+ (l, t1) :: (iter t2)
+ | Types.Tlink texp
+ | Types.Tsubst texp ->
+ iter texp
+ | Types.Tpoly (texp, _) -> iter texp
+ | Types.Tvar _
+ | Types.Ttuple _
+ | Types.Tconstr _
+ | Types.Tobject _
+ | Types.Tfield _
+ | Types.Tnil
+ | Types.Tunivar _
+ | Types.Tpackage _
+ | Types.Tvariant _ ->
+ []
+ in
+ iter typ
+
+(** Create a list of parameters with dummy names "??" from a type list.
+ Used when we want to merge the parameters of a value, from the .ml
+ and the .mli file. In the .mli file we don't have parameter names
+ so there is nothing to merge. With this dummy list we can merge the
+ parameter names from the .ml and the type from the .mli file. *)
+let dummy_parameter_list typ =
+ let normal_name = Odoc_misc.label_name in
+ Printtyp.mark_loops typ;
+ let liste_param = parameter_list_from_arrows typ in
+ let rec iter (label, t) =
+ match t.Types.desc with
+ | Types.Ttuple l ->
+ let open Asttypes in
+ if label = Nolabel then
+ Odoc_parameter.Tuple
+ (List.map (fun t2 -> iter (Nolabel, t2)) l, t)
+ else
+ (* if there is a label, then we don't want to decompose the tuple *)
+ Odoc_parameter.Simple_name
+ { Odoc_parameter.sn_name = normal_name label ;
+ Odoc_parameter.sn_type = t ;
+ Odoc_parameter.sn_text = None }
+ | Types.Tlink t2
+ | Types.Tsubst t2 ->
+ (iter (label, t2))
+
+ | _ ->
+ Odoc_parameter.Simple_name
+ { Odoc_parameter.sn_name = normal_name label ;
+ Odoc_parameter.sn_type = t ;
+ Odoc_parameter.sn_text = None }
+ in
+ List.map iter liste_param
+
+(** Return true if the value is a function, i.e. has a functional type.*)
+let is_function v =
+ let rec f t =
+ match t.Types.desc with
+ Types.Tarrow _ ->
+ true
+ | Types.Tlink t ->
+ f t
+ | _ ->
+ false
+ in
+ f v.val_type
diff --git a/ocamldoc/remove_DEBUG b/ocamldoc/remove_DEBUG
new file mode 100755
index 0000000000..bca6ba049d
--- /dev/null
+++ b/ocamldoc/remove_DEBUG
@@ -0,0 +1,20 @@
+#!/bin/sh
+
+#(***********************************************************************)
+#(* OCamldoc *)
+#(* *)
+#(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+#(* *)
+#(* Copyright 2003 Institut National de Recherche en Informatique et *)
+#(* en Automatique. All rights reserved. This file is distributed *)
+#(* under the terms of the Q Public License version 1.0. *)
+#(* *)
+#(***********************************************************************)
+
+# usage: remove_DEBUG <file>
+# remove from <file> every line that contains the string "DEBUG",
+# respecting the cpp # line annotation conventions
+
+echo "# 1 \"$1\""
+LC_ALL=C sed -e '/DEBUG/c\
+(* DEBUG statement removed *)' "$1"
diff --git a/ocamldoc/runocamldoc b/ocamldoc/runocamldoc
new file mode 100644
index 0000000000..d2112e9cd7
--- /dev/null
+++ b/ocamldoc/runocamldoc
@@ -0,0 +1,23 @@
+#!/bin/sh
+
+#######################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2002 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#######################################################################
+
+case "$1" in
+ true) shift
+ exec ../boot/ocamlrun -I ../otherlibs/unix -I ../otherlibs/str \
+ ./ocamldoc "$@"
+ ;;
+ *) shift
+ exec ./ocamldoc "$@"
+ ;;
+esac
diff --git a/otherlibs/Makefile b/otherlibs/Makefile
new file mode 100644
index 0000000000..3ca2a487ff
--- /dev/null
+++ b/otherlibs/Makefile
@@ -0,0 +1,23 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Common Makefile for otherlibs on the Unix ports
+
+CAMLC=$(CAMLRUN) $(ROOTDIR)/ocamlc -nostdlib -I $(ROOTDIR)/stdlib
+CAMLOPT=$(CAMLRUN) $(ROOTDIR)/ocamlopt -nostdlib \
+ -I $(ROOTDIR)/stdlib
+CFLAGS=-I$(ROOTDIR)/byterun $(SHAREDCCCOMPOPTS) $(EXTRACFLAGS)
+
+include ../Makefile.shared
+# Note .. is the current directory (this makefile is included from
+# a subdirectory)
diff --git a/otherlibs/Makefile.nt b/otherlibs/Makefile.nt
new file mode 100644
index 0000000000..6d16f8d273
--- /dev/null
+++ b/otherlibs/Makefile.nt
@@ -0,0 +1,21 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Common Makefile for otherlibs on the Win32/MinGW ports
+
+include ../Makefile
+
+# The Unix version now works fine under Windows
+
+# Note .. is the current directory (this makefile is included from
+# a subdirectory)
diff --git a/otherlibs/Makefile.shared b/otherlibs/Makefile.shared
new file mode 100644
index 0000000000..cb8bf1748c
--- /dev/null
+++ b/otherlibs/Makefile.shared
@@ -0,0 +1,94 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Common Makefile for otherlibs
+
+ROOTDIR=../..
+include $(ROOTDIR)/config/Makefile
+CAMLRUN ?= $(ROOTDIR)/boot/ocamlrun
+CAMLYACC ?= $(ROOTDIR)/boot/ocamlyacc
+
+# Compilation options
+CC=$(BYTECC)
+COMPFLAGS=-w +33..39 -warn-error A -bin-annot -g -safe-string $(EXTRACAMLFLAGS)
+MKLIB=$(CAMLRUN) $(ROOTDIR)/tools/ocamlmklib
+
+# Variables to be defined by individual libraries:
+#LIBNAME=
+#CLIBNAME=
+#CMIFILES=
+#CAMLOBJS=
+#COBJS=
+#EXTRACFLAGS=
+#EXTRACAMLFLAGS=
+#LINKOPTS=
+#LDOPTS=
+#HEADERS=
+
+CMIFILES ?= $(CAMLOBJS:.cmo=.cmi)
+CAMLOBJS_NAT ?= $(CAMLOBJS:.cmo=.cmx)
+CLIBNAME ?= $(LIBNAME)
+
+all: lib$(CLIBNAME).$(A) $(LIBNAME).cma $(CMIFILES)
+
+allopt: lib$(CLIBNAME).$(A) $(LIBNAME).cmxa $(LIBNAME).$(CMXS) $(CMIFILES)
+
+$(LIBNAME).cma: $(CAMLOBJS)
+ $(MKLIB) -o $(LIBNAME) -oc $(CLIBNAME) -ocamlc '$(CAMLC)' -linkall \
+ $(CAMLOBJS) $(LINKOPTS)
+
+$(LIBNAME).cmxa: $(CAMLOBJS_NAT)
+ $(MKLIB) -o $(LIBNAME) -oc $(CLIBNAME) -ocamlopt '$(CAMLOPT)' -linkall \
+ $(CAMLOBJS_NAT) $(LINKOPTS)
+
+$(LIBNAME).cmxs: $(LIBNAME).cmxa lib$(CLIBNAME).$(A)
+ $(CAMLOPT) -shared -o $(LIBNAME).cmxs -I . $(LIBNAME).cmxa
+
+lib$(CLIBNAME).$(A): $(COBJS)
+ $(MKLIB) -oc $(CLIBNAME) $(COBJS) $(LDOPTS)
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+INSTALL_STUBLIBDIR=$(DESTDIR)$(STUBLIBDIR)
+
+install::
+ if test -f dll$(CLIBNAME)$(EXT_DLL); then \
+ cp dll$(CLIBNAME)$(EXT_DLL) $(INSTALL_STUBLIBDIR)/; fi
+ cp lib$(CLIBNAME).$(A) $(INSTALL_LIBDIR)/
+ cd $(INSTALL_LIBDIR); $(RANLIB) lib$(CLIBNAME).$(A)
+ cp $(LIBNAME).cma $(CMIFILES) $(CMIFILES:.cmi=.mli) $(INSTALL_LIBDIR)/
+ if test -n "$(HEADERS)"; then cp $(HEADERS) $(INSTALL_LIBDIR)/caml/; fi
+
+installopt:
+ cp $(CAMLOBJS_NAT) $(LIBNAME).cmxa $(LIBNAME).$(A) $(INSTALL_LIBDIR)/
+ cd $(INSTALL_LIBDIR); $(RANLIB) $(LIBNAME).a
+ if test -f $(LIBNAME).cmxs; then cp $(LIBNAME).cmxs $(INSTALL_LIBDIR)/; fi
+
+partialclean:
+ rm -f *.cm*
+
+clean:: partialclean
+ rm -f *.dll *.so *.a *.lib *.o *.obj
+
+.SUFFIXES: .ml .mli .cmi .cmo .cmx .$(O)
+
+.mli.cmi:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmo:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmx:
+ $(CAMLOPT) -c $(COMPFLAGS) $<
+
+.c.$(O):
+ $(BYTECC) $(BYTECCCOMPOPTS) $(CFLAGS) -c $<
diff --git a/otherlibs/bigarray/.depend b/otherlibs/bigarray/.depend
new file mode 100644
index 0000000000..c7bc326030
--- /dev/null
+++ b/otherlibs/bigarray/.depend
@@ -0,0 +1,27 @@
+bigarray_stubs.o: bigarray_stubs.c ../../byterun/caml/alloc.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/mlvalues.h bigarray.h ../../byterun/caml/config.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/custom.h \
+ ../../byterun/caml/fail.h ../../byterun/caml/intext.h \
+ ../../byterun/caml/io.h ../../byterun/caml/hash.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h
+mmap_unix.o: mmap_unix.c bigarray.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/config.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/custom.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/io.h ../../byterun/caml/sys.h \
+ ../../byterun/caml/signals.h
+mmap_win32.o: mmap_win32.c bigarray.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/config.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/custom.h \
+ ../../byterun/caml/fail.h ../../byterun/caml/sys.h ../unix/unixsupport.h
+bigarray.cmi :
+bigarray.cmo : bigarray.cmi
+bigarray.cmx : bigarray.cmi
diff --git a/otherlibs/bigarray/Makefile b/otherlibs/bigarray/Makefile
new file mode 100644
index 0000000000..3bcc7a4022
--- /dev/null
+++ b/otherlibs/bigarray/Makefile
@@ -0,0 +1,27 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+LIBNAME=bigarray
+EXTRACFLAGS=-I../$(UNIXLIB) -DIN_OCAML_BIGARRAY -DCAML_NAME_SPACE
+EXTRACAMLFLAGS=-I ../$(UNIXLIB)
+COBJS=bigarray_stubs.$(O) mmap_$(UNIX_OR_WIN32).$(O)
+CAMLOBJS=bigarray.cmo
+HEADERS=bigarray.h
+
+include ../Makefile
+
+depend:
+ $(CC) -MM $(CFLAGS) *.c > .depend
+ $(CAMLRUN) ../../tools/ocamldep *.mli *.ml >> .depend
+
+include .depend
diff --git a/otherlibs/bigarray/Makefile.nt b/otherlibs/bigarray/Makefile.nt
new file mode 100644
index 0000000000..baeaa7a160
--- /dev/null
+++ b/otherlibs/bigarray/Makefile.nt
@@ -0,0 +1,27 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+LIBNAME=bigarray
+EXTRACFLAGS=-I../win32unix -DIN_OCAML_BIGARRAY -DCAML_NAME_SPACE
+EXTRACAMLFLAGS=-I ../win32unix
+COBJS=bigarray_stubs.$(O) mmap_win32.$(O)
+CAMLOBJS=bigarray.cmo
+HEADERS=bigarray.h
+
+include ../Makefile.nt
+
+depend:
+ $(CC) -MM $(CFLAGS) *.c > .depend
+ $(CAMLRUN) ../../tools/ocamldep *.mli *.ml >> .depend
+
+include .depend
diff --git a/otherlibs/bigarray/bigarray.h b/otherlibs/bigarray/bigarray.h
new file mode 100644
index 0000000000..23bde23336
--- /dev/null
+++ b/otherlibs/bigarray/bigarray.h
@@ -0,0 +1,123 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Manuel Serrano and Xavier Leroy, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_BIGARRAY_H
+#define CAML_BIGARRAY_H
+
+#ifndef CAML_NAME_SPACE
+#include "caml/compatibility.h"
+#endif
+#include "caml/config.h"
+#include "caml/mlvalues.h"
+
+typedef signed char caml_ba_int8;
+typedef unsigned char caml_ba_uint8;
+#if SIZEOF_SHORT == 2
+typedef short caml_ba_int16;
+typedef unsigned short caml_ba_uint16;
+#else
+#error "No 16-bit integer type available"
+#endif
+
+#define CAML_BA_MAX_NUM_DIMS 16
+
+enum caml_ba_kind {
+ CAML_BA_FLOAT32, /* Single-precision floats */
+ CAML_BA_FLOAT64, /* Double-precision floats */
+ CAML_BA_SINT8, /* Signed 8-bit integers */
+ CAML_BA_UINT8, /* Unsigned 8-bit integers */
+ CAML_BA_SINT16, /* Signed 16-bit integers */
+ CAML_BA_UINT16, /* Unsigned 16-bit integers */
+ CAML_BA_INT32, /* Signed 32-bit integers */
+ CAML_BA_INT64, /* Signed 64-bit integers */
+ CAML_BA_CAML_INT, /* OCaml-style integers (signed 31 or 63 bits) */
+ CAML_BA_NATIVE_INT, /* Platform-native long integers (32 or 64 bits) */
+ CAML_BA_COMPLEX32, /* Single-precision complex */
+ CAML_BA_COMPLEX64, /* Double-precision complex */
+ CAML_BA_CHAR, /* Characters */
+ CAML_BA_KIND_MASK = 0xFF /* Mask for kind in flags field */
+};
+
+#define Caml_ba_kind_val(v) Int_val(v)
+
+#define Val_caml_ba_kind(k) Val_int(k)
+
+enum caml_ba_layout {
+ CAML_BA_C_LAYOUT = 0, /* Row major, indices start at 0 */
+ CAML_BA_FORTRAN_LAYOUT = 0x100, /* Column major, indices start at 1 */
+ CAML_BA_LAYOUT_MASK = 0x100, /* Mask for layout in flags field */
+ CAML_BA_LAYOUT_SHIFT = 8 /* Bit offset of layout flag */
+};
+
+#define Caml_ba_layout_val(v) (Int_val(v) << CAML_BA_LAYOUT_SHIFT)
+
+#define Val_caml_ba_layout(l) Val_int(l >> CAML_BA_LAYOUT_SHIFT)
+
+enum caml_ba_managed {
+ CAML_BA_EXTERNAL = 0, /* Data is not allocated by OCaml */
+ CAML_BA_MANAGED = 0x200, /* Data is allocated by OCaml */
+ CAML_BA_MAPPED_FILE = 0x400, /* Data is a memory mapped file */
+ CAML_BA_MANAGED_MASK = 0x600 /* Mask for "managed" bits in flags field */
+};
+
+struct caml_ba_proxy {
+ intnat refcount; /* Reference count */
+ void * data; /* Pointer to base of actual data */
+ uintnat size; /* Size of data in bytes (if mapped file) */
+};
+
+struct caml_ba_array {
+ void * data; /* Pointer to raw data */
+ intnat num_dims; /* Number of dimensions */
+ intnat flags; /* Kind of element array + memory layout + allocation status */
+ struct caml_ba_proxy * proxy; /* The proxy for sub-arrays, or NULL */
+ /* PR#5516: use C99's flexible array types if possible */
+#if (__STDC_VERSION__ >= 199901L)
+ intnat dim[] /*[num_dims]*/; /* Size in each dimension */
+#else
+ intnat dim[1] /*[num_dims]*/; /* Size in each dimension */
+#endif
+};
+
+/* Size of struct caml_ba_array, in bytes, without dummy first dimension */
+#if (__STDC_VERSION__ >= 199901L)
+#define SIZEOF_BA_ARRAY sizeof(struct caml_ba_array)
+#else
+#define SIZEOF_BA_ARRAY (sizeof(struct caml_ba_array) - sizeof(intnat))
+#endif
+
+#define Caml_ba_array_val(v) ((struct caml_ba_array *) Data_custom_val(v))
+
+#define Caml_ba_data_val(v) (Caml_ba_array_val(v)->data)
+
+#if defined(IN_OCAML_BIGARRAY)
+#define CAMLBAextern CAMLexport
+#else
+#define CAMLBAextern CAMLextern
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAMLBAextern value
+ caml_ba_alloc(int flags, int num_dims, void * data, intnat * dim);
+CAMLBAextern value caml_ba_alloc_dims(int flags, int num_dims, void * data,
+ ... /*dimensions, with type intnat */);
+CAMLBAextern uintnat caml_ba_byte_size(struct caml_ba_array * b);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_BIGARRAY_H */
diff --git a/otherlibs/bigarray/bigarray.ml b/otherlibs/bigarray/bigarray.ml
new file mode 100644
index 0000000000..a037012682
--- /dev/null
+++ b/otherlibs/bigarray/bigarray.ml
@@ -0,0 +1,310 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Manuel Serrano et Xavier Leroy, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [Bigarray]: large, multi-dimensional, numerical arrays *)
+
+external init : unit -> unit = "caml_ba_init"
+
+let _ = init()
+
+type float32_elt = Float32_elt
+type float64_elt = Float64_elt
+type int8_signed_elt = Int8_signed_elt
+type int8_unsigned_elt = Int8_unsigned_elt
+type int16_signed_elt = Int16_signed_elt
+type int16_unsigned_elt = Int16_unsigned_elt
+type int32_elt = Int32_elt
+type int64_elt = Int64_elt
+type int_elt = Int_elt
+type nativeint_elt = Nativeint_elt
+type complex32_elt = Complex32_elt
+type complex64_elt = Complex64_elt
+
+type ('a, 'b) kind =
+ Float32 : (float, float32_elt) kind
+ | Float64 : (float, float64_elt) kind
+ | Int8_signed : (int, int8_signed_elt) kind
+ | Int8_unsigned : (int, int8_unsigned_elt) kind
+ | Int16_signed : (int, int16_signed_elt) kind
+ | Int16_unsigned : (int, int16_unsigned_elt) kind
+ | Int32 : (int32, int32_elt) kind
+ | Int64 : (int64, int64_elt) kind
+ | Int : (int, int_elt) kind
+ | Nativeint : (nativeint, nativeint_elt) kind
+ | Complex32 : (Complex.t, complex32_elt) kind
+ | Complex64 : (Complex.t, complex64_elt) kind
+ | Char : (char, int8_unsigned_elt) kind
+
+(* Keep those constants in sync with the caml_ba_kind enumeration
+ in bigarray.h *)
+
+let float32 = Float32
+let float64 = Float64
+let int8_signed = Int8_signed
+let int8_unsigned = Int8_unsigned
+let int16_signed = Int16_signed
+let int16_unsigned = Int16_unsigned
+let int32 = Int32
+let int64 = Int64
+let int = Int
+let nativeint = Nativeint
+let complex32 = Complex32
+let complex64 = Complex64
+let char = Char
+
+type c_layout = C_layout_typ
+type fortran_layout = Fortran_layout_typ
+
+type 'a layout =
+ C_layout: c_layout layout
+ | Fortran_layout: fortran_layout layout
+
+(* Keep those constants in sync with the caml_ba_layout enumeration
+ in bigarray.h *)
+
+let c_layout = C_layout
+let fortran_layout = Fortran_layout
+
+module Genarray = struct
+ type ('a, 'b, 'c) t
+ external create: ('a, 'b) kind -> 'c layout -> int array -> ('a, 'b, 'c) t
+ = "caml_ba_create"
+ external get: ('a, 'b, 'c) t -> int array -> 'a
+ = "caml_ba_get_generic"
+ external set: ('a, 'b, 'c) t -> int array -> 'a -> unit
+ = "caml_ba_set_generic"
+ external num_dims: ('a, 'b, 'c) t -> int = "caml_ba_num_dims"
+ external nth_dim: ('a, 'b, 'c) t -> int -> int = "caml_ba_dim"
+ let dims a =
+ let n = num_dims a in
+ let d = Array.make n 0 in
+ for i = 0 to n-1 do d.(i) <- nth_dim a i done;
+ d
+ external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind"
+ external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout"
+
+ external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t
+ = "caml_ba_sub"
+ external sub_right: ('a, 'b, fortran_layout) t -> int -> int ->
+ ('a, 'b, fortran_layout) t
+ = "caml_ba_sub"
+ external slice_left: ('a, 'b, c_layout) t -> int array ->
+ ('a, 'b, c_layout) t
+ = "caml_ba_slice"
+ external slice_right: ('a, 'b, fortran_layout) t -> int array ->
+ ('a, 'b, fortran_layout) t
+ = "caml_ba_slice"
+ external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
+ = "caml_ba_blit"
+ external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill"
+ external map_internal: Unix.file_descr -> ('a, 'b) kind -> 'c layout ->
+ bool -> int array -> int64 -> ('a, 'b, 'c) t
+ = "caml_ba_map_file_bytecode" "caml_ba_map_file"
+ let map_file fd ?(pos = 0L) kind layout shared dims =
+ map_internal fd kind layout shared dims pos
+end
+
+module Array1 = struct
+ type ('a, 'b, 'c) t = ('a, 'b, 'c) Genarray.t
+ let create kind layout dim =
+ Genarray.create kind layout [|dim|]
+ external get: ('a, 'b, 'c) t -> int -> 'a = "%caml_ba_ref_1"
+ external set: ('a, 'b, 'c) t -> int -> 'a -> unit = "%caml_ba_set_1"
+ external unsafe_get: ('a, 'b, 'c) t -> int -> 'a = "%caml_ba_unsafe_ref_1"
+ external unsafe_set: ('a, 'b, 'c) t -> int -> 'a -> unit
+ = "%caml_ba_unsafe_set_1"
+ external dim: ('a, 'b, 'c) t -> int = "%caml_ba_dim_1"
+ external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind"
+ external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout"
+ external sub: ('a, 'b, 'c) t -> int -> int -> ('a, 'b, 'c) t = "caml_ba_sub"
+ external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit"
+ external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill"
+ let of_array (type t) kind (layout: t layout) data =
+ let ba = create kind layout (Array.length data) in
+ let ofs =
+ match layout with
+ C_layout -> 0
+ | Fortran_layout -> 1
+ in
+ for i = 0 to Array.length data - 1 do unsafe_set ba (i + ofs) data.(i) done;
+ ba
+ let map_file fd ?pos kind layout shared dim =
+ Genarray.map_file fd ?pos kind layout shared [|dim|]
+end
+
+module Array2 = struct
+ type ('a, 'b, 'c) t = ('a, 'b, 'c) Genarray.t
+ let create kind layout dim1 dim2 =
+ Genarray.create kind layout [|dim1; dim2|]
+ external get: ('a, 'b, 'c) t -> int -> int -> 'a = "%caml_ba_ref_2"
+ external set: ('a, 'b, 'c) t -> int -> int -> 'a -> unit = "%caml_ba_set_2"
+ external unsafe_get: ('a, 'b, 'c) t -> int -> int -> 'a
+ = "%caml_ba_unsafe_ref_2"
+ external unsafe_set: ('a, 'b, 'c) t -> int -> int -> 'a -> unit
+ = "%caml_ba_unsafe_set_2"
+ external dim1: ('a, 'b, 'c) t -> int = "%caml_ba_dim_1"
+ external dim2: ('a, 'b, 'c) t -> int = "%caml_ba_dim_2"
+ external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind"
+ external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout"
+ external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t
+ = "caml_ba_sub"
+ external sub_right:
+ ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t
+ = "caml_ba_sub"
+ let slice_left a n = Genarray.slice_left a [|n|]
+ let slice_right a n = Genarray.slice_right a [|n|]
+ external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit"
+ external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill"
+ let of_array (type t) kind (layout: t layout) data =
+ let dim1 = Array.length data in
+ let dim2 = if dim1 = 0 then 0 else Array.length data.(0) in
+ let ba = create kind layout dim1 dim2 in
+ let ofs =
+ match layout with
+ C_layout -> 0
+ | Fortran_layout -> 1
+ in
+ for i = 0 to dim1 - 1 do
+ let row = data.(i) in
+ if Array.length row <> dim2 then
+ invalid_arg("Bigarray.Array2.of_array: non-rectangular data");
+ for j = 0 to dim2 - 1 do
+ unsafe_set ba (i + ofs) (j + ofs) row.(j)
+ done
+ done;
+ ba
+ let map_file fd ?pos kind layout shared dim1 dim2 =
+ Genarray.map_file fd ?pos kind layout shared [|dim1;dim2|]
+end
+
+module Array3 = struct
+ type ('a, 'b, 'c) t = ('a, 'b, 'c) Genarray.t
+ let create kind layout dim1 dim2 dim3 =
+ Genarray.create kind layout [|dim1; dim2; dim3|]
+ external get: ('a, 'b, 'c) t -> int -> int -> int -> 'a = "%caml_ba_ref_3"
+ external set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
+ = "%caml_ba_set_3"
+ external unsafe_get: ('a, 'b, 'c) t -> int -> int -> int -> 'a
+ = "%caml_ba_unsafe_ref_3"
+ external unsafe_set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
+ = "%caml_ba_unsafe_set_3"
+ external dim1: ('a, 'b, 'c) t -> int = "%caml_ba_dim_1"
+ external dim2: ('a, 'b, 'c) t -> int = "%caml_ba_dim_2"
+ external dim3: ('a, 'b, 'c) t -> int = "%caml_ba_dim_3"
+ external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind"
+ external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout"
+ external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t
+ = "caml_ba_sub"
+ external sub_right:
+ ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t
+ = "caml_ba_sub"
+ let slice_left_1 a n m = Genarray.slice_left a [|n; m|]
+ let slice_right_1 a n m = Genarray.slice_right a [|n; m|]
+ let slice_left_2 a n = Genarray.slice_left a [|n|]
+ let slice_right_2 a n = Genarray.slice_right a [|n|]
+ external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit = "caml_ba_blit"
+ external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill"
+ let of_array (type t) kind (layout: t layout) data =
+ let dim1 = Array.length data in
+ let dim2 = if dim1 = 0 then 0 else Array.length data.(0) in
+ let dim3 = if dim2 = 0 then 0 else Array.length data.(0).(0) in
+ let ba = create kind layout dim1 dim2 dim3 in
+ let ofs =
+ match layout with
+ C_layout -> 0
+ | Fortran_layout -> 1
+ in
+ for i = 0 to dim1 - 1 do
+ let row = data.(i) in
+ if Array.length row <> dim2 then
+ invalid_arg("Bigarray.Array3.of_array: non-cubic data");
+ for j = 0 to dim2 - 1 do
+ let col = row.(j) in
+ if Array.length col <> dim3 then
+ invalid_arg("Bigarray.Array3.of_array: non-cubic data");
+ for k = 0 to dim3 - 1 do
+ unsafe_set ba (i + ofs) (j + ofs) (k + ofs) col.(k)
+ done
+ done
+ done;
+ ba
+ let map_file fd ?pos kind layout shared dim1 dim2 dim3 =
+ Genarray.map_file fd ?pos kind layout shared [|dim1;dim2;dim3|]
+end
+
+external genarray_of_array1: ('a, 'b, 'c) Array1.t -> ('a, 'b, 'c) Genarray.t
+ = "%identity"
+external genarray_of_array2: ('a, 'b, 'c) Array2.t -> ('a, 'b, 'c) Genarray.t
+ = "%identity"
+external genarray_of_array3: ('a, 'b, 'c) Array3.t -> ('a, 'b, 'c) Genarray.t
+ = "%identity"
+let array1_of_genarray a =
+ if Genarray.num_dims a = 1 then a
+ else invalid_arg "Bigarray.array1_of_genarray"
+let array2_of_genarray a =
+ if Genarray.num_dims a = 2 then a
+ else invalid_arg "Bigarray.array2_of_genarray"
+let array3_of_genarray a =
+ if Genarray.num_dims a = 3 then a
+ else invalid_arg "Bigarray.array3_of_genarray"
+
+external reshape:
+ ('a, 'b, 'c) Genarray.t -> int array -> ('a, 'b, 'c) Genarray.t
+ = "caml_ba_reshape"
+let reshape_1 a dim1 = reshape a [|dim1|]
+let reshape_2 a dim1 dim2 = reshape a [|dim1;dim2|]
+let reshape_3 a dim1 dim2 dim3 = reshape a [|dim1;dim2;dim3|]
+
+(* Force caml_ba_get_{1,2,3,N} to be linked in, since we don't refer
+ to those primitives directly in this file *)
+
+let _ =
+ let _ = Genarray.get in
+ let _ = Array1.get in
+ let _ = Array2.get in
+ let _ = Array3.get in
+ ()
+
+external get1: unit -> unit = "caml_ba_get_1"
+external get2: unit -> unit = "caml_ba_get_2"
+external get3: unit -> unit = "caml_ba_get_3"
+external set1: unit -> unit = "caml_ba_set_1"
+external set2: unit -> unit = "caml_ba_set_2"
+external set3: unit -> unit = "caml_ba_set_3"
+
+(* Index operators *)
+
+(* Array1 *)
+external ( .{} ) : ('a, 'b, 'c) Array1.t -> int -> 'a = "%caml_ba_opt_ref_1"
+external ( .{} <- ) : ('a, 'b, 'c) Array1.t -> int -> 'a -> unit
+ = "%caml_ba_opt_set_1"
+
+
+(* Array2 *)
+external ( .{,} ) : ('a, 'b, 'c) Array2.t -> int->int -> 'a
+ = "%caml_ba_opt_ref_2"
+external ( .{,} <- ) : ('a, 'b, 'c) Array2.t -> int->int -> 'a -> unit
+ = "%caml_ba_opt_set_2"
+
+(*Array3*)
+external ( .{,,} ) : ('a, 'b, 'c) Array3.t -> int->int->int -> 'a
+ = "%caml_ba_opt_ref_3"
+external ( .{,,} <- ) : ('a, 'b, 'c) Array3.t -> int->int->int -> 'a -> unit
+ = "%caml_ba_opt_set_3"
+
+
+(*Genarray*)
+external ( .{,..,} ) : ('a, 'b, 'c) Genarray.t -> int array -> 'a
+ = "caml_ba_get_generic"
+external ( .{,..,} <- ) : ('a, 'b, 'c) Genarray.t -> int array -> 'a -> unit
+ = "caml_ba_set_generic"
diff --git a/otherlibs/bigarray/bigarray.mli b/otherlibs/bigarray/bigarray.mli
new file mode 100644
index 0000000000..689c02924a
--- /dev/null
+++ b/otherlibs/bigarray/bigarray.mli
@@ -0,0 +1,885 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Manuel Serrano and Xavier Leroy, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Large, multi-dimensional, numerical arrays.
+
+ This module implements multi-dimensional arrays of integers and
+ floating-point numbers, thereafter referred to as 'big arrays'.
+ The implementation allows efficient sharing of large numerical
+ arrays between OCaml code and C or Fortran numerical libraries.
+
+ Concerning the naming conventions, users of this module are encouraged
+ to do [open Bigarray] in their source, then refer to array types and
+ operations via short dot notation, e.g. [Array1.t] or [Array2.sub].
+
+ Big arrays support all the OCaml ad-hoc polymorphic operations:
+ - comparisons ([=], [<>], [<=], etc, as well as {!Pervasives.compare});
+ - hashing (module [Hash]);
+ - and structured input-output (the functions from the
+ {!Marshal} module, as well as {!Pervasives.output_value}
+ and {!Pervasives.input_value}).
+*)
+
+(** {6 Element kinds} *)
+
+(** Big arrays can contain elements of the following kinds:
+- IEEE single precision (32 bits) floating-point numbers
+ ({!Bigarray.float32_elt}),
+- IEEE double precision (64 bits) floating-point numbers
+ ({!Bigarray.float64_elt}),
+- IEEE single precision (2 * 32 bits) floating-point complex numbers
+ ({!Bigarray.complex32_elt}),
+- IEEE double precision (2 * 64 bits) floating-point complex numbers
+ ({!Bigarray.complex64_elt}),
+- 8-bit integers (signed or unsigned)
+ ({!Bigarray.int8_signed_elt} or {!Bigarray.int8_unsigned_elt}),
+- 16-bit integers (signed or unsigned)
+ ({!Bigarray.int16_signed_elt} or {!Bigarray.int16_unsigned_elt}),
+- OCaml integers (signed, 31 bits on 32-bit architectures,
+ 63 bits on 64-bit architectures) ({!Bigarray.int_elt}),
+- 32-bit signed integer ({!Bigarray.int32_elt}),
+- 64-bit signed integers ({!Bigarray.int64_elt}),
+- platform-native signed integers (32 bits on 32-bit architectures,
+ 64 bits on 64-bit architectures) ({!Bigarray.nativeint_elt}).
+
+ Each element kind is represented at the type level by one of the
+ [*_elt] types defined below (defined with a single constructor instead
+ of abstract types for technical injectivity reasons).
+*)
+
+type float32_elt = Float32_elt
+type float64_elt = Float64_elt
+type int8_signed_elt = Int8_signed_elt
+type int8_unsigned_elt = Int8_unsigned_elt
+type int16_signed_elt = Int16_signed_elt
+type int16_unsigned_elt = Int16_unsigned_elt
+type int32_elt = Int32_elt
+type int64_elt = Int64_elt
+type int_elt = Int_elt
+type nativeint_elt = Nativeint_elt
+type complex32_elt = Complex32_elt
+type complex64_elt = Complex64_elt
+
+type ('a, 'b) kind =
+ Float32 : (float, float32_elt) kind
+ | Float64 : (float, float64_elt) kind
+ | Int8_signed : (int, int8_signed_elt) kind
+ | Int8_unsigned : (int, int8_unsigned_elt) kind
+ | Int16_signed : (int, int16_signed_elt) kind
+ | Int16_unsigned : (int, int16_unsigned_elt) kind
+ | Int32 : (int32, int32_elt) kind
+ | Int64 : (int64, int64_elt) kind
+ | Int : (int, int_elt) kind
+ | Nativeint : (nativeint, nativeint_elt) kind
+ | Complex32 : (Complex.t, complex32_elt) kind
+ | Complex64 : (Complex.t, complex64_elt) kind
+ | Char : (char, int8_unsigned_elt) kind
+(** To each element kind is associated an OCaml type, which is
+ the type of OCaml values that can be stored in the big array
+ or read back from it. This type is not necessarily the same
+ as the type of the array elements proper: for instance,
+ a big array whose elements are of kind [float32_elt] contains
+ 32-bit single precision floats, but reading or writing one of
+ its elements from OCaml uses the OCaml type [float], which is
+ 64-bit double precision floats.
+
+ The GADT type [('a, 'b) kind] captures this association
+ of an OCaml type ['a] for values read or written in the big array,
+ and of an element kind ['b] which represents the actual contents
+ of the big array. Its constructors list all possible associations
+ of OCaml types with element kinds, and are re-exported below for
+ backward-compatibility reasons.
+
+ Using a generalized algebraic datatype (GADT) here allows to write
+ well-typed polymorphic functions whose return type depend on the
+ argument type, such as:
+
+{[
+ let zero : type a b. (a, b) kind -> a = function
+ | Float32 -> 0.0 | Complex32 -> Complex.zero
+ | Float64 -> 0.0 | Complex64 -> Complex.zero
+ | Int8_signed -> 0 | Int8_unsigned -> 0
+ | Int16_signed -> 0 | Int16_unsigned -> 0
+ | Int32 -> 0l | Int64 -> 0L
+ | Int -> 0 | Nativeint -> 0n
+ | Char -> '\000'
+]}
+*)
+
+val float32 : (float, float32_elt) kind
+(** See {!Bigarray.char}. *)
+
+val float64 : (float, float64_elt) kind
+(** See {!Bigarray.char}. *)
+
+val complex32 : (Complex.t, complex32_elt) kind
+(** See {!Bigarray.char}. *)
+
+val complex64 : (Complex.t, complex64_elt) kind
+(** See {!Bigarray.char}. *)
+
+val int8_signed : (int, int8_signed_elt) kind
+(** See {!Bigarray.char}. *)
+
+val int8_unsigned : (int, int8_unsigned_elt) kind
+(** See {!Bigarray.char}. *)
+
+val int16_signed : (int, int16_signed_elt) kind
+(** See {!Bigarray.char}. *)
+
+val int16_unsigned : (int, int16_unsigned_elt) kind
+(** See {!Bigarray.char}. *)
+
+val int : (int, int_elt) kind
+(** See {!Bigarray.char}. *)
+
+val int32 : (int32, int32_elt) kind
+(** See {!Bigarray.char}. *)
+
+val int64 : (int64, int64_elt) kind
+(** See {!Bigarray.char}. *)
+
+val nativeint : (nativeint, nativeint_elt) kind
+(** See {!Bigarray.char}. *)
+
+val char : (char, int8_unsigned_elt) kind
+(** As shown by the types of the values above,
+ big arrays of kind [float32_elt] and [float64_elt] are
+ accessed using the OCaml type [float]. Big arrays of complex kinds
+ [complex32_elt], [complex64_elt] are accessed with the OCaml type
+ {!Complex.t}. Big arrays of
+ integer kinds are accessed using the smallest OCaml integer
+ type large enough to represent the array elements:
+ [int] for 8- and 16-bit integer bigarrays, as well as OCaml-integer
+ bigarrays; [int32] for 32-bit integer bigarrays; [int64]
+ for 64-bit integer bigarrays; and [nativeint] for
+ platform-native integer bigarrays. Finally, big arrays of
+ kind [int8_unsigned_elt] can also be accessed as arrays of
+ characters instead of arrays of small integers, by using
+ the kind value [char] instead of [int8_unsigned]. *)
+
+(** {6 Array layouts} *)
+
+type c_layout = C_layout_typ
+(** See {!Bigarray.fortran_layout}.*)
+
+type fortran_layout = Fortran_layout_typ
+(** To facilitate interoperability with existing C and Fortran code,
+ this library supports two different memory layouts for big arrays,
+ one compatible with the C conventions,
+ the other compatible with the Fortran conventions.
+
+ In the C-style layout, array indices start at 0, and
+ multi-dimensional arrays are laid out in row-major format.
+ That is, for a two-dimensional array, all elements of
+ row 0 are contiguous in memory, followed by all elements of
+ row 1, etc. In other terms, the array elements at [(x,y)]
+ and [(x, y+1)] are adjacent in memory.
+
+ In the Fortran-style layout, array indices start at 1, and
+ multi-dimensional arrays are laid out in column-major format.
+ That is, for a two-dimensional array, all elements of
+ column 0 are contiguous in memory, followed by all elements of
+ column 1, etc. In other terms, the array elements at [(x,y)]
+ and [(x+1, y)] are adjacent in memory.
+
+ Each layout style is identified at the type level by the
+ phantom types {!Bigarray.c_layout} and {!Bigarray.fortran_layout}
+ respectively. *)
+
+(** {7 Supported layouts}
+
+ The GADT type ['a layout] represents one of the two supported
+ memory layouts: C-style or Fortran-style. Its constructors are
+ re-exported as values below for backward-compatibility reasons.
+*)
+
+type 'a layout =
+ C_layout: c_layout layout
+ | Fortran_layout: fortran_layout layout
+
+val c_layout : c_layout layout
+val fortran_layout : fortran_layout layout
+
+
+(** {6 Generic arrays (of arbitrarily many dimensions)} *)
+
+module Genarray :
+ sig
+ type ('a, 'b, 'c) t
+ (** The type [Genarray.t] is the type of big arrays with variable
+ numbers of dimensions. Any number of dimensions between 1 and 16
+ is supported.
+
+ The three type parameters to [Genarray.t] identify the array element
+ kind and layout, as follows:
+ - the first parameter, ['a], is the OCaml type for accessing array
+ elements ([float], [int], [int32], [int64], [nativeint]);
+ - the second parameter, ['b], is the actual kind of array elements
+ ([float32_elt], [float64_elt], [int8_signed_elt], [int8_unsigned_elt],
+ etc);
+ - the third parameter, ['c], identifies the array layout
+ ([c_layout] or [fortran_layout]).
+
+ For instance, [(float, float32_elt, fortran_layout) Genarray.t]
+ is the type of generic big arrays containing 32-bit floats
+ in Fortran layout; reads and writes in this array use the
+ OCaml type [float]. *)
+
+ external create: ('a, 'b) kind -> 'c layout -> int array -> ('a, 'b, 'c) t
+ = "caml_ba_create"
+ (** [Genarray.create kind layout dimensions] returns a new big array
+ whose element kind is determined by the parameter [kind] (one of
+ [float32], [float64], [int8_signed], etc) and whose layout is
+ determined by the parameter [layout] (one of [c_layout] or
+ [fortran_layout]). The [dimensions] parameter is an array of
+ integers that indicate the size of the big array in each dimension.
+ The length of [dimensions] determines the number of dimensions
+ of the bigarray.
+
+ For instance, [Genarray.create int32 c_layout [|4;6;8|]]
+ returns a fresh big array of 32-bit integers, in C layout,
+ having three dimensions, the three dimensions being 4, 6 and 8
+ respectively.
+
+ Big arrays returned by [Genarray.create] are not initialized:
+ the initial values of array elements is unspecified.
+
+ [Genarray.create] raises [Invalid_argument] if the number of dimensions
+ is not in the range 1 to 16 inclusive, or if one of the dimensions
+ is negative. *)
+
+ external num_dims: ('a, 'b, 'c) t -> int = "caml_ba_num_dims"
+ (** Return the number of dimensions of the given big array. *)
+
+ val dims : ('a, 'b, 'c) t -> int array
+ (** [Genarray.dims a] returns all dimensions of the big array [a],
+ as an array of integers of length [Genarray.num_dims a]. *)
+
+ external nth_dim: ('a, 'b, 'c) t -> int -> int = "caml_ba_dim"
+ (** [Genarray.nth_dim a n] returns the [n]-th dimension of the
+ big array [a]. The first dimension corresponds to [n = 0];
+ the second dimension corresponds to [n = 1]; the last dimension,
+ to [n = Genarray.num_dims a - 1].
+ Raise [Invalid_argument] if [n] is less than 0 or greater or equal than
+ [Genarray.num_dims a]. *)
+
+ external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind"
+ (** Return the kind of the given big array. *)
+
+ external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout"
+ (** Return the layout of the given big array. *)
+
+ external get: ('a, 'b, 'c) t -> int array -> 'a = "caml_ba_get_generic"
+ (** Read an element of a generic big array.
+ [Genarray.get a [|i1; ...; iN|]] returns the element of [a]
+ whose coordinates are [i1] in the first dimension, [i2] in
+ the second dimension, ..., [iN] in the [N]-th dimension.
+
+ If [a] has C layout, the coordinates must be greater or equal than 0
+ and strictly less than the corresponding dimensions of [a].
+ If [a] has Fortran layout, the coordinates must be greater or equal
+ than 1 and less or equal than the corresponding dimensions of [a].
+ Raise [Invalid_argument] if the array [a] does not have exactly [N]
+ dimensions, or if the coordinates are outside the array bounds.
+
+ If [N > 3], alternate syntax is provided: you can write
+ [a.{i1, i2, ..., iN}] instead of [Genarray.get a [|i1; ...; iN|]].
+ (The syntax [a.{...}] with one, two or three coordinates is
+ reserved for accessing one-, two- and three-dimensional arrays
+ as described below.) *)
+
+ external set: ('a, 'b, 'c) t -> int array -> 'a -> unit
+ = "caml_ba_set_generic"
+ (** Assign an element of a generic big array.
+ [Genarray.set a [|i1; ...; iN|] v] stores the value [v] in the
+ element of [a] whose coordinates are [i1] in the first dimension,
+ [i2] in the second dimension, ..., [iN] in the [N]-th dimension.
+
+ The array [a] must have exactly [N] dimensions, and all coordinates
+ must lie inside the array bounds, as described for [Genarray.get];
+ otherwise, [Invalid_argument] is raised.
+
+ If [N > 3], alternate syntax is provided: you can write
+ [a.{i1, i2, ..., iN} <- v] instead of
+ [Genarray.set a [|i1; ...; iN|] v].
+ (The syntax [a.{...} <- v] with one, two or three coordinates is
+ reserved for updating one-, two- and three-dimensional arrays
+ as described below.) *)
+
+ external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t
+ = "caml_ba_sub"
+ (** Extract a sub-array of the given big array by restricting the
+ first (left-most) dimension. [Genarray.sub_left a ofs len]
+ returns a big array with the same number of dimensions as [a],
+ and the same dimensions as [a], except the first dimension,
+ which corresponds to the interval [[ofs ... ofs + len - 1]]
+ of the first dimension of [a]. No copying of elements is
+ involved: the sub-array and the original array share the same
+ storage space. In other terms, the element at coordinates
+ [[|i1; ...; iN|]] of the sub-array is identical to the
+ element at coordinates [[|i1+ofs; ...; iN|]] of the original
+ array [a].
+
+ [Genarray.sub_left] applies only to big arrays in C layout.
+ Raise [Invalid_argument] if [ofs] and [len] do not designate
+ a valid sub-array of [a], that is, if [ofs < 0], or [len < 0],
+ or [ofs + len > Genarray.nth_dim a 0]. *)
+
+ external sub_right:
+ ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t
+ = "caml_ba_sub"
+ (** Extract a sub-array of the given big array by restricting the
+ last (right-most) dimension. [Genarray.sub_right a ofs len]
+ returns a big array with the same number of dimensions as [a],
+ and the same dimensions as [a], except the last dimension,
+ which corresponds to the interval [[ofs ... ofs + len - 1]]
+ of the last dimension of [a]. No copying of elements is
+ involved: the sub-array and the original array share the same
+ storage space. In other terms, the element at coordinates
+ [[|i1; ...; iN|]] of the sub-array is identical to the
+ element at coordinates [[|i1; ...; iN+ofs|]] of the original
+ array [a].
+
+ [Genarray.sub_right] applies only to big arrays in Fortran layout.
+ Raise [Invalid_argument] if [ofs] and [len] do not designate
+ a valid sub-array of [a], that is, if [ofs < 1], or [len < 0],
+ or [ofs + len > Genarray.nth_dim a (Genarray.num_dims a - 1)]. *)
+
+ external slice_left:
+ ('a, 'b, c_layout) t -> int array -> ('a, 'b, c_layout) t
+ = "caml_ba_slice"
+ (** Extract a sub-array of lower dimension from the given big array
+ by fixing one or several of the first (left-most) coordinates.
+ [Genarray.slice_left a [|i1; ... ; iM|]] returns the 'slice'
+ of [a] obtained by setting the first [M] coordinates to
+ [i1], ..., [iM]. If [a] has [N] dimensions, the slice has
+ dimension [N - M], and the element at coordinates
+ [[|j1; ...; j(N-M)|]] in the slice is identical to the element
+ at coordinates [[|i1; ...; iM; j1; ...; j(N-M)|]] in the original
+ array [a]. No copying of elements is involved: the slice and
+ the original array share the same storage space.
+
+ [Genarray.slice_left] applies only to big arrays in C layout.
+ Raise [Invalid_argument] if [M >= N], or if [[|i1; ... ; iM|]]
+ is outside the bounds of [a]. *)
+
+ external slice_right:
+ ('a, 'b, fortran_layout) t -> int array -> ('a, 'b, fortran_layout) t
+ = "caml_ba_slice"
+ (** Extract a sub-array of lower dimension from the given big array
+ by fixing one or several of the last (right-most) coordinates.
+ [Genarray.slice_right a [|i1; ... ; iM|]] returns the 'slice'
+ of [a] obtained by setting the last [M] coordinates to
+ [i1], ..., [iM]. If [a] has [N] dimensions, the slice has
+ dimension [N - M], and the element at coordinates
+ [[|j1; ...; j(N-M)|]] in the slice is identical to the element
+ at coordinates [[|j1; ...; j(N-M); i1; ...; iM|]] in the original
+ array [a]. No copying of elements is involved: the slice and
+ the original array share the same storage space.
+
+ [Genarray.slice_right] applies only to big arrays in Fortran layout.
+ Raise [Invalid_argument] if [M >= N], or if [[|i1; ... ; iM|]]
+ is outside the bounds of [a]. *)
+
+ external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
+ = "caml_ba_blit"
+ (** Copy all elements of a big array in another big array.
+ [Genarray.blit src dst] copies all elements of [src] into
+ [dst]. Both arrays [src] and [dst] must have the same number of
+ dimensions and equal dimensions. Copying a sub-array of [src]
+ to a sub-array of [dst] can be achieved by applying [Genarray.blit]
+ to sub-array or slices of [src] and [dst]. *)
+
+ external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill"
+ (** Set all elements of a big array to a given value.
+ [Genarray.fill a v] stores the value [v] in all elements of
+ the big array [a]. Setting only some elements of [a] to [v]
+ can be achieved by applying [Genarray.fill] to a sub-array
+ or a slice of [a]. *)
+
+ val map_file:
+ Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout ->
+ bool -> int array -> ('a, 'b, 'c) t
+ (** Memory mapping of a file as a big array.
+ [Genarray.map_file fd kind layout shared dims]
+ returns a big array of kind [kind], layout [layout],
+ and dimensions as specified in [dims]. The data contained in
+ this big array are the contents of the file referred to by
+ the file descriptor [fd] (as opened previously with
+ [Unix.openfile], for example). The optional [pos] parameter
+ is the byte offset in the file of the data being mapped;
+ it defaults to 0 (map from the beginning of the file).
+
+ If [shared] is [true], all modifications performed on the array
+ are reflected in the file. This requires that [fd] be opened
+ with write permissions. If [shared] is [false], modifications
+ performed on the array are done in memory only, using
+ copy-on-write of the modified pages; the underlying file is not
+ affected.
+
+ [Genarray.map_file] is much more efficient than reading
+ the whole file in a big array, modifying that big array,
+ and writing it afterwards.
+
+ To adjust automatically the dimensions of the big array to
+ the actual size of the file, the major dimension (that is,
+ the first dimension for an array with C layout, and the last
+ dimension for an array with Fortran layout) can be given as
+ [-1]. [Genarray.map_file] then determines the major dimension
+ from the size of the file. The file must contain an integral
+ number of sub-arrays as determined by the non-major dimensions,
+ otherwise [Failure] is raised.
+
+ If all dimensions of the big array are given, the file size is
+ matched against the size of the big array. If the file is larger
+ than the big array, only the initial portion of the file is
+ mapped to the big array. If the file is smaller than the big
+ array, the file is automatically grown to the size of the big array.
+ This requires write permissions on [fd].
+
+ Array accesses are bounds-checked, but the bounds are determined by
+ the initial call to [map_file]. Therefore, you should make sure no
+ other process modifies the mapped file while you're accessing it,
+ or a SIGBUS signal may be raised. This happens, for instance, if the
+ file is shrunk.
+
+ This function raises [Sys_error] in the case of any errors from the
+ underlying system calls. [Invalid_argument] or [Failure] may be
+ raised in cases where argument validation fails. *)
+
+ end
+
+external ( .{,..,} ) : ('a, 'b, 'c) Genarray.t -> int array -> 'a
+ = "caml_ba_get_generic"
+(** Index operator for generic arrays. When the [Bigarray] module is
+ open, [ bigarray.{a,b,c,d,...} ] is desugared to [ (.{,..,} )
+ bigarray [|a,b,c,d,...|] ]. *)
+
+external ( .{,..,} <- ) : ('a, 'b, 'c) Genarray.t -> int array -> 'a -> unit
+ = "caml_ba_set_generic"
+(** Indexed assignment operator for generic arrays. When the
+ [Bigarray] module is open, [ bigarray.{a,b,c,d,...} <- x ] is
+ desugared to [ (.{,..,} ) bigarray [|a,b,c,d,...|] x ]. *)
+
+(** {6 One-dimensional arrays} *)
+
+(** One-dimensional arrays. The [Array1] structure provides operations
+ similar to those of
+ {!Bigarray.Genarray}, but specialized to the case of one-dimensional arrays.
+ (The [Array2] and [Array3] structures below provide operations
+ specialized for two- and three-dimensional arrays.)
+ Statically knowing the number of dimensions of the array allows
+ faster operations, and more precise static type-checking. *)
+module Array1 : sig
+ type ('a, 'b, 'c) t
+ (** The type of one-dimensional big arrays whose elements have
+ OCaml type ['a], representation kind ['b], and memory layout ['c]. *)
+
+ val create: ('a, 'b) kind -> 'c layout -> int -> ('a, 'b, 'c) t
+ (** [Array1.create kind layout dim] returns a new bigarray of
+ one dimension, whose size is [dim]. [kind] and [layout]
+ determine the array element kind and the array layout
+ as described for [Genarray.create]. *)
+
+ external dim: ('a, 'b, 'c) t -> int = "%caml_ba_dim_1"
+ (** Return the size (dimension) of the given one-dimensional
+ big array. *)
+
+ external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind"
+ (** Return the kind of the given big array. *)
+
+ external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout"
+ (** Return the layout of the given big array. *)
+
+ external get: ('a, 'b, 'c) t -> int -> 'a = "%caml_ba_ref_1"
+ (** [Array1.get a x], or alternatively [a.{x}],
+ returns the element of [a] at index [x].
+ [x] must be greater or equal than [0] and strictly less than
+ [Array1.dim a] if [a] has C layout. If [a] has Fortran layout,
+ [x] must be greater or equal than [1] and less or equal than
+ [Array1.dim a]. Otherwise, [Invalid_argument] is raised. *)
+
+ external set: ('a, 'b, 'c) t -> int -> 'a -> unit = "%caml_ba_set_1"
+ (** [Array1.set a x v], also written [a.{x} <- v],
+ stores the value [v] at index [x] in [a].
+ [x] must be inside the bounds of [a] as described in
+ {!Bigarray.Array1.get};
+ otherwise, [Invalid_argument] is raised. *)
+
+ external sub: ('a, 'b, 'c) t -> int -> int -> ('a, 'b, 'c) t
+ = "caml_ba_sub"
+ (** Extract a sub-array of the given one-dimensional big array.
+ See [Genarray.sub_left] for more details. *)
+
+ external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
+ = "caml_ba_blit"
+ (** Copy the first big array to the second big array.
+ See [Genarray.blit] for more details. *)
+
+ external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill"
+ (** Fill the given big array with the given value.
+ See [Genarray.fill] for more details. *)
+
+ val of_array: ('a, 'b) kind -> 'c layout -> 'a array -> ('a, 'b, 'c) t
+ (** Build a one-dimensional big array initialized from the
+ given array. *)
+
+ val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout ->
+ bool -> int -> ('a, 'b, 'c) t
+ (** Memory mapping of a file as a one-dimensional big array.
+ See {!Bigarray.Genarray.map_file} for more details. *)
+
+ external unsafe_get: ('a, 'b, 'c) t -> int -> 'a = "%caml_ba_unsafe_ref_1"
+ (** Like {!Bigarray.Array1.get}, but bounds checking is not always performed.
+ Use with caution and only when the program logic guarantees that
+ the access is within bounds. *)
+
+ external unsafe_set: ('a, 'b, 'c) t -> int -> 'a -> unit
+ = "%caml_ba_unsafe_set_1"
+ (** Like {!Bigarray.Array1.set}, but bounds checking is not always performed.
+ Use with caution and only when the program logic guarantees that
+ the access is within bounds. *)
+
+end
+
+external ( .{} ) : ('a, 'b, 'c) Array1.t -> int -> 'a = "%caml_ba_opt_ref_1"
+(** Index operator for one-dimensional arrays. When the [Bigarray]
+ module is open, [ bigarray.{a} ] is desugared to [ (.{} ) bigarray a
+ ]. *)
+
+external ( .{} <- ) : ('a, 'b, 'c) Array1.t -> int -> 'a -> unit
+ = "%caml_ba_opt_set_1"
+(** Indexed assignment operator for one-dimensional arrays. When the
+ [Bigarray] module is open, [ bigarray.{a} <- x ] is desugared to [
+ (.{} ) bigarray x ]. *)
+
+(** {6 Two-dimensional arrays} *)
+
+(** Two-dimensional arrays. The [Array2] structure provides operations
+ similar to those of {!Bigarray.Genarray}, but specialized to the
+ case of two-dimensional arrays. *)
+module Array2 :
+ sig
+ type ('a, 'b, 'c) t
+ (** The type of two-dimensional big arrays whose elements have
+ OCaml type ['a], representation kind ['b], and memory layout ['c]. *)
+
+ val create: ('a, 'b) kind -> 'c layout -> int -> int -> ('a, 'b, 'c) t
+ (** [Array2.create kind layout dim1 dim2] returns a new bigarray of
+ two dimension, whose size is [dim1] in the first dimension
+ and [dim2] in the second dimension. [kind] and [layout]
+ determine the array element kind and the array layout
+ as described for {!Bigarray.Genarray.create}. *)
+
+ external dim1: ('a, 'b, 'c) t -> int = "%caml_ba_dim_1"
+ (** Return the first dimension of the given two-dimensional big array. *)
+
+ external dim2: ('a, 'b, 'c) t -> int = "%caml_ba_dim_2"
+ (** Return the second dimension of the given two-dimensional big array. *)
+
+ external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind"
+ (** Return the kind of the given big array. *)
+
+ external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout"
+ (** Return the layout of the given big array. *)
+
+ external get: ('a, 'b, 'c) t -> int -> int -> 'a = "%caml_ba_ref_2"
+ (** [Array2.get a x y], also written [a.{x,y}],
+ returns the element of [a] at coordinates ([x], [y]).
+ [x] and [y] must be within the bounds
+ of [a], as described for {!Bigarray.Genarray.get};
+ otherwise, [Invalid_argument] is raised. *)
+
+ external set: ('a, 'b, 'c) t -> int -> int -> 'a -> unit = "%caml_ba_set_2"
+ (** [Array2.set a x y v], or alternatively [a.{x,y} <- v],
+ stores the value [v] at coordinates ([x], [y]) in [a].
+ [x] and [y] must be within the bounds of [a],
+ as described for {!Bigarray.Genarray.set};
+ otherwise, [Invalid_argument] is raised. *)
+
+ external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t
+ = "caml_ba_sub"
+ (** Extract a two-dimensional sub-array of the given two-dimensional
+ big array by restricting the first dimension.
+ See {!Bigarray.Genarray.sub_left} for more details.
+ [Array2.sub_left] applies only to arrays with C layout. *)
+
+ external sub_right:
+ ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t
+ = "caml_ba_sub"
+ (** Extract a two-dimensional sub-array of the given two-dimensional
+ big array by restricting the second dimension.
+ See {!Bigarray.Genarray.sub_right} for more details.
+ [Array2.sub_right] applies only to arrays with Fortran layout. *)
+
+ val slice_left: ('a, 'b, c_layout) t -> int -> ('a, 'b, c_layout) Array1.t
+ (** Extract a row (one-dimensional slice) of the given two-dimensional
+ big array. The integer parameter is the index of the row to
+ extract. See {!Bigarray.Genarray.slice_left} for more details.
+ [Array2.slice_left] applies only to arrays with C layout. *)
+
+ val slice_right:
+ ('a, 'b, fortran_layout) t -> int -> ('a, 'b, fortran_layout) Array1.t
+ (** Extract a column (one-dimensional slice) of the given
+ two-dimensional big array. The integer parameter is the
+ index of the column to extract. See {!Bigarray.Genarray.slice_right}
+ for more details. [Array2.slice_right] applies only to arrays
+ with Fortran layout. *)
+
+ external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
+ = "caml_ba_blit"
+ (** Copy the first big array to the second big array.
+ See {!Bigarray.Genarray.blit} for more details. *)
+
+ external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill"
+ (** Fill the given big array with the given value.
+ See {!Bigarray.Genarray.fill} for more details. *)
+
+ val of_array: ('a, 'b) kind -> 'c layout -> 'a array array -> ('a, 'b, 'c) t
+ (** Build a two-dimensional big array initialized from the
+ given array of arrays. *)
+
+ val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout ->
+ bool -> int -> int -> ('a, 'b, 'c) t
+ (** Memory mapping of a file as a two-dimensional big array.
+ See {!Bigarray.Genarray.map_file} for more details. *)
+
+ external unsafe_get: ('a, 'b, 'c) t -> int -> int -> 'a
+ = "%caml_ba_unsafe_ref_2"
+ (** Like {!Bigarray.Array2.get}, but bounds checking is not always
+ performed. *)
+
+ external unsafe_set: ('a, 'b, 'c) t -> int -> int -> 'a -> unit
+ = "%caml_ba_unsafe_set_2"
+ (** Like {!Bigarray.Array2.set}, but bounds checking is not always
+ performed. *)
+
+end
+
+external ( .{,} ) : ('a, 'b, 'c) Array2.t -> int -> int -> 'a
+ = "%caml_ba_opt_ref_2"
+(** Index operator for bidimensional arrays. When the [Bigarray] module is open,
+ [ bigarray.{a,b} ] is desugared to [ (.{,} ) bigarray a b ].
+ *)
+
+external ( .{,} <- ) : ('a, 'b, 'c) Array2.t -> int -> int -> 'a -> unit
+ = "%caml_ba_opt_set_2"
+(** Indexed assignment operator for bidimensionnal arrays. When the
+ [Bigarray] module is open, [ bigarray.{a,b} <- x ] is desugared to
+ [ (.{,} ) bigarray a b x ]. *)
+
+
+(** {6 Three-dimensional arrays} *)
+
+(** Three-dimensional arrays. The [Array3] structure provides operations
+ similar to those of {!Bigarray.Genarray}, but specialized to the case
+ of three-dimensional arrays. *)
+module Array3 :
+ sig
+ type ('a, 'b, 'c) t
+ (** The type of three-dimensional big arrays whose elements have
+ OCaml type ['a], representation kind ['b], and memory layout ['c]. *)
+
+ val create: ('a, 'b) kind -> 'c layout -> int -> int -> int -> ('a, 'b, 'c) t
+ (** [Array3.create kind layout dim1 dim2 dim3] returns a new bigarray of
+ three dimension, whose size is [dim1] in the first dimension,
+ [dim2] in the second dimension, and [dim3] in the third.
+ [kind] and [layout] determine the array element kind and
+ the array layout as described for {!Bigarray.Genarray.create}. *)
+
+ external dim1: ('a, 'b, 'c) t -> int = "%caml_ba_dim_1"
+ (** Return the first dimension of the given three-dimensional big array. *)
+
+ external dim2: ('a, 'b, 'c) t -> int = "%caml_ba_dim_2"
+ (** Return the second dimension of the given three-dimensional big array. *)
+
+ external dim3: ('a, 'b, 'c) t -> int = "%caml_ba_dim_3"
+ (** Return the third dimension of the given three-dimensional big array. *)
+
+ external kind: ('a, 'b, 'c) t -> ('a, 'b) kind = "caml_ba_kind"
+ (** Return the kind of the given big array. *)
+
+ external layout: ('a, 'b, 'c) t -> 'c layout = "caml_ba_layout"
+ (** Return the layout of the given big array. *)
+
+ external get: ('a, 'b, 'c) t -> int -> int -> int -> 'a = "%caml_ba_ref_3"
+ (** [Array3.get a x y z], also written [a.{x,y,z}],
+ returns the element of [a] at coordinates ([x], [y], [z]).
+ [x], [y] and [z] must be within the bounds of [a],
+ as described for {!Bigarray.Genarray.get};
+ otherwise, [Invalid_argument] is raised. *)
+
+ external set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
+ = "%caml_ba_set_3"
+ (** [Array3.set a x y v], or alternatively [a.{x,y,z} <- v],
+ stores the value [v] at coordinates ([x], [y], [z]) in [a].
+ [x], [y] and [z] must be within the bounds of [a],
+ as described for {!Bigarray.Genarray.set};
+ otherwise, [Invalid_argument] is raised. *)
+
+ external sub_left: ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) t
+ = "caml_ba_sub"
+ (** Extract a three-dimensional sub-array of the given
+ three-dimensional big array by restricting the first dimension.
+ See {!Bigarray.Genarray.sub_left} for more details. [Array3.sub_left]
+ applies only to arrays with C layout. *)
+
+ external sub_right:
+ ('a, 'b, fortran_layout) t -> int -> int -> ('a, 'b, fortran_layout) t
+ = "caml_ba_sub"
+ (** Extract a three-dimensional sub-array of the given
+ three-dimensional big array by restricting the second dimension.
+ See {!Bigarray.Genarray.sub_right} for more details. [Array3.sub_right]
+ applies only to arrays with Fortran layout. *)
+
+ val slice_left_1:
+ ('a, 'b, c_layout) t -> int -> int -> ('a, 'b, c_layout) Array1.t
+ (** Extract a one-dimensional slice of the given three-dimensional
+ big array by fixing the first two coordinates.
+ The integer parameters are the coordinates of the slice to
+ extract. See {!Bigarray.Genarray.slice_left} for more details.
+ [Array3.slice_left_1] applies only to arrays with C layout. *)
+
+ val slice_right_1:
+ ('a, 'b, fortran_layout) t ->
+ int -> int -> ('a, 'b, fortran_layout) Array1.t
+ (** Extract a one-dimensional slice of the given three-dimensional
+ big array by fixing the last two coordinates.
+ The integer parameters are the coordinates of the slice to
+ extract. See {!Bigarray.Genarray.slice_right} for more details.
+ [Array3.slice_right_1] applies only to arrays with Fortran
+ layout. *)
+
+ val slice_left_2: ('a, 'b, c_layout) t -> int -> ('a, 'b, c_layout) Array2.t
+ (** Extract a two-dimensional slice of the given three-dimensional
+ big array by fixing the first coordinate.
+ The integer parameter is the first coordinate of the slice to
+ extract. See {!Bigarray.Genarray.slice_left} for more details.
+ [Array3.slice_left_2] applies only to arrays with C layout. *)
+
+ val slice_right_2:
+ ('a, 'b, fortran_layout) t -> int -> ('a, 'b, fortran_layout) Array2.t
+ (** Extract a two-dimensional slice of the given
+ three-dimensional big array by fixing the last coordinate.
+ The integer parameter is the coordinate of the slice
+ to extract. See {!Bigarray.Genarray.slice_right} for more details.
+ [Array3.slice_right_2] applies only to arrays with Fortran
+ layout. *)
+
+ external blit: ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> unit
+ = "caml_ba_blit"
+ (** Copy the first big array to the second big array.
+ See {!Bigarray.Genarray.blit} for more details. *)
+
+ external fill: ('a, 'b, 'c) t -> 'a -> unit = "caml_ba_fill"
+ (** Fill the given big array with the given value.
+ See {!Bigarray.Genarray.fill} for more details. *)
+
+ val of_array:
+ ('a, 'b) kind -> 'c layout -> 'a array array array -> ('a, 'b, 'c) t
+ (** Build a three-dimensional big array initialized from the
+ given array of arrays of arrays. *)
+
+ val map_file: Unix.file_descr -> ?pos:int64 -> ('a, 'b) kind -> 'c layout ->
+ bool -> int -> int -> int -> ('a, 'b, 'c) t
+ (** Memory mapping of a file as a three-dimensional big array.
+ See {!Bigarray.Genarray.map_file} for more details. *)
+
+ external unsafe_get: ('a, 'b, 'c) t -> int -> int -> int -> 'a
+ = "%caml_ba_unsafe_ref_3"
+ (** Like {!Bigarray.Array3.get}, but bounds checking is not always
+ performed. *)
+
+ external unsafe_set: ('a, 'b, 'c) t -> int -> int -> int -> 'a -> unit
+ = "%caml_ba_unsafe_set_3"
+ (** Like {!Bigarray.Array3.set}, but bounds checking is not always
+ performed. *)
+
+end
+
+external ( .{,,} ) : ('a, 'b, 'c) Array3.t -> int -> int -> int -> 'a
+ = "%caml_ba_opt_ref_3"
+(** Index operator for tridimensional arrays. When the [Bigarray]
+ module is open, [ bigarray.{a,b,c} ] is desugared to
+ [ (.{,} ) bigarray a b c ]. *)
+
+external ( .{,,} <- ) : ('a, 'b, 'c) Array3.t -> int -> int -> int -> 'a -> unit
+ = "%caml_ba_opt_set_3"
+(** Indexed assignment operator for tridimensionnal arrays. When the
+ [Bigarray] module is open, [ bigarray.{a,b,c} <- x ] is desugared to
+ [ (.{,,} ) bigarray a b c x ]. *)
+
+(** {6 Coercions between generic big arrays and fixed-dimension big arrays} *)
+
+external genarray_of_array1 :
+ ('a, 'b, 'c) Array1.t -> ('a, 'b, 'c) Genarray.t = "%identity"
+(** Return the generic big array corresponding to the given one-dimensional
+ big array. *)
+
+external genarray_of_array2 :
+ ('a, 'b, 'c) Array2.t -> ('a, 'b, 'c) Genarray.t = "%identity"
+(** Return the generic big array corresponding to the given two-dimensional
+ big array. *)
+
+external genarray_of_array3 :
+ ('a, 'b, 'c) Array3.t -> ('a, 'b, 'c) Genarray.t = "%identity"
+(** Return the generic big array corresponding to the given three-dimensional
+ big array. *)
+
+val array1_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array1.t
+(** Return the one-dimensional big array corresponding to the given
+ generic big array. Raise [Invalid_argument] if the generic big array
+ does not have exactly one dimension. *)
+
+val array2_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array2.t
+(** Return the two-dimensional big array corresponding to the given
+ generic big array. Raise [Invalid_argument] if the generic big array
+ does not have exactly two dimensions. *)
+
+val array3_of_genarray : ('a, 'b, 'c) Genarray.t -> ('a, 'b, 'c) Array3.t
+(** Return the three-dimensional big array corresponding to the given
+ generic big array. Raise [Invalid_argument] if the generic big array
+ does not have exactly three dimensions. *)
+
+
+(** {6 Re-shaping big arrays} *)
+
+val reshape : ('a, 'b, 'c) Genarray.t -> int array -> ('a, 'b, 'c) Genarray.t
+(** [reshape b [|d1;...;dN|]] converts the big array [b] to a
+ [N]-dimensional array of dimensions [d1]...[dN]. The returned
+ array and the original array [b] share their data
+ and have the same layout. For instance, assuming that [b]
+ is a one-dimensional array of dimension 12, [reshape b [|3;4|]]
+ returns a two-dimensional array [b'] of dimensions 3 and 4.
+ If [b] has C layout, the element [(x,y)] of [b'] corresponds
+ to the element [x * 3 + y] of [b]. If [b] has Fortran layout,
+ the element [(x,y)] of [b'] corresponds to the element
+ [x + (y - 1) * 4] of [b].
+ The returned big array must have exactly the same number of
+ elements as the original big array [b]. That is, the product
+ of the dimensions of [b] must be equal to [i1 * ... * iN].
+ Otherwise, [Invalid_argument] is raised. *)
+
+val reshape_1 : ('a, 'b, 'c) Genarray.t -> int -> ('a, 'b, 'c) Array1.t
+(** Specialized version of {!Bigarray.reshape} for reshaping to
+ one-dimensional arrays. *)
+
+val reshape_2 : ('a, 'b, 'c) Genarray.t -> int -> int -> ('a, 'b, 'c) Array2.t
+(** Specialized version of {!Bigarray.reshape} for reshaping to
+ two-dimensional arrays. *)
+
+val reshape_3 :
+ ('a, 'b, 'c) Genarray.t -> int -> int -> int -> ('a, 'b, 'c) Array3.t
+(** Specialized version of {!Bigarray.reshape} for reshaping to
+ three-dimensional arrays. *)
diff --git a/otherlibs/bigarray/bigarray_stubs.c b/otherlibs/bigarray/bigarray_stubs.c
new file mode 100644
index 0000000000..c8416f9d6a
--- /dev/null
+++ b/otherlibs/bigarray/bigarray_stubs.c
@@ -0,0 +1,1300 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Manuel Serrano and Xavier Leroy, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stddef.h>
+#include <stdarg.h>
+#include <string.h>
+#include "caml/alloc.h"
+#include "bigarray.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/intext.h"
+#include "caml/hash.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+#include "caml/signals.h"
+
+#define int8 caml_ba_int8
+#define uint8 caml_ba_uint8
+#define int16 caml_ba_int16
+#define uint16 caml_ba_uint16
+
+extern void caml_ba_unmap_file(void * addr, uintnat len);
+ /* from mmap_xxx.c */
+
+/* Compute the number of elements of a big array */
+
+static uintnat caml_ba_num_elts(struct caml_ba_array * b)
+{
+ uintnat num_elts;
+ int i;
+ num_elts = 1;
+ for (i = 0; i < b->num_dims; i++) num_elts = num_elts * b->dim[i];
+ return num_elts;
+}
+
+/* Size in bytes of a bigarray element, indexed by bigarray kind */
+
+int caml_ba_element_size[] =
+{ 4 /*FLOAT32*/, 8 /*FLOAT64*/,
+ 1 /*SINT8*/, 1 /*UINT8*/,
+ 2 /*SINT16*/, 2 /*UINT16*/,
+ 4 /*INT32*/, 8 /*INT64*/,
+ sizeof(value) /*CAML_INT*/, sizeof(value) /*NATIVE_INT*/,
+ 8 /*COMPLEX32*/, 16 /*COMPLEX64*/,
+ 1 /*CHAR*/
+};
+
+/* Compute the number of bytes for the elements of a big array */
+
+CAMLexport uintnat caml_ba_byte_size(struct caml_ba_array * b)
+{
+ return caml_ba_num_elts(b)
+ * caml_ba_element_size[b->flags & CAML_BA_KIND_MASK];
+}
+
+/* Operation table for bigarrays */
+
+static void caml_ba_finalize(value v);
+static int caml_ba_compare(value v1, value v2);
+static intnat caml_ba_hash(value v);
+static void caml_ba_serialize(value, uintnat *, uintnat *);
+uintnat caml_ba_deserialize(void * dst);
+static struct custom_operations caml_ba_ops = {
+ "_bigarray",
+ caml_ba_finalize,
+ caml_ba_compare,
+ caml_ba_hash,
+ caml_ba_serialize,
+ caml_ba_deserialize,
+ custom_compare_ext_default
+};
+
+/* Multiplication of unsigned longs with overflow detection */
+
+static uintnat
+caml_ba_multov(uintnat a, uintnat b, int * overflow)
+{
+#define HALF_SIZE (sizeof(uintnat) * 4)
+#define HALF_MASK (((uintnat)1 << HALF_SIZE) - 1)
+#define LOW_HALF(x) ((x) & HALF_MASK)
+#define HIGH_HALF(x) ((x) >> HALF_SIZE)
+ /* Cut in half words */
+ uintnat al = LOW_HALF(a);
+ uintnat ah = HIGH_HALF(a);
+ uintnat bl = LOW_HALF(b);
+ uintnat bh = HIGH_HALF(b);
+ /* Exact product is:
+ al * bl
+ + ah * bl << HALF_SIZE
+ + al * bh << HALF_SIZE
+ + ah * bh << 2*HALF_SIZE
+ Overflow occurs if:
+ ah * bh is not 0, i.e. ah != 0 and bh != 0
+ OR ah * bl has high half != 0
+ OR ah * bl has high half != 0
+ OR the sum al * bl + LOW_HALF(ah * bl) << HALF_SIZE
+ + LOW_HALF(al * bh) << HALF_SIZE overflows.
+ This sum is equal to p = (a * b) modulo word size. */
+ uintnat p1 = al * bh;
+ uintnat p2 = ah * bl;
+ uintnat p = a * b;
+ if (ah != 0 && bh != 0) *overflow = 1;
+ if (HIGH_HALF(p1) != 0 || HIGH_HALF(p2) != 0) *overflow = 1;
+ p1 <<= HALF_SIZE;
+ p2 <<= HALF_SIZE;
+ p1 += p2;
+ if (p < p1 || p1 < p2) *overflow = 1; /* overflow in sums */
+ return p;
+#undef HALF_SIZE
+#undef LOW_HALF
+#undef HIGH_HALF
+}
+
+/* Allocation of a big array */
+
+#define CAML_BA_MAX_MEMORY 1024*1024*1024
+/* 1 Gb -- after allocating that much, it's probably worth speeding
+ up the major GC */
+
+/* [caml_ba_alloc] will allocate a new bigarray object in the heap.
+ If [data] is NULL, the memory for the contents is also allocated
+ (with [malloc]) by [caml_ba_alloc].
+ [data] cannot point into the OCaml heap.
+ [dim] may point into an object in the OCaml heap.
+*/
+CAMLexport value
+caml_ba_alloc(int flags, int num_dims, void * data, intnat * dim)
+{
+ uintnat num_elts, asize, size;
+ int overflow, i;
+ value res;
+ struct caml_ba_array * b;
+ intnat dimcopy[CAML_BA_MAX_NUM_DIMS];
+
+ Assert(num_dims >= 1 && num_dims <= CAML_BA_MAX_NUM_DIMS);
+ Assert((flags & CAML_BA_KIND_MASK) <= CAML_BA_CHAR);
+ for (i = 0; i < num_dims; i++) dimcopy[i] = dim[i];
+ size = 0;
+ if (data == NULL) {
+ overflow = 0;
+ num_elts = 1;
+ for (i = 0; i < num_dims; i++) {
+ num_elts = caml_ba_multov(num_elts, dimcopy[i], &overflow);
+ }
+ size = caml_ba_multov(num_elts,
+ caml_ba_element_size[flags & CAML_BA_KIND_MASK],
+ &overflow);
+ if (overflow) caml_raise_out_of_memory();
+ data = malloc(size);
+ if (data == NULL && size != 0) caml_raise_out_of_memory();
+ flags |= CAML_BA_MANAGED;
+ }
+ asize = SIZEOF_BA_ARRAY + num_dims * sizeof(intnat);
+ res = caml_alloc_custom(&caml_ba_ops, asize, size, CAML_BA_MAX_MEMORY);
+ b = Caml_ba_array_val(res);
+ b->data = data;
+ b->num_dims = num_dims;
+ b->flags = flags;
+ b->proxy = NULL;
+ for (i = 0; i < num_dims; i++) b->dim[i] = dimcopy[i];
+ return res;
+}
+
+/* Same as caml_ba_alloc, but dimensions are passed as a list of
+ arguments */
+
+CAMLexport value caml_ba_alloc_dims(int flags, int num_dims, void * data, ...)
+{
+ va_list ap;
+ intnat dim[CAML_BA_MAX_NUM_DIMS];
+ int i;
+ value res;
+
+ Assert(num_dims <= CAML_BA_MAX_NUM_DIMS);
+ va_start(ap, data);
+ for (i = 0; i < num_dims; i++) dim[i] = va_arg(ap, intnat);
+ va_end(ap);
+ res = caml_ba_alloc(flags, num_dims, data, dim);
+ return res;
+}
+
+/* Allocate a bigarray from OCaml */
+
+CAMLprim value caml_ba_create(value vkind, value vlayout, value vdim)
+{
+ intnat dim[CAML_BA_MAX_NUM_DIMS];
+ mlsize_t num_dims;
+ int i, flags;
+
+ num_dims = Wosize_val(vdim);
+ if (num_dims < 1 || num_dims > CAML_BA_MAX_NUM_DIMS)
+ caml_invalid_argument("Bigarray.create: bad number of dimensions");
+ for (i = 0; i < num_dims; i++) {
+ dim[i] = Long_val(Field(vdim, i));
+ if (dim[i] < 0)
+ caml_invalid_argument("Bigarray.create: negative dimension");
+ }
+ flags = Caml_ba_kind_val(vkind) | Caml_ba_layout_val(vlayout);
+ return caml_ba_alloc(flags, num_dims, NULL, dim);
+}
+
+/* Given a big array and a vector of indices, check that the indices
+ are within the bounds and return the offset of the corresponding
+ array element in the data part of the array. */
+
+static long caml_ba_offset(struct caml_ba_array * b, intnat * index)
+{
+ intnat offset;
+ int i;
+
+ offset = 0;
+ if ((b->flags & CAML_BA_LAYOUT_MASK) == CAML_BA_C_LAYOUT) {
+ /* C-style layout: row major, indices start at 0 */
+ for (i = 0; i < b->num_dims; i++) {
+ if ((uintnat) index[i] >= (uintnat) b->dim[i])
+ caml_array_bound_error();
+ offset = offset * b->dim[i] + index[i];
+ }
+ } else {
+ /* Fortran-style layout: column major, indices start at 1 */
+ for (i = b->num_dims - 1; i >= 0; i--) {
+ if ((uintnat) (index[i] - 1) >= (uintnat) b->dim[i])
+ caml_array_bound_error();
+ offset = offset * b->dim[i] + (index[i] - 1);
+ }
+ }
+ return offset;
+}
+
+/* Helper function to allocate a record of two double floats */
+
+static value copy_two_doubles(double d0, double d1)
+{
+ value res = caml_alloc_small(2 * Double_wosize, Double_array_tag);
+ Store_double_field(res, 0, d0);
+ Store_double_field(res, 1, d1);
+ return res;
+}
+
+/* Generic code to read from a big array */
+
+value caml_ba_get_N(value vb, value * vind, int nind)
+{
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ intnat index[CAML_BA_MAX_NUM_DIMS];
+ int i;
+ intnat offset;
+
+ /* Check number of indices = number of dimensions of array
+ (maybe not necessary if ML typing guarantees this) */
+ if (nind != b->num_dims)
+ caml_invalid_argument("Bigarray.get: wrong number of indices");
+ /* Compute offset and check bounds */
+ for (i = 0; i < b->num_dims; i++) index[i] = Long_val(vind[i]);
+ offset = caml_ba_offset(b, index);
+ /* Perform read */
+ switch ((b->flags) & CAML_BA_KIND_MASK) {
+ default:
+ Assert(0);
+ case CAML_BA_FLOAT32:
+ return caml_copy_double(((float *) b->data)[offset]);
+ case CAML_BA_FLOAT64:
+ return caml_copy_double(((double *) b->data)[offset]);
+ case CAML_BA_SINT8:
+ return Val_int(((int8 *) b->data)[offset]);
+ case CAML_BA_UINT8:
+ return Val_int(((uint8 *) b->data)[offset]);
+ case CAML_BA_SINT16:
+ return Val_int(((int16 *) b->data)[offset]);
+ case CAML_BA_UINT16:
+ return Val_int(((uint16 *) b->data)[offset]);
+ case CAML_BA_INT32:
+ return caml_copy_int32(((int32_t *) b->data)[offset]);
+ case CAML_BA_INT64:
+ return caml_copy_int64(((int64_t *) b->data)[offset]);
+ case CAML_BA_NATIVE_INT:
+ return caml_copy_nativeint(((intnat *) b->data)[offset]);
+ case CAML_BA_CAML_INT:
+ return Val_long(((intnat *) b->data)[offset]);
+ case CAML_BA_COMPLEX32:
+ { float * p = ((float *) b->data) + offset * 2;
+ return copy_two_doubles(p[0], p[1]); }
+ case CAML_BA_COMPLEX64:
+ { double * p = ((double *) b->data) + offset * 2;
+ return copy_two_doubles(p[0], p[1]); }
+ case CAML_BA_CHAR:
+ return Val_int(((unsigned char *) b->data)[offset]);
+ }
+}
+
+CAMLprim value caml_ba_get_1(value vb, value vind1)
+{
+ return caml_ba_get_N(vb, &vind1, 1);
+}
+
+CAMLprim value caml_ba_get_2(value vb, value vind1, value vind2)
+{
+ value vind[2];
+ vind[0] = vind1; vind[1] = vind2;
+ return caml_ba_get_N(vb, vind, 2);
+}
+
+CAMLprim value caml_ba_get_3(value vb, value vind1, value vind2, value vind3)
+{
+ value vind[3];
+ vind[0] = vind1; vind[1] = vind2; vind[2] = vind3;
+ return caml_ba_get_N(vb, vind, 3);
+}
+
+#if 0
+CAMLprim value caml_ba_get_4(value vb, value vind1, value vind2,
+ value vind3, value vind4)
+{
+ value vind[4];
+ vind[0] = vind1; vind[1] = vind2; vind[2] = vind3; vind[3] = vind4;
+ return caml_ba_get_N(vb, vind, 4);
+}
+
+CAMLprim value caml_ba_get_5(value vb, value vind1, value vind2,
+ value vind3, value vind4, value vind5)
+{
+ value vind[5];
+ vind[0] = vind1; vind[1] = vind2; vind[2] = vind3;
+ vind[3] = vind4; vind[4] = vind5;
+ return caml_ba_get_N(vb, vind, 5);
+}
+
+CAMLprim value caml_ba_get_6(value vb, value vind1, value vind2,
+ value vind3, value vind4, value vind5, value vind6)
+{
+ value vind[6];
+ vind[0] = vind1; vind[1] = vind2; vind[2] = vind3;
+ vind[3] = vind4; vind[4] = vind5; vind[5] = vind6;
+ return caml_ba_get_N(vb, vind, 6);
+}
+#endif
+
+CAMLprim value caml_ba_get_generic(value vb, value vind)
+{
+ return caml_ba_get_N(vb, &Field(vind, 0), Wosize_val(vind));
+}
+
+
+CAMLprim value caml_ba_uint8_get16(value vb, value vind)
+{
+ intnat res;
+ unsigned char b1, b2;
+ intnat idx = Long_val(vind);
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ if (idx < 0 || idx >= b->dim[0] - 1) caml_array_bound_error();
+ b1 = ((unsigned char*) b->data)[idx];
+ b2 = ((unsigned char*) b->data)[idx+1];
+#ifdef ARCH_BIG_ENDIAN
+ res = b1 << 8 | b2;
+#else
+ res = b2 << 8 | b1;
+#endif
+ return Val_int(res);
+}
+
+CAMLprim value caml_ba_uint8_get32(value vb, value vind)
+{
+ intnat res;
+ unsigned char b1, b2, b3, b4;
+ intnat idx = Long_val(vind);
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ if (idx < 0 || idx >= b->dim[0] - 3) caml_array_bound_error();
+ b1 = ((unsigned char*) b->data)[idx];
+ b2 = ((unsigned char*) b->data)[idx+1];
+ b3 = ((unsigned char*) b->data)[idx+2];
+ b4 = ((unsigned char*) b->data)[idx+3];
+#ifdef ARCH_BIG_ENDIAN
+ res = b1 << 24 | b2 << 16 | b3 << 8 | b4;
+#else
+ res = b4 << 24 | b3 << 16 | b2 << 8 | b1;
+#endif
+ return caml_copy_int32(res);
+}
+
+CAMLprim value caml_ba_uint8_get64(value vb, value vind)
+{
+ uint64_t res;
+ unsigned char b1, b2, b3, b4, b5, b6, b7, b8;
+ intnat idx = Long_val(vind);
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ if (idx < 0 || idx >= b->dim[0] - 7) caml_array_bound_error();
+ b1 = ((unsigned char*) b->data)[idx];
+ b2 = ((unsigned char*) b->data)[idx+1];
+ b3 = ((unsigned char*) b->data)[idx+2];
+ b4 = ((unsigned char*) b->data)[idx+3];
+ b5 = ((unsigned char*) b->data)[idx+4];
+ b6 = ((unsigned char*) b->data)[idx+5];
+ b7 = ((unsigned char*) b->data)[idx+6];
+ b8 = ((unsigned char*) b->data)[idx+7];
+#ifdef ARCH_BIG_ENDIAN
+ res = (uint64_t) b1 << 56 | (uint64_t) b2 << 48
+ | (uint64_t) b3 << 40 | (uint64_t) b4 << 32
+ | (uint64_t) b5 << 24 | (uint64_t) b6 << 16
+ | (uint64_t) b7 << 8 | (uint64_t) b8;
+#else
+ res = (uint64_t) b8 << 56 | (uint64_t) b7 << 48
+ | (uint64_t) b6 << 40 | (uint64_t) b5 << 32
+ | (uint64_t) b4 << 24 | (uint64_t) b3 << 16
+ | (uint64_t) b2 << 8 | (uint64_t) b1;
+#endif
+ return caml_copy_int64(res);
+}
+
+/* Generic write to a big array */
+
+static value caml_ba_set_aux(value vb, value * vind, intnat nind, value newval)
+{
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ intnat index[CAML_BA_MAX_NUM_DIMS];
+ int i;
+ intnat offset;
+
+ /* Check number of indices = number of dimensions of array
+ (maybe not necessary if ML typing guarantees this) */
+ if (nind != b->num_dims)
+ caml_invalid_argument("Bigarray.set: wrong number of indices");
+ /* Compute offset and check bounds */
+ for (i = 0; i < b->num_dims; i++) index[i] = Long_val(vind[i]);
+ offset = caml_ba_offset(b, index);
+ /* Perform write */
+ switch (b->flags & CAML_BA_KIND_MASK) {
+ default:
+ Assert(0);
+ case CAML_BA_FLOAT32:
+ ((float *) b->data)[offset] = Double_val(newval); break;
+ case CAML_BA_FLOAT64:
+ ((double *) b->data)[offset] = Double_val(newval); break;
+ case CAML_BA_CHAR:
+ case CAML_BA_SINT8:
+ case CAML_BA_UINT8:
+ ((int8 *) b->data)[offset] = Int_val(newval); break;
+ case CAML_BA_SINT16:
+ case CAML_BA_UINT16:
+ ((int16 *) b->data)[offset] = Int_val(newval); break;
+ case CAML_BA_INT32:
+ ((int32_t *) b->data)[offset] = Int32_val(newval); break;
+ case CAML_BA_INT64:
+ ((int64_t *) b->data)[offset] = Int64_val(newval); break;
+ case CAML_BA_NATIVE_INT:
+ ((intnat *) b->data)[offset] = Nativeint_val(newval); break;
+ case CAML_BA_CAML_INT:
+ ((intnat *) b->data)[offset] = Long_val(newval); break;
+ case CAML_BA_COMPLEX32:
+ { float * p = ((float *) b->data) + offset * 2;
+ p[0] = Double_field(newval, 0);
+ p[1] = Double_field(newval, 1);
+ break; }
+ case CAML_BA_COMPLEX64:
+ { double * p = ((double *) b->data) + offset * 2;
+ p[0] = Double_field(newval, 0);
+ p[1] = Double_field(newval, 1);
+ break; }
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_ba_set_1(value vb, value vind1, value newval)
+{
+ return caml_ba_set_aux(vb, &vind1, 1, newval);
+}
+
+CAMLprim value caml_ba_set_2(value vb, value vind1, value vind2, value newval)
+{
+ value vind[2];
+ vind[0] = vind1; vind[1] = vind2;
+ return caml_ba_set_aux(vb, vind, 2, newval);
+}
+
+CAMLprim value caml_ba_set_3(value vb, value vind1, value vind2, value vind3,
+ value newval)
+{
+ value vind[3];
+ vind[0] = vind1; vind[1] = vind2; vind[2] = vind3;
+ return caml_ba_set_aux(vb, vind, 3, newval);
+}
+
+#if 0
+CAMLprim value caml_ba_set_4(value vb, value vind1, value vind2,
+ value vind3, value vind4, value newval)
+{
+ value vind[4];
+ vind[0] = vind1; vind[1] = vind2; vind[2] = vind3; vind[3] = vind4;
+ return caml_ba_set_aux(vb, vind, 4, newval);
+}
+
+CAMLprim value caml_ba_set_5(value vb, value vind1, value vind2,
+ value vind3, value vind4, value vind5, value newval)
+{
+ value vind[5];
+ vind[0] = vind1; vind[1] = vind2; vind[2] = vind3;
+ vind[3] = vind4; vind[4] = vind5;
+ return caml_ba_set_aux(vb, vind, 5, newval);
+}
+
+CAMLprim value caml_ba_set_6(value vb, value vind1, value vind2,
+ value vind3, value vind4, value vind5,
+ value vind6, value newval)
+{
+ value vind[6];
+ vind[0] = vind1; vind[1] = vind2; vind[2] = vind3;
+ vind[3] = vind4; vind[4] = vind5; vind[5] = vind6;
+ return caml_ba_set_aux(vb, vind, 6, newval);
+}
+
+value caml_ba_set_N(value vb, value * vind, int nargs)
+{
+ return caml_ba_set_aux(vb, vind, nargs - 1, vind[nargs - 1]);
+}
+#endif
+
+CAMLprim value caml_ba_set_generic(value vb, value vind, value newval)
+{
+ return caml_ba_set_aux(vb, &Field(vind, 0), Wosize_val(vind), newval);
+}
+
+CAMLprim value caml_ba_uint8_set16(value vb, value vind, value newval)
+{
+ unsigned char b1, b2;
+ intnat val;
+ intnat idx = Long_val(vind);
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ if (idx < 0 || idx >= b->dim[0] - 1) caml_array_bound_error();
+ val = Long_val(newval);
+#ifdef ARCH_BIG_ENDIAN
+ b1 = 0xFF & val >> 8;
+ b2 = 0xFF & val;
+#else
+ b2 = 0xFF & val >> 8;
+ b1 = 0xFF & val;
+#endif
+ ((unsigned char*) b->data)[idx] = b1;
+ ((unsigned char*) b->data)[idx+1] = b2;
+ return Val_unit;
+}
+
+CAMLprim value caml_ba_uint8_set32(value vb, value vind, value newval)
+{
+ unsigned char b1, b2, b3, b4;
+ intnat idx = Long_val(vind);
+ intnat val;
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ if (idx < 0 || idx >= b->dim[0] - 3) caml_array_bound_error();
+ val = Int32_val(newval);
+#ifdef ARCH_BIG_ENDIAN
+ b1 = 0xFF & val >> 24;
+ b2 = 0xFF & val >> 16;
+ b3 = 0xFF & val >> 8;
+ b4 = 0xFF & val;
+#else
+ b4 = 0xFF & val >> 24;
+ b3 = 0xFF & val >> 16;
+ b2 = 0xFF & val >> 8;
+ b1 = 0xFF & val;
+#endif
+ ((unsigned char*) b->data)[idx] = b1;
+ ((unsigned char*) b->data)[idx+1] = b2;
+ ((unsigned char*) b->data)[idx+2] = b3;
+ ((unsigned char*) b->data)[idx+3] = b4;
+ return Val_unit;
+}
+
+CAMLprim value caml_ba_uint8_set64(value vb, value vind, value newval)
+{
+ unsigned char b1, b2, b3, b4, b5, b6, b7, b8;
+ intnat idx = Long_val(vind);
+ int64_t val;
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ if (idx < 0 || idx >= b->dim[0] - 7) caml_array_bound_error();
+ val = Int64_val(newval);
+#ifdef ARCH_BIG_ENDIAN
+ b1 = 0xFF & val >> 56;
+ b2 = 0xFF & val >> 48;
+ b3 = 0xFF & val >> 40;
+ b4 = 0xFF & val >> 32;
+ b5 = 0xFF & val >> 24;
+ b6 = 0xFF & val >> 16;
+ b7 = 0xFF & val >> 8;
+ b8 = 0xFF & val;
+#else
+ b8 = 0xFF & val >> 56;
+ b7 = 0xFF & val >> 48;
+ b6 = 0xFF & val >> 40;
+ b5 = 0xFF & val >> 32;
+ b4 = 0xFF & val >> 24;
+ b3 = 0xFF & val >> 16;
+ b2 = 0xFF & val >> 8;
+ b1 = 0xFF & val;
+#endif
+ ((unsigned char*) b->data)[idx] = b1;
+ ((unsigned char*) b->data)[idx+1] = b2;
+ ((unsigned char*) b->data)[idx+2] = b3;
+ ((unsigned char*) b->data)[idx+3] = b4;
+ ((unsigned char*) b->data)[idx+4] = b5;
+ ((unsigned char*) b->data)[idx+5] = b6;
+ ((unsigned char*) b->data)[idx+6] = b7;
+ ((unsigned char*) b->data)[idx+7] = b8;
+ return Val_unit;
+}
+
+/* Return the number of dimensions of a big array */
+
+CAMLprim value caml_ba_num_dims(value vb)
+{
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ return Val_long(b->num_dims);
+}
+
+/* Return the n-th dimension of a big array */
+
+CAMLprim value caml_ba_dim(value vb, value vn)
+{
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ intnat n = Long_val(vn);
+ if (n >= b->num_dims) caml_invalid_argument("Bigarray.dim");
+ return Val_long(b->dim[n]);
+}
+
+CAMLprim value caml_ba_dim_1(value vb)
+{
+ return caml_ba_dim(vb, Val_int(0));
+}
+
+CAMLprim value caml_ba_dim_2(value vb)
+{
+ return caml_ba_dim(vb, Val_int(1));
+}
+
+CAMLprim value caml_ba_dim_3(value vb)
+{
+ return caml_ba_dim(vb, Val_int(2));
+}
+
+/* Return the kind of a big array */
+
+CAMLprim value caml_ba_kind(value vb)
+{
+ return Val_caml_ba_kind(Caml_ba_array_val(vb)->flags & CAML_BA_KIND_MASK);
+}
+
+/* Return the layout of a big array */
+
+CAMLprim value caml_ba_layout(value vb)
+{
+ int layout = Caml_ba_array_val(vb)->flags & CAML_BA_LAYOUT_MASK;
+ return Val_caml_ba_layout(layout);
+}
+
+/* Finalization of a big array */
+
+static void caml_ba_finalize(value v)
+{
+ struct caml_ba_array * b = Caml_ba_array_val(v);
+
+ switch (b->flags & CAML_BA_MANAGED_MASK) {
+ case CAML_BA_EXTERNAL:
+ break;
+ case CAML_BA_MANAGED:
+ if (b->proxy == NULL) {
+ free(b->data);
+ } else {
+ if (-- b->proxy->refcount == 0) {
+ free(b->proxy->data);
+ caml_stat_free(b->proxy);
+ }
+ }
+ break;
+ case CAML_BA_MAPPED_FILE:
+ if (b->proxy == NULL) {
+ caml_ba_unmap_file(b->data, caml_ba_byte_size(b));
+ } else {
+ if (-- b->proxy->refcount == 0) {
+ caml_ba_unmap_file(b->proxy->data, b->proxy->size);
+ caml_stat_free(b->proxy);
+ }
+ }
+ break;
+ }
+}
+
+/* Comparison of two big arrays */
+
+static int caml_ba_compare(value v1, value v2)
+{
+ struct caml_ba_array * b1 = Caml_ba_array_val(v1);
+ struct caml_ba_array * b2 = Caml_ba_array_val(v2);
+ uintnat n, num_elts;
+ intnat flags1, flags2;
+ int i;
+
+ /* Compare kind & layout in case the arguments are of different types */
+ flags1 = b1->flags & (CAML_BA_KIND_MASK | CAML_BA_LAYOUT_MASK);
+ flags2 = b2->flags & (CAML_BA_KIND_MASK | CAML_BA_LAYOUT_MASK);
+ if (flags1 != flags2) return flags2 - flags1;
+ /* Compare number of dimensions */
+ if (b1->num_dims != b2->num_dims) return b2->num_dims - b1->num_dims;
+ /* Same number of dimensions: compare dimensions lexicographically */
+ for (i = 0; i < b1->num_dims; i++) {
+ intnat d1 = b1->dim[i];
+ intnat d2 = b2->dim[i];
+ if (d1 != d2) return d1 < d2 ? -1 : 1;
+ }
+ /* Same dimensions: compare contents lexicographically */
+ num_elts = caml_ba_num_elts(b1);
+
+#define DO_INTEGER_COMPARISON(type) \
+ { type * p1 = b1->data; type * p2 = b2->data; \
+ for (n = 0; n < num_elts; n++) { \
+ type e1 = *p1++; type e2 = *p2++; \
+ if (e1 < e2) return -1; \
+ if (e1 > e2) return 1; \
+ } \
+ return 0; \
+ }
+#define DO_FLOAT_COMPARISON(type) \
+ { type * p1 = b1->data; type * p2 = b2->data; \
+ for (n = 0; n < num_elts; n++) { \
+ type e1 = *p1++; type e2 = *p2++; \
+ if (e1 < e2) return -1; \
+ if (e1 > e2) return 1; \
+ if (e1 != e2) { \
+ caml_compare_unordered = 1; \
+ if (e1 == e1) return 1; \
+ if (e2 == e2) return -1; \
+ } \
+ } \
+ return 0; \
+ }
+
+ switch (b1->flags & CAML_BA_KIND_MASK) {
+ case CAML_BA_COMPLEX32:
+ num_elts *= 2; /*fallthrough*/
+ case CAML_BA_FLOAT32:
+ DO_FLOAT_COMPARISON(float);
+ case CAML_BA_COMPLEX64:
+ num_elts *= 2; /*fallthrough*/
+ case CAML_BA_FLOAT64:
+ DO_FLOAT_COMPARISON(double);
+ case CAML_BA_CHAR:
+ DO_INTEGER_COMPARISON(uint8);
+ case CAML_BA_SINT8:
+ DO_INTEGER_COMPARISON(int8);
+ case CAML_BA_UINT8:
+ DO_INTEGER_COMPARISON(uint8);
+ case CAML_BA_SINT16:
+ DO_INTEGER_COMPARISON(int16);
+ case CAML_BA_UINT16:
+ DO_INTEGER_COMPARISON(uint16);
+ case CAML_BA_INT32:
+ DO_INTEGER_COMPARISON(int32_t);
+ case CAML_BA_INT64:
+ DO_INTEGER_COMPARISON(int64_t);
+ case CAML_BA_CAML_INT:
+ case CAML_BA_NATIVE_INT:
+ DO_INTEGER_COMPARISON(intnat);
+ default:
+ Assert(0);
+ return 0; /* should not happen */
+ }
+#undef DO_INTEGER_COMPARISON
+#undef DO_FLOAT_COMPARISON
+}
+
+/* Hashing of a bigarray */
+
+static intnat caml_ba_hash(value v)
+{
+ struct caml_ba_array * b = Caml_ba_array_val(v);
+ intnat num_elts, n;
+ uint32_t h, w;
+ int i;
+
+ num_elts = 1;
+ for (i = 0; i < b->num_dims; i++) num_elts = num_elts * b->dim[i];
+ h = 0;
+
+ switch (b->flags & CAML_BA_KIND_MASK) {
+ case CAML_BA_CHAR:
+ case CAML_BA_SINT8:
+ case CAML_BA_UINT8: {
+ uint8 * p = b->data;
+ if (num_elts > 256) num_elts = 256;
+ for (n = 0; n + 4 <= num_elts; n += 4, p += 4) {
+ w = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
+ h = caml_hash_mix_uint32(h, w);
+ }
+ w = 0;
+ switch (num_elts & 3) {
+ case 3: w = p[2] << 16; /* fallthrough */
+ case 2: w |= p[1] << 8; /* fallthrough */
+ case 1: w |= p[0];
+ h = caml_hash_mix_uint32(h, w);
+ }
+ break;
+ }
+ case CAML_BA_SINT16:
+ case CAML_BA_UINT16: {
+ uint16 * p = b->data;
+ if (num_elts > 128) num_elts = 128;
+ for (n = 0; n + 2 <= num_elts; n += 2, p += 2) {
+ w = p[0] | (p[1] << 16);
+ h = caml_hash_mix_uint32(h, w);
+ }
+ if ((num_elts & 1) != 0)
+ h = caml_hash_mix_uint32(h, p[0]);
+ break;
+ }
+ case CAML_BA_INT32:
+ {
+ uint32_t * p = b->data;
+ if (num_elts > 64) num_elts = 64;
+ for (n = 0; n < num_elts; n++, p++) h = caml_hash_mix_uint32(h, *p);
+ break;
+ }
+ case CAML_BA_CAML_INT:
+ case CAML_BA_NATIVE_INT:
+ {
+ intnat * p = b->data;
+ if (num_elts > 64) num_elts = 64;
+ for (n = 0; n < num_elts; n++, p++) h = caml_hash_mix_intnat(h, *p);
+ break;
+ }
+ case CAML_BA_INT64:
+ {
+ int64_t * p = b->data;
+ if (num_elts > 32) num_elts = 32;
+ for (n = 0; n < num_elts; n++, p++) h = caml_hash_mix_int64(h, *p);
+ break;
+ }
+ case CAML_BA_COMPLEX32:
+ num_elts *= 2; /* fallthrough */
+ case CAML_BA_FLOAT32:
+ {
+ float * p = b->data;
+ if (num_elts > 64) num_elts = 64;
+ for (n = 0; n < num_elts; n++, p++) h = caml_hash_mix_float(h, *p);
+ break;
+ }
+ case CAML_BA_COMPLEX64:
+ num_elts *= 2; /* fallthrough */
+ case CAML_BA_FLOAT64:
+ {
+ double * p = b->data;
+ if (num_elts > 32) num_elts = 32;
+ for (n = 0; n < num_elts; n++, p++) h = caml_hash_mix_double(h, *p);
+ break;
+ }
+ }
+ return h;
+}
+
+static void caml_ba_serialize_longarray(void * data,
+ intnat num_elts,
+ intnat min_val, intnat max_val)
+{
+#ifdef ARCH_SIXTYFOUR
+ int overflow_32 = 0;
+ intnat * p, n;
+ for (n = 0, p = data; n < num_elts; n++, p++) {
+ if (*p < min_val || *p > max_val) { overflow_32 = 1; break; }
+ }
+ if (overflow_32) {
+ caml_serialize_int_1(1);
+ caml_serialize_block_8(data, num_elts);
+ } else {
+ caml_serialize_int_1(0);
+ for (n = 0, p = data; n < num_elts; n++, p++)
+ caml_serialize_int_4((int32_t) *p);
+ }
+#else
+ caml_serialize_int_1(0);
+ caml_serialize_block_4(data, num_elts);
+#endif
+}
+
+static void caml_ba_serialize(value v,
+ uintnat * wsize_32,
+ uintnat * wsize_64)
+{
+ struct caml_ba_array * b = Caml_ba_array_val(v);
+ intnat num_elts;
+ int i;
+
+ /* Serialize header information */
+ caml_serialize_int_4(b->num_dims);
+ caml_serialize_int_4(b->flags & (CAML_BA_KIND_MASK | CAML_BA_LAYOUT_MASK));
+ /* On a 64-bit machine, if any of the dimensions is >= 2^32,
+ the size of the marshaled data will be >= 2^32 and
+ extern_value() will fail. So, it is safe to write the dimensions
+ as 32-bit unsigned integers. */
+ for (i = 0; i < b->num_dims; i++) caml_serialize_int_4(b->dim[i]);
+ /* Compute total number of elements */
+ num_elts = 1;
+ for (i = 0; i < b->num_dims; i++) num_elts = num_elts * b->dim[i];
+ /* Serialize elements */
+ switch (b->flags & CAML_BA_KIND_MASK) {
+ case CAML_BA_CHAR:
+ case CAML_BA_SINT8:
+ case CAML_BA_UINT8:
+ caml_serialize_block_1(b->data, num_elts); break;
+ case CAML_BA_SINT16:
+ case CAML_BA_UINT16:
+ caml_serialize_block_2(b->data, num_elts); break;
+ case CAML_BA_FLOAT32:
+ case CAML_BA_INT32:
+ caml_serialize_block_4(b->data, num_elts); break;
+ case CAML_BA_COMPLEX32:
+ caml_serialize_block_4(b->data, num_elts * 2); break;
+ case CAML_BA_FLOAT64:
+ case CAML_BA_INT64:
+ caml_serialize_block_8(b->data, num_elts); break;
+ case CAML_BA_COMPLEX64:
+ caml_serialize_block_8(b->data, num_elts * 2); break;
+ case CAML_BA_CAML_INT:
+ caml_ba_serialize_longarray(b->data, num_elts, -0x40000000, 0x3FFFFFFF);
+ break;
+ case CAML_BA_NATIVE_INT:
+ caml_ba_serialize_longarray(b->data, num_elts, -0x80000000, 0x7FFFFFFF);
+ break;
+ }
+ /* Compute required size in OCaml heap. Assumes struct caml_ba_array
+ is exactly 4 + num_dims words */
+ Assert(SIZEOF_BA_ARRAY == 4 * sizeof(value));
+ *wsize_32 = (4 + b->num_dims) * 4;
+ *wsize_64 = (4 + b->num_dims) * 8;
+}
+
+static void caml_ba_deserialize_longarray(void * dest, intnat num_elts)
+{
+ int sixty = caml_deserialize_uint_1();
+#ifdef ARCH_SIXTYFOUR
+ if (sixty) {
+ caml_deserialize_block_8(dest, num_elts);
+ } else {
+ intnat * p, n;
+ for (n = 0, p = dest; n < num_elts; n++, p++)
+ *p = caml_deserialize_sint_4();
+ }
+#else
+ if (sixty)
+ caml_deserialize_error("input_value: cannot read bigarray "
+ "with 64-bit OCaml ints");
+ caml_deserialize_block_4(dest, num_elts);
+#endif
+}
+
+uintnat caml_ba_deserialize(void * dst)
+{
+ struct caml_ba_array * b = dst;
+ int i, elt_size;
+ uintnat num_elts;
+
+ /* Read back header information */
+ b->num_dims = caml_deserialize_uint_4();
+ b->flags = caml_deserialize_uint_4() | CAML_BA_MANAGED;
+ b->proxy = NULL;
+ for (i = 0; i < b->num_dims; i++) b->dim[i] = caml_deserialize_uint_4();
+ /* Compute total number of elements */
+ num_elts = caml_ba_num_elts(b);
+ /* Determine element size in bytes */
+ if ((b->flags & CAML_BA_KIND_MASK) > CAML_BA_CHAR)
+ caml_deserialize_error("input_value: bad bigarray kind");
+ elt_size = caml_ba_element_size[b->flags & CAML_BA_KIND_MASK];
+ /* Allocate room for data */
+ b->data = malloc(elt_size * num_elts);
+ if (b->data == NULL)
+ caml_deserialize_error("input_value: out of memory for bigarray");
+ /* Read data */
+ switch (b->flags & CAML_BA_KIND_MASK) {
+ case CAML_BA_CHAR:
+ case CAML_BA_SINT8:
+ case CAML_BA_UINT8:
+ caml_deserialize_block_1(b->data, num_elts); break;
+ case CAML_BA_SINT16:
+ case CAML_BA_UINT16:
+ caml_deserialize_block_2(b->data, num_elts); break;
+ case CAML_BA_FLOAT32:
+ case CAML_BA_INT32:
+ caml_deserialize_block_4(b->data, num_elts); break;
+ case CAML_BA_COMPLEX32:
+ caml_deserialize_block_4(b->data, num_elts * 2); break;
+ case CAML_BA_FLOAT64:
+ case CAML_BA_INT64:
+ caml_deserialize_block_8(b->data, num_elts); break;
+ case CAML_BA_COMPLEX64:
+ caml_deserialize_block_8(b->data, num_elts * 2); break;
+ case CAML_BA_CAML_INT:
+ case CAML_BA_NATIVE_INT:
+ caml_ba_deserialize_longarray(b->data, num_elts); break;
+ }
+ /* PR#5516: use C99's flexible array types if possible */
+ return SIZEOF_BA_ARRAY + b->num_dims * sizeof(intnat);
+}
+
+/* Create / update proxy to indicate that b2 is a sub-array of b1 */
+
+static void caml_ba_update_proxy(struct caml_ba_array * b1,
+ struct caml_ba_array * b2)
+{
+ struct caml_ba_proxy * proxy;
+ /* Nothing to do for un-managed arrays */
+ if ((b1->flags & CAML_BA_MANAGED_MASK) == CAML_BA_EXTERNAL) return;
+ if (b1->proxy != NULL) {
+ /* If b1 is already a proxy for a larger array, increment refcount of
+ proxy */
+ b2->proxy = b1->proxy;
+ ++ b1->proxy->refcount;
+ } else {
+ /* Otherwise, create proxy and attach it to both b1 and b2 */
+ proxy = caml_stat_alloc(sizeof(struct caml_ba_proxy));
+ proxy->refcount = 2; /* original array + sub array */
+ proxy->data = b1->data;
+ proxy->size =
+ b1->flags & CAML_BA_MAPPED_FILE ? caml_ba_byte_size(b1) : 0;
+ b1->proxy = proxy;
+ b2->proxy = proxy;
+ }
+}
+
+/* Slicing */
+
+CAMLprim value caml_ba_slice(value vb, value vind)
+{
+ CAMLparam2 (vb, vind);
+ #define b ((struct caml_ba_array *) Caml_ba_array_val(vb))
+ CAMLlocal1 (res);
+ intnat index[CAML_BA_MAX_NUM_DIMS];
+ int num_inds, i;
+ intnat offset;
+ intnat * sub_dims;
+ char * sub_data;
+
+ /* Check number of indices < number of dimensions of array */
+ num_inds = Wosize_val(vind);
+ if (num_inds >= b->num_dims)
+ caml_invalid_argument("Bigarray.slice: too many indices");
+ /* Compute offset and check bounds */
+ if ((b->flags & CAML_BA_LAYOUT_MASK) == CAML_BA_C_LAYOUT) {
+ /* We slice from the left */
+ for (i = 0; i < num_inds; i++) index[i] = Long_val(Field(vind, i));
+ for (/*nothing*/; i < b->num_dims; i++) index[i] = 0;
+ offset = caml_ba_offset(b, index);
+ sub_dims = b->dim + num_inds;
+ } else {
+ /* We slice from the right */
+ for (i = 0; i < num_inds; i++)
+ index[b->num_dims - num_inds + i] = Long_val(Field(vind, i));
+ for (i = 0; i < b->num_dims - num_inds; i++) index[i] = 1;
+ offset = caml_ba_offset(b, index);
+ sub_dims = b->dim;
+ }
+ sub_data =
+ (char *) b->data +
+ offset * caml_ba_element_size[b->flags & CAML_BA_KIND_MASK];
+ /* Allocate an OCaml bigarray to hold the result */
+ res = caml_ba_alloc(b->flags, b->num_dims - num_inds, sub_data, sub_dims);
+ /* Create or update proxy in case of managed bigarray */
+ caml_ba_update_proxy(b, Caml_ba_array_val(res));
+ /* Return result */
+ CAMLreturn (res);
+
+ #undef b
+}
+
+/* Extracting a sub-array of same number of dimensions */
+
+CAMLprim value caml_ba_sub(value vb, value vofs, value vlen)
+{
+ CAMLparam3 (vb, vofs, vlen);
+ CAMLlocal1 (res);
+ #define b ((struct caml_ba_array *) Caml_ba_array_val(vb))
+ intnat ofs = Long_val(vofs);
+ intnat len = Long_val(vlen);
+ int i, changed_dim;
+ intnat mul;
+ char * sub_data;
+
+ /* Compute offset and check bounds */
+ if ((b->flags & CAML_BA_LAYOUT_MASK) == CAML_BA_C_LAYOUT) {
+ /* We reduce the first dimension */
+ mul = 1;
+ for (i = 1; i < b->num_dims; i++) mul *= b->dim[i];
+ changed_dim = 0;
+ } else {
+ /* We reduce the last dimension */
+ mul = 1;
+ for (i = 0; i < b->num_dims - 1; i++) mul *= b->dim[i];
+ changed_dim = b->num_dims - 1;
+ ofs--; /* Fortran arrays start at 1 */
+ }
+ if (ofs < 0 || len < 0 || ofs + len > b->dim[changed_dim])
+ caml_invalid_argument("Bigarray.sub: bad sub-array");
+ sub_data =
+ (char *) b->data +
+ ofs * mul * caml_ba_element_size[b->flags & CAML_BA_KIND_MASK];
+ /* Allocate an OCaml bigarray to hold the result */
+ res = caml_ba_alloc(b->flags, b->num_dims, sub_data, b->dim);
+ /* Doctor the changed dimension */
+ Caml_ba_array_val(res)->dim[changed_dim] = len;
+ /* Create or update proxy in case of managed bigarray */
+ caml_ba_update_proxy(b, Caml_ba_array_val(res));
+ /* Return result */
+ CAMLreturn (res);
+
+ #undef b
+}
+
+/* Copying a big array into another one */
+
+#define LEAVE_RUNTIME_OP_CUTOFF 4096
+#define is_mmapped(ba) ((ba)->flags & CAML_BA_MAPPED_FILE)
+
+CAMLprim value caml_ba_blit(value vsrc, value vdst)
+{
+ CAMLparam2(vsrc, vdst);
+ struct caml_ba_array * src = Caml_ba_array_val(vsrc);
+ struct caml_ba_array * dst = Caml_ba_array_val(vdst);
+ void *src_data = src->data;
+ void *dst_data = dst->data;
+ int i;
+ intnat num_bytes;
+ int leave_runtime;
+
+ /* Check same numbers of dimensions and same dimensions */
+ if (src->num_dims != dst->num_dims) goto blit_error;
+ for (i = 0; i < src->num_dims; i++)
+ if (src->dim[i] != dst->dim[i]) goto blit_error;
+ /* Compute number of bytes in array data */
+ num_bytes =
+ caml_ba_num_elts(src)
+ * caml_ba_element_size[src->flags & CAML_BA_KIND_MASK];
+ leave_runtime =
+ (
+ (num_bytes >= LEAVE_RUNTIME_OP_CUTOFF*sizeof(long))
+ || is_mmapped(src)
+ || is_mmapped(dst)
+ );
+ /* Do the copying */
+ if (leave_runtime) caml_enter_blocking_section();
+ memmove (dst_data, src_data, num_bytes);
+ if (leave_runtime) caml_leave_blocking_section();
+ CAMLreturn (Val_unit);
+ blit_error:
+ caml_invalid_argument("Bigarray.blit: dimension mismatch");
+ CAMLreturn (Val_unit); /* not reached */
+}
+
+/* Filling a big array with a given value */
+
+#define FILL_GEN_LOOP(n_ops, loop) do{ \
+ int leave_runtime = ((n_ops >= LEAVE_RUNTIME_OP_CUTOFF) || is_mmapped(b)); \
+ if (leave_runtime) caml_enter_blocking_section(); \
+ loop; \
+ if (leave_runtime) caml_leave_blocking_section(); \
+}while(0)
+
+#define FILL_SCALAR_LOOP \
+ FILL_GEN_LOOP(num_elts, \
+ for (p = data; num_elts > 0; p++, num_elts--) *p = init)
+
+#define FILL_COMPLEX_LOOP \
+ FILL_GEN_LOOP(num_elts + num_elts, \
+ for (p = data; num_elts > 0; num_elts--) { *p++ = init0; *p++ = init1; })
+
+CAMLprim value caml_ba_fill(value vb, value vinit)
+{
+ CAMLparam1(vb);
+ struct caml_ba_array * b = Caml_ba_array_val(vb);
+ void *data = b->data;
+ intnat num_elts = caml_ba_num_elts(b);
+
+ switch (b->flags & CAML_BA_KIND_MASK) {
+ default:
+ Assert(0);
+ case CAML_BA_FLOAT32: {
+ float init = Double_val(vinit);
+ float * p;
+ FILL_SCALAR_LOOP;
+ break;
+ }
+ case CAML_BA_FLOAT64: {
+ double init = Double_val(vinit);
+ double * p;
+ FILL_SCALAR_LOOP;
+ break;
+ }
+ case CAML_BA_CHAR:
+ case CAML_BA_SINT8:
+ case CAML_BA_UINT8: {
+ int init = Int_val(vinit);
+ unsigned char * p;
+ FILL_SCALAR_LOOP;
+ break;
+ }
+ case CAML_BA_SINT16:
+ case CAML_BA_UINT16: {
+ int init = Int_val(vinit);
+ int16 * p;
+ FILL_SCALAR_LOOP;
+ break;
+ }
+ case CAML_BA_INT32: {
+ int32_t init = Int32_val(vinit);
+ int32_t * p;
+ FILL_SCALAR_LOOP;
+ break;
+ }
+ case CAML_BA_INT64: {
+ int64_t init = Int64_val(vinit);
+ int64_t * p;
+ FILL_SCALAR_LOOP;
+ break;
+ }
+ case CAML_BA_NATIVE_INT: {
+ intnat init = Nativeint_val(vinit);
+ intnat * p;
+ FILL_SCALAR_LOOP;
+ break;
+ }
+ case CAML_BA_CAML_INT: {
+ intnat init = Long_val(vinit);
+ intnat * p;
+ FILL_SCALAR_LOOP;
+ break;
+ }
+ case CAML_BA_COMPLEX32: {
+ float init0 = Double_field(vinit, 0);
+ float init1 = Double_field(vinit, 1);
+ float * p;
+ FILL_COMPLEX_LOOP;
+ break;
+ }
+ case CAML_BA_COMPLEX64: {
+ double init0 = Double_field(vinit, 0);
+ double init1 = Double_field(vinit, 1);
+ double * p;
+ FILL_COMPLEX_LOOP;
+ break;
+ }
+ }
+ CAMLreturn (Val_unit);
+}
+
+/* Reshape an array: change dimensions and number of dimensions, preserving
+ array contents */
+
+CAMLprim value caml_ba_reshape(value vb, value vdim)
+{
+ CAMLparam2 (vb, vdim);
+ CAMLlocal1 (res);
+#define b ((struct caml_ba_array *) Caml_ba_array_val(vb))
+ intnat dim[CAML_BA_MAX_NUM_DIMS];
+ mlsize_t num_dims;
+ uintnat num_elts;
+ int i;
+
+ num_dims = Wosize_val(vdim);
+ if (num_dims < 1 || num_dims > CAML_BA_MAX_NUM_DIMS)
+ caml_invalid_argument("Bigarray.reshape: bad number of dimensions");
+ num_elts = 1;
+ for (i = 0; i < num_dims; i++) {
+ dim[i] = Long_val(Field(vdim, i));
+ if (dim[i] < 0)
+ caml_invalid_argument("Bigarray.reshape: negative dimension");
+ num_elts *= dim[i];
+ }
+ /* Check that sizes agree */
+ if (num_elts != caml_ba_num_elts(b))
+ caml_invalid_argument("Bigarray.reshape: size mismatch");
+ /* Create bigarray with same data and new dimensions */
+ res = caml_ba_alloc(b->flags, num_dims, b->data, dim);
+ /* Create or update proxy in case of managed bigarray */
+ caml_ba_update_proxy(b, Caml_ba_array_val(res));
+ /* Return result */
+ CAMLreturn (res);
+
+#undef b
+}
+
+/* Initialization */
+
+CAMLprim value caml_ba_init(value unit)
+{
+ caml_register_custom_operations(&caml_ba_ops);
+ return Val_unit;
+}
diff --git a/otherlibs/bigarray/libbigarray.clib b/otherlibs/bigarray/libbigarray.clib
new file mode 100644
index 0000000000..4dc96a4f6a
--- /dev/null
+++ b/otherlibs/bigarray/libbigarray.clib
@@ -0,0 +1 @@
+bigarray_stubs.o mmap_unix.o
diff --git a/otherlibs/bigarray/libbigarraywin32.clib b/otherlibs/bigarray/libbigarraywin32.clib
new file mode 100644
index 0000000000..16661bb80d
--- /dev/null
+++ b/otherlibs/bigarray/libbigarraywin32.clib
@@ -0,0 +1 @@
+bigarray_stubs.o mmap_win32.o
diff --git a/otherlibs/bigarray/mmap_unix.c b/otherlibs/bigarray/mmap_unix.c
new file mode 100644
index 0000000000..027b1e5cf5
--- /dev/null
+++ b/otherlibs/bigarray/mmap_unix.c
@@ -0,0 +1,202 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Manuel Serrano and Xavier Leroy, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Needed (under Linux at least) to get pwrite's prototype in unistd.h.
+ Must be defined before the first system .h is included. */
+#define _XOPEN_SOURCE 500
+
+#include <stddef.h>
+#include <string.h>
+#include "bigarray.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/io.h"
+#include "caml/mlvalues.h"
+#include "caml/sys.h"
+#include "caml/signals.h"
+
+extern int caml_ba_element_size[]; /* from bigarray_stubs.c */
+
+#include <errno.h>
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#ifdef HAS_MMAP
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#endif
+
+#if defined(HAS_MMAP)
+
+#ifndef MAP_FAILED
+#define MAP_FAILED ((void *) -1)
+#endif
+
+/* [caml_grow_file] function contributed by Gerd Stolpmann (PR#5543). */
+
+static int caml_grow_file(int fd, file_offset size)
+{
+ char c;
+ int p;
+
+ /* First use pwrite for growing - it is a conservative method, as it
+ can never happen that we shrink by accident
+ */
+#ifdef HAS_PWRITE
+ c = 0;
+ p = pwrite(fd, &c, 1, size - 1);
+#else
+
+ /* Emulate pwrite with lseek. This should only be necessary on ancient
+ systems nowadays
+ */
+ file_offset currpos;
+ currpos = lseek(fd, 0, SEEK_CUR);
+ if (currpos != -1) {
+ p = lseek(fd, size - 1, SEEK_SET);
+ if (p != -1) {
+ c = 0;
+ p = write(fd, &c, 1);
+ if (p != -1)
+ p = lseek(fd, currpos, SEEK_SET);
+ }
+ }
+ else p=-1;
+#endif
+#ifdef HAS_TRUNCATE
+ if (p == -1 && errno == ESPIPE) {
+ /* Plan B. Check if at least ftruncate is possible. There are
+ some non-seekable descriptor types that do not support pwrite
+ but ftruncate, like shared memory. We never get into this case
+ for real files, so there is no danger of truncating persistent
+ data by accident
+ */
+ p = ftruncate(fd, size);
+ }
+#endif
+ return p;
+}
+
+
+CAMLprim value caml_ba_map_file(value vfd, value vkind, value vlayout,
+ value vshared, value vdim, value vstart)
+{
+ int fd, flags, major_dim, shared;
+ intnat num_dims, i;
+ intnat dim[CAML_BA_MAX_NUM_DIMS];
+ file_offset startpos, file_size, data_size;
+ struct stat st;
+ uintnat array_size, page, delta;
+ void * addr;
+
+ fd = Int_val(vfd);
+ flags = Caml_ba_kind_val(vkind) | Caml_ba_layout_val(vlayout);
+ startpos = File_offset_val(vstart);
+ num_dims = Wosize_val(vdim);
+ major_dim = flags & CAML_BA_FORTRAN_LAYOUT ? num_dims - 1 : 0;
+ /* Extract dimensions from OCaml array */
+ num_dims = Wosize_val(vdim);
+ if (num_dims < 1 || num_dims > CAML_BA_MAX_NUM_DIMS)
+ caml_invalid_argument("Bigarray.mmap: bad number of dimensions");
+ for (i = 0; i < num_dims; i++) {
+ dim[i] = Long_val(Field(vdim, i));
+ if (dim[i] == -1 && i == major_dim) continue;
+ if (dim[i] < 0)
+ caml_invalid_argument("Bigarray.create: negative dimension");
+ }
+ /* Determine file size. We avoid lseek here because it is fragile,
+ and because some mappable file types do not support it
+ */
+ caml_enter_blocking_section();
+ if (fstat(fd, &st) == -1) {
+ caml_leave_blocking_section();
+ caml_sys_error(NO_ARG);
+ }
+ file_size = st.st_size;
+ /* Determine array size in bytes (or size of array without the major
+ dimension if that dimension wasn't specified) */
+ array_size = caml_ba_element_size[flags & CAML_BA_KIND_MASK];
+ for (i = 0; i < num_dims; i++)
+ if (dim[i] != -1) array_size *= dim[i];
+ /* Check if the major dimension is unknown */
+ if (dim[major_dim] == -1) {
+ /* Determine major dimension from file size */
+ if (file_size < startpos) {
+ caml_leave_blocking_section();
+ caml_failwith("Bigarray.mmap: file position exceeds file size");
+ }
+ data_size = file_size - startpos;
+ dim[major_dim] = (uintnat) (data_size / array_size);
+ array_size = dim[major_dim] * array_size;
+ if (array_size != data_size) {
+ caml_leave_blocking_section();
+ caml_failwith("Bigarray.mmap: file size doesn't match array dimensions");
+ }
+ } else {
+ /* Check that file is large enough, and grow it otherwise */
+ if (file_size < startpos + array_size) {
+ if (caml_grow_file(fd, startpos + array_size) == -1) { /* PR#5543 */
+ caml_leave_blocking_section();
+ caml_sys_error(NO_ARG);
+ }
+ }
+ }
+ /* Determine offset so that the mapping starts at the given file pos */
+ page = sysconf(_SC_PAGESIZE);
+ delta = (uintnat) startpos % page;
+ /* Do the mmap */
+ shared = Bool_val(vshared) ? MAP_SHARED : MAP_PRIVATE;
+ if (array_size > 0)
+ addr = mmap(NULL, array_size + delta, PROT_READ | PROT_WRITE,
+ shared, fd, startpos - delta);
+ else
+ addr = NULL; /* PR#5463 - mmap fails on empty region */
+ caml_leave_blocking_section();
+ if (addr == (void *) MAP_FAILED) caml_sys_error(NO_ARG);
+ addr = (void *) ((uintnat) addr + delta);
+ /* Build and return the OCaml bigarray */
+ return caml_ba_alloc(flags | CAML_BA_MAPPED_FILE, num_dims, addr, dim);
+}
+
+#else
+
+CAMLprim value caml_ba_map_file(value vfd, value vkind, value vlayout,
+ value vshared, value vdim, value vpos)
+{
+ caml_invalid_argument("Bigarray.map_file: not supported");
+ return Val_unit;
+}
+
+#endif
+
+CAMLprim value caml_ba_map_file_bytecode(value * argv, int argn)
+{
+ return caml_ba_map_file(argv[0], argv[1], argv[2],
+ argv[3], argv[4], argv[5]);
+}
+
+void caml_ba_unmap_file(void * addr, uintnat len)
+{
+#if defined(HAS_MMAP)
+ uintnat page = sysconf(_SC_PAGESIZE);
+ uintnat delta = (uintnat) addr % page;
+ if (len == 0) return; /* PR#5463 */
+ addr = (void *)((uintnat)addr - delta);
+ len = len + delta;
+#if defined(_POSIX_SYNCHRONIZED_IO)
+ msync(addr, len, MS_ASYNC); /* PR#3571 */
+#endif
+ munmap(addr, len);
+#endif
+}
diff --git a/otherlibs/bigarray/mmap_win32.c b/otherlibs/bigarray/mmap_win32.c
new file mode 100644
index 0000000000..5d7ec6bb88
--- /dev/null
+++ b/otherlibs/bigarray/mmap_win32.c
@@ -0,0 +1,153 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Manuel Serrano and Xavier Leroy, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stddef.h>
+#include <stdio.h>
+#include <string.h>
+#include "bigarray.h"
+#include "caml/alloc.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/mlvalues.h"
+#include "caml/sys.h"
+#include "unixsupport.h"
+
+extern int caml_ba_element_size[]; /* from bigarray_stubs.c */
+
+static void caml_ba_sys_error(void);
+
+#ifndef INVALID_SET_FILE_POINTER
+#define INVALID_SET_FILE_POINTER (-1)
+#endif
+
+static __int64 caml_ba_set_file_pointer(HANDLE h, __int64 dist, DWORD mode)
+{
+ LARGE_INTEGER i;
+ DWORD err;
+
+ i.QuadPart = dist;
+ i.LowPart = SetFilePointer(h, i.LowPart, &i.HighPart, mode);
+ if (i.LowPart == INVALID_SET_FILE_POINTER) return -1;
+ return i.QuadPart;
+}
+
+CAMLprim value caml_ba_map_file(value vfd, value vkind, value vlayout,
+ value vshared, value vdim, value vstart)
+{
+ HANDLE fd, fmap;
+ int flags, major_dim, mode, perm;
+ intnat num_dims, i;
+ intnat dim[CAML_BA_MAX_NUM_DIMS];
+ __int64 currpos, startpos, file_size, data_size;
+ uintnat array_size, page, delta;
+ char c;
+ void * addr;
+ LARGE_INTEGER li;
+ SYSTEM_INFO sysinfo;
+
+ fd = Handle_val(vfd);
+ flags = Caml_ba_kind_val(vkind) | Caml_ba_layout_val(vlayout);
+ startpos = Int64_val(vstart);
+ num_dims = Wosize_val(vdim);
+ major_dim = flags & CAML_BA_FORTRAN_LAYOUT ? num_dims - 1 : 0;
+ /* Extract dimensions from OCaml array */
+ num_dims = Wosize_val(vdim);
+ if (num_dims < 1 || num_dims > CAML_BA_MAX_NUM_DIMS)
+ caml_invalid_argument("Bigarray.mmap: bad number of dimensions");
+ for (i = 0; i < num_dims; i++) {
+ dim[i] = Long_val(Field(vdim, i));
+ if (dim[i] == -1 && i == major_dim) continue;
+ if (dim[i] < 0)
+ caml_invalid_argument("Bigarray.create: negative dimension");
+ }
+ /* Determine file size */
+ currpos = caml_ba_set_file_pointer(fd, 0, FILE_CURRENT);
+ if (currpos == -1) caml_ba_sys_error();
+ file_size = caml_ba_set_file_pointer(fd, 0, FILE_END);
+ if (file_size == -1) caml_ba_sys_error();
+ /* Determine array size in bytes (or size of array without the major
+ dimension if that dimension wasn't specified) */
+ array_size = caml_ba_element_size[flags & CAML_BA_KIND_MASK];
+ for (i = 0; i < num_dims; i++)
+ if (dim[i] != -1) array_size *= dim[i];
+ /* Check if the first/last dimension is unknown */
+ if (dim[major_dim] == -1) {
+ /* Determine first/last dimension from file size */
+ if (file_size < startpos)
+ caml_failwith("Bigarray.mmap: file position exceeds file size");
+ data_size = file_size - startpos;
+ dim[major_dim] = (uintnat) (data_size / array_size);
+ array_size = dim[major_dim] * array_size;
+ if (array_size != data_size)
+ caml_failwith("Bigarray.mmap: file size doesn't match array dimensions");
+ }
+ /* Restore original file position */
+ caml_ba_set_file_pointer(fd, currpos, FILE_BEGIN);
+ /* Create the file mapping */
+ if (Bool_val(vshared)) {
+ perm = PAGE_READWRITE;
+ mode = FILE_MAP_WRITE;
+ } else {
+ perm = PAGE_READONLY; /* doesn't work under Win98 */
+ mode = FILE_MAP_COPY;
+ }
+ li.QuadPart = startpos + array_size;
+ fmap = CreateFileMapping(fd, NULL, perm, li.HighPart, li.LowPart, NULL);
+ if (fmap == NULL) caml_ba_sys_error();
+ /* Determine offset so that the mapping starts at the given file pos */
+ GetSystemInfo(&sysinfo);
+ delta = (uintnat) (startpos % sysinfo.dwAllocationGranularity);
+ /* Map the mapping in memory */
+ li.QuadPart = startpos - delta;
+ addr =
+ MapViewOfFile(fmap, mode, li.HighPart, li.LowPart, array_size + delta);
+ if (addr == NULL) caml_ba_sys_error();
+ addr = (void *) ((uintnat) addr + delta);
+ /* Close the file mapping */
+ CloseHandle(fmap);
+ /* Build and return the OCaml bigarray */
+ return caml_ba_alloc(flags | CAML_BA_MAPPED_FILE, num_dims, addr, dim);
+}
+
+CAMLprim value caml_ba_map_file_bytecode(value * argv, int argn)
+{
+ return caml_ba_map_file(argv[0], argv[1], argv[2],
+ argv[3], argv[4], argv[5]);
+}
+
+void caml_ba_unmap_file(void * addr, uintnat len)
+{
+ SYSTEM_INFO sysinfo;
+ uintnat delta;
+
+ GetSystemInfo(&sysinfo);
+ delta = (uintnat) addr % sysinfo.dwAllocationGranularity;
+ UnmapViewOfFile((void *)((uintnat)addr - delta));
+}
+
+static void caml_ba_sys_error(void)
+{
+ char buffer[512];
+ DWORD errnum;
+
+ errnum = GetLastError();
+ if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ errnum,
+ 0,
+ buffer,
+ sizeof(buffer),
+ NULL))
+ sprintf(buffer, "Unknown error %ld\n", errnum);
+ caml_raise_sys_error(caml_copy_string(buffer));
+}
diff --git a/otherlibs/dynlink/.ignore b/otherlibs/dynlink/.ignore
new file mode 100644
index 0000000000..5ea9775e1d
--- /dev/null
+++ b/otherlibs/dynlink/.ignore
@@ -0,0 +1 @@
+extract_crc
diff --git a/otherlibs/dynlink/Makefile b/otherlibs/dynlink/Makefile
new file mode 100644
index 0000000000..1c422983b2
--- /dev/null
+++ b/otherlibs/dynlink/Makefile
@@ -0,0 +1,110 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Makefile for the dynamic link library
+
+# FIXME reduce redundancy by including ../Makefile
+
+include ../../config/Makefile
+CAMLRUN ?= ../../boot/ocamlrun
+CAMLYACC ?= ../../boot/ocamlyacc
+
+ROOTDIR = ../..
+OCAMLC = $(CAMLRUN) $(ROOTDIR)/ocamlc -nostdlib -I $(ROOTDIR)/stdlib
+OCAMLOPT = $(CAMLRUN) $(ROOTDIR)/ocamlopt -nostdlib -I $(ROOTDIR)/stdlib
+
+INCLUDES=-I ../../utils -I ../../typing -I ../../bytecomp -I ../../asmcomp
+COMPFLAGS=-w +33..39 -warn-error A -bin-annot -g -safe-string \
+ -I ../../stdlib $(INCLUDES)
+
+OBJS=dynlinkaux.cmo dynlink.cmo
+
+COMPILEROBJS=\
+ ../../utils/misc.cmo ../../utils/config.cmo ../../utils/clflags.cmo \
+ ../../utils/tbl.cmo ../../utils/consistbl.cmo \
+ ../../utils/terminfo.cmo ../../utils/warnings.cmo \
+ ../../parsing/asttypes.cmi \
+ ../../parsing/location.cmo ../../parsing/longident.cmo \
+ ../../parsing/docstrings.cmo ../../parsing/ast_helper.cmo \
+ ../../parsing/ast_mapper.cmo \
+ ../../typing/ident.cmo ../../typing/path.cmo \
+ ../../typing/primitive.cmo ../../typing/types.cmo \
+ ../../typing/btype.cmo ../../typing/subst.cmo ../../typing/predef.cmo \
+ ../../typing/datarepr.cmo ../../typing/cmi_format.cmo ../../typing/env.cmo \
+ ../../bytecomp/lambda.cmo ../../bytecomp/instruct.cmo \
+ ../../bytecomp/cmo_format.cmi ../../bytecomp/opcodes.cmo \
+ ../../bytecomp/runtimedef.cmo ../../bytecomp/bytesections.cmo \
+ ../../bytecomp/dll.cmo ../../bytecomp/meta.cmo \
+ ../../bytecomp/symtable.cmo
+
+NATOBJS=dynlink.cmx
+
+all: dynlink.cma extract_crc
+
+allopt: dynlink.cmxa
+
+dynlink.cma: $(OBJS)
+ $(OCAMLC) $(COMPFLAGS) -ccopt "$(NATDYNLINKOPTS)" -a -o dynlink.cma \
+ $(OBJS)
+
+dynlink.cmxa: $(NATOBJS)
+ $(OCAMLOPT) $(COMPFLAGS) -ccopt "$(NATDYNLINKOPTS)" -a -o dynlink.cmxa \
+ $(NATOBJS)
+
+dynlinkaux.cmo: $(COMPILEROBJS)
+ $(OCAMLC) $(COMPFLAGS) -pack -o dynlinkaux.cmo $(COMPILEROBJS)
+
+dynlinkaux.cmi: dynlinkaux.cmo
+
+dynlink.cmx: dynlink.cmi natdynlink.ml
+ cp natdynlink.ml dynlink.mlopt
+ $(OCAMLOPT) -c $(COMPFLAGS) -impl dynlink.mlopt
+ rm -f dynlink.mlopt
+
+extract_crc: dynlink.cma extract_crc.cmo
+ $(OCAMLC) -o extract_crc dynlink.cma extract_crc.cmo
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+
+install:
+ cp dynlink.cmi dynlink.cma dynlink.mli $(INSTALL_LIBDIR)
+ cp extract_crc $(INSTALL_LIBDIR)/extract_crc$(EXE)
+
+installopt:
+ if $(NATDYNLINK); then \
+ cp $(NATOBJS) dynlink.cmxa dynlink.$(A) $(INSTALL_LIBDIR) && \
+ cd $(INSTALL_LIBDIR) && $(RANLIB) dynlink.$(A); \
+ fi
+
+partialclean:
+ rm -f extract_crc *.cm[ioaxt] *.cmti *.cmxa
+
+clean: partialclean
+ rm -f *.$(A) *.$(O) *.so *.dll dynlink.mlopt
+
+.SUFFIXES: .ml .mli .cmo .cmi .cmx
+
+.mli.cmi:
+ $(OCAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmo:
+ $(OCAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmx:
+ $(OCAMLOPT) -c $(COMPFLAGS) $<
+
+depend:
+
+dynlink.cmi: dynlinkaux.cmi
+dynlink.cmo: dynlink.cmi dynlinkaux.cmo
+extract_crc.cmo: dynlink.cmi
diff --git a/otherlibs/dynlink/Makefile.nt b/otherlibs/dynlink/Makefile.nt
new file mode 100644
index 0000000000..c041c2f7fb
--- /dev/null
+++ b/otherlibs/dynlink/Makefile.nt
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Makefile for the dynamic link library
+
+include Makefile
diff --git a/otherlibs/dynlink/dynlink.ml b/otherlibs/dynlink/dynlink.ml
new file mode 100644
index 0000000000..a9ae6e74d1
--- /dev/null
+++ b/otherlibs/dynlink/dynlink.ml
@@ -0,0 +1,332 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Dynamic loading of .cmo files *)
+
+open Dynlinkaux (* REMOVE_ME for ../../debugger/dynlink.ml *)
+open Cmo_format
+
+type linking_error =
+ Undefined_global of string
+ | Unavailable_primitive of string
+ | Uninitialized_global of string
+
+type error =
+ Not_a_bytecode_file of string
+ | Inconsistent_import of string
+ | Unavailable_unit of string
+ | Unsafe_file
+ | Linking_error of string * linking_error
+ | Corrupted_interface of string
+ | File_not_found of string
+ | Cannot_open_dll of string
+ | Inconsistent_implementation of string
+
+exception Error of error
+
+let () =
+ Printexc.register_printer
+ (function
+ | Error err ->
+ let msg = match err with
+ | Not_a_bytecode_file s ->
+ Printf.sprintf "Not_a_bytecode_file %S" s
+ | Inconsistent_import s ->
+ Printf.sprintf "Inconsistent_import %S" s
+ | Unavailable_unit s ->
+ Printf.sprintf "Unavailable_unit %S" s
+ | Unsafe_file ->
+ "Unsafe_file"
+ | Linking_error (s, Undefined_global s') ->
+ Printf.sprintf "Linking_error (%S, Dynlink.Undefined_global %S)"
+ s s'
+ | Linking_error (s, Unavailable_primitive s') ->
+ Printf.sprintf "Linking_error (%S, Dynlink.Unavailable_primitive \
+ %S)" s s'
+ | Linking_error (s, Uninitialized_global s') ->
+ Printf.sprintf "Linking_error (%S, Dynlink.Uninitialized_global \
+ %S)" s s'
+ | Corrupted_interface s ->
+ Printf.sprintf "Corrupted_interface %S" s
+ | File_not_found s ->
+ Printf.sprintf "File_not_found %S" s
+ | Cannot_open_dll s ->
+ Printf.sprintf "Cannot_open_dll %S" s
+ | Inconsistent_implementation s ->
+ Printf.sprintf "Inconsistent_implementation %S" s in
+ Some (Printf.sprintf "Dynlink.Error(Dynlink.%s)" msg)
+ | _ -> None)
+
+(* Management of interface CRCs *)
+
+let crc_interfaces = ref (Consistbl.create ())
+let allow_extension = ref true
+
+(* Check that the object file being loaded has been compiled against
+ the same interfaces as the program itself. In addition, check that
+ only authorized compilation units are referenced. *)
+
+let check_consistency file_name cu =
+ try
+ List.iter
+ (fun (name, crco) ->
+ match crco with
+ None -> ()
+ | Some crc ->
+ if name = cu.cu_name then
+ Consistbl.set !crc_interfaces name crc file_name
+ else if !allow_extension then
+ Consistbl.check !crc_interfaces name crc file_name
+ else
+ Consistbl.check_noadd !crc_interfaces name crc file_name)
+ cu.cu_imports
+ with Consistbl.Inconsistency(name, user, auth) ->
+ raise(Error(Inconsistent_import name))
+ | Consistbl.Not_available(name) ->
+ raise(Error(Unavailable_unit name))
+
+(* Empty the crc_interfaces table *)
+
+let clear_available_units () =
+ Consistbl.clear !crc_interfaces;
+ allow_extension := false
+
+(* Allow only access to the units with the given names *)
+
+let allow_only names =
+ Consistbl.filter (fun name -> List.mem name names) !crc_interfaces;
+ allow_extension := false
+
+(* Prohibit access to the units with the given names *)
+
+let prohibit names =
+ Consistbl.filter (fun name -> not (List.mem name names)) !crc_interfaces;
+ allow_extension := false
+
+(* Initialize the crc_interfaces table with a list of units with fixed CRCs *)
+
+let add_available_units units =
+ List.iter
+ (fun (unit, crc) -> Consistbl.set !crc_interfaces unit crc "")
+ units
+
+(* Default interface CRCs: those found in the current executable *)
+let default_crcs = ref []
+
+let default_available_units () =
+ clear_available_units();
+ List.iter
+ (fun (unit, crco) ->
+ match crco with
+ None -> ()
+ | Some crc -> Consistbl.set !crc_interfaces unit crc "")
+ !default_crcs;
+ allow_extension := true
+
+(* Initialize the linker tables and everything *)
+
+let inited = ref false
+
+let init () =
+ if not !inited then begin
+ default_crcs := Symtable.init_toplevel();
+ default_available_units ();
+ inited := true;
+ end
+
+let clear_available_units () = init(); clear_available_units ()
+let allow_only l = init(); allow_only l
+let prohibit l = init(); prohibit l
+let add_available_units l = init(); add_available_units l
+let default_available_units () = init(); default_available_units ()
+
+(* Read the CRC of an interface from its .cmi file *)
+
+let digest_interface unit loadpath =
+ let filename =
+ let shortname = unit ^ ".cmi" in
+ try
+ Misc.find_in_path_uncap loadpath shortname
+ with Not_found ->
+ raise (Error(File_not_found shortname)) in
+ let ic = open_in_bin filename in
+ try
+ let buffer =
+ really_input_string ic (String.length Config.cmi_magic_number)
+ in
+ if buffer <> Config.cmi_magic_number then begin
+ close_in ic;
+ raise(Error(Corrupted_interface filename))
+ end;
+ let cmi = Cmi_format.input_cmi ic in
+ close_in ic;
+ let crc =
+ match cmi.Cmi_format.cmi_crcs with
+ (_, Some crc) :: _ -> crc
+ | _ -> raise(Error(Corrupted_interface filename))
+ in
+ crc
+ with End_of_file | Failure _ ->
+ close_in ic;
+ raise(Error(Corrupted_interface filename))
+
+(* Initialize the crc_interfaces table with a list of units.
+ Their CRCs are read from their interfaces. *)
+
+let add_interfaces units loadpath =
+ add_available_units
+ (List.map (fun unit -> (unit, digest_interface unit loadpath)) units)
+
+(* Check whether the object file being loaded was compiled in unsafe mode *)
+
+let unsafe_allowed = ref false
+
+let allow_unsafe_modules b =
+ unsafe_allowed := b
+
+let check_unsafe_module cu =
+ if (not !unsafe_allowed) && cu.cu_primitives <> []
+ then raise(Error(Unsafe_file))
+
+(* Load in-core and execute a bytecode object file *)
+
+external register_code_fragment: bytes -> int -> string -> unit
+ = "caml_register_code_fragment"
+
+let load_compunit ic file_name file_digest compunit =
+ check_consistency file_name compunit;
+ check_unsafe_module compunit;
+ seek_in ic compunit.cu_pos;
+ let code_size = compunit.cu_codesize + 8 in
+ let code = Meta.static_alloc code_size in
+ unsafe_really_input ic code 0 compunit.cu_codesize;
+ Bytes.unsafe_set code compunit.cu_codesize (Char.chr Opcodes.opRETURN);
+ Bytes.unsafe_set code (compunit.cu_codesize + 1) '\000';
+ Bytes.unsafe_set code (compunit.cu_codesize + 2) '\000';
+ Bytes.unsafe_set code (compunit.cu_codesize + 3) '\000';
+ Bytes.unsafe_set code (compunit.cu_codesize + 4) '\001';
+ Bytes.unsafe_set code (compunit.cu_codesize + 5) '\000';
+ Bytes.unsafe_set code (compunit.cu_codesize + 6) '\000';
+ Bytes.unsafe_set code (compunit.cu_codesize + 7) '\000';
+ let initial_symtable = Symtable.current_state() in
+ begin try
+ Symtable.patch_object code compunit.cu_reloc;
+ Symtable.check_global_initialized compunit.cu_reloc;
+ Symtable.update_global_table()
+ with Symtable.Error error ->
+ let new_error =
+ match error with
+ Symtable.Undefined_global s -> Undefined_global s
+ | Symtable.Unavailable_primitive s -> Unavailable_primitive s
+ | Symtable.Uninitialized_global s -> Uninitialized_global s
+ | _ -> assert false in
+ raise(Error(Linking_error (file_name, new_error)))
+ end;
+ (* PR#5215: identify this code fragment by
+ digest of file contents + unit name.
+ Unit name is needed for .cma files, which produce several code fragments.*)
+ let digest = Digest.string (file_digest ^ compunit.cu_name) in
+ register_code_fragment code code_size digest;
+ let events =
+ if compunit.cu_debug = 0 then [| |]
+ else begin
+ seek_in ic compunit.cu_debug;
+ [| input_value ic |]
+ end in
+ Meta.add_debug_info code code_size events;
+ begin try
+ ignore((Meta.reify_bytecode code code_size) ())
+ with exn ->
+ Symtable.restore_state initial_symtable;
+ raise exn
+ end
+
+let loadfile file_name =
+ init();
+ if not (Sys.file_exists file_name)
+ then raise (Error (File_not_found file_name));
+ let ic = open_in_bin file_name in
+ let file_digest = Digest.channel ic (-1) in
+ seek_in ic 0;
+ try
+ let buffer =
+ try really_input_string ic (String.length Config.cmo_magic_number)
+ with End_of_file -> raise (Error (Not_a_bytecode_file file_name))
+ in
+ if buffer = Config.cmo_magic_number then begin
+ let compunit_pos = input_binary_int ic in (* Go to descriptor *)
+ seek_in ic compunit_pos;
+ let cu = (input_value ic : compilation_unit) in
+ load_compunit ic file_name file_digest cu
+ end else
+ if buffer = Config.cma_magic_number then begin
+ let toc_pos = input_binary_int ic in (* Go to table of contents *)
+ seek_in ic toc_pos;
+ let lib = (input_value ic : library) in
+ begin try
+ Dll.open_dlls Dll.For_execution
+ (List.map Dll.extract_dll_name lib.lib_dllibs)
+ with Failure reason ->
+ raise(Error(Cannot_open_dll reason))
+ end;
+ List.iter (load_compunit ic file_name file_digest) lib.lib_units
+ end else
+ raise(Error(Not_a_bytecode_file file_name));
+ close_in ic
+ with exc ->
+ close_in ic; raise exc
+
+let loadfile_private file_name =
+ init();
+ let initial_symtable = Symtable.current_state()
+ and initial_crc = !crc_interfaces in
+ try
+ loadfile file_name;
+ Symtable.hide_additions initial_symtable;
+ crc_interfaces := initial_crc
+ with exn ->
+ Symtable.hide_additions initial_symtable;
+ crc_interfaces := initial_crc;
+ raise exn
+
+(* Error report *)
+
+let error_message = function
+ Not_a_bytecode_file name ->
+ name ^ " is not a bytecode object file"
+ | Inconsistent_import name ->
+ "interface mismatch on " ^ name
+ | Unavailable_unit name ->
+ "no implementation available for " ^ name
+ | Unsafe_file ->
+ "this object file uses unsafe features"
+ | Linking_error (name, Undefined_global s) ->
+ "error while linking " ^ name ^ ".\n" ^
+ "Reference to undefined global `" ^ s ^ "'"
+ | Linking_error (name, Unavailable_primitive s) ->
+ "error while linking " ^ name ^ ".\n" ^
+ "The external function `" ^ s ^ "' is not available"
+ | Linking_error (name, Uninitialized_global s) ->
+ "error while linking " ^ name ^ ".\n" ^
+ "The module `" ^ s ^ "' is not yet initialized"
+ | Corrupted_interface name ->
+ "corrupted interface file " ^ name
+ | File_not_found name ->
+ "cannot find file " ^ name ^ " in search path"
+ | Cannot_open_dll reason ->
+ "error loading shared library: " ^ reason
+ | Inconsistent_implementation name ->
+ "implementation mismatch on " ^ name
+
+let is_native = false
+let adapt_filename f = f
diff --git a/otherlibs/dynlink/dynlink.mli b/otherlibs/dynlink/dynlink.mli
new file mode 100644
index 0000000000..98ded877cb
--- /dev/null
+++ b/otherlibs/dynlink/dynlink.mli
@@ -0,0 +1,146 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Dynamic loading of object files. *)
+
+val is_native: bool
+(** [true] if the program is native,
+ [false] if the program is bytecode. *)
+
+(** {6 Dynamic loading of compiled files} *)
+
+val loadfile : string -> unit
+(** In bytecode: load the given bytecode object file ([.cmo] file) or
+ bytecode library file ([.cma] file), and link it with the running
+ program. In native code: load the given OCaml plugin file (usually
+ [.cmxs]), and link it with the running
+ program.
+ All toplevel expressions in the loaded compilation units
+ are evaluated. No facilities are provided to
+ access value names defined by the unit. Therefore, the unit
+ must register itself its entry points with the main program,
+ e.g. by modifying tables of functions. *)
+
+val loadfile_private : string -> unit
+(** Same as [loadfile], except that the compilation units just loaded
+ are hidden (cannot be referenced) from other modules dynamically
+ loaded afterwards. *)
+
+val adapt_filename : string -> string
+(** In bytecode, the identity function. In native code, replace the last
+ extension with [.cmxs]. *)
+
+(** {6 Access control} *)
+
+val allow_only: string list -> unit
+(** [allow_only units] restricts the compilation units that
+ dynamically-linked units can reference: it forbids all references
+ to units other than those named in the list [units]. References
+ to any other compilation unit will cause a [Unavailable_unit]
+ error during [loadfile] or [loadfile_private].
+
+ Initially (or after calling [default_available_units]) all
+ compilation units composing the program currently running are
+ available for reference from dynamically-linked units.
+ [allow_only] can be used to restrict access to a subset of these
+ units, e.g. to the units that compose the API for
+ dynamically-linked code, and prevent access to all other units,
+ e.g. private, internal modules of the running program. If
+ [allow_only] is called several times, access will be restricted to
+ the intersection of the given lists (i.e. a call to [allow_only]
+ can never increase the set of available units). *)
+
+val prohibit: string list -> unit
+(** [prohibit units] prohibits dynamically-linked units from referencing
+ the units named in list [units]. This can be used to prevent
+ access to selected units, e.g. private, internal modules of
+ the running program. *)
+
+val default_available_units: unit -> unit
+(** Reset the set of units that can be referenced from dynamically-linked
+ code to its default value, that is, all units composing the currently
+ running program. *)
+
+val allow_unsafe_modules : bool -> unit
+(** Govern whether unsafe object files are allowed to be
+ dynamically linked. A compilation unit is 'unsafe' if it contains
+ declarations of external functions, which can break type safety.
+ By default, dynamic linking of unsafe object files is
+ not allowed. In native code, this function does nothing; object files
+ with external functions are always allowed to be dynamically linked. *)
+
+(** {6 Deprecated, low-level API for access control} *)
+
+(** @deprecated The functions [add_interfaces], [add_available_units]
+ and [clear_available_units] should not be used in new programs,
+ since the default initialization of allowed units, along with the
+ [allow_only] and [prohibit] function, provides a better, safer
+ mechanism to control access to program units. The three functions
+ below are provided for backward compatibility only and are not
+ available in native code. *)
+
+val add_interfaces : string list -> string list -> unit
+(** [add_interfaces units path] grants dynamically-linked object
+ files access to the compilation units named in list [units].
+ The interfaces ([.cmi] files) for these units are searched in
+ [path] (a list of directory names). *)
+
+val add_available_units : (string * Digest.t) list -> unit
+(** Same as {!Dynlink.add_interfaces}, but instead of searching [.cmi] files
+ to find the unit interfaces, uses the interface digests given
+ for each unit. This way, the [.cmi] interface files need not be
+ available at run-time. The digests can be extracted from [.cmi]
+ files using the [extract_crc] program installed in the
+ OCaml standard library directory. *)
+
+val clear_available_units : unit -> unit
+(** Empty the list of compilation units accessible to dynamically-linked
+ programs. *)
+
+(** {6 Deprecated, initialization} *)
+
+val init : unit -> unit
+(** @deprecated Initialize the [Dynlink] library. This function is called
+ automatically when needed. *)
+
+(** {6 Error reporting} *)
+
+type linking_error =
+ Undefined_global of string
+ | Unavailable_primitive of string
+ | Uninitialized_global of string
+
+type error =
+ Not_a_bytecode_file of string
+ | Inconsistent_import of string
+ | Unavailable_unit of string
+ | Unsafe_file
+ | Linking_error of string * linking_error
+ | Corrupted_interface of string
+ | File_not_found of string
+ | Cannot_open_dll of string
+ | Inconsistent_implementation of string
+
+exception Error of error
+(** Errors in dynamic linking are reported by raising the [Error]
+ exception with a description of the error. *)
+
+val error_message : error -> string
+(** Convert an error description to a printable message. *)
+
+
+(**/**)
+
+(** {6 Internal functions} *)
+
+val digest_interface : string -> string list -> Digest.t
diff --git a/otherlibs/dynlink/dynlinkaux.mlpack b/otherlibs/dynlink/dynlinkaux.mlpack
new file mode 100644
index 0000000000..67b9538e83
--- /dev/null
+++ b/otherlibs/dynlink/dynlinkaux.mlpack
@@ -0,0 +1,5 @@
+Misc Config Clflags Tbl Consistbl
+Terminfo Warnings Asttypes Location Longident
+Ident Path Primitive Types Btype Subst Predef
+Datarepr Cmi_format Env Lambda Instruct Cmo_format Opcodes
+Runtimedef Bytesections Dll Meta Symtable
diff --git a/otherlibs/dynlink/extract_crc.ml b/otherlibs/dynlink/extract_crc.ml
new file mode 100644
index 0000000000..d312aea711
--- /dev/null
+++ b/otherlibs/dynlink/extract_crc.ml
@@ -0,0 +1,51 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Print the digests of unit interfaces *)
+
+let load_path = ref []
+let first = ref true
+
+let print_crc unit =
+ try
+ let crc = Dynlink.digest_interface unit (!load_path @ ["."]) in
+ if !first then first := false else print_string ";\n";
+ print_string " \""; print_string (String.capitalize_ascii unit);
+ print_string "\",\n \"";
+ for i = 0 to String.length crc - 1 do
+ Printf.printf "\\%03d" (Char.code crc.[i])
+ done;
+ print_string "\""
+ with exn ->
+ prerr_string "Error while reading the interface for ";
+ prerr_endline unit;
+ begin match exn with
+ Sys_error msg -> prerr_endline msg
+ | Dynlink.Error(Dynlink.File_not_found name) ->
+ prerr_string "Cannot find file "; prerr_endline name
+ | Dynlink.Error _ -> prerr_endline "Ill-formed .cmi file"
+ | _ -> raise exn
+ end;
+ exit 2
+
+let usage = "Usage: extract_crc [-I <dir>] <files>"
+
+let main () =
+ print_string "let crc_unit_list = [\n";
+ Arg.parse
+ ["-I", Arg.String(fun dir -> load_path := !load_path @ [dir]),
+ "<dir> Add <dir> to the list of include directories"]
+ print_crc usage;
+ print_string "\n]\n"
+
+let _ = main(); exit 0
diff --git a/otherlibs/dynlink/natdynlink.ml b/otherlibs/dynlink/natdynlink.ml
new file mode 100644
index 0000000000..597d60fb5f
--- /dev/null
+++ b/otherlibs/dynlink/natdynlink.ml
@@ -0,0 +1,248 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Dynamic loading of .cmx files *)
+
+type handle
+
+external ndl_open: string -> bool -> handle * bytes = "caml_natdynlink_open"
+external ndl_run: handle -> string -> unit = "caml_natdynlink_run"
+external ndl_getmap: unit -> bytes = "caml_natdynlink_getmap"
+external ndl_globals_inited: unit -> int = "caml_natdynlink_globals_inited"
+
+type linking_error =
+ Undefined_global of string
+ | Unavailable_primitive of string
+ | Uninitialized_global of string
+
+type error =
+ Not_a_bytecode_file of string
+ | Inconsistent_import of string
+ | Unavailable_unit of string
+ | Unsafe_file
+ | Linking_error of string * linking_error
+ | Corrupted_interface of string
+ | File_not_found of string
+ | Cannot_open_dll of string
+ | Inconsistent_implementation of string
+
+exception Error of error
+
+open Cmx_format
+
+(* Copied from config.ml to avoid dependencies *)
+let cmxs_magic_number = "Caml2007D002"
+
+let dll_filename fname =
+ if Filename.is_implicit fname then Filename.concat (Sys.getcwd ()) fname
+ else fname
+
+let read_file filename priv =
+ let dll = dll_filename filename in
+ if not (Sys.file_exists dll) then raise (Error (File_not_found dll));
+
+ let (handle,data) as res = ndl_open dll (not priv) in
+ if Obj.tag (Obj.repr res) = Obj.string_tag
+ then raise (Error (Cannot_open_dll (Obj.magic res)));
+
+ let header : dynheader = Marshal.from_bytes data 0 in
+ if header.dynu_magic <> cmxs_magic_number
+ then raise(Error(Not_a_bytecode_file dll));
+ (dll, handle, header.dynu_units)
+
+
+
+(* Management of interface and implementation CRCs *)
+
+module StrMap = Map.Make(String)
+
+type implem_state =
+ | Loaded
+ | Check_inited of int
+
+type state = {
+ ifaces: (string*string) StrMap.t;
+ implems: (string*string*implem_state) StrMap.t;
+}
+
+let empty_state = {
+ ifaces = StrMap.empty;
+ implems = StrMap.empty;
+}
+
+let global_state = ref empty_state
+
+let allow_extension = ref true
+
+let inited = ref false
+
+let default_available_units () =
+ let map : (string*Digest.t*Digest.t*string list) list =
+ Marshal.from_bytes (ndl_getmap ()) 0 in
+ let exe = Sys.executable_name in
+ let rank = ref 0 in
+ global_state :=
+ List.fold_left
+ (fun st (name,crc_intf,crc_impl,syms) ->
+ rank := !rank + List.length syms;
+ {
+ ifaces = StrMap.add name (crc_intf,exe) st.ifaces;
+ implems = StrMap.add name (crc_impl,exe,Check_inited !rank) st.implems;
+ }
+ )
+ empty_state
+ map;
+ allow_extension := true;
+ inited := true
+
+let init () =
+ if not !inited then default_available_units ()
+
+let add_check_ifaces allow_ext filename ui ifaces =
+ List.fold_left
+ (fun ifaces (name, crco) ->
+ match crco with
+ None -> ifaces
+ | Some crc ->
+ if name = ui.dynu_name
+ then StrMap.add name (crc,filename) ifaces
+ else
+ try
+ let (old_crc,old_src) = StrMap.find name ifaces in
+ if old_crc <> crc
+ then raise(Error(Inconsistent_import(name)))
+ else ifaces
+ with Not_found ->
+ if allow_ext then StrMap.add name (crc,filename) ifaces
+ else raise (Error(Unavailable_unit name))
+ ) ifaces ui.dynu_imports_cmi
+
+let check_implems filename ui implems =
+ List.iter
+ (fun (name, crco) ->
+ match name with
+ |"Out_of_memory"
+ |"Sys_error"
+ |"Failure"
+ |"Invalid_argument"
+ |"End_of_file"
+ |"Division_by_zero"
+ |"Not_found"
+ |"Match_failure"
+ |"Stack_overflow"
+ |"Sys_blocked_io"
+ |"Assert_failure"
+ |"Undefined_recursive_module" -> ()
+ | _ ->
+ try
+ let (old_crc,old_src,state) = StrMap.find name implems in
+ match crco with
+ Some crc when old_crc <> crc ->
+ raise(Error(Inconsistent_implementation(name)))
+ | _ ->
+ match state with
+ | Check_inited i ->
+ if ndl_globals_inited() < i
+ then raise(Error(Unavailable_unit name))
+ | Loaded -> ()
+ with Not_found ->
+ raise (Error(Unavailable_unit name))
+ ) ui.dynu_imports_cmx
+
+let loadunits filename handle units state =
+ let new_ifaces =
+ List.fold_left
+ (fun accu ui -> add_check_ifaces !allow_extension filename ui accu)
+ state.ifaces units in
+ let new_implems =
+ List.fold_left
+ (fun accu ui ->
+ check_implems filename ui accu;
+ StrMap.add ui.dynu_name (ui.dynu_crc,filename,Loaded) accu)
+ state.implems units in
+
+ let defines = List.flatten (List.map (fun ui -> ui.dynu_defines) units) in
+
+ ndl_run handle "_shared_startup";
+ List.iter (ndl_run handle) defines;
+ { implems = new_implems; ifaces = new_ifaces }
+
+let load priv filename =
+ init();
+ let (filename,handle,units) = read_file filename priv in
+ let nstate = loadunits filename handle units !global_state in
+ if not priv then global_state := nstate
+
+let loadfile filename = load false filename
+let loadfile_private filename = load true filename
+
+let allow_only names =
+ init();
+ let old = !global_state.ifaces in
+ let ifaces =
+ List.fold_left
+ (fun ifaces name ->
+ try StrMap.add name (StrMap.find name old) ifaces
+ with Not_found -> ifaces)
+ StrMap.empty names in
+ global_state := { !global_state with ifaces = ifaces };
+ allow_extension := false
+
+let prohibit names =
+ init();
+ let ifaces = List.fold_right StrMap.remove names !global_state.ifaces in
+ global_state := { !global_state with ifaces = ifaces };
+ allow_extension := false
+
+let digest_interface _ _ =
+ failwith "Dynlink.digest_interface: not implemented in native code"
+let add_interfaces _ _ =
+ failwith "Dynlink.add_interfaces: not implemented in native code"
+let add_available_units _ =
+ failwith "Dynlink.add_available_units: not implemented in native code"
+let clear_available_units _ =
+ failwith "Dynlink.clear_available_units: not implemented in native code"
+let allow_unsafe_modules _ =
+ ()
+
+(* Error report *)
+
+let error_message = function
+ Not_a_bytecode_file name ->
+ name ^ " is not an object file"
+ | Inconsistent_import name ->
+ "interface mismatch on " ^ name
+ | Unavailable_unit name ->
+ "no implementation available for " ^ name
+ | Unsafe_file ->
+ "this object file uses unsafe features"
+ | Linking_error (name, Undefined_global s) ->
+ "error while linking " ^ name ^ ".\n" ^
+ "Reference to undefined global `" ^ s ^ "'"
+ | Linking_error (name, Unavailable_primitive s) ->
+ "error while linking " ^ name ^ ".\n" ^
+ "The external function `" ^ s ^ "' is not available"
+ | Linking_error (name, Uninitialized_global s) ->
+ "error while linking " ^ name ^ ".\n" ^
+ "The module `" ^ s ^ "' is not yet initialized"
+ | Corrupted_interface name ->
+ "corrupted interface file " ^ name
+ | File_not_found name ->
+ "cannot find file " ^ name ^ " in search path"
+ | Cannot_open_dll reason ->
+ "error loading shared library: " ^ reason
+ | Inconsistent_implementation name ->
+ "implementation mismatch on " ^ name
+
+let is_native = true
+let adapt_filename f = Filename.chop_extension f ^ ".cmxs"
diff --git a/otherlibs/graph/.depend b/otherlibs/graph/.depend
new file mode 100644
index 0000000000..30f3dac330
--- /dev/null
+++ b/otherlibs/graph/.depend
@@ -0,0 +1,77 @@
+color.o: color.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h
+draw.o: draw.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/mlvalues.h
+dump_img.o: dump_img.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h image.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h
+events.o: events.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/signals.h
+fill.o: fill.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h
+image.o: image.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h image.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/custom.h
+make_img.o: make_img.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h image.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h
+open.o: open.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/callback.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h
+point_col.o: point_col.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h
+sound.o: sound.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h
+subwindow.o: subwindow.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h
+text.o: text.c libgraph.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/mlvalues.h
+graphics.cmi :
+graphicsX11.cmi :
+graphics.cmo : graphics.cmi
+graphics.cmx : graphics.cmi
+graphicsX11.cmo : graphics.cmi graphicsX11.cmi
+graphicsX11.cmx : graphics.cmx graphicsX11.cmi
diff --git a/otherlibs/graph/Makefile b/otherlibs/graph/Makefile
new file mode 100644
index 0000000000..850e02513e
--- /dev/null
+++ b/otherlibs/graph/Makefile
@@ -0,0 +1,32 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Makefile for the portable graphics library
+
+LIBNAME=graphics
+COBJS=open.o draw.o fill.o color.o text.o \
+ image.o make_img.o dump_img.o point_col.o sound.o events.o \
+ subwindow.o
+CAMLOBJS=graphics.cmo graphicsX11.cmo
+LINKOPTS=-cclib "\"$(X11_LINK)\""
+LDOPTS=-ldopt "$(X11_LINK)"
+
+EXTRACFLAGS=$(X11_INCLUDES)
+
+include ../Makefile
+
+depend:
+ $(CC) -MM $(CFLAGS) *.c | sed -e 's, /[^ ]*\.h,,g' > .depend
+ $(CAMLRUN) ../../tools/ocamldep *.mli *.ml >> .depend
+
+include .depend
diff --git a/otherlibs/graph/color.c b/otherlibs/graph/color.c
new file mode 100644
index 0000000000..5b94060523
--- /dev/null
+++ b/otherlibs/graph/color.c
@@ -0,0 +1,231 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+#include <X11/Xatom.h>
+
+/* Cache to speed up the translation rgb -> pixel value. */
+
+struct color_cache_entry {
+ int rgb; /* RGB value with format 0xRRGGBB */
+ unsigned long pixel; /* Pixel value */
+};
+
+#define Color_cache_size 512
+static struct color_cache_entry color_cache[Color_cache_size];
+#define Empty (-1)
+#define Hash_rgb(r,g,b) \
+ ((((r) & 0xE0) << 1) + (((g) & 0xE0) >> 2) + (((b) & 0xE0) >> 5))
+#define Color_cache_slack 16
+
+static int num_overflows = 0;
+
+/* rgb -> pixel conversion *without* display connection */
+
+Bool caml_gr_direct_rgb = False;
+int caml_gr_red_l, caml_gr_red_r;
+int caml_gr_green_l, caml_gr_green_r;
+int caml_gr_blue_l, caml_gr_blue_r;
+unsigned long caml_gr_red_mask, caml_gr_green_mask, caml_gr_blue_mask;
+
+/* rgb -> pixel table */
+unsigned long caml_gr_red_vals[256];
+unsigned long caml_gr_green_vals[256];
+unsigned long caml_gr_blue_vals[256];
+
+void caml_gr_get_shifts( unsigned long mask, int *lsl, int *lsr )
+{
+ int l = 0;
+ int r = 0;
+ int bit = 1;
+ if ( mask == 0 ){ *lsl = -1; *lsr = -1; return; }
+
+ for( l = 0; l < 32; l++ ){
+ if( bit & mask ){ break; }
+ bit = bit << 1;
+ }
+ for( r = l; r < 32; r++ ){
+ if( ! (bit & mask) ){ break; }
+ bit = bit << 1;
+ }
+ /* fix r */
+ if ( r == 32 ) { r = 31; }
+ *lsl = l;
+ *lsr = 16 - (r - l);
+}
+
+void caml_gr_init_direct_rgb_to_pixel(void)
+{
+ Visual *visual;
+ int i;
+
+ visual = DefaultVisual(caml_gr_display,caml_gr_screen);
+
+ if ( visual->class == TrueColor || visual->class == DirectColor ){
+
+ caml_gr_red_mask = visual->red_mask;
+ caml_gr_green_mask = visual->green_mask;
+ caml_gr_blue_mask = visual->blue_mask;
+
+#ifdef QUICKCOLORDEBUG
+ fprintf(stderr, "visual %lx %lx %lx\n",
+ caml_gr_red_mask,
+ caml_gr_green_mask,
+ caml_gr_blue_mask);
+#endif
+
+ caml_gr_get_shifts(caml_gr_red_mask, &caml_gr_red_l, &caml_gr_red_r);
+#ifdef QUICKCOLORDEBUG
+ fprintf(stderr, "red %d %d\n", caml_gr_red_l, caml_gr_red_r);
+#endif
+ for(i=0; i<256; i++){
+ caml_gr_red_vals[i] = (((i << 8) + i) >> caml_gr_red_r) << caml_gr_red_l;
+ }
+
+ caml_gr_get_shifts(caml_gr_green_mask, &caml_gr_green_l, &caml_gr_green_r);
+#ifdef QUICKCOLORDEBUG
+ fprintf(stderr, "green %d %d\n", caml_gr_green_l, caml_gr_green_r);
+#endif
+ for(i=0; i<256; i++){
+ caml_gr_green_vals[i] =
+ (((i << 8) + i) >> caml_gr_green_r) << caml_gr_green_l;
+ }
+
+ caml_gr_get_shifts(caml_gr_blue_mask, &caml_gr_blue_l, &caml_gr_blue_r);
+#ifdef QUICKCOLORDEBUG
+ fprintf(stderr, "blue %d %d\n", caml_gr_blue_l, caml_gr_blue_r);
+#endif
+ for(i=0; i<256; i++){
+ caml_gr_blue_vals[i] =
+ (((i << 8) + i) >> caml_gr_blue_r) << caml_gr_blue_l;
+ }
+
+ if( caml_gr_red_l < 0 || caml_gr_red_r < 0 ||
+ caml_gr_green_l < 0 || caml_gr_green_r < 0 ||
+ caml_gr_blue_l < 0 || caml_gr_blue_r < 0 ){
+#ifdef QUICKCOLORDEBUG
+ fprintf(stderr, "Damn, boost failed\n");
+#endif
+ caml_gr_direct_rgb = False;
+ } else {
+#ifdef QUICKCOLORDEBUG
+ fprintf(stderr, "Boost ok\n");
+#endif
+ caml_gr_direct_rgb = True;
+ }
+ } else {
+ /* we cannot use direct_rgb_to_pixel */
+#ifdef QUICKCOLORDEBUG
+ fprintf(stderr, "No boost!\n");
+#endif
+ caml_gr_direct_rgb = False;
+ }
+}
+
+void caml_gr_init_color_cache(void)
+{
+ int i;
+ for (i = 0; i < Color_cache_size; i++) color_cache[i].rgb = Empty;
+ i = Hash_rgb(0, 0, 0);
+ color_cache[i].rgb = 0;
+ color_cache[i].pixel = caml_gr_black;
+ i = Hash_rgb(0xFF, 0xFF, 0xFF);
+ color_cache[i].rgb = 0xFFFFFF;
+ color_cache[i].pixel = caml_gr_white;
+}
+
+unsigned long caml_gr_pixel_rgb(int rgb)
+{
+ unsigned int r, g, b;
+ int h, i;
+ XColor color;
+
+ r = (rgb >> 16) & 0xFF;
+ g = (rgb >> 8) & 0xFF;
+ b = rgb & 0xFF;
+
+ if (caml_gr_direct_rgb){
+ return caml_gr_red_vals[r] | caml_gr_green_vals[g] | caml_gr_blue_vals[b];
+ }
+
+ h = Hash_rgb(r, g, b);
+ i = h;
+ while(1) {
+ if (color_cache[i].rgb == Empty) break;
+ if (color_cache[i].rgb == rgb) return color_cache[i].pixel;
+ i = (i + 1) & (Color_cache_size - 1);
+ if (i == h) {
+ /* Cache is full. Instead of inserting at slot h, which causes
+ thrashing if many colors hash to the same value,
+ insert at h + n where n is pseudo-random and
+ smaller than Color_cache_slack */
+ int slack = num_overflows++ & (Color_cache_slack - 1);
+ i = (i + slack) & (Color_cache_size - 1);
+ break;
+ }
+ }
+ color.red = r * 0x101;
+ color.green = g * 0x101;
+ color.blue = b * 0x101;
+ XAllocColor(caml_gr_display, caml_gr_colormap, &color);
+ color_cache[i].rgb = rgb;
+ color_cache[i].pixel = color.pixel;
+ return color.pixel;
+}
+
+int caml_gr_rgb_pixel(long unsigned int pixel)
+{
+ register int r,g,b;
+
+ XColor color;
+ int i;
+
+ if (caml_gr_direct_rgb) {
+ r = (((pixel & caml_gr_red_mask) >> caml_gr_red_l) << 8)
+ >> (16 - caml_gr_red_r);
+ g = (((pixel & caml_gr_green_mask) >> caml_gr_green_l) << 8)
+ >> (16 - caml_gr_green_r);
+ b = (((pixel & caml_gr_blue_mask) >> caml_gr_blue_l) << 8)
+ >> (16 - caml_gr_blue_r);
+ return (r << 16) + (g << 8) + b;
+ }
+
+ if (pixel == caml_gr_black) return 0;
+ if (pixel == caml_gr_white) return 0xFFFFFF;
+
+ /* Probably faster to do a linear search than to query the X server. */
+ for (i = 0; i < Color_cache_size; i++) {
+ if (color_cache[i].rgb != Empty && color_cache[i].pixel == pixel)
+ return color_cache[i].rgb;
+ }
+ color.pixel = pixel;
+ XQueryColor(caml_gr_display, caml_gr_colormap, &color);
+ return
+ ((color.red >> 8) << 16) + ((color.green >> 8) << 8) + (color.blue >> 8);
+}
+
+value caml_gr_set_color(value vrgb)
+{
+ int xcolor;
+ caml_gr_check_open();
+ caml_gr_color = Int_val(vrgb);
+ if (caml_gr_color >= 0 ){
+ xcolor = caml_gr_pixel_rgb(Int_val(vrgb));
+ XSetForeground(caml_gr_display, caml_gr_window.gc, xcolor);
+ XSetForeground(caml_gr_display, caml_gr_bstore.gc, xcolor);
+ } else {
+ XSetForeground(caml_gr_display, caml_gr_window.gc, caml_gr_background);
+ XSetForeground(caml_gr_display, caml_gr_bstore.gc, caml_gr_background);
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/graph/draw.c b/otherlibs/graph/draw.c
new file mode 100644
index 0000000000..195860fa9f
--- /dev/null
+++ b/otherlibs/graph/draw.c
@@ -0,0 +1,125 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+#include <caml/alloc.h>
+
+value caml_gr_plot(value vx, value vy)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ caml_gr_check_open();
+ if(caml_gr_remember_modeflag)
+ XDrawPoint(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc, x,
+ Bcvt(y));
+ if(caml_gr_display_modeflag) {
+ XDrawPoint(caml_gr_display, caml_gr_window.win, caml_gr_window.gc, x,
+ Wcvt(y));
+ XFlush(caml_gr_display);
+ }
+ return Val_unit;
+}
+
+value caml_gr_moveto(value vx, value vy)
+{
+ caml_gr_x = Int_val(vx);
+ caml_gr_y = Int_val(vy);
+ return Val_unit;
+}
+
+value caml_gr_current_x(void)
+{
+ return Val_int(caml_gr_x);
+}
+
+value caml_gr_current_y(void)
+{
+ return Val_int(caml_gr_y);
+}
+
+value caml_gr_lineto(value vx, value vy)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ caml_gr_check_open();
+ if(caml_gr_remember_modeflag)
+ XDrawLine(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
+ caml_gr_x, Bcvt(caml_gr_y), x, Bcvt(y));
+ if(caml_gr_display_modeflag) {
+ XDrawLine(caml_gr_display, caml_gr_window.win, caml_gr_window.gc,
+ caml_gr_x, Wcvt(caml_gr_y), x, Wcvt(y));
+ XFlush(caml_gr_display);
+ }
+ caml_gr_x = x;
+ caml_gr_y = y;
+ return Val_unit;
+}
+
+value caml_gr_draw_rect(value vx, value vy, value vw, value vh)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ int w = Int_val(vw);
+ int h = Int_val(vh);
+
+ caml_gr_check_open();
+ if(caml_gr_remember_modeflag)
+ XDrawRectangle(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
+ x, Bcvt(y) - h, w, h);
+ if(caml_gr_display_modeflag) {
+ XDrawRectangle(caml_gr_display, caml_gr_window.win, caml_gr_window.gc,
+ x, Wcvt(y) - h, w, h);
+ XFlush(caml_gr_display);
+ }
+ return Val_unit;
+}
+
+value caml_gr_draw_arc_nat(value vx, value vy, value vrx, value vry, value va1,
+ value va2)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ int rx = Int_val(vrx);
+ int ry = Int_val(vry);
+ int a1 = Int_val(va1);
+ int a2 = Int_val(va2);
+
+ caml_gr_check_open();
+ if(caml_gr_remember_modeflag)
+ XDrawArc(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
+ x - rx, Bcvt(y) - ry, rx * 2, ry * 2, a1 * 64, (a2 - a1) * 64);
+ if(caml_gr_display_modeflag) {
+ XDrawArc(caml_gr_display, caml_gr_window.win, caml_gr_window.gc,
+ x - rx, Wcvt(y) - ry, rx * 2, ry * 2, a1 * 64, (a2 - a1) * 64);
+ XFlush(caml_gr_display);
+ }
+ return Val_unit;
+}
+
+value caml_gr_draw_arc(value *argv, int argc)
+{
+ return caml_gr_draw_arc_nat(argv[0], argv[1], argv[2], argv[3], argv[4],
+ argv[5]);
+}
+
+value caml_gr_set_line_width(value vwidth)
+{
+ int width = Int_val(vwidth);
+
+ caml_gr_check_open();
+ XSetLineAttributes(caml_gr_display, caml_gr_window.gc,
+ width, LineSolid, CapRound, JoinRound);
+ XSetLineAttributes(caml_gr_display, caml_gr_bstore.gc,
+ width, LineSolid, CapRound, JoinRound);
+ return Val_unit;
+}
diff --git a/otherlibs/graph/dump_img.c b/otherlibs/graph/dump_img.c
new file mode 100644
index 0000000000..26f816076c
--- /dev/null
+++ b/otherlibs/graph/dump_img.c
@@ -0,0 +1,56 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+#include "image.h"
+#include <caml/alloc.h>
+#include <caml/memory.h>
+
+value caml_gr_dump_image(value image)
+{
+ int width, height, i, j;
+ XImage * idata, * imask;
+ value m = Val_unit;
+
+ Begin_roots2(image, m);
+ caml_gr_check_open();
+ width = Width_im(image);
+ height = Height_im(image);
+ m = alloc(height, 0);
+ for (i = 0; i < height; i++) {
+ value v = alloc(width, 0);
+ modify(&Field(m, i), v);
+ }
+
+ idata =
+ XGetImage(caml_gr_display, Data_im(image), 0, 0, width, height, (-1),
+ ZPixmap);
+ for (i = 0; i < height; i++)
+ for (j = 0; j < width; j++)
+ Field(Field(m, i), j) =
+ Val_int(caml_gr_rgb_pixel(XGetPixel(idata, j, i)));
+ XDestroyImage(idata);
+
+ if (Mask_im(image) != None) {
+ imask =
+ XGetImage(caml_gr_display, Mask_im(image), 0, 0, width, height, 1,
+ ZPixmap);
+ for (i = 0; i < height; i++)
+ for (j = 0; j < width; j++)
+ if (XGetPixel(imask, j, i) == 0)
+ Field(Field(m, i), j) = Val_int(Transparent);
+ XDestroyImage(imask);
+ }
+ End_roots();
+ return m;
+}
diff --git a/otherlibs/graph/events.c b/otherlibs/graph/events.c
new file mode 100644
index 0000000000..a8fe119baa
--- /dev/null
+++ b/otherlibs/graph/events.c
@@ -0,0 +1,275 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <signal.h>
+#include "libgraph.h"
+#include <caml/alloc.h>
+#include <caml/signals.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#ifdef HAS_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+#include <string.h>
+#include <unistd.h>
+
+struct event_data {
+ short kind;
+ short mouse_x, mouse_y;
+ unsigned char button;
+ unsigned char key;
+};
+
+static struct event_data caml_gr_queue[SIZE_QUEUE];
+static unsigned int caml_gr_head = 0; /* position of next read */
+static unsigned int caml_gr_tail = 0; /* position of next write */
+
+#define QueueIsEmpty (caml_gr_tail == caml_gr_head)
+
+static void caml_gr_enqueue_event(int kind, int mouse_x, int mouse_y,
+ int button, int key)
+{
+ struct event_data * ev;
+
+ ev = &(caml_gr_queue[caml_gr_tail]);
+ ev->kind = kind;
+ ev->mouse_x = mouse_x;
+ ev->mouse_y = mouse_y;
+ ev->button = (button != 0);
+ ev->key = key;
+ caml_gr_tail = (caml_gr_tail + 1) % SIZE_QUEUE;
+ /* If queue was full, it now appears empty; drop oldest entry from queue. */
+ if (QueueIsEmpty) caml_gr_head = (caml_gr_head + 1) % SIZE_QUEUE;
+}
+
+#define BUTTON_STATE(state) \
+ ((state) & (Button1Mask|Button2Mask|Button3Mask|Button4Mask|Button5Mask))
+
+void caml_gr_handle_event(XEvent * event)
+{
+ switch (event->type) {
+
+ case Expose:
+ XCopyArea(caml_gr_display, caml_gr_bstore.win, caml_gr_window.win,
+ caml_gr_window.gc,
+ event->xexpose.x,
+ event->xexpose.y + caml_gr_bstore.h - caml_gr_window.h,
+ event->xexpose.width, event->xexpose.height,
+ event->xexpose.x, event->xexpose.y);
+ XFlush(caml_gr_display);
+ break;
+
+ case ConfigureNotify:
+ caml_gr_window.w = event->xconfigure.width;
+ caml_gr_window.h = event->xconfigure.height;
+ if (caml_gr_window.w > caml_gr_bstore.w
+ || caml_gr_window.h > caml_gr_bstore.h) {
+
+ /* Allocate a new backing store large enough to accomodate
+ both the old backing store and the current window. */
+ struct canvas newbstore;
+ newbstore.w = max(caml_gr_window.w, caml_gr_bstore.w);
+ newbstore.h = max(caml_gr_window.h, caml_gr_bstore.h);
+ newbstore.win =
+ XCreatePixmap(caml_gr_display, caml_gr_window.win, newbstore.w,
+ newbstore.h,
+ XDefaultDepth(caml_gr_display, caml_gr_screen));
+ newbstore.gc = XCreateGC(caml_gr_display, newbstore.win, 0, NULL);
+ XSetBackground(caml_gr_display, newbstore.gc, caml_gr_white);
+ XSetForeground(caml_gr_display, newbstore.gc, caml_gr_white);
+ XFillRectangle(caml_gr_display, newbstore.win, newbstore.gc,
+ 0, 0, newbstore.w, newbstore.h);
+ XSetForeground(caml_gr_display, newbstore.gc, caml_gr_color);
+ if (caml_gr_font != NULL)
+ XSetFont(caml_gr_display, newbstore.gc, caml_gr_font->fid);
+
+ /* Copy the old backing store into the new one */
+ XCopyArea(caml_gr_display, caml_gr_bstore.win, newbstore.win,
+ newbstore.gc,
+ 0, 0, caml_gr_bstore.w, caml_gr_bstore.h, 0,
+ newbstore.h - caml_gr_bstore.h);
+
+ /* Free the old backing store */
+ XFreeGC(caml_gr_display, caml_gr_bstore.gc);
+ XFreePixmap(caml_gr_display, caml_gr_bstore.win);
+
+ /* Use the new backing store */
+ caml_gr_bstore = newbstore;
+ XFlush(caml_gr_display);
+ }
+ break;
+
+ case MappingNotify:
+ XRefreshKeyboardMapping(&(event->xmapping));
+ break;
+
+ case KeyPress:
+ { KeySym thekey;
+ char keytxt[256];
+ int nchars;
+ char * p;
+ nchars = XLookupString(&(event->xkey), keytxt, sizeof(keytxt),
+ &thekey, 0);
+ for (p = keytxt; nchars > 0; p++, nchars--)
+ caml_gr_enqueue_event(event->type, event->xkey.x, event->xkey.y,
+ BUTTON_STATE(event->xkey.state), *p);
+ break;
+ }
+
+ case ButtonPress:
+ case ButtonRelease:
+ caml_gr_enqueue_event(event->type, event->xbutton.x, event->xbutton.y,
+ event->type == ButtonPress, 0);
+ break;
+
+ case MotionNotify:
+ caml_gr_enqueue_event(event->type, event->xmotion.x, event->xmotion.y,
+ BUTTON_STATE(event->xmotion.state), 0);
+ break;
+ }
+}
+
+static value caml_gr_wait_allocate_result(int mouse_x, int mouse_y, int button,
+ int keypressed, int key)
+{
+ value res = alloc_small(5, 0);
+ Field(res, 0) = Val_int(mouse_x);
+ Field(res, 1) = Val_int(mouse_y == -1 ? -1 : Wcvt(mouse_y));
+ Field(res, 2) = Val_bool(button);
+ Field(res, 3) = Val_bool(keypressed);
+ Field(res, 4) = Val_int(key & 0xFF);
+ return res;
+}
+
+static value caml_gr_wait_event_poll(void)
+{
+ int mouse_x, mouse_y, button, key, keypressed;
+ Window rootwin, childwin;
+ int root_x, root_y, win_x, win_y;
+ unsigned int modifiers;
+ unsigned int i;
+
+ caml_process_pending_signals ();
+ if (XQueryPointer(caml_gr_display, caml_gr_window.win,
+ &rootwin, &childwin,
+ &root_x, &root_y, &win_x, &win_y,
+ &modifiers)) {
+ mouse_x = win_x;
+ mouse_y = win_y;
+ } else {
+ mouse_x = -1;
+ mouse_y = -1;
+ }
+ button = modifiers & (Button1Mask | Button2Mask | Button3Mask
+ | Button4Mask | Button5Mask);
+ /* Look inside event queue for pending KeyPress events */
+ key = 0;
+ keypressed = False;
+ for (i = caml_gr_head; i != caml_gr_tail; i = (i + 1) % SIZE_QUEUE) {
+ if (caml_gr_queue[i].kind == KeyPress) {
+ keypressed = True;
+ key = caml_gr_queue[i].key;
+ break;
+ }
+ }
+ return
+ caml_gr_wait_allocate_result(mouse_x, mouse_y, button, keypressed, key);
+}
+
+static value caml_gr_wait_event_in_queue(long mask)
+{
+ struct event_data * ev;
+ /* Pop events in queue until one matches mask. */
+ while (caml_gr_head != caml_gr_tail) {
+ ev = &(caml_gr_queue[caml_gr_head]);
+ caml_gr_head = (caml_gr_head + 1) % SIZE_QUEUE;
+ if ((ev->kind == KeyPress && (mask & KeyPressMask))
+ || (ev->kind == ButtonPress && (mask & ButtonPressMask))
+ || (ev->kind == ButtonRelease && (mask & ButtonReleaseMask))
+ || (ev->kind == MotionNotify && (mask & PointerMotionMask)))
+ return caml_gr_wait_allocate_result(ev->mouse_x, ev->mouse_y,
+ ev->button, ev->kind == KeyPress,
+ ev->key);
+ }
+ return Val_false;
+}
+
+static value caml_gr_wait_event_blocking(long mask)
+{
+ XEvent event;
+ fd_set readfds;
+ value res;
+
+ /* First see if we have a matching event in the queue */
+ res = caml_gr_wait_event_in_queue(mask);
+ if (res != Val_false) return res;
+
+ /* Increase the selected events if required */
+ if ((mask & ~caml_gr_selected_events) != 0) {
+ caml_gr_selected_events |= mask;
+ XSelectInput(caml_gr_display, caml_gr_window.win, caml_gr_selected_events);
+ }
+
+ /* Replenish our event queue from that of X11 */
+ caml_gr_ignore_sigio = True;
+ while (1) {
+ if (XCheckMaskEvent(caml_gr_display, -1 /*all events*/, &event)) {
+ /* One event available: add it to our queue */
+ caml_gr_handle_event(&event);
+ /* See if we now have a matching event */
+ res = caml_gr_wait_event_in_queue(mask);
+ if (res != Val_false) break;
+ } else {
+ /* No event available: block on input socket until one is */
+ FD_ZERO(&readfds);
+ FD_SET(ConnectionNumber(caml_gr_display), &readfds);
+ enter_blocking_section();
+ select(FD_SETSIZE, &readfds, NULL, NULL, NULL);
+ leave_blocking_section();
+ caml_gr_check_open(); /* in case another thread closed the display */
+ }
+ }
+ caml_gr_ignore_sigio = False;
+
+ /* Return result */
+ return res;
+}
+
+value caml_gr_wait_event(value eventlist) /* ML */
+{
+ int mask;
+ Bool poll;
+
+ caml_gr_check_open();
+ mask = 0;
+ poll = False;
+ while (eventlist != Val_int(0)) {
+ switch (Int_val(Field(eventlist, 0))) {
+ case 0: /* Button_down */
+ mask |= ButtonPressMask | OwnerGrabButtonMask; break;
+ case 1: /* Button_up */
+ mask |= ButtonReleaseMask | OwnerGrabButtonMask; break;
+ case 2: /* Key_pressed */
+ mask |= KeyPressMask; break;
+ case 3: /* Mouse_motion */
+ mask |= PointerMotionMask; break;
+ case 4: /* Poll */
+ poll = True; break;
+ }
+ eventlist = Field(eventlist, 1);
+ }
+ if (poll)
+ return caml_gr_wait_event_poll();
+ else
+ return caml_gr_wait_event_blocking(mask);
+}
diff --git a/otherlibs/graph/fill.c b/otherlibs/graph/fill.c
new file mode 100644
index 0000000000..8dc2f8777d
--- /dev/null
+++ b/otherlibs/graph/fill.c
@@ -0,0 +1,88 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+#include <caml/memory.h>
+
+value caml_gr_fill_rect(value vx, value vy, value vw, value vh)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ int w = Int_val(vw);
+ int h = Int_val(vh);
+
+ caml_gr_check_open();
+ if(caml_gr_remember_modeflag)
+ XFillRectangle(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
+ x, Bcvt(y) - h, w + 1, h + 1);
+ if(caml_gr_display_modeflag) {
+ XFillRectangle(caml_gr_display, caml_gr_window.win, caml_gr_window.gc,
+ x, Wcvt(y) - h, w + 1, h + 1);
+ XFlush(caml_gr_display);
+ }
+ return Val_unit;
+}
+
+value caml_gr_fill_poly(value array)
+{
+ XPoint * points;
+ int npoints, i;
+
+ caml_gr_check_open();
+ npoints = Wosize_val(array);
+ points = (XPoint *) caml_stat_alloc(npoints * sizeof(XPoint));
+ for (i = 0; i < npoints; i++) {
+ points[i].x = Int_val(Field(Field(array, i), 0));
+ points[i].y = Bcvt(Int_val(Field(Field(array, i), 1)));
+ }
+ if(caml_gr_remember_modeflag)
+ XFillPolygon(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc, points,
+ npoints, Complex, CoordModeOrigin);
+ if(caml_gr_display_modeflag) {
+ for (i = 0; i < npoints; i++)
+ points[i].y = BtoW(points[i].y);
+ XFillPolygon(caml_gr_display, caml_gr_window.win, caml_gr_window.gc, points,
+ npoints, Complex, CoordModeOrigin);
+ XFlush(caml_gr_display);
+ }
+ stat_free((char *) points);
+ return Val_unit;
+}
+
+value caml_gr_fill_arc_nat(value vx, value vy, value vrx, value vry, value va1,
+ value va2)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ int rx = Int_val(vrx);
+ int ry = Int_val(vry);
+ int a1 = Int_val(va1);
+ int a2 = Int_val(va2);
+
+ caml_gr_check_open();
+ if(caml_gr_remember_modeflag)
+ XFillArc(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
+ x - rx, Bcvt(y) - ry, rx * 2, ry * 2, a1 * 64, (a2 - a1) * 64);
+ if(caml_gr_display_modeflag) {
+ XFillArc(caml_gr_display, caml_gr_window.win, caml_gr_window.gc,
+ x - rx, Wcvt(y) - ry, rx * 2, ry * 2, a1 * 64, (a2 - a1) * 64);
+ XFlush(caml_gr_display);
+ }
+ return Val_unit;
+}
+
+value caml_gr_fill_arc(value *argv, int argc)
+{
+ return caml_gr_fill_arc_nat(argv[0], argv[1], argv[2], argv[3], argv[4],
+ argv[5]);
+}
diff --git a/otherlibs/graph/graphics.ml b/otherlibs/graph/graphics.ml
new file mode 100644
index 0000000000..441c6760cd
--- /dev/null
+++ b/otherlibs/graph/graphics.ml
@@ -0,0 +1,265 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+exception Graphic_failure of string
+
+(* Initializations *)
+
+let _ =
+ Callback.register_exception "Graphics.Graphic_failure" (Graphic_failure "")
+
+external raw_open_graph: string -> unit = "caml_gr_open_graph"
+external raw_close_graph: unit -> unit = "caml_gr_close_graph"
+external sigio_signal: unit -> int = "caml_gr_sigio_signal"
+external sigio_handler: int -> unit = "caml_gr_sigio_handler"
+
+let unix_open_graph arg =
+ Sys.set_signal (sigio_signal()) (Sys.Signal_handle sigio_handler);
+ raw_open_graph arg
+
+let unix_close_graph () =
+ Sys.set_signal (sigio_signal()) Sys.Signal_ignore;
+ raw_close_graph ()
+
+let (open_graph, close_graph) =
+ match Sys.os_type with
+ | "Unix" | "Cygwin" -> (unix_open_graph, unix_close_graph)
+ | "Win32" -> (raw_open_graph, raw_close_graph)
+ | "MacOS" -> (raw_open_graph, raw_close_graph)
+ | _ -> invalid_arg ("Graphics: unknown OS type: " ^ Sys.os_type)
+
+external set_window_title : string -> unit = "caml_gr_set_window_title"
+external resize_window : int -> int -> unit = "caml_gr_resize_window"
+external clear_graph : unit -> unit = "caml_gr_clear_graph"
+external size_x : unit -> int = "caml_gr_size_x"
+external size_y : unit -> int = "caml_gr_size_y"
+
+(* Double-buffering *)
+
+external display_mode : bool -> unit = "caml_gr_display_mode"
+external remember_mode : bool -> unit = "caml_gr_remember_mode"
+external synchronize : unit -> unit = "caml_gr_synchronize"
+
+let auto_synchronize = function
+ | true -> display_mode true; remember_mode true; synchronize ()
+ | false -> display_mode false; remember_mode true
+;;
+
+
+(* Colors *)
+
+type color = int
+
+let rgb r g b = (r lsl 16) + (g lsl 8) + b
+
+external set_color : color -> unit = "caml_gr_set_color"
+
+let black = 0x000000
+and white = 0xFFFFFF
+and red = 0xFF0000
+and green = 0x00FF00
+and blue = 0x0000FF
+and yellow = 0xFFFF00
+and cyan = 0x00FFFF
+and magenta = 0xFF00FF
+
+let background = white
+and foreground = black
+
+(* Drawing *)
+
+external plot : int -> int -> unit = "caml_gr_plot"
+let plots points =
+ for i = 0 to Array.length points - 1 do
+ let (x, y) = points.(i) in
+ plot x y;
+ done
+;;
+external point_color : int -> int -> color = "caml_gr_point_color"
+external moveto : int -> int -> unit = "caml_gr_moveto"
+external current_x : unit -> int = "caml_gr_current_x"
+external current_y : unit -> int = "caml_gr_current_y"
+let current_point () = current_x (), current_y ()
+external lineto : int -> int -> unit = "caml_gr_lineto"
+let rlineto x y = lineto (current_x () + x) (current_y () + y)
+let rmoveto x y = moveto (current_x () + x) (current_y () + y)
+
+external raw_draw_rect : int -> int -> int -> int -> unit = "caml_gr_draw_rect"
+let draw_rect x y w h =
+ if w < 0 || h < 0 then raise (Invalid_argument "draw_rect")
+ else raw_draw_rect x y w h
+;;
+
+let draw_poly, draw_poly_line =
+ let dodraw close_flag points =
+ if Array.length points > 0 then begin
+ let (savex, savey) = current_point () in
+ moveto (fst points.(0)) (snd points.(0));
+ for i = 1 to Array.length points - 1 do
+ let (x, y) = points.(i) in
+ lineto x y;
+ done;
+ if close_flag then lineto (fst points.(0)) (snd points.(0));
+ moveto savex savey;
+ end;
+ in dodraw true, dodraw false
+;;
+let draw_segments segs =
+ let (savex, savey) = current_point () in
+ for i = 0 to Array.length segs - 1 do
+ let (x1, y1, x2, y2) = segs.(i) in
+ moveto x1 y1;
+ lineto x2 y2;
+ done;
+ moveto savex savey;
+;;
+
+external raw_draw_arc : int -> int -> int -> int -> int -> int -> unit
+ = "caml_gr_draw_arc" "caml_gr_draw_arc_nat"
+let draw_arc x y rx ry a1 a2 =
+ if rx < 0 || ry < 0 then raise (Invalid_argument "draw_arc/ellipse/circle")
+ else raw_draw_arc x y rx ry a1 a2
+;;
+
+let draw_ellipse x y rx ry = draw_arc x y rx ry 0 360
+let draw_circle x y r = draw_arc x y r r 0 360
+
+external raw_set_line_width : int -> unit = "caml_gr_set_line_width"
+let set_line_width w =
+ if w < 0 then raise (Invalid_argument "set_line_width")
+ else raw_set_line_width w
+;;
+
+external raw_fill_rect : int -> int -> int -> int -> unit = "caml_gr_fill_rect"
+let fill_rect x y w h =
+ if w < 0 || h < 0 then raise (Invalid_argument "fill_rect")
+ else raw_fill_rect x y w h
+;;
+
+external fill_poly : (int * int) array -> unit = "caml_gr_fill_poly"
+external raw_fill_arc : int -> int -> int -> int -> int -> int -> unit
+ = "caml_gr_fill_arc" "caml_gr_fill_arc_nat"
+let fill_arc x y rx ry a1 a2 =
+ if rx < 0 || ry < 0 then raise (Invalid_argument "fill_arc/ellipse/circle")
+ else raw_fill_arc x y rx ry a1 a2
+;;
+
+let fill_ellipse x y rx ry = fill_arc x y rx ry 0 360
+let fill_circle x y r = fill_arc x y r r 0 360
+
+(* Text *)
+
+external draw_char : char -> unit = "caml_gr_draw_char"
+external draw_string : string -> unit = "caml_gr_draw_string"
+external set_font : string -> unit = "caml_gr_set_font"
+external set_text_size : int -> unit = "caml_gr_set_text_size"
+external text_size : string -> int * int = "caml_gr_text_size"
+
+(* Images *)
+
+type image
+
+let transp = -1
+
+external make_image : color array array -> image = "caml_gr_make_image"
+external dump_image : image -> color array array = "caml_gr_dump_image"
+external draw_image : image -> int -> int -> unit = "caml_gr_draw_image"
+external create_image : int -> int -> image = "caml_gr_create_image"
+external blit_image : image -> int -> int -> unit = "caml_gr_blit_image"
+
+let get_image x y w h =
+ let image = create_image w h in
+ blit_image image x y;
+ image
+
+(* Events *)
+
+type status =
+ { mouse_x : int;
+ mouse_y : int;
+ button : bool;
+ keypressed : bool;
+ key : char }
+
+type event =
+ Button_down
+ | Button_up
+ | Key_pressed
+ | Mouse_motion
+ | Poll
+
+external wait_next_event : event list -> status = "caml_gr_wait_event"
+
+let mouse_pos () =
+ let e = wait_next_event [Poll] in (e.mouse_x, e.mouse_y)
+
+let button_down () =
+ let e = wait_next_event [Poll] in e.button
+
+let read_key () =
+ let e = wait_next_event [Key_pressed] in e.key
+
+let key_pressed () =
+ let e = wait_next_event [Poll] in e.keypressed
+
+let loop_at_exit events handler =
+ let events = List.filter (fun e -> e <> Poll) events in
+ at_exit (fun _ ->
+ try
+ while true do
+ let e = wait_next_event events in
+ handler e
+ done
+ with Exit -> close_graph ()
+ | e -> close_graph (); raise e
+ )
+
+(*** Sound *)
+
+external sound : int -> int -> unit = "caml_gr_sound"
+
+(* Splines *)
+let add (x1, y1) (x2, y2) = (x1 +. x2, y1 +. y2)
+and sub (x1, y1) (x2, y2) = (x1 -. x2, y1 -. y2)
+and middle (x1, y1) (x2, y2) = ((x1 +. x2) /. 2.0, (y1 +. y2) /. 2.0)
+and area (x1, y1) (x2, y2) = abs_float (x1 *. y2 -. x2 *. y1)
+and norm (x1, y1) = sqrt (x1 *. x1 +. y1 *. y1);;
+
+let test a b c d =
+ let v = sub d a in
+ let s = norm v in
+ area v (sub a b) <= s && area v (sub a c) <= s;;
+
+let spline a b c d =
+ let rec spl accu a b c d =
+ if test a b c d then d :: accu else
+ let a' = middle a b
+ and o = middle b c in
+ let b' = middle a' o
+ and d' = middle c d in
+ let c' = middle o d' in
+ let i = middle b' c' in
+ spl (spl accu a a' b' i) i c' d' d in
+ spl [a] a b c d;;
+
+let curveto b c (x, y as d) =
+ let float_point (x, y) = (float_of_int x, float_of_int y) in
+ let round f = int_of_float (f +. 0.5) in
+ let int_point (x, y) = (round x, round y) in
+ let points =
+ spline
+ (float_point (current_point ()))
+ (float_point b) (float_point c) (float_point d) in
+ draw_poly_line
+ (Array.of_list (List.map int_point points));
+ moveto x y;;
diff --git a/otherlibs/graph/graphics.mli b/otherlibs/graph/graphics.mli
new file mode 100644
index 0000000000..81cd4eeb05
--- /dev/null
+++ b/otherlibs/graph/graphics.mli
@@ -0,0 +1,383 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Machine-independent graphics primitives. *)
+
+exception Graphic_failure of string
+(** Raised by the functions below when they encounter an error. *)
+
+
+(** {6 Initializations} *)
+
+val open_graph : string -> unit
+(** Show the graphics window or switch the screen to graphic mode.
+ The graphics window is cleared and the current point is set
+ to (0, 0). The string argument is used to pass optional
+ information on the desired graphics mode, the graphics window
+ size, and so on. Its interpretation is implementation-dependent.
+ If the empty string is given, a sensible default is selected. *)
+
+val close_graph : unit -> unit
+(** Delete the graphics window or switch the screen back to text mode. *)
+
+val set_window_title : string -> unit
+(** Set the title of the graphics window. *)
+
+val resize_window : int -> int -> unit
+(** Resize and erase the graphics window. *)
+
+external clear_graph : unit -> unit = "caml_gr_clear_graph"
+(** Erase the graphics window. *)
+
+external size_x : unit -> int = "caml_gr_size_x"
+(** See {!Graphics.size_y}. *)
+
+external size_y : unit -> int = "caml_gr_size_y"
+(** Return the size of the graphics window. Coordinates of the screen
+ pixels range over [0 .. size_x()-1] and [0 .. size_y()-1].
+ Drawings outside of this rectangle are clipped, without causing
+ an error. The origin (0,0) is at the lower left corner. *)
+
+(** {6 Colors} *)
+
+type color = int
+(** A color is specified by its R, G, B components. Each component
+ is in the range [0..255]. The three components are packed in
+ an [int]: [0xRRGGBB], where [RR] are the two hexadecimal digits for
+ the red component, [GG] for the green component, [BB] for the
+ blue component. *)
+
+val rgb : int -> int -> int -> color
+(** [rgb r g b] returns the integer encoding the color with red
+ component [r], green component [g], and blue component [b].
+ [r], [g] and [b] are in the range [0..255]. *)
+
+external set_color : color -> unit = "caml_gr_set_color"
+(** Set the current drawing color. *)
+
+val background : color
+(** See {!Graphics.foreground}.*)
+
+val foreground : color
+(** Default background and foreground colors (usually, either black
+ foreground on a white background or white foreground on a
+ black background).
+ {!Graphics.clear_graph} fills the screen with the [background] color.
+ The initial drawing color is [foreground]. *)
+
+
+(** {7 Some predefined colors} *)
+
+val black : color
+val white : color
+val red : color
+val green : color
+val blue : color
+val yellow : color
+val cyan : color
+val magenta : color
+
+
+(** {6 Point and line drawing} *)
+
+external plot : int -> int -> unit = "caml_gr_plot"
+(** Plot the given point with the current drawing color. *)
+
+val plots : (int * int) array -> unit
+(** Plot the given points with the current drawing color. *)
+
+external point_color : int -> int -> color = "caml_gr_point_color"
+(** Return the color of the given point in the backing store
+ (see "Double buffering" below). *)
+
+external moveto : int -> int -> unit = "caml_gr_moveto"
+(** Position the current point. *)
+
+val rmoveto : int -> int -> unit
+(** [rmoveto dx dy] translates the current point by the given vector. *)
+
+external current_x : unit -> int = "caml_gr_current_x"
+(** Return the abscissa of the current point. *)
+
+external current_y : unit -> int = "caml_gr_current_y"
+(** Return the ordinate of the current point. *)
+
+val current_point : unit -> int * int
+(** Return the position of the current point. *)
+
+external lineto : int -> int -> unit = "caml_gr_lineto"
+(** Draw a line with endpoints the current point and the given point,
+ and move the current point to the given point. *)
+
+val rlineto : int -> int -> unit
+(** Draw a line with endpoints the current point and the
+ current point translated of the given vector,
+ and move the current point to this point. *)
+
+val curveto : int * int -> int * int -> int * int -> unit
+(** [curveto b c d] draws a cubic Bezier curve starting from
+ the current point to point [d], with control points [b] and
+ [c], and moves the current point to [d]. *)
+
+val draw_rect : int -> int -> int -> int -> unit
+(** [draw_rect x y w h] draws the rectangle with lower left corner
+ at [x,y], width [w] and height [h].
+ The current point is unchanged.
+ Raise [Invalid_argument] if [w] or [h] is negative. *)
+
+val draw_poly_line : (int * int) array -> unit
+(** [draw_poly_line points] draws the line that joins the
+ points given by the array argument.
+ The array contains the coordinates of the vertices of the
+ polygonal line, which need not be closed.
+ The current point is unchanged. *)
+
+val draw_poly : (int * int) array -> unit
+(** [draw_poly polygon] draws the given polygon.
+ The array contains the coordinates of the vertices of the
+ polygon.
+ The current point is unchanged. *)
+
+val draw_segments : (int * int * int * int) array -> unit
+(** [draw_segments segments] draws the segments given in the array
+ argument. Each segment is specified as a quadruple
+ [(x0, y0, x1, y1)] where [(x0, y0)] and [(x1, y1)] are
+ the coordinates of the end points of the segment.
+ The current point is unchanged. *)
+
+val draw_arc : int -> int -> int -> int -> int -> int -> unit
+(** [draw_arc x y rx ry a1 a2] draws an elliptical arc with center
+ [x,y], horizontal radius [rx], vertical radius [ry], from angle
+ [a1] to angle [a2] (in degrees). The current point is unchanged.
+ Raise [Invalid_argument] if [rx] or [ry] is negative. *)
+
+val draw_ellipse : int -> int -> int -> int -> unit
+(** [draw_ellipse x y rx ry] draws an ellipse with center
+ [x,y], horizontal radius [rx] and vertical radius [ry].
+ The current point is unchanged.
+ Raise [Invalid_argument] if [rx] or [ry] is negative. *)
+
+val draw_circle : int -> int -> int -> unit
+(** [draw_circle x y r] draws a circle with center [x,y] and
+ radius [r]. The current point is unchanged.
+ Raise [Invalid_argument] if [r] is negative. *)
+
+val set_line_width : int -> unit
+(** Set the width of points and lines drawn with the functions above.
+ Under X Windows, [set_line_width 0] selects a width of 1 pixel
+ and a faster, but less precise drawing algorithm than the one
+ used when [set_line_width 1] is specified.
+ Raise [Invalid_argument] if the argument is negative. *)
+
+(** {6 Text drawing} *)
+
+external draw_char : char -> unit = "caml_gr_draw_char"
+(** See {!Graphics.draw_string}.*)
+
+external draw_string : string -> unit = "caml_gr_draw_string"
+(** Draw a character or a character string with lower left corner
+ at current position. After drawing, the current position is set
+ to the lower right corner of the text drawn. *)
+
+external set_font : string -> unit = "caml_gr_set_font"
+(** Set the font used for drawing text.
+ The interpretation of the argument to [set_font]
+ is implementation-dependent. *)
+
+val set_text_size : int -> unit
+(** Set the character size used for drawing text.
+ The interpretation of the argument to [set_text_size]
+ is implementation-dependent. *)
+
+external text_size : string -> int * int = "caml_gr_text_size"
+(** Return the dimensions of the given text, if it were drawn with
+ the current font and size. *)
+
+
+(** {6 Filling} *)
+
+val fill_rect : int -> int -> int -> int -> unit
+(** [fill_rect x y w h] fills the rectangle with lower left corner
+ at [x,y], width [w] and height [h], with the current color.
+ Raise [Invalid_argument] if [w] or [h] is negative. *)
+
+external fill_poly : (int * int) array -> unit = "caml_gr_fill_poly"
+(** Fill the given polygon with the current color. The array
+ contains the coordinates of the vertices of the polygon. *)
+
+val fill_arc : int -> int -> int -> int -> int -> int -> unit
+(** Fill an elliptical pie slice with the current color. The
+ parameters are the same as for {!Graphics.draw_arc}. *)
+
+val fill_ellipse : int -> int -> int -> int -> unit
+(** Fill an ellipse with the current color. The
+ parameters are the same as for {!Graphics.draw_ellipse}. *)
+
+val fill_circle : int -> int -> int -> unit
+(** Fill a circle with the current color. The
+ parameters are the same as for {!Graphics.draw_circle}. *)
+
+
+(** {6 Images} *)
+
+type image
+(** The abstract type for images, in internal representation.
+ Externally, images are represented as matrices of colors. *)
+
+val transp : color
+(** In matrices of colors, this color represent a 'transparent'
+ point: when drawing the corresponding image, all pixels on the
+ screen corresponding to a transparent pixel in the image will
+ not be modified, while other points will be set to the color
+ of the corresponding point in the image. This allows superimposing
+ an image over an existing background. *)
+
+external make_image : color array array -> image = "caml_gr_make_image"
+(** Convert the given color matrix to an image.
+ Each sub-array represents one horizontal line. All sub-arrays
+ must have the same length; otherwise, exception [Graphic_failure]
+ is raised. *)
+
+external dump_image : image -> color array array = "caml_gr_dump_image"
+(** Convert an image to a color matrix. *)
+
+external draw_image : image -> int -> int -> unit = "caml_gr_draw_image"
+(** Draw the given image with lower left corner at the given point. *)
+
+val get_image : int -> int -> int -> int -> image
+(** Capture the contents of a rectangle on the screen as an image.
+ The parameters are the same as for {!Graphics.fill_rect}. *)
+
+external create_image : int -> int -> image = "caml_gr_create_image"
+(** [create_image w h] returns a new image [w] pixels wide and [h]
+ pixels tall, to be used in conjunction with [blit_image].
+ The initial image contents are random, except that no point
+ is transparent. *)
+
+external blit_image : image -> int -> int -> unit = "caml_gr_blit_image"
+(** [blit_image img x y] copies screen pixels into the image [img],
+ modifying [img] in-place. The pixels copied are those inside the
+ rectangle with lower left corner at [x,y], and width and height
+ equal to those of the image. Pixels that were transparent in
+ [img] are left unchanged. *)
+
+
+(** {6 Mouse and keyboard events} *)
+
+type status =
+ { mouse_x : int; (** X coordinate of the mouse *)
+ mouse_y : int; (** Y coordinate of the mouse *)
+ button : bool; (** true if a mouse button is pressed *)
+ keypressed : bool; (** true if a key has been pressed *)
+ key : char; (** the character for the key pressed *)
+ }
+(** To report events. *)
+
+
+type event =
+ Button_down (** A mouse button is pressed *)
+ | Button_up (** A mouse button is released *)
+ | Key_pressed (** A key is pressed *)
+ | Mouse_motion (** The mouse is moved *)
+ | Poll (** Don't wait; return immediately *)
+(** To specify events to wait for. *)
+
+
+external wait_next_event : event list -> status = "caml_gr_wait_event"
+(** Wait until one of the events specified in the given event list
+ occurs, and return the status of the mouse and keyboard at
+ that time. If [Poll] is given in the event list, return immediately
+ with the current status. If the mouse cursor is outside of the
+ graphics window, the [mouse_x] and [mouse_y] fields of the event are
+ outside the range [0..size_x()-1, 0..size_y()-1]. Keypresses
+ are queued, and dequeued one by one when the [Key_pressed]
+ event is specified. *)
+
+val loop_at_exit : event list -> (status -> unit) -> unit
+(** Loop before exiting the program, the list given as argument is the
+ list of handlers and the events on which these handlers are called.
+ To exit cleanly the loop, the handler should raise Exit. Any other
+ exception will be propagated outside of the loop.
+ @since 4.01
+*)
+
+(** {6 Mouse and keyboard polling} *)
+
+val mouse_pos : unit -> int * int
+(** Return the position of the mouse cursor, relative to the
+ graphics window. If the mouse cursor is outside of the graphics
+ window, [mouse_pos()] returns a point outside of the range
+ [0..size_x()-1, 0..size_y()-1]. *)
+
+val button_down : unit -> bool
+(** Return [true] if the mouse button is pressed, [false] otherwise. *)
+
+val read_key : unit -> char
+(** Wait for a key to be pressed, and return the corresponding
+ character. Keypresses are queued. *)
+
+val key_pressed : unit -> bool
+(** Return [true] if a keypress is available; that is, if [read_key]
+ would not block. *)
+
+
+(** {6 Sound} *)
+
+external sound : int -> int -> unit = "caml_gr_sound"
+(** [sound freq dur] plays a sound at frequency [freq] (in hertz)
+ for a duration [dur] (in milliseconds). *)
+
+(** {6 Double buffering} *)
+
+val auto_synchronize : bool -> unit
+(** By default, drawing takes place both on the window displayed
+ on screen, and in a memory area (the 'backing store').
+ The backing store image is used to re-paint the on-screen
+ window when necessary.
+
+ To avoid flicker during animations, it is possible to turn
+ off on-screen drawing, perform a number of drawing operations
+ in the backing store only, then refresh the on-screen window
+ explicitly.
+
+ [auto_synchronize false] turns on-screen drawing off. All
+ subsequent drawing commands are performed on the backing store
+ only.
+
+ [auto_synchronize true] refreshes the on-screen window from
+ the backing store (as per [synchronize]), then turns on-screen
+ drawing back on. All subsequent drawing commands are performed
+ both on screen and in the backing store.
+
+ The default drawing mode corresponds to [auto_synchronize true]. *)
+
+external synchronize : unit -> unit = "caml_gr_synchronize"
+(** Synchronize the backing store and the on-screen window, by
+ copying the contents of the backing store onto the graphics
+ window. *)
+
+
+external display_mode : bool -> unit = "caml_gr_display_mode"
+(** Set display mode on or off. When turned on, drawings are done
+ in the graphics window; when turned off, drawings do not affect
+ the graphics window. This occurs independently of
+ drawing into the backing store (see the function {!Graphics.remember_mode}
+ below). Default display mode is on. *)
+
+
+external remember_mode : bool -> unit = "caml_gr_remember_mode"
+(** Set remember mode on or off. When turned on, drawings are done
+ in the backing store; when turned off, the backing store is
+ unaffected by drawings. This occurs independently of drawing
+ onto the graphics window (see the function {!Graphics.display_mode} above).
+ Default remember mode is on. *)
diff --git a/otherlibs/graph/graphics.mllib b/otherlibs/graph/graphics.mllib
new file mode 100644
index 0000000000..d5e8f9ebe8
--- /dev/null
+++ b/otherlibs/graph/graphics.mllib
@@ -0,0 +1 @@
+Graphics GraphicsX11
diff --git a/otherlibs/graph/graphicsX11.ml b/otherlibs/graph/graphicsX11.ml
new file mode 100644
index 0000000000..33ef1bc97c
--- /dev/null
+++ b/otherlibs/graph/graphicsX11.ml
@@ -0,0 +1,40 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis and Jun Furuse, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [GraphicsX11]: additional graphics primitives for
+ the X Windows system *)
+
+type window_id = string
+
+external window_id : unit -> window_id = "caml_gr_window_id"
+
+let subwindows = Hashtbl.create 13
+
+external open_subwindow : int -> int -> int -> int -> window_id
+ = "caml_gr_open_subwindow"
+external close_subwindow : window_id -> unit
+ = "caml_gr_close_subwindow"
+
+let open_subwindow ~x ~y ~width ~height =
+ let wid = open_subwindow x y width height in
+ Hashtbl.add subwindows wid ();
+ wid
+;;
+
+let close_subwindow wid =
+ if Hashtbl.mem subwindows wid then begin
+ close_subwindow wid;
+ Hashtbl.remove subwindows wid
+ end else
+ raise (Graphics.Graphic_failure("close_subwindow: no such subwindow: "^wid))
+;;
diff --git a/otherlibs/graph/graphicsX11.mli b/otherlibs/graph/graphicsX11.mli
new file mode 100644
index 0000000000..918f9d5095
--- /dev/null
+++ b/otherlibs/graph/graphicsX11.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis and Jun Furuse, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Additional graphics primitives for the X Windows system. *)
+
+type window_id = string
+
+val window_id : unit -> window_id
+(** Return the unique identifier of the OCaml graphics window.
+ The returned string is an unsigned 32 bits integer
+ in decimal form. *)
+
+val open_subwindow : x:int -> y:int -> width:int -> height:int -> window_id
+(** Create a sub-window of the current OCaml graphics window
+ and return its identifier. *)
+
+val close_subwindow : window_id -> unit
+(** Close the sub-window having the given identifier. *)
diff --git a/otherlibs/graph/image.c b/otherlibs/graph/image.c
new file mode 100644
index 0000000000..12588bf71c
--- /dev/null
+++ b/otherlibs/graph/image.c
@@ -0,0 +1,106 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+#include "image.h"
+#include <caml/alloc.h>
+#include <caml/custom.h>
+
+static void caml_gr_free_image(value im)
+{
+ XFreePixmap(caml_gr_display, Data_im(im));
+ if (Mask_im(im) != None) XFreePixmap(caml_gr_display, Mask_im(im));
+}
+
+static struct custom_operations image_ops = {
+ "_image",
+ caml_gr_free_image,
+ custom_compare_default,
+ custom_hash_default,
+ custom_serialize_default,
+ custom_deserialize_default,
+ custom_compare_ext_default
+};
+
+#define Max_image_mem 2000000
+
+value caml_gr_new_image(int w, int h)
+{
+ value res = alloc_custom(&image_ops, sizeof(struct grimage),
+ w * h, Max_image_mem);
+ Width_im(res) = w;
+ Height_im(res) = h;
+ Data_im(res) = XCreatePixmap(caml_gr_display, caml_gr_window.win, w, h,
+ XDefaultDepth(caml_gr_display, caml_gr_screen));
+ Mask_im(res) = None;
+ return res;
+}
+
+value caml_gr_create_image(value vw, value vh)
+{
+ caml_gr_check_open();
+ return caml_gr_new_image(Int_val(vw), Int_val(vh));
+}
+
+value caml_gr_blit_image(value im, value vx, value vy)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ caml_gr_check_open();
+ XCopyArea(caml_gr_display, caml_gr_bstore.win, Data_im(im), caml_gr_bstore.gc,
+ x, Bcvt(y) + 1 - Height_im(im),
+ Width_im(im), Height_im(im),
+ 0, 0);
+ return Val_unit;
+}
+
+value caml_gr_draw_image(value im, value vx, value vy)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ int wy = Wcvt(y) + 1 - Height_im(im);
+ int by = Bcvt(y) + 1 - Height_im(im);
+
+ caml_gr_check_open();
+ if (Mask_im(im) != None) {
+ if(caml_gr_remember_modeflag) {
+ XSetClipOrigin(caml_gr_display, caml_gr_bstore.gc, x, by);
+ XSetClipMask(caml_gr_display, caml_gr_bstore.gc, Mask_im(im));
+ }
+ if(caml_gr_display_modeflag) {
+ XSetClipOrigin(caml_gr_display, caml_gr_window.gc, x, wy);
+ XSetClipMask(caml_gr_display, caml_gr_window.gc, Mask_im(im));
+ }
+ }
+ if(caml_gr_remember_modeflag)
+ XCopyArea(caml_gr_display, Data_im(im), caml_gr_bstore.win,
+ caml_gr_bstore.gc,
+ 0, 0,
+ Width_im(im), Height_im(im),
+ x, by);
+ if(caml_gr_display_modeflag)
+ XCopyArea(caml_gr_display, Data_im(im), caml_gr_window.win,
+ caml_gr_window.gc,
+ 0, 0,
+ Width_im(im), Height_im(im),
+ x, wy);
+ if (Mask_im(im) != None) {
+ if(caml_gr_remember_modeflag)
+ XSetClipMask(caml_gr_display, caml_gr_bstore.gc, None);
+ if(caml_gr_display_modeflag)
+ XSetClipMask(caml_gr_display, caml_gr_window.gc, None);
+ }
+ if(caml_gr_display_modeflag)
+ XFlush(caml_gr_display);
+ return Val_unit;
+}
diff --git a/otherlibs/graph/image.h b/otherlibs/graph/image.h
new file mode 100644
index 0000000000..806f1fd2e1
--- /dev/null
+++ b/otherlibs/graph/image.h
@@ -0,0 +1,27 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+struct grimage {
+ int width, height; /* Dimensions of the image */
+ Pixmap data; /* Pixels */
+ Pixmap mask; /* Mask for transparent points, or None */
+};
+
+#define Width_im(i) (((struct grimage *)Data_custom_val(i))->width)
+#define Height_im(i) (((struct grimage *)Data_custom_val(i))->height)
+#define Data_im(i) (((struct grimage *)Data_custom_val(i))->data)
+#define Mask_im(i) (((struct grimage *)Data_custom_val(i))->mask)
+
+#define Transparent (-1)
+
+value caml_gr_new_image(int w, int h);
diff --git a/otherlibs/graph/libgraph.h b/otherlibs/graph/libgraph.h
new file mode 100644
index 0000000000..366293859f
--- /dev/null
+++ b/otherlibs/graph/libgraph.h
@@ -0,0 +1,87 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+#include <caml/mlvalues.h>
+#include <caml/misc.h>
+
+struct canvas {
+ int w, h; /* Dimensions of the drawable */
+ Drawable win; /* The drawable itself */
+ GC gc; /* The associated graphics context */
+};
+
+extern Display * caml_gr_display; /* The display connection */
+extern int caml_gr_screen; /* The screen number */
+extern Colormap caml_gr_colormap; /* The color map */
+extern struct canvas caml_gr_window; /* The graphics window */
+extern struct canvas caml_gr_bstore; /* The pixmap used for backing store */
+extern int caml_gr_white, caml_gr_black; /* Black and white pixels for X */
+extern int caml_gr_background; /* Background color for X
+ (used for CAML color -1) */
+extern Bool caml_gr_display_modeflag; /* Display-mode flag */
+extern Bool caml_gr_remember_modeflag; /* Remember-mode flag */
+extern int caml_gr_x, caml_gr_y; /* Coordinates of the current point */
+extern int caml_gr_color; /* Current *CAML* drawing color (can be -1) */
+extern XFontStruct * caml_gr_font; /* Current font */
+extern long caml_gr_selected_events; /* Events we are interested in */
+extern Bool caml_gr_ignore_sigio; /* Whether to consume events on sigio */
+
+extern Bool caml_gr_direct_rgb;
+extern int caml_gr_byte_order;
+extern int caml_gr_bitmap_unit;
+extern int caml_gr_bits_per_pixel;
+
+#define Wcvt(y) (caml_gr_window.h - 1 - (y))
+#define Bcvt(y) (caml_gr_bstore.h - 1 - (y))
+#define WtoB(y) ((y) + caml_gr_bstore.h - caml_gr_window.h)
+#define BtoW(y) ((y) + caml_gr_window.h - caml_gr_bstore.h)
+#define min(a,b) ((a) < (b) ? (a) : (b))
+#define max(a,b) ((a) > (b) ? (a) : (b))
+
+#define DEFAULT_SCREEN_WIDTH 600
+#define DEFAULT_SCREEN_HEIGHT 450
+#define BORDER_WIDTH 2
+#define DEFAULT_WINDOW_NAME "OCaml graphics"
+#define DEFAULT_SELECTED_EVENTS \
+ (ExposureMask | KeyPressMask | StructureNotifyMask)
+#define DEFAULT_FONT "fixed"
+#define SIZE_QUEUE 256
+
+/* To handle events asynchronously */
+#ifdef HAS_ASYNC_IO
+#define USE_ASYNC_IO
+#define EVENT_SIGNAL SIGIO
+#else
+#ifdef HAS_SETITIMER
+#define USE_INTERVAL_TIMER
+#define EVENT_SIGNAL SIGALRM
+#else
+#define USE_ALARM
+#define EVENT_SIGNAL SIGALRM
+#endif
+#endif
+
+CAMLnoreturn_start
+extern void caml_gr_fail(char *fmt, char *arg)
+CAMLnoreturn_end;
+
+extern void caml_gr_check_open(void);
+extern unsigned long caml_gr_pixel_rgb(int rgb);
+extern int caml_gr_rgb_pixel(long unsigned int pixel);
+extern void caml_gr_handle_event(XEvent *e);
+extern void caml_gr_init_color_cache(void);
+extern void caml_gr_init_direct_rgb_to_pixel(void);
+extern value caml_gr_id_of_window( Window w );
diff --git a/otherlibs/graph/libgraphics.clib b/otherlibs/graph/libgraphics.clib
new file mode 100644
index 0000000000..d3b5b7b693
--- /dev/null
+++ b/otherlibs/graph/libgraphics.clib
@@ -0,0 +1,3 @@
+open.o draw.o fill.o color.o text.o
+image.o make_img.o dump_img.o point_col.o sound.o events.o
+subwindow.o
diff --git a/otherlibs/graph/make_img.c b/otherlibs/graph/make_img.c
new file mode 100644
index 0000000000..b9c4bfca22
--- /dev/null
+++ b/otherlibs/graph/make_img.c
@@ -0,0 +1,97 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+#include "image.h"
+#include <caml/memory.h>
+
+value caml_gr_make_image(value m)
+{
+ int width, height;
+ value im;
+ Bool has_transp;
+ XImage * idata, * imask;
+ char * bdata, * bmask;
+ int i, j, rgb;
+ value line;
+ GC gc;
+
+ caml_gr_check_open();
+ height = Wosize_val(m);
+ if (height == 0) return caml_gr_new_image(0, 0);
+ width = Wosize_val(Field(m, 0));
+ for (i = 1; i < height; i++)
+ if (Wosize_val(Field(m, i)) != width)
+ caml_gr_fail("make_image: lines of different lengths", NULL);
+
+ /* Build an XImage for the data part of the image */
+ idata =
+ XCreateImage(caml_gr_display,
+ DefaultVisual(caml_gr_display, caml_gr_screen),
+ XDefaultDepth(caml_gr_display, caml_gr_screen),
+ ZPixmap, 0, NULL, width, height,
+ BitmapPad(caml_gr_display), 0);
+
+ bdata = (char *) caml_stat_alloc(height * idata->bytes_per_line);
+ idata->data = bdata;
+ has_transp = False;
+
+ for (i = 0; i < height; i++) {
+ line = Field(m, i);
+ for (j = 0; j < width; j++) {
+ rgb = Int_val(Field(line, j));
+ if (rgb == Transparent) { has_transp = True; rgb = 0; }
+ XPutPixel(idata, j, i, caml_gr_pixel_rgb(rgb));
+ }
+ }
+
+ /* If the matrix contains transparent points,
+ build an XImage for the mask part of the image */
+ if (has_transp) {
+ imask =
+ XCreateImage(caml_gr_display,
+ DefaultVisual(caml_gr_display, caml_gr_screen),
+ 1, ZPixmap, 0, NULL, width, height,
+ BitmapPad(caml_gr_display), 0);
+ bmask = (char *) caml_stat_alloc(height * imask->bytes_per_line);
+ imask->data = bmask;
+
+ for (i = 0; i < height; i++) {
+ line = Field(m, i);
+ for (j = 0; j < width; j++) {
+ rgb = Int_val(Field(line, j));
+ XPutPixel(imask, j, i, rgb != Transparent);
+ }
+ }
+ } else {
+ imask = NULL;
+ }
+
+ /* Allocate the image and store the XImages into the Pixmaps */
+ im = caml_gr_new_image(width, height);
+ gc = XCreateGC(caml_gr_display, Data_im(im), 0, NULL);
+ XPutImage(caml_gr_display, Data_im(im), gc, idata, 0, 0, 0, 0, width, height);
+ XDestroyImage(idata);
+ XFreeGC(caml_gr_display, gc);
+ if (has_transp) {
+ Mask_im(im) = XCreatePixmap(caml_gr_display, caml_gr_window.win, width,
+ height, 1);
+ gc = XCreateGC(caml_gr_display, Mask_im(im), 0, NULL);
+ XPutImage(caml_gr_display, Mask_im(im), gc, imask, 0, 0, 0, 0, width,
+ height);
+ XDestroyImage(imask);
+ XFreeGC(caml_gr_display, gc);
+ }
+ XFlush(caml_gr_display);
+ return im;
+}
diff --git a/otherlibs/graph/open.c b/otherlibs/graph/open.c
new file mode 100644
index 0000000000..e8d26acfa9
--- /dev/null
+++ b/otherlibs/graph/open.c
@@ -0,0 +1,398 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <fcntl.h>
+#include <signal.h>
+#include "libgraph.h"
+#include <caml/alloc.h>
+#include <caml/callback.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#ifdef HAS_SETITIMER
+#include <sys/time.h>
+#endif
+
+Display * caml_gr_display = NULL;
+int caml_gr_screen;
+Colormap caml_gr_colormap;
+int caml_gr_white, caml_gr_black, caml_gr_background;
+struct canvas caml_gr_window;
+struct canvas caml_gr_bstore;
+Bool caml_gr_display_modeflag;
+Bool caml_gr_remember_modeflag;
+int caml_gr_x, caml_gr_y;
+int caml_gr_color;
+extern XFontStruct * caml_gr_font;
+long caml_gr_selected_events;
+Bool caml_gr_ignore_sigio = False;
+static Bool caml_gr_initialized = False;
+static char * window_name = NULL;
+
+static int caml_gr_error_handler(Display *display, XErrorEvent *error);
+static int caml_gr_ioerror_handler(Display *display);
+value caml_gr_clear_graph(void);
+
+value caml_gr_open_graph(value arg)
+{
+ char display_name[256], geometry_spec[64];
+ char * p, * q;
+ XSizeHints hints;
+ int ret;
+ XEvent event;
+ int x, y, w, h;
+ XWindowAttributes attributes;
+
+ if (caml_gr_initialized) {
+ caml_gr_clear_graph();
+ } else {
+
+ /* Parse the argument */
+ for (p = String_val(arg), q = display_name; *p != 0 && *p != ' '; p++)
+ if (q < display_name + sizeof(display_name) - 1) *q++ = *p;
+ *q = 0;
+ while (*p == ' ') p++;
+ for (q = geometry_spec; *p != 0; p++)
+ if (q < geometry_spec + sizeof(geometry_spec) - 1) *q++ = *p;
+ *q = 0;
+
+ /* Open the display */
+ if (caml_gr_display == NULL) {
+ caml_gr_display = XOpenDisplay(display_name);
+ if (caml_gr_display == NULL)
+ caml_gr_fail("Cannot open display %s", XDisplayName(display_name));
+ caml_gr_screen = DefaultScreen(caml_gr_display);
+ caml_gr_black = BlackPixel(caml_gr_display, caml_gr_screen);
+ caml_gr_white = WhitePixel(caml_gr_display, caml_gr_screen);
+ caml_gr_background = caml_gr_white;
+ caml_gr_colormap = DefaultColormap(caml_gr_display, caml_gr_screen);
+ }
+
+ /* Set up the error handlers */
+ XSetErrorHandler(caml_gr_error_handler);
+ XSetIOErrorHandler(caml_gr_ioerror_handler);
+
+ /* Parse the geometry specification */
+ hints.x = 0;
+ hints.y = 0;
+ hints.width = DEFAULT_SCREEN_WIDTH;
+ hints.height = DEFAULT_SCREEN_HEIGHT;
+ hints.flags = PPosition | PSize;
+ hints.win_gravity = 0;
+
+ ret = XWMGeometry(caml_gr_display, caml_gr_screen, geometry_spec, "",
+ BORDER_WIDTH,
+ &hints, &x, &y, &w, &h, &hints.win_gravity);
+ if (ret & (XValue | YValue)) {
+ hints.x = x; hints.y = y; hints.flags |= USPosition;
+ }
+ if (ret & (WidthValue | HeightValue)) {
+ hints.width = w; hints.height = h; hints.flags |= USSize;
+ }
+
+ /* Initial drawing color is black */
+ caml_gr_color = 0; /* CAML COLOR */
+
+ /* Create the on-screen window */
+ caml_gr_window.w = hints.width;
+ caml_gr_window.h = hints.height;
+ caml_gr_window.win =
+ XCreateSimpleWindow(caml_gr_display, DefaultRootWindow(caml_gr_display),
+ hints.x, hints.y, hints.width, hints.height,
+ BORDER_WIDTH, caml_gr_black, caml_gr_background);
+ p = window_name;
+ if (p == NULL) p = DEFAULT_WINDOW_NAME;
+ /* What not use XSetWMProperties? */
+ XSetStandardProperties(caml_gr_display, caml_gr_window.win, p, p,
+ None, NULL, 0, &hints);
+ caml_gr_window.gc = XCreateGC(caml_gr_display, caml_gr_window.win, 0, NULL);
+ XSetBackground(caml_gr_display, caml_gr_window.gc, caml_gr_background);
+ XSetForeground(caml_gr_display, caml_gr_window.gc, caml_gr_black);
+
+ /* Require exposure, resize and keyboard events */
+ caml_gr_selected_events = DEFAULT_SELECTED_EVENTS;
+ XSelectInput(caml_gr_display, caml_gr_window.win, caml_gr_selected_events);
+
+ /* Map the window on the screen and wait for the first Expose event */
+ XMapWindow(caml_gr_display, caml_gr_window.win);
+ do { XNextEvent(caml_gr_display, &event); } while (event.type != Expose);
+
+ /* Get the actual window dimensions */
+ XGetWindowAttributes(caml_gr_display, caml_gr_window.win, &attributes);
+ caml_gr_window.w = attributes.width;
+ caml_gr_window.h = attributes.height;
+
+ /* Create the pixmap used for backing store */
+ caml_gr_bstore.w = caml_gr_window.w;
+ caml_gr_bstore.h = caml_gr_window.h;
+ caml_gr_bstore.win =
+ XCreatePixmap(caml_gr_display, caml_gr_window.win, caml_gr_bstore.w,
+ caml_gr_bstore.h,
+ XDefaultDepth(caml_gr_display, caml_gr_screen));
+ caml_gr_bstore.gc = XCreateGC(caml_gr_display, caml_gr_bstore.win, 0, NULL);
+ XSetBackground(caml_gr_display, caml_gr_bstore.gc, caml_gr_background);
+
+ /* Clear the pixmap */
+ XSetForeground(caml_gr_display, caml_gr_bstore.gc, caml_gr_background);
+ XFillRectangle(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
+ 0, 0, caml_gr_bstore.w, caml_gr_bstore.h);
+ XSetForeground(caml_gr_display, caml_gr_bstore.gc, caml_gr_black);
+
+ /* Set the display and remember modes on */
+ caml_gr_display_modeflag = True ;
+ caml_gr_remember_modeflag = True ;
+
+ /* The global data structures are now correctly initialized.
+ In particular, caml_gr_sigio_handler can now handle events safely. */
+ caml_gr_initialized = True;
+
+ /* If possible, request that system calls be restarted after
+ the EVENT_SIGNAL signal. */
+#ifdef POSIX_SIGNALS
+#ifdef SA_RESTART
+ { struct sigaction action;
+ sigaction(EVENT_SIGNAL, NULL, &action);
+ action.sa_flags |= SA_RESTART;
+ sigaction(EVENT_SIGNAL, &action, NULL);
+ }
+#endif
+#endif
+
+#ifdef USE_ASYNC_IO
+ /* If BSD-style asynchronous I/O are supported:
+ arrange for I/O on the connection to trigger the SIGIO signal */
+ ret = fcntl(ConnectionNumber(caml_gr_display), F_GETFL, 0);
+ fcntl(ConnectionNumber(caml_gr_display), F_SETFL, ret | FASYNC);
+ fcntl(ConnectionNumber(caml_gr_display), F_SETOWN, getpid());
+#endif
+ }
+#ifdef USE_INTERVAL_TIMER
+ /* If BSD-style interval timers are provided, use the real-time timer
+ to poll events. */
+ { struct itimerval it;
+ it.it_interval.tv_sec = 0;
+ it.it_interval.tv_usec = 250000;
+ it.it_value.tv_sec = 0;
+ it.it_value.tv_usec = 250000;
+ setitimer(ITIMER_REAL, &it, NULL);
+ }
+#endif
+#ifdef USE_ALARM
+ /* The poor man's solution: use alarm to poll events. */
+ alarm(1);
+#endif
+ /* Position the current point at origin */
+ caml_gr_x = 0;
+ caml_gr_y = 0;
+ /* Reset the color cache */
+ caml_gr_init_color_cache();
+ caml_gr_init_direct_rgb_to_pixel();
+ return Val_unit;
+}
+
+value caml_gr_close_graph(void)
+{
+ if (caml_gr_initialized) {
+#ifdef USE_INTERVAL_TIMER
+ struct itimerval it;
+ it.it_value.tv_sec = 0;
+ it.it_value.tv_usec = 0;
+ setitimer(ITIMER_REAL, &it, NULL);
+#endif
+ caml_gr_initialized = False;
+ if (caml_gr_font != NULL) {
+ XFreeFont(caml_gr_display, caml_gr_font); caml_gr_font = NULL;
+ }
+ XFreeGC(caml_gr_display, caml_gr_window.gc);
+ XDestroyWindow(caml_gr_display, caml_gr_window.win);
+ XFreeGC(caml_gr_display, caml_gr_bstore.gc);
+ XFreePixmap(caml_gr_display, caml_gr_bstore.win);
+ XFlush(caml_gr_display);
+ XCloseDisplay (caml_gr_display);
+ caml_gr_display = NULL;
+ }
+ return Val_unit;
+}
+
+value caml_gr_id_of_window(Window win)
+{
+ char tmp[256];
+
+ sprintf(tmp, "%lu", (unsigned long)win);
+ return copy_string( tmp );
+}
+
+value caml_gr_window_id(void)
+{
+ caml_gr_check_open();
+ return caml_gr_id_of_window(caml_gr_window.win);
+}
+
+value caml_gr_set_window_title(value n)
+{
+ if (window_name != NULL) stat_free(window_name);
+ window_name = caml_strdup(String_val(n));
+ if (caml_gr_initialized) {
+ XStoreName(caml_gr_display, caml_gr_window.win, window_name);
+ XSetIconName(caml_gr_display, caml_gr_window.win, window_name);
+ XFlush(caml_gr_display);
+ }
+ return Val_unit;
+}
+
+value caml_gr_resize_window (value vx, value vy)
+{
+ caml_gr_check_open ();
+
+ caml_gr_window.w = Int_val (vx);
+ caml_gr_window.h = Int_val (vy);
+ XResizeWindow (caml_gr_display, caml_gr_window.win, caml_gr_window.w,
+ caml_gr_window.h);
+
+ XFreeGC(caml_gr_display, caml_gr_bstore.gc);
+ XFreePixmap(caml_gr_display, caml_gr_bstore.win);
+
+ caml_gr_bstore.w = caml_gr_window.w;
+ caml_gr_bstore.h = caml_gr_window.h;
+ caml_gr_bstore.win =
+ XCreatePixmap(caml_gr_display, caml_gr_window.win, caml_gr_bstore.w,
+ caml_gr_bstore.h,
+ XDefaultDepth(caml_gr_display, caml_gr_screen));
+ caml_gr_bstore.gc = XCreateGC(caml_gr_display, caml_gr_bstore.win, 0, NULL);
+ XSetBackground(caml_gr_display, caml_gr_bstore.gc, caml_gr_background);
+
+ caml_gr_clear_graph ();
+ return Val_unit;
+}
+
+value caml_gr_clear_graph(void)
+{
+ caml_gr_check_open();
+ if(caml_gr_remember_modeflag) {
+ XSetForeground(caml_gr_display, caml_gr_bstore.gc, caml_gr_white);
+ XFillRectangle(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
+ 0, 0, caml_gr_bstore.w, caml_gr_bstore.h);
+ XSetForeground(caml_gr_display, caml_gr_bstore.gc, caml_gr_color);
+ }
+ if(caml_gr_display_modeflag) {
+ XSetForeground(caml_gr_display, caml_gr_window.gc, caml_gr_white);
+ XFillRectangle(caml_gr_display, caml_gr_window.win, caml_gr_window.gc,
+ 0, 0, caml_gr_window.w, caml_gr_window.h);
+ XSetForeground(caml_gr_display, caml_gr_window.gc, caml_gr_color);
+ XFlush(caml_gr_display);
+ }
+ caml_gr_init_color_cache();
+ caml_gr_init_direct_rgb_to_pixel();
+ return Val_unit;
+}
+
+value caml_gr_size_x(void)
+{
+ caml_gr_check_open();
+ return Val_int(caml_gr_window.w);
+}
+
+value caml_gr_size_y(void)
+{
+ caml_gr_check_open();
+ return Val_int(caml_gr_window.h);
+}
+
+value caml_gr_synchronize(void)
+{
+ caml_gr_check_open();
+ XCopyArea(caml_gr_display, caml_gr_bstore.win, caml_gr_window.win,
+ caml_gr_window.gc,
+ 0, caml_gr_bstore.h - caml_gr_window.h,
+ caml_gr_window.w, caml_gr_window.h,
+ 0, 0);
+ XFlush(caml_gr_display);
+ return Val_unit ;
+}
+
+value caml_gr_display_mode(value flag)
+{
+ caml_gr_display_modeflag = Bool_val (flag);
+ return Val_unit ;
+}
+
+value caml_gr_remember_mode(value flag)
+{
+ caml_gr_remember_modeflag = Bool_val(flag);
+ return Val_unit ;
+}
+
+/* The caml_gr_sigio_handler is called via the signal machinery in the bytecode
+ interpreter. The signal system ensures that this function will be
+ called either between two bytecode instructions, or during a blocking
+ primitive. In either case, not in the middle of an Xlib call. */
+
+value caml_gr_sigio_signal(value unit)
+{
+ return Val_int(EVENT_SIGNAL);
+}
+
+value caml_gr_sigio_handler(void)
+{
+ XEvent grevent;
+
+ if (caml_gr_initialized && !caml_gr_ignore_sigio) {
+ while (XCheckMaskEvent(caml_gr_display, -1 /*all events*/, &grevent)) {
+ caml_gr_handle_event(&grevent);
+ }
+ }
+#ifdef USE_ALARM
+ alarm(1);
+#endif
+ return Val_unit;
+}
+
+/* Processing of graphic errors */
+
+static value * graphic_failure_exn = NULL;
+
+void caml_gr_fail(char *fmt, char *arg)
+{
+ char buffer[1024];
+
+ if (graphic_failure_exn == NULL) {
+ graphic_failure_exn = caml_named_value("Graphics.Graphic_failure");
+ if (graphic_failure_exn == NULL)
+ invalid_argument("Exception Graphics.Graphic_failure not initialized,"
+ " must link graphics.cma");
+ }
+ sprintf(buffer, fmt, arg);
+ raise_with_string(*graphic_failure_exn, buffer);
+}
+
+void caml_gr_check_open(void)
+{
+ if (!caml_gr_initialized) caml_gr_fail("graphic screen not opened", NULL);
+}
+
+static int caml_gr_error_handler(Display *display, XErrorEvent *error)
+{
+ char errmsg[512];
+ XGetErrorText(error->display, error->error_code, errmsg, sizeof(errmsg));
+ caml_gr_fail("Xlib error: %s", errmsg);
+ return 0;
+}
+
+static int caml_gr_ioerror_handler(Display *display)
+{
+ caml_gr_fail("fatal I/O error", NULL);
+ return 0;
+}
diff --git a/otherlibs/graph/point_col.c b/otherlibs/graph/point_col.c
new file mode 100644
index 0000000000..da1e879986
--- /dev/null
+++ b/otherlibs/graph/point_col.c
@@ -0,0 +1,29 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+
+value caml_gr_point_color(value vx, value vy)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ XImage * im;
+ int rgb;
+
+ caml_gr_check_open();
+ im = XGetImage(caml_gr_display, caml_gr_bstore.win, x, Bcvt(y), 1, 1, (-1),
+ ZPixmap);
+ rgb = caml_gr_rgb_pixel(XGetPixel(im, 0, 0));
+ XDestroyImage(im);
+ return Val_int(rgb);
+}
diff --git a/otherlibs/graph/sound.c b/otherlibs/graph/sound.c
new file mode 100644
index 0000000000..4ce1101069
--- /dev/null
+++ b/otherlibs/graph/sound.c
@@ -0,0 +1,32 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+
+value caml_gr_sound(value vfreq, value vdur)
+{
+ XKeyboardControl kbdcontrol;
+
+ caml_gr_check_open();
+ kbdcontrol.bell_pitch = Int_val(vfreq);
+ kbdcontrol.bell_duration = Int_val(vdur);
+ XChangeKeyboardControl(caml_gr_display, KBBellPitch | KBBellDuration,
+ &kbdcontrol);
+ XBell(caml_gr_display, 0);
+ kbdcontrol.bell_pitch = -1; /* restore default value */
+ kbdcontrol.bell_duration = -1; /* restore default value */
+ XChangeKeyboardControl(caml_gr_display, KBBellPitch | KBBellDuration,
+ &kbdcontrol);
+ XFlush(caml_gr_display);
+ return Val_unit;
+}
diff --git a/otherlibs/graph/subwindow.c b/otherlibs/graph/subwindow.c
new file mode 100644
index 0000000000..952dccb88c
--- /dev/null
+++ b/otherlibs/graph/subwindow.c
@@ -0,0 +1,43 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Jun Furuse, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+
+value caml_gr_open_subwindow(value vx, value vy, value width, value height)
+{
+ Window win;
+
+ int h = Int_val(height);
+ int w = Int_val(width);
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+
+ caml_gr_check_open();
+ win = XCreateSimpleWindow(caml_gr_display, caml_gr_window.win,
+ x, Wcvt(y + h), w, h,
+ 0, caml_gr_black, caml_gr_background);
+ XMapWindow(caml_gr_display, win);
+ XFlush(caml_gr_display);
+ return (caml_gr_id_of_window (win));
+}
+
+value caml_gr_close_subwindow(value wid)
+{
+ Window win;
+
+ caml_gr_check_open();
+ sscanf( String_val(wid), "%lu", (unsigned long *)(&win) );
+ XDestroyWindow(caml_gr_display, win);
+ XFlush(caml_gr_display);
+ return Val_unit;
+}
diff --git a/otherlibs/graph/text.c b/otherlibs/graph/text.c
new file mode 100644
index 0000000000..7450df89d7
--- /dev/null
+++ b/otherlibs/graph/text.c
@@ -0,0 +1,84 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "libgraph.h"
+#include <caml/alloc.h>
+
+XFontStruct * caml_gr_font = NULL;
+
+static void caml_gr_get_font(char *fontname)
+{
+ XFontStruct * font = XLoadQueryFont(caml_gr_display, fontname);
+ if (font == NULL) caml_gr_fail("cannot find font %s", fontname);
+ if (caml_gr_font != NULL) XFreeFont(caml_gr_display, caml_gr_font);
+ caml_gr_font = font;
+ XSetFont(caml_gr_display, caml_gr_window.gc, caml_gr_font->fid);
+ XSetFont(caml_gr_display, caml_gr_bstore.gc, caml_gr_font->fid);
+}
+
+value caml_gr_set_font(value fontname)
+{
+ caml_gr_check_open();
+ caml_gr_get_font(String_val(fontname));
+ return Val_unit;
+}
+
+value caml_gr_set_text_size (value sz)
+{
+ return Val_unit;
+}
+
+static void caml_gr_draw_text(char *txt, int len)
+{
+ if (caml_gr_font == NULL) caml_gr_get_font(DEFAULT_FONT);
+ if (caml_gr_remember_modeflag)
+ XDrawString(caml_gr_display, caml_gr_bstore.win, caml_gr_bstore.gc,
+ caml_gr_x, Bcvt(caml_gr_y) - caml_gr_font->descent + 1, txt,
+ len);
+ if (caml_gr_display_modeflag) {
+ XDrawString(caml_gr_display, caml_gr_window.win, caml_gr_window.gc,
+ caml_gr_x, Wcvt(caml_gr_y) - caml_gr_font->descent + 1, txt,
+ len);
+ XFlush(caml_gr_display);
+ }
+ caml_gr_x += XTextWidth(caml_gr_font, txt, len);
+}
+
+value caml_gr_draw_char(value chr)
+{
+ char str[1];
+ caml_gr_check_open();
+ str[0] = Int_val(chr);
+ caml_gr_draw_text(str, 1);
+ return Val_unit;
+}
+
+value caml_gr_draw_string(value str)
+{
+ caml_gr_check_open();
+ caml_gr_draw_text(String_val(str), string_length(str));
+ return Val_unit;
+}
+
+value caml_gr_text_size(value str)
+{
+ int width;
+ value res;
+ caml_gr_check_open();
+ if (caml_gr_font == NULL) caml_gr_get_font(DEFAULT_FONT);
+ width = XTextWidth(caml_gr_font, String_val(str), string_length(str));
+ res = alloc_small(2, 0);
+ Field(res, 0) = Val_int(width);
+ Field(res, 1) = Val_int(caml_gr_font->ascent + caml_gr_font->descent);
+ return res;
+}
diff --git a/otherlibs/num/.depend b/otherlibs/num/.depend
new file mode 100644
index 0000000000..c885abf051
--- /dev/null
+++ b/otherlibs/num/.depend
@@ -0,0 +1,41 @@
+bng_amd64.o: bng_amd64.c
+bng_arm64.o: bng_arm64.c
+bng.o: bng.c bng.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/compatibility.h bng_amd64.c bng_digit.c
+bng_digit.o: bng_digit.c
+bng_ia32.o: bng_ia32.c
+bng_ppc.o: bng_ppc.c
+bng_sparc.o: bng_sparc.c
+nat_stubs.o: nat_stubs.c ../../byterun/caml/alloc.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/config.h ../../byterun/caml/custom.h \
+ ../../byterun/caml/intext.h ../../byterun/caml/io.h \
+ ../../byterun/caml/fail.h ../../byterun/caml/hash.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/mlvalues.h bng.h nat.h
+arith_flags.cmi :
+arith_status.cmi :
+big_int.cmi : nat.cmi
+int_misc.cmi :
+nat.cmi :
+num.cmi : ratio.cmi nat.cmi big_int.cmi
+ratio.cmi : nat.cmi big_int.cmi
+arith_flags.cmo : arith_flags.cmi
+arith_flags.cmx : arith_flags.cmi
+arith_status.cmo : arith_flags.cmi arith_status.cmi
+arith_status.cmx : arith_flags.cmx arith_status.cmi
+big_int.cmo : nat.cmi int_misc.cmi big_int.cmi
+big_int.cmx : nat.cmx int_misc.cmx big_int.cmi
+int_misc.cmo : int_misc.cmi
+int_misc.cmx : int_misc.cmi
+nat.cmo : int_misc.cmi nat.cmi
+nat.cmx : int_misc.cmx nat.cmi
+num.cmo : ratio.cmi nat.cmi int_misc.cmi big_int.cmi arith_flags.cmi num.cmi
+num.cmx : ratio.cmx nat.cmx int_misc.cmx big_int.cmx arith_flags.cmx num.cmi
+ratio.cmo : nat.cmi int_misc.cmi big_int.cmi arith_flags.cmi ratio.cmi
+ratio.cmx : nat.cmx int_misc.cmx big_int.cmx arith_flags.cmx ratio.cmi
diff --git a/otherlibs/num/.depend.nt b/otherlibs/num/.depend.nt
new file mode 100644
index 0000000000..a22644bab0
--- /dev/null
+++ b/otherlibs/num/.depend.nt
@@ -0,0 +1,66 @@
+bng.dobj: bng.c bng.h ../../byterun/config.h ../../config/m.h \
+ ../../config/s.h ../../byterun/compatibility.h bng_ppc.c bng_digit.c
+bng_alpha.dobj: bng_alpha.c
+bng_amd64.dobj: bng_amd64.c
+bng_digit.dobj: bng_digit.c
+bng_ia32.dobj: bng_ia32.c
+bng_mips.dobj: bng_mips.c
+bng_ppc.dobj: bng_ppc.c
+bng_sparc.dobj: bng_sparc.c
+nat_stubs.dobj: nat_stubs.c ../../byterun/alloc.h \
+ ../../byterun/compatibility.h ../../byterun/misc.h \
+ ../../byterun/config.h ../../config/m.h ../../config/s.h \
+ ../../byterun/mlvalues.h ../../byterun/custom.h ../../byterun/intext.h \
+ ../../byterun/io.h ../../byterun/fix_code.h ../../byterun/fail.h \
+ ../../byterun/memory.h ../../byterun/gc.h ../../byterun/major_gc.h \
+ ../../byterun/freelist.h ../../byterun/minor_gc.h bng.h nat.h
+big_int.cmi: nat.cmi
+num.cmi: ratio.cmi nat.cmi big_int.cmi
+ratio.cmi: nat.cmi big_int.cmi
+arith_flags.cmo: arith_flags.cmi
+arith_flags.cmx: arith_flags.cmi
+arith_status.cmo: arith_flags.cmi arith_status.cmi
+arith_status.cmx: arith_flags.cmx arith_status.cmi
+big_int.cmo: nat.cmi int_misc.cmi big_int.cmi
+big_int.cmx: nat.cmx int_misc.cmx big_int.cmi
+int_misc.cmo: int_misc.cmi
+int_misc.cmx: int_misc.cmi
+nat.cmo: int_misc.cmi nat.cmi
+nat.cmx: int_misc.cmx nat.cmi
+num.cmo: ratio.cmi nat.cmi int_misc.cmi big_int.cmi arith_flags.cmi num.cmi
+num.cmx: ratio.cmx nat.cmx int_misc.cmx big_int.cmx arith_flags.cmx num.cmi
+ratio.cmo: nat.cmi int_misc.cmi big_int.cmi arith_flags.cmi ratio.cmi
+ratio.cmx: nat.cmx int_misc.cmx big_int.cmx arith_flags.cmx ratio.cmi
+bng.sobj: bng.c bng.h ../../byterun/config.h ../../config/m.h \
+ ../../config/s.h ../../byterun/compatibility.h bng_ppc.c bng_digit.c
+bng_alpha.sobj: bng_alpha.c
+bng_amd64.sobj: bng_amd64.c
+bng_digit.sobj: bng_digit.c
+bng_ia32.sobj: bng_ia32.c
+bng_mips.sobj: bng_mips.c
+bng_ppc.sobj: bng_ppc.c
+bng_sparc.sobj: bng_sparc.c
+nat_stubs.sobj: nat_stubs.c ../../byterun/alloc.h \
+ ../../byterun/compatibility.h ../../byterun/misc.h \
+ ../../byterun/config.h ../../config/m.h ../../config/s.h \
+ ../../byterun/mlvalues.h ../../byterun/custom.h ../../byterun/intext.h \
+ ../../byterun/io.h ../../byterun/fix_code.h ../../byterun/fail.h \
+ ../../byterun/memory.h ../../byterun/gc.h ../../byterun/major_gc.h \
+ ../../byterun/freelist.h ../../byterun/minor_gc.h bng.h nat.h
+big_int.cmi: nat.cmi
+num.cmi: ratio.cmi nat.cmi big_int.cmi
+ratio.cmi: nat.cmi big_int.cmi
+arith_flags.cmo: arith_flags.cmi
+arith_flags.cmx: arith_flags.cmi
+arith_status.cmo: arith_flags.cmi arith_status.cmi
+arith_status.cmx: arith_flags.cmx arith_status.cmi
+big_int.cmo: nat.cmi int_misc.cmi big_int.cmi
+big_int.cmx: nat.cmx int_misc.cmx big_int.cmi
+int_misc.cmo: int_misc.cmi
+int_misc.cmx: int_misc.cmi
+nat.cmo: int_misc.cmi nat.cmi
+nat.cmx: int_misc.cmx nat.cmi
+num.cmo: ratio.cmi nat.cmi int_misc.cmi big_int.cmi arith_flags.cmi num.cmi
+num.cmx: ratio.cmx nat.cmx int_misc.cmx big_int.cmx arith_flags.cmx num.cmi
+ratio.cmo: nat.cmi int_misc.cmi big_int.cmi arith_flags.cmi ratio.cmi
+ratio.cmx: nat.cmx int_misc.cmx big_int.cmx arith_flags.cmx ratio.cmi
diff --git a/otherlibs/num/Makefile b/otherlibs/num/Makefile
new file mode 100644
index 0000000000..e08e02943f
--- /dev/null
+++ b/otherlibs/num/Makefile
@@ -0,0 +1,37 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# $Id$
+
+# Makefile for the "num" (exact rational arithmetic) library
+
+LIBNAME=nums
+EXTRACFLAGS=-DBNG_ARCH_$(BNG_ARCH) -DBNG_ASM_LEVEL=$(BNG_ASM_LEVEL)
+CAMLOBJS=int_misc.cmo nat.cmo big_int.cmo arith_flags.cmo \
+ ratio.cmo num.cmo arith_status.cmo
+CMIFILES=big_int.cmi nat.cmi num.cmi ratio.cmi arith_status.cmi
+COBJS=bng.$(O) nat_stubs.$(O)
+
+include ../Makefile
+
+clean::
+ rm -f *~
+
+bng.$(O): bng.h bng_digit.c \
+ bng_amd64.c bng_ia32.c bng_ppc.c bng_sparc.c
+
+depend:
+ $(CC) -MM $(CFLAGS) *.c > .depend
+ $(CAMLRUN) ../../tools/ocamldep *.mli *.ml >> .depend
+
+include .depend
diff --git a/otherlibs/num/Makefile.nt b/otherlibs/num/Makefile.nt
new file mode 100644
index 0000000000..4ac69c7cad
--- /dev/null
+++ b/otherlibs/num/Makefile.nt
@@ -0,0 +1,36 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# $Id$
+
+# Makefile for the "num" (exact rational arithmetic) library
+
+LIBNAME=nums
+EXTRACFLAGS=-DBNG_ARCH_$(BNG_ARCH) -DBNG_ASM_LEVEL=$(BNG_ASM_LEVEL)
+CAMLOBJS=int_misc.cmo nat.cmo big_int.cmo arith_flags.cmo \
+ ratio.cmo num.cmo arith_status.cmo
+CMIFILES=big_int.cmi nat.cmi num.cmi ratio.cmi arith_status.cmi
+COBJS=bng.$(O) nat_stubs.$(O)
+
+include ../Makefile.nt
+
+clean::
+ rm -f *~
+
+bng.$(O): bng.h bng_digit.c \
+ bng_amd64.c bng_ia32.c bng_ppc.c bng_sparc.c
+
+depend:
+ sed -e 's/\.o/.$(O)/g' .depend > .depend.nt
+
+include .depend.nt
diff --git a/otherlibs/num/README b/otherlibs/num/README
new file mode 100644
index 0000000000..a979356d2b
--- /dev/null
+++ b/otherlibs/num/README
@@ -0,0 +1,55 @@
+The "libnum" library implements exact-precision arithmetic on
+big integers and on rationals.
+
+This library is derived from Valerie Menissie-Morain's implementation
+of rational arithmetic for Caml V3.1 (INRIA). Xavier Leroy (INRIA)
+did the Caml Light port. Victor Manuel Gulias Fernandez did the
+initial Caml Special Light port. Pierre Weis did most of the
+maintenance and bug fixing.
+
+Initially, the low-level big integer operations were provided by the
+BigNum package developed by Bernard Serpette, Jean Vuillemin and
+Jean-Claude Herve (INRIA and Digital PRL). License issues forced us to
+replace the BigNum package. The current implementation of low-level
+big integer operations is due to Xavier Leroy.
+
+This library is documented in "The CAML Numbers Reference Manual" by
+Valerie Menissier-Morain, technical report 141, INRIA, july 1992,
+available at ftp://ftp.inria.fr/INRIA/publication/RT/RT-0141.ps.gz
+
+
+USAGE:
+
+To use the bignum library from your programs, just do
+
+ ocamlc <options> nums.cma <.cmo and .ml files>
+or
+ ocamlopt <options> nums.cmxa <.cmx and .ml files>
+
+for the linking phase.
+
+If you'd like to have the bignum functions available at toplevel, do
+
+ ocamlmktop -o ocamltopnum <options> nums.cma <.cmo and .ml files>
+ ./ocamltopnum
+
+As an example, try:
+
+ open Num;;
+ let rec fact n =
+ if n = 0 then Int 1 else mult_num (num_of_int n) (fact(n-1));;
+ string_of_num(fact 1000);;
+
+
+PROCESSOR-SPECIFIC OPTIMIZATIONS:
+
+When compiled with GCC, the low-level primitives use "inline extended asm"
+to exploit useful features of the target processor (additions and
+subtractions with carry; double-width multiplication, division).
+Here are the processors for which such optimizations are available:
+ IA32 (x86) (carry, dwmult, dwdiv, 64-bit ops with SSE2 if available)
+ AMD64 (Opteron) (carry, dwmult, dwdiv)
+ PowerPC (carry, dwmult)
+ Alpha (dwmult)
+ SPARC (carry, dwmult, dwdiv)
+ MIPS (dwmult)
diff --git a/otherlibs/num/arith_flags.ml b/otherlibs/num/arith_flags.ml
new file mode 100644
index 0000000000..df109ae9fb
--- /dev/null
+++ b/otherlibs/num/arith_flags.ml
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let error_when_null_denominator_flag = ref true;;
+
+let normalize_ratio_flag = ref false;;
+
+let normalize_ratio_when_printing_flag = ref true;;
+
+let floating_precision = ref 12;;
+
+let approx_printing_flag = ref false;;
diff --git a/otherlibs/num/arith_flags.mli b/otherlibs/num/arith_flags.mli
new file mode 100644
index 0000000000..791446c24b
--- /dev/null
+++ b/otherlibs/num/arith_flags.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+val error_when_null_denominator_flag : bool ref
+val normalize_ratio_flag : bool ref
+val normalize_ratio_when_printing_flag : bool ref
+val floating_precision : int ref
+val approx_printing_flag : bool ref
diff --git a/otherlibs/num/arith_status.ml b/otherlibs/num/arith_status.ml
new file mode 100644
index 0000000000..585db9d014
--- /dev/null
+++ b/otherlibs/num/arith_status.ml
@@ -0,0 +1,98 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Arith_flags;;
+
+let get_error_when_null_denominator () =
+ !error_when_null_denominator_flag
+and set_error_when_null_denominator choice =
+ error_when_null_denominator_flag := choice;;
+
+let get_normalize_ratio () = !normalize_ratio_flag
+and set_normalize_ratio choice = normalize_ratio_flag := choice;;
+
+let get_normalize_ratio_when_printing () =
+ !normalize_ratio_when_printing_flag
+and set_normalize_ratio_when_printing choice =
+ normalize_ratio_when_printing_flag := choice;;
+
+let get_floating_precision () = !floating_precision
+and set_floating_precision i = floating_precision := i;;
+
+let get_approx_printing () = !approx_printing_flag
+and set_approx_printing b = approx_printing_flag := b;;
+
+let arith_print_string s = print_string s; print_string " --> ";;
+
+let arith_print_bool = function
+ true -> print_string "ON"
+| _ -> print_string "OFF"
+;;
+
+let arith_status () =
+ print_newline ();
+
+ arith_print_string
+ "Normalization during computation";
+ arith_print_bool (get_normalize_ratio ());
+ print_newline ();
+ print_string " (returned by get_normalize_ratio ())";
+ print_newline ();
+ print_string " (modifiable with set_normalize_ratio <your choice>)";
+ print_newline ();
+ print_newline ();
+
+ arith_print_string
+ "Normalization when printing";
+ arith_print_bool (get_normalize_ratio_when_printing ());
+ print_newline ();
+ print_string
+ " (returned by get_normalize_ratio_when_printing ())";
+ print_newline ();
+ print_string
+ " (modifiable with set_normalize_ratio_when_printing <your choice>)";
+ print_newline ();
+ print_newline ();
+
+ arith_print_string
+ "Floating point approximation when printing rational numbers";
+ arith_print_bool (get_approx_printing ());
+ print_newline ();
+ print_string
+ " (returned by get_approx_printing ())";
+ print_newline ();
+ print_string
+ " (modifiable with set_approx_printing <your choice>)";
+ print_newline ();
+ (if (get_approx_printing ())
+ then (print_string " Default precision = ";
+ print_int (get_floating_precision ());
+ print_newline ();
+ print_string " (returned by get_floating_precision ())";
+ print_newline ();
+ print_string
+ " (modifiable with set_floating_precision <your choice>)";
+ print_newline ();
+ print_newline ())
+ else print_newline());
+
+ arith_print_string
+ "Error when a rational denominator is null";
+ arith_print_bool (get_error_when_null_denominator ());
+ print_newline ();
+ print_string " (returned by get_error_when_null_denominator ())";
+ print_newline ();
+ print_string
+ " (modifiable with set_error_when_null_denominator <your choice>)";
+ print_newline ()
+;;
diff --git a/otherlibs/num/arith_status.mli b/otherlibs/num/arith_status.mli
new file mode 100644
index 0000000000..cc0289daae
--- /dev/null
+++ b/otherlibs/num/arith_status.mli
@@ -0,0 +1,57 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Flags that control rational arithmetic. *)
+
+val arith_status: unit -> unit
+ (** Print the current status of the arithmetic flags. *)
+
+val get_error_when_null_denominator : unit -> bool
+ (** See {!Arith_status.set_error_when_null_denominator}.*)
+val set_error_when_null_denominator : bool -> unit
+ (** Get or set the flag [null_denominator]. When on, attempting to
+ create a rational with a null denominator raises an exception.
+ When off, rationals with null denominators are accepted.
+ Initially: on. *)
+
+val get_normalize_ratio : unit -> bool
+ (** See {!Arith_status.set_normalize_ratio}.*)
+val set_normalize_ratio : bool -> unit
+ (** Get or set the flag [normalize_ratio]. When on, rational
+ numbers are normalized after each operation. When off,
+ rational numbers are not normalized until printed.
+ Initially: off. *)
+
+val get_normalize_ratio_when_printing : unit -> bool
+ (** See {!Arith_status.set_normalize_ratio_when_printing}.*)
+val set_normalize_ratio_when_printing : bool -> unit
+ (** Get or set the flag [normalize_ratio_when_printing].
+ When on, rational numbers are normalized before being printed.
+ When off, rational numbers are printed as is, without normalization.
+ Initially: on. *)
+
+val get_approx_printing : unit -> bool
+ (** See {!Arith_status.set_approx_printing}.*)
+val set_approx_printing : bool -> unit
+ (** Get or set the flag [approx_printing].
+ When on, rational numbers are printed as a decimal approximation.
+ When off, rational numbers are printed as a fraction.
+ Initially: off. *)
+
+val get_floating_precision : unit -> int
+ (** See {!Arith_status.set_floating_precision}.*)
+val set_floating_precision : int -> unit
+ (** Get or set the parameter [floating_precision].
+ This parameter is the number of digits displayed when
+ [approx_printing] is on.
+ Initially: 12. *)
diff --git a/otherlibs/num/big_int.ml b/otherlibs/num/big_int.ml
new file mode 100644
index 0000000000..d818a9631a
--- /dev/null
+++ b/otherlibs/num/big_int.ml
@@ -0,0 +1,880 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Int_misc
+open Nat
+
+type big_int =
+ { sign : int;
+ abs_value : nat }
+
+let create_big_int sign nat =
+ if sign = 1 || sign = -1 ||
+ (sign = 0 &&
+ is_zero_nat nat 0 (num_digits_nat nat 0 (length_nat nat)))
+ then { sign = sign;
+ abs_value = nat }
+ else invalid_arg "create_big_int"
+
+(* Sign of a big_int *)
+let sign_big_int bi = bi.sign
+
+let zero_big_int =
+ { sign = 0;
+ abs_value = make_nat 1 }
+
+let unit_big_int =
+ { sign = 1;
+ abs_value = nat_of_int 1 }
+
+(* Number of digits in a big_int *)
+let num_digits_big_int bi =
+ num_digits_nat (bi.abs_value) 0 (length_nat bi.abs_value)
+
+(* Number of bits in a big_int *)
+let num_bits_big_int bi =
+ let nd = num_digits_nat (bi.abs_value) 0 (length_nat bi.abs_value) in
+ (* nd = 1 if bi = 0 *)
+ let lz = num_leading_zero_bits_in_digit bi.abs_value (nd - 1) in
+ (* lz = length_of_digit if bi = 0 *)
+ nd * length_of_digit - lz
+ (* = 0 if bi = 0 *)
+
+(* Opposite of a big_int *)
+let minus_big_int bi =
+ { sign = - bi.sign;
+ abs_value = copy_nat (bi.abs_value) 0 (num_digits_big_int bi)}
+
+(* Absolute value of a big_int *)
+let abs_big_int bi =
+ { sign = if bi.sign = 0 then 0 else 1;
+ abs_value = copy_nat (bi.abs_value) 0 (num_digits_big_int bi)}
+
+(* Comparison operators on big_int *)
+
+(*
+ compare_big_int (bi, bi2) = sign of (bi-bi2)
+ i.e. 1 if bi > bi2
+ 0 if bi = bi2
+ -1 if bi < bi2
+*)
+let compare_big_int bi1 bi2 =
+ if bi1.sign = 0 && bi2.sign = 0 then 0
+ else if bi1.sign < bi2.sign then -1
+ else if bi1.sign > bi2.sign then 1
+ else if bi1.sign = 1 then
+ compare_nat (bi1.abs_value) 0 (num_digits_big_int bi1)
+ (bi2.abs_value) 0 (num_digits_big_int bi2)
+ else
+ compare_nat (bi2.abs_value) 0 (num_digits_big_int bi2)
+ (bi1.abs_value) 0 (num_digits_big_int bi1)
+
+let eq_big_int bi1 bi2 = compare_big_int bi1 bi2 = 0
+and le_big_int bi1 bi2 = compare_big_int bi1 bi2 <= 0
+and ge_big_int bi1 bi2 = compare_big_int bi1 bi2 >= 0
+and lt_big_int bi1 bi2 = compare_big_int bi1 bi2 < 0
+and gt_big_int bi1 bi2 = compare_big_int bi1 bi2 > 0
+
+let max_big_int bi1 bi2 = if lt_big_int bi1 bi2 then bi2 else bi1
+and min_big_int bi1 bi2 = if gt_big_int bi1 bi2 then bi2 else bi1
+
+(* Operations on big_int *)
+
+let pred_big_int bi =
+ match bi.sign with
+ 0 -> { sign = -1; abs_value = nat_of_int 1}
+ | 1 -> let size_bi = num_digits_big_int bi in
+ let copy_bi = copy_nat (bi.abs_value) 0 size_bi in
+ ignore (decr_nat copy_bi 0 size_bi 0);
+ { sign = if is_zero_nat copy_bi 0 size_bi then 0 else 1;
+ abs_value = copy_bi }
+ | _ -> let size_bi = num_digits_big_int bi in
+ let size_res = succ (size_bi) in
+ let copy_bi = create_nat (size_res) in
+ blit_nat copy_bi 0 (bi.abs_value) 0 size_bi;
+ set_digit_nat copy_bi size_bi 0;
+ ignore (incr_nat copy_bi 0 size_res 1);
+ { sign = -1;
+ abs_value = copy_bi }
+
+let succ_big_int bi =
+ match bi.sign with
+ 0 -> {sign = 1; abs_value = nat_of_int 1}
+ | -1 -> let size_bi = num_digits_big_int bi in
+ let copy_bi = copy_nat (bi.abs_value) 0 size_bi in
+ ignore (decr_nat copy_bi 0 size_bi 0);
+ { sign = if is_zero_nat copy_bi 0 size_bi then 0 else -1;
+ abs_value = copy_bi }
+ | _ -> let size_bi = num_digits_big_int bi in
+ let size_res = succ (size_bi) in
+ let copy_bi = create_nat (size_res) in
+ blit_nat copy_bi 0 (bi.abs_value) 0 size_bi;
+ set_digit_nat copy_bi size_bi 0;
+ ignore (incr_nat copy_bi 0 size_res 1);
+ { sign = 1;
+ abs_value = copy_bi }
+
+let add_big_int bi1 bi2 =
+ let size_bi1 = num_digits_big_int bi1
+ and size_bi2 = num_digits_big_int bi2 in
+ if bi1.sign = bi2.sign
+ then (* Add absolute values if signs are the same *)
+ { sign = bi1.sign;
+ abs_value =
+ match compare_nat (bi1.abs_value) 0 size_bi1
+ (bi2.abs_value) 0 size_bi2 with
+ -1 -> let res = create_nat (succ size_bi2) in
+ (blit_nat res 0 (bi2.abs_value) 0 size_bi2;
+ set_digit_nat res size_bi2 0;
+ ignore
+ (add_nat res 0 (succ size_bi2)
+ (bi1.abs_value) 0 size_bi1 0);
+ res)
+ |_ -> let res = create_nat (succ size_bi1) in
+ (blit_nat res 0 (bi1.abs_value) 0 size_bi1;
+ set_digit_nat res size_bi1 0;
+ ignore (add_nat res 0 (succ size_bi1)
+ (bi2.abs_value) 0 size_bi2 0);
+ res)}
+
+ else (* Subtract absolute values if signs are different *)
+ match compare_nat (bi1.abs_value) 0 size_bi1
+ (bi2.abs_value) 0 size_bi2 with
+ 0 -> zero_big_int
+ | 1 -> { sign = bi1.sign;
+ abs_value =
+ let res = copy_nat (bi1.abs_value) 0 size_bi1 in
+ (ignore (sub_nat res 0 size_bi1
+ (bi2.abs_value) 0 size_bi2 1);
+ res) }
+ | _ -> { sign = bi2.sign;
+ abs_value =
+ let res = copy_nat (bi2.abs_value) 0 size_bi2 in
+ (ignore (sub_nat res 0 size_bi2
+ (bi1.abs_value) 0 size_bi1 1);
+ res) }
+
+(* Coercion with int type *)
+let big_int_of_int i =
+ { sign = sign_int i;
+ abs_value =
+ let res = (create_nat 1)
+ in (if i = monster_int
+ then (set_digit_nat res 0 biggest_int;
+ ignore (incr_nat res 0 1 1))
+ else set_digit_nat res 0 (abs i));
+ res }
+
+let add_int_big_int i bi = add_big_int (big_int_of_int i) bi
+
+let sub_big_int bi1 bi2 = add_big_int bi1 (minus_big_int bi2)
+
+(* Returns i * bi *)
+let mult_int_big_int i bi =
+ let size_bi = num_digits_big_int bi in
+ let size_res = succ size_bi in
+ if i = monster_int
+ then let res = create_nat size_res in
+ blit_nat res 0 (bi.abs_value) 0 size_bi;
+ set_digit_nat res size_bi 0;
+ ignore (mult_digit_nat res 0 size_res (bi.abs_value) 0 size_bi
+ (nat_of_int biggest_int) 0);
+ { sign = - (sign_big_int bi);
+ abs_value = res }
+ else let res = make_nat (size_res) in
+ ignore (mult_digit_nat res 0 size_res (bi.abs_value) 0 size_bi
+ (nat_of_int (abs i)) 0);
+ { sign = (sign_int i) * (sign_big_int bi);
+ abs_value = res }
+
+let mult_big_int bi1 bi2 =
+ let size_bi1 = num_digits_big_int bi1
+ and size_bi2 = num_digits_big_int bi2 in
+ let size_res = size_bi1 + size_bi2 in
+ let res = make_nat (size_res) in
+ { sign = bi1.sign * bi2.sign;
+ abs_value =
+ if size_bi2 > size_bi1
+ then (ignore (mult_nat res 0 size_res (bi2.abs_value) 0 size_bi2
+ (bi1.abs_value) 0 size_bi1);res)
+ else (ignore (mult_nat res 0 size_res (bi1.abs_value) 0 size_bi1
+ (bi2.abs_value) 0 size_bi2);res) }
+
+(* (quotient, rest) of the euclidian division of 2 big_int *)
+let quomod_big_int bi1 bi2 =
+ if bi2.sign = 0 then raise Division_by_zero
+ else
+ let size_bi1 = num_digits_big_int bi1
+ and size_bi2 = num_digits_big_int bi2 in
+ match compare_nat (bi1.abs_value) 0 size_bi1
+ (bi2.abs_value) 0 size_bi2 with
+ -1 -> (* 1/2 -> 0, reste 1, -1/2 -> -1, reste 1 *)
+ (* 1/-2 -> 0, reste 1, -1/-2 -> 1, reste 1 *)
+ if bi1.sign >= 0 then
+ (big_int_of_int 0, bi1)
+ else if bi2.sign >= 0 then
+ (big_int_of_int(-1), add_big_int bi2 bi1)
+ else
+ (big_int_of_int 1, sub_big_int bi1 bi2)
+ | 0 -> (big_int_of_int (bi1.sign * bi2.sign), zero_big_int)
+ | _ -> let bi1_negatif = bi1.sign = -1 in
+ let size_q =
+ if bi1_negatif
+ then succ (max (succ (size_bi1 - size_bi2)) 1)
+ else max (succ (size_bi1 - size_bi2)) 1
+ and size_r = succ (max size_bi1 size_bi2)
+ (* r is long enough to contain both quotient and remainder *)
+ (* of the euclidian division *)
+ in
+ (* set up quotient, remainder *)
+ let q = create_nat size_q
+ and r = create_nat size_r in
+ blit_nat r 0 (bi1.abs_value) 0 size_bi1;
+ set_to_zero_nat r size_bi1 (size_r - size_bi1);
+
+ (* do the division of |bi1| by |bi2|
+ - at the beginning, r contains |bi1|
+ - at the end, r contains
+ * in the size_bi2 least significant digits, the remainder
+ * in the size_r-size_bi2 most significant digits, the quotient
+ note the conditions for application of div_nat are verified here
+ *)
+ div_nat r 0 size_r (bi2.abs_value) 0 size_bi2;
+
+ (* separate quotient and remainder *)
+ blit_nat q 0 r size_bi2 (size_r - size_bi2);
+ let not_null_mod = not (is_zero_nat r 0 size_bi2) in
+
+ (* correct the signs, adjusting the quotient and remainder *)
+ if bi1_negatif && not_null_mod
+ then
+ (* bi1<0, r>0, noting r for (r, size_bi2) the remainder, *)
+ (* we have |bi1|=q * |bi2| + r with 0 < r < |bi2|, *)
+ (* thus -bi1 = q * |bi2| + r *)
+ (* and bi1 = (-q) * |bi2| + (-r) with -|bi2| < (-r) < 0 *)
+ (* thus bi1 = -(q+1) * |bi2| + (|bi2|-r) *)
+ (* with 0 < (|bi2|-r) < |bi2| *)
+ (* so the quotient has for sign the opposite of the bi2'one *)
+ (* and for value q+1 *)
+ (* and the remainder is strictly positive *)
+ (* has for value |bi2|-r *)
+ (let new_r = copy_nat (bi2.abs_value) 0 size_bi2 in
+ (* new_r contains (r, size_bi2) the remainder *)
+ { sign = - bi2.sign;
+ abs_value = (set_digit_nat q (pred size_q) 0;
+ ignore (incr_nat q 0 size_q 1); q) },
+ { sign = 1;
+ abs_value =
+ (ignore (sub_nat new_r 0 size_bi2 r 0 size_bi2 1);
+ new_r) })
+ else
+ (if bi1_negatif then set_digit_nat q (pred size_q) 0;
+ { sign = if is_zero_nat q 0 size_q
+ then 0
+ else bi1.sign * bi2.sign;
+ abs_value = q },
+ { sign = if not_null_mod then 1 else 0;
+ abs_value = copy_nat r 0 size_bi2 })
+
+let div_big_int bi1 bi2 = fst (quomod_big_int bi1 bi2)
+and mod_big_int bi1 bi2 = snd (quomod_big_int bi1 bi2)
+
+let gcd_big_int bi1 bi2 =
+ let size_bi1 = num_digits_big_int bi1
+ and size_bi2 = num_digits_big_int bi2 in
+ if is_zero_nat (bi1.abs_value) 0 size_bi1 then abs_big_int bi2
+ else if is_zero_nat (bi2.abs_value) 0 size_bi2 then
+ { sign = 1;
+ abs_value = bi1.abs_value }
+ else
+ { sign = 1;
+ abs_value =
+ match compare_nat (bi1.abs_value) 0 size_bi1
+ (bi2.abs_value) 0 size_bi2 with
+ 0 -> bi1.abs_value
+ | 1 ->
+ let res = copy_nat (bi1.abs_value) 0 size_bi1 in
+ let len =
+ gcd_nat res 0 size_bi1 (bi2.abs_value) 0 size_bi2 in
+ copy_nat res 0 len
+ | _ ->
+ let res = copy_nat (bi2.abs_value) 0 size_bi2 in
+ let len =
+ gcd_nat res 0 size_bi2 (bi1.abs_value) 0 size_bi1 in
+ copy_nat res 0 len
+ }
+
+(* Coercion operators *)
+
+let monster_big_int = big_int_of_int monster_int;;
+
+let monster_nat = monster_big_int.abs_value;;
+
+let is_int_big_int bi =
+ num_digits_big_int bi == 1 &&
+ match compare_nat bi.abs_value 0 1 monster_nat 0 1 with
+ | 0 -> bi.sign == -1
+ | -1 -> true
+ | _ -> false;;
+
+let int_of_big_int bi =
+ try let n = int_of_nat bi.abs_value in
+ if bi.sign = -1 then - n else n
+ with Failure _ ->
+ if eq_big_int bi monster_big_int then monster_int
+ else failwith "int_of_big_int";;
+
+let big_int_of_nativeint i =
+ if i = 0n then
+ zero_big_int
+ else if i > 0n then begin
+ let res = create_nat 1 in
+ set_digit_nat_native res 0 i;
+ { sign = 1; abs_value = res }
+ end else begin
+ let res = create_nat 1 in
+ set_digit_nat_native res 0 (Nativeint.neg i);
+ { sign = -1; abs_value = res }
+ end
+
+let nativeint_of_big_int bi =
+ if num_digits_big_int bi > 1 then failwith "nativeint_of_big_int";
+ let i = nth_digit_nat_native bi.abs_value 0 in
+ if bi.sign >= 0 then
+ if i >= 0n then i else failwith "nativeint_of_big_int"
+ else
+ if i >= 0n || i = Nativeint.min_int
+ then Nativeint.neg i
+ else failwith "nativeint_of_big_int"
+
+let big_int_of_int32 i = big_int_of_nativeint (Nativeint.of_int32 i)
+
+let int32_of_big_int bi =
+ let i = nativeint_of_big_int bi in
+ if i <= 0x7FFF_FFFFn && i >= -0x8000_0000n
+ then Nativeint.to_int32 i
+ else failwith "int32_of_big_int"
+
+let big_int_of_int64 i =
+ if Sys.word_size = 64 then
+ big_int_of_nativeint (Int64.to_nativeint i)
+ else begin
+ let (sg, absi) =
+ if i = 0L then (0, 0L)
+ else if i > 0L then (1, i)
+ else (-1, Int64.neg i) in
+ let res = create_nat 2 in
+ set_digit_nat_native res 0 (Int64.to_nativeint absi);
+ set_digit_nat_native res 1 (Int64.to_nativeint (Int64.shift_right absi 32));
+ { sign = sg; abs_value = res }
+ end
+
+let int64_of_big_int bi =
+ if Sys.word_size = 64 then
+ Int64.of_nativeint (nativeint_of_big_int bi)
+ else begin
+ let i =
+ match num_digits_big_int bi with
+ | 1 -> Int64.logand
+ (Int64.of_nativeint (nth_digit_nat_native bi.abs_value 0))
+ 0xFFFFFFFFL
+ | 2 -> Int64.logor
+ (Int64.logand
+ (Int64.of_nativeint (nth_digit_nat_native bi.abs_value 0))
+ 0xFFFFFFFFL)
+ (Int64.shift_left
+ (Int64.of_nativeint (nth_digit_nat_native bi.abs_value 1))
+ 32)
+ | _ -> failwith "int64_of_big_int" in
+ if bi.sign >= 0 then
+ if i >= 0L then i else failwith "int64_of_big_int"
+ else
+ if i >= 0L || i = Int64.min_int
+ then Int64.neg i
+ else failwith "int64_of_big_int"
+ end
+
+(* Coercion with nat type *)
+let nat_of_big_int bi =
+ if bi.sign = -1
+ then failwith "nat_of_big_int"
+ else copy_nat (bi.abs_value) 0 (num_digits_big_int bi)
+
+let sys_big_int_of_nat nat off len =
+ let length = num_digits_nat nat off len in
+ { sign = if is_zero_nat nat off length then 0 else 1;
+ abs_value = copy_nat nat off length }
+
+let big_int_of_nat nat =
+ sys_big_int_of_nat nat 0 (length_nat nat)
+
+(* Coercion with string type *)
+
+let string_of_big_int bi =
+ if bi.sign = -1
+ then "-" ^ string_of_nat bi.abs_value
+ else string_of_nat bi.abs_value
+
+
+let sys_big_int_of_string_aux s ofs len sgn base =
+ if len < 1 then failwith "sys_big_int_of_string";
+ let n = sys_nat_of_string base s ofs len in
+ if is_zero_nat n 0 (length_nat n) then zero_big_int
+ else {sign = sgn; abs_value = n}
+;;
+
+let sys_big_int_of_string_base s ofs len sgn =
+ if len < 1 then failwith "sys_big_int_of_string";
+ if len < 2 then sys_big_int_of_string_aux s ofs len sgn 10
+ else
+ match (s.[ofs], s.[ofs+1]) with
+ | ('0', 'x') | ('0', 'X') -> sys_big_int_of_string_aux s (ofs+2) (len-2) sgn 16
+ | ('0', 'o') | ('0', 'O') -> sys_big_int_of_string_aux s (ofs+2) (len-2) sgn 8
+ | ('0', 'b') | ('0', 'B') -> sys_big_int_of_string_aux s (ofs+2) (len-2) sgn 2
+ | _ -> sys_big_int_of_string_aux s ofs len sgn 10
+;;
+
+let sys_big_int_of_string s ofs len =
+ if len < 1 then failwith "sys_big_int_of_string";
+ match s.[ofs] with
+ | '-' -> sys_big_int_of_string_base s (ofs+1) (len-1) (-1)
+ | '+' -> sys_big_int_of_string_base s (ofs+1) (len-1) 1
+ | _ -> sys_big_int_of_string_base s ofs len 1
+;;
+
+let big_int_of_string s =
+ sys_big_int_of_string s 0 (String.length s)
+
+let power_base_nat base nat off len =
+ if base = 0 then nat_of_int 0 else
+ if is_zero_nat nat off len || base = 1 then nat_of_int 1 else
+ let power_base = make_nat (succ length_of_digit) in
+ let (pmax, pint) = make_power_base base power_base in
+ let (n, rem) =
+ let (x, y) = quomod_big_int (sys_big_int_of_nat nat off len)
+ (big_int_of_int (succ pmax)) in
+ (int_of_big_int x, int_of_big_int y) in
+ if n = 0 then copy_nat power_base (pred rem) 1 else
+ begin
+ let res = make_nat n
+ and res2 = make_nat (succ n)
+ and l = num_bits_int n - 2 in
+ blit_nat res 0 power_base pmax 1;
+ for i = l downto 0 do
+ let len = num_digits_nat res 0 n in
+ let len2 = min n (2 * len) in
+ let succ_len2 = succ len2 in
+ ignore (square_nat res2 0 len2 res 0 len);
+ begin
+ if n land (1 lsl i) > 0
+ then (set_to_zero_nat res 0 len;
+ ignore (mult_digit_nat res 0 succ_len2
+ res2 0 len2 power_base pmax))
+ else blit_nat res 0 res2 0 len2
+ end;
+ set_to_zero_nat res2 0 len2
+ done;
+ if rem > 0
+ then (ignore (mult_digit_nat res2 0 (succ n)
+ res 0 n power_base (pred rem));
+ res2)
+ else res
+ end
+
+let power_int_positive_int i n =
+ match sign_int n with
+ 0 -> unit_big_int
+ | -1 -> invalid_arg "power_int_positive_int"
+ | _ -> let nat = power_base_int (abs i) n in
+ { sign = if i >= 0
+ then sign_int i
+ else if n land 1 = 0
+ then 1
+ else -1;
+ abs_value = nat}
+
+let power_big_int_positive_int bi n =
+ match sign_int n with
+ 0 -> unit_big_int
+ | -1 -> invalid_arg "power_big_int_positive_int"
+ | _ -> let bi_len = num_digits_big_int bi in
+ let res_len = bi_len * n in
+ let res = make_nat res_len
+ and res2 = make_nat res_len
+ and l = num_bits_int n - 2 in
+ blit_nat res 0 bi.abs_value 0 bi_len;
+ for i = l downto 0 do
+ let len = num_digits_nat res 0 res_len in
+ let len2 = min res_len (2 * len) in
+ set_to_zero_nat res2 0 len2;
+ ignore (square_nat res2 0 len2 res 0 len);
+ if n land (1 lsl i) > 0 then begin
+ let lenp = min res_len (len2 + bi_len) in
+ set_to_zero_nat res 0 lenp;
+ ignore(mult_nat res 0 lenp res2 0 len2 (bi.abs_value) 0 bi_len)
+ end else begin
+ blit_nat res 0 res2 0 len2
+ end
+ done;
+ {sign = if bi.sign >= 0 then bi.sign
+ else if n land 1 = 0 then 1 else -1;
+ abs_value = res}
+
+let power_int_positive_big_int i bi =
+ match sign_big_int bi with
+ 0 -> unit_big_int
+ | -1 -> invalid_arg "power_int_positive_big_int"
+ | _ -> let nat = power_base_nat
+ (abs i) (bi.abs_value) 0 (num_digits_big_int bi) in
+ { sign = if i >= 0
+ then sign_int i
+ else if is_digit_odd (bi.abs_value) 0
+ then -1
+ else 1;
+ abs_value = nat }
+
+let power_big_int_positive_big_int bi1 bi2 =
+ match sign_big_int bi2 with
+ 0 -> unit_big_int
+ | -1 -> invalid_arg "power_big_int_positive_big_int"
+ | _ -> try
+ power_big_int_positive_int bi1 (int_of_big_int bi2)
+ with Failure _ ->
+ try
+ power_int_positive_big_int (int_of_big_int bi1) bi2
+ with Failure _ ->
+ raise Out_of_memory
+ (* If neither bi1 nor bi2 is a small integer, bi1^bi2 is not
+ representable. Indeed, on a 32-bit platform,
+ |bi1| >= 2 and |bi2| >= 2^30, hence bi1^bi2 has at least
+ 2^30 bits = 2^27 bytes, greater than the max size of
+ allocated blocks. On a 64-bit platform,
+ |bi1| >= 2 and |bi2| >= 2^62, hence bi1^bi2 has at least
+ 2^62 bits = 2^59 bytes, greater than the max size of
+ allocated blocks. *)
+
+(* base_power_big_int compute bi*base^n *)
+let base_power_big_int base n bi =
+ match sign_int n with
+ 0 -> bi
+ | -1 -> let nat = power_base_int base (-n) in
+ let len_nat = num_digits_nat nat 0 (length_nat nat)
+ and len_bi = num_digits_big_int bi in
+ if len_bi < len_nat then
+ invalid_arg "base_power_big_int"
+ else if len_bi = len_nat &&
+ compare_digits_nat (bi.abs_value) len_bi nat len_nat = -1
+ then invalid_arg "base_power_big_int"
+ else
+ let copy = create_nat (succ len_bi) in
+ blit_nat copy 0 (bi.abs_value) 0 len_bi;
+ set_digit_nat copy len_bi 0;
+ div_nat copy 0 (succ len_bi)
+ nat 0 len_nat;
+ if not (is_zero_nat copy 0 len_nat)
+ then invalid_arg "base_power_big_int"
+ else { sign = bi.sign;
+ abs_value = copy_nat copy len_nat 1 }
+ | _ -> let nat = power_base_int base n in
+ let len_nat = num_digits_nat nat 0 (length_nat nat)
+ and len_bi = num_digits_big_int bi in
+ let new_len = len_bi + len_nat in
+ let res = make_nat new_len in
+ ignore
+ (if len_bi > len_nat
+ then mult_nat res 0 new_len
+ (bi.abs_value) 0 len_bi
+ nat 0 len_nat
+ else mult_nat res 0 new_len
+ nat 0 len_nat
+ (bi.abs_value) 0 len_bi)
+ ; if is_zero_nat res 0 new_len
+ then zero_big_int
+ else create_big_int (bi.sign) res
+
+(* Other functions needed *)
+
+(* Integer part of the square root of a big_int *)
+let sqrt_big_int bi =
+ match bi.sign with
+ | 0 -> zero_big_int
+ | -1 -> invalid_arg "sqrt_big_int"
+ | _ -> {sign = 1;
+ abs_value = sqrt_nat (bi.abs_value) 0 (num_digits_big_int bi)}
+
+let square_big_int bi =
+ if bi.sign == 0 then zero_big_int else
+ let len_bi = num_digits_big_int bi in
+ let len_res = 2 * len_bi in
+ let res = make_nat len_res in
+ ignore (square_nat res 0 len_res (bi.abs_value) 0 len_bi);
+ {sign = 1; abs_value = res}
+
+(* round off of the futur last digit (of the integer represented by the string
+ argument of the function) that is now the previous one.
+ if s contains an integer of the form (10^n)-1
+ then s <- only 0 digits and the result_int is true
+ else s <- the round number and the result_int is false *)
+let round_futur_last_digit s off_set length =
+ let l = pred (length + off_set) in
+ if Char.code(Bytes.get s l) >= Char.code '5'
+ then
+ let rec round_rec l =
+ if l < off_set then true else begin
+ let current_char = Bytes.get s l in
+ if current_char = '9' then
+ (Bytes.set s l '0'; round_rec (pred l))
+ else
+ (Bytes.set s l (Char.chr (succ (Char.code current_char)));
+ false)
+ end
+ in round_rec (pred l)
+ else false
+
+
+(* Approximation with floating decimal point a` la approx_ratio_exp *)
+let approx_big_int prec bi =
+ let len_bi = num_digits_big_int bi in
+ let n =
+ max 0
+ (int_of_big_int (
+ add_int_big_int
+ (-prec)
+ (div_big_int (mult_big_int (big_int_of_int (pred len_bi))
+ (big_int_of_string "963295986"))
+ (big_int_of_string "100000000")))) in
+ let s =
+ Bytes.unsafe_of_string
+ (string_of_big_int (div_big_int bi (power_int_positive_int 10 n)))
+ in
+ let (sign, off, len) =
+ if Bytes.get s 0 = '-'
+ then ("-", 1, succ prec)
+ else ("", 0, prec) in
+ if (round_futur_last_digit s off (succ prec))
+ then (sign^"1."^(String.make prec '0')^"e"^
+ (string_of_int (n + 1 - off + Bytes.length s)))
+ else (sign^(Bytes.sub_string s off 1)^"."^
+ (Bytes.sub_string s (succ off) (pred prec))
+ ^"e"^(string_of_int (n - succ off + Bytes.length s)))
+
+(* Logical operations *)
+
+(* Shift left by N bits *)
+
+let shift_left_big_int bi n =
+ if n < 0 then invalid_arg "shift_left_big_int"
+ else if n = 0 then bi
+ else if bi.sign = 0 then bi
+ else begin
+ let size_bi = num_digits_big_int bi in
+ let size_res = size_bi + ((n + length_of_digit - 1) / length_of_digit) in
+ let res = create_nat size_res in
+ let ndigits = n / length_of_digit in
+ set_to_zero_nat res 0 ndigits;
+ blit_nat res ndigits bi.abs_value 0 size_bi;
+ let nbits = n mod length_of_digit in
+ if nbits > 0 then
+ shift_left_nat res ndigits size_bi res (ndigits + size_bi) nbits;
+ { sign = bi.sign; abs_value = res }
+ end
+
+(* Shift right by N bits (rounds toward zero) *)
+
+let shift_right_towards_zero_big_int bi n =
+ if n < 0 then invalid_arg "shift_right_towards_zero_big_int"
+ else if n = 0 then bi
+ else if bi.sign = 0 then bi
+ else begin
+ let size_bi = num_digits_big_int bi in
+ let ndigits = n / length_of_digit in
+ let nbits = n mod length_of_digit in
+ if ndigits >= size_bi then zero_big_int else begin
+ let size_res = size_bi - ndigits in
+ let res = create_nat size_res in
+ blit_nat res 0 bi.abs_value ndigits size_res;
+ if nbits > 0 then begin
+ let tmp = create_nat 1 in
+ shift_right_nat res 0 size_res tmp 0 nbits
+ end;
+ if is_zero_nat res 0 size_res
+ then zero_big_int
+ else { sign = bi.sign; abs_value = res }
+ end
+ end
+
+(* Compute 2^n - 1 *)
+
+let two_power_m1_big_int n =
+ if n < 0 then invalid_arg "two_power_m1_big_int"
+ else if n = 0 then zero_big_int
+ else begin
+ let idx = n / length_of_digit in
+ let size_res = idx + 1 in
+ let res = make_nat size_res in
+ set_digit_nat_native res idx
+ (Nativeint.shift_left 1n (n mod length_of_digit));
+ ignore (decr_nat res 0 size_res 0);
+ { sign = 1; abs_value = res }
+ end
+
+(* Shift right by N bits (rounds toward minus infinity) *)
+
+let shift_right_big_int bi n =
+ if n < 0 then invalid_arg "shift_right_big_int"
+ else if bi.sign >= 0 then shift_right_towards_zero_big_int bi n
+ else shift_right_towards_zero_big_int (sub_big_int bi (two_power_m1_big_int n)) n
+
+(* Extract N bits starting at ofs.
+ Treats bi in two's complement.
+ Result is always positive. *)
+
+let extract_big_int bi ofs n =
+ if ofs < 0 || n < 0 then invalid_arg "extract_big_int"
+ else if bi.sign = 0 then bi
+ else begin
+ let size_bi = num_digits_big_int bi in
+ let size_res = (n + length_of_digit - 1) / length_of_digit in
+ let ndigits = ofs / length_of_digit in
+ let nbits = ofs mod length_of_digit in
+ let res = make_nat size_res in
+ if ndigits < size_bi then
+ blit_nat res 0 bi.abs_value ndigits (min size_res (size_bi - ndigits));
+ if bi.sign < 0 then begin
+ (* Two's complement *)
+ complement_nat res 0 size_res;
+ (* PR#6010: need to increment res iff digits 0...ndigits-1 of bi are 0.
+ In this case, digits 0...ndigits-1 of not(bi) are all 0xFF...FF,
+ and adding 1 to them produces a carry out at ndigits. *)
+ let rec carry_incr i =
+ i >= ndigits || i >= size_bi ||
+ (is_digit_zero bi.abs_value i && carry_incr (i + 1)) in
+ if carry_incr 0 then ignore (incr_nat res 0 size_res 1)
+ end;
+ if nbits > 0 then begin
+ let tmp = create_nat 1 in
+ shift_right_nat res 0 size_res tmp 0 nbits
+ end;
+ let n' = n mod length_of_digit in
+ if n' > 0 then begin
+ let tmp = create_nat 1 in
+ set_digit_nat_native tmp 0
+ (Nativeint.shift_right_logical (-1n) (length_of_digit - n'));
+ land_digit_nat res (size_res - 1) tmp 0
+ end;
+ if is_zero_nat res 0 size_res
+ then zero_big_int
+ else { sign = 1; abs_value = res }
+ end
+
+(* Bitwise logical operations. Arguments must be >= 0. *)
+
+let and_big_int a b =
+ if a.sign < 0 || b.sign < 0 then invalid_arg "and_big_int"
+ else if a.sign = 0 || b.sign = 0 then zero_big_int
+ else begin
+ let size_a = num_digits_big_int a
+ and size_b = num_digits_big_int b in
+ let size_res = min size_a size_b in
+ let res = create_nat size_res in
+ blit_nat res 0 a.abs_value 0 size_res;
+ for i = 0 to size_res - 1 do
+ land_digit_nat res i b.abs_value i
+ done;
+ if is_zero_nat res 0 size_res
+ then zero_big_int
+ else { sign = 1; abs_value = res }
+ end
+
+let or_big_int a b =
+ if a.sign < 0 || b.sign < 0 then invalid_arg "or_big_int"
+ else if a.sign = 0 then b
+ else if b.sign = 0 then a
+ else begin
+ let size_a = num_digits_big_int a
+ and size_b = num_digits_big_int b in
+ let size_res = max size_a size_b in
+ let res = create_nat size_res in
+ let or_aux a' b' size_b' =
+ blit_nat res 0 a'.abs_value 0 size_res;
+ for i = 0 to size_b' - 1 do
+ lor_digit_nat res i b'.abs_value i
+ done in
+ if size_a >= size_b
+ then or_aux a b size_b
+ else or_aux b a size_a;
+ if is_zero_nat res 0 size_res
+ then zero_big_int
+ else { sign = 1; abs_value = res }
+ end
+
+let xor_big_int a b =
+ if a.sign < 0 || b.sign < 0 then invalid_arg "xor_big_int"
+ else if a.sign = 0 then b
+ else if b.sign = 0 then a
+ else begin
+ let size_a = num_digits_big_int a
+ and size_b = num_digits_big_int b in
+ let size_res = max size_a size_b in
+ let res = create_nat size_res in
+ let xor_aux a' b' size_b' =
+ blit_nat res 0 a'.abs_value 0 size_res;
+ for i = 0 to size_b' - 1 do
+ lxor_digit_nat res i b'.abs_value i
+ done in
+ if size_a >= size_b
+ then xor_aux a b size_b
+ else xor_aux b a size_a;
+ if is_zero_nat res 0 size_res
+ then zero_big_int
+ else { sign = 1; abs_value = res }
+ end
+
+(* Coercion with float type *)
+
+(* Consider a real number [r] such that
+ - the integral part of [r] is the bigint [x]
+ - 2^54 <= |x| < 2^63
+ - the fractional part of [r] is 0 if [exact = true],
+ nonzero if [exact = false].
+ Then, the following function returns [r] correctly rounded to
+ the nearest double-precision floating-point number.
+ This is an instance of the "round to odd" technique formalized in
+ "When double rounding is odd" by S. Boldo and G. Melquiond.
+ The claim above is lemma Fappli_IEEE_extra.round_odd_fix
+ from the CompCert Coq development. *)
+
+let round_big_int_to_float x exact =
+ assert (let n = num_bits_big_int x in 55 <= n && n <= 63);
+ let m = int64_of_big_int x in
+ (* Unless the fractional part is exactly 0, round m to an odd integer *)
+ let m = if exact then m else Int64.logor m 1L in
+ (* Then convert m to float, with the normal rounding mode. *)
+ Int64.to_float m
+
+let float_of_big_int x =
+ let n = num_bits_big_int x in
+ if n <= 63 then
+ Int64.to_float (int64_of_big_int x)
+ else begin
+ let n = n - 55 in
+ (* Extract top 55 bits of x *)
+ let top = shift_right_big_int x n in
+ (* Check if the other bits are all zero *)
+ let exact = eq_big_int x (shift_left_big_int top n) in
+ (* Round to float and apply exponent *)
+ ldexp (round_big_int_to_float top exact) n
+ end
+
+(* XL: suppression de big_int_of_float et nat_of_float. *)
+
diff --git a/otherlibs/num/big_int.mli b/otherlibs/num/big_int.mli
new file mode 100644
index 0000000000..57fb07792e
--- /dev/null
+++ b/otherlibs/num/big_int.mli
@@ -0,0 +1,197 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Operations on arbitrary-precision integers.
+
+ Big integers (type [big_int]) are signed integers of arbitrary size.
+*)
+
+open Nat
+
+type big_int
+ (** The type of big integers. *)
+
+val zero_big_int : big_int
+ (** The big integer [0]. *)
+val unit_big_int : big_int
+ (** The big integer [1]. *)
+
+(** {6 Arithmetic operations} *)
+
+val minus_big_int : big_int -> big_int
+ (** Unary negation. *)
+val abs_big_int : big_int -> big_int
+ (** Absolute value. *)
+val add_big_int : big_int -> big_int -> big_int
+ (** Addition. *)
+val succ_big_int : big_int -> big_int
+ (** Successor (add 1). *)
+val add_int_big_int : int -> big_int -> big_int
+ (** Addition of a small integer to a big integer. *)
+val sub_big_int : big_int -> big_int -> big_int
+ (** Subtraction. *)
+val pred_big_int : big_int -> big_int
+ (** Predecessor (subtract 1). *)
+val mult_big_int : big_int -> big_int -> big_int
+ (** Multiplication of two big integers. *)
+val mult_int_big_int : int -> big_int -> big_int
+ (** Multiplication of a big integer by a small integer *)
+val square_big_int: big_int -> big_int
+ (** Return the square of the given big integer *)
+val sqrt_big_int: big_int -> big_int
+ (** [sqrt_big_int a] returns the integer square root of [a],
+ that is, the largest big integer [r] such that [r * r <= a].
+ Raise [Invalid_argument] if [a] is negative. *)
+val quomod_big_int : big_int -> big_int -> big_int * big_int
+ (** Euclidean division of two big integers.
+ The first part of the result is the quotient,
+ the second part is the remainder.
+ Writing [(q,r) = quomod_big_int a b], we have
+ [a = q * b + r] and [0 <= r < |b|].
+ Raise [Division_by_zero] if the divisor is zero. *)
+val div_big_int : big_int -> big_int -> big_int
+ (** Euclidean quotient of two big integers.
+ This is the first result [q] of [quomod_big_int] (see above). *)
+val mod_big_int : big_int -> big_int -> big_int
+ (** Euclidean modulus of two big integers.
+ This is the second result [r] of [quomod_big_int] (see above). *)
+val gcd_big_int : big_int -> big_int -> big_int
+ (** Greatest common divisor of two big integers. *)
+val power_int_positive_int: int -> int -> big_int
+val power_big_int_positive_int: big_int -> int -> big_int
+val power_int_positive_big_int: int -> big_int -> big_int
+val power_big_int_positive_big_int: big_int -> big_int -> big_int
+ (** Exponentiation functions. Return the big integer
+ representing the first argument [a] raised to the power [b]
+ (the second argument). Depending
+ on the function, [a] and [b] can be either small integers
+ or big integers. Raise [Invalid_argument] if [b] is negative. *)
+
+(** {6 Comparisons and tests} *)
+
+val sign_big_int : big_int -> int
+ (** Return [0] if the given big integer is zero,
+ [1] if it is positive, and [-1] if it is negative. *)
+val compare_big_int : big_int -> big_int -> int
+ (** [compare_big_int a b] returns [0] if [a] and [b] are equal,
+ [1] if [a] is greater than [b], and [-1] if [a] is smaller
+ than [b]. *)
+val eq_big_int : big_int -> big_int -> bool
+val le_big_int : big_int -> big_int -> bool
+val ge_big_int : big_int -> big_int -> bool
+val lt_big_int : big_int -> big_int -> bool
+val gt_big_int : big_int -> big_int -> bool
+ (** Usual boolean comparisons between two big integers. *)
+val max_big_int : big_int -> big_int -> big_int
+ (** Return the greater of its two arguments. *)
+val min_big_int : big_int -> big_int -> big_int
+ (** Return the smaller of its two arguments. *)
+val num_digits_big_int : big_int -> int
+ (** Return the number of machine words used to store the
+ given big integer. *)
+val num_bits_big_int : big_int -> int
+ (** Return the number of significant bits in the absolute
+ value of the given big integer. [num_bits_big_int a]
+ returns 0 if [a] is 0; otherwise it returns a positive
+ integer [n] such that [2^(n-1) <= |a| < 2^n]. *)
+
+(** {6 Conversions to and from strings} *)
+
+val string_of_big_int : big_int -> string
+ (** Return the string representation of the given big integer,
+ in decimal (base 10). *)
+val big_int_of_string : string -> big_int
+ (** Convert a string to a big integer, in decimal.
+ The string consists of an optional [-] or [+] sign,
+ followed by one or several decimal digits. *)
+
+(** {6 Conversions to and from other numerical types} *)
+
+val big_int_of_int : int -> big_int
+ (** Convert a small integer to a big integer. *)
+val is_int_big_int : big_int -> bool
+ (** Test whether the given big integer is small enough to
+ be representable as a small integer (type [int])
+ without loss of precision. On a 32-bit platform,
+ [is_int_big_int a] returns [true] if and only if
+ [a] is between 2{^30} and 2{^30}-1. On a 64-bit platform,
+ [is_int_big_int a] returns [true] if and only if
+ [a] is between -2{^62} and 2{^62}-1. *)
+val int_of_big_int : big_int -> int
+ (** Convert a big integer to a small integer (type [int]).
+ Raises [Failure "int_of_big_int"] if the big integer
+ is not representable as a small integer. *)
+
+val big_int_of_int32 : int32 -> big_int
+ (** Convert a 32-bit integer to a big integer. *)
+val big_int_of_nativeint : nativeint -> big_int
+ (** Convert a native integer to a big integer. *)
+val big_int_of_int64 : int64 -> big_int
+ (** Convert a 64-bit integer to a big integer. *)
+val int32_of_big_int : big_int -> int32
+ (** Convert a big integer to a 32-bit integer.
+ Raises [Failure] if the big integer is outside the
+ range [[-2{^31}, 2{^31}-1]]. *)
+val nativeint_of_big_int : big_int -> nativeint
+ (** Convert a big integer to a native integer.
+ Raises [Failure] if the big integer is outside the
+ range [[Nativeint.min_int, Nativeint.max_int]]. *)
+val int64_of_big_int : big_int -> int64
+ (** Convert a big integer to a 64-bit integer.
+ Raises [Failure] if the big integer is outside the
+ range [[-2{^63}, 2{^63}-1]]. *)
+
+val float_of_big_int : big_int -> float
+ (** Returns a floating-point number approximating the
+ given big integer. *)
+
+(** {6 Bit-oriented operations} *)
+
+val and_big_int : big_int -> big_int -> big_int
+ (** Bitwise logical 'and'.
+ The arguments must be positive or zero. *)
+val or_big_int : big_int -> big_int -> big_int
+ (** Bitwise logical 'or'.
+ The arguments must be positive or zero. *)
+val xor_big_int : big_int -> big_int -> big_int
+ (** Bitwise logical 'exclusive or'.
+ The arguments must be positive or zero. *)
+val shift_left_big_int : big_int -> int -> big_int
+ (** [shift_left_big_int b n] returns [b] shifted left by [n] bits.
+ Equivalent to multiplication by [2^n]. *)
+val shift_right_big_int : big_int -> int -> big_int
+ (** [shift_right_big_int b n] returns [b] shifted right by [n] bits.
+ Equivalent to division by [2^n] with the result being
+ rounded towards minus infinity. *)
+val shift_right_towards_zero_big_int : big_int -> int -> big_int
+ (** [shift_right_towards_zero_big_int b n] returns [b] shifted
+ right by [n] bits. The shift is performed on the absolute
+ value of [b], and the result has the same sign as [b].
+ Equivalent to division by [2^n] with the result being
+ rounded towards zero. *)
+val extract_big_int : big_int -> int -> int -> big_int
+ (** [extract_big_int bi ofs n] returns a nonnegative number
+ corresponding to bits [ofs] to [ofs + n - 1] of the
+ binary representation of [bi]. If [bi] is negative,
+ a two's complement representation is used. *)
+
+(**/**)
+
+(** {6 For internal use} *)
+val nat_of_big_int : big_int -> nat
+val big_int_of_nat : nat -> big_int
+val base_power_big_int: int -> int -> big_int -> big_int
+val sys_big_int_of_string: string -> int -> int -> big_int
+val round_futur_last_digit : bytes -> int -> int -> bool
+val approx_big_int: int -> big_int -> string
+val round_big_int_to_float: big_int -> bool -> float
diff --git a/otherlibs/num/bng.c b/otherlibs/num/bng.c
new file mode 100644
index 0000000000..585e434e2c
--- /dev/null
+++ b/otherlibs/num/bng.c
@@ -0,0 +1,433 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+#include "bng.h"
+#include "caml/config.h"
+
+#if defined(__GNUC__) && BNG_ASM_LEVEL > 0
+#if defined(BNG_ARCH_ia32)
+#include "bng_ia32.c"
+#elif defined(BNG_ARCH_amd64)
+#include "bng_amd64.c"
+#elif defined(BNG_ARCH_ppc)
+#include "bng_ppc.c"
+#elif defined (BNG_ARCH_sparc)
+#include "bng_sparc.c"
+#elif defined (BNG_ARCH_arm64)
+#include "bng_arm64.c"
+#endif
+#endif
+
+#include "bng_digit.c"
+
+/**** Operations that cannot be overridden ****/
+
+/* Return number of leading zero bits in d */
+int bng_leading_zero_bits(bngdigit d)
+{
+ int n = BNG_BITS_PER_DIGIT;
+#ifdef ARCH_SIXTYFOUR
+ if ((d & 0xFFFFFFFF00000000L) != 0) { n -= 32; d = d >> 32; }
+#endif
+ if ((d & 0xFFFF0000) != 0) { n -= 16; d = d >> 16; }
+ if ((d & 0xFF00) != 0) { n -= 8; d = d >> 8; }
+ if ((d & 0xF0) != 0) { n -= 4; d = d >> 4; }
+ if ((d & 0xC) != 0) { n -= 2; d = d >> 2; }
+ if ((d & 2) != 0) { n -= 1; d = d >> 1; }
+ return n - d;
+}
+
+/* Complement the digits of {a,len} */
+void bng_complement(bng a/*[alen]*/, bngsize alen)
+{
+ for (/**/; alen > 0; alen--, a++) *a = ~*a;
+}
+
+/* Return number of significant digits in {a,alen}. */
+bngsize bng_num_digits(bng a/*[alen]*/, bngsize alen)
+{
+ while (1) {
+ if (alen == 0) return 1;
+ if (a[alen - 1] != 0) return alen;
+ alen--;
+ }
+}
+
+/* Return 0 if {a,alen} = {b,blen}
+ -1 if {a,alen} < {b,blen}
+ 1 if {a,alen} > {b,blen}. */
+int bng_compare(bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen)
+{
+ bngdigit da, db;
+
+ while (alen > 0 && a[alen-1] == 0) alen--;
+ while (blen > 0 && b[blen-1] == 0) blen--;
+ if (alen > blen) return 1;
+ if (alen < blen) return -1;
+ while (alen > 0) {
+ alen--;
+ da = a[alen];
+ db = b[alen];
+ if (da > db) return 1;
+ if (da < db) return -1;
+ }
+ return 0;
+}
+
+/**** Generic definitions of the overridable operations ****/
+
+/* {a,alen} := {a, alen} + carry. Return carry out. */
+static bngcarry bng_generic_add_carry
+ (bng a/*[alen]*/, bngsize alen, bngcarry carry)
+{
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+/* {a,alen} := {a,alen} + {b,blen} + carry. Return carry out.
+ Require alen >= blen. */
+static bngcarry bng_generic_add
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry)
+{
+ alen -= blen;
+ for (/**/; blen > 0; blen--, a++, b++) {
+ BngAdd2Carry(*a, carry, *a, *b, carry);
+ }
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+/* {a,alen} := {a, alen} - carry. Return carry out. */
+static bngcarry bng_generic_sub_carry
+ (bng a/*[alen]*/, bngsize alen, bngcarry carry)
+{
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+/* {a,alen} := {a,alen} - {b,blen} - carry. Return carry out.
+ Require alen >= blen. */
+static bngcarry bng_generic_sub
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry)
+{
+ alen -= blen;
+ for (/**/; blen > 0; blen--, a++, b++) {
+ BngSub2Carry(*a, carry, *a, *b, carry);
+ }
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+/* {a,alen} := {a,alen} << shift.
+ Return the bits shifted out of the most significant digit of a.
+ Require 0 <= shift < BITS_PER_BNGDIGIT. */
+static bngdigit bng_generic_shift_left
+ (bng a/*[alen]*/, bngsize alen,
+ int shift)
+{
+ int shift2 = BNG_BITS_PER_DIGIT - shift;
+ bngdigit carry = 0;
+ if (shift > 0) {
+ for (/**/; alen > 0; alen--, a++) {
+ bngdigit d = *a;
+ *a = (d << shift) | carry;
+ carry = d >> shift2;
+ }
+ }
+ return carry;
+}
+
+/* {a,alen} := {a,alen} >> shift.
+ Return the bits shifted out of the least significant digit of a.
+ Require 0 <= shift < BITS_PER_BNGDIGIT. */
+static bngdigit bng_generic_shift_right
+ (bng a/*[alen]*/, bngsize alen,
+ int shift)
+{
+ int shift2 = BNG_BITS_PER_DIGIT - shift;
+ bngdigit carry = 0;
+ if (shift > 0) {
+ for (a = a + alen - 1; alen > 0; alen--, a--) {
+ bngdigit d = *a;
+ *a = (d >> shift) | carry;
+ carry = d << shift2;
+ }
+ }
+ return carry;
+}
+
+/* {a,alen} := {a,alen} + d * {b,blen}. Return carry out.
+ Require alen >= blen. */
+static bngdigit bng_generic_mult_add_digit
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d)
+{
+ bngdigit out, ph, pl;
+ bngcarry carry;
+
+ alen -= blen;
+ for (out = 0; blen > 0; blen--, a++, b++) {
+ bngdigit bd = *b;
+ /* ph:pl = double-digit product of b's current digit and d */
+ BngMult(ph, pl, bd, d);
+ /* current digit of a += pl + out. Accumulate carries in ph. */
+ BngAdd3(*a, ph, *a, pl, out);
+ /* prepare out for next iteration */
+ out = ph;
+ }
+ if (alen == 0) return out;
+ /* current digit of a += out */
+ BngAdd2(*a, carry, *a, out);
+ a++;
+ alen--;
+ /* Propagate carry */
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+/* {a,alen} := {a,alen} - d * {b,blen}. Return carry out.
+ Require alen >= blen. */
+static bngdigit bng_generic_mult_sub_digit
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d)
+{
+ bngdigit out, ph, pl;
+ bngcarry carry;
+
+ alen -= blen;
+ for (out = 0; blen > 0; blen--, a++, b++) {
+ bngdigit bd = *b;
+ /* ph:pl = double-digit product of b's current digit and d */
+ BngMult(ph, pl, bd, d);
+ /* current digit of a -= pl + out. Accumulate carrys in ph. */
+ BngSub3(*a, ph, *a, pl, out);
+ /* prepare out for next iteration */
+ out = ph;
+ }
+ if (alen == 0) return out;
+ /* current digit of a -= out */
+ BngSub2(*a, carry, *a, out);
+ a++;
+ alen--;
+ /* Propagate carry */
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+/* {a,alen} := {a,alen} + {b,blen} * {c,clen}. Return carry out.
+ Require alen >= blen + clen. */
+static bngcarry bng_generic_mult_add
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bng c/*[clen]*/, bngsize clen)
+{
+ bngcarry carry;
+ for (carry = 0; clen > 0; clen--, c++, alen--, a++)
+ carry += bng_mult_add_digit(a, alen, b, blen, *c);
+ return carry;
+}
+
+/* {a,alen} := 2 * {a,alen} + {b,blen}^2. Return carry out.
+ Require alen >= 2 * blen. */
+static bngcarry bng_generic_square_add
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen)
+{
+ bngcarry carry1, carry2;
+ bngsize i, aofs;
+ bngdigit ph, pl, d;
+
+ /* Double products */
+ for (carry1 = 0, i = 1; i < blen; i++) {
+ aofs = 2 * i - 1;
+ carry1 += bng_mult_add_digit(a + aofs, alen - aofs,
+ b + i, blen - i, b[i - 1]);
+ }
+ /* Multiply by two */
+ carry1 = (carry1 << 1) | bng_shift_left(a, alen, 1);
+ /* Add square of digits */
+ carry2 = 0;
+ for (i = 0; i < blen; i++) {
+ d = b[i];
+ BngMult(ph, pl, d, d);
+ BngAdd2Carry(*a, carry2, *a, pl, carry2);
+ a++;
+ BngAdd2Carry(*a, carry2, *a, ph, carry2);
+ a++;
+ }
+ alen -= 2 * blen;
+ if (alen > 0 && carry2 != 0) {
+ do {
+ if (++(*a) != 0) { carry2 = 0; break; }
+ a++;
+ } while (--alen);
+ }
+ return carry1 + carry2;
+}
+
+/* {a,len-1} := {b,len} / d. Return {b,len} modulo d.
+ Require MSD of b < d.
+ If BngDivNeedsNormalization is defined, require d normalized. */
+static bngdigit bng_generic_div_rem_norm_digit
+ (bng a/*[len-1]*/, bng b/*[len]*/, bngsize len, bngdigit d)
+{
+ bngdigit topdigit, quo, rem;
+ intnat i;
+
+ topdigit = b[len - 1];
+ for (i = len - 2; i >= 0; i--) {
+ /* Divide topdigit:current digit of numerator by d */
+ BngDiv(quo, rem, topdigit, b[i], d);
+ /* Quotient is current digit of result */
+ a[i] = quo;
+ /* Iterate with topdigit = remainder */
+ topdigit = rem;
+ }
+ return topdigit;
+}
+
+#ifdef BngDivNeedsNormalization
+/* {a,len-1} := {b,len} / d. Return {b,len} modulo d.
+ Require MSD of b < d. */
+static bngdigit bng_generic_div_rem_digit
+ (bng a/*[len-1]*/, bng b/*[len]*/, bngsize len, bngdigit d)
+{
+ bngdigit rem;
+ int shift;
+
+ /* Normalize d and b */
+ shift = bng_leading_zero_bits(d);
+ d <<= shift;
+ bng_shift_left(b, len, shift);
+ /* Do the division */
+ rem = bng_div_rem_norm_digit(a, b, len, d);
+ /* Undo normalization on b and remainder */
+ bng_shift_right(b, len, shift);
+ return rem >> shift;
+}
+#endif
+
+/* {n+dlen, nlen-dlen} := {n,nlen} / {d, dlen}.
+ {n, dlen} := {n,nlen} modulo {d, dlen}.
+ Require nlen > dlen and MSD of n < MSD of d.
+ (This implies MSD of d > 0). */
+static void bng_generic_div_rem
+ (bng n/*[nlen]*/, bngsize nlen,
+ bng d/*[dlen]*/, bngsize dlen)
+{
+ bngdigit topden, quo, rem;
+ int shift;
+ bngsize i, j;
+
+ /* Normalize d */
+ shift = bng_leading_zero_bits(d[dlen - 1]);
+ /* Note that no bits of n are lost by the following shift,
+ since n[nlen-1] < d[dlen-1] */
+ bng_shift_left(n, nlen, shift);
+ bng_shift_left(d, dlen, shift);
+ /* Special case if d is just one digit */
+ if (dlen == 1) {
+ *n = bng_div_rem_norm_digit(n + 1, n, nlen, *d);
+ } else {
+ topden = d[dlen - 1];
+ /* Long division */
+ for (j = nlen - 1; j >= dlen; j--) {
+ i = j - dlen;
+ /* At this point:
+ - the current numerator is n[j] : ...................... : n[0]
+ - to be subtracted quo times: d[dlen-1] : ... : d[0] : 0... : 0
+ (there are i zeroes at the end) */
+ /* Under-estimate the next digit of the quotient (quo) */
+ if (topden + 1 == 0)
+ quo = n[j];
+ else
+ BngDiv(quo, rem, n[j], n[j - 1], topden + 1);
+ /* Subtract d * quo (shifted i places) from numerator */
+ n[j] -= bng_mult_sub_digit(n + i, dlen, d, dlen, quo);
+ /* Adjust if necessary */
+ while (n[j] != 0 || bng_compare(n + i, dlen, d, dlen) >= 0) {
+ /* Numerator is still bigger than shifted divisor.
+ Increment quotient and subtract shifted divisor. */
+ quo++;
+ n[j] -= bng_sub(n + i, dlen, d, dlen, 0);
+ }
+ /* Store quotient digit */
+ n[j] = quo;
+ }
+ }
+ /* Undo normalization on remainder and divisor */
+ bng_shift_right(n, dlen, shift);
+ bng_shift_right(d, dlen, shift);
+}
+
+/**** Construction of the table of operations ****/
+
+struct bng_operations bng_ops = {
+ bng_generic_add_carry,
+ bng_generic_add,
+ bng_generic_sub_carry,
+ bng_generic_sub,
+ bng_generic_shift_left,
+ bng_generic_shift_right,
+ bng_generic_mult_add_digit,
+ bng_generic_mult_sub_digit,
+ bng_generic_mult_add,
+ bng_generic_square_add,
+ bng_generic_div_rem_norm_digit,
+#ifdef BngDivNeedsNormalization
+ bng_generic_div_rem_digit,
+#else
+ bng_generic_div_rem_norm_digit,
+#endif
+ bng_generic_div_rem
+};
+
+void bng_init(void)
+{
+#ifdef BNG_SETUP_OPS
+ BNG_SETUP_OPS;
+#endif
+}
diff --git a/otherlibs/num/bng.h b/otherlibs/num/bng.h
new file mode 100644
index 0000000000..527bee6abe
--- /dev/null
+++ b/otherlibs/num/bng.h
@@ -0,0 +1,156 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+#include <string.h>
+#include "caml/config.h"
+
+typedef uintnat bngdigit;
+typedef bngdigit * bng;
+typedef unsigned int bngcarry;
+typedef uintnat bngsize;
+
+#define BNG_BITS_PER_DIGIT (sizeof(bngdigit) * 8)
+#define BNG_BITS_PER_HALF_DIGIT (sizeof(bngdigit) * 4)
+
+struct bng_operations {
+
+ /* {a,alen} := {a, alen} + carry. Return carry out. */
+ bngcarry (*add_carry)
+ (bng a/*[alen]*/, bngsize alen, bngcarry carry);
+#define bng_add_carry bng_ops.add_carry
+
+ /* {a,alen} := {a,alen} + {b,blen} + carry. Return carry out.
+ Require alen >= blen. */
+ bngcarry (*add)
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry);
+#define bng_add bng_ops.add
+
+ /* {a,alen} := {a, alen} - carry. Return carry out. */
+ bngcarry (*sub_carry)
+ (bng a/*[alen]*/, bngsize alen, bngcarry carry);
+#define bng_sub_carry bng_ops.sub_carry
+
+ /* {a,alen} := {a,alen} - {b,blen} - carry. Return carry out.
+ Require alen >= blen. */
+ bngcarry (*sub)
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry);
+#define bng_sub bng_ops.sub
+
+ /* {a,alen} := {a,alen} << shift.
+ Return the bits shifted out of the most significant digit of a.
+ Require 0 <= shift < BITS_PER_BNGDIGIT. */
+ bngdigit (*shift_left)
+ (bng a/*[alen]*/, bngsize alen,
+ int shift);
+#define bng_shift_left bng_ops.shift_left
+
+ /* {a,alen} := {a,alen} >> shift.
+ Return the bits shifted out of the least significant digit of a.
+ Require 0 <= shift < BITS_PER_BNGDIGIT. */
+ bngdigit (*shift_right)
+ (bng a/*[alen]*/, bngsize alen,
+ int shift);
+#define bng_shift_right bng_ops.shift_right
+
+ /* {a,alen} := {a,alen} + d * {b,blen}. Return carry out.
+ Require alen >= blen.
+ If alen > blen, the carry out returned is 0 or 1.
+ If alen == blen, the carry out returned is a full digit. */
+ bngdigit (*mult_add_digit)
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d);
+#define bng_mult_add_digit bng_ops.mult_add_digit
+
+ /* {a,alen} := {a,alen} - d * {b,blen}. Return carry out.
+ Require alen >= blen.
+ If alen > blen, the carry out returned is 0 or 1.
+ If alen == blen, the carry out returned is a full digit. */
+ bngdigit (*mult_sub_digit)
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d);
+#define bng_mult_sub_digit bng_ops.mult_sub_digit
+
+ /* {a,alen} := {a,alen} + {b,blen} * {c,clen}. Return carry out.
+ Require alen >= blen + clen. */
+ bngcarry (*mult_add)
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bng c/*[clen]*/, bngsize clen);
+#define bng_mult_add bng_ops.mult_add
+
+ /* {a,alen} := 2 * {a,alen} + {b,blen}^2. Return carry out.
+ Require alen >= 2 * blen. */
+ bngcarry (*square_add)
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen);
+#define bng_square_add bng_ops.square_add
+
+ /* {a,len-1} := {b,len} / d. Return {b,len} modulo d.
+ Require d is normalized and MSD of b < d.
+ See div_rem_digit for a function that does not require d
+ to be normalized */
+ bngdigit (*div_rem_norm_digit)
+ (bng a/*[len-1]*/, bng b/*[len]*/, bngsize len, bngdigit d);
+#define bng_div_rem_norm_digit bng_ops.div_rem_norm_digit
+
+ /* {a,len-1} := {b,len} / d. Return {b,len} modulo d.
+ Require MSD of b < d. */
+ bngdigit (*div_rem_digit)
+ (bng a/*[len-1]*/, bng b/*[len]*/, bngsize len, bngdigit d);
+#define bng_div_rem_digit bng_ops.div_rem_digit
+
+ /* {n+dlen, nlen-dlen} := {n,nlen} / {d, dlen}.
+ {n, dlen} := {n,nlen} modulo {d, dlen}.
+ Require nlen > dlen and MSD of n < MSD of d (which implies d != 0). */
+ void (*div_rem)
+ (bng n/*[nlen]*/, bngsize nlen,
+ bng d/*[nlen]*/, bngsize dlen);
+#define bng_div_rem bng_ops.div_rem
+};
+
+extern struct bng_operations bng_ops;
+
+/* Initialize the BNG library */
+extern void bng_init(void);
+
+/* {a,alen} := 0 */
+#define bng_zero(a,alen) memset((a), 0, (alen) * sizeof(bngdigit))
+
+/* {a,len} := {b,len} */
+#define bng_assign(a,b,len) memmove((a), (b), (len) * sizeof(bngdigit))
+
+/* Complement the digits of {a,len} */
+extern void bng_complement(bng a/*[alen]*/, bngsize alen);
+
+/* Return number of significant digits in {a,alen}. */
+extern bngsize bng_num_digits(bng a/*[alen]*/, bngsize alen);
+
+/* Return 1 if {a,alen} is 0, 0 otherwise. */
+#define bng_is_zero(a,alen) (bng_num_digits(a,alen) == 0)
+
+/* Return 0 if {a,alen} = {b,blen}
+ <0 if {a,alen} < {b,blen}
+ >0 if {a,alen} > {b,blen}. */
+extern int bng_compare(bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen);
+
+/* Return the number of leading zero bits in digit d. */
+extern int bng_leading_zero_bits(bngdigit d);
diff --git a/otherlibs/num/bng_amd64.c b/otherlibs/num/bng_amd64.c
new file mode 100644
index 0000000000..ecf9f2535d
--- /dev/null
+++ b/otherlibs/num/bng_amd64.c
@@ -0,0 +1,195 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+/* Code specific to the AMD x86_64 architecture. */
+
+#define BngAdd2(res,carryout,arg1,arg2) \
+ asm("xorl %1, %1 \n\t" \
+ "addq %3, %0 \n\t" \
+ "setc %b1" \
+ : "=r" (res), "=&q" (carryout) \
+ : "0" (arg1), "rm" (arg2))
+
+#define BngSub2(res,carryout,arg1,arg2) \
+ asm("xorl %1, %1 \n\t" \
+ "subq %3, %0 \n\t" \
+ "setc %b1" \
+ : "=r" (res), "=&q" (carryout) \
+ : "0" (arg1), "rm" (arg2))
+
+#define BngMult(resh,resl,arg1,arg2) \
+ asm("mulq %3" \
+ : "=a" (resl), "=d" (resh) \
+ : "a" (arg1), "r" (arg2))
+
+#define BngDiv(quo,rem,nh,nl,d) \
+ asm("divq %4" \
+ : "=a" (quo), "=d" (rem) \
+ : "a" (nl), "d" (nh), "r" (d))
+
+/* Reimplementation in asm of some of the bng operations. */
+
+static bngcarry bng_amd64_add
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry)
+{
+ bngdigit tmp;
+ alen -= blen;
+ if (blen > 0) {
+ asm("negb %b3 \n\t"
+ "1: \n\t"
+ "movq (%0), %4 \n\t"
+ "adcq (%1), %4 \n\t"
+ "movq %4, (%0) \n\t"
+ "leaq 8(%0), %0 \n\t"
+ "leaq 8(%1), %1 \n\t"
+ "decq %2 \n\t"
+ "jnz 1b \n\t"
+ "setc %b3"
+ : "=r" (a), "=r" (b), "=r" (blen), "=q" (carry), "=r" (tmp)
+ : "0" (a), "1" (b), "2" (blen), "3" (carry));
+ }
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngcarry bng_amd64_sub
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry)
+{
+ bngdigit tmp;
+ alen -= blen;
+ if (blen > 0) {
+ asm("negb %b3 \n\t"
+ "1: \n\t"
+ "movq (%0), %4 \n\t"
+ "sbbq (%1), %4 \n\t"
+ "movq %4, (%0) \n\t"
+ "leaq 8(%0), %0 \n\t"
+ "leaq 8(%1), %1 \n\t"
+ "decq %2 \n\t"
+ "jnz 1b \n\t"
+ "setc %b3"
+ : "=r" (a), "=r" (b), "=r" (blen), "=q" (carry), "=r" (tmp)
+ : "0" (a), "1" (b), "2" (blen), "3" (carry));
+ }
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngdigit bng_amd64_mult_add_digit
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d)
+{
+ bngdigit out;
+ bngcarry carry;
+
+ alen -= blen;
+ out = 0;
+ if (blen > 0) {
+ asm("1: \n\t"
+ "movq (%1), %%rax \n\t"
+ "mulq %7\n\t" /* rdx:rax = d * next digit of b */
+ "addq (%0), %%rax \n\t" /* add next digit of a to rax */
+ "adcq $0, %%rdx \n\t" /* accumulate carry in rdx */
+ "addq %3, %%rax \n\t" /* add out to rax */
+ "adcq $0, %%rdx \n\t" /* accumulate carry in rdx */
+ "movq %%rax, (%0) \n\t" /* rax is next digit of result */
+ "movq %%rdx, %3 \n\t" /* rdx is next out */
+ "leaq 8(%0), %0 \n\t"
+ "leaq 8(%1), %1 \n\t"
+ "decq %2 \n\t"
+ "jnz 1b"
+ : "=&r" (a), "=&r" (b), "=&r" (blen), "=&r" (out)
+ : "0" (a), "1" (b), "2" (blen), "rm" (d), "3" (out)
+ : "rax", "rdx");
+ }
+ if (alen == 0) return out;
+ /* current digit of a += out */
+ BngAdd2(*a, carry, *a, out);
+ a++;
+ alen--;
+ /* Propagate carry */
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngdigit bng_amd64_mult_sub_digit
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d)
+{
+ bngdigit out, tmp;
+ bngcarry carry;
+
+ alen -= blen;
+ out = 0;
+ if (blen > 0) {
+ asm("1: \n\t"
+ "movq (%1), %%rax \n\t"
+ "movq (%0), %4 \n\t"
+ "mulq %8\n\t" /* rdx:rax = d * next digit of b */
+ "subq %%rax, %4 \n\t" /* subtract rax from next digit of a */
+ "adcq $0, %%rdx \n\t" /* accumulate carry in rdx */
+ "subq %3, %4 \n\t" /* subtract out */
+ "adcq $0, %%rdx \n\t" /* accumulate carry in rdx */
+ "movq %4, (%0) \n\t" /* store next digit of result */
+ "movq %%rdx, %3 \n\t" /* rdx is next out */
+ "leaq 8(%0), %0 \n\t"
+ "leaq 8(%1), %1 \n\t"
+ "decq %2 \n\t"
+ "jnz 1b"
+ : "=&r" (a), "=&r" (b), "=&rm" (blen), "=&r" (out), "=&r" (tmp)
+ : "0" (a), "1" (b), "2" (blen), "rm" (d), "3" (out)
+ : "rax", "rdx");
+ }
+ if (alen == 0) return out;
+ /* current digit of a -= out */
+ BngSub2(*a, carry, *a, out);
+ a++;
+ alen--;
+ /* Propagate carry */
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static void bng_amd64_setup_ops(void)
+{
+ bng_ops.add = bng_amd64_add;
+ bng_ops.sub = bng_amd64_sub;
+ bng_ops.mult_add_digit = bng_amd64_mult_add_digit;
+ bng_ops.mult_sub_digit = bng_amd64_mult_sub_digit;
+}
+
+#define BNG_SETUP_OPS bng_amd64_setup_ops()
diff --git a/otherlibs/num/bng_arm64.c b/otherlibs/num/bng_arm64.c
new file mode 100644
index 0000000000..50843a0e6b
--- /dev/null
+++ b/otherlibs/num/bng_arm64.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2013 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Code specific for the ARM 64 (AArch64) architecture */
+
+#define BngMult(resh,resl,arg1,arg2) \
+ asm("mul %0, %2, %3 \n\t" \
+ "umulh %1, %2, %3" \
+ : "=&r" (resl), "=&r" (resh) \
+ : "r" (arg1), "r" (arg2))
diff --git a/otherlibs/num/bng_digit.c b/otherlibs/num/bng_digit.c
new file mode 100644
index 0000000000..fc10c8a37b
--- /dev/null
+++ b/otherlibs/num/bng_digit.c
@@ -0,0 +1,178 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+/**** Generic operations on digits ****/
+
+/* These macros can be defined in the machine-specific include file.
+ Below are the default definitions (in plain C).
+ Except for BngMult, all macros are guaranteed to evaluate their
+ arguments exactly once. */
+
+#ifndef BngAdd2
+/* res = arg1 + arg2. carryout = carry out. */
+#define BngAdd2(res,carryout,arg1,arg2) { \
+ bngdigit tmp1, tmp2; \
+ tmp1 = arg1; \
+ tmp2 = tmp1 + (arg2); \
+ carryout = (tmp2 < tmp1); \
+ res = tmp2; \
+}
+#endif
+
+#ifndef BngAdd2Carry
+/* res = arg1 + arg2 + carryin. carryout = carry out. */
+#define BngAdd2Carry(res,carryout,arg1,arg2,carryin) { \
+ bngdigit tmp1, tmp2, tmp3; \
+ tmp1 = arg1; \
+ tmp2 = tmp1 + (arg2); \
+ tmp3 = tmp2 + (carryin); \
+ carryout = (tmp2 < tmp1) + (tmp3 < tmp2); \
+ res = tmp3; \
+}
+#endif
+
+#ifndef BngAdd3
+/* res = arg1 + arg2 + arg3. Each carry increments carryaccu. */
+#define BngAdd3(res,carryaccu,arg1,arg2,arg3) { \
+ bngdigit tmp1, tmp2, tmp3; \
+ tmp1 = arg1; \
+ tmp2 = tmp1 + (arg2); \
+ carryaccu += (tmp2 < tmp1); \
+ tmp3 = tmp2 + (arg3); \
+ carryaccu += (tmp3 < tmp2); \
+ res = tmp3; \
+}
+#endif
+
+#ifndef BngSub2
+/* res = arg1 - arg2. carryout = carry out. */
+#define BngSub2(res,carryout,arg1,arg2) { \
+ bngdigit tmp1, tmp2; \
+ tmp1 = arg1; \
+ tmp2 = arg2; \
+ res = tmp1 - tmp2; \
+ carryout = (tmp1 < tmp2); \
+}
+#endif
+
+#ifndef BngSub2Carry
+/* res = arg1 - arg2 - carryin. carryout = carry out. */
+#define BngSub2Carry(res,carryout,arg1,arg2,carryin) { \
+ bngdigit tmp1, tmp2, tmp3; \
+ tmp1 = arg1; \
+ tmp2 = arg2; \
+ tmp3 = tmp1 - tmp2; \
+ res = tmp3 - (carryin); \
+ carryout = (tmp1 < tmp2) + (tmp3 < carryin); \
+}
+#endif
+
+#ifndef BngSub3
+/* res = arg1 - arg2 - arg3. Each carry increments carryaccu. */
+#define BngSub3(res,carryaccu,arg1,arg2,arg3) { \
+ bngdigit tmp1, tmp2, tmp3, tmp4; \
+ tmp1 = arg1; \
+ tmp2 = arg2; \
+ tmp3 = arg3; \
+ tmp4 = tmp1 - tmp2; \
+ res = tmp4 - tmp3; \
+ carryaccu += (tmp1 < tmp2) + (tmp4 < tmp3); \
+}
+#endif
+
+#define BngLowHalf(d) ((d) & (((bngdigit)1 << BNG_BITS_PER_HALF_DIGIT) - 1))
+#define BngHighHalf(d) ((d) >> BNG_BITS_PER_HALF_DIGIT)
+
+#ifndef BngMult
+/* resl = low digit of product arg1 * arg2
+ resh = high digit of product arg1 * arg2. */
+#if SIZEOF_PTR == 4 && defined(ARCH_UINT64_TYPE)
+#define BngMult(resh,resl,arg1,arg2) { \
+ ARCH_UINT64_TYPE p = (ARCH_UINT64_TYPE)(arg1) * (ARCH_UINT64_TYPE)(arg2); \
+ resh = p >> 32; \
+ resl = p; \
+}
+#else
+#define BngMult(resh,resl,arg1,arg2) { \
+ bngdigit p11 = BngLowHalf(arg1) * BngLowHalf(arg2); \
+ bngdigit p12 = BngLowHalf(arg1) * BngHighHalf(arg2); \
+ bngdigit p21 = BngHighHalf(arg1) * BngLowHalf(arg2); \
+ bngdigit p22 = BngHighHalf(arg1) * BngHighHalf(arg2); \
+ resh = p22 + (p12 >> BNG_BITS_PER_HALF_DIGIT) \
+ + (p21 >> BNG_BITS_PER_HALF_DIGIT); \
+ BngAdd3(resl, resh, \
+ p11, p12 << BNG_BITS_PER_HALF_DIGIT, p21 << BNG_BITS_PER_HALF_DIGIT); \
+}
+#endif
+#endif
+
+#ifndef BngDiv
+/* Divide the double-width number nh:nl by d.
+ Require d != 0 and nh < d.
+ Store quotient in quo, remainder in rem.
+ Can be slow if d is not normalized. */
+#define BngDiv(quo,rem,nh,nl,d) bng_div_aux(&(quo),&(rem),nh,nl,d)
+#define BngDivNeedsNormalization
+
+static void bng_div_aux(bngdigit * quo, bngdigit * rem,
+ bngdigit nh, bngdigit nl, bngdigit d)
+{
+ bngdigit dl, dh, ql, qh, pl, ph, nsaved;
+
+ dl = BngLowHalf(d);
+ dh = BngHighHalf(d);
+ /* Under-estimate the top half of the quotient (qh) */
+ qh = nh / (dh + 1);
+ /* Shift nh:nl right by BNG_BITS_PER_HALF_DIGIT bits,
+ so that we focus on the top 1.5 digits of the numerator.
+ Then, subtract (qh * d) from nh:nl. */
+ nsaved = BngLowHalf(nl);
+ ph = qh * dh;
+ pl = qh * dl;
+ nh -= ph; /* Subtract before shifting so that carry propagates for free */
+ nl = (nl >> BNG_BITS_PER_HALF_DIGIT) | (nh << BNG_BITS_PER_HALF_DIGIT);
+ nh = (nh >> BNG_BITS_PER_HALF_DIGIT);
+ nh -= (nl < pl); /* Borrow */
+ nl -= pl;
+ /* Adjust estimate qh until nh:nl < 0:d */
+ while (nh != 0 || nl >= d) {
+ nh -= (nl < d); /* Borrow */
+ nl -= d;
+ qh++;
+ }
+ /* Under-estimate the bottom half of the quotient (ql) */
+ ql = nl / (dh + 1);
+ /* Shift nh:nl left by BNG_BITS_PER_HALF_DIGIT bits, restoring the
+ low bits we saved earlier, so that we focus on the bottom 1.5 digit
+ of the numerator. Then, subtract (ql * d) from nh:nl. */
+ ph = ql * dh;
+ pl = ql * dl;
+ nl -= ph; /* Subtract before shifting so that carry propagates for free */
+ nh = (nl >> BNG_BITS_PER_HALF_DIGIT);
+ nl = (nl << BNG_BITS_PER_HALF_DIGIT) | nsaved;
+ nh -= (nl < pl); /* Borrow */
+ nl -= pl;
+ /* Adjust estimate ql until nh:nl < 0:d */
+ while (nh != 0 || nl >= d) {
+ nh -= (nl < d); /* Borrow */
+ nl -= d;
+ ql++;
+ }
+ /* We're done */
+ *quo = (qh << BNG_BITS_PER_HALF_DIGIT) | ql;
+ *rem = nl;
+}
+
+#endif
diff --git a/otherlibs/num/bng_ia32.c b/otherlibs/num/bng_ia32.c
new file mode 100644
index 0000000000..b4981cd488
--- /dev/null
+++ b/otherlibs/num/bng_ia32.c
@@ -0,0 +1,411 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+/* Code specific to the Intel IA32 (x86) architecture. */
+
+#define BngAdd2(res,carryout,arg1,arg2) \
+ asm("xorl %1, %1 \n\t" \
+ "addl %3, %0 \n\t" \
+ "setc %b1" \
+ : "=r" (res), "=&q" (carryout) \
+ : "0" (arg1), "rm" (arg2))
+
+#define BngSub2(res,carryout,arg1,arg2) \
+ asm("xorl %1, %1 \n\t" \
+ "subl %3, %0 \n\t" \
+ "setc %b1" \
+ : "=r" (res), "=&q" (carryout) \
+ : "0" (arg1), "rm" (arg2))
+
+#define BngMult(resh,resl,arg1,arg2) \
+ asm("mull %3" \
+ : "=a" (resl), "=d" (resh) \
+ : "a" (arg1), "r" (arg2))
+
+#define BngDiv(quo,rem,nh,nl,d) \
+ asm("divl %4" \
+ : "=a" (quo), "=d" (rem) \
+ : "a" (nl), "d" (nh), "r" (d))
+
+/* Reimplementation in asm of some of the bng operations. */
+
+static bngcarry bng_ia32_add
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry)
+{
+ bngdigit tmp;
+ alen -= blen;
+ if (blen > 0) {
+ asm("negb %b3 \n\t"
+ "1: \n\t"
+ "movl (%0), %4 \n\t"
+ "adcl (%1), %4 \n\t"
+ "movl %4, (%0) \n\t"
+ "leal 4(%0), %0 \n\t"
+ "leal 4(%1), %1 \n\t"
+ "decl %2 \n\t"
+ "jnz 1b \n\t"
+ "setc %b3"
+ : "+&r" (a), "+&r" (b), "+&r" (blen), "+&q" (carry), "=&r" (tmp));
+ }
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngcarry bng_ia32_sub
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry)
+{
+ bngdigit tmp;
+ alen -= blen;
+ if (blen > 0) {
+ asm("negb %b3 \n\t"
+ "1: \n\t"
+ "movl (%0), %4 \n\t"
+ "sbbl (%1), %4 \n\t"
+ "movl %4, (%0) \n\t"
+ "leal 4(%0), %0 \n\t"
+ "leal 4(%1), %1 \n\t"
+ "decl %2 \n\t"
+ "jnz 1b \n\t"
+ "setc %b3"
+ : "+&r" (a), "+&r" (b), "+&r" (blen), "+&q" (carry), "=&r" (tmp));
+ }
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngdigit bng_ia32_mult_add_digit
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d)
+{
+ bngdigit out;
+ bngcarry carry;
+
+ alen -= blen;
+ out = 0;
+ if (blen > 0) {
+ asm("1: \n\t"
+ "movl (%1), %%eax \n\t"
+ "mull %4\n\t" /* edx:eax = d * next digit of b */
+ "addl (%0), %%eax \n\t" /* add next digit of a to eax */
+ "adcl $0, %%edx \n\t" /* accumulate carry in edx */
+ "addl %3, %%eax \n\t" /* add out to eax */
+ "adcl $0, %%edx \n\t" /* accumulate carry in edx */
+ "movl %%eax, (%0) \n\t" /* eax is next digit of result */
+ "movl %%edx, %3 \n\t" /* edx is next out */
+ "leal 4(%0), %0 \n\t"
+ "leal 4(%1), %1 \n\t"
+ "decl %2 \n\t"
+ "jnz 1b"
+ : "+&r" (a), "+&r" (b), "+&r" (blen), "=m" (out)
+ : "m" (d)
+ : "eax", "edx");
+ }
+ if (alen == 0) return out;
+ /* current digit of a += out */
+ BngAdd2(*a, carry, *a, out);
+ a++;
+ alen--;
+ /* Propagate carry */
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngdigit bng_ia32_mult_sub_digit
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d)
+{
+ bngdigit out, tmp;
+ bngcarry carry;
+
+ alen -= blen;
+ out = 0;
+ if (blen > 0) {
+ asm("1: \n\t"
+ "movl (%1), %%eax \n\t"
+ "movl (%0), %4 \n\t"
+ "mull %5\n\t" /* edx:eax = d * next digit of b */
+ "subl %%eax, %4 \n\t" /* subtract eax from next digit of a */
+ "adcl $0, %%edx \n\t" /* accumulate carry in edx */
+ "subl %3, %4 \n\t" /* subtract out */
+ "adcl $0, %%edx \n\t" /* accumulate carry in edx */
+ "movl %4, (%0) \n\t" /* store next digit of result */
+ "movl %%edx, %3 \n\t" /* edx is next out */
+ "leal 4(%0), %0 \n\t"
+ "leal 4(%1), %1 \n\t"
+ "decl %2 \n\t"
+ "jnz 1b"
+ : "+&r" (a), "+&r" (b), "=m" (blen), "=m" (out), "=&r" (tmp)
+ : "m" (d)
+ : "eax", "edx");
+ }
+ if (alen == 0) return out;
+ /* current digit of a -= out */
+ BngSub2(*a, carry, *a, out);
+ a++;
+ alen--;
+ /* Propagate carry */
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+/* This is another asm implementation of some of the bng operations,
+ using SSE2 operations to provide 64-bit arithmetic.
+ This is faster than the plain IA32 code above on the Pentium 4.
+ (Arithmetic operations with carry are slow on the Pentium 4). */
+
+#if BNG_ASM_LEVEL >= 2
+
+static bngcarry bng_ia32sse2_add
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry)
+{
+ alen -= blen;
+ if (blen > 0) {
+ asm("movd %3, %%mm0 \n\t" /* MM0 is carry */
+ "1: \n\t"
+ "movd (%0), %%mm1 \n\t" /* MM1 is next digit of a */
+ "movd (%1), %%mm2 \n\t" /* MM2 is next digit of b */
+ "paddq %%mm1, %%mm0 \n\t" /* Add carry (64 bits) */
+ "paddq %%mm2, %%mm0 \n\t" /* Add digits (64 bits) */
+ "movd %%mm0, (%0) \n\t" /* Store low 32 bits of result */
+ "psrlq $32, %%mm0 \n\t" /* Next carry is top 32 bits of results */
+ "addl $4, %0\n\t"
+ "addl $4, %1\n\t"
+ "subl $1, %2\n\t"
+ "jne 1b \n\t"
+ "movd %%mm0, %3 \n\t"
+ "emms"
+ : "+&r" (a), "+&r" (b), "+&r" (blen), "+&rm" (carry));
+ }
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngcarry bng_ia32sse2_sub
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngcarry carry)
+{
+ alen -= blen;
+ if (blen > 0) {
+ asm("movd %3, %%mm0 \n\t" /* MM0 is carry */
+ "1: \n\t"
+ "movd (%0), %%mm1 \n\t" /* MM1 is next digit of a */
+ "movd (%1), %%mm2 \n\t" /* MM2 is next digit of b */
+ "psubq %%mm0, %%mm1 \n\t" /* Subtract carry (64 bits) */
+ "psubq %%mm2, %%mm1 \n\t" /* Subtract digits (64 bits) */
+ "movd %%mm1, (%0) \n\t" /* Store low 32 bits of result */
+ "psrlq $63, %%mm1 \n\t" /* Next carry is sign bit of result */
+ "movq %%mm1, %%mm0 \n\t"
+ "addl $4, %0\n\t"
+ "addl $4, %1\n\t"
+ "subl $1, %2\n\t"
+ "jne 1b \n\t"
+ "movd %%mm0, %3 \n\t"
+ "emms"
+ : "+&r" (a), "+&r" (b), "+&r" (blen), "+&rm" (carry));
+ }
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngdigit bng_ia32sse2_mult_add_digit
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d)
+{
+ bngdigit out;
+ bngcarry carry;
+
+ alen -= blen;
+ out = 0;
+ if (blen > 0) {
+ asm("pxor %%mm0, %%mm0 \n\t" /* MM0 is carry */
+ "movd %4, %%mm7 \n\t" /* MM7 is digit d */
+ "1: \n\t"
+ "movd (%0), %%mm1 \n\t" /* MM1 is next digit of a */
+ "movd (%1), %%mm2 \n\t" /* MM2 is next digit of b */
+ "pmuludq %%mm7, %%mm2 \n\t" /* MM2 = d * digit of b */
+ "paddq %%mm1, %%mm0 \n\t" /* Add product and carry ... */
+ "paddq %%mm2, %%mm0 \n\t" /* ... and digit of a */
+ "movd %%mm0, (%0) \n\t" /* Store low 32 bits of result */
+ "psrlq $32, %%mm0 \n\t" /* Next carry is high 32 bits result */
+ "addl $4, %0\n\t"
+ "addl $4, %1\n\t"
+ "subl $1, %2\n\t"
+ "jne 1b \n\t"
+ "movd %%mm0, %3 \n\t"
+ "emms"
+ : "+&r" (a), "+&r" (b), "+&r" (blen), "=&rm" (out)
+ : "m" (d));
+ }
+ if (alen == 0) return out;
+ /* current digit of a += out */
+ BngAdd2(*a, carry, *a, out);
+ a++;
+ alen--;
+ /* Propagate carry */
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if (++(*a) != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+static bngdigit bng_ia32sse2_mult_sub_digit
+ (bng a/*[alen]*/, bngsize alen,
+ bng b/*[blen]*/, bngsize blen,
+ bngdigit d)
+{
+ static unsigned long long bias1 = 0xFFFFFFFF00000000ULL - 0xFFFFFFFFULL;
+ static unsigned long bias2 = 0xFFFFFFFFUL;
+ bngdigit out;
+ bngcarry carry;
+
+ alen -= blen;
+ out = 0;
+ if (blen > 0) {
+ /* Carry C is represented by ENC(C) = 0xFFFFFFFF - C (one's complement) */
+ asm("movd %6, %%mm0 \n\t" /* MM0 is carry (initially 0xFFFFFFFF) */
+ "movq %5, %%mm6 \n\t" /* MM6 is magic constant bias1 */
+ "movd %4, %%mm7 \n\t" /* MM7 is digit d */
+ "1: \n\t"
+ "movd (%0), %%mm1 \n\t" /* MM1 is next digit of a */
+ "movd (%1), %%mm2 \n\t" /* MM2 is next digit of b */
+ "paddq %%mm6, %%mm1 \n\t" /* bias digit of a */
+ "pmuludq %%mm7, %%mm2 \n\t" /* MM2 = d * digit of b */
+ /* Compute
+ digit of a + ENC(carry) + 0xFFFFFFFF00000000 - 0xFFFFFFFF - product
+ = digit of a - carry + 0xFFFFFFFF00000000 - product
+ = digit of a - carry - productlow + (ENC(nextcarry) << 32) */
+ "psubq %%mm2, %%mm1 \n\t"
+ "paddq %%mm1, %%mm0 \n\t"
+ "movd %%mm0, (%0) \n\t" /* Store low 32 bits of result */
+ "psrlq $32, %%mm0 \n\t" /* Next carry is 32 high bits of result */
+ "addl $4, %0\n\t"
+ "addl $4, %1\n\t"
+ "subl $1, %2\n\t"
+ "jne 1b \n\t"
+ "movd %%mm0, %3 \n\t"
+ "emms"
+ : "+&r" (a), "+&r" (b), "+&r" (blen), "=&rm" (out)
+ : "m" (d), "m" (bias1), "m" (bias2));
+ out = ~out; /* Undo encoding on out digit */
+ }
+ if (alen == 0) return out;
+ /* current digit of a -= out */
+ BngSub2(*a, carry, *a, out);
+ a++;
+ alen--;
+ /* Propagate carry */
+ if (carry == 0 || alen == 0) return carry;
+ do {
+ if ((*a)-- != 0) return 0;
+ a++;
+ } while (--alen);
+ return 1;
+}
+
+/* Detect whether SSE2 instructions are supported */
+
+static int bng_ia32_sse2_supported(void)
+{
+ unsigned int flags, newflags, max_id, capabilities;
+
+#define EFLAG_CPUID 0x00200000
+#define CPUID_IDENTIFY 0
+#define CPUID_CAPABILITIES 1
+#define SSE2_CAPABILITY 26
+
+ /* Check if processor has CPUID instruction */
+ asm("pushfl \n\t"
+ "popl %0"
+ : "=r" (flags) : );
+ newflags = flags ^ EFLAG_CPUID; /* CPUID detection flag */
+ asm("pushfl \n\t"
+ "pushl %1 \n\t"
+ "popfl \n\t"
+ "pushfl \n\t"
+ "popl %0 \n\t"
+ "popfl"
+ : "=r" (flags) : "r" (newflags));
+ /* If CPUID detection flag cannot be changed, CPUID instruction is not
+ available */
+ if ((flags & EFLAG_CPUID) != (newflags & EFLAG_CPUID)) return 0;
+ /* See if SSE2 extensions are supported */
+ asm("pushl %%ebx \n\t" /* need to preserve %ebx for PIC */
+ "cpuid \n\t"
+ "popl %%ebx"
+ : "=a" (max_id) : "a" (CPUID_IDENTIFY): "ecx", "edx");
+ if (max_id < 1) return 0;
+ asm("pushl %%ebx \n\t"
+ "cpuid \n\t"
+ "popl %%ebx"
+ : "=d" (capabilities) : "a" (CPUID_CAPABILITIES) : "ecx");
+ return capabilities & (1 << SSE2_CAPABILITY);
+}
+
+#endif
+
+static void bng_ia32_setup_ops(void)
+{
+#if BNG_ASM_LEVEL >= 2
+ if (bng_ia32_sse2_supported()) {
+ bng_ops.add = bng_ia32sse2_add;
+ bng_ops.sub = bng_ia32sse2_sub;
+ bng_ops.mult_add_digit = bng_ia32sse2_mult_add_digit;
+ bng_ops.mult_sub_digit = bng_ia32sse2_mult_sub_digit;
+ return;
+ }
+#endif
+ bng_ops.add = bng_ia32_add;
+ bng_ops.sub = bng_ia32_sub;
+ bng_ops.mult_add_digit = bng_ia32_mult_add_digit;
+ bng_ops.mult_sub_digit = bng_ia32_mult_sub_digit;
+}
+
+#define BNG_SETUP_OPS bng_ia32_setup_ops()
diff --git a/otherlibs/num/bng_ppc.c b/otherlibs/num/bng_ppc.c
new file mode 100644
index 0000000000..4e9a363fc5
--- /dev/null
+++ b/otherlibs/num/bng_ppc.c
@@ -0,0 +1,94 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+/* Code specific to the PowerPC architecture. */
+
+#define BngAdd2(res,carryout,arg1,arg2) \
+ asm("addc %0, %2, %3 \n\t" \
+ "li %1, 0 \n\t" \
+ "addze %1, %1" \
+ : "=r" (res), "=r" (carryout) \
+ : "r" (arg1), "r" (arg2))
+
+#define BngAdd2Carry(res,carryout,arg1,arg2,carryin) \
+ asm("addic %1, %4, -1 \n\t" \
+ "adde %0, %2, %3 \n\t" \
+ "li %1, 0 \n\t" \
+ "addze %1, %1" \
+ : "=r" (res), "=&r" (carryout) \
+ : "r" (arg1), "r" (arg2), "1" (carryin))
+
+#define BngAdd3(res,carryaccu,arg1,arg2,arg3) \
+ asm("addc %0, %2, %3 \n\t" \
+ "addze %1, %1 \n\t" \
+ "addc %0, %0, %4 \n\t" \
+ "addze %1, %1" \
+ : "=&r" (res), "=&r" (carryaccu) \
+ : "r" (arg1), "r" (arg2), "r" (arg3), "1" (carryaccu))
+
+/* The "subtract" instructions interpret carry differently than what we
+ need: the processor carry bit CA is 1 if no carry occured,
+ 0 if a carry occured. In other terms, CA = !carry.
+ Thus, subfe rd,ra,rb computes rd = ra - rb - !CA
+ subfe rd,rd,rd sets rd = - !CA
+ subfe rd,rd,rd; neg rd, rd sets rd = !CA and recovers "our" carry. */
+
+#define BngSub2(res,carryout,arg1,arg2) \
+ asm("subfc %0, %3, %2 \n\t" \
+ "subfe %1, %1, %1\n\t" \
+ "neg %1, %1" \
+ : "=r" (res), "=r" (carryout) \
+ : "r" (arg1), "r" (arg2))
+
+#define BngSub2Carry(res,carryout,arg1,arg2,carryin) \
+ asm("subfic %1, %4, 0 \n\t" \
+ "subfe %0, %3, %2 \n\t" \
+ "subfe %1, %1, %1 \n\t" \
+ "neg %1, %1" \
+ : "=r" (res), "=&r" (carryout) \
+ : "r" (arg1), "r" (arg2), "1" (carryin))
+
+/* Here is what happens with carryaccu:
+ neg %1, %1 carryaccu = -carryaccu
+ addze %1, %1 carryaccu += !carry1
+ addze %1, %1 carryaccu += !carry2
+ subifc %1, %1, 2 carryaccu = 2 - carryaccu
+ Thus, carryaccu_final = carryaccu_initial + 2 - (1 - carry1) - (1 - carry2)
+ = carryaccu_initial + carry1 + carry2
+*/
+
+#define BngSub3(res,carryaccu,arg1,arg2,arg3) \
+ asm("neg %1, %1 \n\t" \
+ "subfc %0, %3, %2 \n\t" \
+ "addze %1, %1 \n\t" \
+ "subfc %0, %4, %0 \n\t" \
+ "addze %1, %1 \n\t" \
+ "subfic %1, %1, 2 \n\t" \
+ : "=&r" (res), "=&r" (carryaccu) \
+ : "r" (arg1), "r" (arg2), "r" (arg3), "1" (carryaccu))
+
+#if defined(__ppc64__) || defined(__PPC64__)
+#define BngMult(resh,resl,arg1,arg2) \
+ asm("mulld %0, %2, %3 \n\t" \
+ "mulhdu %1, %2, %3" \
+ : "=&r" (resl), "=r" (resh) \
+ : "r" (arg1), "r" (arg2))
+#else
+#define BngMult(resh,resl,arg1,arg2) \
+ asm("mullw %0, %2, %3 \n\t" \
+ "mulhwu %1, %2, %3" \
+ : "=&r" (resl), "=r" (resh) \
+ : "r" (arg1), "r" (arg2))
+#endif
diff --git a/otherlibs/num/bng_sparc.c b/otherlibs/num/bng_sparc.c
new file mode 100644
index 0000000000..4e46a316ae
--- /dev/null
+++ b/otherlibs/num/bng_sparc.c
@@ -0,0 +1,77 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2003 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+/* Code specific to the SPARC (V8 and above) architecture. */
+
+#define BngAdd2(res,carryout,arg1,arg2) \
+ asm("addcc %2, %3, %0 \n\t" \
+ "addx %%g0, 0, %1" \
+ : "=r" (res), "=r" (carryout) \
+ : "r" (arg1), "r" (arg2) \
+ : "cc")
+
+#define BngAdd2Carry(res,carryout,arg1,arg2,carryin) \
+ asm("subcc %%g0, %4, %%g0 \n\t" \
+ "addxcc %2, %3, %0 \n\t" \
+ "addx %%g0, 0, %1" \
+ : "=r" (res), "=r" (carryout) \
+ : "r" (arg1), "r" (arg2), "r" (carryin) \
+ : "cc")
+
+#define BngAdd3(res,carryaccu,arg1,arg2,arg3) \
+ asm("addcc %2, %3, %0 \n\t" \
+ "addx %1, 0, %1 \n\t" \
+ "addcc %0, %4, %0 \n\t" \
+ "addx %1, 0, %1" \
+ : "=r" (res), "=r" (carryaccu) \
+ : "r" (arg1), "r" (arg2), "r" (arg3), "1" (carryaccu) \
+ : "cc")
+
+#define BngSub2(res,carryout,arg1,arg2) \
+ asm("subcc %2, %3, %0 \n\t" \
+ "addx %%g0, 0, %1" \
+ : "=r" (res), "=r" (carryout) \
+ : "r" (arg1), "r" (arg2) \
+ : "cc")
+
+#define BngSub2Carry(res,carryout,arg1,arg2,carryin) \
+ asm("subcc %%g0, %4, %%g0 \n\t" \
+ "subxcc %2, %3, %0 \n\t" \
+ "addx %%g0, 0, %1" \
+ : "=r" (res), "=r" (carryout) \
+ : "r" (arg1), "r" (arg2), "r" (carryin) \
+ : "cc")
+
+#define BngSub3(res,carryaccu,arg1,arg2,arg3) \
+ asm("subcc %2, %3, %0 \n\t" \
+ "addx %1, 0, %1 \n\t" \
+ "subcc %0, %4, %0 \n\t" \
+ "addx %1, 0, %1" \
+ : "=r" (res), "=r" (carryaccu) \
+ : "r" (arg1), "r" (arg2), "r" (arg3), "1" (carryaccu) \
+ : "cc")
+
+#define BngMult(resh,resl,arg1,arg2) \
+ asm("umul %2, %3, %0 \n\t" \
+ "rd %%y, %1" \
+ : "=r" (resl), "=r" (resh) \
+ : "r" (arg1), "r" (arg2))
+
+#define BngDiv(quo,rem,nh,nl,d) \
+ asm("wr %1, %%y \n\t" \
+ "udiv %2, %3, %0" \
+ : "=r" (quo) \
+ : "r" (nh), "r" (nl), "r" (d)); \
+ rem = nl - d * quo
diff --git a/otherlibs/num/int_misc.ml b/otherlibs/num/int_misc.ml
new file mode 100644
index 0000000000..f8a91ee3a3
--- /dev/null
+++ b/otherlibs/num/int_misc.ml
@@ -0,0 +1,34 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Some extra operations on integers *)
+
+let rec gcd_int i1 i2 =
+ if i2 = 0 then abs i1 else gcd_int i2 (i1 mod i2)
+;;
+
+let rec num_bits_int_aux n =
+ if n = 0 then 0 else succ(num_bits_int_aux (n lsr 1));;
+
+let num_bits_int n = num_bits_int_aux (abs n);;
+
+let sign_int i = if i = 0 then 0 else if i > 0 then 1 else -1;;
+
+let length_of_int = Sys.word_size - 2;;
+
+let monster_int = 1 lsl length_of_int;;
+let biggest_int = monster_int - 1;;
+let least_int = - biggest_int;;
+
+let compare_int n1 n2 =
+ if n1 == n2 then 0 else if n1 > n2 then 1 else -1;;
diff --git a/otherlibs/num/int_misc.mli b/otherlibs/num/int_misc.mli
new file mode 100644
index 0000000000..6146732d4d
--- /dev/null
+++ b/otherlibs/num/int_misc.mli
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Some extra operations on integers *)
+
+val gcd_int: int -> int -> int
+val num_bits_int: int -> int
+val compare_int: int -> int -> int
+val sign_int: int -> int
+val length_of_int: int
+val biggest_int: int
+val least_int: int
+val monster_int: int
diff --git a/otherlibs/num/libnums.clib b/otherlibs/num/libnums.clib
new file mode 100644
index 0000000000..47c751f5e5
--- /dev/null
+++ b/otherlibs/num/libnums.clib
@@ -0,0 +1 @@
+bng.o nat_stubs.o
diff --git a/otherlibs/num/nat.h b/otherlibs/num/nat.h
new file mode 100644
index 0000000000..62c7ac9885
--- /dev/null
+++ b/otherlibs/num/nat.h
@@ -0,0 +1,18 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1999 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+/* Nats are represented as unstructured blocks with tag Custom_tag. */
+
+#define Digit_val(nat,pos) (((bng) Data_custom_val(nat))[pos])
diff --git a/otherlibs/num/nat.ml b/otherlibs/num/nat.ml
new file mode 100644
index 0000000000..5ea5fda751
--- /dev/null
+++ b/otherlibs/num/nat.ml
@@ -0,0 +1,575 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Int_misc
+
+type nat;;
+
+external create_nat: int -> nat = "create_nat"
+external set_to_zero_nat: nat -> int -> int -> unit = "set_to_zero_nat"
+external blit_nat: nat -> int -> nat -> int -> int -> unit = "blit_nat"
+external set_digit_nat: nat -> int -> int -> unit = "set_digit_nat"
+external nth_digit_nat: nat -> int -> int = "nth_digit_nat"
+external set_digit_nat_native: nat -> int -> nativeint -> unit = "set_digit_nat_native"
+external nth_digit_nat_native: nat -> int -> nativeint = "nth_digit_nat_native"
+external num_digits_nat: nat -> int -> int -> int = "num_digits_nat"
+external num_leading_zero_bits_in_digit: nat -> int -> int = "num_leading_zero_bits_in_digit"
+external is_digit_int: nat -> int -> bool = "is_digit_int"
+external is_digit_zero: nat -> int -> bool = "is_digit_zero"
+external is_digit_normalized: nat -> int -> bool = "is_digit_normalized"
+external is_digit_odd: nat -> int -> bool = "is_digit_odd"
+external incr_nat: nat -> int -> int -> int -> int = "incr_nat"
+external add_nat: nat -> int -> int -> nat -> int -> int -> int -> int = "add_nat" "add_nat_native"
+external complement_nat: nat -> int -> int -> unit = "complement_nat"
+external decr_nat: nat -> int -> int -> int -> int = "decr_nat"
+external sub_nat: nat -> int -> int -> nat -> int -> int -> int -> int = "sub_nat" "sub_nat_native"
+external mult_digit_nat: nat -> int -> int -> nat -> int -> int -> nat -> int -> int = "mult_digit_nat" "mult_digit_nat_native"
+external mult_nat: nat -> int -> int -> nat -> int -> int -> nat -> int -> int -> int = "mult_nat" "mult_nat_native"
+external square_nat: nat -> int -> int -> nat -> int -> int -> int = "square_nat" "square_nat_native"
+external shift_left_nat: nat -> int -> int -> nat -> int -> int -> unit = "shift_left_nat" "shift_left_nat_native"
+external div_digit_nat: nat -> int -> nat -> int -> nat -> int -> int -> nat -> int -> unit = "div_digit_nat" "div_digit_nat_native"
+external div_nat: nat -> int -> int -> nat -> int -> int -> unit = "div_nat" "div_nat_native"
+external shift_right_nat: nat -> int -> int -> nat -> int -> int -> unit = "shift_right_nat" "shift_right_nat_native"
+external compare_digits_nat: nat -> int -> nat -> int -> int = "compare_digits_nat"
+external compare_nat: nat -> int -> int -> nat -> int -> int -> int = "compare_nat" "compare_nat_native"
+external land_digit_nat: nat -> int -> nat -> int -> unit = "land_digit_nat"
+external lor_digit_nat: nat -> int -> nat -> int -> unit = "lor_digit_nat"
+external lxor_digit_nat: nat -> int -> nat -> int -> unit = "lxor_digit_nat"
+
+external initialize_nat: unit -> unit = "initialize_nat"
+let _ = initialize_nat()
+
+let length_nat (n : nat) = Obj.size (Obj.repr n) - 1
+
+let length_of_digit = Sys.word_size;;
+
+let make_nat len =
+ if len < 0 then invalid_arg "make_nat" else
+ let res = create_nat len in set_to_zero_nat res 0 len; res
+
+(* Nat temporaries *)
+let a_2 = make_nat 2
+and a_1 = make_nat 1
+and b_2 = make_nat 2
+
+let copy_nat nat off_set length =
+ let res = create_nat (length) in
+ blit_nat res 0 nat off_set length;
+ res
+
+let is_zero_nat n off len =
+ compare_nat (make_nat 1) 0 1 n off (num_digits_nat n off len) = 0
+
+let is_nat_int nat off len =
+ num_digits_nat nat off len = 1 && is_digit_int nat off
+
+let sys_int_of_nat nat off len =
+ if is_nat_int nat off len
+ then nth_digit_nat nat off
+ else failwith "int_of_nat"
+
+let int_of_nat nat =
+ sys_int_of_nat nat 0 (length_nat nat)
+
+let nat_of_int i =
+ if i < 0 then invalid_arg "nat_of_int" else
+ let res = make_nat 1 in
+ if i = 0 then res else begin set_digit_nat res 0 i; res end
+
+let eq_nat nat1 off1 len1 nat2 off2 len2 =
+ compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
+ nat2 off2 (num_digits_nat nat2 off2 len2) = 0
+and le_nat nat1 off1 len1 nat2 off2 len2 =
+ compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
+ nat2 off2 (num_digits_nat nat2 off2 len2) <= 0
+and lt_nat nat1 off1 len1 nat2 off2 len2 =
+ compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
+ nat2 off2 (num_digits_nat nat2 off2 len2) < 0
+and ge_nat nat1 off1 len1 nat2 off2 len2 =
+ compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
+ nat2 off2 (num_digits_nat nat2 off2 len2) >= 0
+and gt_nat nat1 off1 len1 nat2 off2 len2 =
+ compare_nat nat1 off1 (num_digits_nat nat1 off1 len1)
+ nat2 off2 (num_digits_nat nat2 off2 len2) > 0
+
+(* XL: now implemented in C for better performance.
+ The code below doesn't handle carries correctly.
+ Fortunately, the carry is never used. *)
+(***
+let square_nat nat1 off1 len1 nat2 off2 len2 =
+ let c = ref 0
+ and trash = make_nat 1 in
+ (* Double product *)
+ for i = 0 to len2 - 2 do
+ c := !c + mult_digit_nat
+ nat1
+ (succ (off1 + 2 * i))
+ (2 * (pred (len2 - i)))
+ nat2
+ (succ (off2 + i))
+ (pred (len2 - i))
+ nat2
+ (off2 + i)
+ done;
+ shift_left_nat nat1 0 len1 trash 0 1;
+ (* Square of digit *)
+ for i = 0 to len2 - 1 do
+ c := !c + mult_digit_nat
+ nat1
+ (off1 + 2 * i)
+ (len1 - 2 * i)
+ nat2
+ (off2 + i)
+ 1
+ nat2
+ (off2 + i)
+ done;
+ !c
+***)
+
+let gcd_int_nat i nat off len =
+ if i = 0 then 1 else
+ if is_nat_int nat off len then begin
+ set_digit_nat nat off (gcd_int (nth_digit_nat nat off) i); 0
+ end else begin
+ let len_copy = succ len in
+ let copy = create_nat len_copy
+ and quotient = create_nat 1
+ and remainder = create_nat 1 in
+ blit_nat copy 0 nat off len;
+ set_digit_nat copy len 0;
+ div_digit_nat quotient 0 remainder 0 copy 0 len_copy (nat_of_int i) 0;
+ set_digit_nat nat off (gcd_int (nth_digit_nat remainder 0) i);
+ 0
+ end
+
+let exchange r1 r2 =
+ let old1 = !r1 in r1 := !r2; r2 := old1
+
+let gcd_nat nat1 off1 len1 nat2 off2 len2 =
+ if is_zero_nat nat1 off1 len1 then begin
+ blit_nat nat1 off1 nat2 off2 len2; len2
+ end else begin
+ let copy1 = ref (create_nat (succ len1))
+ and copy2 = ref (create_nat (succ len2)) in
+ blit_nat !copy1 0 nat1 off1 len1;
+ blit_nat !copy2 0 nat2 off2 len2;
+ set_digit_nat !copy1 len1 0;
+ set_digit_nat !copy2 len2 0;
+ if lt_nat !copy1 0 len1 !copy2 0 len2
+ then exchange copy1 copy2;
+ let real_len1 =
+ ref (num_digits_nat !copy1 0 (length_nat !copy1))
+ and real_len2 =
+ ref (num_digits_nat !copy2 0 (length_nat !copy2)) in
+ while not (is_zero_nat !copy2 0 !real_len2) do
+ set_digit_nat !copy1 !real_len1 0;
+ div_nat !copy1 0 (succ !real_len1) !copy2 0 !real_len2;
+ exchange copy1 copy2;
+ real_len1 := !real_len2;
+ real_len2 := num_digits_nat !copy2 0 !real_len2
+ done;
+ blit_nat nat1 off1 !copy1 0 !real_len1;
+ !real_len1
+ end
+
+(* Racine carrée entière par la méthode de Newton (entière par défaut). *)
+
+(* Théorème: la suite xn+1 = (xn + a/xn) / 2 converge vers la racine *)
+(* carrée entière de a par défaut, si on part d'une valeur x0 *)
+(* strictement plus grande que la racine de a, sauf quand a est un *)
+(* carré - 1, cas auquel la suite alterne entre la racine par défaut *)
+(* et par excès. Dans tous les cas, le dernier terme de la partie *)
+(* strictement décroissante de la suite est le résultat cherché. *)
+
+let sqrt_nat rad off len =
+ let len = num_digits_nat rad off len in
+ (* Copie de travail du radicande *)
+ let len_parity = len mod 2 in
+ let rad_len = len + 1 + len_parity in
+ let rad =
+ let res = create_nat rad_len in
+ blit_nat res 0 rad off len;
+ set_digit_nat res len 0;
+ set_digit_nat res (rad_len - 1) 0;
+ res in
+ let cand_len = (len + 1) / 2 in (* ceiling len / 2 *)
+ let cand_rest = rad_len - cand_len in
+ (* Racine carrée supposée cand = "|FFFF .... |" *)
+ let cand = make_nat cand_len in
+ (* Amélioration de la racine de départ:
+ on calcule nbb le nombre de bits significatifs du premier digit du candidat
+ (la moitié du nombre de bits significatifs dans les deux premiers
+ digits du radicande étendu à une longueur paire).
+ shift_cand est word_size - nbb *)
+ let shift_cand =
+ ((num_leading_zero_bits_in_digit rad (len-1)) +
+ Sys.word_size * len_parity) / 2 in
+ (* Tous les bits du radicande sont à 0, on rend 0. *)
+ if shift_cand = Sys.word_size then cand else
+ begin
+ complement_nat cand 0 cand_len;
+ shift_right_nat cand 0 1 a_1 0 shift_cand;
+ let next_cand = create_nat rad_len in
+ (* Repeat until *)
+ let rec loop () =
+ (* next_cand := rad *)
+ blit_nat next_cand 0 rad 0 rad_len;
+ (* next_cand <- next_cand / cand *)
+ div_nat next_cand 0 rad_len cand 0 cand_len;
+ (* next_cand (poids fort) <- next_cand (poids fort) + cand,
+ i.e. next_cand <- cand + rad / cand *)
+ ignore (add_nat next_cand cand_len cand_rest cand 0 cand_len 0);
+ (* next_cand <- next_cand / 2 *)
+ shift_right_nat next_cand cand_len cand_rest a_1 0 1;
+ if lt_nat next_cand cand_len cand_rest cand 0 cand_len then
+ begin (* cand <- next_cand *)
+ blit_nat cand 0 next_cand cand_len cand_len; loop ()
+ end
+ else cand in
+ loop ()
+ end;;
+
+let power_base_max = make_nat 2;;
+
+match length_of_digit with
+ | 64 ->
+ set_digit_nat power_base_max 0 (Int64.to_int 1000000000000000000L);
+ ignore
+ (mult_digit_nat power_base_max 0 2
+ power_base_max 0 1 (nat_of_int 9) 0)
+ | 32 -> set_digit_nat power_base_max 0 1000000000
+ | _ -> assert false
+;;
+
+let pmax =
+ match length_of_digit with
+ | 64 -> 19
+ | 32 -> 9
+ | _ -> assert false
+;;
+
+let max_superscript_10_power_in_int =
+ match length_of_digit with
+ | 64 -> 18
+ | 32 -> 9
+ | _ -> assert false
+;;
+let max_power_10_power_in_int =
+ match length_of_digit with
+ | 64 -> nat_of_int (Int64.to_int 1000000000000000000L)
+ | 32 -> nat_of_int 1000000000
+ | _ -> assert false
+;;
+
+let raw_string_of_digit nat off =
+ if is_nat_int nat off 1
+ then begin string_of_int (nth_digit_nat nat off) end
+ else begin
+ blit_nat b_2 0 nat off 1;
+ div_digit_nat a_2 0 a_1 0 b_2 0 2 max_power_10_power_in_int 0;
+ let leading_digits = nth_digit_nat a_2 0
+ and s1 = string_of_int (nth_digit_nat a_1 0) in
+ let len = String.length s1 in
+ if leading_digits < 10 then begin
+ let result = Bytes.make (max_superscript_10_power_in_int+1) '0' in
+ Bytes.set result 0 (Char.chr (48 + leading_digits));
+ String.blit s1 0 result (Bytes.length result - len) len;
+ Bytes.to_string result
+ end else begin
+ let result = Bytes.make (max_superscript_10_power_in_int+2) '0' in
+ String.blit (string_of_int leading_digits) 0 result 0 2;
+ String.blit s1 0 result (Bytes.length result - len) len;
+ Bytes.to_string result
+ end
+ end
+
+(* XL: suppression de string_of_digit et de sys_string_of_digit.
+ La copie est de toute facon faite dans string_of_nat, qui est le
+ seul point d entree public dans ce code. *)
+
+(******
+let sys_string_of_digit nat off =
+ let s = raw_string_of_digit nat off in
+ let result = String.create (String.length s) in
+ String.blit s 0 result 0 (String.length s);
+ s
+
+let string_of_digit nat =
+ sys_string_of_digit nat 0
+
+*******)
+
+let digits = "0123456789ABCDEF"
+
+(*
+ make_power_base affecte power_base des puissances successives de base a
+ partir de la puissance 1-ieme.
+ A la fin de la boucle i-1 est la plus grande puissance de la base qui tient
+ sur un seul digit et j est la plus grande puissance de la base qui tient
+ sur un int.
+
+ This function returns [(pmax, pint)] where:
+ [pmax] is the index of the digit of [power_base] that contains the
+ the maximum power of [base] that fits in a digit. This is also one
+ less than the exponent of that power.
+ [pint] is the exponent of the maximum power of [base] that fits in an [int].
+*)
+let make_power_base base power_base =
+ let i = ref 0
+ and j = ref 0 in
+ set_digit_nat power_base 0 base;
+ while incr i; is_digit_zero power_base !i do
+ ignore
+ (mult_digit_nat power_base !i 2
+ power_base (pred !i) 1
+ power_base 0)
+ done;
+ while !j < !i - 1 && is_digit_int power_base !j do incr j done;
+ (!i - 2, !j)
+
+(*
+ int_to_string place la representation de l entier int en base base
+ dans la chaine s en le rangeant de la fin indiquee par pos vers le
+ debut, sur times places et affecte a pos sa nouvelle valeur.
+*)
+let int_to_string int s pos_ref base times =
+ let i = ref int
+ and j = ref times in
+ while ((!i != 0) || (!j != 0)) && (!pos_ref != -1) do
+ Bytes.set s !pos_ref (String.get digits (!i mod base));
+ decr pos_ref;
+ decr j;
+ i := !i / base
+ done
+
+(* XL: suppression de adjust_string *)
+
+let power_base_int base i =
+ if i = 0 || base = 1 then
+ nat_of_int 1
+ else if base = 0 then
+ nat_of_int 0
+ else if i < 0 then
+ invalid_arg "power_base_int"
+ else begin
+ let power_base = make_nat (succ length_of_digit) in
+ let (pmax, pint) = make_power_base base power_base in
+ let n = i / (succ pmax)
+ and rem = i mod (succ pmax) in
+ if n > 0 then begin
+ let newn =
+ if i = biggest_int then n else (succ n) in
+ let res = make_nat newn
+ and res2 = make_nat newn
+ and l = num_bits_int n - 2 in
+ blit_nat res 0 power_base pmax 1;
+ for i = l downto 0 do
+ let len = num_digits_nat res 0 newn in
+ let len2 = min n (2 * len) in
+ let succ_len2 = succ len2 in
+ ignore (square_nat res2 0 len2 res 0 len);
+ if n land (1 lsl i) > 0 then begin
+ set_to_zero_nat res 0 len;
+ ignore
+ (mult_digit_nat res 0 succ_len2
+ res2 0 len2 power_base pmax)
+ end else
+ blit_nat res 0 res2 0 len2;
+ set_to_zero_nat res2 0 len2
+ done;
+ if rem > 0 then begin
+ ignore
+ (mult_digit_nat res2 0 newn
+ res 0 n power_base (pred rem));
+ res2
+ end else res
+ end else
+ copy_nat power_base (pred rem) 1
+ end
+
+(* the ith element (i >= 2) of num_digits_max_vector is :
+ | |
+ | biggest_string_length * log (i) |
+ | ------------------------------- | + 1
+ | length_of_digit * log (2) |
+ -- --
+*)
+
+(* XL: ai specialise le code d origine a length_of_digit = 32. *)
+(* Puis suppression (inutile?) *)
+
+(******
+let num_digits_max_vector =
+ [|0; 0; 1024; 1623; 2048; 2378; 2647; 2875; 3072; 3246; 3402;
+ 3543; 3671; 3789; 3899; 4001; 4096|]
+
+let num_digits_max_vector =
+ match length_of_digit with
+ 16 -> [|0; 0; 2048; 3246; 4096; 4755; 5294; 5749; 6144; 6492; 6803;
+ 7085; 7342; 7578; 7797; 8001; 8192|]
+(* If really exotic machines !!!!
+ | 17 -> [|0; 0; 1928; 3055; 3855; 4476; 4983; 5411; 5783; 6110; 6403;
+ 6668; 6910; 7133; 7339; 7530; 7710|]
+ | 18 -> [|0; 0; 1821; 2886; 3641; 4227; 4706; 5111; 5461; 5771; 6047;
+ 6298; 6526; 6736; 6931; 7112; 7282|]
+ | 19 -> [|0; 0; 1725; 2734; 3449; 4005; 4458; 4842; 5174; 5467; 5729;
+ 5966; 6183; 6382; 6566; 6738; 6898|]
+ | 20 -> [|0; 0; 1639; 2597; 3277; 3804; 4235; 4600; 4915; 5194; 5443;
+ 5668; 5874; 6063; 6238; 6401; 6553|]
+ | 21 -> [|0; 0; 1561; 2473; 3121; 3623; 4034; 4381; 4681; 4946; 5183;
+ 5398; 5594; 5774; 5941; 6096; 6241|]
+ | 22 -> [|0; 0; 1490; 2361; 2979; 3459; 3850; 4182; 4468; 4722; 4948;
+ 5153; 5340; 5512; 5671; 5819; 5958|]
+ | 23 -> [|0; 0; 1425; 2258; 2850; 3308; 3683; 4000; 4274; 4516; 4733;
+ 4929; 5108; 5272; 5424; 5566; 5699|]
+ | 24 -> [|0; 0; 1366; 2164; 2731; 3170; 3530; 3833; 4096; 4328; 4536;
+ 4723; 4895; 5052; 5198; 5334; 5461|]
+ | 25 -> [|0; 0; 1311; 2078; 2622; 3044; 3388; 3680; 3932; 4155; 4354;
+ 4534; 4699; 4850; 4990; 5121; 5243|]
+ | 26 -> [|0; 0; 1261; 1998; 2521; 2927; 3258; 3538; 3781; 3995; 4187;
+ 4360; 4518; 4664; 4798; 4924; 5041|]
+ | 27 -> [|0; 0; 1214; 1924; 2428; 2818; 3137; 3407; 3641; 3847; 4032;
+ 4199; 4351; 4491; 4621; 4742; 4855|]
+ | 28 -> [|0; 0; 1171; 1855; 2341; 2718; 3025; 3286; 3511; 3710; 3888;
+ 4049; 4196; 4331; 4456; 4572; 4681|]
+ | 29 -> [|0; 0; 1130; 1791; 2260; 2624; 2921; 3172; 3390; 3582; 3754;
+ 3909; 4051; 4181; 4302; 4415; 4520|]
+ | 30 -> [|0; 0; 1093; 1732; 2185; 2536; 2824; 3067; 3277; 3463; 3629;
+ 3779; 3916; 4042; 4159; 4267; 4369|]
+ | 31 -> [|0; 0; 1057; 1676; 2114; 2455; 2733; 2968; 3171; 3351; 3512;
+ 3657; 3790; 3912; 4025; 4130; 4228|]
+*)
+ | 32 -> [|0; 0; 1024; 1623; 2048; 2378; 2647; 2875; 3072; 3246; 3402;
+ 3543; 3671; 3789; 3899; 4001; 4096|]
+ | n -> failwith "num_digits_max_vector"
+******)
+
+(* XL: suppression de string_list_of_nat *)
+
+let unadjusted_string_of_nat nat off len_nat =
+ let len = num_digits_nat nat off len_nat in
+ if len = 1 then
+ raw_string_of_digit nat off
+ else
+ let len_copy = ref (succ len) in
+ let copy1 = create_nat !len_copy
+ and copy2 = make_nat !len_copy
+ and rest_digit = make_nat 2 in
+ if len > biggest_int / (succ pmax)
+ then failwith "number too long"
+ else let len_s = (succ pmax) * len in
+ let s = Bytes.make len_s '0'
+ and pos_ref = ref len_s in
+ len_copy := pred !len_copy;
+ blit_nat copy1 0 nat off len;
+ set_digit_nat copy1 len 0;
+ while not (is_zero_nat copy1 0 !len_copy) do
+ div_digit_nat copy2 0
+ rest_digit 0
+ copy1 0 (succ !len_copy)
+ power_base_max 0;
+ let str = raw_string_of_digit rest_digit 0 in
+ String.blit str 0
+ s (!pos_ref - String.length str)
+ (String.length str);
+ (* XL: il y avait pmax a la place de String.length str
+ mais ca ne marche pas avec le blit de Caml Light,
+ qui ne verifie pas les debordements *)
+ pos_ref := !pos_ref - pmax;
+ len_copy := num_digits_nat copy2 0 !len_copy;
+ blit_nat copy1 0 copy2 0 !len_copy;
+ set_digit_nat copy1 !len_copy 0
+ done;
+ Bytes.unsafe_to_string s
+
+let string_of_nat nat =
+ let s = unadjusted_string_of_nat nat 0 (length_nat nat)
+ and index = ref 0 in
+ begin try
+ for i = 0 to String.length s - 2 do
+ if String.get s i <> '0' then (index:= i; raise Exit)
+ done
+ with Exit -> ()
+ end;
+ String.sub s !index (String.length s - !index)
+
+(* XL: suppression de sys_string_of_nat *)
+
+(* XL: suppression de debug_string_nat *)
+
+let base_digit_of_char c base =
+ let n = Char.code c in
+ if n >= 48 && n <= 47 + min base 10 then n - 48
+ else if n >= 65 && n <= 65 + base - 11 then n - 55
+ else if n >= 97 && n <= 97 + base - 11 then n - 87
+ else failwith "invalid digit"
+
+(*
+ La sous-chaine (s, off, len) represente un nat en base base que
+ on determine ici
+*)
+let sys_nat_of_string base s off len =
+ let power_base = make_nat (succ length_of_digit) in
+ let (pmax, pint) = make_power_base base power_base in
+ let new_len = ref (1 + len / (pmax + 1))
+ and current_len = ref 1 in
+ let possible_len = ref (min 2 !new_len) in
+
+ let nat1 = make_nat !new_len
+ and nat2 = make_nat !new_len
+
+ and digits_read = ref 0
+ and bound = off + len - 1
+ and int = ref 0 in
+
+ for i = off to bound do
+ (*
+ on lit pint (au maximum) chiffres, on en fait un int
+ et on l integre au nombre
+ *)
+ let c = String.get s i in
+ begin match c with
+ ' ' | '\t' | '\n' | '\r' | '\\' -> ()
+ | '_' when i > off -> ()
+ | _ -> int := !int * base + base_digit_of_char c base;
+ incr digits_read
+ end;
+ if (!digits_read = pint || i = bound) && not (!digits_read = 0) then
+ begin
+ set_digit_nat nat1 0 !int;
+ let erase_len = if !new_len = !current_len then !current_len - 1
+ else !current_len in
+ for j = 1 to erase_len do
+ set_digit_nat nat1 j 0
+ done;
+ ignore
+ (mult_digit_nat nat1 0 !possible_len
+ nat2 0 !current_len power_base (pred !digits_read));
+ blit_nat nat2 0 nat1 0 !possible_len;
+ current_len := num_digits_nat nat1 0 !possible_len;
+ possible_len := min !new_len (succ !current_len);
+ int := 0;
+ digits_read := 0
+ end
+ done;
+ (*
+ On recadre le nat
+ *)
+ let nat = create_nat !current_len in
+ blit_nat nat 0 nat1 0 !current_len;
+ nat
+
+let nat_of_string s = sys_nat_of_string 10 s 0 (String.length s)
+
+let float_of_nat nat = float_of_string(string_of_nat nat)
diff --git a/otherlibs/num/nat.mli b/otherlibs/num/nat.mli
new file mode 100644
index 0000000000..f9e279b646
--- /dev/null
+++ b/otherlibs/num/nat.mli
@@ -0,0 +1,71 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [Nat]: operations on natural numbers *)
+
+type nat
+
+(* Natural numbers (type [nat]) are positive integers of arbitrary size.
+ All operations on [nat] are performed in-place. *)
+
+external create_nat: int -> nat = "create_nat"
+val make_nat: int -> nat
+external set_to_zero_nat: nat -> int -> int -> unit = "set_to_zero_nat"
+external blit_nat: nat -> int -> nat -> int -> int -> unit = "blit_nat"
+val copy_nat: nat -> int -> int -> nat
+external set_digit_nat: nat -> int -> int -> unit = "set_digit_nat"
+external nth_digit_nat: nat -> int -> int = "nth_digit_nat"
+external set_digit_nat_native: nat -> int -> nativeint -> unit = "set_digit_nat_native"
+external nth_digit_nat_native: nat -> int -> nativeint = "nth_digit_nat_native"
+val length_nat : nat -> int
+external num_digits_nat: nat -> int -> int -> int = "num_digits_nat"
+external num_leading_zero_bits_in_digit: nat -> int -> int = "num_leading_zero_bits_in_digit"
+external is_digit_int: nat -> int -> bool = "is_digit_int"
+external is_digit_zero: nat -> int -> bool = "is_digit_zero"
+external is_digit_normalized: nat -> int -> bool = "is_digit_normalized"
+external is_digit_odd: nat -> int -> bool = "is_digit_odd"
+val is_zero_nat: nat -> int -> int -> bool
+val is_nat_int: nat -> int -> int -> bool
+val int_of_nat: nat -> int
+val nat_of_int: int -> nat
+external incr_nat: nat -> int -> int -> int -> int = "incr_nat"
+external add_nat: nat -> int -> int -> nat -> int -> int -> int -> int = "add_nat" "add_nat_native"
+external complement_nat: nat -> int -> int -> unit = "complement_nat"
+external decr_nat: nat -> int -> int -> int -> int = "decr_nat"
+external sub_nat: nat -> int -> int -> nat -> int -> int -> int -> int = "sub_nat" "sub_nat_native"
+external mult_digit_nat: nat -> int -> int -> nat -> int -> int -> nat -> int -> int = "mult_digit_nat" "mult_digit_nat_native"
+external mult_nat: nat -> int -> int -> nat -> int -> int -> nat -> int -> int -> int = "mult_nat" "mult_nat_native"
+external square_nat: nat -> int -> int -> nat -> int -> int -> int = "square_nat" "square_nat_native"
+external shift_left_nat: nat -> int -> int -> nat -> int -> int -> unit = "shift_left_nat" "shift_left_nat_native"
+external div_digit_nat: nat -> int -> nat -> int -> nat -> int -> int -> nat -> int -> unit = "div_digit_nat" "div_digit_nat_native"
+external div_nat: nat -> int -> int -> nat -> int -> int -> unit = "div_nat" "div_nat_native"
+external shift_right_nat: nat -> int -> int -> nat -> int -> int -> unit = "shift_right_nat" "shift_right_nat_native"
+external compare_digits_nat: nat -> int -> nat -> int -> int = "compare_digits_nat"
+external compare_nat: nat -> int -> int -> nat -> int -> int -> int = "compare_nat" "compare_nat_native"
+val eq_nat : nat -> int -> int -> nat -> int -> int -> bool
+val le_nat : nat -> int -> int -> nat -> int -> int -> bool
+val lt_nat : nat -> int -> int -> nat -> int -> int -> bool
+val ge_nat : nat -> int -> int -> nat -> int -> int -> bool
+val gt_nat : nat -> int -> int -> nat -> int -> int -> bool
+external land_digit_nat: nat -> int -> nat -> int -> unit = "land_digit_nat"
+external lor_digit_nat: nat -> int -> nat -> int -> unit = "lor_digit_nat"
+external lxor_digit_nat: nat -> int -> nat -> int -> unit = "lxor_digit_nat"
+val gcd_nat : nat -> int -> int -> nat -> int -> int -> int
+val sqrt_nat : nat -> int -> int -> nat
+val string_of_nat : nat -> string
+val nat_of_string : string -> nat
+val sys_nat_of_string : int -> string -> int -> int -> nat
+val float_of_nat : nat -> float
+val make_power_base : int -> nat -> int * int
+val power_base_int : int -> int -> nat
+val length_of_digit: int
diff --git a/otherlibs/num/nat_stubs.c b/otherlibs/num/nat_stubs.c
new file mode 100644
index 0000000000..22614e1317
--- /dev/null
+++ b/otherlibs/num/nat_stubs.c
@@ -0,0 +1,418 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* $Id$ */
+
+#include "caml/alloc.h"
+#include "caml/config.h"
+#include "caml/custom.h"
+#include "caml/intext.h"
+#include "caml/fail.h"
+#include "caml/hash.h"
+#include "caml/memory.h"
+#include "caml/mlvalues.h"
+
+#include "bng.h"
+#include "nat.h"
+
+/* Stub code for the Nat module. */
+
+static intnat hash_nat(value);
+static void serialize_nat(value, uintnat *, uintnat *);
+static uintnat deserialize_nat(void * dst);
+
+static struct custom_operations nat_operations = {
+ "_nat",
+ custom_finalize_default,
+ custom_compare_default,
+ hash_nat,
+ serialize_nat,
+ deserialize_nat,
+ custom_compare_ext_default
+};
+
+CAMLprim value initialize_nat(value unit)
+{
+ bng_init();
+ register_custom_operations(&nat_operations);
+ return Val_unit;
+}
+
+CAMLprim value create_nat(value size)
+{
+ mlsize_t sz = Long_val(size);
+
+ return alloc_custom(&nat_operations, sz * sizeof(value), 0, 1);
+}
+
+CAMLprim value length_nat(value nat)
+{
+ return Val_long(Wosize_val(nat) - 1);
+}
+
+CAMLprim value set_to_zero_nat(value nat, value ofs, value len)
+{
+ bng_zero(&Digit_val(nat, Long_val(ofs)), Long_val(len));
+ return Val_unit;
+}
+
+CAMLprim value blit_nat(value nat1, value ofs1,
+ value nat2, value ofs2,
+ value len)
+{
+ bng_assign(&Digit_val(nat1, Long_val(ofs1)),
+ &Digit_val(nat2, Long_val(ofs2)),
+ Long_val(len));
+ return Val_unit;
+}
+
+CAMLprim value set_digit_nat(value nat, value ofs, value digit)
+{
+ Digit_val(nat, Long_val(ofs)) = Long_val(digit);
+ return Val_unit;
+}
+
+CAMLprim value nth_digit_nat(value nat, value ofs)
+{
+ return Val_long(Digit_val(nat, Long_val(ofs)));
+}
+
+CAMLprim value set_digit_nat_native(value nat, value ofs, value digit)
+{
+ Digit_val(nat, Long_val(ofs)) = Nativeint_val(digit);
+ return Val_unit;
+}
+
+CAMLprim value nth_digit_nat_native(value nat, value ofs)
+{
+ return caml_copy_nativeint(Digit_val(nat, Long_val(ofs)));
+}
+
+CAMLprim value num_digits_nat(value nat, value ofs, value len)
+{
+ return Val_long(bng_num_digits(&Digit_val(nat, Long_val(ofs)),
+ Long_val(len)));
+}
+
+CAMLprim value num_leading_zero_bits_in_digit(value nat, value ofs)
+{
+ return
+ Val_long(bng_leading_zero_bits(Digit_val(nat, Long_val(ofs))));
+}
+
+CAMLprim value is_digit_int(value nat, value ofs)
+{
+ return Val_bool(Digit_val(nat, Long_val(ofs)) <= Max_long);
+}
+
+CAMLprim value is_digit_zero(value nat, value ofs)
+{
+ return Val_bool(Digit_val(nat, Long_val(ofs)) == 0);
+}
+
+CAMLprim value is_digit_normalized(value nat, value ofs)
+{
+ return
+ Val_bool(Digit_val(nat, Long_val(ofs)) & ((bngdigit)1 << (BNG_BITS_PER_DIGIT-1)));
+}
+
+CAMLprim value is_digit_odd(value nat, value ofs)
+{
+ return Val_bool(Digit_val(nat, Long_val(ofs)) & 1);
+}
+
+CAMLprim value incr_nat(value nat, value ofs, value len, value carry_in)
+{
+ return Val_long(bng_add_carry(&Digit_val(nat, Long_val(ofs)),
+ Long_val(len), Long_val(carry_in)));
+}
+
+value add_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value len2, value carry_in)
+{
+ return Val_long(bng_add(&Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ &Digit_val(nat2, Long_val(ofs2)), Long_val(len2),
+ Long_val(carry_in)));
+}
+
+CAMLprim value add_nat(value *argv, int argn)
+{
+ return add_nat_native(argv[0], argv[1], argv[2], argv[3],
+ argv[4], argv[5], argv[6]);
+}
+
+CAMLprim value complement_nat(value nat, value ofs, value len)
+{
+ bng_complement(&Digit_val(nat, Long_val(ofs)), Long_val(len));
+ return Val_unit;
+}
+
+CAMLprim value decr_nat(value nat, value ofs, value len, value carry_in)
+{
+ return Val_long(1 ^ bng_sub_carry(&Digit_val(nat, Long_val(ofs)),
+ Long_val(len), 1 ^ Long_val(carry_in)));
+}
+
+value sub_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value len2, value carry_in)
+{
+ return Val_long(1 ^ bng_sub(&Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ &Digit_val(nat2, Long_val(ofs2)), Long_val(len2),
+ 1 ^ Long_val(carry_in)));
+}
+
+CAMLprim value sub_nat(value *argv, int argn)
+{
+ return sub_nat_native(argv[0], argv[1], argv[2], argv[3],
+ argv[4], argv[5], argv[6]);
+}
+
+value mult_digit_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value len2,
+ value nat3, value ofs3)
+{
+ return
+ Val_long(bng_mult_add_digit(
+ &Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ &Digit_val(nat2, Long_val(ofs2)), Long_val(len2),
+ Digit_val(nat3, Long_val(ofs3))));
+}
+
+CAMLprim value mult_digit_nat(value *argv, int argn)
+{
+ return mult_digit_nat_native(argv[0], argv[1], argv[2], argv[3],
+ argv[4], argv[5], argv[6], argv[7]);
+}
+
+value mult_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value len2,
+ value nat3, value ofs3, value len3)
+{
+ return
+ Val_long(bng_mult_add(&Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ &Digit_val(nat2, Long_val(ofs2)), Long_val(len2),
+ &Digit_val(nat3, Long_val(ofs3)), Long_val(len3)));
+}
+
+CAMLprim value mult_nat(value *argv, int argn)
+{
+ return mult_nat_native(argv[0], argv[1], argv[2], argv[3],
+ argv[4], argv[5], argv[6], argv[7], argv[8]);
+}
+
+value square_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value len2)
+{
+ return
+ Val_long(bng_square_add(&Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ &Digit_val(nat2, Long_val(ofs2)), Long_val(len2)));
+}
+
+CAMLprim value square_nat(value *argv, int argn)
+{
+ return square_nat_native(argv[0], argv[1], argv[2],
+ argv[3], argv[4], argv[5]);
+}
+
+value shift_left_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value nbits)
+{
+ Digit_val(nat2, Long_val(ofs2)) =
+ bng_shift_left(&Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ Long_val(nbits));
+ return Val_unit;
+}
+
+CAMLprim value shift_left_nat(value *argv, int argn)
+{
+ return shift_left_nat_native(argv[0], argv[1], argv[2],
+ argv[3], argv[4], argv[5]);
+}
+
+value div_digit_nat_native(value natq, value ofsq,
+ value natr, value ofsr,
+ value nat1, value ofs1, value len1,
+ value nat2, value ofs2)
+{
+ Digit_val(natr, Long_val(ofsr)) =
+ bng_div_rem_digit(&Digit_val(natq, Long_val(ofsq)),
+ &Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ Digit_val(nat2, Long_val(ofs2)));
+ return Val_unit;
+}
+
+CAMLprim value div_digit_nat(value *argv, int argn)
+{
+ return div_digit_nat_native(argv[0], argv[1], argv[2], argv[3],
+ argv[4], argv[5], argv[6], argv[7], argv[8]);
+}
+
+value div_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value len2)
+{
+ bng_div_rem(&Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ &Digit_val(nat2, Long_val(ofs2)), Long_val(len2));
+ return Val_unit;
+}
+
+CAMLprim value div_nat(value *argv, int argn)
+{
+ return div_nat_native(argv[0], argv[1], argv[2],
+ argv[3], argv[4], argv[5]);
+}
+
+value shift_right_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value nbits)
+{
+ Digit_val(nat2, Long_val(ofs2)) =
+ bng_shift_right(&Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ Long_val(nbits));
+ return Val_unit;
+}
+
+CAMLprim value shift_right_nat(value *argv, int argn)
+{
+ return shift_right_nat_native(argv[0], argv[1], argv[2],
+ argv[3], argv[4], argv[5]);
+}
+
+CAMLprim value compare_digits_nat(value nat1, value ofs1,
+ value nat2, value ofs2)
+{
+ bngdigit d1 = Digit_val(nat1, Long_val(ofs1));
+ bngdigit d2 = Digit_val(nat2, Long_val(ofs2));
+ if (d1 > d2) return Val_int(1);
+ if (d1 < d2) return Val_int(-1);
+ return Val_int(0);
+}
+
+value compare_nat_native(value nat1, value ofs1, value len1,
+ value nat2, value ofs2, value len2)
+{
+ return
+ Val_int(bng_compare(&Digit_val(nat1, Long_val(ofs1)), Long_val(len1),
+ &Digit_val(nat2, Long_val(ofs2)), Long_val(len2)));
+}
+
+CAMLprim value compare_nat(value *argv, int argn)
+{
+ return compare_nat_native(argv[0], argv[1], argv[2],
+ argv[3], argv[4], argv[5]);
+}
+
+CAMLprim value land_digit_nat(value nat1, value ofs1, value nat2, value ofs2)
+{
+ Digit_val(nat1, Long_val(ofs1)) &= Digit_val(nat2, Long_val(ofs2));
+ return Val_unit;
+}
+
+CAMLprim value lor_digit_nat(value nat1, value ofs1, value nat2, value ofs2)
+{
+ Digit_val(nat1, Long_val(ofs1)) |= Digit_val(nat2, Long_val(ofs2));
+ return Val_unit;
+}
+
+CAMLprim value lxor_digit_nat(value nat1, value ofs1, value nat2, value ofs2)
+{
+ Digit_val(nat1, Long_val(ofs1)) ^= Digit_val(nat2, Long_val(ofs2));
+ return Val_unit;
+}
+
+/* The wire format for a nat is:
+ - 32-bit word: number of 32-bit words in nat
+ - N 32-bit words (big-endian format)
+ For little-endian platforms, the memory layout between 32-bit and 64-bit
+ machines is identical, so we can write the nat using serialize_block_4.
+ For big-endian 64-bit platforms, we need to swap the two 32-bit halves
+ of 64-bit words to obtain the correct behavior. */
+
+static void serialize_nat(value nat,
+ uintnat * wsize_32,
+ uintnat * wsize_64)
+{
+ mlsize_t len = Wosize_val(nat) - 1;
+
+#ifdef ARCH_SIXTYFOUR
+ len = len * 2; /* two 32-bit words per 64-bit digit */
+ if (len >= ((mlsize_t)1 << 32))
+ failwith("output_value: nat too big");
+#endif
+ serialize_int_4((int32_t) len);
+#if defined(ARCH_SIXTYFOUR) && defined(ARCH_BIG_ENDIAN)
+ { int32_t * p;
+ mlsize_t i;
+ for (i = len, p = Data_custom_val(nat); i > 0; i -= 2, p += 2) {
+ serialize_int_4(p[1]); /* low 32 bits of 64-bit digit */
+ serialize_int_4(p[0]); /* high 32 bits of 64-bit digit */
+ }
+ }
+#else
+ serialize_block_4(Data_custom_val(nat), len);
+#endif
+ *wsize_32 = len * 4;
+ *wsize_64 = len * 4;
+}
+
+static uintnat deserialize_nat(void * dst)
+{
+ mlsize_t len;
+
+ len = deserialize_uint_4();
+#if defined(ARCH_SIXTYFOUR) && defined(ARCH_BIG_ENDIAN)
+ { uint32_t * p;
+ mlsize_t i;
+ for (i = len, p = dst; i > 1; i -= 2, p += 2) {
+ p[1] = deserialize_uint_4(); /* low 32 bits of 64-bit digit */
+ p[0] = deserialize_uint_4(); /* high 32 bits of 64-bit digit */
+ }
+ if (i > 0){
+ p[1] = deserialize_uint_4(); /* low 32 bits of 64-bit digit */
+ p[0] = 0; /* high 32 bits of 64-bit digit */
+ ++ len;
+ }
+ }
+#else
+ deserialize_block_4(dst, len);
+#if defined(ARCH_SIXTYFOUR)
+ if (len & 1){
+ ((uint32_t *) dst)[len] = 0;
+ ++ len;
+ }
+#endif
+#endif
+ return len * 4;
+}
+
+static intnat hash_nat(value v)
+{
+ bngsize len, i;
+ uint32_t h;
+
+ len = bng_num_digits(&Digit_val(v,0), Wosize_val(v) - 1);
+ h = 0;
+ for (i = 0; i < len; i++) {
+ bngdigit d = Digit_val(v, i);
+#ifdef ARCH_SIXTYFOUR
+ /* Mix the two 32-bit halves as if we were on a 32-bit platform,
+ namely low 32 bits first, then high 32 bits.
+ Also, ignore final 32 bits if they are zero. */
+ h = caml_hash_mix_uint32(h, (uint32_t) d);
+ d = d >> 32;
+ if (d == 0 && i + 1 == len) break;
+ h = caml_hash_mix_uint32(h, (uint32_t) d);
+#else
+ h = caml_hash_mix_uint32(h, d);
+#endif
+ }
+ return h;
+}
diff --git a/otherlibs/num/num.ml b/otherlibs/num/num.ml
new file mode 100644
index 0000000000..924e9eab6c
--- /dev/null
+++ b/otherlibs/num/num.ml
@@ -0,0 +1,445 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Int_misc
+open Nat
+open Big_int
+open Arith_flags
+open Ratio
+
+type num = Int of int | Big_int of big_int | Ratio of ratio
+ (* The type of numbers. *)
+
+let biggest_INT = big_int_of_int biggest_int
+and least_INT = big_int_of_int least_int
+
+(* Coercion big_int -> num *)
+let num_of_big_int bi =
+ if le_big_int bi biggest_INT && ge_big_int bi least_INT
+ then Int (int_of_big_int bi)
+ else Big_int bi
+
+let numerator_num = function
+ Ratio r -> ignore (normalize_ratio r); num_of_big_int (numerator_ratio r)
+| n -> n
+
+let denominator_num = function
+ Ratio r -> ignore (normalize_ratio r); num_of_big_int (denominator_ratio r)
+| n -> Int 1
+
+let normalize_num = function
+ Int i -> Int i
+| Big_int bi -> num_of_big_int bi
+| Ratio r -> if is_integer_ratio r
+ then num_of_big_int (numerator_ratio r)
+ else Ratio r
+
+let cautious_normalize_num_when_printing n =
+ if (!normalize_ratio_when_printing_flag) then (normalize_num n) else n
+
+let num_of_ratio r =
+ ignore (normalize_ratio r);
+ if not (is_integer_ratio r) then Ratio r
+ else if is_int_big_int (numerator_ratio r) then
+ Int (int_of_big_int (numerator_ratio r))
+ else Big_int (numerator_ratio r)
+
+(* Operations on num *)
+
+let add_num a b = match (a,b) with
+ ((Int int1), (Int int2)) ->
+ let r = int1 + int2 in
+ if (int1 lxor int2) lor (int1 lxor (r lxor (-1))) < 0
+ then Int r (* No overflow *)
+ else Big_int(add_big_int (big_int_of_int int1) (big_int_of_int int2))
+ | ((Int i), (Big_int bi)) ->
+ num_of_big_int (add_int_big_int i bi)
+ | ((Big_int bi), (Int i)) ->
+ num_of_big_int (add_int_big_int i bi)
+
+ | ((Int i), (Ratio r)) ->
+ Ratio (add_int_ratio i r)
+ | ((Ratio r), (Int i)) ->
+ Ratio (add_int_ratio i r)
+
+ | ((Big_int bi1), (Big_int bi2)) -> num_of_big_int (add_big_int bi1 bi2)
+
+ | ((Big_int bi), (Ratio r)) ->
+ Ratio (add_big_int_ratio bi r)
+ | ((Ratio r), (Big_int bi)) ->
+ Ratio (add_big_int_ratio bi r)
+
+ | ((Ratio r1), (Ratio r2)) -> num_of_ratio (add_ratio r1 r2)
+
+let ( +/ ) = add_num
+
+let minus_num = function
+ Int i -> if i = monster_int
+ then Big_int (minus_big_int (big_int_of_int i))
+ else Int (-i)
+| Big_int bi -> Big_int (minus_big_int bi)
+| Ratio r -> Ratio (minus_ratio r)
+
+let sub_num n1 n2 = add_num n1 (minus_num n2)
+
+let ( -/ ) = sub_num
+
+let mult_num a b = match (a,b) with
+ ((Int int1), (Int int2)) ->
+ if num_bits_int int1 + num_bits_int int2 < length_of_int
+ then Int (int1 * int2)
+ else num_of_big_int (mult_big_int (big_int_of_int int1)
+ (big_int_of_int int2))
+
+ | ((Int i), (Big_int bi)) ->
+ num_of_big_int (mult_int_big_int i bi)
+ | ((Big_int bi), (Int i)) ->
+ num_of_big_int (mult_int_big_int i bi)
+
+ | ((Int i), (Ratio r)) ->
+ num_of_ratio (mult_int_ratio i r)
+ | ((Ratio r), (Int i)) ->
+ num_of_ratio (mult_int_ratio i r)
+
+ | ((Big_int bi1), (Big_int bi2)) ->
+ num_of_big_int (mult_big_int bi1 bi2)
+
+ | ((Big_int bi), (Ratio r)) ->
+ num_of_ratio (mult_big_int_ratio bi r)
+ | ((Ratio r), (Big_int bi)) ->
+ num_of_ratio (mult_big_int_ratio bi r)
+
+ | ((Ratio r1), (Ratio r2)) ->
+ num_of_ratio (mult_ratio r1 r2)
+
+let ( */ ) = mult_num
+
+let square_num = function
+ Int i -> if 2 * num_bits_int i < length_of_int
+ then Int (i * i)
+ else num_of_big_int (square_big_int (big_int_of_int i))
+ | Big_int bi -> Big_int (square_big_int bi)
+ | Ratio r -> Ratio (square_ratio r)
+
+let div_num n1 n2 =
+ match n1 with
+ | Int i1 ->
+ begin match n2 with
+ | Int i2 ->
+ num_of_ratio (create_ratio (big_int_of_int i1) (big_int_of_int i2))
+ | Big_int bi2 -> num_of_ratio (create_ratio (big_int_of_int i1) bi2)
+ | Ratio r2 -> num_of_ratio (div_int_ratio i1 r2) end
+
+ | Big_int bi1 ->
+ begin match n2 with
+ | Int i2 -> num_of_ratio (create_ratio bi1 (big_int_of_int i2))
+ | Big_int bi2 -> num_of_ratio (create_ratio bi1 bi2)
+ | Ratio r2 -> num_of_ratio (div_big_int_ratio bi1 r2) end
+
+ | Ratio r1 ->
+ begin match n2 with
+ | Int i2 -> num_of_ratio (div_ratio_int r1 i2)
+ | Big_int bi2 -> num_of_ratio (div_ratio_big_int r1 bi2)
+ | Ratio r2 -> num_of_ratio (div_ratio r1 r2) end
+;;
+
+let ( // ) = div_num
+
+let floor_num = function
+ Int i as n -> n
+| Big_int bi as n -> n
+| Ratio r -> num_of_big_int (floor_ratio r)
+
+(* Coercion with ratio type *)
+let ratio_of_num = function
+ Int i -> ratio_of_int i
+| Big_int bi -> ratio_of_big_int bi
+| Ratio r -> r
+;;
+
+(* Euclidean division and remainder. The specification is:
+
+ a = b * quo_num a b + mod_num a b
+ quo_num a b is an integer (Z)
+ 0 <= mod_num a b < |b|
+
+A correct but slow implementation is:
+
+ quo_num a b =
+ if b >= 0 then floor_num (div_num a b)
+ else minus_num (floor_num (div_num a (minus_num b)))
+
+ mod_num a b =
+ sub_num a (mult_num b (quo_num a b))
+
+ However, this definition is vastly inefficient (cf PR #3473):
+ we define here a better way of computing the same thing.
+
+ PR#6753: the previous implementation was based on
+ quo_num a b = floor_num (div_num a b)
+ which is incorrect for negative b.
+*)
+
+let quo_num n1 n2 =
+ match n1, n2 with
+ | Int i1, Int i2 ->
+ let q = i1 / i2 and r = i1 mod i2 in
+ Int (if r >= 0 then q else if i2 > 0 then q - 1 else q + 1)
+ | Int i1, Big_int bi2 ->
+ num_of_big_int (div_big_int (big_int_of_int i1) bi2)
+ | Int i1, Ratio r2 ->
+ num_of_big_int (report_sign_ratio r2
+ (floor_ratio (div_int_ratio i1 (abs_ratio r2))))
+ | Big_int bi1, Int i2 ->
+ num_of_big_int (div_big_int bi1 (big_int_of_int i2))
+ | Big_int bi1, Big_int bi2 ->
+ num_of_big_int (div_big_int bi1 bi2)
+ | Big_int bi1, Ratio r2 ->
+ num_of_big_int (report_sign_ratio r2
+ (floor_ratio (div_big_int_ratio bi1 (abs_ratio r2))))
+ | Ratio r1, _ ->
+ let r2 = ratio_of_num n2 in
+ num_of_big_int (report_sign_ratio r2
+ (floor_ratio (div_ratio r1 (abs_ratio r2))))
+
+let mod_num n1 n2 =
+ match n1, n2 with
+ | Int i1, Int i2 ->
+ let r = i1 mod i2 in
+ Int (if r >= 0 then r else if i2 > 0 then r + i2 else r - i2)
+ | Int i1, Big_int bi2 ->
+ num_of_big_int (mod_big_int (big_int_of_int i1) bi2)
+ | Big_int bi1, Int i2 ->
+ num_of_big_int (mod_big_int bi1 (big_int_of_int i2))
+ | Big_int bi1, Big_int bi2 ->
+ num_of_big_int (mod_big_int bi1 bi2)
+ | _, _ ->
+ sub_num n1 (mult_num n2 (quo_num n1 n2))
+
+let power_num_int a b = match (a,b) with
+ ((Int i), n) ->
+ (match sign_int n with
+ 0 -> Int 1
+ | 1 -> num_of_big_int (power_int_positive_int i n)
+ | _ -> Ratio (create_normalized_ratio
+ unit_big_int (power_int_positive_int i (-n))))
+| ((Big_int bi), n) ->
+ (match sign_int n with
+ 0 -> Int 1
+ | 1 -> num_of_big_int (power_big_int_positive_int bi n)
+ | _ -> Ratio (create_normalized_ratio
+ unit_big_int (power_big_int_positive_int bi (-n))))
+| ((Ratio r), n) ->
+ (match sign_int n with
+ 0 -> Int 1
+ | 1 -> Ratio (power_ratio_positive_int r n)
+ | _ -> Ratio (power_ratio_positive_int
+ (inverse_ratio r) (-n)))
+
+let power_num_big_int a b = match (a,b) with
+ ((Int i), n) ->
+ (match sign_big_int n with
+ 0 -> Int 1
+ | 1 -> num_of_big_int (power_int_positive_big_int i n)
+ | _ -> Ratio (create_normalized_ratio
+ unit_big_int
+ (power_int_positive_big_int i (minus_big_int n))))
+| ((Big_int bi), n) ->
+ (match sign_big_int n with
+ 0 -> Int 1
+ | 1 -> num_of_big_int (power_big_int_positive_big_int bi n)
+ | _ -> Ratio (create_normalized_ratio
+ unit_big_int
+ (power_big_int_positive_big_int bi (minus_big_int n))))
+| ((Ratio r), n) ->
+ (match sign_big_int n with
+ 0 -> Int 1
+ | 1 -> Ratio (power_ratio_positive_big_int r n)
+ | _ -> Ratio (power_ratio_positive_big_int
+ (inverse_ratio r) (minus_big_int n)))
+
+let power_num a b = match (a,b) with
+ (n, (Int i)) -> power_num_int n i
+| (n, (Big_int bi)) -> power_num_big_int n bi
+| _ -> invalid_arg "power_num"
+
+let ( **/ ) = power_num
+
+let is_integer_num = function
+ Int _ -> true
+| Big_int _ -> true
+| Ratio r -> is_integer_ratio r
+
+(* integer_num, floor_num, round_num, ceiling_num rendent des nums *)
+let integer_num = function
+ Int i as n -> n
+| Big_int bi as n -> n
+| Ratio r -> num_of_big_int (integer_ratio r)
+
+and round_num = function
+ Int i as n -> n
+| Big_int bi as n -> n
+| Ratio r -> num_of_big_int (round_ratio r)
+
+and ceiling_num = function
+ Int i as n -> n
+| Big_int bi as n -> n
+| Ratio r -> num_of_big_int (ceiling_ratio r)
+
+(* Comparisons on nums *)
+
+let sign_num = function
+ Int i -> sign_int i
+| Big_int bi -> sign_big_int bi
+| Ratio r -> sign_ratio r
+
+let eq_num a b = match (a,b) with
+ ((Int int1), (Int int2)) -> int1 = int2
+
+| ((Int i), (Big_int bi)) -> eq_big_int (big_int_of_int i) bi
+| ((Big_int bi), (Int i)) -> eq_big_int (big_int_of_int i) bi
+
+| ((Int i), (Ratio r)) -> eq_big_int_ratio (big_int_of_int i) r
+| ((Ratio r), (Int i)) -> eq_big_int_ratio (big_int_of_int i) r
+
+| ((Big_int bi1), (Big_int bi2)) -> eq_big_int bi1 bi2
+
+| ((Big_int bi), (Ratio r)) -> eq_big_int_ratio bi r
+| ((Ratio r), (Big_int bi)) -> eq_big_int_ratio bi r
+
+| ((Ratio r1), (Ratio r2)) -> eq_ratio r1 r2
+
+let ( =/ ) = eq_num
+
+let ( <>/ ) a b = not(eq_num a b)
+
+let compare_num a b = match (a,b) with
+ ((Int int1), (Int int2)) -> compare_int int1 int2
+
+| ((Int i), (Big_int bi)) -> compare_big_int (big_int_of_int i) bi
+| ((Big_int bi), (Int i)) -> compare_big_int bi (big_int_of_int i)
+
+| ((Int i), (Ratio r)) -> compare_big_int_ratio (big_int_of_int i) r
+| ((Ratio r), (Int i)) -> -(compare_big_int_ratio (big_int_of_int i) r)
+
+| ((Big_int bi1), (Big_int bi2)) -> compare_big_int bi1 bi2
+
+| ((Big_int bi), (Ratio r)) -> compare_big_int_ratio bi r
+| ((Ratio r), (Big_int bi)) -> -(compare_big_int_ratio bi r)
+
+| ((Ratio r1), (Ratio r2)) -> compare_ratio r1 r2
+
+let lt_num num1 num2 = compare_num num1 num2 < 0
+and le_num num1 num2 = compare_num num1 num2 <= 0
+and gt_num num1 num2 = compare_num num1 num2 > 0
+and ge_num num1 num2 = compare_num num1 num2 >= 0
+
+let ( </ ) = lt_num
+and ( <=/ ) = le_num
+and ( >/ ) = gt_num
+and ( >=/ ) = ge_num
+
+let max_num num1 num2 = if lt_num num1 num2 then num2 else num1
+and min_num num1 num2 = if gt_num num1 num2 then num2 else num1
+
+(* Coercions with basic types *)
+
+(* Coercion with int type *)
+let int_of_num = function
+ Int i -> i
+| Big_int bi -> int_of_big_int bi
+| Ratio r -> int_of_ratio r
+
+and num_of_int i =
+ if i = monster_int
+ then Big_int (big_int_of_int i)
+ else Int i
+
+(* Coercion with nat type *)
+let nat_of_num = function
+ Int i -> nat_of_int i
+| Big_int bi -> nat_of_big_int bi
+| Ratio r -> nat_of_ratio r
+
+and num_of_nat nat =
+ if (is_nat_int nat 0 (length_nat nat))
+ then Int (nth_digit_nat nat 0)
+ else Big_int (big_int_of_nat nat)
+
+(* Coercion with big_int type *)
+let big_int_of_num = function
+ Int i -> big_int_of_int i
+| Big_int bi -> bi
+| Ratio r -> big_int_of_ratio r
+
+let string_of_big_int_for_num bi =
+ if !approx_printing_flag
+ then approx_big_int !floating_precision bi
+ else string_of_big_int bi
+
+(* Coercion with string type *)
+
+(* XL: suppression de sys_string_of_num *)
+
+let string_of_normalized_num = function
+ Int i -> string_of_int i
+| Big_int bi -> string_of_big_int_for_num bi
+| Ratio r -> string_of_ratio r
+let string_of_num n =
+ string_of_normalized_num (cautious_normalize_num_when_printing n)
+let num_of_string s =
+ try
+ let flag = !normalize_ratio_flag in
+ normalize_ratio_flag := true;
+ let r = ratio_of_string s in
+ normalize_ratio_flag := flag;
+ if eq_big_int (denominator_ratio r) unit_big_int
+ then num_of_big_int (numerator_ratio r)
+ else Ratio r
+ with Failure _ ->
+ failwith "num_of_string"
+
+(* Coercion with float type *)
+let float_of_num = function
+ Int i -> float i
+| Big_int bi -> float_of_big_int bi
+| Ratio r -> float_of_ratio r
+
+(* XL: suppression de num_of_float, float_num *)
+
+let succ_num = function
+ Int i -> if i = biggest_int
+ then Big_int (succ_big_int (big_int_of_int i))
+ else Int (succ i)
+| Big_int bi -> num_of_big_int (succ_big_int bi)
+| Ratio r -> Ratio (add_int_ratio 1 r)
+
+and pred_num = function
+ Int i -> if i = monster_int
+ then Big_int (pred_big_int (big_int_of_int i))
+ else Int (pred i)
+| Big_int bi -> num_of_big_int (pred_big_int bi)
+| Ratio r -> Ratio (add_int_ratio (-1) r)
+
+let abs_num = function
+ Int i -> if i = monster_int
+ then Big_int (minus_big_int (big_int_of_int i))
+ else Int (abs i)
+ | Big_int bi -> Big_int (abs_big_int bi)
+ | Ratio r -> Ratio (abs_ratio r)
+
+let approx_num_fix n num = approx_ratio_fix n (ratio_of_num num)
+and approx_num_exp n num = approx_ratio_exp n (ratio_of_num num)
+
+let incr_num r = r := succ_num !r
+and decr_num r = r := pred_num !r
diff --git a/otherlibs/num/num.mli b/otherlibs/num/num.mli
new file mode 100644
index 0000000000..6425085e63
--- /dev/null
+++ b/otherlibs/num/num.mli
@@ -0,0 +1,170 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Operation on arbitrary-precision numbers.
+
+ Numbers (type [num]) are arbitrary-precision rational numbers,
+ plus the special elements [1/0] (infinity) and [0/0] (undefined).
+*)
+
+open Nat
+open Big_int
+open Ratio
+
+(** The type of numbers. *)
+type num =
+ Int of int
+ | Big_int of big_int
+ | Ratio of ratio
+
+
+(** {6 Arithmetic operations} *)
+
+
+val ( +/ ) : num -> num -> num
+(** Same as {!Num.add_num}.*)
+
+val add_num : num -> num -> num
+(** Addition *)
+
+val minus_num : num -> num
+(** Unary negation. *)
+
+val ( -/ ) : num -> num -> num
+(** Same as {!Num.sub_num}.*)
+
+val sub_num : num -> num -> num
+(** Subtraction *)
+
+val ( */ ) : num -> num -> num
+(** Same as {!Num.mult_num}.*)
+
+val mult_num : num -> num -> num
+(** Multiplication *)
+
+val square_num : num -> num
+(** Squaring *)
+
+val ( // ) : num -> num -> num
+(** Same as {!Num.div_num}.*)
+
+val div_num : num -> num -> num
+(** Division *)
+
+val quo_num : num -> num -> num
+(** Euclidean division: quotient. *)
+
+val mod_num : num -> num -> num
+(** Euclidean division: remainder. *)
+
+val ( **/ ) : num -> num -> num
+(** Same as {!Num.power_num}. *)
+
+val power_num : num -> num -> num
+(** Exponentiation *)
+
+val abs_num : num -> num
+(** Absolute value. *)
+
+val succ_num : num -> num
+(** [succ n] is [n+1] *)
+
+val pred_num : num -> num
+(** [pred n] is [n-1] *)
+
+val incr_num : num ref -> unit
+(** [incr r] is [r:=!r+1], where [r] is a reference to a number. *)
+
+val decr_num : num ref -> unit
+(** [decr r] is [r:=!r-1], where [r] is a reference to a number. *)
+
+val is_integer_num : num -> bool
+(** Test if a number is an integer *)
+
+(** The four following functions approximate a number by an integer : *)
+
+val integer_num : num -> num
+(** [integer_num n] returns the integer closest to [n]. In case of ties,
+ rounds towards zero. *)
+
+val floor_num : num -> num
+(** [floor_num n] returns the largest integer smaller or equal to [n]. *)
+
+val round_num : num -> num
+(** [round_num n] returns the integer closest to [n]. In case of ties,
+ rounds off zero. *)
+
+val ceiling_num : num -> num
+(** [ceiling_num n] returns the smallest integer bigger or equal to [n]. *)
+
+
+val sign_num : num -> int
+(** Return [-1], [0] or [1] according to the sign of the argument. *)
+
+(** {7 Comparisons between numbers} *)
+
+val ( =/ ) : num -> num -> bool
+val ( </ ) : num -> num -> bool
+val ( >/ ) : num -> num -> bool
+val ( <=/ ) : num -> num -> bool
+val ( >=/ ) : num -> num -> bool
+val ( <>/ ) : num -> num -> bool
+val eq_num : num -> num -> bool
+val lt_num : num -> num -> bool
+val le_num : num -> num -> bool
+val gt_num : num -> num -> bool
+val ge_num : num -> num -> bool
+
+val compare_num : num -> num -> int
+(** Return [-1], [0] or [1] if the first argument is less than,
+ equal to, or greater than the second argument. *)
+
+val max_num : num -> num -> num
+(** Return the greater of the two arguments. *)
+
+val min_num : num -> num -> num
+(** Return the smaller of the two arguments. *)
+
+
+(** {6 Coercions with strings} *)
+
+val string_of_num : num -> string
+(** Convert a number to a string, using fractional notation. *)
+
+val approx_num_fix : int -> num -> string
+(** See {!Num.approx_num_exp}.*)
+
+val approx_num_exp : int -> num -> string
+(** Approximate a number by a decimal. The first argument is the
+ required precision. The second argument is the number to
+ approximate. {!Num.approx_num_fix} uses decimal notation; the first
+ argument is the number of digits after the decimal point.
+ [approx_num_exp] uses scientific (exponential) notation; the
+ first argument is the number of digits in the mantissa. *)
+
+val num_of_string : string -> num
+(** Convert a string to a number.
+ Raise [Failure "num_of_string"] if the given string is not
+ a valid representation of an integer *)
+
+(** {6 Coercions between numerical types} *)
+
+val int_of_num : num -> int
+val num_of_int : int -> num
+val nat_of_num : num -> nat
+val num_of_nat : nat -> num
+val num_of_big_int : big_int -> num
+val big_int_of_num : num -> big_int
+val ratio_of_num : num -> ratio
+val num_of_ratio : ratio -> num
+val float_of_num : num -> float
diff --git a/otherlibs/num/nums.mllib b/otherlibs/num/nums.mllib
new file mode 100644
index 0000000000..8db1683860
--- /dev/null
+++ b/otherlibs/num/nums.mllib
@@ -0,0 +1 @@
+Int_misc Nat Big_int Arith_flags Ratio Num Arith_status
diff --git a/otherlibs/num/ratio.ml b/otherlibs/num/ratio.ml
new file mode 100644
index 0000000000..3dbbbc985d
--- /dev/null
+++ b/otherlibs/num/ratio.ml
@@ -0,0 +1,616 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Int_misc
+open Nat
+open Big_int
+open Arith_flags
+
+(* Definition of the type ratio :
+ Conventions :
+ - the denominator is always a positive number
+ - the sign of n/0 is the sign of n
+These convention is automatically respected when a ratio is created with
+the create_ratio primitive
+*)
+
+type ratio = { mutable numerator : big_int;
+ mutable denominator : big_int;
+ mutable normalized : bool}
+
+let failwith_zero name =
+ let s = "infinite or undefined rational number" in
+ failwith (if String.length name = 0 then s else name ^ " " ^ s)
+
+let numerator_ratio r = r.numerator
+and denominator_ratio r = r.denominator
+
+let null_denominator r = sign_big_int r.denominator = 0
+
+let verify_null_denominator r =
+ if sign_big_int r.denominator = 0
+ then (if !error_when_null_denominator_flag
+ then (failwith_zero "")
+ else true)
+ else false
+
+let sign_ratio r = sign_big_int r.numerator
+
+(* Physical normalization of rational numbers *)
+(* 1/0, 0/0 and -1/0 are the normalized forms for n/0 numbers *)
+let normalize_ratio r =
+ if r.normalized then r
+ else if verify_null_denominator r then begin
+ r.numerator <- big_int_of_int (sign_big_int r.numerator);
+ r.normalized <- true;
+ r
+ end else begin
+ let p = gcd_big_int r.numerator r.denominator in
+ if eq_big_int p unit_big_int
+ then begin
+ r.normalized <- true; r
+ end else begin
+ r.numerator <- div_big_int (r.numerator) p;
+ r.denominator <- div_big_int (r.denominator) p;
+ r.normalized <- true; r
+ end
+ end
+
+let cautious_normalize_ratio r =
+ if (!normalize_ratio_flag) then (normalize_ratio r) else r
+
+let cautious_normalize_ratio_when_printing r =
+ if (!normalize_ratio_when_printing_flag) then (normalize_ratio r) else r
+
+let create_ratio bi1 bi2 =
+ match sign_big_int bi2 with
+ -1 -> cautious_normalize_ratio
+ { numerator = minus_big_int bi1;
+ denominator = minus_big_int bi2;
+ normalized = false }
+ | 0 -> if !error_when_null_denominator_flag
+ then (failwith_zero "create_ratio")
+ else cautious_normalize_ratio
+ { numerator = bi1; denominator = bi2; normalized = false }
+ | _ -> cautious_normalize_ratio
+ { numerator = bi1; denominator = bi2; normalized = false }
+
+let create_normalized_ratio bi1 bi2 =
+ match sign_big_int bi2 with
+ -1 -> { numerator = minus_big_int bi1;
+ denominator = minus_big_int bi2;
+ normalized = true }
+| 0 -> if !error_when_null_denominator_flag
+ then failwith_zero "create_normalized_ratio"
+ else { numerator = bi1; denominator = bi2; normalized = true }
+| _ -> { numerator = bi1; denominator = bi2; normalized = true }
+
+let is_normalized_ratio r = r.normalized
+
+let report_sign_ratio r bi =
+ if sign_ratio r = -1
+ then minus_big_int bi
+ else bi
+
+let abs_ratio r =
+ { numerator = abs_big_int r.numerator;
+ denominator = r.denominator;
+ normalized = r.normalized }
+
+let is_integer_ratio r =
+ eq_big_int ((normalize_ratio r).denominator) unit_big_int
+
+(* Operations on rational numbers *)
+
+let add_ratio r1 r2 =
+ if !normalize_ratio_flag then begin
+ let p = gcd_big_int ((normalize_ratio r1).denominator)
+ ((normalize_ratio r2).denominator) in
+ if eq_big_int p unit_big_int then
+ {numerator = add_big_int (mult_big_int (r1.numerator) r2.denominator)
+ (mult_big_int (r2.numerator) r1.denominator);
+ denominator = mult_big_int (r1.denominator) r2.denominator;
+ normalized = true}
+ else begin
+ let d1 = div_big_int (r1.denominator) p
+ and d2 = div_big_int (r2.denominator) p in
+ let n = add_big_int (mult_big_int (r1.numerator) d2)
+ (mult_big_int d1 r2.numerator) in
+ let p' = gcd_big_int n p in
+ { numerator = div_big_int n p';
+ denominator = mult_big_int d1 (div_big_int (r2.denominator) p');
+ normalized = true }
+ end
+ end else
+ { numerator = add_big_int (mult_big_int (r1.numerator) r2.denominator)
+ (mult_big_int (r1.denominator) r2.numerator);
+ denominator = mult_big_int (r1.denominator) r2.denominator;
+ normalized = false }
+
+let minus_ratio r =
+ { numerator = minus_big_int (r.numerator);
+ denominator = r.denominator;
+ normalized = r.normalized }
+
+let add_int_ratio i r =
+ ignore (cautious_normalize_ratio r);
+ { numerator = add_big_int (mult_int_big_int i r.denominator) r.numerator;
+ denominator = r.denominator;
+ normalized = r.normalized }
+
+let add_big_int_ratio bi r =
+ ignore (cautious_normalize_ratio r);
+ { numerator = add_big_int (mult_big_int bi r.denominator) r.numerator ;
+ denominator = r.denominator;
+ normalized = r.normalized }
+
+let sub_ratio r1 r2 = add_ratio r1 (minus_ratio r2)
+
+let mult_ratio r1 r2 =
+ if !normalize_ratio_flag then begin
+ let p1 = gcd_big_int ((normalize_ratio r1).numerator)
+ ((normalize_ratio r2).denominator)
+ and p2 = gcd_big_int (r2.numerator) r1.denominator in
+ let (n1, d2) =
+ if eq_big_int p1 unit_big_int
+ then (r1.numerator, r2.denominator)
+ else (div_big_int (r1.numerator) p1, div_big_int (r2.denominator) p1)
+ and (n2, d1) =
+ if eq_big_int p2 unit_big_int
+ then (r2.numerator, r1.denominator)
+ else (div_big_int r2.numerator p2, div_big_int r1.denominator p2) in
+ { numerator = mult_big_int n1 n2;
+ denominator = mult_big_int d1 d2;
+ normalized = true }
+ end else
+ { numerator = mult_big_int (r1.numerator) r2.numerator;
+ denominator = mult_big_int (r1.denominator) r2.denominator;
+ normalized = false }
+
+let mult_int_ratio i r =
+ if !normalize_ratio_flag then
+ begin
+ let p = gcd_big_int ((normalize_ratio r).denominator) (big_int_of_int i) in
+ if eq_big_int p unit_big_int
+ then { numerator = mult_big_int (big_int_of_int i) r.numerator;
+ denominator = r.denominator;
+ normalized = true }
+ else { numerator = mult_big_int (div_big_int (big_int_of_int i) p)
+ r.numerator;
+ denominator = div_big_int (r.denominator) p;
+ normalized = true }
+ end
+ else
+ { numerator = mult_int_big_int i r.numerator;
+ denominator = r.denominator;
+ normalized = false }
+
+let mult_big_int_ratio bi r =
+ if !normalize_ratio_flag then
+ begin
+ let p = gcd_big_int ((normalize_ratio r).denominator) bi in
+ if eq_big_int p unit_big_int
+ then { numerator = mult_big_int bi r.numerator;
+ denominator = r.denominator;
+ normalized = true }
+ else { numerator = mult_big_int (div_big_int bi p) r.numerator;
+ denominator = div_big_int (r.denominator) p;
+ normalized = true }
+ end
+ else
+ { numerator = mult_big_int bi r.numerator;
+ denominator = r.denominator;
+ normalized = false }
+
+let square_ratio r =
+ ignore (cautious_normalize_ratio r);
+ { numerator = square_big_int r.numerator;
+ denominator = square_big_int r.denominator;
+ normalized = r.normalized }
+
+let inverse_ratio r =
+ if !error_when_null_denominator_flag && (sign_big_int r.numerator) = 0
+ then failwith_zero "inverse_ratio"
+ else {numerator = report_sign_ratio r r.denominator;
+ denominator = abs_big_int r.numerator;
+ normalized = r.normalized}
+
+let div_ratio r1 r2 =
+ mult_ratio r1 (inverse_ratio r2)
+
+(* Integer part of a rational number *)
+(* Odd function *)
+let integer_ratio r =
+ if null_denominator r then failwith_zero "integer_ratio"
+ else if sign_ratio r = 0 then zero_big_int
+ else report_sign_ratio r (div_big_int (abs_big_int r.numerator)
+ (abs_big_int r.denominator))
+
+(* Floor of a rational number *)
+(* Always less or equal to r *)
+let floor_ratio r =
+ ignore (verify_null_denominator r);
+ div_big_int (r.numerator) r.denominator
+
+(* Round of a rational number *)
+(* Odd function, 1/2 -> 1 *)
+let round_ratio r =
+ ignore (verify_null_denominator r);
+ let abs_num = abs_big_int r.numerator in
+ let bi = div_big_int abs_num r.denominator in
+ report_sign_ratio r
+ (if sign_big_int
+ (sub_big_int
+ (mult_int_big_int
+ 2
+ (sub_big_int abs_num (mult_big_int (r.denominator) bi)))
+ r.denominator) = -1
+ then bi
+ else succ_big_int bi)
+
+let ceiling_ratio r =
+ if (is_integer_ratio r)
+ then r.numerator
+ else succ_big_int (floor_ratio r)
+
+
+(* Comparison operators on rational numbers *)
+let eq_ratio r1 r2 =
+ ignore (normalize_ratio r1);
+ ignore (normalize_ratio r2);
+ eq_big_int (r1.numerator) r2.numerator &&
+ eq_big_int (r1.denominator) r2.denominator
+
+let compare_ratio r1 r2 =
+ if verify_null_denominator r1 then
+ let sign_num_r1 = sign_big_int r1.numerator in
+ if (verify_null_denominator r2)
+ then
+ let sign_num_r2 = sign_big_int r2.numerator in
+ if sign_num_r1 = 1 && sign_num_r2 = -1 then 1
+ else if sign_num_r1 = -1 && sign_num_r2 = 1 then -1
+ else 0
+ else sign_num_r1
+ else if verify_null_denominator r2 then
+ -(sign_big_int r2.numerator)
+ else match compare_int (sign_big_int r1.numerator)
+ (sign_big_int r2.numerator) with
+ 1 -> 1
+ | -1 -> -1
+ | _ -> if eq_big_int (r1.denominator) r2.denominator
+ then compare_big_int (r1.numerator) r2.numerator
+ else compare_big_int
+ (mult_big_int (r1.numerator) r2.denominator)
+ (mult_big_int (r1.denominator) r2.numerator)
+
+
+let lt_ratio r1 r2 = compare_ratio r1 r2 < 0
+and le_ratio r1 r2 = compare_ratio r1 r2 <= 0
+and gt_ratio r1 r2 = compare_ratio r1 r2 > 0
+and ge_ratio r1 r2 = compare_ratio r1 r2 >= 0
+
+let max_ratio r1 r2 = if lt_ratio r1 r2 then r2 else r1
+and min_ratio r1 r2 = if gt_ratio r1 r2 then r2 else r1
+
+let eq_big_int_ratio bi r =
+ (is_integer_ratio r) && eq_big_int bi r.numerator
+
+let compare_big_int_ratio bi r =
+ ignore (normalize_ratio r);
+ if (verify_null_denominator r)
+ then -(sign_big_int r.numerator)
+ else compare_big_int (mult_big_int bi r.denominator) r.numerator
+
+let lt_big_int_ratio bi r = compare_big_int_ratio bi r < 0
+and le_big_int_ratio bi r = compare_big_int_ratio bi r <= 0
+and gt_big_int_ratio bi r = compare_big_int_ratio bi r > 0
+and ge_big_int_ratio bi r = compare_big_int_ratio bi r >= 0
+
+(* Coercions *)
+
+(* Coercions with type int *)
+let int_of_ratio r =
+ if ((is_integer_ratio r) && (is_int_big_int r.numerator))
+ then (int_of_big_int r.numerator)
+ else failwith "integer argument required"
+
+and ratio_of_int i =
+ { numerator = big_int_of_int i;
+ denominator = unit_big_int;
+ normalized = true }
+
+(* Coercions with type nat *)
+let ratio_of_nat nat =
+ { numerator = big_int_of_nat nat;
+ denominator = unit_big_int;
+ normalized = true }
+
+and nat_of_ratio r =
+ ignore (normalize_ratio r);
+ if not (is_integer_ratio r) then
+ failwith "nat_of_ratio"
+ else if sign_big_int r.numerator > -1 then
+ nat_of_big_int (r.numerator)
+ else failwith "nat_of_ratio"
+
+(* Coercions with type big_int *)
+let ratio_of_big_int bi =
+ { numerator = bi; denominator = unit_big_int; normalized = true }
+
+and big_int_of_ratio r =
+ ignore (normalize_ratio r);
+ if is_integer_ratio r
+ then r.numerator
+ else failwith "big_int_of_ratio"
+
+let div_int_ratio i r =
+ ignore (verify_null_denominator r);
+ mult_int_ratio i (inverse_ratio r)
+
+let div_ratio_int r i =
+ div_ratio r (ratio_of_int i)
+
+let div_big_int_ratio bi r =
+ ignore (verify_null_denominator r);
+ mult_big_int_ratio bi (inverse_ratio r)
+
+let div_ratio_big_int r bi =
+ div_ratio r (ratio_of_big_int bi)
+
+(* Functions on type string *)
+(* giving floating point approximations of rational numbers *)
+
+(* Compares strings that contains only digits, have the same length,
+ from index i to index i + l *)
+let rec compare_num_string s1 s2 i len =
+ if i >= len then 0 else
+ let c1 = int_of_char s1.[i]
+ and c2 = int_of_char s2.[i] in
+ match compare_int c1 c2 with
+ | 0 -> compare_num_string s1 s2 (succ i) len
+ | c -> c;;
+
+(* Position of the leading digit of the decimal expansion *)
+(* of a strictly positive rational number *)
+(* if the decimal expansion of a non null rational r is equal to *)
+(* sigma for k=-P to N of r_k*10^k then msd_ratio r = N *)
+(* Nota : for a big_int we have msd_ratio = nums_digits_big_int -1 *)
+
+(* Tests if s has only zeros characters from index i to index lim *)
+let rec only_zeros s i lim =
+ i >= lim || s.[i] == '0' && only_zeros s (succ i) lim;;
+
+(* Nota : for a big_int we have msd_ratio = nums_digits_big_int -1 *)
+let msd_ratio r =
+ ignore (cautious_normalize_ratio r);
+ if null_denominator r then failwith_zero "msd_ratio"
+ else if sign_big_int r.numerator == 0 then 0
+ else begin
+ let str_num = string_of_big_int r.numerator
+ and str_den = string_of_big_int r.denominator in
+ let size_num = String.length str_num
+ and size_den = String.length str_den in
+ let size_min = min size_num size_den in
+ let m = size_num - size_den in
+ let cmp = compare_num_string str_num str_den 0 size_min in
+ match cmp with
+ | 1 -> m
+ | -1 -> pred m
+ | _ ->
+ if m >= 0 then m else
+ if only_zeros str_den size_min size_den then m
+ else pred m
+ end
+;;
+
+(* Decimal approximations of rational numbers *)
+
+(* Approximation with fix decimal point *)
+(* This is an odd function and the last digit is round off *)
+(* Format integer_part . decimal_part_with_n_digits *)
+let approx_ratio_fix n r =
+ (* Don't need to normalize *)
+ if (null_denominator r) then failwith_zero "approx_ratio_fix"
+ else
+ let sign_r = sign_ratio r in
+ if sign_r = 0
+ then "+0" (* r = 0 *)
+ else
+ (* r.numerator and r.denominator are not null numbers
+ s1 contains one more digit than desired for the round off operation *)
+ if n >= 0 then begin
+ let s1 =
+ string_of_nat
+ (nat_of_big_int
+ (div_big_int
+ (base_power_big_int
+ 10 (succ n) (abs_big_int r.numerator))
+ r.denominator)) in
+ (* Round up and add 1 in front if needed *)
+ let s2 =
+ if round_futur_last_digit (Bytes.unsafe_of_string s1) 0
+ (String.length s1)
+ then "1" ^ s1
+ else s1 in
+ let l2 = String.length s2 - 1 in
+ (* if s2 without last digit is xxxxyyy with n 'yyy' digits:
+ <sign> xxxx . yyy
+ if s2 without last digit is yy with <= n digits:
+ <sign> 0 . 0yy *)
+ if l2 > n then begin
+ let s = Bytes.make (l2 + 2) '0' in
+ Bytes.set s 0 (if sign_r = -1 then '-' else '+');
+ String.blit s2 0 s 1 (l2 - n);
+ Bytes.set s (l2 - n + 1) '.';
+ String.blit s2 (l2 - n) s (l2 - n + 2) n;
+ Bytes.unsafe_to_string s
+ end else begin
+ let s = Bytes.make (n + 3) '0' in
+ Bytes.set s 0 (if sign_r = -1 then '-' else '+');
+ Bytes.set s 2 '.';
+ String.blit s2 0 s (n + 3 - l2) l2;
+ Bytes.unsafe_to_string s
+ end
+ end else begin
+ (* Dubious; what is this code supposed to do? *)
+ let s = string_of_big_int
+ (div_big_int
+ (abs_big_int r.numerator)
+ (base_power_big_int
+ 10 (-n) r.denominator)) in
+ let len = succ (String.length s) in
+ let s' = Bytes.make len '0' in
+ Bytes.set s' 0 (if sign_r = -1 then '-' else '+');
+ String.blit s 0 s' 1 (pred len);
+ Bytes.unsafe_to_string s'
+ end
+
+(* Number of digits of the decimal representation of an int *)
+let num_decimal_digits_int n =
+ String.length (string_of_int n)
+
+(* Approximation with floating decimal point *)
+(* This is an odd function and the last digit is round off *)
+(* Format (+/-)(0. n_first_digits e msd)/(1. n_zeros e (msd+1) *)
+let approx_ratio_exp n r =
+ (* Don't need to normalize *)
+ if (null_denominator r) then failwith_zero "approx_ratio_exp"
+ else if n <= 0 then invalid_arg "approx_ratio_exp"
+ else
+ let sign_r = sign_ratio r
+ and i = ref (n + 3) in
+ if sign_r = 0 then
+ String.concat "" ["+0."; String.make n '0'; "e0"]
+ else
+ let msd = msd_ratio (abs_ratio r) in
+ let k = n - msd in
+ let s =
+ (let nat = nat_of_big_int
+ (if k < 0
+ then
+ div_big_int (abs_big_int r.numerator)
+ (base_power_big_int 10 (- k)
+ r.denominator)
+ else
+ div_big_int (base_power_big_int
+ 10 k (abs_big_int r.numerator))
+ r.denominator) in
+ string_of_nat nat) in
+ if round_futur_last_digit (Bytes.unsafe_of_string s) 0
+ (String.length s)
+ then
+ let m = num_decimal_digits_int (succ msd) in
+ let str = Bytes.make (n + m + 4) '0' in
+ (String.blit (if sign_r = -1 then "-1." else "+1.") 0 str 0 3);
+ Bytes.set str !i ('e');
+ incr i;
+ (if m = 0
+ then Bytes.set str !i '0'
+ else String.blit (string_of_int (succ msd)) 0 str !i m);
+ Bytes.unsafe_to_string str
+ else
+ let m = num_decimal_digits_int (succ msd)
+ and p = n + 3 in
+ let str = Bytes.make (succ (m + p)) '0' in
+ (String.blit (if sign_r = -1 then "-0." else "+0.") 0 str 0 3);
+ (String.blit s 0 str 3 n);
+ Bytes.set str p 'e';
+ (if m = 0
+ then Bytes.set str (succ p) '0'
+ else (String.blit (string_of_int (succ msd)) 0 str (succ p) m));
+ Bytes.unsafe_to_string str
+
+(* String approximation of a rational with a fixed number of significant *)
+(* digits printed *)
+let float_of_rational_string r =
+ let s = approx_ratio_exp !floating_precision r in
+ if String.get s 0 = '+'
+ then (String.sub s 1 (pred (String.length s)))
+ else s
+
+(* Coercions with type string *)
+let string_of_ratio r =
+ ignore (cautious_normalize_ratio_when_printing r);
+ if !approx_printing_flag
+ then float_of_rational_string r
+ else string_of_big_int r.numerator ^ "/" ^ string_of_big_int r.denominator
+
+(* XL: j'ai puissamment simplifie "ratio_of_string" en virant la notation
+ scientifique. *)
+
+let ratio_of_string s =
+ try
+ let n = String.index s '/' in
+ create_ratio (sys_big_int_of_string s 0 n)
+ (sys_big_int_of_string s (n+1) (String.length s - n - 1))
+ with Not_found ->
+ { numerator = big_int_of_string s;
+ denominator = unit_big_int;
+ normalized = true }
+
+(* Coercion with type float *)
+
+let float_of_ratio r =
+ let p = r.numerator and q = r.denominator in
+ (* Special cases 0/0, 0/q and p/0 *)
+ if sign_big_int q = 0 then begin
+ match sign_big_int p with
+ | 0 -> nan
+ | 1 -> infinity
+ | -1 -> neg_infinity
+ | _ -> assert false
+ end
+ else if sign_big_int p = 0 then 0.0
+ else begin
+ let np = num_bits_big_int p and nq = num_bits_big_int q in
+ if np <= 53 && nq <= 53 then
+ (* p and q convert to floats exactly; use FP division to get the
+ correctly-rounded result. *)
+ Int64.to_float (int64_of_big_int p)
+ /. Int64.to_float (int64_of_big_int q)
+ else begin
+ let ap = abs_big_int p in
+ (* |p| is in [2^(np-1), 2^np)
+ q is in [2^(nq-1), 2^nq)
+ hence |p|/q is in (2^(np-nq-1), 2^(np-nq+1)).
+ We define n such that |p|/q*2^n is in [2^54, 2^56).
+ >= 2^54 so that the round to odd technique applies.
+ < 2^56 so that the integral part is representable as an int64. *)
+ let n = 55 - (np - nq) in
+ (* Scaling |p|/q by 2^n *)
+ let (p', q') =
+ if n >= 0
+ then (shift_left_big_int ap n, q)
+ else (ap, shift_left_big_int q (-n)) in
+ (* Euclidean division of p' by q' *)
+ let (quo, rem) = quomod_big_int p' q' in
+ (* quo is the integral part of |p|/q*2^n
+ rem/q' is the fractional part. *)
+ (* Round quo to float *)
+ let f = round_big_int_to_float quo (sign_big_int rem = 0) in
+ (* Apply exponent *)
+ let f = ldexp f (-n) in
+ (* Apply sign *)
+ if sign_big_int p < 0 then -. f else f
+ end
+ end
+
+(* XL: suppression de ratio_of_float *)
+
+let power_ratio_positive_int r n =
+ create_ratio (power_big_int_positive_int (r.numerator) n)
+ (power_big_int_positive_int (r.denominator) n)
+
+let power_ratio_positive_big_int r bi =
+ create_ratio (power_big_int_positive_big_int (r.numerator) bi)
+ (power_big_int_positive_big_int (r.denominator) bi)
diff --git a/otherlibs/num/ratio.mli b/otherlibs/num/ratio.mli
new file mode 100644
index 0000000000..7c9809f149
--- /dev/null
+++ b/otherlibs/num/ratio.mli
@@ -0,0 +1,91 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Operation on rational numbers.
+
+ This module is used to support the implementation of {!Num} and
+ should not be called directly. *)
+
+open Nat
+open Big_int
+
+(* Rationals (type [ratio]) are arbitrary-precision rational numbers,
+ plus the special elements [1/0] (infinity) and [0/0] (undefined).
+ In constrast with numbers (type [num]), the special cases of
+ small integers and big integers are not optimized specially. *)
+
+type ratio
+
+(**/**)
+
+val null_denominator : ratio -> bool
+val numerator_ratio : ratio -> big_int
+val denominator_ratio : ratio -> big_int
+val sign_ratio : ratio -> int
+val normalize_ratio : ratio -> ratio
+val cautious_normalize_ratio : ratio -> ratio
+val cautious_normalize_ratio_when_printing : ratio -> ratio
+val create_ratio : big_int -> big_int -> ratio (* assumes nothing *)
+val create_normalized_ratio : big_int -> big_int -> ratio
+ (* assumes normalized argument *)
+val is_normalized_ratio : ratio -> bool
+val report_sign_ratio : ratio -> big_int -> big_int
+val abs_ratio : ratio -> ratio
+val is_integer_ratio : ratio -> bool
+val add_ratio : ratio -> ratio -> ratio
+val minus_ratio : ratio -> ratio
+val add_int_ratio : int -> ratio -> ratio
+val add_big_int_ratio : big_int -> ratio -> ratio
+val sub_ratio : ratio -> ratio -> ratio
+val mult_ratio : ratio -> ratio -> ratio
+val mult_int_ratio : int -> ratio -> ratio
+val mult_big_int_ratio : big_int -> ratio -> ratio
+val square_ratio : ratio -> ratio
+val inverse_ratio : ratio -> ratio
+val div_ratio : ratio -> ratio -> ratio
+val integer_ratio : ratio -> big_int
+val floor_ratio : ratio -> big_int
+val round_ratio : ratio -> big_int
+val ceiling_ratio : ratio -> big_int
+val eq_ratio : ratio -> ratio -> bool
+val compare_ratio : ratio -> ratio -> int
+val lt_ratio : ratio -> ratio -> bool
+val le_ratio : ratio -> ratio -> bool
+val gt_ratio : ratio -> ratio -> bool
+val ge_ratio : ratio -> ratio -> bool
+val max_ratio : ratio -> ratio -> ratio
+val min_ratio : ratio -> ratio -> ratio
+val eq_big_int_ratio : big_int -> ratio -> bool
+val compare_big_int_ratio : big_int -> ratio -> int
+val lt_big_int_ratio : big_int -> ratio -> bool
+val le_big_int_ratio : big_int -> ratio -> bool
+val gt_big_int_ratio : big_int -> ratio -> bool
+val ge_big_int_ratio : big_int -> ratio -> bool
+val int_of_ratio : ratio -> int
+val ratio_of_int : int -> ratio
+val ratio_of_nat : nat -> ratio
+val nat_of_ratio : ratio -> nat
+val ratio_of_big_int : big_int -> ratio
+val big_int_of_ratio : ratio -> big_int
+val div_int_ratio : int -> ratio -> ratio
+val div_ratio_int : ratio -> int -> ratio
+val div_big_int_ratio : big_int -> ratio -> ratio
+val div_ratio_big_int : ratio -> big_int -> ratio
+val approx_ratio_fix : int -> ratio -> string
+val approx_ratio_exp : int -> ratio -> string
+val float_of_rational_string : ratio -> string
+val string_of_ratio : ratio -> string
+val ratio_of_string : string -> ratio
+val float_of_ratio : ratio -> float
+val power_ratio_positive_int : ratio -> int -> ratio
+val power_ratio_positive_big_int : ratio -> big_int -> ratio
diff --git a/otherlibs/str/.depend b/otherlibs/str/.depend
new file mode 100644
index 0000000000..1d224311c0
--- /dev/null
+++ b/otherlibs/str/.depend
@@ -0,0 +1,11 @@
+strstubs.o: strstubs.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h ../../byterun/caml/fail.h
+str.cmi :
+str.cmo : str.cmi
+str.cmx : str.cmi
diff --git a/otherlibs/str/Makefile b/otherlibs/str/Makefile
new file mode 100644
index 0000000000..93b2bf9539
--- /dev/null
+++ b/otherlibs/str/Makefile
@@ -0,0 +1,33 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Makefile for the str library
+
+
+LIBNAME=str
+COBJS=strstubs.$(O)
+CLIBNAME=camlstr
+CAMLOBJS=str.cmo
+
+include ../Makefile
+
+depend:
+
+str.cmo: str.cmi
+str.cmx: str.cmi
+
+depend:
+ $(CC) -MM $(CFLAGS) *.c > .depend
+ $(CAMLRUN) ../../tools/ocamldep *.mli *.ml >> .depend
+
+include .depend
diff --git a/otherlibs/str/Makefile.nt b/otherlibs/str/Makefile.nt
new file mode 100644
index 0000000000..3b3f51c961
--- /dev/null
+++ b/otherlibs/str/Makefile.nt
@@ -0,0 +1,26 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Makefile for the str library
+
+LIBNAME=str
+COBJS=strstubs.$(O)
+CLIBNAME=camlstr
+CAMLOBJS=str.cmo
+
+include ../Makefile.nt
+
+depend:
+
+str.cmo: str.cmi
+str.cmx: str.cmi
diff --git a/otherlibs/str/libstr.clib b/otherlibs/str/libstr.clib
new file mode 100644
index 0000000000..319e76017c
--- /dev/null
+++ b/otherlibs/str/libstr.clib
@@ -0,0 +1 @@
+strstubs.o
diff --git a/otherlibs/str/str.ml b/otherlibs/str/str.ml
new file mode 100644
index 0000000000..746f52570e
--- /dev/null
+++ b/otherlibs/str/str.ml
@@ -0,0 +1,754 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* In this module, [@ocaml.warnerror "-3"] is used in several places
+ that use deprecated functions to preserve legacy behavior.
+ It overrides -w @3 given on the command line. *)
+
+(** String utilities *)
+
+let string_before s n = String.sub s 0 n
+
+let string_after s n = String.sub s n (String.length s - n)
+
+let first_chars s n = String.sub s 0 n
+
+let last_chars s n = String.sub s (String.length s - n) n
+
+(** Representation of character sets **)
+
+module Charset =
+ struct
+ type t = bytes (* of length 32 *)
+
+ (*let empty = Bytes.make 32 '\000'*)
+ let full = Bytes.make 32 '\255'
+
+ let make_empty () = Bytes.make 32 '\000'
+
+ let add s c =
+ let i = Char.code c in
+ Bytes.set s (i lsr 3)
+ (Char.chr (Char.code (Bytes.get s (i lsr 3))
+ lor (1 lsl (i land 7))))
+
+ let add_range s c1 c2 =
+ for i = Char.code c1 to Char.code c2 do add s (Char.chr i) done
+
+ let singleton c =
+ let s = make_empty () in add s c; s
+
+ (*let range c1 c2 =
+ let s = make_empty () in add_range s c1 c2; s
+ *)
+ let complement s =
+ let r = Bytes.create 32 in
+ for i = 0 to 31 do
+ Bytes.set r i (Char.chr(Char.code (Bytes.get s i) lxor 0xFF))
+ done;
+ r
+
+ let union s1 s2 =
+ let r = Bytes.create 32 in
+ for i = 0 to 31 do
+ Bytes.set r i (Char.chr(Char.code (Bytes.get s1 i)
+ lor Char.code (Bytes.get s2 i)))
+ done;
+ r
+
+ let disjoint s1 s2 =
+ try
+ for i = 0 to 31 do
+ if Char.code (Bytes.get s1 i) land Char.code (Bytes.get s2 i)
+ <> 0
+ then raise Exit
+ done;
+ true
+ with Exit ->
+ false
+
+ let iter fn s =
+ for i = 0 to 31 do
+ let c = Char.code (Bytes.get s i) in
+ if c <> 0 then
+ for j = 0 to 7 do
+ if c land (1 lsl j) <> 0 then fn (Char.chr ((i lsl 3) + j))
+ done
+ done
+
+ let expand s =
+ let r = Bytes.make 256 '\000' in
+ iter (fun c -> Bytes.set r (Char.code c) '\001') s;
+ r
+
+ let fold_case s =
+ (let r = make_empty() in
+ iter (fun c -> add r (Char.lowercase c); add r (Char.uppercase c)) s;
+ r)[@ocaml.warnerror "-3"]
+
+ end
+
+(** Abstract syntax tree for regular expressions *)
+
+type re_syntax =
+ Char of char
+ | String of string
+ | CharClass of Charset.t * bool (* true = complemented, false = normal *)
+ | Seq of re_syntax list
+ | Alt of re_syntax * re_syntax
+ | Star of re_syntax
+ | Plus of re_syntax
+ | Option of re_syntax
+ | Group of int * re_syntax
+ | Refgroup of int
+ | Bol
+ | Eol
+ | Wordboundary
+
+(** Representation of compiled regular expressions *)
+
+type regexp = {
+ prog: int array; (* bytecode instructions *)
+ cpool: string array; (* constant pool (string literals) *)
+ normtable: string; (* case folding table (if any) *)
+ numgroups: int; (* number of \(...\) groups *)
+ numregisters: int; (* number of nullable Star or Plus *)
+ startchars: int (* index of set of starting chars, or -1 if none *)
+}
+
+(** Opcodes for bytecode instructions; see strstubs.c for description *)
+
+let op_CHAR = 0
+let op_CHARNORM = 1
+let op_STRING = 2
+let op_STRINGNORM = 3
+let op_CHARCLASS = 4
+let op_BOL = 5
+let op_EOL = 6
+let op_WORDBOUNDARY = 7
+let op_BEGGROUP = 8
+let op_ENDGROUP = 9
+let op_REFGROUP = 10
+let op_ACCEPT = 11
+let op_SIMPLEOPT = 12
+let op_SIMPLESTAR = 13
+let op_SIMPLEPLUS = 14
+let op_GOTO = 15
+let op_PUSHBACK = 16
+let op_SETMARK = 17
+let op_CHECKPROGRESS = 18
+
+(* Encoding of bytecode instructions *)
+
+let instr opc arg = opc lor (arg lsl 8)
+
+(* Computing relative displacements for GOTO and PUSHBACK instructions *)
+
+let displ dest from = dest - from - 1
+
+(** Compilation of a regular expression *)
+
+(* Determine if a regexp can match the empty string *)
+
+let rec is_nullable = function
+ Char c -> false
+ | String s -> s = ""
+ | CharClass(cl, cmpl) -> false
+ | Seq rl -> List.for_all is_nullable rl
+ | Alt (r1, r2) -> is_nullable r1 || is_nullable r2
+ | Star r -> true
+ | Plus r -> is_nullable r
+ | Option r -> true
+ | Group(n, r) -> is_nullable r
+ | Refgroup n -> true
+ | Bol -> true
+ | Eol -> true
+ | Wordboundary -> true
+
+(* first r returns a set of characters C such that:
+ for all string s, s matches r => the first character of s is in C.
+ For convenience, return Charset.full if r is nullable. *)
+
+let rec first = function
+ Char c -> Charset.singleton c
+ | String s -> if s = "" then Charset.full else Charset.singleton s.[0]
+ | CharClass(cl, cmpl) -> if cmpl then Charset.complement cl else cl
+ | Seq rl -> first_seq rl
+ | Alt (r1, r2) -> Charset.union (first r1) (first r2)
+ | Star r -> Charset.full
+ | Plus r -> first r
+ | Option r -> Charset.full
+ | Group(n, r) -> first r
+ | Refgroup n -> Charset.full
+ | Bol -> Charset.full
+ | Eol -> Charset.full
+ | Wordboundary -> Charset.full
+
+and first_seq = function
+ [] -> Charset.full
+ | (Bol | Eol | Wordboundary) :: rl -> first_seq rl
+ | Star r :: rl -> Charset.union (first r) (first_seq rl)
+ | Option r :: rl -> Charset.union (first r) (first_seq rl)
+ | r :: rl -> first r
+
+(* Transform a Char or CharClass regexp into a character class *)
+
+let charclass_of_regexp fold_case re =
+ let (cl1, compl) =
+ match re with
+ | Char c -> (Charset.singleton c, false)
+ | CharClass(cl, compl) -> (cl, compl)
+ | _ -> assert false in
+ let cl2 = if fold_case then Charset.fold_case cl1 else cl1 in
+ Bytes.to_string (if compl then Charset.complement cl2 else cl2)
+
+(* The case fold table: maps characters to their lowercase equivalent *)
+
+let fold_case_table =
+ (let t = Bytes.create 256 in
+ for i = 0 to 255 do Bytes.set t i (Char.lowercase(Char.chr i)) done;
+ Bytes.to_string t)[@ocaml.warnerror "-3"]
+
+module StringMap =
+ Map.Make(struct type t = string let compare (x:t) y = compare x y end)
+
+(* Compilation of a regular expression *)
+
+let compile fold_case re =
+
+ (* Instruction buffering *)
+ let prog = ref (Array.make 32 0)
+ and progpos = ref 0
+ and cpool = ref StringMap.empty
+ and cpoolpos = ref 0
+ and numgroups = ref 1
+ and numregs = ref 0 in
+ (* Add a new instruction *)
+ let emit_instr opc arg =
+ if !progpos >= Array.length !prog then begin
+ let newlen = ref (Array.length !prog) in
+ while !progpos >= !newlen do newlen := !newlen * 2 done;
+ let nprog = Array.make !newlen 0 in
+ Array.blit !prog 0 nprog 0 (Array.length !prog);
+ prog := nprog
+ end;
+ (!prog).(!progpos) <- (instr opc arg);
+ incr progpos in
+ (* Reserve an instruction slot and return its position *)
+ let emit_hole () =
+ let p = !progpos in incr progpos; p in
+ (* Fill a reserved instruction slot with a GOTO or PUSHBACK instruction *)
+ let patch_instr pos opc dest =
+ (!prog).(pos) <- (instr opc (displ dest pos)) in
+ (* Return the cpool index for the given string, adding it if not
+ already there *)
+ let cpool_index s =
+ try
+ StringMap.find s !cpool
+ with Not_found ->
+ let p = !cpoolpos in
+ cpool := StringMap.add s p !cpool;
+ incr cpoolpos;
+ p in
+ (* Allocate fresh register if regexp is nullable *)
+ let allocate_register_if_nullable r =
+ if is_nullable r then begin
+ let n = !numregs in
+ if n >= 64 then failwith "too many r* or r+ where r is nullable";
+ incr numregs;
+ n
+ end else
+ -1 in
+ (* Main recursive compilation function *)
+ let rec emit_code = function
+ Char c ->
+ if fold_case then
+ emit_instr op_CHARNORM (Char.code (Char.lowercase c))
+ [@ocaml.warnerror "-3"]
+ else
+ emit_instr op_CHAR (Char.code c)
+ | String s ->
+ begin match String.length s with
+ 0 -> ()
+ | 1 ->
+ if fold_case then
+ emit_instr op_CHARNORM (Char.code (Char.lowercase s.[0]))
+ [@ocaml.warnerror "-3"]
+ else
+ emit_instr op_CHAR (Char.code s.[0])
+ | _ ->
+ try
+ (* null characters are not accepted by the STRING* instructions;
+ if one is found, split string at null character *)
+ let i = String.index s '\000' in
+ emit_code (String (string_before s i));
+ emit_instr op_CHAR 0;
+ emit_code (String (string_after s (i+1)))
+ with Not_found ->
+ if fold_case then
+ emit_instr op_STRINGNORM (cpool_index (String.lowercase s))
+ [@ocaml.warnerror "-3"]
+ else
+ emit_instr op_STRING (cpool_index s)
+ end
+ | CharClass(cl, compl) ->
+ let cl1 = if fold_case then Charset.fold_case cl else cl in
+ let cl2 = if compl then Charset.complement cl1 else cl1 in
+ emit_instr op_CHARCLASS (cpool_index (Bytes.to_string cl2))
+ | Seq rl ->
+ emit_seq_code rl
+ | Alt(r1, r2) ->
+ (* PUSHBACK lbl1
+ <match r1>
+ GOTO lbl2
+ lbl1: <match r2>
+ lbl2: ... *)
+ let pos_pushback = emit_hole() in
+ emit_code r1;
+ let pos_goto_end = emit_hole() in
+ let lbl1 = !progpos in
+ emit_code r2;
+ let lbl2 = !progpos in
+ patch_instr pos_pushback op_PUSHBACK lbl1;
+ patch_instr pos_goto_end op_GOTO lbl2
+ | Star r ->
+ (* Implement longest match semantics for compatibility with old Str *)
+ (* General translation:
+ lbl1: PUSHBACK lbl2
+ SETMARK regno
+ <match r>
+ CHECKPROGRESS regno
+ GOTO lbl1
+ lbl2:
+ If r cannot match the empty string, code can be simplified:
+ lbl1: PUSHBACK lbl2
+ <match r>
+ GOTO lbl1
+ lbl2:
+ *)
+ let regno = allocate_register_if_nullable r in
+ let lbl1 = emit_hole() in
+ if regno >= 0 then emit_instr op_SETMARK regno;
+ emit_code r;
+ if regno >= 0 then emit_instr op_CHECKPROGRESS regno;
+ emit_instr op_GOTO (displ lbl1 !progpos);
+ let lbl2 = !progpos in
+ patch_instr lbl1 op_PUSHBACK lbl2
+ | Plus r ->
+ (* Implement longest match semantics for compatibility with old Str *)
+ (* General translation:
+ lbl1: <match r>
+ CHECKPROGRESS regno
+ PUSHBACK lbl2
+ SETMARK regno
+ GOTO lbl1
+ lbl2:
+ If r cannot match the empty string, code can be simplified:
+ lbl1: <match r>
+ PUSHBACK lbl2
+ GOTO_PLUS lbl1
+ lbl2:
+ *)
+ let regno = allocate_register_if_nullable r in
+ let lbl1 = !progpos in
+ emit_code r;
+ if regno >= 0 then emit_instr op_CHECKPROGRESS regno;
+ let pos_pushback = emit_hole() in
+ if regno >= 0 then emit_instr op_SETMARK regno;
+ emit_instr op_GOTO (displ lbl1 !progpos);
+ let lbl2 = !progpos in
+ patch_instr pos_pushback op_PUSHBACK lbl2
+ | Option r ->
+ (* Implement longest match semantics for compatibility with old Str *)
+ (* PUSHBACK lbl
+ <match r>
+ lbl:
+ *)
+ let pos_pushback = emit_hole() in
+ emit_code r;
+ let lbl = !progpos in
+ patch_instr pos_pushback op_PUSHBACK lbl
+ | Group(n, r) ->
+ if n >= 32 then failwith "too many \\(...\\) groups";
+ emit_instr op_BEGGROUP n;
+ emit_code r;
+ emit_instr op_ENDGROUP n;
+ numgroups := max !numgroups (n+1)
+ | Refgroup n ->
+ emit_instr op_REFGROUP n
+ | Bol ->
+ emit_instr op_BOL 0
+ | Eol ->
+ emit_instr op_EOL 0
+ | Wordboundary ->
+ emit_instr op_WORDBOUNDARY 0
+
+ and emit_seq_code = function
+ [] -> ()
+ | Star(Char _ | CharClass _ as r) :: rl
+ when disjoint_modulo_case (first r) (first_seq rl) ->
+ emit_instr op_SIMPLESTAR (cpool_index (charclass_of_regexp fold_case r));
+ emit_seq_code rl
+ | Plus(Char _ | CharClass _ as r) :: rl
+ when disjoint_modulo_case (first r) (first_seq rl) ->
+ emit_instr op_SIMPLEPLUS (cpool_index (charclass_of_regexp fold_case r));
+ emit_seq_code rl
+ | Option(Char _ | CharClass _ as r) :: rl
+ when disjoint_modulo_case (first r) (first_seq rl) ->
+ emit_instr op_SIMPLEOPT (cpool_index (charclass_of_regexp fold_case r));
+ emit_seq_code rl
+ | r :: rl ->
+ emit_code r;
+ emit_seq_code rl
+
+ and disjoint_modulo_case c1 c2 =
+ if fold_case
+ then Charset.disjoint (Charset.fold_case c1) (Charset.fold_case c2)
+ else Charset.disjoint c1 c2
+ in
+
+ emit_code re;
+ emit_instr op_ACCEPT 0;
+ let start = first re in
+ let start' = if fold_case then Charset.fold_case start else start in
+ let start_pos =
+ if start = Charset.full
+ then -1
+ else cpool_index (Bytes.to_string (Charset.expand start')) in
+ let constantpool = Array.make !cpoolpos "" in
+ StringMap.iter (fun str idx -> constantpool.(idx) <- str) !cpool;
+ { prog = Array.sub !prog 0 !progpos;
+ cpool = constantpool;
+ normtable = if fold_case then fold_case_table else "";
+ numgroups = !numgroups;
+ numregisters = !numregs;
+ startchars = start_pos }
+
+(** Parsing of a regular expression *)
+
+(* Efficient buffering of sequences *)
+
+module SeqBuffer = struct
+
+ type t = { sb_chars: Buffer.t; mutable sb_next: re_syntax list }
+
+ let create() = { sb_chars = Buffer.create 16; sb_next = [] }
+
+ let flush buf =
+ let s = Buffer.contents buf.sb_chars in
+ Buffer.clear buf.sb_chars;
+ match String.length s with
+ 0 -> ()
+ | 1 -> buf.sb_next <- Char s.[0] :: buf.sb_next
+ | _ -> buf.sb_next <- String s :: buf.sb_next
+
+ let add buf re =
+ match re with
+ Char c -> Buffer.add_char buf.sb_chars c
+ | _ -> flush buf; buf.sb_next <- re :: buf.sb_next
+
+ let extract buf =
+ flush buf; Seq(List.rev buf.sb_next)
+
+end
+
+(* The character class corresponding to `.' *)
+
+let dotclass = Charset.complement (Charset.singleton '\n')
+
+(* Parse a regular expression *)
+
+let parse s =
+ let len = String.length s in
+ let group_counter = ref 1 in
+
+ let rec regexp0 i =
+ let (r, j) = regexp1 i in
+ regexp0cont r j
+ and regexp0cont r1 i =
+ if i + 2 <= len && s.[i] = '\\' && s.[i+1] = '|' then
+ let (r2, j) = regexp1 (i+2) in
+ regexp0cont (Alt(r1, r2)) j
+ else
+ (r1, i)
+ and regexp1 i =
+ regexp1cont (SeqBuffer.create()) i
+ and regexp1cont sb i =
+ if i >= len
+ || i + 2 <= len && s.[i] = '\\' && (let c = s.[i+1] in c = '|' || c = ')')
+ then
+ (SeqBuffer.extract sb, i)
+ else
+ let (r, j) = regexp2 i in
+ SeqBuffer.add sb r;
+ regexp1cont sb j
+ and regexp2 i =
+ let (r, j) = regexp3 i in
+ regexp2cont r j
+ and regexp2cont r i =
+ if i >= len then (r, i) else
+ match s.[i] with
+ '?' -> regexp2cont (Option r) (i+1)
+ | '*' -> regexp2cont (Star r) (i+1)
+ | '+' -> regexp2cont (Plus r) (i+1)
+ | _ -> (r, i)
+ and regexp3 i =
+ match s.[i] with
+ '\\' -> regexpbackslash (i+1)
+ | '[' -> let (c, compl, j) = regexpclass0 (i+1) in
+ (CharClass(c, compl), j)
+ | '^' -> (Bol, i+1)
+ | '$' -> (Eol, i+1)
+ | '.' -> (CharClass(dotclass, false), i+1)
+ | c -> (Char c, i+1)
+ and regexpbackslash i =
+ if i >= len then (Char '\\', i) else
+ match s.[i] with
+ '|' | ')' ->
+ assert false
+ | '(' ->
+ let group_no = !group_counter in
+ if group_no < 32 then incr group_counter;
+ let (r, j) = regexp0 (i+1) in
+ if j + 1 < len && s.[j] = '\\' && s.[j+1] = ')' then
+ if group_no < 32
+ then (Group(group_no, r), j + 2)
+ else (r, j + 2)
+ else
+ failwith "\\( group not closed by \\)"
+ | '1' .. '9' as c ->
+ (Refgroup(Char.code c - 48), i + 1)
+ | 'b' ->
+ (Wordboundary, i + 1)
+ | c ->
+ (Char c, i + 1)
+ and regexpclass0 i =
+ if i < len && s.[i] = '^'
+ then let (c, j) = regexpclass1 (i+1) in (c, true, j)
+ else let (c, j) = regexpclass1 i in (c, false, j)
+ and regexpclass1 i =
+ let c = Charset.make_empty() in
+ let j = regexpclass2 c i i in
+ (c, j)
+ and regexpclass2 c start i =
+ if i >= len then failwith "[ class not closed by ]";
+ if s.[i] = ']' && i > start then i+1 else begin
+ let c1 = s.[i] in
+ if i+2 < len && s.[i+1] = '-' && s.[i+2] <> ']' then begin
+ let c2 = s.[i+2] in
+ Charset.add_range c c1 c2;
+ regexpclass2 c start (i+3)
+ end else begin
+ Charset.add c c1;
+ regexpclass2 c start (i+1)
+ end
+ end in
+
+ let (r, j) = regexp0 0 in
+ if j = len then r else failwith "spurious \\) in regular expression"
+
+(** Parsing and compilation *)
+
+let regexp e = compile false (parse e)
+
+let regexp_case_fold e = compile true (parse e)
+
+let quote s =
+ let len = String.length s in
+ let buf = Bytes.create (2 * len) in
+ let pos = ref 0 in
+ for i = 0 to len - 1 do
+ match s.[i] with
+ '[' | ']' | '*' | '.' | '\\' | '?' | '+' | '^' | '$' as c ->
+ Bytes.set buf !pos '\\';
+ Bytes.set buf (!pos + 1) c;
+ pos := !pos + 2
+ | c ->
+ Bytes.set buf !pos c;
+ pos := !pos + 1
+ done;
+ Bytes.sub_string buf 0 !pos
+
+let regexp_string s = compile false (String s)
+
+let regexp_string_case_fold s = compile true (String s)
+
+(** Matching functions **)
+
+external re_string_match: regexp -> string -> int -> int array
+ = "re_string_match"
+external re_partial_match: regexp -> string -> int -> int array
+ = "re_partial_match"
+external re_search_forward: regexp -> string -> int -> int array
+ = "re_search_forward"
+external re_search_backward: regexp -> string -> int -> int array
+ = "re_search_backward"
+
+let last_search_result = ref [||]
+
+let string_match re s pos =
+ let res = re_string_match re s pos in
+ last_search_result := res;
+ Array.length res > 0
+
+let string_partial_match re s pos =
+ let res = re_partial_match re s pos in
+ last_search_result := res;
+ Array.length res > 0
+
+let search_forward re s pos =
+ let res = re_search_forward re s pos in
+ last_search_result := res;
+ if Array.length res = 0 then raise Not_found else res.(0)
+
+let search_backward re s pos =
+ let res = re_search_backward re s pos in
+ last_search_result := res;
+ if Array.length res = 0 then raise Not_found else res.(0)
+
+let group_beginning n =
+ let n2 = n + n in
+ if n < 0 || n2 >= Array.length !last_search_result then
+ invalid_arg "Str.group_beginning"
+ else
+ let pos = !last_search_result.(n2) in
+ if pos = -1 then raise Not_found else pos
+
+let group_end n =
+ let n2 = n + n in
+ if n < 0 || n2 >= Array.length !last_search_result then
+ invalid_arg "Str.group_end"
+ else
+ let pos = !last_search_result.(n2 + 1) in
+ if pos = -1 then raise Not_found else pos
+
+let matched_group n txt =
+ let n2 = n + n in
+ if n < 0 || n2 >= Array.length !last_search_result then
+ invalid_arg "Str.matched_group"
+ else
+ let b = !last_search_result.(n2)
+ and e = !last_search_result.(n2 + 1) in
+ if b = -1 then raise Not_found else String.sub txt b (e - b)
+
+let match_beginning () = group_beginning 0
+and match_end () = group_end 0
+and matched_string txt = matched_group 0 txt
+
+(** Replacement **)
+
+external re_replacement_text: string -> int array -> string -> string
+ = "re_replacement_text"
+
+let replace_matched repl matched =
+ re_replacement_text repl !last_search_result matched
+
+let substitute_first expr repl_fun text =
+ try
+ let pos = search_forward expr text 0 in
+ String.concat "" [string_before text pos;
+ repl_fun text;
+ string_after text (match_end())]
+ with Not_found ->
+ text
+
+let opt_search_forward re s pos =
+ try Some(search_forward re s pos) with Not_found -> None
+
+let global_substitute expr repl_fun text =
+ let rec replace accu start last_was_empty =
+ let startpos = if last_was_empty then start + 1 else start in
+ if startpos > String.length text then
+ string_after text start :: accu
+ else
+ match opt_search_forward expr text startpos with
+ | None ->
+ string_after text start :: accu
+ | Some pos ->
+ let end_pos = match_end() in
+ let repl_text = repl_fun text in
+ replace (repl_text :: String.sub text start (pos-start) :: accu)
+ end_pos (end_pos = pos)
+ in
+ String.concat "" (List.rev (replace [] 0 false))
+
+let global_replace expr repl text =
+ global_substitute expr (replace_matched repl) text
+and replace_first expr repl text =
+ substitute_first expr (replace_matched repl) text
+
+(** Splitting *)
+
+let opt_search_forward_progress expr text start =
+ match opt_search_forward expr text start with
+ | None -> None
+ | Some pos ->
+ if match_end() > start then
+ Some pos
+ else if start < String.length text then
+ opt_search_forward expr text (start + 1)
+ else None
+
+let bounded_split expr text num =
+ let start =
+ if string_match expr text 0 then match_end() else 0 in
+ let rec split accu start n =
+ if start >= String.length text then accu else
+ if n = 1 then string_after text start :: accu else
+ match opt_search_forward_progress expr text start with
+ | None ->
+ string_after text start :: accu
+ | Some pos ->
+ split (String.sub text start (pos-start) :: accu)
+ (match_end()) (n-1)
+ in
+ List.rev (split [] start num)
+
+let split expr text = bounded_split expr text 0
+
+let bounded_split_delim expr text num =
+ let rec split accu start n =
+ if start > String.length text then accu else
+ if n = 1 then string_after text start :: accu else
+ match opt_search_forward_progress expr text start with
+ | None ->
+ string_after text start :: accu
+ | Some pos ->
+ split (String.sub text start (pos-start) :: accu)
+ (match_end()) (n-1)
+ in
+ if text = "" then [] else List.rev (split [] 0 num)
+
+let split_delim expr text = bounded_split_delim expr text 0
+
+type split_result = Text of string | Delim of string
+
+let bounded_full_split expr text num =
+ let rec split accu start n =
+ if start >= String.length text then accu else
+ if n = 1 then Text(string_after text start) :: accu else
+ match opt_search_forward_progress expr text start with
+ | None ->
+ Text(string_after text start) :: accu
+ | Some pos ->
+ let s = matched_string text in
+ if pos > start then
+ split (Delim(s) :: Text(String.sub text start (pos-start)) :: accu)
+ (match_end()) (n-1)
+ else
+ split (Delim(s) :: accu)
+ (match_end()) (n-1)
+ in
+ List.rev (split [] 0 num)
+
+let full_split expr text = bounded_full_split expr text 0
diff --git a/otherlibs/str/str.mli b/otherlibs/str/str.mli
new file mode 100644
index 0000000000..448cbd5ac3
--- /dev/null
+++ b/otherlibs/str/str.mli
@@ -0,0 +1,289 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Regular expressions and high-level string processing *)
+
+
+(** {6 Regular expressions} *)
+
+
+type regexp
+(** The type of compiled regular expressions. *)
+
+
+val regexp : string -> regexp
+(** Compile a regular expression. The following constructs are
+ recognized:
+ - [. ] Matches any character except newline.
+ - [* ] (postfix) Matches the preceding expression zero, one or
+ several times
+ - [+ ] (postfix) Matches the preceding expression one or
+ several times
+ - [? ] (postfix) Matches the preceding expression once or
+ not at all
+ - [[..] ] Character set. Ranges are denoted with [-], as in [[a-z]].
+ An initial [^], as in [[^0-9]], complements the set.
+ To include a [\]] character in a set, make it the first
+ character of the set. To include a [-] character in a set,
+ make it the first or the last character of the set.
+ - [^ ] Matches at beginning of line (either at the beginning of
+ the matched string, or just after a newline character).
+ - [$ ] Matches at end of line (either at the end of the matched
+ string, or just before a newline character).
+ - [\| ] (infix) Alternative between two expressions.
+ - [\(..\)] Grouping and naming of the enclosed expression.
+ - [\1 ] The text matched by the first [\(...\)] expression
+ ([\2] for the second expression, and so on up to [\9]).
+ - [\b ] Matches word boundaries.
+ - [\ ] Quotes special characters. The special characters
+ are [$^\.*+?[]].
+
+ Note: the argument to [regexp] is usually a string literal. In this
+ case, any backslash character in the regular expression must be
+ doubled to make it past the OCaml string parser. For example, the
+ following expression:
+ {[ let r = Str.regexp "hello \\([A-Za-z]+\\)" in
+ Str.replace_first r "\\1" "hello world" ]}
+ returns the string ["world"].
+
+ In particular, if you want a regular expression that matches a single
+ backslash character, you need to quote it in the argument to [regexp]
+ (according to the last item of the list above) by adding a second
+ backslash. Then you need to quote both backslashes (according to the
+ syntax of string constants in OCaml) by doubling them again, so you
+ need to write four backslash characters: [Str.regexp "\\\\"].
+*)
+
+val regexp_case_fold : string -> regexp
+(** Same as [regexp], but the compiled expression will match text
+ in a case-insensitive way: uppercase and lowercase letters will
+ be considered equivalent. *)
+
+val quote : string -> string
+(** [Str.quote s] returns a regexp string that matches exactly
+ [s] and nothing else. *)
+
+val regexp_string : string -> regexp
+(** [Str.regexp_string s] returns a regular expression
+ that matches exactly [s] and nothing else.*)
+
+val regexp_string_case_fold : string -> regexp
+(** [Str.regexp_string_case_fold] is similar to {!Str.regexp_string},
+ but the regexp matches in a case-insensitive way. *)
+
+
+(** {6 String matching and searching} *)
+
+
+val string_match : regexp -> string -> int -> bool
+(** [string_match r s start] tests whether a substring of [s] that
+ starts at position [start] matches the regular expression [r].
+ The first character of a string has position [0], as usual. *)
+
+val search_forward : regexp -> string -> int -> int
+(** [search_forward r s start] searches the string [s] for a substring
+ matching the regular expression [r]. The search starts at position
+ [start] and proceeds towards the end of the string.
+ Return the position of the first character of the matched
+ substring.
+ @raise Not_found if no substring matches. *)
+
+val search_backward : regexp -> string -> int -> int
+(** [search_backward r s last] searches the string [s] for a
+ substring matching the regular expression [r]. The search first
+ considers substrings that start at position [last] and proceeds
+ towards the beginning of string. Return the position of the first
+ character of the matched substring.
+ @raise Not_found if no substring matches. *)
+
+val string_partial_match : regexp -> string -> int -> bool
+(** Similar to {!Str.string_match}, but also returns true if
+ the argument string is a prefix of a string that matches.
+ This includes the case of a true complete match. *)
+
+val matched_string : string -> string
+(** [matched_string s] returns the substring of [s] that was matched
+ by the last call to one of the following matching or searching
+ functions:
+ - {!Str.string_match}
+ - {!Str.search_forward}
+ - {!Str.search_backward}
+ - {!Str.string_partial_match}
+ - {!Str.global_substitute}
+ - {!Str.substitute_first}
+
+ provided that none of the following functions was called inbetween:
+ - {!Str.global_replace}
+ - {!Str.replace_first}
+ - {!Str.split}
+ - {!Str.bounded_split}
+ - {!Str.split_delim}
+ - {!Str.bounded_split_delim}
+ - {!Str.full_split}
+ - {!Str.bounded_full_split}
+
+ Note: in the case of [global_substitute] and [substitute_first],
+ a call to [matched_string] is only valid within the [subst] argument,
+ not after [global_substitute] or [substitute_first] returns.
+
+ The user must make sure that the parameter [s] is the same string
+ that was passed to the matching or searching function. *)
+
+val match_beginning : unit -> int
+(** [match_beginning()] returns the position of the first character
+ of the substring that was matched by the last call to a matching
+ or searching function (see {!Str.matched_string} for details). *)
+
+val match_end : unit -> int
+(** [match_end()] returns the position of the character following the
+ last character of the substring that was matched by the last call
+ to a matching or searching function (see {!Str.matched_string} for
+ details). *)
+
+val matched_group : int -> string -> string
+(** [matched_group n s] returns the substring of [s] that was matched
+ by the [n]th group [\(...\)] of the regular expression that was
+ matched by the last call to a matching or searching function (see
+ {!Str.matched_string} for details).
+ The user must make sure that the parameter [s] is the same string
+ that was passed to the matching or searching function.
+ @raise Not_found if the [n]th group
+ of the regular expression was not matched. This can happen
+ with groups inside alternatives [\|], options [?]
+ or repetitions [*]. For instance, the empty string will match
+ [\(a\)*], but [matched_group 1 ""] will raise [Not_found]
+ because the first group itself was not matched. *)
+
+val group_beginning : int -> int
+(** [group_beginning n] returns the position of the first character
+ of the substring that was matched by the [n]th group of
+ the regular expression that was matched by the last call to a
+ matching or searching function (see {!Str.matched_string} for details).
+ @raise Not_found if the [n]th group of the regular expression
+ was not matched.
+ @raise Invalid_argument if there are fewer than [n] groups in
+ the regular expression. *)
+
+val group_end : int -> int
+(** [group_end n] returns
+ the position of the character following the last character of
+ substring that was matched by the [n]th group of the regular
+ expression that was matched by the last call to a matching or
+ searching function (see {!Str.matched_string} for details).
+ @raise Not_found if the [n]th group of the regular expression
+ was not matched.
+ @raise Invalid_argument if there are fewer than [n] groups in
+ the regular expression. *)
+
+
+(** {6 Replacement} *)
+
+
+val global_replace : regexp -> string -> string -> string
+(** [global_replace regexp templ s] returns a string identical to [s],
+ except that all substrings of [s] that match [regexp] have been
+ replaced by [templ]. The replacement template [templ] can contain
+ [\1], [\2], etc; these sequences will be replaced by the text
+ matched by the corresponding group in the regular expression.
+ [\0] stands for the text matched by the whole regular expression. *)
+
+val replace_first : regexp -> string -> string -> string
+(** Same as {!Str.global_replace}, except that only the first substring
+ matching the regular expression is replaced. *)
+
+val global_substitute : regexp -> (string -> string) -> string -> string
+(** [global_substitute regexp subst s] returns a string identical
+ to [s], except that all substrings of [s] that match [regexp]
+ have been replaced by the result of function [subst]. The
+ function [subst] is called once for each matching substring,
+ and receives [s] (the whole text) as argument. *)
+
+val substitute_first : regexp -> (string -> string) -> string -> string
+(** Same as {!Str.global_substitute}, except that only the first substring
+ matching the regular expression is replaced. *)
+
+val replace_matched : string -> string -> string
+(** [replace_matched repl s] returns the replacement text [repl]
+ in which [\1], [\2], etc. have been replaced by the text
+ matched by the corresponding groups in the regular expression
+ that was matched by the last call to a matching or searching
+ function (see {!Str.matched_string} for details).
+ [s] must be the same string that was passed to the matching or
+ searching function. *)
+
+
+(** {6 Splitting} *)
+
+
+val split : regexp -> string -> string list
+(** [split r s] splits [s] into substrings, taking as delimiters
+ the substrings that match [r], and returns the list of substrings.
+ For instance, [split (regexp "[ \t]+") s] splits [s] into
+ blank-separated words. An occurrence of the delimiter at the
+ beginning or at the end of the string is ignored. *)
+
+val bounded_split : regexp -> string -> int -> string list
+(** Same as {!Str.split}, but splits into at most [n] substrings,
+ where [n] is the extra integer parameter. *)
+
+val split_delim : regexp -> string -> string list
+(** Same as {!Str.split} but occurrences of the
+ delimiter at the beginning and at the end of the string are
+ recognized and returned as empty strings in the result.
+ For instance, [split_delim (regexp " ") " abc "]
+ returns [[""; "abc"; ""]], while [split] with the same
+ arguments returns [["abc"]]. *)
+
+val bounded_split_delim : regexp -> string -> int -> string list
+(** Same as {!Str.bounded_split}, but occurrences of the
+ delimiter at the beginning and at the end of the string are
+ recognized and returned as empty strings in the result. *)
+
+type split_result =
+ Text of string
+ | Delim of string
+
+val full_split : regexp -> string -> split_result list
+(** Same as {!Str.split_delim}, but returns
+ the delimiters as well as the substrings contained between
+ delimiters. The former are tagged [Delim] in the result list;
+ the latter are tagged [Text]. For instance,
+ [full_split (regexp "[{}]") "{ab}"] returns
+ [[Delim "{"; Text "ab"; Delim "}"]]. *)
+
+val bounded_full_split : regexp -> string -> int -> split_result list
+(** Same as {!Str.bounded_split_delim}, but returns
+ the delimiters as well as the substrings contained between
+ delimiters. The former are tagged [Delim] in the result list;
+ the latter are tagged [Text]. *)
+
+
+(** {6 Extracting substrings} *)
+
+
+val string_before : string -> int -> string
+(** [string_before s n] returns the substring of all characters of [s]
+ that precede position [n] (excluding the character at
+ position [n]). *)
+
+val string_after : string -> int -> string
+(** [string_after s n] returns the substring of all characters of [s]
+ that follow position [n] (including the character at
+ position [n]). *)
+
+val first_chars : string -> int -> string
+(** [first_chars s n] returns the first [n] characters of [s].
+ This is the same function as {!Str.string_before}. *)
+
+val last_chars : string -> int -> string
+(** [last_chars s n] returns the last [n] characters of [s]. *)
diff --git a/otherlibs/str/strstubs.c b/otherlibs/str/strstubs.c
new file mode 100644
index 0000000000..6c928704b1
--- /dev/null
+++ b/otherlibs/str/strstubs.c
@@ -0,0 +1,530 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <ctype.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/fail.h>
+
+/* The backtracking NFA interpreter */
+
+union backtrack_point {
+ struct {
+ value * pc; /* with low bit set */
+ unsigned char * txt;
+ } pos;
+ struct {
+ unsigned char ** loc; /* with low bit clear */
+ unsigned char * val;
+ } undo;
+};
+
+#define Set_tag(p) ((value *) ((intnat)(p) | 1))
+#define Clear_tag(p) ((value *) ((intnat)(p) & ~1))
+#define Tag_is_set(p) ((intnat)(p) & 1)
+
+#define BACKTRACK_STACK_BLOCK_SIZE 500
+
+struct backtrack_stack {
+ struct backtrack_stack * previous;
+ union backtrack_point point[BACKTRACK_STACK_BLOCK_SIZE];
+};
+
+#define Opcode(x) ((x) & 0xFF)
+#define Arg(x) ((uintnat)(x) >> 8)
+#define SignedArg(x) ((intnat)(x) >> 8)
+
+enum {
+ CHAR, /* match a single character */
+ CHARNORM, /* match a single character, after normalization */
+ STRING, /* match a character string */
+ STRINGNORM, /* match a character string, after normalization */
+ CHARCLASS, /* match a character class */
+ BOL, /* match at beginning of line */
+ EOL, /* match at end of line */
+ WORDBOUNDARY, /* match on a word boundary */
+ BEGGROUP, /* record the beginning of a group */
+ ENDGROUP, /* record the end of a group */
+ REFGROUP, /* match a previously matched group */
+ ACCEPT, /* report success */
+ SIMPLEOPT, /* match a character class 0 or 1 times */
+ SIMPLESTAR, /* match a character class 0, 1 or several times */
+ SIMPLEPLUS, /* match a character class 1 or several times */
+ GOTO, /* unconditional branch */
+ PUSHBACK, /* record a backtrack point --
+ where to jump in case of failure */
+ SETMARK, /* remember current position in given register # */
+ CHECKPROGRESS /* backtrack if no progress was made w.r.t. reg # */
+};
+
+/* Accessors in a compiled regexp */
+#define Prog(re) Field(re, 0)
+#define Cpool(re) Field(re, 1)
+#define Normtable(re) Field(re, 2)
+#define Numgroups(re) Int_val(Field(re, 3))
+#define Numregisters(re) Int_val(Field(re, 4))
+#define Startchars(re) Int_val(Field(re, 5))
+
+/* Record positions of matched groups */
+#define NUM_GROUPS 32
+struct re_group {
+ unsigned char * start;
+ unsigned char * end;
+};
+static struct re_group re_group[NUM_GROUPS];
+
+/* Record positions reached during matching; used to check progress
+ in repeated matching of a regexp. */
+#define NUM_REGISTERS 64
+static unsigned char * re_register[NUM_REGISTERS];
+
+/* The initial backtracking stack */
+static struct backtrack_stack initial_stack = { NULL, };
+
+/* Free a chained list of backtracking stacks */
+static void free_backtrack_stack(struct backtrack_stack * stack)
+{
+ struct backtrack_stack * prevstack;
+ while ((prevstack = stack->previous) != NULL) {
+ stat_free(stack);
+ stack = prevstack;
+ }
+}
+
+/* Membership in a bit vector representing a set of booleans */
+#define In_bitset(s,i,tmp) (tmp = (i), ((s)[tmp >> 3] >> (tmp & 7)) & 1)
+
+/* Determine if a character is a word constituent */
+/* PR#4874: word constituent = letter, digit, underscore. */
+
+static unsigned char re_word_letters[32] = {
+ 0x00, 0x00, 0x00, 0x00, /* 0x00-0x1F: none */
+ 0x00, 0x00, 0xFF, 0x03, /* 0x20-0x3F: digits 0-9 */
+ 0xFE, 0xFF, 0xFF, 0x87, /* 0x40-0x5F: A to Z, _ */
+ 0xFE, 0xFF, 0xFF, 0x07, /* 0x60-0x7F: a to z */
+ 0x00, 0x00, 0x00, 0x00, /* 0x80-0x9F: none */
+ 0x00, 0x00, 0x00, 0x00, /* 0xA0-0xBF: none */
+ 0xFF, 0xFF, 0x7F, 0xFF, /* 0xC0-0xDF: Latin-1 accented uppercase */
+ 0xFF, 0xFF, 0x7F, 0xFF /* 0xE0-0xFF: Latin-1 accented lowercase */
+};
+
+#define Is_word_letter(c) ((re_word_letters[(c) >> 3] >> ((c) & 7)) & 1)
+
+/* The bytecode interpreter for the NFA */
+static int re_match(value re,
+ unsigned char * starttxt,
+ register unsigned char * txt,
+ register unsigned char * endtxt,
+ int accept_partial_match)
+{
+ register value * pc;
+ intnat instr;
+ struct backtrack_stack * stack;
+ union backtrack_point * sp;
+ value cpool;
+ value normtable;
+ unsigned char c;
+ union backtrack_point back;
+
+ { int i;
+ struct re_group * p;
+ unsigned char ** q;
+ for (p = &re_group[1], i = Numgroups(re); i > 1; i--, p++)
+ p->start = p->end = NULL;
+ for (q = &re_register[0], i = Numregisters(re); i > 0; i--, q++)
+ *q = NULL;
+ }
+
+ pc = &Field(Prog(re), 0);
+ stack = &initial_stack;
+ sp = stack->point;
+ cpool = Cpool(re);
+ normtable = Normtable(re);
+ re_group[0].start = txt;
+
+ while (1) {
+ instr = Long_val(*pc++);
+ switch (Opcode(instr)) {
+ case CHAR:
+ if (txt == endtxt) goto prefix_match;
+ if (*txt != Arg(instr)) goto backtrack;
+ txt++;
+ break;
+ case CHARNORM:
+ if (txt == endtxt) goto prefix_match;
+ if (Byte_u(normtable, *txt) != Arg(instr)) goto backtrack;
+ txt++;
+ break;
+ case STRING: {
+ unsigned char * s =
+ (unsigned char *) String_val(Field(cpool, Arg(instr)));
+ while ((c = *s++) != 0) {
+ if (txt == endtxt) goto prefix_match;
+ if (c != *txt) goto backtrack;
+ txt++;
+ }
+ break;
+ }
+ case STRINGNORM: {
+ unsigned char * s =
+ (unsigned char *) String_val(Field(cpool, Arg(instr)));
+ while ((c = *s++) != 0) {
+ if (txt == endtxt) goto prefix_match;
+ if (c != Byte_u(normtable, *txt)) goto backtrack;
+ txt++;
+ }
+ break;
+ }
+ case CHARCLASS:
+ if (txt == endtxt) goto prefix_match;
+ if (! In_bitset(String_val(Field(cpool, Arg(instr))), *txt, c))
+ goto backtrack;
+ txt++;
+ break;
+ case BOL:
+ if (txt > starttxt && txt[-1] != '\n') goto backtrack;
+ break;
+ case EOL:
+ if (txt < endtxt && *txt != '\n') goto backtrack;
+ break;
+ case WORDBOUNDARY:
+ /* At beginning and end of text: no
+ At beginning of text: OK if current char is a letter
+ At end of text: OK if previous char is a letter
+ Otherwise:
+ OK if previous char is a letter and current char not a letter
+ or previous char is not a letter and current char is a letter */
+ if (txt == starttxt) {
+ if (txt == endtxt) goto prefix_match;
+ if (Is_word_letter(txt[0])) break;
+ goto backtrack;
+ } else if (txt == endtxt) {
+ if (Is_word_letter(txt[-1])) break;
+ goto backtrack;
+ } else {
+ if (Is_word_letter(txt[-1]) != Is_word_letter(txt[0])) break;
+ goto backtrack;
+ }
+ case BEGGROUP: {
+ int group_no = Arg(instr);
+ struct re_group * group = &(re_group[group_no]);
+ back.undo.loc = &(group->start);
+ back.undo.val = group->start;
+ group->start = txt;
+ goto push;
+ }
+ case ENDGROUP: {
+ int group_no = Arg(instr);
+ struct re_group * group = &(re_group[group_no]);
+ back.undo.loc = &(group->end);
+ back.undo.val = group->end;
+ group->end = txt;
+ goto push;
+ }
+ case REFGROUP: {
+ int group_no = Arg(instr);
+ struct re_group * group = &(re_group[group_no]);
+ unsigned char * s;
+ if (group->start == NULL || group->end == NULL) goto backtrack;
+ for (s = group->start; s < group->end; s++) {
+ if (txt == endtxt) goto prefix_match;
+ if (*s != *txt) goto backtrack;
+ txt++;
+ }
+ break;
+ }
+ case ACCEPT:
+ goto accept;
+ case SIMPLEOPT: {
+ char * set = String_val(Field(cpool, Arg(instr)));
+ if (txt < endtxt && In_bitset(set, *txt, c)) txt++;
+ break;
+ }
+ case SIMPLESTAR: {
+ char * set = String_val(Field(cpool, Arg(instr)));
+ while (txt < endtxt && In_bitset(set, *txt, c))
+ txt++;
+ break;
+ }
+ case SIMPLEPLUS: {
+ char * set = String_val(Field(cpool, Arg(instr)));
+ if (txt == endtxt) goto prefix_match;
+ if (! In_bitset(set, *txt, c)) goto backtrack;
+ txt++;
+ while (txt < endtxt && In_bitset(set, *txt, c))
+ txt++;
+ break;
+ }
+ case GOTO:
+ pc = pc + SignedArg(instr);
+ break;
+ case PUSHBACK:
+ back.pos.pc = Set_tag(pc + SignedArg(instr));
+ back.pos.txt = txt;
+ goto push;
+ case SETMARK: {
+ int reg_no = Arg(instr);
+ unsigned char ** reg = &(re_register[reg_no]);
+ back.undo.loc = reg;
+ back.undo.val = *reg;
+ *reg = txt;
+ goto push;
+ }
+ case CHECKPROGRESS: {
+ int reg_no = Arg(instr);
+ if (re_register[reg_no] == txt)
+ goto backtrack;
+ break;
+ }
+ default:
+ caml_fatal_error ("impossible case in re_match");
+ }
+ /* Continue with next instruction */
+ continue;
+
+ push:
+ /* Push an item on the backtrack stack and continue with next instr */
+ if (sp == stack->point + BACKTRACK_STACK_BLOCK_SIZE) {
+ struct backtrack_stack * newstack =
+ caml_stat_alloc(sizeof(struct backtrack_stack));
+ newstack->previous = stack;
+ stack = newstack;
+ sp = stack->point;
+ }
+ *sp = back;
+ sp++;
+ continue;
+
+ prefix_match:
+ /* We get here when matching failed because the end of text
+ was encountered. */
+ if (accept_partial_match) goto accept;
+
+ backtrack:
+ /* We get here when matching fails. Backtrack to most recent saved
+ program point, undoing variable assignments on the way. */
+ while (1) {
+ if (sp == stack->point) {
+ struct backtrack_stack * prevstack = stack->previous;
+ if (prevstack == NULL) return 0;
+ stat_free(stack);
+ stack = prevstack;
+ sp = stack->point + BACKTRACK_STACK_BLOCK_SIZE;
+ }
+ sp--;
+ if (Tag_is_set(sp->pos.pc)) {
+ pc = Clear_tag(sp->pos.pc);
+ txt = sp->pos.txt;
+ break;
+ } else {
+ *(sp->undo.loc) = sp->undo.val;
+ }
+ }
+ continue;
+ }
+
+ accept:
+ /* We get here when the regexp was successfully matched */
+ free_backtrack_stack(stack);
+ re_group[0].end = txt;
+ return 1;
+}
+
+/* Allocate an integer array containing the positions of the matched groups.
+ Beginning of group #N is at 2N, end is at 2N+1.
+ Take position = -1 when group wasn't matched. */
+
+static value re_alloc_groups(value re, value str)
+{
+ CAMLparam1(str);
+ CAMLlocal1(res);
+ unsigned char * starttxt = (unsigned char *) String_val(str);
+ int n = Numgroups(re);
+ int i;
+ struct re_group * group;
+
+ res = alloc(n * 2, 0);
+ for (i = 0; i < n; i++) {
+ group = &(re_group[i]);
+ if (group->start == NULL || group->end == NULL) {
+ Field(res, i * 2) = Val_int(-1);
+ Field(res, i * 2 + 1) = Val_int(-1);
+ } else {
+ Field(res, i * 2) = Val_long(group->start - starttxt);
+ Field(res, i * 2 + 1) = Val_long(group->end - starttxt);
+ }
+ }
+ CAMLreturn(res);
+}
+
+/* String matching and searching. All functions return the empty array
+ on failure, and an array of positions on success. */
+
+CAMLprim value re_string_match(value re, value str, value pos)
+{
+ unsigned char * starttxt = &Byte_u(str, 0);
+ unsigned char * txt = &Byte_u(str, Long_val(pos));
+ unsigned char * endtxt = &Byte_u(str, string_length(str));
+
+ if (txt < starttxt || txt > endtxt)
+ invalid_argument("Str.string_match");
+ if (re_match(re, starttxt, txt, endtxt, 0)) {
+ return re_alloc_groups(re, str);
+ } else {
+ return Atom(0);
+ }
+}
+
+CAMLprim value re_partial_match(value re, value str, value pos)
+{
+ unsigned char * starttxt = &Byte_u(str, 0);
+ unsigned char * txt = &Byte_u(str, Long_val(pos));
+ unsigned char * endtxt = &Byte_u(str, string_length(str));
+
+ if (txt < starttxt || txt > endtxt)
+ invalid_argument("Str.string_partial_match");
+ if (re_match(re, starttxt, txt, endtxt, 1)) {
+ return re_alloc_groups(re, str);
+ } else {
+ return Atom(0);
+ }
+}
+
+CAMLprim value re_search_forward(value re, value str, value startpos)
+{
+ unsigned char * starttxt = &Byte_u(str, 0);
+ unsigned char * txt = &Byte_u(str, Long_val(startpos));
+ unsigned char * endtxt = &Byte_u(str, string_length(str));
+ unsigned char * startchars;
+
+ if (txt < starttxt || txt > endtxt)
+ invalid_argument("Str.search_forward");
+ if (Startchars(re) == -1) {
+ do {
+ if (re_match(re, starttxt, txt, endtxt, 0))
+ return re_alloc_groups(re, str);
+ txt++;
+ } while (txt <= endtxt);
+ return Atom(0);
+ } else {
+ startchars =
+ (unsigned char *) String_val(Field(Cpool(re), Startchars(re)));
+ do {
+ while (txt < endtxt && startchars[*txt] == 0) txt++;
+ if (re_match(re, starttxt, txt, endtxt, 0))
+ return re_alloc_groups(re, str);
+ txt++;
+ } while (txt <= endtxt);
+ return Atom(0);
+ }
+}
+
+CAMLprim value re_search_backward(value re, value str, value startpos)
+{
+ unsigned char * starttxt = &Byte_u(str, 0);
+ unsigned char * txt = &Byte_u(str, Long_val(startpos));
+ unsigned char * endtxt = &Byte_u(str, string_length(str));
+ unsigned char * startchars;
+
+ if (txt < starttxt || txt > endtxt)
+ invalid_argument("Str.search_backward");
+ if (Startchars(re) == -1) {
+ do {
+ if (re_match(re, starttxt, txt, endtxt, 0))
+ return re_alloc_groups(re, str);
+ txt--;
+ } while (txt >= starttxt);
+ return Atom(0);
+ } else {
+ startchars =
+ (unsigned char *) String_val(Field(Cpool(re), Startchars(re)));
+ do {
+ while (txt > starttxt && startchars[*txt] == 0) txt--;
+ if (re_match(re, starttxt, txt, endtxt, 0))
+ return re_alloc_groups(re, str);
+ txt--;
+ } while (txt >= starttxt);
+ return Atom(0);
+ }
+}
+
+/* Replacement */
+
+CAMLprim value re_replacement_text(value repl, value groups, value orig)
+{
+ CAMLparam3(repl, groups, orig);
+ CAMLlocal1(res);
+ mlsize_t start, end, len, n;
+ char * p, * q;
+ int c;
+
+ len = 0;
+ p = String_val(repl);
+ n = string_length(repl);
+ while (n > 0) {
+ c = *p++; n--;
+ if(c != '\\')
+ len++;
+ else {
+ if (n == 0) failwith("Str.replace: illegal backslash sequence");
+ c = *p++; n--;
+ switch (c) {
+ case '\\':
+ len++; break;
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ c -= '0';
+ if (c*2 >= Wosize_val(groups))
+ failwith("Str.replace: reference to unmatched group");
+ start = Long_val(Field(groups, c*2));
+ end = Long_val(Field(groups, c*2 + 1));
+ if (start == (mlsize_t) -1)
+ failwith("Str.replace: reference to unmatched group");
+ len += end - start;
+ break;
+ default:
+ len += 2; break;
+ }
+ }
+ }
+ res = alloc_string(len);
+ p = String_val(repl);
+ q = String_val(res);
+ n = string_length(repl);
+ while (n > 0) {
+ c = *p++; n--;
+ if(c != '\\')
+ *q++ = c;
+ else {
+ c = *p++; n--;
+ switch (c) {
+ case '\\':
+ *q++ = '\\'; break;
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ c -= '0';
+ start = Long_val(Field(groups, c*2));
+ end = Long_val(Field(groups, c*2 + 1));
+ len = end - start;
+ memmove (q, &Byte(orig, start), len);
+ q += len;
+ break;
+ default:
+ *q++ = '\\'; *q++ = c; break;
+ }
+ }
+ }
+ CAMLreturn(res);
+}
diff --git a/otherlibs/systhreads/.depend b/otherlibs/systhreads/.depend
new file mode 100644
index 0000000000..fb87b4aa97
--- /dev/null
+++ b/otherlibs/systhreads/.depend
@@ -0,0 +1,30 @@
+st_stubs.o: st_stubs.c ../../byterun/caml/alloc.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/backtrace.h ../../byterun/caml/exec.h \
+ ../../byterun/caml/callback.h ../../byterun/caml/custom.h \
+ ../../byterun/caml/fail.h ../../byterun/caml/io.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/printexc.h ../../byterun/caml/roots.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/signals.h \
+ ../../byterun/caml/stacks.h ../../byterun/caml/sys.h threads.h \
+ st_posix.h
+condition.cmi : mutex.cmi
+event.cmi :
+mutex.cmi :
+thread.cmi :
+threadUnix.cmi :
+condition.cmo : mutex.cmi condition.cmi
+condition.cmx : mutex.cmx condition.cmi
+event.cmo : mutex.cmi condition.cmi event.cmi
+event.cmx : mutex.cmx condition.cmx event.cmi
+mutex.cmo : mutex.cmi
+mutex.cmx : mutex.cmi
+thread.cmo : thread.cmi
+thread.cmx : thread.cmi
+threadUnix.cmo : thread.cmi threadUnix.cmi
+threadUnix.cmx : thread.cmx threadUnix.cmi
diff --git a/otherlibs/systhreads/.ignore b/otherlibs/systhreads/.ignore
new file mode 100644
index 0000000000..71702b88e7
--- /dev/null
+++ b/otherlibs/systhreads/.ignore
@@ -0,0 +1 @@
+thread.ml
diff --git a/otherlibs/systhreads/Makefile b/otherlibs/systhreads/Makefile
new file mode 100644
index 0000000000..73e7f6f614
--- /dev/null
+++ b/otherlibs/systhreads/Makefile
@@ -0,0 +1,114 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+include ../../config/Makefile
+CAMLRUN ?= ../../boot/ocamlrun
+CAMLYACC ?= ../../boot/ocamlyacc
+
+ROOTDIR=../..
+CAMLC=$(CAMLRUN) $(ROOTDIR)/ocamlc -nostdlib \
+ -I $(ROOTDIR)/stdlib -I $(ROOTDIR)/otherlibs/unix
+CAMLOPT=$(CAMLRUN) $(ROOTDIR)/ocamlopt -nostdlib \
+ -I $(ROOTDIR)/stdlib -I $(ROOTDIR)/otherlibs/unix
+MKLIB=$(CAMLRUN) ../../tools/ocamlmklib
+COMPFLAGS=-w +33..39 -warn-error A -g -bin-annot -safe-string
+
+BYTECODE_C_OBJS=st_stubs_b.o
+NATIVECODE_C_OBJS=st_stubs_n.o
+
+THREAD_OBJS= thread.cmo mutex.cmo condition.cmo event.cmo threadUnix.cmo
+
+all: libthreads.a threads.cma
+
+allopt: libthreadsnat.a threads.cmxa
+
+libthreads.a: $(BYTECODE_C_OBJS)
+ $(MKLIB) -o threads $(BYTECODE_C_OBJS) $(PTHREAD_LINK)
+
+st_stubs_b.o: st_stubs.c st_posix.h
+ $(BYTECC) -I../../byterun $(BYTECCCOMPOPTS) $(SHAREDCCCOMPOPTS) \
+ -c st_stubs.c
+ mv st_stubs.o st_stubs_b.o
+
+# Dynamic linking with -lpthread is risky on many platforms, so
+# do not create a shared object for libthreadsnat.
+libthreadsnat.a: $(NATIVECODE_C_OBJS)
+ $(AR) rc libthreadsnat.a $(NATIVECODE_C_OBJS)
+
+st_stubs_n.o: st_stubs.c st_posix.h
+ $(NATIVECC) -I../../asmrun -I../../byterun $(NATIVECCCOMPOPTS) \
+ $(SHAREDCCCOMPOPTS) -DNATIVE_CODE -DTARGET_$(ARCH) \
+ -DMODEL_$(MODEL) -DSYS_$(SYSTEM) -c st_stubs.c
+ mv st_stubs.o st_stubs_n.o
+
+threads.cma: $(THREAD_OBJS)
+ $(MKLIB) -ocamlc '$(CAMLC)' -o threads $(THREAD_OBJS) \
+ -cclib -lunix $(PTHREAD_CAML_LINK)
+
+# See remark above: force static linking of libthreadsnat.a
+threads.cmxa: $(THREAD_OBJS:.cmo=.cmx)
+ $(CAMLOPT) -a -o threads.cmxa $(THREAD_OBJS:.cmo=.cmx) \
+ -cclib -lthreadsnat $(PTHREAD_CAML_LINK)
+
+# Note: I removed "-cclib -lunix" from the line above.
+# Indeed, if we link threads.cmxa, then we must also link unix.cmxa,
+# which itself will pass -lunix to the C linker. It seems more
+# modular to me this way. -- Alain
+
+
+$(THREAD_OBJS:.cmo=.cmx): ../../ocamlopt
+
+partialclean:
+ rm -f *.cm*
+
+clean: partialclean
+ rm -f *.o *.a *.so
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+INSTALL_STUBLIBDIR=$(DESTDIR)$(STUBLIBDIR)
+
+install:
+ if test -f dllthreads.so; then \
+ cp dllthreads.so $(INSTALL_STUBLIBDIR)/dllthreads.so; fi
+ cp libthreads.a $(INSTALL_LIBDIR)/libthreads.a
+ cd $(INSTALL_LIBDIR); $(RANLIB) libthreads.a
+ if test -d $(INSTALL_LIBDIR)/threads; then :; \
+ else mkdir $(INSTALL_LIBDIR)/threads; fi
+ cp $(THREAD_OBJS:.cmo=.cmi) threads.cma $(INSTALL_LIBDIR)/threads
+ rm -f $(INSTALL_LIBDIR)/threads/stdlib.cma
+ cp thread.mli mutex.mli condition.mli event.mli threadUnix.mli \
+ $(INSTALL_LIBDIR)
+ cp threads.h $(INSTALL_LIBDIR)/caml/threads.h
+
+installopt:
+ cp libthreadsnat.a $(INSTALL_LIBDIR)/libthreadsnat.a
+ cd $(INSTALL_LIBDIR); $(RANLIB) libthreadsnat.a
+ cp $(THREAD_OBJS:.cmo=.cmx) threads.cmxa threads.a $(INSTALL_LIBDIR)/threads
+ cd $(INSTALL_LIBDIR)/threads; $(RANLIB) threads.a
+
+.SUFFIXES: .ml .mli .cmo .cmi .cmx
+
+.mli.cmi:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmo:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmx:
+ $(CAMLOPT) -c $(COMPFLAGS) $<
+
+depend: $(GENFILES)
+ -$(CC) -MM -I../../byterun *.c > .depend
+ $(CAMLRUN) ../../tools/ocamldep *.mli *.ml >> .depend
+
+include .depend
diff --git a/otherlibs/systhreads/Makefile.nt b/otherlibs/systhreads/Makefile.nt
new file mode 100644
index 0000000000..22fb1c7179
--- /dev/null
+++ b/otherlibs/systhreads/Makefile.nt
@@ -0,0 +1,104 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+include ../../config/Makefile
+CAMLRUN ?= ../../boot/ocamlrun
+CAMLYACC ?= ../../boot/ocamlyacc
+
+# Compilation options
+CAMLC=$(CAMLRUN) ../../ocamlc -I ../../stdlib -I ../win32unix
+CAMLOPT=$(CAMLRUN) ../../ocamlopt -I ../../stdlib -I ../win32unix
+COMPFLAGS=-w +33 -warn-error A -g
+MKLIB=$(CAMLRUN) ../../tools/ocamlmklib
+CFLAGS=-I../../byterun $(EXTRACFLAGS)
+
+CAMLOBJS=thread.cmo mutex.cmo condition.cmo event.cmo threadUnix.cmo
+CMIFILES=$(CAMLOBJS:.cmo=.cmi)
+COBJS=st_stubs_b.$(O)
+COBJS_NAT=st_stubs_n.$(O)
+
+LIBNAME=threads
+
+all: lib$(LIBNAME).$(A) $(LIBNAME).cma $(CMIFILES)
+
+allopt: lib$(LIBNAME).$(A) $(LIBNAME).cmxa $(LIBNAME).cmxs $(CMIFILES)
+
+$(LIBNAME).cma: $(CAMLOBJS)
+ $(MKLIB) -o $(LIBNAME) -ocamlc "$(CAMLRUN) ../../ocamlc" \
+ -linkall $(CAMLOBJS) $(LINKOPTS)
+
+lib$(LIBNAME).$(A): $(COBJS)
+ $(MKLIB) -o $(LIBNAME) $(COBJS) $(LDOPTS)
+
+st_stubs_b.$(O): st_stubs.c st_win32.h
+ $(BYTECC) $(BYTECCCOMPOPTS) $(CFLAGS) -c st_stubs.c
+ mv st_stubs.$(O) st_stubs_b.$(O)
+
+
+
+$(LIBNAME).cmxa: $(CAMLOBJS:.cmo=.cmx)
+ $(MKLIB) -o $(LIBNAME)nat \
+ -ocamlopt "$(CAMLRUN) ../../ocamlopt" -linkall \
+ $(CAMLOBJS:.cmo=.cmx) $(LINKOPTS)
+ mv $(LIBNAME)nat.cmxa $(LIBNAME).cmxa
+ mv $(LIBNAME)nat.$(A) $(LIBNAME).$(A)
+
+$(LIBNAME).cmxs: $(LIBNAME).cmxa lib$(LIBNAME)nat.$(A)
+ $(CAMLOPT) -shared -o $(LIBNAME).cmxs -I . $(LIBNAME).cmxa -linkall
+
+lib$(LIBNAME)nat.$(A): $(COBJS_NAT)
+ $(MKLIB) -o $(LIBNAME)nat $(COBJS_NAT) $(LDOPTS)
+
+st_stubs_n.$(O): st_stubs.c st_win32.h
+ $(NATIVECC) -DNATIVE_CODE -I../../asmrun -I../../byterun \
+ $(NATIVECCCOMPOPTS) -c st_stubs.c
+ mv st_stubs.$(O) st_stubs_n.$(O)
+
+$(CAMLOBJS:.cmo=.cmx): ../../ocamlopt
+
+partialclean:
+ rm -f *.cm*
+
+clean: partialclean
+ rm -f *.dll *.$(A) *.$(O)
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+INSTALL_STUBLIBDIR=$(DESTDIR)$(STUBLIBDIR)
+
+install:
+ cp dllthreads.dll $(INSTALL_STUBLIBDIR)/dllthreads.dll
+ cp libthreads.$(A) $(INSTALL_LIBDIR)/libthreads.$(A)
+ mkdir -p $(INSTALL_LIBDIR)/threads
+ cp $(CMIFILES) threads.cma $(INSTALL_LIBDIR)/threads
+ rm -f $(INSTALL_LIBDIR)/threads/stdlib.cma
+ cp threads.h $(INSTALL_LIBDIR)/caml/threads.h
+
+installopt:
+ cp libthreadsnat.$(A) $(INSTALL_LIBDIR)/libthreadsnat.$(A)
+ cp $(THREAD_OBJS:.cmo=.cmx) threads.cmxa threads.$(A) $(INSTALL_LIBDIR)/threads
+ cp threads.cmxs $(INSTALL_LIBDIR)/threads
+
+.SUFFIXES: .ml .mli .cmo .cmi .cmx
+
+.mli.cmi:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmo:
+ $(CAMLC) -c -g $(COMPFLAGS) $<
+
+.ml.cmx:
+ $(CAMLOPT) -c $(COMPFLAGS) $<
+
+depend:
+
+include .depend
diff --git a/otherlibs/systhreads/condition.ml b/otherlibs/systhreads/condition.ml
new file mode 100644
index 0000000000..4d12378d76
--- /dev/null
+++ b/otherlibs/systhreads/condition.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type t
+external create: unit -> t = "caml_condition_new"
+external wait: t -> Mutex.t -> unit = "caml_condition_wait"
+external signal: t -> unit = "caml_condition_signal"
+external broadcast: t -> unit = "caml_condition_broadcast"
diff --git a/otherlibs/systhreads/condition.mli b/otherlibs/systhreads/condition.mli
new file mode 100644
index 0000000000..9e005dc663
--- /dev/null
+++ b/otherlibs/systhreads/condition.mli
@@ -0,0 +1,51 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Condition variables to synchronize between threads.
+
+ Condition variables are used when one thread wants to wait until another
+ thread has finished doing something: the former thread 'waits' on the
+ condition variable, the latter thread 'signals' the condition when it
+ is done. Condition variables should always be protected by a mutex.
+ The typical use is (if [D] is a shared data structure, [m] its mutex,
+ and [c] is a condition variable):
+ {[
+ Mutex.lock m;
+ while (* some predicate P over D is not satisfied *) do
+ Condition.wait c m
+ done;
+ (* Modify D *)
+ if (* the predicate P over D is now satified *) then Condition.signal c;
+ Mutex.unlock m
+ ]}
+*)
+
+type t
+(** The type of condition variables. *)
+
+val create : unit -> t
+(** Return a new condition variable. *)
+
+val wait : t -> Mutex.t -> unit
+(** [wait c m] atomically unlocks the mutex [m] and suspends the
+ calling process on the condition variable [c]. The process will
+ restart after the condition variable [c] has been signalled.
+ The mutex [m] is locked again before [wait] returns. *)
+
+val signal : t -> unit
+(** [signal c] restarts one of the processes waiting on the
+ condition variable [c]. *)
+
+val broadcast : t -> unit
+(** [broadcast c] restarts all processes waiting on the
+ condition variable [c]. *)
diff --git a/otherlibs/systhreads/event.ml b/otherlibs/systhreads/event.ml
new file mode 100644
index 0000000000..68d8a5b456
--- /dev/null
+++ b/otherlibs/systhreads/event.ml
@@ -0,0 +1,272 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* David Nowak and Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Events *)
+type 'a basic_event =
+ { poll: unit -> bool;
+ (* If communication can take place immediately, return true. *)
+ suspend: unit -> unit;
+ (* Offer the communication on the channel and get ready
+ to suspend current process. *)
+ result: unit -> 'a }
+ (* Return the result of the communication *)
+
+type 'a behavior = int ref -> Condition.t -> int -> 'a basic_event
+
+type 'a event =
+ Communication of 'a behavior
+ | Choose of 'a event list
+ | WrapAbort of 'a event * (unit -> unit)
+ | Guard of (unit -> 'a event)
+
+(* Communication channels *)
+type 'a channel =
+ { mutable writes_pending: 'a communication Queue.t;
+ (* All offers to write on it *)
+ mutable reads_pending: 'a communication Queue.t }
+ (* All offers to read from it *)
+
+(* Communication offered *)
+and 'a communication =
+ { performed: int ref; (* -1 if not performed yet, set to the number *)
+ (* of the matching communication after rendez-vous. *)
+ condition: Condition.t; (* To restart the blocked thread. *)
+ mutable data: 'a option; (* The data sent or received. *)
+ event_number: int } (* Event number in select *)
+
+(* Create a channel *)
+
+let new_channel () =
+ { writes_pending = Queue.create();
+ reads_pending = Queue.create() }
+
+(* Basic synchronization function *)
+
+let masterlock = Mutex.create()
+
+let do_aborts abort_env genev performed =
+ if abort_env <> [] then begin
+ if performed >= 0 then begin
+ let ids_done = snd genev.(performed) in
+ List.iter
+ (fun (id,f) -> if not (List.mem id ids_done) then f ())
+ abort_env
+ end else begin
+ List.iter (fun (_,f) -> f ()) abort_env
+ end
+ end
+
+let basic_sync abort_env genev =
+ let performed = ref (-1) in
+ let condition = Condition.create() in
+ let bev = Array.make (Array.length genev)
+ (fst (genev.(0)) performed condition 0) in
+ for i = 1 to Array.length genev - 1 do
+ bev.(i) <- (fst genev.(i)) performed condition i
+ done;
+ (* See if any of the events is already activable *)
+ let rec poll_events i =
+ if i >= Array.length bev
+ then false
+ else bev.(i).poll() || poll_events (i+1) in
+ Mutex.lock masterlock;
+ if not (poll_events 0) then begin
+ (* Suspend on all events *)
+ for i = 0 to Array.length bev - 1 do bev.(i).suspend() done;
+ (* Wait until the condition is signalled *)
+ Condition.wait condition masterlock
+ end;
+ Mutex.unlock masterlock;
+ (* Extract the result *)
+ if abort_env = [] then
+ (* Preserve tail recursion *)
+ bev.(!performed).result()
+ else begin
+ let num = !performed in
+ let result = bev.(num).result() in
+ (* Handle the aborts and return the result *)
+ do_aborts abort_env genev num;
+ result
+ end
+
+(* Apply a random permutation on an array *)
+
+let scramble_array a =
+ let len = Array.length a in
+ if len = 0 then invalid_arg "Event.choose";
+ for i = len - 1 downto 1 do
+ let j = Random.int (i + 1) in
+ let temp = a.(i) in a.(i) <- a.(j); a.(j) <- temp
+ done;
+ a
+
+(* Main synchronization function *)
+
+let gensym = let count = ref 0 in fun () -> incr count; !count
+
+let rec flatten_event
+ (abort_list : int list)
+ (accu : ('a behavior * int list) list)
+ (accu_abort : (int * (unit -> unit)) list)
+ ev =
+ match ev with
+ Communication bev -> ((bev,abort_list) :: accu) , accu_abort
+ | WrapAbort (ev,fn) ->
+ let id = gensym () in
+ flatten_event (id :: abort_list) accu ((id,fn)::accu_abort) ev
+ | Choose evl ->
+ let rec flatten_list accu' accu_abort'= function
+ ev :: l ->
+ let (accu'',accu_abort'') =
+ flatten_event abort_list accu' accu_abort' ev in
+ flatten_list accu'' accu_abort'' l
+ | [] -> (accu',accu_abort') in
+ flatten_list accu accu_abort evl
+ | Guard fn -> flatten_event abort_list accu accu_abort (fn ())
+
+let sync ev =
+ let (evl,abort_env) = flatten_event [] [] [] ev in
+ basic_sync abort_env (scramble_array(Array.of_list evl))
+
+(* Event polling -- like sync, but non-blocking *)
+
+let basic_poll abort_env genev =
+ let performed = ref (-1) in
+ let condition = Condition.create() in
+ let bev = Array.make(Array.length genev)
+ (fst genev.(0) performed condition 0) in
+ for i = 1 to Array.length genev - 1 do
+ bev.(i) <- fst genev.(i) performed condition i
+ done;
+ (* See if any of the events is already activable *)
+ let rec poll_events i =
+ if i >= Array.length bev
+ then false
+ else bev.(i).poll() || poll_events (i+1) in
+ Mutex.lock masterlock;
+ let ready = poll_events 0 in
+ if ready then begin
+ (* Extract the result *)
+ Mutex.unlock masterlock;
+ let result = Some(bev.(!performed).result()) in
+ do_aborts abort_env genev !performed; result
+ end else begin
+ (* Cancel the communication offers *)
+ performed := 0;
+ Mutex.unlock masterlock;
+ do_aborts abort_env genev (-1);
+ None
+ end
+
+let poll ev =
+ let (evl,abort_env) = flatten_event [] [] [] ev in
+ basic_poll abort_env (scramble_array(Array.of_list evl))
+
+(* Remove all communication opportunities already synchronized *)
+
+let cleanup_queue q =
+ let q' = Queue.create() in
+ Queue.iter (fun c -> if !(c.performed) = -1 then Queue.add c q') q;
+ q'
+
+(* Event construction *)
+
+let always data =
+ Communication(fun performed condition evnum ->
+ { poll = (fun () -> performed := evnum; true);
+ suspend = (fun () -> ());
+ result = (fun () -> data) })
+
+let send channel data =
+ Communication(fun performed condition evnum ->
+ let wcomm =
+ { performed = performed;
+ condition = condition;
+ data = Some data;
+ event_number = evnum } in
+ { poll = (fun () ->
+ let rec poll () =
+ let rcomm = Queue.take channel.reads_pending in
+ if !(rcomm.performed) >= 0 then
+ poll ()
+ else begin
+ rcomm.data <- wcomm.data;
+ performed := evnum;
+ rcomm.performed := rcomm.event_number;
+ Condition.signal rcomm.condition
+ end in
+ try
+ poll();
+ true
+ with Queue.Empty ->
+ false);
+ suspend = (fun () ->
+ channel.writes_pending <- cleanup_queue channel.writes_pending;
+ Queue.add wcomm channel.writes_pending);
+ result = (fun () -> ()) })
+
+let receive channel =
+ Communication(fun performed condition evnum ->
+ let rcomm =
+ { performed = performed;
+ condition = condition;
+ data = None;
+ event_number = evnum } in
+ { poll = (fun () ->
+ let rec poll () =
+ let wcomm = Queue.take channel.writes_pending in
+ if !(wcomm.performed) >= 0 then
+ poll ()
+ else begin
+ rcomm.data <- wcomm.data;
+ performed := evnum;
+ wcomm.performed := wcomm.event_number;
+ Condition.signal wcomm.condition
+ end in
+ try
+ poll();
+ true
+ with Queue.Empty ->
+ false);
+ suspend = (fun () ->
+ channel.reads_pending <- cleanup_queue channel.reads_pending;
+ Queue.add rcomm channel.reads_pending);
+ result = (fun () ->
+ match rcomm.data with
+ None -> invalid_arg "Event.receive"
+ | Some res -> res) })
+
+let choose evl = Choose evl
+
+let wrap_abort ev fn = WrapAbort(ev,fn)
+
+let guard fn = Guard fn
+
+let rec wrap ev fn =
+ match ev with
+ Communication genev ->
+ Communication(fun performed condition evnum ->
+ let bev = genev performed condition evnum in
+ { poll = bev.poll;
+ suspend = bev.suspend;
+ result = (fun () -> fn(bev.result())) })
+ | Choose evl ->
+ Choose(List.map (fun ev -> wrap ev fn) evl)
+ | WrapAbort (ev, f') ->
+ WrapAbort (wrap ev fn, f')
+ | Guard gu ->
+ Guard(fun () -> wrap (gu()) fn)
+
+(* Convenience functions *)
+
+let select evl = sync(Choose evl)
diff --git a/otherlibs/systhreads/event.mli b/otherlibs/systhreads/event.mli
new file mode 100644
index 0000000000..8352ca1fc8
--- /dev/null
+++ b/otherlibs/systhreads/event.mli
@@ -0,0 +1,79 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* David Nowak and Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** First-class synchronous communication.
+
+ This module implements synchronous inter-thread communications over
+ channels. As in John Reppy's Concurrent ML system, the communication
+ events are first-class values: they can be built and combined
+ independently before being offered for communication.
+*)
+
+type 'a channel
+(** The type of communication channels carrying values of type ['a]. *)
+
+val new_channel : unit -> 'a channel
+(** Return a new channel. *)
+
+type +'a event
+(** The type of communication events returning a result of type ['a]. *)
+
+(** [send ch v] returns the event consisting in sending the value [v]
+ over the channel [ch]. The result value of this event is [()]. *)
+val send : 'a channel -> 'a -> unit event
+
+(** [receive ch] returns the event consisting in receiving a value
+ from the channel [ch]. The result value of this event is the
+ value received. *)
+val receive : 'a channel -> 'a event
+
+val always : 'a -> 'a event
+(** [always v] returns an event that is always ready for
+ synchronization. The result value of this event is [v]. *)
+
+val choose : 'a event list -> 'a event
+(** [choose evl] returns the event that is the alternative of
+ all the events in the list [evl]. *)
+
+val wrap : 'a event -> ('a -> 'b) -> 'b event
+(** [wrap ev fn] returns the event that performs the same communications
+ as [ev], then applies the post-processing function [fn]
+ on the return value. *)
+
+val wrap_abort : 'a event -> (unit -> unit) -> 'a event
+(** [wrap_abort ev fn] returns the event that performs
+ the same communications as [ev], but if it is not selected
+ the function [fn] is called after the synchronization. *)
+
+val guard : (unit -> 'a event) -> 'a event
+(** [guard fn] returns the event that, when synchronized, computes
+ [fn()] and behaves as the resulting event. This allows to
+ compute events with side-effects at the time of the synchronization
+ operation. *)
+
+val sync : 'a event -> 'a
+(** 'Synchronize' on an event: offer all the communication
+ possibilities specified in the event to the outside world,
+ and block until one of the communications succeed. The result
+ value of that communication is returned. *)
+
+val select : 'a event list -> 'a
+(** 'Synchronize' on an alternative of events.
+ [select evl] is shorthand for [sync(choose evl)]. *)
+
+val poll : 'a event -> 'a option
+(** Non-blocking version of {!Event.sync}: offer all the communication
+ possibilities specified in the event to the outside world,
+ and if one can take place immediately, perform it and return
+ [Some r] where [r] is the result value of that communication.
+ Otherwise, return [None] without blocking. *)
diff --git a/otherlibs/systhreads/libthreads.clib b/otherlibs/systhreads/libthreads.clib
new file mode 100644
index 0000000000..a0582d41fa
--- /dev/null
+++ b/otherlibs/systhreads/libthreads.clib
@@ -0,0 +1 @@
+st_stubs_b.o
diff --git a/otherlibs/systhreads/mutex.ml b/otherlibs/systhreads/mutex.ml
new file mode 100644
index 0000000000..5b8be9da47
--- /dev/null
+++ b/otherlibs/systhreads/mutex.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Pascal Cuoq, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type t
+external create: unit -> t = "caml_mutex_new"
+external lock: t -> unit = "caml_mutex_lock"
+external try_lock: t -> bool = "caml_mutex_try_lock"
+external unlock: t -> unit = "caml_mutex_unlock"
diff --git a/otherlibs/systhreads/mutex.mli b/otherlibs/systhreads/mutex.mli
new file mode 100644
index 0000000000..265ae94e6f
--- /dev/null
+++ b/otherlibs/systhreads/mutex.mli
@@ -0,0 +1,47 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Locks for mutual exclusion.
+
+ Mutexes (mutual-exclusion locks) are used to implement critical sections
+ and protect shared mutable data structures against concurrent accesses.
+ The typical use is (if [m] is the mutex associated with the data structure
+ [D]):
+ {[
+ Mutex.lock m;
+ (* Critical section that operates over D *);
+ Mutex.unlock m
+ ]}
+*)
+
+type t
+(** The type of mutexes. *)
+
+val create : unit -> t
+(** Return a new mutex. *)
+
+val lock : t -> unit
+(** Lock the given mutex. Only one thread can have the mutex locked
+ at any time. A thread that attempts to lock a mutex already locked
+ by another thread will suspend until the other thread unlocks
+ the mutex. *)
+
+val try_lock : t -> bool
+(** Same as {!Mutex.lock}, but does not suspend the calling thread if
+ the mutex is already locked: just return [false] immediately
+ in that case. If the mutex is unlocked, lock it and
+ return [true]. *)
+
+val unlock : t -> unit
+(** Unlock the given mutex. Other threads suspended trying to lock
+ the mutex will restart. *)
diff --git a/otherlibs/systhreads/st_posix.h b/otherlibs/systhreads/st_posix.h
new file mode 100644
index 0000000000..b9e2a25b20
--- /dev/null
+++ b/otherlibs/systhreads/st_posix.h
@@ -0,0 +1,426 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 2009 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* POSIX thread implementation of the "st" interface */
+
+#include <errno.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <pthread.h>
+#ifdef __sun
+#define _POSIX_PTHREAD_SEMANTICS
+#endif
+#include <signal.h>
+#include <sys/time.h>
+#ifdef __linux__
+#include <unistd.h>
+#endif
+
+#ifdef __GNUC__
+#define INLINE inline
+#else
+#define INLINE
+#endif
+
+typedef int st_retcode;
+
+#define SIGPREEMPTION SIGVTALRM
+
+/* OS-specific initialization */
+
+static int st_initialize(void)
+{
+ return 0;
+}
+
+/* Thread creation. Created in detached mode if [res] is NULL. */
+
+typedef pthread_t st_thread_id;
+
+static int st_thread_create(st_thread_id * res,
+ void * (*fn)(void *), void * arg)
+{
+ pthread_t thr;
+ pthread_attr_t attr;
+ int rc;
+
+ pthread_attr_init(&attr);
+ if (res == NULL) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
+ rc = pthread_create(&thr, &attr, fn, arg);
+ if (res != NULL) *res = thr;
+ return rc;
+}
+
+#define ST_THREAD_FUNCTION void *
+
+/* Cleanup at thread exit */
+
+static INLINE void st_thread_cleanup(void)
+{
+ return;
+}
+
+/* Thread termination */
+
+static void st_thread_exit(void)
+{
+ pthread_exit(NULL);
+}
+
+static void st_thread_join(st_thread_id thr)
+{
+ pthread_join(thr, NULL);
+ /* best effort: ignore errors */
+}
+
+/* Scheduling hints */
+
+static void INLINE st_thread_yield(void)
+{
+#ifndef __linux__
+ /* sched_yield() doesn't do what we want in Linux 2.6 and up (PR#2663) */
+ sched_yield();
+#endif
+}
+
+/* Thread-specific state */
+
+typedef pthread_key_t st_tlskey;
+
+static int st_tls_newkey(st_tlskey * res)
+{
+ return pthread_key_create(res, NULL);
+}
+
+static INLINE void * st_tls_get(st_tlskey k)
+{
+ return pthread_getspecific(k);
+}
+
+static INLINE void st_tls_set(st_tlskey k, void * v)
+{
+ pthread_setspecific(k, v);
+}
+
+/* The master lock. This is a mutex that is held most of the time,
+ so we implement it in a slightly consoluted way to avoid
+ all risks of busy-waiting. Also, we count the number of waiting
+ threads. */
+
+typedef struct {
+ pthread_mutex_t lock; /* to protect contents */
+ int busy; /* 0 = free, 1 = taken */
+ volatile int waiters; /* number of threads waiting on master lock */
+ pthread_cond_t is_free; /* signaled when free */
+} st_masterlock;
+
+static void st_masterlock_init(st_masterlock * m)
+{
+ pthread_mutex_init(&m->lock, NULL);
+ pthread_cond_init(&m->is_free, NULL);
+ m->busy = 1;
+ m->waiters = 0;
+}
+
+static void st_masterlock_acquire(st_masterlock * m)
+{
+ pthread_mutex_lock(&m->lock);
+ while (m->busy) {
+ m->waiters ++;
+ pthread_cond_wait(&m->is_free, &m->lock);
+ m->waiters --;
+ }
+ m->busy = 1;
+ pthread_mutex_unlock(&m->lock);
+}
+
+static void st_masterlock_release(st_masterlock * m)
+{
+ pthread_mutex_lock(&m->lock);
+ m->busy = 0;
+ pthread_mutex_unlock(&m->lock);
+ pthread_cond_signal(&m->is_free);
+}
+
+static INLINE int st_masterlock_waiters(st_masterlock * m)
+{
+ return m->waiters;
+}
+
+/* Mutexes */
+
+typedef pthread_mutex_t * st_mutex;
+
+static int st_mutex_create(st_mutex * res)
+{
+ int rc;
+ st_mutex m = malloc(sizeof(pthread_mutex_t));
+ if (m == NULL) return ENOMEM;
+ rc = pthread_mutex_init(m, NULL);
+ if (rc != 0) { free(m); return rc; }
+ *res = m;
+ return 0;
+}
+
+static int st_mutex_destroy(st_mutex m)
+{
+ int rc;
+ rc = pthread_mutex_destroy(m);
+ free(m);
+ return rc;
+}
+
+static INLINE int st_mutex_lock(st_mutex m)
+{
+ return pthread_mutex_lock(m);
+}
+
+#define PREVIOUSLY_UNLOCKED 0
+#define ALREADY_LOCKED EBUSY
+
+static INLINE int st_mutex_trylock(st_mutex m)
+{
+ return pthread_mutex_trylock(m);
+}
+
+static INLINE int st_mutex_unlock(st_mutex m)
+{
+ return pthread_mutex_unlock(m);
+}
+
+/* Condition variables */
+
+typedef pthread_cond_t * st_condvar;
+
+static int st_condvar_create(st_condvar * res)
+{
+ int rc;
+ st_condvar c = malloc(sizeof(pthread_cond_t));
+ if (c == NULL) return ENOMEM;
+ rc = pthread_cond_init(c, NULL);
+ if (rc != 0) { free(c); return rc; }
+ *res = c;
+ return 0;
+}
+
+static int st_condvar_destroy(st_condvar c)
+{
+ int rc;
+ rc = pthread_cond_destroy(c);
+ free(c);
+ return rc;
+}
+
+static INLINE int st_condvar_signal(st_condvar c)
+{
+ return pthread_cond_signal(c);
+}
+
+static INLINE int st_condvar_broadcast(st_condvar c)
+{
+ return pthread_cond_broadcast(c);
+}
+
+static INLINE int st_condvar_wait(st_condvar c, st_mutex m)
+{
+ return pthread_cond_wait(c, m);
+}
+
+/* Triggered events */
+
+typedef struct st_event_struct {
+ pthread_mutex_t lock; /* to protect contents */
+ int status; /* 0 = not triggered, 1 = triggered */
+ pthread_cond_t triggered; /* signaled when triggered */
+} * st_event;
+
+static int st_event_create(st_event * res)
+{
+ int rc;
+ st_event e = malloc(sizeof(struct st_event_struct));
+ if (e == NULL) return ENOMEM;
+ rc = pthread_mutex_init(&e->lock, NULL);
+ if (rc != 0) { free(e); return rc; }
+ rc = pthread_cond_init(&e->triggered, NULL);
+ if (rc != 0) { pthread_mutex_destroy(&e->lock); free(e); return rc; }
+ e->status = 0;
+ *res = e;
+ return 0;
+}
+
+static int st_event_destroy(st_event e)
+{
+ int rc1, rc2;
+ rc1 = pthread_mutex_destroy(&e->lock);
+ rc2 = pthread_cond_destroy(&e->triggered);
+ free(e);
+ return rc1 != 0 ? rc1 : rc2;
+}
+
+static int st_event_trigger(st_event e)
+{
+ int rc;
+ rc = pthread_mutex_lock(&e->lock);
+ if (rc != 0) return rc;
+ e->status = 1;
+ rc = pthread_mutex_unlock(&e->lock);
+ if (rc != 0) return rc;
+ rc = pthread_cond_broadcast(&e->triggered);
+ return rc;
+}
+
+static int st_event_wait(st_event e)
+{
+ int rc;
+ rc = pthread_mutex_lock(&e->lock);
+ if (rc != 0) return rc;
+ while(e->status == 0) {
+ rc = pthread_cond_wait(&e->triggered, &e->lock);
+ if (rc != 0) return rc;
+ }
+ rc = pthread_mutex_unlock(&e->lock);
+ return rc;
+}
+
+/* Reporting errors */
+
+static void st_check_error(int retcode, char * msg)
+{
+ char * err;
+ int errlen, msglen;
+ value str;
+
+ if (retcode == 0) return;
+ if (retcode == ENOMEM) raise_out_of_memory();
+ err = strerror(retcode);
+ msglen = strlen(msg);
+ errlen = strlen(err);
+ str = alloc_string(msglen + 2 + errlen);
+ memmove (&Byte(str, 0), msg, msglen);
+ memmove (&Byte(str, msglen), ": ", 2);
+ memmove (&Byte(str, msglen + 2), err, errlen);
+ raise_sys_error(str);
+}
+
+/* Variable used to stop the "tick" thread */
+static volatile int caml_tick_thread_stop = 0;
+
+/* The tick thread: posts a SIGPREEMPTION signal periodically */
+
+static void * caml_thread_tick(void * arg)
+{
+ struct timeval timeout;
+ sigset_t mask;
+
+ /* Block all signals so that we don't try to execute an OCaml signal handler*/
+ sigfillset(&mask);
+ pthread_sigmask(SIG_BLOCK, &mask, NULL);
+ while(! caml_tick_thread_stop) {
+ /* select() seems to be the most efficient way to suspend the
+ thread for sub-second intervals */
+ timeout.tv_sec = 0;
+ timeout.tv_usec = Thread_timeout * 1000;
+ select(0, NULL, NULL, NULL, &timeout);
+ /* The preemption signal should never cause a callback, so don't
+ go through caml_handle_signal(), just record signal delivery via
+ caml_record_signal(). */
+ caml_record_signal(SIGPREEMPTION);
+ }
+ return NULL;
+}
+
+/* "At fork" processing */
+
+#if defined(__ANDROID__)
+/* Android's libc does not include declaration of pthread_atfork;
+ however, it implements it since API level 10 (Gingerbread).
+ The reason for the omission is that Android (GUI) applications
+ are not supposed to fork at all, however this workaround is still
+ included in case OCaml is used for an Android CLI utility. */
+int pthread_atfork(void (*prepare)(void), void (*parent)(void),
+ void (*child)(void));
+#endif
+
+static int st_atfork(void (*fn)(void))
+{
+ return pthread_atfork(NULL, NULL, fn);
+}
+
+/* Signal handling */
+
+static void st_decode_sigset(value vset, sigset_t * set)
+{
+ sigemptyset(set);
+ while (vset != Val_int(0)) {
+ int sig = caml_convert_signal_number(Int_val(Field(vset, 0)));
+ sigaddset(set, sig);
+ vset = Field(vset, 1);
+ }
+}
+
+#ifndef NSIG
+#define NSIG 64
+#endif
+
+static value st_encode_sigset(sigset_t * set)
+{
+ value res = Val_int(0);
+ int i;
+
+ Begin_root(res)
+ for (i = 1; i < NSIG; i++)
+ if (sigismember(set, i) > 0) {
+ value newcons = alloc_small(2, 0);
+ Field(newcons, 0) = Val_int(caml_rev_convert_signal_number(i));
+ Field(newcons, 1) = res;
+ res = newcons;
+ }
+ End_roots();
+ return res;
+}
+
+static int sigmask_cmd[3] = { SIG_SETMASK, SIG_BLOCK, SIG_UNBLOCK };
+
+value caml_thread_sigmask(value cmd, value sigs) /* ML */
+{
+ int how;
+ sigset_t set, oldset;
+ int retcode;
+
+ how = sigmask_cmd[Int_val(cmd)];
+ st_decode_sigset(sigs, &set);
+ enter_blocking_section();
+ retcode = pthread_sigmask(how, &set, &oldset);
+ leave_blocking_section();
+ st_check_error(retcode, "Thread.sigmask");
+ return st_encode_sigset(&oldset);
+}
+
+value caml_wait_signal(value sigs) /* ML */
+{
+#ifdef HAS_SIGWAIT
+ sigset_t set;
+ int retcode, signo;
+
+ st_decode_sigset(sigs, &set);
+ enter_blocking_section();
+ retcode = sigwait(&set, &signo);
+ leave_blocking_section();
+ st_check_error(retcode, "Thread.wait_signal");
+ return Val_int(signo);
+#else
+ invalid_argument("Thread.wait_signal not implemented");
+ return Val_int(0); /* not reached */
+#endif
+}
diff --git a/otherlibs/systhreads/st_stubs.c b/otherlibs/systhreads/st_stubs.c
new file mode 100644
index 0000000000..6ee4bbc199
--- /dev/null
+++ b/otherlibs/systhreads/st_stubs.c
@@ -0,0 +1,889 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1995 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "caml/alloc.h"
+#include "caml/backtrace.h"
+#include "caml/callback.h"
+#include "caml/custom.h"
+#include "caml/fail.h"
+#include "caml/io.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/printexc.h"
+#include "caml/roots.h"
+#include "caml/signals.h"
+#ifdef NATIVE_CODE
+#include "stack.h"
+#else
+#include "caml/stacks.h"
+#endif
+#include "caml/sys.h"
+#include "threads.h"
+
+/* Initial size of bytecode stack when a thread is created (4 Ko) */
+#define Thread_stack_size (Stack_size / 4)
+
+/* Max computation time before rescheduling, in milliseconds */
+#define Thread_timeout 50
+
+/* OS-specific code */
+#ifdef _WIN32
+#include "st_win32.h"
+#else
+#include "st_posix.h"
+#endif
+
+/* The ML value describing a thread (heap-allocated) */
+
+struct caml_thread_descr {
+ value ident; /* Unique integer ID */
+ value start_closure; /* The closure to start this thread */
+ value terminated; /* Triggered event for thread termination */
+};
+
+#define Ident(v) (((struct caml_thread_descr *)(v))->ident)
+#define Start_closure(v) (((struct caml_thread_descr *)(v))->start_closure)
+#define Terminated(v) (((struct caml_thread_descr *)(v))->terminated)
+
+/* The infos on threads (allocated via malloc()) */
+
+struct caml_thread_struct {
+ value descr; /* The heap-allocated descriptor (root) */
+ struct caml_thread_struct * next; /* Double linking of running threads */
+ struct caml_thread_struct * prev;
+#ifdef NATIVE_CODE
+ char * top_of_stack; /* Top of stack for this thread (approx.) */
+ char * bottom_of_stack; /* Saved value of caml_bottom_of_stack */
+ uintnat last_retaddr; /* Saved value of caml_last_return_address */
+ value * gc_regs; /* Saved value of caml_gc_regs */
+ char * exception_pointer; /* Saved value of caml_exception_pointer */
+ struct caml__roots_block * local_roots; /* Saved value of local_roots */
+ struct longjmp_buffer * exit_buf; /* For thread exit */
+#else
+ value * stack_low; /* The execution stack for this thread */
+ value * stack_high;
+ value * stack_threshold;
+ value * sp; /* Saved value of extern_sp for this thread */
+ value * trapsp; /* Saved value of trapsp for this thread */
+ struct caml__roots_block * local_roots; /* Saved value of local_roots */
+ struct longjmp_buffer * external_raise; /* Saved external_raise */
+#endif
+ int backtrace_pos; /* Saved backtrace_pos */
+ backtrace_slot * backtrace_buffer; /* Saved backtrace_buffer */
+ value backtrace_last_exn; /* Saved backtrace_last_exn (root) */
+};
+
+typedef struct caml_thread_struct * caml_thread_t;
+
+/* The "head" of the circular list of thread descriptors */
+static caml_thread_t all_threads = NULL;
+
+/* The descriptor for the currently executing thread */
+static caml_thread_t curr_thread = NULL;
+
+/* The master lock protecting the OCaml runtime system */
+static st_masterlock caml_master_lock;
+
+/* Whether the "tick" thread is already running */
+static int caml_tick_thread_running = 0;
+
+/* The thread identifier of the "tick" thread */
+static st_thread_id caml_tick_thread_id;
+
+/* The key used for storing the thread descriptor in the specific data
+ of the corresponding system thread. */
+static st_tlskey thread_descriptor_key;
+
+/* The key used for unlocking I/O channels on exceptions */
+static st_tlskey last_channel_locked_key;
+
+/* Identifier for next thread creation */
+static intnat thread_next_ident = 0;
+
+/* Forward declarations */
+static value caml_threadstatus_new (void);
+static void caml_threadstatus_terminate (value);
+static st_retcode caml_threadstatus_wait (value);
+
+/* Imports from the native-code runtime system */
+#ifdef NATIVE_CODE
+extern struct longjmp_buffer caml_termination_jmpbuf;
+extern void (*caml_termination_hook)(void);
+#endif
+
+/* Hook for scanning the stacks of the other threads */
+
+static void (*prev_scan_roots_hook) (scanning_action);
+
+static void caml_thread_scan_roots(scanning_action action)
+{
+ caml_thread_t th;
+
+ th = curr_thread;
+ do {
+ (*action)(th->descr, &th->descr);
+ (*action)(th->backtrace_last_exn, &th->backtrace_last_exn);
+ /* Don't rescan the stack of the current thread, it was done already */
+ if (th != curr_thread) {
+#ifdef NATIVE_CODE
+ if (th->bottom_of_stack != NULL)
+ do_local_roots(action, th->bottom_of_stack, th->last_retaddr,
+ th->gc_regs, th->local_roots);
+#else
+ do_local_roots(action, th->sp, th->stack_high, th->local_roots);
+#endif
+ }
+ th = th->next;
+ } while (th != curr_thread);
+ /* Hook */
+ if (prev_scan_roots_hook != NULL) (*prev_scan_roots_hook)(action);
+}
+
+/* Hooks for enter_blocking_section and leave_blocking_section */
+
+static void caml_thread_enter_blocking_section(void)
+{
+ /* Save the stack-related global variables in the thread descriptor
+ of the current thread */
+#ifdef NATIVE_CODE
+ curr_thread->bottom_of_stack = caml_bottom_of_stack;
+ curr_thread->last_retaddr = caml_last_return_address;
+ curr_thread->gc_regs = caml_gc_regs;
+ curr_thread->exception_pointer = caml_exception_pointer;
+ curr_thread->local_roots = local_roots;
+#else
+ curr_thread->stack_low = stack_low;
+ curr_thread->stack_high = stack_high;
+ curr_thread->stack_threshold = stack_threshold;
+ curr_thread->sp = extern_sp;
+ curr_thread->trapsp = trapsp;
+ curr_thread->local_roots = local_roots;
+ curr_thread->external_raise = external_raise;
+#endif
+ curr_thread->backtrace_pos = backtrace_pos;
+ curr_thread->backtrace_buffer = backtrace_buffer;
+ curr_thread->backtrace_last_exn = backtrace_last_exn;
+ /* Tell other threads that the runtime is free */
+ st_masterlock_release(&caml_master_lock);
+}
+
+static void caml_thread_leave_blocking_section(void)
+{
+ /* Wait until the runtime is free */
+ st_masterlock_acquire(&caml_master_lock);
+ /* Update curr_thread to point to the thread descriptor corresponding
+ to the thread currently executing */
+ curr_thread = st_tls_get(thread_descriptor_key);
+ /* Restore the stack-related global variables */
+#ifdef NATIVE_CODE
+ caml_bottom_of_stack= curr_thread->bottom_of_stack;
+ caml_last_return_address = curr_thread->last_retaddr;
+ caml_gc_regs = curr_thread->gc_regs;
+ caml_exception_pointer = curr_thread->exception_pointer;
+ local_roots = curr_thread->local_roots;
+#else
+ stack_low = curr_thread->stack_low;
+ stack_high = curr_thread->stack_high;
+ stack_threshold = curr_thread->stack_threshold;
+ extern_sp = curr_thread->sp;
+ trapsp = curr_thread->trapsp;
+ local_roots = curr_thread->local_roots;
+ external_raise = curr_thread->external_raise;
+#endif
+ backtrace_pos = curr_thread->backtrace_pos;
+ backtrace_buffer = curr_thread->backtrace_buffer;
+ backtrace_last_exn = curr_thread->backtrace_last_exn;
+}
+
+static int caml_thread_try_leave_blocking_section(void)
+{
+ /* Disable immediate processing of signals (PR#3659).
+ try_leave_blocking_section always fails, forcing the signal to be
+ recorded and processed at the next leave_blocking_section or
+ polling. */
+ return 0;
+}
+
+/* Hooks for I/O locking */
+
+static void caml_io_mutex_free(struct channel *chan)
+{
+ st_mutex mutex = chan->mutex;
+ if (mutex != NULL) st_mutex_destroy(mutex);
+}
+
+static void caml_io_mutex_lock(struct channel *chan)
+{
+ st_mutex mutex = chan->mutex;
+
+ if (mutex == NULL) {
+ st_mutex_create(&mutex);
+ chan->mutex = mutex;
+ }
+ /* PR#4351: first try to acquire mutex without releasing the master lock */
+ if (st_mutex_trylock(mutex) == PREVIOUSLY_UNLOCKED) {
+ st_tls_set(last_channel_locked_key, (void *) chan);
+ return;
+ }
+ /* If unsuccessful, block on mutex */
+ enter_blocking_section();
+ st_mutex_lock(mutex);
+ /* Problem: if a signal occurs at this point,
+ and the signal handler raises an exception, we will not
+ unlock the mutex. The alternative (doing the setspecific
+ before locking the mutex is also incorrect, since we could
+ then unlock a mutex that is unlocked or locked by someone else. */
+ st_tls_set(last_channel_locked_key, (void *) chan);
+ leave_blocking_section();
+}
+
+static void caml_io_mutex_unlock(struct channel *chan)
+{
+ st_mutex_unlock(chan->mutex);
+ st_tls_set(last_channel_locked_key, NULL);
+}
+
+static void caml_io_mutex_unlock_exn(void)
+{
+ struct channel * chan = st_tls_get(last_channel_locked_key);
+ if (chan != NULL) caml_io_mutex_unlock(chan);
+}
+
+/* Hook for estimating stack usage */
+
+static uintnat (*prev_stack_usage_hook)(void);
+
+static uintnat caml_thread_stack_usage(void)
+{
+ uintnat sz;
+ caml_thread_t th;
+
+ /* Don't add stack for current thread, this is done elsewhere */
+ for (sz = 0, th = curr_thread->next;
+ th != curr_thread;
+ th = th->next) {
+#ifdef NATIVE_CODE
+ sz += (value *) th->top_of_stack - (value *) th->bottom_of_stack;
+#else
+ sz += th->stack_high - th->sp;
+#endif
+ }
+ if (prev_stack_usage_hook != NULL)
+ sz += prev_stack_usage_hook();
+ return sz;
+}
+
+/* Create and setup a new thread info block.
+ This block has no associated thread descriptor and
+ is not inserted in the list of threads. */
+
+static caml_thread_t caml_thread_new_info(void)
+{
+ caml_thread_t th;
+
+ th = (caml_thread_t) malloc(sizeof(struct caml_thread_struct));
+ if (th == NULL) return NULL;
+ th->descr = Val_unit; /* filled later */
+#ifdef NATIVE_CODE
+ th->bottom_of_stack = NULL;
+ th->top_of_stack = NULL;
+ th->last_retaddr = 1;
+ th->exception_pointer = NULL;
+ th->local_roots = NULL;
+ th->exit_buf = NULL;
+#else
+ /* Allocate the stacks */
+ th->stack_low = (value *) caml_stat_alloc(Thread_stack_size);
+ th->stack_high = th->stack_low + Thread_stack_size / sizeof(value);
+ th->stack_threshold = th->stack_low + Stack_threshold / sizeof(value);
+ th->sp = th->stack_high;
+ th->trapsp = th->stack_high;
+ th->local_roots = NULL;
+ th->external_raise = NULL;
+#endif
+ th->backtrace_pos = 0;
+ th->backtrace_buffer = NULL;
+ th->backtrace_last_exn = Val_unit;
+ return th;
+}
+
+/* Allocate a thread descriptor block. */
+
+static value caml_thread_new_descriptor(value clos)
+{
+ value mu = Val_unit;
+ value descr;
+ Begin_roots2 (clos, mu)
+ /* Create and initialize the termination semaphore */
+ mu = caml_threadstatus_new();
+ /* Create a descriptor for the new thread */
+ descr = alloc_small(3, 0);
+ Ident(descr) = Val_long(thread_next_ident);
+ Start_closure(descr) = clos;
+ Terminated(descr) = mu;
+ thread_next_ident++;
+ End_roots();
+ return descr;
+}
+
+/* Remove a thread info block from the list of threads.
+ Free it and its stack resources. */
+
+static void caml_thread_remove_info(caml_thread_t th)
+{
+ if (th->next == th)
+ all_threads = NULL; /* last OCaml thread exiting */
+ else if (all_threads == th)
+ all_threads = th->next; /* PR#5295 */
+ th->next->prev = th->prev;
+ th->prev->next = th->next;
+#ifndef NATIVE_CODE
+ stat_free(th->stack_low);
+#endif
+ if (th->backtrace_buffer != NULL) free(th->backtrace_buffer);
+ stat_free(th);
+}
+
+/* Reinitialize the thread machinery after a fork() (PR#4577) */
+
+static void caml_thread_reinitialize(void)
+{
+ caml_thread_t thr, next;
+ struct channel * chan;
+
+ /* Remove all other threads (now nonexistent)
+ from the doubly-linked list of threads */
+ thr = curr_thread->next;
+ while (thr != curr_thread) {
+ next = thr->next;
+ stat_free(thr);
+ thr = next;
+ }
+ curr_thread->next = curr_thread;
+ curr_thread->prev = curr_thread;
+ all_threads = curr_thread;
+ /* Reinitialize the master lock machinery,
+ just in case the fork happened while other threads were doing
+ leave_blocking_section */
+ st_masterlock_init(&caml_master_lock);
+ /* Tick thread is not currently running in child process, will be
+ re-created at next Thread.create */
+ caml_tick_thread_running = 0;
+ /* Destroy all IO mutexes; will be reinitialized on demand */
+ for (chan = caml_all_opened_channels;
+ chan != NULL;
+ chan = chan->next) {
+ if (chan->mutex != NULL) {
+ st_mutex_destroy(chan->mutex);
+ chan->mutex = NULL;
+ }
+ }
+}
+
+/* Initialize the thread machinery */
+
+CAMLprim value caml_thread_initialize(value unit) /* ML */
+{
+ /* Protect against repeated initialization (PR#1325) */
+ if (curr_thread != NULL) return Val_unit;
+ /* OS-specific initialization */
+ st_initialize();
+ /* Initialize and acquire the master lock */
+ st_masterlock_init(&caml_master_lock);
+ /* Initialize the keys */
+ st_tls_newkey(&thread_descriptor_key);
+ st_tls_newkey(&last_channel_locked_key);
+ /* Set up a thread info block for the current thread */
+ curr_thread =
+ (caml_thread_t) caml_stat_alloc(sizeof(struct caml_thread_struct));
+ curr_thread->descr = caml_thread_new_descriptor(Val_unit);
+ curr_thread->next = curr_thread;
+ curr_thread->prev = curr_thread;
+ all_threads = curr_thread;
+ curr_thread->backtrace_last_exn = Val_unit;
+#ifdef NATIVE_CODE
+ curr_thread->exit_buf = &caml_termination_jmpbuf;
+#endif
+ /* The stack-related fields will be filled in at the next
+ enter_blocking_section */
+ /* Associate the thread descriptor with the thread */
+ st_tls_set(thread_descriptor_key, (void *) curr_thread);
+ /* Set up the hooks */
+ prev_scan_roots_hook = scan_roots_hook;
+ scan_roots_hook = caml_thread_scan_roots;
+ enter_blocking_section_hook = caml_thread_enter_blocking_section;
+ leave_blocking_section_hook = caml_thread_leave_blocking_section;
+ try_leave_blocking_section_hook = caml_thread_try_leave_blocking_section;
+#ifdef NATIVE_CODE
+ caml_termination_hook = st_thread_exit;
+#endif
+ caml_channel_mutex_free = caml_io_mutex_free;
+ caml_channel_mutex_lock = caml_io_mutex_lock;
+ caml_channel_mutex_unlock = caml_io_mutex_unlock;
+ caml_channel_mutex_unlock_exn = caml_io_mutex_unlock_exn;
+ prev_stack_usage_hook = caml_stack_usage_hook;
+ caml_stack_usage_hook = caml_thread_stack_usage;
+ /* Set up fork() to reinitialize the thread machinery in the child
+ (PR#4577) */
+ st_atfork(caml_thread_reinitialize);
+ return Val_unit;
+}
+
+/* Cleanup the thread machinery on program exit or DLL unload. */
+
+CAMLprim value caml_thread_cleanup(value unit) /* ML */
+{
+ if (caml_tick_thread_running){
+ caml_tick_thread_stop = 1;
+ st_thread_join(caml_tick_thread_id);
+ caml_tick_thread_stop = 0;
+ caml_tick_thread_running = 0;
+ }
+ return Val_unit;
+}
+
+/* Thread cleanup at termination */
+
+static void caml_thread_stop(void)
+{
+#ifndef NATIVE_CODE
+ /* PR#5188: update curr_thread->stack_low because the stack may have
+ been reallocated since the last time we entered a blocking section */
+ curr_thread->stack_low = stack_low;
+#endif
+ /* Signal that the thread has terminated */
+ caml_threadstatus_terminate(Terminated(curr_thread->descr));
+ /* Remove th from the doubly-linked list of threads and free its info block */
+ caml_thread_remove_info(curr_thread);
+ /* OS-specific cleanups */
+ st_thread_cleanup();
+ /* Release the runtime system */
+ st_masterlock_release(&caml_master_lock);
+}
+
+/* Create a thread */
+
+static ST_THREAD_FUNCTION caml_thread_start(void * arg)
+{
+ caml_thread_t th = (caml_thread_t) arg;
+ value clos;
+#ifdef NATIVE_CODE
+ struct longjmp_buffer termination_buf;
+ char tos;
+#endif
+
+ /* Associate the thread descriptor with the thread */
+ st_tls_set(thread_descriptor_key, (void *) th);
+ /* Acquire the global mutex */
+ leave_blocking_section();
+#ifdef NATIVE_CODE
+ /* Record top of stack (approximative) */
+ th->top_of_stack = &tos;
+ /* Setup termination handler (for caml_thread_exit) */
+ if (sigsetjmp(termination_buf.buf, 0) == 0) {
+ th->exit_buf = &termination_buf;
+#endif
+ /* Callback the closure */
+ clos = Start_closure(th->descr);
+ modify(&(Start_closure(th->descr)), Val_unit);
+ callback_exn(clos, Val_unit);
+ caml_thread_stop();
+#ifdef NATIVE_CODE
+ }
+#endif
+ /* The thread now stops running */
+ return 0;
+}
+
+CAMLprim value caml_thread_new(value clos) /* ML */
+{
+ caml_thread_t th;
+ st_retcode err;
+
+ /* Create a thread info block */
+ th = caml_thread_new_info();
+ if (th == NULL) caml_raise_out_of_memory();
+ /* Equip it with a thread descriptor */
+ th->descr = caml_thread_new_descriptor(clos);
+ /* Add thread info block to the list of threads */
+ th->next = curr_thread->next;
+ th->prev = curr_thread;
+ curr_thread->next->prev = th;
+ curr_thread->next = th;
+ /* Create the new thread */
+ err = st_thread_create(NULL, caml_thread_start, (void *) th);
+ if (err != 0) {
+ /* Creation failed, remove thread info block from list of threads */
+ caml_thread_remove_info(th);
+ st_check_error(err, "Thread.create");
+ }
+ /* Create the tick thread if not already done.
+ Because of PR#4666, we start the tick thread late, only when we create
+ the first additional thread in the current process*/
+ if (! caml_tick_thread_running) {
+ err = st_thread_create(&caml_tick_thread_id, caml_thread_tick, NULL);
+ st_check_error(err, "Thread.create");
+ caml_tick_thread_running = 1;
+ }
+ return th->descr;
+}
+
+/* Register a thread already created from C */
+
+CAMLexport int caml_c_thread_register(void)
+{
+ caml_thread_t th;
+ st_retcode err;
+
+ /* Already registered? */
+ if (st_tls_get(thread_descriptor_key) != NULL) return 0;
+ /* Create a thread info block */
+ th = caml_thread_new_info();
+ if (th == NULL) return 0;
+#ifdef NATIVE_CODE
+ th->top_of_stack = (char *) &err;
+#endif
+ /* Take master lock to protect access to the chaining of threads */
+ st_masterlock_acquire(&caml_master_lock);
+ /* Add thread info block to the list of threads */
+ if (all_threads == NULL) {
+ th->next = th;
+ th->prev = th;
+ all_threads = th;
+ } else {
+ th->next = all_threads->next;
+ th->prev = all_threads;
+ all_threads->next->prev = th;
+ all_threads->next = th;
+ }
+ /* Associate the thread descriptor with the thread */
+ st_tls_set(thread_descriptor_key, (void *) th);
+ /* Release the master lock */
+ st_masterlock_release(&caml_master_lock);
+ /* Now we can re-enter the run-time system and heap-allocate the descriptor */
+ leave_blocking_section();
+ th->descr = caml_thread_new_descriptor(Val_unit); /* no closure */
+ /* Create the tick thread if not already done. */
+ if (! caml_tick_thread_running) {
+ err = st_thread_create(&caml_tick_thread_id, caml_thread_tick, NULL);
+ if (err == 0) caml_tick_thread_running = 1;
+ }
+ /* Exit the run-time system */
+ enter_blocking_section();
+ return 1;
+}
+
+/* Unregister a thread that was created from C and registered with
+ the function above */
+
+CAMLexport int caml_c_thread_unregister(void)
+{
+ caml_thread_t th = st_tls_get(thread_descriptor_key);
+ /* Not registered? */
+ if (th == NULL) return 0;
+ /* Wait until the runtime is available */
+ st_masterlock_acquire(&caml_master_lock);
+ /* Forget the thread descriptor */
+ st_tls_set(thread_descriptor_key, NULL);
+ /* Remove thread info block from list of threads, and free it */
+ caml_thread_remove_info(th);
+ /* Release the runtime */
+ st_masterlock_release(&caml_master_lock);
+ return 1;
+}
+
+/* Return the current thread */
+
+CAMLprim value caml_thread_self(value unit) /* ML */
+{
+ if (curr_thread == NULL) invalid_argument("Thread.self: not initialized");
+ return curr_thread->descr;
+}
+
+/* Return the identifier of a thread */
+
+CAMLprim value caml_thread_id(value th) /* ML */
+{
+ return Ident(th);
+}
+
+/* Print uncaught exception and backtrace */
+
+CAMLprim value caml_thread_uncaught_exception(value exn) /* ML */
+{
+ char * msg = format_caml_exception(exn);
+ fprintf(stderr, "Thread %d killed on uncaught exception %s\n",
+ Int_val(Ident(curr_thread->descr)), msg);
+ free(msg);
+ if (caml_backtrace_active) print_exception_backtrace();
+ fflush(stderr);
+ return Val_unit;
+}
+
+/* Terminate current thread */
+
+CAMLprim value caml_thread_exit(value unit) /* ML */
+{
+ struct longjmp_buffer * exit_buf = NULL;
+
+ if (curr_thread == NULL) invalid_argument("Thread.exit: not initialized");
+
+ /* In native code, we cannot call pthread_exit here because on some
+ systems this raises a C++ exception, and ocamlopt-generated stack
+ frames cannot be unwound. Instead, we longjmp to the thread
+ creation point (in caml_thread_start) or to the point in
+ caml_main where caml_termination_hook will be called.
+ Note that threads created in C then registered do not have
+ a creation point (exit_buf == NULL).
+ */
+#ifdef NATIVE_CODE
+ exit_buf = curr_thread->exit_buf;
+#endif
+ caml_thread_stop();
+ if (exit_buf != NULL) {
+ /* Native-code and (main thread or thread created by OCaml) */
+ siglongjmp(exit_buf->buf, 1);
+ } else {
+ /* Bytecode, or thread created from C */
+ st_thread_exit();
+ }
+ return Val_unit; /* not reached */
+}
+
+/* Allow re-scheduling */
+
+CAMLprim value caml_thread_yield(value unit) /* ML */
+{
+ if (st_masterlock_waiters(&caml_master_lock) == 0) return Val_unit;
+ enter_blocking_section();
+ st_thread_yield();
+ leave_blocking_section();
+ return Val_unit;
+}
+
+/* Suspend the current thread until another thread terminates */
+
+CAMLprim value caml_thread_join(value th) /* ML */
+{
+ st_retcode rc = caml_threadstatus_wait(Terminated(th));
+ st_check_error(rc, "Thread.join");
+ return Val_unit;
+}
+
+/* Mutex operations */
+
+#define Mutex_val(v) (* ((st_mutex *) Data_custom_val(v)))
+#define Max_mutex_number 5000
+
+static void caml_mutex_finalize(value wrapper)
+{
+ st_mutex_destroy(Mutex_val(wrapper));
+}
+
+static int caml_mutex_compare(value wrapper1, value wrapper2)
+{
+ st_mutex mut1 = Mutex_val(wrapper1);
+ st_mutex mut2 = Mutex_val(wrapper2);
+ return mut1 == mut2 ? 0 : mut1 < mut2 ? -1 : 1;
+}
+
+static intnat caml_mutex_hash(value wrapper)
+{
+ return (intnat) (Mutex_val(wrapper));
+}
+
+static struct custom_operations caml_mutex_ops = {
+ "_mutex",
+ caml_mutex_finalize,
+ caml_mutex_compare,
+ caml_mutex_hash,
+ custom_serialize_default,
+ custom_deserialize_default
+};
+
+CAMLprim value caml_mutex_new(value unit) /* ML */
+{
+ st_mutex mut = NULL; /* suppress warning */
+ value wrapper;
+ st_check_error(st_mutex_create(&mut), "Mutex.create");
+ wrapper = alloc_custom(&caml_mutex_ops, sizeof(st_mutex *),
+ 1, Max_mutex_number);
+ Mutex_val(wrapper) = mut;
+ return wrapper;
+}
+
+CAMLprim value caml_mutex_lock(value wrapper) /* ML */
+{
+ st_mutex mut = Mutex_val(wrapper);
+ st_retcode retcode;
+
+ /* PR#4351: first try to acquire mutex without releasing the master lock */
+ if (st_mutex_trylock(mut) == PREVIOUSLY_UNLOCKED) return Val_unit;
+ /* If unsuccessful, block on mutex */
+ Begin_root(wrapper) /* prevent the deallocation of mutex */
+ enter_blocking_section();
+ retcode = st_mutex_lock(mut);
+ leave_blocking_section();
+ End_roots();
+ st_check_error(retcode, "Mutex.lock");
+ return Val_unit;
+}
+
+CAMLprim value caml_mutex_unlock(value wrapper) /* ML */
+{
+ st_mutex mut = Mutex_val(wrapper);
+ st_retcode retcode;
+ /* PR#4351: no need to release and reacquire master lock */
+ retcode = st_mutex_unlock(mut);
+ st_check_error(retcode, "Mutex.unlock");
+ return Val_unit;
+}
+
+CAMLprim value caml_mutex_try_lock(value wrapper) /* ML */
+{
+ st_mutex mut = Mutex_val(wrapper);
+ st_retcode retcode;
+ retcode = st_mutex_trylock(mut);
+ if (retcode == ALREADY_LOCKED) return Val_false;
+ st_check_error(retcode, "Mutex.try_lock");
+ return Val_true;
+}
+
+/* Conditions operations */
+
+#define Condition_val(v) (* (st_condvar *) Data_custom_val(v))
+#define Max_condition_number 5000
+
+static void caml_condition_finalize(value wrapper)
+{
+ st_condvar_destroy(Condition_val(wrapper));
+}
+
+static int caml_condition_compare(value wrapper1, value wrapper2)
+{
+ st_condvar cond1 = Condition_val(wrapper1);
+ st_condvar cond2 = Condition_val(wrapper2);
+ return cond1 == cond2 ? 0 : cond1 < cond2 ? -1 : 1;
+}
+
+static intnat caml_condition_hash(value wrapper)
+{
+ return (intnat) (Condition_val(wrapper));
+}
+
+static struct custom_operations caml_condition_ops = {
+ "_condition",
+ caml_condition_finalize,
+ caml_condition_compare,
+ caml_condition_hash,
+ custom_serialize_default,
+ custom_deserialize_default,
+ custom_compare_ext_default
+};
+
+CAMLprim value caml_condition_new(value unit) /* ML */
+{
+ st_condvar cond = NULL; /* suppress warning */
+ value wrapper;
+ st_check_error(st_condvar_create(&cond), "Condition.create");
+ wrapper = alloc_custom(&caml_condition_ops, sizeof(st_condvar *),
+ 1, Max_condition_number);
+ Condition_val(wrapper) = cond;
+ return wrapper;
+}
+
+CAMLprim value caml_condition_wait(value wcond, value wmut) /* ML */
+{
+ st_condvar cond = Condition_val(wcond);
+ st_mutex mut = Mutex_val(wmut);
+ st_retcode retcode;
+
+ Begin_roots2(wcond, wmut) /* prevent deallocation of cond and mutex */
+ enter_blocking_section();
+ retcode = st_condvar_wait(cond, mut);
+ leave_blocking_section();
+ End_roots();
+ st_check_error(retcode, "Condition.wait");
+ return Val_unit;
+}
+
+CAMLprim value caml_condition_signal(value wrapper) /* ML */
+{
+ st_check_error(st_condvar_signal(Condition_val(wrapper)),
+ "Condition.signal");
+ return Val_unit;
+}
+
+CAMLprim value caml_condition_broadcast(value wrapper) /* ML */
+{
+ st_check_error(st_condvar_broadcast(Condition_val(wrapper)),
+ "Condition.broadcast");
+ return Val_unit;
+}
+
+/* Thread status blocks */
+
+#define Threadstatus_val(v) (* ((st_event *) Data_custom_val(v)))
+#define Max_threadstatus_number 500
+
+static void caml_threadstatus_finalize(value wrapper)
+{
+ st_event_destroy(Threadstatus_val(wrapper));
+}
+
+static int caml_threadstatus_compare(value wrapper1, value wrapper2)
+{
+ st_event ts1 = Threadstatus_val(wrapper1);
+ st_event ts2 = Threadstatus_val(wrapper2);
+ return ts1 == ts2 ? 0 : ts1 < ts2 ? -1 : 1;
+}
+
+static struct custom_operations caml_threadstatus_ops = {
+ "_threadstatus",
+ caml_threadstatus_finalize,
+ caml_threadstatus_compare,
+ custom_hash_default,
+ custom_serialize_default,
+ custom_deserialize_default,
+ custom_compare_ext_default
+};
+
+static value caml_threadstatus_new (void)
+{
+ st_event ts = NULL; /* suppress warning */
+ value wrapper;
+ st_check_error(st_event_create(&ts), "Thread.create");
+ wrapper = alloc_custom(&caml_threadstatus_ops, sizeof(st_event *),
+ 1, Max_threadstatus_number);
+ Threadstatus_val(wrapper) = ts;
+ return wrapper;
+}
+
+static void caml_threadstatus_terminate (value wrapper)
+{
+ st_event_trigger(Threadstatus_val(wrapper));
+}
+
+static st_retcode caml_threadstatus_wait (value wrapper)
+{
+ st_event ts = Threadstatus_val(wrapper);
+ st_retcode retcode;
+
+ Begin_roots1(wrapper) /* prevent deallocation of ts */
+ enter_blocking_section();
+ retcode = st_event_wait(ts);
+ leave_blocking_section();
+ End_roots();
+ return retcode;
+}
diff --git a/otherlibs/systhreads/st_win32.h b/otherlibs/systhreads/st_win32.h
new file mode 100644
index 0000000000..9cc7bb8886
--- /dev/null
+++ b/otherlibs/systhreads/st_win32.h
@@ -0,0 +1,421 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 2009 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Win32 implementation of the "st" interface */
+
+#define _WIN32_WINNT 0x0400
+#include <windows.h>
+#include <winerror.h>
+#include <stdio.h>
+#include <signal.h>
+
+#define INLINE __inline
+
+#if 1
+#define TRACE(x)
+#define TRACE1(x,y)
+#else
+#include <stdio.h>
+#define TRACE(x) printf("%d: %s\n", GetCurrentThreadId(), x); fflush(stdout)
+#define TRACE1(x,y) printf("%d: %s %p\n", GetCurrentThreadId(), x, (void *)y); \
+ fflush(stdout)
+#endif
+
+typedef DWORD st_retcode;
+
+#define SIGPREEMPTION SIGTERM
+
+/* Thread-local storage assocaiting a Win32 event to every thread. */
+static DWORD st_thread_sem_key;
+
+/* OS-specific initialization */
+
+static DWORD st_initialize(void)
+{
+ st_thread_sem_key = TlsAlloc();
+ if (st_thread_sem_key == TLS_OUT_OF_INDEXES)
+ return GetLastError();
+ else
+ return 0;
+}
+
+/* Thread creation. Created in detached mode if [res] is NULL. */
+
+typedef HANDLE st_thread_id;
+
+static DWORD st_thread_create(st_thread_id * res,
+ LPTHREAD_START_ROUTINE fn, void * arg)
+{
+ HANDLE h = CreateThread(NULL, 0, fn, arg, 0, NULL);
+ TRACE1("st_thread_create", h);
+ if (h == NULL) return GetLastError();
+ if (res == NULL)
+ CloseHandle(h);
+ else
+ *res = h;
+ return 0;
+}
+
+#define ST_THREAD_FUNCTION DWORD WINAPI
+
+/* Cleanup at thread exit */
+
+static void st_thread_cleanup(void)
+{
+ HANDLE ev = (HANDLE) TlsGetValue(st_thread_sem_key);
+ if (ev != NULL) CloseHandle(ev);
+}
+
+/* Thread termination */
+
+static void st_thread_exit(void)
+{
+ TRACE("st_thread_exit");
+ ExitThread(0);
+}
+
+static void st_thread_join(st_thread_id thr)
+{
+ TRACE1("st_thread_join", h);
+ WaitForSingleObject(thr, INFINITE);
+}
+
+/* Scheduling hints */
+
+static INLINE void st_thread_yield(void)
+{
+ Sleep(0);
+}
+
+/* Thread-specific state */
+
+typedef DWORD st_tlskey;
+
+static DWORD st_tls_newkey(st_tlskey * res)
+{
+ *res = TlsAlloc();
+ if (*res == TLS_OUT_OF_INDEXES)
+ return GetLastError();
+ else
+ return 0;
+}
+
+static INLINE void * st_tls_get(st_tlskey k)
+{
+ return TlsGetValue(k);
+}
+
+static INLINE void st_tls_set(st_tlskey k, void * v)
+{
+ TlsSetValue(k, v);
+}
+
+/* The master lock. */
+
+typedef CRITICAL_SECTION st_masterlock;
+
+static void st_masterlock_init(st_masterlock * m)
+{
+ TRACE("st_masterlock_init");
+ InitializeCriticalSection(m);
+ EnterCriticalSection(m);
+}
+
+static INLINE void st_masterlock_acquire(st_masterlock * m)
+{
+ TRACE("st_masterlock_acquire");
+ EnterCriticalSection(m);
+ TRACE("st_masterlock_acquire (done)");
+}
+
+static INLINE void st_masterlock_release(st_masterlock * m)
+{
+ LeaveCriticalSection(m);
+ TRACE("st_masterlock_released");
+}
+
+static INLINE int st_masterlock_waiters(st_masterlock * m)
+{
+ return 1; /* info not maintained */
+}
+
+/* Mutexes */
+
+typedef CRITICAL_SECTION * st_mutex;
+
+static DWORD st_mutex_create(st_mutex * res)
+{
+ st_mutex m = malloc(sizeof(CRITICAL_SECTION));
+ if (m == NULL) return ERROR_NOT_ENOUGH_MEMORY;
+ InitializeCriticalSection(m);
+ *res = m;
+ return 0;
+}
+
+static DWORD st_mutex_destroy(st_mutex m)
+{
+ DeleteCriticalSection(m);
+ free(m);
+ return 0;
+}
+
+static INLINE DWORD st_mutex_lock(st_mutex m)
+{
+ TRACE1("st_mutex_lock", m);
+ EnterCriticalSection(m);
+ TRACE1("st_mutex_lock (done)", m);
+ return 0;
+}
+
+/* Error codes with the 29th bit set are reserved for the application */
+
+#define PREVIOUSLY_UNLOCKED 0
+#define ALREADY_LOCKED (1<<29)
+
+static INLINE DWORD st_mutex_trylock(st_mutex m)
+{
+ TRACE1("st_mutex_trylock", m);
+ if (TryEnterCriticalSection(m)) {
+ TRACE1("st_mutex_trylock (success)", m);
+ return PREVIOUSLY_UNLOCKED;
+ } else {
+ TRACE1("st_mutex_trylock (failure)", m);
+ return ALREADY_LOCKED;
+ }
+}
+
+static INLINE DWORD st_mutex_unlock(st_mutex m)
+{
+ TRACE1("st_mutex_unlock", m);
+ LeaveCriticalSection(m);
+ return 0;
+}
+
+/* Condition variables */
+
+/* A condition variable is just a list of threads currently
+ waiting on this c.v. Each thread is represented by its
+ associated event. */
+
+struct st_wait_list {
+ HANDLE event; /* event of the first waiting thread */
+ struct st_wait_list * next;
+};
+
+typedef struct st_condvar_struct {
+ CRITICAL_SECTION lock; /* protect the data structure */
+ struct st_wait_list * waiters; /* list of threads waiting */
+} * st_condvar;
+
+static DWORD st_condvar_create(st_condvar * res)
+{
+ st_condvar c = malloc(sizeof(struct st_condvar_struct));
+ if (c == NULL) return ERROR_NOT_ENOUGH_MEMORY;
+ InitializeCriticalSection(&c->lock);
+ c->waiters = NULL;
+ *res = c;
+ return 0;
+}
+
+static DWORD st_condvar_destroy(st_condvar c)
+{
+ TRACE1("st_condvar_destroy", c);
+ DeleteCriticalSection(&c->lock);
+ free(c);
+ return 0;
+}
+
+static DWORD st_condvar_signal(st_condvar c)
+{
+ DWORD rc = 0;
+ struct st_wait_list * curr, * next;
+
+ TRACE1("st_condvar_signal", c);
+ EnterCriticalSection(&c->lock);
+ curr = c->waiters;
+ if (curr != NULL) {
+ next = curr->next;
+ /* Wake up the first waiting thread */
+ TRACE1("st_condvar_signal: waking up", curr->event);
+ if (! SetEvent(curr->event)) rc = GetLastError();
+ /* Remove it from the waiting list */
+ c->waiters = next;
+ }
+ LeaveCriticalSection(&c->lock);
+ return rc;
+}
+
+static DWORD st_condvar_broadcast(st_condvar c)
+{
+ DWORD rc = 0;
+ struct st_wait_list * curr, * next;
+
+ TRACE1("st_condvar_broadcast", c);
+ EnterCriticalSection(&c->lock);
+ /* Wake up all waiting threads */
+ curr = c->waiters;
+ while (curr != NULL) {
+ next = curr->next;
+ TRACE1("st_condvar_signal: waking up", curr->event);
+ if (! SetEvent(curr->event)) rc = GetLastError();
+ curr = next;
+ }
+ /* Remove them all from the waiting list */
+ c->waiters = NULL;
+ LeaveCriticalSection(&c->lock);
+ return rc;
+}
+
+static DWORD st_condvar_wait(st_condvar c, st_mutex m)
+{
+ HANDLE ev;
+ struct st_wait_list wait;
+
+ TRACE1("st_condvar_wait", c);
+ /* Recover (or create) the event associated with the calling thread */
+ ev = (HANDLE) TlsGetValue(st_thread_sem_key);
+ if (ev == 0) {
+ ev = CreateEvent(NULL,
+ FALSE /*auto reset*/,
+ FALSE /*initially unset*/,
+ NULL);
+ if (ev == NULL) return GetLastError();
+ TlsSetValue(st_thread_sem_key, (void *) ev);
+ }
+ EnterCriticalSection(&c->lock);
+ /* Insert the current thread in the waiting list (atomically) */
+ wait.event = ev;
+ wait.next = c->waiters;
+ c->waiters = &wait;
+ LeaveCriticalSection(&c->lock);
+ /* Release the mutex m */
+ LeaveCriticalSection(m);
+ /* Wait for our event to be signaled. There is no risk of lost
+ wakeup, since we inserted ourselves on the waiting list of c
+ before releasing m */
+ TRACE1("st_condvar_wait: blocking on event", ev);
+ if (WaitForSingleObject(ev, INFINITE) == WAIT_FAILED)
+ return GetLastError();
+ /* Reacquire the mutex m */
+ TRACE1("st_condvar_wait: restarted, acquiring mutex", m);
+ EnterCriticalSection(m);
+ TRACE1("st_condvar_wait: acquired mutex", m);
+ return 0;
+}
+
+/* Triggered events */
+
+typedef HANDLE st_event;
+
+static DWORD st_event_create(st_event * res)
+{
+ st_event m =
+ CreateEvent(NULL, TRUE/*manual reset*/, FALSE/*initially unset*/, NULL);
+ TRACE1("st_event_create", m);
+ if (m == NULL) return GetLastError();
+ *res = m;
+ return 0;
+}
+
+static DWORD st_event_destroy(st_event e)
+{
+ TRACE1("st_event_destroy", e);
+ if (CloseHandle(e))
+ return 0;
+ else
+ return GetLastError();
+}
+
+static DWORD st_event_trigger(st_event e)
+{
+ TRACE1("st_event_trigger", e);
+ if (SetEvent(e))
+ return 0;
+ else
+ return GetLastError();
+}
+
+static DWORD st_event_wait(st_event e)
+{
+ TRACE1("st_event_wait", e);
+ if (WaitForSingleObject(e, INFINITE) == WAIT_FAILED)
+ return GetLastError();
+ else
+ return 0;
+}
+
+/* Reporting errors */
+
+static void st_check_error(DWORD retcode, char * msg)
+{
+ char err[1024];
+ int errlen, msglen;
+ value str;
+
+ if (retcode == 0) return;
+ if (retcode == ERROR_NOT_ENOUGH_MEMORY) raise_out_of_memory();
+ if (! FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ retcode,
+ 0,
+ err,
+ sizeof(err),
+ NULL)) {
+ sprintf(err, "error code %lx", retcode);
+ }
+ msglen = strlen(msg);
+ errlen = strlen(err);
+ str = alloc_string(msglen + 2 + errlen);
+ memmove (&Byte(str, 0), msg, msglen);
+ memmove (&Byte(str, msglen), ": ", 2);
+ memmove (&Byte(str, msglen + 2), err, errlen);
+ raise_sys_error(str);
+}
+
+/* Variable used to stop the "tick" thread */
+static volatile int caml_tick_thread_stop = 0;
+
+/* The tick thread: posts a SIGPREEMPTION signal periodically */
+
+static DWORD WINAPI caml_thread_tick(void * arg)
+{
+ while(! caml_tick_thread_stop) {
+ Sleep(Thread_timeout);
+ /* The preemption signal should never cause a callback, so don't
+ go through caml_handle_signal(), just record signal delivery via
+ caml_record_signal(). */
+ caml_record_signal(SIGPREEMPTION);
+ }
+ return 0;
+}
+
+/* "At fork" processing -- none under Win32 */
+
+static DWORD st_atfork(void (*fn)(void))
+{
+ return 0;
+}
+
+/* Signal handling -- none under Win32 */
+
+value caml_thread_sigmask(value cmd, value sigs) /* ML */
+{
+ invalid_argument("Thread.sigmask not implemented");
+ return Val_int(0); /* not reached */
+}
+
+value caml_wait_signal(value sigs) /* ML */
+{
+ invalid_argument("Thread.wait_signal not implemented");
+ return Val_int(0); /* not reached */
+}
diff --git a/otherlibs/systhreads/thread.ml b/otherlibs/systhreads/thread.ml
new file mode 100644
index 0000000000..359d271b87
--- /dev/null
+++ b/otherlibs/systhreads/thread.ml
@@ -0,0 +1,88 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* User-level threads *)
+
+type t
+
+external thread_initialize : unit -> unit = "caml_thread_initialize"
+external thread_cleanup : unit -> unit = "caml_thread_cleanup"
+external thread_new : (unit -> unit) -> t = "caml_thread_new"
+external thread_uncaught_exception : exn -> unit =
+ "caml_thread_uncaught_exception"
+
+external yield : unit -> unit = "caml_thread_yield"
+external self : unit -> t = "caml_thread_self" "noalloc"
+external id : t -> int = "caml_thread_id" "noalloc"
+external join : t -> unit = "caml_thread_join"
+external exit : unit -> unit = "caml_thread_exit"
+
+(* For new, make sure the function passed to thread_new never
+ raises an exception. *)
+
+let create fn arg =
+ thread_new
+ (fun () ->
+ try
+ fn arg; ()
+ with exn ->
+ flush stdout; flush stderr;
+ thread_uncaught_exception exn)
+
+(* Thread.kill is currently not implemented due to problems with
+ cleanup handlers on several platforms *)
+
+let kill th = invalid_arg "Thread.kill: not implemented"
+
+(* Preemption *)
+
+let preempt signal = yield()
+
+(* Initialization of the scheduler *)
+
+let preempt_signal =
+ match Sys.os_type with
+ | "Win32" -> Sys.sigterm
+ | _ -> Sys.sigvtalrm
+
+let _ =
+ Sys.set_signal preempt_signal (Sys.Signal_handle preempt);
+ thread_initialize();
+ at_exit
+ (fun () ->
+ thread_cleanup();
+ (* In case of DLL-embedded OCaml the preempt_signal handler
+ will point to nowhere after DLL unloading and an accidental
+ preempt_signal will crash the main program. So restore the
+ default handler. *)
+ Sys.set_signal preempt_signal Sys.Signal_default
+ )
+
+(* Wait functions *)
+
+let delay time = ignore(Unix.select [] [] [] time)
+
+let wait_read fd = ()
+let wait_write fd = ()
+
+let wait_timed_read fd d =
+ match Unix.select [fd] [] [] d with ([], _, _) -> false | (_, _, _) -> true
+let wait_timed_write fd d =
+ match Unix.select [] [fd] [] d with (_, [], _) -> false | (_, _, _) -> true
+let select = Unix.select
+
+let wait_pid p = Unix.waitpid [] p
+
+external sigmask : Unix.sigprocmask_command -> int list -> int list
+ = "caml_thread_sigmask"
+external wait_signal : int list -> int = "caml_wait_signal"
diff --git a/otherlibs/systhreads/thread.mli b/otherlibs/systhreads/thread.mli
new file mode 100644
index 0000000000..93e52be292
--- /dev/null
+++ b/otherlibs/systhreads/thread.mli
@@ -0,0 +1,131 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Lightweight threads for Posix [1003.1c] and Win32. *)
+
+type t
+(** The type of thread handles. *)
+
+(** {6 Thread creation and termination} *)
+
+val create : ('a -> 'b) -> 'a -> t
+(** [Thread.create funct arg] creates a new thread of control,
+ in which the function application [funct arg]
+ is executed concurrently with the other threads of the program.
+ The application of [Thread.create]
+ returns the handle of the newly created thread.
+ The new thread terminates when the application [funct arg]
+ returns, either normally or by raising an uncaught exception.
+ In the latter case, the exception is printed on standard error,
+ but not propagated back to the parent thread. Similarly, the
+ result of the application [funct arg] is discarded and not
+ directly accessible to the parent thread. *)
+
+val self : unit -> t
+(** Return the thread currently executing. *)
+
+val id : t -> int
+(** Return the identifier of the given thread. A thread identifier
+ is an integer that identifies uniquely the thread.
+ It can be used to build data structures indexed by threads. *)
+
+val exit : unit -> unit
+(** Terminate prematurely the currently executing thread. *)
+
+val kill : t -> unit
+(** Terminate prematurely the thread whose handle is given. *)
+
+(** {6 Suspending threads} *)
+
+val delay: float -> unit
+(** [delay d] suspends the execution of the calling thread for
+ [d] seconds. The other program threads continue to run during
+ this time. *)
+
+val join : t -> unit
+(** [join th] suspends the execution of the calling thread
+ until the thread [th] has terminated. *)
+
+val wait_read : Unix.file_descr -> unit
+(** See {!Thread.wait_write}.*)
+
+val wait_write : Unix.file_descr -> unit
+(** This function does nothing in this implementation. *)
+
+val wait_timed_read : Unix.file_descr -> float -> bool
+(** See {!Thread.wait_timed_read}.*)
+
+val wait_timed_write : Unix.file_descr -> float -> bool
+(** Suspend the execution of the calling thread until at least
+ one character is available for reading ([wait_read]) or
+ one character can be written without blocking ([wait_write])
+ on the given Unix file descriptor. Wait for at most
+ the amount of time given as second argument (in seconds).
+ Return [true] if the file descriptor is ready for input/output
+ and [false] if the timeout expired.
+
+ These functions return immediately [true] in the Win32
+ implementation. *)
+
+val select :
+ Unix.file_descr list -> Unix.file_descr list ->
+ Unix.file_descr list -> float ->
+ Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
+(** Suspend the execution of the calling thead until input/output
+ becomes possible on the given Unix file descriptors.
+ The arguments and results have the same meaning as for
+ [Unix.select].
+ This function is not implemented yet under Win32. *)
+
+val wait_pid : int -> int * Unix.process_status
+(** [wait_pid p] suspends the execution of the calling thread
+ until the process specified by the process identifier [p]
+ terminates. Returns the pid of the child caught and
+ its termination status, as per [Unix.wait].
+ This function is not implemented under MacOS. *)
+
+val yield : unit -> unit
+(** Re-schedule the calling thread without suspending it.
+ This function can be used to give scheduling hints,
+ telling the scheduler that now is a good time to
+ switch to other threads. *)
+
+(** {6 Management of signals} *)
+
+(** Signal handling follows the POSIX thread model: signals generated
+ by a thread are delivered to that thread; signals generated externally
+ are delivered to one of the threads that does not block it.
+ Each thread possesses a set of blocked signals, which can be modified
+ using {!Thread.sigmask}. This set is inherited at thread creation time.
+ Per-thread signal masks are supported only by the system thread library
+ under Unix, but not under Win32, nor by the VM thread library. *)
+
+val sigmask : Unix.sigprocmask_command -> int list -> int list
+(** [sigmask cmd sigs] changes the set of blocked signals for the
+ calling thread.
+ If [cmd] is [SIG_SETMASK], blocked signals are set to those in
+ the list [sigs].
+ If [cmd] is [SIG_BLOCK], the signals in [sigs] are added to
+ the set of blocked signals.
+ If [cmd] is [SIG_UNBLOCK], the signals in [sigs] are removed
+ from the set of blocked signals.
+ [sigmask] returns the set of previously blocked signals for the thread. *)
+
+
+val wait_signal : int list -> int
+(** [wait_signal sigs] suspends the execution of the calling thread
+ until the process receives one of the signals specified in the
+ list [sigs]. It then returns the number of the signal received.
+ Signal handlers attached to the signals in [sigs] will not
+ be invoked. The signals [sigs] are expected to be blocked before
+ calling [wait_signal]. *)
diff --git a/otherlibs/systhreads/threadUnix.ml b/otherlibs/systhreads/threadUnix.ml
new file mode 100644
index 0000000000..c18f75bb47
--- /dev/null
+++ b/otherlibs/systhreads/threadUnix.ml
@@ -0,0 +1,63 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [ThreadUnix]: thread-compatible system calls *)
+
+open Unix
+
+(*** Process handling *)
+
+external execv : string -> string array -> unit = "unix_execv"
+external execve : string -> string array -> string array -> unit
+ = "unix_execve"
+external execvp : string -> string array -> unit = "unix_execvp"
+let wait = Unix.wait
+let waitpid = Unix.waitpid
+let system = Unix.system
+let read = Unix.read
+let write = Unix.write
+let write_substring = Unix.write_substring
+let select = Unix.select
+
+let timed_read fd buff ofs len timeout =
+ if Thread.wait_timed_read fd timeout
+ then Unix.read fd buff ofs len
+ else raise (Unix_error(ETIMEDOUT, "timed_read", ""))
+
+let timed_write fd buff ofs len timeout =
+ if Thread.wait_timed_write fd timeout
+ then Unix.write fd buff ofs len
+ else raise (Unix_error(ETIMEDOUT, "timed_write", ""))
+
+let timed_write_substring fd buff ofs len timeout =
+ timed_write fd (Bytes.unsafe_of_string buff) ofs len timeout
+
+let pipe = Unix.pipe
+
+let open_process_in = Unix.open_process_in
+let open_process_out = Unix.open_process_out
+let open_process = Unix.open_process
+
+external sleep : int -> unit = "unix_sleep"
+
+let socket = Unix.socket
+let accept = Unix.accept
+external connect : file_descr -> sockaddr -> unit = "unix_connect"
+let recv = Unix.recv
+let recvfrom = Unix.recvfrom
+let send = Unix.send
+let send_substring = Unix.send_substring
+let sendto = Unix.sendto
+let sendto_substring = Unix.sendto_substring
+
+let open_connection = Unix.open_connection
diff --git a/otherlibs/systhreads/threadUnix.mli b/otherlibs/systhreads/threadUnix.mli
new file mode 100644
index 0000000000..cac796b925
--- /dev/null
+++ b/otherlibs/systhreads/threadUnix.mli
@@ -0,0 +1,92 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Thread-compatible system calls.
+
+ @deprecated The functionality of this module has been merged back into
+ the {!Unix} module. Threaded programs can now call the functions
+ from module {!Unix} directly, and still get the correct behavior
+ (block the calling thread, if required, but do not block all threads
+ in the process). *)
+
+(** {6 Process handling} *)
+
+val execv : string -> string array -> unit
+val execve : string -> string array -> string array -> unit
+val execvp : string -> string array -> unit
+val wait : unit -> int * Unix.process_status
+val waitpid : Unix.wait_flag list -> int -> int * Unix.process_status
+val system : string -> Unix.process_status
+
+(** {6 Basic input/output} *)
+
+val read : Unix.file_descr -> bytes -> int -> int -> int
+val write : Unix.file_descr -> bytes -> int -> int -> int
+val write_substring : Unix.file_descr -> string -> int -> int -> int
+
+(** {6 Input/output with timeout} *)
+
+val timed_read :
+ Unix.file_descr ->
+ bytes -> int -> int -> float -> int
+(** See {!ThreadUnix.timed_write}. *)
+
+val timed_write :
+ Unix.file_descr ->
+ bytes -> int -> int -> float -> int
+(** Behave as {!ThreadUnix.read} and {!ThreadUnix.write}, except that
+ [Unix_error(ETIMEDOUT,_,_)] is raised if no data is
+ available for reading or ready for writing after [d] seconds.
+ The delay [d] is given in the fifth argument, in seconds. *)
+
+val timed_write_substring :
+ Unix.file_descr -> string -> int -> int -> float -> int
+(** See {!ThreadUnix.timed_write}. *)
+
+(** {6 Polling} *)
+
+val select :
+ Unix.file_descr list -> Unix.file_descr list ->
+ Unix.file_descr list -> float ->
+ Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
+
+(** {6 Pipes and redirections} *)
+
+val pipe : unit -> Unix.file_descr * Unix.file_descr
+val open_process_in: string -> in_channel
+val open_process_out: string -> out_channel
+val open_process: string -> in_channel * out_channel
+
+(** {6 Time} *)
+
+val sleep : int -> unit
+
+(** {6 Sockets} *)
+
+val socket : Unix.socket_domain ->
+ Unix.socket_type -> int -> Unix.file_descr
+val accept : Unix.file_descr -> Unix.file_descr * Unix.sockaddr
+val connect : Unix.file_descr -> Unix.sockaddr -> unit
+val recv : Unix.file_descr -> bytes ->
+ int -> int -> Unix.msg_flag list -> int
+val recvfrom : Unix.file_descr -> bytes -> int -> int ->
+ Unix.msg_flag list -> int * Unix.sockaddr
+val send : Unix.file_descr -> bytes -> int -> int ->
+ Unix.msg_flag list -> int
+val send_substring : Unix.file_descr -> string -> int -> int ->
+ Unix.msg_flag list -> int
+val sendto : Unix.file_descr -> bytes -> int -> int ->
+ Unix.msg_flag list -> Unix.sockaddr -> int
+val sendto_substring : Unix.file_descr -> string -> int -> int ->
+ Unix.msg_flag list -> Unix.sockaddr -> int
+val open_connection : Unix.sockaddr -> in_channel * out_channel
diff --git a/otherlibs/systhreads/threads.h b/otherlibs/systhreads/threads.h
new file mode 100644
index 0000000000..616138da60
--- /dev/null
+++ b/otherlibs/systhreads/threads.h
@@ -0,0 +1,66 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Damien Doligez, INRIA Rocquencourt */
+/* */
+/* Copyright 1995 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_THREADS_H
+#define CAML_THREADS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAMLextern void caml_enter_blocking_section (void);
+CAMLextern void caml_leave_blocking_section (void);
+#define caml_acquire_runtime_system caml_leave_blocking_section
+#define caml_release_runtime_system caml_enter_blocking_section
+
+/* Manage the master lock around the OCaml run-time system.
+ Only one thread at a time can execute OCaml compiled code or
+ OCaml run-time system functions.
+
+ When OCaml calls a C function, the current thread holds the master
+ lock. The C function can release it by calling
+ [caml_release_runtime_system]. Then, another thread can execute OCaml
+ code. However, the calling thread must not access any OCaml data,
+ nor call any runtime system function, nor call back into OCaml.
+
+ Before returning to its OCaml caller, or accessing OCaml data,
+ or call runtime system functions, the current thread must
+ re-acquire the master lock by calling [caml_acquire_runtime_system].
+
+ Symmetrically, if a C function (not called from OCaml) wishes to
+ call back into OCaml code, it should invoke [caml_acquire_runtime_system]
+ first, then do the callback, then invoke [caml_release_runtime_system].
+
+ For historical reasons, alternate names can be used:
+ [caml_enter_blocking_section] instead of [caml_release_runtime_system]
+ [caml_leave_blocking_section] instead of [caml_acquire_runtime_system]
+ Intuition: a ``blocking section'' is a piece of C code that does not
+ use the runtime system (typically, a blocking I/O operation).
+*/
+
+CAMLextern int caml_c_thread_register(void);
+CAMLextern int caml_c_thread_unregister(void);
+
+/* If a thread is created by C code (instead of by OCaml itself),
+ it must be registered with the OCaml runtime system before
+ being able to call back into OCaml code or use other runtime system
+ functions. Just call [caml_c_thread_register] once.
+ Before the thread finishes, it must call [caml_c_thread_unregister].
+ Both functions return 1 on success, 0 on error.
+*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_THREADS_H */
diff --git a/otherlibs/systhreads/threads.mllib b/otherlibs/systhreads/threads.mllib
new file mode 100644
index 0000000000..3ff8841bd8
--- /dev/null
+++ b/otherlibs/systhreads/threads.mllib
@@ -0,0 +1 @@
+Thread Mutex Condition Event ThreadUnix
diff --git a/otherlibs/threads/.depend b/otherlibs/threads/.depend
new file mode 100644
index 0000000000..799714fc73
--- /dev/null
+++ b/otherlibs/threads/.depend
@@ -0,0 +1,38 @@
+scheduler.o: scheduler.c ../../byterun/caml/alloc.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/backtrace.h ../../byterun/caml/exec.h \
+ ../../byterun/caml/callback.h ../../byterun/caml/config.h \
+ ../../byterun/caml/fail.h ../../byterun/caml/io.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/printexc.h ../../byterun/caml/roots.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/signals.h \
+ ../../byterun/caml/stacks.h ../../byterun/caml/sys.h
+condition.cmi : mutex.cmi
+event.cmi :
+marshal.cmi :
+mutex.cmi :
+pervasives.cmi :
+thread.cmi : unix.cmi
+threadUnix.cmi : unix.cmi
+unix.cmi :
+condition.cmo : thread.cmi mutex.cmi condition.cmi
+condition.cmx : thread.cmx mutex.cmx condition.cmi
+event.cmo : mutex.cmi condition.cmi event.cmi
+event.cmx : mutex.cmx condition.cmx event.cmi
+marshal.cmo : marshal.cmi
+marshal.cmx : marshal.cmi
+mutex.cmo : thread.cmi mutex.cmi
+mutex.cmx : thread.cmx mutex.cmi
+pervasives.cmo : unix.cmi pervasives.cmi
+pervasives.cmx : unix.cmx pervasives.cmi
+thread.cmo : unix.cmi thread.cmi
+thread.cmx : unix.cmx thread.cmi
+threadUnix.cmo : unix.cmi thread.cmi threadUnix.cmi
+threadUnix.cmx : unix.cmx thread.cmx threadUnix.cmi
+unix.cmo : unix.cmi
+unix.cmx : unix.cmi
diff --git a/otherlibs/threads/.ignore b/otherlibs/threads/.ignore
new file mode 100644
index 0000000000..fb2df562de
--- /dev/null
+++ b/otherlibs/threads/.ignore
@@ -0,0 +1,3 @@
+marshal.mli
+pervasives.mli
+unix.mli
diff --git a/otherlibs/threads/Makefile b/otherlibs/threads/Makefile
new file mode 100644
index 0000000000..b7851d0b71
--- /dev/null
+++ b/otherlibs/threads/Makefile
@@ -0,0 +1,131 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# FIXME reduce redundancy by including ../Makefile
+
+include ../../config/Makefile
+CAMLRUN ?= ../../boot/ocamlrun
+CAMLYACC ?= ../../boot/ocamlyacc
+
+CC=$(BYTECC)
+CFLAGS=-I../../byterun $(BYTECCCOMPOPTS) $(SHAREDCCCOMPOPTS) -g
+ROOTDIR=../..
+CAMLC=$(CAMLRUN) $(ROOTDIR)/ocamlc -nostdlib \
+ -I $(ROOTDIR)/stdlib -I $(ROOTDIR)/otherlibs/unix
+MKLIB=$(CAMLRUN) ../../tools/ocamlmklib
+COMPFLAGS=-w +33..39 -warn-error A -bin-annot -g -safe-string
+
+C_OBJS=scheduler.o
+
+CAML_OBJS=thread.cmo mutex.cmo condition.cmo event.cmo threadUnix.cmo
+
+LIB=../../stdlib
+
+LIB_OBJS=$(LIB)/camlinternalFormatBasics.cmo pervasives.cmo \
+ $(LIB)/array.cmo $(LIB)/list.cmo $(LIB)/char.cmo $(LIB)/bytes.cmo \
+ $(LIB)/string.cmo $(LIB)/sys.cmo $(LIB)/sort.cmo marshal.cmo \
+ $(LIB)/obj.cmo $(LIB)/int32.cmo $(LIB)/int64.cmo \
+ $(LIB)/nativeint.cmo $(LIB)/lexing.cmo $(LIB)/parsing.cmo \
+ $(LIB)/set.cmo $(LIB)/map.cmo $(LIB)/stack.cmo $(LIB)/queue.cmo \
+ $(LIB)/camlinternalLazy.cmo $(LIB)/lazy.cmo $(LIB)/stream.cmo \
+ $(LIB)/buffer.cmo $(LIB)/camlinternalFormat.cmo $(LIB)/printf.cmo \
+ $(LIB)/arg.cmo $(LIB)/printexc.cmo $(LIB)/gc.cmo $(LIB)/digest.cmo \
+ $(LIB)/random.cmo $(LIB)/hashtbl.cmo $(LIB)/format.cmo \
+ $(LIB)/scanf.cmo $(LIB)/callback.cmo $(LIB)/camlinternalOO.cmo \
+ $(LIB)/oo.cmo $(LIB)/camlinternalMod.cmo $(LIB)/genlex.cmo \
+ $(LIB)/weak.cmo $(LIB)/filename.cmo $(LIB)/complex.cmo \
+ $(LIB)/arrayLabels.cmo $(LIB)/listLabels.cmo $(LIB)/bytesLabels.cmo \
+ $(LIB)/stringLabels.cmo $(LIB)/moreLabels.cmo $(LIB)/stdLabels.cmo
+
+UNIXLIB=../unix
+
+UNIXLIB_OBJS=unix.cmo $(UNIXLIB)/unixLabels.cmo
+
+all: libvmthreads.a threads.cma stdlib.cma unix.cma
+
+allopt:
+
+libvmthreads.a: $(C_OBJS)
+ $(MKLIB) -o threads -oc vmthreads $(C_OBJS)
+
+threads.cma: $(CAML_OBJS)
+ $(MKLIB) -ocamlc '$(CAMLC)' -o threads -oc vmthreads $(CAML_OBJS)
+
+stdlib.cma: $(LIB_OBJS)
+ $(CAMLC) -a -o stdlib.cma $(LIB_OBJS)
+
+unix.cma: $(UNIXLIB_OBJS)
+ $(MKLIB) -ocamlc '$(CAMLC)' -o unix -linkall $(UNIXLIB_OBJS)
+
+pervasives.cmo: pervasives.mli pervasives.cmi pervasives.ml
+ $(CAMLC) ${COMPFLAGS} -nopervasives -c pervasives.ml
+
+pervasives.mli: $(LIB)/pervasives.mli
+ ln -s $(LIB)/pervasives.mli pervasives.mli
+
+pervasives.cmi: $(LIB)/pervasives.cmi
+ ln -s $(LIB)/pervasives.cmi pervasives.cmi
+
+marshal.cmo: marshal.mli marshal.cmi marshal.ml
+ $(CAMLC) ${COMPFLAGS} -c marshal.ml
+
+marshal.mli: $(LIB)/marshal.mli
+ ln -s $(LIB)/marshal.mli marshal.mli
+
+marshal.cmi: $(LIB)/marshal.cmi
+ ln -s $(LIB)/marshal.cmi marshal.cmi
+
+unix.mli: $(UNIXLIB)/unix.mli
+ ln -s -f $(UNIXLIB)/unix.mli unix.mli
+
+unix.cmi: $(UNIXLIB)/unix.cmi
+ ln -s -f $(UNIXLIB)/unix.cmi unix.cmi
+
+unix.cmo: unix.mli unix.cmi $(UNIXLIB)/unixLabels.cmo
+ $(CAMLC) ${COMPFLAGS} -c unix.ml
+
+partialclean:
+ rm -f *.cm*
+
+clean: partialclean
+ rm -f libvmthreads.a dllvmthreads.so *.o
+ rm -f pervasives.mli marshal.mli unix.mli
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+INSTALL_STUBLIBDIR=$(DESTDIR)$(STUBLIBDIR)
+
+install:
+ if test -f dllvmthreads.so; then cp dllvmthreads.so $(INSTALL_STUBLIBDIR)/.; fi
+ mkdir -p $(INSTALL_LIBDIR)/vmthreads
+ cp libvmthreads.a $(INSTALL_LIBDIR)/vmthreads/libvmthreads.a
+ cd $(INSTALL_LIBDIR)/vmthreads; $(RANLIB) libvmthreads.a
+ cp thread.cmi mutex.cmi condition.cmi event.cmi threadUnix.cmi \
+ threads.cma stdlib.cma unix.cma $(INSTALL_LIBDIR)/vmthreads
+ cp thread.mli mutex.mli condition.mli event.mli threadUnix.mli \
+ $(INSTALL_LIBDIR)/vmthreads
+
+installopt:
+
+.SUFFIXES: .ml .mli .cmo .cmi .cmx
+
+.mli.cmi:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmo:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+depend:
+ $(CC) -MM $(CFLAGS) *.c > .depend
+ $(CAMLRUN) ../../tools/ocamldep *.mli *.ml >> .depend
+
+include .depend
diff --git a/otherlibs/threads/condition.ml b/otherlibs/threads/condition.ml
new file mode 100644
index 0000000000..7912cd60cc
--- /dev/null
+++ b/otherlibs/threads/condition.ml
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type t = { mutable waiting: Thread.t list }
+
+let create () = { waiting = [] }
+
+let wait cond mut =
+ Thread.critical_section := true;
+ Mutex.unlock mut;
+ cond.waiting <- Thread.self() :: cond.waiting;
+ Thread.sleep();
+ Mutex.lock mut
+
+let signal cond =
+ match cond.waiting with (* atomic *)
+ [] -> ()
+ | th :: rem -> cond.waiting <- rem (* atomic *); Thread.wakeup th
+
+let broadcast cond =
+ let w = cond.waiting in (* atomic *)
+ cond.waiting <- []; (* atomic *)
+ List.iter Thread.wakeup w
diff --git a/otherlibs/threads/condition.mli b/otherlibs/threads/condition.mli
new file mode 100644
index 0000000000..2d5bcde1fb
--- /dev/null
+++ b/otherlibs/threads/condition.mli
@@ -0,0 +1,51 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Condition variables to synchronize between threads.
+
+ Condition variables are used when one thread wants to wait until another
+ thread has finished doing something: the former thread ``waits'' on the
+ condition variable, the latter thread ``signals'' the condition when it
+ is done. Condition variables should always be protected by a mutex.
+ The typical use is (if [D] is a shared data structure, [m] its mutex,
+ and [c] is a condition variable):
+ {[
+ Mutex.lock m;
+ while (* some predicate P over D is not satisfied *) do
+ Condition.wait c m
+ done;
+ (* Modify D *)
+ if (* the predicate P over D is now satified *) then Condition.signal c;
+ Mutex.unlock m
+ ]}
+*)
+
+type t
+(** The type of condition variables. *)
+
+val create : unit -> t
+(** Return a new condition variable. *)
+
+val wait : t -> Mutex.t -> unit
+(** [wait c m] atomically unlocks the mutex [m] and suspends the
+ calling process on the condition variable [c]. The process will
+ restart after the condition variable [c] has been signalled.
+ The mutex [m] is locked again before [wait] returns. *)
+
+val signal : t -> unit
+(** [signal c] restarts one of the processes waiting on the
+ condition variable [c]. *)
+
+val broadcast : t -> unit
+(** [broadcast c] restarts all processes waiting on the
+ condition variable [c]. *)
diff --git a/otherlibs/threads/event.ml b/otherlibs/threads/event.ml
new file mode 100644
index 0000000000..68d8a5b456
--- /dev/null
+++ b/otherlibs/threads/event.ml
@@ -0,0 +1,272 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* David Nowak and Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Events *)
+type 'a basic_event =
+ { poll: unit -> bool;
+ (* If communication can take place immediately, return true. *)
+ suspend: unit -> unit;
+ (* Offer the communication on the channel and get ready
+ to suspend current process. *)
+ result: unit -> 'a }
+ (* Return the result of the communication *)
+
+type 'a behavior = int ref -> Condition.t -> int -> 'a basic_event
+
+type 'a event =
+ Communication of 'a behavior
+ | Choose of 'a event list
+ | WrapAbort of 'a event * (unit -> unit)
+ | Guard of (unit -> 'a event)
+
+(* Communication channels *)
+type 'a channel =
+ { mutable writes_pending: 'a communication Queue.t;
+ (* All offers to write on it *)
+ mutable reads_pending: 'a communication Queue.t }
+ (* All offers to read from it *)
+
+(* Communication offered *)
+and 'a communication =
+ { performed: int ref; (* -1 if not performed yet, set to the number *)
+ (* of the matching communication after rendez-vous. *)
+ condition: Condition.t; (* To restart the blocked thread. *)
+ mutable data: 'a option; (* The data sent or received. *)
+ event_number: int } (* Event number in select *)
+
+(* Create a channel *)
+
+let new_channel () =
+ { writes_pending = Queue.create();
+ reads_pending = Queue.create() }
+
+(* Basic synchronization function *)
+
+let masterlock = Mutex.create()
+
+let do_aborts abort_env genev performed =
+ if abort_env <> [] then begin
+ if performed >= 0 then begin
+ let ids_done = snd genev.(performed) in
+ List.iter
+ (fun (id,f) -> if not (List.mem id ids_done) then f ())
+ abort_env
+ end else begin
+ List.iter (fun (_,f) -> f ()) abort_env
+ end
+ end
+
+let basic_sync abort_env genev =
+ let performed = ref (-1) in
+ let condition = Condition.create() in
+ let bev = Array.make (Array.length genev)
+ (fst (genev.(0)) performed condition 0) in
+ for i = 1 to Array.length genev - 1 do
+ bev.(i) <- (fst genev.(i)) performed condition i
+ done;
+ (* See if any of the events is already activable *)
+ let rec poll_events i =
+ if i >= Array.length bev
+ then false
+ else bev.(i).poll() || poll_events (i+1) in
+ Mutex.lock masterlock;
+ if not (poll_events 0) then begin
+ (* Suspend on all events *)
+ for i = 0 to Array.length bev - 1 do bev.(i).suspend() done;
+ (* Wait until the condition is signalled *)
+ Condition.wait condition masterlock
+ end;
+ Mutex.unlock masterlock;
+ (* Extract the result *)
+ if abort_env = [] then
+ (* Preserve tail recursion *)
+ bev.(!performed).result()
+ else begin
+ let num = !performed in
+ let result = bev.(num).result() in
+ (* Handle the aborts and return the result *)
+ do_aborts abort_env genev num;
+ result
+ end
+
+(* Apply a random permutation on an array *)
+
+let scramble_array a =
+ let len = Array.length a in
+ if len = 0 then invalid_arg "Event.choose";
+ for i = len - 1 downto 1 do
+ let j = Random.int (i + 1) in
+ let temp = a.(i) in a.(i) <- a.(j); a.(j) <- temp
+ done;
+ a
+
+(* Main synchronization function *)
+
+let gensym = let count = ref 0 in fun () -> incr count; !count
+
+let rec flatten_event
+ (abort_list : int list)
+ (accu : ('a behavior * int list) list)
+ (accu_abort : (int * (unit -> unit)) list)
+ ev =
+ match ev with
+ Communication bev -> ((bev,abort_list) :: accu) , accu_abort
+ | WrapAbort (ev,fn) ->
+ let id = gensym () in
+ flatten_event (id :: abort_list) accu ((id,fn)::accu_abort) ev
+ | Choose evl ->
+ let rec flatten_list accu' accu_abort'= function
+ ev :: l ->
+ let (accu'',accu_abort'') =
+ flatten_event abort_list accu' accu_abort' ev in
+ flatten_list accu'' accu_abort'' l
+ | [] -> (accu',accu_abort') in
+ flatten_list accu accu_abort evl
+ | Guard fn -> flatten_event abort_list accu accu_abort (fn ())
+
+let sync ev =
+ let (evl,abort_env) = flatten_event [] [] [] ev in
+ basic_sync abort_env (scramble_array(Array.of_list evl))
+
+(* Event polling -- like sync, but non-blocking *)
+
+let basic_poll abort_env genev =
+ let performed = ref (-1) in
+ let condition = Condition.create() in
+ let bev = Array.make(Array.length genev)
+ (fst genev.(0) performed condition 0) in
+ for i = 1 to Array.length genev - 1 do
+ bev.(i) <- fst genev.(i) performed condition i
+ done;
+ (* See if any of the events is already activable *)
+ let rec poll_events i =
+ if i >= Array.length bev
+ then false
+ else bev.(i).poll() || poll_events (i+1) in
+ Mutex.lock masterlock;
+ let ready = poll_events 0 in
+ if ready then begin
+ (* Extract the result *)
+ Mutex.unlock masterlock;
+ let result = Some(bev.(!performed).result()) in
+ do_aborts abort_env genev !performed; result
+ end else begin
+ (* Cancel the communication offers *)
+ performed := 0;
+ Mutex.unlock masterlock;
+ do_aborts abort_env genev (-1);
+ None
+ end
+
+let poll ev =
+ let (evl,abort_env) = flatten_event [] [] [] ev in
+ basic_poll abort_env (scramble_array(Array.of_list evl))
+
+(* Remove all communication opportunities already synchronized *)
+
+let cleanup_queue q =
+ let q' = Queue.create() in
+ Queue.iter (fun c -> if !(c.performed) = -1 then Queue.add c q') q;
+ q'
+
+(* Event construction *)
+
+let always data =
+ Communication(fun performed condition evnum ->
+ { poll = (fun () -> performed := evnum; true);
+ suspend = (fun () -> ());
+ result = (fun () -> data) })
+
+let send channel data =
+ Communication(fun performed condition evnum ->
+ let wcomm =
+ { performed = performed;
+ condition = condition;
+ data = Some data;
+ event_number = evnum } in
+ { poll = (fun () ->
+ let rec poll () =
+ let rcomm = Queue.take channel.reads_pending in
+ if !(rcomm.performed) >= 0 then
+ poll ()
+ else begin
+ rcomm.data <- wcomm.data;
+ performed := evnum;
+ rcomm.performed := rcomm.event_number;
+ Condition.signal rcomm.condition
+ end in
+ try
+ poll();
+ true
+ with Queue.Empty ->
+ false);
+ suspend = (fun () ->
+ channel.writes_pending <- cleanup_queue channel.writes_pending;
+ Queue.add wcomm channel.writes_pending);
+ result = (fun () -> ()) })
+
+let receive channel =
+ Communication(fun performed condition evnum ->
+ let rcomm =
+ { performed = performed;
+ condition = condition;
+ data = None;
+ event_number = evnum } in
+ { poll = (fun () ->
+ let rec poll () =
+ let wcomm = Queue.take channel.writes_pending in
+ if !(wcomm.performed) >= 0 then
+ poll ()
+ else begin
+ rcomm.data <- wcomm.data;
+ performed := evnum;
+ wcomm.performed := wcomm.event_number;
+ Condition.signal wcomm.condition
+ end in
+ try
+ poll();
+ true
+ with Queue.Empty ->
+ false);
+ suspend = (fun () ->
+ channel.reads_pending <- cleanup_queue channel.reads_pending;
+ Queue.add rcomm channel.reads_pending);
+ result = (fun () ->
+ match rcomm.data with
+ None -> invalid_arg "Event.receive"
+ | Some res -> res) })
+
+let choose evl = Choose evl
+
+let wrap_abort ev fn = WrapAbort(ev,fn)
+
+let guard fn = Guard fn
+
+let rec wrap ev fn =
+ match ev with
+ Communication genev ->
+ Communication(fun performed condition evnum ->
+ let bev = genev performed condition evnum in
+ { poll = bev.poll;
+ suspend = bev.suspend;
+ result = (fun () -> fn(bev.result())) })
+ | Choose evl ->
+ Choose(List.map (fun ev -> wrap ev fn) evl)
+ | WrapAbort (ev, f') ->
+ WrapAbort (wrap ev fn, f')
+ | Guard gu ->
+ Guard(fun () -> wrap (gu()) fn)
+
+(* Convenience functions *)
+
+let select evl = sync(Choose evl)
diff --git a/otherlibs/threads/event.mli b/otherlibs/threads/event.mli
new file mode 100644
index 0000000000..e38235f197
--- /dev/null
+++ b/otherlibs/threads/event.mli
@@ -0,0 +1,79 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* David Nowak and Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** First-class synchronous communication.
+
+ This module implements synchronous inter-thread communications over
+ channels. As in John Reppy's Concurrent ML system, the communication
+ events are first-class values: they can be built and combined
+ independently before being offered for communication.
+*)
+
+type 'a channel
+(** The type of communication channels carrying values of type ['a]. *)
+
+val new_channel : unit -> 'a channel
+(** Return a new channel. *)
+
+type +'a event
+(** The type of communication events returning a result of type ['a]. *)
+
+(** [send ch v] returns the event consisting in sending the value [v]
+ over the channel [ch]. The result value of this event is [()]. *)
+val send : 'a channel -> 'a -> unit event
+
+(** [receive ch] returns the event consisting in receiving a value
+ from the channel [ch]. The result value of this event is the
+ value received. *)
+val receive : 'a channel -> 'a event
+
+val always : 'a -> 'a event
+(** [always v] returns an event that is always ready for
+ synchronization. The result value of this event is [v]. *)
+
+val choose : 'a event list -> 'a event
+(** [choose evl] returns the event that is the alternative of
+ all the events in the list [evl]. *)
+
+val wrap : 'a event -> ('a -> 'b) -> 'b event
+(** [wrap ev fn] returns the event that performs the same communications
+ as [ev], then applies the post-processing function [fn]
+ on the return value. *)
+
+val wrap_abort : 'a event -> (unit -> unit) -> 'a event
+(** [wrap_abort ev fn] returns the event that performs
+ the same communications as [ev], but if it is not selected
+ the function [fn] is called after the synchronization. *)
+
+val guard : (unit -> 'a event) -> 'a event
+(** [guard fn] returns the event that, when synchronized, computes
+ [fn()] and behaves as the resulting event. This allows events with
+ side-effects to be computed at the time of the synchronization
+ operation. *)
+
+val sync : 'a event -> 'a
+(** ``Synchronize'' on an event: offer all the communication
+ possibilities specified in the event to the outside world,
+ and block until one of the communications succeed. The result
+ value of that communication is returned. *)
+
+val select : 'a event list -> 'a
+(** ``Synchronize'' on an alternative of events.
+ [select evl] is shorthand for [sync(choose evl)]. *)
+
+val poll : 'a event -> 'a option
+(** Non-blocking version of {!Event.sync}: offer all the communication
+ possibilities specified in the event to the outside world,
+ and if one can take place immediately, perform it and return
+ [Some r] where [r] is the result value of that communication.
+ Otherwise, return [None] without blocking. *)
diff --git a/otherlibs/threads/libvmthreads.clib b/otherlibs/threads/libvmthreads.clib
new file mode 100644
index 0000000000..0b4f31e521
--- /dev/null
+++ b/otherlibs/threads/libvmthreads.clib
@@ -0,0 +1 @@
+scheduler.o
diff --git a/otherlibs/threads/marshal.ml b/otherlibs/threads/marshal.ml
new file mode 100644
index 0000000000..005e964372
--- /dev/null
+++ b/otherlibs/threads/marshal.ml
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type extern_flags =
+ No_sharing
+ | Closures
+ | Compat_32
+
+external to_bytes: 'a -> extern_flags list -> bytes
+ = "caml_output_value_to_string"
+
+external to_string: 'a -> extern_flags list -> string
+ = "caml_output_value_to_string"
+
+let to_channel chan v flags =
+ output_string chan (to_string v flags)
+
+external to_buffer_unsafe:
+ bytes -> int -> int -> 'a -> extern_flags list -> int
+ = "caml_output_value_to_buffer"
+
+let to_buffer buff ofs len v flags =
+ if ofs < 0 || len < 0 || ofs + len > Bytes.length buff
+ then invalid_arg "Marshal.to_buffer: substring out of bounds"
+ else to_buffer_unsafe buff ofs len v flags
+
+external from_channel: in_channel -> 'a = "caml_input_value"
+external from_bytes_unsafe: bytes -> int -> 'a
+ = "caml_input_value_from_string"
+external data_size_unsafe: bytes -> int -> int = "caml_marshal_data_size"
+
+let header_size = 20
+let data_size buff ofs =
+ if ofs < 0 || ofs > Bytes.length buff - header_size
+ then invalid_arg "Marshal.data_size"
+ else data_size_unsafe buff ofs
+let total_size buff ofs = header_size + data_size buff ofs
+
+let from_bytes buff ofs =
+ if ofs < 0 || ofs > Bytes.length buff - header_size
+ then invalid_arg "Marshal.from_bytes"
+ else begin
+ let len = data_size_unsafe buff ofs in
+ if ofs > Bytes.length buff - (header_size + len)
+ then invalid_arg "Marshal.from_bytes"
+ else from_bytes_unsafe buff ofs
+ end
+
+let from_string buff ofs = from_bytes (Bytes.unsafe_of_string buff) ofs
diff --git a/otherlibs/threads/mutex.ml b/otherlibs/threads/mutex.ml
new file mode 100644
index 0000000000..976527ceb2
--- /dev/null
+++ b/otherlibs/threads/mutex.ml
@@ -0,0 +1,36 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type t = { mutable locked: bool; mutable waiting: Thread.t list }
+
+let create () = { locked = false; waiting = [] }
+
+let rec lock m =
+ if m.locked then begin (* test and set atomic *)
+ Thread.critical_section := true;
+ m.waiting <- Thread.self() :: m.waiting;
+ Thread.sleep();
+ lock m
+ end else begin
+ m.locked <- true (* test and set atomic *)
+ end
+
+let try_lock m = (* test and set atomic *)
+ if m.locked then false else begin m.locked <- true; true end
+
+let unlock m =
+ (* Don't play with Thread.critical_section here because of Condition.wait *)
+ let w = m.waiting in (* atomic *)
+ m.waiting <- []; (* atomic *)
+ m.locked <- false; (* atomic *)
+ List.iter Thread.wakeup w
diff --git a/otherlibs/threads/mutex.mli b/otherlibs/threads/mutex.mli
new file mode 100644
index 0000000000..265ae94e6f
--- /dev/null
+++ b/otherlibs/threads/mutex.mli
@@ -0,0 +1,47 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Locks for mutual exclusion.
+
+ Mutexes (mutual-exclusion locks) are used to implement critical sections
+ and protect shared mutable data structures against concurrent accesses.
+ The typical use is (if [m] is the mutex associated with the data structure
+ [D]):
+ {[
+ Mutex.lock m;
+ (* Critical section that operates over D *);
+ Mutex.unlock m
+ ]}
+*)
+
+type t
+(** The type of mutexes. *)
+
+val create : unit -> t
+(** Return a new mutex. *)
+
+val lock : t -> unit
+(** Lock the given mutex. Only one thread can have the mutex locked
+ at any time. A thread that attempts to lock a mutex already locked
+ by another thread will suspend until the other thread unlocks
+ the mutex. *)
+
+val try_lock : t -> bool
+(** Same as {!Mutex.lock}, but does not suspend the calling thread if
+ the mutex is already locked: just return [false] immediately
+ in that case. If the mutex is unlocked, lock it and
+ return [true]. *)
+
+val unlock : t -> unit
+(** Unlock the given mutex. Other threads suspended trying to lock
+ the mutex will restart. *)
diff --git a/otherlibs/threads/pervasives.ml b/otherlibs/threads/pervasives.ml
new file mode 100644
index 0000000000..19d03637b7
--- /dev/null
+++ b/otherlibs/threads/pervasives.ml
@@ -0,0 +1,607 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Same as ../../stdlib/pervasives.ml, except that I/O functions have
+ been redefined to not block the whole process, but only the calling
+ thread. *)
+
+(* type 'a option = None | Some of 'a *)
+
+(* Exceptions *)
+
+external register_named_value : string -> 'a -> unit
+ = "caml_register_named_value"
+
+let () =
+ (* for asmrun/fail.c *)
+ register_named_value "Pervasives.array_bound_error"
+ (Invalid_argument "index out of bounds")
+
+
+external raise : exn -> 'a = "%raise"
+external raise_notrace : exn -> 'a = "%raise_notrace"
+
+let failwith s = raise(Failure s)
+let invalid_arg s = raise(Invalid_argument s)
+
+exception Exit
+
+(* Composition operators *)
+
+external ( |> ) : 'a -> ('a -> 'b) -> 'b = "%revapply"
+external ( @@ ) : ('a -> 'b) -> 'a -> 'b = "%apply"
+
+(* Debugging *)
+
+external __LOC__ : string = "%loc_LOC"
+external __FILE__ : string = "%loc_FILE"
+external __LINE__ : int = "%loc_LINE"
+external __MODULE__ : string = "%loc_MODULE"
+external __POS__ : string * int * int * int = "%loc_POS"
+
+external __LOC_OF__ : 'a -> string * 'a = "%loc_LOC"
+external __LINE_OF__ : 'a -> int * 'a = "%loc_LINE"
+external __POS_OF__ : 'a -> (string * int * int * int) * 'a = "%loc_POS"
+
+(* Comparisons *)
+
+external ( = ) : 'a -> 'a -> bool = "%equal"
+external ( <> ) : 'a -> 'a -> bool = "%notequal"
+external ( < ) : 'a -> 'a -> bool = "%lessthan"
+external ( > ) : 'a -> 'a -> bool = "%greaterthan"
+external ( <= ) : 'a -> 'a -> bool = "%lessequal"
+external ( >= ) : 'a -> 'a -> bool = "%greaterequal"
+external compare : 'a -> 'a -> int = "%compare"
+
+let min x y = if x <= y then x else y
+let max x y = if x >= y then x else y
+
+external ( == ) : 'a -> 'a -> bool = "%eq"
+external ( != ) : 'a -> 'a -> bool = "%noteq"
+
+(* Boolean operations *)
+
+external not : bool -> bool = "%boolnot"
+external ( & ) : bool -> bool -> bool = "%sequand"
+external ( && ) : bool -> bool -> bool = "%sequand"
+external ( or ) : bool -> bool -> bool = "%sequor"
+external ( || ) : bool -> bool -> bool = "%sequor"
+
+(* Integer operations *)
+
+external ( ~- ) : int -> int = "%negint"
+external ( ~+ ) : int -> int = "%identity"
+external succ : int -> int = "%succint"
+external pred : int -> int = "%predint"
+external ( + ) : int -> int -> int = "%addint"
+external ( - ) : int -> int -> int = "%subint"
+external ( * ) : int -> int -> int = "%mulint"
+external ( / ) : int -> int -> int = "%divint"
+external ( mod ) : int -> int -> int = "%modint"
+
+let abs x = if x >= 0 then x else -x
+
+external ( land ) : int -> int -> int = "%andint"
+external ( lor ) : int -> int -> int = "%orint"
+external ( lxor ) : int -> int -> int = "%xorint"
+
+let lnot x = x lxor (-1)
+
+external ( lsl ) : int -> int -> int = "%lslint"
+external ( lsr ) : int -> int -> int = "%lsrint"
+external ( asr ) : int -> int -> int = "%asrint"
+
+let max_int = (-1) lsr 1
+let min_int = max_int + 1
+
+(* Floating-point operations *)
+
+external ( ~-. ) : float -> float = "%negfloat"
+external ( ~+. ) : float -> float = "%identity"
+external ( +. ) : float -> float -> float = "%addfloat"
+external ( -. ) : float -> float -> float = "%subfloat"
+external ( *. ) : float -> float -> float = "%mulfloat"
+external ( /. ) : float -> float -> float = "%divfloat"
+external ( ** ) : float -> float -> float = "caml_power_float" "pow" "float"
+external exp : float -> float = "caml_exp_float" "exp" "float"
+external expm1 : float -> float = "caml_expm1_float" "caml_expm1" "float"
+external acos : float -> float = "caml_acos_float" "acos" "float"
+external asin : float -> float = "caml_asin_float" "asin" "float"
+external atan : float -> float = "caml_atan_float" "atan" "float"
+external atan2 : float -> float -> float = "caml_atan2_float" "atan2" "float"
+external hypot : float -> float -> float
+ = "caml_hypot_float" "caml_hypot" "float"
+external cos : float -> float = "caml_cos_float" "cos" "float"
+external cosh : float -> float = "caml_cosh_float" "cosh" "float"
+external log : float -> float = "caml_log_float" "log" "float"
+external log10 : float -> float = "caml_log10_float" "log10" "float"
+external log1p : float -> float = "caml_log1p_float" "caml_log1p" "float"
+external sin : float -> float = "caml_sin_float" "sin" "float"
+external sinh : float -> float = "caml_sinh_float" "sinh" "float"
+external sqrt : float -> float = "caml_sqrt_float" "sqrt" "float"
+external tan : float -> float = "caml_tan_float" "tan" "float"
+external tanh : float -> float = "caml_tanh_float" "tanh" "float"
+external ceil : float -> float = "caml_ceil_float" "ceil" "float"
+external floor : float -> float = "caml_floor_float" "floor" "float"
+external abs_float : float -> float = "%absfloat"
+external copysign : float -> float -> float
+ = "caml_copysign_float" "caml_copysign" "float"
+external mod_float : float -> float -> float = "caml_fmod_float" "fmod" "float"
+external frexp : float -> float * int = "caml_frexp_float"
+external ldexp : float -> int -> float = "caml_ldexp_float"
+external modf : float -> float * float = "caml_modf_float"
+external float : int -> float = "%floatofint"
+external float_of_int : int -> float = "%floatofint"
+external truncate : float -> int = "%intoffloat"
+external int_of_float : float -> int = "%intoffloat"
+external float_of_bits : int64 -> float = "caml_int64_float_of_bits"
+let infinity =
+ float_of_bits 0x7F_F0_00_00_00_00_00_00L
+let neg_infinity =
+ float_of_bits 0xFF_F0_00_00_00_00_00_00L
+let nan =
+ float_of_bits 0x7F_F0_00_00_00_00_00_01L
+let max_float =
+ float_of_bits 0x7F_EF_FF_FF_FF_FF_FF_FFL
+let min_float =
+ float_of_bits 0x00_10_00_00_00_00_00_00L
+let epsilon_float =
+ float_of_bits 0x3C_B0_00_00_00_00_00_00L
+
+type fpclass =
+ FP_normal
+ | FP_subnormal
+ | FP_zero
+ | FP_infinite
+ | FP_nan
+external classify_float : float -> fpclass = "caml_classify_float"
+
+(* String and byte sequence operations -- more in modules String and Bytes *)
+
+external string_length : string -> int = "%string_length"
+external bytes_length : bytes -> int = "%string_length"
+external bytes_create : int -> bytes = "caml_create_string"
+external string_blit : string -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+external bytes_blit : bytes -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+external bytes_unsafe_to_string : bytes -> string = "%identity"
+external bytes_unsafe_of_string : string -> bytes = "%identity"
+
+let ( ^ ) s1 s2 =
+ let l1 = string_length s1 and l2 = string_length s2 in
+ let s = bytes_create (l1 + l2) in
+ string_blit s1 0 s 0 l1;
+ string_blit s2 0 s l1 l2;
+ bytes_unsafe_to_string s
+
+(* Character operations -- more in module Char *)
+
+external int_of_char : char -> int = "%identity"
+external unsafe_char_of_int : int -> char = "%identity"
+let char_of_int n =
+ if n < 0 || n > 255 then invalid_arg "char_of_int" else unsafe_char_of_int n
+
+(* Unit operations *)
+
+external ignore : 'a -> unit = "%ignore"
+
+(* Pair operations *)
+
+external fst : 'a * 'b -> 'a = "%field0"
+external snd : 'a * 'b -> 'b = "%field1"
+
+(* References *)
+
+type 'a ref = { mutable contents : 'a }
+external ref : 'a -> 'a ref = "%makemutable"
+external ( ! ) : 'a ref -> 'a = "%field0"
+external ( := ) : 'a ref -> 'a -> unit = "%setfield0"
+external incr : int ref -> unit = "%incr"
+external decr : int ref -> unit = "%decr"
+
+(* Result type *)
+
+type ('a,'b) result = Ok of 'a | Error of 'b
+
+(* String conversion functions *)
+
+external format_int : string -> int -> string = "caml_format_int"
+external format_float : string -> float -> string = "caml_format_float"
+
+let string_of_bool b =
+ if b then "true" else "false"
+let bool_of_string = function
+ | "true" -> true
+ | "false" -> false
+ | _ -> invalid_arg "bool_of_string"
+
+let string_of_int n =
+ format_int "%d" n
+
+external int_of_string : string -> int = "caml_int_of_string"
+external string_get : string -> int -> char = "%string_safe_get"
+
+let valid_float_lexem s =
+ let l = string_length s in
+ let rec loop i =
+ if i >= l then s ^ "." else
+ match string_get s i with
+ | '0' .. '9' | '-' -> loop (i + 1)
+ | _ -> s
+ in
+ loop 0
+;;
+
+let string_of_float f = valid_float_lexem (format_float "%.12g" f);;
+
+external float_of_string : string -> float = "caml_float_of_string"
+
+(* List operations -- more in module List *)
+
+let rec ( @ ) l1 l2 =
+ match l1 with
+ [] -> l2
+ | hd :: tl -> hd :: (tl @ l2)
+
+
+(* Array index operators *)
+external ( .() ) : 'a array -> int -> 'a = "%array_opt_get"
+external ( .() <- ) : 'a array -> int -> 'a -> unit = "%array_opt_set"
+
+(* String index operators *)
+external ( .[] ) : string -> int -> char = "%string_opt_get"
+external ( .[] <- ) : bytes -> int -> char -> unit = "%string_opt_set"
+
+(* I/O operations *)
+
+type in_channel
+type out_channel
+
+external open_descriptor_out : int -> out_channel
+ = "caml_ml_open_descriptor_out"
+external open_descriptor_in : int -> in_channel = "caml_ml_open_descriptor_in"
+
+let stdin = open_descriptor_in 0
+let stdout = open_descriptor_out 1
+let stderr = open_descriptor_out 2
+
+(* Non-blocking stuff *)
+
+external thread_wait_read_prim : Unix.file_descr -> unit = "thread_wait_read"
+external thread_wait_write_prim : Unix.file_descr -> unit = "thread_wait_write"
+
+let thread_wait_read fd = thread_wait_read_prim fd
+let thread_wait_write fd = thread_wait_write_prim fd
+
+external descr_inchan : in_channel -> Unix.file_descr
+ = "caml_channel_descriptor"
+external descr_outchan : out_channel -> Unix.file_descr
+ = "caml_channel_descriptor"
+
+let wait_inchan ic = thread_wait_read (descr_inchan ic)
+
+let wait_outchan oc len = thread_wait_write (descr_outchan oc)
+
+(* General output functions *)
+
+type open_flag =
+ Open_rdonly | Open_wronly | Open_append
+ | Open_creat | Open_trunc | Open_excl
+ | Open_binary | Open_text | Open_nonblock
+
+external open_desc : string -> open_flag list -> int -> int = "caml_sys_open"
+
+external set_out_channel_name: out_channel -> string -> unit =
+ "caml_ml_set_channel_name"
+
+let open_out_gen mode perm name =
+ let c = open_descriptor_out(open_desc name mode perm) in
+ set_out_channel_name c name;
+ c
+
+let open_out name =
+ open_out_gen [Open_wronly; Open_creat; Open_trunc; Open_text] 0o666 name
+
+let open_out_bin name =
+ open_out_gen [Open_wronly; Open_creat; Open_trunc; Open_binary] 0o666 name
+
+external flush_partial : out_channel -> bool = "caml_ml_flush_partial"
+
+let rec flush oc =
+ let success =
+ try
+ flush_partial oc
+ with Sys_blocked_io ->
+ wait_outchan oc (-1); false in
+ if success then () else flush oc
+
+external out_channels_list : unit -> out_channel list
+ = "caml_ml_out_channels_list"
+
+let flush_all () =
+ let rec iter = function
+ [] -> ()
+ | a::l ->
+ begin try
+ flush a
+ with Sys_error _ ->
+ () (* ignore channels closed during a preceding flush. *)
+ end;
+ iter l
+ in iter (out_channels_list ())
+
+external unsafe_output_partial : out_channel -> bytes -> int -> int -> int
+ = "caml_ml_output_partial"
+
+let rec unsafe_output oc buf pos len =
+ if len > 0 then begin
+ let written =
+ try
+ unsafe_output_partial oc buf pos len
+ with Sys_blocked_io ->
+ wait_outchan oc len; 0 in
+ unsafe_output oc buf (pos + written) (len - written)
+ end
+
+external output_char_blocking : out_channel -> char -> unit
+ = "caml_ml_output_char"
+external output_byte_blocking : out_channel -> int -> unit
+ = "caml_ml_output_char"
+
+let rec output_char oc c =
+ try
+ output_char_blocking oc c
+ with Sys_blocked_io ->
+ wait_outchan oc 1; output_char oc c
+
+let output_bytes oc s =
+ unsafe_output oc s 0 (bytes_length s)
+
+let output_string oc s =
+ unsafe_output oc (bytes_unsafe_of_string s) 0 (string_length s)
+
+let output oc s ofs len =
+ if ofs < 0 || len < 0 || ofs > bytes_length s - len
+ then invalid_arg "output"
+ else unsafe_output oc s ofs len
+
+let output_substring oc s ofs len =
+ output oc (bytes_unsafe_of_string s) ofs len
+
+let rec output_byte oc b =
+ try
+ output_byte_blocking oc b
+ with Sys_blocked_io ->
+ wait_outchan oc 1; output_byte oc b
+
+let output_binary_int oc n =
+ output_byte oc (n asr 24);
+ output_byte oc (n asr 16);
+ output_byte oc (n asr 8);
+ output_byte oc n
+
+external marshal_to_string : 'a -> unit list -> string
+ = "caml_output_value_to_string"
+
+let output_value oc v = output_string oc (marshal_to_string v [])
+
+external seek_out_blocking : out_channel -> int -> unit = "caml_ml_seek_out"
+
+let seek_out oc pos = flush oc; seek_out_blocking oc pos
+
+external pos_out : out_channel -> int = "caml_ml_pos_out"
+external out_channel_length : out_channel -> int = "caml_ml_channel_size"
+external close_out_channel : out_channel -> unit = "caml_ml_close_channel"
+
+let close_out oc = (try flush oc with _ -> ()); close_out_channel oc
+let close_out_noerr oc =
+ (try flush oc with _ -> ());
+ (try close_out_channel oc with _ -> ())
+external set_binary_mode_out : out_channel -> bool -> unit
+ = "caml_ml_set_binary_mode"
+
+(* General input functions *)
+
+external set_in_channel_name: in_channel -> string -> unit =
+ "caml_ml_set_channel_name"
+
+let open_in_gen mode perm name =
+ let c = open_descriptor_in(open_desc name mode perm) in
+ set_in_channel_name c name;
+ c
+
+let open_in name =
+ open_in_gen [Open_rdonly; Open_text] 0 name
+
+let open_in_bin name =
+ open_in_gen [Open_rdonly; Open_binary] 0 name
+
+external input_char_blocking : in_channel -> char = "caml_ml_input_char"
+external input_byte_blocking : in_channel -> int = "caml_ml_input_char"
+
+let rec input_char ic =
+ try
+ input_char_blocking ic
+ with Sys_blocked_io ->
+ wait_inchan ic; input_char ic
+
+external unsafe_input_blocking : in_channel -> bytes -> int -> int -> int
+ = "caml_ml_input"
+
+let rec unsafe_input ic s ofs len =
+ try
+ unsafe_input_blocking ic s ofs len
+ with Sys_blocked_io ->
+ wait_inchan ic; unsafe_input ic s ofs len
+
+let input ic s ofs len =
+ if ofs < 0 || len < 0 || ofs > bytes_length s - len
+ then invalid_arg "input"
+ else unsafe_input ic s ofs len
+
+let rec unsafe_really_input ic s ofs len =
+ if len <= 0 then () else begin
+ let r = unsafe_input ic s ofs len in
+ if r = 0
+ then raise End_of_file
+ else unsafe_really_input ic s (ofs + r) (len - r)
+ end
+
+let really_input ic s ofs len =
+ if ofs < 0 || len < 0 || ofs > bytes_length s - len
+ then invalid_arg "really_input"
+ else unsafe_really_input ic s ofs len
+
+let really_input_string ic len =
+ let s = bytes_create len in
+ really_input ic s 0 len;
+ bytes_unsafe_to_string s
+
+external bytes_set : bytes -> int -> char -> unit = "%string_safe_set"
+
+let input_line ic =
+ let buf = ref (bytes_create 128) in
+ let pos = ref 0 in
+ begin try
+ while true do
+ if !pos = bytes_length !buf then begin
+ let newbuf = bytes_create (2 * !pos) in
+ bytes_blit !buf 0 newbuf 0 !pos;
+ buf := newbuf
+ end;
+ let c = input_char ic in
+ if c = '\n' then raise Exit;
+ bytes_set !buf !pos c;
+ incr pos
+ done
+ with Exit -> ()
+ | End_of_file -> if !pos = 0 then raise End_of_file
+ end;
+ let res = bytes_create !pos in
+ bytes_blit !buf 0 res 0 !pos;
+ bytes_unsafe_to_string res
+
+let rec input_byte ic =
+ try
+ input_byte_blocking ic
+ with Sys_blocked_io ->
+ wait_inchan ic; input_byte ic
+
+let input_binary_int ic =
+ let b1 = input_byte ic in
+ let n1 = if b1 >= 128 then b1 - 256 else b1 in
+ let b2 = input_byte ic in
+ let b3 = input_byte ic in
+ let b4 = input_byte ic in
+ (n1 lsl 24) + (b2 lsl 16) + (b3 lsl 8) + b4
+
+external unmarshal : bytes -> int -> 'a = "caml_input_value_from_string"
+external marshal_data_size : bytes -> int -> int = "caml_marshal_data_size"
+
+let input_value ic =
+ let header = bytes_create 20 in
+ really_input ic header 0 20;
+ let bsize = marshal_data_size header 0 in
+ let buffer = bytes_create (20 + bsize) in
+ bytes_blit header 0 buffer 0 20;
+ really_input ic buffer 20 bsize;
+ unmarshal buffer 0
+
+external seek_in : in_channel -> int -> unit = "caml_ml_seek_in"
+external pos_in : in_channel -> int = "caml_ml_pos_in"
+external in_channel_length : in_channel -> int = "caml_ml_channel_size"
+external close_in : in_channel -> unit = "caml_ml_close_channel"
+let close_in_noerr ic = (try close_in ic with _ -> ());;
+external set_binary_mode_in : in_channel -> bool -> unit
+ = "caml_ml_set_binary_mode"
+
+(* Output functions on standard output *)
+
+let print_char c = output_char stdout c
+let print_string s = output_string stdout s
+let print_bytes s = output_bytes stdout s
+let print_int i = output_string stdout (string_of_int i)
+let print_float f = output_string stdout (string_of_float f)
+let print_endline s =
+ output_string stdout s; output_char stdout '\n'; flush stdout
+let print_newline () = output_char stdout '\n'; flush stdout
+
+(* Output functions on standard error *)
+
+let prerr_char c = output_char stderr c
+let prerr_string s = output_string stderr s
+let prerr_bytes s = output_bytes stderr s
+let prerr_int i = output_string stderr (string_of_int i)
+let prerr_float f = output_string stderr (string_of_float f)
+let prerr_endline s =
+ output_string stderr s; output_char stderr '\n'; flush stderr
+let prerr_newline () = output_char stderr '\n'; flush stderr
+
+(* Input functions on standard input *)
+
+let read_line () = flush stdout; input_line stdin
+let read_int () = int_of_string(read_line())
+let read_float () = float_of_string(read_line())
+
+(* Operations on large files *)
+
+module LargeFile =
+ struct
+ external seek_out : out_channel -> int64 -> unit = "caml_ml_seek_out_64"
+ external pos_out : out_channel -> int64 = "caml_ml_pos_out_64"
+ external out_channel_length : out_channel -> int64
+ = "caml_ml_channel_size_64"
+ external seek_in : in_channel -> int64 -> unit = "caml_ml_seek_in_64"
+ external pos_in : in_channel -> int64 = "caml_ml_pos_in_64"
+ external in_channel_length : in_channel -> int64 = "caml_ml_channel_size_64"
+ end
+
+(* Formats *)
+
+type ('a, 'b, 'c, 'd, 'e, 'f) format6
+ = ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6
+ = Format of ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmt
+ * string
+
+type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6
+
+type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
+
+let string_of_format (Format (fmt, str)) = str
+
+external format_of_string :
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity"
+
+let (^^) (Format (fmt1, str1)) (Format (fmt2, str2)) =
+ Format (CamlinternalFormatBasics.concat_fmt fmt1 fmt2,
+ str1 ^ "%," ^ str2)
+
+(* Miscellaneous *)
+
+external sys_exit : int -> 'a = "caml_sys_exit"
+
+let exit_function = ref flush_all
+
+let at_exit f =
+ let g = !exit_function in
+ exit_function := (fun () -> f(); g())
+
+let do_at_exit () = (!exit_function) ()
+
+let exit retcode =
+ do_at_exit ();
+ sys_exit retcode
+
+let _ = register_named_value "Pervasives.do_at_exit" do_at_exit
diff --git a/otherlibs/threads/scheduler.c b/otherlibs/threads/scheduler.c
new file mode 100644
index 0000000000..315b8d5c26
--- /dev/null
+++ b/otherlibs/threads/scheduler.c
@@ -0,0 +1,874 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The thread scheduler */
+
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "caml/alloc.h"
+#include "caml/backtrace.h"
+#include "caml/callback.h"
+#include "caml/config.h"
+#include "caml/fail.h"
+#include "caml/io.h"
+#include "caml/memory.h"
+#include "caml/misc.h"
+#include "caml/mlvalues.h"
+#include "caml/printexc.h"
+#include "caml/roots.h"
+#include "caml/signals.h"
+#include "caml/stacks.h"
+#include "caml/sys.h"
+
+#if ! (defined(HAS_SELECT) && \
+ defined(HAS_SETITIMER) && \
+ defined(HAS_GETTIMEOFDAY) && \
+ (defined(HAS_WAITPID) || defined(HAS_WAIT4)))
+#include "Cannot compile libthreads, system calls missing"
+#endif
+
+#include <errno.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#ifdef HAS_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+
+#ifndef HAS_WAITPID
+#define waitpid(pid,status,opts) wait4(pid,status,opts,NULL)
+#endif
+
+#ifndef O_NONBLOCK
+#define O_NONBLOCK O_NDELAY
+#endif
+
+/* Configuration */
+
+/* Initial size of stack when a thread is created (4kB) */
+#define Thread_stack_size (Stack_size / 4)
+
+/* Max computation time before rescheduling, in microseconds (50ms) */
+#define Thread_timeout 50000
+
+/* The thread descriptors */
+
+struct caml_thread_struct {
+ value ident; /* Unique id (for equality comparisons) */
+ struct caml_thread_struct * next; /* Double linking of threads */
+ struct caml_thread_struct * prev;
+ value * stack_low; /* The execution stack for this thread */
+ value * stack_high;
+ value * stack_threshold;
+ value * sp;
+ value * trapsp;
+ value backtrace_pos; /* The backtrace info for this thread */
+ backtrace_slot * backtrace_buffer;
+ value backtrace_last_exn;
+ value status; /* RUNNABLE, KILLED. etc (see below) */
+ value fd; /* File descriptor on which we're doing read or write */
+ value readfds, writefds, exceptfds;
+ /* Lists of file descriptors on which we're doing select() */
+ value delay; /* Time until which this thread is blocked */
+ value joining; /* Thread we're trying to join */
+ value waitpid; /* PID of process we're waiting for */
+ value retval; /* Value to return when thread resumes */
+};
+
+typedef struct caml_thread_struct * caml_thread_t;
+
+#define RUNNABLE Val_int(0)
+#define KILLED Val_int(1)
+#define SUSPENDED Val_int(2)
+#define BLOCKED_READ Val_int(4)
+#define BLOCKED_WRITE Val_int(8)
+#define BLOCKED_SELECT Val_int(16)
+#define BLOCKED_DELAY Val_int(32)
+#define BLOCKED_JOIN Val_int(64)
+#define BLOCKED_WAIT Val_int(128)
+
+#define RESUMED_WAKEUP Val_int(0)
+#define RESUMED_DELAY Val_int(1)
+#define RESUMED_JOIN Val_int(2)
+#define RESUMED_IO Val_int(3)
+
+#define TAG_RESUMED_SELECT 0
+#define TAG_RESUMED_WAIT 1
+
+#define NO_FDS Val_unit
+#define NO_DELAY Val_unit
+#define NO_JOINING Val_unit
+#define NO_WAITPID Val_int(0)
+
+#define DELAY_INFTY 1E30 /* +infty, for this purpose */
+
+/* The thread currently active */
+static caml_thread_t curr_thread = NULL;
+/* Identifier for next thread creation */
+static value next_ident = Val_int(0);
+
+#define Assign(dst,src) modify((value *)&(dst), (value)(src))
+
+/* Scan the stacks of the other threads */
+
+static void (*prev_scan_roots_hook) (scanning_action);
+
+static void thread_scan_roots(scanning_action action)
+{
+ caml_thread_t th, start;
+
+ /* Scan all active descriptors */
+ start = curr_thread;
+ (*action)((value) curr_thread, (value *) &curr_thread);
+ /* Don't scan curr_thread->sp, this has already been done.
+ Don't scan local roots either, for the same reason. */
+ for (th = start->next; th != start; th = th->next) {
+ do_local_roots(action, th->sp, th->stack_high, NULL);
+ }
+ /* Hook */
+ if (prev_scan_roots_hook != NULL) (*prev_scan_roots_hook)(action);
+}
+
+/* Forward declarations for async I/O handling */
+
+static int stdin_initial_status, stdout_initial_status, stderr_initial_status;
+static void thread_restore_std_descr(void);
+
+/* Initialize the thread machinery */
+
+value thread_initialize(value unit) /* ML */
+{
+ /* Protect against repeated initialization (PR#1325) */
+ if (curr_thread != NULL) return Val_unit;
+ /* Create a descriptor for the current thread */
+ curr_thread =
+ (caml_thread_t) alloc_shr(sizeof(struct caml_thread_struct)
+ / sizeof(value), 0);
+ curr_thread->ident = next_ident;
+ next_ident = Val_int(Int_val(next_ident) + 1);
+ curr_thread->next = curr_thread;
+ curr_thread->prev = curr_thread;
+ curr_thread->stack_low = stack_low;
+ curr_thread->stack_high = stack_high;
+ curr_thread->stack_threshold = stack_threshold;
+ curr_thread->sp = extern_sp;
+ curr_thread->trapsp = trapsp;
+ curr_thread->backtrace_pos = Val_int(backtrace_pos);
+ curr_thread->backtrace_buffer = backtrace_buffer;
+ caml_initialize (&curr_thread->backtrace_last_exn, backtrace_last_exn);
+ curr_thread->status = RUNNABLE;
+ curr_thread->fd = Val_int(0);
+ curr_thread->readfds = NO_FDS;
+ curr_thread->writefds = NO_FDS;
+ curr_thread->exceptfds = NO_FDS;
+ curr_thread->delay = NO_DELAY;
+ curr_thread->joining = NO_JOINING;
+ curr_thread->waitpid = NO_WAITPID;
+ curr_thread->retval = Val_unit;
+ /* Initialize GC */
+ prev_scan_roots_hook = scan_roots_hook;
+ scan_roots_hook = thread_scan_roots;
+ /* Set standard file descriptors to non-blocking mode */
+ stdin_initial_status = fcntl(0, F_GETFL);
+ stdout_initial_status = fcntl(1, F_GETFL);
+ stderr_initial_status = fcntl(2, F_GETFL);
+ if (stdin_initial_status != -1)
+ fcntl(0, F_SETFL, stdin_initial_status | O_NONBLOCK);
+ if (stdout_initial_status != -1)
+ fcntl(1, F_SETFL, stdout_initial_status | O_NONBLOCK);
+ if (stderr_initial_status != -1)
+ fcntl(2, F_SETFL, stderr_initial_status | O_NONBLOCK);
+ /* Register an at-exit function to restore the standard file descriptors */
+ atexit(thread_restore_std_descr);
+ return Val_unit;
+}
+
+/* Initialize the interval timer used for preemption */
+
+value thread_initialize_preemption(value unit) /* ML */
+{
+ struct itimerval timer;
+
+ timer.it_interval.tv_sec = 0;
+ timer.it_interval.tv_usec = Thread_timeout;
+ timer.it_value = timer.it_interval;
+ setitimer(ITIMER_VIRTUAL, &timer, NULL);
+ return Val_unit;
+}
+
+/* Create a thread */
+
+value thread_new(value clos) /* ML */
+{
+ caml_thread_t th;
+ /* Allocate the thread and its stack */
+ Begin_root(clos);
+ th = (caml_thread_t) alloc_shr(sizeof(struct caml_thread_struct)
+ / sizeof(value), 0);
+ End_roots();
+ th->ident = next_ident;
+ next_ident = Val_int(Int_val(next_ident) + 1);
+ th->stack_low = (value *) caml_stat_alloc(Thread_stack_size);
+ th->stack_high = th->stack_low + Thread_stack_size / sizeof(value);
+ th->stack_threshold = th->stack_low + Stack_threshold / sizeof(value);
+ th->sp = th->stack_high;
+ th->trapsp = th->stack_high;
+ /* Set up a return frame that pretends we're applying the function to ().
+ This way, the next RETURN instruction will run the function. */
+ th->sp -= 5;
+ th->sp[0] = Val_unit; /* dummy local to be popped by RETURN 1 */
+ th->sp[1] = (value) Code_val(clos);
+ th->sp[2] = clos;
+ th->sp[3] = Val_long(0); /* no extra args */
+ th->sp[4] = Val_unit; /* the () argument */
+ /* Fake a C call frame */
+ th->sp--;
+ th->sp[0] = Val_unit; /* a dummy environment */
+ /* Finish initialization of th */
+ th->backtrace_pos = Val_int(0);
+ th->backtrace_buffer = NULL;
+ th->backtrace_last_exn = Val_unit;
+ /* The thread is initially runnable */
+ th->status = RUNNABLE;
+ th->fd = Val_int(0);
+ th->readfds = NO_FDS;
+ th->writefds = NO_FDS;
+ th->exceptfds = NO_FDS;
+ th->delay = NO_DELAY;
+ th->joining = NO_JOINING;
+ th->waitpid = NO_WAITPID;
+ th->retval = Val_unit;
+ /* Insert thread in doubly linked list of threads */
+ th->prev = curr_thread->prev;
+ th->next = curr_thread;
+ Assign(curr_thread->prev->next, th);
+ Assign(curr_thread->prev, th);
+ /* Return thread */
+ return (value) th;
+}
+
+/* Return the thread identifier */
+
+value thread_id(value th) /* ML */
+{
+ return ((caml_thread_t)th)->ident;
+}
+
+/* Return the current time as a floating-point number */
+
+static double timeofday(void)
+{
+ struct timeval tv;
+ gettimeofday(&tv, NULL);
+ return (double) tv.tv_sec + (double) tv.tv_usec * 1e-6;
+}
+
+/* Find a runnable thread and activate it */
+
+#define FOREACH_THREAD(x) x = curr_thread; do { x = x->next;
+#define END_FOREACH(x) } while (x != curr_thread)
+
+static value alloc_process_status(int pid, int status);
+static void add_fdlist_to_set(value fdl, fd_set *set);
+static value inter_fdlist_set(value fdl, fd_set *set, int *count);
+static void find_bad_fd(int fd, fd_set *set);
+static void find_bad_fds(value fdl, fd_set *set);
+
+static value schedule_thread(void)
+{
+ caml_thread_t run_thread, th;
+ fd_set readfds, writefds, exceptfds;
+ double delay, now;
+ int need_select, need_wait;
+
+ /* Don't allow preemption during a callback */
+ if (callback_depth > 1) return curr_thread->retval;
+
+ /* Save the status of the current thread */
+ curr_thread->stack_low = stack_low;
+ curr_thread->stack_high = stack_high;
+ curr_thread->stack_threshold = stack_threshold;
+ curr_thread->sp = extern_sp;
+ curr_thread->trapsp = trapsp;
+ curr_thread->backtrace_pos = Val_int(backtrace_pos);
+ curr_thread->backtrace_buffer = backtrace_buffer;
+ caml_modify (&curr_thread->backtrace_last_exn, backtrace_last_exn);
+
+try_again:
+ /* Find if a thread is runnable.
+ Build fdsets and delay for select.
+ See if some join or wait operations succeeded. */
+ run_thread = NULL;
+ FD_ZERO(&readfds);
+ FD_ZERO(&writefds);
+ FD_ZERO(&exceptfds);
+ delay = DELAY_INFTY;
+ now = -1.0;
+ need_select = 0;
+ need_wait = 0;
+
+ FOREACH_THREAD(th)
+ if (th->status <= SUSPENDED) continue;
+
+ if (th->status & (BLOCKED_READ - 1)) {
+ FD_SET(Int_val(th->fd), &readfds);
+ need_select = 1;
+ }
+ if (th->status & (BLOCKED_WRITE - 1)) {
+ FD_SET(Int_val(th->fd), &writefds);
+ need_select = 1;
+ }
+ if (th->status & (BLOCKED_SELECT - 1)) {
+ add_fdlist_to_set(th->readfds, &readfds);
+ add_fdlist_to_set(th->writefds, &writefds);
+ add_fdlist_to_set(th->exceptfds, &exceptfds);
+ need_select = 1;
+ }
+ if (th->status & (BLOCKED_DELAY - 1)) {
+ double th_delay;
+ if (now < 0.0) now = timeofday();
+ th_delay = Double_val(th->delay) - now;
+ if (th_delay <= 0) {
+ th->status = RUNNABLE;
+ Assign(th->retval,RESUMED_DELAY);
+ } else {
+ if (th_delay < delay) delay = th_delay;
+ }
+ }
+ if (th->status & (BLOCKED_JOIN - 1)) {
+ if (((caml_thread_t)(th->joining))->status == KILLED) {
+ th->status = RUNNABLE;
+ Assign(th->retval, RESUMED_JOIN);
+ }
+ }
+ if (th->status & (BLOCKED_WAIT - 1)) {
+ int status, pid;
+ pid = waitpid(Int_val(th->waitpid), &status, WNOHANG);
+ if (pid > 0) {
+ th->status = RUNNABLE;
+ Assign(th->retval, alloc_process_status(pid, status));
+ } else {
+ need_wait = 1;
+ }
+ }
+ END_FOREACH(th);
+
+ /* Find if a thread is runnable. */
+ run_thread = NULL;
+ FOREACH_THREAD(th)
+ if (th->status == RUNNABLE) { run_thread = th; break; }
+ END_FOREACH(th);
+
+ /* Do the select if needed */
+ if (need_select || run_thread == NULL) {
+ struct timeval delay_tv, * delay_ptr;
+ int retcode;
+ /* If a thread is blocked on wait, don't block forever */
+ if (need_wait && delay > Thread_timeout * 1e-6) {
+ delay = Thread_timeout * 1e-6;
+ }
+ /* Convert delay to a timeval */
+ /* If a thread is runnable, just poll */
+ if (run_thread != NULL) {
+ delay_tv.tv_sec = 0;
+ delay_tv.tv_usec = 0;
+ delay_ptr = &delay_tv;
+ }
+ else if (delay != DELAY_INFTY) {
+ delay_tv.tv_sec = (unsigned int) delay;
+ delay_tv.tv_usec = (delay - (double) delay_tv.tv_sec) * 1E6;
+ delay_ptr = &delay_tv;
+ }
+ else {
+ delay_ptr = NULL;
+ }
+ enter_blocking_section();
+ retcode = select(FD_SETSIZE, &readfds, &writefds, &exceptfds, delay_ptr);
+ leave_blocking_section();
+ if (retcode == -1)
+ switch (errno) {
+ case EINTR:
+ break;
+ case EBADF:
+ /* One of the descriptors in the sets was closed or is bad.
+ Find it using fstat() and wake up the threads waiting on it
+ so that they'll get an error when operating on it. */
+ FOREACH_THREAD(th)
+ if (th->status & (BLOCKED_READ - 1)) {
+ find_bad_fd(Int_val(th->fd), &readfds);
+ }
+ if (th->status & (BLOCKED_WRITE - 1)) {
+ find_bad_fd(Int_val(th->fd), &writefds);
+ }
+ if (th->status & (BLOCKED_SELECT - 1)) {
+ find_bad_fds(th->readfds, &readfds);
+ find_bad_fds(th->writefds, &writefds);
+ find_bad_fds(th->exceptfds, &exceptfds);
+ }
+ END_FOREACH(th);
+ retcode = FD_SETSIZE;
+ break;
+ default:
+ sys_error(NO_ARG);
+ }
+ if (retcode > 0) {
+ /* Some descriptors are ready.
+ Mark the corresponding threads runnable. */
+ FOREACH_THREAD(th)
+ if (retcode <= 0) break;
+ if ((th->status & (BLOCKED_READ - 1)) &&
+ FD_ISSET(Int_val(th->fd), &readfds)) {
+ Assign(th->retval, RESUMED_IO);
+ th->status = RUNNABLE;
+ if (run_thread == NULL) run_thread = th; /* Found one. */
+ /* Wake up only one thread per fd */
+ FD_CLR(Int_val(th->fd), &readfds);
+ retcode--;
+ }
+ if ((th->status & (BLOCKED_WRITE - 1)) &&
+ FD_ISSET(Int_val(th->fd), &writefds)) {
+ Assign(th->retval, RESUMED_IO);
+ th->status = RUNNABLE;
+ if (run_thread == NULL) run_thread = th; /* Found one. */
+ /* Wake up only one thread per fd */
+ FD_CLR(Int_val(th->fd), &readfds);
+ retcode--;
+ }
+ if (th->status & (BLOCKED_SELECT - 1)) {
+ value r = Val_unit, w = Val_unit, e = Val_unit;
+ Begin_roots3(r,w,e)
+ r = inter_fdlist_set(th->readfds, &readfds, &retcode);
+ w = inter_fdlist_set(th->writefds, &writefds, &retcode);
+ e = inter_fdlist_set(th->exceptfds, &exceptfds, &retcode);
+ if (r != NO_FDS || w != NO_FDS || e != NO_FDS) {
+ value retval = alloc_small(3, TAG_RESUMED_SELECT);
+ Field(retval, 0) = r;
+ Field(retval, 1) = w;
+ Field(retval, 2) = e;
+ Assign(th->retval, retval);
+ th->status = RUNNABLE;
+ if (run_thread == NULL) run_thread = th; /* Found one. */
+ }
+ End_roots();
+ }
+ END_FOREACH(th);
+ }
+ /* If we get here with run_thread still NULL, one of the following
+ may have happened:
+ - a delay has expired
+ - a wait() needs to be polled again
+ - the select() failed (e.g. was interrupted)
+ In these cases, we go through the loop once more to make the
+ corresponding threads runnable. */
+ if (run_thread == NULL &&
+ (delay != DELAY_INFTY || need_wait || retcode == -1))
+ goto try_again;
+ }
+
+ /* If we haven't something to run at that point, we're in big trouble. */
+ if (run_thread == NULL) invalid_argument("Thread: deadlock");
+
+ /* Free everything the thread was waiting on */
+ Assign(run_thread->readfds, NO_FDS);
+ Assign(run_thread->writefds, NO_FDS);
+ Assign(run_thread->exceptfds, NO_FDS);
+ Assign(run_thread->delay, NO_DELAY);
+ Assign(run_thread->joining, NO_JOINING);
+ run_thread->waitpid = NO_WAITPID;
+
+ /* Activate the thread */
+ curr_thread = run_thread;
+ stack_low = curr_thread->stack_low;
+ stack_high = curr_thread->stack_high;
+ stack_threshold = curr_thread->stack_threshold;
+ extern_sp = curr_thread->sp;
+ trapsp = curr_thread->trapsp;
+ backtrace_pos = Int_val(curr_thread->backtrace_pos);
+ backtrace_buffer = curr_thread->backtrace_buffer;
+ backtrace_last_exn = curr_thread->backtrace_last_exn;
+ return curr_thread->retval;
+}
+
+/* Since context switching is not allowed in callbacks, a thread that
+ blocks during a callback is a deadlock. */
+
+static void check_callback(void)
+{
+ if (callback_depth > 1)
+ caml_fatal_error("Thread: deadlock during callback");
+}
+
+/* Reschedule without suspending the current thread */
+
+value thread_yield(value unit) /* ML */
+{
+ Assert(curr_thread != NULL);
+ Assign(curr_thread->retval, Val_unit);
+ return schedule_thread();
+}
+
+/* Honor an asynchronous request for re-scheduling */
+
+static void thread_reschedule(void)
+{
+ value accu;
+
+ Assert(curr_thread != NULL);
+ /* Pop accu from event frame, making it look like a C_CALL frame
+ followed by a RETURN frame */
+ accu = *extern_sp++;
+ /* Reschedule */
+ Assign(curr_thread->retval, accu);
+ accu = schedule_thread();
+ /* Push accu below C_CALL frame so that it looks like an event frame */
+ *--extern_sp = accu;
+}
+
+/* Request a re-scheduling as soon as possible */
+
+value thread_request_reschedule(value unit) /* ML */
+{
+ async_action_hook = thread_reschedule;
+ something_to_do = 1;
+ return Val_unit;
+}
+
+/* Suspend the current thread */
+
+value thread_sleep(value unit) /* ML */
+{
+ Assert(curr_thread != NULL);
+ check_callback();
+ curr_thread->status = SUSPENDED;
+ return schedule_thread();
+}
+
+/* Suspend the current thread on a read() or write() request */
+
+static value thread_wait_rw(int kind, value fd)
+{
+ /* Don't do an error if we're not initialized yet
+ (we can be called from thread-safe Pervasives before initialization),
+ just return immediately. */
+ if (curr_thread == NULL) return RESUMED_WAKEUP;
+ /* As a special case, if we're in a callback, don't fail but block
+ the whole process till I/O is possible */
+ if (callback_depth > 1) {
+ fd_set fds;
+ FD_ZERO(&fds);
+ FD_SET(Int_val(fd), &fds);
+ switch(kind) {
+ case BLOCKED_READ: select(FD_SETSIZE, &fds, NULL, NULL, NULL); break;
+ case BLOCKED_WRITE: select(FD_SETSIZE, NULL, &fds, NULL, NULL); break;
+ }
+ return RESUMED_IO;
+ } else {
+ curr_thread->fd = fd;
+ curr_thread->status = kind;
+ return schedule_thread();
+ }
+}
+
+value thread_wait_read(value fd)
+{
+ return thread_wait_rw(BLOCKED_READ, fd);
+}
+
+value thread_wait_write(value fd)
+{
+ return thread_wait_rw(BLOCKED_WRITE, fd);
+}
+
+/* Suspend the current thread on a read() or write() request with timeout */
+
+static value thread_wait_timed_rw(int kind, value arg)
+{
+ double date;
+
+ check_callback();
+ curr_thread->fd = Field(arg, 0);
+ date = timeofday() + Double_val(Field(arg, 1));
+ Assign(curr_thread->delay, copy_double(date));
+ curr_thread->status = kind | BLOCKED_DELAY;
+ return schedule_thread();
+}
+
+value thread_wait_timed_read(value arg)
+{
+ return thread_wait_timed_rw(BLOCKED_READ, arg);
+}
+
+value thread_wait_timed_write(value arg)
+{
+ return thread_wait_timed_rw(BLOCKED_WRITE, arg);
+}
+
+/* Suspend the current thread on a select() request */
+
+value thread_select(value arg) /* ML */
+{
+ double date;
+ check_callback();
+ Assign(curr_thread->readfds, Field(arg, 0));
+ Assign(curr_thread->writefds, Field(arg, 1));
+ Assign(curr_thread->exceptfds, Field(arg, 2));
+ date = Double_val(Field(arg, 3));
+ if (date >= 0.0) {
+ date += timeofday();
+ Assign(curr_thread->delay, copy_double(date));
+ curr_thread->status = BLOCKED_SELECT | BLOCKED_DELAY;
+ } else {
+ curr_thread->status = BLOCKED_SELECT;
+ }
+ return schedule_thread();
+}
+
+/* Primitives to implement suspension on buffered channels */
+
+value thread_inchan_ready(value vchan) /* ML */
+{
+ struct channel * chan = Channel(vchan);
+ return Val_bool(chan->curr < chan->max);
+}
+
+value thread_outchan_ready(value vchan, value vsize) /* ML */
+{
+ struct channel * chan = Channel(vchan);
+ intnat size = Long_val(vsize);
+ /* Negative size means we want to flush the buffer entirely */
+ if (size < 0) {
+ return Val_bool(chan->curr == chan->buff);
+ } else {
+ int free = chan->end - chan->curr;
+ if (chan->curr == chan->buff)
+ return Val_bool(size < free);
+ else
+ return Val_bool(size <= free);
+ }
+}
+
+/* Suspend the current thread for some time */
+
+value thread_delay(value time) /* ML */
+{
+ double date = timeofday() + Double_val(time);
+ Assert(curr_thread != NULL);
+ check_callback();
+ curr_thread->status = BLOCKED_DELAY;
+ Assign(curr_thread->delay, copy_double(date));
+ return schedule_thread();
+}
+
+/* Suspend the current thread until another thread terminates */
+
+value thread_join(value th) /* ML */
+{
+ check_callback();
+ Assert(curr_thread != NULL);
+ if (((caml_thread_t)th)->status == KILLED) return Val_unit;
+ curr_thread->status = BLOCKED_JOIN;
+ Assign(curr_thread->joining, th);
+ return schedule_thread();
+}
+
+/* Suspend the current thread until a Unix process exits */
+
+value thread_wait_pid(value pid) /* ML */
+{
+ Assert(curr_thread != NULL);
+ check_callback();
+ curr_thread->status = BLOCKED_WAIT;
+ curr_thread->waitpid = pid;
+ return schedule_thread();
+}
+
+/* Reactivate another thread */
+
+value thread_wakeup(value thread) /* ML */
+{
+ caml_thread_t th = (caml_thread_t) thread;
+ switch (th->status) {
+ case SUSPENDED:
+ th->status = RUNNABLE;
+ Assign(th->retval, RESUMED_WAKEUP);
+ break;
+ case KILLED:
+ failwith("Thread.wakeup: killed thread");
+ default:
+ failwith("Thread.wakeup: thread not suspended");
+ }
+ return Val_unit;
+}
+
+/* Return the current thread */
+
+value thread_self(value unit) /* ML */
+{
+ Assert(curr_thread != NULL);
+ return (value) curr_thread;
+}
+
+/* Kill a thread */
+
+value thread_kill(value thread) /* ML */
+{
+ value retval = Val_unit;
+ caml_thread_t th = (caml_thread_t) thread;
+ if (th->status == KILLED) failwith("Thread.kill: killed thread");
+ /* Don't paint ourselves in a corner */
+ if (th == th->next) failwith("Thread.kill: cannot kill the last thread");
+ /* This thread is no longer waiting on anything */
+ th->status = KILLED;
+ /* If this is the current thread, activate another one */
+ if (th == curr_thread) {
+ Begin_root(thread);
+ retval = schedule_thread();
+ th = (caml_thread_t) thread;
+ End_roots();
+ }
+ /* Remove thread from the doubly-linked list */
+ Assign(th->prev->next, th->next);
+ Assign(th->next->prev, th->prev);
+ /* Free its resources */
+ stat_free((char *) th->stack_low);
+ th->stack_low = NULL;
+ th->stack_high = NULL;
+ th->stack_threshold = NULL;
+ th->sp = NULL;
+ th->trapsp = NULL;
+ if (th->backtrace_buffer != NULL) {
+ free(th->backtrace_buffer);
+ th->backtrace_buffer = NULL;
+ }
+ return retval;
+}
+
+/* Print uncaught exception and backtrace */
+
+value thread_uncaught_exception(value exn) /* ML */
+{
+ char * msg = format_caml_exception(exn);
+ fprintf(stderr, "Thread %d killed on uncaught exception %s\n",
+ Int_val(curr_thread->ident), msg);
+ free(msg);
+ if (backtrace_active) print_exception_backtrace();
+ fflush(stderr);
+ return Val_unit;
+}
+
+/* Set a list of file descriptors in a fdset */
+
+static void add_fdlist_to_set(value fdl, fd_set *set)
+{
+ for (/*nothing*/; fdl != NO_FDS; fdl = Field(fdl, 1)) {
+ int fd = Int_val(Field(fdl, 0));
+ /* Ignore funky file descriptors, which can cause crashes */
+ if (fd >= 0 && fd < FD_SETSIZE) FD_SET(fd, set);
+ }
+}
+
+/* Build the intersection of a list and a fdset (the list of file descriptors
+ which are both in the list and in the fdset). */
+
+static value inter_fdlist_set(value fdl, fd_set *set, int *count)
+{
+ value res = Val_unit;
+ value cons;
+
+ Begin_roots2(fdl, res);
+ for (res = NO_FDS; fdl != NO_FDS; fdl = Field(fdl, 1)) {
+ int fd = Int_val(Field(fdl, 0));
+ if (FD_ISSET(fd, set)) {
+ cons = alloc_small(2, 0);
+ Field(cons, 0) = Val_int(fd);
+ Field(cons, 1) = res;
+ res = cons;
+ FD_CLR(fd, set); /* wake up only one thread per fd ready */
+ (*count)--;
+ }
+ }
+ End_roots();
+ return res;
+}
+
+/* Find closed file descriptors in a waiting list and set them to 1 in
+ the given fdset */
+
+static void find_bad_fd(int fd, fd_set *set)
+{
+ struct stat s;
+ if (fd >= 0 && fd < FD_SETSIZE && fstat(fd, &s) == -1 && errno == EBADF)
+ FD_SET(fd, set);
+}
+
+static void find_bad_fds(value fdl, fd_set *set)
+{
+ for (/*nothing*/; fdl != NO_FDS; fdl = Field(fdl, 1))
+ find_bad_fd(Int_val(Field(fdl, 0)), set);
+}
+
+/* Auxiliary function for allocating the result of a waitpid() call */
+
+#if !(defined(WIFEXITED) && defined(WEXITSTATUS) && defined(WIFSTOPPED) && \
+ defined(WSTOPSIG) && defined(WTERMSIG))
+/* Assume old-style V7 status word */
+#define WIFEXITED(status) (((status) & 0xFF) == 0)
+#define WEXITSTATUS(status) (((status) >> 8) & 0xFF)
+#define WIFSTOPPED(status) (((status) & 0xFF) == 0xFF)
+#define WSTOPSIG(status) (((status) >> 8) & 0xFF)
+#define WTERMSIG(status) ((status) & 0x3F)
+#endif
+
+#define TAG_WEXITED 0
+#define TAG_WSIGNALED 1
+#define TAG_WSTOPPED 2
+
+static value alloc_process_status(int pid, int status)
+{
+ value st, res;
+
+ if (WIFEXITED(status)) {
+ st = alloc_small(1, TAG_WEXITED);
+ Field(st, 0) = Val_int(WEXITSTATUS(status));
+ }
+ else if (WIFSTOPPED(status)) {
+ st = alloc_small(1, TAG_WSTOPPED);
+ Field(st, 0) = Val_int(WSTOPSIG(status));
+ }
+ else {
+ st = alloc_small(1, TAG_WSIGNALED);
+ Field(st, 0) = Val_int(WTERMSIG(status));
+ }
+ Begin_root(st);
+ res = alloc_small(2, TAG_RESUMED_WAIT);
+ Field(res, 0) = Val_int(pid);
+ Field(res, 1) = st;
+ End_roots();
+ return res;
+}
+
+/* Restore the standard file descriptors to their initial state */
+
+static void thread_restore_std_descr(void)
+{
+ if (stdin_initial_status != -1) fcntl(0, F_SETFL, stdin_initial_status);
+ if (stdout_initial_status != -1) fcntl(1, F_SETFL, stdout_initial_status);
+ if (stderr_initial_status != -1) fcntl(2, F_SETFL, stderr_initial_status);
+}
diff --git a/otherlibs/threads/thread.ml b/otherlibs/threads/thread.ml
new file mode 100644
index 0000000000..6ed0a4bdda
--- /dev/null
+++ b/otherlibs/threads/thread.ml
@@ -0,0 +1,145 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* User-level threads *)
+
+type t
+
+let critical_section = ref false
+
+type resumption_status =
+ Resumed_wakeup
+ | Resumed_delay
+ | Resumed_join
+ | Resumed_io
+ | Resumed_select of
+ Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
+ | Resumed_wait of int * Unix.process_status
+
+(* to avoid warning *)
+let _ = [Resumed_wakeup; Resumed_delay; Resumed_join;
+ Resumed_io; Resumed_select ([], [], []);
+ Resumed_wait (0, Unix.WEXITED 0)]
+
+(* It is mucho important that the primitives that reschedule are called
+ through an ML function call, not directly. That's because when such a
+ primitive returns, the bytecode interpreter is only semi-obedient:
+ it takes sp from the new thread, but keeps pc from the old thread.
+ But that's OK if all calls to rescheduling primitives are immediately
+ followed by a RETURN operation, which will restore the correct pc
+ from the stack. Furthermore, the RETURNs must all have the same
+ frame size, which means that both the primitives and their ML wrappers
+ must take exactly one argument. *)
+
+external thread_initialize : unit -> unit = "thread_initialize"
+external thread_initialize_preemption : unit -> unit
+ = "thread_initialize_preemption"
+external thread_new : (unit -> unit) -> t = "thread_new"
+external thread_yield : unit -> unit = "thread_yield"
+external thread_request_reschedule : unit -> unit = "thread_request_reschedule"
+external thread_sleep : unit -> unit = "thread_sleep"
+external thread_wait_read : Unix.file_descr -> unit = "thread_wait_read"
+external thread_wait_write : Unix.file_descr -> unit = "thread_wait_write"
+external thread_wait_timed_read :
+ Unix.file_descr * float -> resumption_status (* remember: 1 arg *)
+ = "thread_wait_timed_read"
+external thread_wait_timed_write :
+ Unix.file_descr * float -> resumption_status (* remember: 1 arg *)
+ = "thread_wait_timed_write"
+external thread_select :
+ Unix.file_descr list * Unix.file_descr list * (* remember: 1 arg *)
+ Unix.file_descr list * float -> resumption_status
+ = "thread_select"
+external thread_join : t -> unit = "thread_join"
+external thread_delay : float -> unit = "thread_delay"
+external thread_wait_pid : int -> resumption_status = "thread_wait_pid"
+external thread_wakeup : t -> unit = "thread_wakeup"
+external thread_self : unit -> t = "thread_self" "noalloc"
+external thread_kill : t -> unit = "thread_kill"
+external thread_uncaught_exception : exn -> unit = "thread_uncaught_exception"
+external thread_id : t -> int = "thread_id" "noalloc"
+
+(* In sleep() below, we rely on the fact that signals are detected
+ only at function applications and beginning of loops,
+ making all other operations atomic. *)
+
+let yield () = thread_yield()
+let sleep () = critical_section := false; thread_sleep()
+let delay duration = thread_delay duration
+let join th = thread_join th
+let wakeup pid = thread_wakeup pid
+let self () = thread_self()
+let kill pid = thread_kill pid
+let exit () = thread_kill(thread_self())
+let id t = thread_id t
+
+let select_aux arg = thread_select arg
+
+let select readfds writefds exceptfds delay =
+ match select_aux (readfds, writefds, exceptfds, delay) with
+ Resumed_select(r, w, e) -> (r, w, e)
+ | _ -> ([], [], [])
+
+let wait_read fd = thread_wait_read fd
+let wait_write fd = thread_wait_write fd
+
+let wait_timed_read_aux arg = thread_wait_timed_read arg
+let wait_timed_write_aux arg = thread_wait_timed_write arg
+
+let wait_timed_read fd delay =
+ match wait_timed_read_aux (fd, delay) with Resumed_io -> true | _ -> false
+
+let wait_timed_write fd delay =
+ match wait_timed_write_aux (fd, delay) with Resumed_io -> true | _ -> false
+
+let wait_pid_aux pid = thread_wait_pid pid
+
+let wait_pid pid =
+ match wait_pid_aux pid with
+ Resumed_wait(pid, status) -> (pid, status)
+ | _ -> invalid_arg "Thread.wait_pid"
+
+let wait_signal sigs =
+ let gotsig = ref 0 in
+ let self = thread_self() in
+ let sighandler s = gotsig := s; wakeup self in
+ let oldhdlrs =
+ List.map (fun s -> Sys.signal s (Sys.Signal_handle sighandler)) sigs in
+ if !gotsig = 0 then sleep();
+ List.iter2 Sys.set_signal sigs oldhdlrs;
+ !gotsig
+
+(* For Thread.create, make sure the function passed to thread_new
+ always terminates by calling Thread.exit. *)
+
+let create fn arg =
+ thread_new
+ (fun () ->
+ try
+ fn arg; exit()
+ with x ->
+ flush stdout; flush stderr;
+ thread_uncaught_exception x;
+ exit())
+
+(* Preemption *)
+
+let preempt signal =
+ if !critical_section then () else thread_request_reschedule()
+
+(* Initialization of the scheduler *)
+
+let _ =
+ thread_initialize();
+ Sys.set_signal Sys.sigvtalrm (Sys.Signal_handle preempt);
+ thread_initialize_preemption()
diff --git a/otherlibs/threads/thread.mli b/otherlibs/threads/thread.mli
new file mode 100644
index 0000000000..6055d62ab0
--- /dev/null
+++ b/otherlibs/threads/thread.mli
@@ -0,0 +1,138 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Lightweight threads. *)
+
+type t
+(** The type of thread handles. *)
+
+
+(** {6 Thread creation and termination} *)
+
+val create : ('a -> 'b) -> 'a -> t
+(** [Thread.create funct arg] creates a new thread of control,
+ in which the function application [funct arg]
+ is executed concurrently with the other threads of the program.
+ The application of [Thread.create]
+ returns the handle of the newly created thread.
+ The new thread terminates when the application [funct arg]
+ returns, either normally or by raising an uncaught exception.
+ In the latter case, the exception is printed on standard error,
+ but not propagated back to the parent thread. Similarly, the
+ result of the application [funct arg] is discarded and not
+ directly accessible to the parent thread. *)
+
+val self : unit -> t
+(** Return the thread currently executing. *)
+
+val id : t -> int
+(** Return the identifier of the given thread. A thread identifier
+ is an integer that identifies uniquely the thread.
+ It can be used to build data structures indexed by threads. *)
+
+val exit : unit -> unit
+(** Terminate prematurely the currently executing thread. *)
+
+val kill : t -> unit
+(** Terminate prematurely the thread whose handle is given.
+ This functionality is available only with bytecode-level threads. *)
+
+(** {6 Suspending threads} *)
+
+val delay : float -> unit
+(** [delay d] suspends the execution of the calling thread for
+ [d] seconds. The other program threads continue to run during
+ this time. *)
+
+val join : t -> unit
+(** [join th] suspends the execution of the calling thread
+ until the thread [th] has terminated. *)
+
+val wait_read : Unix.file_descr -> unit
+(** See {!Thread.wait_write}.*)
+
+val wait_write : Unix.file_descr -> unit
+(** Suspend the execution of the calling thread until at least
+ one character is available for reading ({!Thread.wait_read}) or
+ one character can be written without blocking ([wait_write])
+ on the given Unix file descriptor. *)
+
+val wait_timed_read : Unix.file_descr -> float -> bool
+(** See {!Thread.wait_timed_write}.*)
+
+val wait_timed_write : Unix.file_descr -> float -> bool
+(** Same as {!Thread.wait_read} and {!Thread.wait_write}, but wait for at most
+ the amount of time given as second argument (in seconds).
+ Return [true] if the file descriptor is ready for input/output
+ and [false] if the timeout expired. *)
+
+val select :
+ Unix.file_descr list -> Unix.file_descr list -> Unix.file_descr list ->
+ float ->
+ Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
+(** Suspend the execution of the calling thead until input/output
+ becomes possible on the given Unix file descriptors.
+ The arguments and results have the same meaning as for
+ {!Unix.select}. *)
+
+val wait_pid : int -> int * Unix.process_status
+(** [wait_pid p] suspends the execution of the calling thread
+ until the Unix process specified by the process identifier [p]
+ terminates. A pid [p] of [-1] means wait for any child.
+ A pid of [0] means wait for any child in the same process group
+ as the current process. Negative pid arguments represent
+ process groups. Returns the pid of the child caught and
+ its termination status, as per {!Unix.wait}. *)
+
+val wait_signal : int list -> int
+(** [wait_signal sigs] suspends the execution of the calling thread
+ until the process receives one of the signals specified in the
+ list [sigs]. It then returns the number of the signal received.
+ Signal handlers attached to the signals in [sigs] will not
+ be invoked. Do not call [wait_signal] concurrently
+ from several threads on the same signals. *)
+
+val yield : unit -> unit
+(** Re-schedule the calling thread without suspending it.
+ This function can be used to give scheduling hints,
+ telling the scheduler that now is a good time to
+ switch to other threads. *)
+
+(**/**)
+
+(** {6 Synchronization primitives}
+
+ The following primitives provide the basis for implementing
+ synchronization functions between threads. Their direct use is
+ discouraged, as they are very low-level and prone to race conditions
+ and deadlocks. The modules {!Mutex}, {!Condition} and {!Event}
+ provide higher-level synchronization primitives. *)
+
+val critical_section : bool ref
+(** Setting this reference to [true] deactivate thread preemption
+ (the timer interrupt that transfers control from thread to thread),
+ causing the current thread to run uninterrupted until
+ [critical_section] is reset to [false] or the current thread
+ explicitely relinquishes control using [sleep], [delay],
+ [wait_inchan] or [wait_descr]. *)
+
+val sleep : unit -> unit
+(** Suspend the calling thread until another thread reactivates it
+ using {!Thread.wakeup}. Just before suspending the thread,
+ {!Thread.critical_section} is reset to [false]. Resetting
+ {!Thread.critical_section} and suspending the calling thread is an
+ atomic operation. *)
+
+val wakeup : t -> unit
+(** Reactivate the given thread. After the call to [wakeup],
+ the suspended thread will resume execution at some future time. *)
diff --git a/otherlibs/threads/threadUnix.ml b/otherlibs/threads/threadUnix.ml
new file mode 100644
index 0000000000..c086c1f55f
--- /dev/null
+++ b/otherlibs/threads/threadUnix.ml
@@ -0,0 +1,66 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [ThreadUnix]: thread-compatible system calls *)
+
+let execv = Unix.execv
+let execve = Unix.execve
+let execvp = Unix.execvp
+let wait = Unix.wait
+let waitpid = Unix.waitpid
+let system = Unix.system
+let read = Unix.read
+let write = Unix.write
+let single_write = Unix.single_write
+let write_substring = Unix.write_substring
+let single_write_substring = Unix.single_write_substring
+let select = Unix.select
+let pipe = Unix.pipe
+let open_process_in = Unix.open_process_in
+let open_process_out = Unix.open_process_out
+let open_process = Unix.open_process
+let open_process_full = Unix.open_process_full
+let sleep = Unix.sleep
+let socket = Unix.socket
+let socketpair = Unix.socketpair
+let accept = Unix.accept
+let connect = Unix.connect
+let recv = Unix.recv
+let recvfrom = Unix.recvfrom
+let send = Unix.send
+let send_substring = Unix.send_substring
+let sendto = Unix.sendto
+let sendto_substring = Unix.sendto_substring
+let open_connection = Unix.open_connection
+let establish_server = Unix.establish_server
+
+open Unix
+
+let rec timed_read fd buff ofs len timeout =
+ if Thread.wait_timed_read fd timeout
+ then begin try Unix.read fd buff ofs len
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ timed_read fd buff ofs len timeout
+ end
+ else raise (Unix_error(ETIMEDOUT, "timed_read", ""))
+
+let rec timed_write fd buff ofs len timeout =
+ if Thread.wait_timed_write fd timeout
+ then begin try Unix.write fd buff ofs len
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ timed_write fd buff ofs len timeout
+ end
+ else raise (Unix_error(ETIMEDOUT, "timed_write", ""))
+
+let timed_write_substring fd buff ofs len timeout =
+ timed_write fd (Bytes.unsafe_of_string buff) ofs len timeout
diff --git a/otherlibs/threads/threadUnix.mli b/otherlibs/threads/threadUnix.mli
new file mode 100644
index 0000000000..52862f98a1
--- /dev/null
+++ b/otherlibs/threads/threadUnix.mli
@@ -0,0 +1,99 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Thread-compatible system calls.
+
+ @deprecated The functionality of this module has been merged back into
+ the {!Unix} module. Threaded programs can now call the functions
+ from module {!Unix} directly, and still get the correct behavior
+ (block the calling thread, if required, but do not block all threads
+ in the process). *)
+
+(** {6 Process handling} *)
+
+val execv : string -> string array -> unit
+val execve : string -> string array -> string array -> unit
+val execvp : string -> string array -> unit
+val wait : unit -> int * Unix.process_status
+val waitpid : Unix.wait_flag list -> int -> int * Unix.process_status
+val system : string -> Unix.process_status
+
+(** {6 Basic input/output} *)
+
+val read : Unix.file_descr -> bytes -> int -> int -> int
+val write : Unix.file_descr -> bytes -> int -> int -> int
+val single_write : Unix.file_descr -> bytes -> int -> int -> int
+val write_substring : Unix.file_descr -> string -> int -> int -> int
+val single_write_substring : Unix.file_descr -> string -> int -> int -> int
+
+(** {6 Input/output with timeout} *)
+
+val timed_read : Unix.file_descr -> bytes -> int -> int -> float -> int
+(** See {!ThreadUnix.timed_write}. *)
+
+val timed_write : Unix.file_descr -> bytes -> int -> int -> float -> int
+(** Behave as {!ThreadUnix.read} and {!ThreadUnix.write}, except that
+ [Unix_error(ETIMEDOUT,_,_)] is raised if no data is
+ available for reading or ready for writing after [d] seconds.
+ The delay [d] is given in the fifth argument, in seconds. *)
+
+val timed_write_substring :
+ Unix.file_descr -> string -> int -> int -> float -> int
+(** See {!ThreadUnix.timed_write}. *)
+
+(** {6 Polling} *)
+
+val select :
+ Unix.file_descr list -> Unix.file_descr list -> Unix.file_descr list ->
+ float ->
+ Unix.file_descr list * Unix.file_descr list * Unix.file_descr list
+
+(** {6 Pipes and redirections} *)
+
+val pipe : unit -> Unix.file_descr * Unix.file_descr
+val open_process_in : string -> in_channel
+val open_process_out : string -> out_channel
+val open_process : string -> in_channel * out_channel
+val open_process_full :
+ string -> string array -> in_channel * out_channel * in_channel
+
+(** {6 Time} *)
+
+val sleep : int -> unit
+
+(** {6 Sockets} *)
+
+val socket : Unix.socket_domain -> Unix.socket_type -> int -> Unix.file_descr
+val socketpair :
+ Unix.socket_domain -> Unix.socket_type -> int ->
+ Unix.file_descr * Unix.file_descr
+val accept : Unix.file_descr -> Unix.file_descr * Unix.sockaddr
+val connect : Unix.file_descr -> Unix.sockaddr -> unit
+val recv :
+ Unix.file_descr -> bytes -> int -> int -> Unix.msg_flag list -> int
+val recvfrom :
+ Unix.file_descr -> bytes -> int -> int -> Unix.msg_flag list ->
+ int * Unix.sockaddr
+val send :
+ Unix.file_descr -> bytes -> int -> int -> Unix.msg_flag list -> int
+val send_substring :
+ Unix.file_descr -> string -> int -> int -> Unix.msg_flag list -> int
+val sendto :
+ Unix.file_descr -> bytes -> int -> int -> Unix.msg_flag list ->
+ Unix.sockaddr -> int
+val sendto_substring :
+ Unix.file_descr -> string -> int -> int -> Unix.msg_flag list ->
+ Unix.sockaddr -> int
+val open_connection : Unix.sockaddr -> in_channel * out_channel
+val establish_server :
+ (in_channel -> out_channel -> unit) -> Unix.sockaddr -> unit
diff --git a/otherlibs/threads/threads.mllib b/otherlibs/threads/threads.mllib
new file mode 100644
index 0000000000..3ff8841bd8
--- /dev/null
+++ b/otherlibs/threads/threads.mllib
@@ -0,0 +1 @@
+Thread Mutex Condition Event ThreadUnix
diff --git a/otherlibs/threads/unix.ml b/otherlibs/threads/unix.ml
new file mode 100644
index 0000000000..a397ec404f
--- /dev/null
+++ b/otherlibs/threads/unix.ml
@@ -0,0 +1,1131 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* An alternate implementation of the Unix module from ../unix
+ which is safe in conjunction with bytecode threads. *)
+
+(* Type definitions that matter for thread operations *)
+
+type file_descr = int
+
+type process_status =
+ WEXITED of int
+ | WSIGNALED of int
+ | WSTOPPED of int
+
+(* We can't call functions from Thread because of type circularities,
+ so we redefine here the functions that we need *)
+
+type resumption_status =
+ Resumed_wakeup
+ | Resumed_delay
+ | Resumed_join
+ | Resumed_io
+ | Resumed_select of file_descr list * file_descr list * file_descr list
+ | Resumed_wait of int * process_status
+
+(* to avoid warning *)
+let _ = [Resumed_wakeup; Resumed_delay; Resumed_join;
+ Resumed_io; Resumed_select ([], [], []);
+ Resumed_wait (0, WEXITED 0)]
+
+external thread_initialize : unit -> unit = "thread_initialize"
+external thread_wait_read : file_descr -> unit = "thread_wait_read"
+external thread_wait_write : file_descr -> unit = "thread_wait_write"
+external thread_select :
+ file_descr list * file_descr list * file_descr list * float
+ -> resumption_status
+ = "thread_select"
+external thread_wait_pid : int -> resumption_status = "thread_wait_pid"
+external thread_delay : float -> unit = "thread_delay"
+
+let wait_read fd = thread_wait_read fd
+let wait_write fd = thread_wait_write fd
+let select_aux arg = thread_select arg
+let wait_pid_aux pid = thread_wait_pid pid
+let delay duration = thread_delay duration
+
+(* Make sure that threads are initialized (PR#1516). *)
+
+let _ = thread_initialize()
+
+(* Back to the Unix module *)
+
+type error =
+ E2BIG
+ | EACCES
+ | EAGAIN
+ | EBADF
+ | EBUSY
+ | ECHILD
+ | EDEADLK
+ | EDOM
+ | EEXIST
+ | EFAULT
+ | EFBIG
+ | EINTR
+ | EINVAL
+ | EIO
+ | EISDIR
+ | EMFILE
+ | EMLINK
+ | ENAMETOOLONG
+ | ENFILE
+ | ENODEV
+ | ENOENT
+ | ENOEXEC
+ | ENOLCK
+ | ENOMEM
+ | ENOSPC
+ | ENOSYS
+ | ENOTDIR
+ | ENOTEMPTY
+ | ENOTTY
+ | ENXIO
+ | EPERM
+ | EPIPE
+ | ERANGE
+ | EROFS
+ | ESPIPE
+ | ESRCH
+ | EXDEV
+ | EWOULDBLOCK
+ | EINPROGRESS
+ | EALREADY
+ | ENOTSOCK
+ | EDESTADDRREQ
+ | EMSGSIZE
+ | EPROTOTYPE
+ | ENOPROTOOPT
+ | EPROTONOSUPPORT
+ | ESOCKTNOSUPPORT
+ | EOPNOTSUPP
+ | EPFNOSUPPORT
+ | EAFNOSUPPORT
+ | EADDRINUSE
+ | EADDRNOTAVAIL
+ | ENETDOWN
+ | ENETUNREACH
+ | ENETRESET
+ | ECONNABORTED
+ | ECONNRESET
+ | ENOBUFS
+ | EISCONN
+ | ENOTCONN
+ | ESHUTDOWN
+ | ETOOMANYREFS
+ | ETIMEDOUT
+ | ECONNREFUSED
+ | EHOSTDOWN
+ | EHOSTUNREACH
+ | ELOOP
+ | EOVERFLOW
+ | EUNKNOWNERR of int
+
+exception Unix_error of error * string * string
+
+let _ = Callback.register_exception "Unix.Unix_error"
+ (Unix_error(E2BIG, "", ""))
+
+external error_message : error -> string = "unix_error_message"
+
+let handle_unix_error f arg =
+ try
+ f arg
+ with Unix_error(err, fun_name, arg) ->
+ prerr_string Sys.argv.(0);
+ prerr_string ": \"";
+ prerr_string fun_name;
+ prerr_string "\" failed";
+ if String.length arg > 0 then begin
+ prerr_string " on \"";
+ prerr_string arg;
+ prerr_string "\""
+ end;
+ prerr_string ": ";
+ prerr_endline (error_message err);
+ exit 2
+
+external environment : unit -> string array = "unix_environment"
+external getenv: string -> string = "caml_sys_getenv"
+external putenv: string -> string -> unit = "unix_putenv"
+
+type interval_timer =
+ ITIMER_REAL
+ | ITIMER_VIRTUAL
+ | ITIMER_PROF
+
+type interval_timer_status =
+ { it_interval: float; (* Period *)
+ it_value: float } (* Current value of the timer *)
+
+external getitimer: interval_timer -> interval_timer_status = "unix_getitimer"
+external setitimer:
+ interval_timer -> interval_timer_status -> interval_timer_status
+ = "unix_setitimer"
+
+type wait_flag =
+ WNOHANG
+ | WUNTRACED
+
+let stdin = 0
+let stdout = 1
+let stderr = 2
+
+type open_flag =
+ O_RDONLY
+ | O_WRONLY
+ | O_RDWR
+ | O_NONBLOCK
+ | O_APPEND
+ | O_CREAT
+ | O_TRUNC
+ | O_EXCL
+ | O_NOCTTY
+ | O_DSYNC
+ | O_SYNC
+ | O_RSYNC
+ | O_SHARE_DELETE
+ | O_CLOEXEC
+
+type file_perm = int
+
+
+external openfile : string -> open_flag list -> file_perm -> file_descr
+ = "unix_open"
+
+external close : file_descr -> unit = "unix_close"
+external unsafe_read : file_descr -> bytes -> int -> int -> int = "unix_read"
+external unsafe_write : file_descr -> bytes -> int -> int -> int
+ = "unix_write"
+external unsafe_single_write : file_descr -> bytes -> int -> int -> int
+ = "unix_single_write"
+
+let rec read fd buf ofs len =
+ try
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.read"
+ else unsafe_read fd buf ofs len
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ wait_read fd; read fd buf ofs len
+
+let rec write fd buf ofs len =
+ try
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.write"
+ else unsafe_write fd buf ofs len
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ wait_write fd; write fd buf ofs len
+
+let rec single_write fd buf ofs len =
+ try
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.single_write"
+ else unsafe_single_write fd buf ofs len
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ wait_write fd; single_write fd buf ofs len
+
+let write_substring fd buf ofs len =
+ write fd (Bytes.unsafe_of_string buf) ofs len
+
+let single_write_substring fd buf ofs len =
+ single_write fd (Bytes.unsafe_of_string buf) ofs len
+
+external in_channel_of_descr : file_descr -> in_channel
+ = "caml_ml_open_descriptor_in"
+external out_channel_of_descr : file_descr -> out_channel
+ = "caml_ml_open_descriptor_out"
+external descr_of_in_channel : in_channel -> file_descr
+ = "caml_channel_descriptor"
+external descr_of_out_channel : out_channel -> file_descr
+ = "caml_channel_descriptor"
+
+type seek_command =
+ SEEK_SET
+ | SEEK_CUR
+ | SEEK_END
+
+external lseek : file_descr -> int -> seek_command -> int = "unix_lseek"
+external truncate : string -> int -> unit = "unix_truncate"
+external ftruncate : file_descr -> int -> unit = "unix_ftruncate"
+
+type file_kind =
+ S_REG
+ | S_DIR
+ | S_CHR
+ | S_BLK
+ | S_LNK
+ | S_FIFO
+ | S_SOCK
+
+type stats =
+ { st_dev : int;
+ st_ino : int;
+ st_kind : file_kind;
+ st_perm : file_perm;
+ st_nlink : int;
+ st_uid : int;
+ st_gid : int;
+ st_rdev : int;
+ st_size : int;
+ st_atime : float;
+ st_mtime : float;
+ st_ctime : float }
+
+external stat : string -> stats = "unix_stat"
+external lstat : string -> stats = "unix_lstat"
+external fstat : file_descr -> stats = "unix_fstat"
+external isatty : file_descr -> bool = "unix_isatty"
+external unlink : string -> unit = "unix_unlink"
+external rename : string -> string -> unit = "unix_rename"
+external link : string -> string -> unit = "unix_link"
+
+module LargeFile =
+ struct
+ external lseek : file_descr -> int64 -> seek_command -> int64
+ = "unix_lseek_64"
+ external truncate : string -> int64 -> unit = "unix_truncate_64"
+ external ftruncate : file_descr -> int64 -> unit = "unix_ftruncate_64"
+ type stats =
+ { st_dev : int;
+ st_ino : int;
+ st_kind : file_kind;
+ st_perm : file_perm;
+ st_nlink : int;
+ st_uid : int;
+ st_gid : int;
+ st_rdev : int;
+ st_size : int64;
+ st_atime : float;
+ st_mtime : float;
+ st_ctime : float;
+ }
+ external stat : string -> stats = "unix_stat_64"
+ external lstat : string -> stats = "unix_lstat_64"
+ external fstat : file_descr -> stats = "unix_fstat_64"
+ end
+
+type access_permission =
+ R_OK
+ | W_OK
+ | X_OK
+ | F_OK
+
+external chmod : string -> file_perm -> unit = "unix_chmod"
+external fchmod : file_descr -> file_perm -> unit = "unix_fchmod"
+external chown : string -> int -> int -> unit = "unix_chown"
+external fchown : file_descr -> int -> int -> unit = "unix_fchown"
+external umask : int -> int = "unix_umask"
+external access : string -> access_permission list -> unit = "unix_access"
+
+external dup : file_descr -> file_descr = "unix_dup"
+external dup2 : file_descr -> file_descr -> unit = "unix_dup2"
+external set_nonblock : file_descr -> unit = "unix_set_nonblock"
+external clear_nonblock : file_descr -> unit = "unix_clear_nonblock"
+external set_close_on_exec : file_descr -> unit = "unix_set_close_on_exec"
+external clear_close_on_exec : file_descr -> unit = "unix_clear_close_on_exec"
+
+external mkdir : string -> file_perm -> unit = "unix_mkdir"
+external rmdir : string -> unit = "unix_rmdir"
+external chdir : string -> unit = "unix_chdir"
+external getcwd : unit -> string = "unix_getcwd"
+external chroot : string -> unit = "unix_chroot"
+
+type dir_handle
+
+external opendir : string -> dir_handle = "unix_opendir"
+external readdir : dir_handle -> string = "unix_readdir"
+external rewinddir : dir_handle -> unit = "unix_rewinddir"
+external closedir : dir_handle -> unit = "unix_closedir"
+
+external _pipe : unit -> file_descr * file_descr = "unix_pipe"
+
+let pipe() =
+ let (out_fd, in_fd as fd_pair) = _pipe() in
+ set_nonblock in_fd;
+ set_nonblock out_fd;
+ fd_pair
+
+external symlink : string -> string -> unit = "unix_symlink"
+external readlink : string -> string = "unix_readlink"
+external mkfifo : string -> file_perm -> unit = "unix_mkfifo"
+
+let select readfds writefds exceptfds delay =
+ match select_aux (readfds, writefds, exceptfds, delay) with
+ Resumed_select(r, w, e) -> (r, w, e)
+ | _ -> ([], [], [])
+
+type lock_command =
+ F_ULOCK
+ | F_LOCK
+ | F_TLOCK
+ | F_TEST
+ | F_RLOCK
+ | F_TRLOCK
+
+external lockf : file_descr -> lock_command -> int -> unit = "unix_lockf"
+
+external _execv : string -> string array -> 'a = "unix_execv"
+external _execve : string -> string array -> string array -> 'a = "unix_execve"
+external _execvp : string -> string array -> 'a = "unix_execvp"
+external _execvpe : string -> string array -> string array -> 'a
+ = "unix_execvpe"
+
+(* Disable the timer interrupt before doing exec, because some OS
+ keep sending timer interrupts to the exec'ed code.
+ Also restore blocking mode on stdin, stdout and stderr,
+ since this is what most programs expect! *)
+
+let safe_clear_nonblock fd =
+ try clear_nonblock fd with Unix_error(_,_,_) -> ()
+let safe_set_nonblock fd =
+ try set_nonblock fd with Unix_error(_,_,_) -> ()
+
+let do_exec fn =
+ let oldtimer =
+ setitimer ITIMER_VIRTUAL {it_interval = 0.0; it_value = 0.0} in
+ safe_clear_nonblock stdin;
+ safe_clear_nonblock stdout;
+ safe_clear_nonblock stderr;
+ try
+ fn ()
+ with Unix_error(_,_,_) as exn ->
+ ignore(setitimer ITIMER_VIRTUAL oldtimer);
+ safe_set_nonblock stdin;
+ safe_set_nonblock stdout;
+ safe_set_nonblock stderr;
+ raise exn
+
+let execv proc args =
+ do_exec (fun () -> _execv proc args)
+
+let execve proc args env =
+ do_exec (fun () -> _execve proc args env)
+
+let execvp proc args =
+ do_exec (fun () -> _execvp proc args)
+
+let execvpe proc args =
+ do_exec (fun () -> _execvpe proc args)
+
+external fork : unit -> int = "unix_fork"
+external _waitpid : wait_flag list -> int -> int * process_status
+ = "unix_waitpid"
+
+let wait_pid pid =
+ match wait_pid_aux pid with
+ Resumed_wait(pid, status) -> (pid, status)
+ | _ -> invalid_arg "Thread.wait_pid"
+
+let wait () = wait_pid (-1)
+
+let waitpid flags pid =
+ if List.mem WNOHANG flags
+ then _waitpid flags pid
+ else wait_pid pid
+
+external getpid : unit -> int = "unix_getpid"
+external getppid : unit -> int = "unix_getppid"
+external nice : int -> int = "unix_nice"
+
+external kill : int -> int -> unit = "unix_kill"
+type sigprocmask_command = SIG_SETMASK | SIG_BLOCK | SIG_UNBLOCK
+external sigprocmask: sigprocmask_command -> int list -> int list
+ = "unix_sigprocmask"
+external sigpending: unit -> int list = "unix_sigpending"
+external sigsuspend: int list -> unit = "unix_sigsuspend"
+
+let pause() =
+ let sigs = sigprocmask SIG_BLOCK [] in sigsuspend sigs
+
+type process_times =
+ { tms_utime : float;
+ tms_stime : float;
+ tms_cutime : float;
+ tms_cstime : float }
+
+type tm =
+ { tm_sec : int;
+ tm_min : int;
+ tm_hour : int;
+ tm_mday : int;
+ tm_mon : int;
+ tm_year : int;
+ tm_wday : int;
+ tm_yday : int;
+ tm_isdst : bool }
+
+external time : unit -> float = "unix_time"
+external gettimeofday : unit -> float = "unix_gettimeofday"
+external gmtime : float -> tm = "unix_gmtime"
+external localtime : float -> tm = "unix_localtime"
+external mktime : tm -> float * tm = "unix_mktime"
+external alarm : int -> int = "unix_alarm"
+
+let sleep secs = delay (float secs)
+
+external times : unit -> process_times = "unix_times"
+external utimes : string -> float -> float -> unit = "unix_utimes"
+
+external getuid : unit -> int = "unix_getuid"
+external geteuid : unit -> int = "unix_geteuid"
+external setuid : int -> unit = "unix_setuid"
+external getgid : unit -> int = "unix_getgid"
+external getegid : unit -> int = "unix_getegid"
+external setgid : int -> unit = "unix_setgid"
+external getgroups : unit -> int array = "unix_getgroups"
+external setgroups : int array -> unit = "unix_setgroups"
+external initgroups : string -> int -> unit = "unix_initgroups"
+
+type passwd_entry =
+ { pw_name : string;
+ pw_passwd : string;
+ pw_uid : int;
+ pw_gid : int;
+ pw_gecos : string;
+ pw_dir : string;
+ pw_shell : string }
+
+type group_entry =
+ { gr_name : string;
+ gr_passwd : string;
+ gr_gid : int;
+ gr_mem : string array }
+
+
+external getlogin : unit -> string = "unix_getlogin"
+external getpwnam : string -> passwd_entry = "unix_getpwnam"
+external getgrnam : string -> group_entry = "unix_getgrnam"
+external getpwuid : int -> passwd_entry = "unix_getpwuid"
+external getgrgid : int -> group_entry = "unix_getgrgid"
+
+type inet_addr = string
+
+external inet_addr_of_string : string -> inet_addr
+ = "unix_inet_addr_of_string"
+external string_of_inet_addr : inet_addr -> string
+ = "unix_string_of_inet_addr"
+
+let inet_addr_any = inet_addr_of_string "0.0.0.0"
+let inet_addr_loopback = inet_addr_of_string "127.0.0.1"
+let inet6_addr_any =
+ try inet_addr_of_string "::" with Failure _ -> inet_addr_any
+let inet6_addr_loopback =
+ try inet_addr_of_string "::1" with Failure _ -> inet_addr_loopback
+
+let is_inet6_addr s = String.length s = 16
+
+type socket_domain =
+ PF_UNIX
+ | PF_INET
+ | PF_INET6
+
+type socket_type =
+ SOCK_STREAM
+ | SOCK_DGRAM
+ | SOCK_RAW
+ | SOCK_SEQPACKET
+
+type sockaddr =
+ ADDR_UNIX of string
+ | ADDR_INET of inet_addr * int
+
+let domain_of_sockaddr = function
+ ADDR_UNIX _ -> PF_UNIX
+ | ADDR_INET(a, _) -> if is_inet6_addr a then PF_INET6 else PF_INET
+
+type shutdown_command =
+ SHUTDOWN_RECEIVE
+ | SHUTDOWN_SEND
+ | SHUTDOWN_ALL
+
+type msg_flag =
+ MSG_OOB
+ | MSG_DONTROUTE
+ | MSG_PEEK
+
+external _socket : socket_domain -> socket_type -> int -> file_descr
+ = "unix_socket"
+external _socketpair :
+ socket_domain -> socket_type -> int -> file_descr * file_descr
+ = "unix_socketpair"
+
+let socket dom typ proto =
+ let s = _socket dom typ proto in
+ set_nonblock s;
+ s
+
+let socketpair dom typ proto =
+ let (s1, s2 as spair) = _socketpair dom typ proto in
+ set_nonblock s1; set_nonblock s2;
+ spair
+
+external _accept : file_descr -> file_descr * sockaddr = "unix_accept"
+
+let rec accept req =
+ wait_read req;
+ try
+ let (s, caller as result) = _accept req in
+ set_nonblock s;
+ result
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) -> accept req
+
+external bind : file_descr -> sockaddr -> unit = "unix_bind"
+external listen : file_descr -> int -> unit = "unix_listen"
+external shutdown : file_descr -> shutdown_command -> unit = "unix_shutdown"
+external getsockname : file_descr -> sockaddr = "unix_getsockname"
+external getpeername : file_descr -> sockaddr = "unix_getpeername"
+
+external _connect : file_descr -> sockaddr -> unit = "unix_connect"
+
+let connect s addr =
+ try
+ _connect s addr
+ with Unix_error((EINPROGRESS | EWOULDBLOCK | EAGAIN), _, _) ->
+ wait_write s;
+ (* Check if it really worked *)
+ ignore(getpeername s)
+
+external unsafe_recv :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int
+ = "unix_recv"
+external unsafe_recvfrom :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int * sockaddr
+ = "unix_recvfrom"
+external unsafe_send :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int
+ = "unix_send"
+external unsafe_sendto :
+ file_descr -> bytes -> int -> int -> msg_flag list -> sockaddr -> int
+ = "unix_sendto" "unix_sendto_native"
+
+let rec recv fd buf ofs len flags =
+ try
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.recv"
+ else unsafe_recv fd buf ofs len flags
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ wait_read fd; recv fd buf ofs len flags
+
+let rec recvfrom fd buf ofs len flags =
+ try
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.recvfrom"
+ else unsafe_recvfrom fd buf ofs len flags
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ wait_read fd;
+ recvfrom fd buf ofs len flags
+
+let rec send fd buf ofs len flags =
+ try
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.send"
+ else unsafe_send fd buf ofs len flags
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ wait_write fd;
+ send fd buf ofs len flags
+
+let rec sendto fd buf ofs len flags addr =
+ try
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.sendto"
+ else unsafe_sendto fd buf ofs len flags addr
+ with Unix_error((EAGAIN | EWOULDBLOCK), _, _) ->
+ wait_write fd;
+ sendto fd buf ofs len flags addr
+
+let send_substring fd buf ofs len flags =
+ send fd (Bytes.unsafe_of_string buf) ofs len flags
+
+let sendto_substring fd buf ofs len flags addr =
+ sendto fd (Bytes.unsafe_of_string buf) ofs len flags addr
+
+type socket_bool_option =
+ SO_DEBUG
+ | SO_BROADCAST
+ | SO_REUSEADDR
+ | SO_KEEPALIVE
+ | SO_DONTROUTE
+ | SO_OOBINLINE
+ | SO_ACCEPTCONN
+ | TCP_NODELAY
+ | IPV6_ONLY
+
+
+type socket_int_option =
+ SO_SNDBUF
+ | SO_RCVBUF
+ | SO_ERROR
+ | SO_TYPE
+ | SO_RCVLOWAT
+ | SO_SNDLOWAT
+
+type socket_optint_option = SO_LINGER
+
+type socket_float_option =
+ SO_RCVTIMEO
+ | SO_SNDTIMEO
+
+type socket_error_option = SO_ERROR
+
+module SO: sig
+ type ('opt, 'v) t
+ val bool: (socket_bool_option, bool) t
+ val int: (socket_int_option, int) t
+ val optint: (socket_optint_option, int option) t
+ val float: (socket_float_option, float) t
+ val error: (socket_error_option, error option) t
+ val get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
+ val set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
+end = struct
+ type ('opt, 'v) t = int
+ let bool = 0
+ let int = 1
+ let optint = 2
+ let float = 3
+ let error = 4
+ external get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
+ = "unix_getsockopt"
+ external set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
+ = "unix_setsockopt"
+end
+
+let getsockopt fd opt = SO.get SO.bool fd opt
+let setsockopt fd opt v = SO.set SO.bool fd opt v
+
+let getsockopt_int fd opt = SO.get SO.int fd opt
+let setsockopt_int fd opt v = SO.set SO.int fd opt v
+
+let getsockopt_optint fd opt = SO.get SO.optint fd opt
+let setsockopt_optint fd opt v = SO.set SO.optint fd opt v
+
+let getsockopt_float fd opt = SO.get SO.float fd opt
+let setsockopt_float fd opt v = SO.set SO.float fd opt v
+
+let getsockopt_error fd = SO.get SO.error fd SO_ERROR
+
+type host_entry =
+ { h_name : string;
+ h_aliases : string array;
+ h_addrtype : socket_domain;
+ h_addr_list : inet_addr array }
+
+type protocol_entry =
+ { p_name : string;
+ p_aliases : string array;
+ p_proto : int }
+
+type service_entry =
+ { s_name : string;
+ s_aliases : string array;
+ s_port : int;
+ s_proto : string }
+
+external gethostname : unit -> string = "unix_gethostname"
+external gethostbyname : string -> host_entry = "unix_gethostbyname"
+external gethostbyaddr : inet_addr -> host_entry = "unix_gethostbyaddr"
+external getprotobyname : string -> protocol_entry
+ = "unix_getprotobyname"
+external getprotobynumber : int -> protocol_entry
+ = "unix_getprotobynumber"
+external getservbyname : string -> string -> service_entry
+ = "unix_getservbyname"
+external getservbyport : int -> string -> service_entry
+ = "unix_getservbyport"
+type addr_info =
+ { ai_family : socket_domain;
+ ai_socktype : socket_type;
+ ai_protocol : int;
+ ai_addr : sockaddr;
+ ai_canonname : string }
+
+type getaddrinfo_option =
+ AI_FAMILY of socket_domain
+ | AI_SOCKTYPE of socket_type
+ | AI_PROTOCOL of int
+ | AI_NUMERICHOST
+ | AI_CANONNAME
+ | AI_PASSIVE
+
+external getaddrinfo_system
+ : string -> string -> getaddrinfo_option list -> addr_info list
+ = "unix_getaddrinfo"
+
+let getaddrinfo_emulation node service opts =
+ (* Parse options *)
+ let opt_socktype = ref None
+ and opt_protocol = ref 0
+ and opt_passive = ref false in
+ List.iter
+ (function AI_SOCKTYPE s -> opt_socktype := Some s
+ | AI_PROTOCOL p -> opt_protocol := p
+ | AI_PASSIVE -> opt_passive := true
+ | _ -> ())
+ opts;
+ (* Determine socket types and port numbers *)
+ let get_port ty kind =
+ if service = "" then [ty, 0] else
+ try
+ [ty, int_of_string service]
+ with Failure _ ->
+ try
+ [ty, (getservbyname service kind).s_port]
+ with Not_found -> []
+ in
+ let ports =
+ match !opt_socktype with
+ | None ->
+ get_port SOCK_STREAM "tcp" @ get_port SOCK_DGRAM "udp"
+ | Some SOCK_STREAM ->
+ get_port SOCK_STREAM "tcp"
+ | Some SOCK_DGRAM ->
+ get_port SOCK_DGRAM "udp"
+ | Some ty ->
+ if service = "" then [ty, 0] else [] in
+ (* Determine IP addresses *)
+ let addresses =
+ if node = "" then
+ if List.mem AI_PASSIVE opts
+ then [inet_addr_any, "0.0.0.0"]
+ else [inet_addr_loopback, "127.0.0.1"]
+ else
+ try
+ [inet_addr_of_string node, node]
+ with Failure _ ->
+ try
+ let he = gethostbyname node in
+ List.map
+ (fun a -> (a, he.h_name))
+ (Array.to_list he.h_addr_list)
+ with Not_found ->
+ [] in
+ (* Cross-product of addresses and ports *)
+ List.flatten
+ (List.map
+ (fun (ty, port) ->
+ List.map
+ (fun (addr, name) ->
+ { ai_family = PF_INET;
+ ai_socktype = ty;
+ ai_protocol = !opt_protocol;
+ ai_addr = ADDR_INET(addr, port);
+ ai_canonname = name })
+ addresses)
+ ports)
+
+let getaddrinfo node service opts =
+ try
+ List.rev(getaddrinfo_system node service opts)
+ with Invalid_argument _ ->
+ getaddrinfo_emulation node service opts
+
+type name_info =
+ { ni_hostname : string;
+ ni_service : string }
+
+type getnameinfo_option =
+ NI_NOFQDN
+ | NI_NUMERICHOST
+ | NI_NAMEREQD
+ | NI_NUMERICSERV
+ | NI_DGRAM
+
+external getnameinfo_system
+ : sockaddr -> getnameinfo_option list -> name_info
+ = "unix_getnameinfo"
+
+let getnameinfo_emulation addr opts =
+ match addr with
+ | ADDR_UNIX f ->
+ { ni_hostname = ""; ni_service = f } (* why not? *)
+ | ADDR_INET(a, p) ->
+ let hostname =
+ try
+ if List.mem NI_NUMERICHOST opts then raise Not_found;
+ (gethostbyaddr a).h_name
+ with Not_found ->
+ if List.mem NI_NAMEREQD opts then raise Not_found;
+ string_of_inet_addr a in
+ let service =
+ try
+ if List.mem NI_NUMERICSERV opts then raise Not_found;
+ let kind = if List.mem NI_DGRAM opts then "udp" else "tcp" in
+ (getservbyport p kind).s_name
+ with Not_found ->
+ string_of_int p in
+ { ni_hostname = hostname; ni_service = service }
+
+let getnameinfo addr opts =
+ try
+ getnameinfo_system addr opts
+ with Invalid_argument _ ->
+ getnameinfo_emulation addr opts
+
+type terminal_io = {
+ mutable c_ignbrk: bool;
+ mutable c_brkint: bool;
+ mutable c_ignpar: bool;
+ mutable c_parmrk: bool;
+ mutable c_inpck: bool;
+ mutable c_istrip: bool;
+ mutable c_inlcr: bool;
+ mutable c_igncr: bool;
+ mutable c_icrnl: bool;
+ mutable c_ixon: bool;
+ mutable c_ixoff: bool;
+ mutable c_opost: bool;
+ mutable c_obaud: int;
+ mutable c_ibaud: int;
+ mutable c_csize: int;
+ mutable c_cstopb: int;
+ mutable c_cread: bool;
+ mutable c_parenb: bool;
+ mutable c_parodd: bool;
+ mutable c_hupcl: bool;
+ mutable c_clocal: bool;
+ mutable c_isig: bool;
+ mutable c_icanon: bool;
+ mutable c_noflsh: bool;
+ mutable c_echo: bool;
+ mutable c_echoe: bool;
+ mutable c_echok: bool;
+ mutable c_echonl: bool;
+ mutable c_vintr: char;
+ mutable c_vquit: char;
+ mutable c_verase: char;
+ mutable c_vkill: char;
+ mutable c_veof: char;
+ mutable c_veol: char;
+ mutable c_vmin: int;
+ mutable c_vtime: int;
+ mutable c_vstart: char;
+ mutable c_vstop: char
+ }
+
+external tcgetattr: file_descr -> terminal_io = "unix_tcgetattr"
+
+type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
+
+external tcsetattr: file_descr -> setattr_when -> terminal_io -> unit
+ = "unix_tcsetattr"
+external tcsendbreak: file_descr -> int -> unit = "unix_tcsendbreak"
+external tcdrain: file_descr -> unit = "unix_tcdrain"
+
+type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
+
+external tcflush: file_descr -> flush_queue -> unit = "unix_tcflush"
+
+type flow_action = TCOOFF | TCOON | TCIOFF | TCION
+
+external tcflow: file_descr -> flow_action -> unit = "unix_tcflow"
+
+external setsid : unit -> int = "unix_setsid"
+
+(* High-level process management (system, popen) *)
+
+let system cmd =
+ match fork() with
+ 0 -> begin try
+ execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
+ with _ ->
+ exit 127
+ end
+ | id -> snd(waitpid [] id)
+
+let rec safe_dup fd =
+ let new_fd = dup fd in
+ if new_fd >= 3 then
+ new_fd
+ else begin
+ let res = safe_dup fd in
+ close new_fd;
+ res
+ end
+
+let safe_close fd =
+ try close fd with Unix_error(_,_,_) -> ()
+
+let perform_redirections new_stdin new_stdout new_stderr =
+ let newnewstdin = safe_dup new_stdin in
+ let newnewstdout = safe_dup new_stdout in
+ let newnewstderr = safe_dup new_stderr in
+ safe_close new_stdin;
+ safe_close new_stdout;
+ safe_close new_stderr;
+ dup2 newnewstdin stdin; close newnewstdin;
+ dup2 newnewstdout stdout; close newnewstdout;
+ dup2 newnewstderr stderr; close newnewstderr
+
+let create_process cmd args new_stdin new_stdout new_stderr =
+ match fork() with
+ 0 ->
+ begin try
+ perform_redirections new_stdin new_stdout new_stderr;
+ execvp cmd args
+ with _ ->
+ exit 127
+ end
+ | id -> id
+
+let create_process_env cmd args env new_stdin new_stdout new_stderr =
+ match fork() with
+ 0 ->
+ begin try
+ perform_redirections new_stdin new_stdout new_stderr;
+ execvpe cmd args env
+ with _ ->
+ exit 127
+ end
+ | id -> id
+
+type popen_process =
+ Process of in_channel * out_channel
+ | Process_in of in_channel
+ | Process_out of out_channel
+ | Process_full of in_channel * out_channel * in_channel
+
+let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t)
+
+let open_proc cmd proc input output toclose =
+ match fork() with
+ 0 -> if input <> stdin then begin dup2 input stdin; close input end;
+ if output <> stdout then begin dup2 output stdout; close output end;
+ List.iter close toclose;
+ begin try execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
+ with _ -> exit 127
+ end
+ | id -> Hashtbl.add popen_processes proc id
+
+let open_process_in cmd =
+ let (in_read, in_write) = pipe() in
+ let inchan = in_channel_of_descr in_read in
+ open_proc cmd (Process_in inchan) stdin in_write [in_read];
+ close in_write;
+ inchan
+
+let open_process_out cmd =
+ let (out_read, out_write) = pipe() in
+ let outchan = out_channel_of_descr out_write in
+ open_proc cmd (Process_out outchan) out_read stdout [out_write];
+ close out_read;
+ outchan
+
+let open_process cmd =
+ let (in_read, in_write) = pipe() in
+ let (out_read, out_write) = pipe() in
+ let inchan = in_channel_of_descr in_read in
+ let outchan = out_channel_of_descr out_write in
+ open_proc cmd (Process(inchan, outchan)) out_read in_write
+ [in_read; out_write];
+ close out_read;
+ close in_write;
+ (inchan, outchan)
+
+let open_proc_full cmd env proc input output error toclose =
+ match fork() with
+ 0 -> dup2 input stdin; close input;
+ dup2 output stdout; close output;
+ dup2 error stderr; close error;
+ List.iter close toclose;
+ begin try execve "/bin/sh" [| "/bin/sh"; "-c"; cmd |] env
+ with _ -> exit 127
+ end
+ | id -> Hashtbl.add popen_processes proc id
+
+let open_process_full cmd env =
+ let (in_read, in_write) = pipe() in
+ let (out_read, out_write) = pipe() in
+ let (err_read, err_write) = pipe() in
+ let inchan = in_channel_of_descr in_read in
+ let outchan = out_channel_of_descr out_write in
+ let errchan = in_channel_of_descr err_read in
+ open_proc_full cmd env (Process_full(inchan, outchan, errchan))
+ out_read in_write err_write [in_read; out_write; err_read];
+ close out_read;
+ close in_write;
+ close err_write;
+ (inchan, outchan, errchan)
+
+let find_proc_id fun_name proc =
+ try
+ let pid = Hashtbl.find popen_processes proc in
+ Hashtbl.remove popen_processes proc;
+ pid
+ with Not_found ->
+ raise(Unix_error(EBADF, fun_name, ""))
+
+let rec waitpid_non_intr pid =
+ try waitpid [] pid
+ with Unix_error (EINTR, _, _) -> waitpid_non_intr pid
+
+let close_process_in inchan =
+ let pid = find_proc_id "close_process_in" (Process_in inchan) in
+ close_in inchan;
+ snd(waitpid_non_intr pid)
+
+let close_process_out outchan =
+ let pid = find_proc_id "close_process_out" (Process_out outchan) in
+ close_out outchan;
+ snd(waitpid_non_intr pid)
+
+let close_process (inchan, outchan) =
+ let pid = find_proc_id "close_process" (Process(inchan, outchan)) in
+ close_in inchan;
+ begin try close_out outchan with Sys_error _ -> () end;
+ snd(waitpid_non_intr pid)
+
+let close_process_full (inchan, outchan, errchan) =
+ let pid =
+ find_proc_id "close_process_full"
+ (Process_full(inchan, outchan, errchan)) in
+ close_in inchan;
+ begin try close_out outchan with Sys_error _ -> () end;
+ close_in errchan;
+ snd(waitpid_non_intr pid)
+
+(* High-level network functions *)
+
+let open_connection sockaddr =
+ let sock =
+ socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
+ try
+ connect sock sockaddr;
+ (in_channel_of_descr sock, out_channel_of_descr sock)
+ with exn ->
+ close sock; raise exn
+
+let shutdown_connection inchan =
+ shutdown (descr_of_in_channel inchan) SHUTDOWN_SEND
+
+let establish_server server_fun sockaddr =
+ let sock =
+ socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
+ setsockopt sock SO_REUSEADDR true;
+ bind sock sockaddr;
+ listen sock 5;
+ while true do
+ let (s, caller) = accept sock in
+ (* The "double fork" trick, the process which calls server_fun will not
+ leave a zombie process *)
+ match fork() with
+ 0 -> if fork() <> 0 then exit 0; (* The son exits, the grandson works *)
+ let inchan = in_channel_of_descr s in
+ let outchan = out_channel_of_descr s in
+ server_fun inchan outchan;
+ close_out outchan;
+ (* The file descriptor was already closed by close_out.
+ close_in inchan;
+ *)
+ exit 0
+ | id -> close s; ignore(waitpid [] id) (* Reclaim the son *)
+ done
diff --git a/otherlibs/threads/unix.mllib b/otherlibs/threads/unix.mllib
new file mode 100644
index 0000000000..8d569c56d0
--- /dev/null
+++ b/otherlibs/threads/unix.mllib
@@ -0,0 +1 @@
+Unix UnixLabels
diff --git a/otherlibs/unix/.depend b/otherlibs/unix/.depend
new file mode 100644
index 0000000000..4f6a638740
--- /dev/null
+++ b/otherlibs/unix/.depend
@@ -0,0 +1,644 @@
+accept.o: accept.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+access.o: access.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h ../../byterun/caml/signals.h \
+ unixsupport.h
+addrofstr.o: addrofstr.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/fail.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+alarm.o: alarm.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+bind.o: bind.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+chdir.o: chdir.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+chmod.o: chmod.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+chown.o: chown.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+chroot.o: chroot.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+close.o: close.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/signals.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+closedir.o: closedir.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+connect.o: connect.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/signals.h unixsupport.h \
+ socketaddr.h ../../byterun/caml/misc.h
+cst2constr.o: cst2constr.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/mlvalues.h cst2constr.h
+cstringv.o: cstringv.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+dup2.o: dup2.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+dup.o: dup.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+envir.o: envir.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h
+errmsg.o: errmsg.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h
+execv.o: execv.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+execve.o: execve.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+execvp.o: execvp.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+exit.o: exit.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+fchmod.o: fchmod.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/signals.h unixsupport.h
+fchown.o: fchown.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/signals.h unixsupport.h
+fcntl.o: fcntl.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+fork.o: fork.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/debugger.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+ftruncate.o: ftruncate.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/io.h \
+ ../../byterun/caml/signals.h unixsupport.h
+getaddrinfo.o: getaddrinfo.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/signals.h unixsupport.h \
+ cst2constr.h socketaddr.h
+getcwd.o: getcwd.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h unixsupport.h
+getegid.o: getegid.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+geteuid.o: geteuid.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+getgid.o: getgid.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+getgr.o: getgr.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+getgroups.o: getgroups.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h unixsupport.h
+gethost.o: gethost.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+gethostname.o: gethostname.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h unixsupport.h
+getlogin.o: getlogin.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+getnameinfo.o: getnameinfo.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+getpeername.o: getpeername.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+getpid.o: getpid.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+getppid.o: getppid.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+getproto.o: getproto.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+getpw.o: getpw.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h ../../byterun/caml/fail.h \
+ unixsupport.h
+getserv.o: getserv.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+getsockname.o: getsockname.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+gettimeofday.o: gettimeofday.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h unixsupport.h
+getuid.o: getuid.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+gmtime.o: gmtime.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+initgroups.o: initgroups.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h unixsupport.h
+isatty.o: isatty.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+itimer.o: itimer.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+kill.o: kill.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h ../../byterun/caml/signals.h
+link.o: link.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+listen.o: listen.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+lockf.o: lockf.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/signals.h unixsupport.h
+lseek.o: lseek.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/io.h \
+ ../../byterun/caml/signals.h unixsupport.h
+mkdir.o: mkdir.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+mkfifo.o: mkfifo.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h ../../byterun/caml/signals.h \
+ unixsupport.h
+nice.o: nice.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+open.o: open.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/signals.h unixsupport.h
+opendir.o: opendir.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/signals.h unixsupport.h
+pipe.o: pipe.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+putenv.o: putenv.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+read.o: read.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+readdir.o: readdir.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/signals.h unixsupport.h
+readlink.o: readlink.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/signals.h unixsupport.h
+rename.o: rename.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+rewinddir.o: rewinddir.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+rmdir.o: rmdir.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+select.o: select.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+sendrecv.o: sendrecv.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+setgid.o: setgid.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+setgroups.o: setgroups.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ unixsupport.h
+setsid.o: setsid.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+setuid.o: setuid.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+shutdown.o: shutdown.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+signals.o: signals.c ../../byterun/caml/alloc.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/fail.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/signals.h unixsupport.h
+sleep.o: sleep.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/signals.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+socketaddr.o: socketaddr.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h unixsupport.h socketaddr.h \
+ ../../byterun/caml/misc.h
+socket.o: socket.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+socketpair.o: socketpair.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h unixsupport.h
+sockopt.o: sockopt.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/fail.h unixsupport.h \
+ socketaddr.h ../../byterun/caml/misc.h
+stat.o: stat.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/alloc.h ../../byterun/caml/signals.h \
+ ../../byterun/caml/io.h unixsupport.h cst2constr.h nanosecond_stat.h
+strofaddr.o: strofaddr.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h unixsupport.h \
+ socketaddr.h ../../byterun/caml/misc.h
+symlink.o: symlink.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h ../../byterun/caml/signals.h \
+ unixsupport.h
+termios.o: termios.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h unixsupport.h
+time.o: time.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h unixsupport.h
+times.o: times.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h unixsupport.h
+truncate.o: truncate.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/fail.h ../../byterun/caml/signals.h \
+ ../../byterun/caml/io.h unixsupport.h
+umask.o: umask.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h unixsupport.h
+unixsupport.o: unixsupport.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/callback.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/fail.h unixsupport.h cst2constr.h
+unlink.o: unlink.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+utimes.o: utimes.c ../../byterun/caml/fail.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/misc.h \
+ ../../byterun/caml/config.h ../../byterun/caml/../../config/m.h \
+ ../../byterun/caml/../../config/s.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/major_gc.h \
+ ../../byterun/caml/freelist.h ../../byterun/caml/minor_gc.h \
+ ../../byterun/caml/address_class.h ../../byterun/caml/signals.h \
+ unixsupport.h
+wait.o: wait.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/alloc.h \
+ ../../byterun/caml/mlvalues.h ../../byterun/caml/fail.h \
+ ../../byterun/caml/memory.h ../../byterun/caml/gc.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+write.o: write.c ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/compatibility.h ../../byterun/caml/config.h \
+ ../../byterun/caml/../../config/m.h ../../byterun/caml/../../config/s.h \
+ ../../byterun/caml/misc.h ../../byterun/caml/memory.h \
+ ../../byterun/caml/gc.h ../../byterun/caml/mlvalues.h \
+ ../../byterun/caml/major_gc.h ../../byterun/caml/freelist.h \
+ ../../byterun/caml/minor_gc.h ../../byterun/caml/address_class.h \
+ ../../byterun/caml/signals.h unixsupport.h
+unixLabels.cmi : unix.cmi
+unix.cmi :
+unixLabels.cmo : unix.cmi unixLabels.cmi
+unixLabels.cmx : unix.cmx unixLabels.cmi
+unix.cmo : unix.cmi
+unix.cmx : unix.cmi
diff --git a/otherlibs/unix/Makefile b/otherlibs/unix/Makefile
new file mode 100644
index 0000000000..faebd3f5c8
--- /dev/null
+++ b/otherlibs/unix/Makefile
@@ -0,0 +1,47 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Makefile for the Unix interface library
+
+LIBNAME=unix
+
+EXTRACAMLFLAGS=-nolabels
+
+COBJS=accept.o access.o addrofstr.o alarm.o bind.o chdir.o chmod.o \
+ chown.o chroot.o close.o closedir.o connect.o cst2constr.o cstringv.o \
+ dup.o dup2.o envir.o errmsg.o execv.o execve.o execvp.o exit.o \
+ fchmod.o fchown.o fcntl.o fork.o ftruncate.o \
+ getaddrinfo.o getcwd.o getegid.o geteuid.o getgid.o \
+ getgr.o getgroups.o gethost.o gethostname.o getlogin.o \
+ getnameinfo.o getpeername.o getpid.o getppid.o getproto.o getpw.o \
+ gettimeofday.o getserv.o getsockname.o getuid.o gmtime.o \
+ initgroups.o isatty.o itimer.o kill.o link.o listen.o lockf.o lseek.o \
+ mkdir.o mkfifo.o nice.o open.o opendir.o pipe.o putenv.o read.o \
+ readdir.o readlink.o rename.o rewinddir.o rmdir.o select.o sendrecv.o \
+ setgid.o setgroups.o setsid.o setuid.o shutdown.o signals.o \
+ sleep.o socket.o socketaddr.o \
+ socketpair.o sockopt.o stat.o strofaddr.o symlink.o termios.o \
+ time.o times.o truncate.o umask.o unixsupport.o unlink.o \
+ utimes.o wait.o write.o
+
+CAMLOBJS=unix.cmo unixLabels.cmo
+
+HEADERS=unixsupport.h socketaddr.h
+
+include ../Makefile
+
+depend:
+ $(CC) -MM $(CFLAGS) *.c > .depend
+ $(CAMLRUN) ../../tools/ocamldep *.mli *.ml >> .depend
+
+include .depend
diff --git a/otherlibs/unix/accept.c b/otherlibs/unix/accept.c
new file mode 100644
index 0000000000..3fd019188f
--- /dev/null
+++ b/otherlibs/unix/accept.c
@@ -0,0 +1,52 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+
+CAMLprim value unix_accept(value sock)
+{
+ int retcode;
+ value res;
+ value a;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ addr_len = sizeof(addr);
+ enter_blocking_section();
+ retcode = accept(Int_val(sock), &addr.s_gen, &addr_len);
+ leave_blocking_section();
+ if (retcode == -1) uerror("accept", Nothing);
+ a = alloc_sockaddr(&addr, addr_len, retcode);
+ Begin_root (a);
+ res = alloc_small(2, 0);
+ Field(res, 0) = Val_int(retcode);
+ Field(res, 1) = a;
+ End_roots();
+ return res;
+}
+
+#else
+
+CAMLprim value unix_accept(value sock)
+{ invalid_argument("accept not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/access.c b/otherlibs/unix/access.c
new file mode 100644
index 0000000000..28c26b820d
--- /dev/null
+++ b/otherlibs/unix/access.c
@@ -0,0 +1,58 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_UNISTD
+# include <unistd.h>
+#else
+# ifndef _WIN32
+# include <sys/file.h>
+# ifndef R_OK
+# define R_OK 4/* test for read permission */
+# define W_OK 2/* test for write permission */
+# define X_OK 1/* test for execute (search) permission */
+# define F_OK 0/* test for presence of file */
+# endif
+# else
+# define R_OK 4/* test for read permission */
+# define W_OK 2/* test for write permission */
+# define X_OK 4/* test for execute permission - not implemented in Win32 */
+# define F_OK 0/* test for presence of file */
+# endif
+#endif
+
+static int access_permission_table[] = {
+ R_OK, W_OK, X_OK, F_OK
+};
+
+CAMLprim value unix_access(value path, value perms)
+{
+ CAMLparam2(path, perms);
+ char * p;
+ int ret, cv_flags;
+
+ cv_flags = convert_flag_list(perms, access_permission_table);
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = access(p, cv_flags);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1)
+ uerror("access", path);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/addrofstr.c b/otherlibs/unix/addrofstr.c
new file mode 100644
index 0000000000..207e1cd990
--- /dev/null
+++ b/otherlibs/unix/addrofstr.c
@@ -0,0 +1,86 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+
+CAMLprim value unix_inet_addr_of_string(value s)
+{
+#if defined(HAS_IPV6)
+#ifdef _WIN32
+ CAMLparam1(s);
+ CAMLlocal1(vres);
+ struct addrinfo hints;
+ struct addrinfo * res;
+ int retcode;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_flags = AI_NUMERICHOST;
+ retcode = getaddrinfo(String_val(s), NULL, &hints, &res);
+ if (retcode != 0) failwith("inet_addr_of_string");
+ switch (res->ai_addr->sa_family) {
+ case AF_INET:
+ {
+ vres =
+ alloc_inet_addr(&((struct sockaddr_in *) res->ai_addr)->sin_addr);
+ break;
+ }
+ case AF_INET6:
+ {
+ vres =
+ alloc_inet6_addr(&((struct sockaddr_in6 *) res->ai_addr)->sin6_addr);
+ break;
+ }
+ default:
+ {
+ freeaddrinfo(res);
+ failwith("inet_addr_of_string");
+ }
+ }
+ freeaddrinfo(res);
+ CAMLreturn (vres);
+#else
+ struct in_addr address;
+ struct in6_addr address6;
+ if (inet_pton(AF_INET, String_val(s), &address) > 0)
+ return alloc_inet_addr(&address);
+ else if (inet_pton(AF_INET6, String_val(s), &address6) > 0)
+ return alloc_inet6_addr(&address6);
+ else
+ failwith("inet_addr_of_string");
+#endif
+#elif defined(HAS_INET_ATON)
+ struct in_addr address;
+ if (inet_aton(String_val(s), &address) == 0)
+ failwith("inet_addr_of_string");
+ return alloc_inet_addr(&address);
+#else
+ struct in_addr address;
+ address.s_addr = inet_addr(String_val(s));
+ if (address.s_addr == (uint32_t) -1) failwith("inet_addr_of_string");
+ return alloc_inet_addr(&address);
+#endif
+}
+
+#else
+
+CAMLprim value unix_inet_addr_of_string(value s)
+{ invalid_argument("inet_addr_of_string not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/alarm.c b/otherlibs/unix/alarm.c
new file mode 100644
index 0000000000..eb92a68293
--- /dev/null
+++ b/otherlibs/unix/alarm.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_alarm(value t)
+{
+ return Val_int(alarm((unsigned int) Long_val(t)));
+}
diff --git a/otherlibs/unix/bind.c b/otherlibs/unix/bind.c
new file mode 100644
index 0000000000..4ea75c21f9
--- /dev/null
+++ b/otherlibs/unix/bind.c
@@ -0,0 +1,39 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+
+CAMLprim value unix_bind(value socket, value address)
+{
+ int ret;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ get_sockaddr(address, &addr, &addr_len);
+ ret = bind(Int_val(socket), &addr.s_gen, addr_len);
+ if (ret == -1) uerror("bind", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_bind(value socket, value address)
+{ invalid_argument("bind not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/chdir.c b/otherlibs/unix/chdir.c
new file mode 100644
index 0000000000..247321119f
--- /dev/null
+++ b/otherlibs/unix/chdir.c
@@ -0,0 +1,31 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_chdir(value path)
+{
+ CAMLparam1(path);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = chdir(p);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("chdir", path);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/chmod.c b/otherlibs/unix/chmod.c
new file mode 100644
index 0000000000..2d3f30fe60
--- /dev/null
+++ b/otherlibs/unix/chmod.c
@@ -0,0 +1,33 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_chmod(value path, value perm)
+{
+ CAMLparam2(path, perm);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = chmod(p, Int_val(perm));
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("chmod", path);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/chown.c b/otherlibs/unix/chown.c
new file mode 100644
index 0000000000..6c9e896a4e
--- /dev/null
+++ b/otherlibs/unix/chown.c
@@ -0,0 +1,31 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_chown(value path, value uid, value gid)
+{
+ CAMLparam1(path);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = chown(p, Int_val(uid), Int_val(gid));
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("chown", path);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/chroot.c b/otherlibs/unix/chroot.c
new file mode 100644
index 0000000000..c30a0da9cd
--- /dev/null
+++ b/otherlibs/unix/chroot.c
@@ -0,0 +1,31 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_chroot(value path)
+{
+ CAMLparam1(path);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = chroot(p);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("chroot", path);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/close.c b/otherlibs/unix/close.c
new file mode 100644
index 0000000000..aff8911f79
--- /dev/null
+++ b/otherlibs/unix/close.c
@@ -0,0 +1,26 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_close(value fd)
+{
+ int ret;
+ caml_enter_blocking_section();
+ ret = close(Int_val(fd));
+ caml_leave_blocking_section();
+ if (ret == -1) uerror("close", Nothing);
+ return Val_unit;
+}
diff --git a/otherlibs/unix/closedir.c b/otherlibs/unix/closedir.c
new file mode 100644
index 0000000000..5e8008d5dc
--- /dev/null
+++ b/otherlibs/unix/closedir.c
@@ -0,0 +1,36 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include <errno.h>
+#include <sys/types.h>
+#ifdef HAS_DIRENT
+#include <dirent.h>
+#else
+#include <sys/dir.h>
+#endif
+
+CAMLprim value unix_closedir(value vd)
+{
+ CAMLparam1(vd);
+ DIR * d = DIR_Val(vd);
+ if (d == (DIR *) NULL) unix_error(EBADF, "closedir", Nothing);
+ caml_enter_blocking_section();
+ closedir(d);
+ caml_leave_blocking_section();
+ DIR_Val(vd) = (DIR *) NULL;
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/connect.c b/otherlibs/unix/connect.c
new file mode 100644
index 0000000000..b4b3e19c33
--- /dev/null
+++ b/otherlibs/unix/connect.c
@@ -0,0 +1,42 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+
+CAMLprim value unix_connect(value socket, value address)
+{
+ int retcode;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ get_sockaddr(address, &addr, &addr_len);
+ enter_blocking_section();
+ retcode = connect(Int_val(socket), &addr.s_gen, addr_len);
+ leave_blocking_section();
+ if (retcode == -1) uerror("connect", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_connect(value socket, value address)
+{ invalid_argument("connect not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/cst2constr.c b/otherlibs/unix/cst2constr.c
new file mode 100644
index 0000000000..87721ce36f
--- /dev/null
+++ b/otherlibs/unix/cst2constr.c
@@ -0,0 +1,24 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/fail.h>
+#include "cst2constr.h"
+
+value cst_to_constr(int n, int *tbl, int size, int deflt)
+{
+ int i;
+ for (i = 0; i < size; i++)
+ if (n == tbl[i]) return Val_int(i);
+ return Val_int(deflt);
+}
diff --git a/otherlibs/unix/cst2constr.h b/otherlibs/unix/cst2constr.h
new file mode 100644
index 0000000000..88985e529a
--- /dev/null
+++ b/otherlibs/unix/cst2constr.h
@@ -0,0 +1,14 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+extern value cst_to_constr(int n, int * tbl, int size, int deflt);
diff --git a/otherlibs/unix/cstringv.c b/otherlibs/unix/cstringv.c
new file mode 100644
index 0000000000..0e61491853
--- /dev/null
+++ b/otherlibs/unix/cstringv.c
@@ -0,0 +1,28 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+
+char ** cstringvect(value arg)
+{
+ char ** res;
+ mlsize_t size, i;
+
+ size = Wosize_val(arg);
+ res = (char **) caml_stat_alloc((size + 1) * sizeof(char *));
+ for (i = 0; i < size; i++) res[i] = String_val(Field(arg, i));
+ res[size] = NULL;
+ return res;
+}
diff --git a/otherlibs/unix/dup.c b/otherlibs/unix/dup.c
new file mode 100644
index 0000000000..c6e9dcf2d0
--- /dev/null
+++ b/otherlibs/unix/dup.c
@@ -0,0 +1,23 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_dup(value fd)
+{
+ int ret;
+ ret = dup(Int_val(fd));
+ if (ret == -1) uerror("dup", Nothing);
+ return Val_int(ret);
+}
diff --git a/otherlibs/unix/dup2.c b/otherlibs/unix/dup2.c
new file mode 100644
index 0000000000..fd9ea3d257
--- /dev/null
+++ b/otherlibs/unix/dup2.c
@@ -0,0 +1,47 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+#ifdef HAS_DUP2
+
+CAMLprim value unix_dup2(value fd1, value fd2)
+{
+ if (dup2(Int_val(fd1), Int_val(fd2)) == -1) uerror("dup2", Nothing);
+ return Val_unit;
+}
+
+#else
+
+static int do_dup2(int fd1, int fd2)
+{
+ int fd;
+ int res;
+
+ fd = dup(fd1);
+ if (fd == -1) return -1;
+ if (fd == fd2) return 0;
+ res = do_dup2(fd1, fd2);
+ close(fd);
+ return res;
+}
+
+CAMLprim value unix_dup2(value fd1, value fd2)
+{
+ close(Int_val(fd2));
+ if (do_dup2(Int_val(fd1), Int_val(fd2)) == -1) uerror("dup2", Nothing);
+ return Val_unit;
+}
+
+#endif
diff --git a/otherlibs/unix/envir.c b/otherlibs/unix/envir.c
new file mode 100644
index 0000000000..366608b634
--- /dev/null
+++ b/otherlibs/unix/envir.c
@@ -0,0 +1,28 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+
+#ifndef _WIN32
+extern char ** environ;
+#endif
+
+CAMLprim value unix_environment(value unit)
+{
+ if (environ != NULL) {
+ return copy_string_array((const char**)environ);
+ } else {
+ return Atom(0);
+ }
+}
diff --git a/otherlibs/unix/errmsg.c b/otherlibs/unix/errmsg.c
new file mode 100644
index 0000000000..0f610e9d81
--- /dev/null
+++ b/otherlibs/unix/errmsg.c
@@ -0,0 +1,26 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+
+extern int error_table[];
+
+CAMLprim value unix_error_message(value err)
+{
+ int errnum;
+ errnum = Is_block(err) ? Int_val(Field(err, 0)) : error_table[Int_val(err)];
+ return copy_string(strerror(errnum));
+}
diff --git a/otherlibs/unix/execv.c b/otherlibs/unix/execv.c
new file mode 100644
index 0000000000..9a77548917
--- /dev/null
+++ b/otherlibs/unix/execv.c
@@ -0,0 +1,29 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+
+extern char ** cstringvect();
+
+CAMLprim value unix_execv(value path, value args)
+{
+ char ** argv;
+ argv = cstringvect(args);
+ (void) execv(String_val(path), argv);
+ stat_free((char *) argv);
+ uerror("execv", path);
+ return Val_unit; /* never reached, but suppress warnings */
+ /* from smart compilers */
+}
diff --git a/otherlibs/unix/execve.c b/otherlibs/unix/execve.c
new file mode 100644
index 0000000000..92171c2d37
--- /dev/null
+++ b/otherlibs/unix/execve.c
@@ -0,0 +1,32 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+
+extern char ** cstringvect();
+
+CAMLprim value unix_execve(value path, value args, value env)
+{
+ char ** argv;
+ char ** envp;
+ argv = cstringvect(args);
+ envp = cstringvect(env);
+ (void) execve(String_val(path), argv, envp);
+ stat_free((char *) argv);
+ stat_free((char *) envp);
+ uerror("execve", path);
+ return Val_unit; /* never reached, but suppress warnings */
+ /* from smart compilers */
+}
diff --git a/otherlibs/unix/execvp.c b/otherlibs/unix/execvp.c
new file mode 100644
index 0000000000..ce6900abf1
--- /dev/null
+++ b/otherlibs/unix/execvp.c
@@ -0,0 +1,48 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+
+extern char ** cstringvect();
+#ifndef _WIN32
+extern char ** environ;
+#endif
+
+CAMLprim value unix_execvp(value path, value args)
+{
+ char ** argv;
+ argv = cstringvect(args);
+ (void) execvp(String_val(path), argv);
+ stat_free((char *) argv);
+ uerror("execvp", path);
+ return Val_unit; /* never reached, but suppress warnings */
+ /* from smart compilers */
+}
+
+CAMLprim value unix_execvpe(value path, value args, value env)
+{
+ char ** argv;
+ char ** saved_environ;
+ argv = cstringvect(args);
+ saved_environ = environ;
+ environ = cstringvect(env);
+ (void) execvp(String_val(path), argv);
+ stat_free((char *) argv);
+ stat_free((char *) environ);
+ environ = saved_environ;
+ uerror("execvp", path);
+ return Val_unit; /* never reached, but suppress warnings */
+ /* from smart compilers */
+}
diff --git a/otherlibs/unix/exit.c b/otherlibs/unix/exit.c
new file mode 100644
index 0000000000..cfc4e16c6a
--- /dev/null
+++ b/otherlibs/unix/exit.c
@@ -0,0 +1,22 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_exit(value n)
+{
+ _exit(Int_val(n));
+ return Val_unit; /* never reached, but suppress warnings */
+ /* from smart compilers */
+}
diff --git a/otherlibs/unix/fchmod.c b/otherlibs/unix/fchmod.c
new file mode 100644
index 0000000000..11578ff261
--- /dev/null
+++ b/otherlibs/unix/fchmod.c
@@ -0,0 +1,38 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_FCHMOD
+
+CAMLprim value unix_fchmod(value fd, value perm)
+{
+ int result;
+ caml_enter_blocking_section();
+ result = fchmod(Int_val(fd), Int_val(perm));
+ caml_leave_blocking_section();
+ if (result == -1) uerror("fchmod", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_fchmod(value fd, value perm)
+{ invalid_argument("fchmod not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/fchown.c b/otherlibs/unix/fchown.c
new file mode 100644
index 0000000000..24872ec8ee
--- /dev/null
+++ b/otherlibs/unix/fchown.c
@@ -0,0 +1,36 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_FCHMOD
+
+CAMLprim value unix_fchown(value fd, value uid, value gid)
+{
+ int result;
+ caml_enter_blocking_section();
+ result = fchown(Int_val(fd), Int_val(uid), Int_val(gid));
+ caml_leave_blocking_section();
+ if (result == -1) uerror("fchown", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_fchown(value fd, value uid, value gid)
+{ invalid_argument("fchown not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/fcntl.c b/otherlibs/unix/fcntl.c
new file mode 100644
index 0000000000..c89e9a6f16
--- /dev/null
+++ b/otherlibs/unix/fcntl.c
@@ -0,0 +1,76 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+
+#ifndef O_NONBLOCK
+#define O_NONBLOCK O_NDELAY
+#endif
+
+CAMLprim value unix_set_nonblock(value fd)
+{
+ int retcode;
+ retcode = fcntl(Int_val(fd), F_GETFL, 0);
+ if (retcode == -1 ||
+ fcntl(Int_val(fd), F_SETFL, retcode | O_NONBLOCK) == -1)
+ uerror("set_nonblock", Nothing);
+ return Val_unit;
+}
+
+CAMLprim value unix_clear_nonblock(value fd)
+{
+ int retcode;
+ retcode = fcntl(Int_val(fd), F_GETFL, 0);
+ if (retcode == -1 ||
+ fcntl(Int_val(fd), F_SETFL, retcode & ~O_NONBLOCK) == -1)
+ uerror("clear_nonblock", Nothing);
+ return Val_unit;
+}
+
+#ifdef FD_CLOEXEC
+
+CAMLprim value unix_set_close_on_exec(value fd)
+{
+ int retcode;
+ retcode = fcntl(Int_val(fd), F_GETFD, 0);
+ if (retcode == -1 ||
+ fcntl(Int_val(fd), F_SETFD, retcode | FD_CLOEXEC) == -1)
+ uerror("set_close_on_exec", Nothing);
+ return Val_unit;
+}
+
+CAMLprim value unix_clear_close_on_exec(value fd)
+{
+ int retcode;
+ retcode = fcntl(Int_val(fd), F_GETFD, 0);
+ if (retcode == -1 ||
+ fcntl(Int_val(fd), F_SETFD, retcode & ~FD_CLOEXEC) == -1)
+ uerror("clear_close_on_exec", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_set_close_on_exec(value fd)
+{ invalid_argument("set_close_on_exec not implemented"); }
+
+CAMLprim value unix_clear_close_on_exec(value fd)
+{ invalid_argument("clear_close_on_exec not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/fork.c b/otherlibs/unix/fork.c
new file mode 100644
index 0000000000..ac0d6772cc
--- /dev/null
+++ b/otherlibs/unix/fork.c
@@ -0,0 +1,28 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/debugger.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_fork(value unit)
+{
+ int ret;
+ ret = fork();
+ if (ret == -1) uerror("fork", Nothing);
+ if (caml_debugger_in_use)
+ if ((caml_debugger_fork_mode && ret == 0) ||
+ (!caml_debugger_fork_mode && ret != 0))
+ caml_debugger_cleanup_fork();
+ return Val_int(ret);
+}
diff --git a/otherlibs/unix/ftruncate.c b/otherlibs/unix/ftruncate.c
new file mode 100644
index 0000000000..08a4a775ed
--- /dev/null
+++ b/otherlibs/unix/ftruncate.c
@@ -0,0 +1,55 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <sys/types.h>
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include <caml/io.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+
+#ifdef HAS_TRUNCATE
+
+CAMLprim value unix_ftruncate(value fd, value len)
+{
+ int result;
+ caml_enter_blocking_section();
+ result = ftruncate(Int_val(fd), Long_val(len));
+ caml_leave_blocking_section();
+ if (result == -1) uerror("ftruncate", Nothing);
+ return Val_unit;
+}
+
+CAMLprim value unix_ftruncate_64(value fd, value len)
+{
+ int result;
+ file_offset ofs = File_offset_val(len);
+ caml_enter_blocking_section();
+ result = ftruncate(Int_val(fd), ofs);
+ caml_leave_blocking_section();
+ if (result == -1) uerror("ftruncate", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_ftruncate(value fd, value len)
+{ invalid_argument("ftruncate not implemented"); }
+
+CAMLprim value unix_ftruncate_64(value fd, value len)
+{ invalid_argument("ftruncate not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/getaddrinfo.c b/otherlibs/unix/getaddrinfo.c
new file mode 100644
index 0000000000..2817934331
--- /dev/null
+++ b/otherlibs/unix/getaddrinfo.c
@@ -0,0 +1,130 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2004 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/misc.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include "cst2constr.h"
+
+#if defined(HAS_SOCKETS) && defined(HAS_IPV6)
+
+#include "socketaddr.h"
+#ifndef _WIN32
+#include <sys/types.h>
+#include <netdb.h>
+#endif
+
+extern int socket_domain_table[]; /* from socket.c */
+extern int socket_type_table[]; /* from socket.c */
+
+static value convert_addrinfo(struct addrinfo * a)
+{
+ CAMLparam0();
+ CAMLlocal3(vres,vaddr,vcanonname);
+ union sock_addr_union sa;
+ socklen_param_type len;
+
+ len = a->ai_addrlen;
+ if (len > sizeof(sa)) len = sizeof(sa);
+ memcpy(&sa.s_gen, a->ai_addr, len);
+ vaddr = alloc_sockaddr(&sa, len, -1);
+ vcanonname = copy_string(a->ai_canonname == NULL ? "" : a->ai_canonname);
+ vres = alloc_small(5, 0);
+ Field(vres, 0) = cst_to_constr(a->ai_family, socket_domain_table, 3, 0);
+ Field(vres, 1) = cst_to_constr(a->ai_socktype, socket_type_table, 4, 0);
+ Field(vres, 2) = Val_int(a->ai_protocol);
+ Field(vres, 3) = vaddr;
+ Field(vres, 4) = vcanonname;
+ CAMLreturn(vres);
+}
+
+CAMLprim value unix_getaddrinfo(value vnode, value vserv, value vopts)
+{
+ CAMLparam3(vnode, vserv, vopts);
+ CAMLlocal3(vres, v, e);
+ char * node, * serv;
+ struct addrinfo hints;
+ struct addrinfo * res, * r;
+ int retcode;
+
+ /* Extract "node" parameter */
+ if (caml_string_length(vnode) == 0) {
+ node = NULL;
+ } else {
+ node = caml_strdup(String_val(vnode));
+ }
+ /* Extract "service" parameter */
+ if (caml_string_length(vserv) == 0) {
+ serv = NULL;
+ } else {
+ serv = caml_strdup(String_val(vserv));
+ }
+ /* Parse options, set hints */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ for (/*nothing*/; Is_block(vopts); vopts = Field(vopts, 1)) {
+ v = Field(vopts, 0);
+ if (Is_block(v))
+ switch (Tag_val(v)) {
+ case 0: /* AI_FAMILY of socket_domain */
+ hints.ai_family = socket_domain_table[Int_val(Field(v, 0))];
+ break;
+ case 1: /* AI_SOCKTYPE of socket_type */
+ hints.ai_socktype = socket_type_table[Int_val(Field(v, 0))];
+ break;
+ case 2: /* AI_PROTOCOL of int */
+ hints.ai_protocol = Int_val(Field(v, 0));
+ break;
+ }
+ else
+ switch (Int_val(v)) {
+ case 0: /* AI_NUMERICHOST */
+ hints.ai_flags |= AI_NUMERICHOST; break;
+ case 1: /* AI_CANONNAME */
+ hints.ai_flags |= AI_CANONNAME; break;
+ case 2: /* AI_PASSIVE */
+ hints.ai_flags |= AI_PASSIVE; break;
+ }
+ }
+ /* Do the call */
+ enter_blocking_section();
+ retcode = getaddrinfo(node, serv, &hints, &res);
+ leave_blocking_section();
+ if (node != NULL) stat_free(node);
+ if (serv != NULL) stat_free(serv);
+ /* Convert result */
+ vres = Val_int(0);
+ if (retcode == 0) {
+ for (r = res; r != NULL; r = r->ai_next) {
+ e = convert_addrinfo(r);
+ v = alloc_small(2, 0);
+ Field(v, 0) = e;
+ Field(v, 1) = vres;
+ vres = v;
+ }
+ freeaddrinfo(res);
+ }
+ CAMLreturn(vres);
+}
+
+#else
+
+CAMLprim value unix_getaddrinfo(value vnode, value vserv, value vopts)
+{ invalid_argument("getaddrinfo not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/getcwd.c b/otherlibs/unix/getcwd.c
new file mode 100644
index 0000000000..043c96b6f6
--- /dev/null
+++ b/otherlibs/unix/getcwd.c
@@ -0,0 +1,56 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+
+#if !defined (_WIN32) && !macintosh
+#include <sys/param.h>
+#endif
+
+#ifndef PATH_MAX
+#ifdef MAXPATHLEN
+#define PATH_MAX MAXPATHLEN
+#else
+#define PATH_MAX 512
+#endif
+#endif
+
+#ifdef HAS_GETCWD
+
+CAMLprim value unix_getcwd(value unit)
+{
+ char buff[PATH_MAX];
+ if (getcwd(buff, sizeof(buff)) == 0) uerror("getcwd", Nothing);
+ return copy_string(buff);
+}
+
+#else
+#ifdef HAS_GETWD
+
+CAMLprim value unix_getcwd(value unit)
+{
+ char buff[PATH_MAX];
+ if (getwd(buff) == 0) uerror("getcwd", copy_string(buff));
+ return copy_string(buff);
+}
+
+#else
+
+CAMLprim value unix_getcwd(value unit)
+{ invalid_argument("getcwd not implemented"); }
+
+#endif
+#endif
diff --git a/otherlibs/unix/getegid.c b/otherlibs/unix/getegid.c
new file mode 100644
index 0000000000..c0ab2b398a
--- /dev/null
+++ b/otherlibs/unix/getegid.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_getegid(value unit)
+{
+ return Val_int(getegid());
+}
diff --git a/otherlibs/unix/geteuid.c b/otherlibs/unix/geteuid.c
new file mode 100644
index 0000000000..095d3fe16c
--- /dev/null
+++ b/otherlibs/unix/geteuid.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_geteuid(value unit)
+{
+ return Val_int(geteuid());
+}
diff --git a/otherlibs/unix/getgid.c b/otherlibs/unix/getgid.c
new file mode 100644
index 0000000000..8a4991a532
--- /dev/null
+++ b/otherlibs/unix/getgid.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_getgid(value unit)
+{
+ return Val_int(getgid());
+}
diff --git a/otherlibs/unix/getgr.c b/otherlibs/unix/getgr.c
new file mode 100644
index 0000000000..14338ccffc
--- /dev/null
+++ b/otherlibs/unix/getgr.c
@@ -0,0 +1,54 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/fail.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+#include <stdio.h>
+#include <grp.h>
+
+static value alloc_group_entry(struct group *entry)
+{
+ value res;
+ value name = Val_unit, pass = Val_unit, mem = Val_unit;
+
+ Begin_roots3 (name, pass, mem);
+ name = copy_string(entry->gr_name);
+ pass = copy_string(entry->gr_passwd);
+ mem = copy_string_array((const char**)entry->gr_mem);
+ res = alloc_small(4, 0);
+ Field(res,0) = name;
+ Field(res,1) = pass;
+ Field(res,2) = Val_int(entry->gr_gid);
+ Field(res,3) = mem;
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_getgrnam(value name)
+{
+ struct group * entry;
+ entry = getgrnam(String_val(name));
+ if (entry == NULL) raise_not_found();
+ return alloc_group_entry(entry);
+}
+
+CAMLprim value unix_getgrgid(value gid)
+{
+ struct group * entry;
+ entry = getgrgid(Int_val(gid));
+ if (entry == NULL) raise_not_found();
+ return alloc_group_entry(entry);
+}
diff --git a/otherlibs/unix/getgroups.c b/otherlibs/unix/getgroups.c
new file mode 100644
index 0000000000..84cd45406a
--- /dev/null
+++ b/otherlibs/unix/getgroups.c
@@ -0,0 +1,47 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+
+#ifdef HAS_GETGROUPS
+
+#include <sys/types.h>
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#include <limits.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_getgroups(value unit)
+{
+ gid_t gidset[NGROUPS_MAX];
+ int n;
+ value res;
+ int i;
+
+ n = getgroups(NGROUPS_MAX, gidset);
+ if (n == -1) uerror("getgroups", Nothing);
+ res = alloc_tuple(n);
+ for (i = 0; i < n; i++)
+ Field(res, i) = Val_int(gidset[i]);
+ return res;
+}
+
+#else
+
+CAMLprim value unix_getgroups(value unit)
+{ invalid_argument("getgroups not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/gethost.c b/otherlibs/unix/gethost.c
new file mode 100644
index 0000000000..0f04fb907a
--- /dev/null
+++ b/otherlibs/unix/gethost.c
@@ -0,0 +1,180 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+#ifndef _WIN32
+#include <sys/types.h>
+#include <netdb.h>
+#endif
+
+#define NETDB_BUFFER_SIZE 10000
+
+#ifdef _WIN32
+#define GETHOSTBYADDR_IS_REENTRANT 1
+#define GETHOSTBYNAME_IS_REENTRANT 1
+#endif
+
+static int entry_h_length;
+
+extern int socket_domain_table[];
+
+static value alloc_one_addr(char const *a)
+{
+ struct in_addr addr;
+#ifdef HAS_IPV6
+ struct in6_addr addr6;
+ if (entry_h_length == 16) {
+ memmove(&addr6, a, 16);
+ return alloc_inet6_addr(&addr6);
+ }
+#endif
+ memmove (&addr, a, 4);
+ return alloc_inet_addr(&addr);
+}
+
+static value alloc_host_entry(struct hostent *entry)
+{
+ value res;
+ value name = Val_unit, aliases = Val_unit;
+ value addr_list = Val_unit, adr = Val_unit;
+
+ Begin_roots4 (name, aliases, addr_list, adr);
+ name = copy_string((char *)(entry->h_name));
+ /* PR#4043: protect against buggy implementations of gethostbyname()
+ that return a NULL pointer in h_aliases */
+ if (entry->h_aliases)
+ aliases = copy_string_array((const char**)entry->h_aliases);
+ else
+ aliases = Atom(0);
+ entry_h_length = entry->h_length;
+#ifdef h_addr
+ addr_list = alloc_array(alloc_one_addr, (const char**)entry->h_addr_list);
+#else
+ adr = alloc_one_addr(entry->h_addr);
+ addr_list = alloc_small(1, 0);
+ Field(addr_list, 0) = adr;
+#endif
+ res = alloc_small(4, 0);
+ Field(res, 0) = name;
+ Field(res, 1) = aliases;
+ switch (entry->h_addrtype) {
+ case PF_UNIX: Field(res, 2) = Val_int(0); break;
+ case PF_INET: Field(res, 2) = Val_int(1); break;
+ default: /*PF_INET6 */ Field(res, 2) = Val_int(2); break;
+ }
+ Field(res, 3) = addr_list;
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_gethostbyaddr(value a)
+{
+ struct in_addr adr = GET_INET_ADDR(a);
+ struct hostent * hp;
+#if HAS_GETHOSTBYADDR_R == 7
+ struct hostent h;
+ char buffer[NETDB_BUFFER_SIZE];
+ int h_errnop;
+ enter_blocking_section();
+ hp = gethostbyaddr_r((char *) &adr, 4, AF_INET,
+ &h, buffer, sizeof(buffer), &h_errnop);
+ leave_blocking_section();
+#elif HAS_GETHOSTBYADDR_R == 8
+ struct hostent h;
+ char buffer[NETDB_BUFFER_SIZE];
+ int h_errnop, rc;
+ enter_blocking_section();
+ rc = gethostbyaddr_r((char *) &adr, 4, AF_INET,
+ &h, buffer, sizeof(buffer), &hp, &h_errnop);
+ leave_blocking_section();
+ if (rc != 0) hp = NULL;
+#else
+#ifdef GETHOSTBYADDR_IS_REENTRANT
+ enter_blocking_section();
+#endif
+ hp = gethostbyaddr((char *) &adr, 4, AF_INET);
+#ifdef GETHOSTBYADDR_IS_REENTRANT
+ leave_blocking_section();
+#endif
+#endif
+ if (hp == (struct hostent *) NULL) raise_not_found();
+ return alloc_host_entry(hp);
+}
+
+CAMLprim value unix_gethostbyname(value name)
+{
+ struct hostent * hp;
+ char * hostname;
+#if HAS_GETHOSTBYNAME_R
+ struct hostent h;
+ char buffer[NETDB_BUFFER_SIZE];
+ int h_errno;
+#endif
+
+#if HAS_GETHOSTBYNAME_R || GETHOSTBYNAME_IS_REENTRANT
+ hostname = caml_strdup(String_val(name));
+#else
+ hostname = String_val(name);
+#endif
+
+#if HAS_GETHOSTBYNAME_R == 5
+ {
+ enter_blocking_section();
+ hp = gethostbyname_r(hostname, &h, buffer, sizeof(buffer), &h_errno);
+ leave_blocking_section();
+ }
+#elif HAS_GETHOSTBYNAME_R == 6
+ {
+ int rc;
+ enter_blocking_section();
+ rc = gethostbyname_r(hostname, &h, buffer, sizeof(buffer), &hp, &h_errno);
+ leave_blocking_section();
+ if (rc != 0) hp = NULL;
+ }
+#else
+#ifdef GETHOSTBYNAME_IS_REENTRANT
+ enter_blocking_section();
+#endif
+ hp = gethostbyname(hostname);
+#ifdef GETHOSTBYNAME_IS_REENTRANT
+ leave_blocking_section();
+#endif
+#endif
+
+#if HAS_GETHOSTBYNAME_R || GETHOSTBYNAME_IS_REENTRANT
+ stat_free(hostname);
+#endif
+
+ if (hp == (struct hostent *) NULL) raise_not_found();
+ return alloc_host_entry(hp);
+}
+
+#else
+
+CAMLprim value unix_gethostbyaddr(value name)
+{ invalid_argument("gethostbyaddr not implemented"); }
+
+CAMLprim value unix_gethostbyname(value name)
+{ invalid_argument("gethostbyname not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/gethostname.c b/otherlibs/unix/gethostname.c
new file mode 100644
index 0000000000..a3aba5748b
--- /dev/null
+++ b/otherlibs/unix/gethostname.c
@@ -0,0 +1,54 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#ifndef _WIN32
+#include <sys/param.h>
+#endif
+#include "unixsupport.h"
+
+#ifdef HAS_GETHOSTNAME
+
+#ifndef MAXHOSTNAMELEN
+#define MAXHOSTNAMELEN 256
+#endif
+
+CAMLprim value unix_gethostname(value unit)
+{
+ char name[MAXHOSTNAMELEN];
+ gethostname(name, MAXHOSTNAMELEN);
+ name[MAXHOSTNAMELEN-1] = 0;
+ return copy_string(name);
+}
+
+#else
+#ifdef HAS_UNAME
+
+#include <sys/utsname.h>
+
+CAMLprim value unix_gethostname(value unit)
+{
+ struct utsname un;
+ uname(&un);
+ return copy_string(un.nodename);
+}
+
+#else
+
+CAMLprim value unix_gethostname(value unit)
+{ invalid_argument("gethostname not implemented"); }
+
+#endif
+#endif
diff --git a/otherlibs/unix/getlogin.c b/otherlibs/unix/getlogin.c
new file mode 100644
index 0000000000..7f40e442f0
--- /dev/null
+++ b/otherlibs/unix/getlogin.c
@@ -0,0 +1,27 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+#include <errno.h>
+
+extern char * getlogin(void);
+
+CAMLprim value unix_getlogin(value unit)
+{
+ char * name;
+ name = getlogin();
+ if (name == NULL) unix_error(ENOENT, "getlogin", Nothing);
+ return copy_string(name);
+}
diff --git a/otherlibs/unix/getnameinfo.c b/otherlibs/unix/getnameinfo.c
new file mode 100644
index 0000000000..d4663957ba
--- /dev/null
+++ b/otherlibs/unix/getnameinfo.c
@@ -0,0 +1,65 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2004 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#if defined(HAS_SOCKETS) && defined(HAS_IPV6)
+
+#include "socketaddr.h"
+#ifndef _WIN32
+#include <sys/types.h>
+#include <netdb.h>
+#endif
+
+static int getnameinfo_flag_table[] = {
+ NI_NOFQDN, NI_NUMERICHOST, NI_NAMEREQD, NI_NUMERICSERV, NI_DGRAM
+};
+
+CAMLprim value unix_getnameinfo(value vaddr, value vopts)
+{
+ CAMLparam0();
+ CAMLlocal3(vhost, vserv, vres);
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+ char host[4096];
+ char serv[1024];
+ int opts, retcode;
+
+ get_sockaddr(vaddr, &addr, &addr_len);
+ opts = convert_flag_list(vopts, getnameinfo_flag_table);
+ enter_blocking_section();
+ retcode =
+ getnameinfo((const struct sockaddr *) &addr.s_gen, addr_len,
+ host, sizeof(host), serv, sizeof(serv), opts);
+ leave_blocking_section();
+ if (retcode != 0) raise_not_found(); /* TODO: detailed error reporting? */
+ vhost = copy_string(host);
+ vserv = copy_string(serv);
+ vres = alloc_small(2, 0);
+ Field(vres, 0) = vhost;
+ Field(vres, 1) = vserv;
+ CAMLreturn(vres);
+}
+
+#else
+
+CAMLprim value unix_getnameinfo(value vaddr, value vopts)
+{ invalid_argument("getnameinfo not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/getpeername.c b/otherlibs/unix/getpeername.c
new file mode 100644
index 0000000000..183b210d3a
--- /dev/null
+++ b/otherlibs/unix/getpeername.c
@@ -0,0 +1,39 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+
+CAMLprim value unix_getpeername(value sock)
+{
+ int retcode;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ addr_len = sizeof(addr);
+ retcode = getpeername(Int_val(sock), &addr.s_gen, &addr_len);
+ if (retcode == -1) uerror("getpeername", Nothing);
+ return alloc_sockaddr(&addr, addr_len, -1);
+}
+
+#else
+
+CAMLprim value unix_getpeername(value sock)
+{ invalid_argument("getpeername not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/getpid.c b/otherlibs/unix/getpid.c
new file mode 100644
index 0000000000..4cf46e4c07
--- /dev/null
+++ b/otherlibs/unix/getpid.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_getpid(value unit)
+{
+ return Val_int(getpid());
+}
diff --git a/otherlibs/unix/getppid.c b/otherlibs/unix/getppid.c
new file mode 100644
index 0000000000..8c30a77a1b
--- /dev/null
+++ b/otherlibs/unix/getppid.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_getppid(value unit)
+{
+ return Val_int(getppid());
+}
diff --git a/otherlibs/unix/getproto.c b/otherlibs/unix/getproto.c
new file mode 100644
index 0000000000..b89cbba411
--- /dev/null
+++ b/otherlibs/unix/getproto.c
@@ -0,0 +1,66 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#ifndef _WIN32
+#include <netdb.h>
+#endif
+
+static value alloc_proto_entry(struct protoent *entry)
+{
+ value res;
+ value name = Val_unit, aliases = Val_unit;
+
+ Begin_roots2 (name, aliases);
+ name = copy_string(entry->p_name);
+ aliases = copy_string_array((const char**)entry->p_aliases);
+ res = alloc_small(3, 0);
+ Field(res,0) = name;
+ Field(res,1) = aliases;
+ Field(res,2) = Val_int(entry->p_proto);
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_getprotobyname(value name)
+{
+ struct protoent * entry;
+ entry = getprotobyname(String_val(name));
+ if (entry == (struct protoent *) NULL) raise_not_found();
+ return alloc_proto_entry(entry);
+}
+
+CAMLprim value unix_getprotobynumber(value proto)
+{
+ struct protoent * entry;
+ entry = getprotobynumber(Int_val(proto));
+ if (entry == (struct protoent *) NULL) raise_not_found();
+ return alloc_proto_entry(entry);
+}
+
+#else
+
+CAMLprim value unix_getprotobynumber(value proto)
+{ invalid_argument("getprotobynumber not implemented"); }
+
+CAMLprim value unix_getprotobyname(value name)
+{ invalid_argument("getprotobyname not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/getpw.c b/otherlibs/unix/getpw.c
new file mode 100644
index 0000000000..82fb4d8fdf
--- /dev/null
+++ b/otherlibs/unix/getpw.c
@@ -0,0 +1,63 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+#include <pwd.h>
+
+static value alloc_passwd_entry(struct passwd *entry)
+{
+ value res;
+ value name = Val_unit, passwd = Val_unit, gecos = Val_unit;
+ value dir = Val_unit, shell = Val_unit;
+
+ Begin_roots5 (name, passwd, gecos, dir, shell);
+ name = copy_string(entry->pw_name);
+ passwd = copy_string(entry->pw_passwd);
+#if !defined(__BEOS__) && !defined(__ANDROID__)
+ gecos = copy_string(entry->pw_gecos);
+#else
+ gecos = copy_string("");
+#endif
+ dir = copy_string(entry->pw_dir);
+ shell = copy_string(entry->pw_shell);
+ res = alloc_small(7, 0);
+ Field(res,0) = name;
+ Field(res,1) = passwd;
+ Field(res,2) = Val_int(entry->pw_uid);
+ Field(res,3) = Val_int(entry->pw_gid);
+ Field(res,4) = gecos;
+ Field(res,5) = dir;
+ Field(res,6) = shell;
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_getpwnam(value name)
+{
+ struct passwd * entry;
+ entry = getpwnam(String_val(name));
+ if (entry == (struct passwd *) NULL) raise_not_found();
+ return alloc_passwd_entry(entry);
+}
+
+CAMLprim value unix_getpwuid(value uid)
+{
+ struct passwd * entry;
+ entry = getpwuid(Int_val(uid));
+ if (entry == (struct passwd *) NULL) raise_not_found();
+ return alloc_passwd_entry(entry);
+}
diff --git a/otherlibs/unix/getserv.c b/otherlibs/unix/getserv.c
new file mode 100644
index 0000000000..deb5f14729
--- /dev/null
+++ b/otherlibs/unix/getserv.c
@@ -0,0 +1,72 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include <sys/types.h>
+
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#endif
+
+static value alloc_service_entry(struct servent *entry)
+{
+ value res;
+ value name = Val_unit, aliases = Val_unit, proto = Val_unit;
+
+ Begin_roots3 (name, aliases, proto);
+ name = copy_string(entry->s_name);
+ aliases = copy_string_array((const char**)entry->s_aliases);
+ proto = copy_string(entry->s_proto);
+ res = alloc_small(4, 0);
+ Field(res,0) = name;
+ Field(res,1) = aliases;
+ Field(res,2) = Val_int(ntohs(entry->s_port));
+ Field(res,3) = proto;
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_getservbyname(value name, value proto)
+{
+ struct servent * entry;
+ entry = getservbyname(String_val(name), String_val(proto));
+ if (entry == (struct servent *) NULL) raise_not_found();
+ return alloc_service_entry(entry);
+}
+
+CAMLprim value unix_getservbyport(value port, value proto)
+{
+ struct servent * entry;
+ entry = getservbyport(htons(Int_val(port)), String_val(proto));
+ if (entry == (struct servent *) NULL) raise_not_found();
+ return alloc_service_entry(entry);
+}
+
+#else
+
+CAMLprim value unix_getservbyport(value port, value proto)
+{ invalid_argument("getservbyport not implemented"); }
+
+CAMLprim value unix_getservbyname(value name, value proto)
+{ invalid_argument("getservbyname not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/getsockname.c b/otherlibs/unix/getsockname.c
new file mode 100644
index 0000000000..b28cfd1454
--- /dev/null
+++ b/otherlibs/unix/getsockname.c
@@ -0,0 +1,39 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+
+CAMLprim value unix_getsockname(value sock)
+{
+ int retcode;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ addr_len = sizeof(addr);
+ retcode = getsockname(Int_val(sock), &addr.s_gen, &addr_len);
+ if (retcode == -1) uerror("getsockname", Nothing);
+ return alloc_sockaddr(&addr, addr_len, -1);
+}
+
+#else
+
+CAMLprim value unix_getsockname(value sock)
+{ invalid_argument("getsockname not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/gettimeofday.c b/otherlibs/unix/gettimeofday.c
new file mode 100644
index 0000000000..9cbfbeaa07
--- /dev/null
+++ b/otherlibs/unix/gettimeofday.c
@@ -0,0 +1,36 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+
+#ifdef HAS_GETTIMEOFDAY
+
+#include <sys/types.h>
+#include <sys/time.h>
+
+CAMLprim value unix_gettimeofday(value unit)
+{
+ struct timeval tp;
+ if (gettimeofday(&tp, NULL) == -1) uerror("gettimeofday", Nothing);
+ return copy_double((double) tp.tv_sec + (double) tp.tv_usec / 1e6);
+}
+
+#else
+
+CAMLprim value unix_gettimeofday(value unit)
+{ invalid_argument("gettimeofday not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/getuid.c b/otherlibs/unix/getuid.c
new file mode 100644
index 0000000000..7d0ce399b9
--- /dev/null
+++ b/otherlibs/unix/getuid.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_getuid(value unit)
+{
+ return Val_int(getuid());
+}
diff --git a/otherlibs/unix/gmtime.c b/otherlibs/unix/gmtime.c
new file mode 100644
index 0000000000..566f174f85
--- /dev/null
+++ b/otherlibs/unix/gmtime.c
@@ -0,0 +1,93 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+#include <time.h>
+#include <errno.h>
+
+static value alloc_tm(struct tm *tm)
+{
+ value res;
+ res = alloc_small(9, 0);
+ Field(res,0) = Val_int(tm->tm_sec);
+ Field(res,1) = Val_int(tm->tm_min);
+ Field(res,2) = Val_int(tm->tm_hour);
+ Field(res,3) = Val_int(tm->tm_mday);
+ Field(res,4) = Val_int(tm->tm_mon);
+ Field(res,5) = Val_int(tm->tm_year);
+ Field(res,6) = Val_int(tm->tm_wday);
+ Field(res,7) = Val_int(tm->tm_yday);
+ Field(res,8) = tm->tm_isdst ? Val_true : Val_false;
+ return res;
+}
+
+CAMLprim value unix_gmtime(value t)
+{
+ time_t clock;
+ struct tm * tm;
+ clock = (time_t) Double_val(t);
+ tm = gmtime(&clock);
+ if (tm == NULL) unix_error(EINVAL, "gmtime", Nothing);
+ return alloc_tm(tm);
+}
+
+CAMLprim value unix_localtime(value t)
+{
+ time_t clock;
+ struct tm * tm;
+ clock = (time_t) Double_val(t);
+ tm = localtime(&clock);
+ if (tm == NULL) unix_error(EINVAL, "localtime", Nothing);
+ return alloc_tm(tm);
+}
+
+#ifdef HAS_MKTIME
+
+CAMLprim value unix_mktime(value t)
+{
+ struct tm tm;
+ time_t clock;
+ value res;
+ value tmval = Val_unit, clkval = Val_unit;
+
+ Begin_roots2(tmval, clkval);
+ tm.tm_sec = Int_val(Field(t, 0));
+ tm.tm_min = Int_val(Field(t, 1));
+ tm.tm_hour = Int_val(Field(t, 2));
+ tm.tm_mday = Int_val(Field(t, 3));
+ tm.tm_mon = Int_val(Field(t, 4));
+ tm.tm_year = Int_val(Field(t, 5));
+ tm.tm_wday = Int_val(Field(t, 6));
+ tm.tm_yday = Int_val(Field(t, 7));
+ tm.tm_isdst = -1; /* tm.tm_isdst = Bool_val(Field(t, 8)); */
+ clock = mktime(&tm);
+ if (clock == (time_t) -1) unix_error(ERANGE, "mktime", Nothing);
+ tmval = alloc_tm(&tm);
+ clkval = copy_double((double) clock);
+ res = alloc_small(2, 0);
+ Field(res, 0) = clkval;
+ Field(res, 1) = tmval;
+ End_roots ();
+ return res;
+}
+
+#else
+
+CAMLprim value unix_mktime(value t)
+{ invalid_argument("mktime not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/initgroups.c b/otherlibs/unix/initgroups.c
new file mode 100644
index 0000000000..ca3ed4c99e
--- /dev/null
+++ b/otherlibs/unix/initgroups.c
@@ -0,0 +1,41 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Stephane Glondu <steph@glondu.net> */
+/* */
+/* Copyright 2009 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+
+#ifdef HAS_INITGROUPS
+
+#include <sys/types.h>
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#include <limits.h>
+#include <grp.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_initgroups(value user, value group)
+{
+ if (initgroups(String_val(user), Int_val(group)) == -1) {
+ uerror("initgroups", Nothing);
+ }
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_initgroups(value user, value group)
+{ invalid_argument("initgroups not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/isatty.c b/otherlibs/unix/isatty.c
new file mode 100644
index 0000000000..935c39d45e
--- /dev/null
+++ b/otherlibs/unix/isatty.c
@@ -0,0 +1,20 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2006 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_isatty(value fd)
+{
+ return (Val_bool(isatty(Int_val(fd))));
+}
diff --git a/otherlibs/unix/itimer.c b/otherlibs/unix/itimer.c
new file mode 100644
index 0000000000..f1950264c3
--- /dev/null
+++ b/otherlibs/unix/itimer.c
@@ -0,0 +1,73 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SETITIMER
+
+#include <math.h>
+#include <sys/time.h>
+
+static void unix_set_timeval(struct timeval * tv, double d)
+{
+ double integr, frac;
+ frac = modf(d, &integr);
+ /* Round time up so that if d is small but not 0, we end up with
+ a non-0 timeval. */
+ tv->tv_sec = integr;
+ tv->tv_usec = ceil(1e6 * frac);
+ if (tv->tv_usec >= 1000000) { tv->tv_sec++; tv->tv_usec = 0; }
+}
+
+static value unix_convert_itimer(struct itimerval *tp)
+{
+#define Get_timeval(tv) (double) tv.tv_sec + (double) tv.tv_usec / 1e6
+ value res = alloc_small(Double_wosize * 2, Double_array_tag);
+ Store_double_field(res, 0, Get_timeval(tp->it_interval));
+ Store_double_field(res, 1, Get_timeval(tp->it_value));
+ return res;
+#undef Get_timeval
+}
+
+static int itimers[3] = { ITIMER_REAL, ITIMER_VIRTUAL, ITIMER_PROF };
+
+CAMLprim value unix_setitimer(value which, value newval)
+{
+ struct itimerval new, old;
+ unix_set_timeval(&new.it_interval, Double_field(newval, 0));
+ unix_set_timeval(&new.it_value, Double_field(newval, 1));
+ if (setitimer(itimers[Int_val(which)], &new, &old) == -1)
+ uerror("setitimer", Nothing);
+ return unix_convert_itimer(&old);
+}
+
+CAMLprim value unix_getitimer(value which)
+{
+ struct itimerval val;
+ if (getitimer(itimers[Int_val(which)], &val) == -1)
+ uerror("getitimer", Nothing);
+ return unix_convert_itimer(&val);
+}
+
+#else
+
+CAMLprim value unix_setitimer(value which, value newval)
+{ invalid_argument("setitimer not implemented"); }
+CAMLprim value unix_getitimer(value which)
+{ invalid_argument("getitimer not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/kill.c b/otherlibs/unix/kill.c
new file mode 100644
index 0000000000..c0f74d48d4
--- /dev/null
+++ b/otherlibs/unix/kill.c
@@ -0,0 +1,27 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+#include <signal.h>
+#include <caml/signals.h>
+
+CAMLprim value unix_kill(value pid, value signal)
+{
+ int sig;
+ sig = convert_signal_number(Int_val(signal));
+ if (kill(Int_val(pid), sig) == -1)
+ uerror("kill", Nothing);
+ return Val_unit;
+}
diff --git a/otherlibs/unix/libunix.clib b/otherlibs/unix/libunix.clib
new file mode 100644
index 0000000000..b866ea06de
--- /dev/null
+++ b/otherlibs/unix/libunix.clib
@@ -0,0 +1,16 @@
+accept.o access.o addrofstr.o alarm.o bind.o chdir.o chmod.o
+chown.o chroot.o close.o closedir.o connect.o cst2constr.o cstringv.o
+dup.o dup2.o envir.o errmsg.o execv.o execve.o execvp.o exit.o
+fchmod.o fchown.o fcntl.o fork.o ftruncate.o
+getaddrinfo.o getcwd.o getegid.o geteuid.o getgid.o
+getgr.o getgroups.o gethost.o gethostname.o getlogin.o
+getnameinfo.o getpeername.o getpid.o getppid.o getproto.o getpw.o
+gettimeofday.o getserv.o getsockname.o getuid.o gmtime.o
+initgroups.o isatty.o itimer.o kill.o link.o listen.o lockf.o lseek.o
+mkdir.o mkfifo.o nice.o open.o opendir.o pipe.o putenv.o read.o
+readdir.o readlink.o rename.o rewinddir.o rmdir.o select.o sendrecv.o
+setgid.o setgroups.o setsid.o setuid.o shutdown.o signals.o
+sleep.o socket.o socketaddr.o
+socketpair.o sockopt.o stat.o strofaddr.o symlink.o termios.o
+time.o times.o truncate.o umask.o unixsupport.o unlink.o
+utimes.o wait.o write.o
diff --git a/otherlibs/unix/link.c b/otherlibs/unix/link.c
new file mode 100644
index 0000000000..0ec42f5fe9
--- /dev/null
+++ b/otherlibs/unix/link.c
@@ -0,0 +1,34 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_link(value path1, value path2)
+{
+ CAMLparam2(path1, path2);
+ char * p1;
+ char * p2;
+ int ret;
+ p1 = caml_strdup(String_val(path1));
+ p2 = caml_strdup(String_val(path2));
+ caml_enter_blocking_section();
+ ret = link(p1, p2);
+ caml_leave_blocking_section();
+ caml_stat_free(p1);
+ caml_stat_free(p2);
+ if (ret == -1) uerror("link", path2);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/listen.c b/otherlibs/unix/listen.c
new file mode 100644
index 0000000000..38efc9fde5
--- /dev/null
+++ b/otherlibs/unix/listen.c
@@ -0,0 +1,33 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include <sys/socket.h>
+
+CAMLprim value unix_listen(value sock, value backlog)
+{
+ if (listen(Int_val(sock), Int_val(backlog)) == -1) uerror("listen", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_listen(value sock, value backlog)
+{ invalid_argument("listen not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/lockf.c b/otherlibs/unix/lockf.c
new file mode 100644
index 0000000000..aeaf451313
--- /dev/null
+++ b/otherlibs/unix/lockf.c
@@ -0,0 +1,114 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#if defined(F_GETLK) && defined(F_SETLK) && defined(F_SETLKW)
+
+CAMLprim value unix_lockf(value fd, value cmd, value span)
+{
+ struct flock l;
+ int ret;
+ int fildes;
+ long size;
+
+ fildes = Int_val(fd);
+ size = Long_val(span);
+ l.l_whence = 1;
+ if (size < 0) {
+ l.l_start = size;
+ l.l_len = -size;
+ } else {
+ l.l_start = 0L;
+ l.l_len = size;
+ }
+ switch (Int_val(cmd)) {
+ case 0: /* F_ULOCK */
+ l.l_type = F_UNLCK;
+ ret = fcntl(fildes, F_SETLK, &l);
+ break;
+ case 1: /* F_LOCK */
+ l.l_type = F_WRLCK;
+ enter_blocking_section();
+ ret = fcntl(fildes, F_SETLKW, &l);
+ leave_blocking_section();
+ break;
+ case 2: /* F_TLOCK */
+ l.l_type = F_WRLCK;
+ ret = fcntl(fildes, F_SETLK, &l);
+ break;
+ case 3: /* F_TEST */
+ l.l_type = F_WRLCK;
+ ret = fcntl(fildes, F_GETLK, &l);
+ if (ret != -1) {
+ if (l.l_type == F_UNLCK)
+ ret = 0;
+ else {
+ errno = EACCES;
+ ret = -1;
+ }
+ }
+ break;
+ case 4: /* F_RLOCK */
+ l.l_type = F_RDLCK;
+ enter_blocking_section();
+ ret = fcntl(fildes, F_SETLKW, &l);
+ leave_blocking_section();
+ break;
+ case 5: /* F_TRLOCK */
+ l.l_type = F_RDLCK;
+ ret = fcntl(fildes, F_SETLK, &l);
+ break;
+ default:
+ errno = EINVAL;
+ ret = -1;
+ }
+ if (ret == -1) uerror("lockf", Nothing);
+ return Val_unit;
+}
+
+#else
+
+#ifdef HAS_LOCKF
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#else
+#define F_ULOCK 0
+#define F_LOCK 1
+#define F_TLOCK 2
+#define F_TEST 3
+#endif
+
+static int lock_command_table[] = {
+ F_ULOCK, F_LOCK, F_TLOCK, F_TEST, F_LOCK, F_TLOCK
+};
+
+CAMLprim value unix_lockf(value fd, value cmd, value span)
+{
+ if (lockf(Int_val(fd), lock_command_table[Int_val(cmd)], Long_val(span))
+ == -1) uerror("lockf", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_lockf(value fd, value cmd, value span)
+{ invalid_argument("lockf not implemented"); }
+
+#endif
+#endif
diff --git a/otherlibs/unix/lseek.c b/otherlibs/unix/lseek.c
new file mode 100644
index 0000000000..5a7b7770af
--- /dev/null
+++ b/otherlibs/unix/lseek.c
@@ -0,0 +1,62 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <sys/types.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/io.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#else
+#define SEEK_SET 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+#endif
+
+#ifndef EOVERFLOW
+#define EOVERFLOW ERANGE
+#endif
+
+static int seek_command_table[] = {
+ SEEK_SET, SEEK_CUR, SEEK_END
+};
+
+CAMLprim value unix_lseek(value fd, value ofs, value cmd)
+{
+ file_offset ret;
+ caml_enter_blocking_section();
+ ret = lseek(Int_val(fd), Long_val(ofs),
+ seek_command_table[Int_val(cmd)]);
+ caml_leave_blocking_section();
+ if (ret == -1) uerror("lseek", Nothing);
+ if (ret > Max_long) unix_error(EOVERFLOW, "lseek", Nothing);
+ return Val_long(ret);
+}
+
+CAMLprim value unix_lseek_64(value fd, value ofs, value cmd)
+{
+ file_offset ret;
+ /* [ofs] is an Int64, which is stored as a custom block; we must therefore
+ extract its contents before dropping the runtime lock, or it might be
+ moved. */
+ file_offset ofs_c = File_offset_val(ofs);
+ caml_enter_blocking_section();
+ ret = lseek(Int_val(fd), ofs_c, seek_command_table[Int_val(cmd)]);
+ caml_leave_blocking_section();
+ if (ret == -1) uerror("lseek", Nothing);
+ return Val_file_offset(ret);
+}
diff --git a/otherlibs/unix/mkdir.c b/otherlibs/unix/mkdir.c
new file mode 100644
index 0000000000..6b9c76e6f0
--- /dev/null
+++ b/otherlibs/unix/mkdir.c
@@ -0,0 +1,33 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_mkdir(value path, value perm)
+{
+ CAMLparam2(path, perm);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = mkdir(p, Int_val(perm));
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("mkdir", path);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/mkfifo.c b/otherlibs/unix/mkfifo.c
new file mode 100644
index 0000000000..074813856d
--- /dev/null
+++ b/otherlibs/unix/mkfifo.c
@@ -0,0 +1,69 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_MKFIFO
+
+CAMLprim value unix_mkfifo(value path, value mode)
+{
+ CAMLparam2(path, mode);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = mkfifo(p, Int_val(mode));
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1)
+ uerror("mkfifo", path);
+ CAMLreturn(Val_unit);
+}
+
+#else
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifdef S_IFIFO
+
+CAMLprim value unix_mkfifo(value path, value mode)
+{
+ CAMLparam2(path, mode);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = mknod(p, (Int_val(mode) & 07777) | S_IFIFO, 0);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1)
+ uerror("mkfifo", path);
+ CAMLreturn(Val_unit);
+}
+
+#else
+
+CAMLprim value unix_mkfifo(value path, value mode)
+{
+ invalid_argument("mkfifo not implemented");
+}
+
+#endif
+#endif
diff --git a/otherlibs/unix/nanosecond_stat.h b/otherlibs/unix/nanosecond_stat.h
new file mode 100644
index 0000000000..c1a648ef12
--- /dev/null
+++ b/otherlibs/unix/nanosecond_stat.h
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Jeremie Dimino, Jane Street Group, LLC */
+/* */
+/* Copyright 2015 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* This file is used by the configure test program nanosecond_stat.c
+ and stat.c in this directory */
+
+#if HAS_NANOSECOND_STAT == 1
+# define NSEC(buf, field) buf->st_##field##tim.tv_nsec
+#elif HAS_NANOSECOND_STAT == 2
+# define NSEC(buf, field) buf->st_##field##timespec.tv_nsec
+#elif HAS_NANOSECOND_STAT == 3
+# define NSEC(buf, field) buf->st_##field##timensec
+#else
+# define NSEC(buf, field) 0
+#endif
diff --git a/otherlibs/unix/nice.c b/otherlibs/unix/nice.c
new file mode 100644
index 0000000000..e8f4f2b0a7
--- /dev/null
+++ b/otherlibs/unix/nice.c
@@ -0,0 +1,32 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include <errno.h>
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+
+CAMLprim value unix_nice(value incr)
+{
+ int ret;
+ errno = 0;
+#ifdef HAS_NICE
+ ret = nice(Int_val(incr));
+#else
+ ret = 0;
+#endif
+ if (ret == -1 && errno != 0) uerror("nice", Nothing);
+ return Val_int(ret);
+}
diff --git a/otherlibs/unix/open.c b/otherlibs/unix/open.c
new file mode 100644
index 0000000000..1bad2c5b91
--- /dev/null
+++ b/otherlibs/unix/open.c
@@ -0,0 +1,82 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/misc.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include <string.h>
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+
+#ifndef O_NONBLOCK
+#define O_NONBLOCK O_NDELAY
+#endif
+#ifndef O_DSYNC
+#define O_DSYNC 0
+#endif
+#ifndef O_SYNC
+#define O_SYNC 0
+#endif
+#ifndef O_RSYNC
+#define O_RSYNC 0
+#endif
+#ifndef O_CLOEXEC
+#define NEED_CLOEXEC_EMULATION
+#define O_CLOEXEC 0
+#endif
+
+static int open_flag_table[14] = {
+ O_RDONLY, O_WRONLY, O_RDWR, O_NONBLOCK, O_APPEND, O_CREAT, O_TRUNC, O_EXCL,
+ O_NOCTTY, O_DSYNC, O_SYNC, O_RSYNC,
+ 0, /* O_SHARE_DELETE, Windows-only */
+ O_CLOEXEC
+};
+
+#ifdef NEED_CLOEXEC_EMULATION
+static int open_cloexec_table[14] = {
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0,
+ 1
+};
+#endif
+
+CAMLprim value unix_open(value path, value flags, value perm)
+{
+ CAMLparam3(path, flags, perm);
+ int fd, cv_flags;
+ char * p;
+
+ cv_flags = convert_flag_list(flags, open_flag_table);
+ p = caml_strdup(String_val(path));
+ /* open on a named FIFO can block (PR#1533) */
+ enter_blocking_section();
+ fd = open(p, cv_flags, Int_val(perm));
+ leave_blocking_section();
+ stat_free(p);
+ if (fd == -1) uerror("open", path);
+#if defined(NEED_CLOEXEC_EMULATION) && defined(FD_CLOEXEC)
+ if (convert_flag_list(flags, open_cloexec_table) != 0) {
+ int flags = fcntl(fd, F_GETFD, 0);
+ if (flags == -1 ||
+ fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
+ uerror("open", path);
+ }
+#endif
+ CAMLreturn (Val_int(fd));
+}
diff --git a/otherlibs/unix/opendir.c b/otherlibs/unix/opendir.c
new file mode 100644
index 0000000000..bdf031b35f
--- /dev/null
+++ b/otherlibs/unix/opendir.c
@@ -0,0 +1,42 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include <sys/types.h>
+#ifdef HAS_DIRENT
+#include <dirent.h>
+#else
+#include <sys/dir.h>
+#endif
+
+CAMLprim value unix_opendir(value path)
+{
+ CAMLparam1(path);
+ DIR * d;
+ value res;
+ char * p;
+
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ d = opendir(p);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (d == (DIR *) NULL) uerror("opendir", path);
+ res = alloc_small(1, Abstract_tag);
+ DIR_Val(res) = d;
+ CAMLreturn(res);
+}
diff --git a/otherlibs/unix/pipe.c b/otherlibs/unix/pipe.c
new file mode 100644
index 0000000000..5f8f23dadf
--- /dev/null
+++ b/otherlibs/unix/pipe.c
@@ -0,0 +1,27 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_pipe(value unit)
+{
+ int fd[2];
+ value res;
+ if (pipe(fd) == -1) uerror("pipe", Nothing);
+ res = alloc_small(2, 0);
+ Field(res, 0) = Val_int(fd[0]);
+ Field(res, 1) = Val_int(fd[1]);
+ return res;
+}
diff --git a/otherlibs/unix/putenv.c b/otherlibs/unix/putenv.c
new file mode 100644
index 0000000000..ccb8f1abef
--- /dev/null
+++ b/otherlibs/unix/putenv.c
@@ -0,0 +1,47 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1998 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/mlvalues.h>
+
+#include "unixsupport.h"
+
+#ifdef HAS_PUTENV
+
+CAMLprim value unix_putenv(value name, value val)
+{
+ mlsize_t namelen = string_length(name);
+ mlsize_t vallen = string_length(val);
+ char * s = (char *) caml_stat_alloc(namelen + 1 + vallen + 1);
+
+ memmove (s, String_val(name), namelen);
+ s[namelen] = '=';
+ memmove (s + namelen + 1, String_val(val), vallen);
+ s[namelen + 1 + vallen] = 0;
+ if (putenv(s) == -1) {
+ caml_stat_free(s);
+ uerror("putenv", name);
+ }
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_putenv(value name, value val)
+{ invalid_argument("putenv not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/read.c b/otherlibs/unix/read.c
new file mode 100644
index 0000000000..14305d37cf
--- /dev/null
+++ b/otherlibs/unix/read.c
@@ -0,0 +1,36 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_read(value fd, value buf, value ofs, value len)
+{
+ long numbytes;
+ int ret;
+ char iobuf[UNIX_BUFFER_SIZE];
+
+ Begin_root (buf);
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ enter_blocking_section();
+ ret = read(Int_val(fd), iobuf, (int) numbytes);
+ leave_blocking_section();
+ if (ret == -1) uerror("read", Nothing);
+ memmove (&Byte(buf, Long_val(ofs)), iobuf, ret);
+ End_roots();
+ return Val_int(ret);
+}
diff --git a/otherlibs/unix/readdir.c b/otherlibs/unix/readdir.c
new file mode 100644
index 0000000000..4c309268ac
--- /dev/null
+++ b/otherlibs/unix/readdir.c
@@ -0,0 +1,40 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/fail.h>
+#include <caml/alloc.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include <errno.h>
+#include <sys/types.h>
+#ifdef HAS_DIRENT
+#include <dirent.h>
+typedef struct dirent directory_entry;
+#else
+#include <sys/dir.h>
+typedef struct direct directory_entry;
+#endif
+
+CAMLprim value unix_readdir(value vd)
+{
+ DIR * d;
+ directory_entry * e;
+ d = DIR_Val(vd);
+ if (d == (DIR *) NULL) unix_error(EBADF, "readdir", Nothing);
+ caml_enter_blocking_section();
+ e = readdir((DIR *) d);
+ caml_leave_blocking_section();
+ if (e == (directory_entry *) NULL) raise_end_of_file();
+ return copy_string(e->d_name);
+}
diff --git a/otherlibs/unix/readlink.c b/otherlibs/unix/readlink.c
new file mode 100644
index 0000000000..836718d1dc
--- /dev/null
+++ b/otherlibs/unix/readlink.c
@@ -0,0 +1,54 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/signals.h>
+
+#ifdef HAS_SYMLINK
+
+#include <sys/param.h>
+#include "unixsupport.h"
+
+#ifndef PATH_MAX
+#ifdef MAXPATHLEN
+#define PATH_MAX MAXPATHLEN
+#else
+#define PATH_MAX 512
+#endif
+#endif
+
+CAMLprim value unix_readlink(value path)
+{
+ CAMLparam1(path);
+ char buffer[PATH_MAX];
+ int len;
+ char * p;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ len = readlink(p, buffer, sizeof(buffer) - 1);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (len == -1) uerror("readlink", path);
+ buffer[len] = '\0';
+ CAMLreturn(copy_string(buffer));
+}
+
+#else
+
+CAMLprim value unix_readlink(value path)
+{ invalid_argument("readlink not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/rename.c b/otherlibs/unix/rename.c
new file mode 100644
index 0000000000..78e0846cd2
--- /dev/null
+++ b/otherlibs/unix/rename.c
@@ -0,0 +1,36 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_rename(value path1, value path2)
+{
+ CAMLparam2(path1, path2);
+ char * p1;
+ char * p2;
+ int ret;
+ p1 = caml_strdup(String_val(path1));
+ p2 = caml_strdup(String_val(path2));
+ caml_enter_blocking_section();
+ ret = rename(p1, p2);
+ caml_leave_blocking_section();
+ caml_stat_free(p2);
+ caml_stat_free(p1);
+ if (ret == -1)
+ uerror("rename", path1);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/rewinddir.c b/otherlibs/unix/rewinddir.c
new file mode 100644
index 0000000000..c37713231e
--- /dev/null
+++ b/otherlibs/unix/rewinddir.c
@@ -0,0 +1,40 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include <errno.h>
+#include <sys/types.h>
+#ifdef HAS_DIRENT
+#include <dirent.h>
+#else
+#include <sys/dir.h>
+#endif
+
+#ifdef HAS_REWINDDIR
+
+CAMLprim value unix_rewinddir(value vd)
+{
+ DIR * d = DIR_Val(vd);
+ if (d == (DIR *) NULL) unix_error(EBADF, "rewinddir", Nothing);
+ rewinddir(d);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_rewinddir(value d)
+{ invalid_argument("rewinddir not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/rmdir.c b/otherlibs/unix/rmdir.c
new file mode 100644
index 0000000000..20359ce6cb
--- /dev/null
+++ b/otherlibs/unix/rmdir.c
@@ -0,0 +1,31 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_rmdir(value path)
+{
+ CAMLparam1(path);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = rmdir(p);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("rmdir", path);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/select.c b/otherlibs/unix/select.c
new file mode 100644
index 0000000000..23c480249d
--- /dev/null
+++ b/otherlibs/unix/select.c
@@ -0,0 +1,112 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SELECT
+
+#include <sys/types.h>
+#include <sys/time.h>
+#ifdef HAS_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+static int fdlist_to_fdset(value fdlist, fd_set *fdset, int *maxfd)
+{
+ value l;
+ FD_ZERO(fdset);
+ for (l = fdlist; l != Val_int(0); l = Field(l, 1)) {
+ long fd = Long_val(Field(l, 0));
+ /* PR#5563: harden against bad fds */
+ if (fd < 0 || fd >= FD_SETSIZE) return -1;
+ FD_SET((int) fd, fdset);
+ if (fd > *maxfd) *maxfd = fd;
+ }
+ return 0;
+}
+
+static value fdset_to_fdlist(value fdlist, fd_set *fdset)
+{
+ value l;
+ value res = Val_int(0);
+
+ Begin_roots2(l, res);
+ for (l = fdlist; l != Val_int(0); l = Field(l, 1)) {
+ int fd = Int_val(Field(l, 0));
+ if (FD_ISSET(fd, fdset)) {
+ value newres = alloc_small(2, 0);
+ Field(newres, 0) = Val_int(fd);
+ Field(newres, 1) = res;
+ res = newres;
+ }
+ }
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_select(value readfds, value writefds, value exceptfds,
+ value timeout)
+{
+ fd_set read, write, except;
+ int maxfd;
+ double tm;
+ struct timeval tv;
+ struct timeval * tvp;
+ int retcode;
+ value res;
+
+ Begin_roots3 (readfds, writefds, exceptfds);
+ maxfd = -1;
+ retcode = fdlist_to_fdset(readfds, &read, &maxfd);
+ retcode += fdlist_to_fdset(writefds, &write, &maxfd);
+ retcode += fdlist_to_fdset(exceptfds, &except, &maxfd);
+ /* PR#5563: if a bad fd was encountered, report EINVAL error */
+ if (retcode != 0) unix_error(EINVAL, "select", Nothing);
+ tm = Double_val(timeout);
+ if (tm < 0.0)
+ tvp = (struct timeval *) NULL;
+ else {
+ tv.tv_sec = (int) tm;
+ tv.tv_usec = (int) (1e6 * (tm - tv.tv_sec));
+ tvp = &tv;
+ }
+ enter_blocking_section();
+ retcode = select(maxfd + 1, &read, &write, &except, tvp);
+ leave_blocking_section();
+ if (retcode == -1) uerror("select", Nothing);
+ readfds = fdset_to_fdlist(readfds, &read);
+ writefds = fdset_to_fdlist(writefds, &write);
+ exceptfds = fdset_to_fdlist(exceptfds, &except);
+ res = alloc_small(3, 0);
+ Field(res, 0) = readfds;
+ Field(res, 1) = writefds;
+ Field(res, 2) = exceptfds;
+ End_roots();
+ return res;
+}
+
+#else
+
+CAMLprim value unix_select(value readfds, value writefds, value exceptfds,
+ value timeout)
+{ invalid_argument("select not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/sendrecv.c b/otherlibs/unix/sendrecv.c
new file mode 100644
index 0000000000..7d251a4375
--- /dev/null
+++ b/otherlibs/unix/sendrecv.c
@@ -0,0 +1,146 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+#include "socketaddr.h"
+
+static int msg_flag_table[] = {
+ MSG_OOB, MSG_DONTROUTE, MSG_PEEK
+};
+
+CAMLprim value unix_recv(value sock, value buff, value ofs, value len,
+ value flags)
+{
+ int ret, cv_flags;
+ long numbytes;
+ char iobuf[UNIX_BUFFER_SIZE];
+
+ cv_flags = convert_flag_list(flags, msg_flag_table);
+ Begin_root (buff);
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ enter_blocking_section();
+ ret = recv(Int_val(sock), iobuf, (int) numbytes, cv_flags);
+ leave_blocking_section();
+ if (ret == -1) uerror("recv", Nothing);
+ memmove (&Byte(buff, Long_val(ofs)), iobuf, ret);
+ End_roots();
+ return Val_int(ret);
+}
+
+CAMLprim value unix_recvfrom(value sock, value buff, value ofs, value len,
+ value flags)
+{
+ int ret, cv_flags;
+ long numbytes;
+ char iobuf[UNIX_BUFFER_SIZE];
+ value res;
+ value adr = Val_unit;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ cv_flags = convert_flag_list(flags, msg_flag_table);
+ Begin_roots2 (buff, adr);
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ addr_len = sizeof(addr);
+ enter_blocking_section();
+ ret = recvfrom(Int_val(sock), iobuf, (int) numbytes, cv_flags,
+ &addr.s_gen, &addr_len);
+ leave_blocking_section();
+ if (ret == -1) uerror("recvfrom", Nothing);
+ memmove (&Byte(buff, Long_val(ofs)), iobuf, ret);
+ adr = alloc_sockaddr(&addr, addr_len, -1);
+ res = alloc_small(2, 0);
+ Field(res, 0) = Val_int(ret);
+ Field(res, 1) = adr;
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_send(value sock, value buff, value ofs, value len,
+ value flags)
+{
+ int ret, cv_flags;
+ long numbytes;
+ char iobuf[UNIX_BUFFER_SIZE];
+
+ cv_flags = convert_flag_list(flags, msg_flag_table);
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ memmove (iobuf, &Byte(buff, Long_val(ofs)), numbytes);
+ enter_blocking_section();
+ ret = send(Int_val(sock), iobuf, (int) numbytes, cv_flags);
+ leave_blocking_section();
+ if (ret == -1) uerror("send", Nothing);
+ return Val_int(ret);
+}
+
+CAMLprim value unix_sendto_native(value sock, value buff, value ofs, value len,
+ value flags, value dest)
+{
+ int ret, cv_flags;
+ long numbytes;
+ char iobuf[UNIX_BUFFER_SIZE];
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ cv_flags = convert_flag_list(flags, msg_flag_table);
+ get_sockaddr(dest, &addr, &addr_len);
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ memmove (iobuf, &Byte(buff, Long_val(ofs)), numbytes);
+ enter_blocking_section();
+ ret = sendto(Int_val(sock), iobuf, (int) numbytes, cv_flags,
+ &addr.s_gen, addr_len);
+ leave_blocking_section();
+ if (ret == -1) uerror("sendto", Nothing);
+ return Val_int(ret);
+}
+
+CAMLprim value unix_sendto(value *argv, int argc)
+{
+ return unix_sendto_native
+ (argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
+}
+
+#else
+
+CAMLprim value unix_recv(value sock, value buff, value ofs, value len,
+ value flags)
+{ invalid_argument("recv not implemented"); }
+
+CAMLprim value unix_recvfrom(value sock, value buff, value ofs, value len,
+ value flags)
+{ invalid_argument("recvfrom not implemented"); }
+
+CAMLprim value unix_send(value sock, value buff, value ofs, value len,
+ value flags)
+{ invalid_argument("send not implemented"); }
+
+CAMLprim value unix_sendto_native(value sock, value buff, value ofs, value len,
+ value flags, value dest)
+{ invalid_argument("sendto not implemented"); }
+
+CAMLprim value unix_sendto(value *argv, int argc)
+{ invalid_argument("sendto not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/setgid.c b/otherlibs/unix/setgid.c
new file mode 100644
index 0000000000..b7204745b7
--- /dev/null
+++ b/otherlibs/unix/setgid.c
@@ -0,0 +1,21 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_setgid(value gid)
+{
+ if (setgid(Int_val(gid)) == -1) uerror("setgid", Nothing);
+ return Val_unit;
+}
diff --git a/otherlibs/unix/setgroups.c b/otherlibs/unix/setgroups.c
new file mode 100644
index 0000000000..7284b735cb
--- /dev/null
+++ b/otherlibs/unix/setgroups.c
@@ -0,0 +1,51 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Stephane Glondu <steph@glondu.net> */
+/* */
+/* Copyright 2009 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+
+#ifdef HAS_SETGROUPS
+
+#include <sys/types.h>
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#include <limits.h>
+#include <grp.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_setgroups(value groups)
+{
+ gid_t * gidset;
+ mlsize_t size, i;
+ int n;
+
+ size = Wosize_val(groups);
+ gidset = (gid_t *) caml_stat_alloc(size * sizeof(gid_t));
+ for (i = 0; i < size; i++) gidset[i] = Int_val(Field(groups, i));
+
+ n = setgroups(size, gidset);
+
+ stat_free(gidset);
+ if (n == -1) uerror("setgroups", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_setgroups(value groups)
+{ invalid_argument("setgroups not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/setsid.c b/otherlibs/unix/setsid.c
new file mode 100644
index 0000000000..92814eba59
--- /dev/null
+++ b/otherlibs/unix/setsid.c
@@ -0,0 +1,29 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1997 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+
+CAMLprim value unix_setsid(value unit)
+{
+#ifdef HAS_SETSID
+ return Val_int(setsid());
+#else
+ invalid_argument("setsid not implemented");
+ return Val_unit;
+#endif
+}
diff --git a/otherlibs/unix/setuid.c b/otherlibs/unix/setuid.c
new file mode 100644
index 0000000000..c8a9c622a6
--- /dev/null
+++ b/otherlibs/unix/setuid.c
@@ -0,0 +1,21 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_setuid(value uid)
+{
+ if (setuid(Int_val(uid)) == -1) uerror("setuid", Nothing);
+ return Val_unit;
+}
diff --git a/otherlibs/unix/shutdown.c b/otherlibs/unix/shutdown.c
new file mode 100644
index 0000000000..1ceafd6ec8
--- /dev/null
+++ b/otherlibs/unix/shutdown.c
@@ -0,0 +1,38 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include <sys/socket.h>
+
+static int shutdown_command_table[] = {
+ 0, 1, 2
+};
+
+CAMLprim value unix_shutdown(value sock, value cmd)
+{
+ if (shutdown(Int_val(sock), shutdown_command_table[Int_val(cmd)]) == -1)
+ uerror("shutdown", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_shutdown(value sock, value cmd)
+{ invalid_argument("shutdown not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/signals.c b/otherlibs/unix/signals.c
new file mode 100644
index 0000000000..d30a70db82
--- /dev/null
+++ b/otherlibs/unix/signals.c
@@ -0,0 +1,104 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1998 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <signal.h>
+
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifndef NSIG
+#define NSIG 64
+#endif
+
+#ifdef POSIX_SIGNALS
+
+static void decode_sigset(value vset, sigset_t * set)
+{
+ sigemptyset(set);
+ while (vset != Val_int(0)) {
+ int sig = caml_convert_signal_number(Int_val(Field(vset, 0)));
+ sigaddset(set, sig);
+ vset = Field(vset, 1);
+ }
+}
+
+static value encode_sigset(sigset_t * set)
+{
+ value res = Val_int(0);
+ int i;
+
+ Begin_root(res)
+ for (i = 1; i < NSIG; i++)
+ if (sigismember(set, i) > 0) {
+ value newcons = alloc_small(2, 0);
+ Field(newcons, 0) = Val_int(caml_rev_convert_signal_number(i));
+ Field(newcons, 1) = res;
+ res = newcons;
+ }
+ End_roots();
+ return res;
+}
+
+static int sigprocmask_cmd[3] = { SIG_SETMASK, SIG_BLOCK, SIG_UNBLOCK };
+
+CAMLprim value unix_sigprocmask(value vaction, value vset)
+{
+ int how;
+ sigset_t set, oldset;
+ int retcode;
+
+ how = sigprocmask_cmd[Int_val(vaction)];
+ decode_sigset(vset, &set);
+ enter_blocking_section();
+ retcode = sigprocmask(how, &set, &oldset);
+ leave_blocking_section();
+ if (retcode == -1) uerror("sigprocmask", Nothing);
+ return encode_sigset(&oldset);
+}
+
+CAMLprim value unix_sigpending(value unit)
+{
+ sigset_t pending;
+ if (sigpending(&pending) == -1) uerror("sigpending", Nothing);
+ return encode_sigset(&pending);
+}
+
+CAMLprim value unix_sigsuspend(value vset)
+{
+ sigset_t set;
+ int retcode;
+ decode_sigset(vset, &set);
+ enter_blocking_section();
+ retcode = sigsuspend(&set);
+ leave_blocking_section();
+ if (retcode == -1 && errno != EINTR) uerror("sigsuspend", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_sigprocmask(value vaction, value vset)
+{ invalid_argument("Unix.sigprocmask not available"); }
+
+CAMLprim value unix_sigpending(value unit)
+{ invalid_argument("Unix.sigpending not available"); }
+
+CAMLprim value unix_sigsuspend(value vset)
+{ invalid_argument("Unix.sigsuspend not available"); }
+
+#endif
diff --git a/otherlibs/unix/sleep.c b/otherlibs/unix/sleep.c
new file mode 100644
index 0000000000..a39c5f829d
--- /dev/null
+++ b/otherlibs/unix/sleep.c
@@ -0,0 +1,24 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_sleep(value t)
+{
+ enter_blocking_section();
+ sleep(Int_val(t));
+ leave_blocking_section();
+ return Val_unit;
+}
diff --git a/otherlibs/unix/socket.c b/otherlibs/unix/socket.c
new file mode 100644
index 0000000000..9cf3ed3a8b
--- /dev/null
+++ b/otherlibs/unix/socket.c
@@ -0,0 +1,54 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+int socket_domain_table[] = {
+ PF_UNIX, PF_INET,
+#if defined(HAS_IPV6)
+ PF_INET6
+#elif defined(PF_UNDEF)
+ PF_UNDEF
+#else
+ 0
+#endif
+};
+
+int socket_type_table[] = {
+ SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET
+};
+
+CAMLprim value unix_socket(value domain, value type, value proto)
+{
+ int retcode;
+ retcode = socket(socket_domain_table[Int_val(domain)],
+ socket_type_table[Int_val(type)],
+ Int_val(proto));
+ if (retcode == -1) uerror("socket", Nothing);
+ return Val_int(retcode);
+
+}
+
+#else
+
+CAMLprim value unix_socket(value domain, value type, value proto)
+{ invalid_argument("socket not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/socketaddr.c b/otherlibs/unix/socketaddr.c
new file mode 100644
index 0000000000..2eca8fc5b8
--- /dev/null
+++ b/otherlibs/unix/socketaddr.c
@@ -0,0 +1,143 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <errno.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+
+#ifdef _WIN32
+#undef EAFNOSUPPORT
+#define EAFNOSUPPORT WSAEAFNOSUPPORT
+#endif
+
+CAMLexport value alloc_inet_addr(struct in_addr * a)
+{
+ value res;
+ /* Use a string rather than an abstract block so that it can be
+ marshaled safely. Remember that a is in network byte order,
+ hence is marshaled in an endian-independent manner. */
+ res = alloc_string(4);
+ memcpy(String_val(res), a, 4);
+ return res;
+}
+
+#ifdef HAS_IPV6
+
+CAMLexport value alloc_inet6_addr(struct in6_addr * a)
+{
+ value res;
+ res = alloc_string(16);
+ memcpy(String_val(res), a, 16);
+ return res;
+}
+
+#endif
+
+void get_sockaddr(value mladr,
+ union sock_addr_union * adr /*out*/,
+ socklen_param_type * adr_len /*out*/)
+{
+ switch(Tag_val(mladr)) {
+#ifndef _WIN32
+ case 0: /* ADDR_UNIX */
+ { value path;
+ mlsize_t len;
+ path = Field(mladr, 0);
+ len = string_length(path);
+ adr->s_unix.sun_family = AF_UNIX;
+ if (len >= sizeof(adr->s_unix.sun_path)) {
+ unix_error(ENAMETOOLONG, "", path);
+ }
+ memmove (adr->s_unix.sun_path, String_val(path), len + 1);
+ *adr_len =
+ ((char *)&(adr->s_unix.sun_path) - (char *)&(adr->s_unix))
+ + len;
+ break;
+ }
+#endif
+ case 1: /* ADDR_INET */
+#ifdef HAS_IPV6
+ if (string_length(Field(mladr, 0)) == 16) {
+ memset(&adr->s_inet6, 0, sizeof(struct sockaddr_in6));
+ adr->s_inet6.sin6_family = AF_INET6;
+ adr->s_inet6.sin6_addr = GET_INET6_ADDR(Field(mladr, 0));
+ adr->s_inet6.sin6_port = htons(Int_val(Field(mladr, 1)));
+#ifdef SIN6_LEN
+ adr->s_inet6.sin6_len = sizeof(struct sockaddr_in6);
+#endif
+ *adr_len = sizeof(struct sockaddr_in6);
+ break;
+ }
+#endif
+ memset(&adr->s_inet, 0, sizeof(struct sockaddr_in));
+ adr->s_inet.sin_family = AF_INET;
+ adr->s_inet.sin_addr = GET_INET_ADDR(Field(mladr, 0));
+ adr->s_inet.sin_port = htons(Int_val(Field(mladr, 1)));
+#ifdef SIN6_LEN
+ adr->s_inet.sin_len = sizeof(struct sockaddr_in);
+#endif
+ *adr_len = sizeof(struct sockaddr_in);
+ break;
+ }
+}
+
+value alloc_sockaddr(union sock_addr_union * adr /*in*/,
+ socklen_param_type adr_len, int close_on_error)
+{
+ value res;
+ switch(adr->s_gen.sa_family) {
+#ifndef _WIN32
+ case AF_UNIX:
+ { value n = copy_string(adr->s_unix.sun_path);
+ Begin_root (n);
+ res = alloc_small(1, 0);
+ Field(res,0) = n;
+ End_roots();
+ break;
+ }
+#endif
+ case AF_INET:
+ { value a = alloc_inet_addr(&adr->s_inet.sin_addr);
+ Begin_root (a);
+ res = alloc_small(2, 1);
+ Field(res,0) = a;
+ Field(res,1) = Val_int(ntohs(adr->s_inet.sin_port));
+ End_roots();
+ break;
+ }
+#ifdef HAS_IPV6
+ case AF_INET6:
+ { value a = alloc_inet6_addr(&adr->s_inet6.sin6_addr);
+ Begin_root (a);
+ res = alloc_small(2, 1);
+ Field(res,0) = a;
+ Field(res,1) = Val_int(ntohs(adr->s_inet6.sin6_port));
+ End_roots();
+ break;
+ }
+#endif
+ default:
+ if (close_on_error != -1) close (close_on_error);
+ unix_error(EAFNOSUPPORT, "", Nothing);
+ }
+ return res;
+}
+
+#endif
diff --git a/otherlibs/unix/socketaddr.h b/otherlibs/unix/socketaddr.h
new file mode 100644
index 0000000000..0077daeaad
--- /dev/null
+++ b/otherlibs/unix/socketaddr.h
@@ -0,0 +1,60 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_SOCKETADDR_H
+#define CAML_SOCKETADDR_H
+
+#include "caml/misc.h"
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+union sock_addr_union {
+ struct sockaddr s_gen;
+ struct sockaddr_un s_unix;
+ struct sockaddr_in s_inet;
+#ifdef HAS_IPV6
+ struct sockaddr_in6 s_inet6;
+#endif
+};
+
+#ifdef HAS_SOCKLEN_T
+typedef socklen_t socklen_param_type;
+#else
+typedef int socklen_param_type;
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern void get_sockaddr (value mladdr,
+ union sock_addr_union * addr /*out*/,
+ socklen_param_type * addr_len /*out*/);
+CAMLexport value alloc_sockaddr (union sock_addr_union * addr /*in*/,
+ socklen_param_type addr_len, int close_on_error);
+CAMLexport value alloc_inet_addr (struct in_addr * inaddr);
+#define GET_INET_ADDR(v) (*((struct in_addr *) (v)))
+
+#ifdef HAS_IPV6
+CAMLexport value alloc_inet6_addr (struct in6_addr * inaddr);
+#define GET_INET6_ADDR(v) (*((struct in6_addr *) (v)))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_SOCKETADDR_H */
diff --git a/otherlibs/unix/socketpair.c b/otherlibs/unix/socketpair.c
new file mode 100644
index 0000000000..4f85f9a6b7
--- /dev/null
+++ b/otherlibs/unix/socketpair.c
@@ -0,0 +1,44 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include <sys/socket.h>
+
+extern int socket_domain_table[], socket_type_table[];
+
+CAMLprim value unix_socketpair(value domain, value type, value proto)
+{
+ int sv[2];
+ value res;
+ if (socketpair(socket_domain_table[Int_val(domain)],
+ socket_type_table[Int_val(type)],
+ Int_val(proto), sv) == -1)
+ uerror("socketpair", Nothing);
+ res = alloc_small(2, 0);
+ Field(res,0) = Val_int(sv[0]);
+ Field(res,1) = Val_int(sv[1]);
+ return res;
+}
+
+#else
+
+CAMLprim value unix_socketpair(value domain, value type, value proto)
+{ invalid_argument("socketpair not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/sockopt.c b/otherlibs/unix/sockopt.c
new file mode 100644
index 0000000000..8137e42c97
--- /dev/null
+++ b/otherlibs/unix/sockopt.c
@@ -0,0 +1,299 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include <errno.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/tcp.h>
+
+#include "socketaddr.h"
+
+#ifndef SO_DEBUG
+#define SO_DEBUG (-1)
+#endif
+#ifndef SO_BROADCAST
+#define SO_BROADCAST (-1)
+#endif
+#ifndef SO_REUSEADDR
+#define SO_REUSEADDR (-1)
+#endif
+#ifndef SO_KEEPALIVE
+#define SO_KEEPALIVE (-1)
+#endif
+#ifndef SO_DONTROUTE
+#define SO_DONTROUTE (-1)
+#endif
+#ifndef SO_OOBINLINE
+#define SO_OOBINLINE (-1)
+#endif
+#ifndef SO_ACCEPTCONN
+#define SO_ACCEPTCONN (-1)
+#endif
+#ifndef SO_SNDBUF
+#define SO_SNDBUF (-1)
+#endif
+#ifndef SO_RCVBUF
+#define SO_RCVBUF (-1)
+#endif
+#ifndef SO_ERROR
+#define SO_ERROR (-1)
+#endif
+#ifndef SO_TYPE
+#define SO_TYPE (-1)
+#endif
+#ifndef SO_RCVLOWAT
+#define SO_RCVLOWAT (-1)
+#endif
+#ifndef SO_SNDLOWAT
+#define SO_SNDLOWAT (-1)
+#endif
+#ifndef SO_LINGER
+#define SO_LINGER (-1)
+#endif
+#ifndef SO_RCVTIMEO
+#define SO_RCVTIMEO (-1)
+#endif
+#ifndef SO_SNDTIMEO
+#define SO_SNDTIMEO (-1)
+#endif
+#ifndef TCP_NODELAY
+#define TCP_NODELAY (-1)
+#endif
+#ifndef SO_ERROR
+#define SO_ERROR (-1)
+#endif
+#ifndef IPPROTO_IPV6
+#define IPPROTO_IPV6 (-1)
+#endif
+#ifndef IPV6_V6ONLY
+#define IPV6_V6ONLY (-1)
+#endif
+
+enum option_type {
+ TYPE_BOOL = 0,
+ TYPE_INT = 1,
+ TYPE_LINGER = 2,
+ TYPE_TIMEVAL = 3,
+ TYPE_UNIX_ERROR = 4
+};
+
+struct socket_option {
+ int level;
+ int option;
+};
+
+/* Table of options, indexed by type */
+
+static struct socket_option sockopt_bool[] = {
+ { SOL_SOCKET, SO_DEBUG },
+ { SOL_SOCKET, SO_BROADCAST },
+ { SOL_SOCKET, SO_REUSEADDR },
+ { SOL_SOCKET, SO_KEEPALIVE },
+ { SOL_SOCKET, SO_DONTROUTE },
+ { SOL_SOCKET, SO_OOBINLINE },
+ { SOL_SOCKET, SO_ACCEPTCONN },
+ { IPPROTO_TCP, TCP_NODELAY },
+ { IPPROTO_IPV6, IPV6_V6ONLY}
+};
+
+static struct socket_option sockopt_int[] = {
+ { SOL_SOCKET, SO_SNDBUF },
+ { SOL_SOCKET, SO_RCVBUF },
+ { SOL_SOCKET, SO_ERROR },
+ { SOL_SOCKET, SO_TYPE },
+ { SOL_SOCKET, SO_RCVLOWAT },
+ { SOL_SOCKET, SO_SNDLOWAT } };
+
+static struct socket_option sockopt_linger[] = {
+ { SOL_SOCKET, SO_LINGER }
+};
+
+static struct socket_option sockopt_timeval[] = {
+ { SOL_SOCKET, SO_RCVTIMEO },
+ { SOL_SOCKET, SO_SNDTIMEO }
+};
+
+static struct socket_option sockopt_unix_error[] = {
+ { SOL_SOCKET, SO_ERROR }
+};
+
+static struct socket_option * sockopt_table[] = {
+ sockopt_bool,
+ sockopt_int,
+ sockopt_linger,
+ sockopt_timeval,
+ sockopt_unix_error
+};
+
+static char * getsockopt_fun_name[] = {
+ "getsockopt",
+ "getsockopt_int",
+ "getsockopt_optint",
+ "getsockopt_float",
+ "getsockopt_error"
+};
+
+static char * setsockopt_fun_name[] = {
+ "setsockopt",
+ "setsockopt_int",
+ "setsockopt_optint",
+ "setsockopt_float",
+ "setsockopt_error"
+};
+
+union option_value {
+ int i;
+ struct linger lg;
+ struct timeval tv;
+};
+
+CAMLexport value
+unix_getsockopt_aux(char * name,
+ enum option_type ty, int level, int option,
+ value socket)
+{
+ union option_value optval;
+ socklen_param_type optsize;
+
+
+ switch (ty) {
+ case TYPE_BOOL:
+ case TYPE_INT:
+ case TYPE_UNIX_ERROR:
+ optsize = sizeof(optval.i); break;
+ case TYPE_LINGER:
+ optsize = sizeof(optval.lg); break;
+ case TYPE_TIMEVAL:
+ optsize = sizeof(optval.tv); break;
+ default:
+ unix_error(EINVAL, name, Nothing);
+ }
+
+ if (getsockopt(Int_val(socket), level, option,
+ (void *) &optval, &optsize) == -1)
+ uerror(name, Nothing);
+
+ switch (ty) {
+ case TYPE_BOOL:
+ return Val_bool(optval.i);
+ case TYPE_INT:
+ return Val_int(optval.i);
+ case TYPE_LINGER:
+ if (optval.lg.l_onoff == 0) {
+ return Val_int(0); /* None */
+ } else {
+ value res = alloc_small(1, 0); /* Some */
+ Field(res, 0) = Val_int(optval.lg.l_linger);
+ return res;
+ }
+ case TYPE_TIMEVAL:
+ return copy_double((double) optval.tv.tv_sec
+ + (double) optval.tv.tv_usec / 1e6);
+ case TYPE_UNIX_ERROR:
+ if (optval.i == 0) {
+ return Val_int(0); /* None */
+ } else {
+ value err, res;
+ err = unix_error_of_code(optval.i);
+ Begin_root(err);
+ res = alloc_small(1, 0); /* Some */
+ Field(res, 0) = err;
+ End_roots();
+ return res;
+ }
+ default:
+ unix_error(EINVAL, name, Nothing);
+ }
+}
+
+CAMLexport value
+unix_setsockopt_aux(char * name,
+ enum option_type ty, int level, int option,
+ value socket, value val)
+{
+ union option_value optval;
+ socklen_param_type optsize;
+ double f;
+
+ switch (ty) {
+ case TYPE_BOOL:
+ case TYPE_INT:
+ optsize = sizeof(optval.i);
+ optval.i = Int_val(val);
+ break;
+ case TYPE_LINGER:
+ optsize = sizeof(optval.lg);
+ optval.lg.l_onoff = Is_block (val);
+ if (optval.lg.l_onoff)
+ optval.lg.l_linger = Int_val (Field (val, 0));
+ break;
+ case TYPE_TIMEVAL:
+ f = Double_val(val);
+ optsize = sizeof(optval.tv);
+ optval.tv.tv_sec = (int) f;
+ optval.tv.tv_usec = (int) (1e6 * (f - optval.tv.tv_sec));
+ break;
+ case TYPE_UNIX_ERROR:
+ default:
+ unix_error(EINVAL, name, Nothing);
+ }
+
+ if (setsockopt(Int_val(socket), level, option,
+ (void *) &optval, optsize) == -1)
+ uerror(name, Nothing);
+
+ return Val_unit;
+}
+
+CAMLprim value unix_getsockopt(value vty, value vsocket, value voption)
+{
+ enum option_type ty = Int_val(vty);
+ struct socket_option * opt = &(sockopt_table[ty][Int_val(voption)]);
+ return unix_getsockopt_aux(getsockopt_fun_name[ty],
+ ty,
+ opt->level,
+ opt->option,
+ vsocket);
+}
+
+CAMLprim value unix_setsockopt(value vty, value vsocket, value voption,
+ value val)
+{
+ enum option_type ty = Int_val(vty);
+ struct socket_option * opt = &(sockopt_table[ty][Int_val(voption)]);
+ return unix_setsockopt_aux(setsockopt_fun_name[ty],
+ ty,
+ opt->level,
+ opt->option,
+ vsocket,
+ val);
+}
+
+#else
+
+CAMLprim value unix_getsockopt(value vty, value socket, value option)
+{ invalid_argument("getsockopt not implemented"); }
+
+CAMLprim value unix_setsockopt(value vty, value socket, value option, value val)
+{ invalid_argument("setsockopt not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/stat.c b/otherlibs/unix/stat.c
new file mode 100644
index 0000000000..52a00005c8
--- /dev/null
+++ b/otherlibs/unix/stat.c
@@ -0,0 +1,171 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include <caml/signals.h>
+#include <caml/io.h>
+#include "unixsupport.h"
+#include "cst2constr.h"
+
+#ifndef S_IFLNK
+#define S_IFLNK 0
+#endif
+#ifndef S_IFIFO
+#define S_IFIFO 0
+#endif
+#ifndef S_IFSOCK
+#define S_IFSOCK 0
+#endif
+#ifndef S_IFBLK
+#define S_IFBLK 0
+#endif
+
+#ifndef EOVERFLOW
+#define EOVERFLOW ERANGE
+#endif
+
+static int file_kind_table[] = {
+ S_IFREG, S_IFDIR, S_IFCHR, S_IFBLK, S_IFLNK, S_IFIFO, S_IFSOCK
+};
+
+static value stat_aux(int use_64, struct stat *buf)
+{
+ CAMLparam0();
+ CAMLlocal5(atime, mtime, ctime, offset, v);
+
+ #include "nanosecond_stat.h"
+ atime = caml_copy_double((double) buf->st_atime
+ + (NSEC(buf, a) / 1000000000.0));
+ mtime = caml_copy_double((double) buf->st_mtime
+ + (NSEC(buf, m) / 1000000000.0));
+ ctime = caml_copy_double((double) buf->st_ctime
+ + (NSEC(buf, c) / 1000000000.0));
+ #undef NSEC
+ offset = use_64 ? Val_file_offset(buf->st_size) : Val_int (buf->st_size);
+ v = alloc_small(12, 0);
+ Field (v, 0) = Val_int (buf->st_dev);
+ Field (v, 1) = Val_int (buf->st_ino);
+ Field (v, 2) = cst_to_constr(buf->st_mode & S_IFMT, file_kind_table,
+ sizeof(file_kind_table) / sizeof(int), 0);
+ Field (v, 3) = Val_int (buf->st_mode & 07777);
+ Field (v, 4) = Val_int (buf->st_nlink);
+ Field (v, 5) = Val_int (buf->st_uid);
+ Field (v, 6) = Val_int (buf->st_gid);
+ Field (v, 7) = Val_int (buf->st_rdev);
+ Field (v, 8) = offset;
+ Field (v, 9) = atime;
+ Field (v, 10) = mtime;
+ Field (v, 11) = ctime;
+ CAMLreturn(v);
+}
+
+CAMLprim value unix_stat(value path)
+{
+ CAMLparam1(path);
+ int ret;
+ struct stat buf;
+ char * p;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = stat(p, &buf);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("stat", path);
+ if (buf.st_size > Max_long && (buf.st_mode & S_IFMT) == S_IFREG)
+ unix_error(EOVERFLOW, "stat", path);
+ CAMLreturn(stat_aux(0, &buf));
+}
+
+CAMLprim value unix_lstat(value path)
+{
+ CAMLparam1(path);
+ int ret;
+ struct stat buf;
+ char * p;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+#ifdef HAS_SYMLINK
+ ret = lstat(p, &buf);
+#else
+ ret = stat(p, &buf);
+#endif
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("lstat", path);
+ if (buf.st_size > Max_long && (buf.st_mode & S_IFMT) == S_IFREG)
+ unix_error(EOVERFLOW, "lstat", path);
+ CAMLreturn(stat_aux(0, &buf));
+}
+
+CAMLprim value unix_fstat(value fd)
+{
+ int ret;
+ struct stat buf;
+ caml_enter_blocking_section();
+ ret = fstat(Int_val(fd), &buf);
+ caml_leave_blocking_section();
+ if (ret == -1) uerror("fstat", Nothing);
+ if (buf.st_size > Max_long && (buf.st_mode & S_IFMT) == S_IFREG)
+ unix_error(EOVERFLOW, "fstat", Nothing);
+ return stat_aux(0, &buf);
+}
+
+CAMLprim value unix_stat_64(value path)
+{
+ CAMLparam1(path);
+ int ret;
+ struct stat buf;
+ char * p;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = stat(p, &buf);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("stat", path);
+ CAMLreturn(stat_aux(1, &buf));
+}
+
+CAMLprim value unix_lstat_64(value path)
+{
+ CAMLparam1(path);
+ int ret;
+ struct stat buf;
+ char * p;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+#ifdef HAS_SYMLINK
+ ret = lstat(p, &buf);
+#else
+ ret = stat(p, &buf);
+#endif
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("lstat", path);
+ CAMLreturn(stat_aux(1, &buf));
+}
+
+CAMLprim value unix_fstat_64(value fd)
+{
+ int ret;
+ struct stat buf;
+ caml_enter_blocking_section();
+ ret = fstat(Int_val(fd), &buf);
+ caml_leave_blocking_section();
+ if (ret == -1) uerror("fstat", Nothing);
+ return stat_aux(1, &buf);
+}
diff --git a/otherlibs/unix/strofaddr.c b/otherlibs/unix/strofaddr.c
new file mode 100644
index 0000000000..c4ea6bad04
--- /dev/null
+++ b/otherlibs/unix/strofaddr.c
@@ -0,0 +1,72 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SOCKETS
+
+#include "socketaddr.h"
+
+CAMLprim value unix_string_of_inet_addr(value a)
+{
+ char * res;
+#ifdef HAS_IPV6
+#ifdef _WIN32
+ char buffer[64];
+ union sock_addr_union sa;
+ int len;
+ int retcode;
+ if (string_length(a) == 16) {
+ memset(&sa.s_inet6, 0, sizeof(struct sockaddr_in6));
+ sa.s_inet6.sin6_family = AF_INET6;
+ sa.s_inet6.sin6_addr = GET_INET6_ADDR(a);
+ len = sizeof(struct sockaddr_in6);
+ } else {
+ memset(&sa.s_inet, 0, sizeof(struct sockaddr_in));
+ sa.s_inet.sin_family = AF_INET;
+ sa.s_inet.sin_addr = GET_INET_ADDR(a);
+ len = sizeof(struct sockaddr_in);
+ }
+ retcode = getnameinfo
+ (&sa.s_gen, len, buffer, sizeof(buffer), NULL, 0, NI_NUMERICHOST);
+ if (retcode != 0)
+ res = NULL;
+ else
+ res = buffer;
+#else
+ char buffer[64];
+ if (string_length(a) == 16)
+ res = (char *)
+ inet_ntop(AF_INET6, (const void *) &GET_INET6_ADDR(a),
+ buffer, sizeof(buffer));
+ else
+ res = (char *)
+ inet_ntop(AF_INET, (const void *) &GET_INET_ADDR(a),
+ buffer, sizeof(buffer));
+#endif
+#else
+ res = inet_ntoa(GET_INET_ADDR(a));
+#endif
+ if (res == NULL) uerror("string_of_inet_addr", Nothing);
+ return copy_string(res);
+}
+
+#else
+
+CAMLprim value unix_string_of_inet_addr(value a)
+{ invalid_argument("string_of_inet_addr not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/symlink.c b/otherlibs/unix/symlink.c
new file mode 100644
index 0000000000..dbbd26655e
--- /dev/null
+++ b/otherlibs/unix/symlink.c
@@ -0,0 +1,45 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_SYMLINK
+
+CAMLprim value unix_symlink(value path1, value path2)
+{
+ CAMLparam2(path1, path2);
+ char * p1;
+ char * p2;
+ int ret;
+ p1 = caml_strdup(String_val(path1));
+ p2 = caml_strdup(String_val(path2));
+ caml_enter_blocking_section();
+ ret = symlink(p1, p2);
+ caml_leave_blocking_section();
+ caml_stat_free(p1);
+ caml_stat_free(p2);
+ if (ret == -1)
+ uerror("symlink", path2);
+ CAMLreturn(Val_unit);
+}
+
+#else
+
+CAMLprim value unix_symlink(value path1, value path2)
+{ invalid_argument("symlink not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/termios.c b/otherlibs/unix/termios.c
new file mode 100644
index 0000000000..40173737dd
--- /dev/null
+++ b/otherlibs/unix/termios.c
@@ -0,0 +1,385 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+
+#ifdef HAS_TERMIOS
+
+#include <termios.h>
+#include <errno.h>
+
+static struct termios terminal_status;
+
+enum { Bool, Enum, Speed, Char, End };
+
+enum { Input, Output };
+
+#define iflags ((long)(&terminal_status.c_iflag))
+#define oflags ((long)(&terminal_status.c_oflag))
+#define cflags ((long)(&terminal_status.c_cflag))
+#define lflags ((long)(&terminal_status.c_lflag))
+
+/* Number of fields in the terminal_io record field. Cf. unix.mli */
+
+#define NFIELDS 38
+
+/* Structure of the terminal_io record. Cf. unix.mli */
+
+static long terminal_io_descr[] = {
+ /* Input modes */
+ Bool, iflags, IGNBRK,
+ Bool, iflags, BRKINT,
+ Bool, iflags, IGNPAR,
+ Bool, iflags, PARMRK,
+ Bool, iflags, INPCK,
+ Bool, iflags, ISTRIP,
+ Bool, iflags, INLCR,
+ Bool, iflags, IGNCR,
+ Bool, iflags, ICRNL,
+ Bool, iflags, IXON,
+ Bool, iflags, IXOFF,
+ /* Output modes */
+ Bool, oflags, OPOST,
+ /* Control modes */
+ Speed, Output,
+ Speed, Input,
+ Enum, cflags, 5, 4, CSIZE, CS5, CS6, CS7, CS8,
+ Enum, cflags, 1, 2, CSTOPB, 0, CSTOPB,
+ Bool, cflags, CREAD,
+ Bool, cflags, PARENB,
+ Bool, cflags, PARODD,
+ Bool, cflags, HUPCL,
+ Bool, cflags, CLOCAL,
+ /* Local modes */
+ Bool, lflags, ISIG,
+ Bool, lflags, ICANON,
+ Bool, lflags, NOFLSH,
+ Bool, lflags, ECHO,
+ Bool, lflags, ECHOE,
+ Bool, lflags, ECHOK,
+ Bool, lflags, ECHONL,
+ /* Control characters */
+ Char, VINTR,
+ Char, VQUIT,
+ Char, VERASE,
+ Char, VKILL,
+ Char, VEOF,
+ Char, VEOL,
+ Char, VMIN,
+ Char, VTIME,
+ Char, VSTART,
+ Char, VSTOP,
+ End
+};
+
+#undef iflags
+#undef oflags
+#undef cflags
+#undef lflags
+
+static struct {
+ speed_t speed;
+ int baud;
+} speedtable[] = {
+
+ /* standard speeds */
+ {B0, 0},
+ {B50, 50},
+ {B75, 75},
+ {B110, 110},
+ {B134, 134},
+ {B150, 150},
+#ifdef B200
+ /* Shouldn't need to be ifdef'd but I'm not sure it's available everywhere. */
+ {B200, 200},
+#endif
+ {B300, 300},
+ {B600, 600},
+ {B1200, 1200},
+ {B1800, 1800},
+ {B2400, 2400},
+ {B4800, 4800},
+ {B9600, 9600},
+ {B19200, 19200},
+ {B38400, 38400},
+
+ /* usual extensions */
+#ifdef B57600
+ {B57600, 57600},
+#endif
+#ifdef B115200
+ {B115200, 115200},
+#endif
+#ifdef B230400
+ {B230400, 230400},
+#endif
+
+ /* Linux extensions */
+#ifdef B460800
+ {B460800, 460800},
+#endif
+#ifdef B500000
+ {B500000, 500000},
+#endif
+#ifdef B576000
+ {B576000, 576000},
+#endif
+#ifdef B921600
+ {B921600, 921600},
+#endif
+#ifdef B1000000
+ {B1000000, 1000000},
+#endif
+#ifdef B1152000
+ {B1152000, 1152000},
+#endif
+#ifdef B1500000
+ {B1500000, 1500000},
+#endif
+#ifdef B2000000
+ {B2000000, 2000000},
+#endif
+#ifdef B2500000
+ {B2500000, 2500000},
+#endif
+#ifdef B3000000
+ {B3000000, 3000000},
+#endif
+#ifdef B3500000
+ {B3500000, 3500000},
+#endif
+#ifdef B4000000
+ {B4000000, 4000000},
+#endif
+
+ /* MacOS extensions */
+#ifdef B7200
+ {B7200, 7200},
+#endif
+#ifdef B14400
+ {B14400, 14400},
+#endif
+#ifdef B28800
+ {B28800, 28800},
+#endif
+#ifdef B76800
+ {B76800, 76800},
+#endif
+
+ /* Cygwin extensions (in addition to the Linux ones) */
+#ifdef B128000
+ {B128000, 128000},
+#endif
+#ifdef B256000
+ {B256000, 256000},
+#endif
+};
+
+#define NSPEEDS (sizeof(speedtable) / sizeof(speedtable[0]))
+
+static void encode_terminal_status(value *dst)
+{
+ long * pc;
+ int i;
+
+ for(pc = terminal_io_descr; *pc != End; dst++) {
+ switch(*pc++) {
+ case Bool:
+ { int * src = (int *) (*pc++);
+ int msk = *pc++;
+ *dst = Val_bool(*src & msk);
+ break; }
+ case Enum:
+ { int * src = (int *) (*pc++);
+ int ofs = *pc++;
+ int num = *pc++;
+ int msk = *pc++;
+ for (i = 0; i < num; i++) {
+ if ((*src & msk) == pc[i]) {
+ *dst = Val_int(i + ofs);
+ break;
+ }
+ }
+ pc += num;
+ break; }
+ case Speed:
+ { int which = *pc++;
+ speed_t speed = 0;
+ *dst = Val_int(9600); /* in case no speed in speedtable matches */
+ switch (which) {
+ case Output:
+ speed = cfgetospeed(&terminal_status); break;
+ case Input:
+ speed = cfgetispeed(&terminal_status); break;
+ }
+ for (i = 0; i < NSPEEDS; i++) {
+ if (speed == speedtable[i].speed) {
+ *dst = Val_int(speedtable[i].baud);
+ break;
+ }
+ }
+ break; }
+ case Char:
+ { int which = *pc++;
+ *dst = Val_int(terminal_status.c_cc[which]);
+ break; }
+ }
+ }
+}
+
+static void decode_terminal_status(value *src)
+{
+ long * pc;
+ int i;
+
+ for (pc = terminal_io_descr; *pc != End; src++) {
+ switch(*pc++) {
+ case Bool:
+ { int * dst = (int *) (*pc++);
+ int msk = *pc++;
+ if (Bool_val(*src))
+ *dst |= msk;
+ else
+ *dst &= ~msk;
+ break; }
+ case Enum:
+ { int * dst = (int *) (*pc++);
+ int ofs = *pc++;
+ int num = *pc++;
+ int msk = *pc++;
+ i = Int_val(*src) - ofs;
+ if (i >= 0 && i < num) {
+ *dst = (*dst & ~msk) | pc[i];
+ } else {
+ unix_error(EINVAL, "tcsetattr", Nothing);
+ }
+ pc += num;
+ break; }
+ case Speed:
+ { int which = *pc++;
+ int baud = Int_val(*src);
+ int res = 0;
+ for (i = 0; i < NSPEEDS; i++) {
+ if (baud == speedtable[i].baud) {
+ switch (which) {
+ case Output:
+ res = cfsetospeed(&terminal_status, speedtable[i].speed); break;
+ case Input:
+ res = cfsetispeed(&terminal_status, speedtable[i].speed); break;
+ }
+ if (res == -1) uerror("tcsetattr", Nothing);
+ goto ok;
+ }
+ }
+ unix_error(EINVAL, "tcsetattr", Nothing);
+ ok:
+ break; }
+ case Char:
+ { int which = *pc++;
+ terminal_status.c_cc[which] = Int_val(*src);
+ break; }
+ }
+ }
+}
+
+CAMLprim value unix_tcgetattr(value fd)
+{
+ value res;
+
+ if (tcgetattr(Int_val(fd), &terminal_status) == -1)
+ uerror("tcgetattr", Nothing);
+ res = alloc_tuple(NFIELDS);
+ encode_terminal_status(&Field(res, 0));
+ return res;
+}
+
+static int when_flag_table[] = {
+ TCSANOW, TCSADRAIN, TCSAFLUSH
+};
+
+CAMLprim value unix_tcsetattr(value fd, value when, value arg)
+{
+ if (tcgetattr(Int_val(fd), &terminal_status) == -1)
+ uerror("tcsetattr", Nothing);
+ decode_terminal_status(&Field(arg, 0));
+ if (tcsetattr(Int_val(fd),
+ when_flag_table[Int_val(when)],
+ &terminal_status) == -1)
+ uerror("tcsetattr", Nothing);
+ return Val_unit;
+}
+
+CAMLprim value unix_tcsendbreak(value fd, value delay)
+{
+ if (tcsendbreak(Int_val(fd), Int_val(delay)) == -1)
+ uerror("tcsendbreak", Nothing);
+ return Val_unit;
+}
+
+#if defined(__ANDROID__)
+CAMLprim value unix_tcdrain(value fd)
+{ invalid_argument("tcdrain not implemented"); }
+#else
+CAMLprim value unix_tcdrain(value fd)
+{
+ if (tcdrain(Int_val(fd)) == -1) uerror("tcdrain", Nothing);
+ return Val_unit;
+}
+#endif
+
+static int queue_flag_table[] = {
+ TCIFLUSH, TCOFLUSH, TCIOFLUSH
+};
+
+CAMLprim value unix_tcflush(value fd, value queue)
+{
+ if (tcflush(Int_val(fd), queue_flag_table[Int_val(queue)]) == -1)
+ uerror("tcflush", Nothing);
+ return Val_unit;
+}
+
+static int action_flag_table[] = {
+ TCOOFF, TCOON, TCIOFF, TCION
+};
+
+CAMLprim value unix_tcflow(value fd, value action)
+{
+ if (tcflow(Int_val(fd), action_flag_table[Int_val(action)]) == -1)
+ uerror("tcflow", Nothing);
+ return Val_unit;
+}
+
+#else
+
+CAMLprim value unix_tcgetattr(value fd)
+{ invalid_argument("tcgetattr not implemented"); }
+
+CAMLprim value unix_tcsetattr(value fd, value when, value arg)
+{ invalid_argument("tcsetattr not implemented"); }
+
+CAMLprim value unix_tcsendbreak(value fd, value delay)
+{ invalid_argument("tcsendbreak not implemented"); }
+
+CAMLprim value unix_tcdrain(value fd)
+{ invalid_argument("tcdrain not implemented"); }
+
+CAMLprim value unix_tcflush(value fd, value queue)
+{ invalid_argument("tcflush not implemented"); }
+
+CAMLprim value unix_tcflow(value fd, value action)
+{ invalid_argument("tcflow not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/time.c b/otherlibs/unix/time.c
new file mode 100644
index 0000000000..495adb660b
--- /dev/null
+++ b/otherlibs/unix/time.c
@@ -0,0 +1,22 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <time.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_time(value unit)
+{
+ return copy_double((double) time((time_t *) NULL));
+}
diff --git a/otherlibs/unix/times.c b/otherlibs/unix/times.c
new file mode 100644
index 0000000000..8760ad2ab2
--- /dev/null
+++ b/otherlibs/unix/times.c
@@ -0,0 +1,65 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+#include <time.h>
+#include <sys/types.h>
+#include <sys/times.h>
+#ifdef HAS_GETRUSAGE
+#include <sys/time.h>
+#include <sys/resource.h>
+#endif
+
+#ifndef CLK_TCK
+#ifdef HZ
+#define CLK_TCK HZ
+#else
+#define CLK_TCK 60
+#endif
+#endif
+
+CAMLprim value unix_times(value unit)
+{
+#ifdef HAS_GETRUSAGE
+
+ value res;
+ struct rusage ru;
+
+ res = alloc_small(4 * Double_wosize, Double_array_tag);
+
+ getrusage (RUSAGE_SELF, &ru);
+ Store_double_field (res, 0, ru.ru_utime.tv_sec + ru.ru_utime.tv_usec / 1e6);
+ Store_double_field (res, 1, ru.ru_stime.tv_sec + ru.ru_stime.tv_usec / 1e6);
+ getrusage (RUSAGE_CHILDREN, &ru);
+ Store_double_field (res, 2, ru.ru_utime.tv_sec + ru.ru_utime.tv_usec / 1e6);
+ Store_double_field (res, 3, ru.ru_stime.tv_sec + ru.ru_stime.tv_usec / 1e6);
+ return res;
+
+#else
+
+ value res;
+ struct tms buffer;
+
+ times(&buffer);
+ res = alloc_small(4 * Double_wosize, Double_array_tag);
+ Store_double_field(res, 0, (double) buffer.tms_utime / CLK_TCK);
+ Store_double_field(res, 1, (double) buffer.tms_stime / CLK_TCK);
+ Store_double_field(res, 2, (double) buffer.tms_cutime / CLK_TCK);
+ Store_double_field(res, 3, (double) buffer.tms_cstime / CLK_TCK);
+ return res;
+
+#endif
+}
diff --git a/otherlibs/unix/truncate.c b/otherlibs/unix/truncate.c
new file mode 100644
index 0000000000..62683fcf88
--- /dev/null
+++ b/otherlibs/unix/truncate.c
@@ -0,0 +1,66 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <sys/types.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/fail.h>
+#include <caml/signals.h>
+#include <caml/io.h>
+#include "unixsupport.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+
+#ifdef HAS_TRUNCATE
+
+CAMLprim value unix_truncate(value path, value len)
+{
+ CAMLparam2(path, len);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = truncate(p, Long_val(len));
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1)
+ uerror("truncate", path);
+ CAMLreturn(Val_unit);
+}
+
+CAMLprim value unix_truncate_64(value path, value vlen)
+{
+ CAMLparam2(path, vlen);
+ char * p;
+ int ret;
+ file_offset len = File_offset_val(vlen);
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = truncate(p, len);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1)
+ uerror("truncate", path);
+ CAMLreturn(Val_unit);
+}
+
+#else
+
+CAMLprim value unix_truncate(value path, value len)
+{ invalid_argument("truncate not implemented"); }
+
+CAMLprim value unix_truncate_64(value path, value len)
+{ invalid_argument("truncate not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/umask.c b/otherlibs/unix/umask.c
new file mode 100644
index 0000000000..9b88f105c5
--- /dev/null
+++ b/otherlibs/unix/umask.c
@@ -0,0 +1,22 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_umask(value perm)
+{
+ return Val_int(umask(Int_val(perm)));
+}
diff --git a/otherlibs/unix/unix.ml b/otherlibs/unix/unix.ml
new file mode 100644
index 0000000000..d18b338adb
--- /dev/null
+++ b/otherlibs/unix/unix.ml
@@ -0,0 +1,1087 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type error =
+ E2BIG
+ | EACCES
+ | EAGAIN
+ | EBADF
+ | EBUSY
+ | ECHILD
+ | EDEADLK
+ | EDOM
+ | EEXIST
+ | EFAULT
+ | EFBIG
+ | EINTR
+ | EINVAL
+ | EIO
+ | EISDIR
+ | EMFILE
+ | EMLINK
+ | ENAMETOOLONG
+ | ENFILE
+ | ENODEV
+ | ENOENT
+ | ENOEXEC
+ | ENOLCK
+ | ENOMEM
+ | ENOSPC
+ | ENOSYS
+ | ENOTDIR
+ | ENOTEMPTY
+ | ENOTTY
+ | ENXIO
+ | EPERM
+ | EPIPE
+ | ERANGE
+ | EROFS
+ | ESPIPE
+ | ESRCH
+ | EXDEV
+ | EWOULDBLOCK
+ | EINPROGRESS
+ | EALREADY
+ | ENOTSOCK
+ | EDESTADDRREQ
+ | EMSGSIZE
+ | EPROTOTYPE
+ | ENOPROTOOPT
+ | EPROTONOSUPPORT
+ | ESOCKTNOSUPPORT
+ | EOPNOTSUPP
+ | EPFNOSUPPORT
+ | EAFNOSUPPORT
+ | EADDRINUSE
+ | EADDRNOTAVAIL
+ | ENETDOWN
+ | ENETUNREACH
+ | ENETRESET
+ | ECONNABORTED
+ | ECONNRESET
+ | ENOBUFS
+ | EISCONN
+ | ENOTCONN
+ | ESHUTDOWN
+ | ETOOMANYREFS
+ | ETIMEDOUT
+ | ECONNREFUSED
+ | EHOSTDOWN
+ | EHOSTUNREACH
+ | ELOOP
+ | EOVERFLOW
+ | EUNKNOWNERR of int
+
+exception Unix_error of error * string * string
+
+let _ = Callback.register_exception "Unix.Unix_error"
+ (Unix_error(E2BIG, "", ""))
+
+external error_message : error -> string = "unix_error_message"
+
+let () =
+ Printexc.register_printer
+ (function
+ | Unix_error (e, s, s') ->
+ let msg = match e with
+ | E2BIG -> "E2BIG"
+ | EACCES -> "EACCES"
+ | EAGAIN -> "EAGAIN"
+ | EBADF -> "EBADF"
+ | EBUSY -> "EBUSY"
+ | ECHILD -> "ECHILD"
+ | EDEADLK -> "EDEADLK"
+ | EDOM -> "EDOM"
+ | EEXIST -> "EEXIST"
+ | EFAULT -> "EFAULT"
+ | EFBIG -> "EFBIG"
+ | EINTR -> "EINTR"
+ | EINVAL -> "EINVAL"
+ | EIO -> "EIO"
+ | EISDIR -> "EISDIR"
+ | EMFILE -> "EMFILE"
+ | EMLINK -> "EMLINK"
+ | ENAMETOOLONG -> "ENAMETOOLONG"
+ | ENFILE -> "ENFILE"
+ | ENODEV -> "ENODEV"
+ | ENOENT -> "ENOENT"
+ | ENOEXEC -> "ENOEXEC"
+ | ENOLCK -> "ENOLCK"
+ | ENOMEM -> "ENOMEM"
+ | ENOSPC -> "ENOSPC"
+ | ENOSYS -> "ENOSYS"
+ | ENOTDIR -> "ENOTDIR"
+ | ENOTEMPTY -> "ENOTEMPTY"
+ | ENOTTY -> "ENOTTY"
+ | ENXIO -> "ENXIO"
+ | EPERM -> "EPERM"
+ | EPIPE -> "EPIPE"
+ | ERANGE -> "ERANGE"
+ | EROFS -> "EROFS"
+ | ESPIPE -> "ESPIPE"
+ | ESRCH -> "ESRCH"
+ | EXDEV -> "EXDEV"
+ | EWOULDBLOCK -> "EWOULDBLOCK"
+ | EINPROGRESS -> "EINPROGRESS"
+ | EALREADY -> "EALREADY"
+ | ENOTSOCK -> "ENOTSOCK"
+ | EDESTADDRREQ -> "EDESTADDRREQ"
+ | EMSGSIZE -> "EMSGSIZE"
+ | EPROTOTYPE -> "EPROTOTYPE"
+ | ENOPROTOOPT -> "ENOPROTOOPT"
+ | EPROTONOSUPPORT -> "EPROTONOSUPPORT"
+ | ESOCKTNOSUPPORT -> "ESOCKTNOSUPPORT"
+ | EOPNOTSUPP -> "EOPNOTSUPP"
+ | EPFNOSUPPORT -> "EPFNOSUPPORT"
+ | EAFNOSUPPORT -> "EAFNOSUPPORT"
+ | EADDRINUSE -> "EADDRINUSE"
+ | EADDRNOTAVAIL -> "EADDRNOTAVAIL"
+ | ENETDOWN -> "ENETDOWN"
+ | ENETUNREACH -> "ENETUNREACH"
+ | ENETRESET -> "ENETRESET"
+ | ECONNABORTED -> "ECONNABORTED"
+ | ECONNRESET -> "ECONNRESET"
+ | ENOBUFS -> "ENOBUFS"
+ | EISCONN -> "EISCONN"
+ | ENOTCONN -> "ENOTCONN"
+ | ESHUTDOWN -> "ESHUTDOWN"
+ | ETOOMANYREFS -> "ETOOMANYREFS"
+ | ETIMEDOUT -> "ETIMEDOUT"
+ | ECONNREFUSED -> "ECONNREFUSED"
+ | EHOSTDOWN -> "EHOSTDOWN"
+ | EHOSTUNREACH -> "EHOSTUNREACH"
+ | ELOOP -> "ELOOP"
+ | EOVERFLOW -> "EOVERFLOW"
+ | EUNKNOWNERR x -> Printf.sprintf "EUNKNOWNERR %d" x in
+ Some (Printf.sprintf "Unix.Unix_error(Unix.%s, %S, %S)" msg s s')
+ | _ -> None)
+
+let handle_unix_error f arg =
+ try
+ f arg
+ with Unix_error(err, fun_name, arg) ->
+ prerr_string Sys.argv.(0);
+ prerr_string ": \"";
+ prerr_string fun_name;
+ prerr_string "\" failed";
+ if String.length arg > 0 then begin
+ prerr_string " on \"";
+ prerr_string arg;
+ prerr_string "\""
+ end;
+ prerr_string ": ";
+ prerr_endline (error_message err);
+ exit 2
+
+external environment : unit -> string array = "unix_environment"
+external getenv: string -> string = "caml_sys_getenv"
+external putenv: string -> string -> unit = "unix_putenv"
+
+type process_status =
+ WEXITED of int
+ | WSIGNALED of int
+ | WSTOPPED of int
+
+type wait_flag =
+ WNOHANG
+ | WUNTRACED
+
+external execv : string -> string array -> 'a = "unix_execv"
+external execve : string -> string array -> string array -> 'a = "unix_execve"
+external execvp : string -> string array -> 'a = "unix_execvp"
+external execvpe : string -> string array -> string array -> 'a = "unix_execvpe"
+external fork : unit -> int = "unix_fork"
+external wait : unit -> int * process_status = "unix_wait"
+external waitpid : wait_flag list -> int -> int * process_status
+ = "unix_waitpid"
+external getpid : unit -> int = "unix_getpid"
+external getppid : unit -> int = "unix_getppid"
+external nice : int -> int = "unix_nice"
+
+type file_descr = int
+
+let stdin = 0
+let stdout = 1
+let stderr = 2
+
+type open_flag =
+ O_RDONLY
+ | O_WRONLY
+ | O_RDWR
+ | O_NONBLOCK
+ | O_APPEND
+ | O_CREAT
+ | O_TRUNC
+ | O_EXCL
+ | O_NOCTTY
+ | O_DSYNC
+ | O_SYNC
+ | O_RSYNC
+ | O_SHARE_DELETE
+ | O_CLOEXEC
+
+type file_perm = int
+
+
+external openfile : string -> open_flag list -> file_perm -> file_descr
+ = "unix_open"
+
+external close : file_descr -> unit = "unix_close"
+external unsafe_read : file_descr -> bytes -> int -> int -> int
+ = "unix_read"
+external unsafe_write : file_descr -> bytes -> int -> int -> int = "unix_write"
+external unsafe_single_write : file_descr -> bytes -> int -> int -> int
+ = "unix_single_write"
+
+let read fd buf ofs len =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.read"
+ else unsafe_read fd buf ofs len
+let write fd buf ofs len =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.write"
+ else unsafe_write fd buf ofs len
+(* write misbehaves because it attempts to write all data by making repeated
+ calls to the Unix write function (see comment in write.c and unix.mli).
+ single_write fixes this by never calling write twice. *)
+let single_write fd buf ofs len =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.single_write"
+ else unsafe_single_write fd buf ofs len
+
+let write_substring fd buf ofs len =
+ write fd (Bytes.unsafe_of_string buf) ofs len
+
+let single_write_substring fd buf ofs len =
+ single_write fd (Bytes.unsafe_of_string buf) ofs len
+
+external in_channel_of_descr : file_descr -> in_channel
+ = "caml_ml_open_descriptor_in"
+external out_channel_of_descr : file_descr -> out_channel
+ = "caml_ml_open_descriptor_out"
+external descr_of_in_channel : in_channel -> file_descr
+ = "caml_channel_descriptor"
+external descr_of_out_channel : out_channel -> file_descr
+ = "caml_channel_descriptor"
+
+type seek_command =
+ SEEK_SET
+ | SEEK_CUR
+ | SEEK_END
+
+external lseek : file_descr -> int -> seek_command -> int = "unix_lseek"
+external truncate : string -> int -> unit = "unix_truncate"
+external ftruncate : file_descr -> int -> unit = "unix_ftruncate"
+
+type file_kind =
+ S_REG
+ | S_DIR
+ | S_CHR
+ | S_BLK
+ | S_LNK
+ | S_FIFO
+ | S_SOCK
+
+type stats =
+ { st_dev : int;
+ st_ino : int;
+ st_kind : file_kind;
+ st_perm : file_perm;
+ st_nlink : int;
+ st_uid : int;
+ st_gid : int;
+ st_rdev : int;
+ st_size : int;
+ st_atime : float;
+ st_mtime : float;
+ st_ctime : float }
+
+external stat : string -> stats = "unix_stat"
+external lstat : string -> stats = "unix_lstat"
+external fstat : file_descr -> stats = "unix_fstat"
+external isatty : file_descr -> bool = "unix_isatty"
+external unlink : string -> unit = "unix_unlink"
+external rename : string -> string -> unit = "unix_rename"
+external link : string -> string -> unit = "unix_link"
+
+module LargeFile =
+ struct
+ external lseek : file_descr -> int64 -> seek_command -> int64
+ = "unix_lseek_64"
+ external truncate : string -> int64 -> unit = "unix_truncate_64"
+ external ftruncate : file_descr -> int64 -> unit = "unix_ftruncate_64"
+ type stats =
+ { st_dev : int;
+ st_ino : int;
+ st_kind : file_kind;
+ st_perm : file_perm;
+ st_nlink : int;
+ st_uid : int;
+ st_gid : int;
+ st_rdev : int;
+ st_size : int64;
+ st_atime : float;
+ st_mtime : float;
+ st_ctime : float;
+ }
+ external stat : string -> stats = "unix_stat_64"
+ external lstat : string -> stats = "unix_lstat_64"
+ external fstat : file_descr -> stats = "unix_fstat_64"
+ end
+
+type access_permission =
+ R_OK
+ | W_OK
+ | X_OK
+ | F_OK
+
+external chmod : string -> file_perm -> unit = "unix_chmod"
+external fchmod : file_descr -> file_perm -> unit = "unix_fchmod"
+external chown : string -> int -> int -> unit = "unix_chown"
+external fchown : file_descr -> int -> int -> unit = "unix_fchown"
+external umask : int -> int = "unix_umask"
+external access : string -> access_permission list -> unit = "unix_access"
+
+external dup : file_descr -> file_descr = "unix_dup"
+external dup2 : file_descr -> file_descr -> unit = "unix_dup2"
+external set_nonblock : file_descr -> unit = "unix_set_nonblock"
+external clear_nonblock : file_descr -> unit = "unix_clear_nonblock"
+external set_close_on_exec : file_descr -> unit = "unix_set_close_on_exec"
+external clear_close_on_exec : file_descr -> unit = "unix_clear_close_on_exec"
+
+(* FD_CLOEXEC should be supported on all Unix systems these days,
+ but just in case... *)
+let try_set_close_on_exec fd =
+ try set_close_on_exec fd; true with Invalid_argument _ -> false
+
+external mkdir : string -> file_perm -> unit = "unix_mkdir"
+external rmdir : string -> unit = "unix_rmdir"
+external chdir : string -> unit = "unix_chdir"
+external getcwd : unit -> string = "unix_getcwd"
+external chroot : string -> unit = "unix_chroot"
+
+type dir_handle
+
+external opendir : string -> dir_handle = "unix_opendir"
+external readdir : dir_handle -> string = "unix_readdir"
+external rewinddir : dir_handle -> unit = "unix_rewinddir"
+external closedir : dir_handle -> unit = "unix_closedir"
+
+external pipe : unit -> file_descr * file_descr = "unix_pipe"
+external symlink : string -> string -> unit = "unix_symlink"
+external readlink : string -> string = "unix_readlink"
+external mkfifo : string -> file_perm -> unit = "unix_mkfifo"
+external select :
+ file_descr list -> file_descr list -> file_descr list -> float ->
+ file_descr list * file_descr list * file_descr list = "unix_select"
+
+type lock_command =
+ F_ULOCK
+ | F_LOCK
+ | F_TLOCK
+ | F_TEST
+ | F_RLOCK
+ | F_TRLOCK
+
+external lockf : file_descr -> lock_command -> int -> unit = "unix_lockf"
+external kill : int -> int -> unit = "unix_kill"
+type sigprocmask_command = SIG_SETMASK | SIG_BLOCK | SIG_UNBLOCK
+external sigprocmask: sigprocmask_command -> int list -> int list
+ = "unix_sigprocmask"
+external sigpending: unit -> int list = "unix_sigpending"
+external sigsuspend: int list -> unit = "unix_sigsuspend"
+
+let pause() =
+ let sigs = sigprocmask SIG_BLOCK [] in sigsuspend sigs
+
+type process_times =
+ { tms_utime : float;
+ tms_stime : float;
+ tms_cutime : float;
+ tms_cstime : float }
+
+type tm =
+ { tm_sec : int;
+ tm_min : int;
+ tm_hour : int;
+ tm_mday : int;
+ tm_mon : int;
+ tm_year : int;
+ tm_wday : int;
+ tm_yday : int;
+ tm_isdst : bool }
+
+external time : unit -> float = "unix_time"
+external gettimeofday : unit -> float = "unix_gettimeofday"
+external gmtime : float -> tm = "unix_gmtime"
+external localtime : float -> tm = "unix_localtime"
+external mktime : tm -> float * tm = "unix_mktime"
+external alarm : int -> int = "unix_alarm"
+external sleep : int -> unit = "unix_sleep"
+external times : unit -> process_times = "unix_times"
+external utimes : string -> float -> float -> unit = "unix_utimes"
+
+type interval_timer =
+ ITIMER_REAL
+ | ITIMER_VIRTUAL
+ | ITIMER_PROF
+
+type interval_timer_status =
+ { it_interval: float; (* Period *)
+ it_value: float } (* Current value of the timer *)
+
+external getitimer: interval_timer -> interval_timer_status = "unix_getitimer"
+external setitimer:
+ interval_timer -> interval_timer_status -> interval_timer_status
+ = "unix_setitimer"
+
+external getuid : unit -> int = "unix_getuid"
+external geteuid : unit -> int = "unix_geteuid"
+external setuid : int -> unit = "unix_setuid"
+external getgid : unit -> int = "unix_getgid"
+external getegid : unit -> int = "unix_getegid"
+external setgid : int -> unit = "unix_setgid"
+external getgroups : unit -> int array = "unix_getgroups"
+external setgroups : int array -> unit = "unix_setgroups"
+external initgroups : string -> int -> unit = "unix_initgroups"
+
+type passwd_entry =
+ { pw_name : string;
+ pw_passwd : string;
+ pw_uid : int;
+ pw_gid : int;
+ pw_gecos : string;
+ pw_dir : string;
+ pw_shell : string }
+
+type group_entry =
+ { gr_name : string;
+ gr_passwd : string;
+ gr_gid : int;
+ gr_mem : string array }
+
+
+external getlogin : unit -> string = "unix_getlogin"
+external getpwnam : string -> passwd_entry = "unix_getpwnam"
+external getgrnam : string -> group_entry = "unix_getgrnam"
+external getpwuid : int -> passwd_entry = "unix_getpwuid"
+external getgrgid : int -> group_entry = "unix_getgrgid"
+
+type inet_addr = string
+
+let is_inet6_addr s = String.length s = 16
+
+external inet_addr_of_string : string -> inet_addr
+ = "unix_inet_addr_of_string"
+external string_of_inet_addr : inet_addr -> string
+ = "unix_string_of_inet_addr"
+
+let inet_addr_any = inet_addr_of_string "0.0.0.0"
+let inet_addr_loopback = inet_addr_of_string "127.0.0.1"
+let inet6_addr_any =
+ try inet_addr_of_string "::" with Failure _ -> inet_addr_any
+let inet6_addr_loopback =
+ try inet_addr_of_string "::1" with Failure _ -> inet_addr_loopback
+
+type socket_domain =
+ PF_UNIX
+ | PF_INET
+ | PF_INET6
+
+type socket_type =
+ SOCK_STREAM
+ | SOCK_DGRAM
+ | SOCK_RAW
+ | SOCK_SEQPACKET
+
+type sockaddr =
+ ADDR_UNIX of string
+ | ADDR_INET of inet_addr * int
+
+let domain_of_sockaddr = function
+ ADDR_UNIX _ -> PF_UNIX
+ | ADDR_INET(a, _) -> if is_inet6_addr a then PF_INET6 else PF_INET
+
+type shutdown_command =
+ SHUTDOWN_RECEIVE
+ | SHUTDOWN_SEND
+ | SHUTDOWN_ALL
+
+type msg_flag =
+ MSG_OOB
+ | MSG_DONTROUTE
+ | MSG_PEEK
+
+external socket : socket_domain -> socket_type -> int -> file_descr
+ = "unix_socket"
+external socketpair :
+ socket_domain -> socket_type -> int -> file_descr * file_descr
+ = "unix_socketpair"
+external accept : file_descr -> file_descr * sockaddr = "unix_accept"
+external bind : file_descr -> sockaddr -> unit = "unix_bind"
+external connect : file_descr -> sockaddr -> unit = "unix_connect"
+external listen : file_descr -> int -> unit = "unix_listen"
+external shutdown : file_descr -> shutdown_command -> unit = "unix_shutdown"
+external getsockname : file_descr -> sockaddr = "unix_getsockname"
+external getpeername : file_descr -> sockaddr = "unix_getpeername"
+
+external unsafe_recv :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int
+ = "unix_recv"
+external unsafe_recvfrom :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int * sockaddr
+ = "unix_recvfrom"
+external unsafe_send :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int
+ = "unix_send"
+external unsafe_sendto :
+ file_descr -> bytes -> int -> int -> msg_flag list -> sockaddr -> int
+ = "unix_sendto" "unix_sendto_native"
+
+let recv fd buf ofs len flags =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.recv"
+ else unsafe_recv fd buf ofs len flags
+let recvfrom fd buf ofs len flags =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.recvfrom"
+ else unsafe_recvfrom fd buf ofs len flags
+let send fd buf ofs len flags =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.send"
+ else unsafe_send fd buf ofs len flags
+let sendto fd buf ofs len flags addr =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.sendto"
+ else unsafe_sendto fd buf ofs len flags addr
+
+let send_substring fd buf ofs len flags =
+ send fd (Bytes.unsafe_of_string buf) ofs len flags
+
+let sendto_substring fd buf ofs len flags addr =
+ sendto fd (Bytes.unsafe_of_string buf) ofs len flags addr
+
+type socket_bool_option =
+ SO_DEBUG
+ | SO_BROADCAST
+ | SO_REUSEADDR
+ | SO_KEEPALIVE
+ | SO_DONTROUTE
+ | SO_OOBINLINE
+ | SO_ACCEPTCONN
+ | TCP_NODELAY
+ | IPV6_ONLY
+
+type socket_int_option =
+ SO_SNDBUF
+ | SO_RCVBUF
+ | SO_ERROR
+ | SO_TYPE
+ | SO_RCVLOWAT
+ | SO_SNDLOWAT
+
+type socket_optint_option = SO_LINGER
+
+type socket_float_option =
+ SO_RCVTIMEO
+ | SO_SNDTIMEO
+
+type socket_error_option = SO_ERROR
+
+module SO: sig
+ type ('opt, 'v) t
+ val bool: (socket_bool_option, bool) t
+ val int: (socket_int_option, int) t
+ val optint: (socket_optint_option, int option) t
+ val float: (socket_float_option, float) t
+ val error: (socket_error_option, error option) t
+ val get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
+ val set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
+end = struct
+ type ('opt, 'v) t = int
+ let bool = 0
+ let int = 1
+ let optint = 2
+ let float = 3
+ let error = 4
+ external get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
+ = "unix_getsockopt"
+ external set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
+ = "unix_setsockopt"
+end
+
+let getsockopt fd opt = SO.get SO.bool fd opt
+let setsockopt fd opt v = SO.set SO.bool fd opt v
+
+let getsockopt_int fd opt = SO.get SO.int fd opt
+let setsockopt_int fd opt v = SO.set SO.int fd opt v
+
+let getsockopt_optint fd opt = SO.get SO.optint fd opt
+let setsockopt_optint fd opt v = SO.set SO.optint fd opt v
+
+let getsockopt_float fd opt = SO.get SO.float fd opt
+let setsockopt_float fd opt v = SO.set SO.float fd opt v
+
+let getsockopt_error fd = SO.get SO.error fd SO_ERROR
+
+type host_entry =
+ { h_name : string;
+ h_aliases : string array;
+ h_addrtype : socket_domain;
+ h_addr_list : inet_addr array }
+
+type protocol_entry =
+ { p_name : string;
+ p_aliases : string array;
+ p_proto : int }
+
+type service_entry =
+ { s_name : string;
+ s_aliases : string array;
+ s_port : int;
+ s_proto : string }
+
+external gethostname : unit -> string = "unix_gethostname"
+external gethostbyname : string -> host_entry = "unix_gethostbyname"
+external gethostbyaddr : inet_addr -> host_entry = "unix_gethostbyaddr"
+external getprotobyname : string -> protocol_entry
+ = "unix_getprotobyname"
+external getprotobynumber : int -> protocol_entry
+ = "unix_getprotobynumber"
+external getservbyname : string -> string -> service_entry
+ = "unix_getservbyname"
+external getservbyport : int -> string -> service_entry
+ = "unix_getservbyport"
+
+type addr_info =
+ { ai_family : socket_domain;
+ ai_socktype : socket_type;
+ ai_protocol : int;
+ ai_addr : sockaddr;
+ ai_canonname : string }
+
+type getaddrinfo_option =
+ AI_FAMILY of socket_domain
+ | AI_SOCKTYPE of socket_type
+ | AI_PROTOCOL of int
+ | AI_NUMERICHOST
+ | AI_CANONNAME
+ | AI_PASSIVE
+
+external getaddrinfo_system
+ : string -> string -> getaddrinfo_option list -> addr_info list
+ = "unix_getaddrinfo"
+
+let getaddrinfo_emulation node service opts =
+ (* Parse options *)
+ let opt_socktype = ref None
+ and opt_protocol = ref 0
+ and opt_passive = ref false in
+ List.iter
+ (function AI_SOCKTYPE s -> opt_socktype := Some s
+ | AI_PROTOCOL p -> opt_protocol := p
+ | AI_PASSIVE -> opt_passive := true
+ | _ -> ())
+ opts;
+ (* Determine socket types and port numbers *)
+ let get_port ty kind =
+ if service = "" then [ty, 0] else
+ try
+ [ty, int_of_string service]
+ with Failure _ ->
+ try
+ [ty, (getservbyname service kind).s_port]
+ with Not_found -> []
+ in
+ let ports =
+ match !opt_socktype with
+ | None ->
+ get_port SOCK_STREAM "tcp" @ get_port SOCK_DGRAM "udp"
+ | Some SOCK_STREAM ->
+ get_port SOCK_STREAM "tcp"
+ | Some SOCK_DGRAM ->
+ get_port SOCK_DGRAM "udp"
+ | Some ty ->
+ if service = "" then [ty, 0] else [] in
+ (* Determine IP addresses *)
+ let addresses =
+ if node = "" then
+ if List.mem AI_PASSIVE opts
+ then [inet_addr_any, "0.0.0.0"]
+ else [inet_addr_loopback, "127.0.0.1"]
+ else
+ try
+ [inet_addr_of_string node, node]
+ with Failure _ ->
+ try
+ let he = gethostbyname node in
+ List.map
+ (fun a -> (a, he.h_name))
+ (Array.to_list he.h_addr_list)
+ with Not_found ->
+ [] in
+ (* Cross-product of addresses and ports *)
+ List.flatten
+ (List.map
+ (fun (ty, port) ->
+ List.map
+ (fun (addr, name) ->
+ { ai_family = PF_INET;
+ ai_socktype = ty;
+ ai_protocol = !opt_protocol;
+ ai_addr = ADDR_INET(addr, port);
+ ai_canonname = name })
+ addresses)
+ ports)
+
+let getaddrinfo node service opts =
+ try
+ List.rev(getaddrinfo_system node service opts)
+ with Invalid_argument _ ->
+ getaddrinfo_emulation node service opts
+
+type name_info =
+ { ni_hostname : string;
+ ni_service : string }
+
+type getnameinfo_option =
+ NI_NOFQDN
+ | NI_NUMERICHOST
+ | NI_NAMEREQD
+ | NI_NUMERICSERV
+ | NI_DGRAM
+
+external getnameinfo_system
+ : sockaddr -> getnameinfo_option list -> name_info
+ = "unix_getnameinfo"
+
+let getnameinfo_emulation addr opts =
+ match addr with
+ | ADDR_UNIX f ->
+ { ni_hostname = ""; ni_service = f } (* why not? *)
+ | ADDR_INET(a, p) ->
+ let hostname =
+ try
+ if List.mem NI_NUMERICHOST opts then raise Not_found;
+ (gethostbyaddr a).h_name
+ with Not_found ->
+ if List.mem NI_NAMEREQD opts then raise Not_found;
+ string_of_inet_addr a in
+ let service =
+ try
+ if List.mem NI_NUMERICSERV opts then raise Not_found;
+ let kind = if List.mem NI_DGRAM opts then "udp" else "tcp" in
+ (getservbyport p kind).s_name
+ with Not_found ->
+ string_of_int p in
+ { ni_hostname = hostname; ni_service = service }
+
+let getnameinfo addr opts =
+ try
+ getnameinfo_system addr opts
+ with Invalid_argument _ ->
+ getnameinfo_emulation addr opts
+
+type terminal_io = {
+ mutable c_ignbrk: bool;
+ mutable c_brkint: bool;
+ mutable c_ignpar: bool;
+ mutable c_parmrk: bool;
+ mutable c_inpck: bool;
+ mutable c_istrip: bool;
+ mutable c_inlcr: bool;
+ mutable c_igncr: bool;
+ mutable c_icrnl: bool;
+ mutable c_ixon: bool;
+ mutable c_ixoff: bool;
+ mutable c_opost: bool;
+ mutable c_obaud: int;
+ mutable c_ibaud: int;
+ mutable c_csize: int;
+ mutable c_cstopb: int;
+ mutable c_cread: bool;
+ mutable c_parenb: bool;
+ mutable c_parodd: bool;
+ mutable c_hupcl: bool;
+ mutable c_clocal: bool;
+ mutable c_isig: bool;
+ mutable c_icanon: bool;
+ mutable c_noflsh: bool;
+ mutable c_echo: bool;
+ mutable c_echoe: bool;
+ mutable c_echok: bool;
+ mutable c_echonl: bool;
+ mutable c_vintr: char;
+ mutable c_vquit: char;
+ mutable c_verase: char;
+ mutable c_vkill: char;
+ mutable c_veof: char;
+ mutable c_veol: char;
+ mutable c_vmin: int;
+ mutable c_vtime: int;
+ mutable c_vstart: char;
+ mutable c_vstop: char
+ }
+
+external tcgetattr: file_descr -> terminal_io = "unix_tcgetattr"
+
+type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
+
+external tcsetattr: file_descr -> setattr_when -> terminal_io -> unit
+ = "unix_tcsetattr"
+external tcsendbreak: file_descr -> int -> unit = "unix_tcsendbreak"
+external tcdrain: file_descr -> unit = "unix_tcdrain"
+
+type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
+
+external tcflush: file_descr -> flush_queue -> unit = "unix_tcflush"
+
+type flow_action = TCOOFF | TCOON | TCIOFF | TCION
+
+external tcflow: file_descr -> flow_action -> unit = "unix_tcflow"
+
+external setsid : unit -> int = "unix_setsid"
+
+(* High-level process management (system, popen) *)
+
+let rec waitpid_non_intr pid =
+ try waitpid [] pid
+ with Unix_error (EINTR, _, _) -> waitpid_non_intr pid
+
+let system cmd =
+ match fork() with
+ 0 -> begin try
+ execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
+ with _ ->
+ exit 127
+ end
+ | id -> snd(waitpid_non_intr id)
+
+let rec safe_dup fd =
+ let new_fd = dup fd in
+ if new_fd >= 3 then
+ new_fd
+ else begin
+ let res = safe_dup fd in
+ close new_fd;
+ res
+ end
+
+let safe_close fd =
+ try close fd with Unix_error(_,_,_) -> ()
+
+let perform_redirections new_stdin new_stdout new_stderr =
+ let newnewstdin = safe_dup new_stdin in
+ let newnewstdout = safe_dup new_stdout in
+ let newnewstderr = safe_dup new_stderr in
+ safe_close new_stdin;
+ safe_close new_stdout;
+ safe_close new_stderr;
+ dup2 newnewstdin stdin; close newnewstdin;
+ dup2 newnewstdout stdout; close newnewstdout;
+ dup2 newnewstderr stderr; close newnewstderr
+
+let create_process cmd args new_stdin new_stdout new_stderr =
+ match fork() with
+ 0 ->
+ begin try
+ perform_redirections new_stdin new_stdout new_stderr;
+ execvp cmd args
+ with _ ->
+ exit 127
+ end
+ | id -> id
+
+let create_process_env cmd args env new_stdin new_stdout new_stderr =
+ match fork() with
+ 0 ->
+ begin try
+ perform_redirections new_stdin new_stdout new_stderr;
+ execvpe cmd args env
+ with _ ->
+ exit 127
+ end
+ | id -> id
+
+type popen_process =
+ Process of in_channel * out_channel
+ | Process_in of in_channel
+ | Process_out of out_channel
+ | Process_full of in_channel * out_channel * in_channel
+
+let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t)
+
+let open_proc cmd proc input output toclose =
+ let cloexec = List.for_all try_set_close_on_exec toclose in
+ match fork() with
+ 0 -> if input <> stdin then begin dup2 input stdin; close input end;
+ if output <> stdout then begin dup2 output stdout; close output end;
+ if not cloexec then List.iter close toclose;
+ begin try execv "/bin/sh" [| "/bin/sh"; "-c"; cmd |]
+ with _ -> exit 127
+ end
+ | id -> Hashtbl.add popen_processes proc id
+
+let open_process_in cmd =
+ let (in_read, in_write) = pipe() in
+ let inchan = in_channel_of_descr in_read in
+ begin
+ try
+ open_proc cmd (Process_in inchan) stdin in_write [in_read];
+ with e ->
+ close_in inchan;
+ close in_write;
+ raise e
+ end;
+ close in_write;
+ inchan
+
+let open_process_out cmd =
+ let (out_read, out_write) = pipe() in
+ let outchan = out_channel_of_descr out_write in
+ begin
+ try
+ open_proc cmd (Process_out outchan) out_read stdout [out_write];
+ with e ->
+ close_out outchan;
+ close out_read;
+ raise e
+ end;
+ close out_read;
+ outchan
+
+let open_process cmd =
+ let (in_read, in_write) = pipe() in
+ let fds_to_close = ref [in_read;in_write] in
+ try
+ let (out_read, out_write) = pipe() in
+ fds_to_close := [in_read;in_write;out_read;out_write];
+ let inchan = in_channel_of_descr in_read in
+ let outchan = out_channel_of_descr out_write in
+ open_proc cmd (Process(inchan, outchan)) out_read in_write
+ [in_read; out_write];
+ close out_read;
+ close in_write;
+ (inchan, outchan)
+ with e ->
+ List.iter close !fds_to_close;
+ raise e
+
+let open_proc_full cmd env proc input output error toclose =
+ let cloexec = List.for_all try_set_close_on_exec toclose in
+ match fork() with
+ 0 -> dup2 input stdin; close input;
+ dup2 output stdout; close output;
+ dup2 error stderr; close error;
+ if not cloexec then List.iter close toclose;
+ begin try execve "/bin/sh" [| "/bin/sh"; "-c"; cmd |] env
+ with _ -> exit 127
+ end
+ | id -> Hashtbl.add popen_processes proc id
+
+let open_process_full cmd env =
+ let (in_read, in_write) = pipe() in
+ let fds_to_close = ref [in_read;in_write] in
+ try
+ let (out_read, out_write) = pipe() in
+ fds_to_close := out_read::out_write:: !fds_to_close;
+ let (err_read, err_write) = pipe() in
+ fds_to_close := err_read::err_write:: !fds_to_close;
+ let inchan = in_channel_of_descr in_read in
+ let outchan = out_channel_of_descr out_write in
+ let errchan = in_channel_of_descr err_read in
+ open_proc_full cmd env (Process_full(inchan, outchan, errchan))
+ out_read in_write err_write [in_read; out_write; err_read];
+ close out_read;
+ close in_write;
+ close err_write;
+ (inchan, outchan, errchan)
+ with e ->
+ List.iter close !fds_to_close;
+ raise e
+
+let find_proc_id fun_name proc =
+ try
+ let pid = Hashtbl.find popen_processes proc in
+ Hashtbl.remove popen_processes proc;
+ pid
+ with Not_found ->
+ raise(Unix_error(EBADF, fun_name, ""))
+
+let close_process_in inchan =
+ let pid = find_proc_id "close_process_in" (Process_in inchan) in
+ close_in inchan;
+ snd(waitpid_non_intr pid)
+
+let close_process_out outchan =
+ let pid = find_proc_id "close_process_out" (Process_out outchan) in
+ close_out outchan;
+ snd(waitpid_non_intr pid)
+
+let close_process (inchan, outchan) =
+ let pid = find_proc_id "close_process" (Process(inchan, outchan)) in
+ close_in inchan;
+ begin try close_out outchan with Sys_error _ -> () end;
+ snd(waitpid_non_intr pid)
+
+let close_process_full (inchan, outchan, errchan) =
+ let pid =
+ find_proc_id "close_process_full"
+ (Process_full(inchan, outchan, errchan)) in
+ close_in inchan;
+ begin try close_out outchan with Sys_error _ -> () end;
+ close_in errchan;
+ snd(waitpid_non_intr pid)
+
+(* High-level network functions *)
+
+let open_connection sockaddr =
+ let sock =
+ socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
+ try
+ connect sock sockaddr;
+ ignore(try_set_close_on_exec sock);
+ (in_channel_of_descr sock, out_channel_of_descr sock)
+ with exn ->
+ close sock; raise exn
+
+let shutdown_connection inchan =
+ shutdown (descr_of_in_channel inchan) SHUTDOWN_SEND
+
+let rec accept_non_intr s =
+ try accept s
+ with Unix_error (EINTR, _, _) -> accept_non_intr s
+
+let establish_server server_fun sockaddr =
+ let sock =
+ socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
+ setsockopt sock SO_REUSEADDR true;
+ bind sock sockaddr;
+ listen sock 5;
+ while true do
+ let (s, caller) = accept_non_intr sock in
+ (* The "double fork" trick, the process which calls server_fun will not
+ leave a zombie process *)
+ match fork() with
+ 0 -> if fork() <> 0 then exit 0; (* The son exits, the grandson works *)
+ close sock;
+ ignore(try_set_close_on_exec s);
+ let inchan = in_channel_of_descr s in
+ let outchan = out_channel_of_descr s in
+ server_fun inchan outchan;
+ (* Do not close inchan nor outchan, as the server_fun could
+ have done it already, and we are about to exit anyway
+ (PR#3794) *)
+ exit 0
+ | id -> close s; ignore(waitpid_non_intr id) (* Reclaim the son *)
+ done
diff --git a/otherlibs/unix/unix.mli b/otherlibs/unix/unix.mli
new file mode 100644
index 0000000000..dea5cb30be
--- /dev/null
+++ b/otherlibs/unix/unix.mli
@@ -0,0 +1,1377 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Interface to the Unix system.
+
+ Note: all the functions of this module (except [error_message] and
+ [handle_unix_error]) are liable to raise the [Unix_error]
+ exception whenever the underlying system call signals an error. *)
+
+
+(** {6 Error report} *)
+
+
+type error =
+ E2BIG (** Argument list too long *)
+ | EACCES (** Permission denied *)
+ | EAGAIN (** Resource temporarily unavailable; try again *)
+ | EBADF (** Bad file descriptor *)
+ | EBUSY (** Resource unavailable *)
+ | ECHILD (** No child process *)
+ | EDEADLK (** Resource deadlock would occur *)
+ | EDOM (** Domain error for math functions, etc. *)
+ | EEXIST (** File exists *)
+ | EFAULT (** Bad address *)
+ | EFBIG (** File too large *)
+ | EINTR (** Function interrupted by signal *)
+ | EINVAL (** Invalid argument *)
+ | EIO (** Hardware I/O error *)
+ | EISDIR (** Is a directory *)
+ | EMFILE (** Too many open files by the process *)
+ | EMLINK (** Too many links *)
+ | ENAMETOOLONG (** Filename too long *)
+ | ENFILE (** Too many open files in the system *)
+ | ENODEV (** No such device *)
+ | ENOENT (** No such file or directory *)
+ | ENOEXEC (** Not an executable file *)
+ | ENOLCK (** No locks available *)
+ | ENOMEM (** Not enough memory *)
+ | ENOSPC (** No space left on device *)
+ | ENOSYS (** Function not supported *)
+ | ENOTDIR (** Not a directory *)
+ | ENOTEMPTY (** Directory not empty *)
+ | ENOTTY (** Inappropriate I/O control operation *)
+ | ENXIO (** No such device or address *)
+ | EPERM (** Operation not permitted *)
+ | EPIPE (** Broken pipe *)
+ | ERANGE (** Result too large *)
+ | EROFS (** Read-only file system *)
+ | ESPIPE (** Invalid seek e.g. on a pipe *)
+ | ESRCH (** No such process *)
+ | EXDEV (** Invalid link *)
+ | EWOULDBLOCK (** Operation would block *)
+ | EINPROGRESS (** Operation now in progress *)
+ | EALREADY (** Operation already in progress *)
+ | ENOTSOCK (** Socket operation on non-socket *)
+ | EDESTADDRREQ (** Destination address required *)
+ | EMSGSIZE (** Message too long *)
+ | EPROTOTYPE (** Protocol wrong type for socket *)
+ | ENOPROTOOPT (** Protocol not available *)
+ | EPROTONOSUPPORT (** Protocol not supported *)
+ | ESOCKTNOSUPPORT (** Socket type not supported *)
+ | EOPNOTSUPP (** Operation not supported on socket *)
+ | EPFNOSUPPORT (** Protocol family not supported *)
+ | EAFNOSUPPORT (** Address family not supported by protocol family *)
+ | EADDRINUSE (** Address already in use *)
+ | EADDRNOTAVAIL (** Can't assign requested address *)
+ | ENETDOWN (** Network is down *)
+ | ENETUNREACH (** Network is unreachable *)
+ | ENETRESET (** Network dropped connection on reset *)
+ | ECONNABORTED (** Software caused connection abort *)
+ | ECONNRESET (** Connection reset by peer *)
+ | ENOBUFS (** No buffer space available *)
+ | EISCONN (** Socket is already connected *)
+ | ENOTCONN (** Socket is not connected *)
+ | ESHUTDOWN (** Can't send after socket shutdown *)
+ | ETOOMANYREFS (** Too many references: can't splice *)
+ | ETIMEDOUT (** Connection timed out *)
+ | ECONNREFUSED (** Connection refused *)
+ | EHOSTDOWN (** Host is down *)
+ | EHOSTUNREACH (** No route to host *)
+ | ELOOP (** Too many levels of symbolic links *)
+ | EOVERFLOW (** File size or position not representable *)
+
+ | EUNKNOWNERR of int (** Unknown error *)
+(** The type of error codes.
+ Errors defined in the POSIX standard
+ and additional errors from UNIX98 and BSD.
+ All other errors are mapped to EUNKNOWNERR.
+*)
+
+
+exception Unix_error of error * string * string
+(** Raised by the system calls below when an error is encountered.
+ The first component is the error code; the second component
+ is the function name; the third component is the string parameter
+ to the function, if it has one, or the empty string otherwise. *)
+
+val error_message : error -> string
+(** Return a string describing the given error code. *)
+
+val handle_unix_error : ('a -> 'b) -> 'a -> 'b
+(** [handle_unix_error f x] applies [f] to [x] and returns the result.
+ If the exception [Unix_error] is raised, it prints a message
+ describing the error and exits with code 2. *)
+
+
+(** {6 Access to the process environment} *)
+
+
+val environment : unit -> string array
+(** Return the process environment, as an array of strings
+ with the format ``variable=value''. *)
+
+val getenv : string -> string
+(** Return the value associated to a variable in the process
+ environment. Raise [Not_found] if the variable is unbound.
+ (This function is identical to {!Sys.getenv}.) *)
+
+val putenv : string -> string -> unit
+(** [Unix.putenv name value] sets the value associated to a
+ variable in the process environment.
+ [name] is the name of the environment variable,
+ and [value] its new associated value. *)
+
+
+(** {6 Process handling} *)
+
+
+type process_status =
+ WEXITED of int
+ (** The process terminated normally by [exit];
+ the argument is the return code. *)
+ | WSIGNALED of int
+ (** The process was killed by a signal;
+ the argument is the signal number. *)
+ | WSTOPPED of int
+ (** The process was stopped by a signal; the argument is the
+ signal number. *)
+(** The termination status of a process. See module {!Sys} for the
+ definitions of the standard signal numbers. Note that they are
+ not the numbers used by the OS. *)
+
+
+type wait_flag =
+ WNOHANG (** do not block if no child has
+ died yet, but immediately return with a pid equal to 0.*)
+ | WUNTRACED (** report also the children that receive stop signals. *)
+(** Flags for {!Unix.waitpid}. *)
+
+val execv : string -> string array -> 'a
+(** [execv prog args] execute the program in file [prog], with
+ the arguments [args], and the current process environment.
+ These [execv*] functions never return: on success, the current
+ program is replaced by the new one;
+ on failure, a {!Unix.Unix_error} exception is raised. *)
+
+val execve : string -> string array -> string array -> 'a
+(** Same as {!Unix.execv}, except that the third argument provides the
+ environment to the program executed. *)
+
+val execvp : string -> string array -> 'a
+(** Same as {!Unix.execv}, except that
+ the program is searched in the path. *)
+
+val execvpe : string -> string array -> string array -> 'a
+(** Same as {!Unix.execve}, except that
+ the program is searched in the path. *)
+
+val fork : unit -> int
+(** Fork a new process. The returned integer is 0 for the child
+ process, the pid of the child process for the parent process. *)
+
+val wait : unit -> int * process_status
+(** Wait until one of the children processes die, and return its pid
+ and termination status. *)
+
+val waitpid : wait_flag list -> int -> int * process_status
+(** Same as {!Unix.wait}, but waits for the child process whose pid is given.
+ A pid of [-1] means wait for any child.
+ A pid of [0] means wait for any child in the same process group
+ as the current process.
+ Negative pid arguments represent process groups.
+ The list of options indicates whether [waitpid] should return
+ immediately without waiting, and whether it should report stopped
+ children. *)
+
+val system : string -> process_status
+(** Execute the given command, wait until it terminates, and return
+ its termination status. The string is interpreted by the shell
+ [/bin/sh] and therefore can contain redirections, quotes, variables,
+ etc. The result [WEXITED 127] indicates that the shell couldn't
+ be executed. *)
+
+val getpid : unit -> int
+(** Return the pid of the process. *)
+
+val getppid : unit -> int
+(** Return the pid of the parent process. *)
+
+val nice : int -> int
+(** Change the process priority. The integer argument is added to the
+ ``nice'' value. (Higher values of the ``nice'' value mean
+ lower priorities.) Return the new nice value. *)
+
+
+(** {6 Basic file input/output} *)
+
+
+type file_descr
+(** The abstract type of file descriptors. *)
+
+val stdin : file_descr
+(** File descriptor for standard input.*)
+
+val stdout : file_descr
+(** File descriptor for standard output.*)
+
+val stderr : file_descr
+(** File descriptor for standard error. *)
+
+type open_flag =
+ O_RDONLY (** Open for reading *)
+ | O_WRONLY (** Open for writing *)
+ | O_RDWR (** Open for reading and writing *)
+ | O_NONBLOCK (** Open in non-blocking mode *)
+ | O_APPEND (** Open for append *)
+ | O_CREAT (** Create if nonexistent *)
+ | O_TRUNC (** Truncate to 0 length if existing *)
+ | O_EXCL (** Fail if existing *)
+ | O_NOCTTY (** Don't make this dev a controlling tty *)
+ | O_DSYNC (** Writes complete as `Synchronised I/O data
+ integrity completion' *)
+ | O_SYNC (** Writes complete as `Synchronised I/O file
+ integrity completion' *)
+ | O_RSYNC (** Reads complete as writes (depending on
+ O_SYNC/O_DSYNC) *)
+ | O_SHARE_DELETE (** Windows only: allow the file to be deleted
+ while still open *)
+ | O_CLOEXEC (** Set the close-on-exec flag on the
+ descriptor returned by {!openfile} *)
+(** The flags to {!Unix.openfile}. *)
+
+
+type file_perm = int
+(** The type of file access rights, e.g. [0o640] is read and write for user,
+ read for group, none for others *)
+
+val openfile : string -> open_flag list -> file_perm -> file_descr
+(** Open the named file with the given flags. Third argument is the
+ permissions to give to the file if it is created (see
+ {!umask}). Return a file descriptor on the named file. *)
+
+val close : file_descr -> unit
+(** Close a file descriptor. *)
+
+val read : file_descr -> bytes -> int -> int -> int
+(** [read fd buff ofs len] reads [len] bytes from descriptor [fd],
+ storing them in byte sequence [buff], starting at position [ofs] in
+ [buff]. Return the number of bytes actually read. *)
+
+val write : file_descr -> bytes -> int -> int -> int
+(** [write fd buff ofs len] writes [len] bytes to descriptor [fd],
+ taking them from byte sequence [buff], starting at position [ofs]
+ in [buff]. Return the number of bytes actually written. [write]
+ repeats the writing operation until all bytes have been written or
+ an error occurs. *)
+
+val single_write : file_descr -> bytes -> int -> int -> int
+(** Same as [write], but attempts to write only once.
+ Thus, if an error occurs, [single_write] guarantees that no data
+ has been written. *)
+
+val write_substring : file_descr -> string -> int -> int -> int
+(** Same as [write], but take the data from a string instead of a byte
+ sequence. *)
+
+val single_write_substring : file_descr -> string -> int -> int -> int
+(** Same as [single_write], but take the data from a string instead of
+ a byte sequence. *)
+
+(** {6 Interfacing with the standard input/output library} *)
+
+
+
+val in_channel_of_descr : file_descr -> in_channel
+(** Create an input channel reading from the given descriptor.
+ The channel is initially in binary mode; use
+ [set_binary_mode_in ic false] if text mode is desired.
+ Beware that channels are buffered so more characters may have been
+ read from the file descriptor than those accessed using channel functions.
+ Channels also keep a copy of the current position in the file.
+
+ You need to explicitly close all channels created with this function.
+ Closing the channel also closes the underlying file descriptor (unless
+ it was already closed). *)
+
+val out_channel_of_descr : file_descr -> out_channel
+(** Create an output channel writing on the given descriptor.
+ The channel is initially in binary mode; use
+ [set_binary_mode_out oc false] if text mode is desired.
+ Beware that channels are buffered so you may have to [flush] them
+ to ensure that all data has been sent to the file descriptor.
+ Channels also keep a copy of the current position in the file.
+
+ You need to explicitly close all channels created with this function.
+ Closing the channel flushes the data and closes the underlying file
+ descriptor (unless it has already been closed, in which case the
+ buffered data is lost).*)
+
+val descr_of_in_channel : in_channel -> file_descr
+(** Return the descriptor corresponding to an input channel. *)
+
+val descr_of_out_channel : out_channel -> file_descr
+(** Return the descriptor corresponding to an output channel. *)
+
+
+(** {6 Seeking and truncating} *)
+
+
+type seek_command =
+ SEEK_SET (** indicates positions relative to the beginning of the file *)
+ | SEEK_CUR (** indicates positions relative to the current position *)
+ | SEEK_END (** indicates positions relative to the end of the file *)
+(** Positioning modes for {!Unix.lseek}. *)
+
+
+val lseek : file_descr -> int -> seek_command -> int
+(** Set the current position for a file descriptor, and return the resulting
+ offset (from the beginning of the file). *)
+
+val truncate : string -> int -> unit
+(** Truncates the named file to the given size. *)
+
+val ftruncate : file_descr -> int -> unit
+(** Truncates the file corresponding to the given descriptor
+ to the given size. *)
+
+
+(** {6 File status} *)
+
+
+type file_kind =
+ S_REG (** Regular file *)
+ | S_DIR (** Directory *)
+ | S_CHR (** Character device *)
+ | S_BLK (** Block device *)
+ | S_LNK (** Symbolic link *)
+ | S_FIFO (** Named pipe *)
+ | S_SOCK (** Socket *)
+
+type stats =
+ { st_dev : int; (** Device number *)
+ st_ino : int; (** Inode number *)
+ st_kind : file_kind; (** Kind of the file *)
+ st_perm : file_perm; (** Access rights *)
+ st_nlink : int; (** Number of links *)
+ st_uid : int; (** User id of the owner *)
+ st_gid : int; (** Group ID of the file's group *)
+ st_rdev : int; (** Device minor number *)
+ st_size : int; (** Size in bytes *)
+ st_atime : float; (** Last access time *)
+ st_mtime : float; (** Last modification time *)
+ st_ctime : float; (** Last status change time *)
+ }
+(** The information returned by the {!Unix.stat} calls. *)
+
+val stat : string -> stats
+(** Return the information for the named file. *)
+
+val lstat : string -> stats
+(** Same as {!Unix.stat}, but in case the file is a symbolic link,
+ return the information for the link itself. *)
+
+val fstat : file_descr -> stats
+(** Return the information for the file associated with the given
+ descriptor. *)
+
+val isatty : file_descr -> bool
+(** Return [true] if the given file descriptor refers to a terminal or
+ console window, [false] otherwise. *)
+
+(** {6 File operations on large files} *)
+
+module LargeFile :
+ sig
+ val lseek : file_descr -> int64 -> seek_command -> int64
+ val truncate : string -> int64 -> unit
+ val ftruncate : file_descr -> int64 -> unit
+ type stats =
+ { st_dev : int; (** Device number *)
+ st_ino : int; (** Inode number *)
+ st_kind : file_kind; (** Kind of the file *)
+ st_perm : file_perm; (** Access rights *)
+ st_nlink : int; (** Number of links *)
+ st_uid : int; (** User id of the owner *)
+ st_gid : int; (** Group ID of the file's group *)
+ st_rdev : int; (** Device minor number *)
+ st_size : int64; (** Size in bytes *)
+ st_atime : float; (** Last access time *)
+ st_mtime : float; (** Last modification time *)
+ st_ctime : float; (** Last status change time *)
+ }
+ val stat : string -> stats
+ val lstat : string -> stats
+ val fstat : file_descr -> stats
+ end
+(** File operations on large files.
+ This sub-module provides 64-bit variants of the functions
+ {!Unix.lseek} (for positioning a file descriptor),
+ {!Unix.truncate} and {!Unix.ftruncate} (for changing the size of a file),
+ and {!Unix.stat}, {!Unix.lstat} and {!Unix.fstat} (for obtaining
+ information on files). These alternate functions represent
+ positions and sizes by 64-bit integers (type [int64]) instead of
+ regular integers (type [int]), thus allowing operating on files
+ whose sizes are greater than [max_int]. *)
+
+
+(** {6 Operations on file names} *)
+
+
+val unlink : string -> unit
+(** Removes the named file *)
+
+val rename : string -> string -> unit
+(** [rename old new] changes the name of a file from [old] to [new]. *)
+
+val link : string -> string -> unit
+(** [link source dest] creates a hard link named [dest] to the file
+ named [source]. *)
+
+
+(** {6 File permissions and ownership} *)
+
+
+type access_permission =
+ R_OK (** Read permission *)
+ | W_OK (** Write permission *)
+ | X_OK (** Execution permission *)
+ | F_OK (** File exists *)
+(** Flags for the {!Unix.access} call. *)
+
+
+val chmod : string -> file_perm -> unit
+(** Change the permissions of the named file. *)
+
+val fchmod : file_descr -> file_perm -> unit
+(** Change the permissions of an opened file. *)
+
+val chown : string -> int -> int -> unit
+(** Change the owner uid and owner gid of the named file. *)
+
+val fchown : file_descr -> int -> int -> unit
+(** Change the owner uid and owner gid of an opened file. *)
+
+val umask : int -> int
+(** Set the process's file mode creation mask, and return the previous
+ mask. *)
+
+val access : string -> access_permission list -> unit
+(** Check that the process has the given permissions over the named
+ file. Raise [Unix_error] otherwise. *)
+
+
+(** {6 Operations on file descriptors} *)
+
+
+val dup : file_descr -> file_descr
+(** Return a new file descriptor referencing the same file as
+ the given descriptor. *)
+
+val dup2 : file_descr -> file_descr -> unit
+(** [dup2 fd1 fd2] duplicates [fd1] to [fd2], closing [fd2] if already
+ opened. *)
+
+val set_nonblock : file_descr -> unit
+(** Set the ``non-blocking'' flag on the given descriptor.
+ When the non-blocking flag is set, reading on a descriptor
+ on which there is temporarily no data available raises the
+ [EAGAIN] or [EWOULDBLOCK] error instead of blocking;
+ writing on a descriptor on which there is temporarily no room
+ for writing also raises [EAGAIN] or [EWOULDBLOCK]. *)
+
+val clear_nonblock : file_descr -> unit
+(** Clear the ``non-blocking'' flag on the given descriptor.
+ See {!Unix.set_nonblock}.*)
+
+val set_close_on_exec : file_descr -> unit
+(** Set the ``close-on-exec'' flag on the given descriptor.
+ A descriptor with the close-on-exec flag is automatically
+ closed when the current process starts another program with
+ one of the [exec] functions. *)
+
+val clear_close_on_exec : file_descr -> unit
+(** Clear the ``close-on-exec'' flag on the given descriptor.
+ See {!Unix.set_close_on_exec}.*)
+
+
+(** {6 Directories} *)
+
+
+val mkdir : string -> file_perm -> unit
+(** Create a directory with the given permissions (see {!umask}). *)
+
+val rmdir : string -> unit
+(** Remove an empty directory. *)
+
+val chdir : string -> unit
+(** Change the process working directory. *)
+
+val getcwd : unit -> string
+(** Return the name of the current working directory. *)
+
+val chroot : string -> unit
+(** Change the process root directory. *)
+
+type dir_handle
+(** The type of descriptors over opened directories. *)
+
+val opendir : string -> dir_handle
+(** Open a descriptor on a directory *)
+
+val readdir : dir_handle -> string
+(** Return the next entry in a directory.
+ @raise End_of_file when the end of the directory has been reached. *)
+
+val rewinddir : dir_handle -> unit
+(** Reposition the descriptor to the beginning of the directory *)
+
+val closedir : dir_handle -> unit
+(** Close a directory descriptor. *)
+
+
+
+(** {6 Pipes and redirections} *)
+
+
+val pipe : unit -> file_descr * file_descr
+(** Create a pipe. The first component of the result is opened
+ for reading, that's the exit to the pipe. The second component is
+ opened for writing, that's the entrance to the pipe. *)
+
+val mkfifo : string -> file_perm -> unit
+(** Create a named pipe with the given permissions (see {!umask}). *)
+
+
+(** {6 High-level process and redirection management} *)
+
+
+val create_process :
+ string -> string array -> file_descr -> file_descr -> file_descr -> int
+(** [create_process prog args new_stdin new_stdout new_stderr]
+ forks a new process that executes the program
+ in file [prog], with arguments [args]. The pid of the new
+ process is returned immediately; the new process executes
+ concurrently with the current process.
+ The standard input and outputs of the new process are connected
+ to the descriptors [new_stdin], [new_stdout] and [new_stderr].
+ Passing e.g. [stdout] for [new_stdout] prevents the redirection
+ and causes the new process to have the same standard output
+ as the current process.
+ The executable file [prog] is searched in the path.
+ The new process has the same environment as the current process. *)
+
+val create_process_env :
+ string -> string array -> string array -> file_descr -> file_descr ->
+ file_descr -> int
+(** [create_process_env prog args env new_stdin new_stdout new_stderr]
+ works as {!Unix.create_process}, except that the extra argument
+ [env] specifies the environment passed to the program. *)
+
+
+val open_process_in : string -> in_channel
+(** High-level pipe and process management. This function
+ runs the given command in parallel with the program.
+ The standard output of the command is redirected to a pipe,
+ which can be read via the returned input channel.
+ The command is interpreted by the shell [/bin/sh] (cf. [system]). *)
+
+val open_process_out : string -> out_channel
+(** Same as {!Unix.open_process_in}, but redirect the standard input of
+ the command to a pipe. Data written to the returned output channel
+ is sent to the standard input of the command.
+ Warning: writes on output channels are buffered, hence be careful
+ to call {!Pervasives.flush} at the right times to ensure
+ correct synchronization. *)
+
+val open_process : string -> in_channel * out_channel
+(** Same as {!Unix.open_process_out}, but redirects both the standard input
+ and standard output of the command to pipes connected to the two
+ returned channels. The input channel is connected to the output
+ of the command, and the output channel to the input of the command. *)
+
+val open_process_full :
+ string -> string array -> in_channel * out_channel * in_channel
+(** Similar to {!Unix.open_process}, but the second argument specifies
+ the environment passed to the command. The result is a triple
+ of channels connected respectively to the standard output, standard input,
+ and standard error of the command. *)
+
+val close_process_in : in_channel -> process_status
+(** Close channels opened by {!Unix.open_process_in},
+ wait for the associated command to terminate,
+ and return its termination status. *)
+
+val close_process_out : out_channel -> process_status
+(** Close channels opened by {!Unix.open_process_out},
+ wait for the associated command to terminate,
+ and return its termination status. *)
+
+val close_process : in_channel * out_channel -> process_status
+(** Close channels opened by {!Unix.open_process},
+ wait for the associated command to terminate,
+ and return its termination status. *)
+
+val close_process_full :
+ in_channel * out_channel * in_channel -> process_status
+(** Close channels opened by {!Unix.open_process_full},
+ wait for the associated command to terminate,
+ and return its termination status. *)
+
+
+(** {6 Symbolic links} *)
+
+
+val symlink : string -> string -> unit
+(** [symlink source dest] creates the file [dest] as a symbolic link
+ to the file [source]. *)
+
+val readlink : string -> string
+(** Read the contents of a link. *)
+
+
+(** {6 Polling} *)
+
+
+val select :
+ file_descr list -> file_descr list -> file_descr list -> float ->
+ file_descr list * file_descr list * file_descr list
+(** Wait until some input/output operations become possible on
+ some channels. The three list arguments are, respectively, a set
+ of descriptors to check for reading (first argument), for writing
+ (second argument), or for exceptional conditions (third argument).
+ The fourth argument is the maximal timeout, in seconds; a
+ negative fourth argument means no timeout (unbounded wait).
+ The result is composed of three sets of descriptors: those ready
+ for reading (first component), ready for writing (second component),
+ and over which an exceptional condition is pending (third
+ component). *)
+
+(** {6 Locking} *)
+
+
+type lock_command =
+ F_ULOCK (** Unlock a region *)
+ | F_LOCK (** Lock a region for writing, and block if already locked *)
+ | F_TLOCK (** Lock a region for writing, or fail if already locked *)
+ | F_TEST (** Test a region for other process locks *)
+ | F_RLOCK (** Lock a region for reading, and block if already locked *)
+ | F_TRLOCK (** Lock a region for reading, or fail if already locked *)
+(** Commands for {!Unix.lockf}. *)
+
+val lockf : file_descr -> lock_command -> int -> unit
+(** [lockf fd cmd size] puts a lock on a region of the file opened
+ as [fd]. The region starts at the current read/write position for
+ [fd] (as set by {!Unix.lseek}), and extends [size] bytes forward if
+ [size] is positive, [size] bytes backwards if [size] is negative,
+ or to the end of the file if [size] is zero.
+ A write lock prevents any other
+ process from acquiring a read or write lock on the region.
+ A read lock prevents any other
+ process from acquiring a write lock on the region, but lets
+ other processes acquire read locks on it.
+
+ The [F_LOCK] and [F_TLOCK] commands attempts to put a write lock
+ on the specified region.
+ The [F_RLOCK] and [F_TRLOCK] commands attempts to put a read lock
+ on the specified region.
+ If one or several locks put by another process prevent the current process
+ from acquiring the lock, [F_LOCK] and [F_RLOCK] block until these locks
+ are removed, while [F_TLOCK] and [F_TRLOCK] fail immediately with an
+ exception.
+ The [F_ULOCK] removes whatever locks the current process has on
+ the specified region.
+ Finally, the [F_TEST] command tests whether a write lock can be
+ acquired on the specified region, without actually putting a lock.
+ It returns immediately if successful, or fails otherwise. *)
+
+
+(** {6 Signals}
+ Note: installation of signal handlers is performed via
+ the functions {!Sys.signal} and {!Sys.set_signal}.
+*)
+
+val kill : int -> int -> unit
+(** [kill pid sig] sends signal number [sig] to the process
+ with id [pid]. Under Windows, only the [Sys.sigkill] signal
+ is emulated. *)
+
+type sigprocmask_command =
+ SIG_SETMASK
+ | SIG_BLOCK
+ | SIG_UNBLOCK
+
+val sigprocmask : sigprocmask_command -> int list -> int list
+(** [sigprocmask cmd sigs] changes the set of blocked signals.
+ If [cmd] is [SIG_SETMASK], blocked signals are set to those in
+ the list [sigs].
+ If [cmd] is [SIG_BLOCK], the signals in [sigs] are added to
+ the set of blocked signals.
+ If [cmd] is [SIG_UNBLOCK], the signals in [sigs] are removed
+ from the set of blocked signals.
+ [sigprocmask] returns the set of previously blocked signals. *)
+
+val sigpending : unit -> int list
+(** Return the set of blocked signals that are currently pending. *)
+
+val sigsuspend : int list -> unit
+(** [sigsuspend sigs] atomically sets the blocked signals to [sigs]
+ and waits for a non-ignored, non-blocked signal to be delivered.
+ On return, the blocked signals are reset to their initial value. *)
+
+val pause : unit -> unit
+(** Wait until a non-ignored, non-blocked signal is delivered. *)
+
+
+(** {6 Time functions} *)
+
+
+type process_times =
+ { tms_utime : float; (** User time for the process *)
+ tms_stime : float; (** System time for the process *)
+ tms_cutime : float; (** User time for the children processes *)
+ tms_cstime : float; (** System time for the children processes *)
+ }
+(** The execution times (CPU times) of a process. *)
+
+type tm =
+ { tm_sec : int; (** Seconds 0..60 *)
+ tm_min : int; (** Minutes 0..59 *)
+ tm_hour : int; (** Hours 0..23 *)
+ tm_mday : int; (** Day of month 1..31 *)
+ tm_mon : int; (** Month of year 0..11 *)
+ tm_year : int; (** Year - 1900 *)
+ tm_wday : int; (** Day of week (Sunday is 0) *)
+ tm_yday : int; (** Day of year 0..365 *)
+ tm_isdst : bool; (** Daylight time savings in effect *)
+ }
+(** The type representing wallclock time and calendar date. *)
+
+
+val time : unit -> float
+(** Return the current time since 00:00:00 GMT, Jan. 1, 1970,
+ in seconds. *)
+
+val gettimeofday : unit -> float
+(** Same as {!Unix.time}, but with resolution better than 1 second. *)
+
+val gmtime : float -> tm
+(** Convert a time in seconds, as returned by {!Unix.time}, into a date and
+ a time. Assumes UTC (Coordinated Universal Time), also known as GMT. *)
+
+val localtime : float -> tm
+(** Convert a time in seconds, as returned by {!Unix.time}, into a date and
+ a time. Assumes the local time zone. *)
+
+val mktime : tm -> float * tm
+(** Convert a date and time, specified by the [tm] argument, into
+ a time in seconds, as returned by {!Unix.time}. The [tm_isdst],
+ [tm_wday] and [tm_yday] fields of [tm] are ignored. Also return a
+ normalized copy of the given [tm] record, with the [tm_wday],
+ [tm_yday], and [tm_isdst] fields recomputed from the other fields,
+ and the other fields normalized (so that, e.g., 40 October is
+ changed into 9 November). The [tm] argument is interpreted in the
+ local time zone. *)
+
+val alarm : int -> int
+(** Schedule a [SIGALRM] signal after the given number of seconds. *)
+
+val sleep : int -> unit
+(** Stop execution for the given number of seconds. *)
+
+val times : unit -> process_times
+(** Return the execution times of the process. *)
+
+val utimes : string -> float -> float -> unit
+(** Set the last access time (second arg) and last modification time
+ (third arg) for a file. Times are expressed in seconds from
+ 00:00:00 GMT, Jan. 1, 1970. A time of [0.0] is interpreted as the
+ current time. *)
+
+type interval_timer =
+ ITIMER_REAL
+ (** decrements in real time, and sends the signal [SIGALRM] when
+ expired.*)
+ | ITIMER_VIRTUAL
+ (** decrements in process virtual time, and sends [SIGVTALRM]
+ when expired. *)
+ | ITIMER_PROF
+ (** (for profiling) decrements both when the process
+ is running and when the system is running on behalf of the
+ process; it sends [SIGPROF] when expired. *)
+(** The three kinds of interval timers. *)
+
+type interval_timer_status =
+ { it_interval : float; (** Period *)
+ it_value : float; (** Current value of the timer *)
+ }
+(** The type describing the status of an interval timer *)
+
+val getitimer : interval_timer -> interval_timer_status
+(** Return the current status of the given interval timer. *)
+
+val setitimer :
+ interval_timer -> interval_timer_status -> interval_timer_status
+(** [setitimer t s] sets the interval timer [t] and returns
+ its previous status. The [s] argument is interpreted as follows:
+ [s.it_value], if nonzero, is the time to the next timer expiration;
+ [s.it_interval], if nonzero, specifies a value to
+ be used in reloading [it_value] when the timer expires.
+ Setting [s.it_value] to zero disables the timer.
+ Setting [s.it_interval] to zero causes the timer to be disabled
+ after its next expiration. *)
+
+
+(** {6 User id, group id} *)
+
+
+val getuid : unit -> int
+(** Return the user id of the user executing the process. *)
+
+val geteuid : unit -> int
+(** Return the effective user id under which the process runs. *)
+
+val setuid : int -> unit
+(** Set the real user id and effective user id for the process. *)
+
+val getgid : unit -> int
+(** Return the group id of the user executing the process. *)
+
+val getegid : unit -> int
+(** Return the effective group id under which the process runs. *)
+
+val setgid : int -> unit
+(** Set the real group id and effective group id for the process. *)
+
+val getgroups : unit -> int array
+(** Return the list of groups to which the user executing the process
+ belongs. *)
+
+val setgroups : int array -> unit
+ (** [setgroups groups] sets the supplementary group IDs for the
+ calling process. Appropriate privileges are required. *)
+
+val initgroups : string -> int -> unit
+ (** [initgroups user group] initializes the group access list by
+ reading the group database /etc/group and using all groups of
+ which [user] is a member. The additional group [group] is also
+ added to the list. *)
+
+type passwd_entry =
+ { pw_name : string;
+ pw_passwd : string;
+ pw_uid : int;
+ pw_gid : int;
+ pw_gecos : string;
+ pw_dir : string;
+ pw_shell : string
+ }
+(** Structure of entries in the [passwd] database. *)
+
+type group_entry =
+ { gr_name : string;
+ gr_passwd : string;
+ gr_gid : int;
+ gr_mem : string array
+ }
+(** Structure of entries in the [groups] database. *)
+
+val getlogin : unit -> string
+(** Return the login name of the user executing the process. *)
+
+val getpwnam : string -> passwd_entry
+(** Find an entry in [passwd] with the given name, or raise
+ [Not_found]. *)
+
+val getgrnam : string -> group_entry
+(** Find an entry in [group] with the given name, or raise
+ [Not_found]. *)
+
+val getpwuid : int -> passwd_entry
+(** Find an entry in [passwd] with the given user id, or raise
+ [Not_found]. *)
+
+val getgrgid : int -> group_entry
+(** Find an entry in [group] with the given group id, or raise
+ [Not_found]. *)
+
+
+(** {6 Internet addresses} *)
+
+
+type inet_addr
+(** The abstract type of Internet addresses. *)
+
+val inet_addr_of_string : string -> inet_addr
+(** Conversion from the printable representation of an Internet
+ address to its internal representation. The argument string
+ consists of 4 numbers separated by periods ([XXX.YYY.ZZZ.TTT])
+ for IPv4 addresses, and up to 8 numbers separated by colons
+ for IPv6 addresses. Raise [Failure] when given a string that
+ does not match these formats. *)
+
+val string_of_inet_addr : inet_addr -> string
+(** Return the printable representation of the given Internet address.
+ See {!Unix.inet_addr_of_string} for a description of the
+ printable representation. *)
+
+val inet_addr_any : inet_addr
+(** A special IPv4 address, for use only with [bind], representing
+ all the Internet addresses that the host machine possesses. *)
+
+val inet_addr_loopback : inet_addr
+(** A special IPv4 address representing the host machine ([127.0.0.1]). *)
+
+val inet6_addr_any : inet_addr
+(** A special IPv6 address, for use only with [bind], representing
+ all the Internet addresses that the host machine possesses. *)
+
+val inet6_addr_loopback : inet_addr
+(** A special IPv6 address representing the host machine ([::1]). *)
+
+
+(** {6 Sockets} *)
+
+
+type socket_domain =
+ PF_UNIX (** Unix domain *)
+ | PF_INET (** Internet domain (IPv4) *)
+ | PF_INET6 (** Internet domain (IPv6) *)
+(** The type of socket domains. Not all platforms support
+ IPv6 sockets (type [PF_INET6]). *)
+
+type socket_type =
+ SOCK_STREAM (** Stream socket *)
+ | SOCK_DGRAM (** Datagram socket *)
+ | SOCK_RAW (** Raw socket *)
+ | SOCK_SEQPACKET (** Sequenced packets socket *)
+(** The type of socket kinds, specifying the semantics of
+ communications. *)
+
+type sockaddr =
+ ADDR_UNIX of string
+ | ADDR_INET of inet_addr * int
+(** The type of socket addresses. [ADDR_UNIX name] is a socket
+ address in the Unix domain; [name] is a file name in the file
+ system. [ADDR_INET(addr,port)] is a socket address in the Internet
+ domain; [addr] is the Internet address of the machine, and
+ [port] is the port number. *)
+
+val socket : socket_domain -> socket_type -> int -> file_descr
+(** Create a new socket in the given domain, and with the
+ given kind. The third argument is the protocol type; 0 selects
+ the default protocol for that kind of sockets. *)
+
+val domain_of_sockaddr: sockaddr -> socket_domain
+(** Return the socket domain adequate for the given socket address. *)
+
+val socketpair :
+ socket_domain -> socket_type -> int -> file_descr * file_descr
+(** Create a pair of unnamed sockets, connected together. *)
+
+val accept : file_descr -> file_descr * sockaddr
+(** Accept connections on the given socket. The returned descriptor
+ is a socket connected to the client; the returned address is
+ the address of the connecting client. *)
+
+val bind : file_descr -> sockaddr -> unit
+(** Bind a socket to an address. *)
+
+val connect : file_descr -> sockaddr -> unit
+(** Connect a socket to an address. *)
+
+val listen : file_descr -> int -> unit
+(** Set up a socket for receiving connection requests. The integer
+ argument is the maximal number of pending requests. *)
+
+type shutdown_command =
+ SHUTDOWN_RECEIVE (** Close for receiving *)
+ | SHUTDOWN_SEND (** Close for sending *)
+ | SHUTDOWN_ALL (** Close both *)
+(** The type of commands for [shutdown]. *)
+
+
+val shutdown : file_descr -> shutdown_command -> unit
+(** Shutdown a socket connection. [SHUTDOWN_SEND] as second argument
+ causes reads on the other end of the connection to return
+ an end-of-file condition.
+ [SHUTDOWN_RECEIVE] causes writes on the other end of the connection
+ to return a closed pipe condition ([SIGPIPE] signal). *)
+
+val getsockname : file_descr -> sockaddr
+(** Return the address of the given socket. *)
+
+val getpeername : file_descr -> sockaddr
+(** Return the address of the host connected to the given socket. *)
+
+type msg_flag =
+ MSG_OOB
+ | MSG_DONTROUTE
+ | MSG_PEEK
+(** The flags for {!Unix.recv}, {!Unix.recvfrom},
+ {!Unix.send} and {!Unix.sendto}. *)
+
+val recv : file_descr -> bytes -> int -> int -> msg_flag list -> int
+(** Receive data from a connected socket. *)
+
+val recvfrom :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int * sockaddr
+(** Receive data from an unconnected socket. *)
+
+val send : file_descr -> bytes -> int -> int -> msg_flag list -> int
+(** Send data over a connected socket. *)
+
+val send_substring : file_descr -> string -> int -> int -> msg_flag list -> int
+(** Same as [send], but take the data from a string instead of a byte
+ sequence. *)
+
+val sendto :
+ file_descr -> bytes -> int -> int -> msg_flag list -> sockaddr -> int
+(** Send data over an unconnected socket. *)
+
+val sendto_substring :
+ file_descr -> string -> int -> int -> msg_flag list -> sockaddr -> int
+(** Same as [sendto], but take the data from a string instead of a
+ byte sequence. *)
+
+
+(** {6 Socket options} *)
+
+
+type socket_bool_option =
+ SO_DEBUG (** Record debugging information *)
+ | SO_BROADCAST (** Permit sending of broadcast messages *)
+ | SO_REUSEADDR (** Allow reuse of local addresses for bind *)
+ | SO_KEEPALIVE (** Keep connection active *)
+ | SO_DONTROUTE (** Bypass the standard routing algorithms *)
+ | SO_OOBINLINE (** Leave out-of-band data in line *)
+ | SO_ACCEPTCONN (** Report whether socket listening is enabled *)
+ | TCP_NODELAY (** Control the Nagle algorithm for TCP sockets *)
+ | IPV6_ONLY (** Forbid binding an IPv6 socket to an IPv4 address *)
+(** The socket options that can be consulted with {!Unix.getsockopt}
+ and modified with {!Unix.setsockopt}. These options have a boolean
+ ([true]/[false]) value. *)
+
+type socket_int_option =
+ SO_SNDBUF (** Size of send buffer *)
+ | SO_RCVBUF (** Size of received buffer *)
+ | SO_ERROR (** Deprecated. Use {!Unix.getsockopt_error} instead. *)
+ | SO_TYPE (** Report the socket type *)
+ | SO_RCVLOWAT (** Minimum number of bytes to process for input operations*)
+ | SO_SNDLOWAT (** Minimum number of bytes to process for output
+ operations *)
+(** The socket options that can be consulted with {!Unix.getsockopt_int}
+ and modified with {!Unix.setsockopt_int}. These options have an
+ integer value. *)
+
+type socket_optint_option =
+ SO_LINGER (** Whether to linger on closed connections
+ that have data present, and for how long
+ (in seconds) *)
+(** The socket options that can be consulted with {!Unix.getsockopt_optint}
+ and modified with {!Unix.setsockopt_optint}. These options have a
+ value of type [int option], with [None] meaning ``disabled''. *)
+
+type socket_float_option =
+ SO_RCVTIMEO (** Timeout for input operations *)
+ | SO_SNDTIMEO (** Timeout for output operations *)
+(** The socket options that can be consulted with {!Unix.getsockopt_float}
+ and modified with {!Unix.setsockopt_float}. These options have a
+ floating-point value representing a time in seconds.
+ The value 0 means infinite timeout. *)
+
+val getsockopt : file_descr -> socket_bool_option -> bool
+(** Return the current status of a boolean-valued option
+ in the given socket. *)
+
+val setsockopt : file_descr -> socket_bool_option -> bool -> unit
+(** Set or clear a boolean-valued option in the given socket. *)
+
+val getsockopt_int : file_descr -> socket_int_option -> int
+(** Same as {!Unix.getsockopt} for an integer-valued socket option. *)
+
+val setsockopt_int : file_descr -> socket_int_option -> int -> unit
+(** Same as {!Unix.setsockopt} for an integer-valued socket option. *)
+
+val getsockopt_optint : file_descr -> socket_optint_option -> int option
+(** Same as {!Unix.getsockopt} for a socket option whose value is an
+ [int option]. *)
+
+val setsockopt_optint :
+ file_descr -> socket_optint_option -> int option -> unit
+(** Same as {!Unix.setsockopt} for a socket option whose value is an
+ [int option]. *)
+
+val getsockopt_float : file_descr -> socket_float_option -> float
+(** Same as {!Unix.getsockopt} for a socket option whose value is a
+ floating-point number. *)
+
+val setsockopt_float : file_descr -> socket_float_option -> float -> unit
+(** Same as {!Unix.setsockopt} for a socket option whose value is a
+ floating-point number. *)
+
+val getsockopt_error : file_descr -> error option
+(** Return the error condition associated with the given socket,
+ and clear it. *)
+
+(** {6 High-level network connection functions} *)
+
+
+val open_connection : sockaddr -> in_channel * out_channel
+(** Connect to a server at the given address.
+ Return a pair of buffered channels connected to the server.
+ Remember to call {!Pervasives.flush} on the output channel at the right
+ times to ensure correct synchronization. *)
+
+val shutdown_connection : in_channel -> unit
+(** ``Shut down'' a connection established with {!Unix.open_connection};
+ that is, transmit an end-of-file condition to the server reading
+ on the other side of the connection. This does not fully close the
+ file descriptor associated with the channel, which you must remember
+ to free via {!Pervasives.close_in}. *)
+
+val establish_server : (in_channel -> out_channel -> unit) -> sockaddr -> unit
+(** Establish a server on the given address.
+ The function given as first argument is called for each connection
+ with two buffered channels connected to the client. A new process
+ is created for each connection. The function {!Unix.establish_server}
+ never returns normally. *)
+
+
+(** {6 Host and protocol databases} *)
+
+
+type host_entry =
+ { h_name : string;
+ h_aliases : string array;
+ h_addrtype : socket_domain;
+ h_addr_list : inet_addr array
+ }
+(** Structure of entries in the [hosts] database. *)
+
+type protocol_entry =
+ { p_name : string;
+ p_aliases : string array;
+ p_proto : int
+ }
+(** Structure of entries in the [protocols] database. *)
+
+type service_entry =
+ { s_name : string;
+ s_aliases : string array;
+ s_port : int;
+ s_proto : string
+ }
+(** Structure of entries in the [services] database. *)
+
+val gethostname : unit -> string
+(** Return the name of the local host. *)
+
+val gethostbyname : string -> host_entry
+(** Find an entry in [hosts] with the given name, or raise
+ [Not_found]. *)
+
+val gethostbyaddr : inet_addr -> host_entry
+(** Find an entry in [hosts] with the given address, or raise
+ [Not_found]. *)
+
+val getprotobyname : string -> protocol_entry
+(** Find an entry in [protocols] with the given name, or raise
+ [Not_found]. *)
+
+val getprotobynumber : int -> protocol_entry
+(** Find an entry in [protocols] with the given protocol number,
+ or raise [Not_found]. *)
+
+val getservbyname : string -> string -> service_entry
+(** Find an entry in [services] with the given name, or raise
+ [Not_found]. *)
+
+val getservbyport : int -> string -> service_entry
+(** Find an entry in [services] with the given service number,
+ or raise [Not_found]. *)
+
+type addr_info =
+ { ai_family : socket_domain; (** Socket domain *)
+ ai_socktype : socket_type; (** Socket type *)
+ ai_protocol : int; (** Socket protocol number *)
+ ai_addr : sockaddr; (** Address *)
+ ai_canonname : string (** Canonical host name *)
+ }
+(** Address information returned by {!Unix.getaddrinfo}. *)
+
+type getaddrinfo_option =
+ AI_FAMILY of socket_domain (** Impose the given socket domain *)
+ | AI_SOCKTYPE of socket_type (** Impose the given socket type *)
+ | AI_PROTOCOL of int (** Impose the given protocol *)
+ | AI_NUMERICHOST (** Do not call name resolver,
+ expect numeric IP address *)
+ | AI_CANONNAME (** Fill the [ai_canonname] field
+ of the result *)
+ | AI_PASSIVE (** Set address to ``any'' address
+ for use with {!Unix.bind} *)
+(** Options to {!Unix.getaddrinfo}. *)
+
+val getaddrinfo:
+ string -> string -> getaddrinfo_option list -> addr_info list
+(** [getaddrinfo host service opts] returns a list of {!Unix.addr_info}
+ records describing socket parameters and addresses suitable for
+ communicating with the given host and service. The empty list is
+ returned if the host or service names are unknown, or the constraints
+ expressed in [opts] cannot be satisfied.
+
+ [host] is either a host name or the string representation of an IP
+ address. [host] can be given as the empty string; in this case,
+ the ``any'' address or the ``loopback'' address are used,
+ depending whether [opts] contains [AI_PASSIVE].
+ [service] is either a service name or the string representation of
+ a port number. [service] can be given as the empty string;
+ in this case, the port field of the returned addresses is set to 0.
+ [opts] is a possibly empty list of options that allows the caller
+ to force a particular socket domain (e.g. IPv6 only or IPv4 only)
+ or a particular socket type (e.g. TCP only or UDP only). *)
+
+type name_info =
+ { ni_hostname : string; (** Name or IP address of host *)
+ ni_service : string } (** Name of service or port number *)
+(** Host and service information returned by {!Unix.getnameinfo}. *)
+
+type getnameinfo_option =
+ NI_NOFQDN (** Do not qualify local host names *)
+ | NI_NUMERICHOST (** Always return host as IP address *)
+ | NI_NAMEREQD (** Fail if host name cannot be determined *)
+ | NI_NUMERICSERV (** Always return service as port number *)
+ | NI_DGRAM (** Consider the service as UDP-based
+ instead of the default TCP *)
+(** Options to {!Unix.getnameinfo}. *)
+
+val getnameinfo : sockaddr -> getnameinfo_option list -> name_info
+(** [getnameinfo addr opts] returns the host name and service name
+ corresponding to the socket address [addr]. [opts] is a possibly
+ empty list of options that governs how these names are obtained.
+ Raise [Not_found] if an error occurs. *)
+
+
+(** {6 Terminal interface} *)
+
+
+(** The following functions implement the POSIX standard terminal
+ interface. They provide control over asynchronous communication ports
+ and pseudo-terminals. Refer to the [termios] man page for a
+ complete description. *)
+
+type terminal_io =
+ {
+ (* input modes *)
+ mutable c_ignbrk : bool; (** Ignore the break condition. *)
+ mutable c_brkint : bool; (** Signal interrupt on break condition. *)
+ mutable c_ignpar : bool; (** Ignore characters with parity errors. *)
+ mutable c_parmrk : bool; (** Mark parity errors. *)
+ mutable c_inpck : bool; (** Enable parity check on input. *)
+ mutable c_istrip : bool; (** Strip 8th bit on input characters. *)
+ mutable c_inlcr : bool; (** Map NL to CR on input. *)
+ mutable c_igncr : bool; (** Ignore CR on input. *)
+ mutable c_icrnl : bool; (** Map CR to NL on input. *)
+ mutable c_ixon : bool; (** Recognize XON/XOFF characters on input. *)
+ mutable c_ixoff : bool; (** Emit XON/XOFF chars to control input flow. *)
+ (* Output modes: *)
+ mutable c_opost : bool; (** Enable output processing. *)
+ (* Control modes: *)
+ mutable c_obaud : int; (** Output baud rate (0 means close connection).*)
+ mutable c_ibaud : int; (** Input baud rate. *)
+ mutable c_csize : int; (** Number of bits per character (5-8). *)
+ mutable c_cstopb : int; (** Number of stop bits (1-2). *)
+ mutable c_cread : bool; (** Reception is enabled. *)
+ mutable c_parenb : bool; (** Enable parity generation and detection. *)
+ mutable c_parodd : bool; (** Specify odd parity instead of even. *)
+ mutable c_hupcl : bool; (** Hang up on last close. *)
+ mutable c_clocal : bool; (** Ignore modem status lines. *)
+ (* Local modes: *)
+ mutable c_isig : bool; (** Generate signal on INTR, QUIT, SUSP. *)
+ mutable c_icanon : bool; (** Enable canonical processing
+ (line buffering and editing) *)
+ mutable c_noflsh : bool; (** Disable flush after INTR, QUIT, SUSP. *)
+ mutable c_echo : bool; (** Echo input characters. *)
+ mutable c_echoe : bool; (** Echo ERASE (to erase previous character). *)
+ mutable c_echok : bool; (** Echo KILL (to erase the current line). *)
+ mutable c_echonl : bool; (** Echo NL even if c_echo is not set. *)
+ (* Control characters: *)
+ mutable c_vintr : char; (** Interrupt character (usually ctrl-C). *)
+ mutable c_vquit : char; (** Quit character (usually ctrl-\). *)
+ mutable c_verase : char; (** Erase character (usually DEL or ctrl-H). *)
+ mutable c_vkill : char; (** Kill line character (usually ctrl-U). *)
+ mutable c_veof : char; (** End-of-file character (usually ctrl-D). *)
+ mutable c_veol : char; (** Alternate end-of-line char. (usually none). *)
+ mutable c_vmin : int; (** Minimum number of characters to read
+ before the read request is satisfied. *)
+ mutable c_vtime : int; (** Maximum read wait (in 0.1s units). *)
+ mutable c_vstart : char; (** Start character (usually ctrl-Q). *)
+ mutable c_vstop : char; (** Stop character (usually ctrl-S). *)
+ }
+
+val tcgetattr : file_descr -> terminal_io
+(** Return the status of the terminal referred to by the given
+ file descriptor. *)
+
+type setattr_when =
+ TCSANOW
+ | TCSADRAIN
+ | TCSAFLUSH
+
+val tcsetattr : file_descr -> setattr_when -> terminal_io -> unit
+(** Set the status of the terminal referred to by the given
+ file descriptor. The second argument indicates when the
+ status change takes place: immediately ([TCSANOW]),
+ when all pending output has been transmitted ([TCSADRAIN]),
+ or after flushing all input that has been received but not
+ read ([TCSAFLUSH]). [TCSADRAIN] is recommended when changing
+ the output parameters; [TCSAFLUSH], when changing the input
+ parameters. *)
+
+val tcsendbreak : file_descr -> int -> unit
+(** Send a break condition on the given file descriptor.
+ The second argument is the duration of the break, in 0.1s units;
+ 0 means standard duration (0.25s). *)
+
+val tcdrain : file_descr -> unit
+(** Waits until all output written on the given file descriptor
+ has been transmitted. *)
+
+type flush_queue =
+ TCIFLUSH
+ | TCOFLUSH
+ | TCIOFLUSH
+
+val tcflush : file_descr -> flush_queue -> unit
+(** Discard data written on the given file descriptor but not yet
+ transmitted, or data received but not yet read, depending on the
+ second argument: [TCIFLUSH] flushes data received but not read,
+ [TCOFLUSH] flushes data written but not transmitted, and
+ [TCIOFLUSH] flushes both. *)
+
+type flow_action =
+ TCOOFF
+ | TCOON
+ | TCIOFF
+ | TCION
+
+val tcflow : file_descr -> flow_action -> unit
+(** Suspend or restart reception or transmission of data on
+ the given file descriptor, depending on the second argument:
+ [TCOOFF] suspends output, [TCOON] restarts output,
+ [TCIOFF] transmits a STOP character to suspend input,
+ and [TCION] transmits a START character to restart input. *)
+
+val setsid : unit -> int
+(** Put the calling process in a new session and detach it from
+ its controlling terminal. *)
diff --git a/otherlibs/unix/unix.mllib b/otherlibs/unix/unix.mllib
new file mode 100644
index 0000000000..8d569c56d0
--- /dev/null
+++ b/otherlibs/unix/unix.mllib
@@ -0,0 +1 @@
+Unix UnixLabels
diff --git a/otherlibs/unix/unixLabels.ml b/otherlibs/unix/unixLabels.ml
new file mode 100644
index 0000000000..1bd410bda4
--- /dev/null
+++ b/otherlibs/unix/unixLabels.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [UnixLabels]: labelled Unix module *)
+
+include Unix
diff --git a/otherlibs/unix/unixLabels.mli b/otherlibs/unix/unixLabels.mli
new file mode 100644
index 0000000000..76ff890b12
--- /dev/null
+++ b/otherlibs/unix/unixLabels.mli
@@ -0,0 +1,1369 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Interface to the Unix system.
+ To use as replacement to default {!Unix} module,
+ add [module Unix = UnixLabels] in your implementation.
+*)
+
+(** {6 Error report} *)
+
+
+type error = Unix.error =
+ E2BIG (** Argument list too long *)
+ | EACCES (** Permission denied *)
+ | EAGAIN (** Resource temporarily unavailable; try again *)
+ | EBADF (** Bad file descriptor *)
+ | EBUSY (** Resource unavailable *)
+ | ECHILD (** No child process *)
+ | EDEADLK (** Resource deadlock would occur *)
+ | EDOM (** Domain error for math functions, etc. *)
+ | EEXIST (** File exists *)
+ | EFAULT (** Bad address *)
+ | EFBIG (** File too large *)
+ | EINTR (** Function interrupted by signal *)
+ | EINVAL (** Invalid argument *)
+ | EIO (** Hardware I/O error *)
+ | EISDIR (** Is a directory *)
+ | EMFILE (** Too many open files by the process *)
+ | EMLINK (** Too many links *)
+ | ENAMETOOLONG (** Filename too long *)
+ | ENFILE (** Too many open files in the system *)
+ | ENODEV (** No such device *)
+ | ENOENT (** No such file or directory *)
+ | ENOEXEC (** Not an executable file *)
+ | ENOLCK (** No locks available *)
+ | ENOMEM (** Not enough memory *)
+ | ENOSPC (** No space left on device *)
+ | ENOSYS (** Function not supported *)
+ | ENOTDIR (** Not a directory *)
+ | ENOTEMPTY (** Directory not empty *)
+ | ENOTTY (** Inappropriate I/O control operation *)
+ | ENXIO (** No such device or address *)
+ | EPERM (** Operation not permitted *)
+ | EPIPE (** Broken pipe *)
+ | ERANGE (** Result too large *)
+ | EROFS (** Read-only file system *)
+ | ESPIPE (** Invalid seek e.g. on a pipe *)
+ | ESRCH (** No such process *)
+ | EXDEV (** Invalid link *)
+ | EWOULDBLOCK (** Operation would block *)
+ | EINPROGRESS (** Operation now in progress *)
+ | EALREADY (** Operation already in progress *)
+ | ENOTSOCK (** Socket operation on non-socket *)
+ | EDESTADDRREQ (** Destination address required *)
+ | EMSGSIZE (** Message too long *)
+ | EPROTOTYPE (** Protocol wrong type for socket *)
+ | ENOPROTOOPT (** Protocol not available *)
+ | EPROTONOSUPPORT (** Protocol not supported *)
+ | ESOCKTNOSUPPORT (** Socket type not supported *)
+ | EOPNOTSUPP (** Operation not supported on socket *)
+ | EPFNOSUPPORT (** Protocol family not supported *)
+ | EAFNOSUPPORT (** Address family not supported by protocol family *)
+ | EADDRINUSE (** Address already in use *)
+ | EADDRNOTAVAIL (** Can't assign requested address *)
+ | ENETDOWN (** Network is down *)
+ | ENETUNREACH (** Network is unreachable *)
+ | ENETRESET (** Network dropped connection on reset *)
+ | ECONNABORTED (** Software caused connection abort *)
+ | ECONNRESET (** Connection reset by peer *)
+ | ENOBUFS (** No buffer space available *)
+ | EISCONN (** Socket is already connected *)
+ | ENOTCONN (** Socket is not connected *)
+ | ESHUTDOWN (** Can't send after socket shutdown *)
+ | ETOOMANYREFS (** Too many references: can't splice *)
+ | ETIMEDOUT (** Connection timed out *)
+ | ECONNREFUSED (** Connection refused *)
+ | EHOSTDOWN (** Host is down *)
+ | EHOSTUNREACH (** No route to host *)
+ | ELOOP (** Too many levels of symbolic links *)
+ | EOVERFLOW (** File size or position not representable *)
+
+ | EUNKNOWNERR of int (** Unknown error *)
+(** The type of error codes.
+ Errors defined in the POSIX standard
+ and additional errors from UNIX98 and BSD.
+ All other errors are mapped to EUNKNOWNERR.
+*)
+
+
+exception Unix_error of error * string * string
+(** Raised by the system calls below when an error is encountered.
+ The first component is the error code; the second component
+ is the function name; the third component is the string parameter
+ to the function, if it has one, or the empty string otherwise. *)
+
+val error_message : error -> string
+(** Return a string describing the given error code. *)
+
+val handle_unix_error : ('a -> 'b) -> 'a -> 'b
+(** [handle_unix_error f x] applies [f] to [x] and returns the result.
+ If the exception [Unix_error] is raised, it prints a message
+ describing the error and exits with code 2. *)
+
+
+(** {6 Access to the process environment} *)
+
+
+val environment : unit -> string array
+(** Return the process environment, as an array of strings
+ with the format ``variable=value''. *)
+
+val getenv : string -> string
+(** Return the value associated to a variable in the process
+ environment. Raise [Not_found] if the variable is unbound.
+ (This function is identical to [Sys.getenv].) *)
+
+val putenv : string -> string -> unit
+(** [Unix.putenv name value] sets the value associated to a
+ variable in the process environment.
+ [name] is the name of the environment variable,
+ and [value] its new associated value. *)
+
+
+(** {6 Process handling} *)
+
+
+type process_status = Unix.process_status =
+ WEXITED of int
+ (** The process terminated normally by [exit];
+ the argument is the return code. *)
+ | WSIGNALED of int
+ (** The process was killed by a signal;
+ the argument is the signal number. *)
+ | WSTOPPED of int
+ (** The process was stopped by a signal; the argument is the
+ signal number. *)
+(** The termination status of a process. See module {!Sys} for the
+ definitions of the standard signal numbers. Note that they are
+ not the numbers used by the OS. *)
+
+
+type wait_flag = Unix.wait_flag =
+ WNOHANG (** do not block if no child has
+ died yet, but immediately return with a pid equal to 0.*)
+ | WUNTRACED (** report also the children that receive stop signals. *)
+(** Flags for {!UnixLabels.waitpid}. *)
+
+val execv : prog:string -> args:string array -> 'a
+(** [execv prog args] execute the program in file [prog], with
+ the arguments [args], and the current process environment.
+ These [execv*] functions never return: on success, the current
+ program is replaced by the new one;
+ on failure, a {!UnixLabels.Unix_error} exception is raised. *)
+
+val execve : prog:string -> args:string array -> env:string array -> 'a
+(** Same as {!UnixLabels.execv}, except that the third argument provides the
+ environment to the program executed. *)
+
+val execvp : prog:string -> args:string array -> 'a
+(** Same as {!UnixLabels.execv}, except that
+ the program is searched in the path. *)
+
+val execvpe : prog:string -> args:string array -> env:string array -> 'a
+(** Same as {!UnixLabels.execve}, except that
+ the program is searched in the path. *)
+
+val fork : unit -> int
+(** Fork a new process. The returned integer is 0 for the child
+ process, the pid of the child process for the parent process. *)
+
+val wait : unit -> int * process_status
+(** Wait until one of the children processes die, and return its pid
+ and termination status. *)
+
+val waitpid : mode:wait_flag list -> int -> int * process_status
+(** Same as {!UnixLabels.wait}, but waits for the child process whose pid
+ is given.
+ A pid of [-1] means wait for any child.
+ A pid of [0] means wait for any child in the same process group
+ as the current process.
+ Negative pid arguments represent process groups.
+ The list of options indicates whether [waitpid] should return
+ immediately without waiting, or also report stopped children. *)
+
+val system : string -> process_status
+(** Execute the given command, wait until it terminates, and return
+ its termination status. The string is interpreted by the shell
+ [/bin/sh] and therefore can contain redirections, quotes, variables,
+ etc. The result [WEXITED 127] indicates that the shell couldn't
+ be executed. *)
+
+val getpid : unit -> int
+(** Return the pid of the process. *)
+
+val getppid : unit -> int
+(** Return the pid of the parent process. *)
+
+val nice : int -> int
+(** Change the process priority. The integer argument is added to the
+ ``nice'' value. (Higher values of the ``nice'' value mean
+ lower priorities.) Return the new nice value. *)
+
+
+(** {6 Basic file input/output} *)
+
+
+type file_descr = Unix.file_descr
+(** The abstract type of file descriptors. *)
+
+val stdin : file_descr
+(** File descriptor for standard input.*)
+
+val stdout : file_descr
+(** File descriptor for standard output.*)
+
+val stderr : file_descr
+(** File descriptor for standard error. *)
+
+type open_flag = Unix.open_flag =
+ O_RDONLY (** Open for reading *)
+ | O_WRONLY (** Open for writing *)
+ | O_RDWR (** Open for reading and writing *)
+ | O_NONBLOCK (** Open in non-blocking mode *)
+ | O_APPEND (** Open for append *)
+ | O_CREAT (** Create if nonexistent *)
+ | O_TRUNC (** Truncate to 0 length if existing *)
+ | O_EXCL (** Fail if existing *)
+ | O_NOCTTY (** Don't make this dev a controlling tty *)
+ | O_DSYNC (** Writes complete as `Synchronised I/O data
+ integrity completion' *)
+ | O_SYNC (** Writes complete as `Synchronised I/O file
+ integrity completion' *)
+ | O_RSYNC (** Reads complete as writes (depending
+ on O_SYNC/O_DSYNC) *)
+ | O_SHARE_DELETE (** Windows only: allow the file to be deleted
+ while still open *)
+ | O_CLOEXEC (** Set the close-on-exec flag on the
+ descriptor returned by {!openfile} *)
+(** The flags to {!UnixLabels.openfile}. *)
+
+
+type file_perm = int
+(** The type of file access rights, e.g. [0o640] is read and write for user,
+ read for group, none for others *)
+
+val openfile : string -> mode:open_flag list -> perm:file_perm -> file_descr
+(** Open the named file with the given flags. Third argument is
+ the permissions to give to the file if it is created. Return
+ a file descriptor on the named file. *)
+
+val close : file_descr -> unit
+(** Close a file descriptor. *)
+
+val read : file_descr -> buf:bytes -> pos:int -> len:int -> int
+(** [read fd buff ofs len] reads [len] bytes from descriptor [fd],
+ storing them in byte sequence [buff], starting at position [ofs] in
+ [buff]. Return the number of bytes actually read. *)
+
+val write : file_descr -> buf:bytes -> pos:int -> len:int -> int
+(** [write fd buff ofs len] writes [len] bytes to descriptor [fd],
+ taking them from byte sequence [buff], starting at position [ofs]
+ in [buff]. Return the number of bytes actually written. [write]
+ repeats the writing operation until all bytes have been written or
+ an error occurs. *)
+
+val single_write : file_descr -> buf:bytes -> pos:int -> len:int -> int
+(** Same as [write], but attempts to write only once.
+ Thus, if an error occurs, [single_write] guarantees that no data
+ has been written. *)
+
+val write_substring : file_descr -> buf:string -> pos:int -> len:int -> int
+(** Same as [write], but take the data from a string instead of a byte
+ sequence. *)
+
+val single_write_substring :
+ file_descr -> buf:string -> pos:int -> len:int -> int
+(** Same as [single_write], but take the data from a string instead of
+ a byte sequence. *)
+
+(** {6 Interfacing with the standard input/output library} *)
+
+
+
+val in_channel_of_descr : file_descr -> in_channel
+(** Create an input channel reading from the given descriptor.
+ The channel is initially in binary mode; use
+ [set_binary_mode_in ic false] if text mode is desired. *)
+
+val out_channel_of_descr : file_descr -> out_channel
+(** Create an output channel writing on the given descriptor.
+ The channel is initially in binary mode; use
+ [set_binary_mode_out oc false] if text mode is desired. *)
+
+val descr_of_in_channel : in_channel -> file_descr
+(** Return the descriptor corresponding to an input channel. *)
+
+val descr_of_out_channel : out_channel -> file_descr
+(** Return the descriptor corresponding to an output channel. *)
+
+
+(** {6 Seeking and truncating} *)
+
+
+type seek_command = Unix.seek_command =
+ SEEK_SET (** indicates positions relative to the beginning of the file *)
+ | SEEK_CUR (** indicates positions relative to the current position *)
+ | SEEK_END (** indicates positions relative to the end of the file *)
+(** Positioning modes for {!UnixLabels.lseek}. *)
+
+
+val lseek : file_descr -> int -> mode:seek_command -> int
+(** Set the current position for a file descriptor, and return the resulting
+ offset (from the beginning of the file). *)
+
+val truncate : string -> len:int -> unit
+(** Truncates the named file to the given size. *)
+
+val ftruncate : file_descr -> len:int -> unit
+(** Truncates the file corresponding to the given descriptor
+ to the given size. *)
+
+
+(** {6 File status} *)
+
+
+type file_kind = Unix.file_kind =
+ S_REG (** Regular file *)
+ | S_DIR (** Directory *)
+ | S_CHR (** Character device *)
+ | S_BLK (** Block device *)
+ | S_LNK (** Symbolic link *)
+ | S_FIFO (** Named pipe *)
+ | S_SOCK (** Socket *)
+
+type stats = Unix.stats =
+ { st_dev : int; (** Device number *)
+ st_ino : int; (** Inode number *)
+ st_kind : file_kind; (** Kind of the file *)
+ st_perm : file_perm; (** Access rights *)
+ st_nlink : int; (** Number of links *)
+ st_uid : int; (** User id of the owner *)
+ st_gid : int; (** Group ID of the file's group *)
+ st_rdev : int; (** Device minor number *)
+ st_size : int; (** Size in bytes *)
+ st_atime : float; (** Last access time *)
+ st_mtime : float; (** Last modification time *)
+ st_ctime : float; (** Last status change time *)
+ }
+(** The information returned by the {!UnixLabels.stat} calls. *)
+
+val stat : string -> stats
+(** Return the information for the named file. *)
+
+val lstat : string -> stats
+(** Same as {!UnixLabels.stat}, but in case the file is a symbolic link,
+ return the information for the link itself. *)
+
+val fstat : file_descr -> stats
+(** Return the information for the file associated with the given
+ descriptor. *)
+
+val isatty : file_descr -> bool
+(** Return [true] if the given file descriptor refers to a terminal or
+ console window, [false] otherwise. *)
+
+(** {6 File operations on large files} *)
+
+module LargeFile :
+ sig
+ val lseek : file_descr -> int64 -> mode:seek_command -> int64
+ val truncate : string -> len:int64 -> unit
+ val ftruncate : file_descr -> len:int64 -> unit
+ type stats = Unix.LargeFile.stats =
+ { st_dev : int; (** Device number *)
+ st_ino : int; (** Inode number *)
+ st_kind : file_kind; (** Kind of the file *)
+ st_perm : file_perm; (** Access rights *)
+ st_nlink : int; (** Number of links *)
+ st_uid : int; (** User id of the owner *)
+ st_gid : int; (** Group ID of the file's group *)
+ st_rdev : int; (** Device minor number *)
+ st_size : int64; (** Size in bytes *)
+ st_atime : float; (** Last access time *)
+ st_mtime : float; (** Last modification time *)
+ st_ctime : float; (** Last status change time *)
+ }
+ val stat : string -> stats
+ val lstat : string -> stats
+ val fstat : file_descr -> stats
+ end
+(** File operations on large files.
+ This sub-module provides 64-bit variants of the functions
+ {!UnixLabels.lseek} (for positioning a file descriptor),
+ {!UnixLabels.truncate} and {!UnixLabels.ftruncate}
+ (for changing the size of a file),
+ and {!UnixLabels.stat}, {!UnixLabels.lstat} and {!UnixLabels.fstat}
+ (for obtaining information on files). These alternate functions represent
+ positions and sizes by 64-bit integers (type [int64]) instead of
+ regular integers (type [int]), thus allowing operating on files
+ whose sizes are greater than [max_int]. *)
+
+
+(** {6 Operations on file names} *)
+
+
+val unlink : string -> unit
+(** Removes the named file *)
+
+val rename : src:string -> dst:string -> unit
+(** [rename old new] changes the name of a file from [old] to [new]. *)
+
+val link : src:string -> dst:string -> unit
+(** [link source dest] creates a hard link named [dest] to the file
+ named [source]. *)
+
+
+(** {6 File permissions and ownership} *)
+
+
+type access_permission = Unix.access_permission =
+ R_OK (** Read permission *)
+ | W_OK (** Write permission *)
+ | X_OK (** Execution permission *)
+ | F_OK (** File exists *)
+(** Flags for the {!UnixLabels.access} call. *)
+
+
+val chmod : string -> perm:file_perm -> unit
+(** Change the permissions of the named file. *)
+
+val fchmod : file_descr -> perm:file_perm -> unit
+(** Change the permissions of an opened file. *)
+
+val chown : string -> uid:int -> gid:int -> unit
+(** Change the owner uid and owner gid of the named file. *)
+
+val fchown : file_descr -> uid:int -> gid:int -> unit
+(** Change the owner uid and owner gid of an opened file. *)
+
+val umask : int -> int
+(** Set the process's file mode creation mask, and return the previous
+ mask. *)
+
+val access : string -> perm:access_permission list -> unit
+(** Check that the process has the given permissions over the named
+ file. Raise [Unix_error] otherwise. *)
+
+
+(** {6 Operations on file descriptors} *)
+
+
+val dup : file_descr -> file_descr
+(** Return a new file descriptor referencing the same file as
+ the given descriptor. *)
+
+val dup2 : src:file_descr -> dst:file_descr -> unit
+(** [dup2 fd1 fd2] duplicates [fd1] to [fd2], closing [fd2] if already
+ opened. *)
+
+val set_nonblock : file_descr -> unit
+(** Set the ``non-blocking'' flag on the given descriptor.
+ When the non-blocking flag is set, reading on a descriptor
+ on which there is temporarily no data available raises the
+ [EAGAIN] or [EWOULDBLOCK] error instead of blocking;
+ writing on a descriptor on which there is temporarily no room
+ for writing also raises [EAGAIN] or [EWOULDBLOCK]. *)
+
+val clear_nonblock : file_descr -> unit
+(** Clear the ``non-blocking'' flag on the given descriptor.
+ See {!UnixLabels.set_nonblock}.*)
+
+val set_close_on_exec : file_descr -> unit
+(** Set the ``close-on-exec'' flag on the given descriptor.
+ A descriptor with the close-on-exec flag is automatically
+ closed when the current process starts another program with
+ one of the [exec] functions. *)
+
+val clear_close_on_exec : file_descr -> unit
+(** Clear the ``close-on-exec'' flag on the given descriptor.
+ See {!UnixLabels.set_close_on_exec}.*)
+
+
+(** {6 Directories} *)
+
+
+val mkdir : string -> perm:file_perm -> unit
+(** Create a directory with the given permissions. *)
+
+val rmdir : string -> unit
+(** Remove an empty directory. *)
+
+val chdir : string -> unit
+(** Change the process working directory. *)
+
+val getcwd : unit -> string
+(** Return the name of the current working directory. *)
+
+val chroot : string -> unit
+(** Change the process root directory. *)
+
+type dir_handle = Unix.dir_handle
+(** The type of descriptors over opened directories. *)
+
+val opendir : string -> dir_handle
+(** Open a descriptor on a directory *)
+
+val readdir : dir_handle -> string
+(** Return the next entry in a directory.
+ @raise End_of_file when the end of the directory has been reached. *)
+
+val rewinddir : dir_handle -> unit
+(** Reposition the descriptor to the beginning of the directory *)
+
+val closedir : dir_handle -> unit
+(** Close a directory descriptor. *)
+
+
+
+(** {6 Pipes and redirections} *)
+
+
+val pipe : unit -> file_descr * file_descr
+(** Create a pipe. The first component of the result is opened
+ for reading, that's the exit to the pipe. The second component is
+ opened for writing, that's the entrance to the pipe. *)
+
+val mkfifo : string -> perm:file_perm -> unit
+(** Create a named pipe with the given permissions. *)
+
+
+(** {6 High-level process and redirection management} *)
+
+
+val create_process :
+ prog:string -> args:string array -> stdin:file_descr -> stdout:file_descr ->
+ stderr:file_descr -> int
+(** [create_process prog args new_stdin new_stdout new_stderr]
+ forks a new process that executes the program
+ in file [prog], with arguments [args]. The pid of the new
+ process is returned immediately; the new process executes
+ concurrently with the current process.
+ The standard input and outputs of the new process are connected
+ to the descriptors [new_stdin], [new_stdout] and [new_stderr].
+ Passing e.g. [stdout] for [new_stdout] prevents the redirection
+ and causes the new process to have the same standard output
+ as the current process.
+ The executable file [prog] is searched in the path.
+ The new process has the same environment as the current process. *)
+
+val create_process_env :
+ prog:string -> args:string array -> env:string array -> stdin:file_descr ->
+ stdout:file_descr -> stderr:file_descr -> int
+(** [create_process_env prog args env new_stdin new_stdout new_stderr]
+ works as {!UnixLabels.create_process}, except that the extra argument
+ [env] specifies the environment passed to the program. *)
+
+
+val open_process_in : string -> in_channel
+(** High-level pipe and process management. This function
+ runs the given command in parallel with the program.
+ The standard output of the command is redirected to a pipe,
+ which can be read via the returned input channel.
+ The command is interpreted by the shell [/bin/sh] (cf. [system]). *)
+
+val open_process_out : string -> out_channel
+(** Same as {!UnixLabels.open_process_in}, but redirect the standard input of
+ the command to a pipe. Data written to the returned output channel
+ is sent to the standard input of the command.
+ Warning: writes on output channels are buffered, hence be careful
+ to call {!Pervasives.flush} at the right times to ensure
+ correct synchronization. *)
+
+val open_process : string -> in_channel * out_channel
+(** Same as {!UnixLabels.open_process_out}, but redirects both the standard
+ input and standard output of the command to pipes connected to the two
+ returned channels. The input channel is connected to the output
+ of the command, and the output channel to the input of the command. *)
+
+val open_process_full :
+ string -> env:string array -> in_channel * out_channel * in_channel
+(** Similar to {!UnixLabels.open_process}, but the second argument specifies
+ the environment passed to the command. The result is a triple
+ of channels connected respectively to the standard output, standard input,
+ and standard error of the command. *)
+
+val close_process_in : in_channel -> process_status
+(** Close channels opened by {!UnixLabels.open_process_in},
+ wait for the associated command to terminate,
+ and return its termination status. *)
+
+val close_process_out : out_channel -> process_status
+(** Close channels opened by {!UnixLabels.open_process_out},
+ wait for the associated command to terminate,
+ and return its termination status. *)
+
+val close_process : in_channel * out_channel -> process_status
+(** Close channels opened by {!UnixLabels.open_process},
+ wait for the associated command to terminate,
+ and return its termination status. *)
+
+val close_process_full :
+ in_channel * out_channel * in_channel -> process_status
+(** Close channels opened by {!UnixLabels.open_process_full},
+ wait for the associated command to terminate,
+ and return its termination status. *)
+
+
+(** {6 Symbolic links} *)
+
+
+val symlink : src:string -> dst:string -> unit
+(** [symlink source dest] creates the file [dest] as a symbolic link
+ to the file [source]. *)
+
+val readlink : string -> string
+(** Read the contents of a link. *)
+
+
+(** {6 Polling} *)
+
+
+val select :
+ read:file_descr list -> write:file_descr list -> except:file_descr list ->
+ timeout:float -> file_descr list * file_descr list * file_descr list
+(** Wait until some input/output operations become possible on
+ some channels. The three list arguments are, respectively, a set
+ of descriptors to check for reading (first argument), for writing
+ (second argument), or for exceptional conditions (third argument).
+ The fourth argument is the maximal timeout, in seconds; a
+ negative fourth argument means no timeout (unbounded wait).
+ The result is composed of three sets of descriptors: those ready
+ for reading (first component), ready for writing (second component),
+ and over which an exceptional condition is pending (third
+ component). *)
+
+(** {6 Locking} *)
+
+
+type lock_command = Unix.lock_command =
+ F_ULOCK (** Unlock a region *)
+ | F_LOCK (** Lock a region for writing, and block if already locked *)
+ | F_TLOCK (** Lock a region for writing, or fail if already locked *)
+ | F_TEST (** Test a region for other process locks *)
+ | F_RLOCK (** Lock a region for reading, and block if already locked *)
+ | F_TRLOCK (** Lock a region for reading, or fail if already locked *)
+(** Commands for {!UnixLabels.lockf}. *)
+
+val lockf : file_descr -> mode:lock_command -> len:int -> unit
+(** [lockf fd cmd size] puts a lock on a region of the file opened
+ as [fd]. The region starts at the current read/write position for
+ [fd] (as set by {!UnixLabels.lseek}), and extends [size] bytes forward if
+ [size] is positive, [size] bytes backwards if [size] is negative,
+ or to the end of the file if [size] is zero.
+ A write lock prevents any other
+ process from acquiring a read or write lock on the region.
+ A read lock prevents any other
+ process from acquiring a write lock on the region, but lets
+ other processes acquire read locks on it.
+
+ The [F_LOCK] and [F_TLOCK] commands attempts to put a write lock
+ on the specified region.
+ The [F_RLOCK] and [F_TRLOCK] commands attempts to put a read lock
+ on the specified region.
+ If one or several locks put by another process prevent the current process
+ from acquiring the lock, [F_LOCK] and [F_RLOCK] block until these locks
+ are removed, while [F_TLOCK] and [F_TRLOCK] fail immediately with an
+ exception.
+ The [F_ULOCK] removes whatever locks the current process has on
+ the specified region.
+ Finally, the [F_TEST] command tests whether a write lock can be
+ acquired on the specified region, without actually putting a lock.
+ It returns immediately if successful, or fails otherwise. *)
+
+
+(** {6 Signals}
+ Note: installation of signal handlers is performed via
+ the functions {!Sys.signal} and {!Sys.set_signal}.
+*)
+
+val kill : pid:int -> signal:int -> unit
+(** [kill pid sig] sends signal number [sig] to the process
+ with id [pid]. *)
+
+type sigprocmask_command = Unix.sigprocmask_command =
+ SIG_SETMASK
+ | SIG_BLOCK
+ | SIG_UNBLOCK
+
+val sigprocmask : mode:sigprocmask_command -> int list -> int list
+(** [sigprocmask cmd sigs] changes the set of blocked signals.
+ If [cmd] is [SIG_SETMASK], blocked signals are set to those in
+ the list [sigs].
+ If [cmd] is [SIG_BLOCK], the signals in [sigs] are added to
+ the set of blocked signals.
+ If [cmd] is [SIG_UNBLOCK], the signals in [sigs] are removed
+ from the set of blocked signals.
+ [sigprocmask] returns the set of previously blocked signals. *)
+
+val sigpending : unit -> int list
+(** Return the set of blocked signals that are currently pending. *)
+
+val sigsuspend : int list -> unit
+(** [sigsuspend sigs] atomically sets the blocked signals to [sigs]
+ and waits for a non-ignored, non-blocked signal to be delivered.
+ On return, the blocked signals are reset to their initial value. *)
+
+val pause : unit -> unit
+(** Wait until a non-ignored, non-blocked signal is delivered. *)
+
+
+(** {6 Time functions} *)
+
+
+type process_times = Unix.process_times =
+ { tms_utime : float; (** User time for the process *)
+ tms_stime : float; (** System time for the process *)
+ tms_cutime : float; (** User time for the children processes *)
+ tms_cstime : float; (** System time for the children processes *)
+ }
+(** The execution times (CPU times) of a process. *)
+
+type tm = Unix.tm =
+ { tm_sec : int; (** Seconds 0..60 *)
+ tm_min : int; (** Minutes 0..59 *)
+ tm_hour : int; (** Hours 0..23 *)
+ tm_mday : int; (** Day of month 1..31 *)
+ tm_mon : int; (** Month of year 0..11 *)
+ tm_year : int; (** Year - 1900 *)
+ tm_wday : int; (** Day of week (Sunday is 0) *)
+ tm_yday : int; (** Day of year 0..365 *)
+ tm_isdst : bool; (** Daylight time savings in effect *)
+ }
+(** The type representing wallclock time and calendar date. *)
+
+
+val time : unit -> float
+(** Return the current time since 00:00:00 GMT, Jan. 1, 1970,
+ in seconds. *)
+
+val gettimeofday : unit -> float
+(** Same as {!UnixLabels.time}, but with resolution better than 1 second. *)
+
+val gmtime : float -> tm
+(** Convert a time in seconds, as returned by {!UnixLabels.time}, into a date
+ and a time. Assumes UTC (Coordinated Universal Time), also known as GMT. *)
+
+val localtime : float -> tm
+(** Convert a time in seconds, as returned by {!UnixLabels.time}, into a date
+ and a time. Assumes the local time zone. *)
+
+val mktime : tm -> float * tm
+(** Convert a date and time, specified by the [tm] argument, into
+ a time in seconds, as returned by {!UnixLabels.time}. The [tm_isdst],
+ [tm_wday] and [tm_yday] fields of [tm] are ignored. Also return a
+ normalized copy of the given [tm] record, with the [tm_wday],
+ [tm_yday], and [tm_isdst] fields recomputed from the other fields,
+ and the other fields normalized (so that, e.g., 40 October is
+ changed into 9 November). The [tm] argument is interpreted in the
+ local time zone. *)
+
+val alarm : int -> int
+(** Schedule a [SIGALRM] signal after the given number of seconds. *)
+
+val sleep : int -> unit
+(** Stop execution for the given number of seconds. *)
+
+val times : unit -> process_times
+(** Return the execution times of the process. *)
+
+val utimes : string -> access:float -> modif:float -> unit
+(** Set the last access time (second arg) and last modification time
+ (third arg) for a file. Times are expressed in seconds from
+ 00:00:00 GMT, Jan. 1, 1970. A time of [0.0] is interpreted as the
+ current time. *)
+
+type interval_timer = Unix.interval_timer =
+ ITIMER_REAL
+ (** decrements in real time, and sends the signal [SIGALRM] when
+ expired.*)
+ | ITIMER_VIRTUAL
+ (** decrements in process virtual time, and sends [SIGVTALRM] when
+ expired. *)
+ | ITIMER_PROF
+ (** (for profiling) decrements both when the process
+ is running and when the system is running on behalf of the
+ process; it sends [SIGPROF] when expired. *)
+(** The three kinds of interval timers. *)
+
+type interval_timer_status = Unix.interval_timer_status =
+ { it_interval : float; (** Period *)
+ it_value : float; (** Current value of the timer *)
+ }
+(** The type describing the status of an interval timer *)
+
+val getitimer : interval_timer -> interval_timer_status
+(** Return the current status of the given interval timer. *)
+
+val setitimer :
+ interval_timer -> interval_timer_status -> interval_timer_status
+(** [setitimer t s] sets the interval timer [t] and returns
+ its previous status. The [s] argument is interpreted as follows:
+ [s.it_value], if nonzero, is the time to the next timer expiration;
+ [s.it_interval], if nonzero, specifies a value to
+ be used in reloading it_value when the timer expires.
+ Setting [s.it_value] to zero disable the timer.
+ Setting [s.it_interval] to zero causes the timer to be disabled
+ after its next expiration. *)
+
+
+(** {6 User id, group id} *)
+
+
+val getuid : unit -> int
+(** Return the user id of the user executing the process. *)
+
+val geteuid : unit -> int
+(** Return the effective user id under which the process runs. *)
+
+val setuid : int -> unit
+(** Set the real user id and effective user id for the process. *)
+
+val getgid : unit -> int
+(** Return the group id of the user executing the process. *)
+
+val getegid : unit -> int
+(** Return the effective group id under which the process runs. *)
+
+val setgid : int -> unit
+(** Set the real group id and effective group id for the process. *)
+
+val getgroups : unit -> int array
+(** Return the list of groups to which the user executing the process
+ belongs. *)
+
+val setgroups : int array -> unit
+ (** [setgroups groups] sets the supplementary group IDs for the
+ calling process. Appropriate privileges are required. *)
+
+val initgroups : string -> int -> unit
+ (** [initgroups user group] initializes the group access list by
+ reading the group database /etc/group and using all groups of
+ which [user] is a member. The additional group [group] is also
+ added to the list. *)
+
+type passwd_entry = Unix.passwd_entry =
+ { pw_name : string;
+ pw_passwd : string;
+ pw_uid : int;
+ pw_gid : int;
+ pw_gecos : string;
+ pw_dir : string;
+ pw_shell : string
+ }
+(** Structure of entries in the [passwd] database. *)
+
+type group_entry = Unix.group_entry =
+ { gr_name : string;
+ gr_passwd : string;
+ gr_gid : int;
+ gr_mem : string array
+ }
+(** Structure of entries in the [groups] database. *)
+
+val getlogin : unit -> string
+(** Return the login name of the user executing the process. *)
+
+val getpwnam : string -> passwd_entry
+(** Find an entry in [passwd] with the given name, or raise
+ [Not_found]. *)
+
+val getgrnam : string -> group_entry
+(** Find an entry in [group] with the given name, or raise
+ [Not_found]. *)
+
+val getpwuid : int -> passwd_entry
+(** Find an entry in [passwd] with the given user id, or raise
+ [Not_found]. *)
+
+val getgrgid : int -> group_entry
+(** Find an entry in [group] with the given group id, or raise
+ [Not_found]. *)
+
+
+(** {6 Internet addresses} *)
+
+
+type inet_addr = Unix.inet_addr
+(** The abstract type of Internet addresses. *)
+
+val inet_addr_of_string : string -> inet_addr
+(** Conversion from the printable representation of an Internet
+ address to its internal representation. The argument string
+ consists of 4 numbers separated by periods ([XXX.YYY.ZZZ.TTT])
+ for IPv4 addresses, and up to 8 numbers separated by colons
+ for IPv6 addresses. Raise [Failure] when given a string that
+ does not match these formats. *)
+
+val string_of_inet_addr : inet_addr -> string
+(** Return the printable representation of the given Internet address.
+ See {!Unix.inet_addr_of_string} for a description of the
+ printable representation. *)
+
+val inet_addr_any : inet_addr
+(** A special IPv4 address, for use only with [bind], representing
+ all the Internet addresses that the host machine possesses. *)
+
+val inet_addr_loopback : inet_addr
+(** A special IPv4 address representing the host machine ([127.0.0.1]). *)
+
+val inet6_addr_any : inet_addr
+(** A special IPv6 address, for use only with [bind], representing
+ all the Internet addresses that the host machine possesses. *)
+
+val inet6_addr_loopback : inet_addr
+(** A special IPv6 address representing the host machine ([::1]). *)
+
+
+(** {6 Sockets} *)
+
+
+type socket_domain = Unix.socket_domain =
+ PF_UNIX (** Unix domain *)
+ | PF_INET (** Internet domain (IPv4) *)
+ | PF_INET6 (** Internet domain (IPv6) *)
+(** The type of socket domains. Not all platforms support
+ IPv6 sockets (type [PF_INET6]). *)
+
+type socket_type = Unix.socket_type =
+ SOCK_STREAM (** Stream socket *)
+ | SOCK_DGRAM (** Datagram socket *)
+ | SOCK_RAW (** Raw socket *)
+ | SOCK_SEQPACKET (** Sequenced packets socket *)
+(** The type of socket kinds, specifying the semantics of
+ communications. *)
+
+type sockaddr = Unix.sockaddr =
+ ADDR_UNIX of string
+ | ADDR_INET of inet_addr * int
+(** The type of socket addresses. [ADDR_UNIX name] is a socket
+ address in the Unix domain; [name] is a file name in the file
+ system. [ADDR_INET(addr,port)] is a socket address in the Internet
+ domain; [addr] is the Internet address of the machine, and
+ [port] is the port number. *)
+
+val socket :
+ domain:socket_domain -> kind:socket_type -> protocol:int -> file_descr
+(** Create a new socket in the given domain, and with the
+ given kind. The third argument is the protocol type; 0 selects
+ the default protocol for that kind of sockets. *)
+
+val domain_of_sockaddr: sockaddr -> socket_domain
+(** Return the socket domain adequate for the given socket address. *)
+
+val socketpair :
+ domain:socket_domain -> kind:socket_type -> protocol:int ->
+ file_descr * file_descr
+(** Create a pair of unnamed sockets, connected together. *)
+
+val accept : file_descr -> file_descr * sockaddr
+(** Accept connections on the given socket. The returned descriptor
+ is a socket connected to the client; the returned address is
+ the address of the connecting client. *)
+
+val bind : file_descr -> addr:sockaddr -> unit
+(** Bind a socket to an address. *)
+
+val connect : file_descr -> addr:sockaddr -> unit
+(** Connect a socket to an address. *)
+
+val listen : file_descr -> max:int -> unit
+(** Set up a socket for receiving connection requests. The integer
+ argument is the maximal number of pending requests. *)
+
+type shutdown_command = Unix.shutdown_command =
+ SHUTDOWN_RECEIVE (** Close for receiving *)
+ | SHUTDOWN_SEND (** Close for sending *)
+ | SHUTDOWN_ALL (** Close both *)
+(** The type of commands for [shutdown]. *)
+
+
+val shutdown : file_descr -> mode:shutdown_command -> unit
+(** Shutdown a socket connection. [SHUTDOWN_SEND] as second argument
+ causes reads on the other end of the connection to return
+ an end-of-file condition.
+ [SHUTDOWN_RECEIVE] causes writes on the other end of the connection
+ to return a closed pipe condition ([SIGPIPE] signal). *)
+
+val getsockname : file_descr -> sockaddr
+(** Return the address of the given socket. *)
+
+val getpeername : file_descr -> sockaddr
+(** Return the address of the host connected to the given socket. *)
+
+type msg_flag = Unix.msg_flag =
+ MSG_OOB
+ | MSG_DONTROUTE
+ | MSG_PEEK
+(** The flags for {!UnixLabels.recv}, {!UnixLabels.recvfrom},
+ {!UnixLabels.send} and {!UnixLabels.sendto}. *)
+
+val recv :
+ file_descr -> buf:bytes -> pos:int -> len:int -> mode:msg_flag list -> int
+(** Receive data from a connected socket. *)
+
+val recvfrom :
+ file_descr -> buf:bytes -> pos:int -> len:int -> mode:msg_flag list ->
+ int * sockaddr
+(** Receive data from an unconnected socket. *)
+
+val send :
+ file_descr -> buf:bytes -> pos:int -> len:int -> mode:msg_flag list -> int
+(** Send data over a connected socket. *)
+
+val send_substring :
+ file_descr -> buf:string -> pos:int -> len:int -> mode:msg_flag list -> int
+(** Same as [send], but take the data from a string instead of a byte
+ sequence. *)
+
+val sendto :
+ file_descr -> buf:bytes -> pos:int -> len:int -> mode:msg_flag list ->
+ addr:sockaddr -> int
+(** Send data over an unconnected socket. *)
+
+val sendto_substring :
+ file_descr -> bug:string -> pos:int -> len:int -> mode:msg_flag list
+ -> sockaddr -> int
+(** Same as [sendto], but take the data from a string instead of a
+ byte sequence. *)
+
+
+
+(** {6 Socket options} *)
+
+
+type socket_bool_option =
+ SO_DEBUG (** Record debugging information *)
+ | SO_BROADCAST (** Permit sending of broadcast messages *)
+ | SO_REUSEADDR (** Allow reuse of local addresses for bind *)
+ | SO_KEEPALIVE (** Keep connection active *)
+ | SO_DONTROUTE (** Bypass the standard routing algorithms *)
+ | SO_OOBINLINE (** Leave out-of-band data in line *)
+ | SO_ACCEPTCONN (** Report whether socket listening is enabled *)
+ | TCP_NODELAY (** Control the Nagle algorithm for TCP sockets *)
+ | IPV6_ONLY (** Forbid binding an IPv6 socket to an IPv4 address *)
+(** The socket options that can be consulted with {!UnixLabels.getsockopt}
+ and modified with {!UnixLabels.setsockopt}. These options have a boolean
+ ([true]/[false]) value. *)
+
+type socket_int_option =
+ SO_SNDBUF (** Size of send buffer *)
+ | SO_RCVBUF (** Size of received buffer *)
+ | SO_ERROR (** Deprecated. Use {!Unix.getsockopt_error} instead. *)
+ | SO_TYPE (** Report the socket type *)
+ | SO_RCVLOWAT (** Minimum number of bytes to process for input operations *)
+ | SO_SNDLOWAT (** Minimum number of bytes to process for output operations *)
+(** The socket options that can be consulted with {!UnixLabels.getsockopt_int}
+ and modified with {!UnixLabels.setsockopt_int}. These options have an
+ integer value. *)
+
+type socket_optint_option =
+ SO_LINGER (** Whether to linger on closed connections
+ that have data present, and for how long
+ (in seconds) *)
+(** The socket options that can be consulted with {!Unix.getsockopt_optint}
+ and modified with {!Unix.setsockopt_optint}. These options have a
+ value of type [int option], with [None] meaning ``disabled''. *)
+
+type socket_float_option =
+ SO_RCVTIMEO (** Timeout for input operations *)
+ | SO_SNDTIMEO (** Timeout for output operations *)
+(** The socket options that can be consulted with {!UnixLabels.getsockopt_float}
+ and modified with {!UnixLabels.setsockopt_float}. These options have a
+ floating-point value representing a time in seconds.
+ The value 0 means infinite timeout. *)
+
+val getsockopt : file_descr -> socket_bool_option -> bool
+(** Return the current status of a boolean-valued option
+ in the given socket. *)
+
+val setsockopt : file_descr -> socket_bool_option -> bool -> unit
+(** Set or clear a boolean-valued option in the given socket. *)
+
+val getsockopt_int : file_descr -> socket_int_option -> int
+(** Same as {!Unix.getsockopt} for an integer-valued socket option. *)
+
+val setsockopt_int : file_descr -> socket_int_option -> int -> unit
+(** Same as {!Unix.setsockopt} for an integer-valued socket option. *)
+
+val getsockopt_optint : file_descr -> socket_optint_option -> int option
+(** Same as {!Unix.getsockopt} for a socket option whose value is
+ an [int option]. *)
+
+val setsockopt_optint :
+ file_descr -> socket_optint_option -> int option -> unit
+(** Same as {!Unix.setsockopt} for a socket option whose value is
+ an [int option]. *)
+
+val getsockopt_float : file_descr -> socket_float_option -> float
+(** Same as {!Unix.getsockopt} for a socket option whose value is a
+ floating-point number. *)
+
+val setsockopt_float : file_descr -> socket_float_option -> float -> unit
+(** Same as {!Unix.setsockopt} for a socket option whose value is a
+ floating-point number. *)
+
+val getsockopt_error : file_descr -> error option
+(** Return the error condition associated with the given socket,
+ and clear it. *)
+
+(** {6 High-level network connection functions} *)
+
+
+val open_connection : sockaddr -> in_channel * out_channel
+(** Connect to a server at the given address.
+ Return a pair of buffered channels connected to the server.
+ Remember to call {!Pervasives.flush} on the output channel at the right
+ times to ensure correct synchronization. *)
+
+val shutdown_connection : in_channel -> unit
+(** ``Shut down'' a connection established with {!UnixLabels.open_connection};
+ that is, transmit an end-of-file condition to the server reading
+ on the other side of the connection. *)
+
+val establish_server :
+ (in_channel -> out_channel -> unit) -> addr:sockaddr -> unit
+(** Establish a server on the given address.
+ The function given as first argument is called for each connection
+ with two buffered channels connected to the client. A new process
+ is created for each connection. The function {!UnixLabels.establish_server}
+ never returns normally. *)
+
+
+(** {6 Host and protocol databases} *)
+
+
+type host_entry = Unix.host_entry =
+ { h_name : string;
+ h_aliases : string array;
+ h_addrtype : socket_domain;
+ h_addr_list : inet_addr array
+ }
+(** Structure of entries in the [hosts] database. *)
+
+type protocol_entry = Unix.protocol_entry =
+ { p_name : string;
+ p_aliases : string array;
+ p_proto : int
+ }
+(** Structure of entries in the [protocols] database. *)
+
+type service_entry = Unix.service_entry =
+ { s_name : string;
+ s_aliases : string array;
+ s_port : int;
+ s_proto : string
+ }
+(** Structure of entries in the [services] database. *)
+
+val gethostname : unit -> string
+(** Return the name of the local host. *)
+
+val gethostbyname : string -> host_entry
+(** Find an entry in [hosts] with the given name, or raise
+ [Not_found]. *)
+
+val gethostbyaddr : inet_addr -> host_entry
+(** Find an entry in [hosts] with the given address, or raise
+ [Not_found]. *)
+
+val getprotobyname : string -> protocol_entry
+(** Find an entry in [protocols] with the given name, or raise
+ [Not_found]. *)
+
+val getprotobynumber : int -> protocol_entry
+(** Find an entry in [protocols] with the given protocol number,
+ or raise [Not_found]. *)
+
+val getservbyname : string -> protocol:string -> service_entry
+(** Find an entry in [services] with the given name, or raise
+ [Not_found]. *)
+
+val getservbyport : int -> protocol:string -> service_entry
+(** Find an entry in [services] with the given service number,
+ or raise [Not_found]. *)
+
+type addr_info =
+ { ai_family : socket_domain; (** Socket domain *)
+ ai_socktype : socket_type; (** Socket type *)
+ ai_protocol : int; (** Socket protocol number *)
+ ai_addr : sockaddr; (** Address *)
+ ai_canonname : string (** Canonical host name *)
+ }
+(** Address information returned by {!Unix.getaddrinfo}. *)
+
+type getaddrinfo_option =
+ AI_FAMILY of socket_domain (** Impose the given socket domain *)
+ | AI_SOCKTYPE of socket_type (** Impose the given socket type *)
+ | AI_PROTOCOL of int (** Impose the given protocol *)
+ | AI_NUMERICHOST (** Do not call name resolver,
+ expect numeric IP address *)
+ | AI_CANONNAME (** Fill the [ai_canonname] field
+ of the result *)
+ | AI_PASSIVE (** Set address to ``any'' address
+ for use with {!Unix.bind} *)
+(** Options to {!Unix.getaddrinfo}. *)
+
+val getaddrinfo:
+ string -> string -> getaddrinfo_option list -> addr_info list
+(** [getaddrinfo host service opts] returns a list of {!Unix.addr_info}
+ records describing socket parameters and addresses suitable for
+ communicating with the given host and service. The empty list is
+ returned if the host or service names are unknown, or the constraints
+ expressed in [opts] cannot be satisfied.
+
+ [host] is either a host name or the string representation of an IP
+ address. [host] can be given as the empty string; in this case,
+ the ``any'' address or the ``loopback'' address are used,
+ depending whether [opts] contains [AI_PASSIVE].
+ [service] is either a service name or the string representation of
+ a port number. [service] can be given as the empty string;
+ in this case, the port field of the returned addresses is set to 0.
+ [opts] is a possibly empty list of options that allows the caller
+ to force a particular socket domain (e.g. IPv6 only or IPv4 only)
+ or a particular socket type (e.g. TCP only or UDP only). *)
+
+type name_info =
+ { ni_hostname : string; (** Name or IP address of host *)
+ ni_service : string } (** Name of service or port number *)
+(** Host and service information returned by {!Unix.getnameinfo}. *)
+
+type getnameinfo_option =
+ NI_NOFQDN (** Do not qualify local host names *)
+ | NI_NUMERICHOST (** Always return host as IP address *)
+ | NI_NAMEREQD (** Fail if host name cannot be determined *)
+ | NI_NUMERICSERV (** Always return service as port number *)
+ | NI_DGRAM (** Consider the service as UDP-based
+ instead of the default TCP *)
+(** Options to {!Unix.getnameinfo}. *)
+
+val getnameinfo : sockaddr -> getnameinfo_option list -> name_info
+(** [getnameinfo addr opts] returns the host name and service name
+ corresponding to the socket address [addr]. [opts] is a possibly
+ empty list of options that governs how these names are obtained.
+ Raise [Not_found] if an error occurs. *)
+
+
+(** {6 Terminal interface} *)
+
+
+(** The following functions implement the POSIX standard terminal
+ interface. They provide control over asynchronous communication ports
+ and pseudo-terminals. Refer to the [termios] man page for a
+ complete description. *)
+
+type terminal_io = Unix.terminal_io =
+ {
+ (* input modes *)
+ mutable c_ignbrk : bool; (** Ignore the break condition. *)
+ mutable c_brkint : bool; (** Signal interrupt on break condition. *)
+ mutable c_ignpar : bool; (** Ignore characters with parity errors. *)
+ mutable c_parmrk : bool; (** Mark parity errors. *)
+ mutable c_inpck : bool; (** Enable parity check on input. *)
+ mutable c_istrip : bool; (** Strip 8th bit on input characters. *)
+ mutable c_inlcr : bool; (** Map NL to CR on input. *)
+ mutable c_igncr : bool; (** Ignore CR on input. *)
+ mutable c_icrnl : bool; (** Map CR to NL on input. *)
+ mutable c_ixon : bool; (** Recognize XON/XOFF characters on input. *)
+ mutable c_ixoff : bool; (** Emit XON/XOFF chars to control input flow. *)
+ (* Output modes: *)
+ mutable c_opost : bool; (** Enable output processing. *)
+ (* Control modes: *)
+ mutable c_obaud : int; (** Output baud rate (0 means close connection).*)
+ mutable c_ibaud : int; (** Input baud rate. *)
+ mutable c_csize : int; (** Number of bits per character (5-8). *)
+ mutable c_cstopb : int; (** Number of stop bits (1-2). *)
+ mutable c_cread : bool; (** Reception is enabled. *)
+ mutable c_parenb : bool; (** Enable parity generation and detection. *)
+ mutable c_parodd : bool; (** Specify odd parity instead of even. *)
+ mutable c_hupcl : bool; (** Hang up on last close. *)
+ mutable c_clocal : bool; (** Ignore modem status lines. *)
+ (* Local modes: *)
+ mutable c_isig : bool; (** Generate signal on INTR, QUIT, SUSP. *)
+ mutable c_icanon : bool; (** Enable canonical processing
+ (line buffering and editing) *)
+ mutable c_noflsh : bool; (** Disable flush after INTR, QUIT, SUSP. *)
+ mutable c_echo : bool; (** Echo input characters. *)
+ mutable c_echoe : bool; (** Echo ERASE (to erase previous character). *)
+ mutable c_echok : bool; (** Echo KILL (to erase the current line). *)
+ mutable c_echonl : bool; (** Echo NL even if c_echo is not set. *)
+ (* Control characters: *)
+ mutable c_vintr : char; (** Interrupt character (usually ctrl-C). *)
+ mutable c_vquit : char; (** Quit character (usually ctrl-\). *)
+ mutable c_verase : char; (** Erase character (usually DEL or ctrl-H). *)
+ mutable c_vkill : char; (** Kill line character (usually ctrl-U). *)
+ mutable c_veof : char; (** End-of-file character (usually ctrl-D). *)
+ mutable c_veol : char; (** Alternate end-of-line char. (usually none). *)
+ mutable c_vmin : int; (** Minimum number of characters to read
+ before the read request is satisfied. *)
+ mutable c_vtime : int; (** Maximum read wait (in 0.1s units). *)
+ mutable c_vstart : char; (** Start character (usually ctrl-Q). *)
+ mutable c_vstop : char; (** Stop character (usually ctrl-S). *)
+ }
+
+val tcgetattr : file_descr -> terminal_io
+(** Return the status of the terminal referred to by the given
+ file descriptor. *)
+
+type setattr_when = Unix.setattr_when =
+ TCSANOW
+ | TCSADRAIN
+ | TCSAFLUSH
+
+val tcsetattr : file_descr -> mode:setattr_when -> terminal_io -> unit
+(** Set the status of the terminal referred to by the given
+ file descriptor. The second argument indicates when the
+ status change takes place: immediately ([TCSANOW]),
+ when all pending output has been transmitted ([TCSADRAIN]),
+ or after flushing all input that has been received but not
+ read ([TCSAFLUSH]). [TCSADRAIN] is recommended when changing
+ the output parameters; [TCSAFLUSH], when changing the input
+ parameters. *)
+
+val tcsendbreak : file_descr -> duration:int -> unit
+(** Send a break condition on the given file descriptor.
+ The second argument is the duration of the break, in 0.1s units;
+ 0 means standard duration (0.25s). *)
+
+val tcdrain : file_descr -> unit
+(** Waits until all output written on the given file descriptor
+ has been transmitted. *)
+
+type flush_queue = Unix.flush_queue =
+ TCIFLUSH
+ | TCOFLUSH
+ | TCIOFLUSH
+
+val tcflush : file_descr -> mode:flush_queue -> unit
+(** Discard data written on the given file descriptor but not yet
+ transmitted, or data received but not yet read, depending on the
+ second argument: [TCIFLUSH] flushes data received but not read,
+ [TCOFLUSH] flushes data written but not transmitted, and
+ [TCIOFLUSH] flushes both. *)
+
+type flow_action = Unix.flow_action =
+ TCOOFF
+ | TCOON
+ | TCIOFF
+ | TCION
+
+val tcflow : file_descr -> mode:flow_action -> unit
+(** Suspend or restart reception or transmission of data on
+ the given file descriptor, depending on the second argument:
+ [TCOOFF] suspends output, [TCOON] restarts output,
+ [TCIOFF] transmits a STOP character to suspend input,
+ and [TCION] transmits a START character to restart input. *)
+
+val setsid : unit -> int
+(** Put the calling process in a new session and detach it from
+ its controlling terminal. *)
diff --git a/otherlibs/unix/unixsupport.c b/otherlibs/unix/unixsupport.c
new file mode 100644
index 0000000000..6c7171fdd6
--- /dev/null
+++ b/otherlibs/unix/unixsupport.c
@@ -0,0 +1,309 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/callback.h>
+#include <caml/memory.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+#include "cst2constr.h"
+#include <errno.h>
+
+#ifndef E2BIG
+#define E2BIG (-1)
+#endif
+#ifndef EACCES
+#define EACCES (-1)
+#endif
+#ifndef EAGAIN
+#define EAGAIN (-1)
+#endif
+#ifndef EBADF
+#define EBADF (-1)
+#endif
+#ifndef EBUSY
+#define EBUSY (-1)
+#endif
+#ifndef ECHILD
+#define ECHILD (-1)
+#endif
+#ifndef EDEADLK
+#define EDEADLK (-1)
+#endif
+#ifndef EDOM
+#define EDOM (-1)
+#endif
+#ifndef EEXIST
+#define EEXIST (-1)
+#endif
+
+#ifndef EFAULT
+#define EFAULT (-1)
+#endif
+#ifndef EFBIG
+#define EFBIG (-1)
+#endif
+#ifndef EINTR
+#define EINTR (-1)
+#endif
+#ifndef EINVAL
+#define EINVAL (-1)
+#endif
+#ifndef EIO
+#define EIO (-1)
+#endif
+#ifndef EISDIR
+#define EISDIR (-1)
+#endif
+#ifndef EMFILE
+#define EMFILE (-1)
+#endif
+#ifndef EMLINK
+#define EMLINK (-1)
+#endif
+#ifndef ENAMETOOLONG
+#define ENAMETOOLONG (-1)
+#endif
+#ifndef ENFILE
+#define ENFILE (-1)
+#endif
+#ifndef ENODEV
+#define ENODEV (-1)
+#endif
+#ifndef ENOENT
+#define ENOENT (-1)
+#endif
+#ifndef ENOEXEC
+#define ENOEXEC (-1)
+#endif
+#ifndef ENOLCK
+#define ENOLCK (-1)
+#endif
+#ifndef ENOMEM
+#define ENOMEM (-1)
+#endif
+#ifndef ENOSPC
+#define ENOSPC (-1)
+#endif
+#ifndef ENOSYS
+#define ENOSYS (-1)
+#endif
+#ifndef ENOTDIR
+#define ENOTDIR (-1)
+#endif
+#ifndef ENOTEMPTY
+#define ENOTEMPTY (-1)
+#endif
+#ifndef ENOTTY
+#define ENOTTY (-1)
+#endif
+#ifndef ENXIO
+#define ENXIO (-1)
+#endif
+#ifndef EPERM
+#define EPERM (-1)
+#endif
+#ifndef EPIPE
+#define EPIPE (-1)
+#endif
+#ifndef ERANGE
+#define ERANGE (-1)
+#endif
+#ifndef EROFS
+#define EROFS (-1)
+#endif
+#ifndef ESPIPE
+#define ESPIPE (-1)
+#endif
+#ifndef ESRCH
+#define ESRCH (-1)
+#endif
+#ifndef EXDEV
+#define EXDEV (-1)
+#endif
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK (-1)
+#endif
+#ifndef EINPROGRESS
+#define EINPROGRESS (-1)
+#endif
+#ifndef EALREADY
+#define EALREADY (-1)
+#endif
+#ifndef ENOTSOCK
+#define ENOTSOCK (-1)
+#endif
+#ifndef EDESTADDRREQ
+#define EDESTADDRREQ (-1)
+#endif
+#ifndef EMSGSIZE
+#define EMSGSIZE (-1)
+#endif
+#ifndef EPROTOTYPE
+#define EPROTOTYPE (-1)
+#endif
+#ifndef ENOPROTOOPT
+#define ENOPROTOOPT (-1)
+#endif
+#ifndef EPROTONOSUPPORT
+#define EPROTONOSUPPORT (-1)
+#endif
+#ifndef ESOCKTNOSUPPORT
+#define ESOCKTNOSUPPORT (-1)
+#endif
+#ifndef EOPNOTSUPP
+# ifdef ENOTSUP
+# define EOPNOTSUPP ENOTSUP
+# else
+# define EOPNOTSUPP (-1)
+# endif
+#endif
+#ifndef EPFNOSUPPORT
+#define EPFNOSUPPORT (-1)
+#endif
+#ifndef EAFNOSUPPORT
+#define EAFNOSUPPORT (-1)
+#endif
+#ifndef EADDRINUSE
+#define EADDRINUSE (-1)
+#endif
+#ifndef EADDRNOTAVAIL
+#define EADDRNOTAVAIL (-1)
+#endif
+#ifndef ENETDOWN
+#define ENETDOWN (-1)
+#endif
+#ifndef ENETUNREACH
+#define ENETUNREACH (-1)
+#endif
+#ifndef ENETRESET
+#define ENETRESET (-1)
+#endif
+#ifndef ECONNABORTED
+#define ECONNABORTED (-1)
+#endif
+#ifndef ECONNRESET
+#define ECONNRESET (-1)
+#endif
+#ifndef ENOBUFS
+#define ENOBUFS (-1)
+#endif
+#ifndef EISCONN
+#define EISCONN (-1)
+#endif
+#ifndef ENOTCONN
+#define ENOTCONN (-1)
+#endif
+#ifndef ESHUTDOWN
+#define ESHUTDOWN (-1)
+#endif
+#ifndef ETOOMANYREFS
+#define ETOOMANYREFS (-1)
+#endif
+#ifndef ETIMEDOUT
+#define ETIMEDOUT (-1)
+#endif
+#ifndef ECONNREFUSED
+#define ECONNREFUSED (-1)
+#endif
+#ifndef EHOSTDOWN
+#define EHOSTDOWN (-1)
+#endif
+#ifndef EHOSTUNREACH
+#define EHOSTUNREACH (-1)
+#endif
+#ifndef ENOTEMPTY
+#define ENOTEMPTY (-1)
+#endif
+#ifndef ELOOP
+#define ELOOP (-1)
+#endif
+#ifndef EOVERFLOW
+#define EOVERFLOW (-1)
+#endif
+
+int error_table[] = {
+ E2BIG, EACCES, EAGAIN, EBADF, EBUSY, ECHILD, EDEADLK, EDOM,
+ EEXIST, EFAULT, EFBIG, EINTR, EINVAL, EIO, EISDIR, EMFILE, EMLINK,
+ ENAMETOOLONG, ENFILE, ENODEV, ENOENT, ENOEXEC, ENOLCK, ENOMEM, ENOSPC,
+ ENOSYS, ENOTDIR, ENOTEMPTY, ENOTTY, ENXIO, EPERM, EPIPE, ERANGE,
+ EROFS, ESPIPE, ESRCH, EXDEV, EWOULDBLOCK, EINPROGRESS, EALREADY,
+ ENOTSOCK, EDESTADDRREQ, EMSGSIZE, EPROTOTYPE, ENOPROTOOPT,
+ EPROTONOSUPPORT, ESOCKTNOSUPPORT, EOPNOTSUPP, EPFNOSUPPORT,
+ EAFNOSUPPORT, EADDRINUSE, EADDRNOTAVAIL, ENETDOWN, ENETUNREACH,
+ ENETRESET, ECONNABORTED, ECONNRESET, ENOBUFS, EISCONN, ENOTCONN,
+ ESHUTDOWN, ETOOMANYREFS, ETIMEDOUT, ECONNREFUSED, EHOSTDOWN,
+ EHOSTUNREACH, ELOOP, EOVERFLOW /*, EUNKNOWNERR */
+};
+
+static value * unix_error_exn = NULL;
+
+value unix_error_of_code (int errcode)
+{
+ int errconstr;
+ value err;
+
+#if defined(ENOTSUP) && (EOPNOTSUPP != ENOTSUP)
+ if (errcode == ENOTSUP)
+ errcode = EOPNOTSUPP;
+#endif
+
+ errconstr =
+ cst_to_constr(errcode, error_table, sizeof(error_table)/sizeof(int), -1);
+ if (errconstr == Val_int(-1)) {
+ err = alloc_small(1, 0);
+ Field(err, 0) = Val_int(errcode);
+ } else {
+ err = errconstr;
+ }
+ return err;
+}
+
+extern int code_of_unix_error (value error)
+{
+ if (Is_block(error)) {
+ return Int_val(Field(error, 0));
+ } else {
+ return error_table[Int_val(error)];
+ }
+}
+
+void unix_error(int errcode, char *cmdname, value cmdarg)
+{
+ value res;
+ value name = Val_unit, err = Val_unit, arg = Val_unit;
+
+ Begin_roots3 (name, err, arg);
+ arg = cmdarg == Nothing ? copy_string("") : cmdarg;
+ name = copy_string(cmdname);
+ err = unix_error_of_code (errcode);
+ if (unix_error_exn == NULL) {
+ unix_error_exn = caml_named_value("Unix.Unix_error");
+ if (unix_error_exn == NULL)
+ invalid_argument("Exception Unix.Unix_error not initialized,"
+ " please link unix.cma");
+ }
+ res = alloc_small(4, 0);
+ Field(res, 0) = *unix_error_exn;
+ Field(res, 1) = err;
+ Field(res, 2) = name;
+ Field(res, 3) = arg;
+ End_roots();
+ mlraise(res);
+}
+
+void uerror(char *cmdname, value cmdarg)
+{
+ unix_error(errno, cmdname, cmdarg);
+}
diff --git a/otherlibs/unix/unixsupport.h b/otherlibs/unix/unixsupport.h
new file mode 100644
index 0000000000..a6a690b834
--- /dev/null
+++ b/otherlibs/unix/unixsupport.h
@@ -0,0 +1,46 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_UNIXSUPPORT_H
+#define CAML_UNIXSUPPORT_H
+
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define Nothing ((value) 0)
+
+extern value unix_error_of_code (int errcode);
+extern int code_of_unix_error (value error);
+
+CAMLnoreturn_start
+extern void unix_error (int errcode, char * cmdname, value arg)
+CAMLnoreturn_end;
+
+CAMLnoreturn_start
+extern void uerror (char * cmdname, value arg)
+CAMLnoreturn_end;
+
+#define UNIX_BUFFER_SIZE 65536
+
+#define DIR_Val(v) *((DIR **) &Field(v, 0))
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_UNIXSUPPORT_H */
diff --git a/otherlibs/unix/unlink.c b/otherlibs/unix/unlink.c
new file mode 100644
index 0000000000..687c69c26a
--- /dev/null
+++ b/otherlibs/unix/unlink.c
@@ -0,0 +1,31 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_unlink(value path)
+{
+ CAMLparam1(path);
+ char * p;
+ int ret;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = unlink(p);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("unlink", path);
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/unix/utimes.c b/otherlibs/unix/utimes.c
new file mode 100644
index 0000000000..bf2ae2fb26
--- /dev/null
+++ b/otherlibs/unix/utimes.c
@@ -0,0 +1,88 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/fail.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifdef HAS_UTIME
+
+#include <sys/types.h>
+#ifndef _WIN32
+#include <utime.h>
+#else
+#include <sys/utime.h>
+#endif
+
+CAMLprim value unix_utimes(value path, value atime, value mtime)
+{
+ CAMLparam3(path, atime, mtime);
+ struct utimbuf times, * t;
+ char * p;
+ int ret;
+ times.actime = Double_val(atime);
+ times.modtime = Double_val(mtime);
+ if (times.actime || times.modtime)
+ t = &times;
+ else
+ t = (struct utimbuf *) NULL;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = utime(p, t);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("utimes", path);
+ CAMLreturn(Val_unit);
+}
+
+#else
+
+#ifdef HAS_UTIMES
+
+#include <sys/types.h>
+#include <sys/time.h>
+
+CAMLprim value unix_utimes(value path, value atime, value mtime)
+{
+ CAMLparam3(path, atime, mtime);
+ struct timeval tv[2], * t;
+ char * p;
+ int ret;
+ double at = Double_val(atime);
+ double mt = Double_val(mtime);
+ tv[0].tv_sec = at;
+ tv[0].tv_usec = (at - tv[0].tv_sec) * 1000000;
+ tv[1].tv_sec = mt;
+ tv[1].tv_usec = (mt - tv[1].tv_sec) * 1000000;
+ if (tv[0].tv_sec || tv[1].tv_sec)
+ t = tv;
+ else
+ t = (struct timeval *) NULL;
+ p = caml_strdup(String_val(path));
+ caml_enter_blocking_section();
+ ret = utimes(p, t);
+ caml_leave_blocking_section();
+ caml_stat_free(p);
+ if (ret == -1) uerror("utimes", path);
+ CAMLreturn(Val_unit);
+}
+
+#else
+
+CAMLprim value unix_utimes(value path, value atime, value mtime)
+{ invalid_argument("utimes not implemented"); }
+
+#endif
+#endif
diff --git a/otherlibs/unix/wait.c b/otherlibs/unix/wait.c
new file mode 100644
index 0000000000..a8eb42b78e
--- /dev/null
+++ b/otherlibs/unix/wait.c
@@ -0,0 +1,100 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#if !(defined(WIFEXITED) && defined(WEXITSTATUS) && defined(WIFSTOPPED) && \
+ defined(WSTOPSIG) && defined(WTERMSIG))
+/* Assume old-style V7 status word */
+#define WIFEXITED(status) (((status) & 0xFF) == 0)
+#define WEXITSTATUS(status) (((status) >> 8) & 0xFF)
+#define WIFSTOPPED(status) (((status) & 0xFF) == 0xFF)
+#define WSTOPSIG(status) (((status) >> 8) & 0xFF)
+#define WTERMSIG(status) ((status) & 0x3F)
+#endif
+
+#define TAG_WEXITED 0
+#define TAG_WSIGNALED 1
+#define TAG_WSTOPPED 2
+
+static value alloc_process_status(int pid, int status)
+{
+ value st, res;
+
+ if (WIFEXITED(status)) {
+ st = alloc_small(1, TAG_WEXITED);
+ Field(st, 0) = Val_int(WEXITSTATUS(status));
+ }
+ else if (WIFSTOPPED(status)) {
+ st = alloc_small(1, TAG_WSTOPPED);
+ Field(st, 0) = Val_int(caml_rev_convert_signal_number(WSTOPSIG(status)));
+ }
+ else {
+ st = alloc_small(1, TAG_WSIGNALED);
+ Field(st, 0) = Val_int(caml_rev_convert_signal_number(WTERMSIG(status)));
+ }
+ Begin_root (st);
+ res = alloc_small(2, 0);
+ Field(res, 0) = Val_int(pid);
+ Field(res, 1) = st;
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_wait(value unit)
+{
+ int pid, status;
+
+ enter_blocking_section();
+ pid = wait(&status);
+ leave_blocking_section();
+ if (pid == -1) uerror("wait", Nothing);
+ return alloc_process_status(pid, status);
+}
+
+#if defined(HAS_WAITPID) || defined(HAS_WAIT4)
+
+#ifndef HAS_WAITPID
+#define waitpid(pid,status,opts) wait4(pid,status,opts,NULL)
+#endif
+
+static int wait_flag_table[] = {
+ WNOHANG, WUNTRACED
+};
+
+CAMLprim value unix_waitpid(value flags, value pid_req)
+{
+ int pid, status, cv_flags;
+
+ cv_flags = convert_flag_list(flags, wait_flag_table);
+ enter_blocking_section();
+ pid = waitpid(Int_val(pid_req), &status, cv_flags);
+ leave_blocking_section();
+ if (pid == -1) uerror("waitpid", Nothing);
+ return alloc_process_status(pid, status);
+}
+
+#else
+
+CAMLprim value unix_waitpid(value flags, value pid_req)
+{ invalid_argument("waitpid not implemented"); }
+
+#endif
diff --git a/otherlibs/unix/write.c b/otherlibs/unix/write.c
new file mode 100644
index 0000000000..d6842d9f87
--- /dev/null
+++ b/otherlibs/unix/write.c
@@ -0,0 +1,84 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+#ifndef EAGAIN
+#define EAGAIN (-1)
+#endif
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK (-1)
+#endif
+
+CAMLprim value unix_write(value fd, value buf, value vofs, value vlen)
+{
+ long ofs, len, written;
+ int numbytes, ret;
+ char iobuf[UNIX_BUFFER_SIZE];
+
+ Begin_root (buf);
+ ofs = Long_val(vofs);
+ len = Long_val(vlen);
+ written = 0;
+ while (len > 0) {
+ numbytes = len > UNIX_BUFFER_SIZE ? UNIX_BUFFER_SIZE : len;
+ memmove (iobuf, &Byte(buf, ofs), numbytes);
+ enter_blocking_section();
+ ret = write(Int_val(fd), iobuf, numbytes);
+ leave_blocking_section();
+ if (ret == -1) {
+ if ((errno == EAGAIN || errno == EWOULDBLOCK) && written > 0) break;
+ uerror("write", Nothing);
+ }
+ written += ret;
+ ofs += ret;
+ len -= ret;
+ }
+ End_roots();
+ return Val_long(written);
+}
+
+/* When an error occurs after the first loop, unix_write reports the
+ error and discards the number of already written characters.
+ In this case, it would be better to discard the error and return the
+ number of bytes written, since most likely, unix_write will be call again,
+ and the error will be reproduced and this time will be reported.
+ This problem is avoided in unix_single_write, which is faithful to the
+ Unix system call. */
+
+CAMLprim value unix_single_write(value fd, value buf, value vofs, value vlen)
+{
+ long ofs, len;
+ int numbytes, ret;
+ char iobuf[UNIX_BUFFER_SIZE];
+
+ Begin_root (buf);
+ ofs = Long_val(vofs);
+ len = Long_val(vlen);
+ ret = 0;
+ if (len > 0) {
+ numbytes = len > UNIX_BUFFER_SIZE ? UNIX_BUFFER_SIZE : len;
+ memmove (iobuf, &Byte(buf, ofs), numbytes);
+ enter_blocking_section();
+ ret = write(Int_val(fd), iobuf, numbytes);
+ leave_blocking_section();
+ if (ret == -1) uerror("single_write", Nothing);
+ }
+ End_roots();
+ return Val_int(ret);
+}
diff --git a/otherlibs/win32graph/.ignore b/otherlibs/win32graph/.ignore
new file mode 100644
index 0000000000..090a9a2537
--- /dev/null
+++ b/otherlibs/win32graph/.ignore
@@ -0,0 +1,2 @@
+graphics.ml
+graphics.mli
diff --git a/otherlibs/win32graph/Makefile.nt b/otherlibs/win32graph/Makefile.nt
new file mode 100644
index 0000000000..f09392ed74
--- /dev/null
+++ b/otherlibs/win32graph/Makefile.nt
@@ -0,0 +1,33 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2001 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+LIBNAME=graphics
+COBJS=open.$(O) draw.$(O) events.$(O) dib.$(O)
+CAMLOBJS=graphics.cmo
+WIN32LIBS=$(call SYSLIB,kernel32) $(call SYSLIB,gdi32) $(call SYSLIB,user32)
+LINKOPTS=-cclib "\"$(WIN32LIBS)\""
+LDOPTS=-ldopt "$(WIN32LIBS)"
+
+include ../Makefile.nt
+
+graphics.ml: ../graph/graphics.ml
+ cp ../graph/graphics.ml graphics.ml
+graphics.mli: ../graph/graphics.mli
+ cp ../graph/graphics.mli graphics.mli
+
+depend:
+
+graphics.cmo: graphics.cmi
+graphics.cmx: graphics.cmi
+draw.$(O): libgraph.h
+open.$(O): libgraph.h
diff --git a/otherlibs/win32graph/dib.c b/otherlibs/win32graph/dib.c
new file mode 100644
index 0000000000..4c489d5278
--- /dev/null
+++ b/otherlibs/win32graph/dib.c
@@ -0,0 +1,497 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Developed by Jacob Navia */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+//-----------------------------------------------------------------------------
+// DIB.C
+//
+// This is a collection of useful DIB manipulation/information gathering
+// functions. Many functions are supplied simply to take the burden
+// of taking into account whether a DIB is a Win30 style or OS/2 style
+// DIB away from the application.
+//
+// The functions in this module assume that the DIB pointers or handles
+// passed to them point to a block of memory in one of two formats:
+//
+// a) BITMAPINFOHEADER + color table + DIB bits (3.0 style DIB)
+// b) BITMAPCOREHEADER + color table + DIB bits (OS/2 PM style)
+//
+// The SDK Reference, Volume 2 describes these data structures.
+//
+// A number of functions in this module were lifted from SHOWDIB,
+// and modified to handle OS/2 DIBs.
+//
+// The functions in this module could be streamlined (made faster and
+// smaller) by removing the OS/2 DIB specific code, and assuming all
+// DIBs passed to it are Win30 style DIBs. The DIB file reading code
+// would need to be modified to always convert DIBs to Win30 style
+// DIBs. The only reason this isn't done in DIBView is because DIBView
+// was written to test display and printer drivers (which are supposed
+// to support OS/2 DIBs wherever they support Win30 style DIBs). SHOWDIB
+// is a great example of how to go about doing this.
+//-----------------------------------------------------------------------------
+
+
+#include <windows.h>
+#include <caml/memory.h>
+#include <string.h>
+#include <caml/io.h>
+#include <stdio.h>
+ // Size of window extra bytes (we store a handle to a PALINFO structure).
+
+#define PAL_CBWNDEXTRA (1 * sizeof (WORD))
+
+
+typedef struct
+ {
+ HPALETTE hPal; // Handle to palette being displayed.
+ WORD wEntries; // # of entries in the palette.
+ int nSquareSize; // Size of palette square (see PAL_SIZE)
+ HWND hInfoWnd; // Handle to the info bar window.
+ int nRows, nCols; // # of Rows/Columns in window.
+ int cxSquare, cySquare; // Pixel width/height of palette square.
+ WORD wEntry; // Currently selected palette square.
+ } PALINFO, FAR *LPPALINFO;
+ // Window Words.
+#define WW_PAL_HPALINFO 0 // Handle to PALINFO structure.
+ // The following define is for CopyPaletteChangingFlags().
+#define DONT_CHANGE_FLAGS -1
+ // The following is the palette version that goes in a
+ // LOGPALETTE's palVersion field.
+#define PALVERSION 0x300
+// This is an enumeration for the various ways we can display
+// a palette in PaletteWndProc().
+enum PAL_SIZE
+ {
+ PALSIZE_TINY = 0,
+ PALSIZE_SMALL,
+ PALSIZE_MEDIUM,
+ PALSIZE_LARGE
+ };
+#define CopyPalette(hPal) CopyPaletteChangingFlags (hPal, DONT_CHANGE_FLAGS)
+#define CopyPalForAnimation(hPal) CopyPaletteChangingFlags (hPal, PC_RESERVED)
+// WIDTHBYTES takes # of bits in a scan line and rounds up to nearest
+// word.
+#define WIDTHBYTES(bits) (((bits) + 31) / 32 * 4)
+
+ // Given a pointer to a DIB header, return TRUE if is a Windows 3.0 style
+ // DIB, false if otherwise (PM style DIB).
+#define IS_WIN30_DIB(lpbi) ((*(LPDWORD) (lpbi)) == sizeof (BITMAPINFOHEADER))
+
+static WORD PaletteSize (LPSTR lpbi);
+
+extern void ShowDbgMsg(char *);
+static BOOL MyRead (int, LPSTR, DWORD);
+/*-------------- DIB header Marker Define -------------------------*/
+#define DIB_HEADER_MARKER ((WORD) ('M' << 8) | 'B')
+/*-------------- MyRead Function Define ---------------------------*/
+
+// When we read in a DIB, we read it in in chunks. We read half a segment
+// at a time. This way we insure that we don't cross any segment
+// boundries in _lread() during a read. We don't read in a full segment
+// at a time, since _lread takes some "int" type parms instead of
+// WORD type params (it'd work, but the compiler would give you warnings)...
+
+#define BYTES_PER_READ 32767
+
+/*-------------- Define for PM DIB -------------------------------*/
+// The constants for RGB, RLE4, RLE8 are already defined inside
+// of Windows.h
+
+#define BI_PM 3L
+
+
+/*-------------- Magic numbers -------------------------------------*/
+// Maximum length of a filename for DOS is 128 characters.
+
+#define MAX_FILENAME 129
+
+
+/*-------------- TypeDef Structures -------------------------------*/
+
+typedef struct InfoStruct
+ {
+ char szName[13];
+ char szType[15];
+ DWORD cbWidth;
+ DWORD cbHeight;
+ DWORD cbColors;
+ char szCompress[5];
+ } INFOSTRUCT;
+
+// Some macros.
+#define RECTWIDTH(lpRect) ((lpRect)->right - (lpRect)->left)
+#define RECTHEIGHT(lpRect) ((lpRect)->bottom - (lpRect)->top)
+//---------------------------------------------------------------------
+//
+// Function: FindDIBBits
+//
+// Purpose: Given a pointer to a DIB, returns a pointer to the
+// DIB's bitmap bits.
+//
+// Parms: lpbi == pointer to DIB header (either BITMAPINFOHEADER
+// or BITMAPCOREHEADER)
+//
+// History: Date Reason
+// 6/01/91 Created
+//
+//---------------------------------------------------------------------
+static LPSTR FindDIBBits (LPSTR lpbi)
+{
+ return (lpbi + *(LPDWORD)lpbi + PaletteSize (lpbi));
+}
+
+
+//---------------------------------------------------------------------
+//
+// Function: DIBNumColors
+//
+// Purpose: Given a pointer to a DIB, returns a number of colors in
+// the DIB's color table.
+//
+// Parms: lpbi == pointer to DIB header (either BITMAPINFOHEADER
+// or BITMAPCOREHEADER)
+//
+// History: Date Reason
+// 6/01/91 Created
+//
+//---------------------------------------------------------------------
+static WORD DIBNumColors (LPSTR lpbi)
+{
+ WORD wBitCount;
+
+
+ // If this is a Windows style DIB, the number of colors in the
+ // color table can be less than the number of bits per pixel
+ // allows for (i.e. lpbi->biClrUsed can be set to some value).
+ // If this is the case, return the appropriate value.
+
+ if (IS_WIN30_DIB (lpbi))
+ {
+ DWORD dwClrUsed;
+
+ dwClrUsed = ((LPBITMAPINFOHEADER) lpbi)->biClrUsed;
+
+ if (dwClrUsed)
+ return (WORD) dwClrUsed;
+ }
+
+
+ // Calculate the number of colors in the color table based on
+ // the number of bits per pixel for the DIB.
+
+ if (IS_WIN30_DIB (lpbi))
+ wBitCount = ((LPBITMAPINFOHEADER) lpbi)->biBitCount;
+ else
+ wBitCount = ((LPBITMAPCOREHEADER) lpbi)->bcBitCount;
+
+ switch (wBitCount)
+ {
+ case 1:
+ return 2;
+
+ case 4:
+ return 16;
+
+ case 8:
+ return 256;
+
+ default:
+ return 0;
+ }
+}
+
+//---------------------------------------------------------------------
+//
+// Function: PaletteSize
+//
+// Purpose: Given a pointer to a DIB, returns number of bytes
+// in the DIB's color table.
+//
+// Parms: lpbi == pointer to DIB header (either BITMAPINFOHEADER
+// or BITMAPCOREHEADER)
+//
+// History: Date Reason
+// 6/01/91 Created
+//
+//---------------------------------------------------------------------
+static WORD PaletteSize (LPSTR lpbi)
+{
+ if (IS_WIN30_DIB (lpbi))
+ return (DIBNumColors (lpbi) * sizeof (RGBQUAD));
+ else
+ return (DIBNumColors (lpbi) * sizeof (RGBTRIPLE));
+}
+
+//---------------------------------------------------------------------
+//
+// Function: DIBHeight
+//
+// Purpose: Given a pointer to a DIB, returns its height. Note
+// that it returns a DWORD (since a Win30 DIB can have
+// a DWORD in its height field), but under Win30, the
+// high order word isn't used!
+//
+// Parms: lpDIB == pointer to DIB header (either BITMAPINFOHEADER
+// or BITMAPCOREHEADER)
+//
+// History: Date Reason
+// 6/01/91 Created
+//
+//---------------------------------------------------------------------
+static DWORD DIBHeight (LPSTR lpDIB)
+{
+ LPBITMAPINFOHEADER lpbmi;
+ LPBITMAPCOREHEADER lpbmc;
+
+ lpbmi = (LPBITMAPINFOHEADER) lpDIB;
+ lpbmc = (LPBITMAPCOREHEADER) lpDIB;
+
+ if (lpbmi->biSize == sizeof (BITMAPINFOHEADER))
+ return lpbmi->biHeight;
+ else
+ return (DWORD) lpbmc->bcHeight;
+}
+
+/*************************************************************************
+
+ Function: ReadDIBFile (int)
+
+ Purpose: Reads in the specified DIB file into a global chunk of
+ memory.
+
+ Returns: A handle to a dib (hDIB) if successful.
+ NULL if an error occurs.
+
+ Comments: BITMAPFILEHEADER is stripped off of the DIB. Everything
+ from the end of the BITMAPFILEHEADER structure on is
+ returned in the global memory handle.
+
+ History: Date Author Reason
+
+ 6/1/91 Created
+ 6/27/91 Removed PM bitmap conversion routines.
+ 6/31/91 Removed logic which overallocated memory
+ (to account for bad display drivers).
+ 11/08/91 Again removed logic which overallocated
+ memory (it had creeped back in!)
+
+*************************************************************************/
+static HANDLE ReadDIBFile (int hFile,int dwBitsSize)
+{
+ BITMAPFILEHEADER bmfHeader;
+ HANDLE hDIB;
+ LPSTR pDIB;
+
+
+
+ // Go read the DIB file header and check if it's valid.
+
+ if ((_lread (hFile, (LPSTR) &bmfHeader, sizeof (bmfHeader))
+ != sizeof (bmfHeader))
+ || (bmfHeader.bfType != DIB_HEADER_MARKER))
+ {
+ // ShowDbgMsg("Not a DIB file!");
+ return NULL;
+ }
+
+ // Allocate memory for DIB
+
+ hDIB = GlobalAlloc (GMEM_SHARE|GMEM_MOVEABLE | GMEM_ZEROINIT,
+ dwBitsSize - sizeof(BITMAPFILEHEADER));
+
+ if (hDIB == 0)
+ {
+ // ShowDbgMsg("Couldn't allocate memory!");
+ return NULL;
+ }
+
+ pDIB = GlobalLock (hDIB);
+
+ // Go read the bits.
+
+ if (!MyRead (hFile, pDIB, dwBitsSize - sizeof(BITMAPFILEHEADER)))
+ {
+ GlobalUnlock (hDIB);
+ GlobalFree (hDIB);
+ // ShowDbgMsg("Error reading file!");
+ return NULL;
+ }
+
+
+ GlobalUnlock (hDIB);
+ return hDIB;
+}
+
+/*************************************************************************
+
+ Function: MyRead (int, LPSTR, DWORD)
+
+ Purpose: Routine to read files greater than 64K in size.
+
+ Returns: TRUE if successful.
+ FALSE if an error occurs.
+
+ Comments:
+
+ History: Date Reason
+
+ 6/1/91 Created
+
+*************************************************************************/
+static BOOL MyRead (int hFile, LPSTR lpBuffer, DWORD dwSize)
+{
+ char *lpInBuf = (char *) lpBuffer;
+ int nBytes;
+
+
+ while (dwSize)
+ {
+ nBytes = (int) (dwSize > (DWORD) BYTES_PER_READ ? BYTES_PER_READ :
+ LOWORD (dwSize));
+
+ if (_lread (hFile, (LPSTR) lpInBuf, nBytes) != (WORD) nBytes)
+ return FALSE;
+
+ dwSize -= nBytes;
+ lpInBuf += nBytes;
+ }
+
+ return TRUE;
+}
+
+//---------------------------------------------------------------------
+//
+// Function: DIBPaint
+//
+// Purpose: Painting routine for a DIB. Calls StretchDIBits() or
+// SetDIBitsToDevice() to paint the DIB. The DIB is
+// output to the specified DC, at the coordinates given
+// in lpDCRect. The area of the DIB to be output is
+// given by lpDIBRect. The specified palette is used.
+//
+// Parms: hDC == DC to do output to.
+// lpDCRect == Rectangle on DC to do output to.
+// hDIB == Handle to global memory with a DIB spec
+// in it (either a BITMAPINFO or BITMAPCOREINFO
+// followed by the DIB bits).
+// lpDIBRect == Rect of DIB to output into lpDCRect.
+// hPal == Palette to be used.
+//
+// History: Date Reason
+// 6/01/91 Created
+//
+//---------------------------------------------------------------------
+static void DIBPaint (HDC hDC,LPRECT lpDCRect,HANDLE hDIB)
+{
+ LPSTR lpDIBHdr, lpDIBBits;
+
+ if (!hDIB)
+ return;
+ // Lock down the DIB, and get a pointer to the beginning of the bit
+ // buffer.
+ lpDIBHdr = GlobalLock (hDIB);
+ lpDIBBits = FindDIBBits (lpDIBHdr);
+ // Make sure to use the stretching mode best for color pictures.
+ SetStretchBltMode (hDC, COLORONCOLOR);
+ SetDIBitsToDevice (hDC, // hDC
+ lpDCRect->left, // DestX
+ lpDCRect->top, // DestY
+ RECTWIDTH (lpDCRect), // nDestWidth
+ RECTHEIGHT (lpDCRect), // nDestHeight
+ 0, // SrcX
+ 0,
+ // (int) DIBHeight (lpDIBHdr), // SrcY
+ 0, // nStartScan
+ (WORD) DIBHeight (lpDIBHdr), // nNumScans
+ lpDIBBits, // lpBits
+ (LPBITMAPINFO) lpDIBHdr, // lpBitsInfo
+ DIB_RGB_COLORS); // wUsage
+
+ GlobalUnlock (hDIB);
+}
+
+static unsigned int Getfilesize(char *name)
+{
+ FILE *f;
+ unsigned int size;
+
+ f = fopen(name,"rb");
+ if (f == NULL)
+ return 0;
+ fseek(f,0,SEEK_END);
+ size = ftell(f);
+ fclose(f);
+ return size;
+}
+
+
+HANDLE ChargerBitmap(char *FileName,POINT *lppt)
+{
+ HFILE hFile;
+ OFSTRUCT ofstruct;
+ HANDLE result;
+ LPSTR lpDIBHdr;
+ unsigned int size;
+
+ size = Getfilesize(FileName);
+ hFile=OpenFile((LPSTR) FileName, &ofstruct,
+ OF_READ | OF_SHARE_DENY_WRITE);
+ result = ReadDIBFile(hFile,size);
+ if (hFile) _lclose(hFile);
+ if (result) {
+ LPBITMAPINFOHEADER lpbmi;
+ LPBITMAPCOREHEADER lpbmc;
+
+ lpDIBHdr = GlobalLock (result);
+ lpbmi = (LPBITMAPINFOHEADER) lpDIBHdr;
+ lpbmc = (LPBITMAPCOREHEADER) lpDIBHdr;
+
+ if (lpbmi->biSize == sizeof (BITMAPINFOHEADER)) {
+ lppt->y = lpbmi->biHeight;
+ lppt->x = lpbmi->biWidth;
+ }
+ else {
+ lppt->y = lpbmc->bcHeight;
+ lppt->x = lpbmc->bcWidth;
+ }
+ GlobalUnlock(result);
+ }
+ return(result);
+}
+
+void DessinerBitmap(HANDLE hDIB,HDC hDC,LPRECT lpDCRect)
+{
+ DIBPaint (hDC,
+ lpDCRect,
+ hDIB);
+}
+
+void AfficheBitmap(char *filename,HDC hDC,int x,int y)
+{
+ RECT rc;
+ HANDLE hdib;
+ POINT pt;
+ char titi[60];
+
+ hdib = ChargerBitmap(filename,&pt);
+ if (hdib == NULL) {
+ return;
+ }
+ rc.top = y;
+ rc.left = x;
+ rc.right = pt.x+x;
+ rc.bottom = pt.y+y;
+ pt.y += GetSystemMetrics(SM_CYCAPTION);
+ DessinerBitmap(hdib,hDC,&rc);
+ GlobalFree(hdib);
+}
diff --git a/otherlibs/win32graph/draw.c b/otherlibs/win32graph/draw.c
new file mode 100644
index 0000000000..14a93bb9c4
--- /dev/null
+++ b/otherlibs/win32graph/draw.c
@@ -0,0 +1,653 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Developed by Jacob Navia, based on code by J-M Geffroy and X Leroy */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <math.h>
+#include "caml/mlvalues.h"
+#include "caml/alloc.h"
+#include "caml/fail.h"
+#include "libgraph.h"
+#include "caml/custom.h"
+#include "caml/memory.h"
+
+HDC gcMetaFile;
+int grdisplay_mode;
+int grremember_mode;
+GR_WINDOW grwindow;
+
+static void GetCurrentPosition(HDC hDC,POINT *pt)
+{
+ MoveToEx(hDC,0,0,pt);
+ MoveToEx(hDC,pt->x,pt->y,0);
+}
+
+static value gr_draw_or_fill_arc(value vx, value vy, value vrx, value vry,
+ value vstart, value vend, BOOL fill);
+
+CAMLprim value caml_gr_plot(value vx, value vy)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ gr_check_open();
+ if(grremember_mode)
+ SetPixel(grwindow.gcBitmap, x, Wcvt(y),grwindow.CurrentColor);
+ if(grdisplay_mode) {
+ SetPixel(grwindow.gc, x, Wcvt(y),grwindow.CurrentColor);
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_moveto(value vx, value vy)
+{
+ grwindow.grx = Int_val(vx);
+ grwindow.gry = Int_val(vy);
+ if(grremember_mode)
+ MoveToEx(grwindow.gcBitmap,grwindow.grx,Wcvt(grwindow.gry),0);
+ if (grdisplay_mode)
+ MoveToEx(grwindow.gc,grwindow.grx,Wcvt(grwindow.gry),0);
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_current_x(value unit)
+{
+ return Val_int(grwindow.grx);
+}
+
+CAMLprim value caml_gr_current_y(value unit)
+{
+ return Val_int(grwindow.gry);
+}
+
+CAMLprim value caml_gr_lineto(value vx, value vy)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ gr_check_open();
+ SelectObject(grwindow.gc,grwindow.CurrentPen);
+ SelectObject(grwindow.gcBitmap,grwindow.CurrentPen);
+ if (grremember_mode)
+ LineTo(grwindow.gcBitmap,x,Wcvt(y));
+ if (grdisplay_mode)
+ LineTo(grwindow.gc, x, Wcvt(y));
+ grwindow.grx = x;
+ grwindow.gry = y;
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_draw_rect(value vx, value vy, value vw, value vh)
+{
+ int x, y, w, h;
+ POINT pt[5];
+ x=Int_val(vx);
+ y=Wcvt(Int_val(vy));
+ w=Int_val(vw);
+ h=Int_val(vh);
+
+ pt[0].x = x; pt[0].y = y - h;
+ pt[1].x = x + w; pt[1].y = y - h;
+ pt[2].x = x + w; pt[2].y = y;
+ pt[3].x = x; pt[3].y = y;
+ pt[4].x = x; pt[4].y = y - h;
+ if (grremember_mode) {
+ Polyline(grwindow.gcBitmap,pt, 5);
+ }
+ if (grdisplay_mode) {
+ Polyline(grwindow.gc,pt, 5);
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_draw_text(value text,value x)
+{
+ POINT pt;
+ int oldmode = SetBkMode(grwindow.gc,TRANSPARENT);
+ SetBkMode(grwindow.gcBitmap,TRANSPARENT);
+ SetTextAlign(grwindow.gcBitmap, TA_UPDATECP|TA_BOTTOM);
+ SetTextAlign(grwindow.gc, TA_UPDATECP|TA_BOTTOM);
+ if (grremember_mode) {
+ TextOut(grwindow.gcBitmap,0,0,(char *)text,x);
+ }
+ if(grdisplay_mode) {
+ TextOut(grwindow.gc,0,0,(char *)text,x);
+ }
+ GetCurrentPosition(grwindow.gc,&pt);
+ grwindow.grx = pt.x;
+ grwindow.gry = grwindow.height - pt.y;
+ SetBkMode(grwindow.gc,oldmode);
+ SetBkMode(grwindow.gcBitmap,oldmode);
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_fill_rect(value vx, value vy, value vw, value vh)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ int w = Int_val(vw);
+ int h = Int_val(vh);
+ RECT rc;
+
+ gr_check_open();
+ rc.left = x;
+ rc.top = Wcvt(y);
+ rc.right = x+w;
+ rc.bottom = Wcvt(y)-h;
+ if (grdisplay_mode)
+ FillRect(grwindow.gc,&rc,grwindow.CurrentBrush);
+ if (grremember_mode)
+ FillRect(grwindow.gcBitmap,&rc,grwindow.CurrentBrush);
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_sound(value freq, value vdur)
+{
+ Beep(freq,vdur);
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_point_color(value vx, value vy)
+{
+ int x = Int_val(vx);
+ int y = Int_val(vy);
+ COLORREF rgb;
+ unsigned long b,g,r;
+
+ gr_check_open();
+ rgb = GetPixel(grwindow.gcBitmap,x,Wcvt(y));
+ b = (unsigned long)((rgb & 0xFF0000) >> 16);
+ g = (unsigned long)((rgb & 0x00FF00) >> 8);
+ r = (unsigned long)(rgb & 0x0000FF);
+ return Val_long((r<<16) + (g<<8) + b);
+}
+
+CAMLprim value caml_gr_circle(value x,value y,value radius)
+{
+ int left,top,right,bottom;
+
+ gr_check_open();
+ left = x - radius/2;
+ top = Wcvt(y) - radius/2;
+ right = left+radius;
+ bottom = top+radius;
+ Ellipse(grwindow.gcBitmap,left,top,right,bottom);
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_set_window_title(value text)
+{
+ SetWindowText(grwindow.hwnd,(char *)text);
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_draw_arc(value *argv, int argc)
+{
+ return gr_draw_or_fill_arc(argv[0], argv[1], argv[2], argv[3],
+ argv[4], argv[5], FALSE);
+}
+
+CAMLprim value caml_gr_draw_arc_nat(vx, vy, vrx, vry, vstart, vend)
+{
+ return gr_draw_or_fill_arc(vx, vy, vrx, vry, vstart, vend, FALSE);
+}
+
+CAMLprim value caml_gr_set_line_width(value vwidth)
+{
+ int width = Int_val(vwidth);
+ HPEN oldPen,newPen;
+
+ gr_check_open();
+ oldPen = grwindow.CurrentPen;
+ newPen = CreatePen(PS_SOLID,width,grwindow.CurrentColor);
+ SelectObject(grwindow.gcBitmap,newPen);
+ SelectObject(grwindow.gc,newPen);
+ DeleteObject(oldPen);
+ grwindow.CurrentPen = newPen;
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_set_color(value vcolor)
+{
+ HBRUSH oldBrush, newBrush;
+ LOGBRUSH lb;
+ LOGPEN pen;
+ HPEN newPen;
+ int color = Long_val(vcolor);
+
+ int r = (color & 0xFF0000) >> 16,
+ g = (color & 0x00FF00) >> 8 ,
+ b = color & 0x0000FF;
+ COLORREF c = RGB(r,g,b);
+ memset(&lb,0,sizeof(lb));
+ memset(&pen,0,sizeof(LOGPEN));
+ gr_check_open();
+ GetObject(grwindow.CurrentPen,sizeof(LOGPEN),&pen);
+ pen.lopnColor = c;
+ newPen = CreatePenIndirect(&pen);
+ SelectObject(grwindow.gcBitmap,newPen);
+ SelectObject(grwindow.gc,newPen);
+ DeleteObject(grwindow.CurrentPen);
+ grwindow.CurrentPen = newPen;
+ SetTextColor(grwindow.gc,c);
+ SetTextColor(grwindow.gcBitmap,c);
+ oldBrush = grwindow.CurrentBrush;
+ lb.lbStyle = BS_SOLID;
+ lb.lbColor = c;
+ newBrush = CreateBrushIndirect(&lb);
+ SelectObject(grwindow.gc,newBrush);
+ SelectObject(grwindow.gcBitmap,newBrush);
+ DeleteObject(oldBrush);
+ grwindow.CurrentBrush = newBrush;
+ grwindow.CurrentColor = c;
+ return Val_unit;
+}
+
+
+static value gr_draw_or_fill_arc(value vx, value vy, value vrx, value vry,
+ value vstart, value vend, BOOL fill)
+{
+ int x, y, r_x, r_y, start, end;
+ int x1, y1, x2, y2, x3, y3, x4, y4;
+ double cvt = 3.141592653/180.0;
+
+ r_x = Int_val(vrx);
+ r_y = Int_val(vry);
+ if ((r_x < 0) || (r_y < 0))
+ invalid_argument("draw_arc: radius must be positive");
+ x = Int_val(vx);
+ y = Int_val(vy);
+ start = Int_val(vstart);
+ end = Int_val(vend);
+
+ // Upper-left corner of bounding rect.
+ x1= x - r_x;
+ y1= y + r_y;
+ // Lower-right corner of bounding rect.
+ x2= x + r_x;
+ y2= y - r_y;
+ // Starting point
+ x3=x + (int)(100.0*cos(cvt*start));
+ y3=y + (int)(100.0*sin(cvt*start));
+ // Ending point
+ x4=x + (int)(100.0*cos(cvt*end));
+ y4=y + (int)(100.0*sin(cvt*end));
+
+ if (grremember_mode) {
+ SelectObject(grwindow.gcBitmap,grwindow.CurrentPen);
+ SelectObject(grwindow.gcBitmap,grwindow.CurrentBrush);
+ if( fill )
+ Pie(grwindow.gcBitmap,x1, Wcvt(y1), x2, Wcvt(y2),
+ x3, Wcvt(y3), x4, Wcvt(y4));
+ else
+ Arc(grwindow.gcBitmap,x1, Wcvt(y1), x2, Wcvt(y2),
+ x3, Wcvt(y3), x4, Wcvt(y4));
+ }
+ if( grdisplay_mode ) {
+ SelectObject(grwindow.gc,grwindow.CurrentPen);
+ SelectObject(grwindow.gc,grwindow.CurrentBrush);
+ if (fill)
+ Pie(grwindow.gc,x1, Wcvt(y1), x2, Wcvt(y2),
+ x3, Wcvt(y3), x4, Wcvt(y4));
+ else
+ Arc(grwindow.gc,x1, Wcvt(y1), x2, Wcvt(y2),
+ x3, Wcvt(y3), x4, Wcvt(y4));
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_show_bitmap(value filename,int x,int y)
+{
+ AfficheBitmap(filename,grwindow.gcBitmap,x,Wcvt(y));
+ AfficheBitmap(filename,grwindow.gc,x,Wcvt(y));
+ return Val_unit;
+}
+
+
+
+CAMLprim value caml_gr_get_mousex(value unit)
+{
+ POINT pt;
+ GetCursorPos(&pt);
+ MapWindowPoints(HWND_DESKTOP,grwindow.hwnd,&pt,1);
+ return pt.x;
+}
+
+CAMLprim value caml_gr_get_mousey(value unit)
+{
+ POINT pt;
+ GetCursorPos(&pt);
+ MapWindowPoints(HWND_DESKTOP,grwindow.hwnd,&pt,1);
+ return grwindow.height - pt.y - 1;
+}
+
+
+static void gr_font(char *fontname)
+{
+ HFONT hf = CreationFont(fontname);
+
+ if (hf && hf != INVALID_HANDLE_VALUE) {
+ HFONT oldFont = SelectObject(grwindow.gc,hf);
+ SelectObject(grwindow.gcBitmap,hf);
+ DeleteObject(grwindow.CurrentFont);
+ grwindow.CurrentFont = hf;
+ }
+}
+
+CAMLprim value caml_gr_set_font(value fontname)
+{
+ gr_check_open();
+ gr_font(String_val(fontname));
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_set_text_size (value sz)
+{
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_draw_char(value chr)
+{
+ char str[1];
+ gr_check_open();
+ str[0] = Int_val(chr);
+ caml_gr_draw_text((value)str, 1);
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_draw_string(value str)
+{
+ gr_check_open();
+ caml_gr_draw_text(str, string_length(str));
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_text_size(value str)
+{
+ SIZE extent;
+ value res;
+
+ mlsize_t len = string_length(str);
+ if (len > 32767) len = 32767;
+
+ GetTextExtentPoint(grwindow.gc,String_val(str), len,&extent);
+
+ res = alloc_tuple(2);
+ Field(res, 0) = Val_long(extent.cx);
+ Field(res, 1) = Val_long(extent.cy);
+
+ return res;
+}
+
+CAMLprim value caml_gr_fill_poly(value vect)
+{
+ int n_points, i;
+ POINT *p,*poly;
+ n_points = Wosize_val(vect);
+ if (n_points < 3)
+ gr_fail("fill_poly: not enough points",0);
+
+ poly = (POINT *)malloc(n_points*sizeof(POINT));
+
+ p = poly;
+ for( i = 0; i < n_points; i++ ){
+ p->x = Int_val(Field(Field(vect,i),0));
+ p->y = Wcvt(Int_val(Field(Field(vect,i),1)));
+ p++;
+ }
+ if (grremember_mode) {
+ SelectObject(grwindow.gcBitmap,grwindow.CurrentBrush);
+ Polygon(grwindow.gcBitmap,poly,n_points);
+ }
+ if (grdisplay_mode) {
+ SelectObject(grwindow.gcBitmap,grwindow.CurrentBrush);
+ Polygon(grwindow.gc,poly,n_points);
+ }
+ free(poly);
+
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_fill_arc(value *argv, int argc)
+{
+ return gr_draw_or_fill_arc(argv[0], argv[1], argv[2], argv[3],
+ argv[4], argv[5], TRUE);
+}
+
+CAMLprim value caml_gr_fill_arc_nat(vx, vy, vrx, vry, vstart, vend)
+{
+ return gr_draw_or_fill_arc(vx, vy, vrx, vry, vstart, vend, TRUE);
+}
+
+// Image primitives
+struct image {
+ int w;
+ int h;
+ HBITMAP data;
+ HBITMAP mask;
+};
+
+#define Width(i) (((struct image *)Data_custom_val(i))->w)
+#define Height(i) (((struct image *)Data_custom_val(i))->h)
+#define Data(i) (((struct image *)Data_custom_val(i))->data)
+#define Mask(i) (((struct image *)Data_custom_val(i))->mask)
+#define Max_image_mem 500000
+
+static void finalize_image (value i)
+{
+ DeleteObject (Data(i));
+ if (Mask(i) != NULL) DeleteObject(Mask(i));
+}
+
+static struct custom_operations image_ops = {
+ "_image",
+ finalize_image,
+ custom_compare_default,
+ custom_hash_default,
+ custom_serialize_default,
+ custom_deserialize_default,
+ custom_compare_ext_default
+};
+
+CAMLprim value caml_gr_create_image(value vw, value vh)
+{
+ HBITMAP cbm;
+ value res;
+ int w = Int_val(vw);
+ int h = Int_val(vh);
+
+ if (w < 0 || h < 0)
+ gr_fail("create_image: width and height must be positive",0);
+
+ cbm = CreateCompatibleBitmap(grwindow.gc, w, h);
+ if (cbm == NULL)
+ gr_fail("create_image: cannot create bitmap", 0);
+ res = alloc_custom(&image_ops, sizeof(struct image),
+ w * h, Max_image_mem);
+ if (res) {
+ Width (res) = w;
+ Height (res) = h;
+ Data (res) = cbm;
+ Mask (res) = NULL;
+ }
+ return res;
+}
+
+CAMLprim value caml_gr_blit_image (value i, value x, value y)
+{
+ HBITMAP oldBmp = SelectObject(grwindow.tempDC,Data(i));
+ int xsrc = Int_val(x);
+ int ysrc = Wcvt(Int_val(y) + Height(i) - 1);
+ BitBlt(grwindow.tempDC,0, 0, Width(i), Height(i),
+ grwindow.gcBitmap, xsrc, ysrc, SRCCOPY);
+ SelectObject(grwindow.tempDC,oldBmp);
+ return Val_unit;
+}
+
+
+CAMLprim value caml_gr_draw_image(value i, value x, value y)
+{
+ HBITMAP oldBmp;
+
+ int xdst = Int_val(x);
+ int ydst = Wcvt(Int_val(y)+Height(i)-1);
+ if (Mask(i) == NULL) {
+ if (grremember_mode) {
+ oldBmp = SelectObject(grwindow.tempDC,Data(i));
+ BitBlt(grwindow.gcBitmap,xdst, ydst, Width(i),
+ Height(i),
+ grwindow.tempDC, 0, 0, SRCCOPY);
+ SelectObject(grwindow.tempDC,oldBmp);
+ }
+ if (grdisplay_mode) {
+ oldBmp = SelectObject(grwindow.tempDC,Data(i));
+ BitBlt(grwindow.gc,xdst, ydst, Width(i), Height(i),
+ grwindow.tempDC, 0, 0, SRCCOPY);
+ SelectObject(grwindow.tempDC,oldBmp);
+ }
+ }
+ else {
+ if (grremember_mode) {
+ oldBmp = SelectObject(grwindow.tempDC,Mask(i));
+ BitBlt(grwindow.gcBitmap,xdst, ydst, Width(i),
+ Height(i),
+ grwindow.tempDC, 0, 0, SRCAND);
+ SelectObject(grwindow.tempDC,Data(i));
+ BitBlt(grwindow.gcBitmap,xdst, ydst, Width(i),
+ Height(i),
+ grwindow.tempDC, 0, 0, SRCPAINT);
+ SelectObject(grwindow.tempDC,oldBmp);
+ }
+ if (grdisplay_mode) {
+ oldBmp = SelectObject(grwindow.tempDC,Mask(i));
+ BitBlt(grwindow.gc,xdst, ydst, Width(i), Height(i),
+ grwindow.tempDC, 0, 0, SRCAND);
+ SelectObject(grwindow.tempDC,Data(i));
+ BitBlt(grwindow.gc,xdst, ydst, Width(i), Height(i),
+ grwindow.tempDC, 0, 0, SRCPAINT);
+ SelectObject(grwindow.tempDC,oldBmp);
+ }
+ }
+
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_make_image(value matrix)
+{
+ int width, height,has_transp,i,j;
+ value img;
+ HBITMAP oldBmp;
+ height = Wosize_val(matrix);
+ if (height == 0) {
+ width = 0;
+ }
+ else {
+ width = Wosize_val(Field(matrix, 0));
+ for (i = 1; i < height; i++) {
+ if (width != (int) Wosize_val(Field(matrix, i)))
+ gr_fail("make_image: non-rectangular matrix",0);
+ }
+ }
+ Begin_roots1(matrix)
+ img = caml_gr_create_image(Val_int(width), Val_int(height));
+ End_roots();
+ has_transp = 0;
+ oldBmp = SelectObject(grwindow.tempDC,Data(img));
+ for (i = 0; i < height; i++) {
+ for (j = 0; j < width; j++) {
+ int col = Long_val (Field (Field (matrix, i), j));
+ if (col == -1){
+ has_transp = 1;
+ SetPixel(grwindow.tempDC,j, i, 0);
+ }
+ else {
+ int red = (col >> 16) & 0xFF;
+ int green = (col >> 8) & 0xFF;
+ int blue = col & 0xFF;
+ SetPixel(grwindow.tempDC,j, i,
+ RGB(red, green, blue));
+ }
+ }
+ }
+ SelectObject(grwindow.tempDC,oldBmp);
+ if (has_transp) {
+ HBITMAP cbm;
+ cbm = CreateCompatibleBitmap(grwindow.gc, width, height);
+ Mask(img) = cbm;
+ oldBmp = SelectObject(grwindow.tempDC,Mask(img));
+ for (i = 0; i < height; i++) {
+ for (j = 0; j < width; j++) {
+ int col = Long_val (Field (Field (matrix,i),j));
+ SetPixel(grwindow.tempDC,j, i,
+ col == -1 ? 0xFFFFFF : 0);
+ }
+ }
+ SelectObject(grwindow.tempDC,oldBmp);
+ }
+ return img;
+}
+
+static value alloc_int_vect(mlsize_t size)
+{
+ value res;
+ mlsize_t i;
+
+ if (size == 0) return Atom(0);
+ if (size <= Max_young_wosize) {
+ res = alloc(size, 0);
+ }
+ else {
+ res = alloc_shr(size, 0);
+ }
+ for (i = 0; i < size; i++) {
+ Field(res, i) = Val_long(0);
+ }
+ return res;
+}
+
+CAMLprim value caml_gr_dump_image (value img)
+{
+ int height = Height(img);
+ int width = Width(img);
+ value matrix = Val_unit;
+ int i, j;
+ HBITMAP oldBmp;
+
+ Begin_roots2(img, matrix)
+ matrix = alloc_int_vect (height);
+ for (i = 0; i < height; i++) {
+ modify (&Field (matrix, i), alloc_int_vect (width));
+ }
+ End_roots();
+
+ oldBmp = SelectObject(grwindow.tempDC,Data(img));
+ for (i = 0; i < height; i++) {
+ for (j = 0; j < width; j++) {
+ int col = GetPixel(grwindow.tempDC,j, i);
+ int blue = (col >> 16) & 0xFF;
+ int green = (col >> 8) & 0xFF;
+ int red = col & 0xFF;
+ Field(Field(matrix, i), j) = Val_long((red << 16) +
+ (green << 8) + blue);
+ }
+ }
+ SelectObject(grwindow.tempDC,oldBmp);
+ if (Mask(img) != NULL) {
+ oldBmp = SelectObject(grwindow.tempDC,Mask(img));
+ for (i = 0; i < height; i++) {
+ for (j = 0; j < width; j++) {
+ if (GetPixel(grwindow.tempDC,j, i) != 0)
+ Field(Field(matrix, i), j) =
+ Val_long(-1);
+ }
+ }
+ SelectObject(grwindow.tempDC,oldBmp);
+ }
+ return matrix;
+}
diff --git a/otherlibs/win32graph/events.c b/otherlibs/win32graph/events.c
new file mode 100755
index 0000000000..837e53ac14
--- /dev/null
+++ b/otherlibs/win32graph/events.c
@@ -0,0 +1,198 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2004 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "caml/mlvalues.h"
+#include "caml/alloc.h"
+#include "libgraph.h"
+#include <windows.h>
+
+enum {
+ EVENT_BUTTON_DOWN = 1,
+ EVENT_BUTTON_UP = 2,
+ EVENT_KEY_PRESSED = 4,
+ EVENT_MOUSE_MOTION = 8
+};
+
+struct event_data {
+ short mouse_x, mouse_y;
+ unsigned char kind;
+ unsigned char button;
+ unsigned char key;
+};
+
+static struct event_data caml_gr_queue[SIZE_QUEUE];
+static unsigned int caml_gr_head = 0; /* position of next read */
+static unsigned int caml_gr_tail = 0; /* position of next write */
+
+static int caml_gr_event_mask = EVENT_KEY_PRESSED;
+static int last_button = 0;
+static LPARAM last_pos = 0;
+
+HANDLE caml_gr_queue_semaphore = NULL;
+CRITICAL_SECTION caml_gr_queue_mutex;
+
+void caml_gr_init_event_queue(void)
+{
+ if (caml_gr_queue_semaphore == NULL) {
+ caml_gr_queue_semaphore = CreateSemaphore(NULL, 0, SIZE_QUEUE, NULL);
+ InitializeCriticalSection(&caml_gr_queue_mutex);
+ }
+}
+
+#define QueueIsEmpty (caml_gr_tail == caml_gr_head)
+
+static void caml_gr_enqueue_event(int kind, LPARAM mouse_xy,
+ int button, int key)
+{
+ struct event_data * ev;
+
+ if ((caml_gr_event_mask & kind) == 0) return;
+ EnterCriticalSection(&caml_gr_queue_mutex);
+ ev = &(caml_gr_queue[caml_gr_tail]);
+ ev->kind = kind;
+ ev->mouse_x = GET_X_LPARAM(mouse_xy);
+ ev->mouse_y = GET_Y_LPARAM(mouse_xy);
+ ev->button = (button != 0);
+ ev->key = key;
+ caml_gr_tail = (caml_gr_tail + 1) % SIZE_QUEUE;
+ /* If queue was full, it now appears empty;
+ drop oldest entry from queue. */
+ if (QueueIsEmpty) {
+ caml_gr_head = (caml_gr_head + 1) % SIZE_QUEUE;
+ } else {
+ /* One more event in queue */
+ ReleaseSemaphore(caml_gr_queue_semaphore, 1, NULL);
+ }
+ LeaveCriticalSection(&caml_gr_queue_mutex);
+}
+
+void caml_gr_handle_event(UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch (msg) {
+ case WM_LBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ last_button = 1;
+ last_pos = lParam;
+ caml_gr_enqueue_event(EVENT_BUTTON_DOWN, lParam, 1, 0);
+ break;
+
+ case WM_LBUTTONUP:
+ case WM_RBUTTONUP:
+ case WM_MBUTTONUP:
+ last_button = 0;
+ last_pos = lParam;
+ caml_gr_enqueue_event(EVENT_BUTTON_UP, lParam, 0, 0);
+ break;
+
+ case WM_CHAR:
+ caml_gr_enqueue_event(EVENT_KEY_PRESSED, last_pos, last_button, wParam);
+ break;
+
+ case WM_MOUSEMOVE:
+ last_pos = lParam;
+ caml_gr_enqueue_event(EVENT_MOUSE_MOTION, lParam, last_button, 0);
+ break;
+ }
+}
+
+static value caml_gr_wait_allocate_result(int mouse_x, int mouse_y,
+ int button,
+ int keypressed, int key)
+{
+ value res = alloc_small(5, 0);
+ Field(res, 0) = Val_int(mouse_x);
+ Field(res, 1) = Val_int(grwindow.height - 1 - mouse_y);
+ Field(res, 2) = Val_bool(button);
+ Field(res, 3) = Val_bool(keypressed);
+ Field(res, 4) = Val_int(key & 0xFF);
+ return res;
+}
+
+static value caml_gr_wait_event_poll(void)
+{
+ int key, keypressed, i;
+
+ /* Look inside event queue for pending KeyPress events */
+ EnterCriticalSection(&caml_gr_queue_mutex);
+ key = 0;
+ keypressed = 0;
+ for (i = caml_gr_head; i != caml_gr_tail; i = (i + 1) % SIZE_QUEUE) {
+ if (caml_gr_queue[i].kind == EVENT_KEY_PRESSED) {
+ keypressed = 1;
+ key = caml_gr_queue[i].key;
+ break;
+ }
+ }
+ LeaveCriticalSection(&caml_gr_queue_mutex);
+ /* Use global vars for mouse position and buttons */
+ return caml_gr_wait_allocate_result(GET_X_LPARAM(last_pos),
+ GET_Y_LPARAM(last_pos),
+ last_button,
+ keypressed, key);
+}
+
+static value caml_gr_wait_event_blocking(int mask)
+{
+ struct event_data ev;
+
+ /* Increase the selected events if needed */
+ caml_gr_event_mask |= mask;
+ /* Pop events from queue until one matches */
+ do {
+ /* Wait for event queue to be non-empty */
+ WaitForSingleObject(caml_gr_queue_semaphore, INFINITE);
+ /* Pop oldest event in queue */
+ EnterCriticalSection(&caml_gr_queue_mutex);
+ ev = caml_gr_queue[caml_gr_head];
+ /* Queue should never be empty at this point, but just in case... */
+ if (QueueIsEmpty) {
+ ev.kind = 0;
+ } else {
+ caml_gr_head = (caml_gr_head + 1) % SIZE_QUEUE;
+ }
+ LeaveCriticalSection(&caml_gr_queue_mutex);
+ /* Check if it matches */
+ } while ((ev.kind & mask) == 0);
+ return caml_gr_wait_allocate_result(ev.mouse_x, ev.mouse_y, ev.button,
+ ev.kind == EVENT_KEY_PRESSED,
+ ev.key);
+}
+
+CAMLprim value caml_gr_wait_event(value eventlist) /* ML */
+{
+ int mask, poll;
+
+ gr_check_open();
+ mask = 0;
+ poll = 0;
+ while (eventlist != Val_int(0)) {
+ switch (Int_val(Field(eventlist, 0))) {
+ case 0: /* Button_down */
+ mask |= EVENT_BUTTON_DOWN; break;
+ case 1: /* Button_up */
+ mask |= EVENT_BUTTON_UP; break;
+ case 2: /* Key_pressed */
+ mask |= EVENT_KEY_PRESSED; break;
+ case 3: /* Mouse_motion */
+ mask |= EVENT_MOUSE_MOTION; break;
+ case 4: /* Poll */
+ poll = 1; break;
+ }
+ eventlist = Field(eventlist, 1);
+ }
+ if (poll)
+ return caml_gr_wait_event_poll();
+ else
+ return caml_gr_wait_event_blocking(mask);
+}
diff --git a/otherlibs/win32graph/libgraph.h b/otherlibs/win32graph/libgraph.h
new file mode 100644
index 0000000000..99ede99527
--- /dev/null
+++ b/otherlibs/win32graph/libgraph.h
@@ -0,0 +1,76 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Jacob Navia, after Xavier Leroy */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <windows.h>
+#include <windowsx.h>
+
+struct canvas {
+ int w, h; /* Dimensions of the drawable */
+ HWND win; /* The drawable itself */
+ HDC gc; /* The associated graphics context */
+};
+
+extern HWND grdisplay; /* The display connection */
+extern COLORREF grbackground;
+extern BOOL grdisplay_mode; /* Display-mode flag */
+extern BOOL grremember_mode; /* Remember-mode flag */
+extern int grx, gry; /* Coordinates of the current point */
+extern int grcolor; /* Current *CAML* drawing color (can be -1) */
+extern HFONT * grfont; /* Current font */
+
+extern BOOL direct_rgb;
+extern int byte_order;
+extern int bitmap_unit;
+extern int bits_per_pixel;
+
+#define Wcvt(y) (grwindow.height - 1 - (y))
+#define Bcvt(y) (grwindow.height - 1 - (y))
+#define WtoB(y) ((y) + WindowRect.bottom - grwindow.h)
+
+#define DEFAULT_SCREEN_WIDTH 1024
+#define DEFAULT_SCREEN_HEIGHT 768
+#define BORDER_WIDTH 2
+#define WINDOW_NAME "OCaml graphics"
+#define ICON_NAME "OCaml graphics"
+#define SIZE_QUEUE 256
+
+void gr_fail(char *fmt, char *arg);
+void gr_check_open(void);
+CAMLprim value caml_gr_set_color(value vcolor);
+
+// Windows specific definitions
+extern RECT WindowRect;
+extern int grCurrentColor;
+
+typedef struct tagWindow {
+ HDC gc;
+ HDC gcBitmap;
+ HWND hwnd;
+ HBRUSH CurrentBrush;
+ HPEN CurrentPen;
+ DWORD CurrentColor;
+ int width;
+ int height;
+ int grx;
+ int gry;
+ HBITMAP hBitmap;
+ HFONT CurrentFont;
+ int CurrentFontSize;
+ HDC tempDC; // For image operations;
+} GR_WINDOW;
+
+extern GR_WINDOW grwindow;
+HFONT CreationFont(char *name);
+extern void caml_gr_init_event_queue(void);
+extern void caml_gr_handle_event(UINT msg, WPARAM wParam, LPARAM lParam);
diff --git a/otherlibs/win32graph/libgraphics.clib b/otherlibs/win32graph/libgraphics.clib
new file mode 100644
index 0000000000..5084c973c5
--- /dev/null
+++ b/otherlibs/win32graph/libgraphics.clib
@@ -0,0 +1 @@
+open.o draw.o events.o dib.o
diff --git a/otherlibs/win32graph/open.c b/otherlibs/win32graph/open.c
new file mode 100644
index 0000000000..8d17298bd7
--- /dev/null
+++ b/otherlibs/win32graph/open.c
@@ -0,0 +1,371 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Developed by Jacob Navia, based on code by J-M Geffroy and X Leroy */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <fcntl.h>
+#include <signal.h>
+#include "caml/mlvalues.h"
+#include "caml/fail.h"
+#include "libgraph.h"
+#include "caml/callback.h"
+#include <windows.h>
+
+static value gr_reset(void);
+static long tid;
+static HANDLE threadHandle;
+HWND grdisplay = NULL;
+int grscreen;
+COLORREF grwhite, grblack;
+COLORREF grbackground;
+int grCurrentColor;
+struct canvas grbstore;
+BOOL grdisplay_mode;
+BOOL grremember_mode;
+int grx, gry;
+int grcolor;
+extern HFONT * grfont;
+MSG msg;
+
+static char *szOcamlWindowClass = "OcamlWindowClass";
+static BOOL gr_initialized = 0;
+CAMLprim value caml_gr_clear_graph(value unit);
+HANDLE hInst;
+
+HFONT CreationFont(char *name)
+{
+ LOGFONT CurrentFont;
+ memset(&CurrentFont, 0, sizeof(LOGFONT));
+ CurrentFont.lfCharSet = ANSI_CHARSET;
+ CurrentFont.lfWeight = FW_NORMAL;
+ CurrentFont.lfHeight = grwindow.CurrentFontSize;
+ CurrentFont.lfPitchAndFamily = (BYTE) (FIXED_PITCH | FF_MODERN);
+ strncpy(CurrentFont.lfFaceName, name, sizeof(CurrentFont.lfFaceName));
+ CurrentFont.lfFaceName[sizeof(CurrentFont.lfFaceName) - 1] = 0;
+ return (CreateFontIndirect(&CurrentFont));
+}
+
+void SetCoordinates(HWND hwnd)
+{
+ RECT rc;
+
+ GetClientRect(hwnd,&rc);
+ grwindow.width = rc.right;
+ grwindow.height = rc.bottom;
+ gr_reset();
+}
+
+void ResetForClose(HWND hwnd)
+{
+ DeleteDC(grwindow.tempDC);
+ DeleteDC(grwindow.gcBitmap);
+ DeleteObject(grwindow.hBitmap);
+ memset(&grwindow,0,sizeof(grwindow));
+ gr_initialized = 0;
+}
+
+
+
+static LRESULT CALLBACK GraphicsWndProc(HWND hwnd,UINT msg,WPARAM wParam,
+ LPARAM lParam)
+{
+ PAINTSTRUCT ps;
+ HDC hdc;
+
+ switch (msg) {
+ // Create the MDI client invisible window
+ case WM_CREATE:
+ break;
+ case WM_PAINT:
+ hdc = BeginPaint(hwnd,&ps);
+ BitBlt(hdc,0,0,grwindow.width,grwindow.height,
+ grwindow.gcBitmap,0,0,SRCCOPY);
+ EndPaint(hwnd,&ps);
+ break;
+ // Move the child windows
+ case WM_SIZE:
+ // Position the MDI client window between the tool and
+ // status bars
+ if (wParam != SIZE_MINIMIZED) {
+ SetCoordinates(hwnd);
+ }
+
+ return 0;
+ // End application
+ case WM_DESTROY:
+ ResetForClose(hwnd);
+ gr_check_open();
+ break;
+ }
+ caml_gr_handle_event(msg, wParam, lParam);
+ return DefWindowProc(hwnd, msg, wParam, lParam);
+}
+
+int DoRegisterClass(void)
+{
+ WNDCLASS wc;
+
+ memset(&wc,0,sizeof(WNDCLASS));
+ wc.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC ;
+ wc.lpfnWndProc = (WNDPROC)GraphicsWndProc;
+ wc.hInstance = hInst;
+ wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
+ wc.lpszClassName = szOcamlWindowClass;
+ wc.lpszMenuName = 0;
+ wc.hCursor = LoadCursor(NULL,IDC_ARROW);
+ wc.hIcon = 0;
+ return RegisterClass(&wc);
+}
+
+static value gr_reset(void)
+{
+ RECT rc;
+ int screenx,screeny;
+
+ screenx = GetSystemMetrics(SM_CXSCREEN);
+ screeny = GetSystemMetrics(SM_CYSCREEN);
+ GetClientRect(grwindow.hwnd,&rc);
+ grwindow.gc = GetDC(grwindow.hwnd);
+ grwindow.width = rc.right;
+ grwindow.height = rc.bottom;
+ if (grwindow.gcBitmap == (HDC)0) {
+ grwindow.hBitmap = CreateCompatibleBitmap(grwindow.gc,screenx,
+ screeny);
+ grwindow.gcBitmap = CreateCompatibleDC(grwindow.gc);
+ grwindow.tempDC = CreateCompatibleDC(grwindow.gc);
+ SelectObject(grwindow.gcBitmap,grwindow.hBitmap);
+ SetMapMode(grwindow.gcBitmap,MM_TEXT);
+ MoveToEx(grwindow.gcBitmap,0,grwindow.height-1,0);
+ BitBlt(grwindow.gcBitmap,0,0,screenx,screeny,
+ grwindow.gcBitmap,0,0,WHITENESS);
+ grwindow.CurrentFontSize = 15;
+ grwindow.CurrentFont = CreationFont("Courier");
+ }
+ grwindow.CurrentColor = GetSysColor(COLOR_WINDOWTEXT);
+ grwindow.grx = 0;
+ grwindow.gry = 0;
+ grwindow.CurrentPen = SelectObject(grwindow.gc,
+ GetStockObject(WHITE_PEN));
+ SelectObject(grwindow.gc,grwindow.CurrentPen);
+ SelectObject(grwindow.gcBitmap,grwindow.CurrentPen);
+ grwindow.CurrentBrush = SelectObject(grwindow.gc,
+ GetStockObject(WHITE_BRUSH));
+ SelectObject(grwindow.gc,grwindow.CurrentBrush);
+ SelectObject(grwindow.gcBitmap,grwindow.CurrentBrush);
+ caml_gr_set_color(Val_long(0));
+ SelectObject(grwindow.gc,grwindow.CurrentFont);
+ SelectObject(grwindow.gcBitmap,grwindow.CurrentFont);
+ grdisplay_mode = grremember_mode = 1;
+ MoveToEx(grwindow.gc,0,grwindow.height-1,0);
+ MoveToEx(grwindow.gcBitmap,0,grwindow.height-1,0);
+ SetTextAlign(grwindow.gcBitmap,TA_BOTTOM);
+ SetTextAlign(grwindow.gc,TA_BOTTOM);
+ return Val_unit;
+}
+
+void SuspendGraphicThread(void)
+{
+ SuspendThread(threadHandle);
+}
+
+void ResumeGraphicThread(void)
+{
+ ResumeThread(threadHandle);
+}
+
+/* For handshake between the event handling thread and the main thread */
+static char * open_graph_errmsg;
+static HANDLE open_graph_event;
+
+static DWORD WINAPI gr_open_graph_internal(value arg)
+{
+ RECT rc;
+ int ret;
+ int event;
+ int x, y, w, h;
+ int screenx,screeny;
+ int attributes;
+ static int registered;
+ MSG msg;
+
+ gr_initialized = TRUE;
+ hInst = GetModuleHandle(NULL);
+ x = y = w = h = CW_USEDEFAULT;
+ sscanf(String_val(arg), "%dx%d+%d+%d", &w, &h, &x, &y);
+
+ /* Open the display */
+ if (grwindow.hwnd == NULL || !IsWindow(grwindow.hwnd)) {
+ if (!registered) {
+ registered = DoRegisterClass();
+ if (!registered) {
+ open_graph_errmsg = "Cannot register the window class";
+ SetEvent(open_graph_event);
+ return 1;
+ }
+ }
+ grwindow.hwnd = CreateWindow(szOcamlWindowClass,
+ WINDOW_NAME,
+ WS_OVERLAPPEDWINDOW,
+ x,y,
+ w,h,
+ NULL,0,hInst,NULL);
+ if (grwindow.hwnd == NULL) {
+ open_graph_errmsg = "Cannot create window";
+ SetEvent(open_graph_event);
+ return 1;
+ }
+#if 0
+ if (x != CW_USEDEFAULT) {
+ rc.left = 0;
+ rc.top = 0;
+ rc.right = w;
+ rc.bottom = h;
+ AdjustWindowRect(&rc,GetWindowLong(grwindow.hwnd,GWL_STYLE),0);
+ MoveWindow(grwindow.hwnd,x,y,rc.right-rc.left,rc.bottom-rc.top,1);
+ }
+#endif
+ }
+ gr_reset();
+ ShowWindow(grwindow.hwnd,SW_SHOWNORMAL);
+
+ /* Position the current point at origin */
+ grwindow.grx = 0;
+ grwindow.gry = 0;
+
+ caml_gr_init_event_queue();
+
+ /* The global data structures are now correctly initialized.
+ Restart the OCaml main thread. */
+ open_graph_errmsg = NULL;
+ SetEvent(open_graph_event);
+
+ /* Enter the message handling loop */
+ while (GetMessage(&msg,NULL,0,0)) {
+ TranslateMessage(&msg); // Translates virtual key codes
+ DispatchMessage(&msg); // Dispatches message to window
+ if (!IsWindow(grwindow.hwnd))
+ break;
+ }
+ return 0;
+}
+
+CAMLprim value caml_gr_open_graph(value arg)
+{
+ long tid;
+ if (gr_initialized) return Val_unit;
+ open_graph_event = CreateEvent(NULL, FALSE, FALSE, NULL);
+ threadHandle =
+ CreateThread(NULL,0,
+ (LPTHREAD_START_ROUTINE)gr_open_graph_internal,(void **)arg,
+ 0,
+ &tid);
+ WaitForSingleObject(open_graph_event, INFINITE);
+ CloseHandle(open_graph_event);
+ if (open_graph_errmsg != NULL) gr_fail("%s", open_graph_errmsg);
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_close_graph(value unit)
+{
+ if (gr_initialized) {
+ PostMessage(grwindow.hwnd, WM_CLOSE, 0, 0);
+ WaitForSingleObject(threadHandle, INFINITE);
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_clear_graph(value unit)
+{
+ gr_check_open();
+ if(grremember_mode) {
+ BitBlt(grwindow.gcBitmap,0,0,grwindow.width,grwindow.height,
+ grwindow.gcBitmap,0,0,WHITENESS);
+ }
+ if(grdisplay_mode) {
+ BitBlt(grwindow.gc,0,0,grwindow.width,grwindow.height,
+ grwindow.gc,0,0,WHITENESS);
+ }
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_size_x(value unit)
+{
+ gr_check_open();
+ return Val_int(grwindow.width);
+}
+
+CAMLprim value caml_gr_size_y(value unit)
+{
+ gr_check_open();
+ return Val_int(grwindow.height);
+}
+
+CAMLprim value caml_gr_resize_window (value vx, value vy)
+{
+ gr_check_open ();
+
+ /* FIXME TODO implement this function... */
+
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_synchronize(value unit)
+{
+ gr_check_open();
+ BitBlt(grwindow.gc,0,0,grwindow.width,grwindow.height,
+ grwindow.gcBitmap,0,0,SRCCOPY);
+ return Val_unit ;
+}
+
+CAMLprim value caml_gr_display_mode(value flag)
+{
+ grdisplay_mode = (Int_val(flag)) ? 1 : 0;
+ return Val_unit ;
+}
+
+CAMLprim value caml_gr_remember_mode(value flag)
+{
+ grremember_mode = (Int_val(flag)) ? 1 : 0;
+ return Val_unit ;
+}
+
+CAMLprim value caml_gr_sigio_signal(value unit)
+{
+ return Val_unit;
+}
+
+CAMLprim value caml_gr_sigio_handler(value unit)
+{
+ return Val_unit;
+}
+
+
+/* Processing of graphic errors */
+
+static value * graphic_failure_exn = NULL;
+void gr_fail(char *fmt, char *arg)
+{
+ char buffer[1024];
+
+ if (graphic_failure_exn == NULL) {
+ graphic_failure_exn = caml_named_value("Graphics.Graphic_failure");
+ if (graphic_failure_exn == NULL)
+ invalid_argument("Exception Graphics.Graphic_failure not initialized, "
+ "must link graphics.cma");
+ }
+ sprintf(buffer, fmt, arg);
+ raise_with_string(*graphic_failure_exn, buffer);
+}
+
+void gr_check_open(void)
+{
+ if (!gr_initialized) gr_fail("graphic screen not opened", NULL);
+}
diff --git a/otherlibs/win32unix/.depend b/otherlibs/win32unix/.depend
new file mode 100644
index 0000000000..a608240cdf
--- /dev/null
+++ b/otherlibs/win32unix/.depend
@@ -0,0 +1,5 @@
+unix.cmo: unix.cmi
+unix.cmx: unix.cmi
+unixLabels.cmo: unix.cmi unixLabels.cmi
+unixLabels.cmx: unix.cmx unixLabels.cmi
+unixLabels.cmi: unix.cmi
diff --git a/otherlibs/win32unix/.ignore b/otherlibs/win32unix/.ignore
new file mode 100644
index 0000000000..1eac7a1fe3
--- /dev/null
+++ b/otherlibs/win32unix/.ignore
@@ -0,0 +1,29 @@
+unixLabels.ml*
+unix.mli
+unix.lib
+access.c
+addrofstr.c
+chdir.c
+chmod.c
+cst2constr.c
+cstringv.c
+envir.c
+execv.c
+execve.c
+execvp.c
+exit.c
+getaddrinfo.c
+getcwd.c
+gethost.c
+gethostname.c
+getnameinfo.c
+getproto.c
+getserv.c
+gmtime.c
+putenv.c
+rmdir.c
+socketaddr.c
+strofaddr.c
+time.c
+unlink.c
+utimes.c
diff --git a/otherlibs/win32unix/Makefile b/otherlibs/win32unix/Makefile
new file mode 100644
index 0000000000..72248e53af
--- /dev/null
+++ b/otherlibs/win32unix/Makefile
@@ -0,0 +1,60 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Files in this directory
+WIN_FILES = accept.c bind.c channels.c close.c \
+ close_on.c connect.c createprocess.c dup.c dup2.c errmsg.c \
+ getpeername.c getpid.c getsockname.c gettimeofday.c \
+ link.c listen.c lockf.c lseek.c nonblock.c \
+ mkdir.c open.c pipe.c read.c rename.c \
+ select.c sendrecv.c \
+ shutdown.c sleep.c socket.c sockopt.c startup.c stat.c \
+ system.c times.c unixsupport.c windir.c winwait.c write.c \
+ winlist.c winworker.c windbug.c
+
+# Files from the ../unix directory
+UNIX_FILES = access.c addrofstr.c chdir.c chmod.c cst2constr.c \
+ cstringv.c envir.c execv.c execve.c execvp.c \
+ exit.c getaddrinfo.c getcwd.c gethost.c gethostname.c \
+ getnameinfo.c getproto.c \
+ getserv.c gmtime.c putenv.c rmdir.c \
+ socketaddr.c strofaddr.c time.c unlink.c utimes.c
+
+UNIX_CAML_FILES = unix.mli unixLabels.mli unixLabels.ml
+
+ALL_FILES=$(WIN_FILES) $(UNIX_FILES)
+WSOCKLIB=$(call SYSLIB,ws2_32)
+
+LIBNAME=unix
+COBJS=$(ALL_FILES:.c=.$(O))
+CAMLOBJS=unix.cmo unixLabels.cmo
+LINKOPTS=-cclib $(WSOCKLIB)
+LDOPTS=-ldopt $(WSOCKLIB)
+EXTRACAMLFLAGS=-nolabels
+EXTRACFLAGS=-I../unix
+HEADERS=unixsupport.h socketaddr.h
+
+
+include ../Makefile
+
+clean::
+ rm -f $(UNIX_FILES) $(UNIX_CAML_FILES)
+
+$(UNIX_FILES) $(UNIX_CAML_FILES): %: ../unix/%
+ cp ../unix/$* $*
+
+depend:
+
+$(COBJS): unixsupport.h
+
+include .depend
diff --git a/otherlibs/win32unix/Makefile.nt b/otherlibs/win32unix/Makefile.nt
new file mode 100644
index 0000000000..77555b2c70
--- /dev/null
+++ b/otherlibs/win32unix/Makefile.nt
@@ -0,0 +1,60 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../../LICENSE. #
+# #
+#########################################################################
+
+# Files in this directory
+WIN_FILES = accept.c bind.c channels.c close.c \
+ close_on.c connect.c createprocess.c dup.c dup2.c errmsg.c \
+ getpeername.c getpid.c getsockname.c gettimeofday.c \
+ link.c listen.c lockf.c lseek.c nonblock.c \
+ mkdir.c open.c pipe.c read.c rename.c \
+ select.c sendrecv.c \
+ shutdown.c sleep.c socket.c sockopt.c startup.c stat.c \
+ system.c times.c unixsupport.c windir.c winwait.c write.c \
+ winlist.c winworker.c windbug.c
+
+# Files from the ../unix directory
+UNIX_FILES = access.c addrofstr.c chdir.c chmod.c cst2constr.c \
+ cstringv.c envir.c execv.c execve.c execvp.c \
+ exit.c getaddrinfo.c getcwd.c gethost.c gethostname.c \
+ getnameinfo.c getproto.c \
+ getserv.c gmtime.c putenv.c rmdir.c \
+ socketaddr.c strofaddr.c time.c unlink.c utimes.c
+
+UNIX_CAML_FILES = unix.mli unixLabels.mli unixLabels.ml
+
+ALL_FILES=$(WIN_FILES) $(UNIX_FILES)
+WSOCKLIB=$(call SYSLIB,ws2_32)
+
+LIBNAME=unix
+COBJS=$(ALL_FILES:.c=.$(O))
+CAMLOBJS=unix.cmo unixLabels.cmo
+LINKOPTS=-cclib $(WSOCKLIB)
+LDOPTS=-ldopt $(WSOCKLIB)
+EXTRACAMLFLAGS=-nolabels
+EXTRACFLAGS=-I../unix
+HEADERS=unixsupport.h socketaddr.h
+
+
+include ../Makefile.nt
+
+clean::
+ rm -f $(UNIX_FILES) $(UNIX_CAML_FILES)
+
+$(UNIX_FILES) $(UNIX_CAML_FILES): %: ../unix/%
+ cp ../unix/$* $*
+
+depend:
+
+$(COBJS): unixsupport.h
+
+include .depend
diff --git a/otherlibs/win32unix/accept.c b/otherlibs/win32unix/accept.c
new file mode 100644
index 0000000000..f705f0f090
--- /dev/null
+++ b/otherlibs/win32unix/accept.c
@@ -0,0 +1,64 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include <mswsock.h> // for SO_OPENTYPE and SO_SYNCHRONOUS_NONALERT
+#include "socketaddr.h"
+
+CAMLprim value unix_accept(sock)
+ value sock;
+{
+ SOCKET sconn = Socket_val(sock);
+ SOCKET snew;
+ value fd = Val_unit, adr = Val_unit, res;
+ int oldvalue, oldvaluelen, newvalue, retcode;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+ DWORD err = 0;
+
+ oldvaluelen = sizeof(oldvalue);
+ retcode = getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &oldvalue, &oldvaluelen);
+ if (retcode == 0) {
+ /* Set sockets to synchronous mode */
+ newvalue = SO_SYNCHRONOUS_NONALERT;
+ setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &newvalue, sizeof(newvalue));
+ }
+ addr_len = sizeof(sock_addr);
+ enter_blocking_section();
+ snew = accept(sconn, &addr.s_gen, &addr_len);
+ if (snew == INVALID_SOCKET) err = WSAGetLastError ();
+ leave_blocking_section();
+ if (retcode == 0) {
+ /* Restore initial mode */
+ setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &oldvalue, oldvaluelen);
+ }
+ if (snew == INVALID_SOCKET) {
+ win32_maperr(err);
+ uerror("accept", Nothing);
+ }
+ Begin_roots2 (fd, adr)
+ fd = win_alloc_socket(snew);
+ adr = alloc_sockaddr(&addr, addr_len, snew);
+ res = alloc_small(2, 0);
+ Field(res, 0) = fd;
+ Field(res, 1) = adr;
+ End_roots();
+ return res;
+}
diff --git a/otherlibs/win32unix/bind.c b/otherlibs/win32unix/bind.c
new file mode 100644
index 0000000000..4b1d3def6b
--- /dev/null
+++ b/otherlibs/win32unix/bind.c
@@ -0,0 +1,32 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include "socketaddr.h"
+
+CAMLprim value unix_bind(socket, address)
+ value socket, address;
+{
+ int ret;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ get_sockaddr(address, &addr, &addr_len);
+ ret = bind(Socket_val(socket), &addr.s_gen, addr_len);
+ if (ret == -1) {
+ win32_maperr(WSAGetLastError());
+ uerror("bind", Nothing);
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/channels.c b/otherlibs/win32unix/channels.c
new file mode 100644
index 0000000000..b6350e1742
--- /dev/null
+++ b/otherlibs/win32unix/channels.c
@@ -0,0 +1,90 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/io.h>
+#include <caml/memory.h>
+#include "unixsupport.h"
+#include <fcntl.h>
+
+extern intptr_t _get_osfhandle(int);
+extern int _open_osfhandle(intptr_t, int);
+
+int win_CRT_fd_of_filedescr(value handle)
+{
+ if (CRT_fd_val(handle) != NO_CRT_FD) {
+ return CRT_fd_val(handle);
+ } else {
+ int fd = _open_osfhandle((intptr_t) Handle_val(handle), O_BINARY);
+ if (fd == -1) uerror("channel_of_descr", Nothing);
+ CRT_fd_val(handle) = fd;
+ return fd;
+ }
+}
+
+CAMLprim value win_inchannel_of_filedescr(value handle)
+{
+ CAMLparam1(handle);
+ CAMLlocal1(vchan);
+ struct channel * chan;
+
+ chan = caml_open_descriptor_in(win_CRT_fd_of_filedescr(handle));
+ if (Descr_kind_val(handle) == KIND_SOCKET)
+ chan->flags |= CHANNEL_FLAG_FROM_SOCKET;
+ vchan = caml_alloc_channel(chan);
+ CAMLreturn(vchan);
+}
+
+CAMLprim value win_outchannel_of_filedescr(value handle)
+{
+ CAMLparam1(handle);
+ CAMLlocal1(vchan);
+ int fd;
+ struct channel * chan;
+
+ chan = caml_open_descriptor_out(win_CRT_fd_of_filedescr(handle));
+ if (Descr_kind_val(handle) == KIND_SOCKET)
+ chan->flags |= CHANNEL_FLAG_FROM_SOCKET;
+ vchan = caml_alloc_channel(chan);
+ CAMLreturn(vchan);
+}
+
+CAMLprim value win_filedescr_of_channel(value vchan)
+{
+ CAMLparam1(vchan);
+ CAMLlocal1(fd);
+ struct channel * chan;
+ HANDLE h;
+
+ chan = Channel(vchan);
+ if (chan->fd == -1) uerror("descr_of_channel", Nothing);
+ h = (HANDLE) _get_osfhandle(chan->fd);
+ if (chan->flags & CHANNEL_FLAG_FROM_SOCKET)
+ fd = win_alloc_socket((SOCKET) h);
+ else
+ fd = win_alloc_handle(h);
+ CRT_fd_val(fd) = chan->fd;
+ CAMLreturn(fd);
+}
+
+CAMLprim value win_handle_fd(value vfd)
+{
+ int crt_fd = Int_val(vfd);
+ /* PR#4750: do not use the _or_socket variant as it can cause performance
+ degradation and this function is only used with the standard
+ handles 0, 1, 2, which are not sockets. */
+ value res = win_alloc_handle((HANDLE) _get_osfhandle(crt_fd));
+ CRT_fd_val(res) = crt_fd;
+ return res;
+}
diff --git a/otherlibs/win32unix/close.c b/otherlibs/win32unix/close.c
new file mode 100644
index 0000000000..7f8da29dac
--- /dev/null
+++ b/otherlibs/win32unix/close.c
@@ -0,0 +1,42 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include <caml/io.h>
+
+extern int _close(int);
+
+CAMLprim value unix_close(value fd)
+{
+ if (Descr_kind_val(fd) == KIND_SOCKET) {
+ if (closesocket(Socket_val(fd)) != 0) {
+ win32_maperr(WSAGetLastError());
+ uerror("close", Nothing);
+ }
+ } else {
+ /* If we have an fd then closing it also closes
+ * the underlying handle. Also, closing only
+ * the handle and not the fd leads to fd leaks. */
+ if (CRT_fd_val(fd) != NO_CRT_FD) {
+ if (_close(CRT_fd_val(fd)) != 0)
+ uerror("close", Nothing);
+ } else {
+ if (! CloseHandle(Handle_val(fd))) {
+ win32_maperr(GetLastError());
+ uerror("close", Nothing);
+ }
+ }
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/close_on.c b/otherlibs/win32unix/close_on.c
new file mode 100644
index 0000000000..7a316abcae
--- /dev/null
+++ b/otherlibs/win32unix/close_on.c
@@ -0,0 +1,41 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include <windows.h>
+
+int win_set_inherit(value fd, BOOL inherit)
+{
+ /* According to the MSDN, SetHandleInformation may not work
+ for console handles on WinNT4 and earlier versions. */
+ if (! SetHandleInformation(Handle_val(fd),
+ HANDLE_FLAG_INHERIT,
+ inherit ? HANDLE_FLAG_INHERIT : 0)) {
+ win32_maperr(GetLastError());
+ return -1;
+ }
+ return 0;
+}
+
+CAMLprim value win_set_close_on_exec(value fd)
+{
+ if (win_set_inherit(fd, FALSE) == -1) uerror("set_close_on_exec", Nothing);
+ return Val_unit;
+}
+
+CAMLprim value win_clear_close_on_exec(value fd)
+{
+ if (win_set_inherit(fd, TRUE) == -1) uerror("clear_close_on_exec", Nothing);
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/connect.c b/otherlibs/win32unix/connect.c
new file mode 100644
index 0000000000..37cdbdaa87
--- /dev/null
+++ b/otherlibs/win32unix/connect.c
@@ -0,0 +1,37 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include "socketaddr.h"
+
+CAMLprim value unix_connect(socket, address)
+ value socket, address;
+{
+ SOCKET s = Socket_val(socket);
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+ DWORD err = 0;
+
+ get_sockaddr(address, &addr, &addr_len);
+ enter_blocking_section();
+ if (connect(s, &addr.s_gen, addr_len) == -1)
+ err = WSAGetLastError();
+ leave_blocking_section();
+ if (err) {
+ win32_maperr(err);
+ uerror("connect", Nothing);
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/createprocess.c b/otherlibs/win32unix/createprocess.c
new file mode 100644
index 0000000000..791acbb50d
--- /dev/null
+++ b/otherlibs/win32unix/createprocess.c
@@ -0,0 +1,91 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include <windows.h>
+#include <caml/osdeps.h>
+
+static int win_has_console(void);
+
+value win_create_process_native(value cmd, value cmdline, value env,
+ value fd1, value fd2, value fd3)
+{
+ PROCESS_INFORMATION pi;
+ STARTUPINFO si;
+ char * exefile, * envp;
+ int flags;
+
+ exefile = search_exe_in_path(String_val(cmd));
+ if (env != Val_int(0)) {
+ envp = String_val(Field(env, 0));
+ } else {
+ envp = NULL;
+ }
+ /* Prepare stdin/stdout/stderr redirection */
+ ZeroMemory(&si, sizeof(STARTUPINFO));
+ si.cb = sizeof(STARTUPINFO);
+ si.dwFlags = STARTF_USESTDHANDLES;
+ si.hStdInput = Handle_val(fd1);
+ si.hStdOutput = Handle_val(fd2);
+ si.hStdError = Handle_val(fd3);
+ /* If we do not have a console window, then we must create one
+ before running the process (keep it hidden for apparence).
+ If we are starting a GUI application, the newly created
+ console should not matter. */
+ if (win_has_console())
+ flags = 0;
+ else {
+ flags = CREATE_NEW_CONSOLE;
+ si.dwFlags = (STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES);
+ si.wShowWindow = SW_HIDE;
+ }
+ /* Create the process */
+ if (! CreateProcess(exefile, String_val(cmdline), NULL, NULL,
+ TRUE, flags, envp, NULL, &si, &pi)) {
+ caml_stat_free(exefile);
+ win32_maperr(GetLastError());
+ uerror("create_process", cmd);
+ }
+ caml_stat_free(exefile);
+ CloseHandle(pi.hThread);
+ /* Return the process handle as pseudo-PID
+ (this is consistent with the wait() emulation in the MSVC C library */
+ return Val_long(pi.hProcess);
+}
+
+CAMLprim value win_create_process(value * argv, int argn)
+{
+ return win_create_process_native(argv[0], argv[1], argv[2],
+ argv[3], argv[4], argv[5]);
+}
+
+static int win_has_console(void)
+{
+ HANDLE h, log;
+ int i;
+
+ h = CreateFile("CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (h == INVALID_HANDLE_VALUE) {
+ return 0;
+ } else {
+ CloseHandle(h);
+ return 1;
+ }
+}
+
+CAMLprim value win_terminate_process(value v_pid)
+{
+ return (Val_bool(TerminateProcess((HANDLE) Long_val(v_pid), 0)));
+}
diff --git a/otherlibs/win32unix/dup.c b/otherlibs/win32unix/dup.c
new file mode 100644
index 0000000000..5db19e3073
--- /dev/null
+++ b/otherlibs/win32unix/dup.c
@@ -0,0 +1,31 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_dup(value fd)
+{
+ HANDLE newh;
+ value newfd;
+ int kind = Descr_kind_val(fd);
+ if (! DuplicateHandle(GetCurrentProcess(), Handle_val(fd),
+ GetCurrentProcess(), &newh,
+ 0L, TRUE, DUPLICATE_SAME_ACCESS)) {
+ win32_maperr(GetLastError());
+ return -1;
+ }
+ newfd = win_alloc_handle(newh);
+ Descr_kind_val(newfd) = kind;
+ return newfd;
+}
diff --git a/otherlibs/win32unix/dup2.c b/otherlibs/win32unix/dup2.c
new file mode 100644
index 0000000000..5184207798
--- /dev/null
+++ b/otherlibs/win32unix/dup2.c
@@ -0,0 +1,40 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+extern int _dup2(int, int);
+
+CAMLprim value unix_dup2(value fd1, value fd2)
+{
+ HANDLE oldh, newh;
+
+ oldh = Handle_val(fd2);
+ if (! DuplicateHandle(GetCurrentProcess(), Handle_val(fd1),
+ GetCurrentProcess(), &newh,
+ 0L, TRUE, DUPLICATE_SAME_ACCESS)) {
+ win32_maperr(GetLastError());
+ return -1;
+ }
+ Handle_val(fd2) = newh;
+ if (Descr_kind_val(fd2) == KIND_SOCKET)
+ closesocket((SOCKET) oldh);
+ else
+ CloseHandle(oldh);
+ Descr_kind_val(fd2) = Descr_kind_val(fd1);
+ /* Reflect the dup2 on the CRT fds, if any */
+ if (CRT_fd_val(fd1) != NO_CRT_FD || CRT_fd_val(fd2) != NO_CRT_FD)
+ _dup2(win_CRT_fd_of_filedescr(fd1), win_CRT_fd_of_filedescr(fd2));
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/errmsg.c b/otherlibs/win32unix/errmsg.c
new file mode 100644
index 0000000000..6107abc395
--- /dev/null
+++ b/otherlibs/win32unix/errmsg.c
@@ -0,0 +1,41 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+
+extern int error_table[];
+
+CAMLprim value unix_error_message(value err)
+{
+ int errnum;
+ char buffer[512];
+
+ errnum = Is_block(err) ? Int_val(Field(err, 0)) : error_table[Int_val(err)];
+ if (errnum > 0)
+ return copy_string(strerror(errnum));
+ if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ -errnum,
+ 0,
+ buffer,
+ sizeof(buffer),
+ NULL))
+ return copy_string(buffer);
+ sprintf(buffer, "unknown error #%d", errnum);
+ return copy_string(buffer);
+}
diff --git a/otherlibs/win32unix/getpeername.c b/otherlibs/win32unix/getpeername.c
new file mode 100644
index 0000000000..3467e03fd2
--- /dev/null
+++ b/otherlibs/win32unix/getpeername.c
@@ -0,0 +1,33 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include "socketaddr.h"
+
+CAMLprim value unix_getpeername(sock)
+ value sock;
+{
+ int retcode;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ addr_len = sizeof(sock_addr);
+ retcode = getpeername(Socket_val(sock),
+ &addr.s_gen, &addr_len);
+ if (retcode == -1) {
+ win32_maperr(WSAGetLastError());
+ uerror("getpeername", Nothing);
+ }
+ return alloc_sockaddr(&addr, addr_len, -1);
+}
diff --git a/otherlibs/win32unix/getpid.c b/otherlibs/win32unix/getpid.c
new file mode 100644
index 0000000000..06d95356ee
--- /dev/null
+++ b/otherlibs/win32unix/getpid.c
@@ -0,0 +1,22 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+extern value val_process_id;
+
+CAMLprim value unix_getpid(value unit)
+{
+ return val_process_id;
+}
diff --git a/otherlibs/win32unix/getsockname.c b/otherlibs/win32unix/getsockname.c
new file mode 100644
index 0000000000..21e9d0630d
--- /dev/null
+++ b/otherlibs/win32unix/getsockname.c
@@ -0,0 +1,30 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include "socketaddr.h"
+
+CAMLprim value unix_getsockname(sock)
+ value sock;
+{
+ int retcode;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+
+ addr_len = sizeof(sock_addr);
+ retcode = getsockname(Socket_val(sock),
+ &addr.s_gen, &addr_len);
+ if (retcode == -1) uerror("getsockname", Nothing);
+ return alloc_sockaddr(&addr, addr_len, -1);
+}
diff --git a/otherlibs/win32unix/gettimeofday.c b/otherlibs/win32unix/gettimeofday.c
new file mode 100644
index 0000000000..34f00f3ec2
--- /dev/null
+++ b/otherlibs/win32unix/gettimeofday.c
@@ -0,0 +1,30 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <time.h>
+
+#include "unixsupport.h"
+
+/* Unix epoch as a Windows timestamp in hundreds of ns */
+#define epoch_ft 116444736000000000.0;
+
+CAMLprim value unix_gettimeofday(value unit)
+{
+ FILETIME ft;
+ double tm;
+ GetSystemTimeAsFileTime(&ft);
+ tm = *(uint64_t *)&ft - epoch_ft; /* shift to Epoch-relative time */
+ return copy_double(tm * 1e-7); /* tm is in 100ns */
+}
diff --git a/otherlibs/win32unix/libunix.clib b/otherlibs/win32unix/libunix.clib
new file mode 100644
index 0000000000..043dcf7600
--- /dev/null
+++ b/otherlibs/win32unix/libunix.clib
@@ -0,0 +1,17 @@
+# Files in this directory
+accept.o bind.o channels.o close.o
+close_on.o connect.o createprocess.o dup.o dup2.o errmsg.o
+getpeername.o getpid.o getsockname.o gettimeofday.o
+link.o listen.o lockf.o lseek.o nonblock.o
+mkdir.o open.o pipe.o read.o rename.o
+select.o sendrecv.o
+shutdown.o sleep.o socket.o sockopt.o startup.o stat.o
+system.o unixsupport.o windir.o winwait.o write.o
+winlist.o winworker.o windbug.o
+
+# Files from the ../unix directory
+access.o addrofstr.o chdir.o chmod.o cst2constr.o
+cstringv.o envir.o execv.o execve.o execvp.o
+exit.o getcwd.o gethost.o gethostname.o getproto.o
+getserv.o gmtime.o putenv.o rmdir.o
+socketaddr.o strofaddr.o time.o unlink.o utimes.o
diff --git a/otherlibs/win32unix/link.c b/otherlibs/win32unix/link.c
new file mode 100644
index 0000000000..93d21508a2
--- /dev/null
+++ b/otherlibs/win32unix/link.c
@@ -0,0 +1,40 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* File contributed by Lionel Fourquaux */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+#include <windows.h>
+
+typedef
+BOOL (WINAPI *tCreateHardLink)(
+ LPCTSTR lpFileName,
+ LPCTSTR lpExistingFileName,
+ LPSECURITY_ATTRIBUTES lpSecurityAttributes
+);
+
+CAMLprim value unix_link(value path1, value path2)
+{
+ HMODULE hModKernel32;
+ tCreateHardLink pCreateHardLink;
+ hModKernel32 = GetModuleHandle("KERNEL32.DLL");
+ pCreateHardLink =
+ (tCreateHardLink) GetProcAddress(hModKernel32, "CreateHardLinkA");
+ if (pCreateHardLink == NULL)
+ invalid_argument("Unix.link not implemented");
+ if (! pCreateHardLink(String_val(path2), String_val(path1), NULL)) {
+ win32_maperr(GetLastError());
+ uerror("link", path2);
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/listen.c b/otherlibs/win32unix/listen.c
new file mode 100644
index 0000000000..767db61d79
--- /dev/null
+++ b/otherlibs/win32unix/listen.c
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_listen(sock, backlog)
+ value sock, backlog;
+{
+ if (listen(Socket_val(sock), Int_val(backlog)) == -1) {
+ win32_maperr(WSAGetLastError());
+ uerror("listen", Nothing);
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/lockf.c b/otherlibs/win32unix/lockf.c
new file mode 100644
index 0000000000..9c705a6788
--- /dev/null
+++ b/otherlibs/win32unix/lockf.c
@@ -0,0 +1,159 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Tracy Camp, PolyServe Inc., <campt@polyserve.com> */
+/* Further improvements by Reed Wilson */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* under the terms of the GNU Library General Public License. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <fcntl.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+#include <stdio.h>
+#include <caml/signals.h>
+
+#ifndef INVALID_SET_FILE_POINTER
+#define INVALID_SET_FILE_POINTER (-1)
+#endif
+
+/* Sets handle h to a position based on gohere */
+/* output, if set, is changed to the new location */
+
+static void set_file_pointer(HANDLE h, LARGE_INTEGER gohere,
+ PLARGE_INTEGER output, DWORD method)
+{
+ LONG high = gohere.HighPart;
+ DWORD ret = SetFilePointer(h, gohere.LowPart, &high, method);
+ if(ret == INVALID_SET_FILE_POINTER) {
+ DWORD err = GetLastError();
+ if(err != NO_ERROR) {
+ win32_maperr(err);
+ uerror("lockf", Nothing);
+ }
+ }
+ if(output != NULL) {
+ output->LowPart = ret;
+ output->HighPart = high;
+ }
+}
+
+CAMLprim value unix_lockf(value fd, value cmd, value span)
+{
+ CAMLparam3(fd, cmd, span);
+ OVERLAPPED overlap;
+ intnat l_len;
+ HANDLE h;
+ OSVERSIONINFO version;
+ LARGE_INTEGER cur_position;
+ LARGE_INTEGER beg_position;
+ LARGE_INTEGER lock_len;
+ LARGE_INTEGER zero;
+ DWORD err = NO_ERROR;
+
+ version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ if(GetVersionEx(&version) == 0) {
+ invalid_argument("lockf only supported on WIN32_NT platforms:"
+ " could not determine current platform.");
+ }
+ if(version.dwPlatformId != VER_PLATFORM_WIN32_NT) {
+ invalid_argument("lockf only supported on WIN32_NT platforms");
+ }
+
+ h = Handle_val(fd);
+
+ l_len = Long_val(span);
+
+ /* No matter what, we need the current position in the file */
+ zero.HighPart = zero.LowPart = 0;
+ set_file_pointer(h, zero, &cur_position, FILE_CURRENT);
+
+ /* All unused fields must be set to zero */
+ memset(&overlap, 0, sizeof(overlap));
+
+ if(l_len == 0) {
+ /* Lock from cur to infinity */
+ lock_len.QuadPart = -1;
+ overlap.OffsetHigh = cur_position.HighPart;
+ overlap.Offset = cur_position.LowPart ;
+ }
+ else if(l_len > 0) {
+ /* Positive file offset */
+ lock_len.QuadPart = l_len;
+ overlap.OffsetHigh = cur_position.HighPart;
+ overlap.Offset = cur_position.LowPart ;
+ }
+ else {
+ /* Negative file offset */
+ lock_len.QuadPart = - l_len;
+ if (lock_len.QuadPart > cur_position.QuadPart) {
+ errno = EINVAL;
+ uerror("lockf", Nothing);
+ }
+ beg_position.QuadPart = cur_position.QuadPart - lock_len.QuadPart;
+ overlap.OffsetHigh = beg_position.HighPart;
+ overlap.Offset = beg_position.LowPart ;
+ }
+
+ switch(Int_val(cmd)) {
+ case 0: /* F_ULOCK - unlock */
+ if (! UnlockFileEx(h, 0,
+ lock_len.LowPart, lock_len.HighPart, &overlap))
+ err = GetLastError();
+ break;
+ case 1: /* F_LOCK - blocking write lock */
+ enter_blocking_section();
+ if (! LockFileEx(h, LOCKFILE_EXCLUSIVE_LOCK, 0,
+ lock_len.LowPart, lock_len.HighPart, &overlap))
+ err = GetLastError();
+ leave_blocking_section();
+ break;
+ case 2: /* F_TLOCK - non-blocking write lock */
+ if (! LockFileEx(h, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0,
+ lock_len.LowPart, lock_len.HighPart, &overlap))
+ err = GetLastError();
+ break;
+ case 3: /* F_TEST - check whether a write lock can be obtained */
+ /* I'm doing this by aquiring an immediate write
+ * lock and then releasing it. It is not clear that
+ * this behavior matches anything in particular, but
+ * it is not clear the nature of the lock test performed
+ * by ocaml (unix) currently. */
+ if (LockFileEx(h, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0,
+ lock_len.LowPart, lock_len.HighPart, &overlap)) {
+ UnlockFileEx(h, 0, lock_len.LowPart, lock_len.HighPart, &overlap);
+ } else {
+ err = GetLastError();
+ }
+ break;
+ case 4: /* F_RLOCK - blocking read lock */
+ enter_blocking_section();
+ if (! LockFileEx(h, 0, 0,
+ lock_len.LowPart, lock_len.HighPart, &overlap))
+ err = GetLastError();
+ leave_blocking_section();
+ break;
+ case 5: /* F_TRLOCK - non-blocking read lock */
+ if (! LockFileEx(h, LOCKFILE_FAIL_IMMEDIATELY, 0,
+ lock_len.LowPart, lock_len.HighPart, &overlap))
+ err = GetLastError();
+ break;
+ default:
+ errno = EINVAL;
+ uerror("lockf", Nothing);
+ }
+ if (err != NO_ERROR) {
+ win32_maperr(err);
+ uerror("lockf", Nothing);
+ }
+ CAMLreturn(Val_unit);
+}
diff --git a/otherlibs/win32unix/lseek.c b/otherlibs/win32unix/lseek.c
new file mode 100644
index 0000000000..6c30a62ae9
--- /dev/null
+++ b/otherlibs/win32unix/lseek.c
@@ -0,0 +1,68 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#else
+#define SEEK_SET 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+#endif
+
+static DWORD seek_command_table[] = {
+ FILE_BEGIN, FILE_CURRENT, FILE_END
+};
+
+#ifndef INVALID_SET_FILE_POINTER
+#define INVALID_SET_FILE_POINTER (-1)
+#endif
+
+static __int64 caml_set_file_pointer(HANDLE h, __int64 dist, DWORD mode)
+{
+ LARGE_INTEGER i;
+ DWORD err;
+
+ i.QuadPart = dist;
+ i.LowPart = SetFilePointer(h, i.LowPart, &i.HighPart, mode);
+ if (i.LowPart == INVALID_SET_FILE_POINTER) {
+ err = GetLastError();
+ if (err != NO_ERROR) { win32_maperr(err); uerror("lseek", Nothing); }
+ }
+ return i.QuadPart;
+}
+
+CAMLprim value unix_lseek(value fd, value ofs, value cmd)
+{
+ __int64 ret;
+
+ ret = caml_set_file_pointer(Handle_val(fd), Long_val(ofs),
+ seek_command_table[Int_val(cmd)]);
+ if (ret > Max_long) {
+ win32_maperr(ERROR_ARITHMETIC_OVERFLOW);
+ uerror("lseek", Nothing);
+ }
+ return Val_long(ret);
+}
+
+CAMLprim value unix_lseek_64(value fd, value ofs, value cmd)
+{
+ __int64 ret;
+
+ ret = caml_set_file_pointer(Handle_val(fd), Int64_val(ofs),
+ seek_command_table[Int_val(cmd)]);
+ return copy_int64(ret);
+}
diff --git a/otherlibs/win32unix/mkdir.c b/otherlibs/win32unix/mkdir.c
new file mode 100644
index 0000000000..21bca10ce4
--- /dev/null
+++ b/otherlibs/win32unix/mkdir.c
@@ -0,0 +1,22 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_mkdir(path, perm)
+ value path, perm;
+{
+ if (_mkdir(String_val(path)) == -1) uerror("mkdir", path);
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/nonblock.c b/otherlibs/win32unix/nonblock.c
new file mode 100755
index 0000000000..4001beca6c
--- /dev/null
+++ b/otherlibs/win32unix/nonblock.c
@@ -0,0 +1,42 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_set_nonblock(socket)
+ value socket;
+{
+ u_long non_block = 1;
+
+ if (ioctlsocket(Socket_val(socket), FIONBIO, &non_block) != 0) {
+ win32_maperr(WSAGetLastError());
+ uerror("unix_set_nonblock", Nothing);
+ }
+ Flags_fd_val(socket) = Flags_fd_val(socket) & ~FLAGS_FD_IS_BLOCKING;
+ return Val_unit;
+}
+
+CAMLprim value unix_clear_nonblock(socket)
+ value socket;
+{
+ u_long non_block = 0;
+
+ if (ioctlsocket(Socket_val(socket), FIONBIO, &non_block) != 0) {
+ win32_maperr(WSAGetLastError());
+ uerror("unix_clear_nonblock", Nothing);
+ }
+ Flags_fd_val(socket) = Flags_fd_val(socket) | FLAGS_FD_IS_BLOCKING;
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/open.c b/otherlibs/win32unix/open.c
new file mode 100644
index 0000000000..f9e9df21ad
--- /dev/null
+++ b/otherlibs/win32unix/open.c
@@ -0,0 +1,76 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+#include <fcntl.h>
+
+static int open_access_flags[14] = {
+ GENERIC_READ, GENERIC_WRITE, GENERIC_READ|GENERIC_WRITE,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+static int open_create_flags[14] = {
+ 0, 0, 0, 0, 0, O_CREAT, O_TRUNC, O_EXCL, 0, 0, 0, 0, 0, 0
+};
+
+static int open_share_flags[14] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, FILE_SHARE_DELETE, 0
+};
+
+static int open_cloexec_flags[14] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
+};
+
+CAMLprim value unix_open(value path, value flags, value perm)
+{
+ int fileaccess, createflags, fileattrib, filecreate, sharemode, cloexec;
+ SECURITY_ATTRIBUTES attr;
+ HANDLE h;
+
+ fileaccess = convert_flag_list(flags, open_access_flags);
+ sharemode = FILE_SHARE_READ | FILE_SHARE_WRITE
+ | convert_flag_list(flags, open_share_flags);
+
+ createflags = convert_flag_list(flags, open_create_flags);
+ if ((createflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
+ filecreate = CREATE_NEW;
+ else if ((createflags & (O_CREAT | O_TRUNC)) == (O_CREAT | O_TRUNC))
+ filecreate = CREATE_ALWAYS;
+ else if (createflags & O_TRUNC)
+ filecreate = TRUNCATE_EXISTING;
+ else if (createflags & O_CREAT)
+ filecreate = OPEN_ALWAYS;
+ else
+ filecreate = OPEN_EXISTING;
+
+ if ((createflags & O_CREAT) && (Int_val(perm) & 0200) == 0)
+ fileattrib = FILE_ATTRIBUTE_READONLY;
+ else
+ fileattrib = FILE_ATTRIBUTE_NORMAL;
+
+ cloexec = convert_flag_list(flags, open_cloexec_flags);
+ attr.nLength = sizeof(attr);
+ attr.lpSecurityDescriptor = NULL;
+ attr.bInheritHandle = cloexec ? FALSE : TRUE;
+
+ h = CreateFile(String_val(path), fileaccess,
+ sharemode, &attr,
+ filecreate, fileattrib, NULL);
+ if (h == INVALID_HANDLE_VALUE) {
+ win32_maperr(GetLastError());
+ uerror("open", path);
+ }
+ return win_alloc_handle(h);
+}
diff --git a/otherlibs/win32unix/pipe.c b/otherlibs/win32unix/pipe.c
new file mode 100644
index 0000000000..88debb023a
--- /dev/null
+++ b/otherlibs/win32unix/pipe.c
@@ -0,0 +1,44 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+#include <fcntl.h>
+
+/* PR#4749: pick a size that matches that of I/O buffers */
+#define SIZEBUF 4096
+
+CAMLprim value unix_pipe(value unit)
+{
+ SECURITY_ATTRIBUTES attr;
+ HANDLE readh, writeh;
+ value readfd = Val_unit, writefd = Val_unit, res;
+
+ attr.nLength = sizeof(attr);
+ attr.lpSecurityDescriptor = NULL;
+ attr.bInheritHandle = TRUE;
+ if (! CreatePipe(&readh, &writeh, &attr, SIZEBUF)) {
+ win32_maperr(GetLastError());
+ uerror("pipe", Nothing);
+ }
+ Begin_roots2(readfd, writefd)
+ readfd = win_alloc_handle(readh);
+ writefd = win_alloc_handle(writeh);
+ res = alloc_small(2, 0);
+ Field(res, 0) = readfd;
+ Field(res, 1) = writefd;
+ End_roots();
+ return res;
+}
diff --git a/otherlibs/win32unix/read.c b/otherlibs/win32unix/read.c
new file mode 100644
index 0000000000..d65683cc60
--- /dev/null
+++ b/otherlibs/win32unix/read.c
@@ -0,0 +1,52 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_read(value fd, value buf, value ofs, value vlen)
+{
+ intnat len;
+ DWORD numbytes, numread;
+ char iobuf[UNIX_BUFFER_SIZE];
+ DWORD err = 0;
+
+ Begin_root (buf);
+ len = Long_val(vlen);
+ numbytes = len > UNIX_BUFFER_SIZE ? UNIX_BUFFER_SIZE : len;
+ if (Descr_kind_val(fd) == KIND_SOCKET) {
+ int ret;
+ SOCKET s = Socket_val(fd);
+ enter_blocking_section();
+ ret = recv(s, iobuf, numbytes, 0);
+ if (ret == SOCKET_ERROR) err = WSAGetLastError();
+ leave_blocking_section();
+ numread = ret;
+ } else {
+ HANDLE h = Handle_val(fd);
+ enter_blocking_section();
+ if (! ReadFile(h, iobuf, numbytes, &numread, NULL))
+ err = GetLastError();
+ leave_blocking_section();
+ }
+ if (err) {
+ win32_maperr(err);
+ uerror("read", Nothing);
+ }
+ memmove (&Byte(buf, Long_val(ofs)), iobuf, numread);
+ End_roots();
+ return Val_int(numread);
+}
diff --git a/otherlibs/win32unix/rename.c b/otherlibs/win32unix/rename.c
new file mode 100644
index 0000000000..ad46ead246
--- /dev/null
+++ b/otherlibs/win32unix/rename.c
@@ -0,0 +1,41 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Tracy Camp, PolyServe Inc., <campt@polyserve.com> */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_rename(value path1, value path2)
+{
+ static int supports_MoveFileEx = -1; /* don't know yet */
+ BOOL ok;
+
+ if (supports_MoveFileEx < 0) {
+ OSVERSIONINFO VersionInfo;
+ VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ supports_MoveFileEx =
+ (GetVersionEx(&VersionInfo) != 0)
+ && (VersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT);
+ }
+ if (supports_MoveFileEx > 0)
+ ok = MoveFileEx(String_val(path1), String_val(path2),
+ MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH |
+ MOVEFILE_COPY_ALLOWED);
+ else
+ ok = MoveFile(String_val(path1), String_val(path2));
+ if (! ok) {
+ win32_maperr(GetLastError());
+ uerror("rename", path1);
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/select.c b/otherlibs/win32unix/select.c
new file mode 100644
index 0000000000..826ad172ad
--- /dev/null
+++ b/otherlibs/win32unix/select.c
@@ -0,0 +1,1319 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Sylvain Le Gall for Lexifi */
+/* */
+/* Copyright 2008 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/fail.h>
+#include <caml/signals.h>
+#include "winworker.h"
+#include <stdio.h>
+#include "windbug.h"
+#include "winlist.h"
+
+/* This constant define the maximum number of objects that
+ * can be handle by a SELECTDATA.
+ * It takes the following parameters into account:
+ * - limitation on number of objects is mostly due to limitation
+ * a WaitForMultipleObjects
+ * - there is always an event "hStop" to watch
+ *
+ * This lead to pick the following value as the biggest possible
+ * value
+ */
+#define MAXIMUM_SELECT_OBJECTS (MAXIMUM_WAIT_OBJECTS - 1)
+
+/* Manage set of handle */
+typedef struct _SELECTHANDLESET {
+ LPHANDLE lpHdl;
+ DWORD nMax;
+ DWORD nLast;
+} SELECTHANDLESET;
+
+typedef SELECTHANDLESET *LPSELECTHANDLESET;
+
+void handle_set_init (LPSELECTHANDLESET hds, LPHANDLE lpHdl, DWORD max)
+{
+ DWORD i;
+
+ hds->lpHdl = lpHdl;
+ hds->nMax = max;
+ hds->nLast = 0;
+
+ /* Set to invalid value every entry of the handle */
+ for (i = 0; i < hds->nMax; i++)
+ {
+ hds->lpHdl[i] = INVALID_HANDLE_VALUE;
+ };
+}
+
+void handle_set_add (LPSELECTHANDLESET hds, HANDLE hdl)
+{
+ LPSELECTHANDLESET res;
+
+ if (hds->nLast < hds->nMax)
+ {
+ hds->lpHdl[hds->nLast] = hdl;
+ hds->nLast++;
+ }
+
+ DEBUG_PRINT("Adding handle %x to set %x", hdl, hds);
+}
+
+BOOL handle_set_mem (LPSELECTHANDLESET hds, HANDLE hdl)
+{
+ BOOL res;
+ DWORD i;
+
+ res = FALSE;
+ for (i = 0; !res && i < hds->nLast; i++)
+ {
+ res = (hds->lpHdl[i] == hdl);
+ }
+
+ return res;
+}
+
+void handle_set_reset (LPSELECTHANDLESET hds)
+{
+ DWORD i;
+
+ for (i = 0; i < hds->nMax; i++)
+ {
+ hds->lpHdl[i] = INVALID_HANDLE_VALUE;
+ }
+ hds->nMax = 0;
+ hds->nLast = 0;
+ hds->lpHdl = NULL;
+}
+
+/* Data structure for handling select */
+
+typedef enum _SELECTHANDLETYPE {
+ SELECT_HANDLE_NONE = 0,
+ SELECT_HANDLE_DISK,
+ SELECT_HANDLE_CONSOLE,
+ SELECT_HANDLE_PIPE,
+ SELECT_HANDLE_SOCKET,
+} SELECTHANDLETYPE;
+
+typedef enum _SELECTMODE {
+ SELECT_MODE_NONE = 0,
+ SELECT_MODE_READ = 1,
+ SELECT_MODE_WRITE = 2,
+ SELECT_MODE_EXCEPT = 4,
+} SELECTMODE;
+
+typedef enum _SELECTSTATE {
+ SELECT_STATE_NONE = 0,
+ SELECT_STATE_INITFAILED,
+ SELECT_STATE_ERROR,
+ SELECT_STATE_SIGNALED
+} SELECTSTATE;
+
+typedef enum _SELECTTYPE {
+ SELECT_TYPE_NONE = 0,
+ SELECT_TYPE_STATIC, /* Result is known without running anything */
+ SELECT_TYPE_CONSOLE_READ, /* Reading data on console */
+ SELECT_TYPE_PIPE_READ, /* Reading data on pipe */
+ SELECT_TYPE_SOCKET /* Classic select */
+} SELECTTYPE;
+
+/* Data structure for results */
+typedef struct _SELECTRESULT {
+ LIST lst;
+ SELECTMODE EMode;
+ int lpOrigIdx;
+} SELECTRESULT;
+
+typedef SELECTRESULT *LPSELECTRESULT;
+
+/* Data structure for query */
+typedef struct _SELECTQUERY {
+ LIST lst;
+ SELECTMODE EMode;
+ HANDLE hFileDescr;
+ int lpOrigIdx;
+ unsigned int uFlagsFd; /* Copy of filedescr->flags_fd */
+} SELECTQUERY;
+
+typedef SELECTQUERY *LPSELECTQUERY;
+
+typedef struct _SELECTDATA {
+ LIST lst;
+ SELECTTYPE EType;
+ /* Sockets may generate a result for all three lists from one single
+ query object
+ */
+ SELECTRESULT aResults[MAXIMUM_SELECT_OBJECTS * 3];
+ DWORD nResultsCount;
+ /* Data following are dedicated to APC like call, they
+ will be initialized if required.
+ */
+ WORKERFUNC funcWorker;
+ SELECTQUERY aQueries[MAXIMUM_SELECT_OBJECTS];
+ DWORD nQueriesCount;
+ SELECTSTATE EState;
+ DWORD nError;
+ LPWORKER lpWorker;
+} SELECTDATA;
+
+typedef SELECTDATA *LPSELECTDATA;
+
+/* Get error status if associated condition is false */
+static BOOL check_error(LPSELECTDATA lpSelectData, BOOL bFailed)
+{
+ if (bFailed && lpSelectData->nError == 0)
+ {
+ lpSelectData->EState = SELECT_STATE_ERROR;
+ lpSelectData->nError = GetLastError();
+ }
+ return bFailed;
+}
+
+/* Create data associated with a select operation */
+LPSELECTDATA select_data_new (LPSELECTDATA lpSelectData, SELECTTYPE EType)
+{
+ /* Allocate the data structure */
+ LPSELECTDATA res;
+ DWORD i;
+
+ res = (LPSELECTDATA)caml_stat_alloc(sizeof(SELECTDATA));
+
+ /* Init common data */
+ list_init((LPLIST)res);
+ list_next_set((LPLIST)res, (LPLIST)lpSelectData);
+ res->EType = EType;
+ res->nResultsCount = 0;
+
+
+ /* Data following are dedicated to APC like call, they
+ will be initialized if required. For now they are set to
+ invalid values.
+ */
+ res->funcWorker = NULL;
+ res->nQueriesCount = 0;
+ res->EState = SELECT_STATE_NONE;
+ res->nError = 0;
+ res->lpWorker = NULL;
+
+ return res;
+}
+
+/* Free select data */
+void select_data_free (LPSELECTDATA lpSelectData)
+{
+ DWORD i;
+
+ DEBUG_PRINT("Freeing data of %x", lpSelectData);
+
+ /* Free APC related data, if they exists */
+ if (lpSelectData->lpWorker != NULL)
+ {
+ worker_job_finish(lpSelectData->lpWorker);
+ lpSelectData->lpWorker = NULL;
+ };
+
+ /* Make sure results/queries cannot be accessed */
+ lpSelectData->nResultsCount = 0;
+ lpSelectData->nQueriesCount = 0;
+
+ caml_stat_free(lpSelectData);
+}
+
+/* Add a result to select data, return zero if something goes wrong. */
+DWORD select_data_result_add (LPSELECTDATA lpSelectData, SELECTMODE EMode,
+ int lpOrigIdx)
+{
+ DWORD res;
+ DWORD i;
+
+ res = 0;
+ if (lpSelectData->nResultsCount < MAXIMUM_SELECT_OBJECTS * 3)
+ {
+ i = lpSelectData->nResultsCount;
+ lpSelectData->aResults[i].EMode = EMode;
+ lpSelectData->aResults[i].lpOrigIdx = lpOrigIdx;
+ lpSelectData->nResultsCount++;
+ res = 1;
+ }
+
+ return res;
+}
+
+/* Add a query to select data, return zero if something goes wrong */
+DWORD select_data_query_add (LPSELECTDATA lpSelectData,
+ SELECTMODE EMode,
+ HANDLE hFileDescr,
+ int lpOrigIdx,
+ unsigned int uFlagsFd)
+{
+ DWORD res;
+ DWORD i;
+
+ res = 0;
+ if (lpSelectData->nQueriesCount < MAXIMUM_SELECT_OBJECTS)
+ {
+ i = lpSelectData->nQueriesCount;
+ lpSelectData->aQueries[i].EMode = EMode;
+ lpSelectData->aQueries[i].hFileDescr = hFileDescr;
+ lpSelectData->aQueries[i].lpOrigIdx = lpOrigIdx;
+ lpSelectData->aQueries[i].uFlagsFd = uFlagsFd;
+ lpSelectData->nQueriesCount++;
+ res = 1;
+ }
+
+ return res;
+}
+
+/* Search for a job that has available query slots and that match provided type.
+ * If none is found, create a new one. Return the corresponding SELECTDATA, and
+ * update provided SELECTDATA head, if required.
+ */
+LPSELECTDATA select_data_job_search (LPSELECTDATA *lppSelectData,
+ SELECTTYPE EType)
+{
+ LPSELECTDATA res;
+
+ res = NULL;
+
+ /* Search for job */
+ DEBUG_PRINT("Searching an available job for type %d", EType);
+ res = *lppSelectData;
+ while (
+ res != NULL
+ && !(
+ res->EType == EType
+ && res->nQueriesCount < MAXIMUM_SELECT_OBJECTS
+ )
+ )
+ {
+ res = LIST_NEXT(LPSELECTDATA, res);
+ }
+
+ /* No matching job found, create one */
+ if (res == NULL)
+ {
+ DEBUG_PRINT("No job for type %d found, create one", EType);
+ res = select_data_new(*lppSelectData, EType);
+ *lppSelectData = res;
+ }
+
+ return res;
+}
+
+/***********************/
+/* Console */
+/***********************/
+
+void read_console_poll(HANDLE hStop, void *_data)
+{
+ HANDLE events[2];
+ INPUT_RECORD record;
+ DWORD waitRes;
+ DWORD n;
+ LPSELECTDATA lpSelectData;
+ LPSELECTQUERY lpQuery;
+
+ DEBUG_PRINT("Waiting for data on console");
+
+ record;
+ waitRes = 0;
+ n = 0;
+ lpSelectData = (LPSELECTDATA)_data;
+ lpQuery = &(lpSelectData->aQueries[0]);
+
+ events[0] = hStop;
+ events[1] = lpQuery->hFileDescr;
+ while (lpSelectData->EState == SELECT_STATE_NONE)
+ {
+ waitRes = WaitForMultipleObjects(2, events, FALSE, INFINITE);
+ if (waitRes == WAIT_OBJECT_0
+ || check_error(lpSelectData, waitRes == WAIT_FAILED))
+ {
+ /* stop worker event or error */
+ break;
+ }
+ /* console event */
+ if (check_error(lpSelectData, PeekConsoleInput(lpQuery->hFileDescr,
+ &record, 1, &n)
+ == 0))
+ {
+ break;
+ }
+ /* check for ASCII keypress only */
+ if (record.EventType == KEY_EVENT &&
+ record.Event.KeyEvent.bKeyDown &&
+ record.Event.KeyEvent.uChar.AsciiChar != 0)
+ {
+ select_data_result_add(lpSelectData, lpQuery->EMode, lpQuery->lpOrigIdx);
+ lpSelectData->EState = SELECT_STATE_SIGNALED;
+ break;
+ }
+ else
+ {
+ /* discard everything else and try again */
+ if (check_error(lpSelectData, ReadConsoleInput(lpQuery->hFileDescr,
+ &record, 1, &n)
+ == 0))
+ {
+ break;
+ }
+ }
+ };
+}
+
+/* Add a function to monitor console input */
+LPSELECTDATA read_console_poll_add (LPSELECTDATA lpSelectData,
+ SELECTMODE EMode,
+ HANDLE hFileDescr,
+ int lpOrigIdx,
+ unsigned int uFlagsFd)
+{
+ LPSELECTDATA res;
+
+ res = select_data_new(lpSelectData, SELECT_TYPE_CONSOLE_READ);
+ res->funcWorker = read_console_poll;
+ select_data_query_add(res, SELECT_MODE_READ, hFileDescr, lpOrigIdx, uFlagsFd);
+
+ return res;
+}
+
+/***********************/
+/* Pipe */
+/***********************/
+
+/* Monitor a pipe for input */
+void read_pipe_poll (HANDLE hStop, void *_data)
+{
+ DWORD res;
+ DWORD event;
+ DWORD n;
+ LPSELECTQUERY iterQuery;
+ LPSELECTDATA lpSelectData;
+ DWORD i;
+ DWORD wait;
+
+ /* Poll pipe */
+ event = 0;
+ n = 0;
+ lpSelectData = (LPSELECTDATA)_data;
+ wait = 1;
+
+ DEBUG_PRINT("Checking data pipe");
+ while (lpSelectData->EState == SELECT_STATE_NONE)
+ {
+ for (i = 0; i < lpSelectData->nQueriesCount; i++)
+ {
+ iterQuery = &(lpSelectData->aQueries[i]);
+ res = PeekNamedPipe(
+ iterQuery->hFileDescr,
+ NULL,
+ 0,
+ NULL,
+ &n,
+ NULL);
+ if (check_error(lpSelectData,
+ (res == 0) &&
+ (GetLastError() != ERROR_BROKEN_PIPE)))
+ {
+ break;
+ };
+
+ if ((n > 0) || (res == 0))
+ {
+ lpSelectData->EState = SELECT_STATE_SIGNALED;
+ select_data_result_add(lpSelectData, iterQuery->EMode,
+ iterQuery->lpOrigIdx);
+ };
+ };
+
+ /* Alas, nothing except polling seems to work for pipes.
+ Check the state & stop_worker_event every 10 ms
+ */
+ if (lpSelectData->EState == SELECT_STATE_NONE)
+ {
+ event = WaitForSingleObject(hStop, wait);
+
+ /* Fast start: begin to wait 1, 2, 4, 8 and then 10 ms.
+ * If we are working with the output of a program there is
+ * a chance that one of the 4 first calls succeed.
+ */
+ wait = 2 * wait;
+ if (wait > 10)
+ {
+ wait = 10;
+ };
+ if (event == WAIT_OBJECT_0
+ || check_error(lpSelectData, event == WAIT_FAILED))
+ {
+ break;
+ }
+ }
+ }
+ DEBUG_PRINT("Finish checking data on pipe");
+}
+
+/* Add a function to monitor pipe input */
+LPSELECTDATA read_pipe_poll_add (LPSELECTDATA lpSelectData,
+ SELECTMODE EMode,
+ HANDLE hFileDescr,
+ int lpOrigIdx,
+ unsigned int uFlagsFd)
+{
+ LPSELECTDATA res;
+ LPSELECTDATA hd;
+
+ hd = lpSelectData;
+ /* Polling pipe is a non blocking operation by default. This means that each
+ worker can handle many pipe. We begin to try to find a worker that is
+ polling pipe, but for which there is under the limit of pipe per worker.
+ */
+ DEBUG_PRINT("Searching an available worker handling pipe");
+ res = select_data_job_search(&hd, SELECT_TYPE_PIPE_READ);
+
+ /* Add a new pipe to poll */
+ res->funcWorker = read_pipe_poll;
+ select_data_query_add(res, EMode, hFileDescr, lpOrigIdx, uFlagsFd);
+
+ return hd;
+}
+
+/***********************/
+/* Socket */
+/***********************/
+
+/* Monitor socket */
+void socket_poll (HANDLE hStop, void *_data)
+{
+ LPSELECTDATA lpSelectData;
+ LPSELECTQUERY iterQuery;
+ HANDLE aEvents[MAXIMUM_SELECT_OBJECTS];
+ DWORD nEvents;
+ long maskEvents;
+ DWORD i;
+ u_long iMode;
+ SELECTMODE mode;
+ WSANETWORKEVENTS events;
+
+ lpSelectData = (LPSELECTDATA)_data;
+
+ DEBUG_PRINT("Worker has %d queries to service", lpSelectData->nQueriesCount);
+ for (nEvents = 0; nEvents < lpSelectData->nQueriesCount; nEvents++)
+ {
+ iterQuery = &(lpSelectData->aQueries[nEvents]);
+ aEvents[nEvents] = CreateEvent(NULL, TRUE, FALSE, NULL);
+ maskEvents = 0;
+ mode = iterQuery->EMode;
+ if ((mode & SELECT_MODE_READ) != 0)
+ {
+ DEBUG_PRINT("Polling read for %d", iterQuery->hFileDescr);
+ maskEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
+ }
+ if ((mode & SELECT_MODE_WRITE) != 0)
+ {
+ DEBUG_PRINT("Polling write for %d", iterQuery->hFileDescr);
+ maskEvents |= FD_WRITE | FD_CONNECT | FD_CLOSE;
+ }
+ if ((mode & SELECT_MODE_EXCEPT) != 0)
+ {
+ DEBUG_PRINT("Polling exceptions for %d", iterQuery->hFileDescr);
+ maskEvents |= FD_OOB;
+ }
+
+ check_error(lpSelectData,
+ WSAEventSelect(
+ (SOCKET)(iterQuery->hFileDescr),
+ aEvents[nEvents],
+ maskEvents) == SOCKET_ERROR);
+ }
+
+ /* Add stop event */
+ aEvents[nEvents] = hStop;
+ nEvents++;
+
+ if (lpSelectData->nError == 0)
+ {
+ check_error(lpSelectData,
+ WaitForMultipleObjects(
+ nEvents,
+ aEvents,
+ FALSE,
+ INFINITE) == WAIT_FAILED);
+ };
+
+ if (lpSelectData->nError == 0)
+ {
+ for (i = 0; i < lpSelectData->nQueriesCount; i++)
+ {
+ iterQuery = &(lpSelectData->aQueries[i]);
+ if (WaitForSingleObject(aEvents[i], 0) == WAIT_OBJECT_0)
+ {
+ DEBUG_PRINT("Socket %d has pending events", (i - 1));
+ if (iterQuery != NULL)
+ {
+ /* Find out what kind of events were raised
+ */
+ if (WSAEnumNetworkEvents((SOCKET)(iterQuery->hFileDescr),
+ aEvents[i], &events) == 0)
+ {
+ if ((iterQuery->EMode & SELECT_MODE_READ) != 0
+ && (events.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
+ != 0)
+ {
+ select_data_result_add(lpSelectData, SELECT_MODE_READ,
+ iterQuery->lpOrigIdx);
+ }
+ if ((iterQuery->EMode & SELECT_MODE_WRITE) != 0
+ && (events.lNetworkEvents & (FD_WRITE | FD_CONNECT | FD_CLOSE))
+ != 0)
+ {
+ select_data_result_add(lpSelectData, SELECT_MODE_WRITE,
+ iterQuery->lpOrigIdx);
+ }
+ if ((iterQuery->EMode & SELECT_MODE_EXCEPT) != 0
+ && (events.lNetworkEvents & FD_OOB) != 0)
+ {
+ select_data_result_add(lpSelectData, SELECT_MODE_EXCEPT,
+ iterQuery->lpOrigIdx);
+ }
+ }
+ }
+ }
+ /* WSAEventSelect() automatically sets socket to nonblocking mode.
+ Restore the blocking one. */
+ if (iterQuery->uFlagsFd & FLAGS_FD_IS_BLOCKING)
+ {
+ DEBUG_PRINT("Restore a blocking socket");
+ iMode = 0;
+ check_error(lpSelectData,
+ WSAEventSelect((SOCKET)(iterQuery->hFileDescr), aEvents[i], 0) != 0 ||
+ ioctlsocket((SOCKET)(iterQuery->hFileDescr), FIONBIO, &iMode) != 0);
+ }
+ else
+ {
+ check_error(lpSelectData,
+ WSAEventSelect((SOCKET)(iterQuery->hFileDescr), aEvents[i], 0) != 0);
+ };
+
+ CloseHandle(aEvents[i]);
+ aEvents[i] = INVALID_HANDLE_VALUE;
+ }
+ }
+}
+
+/* Add a function to monitor socket */
+LPSELECTDATA socket_poll_add (LPSELECTDATA lpSelectData,
+ SELECTMODE EMode,
+ HANDLE hFileDescr,
+ int lpOrigIdx,
+ unsigned int uFlagsFd)
+{
+ LPSELECTDATA res;
+ LPSELECTDATA candidate;
+ long i;
+ LPSELECTQUERY aQueries;
+
+ res = lpSelectData;
+ candidate = NULL;
+ aQueries = NULL;
+
+ /* Polling socket can be done mulitple handle at the same time. You just
+ need one worker to use it. Try to find if there is already a worker
+ handling this kind of request.
+ Only one event can be associated with a given socket which means
+ that if a socket is in more than one of the fd_sets then we have
+ to find that particular query and update EMode with the
+ additional flag.
+ */
+ DEBUG_PRINT("Scanning list of worker to find one that already handle socket");
+ /* Search for job */
+ DEBUG_PRINT("Searching for an available job for type %d for descriptor %d",
+ SELECT_TYPE_SOCKET, hFileDescr);
+ while (res != NULL)
+ {
+ if (res->EType == SELECT_TYPE_SOCKET)
+ {
+ i = res->nQueriesCount - 1;
+ aQueries = res->aQueries;
+ while (i >= 0 && aQueries[i].hFileDescr != hFileDescr)
+ {
+ i--;
+ }
+ /* If we didn't find the socket but this worker has available
+ slots, store it
+ */
+ if (i < 0)
+ {
+ if ( res->nQueriesCount < MAXIMUM_SELECT_OBJECTS)
+ {
+ candidate = res;
+ }
+ res = LIST_NEXT(LPSELECTDATA, res);
+ }
+ else
+ {
+ /* Previous socket query located -- we're finished
+ */
+ aQueries = &aQueries[i];
+ break;
+ }
+ }
+ else
+ {
+ res = LIST_NEXT(LPSELECTDATA, res);
+ }
+ }
+
+ if (res == NULL)
+ {
+ res = candidate;
+
+ /* No matching job found, create one */
+ if (res == NULL)
+ {
+ DEBUG_PRINT("No job for type %d found, create one", SELECT_TYPE_SOCKET);
+ res = select_data_new(lpSelectData, SELECT_TYPE_SOCKET);
+ res->funcWorker = socket_poll;
+ res->nQueriesCount = 1;
+ aQueries = &res->aQueries[0];
+ }
+ else
+ {
+ aQueries = &(res->aQueries[res->nQueriesCount++]);
+ }
+ aQueries->EMode = EMode;
+ aQueries->hFileDescr = hFileDescr;
+ aQueries->lpOrigIdx = lpOrigIdx;
+ aQueries->uFlagsFd = uFlagsFd;
+ DEBUG_PRINT("Socket %x added", hFileDescr);
+ }
+ else
+ {
+ aQueries->EMode |= EMode;
+ DEBUG_PRINT("Socket %x updated to %d", hFileDescr, aQueries->EMode);
+ }
+
+ return res;
+}
+
+/***********************/
+/* Static */
+/***********************/
+
+/* Add a static result */
+LPSELECTDATA static_poll_add (LPSELECTDATA lpSelectData,
+ SELECTMODE EMode,
+ HANDLE hFileDescr,
+ int lpOrigIdx,
+ unsigned int uFlagsFd)
+{
+ LPSELECTDATA res;
+ LPSELECTDATA hd;
+
+ /* Look for an already initialized static element */
+ hd = lpSelectData;
+ res = select_data_job_search(&hd, SELECT_TYPE_STATIC);
+
+ /* Add a new query/result */
+ select_data_query_add(res, EMode, hFileDescr, lpOrigIdx, uFlagsFd);
+ select_data_result_add(res, EMode, lpOrigIdx);
+
+ return hd;
+}
+
+/********************************/
+/* Generic select data handling */
+/********************************/
+
+/* Guess handle type */
+static SELECTHANDLETYPE get_handle_type(value fd)
+{
+ DWORD mode;
+ SELECTHANDLETYPE res;
+
+ CAMLparam1(fd);
+
+ mode = 0;
+ res = SELECT_HANDLE_NONE;
+
+ if (Descr_kind_val(fd) == KIND_SOCKET)
+ {
+ res = SELECT_HANDLE_SOCKET;
+ }
+ else
+ {
+ switch(GetFileType(Handle_val(fd)))
+ {
+ case FILE_TYPE_DISK:
+ res = SELECT_HANDLE_DISK;
+ break;
+
+ case FILE_TYPE_CHAR: /* character file or a console */
+ if (GetConsoleMode(Handle_val(fd), &mode) != 0)
+ {
+ res = SELECT_HANDLE_CONSOLE;
+ }
+ else
+ {
+ res = SELECT_HANDLE_NONE;
+ };
+ break;
+
+ case FILE_TYPE_PIPE: /* a named or an anonymous pipe (socket
+ already handled) */
+ res = SELECT_HANDLE_PIPE;
+ break;
+ };
+ };
+
+ CAMLreturnT(SELECTHANDLETYPE, res);
+}
+
+/* Choose what to do with given data */
+LPSELECTDATA select_data_dispatch (LPSELECTDATA lpSelectData, SELECTMODE EMode,
+ value fd, int lpOrigIdx)
+{
+ LPSELECTDATA res;
+ HANDLE hFileDescr;
+ struct sockaddr sa;
+ int sa_len;
+ BOOL alreadyAdded;
+ unsigned int uFlagsFd;
+
+ CAMLparam1(fd);
+
+ res = lpSelectData;
+ hFileDescr = Handle_val(fd);
+ sa_len = sizeof(sa);
+ alreadyAdded = FALSE;
+ uFlagsFd = Flags_fd_val(fd);
+
+ DEBUG_PRINT("Begin dispatching handle %x", hFileDescr);
+
+ DEBUG_PRINT("Waiting for %d on handle %x", EMode, hFileDescr);
+
+ /* There is only 2 way to have except mode: transmission of OOB data through
+ a socket TCP/IP and through a strange interaction with a TTY.
+ With windows, we only consider the TCP/IP except condition
+ */
+ switch(get_handle_type(fd))
+ {
+ case SELECT_HANDLE_DISK:
+ DEBUG_PRINT("Handle %x is a disk handle", hFileDescr);
+ /* Disk is always ready in read/write operation */
+ if (EMode == SELECT_MODE_READ || EMode == SELECT_MODE_WRITE)
+ {
+ res = static_poll_add(res, EMode, hFileDescr, lpOrigIdx, uFlagsFd);
+ };
+ break;
+
+ case SELECT_HANDLE_CONSOLE:
+ DEBUG_PRINT("Handle %x is a console handle", hFileDescr);
+ /* Console is always ready in write operation, need to check for read. */
+ if (EMode == SELECT_MODE_READ)
+ {
+ res = read_console_poll_add(res, EMode, hFileDescr, lpOrigIdx,
+ uFlagsFd);
+ }
+ else if (EMode == SELECT_MODE_WRITE)
+ {
+ res = static_poll_add(res, EMode, hFileDescr, lpOrigIdx, uFlagsFd);
+ };
+ break;
+
+ case SELECT_HANDLE_PIPE:
+ DEBUG_PRINT("Handle %x is a pipe handle", hFileDescr);
+ /* Console is always ready in write operation, need to check for read. */
+ if (EMode == SELECT_MODE_READ)
+ {
+ DEBUG_PRINT("Need to check availability of data on pipe");
+ res = read_pipe_poll_add(res, EMode, hFileDescr, lpOrigIdx, uFlagsFd);
+ }
+ else if (EMode == SELECT_MODE_WRITE)
+ {
+ DEBUG_PRINT("No need to check availability of data on pipe, "
+ "write operation always possible");
+ res = static_poll_add(res, EMode, hFileDescr, lpOrigIdx, uFlagsFd);
+ };
+ break;
+
+ case SELECT_HANDLE_SOCKET:
+ DEBUG_PRINT("Handle %x is a socket handle", hFileDescr);
+ if (getsockname((SOCKET)hFileDescr, &sa, &sa_len) == SOCKET_ERROR)
+ {
+ if (WSAGetLastError() == WSAEINVAL)
+ {
+ /* Socket is not bound */
+ DEBUG_PRINT("Socket is not connected");
+ if (EMode == SELECT_MODE_WRITE || EMode == SELECT_MODE_READ)
+ {
+ res = static_poll_add(res, EMode, hFileDescr, lpOrigIdx, uFlagsFd);
+ alreadyAdded = TRUE;
+ }
+ }
+ }
+ if (!alreadyAdded)
+ {
+ res = socket_poll_add(res, EMode, hFileDescr, lpOrigIdx, uFlagsFd);
+ }
+ break;
+
+ default:
+ DEBUG_PRINT("Handle %x is unknown", hFileDescr);
+ win32_maperr(ERROR_INVALID_HANDLE);
+ uerror("select", Nothing);
+ break;
+ };
+
+ DEBUG_PRINT("Finish dispatching handle %x", hFileDescr);
+
+ CAMLreturnT(LPSELECTDATA, res);
+}
+
+static DWORD caml_list_length (value lst)
+{
+ DWORD res;
+
+ CAMLparam1 (lst);
+ CAMLlocal1 (l);
+
+ for (res = 0, l = lst; l != Val_int(0); l = Field(l, 1), res++)
+ { }
+
+ CAMLreturnT(DWORD, res);
+}
+
+static value find_handle(LPSELECTRESULT iterResult, value readfds,
+ value writefds, value exceptfds)
+{
+ CAMLparam3(readfds, writefds, exceptfds);
+ CAMLlocal2(result, list);
+ int i;
+
+ switch( iterResult->EMode )
+ {
+ case SELECT_MODE_READ:
+ list = readfds;
+ break;
+ case SELECT_MODE_WRITE:
+ list = writefds;
+ break;
+ case SELECT_MODE_EXCEPT:
+ list = exceptfds;
+ break;
+ };
+
+ for(i=0; list != Val_unit && i < iterResult->lpOrigIdx; ++i )
+ {
+ list = Field(list, 1);
+ }
+
+ if (list == Val_unit)
+ failwith ("select.c: original file handle not found");
+
+ result = Field(list, 0);
+
+ CAMLreturn( result );
+}
+
+#define MAX(a, b) ((a) > (b) ? (a) : (b))
+
+/* Convert fdlist to an fd_set if all the handles in fdlist are
+ * sockets and return 0. Returns 1 if a non-socket value is
+ * encountered.
+ */
+static int fdlist_to_fdset(value fdlist, fd_set *fdset)
+{
+ value l, c;
+ FD_ZERO(fdset);
+ for (l = fdlist; l != Val_int(0); l = Field(l, 1)) {
+ c = Field(l, 0);
+ if (Descr_kind_val(c) == KIND_SOCKET) {
+ FD_SET(Socket_val(c), fdset);
+ } else {
+ DEBUG_PRINT("Non socket value encountered");
+ return 0;
+ }
+ }
+ return 1;
+}
+
+static value fdset_to_fdlist(value fdlist, fd_set *fdset)
+{
+ value res = Val_int(0);
+ Begin_roots2(fdlist, res)
+ for (/*nothing*/; fdlist != Val_int(0); fdlist = Field(fdlist, 1)) {
+ value s = Field(fdlist, 0);
+ if (FD_ISSET(Socket_val(s), fdset)) {
+ value newres = alloc_small(2, 0);
+ Field(newres, 0) = s;
+ Field(newres, 1) = res;
+ res = newres;
+ }
+ }
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_select(value readfds, value writefds, value exceptfds,
+ value timeout)
+{
+ /* Event associated to handle */
+ DWORD nEventsCount;
+ DWORD nEventsMax;
+ HANDLE *lpEventsDone;
+
+ /* Data for all handles */
+ LPSELECTDATA lpSelectData;
+ LPSELECTDATA iterSelectData;
+
+ /* Iterator for results */
+ LPSELECTRESULT iterResult;
+
+ /* Iterator */
+ DWORD i;
+
+ /* Error status */
+ DWORD err;
+
+ /* Time to wait */
+ DWORD milliseconds;
+
+ /* Is there static select data */
+ BOOL hasStaticData = FALSE;
+
+ /* Wait return */
+ DWORD waitRet;
+
+ /* Set of handle */
+ SELECTHANDLESET hds;
+ DWORD hdsMax;
+ LPHANDLE hdsData;
+
+ /* Length of each list */
+ DWORD readfds_len;
+ DWORD writefds_len;
+ DWORD exceptfds_len;
+
+ CAMLparam4 (readfds, writefds, exceptfds, timeout);
+ CAMLlocal5 (read_list, write_list, except_list, res, l);
+ CAMLlocal1 (fd);
+
+ fd_set read, write, except;
+ double tm;
+ struct timeval tv;
+ struct timeval * tvp;
+
+ DEBUG_PRINT("in select");
+
+ err = 0;
+ tm = Double_val(timeout);
+ if (readfds == Val_int(0)
+ && writefds == Val_int(0)
+ && exceptfds == Val_int(0)) {
+ DEBUG_PRINT("nothing to do");
+ if ( tm > 0.0 ) {
+ enter_blocking_section();
+ Sleep( (int)(tm * 1000));
+ leave_blocking_section();
+ }
+ read_list = write_list = except_list = Val_int(0);
+ } else {
+ if (fdlist_to_fdset(readfds, &read)
+ && fdlist_to_fdset(writefds, &write)
+ && fdlist_to_fdset(exceptfds, &except)) {
+ DEBUG_PRINT("only sockets to select on, using classic select");
+ if (tm < 0.0) {
+ tvp = (struct timeval *) NULL;
+ } else {
+ tv.tv_sec = (int) tm;
+ tv.tv_usec = (int) (1e6 * (tm - (int) tm));
+ tvp = &tv;
+ }
+ enter_blocking_section();
+ if (select(FD_SETSIZE, &read, &write, &except, tvp) == -1) {
+ err = WSAGetLastError();
+ DEBUG_PRINT("Error %ld occurred", err);
+ }
+ leave_blocking_section();
+ if (err) {
+ DEBUG_PRINT("Error %ld occurred", err);
+ win32_maperr(err);
+ uerror("select", Nothing);
+ }
+ read_list = fdset_to_fdlist(readfds, &read);
+ write_list = fdset_to_fdlist(writefds, &write);
+ except_list = fdset_to_fdlist(exceptfds, &except);
+ } else {
+ nEventsCount = 0;
+ nEventsMax = 0;
+ lpEventsDone = NULL;
+ lpSelectData = NULL;
+ iterSelectData = NULL;
+ iterResult = NULL;
+ hasStaticData = 0;
+ waitRet = 0;
+ readfds_len = caml_list_length(readfds);
+ writefds_len = caml_list_length(writefds);
+ exceptfds_len = caml_list_length(exceptfds);
+ hdsMax = MAX(readfds_len, MAX(writefds_len, exceptfds_len));
+
+ hdsData = (HANDLE *)caml_stat_alloc(sizeof(HANDLE) * hdsMax);
+
+ if (tm >= 0.0)
+ {
+ milliseconds = 1000 * tm;
+ DEBUG_PRINT("Will wait %d ms", milliseconds);
+ }
+ else
+ {
+ milliseconds = INFINITE;
+ }
+
+
+ /* Create list of select data, based on the different list of fd
+ to watch */
+ DEBUG_PRINT("Dispatch read fd");
+ handle_set_init(&hds, hdsData, hdsMax);
+ i=0;
+ for (l = readfds; l != Val_int(0); l = Field(l, 1))
+ {
+ fd = Field(l, 0);
+ if (!handle_set_mem(&hds, Handle_val(fd)))
+ {
+ handle_set_add(&hds, Handle_val(fd));
+ lpSelectData = select_data_dispatch(lpSelectData,
+ SELECT_MODE_READ, fd, i++);
+ }
+ else
+ {
+ DEBUG_PRINT("Discarding handle %x which is already monitor "
+ "for read", Handle_val(fd));
+ }
+ }
+ handle_set_reset(&hds);
+
+ DEBUG_PRINT("Dispatch write fd");
+ handle_set_init(&hds, hdsData, hdsMax);
+ i=0;
+ for (l = writefds; l != Val_int(0); l = Field(l, 1))
+ {
+ fd = Field(l, 0);
+ if (!handle_set_mem(&hds, Handle_val(fd)))
+ {
+ handle_set_add(&hds, Handle_val(fd));
+ lpSelectData = select_data_dispatch(lpSelectData,
+ SELECT_MODE_WRITE, fd, i++);
+ }
+ else
+ {
+ DEBUG_PRINT("Discarding handle %x which is already monitor "
+ "for write", Handle_val(fd));
+ }
+ }
+ handle_set_reset(&hds);
+
+ DEBUG_PRINT("Dispatch exceptional fd");
+ handle_set_init(&hds, hdsData, hdsMax);
+ i=0;
+ for (l = exceptfds; l != Val_int(0); l = Field(l, 1))
+ {
+ fd = Field(l, 0);
+ if (!handle_set_mem(&hds, Handle_val(fd)))
+ {
+ handle_set_add(&hds, Handle_val(fd));
+ lpSelectData = select_data_dispatch(lpSelectData,
+ SELECT_MODE_EXCEPT, fd, i++);
+ }
+ else
+ {
+ DEBUG_PRINT("Discarding handle %x which is already monitor "
+ "for exceptional", Handle_val(fd));
+ }
+ }
+ handle_set_reset(&hds);
+
+ /* Building the list of handle to wait for */
+ DEBUG_PRINT("Building events done array");
+ nEventsMax = list_length((LPLIST)lpSelectData);
+ nEventsCount = 0;
+ lpEventsDone = (HANDLE *)caml_stat_alloc(sizeof(HANDLE) * nEventsMax);
+
+ iterSelectData = lpSelectData;
+ while (iterSelectData != NULL)
+ {
+ /* Check if it is static data. If this is the case, launch everything
+ * but don't wait for events. It helps to test if there are events on
+ * any other fd (which are not static), knowing that there is at least
+ * one result (the static data).
+ */
+ if (iterSelectData->EType == SELECT_TYPE_STATIC)
+ {
+ hasStaticData = TRUE;
+ };
+
+ /* Execute APC */
+ if (iterSelectData->funcWorker != NULL)
+ {
+ iterSelectData->lpWorker =
+ worker_job_submit(
+ iterSelectData->funcWorker,
+ (void *)iterSelectData);
+ DEBUG_PRINT("Job submitted to worker %x",
+ iterSelectData->lpWorker);
+ lpEventsDone[nEventsCount]
+ = worker_job_event_done(iterSelectData->lpWorker);
+ nEventsCount++;
+ };
+ iterSelectData = LIST_NEXT(LPSELECTDATA, iterSelectData);
+ };
+
+ DEBUG_PRINT("Need to watch %d workers", nEventsCount);
+
+ /* Processing select itself */
+ enter_blocking_section();
+ /* There are worker started, waiting to be monitored */
+ if (nEventsCount > 0)
+ {
+ /* Waiting for event */
+ if (err == 0 && !hasStaticData)
+ {
+ DEBUG_PRINT("Waiting for one select worker to be done");
+ switch (WaitForMultipleObjects(nEventsCount, lpEventsDone, FALSE,
+ milliseconds))
+ {
+ case WAIT_FAILED:
+ err = GetLastError();
+ break;
+
+ case WAIT_TIMEOUT:
+ DEBUG_PRINT("Select timeout");
+ break;
+
+ default:
+ DEBUG_PRINT("One worker is done");
+ break;
+ };
+ }
+
+ /* Ordering stop to every worker */
+ DEBUG_PRINT("Sending stop signal to every select workers");
+ iterSelectData = lpSelectData;
+ while (iterSelectData != NULL)
+ {
+ if (iterSelectData->lpWorker != NULL)
+ {
+ worker_job_stop(iterSelectData->lpWorker);
+ };
+ iterSelectData = LIST_NEXT(LPSELECTDATA, iterSelectData);
+ };
+
+ DEBUG_PRINT("Waiting for every select worker to be done");
+ switch (WaitForMultipleObjects(nEventsCount, lpEventsDone, TRUE,
+ INFINITE))
+ {
+ case WAIT_FAILED:
+ err = GetLastError();
+ break;
+
+ default:
+ DEBUG_PRINT("Every worker is done");
+ break;
+ }
+ }
+ /* Nothing to monitor but some time to wait. */
+ else if (!hasStaticData)
+ {
+ Sleep(milliseconds);
+ }
+ leave_blocking_section();
+
+ DEBUG_PRINT("Error status: %d (0 is ok)", err);
+ /* Build results */
+ if (err == 0)
+ {
+ DEBUG_PRINT("Building result");
+ read_list = Val_unit;
+ write_list = Val_unit;
+ except_list = Val_unit;
+
+ iterSelectData = lpSelectData;
+ while (iterSelectData != NULL)
+ {
+ for (i = 0; i < iterSelectData->nResultsCount; i++)
+ {
+ iterResult = &(iterSelectData->aResults[i]);
+ l = alloc_small(2, 0);
+ Store_field(l, 0, find_handle(iterResult, readfds, writefds,
+ exceptfds));
+ switch (iterResult->EMode)
+ {
+ case SELECT_MODE_READ:
+ Store_field(l, 1, read_list);
+ read_list = l;
+ break;
+ case SELECT_MODE_WRITE:
+ Store_field(l, 1, write_list);
+ write_list = l;
+ break;
+ case SELECT_MODE_EXCEPT:
+ Store_field(l, 1, except_list);
+ except_list = l;
+ break;
+ }
+ }
+ /* We try to only process the first error, bypass other errors */
+ if (err == 0 && iterSelectData->EState == SELECT_STATE_ERROR)
+ {
+ err = iterSelectData->nError;
+ }
+ iterSelectData = LIST_NEXT(LPSELECTDATA, iterSelectData);
+ }
+ }
+
+ /* Free resources */
+ DEBUG_PRINT("Free selectdata resources");
+ iterSelectData = lpSelectData;
+ while (iterSelectData != NULL)
+ {
+ lpSelectData = iterSelectData;
+ iterSelectData = LIST_NEXT(LPSELECTDATA, iterSelectData);
+ select_data_free(lpSelectData);
+ }
+ lpSelectData = NULL;
+
+ /* Free allocated events/handle set array */
+ DEBUG_PRINT("Free local allocated resources");
+ caml_stat_free(lpEventsDone);
+ caml_stat_free(hdsData);
+
+ DEBUG_PRINT("Raise error if required");
+ if (err != 0)
+ {
+ win32_maperr(err);
+ uerror("select", Nothing);
+ }
+ }
+ }
+
+ DEBUG_PRINT("Build final result");
+ res = alloc_small(3, 0);
+ Store_field(res, 0, read_list);
+ Store_field(res, 1, write_list);
+ Store_field(res, 2, except_list);
+
+ DEBUG_PRINT("out select");
+
+ CAMLreturn(res);
+}
diff --git a/otherlibs/win32unix/sendrecv.c b/otherlibs/win32unix/sendrecv.c
new file mode 100644
index 0000000000..5957f6ed8f
--- /dev/null
+++ b/otherlibs/win32unix/sendrecv.c
@@ -0,0 +1,141 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include "socketaddr.h"
+
+static int msg_flag_table[] = {
+ MSG_OOB, MSG_DONTROUTE, MSG_PEEK
+};
+
+CAMLprim value unix_recv(value sock, value buff, value ofs, value len,
+ value flags)
+{
+ SOCKET s = Socket_val(sock);
+ int flg = convert_flag_list(flags, msg_flag_table);
+ int ret;
+ intnat numbytes;
+ char iobuf[UNIX_BUFFER_SIZE];
+ DWORD err = 0;
+
+ Begin_root (buff);
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ enter_blocking_section();
+ ret = recv(s, iobuf, (int) numbytes, flg);
+ if (ret == -1) err = WSAGetLastError();
+ leave_blocking_section();
+ if (ret == -1) {
+ win32_maperr(err);
+ uerror("recv", Nothing);
+ }
+ memmove (&Byte(buff, Long_val(ofs)), iobuf, ret);
+ End_roots();
+ return Val_int(ret);
+}
+
+CAMLprim value unix_recvfrom(value sock, value buff, value ofs, value len,
+ value flags)
+{
+ SOCKET s = Socket_val(sock);
+ int flg = convert_flag_list(flags, msg_flag_table);
+ int ret;
+ intnat numbytes;
+ char iobuf[UNIX_BUFFER_SIZE];
+ value res;
+ value adr = Val_unit;
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+ DWORD err = 0;
+
+ Begin_roots2 (buff, adr);
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ addr_len = sizeof(sock_addr);
+ enter_blocking_section();
+ ret = recvfrom(s, iobuf, (int) numbytes, flg, &addr.s_gen, &addr_len);
+ if (ret == -1) err = WSAGetLastError();
+ leave_blocking_section();
+ if (ret == -1) {
+ win32_maperr(err);
+ uerror("recvfrom", Nothing);
+ }
+ memmove (&Byte(buff, Long_val(ofs)), iobuf, ret);
+ adr = alloc_sockaddr(&addr, addr_len, -1);
+ res = alloc_small(2, 0);
+ Field(res, 0) = Val_int(ret);
+ Field(res, 1) = adr;
+ End_roots();
+ return res;
+}
+
+CAMLprim value unix_send(value sock, value buff, value ofs, value len,
+ value flags)
+{
+ SOCKET s = Socket_val(sock);
+ int flg = convert_flag_list(flags, msg_flag_table);
+ int ret;
+ intnat numbytes;
+ char iobuf[UNIX_BUFFER_SIZE];
+ DWORD err = 0;
+
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ memmove (iobuf, &Byte(buff, Long_val(ofs)), numbytes);
+ enter_blocking_section();
+ ret = send(s, iobuf, (int) numbytes, flg);
+ if (ret == -1) err = WSAGetLastError();
+ leave_blocking_section();
+ if (ret == -1) {
+ win32_maperr(err);
+ uerror("send", Nothing);
+ }
+ return Val_int(ret);
+}
+
+value unix_sendto_native(value sock, value buff, value ofs, value len,
+ value flags, value dest)
+{
+ SOCKET s = Socket_val(sock);
+ int flg = convert_flag_list(flags, msg_flag_table);
+ int ret;
+ intnat numbytes;
+ char iobuf[UNIX_BUFFER_SIZE];
+ union sock_addr_union addr;
+ socklen_param_type addr_len;
+ DWORD err = 0;
+
+ get_sockaddr(dest, &addr, &addr_len);
+ numbytes = Long_val(len);
+ if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE;
+ memmove (iobuf, &Byte(buff, Long_val(ofs)), numbytes);
+ enter_blocking_section();
+ ret = sendto(s, iobuf, (int) numbytes, flg, &addr.s_gen, addr_len);
+ if (ret == -1) err = WSAGetLastError();
+ leave_blocking_section();
+ if (ret == -1) {
+ win32_maperr(err);
+ uerror("sendto", Nothing);
+ }
+ return Val_int(ret);
+}
+
+CAMLprim value unix_sendto(value * argv, int argc)
+{
+ return unix_sendto_native
+ (argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
+}
diff --git a/otherlibs/win32unix/shutdown.c b/otherlibs/win32unix/shutdown.c
new file mode 100644
index 0000000000..9602311161
--- /dev/null
+++ b/otherlibs/win32unix/shutdown.c
@@ -0,0 +1,30 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+
+static int shutdown_command_table[] = {
+ 0, 1, 2
+};
+
+CAMLprim value unix_shutdown(sock, cmd)
+ value sock, cmd;
+{
+ if (shutdown(Socket_val(sock),
+ shutdown_command_table[Int_val(cmd)]) == -1) {
+ win32_maperr(WSAGetLastError());
+ uerror("shutdown", Nothing);
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/sleep.c b/otherlibs/win32unix/sleep.c
new file mode 100644
index 0000000000..6d630d2057
--- /dev/null
+++ b/otherlibs/win32unix/sleep.c
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_sleep(t)
+ value t;
+{
+ enter_blocking_section();
+ Sleep(Int_val(t) * 1000);
+ leave_blocking_section();
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/socket.c b/otherlibs/win32unix/socket.c
new file mode 100644
index 0000000000..9385e82e7e
--- /dev/null
+++ b/otherlibs/win32unix/socket.c
@@ -0,0 +1,67 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include "unixsupport.h"
+#include <mswsock.h> // for SO_OPENTYPE and SO_SYNCHRONOUS_NONALERT
+
+int socket_domain_table[] = {
+ PF_UNIX, PF_INET,
+#if defined(HAS_IPV6)
+ PF_INET6
+#else
+ 0
+#endif
+};
+
+int socket_type_table[] = {
+ SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET
+};
+
+CAMLprim value unix_socket(domain, type, proto)
+ value domain, type, proto;
+{
+ SOCKET s;
+ int oldvalue, oldvaluelen, newvalue, retcode;
+
+ #ifndef HAS_IPV6
+ /* IPv6 requires WinSock2, we must raise an error on PF_INET6 */
+ if (Int_val(domain) >= sizeof(socket_domain_table)/sizeof(int)) {
+ win32_maperr(WSAEPFNOSUPPORT);
+ uerror("socket", Nothing);
+ }
+ #endif
+
+ oldvaluelen = sizeof(oldvalue);
+ retcode = getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &oldvalue, &oldvaluelen);
+ if (retcode == 0) {
+ /* Set sockets to synchronous mode */
+ newvalue = SO_SYNCHRONOUS_NONALERT;
+ setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &newvalue, sizeof(newvalue));
+ }
+ s = socket(socket_domain_table[Int_val(domain)],
+ socket_type_table[Int_val(type)],
+ Int_val(proto));
+ if (retcode == 0) {
+ /* Restore initial mode */
+ setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
+ (char *) &oldvalue, oldvaluelen);
+ }
+ if (s == INVALID_SOCKET) {
+ win32_maperr(WSAGetLastError());
+ uerror("socket", Nothing);
+ }
+ return win_alloc_socket(s);
+}
diff --git a/otherlibs/win32unix/socketaddr.h b/otherlibs/win32unix/socketaddr.h
new file mode 100644
index 0000000000..f3b6caf0fd
--- /dev/null
+++ b/otherlibs/win32unix/socketaddr.h
@@ -0,0 +1,56 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_SOCKETADDR_H
+#define CAML_SOCKETADDR_H
+
+#include "caml/misc.h"
+
+union sock_addr_union {
+ struct sockaddr s_gen;
+ struct sockaddr_in s_inet;
+#ifdef HAS_IPV6
+ struct sockaddr_in6 s_inet6;
+#endif
+};
+
+extern union sock_addr_union sock_addr;
+
+#ifdef HAS_SOCKLEN_T
+typedef socklen_t socklen_param_type;
+#else
+typedef int socklen_param_type;
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern void get_sockaddr (value mladdr,
+ union sock_addr_union * addr /*out*/,
+ socklen_param_type * addr_len /*out*/);
+CAMLprim value alloc_sockaddr (union sock_addr_union * addr /*in*/,
+ socklen_param_type addr_len, int close_on_error);
+CAMLprim value alloc_inet_addr (struct in_addr * inaddr);
+#define GET_INET_ADDR(v) (*((struct in_addr *) (v)))
+
+#ifdef HAS_IPV6
+CAMLexport value alloc_inet6_addr (struct in6_addr * inaddr);
+#define GET_INET6_ADDR(v) (*((struct in6_addr *) (v)))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_SOCKETADDR_H */
diff --git a/otherlibs/win32unix/sockopt.c b/otherlibs/win32unix/sockopt.c
new file mode 100644
index 0000000000..aebc517a0d
--- /dev/null
+++ b/otherlibs/win32unix/sockopt.c
@@ -0,0 +1,227 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+#include "socketaddr.h"
+
+#ifndef IPPROTO_IPV6
+#define IPPROTO_IPV6 (-1)
+#endif
+#ifndef IPV6_V6ONLY
+#define IPV6_V6ONLY (-1)
+#endif
+
+enum option_type {
+ TYPE_BOOL = 0,
+ TYPE_INT = 1,
+ TYPE_LINGER = 2,
+ TYPE_TIMEVAL = 3,
+ TYPE_UNIX_ERROR = 4
+};
+
+struct socket_option {
+ int level;
+ int option;
+};
+
+/* Table of options, indexed by type */
+
+static struct socket_option sockopt_bool[] = {
+ { SOL_SOCKET, SO_DEBUG },
+ { SOL_SOCKET, SO_BROADCAST },
+ { SOL_SOCKET, SO_REUSEADDR },
+ { SOL_SOCKET, SO_KEEPALIVE },
+ { SOL_SOCKET, SO_DONTROUTE },
+ { SOL_SOCKET, SO_OOBINLINE },
+ { SOL_SOCKET, SO_ACCEPTCONN },
+ { IPPROTO_TCP, TCP_NODELAY },
+ { IPPROTO_IPV6, IPV6_V6ONLY}
+};
+
+static struct socket_option sockopt_int[] = {
+ { SOL_SOCKET, SO_SNDBUF },
+ { SOL_SOCKET, SO_RCVBUF },
+ { SOL_SOCKET, SO_ERROR },
+ { SOL_SOCKET, SO_TYPE },
+ { SOL_SOCKET, SO_RCVLOWAT },
+ { SOL_SOCKET, SO_SNDLOWAT } };
+
+static struct socket_option sockopt_linger[] = {
+ { SOL_SOCKET, SO_LINGER }
+};
+
+static struct socket_option sockopt_timeval[] = {
+ { SOL_SOCKET, SO_RCVTIMEO },
+ { SOL_SOCKET, SO_SNDTIMEO }
+};
+
+static struct socket_option sockopt_unix_error[] = {
+ { SOL_SOCKET, SO_ERROR }
+};
+
+static struct socket_option * sockopt_table[] = {
+ sockopt_bool,
+ sockopt_int,
+ sockopt_linger,
+ sockopt_timeval,
+ sockopt_unix_error
+};
+
+static char * getsockopt_fun_name[] = {
+ "getsockopt",
+ "getsockopt_int",
+ "getsockopt_optint",
+ "getsockopt_float",
+ "getsockopt_error"
+};
+
+static char * setsockopt_fun_name[] = {
+ "setsockopt",
+ "setsockopt_int",
+ "setsockopt_optint",
+ "setsockopt_float",
+ "setsockopt_error"
+};
+
+union option_value {
+ int i;
+ struct linger lg;
+ struct timeval tv;
+};
+
+CAMLexport value
+unix_getsockopt_aux(char * name,
+ enum option_type ty, int level, int option,
+ value socket)
+{
+ union option_value optval;
+ socklen_param_type optsize;
+
+
+ switch (ty) {
+ case TYPE_BOOL:
+ case TYPE_INT:
+ case TYPE_UNIX_ERROR:
+ optsize = sizeof(optval.i); break;
+ case TYPE_LINGER:
+ optsize = sizeof(optval.lg); break;
+ case TYPE_TIMEVAL:
+ optsize = sizeof(optval.tv); break;
+ default:
+ unix_error(EINVAL, name, Nothing);
+ }
+
+ if (getsockopt(Socket_val(socket), level, option,
+ (void *) &optval, &optsize) == -1)
+ uerror(name, Nothing);
+
+ switch (ty) {
+ case TYPE_BOOL:
+ case TYPE_INT:
+ return Val_int(optval.i);
+ case TYPE_LINGER:
+ if (optval.lg.l_onoff == 0) {
+ return Val_int(0); /* None */
+ } else {
+ value res = alloc_small(1, 0); /* Some */
+ Field(res, 0) = Val_int(optval.lg.l_linger);
+ return res;
+ }
+ case TYPE_TIMEVAL:
+ return copy_double((double) optval.tv.tv_sec
+ + (double) optval.tv.tv_usec / 1e6);
+ case TYPE_UNIX_ERROR:
+ if (optval.i == 0) {
+ return Val_int(0); /* None */
+ } else {
+ value err, res;
+ err = unix_error_of_code(optval.i);
+ Begin_root(err);
+ res = alloc_small(1, 0); /* Some */
+ Field(res, 0) = err;
+ End_roots();
+ return res;
+ }
+ default:
+ unix_error(EINVAL, name, Nothing);
+ return Val_unit; /* Avoid warning */
+ }
+}
+
+CAMLexport value
+unix_setsockopt_aux(char * name,
+ enum option_type ty, int level, int option,
+ value socket, value val)
+{
+ union option_value optval;
+ socklen_param_type optsize;
+ double f;
+
+ switch (ty) {
+ case TYPE_BOOL:
+ case TYPE_INT:
+ optsize = sizeof(optval.i);
+ optval.i = Int_val(val);
+ break;
+ case TYPE_LINGER:
+ optsize = sizeof(optval.lg);
+ optval.lg.l_onoff = Is_block (val);
+ if (optval.lg.l_onoff)
+ optval.lg.l_linger = Int_val (Field (val, 0));
+ break;
+ case TYPE_TIMEVAL:
+ f = Double_val(val);
+ optsize = sizeof(optval.tv);
+ optval.tv.tv_sec = (int) f;
+ optval.tv.tv_usec = (int) (1e6 * (f - optval.tv.tv_sec));
+ break;
+ case TYPE_UNIX_ERROR:
+ default:
+ unix_error(EINVAL, name, Nothing);
+ }
+
+ if (setsockopt(Socket_val(socket), level, option,
+ (void *) &optval, optsize) == -1)
+ uerror(name, Nothing);
+
+ return Val_unit;
+}
+
+CAMLprim value unix_getsockopt(value vty, value vsocket, value voption)
+{
+ enum option_type ty = Int_val(vty);
+ struct socket_option * opt = &(sockopt_table[ty][Int_val(voption)]);
+ return unix_getsockopt_aux(getsockopt_fun_name[ty],
+ ty,
+ opt->level,
+ opt->option,
+ vsocket);
+}
+
+CAMLprim value unix_setsockopt(value vty, value vsocket, value voption,
+ value val)
+{
+ enum option_type ty = Int_val(vty);
+ struct socket_option * opt = &(sockopt_table[ty][Int_val(voption)]);
+ return unix_setsockopt_aux(setsockopt_fun_name[ty],
+ ty,
+ opt->level,
+ opt->option,
+ vsocket,
+ val);
+}
diff --git a/otherlibs/win32unix/startup.c b/otherlibs/win32unix/startup.c
new file mode 100644
index 0000000000..be66c8a822
--- /dev/null
+++ b/otherlibs/win32unix/startup.c
@@ -0,0 +1,49 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <caml/mlvalues.h>
+#include "winworker.h"
+#include "windbug.h"
+
+value val_process_id;
+
+CAMLprim value win_startup(unit)
+ value unit;
+{
+ WSADATA wsaData;
+ int i;
+ HANDLE h;
+
+ (void) WSAStartup(MAKEWORD(2, 0), &wsaData);
+ DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(),
+ GetCurrentProcess(), &h, 0, TRUE,
+ DUPLICATE_SAME_ACCESS);
+ val_process_id = Val_int(h);
+
+ worker_init();
+
+ return Val_unit;
+}
+
+CAMLprim value win_cleanup(unit)
+ value unit;
+{
+ worker_cleanup();
+
+ (void) WSACleanup();
+
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/stat.c b/otherlibs/win32unix/stat.c
new file mode 100644
index 0000000000..46fc9841b1
--- /dev/null
+++ b/otherlibs/win32unix/stat.c
@@ -0,0 +1,109 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+#include "cst2constr.h"
+#define _INTEGRAL_MAX_BITS 64
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifndef S_IFLNK
+#define S_IFLNK 0
+#endif
+#ifndef S_IFIFO
+#define S_IFIFO 0
+#endif
+#ifndef S_IFSOCK
+#define S_IFSOCK 0
+#endif
+#ifndef S_IFBLK
+#define S_IFBLK 0
+#endif
+
+static int file_kind_table[] = {
+ S_IFREG, S_IFDIR, S_IFCHR, S_IFBLK, S_IFLNK, S_IFIFO, S_IFSOCK
+};
+
+static value stat_aux(int use_64, struct _stati64 *buf)
+{
+ CAMLparam0 ();
+ CAMLlocal1 (v);
+
+ v = caml_alloc (12, 0);
+ Store_field (v, 0, Val_int (buf->st_dev));
+ Store_field (v, 1, Val_int (buf->st_ino));
+ Store_field (v, 2, cst_to_constr (buf->st_mode & S_IFMT, file_kind_table,
+ sizeof(file_kind_table) / sizeof(int), 0));
+ Store_field (v, 3, Val_int(buf->st_mode & 07777));
+ Store_field (v, 4, Val_int (buf->st_nlink));
+ Store_field (v, 5, Val_int (buf->st_uid));
+ Store_field (v, 6, Val_int (buf->st_gid));
+ Store_field (v, 7, Val_int (buf->st_rdev));
+ Store_field (v, 8,
+ use_64 ? copy_int64(buf->st_size) : Val_int (buf->st_size));
+ Store_field (v, 9, copy_double((double) buf->st_atime));
+ Store_field (v, 10, copy_double((double) buf->st_mtime));
+ Store_field (v, 11, copy_double((double) buf->st_ctime));
+ CAMLreturn (v);
+}
+
+CAMLprim value unix_stat(value path)
+{
+ int ret;
+ struct _stati64 buf;
+
+ ret = _stati64(String_val(path), &buf);
+ if (ret == -1) uerror("stat", path);
+ if (buf.st_size > Max_long) {
+ win32_maperr(ERROR_ARITHMETIC_OVERFLOW);
+ uerror("stat", path);
+ }
+ return stat_aux(0, &buf);
+}
+
+CAMLprim value unix_stat_64(value path)
+{
+ int ret;
+ struct _stati64 buf;
+ ret = _stati64(String_val(path), &buf);
+ if (ret == -1) uerror("stat", path);
+ return stat_aux(1, &buf);
+}
+
+CAMLprim value unix_fstat(value handle)
+{
+ int ret;
+ struct _stati64 buf;
+
+ ret = _fstati64(win_CRT_fd_of_filedescr(handle), &buf);
+ if (ret == -1) uerror("fstat", Nothing);
+ if (buf.st_size > Max_long) {
+ win32_maperr(ERROR_ARITHMETIC_OVERFLOW);
+ uerror("fstat", Nothing);
+ }
+ return stat_aux(0, &buf);
+}
+
+CAMLprim value unix_fstat_64(value handle)
+{
+ int ret;
+ struct _stati64 buf;
+
+ ret = _fstati64(win_CRT_fd_of_filedescr(handle), &buf);
+ if (ret == -1) uerror("fstat", Nothing);
+ return stat_aux(1, &buf);
+}
diff --git a/otherlibs/win32unix/system.c b/otherlibs/win32unix/system.c
new file mode 100644
index 0000000000..202dcd0813
--- /dev/null
+++ b/otherlibs/win32unix/system.c
@@ -0,0 +1,42 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include <process.h>
+#include <stdio.h>
+
+CAMLprim value win_system(cmd)
+ value cmd;
+{
+ int ret;
+ value st;
+ char *buf;
+ intnat len;
+
+ len = caml_string_length (cmd);
+ buf = caml_stat_alloc (len + 1);
+ memmove (buf, String_val (cmd), len + 1);
+ enter_blocking_section();
+ _flushall();
+ ret = system(buf);
+ leave_blocking_section();
+ caml_stat_free(buf);
+ if (ret == -1) uerror("system", Nothing);
+ st = alloc_small(1, 0); /* Tag 0: Exited */
+ Field(st, 0) = Val_int(ret);
+ return st;
+}
diff --git a/otherlibs/win32unix/times.c b/otherlibs/win32unix/times.c
new file mode 100644
index 0000000000..e97d3a5c28
--- /dev/null
+++ b/otherlibs/win32unix/times.c
@@ -0,0 +1,48 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* File contributed by Josh Berdine */
+/* */
+/* Copyright 2011 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include "unixsupport.h"
+#include <windows.h>
+
+
+double to_sec(FILETIME ft) {
+ ULARGE_INTEGER tmp;
+
+ tmp.u.LowPart = ft.dwLowDateTime;
+ tmp.u.HighPart = ft.dwHighDateTime;
+
+ /* convert to seconds:
+ GetProcessTimes returns number of 100-nanosecond intervals */
+ return tmp.QuadPart / 1e7;
+}
+
+
+value unix_times(value unit) {
+ value res;
+ FILETIME creation, exit, stime, utime;
+
+ if (!(GetProcessTimes(GetCurrentProcess(), &creation, &exit, &stime,
+ &utime))) {
+ win32_maperr(GetLastError());
+ uerror("times", Nothing);
+ }
+
+ res = alloc_small(4 * Double_wosize, Double_array_tag);
+ Store_double_field(res, 0, to_sec(utime));
+ Store_double_field(res, 1, to_sec(stime));
+ Store_double_field(res, 2, 0);
+ Store_double_field(res, 3, 0);
+ return res;
+}
diff --git a/otherlibs/win32unix/unix.ml b/otherlibs/win32unix/unix.ml
new file mode 100644
index 0000000000..b74f063e83
--- /dev/null
+++ b/otherlibs/win32unix/unix.ml
@@ -0,0 +1,994 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Initialization *)
+
+external startup: unit -> unit = "win_startup"
+external cleanup: unit -> unit = "win_cleanup"
+
+let _ = startup(); at_exit cleanup
+
+(* Errors *)
+
+type error =
+ (* Errors defined in the POSIX standard *)
+ E2BIG (* Argument list too long *)
+ | EACCES (* Permission denied *)
+ | EAGAIN (* Resource temporarily unavailable; try again *)
+ | EBADF (* Bad file descriptor *)
+ | EBUSY (* Resource unavailable *)
+ | ECHILD (* No child process *)
+ | EDEADLK (* Resource deadlock would occur *)
+ | EDOM (* Domain error for math functions, etc. *)
+ | EEXIST (* File exists *)
+ | EFAULT (* Bad address *)
+ | EFBIG (* File too large *)
+ | EINTR (* Function interrupted by signal *)
+ | EINVAL (* Invalid argument *)
+ | EIO (* Hardware I/O error *)
+ | EISDIR (* Is a directory *)
+ | EMFILE (* Too many open files by the process *)
+ | EMLINK (* Too many links *)
+ | ENAMETOOLONG (* Filename too long *)
+ | ENFILE (* Too many open files in the system *)
+ | ENODEV (* No such device *)
+ | ENOENT (* No such file or directory *)
+ | ENOEXEC (* Not an executable file *)
+ | ENOLCK (* No locks available *)
+ | ENOMEM (* Not enough memory *)
+ | ENOSPC (* No space left on device *)
+ | ENOSYS (* Function not supported *)
+ | ENOTDIR (* Not a directory *)
+ | ENOTEMPTY (* Directory not empty *)
+ | ENOTTY (* Inappropriate I/O control operation *)
+ | ENXIO (* No such device or address *)
+ | EPERM (* Operation not permitted *)
+ | EPIPE (* Broken pipe *)
+ | ERANGE (* Result too large *)
+ | EROFS (* Read-only file system *)
+ | ESPIPE (* Invalid seek e.g. on a pipe *)
+ | ESRCH (* No such process *)
+ | EXDEV (* Invalid link *)
+ (* Additional errors, mostly BSD *)
+ | EWOULDBLOCK (* Operation would block *)
+ | EINPROGRESS (* Operation now in progress *)
+ | EALREADY (* Operation already in progress *)
+ | ENOTSOCK (* Socket operation on non-socket *)
+ | EDESTADDRREQ (* Destination address required *)
+ | EMSGSIZE (* Message too long *)
+ | EPROTOTYPE (* Protocol wrong type for socket *)
+ | ENOPROTOOPT (* Protocol not available *)
+ | EPROTONOSUPPORT (* Protocol not supported *)
+ | ESOCKTNOSUPPORT (* Socket type not supported *)
+ | EOPNOTSUPP (* Operation not supported on socket *)
+ | EPFNOSUPPORT (* Protocol family not supported *)
+ | EAFNOSUPPORT (* Address family not supported by protocol family *)
+ | EADDRINUSE (* Address already in use *)
+ | EADDRNOTAVAIL (* Can't assign requested address *)
+ | ENETDOWN (* Network is down *)
+ | ENETUNREACH (* Network is unreachable *)
+ | ENETRESET (* Network dropped connection on reset *)
+ | ECONNABORTED (* Software caused connection abort *)
+ | ECONNRESET (* Connection reset by peer *)
+ | ENOBUFS (* No buffer space available *)
+ | EISCONN (* Socket is already connected *)
+ | ENOTCONN (* Socket is not connected *)
+ | ESHUTDOWN (* Can't send after socket shutdown *)
+ | ETOOMANYREFS (* Too many references: can't splice *)
+ | ETIMEDOUT (* Connection timed out *)
+ | ECONNREFUSED (* Connection refused *)
+ | EHOSTDOWN (* Host is down *)
+ | EHOSTUNREACH (* No route to host *)
+ | ELOOP (* Too many levels of symbolic links *)
+ | EOVERFLOW
+ (* All other errors are mapped to EUNKNOWNERR *)
+ | EUNKNOWNERR of int (* Unknown error *)
+
+exception Unix_error of error * string * string
+
+let _ = Callback.register_exception "Unix.Unix_error"
+ (Unix_error(E2BIG, "", ""))
+
+external error_message : error -> string = "unix_error_message"
+
+let handle_unix_error f arg =
+ try
+ f arg
+ with Unix_error(err, fun_name, arg) ->
+ prerr_string Sys.argv.(0);
+ prerr_string ": \"";
+ prerr_string fun_name;
+ prerr_string "\" failed";
+ if String.length arg > 0 then begin
+ prerr_string " on \"";
+ prerr_string arg;
+ prerr_string "\""
+ end;
+ prerr_string ": ";
+ prerr_endline (error_message err);
+ exit 2
+
+external environment : unit -> string array = "unix_environment"
+external getenv: string -> string = "caml_sys_getenv"
+external putenv: string -> string -> unit = "unix_putenv"
+
+type process_status =
+ WEXITED of int
+ | WSIGNALED of int
+ | WSTOPPED of int
+
+type wait_flag =
+ WNOHANG
+ | WUNTRACED
+
+type file_descr
+
+external execv : string -> string array -> 'a = "unix_execv"
+external execve : string -> string array -> string array -> 'a = "unix_execve"
+external execvp : string -> string array -> 'a = "unix_execvp"
+external execvpe : string -> string array -> string array -> 'a = "unix_execvpe"
+
+external waitpid : wait_flag list -> int -> int * process_status
+ = "win_waitpid"
+external getpid : unit -> int = "unix_getpid"
+
+let fork () = invalid_arg "Unix.fork not implemented"
+let wait () = invalid_arg "Unix.wait not implemented"
+let getppid () = invalid_arg "Unix.getppid not implemented"
+let nice prio = invalid_arg "Unix.nice not implemented"
+
+(* Basic file input/output *)
+
+external filedescr_of_fd : int -> file_descr = "win_handle_fd"
+
+let stdin = filedescr_of_fd 0
+let stdout = filedescr_of_fd 1
+let stderr = filedescr_of_fd 2
+
+type open_flag =
+ O_RDONLY
+ | O_WRONLY
+ | O_RDWR
+ | O_NONBLOCK
+ | O_APPEND
+ | O_CREAT
+ | O_TRUNC
+ | O_EXCL
+ | O_NOCTTY
+ | O_DSYNC
+ | O_SYNC
+ | O_RSYNC
+ | O_SHARE_DELETE
+ | O_CLOEXEC
+
+type file_perm = int
+
+external openfile : string -> open_flag list -> file_perm -> file_descr
+ = "unix_open"
+external close : file_descr -> unit = "unix_close"
+external unsafe_read : file_descr -> bytes -> int -> int -> int
+ = "unix_read"
+external unsafe_write : file_descr -> bytes -> int -> int -> int
+ = "unix_write"
+external unsafe_single_write : file_descr -> bytes -> int -> int -> int
+ = "unix_single_write"
+
+let read fd buf ofs len =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.read"
+ else unsafe_read fd buf ofs len
+let write fd buf ofs len =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.write"
+ else unsafe_write fd buf ofs len
+let single_write fd buf ofs len =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.single_write"
+ else unsafe_single_write fd buf ofs len
+
+let write_substring fd buf ofs len =
+ write fd (Bytes.unsafe_of_string buf) ofs len
+
+let single_write_substring fd buf ofs len =
+ single_write fd (Bytes.unsafe_of_string buf) ofs len
+
+(* Interfacing with the standard input/output library *)
+
+external in_channel_of_descr: file_descr -> in_channel
+ = "win_inchannel_of_filedescr"
+external out_channel_of_descr: file_descr -> out_channel
+ = "win_outchannel_of_filedescr"
+external descr_of_in_channel : in_channel -> file_descr
+ = "win_filedescr_of_channel"
+external descr_of_out_channel : out_channel -> file_descr
+ = "win_filedescr_of_channel"
+
+(* Seeking and truncating *)
+
+type seek_command =
+ SEEK_SET
+ | SEEK_CUR
+ | SEEK_END
+
+external lseek : file_descr -> int -> seek_command -> int = "unix_lseek"
+
+let truncate name len = invalid_arg "Unix.truncate not implemented"
+let ftruncate fd len = invalid_arg "Unix.ftruncate not implemented"
+
+(* File statistics *)
+
+type file_kind =
+ S_REG
+ | S_DIR
+ | S_CHR
+ | S_BLK
+ | S_LNK
+ | S_FIFO
+ | S_SOCK
+
+type stats =
+ { st_dev : int;
+ st_ino : int;
+ st_kind : file_kind;
+ st_perm : file_perm;
+ st_nlink : int;
+ st_uid : int;
+ st_gid : int;
+ st_rdev : int;
+ st_size : int;
+ st_atime : float;
+ st_mtime : float;
+ st_ctime : float }
+
+external stat : string -> stats = "unix_stat"
+let lstat = stat
+external fstat : file_descr -> stats = "unix_fstat"
+let isatty fd =
+ match (fstat fd).st_kind with S_CHR -> true | _ -> false
+
+(* Operations on file names *)
+
+external unlink : string -> unit = "unix_unlink"
+external rename : string -> string -> unit = "unix_rename"
+external link : string -> string -> unit = "unix_link"
+
+(* Operations on large files *)
+
+module LargeFile =
+ struct
+ external lseek : file_descr -> int64 -> seek_command -> int64
+ = "unix_lseek_64"
+ let truncate name len =
+ invalid_arg "Unix.LargeFile.truncate not implemented"
+ let ftruncate name len =
+ invalid_arg "Unix.LargeFile.ftruncate not implemented"
+ type stats =
+ { st_dev : int;
+ st_ino : int;
+ st_kind : file_kind;
+ st_perm : file_perm;
+ st_nlink : int;
+ st_uid : int;
+ st_gid : int;
+ st_rdev : int;
+ st_size : int64;
+ st_atime : float;
+ st_mtime : float;
+ st_ctime : float;
+ }
+ external stat : string -> stats = "unix_stat_64"
+ let lstat = stat
+ external fstat : file_descr -> stats = "unix_fstat_64"
+ end
+
+(* File permissions and ownership *)
+
+type access_permission =
+ R_OK
+ | W_OK
+ | X_OK
+ | F_OK
+
+external chmod : string -> file_perm -> unit = "unix_chmod"
+let fchmod fd perm = invalid_arg "Unix.fchmod not implemented"
+let chown file perm = invalid_arg "Unix.chown not implemented"
+let fchown fd perm = invalid_arg "Unix.fchown not implemented"
+let umask msk = invalid_arg "Unix.umask not implemented"
+
+external access : string -> access_permission list -> unit = "unix_access"
+
+(* Operations on file descriptors *)
+
+external dup : file_descr -> file_descr = "unix_dup"
+external dup2 : file_descr -> file_descr -> unit = "unix_dup2"
+
+external set_nonblock : file_descr -> unit = "unix_set_nonblock"
+external clear_nonblock : file_descr -> unit = "unix_clear_nonblock"
+
+external set_close_on_exec : file_descr -> unit = "win_set_close_on_exec"
+external clear_close_on_exec : file_descr -> unit = "win_clear_close_on_exec"
+
+(* Directories *)
+
+external mkdir : string -> file_perm -> unit = "unix_mkdir"
+external rmdir : string -> unit = "unix_rmdir"
+external chdir : string -> unit = "unix_chdir"
+external getcwd : unit -> string = "unix_getcwd"
+let chroot _ = invalid_arg "Unix.chroot not implemented"
+
+type dir_entry =
+ Dir_empty
+ | Dir_read of string
+ | Dir_toread
+
+type dir_handle =
+ { dirname: string; mutable handle: int; mutable entry_read: dir_entry }
+
+external findfirst : string -> string * int = "win_findfirst"
+external findnext : int -> string= "win_findnext"
+
+let opendir dirname =
+ try
+ let (first_entry, handle) = findfirst (Filename.concat dirname "*.*") in
+ { dirname = dirname; handle = handle; entry_read = Dir_read first_entry }
+ with End_of_file ->
+ { dirname = dirname; handle = 0; entry_read = Dir_empty }
+
+let readdir d =
+ match d.entry_read with
+ Dir_empty -> raise End_of_file
+ | Dir_read name -> d.entry_read <- Dir_toread; name
+ | Dir_toread -> findnext d.handle
+
+external win_findclose : int -> unit = "win_findclose"
+
+let closedir d =
+ match d.entry_read with
+ Dir_empty -> ()
+ | _ -> win_findclose d.handle
+
+let rewinddir d =
+ closedir d;
+ try
+ let (first_entry, handle) = findfirst (d.dirname ^ "\\*.*") in
+ d.handle <- handle; d.entry_read <- Dir_read first_entry
+ with End_of_file ->
+ d.handle <- 0; d.entry_read <- Dir_empty
+
+(* Pipes *)
+
+external pipe : unit -> file_descr * file_descr = "unix_pipe"
+
+let mkfifo name perm = invalid_arg "Unix.mkfifo not implemented"
+
+(* Symbolic links *)
+
+let readlink path = invalid_arg "Unix.readlink not implemented"
+let symlink path1 path2 = invalid_arg "Unix.symlink not implemented"
+
+(* Locking *)
+
+type lock_command =
+ F_ULOCK
+ | F_LOCK
+ | F_TLOCK
+ | F_TEST
+ | F_RLOCK
+ | F_TRLOCK
+
+external lockf : file_descr -> lock_command -> int -> unit = "unix_lockf"
+
+external terminate_process: int -> bool = "win_terminate_process"
+
+let kill pid signo =
+ if signo <> Sys.sigkill then
+ invalid_arg "Unix.kill"
+ else
+ if not (terminate_process pid) then
+ raise(Unix_error(ESRCH, "kill", ""))
+ (* could be more precise *)
+
+type sigprocmask_command = SIG_SETMASK | SIG_BLOCK | SIG_UNBLOCK
+let sigprocmask cmd sigs = invalid_arg "Unix.sigprocmask not implemented"
+let sigpending () = invalid_arg "Unix.sigpending not implemented"
+let sigsuspend sigs = invalid_arg "Unix.sigsuspend not implemented"
+let pause () = invalid_arg "Unix.pause not implemented"
+
+(* Time functions *)
+
+type process_times =
+ { tms_utime : float;
+ tms_stime : float;
+ tms_cutime : float;
+ tms_cstime : float }
+
+type tm =
+ { tm_sec : int;
+ tm_min : int;
+ tm_hour : int;
+ tm_mday : int;
+ tm_mon : int;
+ tm_year : int;
+ tm_wday : int;
+ tm_yday : int;
+ tm_isdst : bool }
+
+external time : unit -> float = "unix_time"
+external gettimeofday : unit -> float = "unix_gettimeofday"
+external gmtime : float -> tm = "unix_gmtime"
+external localtime : float -> tm = "unix_localtime"
+external mktime : tm -> float * tm = "unix_mktime"
+let alarm n = invalid_arg "Unix.alarm not implemented"
+external sleep : int -> unit = "unix_sleep"
+external times: unit -> process_times = "unix_times"
+external utimes : string -> float -> float -> unit = "unix_utimes"
+
+type interval_timer =
+ ITIMER_REAL
+ | ITIMER_VIRTUAL
+ | ITIMER_PROF
+
+type interval_timer_status =
+ { it_interval: float;
+ it_value: float }
+
+let getitimer it = invalid_arg "Unix.getitimer not implemented"
+let setitimer it tm = invalid_arg "Unix.setitimer not implemented"
+
+(* User id, group id *)
+
+let getuid () = 1
+let geteuid = getuid
+let setuid id = invalid_arg "Unix.setuid not implemented"
+
+let getgid () = 1
+let getegid = getgid
+let setgid id = invalid_arg "Unix.setgid not implemented"
+
+let getgroups () = [|1|]
+let setgroups _ = invalid_arg "Unix.setgroups not implemented"
+let initgroups _ _ = invalid_arg "Unix.initgroups not implemented"
+
+type passwd_entry =
+ { pw_name : string;
+ pw_passwd : string;
+ pw_uid : int;
+ pw_gid : int;
+ pw_gecos : string;
+ pw_dir : string;
+ pw_shell : string }
+
+type group_entry =
+ { gr_name : string;
+ gr_passwd : string;
+ gr_gid : int;
+ gr_mem : string array }
+
+let getlogin () = try Sys.getenv "USERNAME" with Not_found -> ""
+let getpwnam x = raise Not_found
+let getgrnam = getpwnam
+let getpwuid = getpwnam
+let getgrgid = getpwnam
+
+(* Internet addresses *)
+
+type inet_addr = string
+
+let is_inet6_addr s = String.length s = 16
+
+external inet_addr_of_string : string -> inet_addr
+ = "unix_inet_addr_of_string"
+external string_of_inet_addr : inet_addr -> string
+ = "unix_string_of_inet_addr"
+
+let inet_addr_any = inet_addr_of_string "0.0.0.0"
+let inet_addr_loopback = inet_addr_of_string "127.0.0.1"
+let inet6_addr_any =
+ try inet_addr_of_string "::" with Failure _ -> inet_addr_any
+let inet6_addr_loopback =
+ try inet_addr_of_string "::1" with Failure _ -> inet_addr_loopback
+
+(* Sockets *)
+
+type socket_domain =
+ PF_UNIX
+ | PF_INET
+ | PF_INET6
+
+type socket_type =
+ SOCK_STREAM
+ | SOCK_DGRAM
+ | SOCK_RAW
+ | SOCK_SEQPACKET
+
+type sockaddr =
+ ADDR_UNIX of string
+ | ADDR_INET of inet_addr * int
+
+let domain_of_sockaddr = function
+ ADDR_UNIX _ -> PF_UNIX
+ | ADDR_INET(a, _) -> if is_inet6_addr a then PF_INET6 else PF_INET
+
+type shutdown_command =
+ SHUTDOWN_RECEIVE
+ | SHUTDOWN_SEND
+ | SHUTDOWN_ALL
+
+type msg_flag =
+ MSG_OOB
+ | MSG_DONTROUTE
+ | MSG_PEEK
+
+external socket : socket_domain -> socket_type -> int -> file_descr
+ = "unix_socket"
+let socketpair dom ty proto = invalid_arg "Unix.socketpair not implemented"
+external accept : file_descr -> file_descr * sockaddr = "unix_accept"
+external bind : file_descr -> sockaddr -> unit = "unix_bind"
+external connect : file_descr -> sockaddr -> unit = "unix_connect"
+external listen : file_descr -> int -> unit = "unix_listen"
+external shutdown : file_descr -> shutdown_command -> unit = "unix_shutdown"
+external getsockname : file_descr -> sockaddr = "unix_getsockname"
+external getpeername : file_descr -> sockaddr = "unix_getpeername"
+
+external unsafe_recv :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int
+ = "unix_recv"
+external unsafe_recvfrom :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int * sockaddr
+ = "unix_recvfrom"
+external unsafe_send :
+ file_descr -> bytes -> int -> int -> msg_flag list -> int
+ = "unix_send"
+external unsafe_sendto :
+ file_descr -> bytes -> int -> int -> msg_flag list -> sockaddr -> int
+ = "unix_sendto" "unix_sendto_native"
+
+let recv fd buf ofs len flags =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.recv"
+ else unsafe_recv fd buf ofs len flags
+let recvfrom fd buf ofs len flags =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.recvfrom"
+ else unsafe_recvfrom fd buf ofs len flags
+let send fd buf ofs len flags =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.send"
+ else unsafe_send fd buf ofs len flags
+let sendto fd buf ofs len flags addr =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
+ then invalid_arg "Unix.sendto"
+ else unsafe_sendto fd buf ofs len flags addr
+
+let send_substring fd buf ofs len flags =
+ send fd (Bytes.unsafe_of_string buf) ofs len flags
+
+let sendto_substring fd buf ofs len flags addr =
+ sendto fd (Bytes.unsafe_of_string buf) ofs len flags addr
+
+type socket_bool_option =
+ SO_DEBUG
+ | SO_BROADCAST
+ | SO_REUSEADDR
+ | SO_KEEPALIVE
+ | SO_DONTROUTE
+ | SO_OOBINLINE
+ | SO_ACCEPTCONN
+ | TCP_NODELAY
+ | IPV6_ONLY
+
+type socket_int_option =
+ SO_SNDBUF
+ | SO_RCVBUF
+ | SO_ERROR
+ | SO_TYPE
+ | SO_RCVLOWAT
+ | SO_SNDLOWAT
+
+type socket_optint_option = SO_LINGER
+
+type socket_float_option =
+ SO_RCVTIMEO
+ | SO_SNDTIMEO
+
+type socket_error_option = SO_ERROR
+
+module SO: sig
+ type ('opt, 'v) t
+ val bool: (socket_bool_option, bool) t
+ val int: (socket_int_option, int) t
+ val optint: (socket_optint_option, int option) t
+ val float: (socket_float_option, float) t
+ val error: (socket_error_option, error option) t
+ val get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
+ val set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
+end = struct
+ type ('opt, 'v) t = int
+ let bool = 0
+ let int = 1
+ let optint = 2
+ let float = 3
+ let error = 4
+ external get: ('opt, 'v) t -> file_descr -> 'opt -> 'v
+ = "unix_getsockopt"
+ external set: ('opt, 'v) t -> file_descr -> 'opt -> 'v -> unit
+ = "unix_setsockopt"
+end
+
+let getsockopt fd opt = SO.get SO.bool fd opt
+let setsockopt fd opt v = SO.set SO.bool fd opt v
+
+let getsockopt_int fd opt = SO.get SO.int fd opt
+let setsockopt_int fd opt v = SO.set SO.int fd opt v
+
+let getsockopt_optint fd opt = SO.get SO.optint fd opt
+let setsockopt_optint fd opt v = SO.set SO.optint fd opt v
+
+let getsockopt_float fd opt = SO.get SO.float fd opt
+let setsockopt_float fd opt v = SO.set SO.float fd opt v
+
+let getsockopt_error fd = SO.get SO.error fd SO_ERROR
+
+(* Host and protocol databases *)
+
+type host_entry =
+ { h_name : string;
+ h_aliases : string array;
+ h_addrtype : socket_domain;
+ h_addr_list : inet_addr array }
+
+type protocol_entry =
+ { p_name : string;
+ p_aliases : string array;
+ p_proto : int }
+
+type service_entry =
+ { s_name : string;
+ s_aliases : string array;
+ s_port : int;
+ s_proto : string }
+
+external gethostname : unit -> string = "unix_gethostname"
+external gethostbyname : string -> host_entry = "unix_gethostbyname"
+external gethostbyaddr : inet_addr -> host_entry = "unix_gethostbyaddr"
+external getprotobyname : string -> protocol_entry
+ = "unix_getprotobyname"
+external getprotobynumber : int -> protocol_entry
+ = "unix_getprotobynumber"
+
+external getservbyname : string -> string -> service_entry
+ = "unix_getservbyname"
+external getservbyport : int -> string -> service_entry
+ = "unix_getservbyport"
+
+type addr_info =
+ { ai_family : socket_domain;
+ ai_socktype : socket_type;
+ ai_protocol : int;
+ ai_addr : sockaddr;
+ ai_canonname : string }
+
+type getaddrinfo_option =
+ AI_FAMILY of socket_domain
+ | AI_SOCKTYPE of socket_type
+ | AI_PROTOCOL of int
+ | AI_NUMERICHOST
+ | AI_CANONNAME
+ | AI_PASSIVE
+
+external getaddrinfo_system
+ : string -> string -> getaddrinfo_option list -> addr_info list
+ = "unix_getaddrinfo"
+
+let getaddrinfo_emulation node service opts =
+ (* Parse options *)
+ let opt_socktype = ref None
+ and opt_protocol = ref 0
+ and opt_passive = ref false in
+ List.iter
+ (function AI_SOCKTYPE s -> opt_socktype := Some s
+ | AI_PROTOCOL p -> opt_protocol := p
+ | AI_PASSIVE -> opt_passive := true
+ | _ -> ())
+ opts;
+ (* Determine socket types and port numbers *)
+ let get_port ty kind =
+ if service = "" then [ty, 0] else
+ try
+ [ty, int_of_string service]
+ with Failure _ ->
+ try
+ [ty, (getservbyname service kind).s_port]
+ with Not_found -> []
+ in
+ let ports =
+ match !opt_socktype with
+ | None ->
+ get_port SOCK_STREAM "tcp" @ get_port SOCK_DGRAM "udp"
+ | Some SOCK_STREAM ->
+ get_port SOCK_STREAM "tcp"
+ | Some SOCK_DGRAM ->
+ get_port SOCK_DGRAM "udp"
+ | Some ty ->
+ if service = "" then [ty, 0] else [] in
+ (* Determine IP addresses *)
+ let addresses =
+ if node = "" then
+ if List.mem AI_PASSIVE opts
+ then [inet_addr_any, "0.0.0.0"]
+ else [inet_addr_loopback, "127.0.0.1"]
+ else
+ try
+ [inet_addr_of_string node, node]
+ with Failure _ ->
+ try
+ let he = gethostbyname node in
+ List.map
+ (fun a -> (a, he.h_name))
+ (Array.to_list he.h_addr_list)
+ with Not_found ->
+ [] in
+ (* Cross-product of addresses and ports *)
+ List.flatten
+ (List.map
+ (fun (ty, port) ->
+ List.map
+ (fun (addr, name) ->
+ { ai_family = PF_INET;
+ ai_socktype = ty;
+ ai_protocol = !opt_protocol;
+ ai_addr = ADDR_INET(addr, port);
+ ai_canonname = name })
+ addresses)
+ ports)
+
+let getaddrinfo node service opts =
+ try
+ List.rev(getaddrinfo_system node service opts)
+ with Invalid_argument _ ->
+ getaddrinfo_emulation node service opts
+
+type name_info =
+ { ni_hostname : string;
+ ni_service : string }
+
+type getnameinfo_option =
+ NI_NOFQDN
+ | NI_NUMERICHOST
+ | NI_NAMEREQD
+ | NI_NUMERICSERV
+ | NI_DGRAM
+
+external getnameinfo_system
+ : sockaddr -> getnameinfo_option list -> name_info
+ = "unix_getnameinfo"
+
+let getnameinfo_emulation addr opts =
+ match addr with
+ | ADDR_UNIX f ->
+ { ni_hostname = ""; ni_service = f } (* why not? *)
+ | ADDR_INET(a, p) ->
+ let hostname =
+ try
+ if List.mem NI_NUMERICHOST opts then raise Not_found;
+ (gethostbyaddr a).h_name
+ with Not_found ->
+ if List.mem NI_NAMEREQD opts then raise Not_found;
+ string_of_inet_addr a in
+ let service =
+ try
+ if List.mem NI_NUMERICSERV opts then raise Not_found;
+ let kind = if List.mem NI_DGRAM opts then "udp" else "tcp" in
+ (getservbyport p kind).s_name
+ with Not_found ->
+ string_of_int p in
+ { ni_hostname = hostname; ni_service = service }
+
+let getnameinfo addr opts =
+ try
+ getnameinfo_system addr opts
+ with Invalid_argument _ ->
+ getnameinfo_emulation addr opts
+
+(* High-level process management (system, popen) *)
+
+external win_create_process : string -> string -> string option ->
+ file_descr -> file_descr -> file_descr -> int
+ = "win_create_process" "win_create_process_native"
+
+let make_cmdline args =
+ let maybe_quote f =
+ if String.contains f ' ' || String.contains f '\"' || f = ""
+ then Filename.quote f
+ else f in
+ String.concat " " (List.map maybe_quote (Array.to_list args))
+
+let create_process prog args fd1 fd2 fd3 =
+ win_create_process prog (make_cmdline args) None fd1 fd2 fd3
+
+let create_process_env prog args env fd1 fd2 fd3 =
+ win_create_process prog (make_cmdline args)
+ (Some(String.concat "\000" (Array.to_list env) ^ "\000"))
+ fd1 fd2 fd3
+
+external system: string -> process_status = "win_system"
+
+type popen_process =
+ Process of in_channel * out_channel
+ | Process_in of in_channel
+ | Process_out of out_channel
+ | Process_full of in_channel * out_channel * in_channel
+
+let popen_processes = (Hashtbl.create 7 : (popen_process, int) Hashtbl.t)
+
+let open_proc cmd optenv proc input output error =
+ let shell =
+ try Sys.getenv "COMSPEC"
+ with Not_found -> raise(Unix_error(ENOEXEC, "open_proc", cmd)) in
+ let pid =
+ win_create_process shell (shell ^ " /c " ^ cmd) optenv
+ input output error in
+ Hashtbl.add popen_processes proc pid
+
+let open_process_in cmd =
+ let (in_read, in_write) = pipe() in
+ set_close_on_exec in_read;
+ let inchan = in_channel_of_descr in_read in
+ open_proc cmd None (Process_in inchan) stdin in_write stderr;
+ close in_write;
+ inchan
+
+let open_process_out cmd =
+ let (out_read, out_write) = pipe() in
+ set_close_on_exec out_write;
+ let outchan = out_channel_of_descr out_write in
+ open_proc cmd None (Process_out outchan) out_read stdout stderr;
+ close out_read;
+ outchan
+
+let open_process cmd =
+ let (in_read, in_write) = pipe() in
+ let (out_read, out_write) = pipe() in
+ set_close_on_exec in_read;
+ set_close_on_exec out_write;
+ let inchan = in_channel_of_descr in_read in
+ let outchan = out_channel_of_descr out_write in
+ open_proc cmd None (Process(inchan, outchan)) out_read in_write stderr;
+ close out_read; close in_write;
+ (inchan, outchan)
+
+let open_process_full cmd env =
+ let (in_read, in_write) = pipe() in
+ let (out_read, out_write) = pipe() in
+ let (err_read, err_write) = pipe() in
+ set_close_on_exec in_read;
+ set_close_on_exec out_write;
+ set_close_on_exec err_read;
+ let inchan = in_channel_of_descr in_read in
+ let outchan = out_channel_of_descr out_write in
+ let errchan = in_channel_of_descr err_read in
+ open_proc cmd (Some(String.concat "\000" (Array.to_list env) ^ "\000"))
+ (Process_full(inchan, outchan, errchan))
+ out_read in_write err_write;
+ close out_read; close in_write; close err_write;
+ (inchan, outchan, errchan)
+
+let find_proc_id fun_name proc =
+ try
+ let pid = Hashtbl.find popen_processes proc in
+ Hashtbl.remove popen_processes proc;
+ pid
+ with Not_found ->
+ raise(Unix_error(EBADF, fun_name, ""))
+
+let close_process_in inchan =
+ let pid = find_proc_id "close_process_in" (Process_in inchan) in
+ close_in inchan;
+ snd(waitpid [] pid)
+
+let close_process_out outchan =
+ let pid = find_proc_id "close_process_out" (Process_out outchan) in
+ close_out outchan;
+ snd(waitpid [] pid)
+
+let close_process (inchan, outchan) =
+ let pid = find_proc_id "close_process" (Process(inchan, outchan)) in
+ close_in inchan; close_out outchan;
+ snd(waitpid [] pid)
+
+let close_process_full (inchan, outchan, errchan) =
+ let pid =
+ find_proc_id "close_process_full"
+ (Process_full(inchan, outchan, errchan)) in
+ close_in inchan; close_out outchan; close_in errchan;
+ snd(waitpid [] pid)
+
+(* Polling *)
+
+external select :
+ file_descr list -> file_descr list -> file_descr list -> float ->
+ file_descr list * file_descr list * file_descr list = "unix_select"
+
+(* High-level network functions *)
+
+let open_connection sockaddr =
+ let sock =
+ socket (domain_of_sockaddr sockaddr) SOCK_STREAM 0 in
+ try
+ connect sock sockaddr;
+ set_close_on_exec sock;
+ (in_channel_of_descr sock, out_channel_of_descr sock)
+ with exn ->
+ close sock; raise exn
+
+let shutdown_connection inchan =
+ shutdown (descr_of_in_channel inchan) SHUTDOWN_SEND
+
+let establish_server server_fun sockaddr =
+ invalid_arg "Unix.establish_server not implemented"
+
+(* Terminal interface *)
+
+type terminal_io = {
+ mutable c_ignbrk: bool;
+ mutable c_brkint: bool;
+ mutable c_ignpar: bool;
+ mutable c_parmrk: bool;
+ mutable c_inpck: bool;
+ mutable c_istrip: bool;
+ mutable c_inlcr: bool;
+ mutable c_igncr: bool;
+ mutable c_icrnl: bool;
+ mutable c_ixon: bool;
+ mutable c_ixoff: bool;
+ mutable c_opost: bool;
+ mutable c_obaud: int;
+ mutable c_ibaud: int;
+ mutable c_csize: int;
+ mutable c_cstopb: int;
+ mutable c_cread: bool;
+ mutable c_parenb: bool;
+ mutable c_parodd: bool;
+ mutable c_hupcl: bool;
+ mutable c_clocal: bool;
+ mutable c_isig: bool;
+ mutable c_icanon: bool;
+ mutable c_noflsh: bool;
+ mutable c_echo: bool;
+ mutable c_echoe: bool;
+ mutable c_echok: bool;
+ mutable c_echonl: bool;
+ mutable c_vintr: char;
+ mutable c_vquit: char;
+ mutable c_verase: char;
+ mutable c_vkill: char;
+ mutable c_veof: char;
+ mutable c_veol: char;
+ mutable c_vmin: int;
+ mutable c_vtime: int;
+ mutable c_vstart: char;
+ mutable c_vstop: char
+ }
+
+type setattr_when = TCSANOW | TCSADRAIN | TCSAFLUSH
+
+let tcgetattr fd = invalid_arg "Unix.tcgetattr not implemented"
+let tcsetattr fd wh = invalid_arg "Unix.tcsetattr not implemented"
+let tcsendbreak fd n = invalid_arg "Unix.tcsendbreak not implemented"
+let tcdrain fd = invalid_arg "Unix.tcdrain not implemented"
+
+type flush_queue = TCIFLUSH | TCOFLUSH | TCIOFLUSH
+let tcflush fd q = invalid_arg "Unix.tcflush not implemented"
+type flow_action = TCOOFF | TCOON | TCIOFF | TCION
+let tcflow fd fl = invalid_arg "Unix.tcflow not implemented"
+let setsid () = invalid_arg "Unix.setsid not implemented"
diff --git a/otherlibs/win32unix/unixsupport.c b/otherlibs/win32unix/unixsupport.c
new file mode 100644
index 0000000000..85f220c329
--- /dev/null
+++ b/otherlibs/win32unix/unixsupport.c
@@ -0,0 +1,311 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <stddef.h>
+#include <caml/mlvalues.h>
+#include <caml/callback.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/fail.h>
+#include <caml/custom.h>
+#include "unixsupport.h"
+#include "cst2constr.h"
+#include <errno.h>
+
+/* Heap-allocation of Windows file handles */
+
+static int win_handle_compare(value v1, value v2)
+{
+ HANDLE h1 = Handle_val(v1);
+ HANDLE h2 = Handle_val(v2);
+ return h1 == h2 ? 0 : h1 < h2 ? -1 : 1;
+}
+
+static intnat win_handle_hash(value v)
+{
+ return (intnat) Handle_val(v);
+}
+
+static struct custom_operations win_handle_ops = {
+ "_handle",
+ custom_finalize_default,
+ win_handle_compare,
+ win_handle_hash,
+ custom_serialize_default,
+ custom_deserialize_default,
+ custom_compare_ext_default
+};
+
+value win_alloc_handle(HANDLE h)
+{
+ value res = alloc_custom(&win_handle_ops, sizeof(struct filedescr), 0, 1);
+ Handle_val(res) = h;
+ Descr_kind_val(res) = KIND_HANDLE;
+ CRT_fd_val(res) = NO_CRT_FD;
+ Flags_fd_val(res) = FLAGS_FD_IS_BLOCKING;
+ return res;
+}
+
+value win_alloc_socket(SOCKET s)
+{
+ value res = alloc_custom(&win_handle_ops, sizeof(struct filedescr), 0, 1);
+ Socket_val(res) = s;
+ Descr_kind_val(res) = KIND_SOCKET;
+ CRT_fd_val(res) = NO_CRT_FD;
+ Flags_fd_val(res) = FLAGS_FD_IS_BLOCKING;
+ return res;
+}
+
+#if 0
+/* PR#4750: this function is no longer used */
+value win_alloc_handle_or_socket(HANDLE h)
+{
+ value res = win_alloc_handle(h);
+ int opt;
+ int optlen = sizeof(opt);
+ if (getsockopt((SOCKET) h, SOL_SOCKET, SO_TYPE, (char *)&opt, &optlen) == 0)
+ Descr_kind_val(res) = KIND_SOCKET;
+ return res;
+}
+#endif
+
+/* Mapping of Windows error codes to POSIX error codes */
+
+struct error_entry { DWORD win_code; int range; int posix_code; };
+
+static struct error_entry win_error_table[] = {
+ { ERROR_INVALID_FUNCTION, 0, EINVAL},
+ { ERROR_FILE_NOT_FOUND, 0, ENOENT},
+ { ERROR_PATH_NOT_FOUND, 0, ENOENT},
+ { ERROR_TOO_MANY_OPEN_FILES, 0, EMFILE},
+ { ERROR_ACCESS_DENIED, 0, EACCES},
+ { ERROR_INVALID_HANDLE, 0, EBADF},
+ { ERROR_ARENA_TRASHED, 0, ENOMEM},
+ { ERROR_NOT_ENOUGH_MEMORY, 0, ENOMEM},
+ { ERROR_INVALID_BLOCK, 0, ENOMEM},
+ { ERROR_BAD_ENVIRONMENT, 0, E2BIG},
+ { ERROR_BAD_FORMAT, 0, ENOEXEC},
+ { ERROR_INVALID_ACCESS, 0, EINVAL},
+ { ERROR_INVALID_DATA, 0, EINVAL},
+ { ERROR_INVALID_DRIVE, 0, ENOENT},
+ { ERROR_CURRENT_DIRECTORY, 0, EACCES},
+ { ERROR_NOT_SAME_DEVICE, 0, EXDEV},
+ { ERROR_NO_MORE_FILES, 0, ENOENT},
+ { ERROR_LOCK_VIOLATION, 0, EACCES},
+ { ERROR_BAD_NETPATH, 0, ENOENT},
+ { ERROR_NETWORK_ACCESS_DENIED, 0, EACCES},
+ { ERROR_BAD_NET_NAME, 0, ENOENT},
+ { ERROR_FILE_EXISTS, 0, EEXIST},
+ { ERROR_CANNOT_MAKE, 0, EACCES},
+ { ERROR_FAIL_I24, 0, EACCES},
+ { ERROR_INVALID_PARAMETER, 0, EINVAL},
+ { ERROR_NO_PROC_SLOTS, 0, EAGAIN},
+ { ERROR_DRIVE_LOCKED, 0, EACCES},
+ { ERROR_BROKEN_PIPE, 0, EPIPE},
+ { ERROR_NO_DATA, 0, EPIPE},
+ { ERROR_DISK_FULL, 0, ENOSPC},
+ { ERROR_INVALID_TARGET_HANDLE, 0, EBADF},
+ { ERROR_INVALID_HANDLE, 0, EINVAL},
+ { ERROR_WAIT_NO_CHILDREN, 0, ECHILD},
+ { ERROR_CHILD_NOT_COMPLETE, 0, ECHILD},
+ { ERROR_DIRECT_ACCESS_HANDLE, 0, EBADF},
+ { ERROR_NEGATIVE_SEEK, 0, EINVAL},
+ { ERROR_SEEK_ON_DEVICE, 0, EACCES},
+ { ERROR_DIR_NOT_EMPTY, 0, ENOTEMPTY},
+ { ERROR_NOT_LOCKED, 0, EACCES},
+ { ERROR_BAD_PATHNAME, 0, ENOENT},
+ { ERROR_MAX_THRDS_REACHED, 0, EAGAIN},
+ { ERROR_LOCK_FAILED, 0, EACCES},
+ { ERROR_ALREADY_EXISTS, 0, EEXIST},
+ { ERROR_FILENAME_EXCED_RANGE, 0, ENOENT},
+ { ERROR_NESTING_NOT_ALLOWED, 0, EAGAIN},
+ { ERROR_NOT_ENOUGH_QUOTA, 0, ENOMEM},
+ { ERROR_INVALID_STARTING_CODESEG,
+ ERROR_INFLOOP_IN_RELOC_CHAIN - ERROR_INVALID_STARTING_CODESEG,
+ ENOEXEC },
+ { ERROR_WRITE_PROTECT,
+ ERROR_SHARING_BUFFER_EXCEEDED - ERROR_WRITE_PROTECT,
+ EACCES },
+ { WSAEINVAL, 0, EINVAL },
+ { WSAEACCES, 0, EACCES },
+ { WSAEBADF, 0, EBADF },
+ { WSAEFAULT, 0, EFAULT },
+ { WSAEINTR, 0, EINTR },
+ { WSAEINVAL, 0, EINVAL },
+ { WSAEMFILE, 0, EMFILE },
+#ifdef WSANAMETOOLONG
+ { WSANAMETOOLONG, 0, ENAMETOOLONG },
+#endif
+#ifdef WSAENFILE
+ { WSAENFILE, 0, ENFILE },
+#endif
+ { WSAENOTEMPTY, 0, ENOTEMPTY },
+ { 0, -1, 0 }
+};
+
+void win32_maperr(DWORD errcode)
+{
+ int i;
+
+ for (i = 0; win_error_table[i].range >= 0; i++) {
+ if (errcode >= win_error_table[i].win_code &&
+ errcode <= win_error_table[i].win_code + win_error_table[i].range) {
+ errno = win_error_table[i].posix_code;
+ return;
+ }
+ }
+ /* Not found: save original error code, negated so that we can
+ recognize it in unix_error_message */
+ errno = -errcode;
+}
+
+/* Windows socket errors */
+#undef EWOULDBLOCK
+#define EWOULDBLOCK -WSAEWOULDBLOCK
+#undef EINPROGRESS
+#define EINPROGRESS -WSAEINPROGRESS
+#undef EALREADY
+#define EALREADY -WSAEALREADY
+#undef ENOTSOCK
+#define ENOTSOCK -WSAENOTSOCK
+#undef EDESTADDRREQ
+#define EDESTADDRREQ -WSAEDESTADDRREQ
+#undef EMSGSIZE
+#define EMSGSIZE -WSAEMSGSIZE
+#undef EPROTOTYPE
+#define EPROTOTYPE -WSAEPROTOTYPE
+#undef ENOPROTOOPT
+#define ENOPROTOOPT -WSAENOPROTOOPT
+#undef EPROTONOSUPPORT
+#define EPROTONOSUPPORT -WSAEPROTONOSUPPORT
+#undef ESOCKTNOSUPPORT
+#define ESOCKTNOSUPPORT -WSAESOCKTNOSUPPORT
+#undef EOPNOTSUPP
+#define EOPNOTSUPP -WSAEOPNOTSUPP
+#undef EPFNOSUPPORT
+#define EPFNOSUPPORT -WSAEPFNOSUPPORT
+#undef EAFNOSUPPORT
+#define EAFNOSUPPORT -WSAEAFNOSUPPORT
+#undef EADDRINUSE
+#define EADDRINUSE -WSAEADDRINUSE
+#undef EADDRNOTAVAIL
+#define EADDRNOTAVAIL -WSAEADDRNOTAVAIL
+#undef ENETDOWN
+#define ENETDOWN -WSAENETDOWN
+#undef ENETUNREACH
+#define ENETUNREACH -WSAENETUNREACH
+#undef ENETRESET
+#define ENETRESET -WSAENETRESET
+#undef ECONNABORTED
+#define ECONNABORTED -WSAECONNABORTED
+#undef ECONNRESET
+#define ECONNRESET -WSAECONNRESET
+#undef ENOBUFS
+#define ENOBUFS -WSAENOBUFS
+#undef EISCONN
+#define EISCONN -WSAEISCONN
+#undef ENOTCONN
+#define ENOTCONN -WSAENOTCONN
+#undef ESHUTDOWN
+#define ESHUTDOWN -WSAESHUTDOWN
+#undef ETOOMANYREFS
+#define ETOOMANYREFS -WSAETOOMANYREFS
+#undef ETIMEDOUT
+#define ETIMEDOUT -WSAETIMEDOUT
+#undef ECONNREFUSED
+#define ECONNREFUSED -WSAECONNREFUSED
+#undef ELOOP
+#define ELOOP -WSAELOOP
+#undef EHOSTDOWN
+#define EHOSTDOWN -WSAEHOSTDOWN
+#undef EHOSTUNREACH
+#define EHOSTUNREACH -WSAEHOSTUNREACH
+#undef EPROCLIM
+#define EPROCLIM -WSAEPROCLIM
+#undef EUSERS
+#define EUSERS -WSAEUSERS
+#undef EDQUOT
+#define EDQUOT -WSAEDQUOT
+#undef ESTALE
+#define ESTALE -WSAESTALE
+#undef EREMOTE
+#define EREMOTE -WSAEREMOTE
+
+#undef EOVERFLOW
+#define EOVERFLOW -ERROR_ARITHMETIC_OVERFLOW
+#undef EACCESS
+#define EACCESS EACCES
+
+int error_table[] = {
+ E2BIG, EACCESS, EAGAIN, EBADF, EBUSY, ECHILD, EDEADLK, EDOM,
+ EEXIST, EFAULT, EFBIG, EINTR, EINVAL, EIO, EISDIR, EMFILE, EMLINK,
+ ENAMETOOLONG, ENFILE, ENODEV, ENOENT, ENOEXEC, ENOLCK, ENOMEM, ENOSPC,
+ ENOSYS, ENOTDIR, ENOTEMPTY, ENOTTY, ENXIO, EPERM, EPIPE, ERANGE,
+ EROFS, ESPIPE, ESRCH, EXDEV, EWOULDBLOCK, EINPROGRESS, EALREADY,
+ ENOTSOCK, EDESTADDRREQ, EMSGSIZE, EPROTOTYPE, ENOPROTOOPT,
+ EPROTONOSUPPORT, ESOCKTNOSUPPORT, EOPNOTSUPP, EPFNOSUPPORT,
+ EAFNOSUPPORT, EADDRINUSE, EADDRNOTAVAIL, ENETDOWN, ENETUNREACH,
+ ENETRESET, ECONNABORTED, ECONNRESET, ENOBUFS, EISCONN, ENOTCONN,
+ ESHUTDOWN, ETOOMANYREFS, ETIMEDOUT, ECONNREFUSED, EHOSTDOWN,
+ EHOSTUNREACH, ELOOP, EOVERFLOW /*, EUNKNOWNERR */
+};
+
+static value * unix_error_exn = NULL;
+
+value unix_error_of_code (int errcode)
+{
+ int errconstr;
+ value err;
+
+ errconstr =
+ cst_to_constr(errcode, error_table, sizeof(error_table)/sizeof(int), -1);
+ if (errconstr == Val_int(-1)) {
+ err = alloc_small(1, 0);
+ Field(err, 0) = Val_int(errcode);
+ } else {
+ err = errconstr;
+ }
+ return err;
+}
+
+void unix_error(int errcode, char *cmdname, value cmdarg)
+{
+ value res;
+ value name = Val_unit, err = Val_unit, arg = Val_unit;
+ int errconstr;
+
+ Begin_roots3 (name, err, arg);
+ arg = cmdarg == Nothing ? copy_string("") : cmdarg;
+ name = copy_string(cmdname);
+ err = unix_error_of_code (errcode);
+ if (unix_error_exn == NULL) {
+ unix_error_exn = caml_named_value("Unix.Unix_error");
+ if (unix_error_exn == NULL)
+ invalid_argument("Exception Unix.Unix_error not initialized,"
+ " please link unix.cma");
+ }
+ res = alloc_small(4, 0);
+ Field(res, 0) = *unix_error_exn;
+ Field(res, 1) = err;
+ Field(res, 2) = name;
+ Field(res, 3) = arg;
+ End_roots();
+ mlraise(res);
+}
+
+void uerror(cmdname, cmdarg)
+ char * cmdname;
+ value cmdarg;
+{
+ unix_error(errno, cmdname, cmdarg);
+}
diff --git a/otherlibs/win32unix/unixsupport.h b/otherlibs/win32unix/unixsupport.h
new file mode 100644
index 0000000000..b8efb27806
--- /dev/null
+++ b/otherlibs/win32unix/unixsupport.h
@@ -0,0 +1,77 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy and Pascal Cuoq, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef CAML_UNIXSUPPORT_H
+#define CAML_UNIXSUPPORT_H
+
+#define WIN32_LEAN_AND_MEAN
+#include <wtypes.h>
+#include <winbase.h>
+#include <stdlib.h>
+#include <direct.h>
+#include <process.h>
+#include <sys/types.h>
+#include <winsock2.h>
+#ifdef HAS_IPV6
+#include <ws2tcpip.h>
+#include <wspiapi.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct filedescr {
+ union {
+ HANDLE handle;
+ SOCKET socket;
+ } fd; /* Real windows handle */
+ enum { KIND_HANDLE, KIND_SOCKET } kind;
+ int crt_fd; /* C runtime descriptor */
+ unsigned int flags_fd; /* See FLAGS_FD_* */
+};
+
+#define Handle_val(v) (((struct filedescr *) Data_custom_val(v))->fd.handle)
+#define Socket_val(v) (((struct filedescr *) Data_custom_val(v))->fd.socket)
+#define Descr_kind_val(v) (((struct filedescr *) Data_custom_val(v))->kind)
+#define CRT_fd_val(v) (((struct filedescr *) Data_custom_val(v))->crt_fd)
+#define Flags_fd_val(v) (((struct filedescr *) Data_custom_val(v))->flags_fd)
+
+/* extern value win_alloc_handle_or_socket(HANDLE); */
+extern value win_alloc_handle(HANDLE);
+extern value win_alloc_socket(SOCKET);
+extern int win_CRT_fd_of_filedescr(value handle);
+
+#define NO_CRT_FD (-1)
+#define Nothing ((value) 0)
+
+extern void win32_maperr(DWORD errcode);
+extern value unix_error_of_code (int errcode);
+extern void unix_error (int errcode, char * cmdname, value arg);
+extern void uerror (char * cmdname, value arg);
+extern value unix_freeze_buffer (value);
+
+/* Information stored in flags_fd, describing more precisely the socket
+ * and its status. The whole flags_fd is initialized to 0.
+ */
+
+/* Blocking or nonblocking. By default a filedescr is in blocking state */
+#define FLAGS_FD_IS_BLOCKING (1<<0)
+
+#define UNIX_BUFFER_SIZE 65536
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CAML_UNIXSUPPORT_H */
diff --git a/otherlibs/win32unix/windbug.c b/otherlibs/win32unix/windbug.c
new file mode 100644
index 0000000000..a5e0d649f8
--- /dev/null
+++ b/otherlibs/win32unix/windbug.c
@@ -0,0 +1,30 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Sylvain Le Gall for Lexifi */
+/* */
+/* Copyright 2008 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include "windbug.h"
+
+int debug_test (void)
+{
+ static int debug_init = 0;
+ static int debug = 0;
+
+#ifdef DEBUG
+ if (!debug_init)
+ {
+ debug = (getenv("OCAMLDEBUG") != NULL);
+ debug_init = 1;
+ };
+#endif
+
+ return debug;
+}
diff --git a/otherlibs/win32unix/windbug.h b/otherlibs/win32unix/windbug.h
new file mode 100644
index 0000000000..eb7c94f12b
--- /dev/null
+++ b/otherlibs/win32unix/windbug.h
@@ -0,0 +1,40 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Sylvain Le Gall for Lexifi */
+/* */
+/* Copyright 2008 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifdef DEBUG
+
+#include <stdio.h>
+#include <windows.h>
+
+/* According to MSDN, MSVC supports the gcc ## operator (to deal with empty
+ argument lists)
+ */
+#define DEBUG_PRINT(fmt, ...) \
+ do \
+ { \
+ if (debug_test()) \
+ { \
+ fprintf(stderr, "DBUG (pid:%ld, tid: %ld): ", GetCurrentProcessId(), \
+ GetCurrentThreadId()); \
+ fprintf(stderr, fmt, ##__VA_ARGS__); \
+ fprintf(stderr, "\n"); \
+ fflush(stderr); \
+ }; \
+ } while(0)
+
+/* Test if we are in dbug mode */
+int debug_test (void);
+
+#else
+#define DEBUG_PRINT(fmt, ...)
+#endif
diff --git a/otherlibs/win32unix/windir.c b/otherlibs/win32unix/windir.c
new file mode 100644
index 0000000000..ef952aa902
--- /dev/null
+++ b/otherlibs/win32unix/windir.c
@@ -0,0 +1,77 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Pascal Cuoq and Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <errno.h>
+#include <caml/alloc.h>
+#include <caml/fail.h>
+#include "unixsupport.h"
+
+CAMLprim value win_findfirst(name)
+ value name;
+{
+ HANDLE h;
+ value v;
+ WIN32_FIND_DATA fileinfo;
+ value valname = Val_unit;
+ value valh = Val_unit;
+
+ Begin_roots2 (valname,valh);
+ h = FindFirstFile(String_val(name),&fileinfo);
+ if (h == INVALID_HANDLE_VALUE) {
+ DWORD err = GetLastError();
+ if (err == ERROR_NO_MORE_FILES)
+ raise_end_of_file();
+ else {
+ win32_maperr(err);
+ uerror("opendir", Nothing);
+ }
+ }
+ valname = copy_string(fileinfo.cFileName);
+ valh = win_alloc_handle(h);
+ v = alloc_small(2, 0);
+ Field(v,0) = valname;
+ Field(v,1) = valh;
+ End_roots();
+ return v;
+}
+
+CAMLprim value win_findnext(valh)
+ value valh;
+{
+ WIN32_FIND_DATA fileinfo;
+ BOOL retcode;
+
+ retcode = FindNextFile(Handle_val(valh), &fileinfo);
+ if (!retcode) {
+ DWORD err = GetLastError();
+ if (err == ERROR_NO_MORE_FILES)
+ raise_end_of_file();
+ else {
+ win32_maperr(err);
+ uerror("readdir", Nothing);
+ }
+ }
+ return copy_string(fileinfo.cFileName);
+}
+
+CAMLprim value win_findclose(valh)
+ value valh;
+{
+ if (! FindClose(Handle_val(valh))) {
+ win32_maperr(GetLastError());
+ uerror("closedir", Nothing);
+ }
+ return Val_unit;
+}
diff --git a/otherlibs/win32unix/winlist.c b/otherlibs/win32unix/winlist.c
new file mode 100644
index 0000000000..3c80b334c8
--- /dev/null
+++ b/otherlibs/win32unix/winlist.c
@@ -0,0 +1,78 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Sylvain Le Gall for Lexifi */
+/* */
+/* Copyright 2008 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Basic list function in C. */
+
+#include "winlist.h"
+#include <windows.h>
+
+void list_init (LPLIST lst)
+{
+ lst->lpNext = NULL;
+}
+
+void list_cleanup (LPLIST lst)
+{
+ lst->lpNext = NULL;
+}
+
+void list_next_set (LPLIST lst, LPLIST next)
+{
+ lst->lpNext = next;
+}
+
+LPLIST list_next (LPLIST lst)
+{
+ return lst->lpNext;
+}
+
+int list_length (LPLIST lst)
+{
+ int length = 0;
+ LPLIST iter = lst;
+ while (iter != NULL)
+ {
+ length++;
+ iter = list_next(iter);
+ };
+ return length;
+}
+
+LPLIST list_concat (LPLIST lsta, LPLIST lstb)
+{
+ LPLIST res = NULL;
+ LPLIST iter = NULL;
+ LPLIST iterPrev = NULL;
+
+ if (lsta == NULL)
+ {
+ res = lstb;
+ }
+ else if (lstb == NULL)
+ {
+ res = lsta;
+ }
+ else
+ {
+ res = lsta;
+ iter = lsta;
+ while (iter != NULL)
+ {
+ iterPrev = iter;
+ iter = list_next(iter);
+ };
+ iterPrev->lpNext = lstb;
+ };
+
+ return res;
+}
diff --git a/otherlibs/win32unix/winlist.h b/otherlibs/win32unix/winlist.h
new file mode 100644
index 0000000000..8b35c5516c
--- /dev/null
+++ b/otherlibs/win32unix/winlist.h
@@ -0,0 +1,53 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Sylvain Le Gall for Lexifi */
+/* */
+/* Copyright 2008 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef _WINLIST_H
+#define _WINLIST_H
+
+/* Basic list function in C. */
+
+/* Singly-linked list data structure.
+ * To transform a C struct into a list structure, you must include
+ * at first position of your C struct a "LIST lst" and call list_init
+ * on this data structure.
+ *
+ * See winworker.c for example.
+ */
+typedef struct _LIST LIST;
+typedef LIST *LPLIST;
+
+struct _LIST {
+ LPLIST lpNext;
+};
+
+/* Initialize list data structure */
+void list_init (LPLIST lst);
+
+/* Cleanup list data structure */
+void list_cleanup (LPLIST lst);
+
+/* Set next element */
+void list_next_set (LPLIST lst, LPLIST next);
+
+/* Return next element */
+LPLIST list_next (LPLIST);
+
+#define LIST_NEXT(T, e) ((T)(list_next((LPLIST)(e))))
+
+/* Get number of element */
+int list_length (LPLIST);
+
+/* Concat two list. */
+LPLIST list_concat (LPLIST, LPLIST);
+
+#endif /* _WINLIST_H */
diff --git a/otherlibs/win32unix/winwait.c b/otherlibs/win32unix/winwait.c
new file mode 100644
index 0000000000..510a16fea1
--- /dev/null
+++ b/otherlibs/win32unix/winwait.c
@@ -0,0 +1,68 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Pascal Cuoq and Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+#include <windows.h>
+#include <sys/types.h>
+
+static value alloc_process_status(HANDLE pid, int status)
+{
+ value res, st;
+
+ st = alloc(1, 0);
+ Field(st, 0) = Val_int(status);
+ Begin_root (st);
+ res = alloc_small(2, 0);
+ Field(res, 0) = Val_long((intnat) pid);
+ Field(res, 1) = st;
+ End_roots();
+ return res;
+}
+
+enum { CAML_WNOHANG = 1, CAML_WUNTRACED = 2 };
+
+static int wait_flag_table[] = { CAML_WNOHANG, CAML_WUNTRACED };
+
+CAMLprim value win_waitpid(value vflags, value vpid_req)
+{
+ int flags;
+ DWORD status, retcode;
+ HANDLE pid_req = (HANDLE) Long_val(vpid_req);
+ DWORD err = 0;
+
+ flags = convert_flag_list(vflags, wait_flag_table);
+ if ((flags & CAML_WNOHANG) == 0) {
+ enter_blocking_section();
+ retcode = WaitForSingleObject(pid_req, INFINITE);
+ if (retcode == WAIT_FAILED) err = GetLastError();
+ leave_blocking_section();
+ if (err) {
+ win32_maperr(err);
+ uerror("waitpid", Nothing);
+ }
+ }
+ if (! GetExitCodeProcess(pid_req, &status)) {
+ win32_maperr(GetLastError());
+ uerror("waitpid", Nothing);
+ }
+ if (status == STILL_ACTIVE)
+ return alloc_process_status((HANDLE) 0, 0);
+ else {
+ CloseHandle(pid_req);
+ return alloc_process_status(pid_req, status);
+ }
+}
diff --git a/otherlibs/win32unix/winworker.c b/otherlibs/win32unix/winworker.c
new file mode 100644
index 0000000000..bcd5947aec
--- /dev/null
+++ b/otherlibs/win32unix/winworker.c
@@ -0,0 +1,320 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Sylvain Le Gall for Lexifi */
+/* */
+/* Copyright 2008 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/alloc.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "winworker.h"
+#include "winlist.h"
+#include "windbug.h"
+
+typedef enum {
+ WORKER_CMD_NONE = 0,
+ WORKER_CMD_EXEC,
+ WORKER_CMD_STOP
+} WORKERCMD;
+
+struct _WORKER {
+ LIST lst; /* This structure is used as a list. */
+ HANDLE hJobStarted; /* Event representing that the function has begun.*/
+ HANDLE hJobStop; /* Event that can be used to notify the function
+ that it should stop processing. */
+ HANDLE hJobDone; /* Event representing that the function has
+ finished. */
+ void *lpJobUserData; /* User data for the job. */
+ WORKERFUNC hJobFunc; /* Function to be called during APC */
+ HANDLE hWorkerReady; /* Worker is ready. */
+ HANDLE hCommandReady; /* Worker should execute command. */
+ WORKERCMD ECommand; /* Command to execute */
+ HANDLE hThread; /* Thread handle of the worker. */
+};
+
+#define THREAD_WORKERS_MAX 16
+#define THREAD_WORKERS_MEM 4000
+
+LPWORKER lpWorkers = NULL;
+DWORD nWorkersCurrent = 0;
+DWORD nWorkersMax = 0;
+HANDLE hWorkersMutex = INVALID_HANDLE_VALUE;
+
+DWORD WINAPI worker_wait (LPVOID _data)
+{
+ BOOL bExit;
+ LPWORKER lpWorker;
+
+ lpWorker = (LPWORKER )_data;
+ bExit = FALSE;
+
+ DEBUG_PRINT("Worker %x starting", lpWorker);
+ while (
+ !bExit
+ && SignalObjectAndWait(
+ lpWorker->hWorkerReady,
+ lpWorker->hCommandReady,
+ INFINITE,
+ TRUE) == WAIT_OBJECT_0)
+ {
+ DEBUG_PRINT("Worker %x running", lpWorker);
+ switch (lpWorker->ECommand)
+ {
+ case WORKER_CMD_NONE:
+ break;
+
+ case WORKER_CMD_EXEC:
+ if (lpWorker->hJobFunc != NULL)
+ {
+ SetEvent(lpWorker->hJobStarted);
+ lpWorker->hJobFunc(lpWorker->hJobStop, lpWorker->lpJobUserData);
+ SetEvent(lpWorker->hJobDone);
+ };
+ break;
+
+ case WORKER_CMD_STOP:
+ bExit = TRUE;
+ break;
+ }
+ };
+ DEBUG_PRINT("Worker %x exiting", lpWorker);
+
+ return 0;
+}
+
+LPWORKER worker_new (void)
+{
+ LPWORKER lpWorker = NULL;
+
+ lpWorker = (LPWORKER)caml_stat_alloc(sizeof(WORKER));
+ list_init((LPLIST)lpWorker);
+ lpWorker->hJobStarted = CreateEvent(NULL, TRUE, FALSE, NULL);
+ lpWorker->hJobStop = CreateEvent(NULL, TRUE, FALSE, NULL);
+ lpWorker->hJobDone = CreateEvent(NULL, TRUE, FALSE, NULL);
+ lpWorker->lpJobUserData = NULL;
+ lpWorker->hWorkerReady = CreateEvent(NULL, FALSE, FALSE, NULL);
+ lpWorker->hCommandReady = CreateEvent(NULL, FALSE, FALSE, NULL);
+ lpWorker->ECommand = WORKER_CMD_NONE;
+ lpWorker->hThread = CreateThread(
+ NULL,
+ THREAD_WORKERS_MEM,
+ worker_wait,
+ (LPVOID)lpWorker,
+ 0,
+ NULL);
+
+ return lpWorker;
+};
+
+void worker_free (LPWORKER lpWorker)
+{
+ /* Wait for termination of the worker */
+ DEBUG_PRINT("Shutting down worker %x", lpWorker);
+ WaitForSingleObject(lpWorker->hWorkerReady, INFINITE);
+ lpWorker->ECommand = WORKER_CMD_STOP;
+ SetEvent(lpWorker->hCommandReady);
+ WaitForSingleObject(lpWorker->hThread, INFINITE);
+
+ /* Free resources */
+ DEBUG_PRINT("Freeing resources of worker %x", lpWorker);
+ if (lpWorker->hThread != INVALID_HANDLE_VALUE)
+ {
+ CloseHandle(lpWorker->hThread);
+ lpWorker->hThread = INVALID_HANDLE_VALUE;
+ }
+
+ if (lpWorker->hJobStarted != INVALID_HANDLE_VALUE)
+ {
+ CloseHandle(lpWorker->hJobStarted);
+ lpWorker->hJobStarted = INVALID_HANDLE_VALUE;
+ }
+
+ if (lpWorker->hJobStop != INVALID_HANDLE_VALUE)
+ {
+ CloseHandle(lpWorker->hJobStop);
+ lpWorker->hJobStop = INVALID_HANDLE_VALUE;
+ }
+
+ if (lpWorker->hJobDone != INVALID_HANDLE_VALUE)
+ {
+ CloseHandle(lpWorker->hJobDone);
+ lpWorker->hJobDone = INVALID_HANDLE_VALUE;
+ }
+
+ lpWorker->lpJobUserData = NULL;
+ lpWorker->hJobFunc = NULL;
+
+ if (lpWorker->hWorkerReady != INVALID_HANDLE_VALUE)
+ {
+ CloseHandle(lpWorker->hWorkerReady);
+ lpWorker->hWorkerReady = INVALID_HANDLE_VALUE;
+ }
+
+ if (lpWorker->hCommandReady != INVALID_HANDLE_VALUE)
+ {
+ CloseHandle(lpWorker->hCommandReady);
+ lpWorker->hCommandReady = INVALID_HANDLE_VALUE;
+ }
+
+ caml_stat_free(lpWorker);
+};
+
+LPWORKER worker_pop (void)
+{
+ LPWORKER lpWorkerFree = NULL;
+
+ WaitForSingleObject(hWorkersMutex, INFINITE);
+ /* Get the first worker of the list */
+ if (lpWorkers != NULL)
+ {
+ lpWorkerFree = lpWorkers;
+ lpWorkers = LIST_NEXT(LPWORKER, lpWorkers);
+ }
+ nWorkersCurrent++;
+ nWorkersMax = (nWorkersCurrent > nWorkersMax ? nWorkersCurrent : nWorkersMax);
+ DEBUG_PRINT("Workers running current/runnning max/waiting: %d/%d/%d",
+ nWorkersCurrent,
+ nWorkersMax,
+ list_length((LPLIST)lpWorkers));
+ ReleaseMutex(hWorkersMutex);
+
+ if (lpWorkerFree == NULL)
+ {
+ /* We cannot find a free worker, create one. */
+ lpWorkerFree = worker_new();
+ }
+
+ /* Ensure that we don't get dangling pointer to old data. */
+ list_init((LPLIST)lpWorkerFree);
+ lpWorkerFree->lpJobUserData = NULL;
+
+ /* Reset events */
+ ResetEvent(lpWorkerFree->hJobStarted);
+ ResetEvent(lpWorkerFree->hJobStop);
+ ResetEvent(lpWorkerFree->hJobDone);
+
+ return lpWorkerFree;
+}
+
+void worker_push(LPWORKER lpWorker)
+{
+ BOOL bFreeWorker;
+
+ bFreeWorker = TRUE;
+
+ WaitForSingleObject(hWorkersMutex, INFINITE);
+ DEBUG_PRINT("Testing if we are under the maximum number of running workers");
+ if (list_length((LPLIST)lpWorkers) < THREAD_WORKERS_MAX)
+ {
+ DEBUG_PRINT("Saving this worker for future use");
+ DEBUG_PRINT("Next: %x", ((LPLIST)lpWorker)->lpNext);
+ lpWorkers = (LPWORKER)list_concat((LPLIST)lpWorker, (LPLIST)lpWorkers);
+ bFreeWorker = FALSE;
+ };
+ nWorkersCurrent--;
+ DEBUG_PRINT("Workers running current/runnning max/waiting: %d/%d/%d",
+ nWorkersCurrent,
+ nWorkersMax,
+ list_length((LPLIST)lpWorkers));
+ ReleaseMutex(hWorkersMutex);
+
+ if (bFreeWorker)
+ {
+ DEBUG_PRINT("Freeing worker %x", lpWorker);
+ worker_free(lpWorker);
+ }
+}
+
+void worker_init (void)
+{
+ int i = 0;
+
+ /* Init a shared variable. The only way to ensure that no other
+ worker will be at the same point is to use a critical section.
+ */
+ DEBUG_PRINT("Allocating mutex for workers");
+ if (hWorkersMutex == INVALID_HANDLE_VALUE)
+ {
+ hWorkersMutex = CreateMutex(NULL, FALSE, NULL);
+ }
+}
+
+void worker_cleanup(void)
+{
+ LPWORKER lpWorker = NULL;
+
+ /* WARNING: we can have a race condition here, if while this code
+ is executed another worker is waiting to access hWorkersMutex,
+ he will never be able to get it...
+ */
+ if (hWorkersMutex != INVALID_HANDLE_VALUE)
+ {
+ WaitForSingleObject(hWorkersMutex, INFINITE);
+ DEBUG_PRINT("Freeing global resource of workers");
+ /* Empty the queue of worker worker */
+ while (lpWorkers != NULL)
+ {
+ ReleaseMutex(hWorkersMutex);
+ lpWorker = worker_pop();
+ DEBUG_PRINT("Freeing worker %x", lpWorker);
+ WaitForSingleObject(hWorkersMutex, INFINITE);
+ worker_free(lpWorker);
+ };
+ ReleaseMutex(hWorkersMutex);
+
+ /* Destroy associated mutex */
+ CloseHandle(hWorkersMutex);
+ hWorkersMutex = INVALID_HANDLE_VALUE;
+ };
+}
+
+LPWORKER worker_job_submit (WORKERFUNC f, void *user_data)
+{
+ LPWORKER lpWorker = worker_pop();
+
+ DEBUG_PRINT("Waiting for worker to be ready");
+ enter_blocking_section();
+ WaitForSingleObject(lpWorker->hWorkerReady, INFINITE);
+ ResetEvent(lpWorker->hWorkerReady);
+ leave_blocking_section();
+ DEBUG_PRINT("Worker is ready");
+
+ lpWorker->hJobFunc = f;
+ lpWorker->lpJobUserData = user_data;
+ lpWorker->ECommand = WORKER_CMD_EXEC;
+
+ DEBUG_PRINT("Call worker (func: %x, worker: %x)", f, lpWorker);
+ SetEvent(lpWorker->hCommandReady);
+
+ return (LPWORKER)lpWorker;
+}
+
+HANDLE worker_job_event_done (LPWORKER lpWorker)
+{
+ return lpWorker->hJobDone;
+}
+
+void worker_job_stop (LPWORKER lpWorker)
+{
+ DEBUG_PRINT("Sending stop signal to worker %x", lpWorker);
+ SetEvent(lpWorker->hJobStop);
+ DEBUG_PRINT("Signal sent to worker %x", lpWorker);
+}
+
+void worker_job_finish (LPWORKER lpWorker)
+{
+ DEBUG_PRINT("Finishing call of worker %x", lpWorker);
+ enter_blocking_section();
+ WaitForSingleObject(lpWorker->hJobDone, INFINITE);
+ leave_blocking_section();
+
+ worker_push(lpWorker);
+}
diff --git a/otherlibs/win32unix/winworker.h b/otherlibs/win32unix/winworker.h
new file mode 100644
index 0000000000..cb9bf4f8d2
--- /dev/null
+++ b/otherlibs/win32unix/winworker.h
@@ -0,0 +1,70 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Contributed by Sylvain Le Gall for Lexifi */
+/* */
+/* Copyright 2008 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#ifndef _WINWORKER_H
+#define _WINWORKER_H
+
+#define _WIN32_WINNT 0x0400
+#include "unixsupport.h"
+#include <windows.h>
+
+/* Pool of worker threads.
+ *
+ * These functions help to manage a pool of worker thread and submit task to
+ * the pool. It helps to reduce the number of thread creation.
+ *
+ * Each worker are started in alertable wait state and jobs are submitted as
+ * APC (asynchronous procedure call).
+ */
+
+/* Data associated with submitted job */
+typedef struct _WORKER WORKER;
+typedef WORKER *LPWORKER;
+
+/* Function type of submitted job:
+ * void worker_call (HANDLE hStop, void *data)
+ *
+ * This function will be called using the data following:
+ * - hStop must be watched for change, since it represents an external command
+ * to stop the call. This event is shared through the WORKER structure, which
+ * can be access throuhg worker_job_event_done.
+ * - data is user provided data for the function.
+ */
+typedef void (*WORKERFUNC) (HANDLE, void *);
+
+/* Initialize global data structure for worker
+ */
+void worker_init (void);
+
+/* Free global data structure for worker
+ */
+void worker_cleanup (void);
+
+/* Submit a job to worker. Use returned data to synchronize with the procedure
+ * submitted.
+ */
+LPWORKER worker_job_submit (WORKERFUNC f, void *data);
+
+/* Get event to know when a job is done.
+ */
+HANDLE worker_job_event_done (LPWORKER);
+
+/* Ask a job to stop processing.
+ */
+void worker_job_stop (LPWORKER);
+
+/* End a job submitted to worker.
+ */
+void worker_job_finish (LPWORKER);
+
+#endif /* _WINWORKER_H */
diff --git a/otherlibs/win32unix/write.c b/otherlibs/win32unix/write.c
new file mode 100644
index 0000000000..dc0ae91b7d
--- /dev/null
+++ b/otherlibs/win32unix/write.c
@@ -0,0 +1,99 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <errno.h>
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/memory.h>
+#include <caml/signals.h>
+#include "unixsupport.h"
+
+CAMLprim value unix_write(value fd, value buf, value vofs, value vlen)
+{
+ intnat ofs, len, written;
+ DWORD numbytes, numwritten;
+ char iobuf[UNIX_BUFFER_SIZE];
+ DWORD err = 0;
+
+ Begin_root (buf);
+ ofs = Long_val(vofs);
+ len = Long_val(vlen);
+ written = 0;
+ while (len > 0) {
+ numbytes = len > UNIX_BUFFER_SIZE ? UNIX_BUFFER_SIZE : len;
+ memmove (iobuf, &Byte(buf, ofs), numbytes);
+ if (Descr_kind_val(fd) == KIND_SOCKET) {
+ int ret;
+ SOCKET s = Socket_val(fd);
+ enter_blocking_section();
+ ret = send(s, iobuf, numbytes, 0);
+ if (ret == SOCKET_ERROR) err = WSAGetLastError();
+ leave_blocking_section();
+ numwritten = ret;
+ } else {
+ HANDLE h = Handle_val(fd);
+ enter_blocking_section();
+ if (! WriteFile(h, iobuf, numbytes, &numwritten, NULL))
+ err = GetLastError();
+ leave_blocking_section();
+ }
+ if (err) {
+ win32_maperr(err);
+ uerror("write", Nothing);
+ }
+ written += numwritten;
+ ofs += numwritten;
+ len -= numwritten;
+ }
+ End_roots();
+ return Val_long(written);
+}
+
+CAMLprim value unix_single_write(value fd, value buf, value vofs, value vlen)
+{
+ intnat ofs, len, written;
+ DWORD numbytes, numwritten;
+ char iobuf[UNIX_BUFFER_SIZE];
+ DWORD err = 0;
+
+ Begin_root (buf);
+ ofs = Long_val(vofs);
+ len = Long_val(vlen);
+ written = 0;
+ if (len > 0) {
+ numbytes = len > UNIX_BUFFER_SIZE ? UNIX_BUFFER_SIZE : len;
+ memmove (iobuf, &Byte(buf, ofs), numbytes);
+ if (Descr_kind_val(fd) == KIND_SOCKET) {
+ int ret;
+ SOCKET s = Socket_val(fd);
+ enter_blocking_section();
+ ret = send(s, iobuf, numbytes, 0);
+ if (ret == SOCKET_ERROR) err = WSAGetLastError();
+ leave_blocking_section();
+ numwritten = ret;
+ } else {
+ HANDLE h = Handle_val(fd);
+ enter_blocking_section();
+ if (! WriteFile(h, iobuf, numbytes, &numwritten, NULL))
+ err = GetLastError();
+ leave_blocking_section();
+ }
+ if (err) {
+ win32_maperr(err);
+ uerror("single_write", Nothing);
+ }
+ written = numwritten;
+ }
+ End_roots();
+ return Val_long(written);
+}
diff --git a/parsing/.ignore b/parsing/.ignore
new file mode 100644
index 0000000000..5602bf8a2d
--- /dev/null
+++ b/parsing/.ignore
@@ -0,0 +1,9 @@
+parser.ml
+parser.mli
+lexer.ml
+lexer_tmp.mll
+lexer_tmp.ml
+linenum.ml
+parser.output
+parser.automaton
+parser.conflicts
diff --git a/parsing/ast_helper.ml b/parsing/ast_helper.ml
new file mode 100644
index 0000000000..7a01f101e8
--- /dev/null
+++ b/parsing/ast_helper.ml
@@ -0,0 +1,482 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Helpers to produce Parsetree fragments *)
+
+open Asttypes
+open Parsetree
+open Docstrings
+
+type lid = Longident.t loc
+type str = string loc
+type loc = Location.t
+type attrs = attribute list
+
+let default_loc = ref Location.none
+
+let with_default_loc l f =
+ let old = !default_loc in
+ default_loc := l;
+ try let r = f () in default_loc := old; r
+ with exn -> default_loc := old; raise exn
+
+module Typ = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) d =
+ {ptyp_desc = d; ptyp_loc = loc; ptyp_attributes = attrs}
+ let attr d a = {d with ptyp_attributes = d.ptyp_attributes @ [a]}
+
+ let any ?loc ?attrs () = mk ?loc ?attrs Ptyp_any
+ let var ?loc ?attrs a = mk ?loc ?attrs (Ptyp_var a)
+ let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_arrow (a, b, c))
+ let tuple ?loc ?attrs a = mk ?loc ?attrs (Ptyp_tuple a)
+ let constr ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_constr (a, b))
+ let object_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_object (a, b))
+ let class_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_class (a, b))
+ let alias ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_alias (a, b))
+ let variant ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_variant (a, b, c))
+ let poly ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_poly (a, b))
+ let package ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_package (a, b))
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Ptyp_extension a)
+
+ let force_poly t =
+ match t.ptyp_desc with
+ | Ptyp_poly _ -> t
+ | _ -> poly ~loc:t.ptyp_loc [] t (* -> ghost? *)
+end
+
+module Pat = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) d =
+ {ppat_desc = d; ppat_loc = loc; ppat_attributes = attrs}
+ let attr d a = {d with ppat_attributes = d.ppat_attributes @ [a]}
+
+ let any ?loc ?attrs () = mk ?loc ?attrs Ppat_any
+ let var ?loc ?attrs a = mk ?loc ?attrs (Ppat_var a)
+ let alias ?loc ?attrs a b = mk ?loc ?attrs (Ppat_alias (a, b))
+ let constant ?loc ?attrs a = mk ?loc ?attrs (Ppat_constant a)
+ let interval ?loc ?attrs a b = mk ?loc ?attrs (Ppat_interval (a, b))
+ let tuple ?loc ?attrs a = mk ?loc ?attrs (Ppat_tuple a)
+ let construct ?loc ?attrs a b = mk ?loc ?attrs (Ppat_construct (a, b))
+ let variant ?loc ?attrs a b = mk ?loc ?attrs (Ppat_variant (a, b))
+ let record ?loc ?attrs a b = mk ?loc ?attrs (Ppat_record (a, b))
+ let array ?loc ?attrs a = mk ?loc ?attrs (Ppat_array a)
+ let or_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_or (a, b))
+ let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_constraint (a, b))
+ let type_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_type a)
+ let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_lazy a)
+ let unpack ?loc ?attrs a = mk ?loc ?attrs (Ppat_unpack a)
+ let exception_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_exception a)
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Ppat_extension a)
+end
+
+module Exp = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) d =
+ {pexp_desc = d; pexp_loc = loc; pexp_attributes = attrs}
+ let attr d a = {d with pexp_attributes = d.pexp_attributes @ [a]}
+
+ let ident ?loc ?attrs a = mk ?loc ?attrs (Pexp_ident a)
+ let constant ?loc ?attrs a = mk ?loc ?attrs (Pexp_constant a)
+ let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_let (a, b, c))
+ let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pexp_fun (a, b, c, d))
+ let function_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_function a)
+ let apply ?loc ?attrs a b = mk ?loc ?attrs (Pexp_apply (a, b))
+ let match_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_match (a, b))
+ let try_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_try (a, b))
+ let tuple ?loc ?attrs a = mk ?loc ?attrs (Pexp_tuple a)
+ let construct ?loc ?attrs a b = mk ?loc ?attrs (Pexp_construct (a, b))
+ let variant ?loc ?attrs a b = mk ?loc ?attrs (Pexp_variant (a, b))
+ let record ?loc ?attrs a b = mk ?loc ?attrs (Pexp_record (a, b))
+ let field ?loc ?attrs a b = mk ?loc ?attrs (Pexp_field (a, b))
+ let setfield ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_setfield (a, b, c))
+ let array ?loc ?attrs a = mk ?loc ?attrs (Pexp_array a)
+ let ifthenelse ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_ifthenelse (a, b, c))
+ let sequence ?loc ?attrs a b = mk ?loc ?attrs (Pexp_sequence (a, b))
+ let while_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_while (a, b))
+ let for_ ?loc ?attrs a b c d e = mk ?loc ?attrs (Pexp_for (a, b, c, d, e))
+ let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_constraint (a, b))
+ let coerce ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_coerce (a, b, c))
+ let send ?loc ?attrs a b = mk ?loc ?attrs (Pexp_send (a, b))
+ let new_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_new a)
+ let setinstvar ?loc ?attrs a b = mk ?loc ?attrs (Pexp_setinstvar (a, b))
+ let override ?loc ?attrs a = mk ?loc ?attrs (Pexp_override a)
+ let letmodule ?loc ?attrs a b c= mk ?loc ?attrs (Pexp_letmodule (a, b, c))
+ let assert_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_assert a)
+ let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_lazy a)
+ let poly ?loc ?attrs a b = mk ?loc ?attrs (Pexp_poly (a, b))
+ let object_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_object a)
+ let newtype ?loc ?attrs a b = mk ?loc ?attrs (Pexp_newtype (a, b))
+ let pack ?loc ?attrs a = mk ?loc ?attrs (Pexp_pack a)
+ let open_ ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_open (a, b, c))
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Pexp_extension a)
+
+ let case lhs ?guard rhs =
+ {
+ pc_lhs = lhs;
+ pc_guard = guard;
+ pc_rhs = rhs;
+ }
+end
+
+module Mty = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) d =
+ {pmty_desc = d; pmty_loc = loc; pmty_attributes = attrs}
+ let attr d a = {d with pmty_attributes = d.pmty_attributes @ [a]}
+
+ let ident ?loc ?attrs a = mk ?loc ?attrs (Pmty_ident a)
+ let alias ?loc ?attrs a = mk ?loc ?attrs (Pmty_alias a)
+ let signature ?loc ?attrs a = mk ?loc ?attrs (Pmty_signature a)
+ let functor_ ?loc ?attrs a b c = mk ?loc ?attrs (Pmty_functor (a, b, c))
+ let with_ ?loc ?attrs a b = mk ?loc ?attrs (Pmty_with (a, b))
+ let typeof_ ?loc ?attrs a = mk ?loc ?attrs (Pmty_typeof a)
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Pmty_extension a)
+end
+
+module Mod = struct
+let mk ?(loc = !default_loc) ?(attrs = []) d =
+ {pmod_desc = d; pmod_loc = loc; pmod_attributes = attrs}
+ let attr d a = {d with pmod_attributes = d.pmod_attributes @ [a]}
+
+ let ident ?loc ?attrs x = mk ?loc ?attrs (Pmod_ident x)
+ let structure ?loc ?attrs x = mk ?loc ?attrs (Pmod_structure x)
+ let functor_ ?loc ?attrs arg arg_ty body =
+ mk ?loc ?attrs (Pmod_functor (arg, arg_ty, body))
+ let apply ?loc ?attrs m1 m2 = mk ?loc ?attrs (Pmod_apply (m1, m2))
+ let constraint_ ?loc ?attrs m mty = mk ?loc ?attrs (Pmod_constraint (m, mty))
+ let unpack ?loc ?attrs e = mk ?loc ?attrs (Pmod_unpack e)
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Pmod_extension a)
+end
+
+module Sig = struct
+ let mk ?(loc = !default_loc) d = {psig_desc = d; psig_loc = loc}
+
+ let value ?loc a = mk ?loc (Psig_value a)
+ let type_ ?loc rec_flag a = mk ?loc (Psig_type (rec_flag, a))
+ let type_extension ?loc a = mk ?loc (Psig_typext a)
+ let exception_ ?loc a = mk ?loc (Psig_exception a)
+ let module_ ?loc a = mk ?loc (Psig_module a)
+ let rec_module ?loc a = mk ?loc (Psig_recmodule a)
+ let modtype ?loc a = mk ?loc (Psig_modtype a)
+ let open_ ?loc a = mk ?loc (Psig_open a)
+ let include_ ?loc a = mk ?loc (Psig_include a)
+ let class_ ?loc a = mk ?loc (Psig_class a)
+ let class_type ?loc a = mk ?loc (Psig_class_type a)
+ let extension ?loc ?(attrs = []) a = mk ?loc (Psig_extension (a, attrs))
+ let attribute ?loc a = mk ?loc (Psig_attribute a)
+ let text txt =
+ List.map
+ (fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
+ txt
+end
+
+module Str = struct
+ let mk ?(loc = !default_loc) d = {pstr_desc = d; pstr_loc = loc}
+
+ let eval ?loc ?(attrs = []) a = mk ?loc (Pstr_eval (a, attrs))
+ let value ?loc a b = mk ?loc (Pstr_value (a, b))
+ let primitive ?loc a = mk ?loc (Pstr_primitive a)
+ let type_ ?loc rec_flag a = mk ?loc (Pstr_type (rec_flag, a))
+ let type_extension ?loc a = mk ?loc (Pstr_typext a)
+ let exception_ ?loc a = mk ?loc (Pstr_exception a)
+ let module_ ?loc a = mk ?loc (Pstr_module a)
+ let rec_module ?loc a = mk ?loc (Pstr_recmodule a)
+ let modtype ?loc a = mk ?loc (Pstr_modtype a)
+ let open_ ?loc a = mk ?loc (Pstr_open a)
+ let class_ ?loc a = mk ?loc (Pstr_class a)
+ let class_type ?loc a = mk ?loc (Pstr_class_type a)
+ let include_ ?loc a = mk ?loc (Pstr_include a)
+ let extension ?loc ?(attrs = []) a = mk ?loc (Pstr_extension (a, attrs))
+ let attribute ?loc a = mk ?loc (Pstr_attribute a)
+ let text txt =
+ List.map
+ (fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
+ txt
+end
+
+module Cl = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) d =
+ {
+ pcl_desc = d;
+ pcl_loc = loc;
+ pcl_attributes = attrs;
+ }
+ let attr d a = {d with pcl_attributes = d.pcl_attributes @ [a]}
+
+ let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constr (a, b))
+ let structure ?loc ?attrs a = mk ?loc ?attrs (Pcl_structure a)
+ let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pcl_fun (a, b, c, d))
+ let apply ?loc ?attrs a b = mk ?loc ?attrs (Pcl_apply (a, b))
+ let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcl_let (a, b, c))
+ let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constraint (a, b))
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Pcl_extension a)
+end
+
+module Cty = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) d =
+ {
+ pcty_desc = d;
+ pcty_loc = loc;
+ pcty_attributes = attrs;
+ }
+ let attr d a = {d with pcty_attributes = d.pcty_attributes @ [a]}
+
+ let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcty_constr (a, b))
+ let signature ?loc ?attrs a = mk ?loc ?attrs (Pcty_signature a)
+ let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Pcty_arrow (a, b, c))
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Pcty_extension a)
+end
+
+module Ctf = struct
+ let mk ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) d =
+ {
+ pctf_desc = d;
+ pctf_loc = loc;
+ pctf_attributes = add_docs_attrs docs attrs;
+ }
+
+ let inherit_ ?loc ?attrs a = mk ?loc ?attrs (Pctf_inherit a)
+ let val_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_val (a, b, c, d))
+ let method_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_method (a, b, c, d))
+ let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pctf_constraint (a, b))
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Pctf_extension a)
+ let attribute ?loc a = mk ?loc (Pctf_attribute a)
+ let text txt =
+ List.map
+ (fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
+ txt
+
+ let attr d a = {d with pctf_attributes = d.pctf_attributes @ [a]}
+
+end
+
+module Cf = struct
+ let mk ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) d =
+ {
+ pcf_desc = d;
+ pcf_loc = loc;
+ pcf_attributes = add_docs_attrs docs attrs;
+ }
+
+ let inherit_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_inherit (a, b, c))
+ let val_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_val (a, b, c))
+ let method_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_method (a, b, c))
+ let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcf_constraint (a, b))
+ let initializer_ ?loc ?attrs a = mk ?loc ?attrs (Pcf_initializer a)
+ let extension ?loc ?attrs a = mk ?loc ?attrs (Pcf_extension a)
+ let attribute ?loc a = mk ?loc (Pcf_attribute a)
+ let text txt =
+ List.map
+ (fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
+ txt
+
+ let virtual_ ct = Cfk_virtual ct
+ let concrete o e = Cfk_concrete (o, e)
+
+ let attr d a = {d with pcf_attributes = d.pcf_attributes @ [a]}
+
+end
+
+module Val = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
+ ?(prim = []) name typ =
+ {
+ pval_name = name;
+ pval_type = typ;
+ pval_attributes = add_docs_attrs docs attrs;
+ pval_loc = loc;
+ pval_prim = prim;
+ }
+end
+
+module Md = struct
+ let mk ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) ?(text = []) name typ =
+ {
+ pmd_name = name;
+ pmd_type = typ;
+ pmd_attributes =
+ add_text_attrs text (add_docs_attrs docs attrs);
+ pmd_loc = loc;
+ }
+end
+
+module Mtd = struct
+ let mk ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) ?(text = []) ?typ name =
+ {
+ pmtd_name = name;
+ pmtd_type = typ;
+ pmtd_attributes =
+ add_text_attrs text (add_docs_attrs docs attrs);
+ pmtd_loc = loc;
+ }
+end
+
+module Mb = struct
+ let mk ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) ?(text = []) name expr =
+ {
+ pmb_name = name;
+ pmb_expr = expr;
+ pmb_attributes =
+ add_text_attrs text (add_docs_attrs docs attrs);
+ pmb_loc = loc;
+ }
+end
+
+module Opn = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
+ ?(override = Fresh) lid =
+ {
+ popen_lid = lid;
+ popen_override = override;
+ popen_loc = loc;
+ popen_attributes = add_docs_attrs docs attrs;
+ }
+end
+
+module Incl = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs) mexpr =
+ {
+ pincl_mod = mexpr;
+ pincl_loc = loc;
+ pincl_attributes = add_docs_attrs docs attrs;
+ }
+
+end
+
+module Vb = struct
+ let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
+ ?(text = []) pat expr =
+ {
+ pvb_pat = pat;
+ pvb_expr = expr;
+ pvb_attributes =
+ add_text_attrs text (add_docs_attrs docs attrs);
+ pvb_loc = loc;
+ }
+end
+
+module Ci = struct
+ let mk ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) ?(text = [])
+ ?(virt = Concrete) ?(params = []) name expr =
+ {
+ pci_virt = virt;
+ pci_params = params;
+ pci_name = name;
+ pci_expr = expr;
+ pci_attributes =
+ add_text_attrs text (add_docs_attrs docs attrs);
+ pci_loc = loc;
+ }
+end
+
+module Type = struct
+ let mk ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) ?(text = [])
+ ?(params = [])
+ ?(cstrs = [])
+ ?(kind = Ptype_abstract)
+ ?(priv = Public)
+ ?manifest
+ name =
+ {
+ ptype_name = name;
+ ptype_params = params;
+ ptype_cstrs = cstrs;
+ ptype_kind = kind;
+ ptype_private = priv;
+ ptype_manifest = manifest;
+ ptype_attributes =
+ add_text_attrs text (add_docs_attrs docs attrs);
+ ptype_loc = loc;
+ }
+
+ let constructor ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
+ ?(args = Pcstr_tuple []) ?res name =
+ {
+ pcd_name = name;
+ pcd_args = args;
+ pcd_res = res;
+ pcd_loc = loc;
+ pcd_attributes = add_info_attrs info attrs;
+ }
+
+ let field ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
+ ?(mut = Immutable) name typ =
+ {
+ pld_name = name;
+ pld_mutable = mut;
+ pld_type = typ;
+ pld_loc = loc;
+ pld_attributes = add_info_attrs info attrs;
+ }
+
+end
+
+(** Type extensions *)
+module Te = struct
+ let mk ?(attrs = []) ?(docs = empty_docs)
+ ?(params = []) ?(priv = Public) path constructors =
+ {
+ ptyext_path = path;
+ ptyext_params = params;
+ ptyext_constructors = constructors;
+ ptyext_private = priv;
+ ptyext_attributes = add_docs_attrs docs attrs;
+ }
+
+ let constructor ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) ?(info = empty_info) name kind =
+ {
+ pext_name = name;
+ pext_kind = kind;
+ pext_loc = loc;
+ pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
+ }
+
+ let decl ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
+ ?(info = empty_info) ?(args = Pcstr_tuple []) ?res name =
+ {
+ pext_name = name;
+ pext_kind = Pext_decl(args, res);
+ pext_loc = loc;
+ pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
+ }
+
+ let rebind ?(loc = !default_loc) ?(attrs = [])
+ ?(docs = empty_docs) ?(info = empty_info) name lid =
+ {
+ pext_name = name;
+ pext_kind = Pext_rebind lid;
+ pext_loc = loc;
+ pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
+ }
+
+end
+
+module Csig = struct
+ let mk self fields =
+ {
+ pcsig_self = self;
+ pcsig_fields = fields;
+ }
+end
+
+module Cstr = struct
+ let mk self fields =
+ {
+ pcstr_self = self;
+ pcstr_fields = fields;
+ }
+end
diff --git a/parsing/ast_helper.mli b/parsing/ast_helper.mli
new file mode 100644
index 0000000000..72bffcee7b
--- /dev/null
+++ b/parsing/ast_helper.mli
@@ -0,0 +1,410 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Helpers to produce Parsetree fragments *)
+
+open Parsetree
+open Asttypes
+open Docstrings
+
+type lid = Longident.t loc
+type str = string loc
+type loc = Location.t
+type attrs = attribute list
+
+(** {2 Default locations} *)
+
+val default_loc: loc ref
+ (** Default value for all optional location arguments. *)
+
+val with_default_loc: loc -> (unit -> 'a) -> 'a
+ (** Set the [default_loc] within the scope of the execution
+ of the provided function. *)
+
+(** {2 Core language} *)
+
+(** Type expressions *)
+module Typ :
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> core_type_desc -> core_type
+ val attr: core_type -> attribute -> core_type
+
+ val any: ?loc:loc -> ?attrs:attrs -> unit -> core_type
+ val var: ?loc:loc -> ?attrs:attrs -> string -> core_type
+ val arrow: ?loc:loc -> ?attrs:attrs -> arg_label -> core_type -> core_type
+ -> core_type
+ val tuple: ?loc:loc -> ?attrs:attrs -> core_type list -> core_type
+ val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type
+ val object_: ?loc:loc -> ?attrs:attrs ->
+ (string * attributes * core_type) list -> closed_flag ->
+ core_type
+ val class_: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> core_type
+ val alias: ?loc:loc -> ?attrs:attrs -> core_type -> string -> core_type
+ val variant: ?loc:loc -> ?attrs:attrs -> row_field list -> closed_flag
+ -> label list option -> core_type
+ val poly: ?loc:loc -> ?attrs:attrs -> string list -> core_type -> core_type
+ val package: ?loc:loc -> ?attrs:attrs -> lid -> (lid * core_type) list
+ -> core_type
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> core_type
+
+ val force_poly: core_type -> core_type
+ end
+
+(** Patterns *)
+module Pat:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> pattern_desc -> pattern
+ val attr:pattern -> attribute -> pattern
+
+ val any: ?loc:loc -> ?attrs:attrs -> unit -> pattern
+ val var: ?loc:loc -> ?attrs:attrs -> str -> pattern
+ val alias: ?loc:loc -> ?attrs:attrs -> pattern -> str -> pattern
+ val constant: ?loc:loc -> ?attrs:attrs -> constant -> pattern
+ val interval: ?loc:loc -> ?attrs:attrs -> constant -> constant -> pattern
+ val tuple: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern
+ val construct: ?loc:loc -> ?attrs:attrs -> lid -> pattern option -> pattern
+ val variant: ?loc:loc -> ?attrs:attrs -> label -> pattern option -> pattern
+ val record: ?loc:loc -> ?attrs:attrs -> (lid * pattern) list -> closed_flag
+ -> pattern
+ val array: ?loc:loc -> ?attrs:attrs -> pattern list -> pattern
+ val or_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern -> pattern
+ val constraint_: ?loc:loc -> ?attrs:attrs -> pattern -> core_type -> pattern
+ val type_: ?loc:loc -> ?attrs:attrs -> lid -> pattern
+ val lazy_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern
+ val unpack: ?loc:loc -> ?attrs:attrs -> str -> pattern
+ val exception_: ?loc:loc -> ?attrs:attrs -> pattern -> pattern
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> pattern
+ end
+
+(** Expressions *)
+module Exp:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> expression_desc -> expression
+ val attr: expression -> attribute -> expression
+
+ val ident: ?loc:loc -> ?attrs:attrs -> lid -> expression
+ val constant: ?loc:loc -> ?attrs:attrs -> constant -> expression
+ val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list
+ -> expression -> expression
+ val fun_: ?loc:loc -> ?attrs:attrs -> arg_label -> expression option
+ -> pattern -> expression -> expression
+ val function_: ?loc:loc -> ?attrs:attrs -> case list -> expression
+ val apply: ?loc:loc -> ?attrs:attrs -> expression
+ -> (arg_label * expression) list -> expression
+ val match_: ?loc:loc -> ?attrs:attrs -> expression -> case list
+ -> expression
+ val try_: ?loc:loc -> ?attrs:attrs -> expression -> case list -> expression
+ val tuple: ?loc:loc -> ?attrs:attrs -> expression list -> expression
+ val construct: ?loc:loc -> ?attrs:attrs -> lid -> expression option
+ -> expression
+ val variant: ?loc:loc -> ?attrs:attrs -> label -> expression option
+ -> expression
+ val record: ?loc:loc -> ?attrs:attrs -> (lid * expression) list
+ -> expression option -> expression
+ val field: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression
+ val setfield: ?loc:loc -> ?attrs:attrs -> expression -> lid -> expression
+ -> expression
+ val array: ?loc:loc -> ?attrs:attrs -> expression list -> expression
+ val ifthenelse: ?loc:loc -> ?attrs:attrs -> expression -> expression
+ -> expression option -> expression
+ val sequence: ?loc:loc -> ?attrs:attrs -> expression -> expression
+ -> expression
+ val while_: ?loc:loc -> ?attrs:attrs -> expression -> expression
+ -> expression
+ val for_: ?loc:loc -> ?attrs:attrs -> pattern -> expression -> expression
+ -> direction_flag -> expression -> expression
+ val coerce: ?loc:loc -> ?attrs:attrs -> expression -> core_type option
+ -> core_type -> expression
+ val constraint_: ?loc:loc -> ?attrs:attrs -> expression -> core_type
+ -> expression
+ val send: ?loc:loc -> ?attrs:attrs -> expression -> string -> expression
+ val new_: ?loc:loc -> ?attrs:attrs -> lid -> expression
+ val setinstvar: ?loc:loc -> ?attrs:attrs -> str -> expression -> expression
+ val override: ?loc:loc -> ?attrs:attrs -> (str * expression) list
+ -> expression
+ val letmodule: ?loc:loc -> ?attrs:attrs -> str -> module_expr -> expression
+ -> expression
+ val assert_: ?loc:loc -> ?attrs:attrs -> expression -> expression
+ val lazy_: ?loc:loc -> ?attrs:attrs -> expression -> expression
+ val poly: ?loc:loc -> ?attrs:attrs -> expression -> core_type option
+ -> expression
+ val object_: ?loc:loc -> ?attrs:attrs -> class_structure -> expression
+ val newtype: ?loc:loc -> ?attrs:attrs -> string -> expression -> expression
+ val pack: ?loc:loc -> ?attrs:attrs -> module_expr -> expression
+ val open_: ?loc:loc -> ?attrs:attrs -> override_flag -> lid -> expression
+ -> expression
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> expression
+
+ val case: pattern -> ?guard:expression -> expression -> case
+ end
+
+(** Value declarations *)
+module Val:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs ->
+ ?prim:string list -> str -> core_type -> value_description
+ end
+
+(** Type declarations *)
+module Type:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text ->
+ ?params:(core_type * variance) list ->
+ ?cstrs:(core_type * core_type * loc) list ->
+ ?kind:type_kind -> ?priv:private_flag -> ?manifest:core_type -> str ->
+ type_declaration
+
+ val constructor: ?loc:loc -> ?attrs:attrs -> ?info:info ->
+ ?args:constructor_arguments -> ?res:core_type -> str ->
+ constructor_declaration
+ val field: ?loc:loc -> ?attrs:attrs -> ?info:info ->
+ ?mut:mutable_flag -> str -> core_type -> label_declaration
+ end
+
+(** Type extensions *)
+module Te:
+ sig
+ val mk: ?attrs:attrs -> ?docs:docs ->
+ ?params:(core_type * variance) list -> ?priv:private_flag ->
+ lid -> extension_constructor list -> type_extension
+
+ val constructor: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info ->
+ str -> extension_constructor_kind -> extension_constructor
+
+ val decl: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info ->
+ ?args:constructor_arguments -> ?res:core_type -> str ->
+ extension_constructor
+ val rebind: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?info:info ->
+ str -> lid -> extension_constructor
+ end
+
+(** {2 Module language} *)
+
+(** Module type expressions *)
+module Mty:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> module_type_desc -> module_type
+ val attr: module_type -> attribute -> module_type
+
+ val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_type
+ val alias: ?loc:loc -> ?attrs:attrs -> lid -> module_type
+ val signature: ?loc:loc -> ?attrs:attrs -> signature -> module_type
+ val functor_: ?loc:loc -> ?attrs:attrs ->
+ str -> module_type option -> module_type -> module_type
+ val with_: ?loc:loc -> ?attrs:attrs -> module_type ->
+ with_constraint list -> module_type
+ val typeof_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_type
+ end
+
+(** Module expressions *)
+module Mod:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> module_expr_desc -> module_expr
+ val attr: module_expr -> attribute -> module_expr
+
+ val ident: ?loc:loc -> ?attrs:attrs -> lid -> module_expr
+ val structure: ?loc:loc -> ?attrs:attrs -> structure -> module_expr
+ val functor_: ?loc:loc -> ?attrs:attrs ->
+ str -> module_type option -> module_expr -> module_expr
+ val apply: ?loc:loc -> ?attrs:attrs -> module_expr -> module_expr ->
+ module_expr
+ val constraint_: ?loc:loc -> ?attrs:attrs -> module_expr -> module_type ->
+ module_expr
+ val unpack: ?loc:loc -> ?attrs:attrs -> expression -> module_expr
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> module_expr
+ end
+
+(** Signature items *)
+module Sig:
+ sig
+ val mk: ?loc:loc -> signature_item_desc -> signature_item
+
+ val value: ?loc:loc -> value_description -> signature_item
+ val type_: ?loc:loc -> rec_flag -> type_declaration list -> signature_item
+ val type_extension: ?loc:loc -> type_extension -> signature_item
+ val exception_: ?loc:loc -> extension_constructor -> signature_item
+ val module_: ?loc:loc -> module_declaration -> signature_item
+ val rec_module: ?loc:loc -> module_declaration list -> signature_item
+ val modtype: ?loc:loc -> module_type_declaration -> signature_item
+ val open_: ?loc:loc -> open_description -> signature_item
+ val include_: ?loc:loc -> include_description -> signature_item
+ val class_: ?loc:loc -> class_description list -> signature_item
+ val class_type: ?loc:loc -> class_type_declaration list -> signature_item
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> signature_item
+ val attribute: ?loc:loc -> attribute -> signature_item
+ val text: text -> signature_item list
+ end
+
+(** Structure items *)
+module Str:
+ sig
+ val mk: ?loc:loc -> structure_item_desc -> structure_item
+
+ val eval: ?loc:loc -> ?attrs:attributes -> expression -> structure_item
+ val value: ?loc:loc -> rec_flag -> value_binding list -> structure_item
+ val primitive: ?loc:loc -> value_description -> structure_item
+ val type_: ?loc:loc -> rec_flag -> type_declaration list -> structure_item
+ val type_extension: ?loc:loc -> type_extension -> structure_item
+ val exception_: ?loc:loc -> extension_constructor -> structure_item
+ val module_: ?loc:loc -> module_binding -> structure_item
+ val rec_module: ?loc:loc -> module_binding list -> structure_item
+ val modtype: ?loc:loc -> module_type_declaration -> structure_item
+ val open_: ?loc:loc -> open_description -> structure_item
+ val class_: ?loc:loc -> class_declaration list -> structure_item
+ val class_type: ?loc:loc -> class_type_declaration list -> structure_item
+ val include_: ?loc:loc -> include_declaration -> structure_item
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> structure_item
+ val attribute: ?loc:loc -> attribute -> structure_item
+ val text: text -> structure_item list
+ end
+
+(** Module declarations *)
+module Md:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text ->
+ str -> module_type -> module_declaration
+ end
+
+(** Module type declarations *)
+module Mtd:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text ->
+ ?typ:module_type -> str -> module_type_declaration
+ end
+
+(** Module bindings *)
+module Mb:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text ->
+ str -> module_expr -> module_binding
+ end
+
+(* Opens *)
+module Opn:
+ sig
+ val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs ->
+ ?override:override_flag -> lid -> open_description
+ end
+
+(* Includes *)
+module Incl:
+ sig
+ val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs -> 'a -> 'a include_infos
+ end
+
+(** Value bindings *)
+
+module Vb:
+ sig
+ val mk: ?loc: loc -> ?attrs:attrs -> ?docs:docs -> ?text:text ->
+ pattern -> expression -> value_binding
+ end
+
+
+(** {2 Class language} *)
+
+(** Class type expressions *)
+module Cty:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> class_type_desc -> class_type
+ val attr: class_type -> attribute -> class_type
+
+ val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_type
+ val signature: ?loc:loc -> ?attrs:attrs -> class_signature -> class_type
+ val arrow: ?loc:loc -> ?attrs:attrs -> arg_label -> core_type ->
+ class_type -> class_type
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type
+ end
+
+(** Class type fields *)
+module Ctf:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs ->
+ class_type_field_desc -> class_type_field
+ val attr: class_type_field -> attribute -> class_type_field
+
+ val inherit_: ?loc:loc -> ?attrs:attrs -> class_type -> class_type_field
+ val val_: ?loc:loc -> ?attrs:attrs -> string -> mutable_flag ->
+ virtual_flag -> core_type -> class_type_field
+ val method_: ?loc:loc -> ?attrs:attrs -> string -> private_flag ->
+ virtual_flag -> core_type -> class_type_field
+ val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type ->
+ class_type_field
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_type_field
+ val attribute: ?loc:loc -> attribute -> class_type_field
+ val text: text -> class_type_field list
+ end
+
+(** Class expressions *)
+module Cl:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> class_expr_desc -> class_expr
+ val attr: class_expr -> attribute -> class_expr
+
+ val constr: ?loc:loc -> ?attrs:attrs -> lid -> core_type list -> class_expr
+ val structure: ?loc:loc -> ?attrs:attrs -> class_structure -> class_expr
+ val fun_: ?loc:loc -> ?attrs:attrs -> arg_label -> expression option ->
+ pattern -> class_expr -> class_expr
+ val apply: ?loc:loc -> ?attrs:attrs -> class_expr ->
+ (arg_label * expression) list -> class_expr
+ val let_: ?loc:loc -> ?attrs:attrs -> rec_flag -> value_binding list ->
+ class_expr -> class_expr
+ val constraint_: ?loc:loc -> ?attrs:attrs -> class_expr -> class_type ->
+ class_expr
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_expr
+ end
+
+(** Class fields *)
+module Cf:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> class_field_desc ->
+ class_field
+ val attr: class_field -> attribute -> class_field
+
+ val inherit_: ?loc:loc -> ?attrs:attrs -> override_flag -> class_expr ->
+ string option -> class_field
+ val val_: ?loc:loc -> ?attrs:attrs -> str -> mutable_flag ->
+ class_field_kind -> class_field
+ val method_: ?loc:loc -> ?attrs:attrs -> str -> private_flag ->
+ class_field_kind -> class_field
+ val constraint_: ?loc:loc -> ?attrs:attrs -> core_type -> core_type ->
+ class_field
+ val initializer_: ?loc:loc -> ?attrs:attrs -> expression -> class_field
+ val extension: ?loc:loc -> ?attrs:attrs -> extension -> class_field
+ val attribute: ?loc:loc -> attribute -> class_field
+ val text: text -> class_field list
+
+ val virtual_: core_type -> class_field_kind
+ val concrete: override_flag -> expression -> class_field_kind
+
+ end
+
+(** Classes *)
+module Ci:
+ sig
+ val mk: ?loc:loc -> ?attrs:attrs -> ?docs:docs -> ?text:text ->
+ ?virt:virtual_flag -> ?params:(core_type * variance) list ->
+ str -> 'a -> 'a class_infos
+ end
+
+(** Class signatures *)
+module Csig:
+ sig
+ val mk: core_type -> class_type_field list -> class_signature
+ end
+
+(** Class structures *)
+module Cstr:
+ sig
+ val mk: pattern -> class_field list -> class_structure
+ end
diff --git a/parsing/ast_mapper.ml b/parsing/ast_mapper.ml
new file mode 100644
index 0000000000..493d11ff84
--- /dev/null
+++ b/parsing/ast_mapper.ml
@@ -0,0 +1,908 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A generic Parsetree mapping class *)
+
+(*
+[@@@ocaml.warning "+9"]
+ (* Ensure that record patterns don't miss any field. *)
+*)
+
+
+open Asttypes
+open Parsetree
+open Ast_helper
+open Location
+
+type mapper = {
+ attribute: mapper -> attribute -> attribute;
+ attributes: mapper -> attribute list -> attribute list;
+ case: mapper -> case -> case;
+ cases: mapper -> case list -> case list;
+ class_declaration: mapper -> class_declaration -> class_declaration;
+ class_description: mapper -> class_description -> class_description;
+ class_expr: mapper -> class_expr -> class_expr;
+ class_field: mapper -> class_field -> class_field;
+ class_signature: mapper -> class_signature -> class_signature;
+ class_structure: mapper -> class_structure -> class_structure;
+ class_type: mapper -> class_type -> class_type;
+ class_type_declaration: mapper -> class_type_declaration
+ -> class_type_declaration;
+ class_type_field: mapper -> class_type_field -> class_type_field;
+ constructor_declaration: mapper -> constructor_declaration
+ -> constructor_declaration;
+ expr: mapper -> expression -> expression;
+ extension: mapper -> extension -> extension;
+ extension_constructor: mapper -> extension_constructor
+ -> extension_constructor;
+ include_declaration: mapper -> include_declaration -> include_declaration;
+ include_description: mapper -> include_description -> include_description;
+ label_declaration: mapper -> label_declaration -> label_declaration;
+ location: mapper -> Location.t -> Location.t;
+ module_binding: mapper -> module_binding -> module_binding;
+ module_declaration: mapper -> module_declaration -> module_declaration;
+ module_expr: mapper -> module_expr -> module_expr;
+ module_type: mapper -> module_type -> module_type;
+ module_type_declaration: mapper -> module_type_declaration
+ -> module_type_declaration;
+ open_description: mapper -> open_description -> open_description;
+ pat: mapper -> pattern -> pattern;
+ payload: mapper -> payload -> payload;
+ signature: mapper -> signature -> signature;
+ signature_item: mapper -> signature_item -> signature_item;
+ structure: mapper -> structure -> structure;
+ structure_item: mapper -> structure_item -> structure_item;
+ typ: mapper -> core_type -> core_type;
+ type_declaration: mapper -> type_declaration -> type_declaration;
+ type_extension: mapper -> type_extension -> type_extension;
+ type_kind: mapper -> type_kind -> type_kind;
+ value_binding: mapper -> value_binding -> value_binding;
+ value_description: mapper -> value_description -> value_description;
+ with_constraint: mapper -> with_constraint -> with_constraint;
+}
+
+let map_fst f (x, y) = (f x, y)
+let map_snd f (x, y) = (x, f y)
+let map_tuple f1 f2 (x, y) = (f1 x, f2 y)
+let map_tuple3 f1 f2 f3 (x, y, z) = (f1 x, f2 y, f3 z)
+let map_opt f = function None -> None | Some x -> Some (f x)
+
+let map_loc sub {loc; txt} = {loc = sub.location sub loc; txt}
+
+module T = struct
+ (* Type expressions for the core language *)
+
+ let row_field sub = function
+ | Rtag (l, attrs, b, tl) ->
+ Rtag (l, sub.attributes sub attrs, b, List.map (sub.typ sub) tl)
+ | Rinherit t -> Rinherit (sub.typ sub t)
+
+ let map sub {ptyp_desc = desc; ptyp_loc = loc; ptyp_attributes = attrs} =
+ let open Typ in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Ptyp_any -> any ~loc ~attrs ()
+ | Ptyp_var s -> var ~loc ~attrs s
+ | Ptyp_arrow (lab, t1, t2) ->
+ arrow ~loc ~attrs lab (sub.typ sub t1) (sub.typ sub t2)
+ | Ptyp_tuple tyl -> tuple ~loc ~attrs (List.map (sub.typ sub) tyl)
+ | Ptyp_constr (lid, tl) ->
+ constr ~loc ~attrs (map_loc sub lid) (List.map (sub.typ sub) tl)
+ | Ptyp_object (l, o) ->
+ let f (s, a, t) = (s, sub.attributes sub a, sub.typ sub t) in
+ object_ ~loc ~attrs (List.map f l) o
+ | Ptyp_class (lid, tl) ->
+ class_ ~loc ~attrs (map_loc sub lid) (List.map (sub.typ sub) tl)
+ | Ptyp_alias (t, s) -> alias ~loc ~attrs (sub.typ sub t) s
+ | Ptyp_variant (rl, b, ll) ->
+ variant ~loc ~attrs (List.map (row_field sub) rl) b ll
+ | Ptyp_poly (sl, t) -> poly ~loc ~attrs sl (sub.typ sub t)
+ | Ptyp_package (lid, l) ->
+ package ~loc ~attrs (map_loc sub lid)
+ (List.map (map_tuple (map_loc sub) (sub.typ sub)) l)
+ | Ptyp_extension x -> extension ~loc ~attrs (sub.extension sub x)
+
+ let map_type_declaration sub
+ {ptype_name; ptype_params; ptype_cstrs;
+ ptype_kind;
+ ptype_private;
+ ptype_manifest;
+ ptype_attributes;
+ ptype_loc} =
+ Type.mk (map_loc sub ptype_name)
+ ~params:(List.map (map_fst (sub.typ sub)) ptype_params)
+ ~priv:ptype_private
+ ~cstrs:(List.map
+ (map_tuple3 (sub.typ sub) (sub.typ sub) (sub.location sub))
+ ptype_cstrs)
+ ~kind:(sub.type_kind sub ptype_kind)
+ ?manifest:(map_opt (sub.typ sub) ptype_manifest)
+ ~loc:(sub.location sub ptype_loc)
+ ~attrs:(sub.attributes sub ptype_attributes)
+
+ let map_type_kind sub = function
+ | Ptype_abstract -> Ptype_abstract
+ | Ptype_variant l ->
+ Ptype_variant (List.map (sub.constructor_declaration sub) l)
+ | Ptype_record l -> Ptype_record (List.map (sub.label_declaration sub) l)
+ | Ptype_open -> Ptype_open
+
+ let map_constructor_arguments sub = function
+ | Pcstr_tuple l -> Pcstr_tuple (List.map (sub.typ sub) l)
+ | Pcstr_record l ->
+ Pcstr_record (List.map (sub.label_declaration sub) l)
+
+ let map_type_extension sub
+ {ptyext_path; ptyext_params;
+ ptyext_constructors;
+ ptyext_private;
+ ptyext_attributes} =
+ Te.mk
+ (map_loc sub ptyext_path)
+ (List.map (sub.extension_constructor sub) ptyext_constructors)
+ ~params:(List.map (map_fst (sub.typ sub)) ptyext_params)
+ ~priv:ptyext_private
+ ~attrs:(sub.attributes sub ptyext_attributes)
+
+ let map_extension_constructor_kind sub = function
+ Pext_decl(ctl, cto) ->
+ Pext_decl(map_constructor_arguments sub ctl, map_opt (sub.typ sub) cto)
+ | Pext_rebind li ->
+ Pext_rebind (map_loc sub li)
+
+ let map_extension_constructor sub
+ {pext_name;
+ pext_kind;
+ pext_loc;
+ pext_attributes} =
+ Te.constructor
+ (map_loc sub pext_name)
+ (map_extension_constructor_kind sub pext_kind)
+ ~loc:(sub.location sub pext_loc)
+ ~attrs:(sub.attributes sub pext_attributes)
+
+end
+
+module CT = struct
+ (* Type expressions for the class language *)
+
+ let map sub {pcty_loc = loc; pcty_desc = desc; pcty_attributes = attrs} =
+ let open Cty in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Pcty_constr (lid, tys) ->
+ constr ~loc ~attrs (map_loc sub lid) (List.map (sub.typ sub) tys)
+ | Pcty_signature x -> signature ~loc ~attrs (sub.class_signature sub x)
+ | Pcty_arrow (lab, t, ct) ->
+ arrow ~loc ~attrs lab (sub.typ sub t) (sub.class_type sub ct)
+ | Pcty_extension x -> extension ~loc ~attrs (sub.extension sub x)
+
+ let map_field sub {pctf_desc = desc; pctf_loc = loc; pctf_attributes = attrs}
+ =
+ let open Ctf in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Pctf_inherit ct -> inherit_ ~loc ~attrs (sub.class_type sub ct)
+ | Pctf_val (s, m, v, t) -> val_ ~loc ~attrs s m v (sub.typ sub t)
+ | Pctf_method (s, p, v, t) -> method_ ~loc ~attrs s p v (sub.typ sub t)
+ | Pctf_constraint (t1, t2) ->
+ constraint_ ~loc ~attrs (sub.typ sub t1) (sub.typ sub t2)
+ | Pctf_attribute x -> attribute ~loc (sub.attribute sub x)
+ | Pctf_extension x -> extension ~loc ~attrs (sub.extension sub x)
+
+ let map_signature sub {pcsig_self; pcsig_fields} =
+ Csig.mk
+ (sub.typ sub pcsig_self)
+ (List.map (sub.class_type_field sub) pcsig_fields)
+end
+
+module MT = struct
+ (* Type expressions for the module language *)
+
+ let map sub {pmty_desc = desc; pmty_loc = loc; pmty_attributes = attrs} =
+ let open Mty in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Pmty_ident s -> ident ~loc ~attrs (map_loc sub s)
+ | Pmty_alias s -> alias ~loc ~attrs (map_loc sub s)
+ | Pmty_signature sg -> signature ~loc ~attrs (sub.signature sub sg)
+ | Pmty_functor (s, mt1, mt2) ->
+ functor_ ~loc ~attrs (map_loc sub s)
+ (Misc.may_map (sub.module_type sub) mt1)
+ (sub.module_type sub mt2)
+ | Pmty_with (mt, l) ->
+ with_ ~loc ~attrs (sub.module_type sub mt)
+ (List.map (sub.with_constraint sub) l)
+ | Pmty_typeof me -> typeof_ ~loc ~attrs (sub.module_expr sub me)
+ | Pmty_extension x -> extension ~loc ~attrs (sub.extension sub x)
+
+ let map_with_constraint sub = function
+ | Pwith_type (lid, d) ->
+ Pwith_type (map_loc sub lid, sub.type_declaration sub d)
+ | Pwith_module (lid, lid2) ->
+ Pwith_module (map_loc sub lid, map_loc sub lid2)
+ | Pwith_typesubst d -> Pwith_typesubst (sub.type_declaration sub d)
+ | Pwith_modsubst (s, lid) ->
+ Pwith_modsubst (map_loc sub s, map_loc sub lid)
+
+ let map_signature_item sub {psig_desc = desc; psig_loc = loc} =
+ let open Sig in
+ let loc = sub.location sub loc in
+ match desc with
+ | Psig_value vd -> value ~loc (sub.value_description sub vd)
+ | Psig_type (rf, l) -> type_ ~loc rf (List.map (sub.type_declaration sub) l)
+ | Psig_typext te -> type_extension ~loc (sub.type_extension sub te)
+ | Psig_exception ed -> exception_ ~loc (sub.extension_constructor sub ed)
+ | Psig_module x -> module_ ~loc (sub.module_declaration sub x)
+ | Psig_recmodule l ->
+ rec_module ~loc (List.map (sub.module_declaration sub) l)
+ | Psig_modtype x -> modtype ~loc (sub.module_type_declaration sub x)
+ | Psig_open x -> open_ ~loc (sub.open_description sub x)
+ | Psig_include x -> include_ ~loc (sub.include_description sub x)
+ | Psig_class l -> class_ ~loc (List.map (sub.class_description sub) l)
+ | Psig_class_type l ->
+ class_type ~loc (List.map (sub.class_type_declaration sub) l)
+ | Psig_extension (x, attrs) ->
+ extension ~loc (sub.extension sub x) ~attrs:(sub.attributes sub attrs)
+ | Psig_attribute x -> attribute ~loc (sub.attribute sub x)
+end
+
+
+module M = struct
+ (* Value expressions for the module language *)
+
+ let map sub {pmod_loc = loc; pmod_desc = desc; pmod_attributes = attrs} =
+ let open Mod in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Pmod_ident x -> ident ~loc ~attrs (map_loc sub x)
+ | Pmod_structure str -> structure ~loc ~attrs (sub.structure sub str)
+ | Pmod_functor (arg, arg_ty, body) ->
+ functor_ ~loc ~attrs (map_loc sub arg)
+ (Misc.may_map (sub.module_type sub) arg_ty)
+ (sub.module_expr sub body)
+ | Pmod_apply (m1, m2) ->
+ apply ~loc ~attrs (sub.module_expr sub m1) (sub.module_expr sub m2)
+ | Pmod_constraint (m, mty) ->
+ constraint_ ~loc ~attrs (sub.module_expr sub m)
+ (sub.module_type sub mty)
+ | Pmod_unpack e -> unpack ~loc ~attrs (sub.expr sub e)
+ | Pmod_extension x -> extension ~loc ~attrs (sub.extension sub x)
+
+ let map_structure_item sub {pstr_loc = loc; pstr_desc = desc} =
+ let open Str in
+ let loc = sub.location sub loc in
+ match desc with
+ | Pstr_eval (x, attrs) ->
+ eval ~loc ~attrs:(sub.attributes sub attrs) (sub.expr sub x)
+ | Pstr_value (r, vbs) -> value ~loc r (List.map (sub.value_binding sub) vbs)
+ | Pstr_primitive vd -> primitive ~loc (sub.value_description sub vd)
+ | Pstr_type (rf, l) -> type_ ~loc rf (List.map (sub.type_declaration sub) l)
+ | Pstr_typext te -> type_extension ~loc (sub.type_extension sub te)
+ | Pstr_exception ed -> exception_ ~loc (sub.extension_constructor sub ed)
+ | Pstr_module x -> module_ ~loc (sub.module_binding sub x)
+ | Pstr_recmodule l -> rec_module ~loc (List.map (sub.module_binding sub) l)
+ | Pstr_modtype x -> modtype ~loc (sub.module_type_declaration sub x)
+ | Pstr_open x -> open_ ~loc (sub.open_description sub x)
+ | Pstr_class l -> class_ ~loc (List.map (sub.class_declaration sub) l)
+ | Pstr_class_type l ->
+ class_type ~loc (List.map (sub.class_type_declaration sub) l)
+ | Pstr_include x -> include_ ~loc (sub.include_declaration sub x)
+ | Pstr_extension (x, attrs) ->
+ extension ~loc (sub.extension sub x) ~attrs:(sub.attributes sub attrs)
+ | Pstr_attribute x -> attribute ~loc (sub.attribute sub x)
+end
+
+module E = struct
+ (* Value expressions for the core language *)
+
+ let map sub {pexp_loc = loc; pexp_desc = desc; pexp_attributes = attrs} =
+ let open Exp in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Pexp_ident x -> ident ~loc ~attrs (map_loc sub x)
+ | Pexp_constant x -> constant ~loc ~attrs x
+ | Pexp_let (r, vbs, e) ->
+ let_ ~loc ~attrs r (List.map (sub.value_binding sub) vbs)
+ (sub.expr sub e)
+ | Pexp_fun (lab, def, p, e) ->
+ fun_ ~loc ~attrs lab (map_opt (sub.expr sub) def) (sub.pat sub p)
+ (sub.expr sub e)
+ | Pexp_function pel -> function_ ~loc ~attrs (sub.cases sub pel)
+ | Pexp_apply (e, l) ->
+ apply ~loc ~attrs (sub.expr sub e) (List.map (map_snd (sub.expr sub)) l)
+ | Pexp_match (e, pel) ->
+ match_ ~loc ~attrs (sub.expr sub e) (sub.cases sub pel)
+ | Pexp_try (e, pel) -> try_ ~loc ~attrs (sub.expr sub e) (sub.cases sub pel)
+ | Pexp_tuple el -> tuple ~loc ~attrs (List.map (sub.expr sub) el)
+ | Pexp_construct (lid, arg) ->
+ construct ~loc ~attrs (map_loc sub lid) (map_opt (sub.expr sub) arg)
+ | Pexp_variant (lab, eo) ->
+ variant ~loc ~attrs lab (map_opt (sub.expr sub) eo)
+ | Pexp_record (l, eo) ->
+ record ~loc ~attrs (List.map (map_tuple (map_loc sub) (sub.expr sub)) l)
+ (map_opt (sub.expr sub) eo)
+ | Pexp_field (e, lid) ->
+ field ~loc ~attrs (sub.expr sub e) (map_loc sub lid)
+ | Pexp_setfield (e1, lid, e2) ->
+ setfield ~loc ~attrs (sub.expr sub e1) (map_loc sub lid)
+ (sub.expr sub e2)
+ | Pexp_array el -> array ~loc ~attrs (List.map (sub.expr sub) el)
+ | Pexp_ifthenelse (e1, e2, e3) ->
+ ifthenelse ~loc ~attrs (sub.expr sub e1) (sub.expr sub e2)
+ (map_opt (sub.expr sub) e3)
+ | Pexp_sequence (e1, e2) ->
+ sequence ~loc ~attrs (sub.expr sub e1) (sub.expr sub e2)
+ | Pexp_while (e1, e2) ->
+ while_ ~loc ~attrs (sub.expr sub e1) (sub.expr sub e2)
+ | Pexp_for (p, e1, e2, d, e3) ->
+ for_ ~loc ~attrs (sub.pat sub p) (sub.expr sub e1) (sub.expr sub e2) d
+ (sub.expr sub e3)
+ | Pexp_coerce (e, t1, t2) ->
+ coerce ~loc ~attrs (sub.expr sub e) (map_opt (sub.typ sub) t1)
+ (sub.typ sub t2)
+ | Pexp_constraint (e, t) ->
+ constraint_ ~loc ~attrs (sub.expr sub e) (sub.typ sub t)
+ | Pexp_send (e, s) -> send ~loc ~attrs (sub.expr sub e) s
+ | Pexp_new lid -> new_ ~loc ~attrs (map_loc sub lid)
+ | Pexp_setinstvar (s, e) ->
+ setinstvar ~loc ~attrs (map_loc sub s) (sub.expr sub e)
+ | Pexp_override sel ->
+ override ~loc ~attrs
+ (List.map (map_tuple (map_loc sub) (sub.expr sub)) sel)
+ | Pexp_letmodule (s, me, e) ->
+ letmodule ~loc ~attrs (map_loc sub s) (sub.module_expr sub me)
+ (sub.expr sub e)
+ | Pexp_assert e -> assert_ ~loc ~attrs (sub.expr sub e)
+ | Pexp_lazy e -> lazy_ ~loc ~attrs (sub.expr sub e)
+ | Pexp_poly (e, t) ->
+ poly ~loc ~attrs (sub.expr sub e) (map_opt (sub.typ sub) t)
+ | Pexp_object cls -> object_ ~loc ~attrs (sub.class_structure sub cls)
+ | Pexp_newtype (s, e) -> newtype ~loc ~attrs s (sub.expr sub e)
+ | Pexp_pack me -> pack ~loc ~attrs (sub.module_expr sub me)
+ | Pexp_open (ovf, lid, e) ->
+ open_ ~loc ~attrs ovf (map_loc sub lid) (sub.expr sub e)
+ | Pexp_extension x -> extension ~loc ~attrs (sub.extension sub x)
+end
+
+module P = struct
+ (* Patterns *)
+
+ let map sub {ppat_desc = desc; ppat_loc = loc; ppat_attributes = attrs} =
+ let open Pat in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Ppat_any -> any ~loc ~attrs ()
+ | Ppat_var s -> var ~loc ~attrs (map_loc sub s)
+ | Ppat_alias (p, s) -> alias ~loc ~attrs (sub.pat sub p) (map_loc sub s)
+ | Ppat_constant c -> constant ~loc ~attrs c
+ | Ppat_interval (c1, c2) -> interval ~loc ~attrs c1 c2
+ | Ppat_tuple pl -> tuple ~loc ~attrs (List.map (sub.pat sub) pl)
+ | Ppat_construct (l, p) ->
+ construct ~loc ~attrs (map_loc sub l) (map_opt (sub.pat sub) p)
+ | Ppat_variant (l, p) -> variant ~loc ~attrs l (map_opt (sub.pat sub) p)
+ | Ppat_record (lpl, cf) ->
+ record ~loc ~attrs
+ (List.map (map_tuple (map_loc sub) (sub.pat sub)) lpl) cf
+ | Ppat_array pl -> array ~loc ~attrs (List.map (sub.pat sub) pl)
+ | Ppat_or (p1, p2) -> or_ ~loc ~attrs (sub.pat sub p1) (sub.pat sub p2)
+ | Ppat_constraint (p, t) ->
+ constraint_ ~loc ~attrs (sub.pat sub p) (sub.typ sub t)
+ | Ppat_type s -> type_ ~loc ~attrs (map_loc sub s)
+ | Ppat_lazy p -> lazy_ ~loc ~attrs (sub.pat sub p)
+ | Ppat_unpack s -> unpack ~loc ~attrs (map_loc sub s)
+ | Ppat_exception p -> exception_ ~loc ~attrs (sub.pat sub p)
+ | Ppat_extension x -> extension ~loc ~attrs (sub.extension sub x)
+end
+
+module CE = struct
+ (* Value expressions for the class language *)
+
+ let map sub {pcl_loc = loc; pcl_desc = desc; pcl_attributes = attrs} =
+ let open Cl in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Pcl_constr (lid, tys) ->
+ constr ~loc ~attrs (map_loc sub lid) (List.map (sub.typ sub) tys)
+ | Pcl_structure s ->
+ structure ~loc ~attrs (sub.class_structure sub s)
+ | Pcl_fun (lab, e, p, ce) ->
+ fun_ ~loc ~attrs lab
+ (map_opt (sub.expr sub) e)
+ (sub.pat sub p)
+ (sub.class_expr sub ce)
+ | Pcl_apply (ce, l) ->
+ apply ~loc ~attrs (sub.class_expr sub ce)
+ (List.map (map_snd (sub.expr sub)) l)
+ | Pcl_let (r, vbs, ce) ->
+ let_ ~loc ~attrs r (List.map (sub.value_binding sub) vbs)
+ (sub.class_expr sub ce)
+ | Pcl_constraint (ce, ct) ->
+ constraint_ ~loc ~attrs (sub.class_expr sub ce) (sub.class_type sub ct)
+ | Pcl_extension x -> extension ~loc ~attrs (sub.extension sub x)
+
+ let map_kind sub = function
+ | Cfk_concrete (o, e) -> Cfk_concrete (o, sub.expr sub e)
+ | Cfk_virtual t -> Cfk_virtual (sub.typ sub t)
+
+ let map_field sub {pcf_desc = desc; pcf_loc = loc; pcf_attributes = attrs} =
+ let open Cf in
+ let loc = sub.location sub loc in
+ let attrs = sub.attributes sub attrs in
+ match desc with
+ | Pcf_inherit (o, ce, s) -> inherit_ ~loc ~attrs o (sub.class_expr sub ce) s
+ | Pcf_val (s, m, k) -> val_ ~loc ~attrs (map_loc sub s) m (map_kind sub k)
+ | Pcf_method (s, p, k) ->
+ method_ ~loc ~attrs (map_loc sub s) p (map_kind sub k)
+ | Pcf_constraint (t1, t2) ->
+ constraint_ ~loc ~attrs (sub.typ sub t1) (sub.typ sub t2)
+ | Pcf_initializer e -> initializer_ ~loc ~attrs (sub.expr sub e)
+ | Pcf_attribute x -> attribute ~loc (sub.attribute sub x)
+ | Pcf_extension x -> extension ~loc ~attrs (sub.extension sub x)
+
+ let map_structure sub {pcstr_self; pcstr_fields} =
+ {
+ pcstr_self = sub.pat sub pcstr_self;
+ pcstr_fields = List.map (sub.class_field sub) pcstr_fields;
+ }
+
+ let class_infos sub f {pci_virt; pci_params = pl; pci_name; pci_expr;
+ pci_loc; pci_attributes} =
+ Ci.mk
+ ~virt:pci_virt
+ ~params:(List.map (map_fst (sub.typ sub)) pl)
+ (map_loc sub pci_name)
+ (f pci_expr)
+ ~loc:(sub.location sub pci_loc)
+ ~attrs:(sub.attributes sub pci_attributes)
+end
+
+(* Now, a generic AST mapper, to be extended to cover all kinds and
+ cases of the OCaml grammar. The default behavior of the mapper is
+ the identity. *)
+
+let default_mapper =
+ {
+ structure = (fun this l -> List.map (this.structure_item this) l);
+ structure_item = M.map_structure_item;
+ module_expr = M.map;
+ signature = (fun this l -> List.map (this.signature_item this) l);
+ signature_item = MT.map_signature_item;
+ module_type = MT.map;
+ with_constraint = MT.map_with_constraint;
+ class_declaration =
+ (fun this -> CE.class_infos this (this.class_expr this));
+ class_expr = CE.map;
+ class_field = CE.map_field;
+ class_structure = CE.map_structure;
+ class_type = CT.map;
+ class_type_field = CT.map_field;
+ class_signature = CT.map_signature;
+ class_type_declaration =
+ (fun this -> CE.class_infos this (this.class_type this));
+ class_description =
+ (fun this -> CE.class_infos this (this.class_type this));
+ type_declaration = T.map_type_declaration;
+ type_kind = T.map_type_kind;
+ typ = T.map;
+ type_extension = T.map_type_extension;
+ extension_constructor = T.map_extension_constructor;
+ value_description =
+ (fun this {pval_name; pval_type; pval_prim; pval_loc;
+ pval_attributes} ->
+ Val.mk
+ (map_loc this pval_name)
+ (this.typ this pval_type)
+ ~attrs:(this.attributes this pval_attributes)
+ ~loc:(this.location this pval_loc)
+ ~prim:pval_prim
+ );
+
+ pat = P.map;
+ expr = E.map;
+
+ module_declaration =
+ (fun this {pmd_name; pmd_type; pmd_attributes; pmd_loc} ->
+ Md.mk
+ (map_loc this pmd_name)
+ (this.module_type this pmd_type)
+ ~attrs:(this.attributes this pmd_attributes)
+ ~loc:(this.location this pmd_loc)
+ );
+
+ module_type_declaration =
+ (fun this {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} ->
+ Mtd.mk
+ (map_loc this pmtd_name)
+ ?typ:(map_opt (this.module_type this) pmtd_type)
+ ~attrs:(this.attributes this pmtd_attributes)
+ ~loc:(this.location this pmtd_loc)
+ );
+
+ module_binding =
+ (fun this {pmb_name; pmb_expr; pmb_attributes; pmb_loc} ->
+ Mb.mk (map_loc this pmb_name) (this.module_expr this pmb_expr)
+ ~attrs:(this.attributes this pmb_attributes)
+ ~loc:(this.location this pmb_loc)
+ );
+
+
+ open_description =
+ (fun this {popen_lid; popen_override; popen_attributes; popen_loc} ->
+ Opn.mk (map_loc this popen_lid)
+ ~override:popen_override
+ ~loc:(this.location this popen_loc)
+ ~attrs:(this.attributes this popen_attributes)
+ );
+
+
+ include_description =
+ (fun this {pincl_mod; pincl_attributes; pincl_loc} ->
+ Incl.mk (this.module_type this pincl_mod)
+ ~loc:(this.location this pincl_loc)
+ ~attrs:(this.attributes this pincl_attributes)
+ );
+
+ include_declaration =
+ (fun this {pincl_mod; pincl_attributes; pincl_loc} ->
+ Incl.mk (this.module_expr this pincl_mod)
+ ~loc:(this.location this pincl_loc)
+ ~attrs:(this.attributes this pincl_attributes)
+ );
+
+
+ value_binding =
+ (fun this {pvb_pat; pvb_expr; pvb_attributes; pvb_loc} ->
+ Vb.mk
+ (this.pat this pvb_pat)
+ (this.expr this pvb_expr)
+ ~loc:(this.location this pvb_loc)
+ ~attrs:(this.attributes this pvb_attributes)
+ );
+
+
+ constructor_declaration =
+ (fun this {pcd_name; pcd_args; pcd_res; pcd_loc; pcd_attributes} ->
+ Type.constructor
+ (map_loc this pcd_name)
+ ~args:(T.map_constructor_arguments this pcd_args)
+ ?res:(map_opt (this.typ this) pcd_res)
+ ~loc:(this.location this pcd_loc)
+ ~attrs:(this.attributes this pcd_attributes)
+ );
+
+ label_declaration =
+ (fun this {pld_name; pld_type; pld_loc; pld_mutable; pld_attributes} ->
+ Type.field
+ (map_loc this pld_name)
+ (this.typ this pld_type)
+ ~mut:pld_mutable
+ ~loc:(this.location this pld_loc)
+ ~attrs:(this.attributes this pld_attributes)
+ );
+
+ cases = (fun this l -> List.map (this.case this) l);
+ case =
+ (fun this {pc_lhs; pc_guard; pc_rhs} ->
+ {
+ pc_lhs = this.pat this pc_lhs;
+ pc_guard = map_opt (this.expr this) pc_guard;
+ pc_rhs = this.expr this pc_rhs;
+ }
+ );
+
+
+
+ location = (fun this l -> l);
+
+ extension = (fun this (s, e) -> (map_loc this s, this.payload this e));
+ attribute = (fun this (s, e) -> (map_loc this s, this.payload this e));
+ attributes = (fun this l -> List.map (this.attribute this) l);
+ payload =
+ (fun this -> function
+ | PStr x -> PStr (this.structure this x)
+ | PTyp x -> PTyp (this.typ this x)
+ | PPat (x, g) -> PPat (this.pat this x, map_opt (this.expr this) g)
+ );
+ }
+
+let rec extension_of_error {loc; msg; if_highlight; sub} =
+ { loc; txt = "ocaml.error" },
+ PStr ([Str.eval (Exp.constant (Const_string (msg, None)));
+ Str.eval (Exp.constant (Const_string (if_highlight, None)))] @
+ (List.map (fun ext -> Str.extension (extension_of_error ext)) sub))
+
+let attribute_of_warning loc s =
+ { loc; txt = "ocaml.ppwarning" },
+ PStr ([Str.eval ~loc (Exp.constant (Const_string (s, None)))])
+
+module StringMap = Map.Make(struct
+ type t = string
+ let compare = compare
+end)
+
+let cookies = ref StringMap.empty
+
+let get_cookie k =
+ try Some (StringMap.find k !cookies)
+ with Not_found -> None
+
+let set_cookie k v =
+ cookies := StringMap.add k v !cookies
+
+let tool_name_ref = ref "_none_"
+
+let tool_name () = !tool_name_ref
+
+
+module PpxContext = struct
+ open Longident
+ open Asttypes
+ open Ast_helper
+
+ let lid name = { txt = Lident name; loc = Location.none }
+
+ let make_string x = Exp.constant (Const_string (x, None))
+
+ let make_bool x =
+ if x
+ then Exp.construct (lid "true") None
+ else Exp.construct (lid "false") None
+
+ let rec make_list f lst =
+ match lst with
+ | x :: rest ->
+ Exp.construct (lid "::") (Some (Exp.tuple [f x; make_list f rest]))
+ | [] ->
+ Exp.construct (lid "[]") None
+
+ let make_pair f1 f2 (x1, x2) =
+ Exp.tuple [f1 x1; f2 x2]
+
+ let make_option f opt =
+ match opt with
+ | Some x -> Exp.construct (lid "Some") (Some (f x))
+ | None -> Exp.construct (lid "None") None
+
+ let get_cookies () =
+ lid "cookies",
+ make_list (make_pair make_string (fun x -> x))
+ (StringMap.bindings !cookies)
+
+ let mk fields =
+ { txt = "ocaml.ppx.context"; loc = Location.none },
+ Parsetree.PStr [Str.eval (Exp.record fields None)]
+
+ let make ~tool_name () =
+ let fields =
+ [
+ lid "tool_name", make_string tool_name;
+ lid "include_dirs", make_list make_string !Clflags.include_dirs;
+ lid "load_path", make_list make_string !Config.load_path;
+ lid "open_modules", make_list make_string !Clflags.open_modules;
+ lid "for_package", make_option make_string !Clflags.for_package;
+ lid "debug", make_bool !Clflags.debug;
+ get_cookies ()
+ ]
+ in
+ mk fields
+
+ let get_fields = function
+ | PStr [{pstr_desc = Pstr_eval
+ ({ pexp_desc = Pexp_record (fields, None) }, [])}] ->
+ fields
+ | _ ->
+ raise_errorf "Internal error: invalid [@@@ocaml.ppx.context] syntax"
+
+ let restore fields =
+ let field name payload =
+ let rec get_string = function
+ | { pexp_desc = Pexp_constant (Const_string (str, None)) } -> str
+ | _ -> raise_errorf "Internal error: invalid [@@@ocaml.ppx.context \
+ { %s }] string syntax" name
+ and get_bool pexp =
+ match pexp with
+ | {pexp_desc = Pexp_construct ({txt = Longident.Lident "true"},
+ None)} ->
+ true
+ | {pexp_desc = Pexp_construct ({txt = Longident.Lident "false"},
+ None)} ->
+ false
+ | _ -> raise_errorf "Internal error: invalid [@@@ocaml.ppx.context \
+ { %s }] bool syntax" name
+ and get_list elem = function
+ | {pexp_desc =
+ Pexp_construct ({txt = Longident.Lident "::"},
+ Some {pexp_desc = Pexp_tuple [exp; rest]}) } ->
+ elem exp :: get_list elem rest
+ | {pexp_desc =
+ Pexp_construct ({txt = Longident.Lident "[]"}, None)} ->
+ []
+ | _ -> raise_errorf "Internal error: invalid [@@@ocaml.ppx.context \
+ { %s }] list syntax" name
+ and get_pair f1 f2 = function
+ | {pexp_desc = Pexp_tuple [e1; e2]} ->
+ (f1 e1, f2 e2)
+ | _ -> raise_errorf "Internal error: invalid [@@@ocaml.ppx.context \
+ { %s }] pair syntax" name
+ and get_option elem = function
+ | { pexp_desc =
+ Pexp_construct ({ txt = Longident.Lident "Some" }, Some exp) } ->
+ Some (elem exp)
+ | { pexp_desc =
+ Pexp_construct ({ txt = Longident.Lident "None" }, None) } ->
+ None
+ | _ -> raise_errorf "Internal error: invalid [@@@ocaml.ppx.context \
+ { %s }] option syntax" name
+ in
+ match name with
+ | "tool_name" ->
+ tool_name_ref := get_string payload
+ | "include_dirs" ->
+ Clflags.include_dirs := get_list get_string payload
+ | "load_path" ->
+ Config.load_path := get_list get_string payload
+ | "open_modules" ->
+ Clflags.open_modules := get_list get_string payload
+ | "for_package" ->
+ Clflags.for_package := get_option get_string payload
+ | "debug" ->
+ Clflags.debug := get_bool payload
+ | "cookies" ->
+ let l = get_list (get_pair get_string (fun x -> x)) payload in
+ cookies :=
+ List.fold_left
+ (fun s (k, v) -> StringMap.add k v s) StringMap.empty
+ l
+ | _ ->
+ ()
+ in
+ List.iter (function ({txt=Lident name}, x) -> field name x | _ -> ()) fields
+
+ let update_cookies fields =
+ let fields =
+ List.filter
+ (function ({txt=Lident "cookies"}, _) -> false | _ -> true)
+ fields
+ in
+ fields @ [get_cookies ()]
+end
+
+let ppx_context = PpxContext.make
+
+
+let apply_lazy ~source ~target mapper =
+ let implem ast =
+ try
+ let fields, ast =
+ match ast with
+ | {pstr_desc = Pstr_attribute ({txt = "ocaml.ppx.context"}, x)} :: l ->
+ PpxContext.get_fields x, l
+ | _ -> [], ast
+ in
+ PpxContext.restore fields;
+ let mapper = mapper () in
+ let ast = mapper.structure mapper ast in
+ let fields = PpxContext.update_cookies fields in
+ Str.attribute (PpxContext.mk fields) :: ast
+ with exn ->
+ match error_of_exn exn with
+ | Some error ->
+ [{pstr_desc = Pstr_extension (extension_of_error error, []);
+ pstr_loc = Location.none}]
+ | None -> raise exn
+ in
+ let iface ast =
+ try
+ let fields, ast =
+ match ast with
+ | {psig_desc = Psig_attribute ({txt = "ocaml.ppx.context"}, x)} :: l ->
+ PpxContext.get_fields x, l
+ | _ -> [], ast
+ in
+ PpxContext.restore fields;
+ let mapper = mapper () in
+ let ast = mapper.signature mapper ast in
+ let fields = PpxContext.update_cookies fields in
+ Sig.attribute (PpxContext.mk fields) :: ast
+ with exn ->
+ match error_of_exn exn with
+ | Some error ->
+ [{psig_desc = Psig_extension (extension_of_error error, []);
+ psig_loc = Location.none}]
+ | None -> raise exn
+ in
+
+ let ic = open_in_bin source in
+ let magic =
+ really_input_string ic (String.length Config.ast_impl_magic_number)
+ in
+
+ let rewrite transform =
+ Location.input_name := input_value ic;
+ let ast = input_value ic in
+ close_in ic;
+ let ast = transform ast in
+ let oc = open_out_bin target in
+ output_string oc magic;
+ output_value oc !Location.input_name;
+ output_value oc ast;
+ close_out oc
+ and fail () =
+ close_in ic;
+ failwith "Ast_mapper: OCaml version mismatch or malformed input";
+ in
+
+ if magic = Config.ast_impl_magic_number then
+ rewrite (implem : structure -> structure)
+ else if magic = Config.ast_intf_magic_number then
+ rewrite (iface : signature -> signature)
+ else fail ()
+
+let drop_ppx_context_str ~restore = function
+ | {pstr_desc = Pstr_attribute({Location.txt = "ocaml.ppx.context"}, a)}
+ :: items ->
+ if restore then
+ PpxContext.restore (PpxContext.get_fields a);
+ items
+ | items -> items
+
+let drop_ppx_context_sig ~restore = function
+ | {psig_desc = Psig_attribute({Location.txt = "ocaml.ppx.context"}, a)}
+ :: items ->
+ if restore then
+ PpxContext.restore (PpxContext.get_fields a);
+ items
+ | items -> items
+
+let add_ppx_context_str ~tool_name ast =
+ Ast_helper.Str.attribute (ppx_context ~tool_name ()) :: ast
+
+let add_ppx_context_sig ~tool_name ast =
+ Ast_helper.Sig.attribute (ppx_context ~tool_name ()) :: ast
+
+
+let apply ~source ~target mapper =
+ apply_lazy ~source ~target (fun () -> mapper)
+
+let run_main mapper =
+ try
+ let a = Sys.argv in
+ let n = Array.length a in
+ if n > 2 then
+ let mapper () =
+ try mapper (Array.to_list (Array.sub a 1 (n - 3)))
+ with exn ->
+ (* PR #6463 *)
+ let f _ _ = raise exn in
+ {default_mapper with structure = f; signature = f}
+ in
+ apply_lazy ~source:a.(n - 2) ~target:a.(n - 1) mapper
+ else begin
+ Printf.eprintf "Usage: %s [extra_args] <infile> <outfile>\n%!"
+ Sys.executable_name;
+ exit 2
+ end
+ with exn ->
+ prerr_endline (Printexc.to_string exn);
+ exit 2
+
+let register_function = ref (fun _name f -> run_main f)
+let register name f = !register_function name f
diff --git a/parsing/ast_mapper.mli b/parsing/ast_mapper.mli
new file mode 100644
index 0000000000..2dc301fb09
--- /dev/null
+++ b/parsing/ast_mapper.mli
@@ -0,0 +1,197 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** The interface of a -ppx rewriter
+
+ A -ppx rewriter is a program that accepts a serialized abstract syntax
+ tree and outputs another, possibly modified, abstract syntax tree.
+ This module encapsulates the interface between the compiler and
+ the -ppx rewriters, handling such details as the serialization format,
+ forwarding of command-line flags, and storing state.
+
+ {!mapper} allows to implement AST rewriting using open recursion.
+ A typical mapper would be based on {!default_mapper}, a deep
+ identity mapper, and will fall back on it for handling the syntax it
+ does not modify. For example:
+
+ {[
+open Asttypes
+open Parsetree
+open Ast_mapper
+
+let test_mapper argv =
+ { default_mapper with
+ expr = fun mapper expr ->
+ match expr with
+ | { pexp_desc = Pexp_extension ({ txt = "test" }, PStr [])} ->
+ Ast_helper.Exp.constant (Const_int 42)
+ | other -> default_mapper.expr mapper other; }
+
+let () =
+ register "ppx_test" test_mapper]}
+
+ This -ppx rewriter, which replaces [[%test]] in expressions with
+ the constant [42], can be compiled using
+ [ocamlc -o ppx_test -I +compiler-libs ocamlcommon.cma ppx_test.ml].
+
+ *)
+
+open Parsetree
+
+(** {2 A generic Parsetree mapper} *)
+
+type mapper = {
+ attribute: mapper -> attribute -> attribute;
+ attributes: mapper -> attribute list -> attribute list;
+ case: mapper -> case -> case;
+ cases: mapper -> case list -> case list;
+ class_declaration: mapper -> class_declaration -> class_declaration;
+ class_description: mapper -> class_description -> class_description;
+ class_expr: mapper -> class_expr -> class_expr;
+ class_field: mapper -> class_field -> class_field;
+ class_signature: mapper -> class_signature -> class_signature;
+ class_structure: mapper -> class_structure -> class_structure;
+ class_type: mapper -> class_type -> class_type;
+ class_type_declaration: mapper -> class_type_declaration
+ -> class_type_declaration;
+ class_type_field: mapper -> class_type_field -> class_type_field;
+ constructor_declaration: mapper -> constructor_declaration
+ -> constructor_declaration;
+ expr: mapper -> expression -> expression;
+ extension: mapper -> extension -> extension;
+ extension_constructor: mapper -> extension_constructor
+ -> extension_constructor;
+ include_declaration: mapper -> include_declaration -> include_declaration;
+ include_description: mapper -> include_description -> include_description;
+ label_declaration: mapper -> label_declaration -> label_declaration;
+ location: mapper -> Location.t -> Location.t;
+ module_binding: mapper -> module_binding -> module_binding;
+ module_declaration: mapper -> module_declaration -> module_declaration;
+ module_expr: mapper -> module_expr -> module_expr;
+ module_type: mapper -> module_type -> module_type;
+ module_type_declaration: mapper -> module_type_declaration
+ -> module_type_declaration;
+ open_description: mapper -> open_description -> open_description;
+ pat: mapper -> pattern -> pattern;
+ payload: mapper -> payload -> payload;
+ signature: mapper -> signature -> signature;
+ signature_item: mapper -> signature_item -> signature_item;
+ structure: mapper -> structure -> structure;
+ structure_item: mapper -> structure_item -> structure_item;
+ typ: mapper -> core_type -> core_type;
+ type_declaration: mapper -> type_declaration -> type_declaration;
+ type_extension: mapper -> type_extension -> type_extension;
+ type_kind: mapper -> type_kind -> type_kind;
+ value_binding: mapper -> value_binding -> value_binding;
+ value_description: mapper -> value_description -> value_description;
+ with_constraint: mapper -> with_constraint -> with_constraint;
+}
+(** A mapper record implements one "method" per syntactic category,
+ using an open recursion style: each method takes as its first
+ argument the mapper to be applied to children in the syntax
+ tree. *)
+
+val default_mapper: mapper
+(** A default mapper, which implements a "deep identity" mapping. *)
+
+(** {2 Apply mappers to compilation units} *)
+
+val tool_name: unit -> string
+(** Can be used within a ppx preprocessor to know which tool is
+ calling it ["ocamlc"], ["ocamlopt"], ["ocamldoc"], ["ocamldep"],
+ ["ocaml"], ... Some global variables that reflect command-line
+ options are automatically synchronized between the calling tool
+ and the ppx preprocessor: [Clflags.include_dirs],
+ [Config.load_path], [Clflags.open_modules], [Clflags.for_package],
+ [Clflags.debug]. *)
+
+
+val apply: source:string -> target:string -> mapper -> unit
+(** Apply a mapper (parametrized by the unit name) to a dumped
+ parsetree found in the [source] file and put the result in the
+ [target] file. The [structure] or [signature] field of the mapper
+ is applied to the implementation or interface. *)
+
+val run_main: (string list -> mapper) -> unit
+(** Entry point to call to implement a standalone -ppx rewriter from a
+ mapper, parametrized by the command line arguments. The current
+ unit name can be obtained from [Location.input_name]. This
+ function implements proper error reporting for uncaught
+ exceptions. *)
+
+(** {2 Registration API} *)
+
+val register_function: (string -> (string list -> mapper) -> unit) ref
+
+val register: string -> (string list -> mapper) -> unit
+(** Apply the [register_function]. The default behavior is to run the
+ mapper immediately, taking arguments from the process command
+ line. This is to support a scenario where a mapper is linked as a
+ stand-alone executable.
+
+ It is possible to overwrite the [register_function] to define
+ "-ppx drivers", which combine several mappers in a single process.
+ Typically, a driver starts by defining [register_function] to a
+ custom implementation, then lets ppx rewriters (linked statically
+ or dynamically) register themselves, and then run all or some of
+ them. It is also possible to have -ppx drivers apply rewriters to
+ only specific parts of an AST.
+
+ The first argument to [register] is a symbolic name to be used by
+ the ppx driver. *)
+
+
+(** {2 Convenience functions to write mappers} *)
+
+val map_opt: ('a -> 'b) -> 'a option -> 'b option
+
+val extension_of_error: Location.error -> extension
+(** Encode an error into an 'ocaml.error' extension node which can be
+ inserted in a generated Parsetree. The compiler will be
+ responsible for reporting the error. *)
+
+val attribute_of_warning: Location.t -> string -> attribute
+(** Encode a warning message into an 'ocaml.ppwarning' attribute which can be
+ inserted in a generated Parsetree. The compiler will be
+ responsible for reporting the warning. *)
+
+(** {2 Helper functions to call external mappers} *)
+
+val add_ppx_context_str:
+ tool_name:string -> Parsetree.structure -> Parsetree.structure
+(** Extract information from the current environment and encode it
+ into an attribute which is prepended to the list of structure
+ items in order to pass the information to an external
+ processor. *)
+
+val add_ppx_context_sig:
+ tool_name:string -> Parsetree.signature -> Parsetree.signature
+(** Same as [add_ppx_context_str], but for signatures. *)
+
+val drop_ppx_context_str:
+ restore:bool -> Parsetree.structure -> Parsetree.structure
+(** Drop the ocaml.ppx.context attribute from a structure. If
+ [restore] is true, also restore the associated data in the current
+ process. *)
+
+val drop_ppx_context_sig:
+ restore:bool -> Parsetree.signature -> Parsetree.signature
+(** Same as [drop_ppx_context_str], but for signatures. *)
+
+(** {2 Cookies} *)
+
+(** Cookies are used to pass information from a ppx processor to
+ a further invocation of itself, when called from the OCaml
+ toplevel (or other tools that support cookies). *)
+
+val set_cookie: string -> Parsetree.expression -> unit
+val get_cookie: string -> Parsetree.expression option
diff --git a/parsing/asttypes.mli b/parsing/asttypes.mli
new file mode 100644
index 0000000000..a0d6361623
--- /dev/null
+++ b/parsing/asttypes.mli
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliary a.s.t. types used by parsetree and typedtree. *)
+
+type constant =
+ Const_int of int
+ | Const_char of char
+ | Const_string of string * string option
+ | Const_float of string
+ | Const_int32 of int32
+ | Const_int64 of int64
+ | Const_nativeint of nativeint
+
+type rec_flag = Nonrecursive | Recursive
+
+type direction_flag = Upto | Downto
+
+type private_flag = Private | Public
+
+type mutable_flag = Immutable | Mutable
+
+type virtual_flag = Virtual | Concrete
+
+type override_flag = Override | Fresh
+
+type closed_flag = Closed | Open
+
+type label = string
+
+type arg_label =
+ Nolabel
+ | Labelled of string (* label:T -> ... *)
+ | Optional of string (* ?label:T -> ... *)
+
+type 'a loc = 'a Location.loc = {
+ txt : 'a;
+ loc : Location.t;
+}
+
+
+type variance =
+ | Covariant
+ | Contravariant
+ | Invariant
diff --git a/parsing/docstrings.ml b/parsing/docstrings.ml
new file mode 100644
index 0000000000..acb035c54b
--- /dev/null
+++ b/parsing/docstrings.ml
@@ -0,0 +1,341 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Leo White *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Location
+
+(* Docstrings *)
+
+(* A docstring is "attached" if it has been inserted in the AST. This
+ is used for generating unexpected docstring warnings. *)
+type ds_attached =
+ | Unattached (* Not yet attached anything.*)
+ | Info (* Attached to a field or constructor. *)
+ | Docs (* Attached to an item or as floating text. *)
+
+(* A docstring is "associated" with an item if there are no blank lines between
+ them. This is used for generating docstring ambiguity warnings. *)
+type ds_associated =
+ | Zero (* Not associated with an item *)
+ | One (* Associated with one item *)
+ | Many (* Associated with multiple items (ambiguity) *)
+
+type docstring =
+ { ds_body: string;
+ ds_loc: Location.t;
+ mutable ds_attached: ds_attached;
+ mutable ds_associated: ds_associated; }
+
+(* List of docstrings *)
+
+let docstrings : docstring list ref = ref []
+
+(* Warn for unused and ambiguous docstrings *)
+
+let warn_bad_docstrings () =
+ if Warnings.is_active (Warnings.Bad_docstring true) then begin
+ List.iter
+ (fun ds ->
+ match ds.ds_attached with
+ | Info -> ()
+ | Unattached ->
+ prerr_warning ds.ds_loc (Warnings.Bad_docstring true)
+ | Docs ->
+ match ds.ds_associated with
+ | Zero | One -> ()
+ | Many ->
+ prerr_warning ds.ds_loc (Warnings.Bad_docstring false))
+ (List.rev !docstrings)
+end
+
+(* Docstring constructors and descturctors *)
+
+let docstring body loc =
+ let ds =
+ { ds_body = body;
+ ds_loc = loc;
+ ds_attached = Unattached;
+ ds_associated = Zero; }
+ in
+ docstrings := ds :: !docstrings;
+ ds
+
+let docstring_body ds = ds.ds_body
+
+let docstring_loc ds = ds.ds_loc
+
+(* Docstrings attached to items *)
+
+type docs =
+ { docs_pre: docstring option;
+ docs_post: docstring option; }
+
+let empty_docs = { docs_pre = None; docs_post = None }
+
+let doc_loc = {txt = "ocaml.doc"; loc = Location.none}
+
+let docs_attr ds =
+ let open Asttypes in
+ let open Parsetree in
+ let exp =
+ { pexp_desc = Pexp_constant (Const_string(ds.ds_body, None));
+ pexp_loc = ds.ds_loc;
+ pexp_attributes = []; }
+ in
+ let item =
+ { pstr_desc = Pstr_eval (exp, []); pstr_loc = exp.pexp_loc }
+ in
+ (doc_loc, PStr [item])
+
+let add_docs_attrs docs attrs =
+ let attrs =
+ match docs.docs_pre with
+ | None -> attrs
+ | Some ds -> docs_attr ds :: attrs
+ in
+ let attrs =
+ match docs.docs_post with
+ | None -> attrs
+ | Some ds -> attrs @ [docs_attr ds]
+ in
+ attrs
+
+(* Docstrings attached to consturctors or fields *)
+
+type info = docstring option
+
+let empty_info = None
+
+let info_attr = docs_attr
+
+let add_info_attrs info attrs =
+ let attrs =
+ match info with
+ | None -> attrs
+ | Some ds -> attrs @ [info_attr ds]
+ in
+ attrs
+
+(* Docstrings not attached to a specifc item *)
+
+type text = docstring list
+
+let empty_text = []
+
+let text_loc = {txt = "ocaml.text"; loc = Location.none}
+
+let text_attr ds =
+ let open Asttypes in
+ let open Parsetree in
+ let exp =
+ { pexp_desc = Pexp_constant (Const_string(ds.ds_body, None));
+ pexp_loc = ds.ds_loc;
+ pexp_attributes = []; }
+ in
+ let item =
+ { pstr_desc = Pstr_eval (exp, []); pstr_loc = exp.pexp_loc }
+ in
+ (text_loc, PStr [item])
+
+let add_text_attrs dsl attrs =
+ (List.map text_attr dsl) @ attrs
+
+(* Find the first non-info docstring in a list, attach it and return it *)
+let get_docstring ~info dsl =
+ let rec loop = function
+ | [] -> None
+ | {ds_attached = Info; _} :: rest -> loop rest
+ | ds :: rest ->
+ ds.ds_attached <- if info then Info else Docs;
+ Some ds
+ in
+ loop dsl
+
+(* Find all the non-info docstrings in a list, attach them and return them *)
+let get_docstrings dsl =
+ let rec loop acc = function
+ | [] -> List.rev acc
+ | {ds_attached = Info; _} :: rest -> loop acc rest
+ | ds :: rest ->
+ ds.ds_attached <- Docs;
+ loop (ds :: acc) rest
+ in
+ loop [] dsl
+
+(* "Associate" all the docstrings in a list *)
+let associate_docstrings dsl =
+ List.iter
+ (fun ds ->
+ match ds.ds_associated with
+ | Zero -> ds.ds_associated <- One
+ | (One | Many) -> ds.ds_associated <- Many)
+ dsl
+
+(* Map from positions to pre docstrings *)
+
+let pre_table : (Lexing.position, docstring list) Hashtbl.t =
+ Hashtbl.create 50
+
+let set_pre_docstrings pos dsl =
+ if dsl <> [] then Hashtbl.add pre_table pos dsl
+
+let get_pre_docs pos =
+ try
+ let dsl = Hashtbl.find pre_table pos in
+ associate_docstrings dsl;
+ get_docstring ~info:false dsl
+ with Not_found -> None
+
+let mark_pre_docs pos =
+ try
+ let dsl = Hashtbl.find pre_table pos in
+ associate_docstrings dsl
+ with Not_found -> ()
+
+(* Map from positions to post docstrings *)
+
+let post_table : (Lexing.position, docstring list) Hashtbl.t =
+ Hashtbl.create 50
+
+let set_post_docstrings pos dsl =
+ if dsl <> [] then Hashtbl.add post_table pos dsl
+
+let get_post_docs pos =
+ try
+ let dsl = Hashtbl.find post_table pos in
+ associate_docstrings dsl;
+ get_docstring ~info:false dsl
+ with Not_found -> None
+
+let mark_post_docs pos =
+ try
+ let dsl = Hashtbl.find post_table pos in
+ associate_docstrings dsl
+ with Not_found -> ()
+
+let get_info pos =
+ try
+ let dsl = Hashtbl.find post_table pos in
+ get_docstring ~info:true dsl
+ with Not_found -> None
+
+(* Map from positions to floating docstrings *)
+
+let floating_table : (Lexing.position, docstring list) Hashtbl.t =
+ Hashtbl.create 50
+
+let set_floating_docstrings pos dsl =
+ if dsl <> [] then Hashtbl.add floating_table pos dsl
+
+let get_text pos =
+ try
+ let dsl = Hashtbl.find floating_table pos in
+ get_docstrings dsl
+ with Not_found -> []
+
+(* Maps from positions to extra docstrings *)
+
+let pre_extra_table : (Lexing.position, docstring list) Hashtbl.t =
+ Hashtbl.create 50
+
+let set_pre_extra_docstrings pos dsl =
+ if dsl <> [] then Hashtbl.add pre_extra_table pos dsl
+
+let get_pre_extra_text pos =
+ try
+ let dsl = Hashtbl.find pre_extra_table pos in
+ get_docstrings dsl
+ with Not_found -> []
+
+let post_extra_table : (Lexing.position, docstring list) Hashtbl.t =
+ Hashtbl.create 50
+
+let set_post_extra_docstrings pos dsl =
+ if dsl <> [] then Hashtbl.add post_extra_table pos dsl
+
+let get_post_extra_text pos =
+ try
+ let dsl = Hashtbl.find post_extra_table pos in
+ get_docstrings dsl
+ with Not_found -> []
+
+(* Docstrings from parser actions *)
+
+let symbol_docs () =
+ { docs_pre = get_pre_docs (Parsing.symbol_start_pos ());
+ docs_post = get_post_docs (Parsing.symbol_end_pos ()); }
+
+let symbol_docs_lazy () =
+ let p1 = Parsing.symbol_start_pos () in
+ let p2 = Parsing.symbol_end_pos () in
+ lazy { docs_pre = get_pre_docs p1;
+ docs_post = get_post_docs p2; }
+
+let rhs_docs pos1 pos2 =
+ { docs_pre = get_pre_docs (Parsing.rhs_start_pos pos1);
+ docs_post = get_post_docs (Parsing.rhs_end_pos pos2); }
+
+let rhs_docs_lazy pos1 pos2 =
+ let p1 = Parsing.rhs_start_pos pos1 in
+ let p2 = Parsing.rhs_end_pos pos2 in
+ lazy { docs_pre = get_pre_docs p1;
+ docs_post = get_post_docs p2; }
+
+let mark_symbol_docs () =
+ mark_pre_docs (Parsing.symbol_start_pos ());
+ mark_post_docs (Parsing.symbol_end_pos ())
+
+let mark_rhs_docs pos1 pos2 =
+ mark_pre_docs (Parsing.rhs_start_pos pos1);
+ mark_post_docs (Parsing.rhs_end_pos pos2)
+
+let symbol_info () =
+ get_info (Parsing.symbol_end_pos ())
+
+let rhs_info pos =
+ get_info (Parsing.rhs_end_pos pos)
+
+let symbol_text () =
+ get_text (Parsing.symbol_start_pos ())
+
+let symbol_text_lazy () =
+ let pos = Parsing.symbol_start_pos () in
+ lazy (get_text pos)
+
+let rhs_text pos =
+ get_text (Parsing.rhs_start_pos pos)
+
+let rhs_text_lazy pos =
+ let pos = Parsing.rhs_start_pos pos in
+ lazy (get_text pos)
+
+let symbol_pre_extra_text () =
+ get_pre_extra_text (Parsing.symbol_start_pos ())
+
+let symbol_post_extra_text () =
+ get_post_extra_text (Parsing.symbol_end_pos ())
+
+let rhs_pre_extra_text pos =
+ get_pre_extra_text (Parsing.rhs_start_pos pos)
+
+let rhs_post_extra_text pos =
+ get_post_extra_text (Parsing.rhs_end_pos pos)
+
+
+(* (Re)Initialise all comment state *)
+
+let init () =
+ docstrings := [];
+ Hashtbl.reset pre_table;
+ Hashtbl.reset post_table;
+ Hashtbl.reset floating_table;
+ Hashtbl.reset pre_extra_table;
+ Hashtbl.reset post_extra_table
diff --git a/parsing/docstrings.mli b/parsing/docstrings.mli
new file mode 100644
index 0000000000..e873785012
--- /dev/null
+++ b/parsing/docstrings.mli
@@ -0,0 +1,148 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Leo White *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** (Re)Initialise all docstring state *)
+val init : unit -> unit
+
+(** Emit warnings for unattached and ambiguous docstrings *)
+val warn_bad_docstrings : unit -> unit
+
+(** {3 Docstrings} *)
+
+(** Documentation comments *)
+type docstring
+
+(** Create a docstring *)
+val docstring : string -> Location.t -> docstring
+
+(** Get the text of a docstring *)
+val docstring_body : docstring -> string
+
+(** Get the location of a docstring *)
+val docstring_loc : docstring -> Location.t
+
+(** {3 Set functions}
+
+ These functions are used by the lexer to associate docstrings to
+ the locations of tokens. *)
+
+(** Docstrings immediately preceding a token *)
+val set_pre_docstrings : Lexing.position -> docstring list -> unit
+
+(** Docstrings immediately following a token *)
+val set_post_docstrings : Lexing.position -> docstring list -> unit
+
+(** Docstrings not immediately adjacent to a token *)
+val set_floating_docstrings : Lexing.position -> docstring list -> unit
+
+(** Docstrings immediately following the token which precedes this one *)
+val set_pre_extra_docstrings : Lexing.position -> docstring list -> unit
+
+(** Docstrings immediately preceding the token which follows this one *)
+val set_post_extra_docstrings : Lexing.position -> docstring list -> unit
+
+(** {3 Items}
+
+ The {!docs} type represents documentation attached to an item. *)
+
+type docs =
+ { docs_pre: docstring option;
+ docs_post: docstring option; }
+
+val empty_docs : docs
+
+val docs_attr : docstring -> Parsetree.attribute
+
+(** Convert item documentation to attributes and add them to an
+ attribute list *)
+val add_docs_attrs : docs -> Parsetree.attributes -> Parsetree.attributes
+
+(** Fetch the item documentation for the current symbol. This also
+ marks this documentation (for ambiguity warnings). *)
+val symbol_docs : unit -> docs
+val symbol_docs_lazy : unit -> docs Lazy.t
+
+(** Fetch the item documentation for the symbols between two
+ positions. This also marks this documentation (for ambiguity
+ warnings). *)
+val rhs_docs : int -> int -> docs
+val rhs_docs_lazy : int -> int -> docs Lazy.t
+
+(** Mark the item documentation for the current symbol (for ambiguity
+ warnings). *)
+val mark_symbol_docs : unit -> unit
+
+(** Mark as associated the item documentation for the symbols between
+ two positions (for ambiguity warnings) *)
+val mark_rhs_docs : int -> int -> unit
+
+(** {3 Fields and constructors}
+
+ The {!info} type represents documentation attached to a field or
+ constructor. *)
+
+type info = docstring option
+
+val empty_info : info
+
+val info_attr : docstring -> Parsetree.attribute
+
+(** Convert field info to attributes and add them to an
+ attribute list *)
+val add_info_attrs : info -> Parsetree.attributes -> Parsetree.attributes
+
+(** Fetch the field info for the current symbol. *)
+val symbol_info : unit -> info
+
+(** Fetch the field info following the symbol at a given position. *)
+val rhs_info : int -> info
+
+(** {3 Unattached comments}
+
+ The {!text} type represents documentation which is not attached to
+ anything. *)
+
+type text = docstring list
+
+val empty_text : text
+
+val text_attr : docstring -> Parsetree.attribute
+
+(** Convert text to attributes and add them to an attribute list *)
+val add_text_attrs : text -> Parsetree.attributes -> Parsetree.attributes
+
+(** Fetch the text preceding the current symbol. *)
+val symbol_text : unit -> text
+val symbol_text_lazy : unit -> text Lazy.t
+
+(** Fetch the text preceding the symbol at the given position. *)
+val rhs_text : int -> text
+val rhs_text_lazy : int -> text Lazy.t
+
+(** {3 Extra text}
+
+ There may be additional text attached to the delimiters of a block
+ (e.g. [struct] and [end]). This is fetched by the following
+ functions, which are applied to the contents of the block rather
+ than the delimiters. *)
+
+(** Fetch additional text preceding the current symbol *)
+val symbol_pre_extra_text : unit -> text
+
+(** Fetch additional text following the current symbol *)
+val symbol_post_extra_text : unit -> text
+
+(** Fetch additional text preceding the symbol at the given position *)
+val rhs_pre_extra_text : int -> text
+
+(** Fetch additional text following the symbol at the given position *)
+val rhs_post_extra_text : int -> text
diff --git a/parsing/lexer.mli b/parsing/lexer.mli
new file mode 100644
index 0000000000..2cad4f7f79
--- /dev/null
+++ b/parsing/lexer.mli
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexical analyzer *)
+
+val init : unit -> unit
+val token: Lexing.lexbuf -> Parser.token
+val skip_sharp_bang: Lexing.lexbuf -> unit
+
+type error =
+ | Illegal_character of char
+ | Illegal_escape of string
+ | Unterminated_comment of Location.t
+ | Unterminated_string
+ | Unterminated_string_in_comment of Location.t * Location.t
+ | Keyword_as_label of string
+ | Literal_overflow of string
+ | Invalid_literal of string
+;;
+
+exception Error of error * Location.t
+
+open Format
+
+val report_error: formatter -> error -> unit
+ (* Deprecated. Use Location.{error_of_exn, report_error}. *)
+
+val in_comment : unit -> bool;;
+val in_string : unit -> bool;;
+
+
+val print_warnings : bool ref
+val comments : unit -> (string * Location.t) list
+val token_with_comments : Lexing.lexbuf -> Parser.token
+
+(*
+ [set_preprocessor init preprocessor] registers [init] as the function
+to call to initialize the preprocessor when the lexer is initialized,
+and [preprocessor] a function that is called when a new token is needed
+by the parser, as [preprocessor lexer lexbuf] where [lexer] is the
+lexing function.
+
+When a preprocessor is configured by calling [set_preprocessor], the lexer
+changes its behavior to accept backslash-newline as a token-separating blank.
+*)
+
+val set_preprocessor :
+ (unit -> unit) ->
+ ((Lexing.lexbuf -> Parser.token) -> Lexing.lexbuf -> Parser.token) ->
+ unit
diff --git a/parsing/lexer.mll b/parsing/lexer.mll
new file mode 100644
index 0000000000..ef5c5d0e38
--- /dev/null
+++ b/parsing/lexer.mll
@@ -0,0 +1,779 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexer definition *)
+
+{
+open Lexing
+open Misc
+open Parser
+
+type error =
+ | Illegal_character of char
+ | Illegal_escape of string
+ | Unterminated_comment of Location.t
+ | Unterminated_string
+ | Unterminated_string_in_comment of Location.t * Location.t
+ | Keyword_as_label of string
+ | Literal_overflow of string
+ | Invalid_literal of string
+;;
+
+exception Error of error * Location.t;;
+
+(* The table of keywords *)
+
+let keyword_table =
+ create_hashtable 149 [
+ "and", AND;
+ "as", AS;
+ "assert", ASSERT;
+ "begin", BEGIN;
+ "class", CLASS;
+ "constraint", CONSTRAINT;
+ "do", DO;
+ "done", DONE;
+ "downto", DOWNTO;
+ "else", ELSE;
+ "end", END;
+ "exception", EXCEPTION;
+ "external", EXTERNAL;
+ "false", FALSE;
+ "for", FOR;
+ "fun", FUN;
+ "function", FUNCTION;
+ "functor", FUNCTOR;
+ "if", IF;
+ "in", IN;
+ "include", INCLUDE;
+ "inherit", INHERIT;
+ "initializer", INITIALIZER;
+ "lazy", LAZY;
+ "let", LET;
+ "match", MATCH;
+ "method", METHOD;
+ "module", MODULE;
+ "mutable", MUTABLE;
+ "new", NEW;
+ "nonrec", NONREC;
+ "object", OBJECT;
+ "of", OF;
+ "open", OPEN;
+ "or", OR;
+(* "parser", PARSER; *)
+ "private", PRIVATE;
+ "rec", REC;
+ "sig", SIG;
+ "struct", STRUCT;
+ "then", THEN;
+ "to", TO;
+ "true", TRUE;
+ "try", TRY;
+ "type", TYPE;
+ "val", VAL;
+ "virtual", VIRTUAL;
+ "when", WHEN;
+ "while", WHILE;
+ "with", WITH;
+
+ "lor", INFIXOP3("lor"); (* Should be INFIXOP2 *)
+ "lxor", INFIXOP3("lxor"); (* Should be INFIXOP2 *)
+ "mod", INFIXOP3("mod");
+ "land", INFIXOP3("land");
+ "lsl", INFIXOP4("lsl");
+ "lsr", INFIXOP4("lsr");
+ "asr", INFIXOP4("asr")
+]
+
+(* To buffer string literals *)
+
+let initial_string_buffer = Bytes.create 256
+let string_buff = ref initial_string_buffer
+let string_index = ref 0
+
+let reset_string_buffer () =
+ string_buff := initial_string_buffer;
+ string_index := 0
+
+let store_string_char c =
+ if !string_index >= Bytes.length !string_buff then begin
+ let new_buff = Bytes.create (Bytes.length (!string_buff) * 2) in
+ Bytes.blit !string_buff 0 new_buff 0 (Bytes.length !string_buff);
+ string_buff := new_buff
+ end;
+ Bytes.unsafe_set !string_buff !string_index c;
+ incr string_index
+
+let store_string s =
+ for i = 0 to String.length s - 1 do
+ store_string_char s.[i];
+ done
+
+let store_lexeme lexbuf =
+ store_string (Lexing.lexeme lexbuf)
+
+let get_stored_string () =
+ let s = Bytes.sub_string !string_buff 0 !string_index in
+ string_buff := initial_string_buffer;
+ s
+
+(* To store the position of the beginning of a string and comment *)
+let string_start_loc = ref Location.none;;
+let comment_start_loc = ref [];;
+let in_comment () = !comment_start_loc <> [];;
+let is_in_string = ref false
+let in_string () = !is_in_string
+let print_warnings = ref true
+
+let with_comment_buffer comment lexbuf =
+ let start_loc = Location.curr lexbuf in
+ comment_start_loc := [start_loc];
+ reset_string_buffer ();
+ let end_loc = comment lexbuf in
+ let s = get_stored_string () in
+ reset_string_buffer ();
+ let loc = { start_loc with Location.loc_end = end_loc.Location.loc_end } in
+ s, loc
+
+(* To translate escape sequences *)
+
+let char_for_backslash = function
+ | 'n' -> '\010'
+ | 'r' -> '\013'
+ | 'b' -> '\008'
+ | 't' -> '\009'
+ | c -> c
+
+let char_for_decimal_code lexbuf i =
+ let c = 100 * (Char.code(Lexing.lexeme_char lexbuf i) - 48) +
+ 10 * (Char.code(Lexing.lexeme_char lexbuf (i+1)) - 48) +
+ (Char.code(Lexing.lexeme_char lexbuf (i+2)) - 48) in
+ if (c < 0 || c > 255) then
+ if in_comment ()
+ then 'x'
+ else raise (Error(Illegal_escape (Lexing.lexeme lexbuf),
+ Location.curr lexbuf))
+ else Char.chr c
+
+let char_for_hexadecimal_code lexbuf i =
+ let d1 = Char.code (Lexing.lexeme_char lexbuf i) in
+ let val1 = if d1 >= 97 then d1 - 87
+ else if d1 >= 65 then d1 - 55
+ else d1 - 48
+ in
+ let d2 = Char.code (Lexing.lexeme_char lexbuf (i+1)) in
+ let val2 = if d2 >= 97 then d2 - 87
+ else if d2 >= 65 then d2 - 55
+ else d2 - 48
+ in
+ Char.chr (val1 * 16 + val2)
+
+(* To convert integer literals, allowing max_int + 1 (PR#4210) *)
+
+let cvt_int_literal s =
+ - int_of_string ("-" ^ s)
+let cvt_int32_literal s =
+ Int32.neg (Int32.of_string ("-" ^ String.sub s 0 (String.length s - 1)))
+let cvt_int64_literal s =
+ Int64.neg (Int64.of_string ("-" ^ String.sub s 0 (String.length s - 1)))
+let cvt_nativeint_literal s =
+ Nativeint.neg (Nativeint.of_string ("-" ^ String.sub s 0
+ (String.length s - 1)))
+
+(* Remove underscores from float literals *)
+
+let remove_underscores s =
+ let l = String.length s in
+ let b = Bytes.create l in
+ let rec remove src dst =
+ if src >= l then
+ if dst >= l then s else Bytes.sub_string b 0 dst
+ else
+ match s.[src] with
+ '_' -> remove (src + 1) dst
+ | c -> Bytes.set b dst c; remove (src + 1) (dst + 1)
+ in remove 0 0
+
+(* recover the name from a LABEL or OPTLABEL token *)
+
+let get_label_name lexbuf =
+ let s = Lexing.lexeme lexbuf in
+ let name = String.sub s 1 (String.length s - 2) in
+ if Hashtbl.mem keyword_table name then
+ raise (Error(Keyword_as_label name, Location.curr lexbuf));
+ name
+;;
+
+(* Update the current location with file name and line number. *)
+
+let update_loc lexbuf file line absolute chars =
+ let pos = lexbuf.lex_curr_p in
+ let new_file = match file with
+ | None -> pos.pos_fname
+ | Some s -> s
+ in
+ lexbuf.lex_curr_p <- { pos with
+ pos_fname = new_file;
+ pos_lnum = if absolute then line else pos.pos_lnum + line;
+ pos_bol = pos.pos_cnum - chars;
+ }
+;;
+
+let preprocessor = ref None
+
+let escaped_newlines = ref false
+
+(* Warn about Latin-1 characters used in idents *)
+
+let warn_latin1 lexbuf =
+ Location.prerr_warning (Location.curr lexbuf)
+ (Warnings.Deprecated "ISO-Latin1 characters in identifiers")
+;;
+
+let comment_list = ref []
+
+let add_comment com =
+ comment_list := com :: !comment_list
+
+let add_docstring_comment ds =
+ let com = (Docstrings.docstring_body ds, Docstrings.docstring_loc ds) in
+ add_comment com
+
+let comments () = List.rev !comment_list
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Illegal_character c ->
+ fprintf ppf "Illegal character (%s)" (Char.escaped c)
+ | Illegal_escape s ->
+ fprintf ppf "Illegal backslash escape in string or character (%s)" s
+ | Unterminated_comment _ ->
+ fprintf ppf "Comment not terminated"
+ | Unterminated_string ->
+ fprintf ppf "String literal not terminated"
+ | Unterminated_string_in_comment (_, loc) ->
+ fprintf ppf "This comment contains an unterminated string literal@.\
+ %aString literal begins here"
+ Location.print_error loc
+ | Keyword_as_label kwd ->
+ fprintf ppf "`%s' is a keyword, it cannot be used as label name" kwd
+ | Literal_overflow ty ->
+ fprintf ppf "Integer literal exceeds the range of representable \
+ integers of type %s" ty
+ | Invalid_literal s ->
+ fprintf ppf "Invalid literal %s" s
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (err, loc) ->
+ Some (Location.error_of_printer loc report_error err)
+ | _ ->
+ None
+ )
+
+}
+
+let newline = ('\013'* '\010')
+let blank = [' ' '\009' '\012']
+let lowercase = ['a'-'z' '_']
+let uppercase = ['A'-'Z']
+let identchar = ['A'-'Z' 'a'-'z' '_' '\'' '0'-'9']
+let lowercase_latin1 = ['a'-'z' '\223'-'\246' '\248'-'\255' '_']
+let uppercase_latin1 = ['A'-'Z' '\192'-'\214' '\216'-'\222']
+let identchar_latin1 =
+ ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9']
+let symbolchar =
+ ['!' '$' '%' '&' '*' '+' '-' '.' '/' ':' '<' '=' '>' '?' '@' '^' '|' '~']
+let decimal_literal =
+ ['0'-'9'] ['0'-'9' '_']*
+let hex_literal =
+ '0' ['x' 'X'] ['0'-'9' 'A'-'F' 'a'-'f']['0'-'9' 'A'-'F' 'a'-'f' '_']*
+let oct_literal =
+ '0' ['o' 'O'] ['0'-'7'] ['0'-'7' '_']*
+let bin_literal =
+ '0' ['b' 'B'] ['0'-'1'] ['0'-'1' '_']*
+let int_literal =
+ decimal_literal | hex_literal | oct_literal | bin_literal
+let float_literal =
+ ['0'-'9'] ['0'-'9' '_']*
+ ('.' ['0'-'9' '_']* )?
+ (['e' 'E'] ['+' '-']? ['0'-'9'] ['0'-'9' '_']*)?
+
+rule token = parse
+ | "\\" newline {
+ if not !escaped_newlines then
+ raise (Error(Illegal_character (Lexing.lexeme_char lexbuf 0),
+ Location.curr lexbuf));
+ update_loc lexbuf None 1 false 0;
+ token lexbuf }
+ | newline
+ { update_loc lexbuf None 1 false 0;
+ EOL }
+ | blank +
+ { token lexbuf }
+ | "_"
+ { UNDERSCORE }
+ | "~"
+ { TILDE }
+ | "~" lowercase identchar * ':'
+ { LABEL (get_label_name lexbuf) }
+ | "~" lowercase_latin1 identchar_latin1 * ':'
+ { warn_latin1 lexbuf; LABEL (get_label_name lexbuf) }
+ | "?"
+ { QUESTION }
+ | "?" lowercase identchar * ':'
+ { OPTLABEL (get_label_name lexbuf) }
+ | "?" lowercase_latin1 identchar_latin1 * ':'
+ { warn_latin1 lexbuf; OPTLABEL (get_label_name lexbuf) }
+ | lowercase identchar *
+ { let s = Lexing.lexeme lexbuf in
+ try Hashtbl.find keyword_table s
+ with Not_found -> LIDENT s }
+ | lowercase_latin1 identchar_latin1 *
+ { warn_latin1 lexbuf; LIDENT (Lexing.lexeme lexbuf) }
+ | uppercase identchar *
+ { UIDENT(Lexing.lexeme lexbuf) } (* No capitalized keywords *)
+ | uppercase_latin1 identchar_latin1 *
+ { warn_latin1 lexbuf; UIDENT(Lexing.lexeme lexbuf) }
+ | int_literal
+ { try
+ INT (cvt_int_literal (Lexing.lexeme lexbuf))
+ with Failure _ ->
+ raise (Error(Literal_overflow "int", Location.curr lexbuf))
+ }
+ | float_literal
+ { FLOAT (remove_underscores(Lexing.lexeme lexbuf)) }
+ | int_literal "l"
+ { try
+ INT32 (cvt_int32_literal (Lexing.lexeme lexbuf))
+ with Failure _ ->
+ raise (Error(Literal_overflow "int32", Location.curr lexbuf)) }
+ | int_literal "L"
+ { try
+ INT64 (cvt_int64_literal (Lexing.lexeme lexbuf))
+ with Failure _ ->
+ raise (Error(Literal_overflow "int64", Location.curr lexbuf)) }
+ | int_literal "n"
+ { try
+ NATIVEINT (cvt_nativeint_literal (Lexing.lexeme lexbuf))
+ with Failure _ ->
+ raise (Error(Literal_overflow "nativeint", Location.curr lexbuf)) }
+ | (float_literal | int_literal) identchar+
+ { raise (Error(Invalid_literal (Lexing.lexeme lexbuf),
+ Location.curr lexbuf)) }
+ | "\""
+ { reset_string_buffer();
+ is_in_string := true;
+ let string_start = lexbuf.lex_start_p in
+ string_start_loc := Location.curr lexbuf;
+ string lexbuf;
+ is_in_string := false;
+ lexbuf.lex_start_p <- string_start;
+ STRING (get_stored_string(), None) }
+ | "{" lowercase* "|"
+ { reset_string_buffer();
+ let delim = Lexing.lexeme lexbuf in
+ let delim = String.sub delim 1 (String.length delim - 2) in
+ is_in_string := true;
+ let string_start = lexbuf.lex_start_p in
+ string_start_loc := Location.curr lexbuf;
+ quoted_string delim lexbuf;
+ is_in_string := false;
+ lexbuf.lex_start_p <- string_start;
+ STRING (get_stored_string(), Some delim) }
+ | "\'" newline "\'"
+ { update_loc lexbuf None 1 false 1;
+ CHAR (Lexing.lexeme_char lexbuf 1) }
+ | "\'" [^ '\\' '\'' '\010' '\013'] "\'"
+ { CHAR(Lexing.lexeme_char lexbuf 1) }
+ | "\'\\" ['\\' '\'' '\"' 'n' 't' 'b' 'r' ' '] "\'"
+ { CHAR(char_for_backslash (Lexing.lexeme_char lexbuf 2)) }
+ | "\'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "\'"
+ { CHAR(char_for_decimal_code lexbuf 2) }
+ | "\'\\" 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "\'"
+ { CHAR(char_for_hexadecimal_code lexbuf 3) }
+ | "\'\\" _
+ { let l = Lexing.lexeme lexbuf in
+ let esc = String.sub l 1 (String.length l - 1) in
+ raise (Error(Illegal_escape esc, Location.curr lexbuf))
+ }
+ | "(*"
+ { let s, loc = with_comment_buffer comment lexbuf in
+ COMMENT (s, loc) }
+ | "(**"
+ { let s, loc = with_comment_buffer comment lexbuf in
+ DOCSTRING (Docstrings.docstring s loc) }
+ | "(**" ('*'+) as stars
+ { let s, loc =
+ with_comment_buffer
+ (fun lexbuf ->
+ store_string ("*" ^ stars);
+ comment lexbuf)
+ lexbuf
+ in
+ COMMENT (s, loc) }
+ | "(*)"
+ { if !print_warnings then
+ Location.prerr_warning (Location.curr lexbuf) Warnings.Comment_start;
+ let s, loc = with_comment_buffer comment lexbuf in
+ COMMENT (s, loc) }
+ | "(*" ('*'*) as stars "*)"
+ { COMMENT (stars, Location.curr lexbuf) }
+ | "*)"
+ { let loc = Location.curr lexbuf in
+ Location.prerr_warning loc Warnings.Comment_not_end;
+ lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_curr_pos - 1;
+ let curpos = lexbuf.lex_curr_p in
+ lexbuf.lex_curr_p <- { curpos with pos_cnum = curpos.pos_cnum - 1 };
+ STAR
+ }
+ | "#" [' ' '\t']* (['0'-'9']+ as num) [' ' '\t']*
+ ("\"" ([^ '\010' '\013' '\"' ] * as name) "\"")?
+ [^ '\010' '\013'] * newline
+ { update_loc lexbuf name (int_of_string num) true 0;
+ token lexbuf
+ }
+ | "#" { SHARP }
+ | "&" { AMPERSAND }
+ | "&&" { AMPERAMPER }
+ | "`" { BACKQUOTE }
+ | "\'" { QUOTE }
+ | "(" { LPAREN }
+ | ")" { RPAREN }
+ | "*" { STAR }
+ | "," { COMMA }
+ | "->" { MINUSGREATER }
+ | "." { DOT }
+ | ".." { DOTDOT }
+ | ":" { COLON }
+ | "::" { COLONCOLON }
+ | ":=" { COLONEQUAL }
+ | ":>" { COLONGREATER }
+ | ";" { SEMI }
+ | ";;" { SEMISEMI }
+ | "<" { LESS }
+ | "<-" { LESSMINUS }
+ | "=" { EQUAL }
+ | "[" { LBRACKET }
+ | "[|" { LBRACKETBAR }
+ | "[<" { LBRACKETLESS }
+ | "[>" { LBRACKETGREATER }
+ | "]" { RBRACKET }
+ | "{" { LBRACE }
+ | "{<" { LBRACELESS }
+ | "|" { BAR }
+ | "||" { BARBAR }
+ | "|]" { BARRBRACKET }
+ | ">" { GREATER }
+ | ">]" { GREATERRBRACKET }
+ | "}" { RBRACE }
+ | ">}" { GREATERRBRACE }
+ | "[@" { LBRACKETAT }
+ | "[%" { LBRACKETPERCENT }
+ | "[%%" { LBRACKETPERCENTPERCENT }
+ | "[@@" { LBRACKETATAT }
+ | "[@@@" { LBRACKETATATAT }
+ | "!" { BANG }
+ | "!=" { INFIXOP0 "!=" }
+ | "+" { PLUS }
+ | "+." { PLUSDOT }
+ | "+=" { PLUSEQ }
+ | "-" { MINUS }
+ | "-." { MINUSDOT }
+
+ | "!" symbolchar +
+ { PREFIXOP(Lexing.lexeme lexbuf) }
+ | ['~' '?'] symbolchar +
+ { PREFIXOP(Lexing.lexeme lexbuf) }
+ | ['=' '<' '>' '|' '&' '$'] symbolchar *
+ { INFIXOP0(Lexing.lexeme lexbuf) }
+ | ['@' '^'] symbolchar *
+ { INFIXOP1(Lexing.lexeme lexbuf) }
+ | ['+' '-'] symbolchar *
+ { INFIXOP2(Lexing.lexeme lexbuf) }
+ | "**" symbolchar *
+ { INFIXOP4(Lexing.lexeme lexbuf) }
+ | '%' { PERCENT }
+ | ['*' '/' '%'] symbolchar *
+ { INFIXOP3(Lexing.lexeme lexbuf) }
+ | '#' (symbolchar | '#') +
+ { SHARPOP(Lexing.lexeme lexbuf) }
+ | eof { EOF }
+ | _
+ { raise (Error(Illegal_character (Lexing.lexeme_char lexbuf 0),
+ Location.curr lexbuf))
+ }
+
+and comment = parse
+ "(*"
+ { comment_start_loc := (Location.curr lexbuf) :: !comment_start_loc;
+ store_lexeme lexbuf;
+ comment lexbuf;
+ }
+ | "*)"
+ { match !comment_start_loc with
+ | [] -> assert false
+ | [_] -> comment_start_loc := []; Location.curr lexbuf
+ | _ :: l -> comment_start_loc := l;
+ store_lexeme lexbuf;
+ comment lexbuf;
+ }
+ | "\""
+ {
+ string_start_loc := Location.curr lexbuf;
+ store_string_char '\"';
+ is_in_string := true;
+ begin try string lexbuf
+ with Error (Unterminated_string, str_start) ->
+ match !comment_start_loc with
+ | [] -> assert false
+ | loc :: _ ->
+ let start = List.hd (List.rev !comment_start_loc) in
+ comment_start_loc := [];
+ raise (Error (Unterminated_string_in_comment (start, str_start),
+ loc))
+ end;
+ is_in_string := false;
+ store_string_char '\"';
+ comment lexbuf }
+ | "{" lowercase* "|"
+ {
+ let delim = Lexing.lexeme lexbuf in
+ let delim = String.sub delim 1 (String.length delim - 2) in
+ string_start_loc := Location.curr lexbuf;
+ store_lexeme lexbuf;
+ is_in_string := true;
+ begin try quoted_string delim lexbuf
+ with Error (Unterminated_string, str_start) ->
+ match !comment_start_loc with
+ | [] -> assert false
+ | loc :: _ ->
+ let start = List.hd (List.rev !comment_start_loc) in
+ comment_start_loc := [];
+ raise (Error (Unterminated_string_in_comment (start, str_start),
+ loc))
+ end;
+ is_in_string := false;
+ store_string_char '|';
+ store_string delim;
+ store_string_char '}';
+ comment lexbuf }
+
+ | "\'\'"
+ { store_lexeme lexbuf; comment lexbuf }
+ | "\'" newline "\'"
+ { update_loc lexbuf None 1 false 1;
+ store_lexeme lexbuf;
+ comment lexbuf
+ }
+ | "\'" [^ '\\' '\'' '\010' '\013' ] "\'"
+ { store_lexeme lexbuf; comment lexbuf }
+ | "\'\\" ['\\' '\"' '\'' 'n' 't' 'b' 'r' ' '] "\'"
+ { store_lexeme lexbuf; comment lexbuf }
+ | "\'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "\'"
+ { store_lexeme lexbuf; comment lexbuf }
+ | "\'\\" 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "\'"
+ { store_lexeme lexbuf; comment lexbuf }
+ | eof
+ { match !comment_start_loc with
+ | [] -> assert false
+ | loc :: _ ->
+ let start = List.hd (List.rev !comment_start_loc) in
+ comment_start_loc := [];
+ raise (Error (Unterminated_comment start, loc))
+ }
+ | newline
+ { update_loc lexbuf None 1 false 0;
+ store_lexeme lexbuf;
+ comment lexbuf
+ }
+ | _
+ { store_lexeme lexbuf; comment lexbuf }
+
+and string = parse
+ '\"'
+ { () }
+ | '\\' newline ([' ' '\t'] * as space)
+ { update_loc lexbuf None 1 false (String.length space);
+ string lexbuf
+ }
+ | '\\' ['\\' '\'' '\"' 'n' 't' 'b' 'r' ' ']
+ { store_string_char(char_for_backslash(Lexing.lexeme_char lexbuf 1));
+ string lexbuf }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9']
+ { store_string_char(char_for_decimal_code lexbuf 1);
+ string lexbuf }
+ | '\\' 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F']
+ { store_string_char(char_for_hexadecimal_code lexbuf 2);
+ string lexbuf }
+ | '\\' _
+ { if in_comment ()
+ then string lexbuf
+ else begin
+(* Should be an error, but we are very lax.
+ raise (Error (Illegal_escape (Lexing.lexeme lexbuf),
+ Location.curr lexbuf))
+*)
+ let loc = Location.curr lexbuf in
+ Location.prerr_warning loc Warnings.Illegal_backslash;
+ store_string_char (Lexing.lexeme_char lexbuf 0);
+ store_string_char (Lexing.lexeme_char lexbuf 1);
+ string lexbuf
+ end
+ }
+ | newline
+ { if not (in_comment ()) then
+ Location.prerr_warning (Location.curr lexbuf) Warnings.Eol_in_string;
+ update_loc lexbuf None 1 false 0;
+ store_lexeme lexbuf;
+ string lexbuf
+ }
+ | eof
+ { is_in_string := false;
+ raise (Error (Unterminated_string, !string_start_loc)) }
+ | _
+ { store_string_char(Lexing.lexeme_char lexbuf 0);
+ string lexbuf }
+
+and quoted_string delim = parse
+ | newline
+ { update_loc lexbuf None 1 false 0;
+ store_lexeme lexbuf;
+ quoted_string delim lexbuf
+ }
+ | eof
+ { is_in_string := false;
+ raise (Error (Unterminated_string, !string_start_loc)) }
+ | "|" lowercase* "}"
+ {
+ let edelim = Lexing.lexeme lexbuf in
+ let edelim = String.sub edelim 1 (String.length edelim - 2) in
+ if delim = edelim then ()
+ else (store_lexeme lexbuf; quoted_string delim lexbuf)
+ }
+ | _
+ { store_string_char(Lexing.lexeme_char lexbuf 0);
+ quoted_string delim lexbuf }
+
+and skip_sharp_bang = parse
+ | "#!" [^ '\n']* '\n' [^ '\n']* "\n!#\n"
+ { update_loc lexbuf None 3 false 0 }
+ | "#!" [^ '\n']* '\n'
+ { update_loc lexbuf None 1 false 0 }
+ | "" { () }
+
+{
+
+ let token_with_comments lexbuf =
+ match !preprocessor with
+ | None -> token lexbuf
+ | Some (_init, preprocess) -> preprocess token lexbuf
+
+ type newline_state =
+ | NoLine (* There have been no blank lines yet. *)
+ | NewLine
+ (* There have been no blank lines, and the previous
+ token was a newline. *)
+ | BlankLine (* There have been blank lines. *)
+
+ type doc_state =
+ | Initial (* There have been no docstrings yet *)
+ | After of docstring list
+ (* There have been docstrings, none of which were
+ preceeded by a blank line *)
+ | Before of docstring list * docstring list * docstring list
+ (* There have been docstrings, some of which were
+ preceeded by a blank line *)
+
+ and docstring = Docstrings.docstring
+
+ let token lexbuf =
+ let post_pos = lexeme_end_p lexbuf in
+ let attach lines docs pre_pos =
+ let open Docstrings in
+ match docs, lines with
+ | Initial, _ -> ()
+ | After a, (NoLine | NewLine) ->
+ set_post_docstrings post_pos (List.rev a);
+ set_pre_docstrings pre_pos a;
+ | After a, BlankLine ->
+ set_post_docstrings post_pos (List.rev a);
+ set_pre_extra_docstrings pre_pos (List.rev a)
+ | Before(a, f, b), (NoLine | NewLine) ->
+ set_post_docstrings post_pos (List.rev a);
+ set_post_extra_docstrings post_pos
+ (List.rev_append f (List.rev b));
+ set_floating_docstrings pre_pos (List.rev f);
+ set_pre_extra_docstrings pre_pos (List.rev a);
+ set_pre_docstrings pre_pos b
+ | Before(a, f, b), BlankLine ->
+ set_post_docstrings post_pos (List.rev a);
+ set_post_extra_docstrings post_pos
+ (List.rev_append f (List.rev b));
+ set_floating_docstrings pre_pos
+ (List.rev_append f (List.rev b));
+ set_pre_extra_docstrings pre_pos (List.rev a)
+ in
+ let rec loop lines docs lexbuf =
+ match token_with_comments lexbuf with
+ | COMMENT (s, loc) ->
+ add_comment (s, loc);
+ let lines' =
+ match lines with
+ | NoLine -> NoLine
+ | NewLine -> NoLine
+ | BlankLine -> BlankLine
+ in
+ loop lines' docs lexbuf
+ | EOL ->
+ let lines' =
+ match lines with
+ | NoLine -> NewLine
+ | NewLine -> BlankLine
+ | BlankLine -> BlankLine
+ in
+ loop lines' docs lexbuf
+ | DOCSTRING doc ->
+ add_docstring_comment doc;
+ let docs' =
+ match docs, lines with
+ | Initial, (NoLine | NewLine) -> After [doc]
+ | Initial, BlankLine -> Before([], [], [doc])
+ | After a, (NoLine | NewLine) -> After (doc :: a)
+ | After a, BlankLine -> Before (a, [], [doc])
+ | Before(a, f, b), (NoLine | NewLine) -> Before(a, f, doc :: b)
+ | Before(a, f, b), BlankLine -> Before(a, b @ f, [doc])
+ in
+ loop NoLine docs' lexbuf
+ | tok ->
+ attach lines docs (lexeme_start_p lexbuf);
+ tok
+ in
+ loop NoLine Initial lexbuf
+
+ let init () =
+ is_in_string := false;
+ comment_start_loc := [];
+ comment_list := [];
+ match !preprocessor with
+ | None -> ()
+ | Some (init, _preprocess) -> init ()
+
+ let set_preprocessor init preprocess =
+ escaped_newlines := true;
+ preprocessor := Some (init, preprocess)
+
+}
diff --git a/parsing/location.ml b/parsing/location.ml
new file mode 100644
index 0000000000..57a5179ee3
--- /dev/null
+++ b/parsing/location.ml
@@ -0,0 +1,443 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Lexing
+
+let absname = ref false
+ (* This reference should be in Clflags, but it would create an additional
+ dependency and make bootstrapping Camlp4 more difficult. *)
+
+type t = { loc_start: position; loc_end: position; loc_ghost: bool };;
+
+let in_file name =
+ let loc = {
+ pos_fname = name;
+ pos_lnum = 1;
+ pos_bol = 0;
+ pos_cnum = -1;
+ } in
+ { loc_start = loc; loc_end = loc; loc_ghost = true }
+;;
+
+let none = in_file "_none_";;
+
+let curr lexbuf = {
+ loc_start = lexbuf.lex_start_p;
+ loc_end = lexbuf.lex_curr_p;
+ loc_ghost = false
+};;
+
+let init lexbuf fname =
+ lexbuf.lex_curr_p <- {
+ pos_fname = fname;
+ pos_lnum = 1;
+ pos_bol = 0;
+ pos_cnum = 0;
+ }
+;;
+
+let symbol_rloc () = {
+ loc_start = Parsing.symbol_start_pos ();
+ loc_end = Parsing.symbol_end_pos ();
+ loc_ghost = false;
+};;
+
+let symbol_gloc () = {
+ loc_start = Parsing.symbol_start_pos ();
+ loc_end = Parsing.symbol_end_pos ();
+ loc_ghost = true;
+};;
+
+let rhs_loc n = {
+ loc_start = Parsing.rhs_start_pos n;
+ loc_end = Parsing.rhs_end_pos n;
+ loc_ghost = false;
+};;
+
+let input_name = ref "_none_"
+let input_lexbuf = ref (None : lexbuf option)
+
+(* Terminal info *)
+
+let status = ref Terminfo.Uninitialised
+
+let num_loc_lines = ref 0 (* number of lines already printed after input *)
+
+let print_updating_num_loc_lines ppf f arg =
+ let open Format in
+ let out_functions = pp_get_formatter_out_functions ppf () in
+ let out_string str start len =
+ let rec count i c =
+ if i = start + len then c
+ else if String.get str i = '\n' then count (succ i) (succ c)
+ else count (succ i) c in
+ num_loc_lines := !num_loc_lines + count start 0 ;
+ out_functions.out_string str start len in
+ pp_set_formatter_out_functions ppf
+ { out_functions with out_string } ;
+ f ppf arg ;
+ pp_print_flush ppf ();
+ pp_set_formatter_out_functions ppf out_functions
+
+(* Highlight the locations using standout mode. *)
+
+let highlight_terminfo ppf num_lines lb locs =
+ Format.pp_print_flush ppf (); (* avoid mixing Format and normal output *)
+ (* Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer. *)
+ let pos0 = -lb.lex_abs_pos in
+ (* Do nothing if the buffer does not contain the whole phrase. *)
+ if pos0 < 0 then raise Exit;
+ (* Count number of lines in phrase *)
+ let lines = ref !num_loc_lines in
+ for i = pos0 to lb.lex_buffer_len - 1 do
+ if Bytes.get lb.lex_buffer i = '\n' then incr lines
+ done;
+ (* If too many lines, give up *)
+ if !lines >= num_lines - 2 then raise Exit;
+ (* Move cursor up that number of lines *)
+ flush stdout; Terminfo.backup !lines;
+ (* Print the input, switching to standout for the location *)
+ let bol = ref false in
+ print_string "# ";
+ for pos = 0 to lb.lex_buffer_len - pos0 - 1 do
+ if !bol then (print_string " "; bol := false);
+ if List.exists (fun loc -> pos = loc.loc_start.pos_cnum) locs then
+ Terminfo.standout true;
+ if List.exists (fun loc -> pos = loc.loc_end.pos_cnum) locs then
+ Terminfo.standout false;
+ let c = Bytes.get lb.lex_buffer (pos + pos0) in
+ print_char c;
+ bol := (c = '\n')
+ done;
+ (* Make sure standout mode is over *)
+ Terminfo.standout false;
+ (* Position cursor back to original location *)
+ Terminfo.resume !num_loc_lines;
+ flush stdout
+
+(* Highlight the location by printing it again. *)
+
+let highlight_dumb ppf lb loc =
+ (* Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer. *)
+ let pos0 = -lb.lex_abs_pos in
+ (* Do nothing if the buffer does not contain the whole phrase. *)
+ if pos0 < 0 then raise Exit;
+ let end_pos = lb.lex_buffer_len - pos0 - 1 in
+ (* Determine line numbers for the start and end points *)
+ let line_start = ref 0 and line_end = ref 0 in
+ for pos = 0 to end_pos do
+ if Bytes.get lb.lex_buffer (pos + pos0) = '\n' then begin
+ if loc.loc_start.pos_cnum > pos then incr line_start;
+ if loc.loc_end.pos_cnum > pos then incr line_end;
+ end
+ done;
+ (* Print character location (useful for Emacs) *)
+ Format.fprintf ppf "Characters %i-%i:@."
+ loc.loc_start.pos_cnum loc.loc_end.pos_cnum;
+ (* Print the input, underlining the location *)
+ Format.pp_print_string ppf " ";
+ let line = ref 0 in
+ let pos_at_bol = ref 0 in
+ for pos = 0 to end_pos do
+ match Bytes.get lb.lex_buffer (pos + pos0) with
+ | '\n' ->
+ if !line = !line_start && !line = !line_end then begin
+ (* loc is on one line: underline location *)
+ Format.fprintf ppf "@. ";
+ for _i = !pos_at_bol to loc.loc_start.pos_cnum - 1 do
+ Format.pp_print_char ppf ' '
+ done;
+ for _i = loc.loc_start.pos_cnum to loc.loc_end.pos_cnum - 1 do
+ Format.pp_print_char ppf '^'
+ done
+ end;
+ if !line >= !line_start && !line <= !line_end then begin
+ Format.fprintf ppf "@.";
+ if pos < loc.loc_end.pos_cnum then Format.pp_print_string ppf " "
+ end;
+ incr line;
+ pos_at_bol := pos + 1
+ | '\r' -> () (* discard *)
+ | c ->
+ if !line = !line_start && !line = !line_end then
+ (* loc is on one line: print whole line *)
+ Format.pp_print_char ppf c
+ else if !line = !line_start then
+ (* first line of multiline loc:
+ print a dot for each char before loc_start *)
+ if pos < loc.loc_start.pos_cnum then
+ Format.pp_print_char ppf '.'
+ else
+ Format.pp_print_char ppf c
+ else if !line = !line_end then
+ (* last line of multiline loc: print a dot for each char
+ after loc_end, even whitespaces *)
+ if pos < loc.loc_end.pos_cnum then
+ Format.pp_print_char ppf c
+ else
+ Format.pp_print_char ppf '.'
+ else if !line > !line_start && !line < !line_end then
+ (* intermediate line of multiline loc: print whole line *)
+ Format.pp_print_char ppf c
+ done
+
+(* Highlight the location using one of the supported modes. *)
+
+let rec highlight_locations ppf locs =
+ match !status with
+ Terminfo.Uninitialised ->
+ status := Terminfo.setup stdout; highlight_locations ppf locs
+ | Terminfo.Bad_term ->
+ begin match !input_lexbuf with
+ None -> false
+ | Some lb ->
+ let norepeat =
+ try Sys.getenv "TERM" = "norepeat" with Not_found -> false in
+ if norepeat then false else
+ let loc1 = List.hd locs in
+ try highlight_dumb ppf lb loc1; true
+ with Exit -> false
+ end
+ | Terminfo.Good_term num_lines ->
+ begin match !input_lexbuf with
+ None -> false
+ | Some lb ->
+ try highlight_terminfo ppf num_lines lb locs; true
+ with Exit -> false
+ end
+
+(* Print the location in some way or another *)
+
+open Format
+
+let absolute_path s = (* This function could go into Filename *)
+ let open Filename in
+ let s = if is_relative s then concat (Sys.getcwd ()) s else s in
+ (* Now simplify . and .. components *)
+ let rec aux s =
+ let base = basename s in
+ let dir = dirname s in
+ if dir = s then dir
+ else if base = current_dir_name then aux dir
+ else if base = parent_dir_name then dirname (aux dir)
+ else concat (aux dir) base
+ in
+ aux s
+
+let show_filename file =
+ if !absname then absolute_path file else file
+
+let print_filename ppf file =
+ Format.fprintf ppf "%s" (show_filename file)
+
+let reset () =
+ num_loc_lines := 0
+
+let (msg_file, msg_line, msg_chars, msg_to, msg_colon) =
+ ("File \"", "\", line ", ", characters ", "-", ":")
+
+(* return file, line, char from the given position *)
+let get_pos_info pos =
+ (pos.pos_fname, pos.pos_lnum, pos.pos_cnum - pos.pos_bol)
+;;
+
+let setup_colors () =
+ Misc.Color.setup !Clflags.color
+
+let print_loc ppf loc =
+ setup_colors ();
+ let (file, line, startchar) = get_pos_info loc.loc_start in
+ let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in
+ if file = "//toplevel//" then begin
+ if highlight_locations ppf [loc] then () else
+ fprintf ppf "Characters %i-%i"
+ loc.loc_start.pos_cnum loc.loc_end.pos_cnum
+ end else begin
+ fprintf ppf "%s@{<loc>%a%s%i" msg_file print_filename file msg_line line;
+ if startchar >= 0 then
+ fprintf ppf "%s%i%s%i" msg_chars startchar msg_to endchar;
+ fprintf ppf "@}"
+ end
+;;
+
+let print ppf loc =
+ setup_colors ();
+ if loc.loc_start.pos_fname = "//toplevel//"
+ && highlight_locations ppf [loc] then ()
+ else fprintf ppf "@{<loc>%a@}%s@." print_loc loc msg_colon
+;;
+
+let error_prefix = "Error"
+let warning_prefix = "Warning"
+
+let print_error_prefix ppf () =
+ setup_colors ();
+ fprintf ppf "@{<error>%s@}:" error_prefix;
+ ()
+;;
+
+let print_error ppf loc =
+ print ppf loc;
+ print_error_prefix ppf ()
+;;
+
+let print_error_cur_file ppf () = print_error ppf (in_file !input_name);;
+
+let default_warning_printer loc ppf w =
+ if Warnings.is_active w then begin
+ setup_colors ();
+ print ppf loc;
+ fprintf ppf "@{<warning>%s@} %a@." warning_prefix Warnings.print w
+ end
+;;
+
+let warning_printer = ref default_warning_printer ;;
+
+let print_warning loc ppf w =
+ print_updating_num_loc_lines ppf (!warning_printer loc) w
+;;
+
+let formatter_for_warnings = ref err_formatter;;
+let prerr_warning loc w = print_warning loc !formatter_for_warnings w;;
+
+let echo_eof () =
+ print_newline ();
+ incr num_loc_lines
+
+type 'a loc = {
+ txt : 'a;
+ loc : t;
+}
+
+let mkloc txt loc = { txt ; loc }
+let mknoloc txt = mkloc txt none
+
+
+type error =
+ {
+ loc: t;
+ msg: string;
+ sub: error list;
+ if_highlight: string; (* alternative message if locations are highlighted *)
+ }
+
+let pp_ksprintf ?before k fmt =
+ let buf = Buffer.create 64 in
+ let ppf = Format.formatter_of_buffer buf in
+ Misc.Color.set_color_tag_handling ppf;
+ begin match before with
+ | None -> ()
+ | Some f -> f ppf
+ end;
+ kfprintf
+ (fun _ ->
+ pp_print_flush ppf ();
+ let msg = Buffer.contents buf in
+ k msg)
+ ppf fmt
+
+let errorf ?(loc = none) ?(sub = []) ?(if_highlight = "") fmt =
+ pp_ksprintf
+ (fun msg -> {loc; msg; sub; if_highlight})
+ fmt
+
+let errorf_prefixed ?(loc=none) ?(sub=[]) ?(if_highlight="") fmt =
+ pp_ksprintf
+ ~before:(fun ppf -> fprintf ppf "%a " print_error_prefix ())
+ (fun msg -> {loc; msg; sub; if_highlight})
+ fmt
+
+let error ?(loc = none) ?(sub = []) ?(if_highlight = "") msg =
+ {loc; msg; sub; if_highlight}
+
+let error_of_exn : (exn -> error option) list ref = ref []
+
+let register_error_of_exn f = error_of_exn := f :: !error_of_exn
+
+let error_of_exn exn =
+ let rec loop = function
+ | [] -> None
+ | f :: rest ->
+ match f exn with
+ | Some _ as r -> r
+ | None -> loop rest
+ in
+ loop !error_of_exn
+
+let rec default_error_reporter ppf ({loc; msg; sub; if_highlight} as err) =
+ let highlighted =
+ if if_highlight <> "" then
+ let rec collect_locs locs {loc; sub; if_highlight; _} =
+ List.fold_left collect_locs (loc :: locs) sub
+ in
+ let locs = collect_locs [] err in
+ highlight_locations ppf locs
+ else
+ false
+ in
+ if highlighted then
+ Format.pp_print_string ppf if_highlight
+ else begin
+ print ppf loc;
+ Format.pp_print_string ppf msg;
+ List.iter (Format.fprintf ppf "@\n@[<2>%a@]" default_error_reporter) sub
+ end
+
+let error_reporter = ref default_error_reporter
+
+let report_error ppf err =
+ print_updating_num_loc_lines ppf !error_reporter err
+;;
+
+let error_of_printer loc print x =
+ errorf_prefixed ~loc "%a@?" print x
+
+let error_of_printer_file print x =
+ error_of_printer (in_file !input_name) print x
+
+let () =
+ register_error_of_exn
+ (function
+ | Sys_error msg ->
+ Some (errorf_prefixed ~loc:(in_file !input_name)
+ "I/O error: %s" msg)
+ | Warnings.Errors n ->
+ Some
+ (errorf_prefixed ~loc:(in_file !input_name)
+ "Some fatal warnings were triggered (%d occurrences)" n)
+ | _ ->
+ None
+ )
+
+
+let rec report_exception_rec n ppf exn =
+ try match error_of_exn exn with
+ | Some err ->
+ fprintf ppf "@[%a@]@." report_error err
+ | None -> raise exn
+ with exn when n > 0 ->
+ report_exception_rec (n-1) ppf exn
+
+let report_exception ppf exn = report_exception_rec 5 ppf exn
+
+
+exception Error of error
+
+let () =
+ register_error_of_exn
+ (function
+ | Error e -> Some e
+ | _ -> None
+ )
+
+let raise_errorf ?(loc = none) ?(sub = []) ?(if_highlight = "") =
+ pp_ksprintf (fun msg -> raise (Error ({loc; msg; sub; if_highlight})))
diff --git a/parsing/location.mli b/parsing/location.mli
new file mode 100644
index 0000000000..9c7421f09d
--- /dev/null
+++ b/parsing/location.mli
@@ -0,0 +1,142 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Source code locations (ranges of positions), used in parsetree. *)
+
+open Format
+
+type t = {
+ loc_start: Lexing.position;
+ loc_end: Lexing.position;
+ loc_ghost: bool;
+}
+
+(* Note on the use of Lexing.position in this module.
+ If [pos_fname = ""], then use [!input_name] instead.
+ If [pos_lnum = -1], then [pos_bol = 0]. Use [pos_cnum] and
+ re-parse the file to get the line and character numbers.
+ Else all fields are correct.
+*)
+
+val none : t
+(** An arbitrary value of type [t]; describes an empty ghost range. *)
+
+val in_file : string -> t
+(** Return an empty ghost range located in a given file. *)
+
+val init : Lexing.lexbuf -> string -> unit
+(** Set the file name and line number of the [lexbuf] to be the start
+ of the named file. *)
+
+val curr : Lexing.lexbuf -> t
+(** Get the location of the current token from the [lexbuf]. *)
+
+val symbol_rloc: unit -> t
+val symbol_gloc: unit -> t
+
+(** [rhs_loc n] returns the location of the symbol at position [n], starting
+ at 1, in the current parser rule. *)
+val rhs_loc: int -> t
+
+val input_name: string ref
+val input_lexbuf: Lexing.lexbuf option ref
+
+val get_pos_info: Lexing.position -> string * int * int (* file, line, char *)
+val print_loc: formatter -> t -> unit
+val print_error: formatter -> t -> unit
+val print_error_cur_file: formatter -> unit -> unit
+val print_warning: t -> formatter -> Warnings.t -> unit
+val formatter_for_warnings : formatter ref
+val prerr_warning: t -> Warnings.t -> unit
+val echo_eof: unit -> unit
+val reset: unit -> unit
+
+val warning_printer : (t -> formatter -> Warnings.t -> unit) ref
+(** Hook for intercepting warnings. *)
+
+val default_warning_printer : t -> formatter -> Warnings.t -> unit
+(** Original warning printer for use in hooks. *)
+
+val highlight_locations: formatter -> t list -> bool
+
+type 'a loc = {
+ txt : 'a;
+ loc : t;
+}
+
+val mknoloc : 'a -> 'a loc
+val mkloc : 'a -> t -> 'a loc
+
+val print: formatter -> t -> unit
+val print_filename: formatter -> string -> unit
+
+val absolute_path: string -> string
+
+val show_filename: string -> string
+ (** In -absname mode, return the absolute path for this filename.
+ Otherwise, returns the filename unchanged. *)
+
+
+val absname: bool ref
+
+(* Support for located errors *)
+
+type error =
+ {
+ loc: t;
+ msg: string;
+ sub: error list;
+ if_highlight: string; (* alternative message if locations are highlighted *)
+ }
+
+exception Error of error
+
+val print_error_prefix: formatter -> unit -> unit
+ (* print the prefix "Error:" possibly with style *)
+
+val error: ?loc:t -> ?sub:error list -> ?if_highlight:string -> string -> error
+
+val errorf: ?loc:t -> ?sub:error list -> ?if_highlight:string
+ -> ('a, Format.formatter, unit, error) format4 -> 'a
+
+val errorf_prefixed : ?loc:t -> ?sub:error list -> ?if_highlight:string
+ -> ('a, Format.formatter, unit, error) format4 -> 'a
+ (* same as {!errorf}, but prints the error prefix "Error:" before yielding
+ * to the format string *)
+
+val raise_errorf: ?loc:t -> ?sub:error list -> ?if_highlight:string
+ -> ('a, Format.formatter, unit, 'b) format4 -> 'a
+
+val error_of_printer: t -> (formatter -> 'a -> unit) -> 'a -> error
+
+val error_of_printer_file: (formatter -> 'a -> unit) -> 'a -> error
+
+val error_of_exn: exn -> error option
+
+val register_error_of_exn: (exn -> error option) -> unit
+ (* Each compiler module which defines a custom type of exception
+ which can surface as a user-visible error should register
+ a "printer" for this exception using [register_error_of_exn].
+ The result of the printer is an [error] value containing
+ a location, a message, and optionally sub-messages (each of them
+ being located as well). *)
+
+val report_error: formatter -> error -> unit
+
+val error_reporter : (formatter -> error -> unit) ref
+(** Hook for intercepting error reports. *)
+
+val default_error_reporter : formatter -> error -> unit
+(** Original error reporter for use in hooks. *)
+
+val report_exception: formatter -> exn -> unit
+ (* Reraise the exception if it is unknown. *)
diff --git a/parsing/longident.ml b/parsing/longident.ml
new file mode 100644
index 0000000000..706881af3a
--- /dev/null
+++ b/parsing/longident.ml
@@ -0,0 +1,41 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type t =
+ Lident of string
+ | Ldot of t * string
+ | Lapply of t * t
+
+let rec flat accu = function
+ Lident s -> s :: accu
+ | Ldot(lid, s) -> flat (s :: accu) lid
+ | Lapply(_, _) -> Misc.fatal_error "Longident.flat"
+
+let flatten lid = flat [] lid
+
+let last = function
+ Lident s -> s
+ | Ldot(_, s) -> s
+ | Lapply(_, _) -> Misc.fatal_error "Longident.last"
+
+let rec split_at_dots s pos =
+ try
+ let dot = String.index_from s pos '.' in
+ String.sub s pos (dot - pos) :: split_at_dots s (dot + 1)
+ with Not_found ->
+ [String.sub s pos (String.length s - pos)]
+
+let parse s =
+ match split_at_dots s 0 with
+ [] -> Lident "" (* should not happen, but don't put assert false
+ so as not to crash the toplevel (see Genprintval) *)
+ | hd :: tl -> List.fold_left (fun p s -> Ldot(p, s)) (Lident hd) tl
diff --git a/parsing/longident.mli b/parsing/longident.mli
new file mode 100644
index 0000000000..9e7958550c
--- /dev/null
+++ b/parsing/longident.mli
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Long identifiers, used in parsetree. *)
+
+type t =
+ Lident of string
+ | Ldot of t * string
+ | Lapply of t * t
+
+val flatten: t -> string list
+val last: t -> string
+val parse: string -> t
diff --git a/parsing/parse.ml b/parsing/parse.ml
new file mode 100644
index 0000000000..0941bf803b
--- /dev/null
+++ b/parsing/parse.ml
@@ -0,0 +1,64 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Entry points in the parser *)
+
+(* Skip tokens to the end of the phrase *)
+
+let rec skip_phrase lexbuf =
+ try
+ match Lexer.token lexbuf with
+ Parser.SEMISEMI | Parser.EOF -> ()
+ | _ -> skip_phrase lexbuf
+ with
+ | Lexer.Error (Lexer.Unterminated_comment _, _)
+ | Lexer.Error (Lexer.Unterminated_string, _)
+ | Lexer.Error (Lexer.Unterminated_string_in_comment _, _)
+ | Lexer.Error (Lexer.Illegal_character _, _) -> skip_phrase lexbuf
+;;
+
+let maybe_skip_phrase lexbuf =
+ if Parsing.is_current_lookahead Parser.SEMISEMI
+ || Parsing.is_current_lookahead Parser.EOF
+ then ()
+ else skip_phrase lexbuf
+
+let wrap parsing_fun lexbuf =
+ try
+ Docstrings.init ();
+ Lexer.init ();
+ let ast = parsing_fun Lexer.token lexbuf in
+ Parsing.clear_parser();
+ Docstrings.warn_bad_docstrings ();
+ ast
+ with
+ | Lexer.Error(Lexer.Illegal_character _, _) as err
+ when !Location.input_name = "//toplevel//"->
+ skip_phrase lexbuf;
+ raise err
+ | Syntaxerr.Error _ as err
+ when !Location.input_name = "//toplevel//" ->
+ maybe_skip_phrase lexbuf;
+ raise err
+ | Parsing.Parse_error | Syntaxerr.Escape_error ->
+ let loc = Location.curr lexbuf in
+ if !Location.input_name = "//toplevel//"
+ then maybe_skip_phrase lexbuf;
+ raise(Syntaxerr.Error(Syntaxerr.Other loc))
+
+let implementation = wrap Parser.implementation
+and interface = wrap Parser.interface
+and toplevel_phrase = wrap Parser.toplevel_phrase
+and use_file = wrap Parser.use_file
+and core_type = wrap Parser.parse_core_type
+and expression = wrap Parser.parse_expression
+and pattern = wrap Parser.parse_pattern
diff --git a/parsing/parse.mli b/parsing/parse.mli
new file mode 100644
index 0000000000..9d17a24b32
--- /dev/null
+++ b/parsing/parse.mli
@@ -0,0 +1,21 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Entry points in the parser *)
+
+val implementation : Lexing.lexbuf -> Parsetree.structure
+val interface : Lexing.lexbuf -> Parsetree.signature
+val toplevel_phrase : Lexing.lexbuf -> Parsetree.toplevel_phrase
+val use_file : Lexing.lexbuf -> Parsetree.toplevel_phrase list
+val core_type : Lexing.lexbuf -> Parsetree.core_type
+val expression : Lexing.lexbuf -> Parsetree.expression
+val pattern : Lexing.lexbuf -> Parsetree.pattern
diff --git a/parsing/parser.mly b/parsing/parser.mly
new file mode 100644
index 0000000000..1cc2dea085
--- /dev/null
+++ b/parsing/parser.mly
@@ -0,0 +1,2440 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* The parser definition */
+
+%{
+open Location
+open Asttypes
+open Longident
+open Parsetree
+open Ast_helper
+open Docstrings
+
+let mktyp d = Typ.mk ~loc:(symbol_rloc()) d
+let mkpat d = Pat.mk ~loc:(symbol_rloc()) d
+let mkexp d = Exp.mk ~loc:(symbol_rloc()) d
+let mkmty d = Mty.mk ~loc:(symbol_rloc()) d
+let mksig d = Sig.mk ~loc:(symbol_rloc()) d
+let mkmod d = Mod.mk ~loc:(symbol_rloc()) d
+let mkstr d = Str.mk ~loc:(symbol_rloc()) d
+let mkclass d = Cl.mk ~loc:(symbol_rloc()) d
+let mkcty d = Cty.mk ~loc:(symbol_rloc()) d
+let mkctf ?attrs ?docs d =
+ Ctf.mk ~loc:(symbol_rloc()) ?attrs ?docs d
+let mkcf ?attrs ?docs d =
+ Cf.mk ~loc:(symbol_rloc()) ?attrs ?docs d
+
+let mkrhs rhs pos = mkloc rhs (rhs_loc pos)
+
+let reloc_pat x = { x with ppat_loc = symbol_rloc () };;
+let reloc_exp x = { x with pexp_loc = symbol_rloc () };;
+
+let mkoperator name pos =
+ let loc = rhs_loc pos in
+ Exp.mk ~loc (Pexp_ident(mkloc (Lident name) loc))
+
+let mkpatvar name pos =
+ Pat.mk ~loc:(rhs_loc pos) (Ppat_var (mkrhs name pos))
+
+(*
+ Ghost expressions and patterns:
+ expressions and patterns that do not appear explicitly in the
+ source file they have the loc_ghost flag set to true.
+ Then the profiler will not try to instrument them and the
+ -annot option will not try to display their type.
+
+ Every grammar rule that generates an element with a location must
+ make at most one non-ghost element, the topmost one.
+
+ How to tell whether your location must be ghost:
+ A location corresponds to a range of characters in the source file.
+ If the location contains a piece of code that is syntactically
+ valid (according to the documentation), and corresponds to the
+ AST node, then the location must be real; in all other cases,
+ it must be ghost.
+*)
+let ghexp d = Exp.mk ~loc:(symbol_gloc ()) d
+let ghpat d = Pat.mk ~loc:(symbol_gloc ()) d
+let ghtyp d = Typ.mk ~loc:(symbol_gloc ()) d
+let ghloc d = { txt = d; loc = symbol_gloc () }
+let ghstr d = Str.mk ~loc:(symbol_gloc()) d
+
+let ghunit () =
+ ghexp (Pexp_construct (mknoloc (Lident "()"), None))
+
+let mkinfix arg1 name arg2 =
+ mkexp(Pexp_apply(mkoperator name 2, [Nolabel, arg1; Nolabel, arg2]))
+
+let neg_float_string f =
+ if String.length f > 0 && f.[0] = '-'
+ then String.sub f 1 (String.length f - 1)
+ else "-" ^ f
+
+let mkuminus name arg =
+ match name, arg.pexp_desc with
+ | "-", Pexp_constant(Const_int n) ->
+ mkexp(Pexp_constant(Const_int(-n)))
+ | "-", Pexp_constant(Const_int32 n) ->
+ mkexp(Pexp_constant(Const_int32(Int32.neg n)))
+ | "-", Pexp_constant(Const_int64 n) ->
+ mkexp(Pexp_constant(Const_int64(Int64.neg n)))
+ | "-", Pexp_constant(Const_nativeint n) ->
+ mkexp(Pexp_constant(Const_nativeint(Nativeint.neg n)))
+ | ("-" | "-."), Pexp_constant(Const_float f) ->
+ mkexp(Pexp_constant(Const_float(neg_float_string f)))
+ | _ ->
+ mkexp(Pexp_apply(mkoperator ("~" ^ name) 1, [Nolabel, arg]))
+
+let mkuplus name arg =
+ let desc = arg.pexp_desc in
+ match name, desc with
+ | "+", Pexp_constant(Const_int _)
+ | "+", Pexp_constant(Const_int32 _)
+ | "+", Pexp_constant(Const_int64 _)
+ | "+", Pexp_constant(Const_nativeint _)
+ | ("+" | "+."), Pexp_constant(Const_float _) -> mkexp desc
+ | _ ->
+ mkexp(Pexp_apply(mkoperator ("~" ^ name) 1, [Nolabel, arg]))
+
+let mkexp_cons consloc args loc =
+ Exp.mk ~loc (Pexp_construct(mkloc (Lident "::") consloc, Some args))
+
+let mkpat_cons consloc args loc =
+ Pat.mk ~loc (Ppat_construct(mkloc (Lident "::") consloc, Some args))
+
+let rec mktailexp nilloc = function
+ [] ->
+ let loc = { nilloc with loc_ghost = true } in
+ let nil = { txt = Lident "[]"; loc = loc } in
+ Exp.mk ~loc (Pexp_construct (nil, None))
+ | e1 :: el ->
+ let exp_el = mktailexp nilloc el in
+ let loc = {loc_start = e1.pexp_loc.loc_start;
+ loc_end = exp_el.pexp_loc.loc_end;
+ loc_ghost = true}
+ in
+ let arg = Exp.mk ~loc (Pexp_tuple [e1; exp_el]) in
+ mkexp_cons {loc with loc_ghost = true} arg loc
+
+let rec mktailpat nilloc = function
+ [] ->
+ let loc = { nilloc with loc_ghost = true } in
+ let nil = { txt = Lident "[]"; loc = loc } in
+ Pat.mk ~loc (Ppat_construct (nil, None))
+ | p1 :: pl ->
+ let pat_pl = mktailpat nilloc pl in
+ let loc = {loc_start = p1.ppat_loc.loc_start;
+ loc_end = pat_pl.ppat_loc.loc_end;
+ loc_ghost = true}
+ in
+ let arg = Pat.mk ~loc (Ppat_tuple [p1; pat_pl]) in
+ mkpat_cons {loc with loc_ghost = true} arg loc
+
+let mkstrexp e attrs =
+ { pstr_desc = Pstr_eval (e, attrs); pstr_loc = e.pexp_loc }
+
+let mkexp_constraint e (t1, t2) =
+ match t1, t2 with
+ | Some t, None -> ghexp(Pexp_constraint(e, t))
+ | _, Some t -> ghexp(Pexp_coerce(e, t1, t))
+ | None, None -> assert false
+
+let array_function par assign=
+ let op = if assign then par^"<-" else par in
+ ghloc ( Lident op )
+
+let syntax_error () =
+ raise Syntaxerr.Escape_error
+
+let unclosed opening_name opening_num closing_name closing_num =
+ raise(Syntaxerr.Error(Syntaxerr.Unclosed(rhs_loc opening_num, opening_name,
+ rhs_loc closing_num, closing_name)))
+
+let expecting pos nonterm =
+ raise Syntaxerr.(Error(Expecting(rhs_loc pos, nonterm)))
+
+let not_expecting pos nonterm =
+ raise Syntaxerr.(Error(Not_expecting(rhs_loc pos, nonterm)))
+
+let bigarray_function order assign =
+ let op =
+ match order with
+ | 1 -> ".{}"
+ | 2 -> ".{,}"
+ | 3 -> ".{,,}"
+ | _ -> ".{,..,}"
+ in
+ let op= if assign then op^"<-" else op in
+ ghloc ( Lident op )
+
+let bigarray_untuplify = function
+ { pexp_desc = Pexp_tuple explist; pexp_loc = _ } -> explist
+ | exp -> [exp]
+
+let bigarray_get arr arg =
+ let get order = bigarray_function order false in
+ match bigarray_untuplify arg with
+ [c1] ->
+ mkexp(Pexp_apply(ghexp(Pexp_ident(get 1)),
+ [Nolabel, arr; Nolabel, c1]))
+ | [c1;c2] ->
+ mkexp(Pexp_apply(ghexp(Pexp_ident(get 2)),
+ [Nolabel, arr; Nolabel, c1; Nolabel, c2]))
+ | [c1;c2;c3] ->
+ mkexp(Pexp_apply(ghexp(Pexp_ident(get 3)),
+ [Nolabel, arr; Nolabel, c1; Nolabel, c2; Nolabel, c3]))
+ | coords ->
+ mkexp(Pexp_apply(ghexp(Pexp_ident(get 0)),
+ [Nolabel, arr; Nolabel, ghexp(Pexp_array coords)]))
+
+let bigarray_set arr arg newval =
+ let set order = bigarray_function order true in
+ match bigarray_untuplify arg with
+ [c1] ->
+ mkexp(Pexp_apply(ghexp(Pexp_ident(set 1)),
+ [Nolabel, arr; Nolabel, c1; Nolabel, newval]))
+ | [c1;c2] ->
+ mkexp(Pexp_apply(ghexp(Pexp_ident(set 2)),
+ [Nolabel, arr; Nolabel, c1; Nolabel, c2;
+ Nolabel, newval]))
+ | [c1;c2;c3] ->
+ mkexp(Pexp_apply(ghexp(Pexp_ident(set 3)),
+ [Nolabel, arr; Nolabel, c1; Nolabel, c2; Nolabel, c3;
+ Nolabel, newval]))
+ | coords ->
+ mkexp(Pexp_apply(ghexp(Pexp_ident(set 0)),
+ [Nolabel, arr;
+ Nolabel, ghexp(Pexp_array coords);
+ Nolabel, newval]))
+
+let lapply p1 p2 =
+ if !Clflags.applicative_functors
+ then Lapply(p1, p2)
+ else raise (Syntaxerr.Error(Syntaxerr.Applicative_path (symbol_rloc())))
+
+let exp_of_label lbl pos =
+ mkexp (Pexp_ident(mkrhs (Lident(Longident.last lbl)) pos))
+
+let pat_of_label lbl pos =
+ mkpat (Ppat_var (mkrhs (Longident.last lbl) pos))
+
+let check_variable vl loc v =
+ if List.mem v vl then
+ raise Syntaxerr.(Error(Variable_in_scope(loc,v)))
+
+let varify_constructors var_names t =
+ let rec loop t =
+ let desc =
+ match t.ptyp_desc with
+ | Ptyp_any -> Ptyp_any
+ | Ptyp_var x ->
+ check_variable var_names t.ptyp_loc x;
+ Ptyp_var x
+ | Ptyp_arrow (label,core_type,core_type') ->
+ Ptyp_arrow(label, loop core_type, loop core_type')
+ | Ptyp_tuple lst -> Ptyp_tuple (List.map loop lst)
+ | Ptyp_constr( { txt = Lident s }, []) when List.mem s var_names ->
+ Ptyp_var s
+ | Ptyp_constr(longident, lst) ->
+ Ptyp_constr(longident, List.map loop lst)
+ | Ptyp_object (lst, o) ->
+ Ptyp_object
+ (List.map (fun (s, attrs, t) -> (s, attrs, loop t)) lst, o)
+ | Ptyp_class (longident, lst) ->
+ Ptyp_class (longident, List.map loop lst)
+ | Ptyp_alias(core_type, string) ->
+ check_variable var_names t.ptyp_loc string;
+ Ptyp_alias(loop core_type, string)
+ | Ptyp_variant(row_field_list, flag, lbl_lst_option) ->
+ Ptyp_variant(List.map loop_row_field row_field_list,
+ flag, lbl_lst_option)
+ | Ptyp_poly(string_lst, core_type) ->
+ List.iter (check_variable var_names t.ptyp_loc) string_lst;
+ Ptyp_poly(string_lst, loop core_type)
+ | Ptyp_package(longident,lst) ->
+ Ptyp_package(longident,List.map (fun (n,typ) -> (n,loop typ) ) lst)
+ | Ptyp_extension (s, arg) ->
+ Ptyp_extension (s, arg)
+ in
+ {t with ptyp_desc = desc}
+ and loop_row_field =
+ function
+ | Rtag(label,attrs,flag,lst) ->
+ Rtag(label,attrs,flag,List.map loop lst)
+ | Rinherit t ->
+ Rinherit (loop t)
+ in
+ loop t
+
+let mk_newtypes newtypes exp =
+ List.fold_right (fun newtype exp -> mkexp (Pexp_newtype (newtype, exp)))
+ newtypes exp
+
+let wrap_type_annotation newtypes core_type body =
+ let exp = mkexp(Pexp_constraint(body,core_type)) in
+ let exp = mk_newtypes newtypes exp in
+ (exp, ghtyp(Ptyp_poly(newtypes,varify_constructors newtypes core_type)))
+
+let wrap_exp_attrs body (ext, attrs) =
+ (* todo: keep exact location for the entire attribute *)
+ let body = {body with pexp_attributes = attrs @ body.pexp_attributes} in
+ match ext with
+ | None -> body
+ | Some id -> ghexp(Pexp_extension (id, PStr [mkstrexp body []]))
+
+let mkexp_attrs d attrs =
+ wrap_exp_attrs (mkexp d) attrs
+
+let text_str pos = Str.text (rhs_text pos)
+let text_sig pos = Sig.text (rhs_text pos)
+let text_cstr pos = Cf.text (rhs_text pos)
+let text_csig pos = Ctf.text (rhs_text pos)
+let text_def pos = [Ptop_def (Str.text (rhs_text pos))]
+
+let extra_text text pos items =
+ let pre_extras = rhs_pre_extra_text pos in
+ let post_extras = rhs_post_extra_text pos in
+ text pre_extras @ items @ text post_extras
+
+let extra_str pos items = extra_text Str.text pos items
+let extra_sig pos items = extra_text Sig.text pos items
+let extra_cstr pos items = extra_text Cf.text pos items
+let extra_csig pos items = extra_text Ctf.text pos items
+let extra_def pos items =
+ extra_text (fun txt -> [Ptop_def (Str.text txt)]) pos items
+
+type let_binding =
+ { lb_pattern: pattern;
+ lb_expression: expression;
+ lb_attributes: attributes;
+ lb_docs: docs Lazy.t;
+ lb_text: text Lazy.t;
+ lb_loc: Location.t; }
+
+type let_bindings =
+ { lbs_bindings: let_binding list;
+ lbs_rec: rec_flag;
+ lbs_extension: string Asttypes.loc option;
+ lbs_attributes: attributes;
+ lbs_loc: Location.t }
+
+let mklb (p, e) attrs =
+ { lb_pattern = p;
+ lb_expression = e;
+ lb_attributes = attrs;
+ lb_docs = symbol_docs_lazy ();
+ lb_text = symbol_text_lazy ();
+ lb_loc = symbol_rloc (); }
+
+let mklbs (ext, attrs) rf lb =
+ { lbs_bindings = [lb];
+ lbs_rec = rf;
+ lbs_extension = ext ;
+ lbs_attributes = attrs;
+ lbs_loc = symbol_rloc (); }
+
+let addlb lbs lb =
+ { lbs with lbs_bindings = lb :: lbs.lbs_bindings }
+
+let val_of_let_bindings lbs =
+ let str =
+ match lbs.lbs_bindings with
+ | [ {lb_pattern = { ppat_desc = Ppat_any; ppat_loc = _ }; _} as lb ] ->
+ let exp = wrap_exp_attrs lb.lb_expression
+ (None, lbs.lbs_attributes) in
+ mkstr (Pstr_eval (exp, lb.lb_attributes))
+ | bindings ->
+ if lbs.lbs_attributes <> [] then
+ raise Syntaxerr.(Error(Not_expecting(lbs.lbs_loc, "attributes")));
+ let bindings =
+ List.map
+ (fun lb ->
+ Vb.mk ~loc:lb.lb_loc ~attrs:lb.lb_attributes
+ ~docs:(Lazy.force lb.lb_docs)
+ ~text:(Lazy.force lb.lb_text)
+ lb.lb_pattern lb.lb_expression)
+ bindings
+ in
+ mkstr(Pstr_value(lbs.lbs_rec, List.rev bindings))
+ in
+ match lbs.lbs_extension with
+ | None -> str
+ | Some id -> ghstr (Pstr_extension((id, PStr [str]), []))
+
+let expr_of_let_bindings lbs body =
+ let bindings =
+ List.map
+ (fun lb ->
+ if lb.lb_attributes <> [] then
+ raise Syntaxerr.(Error(Not_expecting(lb.lb_loc, "item attribute")));
+ Vb.mk ~loc:lb.lb_loc lb.lb_pattern lb.lb_expression)
+ lbs.lbs_bindings
+ in
+ mkexp_attrs (Pexp_let(lbs.lbs_rec, List.rev bindings, body))
+ (lbs.lbs_extension, lbs.lbs_attributes)
+
+let class_of_let_bindings lbs body =
+ let bindings =
+ List.map
+ (fun lb ->
+ if lb.lb_attributes <> [] then
+ raise Syntaxerr.(Error(Not_expecting(lb.lb_loc, "item attribute")));
+ Vb.mk ~loc:lb.lb_loc lb.lb_pattern lb.lb_expression)
+ lbs.lbs_bindings
+ in
+ if lbs.lbs_extension <> None then
+ raise Syntaxerr.(Error(Not_expecting(lbs.lbs_loc, "extension")));
+ if lbs.lbs_attributes <> [] then
+ raise Syntaxerr.(Error(Not_expecting(lbs.lbs_loc, "attributes")));
+ mkclass(Pcl_let (lbs.lbs_rec, List.rev bindings, body))
+
+%}
+
+/* Tokens */
+
+%token AMPERAMPER
+%token AMPERSAND
+%token AND
+%token AS
+%token ASSERT
+%token BACKQUOTE
+%token BANG
+%token BAR
+%token BARBAR
+%token BARRBRACKET
+%token BEGIN
+%token <char> CHAR
+%token CLASS
+%token COLON
+%token COLONCOLON
+%token COLONEQUAL
+%token COLONGREATER
+%token COMMA
+%token CONSTRAINT
+%token DO
+%token DONE
+%token DOT
+%token DOTDOT
+%token DOWNTO
+%token ELSE
+%token END
+%token EOF
+%token EQUAL
+%token EXCEPTION
+%token EXTERNAL
+%token FALSE
+%token <string> FLOAT
+%token FOR
+%token FUN
+%token FUNCTION
+%token FUNCTOR
+%token GREATER
+%token GREATERRBRACE
+%token GREATERRBRACKET
+%token IF
+%token IN
+%token INCLUDE
+%token <string> INFIXOP0
+%token <string> INFIXOP1
+%token <string> INFIXOP2
+%token <string> INFIXOP3
+%token <string> INFIXOP4
+%token INHERIT
+%token INITIALIZER
+%token <int> INT
+%token <int32> INT32
+%token <int64> INT64
+%token <string> LABEL
+%token LAZY
+%token LBRACE
+%token LBRACELESS
+%token LBRACKET
+%token LBRACKETBAR
+%token LBRACKETLESS
+%token LBRACKETGREATER
+%token LBRACKETPERCENT
+%token LBRACKETPERCENTPERCENT
+%token LESS
+%token LESSMINUS
+%token LET
+%token <string> LIDENT
+%token LPAREN
+%token LBRACKETAT
+%token LBRACKETATAT
+%token LBRACKETATATAT
+%token MATCH
+%token METHOD
+%token MINUS
+%token MINUSDOT
+%token MINUSGREATER
+%token MODULE
+%token MUTABLE
+%token <nativeint> NATIVEINT
+%token NEW
+%token NONREC
+%token OBJECT
+%token OF
+%token OPEN
+%token <string> OPTLABEL
+%token OR
+/* %token PARSER */
+%token PERCENT
+%token PLUS
+%token PLUSDOT
+%token PLUSEQ
+%token <string> PREFIXOP
+%token PRIVATE
+%token QUESTION
+%token QUOTE
+%token RBRACE
+%token RBRACKET
+%token REC
+%token RPAREN
+%token SEMI
+%token SEMISEMI
+%token SHARP
+%token <string> SHARPOP
+%token SIG
+%token STAR
+%token <string * string option> STRING
+%token STRUCT
+%token THEN
+%token TILDE
+%token TO
+%token TRUE
+%token TRY
+%token TYPE
+%token <string> UIDENT
+%token UNDERSCORE
+%token VAL
+%token VIRTUAL
+%token WHEN
+%token WHILE
+%token WITH
+%token <string * Location.t> COMMENT
+%token <Docstrings.docstring> DOCSTRING
+
+%token EOL
+
+/* Precedences and associativities.
+
+Tokens and rules have precedences. A reduce/reduce conflict is resolved
+in favor of the first rule (in source file order). A shift/reduce conflict
+is resolved by comparing the precedence and associativity of the token to
+be shifted with those of the rule to be reduced.
+
+By default, a rule has the precedence of its rightmost terminal (if any).
+
+When there is a shift/reduce conflict between a rule and a token that
+have the same precedence, it is resolved using the associativity:
+if the token is left-associative, the parser will reduce; if
+right-associative, the parser will shift; if non-associative,
+the parser will declare a syntax error.
+
+We will only use associativities with operators of the kind x * x -> x
+for example, in the rules of the form expr: expr BINOP expr
+in all other cases, we define two precedences if needed to resolve
+conflicts.
+
+The precedences must be listed from low to high.
+*/
+
+%nonassoc IN
+%nonassoc below_SEMI
+%nonassoc SEMI /* below EQUAL ({lbl=...; lbl=...}) */
+%nonassoc LET /* above SEMI ( ...; let ... in ...) */
+%nonassoc below_WITH
+%nonassoc FUNCTION WITH /* below BAR (match ... with ...) */
+%nonassoc AND /* above WITH (module rec A: SIG with ... and ...) */
+%nonassoc THEN /* below ELSE (if ... then ...) */
+%nonassoc ELSE /* (if ... then ... else ...) */
+%nonassoc LESSMINUS /* below COLONEQUAL (lbl <- x := e) */
+%right COLONEQUAL /* expr (e := e := e) */
+%nonassoc AS
+%left BAR /* pattern (p|p|p) */
+%nonassoc below_COMMA
+%left COMMA /* expr/expr_comma_list (e,e,e) */
+%right MINUSGREATER /* core_type2 (t -> t -> t) */
+%right OR BARBAR /* expr (e || e || e) */
+%right AMPERSAND AMPERAMPER /* expr (e && e && e) */
+%nonassoc below_EQUAL
+%left INFIXOP0 EQUAL LESS GREATER /* expr (e OP e OP e) */
+%right INFIXOP1 /* expr (e OP e OP e) */
+%nonassoc below_LBRACKETAT
+%nonassoc LBRACKETAT
+%nonassoc LBRACKETATAT
+%right COLONCOLON /* expr (e :: e :: e) */
+%left INFIXOP2 PLUS PLUSDOT MINUS MINUSDOT PLUSEQ /* expr (e OP e OP e) */
+%left PERCENT INFIXOP3 STAR /* expr (e OP e OP e) */
+%right INFIXOP4 /* expr (e OP e OP e) */
+%nonassoc prec_unary_minus prec_unary_plus /* unary - */
+%nonassoc prec_constant_constructor /* cf. simple_expr (C versus C x) */
+%nonassoc prec_constr_appl /* above AS BAR COLONCOLON COMMA */
+%nonassoc below_SHARP
+%nonassoc SHARP /* simple_expr/toplevel_directive */
+%left SHARPOP
+%nonassoc below_DOT
+%nonassoc DOT
+/* Finally, the first tokens of simple_expr are above everything else. */
+%nonassoc BACKQUOTE BANG BEGIN CHAR FALSE FLOAT INT INT32 INT64
+ LBRACE LBRACELESS LBRACKET LBRACKETBAR LIDENT LPAREN
+ NEW NATIVEINT PREFIXOP STRING TRUE UIDENT
+ LBRACKETPERCENT LBRACKETPERCENTPERCENT
+
+
+/* Entry points */
+
+%start implementation /* for implementation files */
+%type <Parsetree.structure> implementation
+%start interface /* for interface files */
+%type <Parsetree.signature> interface
+%start toplevel_phrase /* for interactive use */
+%type <Parsetree.toplevel_phrase> toplevel_phrase
+%start use_file /* for the #use directive */
+%type <Parsetree.toplevel_phrase list> use_file
+%start parse_core_type
+%type <Parsetree.core_type> parse_core_type
+%start parse_expression
+%type <Parsetree.expression> parse_expression
+%start parse_pattern
+%type <Parsetree.pattern> parse_pattern
+%%
+
+/* Entry points */
+
+implementation:
+ structure EOF { extra_str 1 $1 }
+;
+interface:
+ signature EOF { extra_sig 1 $1 }
+;
+toplevel_phrase:
+ top_structure SEMISEMI { Ptop_def (extra_str 1 $1) }
+ | toplevel_directive SEMISEMI { $1 }
+ | EOF { raise End_of_file }
+;
+top_structure:
+ seq_expr post_item_attributes
+ { (text_str 1) @ [mkstrexp $1 $2] }
+ | top_structure_tail
+ { $1 }
+;
+top_structure_tail:
+ /* empty */ { [] }
+ | structure_item top_structure_tail { (text_str 1) @ $1 :: $2 }
+;
+use_file:
+ use_file_body { extra_def 1 $1 }
+;
+use_file_body:
+ use_file_tail { $1 }
+ | seq_expr post_item_attributes use_file_tail
+ { (text_def 1) @ Ptop_def[mkstrexp $1 $2] :: $3 }
+;
+use_file_tail:
+ EOF
+ { [] }
+ | SEMISEMI EOF
+ { text_def 1 }
+ | SEMISEMI seq_expr post_item_attributes use_file_tail
+ { mark_rhs_docs 2 3;
+ (text_def 1) @ (text_def 2) @ Ptop_def[mkstrexp $2 $3] :: $4 }
+ | SEMISEMI structure_item use_file_tail
+ { (text_def 1) @ (text_def 2) @ Ptop_def[$2] :: $3 }
+ | SEMISEMI toplevel_directive use_file_tail
+ { mark_rhs_docs 2 3;
+ (text_def 1) @ (text_def 2) @ $2 :: $3 }
+ | structure_item use_file_tail
+ { (text_def 1) @ Ptop_def[$1] :: $2 }
+ | toplevel_directive use_file_tail
+ { mark_rhs_docs 1 1;
+ (text_def 1) @ $1 :: $2 }
+;
+parse_core_type:
+ core_type EOF { $1 }
+;
+parse_expression:
+ seq_expr EOF { $1 }
+;
+parse_pattern:
+ pattern EOF { $1 }
+;
+
+/* Module expressions */
+
+functor_arg:
+ LPAREN RPAREN
+ { mkrhs "*" 2, None }
+ | LPAREN functor_arg_name COLON module_type RPAREN
+ { mkrhs $2 2, Some $4 }
+;
+
+functor_arg_name:
+ UIDENT { $1 }
+ | UNDERSCORE { "_" }
+;
+
+functor_args:
+ functor_args functor_arg
+ { $2 :: $1 }
+ | functor_arg
+ { [ $1 ] }
+;
+
+module_expr:
+ mod_longident
+ { mkmod(Pmod_ident (mkrhs $1 1)) }
+ | STRUCT structure END
+ { mkmod(Pmod_structure(extra_str 2 $2)) }
+ | STRUCT structure error
+ { unclosed "struct" 1 "end" 3 }
+ | FUNCTOR functor_args MINUSGREATER module_expr
+ { List.fold_left (fun acc (n, t) -> mkmod(Pmod_functor(n, t, acc)))
+ $4 $2 }
+ | module_expr LPAREN module_expr RPAREN
+ { mkmod(Pmod_apply($1, $3)) }
+ | module_expr LPAREN RPAREN
+ { mkmod(Pmod_apply($1, mkmod (Pmod_structure []))) }
+ | module_expr LPAREN module_expr error
+ { unclosed "(" 2 ")" 4 }
+ | LPAREN module_expr COLON module_type RPAREN
+ { mkmod(Pmod_constraint($2, $4)) }
+ | LPAREN module_expr COLON module_type error
+ { unclosed "(" 1 ")" 5 }
+ | LPAREN module_expr RPAREN
+ { $2 }
+ | LPAREN module_expr error
+ { unclosed "(" 1 ")" 3 }
+ | LPAREN VAL expr RPAREN
+ { mkmod(Pmod_unpack $3) }
+ | LPAREN VAL expr COLON package_type RPAREN
+ { mkmod(Pmod_unpack(
+ ghexp(Pexp_constraint($3, ghtyp(Ptyp_package $5))))) }
+ | LPAREN VAL expr COLON package_type COLONGREATER package_type RPAREN
+ { mkmod(Pmod_unpack(
+ ghexp(Pexp_coerce($3, Some(ghtyp(Ptyp_package $5)),
+ ghtyp(Ptyp_package $7))))) }
+ | LPAREN VAL expr COLONGREATER package_type RPAREN
+ { mkmod(Pmod_unpack(
+ ghexp(Pexp_coerce($3, None, ghtyp(Ptyp_package $5))))) }
+ | LPAREN VAL expr COLON error
+ { unclosed "(" 1 ")" 5 }
+ | LPAREN VAL expr COLONGREATER error
+ { unclosed "(" 1 ")" 5 }
+ | LPAREN VAL expr error
+ { unclosed "(" 1 ")" 4 }
+ | module_expr attribute
+ { Mod.attr $1 $2 }
+ | extension
+ { mkmod(Pmod_extension $1) }
+;
+
+structure:
+ seq_expr post_item_attributes structure_tail
+ { mark_rhs_docs 1 2;
+ (text_str 1) @ mkstrexp $1 $2 :: $3 }
+ | structure_tail { $1 }
+;
+structure_tail:
+ /* empty */ { [] }
+ | SEMISEMI structure { (text_str 1) @ $2 }
+ | structure_item structure_tail { (text_str 1) @ $1 :: $2 }
+;
+structure_item:
+ let_bindings
+ { val_of_let_bindings $1 }
+ | primitive_declaration
+ { mkstr (Pstr_primitive $1) }
+ | value_description
+ { mkstr (Pstr_primitive $1) }
+ | type_declarations
+ { let (nr, l) = $1 in mkstr(Pstr_type (nr, List.rev l)) }
+ | str_type_extension
+ { mkstr(Pstr_typext $1) }
+ | str_exception_declaration
+ { mkstr(Pstr_exception $1) }
+ | module_binding
+ { mkstr(Pstr_module $1) }
+ | rec_module_bindings
+ { mkstr(Pstr_recmodule(List.rev $1)) }
+ | module_type_declaration
+ { mkstr(Pstr_modtype $1) }
+ | open_statement { mkstr(Pstr_open $1) }
+ | class_declarations
+ { mkstr(Pstr_class (List.rev $1)) }
+ | class_type_declarations
+ { mkstr(Pstr_class_type (List.rev $1)) }
+ | str_include_statement
+ { mkstr(Pstr_include $1) }
+ | item_extension post_item_attributes
+ { mkstr(Pstr_extension ($1, (add_docs_attrs (symbol_docs ()) $2))) }
+ | floating_attribute
+ { mark_symbol_docs ();
+ mkstr(Pstr_attribute $1) }
+;
+str_include_statement:
+ INCLUDE module_expr post_item_attributes
+ { Incl.mk $2 ~attrs:$3
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+module_binding_body:
+ EQUAL module_expr
+ { $2 }
+ | COLON module_type EQUAL module_expr
+ { mkmod(Pmod_constraint($4, $2)) }
+ | functor_arg module_binding_body
+ { mkmod(Pmod_functor(fst $1, snd $1, $2)) }
+;
+module_binding:
+ MODULE UIDENT module_binding_body post_item_attributes
+ { Mb.mk (mkrhs $2 2) $3 ~attrs:$4
+ ~loc:(symbol_rloc ()) ~docs:(symbol_docs ()) }
+;
+rec_module_bindings:
+ rec_module_binding { [$1] }
+ | rec_module_bindings and_module_binding { $2 :: $1 }
+;
+rec_module_binding:
+ MODULE REC UIDENT module_binding_body post_item_attributes
+ { Mb.mk (mkrhs $3 3) $4 ~attrs:$5
+ ~loc:(symbol_rloc ()) ~docs:(symbol_docs ()) }
+;
+and_module_binding:
+ AND UIDENT module_binding_body post_item_attributes
+ { Mb.mk (mkrhs $2 2) $3 ~attrs:$4 ~loc:(symbol_rloc ())
+ ~text:(symbol_text ()) ~docs:(symbol_docs ()) }
+;
+
+/* Module types */
+
+module_type:
+ mty_longident
+ { mkmty(Pmty_ident (mkrhs $1 1)) }
+ | SIG signature END
+ { mkmty(Pmty_signature (extra_sig 2 $2)) }
+ | SIG signature error
+ { unclosed "sig" 1 "end" 3 }
+ | FUNCTOR functor_args MINUSGREATER module_type
+ %prec below_WITH
+ { List.fold_left (fun acc (n, t) -> mkmty(Pmty_functor(n, t, acc)))
+ $4 $2 }
+ | module_type WITH with_constraints
+ { mkmty(Pmty_with($1, List.rev $3)) }
+ | MODULE TYPE OF module_expr %prec below_LBRACKETAT
+ { mkmty(Pmty_typeof $4) }
+/* | LPAREN MODULE mod_longident RPAREN
+ { mkmty (Pmty_alias (mkrhs $3 3)) } */
+ | LPAREN module_type RPAREN
+ { $2 }
+ | LPAREN module_type error
+ { unclosed "(" 1 ")" 3 }
+ | extension
+ { mkmty(Pmty_extension $1) }
+ | module_type attribute
+ { Mty.attr $1 $2 }
+;
+signature:
+ /* empty */ { [] }
+ | SEMISEMI signature { (text_sig 1) @ $2 }
+ | signature_item signature { (text_sig 1) @ $1 :: $2 }
+;
+signature_item:
+ value_description
+ { mksig(Psig_value $1) }
+ | primitive_declaration
+ { mksig(Psig_value $1) }
+ | type_declarations
+ { let (nr, l) = $1 in mksig(Psig_type (nr, List.rev l)) }
+ | sig_type_extension
+ { mksig(Psig_typext $1) }
+ | sig_exception_declaration
+ { mksig(Psig_exception $1) }
+ | module_declaration
+ { mksig(Psig_module $1) }
+ | module_alias
+ { mksig(Psig_module $1) }
+ | rec_module_declarations
+ { mksig(Psig_recmodule (List.rev $1)) }
+ | module_type_declaration
+ { mksig(Psig_modtype $1) }
+ | open_statement
+ { mksig(Psig_open $1) }
+ | sig_include_statement
+ { mksig(Psig_include $1) }
+ | class_descriptions
+ { mksig(Psig_class (List.rev $1)) }
+ | class_type_declarations
+ { mksig(Psig_class_type (List.rev $1)) }
+ | item_extension post_item_attributes
+ { mksig(Psig_extension ($1, (add_docs_attrs (symbol_docs ()) $2))) }
+ | floating_attribute
+ { mark_symbol_docs ();
+ mksig(Psig_attribute $1) }
+;
+open_statement:
+ | OPEN override_flag mod_longident post_item_attributes
+ { Opn.mk (mkrhs $3 3) ~override:$2 ~attrs:$4
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+sig_include_statement:
+ INCLUDE module_type post_item_attributes %prec below_WITH
+ { Incl.mk $2 ~attrs:$3
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+module_declaration_body:
+ COLON module_type
+ { $2 }
+ | LPAREN UIDENT COLON module_type RPAREN module_declaration_body
+ { mkmty(Pmty_functor(mkrhs $2 2, Some $4, $6)) }
+ | LPAREN RPAREN module_declaration_body
+ { mkmty(Pmty_functor(mkrhs "*" 1, None, $3)) }
+;
+module_declaration:
+ MODULE UIDENT module_declaration_body post_item_attributes
+ { Md.mk (mkrhs $2 2) $3 ~attrs:$4
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+module_alias:
+ MODULE UIDENT EQUAL mod_longident post_item_attributes
+ { Md.mk (mkrhs $2 2)
+ (Mty.alias ~loc:(rhs_loc 4) (mkrhs $4 4)) ~attrs:$5
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+rec_module_declarations:
+ rec_module_declaration { [$1] }
+ | rec_module_declarations and_module_declaration { $2 :: $1 }
+;
+rec_module_declaration:
+ MODULE REC UIDENT COLON module_type post_item_attributes
+ { Md.mk (mkrhs $3 3) $5 ~attrs:$6
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+and_module_declaration:
+ AND UIDENT COLON module_type post_item_attributes
+ { Md.mk (mkrhs $2 2) $4 ~attrs:$5 ~loc:(symbol_rloc())
+ ~text:(symbol_text()) ~docs:(symbol_docs()) }
+;
+module_type_declaration_body:
+ /* empty */ { None }
+ | EQUAL module_type { Some $2 }
+;
+module_type_declaration:
+ MODULE TYPE ident module_type_declaration_body post_item_attributes
+ { Mtd.mk (mkrhs $3 3) ?typ:$4 ~attrs:$5
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+/* Class expressions */
+
+class_declarations:
+ class_declaration { [$1] }
+ | class_declarations and_class_declaration { $2 :: $1 }
+;
+class_declaration:
+ CLASS virtual_flag class_type_parameters LIDENT class_fun_binding
+ post_item_attributes
+ { Ci.mk (mkrhs $4 4) $5 ~virt:$2 ~params:$3 ~attrs:$6
+ ~loc:(symbol_rloc ()) ~docs:(symbol_docs ()) }
+;
+and_class_declaration:
+ AND virtual_flag class_type_parameters LIDENT class_fun_binding
+ post_item_attributes
+ { Ci.mk (mkrhs $4 4) $5 ~virt:$2 ~params:$3
+ ~attrs:$6 ~loc:(symbol_rloc ())
+ ~text:(symbol_text ()) ~docs:(symbol_docs ()) }
+;
+class_fun_binding:
+ EQUAL class_expr
+ { $2 }
+ | COLON class_type EQUAL class_expr
+ { mkclass(Pcl_constraint($4, $2)) }
+ | labeled_simple_pattern class_fun_binding
+ { let (l,o,p) = $1 in mkclass(Pcl_fun(l, o, p, $2)) }
+;
+class_type_parameters:
+ /*empty*/ { [] }
+ | LBRACKET type_parameter_list RBRACKET { List.rev $2 }
+;
+class_fun_def:
+ labeled_simple_pattern MINUSGREATER class_expr
+ { let (l,o,p) = $1 in mkclass(Pcl_fun(l, o, p, $3)) }
+ | labeled_simple_pattern class_fun_def
+ { let (l,o,p) = $1 in mkclass(Pcl_fun(l, o, p, $2)) }
+;
+class_expr:
+ class_simple_expr
+ { $1 }
+ | FUN class_fun_def
+ { $2 }
+ | class_simple_expr simple_labeled_expr_list
+ { mkclass(Pcl_apply($1, List.rev $2)) }
+ | let_bindings IN class_expr
+ { class_of_let_bindings $1 $3 }
+ | class_expr attribute
+ { Cl.attr $1 $2 }
+ | extension
+ { mkclass(Pcl_extension $1) }
+;
+class_simple_expr:
+ LBRACKET core_type_comma_list RBRACKET class_longident
+ { mkclass(Pcl_constr(mkloc $4 (rhs_loc 4), List.rev $2)) }
+ | class_longident
+ { mkclass(Pcl_constr(mkrhs $1 1, [])) }
+ | OBJECT class_structure END
+ { mkclass(Pcl_structure $2) }
+ | OBJECT class_structure error
+ { unclosed "object" 1 "end" 3 }
+ | LPAREN class_expr COLON class_type RPAREN
+ { mkclass(Pcl_constraint($2, $4)) }
+ | LPAREN class_expr COLON class_type error
+ { unclosed "(" 1 ")" 5 }
+ | LPAREN class_expr RPAREN
+ { $2 }
+ | LPAREN class_expr error
+ { unclosed "(" 1 ")" 3 }
+;
+class_structure:
+ | class_self_pattern class_fields
+ { Cstr.mk $1 (extra_cstr 2 (List.rev $2)) }
+;
+class_self_pattern:
+ LPAREN pattern RPAREN
+ { reloc_pat $2 }
+ | LPAREN pattern COLON core_type RPAREN
+ { mkpat(Ppat_constraint($2, $4)) }
+ | /* empty */
+ { ghpat(Ppat_any) }
+;
+class_fields:
+ /* empty */
+ { [] }
+ | class_fields class_field
+ { $2 :: (text_cstr 2) @ $1 }
+;
+class_field:
+ | INHERIT override_flag class_expr parent_binder post_item_attributes
+ { mkcf (Pcf_inherit ($2, $3, $4)) ~attrs:$5 ~docs:(symbol_docs ()) }
+ | VAL value post_item_attributes
+ { mkcf (Pcf_val $2) ~attrs:$3 ~docs:(symbol_docs ()) }
+ | METHOD method_ post_item_attributes
+ { mkcf (Pcf_method $2) ~attrs:$3 ~docs:(symbol_docs ()) }
+ | CONSTRAINT constrain_field post_item_attributes
+ { mkcf (Pcf_constraint $2) ~attrs:$3 ~docs:(symbol_docs ()) }
+ | INITIALIZER seq_expr post_item_attributes
+ { mkcf (Pcf_initializer $2) ~attrs:$3 ~docs:(symbol_docs ()) }
+ | item_extension post_item_attributes
+ { mkcf (Pcf_extension $1) ~attrs:$2 ~docs:(symbol_docs ()) }
+ | floating_attribute
+ { mark_symbol_docs ();
+ mkcf (Pcf_attribute $1) }
+;
+parent_binder:
+ AS LIDENT
+ { Some $2 }
+ | /* empty */
+ { None }
+;
+value:
+/* TODO: factorize these rules (also with method): */
+ override_flag MUTABLE VIRTUAL label COLON core_type
+ { if $1 = Override then syntax_error ();
+ mkloc $4 (rhs_loc 4), Mutable, Cfk_virtual $6 }
+ | VIRTUAL mutable_flag label COLON core_type
+ { mkrhs $3 3, $2, Cfk_virtual $5 }
+ | override_flag mutable_flag label EQUAL seq_expr
+ { mkrhs $3 3, $2, Cfk_concrete ($1, $5) }
+ | override_flag mutable_flag label type_constraint EQUAL seq_expr
+ {
+ let e = mkexp_constraint $6 $4 in
+ mkrhs $3 3, $2, Cfk_concrete ($1, e)
+ }
+;
+method_:
+/* TODO: factorize those rules... */
+ override_flag PRIVATE VIRTUAL label COLON poly_type
+ { if $1 = Override then syntax_error ();
+ mkloc $4 (rhs_loc 4), Private, Cfk_virtual $6 }
+ | override_flag VIRTUAL private_flag label COLON poly_type
+ { if $1 = Override then syntax_error ();
+ mkloc $4 (rhs_loc 4), $3, Cfk_virtual $6 }
+ | override_flag private_flag label strict_binding
+ { mkloc $3 (rhs_loc 3), $2,
+ Cfk_concrete ($1, ghexp(Pexp_poly ($4, None))) }
+ | override_flag private_flag label COLON poly_type EQUAL seq_expr
+ { mkloc $3 (rhs_loc 3), $2,
+ Cfk_concrete ($1, ghexp(Pexp_poly($7, Some $5))) }
+ | override_flag private_flag label COLON TYPE lident_list
+ DOT core_type EQUAL seq_expr
+ { let exp, poly = wrap_type_annotation $6 $8 $10 in
+ mkloc $3 (rhs_loc 3), $2,
+ Cfk_concrete ($1, ghexp(Pexp_poly(exp, Some poly))) }
+;
+
+/* Class types */
+
+class_type:
+ class_signature
+ { $1 }
+ | QUESTION LIDENT COLON simple_core_type_or_tuple MINUSGREATER
+ class_type
+ { mkcty(Pcty_arrow(Optional $2 , $4, $6)) }
+ | OPTLABEL simple_core_type_or_tuple MINUSGREATER class_type
+ { mkcty(Pcty_arrow(Optional $1, $2, $4)) }
+ | LIDENT COLON simple_core_type_or_tuple MINUSGREATER class_type
+ { mkcty(Pcty_arrow(Labelled $1, $3, $5)) }
+ | simple_core_type_or_tuple MINUSGREATER class_type
+ { mkcty(Pcty_arrow(Nolabel, $1, $3)) }
+ ;
+class_signature:
+ LBRACKET core_type_comma_list RBRACKET clty_longident
+ { mkcty(Pcty_constr (mkloc $4 (rhs_loc 4), List.rev $2)) }
+ | clty_longident
+ { mkcty(Pcty_constr (mkrhs $1 1, [])) }
+ | OBJECT class_sig_body END
+ { mkcty(Pcty_signature $2) }
+ | OBJECT class_sig_body error
+ { unclosed "object" 1 "end" 3 }
+ | class_signature attribute
+ { Cty.attr $1 $2 }
+ | extension
+ { mkcty(Pcty_extension $1) }
+;
+class_sig_body:
+ class_self_type class_sig_fields
+ { Csig.mk $1 (extra_csig 2 (List.rev $2)) }
+;
+class_self_type:
+ LPAREN core_type RPAREN
+ { $2 }
+ | /* empty */
+ { mktyp(Ptyp_any) }
+;
+class_sig_fields:
+ /* empty */ { [] }
+| class_sig_fields class_sig_field { $2 :: (text_csig 2) @ $1 }
+;
+class_sig_field:
+ INHERIT class_signature post_item_attributes
+ { mkctf (Pctf_inherit $2) ~attrs:$3 ~docs:(symbol_docs ()) }
+ | VAL value_type post_item_attributes
+ { mkctf (Pctf_val $2) ~attrs:$3 ~docs:(symbol_docs ()) }
+ | METHOD private_virtual_flags label COLON poly_type post_item_attributes
+ {
+ let (p, v) = $2 in
+ mkctf (Pctf_method ($3, p, v, $5)) ~attrs:$6 ~docs:(symbol_docs ())
+ }
+ | CONSTRAINT constrain_field post_item_attributes
+ { mkctf (Pctf_constraint $2) ~attrs:$3 ~docs:(symbol_docs ()) }
+ | item_extension post_item_attributes
+ { mkctf (Pctf_extension $1) ~attrs:$2 ~docs:(symbol_docs ()) }
+ | floating_attribute
+ { mark_symbol_docs ();
+ mkctf(Pctf_attribute $1) }
+;
+value_type:
+ VIRTUAL mutable_flag label COLON core_type
+ { $3, $2, Virtual, $5 }
+ | MUTABLE virtual_flag label COLON core_type
+ { $3, Mutable, $2, $5 }
+ | label COLON core_type
+ { $1, Immutable, Concrete, $3 }
+;
+constrain:
+ core_type EQUAL core_type { $1, $3, symbol_rloc() }
+;
+constrain_field:
+ core_type EQUAL core_type { $1, $3 }
+;
+class_descriptions:
+ class_description { [$1] }
+ | class_descriptions and_class_description { $2 :: $1 }
+;
+class_description:
+ CLASS virtual_flag class_type_parameters LIDENT COLON class_type
+ post_item_attributes
+ { Ci.mk (mkrhs $4 4) $6 ~virt:$2 ~params:$3 ~attrs:$7
+ ~loc:(symbol_rloc ()) ~docs:(symbol_docs ()) }
+;
+and_class_description:
+ AND virtual_flag class_type_parameters LIDENT COLON class_type
+ post_item_attributes
+ { Ci.mk (mkrhs $4 4) $6 ~virt:$2 ~params:$3
+ ~attrs:$7 ~loc:(symbol_rloc ())
+ ~text:(symbol_text ()) ~docs:(symbol_docs ()) }
+;
+class_type_declarations:
+ class_type_declaration { [$1] }
+ | class_type_declarations and_class_type_declaration { $2 :: $1 }
+;
+class_type_declaration:
+ CLASS TYPE virtual_flag class_type_parameters LIDENT EQUAL
+ class_signature post_item_attributes
+ { Ci.mk (mkrhs $5 5) $7 ~virt:$3 ~params:$4 ~attrs:$8
+ ~loc:(symbol_rloc ()) ~docs:(symbol_docs ()) }
+;
+and_class_type_declaration:
+ AND virtual_flag class_type_parameters LIDENT EQUAL
+ class_signature post_item_attributes
+ { Ci.mk (mkrhs $4 4) $6 ~virt:$2 ~params:$3
+ ~attrs:$7 ~loc:(symbol_rloc ())
+ ~text:(symbol_text ()) ~docs:(symbol_docs ()) }
+;
+
+/* Core expressions */
+
+seq_expr:
+ | expr %prec below_SEMI { $1 }
+ | expr SEMI { reloc_exp $1 }
+ | expr SEMI seq_expr { mkexp(Pexp_sequence($1, $3)) }
+;
+labeled_simple_pattern:
+ QUESTION LPAREN label_let_pattern opt_default RPAREN
+ { (Optional (fst $3), $4, snd $3) }
+ | QUESTION label_var
+ { (Optional (fst $2), None, snd $2) }
+ | OPTLABEL LPAREN let_pattern opt_default RPAREN
+ { (Optional $1, $4, $3) }
+ | OPTLABEL pattern_var
+ { (Optional $1, None, $2) }
+ | TILDE LPAREN label_let_pattern RPAREN
+ { (Labelled (fst $3), None, snd $3) }
+ | TILDE label_var
+ { (Labelled (fst $2), None, snd $2) }
+ | LABEL simple_pattern
+ { (Labelled $1, None, $2) }
+ | simple_pattern
+ { (Nolabel, None, $1) }
+;
+pattern_var:
+ LIDENT { mkpat(Ppat_var (mkrhs $1 1)) }
+ | UNDERSCORE { mkpat Ppat_any }
+;
+opt_default:
+ /* empty */ { None }
+ | EQUAL seq_expr { Some $2 }
+;
+label_let_pattern:
+ label_var
+ { $1 }
+ | label_var COLON core_type
+ { let (lab, pat) = $1 in (lab, mkpat(Ppat_constraint(pat, $3))) }
+;
+label_var:
+ LIDENT { ($1, mkpat(Ppat_var (mkrhs $1 1))) }
+;
+let_pattern:
+ pattern
+ { $1 }
+ | pattern COLON core_type
+ { mkpat(Ppat_constraint($1, $3)) }
+;
+expr:
+ simple_expr %prec below_SHARP
+ { $1 }
+ | simple_expr simple_labeled_expr_list
+ { mkexp(Pexp_apply($1, List.rev $2)) }
+ | let_bindings IN seq_expr
+ { expr_of_let_bindings $1 $3 }
+ | LET MODULE ext_attributes UIDENT module_binding_body IN seq_expr
+ { mkexp_attrs (Pexp_letmodule(mkrhs $4 4, $5, $7)) $3 }
+ | LET OPEN override_flag ext_attributes mod_longident IN seq_expr
+ { mkexp_attrs (Pexp_open($3, mkrhs $5 5, $7)) $4 }
+ | FUNCTION ext_attributes opt_bar match_cases
+ { mkexp_attrs (Pexp_function(List.rev $4)) $2 }
+ | FUN ext_attributes labeled_simple_pattern fun_def
+ { let (l,o,p) = $3 in
+ mkexp_attrs (Pexp_fun(l, o, p, $4)) $2 }
+ | FUN ext_attributes LPAREN TYPE lident_list RPAREN fun_def
+ { mkexp_attrs (mk_newtypes $5 $7).pexp_desc $2 }
+ | MATCH ext_attributes seq_expr WITH opt_bar match_cases
+ { mkexp_attrs (Pexp_match($3, List.rev $6)) $2 }
+ | TRY ext_attributes seq_expr WITH opt_bar match_cases
+ { mkexp_attrs (Pexp_try($3, List.rev $6)) $2 }
+ | TRY ext_attributes seq_expr WITH error
+ { syntax_error() }
+ | expr_comma_list %prec below_COMMA
+ { mkexp(Pexp_tuple(List.rev $1)) }
+ | constr_longident simple_expr %prec below_SHARP
+ { mkexp(Pexp_construct(mkrhs $1 1, Some $2)) }
+ | name_tag simple_expr %prec below_SHARP
+ { mkexp(Pexp_variant($1, Some $2)) }
+ | IF ext_attributes seq_expr THEN expr ELSE expr
+ { mkexp_attrs(Pexp_ifthenelse($3, $5, Some $7)) $2 }
+ | IF ext_attributes seq_expr THEN expr
+ { mkexp_attrs (Pexp_ifthenelse($3, $5, None)) $2 }
+ | WHILE ext_attributes seq_expr DO seq_expr DONE
+ { mkexp_attrs (Pexp_while($3, $5)) $2 }
+ | FOR ext_attributes pattern EQUAL seq_expr direction_flag seq_expr DO
+ seq_expr DONE
+ { mkexp_attrs(Pexp_for($3, $5, $7, $6, $9)) $2 }
+ | expr COLONCOLON expr
+ { mkexp_cons (rhs_loc 2) (ghexp(Pexp_tuple[$1;$3])) (symbol_rloc()) }
+ | LPAREN COLONCOLON RPAREN LPAREN expr COMMA expr RPAREN
+ { mkexp_cons (rhs_loc 2) (ghexp(Pexp_tuple[$5;$7])) (symbol_rloc()) }
+ | expr INFIXOP0 expr
+ { mkinfix $1 $2 $3 }
+ | expr INFIXOP1 expr
+ { mkinfix $1 $2 $3 }
+ | expr INFIXOP2 expr
+ { mkinfix $1 $2 $3 }
+ | expr INFIXOP3 expr
+ { mkinfix $1 $2 $3 }
+ | expr INFIXOP4 expr
+ { mkinfix $1 $2 $3 }
+ | expr PLUS expr
+ { mkinfix $1 "+" $3 }
+ | expr PLUSDOT expr
+ { mkinfix $1 "+." $3 }
+ | expr PLUSEQ expr
+ { mkinfix $1 "+=" $3 }
+ | expr MINUS expr
+ { mkinfix $1 "-" $3 }
+ | expr MINUSDOT expr
+ { mkinfix $1 "-." $3 }
+ | expr STAR expr
+ { mkinfix $1 "*" $3 }
+ | expr PERCENT expr
+ { mkinfix $1 "%" $3 }
+ | expr EQUAL expr
+ { mkinfix $1 "=" $3 }
+ | expr LESS expr
+ { mkinfix $1 "<" $3 }
+ | expr GREATER expr
+ { mkinfix $1 ">" $3 }
+ | expr OR expr
+ { mkinfix $1 "or" $3 }
+ | expr BARBAR expr
+ { mkinfix $1 "||" $3 }
+ | expr AMPERSAND expr
+ { mkinfix $1 "&" $3 }
+ | expr AMPERAMPER expr
+ { mkinfix $1 "&&" $3 }
+ | expr COLONEQUAL expr
+ { mkinfix $1 ":=" $3 }
+ | subtractive expr %prec prec_unary_minus
+ { mkuminus $1 $2 }
+ | additive expr %prec prec_unary_plus
+ { mkuplus $1 $2 }
+ | simple_expr DOT label_longident LESSMINUS expr
+ { mkexp(Pexp_setfield($1, mkrhs $3 3, $5)) }
+ | simple_expr DOT LPAREN seq_expr RPAREN LESSMINUS expr
+ { mkexp(Pexp_apply(ghexp(Pexp_ident(array_function ".()" true)),
+ [Nolabel,$1; Nolabel,$4; Nolabel,$7])) }
+ | simple_expr DOT LBRACKET seq_expr RBRACKET LESSMINUS expr
+ { mkexp(Pexp_apply(ghexp(Pexp_ident(array_function ".[]" true)),
+ [Nolabel,$1; Nolabel,$4; Nolabel,$7])) }
+ | simple_expr DOT LBRACE expr RBRACE LESSMINUS expr
+ { bigarray_set $1 $4 $7 }
+ | label LESSMINUS expr
+ { mkexp(Pexp_setinstvar(mkrhs $1 1, $3)) }
+ | ASSERT ext_attributes simple_expr %prec below_SHARP
+ { mkexp_attrs (Pexp_assert $3) $2 }
+ | LAZY ext_attributes simple_expr %prec below_SHARP
+ { mkexp_attrs (Pexp_lazy $3) $2 }
+ | OBJECT ext_attributes class_structure END
+ { mkexp_attrs (Pexp_object $3) $2 }
+ | OBJECT ext_attributes class_structure error
+ { unclosed "object" 1 "end" 4 }
+ | expr attribute
+ { Exp.attr $1 $2 }
+;
+simple_expr:
+ val_longident
+ { mkexp(Pexp_ident (mkrhs $1 1)) }
+ | constant
+ { mkexp(Pexp_constant $1) }
+ | constr_longident %prec prec_constant_constructor
+ { mkexp(Pexp_construct(mkrhs $1 1, None)) }
+ | name_tag %prec prec_constant_constructor
+ { mkexp(Pexp_variant($1, None)) }
+ | LPAREN seq_expr RPAREN
+ { reloc_exp $2 }
+ | LPAREN seq_expr error
+ { unclosed "(" 1 ")" 3 }
+ | BEGIN ext_attributes seq_expr END
+ { wrap_exp_attrs (reloc_exp $3) $2 (* check location *) }
+ | BEGIN ext_attributes END
+ { mkexp_attrs (Pexp_construct (mkloc (Lident "()") (symbol_rloc ()),
+ None)) $2 }
+ | BEGIN ext_attributes seq_expr error
+ { unclosed "begin" 1 "end" 3 }
+ | LPAREN seq_expr type_constraint RPAREN
+ { mkexp_constraint $2 $3 }
+ | simple_expr DOT label_longident
+ { mkexp(Pexp_field($1, mkrhs $3 3)) }
+ | mod_longident DOT LPAREN seq_expr RPAREN
+ { mkexp(Pexp_open(Fresh, mkrhs $1 1, $4)) }
+ | mod_longident DOT LPAREN RPAREN
+ { mkexp(Pexp_open(Fresh, mkrhs $1 1,
+ mkexp(Pexp_construct(mkrhs (Lident "()") 1, None)))) }
+ | mod_longident DOT LPAREN seq_expr error
+ { unclosed "(" 3 ")" 5 }
+ | simple_expr DOT LPAREN seq_expr RPAREN
+ { mkexp(Pexp_apply(ghexp(Pexp_ident(array_function ".()" false)),
+ [Nolabel,$1; Nolabel,$4])) }
+ | simple_expr DOT LPAREN seq_expr error
+ { unclosed "(" 3 ")" 5 }
+ | simple_expr DOT LBRACKET seq_expr RBRACKET
+ { mkexp(Pexp_apply(ghexp(Pexp_ident(array_function ".[]" false)),
+ [Nolabel,$1; Nolabel,$4])) }
+ | simple_expr DOT LBRACKET seq_expr error
+ { unclosed "[" 3 "]" 5 }
+ | simple_expr DOT LBRACE expr RBRACE
+ { bigarray_get $1 $4 }
+ | simple_expr DOT LBRACE expr_comma_list error
+ { unclosed "{" 3 "}" 5 }
+ | LBRACE record_expr RBRACE
+ { let (exten, fields) = $2 in mkexp (Pexp_record(fields, exten)) }
+ | LBRACE record_expr error
+ { unclosed "{" 1 "}" 3 }
+ | mod_longident DOT LBRACE record_expr RBRACE
+ { let (exten, fields) = $4 in
+ let rec_exp = mkexp(Pexp_record(fields, exten)) in
+ mkexp(Pexp_open(Fresh, mkrhs $1 1, rec_exp)) }
+ | mod_longident DOT LBRACE record_expr error
+ { unclosed "{" 3 "}" 5 }
+ | LBRACKETBAR expr_semi_list opt_semi BARRBRACKET
+ { mkexp (Pexp_array(List.rev $2)) }
+ | LBRACKETBAR expr_semi_list opt_semi error
+ { unclosed "[|" 1 "|]" 4 }
+ | LBRACKETBAR BARRBRACKET
+ { mkexp (Pexp_array []) }
+ | mod_longident DOT LBRACKETBAR expr_semi_list opt_semi BARRBRACKET
+ { mkexp(Pexp_open(Fresh, mkrhs $1 1, mkexp(Pexp_array(List.rev $4)))) }
+ | mod_longident DOT LBRACKETBAR BARRBRACKET
+ { mkexp(Pexp_open(Fresh, mkrhs $1 1, mkexp(Pexp_array []))) }
+ | mod_longident DOT LBRACKETBAR expr_semi_list opt_semi error
+ { unclosed "[|" 3 "|]" 6 }
+ | LBRACKET expr_semi_list opt_semi RBRACKET
+ { reloc_exp (mktailexp (rhs_loc 4) (List.rev $2)) }
+ | LBRACKET expr_semi_list opt_semi error
+ { unclosed "[" 1 "]" 4 }
+ | mod_longident DOT LBRACKET expr_semi_list opt_semi RBRACKET
+ { let list_exp = reloc_exp (mktailexp (rhs_loc 6) (List.rev $4)) in
+ mkexp(Pexp_open(Fresh, mkrhs $1 1, list_exp)) }
+ | mod_longident DOT LBRACKET RBRACKET
+ { mkexp(Pexp_open(Fresh, mkrhs $1 1,
+ mkexp(Pexp_construct(mkrhs (Lident "[]") 1, None)))) }
+ | mod_longident DOT LBRACKET expr_semi_list opt_semi error
+ { unclosed "[" 3 "]" 6 }
+ | PREFIXOP simple_expr
+ { mkexp(Pexp_apply(mkoperator $1 1, [Nolabel,$2])) }
+ | BANG simple_expr
+ { mkexp(Pexp_apply(mkoperator "!" 1, [Nolabel,$2])) }
+ | NEW ext_attributes class_longident
+ { mkexp_attrs (Pexp_new(mkrhs $3 3)) $2 }
+ | LBRACELESS field_expr_list GREATERRBRACE
+ { mkexp (Pexp_override $2) }
+ | LBRACELESS field_expr_list error
+ { unclosed "{<" 1 ">}" 4 }
+ | LBRACELESS GREATERRBRACE
+ { mkexp (Pexp_override [])}
+ | mod_longident DOT LBRACELESS field_expr_list GREATERRBRACE
+ { mkexp(Pexp_open(Fresh, mkrhs $1 1, mkexp (Pexp_override $4)))}
+ | mod_longident DOT LBRACELESS GREATERRBRACE
+ { mkexp(Pexp_open(Fresh, mkrhs $1 1, mkexp (Pexp_override [])))}
+ | mod_longident DOT LBRACELESS field_expr_list error
+ { unclosed "{<" 3 ">}" 6 }
+ | simple_expr SHARP label
+ { mkexp(Pexp_send($1, $3)) }
+ | simple_expr SHARPOP simple_expr
+ { mkinfix $1 $2 $3 }
+ | LPAREN MODULE module_expr RPAREN
+ { mkexp (Pexp_pack $3) }
+ | LPAREN MODULE module_expr COLON package_type RPAREN
+ { mkexp (Pexp_constraint (ghexp (Pexp_pack $3),
+ ghtyp (Ptyp_package $5))) }
+ | LPAREN MODULE module_expr COLON error
+ { unclosed "(" 1 ")" 5 }
+ | mod_longident DOT LPAREN MODULE module_expr COLON package_type RPAREN
+ { mkexp(Pexp_open(Fresh, mkrhs $1 1,
+ mkexp (Pexp_constraint (ghexp (Pexp_pack $5),
+ ghtyp (Ptyp_package $7))))) }
+ | mod_longident DOT LPAREN MODULE module_expr COLON error
+ { unclosed "(" 3 ")" 7 }
+ | extension
+ { mkexp (Pexp_extension $1) }
+;
+simple_labeled_expr_list:
+ labeled_simple_expr
+ { [$1] }
+ | simple_labeled_expr_list labeled_simple_expr
+ { $2 :: $1 }
+;
+labeled_simple_expr:
+ simple_expr %prec below_SHARP
+ { (Nolabel, $1) }
+ | label_expr
+ { $1 }
+;
+label_expr:
+ LABEL simple_expr %prec below_SHARP
+ { (Labelled $1, $2) }
+ | TILDE label_ident
+ { (Labelled (fst $2), snd $2) }
+ | QUESTION label_ident
+ { (Optional (fst $2), snd $2) }
+ | OPTLABEL simple_expr %prec below_SHARP
+ { (Optional $1, $2) }
+;
+label_ident:
+ LIDENT { ($1, mkexp(Pexp_ident(mkrhs (Lident $1) 1))) }
+;
+lident_list:
+ LIDENT { [$1] }
+ | LIDENT lident_list { $1 :: $2 }
+;
+let_binding_body:
+ val_ident fun_binding
+ { (mkpatvar $1 1, $2) }
+ | val_ident COLON typevar_list DOT core_type EQUAL seq_expr
+ { (ghpat(Ppat_constraint(mkpatvar $1 1,
+ ghtyp(Ptyp_poly(List.rev $3,$5)))),
+ $7) }
+ | val_ident COLON TYPE lident_list DOT core_type EQUAL seq_expr
+ { let exp, poly = wrap_type_annotation $4 $6 $8 in
+ (ghpat(Ppat_constraint(mkpatvar $1 1, poly)), exp) }
+ | pattern EQUAL seq_expr
+ { ($1, $3) }
+ | simple_pattern_not_ident COLON core_type EQUAL seq_expr
+ { (ghpat(Ppat_constraint($1, $3)), $5) }
+;
+let_bindings:
+ let_binding { $1 }
+ | let_bindings and_let_binding { addlb $1 $2 }
+;
+let_binding:
+ LET ext_attributes rec_flag let_binding_body post_item_attributes
+ { mklbs $2 $3 (mklb $4 $5) }
+;
+and_let_binding:
+ AND let_binding_body post_item_attributes
+ { mklb $2 $3 }
+;
+fun_binding:
+ strict_binding
+ { $1 }
+ | type_constraint EQUAL seq_expr
+ { mkexp_constraint $3 $1 }
+;
+strict_binding:
+ EQUAL seq_expr
+ { $2 }
+ | labeled_simple_pattern fun_binding
+ { let (l, o, p) = $1 in ghexp(Pexp_fun(l, o, p, $2)) }
+ | LPAREN TYPE lident_list RPAREN fun_binding
+ { mk_newtypes $3 $5 }
+;
+match_cases:
+ match_case { [$1] }
+ | match_cases BAR match_case { $3 :: $1 }
+;
+match_case:
+ pattern MINUSGREATER seq_expr
+ { Exp.case $1 $3 }
+ | pattern WHEN seq_expr MINUSGREATER seq_expr
+ { Exp.case $1 ~guard:$3 $5 }
+;
+fun_def:
+ MINUSGREATER seq_expr { $2 }
+/* Cf #5939: we used to accept (fun p when e0 -> e) */
+ | labeled_simple_pattern fun_def
+ {
+ let (l,o,p) = $1 in
+ ghexp(Pexp_fun(l, o, p, $2))
+ }
+ | LPAREN TYPE lident_list RPAREN fun_def
+ { mk_newtypes $3 $5 }
+;
+expr_comma_list:
+ expr_comma_list COMMA expr { $3 :: $1 }
+ | expr COMMA expr { [$3; $1] }
+;
+record_expr:
+ simple_expr WITH lbl_expr_list { (Some $1, $3) }
+ | lbl_expr_list { (None, $1) }
+;
+lbl_expr_list:
+ lbl_expr { [$1] }
+ | lbl_expr SEMI lbl_expr_list { $1 :: $3 }
+ | lbl_expr SEMI { [$1] }
+;
+lbl_expr:
+ label_longident EQUAL expr
+ { (mkrhs $1 1,$3) }
+ | label_longident
+ { (mkrhs $1 1, exp_of_label $1 1) }
+;
+field_expr_list:
+ field_expr opt_semi { [$1] }
+ | field_expr SEMI field_expr_list { $1 :: $3 }
+;
+field_expr:
+ label EQUAL expr
+ { (mkrhs $1 1, $3) }
+ | label
+ { (mkrhs $1 1, exp_of_label (Lident $1) 1) }
+;
+expr_semi_list:
+ expr { [$1] }
+ | expr_semi_list SEMI expr { $3 :: $1 }
+;
+type_constraint:
+ COLON core_type { (Some $2, None) }
+ | COLON core_type COLONGREATER core_type { (Some $2, Some $4) }
+ | COLONGREATER core_type { (None, Some $2) }
+ | COLON error { syntax_error() }
+ | COLONGREATER error { syntax_error() }
+;
+
+/* Patterns */
+
+pattern:
+ simple_pattern
+ { $1 }
+ | pattern AS val_ident
+ { mkpat(Ppat_alias($1, mkrhs $3 3)) }
+ | pattern AS error
+ { expecting 3 "identifier" }
+ | pattern_comma_list %prec below_COMMA
+ { mkpat(Ppat_tuple(List.rev $1)) }
+ | constr_longident pattern %prec prec_constr_appl
+ { mkpat(Ppat_construct(mkrhs $1 1, Some $2)) }
+ | name_tag pattern %prec prec_constr_appl
+ { mkpat(Ppat_variant($1, Some $2)) }
+ | pattern COLONCOLON pattern
+ { mkpat_cons (rhs_loc 2) (ghpat(Ppat_tuple[$1;$3])) (symbol_rloc()) }
+ | pattern COLONCOLON error
+ { expecting 3 "pattern" }
+ | LPAREN COLONCOLON RPAREN LPAREN pattern COMMA pattern RPAREN
+ { mkpat_cons (rhs_loc 2) (ghpat(Ppat_tuple[$5;$7])) (symbol_rloc()) }
+ | LPAREN COLONCOLON RPAREN LPAREN pattern COMMA pattern error
+ { unclosed "(" 4 ")" 8 }
+ | pattern BAR pattern
+ { mkpat(Ppat_or($1, $3)) }
+ | pattern BAR error
+ { expecting 3 "pattern" }
+ | LAZY simple_pattern
+ { mkpat(Ppat_lazy $2) }
+ | EXCEPTION pattern %prec prec_constr_appl
+ { mkpat(Ppat_exception $2) }
+ | pattern attribute
+ { Pat.attr $1 $2 }
+;
+simple_pattern:
+ val_ident %prec below_EQUAL
+ { mkpat(Ppat_var (mkrhs $1 1)) }
+ | simple_pattern_not_ident { $1 }
+;
+simple_pattern_not_ident:
+ | UNDERSCORE
+ { mkpat(Ppat_any) }
+ | signed_constant
+ { mkpat(Ppat_constant $1) }
+ | signed_constant DOTDOT signed_constant
+ { mkpat(Ppat_interval ($1, $3)) }
+ | constr_longident
+ { mkpat(Ppat_construct(mkrhs $1 1, None)) }
+ | name_tag
+ { mkpat(Ppat_variant($1, None)) }
+ | SHARP type_longident
+ { mkpat(Ppat_type (mkrhs $2 2)) }
+ | LBRACE lbl_pattern_list RBRACE
+ { let (fields, closed) = $2 in mkpat(Ppat_record(fields, closed)) }
+ | LBRACE lbl_pattern_list error
+ { unclosed "{" 1 "}" 3 }
+ | LBRACKET pattern_semi_list opt_semi RBRACKET
+ { reloc_pat (mktailpat (rhs_loc 4) (List.rev $2)) }
+ | LBRACKET pattern_semi_list opt_semi error
+ { unclosed "[" 1 "]" 4 }
+ | LBRACKETBAR pattern_semi_list opt_semi BARRBRACKET
+ { mkpat(Ppat_array(List.rev $2)) }
+ | LBRACKETBAR BARRBRACKET
+ { mkpat(Ppat_array []) }
+ | LBRACKETBAR pattern_semi_list opt_semi error
+ { unclosed "[|" 1 "|]" 4 }
+ | LPAREN pattern RPAREN
+ { reloc_pat $2 }
+ | LPAREN pattern error
+ { unclosed "(" 1 ")" 3 }
+ | LPAREN pattern COLON core_type RPAREN
+ { mkpat(Ppat_constraint($2, $4)) }
+ | LPAREN pattern COLON core_type error
+ { unclosed "(" 1 ")" 5 }
+ | LPAREN pattern COLON error
+ { expecting 4 "type" }
+ | LPAREN MODULE UIDENT RPAREN
+ { mkpat(Ppat_unpack (mkrhs $3 3)) }
+ | LPAREN MODULE UIDENT COLON package_type RPAREN
+ { mkpat(Ppat_constraint(mkpat(Ppat_unpack (mkrhs $3 3)),
+ ghtyp(Ptyp_package $5))) }
+ | LPAREN MODULE UIDENT COLON package_type error
+ { unclosed "(" 1 ")" 6 }
+ | extension
+ { mkpat(Ppat_extension $1) }
+;
+
+pattern_comma_list:
+ pattern_comma_list COMMA pattern { $3 :: $1 }
+ | pattern COMMA pattern { [$3; $1] }
+ | pattern COMMA error { expecting 3 "pattern" }
+;
+pattern_semi_list:
+ pattern { [$1] }
+ | pattern_semi_list SEMI pattern { $3 :: $1 }
+;
+lbl_pattern_list:
+ lbl_pattern { [$1], Closed }
+ | lbl_pattern SEMI { [$1], Closed }
+ | lbl_pattern SEMI UNDERSCORE opt_semi { [$1], Open }
+ | lbl_pattern SEMI lbl_pattern_list
+ { let (fields, closed) = $3 in $1 :: fields, closed }
+;
+lbl_pattern:
+ label_longident EQUAL pattern
+ { (mkrhs $1 1,$3) }
+ | label_longident
+ { (mkrhs $1 1, pat_of_label $1 1) }
+;
+
+/* Value descriptions */
+
+value_description:
+ VAL val_ident COLON core_type post_item_attributes
+ { Val.mk (mkrhs $2 2) $4 ~attrs:$5
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+
+/* Primitive declarations */
+
+primitive_declaration_body:
+ STRING { [fst $1] }
+ | STRING primitive_declaration_body { fst $1 :: $2 }
+;
+primitive_declaration:
+ EXTERNAL val_ident COLON core_type EQUAL primitive_declaration_body
+ post_item_attributes
+ { Val.mk (mkrhs $2 2) $4 ~prim:$6 ~attrs:$7
+ ~loc:(symbol_rloc ()) ~docs:(symbol_docs ()) }
+;
+
+/* Type declarations */
+
+type_declarations:
+ type_declaration
+ { let (nonrec_flag, ty) = $1 in (nonrec_flag, [ty]) }
+ | type_declarations and_type_declaration
+ { let (nonrec_flag, tys) = $1 in (nonrec_flag, $2 :: tys) }
+;
+
+type_declaration:
+ TYPE nonrec_flag optional_type_parameters LIDENT type_kind constraints
+ post_item_attributes
+ { let (kind, priv, manifest) = $5 in
+ let ty =
+ Type.mk (mkrhs $4 4) ~params:$3 ~cstrs:(List.rev $6) ~kind
+ ~priv ?manifest ~attrs:$7
+ ~loc:(symbol_rloc ()) ~docs:(symbol_docs ())
+ in
+ ($2, ty) }
+;
+and_type_declaration:
+ AND optional_type_parameters LIDENT type_kind constraints
+ post_item_attributes
+ { let (kind, priv, manifest) = $4 in
+ Type.mk (mkrhs $3 3) ~params:$2 ~cstrs:(List.rev $5)
+ ~kind ~priv ?manifest ~attrs:$6 ~loc:(symbol_rloc ())
+ ~text:(symbol_text ()) ~docs:(symbol_docs ()) }
+;
+constraints:
+ constraints CONSTRAINT constrain { $3 :: $1 }
+ | /* empty */ { [] }
+;
+type_kind:
+ /*empty*/
+ { (Ptype_abstract, Public, None) }
+ | EQUAL core_type
+ { (Ptype_abstract, Public, Some $2) }
+ | EQUAL PRIVATE core_type
+ { (Ptype_abstract, Private, Some $3) }
+ | EQUAL constructor_declarations
+ { (Ptype_variant(List.rev $2), Public, None) }
+ | EQUAL PRIVATE constructor_declarations
+ { (Ptype_variant(List.rev $3), Private, None) }
+ | EQUAL DOTDOT
+ { (Ptype_open, Public, None) }
+ | EQUAL private_flag LBRACE label_declarations RBRACE
+ { (Ptype_record $4, $2, None) }
+ | EQUAL core_type EQUAL private_flag constructor_declarations
+ { (Ptype_variant(List.rev $5), $4, Some $2) }
+ | EQUAL core_type EQUAL DOTDOT
+ { (Ptype_open, Public, Some $2) }
+ | EQUAL core_type EQUAL private_flag LBRACE label_declarations RBRACE
+ { (Ptype_record $6, $4, Some $2) }
+;
+optional_type_parameters:
+ /*empty*/ { [] }
+ | optional_type_parameter { [$1] }
+ | LPAREN optional_type_parameter_list RPAREN { List.rev $2 }
+;
+optional_type_parameter:
+ type_variance optional_type_variable { $2, $1 }
+;
+optional_type_parameter_list:
+ optional_type_parameter { [$1] }
+ | optional_type_parameter_list COMMA optional_type_parameter { $3 :: $1 }
+;
+optional_type_variable:
+ QUOTE ident { mktyp(Ptyp_var $2) }
+ | UNDERSCORE { mktyp(Ptyp_any) }
+;
+
+
+type_parameters:
+ /*empty*/ { [] }
+ | type_parameter { [$1] }
+ | LPAREN type_parameter_list RPAREN { List.rev $2 }
+;
+type_parameter:
+ type_variance type_variable { $2, $1 }
+;
+type_variance:
+ /* empty */ { Invariant }
+ | PLUS { Covariant }
+ | MINUS { Contravariant }
+;
+type_variable:
+ QUOTE ident { mktyp(Ptyp_var $2) }
+;
+type_parameter_list:
+ type_parameter { [$1] }
+ | type_parameter_list COMMA type_parameter { $3 :: $1 }
+;
+constructor_declarations:
+ constructor_declaration { [$1] }
+ | bar_constructor_declaration { [$1] }
+ | constructor_declarations bar_constructor_declaration { $2 :: $1 }
+;
+constructor_declaration:
+ | constr_ident generalized_constructor_arguments attributes
+ {
+ let args,res = $2 in
+ Type.constructor (mkrhs $1 1) ~args ?res ~attrs:$3
+ ~loc:(symbol_rloc()) ~info:(symbol_info ())
+ }
+;
+bar_constructor_declaration:
+ | BAR constr_ident generalized_constructor_arguments attributes
+ {
+ let args,res = $3 in
+ Type.constructor (mkrhs $2 2) ~args ?res ~attrs:$4
+ ~loc:(symbol_rloc()) ~info:(symbol_info ())
+ }
+;
+str_exception_declaration:
+ | sig_exception_declaration { $1 }
+ | EXCEPTION constr_ident EQUAL constr_longident attributes
+ post_item_attributes
+ { Te.rebind (mkrhs $2 2) (mkrhs $4 4) ~attrs:($5 @ $6)
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+sig_exception_declaration:
+ | EXCEPTION constr_ident generalized_constructor_arguments attributes
+ post_item_attributes
+ { let args, res = $3 in
+ Te.decl (mkrhs $2 2) ~args ?res ~attrs:($4 @ $5)
+ ~loc:(symbol_rloc()) ~docs:(symbol_docs ()) }
+;
+generalized_constructor_arguments:
+ /*empty*/ { (Pcstr_tuple [],None) }
+ | OF constructor_arguments { ($2,None) }
+ | COLON constructor_arguments MINUSGREATER simple_core_type
+ { ($2,Some $4) }
+ | COLON simple_core_type
+ { (Pcstr_tuple [],Some $2) }
+;
+
+constructor_arguments:
+ | core_type_list { Pcstr_tuple (List.rev $1) }
+ | LBRACE label_declarations RBRACE { Pcstr_record $2 }
+;
+label_declarations:
+ label_declaration { [$1] }
+ | label_declaration_semi { [$1] }
+ | label_declaration_semi label_declarations { $1 :: $2 }
+;
+label_declaration:
+ mutable_flag label COLON poly_type_no_attr attributes
+ {
+ Type.field (mkrhs $2 2) $4 ~mut:$1 ~attrs:$5
+ ~loc:(symbol_rloc()) ~info:(symbol_info ())
+ }
+;
+label_declaration_semi:
+ mutable_flag label COLON poly_type_no_attr attributes SEMI attributes
+ {
+ let info =
+ match rhs_info 5 with
+ | Some _ as info_before_semi -> info_before_semi
+ | None -> symbol_info ()
+ in
+ Type.field (mkrhs $2 2) $4 ~mut:$1 ~attrs:($5 @ $7)
+ ~loc:(symbol_rloc()) ~info
+ }
+;
+
+/* Type Extensions */
+
+str_type_extension:
+ TYPE nonrec_flag optional_type_parameters type_longident
+ PLUSEQ private_flag str_extension_constructors post_item_attributes
+ { if $2 <> Recursive then not_expecting 2 "nonrec flag";
+ Te.mk (mkrhs $4 4) (List.rev $7) ~params:$3 ~priv:$6
+ ~attrs:$8 ~docs:(symbol_docs ()) }
+;
+sig_type_extension:
+ TYPE nonrec_flag optional_type_parameters type_longident
+ PLUSEQ private_flag sig_extension_constructors post_item_attributes
+ { if $2 <> Recursive then not_expecting 2 "nonrec flag";
+ Te.mk (mkrhs $4 4) (List.rev $7) ~params:$3 ~priv:$6
+ ~attrs:$8 ~docs:(symbol_docs ()) }
+;
+str_extension_constructors:
+ extension_constructor_declaration { [$1] }
+ | bar_extension_constructor_declaration { [$1] }
+ | extension_constructor_rebind { [$1] }
+ | bar_extension_constructor_rebind { [$1] }
+ | str_extension_constructors bar_extension_constructor_declaration
+ { $2 :: $1 }
+ | str_extension_constructors bar_extension_constructor_rebind
+ { $2 :: $1 }
+;
+sig_extension_constructors:
+ extension_constructor_declaration { [$1] }
+ | bar_extension_constructor_declaration { [$1] }
+ | sig_extension_constructors bar_extension_constructor_declaration
+ { $2 :: $1 }
+;
+extension_constructor_declaration:
+ | constr_ident generalized_constructor_arguments attributes
+ { let args, res = $2 in
+ Te.decl (mkrhs $1 1) ~args ?res ~attrs:$3
+ ~loc:(symbol_rloc()) ~info:(symbol_info ()) }
+;
+bar_extension_constructor_declaration:
+ | BAR constr_ident generalized_constructor_arguments attributes
+ { let args, res = $3 in
+ Te.decl (mkrhs $2 2) ~args ?res ~attrs:$4
+ ~loc:(symbol_rloc()) ~info:(symbol_info ()) }
+;
+extension_constructor_rebind:
+ | constr_ident EQUAL constr_longident attributes
+ { Te.rebind (mkrhs $1 1) (mkrhs $3 3) ~attrs:$4
+ ~loc:(symbol_rloc()) ~info:(symbol_info ()) }
+;
+bar_extension_constructor_rebind:
+ | BAR constr_ident EQUAL constr_longident attributes
+ { Te.rebind (mkrhs $2 2) (mkrhs $4 4) ~attrs:$5
+ ~loc:(symbol_rloc()) ~info:(symbol_info ()) }
+;
+
+/* "with" constraints (additional type equations over signature components) */
+
+with_constraints:
+ with_constraint { [$1] }
+ | with_constraints AND with_constraint { $3 :: $1 }
+;
+with_constraint:
+ TYPE type_parameters label_longident with_type_binder core_type_no_attr
+ constraints
+ { Pwith_type
+ (mkrhs $3 3,
+ (Type.mk (mkrhs (Longident.last $3) 3)
+ ~params:$2
+ ~cstrs:(List.rev $6)
+ ~manifest:$5
+ ~priv:$4
+ ~loc:(symbol_rloc()))) }
+ /* used label_longident instead of type_longident to disallow
+ functor applications in type path */
+ | TYPE type_parameters label COLONEQUAL core_type_no_attr
+ { Pwith_typesubst
+ (Type.mk (mkrhs $3 3)
+ ~params:$2
+ ~manifest:$5
+ ~loc:(symbol_rloc())) }
+ | MODULE mod_longident EQUAL mod_ext_longident
+ { Pwith_module (mkrhs $2 2, mkrhs $4 4) }
+ | MODULE UIDENT COLONEQUAL mod_ext_longident
+ { Pwith_modsubst (mkrhs $2 2, mkrhs $4 4) }
+;
+with_type_binder:
+ EQUAL { Public }
+ | EQUAL PRIVATE { Private }
+;
+
+/* Polymorphic types */
+
+typevar_list:
+ QUOTE ident { [$2] }
+ | typevar_list QUOTE ident { $3 :: $1 }
+;
+poly_type:
+ core_type
+ { $1 }
+ | typevar_list DOT core_type
+ { mktyp(Ptyp_poly(List.rev $1, $3)) }
+;
+poly_type_no_attr:
+ core_type_no_attr
+ { $1 }
+ | typevar_list DOT core_type_no_attr
+ { mktyp(Ptyp_poly(List.rev $1, $3)) }
+;
+
+/* Core types */
+
+core_type:
+ core_type_no_attr
+ { $1 }
+ | core_type attribute
+ { Typ.attr $1 $2 }
+;
+core_type_no_attr:
+ core_type2
+ { $1 }
+ | core_type2 AS QUOTE ident
+ { mktyp(Ptyp_alias($1, $4)) }
+;
+core_type2:
+ simple_core_type_or_tuple
+ { $1 }
+ | QUESTION LIDENT COLON core_type2 MINUSGREATER core_type2
+ { mktyp(Ptyp_arrow(Optional $2 , $4, $6)) }
+ | OPTLABEL core_type2 MINUSGREATER core_type2
+ { mktyp(Ptyp_arrow(Optional $1 , $2, $4)) }
+ | LIDENT COLON core_type2 MINUSGREATER core_type2
+ { mktyp(Ptyp_arrow(Labelled $1, $3, $5)) }
+ | core_type2 MINUSGREATER core_type2
+ { mktyp(Ptyp_arrow(Nolabel, $1, $3)) }
+;
+
+simple_core_type:
+ simple_core_type2 %prec below_SHARP
+ { $1 }
+ | LPAREN core_type_comma_list RPAREN %prec below_SHARP
+ { match $2 with [sty] -> sty | _ -> raise Parse_error }
+;
+
+simple_core_type2:
+ QUOTE ident
+ { mktyp(Ptyp_var $2) }
+ | UNDERSCORE
+ { mktyp(Ptyp_any) }
+ | type_longident
+ { mktyp(Ptyp_constr(mkrhs $1 1, [])) }
+ | simple_core_type2 type_longident
+ { mktyp(Ptyp_constr(mkrhs $2 2, [$1])) }
+ | LPAREN core_type_comma_list RPAREN type_longident
+ { mktyp(Ptyp_constr(mkrhs $4 4, List.rev $2)) }
+ | LESS meth_list GREATER
+ { let (f, c) = $2 in mktyp(Ptyp_object (f, c)) }
+ | LESS GREATER
+ { mktyp(Ptyp_object ([], Closed)) }
+ | SHARP class_longident
+ { mktyp(Ptyp_class(mkrhs $2 2, [])) }
+ | simple_core_type2 SHARP class_longident
+ { mktyp(Ptyp_class(mkrhs $3 3, [$1])) }
+ | LPAREN core_type_comma_list RPAREN SHARP class_longident
+ { mktyp(Ptyp_class(mkrhs $5 5, List.rev $2)) }
+ | LBRACKET tag_field RBRACKET
+ { mktyp(Ptyp_variant([$2], Closed, None)) }
+/* PR#3835: this is not LR(1), would need lookahead=2
+ | LBRACKET simple_core_type RBRACKET
+ { mktyp(Ptyp_variant([$2], Closed, None)) }
+*/
+ | LBRACKET BAR row_field_list RBRACKET
+ { mktyp(Ptyp_variant(List.rev $3, Closed, None)) }
+ | LBRACKET row_field BAR row_field_list RBRACKET
+ { mktyp(Ptyp_variant($2 :: List.rev $4, Closed, None)) }
+ | LBRACKETGREATER opt_bar row_field_list RBRACKET
+ { mktyp(Ptyp_variant(List.rev $3, Open, None)) }
+ | LBRACKETGREATER RBRACKET
+ { mktyp(Ptyp_variant([], Open, None)) }
+ | LBRACKETLESS opt_bar row_field_list RBRACKET
+ { mktyp(Ptyp_variant(List.rev $3, Closed, Some [])) }
+ | LBRACKETLESS opt_bar row_field_list GREATER name_tag_list RBRACKET
+ { mktyp(Ptyp_variant(List.rev $3, Closed, Some (List.rev $5))) }
+ | LPAREN MODULE package_type RPAREN
+ { mktyp(Ptyp_package $3) }
+ | extension
+ { mktyp (Ptyp_extension $1) }
+;
+package_type:
+ mty_longident { (mkrhs $1 1, []) }
+ | mty_longident WITH package_type_cstrs { (mkrhs $1 1, $3) }
+;
+package_type_cstr:
+ TYPE label_longident EQUAL core_type { (mkrhs $2 2, $4) }
+;
+package_type_cstrs:
+ package_type_cstr { [$1] }
+ | package_type_cstr AND package_type_cstrs { $1::$3 }
+;
+row_field_list:
+ row_field { [$1] }
+ | row_field_list BAR row_field { $3 :: $1 }
+;
+row_field:
+ tag_field { $1 }
+ | simple_core_type { Rinherit $1 }
+;
+tag_field:
+ name_tag OF opt_ampersand amper_type_list attributes
+ { Rtag ($1, $5, $3, List.rev $4) }
+ | name_tag attributes
+ { Rtag ($1, $2, true, []) }
+;
+opt_ampersand:
+ AMPERSAND { true }
+ | /* empty */ { false }
+;
+amper_type_list:
+ core_type_no_attr { [$1] }
+ | amper_type_list AMPERSAND core_type_no_attr { $3 :: $1 }
+;
+name_tag_list:
+ name_tag { [$1] }
+ | name_tag_list name_tag { $2 :: $1 }
+;
+simple_core_type_or_tuple:
+ simple_core_type { $1 }
+ | simple_core_type STAR core_type_list
+ { mktyp(Ptyp_tuple($1 :: List.rev $3)) }
+;
+core_type_comma_list:
+ core_type { [$1] }
+ | core_type_comma_list COMMA core_type { $3 :: $1 }
+;
+core_type_list:
+ simple_core_type { [$1] }
+ | core_type_list STAR simple_core_type { $3 :: $1 }
+;
+meth_list:
+ field SEMI meth_list { let (f, c) = $3 in ($1 :: f, c) }
+ | field opt_semi { [$1], Closed }
+ | DOTDOT { [], Open }
+;
+field:
+ label COLON poly_type_no_attr attributes { ($1, $4, $3) }
+;
+label:
+ LIDENT { $1 }
+;
+
+/* Constants */
+
+constant:
+ INT { Const_int $1 }
+ | CHAR { Const_char $1 }
+ | STRING { let (s, d) = $1 in Const_string (s, d) }
+ | FLOAT { Const_float $1 }
+ | INT32 { Const_int32 $1 }
+ | INT64 { Const_int64 $1 }
+ | NATIVEINT { Const_nativeint $1 }
+;
+signed_constant:
+ constant { $1 }
+ | MINUS INT { Const_int(- $2) }
+ | MINUS FLOAT { Const_float("-" ^ $2) }
+ | MINUS INT32 { Const_int32(Int32.neg $2) }
+ | MINUS INT64 { Const_int64(Int64.neg $2) }
+ | MINUS NATIVEINT { Const_nativeint(Nativeint.neg $2) }
+ | PLUS INT { Const_int $2 }
+ | PLUS FLOAT { Const_float $2 }
+ | PLUS INT32 { Const_int32 $2 }
+ | PLUS INT64 { Const_int64 $2 }
+ | PLUS NATIVEINT { Const_nativeint $2 }
+;
+
+/* Identifiers and long identifiers */
+
+ident:
+ UIDENT { $1 }
+ | LIDENT { $1 }
+;
+val_ident:
+ LIDENT { $1 }
+ | LPAREN operator RPAREN { $2 }
+ | LPAREN operator error { unclosed "(" 1 ")" 3 }
+ | LPAREN error { expecting 2 "operator" }
+ | LPAREN MODULE error { expecting 3 "module-expr" }
+;
+operator:
+ PREFIXOP { $1 }
+ | INFIXOP0 { $1 }
+ | INFIXOP1 { $1 }
+ | INFIXOP2 { $1 }
+ | INFIXOP3 { $1 }
+ | INFIXOP4 { $1 }
+ | SHARPOP { $1 }
+ | BANG { "!" }
+ | PLUS { "+" }
+ | PLUSDOT { "+." }
+ | MINUS { "-" }
+ | MINUSDOT { "-." }
+ | STAR { "*" }
+ | EQUAL { "=" }
+ | LESS { "<" }
+ | GREATER { ">" }
+ | OR { "or" }
+ | BARBAR { "||" }
+ | AMPERSAND { "&" }
+ | AMPERAMPER { "&&" }
+ | COLONEQUAL { ":=" }
+ | PLUSEQ { "+=" }
+ | PERCENT { "%" }
+ | index_operator { $1 }
+;
+index_operator:
+ DOT index_operator_core opt_assign_arrow { $2^$3 }
+;
+index_operator_core:
+ | LPAREN RPAREN { ".()" }
+ | LBRACKET RBRACKET { ".[]" }
+ | LBRACE RBRACE { ".{}" }
+ | LBRACE COMMA RBRACE { ".{,}" }
+ | LBRACE COMMA COMMA RBRACE { ".{,,}" }
+ | LBRACE COMMA DOTDOT COMMA RBRACE { ".{,..,}"}
+;
+
+opt_assign_arrow:
+ { "" }
+ | LESSMINUS { "<-" }
+;
+
+constr_ident:
+ UIDENT { $1 }
+/* | LBRACKET RBRACKET { "[]" } */
+ | LPAREN RPAREN { "()" }
+ | COLONCOLON { "::" }
+/* | LPAREN COLONCOLON RPAREN { "::" } */
+ | FALSE { "false" }
+ | TRUE { "true" }
+;
+
+val_longident:
+ val_ident { Lident $1 }
+ | mod_longident DOT val_ident { Ldot($1, $3) }
+;
+constr_longident:
+ mod_longident %prec below_DOT { $1 }
+ | LBRACKET RBRACKET { Lident "[]" }
+ | LPAREN RPAREN { Lident "()" }
+ | FALSE { Lident "false" }
+ | TRUE { Lident "true" }
+;
+label_longident:
+ LIDENT { Lident $1 }
+ | mod_longident DOT LIDENT { Ldot($1, $3) }
+;
+type_longident:
+ LIDENT { Lident $1 }
+ | mod_ext_longident DOT LIDENT { Ldot($1, $3) }
+;
+mod_longident:
+ UIDENT { Lident $1 }
+ | mod_longident DOT UIDENT { Ldot($1, $3) }
+;
+mod_ext_longident:
+ UIDENT { Lident $1 }
+ | mod_ext_longident DOT UIDENT { Ldot($1, $3) }
+ | mod_ext_longident LPAREN mod_ext_longident RPAREN { lapply $1 $3 }
+;
+mty_longident:
+ ident { Lident $1 }
+ | mod_ext_longident DOT ident { Ldot($1, $3) }
+;
+clty_longident:
+ LIDENT { Lident $1 }
+ | mod_ext_longident DOT LIDENT { Ldot($1, $3) }
+;
+class_longident:
+ LIDENT { Lident $1 }
+ | mod_longident DOT LIDENT { Ldot($1, $3) }
+;
+
+/* Toplevel directives */
+
+toplevel_directive:
+ SHARP ident { Ptop_dir($2, Pdir_none) }
+ | SHARP ident STRING { Ptop_dir($2, Pdir_string (fst $3)) }
+ | SHARP ident INT { Ptop_dir($2, Pdir_int $3) }
+ | SHARP ident val_longident { Ptop_dir($2, Pdir_ident $3) }
+ | SHARP ident mod_longident { Ptop_dir($2, Pdir_ident $3) }
+ | SHARP ident FALSE { Ptop_dir($2, Pdir_bool false) }
+ | SHARP ident TRUE { Ptop_dir($2, Pdir_bool true) }
+;
+
+/* Miscellaneous */
+
+name_tag:
+ BACKQUOTE ident { $2 }
+;
+rec_flag:
+ /* empty */ { Nonrecursive }
+ | REC { Recursive }
+;
+nonrec_flag:
+ /* empty */ { Recursive }
+ | NONREC { Nonrecursive }
+;
+direction_flag:
+ TO { Upto }
+ | DOWNTO { Downto }
+;
+private_flag:
+ /* empty */ { Public }
+ | PRIVATE { Private }
+;
+mutable_flag:
+ /* empty */ { Immutable }
+ | MUTABLE { Mutable }
+;
+virtual_flag:
+ /* empty */ { Concrete }
+ | VIRTUAL { Virtual }
+;
+private_virtual_flags:
+ /* empty */ { Public, Concrete }
+ | PRIVATE { Private, Concrete }
+ | VIRTUAL { Public, Virtual }
+ | PRIVATE VIRTUAL { Private, Virtual }
+ | VIRTUAL PRIVATE { Private, Virtual }
+;
+override_flag:
+ /* empty */ { Fresh }
+ | BANG { Override }
+;
+opt_bar:
+ /* empty */ { () }
+ | BAR { () }
+;
+opt_semi:
+ | /* empty */ { () }
+ | SEMI { () }
+;
+subtractive:
+ | MINUS { "-" }
+ | MINUSDOT { "-." }
+;
+additive:
+ | PLUS { "+" }
+ | PLUSDOT { "+." }
+;
+
+/* Attributes and extensions */
+
+single_attr_id:
+ LIDENT { $1 }
+ | UIDENT { $1 }
+ | AND { "and" }
+ | AS { "as" }
+ | ASSERT { "assert" }
+ | BEGIN { "begin" }
+ | CLASS { "class" }
+ | CONSTRAINT { "constraint" }
+ | DO { "do" }
+ | DONE { "done" }
+ | DOWNTO { "downto" }
+ | ELSE { "else" }
+ | END { "end" }
+ | EXCEPTION { "exception" }
+ | EXTERNAL { "external" }
+ | FALSE { "false" }
+ | FOR { "for" }
+ | FUN { "fun" }
+ | FUNCTION { "function" }
+ | FUNCTOR { "functor" }
+ | IF { "if" }
+ | IN { "in" }
+ | INCLUDE { "include" }
+ | INHERIT { "inherit" }
+ | INITIALIZER { "initializer" }
+ | LAZY { "lazy" }
+ | LET { "let" }
+ | MATCH { "match" }
+ | METHOD { "method" }
+ | MODULE { "module" }
+ | MUTABLE { "mutable" }
+ | NEW { "new" }
+ | NONREC { "nonrec" }
+ | OBJECT { "object" }
+ | OF { "of" }
+ | OPEN { "open" }
+ | OR { "or" }
+ | PRIVATE { "private" }
+ | REC { "rec" }
+ | SIG { "sig" }
+ | STRUCT { "struct" }
+ | THEN { "then" }
+ | TO { "to" }
+ | TRUE { "true" }
+ | TRY { "try" }
+ | TYPE { "type" }
+ | VAL { "val" }
+ | VIRTUAL { "virtual" }
+ | WHEN { "when" }
+ | WHILE { "while" }
+ | WITH { "with" }
+/* mod/land/lor/lxor/lsl/lsr/asr are not supported for now */
+;
+
+attr_id:
+ single_attr_id { mkloc $1 (symbol_rloc()) }
+ | single_attr_id DOT attr_id { mkloc ($1 ^ "." ^ $3.txt) (symbol_rloc())}
+;
+attribute:
+ LBRACKETAT attr_id payload RBRACKET { ($2, $3) }
+;
+post_item_attribute:
+ LBRACKETATAT attr_id payload RBRACKET { ($2, $3) }
+;
+floating_attribute:
+ LBRACKETATATAT attr_id payload RBRACKET { ($2, $3) }
+;
+post_item_attributes:
+ /* empty */ { [] }
+ | post_item_attribute post_item_attributes { $1 :: $2 }
+;
+attributes:
+ /* empty */{ [] }
+ | attribute attributes { $1 :: $2 }
+;
+ext_attributes:
+ /* empty */ { None, [] }
+ | attribute attributes { None, $1 :: $2 }
+ | PERCENT attr_id attributes { Some $2, $3 }
+;
+extension:
+ LBRACKETPERCENT attr_id payload RBRACKET { ($2, $3) }
+;
+item_extension:
+ LBRACKETPERCENTPERCENT attr_id payload RBRACKET { ($2, $3) }
+;
+payload:
+ structure { PStr $1 }
+ | COLON core_type { PTyp $2 }
+ | QUESTION pattern { PPat ($2, None) }
+ | QUESTION pattern WHEN seq_expr { PPat ($2, Some $4) }
+;
+%%
diff --git a/parsing/parsetree.mli b/parsing/parsetree.mli
new file mode 100644
index 0000000000..3f97142a51
--- /dev/null
+++ b/parsing/parsetree.mli
@@ -0,0 +1,836 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Abstract syntax tree produced by parsing *)
+
+open Asttypes
+
+(** {2 Extension points} *)
+
+type attribute = string loc * payload
+ (* [@id ARG]
+ [@@id ARG]
+
+ Metadata containers passed around within the AST.
+ The compiler ignores unknown attributes.
+ *)
+
+and extension = string loc * payload
+ (* [%id ARG]
+ [%%id ARG]
+
+ Sub-language placeholder -- rejected by the typechecker.
+ *)
+
+and attributes = attribute list
+
+and payload =
+ | PStr of structure
+ | PTyp of core_type (* : T *)
+ | PPat of pattern * expression option (* ? P or ? P when E *)
+
+(** {2 Core language} *)
+
+(* Type expressions *)
+
+and core_type =
+ {
+ ptyp_desc: core_type_desc;
+ ptyp_loc: Location.t;
+ ptyp_attributes: attributes; (* ... [@id1] [@id2] *)
+ }
+
+and core_type_desc =
+ | Ptyp_any
+ (* _ *)
+ | Ptyp_var of string
+ (* 'a *)
+ | Ptyp_arrow of arg_label * core_type * core_type
+ (* T1 -> T2 Simple
+ ~l:T1 -> T2 Labelled
+ ?l:T1 -> T2 Otional
+ *)
+ | Ptyp_tuple of core_type list
+ (* T1 * ... * Tn
+
+ Invariant: n >= 2
+ *)
+ | Ptyp_constr of Longident.t loc * core_type list
+ (* tconstr
+ T tconstr
+ (T1, ..., Tn) tconstr
+ *)
+ | Ptyp_object of (string * attributes * core_type) list * closed_flag
+ (* < l1:T1; ...; ln:Tn > (flag = Closed)
+ < l1:T1; ...; ln:Tn; .. > (flag = Open)
+ *)
+ | Ptyp_class of Longident.t loc * core_type list
+ (* #tconstr
+ T #tconstr
+ (T1, ..., Tn) #tconstr
+ *)
+ | Ptyp_alias of core_type * string
+ (* T as 'a *)
+ | Ptyp_variant of row_field list * closed_flag * label list option
+ (* [ `A|`B ] (flag = Closed; labels = None)
+ [> `A|`B ] (flag = Open; labels = None)
+ [< `A|`B ] (flag = Closed; labels = Some [])
+ [< `A|`B > `X `Y ](flag = Closed; labels = Some ["X";"Y"])
+ *)
+ | Ptyp_poly of string list * core_type
+ (* 'a1 ... 'an. T
+
+ Can only appear in the following context:
+
+ - As the core_type of a Ppat_constraint node corresponding
+ to a constraint on a let-binding: let x : 'a1 ... 'an. T
+ = e ...
+
+ - Under Cfk_virtual for methods (not values).
+
+ - As the core_type of a Pctf_method node.
+
+ - As the core_type of a Pexp_poly node.
+
+ - As the pld_type field of a label_declaration.
+
+ - As a core_type of a Ptyp_object node.
+ *)
+
+ | Ptyp_package of package_type
+ (* (module S) *)
+ | Ptyp_extension of extension
+ (* [%id] *)
+
+and package_type = Longident.t loc * (Longident.t loc * core_type) list
+ (*
+ (module S)
+ (module S with type t1 = T1 and ... and tn = Tn)
+ *)
+
+and row_field =
+ | Rtag of label * attributes * bool * core_type list
+ (* [`A] ( true, [] )
+ [`A of T] ( false, [T] )
+ [`A of T1 & .. & Tn] ( false, [T1;...Tn] )
+ [`A of & T1 & .. & Tn] ( true, [T1;...Tn] )
+
+ - The 2nd field is true if the tag contains a
+ constant (empty) constructor.
+ - '&' occurs when several types are used for the same constructor
+ (see 4.2 in the manual)
+
+ - TODO: switch to a record representation, and keep location
+ *)
+ | Rinherit of core_type
+ (* [ T ] *)
+
+(* Patterns *)
+
+and pattern =
+ {
+ ppat_desc: pattern_desc;
+ ppat_loc: Location.t;
+ ppat_attributes: attributes; (* ... [@id1] [@id2] *)
+ }
+
+and pattern_desc =
+ | Ppat_any
+ (* _ *)
+ | Ppat_var of string loc
+ (* x *)
+ | Ppat_alias of pattern * string loc
+ (* P as 'a *)
+ | Ppat_constant of constant
+ (* 1, 'a', "true", 1.0, 1l, 1L, 1n *)
+ | Ppat_interval of constant * constant
+ (* 'a'..'z'
+
+ Other forms of interval are recognized by the parser
+ but rejected by the type-checker. *)
+ | Ppat_tuple of pattern list
+ (* (P1, ..., Pn)
+
+ Invariant: n >= 2
+ *)
+ | Ppat_construct of Longident.t loc * pattern option
+ (* C None
+ C P Some P
+ C (P1, ..., Pn) Some (Ppat_tuple [P1; ...; Pn])
+ *)
+ | Ppat_variant of label * pattern option
+ (* `A (None)
+ `A P (Some P)
+ *)
+ | Ppat_record of (Longident.t loc * pattern) list * closed_flag
+ (* { l1=P1; ...; ln=Pn } (flag = Closed)
+ { l1=P1; ...; ln=Pn; _} (flag = Open)
+
+ Invariant: n > 0
+ *)
+ | Ppat_array of pattern list
+ (* [| P1; ...; Pn |] *)
+ | Ppat_or of pattern * pattern
+ (* P1 | P2 *)
+ | Ppat_constraint of pattern * core_type
+ (* (P : T) *)
+ | Ppat_type of Longident.t loc
+ (* #tconst *)
+ | Ppat_lazy of pattern
+ (* lazy P *)
+ | Ppat_unpack of string loc
+ (* (module P)
+ Note: (module P : S) is represented as
+ Ppat_constraint(Ppat_unpack, Ptyp_package)
+ *)
+ | Ppat_exception of pattern
+ (* exception P *)
+ | Ppat_extension of extension
+ (* [%id] *)
+
+(* Value expressions *)
+
+and expression =
+ {
+ pexp_desc: expression_desc;
+ pexp_loc: Location.t;
+ pexp_attributes: attributes; (* ... [@id1] [@id2] *)
+ }
+
+and expression_desc =
+ | Pexp_ident of Longident.t loc
+ (* x
+ M.x
+ *)
+ | Pexp_constant of constant
+ (* 1, 'a', "true", 1.0, 1l, 1L, 1n *)
+ | Pexp_let of rec_flag * value_binding list * expression
+ (* let P1 = E1 and ... and Pn = EN in E (flag = Nonrecursive)
+ let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
+ *)
+ | Pexp_function of case list
+ (* function P1 -> E1 | ... | Pn -> En *)
+ | Pexp_fun of arg_label * expression option * pattern * expression
+ (* fun P -> E1 (Simple, None)
+ fun ~l:P -> E1 (Labelled l, None)
+ fun ?l:P -> E1 (Optional l, None)
+ fun ?l:(P = E0) -> E1 (Optional l, Some E0)
+
+ Notes:
+ - If E0 is provided, only Optional is allowed.
+ - "fun P1 P2 .. Pn -> E1" is represented as nested Pexp_fun.
+ - "let f P = E" is represented using Pexp_fun.
+ *)
+ | Pexp_apply of expression * (arg_label * expression) list
+ (* E0 ~l1:E1 ... ~ln:En
+ li can be empty (non labeled argument) or start with '?'
+ (optional argument).
+
+ Invariant: n > 0
+ *)
+ | Pexp_match of expression * case list
+ (* match E0 with P1 -> E1 | ... | Pn -> En *)
+ | Pexp_try of expression * case list
+ (* try E0 with P1 -> E1 | ... | Pn -> En *)
+ | Pexp_tuple of expression list
+ (* (E1, ..., En)
+
+ Invariant: n >= 2
+ *)
+ | Pexp_construct of Longident.t loc * expression option
+ (* C None
+ C E Some E
+ C (E1, ..., En) Some (Pexp_tuple[E1;...;En])
+ *)
+ | Pexp_variant of label * expression option
+ (* `A (None)
+ `A E (Some E)
+ *)
+ | Pexp_record of (Longident.t loc * expression) list * expression option
+ (* { l1=P1; ...; ln=Pn } (None)
+ { E0 with l1=P1; ...; ln=Pn } (Some E0)
+
+ Invariant: n > 0
+ *)
+ | Pexp_field of expression * Longident.t loc
+ (* E.l *)
+ | Pexp_setfield of expression * Longident.t loc * expression
+ (* E1.l <- E2 *)
+ | Pexp_array of expression list
+ (* [| E1; ...; En |] *)
+ | Pexp_ifthenelse of expression * expression * expression option
+ (* if E1 then E2 else E3 *)
+ | Pexp_sequence of expression * expression
+ (* E1; E2 *)
+ | Pexp_while of expression * expression
+ (* while E1 do E2 done *)
+ | Pexp_for of
+ pattern * expression * expression * direction_flag * expression
+ (* for i = E1 to E2 do E3 done (flag = Upto)
+ for i = E1 downto E2 do E3 done (flag = Downto)
+ *)
+ | Pexp_constraint of expression * core_type
+ (* (E : T) *)
+ | Pexp_coerce of expression * core_type option * core_type
+ (* (E :> T) (None, T)
+ (E : T0 :> T) (Some T0, T)
+ *)
+ | Pexp_send of expression * string
+ (* E # m *)
+ | Pexp_new of Longident.t loc
+ (* new M.c *)
+ | Pexp_setinstvar of string loc * expression
+ (* x <- 2 *)
+ | Pexp_override of (string loc * expression) list
+ (* {< x1 = E1; ...; Xn = En >} *)
+ | Pexp_letmodule of string loc * module_expr * expression
+ (* let module M = ME in E *)
+ | Pexp_assert of expression
+ (* assert E
+ Note: "assert false" is treated in a special way by the
+ type-checker. *)
+ | Pexp_lazy of expression
+ (* lazy E *)
+ | Pexp_poly of expression * core_type option
+ (* Used for method bodies.
+
+ Can only be used as the expression under Cfk_concrete
+ for methods (not values). *)
+ | Pexp_object of class_structure
+ (* object ... end *)
+ | Pexp_newtype of string * expression
+ (* fun (type t) -> E *)
+ | Pexp_pack of module_expr
+ (* (module ME)
+
+ (module ME : S) is represented as
+ Pexp_constraint(Pexp_pack, Ptyp_package S) *)
+ | Pexp_open of override_flag * Longident.t loc * expression
+ (* let open M in E
+ let! open M in E
+ *)
+ | Pexp_extension of extension
+ (* [%id] *)
+
+and case = (* (P -> E) or (P when E0 -> E) *)
+ {
+ pc_lhs: pattern;
+ pc_guard: expression option;
+ pc_rhs: expression;
+ }
+
+(* Value descriptions *)
+
+and value_description =
+ {
+ pval_name: string loc;
+ pval_type: core_type;
+ pval_prim: string list;
+ pval_attributes: attributes; (* ... [@@id1] [@@id2] *)
+ pval_loc: Location.t;
+ }
+
+(*
+ val x: T (prim = [])
+ external x: T = "s1" ... "sn" (prim = ["s1";..."sn"])
+*)
+
+(* Type declarations *)
+
+and type_declaration =
+ {
+ ptype_name: string loc;
+ ptype_params: (core_type * variance) list;
+ (* ('a1,...'an) t; None represents _*)
+ ptype_cstrs: (core_type * core_type * Location.t) list;
+ (* ... constraint T1=T1' ... constraint Tn=Tn' *)
+ ptype_kind: type_kind;
+ ptype_private: private_flag; (* = private ... *)
+ ptype_manifest: core_type option; (* = T *)
+ ptype_attributes: attributes; (* ... [@@id1] [@@id2] *)
+ ptype_loc: Location.t;
+ }
+
+(*
+ type t (abstract, no manifest)
+ type t = T0 (abstract, manifest=T0)
+ type t = C of T | ... (variant, no manifest)
+ type t = T0 = C of T | ... (variant, manifest=T0)
+ type t = {l: T; ...} (record, no manifest)
+ type t = T0 = {l : T; ...} (record, manifest=T0)
+ type t = .. (open, no manifest)
+*)
+
+and type_kind =
+ | Ptype_abstract
+ | Ptype_variant of constructor_declaration list
+ (* Invariant: non-empty list *)
+ | Ptype_record of label_declaration list
+ (* Invariant: non-empty list *)
+ | Ptype_open
+
+and label_declaration =
+ {
+ pld_name: string loc;
+ pld_mutable: mutable_flag;
+ pld_type: core_type;
+ pld_loc: Location.t;
+ pld_attributes: attributes; (* l [@id1] [@id2] : T *)
+ }
+
+(* { ...; l: T; ... } (mutable=Immutable)
+ { ...; mutable l: T; ... } (mutable=Mutable)
+
+ Note: T can be a Ptyp_poly.
+*)
+
+and constructor_declaration =
+ {
+ pcd_name: string loc;
+ pcd_args: constructor_arguments;
+ pcd_res: core_type option;
+ pcd_loc: Location.t;
+ pcd_attributes: attributes; (* C [@id1] [@id2] of ... *)
+ }
+
+and constructor_arguments =
+ | Pcstr_tuple of core_type list
+ | Pcstr_record of label_declaration list
+
+(*
+ | C of T1 * ... * Tn (res = None, args = Pcstr_tuple [])
+ | C: T0 (res = Some T0, args = [])
+ | C: T1 * ... * Tn -> T0 (res = Some T0, args = Pcstr_tuple)
+ | C of {...} (res = None, args = Pcstr_record)
+ | C: {...} -> T0 (res = Some T0, args = Pcstr_record)
+ | C of {...} as t (res = None, args = Pcstr_record)
+*)
+
+and type_extension =
+ {
+ ptyext_path: Longident.t loc;
+ ptyext_params: (core_type * variance) list;
+ ptyext_constructors: extension_constructor list;
+ ptyext_private: private_flag;
+ ptyext_attributes: attributes; (* ... [@@id1] [@@id2] *)
+ }
+(*
+ type t += ...
+*)
+
+and extension_constructor =
+ {
+ pext_name: string loc;
+ pext_kind : extension_constructor_kind;
+ pext_loc : Location.t;
+ pext_attributes: attributes; (* C [@id1] [@id2] of ... *)
+ }
+
+and extension_constructor_kind =
+ Pext_decl of constructor_arguments * core_type option
+ (*
+ | C of T1 * ... * Tn ([T1; ...; Tn], None)
+ | C: T0 ([], Some T0)
+ | C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0)
+ *)
+ | Pext_rebind of Longident.t loc
+ (*
+ | C = D
+ *)
+
+(** {2 Class language} *)
+
+(* Type expressions for the class language *)
+
+and class_type =
+ {
+ pcty_desc: class_type_desc;
+ pcty_loc: Location.t;
+ pcty_attributes: attributes; (* ... [@id1] [@id2] *)
+ }
+
+and class_type_desc =
+ | Pcty_constr of Longident.t loc * core_type list
+ (* c
+ ['a1, ..., 'an] c *)
+ | Pcty_signature of class_signature
+ (* object ... end *)
+ | Pcty_arrow of arg_label * core_type * class_type
+ (* T -> CT Simple
+ ~l:T -> CT Labelled l
+ ?l:T -> CT Optional l
+ *)
+ | Pcty_extension of extension
+ (* [%id] *)
+
+and class_signature =
+ {
+ pcsig_self: core_type;
+ pcsig_fields: class_type_field list;
+ }
+(* object('selfpat) ... end
+ object ... end (self = Ptyp_any)
+ *)
+
+and class_type_field =
+ {
+ pctf_desc: class_type_field_desc;
+ pctf_loc: Location.t;
+ pctf_attributes: attributes; (* ... [@@id1] [@@id2] *)
+ }
+
+and class_type_field_desc =
+ | Pctf_inherit of class_type
+ (* inherit CT *)
+ | Pctf_val of (string * mutable_flag * virtual_flag * core_type)
+ (* val x: T *)
+ | Pctf_method of (string * private_flag * virtual_flag * core_type)
+ (* method x: T
+
+ Note: T can be a Ptyp_poly.
+ *)
+ | Pctf_constraint of (core_type * core_type)
+ (* constraint T1 = T2 *)
+ | Pctf_attribute of attribute
+ (* [@@@id] *)
+ | Pctf_extension of extension
+ (* [%%id] *)
+
+and 'a class_infos =
+ {
+ pci_virt: virtual_flag;
+ pci_params: (core_type * variance) list;
+ pci_name: string loc;
+ pci_expr: 'a;
+ pci_loc: Location.t;
+ pci_attributes: attributes; (* ... [@@id1] [@@id2] *)
+ }
+(* class c = ...
+ class ['a1,...,'an] c = ...
+ class virtual c = ...
+
+ Also used for "class type" declaration.
+*)
+
+and class_description = class_type class_infos
+
+and class_type_declaration = class_type class_infos
+
+(* Value expressions for the class language *)
+
+and class_expr =
+ {
+ pcl_desc: class_expr_desc;
+ pcl_loc: Location.t;
+ pcl_attributes: attributes; (* ... [@id1] [@id2] *)
+ }
+
+and class_expr_desc =
+ | Pcl_constr of Longident.t loc * core_type list
+ (* c
+ ['a1, ..., 'an] c *)
+ | Pcl_structure of class_structure
+ (* object ... end *)
+ | Pcl_fun of arg_label * expression option * pattern * class_expr
+ (* fun P -> CE (Simple, None)
+ fun ~l:P -> CE (Labelled l, None)
+ fun ?l:P -> CE (Optional l, None)
+ fun ?l:(P = E0) -> CE (Optional l, Some E0)
+ *)
+ | Pcl_apply of class_expr * (arg_label * expression) list
+ (* CE ~l1:E1 ... ~ln:En
+ li can be empty (non labeled argument) or start with '?'
+ (optional argument).
+
+ Invariant: n > 0
+ *)
+ | Pcl_let of rec_flag * value_binding list * class_expr
+ (* let P1 = E1 and ... and Pn = EN in CE (flag = Nonrecursive)
+ let rec P1 = E1 and ... and Pn = EN in CE (flag = Recursive)
+ *)
+ | Pcl_constraint of class_expr * class_type
+ (* (CE : CT) *)
+ | Pcl_extension of extension
+ (* [%id] *)
+
+and class_structure =
+ {
+ pcstr_self: pattern;
+ pcstr_fields: class_field list;
+ }
+(* object(selfpat) ... end
+ object ... end (self = Ppat_any)
+ *)
+
+and class_field =
+ {
+ pcf_desc: class_field_desc;
+ pcf_loc: Location.t;
+ pcf_attributes: attributes; (* ... [@@id1] [@@id2] *)
+ }
+
+and class_field_desc =
+ | Pcf_inherit of override_flag * class_expr * string option
+ (* inherit CE
+ inherit CE as x
+ inherit! CE
+ inherit! CE as x
+ *)
+ | Pcf_val of (string loc * mutable_flag * class_field_kind)
+ (* val x = E
+ val virtual x: T
+ *)
+ | Pcf_method of (string loc * private_flag * class_field_kind)
+ (* method x = E (E can be a Pexp_poly)
+ method virtual x: T (T can be a Ptyp_poly)
+ *)
+ | Pcf_constraint of (core_type * core_type)
+ (* constraint T1 = T2 *)
+ | Pcf_initializer of expression
+ (* initializer E *)
+ | Pcf_attribute of attribute
+ (* [@@@id] *)
+ | Pcf_extension of extension
+ (* [%%id] *)
+
+and class_field_kind =
+ | Cfk_virtual of core_type
+ | Cfk_concrete of override_flag * expression
+
+and class_declaration = class_expr class_infos
+
+(** {2 Module language} *)
+
+(* Type expressions for the module language *)
+
+and module_type =
+ {
+ pmty_desc: module_type_desc;
+ pmty_loc: Location.t;
+ pmty_attributes: attributes; (* ... [@id1] [@id2] *)
+ }
+
+and module_type_desc =
+ | Pmty_ident of Longident.t loc
+ (* S *)
+ | Pmty_signature of signature
+ (* sig ... end *)
+ | Pmty_functor of string loc * module_type option * module_type
+ (* functor(X : MT1) -> MT2 *)
+ | Pmty_with of module_type * with_constraint list
+ (* MT with ... *)
+ | Pmty_typeof of module_expr
+ (* module type of ME *)
+ | Pmty_extension of extension
+ (* [%id] *)
+ | Pmty_alias of Longident.t loc
+ (* (module M) *)
+
+and signature = signature_item list
+
+and signature_item =
+ {
+ psig_desc: signature_item_desc;
+ psig_loc: Location.t;
+ }
+
+and signature_item_desc =
+ | Psig_value of value_description
+ (*
+ val x: T
+ external x: T = "s1" ... "sn"
+ *)
+ | Psig_type of rec_flag * type_declaration list
+ (* type t1 = ... and ... and tn = ... *)
+ | Psig_typext of type_extension
+ (* type t1 += ... *)
+ | Psig_exception of extension_constructor
+ (* exception C of T *)
+ | Psig_module of module_declaration
+ (* module X : MT *)
+ | Psig_recmodule of module_declaration list
+ (* module rec X1 : MT1 and ... and Xn : MTn *)
+ | Psig_modtype of module_type_declaration
+ (* module type S = MT
+ module type S *)
+ | Psig_open of open_description
+ (* open X *)
+ | Psig_include of include_description
+ (* include MT *)
+ | Psig_class of class_description list
+ (* class c1 : ... and ... and cn : ... *)
+ | Psig_class_type of class_type_declaration list
+ (* class type ct1 = ... and ... and ctn = ... *)
+ | Psig_attribute of attribute
+ (* [@@@id] *)
+ | Psig_extension of extension * attributes
+ (* [%%id] *)
+
+and module_declaration =
+ {
+ pmd_name: string loc;
+ pmd_type: module_type;
+ pmd_attributes: attributes; (* ... [@@id1] [@@id2] *)
+ pmd_loc: Location.t;
+ }
+(* S : MT *)
+
+and module_type_declaration =
+ {
+ pmtd_name: string loc;
+ pmtd_type: module_type option;
+ pmtd_attributes: attributes; (* ... [@@id1] [@@id2] *)
+ pmtd_loc: Location.t;
+ }
+(* S = MT
+ S (abstract module type declaration, pmtd_type = None)
+*)
+
+and open_description =
+ {
+ popen_lid: Longident.t loc;
+ popen_override: override_flag;
+ popen_loc: Location.t;
+ popen_attributes: attributes;
+ }
+(* open! X - popen_override = Override (silences the 'used identifier
+ shadowing' warning)
+ open X - popen_override = Fresh
+ *)
+
+and 'a include_infos =
+ {
+ pincl_mod: 'a;
+ pincl_loc: Location.t;
+ pincl_attributes: attributes;
+ }
+
+and include_description = module_type include_infos
+(* include MT *)
+
+and include_declaration = module_expr include_infos
+(* include ME *)
+
+and with_constraint =
+ | Pwith_type of Longident.t loc * type_declaration
+ (* with type X.t = ...
+
+ Note: the last component of the longident must match
+ the name of the type_declaration. *)
+ | Pwith_module of Longident.t loc * Longident.t loc
+ (* with module X.Y = Z *)
+ | Pwith_typesubst of type_declaration
+ (* with type t := ... *)
+ | Pwith_modsubst of string loc * Longident.t loc
+ (* with module X := Z *)
+
+(* Value expressions for the module language *)
+
+and module_expr =
+ {
+ pmod_desc: module_expr_desc;
+ pmod_loc: Location.t;
+ pmod_attributes: attributes; (* ... [@id1] [@id2] *)
+ }
+
+and module_expr_desc =
+ | Pmod_ident of Longident.t loc
+ (* X *)
+ | Pmod_structure of structure
+ (* struct ... end *)
+ | Pmod_functor of string loc * module_type option * module_expr
+ (* functor(X : MT1) -> ME *)
+ | Pmod_apply of module_expr * module_expr
+ (* ME1(ME2) *)
+ | Pmod_constraint of module_expr * module_type
+ (* (ME : MT) *)
+ | Pmod_unpack of expression
+ (* (val E) *)
+ | Pmod_extension of extension
+ (* [%id] *)
+
+and structure = structure_item list
+
+and structure_item =
+ {
+ pstr_desc: structure_item_desc;
+ pstr_loc: Location.t;
+ }
+
+and structure_item_desc =
+ | Pstr_eval of expression * attributes
+ (* E *)
+ | Pstr_value of rec_flag * value_binding list
+ (* let P1 = E1 and ... and Pn = EN (flag = Nonrecursive)
+ let rec P1 = E1 and ... and Pn = EN (flag = Recursive)
+ *)
+ | Pstr_primitive of value_description
+ (* val x: T
+ external x: T = "s1" ... "sn" *)
+ | Pstr_type of rec_flag * type_declaration list
+ (* type t1 = ... and ... and tn = ... *)
+ | Pstr_typext of type_extension
+ (* type t1 += ... *)
+ | Pstr_exception of extension_constructor
+ (* exception C of T
+ exception C = M.X *)
+ | Pstr_module of module_binding
+ (* module X = ME *)
+ | Pstr_recmodule of module_binding list
+ (* module rec X1 = ME1 and ... and Xn = MEn *)
+ | Pstr_modtype of module_type_declaration
+ (* module type S = MT *)
+ | Pstr_open of open_description
+ (* open X *)
+ | Pstr_class of class_declaration list
+ (* class c1 = ... and ... and cn = ... *)
+ | Pstr_class_type of class_type_declaration list
+ (* class type ct1 = ... and ... and ctn = ... *)
+ | Pstr_include of include_declaration
+ (* include ME *)
+ | Pstr_attribute of attribute
+ (* [@@@id] *)
+ | Pstr_extension of extension * attributes
+ (* [%%id] *)
+
+and value_binding =
+ {
+ pvb_pat: pattern;
+ pvb_expr: expression;
+ pvb_attributes: attributes;
+ pvb_loc: Location.t;
+ }
+
+and module_binding =
+ {
+ pmb_name: string loc;
+ pmb_expr: module_expr;
+ pmb_attributes: attributes;
+ pmb_loc: Location.t;
+ }
+(* X = ME *)
+
+(** {2 Toplevel} *)
+
+(* Toplevel phrases *)
+
+type toplevel_phrase =
+ | Ptop_def of structure
+ | Ptop_dir of string * directive_argument
+ (* #use, #load ... *)
+
+and directive_argument =
+ | Pdir_none
+ | Pdir_string of string
+ | Pdir_int of int
+ | Pdir_ident of Longident.t
+ | Pdir_bool of bool
diff --git a/parsing/pprintast.ml b/parsing/pprintast.ml
new file mode 100644
index 0000000000..05ac854b6a
--- /dev/null
+++ b/parsing/pprintast.ml
@@ -0,0 +1,1452 @@
+(**************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Thomas Gazagnaire (OCamlPro), Fabrice Le Fessant (INRIA Saclay) *)
+(* Hongbo Zhang (University of Pennsylvania) *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(**************************************************************************)
+
+(* Original Code from Ber-metaocaml, modified for 3.12.0 and fixed *)
+(* Printing code expressions *)
+(* Authors: Ed Pizzi, Fabrice Le Fessant *)
+(* Extensive Rewrite: Hongbo Zhang: University of Pennsylvania *)
+(* TODO more fine-grained precedence pretty-printing *)
+
+open Asttypes
+open Format
+open Location
+open Longident
+open Parsetree
+
+let prefix_symbols = [ '!'; '?'; '~' ] ;;
+let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/';
+ '$'; '%' ]
+let operator_chars = [ '!'; '$'; '%'; '&'; '*'; '+'; '-'; '.'; '/';
+ ':'; '<'; '='; '>'; '?'; '@'; '^'; '|'; '~' ]
+let numeric_chars = [ '0'; '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9' ]
+
+(* type fixity = Infix| Prefix *)
+
+let special_infix_strings =
+ ["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!=" ]
+
+(* determines if the string is an infix string.
+ checks backwards, first allowing a renaming postfix ("_102") which
+ may have resulted from Pexp -> Texp -> Pexp translation, then checking
+ if all the characters in the beginning of the string are valid infix
+ characters. *)
+let fixity_of_string = function
+ | s when List.mem s special_infix_strings -> `Infix s
+ | s when List.mem s.[0] infix_symbols -> `Infix s
+ | s when List.mem s.[0] prefix_symbols -> `Prefix s
+ | _ -> `Normal
+
+let view_fixity_of_exp = function
+ | {pexp_desc = Pexp_ident {txt=Lident l;_};_} -> fixity_of_string l
+ | _ -> `Normal ;;
+
+let is_infix = function | `Infix _ -> true | _ -> false
+
+(* which identifiers are in fact operators needing parentheses *)
+let needs_parens txt =
+ is_infix (fixity_of_string txt)
+ || List.mem txt.[0] prefix_symbols
+
+(* some infixes need spaces around parens to avoid clashes with comment
+ syntax *)
+let needs_spaces txt =
+ txt.[0]='*' || txt.[String.length txt - 1] = '*'
+
+(* add parentheses to binders when they are in fact infix or prefix operators *)
+let protect_ident ppf txt =
+ let format : (_, _, _) format =
+ if not (needs_parens txt) then "%s"
+ else if needs_spaces txt then "(@;%s@;)"
+ else "(%s)"
+ in fprintf ppf format txt
+
+let protect_longident ppf print_longident longprefix txt =
+ let format : (_, _, _) format =
+ if not (needs_parens txt) then "%a.%s"
+ else if needs_spaces txt then "%a.(@;%s@;)"
+ else "%a.(%s)" in
+ fprintf ppf format print_longident longprefix txt
+
+type space_formatter = (unit, Format.formatter, unit) format
+
+let override = function
+ | Override -> "!"
+ | Fresh -> ""
+
+(* variance encoding: need to sync up with the [parser.mly] *)
+let type_variance = function
+ | Invariant -> ""
+ | Covariant -> "+"
+ | Contravariant -> "-"
+
+type construct =
+ [ `cons of expression list
+ | `list of expression list
+ | `nil
+ | `normal
+ | `simple of Longident.t
+ | `tuple ]
+
+let view_expr x =
+ match x.pexp_desc with
+ | Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple
+ | Pexp_construct ( {txt= Lident "[]";_},_) -> `nil
+ | Pexp_construct ( {txt= Lident"::";_},Some _) ->
+ let rec loop exp acc = match exp with
+ | {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_);_} ->
+ (List.rev acc,true)
+ | {pexp_desc=
+ Pexp_construct ({txt=Lident "::";_},
+ Some ({pexp_desc= Pexp_tuple([e1;e2]);_}));_} ->
+ loop e2 (e1::acc)
+ | e -> (List.rev (e::acc),false) in
+ let (ls,b) = loop x [] in
+ if b then
+ `list ls
+ else `cons ls
+ | Pexp_construct (x,None) -> `simple (x.txt)
+ | _ -> `normal
+
+let is_simple_construct :construct -> bool = function
+ | `nil | `tuple | `list _ | `simple _ -> true
+ | `cons _ | `normal -> false
+
+let pp = fprintf
+
+class printer ()= object(self:'self)
+ val pipe = false
+ val semi = false
+ val ifthenelse = false
+ method under_pipe = {<pipe=true>}
+ method under_semi = {<semi=true>}
+ method under_ifthenelse = {<ifthenelse=true>}
+ method reset_semi = {<semi=false>}
+ method reset_ifthenelse = {<ifthenelse=false>}
+ method reset_pipe = {<pipe=false>}
+ method reset = {<pipe=false;semi=false;ifthenelse=false>}
+ method list : 'a . ?sep:space_formatter -> ?first:space_formatter ->
+ ?last:space_formatter -> (Format.formatter -> 'a -> unit) ->
+ Format.formatter -> 'a list -> unit
+ = fun ?sep ?first ?last fu f xs ->
+ let first = match first with Some x -> x |None -> ""
+ and last = match last with Some x -> x |None -> ""
+ and sep = match sep with Some x -> x |None -> "@ " in
+ let aux f = function
+ | [] -> ()
+ | [x] -> fu f x
+ | xs ->
+ let rec loop f = function
+ | [x] -> fu f x
+ | x::xs -> fu f x; pp f sep; loop f xs;
+ | _ -> assert false in begin
+ pp f first; loop f xs; pp f last;
+ end in
+ aux f xs
+ method option : 'a. ?first:space_formatter -> ?last:space_formatter ->
+ (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit =
+ fun ?first ?last fu f a ->
+ let first = match first with Some x -> x | None -> ""
+ and last = match last with Some x -> x | None -> "" in
+ match a with
+ | None -> ()
+ | Some x -> pp f first; fu f x; pp f last;
+ method paren: 'a . ?first:space_formatter -> ?last:space_formatter ->
+ bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit =
+ fun ?(first="") ?(last="") b fu f x ->
+ if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")")
+ else fu f x
+
+
+ method longident f = function
+ | Lident s -> protect_ident f s
+ | Ldot(y,s) -> protect_longident f self#longident y s
+ | Lapply (y,s) ->
+ pp f "%a(%a)" self#longident y self#longident s
+ method longident_loc f x = pp f "%a" self#longident x.txt
+ method constant f = function
+ | Const_char i -> pp f "%C" i
+ | Const_string (i, None) -> pp f "%S" i
+ | Const_string (i, Some delim) -> pp f "{%s|%s|%s}" delim i delim
+ | Const_int i -> self#paren (i<0) (fun f -> pp f "%d") f i
+ | Const_float i -> self#paren (i.[0]='-') (fun f -> pp f "%s") f i
+ | Const_int32 i -> self#paren (i<0l) (fun f -> pp f "%ldl") f i
+ | Const_int64 i -> self#paren (i<0L) (fun f -> pp f "%LdL") f i
+ (* pp f "%LdL" i *)
+ | Const_nativeint i -> self#paren (i<0n) (fun f -> pp f "%ndn") f i
+ (* pp f "%ndn" i *)
+
+ (* trailing space*)
+ method mutable_flag f = function
+ | Immutable -> ()
+ | Mutable -> pp f "mutable@;"
+ method virtual_flag f = function
+ | Concrete -> ()
+ | Virtual -> pp f "virtual@;"
+
+ (* trailing space added *)
+ method rec_flag f rf =
+ match rf with
+ | Nonrecursive -> ()
+ | Recursive -> pp f "rec "
+ method nonrec_flag f rf =
+ match rf with
+ | Nonrecursive -> pp f "nonrec "
+ | Recursive -> ()
+ method direction_flag f = function
+ | Upto -> pp f "to@ "
+ | Downto -> pp f "downto@ "
+ method private_flag f = function
+ | Public -> ()
+ | Private -> pp f "private@ "
+
+ method constant_string f s = pp f "%S" s
+ method tyvar f str = pp f "'%s" str
+ method string_quot f x = pp f "`%s" x
+
+ (* c ['a,'b] *)
+ method class_params_def f = function
+ | [] -> ()
+ | l ->
+ pp f "[%a] " (* space *)
+ (self#list self#type_param ~sep:",") l
+
+ method type_with_label f (label,({ptyp_desc;_}as c) ) =
+ match label with
+ | Nolabel -> self#core_type1 f c (* otherwise parenthesize *)
+ | Labelled s -> pp f "%s:%a" s self#core_type1 c
+ | Optional s -> pp f "?%s:%a" s self#core_type1 c
+ method core_type f x =
+ if x.ptyp_attributes <> [] then begin
+ pp f "((%a)%a)" self#core_type {x with ptyp_attributes=[]}
+ self#attributes x.ptyp_attributes
+ end
+ else match x.ptyp_desc with
+ | Ptyp_arrow (l, ct1, ct2) ->
+ pp f "@[<2>%a@;->@;%a@]" (* FIXME remove parens later *)
+ self#type_with_label (l,ct1) self#core_type ct2
+ | Ptyp_alias (ct, s) ->
+ pp f "@[<2>%a@;as@;'%s@]" self#core_type1 ct s
+ | Ptyp_poly (sl, ct) ->
+ pp f "@[<2>%a%a@]"
+ (fun f l ->
+ pp f "%a"
+ (fun f l -> match l with
+ | [] -> ()
+ | _ ->
+ pp f "%a@;.@;"
+ (self#list self#tyvar ~sep:"@;") l)
+ l)
+ sl self#core_type ct
+ | _ -> pp f "@[<2>%a@]" self#core_type1 x
+ method core_type1 f x =
+ if x.ptyp_attributes <> [] then self#core_type f x
+ else match x.ptyp_desc with
+ | Ptyp_any -> pp f "_";
+ | Ptyp_var s -> self#tyvar f s;
+ | Ptyp_tuple l -> pp f "(%a)" (self#list self#core_type1 ~sep:"*@;") l
+ | Ptyp_constr (li, l) ->
+ pp f (* "%a%a@;" *) "%a%a"
+ (fun f l -> match l with
+ |[] -> ()
+ |[x]-> pp f "%a@;" self#core_type1 x
+ | _ -> self#list ~first:"(" ~last:")@;" self#core_type ~sep:"," f l)
+ l self#longident_loc li
+ | Ptyp_variant (l, closed, low) ->
+ let type_variant_helper f x =
+ match x with
+ | Rtag (l, attrs, _, ctl) -> pp f "@[<2>%a%a@;%a@]" self#string_quot l
+ (fun f l -> match l with
+ |[] -> ()
+ | _ -> pp f "@;of@;%a"
+ (self#list self#core_type ~sep:"&") ctl) ctl
+ self#attributes attrs
+ | Rinherit ct -> self#core_type f ct in
+ pp f "@[<2>[%a%a]@]"
+ (fun f l
+ ->
+ match l with
+ | [] -> ()
+ | _ ->
+ pp f "%s@;%a"
+ (match (closed,low) with
+ | (Closed,None) -> ""
+ | (Closed,Some _) -> "<" (* FIXME desugar the syntax sugar*)
+ | (Open,_) -> ">")
+ (self#list type_variant_helper ~sep:"@;<1 -2>| ") l) l
+ (fun f low
+ ->
+ match low with
+ |Some [] |None -> ()
+ |Some xs ->
+ pp f ">@ %a"
+ (self#list self#string_quot) xs) low
+ | Ptyp_object (l, o) ->
+ let core_field_type f (s, attrs, ct) =
+ pp f "@[<hov2>%s%a@ :%a@ @]" s
+ self#attributes attrs self#core_type ct
+ in
+ let field_var f = function
+ | Asttypes.Closed -> ()
+ | Asttypes.Open ->
+ match l with
+ | [] -> pp f ".."
+ | _ -> pp f " ;.."
+ in
+ pp f "@[<hov2><@ %a%a@ >@]" (self#list core_field_type ~sep:";") l
+ field_var o
+ | Ptyp_class (li, l) -> (*FIXME*)
+ pp f "@[<hov2>%a#%a@]"
+ (self#list self#core_type ~sep:"," ~first:"(" ~last:")") l
+ self#longident_loc li
+ | Ptyp_package (lid, cstrs) ->
+ let aux f (s, ct) =
+ pp f "type %a@ =@ %a" self#longident_loc s self#core_type ct in
+ (match cstrs with
+ |[] -> pp f "@[<hov2>(module@ %a)@]" self#longident_loc lid
+ |_ ->
+ pp f "@[<hov2>(module@ %a@ with@ %a)@]" self#longident_loc lid
+ (self#list aux ~sep:"@ and@ ") cstrs)
+ | Ptyp_extension e -> self#extension f e
+ | _ -> self#paren true self#core_type f x
+ (********************pattern********************)
+ (* be cautious when use [pattern], [pattern1] is preferred *)
+ method pattern f x =
+ let rec list_of_pattern acc = function (* only consider ((A|B)|C)*)
+ | {ppat_desc= Ppat_or (p1,p2);_} ->
+ list_of_pattern (p2::acc) p1
+ | x -> x::acc in
+ if x.ppat_attributes <> [] then begin
+ pp f "((%a)%a)" self#pattern {x with ppat_attributes=[]}
+ self#attributes x.ppat_attributes
+ end
+ else match x.ppat_desc with
+ | Ppat_alias (p, s) -> pp f "@[<2>%a@;as@;%a@]"
+ self#pattern p protect_ident s.txt (* RA*)
+ | Ppat_or (p1, p2) -> (* *)
+ pp f "@[<hov0>%a@]" (self#list ~sep:"@,|" self#pattern)
+ (list_of_pattern [] x)
+ | _ -> self#pattern1 f x
+ method pattern1 (f:Format.formatter) (x:pattern) :unit =
+ let rec pattern_list_helper f = function
+ | {ppat_desc =
+ Ppat_construct
+ ({ txt = Lident("::") ;_},
+ Some ({ppat_desc = Ppat_tuple([pat1; pat2]);_})); _}
+ -> pp f "%a::%a" self#simple_pattern pat1 pattern_list_helper pat2
+ (*RA*)
+ | p -> self#pattern1 f p in
+ if x.ppat_attributes <> [] then self#pattern f x
+ else match x.ppat_desc with
+ | Ppat_variant (l, Some p) -> pp f "@[<2>`%s@;%a@]" l self#simple_pattern p
+ | Ppat_construct (({txt=Lident("()"|"[]");_}), _) -> self#simple_pattern f x
+ | Ppat_construct (({txt;_} as li), po) ->
+ (* FIXME The third field always false *)
+ if txt = Lident "::" then
+ pp f "%a" pattern_list_helper x
+ else
+ (match po with
+ |Some x ->
+ pp f "%a@;%a" self#longident_loc li self#simple_pattern x
+ | None -> pp f "%a@;"self#longident_loc li )
+ | _ -> self#simple_pattern f x
+ method simple_pattern (f:Format.formatter) (x:pattern) :unit =
+ if x.ppat_attributes <> [] then self#pattern f x
+ else match x.ppat_desc with
+ | Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), _) -> pp f "%s" x
+ | Ppat_any -> pp f "_";
+ | Ppat_var ({txt = txt;_}) -> protect_ident f txt
+ | Ppat_array l ->
+ pp f "@[<2>[|%a|]@]" (self#list self#pattern1 ~sep:";") l
+ | Ppat_unpack (s) ->
+ pp f "(module@ %s)@ " s.txt
+ | Ppat_type li ->
+ pp f "#%a" self#longident_loc li
+ | Ppat_record (l, closed) ->
+ let longident_x_pattern f (li, p) =
+ match (li,p.ppat_desc) with
+ | ({txt=Lident s;_ },Ppat_var {txt;_} ) when s = txt ->
+ pp f "@[<2>%a@]" self#longident_loc li
+ | _ ->
+ pp f "@[<2>%a@;=@;%a@]" self#longident_loc li self#pattern1 p in
+ (match closed with
+ |Closed ->
+ pp f "@[<2>{@;%a@;}@]"
+ (self#list longident_x_pattern ~sep:";@;") l
+ | _ ->
+ pp f "@[<2>{@;%a;_}@]"
+ (self#list longident_x_pattern ~sep:";@;") l)
+ | Ppat_tuple l -> pp f "@[<1>(%a)@]" (self#list ~sep:"," self#pattern1) l
+ (* level1*)
+ | Ppat_constant (c) -> pp f "%a" self#constant c
+ | Ppat_interval (c1, c2) -> pp f "%a..%a" self#constant c1 self#constant c2
+ | Ppat_variant (l,None) -> pp f "`%s" l
+ | Ppat_constraint (p, ct) ->
+ pp f "@[<2>(%a@;:@;%a)@]" self#pattern1 p self#core_type ct
+ | Ppat_lazy p ->
+ pp f "@[<2>(lazy@;%a)@]" self#pattern1 p
+ | Ppat_exception p ->
+ pp f "@[<2>exception@;%a@]" self#pattern1 p
+ | Ppat_extension e -> self#extension f e
+ | _ -> self#paren true self#pattern f x
+
+ method label_exp f (l,opt,p) =
+ match l with
+ | Nolabel ->
+ pp f "%a@ " self#simple_pattern p
+ (*single case pattern parens needed here *)
+ | Optional rest ->
+ begin match p.ppat_desc with
+ | Ppat_var {txt;_} when txt = rest ->
+ (match opt with
+ | Some o -> pp f "?(%s=@;%a)@;" rest self#expression o
+ | None -> pp f "?%s@ " rest)
+ | _ ->
+ (match opt with
+ | Some o ->
+ pp f "?%s:(%a=@;%a)@;" rest self#pattern1 p self#expression o
+ | None -> pp f "?%s:%a@;" rest self#simple_pattern p)
+ end
+ | Labelled l ->
+ (match p.ppat_desc with
+ | Ppat_var {txt;_} when txt = l ->
+ pp f "~%s@;" l
+ | _ -> pp f "~%s:%a@;" l self#simple_pattern p )
+ method sugar_expr f e =
+ if e.pexp_attributes <> [] then false
+ (* should also check attributes underneath *)
+ else match e.pexp_desc with
+ | Pexp_apply
+ ({pexp_desc=
+ Pexp_ident
+ {txt= Ldot (Lident (("Array"|"String") as s),"get");_};_},
+ [(_,e1);(_,e2)]) -> begin
+ let fmt:(_,_,_)format =
+ if s= "Array" then "@[%a.(%a)@]" else "@[%a.[%a]@]" in
+ pp f fmt self#simple_expr e1 self#expression e2;
+ true
+ end
+ |Pexp_apply
+ ({pexp_desc=
+ Pexp_ident
+ {txt= Ldot (Lident (("Array"|"String") as s),
+ "set");_};_},[(_,e1);(_,e2);(_,e3)])
+ ->
+ let fmt :(_,_,_) format=
+ if s= "Array" then
+ "@[%a.(%a)@ <-@;%a@]"
+ else
+ "@[%a.[%a]@ <-@;%a@]" in (* @;< gives error here *)
+ pp f fmt self#simple_expr e1 self#expression e2 self#expression e3;
+ true
+ | Pexp_apply ({pexp_desc=Pexp_ident {txt=Lident "!";_};_}, [(_,e)]) -> begin
+ pp f "@[<hov>!%a@]" self#simple_expr e;
+ true
+ end
+ | Pexp_apply
+ ({pexp_desc=Pexp_ident
+ {txt= Ldot (Ldot (Lident "Bigarray", array),
+ ("get"|"set" as gs)) ;_};_},
+ label_exprs) ->
+ begin match array, gs, label_exprs with
+ | "Genarray", "get",
+ [(_,a);(_,{pexp_desc=Pexp_array ls;_})] ->
+ pp f "@[%a.{%a}@]" self#simple_expr a
+ (self#list ~sep:"," self#simple_expr ) ls;
+ true
+ | "Genarray", "set",
+ [(_,a);(_,{pexp_desc=Pexp_array ls;_});(_,c)] ->
+ pp f "@[%a.{%a}@ <-@ %a@]" self#simple_expr a
+ (self#list ~sep:"," self#simple_expr ) ls self#simple_expr c;
+ true
+ | "Array1", "set", [(_,a);(_,i);(_,v)] ->
+ pp f "@[%a.{%a}@ <-@ %a@]"
+ self#simple_expr a
+ self#simple_expr i
+ self#simple_expr v;
+ true
+ | "Array2", "set", [(_,a);(_,i1);(_,i2);(_,v)] ->
+ pp f "@[%a.{%a,%a}@ <-@ %a@]"
+ self#simple_expr a
+ self#simple_expr i1
+ self#simple_expr i2
+ self#simple_expr v;
+ true
+ | "Array3", "set", [(_,a);(_,i1);(_,i2);(_,i3);(_,v)] ->
+ pp f "@[%a.{%a,%a,%a}@ <-@ %a@]"
+ self#simple_expr a
+ self#simple_expr i1
+ self#simple_expr i2
+ self#simple_expr i3
+ self#simple_expr v;
+ true
+ | "Array1", "get", [(_,a);(_,i)] ->
+ pp f "@[%a.{%a}@]"
+ self#simple_expr a
+ self#simple_expr i;
+ true
+ | "Array2", "get", [(_,a);(_,i1);(_,i2)] ->
+ pp f "@[%a.{%a,%a}@]"
+ self#simple_expr a
+ self#simple_expr i1
+ self#simple_expr i2;
+ true
+ | "Array3", "get", [(_,a);(_,i1);(_,i2);(_,i3)] ->
+ pp f "@[%a.{%a,%a,%a}@]"
+ self#simple_expr a
+ self#simple_expr i1
+ self#simple_expr i2
+ self#simple_expr i3;
+ true
+ | _ -> false
+ end
+ | _ -> false
+ method expression f x =
+ if x.pexp_attributes <> [] then begin
+ pp f "((%a)%a)" self#expression {x with pexp_attributes=[]}
+ self#attributes x.pexp_attributes
+ end
+ else match x.pexp_desc with
+ | Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _
+ when pipe || semi ->
+ self#paren true self#reset#expression f x
+ | Pexp_ifthenelse _ | Pexp_sequence _ when ifthenelse ->
+ self#paren true self#reset#expression f x
+ | Pexp_let _ | Pexp_letmodule _ when semi ->
+ self#paren true self#reset#expression f x
+ | Pexp_fun (l, e0, p, e) ->
+ pp f "@[<2>fun@;%a@;->@;%a@]"
+ self#label_exp (l, e0, p)
+ self#expression e
+ | Pexp_function l ->
+ pp f "@[<hv>function%a@]" self#case_list l
+ | Pexp_match (e, l) ->
+ pp f "@[<hv0>@[<hv0>@[<2>match %a@]@ with@]%a@]" self#reset#expression
+ e self#case_list l
+
+ | Pexp_try (e, l) ->
+ pp f "@[<0>@[<hv2>try@ %a@]@ @[<0>with%a@]@]"
+ (* "try@;@[<2>%a@]@\nwith@\n%a"*)
+ self#reset#expression e self#case_list l
+ | Pexp_let (rf, l, e) ->
+ (* pp f "@[<2>let %a%a in@;<1 -2>%a@]"
+ (*no identation here, a new line*) *)
+ (* self#rec_flag rf *)
+ pp f "@[<2>%a in@;<1 -2>%a@]"
+ self#reset#bindings (rf,l)
+ self#expression e
+ | Pexp_apply (e, l) ->
+ (if not (self#sugar_expr f x) then
+ match view_fixity_of_exp e with
+ | `Infix s ->
+ (match l with
+ | [ arg1; arg2 ] ->
+ pp f "@[<2>%a@;%s@;%a@]"
+ (* FIXME associativity lable_x_expression_parm*)
+ self#reset#label_x_expression_param arg1 s
+ self#label_x_expression_param arg2
+ | _ ->
+ pp f "@[<2>%a %a@]" self#simple_expr e
+ (self#list self#label_x_expression_param) l)
+ | `Prefix s ->
+ let s =
+ if List.mem s ["~+";"~-";"~+.";"~-."]
+ then String.sub s 1 (String.length s -1)
+ else s
+ in
+ (match l with
+ |[v] -> pp f "@[<2>%s@;%a@]" s self#label_x_expression_param v
+ | _ -> pp f "@[<2>%s@;%a@]" s
+ (self#list self#label_x_expression_param) l
+ (*FIXME assert false*)
+ )
+ | _ ->
+ pp f "@[<hov2>%a@]" begin fun f (e,l) ->
+ pp f "%a@ %a" self#expression2 e
+ (self#list self#reset#label_x_expression_param) l
+ (*reset here only because [function,match,try,sequence] are
+ lower priority*)
+ end (e,l))
+
+ | Pexp_construct (li, Some eo)
+ when not (is_simple_construct (view_expr x))-> (* Not efficient FIXME*)
+ (match view_expr x with
+ | `cons ls -> self#list self#simple_expr f ls ~sep:"@;::@;"
+ | `normal ->
+ pp f "@[<2>%a@;%a@]" self#longident_loc li
+ self#simple_expr eo
+ | _ -> assert false)
+ | Pexp_setfield (e1, li, e2) ->
+ pp f "@[<2>%a.%a@ <-@ %a@]" self#simple_expr e1 self#longident_loc li
+ self#expression e2;
+ | Pexp_ifthenelse (e1, e2, eo) ->
+ (* @;@[<2>else@ %a@]@] *)
+ let fmt:(_,_,_)format ="@[<hv0>@[<2>if@ %a@]@;@[<2>then@ %a@]%a@]" in
+ pp f fmt self#under_ifthenelse#expression e1
+ self#under_ifthenelse#expression e2
+ (fun f eo -> match eo with
+ | Some x -> pp f "@;@[<2>else@;%a@]" self#under_semi#expression x
+ | None -> () (* pp f "()" *)) eo
+ | Pexp_sequence _ ->
+ let rec sequence_helper acc = function
+ | {pexp_desc=Pexp_sequence(e1,e2);_} ->
+ sequence_helper (e1::acc) e2
+ | v -> List.rev (v::acc) in
+ let lst = sequence_helper [] x in
+ pp f "@[<hv>%a@]"
+ (self#list self#under_semi#expression ~sep:";@;") lst
+ | Pexp_new (li) ->
+ pp f "@[<hov2>new@ %a@]" self#longident_loc li;
+ | Pexp_setinstvar (s, e) ->
+ pp f "@[<hov2>%s@ <-@ %a@]" s.txt self#expression e
+ | Pexp_override l -> (* FIXME *)
+ let string_x_expression f (s, e) =
+ pp f "@[<hov2>%s@ =@ %a@]" s.txt self#expression e in
+ pp f "@[<hov2>{<%a>}@]"
+ (self#list string_x_expression ~sep:";" ) l;
+ | Pexp_letmodule (s, me, e) ->
+ pp f "@[<hov2>let@ module@ %s@ =@ %a@ in@ %a@]" s.txt
+ self#reset#module_expr me self#expression e
+ | Pexp_assert e ->
+ pp f "@[<hov2>assert@ %a@]" self#simple_expr e
+ | Pexp_lazy (e) ->
+ pp f "@[<hov2>lazy@ %a@]" self#simple_expr e
+ (* Pexp_poly: impossible but we should print it anyway, rather
+ than assert false *)
+ | Pexp_poly (e, None) ->
+ pp f "@[<hov2>!poly!@ %a@]" self#simple_expr e
+ | Pexp_poly (e, Some ct) ->
+ pp f "@[<hov2>(!poly!@ %a@ : %a)@]" self#simple_expr e self#core_type ct
+ | Pexp_open (ovf, lid, e) ->
+ pp f "@[<2>let open%s %a in@;%a@]" (override ovf) self#longident_loc lid
+ self#expression e
+ | Pexp_variant (l,Some eo) ->
+ pp f "@[<2>`%s@;%a@]" l self#simple_expr eo
+ | Pexp_extension e -> self#extension f e
+ | _ -> self#expression1 f x
+ method expression1 f x =
+ if x.pexp_attributes <> [] then self#expression f x
+ else match x.pexp_desc with
+ | Pexp_object cs -> pp f "%a" self#class_structure cs
+ | _ -> self#expression2 f x
+ (* used in [Pexp_apply] *)
+ method expression2 f x =
+ if x.pexp_attributes <> [] then self#expression f x
+ else match x.pexp_desc with
+ | Pexp_field (e, li) ->
+ pp f "@[<hov2>%a.%a@]" self#simple_expr e self#longident_loc li
+ | Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" self#simple_expr e s
+
+ | _ -> self#simple_expr f x
+ method simple_expr f x =
+ if x.pexp_attributes <> [] then self#expression f x
+ else match x.pexp_desc with
+ | Pexp_construct _ when is_simple_construct (view_expr x) ->
+ (match view_expr x with
+ | `nil -> pp f "[]"
+ | `tuple -> pp f "()"
+ | `list xs ->
+ pp f "@[<hv0>[%a]@]"
+ (self#list self#under_semi#expression ~sep:";@;") xs
+ | `simple x -> self#longident f x
+ | _ -> assert false)
+ | Pexp_ident li ->
+ self#longident_loc f li
+ (* (match view_fixity_of_exp x with *)
+ (* |`Normal -> self#longident_loc f li *)
+ (* | `Prefix _ | `Infix _ -> pp f "( %a )" self#longident_loc li) *)
+ | Pexp_constant c -> self#constant f c;
+ | Pexp_pack me ->
+ pp f "(module@;%a)" self#module_expr me
+ | Pexp_newtype (lid, e) ->
+ pp f "fun@;(type@;%s)@;->@;%a" lid self#expression e
+ | Pexp_tuple l ->
+ pp f "@[<hov2>(%a)@]" (self#list self#simple_expr ~sep:",@;") l
+ | Pexp_constraint (e, ct) ->
+ pp f "(%a : %a)" self#expression e self#core_type ct
+ | Pexp_coerce (e, cto1, ct) ->
+ pp f "(%a%a :> %a)" self#expression e
+ (self#option self#core_type ~first:" : " ~last:" ")
+ cto1 (* no sep hint*)
+ self#core_type ct
+ | Pexp_variant (l, None) -> pp f "`%s" l
+ | Pexp_record (l, eo) ->
+ let longident_x_expression f ( li, e) =
+ match e.pexp_desc with
+ | Pexp_ident {txt;_} when li.txt = txt ->
+ pp f "@[<hov2>%a@]" self#longident_loc li
+ | _ ->
+ pp f "@[<hov2>%a@;=@;%a@]" self#longident_loc li self#simple_expr
+ e
+ in
+ pp f "@[<hv0>@[<hv2>{@;%a%a@]@;}@]"(* "@[<hov2>{%a%a}@]" *)
+ (self#option ~last:" with@;" self#simple_expr) eo
+ (self#list longident_x_expression ~sep:";@;") l
+ | Pexp_array (l) ->
+ pp f "@[<0>@[<2>[|%a|]@]@]"
+ (self#list self#under_semi#simple_expr ~sep:";") l
+ | Pexp_while (e1, e2) ->
+ let fmt:(_,_,_)format = "@[<2>while@;%a@;do@;%a@;done@]" in
+ pp f fmt self#expression e1 self#expression e2
+ | Pexp_for (s, e1, e2, df, e3) ->
+ let fmt:(_,_,_)format =
+ "@[<hv0>@[<hv2>@[<2>for %a =@;%a@;%a%a@;do@]@;%a@]@;done@]" in
+ pp f fmt self#pattern s self#expression e1 self#direction_flag df
+ self#expression e2 self#expression e3
+ | _ -> self#paren true self#expression f x
+
+ method attributes f l =
+ List.iter (self # attribute f) l
+
+ method item_attributes f l =
+ List.iter (self # item_attribute f) l
+
+ method attribute f (s, e) =
+ pp f "@[<2>[@@%s@ %a]@]" s.txt self#payload e
+
+ method item_attribute f (s, e) =
+ pp f "@[<2>[@@@@%s@ %a]@]" s.txt self#payload e
+
+ method floating_attribute f (s, e) =
+ pp f "@[<2>[@@@@@@%s@ %a]@]" s.txt self#payload e
+
+ method value_description f x =
+ (* note: value_description has an attribute field,
+ but they're already printed by the callers this method *)
+ pp f "@[<hov2>%a%a@]" self#core_type x.pval_type
+ (fun f x ->
+ if x.pval_prim<>[] then begin
+ pp f "@ =@ %a"
+ (self#list self#constant_string)
+ x.pval_prim ;
+ end) x
+
+ method extension f (s, e) =
+ pp f "@[<2>[%%%s@ %a]@]" s.txt self#payload e
+
+ method item_extension f (s, e) =
+ pp f "@[<2>[%%%%%s@ %a]@]" s.txt self#payload e
+
+ method exception_declaration f ext =
+ pp f "@[<hov2>exception@ %a@]" self#extension_constructor ext
+
+ method class_signature f { pcsig_self = ct; pcsig_fields = l ;_} =
+ let class_type_field f x =
+ match x.pctf_desc with
+ | Pctf_inherit (ct) ->
+ pp f "@[<2>inherit@ %a@]%a" self#class_type ct
+ self#item_attributes x.pctf_attributes
+ | Pctf_val (s, mf, vf, ct) ->
+ pp f "@[<2>val @ %a%a%s@ :@ %a@]%a"
+ self#mutable_flag mf self#virtual_flag vf s self#core_type ct
+ self#item_attributes x.pctf_attributes
+ | Pctf_method (s, pf, vf, ct) ->
+ pp f "@[<2>method %a %a%s :@;%a@]%a"
+ self#private_flag pf self#virtual_flag vf s self#core_type ct
+ self#item_attributes x.pctf_attributes
+ | Pctf_constraint (ct1, ct2) ->
+ pp f "@[<2>constraint@ %a@ =@ %a@]%a"
+ self#core_type ct1 self#core_type ct2
+ self#item_attributes x.pctf_attributes
+ | Pctf_attribute a -> self#floating_attribute f a
+ | Pctf_extension e ->
+ self#item_extension f e;
+ self#item_attributes f x.pctf_attributes
+ in
+ pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]"
+ (fun f ct -> match ct.ptyp_desc with
+ | Ptyp_any -> ()
+ | _ -> pp f " (%a)" self#core_type ct) ct
+ (self#list class_type_field ~sep:"@;") l ;
+
+ (* call [class_signature] called by [class_signature] *)
+ method class_type f x =
+ match x.pcty_desc with
+ | Pcty_signature cs ->
+ self#class_signature f cs;
+ self#attributes f x.pcty_attributes
+ | Pcty_constr (li, l) ->
+ pp f "%a%a%a"
+ (fun f l -> match l with
+ | [] -> ()
+ | _ -> pp f "[%a]@ " (self#list self#core_type ~sep:"," ) l) l
+ self#longident_loc li
+ self#attributes x.pcty_attributes
+ | Pcty_arrow (l, co, cl) ->
+ pp f "@[<2>%a@;->@;%a@]" (* FIXME remove parens later *)
+ self#type_with_label (l,co)
+ self#class_type cl
+ | Pcty_extension e ->
+ self#extension f e;
+ self#attributes f x.pcty_attributes
+
+ (* [class type a = object end] *)
+ method class_type_declaration_list f l =
+ let class_type_declaration kwd f ({pci_params=ls;pci_name={txt;_};_} as x) =
+ pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd
+ self#virtual_flag x.pci_virt
+ self#class_params_def ls txt
+ self#class_type x.pci_expr
+ self#item_attributes x.pci_attributes
+ in
+ match l with
+ | [] -> ()
+ | [x] -> class_type_declaration "class type" f x
+ | x :: xs ->
+ pp f "@[<v>%a@,%a@]"
+ (class_type_declaration "class type") x
+ (self#list ~sep:"@," (class_type_declaration "and")) xs
+
+ method class_field f x =
+ match x.pcf_desc with
+ | Pcf_inherit (ovf, ce, so) ->
+ pp f "@[<2>inherit@ %s@ %a%a@]%a" (override ovf)
+ self#class_expr ce
+ (fun f so -> match so with
+ | None -> ();
+ | Some (s) -> pp f "@ as %s" s ) so
+ self#item_attributes x.pcf_attributes
+ | Pcf_val (s, mf, Cfk_concrete (ovf, e)) ->
+ pp f "@[<2>val%s %a%s =@;%a@]%a" (override ovf)
+ self#mutable_flag mf s.txt
+ self#expression e
+ self#item_attributes x.pcf_attributes
+ | Pcf_method (s, pf, Cfk_virtual ct) ->
+ pp f "@[<2>method virtual %a %s :@;%a@]%a"
+ self#private_flag pf s.txt
+ self#core_type ct
+ self#item_attributes x.pcf_attributes
+ | Pcf_val (s, mf, Cfk_virtual ct) ->
+ pp f "@[<2>val virtual %a%s :@ %a@]%a"
+ self#mutable_flag mf s.txt
+ self#core_type ct
+ self#item_attributes x.pcf_attributes
+ | Pcf_method (s, pf, Cfk_concrete (ovf, e)) ->
+ let bind e =
+ self#binding f
+ {pvb_pat=
+ {ppat_desc=Ppat_var s;ppat_loc=Location.none;ppat_attributes=[]};
+ pvb_expr=e;
+ pvb_attributes=[];
+ pvb_loc=Location.none;
+ }
+ in
+ pp f "@[<2>method%s %a%a@]%a"
+ (override ovf)
+ self#private_flag pf
+ (fun f e -> match e.pexp_desc with
+ | Pexp_poly (e, Some ct) ->
+ pp f "%s :@;%a=@;%a"
+ s.txt (self#core_type) ct self#expression e
+ | Pexp_poly (e,None) -> bind e
+ | _ -> bind e) e
+ self#item_attributes x.pcf_attributes
+ | Pcf_constraint (ct1, ct2) ->
+ pp f "@[<2>constraint %a =@;%a@]%a"
+ self#core_type ct1
+ self#core_type ct2
+ self#item_attributes x.pcf_attributes
+ | Pcf_initializer (e) ->
+ pp f "@[<2>initializer@ %a@]%a"
+ self#expression e
+ self#item_attributes x.pcf_attributes
+ | Pcf_attribute a -> self#floating_attribute f a
+ | Pcf_extension e ->
+ self#item_extension f e;
+ self#item_attributes f x.pcf_attributes
+
+ method class_structure f { pcstr_self = p; pcstr_fields = l } =
+ pp f "@[<hv0>@[<hv2>object%a@;%a@]@;end@]"
+ (fun f p -> match p.ppat_desc with
+ | Ppat_any -> ()
+ | Ppat_constraint _ -> pp f " %a" self#pattern p
+ | _ -> pp f " (%a)" self#pattern p) p
+ (self#list self#class_field ) l
+
+ method class_expr f x =
+ if x.pcl_attributes <> [] then begin
+ pp f "((%a)%a)" self#class_expr {x with pcl_attributes=[]}
+ self#attributes x.pcl_attributes
+ end else
+ match x.pcl_desc with
+ | Pcl_structure (cs) -> self#class_structure f cs
+ | Pcl_fun (l, eo, p, e) ->
+ pp f "fun@ %a@ ->@ %a"
+ self#label_exp (l,eo,p)
+ self#class_expr e
+ | Pcl_let (rf, l, ce) ->
+ pp f "%a@ in@ %a"
+ self#bindings (rf,l)
+ self#class_expr ce
+ | Pcl_apply (ce, l) ->
+ pp f "(%a@ %a)"
+ self#class_expr ce
+ (self#list self#label_x_expression_param) l
+ | Pcl_constr (li, l) ->
+ pp f "%a%a"
+ (fun f l-> if l <>[] then
+ pp f "[%a]@ "
+ (self#list self#core_type ~sep:"," ) l ) l
+ self#longident_loc li
+ | Pcl_constraint (ce, ct) ->
+ pp f "(%a@ :@ %a)"
+ self#class_expr ce
+ self#class_type ct
+ | Pcl_extension e -> self#extension f e
+
+ method module_type f x =
+ if x.pmty_attributes <> [] then begin
+ pp f "((%a)%a)" self#module_type {x with pmty_attributes=[]}
+ self#attributes x.pmty_attributes
+ end else
+ match x.pmty_desc with
+ | Pmty_ident li ->
+ pp f "%a" self#longident_loc li;
+ | Pmty_alias li ->
+ pp f "(module %a)" self#longident_loc li;
+ | Pmty_signature (s) ->
+ pp f "@[<hv0>@[<hv2>sig@ %a@]@ end@]" (* "@[<hov>sig@ %a@ end@]" *)
+ (self#list self#signature_item ) s (* FIXME wrong indentation*)
+ | Pmty_functor (_, None, mt2) ->
+ pp f "@[<hov2>functor () ->@ %a@]" self#module_type mt2
+ | Pmty_functor (s, Some mt1, mt2) ->
+ pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" s.txt
+ self#module_type mt1 self#module_type mt2
+ | Pmty_with (mt, l) ->
+ let with_constraint f = function
+ | Pwith_type (li, ({ptype_params= ls ;_} as td)) ->
+ let ls = List.map fst ls in
+ pp f "type@ %a %a =@ %a"
+ (self#list self#core_type ~sep:"," ~first:"(" ~last:")")
+ ls self#longident_loc li self#type_declaration td
+ | Pwith_module (li, li2) ->
+ pp f "module %a =@ %a" self#longident_loc li self#longident_loc
+ li2;
+ | Pwith_typesubst ({ptype_params=ls;_} as td) ->
+ let ls = List.map fst ls in
+ pp f "type@ %a %s :=@ %a"
+ (self#list self#core_type ~sep:"," ~first:"(" ~last:")")
+ ls td.ptype_name.txt
+ self#type_declaration td
+ | Pwith_modsubst (s, li2) ->
+ pp f "module %s :=@ %a" s.txt self#longident_loc li2 in
+ (match l with
+ | [] -> pp f "@[<hov2>%a@]" self#module_type mt
+ | _ -> pp f "@[<hov2>(%a@ with@ %a)@]"
+ self#module_type mt (self#list with_constraint ~sep:"@ and@ ") l )
+ | Pmty_typeof me ->
+ pp f "@[<hov2>module@ type@ of@ %a@]"
+ self#module_expr me
+ | Pmty_extension e -> self#extension f e
+
+ method signature f x = self#list ~sep:"@\n" self#signature_item f x
+
+ method signature_item f x :unit= begin
+ match x.psig_desc with
+ | Psig_type (rf, l) ->
+ self#type_def_list f (rf, l)
+ | Psig_value vd ->
+ let intro = if vd.pval_prim = [] then "val" else "external" in
+ pp f "@[<2>%s@ %a@ :@ %a@]%a" intro
+ protect_ident vd.pval_name.txt
+ self#value_description vd
+ self#item_attributes vd.pval_attributes
+ | Psig_typext te ->
+ self#type_extension f te
+ | Psig_exception ed ->
+ self#exception_declaration f ed
+ | Psig_class l ->
+ let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) =
+ pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd
+ self#virtual_flag x.pci_virt
+ self#class_params_def ls txt
+ self#class_type x.pci_expr
+ self#item_attributes x.pci_attributes
+ in begin
+ match l with
+ | [] -> ()
+ | [x] -> class_description "class" f x
+ | x :: xs ->
+ pp f "@[<v>%a@,%a@]"
+ (class_description "class") x
+ (self#list ~sep:"@," (class_description "and")) xs
+ end
+ | Psig_module ({pmd_type={pmty_desc=Pmty_alias alias};_} as pmd) ->
+ pp f "@[<hov>module@ %s@ =@ %a@]%a" pmd.pmd_name.txt
+ self#longident_loc alias
+ self#item_attributes pmd.pmd_attributes
+ | Psig_module pmd ->
+ pp f "@[<hov>module@ %s@ :@ %a@]%a"
+ pmd.pmd_name.txt
+ self#module_type pmd.pmd_type
+ self#item_attributes pmd.pmd_attributes
+ | Psig_open od ->
+ pp f "@[<hov2>open%s@ %a@]%a"
+ (override od.popen_override)
+ self#longident_loc od.popen_lid
+ self#item_attributes od.popen_attributes
+ | Psig_include incl ->
+ pp f "@[<hov2>include@ %a@]%a"
+ self#module_type incl.pincl_mod
+ self#item_attributes incl.pincl_attributes
+ | Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} ->
+ pp f "@[<hov2>module@ type@ %s%a@]%a"
+ s.txt
+ (fun f md -> match md with
+ | None -> ()
+ | Some mt ->
+ pp_print_space f () ;
+ pp f "@ =@ %a" self#module_type mt
+ ) md
+ self#item_attributes attrs
+ | Psig_class_type (l) ->
+ self#class_type_declaration_list f l ;
+ | Psig_recmodule decls ->
+ let rec string_x_module_type_list f ?(first=true) l =
+ match l with
+ | [] -> () ;
+ | pmd :: tl ->
+ if not first then
+ pp f "@ @[<hov2>and@ %s:@ %a@]%a" pmd.pmd_name.txt
+ self#module_type pmd.pmd_type
+ self#item_attributes pmd.pmd_attributes
+ else
+ pp f "@[<hov2>module@ rec@ %s:@ %a@]%a" pmd.pmd_name.txt
+ self#module_type pmd.pmd_type
+ self#item_attributes pmd.pmd_attributes;
+ string_x_module_type_list f ~first:false tl
+ in
+ string_x_module_type_list f decls
+ | Psig_attribute a -> self#floating_attribute f a
+ | Psig_extension(e, a) ->
+ self#item_extension f e;
+ self#item_attributes f a
+ end
+ method module_expr f x =
+ if x.pmod_attributes <> [] then begin
+ pp f "((%a)%a)" self#module_expr {x with pmod_attributes=[]}
+ self#attributes x.pmod_attributes
+ end else
+ match x.pmod_desc with
+ | Pmod_structure (s) ->
+ pp f "@[<hv2>struct@;@[<0>%a@]@;<1 -2>end@]"
+ (self#list self#structure_item ~sep:"@\n") s;
+ | Pmod_constraint (me, mt) ->
+ pp f "@[<hov2>(%a@ :@ %a)@]"
+ self#module_expr me
+ self#module_type mt
+ | Pmod_ident (li) ->
+ pp f "%a" self#longident_loc li;
+ | Pmod_functor (_, None, me) ->
+ pp f "functor ()@;->@;%a" self#module_expr me
+ | Pmod_functor (s, Some mt, me) ->
+ pp f "functor@ (%s@ :@ %a)@;->@;%a"
+ s.txt self#module_type mt self#module_expr me
+ | Pmod_apply (me1, me2) ->
+ pp f "%a(%a)" self#module_expr me1 self#module_expr me2
+ | Pmod_unpack e ->
+ pp f "(val@ %a)" self#expression e
+ | Pmod_extension e -> self#extension f e
+
+ method structure f x = self#list ~sep:"@\n" self#structure_item f x
+
+ method payload f = function
+ | PStr [{pstr_desc = Pstr_eval (e, attrs)}] ->
+ pp f "@[<2>%a@]%a"
+ self#expression e
+ self#item_attributes attrs
+ | PStr x -> self#structure f x
+ | PTyp x -> pp f ":"; self#core_type f x
+ | PPat (x, None) -> pp f "?"; self#pattern f x
+ | PPat (x, Some e) ->
+ pp f "?"; self#pattern f x;
+ pp f " when "; self#expression f e
+
+ (* transform [f = fun g h -> ..] to [f g h = ... ] could be improved *)
+ method binding f {pvb_pat=p; pvb_expr=x; _} =
+ (* .pvb_attributes have already been printed by the caller, #bindings *)
+ let rec pp_print_pexp_function f x =
+ if x.pexp_attributes <> [] then pp f "=@;%a" self#expression x
+ else match x.pexp_desc with
+ | Pexp_fun (label, eo, p, e) ->
+ if label=Nolabel then
+ pp f "%a@ %a" self#simple_pattern p pp_print_pexp_function e
+ else
+ pp f "%a@ %a" self#label_exp (label,eo,p) pp_print_pexp_function e
+ | Pexp_newtype (str,e) ->
+ pp f "(type@ %s)@ %a" str pp_print_pexp_function e
+ | _ -> pp f "=@;%a" self#expression x in
+ if x.pexp_attributes <> [] then
+ pp f "%a@;=@;%a" self#pattern p self#expression x
+ else match (x.pexp_desc,p.ppat_desc) with
+ | ( _ , Ppat_constraint( p ,ty)) -> (* special case for the first*)
+ (match ty.ptyp_desc with
+ | Ptyp_poly _ ->
+ pp f "%a@;:@;%a=@;%a" self#simple_pattern p
+ self#core_type ty self#expression x
+ | _ ->
+ pp f "(%a@;:%a)=@;%a" self#simple_pattern p
+ self#core_type ty self#expression x)
+ | Pexp_constraint (e,t1),Ppat_var {txt;_} ->
+ pp f "%s:@ %a@;=@;%a" txt self#core_type t1 self#expression e
+ | (_, Ppat_var _) ->
+ pp f "%a@ %a" self#simple_pattern p pp_print_pexp_function x
+ | _ ->
+ pp f "%a@;=@;%a" self#pattern p self#expression x
+ (* [in] is not printed *)
+ method bindings f (rf,l) =
+ let binding kwd rf f x =
+ pp f "@[<2>%s %a%a@]%a" kwd self#rec_flag rf
+ self#binding x self#item_attributes x.pvb_attributes
+ in
+ begin match l with
+ | [] -> ()
+ | [x] -> binding "let" rf f x
+ | x::xs ->
+ pp f "@[<v>%a@,%a@]"
+ (binding "let" rf) x
+ (self#list ~sep:"@," (binding "and" Nonrecursive)) xs
+ end
+
+ method structure_item f x = begin
+ match x.pstr_desc with
+ | Pstr_eval (e, attrs) ->
+ pp f "@[<hov2>let@ _ =@ %a@]%a"
+ self#expression e
+ self#item_attributes attrs
+ | Pstr_type (_, []) -> assert false
+ | Pstr_type (rf, l) -> self#type_def_list f (rf, l)
+ | Pstr_value (rf, l) ->
+ (* pp f "@[<hov2>let %a%a@]" self#rec_flag rf self#bindings l *)
+ pp f "@[<2>%a@]" self#bindings (rf,l)
+ | Pstr_typext te -> self#type_extension f te
+ | Pstr_exception ed -> self#exception_declaration f ed
+ | Pstr_module x ->
+ let rec module_helper me =
+ match me.pmod_desc with
+ | Pmod_functor(s,mt,me') when me.pmod_attributes = [] ->
+ if mt = None then pp f "()"
+ else Misc.may (pp f "(%s:%a)" s.txt self#module_type) mt;
+ module_helper me'
+ | _ -> me
+ in
+ pp f "@[<hov2>module %s%a@]%a"
+ x.pmb_name.txt
+ (fun f me ->
+ let me = module_helper me in
+ (match me.pmod_desc with
+ | Pmod_constraint
+ (me',
+ ({pmty_desc=(Pmty_ident (_)
+ | Pmty_signature (_));_} as mt))
+ when me.pmod_attributes = [] ->
+ pp f " :@;%a@;=@;%a@;" self#module_type mt self#module_expr me'
+ | _ ->
+ pp f " =@ %a" self#module_expr me
+ )) x.pmb_expr
+ self#item_attributes x.pmb_attributes
+ | Pstr_open od ->
+ pp f "@[<2>open%s@;%a@]%a"
+ (override od.popen_override)
+ self#longident_loc od.popen_lid
+ self#item_attributes od.popen_attributes
+ | Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} ->
+ pp f "@[<hov2>module@ type@ %s%a@]%a"
+ s.txt
+ (fun f md -> match md with
+ | None -> ()
+ | Some mt ->
+ pp_print_space f () ;
+ pp f "@ =@ %a" self#module_type mt
+ ) md
+ self#item_attributes attrs
+ | Pstr_class l ->
+ let extract_class_args cl =
+ let rec loop acc cl =
+ match cl.pcl_desc with
+ | Pcl_fun (l, eo, p, cl') when cl.pcl_attributes = [] ->
+ loop ((l,eo,p) :: acc) cl'
+ | _ -> List.rev acc, cl
+ in
+ let args, cl = loop [] cl in
+ let constr, cl =
+ match cl.pcl_desc with
+ | Pcl_constraint (cl', ct) when cl.pcl_attributes = [] ->
+ Some ct, cl'
+ | _ -> None, cl
+ in
+ args, constr, cl
+ in
+ let class_constraint f ct = pp f ": @[%a@] " self#class_type ct in
+ let class_declaration kwd f
+ ({pci_params=ls; pci_name={txt;_}; _} as x) =
+ let args, constr, cl = extract_class_args x.pci_expr in
+ pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd
+ self#virtual_flag x.pci_virt
+ self#class_params_def ls txt
+ (self#list self#label_exp) args
+ (self#option class_constraint) constr
+ self#class_expr cl
+ self#item_attributes x.pci_attributes
+ in begin
+ match l with
+ | [] -> ()
+ | [x] -> class_declaration "class" f x
+ | x :: xs ->
+ pp f "@[<v>%a@,%a@]"
+ (class_declaration "class") x
+ (self#list ~sep:"@," (class_declaration "and")) xs
+ end
+ | Pstr_class_type (l) ->
+ self#class_type_declaration_list f l ;
+ | Pstr_primitive vd ->
+ pp f "@[<hov2>external@ %a@ :@ %a@]%a"
+ protect_ident vd.pval_name.txt
+ self#value_description vd
+ self#item_attributes vd.pval_attributes
+ | Pstr_include incl ->
+ pp f "@[<hov2>include@ %a@]%a"
+ self#module_expr incl.pincl_mod
+ self#item_attributes incl.pincl_attributes
+ | Pstr_recmodule decls -> (* 3.07 *)
+ let aux f = function
+ | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) ->
+ pp f "@[<hov2>@ and@ %s:%a@ =@ %a@]%a" pmb.pmb_name.txt
+ self#module_type typ
+ self#module_expr expr
+ self#item_attributes pmb.pmb_attributes
+ | _ -> assert false
+ in
+ begin match decls with
+ | ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 ->
+ pp f "@[<hv>@[<hov2>module@ rec@ %s:%a@ =@ %a@]%a@ %a@]"
+ pmb.pmb_name.txt
+ self#module_type typ
+ self#module_expr expr
+ self#item_attributes pmb.pmb_attributes
+ (fun f l2 -> List.iter (aux f) l2) l2
+ | _ -> assert false
+ end
+ | Pstr_attribute a -> self#floating_attribute f a
+ | Pstr_extension(e, a) ->
+ self#item_extension f e;
+ self#item_attributes f a
+ end
+ method type_param f (ct, a) =
+ pp f "%s%a" (type_variance a) self#core_type ct
+ method type_params f = function
+ [] -> ()
+ | l -> pp f "%a " (self#list self#type_param ~first:"(" ~last:")" ~sep:",") l
+ method type_def_list f (rf, l) =
+ let type_decl kwd rf f x =
+ let eq =
+ if (x.ptype_kind = Ptype_abstract)
+ && (x.ptype_manifest = None) then ""
+ else " ="
+ in
+ pp f "@[<2>%s %a%a%s%s%a@]%a" kwd
+ self#nonrec_flag rf
+ self#type_params x.ptype_params
+ x.ptype_name.txt eq
+ self#type_declaration x
+ self#item_attributes x.ptype_attributes
+ in
+ match l with
+ | [] -> assert false
+ | [x] -> type_decl "type" rf f x
+ | x :: xs -> pp f "@[<v>%a@,%a@]"
+ (type_decl "type" rf) x
+ (self#list ~sep:"@," (type_decl "and" Recursive)) xs
+
+ method record_declaration f lbls =
+ let type_record_field f pld =
+ pp f "@[<2>%a%s:@;%a@;%a@]"
+ self#mutable_flag pld.pld_mutable
+ pld.pld_name.txt
+ self#core_type pld.pld_type
+ self#attributes pld.pld_attributes
+ in
+ pp f "{@\n%a}"
+ (self#list type_record_field ~sep:";@\n" ) lbls
+
+ method type_declaration f x =
+ (* type_declaration has an attribute field,
+ but it's been printed by the caller of this method *)
+ let priv f =
+ match x.ptype_private with
+ Public -> ()
+ | Private -> pp f "@;private"
+ in
+ let manifest f =
+ match x.ptype_manifest with
+ | None -> ()
+ | Some y -> pp f "@;%a" self#core_type y
+ in
+ let constructor_declaration f pcd =
+ pp f "|@;";
+ self#constructor_declaration f (pcd.pcd_name.txt, pcd.pcd_args,
+ pcd.pcd_res, pcd.pcd_attributes)
+ in
+ let repr f =
+ let intro f =
+ if x.ptype_manifest = None then ()
+ else pp f "@;="
+ in
+ match x.ptype_kind with
+ | Ptype_variant xs ->
+ pp f "%t@\n%a" intro
+ (self#list ~sep:"@\n" constructor_declaration) xs
+ | Ptype_abstract -> ()
+ | Ptype_record l ->
+ pp f "%t@;%a" intro self#record_declaration l
+ | Ptype_open -> pp f "%t@;.." intro
+ in
+ let constraints f =
+ List.iter
+ (fun (ct1,ct2,_) ->
+ pp f "@[<hov2>@ constraint@ %a@ =@ %a@]"
+ self#core_type ct1 self#core_type ct2)
+ x.ptype_cstrs
+ in
+ pp f "%t%t%t%t" priv manifest repr constraints
+
+ method type_extension f x =
+ let extension_constructor f x =
+ pp f "@\n|@;%a" self#extension_constructor x
+ in
+ pp f "@[<2>type %a%a +=%a@]%a"
+ (fun f -> function
+ | [] -> ()
+ | l -> pp f "%a@;" (self#list self#type_param ~first:"("
+ ~last:")" ~sep:",")
+ l)
+ x.ptyext_params
+ self#longident_loc x.ptyext_path
+ (self#list ~sep:"" extension_constructor)
+ x.ptyext_constructors
+ self#item_attributes x.ptyext_attributes
+
+ method constructor_declaration f (name, args, res, attrs) =
+ match res with
+ | None ->
+ pp f "%s%a@;%a" name
+ (fun f -> function
+ | Pcstr_tuple [] -> ()
+ | Pcstr_tuple l ->
+ pp f "@;of@;%a" (self#list self#core_type1 ~sep:"*@;") l
+ | Pcstr_record l -> pp f "@;of@;%a" (self#record_declaration) l
+ ) args
+ self#attributes attrs
+ | Some r ->
+ pp f "%s:@;%a@;%a" name
+ (fun f -> function
+ | Pcstr_tuple [] -> self#core_type1 f r
+ | Pcstr_tuple l -> pp f "%a@;->@;%a"
+ (self#list self#core_type1 ~sep:"*@;") l
+ self#core_type1 r
+ | Pcstr_record l ->
+ pp f "%a@;->@;%a" (self#record_declaration) l self#core_type1 r
+ )
+ args
+ self#attributes attrs
+
+
+ method extension_constructor f x =
+ match x.pext_kind with
+ | Pext_decl(l, r) ->
+ self#constructor_declaration f (x.pext_name.txt, l, r,
+ x.pext_attributes)
+ | Pext_rebind li ->
+ pp f "%s%a@;=@;%a" x.pext_name.txt
+ self#attributes x.pext_attributes
+ self#longident_loc li
+
+ method case_list f l : unit =
+ let aux f {pc_lhs; pc_guard; pc_rhs} =
+ pp f "@;| @[<2>%a%a@;->@;%a@]"
+ self#pattern pc_lhs (self#option self#expression ~first:"@;when@;")
+ pc_guard self#under_pipe#expression pc_rhs
+ in
+ self#list aux f l ~sep:""
+ method label_x_expression_param f (l,e) =
+ let simple_name = match e.pexp_desc with
+ | Pexp_ident {txt=Lident l;_} -> Some l
+ | _ -> None
+ in match l with
+ | Nolabel -> self#expression2 f e ; (* level 2*)
+ | Optional str ->
+ if Some str = simple_name then
+ pp f "?%s" str
+ else
+ pp f "?%s:%a" str self#simple_expr e
+ | Labelled lbl ->
+ if Some lbl = simple_name then
+ pp f "~%s" lbl
+ else
+ pp f "~%s:%a" lbl self#simple_expr e
+
+ method directive_argument f x =
+ (match x with
+ | Pdir_none -> ()
+ | Pdir_string (s) -> pp f "@ %S" s
+ | Pdir_int (i) -> pp f "@ %d" i
+ | Pdir_ident (li) -> pp f "@ %a" self#longident li
+ | Pdir_bool (b) -> pp f "@ %s" (string_of_bool b))
+
+ method toplevel_phrase f x =
+ match x with
+ | Ptop_def (s) ->
+ pp_open_hvbox f 0;
+ self#list self#structure_item f s ;
+ pp_close_box f ();
+ | Ptop_dir (s, da) ->
+ pp f "@[<hov2>#%s@ %a@]" s self#directive_argument da
+end;;
+
+
+let default = new printer ()
+
+
+let toplevel_phrase f x =
+ match x with
+ | Ptop_def (s) ->pp f "@[<hov0>%a@]" (default#list default#structure_item) s
+ (* pp_open_hvbox f 0; *)
+ (* pp_print_list structure_item f s ; *)
+ (* pp_close_box f (); *)
+ | Ptop_dir (s, da) ->
+ pp f "@[<hov2>#%s@ %a@]" s default#directive_argument da
+ (* pp f "@[<hov2>#%s@ %a@]" s directive_argument da *)
+
+let expression f x =
+ pp f "@[%a@]" default#expression x
+
+
+let string_of_expression x =
+ ignore (flush_str_formatter ()) ;
+ let f = str_formatter in
+ default#expression f x ;
+ flush_str_formatter () ;;
+let string_of_structure x =
+ ignore (flush_str_formatter ());
+ let f = str_formatter in
+ default#structure f x;
+ flush_str_formatter ();;
+
+let top_phrase f x =
+ pp_print_newline f () ;
+ toplevel_phrase f x;
+ pp f ";;" ;
+ pp_print_newline f ();;
+
+let core_type=default#core_type
+let pattern=default#pattern
+let signature=default#signature
+let structure=default#structure
diff --git a/parsing/pprintast.mli b/parsing/pprintast.mli
new file mode 100644
index 0000000000..a77fb6c16d
--- /dev/null
+++ b/parsing/pprintast.mli
@@ -0,0 +1,147 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Hongbo Zhang (University of Pennsylvania) *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type space_formatter = (unit, Format.formatter, unit) format
+class printer :
+ unit ->
+ object ('b)
+ val pipe : bool
+ val semi : bool
+ method binding :
+ Format.formatter -> Parsetree.value_binding -> unit
+ method bindings:
+ Format.formatter ->
+ Asttypes.rec_flag * Parsetree.value_binding list ->
+ unit
+ method case_list :
+ Format.formatter -> Parsetree.case list -> unit
+ method class_expr : Format.formatter -> Parsetree.class_expr -> unit
+ method class_field : Format.formatter -> Parsetree.class_field -> unit
+ method class_params_def :
+ Format.formatter -> (Parsetree.core_type * Asttypes.variance) list -> unit
+ method class_signature :
+ Format.formatter -> Parsetree.class_signature -> unit
+ method class_structure :
+ Format.formatter -> Parsetree.class_structure -> unit
+ method class_type : Format.formatter -> Parsetree.class_type -> unit
+ method class_type_declaration_list :
+ Format.formatter -> Parsetree.class_type_declaration list -> unit
+ method constant : Format.formatter -> Asttypes.constant -> unit
+ method constant_string : Format.formatter -> string -> unit
+ method constructor_declaration :
+ Format.formatter -> (string * Parsetree.constructor_arguments
+ * Parsetree.core_type option * Parsetree.attributes)
+ -> unit
+ method core_type : Format.formatter -> Parsetree.core_type -> unit
+ method core_type1 : Format.formatter -> Parsetree.core_type -> unit
+ method direction_flag :
+ Format.formatter -> Asttypes.direction_flag -> unit
+ method directive_argument :
+ Format.formatter -> Parsetree.directive_argument -> unit
+ method exception_declaration :
+ Format.formatter -> Parsetree.extension_constructor -> unit
+ method expression : Format.formatter -> Parsetree.expression -> unit
+ method expression1 : Format.formatter -> Parsetree.expression -> unit
+ method expression2 : Format.formatter -> Parsetree.expression -> unit
+ method extension_constructor :
+ Format.formatter -> Parsetree.extension_constructor -> unit
+ method label_exp :
+ Format.formatter ->
+ Asttypes.arg_label * Parsetree.expression option * Parsetree.pattern ->
+ unit
+ method label_x_expression_param :
+ Format.formatter -> Asttypes.arg_label * Parsetree.expression -> unit
+ method list :
+ ?sep:space_formatter ->
+ ?first:space_formatter ->
+ ?last:space_formatter ->
+ (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a list -> unit
+ method longident : Format.formatter -> Longident.t -> unit
+ method longident_loc :
+ Format.formatter -> Longident.t Asttypes.loc -> unit
+ method module_expr : Format.formatter -> Parsetree.module_expr -> unit
+ method module_type : Format.formatter -> Parsetree.module_type -> unit
+ method mutable_flag : Format.formatter -> Asttypes.mutable_flag -> unit
+ method option :
+ ?first:space_formatter ->
+ ?last:space_formatter ->
+ (Format.formatter -> 'a -> unit) ->
+ Format.formatter -> 'a option -> unit
+ method paren :
+ ?first:space_formatter -> ?last:space_formatter -> bool ->
+ (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit
+ method pattern : Format.formatter -> Parsetree.pattern -> unit
+ method pattern1 : Format.formatter -> Parsetree.pattern -> unit
+ method payload : Format.formatter -> Parsetree.payload -> unit
+ method private_flag : Format.formatter -> Asttypes.private_flag -> unit
+ method rec_flag : Format.formatter -> Asttypes.rec_flag -> unit
+ method nonrec_flag : Format.formatter -> Asttypes.rec_flag -> unit
+ method record_declaration :
+ Format.formatter -> Parsetree.label_declaration list -> unit
+
+ method reset : 'b
+ method reset_semi : 'b
+ method reset_ifthenelse : 'b
+ method reset_pipe : 'b
+
+ method signature :
+ Format.formatter -> Parsetree.signature_item list -> unit
+ method signature_item :
+ Format.formatter -> Parsetree.signature_item -> unit
+ method simple_expr : Format.formatter -> Parsetree.expression -> unit
+ method simple_pattern : Format.formatter -> Parsetree.pattern -> unit
+ method string_quot : Format.formatter -> Asttypes.label -> unit
+ method structure :
+ Format.formatter -> Parsetree.structure_item list -> unit
+ method structure_item :
+ Format.formatter -> Parsetree.structure_item -> unit
+ method sugar_expr : Format.formatter -> Parsetree.expression -> bool
+ method toplevel_phrase :
+ Format.formatter -> Parsetree.toplevel_phrase -> unit
+ method type_declaration :
+ Format.formatter -> Parsetree.type_declaration -> unit
+ method type_def_list :
+ Format.formatter -> Asttypes.rec_flag * Parsetree.type_declaration list
+ -> unit
+ method type_extension :
+ Format.formatter -> Parsetree.type_extension -> unit
+ method type_param :
+ Format.formatter -> Parsetree.core_type * Asttypes.variance -> unit
+ method type_params :
+ Format.formatter -> (Parsetree.core_type * Asttypes.variance) list -> unit
+ method type_with_label :
+ Format.formatter -> Asttypes.arg_label * Parsetree.core_type -> unit
+ method tyvar : Format.formatter -> string -> unit
+ method under_pipe : 'b
+ method under_semi : 'b
+ method under_ifthenelse : 'b
+ method value_description :
+ Format.formatter -> Parsetree.value_description -> unit
+ method virtual_flag : Format.formatter -> Asttypes.virtual_flag -> unit
+ method attribute : Format.formatter -> Parsetree.attribute -> unit
+ method item_attribute : Format.formatter -> Parsetree.attribute -> unit
+ method floating_attribute : Format.formatter -> Parsetree.attribute -> unit
+ method attributes : Format.formatter -> Parsetree.attributes -> unit
+ method item_attributes : Format.formatter -> Parsetree.attributes -> unit
+ method extension : Format.formatter -> Parsetree.extension -> unit
+ method item_extension : Format.formatter -> Parsetree.extension -> unit
+ end
+val default : printer
+val toplevel_phrase : Format.formatter -> Parsetree.toplevel_phrase -> unit
+val expression : Format.formatter -> Parsetree.expression -> unit
+val string_of_expression : Parsetree.expression -> string
+val top_phrase: Format.formatter -> Parsetree.toplevel_phrase -> unit
+val core_type: Format.formatter -> Parsetree.core_type -> unit
+val pattern: Format.formatter -> Parsetree.pattern -> unit
+val signature: Format.formatter -> Parsetree.signature -> unit
+val structure: Format.formatter -> Parsetree.structure -> unit
+val string_of_structure: Parsetree.structure -> string
diff --git a/parsing/printast.ml b/parsing/printast.ml
new file mode 100644
index 0000000000..a0bff6e9ad
--- /dev/null
+++ b/parsing/printast.ml
@@ -0,0 +1,899 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Asttypes;;
+open Format;;
+open Lexing;;
+open Location;;
+open Parsetree;;
+
+let fmt_position with_name f l =
+ let fname = if with_name then l.pos_fname else "" in
+ if l.pos_lnum = -1
+ then fprintf f "%s[%d]" fname l.pos_cnum
+ else fprintf f "%s[%d,%d+%d]" fname l.pos_lnum l.pos_bol
+ (l.pos_cnum - l.pos_bol)
+;;
+
+let fmt_location f loc =
+ let p_2nd_name = loc.loc_start.pos_fname <> loc.loc_end.pos_fname in
+ fprintf f "(%a..%a)" (fmt_position true) loc.loc_start
+ (fmt_position p_2nd_name) loc.loc_end;
+ if loc.loc_ghost then fprintf f " ghost";
+;;
+
+let rec fmt_longident_aux f x =
+ match x with
+ | Longident.Lident (s) -> fprintf f "%s" s;
+ | Longident.Ldot (y, s) -> fprintf f "%a.%s" fmt_longident_aux y s;
+ | Longident.Lapply (y, z) ->
+ fprintf f "%a(%a)" fmt_longident_aux y fmt_longident_aux z;
+;;
+
+let fmt_longident f x = fprintf f "\"%a\"" fmt_longident_aux x;;
+
+let fmt_longident_loc f x =
+ fprintf f "\"%a\" %a" fmt_longident_aux x.txt fmt_location x.loc;
+;;
+
+let fmt_string_loc f x =
+ fprintf f "\"%s\" %a" x.txt fmt_location x.loc;
+;;
+
+let fmt_constant f x =
+ match x with
+ | Const_int (i) -> fprintf f "Const_int %d" i;
+ | Const_char (c) -> fprintf f "Const_char %02x" (Char.code c);
+ | Const_string (s, None) -> fprintf f "Const_string(%S,None)" s;
+ | Const_string (s, Some delim) ->
+ fprintf f "Const_string (%S,Some %S)" s delim;
+ | Const_float (s) -> fprintf f "Const_float %s" s;
+ | Const_int32 (i) -> fprintf f "Const_int32 %ld" i;
+ | Const_int64 (i) -> fprintf f "Const_int64 %Ld" i;
+ | Const_nativeint (i) -> fprintf f "Const_nativeint %nd" i;
+;;
+
+let fmt_mutable_flag f x =
+ match x with
+ | Immutable -> fprintf f "Immutable";
+ | Mutable -> fprintf f "Mutable";
+;;
+
+let fmt_virtual_flag f x =
+ match x with
+ | Virtual -> fprintf f "Virtual";
+ | Concrete -> fprintf f "Concrete";
+;;
+
+let fmt_override_flag f x =
+ match x with
+ | Override -> fprintf f "Override";
+ | Fresh -> fprintf f "Fresh";
+;;
+
+let fmt_closed_flag f x =
+ match x with
+ | Closed -> fprintf f "Closed"
+ | Open -> fprintf f "Open"
+
+let fmt_rec_flag f x =
+ match x with
+ | Nonrecursive -> fprintf f "Nonrec";
+ | Recursive -> fprintf f "Rec";
+;;
+
+let fmt_direction_flag f x =
+ match x with
+ | Upto -> fprintf f "Up";
+ | Downto -> fprintf f "Down";
+;;
+
+let fmt_private_flag f x =
+ match x with
+ | Public -> fprintf f "Public";
+ | Private -> fprintf f "Private";
+;;
+
+let line i f s (*...*) =
+ fprintf f "%s" (String.make ((2*i) mod 72) ' ');
+ fprintf f s (*...*)
+;;
+
+let list i f ppf l =
+ match l with
+ | [] -> line i ppf "[]\n";
+ | _ :: _ ->
+ line i ppf "[\n";
+ List.iter (f (i+1) ppf) l;
+ line i ppf "]\n";
+;;
+
+let option i f ppf x =
+ match x with
+ | None -> line i ppf "None\n";
+ | Some x ->
+ line i ppf "Some\n";
+ f (i+1) ppf x;
+;;
+
+let longident_loc i ppf li = line i ppf "%a\n" fmt_longident_loc li;;
+let string i ppf s = line i ppf "\"%s\"\n" s;;
+let string_loc i ppf s = line i ppf "%a\n" fmt_string_loc s;;
+let bool i ppf x = line i ppf "%s\n" (string_of_bool x);;
+let label i ppf x = line i ppf "label=\"%s\"\n" x;;
+let arg_label i ppf = function
+ | Nolabel -> line i ppf "Nolabel\n"
+ | Optional s -> line i ppf "Optional \"%s\"\n" s
+ | Labelled s -> line i ppf "Labelled \"%s\"\n" s
+;;
+
+let rec core_type i ppf x =
+ line i ppf "core_type %a\n" fmt_location x.ptyp_loc;
+ attributes i ppf x.ptyp_attributes;
+ let i = i+1 in
+ match x.ptyp_desc with
+ | Ptyp_any -> line i ppf "Ptyp_any\n";
+ | Ptyp_var (s) -> line i ppf "Ptyp_var %s\n" s;
+ | Ptyp_arrow (l, ct1, ct2) ->
+ line i ppf "Ptyp_arrow\n";
+ arg_label i ppf l;
+ core_type i ppf ct1;
+ core_type i ppf ct2;
+ | Ptyp_tuple l ->
+ line i ppf "Ptyp_tuple\n";
+ list i core_type ppf l;
+ | Ptyp_constr (li, l) ->
+ line i ppf "Ptyp_constr %a\n" fmt_longident_loc li;
+ list i core_type ppf l;
+ | Ptyp_variant (l, closed, low) ->
+ line i ppf "Ptyp_variant closed=%a\n" fmt_closed_flag closed;
+ list i label_x_bool_x_core_type_list ppf l;
+ option i (fun i -> list i string) ppf low
+ | Ptyp_object (l, c) ->
+ line i ppf "Ptyp_object %a\n" fmt_closed_flag c;
+ let i = i + 1 in
+ List.iter
+ (fun (s, attrs, t) ->
+ line i ppf "method %s\n" s;
+ attributes i ppf attrs;
+ core_type (i + 1) ppf t
+ )
+ l
+ | Ptyp_class (li, l) ->
+ line i ppf "Ptyp_class %a\n" fmt_longident_loc li;
+ list i core_type ppf l
+ | Ptyp_alias (ct, s) ->
+ line i ppf "Ptyp_alias \"%s\"\n" s;
+ core_type i ppf ct;
+ | Ptyp_poly (sl, ct) ->
+ line i ppf "Ptyp_poly%a\n"
+ (fun ppf -> List.iter (fun x -> fprintf ppf " '%s" x)) sl;
+ core_type i ppf ct;
+ | Ptyp_package (s, l) ->
+ line i ppf "Ptyp_package %a\n" fmt_longident_loc s;
+ list i package_with ppf l;
+ | Ptyp_extension (s, arg) ->
+ line i ppf "Ptyp_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and package_with i ppf (s, t) =
+ line i ppf "with type %a\n" fmt_longident_loc s;
+ core_type i ppf t
+
+and pattern i ppf x =
+ line i ppf "pattern %a\n" fmt_location x.ppat_loc;
+ attributes i ppf x.ppat_attributes;
+ let i = i+1 in
+ match x.ppat_desc with
+ | Ppat_any -> line i ppf "Ppat_any\n";
+ | Ppat_var (s) -> line i ppf "Ppat_var %a\n" fmt_string_loc s;
+ | Ppat_alias (p, s) ->
+ line i ppf "Ppat_alias %a\n" fmt_string_loc s;
+ pattern i ppf p;
+ | Ppat_constant (c) -> line i ppf "Ppat_constant %a\n" fmt_constant c;
+ | Ppat_interval (c1, c2) ->
+ line i ppf "Ppat_interval %a..%a\n" fmt_constant c1 fmt_constant c2;
+ | Ppat_tuple (l) ->
+ line i ppf "Ppat_tuple\n";
+ list i pattern ppf l;
+ | Ppat_construct (li, po) ->
+ line i ppf "Ppat_construct %a\n" fmt_longident_loc li;
+ option i pattern ppf po;
+ | Ppat_variant (l, po) ->
+ line i ppf "Ppat_variant \"%s\"\n" l;
+ option i pattern ppf po;
+ | Ppat_record (l, c) ->
+ line i ppf "Ppat_record %a\n" fmt_closed_flag c;
+ list i longident_x_pattern ppf l;
+ | Ppat_array (l) ->
+ line i ppf "Ppat_array\n";
+ list i pattern ppf l;
+ | Ppat_or (p1, p2) ->
+ line i ppf "Ppat_or\n";
+ pattern i ppf p1;
+ pattern i ppf p2;
+ | Ppat_lazy p ->
+ line i ppf "Ppat_lazy\n";
+ pattern i ppf p;
+ | Ppat_constraint (p, ct) ->
+ line i ppf "Ppat_constraint\n";
+ pattern i ppf p;
+ core_type i ppf ct;
+ | Ppat_type (li) ->
+ line i ppf "Ppat_type\n";
+ longident_loc i ppf li
+ | Ppat_unpack s ->
+ line i ppf "Ppat_unpack %a\n" fmt_string_loc s;
+ | Ppat_exception p ->
+ line i ppf "Ppat_exception\n";
+ pattern i ppf p
+ | Ppat_extension (s, arg) ->
+ line i ppf "Ppat_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and expression i ppf x =
+ line i ppf "expression %a\n" fmt_location x.pexp_loc;
+ attributes i ppf x.pexp_attributes;
+ let i = i+1 in
+ match x.pexp_desc with
+ | Pexp_ident (li) -> line i ppf "Pexp_ident %a\n" fmt_longident_loc li;
+ | Pexp_constant (c) -> line i ppf "Pexp_constant %a\n" fmt_constant c;
+ | Pexp_let (rf, l, e) ->
+ line i ppf "Pexp_let %a\n" fmt_rec_flag rf;
+ list i value_binding ppf l;
+ expression i ppf e;
+ | Pexp_function l ->
+ line i ppf "Pexp_function\n";
+ list i case ppf l;
+ | Pexp_fun (l, eo, p, e) ->
+ line i ppf "Pexp_fun\n";
+ arg_label i ppf l;
+ option i expression ppf eo;
+ pattern i ppf p;
+ expression i ppf e;
+ | Pexp_apply (e, l) ->
+ line i ppf "Pexp_apply\n";
+ expression i ppf e;
+ list i label_x_expression ppf l;
+ | Pexp_match (e, l) ->
+ line i ppf "Pexp_match\n";
+ expression i ppf e;
+ list i case ppf l;
+ | Pexp_try (e, l) ->
+ line i ppf "Pexp_try\n";
+ expression i ppf e;
+ list i case ppf l;
+ | Pexp_tuple (l) ->
+ line i ppf "Pexp_tuple\n";
+ list i expression ppf l;
+ | Pexp_construct (li, eo) ->
+ line i ppf "Pexp_construct %a\n" fmt_longident_loc li;
+ option i expression ppf eo;
+ | Pexp_variant (l, eo) ->
+ line i ppf "Pexp_variant \"%s\"\n" l;
+ option i expression ppf eo;
+ | Pexp_record (l, eo) ->
+ line i ppf "Pexp_record\n";
+ list i longident_x_expression ppf l;
+ option i expression ppf eo;
+ | Pexp_field (e, li) ->
+ line i ppf "Pexp_field\n";
+ expression i ppf e;
+ longident_loc i ppf li;
+ | Pexp_setfield (e1, li, e2) ->
+ line i ppf "Pexp_setfield\n";
+ expression i ppf e1;
+ longident_loc i ppf li;
+ expression i ppf e2;
+ | Pexp_array (l) ->
+ line i ppf "Pexp_array\n";
+ list i expression ppf l;
+ | Pexp_ifthenelse (e1, e2, eo) ->
+ line i ppf "Pexp_ifthenelse\n";
+ expression i ppf e1;
+ expression i ppf e2;
+ option i expression ppf eo;
+ | Pexp_sequence (e1, e2) ->
+ line i ppf "Pexp_sequence\n";
+ expression i ppf e1;
+ expression i ppf e2;
+ | Pexp_while (e1, e2) ->
+ line i ppf "Pexp_while\n";
+ expression i ppf e1;
+ expression i ppf e2;
+ | Pexp_for (p, e1, e2, df, e3) ->
+ line i ppf "Pexp_for %a\n" fmt_direction_flag df;
+ pattern i ppf p;
+ expression i ppf e1;
+ expression i ppf e2;
+ expression i ppf e3;
+ | Pexp_constraint (e, ct) ->
+ line i ppf "Pexp_constraint\n";
+ expression i ppf e;
+ core_type i ppf ct;
+ | Pexp_coerce (e, cto1, cto2) ->
+ line i ppf "Pexp_coerce\n";
+ expression i ppf e;
+ option i core_type ppf cto1;
+ core_type i ppf cto2;
+ | Pexp_send (e, s) ->
+ line i ppf "Pexp_send \"%s\"\n" s;
+ expression i ppf e;
+ | Pexp_new (li) -> line i ppf "Pexp_new %a\n" fmt_longident_loc li;
+ | Pexp_setinstvar (s, e) ->
+ line i ppf "Pexp_setinstvar %a\n" fmt_string_loc s;
+ expression i ppf e;
+ | Pexp_override (l) ->
+ line i ppf "Pexp_override\n";
+ list i string_x_expression ppf l;
+ | Pexp_letmodule (s, me, e) ->
+ line i ppf "Pexp_letmodule %a\n" fmt_string_loc s;
+ module_expr i ppf me;
+ expression i ppf e;
+ | Pexp_assert (e) ->
+ line i ppf "Pexp_assert\n";
+ expression i ppf e;
+ | Pexp_lazy (e) ->
+ line i ppf "Pexp_lazy\n";
+ expression i ppf e;
+ | Pexp_poly (e, cto) ->
+ line i ppf "Pexp_poly\n";
+ expression i ppf e;
+ option i core_type ppf cto;
+ | Pexp_object s ->
+ line i ppf "Pexp_object\n";
+ class_structure i ppf s
+ | Pexp_newtype (s, e) ->
+ line i ppf "Pexp_newtype \"%s\"\n" s;
+ expression i ppf e
+ | Pexp_pack me ->
+ line i ppf "Pexp_pack\n";
+ module_expr i ppf me
+ | Pexp_open (ovf, m, e) ->
+ line i ppf "Pexp_open %a \"%a\"\n" fmt_override_flag ovf
+ fmt_longident_loc m;
+ expression i ppf e
+ | Pexp_extension (s, arg) ->
+ line i ppf "Pexp_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and value_description i ppf x =
+ line i ppf "value_description %a %a\n" fmt_string_loc
+ x.pval_name fmt_location x.pval_loc;
+ attributes i ppf x.pval_attributes;
+ core_type (i+1) ppf x.pval_type;
+ list (i+1) string ppf x.pval_prim
+
+and type_parameter i ppf (x, _variance) = core_type i ppf x
+
+and type_declaration i ppf x =
+ line i ppf "type_declaration %a %a\n" fmt_string_loc x.ptype_name
+ fmt_location x.ptype_loc;
+ attributes i ppf x.ptype_attributes;
+ let i = i+1 in
+ line i ppf "ptype_params =\n";
+ list (i+1) type_parameter ppf x.ptype_params;
+ line i ppf "ptype_cstrs =\n";
+ list (i+1) core_type_x_core_type_x_location ppf x.ptype_cstrs;
+ line i ppf "ptype_kind =\n";
+ type_kind (i+1) ppf x.ptype_kind;
+ line i ppf "ptype_private = %a\n" fmt_private_flag x.ptype_private;
+ line i ppf "ptype_manifest =\n";
+ option (i+1) core_type ppf x.ptype_manifest
+
+and attributes i ppf l =
+ let i = i + 1 in
+ List.iter
+ (fun (s, arg) ->
+ line i ppf "attribute \"%s\"\n" s.txt;
+ payload (i + 1) ppf arg;
+ )
+ l
+
+and payload i ppf = function
+ | PStr x -> structure i ppf x
+ | PTyp x -> core_type i ppf x
+ | PPat (x, None) -> pattern i ppf x
+ | PPat (x, Some g) ->
+ pattern i ppf x;
+ line i ppf "<when>\n";
+ expression (i + 1) ppf g
+
+
+and type_kind i ppf x =
+ match x with
+ | Ptype_abstract ->
+ line i ppf "Ptype_abstract\n"
+ | Ptype_variant l ->
+ line i ppf "Ptype_variant\n";
+ list (i+1) constructor_decl ppf l;
+ | Ptype_record l ->
+ line i ppf "Ptype_record\n";
+ list (i+1) label_decl ppf l;
+ | Ptype_open ->
+ line i ppf "Ptype_open\n";
+
+and type_extension i ppf x =
+ line i ppf "type_extension\n";
+ attributes i ppf x.ptyext_attributes;
+ let i = i+1 in
+ line i ppf "ptyext_path = %a\n" fmt_longident_loc x.ptyext_path;
+ line i ppf "ptyext_params =\n";
+ list (i+1) type_parameter ppf x.ptyext_params;
+ line i ppf "ptyext_constructors =\n";
+ list (i+1) extension_constructor ppf x.ptyext_constructors;
+ line i ppf "ptyext_private = %a\n" fmt_private_flag x.ptyext_private;
+
+and extension_constructor i ppf x =
+ line i ppf "extension_constructor %a\n" fmt_location x.pext_loc;
+ attributes i ppf x.pext_attributes;
+ let i = i + 1 in
+ line i ppf "pext_name = \"%s\"\n" x.pext_name.txt;
+ line i ppf "pext_kind =\n";
+ extension_constructor_kind (i + 1) ppf x.pext_kind;
+
+and extension_constructor_kind i ppf x =
+ match x with
+ Pext_decl(a, r) ->
+ line i ppf "Pext_decl\n";
+ constructor_arguments (i+1) ppf a;
+ option (i+1) core_type ppf r;
+ | Pext_rebind li ->
+ line i ppf "Pext_rebind\n";
+ line (i+1) ppf "%a\n" fmt_longident_loc li;
+
+and class_type i ppf x =
+ line i ppf "class_type %a\n" fmt_location x.pcty_loc;
+ attributes i ppf x.pcty_attributes;
+ let i = i+1 in
+ match x.pcty_desc with
+ | Pcty_constr (li, l) ->
+ line i ppf "Pcty_constr %a\n" fmt_longident_loc li;
+ list i core_type ppf l;
+ | Pcty_signature (cs) ->
+ line i ppf "Pcty_signature\n";
+ class_signature i ppf cs;
+ | Pcty_arrow (l, co, cl) ->
+ line i ppf "Pcty_arrow\n";
+ arg_label i ppf l;
+ core_type i ppf co;
+ class_type i ppf cl;
+ | Pcty_extension (s, arg) ->
+ line i ppf "Pcty_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and class_signature i ppf cs =
+ line i ppf "class_signature\n";
+ core_type (i+1) ppf cs.pcsig_self;
+ list (i+1) class_type_field ppf cs.pcsig_fields;
+
+and class_type_field i ppf x =
+ line i ppf "class_type_field %a\n" fmt_location x.pctf_loc;
+ let i = i+1 in
+ attributes i ppf x.pctf_attributes;
+ match x.pctf_desc with
+ | Pctf_inherit (ct) ->
+ line i ppf "Pctf_inherit\n";
+ class_type i ppf ct;
+ | Pctf_val (s, mf, vf, ct) ->
+ line i ppf "Pctf_val \"%s\" %a %a\n" s fmt_mutable_flag mf
+ fmt_virtual_flag vf;
+ core_type (i+1) ppf ct;
+ | Pctf_method (s, pf, vf, ct) ->
+ line i ppf "Pctf_method \"%s\" %a %a\n" s fmt_private_flag pf
+ fmt_virtual_flag vf;
+ core_type (i+1) ppf ct;
+ | Pctf_constraint (ct1, ct2) ->
+ line i ppf "Pctf_constraint\n";
+ core_type (i+1) ppf ct1;
+ core_type (i+1) ppf ct2;
+ | Pctf_attribute (s, arg) ->
+ line i ppf "Pctf_attribute \"%s\"\n" s.txt;
+ payload i ppf arg
+ | Pctf_extension (s, arg) ->
+ line i ppf "Pctf_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and class_description i ppf x =
+ line i ppf "class_description %a\n" fmt_location x.pci_loc;
+ attributes i ppf x.pci_attributes;
+ let i = i+1 in
+ line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt;
+ line i ppf "pci_params =\n";
+ list (i+1) type_parameter ppf x.pci_params;
+ line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name;
+ line i ppf "pci_expr =\n";
+ class_type (i+1) ppf x.pci_expr;
+
+and class_type_declaration i ppf x =
+ line i ppf "class_type_declaration %a\n" fmt_location x.pci_loc;
+ attributes i ppf x.pci_attributes;
+ let i = i+1 in
+ line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt;
+ line i ppf "pci_params =\n";
+ list (i+1) type_parameter ppf x.pci_params;
+ line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name;
+ line i ppf "pci_expr =\n";
+ class_type (i+1) ppf x.pci_expr;
+
+and class_expr i ppf x =
+ line i ppf "class_expr %a\n" fmt_location x.pcl_loc;
+ attributes i ppf x.pcl_attributes;
+ let i = i+1 in
+ match x.pcl_desc with
+ | Pcl_constr (li, l) ->
+ line i ppf "Pcl_constr %a\n" fmt_longident_loc li;
+ list i core_type ppf l;
+ | Pcl_structure (cs) ->
+ line i ppf "Pcl_structure\n";
+ class_structure i ppf cs;
+ | Pcl_fun (l, eo, p, e) ->
+ line i ppf "Pcl_fun\n";
+ arg_label i ppf l;
+ option i expression ppf eo;
+ pattern i ppf p;
+ class_expr i ppf e;
+ | Pcl_apply (ce, l) ->
+ line i ppf "Pcl_apply\n";
+ class_expr i ppf ce;
+ list i label_x_expression ppf l;
+ | Pcl_let (rf, l, ce) ->
+ line i ppf "Pcl_let %a\n" fmt_rec_flag rf;
+ list i value_binding ppf l;
+ class_expr i ppf ce;
+ | Pcl_constraint (ce, ct) ->
+ line i ppf "Pcl_constraint\n";
+ class_expr i ppf ce;
+ class_type i ppf ct;
+ | Pcl_extension (s, arg) ->
+ line i ppf "Pcl_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and class_structure i ppf { pcstr_self = p; pcstr_fields = l } =
+ line i ppf "class_structure\n";
+ pattern (i+1) ppf p;
+ list (i+1) class_field ppf l;
+
+and class_field i ppf x =
+ line i ppf "class_field %a\n" fmt_location x.pcf_loc;
+ let i = i + 1 in
+ attributes i ppf x.pcf_attributes;
+ match x.pcf_desc with
+ | Pcf_inherit (ovf, ce, so) ->
+ line i ppf "Pcf_inherit %a\n" fmt_override_flag ovf;
+ class_expr (i+1) ppf ce;
+ option (i+1) string ppf so;
+ | Pcf_val (s, mf, k) ->
+ line i ppf "Pcf_val %a\n" fmt_mutable_flag mf;
+ line (i+1) ppf "%a\n" fmt_string_loc s;
+ class_field_kind (i+1) ppf k
+ | Pcf_method (s, pf, k) ->
+ line i ppf "Pcf_method %a\n" fmt_private_flag pf;
+ line (i+1) ppf "%a\n" fmt_string_loc s;
+ class_field_kind (i+1) ppf k
+ | Pcf_constraint (ct1, ct2) ->
+ line i ppf "Pcf_constraint\n";
+ core_type (i+1) ppf ct1;
+ core_type (i+1) ppf ct2;
+ | Pcf_initializer (e) ->
+ line i ppf "Pcf_initializer\n";
+ expression (i+1) ppf e;
+ | Pcf_attribute (s, arg) ->
+ line i ppf "Pcf_attribute \"%s\"\n" s.txt;
+ payload i ppf arg
+ | Pcf_extension (s, arg) ->
+ line i ppf "Pcf_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and class_field_kind i ppf = function
+ | Cfk_concrete (o, e) ->
+ line i ppf "Concrete %a\n" fmt_override_flag o;
+ expression i ppf e
+ | Cfk_virtual t ->
+ line i ppf "Virtual\n";
+ core_type i ppf t
+
+and class_declaration i ppf x =
+ line i ppf "class_declaration %a\n" fmt_location x.pci_loc;
+ attributes i ppf x.pci_attributes;
+ let i = i+1 in
+ line i ppf "pci_virt = %a\n" fmt_virtual_flag x.pci_virt;
+ line i ppf "pci_params =\n";
+ list (i+1) type_parameter ppf x.pci_params;
+ line i ppf "pci_name = %a\n" fmt_string_loc x.pci_name;
+ line i ppf "pci_expr =\n";
+ class_expr (i+1) ppf x.pci_expr;
+
+and module_type i ppf x =
+ line i ppf "module_type %a\n" fmt_location x.pmty_loc;
+ attributes i ppf x.pmty_attributes;
+ let i = i+1 in
+ match x.pmty_desc with
+ | Pmty_ident li -> line i ppf "Pmty_ident %a\n" fmt_longident_loc li;
+ | Pmty_alias li -> line i ppf "Pmty_alias %a\n" fmt_longident_loc li;
+ | Pmty_signature (s) ->
+ line i ppf "Pmty_signature\n";
+ signature i ppf s;
+ | Pmty_functor (s, mt1, mt2) ->
+ line i ppf "Pmty_functor %a\n" fmt_string_loc s;
+ Misc.may (module_type i ppf) mt1;
+ module_type i ppf mt2;
+ | Pmty_with (mt, l) ->
+ line i ppf "Pmty_with\n";
+ module_type i ppf mt;
+ list i with_constraint ppf l;
+ | Pmty_typeof m ->
+ line i ppf "Pmty_typeof\n";
+ module_expr i ppf m;
+ | Pmty_extension (s, arg) ->
+ line i ppf "Pmod_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and signature i ppf x = list i signature_item ppf x
+
+and signature_item i ppf x =
+ line i ppf "signature_item %a\n" fmt_location x.psig_loc;
+ let i = i+1 in
+ match x.psig_desc with
+ | Psig_value vd ->
+ line i ppf "Psig_value\n";
+ value_description i ppf vd;
+ | Psig_type (rf, l) ->
+ line i ppf "Psig_type %a\n" fmt_rec_flag rf;
+ list i type_declaration ppf l;
+ | Psig_typext te ->
+ line i ppf "Psig_typext\n";
+ type_extension i ppf te
+ | Psig_exception ext ->
+ line i ppf "Psig_exception\n";
+ extension_constructor i ppf ext;
+ | Psig_module pmd ->
+ line i ppf "Psig_module %a\n" fmt_string_loc pmd.pmd_name;
+ attributes i ppf pmd.pmd_attributes;
+ module_type i ppf pmd.pmd_type
+ | Psig_recmodule decls ->
+ line i ppf "Psig_recmodule\n";
+ list i module_declaration ppf decls;
+ | Psig_modtype x ->
+ line i ppf "Psig_modtype %a\n" fmt_string_loc x.pmtd_name;
+ attributes i ppf x.pmtd_attributes;
+ modtype_declaration i ppf x.pmtd_type
+ | Psig_open od ->
+ line i ppf "Psig_open %a %a\n"
+ fmt_override_flag od.popen_override
+ fmt_longident_loc od.popen_lid;
+ attributes i ppf od.popen_attributes
+ | Psig_include incl ->
+ line i ppf "Psig_include\n";
+ module_type i ppf incl.pincl_mod;
+ attributes i ppf incl.pincl_attributes
+ | Psig_class (l) ->
+ line i ppf "Psig_class\n";
+ list i class_description ppf l;
+ | Psig_class_type (l) ->
+ line i ppf "Psig_class_type\n";
+ list i class_type_declaration ppf l;
+ | Psig_extension ((s, arg), attrs) ->
+ line i ppf "Psig_extension \"%s\"\n" s.txt;
+ attributes i ppf attrs;
+ payload i ppf arg
+ | Psig_attribute (s, arg) ->
+ line i ppf "Psig_attribute \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and modtype_declaration i ppf = function
+ | None -> line i ppf "#abstract"
+ | Some mt -> module_type (i+1) ppf mt
+
+and with_constraint i ppf x =
+ match x with
+ | Pwith_type (lid, td) ->
+ line i ppf "Pwith_type %a\n" fmt_longident_loc lid;
+ type_declaration (i+1) ppf td;
+ | Pwith_typesubst (td) ->
+ line i ppf "Pwith_typesubst\n";
+ type_declaration (i+1) ppf td;
+ | Pwith_module (lid1, lid2) ->
+ line i ppf "Pwith_module %a = %a\n"
+ fmt_longident_loc lid1
+ fmt_longident_loc lid2;
+ | Pwith_modsubst (s, li) ->
+ line i ppf "Pwith_modsubst %a = %a\n"
+ fmt_string_loc s
+ fmt_longident_loc li;
+
+and module_expr i ppf x =
+ line i ppf "module_expr %a\n" fmt_location x.pmod_loc;
+ attributes i ppf x.pmod_attributes;
+ let i = i+1 in
+ match x.pmod_desc with
+ | Pmod_ident (li) -> line i ppf "Pmod_ident %a\n" fmt_longident_loc li;
+ | Pmod_structure (s) ->
+ line i ppf "Pmod_structure\n";
+ structure i ppf s;
+ | Pmod_functor (s, mt, me) ->
+ line i ppf "Pmod_functor %a\n" fmt_string_loc s;
+ Misc.may (module_type i ppf) mt;
+ module_expr i ppf me;
+ | Pmod_apply (me1, me2) ->
+ line i ppf "Pmod_apply\n";
+ module_expr i ppf me1;
+ module_expr i ppf me2;
+ | Pmod_constraint (me, mt) ->
+ line i ppf "Pmod_constraint\n";
+ module_expr i ppf me;
+ module_type i ppf mt;
+ | Pmod_unpack (e) ->
+ line i ppf "Pmod_unpack\n";
+ expression i ppf e;
+ | Pmod_extension (s, arg) ->
+ line i ppf "Pmod_extension \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and structure i ppf x = list i structure_item ppf x
+
+and structure_item i ppf x =
+ line i ppf "structure_item %a\n" fmt_location x.pstr_loc;
+ let i = i+1 in
+ match x.pstr_desc with
+ | Pstr_eval (e, attrs) ->
+ line i ppf "Pstr_eval\n";
+ attributes i ppf attrs;
+ expression i ppf e;
+ | Pstr_value (rf, l) ->
+ line i ppf "Pstr_value %a\n" fmt_rec_flag rf;
+ list i value_binding ppf l;
+ | Pstr_primitive vd ->
+ line i ppf "Pstr_primitive\n";
+ value_description i ppf vd;
+ | Pstr_type (rf, l) ->
+ line i ppf "Pstr_type %a\n" fmt_rec_flag rf;
+ list i type_declaration ppf l;
+ | Pstr_typext te ->
+ line i ppf "Pstr_typext\n";
+ type_extension i ppf te
+ | Pstr_exception ext ->
+ line i ppf "Pstr_exception\n";
+ extension_constructor i ppf ext;
+ | Pstr_module x ->
+ line i ppf "Pstr_module\n";
+ module_binding i ppf x
+ | Pstr_recmodule bindings ->
+ line i ppf "Pstr_recmodule\n";
+ list i module_binding ppf bindings;
+ | Pstr_modtype x ->
+ line i ppf "Pstr_modtype %a\n" fmt_string_loc x.pmtd_name;
+ attributes i ppf x.pmtd_attributes;
+ modtype_declaration i ppf x.pmtd_type
+ | Pstr_open od ->
+ line i ppf "Pstr_open %a %a\n"
+ fmt_override_flag od.popen_override
+ fmt_longident_loc od.popen_lid;
+ attributes i ppf od.popen_attributes
+ | Pstr_class (l) ->
+ line i ppf "Pstr_class\n";
+ list i class_declaration ppf l;
+ | Pstr_class_type (l) ->
+ line i ppf "Pstr_class_type\n";
+ list i class_type_declaration ppf l;
+ | Pstr_include incl ->
+ line i ppf "Pstr_include";
+ attributes i ppf incl.pincl_attributes;
+ module_expr i ppf incl.pincl_mod
+ | Pstr_extension ((s, arg), attrs) ->
+ line i ppf "Pstr_extension \"%s\"\n" s.txt;
+ attributes i ppf attrs;
+ payload i ppf arg
+ | Pstr_attribute (s, arg) ->
+ line i ppf "Pstr_attribute \"%s\"\n" s.txt;
+ payload i ppf arg
+
+and module_declaration i ppf pmd =
+ string_loc i ppf pmd.pmd_name;
+ attributes i ppf pmd.pmd_attributes;
+ module_type (i+1) ppf pmd.pmd_type;
+
+and module_binding i ppf x =
+ string_loc i ppf x.pmb_name;
+ attributes i ppf x.pmb_attributes;
+ module_expr (i+1) ppf x.pmb_expr
+
+and core_type_x_core_type_x_location i ppf (ct1, ct2, l) =
+ line i ppf "<constraint> %a\n" fmt_location l;
+ core_type (i+1) ppf ct1;
+ core_type (i+1) ppf ct2;
+
+and constructor_decl i ppf
+ {pcd_name; pcd_args; pcd_res; pcd_loc; pcd_attributes} =
+ line i ppf "%a\n" fmt_location pcd_loc;
+ line (i+1) ppf "%a\n" fmt_string_loc pcd_name;
+ attributes i ppf pcd_attributes;
+ constructor_arguments (i+1) ppf pcd_args;
+ option (i+1) core_type ppf pcd_res
+
+and constructor_arguments i ppf = function
+ | Pcstr_tuple l -> list i core_type ppf l
+ | Pcstr_record l -> list i label_decl ppf l
+
+and label_decl i ppf {pld_name; pld_mutable; pld_type; pld_loc; pld_attributes}=
+ line i ppf "%a\n" fmt_location pld_loc;
+ attributes i ppf pld_attributes;
+ line (i+1) ppf "%a\n" fmt_mutable_flag pld_mutable;
+ line (i+1) ppf "%a" fmt_string_loc pld_name;
+ core_type (i+1) ppf pld_type
+
+and longident_x_pattern i ppf (li, p) =
+ line i ppf "%a\n" fmt_longident_loc li;
+ pattern (i+1) ppf p;
+
+and case i ppf {pc_lhs; pc_guard; pc_rhs} =
+ line i ppf "<case>\n";
+ pattern (i+1) ppf pc_lhs;
+ begin match pc_guard with
+ | None -> ()
+ | Some g -> line (i+1) ppf "<when>\n"; expression (i + 2) ppf g
+ end;
+ expression (i+1) ppf pc_rhs;
+
+and value_binding i ppf x =
+ line i ppf "<def>\n";
+ attributes (i+1) ppf x.pvb_attributes;
+ pattern (i+1) ppf x.pvb_pat;
+ expression (i+1) ppf x.pvb_expr
+
+and string_x_expression i ppf (s, e) =
+ line i ppf "<override> %a\n" fmt_string_loc s;
+ expression (i+1) ppf e;
+
+and longident_x_expression i ppf (li, e) =
+ line i ppf "%a\n" fmt_longident_loc li;
+ expression (i+1) ppf e;
+
+and label_x_expression i ppf (l,e) =
+ line i ppf "<arg>\n";
+ arg_label i ppf l;
+ expression (i+1) ppf e;
+
+and label_x_bool_x_core_type_list i ppf x =
+ match x with
+ Rtag (l, attrs, b, ctl) ->
+ line i ppf "Rtag \"%s\" %s\n" l (string_of_bool b);
+ attributes (i+1) ppf attrs;
+ list (i+1) core_type ppf ctl
+ | Rinherit (ct) ->
+ line i ppf "Rinherit\n";
+ core_type (i+1) ppf ct
+;;
+
+let rec toplevel_phrase i ppf x =
+ match x with
+ | Ptop_def (s) ->
+ line i ppf "Ptop_def\n";
+ structure (i+1) ppf s;
+ | Ptop_dir (s, da) ->
+ line i ppf "Ptop_dir \"%s\"\n" s;
+ directive_argument i ppf da;
+
+and directive_argument i ppf x =
+ match x with
+ | Pdir_none -> line i ppf "Pdir_none\n"
+ | Pdir_string (s) -> line i ppf "Pdir_string \"%s\"\n" s;
+ | Pdir_int (n) -> line i ppf "Pdir_int %d\n" n;
+ | Pdir_ident (li) -> line i ppf "Pdir_ident %a\n" fmt_longident li;
+ | Pdir_bool (b) -> line i ppf "Pdir_bool %s\n" (string_of_bool b);
+;;
+
+let interface ppf x = list 0 signature_item ppf x;;
+
+let implementation ppf x = list 0 structure_item ppf x;;
+
+let top_phrase ppf x = toplevel_phrase 0 ppf x;;
diff --git a/parsing/printast.mli b/parsing/printast.mli
new file mode 100644
index 0000000000..8523e71c92
--- /dev/null
+++ b/parsing/printast.mli
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Parsetree;;
+open Format;;
+
+val interface : formatter -> signature_item list -> unit;;
+val implementation : formatter -> structure_item list -> unit;;
+val top_phrase : formatter -> toplevel_phrase -> unit;;
+
+val expression: int -> formatter -> expression -> unit
+val structure: int -> formatter -> structure -> unit
+val payload: int -> formatter -> payload -> unit
diff --git a/parsing/syntaxerr.ml b/parsing/syntaxerr.ml
new file mode 100644
index 0000000000..cedfc36c1b
--- /dev/null
+++ b/parsing/syntaxerr.ml
@@ -0,0 +1,80 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliary type for reporting syntax errors *)
+
+type error =
+ Unclosed of Location.t * string * Location.t * string
+ | Expecting of Location.t * string
+ | Not_expecting of Location.t * string
+ | Applicative_path of Location.t
+ | Variable_in_scope of Location.t * string
+ | Other of Location.t
+ | Ill_formed_ast of Location.t * string
+
+exception Error of error
+exception Escape_error
+
+let prepare_error = function
+ | Unclosed(opening_loc, opening, closing_loc, closing) ->
+ Location.errorf_prefixed ~loc:closing_loc
+ ~sub:[
+ Location.errorf_prefixed ~loc:opening_loc
+ "This '%s' might be unmatched" opening
+ ]
+ ~if_highlight:
+ (Printf.sprintf "Syntax error: '%s' expected, \
+ the highlighted '%s' might be unmatched"
+ closing opening)
+ "Syntax error: '%s' expected" closing
+
+ | Expecting (loc, nonterm) ->
+ Location.errorf_prefixed ~loc "Syntax error: %s expected." nonterm
+ | Not_expecting (loc, nonterm) ->
+ Location.errorf_prefixed ~loc "Syntax error: %s not expected." nonterm
+ | Applicative_path loc ->
+ Location.errorf_prefixed ~loc
+ "Syntax error: applicative paths of the form F(X).t \
+ are not supported when the option -no-app-func is set."
+ | Variable_in_scope (loc, var) ->
+ Location.errorf_prefixed ~loc
+ "In this scoped type, variable '%s \
+ is reserved for the local type %s."
+ var var
+ | Other loc ->
+ Location.errorf_prefixed ~loc "Syntax error"
+ | Ill_formed_ast (loc, s) ->
+ Location.errorf_prefixed ~loc "broken invariant in parsetree: %s" s
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (prepare_error err)
+ | _ -> None
+ )
+
+
+let report_error ppf err =
+ Location.report_error ppf (prepare_error err)
+
+let location_of_error = function
+ | Unclosed(l,_,_,_)
+ | Applicative_path l
+ | Variable_in_scope(l,_)
+ | Other l
+ | Not_expecting (l, _)
+ | Ill_formed_ast (l, _)
+ | Expecting (l, _) -> l
+
+
+let ill_formed_ast loc s =
+ raise (Error (Ill_formed_ast (loc, s)))
diff --git a/parsing/syntaxerr.mli b/parsing/syntaxerr.mli
new file mode 100644
index 0000000000..8147213fa4
--- /dev/null
+++ b/parsing/syntaxerr.mli
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliary type for reporting syntax errors *)
+
+open Format
+
+type error =
+ Unclosed of Location.t * string * Location.t * string
+ | Expecting of Location.t * string
+ | Not_expecting of Location.t * string
+ | Applicative_path of Location.t
+ | Variable_in_scope of Location.t * string
+ | Other of Location.t
+ | Ill_formed_ast of Location.t * string
+
+exception Error of error
+exception Escape_error
+
+val report_error: formatter -> error -> unit
+ (* Deprecated. Use Location.{error_of_exn, report_error}. *)
+
+val location_of_error: error -> Location.t
+val ill_formed_ast: Location.t -> string -> 'a
diff --git a/stdlib/.depend b/stdlib/.depend
new file mode 100644
index 0000000000..a3bbd65b3b
--- /dev/null
+++ b/stdlib/.depend
@@ -0,0 +1,301 @@
+arg.cmi :
+arrayLabels.cmi :
+array.cmi :
+buffer.cmi :
+bytesLabels.cmi :
+bytes.cmi :
+callback.cmi :
+camlinternalFormatBasics.cmi :
+camlinternalFormat.cmi : camlinternalFormatBasics.cmi buffer.cmi
+camlinternalLazy.cmi :
+camlinternalMod.cmi : obj.cmi
+camlinternalOO.cmi : obj.cmi
+char.cmi :
+complex.cmi :
+digest.cmi :
+filename.cmi :
+format.cmi : pervasives.cmi buffer.cmi
+gc.cmi :
+genlex.cmi : stream.cmi
+hashtbl.cmi :
+int32.cmi :
+int64.cmi :
+lazy.cmi :
+lexing.cmi :
+listLabels.cmi :
+list.cmi :
+map.cmi :
+marshal.cmi :
+moreLabels.cmi : set.cmi map.cmi hashtbl.cmi
+nativeint.cmi :
+obj.cmi : int32.cmi
+oo.cmi : camlinternalOO.cmi
+parsing.cmi : obj.cmi lexing.cmi
+pervasives.cmi : camlinternalFormatBasics.cmi
+printexc.cmi :
+printf.cmi : buffer.cmi
+queue.cmi :
+random.cmi : nativeint.cmi int64.cmi int32.cmi
+scanf.cmi : pervasives.cmi
+set.cmi :
+sort.cmi :
+stack.cmi :
+stdLabels.cmi : stringLabels.cmi listLabels.cmi bytesLabels.cmi \
+ arrayLabels.cmi
+stream.cmi :
+stringLabels.cmi :
+string.cmi :
+sys.cmi :
+weak.cmi : hashtbl.cmi
+arg.cmo : sys.cmi string.cmi printf.cmi list.cmi buffer.cmi array.cmi \
+ arg.cmi
+arg.cmx : sys.cmx string.cmx printf.cmx list.cmx buffer.cmx array.cmx \
+ arg.cmi
+arrayLabels.cmo : array.cmi arrayLabels.cmi
+arrayLabels.cmx : array.cmx arrayLabels.cmi
+array.cmo : array.cmi
+array.cmx : array.cmi
+buffer.cmo : sys.cmi string.cmi bytes.cmi buffer.cmi
+buffer.cmx : sys.cmx string.cmx bytes.cmx buffer.cmi
+bytesLabels.cmo : bytes.cmi bytesLabels.cmi
+bytesLabels.cmx : bytes.cmx bytesLabels.cmi
+bytes.cmo : pervasives.cmi list.cmi char.cmi bytes.cmi
+bytes.cmx : pervasives.cmx list.cmx char.cmx bytes.cmi
+callback.cmo : obj.cmi callback.cmi
+callback.cmx : obj.cmx callback.cmi
+camlinternalFormatBasics.cmo : camlinternalFormatBasics.cmi
+camlinternalFormatBasics.cmx : camlinternalFormatBasics.cmi
+camlinternalFormat.cmo : sys.cmi string.cmi char.cmi \
+ camlinternalFormatBasics.cmi bytes.cmi buffer.cmi camlinternalFormat.cmi
+camlinternalFormat.cmx : sys.cmx string.cmx char.cmx \
+ camlinternalFormatBasics.cmx bytes.cmx buffer.cmx camlinternalFormat.cmi
+camlinternalLazy.cmo : obj.cmi camlinternalLazy.cmi
+camlinternalLazy.cmx : obj.cmx camlinternalLazy.cmi
+camlinternalMod.cmo : obj.cmi camlinternalOO.cmi array.cmi \
+ camlinternalMod.cmi
+camlinternalMod.cmx : obj.cmx camlinternalOO.cmx array.cmx \
+ camlinternalMod.cmi
+camlinternalOO.cmo : sys.cmi string.cmi obj.cmi map.cmi list.cmi char.cmi \
+ array.cmi camlinternalOO.cmi
+camlinternalOO.cmx : sys.cmx string.cmx obj.cmx map.cmx list.cmx char.cmx \
+ array.cmx camlinternalOO.cmi
+char.cmo : char.cmi
+char.cmx : char.cmi
+complex.cmo : complex.cmi
+complex.cmx : complex.cmi
+digest.cmo : string.cmi char.cmi bytes.cmi digest.cmi
+digest.cmx : string.cmx char.cmx bytes.cmx digest.cmi
+filename.cmo : sys.cmi string.cmi random.cmi printf.cmi lazy.cmi buffer.cmi \
+ filename.cmi
+filename.cmx : sys.cmx string.cmx random.cmx printf.cmx lazy.cmx buffer.cmx \
+ filename.cmi
+format.cmo : string.cmi pervasives.cmi camlinternalFormatBasics.cmi \
+ camlinternalFormat.cmi buffer.cmi format.cmi
+format.cmx : string.cmx pervasives.cmx camlinternalFormatBasics.cmx \
+ camlinternalFormat.cmx buffer.cmx format.cmi
+gc.cmo : sys.cmi printf.cmi gc.cmi
+gc.cmx : sys.cmx printf.cmx gc.cmi
+genlex.cmo : string.cmi stream.cmi list.cmi hashtbl.cmi char.cmi bytes.cmi \
+ genlex.cmi
+genlex.cmx : string.cmx stream.cmx list.cmx hashtbl.cmx char.cmx bytes.cmx \
+ genlex.cmi
+hashtbl.cmo : sys.cmi string.cmi random.cmi obj.cmi lazy.cmi array.cmi \
+ hashtbl.cmi
+hashtbl.cmx : sys.cmx string.cmx random.cmx obj.cmx lazy.cmx array.cmx \
+ hashtbl.cmi
+int32.cmo : pervasives.cmi int32.cmi
+int32.cmx : pervasives.cmx int32.cmi
+int64.cmo : pervasives.cmi int64.cmi
+int64.cmx : pervasives.cmx int64.cmi
+lazy.cmo : obj.cmi camlinternalLazy.cmi lazy.cmi
+lazy.cmx : obj.cmx camlinternalLazy.cmx lazy.cmi
+lexing.cmo : sys.cmi string.cmi bytes.cmi array.cmi lexing.cmi
+lexing.cmx : sys.cmx string.cmx bytes.cmx array.cmx lexing.cmi
+listLabels.cmo : list.cmi listLabels.cmi
+listLabels.cmx : list.cmx listLabels.cmi
+list.cmo : list.cmi
+list.cmx : list.cmi
+map.cmo : map.cmi
+map.cmx : map.cmi
+marshal.cmo : bytes.cmi marshal.cmi
+marshal.cmx : bytes.cmx marshal.cmi
+moreLabels.cmo : set.cmi map.cmi hashtbl.cmi moreLabels.cmi
+moreLabels.cmx : set.cmx map.cmx hashtbl.cmx moreLabels.cmi
+nativeint.cmo : sys.cmi pervasives.cmi nativeint.cmi
+nativeint.cmx : sys.cmx pervasives.cmx nativeint.cmi
+obj.cmo : marshal.cmi int32.cmi array.cmi obj.cmi
+obj.cmx : marshal.cmx int32.cmx array.cmx obj.cmi
+oo.cmo : camlinternalOO.cmi oo.cmi
+oo.cmx : camlinternalOO.cmx oo.cmi
+parsing.cmo : obj.cmi lexing.cmi array.cmi parsing.cmi
+parsing.cmx : obj.cmx lexing.cmx array.cmx parsing.cmi
+pervasives.cmo : camlinternalFormatBasics.cmi pervasives.cmi
+pervasives.cmx : camlinternalFormatBasics.cmx pervasives.cmi
+printexc.cmo : printf.cmi pervasives.cmi obj.cmi buffer.cmi array.cmi \
+ printexc.cmi
+printexc.cmx : printf.cmx pervasives.cmx obj.cmx buffer.cmx array.cmx \
+ printexc.cmi
+printf.cmo : camlinternalFormatBasics.cmi camlinternalFormat.cmi buffer.cmi \
+ printf.cmi
+printf.cmx : camlinternalFormatBasics.cmx camlinternalFormat.cmx buffer.cmx \
+ printf.cmi
+queue.cmo : obj.cmi queue.cmi
+queue.cmx : obj.cmx queue.cmi
+random.cmo : pervasives.cmi nativeint.cmi int64.cmi int32.cmi digest.cmi \
+ char.cmi array.cmi random.cmi
+random.cmx : pervasives.cmx nativeint.cmx int64.cmx int32.cmx digest.cmx \
+ char.cmx array.cmx random.cmi
+scanf.cmo : string.cmi printf.cmi pervasives.cmi list.cmi \
+ camlinternalFormatBasics.cmi camlinternalFormat.cmi bytes.cmi buffer.cmi \
+ scanf.cmi
+scanf.cmx : string.cmx printf.cmx pervasives.cmx list.cmx \
+ camlinternalFormatBasics.cmx camlinternalFormat.cmx bytes.cmx buffer.cmx \
+ scanf.cmi
+set.cmo : list.cmi set.cmi
+set.cmx : list.cmx set.cmi
+sort.cmo : array.cmi sort.cmi
+sort.cmx : array.cmx sort.cmi
+stack.cmo : list.cmi stack.cmi
+stack.cmx : list.cmx stack.cmi
+std_exit.cmo :
+std_exit.cmx :
+stdLabels.cmo : stringLabels.cmi listLabels.cmi bytesLabels.cmi \
+ arrayLabels.cmi stdLabels.cmi
+stdLabels.cmx : stringLabels.cmx listLabels.cmx bytesLabels.cmx \
+ arrayLabels.cmx stdLabels.cmi
+stream.cmo : string.cmi obj.cmi list.cmi lazy.cmi bytes.cmi stream.cmi
+stream.cmx : string.cmx obj.cmx list.cmx lazy.cmx bytes.cmx stream.cmi
+stringLabels.cmo : string.cmi stringLabels.cmi
+stringLabels.cmx : string.cmx stringLabels.cmi
+string.cmo : pervasives.cmi list.cmi bytes.cmi string.cmi
+string.cmx : pervasives.cmx list.cmx bytes.cmx string.cmi
+sys.cmo : sys.cmi
+sys.cmx : sys.cmi
+weak.cmo : sys.cmi obj.cmi hashtbl.cmi array.cmi weak.cmi
+weak.cmx : sys.cmx obj.cmx hashtbl.cmx array.cmx weak.cmi
+arg.cmo : sys.cmi string.cmi printf.cmi list.cmi buffer.cmi array.cmi \
+ arg.cmi
+arg.p.cmx : sys.p.cmx string.p.cmx printf.p.cmx list.p.cmx buffer.p.cmx array.p.cmx \
+ arg.cmi
+arrayLabels.cmo : array.cmi arrayLabels.cmi
+arrayLabels.p.cmx : array.p.cmx arrayLabels.cmi
+array.cmo : array.cmi
+array.p.cmx : array.cmi
+buffer.cmo : sys.cmi string.cmi bytes.cmi buffer.cmi
+buffer.p.cmx : sys.p.cmx string.p.cmx bytes.p.cmx buffer.cmi
+bytesLabels.cmo : bytes.cmi bytesLabels.cmi
+bytesLabels.p.cmx : bytes.p.cmx bytesLabels.cmi
+bytes.cmo : pervasives.cmi list.cmi char.cmi bytes.cmi
+bytes.p.cmx : pervasives.p.cmx list.p.cmx char.p.cmx bytes.cmi
+callback.cmo : obj.cmi callback.cmi
+callback.p.cmx : obj.p.cmx callback.cmi
+camlinternalFormatBasics.cmo : camlinternalFormatBasics.cmi
+camlinternalFormatBasics.p.cmx : camlinternalFormatBasics.cmi
+camlinternalFormat.cmo : sys.cmi string.cmi char.cmi \
+ camlinternalFormatBasics.cmi bytes.cmi buffer.cmi camlinternalFormat.cmi
+camlinternalFormat.p.cmx : sys.p.cmx string.p.cmx char.p.cmx \
+ camlinternalFormatBasics.p.cmx bytes.p.cmx buffer.p.cmx camlinternalFormat.cmi
+camlinternalLazy.cmo : obj.cmi camlinternalLazy.cmi
+camlinternalLazy.p.cmx : obj.p.cmx camlinternalLazy.cmi
+camlinternalMod.cmo : obj.cmi camlinternalOO.cmi array.cmi \
+ camlinternalMod.cmi
+camlinternalMod.p.cmx : obj.p.cmx camlinternalOO.p.cmx array.p.cmx \
+ camlinternalMod.cmi
+camlinternalOO.cmo : sys.cmi string.cmi obj.cmi map.cmi list.cmi char.cmi \
+ array.cmi camlinternalOO.cmi
+camlinternalOO.p.cmx : sys.p.cmx string.p.cmx obj.p.cmx map.p.cmx list.p.cmx char.p.cmx \
+ array.p.cmx camlinternalOO.cmi
+char.cmo : char.cmi
+char.p.cmx : char.cmi
+complex.cmo : complex.cmi
+complex.p.cmx : complex.cmi
+digest.cmo : string.cmi char.cmi bytes.cmi digest.cmi
+digest.p.cmx : string.p.cmx char.p.cmx bytes.p.cmx digest.cmi
+filename.cmo : sys.cmi string.cmi random.cmi printf.cmi lazy.cmi buffer.cmi \
+ filename.cmi
+filename.p.cmx : sys.p.cmx string.p.cmx random.p.cmx printf.p.cmx lazy.p.cmx buffer.p.cmx \
+ filename.cmi
+format.cmo : string.cmi pervasives.cmi camlinternalFormatBasics.cmi \
+ camlinternalFormat.cmi buffer.cmi format.cmi
+format.p.cmx : string.p.cmx pervasives.p.cmx camlinternalFormatBasics.p.cmx \
+ camlinternalFormat.p.cmx buffer.p.cmx format.cmi
+gc.cmo : sys.cmi printf.cmi gc.cmi
+gc.p.cmx : sys.p.cmx printf.p.cmx gc.cmi
+genlex.cmo : string.cmi stream.cmi list.cmi hashtbl.cmi char.cmi bytes.cmi \
+ genlex.cmi
+genlex.p.cmx : string.p.cmx stream.p.cmx list.p.cmx hashtbl.p.cmx char.p.cmx bytes.p.cmx \
+ genlex.cmi
+hashtbl.cmo : sys.cmi string.cmi random.cmi obj.cmi lazy.cmi array.cmi \
+ hashtbl.cmi
+hashtbl.p.cmx : sys.p.cmx string.p.cmx random.p.cmx obj.p.cmx lazy.p.cmx array.p.cmx \
+ hashtbl.cmi
+int32.cmo : pervasives.cmi int32.cmi
+int32.p.cmx : pervasives.p.cmx int32.cmi
+int64.cmo : pervasives.cmi int64.cmi
+int64.p.cmx : pervasives.p.cmx int64.cmi
+lazy.cmo : obj.cmi camlinternalLazy.cmi lazy.cmi
+lazy.p.cmx : obj.p.cmx camlinternalLazy.p.cmx lazy.cmi
+lexing.cmo : sys.cmi string.cmi bytes.cmi array.cmi lexing.cmi
+lexing.p.cmx : sys.p.cmx string.p.cmx bytes.p.cmx array.p.cmx lexing.cmi
+listLabels.cmo : list.cmi listLabels.cmi
+listLabels.p.cmx : list.p.cmx listLabels.cmi
+list.cmo : list.cmi
+list.p.cmx : list.cmi
+map.cmo : map.cmi
+map.p.cmx : map.cmi
+marshal.cmo : bytes.cmi marshal.cmi
+marshal.p.cmx : bytes.p.cmx marshal.cmi
+moreLabels.cmo : set.cmi map.cmi hashtbl.cmi moreLabels.cmi
+moreLabels.p.cmx : set.p.cmx map.p.cmx hashtbl.p.cmx moreLabels.cmi
+nativeint.cmo : sys.cmi pervasives.cmi nativeint.cmi
+nativeint.p.cmx : sys.p.cmx pervasives.p.cmx nativeint.cmi
+obj.cmo : marshal.cmi int32.cmi array.cmi obj.cmi
+obj.p.cmx : marshal.p.cmx int32.p.cmx array.p.cmx obj.cmi
+oo.cmo : camlinternalOO.cmi oo.cmi
+oo.p.cmx : camlinternalOO.p.cmx oo.cmi
+parsing.cmo : obj.cmi lexing.cmi array.cmi parsing.cmi
+parsing.p.cmx : obj.p.cmx lexing.p.cmx array.p.cmx parsing.cmi
+pervasives.cmo : camlinternalFormatBasics.cmi pervasives.cmi
+pervasives.p.cmx : camlinternalFormatBasics.p.cmx pervasives.cmi
+printexc.cmo : printf.cmi pervasives.cmi obj.cmi buffer.cmi array.cmi \
+ printexc.cmi
+printexc.p.cmx : printf.p.cmx pervasives.p.cmx obj.p.cmx buffer.p.cmx array.p.cmx \
+ printexc.cmi
+printf.cmo : camlinternalFormatBasics.cmi camlinternalFormat.cmi buffer.cmi \
+ printf.cmi
+printf.p.cmx : camlinternalFormatBasics.p.cmx camlinternalFormat.p.cmx buffer.p.cmx \
+ printf.cmi
+queue.cmo : obj.cmi queue.cmi
+queue.p.cmx : obj.p.cmx queue.cmi
+random.cmo : pervasives.cmi nativeint.cmi int64.cmi int32.cmi digest.cmi \
+ char.cmi array.cmi random.cmi
+random.p.cmx : pervasives.p.cmx nativeint.p.cmx int64.p.cmx int32.p.cmx digest.p.cmx \
+ char.p.cmx array.p.cmx random.cmi
+scanf.cmo : string.cmi printf.cmi pervasives.cmi list.cmi \
+ camlinternalFormatBasics.cmi camlinternalFormat.cmi bytes.cmi buffer.cmi \
+ scanf.cmi
+scanf.p.cmx : string.p.cmx printf.p.cmx pervasives.p.cmx list.p.cmx \
+ camlinternalFormatBasics.p.cmx camlinternalFormat.p.cmx bytes.p.cmx buffer.p.cmx \
+ scanf.cmi
+set.cmo : list.cmi set.cmi
+set.p.cmx : list.p.cmx set.cmi
+sort.cmo : array.cmi sort.cmi
+sort.p.cmx : array.p.cmx sort.cmi
+stack.cmo : list.cmi stack.cmi
+stack.p.cmx : list.p.cmx stack.cmi
+std_exit.cmo :
+std_exit.p.cmx :
+stdLabels.cmo : stringLabels.cmi listLabels.cmi bytesLabels.cmi \
+ arrayLabels.cmi stdLabels.cmi
+stdLabels.p.cmx : stringLabels.p.cmx listLabels.p.cmx bytesLabels.p.cmx \
+ arrayLabels.p.cmx stdLabels.cmi
+stream.cmo : string.cmi obj.cmi list.cmi lazy.cmi bytes.cmi stream.cmi
+stream.p.cmx : string.p.cmx obj.p.cmx list.p.cmx lazy.p.cmx bytes.p.cmx stream.cmi
+stringLabels.cmo : string.cmi stringLabels.cmi
+stringLabels.p.cmx : string.p.cmx stringLabels.cmi
+string.cmo : pervasives.cmi list.cmi bytes.cmi string.cmi
+string.p.cmx : pervasives.p.cmx list.p.cmx bytes.p.cmx string.cmi
+sys.cmo : sys.cmi
+sys.p.cmx : sys.cmi
+weak.cmo : sys.cmi obj.cmi hashtbl.cmi array.cmi weak.cmi
+weak.p.cmx : sys.p.cmx obj.p.cmx hashtbl.p.cmx array.p.cmx weak.cmi
diff --git a/stdlib/.ignore b/stdlib/.ignore
new file mode 100644
index 0000000000..20d8653fe9
--- /dev/null
+++ b/stdlib/.ignore
@@ -0,0 +1,8 @@
+camlheader
+target_camlheader
+camlheaderd
+target_camlheaderd
+camlheader_ur
+labelled-*
+caml
+sys.ml
diff --git a/stdlib/Compflags b/stdlib/Compflags
new file mode 100755
index 0000000000..f393c4ec00
--- /dev/null
+++ b/stdlib/Compflags
@@ -0,0 +1,28 @@
+#!/bin/sh
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2004 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+case $1 in
+ pervasives.cm[iox]|pervasives.p.cmx) echo ' -nopervasives';;
+ camlinternalOO.cmi) echo ' -nopervasives';;
+ camlinternalOO.cmx|camlinternalOO.p.cmx) echo ' -inline 0';;
+ buffer.cmx|buffer.p.cmx) echo ' -inline 3';;
+ # make sure add_char is inlined (PR#5872)
+ buffer.cm[io]) echo ' -w A';;
+ camlinternalFormat.cm[io]) echo ' -w Ae';;
+ camlinternalFormatBasics*.cm[iox]) echo ' -nopervasives';;
+ printf.cm[io]|format.cm[io]|scanf.cm[io]) echo ' -w Ae';;
+ scanf.cmx|scanf.p.cmx) echo ' -inline 9';;
+ *Labels.cm[ox]|*Labels.p.cmx) echo ' -nolabels -no-alias-deps';;
+ *) echo ' ';;
+esac
diff --git a/stdlib/Makefile b/stdlib/Makefile
new file mode 100644
index 0000000000..92fa3740ea
--- /dev/null
+++ b/stdlib/Makefile
@@ -0,0 +1,73 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include Makefile.shared
+
+allopt:
+ $(MAKE) stdlib.cmxa std_exit.cmx
+ $(MAKE) allopt-$(PROFILING)
+
+allopt-noprof:
+
+allopt-prof: stdlib.p.cmxa std_exit.p.cmx
+ rm -f std_exit.p.cmi
+
+installopt: installopt-default installopt-$(PROFILING)
+
+installopt-default:
+ cp stdlib.cmxa stdlib.a std_exit.o *.cmx $(INSTALL_LIBDIR)
+ cd $(INSTALL_LIBDIR); $(RANLIB) stdlib.a
+
+installopt-noprof:
+ rm -f $(INSTALL_LIBDIR)/stdlib.p.cmxa; \
+ ln -s stdlib.cmxa $(INSTALL_LIBDIR)/stdlib.p.cmxa
+ rm -f $(INSTALL_LIBDIR)/stdlib.p.a; \
+ ln -s stdlib.a $(INSTALL_LIBDIR)/stdlib.p.a
+ rm -f $(INSTALL_LIBDIR)/std_exit.p.cmx; \
+ ln -s std_exit.cmx $(INSTALL_LIBDIR)/std_exit.p.cmx
+ rm -f $(INSTALL_LIBDIR)/std_exit.p.o; \
+ ln -s std_exit.o $(INSTALL_LIBDIR)/std_exit.p.o
+
+installopt-prof:
+ cp stdlib.p.cmxa stdlib.p.a std_exit.p.cmx std_exit.p.o $(INSTALL_LIBDIR)
+ cd $(INSTALL_LIBDIR); $(RANLIB) stdlib.p.a
+
+stdlib.p.cmxa: $(OBJS:.cmo=.p.cmx)
+ $(CAMLOPT) -a -o stdlib.p.cmxa $(OBJS:.cmo=.p.cmx)
+
+camlheader target_camlheader camlheaderd target_camlheaderd camlheader_ur: \
+ header.c ../config/Makefile
+ if $(SHARPBANGSCRIPTS); then \
+ echo '#!$(BINDIR)/ocamlrun' > camlheader && \
+ echo '#!$(TARGET_BINDIR)/ocamlrun' > target_camlheader && \
+ echo '#!$(BINDIR)/ocamlrund' > camlheaderd && \
+ echo '#!$(TARGET_BINDIR)/ocamlrund' > target_camlheaderd && \
+ echo '#!' | tr -d '\012' > camlheader_ur; \
+ else \
+ for suff in '' d; do \
+ $(BYTECC) $(BYTECCCOMPOPTS) $(BYTECCLINKOPTS) \
+ -DRUNTIME_NAME='"$(BINDIR)/ocamlrun'$$suff'"' \
+ header.c -o tmpheader$(EXE) && \
+ strip tmpheader$(EXE) && \
+ mv tmpheader$(EXE) camlheader$$suff && \
+ $(BYTECC) $(BYTECCCOMPOPTS) $(BYTECCLINKOPTS) \
+ -DRUNTIME_NAME='"$(TARGET_BINDIR)/ocamlrun'$$suff'"' \
+ header.c -o tmpheader$(EXE) && \
+ strip tmpheader$(EXE) && \
+ mv tmpheader$(EXE) target_camlheader$$suff; \
+ done && \
+ cp camlheader camlheader_ur; \
+ fi
+
+.PHONY: all allopt allopt-noprof allopt-prof install installopt
+.PHONY: installopt-default installopt-noprof installopt-prof clean depend
diff --git a/stdlib/Makefile.nt b/stdlib/Makefile.nt
new file mode 100644
index 0000000000..5bc2e0edfa
--- /dev/null
+++ b/stdlib/Makefile.nt
@@ -0,0 +1,38 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include Makefile.shared
+
+allopt: stdlib.cmxa std_exit.cmx
+
+installopt:
+ cp stdlib.cmxa stdlib.$(A) std_exit.$(O) *.cmx $(INSTALL_LIBDIR)
+
+camlheader target_camlheader camlheader_ur: headernt.c ../config/Makefile
+ $(BYTECC) $(BYTECCCOMPOPTS) -c -I../byterun \
+ -DRUNTIME_NAME='"ocamlrun"' headernt.c
+ $(MKEXE) -o tmpheader.exe headernt.$(O) $(EXTRALIBS)
+ rm -f camlheader.exe
+ mv tmpheader.exe camlheader
+ cp camlheader target_camlheader
+ cp camlheader camlheader_ur
+
+camlheaderd target_camlheaderd: headernt.c ../config/Makefile
+ $(BYTECC) $(BYTECCCOMPOPTS) -c -I../byterun \
+ -DRUNTIME_NAME='"ocamlrund"' headernt.c
+ $(MKEXE) -o tmpheader.exe headernt.$(O) $(EXTRALIBS)
+ mv tmpheader.exe camlheaderd
+ cp camlheaderd target_camlheaderd
+
+# TODO: do not call flexlink to build tmpheader.exe (we don't need
+# the export table)
diff --git a/stdlib/Makefile.shared b/stdlib/Makefile.shared
new file mode 100755
index 0000000000..4b4d977340
--- /dev/null
+++ b/stdlib/Makefile.shared
@@ -0,0 +1,112 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+TARGET_BINDIR ?= $(BINDIR)
+
+COMPILER=../ocamlc
+CAMLC=$(CAMLRUN) $(COMPILER)
+COMPFLAGS=-strict-sequence -w +33..39 -g -warn-error A -bin-annot -nostdlib \
+ -safe-string
+OPTCOMPILER=../ocamlopt
+CAMLOPT=$(CAMLRUN) $(OPTCOMPILER)
+CAMLDEP=$(CAMLRUN) ../tools/ocamldep
+
+OBJS=camlinternalFormatBasics.cmo pervasives.cmo $(OTHERS)
+OTHERS=array.cmo list.cmo char.cmo bytes.cmo string.cmo sys.cmo \
+ sort.cmo marshal.cmo obj.cmo \
+ int32.cmo int64.cmo nativeint.cmo \
+ lexing.cmo parsing.cmo \
+ set.cmo map.cmo stack.cmo queue.cmo \
+ camlinternalLazy.cmo lazy.cmo stream.cmo \
+ buffer.cmo camlinternalFormat.cmo printf.cmo \
+ arg.cmo printexc.cmo gc.cmo \
+ digest.cmo random.cmo hashtbl.cmo weak.cmo \
+ format.cmo scanf.cmo callback.cmo \
+ camlinternalOO.cmo oo.cmo camlinternalMod.cmo \
+ genlex.cmo \
+ filename.cmo complex.cmo \
+ arrayLabels.cmo listLabels.cmo bytesLabels.cmo \
+ stringLabels.cmo moreLabels.cmo stdLabels.cmo
+
+all: stdlib.cma std_exit.cmo camlheader target_camlheader camlheader_ur
+
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+
+install: install-$(RUNTIMED)
+ cp stdlib.cma std_exit.cmo *.cmi *.cmt *.cmti *.mli *.ml \
+ camlheader_ur \
+ $(INSTALL_LIBDIR)
+ cp target_camlheader $(INSTALL_LIBDIR)/camlheader
+
+install-noruntimed:
+.PHONY: install-noruntimed
+
+install-runtimed: target_camlheaderd
+ cp target_camlheaderd $(INSTALL_LIBDIR)/camlheaderd
+.PHONY: install-runtimed
+
+stdlib.cma: $(OBJS)
+ $(CAMLC) -a -o stdlib.cma $(OBJS)
+
+stdlib.cmxa: $(OBJS:.cmo=.cmx)
+ $(CAMLOPT) -a -o stdlib.cmxa $(OBJS:.cmo=.cmx)
+
+sys.ml: sys.mlp ../VERSION
+ sed -e "s|%%VERSION%%|`sed -e 1q ../VERSION`|" sys.mlp >sys.ml
+
+clean::
+ rm -f sys.ml
+
+clean::
+ rm -f camlheader target_camlheader camlheader_ur target_camlheaderd
+
+.SUFFIXES: .mli .ml .cmi .cmo .cmx .p.cmx
+
+.mli.cmi:
+ $(CAMLC) $(COMPFLAGS) `./Compflags $@` -c $<
+
+.ml.cmo:
+ $(CAMLC) $(COMPFLAGS) `./Compflags $@` -c $<
+
+.ml.cmx:
+ $(CAMLOPT) $(COMPFLAGS) `./Compflags $@` -c $<
+
+.ml.p.cmx:
+ $(CAMLOPT) $(COMPFLAGS) `./Compflags $@` -p -c -o $*.p.cmx $<
+
+# Dependencies on the compiler
+$(OBJS) std_exit.cmo: $(COMPILER)
+$(OBJS:.cmo=.cmi) std_exit.cmi: $(COMPILER)
+$(OBJS:.cmo=.cmx) std_exit.cmx: $(OPTCOMPILER)
+$(OBJS:.cmo=.p.cmx) std_exit.p.cmx: $(OPTCOMPILER)
+
+# Dependencies on Pervasives (not tracked by ocamldep)
+$(OTHERS) std_exit.cmo: pervasives.cmi
+$(OTHERS:.cmo=.cmi) std_exit.cmi: pervasives.cmi
+$(OBJS:.cmo=.cmx) std_exit.cmx: pervasives.cmi
+$(OBJS:.cmo=.p.cmx) std_exit.p.cmx: pervasives.cmi
+$(OTHERS:.cmo=.cmx) std_exit.cmx: pervasives.cmx
+$(OTHERS:.cmo=.p.cmx) std_exit.p.cmx: pervasives.cmx
+
+clean::
+ rm -f *.cm* *.$(O) *.$(A)
+ rm -f *~
+
+include .depend
+
+depend:
+ $(CAMLDEP) *.mli *.ml > .depend
+ $(CAMLDEP) *.ml | sed -e 's/\.cmx/.p.cmx/g' >>.depend
diff --git a/stdlib/StdlibModules b/stdlib/StdlibModules
new file mode 100644
index 0000000000..abdfcb3620
--- /dev/null
+++ b/stdlib/StdlibModules
@@ -0,0 +1,67 @@
+# -*- Makefile -*-
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2002 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the GNU Library General Public License, with #
+# the special exception on linking described in file ../LICENSE. #
+# #
+#########################################################################
+
+# This file lists all standard library modules.
+# It is used in particular to know what to expunge in toplevels.
+
+STDLIB_MODULES=\
+ arg \
+ array \
+ arrayLabels \
+ buffer \
+ bytes \
+ bytesLabels \
+ callback \
+ camlinternalFormat \
+ camlinternalFormatBasics \
+ camlinternalLazy \
+ camlinternalMod \
+ camlinternalOO \
+ char \
+ complex \
+ digest \
+ filename \
+ format \
+ gc \
+ genlex \
+ hashtbl \
+ int32 \
+ int64 \
+ lazy \
+ lexing \
+ list \
+ listLabels \
+ map \
+ marshal \
+ moreLabels \
+ nativeint \
+ obj \
+ oo \
+ parsing \
+ pervasives \
+ printexc \
+ printf \
+ queue \
+ random \
+ scanf \
+ set \
+ sort \
+ stack \
+ stdLabels \
+ stream \
+ string \
+ stringLabels \
+ sys \
+ weak
diff --git a/stdlib/arg.ml b/stdlib/arg.ml
new file mode 100644
index 0000000000..d7b8ac0bf6
--- /dev/null
+++ b/stdlib/arg.ml
@@ -0,0 +1,278 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type key = string
+type doc = string
+type usage_msg = string
+type anon_fun = (string -> unit)
+
+type spec =
+ | Unit of (unit -> unit) (* Call the function with unit argument *)
+ | Bool of (bool -> unit) (* Call the function with a bool argument *)
+ | Set of bool ref (* Set the reference to true *)
+ | Clear of bool ref (* Set the reference to false *)
+ | String of (string -> unit) (* Call the function with a string argument *)
+ | Set_string of string ref (* Set the reference to the string argument *)
+ | Int of (int -> unit) (* Call the function with an int argument *)
+ | Set_int of int ref (* Set the reference to the int argument *)
+ | Float of (float -> unit) (* Call the function with a float argument *)
+ | Set_float of float ref (* Set the reference to the float argument *)
+ | Tuple of spec list (* Take several arguments according to the
+ spec list *)
+ | Symbol of string list * (string -> unit)
+ (* Take one of the symbols as argument and
+ call the function with the symbol. *)
+ | Rest of (string -> unit) (* Stop interpreting keywords and call the
+ function with each remaining argument *)
+
+exception Bad of string
+exception Help of string
+
+type error =
+ | Unknown of string
+ | Wrong of string * string * string (* option, actual, expected *)
+ | Missing of string
+ | Message of string
+
+exception Stop of error;; (* used internally *)
+
+open Printf
+
+let rec assoc3 x l =
+ match l with
+ | [] -> raise Not_found
+ | (y1, y2, y3) :: t when y1 = x -> y2
+ | _ :: t -> assoc3 x t
+;;
+
+let make_symlist prefix sep suffix l =
+ match l with
+ | [] -> "<none>"
+ | h::t -> (List.fold_left (fun x y -> x ^ sep ^ y) (prefix ^ h) t) ^ suffix
+;;
+
+let print_spec buf (key, spec, doc) =
+ if String.length doc > 0 then
+ match spec with
+ | Symbol (l, _) ->
+ bprintf buf " %s %s%s\n" key (make_symlist "{" "|" "}" l) doc
+ | _ ->
+ bprintf buf " %s %s\n" key doc
+;;
+
+let help_action () = raise (Stop (Unknown "-help"));;
+
+let add_help speclist =
+ let add1 =
+ try ignore (assoc3 "-help" speclist); []
+ with Not_found ->
+ ["-help", Unit help_action, " Display this list of options"]
+ and add2 =
+ try ignore (assoc3 "--help" speclist); []
+ with Not_found ->
+ ["--help", Unit help_action, " Display this list of options"]
+ in
+ speclist @ (add1 @ add2)
+;;
+
+let usage_b buf speclist errmsg =
+ bprintf buf "%s\n" errmsg;
+ List.iter (print_spec buf) (add_help speclist);
+;;
+
+let usage_string speclist errmsg =
+ let b = Buffer.create 200 in
+ usage_b b speclist errmsg;
+ Buffer.contents b;
+;;
+
+let usage speclist errmsg =
+ eprintf "%s" (usage_string speclist errmsg);
+;;
+
+let current = ref 0;;
+
+let parse_argv_dynamic ?(current=current) argv speclist anonfun errmsg =
+ let l = Array.length argv in
+ let b = Buffer.create 200 in
+ let initpos = !current in
+ let stop error =
+ let progname = if initpos < l then argv.(initpos) else "(?)" in
+ begin match error with
+ | Unknown "-help" -> ()
+ | Unknown "--help" -> ()
+ | Unknown s ->
+ bprintf b "%s: unknown option '%s'.\n" progname s
+ | Missing s ->
+ bprintf b "%s: option '%s' needs an argument.\n" progname s
+ | Wrong (opt, arg, expected) ->
+ bprintf b "%s: wrong argument '%s'; option '%s' expects %s.\n"
+ progname arg opt expected
+ | Message s ->
+ bprintf b "%s: %s.\n" progname s
+ end;
+ usage_b b !speclist errmsg;
+ if error = Unknown "-help" || error = Unknown "--help"
+ then raise (Help (Buffer.contents b))
+ else raise (Bad (Buffer.contents b))
+ in
+ incr current;
+ while !current < l do
+ let s = argv.(!current) in
+ if String.length s >= 1 && s.[0] = '-' then begin
+ let action =
+ try assoc3 s !speclist
+ with Not_found -> stop (Unknown s)
+ in
+ begin try
+ let rec treat_action = function
+ | Unit f -> f ();
+ | Bool f when !current + 1 < l ->
+ let arg = argv.(!current + 1) in
+ begin try f (bool_of_string arg)
+ with Invalid_argument "bool_of_string" ->
+ raise (Stop (Wrong (s, arg, "a boolean")))
+ end;
+ incr current;
+ | Set r -> r := true;
+ | Clear r -> r := false;
+ | String f when !current + 1 < l ->
+ f argv.(!current + 1);
+ incr current;
+ | Symbol (symb, f) when !current + 1 < l ->
+ let arg = argv.(!current + 1) in
+ if List.mem arg symb then begin
+ f argv.(!current + 1);
+ incr current;
+ end else begin
+ raise (Stop (Wrong (s, arg, "one of: "
+ ^ (make_symlist "" " " "" symb))))
+ end
+ | Set_string r when !current + 1 < l ->
+ r := argv.(!current + 1);
+ incr current;
+ | Int f when !current + 1 < l ->
+ let arg = argv.(!current + 1) in
+ begin try f (int_of_string arg)
+ with Failure "int_of_string" ->
+ raise (Stop (Wrong (s, arg, "an integer")))
+ end;
+ incr current;
+ | Set_int r when !current + 1 < l ->
+ let arg = argv.(!current + 1) in
+ begin try r := (int_of_string arg)
+ with Failure "int_of_string" ->
+ raise (Stop (Wrong (s, arg, "an integer")))
+ end;
+ incr current;
+ | Float f when !current + 1 < l ->
+ let arg = argv.(!current + 1) in
+ begin try f (float_of_string arg);
+ with Failure "float_of_string" ->
+ raise (Stop (Wrong (s, arg, "a float")))
+ end;
+ incr current;
+ | Set_float r when !current + 1 < l ->
+ let arg = argv.(!current + 1) in
+ begin try r := (float_of_string arg);
+ with Failure "float_of_string" ->
+ raise (Stop (Wrong (s, arg, "a float")))
+ end;
+ incr current;
+ | Tuple specs ->
+ List.iter treat_action specs;
+ | Rest f ->
+ while !current < l - 1 do
+ f argv.(!current + 1);
+ incr current;
+ done;
+ | _ -> raise (Stop (Missing s))
+ in
+ treat_action action
+ with Bad m -> stop (Message m);
+ | Stop e -> stop e;
+ end;
+ incr current;
+ end else begin
+ (try anonfun s with Bad m -> stop (Message m));
+ incr current;
+ end;
+ done;
+;;
+
+let parse_argv ?(current=current) argv speclist anonfun errmsg =
+ parse_argv_dynamic ~current:current argv (ref speclist) anonfun errmsg;
+;;
+
+let parse l f msg =
+ try
+ parse_argv Sys.argv l f msg;
+ with
+ | Bad msg -> eprintf "%s" msg; exit 2;
+ | Help msg -> printf "%s" msg; exit 0;
+;;
+
+let parse_dynamic l f msg =
+ try
+ parse_argv_dynamic Sys.argv l f msg;
+ with
+ | Bad msg -> eprintf "%s" msg; exit 2;
+ | Help msg -> printf "%s" msg; exit 0;
+;;
+
+let second_word s =
+ let len = String.length s in
+ let rec loop n =
+ if n >= len then len
+ else if s.[n] = ' ' then loop (n+1)
+ else n
+ in
+ try loop (String.index s ' ')
+ with Not_found -> len
+;;
+
+let max_arg_len cur (kwd, spec, doc) =
+ match spec with
+ | Symbol _ -> max cur (String.length kwd)
+ | _ -> max cur (String.length kwd + second_word doc)
+;;
+
+let add_padding len ksd =
+ match ksd with
+ | (_, _, "") ->
+ (* Do not pad undocumented options, so that they still don't show up when
+ * run through [usage] or [parse]. *)
+ ksd
+ | (kwd, (Symbol (l, _) as spec), msg) ->
+ let cutcol = second_word msg in
+ let spaces = String.make ((max 0 (len - cutcol)) + 3) ' ' in
+ (kwd, spec, "\n" ^ spaces ^ msg)
+ | (kwd, spec, msg) ->
+ let cutcol = second_word msg in
+ let kwd_len = String.length kwd in
+ let diff = len - kwd_len - cutcol in
+ if diff <= 0 then
+ (kwd, spec, msg)
+ else
+ let spaces = String.make diff ' ' in
+ let prefix = String.sub msg 0 cutcol in
+ let suffix = String.sub msg cutcol (String.length msg - cutcol) in
+ (kwd, spec, prefix ^ spaces ^ suffix)
+;;
+
+let align ?(limit=max_int) speclist =
+ let completed = add_help speclist in
+ let len = List.fold_left max_arg_len 0 completed in
+ let len = min len limit in
+ List.map (add_padding len) completed
+;;
diff --git a/stdlib/arg.mli b/stdlib/arg.mli
new file mode 100644
index 0000000000..0999edf5f3
--- /dev/null
+++ b/stdlib/arg.mli
@@ -0,0 +1,158 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Parsing of command line arguments.
+
+ This module provides a general mechanism for extracting options and
+ arguments from the command line to the program.
+
+ Syntax of command lines:
+ A keyword is a character string starting with a [-].
+ An option is a keyword alone or followed by an argument.
+ The types of keywords are: [Unit], [Bool], [Set], [Clear],
+ [String], [Set_string], [Int], [Set_int], [Float], [Set_float],
+ [Tuple], [Symbol], and [Rest].
+ [Unit], [Set] and [Clear] keywords take no argument. A [Rest]
+ keyword takes the remaining of the command line as arguments.
+ Every other keyword takes the following word on the command line
+ as argument.
+ Arguments not preceded by a keyword are called anonymous arguments.
+
+ Examples ([cmd] is assumed to be the command name):
+- [cmd -flag ](a unit option)
+- [cmd -int 1 ](an int option with argument [1])
+- [cmd -string foobar ](a string option with argument ["foobar"])
+- [cmd -float 12.34 ](a float option with argument [12.34])
+- [cmd a b c ](three anonymous arguments: ["a"], ["b"], and ["c"])
+- [cmd a b -- c d ](two anonymous arguments and a rest option with
+ two arguments)
+*)
+
+type spec =
+ | Unit of (unit -> unit) (** Call the function with unit argument *)
+ | Bool of (bool -> unit) (** Call the function with a bool argument *)
+ | Set of bool ref (** Set the reference to true *)
+ | Clear of bool ref (** Set the reference to false *)
+ | String of (string -> unit) (** Call the function with a string argument *)
+ | Set_string of string ref (** Set the reference to the string argument *)
+ | Int of (int -> unit) (** Call the function with an int argument *)
+ | Set_int of int ref (** Set the reference to the int argument *)
+ | Float of (float -> unit) (** Call the function with a float argument *)
+ | Set_float of float ref (** Set the reference to the float argument *)
+ | Tuple of spec list (** Take several arguments according to the
+ spec list *)
+ | Symbol of string list * (string -> unit)
+ (** Take one of the symbols as argument and
+ call the function with the symbol *)
+ | Rest of (string -> unit) (** Stop interpreting keywords and call the
+ function with each remaining argument *)
+(** The concrete type describing the behavior associated
+ with a keyword. *)
+
+type key = string
+type doc = string
+type usage_msg = string
+type anon_fun = (string -> unit)
+
+val parse :
+ (key * spec * doc) list -> anon_fun -> usage_msg -> unit
+(** [Arg.parse speclist anon_fun usage_msg] parses the command line.
+ [speclist] is a list of triples [(key, spec, doc)].
+ [key] is the option keyword, it must start with a ['-'] character.
+ [spec] gives the option type and the function to call when this option
+ is found on the command line.
+ [doc] is a one-line description of this option.
+ [anon_fun] is called on anonymous arguments.
+ The functions in [spec] and [anon_fun] are called in the same order
+ as their arguments appear on the command line.
+
+ If an error occurs, [Arg.parse] exits the program, after printing
+ to standard error an error message as follows:
+- The reason for the error: unknown option, invalid or missing argument, etc.
+- [usage_msg]
+- The list of options, each followed by the corresponding [doc] string.
+ Beware: options that have an empty [doc] string will not be included in the
+ list.
+
+ For the user to be able to specify anonymous arguments starting with a
+ [-], include for example [("-", String anon_fun, doc)] in [speclist].
+
+ By default, [parse] recognizes two unit options, [-help] and [--help],
+ which will print to standard output [usage_msg] and the list of
+ options, and exit the program. You can override this behaviour
+ by specifying your own [-help] and [--help] options in [speclist].
+*)
+
+val parse_dynamic :
+ (key * spec * doc) list ref -> anon_fun -> usage_msg -> unit
+(** Same as {!Arg.parse}, except that the [speclist] argument is a reference
+ and may be updated during the parsing. A typical use for this feature
+ is to parse command lines of the form:
+- command subcommand [options]
+ where the list of options depends on the value of the subcommand argument.
+*)
+
+val parse_argv : ?current: int ref -> string array ->
+ (key * spec * doc) list -> anon_fun -> usage_msg -> unit
+(** [Arg.parse_argv ~current args speclist anon_fun usage_msg] parses
+ the array [args] as if it were the command line. It uses and updates
+ the value of [~current] (if given), or [Arg.current]. You must set
+ it before calling [parse_argv]. The initial value of [current]
+ is the index of the program name (argument 0) in the array.
+ If an error occurs, [Arg.parse_argv] raises [Arg.Bad] with
+ the error message as argument. If option [-help] or [--help] is
+ given, [Arg.parse_argv] raises [Arg.Help] with the help message
+ as argument.
+*)
+
+val parse_argv_dynamic : ?current:int ref -> string array ->
+ (key * spec * doc) list ref -> anon_fun -> string -> unit
+(** Same as {!Arg.parse_argv}, except that the [speclist] argument is a
+ reference and may be updated during the parsing.
+ See {!Arg.parse_dynamic}.
+*)
+
+exception Help of string
+(** Raised by [Arg.parse_argv] when the user asks for help. *)
+
+exception Bad of string
+(** Functions in [spec] or [anon_fun] can raise [Arg.Bad] with an error
+ message to reject invalid arguments.
+ [Arg.Bad] is also raised by [Arg.parse_argv] in case of an error. *)
+
+val usage : (key * spec * doc) list -> usage_msg -> unit
+(** [Arg.usage speclist usage_msg] prints to standard error
+ an error message that includes the list of valid options. This is
+ the same message that {!Arg.parse} prints in case of error.
+ [speclist] and [usage_msg] are the same as for [Arg.parse]. *)
+
+val usage_string : (key * spec * doc) list -> usage_msg -> string
+(** Returns the message that would have been printed by {!Arg.usage},
+ if provided with the same parameters. *)
+
+val align: ?limit: int -> (key * spec * doc) list -> (key * spec * doc) list;;
+(** Align the documentation strings by inserting spaces at the first
+ space, according to the length of the keyword. Use a
+ space as the first character in a doc string if you want to
+ align the whole string. The doc strings corresponding to
+ [Symbol] arguments are aligned on the next line.
+ @param limit options with keyword and message longer than
+ [limit] will not be used to compute the alignement.
+*)
+
+val current : int ref
+(** Position (in {!Sys.argv}) of the argument being processed. You can
+ change this value, e.g. to force {!Arg.parse} to skip some arguments.
+ {!Arg.parse} uses the initial value of {!Arg.current} as the index of
+ argument 0 (the program name) and starts parsing arguments
+ at the next element. *)
diff --git a/stdlib/array.ml b/stdlib/array.ml
new file mode 100644
index 0000000000..43e4f768d8
--- /dev/null
+++ b/stdlib/array.ml
@@ -0,0 +1,240 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Array operations *)
+
+external length : 'a array -> int = "%array_length"
+external get: 'a array -> int -> 'a = "%array_safe_get"
+external set: 'a array -> int -> 'a -> unit = "%array_safe_set"
+external unsafe_get: 'a array -> int -> 'a = "%array_unsafe_get"
+external unsafe_set: 'a array -> int -> 'a -> unit = "%array_unsafe_set"
+external make: int -> 'a -> 'a array = "caml_make_vect"
+external create: int -> 'a -> 'a array = "caml_make_vect"
+external unsafe_sub : 'a array -> int -> int -> 'a array = "caml_array_sub"
+external append_prim : 'a array -> 'a array -> 'a array = "caml_array_append"
+external concat : 'a array list -> 'a array = "caml_array_concat"
+external unsafe_blit :
+ 'a array -> int -> 'a array -> int -> int -> unit = "caml_array_blit"
+external create_float: int -> float array = "caml_make_float_vect"
+let make_float = create_float
+
+let init l f =
+ if l = 0 then [||] else
+ if l < 0 then invalid_arg "Array.init"
+ (* See #6575. We could also check for maximum array size, but this depends
+ on whether we create a float array or a regular one... *)
+ else
+ let res = create l (f 0) in
+ for i = 1 to pred l do
+ unsafe_set res i (f i)
+ done;
+ res
+
+let make_matrix sx sy init =
+ let res = create sx [||] in
+ for x = 0 to pred sx do
+ unsafe_set res x (create sy init)
+ done;
+ res
+
+let create_matrix = make_matrix
+
+let copy a =
+ let l = length a in if l = 0 then [||] else unsafe_sub a 0 l
+
+let append a1 a2 =
+ let l1 = length a1 in
+ if l1 = 0 then copy a2
+ else if length a2 = 0 then unsafe_sub a1 0 l1
+ else append_prim a1 a2
+
+let sub a ofs len =
+ if len < 0 || ofs > length a - len
+ then invalid_arg "Array.sub"
+ else unsafe_sub a ofs len
+
+let fill a ofs len v =
+ if ofs < 0 || len < 0 || ofs > length a - len
+ then invalid_arg "Array.fill"
+ else for i = ofs to ofs + len - 1 do unsafe_set a i v done
+
+let blit a1 ofs1 a2 ofs2 len =
+ if len < 0 || ofs1 < 0 || ofs1 > length a1 - len
+ || ofs2 < 0 || ofs2 > length a2 - len
+ then invalid_arg "Array.blit"
+ else unsafe_blit a1 ofs1 a2 ofs2 len
+
+let iter f a =
+ for i = 0 to length a - 1 do f(unsafe_get a i) done
+
+let map f a =
+ let l = length a in
+ if l = 0 then [||] else begin
+ let r = create l (f(unsafe_get a 0)) in
+ for i = 1 to l - 1 do
+ unsafe_set r i (f(unsafe_get a i))
+ done;
+ r
+ end
+
+let iteri f a =
+ for i = 0 to length a - 1 do f i (unsafe_get a i) done
+
+let mapi f a =
+ let l = length a in
+ if l = 0 then [||] else begin
+ let r = create l (f 0 (unsafe_get a 0)) in
+ for i = 1 to l - 1 do
+ unsafe_set r i (f i (unsafe_get a i))
+ done;
+ r
+ end
+
+let to_list a =
+ let rec tolist i res =
+ if i < 0 then res else tolist (i - 1) (unsafe_get a i :: res) in
+ tolist (length a - 1) []
+
+(* Cannot use List.length here because the List module depends on Array. *)
+let rec list_length accu = function
+ | [] -> accu
+ | h::t -> list_length (succ accu) t
+;;
+
+let of_list = function
+ [] -> [||]
+ | hd::tl as l ->
+ let a = create (list_length 0 l) hd in
+ let rec fill i = function
+ [] -> a
+ | hd::tl -> unsafe_set a i hd; fill (i+1) tl in
+ fill 1 tl
+
+let fold_left f x a =
+ let r = ref x in
+ for i = 0 to length a - 1 do
+ r := f !r (unsafe_get a i)
+ done;
+ !r
+
+let fold_right f a x =
+ let r = ref x in
+ for i = length a - 1 downto 0 do
+ r := f (unsafe_get a i) !r
+ done;
+ !r
+
+exception Bottom of int;;
+let sort cmp a =
+ let maxson l i =
+ let i31 = i+i+i+1 in
+ let x = ref i31 in
+ if i31+2 < l then begin
+ if cmp (get a i31) (get a (i31+1)) < 0 then x := i31+1;
+ if cmp (get a !x) (get a (i31+2)) < 0 then x := i31+2;
+ !x
+ end else
+ if i31+1 < l && cmp (get a i31) (get a (i31+1)) < 0
+ then i31+1
+ else if i31 < l then i31 else raise (Bottom i)
+ in
+ let rec trickledown l i e =
+ let j = maxson l i in
+ if cmp (get a j) e > 0 then begin
+ set a i (get a j);
+ trickledown l j e;
+ end else begin
+ set a i e;
+ end;
+ in
+ let trickle l i e = try trickledown l i e with Bottom i -> set a i e in
+ let rec bubbledown l i =
+ let j = maxson l i in
+ set a i (get a j);
+ bubbledown l j
+ in
+ let bubble l i = try bubbledown l i with Bottom i -> i in
+ let rec trickleup i e =
+ let father = (i - 1) / 3 in
+ assert (i <> father);
+ if cmp (get a father) e < 0 then begin
+ set a i (get a father);
+ if father > 0 then trickleup father e else set a 0 e;
+ end else begin
+ set a i e;
+ end;
+ in
+ let l = length a in
+ for i = (l + 1) / 3 - 1 downto 0 do trickle l i (get a i); done;
+ for i = l - 1 downto 2 do
+ let e = (get a i) in
+ set a i (get a 0);
+ trickleup (bubble i 0) e;
+ done;
+ if l > 1 then (let e = (get a 1) in set a 1 (get a 0); set a 0 e);
+;;
+
+let cutoff = 5;;
+let stable_sort cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ set dst d s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 (get a i1) i2 s2 (d + 1)
+ else
+ blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ set dst d s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 (get src2 i2) (d + 1)
+ else
+ blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs (get a src1ofs) src2ofs (get src2 src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = (get a (srcofs + i)) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp (get dst !j) e > 0) do
+ set dst (!j + 1) (get dst !j);
+ decr j;
+ done;
+ set dst (!j + 1) e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = make l2 (get a 0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let fast_sort = stable_sort;;
diff --git a/stdlib/array.mli b/stdlib/array.mli
new file mode 100644
index 0000000000..c2edadbf8a
--- /dev/null
+++ b/stdlib/array.mli
@@ -0,0 +1,215 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Array operations. *)
+
+external length : 'a array -> int = "%array_length"
+(** Return the length (number of elements) of the given array. *)
+
+external get : 'a array -> int -> 'a = "%array_safe_get"
+(** [Array.get a n] returns the element number [n] of array [a].
+ The first element has number 0.
+ The last element has number [Array.length a - 1].
+ You can also write [a.(n)] instead of [Array.get a n].
+
+ Raise [Invalid_argument "index out of bounds"]
+ if [n] is outside the range 0 to [(Array.length a - 1)]. *)
+
+external set : 'a array -> int -> 'a -> unit = "%array_safe_set"
+(** [Array.set a n x] modifies array [a] in place, replacing
+ element number [n] with [x].
+ You can also write [a.(n) <- x] instead of [Array.set a n x].
+
+ Raise [Invalid_argument "index out of bounds"]
+ if [n] is outside the range 0 to [Array.length a - 1]. *)
+
+external make : int -> 'a -> 'a array = "caml_make_vect"
+(** [Array.make n x] returns a fresh array of length [n],
+ initialized with [x].
+ All the elements of this new array are initially
+ physically equal to [x] (in the sense of the [==] predicate).
+ Consequently, if [x] is mutable, it is shared among all elements
+ of the array, and modifying [x] through one of the array entries
+ will modify all other entries at the same time.
+
+ Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
+ If the value of [x] is a floating-point number, then the maximum
+ size is only [Sys.max_array_length / 2].*)
+
+external create : int -> 'a -> 'a array = "caml_make_vect"
+ [@@ocaml.deprecated "Use Array.make instead."]
+(** @deprecated [Array.create] is an alias for {!Array.make}. *)
+
+val init : int -> (int -> 'a) -> 'a array
+(** [Array.init n f] returns a fresh array of length [n],
+ with element number [i] initialized to the result of [f i].
+ In other terms, [Array.init n f] tabulates the results of [f]
+ applied to the integers [0] to [n-1].
+
+ Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
+ If the return type of [f] is [float], then the maximum
+ size is only [Sys.max_array_length / 2].*)
+
+val make_matrix : int -> int -> 'a -> 'a array array
+(** [Array.make_matrix dimx dimy e] returns a two-dimensional array
+ (an array of arrays) with first dimension [dimx] and
+ second dimension [dimy]. All the elements of this new matrix
+ are initially physically equal to [e].
+ The element ([x,y]) of a matrix [m] is accessed
+ with the notation [m.(x).(y)].
+
+ Raise [Invalid_argument] if [dimx] or [dimy] is negative or
+ greater than [Sys.max_array_length].
+ If the value of [e] is a floating-point number, then the maximum
+ size is only [Sys.max_array_length / 2]. *)
+
+val create_matrix : int -> int -> 'a -> 'a array array
+ [@@ocaml.deprecated "Use Array.make_matrix instead."]
+(** @deprecated [Array.create_matrix] is an alias for {!Array.make_matrix}. *)
+
+val append : 'a array -> 'a array -> 'a array
+(** [Array.append v1 v2] returns a fresh array containing the
+ concatenation of the arrays [v1] and [v2]. *)
+
+val concat : 'a array list -> 'a array
+(** Same as [Array.append], but concatenates a list of arrays. *)
+
+val sub : 'a array -> int -> int -> 'a array
+(** [Array.sub a start len] returns a fresh array of length [len],
+ containing the elements number [start] to [start + len - 1]
+ of array [a].
+
+ Raise [Invalid_argument "Array.sub"] if [start] and [len] do not
+ designate a valid subarray of [a]; that is, if
+ [start < 0], or [len < 0], or [start + len > Array.length a]. *)
+
+val copy : 'a array -> 'a array
+(** [Array.copy a] returns a copy of [a], that is, a fresh array
+ containing the same elements as [a]. *)
+
+val fill : 'a array -> int -> int -> 'a -> unit
+(** [Array.fill a ofs len x] modifies the array [a] in place,
+ storing [x] in elements number [ofs] to [ofs + len - 1].
+
+ Raise [Invalid_argument "Array.fill"] if [ofs] and [len] do not
+ designate a valid subarray of [a]. *)
+
+val blit : 'a array -> int -> 'a array -> int -> int -> unit
+(** [Array.blit v1 o1 v2 o2 len] copies [len] elements
+ from array [v1], starting at element number [o1], to array [v2],
+ starting at element number [o2]. It works correctly even if
+ [v1] and [v2] are the same array, and the source and
+ destination chunks overlap.
+
+ Raise [Invalid_argument "Array.blit"] if [o1] and [len] do not
+ designate a valid subarray of [v1], or if [o2] and [len] do not
+ designate a valid subarray of [v2]. *)
+
+val to_list : 'a array -> 'a list
+(** [Array.to_list a] returns the list of all the elements of [a]. *)
+
+val of_list : 'a list -> 'a array
+(** [Array.of_list l] returns a fresh array containing the elements
+ of [l]. *)
+
+val iter : ('a -> unit) -> 'a array -> unit
+(** [Array.iter f a] applies function [f] in turn to all
+ the elements of [a]. It is equivalent to
+ [f a.(0); f a.(1); ...; f a.(Array.length a - 1); ()]. *)
+
+val map : ('a -> 'b) -> 'a array -> 'b array
+(** [Array.map f a] applies function [f] to all the elements of [a],
+ and builds an array with the results returned by [f]:
+ [[| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]]. *)
+
+val iteri : (int -> 'a -> unit) -> 'a array -> unit
+(** Same as {!Array.iter}, but the
+ function is applied to the index of the element as first argument,
+ and the element itself as second argument. *)
+
+val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array
+(** Same as {!Array.map}, but the
+ function is applied to the index of the element as first argument,
+ and the element itself as second argument. *)
+
+val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
+(** [Array.fold_left f x a] computes
+ [f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)],
+ where [n] is the length of the array [a]. *)
+
+val fold_right : ('b -> 'a -> 'a) -> 'b array -> 'a -> 'a
+(** [Array.fold_right f a x] computes
+ [f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))],
+ where [n] is the length of the array [a]. *)
+
+external create_float: int -> float array = "caml_make_float_vect"
+(** [Array.create_float n] returns a fresh float array of length [n],
+ with uninitialized data.
+ @since 4.03 *)
+
+val make_float: int -> float array
+ [@@ocaml.deprecated "Use Array.create_float instead."]
+(** @deprecated [Array.make_float] is an alias for {!Array.create_float}. *)
+
+(** {6 Sorting} *)
+
+
+val sort : ('a -> 'a -> int) -> 'a array -> unit
+(** Sort an array in increasing order according to a comparison
+ function. The comparison function must return 0 if its arguments
+ compare as equal, a positive integer if the first is greater,
+ and a negative integer if the first is smaller (see below for a
+ complete specification). For example, {!Pervasives.compare} is
+ a suitable comparison function, provided there are no floating-point
+ NaN values in the data. After calling [Array.sort], the
+ array is sorted in place in increasing order.
+ [Array.sort] is guaranteed to run in constant heap space
+ and (at most) logarithmic stack space.
+
+ The current implementation uses Heap Sort. It runs in constant
+ stack space.
+
+ Specification of the comparison function:
+ Let [a] be the array and [cmp] the comparison function. The following
+ must be true for all x, y, z in a :
+- [cmp x y] > 0 if and only if [cmp y x] < 0
+- if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0
+
+ When [Array.sort] returns, [a] contains the same elements as before,
+ reordered in such a way that for all i and j valid indices of [a] :
+- [cmp a.(i) a.(j)] >= 0 if and only if i >= j
+*)
+
+val stable_sort : ('a -> 'a -> int) -> 'a array -> unit
+(** Same as {!Array.sort}, but the sorting algorithm is stable (i.e.
+ elements that compare equal are kept in their original order) and
+ not guaranteed to run in constant heap space.
+
+ The current implementation uses Merge Sort. It uses [n/2]
+ words of heap space, where [n] is the length of the array.
+ It is usually faster than the current implementation of {!Array.sort}.
+*)
+
+val fast_sort : ('a -> 'a -> int) -> 'a array -> unit
+(** Same as {!Array.sort} or {!Array.stable_sort}, whichever is faster
+ on typical input.
+*)
+
+
+(**/**)
+(** {6 Undocumented functions} *)
+
+(* The following is for system use only. Do not call directly. *)
+
+external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
+external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
diff --git a/stdlib/arrayLabels.ml b/stdlib/arrayLabels.ml
new file mode 100644
index 0000000000..39b4bde7f9
--- /dev/null
+++ b/stdlib/arrayLabels.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [ArrayLabels]: labelled Array module *)
+
+include Array
diff --git a/stdlib/arrayLabels.mli b/stdlib/arrayLabels.mli
new file mode 100644
index 0000000000..7df2b8a784
--- /dev/null
+++ b/stdlib/arrayLabels.mli
@@ -0,0 +1,221 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Array operations. *)
+
+external length : 'a array -> int = "%array_length"
+(** Return the length (number of elements) of the given array. *)
+
+external get : 'a array -> int -> 'a = "%array_safe_get"
+(** [ArrayLabels.get a n] returns the element number [n] of array [a].
+ The first element has number 0.
+ The last element has number [ArrayLabels.length a - 1].
+ You can also write [a.(n)] instead of [ArrayLabels.get a n].
+
+ Raise [Invalid_argument "index out of bounds"]
+ if [n] is outside the range 0 to [(ArrayLabels.length a - 1)]. *)
+
+external set : 'a array -> int -> 'a -> unit = "%array_safe_set"
+(** [ArrayLabels.set a n x] modifies array [a] in place, replacing
+ element number [n] with [x].
+ You can also write [a.(n) <- x] instead of [ArrayLabels.set a n x].
+
+ Raise [Invalid_argument "index out of bounds"]
+ if [n] is outside the range 0 to [ArrayLabels.length a - 1]. *)
+
+external make : int -> 'a -> 'a array = "caml_make_vect"
+(** [ArrayLabels.make n x] returns a fresh array of length [n],
+ initialized with [x].
+ All the elements of this new array are initially
+ physically equal to [x] (in the sense of the [==] predicate).
+ Consequently, if [x] is mutable, it is shared among all elements
+ of the array, and modifying [x] through one of the array entries
+ will modify all other entries at the same time.
+
+ Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
+ If the value of [x] is a floating-point number, then the maximum
+ size is only [Sys.max_array_length / 2].*)
+
+external create : int -> 'a -> 'a array = "caml_make_vect"
+ [@@ocaml.deprecated "Use ArrayLabels.make instead."]
+(** @deprecated [ArrayLabels.create] is an alias for {!ArrayLabels.make}. *)
+
+val init : int -> f:(int -> 'a) -> 'a array
+(** [ArrayLabels.init n f] returns a fresh array of length [n],
+ with element number [i] initialized to the result of [f i].
+ In other terms, [ArrayLabels.init n f] tabulates the results of [f]
+ applied to the integers [0] to [n-1].
+
+ Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
+ If the return type of [f] is [float], then the maximum
+ size is only [Sys.max_array_length / 2].*)
+
+val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
+(** [ArrayLabels.make_matrix dimx dimy e] returns a two-dimensional array
+ (an array of arrays) with first dimension [dimx] and
+ second dimension [dimy]. All the elements of this new matrix
+ are initially physically equal to [e].
+ The element ([x,y]) of a matrix [m] is accessed
+ with the notation [m.(x).(y)].
+
+ Raise [Invalid_argument] if [dimx] or [dimy] is negative or
+ greater than [Sys.max_array_length].
+ If the value of [e] is a floating-point number, then the maximum
+ size is only [Sys.max_array_length / 2]. *)
+
+val create_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
+ [@@ocaml.deprecated "Use ArrayLabels.make_matrix instead."]
+(** @deprecated [ArrayLabels.create_matrix] is an alias for
+ {!ArrayLabels.make_matrix}. *)
+
+val append : 'a array -> 'a array -> 'a array
+(** [ArrayLabels.append v1 v2] returns a fresh array containing the
+ concatenation of the arrays [v1] and [v2]. *)
+
+val concat : 'a array list -> 'a array
+(** Same as [ArrayLabels.append], but concatenates a list of arrays. *)
+
+val sub : 'a array -> pos:int -> len:int -> 'a array
+(** [ArrayLabels.sub a start len] returns a fresh array of length [len],
+ containing the elements number [start] to [start + len - 1]
+ of array [a].
+
+ Raise [Invalid_argument "Array.sub"] if [start] and [len] do not
+ designate a valid subarray of [a]; that is, if
+ [start < 0], or [len < 0], or [start + len > ArrayLabels.length a]. *)
+
+val copy : 'a array -> 'a array
+(** [ArrayLabels.copy a] returns a copy of [a], that is, a fresh array
+ containing the same elements as [a]. *)
+
+val fill : 'a array -> pos:int -> len:int -> 'a -> unit
+(** [ArrayLabels.fill a ofs len x] modifies the array [a] in place,
+ storing [x] in elements number [ofs] to [ofs + len - 1].
+
+ Raise [Invalid_argument "Array.fill"] if [ofs] and [len] do not
+ designate a valid subarray of [a]. *)
+
+val blit :
+ src:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int ->
+ unit
+(** [ArrayLabels.blit v1 o1 v2 o2 len] copies [len] elements
+ from array [v1], starting at element number [o1], to array [v2],
+ starting at element number [o2]. It works correctly even if
+ [v1] and [v2] are the same array, and the source and
+ destination chunks overlap.
+
+ Raise [Invalid_argument "Array.blit"] if [o1] and [len] do not
+ designate a valid subarray of [v1], or if [o2] and [len] do not
+ designate a valid subarray of [v2]. *)
+
+val to_list : 'a array -> 'a list
+(** [ArrayLabels.to_list a] returns the list of all the elements of [a]. *)
+
+val of_list : 'a list -> 'a array
+(** [ArrayLabels.of_list l] returns a fresh array containing the elements
+ of [l]. *)
+
+val iter : f:('a -> unit) -> 'a array -> unit
+(** [ArrayLabels.iter f a] applies function [f] in turn to all
+ the elements of [a]. It is equivalent to
+ [f a.(0); f a.(1); ...; f a.(ArrayLabels.length a - 1); ()]. *)
+
+val map : f:('a -> 'b) -> 'a array -> 'b array
+(** [ArrayLabels.map f a] applies function [f] to all the elements of [a],
+ and builds an array with the results returned by [f]:
+ [[| f a.(0); f a.(1); ...; f a.(ArrayLabels.length a - 1) |]]. *)
+
+val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
+(** Same as {!ArrayLabels.iter}, but the
+ function is applied to the index of the element as first argument,
+ and the element itself as second argument. *)
+
+val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array
+(** Same as {!ArrayLabels.map}, but the
+ function is applied to the index of the element as first argument,
+ and the element itself as second argument. *)
+
+val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b array -> 'a
+(** [ArrayLabels.fold_left f x a] computes
+ [f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)],
+ where [n] is the length of the array [a]. *)
+
+val fold_right : f:('b -> 'a -> 'a) -> 'b array -> init:'a -> 'a
+(** [ArrayLabels.fold_right f a x] computes
+ [f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))],
+ where [n] is the length of the array [a]. *)
+
+external create_float: int -> float array = "caml_make_float_vect"
+(** [ArrayLabels.create_float n] returns a fresh float array of length [n],
+ with uninitialized data.
+ @since 4.03 *)
+
+val make_float: int -> float array
+ [@@ocaml.deprecated "Use ArrayLabels.create_float instead."]
+(** @deprecated [ArrayLabels.make_float] is an alias for
+ {!ArrayLabels.create_float}. *)
+
+
+(** {6 Sorting} *)
+
+
+val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
+(** Sort an array in increasing order according to a comparison
+ function. The comparison function must return 0 if its arguments
+ compare as equal, a positive integer if the first is greater,
+ and a negative integer if the first is smaller (see below for a
+ complete specification). For example, {!Pervasives.compare} is
+ a suitable comparison function, provided there are no floating-point
+ NaN values in the data. After calling [ArrayLabels.sort], the
+ array is sorted in place in increasing order.
+ [ArrayLabels.sort] is guaranteed to run in constant heap space
+ and (at most) logarithmic stack space.
+
+ The current implementation uses Heap Sort. It runs in constant
+ stack space.
+
+ Specification of the comparison function:
+ Let [a] be the array and [cmp] the comparison function. The following
+ must be true for all x, y, z in a :
+- [cmp x y] > 0 if and only if [cmp y x] < 0
+- if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0
+
+ When [ArrayLabels.sort] returns, [a] contains the same elements as before,
+ reordered in such a way that for all i and j valid indices of [a] :
+- [cmp a.(i) a.(j)] >= 0 if and only if i >= j
+*)
+
+val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
+(** Same as {!ArrayLabels.sort}, but the sorting algorithm is stable (i.e.
+ elements that compare equal are kept in their original order) and
+ not guaranteed to run in constant heap space.
+
+ The current implementation uses Merge Sort. It uses [n/2]
+ words of heap space, where [n] is the length of the array.
+ It is usually faster than the current implementation of {!ArrayLabels.sort}.
+*)
+
+val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
+(** Same as {!ArrayLabels.sort} or {!ArrayLabels.stable_sort}, whichever is
+ faster on typical input.
+*)
+
+
+(**/**)
+
+(** {6 Undocumented functions} *)
+
+(* The following is for system use only. Do not call directly. *)
+
+external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
+external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
diff --git a/stdlib/buffer.ml b/stdlib/buffer.ml
new file mode 100644
index 0000000000..93a25cb09d
--- /dev/null
+++ b/stdlib/buffer.ml
@@ -0,0 +1,188 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis and Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Extensible buffers *)
+
+type t =
+ {mutable buffer : bytes;
+ mutable position : int;
+ mutable length : int;
+ initial_buffer : bytes}
+
+let create n =
+ let n = if n < 1 then 1 else n in
+ let n = if n > Sys.max_string_length then Sys.max_string_length else n in
+ let s = Bytes.create n in
+ {buffer = s; position = 0; length = n; initial_buffer = s}
+
+let contents b = Bytes.sub_string b.buffer 0 b.position
+let to_bytes b = Bytes.sub b.buffer 0 b.position
+
+let sub b ofs len =
+ if ofs < 0 || len < 0 || ofs > b.position - len
+ then invalid_arg "Buffer.sub"
+ else Bytes.sub_string b.buffer ofs len
+;;
+
+let blit src srcoff dst dstoff len =
+ if len < 0 || srcoff < 0 || srcoff > src.position - len
+ || dstoff < 0 || dstoff > (Bytes.length dst) - len
+ then invalid_arg "Buffer.blit"
+ else
+ Bytes.unsafe_blit src.buffer srcoff dst dstoff len
+;;
+
+let nth b ofs =
+ if ofs < 0 || ofs >= b.position then
+ invalid_arg "Buffer.nth"
+ else Bytes.unsafe_get b.buffer ofs
+;;
+
+let length b = b.position
+
+let clear b = b.position <- 0
+
+let reset b =
+ b.position <- 0; b.buffer <- b.initial_buffer;
+ b.length <- Bytes.length b.buffer
+
+let resize b more =
+ let len = b.length in
+ let new_len = ref len in
+ while b.position + more > !new_len do new_len := 2 * !new_len done;
+ if !new_len > Sys.max_string_length then begin
+ if b.position + more <= Sys.max_string_length
+ then new_len := Sys.max_string_length
+ else failwith "Buffer.add: cannot grow buffer"
+ end;
+ let new_buffer = Bytes.create !new_len in
+ (* PR#6148: let's keep using [blit] rather than [unsafe_blit] in
+ this tricky function that is slow anyway. *)
+ Bytes.blit b.buffer 0 new_buffer 0 b.position;
+ b.buffer <- new_buffer;
+ b.length <- !new_len
+
+let add_char b c =
+ let pos = b.position in
+ if pos >= b.length then resize b 1;
+ Bytes.unsafe_set b.buffer pos c;
+ b.position <- pos + 1
+
+let add_substring b s offset len =
+ if offset < 0 || len < 0 || offset + len > String.length s
+ then invalid_arg "Buffer.add_substring/add_subbytes";
+ let new_position = b.position + len in
+ if new_position > b.length then resize b len;
+ Bytes.blit_string s offset b.buffer b.position len;
+ b.position <- new_position
+
+let add_subbytes b s offset len =
+ add_substring b (Bytes.unsafe_to_string s) offset len
+
+let add_string b s =
+ let len = String.length s in
+ let new_position = b.position + len in
+ if new_position > b.length then resize b len;
+ Bytes.blit_string s 0 b.buffer b.position len;
+ b.position <- new_position
+
+let add_bytes b s = add_string b (Bytes.unsafe_to_string s)
+
+let add_buffer b bs =
+ add_subbytes b bs.buffer 0 bs.position
+
+(* read up to [len] bytes from [ic] into [b]. *)
+let rec add_channel_rec b ic len =
+ if len > 0 then (
+ let n = input ic b.buffer b.position len in
+ b.position <- b.position + n;
+ if n = 0 then raise End_of_file
+ else add_channel_rec b ic (len-n) (* n <= len *)
+ )
+
+let add_channel b ic len =
+ if len < 0 || len > Sys.max_string_length then (* PR#5004 *)
+ invalid_arg "Buffer.add_channel";
+ if b.position + len > b.length then resize b len;
+ add_channel_rec b ic len
+
+let output_buffer oc b =
+ output oc b.buffer 0 b.position
+
+let closing = function
+ | '(' -> ')'
+ | '{' -> '}'
+ | _ -> assert false;;
+
+(* opening and closing: open and close characters, typically ( and )
+ k: balance of opening and closing chars
+ s: the string where we are searching
+ start: the index where we start the search. *)
+let advance_to_closing opening closing k s start =
+ let rec advance k i lim =
+ if i >= lim then raise Not_found else
+ if s.[i] = opening then advance (k + 1) (i + 1) lim else
+ if s.[i] = closing then
+ if k = 0 then i else advance (k - 1) (i + 1) lim
+ else advance k (i + 1) lim in
+ advance k start (String.length s);;
+
+let advance_to_non_alpha s start =
+ let rec advance i lim =
+ if i >= lim then lim else
+ match s.[i] with
+ | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' -> advance (i + 1) lim
+ | _ -> i in
+ advance start (String.length s);;
+
+(* We are just at the beginning of an ident in s, starting at start. *)
+let find_ident s start lim =
+ if start >= lim then raise Not_found else
+ match s.[start] with
+ (* Parenthesized ident ? *)
+ | '(' | '{' as c ->
+ let new_start = start + 1 in
+ let stop = advance_to_closing c (closing c) 0 s new_start in
+ String.sub s new_start (stop - start - 1), stop + 1
+ (* Regular ident *)
+ | _ ->
+ let stop = advance_to_non_alpha s (start + 1) in
+ String.sub s start (stop - start), stop;;
+
+(* Substitute $ident, $(ident), or ${ident} in s,
+ according to the function mapping f. *)
+let add_substitute b f s =
+ let lim = String.length s in
+ let rec subst previous i =
+ if i < lim then begin
+ match s.[i] with
+ | '$' as current when previous = '\\' ->
+ add_char b current;
+ subst ' ' (i + 1)
+ | '$' ->
+ let j = i + 1 in
+ let ident, next_i = find_ident s j lim in
+ add_string b (f ident);
+ subst ' ' next_i
+ | current when previous == '\\' ->
+ add_char b '\\';
+ add_char b current;
+ subst ' ' (i + 1)
+ | '\\' as current ->
+ subst current (i + 1)
+ | current ->
+ add_char b current;
+ subst current (i + 1)
+ end else
+ if previous = '\\' then add_char b previous in
+ subst ' ' 0;;
diff --git a/stdlib/buffer.mli b/stdlib/buffer.mli
new file mode 100644
index 0000000000..22684f7f21
--- /dev/null
+++ b/stdlib/buffer.mli
@@ -0,0 +1,131 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis and Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Extensible buffers.
+
+ This module implements buffers that automatically expand
+ as necessary. It provides accumulative concatenation of strings
+ in quasi-linear time (instead of quadratic time when strings are
+ concatenated pairwise).
+*)
+
+type t
+(** The abstract type of buffers. *)
+
+val create : int -> t
+(** [create n] returns a fresh buffer, initially empty.
+ The [n] parameter is the initial size of the internal byte sequence
+ that holds the buffer contents. That byte sequence is automatically
+ reallocated when more than [n] characters are stored in the buffer,
+ but shrinks back to [n] characters when [reset] is called.
+ For best performance, [n] should be of the same order of magnitude
+ as the number of characters that are expected to be stored in
+ the buffer (for instance, 80 for a buffer that holds one output
+ line). Nothing bad will happen if the buffer grows beyond that
+ limit, however. In doubt, take [n = 16] for instance.
+ If [n] is not between 1 and {!Sys.max_string_length}, it will
+ be clipped to that interval. *)
+
+val contents : t -> string
+(** Return a copy of the current contents of the buffer.
+ The buffer itself is unchanged. *)
+
+val to_bytes : t -> bytes
+(** Return a copy of the current contents of the buffer.
+ The buffer itself is unchanged.
+ @since 4.02 *)
+
+val sub : t -> int -> int -> string
+(** [Buffer.sub b off len] returns a copy of [len] bytes from the
+ current contents of the buffer [b], starting at offset [off].
+
+ Raise [Invalid_argument] if [srcoff] and [len] do not designate a valid
+ range of [b]. *)
+
+val blit : t -> int -> bytes -> int -> int -> unit
+(** [Buffer.blit src srcoff dst dstoff len] copies [len] characters from
+ the current contents of the buffer [src], starting at offset [srcoff]
+ to [dst], starting at character [dstoff].
+
+ Raise [Invalid_argument] if [srcoff] and [len] do not designate a valid
+ range of [src], or if [dstoff] and [len] do not designate a valid
+ range of [dst].
+ @since 3.11.2
+*)
+
+val nth : t -> int -> char
+(** Get the n-th character of the buffer. Raise [Invalid_argument] if
+ index out of bounds *)
+
+val length : t -> int
+(** Return the number of characters currently contained in the buffer. *)
+
+val clear : t -> unit
+(** Empty the buffer. *)
+
+val reset : t -> unit
+(** Empty the buffer and deallocate the internal byte sequence holding the
+ buffer contents, replacing it with the initial internal byte sequence
+ of length [n] that was allocated by {!Buffer.create} [n].
+ For long-lived buffers that may have grown a lot, [reset] allows
+ faster reclamation of the space used by the buffer. *)
+
+val add_char : t -> char -> unit
+(** [add_char b c] appends the character [c] at the end of buffer [b]. *)
+
+val add_string : t -> string -> unit
+(** [add_string b s] appends the string [s] at the end of buffer [b]. *)
+
+val add_bytes : t -> bytes -> unit
+(** [add_bytes b s] appends the byte sequence [s] at the end of buffer [b].
+ @since 4.02 *)
+
+val add_substring : t -> string -> int -> int -> unit
+(** [add_substring b s ofs len] takes [len] characters from offset
+ [ofs] in string [s] and appends them at the end of buffer [b]. *)
+
+val add_subbytes : t -> bytes -> int -> int -> unit
+(** [add_subbytes b s ofs len] takes [len] characters from offset
+ [ofs] in byte sequence [s] and appends them at the end of buffer [b].
+ @since 4.02 *)
+
+val add_substitute : t -> (string -> string) -> string -> unit
+(** [add_substitute b f s] appends the string pattern [s] at the end
+ of buffer [b] with substitution.
+ The substitution process looks for variables into
+ the pattern and substitutes each variable name by its value, as
+ obtained by applying the mapping [f] to the variable name. Inside the
+ string pattern, a variable name immediately follows a non-escaped
+ [$] character and is one of the following:
+ - a non empty sequence of alphanumeric or [_] characters,
+ - an arbitrary sequence of characters enclosed by a pair of
+ matching parentheses or curly brackets.
+ An escaped [$] character is a [$] that immediately follows a backslash
+ character; it then stands for a plain [$].
+ Raise [Not_found] if the closing character of a parenthesized variable
+ cannot be found. *)
+
+val add_buffer : t -> t -> unit
+(** [add_buffer b1 b2] appends the current contents of buffer [b2]
+ at the end of buffer [b1]. [b2] is not modified. *)
+
+val add_channel : t -> in_channel -> int -> unit
+(** [add_channel b ic n] reads at most [n] characters from the
+ input channel [ic] and stores them at the end of buffer [b].
+ Raise [End_of_file] if the channel contains fewer than [n]
+ characters. In this case, the characters are still added to
+ the buffer, so as to avoid loss of data. *)
+
+val output_buffer : out_channel -> t -> unit
+(** [output_buffer oc b] writes the current contents of buffer [b]
+ on the output channel [oc]. *)
diff --git a/stdlib/bytes.ml b/stdlib/bytes.ml
new file mode 100644
index 0000000000..6997a78bd0
--- /dev/null
+++ b/stdlib/bytes.ml
@@ -0,0 +1,268 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Byte sequence operations *)
+
+external length : bytes -> int = "%string_length"
+external string_length : string -> int = "%string_length"
+external get : bytes -> int -> char = "%string_safe_get"
+external set : bytes -> int -> char -> unit = "%string_safe_set"
+external create : int -> bytes = "caml_create_string"
+external unsafe_get : bytes -> int -> char = "%string_unsafe_get"
+external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
+external unsafe_fill : bytes -> int -> int -> char -> unit
+ = "caml_fill_string" "noalloc"
+external unsafe_to_string : bytes -> string = "%identity"
+external unsafe_of_string : string -> bytes = "%identity"
+
+external unsafe_blit : bytes -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+external unsafe_blit_string : string -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+
+let make n c =
+ let s = create n in
+ unsafe_fill s 0 n c;
+ s
+
+let init n f =
+ let s = create n in
+ for i = 0 to n - 1 do
+ unsafe_set s i (f i)
+ done;
+ s
+
+let empty = create 0;;
+
+let copy s =
+ let len = length s in
+ let r = create len in
+ unsafe_blit s 0 r 0 len;
+ r
+
+let to_string b = unsafe_to_string (copy b)
+let of_string s = copy (unsafe_of_string s)
+
+let sub s ofs len =
+ if ofs < 0 || len < 0 || ofs > length s - len
+ then invalid_arg "String.sub / Bytes.sub"
+ else begin
+ let r = create len in
+ unsafe_blit s ofs r 0 len;
+ r
+ end
+
+let sub_string b ofs len = unsafe_to_string (sub b ofs len)
+
+let extend s left right =
+ let len = length s + left + right in
+ let r = create len in
+ let (srcoff, dstoff) = if left < 0 then -left, 0 else 0, left in
+ let cpylen = min (length s - srcoff) (len - dstoff) in
+ if cpylen > 0 then unsafe_blit s srcoff r dstoff cpylen;
+ r
+
+let fill s ofs len c =
+ if ofs < 0 || len < 0 || ofs > length s - len
+ then invalid_arg "String.fill / Bytes.fill"
+ else unsafe_fill s ofs len c
+
+let blit s1 ofs1 s2 ofs2 len =
+ if len < 0 || ofs1 < 0 || ofs1 > length s1 - len
+ || ofs2 < 0 || ofs2 > length s2 - len
+ then invalid_arg "Bytes.blit"
+ else unsafe_blit s1 ofs1 s2 ofs2 len
+
+let blit_string s1 ofs1 s2 ofs2 len =
+ if len < 0 || ofs1 < 0 || ofs1 > string_length s1 - len
+ || ofs2 < 0 || ofs2 > length s2 - len
+ then invalid_arg "String.blit / Bytes.blit_string"
+ else unsafe_blit_string s1 ofs1 s2 ofs2 len
+
+let iter f a =
+ for i = 0 to length a - 1 do f(unsafe_get a i) done
+
+let iteri f a =
+ for i = 0 to length a - 1 do f i (unsafe_get a i) done
+
+let concat sep l =
+ match l with
+ [] -> empty
+ | hd :: tl ->
+ let num = ref 0 and len = ref 0 in
+ List.iter (fun s -> incr num; len := !len + length s) l;
+ let r = create (!len + length sep * (!num - 1)) in
+ unsafe_blit hd 0 r 0 (length hd);
+ let pos = ref(length hd) in
+ List.iter
+ (fun s ->
+ unsafe_blit sep 0 r !pos (length sep);
+ pos := !pos + length sep;
+ unsafe_blit s 0 r !pos (length s);
+ pos := !pos + length s)
+ tl;
+ r
+
+let cat s1 s2 =
+ let l1 = length s1 in
+ let l2 = length s2 in
+ let r = create (l1 + l2) in
+ unsafe_blit s1 0 r 0 l1;
+ unsafe_blit s2 0 r l1 l2;
+ r
+;;
+
+external char_code: char -> int = "%identity"
+external char_chr: int -> char = "%identity"
+
+let is_space = function
+ | ' ' | '\012' | '\n' | '\r' | '\t' -> true
+ | _ -> false
+
+let trim s =
+ let len = length s in
+ let i = ref 0 in
+ while !i < len && is_space (unsafe_get s !i) do
+ incr i
+ done;
+ let j = ref (len - 1) in
+ while !j >= !i && is_space (unsafe_get s !j) do
+ decr j
+ done;
+ if !j >= !i then
+ sub s !i (!j - !i + 1)
+ else
+ empty
+
+let escaped s =
+ let n = ref 0 in
+ for i = 0 to length s - 1 do
+ n := !n +
+ (match unsafe_get s i with
+ | '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> 2
+ | ' ' .. '~' -> 1
+ | _ -> 4)
+ done;
+ if !n = length s then copy s else begin
+ let s' = create !n in
+ n := 0;
+ for i = 0 to length s - 1 do
+ begin match unsafe_get s i with
+ | ('\"' | '\\') as c ->
+ unsafe_set s' !n '\\'; incr n; unsafe_set s' !n c
+ | '\n' ->
+ unsafe_set s' !n '\\'; incr n; unsafe_set s' !n 'n'
+ | '\t' ->
+ unsafe_set s' !n '\\'; incr n; unsafe_set s' !n 't'
+ | '\r' ->
+ unsafe_set s' !n '\\'; incr n; unsafe_set s' !n 'r'
+ | '\b' ->
+ unsafe_set s' !n '\\'; incr n; unsafe_set s' !n 'b'
+ | (' ' .. '~') as c -> unsafe_set s' !n c
+ | c ->
+ let a = char_code c in
+ unsafe_set s' !n '\\';
+ incr n;
+ unsafe_set s' !n (char_chr (48 + a / 100));
+ incr n;
+ unsafe_set s' !n (char_chr (48 + (a / 10) mod 10));
+ incr n;
+ unsafe_set s' !n (char_chr (48 + a mod 10));
+ end;
+ incr n
+ done;
+ s'
+ end
+
+let map f s =
+ let l = length s in
+ if l = 0 then s else begin
+ let r = create l in
+ for i = 0 to l - 1 do unsafe_set r i (f (unsafe_get s i)) done;
+ r
+ end
+
+let mapi f s =
+ let l = length s in
+ if l = 0 then s else begin
+ let r = create l in
+ for i = 0 to l - 1 do unsafe_set r i (f i (unsafe_get s i)) done;
+ r
+ end
+
+let uppercase_ascii s = map Char.uppercase_ascii s
+let lowercase_ascii s = map Char.lowercase_ascii s
+
+let apply1 f s =
+ if length s = 0 then s else begin
+ let r = copy s in
+ unsafe_set r 0 (f(unsafe_get s 0));
+ r
+ end
+
+let capitalize_ascii s = apply1 Char.uppercase_ascii s
+let uncapitalize_ascii s = apply1 Char.lowercase_ascii s
+
+let rec index_rec s lim i c =
+ if i >= lim then raise Not_found else
+ if unsafe_get s i = c then i else index_rec s lim (i + 1) c;;
+
+let index s c = index_rec s (length s) 0 c;;
+
+let index_from s i c =
+ let l = length s in
+ if i < 0 || i > l then invalid_arg "String.index_from / Bytes.index_from" else
+ index_rec s l i c;;
+
+let rec rindex_rec s i c =
+ if i < 0 then raise Not_found else
+ if unsafe_get s i = c then i else rindex_rec s (i - 1) c;;
+
+let rindex s c = rindex_rec s (length s - 1) c;;
+
+let rindex_from s i c =
+ if i < -1 || i >= length s then
+ invalid_arg "String.rindex_from / Bytes.rindex_from"
+ else
+ rindex_rec s i c
+;;
+
+let contains_from s i c =
+ let l = length s in
+ if i < 0 || i > l then
+ invalid_arg "String.contains_from / Bytes.contains_from"
+ else
+ try ignore (index_rec s l i c); true with Not_found -> false
+;;
+
+let contains s c = contains_from s 0 c;;
+
+let rcontains_from s i c =
+ if i < 0 || i >= length s then
+ invalid_arg "String.rcontains_from / Bytes.rcontains_from"
+ else
+ try ignore (rindex_rec s i c); true with Not_found -> false
+;;
+
+type t = bytes
+
+let compare (x: t) (y: t) = Pervasives.compare x y
+external equal : t -> t -> bool = "caml_string_equal"
+
+(* Deprecated functions implemented via other deprecated functions *)
+[@@@ocaml.warning "-3"]
+let uppercase s = map Char.uppercase s
+let lowercase s = map Char.lowercase s
+
+let capitalize s = apply1 Char.uppercase s
+let uncapitalize s = apply1 Char.lowercase s
diff --git a/stdlib/bytes.mli b/stdlib/bytes.mli
new file mode 100644
index 0000000000..621c619f78
--- /dev/null
+++ b/stdlib/bytes.mli
@@ -0,0 +1,431 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Byte sequence operations.
+
+ A byte sequence is a mutable data structure that contains a
+ fixed-length sequence of bytes. Each byte can be indexed in
+ constant time for reading or writing.
+
+ Given a byte sequence [s] of length [l], we can access each of the
+ [l] bytes of [s] via its index in the sequence. Indexes start at
+ [0], and we will call an index valid in [s] if it falls within the
+ range [[0...l-1]] (inclusive). A position is the point between two
+ bytes or at the beginning or end of the sequence. We call a
+ position valid in [s] if it falls within the range [[0...l]]
+ (inclusive). Note that the byte at index [n] is between positions
+ [n] and [n+1].
+
+ Two parameters [start] and [len] are said to designate a valid
+ range of [s] if [len >= 0] and [start] and [start+len] are valid
+ positions in [s].
+
+ Byte sequences can be modified in place, for instance via the [set]
+ and [blit] functions described below. See also strings (module
+ {!String}), which are almost the same data structure, but cannot be
+ modified in place.
+
+ Bytes are represented by the OCaml type [char].
+
+ @since 4.02.0
+ *)
+
+external length : bytes -> int = "%string_length"
+(** Return the length (number of bytes) of the argument. *)
+
+external get : bytes -> int -> char = "%string_safe_get"
+(** [get s n] returns the byte at index [n] in argument [s].
+
+ Raise [Invalid_argument] if [n] not a valid index in [s]. *)
+
+external set : bytes -> int -> char -> unit = "%string_safe_set"
+(** [set s n c] modifies [s] in place, replacing the byte at index [n]
+ with [c].
+
+ Raise [Invalid_argument] if [n] is not a valid index in [s]. *)
+
+external create : int -> bytes = "caml_create_string"
+(** [create n] returns a new byte sequence of length [n]. The
+ sequence is uninitialized and contains arbitrary bytes.
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val make : int -> char -> bytes
+(** [make n c] returns a new byte sequence of length [n], filled with
+ the byte [c].
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val init : int -> (int -> char) -> bytes
+(** [Bytes.init n f] returns a fresh byte sequence of length [n], with
+ character [i] initialized to the result of [f i] (in increasing
+ index order).
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val empty : bytes
+(** A byte sequence of size 0. *)
+
+val copy : bytes -> bytes
+(** Return a new byte sequence that contains the same bytes as the
+ argument. *)
+
+val of_string : string -> bytes
+(** Return a new byte sequence that contains the same bytes as the
+ given string. *)
+
+val to_string : bytes -> string
+(** Return a new string that contains the same bytes as the given byte
+ sequence. *)
+
+val sub : bytes -> int -> int -> bytes
+(** [sub s start len] returns a new byte sequence of length [len],
+ containing the subsequence of [s] that starts at position [start]
+ and has length [len].
+
+ Raise [Invalid_argument] if [start] and [len] do not designate a
+ valid range of [s]. *)
+
+val sub_string : bytes -> int -> int -> string
+(** Same as [sub] but return a string instead of a byte sequence. *)
+
+val extend : bytes -> int -> int -> bytes
+(** [extend s left right] returns a new byte sequence that contains
+ the bytes of [s], with [left] uninitialized bytes prepended and
+ [right] uninitialized bytes appended to it. If [left] or [right]
+ is negative, then bytes are removed (instead of appended) from
+ the corresponding side of [s].
+
+ Raise [Invalid_argument] if the result length is negative or
+ longer than {!Sys.max_string_length} bytes. *)
+
+val fill : bytes -> int -> int -> char -> unit
+(** [fill s start len c] modifies [s] in place, replacing [len]
+ characters with [c], starting at [start].
+
+ Raise [Invalid_argument] if [start] and [len] do not designate a
+ valid range of [s]. *)
+
+val blit : bytes -> int -> bytes -> int -> int -> unit
+(** [blit src srcoff dst dstoff len] copies [len] bytes from sequence
+ [src], starting at index [srcoff], to sequence [dst], starting at
+ index [dstoff]. It works correctly even if [src] and [dst] are the
+ same byte sequence, and the source and destination intervals
+ overlap.
+
+ Raise [Invalid_argument] if [srcoff] and [len] do not
+ designate a valid range of [src], or if [dstoff] and [len]
+ do not designate a valid range of [dst]. *)
+
+val blit_string : string -> int -> bytes -> int -> int -> unit
+(** [blit src srcoff dst dstoff len] copies [len] bytes from string
+ [src], starting at index [srcoff], to byte sequence [dst],
+ starting at index [dstoff].
+
+ Raise [Invalid_argument] if [srcoff] and [len] do not
+ designate a valid range of [src], or if [dstoff] and [len]
+ do not designate a valid range of [dst]. *)
+
+val concat : bytes -> bytes list -> bytes
+(** [concat sep sl] concatenates the list of byte sequences [sl],
+ inserting the separator byte sequence [sep] between each, and
+ returns the result as a new byte sequence.
+
+ Raise [Invalid_argument] if the result is longer than
+ {!Sys.max_string_length} bytes. *)
+
+val cat : bytes -> bytes -> bytes
+(** [cat s1 s2] concatenates [s1] and [s2] and returns the result
+ as new byte sequence.
+
+ Raise [Invalid_argument] if the result is longer than
+ {!Sys.max_string_length} bytes. *)
+
+val iter : (char -> unit) -> bytes -> unit
+(** [iter f s] applies function [f] in turn to all the bytes of [s].
+ It is equivalent to [f (get s 0); f (get s 1); ...; f (get s
+ (length s - 1)); ()]. *)
+
+val iteri : (int -> char -> unit) -> bytes -> unit
+(** Same as {!Bytes.iter}, but the function is applied to the index of
+ the byte as first argument and the byte itself as second
+ argument. *)
+
+val map : (char -> char) -> bytes -> bytes
+(** [map f s] applies function [f] in turn to all the bytes of [s]
+ (in increasing index order) and stores the resulting bytes in
+ a new sequence that is returned as the result. *)
+
+val mapi : (int -> char -> char) -> bytes -> bytes
+(** [mapi f s] calls [f] with each character of [s] and its
+ index (in increasing index order) and stores the resulting bytes
+ in a new sequence that is returned as the result. *)
+
+val trim : bytes -> bytes
+(** Return a copy of the argument, without leading and trailing
+ whitespace. The bytes regarded as whitespace are the ASCII
+ characters [' '], ['\012'], ['\n'], ['\r'], and ['\t']. *)
+
+val escaped : bytes -> bytes
+(** Return a copy of the argument, with special characters represented
+ by escape sequences, following the lexical conventions of OCaml.
+ All characters outside the ASCII printable range (32..126) are
+ escaped, as well as backslash and double-quote.
+
+ Raise [Invalid_argument] if the result is longer than
+ {!Sys.max_string_length} bytes. *)
+
+val index : bytes -> char -> int
+(** [index s c] returns the index of the first occurrence of byte [c]
+ in [s].
+
+ Raise [Not_found] if [c] does not occur in [s]. *)
+
+val rindex : bytes -> char -> int
+(** [rindex s c] returns the index of the last occurrence of byte [c]
+ in [s].
+
+ Raise [Not_found] if [c] does not occur in [s]. *)
+
+val index_from : bytes -> int -> char -> int
+(** [index_from s i c] returns the index of the first occurrence of
+ byte [c] in [s] after position [i]. [Bytes.index s c] is
+ equivalent to [Bytes.index_from s 0 c].
+
+ Raise [Invalid_argument] if [i] is not a valid position in [s].
+ Raise [Not_found] if [c] does not occur in [s] after position [i]. *)
+
+val rindex_from : bytes -> int -> char -> int
+(** [rindex_from s i c] returns the index of the last occurrence of
+ byte [c] in [s] before position [i+1]. [rindex s c] is equivalent
+ to [rindex_from s (Bytes.length s - 1) c].
+
+ Raise [Invalid_argument] if [i+1] is not a valid position in [s].
+ Raise [Not_found] if [c] does not occur in [s] before position [i+1]. *)
+
+val contains : bytes -> char -> bool
+(** [contains s c] tests if byte [c] appears in [s]. *)
+
+val contains_from : bytes -> int -> char -> bool
+(** [contains_from s start c] tests if byte [c] appears in [s] after
+ position [start]. [contains s c] is equivalent to [contains_from
+ s 0 c].
+
+ Raise [Invalid_argument] if [start] is not a valid position in [s]. *)
+
+val rcontains_from : bytes -> int -> char -> bool
+(** [rcontains_from s stop c] tests if byte [c] appears in [s] before
+ position [stop+1].
+
+ Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid
+ position in [s]. *)
+
+val uppercase : bytes -> bytes
+ [@@ocaml.deprecated "Use Bytes.uppercase_ascii instead."]
+(** Return a copy of the argument, with all lowercase letters
+ translated to uppercase, including accented letters of the ISO
+ Latin-1 (8859-1) character set.
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val lowercase : bytes -> bytes
+ [@@ocaml.deprecated "Use Bytes.lowercase_ascii instead."]
+(** Return a copy of the argument, with all uppercase letters
+ translated to lowercase, including accented letters of the ISO
+ Latin-1 (8859-1) character set.
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val capitalize : bytes -> bytes
+ [@@ocaml.deprecated "Use Bytes.capitalize_ascii instead."]
+(** Return a copy of the argument, with the first character set to uppercase,
+ using the ISO Latin-1 (8859-1) character set..
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val uncapitalize : bytes -> bytes
+ [@@ocaml.deprecated "Use Bytes.uncapitalize_ascii instead."]
+(** Return a copy of the argument, with the first character set to lowercase,
+ using the ISO Latin-1 (8859-1) character set..
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val uppercase_ascii : bytes -> bytes
+(** Return a copy of the argument, with all lowercase letters
+ translated to uppercase, using the US-ASCII character set.
+ @since 4.03.0 *)
+
+val lowercase_ascii : bytes -> bytes
+(** Return a copy of the argument, with all uppercase letters
+ translated to lowercase, using the US-ASCII character set.
+ @since 4.03.0 *)
+
+val capitalize_ascii : bytes -> bytes
+(** Return a copy of the argument, with the first character set to uppercase,
+ using the US-ASCII character set.
+ @since 4.03.0 *)
+
+val uncapitalize_ascii : bytes -> bytes
+(** Return a copy of the argument, with the first character set to lowercase,
+ using the US-ASCII character set.
+ @since 4.03.0 *)
+
+type t = bytes
+(** An alias for the type of byte sequences. *)
+
+val compare: t -> t -> int
+(** The comparison function for byte sequences, with the same
+ specification as {!Pervasives.compare}. Along with the type [t],
+ this function [compare] allows the module [Bytes] to be passed as
+ argument to the functors {!Set.Make} and {!Map.Make}. *)
+
+val equal: t -> t -> bool
+(** The equality function for byte sequences.
+ @since 4.03.0 *)
+
+(** {4 Unsafe conversions (for advanced users)}
+
+ This section describes unsafe, low-level conversion functions
+ between [bytes] and [string]. They do not copy the internal data;
+ used improperly, they can break the immutability invariant on
+ strings provided by the [-safe-string] option. They are available for
+ expert library authors, but for most purposes you should use the
+ always-correct {!Bytes.to_string} and {!Bytes.of_string} instead.
+*)
+
+val unsafe_to_string : bytes -> string
+(** Unsafely convert a byte sequence into a string.
+
+ To reason about the use of [unsafe_to_string], it is convenient to
+ consider an "ownership" discipline. A piece of code that
+ manipulates some data "owns" it; there are several disjoint ownership
+ modes, including:
+ - Unique ownership: the data may be accessed and mutated
+ - Shared ownership: the data has several owners, that may only
+ access it, not mutate it.
+
+ Unique ownership is linear: passing the data to another piece of
+ code means giving up ownership (we cannot write the
+ data again). A unique owner may decide to make the data shared
+ (giving up mutation rights on it), but shared data may not become
+ uniquely-owned again.
+
+ [unsafe_to_string s] can only be used when the caller owns the byte
+ sequence [s] -- either uniquely or as shared immutable data. The
+ caller gives up ownership of [s], and gains ownership of the
+ returned string.
+
+ There are two valid use-cases that respect this ownership
+ discipline:
+
+ 1. Creating a string by initializing and mutating a byte sequence
+ that is never changed after initialization is performed.
+
+ {[
+let string_init len f : string =
+ let s = Bytes.create len in
+ for i = 0 to len - 1 do Bytes.set s i (f i) done;
+ Bytes.unsafe_to_string s
+ ]}
+
+ This function is safe because the byte sequence [s] will never be
+ accessed or mutated after [unsafe_to_string] is called. The
+ [string_init] code gives up ownership of [s], and returns the
+ ownership of the resulting string to its caller.
+
+ Note that it would be unsafe if [s] was passed as an additional
+ parameter to the function [f] as it could escape this way and be
+ mutated in the future -- [string_init] would give up ownership of
+ [s] to pass it to [f], and could not call [unsafe_to_string]
+ safely.
+
+ We have provided the {!String.init}, {!String.map} and
+ {!String.mapi} functions to cover most cases of building
+ new strings. You should prefer those over [to_string] or
+ [unsafe_to_string] whenever applicable.
+
+ 2. Temporarily giving ownership of a byte sequence to a function
+ that expects a uniquely owned string and returns ownership back, so
+ that we can mutate the sequence again after the call ended.
+
+ {[
+let bytes_length (s : bytes) =
+ String.length (Bytes.unsafe_to_string s)
+ ]}
+
+ In this use-case, we do not promise that [s] will never be mutated
+ after the call to [bytes_length s]. The {!String.length} function
+ temporarily borrows unique ownership of the byte sequence
+ (and sees it as a [string]), but returns this ownership back to
+ the caller, which may assume that [s] is still a valid byte
+ sequence after the call. Note that this is only correct because we
+ know that {!String.length} does not capture its argument -- it could
+ escape by a side-channel such as a memoization combinator.
+
+ The caller may not mutate [s] while the string is borrowed (it has
+ temporarily given up ownership). This affects concurrent programs,
+ but also higher-order functions: if [String.length] returned
+ a closure to be called later, [s] should not be mutated until this
+ closure is fully applied and returns ownership.
+*)
+
+val unsafe_of_string : string -> bytes
+(** Unsafely convert a shared string to a byte sequence that should
+ not be mutated.
+
+ The same ownership discipline that makes [unsafe_to_string]
+ correct applies to [unsafe_of_string]: you may use it if you were
+ the owner of the [string] value, and you will own the return
+ [bytes] in the same mode.
+
+ In practice, unique ownership of string values is extremely
+ difficult to reason about correctly. You should always assume
+ strings are shared, never uniquely owned.
+
+ For example, string literals are implicitly shared by the
+ compiler, so you never uniquely own them.
+
+ {[
+let incorrect = Bytes.unsafe_of_string "hello"
+let s = Bytes.of_string "hello"
+ ]}
+
+ The first declaration is incorrect, because the string literal
+ ["hello"] could be shared by the compiler with other parts of the
+ program, and mutating [incorrect] is a bug. You must always use
+ the second version, which performs a copy and is thus correct.
+
+ Assuming unique ownership of strings that are not string
+ literals, but are (partly) built from string literals, is also
+ incorrect. For example, mutating [unsafe_of_string ("foo" ^ s)]
+ could mutate the shared string ["foo"] -- assuming a rope-like
+ representation of strings. More generally, functions operating on
+ strings will assume shared ownership, they do not preserve unique
+ ownership. It is thus incorrect to assume unique ownership of the
+ result of [unsafe_of_string].
+
+ The only case we have reasonable confidence is safe is if the
+ produced [bytes] is shared -- used as an immutable byte
+ sequence. This is possibly useful for incremental migration of
+ low-level programs that manipulate immutable sequences of bytes
+ (for example {!Marshal.from_bytes}) and previously used the
+ [string] type for this purpose.
+*)
+
+(**/**)
+
+(* The following is for system use only. Do not call directly. *)
+
+external unsafe_get : bytes -> int -> char = "%string_unsafe_get"
+external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
+external unsafe_blit :
+ bytes -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+external unsafe_fill :
+ bytes -> int -> int -> char -> unit = "caml_fill_string" "noalloc"
diff --git a/stdlib/bytesLabels.ml b/stdlib/bytesLabels.ml
new file mode 100644
index 0000000000..8ec8ec9e10
--- /dev/null
+++ b/stdlib/bytesLabels.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [BytesLabels]: labelled Bytes module *)
+
+include Bytes
diff --git a/stdlib/bytesLabels.mli b/stdlib/bytesLabels.mli
new file mode 100644
index 0000000000..04043182f4
--- /dev/null
+++ b/stdlib/bytesLabels.mli
@@ -0,0 +1,215 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Byte sequence operations.
+ @since 4.02.0
+ *)
+
+external length : bytes -> int = "%string_length"
+(** Return the length (number of bytes) of the argument. *)
+
+external get : bytes -> int -> char = "%string_safe_get"
+(** [get s n] returns the byte at index [n] in argument [s].
+
+ Raise [Invalid_argument] if [n] not a valid index in [s]. *)
+
+
+external set : bytes -> int -> char -> unit = "%string_safe_set"
+(** [set s n c] modifies [s] in place, replacing the byte at index [n]
+ with [c].
+
+ Raise [Invalid_argument] if [n] is not a valid index in [s]. *)
+
+external create : int -> bytes = "caml_create_string"
+(** [create n] returns a new byte sequence of length [n]. The
+ sequence is uninitialized and contains arbitrary bytes.
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val make : int -> char -> bytes
+(** [make n c] returns a new byte sequence of length [n], filled with
+ the byte [c].
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val init : int -> f:(int -> char) -> bytes
+(** [init n f] returns a fresh byte sequence of length [n],
+ with character [i] initialized to the result of [f i].
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val empty : bytes
+(** A byte sequence of size 0. *)
+
+val copy : bytes -> bytes
+(** Return a new byte sequence that contains the same bytes as the
+ argument. *)
+
+val of_string : string -> bytes
+(** Return a new byte sequence that contains the same bytes as the
+ given string. *)
+
+val to_string : bytes -> string
+(** Return a new string that contains the same bytes as the given byte
+ sequence. *)
+
+val sub : bytes -> pos:int -> len:int -> bytes
+(** [sub s start len] returns a new byte sequence of length [len],
+ containing the subsequence of [s] that starts at position [start]
+ and has length [len].
+
+ Raise [Invalid_argument] if [start] and [len] do not designate a
+ valid range of [s]. *)
+
+val sub_string : bytes -> int -> int -> string
+(** Same as [sub] but return a string instead of a byte sequence. *)
+
+val fill : bytes -> pos:int -> len:int -> char -> unit
+(** [fill s start len c] modifies [s] in place, replacing [len]
+ characters with [c], starting at [start].
+
+ Raise [Invalid_argument] if [start] and [len] do not designate a
+ valid range of [s]. *)
+
+val blit :
+ src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int
+ -> unit
+(** [blit src srcoff dst dstoff len] copies [len] bytes from sequence
+ [src], starting at index [srcoff], to sequence [dst], starting at
+ index [dstoff]. It works correctly even if [src] and [dst] are the
+ same byte sequence, and the source and destination intervals
+ overlap.
+
+ Raise [Invalid_argument] if [srcoff] and [len] do not
+ designate a valid range of [src], or if [dstoff] and [len]
+ do not designate a valid range of [dst]. *)
+
+val concat : sep:bytes -> bytes list -> bytes
+(** [concat sep sl] concatenates the list of byte sequences [sl],
+ inserting the separator byte sequence [sep] between each, and
+ returns the result as a new byte sequence. *)
+
+val iter : f:(char -> unit) -> bytes -> unit
+(** [iter f s] applies function [f] in turn to all the bytes of [s].
+ It is equivalent to [f (get s 0); f (get s 1); ...; f (get s
+ (length s - 1)); ()]. *)
+
+val iteri : f:(int -> char -> unit) -> bytes -> unit
+(** Same as {!Bytes.iter}, but the function is applied to the index of
+ the byte as first argument and the byte itself as second
+ argument. *)
+
+val map : f:(char -> char) -> bytes -> bytes
+(** [map f s] applies function [f] in turn to all the bytes of [s] and
+ stores the resulting bytes in a new sequence that is returned as
+ the result. *)
+
+val mapi : f:(int -> char -> char) -> bytes -> bytes
+(** [mapi f s] calls [f] with each character of [s] and its
+ index (in increasing index order) and stores the resulting bytes
+ in a new sequence that is returned as the result. *)
+
+val trim : bytes -> bytes
+(** Return a copy of the argument, without leading and trailing
+ whitespace. The bytes regarded as whitespace are the ASCII
+ characters [' '], ['\012'], ['\n'], ['\r'], and ['\t']. *)
+
+val escaped : bytes -> bytes
+(** Return a copy of the argument, with special characters represented
+ by escape sequences, following the lexical conventions of OCaml. *)
+
+val index : bytes -> char -> int
+(** [index s c] returns the index of the first occurrence of byte [c]
+ in [s].
+
+ Raise [Not_found] if [c] does not occur in [s]. *)
+
+val rindex : bytes -> char -> int
+(** [rindex s c] returns the index of the last occurrence of byte [c]
+ in [s].
+
+ Raise [Not_found] if [c] does not occur in [s]. *)
+
+val index_from : bytes -> int -> char -> int
+(** [index_from s i c] returns the index of the first occurrence of
+ byte [c] in [s] after position [i]. [Bytes.index s c] is
+ equivalent to [Bytes.index_from s 0 c].
+
+ Raise [Invalid_argument] if [i] is not a valid position in [s].
+ Raise [Not_found] if [c] does not occur in [s] after position [i]. *)
+
+val rindex_from : bytes -> int -> char -> int
+(** [rindex_from s i c] returns the index of the last occurrence of
+ byte [c] in [s] before position [i+1]. [rindex s c] is equivalent
+ to [rindex_from s (Bytes.length s - 1) c].
+
+ Raise [Invalid_argument] if [i+1] is not a valid position in [s].
+ Raise [Not_found] if [c] does not occur in [s] before position [i+1]. *)
+
+val contains : bytes -> char -> bool
+(** [contains s c] tests if byte [c] appears in [s]. *)
+
+val contains_from : bytes -> int -> char -> bool
+(** [contains_from s start c] tests if byte [c] appears in [s] after
+ position [start]. [contains s c] is equivalent to [contains_from
+ s 0 c].
+
+ Raise [Invalid_argument] if [start] is not a valid position in [s]. *)
+
+val rcontains_from : bytes -> int -> char -> bool
+(** [rcontains_from s stop c] tests if byte [c] appears in [s] before
+ position [stop+1].
+
+ Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid
+ position in [s]. *)
+
+val uppercase : bytes -> bytes
+(** Return a copy of the argument, with all lowercase letters
+ translated to uppercase, including accented letters of the ISO
+ Latin-1 (8859-1) character set. *)
+
+val lowercase : bytes -> bytes
+(** Return a copy of the argument, with all uppercase letters
+ translated to lowercase, including accented letters of the ISO
+ Latin-1 (8859-1) character set. *)
+
+val capitalize : bytes -> bytes
+(** Return a copy of the argument, with the first byte set to
+ uppercase. *)
+
+val uncapitalize : bytes -> bytes
+(** Return a copy of the argument, with the first byte set to
+ lowercase. *)
+
+type t = bytes
+(** An alias for the type of byte sequences. *)
+
+val compare: t -> t -> int
+(** The comparison function for byte sequences, with the same
+ specification as {!Pervasives.compare}. Along with the type [t],
+ this function [compare] allows the module [Bytes] to be passed as
+ argument to the functors {!Set.Make} and {!Map.Make}. *)
+
+(**/**)
+
+(* The following is for system use only. Do not call directly. *)
+
+external unsafe_get : bytes -> int -> char = "%string_unsafe_get"
+external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
+external unsafe_blit :
+ src:bytes -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int ->
+ unit = "caml_blit_string" "noalloc"
+external unsafe_fill :
+ bytes -> pos:int -> len:int -> char -> unit = "caml_fill_string" "noalloc"
+val unsafe_to_string : bytes -> string
+val unsafe_of_string : string -> bytes
diff --git a/stdlib/callback.ml b/stdlib/callback.ml
new file mode 100644
index 0000000000..6e4f9481e1
--- /dev/null
+++ b/stdlib/callback.ml
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Registering OCaml values with the C runtime for later callbacks *)
+
+external register_named_value : string -> Obj.t -> unit
+ = "caml_register_named_value"
+
+let register name v =
+ register_named_value name (Obj.repr v)
+
+let register_exception name (exn : exn) =
+ let exn = Obj.repr exn in
+ let slot = if Obj.tag exn = Obj.object_tag then exn else Obj.field exn 0 in
+ register_named_value name slot
diff --git a/stdlib/callback.mli b/stdlib/callback.mli
new file mode 100644
index 0000000000..de0d18373c
--- /dev/null
+++ b/stdlib/callback.mli
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Registering OCaml values with the C runtime.
+
+ This module allows OCaml values to be registered with the C runtime
+ under a symbolic name, so that C code can later call back registered
+ OCaml functions, or raise registered OCaml exceptions.
+*)
+
+val register : string -> 'a -> unit
+(** [Callback.register n v] registers the value [v] under
+ the name [n]. C code can later retrieve a handle to [v]
+ by calling [caml_named_value(n)]. *)
+
+val register_exception : string -> exn -> unit
+(** [Callback.register_exception n exn] registers the
+ exception contained in the exception value [exn]
+ under the name [n]. C code can later retrieve a handle to
+ the exception by calling [caml_named_value(n)]. The exception
+ value thus obtained is suitable for passing as first argument
+ to [raise_constant] or [raise_with_arg]. *)
diff --git a/stdlib/camlinternalFormat.ml b/stdlib/camlinternalFormat.ml
new file mode 100644
index 0000000000..9d4ba4f4bf
--- /dev/null
+++ b/stdlib/camlinternalFormat.ml
@@ -0,0 +1,2827 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benoit Vaugon, ENSTA *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open CamlinternalFormatBasics
+
+(******************************************************************************)
+ (* Tools to manipulate scanning set of chars (see %[...]) *)
+
+type mutable_char_set = bytes
+
+(* Create a fresh, empty, mutable char set. *)
+let create_char_set () = Bytes.make 32 '\000'
+
+(* Add a char in a mutable char set. *)
+let add_in_char_set char_set c =
+ let ind = int_of_char c in
+ let str_ind = ind lsr 3 and mask = 1 lsl (ind land 0b111) in
+ Bytes.set char_set str_ind
+ (char_of_int (int_of_char (Bytes.get char_set str_ind) lor mask))
+
+let freeze_char_set char_set =
+ Bytes.to_string char_set
+
+(* Compute the complement of a char set. *)
+let rev_char_set char_set =
+ let char_set' = create_char_set () in
+ for i = 0 to 31 do
+ Bytes.set char_set' i
+ (char_of_int (int_of_char (String.get char_set i) lxor 0xFF));
+ done;
+ Bytes.unsafe_to_string char_set'
+
+(* Return true if a `c' is in `char_set'. *)
+let is_in_char_set char_set c =
+ let ind = int_of_char c in
+ let str_ind = ind lsr 3 and mask = 1 lsl (ind land 0b111) in
+ (int_of_char (String.get char_set str_ind) land mask) <> 0
+
+
+(******************************************************************************)
+ (* Ignored param conversion *)
+
+(* GADT used to abstract an existential type parameter. *)
+(* See param_format_of_ignored_format. *)
+type ('a, 'b, 'c, 'd, 'e, 'f) param_format_ebb = Param_format_EBB :
+ ('x -> 'a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) param_format_ebb
+
+(* Compute a padding associated to a pad_option (see "%_42d"). *)
+let pad_of_pad_opt pad_opt = match pad_opt with
+ | None -> No_padding
+ | Some width -> Lit_padding (Right, width)
+
+(* Compute a precision associated to a prec_option (see "%_.42f"). *)
+let prec_of_prec_opt prec_opt = match prec_opt with
+ | None -> No_precision
+ | Some ndec -> Lit_precision ndec
+
+(* Turn an ignored param into its equivalent not-ignored format node. *)
+(* Used for format pretty-printing and Scanf. *)
+let param_format_of_ignored_format : type a b c d e f x y .
+ (a, b, c, d, y, x) ignored -> (x, b, c, y, e, f) fmt ->
+ (a, b, c, d, e, f) param_format_ebb =
+fun ign fmt -> match ign with
+ | Ignored_char ->
+ Param_format_EBB (Char fmt)
+ | Ignored_caml_char ->
+ Param_format_EBB (Caml_char fmt)
+ | Ignored_string pad_opt ->
+ Param_format_EBB (String (pad_of_pad_opt pad_opt, fmt))
+ | Ignored_caml_string pad_opt ->
+ Param_format_EBB (Caml_string (pad_of_pad_opt pad_opt, fmt))
+ | Ignored_int (iconv, pad_opt) ->
+ Param_format_EBB (Int (iconv, pad_of_pad_opt pad_opt, No_precision, fmt))
+ | Ignored_int32 (iconv, pad_opt) ->
+ Param_format_EBB
+ (Int32 (iconv, pad_of_pad_opt pad_opt, No_precision, fmt))
+ | Ignored_nativeint (iconv, pad_opt) ->
+ Param_format_EBB
+ (Nativeint (iconv, pad_of_pad_opt pad_opt, No_precision, fmt))
+ | Ignored_int64 (iconv, pad_opt) ->
+ Param_format_EBB
+ (Int64 (iconv, pad_of_pad_opt pad_opt, No_precision, fmt))
+ | Ignored_float (pad_opt, prec_opt) ->
+ Param_format_EBB
+ (Float (Float_f, pad_of_pad_opt pad_opt, prec_of_prec_opt prec_opt, fmt))
+ | Ignored_bool ->
+ Param_format_EBB (Bool fmt)
+ | Ignored_format_arg (pad_opt, fmtty) ->
+ Param_format_EBB (Format_arg (pad_opt, fmtty, fmt))
+ | Ignored_format_subst (pad_opt, fmtty) ->
+ Param_format_EBB
+ (Format_subst (pad_opt, fmtty, fmt))
+ | Ignored_reader ->
+ Param_format_EBB (Reader fmt)
+ | Ignored_scan_char_set (width_opt, char_set) ->
+ Param_format_EBB (Scan_char_set (width_opt, char_set, fmt))
+ | Ignored_scan_get_counter counter ->
+ Param_format_EBB (Scan_get_counter (counter, fmt))
+ | Ignored_scan_next_char ->
+ Param_format_EBB (Scan_next_char fmt)
+
+
+(******************************************************************************)
+ (* Types *)
+
+type ('b, 'c) acc_formatting_gen =
+ | Acc_open_tag of ('b, 'c) acc
+ | Acc_open_box of ('b, 'c) acc
+
+(* Reversed list of printing atoms. *)
+(* Used to accumulate printf arguments. *)
+and ('b, 'c) acc =
+ | Acc_formatting_lit of ('b, 'c) acc * formatting_lit
+ (* Special fmtting (box) *)
+ | Acc_formatting_gen of ('b, 'c) acc * ('b, 'c) acc_formatting_gen
+ (* Special fmtting (box) *)
+ | Acc_string_literal of ('b, 'c) acc * string (* Literal string *)
+ | Acc_char_literal of ('b, 'c) acc * char (* Literal char *)
+ | Acc_data_string of ('b, 'c) acc * string (* Generated string *)
+ | Acc_data_char of ('b, 'c) acc * char (* Generated char *)
+ | Acc_delay of ('b, 'c) acc * ('b -> 'c)
+ (* Delayed printing (%a, %t) *)
+ | Acc_flush of ('b, 'c) acc (* Flush *)
+ | Acc_invalid_arg of ('b, 'c) acc * string
+ (* Raise Invalid_argument msg *)
+ | End_of_acc
+
+(* List of heterogeneous values. *)
+(* Used to accumulate scanf callback arguments. *)
+type ('a, 'b) heter_list =
+ | Cons : 'c * ('a, 'b) heter_list -> ('c -> 'a, 'b) heter_list
+ | Nil : ('b, 'b) heter_list
+
+(* Existential Black Boxes. *)
+(* Used to abstract some existential type parameters. *)
+
+(* GADT type associating a padding and an fmtty. *)
+(* See the type_padding function. *)
+type ('a, 'b, 'c, 'd, 'e, 'f) padding_fmtty_ebb = Padding_fmtty_EBB :
+ ('x, 'y) padding * ('y, 'b, 'c, 'd, 'e, 'f) fmtty ->
+ ('x, 'b, 'c, 'd, 'e, 'f) padding_fmtty_ebb
+
+(* GADT type associating a padding, a precision and an fmtty. *)
+(* See the type_padprec function. *)
+type ('a, 'b, 'c, 'd, 'e, 'f) padprec_fmtty_ebb = Padprec_fmtty_EBB :
+ ('x, 'y) padding * ('y, 'z) precision * ('z, 'b, 'c, 'd, 'e, 'f) fmtty ->
+ ('x, 'b, 'c, 'd, 'e, 'f) padprec_fmtty_ebb
+
+(* GADT type associating a padding and an fmt. *)
+(* See make_padding_fmt_ebb and parse_format functions. *)
+type ('a, 'b, 'c, 'e, 'f) padding_fmt_ebb = Padding_fmt_EBB :
+ (_, 'x -> 'a) padding *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'e, 'f) padding_fmt_ebb
+
+(* GADT type associating a precision and an fmt. *)
+(* See make_precision_fmt_ebb and parse_format functions. *)
+type ('a, 'b, 'c, 'e, 'f) precision_fmt_ebb = Precision_fmt_EBB :
+ (_, 'x -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'e, 'f) precision_fmt_ebb
+
+(* GADT type associating a padding, a precision and an fmt. *)
+(* See make_padprec_fmt_ebb and parse_format functions. *)
+type ('p, 'b, 'c, 'e, 'f) padprec_fmt_ebb = Padprec_fmt_EBB :
+ ('x, 'y) padding * ('y, 'p -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('p, 'b, 'c, 'e, 'f) padprec_fmt_ebb
+
+(* Abstract the 'a and 'd parameters of an fmt. *)
+(* Output type of the format parsing function. *)
+type ('b, 'c, 'e, 'f) fmt_ebb = Fmt_EBB :
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('b, 'c, 'e, 'f) fmt_ebb
+
+(* GADT type associating an fmtty and an fmt. *)
+(* See the type_format_gen function. *)
+type ('a, 'b, 'c, 'd, 'e, 'f) fmt_fmtty_ebb = Fmt_fmtty_EBB :
+ ('a, 'b, 'c, 'd, 'y, 'x) fmt *
+ ('x, 'b, 'c, 'y, 'e, 'f) fmtty ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt_fmtty_ebb
+
+(* GADT type associating an fmtty and an fmt. *)
+(* See the type_ignored_format_substitution function. *)
+type ('a, 'b, 'c, 'd, 'e, 'f) fmtty_fmt_ebb = Fmtty_fmt_EBB :
+ ('a, 'b, 'c, 'd, 'y, 'x) fmtty *
+ ('x, 'b, 'c, 'y, 'e, 'f) fmt_fmtty_ebb ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmtty_fmt_ebb
+
+(* Abstract all fmtty type parameters. *)
+(* Used to compare format types. *)
+type fmtty_ebb = Fmtty_EBB : ('a, 'b, 'c, 'd, 'e, 'f) fmtty -> fmtty_ebb
+
+(* Abstract all padding type parameters. *)
+(* Used to compare paddings. *)
+type padding_ebb = Padding_EBB : ('a, 'b) padding -> padding_ebb
+
+(* Abstract all precision type parameters. *)
+(* Used to compare precisions. *)
+type precision_ebb = Precision_EBB : ('a, 'b) precision -> precision_ebb
+
+(******************************************************************************)
+ (* Constants *)
+
+(* Default precision for float printing. *)
+let default_float_precision = 6
+
+(******************************************************************************)
+ (* Externals *)
+
+external format_float: string -> float -> string
+ = "caml_format_float"
+external format_int: string -> int -> string
+ = "caml_format_int"
+external format_int32: string -> int32 -> string
+ = "caml_int32_format"
+external format_nativeint: string -> nativeint -> string
+ = "caml_nativeint_format"
+external format_int64: string -> int64 -> string
+ = "caml_int64_format"
+
+(******************************************************************************)
+ (* Tools to pretty-print formats *)
+
+(* Type of extensible character buffers. *)
+type buffer = {
+ mutable ind : int;
+ mutable bytes : bytes;
+}
+
+(* Create a fresh buffer. *)
+let buffer_create init_size = { ind = 0; bytes = Bytes.create init_size }
+
+(* Check size of the buffer and grow it if needed. *)
+let buffer_check_size buf overhead =
+ let len = Bytes.length buf.bytes in
+ let min_len = buf.ind + overhead in
+ if min_len > len then (
+ let new_len = max (len * 2) min_len in
+ let new_str = Bytes.create new_len in
+ Bytes.blit buf.bytes 0 new_str 0 len;
+ buf.bytes <- new_str;
+ )
+
+(* Add the character `c' to the buffer `buf'. *)
+let buffer_add_char buf c =
+ buffer_check_size buf 1;
+ Bytes.set buf.bytes buf.ind c;
+ buf.ind <- buf.ind + 1
+
+(* Add the string `s' to the buffer `buf'. *)
+let buffer_add_string buf s =
+ let str_len = String.length s in
+ buffer_check_size buf str_len;
+ String.blit s 0 buf.bytes buf.ind str_len;
+ buf.ind <- buf.ind + str_len
+
+(* Get the content of the buffer. *)
+let buffer_contents buf =
+ Bytes.sub_string buf.bytes 0 buf.ind
+
+(***)
+
+(* Convert an integer conversion to char. *)
+let char_of_iconv iconv = match iconv with
+ | Int_d | Int_pd | Int_sd -> 'd' | Int_i | Int_pi | Int_si -> 'i'
+ | Int_x | Int_Cx -> 'x' | Int_X | Int_CX -> 'X' | Int_o | Int_Co -> 'o'
+ | Int_u -> 'u'
+
+(* Convert a float conversion to char. *)
+let char_of_fconv fconv = match fconv with
+ | Float_f | Float_pf | Float_sf -> 'f' | Float_e | Float_pe | Float_se -> 'e'
+ | Float_E | Float_pE | Float_sE -> 'E' | Float_g | Float_pg | Float_sg -> 'g'
+ | Float_G | Float_pG | Float_sG -> 'G' | Float_F -> 'F'
+
+(* Convert a scanning counter to char. *)
+let char_of_counter counter = match counter with
+ | Line_counter -> 'l'
+ | Char_counter -> 'n'
+ | Token_counter -> 'N'
+
+(***)
+
+(* Print a char_set in a buffer with the OCaml format lexical convention. *)
+let bprint_char_set buf char_set =
+ let rec print_start set =
+ let is_alone c =
+ let before, after = Char.(chr (code c - 1), chr (code c + 1)) in
+ is_in_char_set set c
+ && not (is_in_char_set set before && is_in_char_set set after) in
+ if is_alone ']' then buffer_add_char buf ']';
+ print_out set 1;
+ if is_alone '-' then buffer_add_char buf '-';
+ and print_out set i =
+ if i < 256 then
+ if is_in_char_set set (char_of_int i) then print_first set i
+ else print_out set (i + 1)
+ and print_first set i =
+ match char_of_int i with
+ | '\255' -> print_char buf 255;
+ | ']' | '-' -> print_out set (i + 1);
+ | _ -> print_second set (i + 1);
+ and print_second set i =
+ if is_in_char_set set (char_of_int i) then
+ match char_of_int i with
+ | '\255' ->
+ print_char buf 254;
+ print_char buf 255;
+ | ']' | '-' when not (is_in_char_set set (char_of_int (i + 1))) ->
+ print_char buf (i - 1);
+ print_out set (i + 1);
+ | _ when not (is_in_char_set set (char_of_int (i + 1))) ->
+ print_char buf (i - 1);
+ print_char buf i;
+ print_out set (i + 2);
+ | _ ->
+ print_in set (i - 1) (i + 2);
+ else (
+ print_char buf (i - 1);
+ print_out set (i + 1);
+ )
+ and print_in set i j =
+ if j = 256 || not (is_in_char_set set (char_of_int j)) then (
+ print_char buf i;
+ print_char buf (int_of_char '-');
+ print_char buf (j - 1);
+ if j < 256 then print_out set (j + 1);
+ ) else
+ print_in set i (j + 1);
+ and print_char buf i = match char_of_int i with
+ | '%' -> buffer_add_char buf '%'; buffer_add_char buf '%';
+ | '@' -> buffer_add_char buf '%'; buffer_add_char buf '@';
+ | c -> buffer_add_char buf c;
+ in
+ buffer_add_char buf '[';
+ print_start (
+ if is_in_char_set char_set '\000'
+ then ( buffer_add_char buf '^'; rev_char_set char_set )
+ else char_set
+ );
+ buffer_add_char buf ']'
+
+(***)
+
+(* Print a padty in a buffer with the format-like syntax. *)
+let bprint_padty buf padty = match padty with
+ | Left -> buffer_add_char buf '-'
+ | Right -> ()
+ | Zeros -> buffer_add_char buf '0'
+
+(* Print the '_' of an ignored flag if needed. *)
+let bprint_ignored_flag buf ign_flag =
+ if ign_flag then buffer_add_char buf '_'
+
+(***)
+
+let bprint_pad_opt buf pad_opt = match pad_opt with
+ | None -> ()
+ | Some width -> buffer_add_string buf (string_of_int width)
+
+(***)
+
+(* Print padding in a buffer with the format-like syntax. *)
+let bprint_padding : type a b . buffer -> (a, b) padding -> unit =
+fun buf pad -> match pad with
+ | No_padding -> ()
+ | Lit_padding (padty, n) ->
+ bprint_padty buf padty;
+ buffer_add_string buf (string_of_int n);
+ | Arg_padding padty ->
+ bprint_padty buf padty;
+ buffer_add_char buf '*'
+
+(* Print precision in a buffer with the format-like syntax. *)
+let bprint_precision : type a b . buffer -> (a, b) precision -> unit =
+ fun buf prec -> match prec with
+ | No_precision -> ()
+ | Lit_precision n ->
+ buffer_add_char buf '.';
+ buffer_add_string buf (string_of_int n);
+ | Arg_precision ->
+ buffer_add_string buf ".*"
+
+(***)
+
+(* Print the optionnal '+', ' ' or '#' associated to an int conversion. *)
+let bprint_iconv_flag buf iconv = match iconv with
+ | Int_pd | Int_pi -> buffer_add_char buf '+'
+ | Int_sd | Int_si -> buffer_add_char buf ' '
+ | Int_Cx | Int_CX | Int_Co -> buffer_add_char buf '#'
+ | Int_d | Int_i | Int_x | Int_X | Int_o | Int_u -> ()
+
+(* Print an complete int format in a buffer (ex: "%3.*d"). *)
+let bprint_int_fmt buf ign_flag iconv pad prec =
+ buffer_add_char buf '%';
+ bprint_ignored_flag buf ign_flag;
+ bprint_iconv_flag buf iconv;
+ bprint_padding buf pad;
+ bprint_precision buf prec;
+ buffer_add_char buf (char_of_iconv iconv)
+
+(* Print a complete int32, nativeint or int64 format in a buffer. *)
+let bprint_altint_fmt buf ign_flag iconv pad prec c =
+ buffer_add_char buf '%';
+ bprint_ignored_flag buf ign_flag;
+ bprint_iconv_flag buf iconv;
+ bprint_padding buf pad;
+ bprint_precision buf prec;
+ buffer_add_char buf c;
+ buffer_add_char buf (char_of_iconv iconv)
+
+(***)
+
+(* Print the optionnal '+' associated to a float conversion. *)
+let bprint_fconv_flag buf fconv = match fconv with
+ | Float_pf | Float_pe | Float_pE | Float_pg | Float_pG ->
+ buffer_add_char buf '+'
+ | Float_sf | Float_se | Float_sE | Float_sg | Float_sG ->
+ buffer_add_char buf ' '
+ | Float_f | Float_e | Float_E | Float_g | Float_G | Float_F ->
+ ()
+
+(* Print a complete float format in a buffer (ex: "%+*.3f"). *)
+let bprint_float_fmt buf ign_flag fconv pad prec =
+ buffer_add_char buf '%';
+ bprint_ignored_flag buf ign_flag;
+ bprint_fconv_flag buf fconv;
+ bprint_padding buf pad;
+ bprint_precision buf prec;
+ buffer_add_char buf (char_of_fconv fconv)
+
+(* Compute the literal string representation of a formatting_lit. *)
+(* Also used by Printf and Scanf where formatting is not interpreted. *)
+let string_of_formatting_lit formatting_lit = match formatting_lit with
+ | Close_box -> "@]"
+ | Close_tag -> "@}"
+ | Break (str, _, _) -> str
+ | FFlush -> "@?"
+ | Force_newline -> "@\n"
+ | Flush_newline -> "@."
+ | Magic_size (str, _) -> str
+ | Escaped_at -> "@@"
+ | Escaped_percent -> "@%"
+ | Scan_indic c -> "@" ^ (String.make 1 c)
+
+(* Compute the literal string representation of a formatting. *)
+(* Also used by Printf and Scanf where formatting is not interpreted. *)
+let string_of_formatting_gen : type a b c d e f .
+ (a, b, c, d, e, f) formatting_gen -> string =
+ fun formatting_gen -> match formatting_gen with
+ | Open_tag (Format (_, str)) -> str
+ | Open_box (Format (_, str)) -> str
+
+(***)
+
+(* Print a literal char in a buffer, escape '%' by "%%". *)
+let bprint_char_literal buf chr = match chr with
+ | '%' -> buffer_add_string buf "%%"
+ | _ -> buffer_add_char buf chr
+
+(* Print a literal string in a buffer, escape all '%' by "%%". *)
+let bprint_string_literal buf str =
+ for i = 0 to String.length str - 1 do
+ bprint_char_literal buf str.[i]
+ done
+
+(******************************************************************************)
+ (* Format pretty-printing *)
+
+(* Print a complete format type (an fmtty) in a buffer. *)
+let rec bprint_fmtty : type a b c d e f g h i j k l .
+ buffer -> (a, b, c, d, e, f, g, h, i, j, k, l) fmtty_rel -> unit =
+fun buf fmtty -> match fmtty with
+ | Char_ty rest -> buffer_add_string buf "%c"; bprint_fmtty buf rest;
+ | String_ty rest -> buffer_add_string buf "%s"; bprint_fmtty buf rest;
+ | Int_ty rest -> buffer_add_string buf "%i"; bprint_fmtty buf rest;
+ | Int32_ty rest -> buffer_add_string buf "%li"; bprint_fmtty buf rest;
+ | Nativeint_ty rest -> buffer_add_string buf "%ni"; bprint_fmtty buf rest;
+ | Int64_ty rest -> buffer_add_string buf "%Li"; bprint_fmtty buf rest;
+ | Float_ty rest -> buffer_add_string buf "%f"; bprint_fmtty buf rest;
+ | Bool_ty rest -> buffer_add_string buf "%B"; bprint_fmtty buf rest;
+ | Alpha_ty rest -> buffer_add_string buf "%a"; bprint_fmtty buf rest;
+ | Theta_ty rest -> buffer_add_string buf "%t"; bprint_fmtty buf rest;
+ | Any_ty rest -> buffer_add_string buf "%?"; bprint_fmtty buf rest;
+ | Reader_ty rest -> buffer_add_string buf "%r"; bprint_fmtty buf rest;
+
+ | Ignored_reader_ty rest ->
+ buffer_add_string buf "%_r";
+ bprint_fmtty buf rest;
+
+ | Format_arg_ty (sub_fmtty, rest) ->
+ buffer_add_string buf "%{"; bprint_fmtty buf sub_fmtty;
+ buffer_add_string buf "%}"; bprint_fmtty buf rest;
+ | Format_subst_ty (sub_fmtty, _, rest) ->
+ buffer_add_string buf "%("; bprint_fmtty buf sub_fmtty;
+ buffer_add_string buf "%)"; bprint_fmtty buf rest;
+
+ | End_of_fmtty -> ()
+
+(***)
+
+let rec int_of_custom_arity : type a b c .
+ (a, b, c) custom_arity -> int =
+ function
+ | Custom_zero -> 0
+ | Custom_succ x -> 1 + int_of_custom_arity x
+
+(* Print a complete format in a buffer. *)
+let bprint_fmt buf fmt =
+ let rec fmtiter : type a b c d e f .
+ (a, b, c, d, e, f) fmt -> bool -> unit =
+ fun fmt ign_flag -> match fmt with
+ | String (pad, rest) ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ bprint_padding buf pad; buffer_add_char buf 's';
+ fmtiter rest false;
+ | Caml_string (pad, rest) ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ bprint_padding buf pad; buffer_add_char buf 'S';
+ fmtiter rest false;
+
+ | Int (iconv, pad, prec, rest) ->
+ bprint_int_fmt buf ign_flag iconv pad prec;
+ fmtiter rest false;
+ | Int32 (iconv, pad, prec, rest) ->
+ bprint_altint_fmt buf ign_flag iconv pad prec 'l';
+ fmtiter rest false;
+ | Nativeint (iconv, pad, prec, rest) ->
+ bprint_altint_fmt buf ign_flag iconv pad prec 'n';
+ fmtiter rest false;
+ | Int64 (iconv, pad, prec, rest) ->
+ bprint_altint_fmt buf ign_flag iconv pad prec 'L';
+ fmtiter rest false;
+ | Float (fconv, pad, prec, rest) ->
+ bprint_float_fmt buf ign_flag fconv pad prec;
+ fmtiter rest false;
+
+ | Char rest ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ buffer_add_char buf 'c'; fmtiter rest false;
+ | Caml_char rest ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ buffer_add_char buf 'C'; fmtiter rest false;
+ | Bool rest ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ buffer_add_char buf 'B'; fmtiter rest false;
+ | Alpha rest ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ buffer_add_char buf 'a'; fmtiter rest false;
+ | Theta rest ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ buffer_add_char buf 't'; fmtiter rest false;
+ | Custom (arity, _, rest) ->
+ for _i = 1 to int_of_custom_arity arity do
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ buffer_add_char buf '?';
+ done;
+ fmtiter rest false;
+ | Reader rest ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ buffer_add_char buf 'r'; fmtiter rest false;
+ | Flush rest ->
+ buffer_add_string buf "%!";
+ fmtiter rest ign_flag;
+
+ | String_literal (str, rest) ->
+ bprint_string_literal buf str;
+ fmtiter rest ign_flag;
+ | Char_literal (chr, rest) ->
+ bprint_char_literal buf chr;
+ fmtiter rest ign_flag;
+
+ | Format_arg (pad_opt, fmtty, rest) ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ bprint_pad_opt buf pad_opt; buffer_add_char buf '{';
+ bprint_fmtty buf fmtty; buffer_add_char buf '%'; buffer_add_char buf '}';
+ fmtiter rest false;
+ | Format_subst (pad_opt, fmtty, rest) ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ bprint_pad_opt buf pad_opt; buffer_add_char buf '(';
+ bprint_fmtty buf fmtty; buffer_add_char buf '%'; buffer_add_char buf ')';
+ fmtiter rest false;
+
+ | Scan_char_set (width_opt, char_set, rest) ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ bprint_pad_opt buf width_opt; bprint_char_set buf char_set;
+ fmtiter rest false;
+ | Scan_get_counter (counter, rest) ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ buffer_add_char buf (char_of_counter counter);
+ fmtiter rest false;
+ | Scan_next_char rest ->
+ buffer_add_char buf '%'; bprint_ignored_flag buf ign_flag;
+ bprint_string_literal buf "0c"; fmtiter rest false;
+
+ | Ignored_param (ign, rest) ->
+ let Param_format_EBB fmt' = param_format_of_ignored_format ign rest in
+ fmtiter fmt' true;
+
+ | Formatting_lit (fmting_lit, rest) ->
+ bprint_string_literal buf (string_of_formatting_lit fmting_lit);
+ fmtiter rest ign_flag;
+ | Formatting_gen (fmting_gen, rest) ->
+ bprint_string_literal buf "@{";
+ bprint_string_literal buf (string_of_formatting_gen fmting_gen);
+ fmtiter rest ign_flag;
+
+ | End_of_format -> ()
+
+ in fmtiter fmt false
+
+(***)
+
+(* Convert a format to string. *)
+let string_of_fmt fmt =
+ let buf = buffer_create 16 in
+ bprint_fmt buf fmt;
+ buffer_contents buf
+
+(******************************************************************************)
+ (* Type extraction *)
+
+type (_, _) eq = Refl : ('a, 'a) eq
+
+(* Invariant: this function is the identity on values.
+
+ In particular, if (ty1, ty2) have equal values, then
+ (trans (symm ty1) ty2) respects the 'trans' precondition. *)
+let rec symm : type a1 b1 c1 d1 e1 f1 a2 b2 c2 d2 e2 f2 .
+ (a1, b1, c1, d1, e1, f1,
+ a2, b2, c2, d2, e2, f2) fmtty_rel
+-> (a2, b2, c2, d2, e2, f2,
+ a1, b1, c1, d1, e1, f1) fmtty_rel
+= function
+ | Char_ty rest -> Char_ty (symm rest)
+ | Int_ty rest -> Int_ty (symm rest)
+ | Int32_ty rest -> Int32_ty (symm rest)
+ | Int64_ty rest -> Int64_ty (symm rest)
+ | Nativeint_ty rest -> Nativeint_ty (symm rest)
+ | Float_ty rest -> Float_ty (symm rest)
+ | Bool_ty rest -> Bool_ty (symm rest)
+ | String_ty rest -> String_ty (symm rest)
+ | Theta_ty rest -> Theta_ty (symm rest)
+ | Alpha_ty rest -> Alpha_ty (symm rest)
+ | Any_ty rest -> Any_ty (symm rest)
+ | Reader_ty rest -> Reader_ty (symm rest)
+ | Ignored_reader_ty rest -> Ignored_reader_ty (symm rest)
+ | Format_arg_ty (ty, rest) ->
+ Format_arg_ty (ty, symm rest)
+ | Format_subst_ty (ty1, ty2, rest) ->
+ Format_subst_ty (ty2, ty1, symm rest)
+ | End_of_fmtty -> End_of_fmtty
+
+let rec fmtty_rel_det : type a1 b c d1 e1 f1 a2 d2 e2 f2 .
+ (a1, b, c, d1, e1, f1,
+ a2, b, c, d2, e2, f2) fmtty_rel ->
+ ((f1, f2) eq -> (a1, a2) eq)
+ * ((a1, a2) eq -> (f1, f2) eq)
+ * ((e1, e2) eq -> (d1, d2) eq)
+ * ((d1, d2) eq -> (e1, e2) eq)
+= function
+ | End_of_fmtty ->
+ (fun Refl -> Refl),
+ (fun Refl -> Refl),
+ (fun Refl -> Refl),
+ (fun Refl -> Refl)
+ | Char_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | String_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Int_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Int32_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Int64_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Nativeint_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Float_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Bool_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+
+ | Theta_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Alpha_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Any_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Reader_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ (fun Refl -> let Refl = ed Refl in Refl),
+ (fun Refl -> let Refl = de Refl in Refl)
+ | Ignored_reader_ty rest ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ (fun Refl -> let Refl = ed Refl in Refl),
+ (fun Refl -> let Refl = de Refl in Refl)
+ | Format_arg_ty (_ty, rest) ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ (fun Refl -> let Refl = fa Refl in Refl),
+ (fun Refl -> let Refl = af Refl in Refl),
+ ed, de
+ | Format_subst_ty (ty1, ty2, rest) ->
+ let fa, af, ed, de = fmtty_rel_det rest in
+ let ty = trans (symm ty1) ty2 in
+ let ag, ga, dj, jd = fmtty_rel_det ty in
+ (fun Refl -> let Refl = fa Refl in let Refl = ag Refl in Refl),
+ (fun Refl -> let Refl = ga Refl in let Refl = af Refl in Refl),
+ (fun Refl -> let Refl = ed Refl in let Refl = dj Refl in Refl),
+ (fun Refl -> let Refl = jd Refl in let Refl = de Refl in Refl)
+
+(* Precondition: we assume that the two fmtty_rel arguments have equal
+ values (at possibly distinct types); this invariant comes from the way
+ fmtty_rel witnesses are produced by the type-checker
+
+ The code below uses (assert false) when this assumption is broken. The
+ code pattern is the following:
+
+ | Foo x, Foo y ->
+ (* case where indeed both values
+ start with constructor Foo *)
+ | Foo _, _
+ | _, Foo _ ->
+ (* different head constructors: broken precondition *)
+ assert false
+*)
+and trans : type
+ a1 b1 c1 d1 e1 f1
+ a2 b2 c2 d2 e2 f2
+ a3 b3 c3 d3 e3 f3
+.
+ (a1, b1, c1, d1, e1, f1,
+ a2, b2, c2, d2, e2, f2) fmtty_rel
+-> (a2, b2, c2, d2, e2, f2,
+ a3, b3, c3, d3, e3, f3) fmtty_rel
+-> (a1, b1, c1, d1, e1, f1,
+ a3, b3, c3, d3, e3, f3) fmtty_rel
+= fun ty1 ty2 -> match ty1, ty2 with
+ | Char_ty rest1, Char_ty rest2 -> Char_ty (trans rest1 rest2)
+ | String_ty rest1, String_ty rest2 -> String_ty (trans rest1 rest2)
+ | Bool_ty rest1, Bool_ty rest2 -> Bool_ty (trans rest1 rest2)
+ | Int_ty rest1, Int_ty rest2 -> Int_ty (trans rest1 rest2)
+ | Int32_ty rest1, Int32_ty rest2 -> Int32_ty (trans rest1 rest2)
+ | Int64_ty rest1, Int64_ty rest2 -> Int64_ty (trans rest1 rest2)
+ | Nativeint_ty rest1, Nativeint_ty rest2 -> Nativeint_ty (trans rest1 rest2)
+ | Float_ty rest1, Float_ty rest2 -> Float_ty (trans rest1 rest2)
+
+ | Alpha_ty rest1, Alpha_ty rest2 -> Alpha_ty (trans rest1 rest2)
+ | Alpha_ty _, _ -> assert false
+ | _, Alpha_ty _ -> assert false
+
+ | Theta_ty rest1, Theta_ty rest2 -> Theta_ty (trans rest1 rest2)
+ | Theta_ty _, _ -> assert false
+ | _, Theta_ty _ -> assert false
+
+ | Any_ty rest1, Any_ty rest2 -> Any_ty (trans rest1 rest2)
+ | Any_ty _, _ -> assert false
+ | _, Any_ty _ -> assert false
+
+ | Reader_ty rest1, Reader_ty rest2 -> Reader_ty (trans rest1 rest2)
+ | Reader_ty _, _ -> assert false
+ | _, Reader_ty _ -> assert false
+
+ | Ignored_reader_ty rest1, Ignored_reader_ty rest2 ->
+ Ignored_reader_ty (trans rest1 rest2)
+ | Ignored_reader_ty _, _ -> assert false
+ | _, Ignored_reader_ty _ -> assert false
+
+ | Format_arg_ty (ty1, rest1), Format_arg_ty (ty2, rest2) ->
+ Format_arg_ty (trans ty1 ty2, trans rest1 rest2)
+ | Format_arg_ty _, _ -> assert false
+ | _, Format_arg_ty _ -> assert false
+
+ | Format_subst_ty (ty11, ty12, rest1),
+ Format_subst_ty (ty21, ty22, rest2) ->
+ let ty = trans (symm ty12) ty21 in
+ let _, f2, _, f4 = fmtty_rel_det ty in
+ let Refl = f2 Refl in
+ let Refl = f4 Refl in
+ Format_subst_ty (ty11, ty22, trans rest1 rest2)
+ | Format_subst_ty _, _ -> assert false
+ | _, Format_subst_ty _ -> assert false
+
+ | End_of_fmtty, End_of_fmtty -> End_of_fmtty
+ | End_of_fmtty, _ -> assert false
+ | _, End_of_fmtty -> assert false
+
+let rec fmtty_of_formatting_gen : type a b c d e f .
+ (a, b, c, d, e, f) formatting_gen ->
+ (a, b, c, d, e, f) fmtty =
+fun formatting_gen -> match formatting_gen with
+ | Open_tag (Format (fmt, _)) -> fmtty_of_fmt fmt
+ | Open_box (Format (fmt, _)) -> fmtty_of_fmt fmt
+
+(* Extract the type representation (an fmtty) of a format. *)
+and fmtty_of_fmt : type a b c d e f .
+ (a, b, c, d, e, f) fmt -> (a, b, c, d, e, f) fmtty =
+fun fmtty -> match fmtty with
+ | String (pad, rest) ->
+ fmtty_of_padding_fmtty pad (String_ty (fmtty_of_fmt rest))
+ | Caml_string (pad, rest) ->
+ fmtty_of_padding_fmtty pad (String_ty (fmtty_of_fmt rest))
+
+ | Int (_, pad, prec, rest) ->
+ let ty_rest = fmtty_of_fmt rest in
+ let prec_ty = fmtty_of_precision_fmtty prec (Int_ty ty_rest) in
+ fmtty_of_padding_fmtty pad prec_ty
+ | Int32 (_, pad, prec, rest) ->
+ let ty_rest = fmtty_of_fmt rest in
+ let prec_ty = fmtty_of_precision_fmtty prec (Int32_ty ty_rest) in
+ fmtty_of_padding_fmtty pad prec_ty
+ | Nativeint (_, pad, prec, rest) ->
+ let ty_rest = fmtty_of_fmt rest in
+ let prec_ty = fmtty_of_precision_fmtty prec (Nativeint_ty ty_rest) in
+ fmtty_of_padding_fmtty pad prec_ty
+ | Int64 (_, pad, prec, rest) ->
+ let ty_rest = fmtty_of_fmt rest in
+ let prec_ty = fmtty_of_precision_fmtty prec (Int64_ty ty_rest) in
+ fmtty_of_padding_fmtty pad prec_ty
+ | Float (_, pad, prec, rest) ->
+ let ty_rest = fmtty_of_fmt rest in
+ let prec_ty = fmtty_of_precision_fmtty prec (Float_ty ty_rest) in
+ fmtty_of_padding_fmtty pad prec_ty
+
+ | Char rest -> Char_ty (fmtty_of_fmt rest)
+ | Caml_char rest -> Char_ty (fmtty_of_fmt rest)
+ | Bool rest -> Bool_ty (fmtty_of_fmt rest)
+ | Alpha rest -> Alpha_ty (fmtty_of_fmt rest)
+ | Theta rest -> Theta_ty (fmtty_of_fmt rest)
+ | Custom (arity, _, rest) -> fmtty_of_custom arity (fmtty_of_fmt rest)
+ | Reader rest -> Reader_ty (fmtty_of_fmt rest)
+
+ | Format_arg (_, ty, rest) ->
+ Format_arg_ty (ty, fmtty_of_fmt rest)
+ | Format_subst (_, ty, rest) ->
+ Format_subst_ty (ty, ty, fmtty_of_fmt rest)
+
+ | Flush rest -> fmtty_of_fmt rest
+ | String_literal (_, rest) -> fmtty_of_fmt rest
+ | Char_literal (_, rest) -> fmtty_of_fmt rest
+
+ | Scan_char_set (_, _, rest) -> String_ty (fmtty_of_fmt rest)
+ | Scan_get_counter (_, rest) -> Int_ty (fmtty_of_fmt rest)
+ | Scan_next_char rest -> Char_ty (fmtty_of_fmt rest)
+ | Ignored_param (ign, rest) -> fmtty_of_ignored_format ign rest
+ | Formatting_lit (_, rest) -> fmtty_of_fmt rest
+ | Formatting_gen (fmting_gen, rest) ->
+ concat_fmtty (fmtty_of_formatting_gen fmting_gen) (fmtty_of_fmt rest)
+
+ | End_of_format -> End_of_fmtty
+
+and fmtty_of_custom : type x y a b c d e f .
+ (a, x, y) custom_arity -> (a, b, c, d, e, f) fmtty ->
+ (y, b, c, d, e, f) fmtty =
+fun arity fmtty -> match arity with
+ | Custom_zero -> fmtty
+ | Custom_succ arity -> Any_ty (fmtty_of_custom arity fmtty)
+
+(* Extract the fmtty of an ignored parameter followed by the rest of
+ the format. *)
+and fmtty_of_ignored_format : type x y a b c d e f .
+ (a, b, c, d, y, x) ignored ->
+ (x, b, c, y, e, f) fmt ->
+ (a, b, c, d, e, f) fmtty =
+fun ign fmt -> match ign with
+ | Ignored_char -> fmtty_of_fmt fmt
+ | Ignored_caml_char -> fmtty_of_fmt fmt
+ | Ignored_string _ -> fmtty_of_fmt fmt
+ | Ignored_caml_string _ -> fmtty_of_fmt fmt
+ | Ignored_int (_, _) -> fmtty_of_fmt fmt
+ | Ignored_int32 (_, _) -> fmtty_of_fmt fmt
+ | Ignored_nativeint (_, _) -> fmtty_of_fmt fmt
+ | Ignored_int64 (_, _) -> fmtty_of_fmt fmt
+ | Ignored_float (_, _) -> fmtty_of_fmt fmt
+ | Ignored_bool -> fmtty_of_fmt fmt
+ | Ignored_format_arg _ -> fmtty_of_fmt fmt
+ | Ignored_format_subst (_, fmtty) -> concat_fmtty fmtty (fmtty_of_fmt fmt)
+ | Ignored_reader -> Ignored_reader_ty (fmtty_of_fmt fmt)
+ | Ignored_scan_char_set _ -> fmtty_of_fmt fmt
+ | Ignored_scan_get_counter _ -> fmtty_of_fmt fmt
+ | Ignored_scan_next_char -> fmtty_of_fmt fmt
+
+(* Add an Int_ty node if padding is taken as an extra argument (ex: "%*s"). *)
+and fmtty_of_padding_fmtty : type x a b c d e f .
+ (x, a) padding -> (a, b, c, d, e, f) fmtty -> (x, b, c, d, e, f) fmtty =
+ fun pad fmtty -> match pad with
+ | No_padding -> fmtty
+ | Lit_padding _ -> fmtty
+ | Arg_padding _ -> Int_ty fmtty
+
+(* Add an Int_ty node if precision is taken as an extra argument (ex: "%.*f").*)
+and fmtty_of_precision_fmtty : type x a b c d e f .
+ (x, a) precision -> (a, b, c, d, e, f) fmtty -> (x, b, c, d, e, f) fmtty =
+ fun prec fmtty -> match prec with
+ | No_precision -> fmtty
+ | Lit_precision _ -> fmtty
+ | Arg_precision -> Int_ty fmtty
+
+(******************************************************************************)
+ (* Format typing *)
+
+(* Exception raised when a format does not match a given format type. *)
+exception Type_mismatch
+
+(* Type a padding. *)
+(* Take an Int_ty from the fmtty if the integer should be kept as argument. *)
+(* Raise Type_mismatch in case of type mismatch. *)
+let type_padding : type a b c d e f x y .
+ (x, y) padding -> (a, b, c, d, e, f) fmtty ->
+ (a, b, c, d, e, f) padding_fmtty_ebb =
+fun pad fmtty -> match pad, fmtty with
+ | No_padding, _ -> Padding_fmtty_EBB (No_padding, fmtty)
+ | Lit_padding (padty, w), _ -> Padding_fmtty_EBB (Lit_padding (padty,w),fmtty)
+ | Arg_padding padty, Int_ty rest -> Padding_fmtty_EBB (Arg_padding padty,rest)
+ | _ -> raise Type_mismatch
+
+(* Convert a (upadding, uprecision) to a (padding, precision). *)
+(* Take one or two Int_ty from the fmtty if needed. *)
+(* Raise Type_mismatch in case of type mismatch. *)
+let type_padprec : type a b c d e f x y z .
+ (x, y) padding -> (y, z) precision -> (a, b, c, d, e, f) fmtty ->
+ (a, b, c, d, e, f) padprec_fmtty_ebb =
+fun pad prec fmtty -> match prec, type_padding pad fmtty with
+ | No_precision, Padding_fmtty_EBB (pad, rest) ->
+ Padprec_fmtty_EBB (pad, No_precision, rest)
+ | Lit_precision p, Padding_fmtty_EBB (pad, rest) ->
+ Padprec_fmtty_EBB (pad, Lit_precision p, rest)
+ | Arg_precision, Padding_fmtty_EBB (pad, Int_ty rest) ->
+ Padprec_fmtty_EBB (pad, Arg_precision, rest)
+ | _, Padding_fmtty_EBB (_, _) -> raise Type_mismatch
+
+(* Type a format according to an fmtty. *)
+(* If typing succeed, generate a copy of the format with the same
+ type parameters as the fmtty. *)
+(* Raise a Failure with an error message in case of type mismatch. *)
+let rec type_format :
+ type a1 b1 c1 d1 e1 f1
+ a2 b2 c2 d2 e2 f2 .
+ (a1, b1, c1, d1, e1, f1) fmt
+ -> (a2, b2, c2, d2, e2, f2) fmtty
+ -> (a2, b2, c2, d2, e2, f2) fmt
+= fun fmt fmtty -> match type_format_gen fmt fmtty with
+ | Fmt_fmtty_EBB (fmt', End_of_fmtty) -> fmt'
+ | _ -> raise Type_mismatch
+
+and type_format_gen :
+ type a1 b1 c1 d1 e1 f1
+ a2 b2 c2 d2 e2 f2 .
+ (a1, b1, c1, d1, e1, f1) fmt
+ -> (a2, b2, c2, d2, e2, f2) fmtty
+ -> (a2, b2, c2, d2, e2, f2) fmt_fmtty_ebb
+= fun fmt fmtty -> match fmt, fmtty with
+ | Char fmt_rest, Char_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Char fmt', fmtty')
+ | Caml_char fmt_rest, Char_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Caml_char fmt', fmtty')
+ | String (pad, fmt_rest), _ -> (
+ match type_padding pad fmtty with
+ | Padding_fmtty_EBB (pad, String_ty fmtty_rest) ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (String (pad, fmt'), fmtty')
+ | Padding_fmtty_EBB (_, _) -> raise Type_mismatch
+ )
+ | Caml_string (pad, fmt_rest), _ -> (
+ match type_padding pad fmtty with
+ | Padding_fmtty_EBB (pad, String_ty fmtty_rest) ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Caml_string (pad, fmt'), fmtty')
+ | Padding_fmtty_EBB (_, _) -> raise Type_mismatch
+ )
+ | Int (iconv, pad, prec, fmt_rest), _ -> (
+ match type_padprec pad prec fmtty with
+ | Padprec_fmtty_EBB (pad, prec, Int_ty fmtty_rest) ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Int (iconv, pad, prec, fmt'), fmtty')
+ | Padprec_fmtty_EBB (_, _, _) -> raise Type_mismatch
+ )
+ | Int32 (iconv, pad, prec, fmt_rest), _ -> (
+ match type_padprec pad prec fmtty with
+ | Padprec_fmtty_EBB (pad, prec, Int32_ty fmtty_rest) ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Int32 (iconv, pad, prec, fmt'), fmtty')
+ | Padprec_fmtty_EBB (_, _, _) -> raise Type_mismatch
+ )
+ | Nativeint (iconv, pad, prec, fmt_rest), _ -> (
+ match type_padprec pad prec fmtty with
+ | Padprec_fmtty_EBB (pad, prec, Nativeint_ty fmtty_rest) ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Nativeint (iconv, pad, prec, fmt'), fmtty')
+ | Padprec_fmtty_EBB (_, _, _) -> raise Type_mismatch
+ )
+ | Int64 (iconv, pad, prec, fmt_rest), _ -> (
+ match type_padprec pad prec fmtty with
+ | Padprec_fmtty_EBB (pad, prec, Int64_ty fmtty_rest) ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Int64 (iconv, pad, prec, fmt'), fmtty')
+ | Padprec_fmtty_EBB (_, _, _) -> raise Type_mismatch
+ )
+ | Float (fconv, pad, prec, fmt_rest), _ -> (
+ match type_padprec pad prec fmtty with
+ | Padprec_fmtty_EBB (pad, prec, Float_ty fmtty_rest) ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Float (fconv, pad, prec, fmt'), fmtty')
+ | Padprec_fmtty_EBB (_, _, _) -> raise Type_mismatch
+ )
+ | Bool fmt_rest, Bool_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Bool fmt', fmtty')
+ | Flush fmt_rest, fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Flush fmt', fmtty')
+
+ | String_literal (str, fmt_rest), fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (String_literal (str, fmt'), fmtty')
+ | Char_literal (chr, fmt_rest), fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Char_literal (chr, fmt'), fmtty')
+
+ | Format_arg (pad_opt, sub_fmtty, fmt_rest),
+ Format_arg_ty (sub_fmtty', fmtty_rest) ->
+ if Fmtty_EBB sub_fmtty <> Fmtty_EBB sub_fmtty' then raise Type_mismatch;
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Format_arg (pad_opt, sub_fmtty', fmt'), fmtty')
+ | Format_subst (pad_opt, sub_fmtty, fmt_rest),
+ Format_subst_ty (sub_fmtty1, _sub_fmtty2, fmtty_rest) ->
+ if Fmtty_EBB (erase_rel sub_fmtty) <> Fmtty_EBB (erase_rel sub_fmtty1) then
+ raise Type_mismatch;
+ let Fmt_fmtty_EBB (fmt', fmtty') =
+ type_format_gen fmt_rest (erase_rel fmtty_rest)
+ in
+ Fmt_fmtty_EBB (Format_subst (pad_opt, sub_fmtty1, fmt'), fmtty')
+ (* Printf and Format specific constructors: *)
+ | Alpha fmt_rest, Alpha_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Alpha fmt', fmtty')
+ | Theta fmt_rest, Theta_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Theta fmt', fmtty')
+
+ (* Format specific constructors: *)
+ | Formatting_lit (formatting_lit, fmt_rest), fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Formatting_lit (formatting_lit, fmt'), fmtty')
+ | Formatting_gen (formatting_gen, fmt_rest), fmtty_rest ->
+ type_formatting_gen formatting_gen fmt_rest fmtty_rest
+
+ (* Scanf specific constructors: *)
+ | Reader fmt_rest, Reader_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Reader fmt', fmtty')
+ | Scan_char_set (width_opt, char_set, fmt_rest), String_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Scan_char_set (width_opt, char_set, fmt'), fmtty')
+ | Scan_get_counter (counter, fmt_rest), Int_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt_rest fmtty_rest in
+ Fmt_fmtty_EBB (Scan_get_counter (counter, fmt'), fmtty')
+ | Ignored_param (ign, rest), fmtty_rest ->
+ type_ignored_param ign rest fmtty_rest
+
+ | End_of_format, fmtty_rest -> Fmt_fmtty_EBB (End_of_format, fmtty_rest)
+
+ | _ -> raise Type_mismatch
+
+and type_formatting_gen : type a1 a3 b1 b3 c1 c3 d1 d3 e1 e2 e3 f1 f2 f3 .
+ (a1, b1, c1, d1, e1, f1) formatting_gen ->
+ (f1, b1, c1, e1, e2, f2) fmt ->
+ (a3, b3, c3, d3, e3, f3) fmtty ->
+ (a3, b3, c3, d3, e3, f3) fmt_fmtty_ebb =
+fun formatting_gen fmt0 fmtty0 -> match formatting_gen with
+ | Open_tag (Format (fmt1, str)) ->
+ let Fmt_fmtty_EBB (fmt2, fmtty2) = type_format_gen fmt1 fmtty0 in
+ let Fmt_fmtty_EBB (fmt3, fmtty3) = type_format_gen fmt0 fmtty2 in
+ Fmt_fmtty_EBB (Formatting_gen (Open_tag (Format (fmt2, str)), fmt3), fmtty3)
+ | Open_box (Format (fmt1, str)) ->
+ let Fmt_fmtty_EBB (fmt2, fmtty2) = type_format_gen fmt1 fmtty0 in
+ let Fmt_fmtty_EBB (fmt3, fmtty3) = type_format_gen fmt0 fmtty2 in
+ Fmt_fmtty_EBB (Formatting_gen (Open_box (Format (fmt2, str)), fmt3), fmtty3)
+
+(* Type an Ignored_param node according to an fmtty. *)
+and type_ignored_param : type p q x y z t u v a b c d e f .
+ (x, y, z, t, q, p) ignored ->
+ (p, y, z, q, u, v) fmt ->
+ (a, b, c, d, e, f) fmtty ->
+ (a, b, c, d, e, f) fmt_fmtty_ebb =
+fun ign fmt fmtty -> match ign with
+ | Ignored_char as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_caml_char as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_string _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_caml_string _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_int _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_int32 _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_nativeint _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_int64 _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_float _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_bool as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_scan_char_set _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_scan_get_counter _ as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_scan_next_char as ign' -> type_ignored_param_one ign' fmt fmtty
+ | Ignored_format_arg (pad_opt, sub_fmtty) ->
+ type_ignored_param_one (Ignored_format_arg (pad_opt, sub_fmtty)) fmt fmtty
+ | Ignored_format_subst (pad_opt, sub_fmtty) ->
+ let Fmtty_fmt_EBB (sub_fmtty', Fmt_fmtty_EBB (fmt', fmtty')) =
+ type_ignored_format_substitution sub_fmtty fmt fmtty in
+ Fmt_fmtty_EBB (Ignored_param (Ignored_format_subst (pad_opt, sub_fmtty'),
+ fmt'),
+ fmtty')
+ | Ignored_reader -> (
+ match fmtty with
+ | Ignored_reader_ty fmtty_rest ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt fmtty_rest in
+ Fmt_fmtty_EBB (Ignored_param (Ignored_reader, fmt'), fmtty')
+ | _ -> raise Type_mismatch
+ )
+
+and type_ignored_param_one : type a1 a2 b1 b2 c1 c2 d1 d2 e1 e2 f1 f2 .
+ (a2, b2, c2, d2, d2, a2) ignored ->
+ (a1, b1, c1, d1, e1, f1) fmt ->
+ (a2, b2, c2, d2, e2, f2) fmtty ->
+ (a2, b2, c2, d2, e2, f2) fmt_fmtty_ebb
+= fun ign fmt fmtty ->
+ let Fmt_fmtty_EBB (fmt', fmtty') = type_format_gen fmt fmtty in
+ Fmt_fmtty_EBB (Ignored_param (ign, fmt'), fmtty')
+
+(* Typing of the complex case: "%_(...%)". *)
+and type_ignored_format_substitution : type w x y z p s t u a b c d e f .
+ (w, x, y, z, s, p) fmtty ->
+ (p, x, y, s, t, u) fmt ->
+ (a, b, c, d, e, f) fmtty -> (a, b, c, d, e, f) fmtty_fmt_ebb =
+fun sub_fmtty fmt fmtty -> match sub_fmtty, fmtty with
+ | Char_ty sub_fmtty_rest, Char_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Char_ty sub_fmtty_rest', fmt')
+ | String_ty sub_fmtty_rest, String_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (String_ty sub_fmtty_rest', fmt')
+ | Int_ty sub_fmtty_rest, Int_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Int_ty sub_fmtty_rest', fmt')
+ | Int32_ty sub_fmtty_rest, Int32_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Int32_ty sub_fmtty_rest', fmt')
+ | Nativeint_ty sub_fmtty_rest, Nativeint_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Nativeint_ty sub_fmtty_rest', fmt')
+ | Int64_ty sub_fmtty_rest, Int64_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Int64_ty sub_fmtty_rest', fmt')
+ | Float_ty sub_fmtty_rest, Float_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Float_ty sub_fmtty_rest', fmt')
+ | Bool_ty sub_fmtty_rest, Bool_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Bool_ty sub_fmtty_rest', fmt')
+ | Alpha_ty sub_fmtty_rest, Alpha_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Alpha_ty sub_fmtty_rest', fmt')
+ | Theta_ty sub_fmtty_rest, Theta_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Theta_ty sub_fmtty_rest', fmt')
+ | Reader_ty sub_fmtty_rest, Reader_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Reader_ty sub_fmtty_rest', fmt')
+ | Ignored_reader_ty sub_fmtty_rest, Ignored_reader_ty fmtty_rest ->
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Ignored_reader_ty sub_fmtty_rest', fmt')
+
+ | Format_arg_ty (sub2_fmtty, sub_fmtty_rest),
+ Format_arg_ty (sub2_fmtty', fmtty_rest) ->
+ if Fmtty_EBB sub2_fmtty <> Fmtty_EBB sub2_fmtty' then raise Type_mismatch;
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution sub_fmtty_rest fmt fmtty_rest in
+ Fmtty_fmt_EBB (Format_arg_ty (sub2_fmtty', sub_fmtty_rest'), fmt')
+ | Format_subst_ty (sub1_fmtty, sub2_fmtty, sub_fmtty_rest),
+ Format_subst_ty (sub1_fmtty', sub2_fmtty', fmtty_rest) ->
+ (* TODO define Fmtty_rel_EBB to remove those erase_rel *)
+ if Fmtty_EBB (erase_rel sub1_fmtty) <> Fmtty_EBB (erase_rel sub1_fmtty')
+ then raise Type_mismatch;
+ if Fmtty_EBB (erase_rel sub2_fmtty) <> Fmtty_EBB (erase_rel sub2_fmtty')
+ then raise Type_mismatch;
+ let sub_fmtty' = trans (symm sub1_fmtty') sub2_fmtty' in
+ let _, f2, _, f4 = fmtty_rel_det sub_fmtty' in
+ let Refl = f2 Refl in
+ let Refl = f4 Refl in
+ let Fmtty_fmt_EBB (sub_fmtty_rest', fmt') =
+ type_ignored_format_substitution (erase_rel sub_fmtty_rest) fmt fmtty_rest
+ in
+ Fmtty_fmt_EBB (Format_subst_ty (sub1_fmtty', sub2_fmtty',
+ symm sub_fmtty_rest'),
+ fmt')
+ | End_of_fmtty, fmtty ->
+ Fmtty_fmt_EBB (End_of_fmtty, type_format_gen fmt fmtty)
+ | _ -> raise Type_mismatch
+
+(* This implementation of `recast` is a bit disappointing. The
+ invariant provided by the type are very strong: the input format's
+ type is in relation to the output type's as witnessed by the
+ fmtty_rel argument. One would at first expect this function to be
+ total, and implementable by exhaustive pattern matching. Instead,
+ we reuse the highly partial and much less well-defined function
+ `type_format` that has lost all knowledge of the correspondence
+ between the argument's types.
+
+ Besides the fact that this function reuses a lot of the
+ `type_format` logic (eg.: seeing Int_ty in the fmtty parameter does
+ not let you match on Int only, as you may in fact have Float
+ (Arg_padding, ...) ("%.*d") beginning with an Int_ty), it is also
+ a partial function, because the typing information in a format is
+ not quite enough to reconstruct it unambiguously. For example, the
+ format types of "%d%_r" and "%_r%d" have the same format6
+ parameters, but they are not at all exchangeable, and putting one
+ in place of the other must result in a dynamic failure.
+
+ Given that:
+ - we'd have to duplicate a lot of non-trivial typing logic from type_format
+ - this wouldn't even eliminate (all) the dynamic failures
+ we decided to just reuse type_format directly for now.
+*)
+let recast :
+ type a1 b1 c1 d1 e1 f1
+ a2 b2 c2 d2 e2 f2
+ .
+ (a1, b1, c1, d1, e1, f1) fmt
+ -> (a1, b1, c1, d1, e1, f1,
+ a2, b2, c2, d2, e2, f2) fmtty_rel
+ -> (a2, b2, c2, d2, e2, f2) fmt
+= fun fmt fmtty ->
+ type_format fmt (erase_rel (symm fmtty))
+
+(******************************************************************************)
+ (* Printing tools *)
+
+(* Add padding spaces arround a string. *)
+let fix_padding padty width str =
+ let len = String.length str in
+ let width, padty =
+ abs width,
+ (* while literal padding widths are always non-negative,
+ dynamically-set widths (Arg_padding, eg. %*d) may be negative;
+ we interpret those as specifying a padding-to-the-left; this
+ means that '0' may get dropped even if it was explicitly set,
+ but:
+ - this is what the legacy implementation does, and
+ we preserve compatibility if possible
+ - we could only signal this issue by failing at runtime,
+ which is not very nice... *)
+ if width < 0 then Left else padty in
+ if width <= len then str else
+ let res = Bytes.make width (if padty = Zeros then '0' else ' ') in
+ begin match padty with
+ | Left -> String.blit str 0 res 0 len
+ | Right -> String.blit str 0 res (width - len) len
+ | Zeros when len > 0 && (str.[0] = '+' || str.[0] = '-' || str.[0] = ' ') ->
+ Bytes.set res 0 str.[0];
+ String.blit str 1 res (width - len + 1) (len - 1)
+ | Zeros when len > 1 && str.[0] = '0' && (str.[1] = 'x' || str.[1] = 'X') ->
+ Bytes.set res 1 str.[1];
+ String.blit str 2 res (width - len + 2) (len - 2)
+ | Zeros ->
+ String.blit str 0 res (width - len) len
+ end;
+ Bytes.unsafe_to_string res
+
+(* Add '0' padding to int, int32, nativeint or int64 string representation. *)
+let fix_int_precision prec str =
+ let prec = abs prec in
+ let len = String.length str in
+ match str.[0] with
+ | ('+' | '-' | ' ') as c when prec + 1 > len ->
+ let res = Bytes.make (prec + 1) '0' in
+ Bytes.set res 0 c;
+ String.blit str 1 res (prec - len + 2) (len - 1);
+ Bytes.unsafe_to_string res
+ | '0' when prec + 2 > len && len > 1 && (str.[1] = 'x' || str.[1] = 'X') ->
+ let res = Bytes.make (prec + 2) '0' in
+ Bytes.set res 1 str.[1];
+ String.blit str 2 res (prec - len + 4) (len - 2);
+ Bytes.unsafe_to_string res
+ | '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' when prec > len ->
+ let res = Bytes.make prec '0' in
+ String.blit str 0 res (prec - len) len;
+ Bytes.unsafe_to_string res
+ | _ ->
+ str
+
+(* Escape a string according to the OCaml lexing convention. *)
+let string_to_caml_string str =
+ let str = String.escaped str in
+ let l = String.length str in
+ let res = Bytes.make (l + 2) '\"' in
+ String.unsafe_blit str 0 res 1 l;
+ Bytes.unsafe_to_string res
+
+(* Generate the format_int/int32/nativeint/int64 first argument
+ from an int_conv. *)
+let format_of_iconv = function
+ | Int_d -> "%d" | Int_pd -> "%+d" | Int_sd -> "% d"
+ | Int_i -> "%i" | Int_pi -> "%+i" | Int_si -> "% i"
+ | Int_x -> "%x" | Int_Cx -> "%#x"
+ | Int_X -> "%X" | Int_CX -> "%#X"
+ | Int_o -> "%o" | Int_Co -> "%#o"
+ | Int_u -> "%u"
+
+let format_of_iconvL = function
+ | Int_d -> "%Ld" | Int_pd -> "%+Ld" | Int_sd -> "% Ld"
+ | Int_i -> "%Li" | Int_pi -> "%+Li" | Int_si -> "% Li"
+ | Int_x -> "%Lx" | Int_Cx -> "%#Lx"
+ | Int_X -> "%LX" | Int_CX -> "%#LX"
+ | Int_o -> "%Lo" | Int_Co -> "%#Lo"
+ | Int_u -> "%Lu"
+
+let format_of_iconvl = function
+ | Int_d -> "%ld" | Int_pd -> "%+ld" | Int_sd -> "% ld"
+ | Int_i -> "%li" | Int_pi -> "%+li" | Int_si -> "% li"
+ | Int_x -> "%lx" | Int_Cx -> "%#lx"
+ | Int_X -> "%lX" | Int_CX -> "%#lX"
+ | Int_o -> "%lo" | Int_Co -> "%#lo"
+ | Int_u -> "%lu"
+
+let format_of_iconvn = function
+ | Int_d -> "%nd" | Int_pd -> "%+nd" | Int_sd -> "% nd"
+ | Int_i -> "%ni" | Int_pi -> "%+ni" | Int_si -> "% ni"
+ | Int_x -> "%nx" | Int_Cx -> "%#nx"
+ | Int_X -> "%nX" | Int_CX -> "%#nX"
+ | Int_o -> "%no" | Int_Co -> "%#no"
+ | Int_u -> "%nu"
+
+(* Generate the format_float first argument form a float_conv. *)
+let format_of_fconv fconv prec =
+ if fconv = Float_F then "%.12g" else
+ let prec = abs prec in
+ let symb = char_of_fconv fconv in
+ let buf = buffer_create 16 in
+ buffer_add_char buf '%';
+ bprint_fconv_flag buf fconv;
+ buffer_add_char buf '.';
+ buffer_add_string buf (string_of_int prec);
+ buffer_add_char buf symb;
+ buffer_contents buf
+
+(* Convert an integer to a string according to a conversion. *)
+let convert_int iconv n = format_int (format_of_iconv iconv) n
+let convert_int32 iconv n = format_int32 (format_of_iconvl iconv) n
+let convert_nativeint iconv n = format_nativeint (format_of_iconvn iconv) n
+let convert_int64 iconv n = format_int64 (format_of_iconvL iconv) n
+
+(* Convert a float to string. *)
+(* Fix special case of "OCaml float format". *)
+let convert_float fconv prec x =
+ let prec = abs prec in
+ let str = format_float (format_of_fconv fconv prec) x in
+ if fconv <> Float_F then str else
+ let len = String.length str in
+ let rec is_valid i =
+ if i = len then false else
+ match str.[i] with
+ | '.' | 'e' | 'E' -> true
+ | _ -> is_valid (i + 1)
+ in
+ match classify_float x with
+ | FP_normal | FP_subnormal | FP_zero ->
+ if is_valid 0 then str else str ^ "."
+ | FP_infinite ->
+ if x < 0.0 then "neg_infinity" else "infinity"
+ | FP_nan -> "nan"
+
+(* Convert a char to a string according to the OCaml lexical convention. *)
+let format_caml_char c =
+ let str = Char.escaped c in
+ let l = String.length str in
+ let res = Bytes.make (l + 2) '\'' in
+ String.unsafe_blit str 0 res 1 l;
+ Bytes.unsafe_to_string res
+
+(* Convert a format type to string *)
+let string_of_fmtty fmtty =
+ let buf = buffer_create 16 in
+ bprint_fmtty buf fmtty;
+ buffer_contents buf
+
+(******************************************************************************)
+ (* Generic printing function *)
+
+(* Make a generic printing function. *)
+(* Used to generate Printf and Format printing functions. *)
+(* Parameters:
+ k: a continuation finally applied to the output stream and the accumulator.
+ o: the output stream (see k, %a and %t).
+ acc: rev list of printing entities (string, char, flush, formatting, ...).
+ fmt: the format. *)
+let rec make_printf : type a b c d e f .
+ (b -> (b, c) acc -> f) -> b -> (b, c) acc ->
+ (a, b, c, d, e, f) fmt -> a =
+fun k o acc fmt -> match fmt with
+ | Char rest ->
+ fun c ->
+ let new_acc = Acc_data_char (acc, c) in
+ make_printf k o new_acc rest
+ | Caml_char rest ->
+ fun c ->
+ let new_acc = Acc_data_string (acc, format_caml_char c) in
+ make_printf k o new_acc rest
+ | String (pad, rest) ->
+ make_string_padding k o acc rest pad (fun str -> str)
+ | Caml_string (pad, rest) ->
+ make_string_padding k o acc rest pad string_to_caml_string
+ | Int (iconv, pad, prec, rest) ->
+ make_int_padding_precision k o acc rest pad prec convert_int iconv
+ | Int32 (iconv, pad, prec, rest) ->
+ make_int_padding_precision k o acc rest pad prec convert_int32 iconv
+ | Nativeint (iconv, pad, prec, rest) ->
+ make_int_padding_precision k o acc rest pad prec convert_nativeint iconv
+ | Int64 (iconv, pad, prec, rest) ->
+ make_int_padding_precision k o acc rest pad prec convert_int64 iconv
+ | Float (fconv, pad, prec, rest) ->
+ make_float_padding_precision k o acc rest pad prec fconv
+ | Bool rest ->
+ fun b -> make_printf k o (Acc_data_string (acc, string_of_bool b)) rest
+ | Alpha rest ->
+ fun f x -> make_printf k o (Acc_delay (acc, fun o -> f o x)) rest
+ | Theta rest ->
+ fun f -> make_printf k o (Acc_delay (acc, f)) rest
+ | Custom (arity, f, rest) ->
+ make_custom k o acc rest arity (f ())
+ | Reader _ ->
+ (* This case is impossible, by typing of formats. *)
+ (* Indeed, since printf and co. take a format4 as argument, the 'd and 'e
+ type parameters of fmt are obviously equals. The Reader is the
+ only constructor which touch 'd and 'e type parameters of the format
+ type, it adds an (->) to the 'd parameters. Consequently, a format4
+ cannot contain a Reader node, except in the sub-format associated to
+ an %{...%}. It's not a problem because make_printf do not call
+ itself recursively on the sub-format associated to %{...%}. *)
+ assert false
+ | Flush rest ->
+ make_printf k o (Acc_flush acc) rest
+
+ | String_literal (str, rest) ->
+ make_printf k o (Acc_string_literal (acc, str)) rest
+ | Char_literal (chr, rest) ->
+ make_printf k o (Acc_char_literal (acc, chr)) rest
+
+ | Format_arg (_, sub_fmtty, rest) ->
+ let ty = string_of_fmtty sub_fmtty in
+ (fun str ->
+ ignore str;
+ make_printf k o (Acc_data_string (acc, ty)) rest)
+ | Format_subst (_, fmtty, rest) ->
+ fun (Format (fmt, _)) -> make_printf k o acc
+ (concat_fmt (recast fmt fmtty) rest)
+
+ | Scan_char_set (_, _, rest) ->
+ let new_acc = Acc_invalid_arg (acc, "Printf: bad conversion %[") in
+ fun _ -> make_printf k o new_acc rest
+ | Scan_get_counter (_, rest) ->
+ (* This case should be refused for Printf. *)
+ (* Accepted for backward compatibility. *)
+ (* Interpret %l, %n and %L as %u. *)
+ fun n ->
+ let new_acc = Acc_data_string (acc, format_int "%u" n) in
+ make_printf k o new_acc rest
+ | Scan_next_char rest ->
+ fun c ->
+ let new_acc = Acc_data_char (acc, c) in
+ make_printf k o new_acc rest
+ | Ignored_param (ign, rest) ->
+ make_ignored_param k o acc ign rest
+
+ | Formatting_lit (fmting_lit, rest) ->
+ make_printf k o (Acc_formatting_lit (acc, fmting_lit)) rest
+ | Formatting_gen (Open_tag (Format (fmt', _)), rest) ->
+ let k' koc kacc =
+ make_printf k koc (Acc_formatting_gen (acc, Acc_open_tag kacc)) rest in
+ make_printf k' o End_of_acc fmt'
+ | Formatting_gen (Open_box (Format (fmt', _)), rest) ->
+ let k' koc kacc =
+ make_printf k koc (Acc_formatting_gen (acc, Acc_open_box kacc)) rest in
+ make_printf k' o End_of_acc fmt'
+
+ | End_of_format ->
+ k o acc
+
+(* Delay the error (Invalid_argument "Printf: bad conversion %_"). *)
+(* Generate functions to take remaining arguments (after the "%_"). *)
+and make_ignored_param : type x y a b c d e f .
+ (b -> (b, c) acc -> f) -> b -> (b, c) acc ->
+ (a, b, c, d, y, x) ignored ->
+ (x, b, c, y, e, f) fmt -> a =
+fun k o acc ign fmt -> match ign with
+ | Ignored_char -> make_invalid_arg k o acc fmt
+ | Ignored_caml_char -> make_invalid_arg k o acc fmt
+ | Ignored_string _ -> make_invalid_arg k o acc fmt
+ | Ignored_caml_string _ -> make_invalid_arg k o acc fmt
+ | Ignored_int (_, _) -> make_invalid_arg k o acc fmt
+ | Ignored_int32 (_, _) -> make_invalid_arg k o acc fmt
+ | Ignored_nativeint (_, _) -> make_invalid_arg k o acc fmt
+ | Ignored_int64 (_, _) -> make_invalid_arg k o acc fmt
+ | Ignored_float (_, _) -> make_invalid_arg k o acc fmt
+ | Ignored_bool -> make_invalid_arg k o acc fmt
+ | Ignored_format_arg _ -> make_invalid_arg k o acc fmt
+ | Ignored_format_subst (_, fmtty) -> make_from_fmtty k o acc fmtty fmt
+ | Ignored_reader -> assert false
+ | Ignored_scan_char_set _ -> make_invalid_arg k o acc fmt
+ | Ignored_scan_get_counter _ -> make_invalid_arg k o acc fmt
+ | Ignored_scan_next_char -> make_invalid_arg k o acc fmt
+
+
+(* Special case of printf "%_(". *)
+and make_from_fmtty : type x y a b c d e f .
+ (b -> (b, c) acc -> f) -> b -> (b, c) acc ->
+ (a, b, c, d, y, x) fmtty ->
+ (x, b, c, y, e, f) fmt -> a =
+fun k o acc fmtty fmt -> match fmtty with
+ | Char_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | String_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Int_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Int32_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Nativeint_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Int64_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Float_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Bool_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Alpha_ty rest -> fun _ _ -> make_from_fmtty k o acc rest fmt
+ | Theta_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Any_ty rest -> fun _ -> make_from_fmtty k o acc rest fmt
+ | Reader_ty _ -> assert false
+ | Ignored_reader_ty _ -> assert false
+ | Format_arg_ty (_, rest) -> fun _ -> make_from_fmtty k o acc rest fmt
+ | End_of_fmtty -> make_invalid_arg k o acc fmt
+ | Format_subst_ty (ty1, ty2, rest) ->
+ let ty = trans (symm ty1) ty2 in
+ fun _ -> make_from_fmtty k o acc (concat_fmtty ty rest) fmt
+
+(* Insert an Acc_invalid_arg in the accumulator and continue to generate
+ closures to get the remaining arguments. *)
+and make_invalid_arg : type a b c d e f .
+ (b -> (b, c) acc -> f) -> b -> (b, c) acc ->
+ (a, b, c, d, e, f) fmt -> a =
+fun k o acc fmt ->
+ make_printf k o (Acc_invalid_arg (acc, "Printf: bad conversion %_")) fmt
+
+(* Fix padding, take it as an extra integer argument if needed. *)
+and make_string_padding : type x z a b c d e f .
+ (b -> (b, c) acc -> f) -> b -> (b, c) acc ->
+ (a, b, c, d, e, f) fmt ->
+ (x, z -> a) padding -> (z -> string) -> x =
+ fun k o acc fmt pad trans -> match pad with
+ | No_padding ->
+ fun x ->
+ let new_acc = Acc_data_string (acc, trans x) in
+ make_printf k o new_acc fmt
+ | Lit_padding (padty, width) ->
+ fun x ->
+ let new_acc = Acc_data_string (acc, fix_padding padty width (trans x)) in
+ make_printf k o new_acc fmt
+ | Arg_padding padty ->
+ fun w x ->
+ let new_acc = Acc_data_string (acc, fix_padding padty w (trans x)) in
+ make_printf k o new_acc fmt
+
+(* Fix padding and precision for int, int32, nativeint or int64. *)
+(* Take one or two extra integer arguments if needed. *)
+and make_int_padding_precision : type x y z a b c d e f .
+ (b -> (b, c) acc -> f) -> b -> (b, c) acc ->
+ (a, b, c, d, e, f) fmt ->
+ (x, y) padding -> (y, z -> a) precision -> (int_conv -> z -> string) ->
+ int_conv -> x =
+ fun k o acc fmt pad prec trans iconv -> match pad, prec with
+ | No_padding, No_precision ->
+ fun x ->
+ let str = trans iconv x in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | No_padding, Lit_precision p ->
+ fun x ->
+ let str = fix_int_precision p (trans iconv x) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | No_padding, Arg_precision ->
+ fun p x ->
+ let str = fix_int_precision p (trans iconv x) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Lit_padding (padty, w), No_precision ->
+ fun x ->
+ let str = fix_padding padty w (trans iconv x) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Lit_padding (padty, w), Lit_precision p ->
+ fun x ->
+ let str = fix_padding padty w (fix_int_precision p (trans iconv x)) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Lit_padding (padty, w), Arg_precision ->
+ fun p x ->
+ let str = fix_padding padty w (fix_int_precision p (trans iconv x)) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Arg_padding padty, No_precision ->
+ fun w x ->
+ let str = fix_padding padty w (trans iconv x) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Arg_padding padty, Lit_precision p ->
+ fun w x ->
+ let str = fix_padding padty w (fix_int_precision p (trans iconv x)) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Arg_padding padty, Arg_precision ->
+ fun w p x ->
+ let str = fix_padding padty w (fix_int_precision p (trans iconv x)) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+
+(* Convert a float, fix padding and precision if needed. *)
+(* Take the float argument and one or two extra integer arguments if needed. *)
+and make_float_padding_precision : type x y a b c d e f .
+ (b -> (b, c) acc -> f) -> b -> (b, c) acc ->
+ (a, b, c, d, e, f) fmt ->
+ (x, y) padding -> (y, float -> a) precision -> float_conv -> x =
+ fun k o acc fmt pad prec fconv -> match pad, prec with
+ | No_padding, No_precision ->
+ fun x ->
+ let str = convert_float fconv default_float_precision x in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | No_padding, Lit_precision p ->
+ fun x ->
+ let str = convert_float fconv p x in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | No_padding, Arg_precision ->
+ fun p x ->
+ let str = convert_float fconv p x in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Lit_padding (padty, w), No_precision ->
+ fun x ->
+ let str = convert_float fconv default_float_precision x in
+ let str' = fix_padding padty w str in
+ make_printf k o (Acc_data_string (acc, str')) fmt
+ | Lit_padding (padty, w), Lit_precision p ->
+ fun x ->
+ let str = fix_padding padty w (convert_float fconv p x) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Lit_padding (padty, w), Arg_precision ->
+ fun p x ->
+ let str = fix_padding padty w (convert_float fconv p x) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Arg_padding padty, No_precision ->
+ fun w x ->
+ let str = convert_float fconv default_float_precision x in
+ let str' = fix_padding padty w str in
+ make_printf k o (Acc_data_string (acc, str')) fmt
+ | Arg_padding padty, Lit_precision p ->
+ fun w x ->
+ let str = fix_padding padty w (convert_float fconv p x) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+ | Arg_padding padty, Arg_precision ->
+ fun w p x ->
+ let str = fix_padding padty w (convert_float fconv p x) in
+ make_printf k o (Acc_data_string (acc, str)) fmt
+
+and make_custom : type x y a b c d e f .
+ (b -> (b, c) acc -> f) -> b -> (b, c) acc ->
+ (a, b, c, d, e, f) fmt ->
+ (a, x, y) custom_arity -> x -> y =
+ fun k o acc rest arity f -> match arity with
+ | Custom_zero -> make_printf k o (Acc_data_string (acc, f)) rest
+ | Custom_succ arity ->
+ fun x ->
+ make_custom k o acc rest arity (f x)
+
+(******************************************************************************)
+ (* Continuations for make_printf *)
+
+(* Recursively output an "accumulator" containing a reversed list of
+ printing entities (string, char, flus, ...) in an output_stream. *)
+(* Used as a continuation of make_printf. *)
+let rec output_acc o acc = match acc with
+ | Acc_formatting_lit (p, fmting_lit) ->
+ let s = string_of_formatting_lit fmting_lit in
+ output_acc o p; output_string o s;
+ | Acc_formatting_gen (p, Acc_open_tag acc') ->
+ output_acc o p; output_string o "@{"; output_acc o acc';
+ | Acc_formatting_gen (p, Acc_open_box acc') ->
+ output_acc o p; output_string o "@["; output_acc o acc';
+ | Acc_string_literal (p, s)
+ | Acc_data_string (p, s) -> output_acc o p; output_string o s
+ | Acc_char_literal (p, c)
+ | Acc_data_char (p, c) -> output_acc o p; output_char o c
+ | Acc_delay (p, f) -> output_acc o p; f o
+ | Acc_flush p -> output_acc o p; flush o
+ | Acc_invalid_arg (p, msg) -> output_acc o p; invalid_arg msg;
+ | End_of_acc -> ()
+
+(* Recursively output an "accumulator" containing a reversed list of
+ printing entities (string, char, flus, ...) in a buffer. *)
+(* Used as a continuation of make_printf. *)
+let rec bufput_acc b acc = match acc with
+ | Acc_formatting_lit (p, fmting_lit) ->
+ let s = string_of_formatting_lit fmting_lit in
+ bufput_acc b p; Buffer.add_string b s;
+ | Acc_formatting_gen (p, Acc_open_tag acc') ->
+ bufput_acc b p; Buffer.add_string b "@{"; bufput_acc b acc';
+ | Acc_formatting_gen (p, Acc_open_box acc') ->
+ bufput_acc b p; Buffer.add_string b "@["; bufput_acc b acc';
+ | Acc_string_literal (p, s)
+ | Acc_data_string (p, s) -> bufput_acc b p; Buffer.add_string b s
+ | Acc_char_literal (p, c)
+ | Acc_data_char (p, c) -> bufput_acc b p; Buffer.add_char b c
+ | Acc_delay (p, f) -> bufput_acc b p; f b
+ | Acc_flush p -> bufput_acc b p;
+ | Acc_invalid_arg (p, msg) -> bufput_acc b p; invalid_arg msg;
+ | End_of_acc -> ()
+
+(* Recursively output an "accumulator" containing a reversed list of
+ printing entities (string, char, flus, ...) in a buffer. *)
+(* Differ from bufput_acc by the interpretation of %a and %t. *)
+(* Used as a continuation of make_printf. *)
+let rec strput_acc b acc = match acc with
+ | Acc_formatting_lit (p, fmting_lit) ->
+ let s = string_of_formatting_lit fmting_lit in
+ strput_acc b p; Buffer.add_string b s;
+ | Acc_formatting_gen (p, Acc_open_tag acc') ->
+ strput_acc b p; Buffer.add_string b "@{"; strput_acc b acc';
+ | Acc_formatting_gen (p, Acc_open_box acc') ->
+ strput_acc b p; Buffer.add_string b "@["; strput_acc b acc';
+ | Acc_string_literal (p, s)
+ | Acc_data_string (p, s) -> strput_acc b p; Buffer.add_string b s
+ | Acc_char_literal (p, c)
+ | Acc_data_char (p, c) -> strput_acc b p; Buffer.add_char b c
+ | Acc_delay (p, f) -> strput_acc b p; Buffer.add_string b (f ())
+ | Acc_flush p -> strput_acc b p;
+ | Acc_invalid_arg (p, msg) -> strput_acc b p; invalid_arg msg;
+ | End_of_acc -> ()
+
+(******************************************************************************)
+ (* Error managment *)
+
+(* Raise a Failure with a pretty-printed error message. *)
+let failwith_message (Format (fmt, _)) =
+ let buf = Buffer.create 256 in
+ let k () acc = strput_acc buf acc; failwith (Buffer.contents buf) in
+ make_printf k () End_of_acc fmt
+
+(******************************************************************************)
+ (* Formatting tools *)
+
+(* Convert a string to an open block description (indent, block_type) *)
+let open_box_of_string str =
+ if str = "" then (0, Pp_box) else
+ let len = String.length str in
+ let invalid_box () = failwith_message "invalid box description %S" str in
+ let rec parse_spaces i =
+ if i = len then i else
+ match str.[i] with
+ | ' ' | '\t' -> parse_spaces (i + 1)
+ | _ -> i
+ and parse_lword i j =
+ if j = len then j else
+ match str.[j] with
+ | 'a' .. 'z' -> parse_lword i (j + 1)
+ | _ -> j
+ and parse_int i j =
+ if j = len then j else
+ match str.[j] with
+ | '0' .. '9' | '-' -> parse_int i (j + 1)
+ | _ -> j in
+ let wstart = parse_spaces 0 in
+ let wend = parse_lword wstart wstart in
+ let box_name = String.sub str wstart (wend - wstart) in
+ let nstart = parse_spaces wend in
+ let nend = parse_int nstart nstart in
+ let indent =
+ if nstart = nend then 0 else
+ try int_of_string (String.sub str nstart (nend - nstart))
+ with Failure _ -> invalid_box () in
+ let exp_end = parse_spaces nend in
+ let () = if exp_end <> len then invalid_box () in
+ let box_type = match box_name with
+ | "" | "b" -> Pp_box
+ | "h" -> Pp_hbox
+ | "v" -> Pp_vbox
+ | "hv" -> Pp_hvbox
+ | "hov" -> Pp_hovbox
+ | _ -> invalid_box () in
+ (indent, box_type)
+
+(******************************************************************************)
+ (* Parsing tools *)
+
+(* Create a padding_fmt_ebb from a padding and a format. *)
+(* Copy the padding to disjoin the type parameters of argument and result. *)
+let make_padding_fmt_ebb : type x y .
+ (x, y) padding -> (_, _, _, _, _, _) fmt ->
+ (_, _, _, _, _) padding_fmt_ebb =
+fun pad fmt -> match pad with
+ | No_padding -> Padding_fmt_EBB (No_padding, fmt)
+ | Lit_padding (s, w) -> Padding_fmt_EBB (Lit_padding (s, w), fmt)
+ | Arg_padding s -> Padding_fmt_EBB (Arg_padding s, fmt)
+
+(* Create a precision_fmt_ebb from a precision and a format. *)
+(* Copy the precision to disjoin the type parameters of argument and result. *)
+let make_precision_fmt_ebb : type x y .
+ (x, y) precision -> (_, _, _, _, _, _) fmt ->
+ (_, _, _, _, _) precision_fmt_ebb =
+fun prec fmt -> match prec with
+ | No_precision -> Precision_fmt_EBB (No_precision, fmt)
+ | Lit_precision p -> Precision_fmt_EBB (Lit_precision p, fmt)
+ | Arg_precision -> Precision_fmt_EBB (Arg_precision, fmt)
+
+(* Create a padprec_fmt_ebb forma a padding, a precision and a format. *)
+(* Copy the padding and the precision to disjoin type parameters of arguments
+ and result. *)
+let make_padprec_fmt_ebb : type x y z t .
+ (x, y) padding -> (z, t) precision ->
+ (_, _, _, _, _, _) fmt ->
+ (_, _, _, _, _) padprec_fmt_ebb =
+fun pad prec fmt ->
+ let Precision_fmt_EBB (prec, fmt') = make_precision_fmt_ebb prec fmt in
+ match pad with
+ | No_padding -> Padprec_fmt_EBB (No_padding, prec, fmt')
+ | Lit_padding (s, w) -> Padprec_fmt_EBB (Lit_padding (s, w), prec, fmt')
+ | Arg_padding s -> Padprec_fmt_EBB (Arg_padding s, prec, fmt')
+
+(******************************************************************************)
+ (* Format parsing *)
+
+(* Parse a string representing a format and create a fmt_ebb. *)
+(* Raise an Failure exception in case of invalid format. *)
+let fmt_ebb_of_string ?legacy_behavior str =
+ (* Parameters naming convention: *)
+ (* - lit_start: start of the literal sequence. *)
+ (* - str_ind: current index in the string. *)
+ (* - end_ind: end of the current (sub-)format. *)
+ (* - pct_ind: index of the '%' in the current micro-format. *)
+ (* - zero: is the '0' flag defined in the current micro-format. *)
+ (* - minus: is the '-' flag defined in the current micro-format. *)
+ (* - plus: is the '+' flag defined in the current micro-format. *)
+ (* - sharp: is the '#' flag defined in the current micro-format. *)
+ (* - space: is the ' ' flag defined in the current micro-format. *)
+ (* - ign: is the '_' flag defined in the current micro-format. *)
+ (* - pad: padding of the current micro-format. *)
+ (* - prec: precision of the current micro-format. *)
+ (* - symb: char representing the conversion ('c', 's', 'd', ...). *)
+ (* - char_set: set of characters as bitmap (see scanf %[...]). *)
+
+ let legacy_behavior = match legacy_behavior with
+ | Some flag -> flag
+ | None -> true
+ (* When this flag is enabled, the format parser tries to behave as
+ the <4.02 implementations, in particular it ignores most benine
+ nonsensical format. When the flag is disabled, it will reject any
+ format that is not accepted by the specification.
+
+ A typical example would be "%+ d": specifying both '+' (if the
+ number is positive, pad with a '+' to get the same width as
+ negative numbres) and ' ' (if the number is positive, pad with
+ a space) does not make sense, but the legacy (< 4.02)
+ implementation was happy to just ignore the space.
+ *)
+ in
+
+ (* Raise a Failure with a friendly error message. *)
+ let invalid_format_message str_ind msg =
+ failwith_message
+ "invalid format %S: at character number %d, %s"
+ str str_ind msg;
+ in
+
+ (* Used when the end of the format (or the current sub-format) was encoutered
+ unexpectedly. *)
+ let unexpected_end_of_format end_ind =
+ invalid_format_message end_ind
+ "unexpected end of format"
+ in
+
+ (* Used for %0c: no other widths are implemented *)
+ let invalid_nonnull_char_width str_ind =
+ invalid_format_message str_ind
+ "non-zero widths are unsupported for %c conversions"
+ in
+ (* Raise Failure with a friendly error message about an option dependencie
+ problem. *)
+ let invalid_format_without str_ind c s =
+ failwith_message
+ "invalid format %S: at character number %d, '%c' without %s"
+ str str_ind c s
+ in
+
+ (* Raise Failure with a friendly error message about an unexpected
+ character. *)
+ let expected_character str_ind expected read =
+ failwith_message
+ "invalid format %S: at character number %d, %s expected, read %C"
+ str str_ind expected read
+ in
+
+ (* Parse the string from beg_ind (included) to end_ind (excluded). *)
+ let rec parse : type e f . int -> int -> (_, _, e, f) fmt_ebb =
+ fun beg_ind end_ind -> parse_literal beg_ind beg_ind end_ind
+
+ (* Read literal characters up to '%' or '@' special characters. *)
+ and parse_literal : type e f . int -> int -> int -> (_, _, e, f) fmt_ebb =
+ fun lit_start str_ind end_ind ->
+ if str_ind = end_ind then add_literal lit_start str_ind End_of_format else
+ match str.[str_ind] with
+ | '%' ->
+ let Fmt_EBB fmt_rest = parse_format str_ind end_ind in
+ add_literal lit_start str_ind fmt_rest
+ | '@' ->
+ let Fmt_EBB fmt_rest = parse_after_at (str_ind + 1) end_ind in
+ add_literal lit_start str_ind fmt_rest
+ | _ ->
+ parse_literal lit_start (str_ind + 1) end_ind
+
+ (* Parse a format after '%' *)
+ and parse_format : type e f . int -> int -> (_, _, e, f) fmt_ebb =
+ fun pct_ind end_ind -> parse_ign pct_ind (pct_ind + 1) end_ind
+
+ and parse_ign : type e f . int -> int -> int -> (_, _, e, f) fmt_ebb =
+ fun pct_ind str_ind end_ind ->
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind] with
+ | '_' -> parse_flags pct_ind (str_ind+1) end_ind true
+ | _ -> parse_flags pct_ind str_ind end_ind false
+
+ and parse_flags : type e f . int -> int -> int -> bool -> (_, _, e, f) fmt_ebb
+ =
+ fun pct_ind str_ind end_ind ign ->
+ let zero = ref false and minus = ref false
+ and plus = ref false and space = ref false
+ and sharp = ref false in
+ let set_flag str_ind flag =
+ (* in legacy mode, duplicate flags are accepted *)
+ if !flag && not legacy_behavior then
+ failwith_message
+ "invalid format %S: at character number %d, duplicate flag %C"
+ str str_ind str.[str_ind];
+ flag := true;
+ in
+ let rec read_flags str_ind =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ begin match str.[str_ind] with
+ | '0' -> set_flag str_ind zero; read_flags (str_ind + 1)
+ | '-' -> set_flag str_ind minus; read_flags (str_ind + 1)
+ | '+' -> set_flag str_ind plus; read_flags (str_ind + 1)
+ | '#' -> set_flag str_ind sharp; read_flags (str_ind + 1)
+ | ' ' -> set_flag str_ind space; read_flags (str_ind + 1)
+ | _ ->
+ parse_padding pct_ind str_ind end_ind
+ !zero !minus !plus !sharp !space ign
+ end
+ in
+ read_flags str_ind
+
+ (* Try to read a digital or a '*' padding. *)
+ and parse_padding : type e f .
+ int -> int -> int -> bool -> bool -> bool -> bool -> bool -> bool ->
+ (_, _, e, f) fmt_ebb =
+ fun pct_ind str_ind end_ind zero minus plus sharp space ign ->
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ let padty = match zero, minus with
+ | false, false -> Right
+ | false, true -> Left
+ | true, false -> Zeros
+ | true, true ->
+ if legacy_behavior then Left
+ else incompatible_flag pct_ind str_ind '-' "0" in
+ match str.[str_ind] with
+ | '0' .. '9' ->
+ let new_ind, width = parse_positive str_ind end_ind 0 in
+ parse_after_padding pct_ind new_ind end_ind minus plus sharp space ign
+ (Lit_padding (padty, width))
+ | '*' ->
+ parse_after_padding pct_ind (str_ind + 1) end_ind minus plus sharp space
+ ign (Arg_padding padty)
+ | _ ->
+ begin match padty with
+ | Left ->
+ if not legacy_behavior then
+ invalid_format_without (str_ind - 1) '-' "padding";
+ parse_after_padding pct_ind str_ind end_ind minus plus sharp space ign
+ No_padding
+ | Zeros ->
+ (* a '0' padding indication not followed by anything should
+ be interpreted as a Right padding of width 0. This is used
+ by scanning conversions %0s and %0c *)
+ parse_after_padding pct_ind str_ind end_ind minus plus sharp space ign
+ (Lit_padding (Right, 0))
+ | Right ->
+ parse_after_padding pct_ind str_ind end_ind minus plus sharp space ign
+ No_padding
+ end
+
+ (* Is precision defined? *)
+ and parse_after_padding : type x e f .
+ int -> int -> int -> bool -> bool -> bool -> bool -> bool ->
+ (x, _) padding -> (_, _, e, f) fmt_ebb =
+ fun pct_ind str_ind end_ind minus plus sharp space ign pad ->
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind] with
+ | '.' ->
+ parse_precision pct_ind (str_ind + 1) end_ind minus plus sharp space ign
+ pad
+ | symb ->
+ parse_conversion pct_ind (str_ind + 1) end_ind plus sharp space ign pad
+ No_precision pad symb
+
+ (* Read the digital or '*' precision. *)
+ and parse_precision : type x e f .
+ int -> int -> int -> bool -> bool -> bool -> bool -> bool ->
+ (x, _) padding -> (_, _, e, f) fmt_ebb =
+ fun pct_ind str_ind end_ind minus plus sharp space ign pad ->
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ let parse_literal minus str_ind =
+ let new_ind, prec = parse_positive str_ind end_ind 0 in
+ parse_after_precision pct_ind new_ind end_ind minus plus sharp space ign
+ pad (Lit_precision prec) in
+ match str.[str_ind] with
+ | '0' .. '9' -> parse_literal minus str_ind
+ | ('+' | '-') as symb when legacy_behavior ->
+ (* Legacy mode would accept and ignore '+' or '-' before the
+ integer describing the desired precision; not that this
+ cannot happen for padding width, as '+' and '-' already have
+ a semantics there.
+
+ That said, the idea (supported by this tweak) that width and
+ precision literals are "integer literals" in the OCaml sense is
+ still blatantly wrong, as 123_456 or 0xFF are rejected. *)
+ parse_literal (minus || symb = '-') (str_ind + 1)
+ | '*' ->
+ parse_after_precision pct_ind (str_ind + 1) end_ind minus plus sharp space
+ ign pad Arg_precision
+ | _ ->
+ if legacy_behavior then
+ (* note that legacy implementation did not ignore '.' without
+ a number (as it does for padding indications), but
+ interprets it as '.0' *)
+ parse_after_precision pct_ind str_ind end_ind minus plus sharp space ign
+ pad (Lit_precision 0)
+ else
+ invalid_format_without (str_ind - 1) '.' "precision"
+
+ (* Try to read the conversion. *)
+ and parse_after_precision : type x y z t e f .
+ int -> int -> int -> bool -> bool -> bool -> bool -> bool ->
+ (x, y) padding -> (z, t) precision -> (_, _, e, f) fmt_ebb =
+ fun pct_ind str_ind end_ind minus plus sharp space ign pad prec ->
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ let parse_conv (type u) (type v) (padprec : (u, v) padding) =
+ parse_conversion pct_ind (str_ind + 1) end_ind plus sharp space ign pad
+ prec padprec str.[str_ind] in
+ (* in legacy mode, some formats (%s and %S) accept a weird mix of
+ padding and precision, which is merged as a single padding
+ information. For example, in %.10s the precision is implicitly
+ understood as padding %10s, but the left-padding component may
+ be specified either as a left padding or a negative precision:
+ %-.3s and %.-3s are equivalent to %-3s *)
+ match pad with
+ | No_padding -> (
+ match minus, prec with
+ | _, No_precision -> parse_conv No_padding
+ | false, Lit_precision n -> parse_conv (Lit_padding (Right, n))
+ | true, Lit_precision n -> parse_conv (Lit_padding (Left, n))
+ | false, Arg_precision -> parse_conv (Arg_padding Right)
+ | true, Arg_precision -> parse_conv (Arg_padding Left)
+ )
+ | pad -> parse_conv pad
+
+ (* Case analysis on conversion. *)
+ and parse_conversion : type x y z t u v e f .
+ int -> int -> int -> bool -> bool -> bool -> bool -> (x, y) padding ->
+ (z, t) precision -> (u, v) padding -> char -> (_, _, e, f) fmt_ebb =
+ fun pct_ind str_ind end_ind plus sharp space ign pad prec padprec symb ->
+ (* Flags used to check option usages/compatibilities. *)
+ let plus_used = ref false and sharp_used = ref false
+ and space_used = ref false and ign_used = ref false
+ and pad_used = ref false and prec_used = ref false in
+
+ (* Access to options, update flags. *)
+ let get_plus () = plus_used := true; plus
+ and get_sharp () = sharp_used := true; sharp
+ and get_space () = space_used := true; space
+ and get_ign () = ign_used := true; ign
+ and get_pad () = pad_used := true; pad
+ and get_prec () = prec_used := true; prec
+ and get_padprec () = pad_used := true; padprec in
+
+ let get_int_pad () =
+ (* %5.3d is accepted and meaningful: pad to length 5 with
+ spaces, but first pad with zeros upto length 3 (0-padding
+ is the interpretation of "precision" for integer formats).
+
+ %05.3d is redundant: pad to length 5 *with zeros*, but
+ first pad with zeros... To add insult to the injury, the
+ legacy implementation ignores the 0-padding indication and
+ does the 5 padding with spaces instead. We reuse this
+ interpretation for compatiblity, but statically reject this
+ format when the legacy mode is disabled, to protect strict
+ users from this corner case. *)
+ match get_pad (), get_prec () with
+ | pad, No_precision -> pad
+ | No_padding, _ -> No_padding
+ | Lit_padding (Zeros, n), _ ->
+ if legacy_behavior then Lit_padding (Right, n)
+ else incompatible_flag pct_ind str_ind '0' "precision"
+ | Arg_padding Zeros, _ ->
+ if legacy_behavior then Arg_padding Right
+ else incompatible_flag pct_ind str_ind '0' "precision"
+ | Lit_padding _ as pad, _ -> pad
+ | Arg_padding _ as pad, _ -> pad in
+
+ (* Check that padty <> Zeros. *)
+ let check_no_0 symb (type a) (type b) (pad : (a, b) padding) =
+ match pad with
+ | No_padding -> pad
+ | Lit_padding ((Left | Right), _) -> pad
+ | Arg_padding (Left | Right) -> pad
+ | Lit_padding (Zeros, width) ->
+ if legacy_behavior then Lit_padding (Right, width)
+ else incompatible_flag pct_ind str_ind symb "0"
+ | Arg_padding Zeros ->
+ if legacy_behavior then Arg_padding Right
+ else incompatible_flag pct_ind str_ind symb "0"
+ in
+
+ (* Get padding as a pad_option (see "%_", "%{", "%(" and "%[").
+ (no need for legacy mode tweaking, those were rejected by the
+ legacy parser as well) *)
+ let opt_of_pad c (type a) (type b) (pad : (a, b) padding) = match pad with
+ | No_padding -> None
+ | Lit_padding (Right, width) -> Some width
+ | Lit_padding (Zeros, width) ->
+ if legacy_behavior then Some width
+ else incompatible_flag pct_ind str_ind c "'0'"
+ | Lit_padding (Left, width) ->
+ if legacy_behavior then Some width
+ else incompatible_flag pct_ind str_ind c "'-'"
+ | Arg_padding _ -> incompatible_flag pct_ind str_ind c "'*'"
+ in
+ let get_pad_opt c = opt_of_pad c (get_pad ()) in
+ let get_padprec_opt c = opt_of_pad c (get_padprec ()) in
+
+ (* Get precision as a prec_option (see "%_f").
+ (no need for legacy mode tweaking, those were rejected by the
+ legacy parser as well) *)
+ let get_prec_opt () = match get_prec () with
+ | No_precision -> None
+ | Lit_precision ndec -> Some ndec
+ | Arg_precision -> incompatible_flag pct_ind str_ind '_' "'*'"
+ in
+
+ let fmt_result = match symb with
+ | ',' ->
+ parse str_ind end_ind
+ | 'c' ->
+ let char_format fmt_rest = (* %c *)
+ if get_ign ()
+ then Fmt_EBB (Ignored_param (Ignored_char, fmt_rest))
+ else Fmt_EBB (Char fmt_rest)
+ in
+ let scan_format fmt_rest = (* %0c *)
+ if get_ign ()
+ then Fmt_EBB (Ignored_param (Ignored_scan_next_char, fmt_rest))
+ else Fmt_EBB (Scan_next_char fmt_rest)
+ in
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ begin match get_pad_opt 'c' with
+ | None -> char_format fmt_rest
+ | Some 0 -> scan_format fmt_rest
+ | Some _n ->
+ if not legacy_behavior
+ then invalid_nonnull_char_width str_ind
+ else (* legacy ignores %c widths *) char_format fmt_rest
+ end
+ | 'C' ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ if get_ign () then Fmt_EBB (Ignored_param (Ignored_caml_char,fmt_rest))
+ else Fmt_EBB (Caml_char fmt_rest)
+ | 's' ->
+ let pad = check_no_0 symb (get_padprec ()) in
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ if get_ign () then
+ let ignored = Ignored_string (get_padprec_opt '_') in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ let Padding_fmt_EBB (pad', fmt_rest') =
+ make_padding_fmt_ebb pad fmt_rest in
+ Fmt_EBB (String (pad', fmt_rest'))
+ | 'S' ->
+ let pad = check_no_0 symb (get_padprec ()) in
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ if get_ign () then
+ let ignored = Ignored_caml_string (get_padprec_opt '_') in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ let Padding_fmt_EBB (pad', fmt_rest') =
+ make_padding_fmt_ebb pad fmt_rest in
+ Fmt_EBB (Caml_string (pad', fmt_rest'))
+ | 'd' | 'i' | 'x' | 'X' | 'o' | 'u' ->
+ let iconv = compute_int_conv pct_ind str_ind (get_plus ()) (get_sharp ())
+ (get_space ()) symb in
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ if get_ign () then
+ let ignored = Ignored_int (iconv, get_pad_opt '_') in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ let Padprec_fmt_EBB (pad', prec', fmt_rest') =
+ make_padprec_fmt_ebb (get_int_pad ()) (get_prec ()) fmt_rest in
+ Fmt_EBB (Int (iconv, pad', prec', fmt_rest'))
+ | 'N' ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ let counter = Token_counter in
+ if get_ign () then
+ let ignored = Ignored_scan_get_counter counter in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ Fmt_EBB (Scan_get_counter (counter, fmt_rest))
+ | 'l' | 'n' | 'L' when str_ind=end_ind || not (is_int_base str.[str_ind]) ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ let counter = counter_of_char symb in
+ if get_ign () then
+ let ignored = Ignored_scan_get_counter counter in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ Fmt_EBB (Scan_get_counter (counter, fmt_rest))
+ | 'l' ->
+ let iconv =
+ compute_int_conv pct_ind (str_ind + 1) (get_plus ()) (get_sharp ())
+ (get_space ()) str.[str_ind] in
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ if get_ign () then
+ let ignored = Ignored_int32 (iconv, get_pad_opt '_') in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ let Padprec_fmt_EBB (pad', prec', fmt_rest') =
+ make_padprec_fmt_ebb (get_int_pad ()) (get_prec ()) fmt_rest in
+ Fmt_EBB (Int32 (iconv, pad', prec', fmt_rest'))
+ | 'n' ->
+ let iconv =
+ compute_int_conv pct_ind (str_ind + 1) (get_plus ())
+ (get_sharp ()) (get_space ()) str.[str_ind] in
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ if get_ign () then
+ let ignored = Ignored_nativeint (iconv, get_pad_opt '_') in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ let Padprec_fmt_EBB (pad', prec', fmt_rest') =
+ make_padprec_fmt_ebb (get_int_pad ()) (get_prec ()) fmt_rest in
+ Fmt_EBB (Nativeint (iconv, pad', prec', fmt_rest'))
+ | 'L' ->
+ let iconv =
+ compute_int_conv pct_ind (str_ind + 1) (get_plus ()) (get_sharp ())
+ (get_space ()) str.[str_ind] in
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ if get_ign () then
+ let ignored = Ignored_int64 (iconv, get_pad_opt '_') in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ let Padprec_fmt_EBB (pad', prec', fmt_rest') =
+ make_padprec_fmt_ebb (get_int_pad ()) (get_prec ()) fmt_rest in
+ Fmt_EBB (Int64 (iconv, pad', prec', fmt_rest'))
+ | 'f' | 'e' | 'E' | 'g' | 'G' | 'F' ->
+ let fconv = compute_float_conv pct_ind str_ind (get_plus ())
+ (get_space ()) symb in
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ if get_ign () then
+ let ignored = Ignored_float (get_pad_opt '_', get_prec_opt ()) in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ let Padprec_fmt_EBB (pad', prec', fmt_rest') =
+ make_padprec_fmt_ebb (get_pad ()) (get_prec ()) fmt_rest in
+ Fmt_EBB (Float (fconv, pad', prec', fmt_rest'))
+ | 'b' | 'B' ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ if get_ign () then Fmt_EBB (Ignored_param (Ignored_bool, fmt_rest))
+ else Fmt_EBB (Bool fmt_rest)
+ | 'a' ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ Fmt_EBB (Alpha fmt_rest)
+ | 't' ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ Fmt_EBB (Theta fmt_rest)
+ | 'r' ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ if get_ign () then Fmt_EBB (Ignored_param (Ignored_reader, fmt_rest))
+ else Fmt_EBB (Reader fmt_rest)
+ | '!' ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ Fmt_EBB (Flush fmt_rest)
+ | ('%' | '@') as c ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ Fmt_EBB (Char_literal (c, fmt_rest))
+ | '{' ->
+ let sub_end = search_subformat_end str_ind end_ind '}' in
+ let Fmt_EBB sub_fmt = parse str_ind sub_end in
+ let Fmt_EBB fmt_rest = parse (sub_end + 2) end_ind in
+ let sub_fmtty = fmtty_of_fmt sub_fmt in
+ if get_ign () then
+ let ignored = Ignored_format_arg (get_pad_opt '_', sub_fmtty) in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ Fmt_EBB (Format_arg (get_pad_opt '{', sub_fmtty, fmt_rest))
+ | '(' ->
+ let sub_end = search_subformat_end str_ind end_ind ')' in
+ let Fmt_EBB fmt_rest = parse (sub_end + 2) end_ind in
+ let Fmt_EBB sub_fmt = parse str_ind sub_end in
+ let sub_fmtty = fmtty_of_fmt sub_fmt in
+ if get_ign () then
+ let ignored = Ignored_format_subst (get_pad_opt '_', sub_fmtty) in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ Fmt_EBB (Format_subst (get_pad_opt '(', sub_fmtty, fmt_rest))
+ | '[' ->
+ let next_ind, char_set = parse_char_set str_ind end_ind in
+ let Fmt_EBB fmt_rest = parse next_ind end_ind in
+ if get_ign () then
+ let ignored = Ignored_scan_char_set (get_pad_opt '_', char_set) in
+ Fmt_EBB (Ignored_param (ignored, fmt_rest))
+ else
+ Fmt_EBB (Scan_char_set (get_pad_opt '[', char_set, fmt_rest))
+ | '-' | '+' | '#' | ' ' | '_' ->
+ failwith_message
+ "invalid format %S: at character number %d, \
+ flag %C is only allowed after the '%%', before padding and precision"
+ str pct_ind symb
+ | _ ->
+ failwith_message
+ "invalid format %S: at character number %d, \
+ invalid conversion \"%%%c\"" str (str_ind - 1) symb
+ in
+ (* Check for unused options, and reject them as incompatible.
+
+ Such checks need to be disabled in legacy mode, as the legacy
+ parser silently ignored incompatible flags. *)
+ if not legacy_behavior then begin
+ if not !plus_used && plus then
+ incompatible_flag pct_ind str_ind symb "'+'";
+ if not !sharp_used && sharp then
+ incompatible_flag pct_ind str_ind symb "'#'";
+ if not !space_used && space then
+ incompatible_flag pct_ind str_ind symb "' '";
+ if not !pad_used && Padding_EBB pad <> Padding_EBB No_padding then
+ incompatible_flag pct_ind str_ind symb "`padding'";
+ if not !prec_used && Precision_EBB prec <> Precision_EBB No_precision then
+ incompatible_flag pct_ind str_ind (if ign then '_' else symb)
+ "`precision'";
+ if ign && plus then incompatible_flag pct_ind str_ind '_' "'+'";
+ end;
+ (* this last test must not be disabled in legacy mode,
+ as ignoring it would typically result in a different typing
+ than what the legacy parser used *)
+ if not !ign_used && ign then
+ begin match symb with
+ (* argument-less formats can safely be ignored in legacy mode *)
+ | ('@' | '%' | '!' | ',') when legacy_behavior -> ()
+ | _ ->
+ incompatible_flag pct_ind str_ind symb "'_'"
+ end;
+ fmt_result
+
+ (* Parse formatting informations (after '@'). *)
+ and parse_after_at : type e f . int -> int -> (_, _, e, f) fmt_ebb =
+ fun str_ind end_ind ->
+ if str_ind = end_ind then Fmt_EBB (Char_literal ('@', End_of_format))
+ else
+ match str.[str_ind] with
+ | '[' ->
+ parse_tag false (str_ind + 1) end_ind
+ | ']' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (Close_box, fmt_rest))
+ | '{' ->
+ parse_tag true (str_ind + 1) end_ind
+ | '}' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (Close_tag, fmt_rest))
+ | ',' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (Break ("@,", 0, 0), fmt_rest))
+ | ' ' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (Break ("@ ", 1, 0), fmt_rest))
+ | ';' ->
+ parse_good_break (str_ind + 1) end_ind
+ | '?' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (FFlush, fmt_rest))
+ | '\n' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (Force_newline, fmt_rest))
+ | '.' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (Flush_newline, fmt_rest))
+ | '<' ->
+ parse_magic_size (str_ind + 1) end_ind
+ | '@' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (Escaped_at, fmt_rest))
+ | '%' when str_ind + 1 < end_ind && str.[str_ind + 1] = '%' ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 2) end_ind in
+ Fmt_EBB (Formatting_lit (Escaped_percent, fmt_rest))
+ | '%' ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ Fmt_EBB (Char_literal ('@', fmt_rest))
+ | c ->
+ let Fmt_EBB fmt_rest = parse (str_ind + 1) end_ind in
+ Fmt_EBB (Formatting_lit (Scan_indic c, fmt_rest))
+
+ and check_open_box : type a b c d e f . (a, b, c, d, e, f) fmt -> unit =
+ fun fmt -> match fmt with
+ | String_literal (str, End_of_format) -> (
+ try ignore (open_box_of_string str) with Failure _ ->
+ ((* Emit warning: invalid open box *))
+ )
+ | _ -> ()
+
+ (* Try to read the optionnal <name> after "@{" or "@[". *)
+ and parse_tag : type e f . bool -> int -> int -> (_, _, e, f) fmt_ebb =
+ fun is_open_tag str_ind end_ind ->
+ try
+ if str_ind = end_ind then raise Not_found;
+ match str.[str_ind] with
+ | '<' ->
+ let ind = String.index_from str (str_ind + 1) '>' in
+ if ind >= end_ind then raise Not_found;
+ let sub_str = String.sub str str_ind (ind - str_ind + 1) in
+ let Fmt_EBB fmt_rest = parse (ind + 1) end_ind in
+ let Fmt_EBB sub_fmt = parse str_ind (ind + 1) in
+ let sub_format = Format (sub_fmt, sub_str) in
+ let formatting = if is_open_tag then Open_tag sub_format else (
+ check_open_box sub_fmt;
+ Open_box sub_format) in
+ Fmt_EBB (Formatting_gen (formatting, fmt_rest))
+ | _ ->
+ raise Not_found
+ with Not_found ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ let sub_format = Format (End_of_format, "") in
+ let formatting =
+ if is_open_tag then Open_tag sub_format else Open_box sub_format in
+ Fmt_EBB (Formatting_gen (formatting, fmt_rest))
+
+ (* Try to read the optionnal <width offset> after "@;". *)
+ and parse_good_break : type e f . int -> int -> (_, _, e, f) fmt_ebb =
+ fun str_ind end_ind ->
+ let next_ind, formatting_lit =
+ try
+ if str_ind = end_ind || str.[str_ind] <> '<' then raise Not_found;
+ let str_ind_1 = parse_spaces (str_ind + 1) end_ind in
+ match str.[str_ind_1] with
+ | '0' .. '9' | '-' -> (
+ let str_ind_2, width = parse_integer str_ind_1 end_ind in
+ let str_ind_3 = parse_spaces str_ind_2 end_ind in
+ match str.[str_ind_3] with
+ | '>' ->
+ let s = String.sub str (str_ind-2) (str_ind_3-str_ind+3) in
+ str_ind_3 + 1, Break (s, width, 0)
+ | '0' .. '9' | '-' ->
+ let str_ind_4, offset = parse_integer str_ind_3 end_ind in
+ let str_ind_5 = parse_spaces str_ind_4 end_ind in
+ if str.[str_ind_5] <> '>' then raise Not_found;
+ let s = String.sub str (str_ind-2) (str_ind_5-str_ind+3) in
+ str_ind_5 + 1, Break (s, width, offset)
+ | _ -> raise Not_found
+ )
+ | _ -> raise Not_found
+ with Not_found | Failure _ ->
+ str_ind, Break ("@;", 1, 0)
+ in
+ let Fmt_EBB fmt_rest = parse next_ind end_ind in
+ Fmt_EBB (Formatting_lit (formatting_lit, fmt_rest))
+
+ (* Parse the size in a <n>. *)
+ and parse_magic_size : type e f . int -> int -> (_, _, e, f) fmt_ebb =
+ fun str_ind end_ind ->
+ match
+ try
+ let str_ind_1 = parse_spaces str_ind end_ind in
+ match str.[str_ind_1] with
+ | '0' .. '9' | '-' ->
+ let str_ind_2, size = parse_integer str_ind_1 end_ind in
+ let str_ind_3 = parse_spaces str_ind_2 end_ind in
+ if str.[str_ind_3] <> '>' then raise Not_found;
+ let s = String.sub str (str_ind - 2) (str_ind_3 - str_ind + 3) in
+ Some (str_ind_3 + 1, Magic_size (s, size))
+ | _ -> None
+ with Not_found | Failure _ ->
+ None
+ with
+ | Some (next_ind, formatting_lit) ->
+ let Fmt_EBB fmt_rest = parse next_ind end_ind in
+ Fmt_EBB (Formatting_lit (formatting_lit, fmt_rest))
+ | None ->
+ let Fmt_EBB fmt_rest = parse str_ind end_ind in
+ Fmt_EBB (Formatting_lit (Scan_indic '<', fmt_rest))
+
+ (* Parse and construct a char set. *)
+ and parse_char_set str_ind end_ind =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+
+ let char_set = create_char_set () in
+ let add_char c =
+ add_in_char_set char_set c;
+ in
+ let add_range c c' =
+ for i = int_of_char c to int_of_char c' do
+ add_in_char_set char_set (char_of_int i);
+ done;
+ in
+
+ let fail_single_percent str_ind =
+ failwith_message
+ "invalid format %S: '%%' alone is not accepted in character sets, \
+ use %%%% instead at position %d." str str_ind;
+ in
+
+ (* Parse the first character of a char set. *)
+ let rec parse_char_set_start str_ind end_ind =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ let c = str.[str_ind] in
+ parse_char_set_after_char (str_ind + 1) end_ind c;
+
+ (* Parse the content of a char set until the first ']'. *)
+ and parse_char_set_content str_ind end_ind =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind] with
+ | ']' ->
+ str_ind + 1
+ | '-' ->
+ add_char '-';
+ parse_char_set_content (str_ind + 1) end_ind;
+ | c ->
+ parse_char_set_after_char (str_ind + 1) end_ind c;
+
+ (* Test for range in char set. *)
+ and parse_char_set_after_char str_ind end_ind c =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind] with
+ | ']' ->
+ add_char c;
+ str_ind + 1
+ | '-' ->
+ parse_char_set_after_minus (str_ind + 1) end_ind c
+ | ('%' | '@') as c' when c = '%' ->
+ add_char c';
+ parse_char_set_content (str_ind + 1) end_ind
+ | c' ->
+ if c = '%' then fail_single_percent str_ind;
+ (* note that '@' alone is accepted, as done by the legacy
+ implementation; the documentation specifically requires %@
+ so we could warn on that *)
+ add_char c;
+ parse_char_set_after_char (str_ind + 1) end_ind c'
+
+ (* Manage range in char set (except if the '-' the last char before ']') *)
+ and parse_char_set_after_minus str_ind end_ind c =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind] with
+ | ']' ->
+ add_char c;
+ add_char '-';
+ str_ind + 1
+ | '%' ->
+ if str_ind + 1 = end_ind then unexpected_end_of_format end_ind;
+ begin match str.[str_ind + 1] with
+ | ('%' | '@') as c' ->
+ add_range c c';
+ parse_char_set_content (str_ind + 2) end_ind
+ | _ -> fail_single_percent str_ind
+ end
+ | c' ->
+ add_range c c';
+ parse_char_set_content (str_ind + 1) end_ind
+ in
+ let str_ind, reverse =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind] with
+ | '^' -> str_ind + 1, true
+ | _ -> str_ind, false in
+ let next_ind = parse_char_set_start str_ind end_ind in
+ let char_set = freeze_char_set char_set in
+ next_ind, (if reverse then rev_char_set char_set else char_set)
+
+ (* Consume all next spaces, raise an Failure if end_ind is reached. *)
+ and parse_spaces str_ind end_ind =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ if str.[str_ind] = ' ' then parse_spaces (str_ind + 1) end_ind else str_ind
+
+ (* Read a positive integer from the string, raise a Failure if end_ind is
+ reached. *)
+ and parse_positive str_ind end_ind acc =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind] with
+ | '0' .. '9' as c ->
+ let new_acc = acc * 10 + (int_of_char c - int_of_char '0') in
+ if new_acc > Sys.max_string_length then
+ failwith_message
+ "invalid format %S: integer %d is greater than the limit %d"
+ str new_acc Sys.max_string_length
+ else
+ parse_positive (str_ind + 1) end_ind new_acc
+ | _ -> str_ind, acc
+
+ (* Read a positive or negative integer from the string, raise a Failure
+ if end_ind is reached. *)
+ and parse_integer str_ind end_ind =
+ if str_ind = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind] with
+ | '0' .. '9' -> parse_positive str_ind end_ind 0
+ | '-' -> (
+ if str_ind + 1 = end_ind then unexpected_end_of_format end_ind;
+ match str.[str_ind + 1] with
+ | '0' .. '9' ->
+ let next_ind, n = parse_positive (str_ind + 1) end_ind 0 in
+ next_ind, -n
+ | c ->
+ expected_character (str_ind + 1) "digit" c
+ )
+ | _ -> assert false
+
+ (* Add a literal to a format from a literal character sub-sequence. *)
+ and add_literal : type a d e f .
+ int -> int -> (a, _, _, d, e, f) fmt ->
+ (_, _, e, f) fmt_ebb =
+ fun lit_start str_ind fmt -> match str_ind - lit_start with
+ | 0 -> Fmt_EBB fmt
+ | 1 -> Fmt_EBB (Char_literal (str.[lit_start], fmt))
+ | size -> Fmt_EBB (String_literal (String.sub str lit_start size, fmt))
+
+ (* Search the end of the current sub-format
+ (i.e. the corresponding "%}" or "%)") *)
+ and search_subformat_end str_ind end_ind c =
+ if str_ind = end_ind then
+ failwith_message
+ "invalid format %S: unclosed sub-format, \
+ expected \"%%%c\" at character number %d" str c end_ind;
+ match str.[str_ind] with
+ | '%' ->
+ if str_ind + 1 = end_ind then unexpected_end_of_format end_ind;
+ if str.[str_ind + 1] = c then (* End of format found *) str_ind else
+ begin match str.[str_ind + 1] with
+ | '_' ->
+ (* Search for "%_(" or "%_{". *)
+ if str_ind + 2 = end_ind then unexpected_end_of_format end_ind;
+ begin match str.[str_ind + 2] with
+ | '{' ->
+ let sub_end = search_subformat_end (str_ind + 3) end_ind '}' in
+ search_subformat_end (sub_end + 2) end_ind c
+ | '(' ->
+ let sub_end = search_subformat_end (str_ind + 3) end_ind ')' in
+ search_subformat_end (sub_end + 2) end_ind c
+ | _ -> search_subformat_end (str_ind + 3) end_ind c
+ end
+ | '{' ->
+ (* %{...%} sub-format found. *)
+ let sub_end = search_subformat_end (str_ind + 2) end_ind '}' in
+ search_subformat_end (sub_end + 2) end_ind c
+ | '(' ->
+ (* %(...%) sub-format found. *)
+ let sub_end = search_subformat_end (str_ind + 2) end_ind ')' in
+ search_subformat_end (sub_end + 2) end_ind c
+ | '}' ->
+ (* Error: %(...%}. *)
+ expected_character (str_ind + 1) "character ')'" '}';
+ | ')' ->
+ (* Error: %{...%). *)
+ expected_character (str_ind + 1) "character '}'" ')';
+ | _ ->
+ search_subformat_end (str_ind + 2) end_ind c
+ end
+ | _ -> search_subformat_end (str_ind + 1) end_ind c
+
+ (* Check if symb is a valid int conversion after "%l", "%n" or "%L" *)
+ and is_int_base symb = match symb with
+ | 'd' | 'i' | 'x' | 'X' | 'o' | 'u' -> true
+ | _ -> false
+
+ (* Convert a char (l, n or L) to its associated counter. *)
+ and counter_of_char symb = match symb with
+ | 'l' -> Line_counter | 'n' -> Char_counter
+ | 'L' -> Token_counter | _ -> assert false
+
+ (* Convert (plus, symb) to its associated int_conv. *)
+ and compute_int_conv pct_ind str_ind plus sharp space symb =
+ match plus, sharp, space, symb with
+ | false, false, false, 'd' -> Int_d | false, false, false, 'i' -> Int_i
+ | false, false, true, 'd' -> Int_sd | false, false, true, 'i' -> Int_si
+ | true, false, false, 'd' -> Int_pd | true, false, false, 'i' -> Int_pi
+ | false, false, false, 'x' -> Int_x | false, false, false, 'X' -> Int_X
+ | false, true, false, 'x' -> Int_Cx | false, true, false, 'X' -> Int_CX
+ | false, false, false, 'o' -> Int_o
+ | false, true, false, 'o' -> Int_Co
+ | false, false, false, 'u' -> Int_u
+ | _, true, _, 'x' when legacy_behavior -> Int_Cx
+ | _, true, _, 'X' when legacy_behavior -> Int_CX
+ | _, true, _, 'o' when legacy_behavior -> Int_Co
+ | _, true, _, ('d' | 'i' | 'u') ->
+ if legacy_behavior then (* ignore *)
+ compute_int_conv pct_ind str_ind plus false space symb
+ else incompatible_flag pct_ind str_ind symb "'#'"
+ | true, _, true, _ ->
+ if legacy_behavior then
+ (* plus and space: legacy implementation prefers plus *)
+ compute_int_conv pct_ind str_ind plus sharp false symb
+ else incompatible_flag pct_ind str_ind ' ' "'+'"
+ | false, _, true, _ ->
+ if legacy_behavior then (* ignore *)
+ compute_int_conv pct_ind str_ind plus sharp false symb
+ else incompatible_flag pct_ind str_ind symb "' '"
+ | true, _, false, _ ->
+ if legacy_behavior then (* ignore *)
+ compute_int_conv pct_ind str_ind false sharp space symb
+ else incompatible_flag pct_ind str_ind symb "'+'"
+ | false, _, false, _ -> assert false
+
+ (* Convert (plus, symb) to its associated float_conv. *)
+ and compute_float_conv pct_ind str_ind plus space symb =
+ match plus, space, symb with
+ | false, false, 'f' -> Float_f | false, false, 'e' -> Float_e
+ | false, true, 'f' -> Float_sf | false, true, 'e' -> Float_se
+ | true, false, 'f' -> Float_pf | true, false, 'e' -> Float_pe
+ | false, false, 'E' -> Float_E | false, false, 'g' -> Float_g
+ | false, true, 'E' -> Float_sE | false, true, 'g' -> Float_sg
+ | true, false, 'E' -> Float_pE | true, false, 'g' -> Float_pg
+ | false, false, 'G' -> Float_G
+ | false, true, 'G' -> Float_sG
+ | true, false, 'G' -> Float_pG
+ | false, false, 'F' -> Float_F
+ | true, true, _ ->
+ if legacy_behavior then
+ (* plus and space: legacy implementation prefers plus *)
+ compute_float_conv pct_ind str_ind plus false symb
+ else incompatible_flag pct_ind str_ind ' ' "'+'"
+ | false, true, _ ->
+ if legacy_behavior then (* ignore *)
+ compute_float_conv pct_ind str_ind plus false symb
+ else incompatible_flag pct_ind str_ind symb "' '"
+ | true, false, _ ->
+ if legacy_behavior then (* ignore *)
+ compute_float_conv pct_ind str_ind false space symb
+ else incompatible_flag pct_ind str_ind symb "'+'"
+ | false, false, _ -> assert false
+
+ (* Raise a Failure with a friendly error message about incompatible options.*)
+ and incompatible_flag : type a . int -> int -> char -> string -> a =
+ fun pct_ind str_ind symb option ->
+ let subfmt = String.sub str pct_ind (str_ind - pct_ind) in
+ failwith_message
+ "invalid format %S: at character number %d, \
+ %s is incompatible with '%c' in sub-format %S"
+ str pct_ind option symb subfmt;
+
+ in parse 0 (String.length str)
+
+(******************************************************************************)
+ (* Guarded string to format conversions *)
+
+(* Convert a string to a format according to an fmtty. *)
+(* Raise a Failure with an error message in case of type mismatch. *)
+let format_of_string_fmtty str fmtty =
+ let Fmt_EBB fmt = fmt_ebb_of_string str in
+ try Format (type_format fmt fmtty, str)
+ with Type_mismatch ->
+ failwith_message
+ "bad input: format type mismatch between %S and %S"
+ str (string_of_fmtty fmtty)
+
+(* Convert a string to a format compatible with an other format. *)
+(* Raise a Failure with an error message in case of type mismatch. *)
+let format_of_string_format str (Format (fmt', str')) =
+ let Fmt_EBB fmt = fmt_ebb_of_string str in
+ try Format (type_format fmt (fmtty_of_fmt fmt'), str)
+ with Type_mismatch ->
+ failwith_message
+ "bad input: format type mismatch between %S and %S" str str'
diff --git a/stdlib/camlinternalFormat.mli b/stdlib/camlinternalFormat.mli
new file mode 100644
index 0000000000..036bcb0ec7
--- /dev/null
+++ b/stdlib/camlinternalFormat.mli
@@ -0,0 +1,118 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benoit Vaugon, ENSTA *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* No comments, OCaml stdlib internal use only. *)
+
+open CamlinternalFormatBasics
+
+val is_in_char_set : char_set -> char -> bool
+val rev_char_set : char_set -> char_set
+
+type mutable_char_set = bytes
+val create_char_set : unit -> mutable_char_set
+val add_in_char_set : mutable_char_set -> char -> unit
+val freeze_char_set : mutable_char_set -> char_set
+
+type ('a, 'b, 'c, 'd, 'e, 'f) param_format_ebb = Param_format_EBB :
+ ('x -> 'a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) param_format_ebb
+
+val param_format_of_ignored_format :
+ ('a, 'b, 'c, 'd, 'y, 'x) ignored -> ('x, 'b, 'c, 'y, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) param_format_ebb
+
+type ('b, 'c) acc_formatting_gen =
+ | Acc_open_tag of ('b, 'c) acc
+ | Acc_open_box of ('b, 'c) acc
+
+and ('b, 'c) acc =
+ | Acc_formatting_lit of ('b, 'c) acc * formatting_lit
+ | Acc_formatting_gen of ('b, 'c) acc * ('b, 'c) acc_formatting_gen
+ | Acc_string_literal of ('b, 'c) acc * string
+ | Acc_char_literal of ('b, 'c) acc * char
+ | Acc_data_string of ('b, 'c) acc * string
+ | Acc_data_char of ('b, 'c) acc * char
+ | Acc_delay of ('b, 'c) acc * ('b -> 'c)
+ | Acc_flush of ('b, 'c) acc
+ | Acc_invalid_arg of ('b, 'c) acc * string
+ | End_of_acc
+
+type ('a, 'b) heter_list =
+ | Cons : 'c * ('a, 'b) heter_list -> ('c -> 'a, 'b) heter_list
+ | Nil : ('b, 'b) heter_list
+
+type ('b, 'c, 'e, 'f) fmt_ebb = Fmt_EBB :
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmt ->
+ ('b, 'c, 'e, 'f) fmt_ebb
+
+val make_printf :
+ ('b -> ('b, 'c) acc -> 'd) -> 'b -> ('b, 'c) acc ->
+ ('a, 'b, 'c, 'c, 'c, 'd) CamlinternalFormatBasics.fmt -> 'a
+
+val output_acc : out_channel -> (out_channel, unit) acc -> unit
+val bufput_acc : Buffer.t -> (Buffer.t, unit) acc -> unit
+val strput_acc : Buffer.t -> (unit, string) acc -> unit
+
+val type_format :
+ ('x, 'b, 'c, 't, 'u, 'v) CamlinternalFormatBasics.fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmtty ->
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmt
+
+val fmt_ebb_of_string :
+ ?legacy_behavior:bool -> string -> ('b, 'c, 'e, 'f) fmt_ebb
+(* warning: the optional flag legacy_behavior is EXPERIMENTAL and will
+ be removed in the next version. You must not set it explicitly. It
+ is only used by the type-checker implementation.
+*)
+
+val format_of_string_fmtty :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmtty ->
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6
+
+val format_of_string_format :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6
+
+val char_of_iconv : CamlinternalFormatBasics.int_conv -> char
+val string_of_formatting_lit : CamlinternalFormatBasics.formatting_lit -> string
+val string_of_formatting_gen :
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.formatting_gen -> string
+
+val string_of_fmtty :
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmtty -> string
+val string_of_fmt :
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmt -> string
+
+val open_box_of_string : string -> int * block_type
+
+val symm :
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+-> ('a2, 'b2, 'c2, 'd2, 'e2, 'f2,
+ 'a1, 'b1, 'c1, 'd1, 'e1, 'f1) fmtty_rel
+
+val trans :
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+-> ('a2, 'b2, 'c2, 'd2, 'e2, 'f2,
+ 'a3, 'b3, 'c3, 'd3, 'e3, 'f3) fmtty_rel
+-> ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a3, 'b3, 'c3, 'd3, 'e3, 'f3) fmtty_rel
+
+val recast :
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1) fmt
+-> ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+-> ('a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmt
diff --git a/stdlib/camlinternalFormatBasics.ml b/stdlib/camlinternalFormatBasics.ml
new file mode 100644
index 0000000000..60a74524ec
--- /dev/null
+++ b/stdlib/camlinternalFormatBasics.ml
@@ -0,0 +1,679 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benoit Vaugon, ENSTA *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Padding position. *)
+type padty =
+ | Left (* Text is left justified ('-' option). *)
+ | Right (* Text is right justified (no '-' option). *)
+ | Zeros (* Text is right justified by zeros (see '0' option). *)
+
+(***)
+
+(* Integer conversion. *)
+type int_conv =
+ | Int_d | Int_pd | Int_sd (* %d | %+d | % d *)
+ | Int_i | Int_pi | Int_si (* %i | %+i | % i *)
+ | Int_x | Int_Cx (* %x | %#x *)
+ | Int_X | Int_CX (* %X | %#X *)
+ | Int_o | Int_Co (* %o | %#o *)
+ | Int_u (* %u *)
+
+(* Float conversion. *)
+type float_conv =
+ | Float_f | Float_pf | Float_sf (* %f | %+f | % f *)
+ | Float_e | Float_pe | Float_se (* %e | %+e | % e *)
+ | Float_E | Float_pE | Float_sE (* %E | %+E | % E *)
+ | Float_g | Float_pg | Float_sg (* %g | %+g | % g *)
+ | Float_G | Float_pG | Float_sG (* %G | %+G | % G *)
+ | Float_F (* %F *)
+
+(***)
+
+(* Char sets (see %[...]) are bitmaps implemented as 32-char strings. *)
+type char_set = string
+
+(***)
+
+(* Counter used in Scanf. *)
+type counter =
+ | Line_counter (* %l *)
+ | Char_counter (* %n *)
+ | Token_counter (* %N, %L *)
+
+(***)
+
+(* Padding of strings and numbers. *)
+type ('a, 'b) padding =
+ (* No padding (ex: "%d") *)
+ | No_padding : ('a, 'a) padding
+ (* Literal padding (ex: "%8d") *)
+ | Lit_padding : padty * int -> ('a, 'a) padding
+ (* Padding as extra argument (ex: "%*d") *)
+ | Arg_padding : padty -> (int -> 'a, 'a) padding
+
+(* Some formats, such as %_d,
+ only accept an optional number as padding option (no extra argument) *)
+type pad_option = int option
+
+(* Precision of floats and '0'-padding of integers. *)
+type ('a, 'b) precision =
+ (* No precision (ex: "%f") *)
+ | No_precision : ('a, 'a) precision
+ (* Literal precision (ex: "%.3f") *)
+ | Lit_precision : int -> ('a, 'a) precision
+ (* Precision as extra argument (ex: "%.*f") *)
+ | Arg_precision : (int -> 'a, 'a) precision
+
+(* Some formats, such as %_f,
+ only accept an optional number as precision option (no extra argument) *)
+type prec_option = int option
+
+(* see the Custom format combinator *)
+type ('a, 'b, 'c) custom_arity =
+ | Custom_zero : ('a, string, 'a) custom_arity
+ | Custom_succ : ('a, 'b, 'c) custom_arity ->
+ ('a, 'x -> 'b, 'x -> 'c) custom_arity
+
+(***)
+
+(* Relational format types
+
+In the first format+gadts implementation, the type for %(..%) in the
+fmt GADT was as follows:
+
+| Format_subst : (* %(...%) *)
+ pad_option * ('d1, 'q1, 'd2, 'q2) reader_nb_unifier *
+ ('x, 'b, 'c, 'd1, 'q1, 'u) fmtty *
+ ('u, 'b, 'c, 'q1, 'e1, 'f) fmt ->
+ (('x, 'b, 'c, 'd2, 'q2, 'u) format6 -> 'x, 'b, 'c, 'd1, 'e1, 'f) fmt
+
+Notice that the 'u parameter in 'f position in the format argument
+(('x, .., 'u) format6 -> ..) is equal to the 'u parameter in 'a
+position in the format tail (('u, .., 'f) fmt). This means that the
+type of the expected format parameter depends of where the %(...%)
+are in the format string:
+
+ # Printf.printf "%(%)";;
+ - : (unit, out_channel, unit, '_a, '_a, unit)
+ CamlinternalFormatBasics.format6 -> unit
+ = <fun>
+ # Printf.printf "%(%)%d";;
+ - : (int -> unit, out_channel, unit, '_a, '_a, int -> unit)
+ CamlinternalFormatBasics.format6 -> int -> unit
+ = <fun>
+
+On the contrary, the legacy typer gives a clever type that does not
+depend on the position of %(..%) in the format string. For example,
+%(%) will have the polymorphic type ('a, 'b, 'c, 'd, 'd, 'a): it can
+be concatenated to any format type, and only enforces the constraint
+that its 'a and 'f parameters are equal (no format arguments) and 'd
+and 'e are equal (no reader argument).
+
+The weakening of this parameter type in the GADT version broke user
+code (in fact it essentially made %(...%) unusable except at the last
+position of a format). In particular, the following would not work
+anymore:
+
+ fun sep ->
+ Format.printf "foo%(%)bar%(%)baz" sep sep
+
+As the type-checker would require two *incompatible* types for the %(%)
+in different positions.
+
+The solution to regain a general type for %(..%) is to generalize this
+technique, not only on the 'd, 'e parameters, but on all six
+parameters of a format: we introduce a "relational" type
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+whose values are proofs that ('a1, .., 'f1) and ('a2, .., 'f2) morally
+correspond to the same format type: 'a1 is obtained from 'f1,'b1,'c1
+in the exact same way that 'a2 is obtained from 'f2,'b2,'c2, etc.
+
+For example, the relation between two format types beginning with a Char
+parameter is as follows:
+
+| Char_ty : (* %c *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (char -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ char -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+
+In the general case, the term structure of fmtty_rel is (almost[1])
+isomorphic to the fmtty of the previous implementation: every
+constructor is re-read with a binary, relational type, instead of the
+previous unary typing. fmtty can then be re-defined as the diagonal of
+fmtty_rel:
+
+ type ('a, 'b, 'c, 'd, 'e, 'f) fmtty =
+ ('a, 'b, 'c, 'd, 'e, 'f,
+ 'a, 'b, 'c, 'd, 'e, 'f) fmtty_rel
+
+Once we have this fmtty_rel type in place, we can give the more
+general type to %(...%):
+
+| Format_subst : (* %(...%) *)
+ pad_option *
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g2, 'b, 'c, 'j2, 'd, 'a) fmtty_rel *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g2, 'b, 'c, 'j2, 'e, 'f) fmt
+
+We accept any format (('g, 'h, 'i, 'j, 'k, 'l) format6) (this is
+completely unrelated to the type of the current format), but also
+require a proof that this format is in relation to another format that
+is concatenable to the format tail. When executing a %(...%) format
+(in camlinternalFormat.ml:make_printf or scanf.ml:make_scanf), we
+transtype the format along this relation using the 'recast' function
+to transpose between related format types.
+
+ val recast :
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1) fmt
+ -> ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ -> ('a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmt
+
+NOTE [1]: the typing of Format_subst_ty requires not one format type, but
+two, one to establish the link between the format argument and the
+first six parameters, and the other for the link between the format
+argumant and the last six parameters.
+
+| Format_subst_ty : (* %(...%) *)
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g1, 'b1, 'c1, 'j1, 'd1, 'a1) fmtty_rel *
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g2, 'b2, 'c2, 'j2, 'd2, 'a2) fmtty_rel *
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g1, 'b1, 'c1, 'j1, 'e1, 'f1,
+ ('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g2, 'b2, 'c2, 'j2, 'e2, 'f2) fmtty_rel
+
+When we generate a format AST, we generate exactly the same witness
+for both relations, and the witness-conversion functions in
+camlinternalFormat do rely on this invariant. For example, the
+function that proves that the relation is transitive
+
+ val trans :
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ -> ('a2, 'b2, 'c2, 'd2, 'e2, 'f2,
+ 'a3, 'b3, 'c3, 'd3, 'e3, 'f3) fmtty_rel
+ -> ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a3, 'b3, 'c3, 'd3, 'e3, 'f3) fmtty_rel
+
+does assume that the two input have exactly the same term structure
+(and is only every used for argument witnesses of the
+Format_subst_ty constructor).
+*)
+
+(* Type of a block used by the Format pretty-printer. *)
+type block_type =
+ | Pp_hbox (* Horizontal block no line breaking *)
+ | Pp_vbox (* Vertical block each break leads to a new line *)
+ | Pp_hvbox (* Horizontal-vertical block: same as vbox, except if this block
+ is small enough to fit on a single line *)
+ | Pp_hovbox (* Horizontal or Vertical block: breaks lead to new line
+ only when necessary to print the content of the block *)
+ | Pp_box (* Horizontal or Indent block: breaks lead to new line
+ only when necessary to print the content of the block, or
+ when it leads to a new indentation of the current line *)
+ | Pp_fits (* Internal usage: when a block fits on a single line *)
+
+(* Formatting element used by the Format pretty-printter. *)
+type formatting_lit =
+ | Close_box (* @] *)
+ | Close_tag (* @} *)
+ | Break of string * int * int (* @, | @ | @; | @;<> *)
+ | FFlush (* @? *)
+ | Force_newline (* @\n *)
+ | Flush_newline (* @. *)
+ | Magic_size of string * int (* @<n> *)
+ | Escaped_at (* @@ *)
+ | Escaped_percent (* @%% *)
+ | Scan_indic of char (* @X *)
+
+(* Formatting element used by the Format pretty-printter. *)
+type ('a, 'b, 'c, 'd, 'e, 'f) formatting_gen =
+ | Open_tag : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> (* @{ *)
+ ('a, 'b, 'c, 'd, 'e, 'f) formatting_gen
+ | Open_box : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> (* @[ *)
+ ('a, 'b, 'c, 'd, 'e, 'f) formatting_gen
+
+(***)
+
+(* List of format type elements. *)
+(* In particular used to represent %(...%) and %{...%} contents. *)
+and ('a, 'b, 'c, 'd, 'e, 'f) fmtty =
+ ('a, 'b, 'c, 'd, 'e, 'f,
+ 'a, 'b, 'c, 'd, 'e, 'f) fmtty_rel
+and ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel =
+ | Char_ty : (* %c *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (char -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ char -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | String_ty : (* %s *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (string -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ string -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | Int_ty : (* %d *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (int -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ int -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | Int32_ty : (* %ld *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (int32 -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ int32 -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | Nativeint_ty : (* %nd *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (nativeint -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ nativeint -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | Int64_ty : (* %Ld *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (int64 -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ int64 -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | Float_ty : (* %f *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (float -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ float -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | Bool_ty : (* %B *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (bool -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ bool -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+
+ | Format_arg_ty : (* %{...%} *)
+ ('g, 'h, 'i, 'j, 'k, 'l) fmtty *
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ ('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2)
+ fmtty_rel
+ | Format_subst_ty : (* %(...%) *)
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g1, 'b1, 'c1, 'j1, 'd1, 'a1) fmtty_rel *
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g2, 'b2, 'c2, 'j2, 'd2, 'a2) fmtty_rel *
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g1, 'b1, 'c1, 'j1, 'e1, 'f1,
+ ('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g2, 'b2, 'c2, 'j2, 'e2, 'f2)
+ fmtty_rel
+
+ (* Printf and Format specific constructors. *)
+ | Alpha_ty : (* %a *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('b1 -> 'x -> 'c1) -> 'x -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ ('b2 -> 'x -> 'c2) -> 'x -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | Theta_ty : (* %t *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('b1 -> 'c1) -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ ('b2 -> 'c2) -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+ | Any_ty : (* Used for custom formats *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ ('x -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'x -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+
+ (* Scanf specific constructor. *)
+ | Reader_ty : (* %r *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ ('x -> 'a1, 'b1, 'c1, ('b1 -> 'x) -> 'd1, 'e1, 'f1,
+ 'x -> 'a2, 'b2, 'c2, ('b2 -> 'x) -> 'd2, 'e2, 'f2) fmtty_rel
+ | Ignored_reader_ty : (* %_r *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ ('a1, 'b1, 'c1, ('b1 -> 'x) -> 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, ('b2 -> 'x) -> 'd2, 'e2, 'f2) fmtty_rel
+
+ | End_of_fmtty :
+ ('f1, 'b1, 'c1, 'd1, 'd1, 'f1,
+ 'f2, 'b2, 'c2, 'd2, 'd2, 'f2) fmtty_rel
+
+(***)
+
+(* List of format elements. *)
+and ('a, 'b, 'c, 'd, 'e, 'f) fmt =
+ | Char : (* %c *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (char -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Caml_char : (* %C *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (char -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ | String : (* %s *)
+ ('x, string -> 'a) padding * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+ | Caml_string : (* %S *)
+ ('x, string -> 'a) padding * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+ | Int : (* %[dixXuo] *)
+ int_conv * ('x, 'y) padding * ('y, int -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+ | Int32 : (* %l[dixXuo] *)
+ int_conv * ('x, 'y) padding * ('y, int32 -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+ | Nativeint : (* %n[dixXuo] *)
+ int_conv * ('x, 'y) padding * ('y, nativeint -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+ | Int64 : (* %L[dixXuo] *)
+ int_conv * ('x, 'y) padding * ('y, int64 -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+ | Float : (* %[feEgGF] *)
+ float_conv * ('x, 'y) padding * ('y, float -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+ | Bool : (* %[bB] *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (bool -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Flush : (* %! *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+
+ | String_literal : (* abc *)
+ string * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Char_literal : (* x *)
+ char * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+
+ | Format_arg : (* %{...%} *)
+ pad_option * ('g, 'h, 'i, 'j, 'k, 'l) fmtty *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Format_subst : (* %(...%) *)
+ pad_option *
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g2, 'b, 'c, 'j2, 'd, 'a) fmtty_rel *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g2, 'b, 'c, 'j2, 'e, 'f) fmt
+
+ (* Printf and Format specific constructor. *)
+ | Alpha : (* %a *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('b -> 'x -> 'c) -> 'x -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Theta : (* %t *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('b -> 'c) -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+
+ (* Format specific constructor: *)
+ | Formatting_lit : (* @_ *)
+ formatting_lit * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Formatting_gen : (* @_ *)
+ ('a1, 'b, 'c, 'd1, 'e1, 'f1) formatting_gen *
+ ('f1, 'b, 'c, 'e1, 'e2, 'f2) fmt -> ('a1, 'b, 'c, 'd1, 'e2, 'f2) fmt
+
+ (* Scanf specific constructors: *)
+ | Reader : (* %r *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x -> 'a, 'b, 'c, ('b -> 'x) -> 'd, 'e, 'f) fmt
+ | Scan_char_set : (* %[...] *)
+ pad_option * char_set * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (string -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Scan_get_counter : (* %[nlNL] *)
+ counter * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (int -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Scan_next_char : (* %0c *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (char -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ | Ignored_param : (* %_ *)
+ ('a, 'b, 'c, 'd, 'y, 'x) ignored * ('x, 'b, 'c, 'y, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+
+ (* Custom printing format (PR#6452, GPR#140)
+
+ We include a type Custom of "custom converters", where an
+ arbitrary function can be used to convert one or more
+ arguments. There is no syntax for custom converters, it is only
+ inteded for custom processors that wish to rely on the
+ stdlib-defined format GADTs.
+
+ For instance a pre-processor could choose to interpret strings
+ prefixed with ["!"] as format strings where [%{{ ... }}] is
+ a special form to pass a to_string function, so that one could
+ write:
+
+ {[
+ type t = { x : int; y : int }
+
+ let string_of_t t = Printf.sprintf "{ x = %d; y = %d }" t.x t.y
+
+ Printf.printf !"t = %{{string_of_t}}" { x = 42; y = 42 }
+ ]}
+ *)
+ | Custom :
+ ('a, 'x, 'y) custom_arity * (unit -> 'x) * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('y, 'b, 'c, 'd, 'e, 'f) fmt
+
+ (* end of a format specification *)
+ | End_of_format :
+ ('f, 'b, 'c, 'e, 'e, 'f) fmt
+
+(***)
+
+(* Type for ignored parameters (see "%_"). *)
+and ('a, 'b, 'c, 'd, 'e, 'f) ignored =
+ | Ignored_char : (* %_c *)
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_caml_char : (* %_C *)
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_string : (* %_s *)
+ pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_caml_string : (* %_S *)
+ pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_int : (* %_d *)
+ int_conv * pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_int32 : (* %_ld *)
+ int_conv * pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_nativeint : (* %_nd *)
+ int_conv * pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_int64 : (* %_Ld *)
+ int_conv * pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_float : (* %_f *)
+ pad_option * prec_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_bool : (* %_B *)
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_format_arg : (* %_{...%} *)
+ pad_option * ('g, 'h, 'i, 'j, 'k, 'l) fmtty ->
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_format_subst : (* %_(...%) *)
+ pad_option * ('a, 'b, 'c, 'd, 'e, 'f) fmtty ->
+ ('a, 'b, 'c, 'd, 'e, 'f) ignored
+ | Ignored_reader : (* %_r *)
+ ('a, 'b, 'c, ('b -> 'x) -> 'd, 'd, 'a) ignored
+ | Ignored_scan_char_set : (* %_[...] *)
+ pad_option * char_set -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_scan_get_counter : (* %_[nlNL] *)
+ counter -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_scan_next_char : (* %_0c *)
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+
+and ('a, 'b, 'c, 'd, 'e, 'f) format6 =
+ Format of ('a, 'b, 'c, 'd, 'e, 'f) fmt * string
+
+let rec erase_rel : type a b c d e f g h i j k l .
+ (a, b, c, d, e, f,
+ g, h, i, j, k, l) fmtty_rel -> (a, b, c, d, e, f) fmtty
+= function
+ | Char_ty rest ->
+ Char_ty (erase_rel rest)
+ | String_ty rest ->
+ String_ty (erase_rel rest)
+ | Int_ty rest ->
+ Int_ty (erase_rel rest)
+ | Int32_ty rest ->
+ Int32_ty (erase_rel rest)
+ | Int64_ty rest ->
+ Int64_ty (erase_rel rest)
+ | Nativeint_ty rest ->
+ Nativeint_ty (erase_rel rest)
+ | Float_ty rest ->
+ Float_ty (erase_rel rest)
+ | Bool_ty rest ->
+ Bool_ty (erase_rel rest)
+ | Format_arg_ty (ty, rest) ->
+ Format_arg_ty (ty, erase_rel rest)
+ | Format_subst_ty (ty1, ty2, rest) ->
+ Format_subst_ty (ty1, ty1, erase_rel rest)
+ | Alpha_ty rest ->
+ Alpha_ty (erase_rel rest)
+ | Theta_ty rest ->
+ Theta_ty (erase_rel rest)
+ | Any_ty rest ->
+ Any_ty (erase_rel rest)
+ | Reader_ty rest ->
+ Reader_ty (erase_rel rest)
+ | Ignored_reader_ty rest ->
+ Ignored_reader_ty (erase_rel rest)
+ | End_of_fmtty -> End_of_fmtty
+
+(******************************************************************************)
+ (* Format type concatenation *)
+
+(* Concatenate two format types. *)
+(* Used by:
+ * reader_nb_unifier_of_fmtty to count readers in an fmtty,
+ * Scanf.take_fmtty_format_readers to extract readers inside %(...%),
+ * CamlinternalFormat.fmtty_of_ignored_format to extract format type. *)
+
+(*
+let rec concat_fmtty : type a b c d e f g h .
+ (a, b, c, d, e, f) fmtty ->
+ (f, b, c, e, g, h) fmtty ->
+ (a, b, c, d, g, h) fmtty =
+*)
+let rec concat_fmtty :
+ type a1 b1 c1 d1 e1 f1
+ a2 b2 c2 d2 e2 f2
+ g1 j1 g2 j2
+ .
+ (g1, b1, c1, j1, d1, a1,
+ g2, b2, c2, j2, d2, a2) fmtty_rel ->
+ (a1, b1, c1, d1, e1, f1,
+ a2, b2, c2, d2, e2, f2) fmtty_rel ->
+ (g1, b1, c1, j1, e1, f1,
+ g2, b2, c2, j2, e2, f2) fmtty_rel =
+fun fmtty1 fmtty2 -> match fmtty1 with
+ | Char_ty rest ->
+ Char_ty (concat_fmtty rest fmtty2)
+ | String_ty rest ->
+ String_ty (concat_fmtty rest fmtty2)
+ | Int_ty rest ->
+ Int_ty (concat_fmtty rest fmtty2)
+ | Int32_ty rest ->
+ Int32_ty (concat_fmtty rest fmtty2)
+ | Nativeint_ty rest ->
+ Nativeint_ty (concat_fmtty rest fmtty2)
+ | Int64_ty rest ->
+ Int64_ty (concat_fmtty rest fmtty2)
+ | Float_ty rest ->
+ Float_ty (concat_fmtty rest fmtty2)
+ | Bool_ty rest ->
+ Bool_ty (concat_fmtty rest fmtty2)
+ | Alpha_ty rest ->
+ Alpha_ty (concat_fmtty rest fmtty2)
+ | Theta_ty rest ->
+ Theta_ty (concat_fmtty rest fmtty2)
+ | Any_ty rest ->
+ Any_ty (concat_fmtty rest fmtty2)
+ | Reader_ty rest ->
+ Reader_ty (concat_fmtty rest fmtty2)
+ | Ignored_reader_ty rest ->
+ Ignored_reader_ty (concat_fmtty rest fmtty2)
+ | Format_arg_ty (ty, rest) ->
+ Format_arg_ty (ty, concat_fmtty rest fmtty2)
+ | Format_subst_ty (ty1, ty2, rest) ->
+ Format_subst_ty (ty1, ty2, concat_fmtty rest fmtty2)
+ | End_of_fmtty -> fmtty2
+
+(******************************************************************************)
+ (* Format concatenation *)
+
+(* Concatenate two formats. *)
+let rec concat_fmt : type a b c d e f g h .
+ (a, b, c, d, e, f) fmt ->
+ (f, b, c, e, g, h) fmt ->
+ (a, b, c, d, g, h) fmt =
+fun fmt1 fmt2 -> match fmt1 with
+ | String (pad, rest) ->
+ String (pad, concat_fmt rest fmt2)
+ | Caml_string (pad, rest) ->
+ Caml_string (pad, concat_fmt rest fmt2)
+
+ | Int (iconv, pad, prec, rest) ->
+ Int (iconv, pad, prec, concat_fmt rest fmt2)
+ | Int32 (iconv, pad, prec, rest) ->
+ Int32 (iconv, pad, prec, concat_fmt rest fmt2)
+ | Nativeint (iconv, pad, prec, rest) ->
+ Nativeint (iconv, pad, prec, concat_fmt rest fmt2)
+ | Int64 (iconv, pad, prec, rest) ->
+ Int64 (iconv, pad, prec, concat_fmt rest fmt2)
+ | Float (fconv, pad, prec, rest) ->
+ Float (fconv, pad, prec, concat_fmt rest fmt2)
+
+ | Char (rest) ->
+ Char (concat_fmt rest fmt2)
+ | Caml_char rest ->
+ Caml_char (concat_fmt rest fmt2)
+ | Bool rest ->
+ Bool (concat_fmt rest fmt2)
+ | Alpha rest ->
+ Alpha (concat_fmt rest fmt2)
+ | Theta rest ->
+ Theta (concat_fmt rest fmt2)
+ | Custom (arity, f, rest) ->
+ Custom (arity, f, concat_fmt rest fmt2)
+ | Reader rest ->
+ Reader (concat_fmt rest fmt2)
+ | Flush rest ->
+ Flush (concat_fmt rest fmt2)
+
+ | String_literal (str, rest) ->
+ String_literal (str, concat_fmt rest fmt2)
+ | Char_literal (chr, rest) ->
+ Char_literal (chr, concat_fmt rest fmt2)
+
+ | Format_arg (pad, fmtty, rest) ->
+ Format_arg (pad, fmtty, concat_fmt rest fmt2)
+ | Format_subst (pad, fmtty, rest) ->
+ Format_subst (pad, fmtty, concat_fmt rest fmt2)
+
+ | Scan_char_set (width_opt, char_set, rest) ->
+ Scan_char_set (width_opt, char_set, concat_fmt rest fmt2)
+ | Scan_get_counter (counter, rest) ->
+ Scan_get_counter (counter, concat_fmt rest fmt2)
+ | Scan_next_char (rest) ->
+ Scan_next_char (concat_fmt rest fmt2)
+ | Ignored_param (ign, rest) ->
+ Ignored_param (ign, concat_fmt rest fmt2)
+
+ | Formatting_lit (fmting_lit, rest) ->
+ Formatting_lit (fmting_lit, concat_fmt rest fmt2)
+ | Formatting_gen (fmting_gen, rest) ->
+ Formatting_gen (fmting_gen, concat_fmt rest fmt2)
+
+ | End_of_format ->
+ fmt2
diff --git a/stdlib/camlinternalFormatBasics.mli b/stdlib/camlinternalFormatBasics.mli
new file mode 100644
index 0000000000..ee0235661b
--- /dev/null
+++ b/stdlib/camlinternalFormatBasics.mli
@@ -0,0 +1,322 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benoit Vaugon, ENSTA *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* No comments, OCaml stdlib internal use only. *)
+
+type padty = Left | Right | Zeros
+
+type int_conv =
+ | Int_d | Int_pd | Int_sd | Int_i | Int_pi | Int_si
+ | Int_x | Int_Cx | Int_X | Int_CX | Int_o | Int_Co | Int_u
+
+type float_conv =
+ | Float_f | Float_pf | Float_sf | Float_e | Float_pe | Float_se
+ | Float_E | Float_pE | Float_sE | Float_g | Float_pg | Float_sg
+ | Float_G | Float_pG | Float_sG | Float_F
+
+type char_set = string
+
+type counter = Line_counter | Char_counter | Token_counter
+
+type ('a, 'b) padding =
+ | No_padding : ('a, 'a) padding
+ | Lit_padding : padty * int -> ('a, 'a) padding
+ | Arg_padding : padty -> (int -> 'a, 'a) padding
+
+type pad_option = int option
+
+type ('a, 'b) precision =
+ | No_precision : ('a, 'a) precision
+ | Lit_precision : int -> ('a, 'a) precision
+ | Arg_precision : (int -> 'a, 'a) precision
+
+type prec_option = int option
+
+type ('a, 'b, 'c) custom_arity =
+ | Custom_zero : ('a, string, 'a) custom_arity
+ | Custom_succ : ('a, 'b, 'c) custom_arity ->
+ ('a, 'x -> 'b, 'x -> 'c) custom_arity
+
+type block_type = Pp_hbox | Pp_vbox | Pp_hvbox | Pp_hovbox | Pp_box | Pp_fits
+
+type formatting_lit =
+ | Close_box
+ | Close_tag
+ | Break of string * int * int
+ | FFlush
+ | Force_newline
+ | Flush_newline
+ | Magic_size of string * int
+ | Escaped_at
+ | Escaped_percent
+ | Scan_indic of char
+
+type ('a, 'b, 'c, 'd, 'e, 'f) formatting_gen =
+ | Open_tag : ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) formatting_gen
+ | Open_box : ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) formatting_gen
+
+and ('a, 'b, 'c, 'd, 'e, 'f) fmtty =
+ ('a, 'b, 'c, 'd, 'e, 'f,
+ 'a, 'b, 'c, 'd, 'e, 'f) fmtty_rel
+and ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel =
+| Char_ty : (* %c *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (char -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ char -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| String_ty : (* %s *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (string -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ string -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Int_ty : (* %d *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (int -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ int -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Int32_ty : (* %ld *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (int32 -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ int32 -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Nativeint_ty : (* %nd *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (nativeint -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ nativeint -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Int64_ty : (* %Ld *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (int64 -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ int64 -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Float_ty : (* %f *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (float -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ float -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Bool_ty : (* %B *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (bool -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ bool -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Format_arg_ty : (* %{...%} *)
+ ('g, 'h, 'i, 'j, 'k, 'l) fmtty *
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ ('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Format_subst_ty : (* %(...%) *)
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g1, 'b1, 'c1, 'j1, 'd1, 'a1) fmtty_rel *
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g2, 'b2, 'c2, 'j2, 'd2, 'a2) fmtty_rel *
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g1, 'b1, 'c1, 'j1, 'e1, 'f1,
+ ('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g2, 'b2, 'c2, 'j2, 'e2, 'f2) fmtty_rel
+
+(* Printf and Format specific constructors. *)
+| Alpha_ty : (* %a *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('b1 -> 'x -> 'c1) -> 'x -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ ('b2 -> 'x -> 'c2) -> 'x -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Theta_ty : (* %t *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ (('b1 -> 'c1) -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ ('b2 -> 'c2) -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+| Any_ty : (* Used for custom formats *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ ('x -> 'a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'x -> 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel
+
+(* Scanf specific constructor. *)
+| Reader_ty : (* %r *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ ('x -> 'a1, 'b1, 'c1, ('b1 -> 'x) -> 'd1, 'e1, 'f1,
+ 'x -> 'a2, 'b2, 'c2, ('b2 -> 'x) -> 'd2, 'e2, 'f2) fmtty_rel
+| Ignored_reader_ty : (* %_r *)
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ ('a1, 'b1, 'c1, ('b1 -> 'x) -> 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, ('b2 -> 'x) -> 'd2, 'e2, 'f2) fmtty_rel
+
+| End_of_fmtty :
+ ('f1, 'b1, 'c1, 'd1, 'd1, 'f1,
+ 'f2, 'b2, 'c2, 'd2, 'd2, 'f2) fmtty_rel
+
+(**)
+
+(** List of format elements. *)
+and ('a, 'b, 'c, 'd, 'e, 'f) fmt =
+| Char : (* %c *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (char -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+| Caml_char : (* %C *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (char -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+| String : (* %s *)
+ ('x, string -> 'a) padding * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+| Caml_string : (* %S *)
+ ('x, string -> 'a) padding * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+| Int : (* %[dixXuo] *)
+ int_conv * ('x, 'y) padding * ('y, int -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+| Int32 : (* %l[dixXuo] *)
+ int_conv * ('x, 'y) padding * ('y, int32 -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+| Nativeint : (* %n[dixXuo] *)
+ int_conv * ('x, 'y) padding * ('y, nativeint -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+| Int64 : (* %L[dixXuo] *)
+ int_conv * ('x, 'y) padding * ('y, int64 -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+| Float : (* %[feEgGF] *)
+ float_conv * ('x, 'y) padding * ('y, float -> 'a) precision *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x, 'b, 'c, 'd, 'e, 'f) fmt
+| Bool : (* %[bB] *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (bool -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+| Flush : (* %! *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+
+| String_literal : (* abc *)
+ string * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+| Char_literal : (* x *)
+ char * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+
+| Format_arg : (* %{...%} *)
+ pad_option * ('g, 'h, 'i, 'j, 'k, 'l) fmtty *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+| Format_subst : (* %(...%) *)
+ pad_option *
+ ('g, 'h, 'i, 'j, 'k, 'l,
+ 'g2, 'b, 'c, 'j2, 'd, 'a) fmtty_rel *
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('g, 'h, 'i, 'j, 'k, 'l) format6 -> 'g2, 'b, 'c, 'j2, 'e, 'f) fmt
+
+(* Printf and Format specific constructor. *)
+| Alpha : (* %a *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('b -> 'x -> 'c) -> 'x -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+| Theta : (* %t *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (('b -> 'c) -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+
+(* Format specific constructor: *)
+| Formatting_lit : (* @_ *)
+ formatting_lit * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+| Formatting_gen : (* @_ *)
+ ('a1, 'b, 'c, 'd1, 'e1, 'f1) formatting_gen *
+ ('f1, 'b, 'c, 'e1, 'e2, 'f2) fmt -> ('a1, 'b, 'c, 'd1, 'e2, 'f2) fmt
+
+(* Scanf specific constructors: *)
+| Reader : (* %r *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('x -> 'a, 'b, 'c, ('b -> 'x) -> 'd, 'e, 'f) fmt
+| Scan_char_set : (* %[...] *)
+ pad_option * char_set * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (string -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+| Scan_get_counter : (* %[nlNL] *)
+ counter * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (int -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+| Scan_next_char : (* %0c *)
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ (char -> 'a, 'b, 'c, 'd, 'e, 'f) fmt
+ (* %0c behaves as %c for printing, but when scanning it does not
+ consume the character from the input stream *)
+| Ignored_param : (* %_ *)
+ ('a, 'b, 'c, 'd, 'y, 'x) ignored * ('x, 'b, 'c, 'y, 'e, 'f) fmt ->
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt
+
+(* Custom printing format *)
+| Custom :
+ ('a, 'x, 'y) custom_arity * (unit -> 'x) * ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('y, 'b, 'c, 'd, 'e, 'f) fmt
+
+| End_of_format :
+ ('f, 'b, 'c, 'e, 'e, 'f) fmt
+
+and ('a, 'b, 'c, 'd, 'e, 'f) ignored =
+ | Ignored_char :
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_caml_char :
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_string :
+ pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_caml_string :
+ pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_int :
+ int_conv * pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_int32 :
+ int_conv * pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_nativeint :
+ int_conv * pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_int64 :
+ int_conv * pad_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_float :
+ pad_option * prec_option -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_bool :
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_format_arg :
+ pad_option * ('g, 'h, 'i, 'j, 'k, 'l) fmtty ->
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_format_subst :
+ pad_option * ('a, 'b, 'c, 'd, 'e, 'f) fmtty ->
+ ('a, 'b, 'c, 'd, 'e, 'f) ignored
+ | Ignored_reader :
+ ('a, 'b, 'c, ('b -> 'x) -> 'd, 'd, 'a) ignored
+ | Ignored_scan_char_set :
+ pad_option * char_set -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_scan_get_counter :
+ counter -> ('a, 'b, 'c, 'd, 'd, 'a) ignored
+ | Ignored_scan_next_char :
+ ('a, 'b, 'c, 'd, 'd, 'a) ignored
+
+and ('a, 'b, 'c, 'd, 'e, 'f) format6 =
+ Format of ('a, 'b, 'c, 'd, 'e, 'f) fmt * string
+
+val concat_fmtty :
+ ('g1, 'b1, 'c1, 'j1, 'd1, 'a1,
+ 'g2, 'b2, 'c2, 'j2, 'd2, 'a2) fmtty_rel ->
+ ('a1, 'b1, 'c1, 'd1, 'e1, 'f1,
+ 'a2, 'b2, 'c2, 'd2, 'e2, 'f2) fmtty_rel ->
+ ('g1, 'b1, 'c1, 'j1, 'e1, 'f1,
+ 'g2, 'b2, 'c2, 'j2, 'e2, 'f2) fmtty_rel
+
+val erase_rel :
+ ('a, 'b, 'c, 'd, 'e, 'f,
+ 'g, 'h, 'i, 'j, 'k, 'l) fmtty_rel -> ('a, 'b, 'c, 'd, 'e, 'f) fmtty
+
+val concat_fmt :
+ ('a, 'b, 'c, 'd, 'e, 'f) fmt ->
+ ('f, 'b, 'c, 'e, 'g, 'h) fmt ->
+ ('a, 'b, 'c, 'd, 'g, 'h) fmt
diff --git a/stdlib/camlinternalLazy.ml b/stdlib/camlinternalLazy.ml
new file mode 100644
index 0000000000..dfdb19c741
--- /dev/null
+++ b/stdlib/camlinternalLazy.ml
@@ -0,0 +1,64 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Internals of forcing lazy values. *)
+
+exception Undefined;;
+
+let raise_undefined = Obj.repr (fun () -> raise Undefined);;
+
+(* Assume [blk] is a block with tag lazy *)
+let force_lazy_block (blk : 'arg lazy_t) =
+ let closure = (Obj.obj (Obj.field (Obj.repr blk) 0) : unit -> 'arg) in
+ Obj.set_field (Obj.repr blk) 0 raise_undefined;
+ try
+ let result = closure () in
+ (* do set_field BEFORE set_tag *)
+ Obj.set_field (Obj.repr blk) 0 (Obj.repr result);
+ Obj.set_tag (Obj.repr blk) Obj.forward_tag;
+ result
+ with e ->
+ Obj.set_field (Obj.repr blk) 0 (Obj.repr (fun () -> raise e));
+ raise e
+;;
+
+(* Assume [blk] is a block with tag lazy *)
+let force_val_lazy_block (blk : 'arg lazy_t) =
+ let closure = (Obj.obj (Obj.field (Obj.repr blk) 0) : unit -> 'arg) in
+ Obj.set_field (Obj.repr blk) 0 raise_undefined;
+ let result = closure () in
+ (* do set_field BEFORE set_tag *)
+ Obj.set_field (Obj.repr blk) 0 (Obj.repr result);
+ Obj.set_tag (Obj.repr blk) (Obj.forward_tag);
+ result
+;;
+
+(* [force] is not used, since [Lazy.force] is declared as a primitive
+ whose code inlines the tag tests of its argument. This function is
+ here for the sake of completeness, and for debugging purpose. *)
+
+let force (lzv : 'arg lazy_t) =
+ let x = Obj.repr lzv in
+ let t = Obj.tag x in
+ if t = Obj.forward_tag then (Obj.obj (Obj.field x 0) : 'arg) else
+ if t <> Obj.lazy_tag then (Obj.obj x : 'arg)
+ else force_lazy_block lzv
+;;
+
+let force_val (lzv : 'arg lazy_t) =
+ let x = Obj.repr lzv in
+ let t = Obj.tag x in
+ if t = Obj.forward_tag then (Obj.obj (Obj.field x 0) : 'arg) else
+ if t <> Obj.lazy_tag then (Obj.obj x : 'arg)
+ else force_val_lazy_block lzv
+;;
diff --git a/stdlib/camlinternalLazy.mli b/stdlib/camlinternalLazy.mli
new file mode 100644
index 0000000000..27f87d14d3
--- /dev/null
+++ b/stdlib/camlinternalLazy.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Run-time support for lazy values.
+ All functions in this module are for system use only, not for the
+ casual user. *)
+
+exception Undefined;;
+
+val force_lazy_block : 'a lazy_t -> 'a ;;
+
+val force_val_lazy_block : 'a lazy_t -> 'a ;;
+
+val force : 'a lazy_t -> 'a ;;
+val force_val : 'a lazy_t -> 'a ;;
diff --git a/stdlib/camlinternalMod.ml b/stdlib/camlinternalMod.ml
new file mode 100644
index 0000000000..937d8d991e
--- /dev/null
+++ b/stdlib/camlinternalMod.ml
@@ -0,0 +1,72 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2004 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type shape =
+ | Function
+ | Lazy
+ | Class
+ | Module of shape array
+ | Value of Obj.t
+
+let overwrite o n =
+ assert (Obj.size o >= Obj.size n);
+ for i = 0 to Obj.size n - 1 do
+ Obj.set_field o i (Obj.field n i)
+ done
+
+let rec init_mod loc shape =
+ match shape with
+ | Function ->
+ (* Two code pointer words (curried and full application), arity
+ and eight environment entries makes 11 words. *)
+ let closure = Obj.new_block Obj.closure_tag 11 in
+ let template =
+ Obj.repr (fun _ -> raise (Undefined_recursive_module loc))
+ in
+ overwrite closure template;
+ closure
+ | Lazy ->
+ Obj.repr (lazy (raise (Undefined_recursive_module loc)))
+ | Class ->
+ Obj.repr (CamlinternalOO.dummy_class loc)
+ | Module comps ->
+ Obj.repr (Array.map (init_mod loc) comps)
+ | Value v ->
+ v
+
+let rec update_mod shape o n =
+ match shape with
+ | Function ->
+ if Obj.tag n = Obj.closure_tag && Obj.size n <= Obj.size o
+ then begin overwrite o n; Obj.truncate o (Obj.size n) (* PR #4008 *) end
+ else overwrite o (Obj.repr (fun x -> (Obj.obj n : _ -> _) x))
+ | Lazy ->
+ if Obj.tag n = Obj.lazy_tag then
+ Obj.set_field o 0 (Obj.field n 0)
+ else if Obj.tag n = Obj.forward_tag then begin (* PR#4316 *)
+ Obj.set_tag o Obj.forward_tag;
+ Obj.set_field o 0 (Obj.field n 0)
+ end else begin
+ (* forwarding pointer was shortcut by GC *)
+ Obj.set_tag o Obj.forward_tag;
+ Obj.set_field o 0 n
+ end
+ | Class ->
+ assert (Obj.tag n = 0 && Obj.size n = 4);
+ overwrite o n
+ | Module comps ->
+ assert (Obj.tag n = 0 && Obj.size n >= Array.length comps);
+ for i = 0 to Array.length comps - 1 do
+ update_mod comps.(i) (Obj.field o i) (Obj.field n i)
+ done
+ | Value v -> () (* the value is already there *)
diff --git a/stdlib/camlinternalMod.mli b/stdlib/camlinternalMod.mli
new file mode 100644
index 0000000000..96535d0e3a
--- /dev/null
+++ b/stdlib/camlinternalMod.mli
@@ -0,0 +1,26 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2004 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Run-time support for recursive modules.
+ All functions in this module are for system use only, not for the
+ casual user. *)
+
+type shape =
+ | Function
+ | Lazy
+ | Class
+ | Module of shape array
+ | Value of Obj.t
+
+val init_mod: string * int * int -> shape -> Obj.t
+val update_mod: shape -> Obj.t -> Obj.t -> unit
diff --git a/stdlib/camlinternalOO.ml b/stdlib/camlinternalOO.ml
new file mode 100644
index 0000000000..3c39c0b672
--- /dev/null
+++ b/stdlib/camlinternalOO.ml
@@ -0,0 +1,586 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Obj
+
+(**** Object representation ****)
+
+external set_id: 'a -> 'a = "caml_set_oo_id" "noalloc"
+
+(**** Object copy ****)
+
+let copy o =
+ let o = (Obj.obj (Obj.dup (Obj.repr o))) in
+ set_id o
+
+(**** Compression options ****)
+(* Parameters *)
+type params = {
+ mutable compact_table : bool;
+ mutable copy_parent : bool;
+ mutable clean_when_copying : bool;
+ mutable retry_count : int;
+ mutable bucket_small_size : int
+ }
+
+let params = {
+ compact_table = true;
+ copy_parent = true;
+ clean_when_copying = true;
+ retry_count = 3;
+ bucket_small_size = 16
+}
+
+(**** Parameters ****)
+
+let step = Sys.word_size / 16
+let initial_object_size = 2
+
+(**** Items ****)
+
+type item = DummyA | DummyB | DummyC of int
+let _ = [DummyA; DummyB; DummyC 0] (* to avoid warnings *)
+
+let dummy_item = (magic () : item)
+
+(**** Types ****)
+
+type tag
+type label = int
+type closure = item
+type t = DummyA | DummyB | DummyC of int
+let _ = [DummyA; DummyB; DummyC 0] (* to avoid warnings *)
+
+type obj = t array
+external ret : (obj -> 'a) -> closure = "%identity"
+
+(**** Labels ****)
+
+let public_method_label s : tag =
+ let accu = ref 0 in
+ for i = 0 to String.length s - 1 do
+ accu := 223 * !accu + Char.code s.[i]
+ done;
+ (* reduce to 31 bits *)
+ accu := !accu land (1 lsl 31 - 1);
+ (* make it signed for 64 bits architectures *)
+ let tag = if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu in
+ (* Printf.eprintf "%s = %d\n" s tag; flush stderr; *)
+ magic tag
+
+(**** Sparse array ****)
+
+module Vars =
+ Map.Make(struct type t = string let compare (x:t) y = compare x y end)
+type vars = int Vars.t
+
+module Meths =
+ Map.Make(struct type t = string let compare (x:t) y = compare x y end)
+type meths = label Meths.t
+module Labs =
+ Map.Make(struct type t = label let compare (x:t) y = compare x y end)
+type labs = bool Labs.t
+
+(* The compiler assumes that the first field of this structure is [size]. *)
+type table =
+ { mutable size: int;
+ mutable methods: closure array;
+ mutable methods_by_name: meths;
+ mutable methods_by_label: labs;
+ mutable previous_states:
+ (meths * labs * (label * item) list * vars *
+ label list * string list) list;
+ mutable hidden_meths: (label * item) list;
+ mutable vars: vars;
+ mutable initializers: (obj -> unit) list }
+
+let dummy_table =
+ { methods = [| dummy_item |];
+ methods_by_name = Meths.empty;
+ methods_by_label = Labs.empty;
+ previous_states = [];
+ hidden_meths = [];
+ vars = Vars.empty;
+ initializers = [];
+ size = 0 }
+
+let table_count = ref 0
+
+(* dummy_met should be a pointer, so use an atom *)
+let dummy_met : item = obj (Obj.new_block 0 0)
+(* if debugging is needed, this could be a good idea: *)
+(* let dummy_met () = failwith "Undefined method" *)
+
+let rec fit_size n =
+ if n <= 2 then n else
+ fit_size ((n+1)/2) * 2
+
+let new_table pub_labels =
+ incr table_count;
+ let len = Array.length pub_labels in
+ let methods = Array.make (len*2+2) dummy_met in
+ methods.(0) <- magic len;
+ methods.(1) <- magic (fit_size len * Sys.word_size / 8 - 1);
+ for i = 0 to len - 1 do methods.(i*2+3) <- magic pub_labels.(i) done;
+ { methods = methods;
+ methods_by_name = Meths.empty;
+ methods_by_label = Labs.empty;
+ previous_states = [];
+ hidden_meths = [];
+ vars = Vars.empty;
+ initializers = [];
+ size = initial_object_size }
+
+let resize array new_size =
+ let old_size = Array.length array.methods in
+ if new_size > old_size then begin
+ let new_buck = Array.make new_size dummy_met in
+ Array.blit array.methods 0 new_buck 0 old_size;
+ array.methods <- new_buck
+ end
+
+let put array label element =
+ resize array (label + 1);
+ array.methods.(label) <- element
+
+(**** Classes ****)
+
+let method_count = ref 0
+let inst_var_count = ref 0
+
+(* type t *)
+type meth = item
+
+let new_method table =
+ let index = Array.length table.methods in
+ resize table (index + 1);
+ index
+
+let get_method_label table name =
+ try
+ Meths.find name table.methods_by_name
+ with Not_found ->
+ let label = new_method table in
+ table.methods_by_name <- Meths.add name label table.methods_by_name;
+ table.methods_by_label <- Labs.add label true table.methods_by_label;
+ label
+
+let get_method_labels table names =
+ Array.map (get_method_label table) names
+
+let set_method table label element =
+ incr method_count;
+ if Labs.find label table.methods_by_label then
+ put table label element
+ else
+ table.hidden_meths <- (label, element) :: table.hidden_meths
+
+let get_method table label =
+ try List.assoc label table.hidden_meths
+ with Not_found -> table.methods.(label)
+
+let to_list arr =
+ if arr == magic 0 then [] else Array.to_list arr
+
+let narrow table vars virt_meths concr_meths =
+ let vars = to_list vars
+ and virt_meths = to_list virt_meths
+ and concr_meths = to_list concr_meths in
+ let virt_meth_labs = List.map (get_method_label table) virt_meths in
+ let concr_meth_labs = List.map (get_method_label table) concr_meths in
+ table.previous_states <-
+ (table.methods_by_name, table.methods_by_label, table.hidden_meths,
+ table.vars, virt_meth_labs, vars)
+ :: table.previous_states;
+ table.vars <-
+ Vars.fold
+ (fun lab info tvars ->
+ if List.mem lab vars then Vars.add lab info tvars else tvars)
+ table.vars Vars.empty;
+ let by_name = ref Meths.empty in
+ let by_label = ref Labs.empty in
+ List.iter2
+ (fun met label ->
+ by_name := Meths.add met label !by_name;
+ by_label :=
+ Labs.add label
+ (try Labs.find label table.methods_by_label with Not_found -> true)
+ !by_label)
+ concr_meths concr_meth_labs;
+ List.iter2
+ (fun met label ->
+ by_name := Meths.add met label !by_name;
+ by_label := Labs.add label false !by_label)
+ virt_meths virt_meth_labs;
+ table.methods_by_name <- !by_name;
+ table.methods_by_label <- !by_label;
+ table.hidden_meths <-
+ List.fold_right
+ (fun ((lab, _) as met) hm ->
+ if List.mem lab virt_meth_labs then hm else met::hm)
+ table.hidden_meths
+ []
+
+let widen table =
+ let (by_name, by_label, saved_hidden_meths, saved_vars, virt_meths, vars) =
+ List.hd table.previous_states
+ in
+ table.previous_states <- List.tl table.previous_states;
+ table.vars <-
+ List.fold_left
+ (fun s v -> Vars.add v (Vars.find v table.vars) s)
+ saved_vars vars;
+ table.methods_by_name <- by_name;
+ table.methods_by_label <- by_label;
+ table.hidden_meths <-
+ List.fold_right
+ (fun ((lab, _) as met) hm ->
+ if List.mem lab virt_meths then hm else met::hm)
+ table.hidden_meths
+ saved_hidden_meths
+
+let new_slot table =
+ let index = table.size in
+ table.size <- index + 1;
+ index
+
+let new_variable table name =
+ try Vars.find name table.vars
+ with Not_found ->
+ let index = new_slot table in
+ if name <> "" then table.vars <- Vars.add name index table.vars;
+ index
+
+let to_array arr =
+ if arr = Obj.magic 0 then [||] else arr
+
+let new_methods_variables table meths vals =
+ let meths = to_array meths in
+ let nmeths = Array.length meths and nvals = Array.length vals in
+ let res = Array.make (nmeths + nvals) 0 in
+ for i = 0 to nmeths - 1 do
+ res.(i) <- get_method_label table meths.(i)
+ done;
+ for i = 0 to nvals - 1 do
+ res.(i+nmeths) <- new_variable table vals.(i)
+ done;
+ res
+
+let get_variable table name =
+ try Vars.find name table.vars with Not_found -> assert false
+
+let get_variables table names =
+ Array.map (get_variable table) names
+
+let add_initializer table f =
+ table.initializers <- f::table.initializers
+
+(*
+module Keys =
+ Map.Make(struct type t = tag array let compare (x:t) y = compare x y end)
+let key_map = ref Keys.empty
+let get_key tags : item =
+ try magic (Keys.find tags !key_map : tag array)
+ with Not_found ->
+ key_map := Keys.add tags tags !key_map;
+ magic tags
+*)
+
+let create_table public_methods =
+ if public_methods == magic 0 then new_table [||] else
+ (* [public_methods] must be in ascending order for bytecode *)
+ let tags = Array.map public_method_label public_methods in
+ let table = new_table tags in
+ Array.iteri
+ (fun i met ->
+ let lab = i*2+2 in
+ table.methods_by_name <- Meths.add met lab table.methods_by_name;
+ table.methods_by_label <- Labs.add lab true table.methods_by_label)
+ public_methods;
+ table
+
+let init_class table =
+ inst_var_count := !inst_var_count + table.size - 1;
+ table.initializers <- List.rev table.initializers;
+ resize table (3 + magic table.methods.(1) * 16 / Sys.word_size)
+
+let inherits cla vals virt_meths concr_meths (_, super, _, env) top =
+ narrow cla vals virt_meths concr_meths;
+ let init =
+ if top then super cla env else Obj.repr (super cla) in
+ widen cla;
+ Array.concat
+ [[| repr init |];
+ magic (Array.map (get_variable cla) (to_array vals) : int array);
+ Array.map
+ (fun nm -> repr (get_method cla (get_method_label cla nm) : closure))
+ (to_array concr_meths) ]
+
+let make_class pub_meths class_init =
+ let table = create_table pub_meths in
+ let env_init = class_init table in
+ init_class table;
+ (env_init (Obj.repr 0), class_init, env_init, Obj.repr 0)
+
+type init_table = { mutable env_init: t; mutable class_init: table -> t }
+
+let make_class_store pub_meths class_init init_table =
+ let table = create_table pub_meths in
+ let env_init = class_init table in
+ init_class table;
+ init_table.class_init <- class_init;
+ init_table.env_init <- env_init
+
+let dummy_class loc =
+ let undef = fun _ -> raise (Undefined_recursive_module loc) in
+ (Obj.magic undef, undef, undef, Obj.repr 0)
+
+(**** Objects ****)
+
+let create_object table =
+ (* XXX Appel de [obj_block] *)
+ let obj = Obj.new_block Obj.object_tag table.size in
+ (* XXX Appel de [caml_modify] *)
+ Obj.set_field obj 0 (Obj.repr table.methods);
+ Obj.obj (set_id obj)
+
+let create_object_opt obj_0 table =
+ if (Obj.magic obj_0 : bool) then obj_0 else begin
+ (* XXX Appel de [obj_block] *)
+ let obj = Obj.new_block Obj.object_tag table.size in
+ (* XXX Appel de [caml_modify] *)
+ Obj.set_field obj 0 (Obj.repr table.methods);
+ Obj.obj (set_id obj)
+ end
+
+let rec iter_f obj =
+ function
+ [] -> ()
+ | f::l -> f obj; iter_f obj l
+
+let run_initializers obj table =
+ let inits = table.initializers in
+ if inits <> [] then
+ iter_f obj inits
+
+let run_initializers_opt obj_0 obj table =
+ if (Obj.magic obj_0 : bool) then obj else begin
+ let inits = table.initializers in
+ if inits <> [] then iter_f obj inits;
+ obj
+ end
+
+let create_object_and_run_initializers obj_0 table =
+ if (Obj.magic obj_0 : bool) then obj_0 else begin
+ let obj = create_object table in
+ run_initializers obj table;
+ obj
+ end
+
+(* Equivalent primitive below
+let sendself obj lab =
+ (magic obj : (obj -> t) array array).(0).(lab) obj
+*)
+external send : obj -> tag -> 'a = "%send"
+external sendcache : obj -> tag -> t -> int -> 'a = "%sendcache"
+external sendself : obj -> label -> 'a = "%sendself"
+external get_public_method : obj -> tag -> closure
+ = "caml_get_public_method" "noalloc"
+
+(**** table collection access ****)
+
+type tables = Empty | Cons of closure * tables * tables
+type mut_tables =
+ {key: closure; mutable data: tables; mutable next: tables}
+external mut : tables -> mut_tables = "%identity"
+external demut : mut_tables -> tables = "%identity"
+
+let build_path n keys tables =
+ (* Be careful not to create a seemingly immutable block, otherwise it could
+ be statically allocated. See #5779. *)
+ let res = demut {key = Obj.magic 0; data = Empty; next = Empty} in
+ let r = ref res in
+ for i = 0 to n do
+ r := Cons (keys.(i), !r, Empty)
+ done;
+ tables.data <- !r;
+ res
+
+let rec lookup_keys i keys tables =
+ if i < 0 then tables else
+ let key = keys.(i) in
+ let rec lookup_key tables =
+ if tables.key == key then lookup_keys (i-1) keys tables.data else
+ if tables.next <> Empty then lookup_key (mut tables.next) else
+ let next = Cons (key, Empty, Empty) in
+ tables.next <- next;
+ build_path (i-1) keys (mut next)
+ in
+ lookup_key (mut tables)
+
+let lookup_tables root keys =
+ let root = mut root in
+ if root.data <> Empty then
+ lookup_keys (Array.length keys - 1) keys root.data
+ else
+ build_path (Array.length keys - 1) keys root
+
+(**** builtin methods ****)
+
+let get_const x = ret (fun obj -> x)
+let get_var n = ret (fun obj -> Array.unsafe_get obj n)
+let get_env e n =
+ ret (fun obj ->
+ Array.unsafe_get (Obj.magic (Array.unsafe_get obj e) : obj) n)
+let get_meth n = ret (fun obj -> sendself obj n)
+let set_var n = ret (fun obj x -> Array.unsafe_set obj n x)
+let app_const f x = ret (fun obj -> f x)
+let app_var f n = ret (fun obj -> f (Array.unsafe_get obj n))
+let app_env f e n =
+ ret (fun obj ->
+ f (Array.unsafe_get (Obj.magic (Array.unsafe_get obj e) : obj) n))
+let app_meth f n = ret (fun obj -> f (sendself obj n))
+let app_const_const f x y = ret (fun obj -> f x y)
+let app_const_var f x n = ret (fun obj -> f x (Array.unsafe_get obj n))
+let app_const_meth f x n = ret (fun obj -> f x (sendself obj n))
+let app_var_const f n x = ret (fun obj -> f (Array.unsafe_get obj n) x)
+let app_meth_const f n x = ret (fun obj -> f (sendself obj n) x)
+let app_const_env f x e n =
+ ret (fun obj ->
+ f x (Array.unsafe_get (Obj.magic (Array.unsafe_get obj e) : obj) n))
+let app_env_const f e n x =
+ ret (fun obj ->
+ f (Array.unsafe_get (Obj.magic (Array.unsafe_get obj e) : obj) n) x)
+let meth_app_const n x = ret (fun obj -> (sendself obj n : _ -> _) x)
+let meth_app_var n m =
+ ret (fun obj -> (sendself obj n : _ -> _) (Array.unsafe_get obj m))
+let meth_app_env n e m =
+ ret (fun obj -> (sendself obj n : _ -> _)
+ (Array.unsafe_get (Obj.magic (Array.unsafe_get obj e) : obj) m))
+let meth_app_meth n m =
+ ret (fun obj -> (sendself obj n : _ -> _) (sendself obj m))
+let send_const m x c =
+ ret (fun obj -> sendcache x m (Array.unsafe_get obj 0) c)
+let send_var m n c =
+ ret (fun obj ->
+ sendcache (Obj.magic (Array.unsafe_get obj n) : obj) m
+ (Array.unsafe_get obj 0) c)
+let send_env m e n c =
+ ret (fun obj ->
+ sendcache
+ (Obj.magic (Array.unsafe_get
+ (Obj.magic (Array.unsafe_get obj e) : obj) n) : obj)
+ m (Array.unsafe_get obj 0) c)
+let send_meth m n c =
+ ret (fun obj ->
+ sendcache (sendself obj n) m (Array.unsafe_get obj 0) c)
+let new_cache table =
+ let n = new_method table in
+ let n =
+ if n mod 2 = 0 || n > 2 + magic table.methods.(1) * 16 / Sys.word_size
+ then n else new_method table
+ in
+ table.methods.(n) <- Obj.magic 0;
+ n
+
+type impl =
+ GetConst
+ | GetVar
+ | GetEnv
+ | GetMeth
+ | SetVar
+ | AppConst
+ | AppVar
+ | AppEnv
+ | AppMeth
+ | AppConstConst
+ | AppConstVar
+ | AppConstEnv
+ | AppConstMeth
+ | AppVarConst
+ | AppEnvConst
+ | AppMethConst
+ | MethAppConst
+ | MethAppVar
+ | MethAppEnv
+ | MethAppMeth
+ | SendConst
+ | SendVar
+ | SendEnv
+ | SendMeth
+ | Closure of closure
+
+let method_impl table i arr =
+ let next () = incr i; magic arr.(!i) in
+ match next() with
+ GetConst -> let x : t = next() in get_const x
+ | GetVar -> let n = next() in get_var n
+ | GetEnv -> let e = next() and n = next() in get_env e n
+ | GetMeth -> let n = next() in get_meth n
+ | SetVar -> let n = next() in set_var n
+ | AppConst -> let f = next() and x = next() in app_const f x
+ | AppVar -> let f = next() and n = next () in app_var f n
+ | AppEnv ->
+ let f = next() and e = next() and n = next() in app_env f e n
+ | AppMeth -> let f = next() and n = next () in app_meth f n
+ | AppConstConst ->
+ let f = next() and x = next() and y = next() in app_const_const f x y
+ | AppConstVar ->
+ let f = next() and x = next() and n = next() in app_const_var f x n
+ | AppConstEnv ->
+ let f = next() and x = next() and e = next () and n = next() in
+ app_const_env f x e n
+ | AppConstMeth ->
+ let f = next() and x = next() and n = next() in app_const_meth f x n
+ | AppVarConst ->
+ let f = next() and n = next() and x = next() in app_var_const f n x
+ | AppEnvConst ->
+ let f = next() and e = next () and n = next() and x = next() in
+ app_env_const f e n x
+ | AppMethConst ->
+ let f = next() and n = next() and x = next() in app_meth_const f n x
+ | MethAppConst ->
+ let n = next() and x = next() in meth_app_const n x
+ | MethAppVar ->
+ let n = next() and m = next() in meth_app_var n m
+ | MethAppEnv ->
+ let n = next() and e = next() and m = next() in meth_app_env n e m
+ | MethAppMeth ->
+ let n = next() and m = next() in meth_app_meth n m
+ | SendConst ->
+ let m = next() and x = next() in send_const m x (new_cache table)
+ | SendVar ->
+ let m = next() and n = next () in send_var m n (new_cache table)
+ | SendEnv ->
+ let m = next() and e = next() and n = next() in
+ send_env m e n (new_cache table)
+ | SendMeth ->
+ let m = next() and n = next () in send_meth m n (new_cache table)
+ | Closure _ as clo -> magic clo
+
+let set_methods table methods =
+ let len = Array.length methods and i = ref 0 in
+ while !i < len do
+ let label = methods.(!i) and clo = method_impl table i methods in
+ set_method table label clo;
+ incr i
+ done
+
+(**** Statistics ****)
+
+type stats =
+ { classes: int; methods: int; inst_vars: int; }
+
+let stats () =
+ { classes = !table_count;
+ methods = !method_count; inst_vars = !inst_var_count; }
diff --git a/stdlib/camlinternalOO.mli b/stdlib/camlinternalOO.mli
new file mode 100644
index 0000000000..afbe61bb9f
--- /dev/null
+++ b/stdlib/camlinternalOO.mli
@@ -0,0 +1,151 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Run-time support for objects and classes.
+ All functions in this module are for system use only, not for the
+ casual user. *)
+
+(** {6 Classes} *)
+
+type tag
+type label
+type table
+type meth
+type t
+type obj
+type closure
+val public_method_label : string -> tag
+val new_method : table -> label
+val new_variable : table -> string -> int
+val new_methods_variables :
+ table -> string array -> string array -> label array
+val get_variable : table -> string -> int
+val get_variables : table -> string array -> int array
+val get_method_label : table -> string -> label
+val get_method_labels : table -> string array -> label array
+val get_method : table -> label -> meth
+val set_method : table -> label -> meth -> unit
+val set_methods : table -> label array -> unit
+val narrow : table -> string array -> string array -> string array -> unit
+val widen : table -> unit
+val add_initializer : table -> (obj -> unit) -> unit
+val dummy_table : table
+val create_table : string array -> table
+val init_class : table -> unit
+val inherits :
+ table -> string array -> string array -> string array ->
+ (t * (table -> obj -> Obj.t) * t * obj) -> bool -> Obj.t array
+val make_class :
+ string array -> (table -> Obj.t -> t) ->
+ (t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t)
+type init_table
+val make_class_store :
+ string array -> (table -> t) -> init_table -> unit
+val dummy_class :
+ string * int * int ->
+ (t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t)
+
+(** {6 Objects} *)
+
+val copy : (< .. > as 'a) -> 'a
+val create_object : table -> obj
+val create_object_opt : obj -> table -> obj
+val run_initializers : obj -> table -> unit
+val run_initializers_opt : obj -> obj -> table -> obj
+val create_object_and_run_initializers : obj -> table -> obj
+external send : obj -> tag -> t = "%send"
+external sendcache : obj -> tag -> t -> int -> t = "%sendcache"
+external sendself : obj -> label -> t = "%sendself"
+external get_public_method : obj -> tag -> closure
+ = "caml_get_public_method" "noalloc"
+
+(** {6 Table cache} *)
+
+type tables
+val lookup_tables : tables -> closure array -> tables
+
+(** {6 Builtins to reduce code size} *)
+
+(*
+val get_const : t -> closure
+val get_var : int -> closure
+val get_env : int -> int -> closure
+val get_meth : label -> closure
+val set_var : int -> closure
+val app_const : (t -> t) -> t -> closure
+val app_var : (t -> t) -> int -> closure
+val app_env : (t -> t) -> int -> int -> closure
+val app_meth : (t -> t) -> label -> closure
+val app_const_const : (t -> t -> t) -> t -> t -> closure
+val app_const_var : (t -> t -> t) -> t -> int -> closure
+val app_const_env : (t -> t -> t) -> t -> int -> int -> closure
+val app_const_meth : (t -> t -> t) -> t -> label -> closure
+val app_var_const : (t -> t -> t) -> int -> t -> closure
+val app_env_const : (t -> t -> t) -> int -> int -> t -> closure
+val app_meth_const : (t -> t -> t) -> label -> t -> closure
+val meth_app_const : label -> t -> closure
+val meth_app_var : label -> int -> closure
+val meth_app_env : label -> int -> int -> closure
+val meth_app_meth : label -> label -> closure
+val send_const : tag -> obj -> int -> closure
+val send_var : tag -> int -> int -> closure
+val send_env : tag -> int -> int -> int -> closure
+val send_meth : tag -> label -> int -> closure
+*)
+
+type impl =
+ GetConst
+ | GetVar
+ | GetEnv
+ | GetMeth
+ | SetVar
+ | AppConst
+ | AppVar
+ | AppEnv
+ | AppMeth
+ | AppConstConst
+ | AppConstVar
+ | AppConstEnv
+ | AppConstMeth
+ | AppVarConst
+ | AppEnvConst
+ | AppMethConst
+ | MethAppConst
+ | MethAppVar
+ | MethAppEnv
+ | MethAppMeth
+ | SendConst
+ | SendVar
+ | SendEnv
+ | SendMeth
+ | Closure of closure
+
+(** {6 Parameters} *)
+
+(* currently disabled *)
+type params =
+ { mutable compact_table : bool;
+ mutable copy_parent : bool;
+ mutable clean_when_copying : bool;
+ mutable retry_count : int;
+ mutable bucket_small_size : int }
+
+val params : params
+
+(** {6 Statistics} *)
+
+type stats =
+ { classes : int;
+ methods : int;
+ inst_vars : int }
+val stats : unit -> stats
diff --git a/stdlib/char.ml b/stdlib/char.ml
new file mode 100644
index 0000000000..58afbc7585
--- /dev/null
+++ b/stdlib/char.ml
@@ -0,0 +1,74 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Character operations *)
+
+external code: char -> int = "%identity"
+external unsafe_chr: int -> char = "%identity"
+
+let chr n =
+ if n < 0 || n > 255 then invalid_arg "Char.chr" else unsafe_chr n
+
+external string_create: int -> string = "caml_create_string"
+external string_unsafe_get : string -> int -> char = "%string_unsafe_get"
+external string_unsafe_set : string -> int -> char -> unit
+ = "%string_unsafe_set"
+
+let escaped = function
+ | '\'' -> "\\'"
+ | '\\' -> "\\\\"
+ | '\n' -> "\\n"
+ | '\t' -> "\\t"
+ | '\r' -> "\\r"
+ | '\b' -> "\\b"
+ | ' ' .. '~' as c ->
+ let s = string_create 1 in
+ string_unsafe_set s 0 c;
+ s
+ | c ->
+ let n = code c in
+ let s = string_create 4 in
+ string_unsafe_set s 0 '\\';
+ string_unsafe_set s 1 (unsafe_chr (48 + n / 100));
+ string_unsafe_set s 2 (unsafe_chr (48 + (n / 10) mod 10));
+ string_unsafe_set s 3 (unsafe_chr (48 + n mod 10));
+ s
+
+let lowercase c =
+ if (c >= 'A' && c <= 'Z')
+ || (c >= '\192' && c <= '\214')
+ || (c >= '\216' && c <= '\222')
+ then unsafe_chr(code c + 32)
+ else c
+
+let uppercase c =
+ if (c >= 'a' && c <= 'z')
+ || (c >= '\224' && c <= '\246')
+ || (c >= '\248' && c <= '\254')
+ then unsafe_chr(code c - 32)
+ else c
+
+let lowercase_ascii c =
+ if (c >= 'A' && c <= 'Z')
+ then unsafe_chr(code c + 32)
+ else c
+
+let uppercase_ascii c =
+ if (c >= 'a' && c <= 'z')
+ then unsafe_chr(code c - 32)
+ else c
+
+type t = char
+
+let compare c1 c2 = code c1 - code c2
+let equal (c1: t) (c2: t) = compare c1 c2 = 0
diff --git a/stdlib/char.mli b/stdlib/char.mli
new file mode 100644
index 0000000000..a5ad202114
--- /dev/null
+++ b/stdlib/char.mli
@@ -0,0 +1,70 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Character operations. *)
+
+external code : char -> int = "%identity"
+(** Return the ASCII code of the argument. *)
+
+val chr : int -> char
+(** Return the character with the given ASCII code.
+ Raise [Invalid_argument "Char.chr"] if the argument is
+ outside the range 0--255. *)
+
+val escaped : char -> string
+(** Return a string representing the given character,
+ with special characters escaped following the lexical conventions
+ of OCaml.
+ All characters outside the ASCII printable range (32..126) are
+ escaped, as well as backslash, double-quote, and single-quote. *)
+
+val lowercase : char -> char
+ [@@ocaml.deprecated "Use Char.lowercase_ascii instead."]
+(** Convert the given character to its equivalent lowercase character,
+ using the ISO Latin-1 (8859-1) character set.
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val uppercase : char -> char
+ [@@ocaml.deprecated "Use Char.uppercase_ascii instead."]
+(** Convert the given character to its equivalent uppercase character,
+ using the ISO Latin-1 (8859-1) character set.
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val lowercase_ascii : char -> char
+(** Convert the given character to its equivalent lowercase character,
+ using the US-ASCII character set.
+ @since 4.03.0 *)
+
+val uppercase_ascii : char -> char
+(** Convert the given character to its equivalent uppercase character,
+ using the US-ASCII character set.
+ @since 4.03.0 *)
+
+type t = char
+(** An alias for the type of characters. *)
+
+val compare: t -> t -> int
+(** The comparison function for characters, with the same specification as
+ {!Pervasives.compare}. Along with the type [t], this function [compare]
+ allows the module [Char] to be passed as argument to the functors
+ {!Set.Make} and {!Map.Make}. *)
+
+val equal: t -> t -> bool
+(** The equal function for chars.
+ @since 4.03.0 *)
+
+(**/**)
+
+(* The following is for system use only. Do not call directly. *)
+
+external unsafe_chr : int -> char = "%identity"
diff --git a/stdlib/complex.ml b/stdlib/complex.ml
new file mode 100644
index 0000000000..6d71d46af3
--- /dev/null
+++ b/stdlib/complex.ml
@@ -0,0 +1,85 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Complex numbers *)
+
+type t = { re: float; im: float }
+
+let zero = { re = 0.0; im = 0.0 }
+let one = { re = 1.0; im = 0.0 }
+let i = { re = 0.0; im = 1.0 }
+
+let add x y = { re = x.re +. y.re; im = x.im +. y.im }
+
+let sub x y = { re = x.re -. y.re; im = x.im -. y.im }
+
+let neg x = { re = -. x.re; im = -. x.im }
+
+let conj x = { re = x.re; im = -. x.im }
+
+let mul x y = { re = x.re *. y.re -. x.im *. y.im;
+ im = x.re *. y.im +. x.im *. y.re }
+
+let div x y =
+ if abs_float y.re >= abs_float y.im then
+ let r = y.im /. y.re in
+ let d = y.re +. r *. y.im in
+ { re = (x.re +. r *. x.im) /. d;
+ im = (x.im -. r *. x.re) /. d }
+ else
+ let r = y.re /. y.im in
+ let d = y.im +. r *. y.re in
+ { re = (r *. x.re +. x.im) /. d;
+ im = (r *. x.im -. x.re) /. d }
+
+let inv x = div one x
+
+let norm2 x = x.re *. x.re +. x.im *. x.im
+
+let norm x =
+ (* Watch out for overflow in computing re^2 + im^2 *)
+ let r = abs_float x.re and i = abs_float x.im in
+ if r = 0.0 then i
+ else if i = 0.0 then r
+ else if r >= i then
+ let q = i /. r in r *. sqrt(1.0 +. q *. q)
+ else
+ let q = r /. i in i *. sqrt(1.0 +. q *. q)
+
+let arg x = atan2 x.im x.re
+
+let polar n a = { re = cos a *. n; im = sin a *. n }
+
+let sqrt x =
+ if x.re = 0.0 && x.im = 0.0 then { re = 0.0; im = 0.0 }
+ else begin
+ let r = abs_float x.re and i = abs_float x.im in
+ let w =
+ if r >= i then begin
+ let q = i /. r in
+ sqrt(r) *. sqrt(0.5 *. (1.0 +. sqrt(1.0 +. q *. q)))
+ end else begin
+ let q = r /. i in
+ sqrt(i) *. sqrt(0.5 *. (q +. sqrt(1.0 +. q *. q)))
+ end in
+ if x.re >= 0.0
+ then { re = w; im = 0.5 *. x.im /. w }
+ else { re = 0.5 *. i /. w; im = if x.im >= 0.0 then w else -. w }
+ end
+
+let exp x =
+ let e = exp x.re in { re = e *. cos x.im; im = e *. sin x.im }
+
+let log x = { re = log (norm x); im = atan2 x.im x.re }
+
+let pow x y = exp (mul y (log x))
diff --git a/stdlib/complex.mli b/stdlib/complex.mli
new file mode 100644
index 0000000000..645aa93143
--- /dev/null
+++ b/stdlib/complex.mli
@@ -0,0 +1,84 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Complex numbers.
+
+ This module provides arithmetic operations on complex numbers.
+ Complex numbers are represented by their real and imaginary parts
+ (cartesian representation). Each part is represented by a
+ double-precision floating-point number (type [float]). *)
+
+type t = { re: float; im: float }
+(** The type of complex numbers. [re] is the real part and [im] the
+ imaginary part. *)
+
+val zero: t
+(** The complex number [0]. *)
+
+val one: t
+(** The complex number [1]. *)
+
+val i: t
+(** The complex number [i]. *)
+
+val neg: t -> t
+(** Unary negation. *)
+
+val conj: t -> t
+(** Conjugate: given the complex [x + i.y], returns [x - i.y]. *)
+
+val add: t -> t -> t
+(** Addition *)
+
+val sub: t -> t -> t
+(** Subtraction *)
+
+val mul: t -> t -> t
+(** Multiplication *)
+
+val inv: t -> t
+(** Multiplicative inverse ([1/z]). *)
+
+val div: t -> t -> t
+(** Division *)
+
+val sqrt: t -> t
+(** Square root. The result [x + i.y] is such that [x > 0] or
+ [x = 0] and [y >= 0].
+ This function has a discontinuity along the negative real axis. *)
+
+val norm2: t -> float
+(** Norm squared: given [x + i.y], returns [x^2 + y^2]. *)
+
+val norm: t -> float
+(** Norm: given [x + i.y], returns [sqrt(x^2 + y^2)]. *)
+
+val arg: t -> float
+(** Argument. The argument of a complex number is the angle
+ in the complex plane between the positive real axis and a line
+ passing through zero and the number. This angle ranges from
+ [-pi] to [pi]. This function has a discontinuity along the
+ negative real axis. *)
+
+val polar: float -> float -> t
+(** [polar norm arg] returns the complex having norm [norm]
+ and argument [arg]. *)
+
+val exp: t -> t
+(** Exponentiation. [exp z] returns [e] to the [z] power. *)
+
+val log: t -> t
+(** Natural logarithm (in base [e]). *)
+
+val pow: t -> t -> t
+(** Power function. [pow z1 z2] returns [z1] to the [z2] power. *)
diff --git a/stdlib/digest.ml b/stdlib/digest.ml
new file mode 100644
index 0000000000..aa3dc9eb35
--- /dev/null
+++ b/stdlib/digest.ml
@@ -0,0 +1,73 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Message digest (MD5) *)
+
+type t = string
+
+let compare = String.compare
+let equal = String.equal
+
+external unsafe_string: string -> int -> int -> t = "caml_md5_string"
+external channel: in_channel -> int -> t = "caml_md5_chan"
+
+let string str =
+ unsafe_string str 0 (String.length str)
+
+let bytes b = string (Bytes.unsafe_to_string b)
+
+let substring str ofs len =
+ if ofs < 0 || len < 0 || ofs > String.length str - len
+ then invalid_arg "Digest.substring"
+ else unsafe_string str ofs len
+
+let subbytes b ofs len = substring (Bytes.unsafe_to_string b) ofs len
+
+let file filename =
+ let ic = open_in_bin filename in
+ match channel ic (-1) with
+ | d -> close_in ic; d
+ | exception e -> close_in ic; raise e
+
+let output chan digest =
+ output_string chan digest
+
+let input chan = really_input_string chan 16
+
+let char_hex n =
+ Char.unsafe_chr (n + if n < 10 then Char.code '0' else (Char.code 'a' - 10))
+
+let to_hex d =
+ let result = Bytes.create 32 in
+ for i = 0 to 15 do
+ let x = Char.code d.[i] in
+ Bytes.unsafe_set result (i*2) (char_hex (x lsr 4));
+ Bytes.unsafe_set result (i*2+1) (char_hex (x land 0x0f));
+ done;
+ Bytes.unsafe_to_string result
+
+let from_hex s =
+ if String.length s <> 32 then raise (Invalid_argument "Digest.from_hex");
+ let digit c =
+ match c with
+ | '0'..'9' -> Char.code c - Char.code '0'
+ | 'A'..'F' -> Char.code c - Char.code 'A' + 10
+ | 'a'..'f' -> Char.code c - Char.code 'a' + 10
+ | _ -> raise (Invalid_argument "Digest.from_hex")
+ in
+ let byte i = digit s.[i] lsl 4 + digit s.[i+1] in
+ let result = Bytes.create 16 in
+ for i = 0 to 15 do
+ Bytes.set result i (Char.chr (byte (2 * i)));
+ done;
+ Bytes.unsafe_to_string result
diff --git a/stdlib/digest.mli b/stdlib/digest.mli
new file mode 100644
index 0000000000..29e5b3973e
--- /dev/null
+++ b/stdlib/digest.mli
@@ -0,0 +1,80 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** MD5 message digest.
+
+ This module provides functions to compute 128-bit 'digests' of
+ arbitrary-length strings or files. The digests are of cryptographic
+ quality: it is very hard, given a digest, to forge a string having
+ that digest. The algorithm used is MD5. This module should not be
+ used for secure and sensitive cryptographic applications. For these
+ kind of applications more recent and stronger cryptographic
+ primitives should be used instead.
+*)
+
+type t = string
+(** The type of digests: 16-character strings. *)
+
+val compare : t -> t -> int
+(** The comparison function for 16-character digest, with the same
+ specification as {!Pervasives.compare} and the implementation
+ shared with {!String.compare}. Along with the type [t], this
+ function [compare] allows the module [Digest] to be passed as
+ argument to the functors {!Set.Make} and {!Map.Make}.
+ @since 4.00.0 *)
+
+val equal : t -> t -> bool
+(** The equal function for 16-character digest.
+ @since 4.03.0 *)
+
+val string : string -> t
+(** Return the digest of the given string. *)
+
+val bytes : bytes -> t
+(** Return the digest of the given byte sequence.
+ @since 4.02.0 *)
+
+val substring : string -> int -> int -> t
+(** [Digest.substring s ofs len] returns the digest of the substring
+ of [s] starting at index [ofs] and containing [len] characters. *)
+
+val subbytes : bytes -> int -> int -> t
+(** [Digest.subbytes s ofs len] returns the digest of the subsequence
+ of [s] starting at index [ofs] and containing [len] bytes.
+ @since 4.02.0 *)
+
+external channel : in_channel -> int -> t = "caml_md5_chan"
+(** If [len] is nonnegative, [Digest.channel ic len] reads [len]
+ characters from channel [ic] and returns their digest, or raises
+ [End_of_file] if end-of-file is reached before [len] characters
+ are read. If [len] is negative, [Digest.channel ic len] reads
+ all characters from [ic] until end-of-file is reached and return
+ their digest. *)
+
+val file : string -> t
+(** Return the digest of the file whose name is given. *)
+
+val output : out_channel -> t -> unit
+(** Write a digest on the given output channel. *)
+
+val input : in_channel -> t
+(** Read a digest from the given input channel. *)
+
+val to_hex : t -> string
+(** Return the printable hexadecimal representation of the given digest. *)
+
+val from_hex : string -> t
+(** Convert a hexadecimal representation back into the corresponding digest.
+ Raise [Invalid_argument] if the argument is not exactly 32 hexadecimal
+ characters.
+ @since 4.00.0 *)
diff --git a/stdlib/filename.ml b/stdlib/filename.ml
new file mode 100644
index 0000000000..526b763a3e
--- /dev/null
+++ b/stdlib/filename.ml
@@ -0,0 +1,242 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let generic_quote quotequote s =
+ let l = String.length s in
+ let b = Buffer.create (l + 20) in
+ Buffer.add_char b '\'';
+ for i = 0 to l - 1 do
+ if s.[i] = '\''
+ then Buffer.add_string b quotequote
+ else Buffer.add_char b s.[i]
+ done;
+ Buffer.add_char b '\'';
+ Buffer.contents b
+
+(* This function implements the Open Group specification found here:
+ [[1]] http://pubs.opengroup.org/onlinepubs/9699919799/utilities/basename.html
+ In step 1 of [[1]], we choose to return "." for empty input.
+ (for compatibility with previous versions of OCaml)
+ In step 2, we choose to process "//" normally.
+ Step 6 is not implemented: we consider that the [suffix] operand is
+ always absent. Suffixes are handled by [chop_suffix] and [chop_extension].
+*)
+let generic_basename is_dir_sep current_dir_name name =
+ let rec find_end n =
+ if n < 0 then String.sub name 0 1
+ else if is_dir_sep name n then find_end (n - 1)
+ else find_beg n (n + 1)
+ and find_beg n p =
+ if n < 0 then String.sub name 0 p
+ else if is_dir_sep name n then String.sub name (n + 1) (p - n - 1)
+ else find_beg (n - 1) p
+ in
+ if name = ""
+ then current_dir_name
+ else find_end (String.length name - 1)
+
+(* This function implements the Open Group specification found here:
+ [[2]] http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html
+ In step 6 of [[2]], we choose to process "//" normally.
+*)
+let generic_dirname is_dir_sep current_dir_name name =
+ let rec trailing_sep n =
+ if n < 0 then String.sub name 0 1
+ else if is_dir_sep name n then trailing_sep (n - 1)
+ else base n
+ and base n =
+ if n < 0 then current_dir_name
+ else if is_dir_sep name n then intermediate_sep n
+ else base (n - 1)
+ and intermediate_sep n =
+ if n < 0 then String.sub name 0 1
+ else if is_dir_sep name n then intermediate_sep (n - 1)
+ else String.sub name 0 (n + 1)
+ in
+ if name = ""
+ then current_dir_name
+ else trailing_sep (String.length name - 1)
+
+module Unix = struct
+ let current_dir_name = "."
+ let parent_dir_name = ".."
+ let dir_sep = "/"
+ let is_dir_sep s i = s.[i] = '/'
+ let is_relative n = String.length n < 1 || n.[0] <> '/';;
+ let is_implicit n =
+ is_relative n
+ && (String.length n < 2 || String.sub n 0 2 <> "./")
+ && (String.length n < 3 || String.sub n 0 3 <> "../")
+ let check_suffix name suff =
+ String.length name >= String.length suff &&
+ String.sub name (String.length name - String.length suff)
+ (String.length suff) = suff
+ let temp_dir_name =
+ try Sys.getenv "TMPDIR" with Not_found -> "/tmp"
+ let quote = generic_quote "'\\''"
+ let basename = generic_basename is_dir_sep current_dir_name
+ let dirname = generic_dirname is_dir_sep current_dir_name
+end
+
+module Win32 = struct
+ let current_dir_name = "."
+ let parent_dir_name = ".."
+ let dir_sep = "\\"
+ let is_dir_sep s i = let c = s.[i] in c = '/' || c = '\\' || c = ':'
+ let is_relative n =
+ (String.length n < 1 || n.[0] <> '/')
+ && (String.length n < 1 || n.[0] <> '\\')
+ && (String.length n < 2 || n.[1] <> ':')
+ let is_implicit n =
+ is_relative n
+ && (String.length n < 2 || String.sub n 0 2 <> "./")
+ && (String.length n < 2 || String.sub n 0 2 <> ".\\")
+ && (String.length n < 3 || String.sub n 0 3 <> "../")
+ && (String.length n < 3 || String.sub n 0 3 <> "..\\")
+ let check_suffix name suff =
+ String.length name >= String.length suff &&
+ (let s = String.sub name (String.length name - String.length suff)
+ (String.length suff) in
+ String.lowercase_ascii s = String.lowercase_ascii suff)
+ let temp_dir_name =
+ try Sys.getenv "TEMP" with Not_found -> "."
+ let quote s =
+ let l = String.length s in
+ let b = Buffer.create (l + 20) in
+ Buffer.add_char b '\"';
+ let rec loop i =
+ if i = l then Buffer.add_char b '\"' else
+ match s.[i] with
+ | '\"' -> loop_bs 0 i;
+ | '\\' -> loop_bs 0 i;
+ | c -> Buffer.add_char b c; loop (i+1);
+ and loop_bs n i =
+ if i = l then begin
+ Buffer.add_char b '\"';
+ add_bs n;
+ end else begin
+ match s.[i] with
+ | '\"' -> add_bs (2*n+1); Buffer.add_char b '\"'; loop (i+1);
+ | '\\' -> loop_bs (n+1) (i+1);
+ | c -> add_bs n; loop i
+ end
+ and add_bs n = for _j = 1 to n do Buffer.add_char b '\\'; done
+ in
+ loop 0;
+ Buffer.contents b
+ let has_drive s =
+ let is_letter = function
+ | 'A' .. 'Z' | 'a' .. 'z' -> true
+ | _ -> false
+ in
+ String.length s >= 2 && is_letter s.[0] && s.[1] = ':'
+ let drive_and_path s =
+ if has_drive s
+ then (String.sub s 0 2, String.sub s 2 (String.length s - 2))
+ else ("", s)
+ let dirname s =
+ let (drive, path) = drive_and_path s in
+ let dir = generic_dirname is_dir_sep current_dir_name path in
+ drive ^ dir
+ let basename s =
+ let (drive, path) = drive_and_path s in
+ generic_basename is_dir_sep current_dir_name path
+end
+
+module Cygwin = struct
+ let current_dir_name = "."
+ let parent_dir_name = ".."
+ let dir_sep = "/"
+ let is_dir_sep = Win32.is_dir_sep
+ let is_relative = Win32.is_relative
+ let is_implicit = Win32.is_implicit
+ let check_suffix = Win32.check_suffix
+ let temp_dir_name = Unix.temp_dir_name
+ let quote = Unix.quote
+ let basename = generic_basename is_dir_sep current_dir_name
+ let dirname = generic_dirname is_dir_sep current_dir_name
+end
+
+let (current_dir_name, parent_dir_name, dir_sep, is_dir_sep,
+ is_relative, is_implicit, check_suffix, temp_dir_name, quote, basename,
+ dirname) =
+ match Sys.os_type with
+ "Unix" ->
+ (Unix.current_dir_name, Unix.parent_dir_name, Unix.dir_sep,
+ Unix.is_dir_sep,
+ Unix.is_relative, Unix.is_implicit, Unix.check_suffix,
+ Unix.temp_dir_name, Unix.quote, Unix.basename, Unix.dirname)
+ | "Win32" ->
+ (Win32.current_dir_name, Win32.parent_dir_name, Win32.dir_sep,
+ Win32.is_dir_sep,
+ Win32.is_relative, Win32.is_implicit, Win32.check_suffix,
+ Win32.temp_dir_name, Win32.quote, Win32.basename, Win32.dirname)
+ | "Cygwin" ->
+ (Cygwin.current_dir_name, Cygwin.parent_dir_name, Cygwin.dir_sep,
+ Cygwin.is_dir_sep,
+ Cygwin.is_relative, Cygwin.is_implicit, Cygwin.check_suffix,
+ Cygwin.temp_dir_name, Cygwin.quote, Cygwin.basename, Cygwin.dirname)
+ | _ -> assert false
+
+let concat dirname filename =
+ let l = String.length dirname in
+ if l = 0 || is_dir_sep dirname (l-1)
+ then dirname ^ filename
+ else dirname ^ dir_sep ^ filename
+
+let chop_suffix name suff =
+ let n = String.length name - String.length suff in
+ if n < 0 then invalid_arg "Filename.chop_suffix" else String.sub name 0 n
+
+let chop_extension name =
+ let rec search_dot i =
+ if i < 0 || is_dir_sep name i then invalid_arg "Filename.chop_extension"
+ else if name.[i] = '.' then String.sub name 0 i
+ else search_dot (i - 1) in
+ search_dot (String.length name - 1)
+
+external open_desc: string -> open_flag list -> int -> int = "caml_sys_open"
+external close_desc: int -> unit = "caml_sys_close"
+
+let prng = lazy(Random.State.make_self_init ());;
+
+let temp_file_name temp_dir prefix suffix =
+ let rnd = (Random.State.bits (Lazy.force prng)) land 0xFFFFFF in
+ concat temp_dir (Printf.sprintf "%s%06x%s" prefix rnd suffix)
+;;
+
+let current_temp_dir_name = ref temp_dir_name
+
+let set_temp_dir_name s = current_temp_dir_name := s
+let get_temp_dir_name () = !current_temp_dir_name
+
+let temp_file ?(temp_dir = !current_temp_dir_name) prefix suffix =
+ let rec try_name counter =
+ let name = temp_file_name temp_dir prefix suffix in
+ try
+ close_desc(open_desc name [Open_wronly; Open_creat; Open_excl] 0o600);
+ name
+ with Sys_error _ as e ->
+ if counter >= 1000 then raise e else try_name (counter + 1)
+ in try_name 0
+
+let open_temp_file ?(mode = [Open_text]) ?(perms = 0o600)
+ ?(temp_dir = !current_temp_dir_name) prefix suffix =
+ let rec try_name counter =
+ let name = temp_file_name temp_dir prefix suffix in
+ try
+ (name,
+ open_out_gen (Open_wronly::Open_creat::Open_excl::mode) perms name)
+ with Sys_error _ as e ->
+ if counter >= 1000 then raise e else try_name (counter + 1)
+ in try_name 0
diff --git a/stdlib/filename.mli b/stdlib/filename.mli
new file mode 100644
index 0000000000..dbdeb50236
--- /dev/null
+++ b/stdlib/filename.mli
@@ -0,0 +1,141 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Operations on file names. *)
+
+val current_dir_name : string
+(** The conventional name for the current directory (e.g. [.] in Unix). *)
+
+val parent_dir_name : string
+(** The conventional name for the parent of the current directory
+ (e.g. [..] in Unix). *)
+
+val dir_sep : string
+(** The directory separator (e.g. [/] in Unix). @since 3.11.2 *)
+
+val concat : string -> string -> string
+(** [concat dir file] returns a file name that designates file
+ [file] in directory [dir]. *)
+
+val is_relative : string -> bool
+(** Return [true] if the file name is relative to the current
+ directory, [false] if it is absolute (i.e. in Unix, starts
+ with [/]). *)
+
+val is_implicit : string -> bool
+(** Return [true] if the file name is relative and does not start
+ with an explicit reference to the current directory ([./] or
+ [../] in Unix), [false] if it starts with an explicit reference
+ to the root directory or the current directory. *)
+
+val check_suffix : string -> string -> bool
+(** [check_suffix name suff] returns [true] if the filename [name]
+ ends with the suffix [suff]. *)
+
+val chop_suffix : string -> string -> string
+(** [chop_suffix name suff] removes the suffix [suff] from
+ the filename [name]. The behavior is undefined if [name] does not
+ end with the suffix [suff]. *)
+
+val chop_extension : string -> string
+(** Return the given file name without its extension. The extension
+ is the shortest suffix starting with a period and not including
+ a directory separator, [.xyz] for instance.
+
+ Raise [Invalid_argument] if the given name does not contain
+ an extension. *)
+
+val basename : string -> string
+(** Split a file name into directory name / base file name.
+ If [name] is a valid file name, then [concat (dirname name) (basename name)]
+ returns a file name which is equivalent to [name]. Moreover,
+ after setting the current directory to [dirname name] (with {!Sys.chdir}),
+ references to [basename name] (which is a relative file name)
+ designate the same file as [name] before the call to {!Sys.chdir}.
+
+ This function conforms to the specification of POSIX.1-2008 for the
+ [basename] utility. *)
+
+val dirname : string -> string
+(** See {!Filename.basename}.
+ This function conforms to the specification of POSIX.1-2008 for the
+ [dirname] utility. *)
+
+val temp_file : ?temp_dir: string -> string -> string -> string
+(** [temp_file prefix suffix] returns the name of a
+ fresh temporary file in the temporary directory.
+ The base name of the temporary file is formed by concatenating
+ [prefix], then a suitably chosen integer number, then [suffix].
+ The optional argument [temp_dir] indicates the temporary directory
+ to use, defaulting to the current result of {!Filename.get_temp_dir_name}.
+ The temporary file is created empty, with permissions [0o600]
+ (readable and writable only by the file owner). The file is
+ guaranteed to be different from any other file that existed when
+ [temp_file] was called.
+ Raise [Sys_error] if the file could not be created.
+ @before 3.11.2 no ?temp_dir optional argument
+*)
+
+val open_temp_file :
+ ?mode: open_flag list -> ?perms: int -> ?temp_dir: string -> string ->
+ string -> string * out_channel
+(** Same as {!Filename.temp_file}, but returns both the name of a fresh
+ temporary file, and an output channel opened (atomically) on
+ this file. This function is more secure than [temp_file]: there
+ is no risk that the temporary file will be modified (e.g. replaced
+ by a symbolic link) before the program opens it. The optional argument
+ [mode] is a list of additional flags to control the opening of the file.
+ It can contain one or several of [Open_append], [Open_binary],
+ and [Open_text]. The default is [[Open_text]] (open in text mode). The
+ file is created with permissions [perms] (defaults to readable and
+ writable only by the file owner, [0o600]).
+
+ @raise Sys_error if the file could not be opened.
+ @before 4.03.0 no ?perms optional argument
+ @before 3.11.2 no ?temp_dir optional argument
+*)
+
+val get_temp_dir_name : unit -> string
+(** The name of the temporary directory:
+ Under Unix, the value of the [TMPDIR] environment variable, or "/tmp"
+ if the variable is not set.
+ Under Windows, the value of the [TEMP] environment variable, or "."
+ if the variable is not set.
+ The temporary directory can be changed with {!Filename.set_temp_dir_name}.
+ @since 4.00.0
+*)
+
+val set_temp_dir_name : string -> unit
+(** Change the temporary directory returned by {!Filename.get_temp_dir_name}
+ and used by {!Filename.temp_file} and {!Filename.open_temp_file}.
+ @since 4.00.0
+*)
+
+val temp_dir_name : string
+ [@@ocaml.deprecated "Use Filename.get_temp_dir_name instead"]
+(** The name of the initial temporary directory:
+ Under Unix, the value of the [TMPDIR] environment variable, or "/tmp"
+ if the variable is not set.
+ Under Windows, the value of the [TEMP] environment variable, or "."
+ if the variable is not set.
+ @deprecated You should use {!Filename.get_temp_dir_name} instead.
+ @since 3.09.1
+*)
+
+val quote : string -> string
+(** Return a quoted version of a file name, suitable for use as
+ one argument in a command line, escaping all meta-characters.
+ Warning: under Windows, the output is only suitable for use
+ with programs that follow the standard Windows quoting
+ conventions.
+ *)
diff --git a/stdlib/format.ml b/stdlib/format.ml
new file mode 100644
index 0000000000..2b77c77678
--- /dev/null
+++ b/stdlib/format.ml
@@ -0,0 +1,1231 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* A pretty-printing facility and definition of formatters for 'parallel'
+ (i.e. unrelated or independent) pretty-printing on multiple out channels. *)
+
+(**************************************************************
+
+ Data structures definitions.
+
+ **************************************************************)
+
+type size;;
+
+external size_of_int : int -> size = "%identity"
+;;
+external int_of_size : size -> int = "%identity"
+;;
+
+(* Tokens are one of the following : *)
+
+type block_type
+ = CamlinternalFormatBasics.block_type
+ = Pp_hbox | Pp_vbox | Pp_hvbox | Pp_hovbox | Pp_box | Pp_fits
+
+type pp_token =
+| Pp_text of string (* normal text *)
+| Pp_break of int * int (* complete break *)
+| Pp_tbreak of int * int (* go to next tabulation *)
+| Pp_stab (* set a tabulation *)
+| Pp_begin of int * block_type (* beginning of a block *)
+| Pp_end (* end of a block *)
+| Pp_tbegin of tblock (* beginning of a tabulation block *)
+| Pp_tend (* end of a tabulation block *)
+| Pp_newline (* to force a newline inside a block *)
+| Pp_if_newline (* to do something only if this very
+ line has been broken *)
+| Pp_open_tag of tag (* opening a tag name *)
+| Pp_close_tag (* closing the most recently opened tag *)
+
+and tag = string
+
+and tblock = Pp_tbox of int list ref (* Tabulation box *)
+
+(* The Queue:
+ contains all formatting elements.
+ elements are tuples (size, token, length), where
+ size is set when the size of the block is known
+ len is the declared length of the token. *)
+type pp_queue_elem = {
+ mutable elem_size : size;
+ token : pp_token;
+ length : int;
+}
+;;
+
+(* Scan stack:
+ each element is (left_total, queue element) where left_total
+ is the value of pp_left_total when the element has been enqueued. *)
+type pp_scan_elem = Scan_elem of int * pp_queue_elem;;
+
+(* Formatting stack:
+ used to break the lines while printing tokens.
+ The formatting stack contains the description of
+ the currently active blocks. *)
+type pp_format_elem = Format_elem of block_type * int;;
+
+(* General purpose queues, used in the formatter. *)
+type 'a queue_elem =
+ | Nil
+ | Cons of 'a queue_cell
+
+and 'a queue_cell = {
+ mutable head : 'a;
+ mutable tail : 'a queue_elem;
+}
+;;
+
+type 'a queue = {
+ mutable insert : 'a queue_elem;
+ mutable body : 'a queue_elem;
+}
+;;
+
+(* The formatter specific tag handling functions. *)
+type formatter_tag_functions = {
+ mark_open_tag : tag -> string;
+ mark_close_tag : tag -> string;
+ print_open_tag : tag -> unit;
+ print_close_tag : tag -> unit;
+}
+;;
+
+(* A formatter with all its machinery. *)
+type formatter = {
+ mutable pp_scan_stack : pp_scan_elem list;
+ mutable pp_format_stack : pp_format_elem list;
+ mutable pp_tbox_stack : tblock list;
+ mutable pp_tag_stack : tag list;
+ mutable pp_mark_stack : tag list;
+ (* Global variables: default initialization is
+ set_margin 78
+ set_min_space_left 0. *)
+ (* Value of right margin. *)
+ mutable pp_margin : int;
+ (* Minimal space left before margin, when opening a block. *)
+ mutable pp_min_space_left : int;
+ (* Maximum value of indentation:
+ no blocks can be opened further. *)
+ mutable pp_max_indent : int;
+ (* Space remaining on the current line. *)
+ mutable pp_space_left : int;
+ (* Current value of indentation. *)
+ mutable pp_current_indent : int;
+ (* True when the line has been broken by the pretty-printer. *)
+ mutable pp_is_new_line : bool;
+ (* Total width of tokens already printed. *)
+ mutable pp_left_total : int;
+ (* Total width of tokens ever put in queue. *)
+ mutable pp_right_total : int;
+ (* Current number of opened blocks. *)
+ mutable pp_curr_depth : int;
+ (* Maximum number of blocks which can be simultaneously opened. *)
+ mutable pp_max_boxes : int;
+ (* Ellipsis string. *)
+ mutable pp_ellipsis : string;
+ (* Output function. *)
+ mutable pp_out_string : string -> int -> int -> unit;
+ (* Flushing function. *)
+ mutable pp_out_flush : unit -> unit;
+ (* Output of new lines. *)
+ mutable pp_out_newline : unit -> unit;
+ (* Output of indentation spaces. *)
+ mutable pp_out_spaces : int -> unit;
+ (* Are tags printed ? *)
+ mutable pp_print_tags : bool;
+ (* Are tags marked ? *)
+ mutable pp_mark_tags : bool;
+ (* Find opening and closing markers of tags. *)
+ mutable pp_mark_open_tag : tag -> string;
+ mutable pp_mark_close_tag : tag -> string;
+ mutable pp_print_open_tag : tag -> unit;
+ mutable pp_print_close_tag : tag -> unit;
+ (* The pretty-printer queue. *)
+ mutable pp_queue : pp_queue_elem queue;
+}
+;;
+
+(**************************************************************
+
+ Auxilliaries and basic functions.
+
+ **************************************************************)
+
+
+(* Queues auxilliaries. *)
+let make_queue () = { insert = Nil; body = Nil; };;
+
+let clear_queue q = q.insert <- Nil; q.body <- Nil;;
+
+let add_queue x q =
+ let c = Cons { head = x; tail = Nil; } in
+ match q with
+ | { insert = Cons cell; body = _; } ->
+ q.insert <- c; cell.tail <- c
+ (* Invariant: when insert is Nil body should be Nil. *)
+ | { insert = Nil; body = _; } ->
+ q.insert <- c; q.body <- c
+;;
+
+exception Empty_queue;;
+
+let peek_queue = function
+ | { body = Cons { head = x; tail = _; }; _ } -> x
+ | { body = Nil; insert = _; } -> raise Empty_queue
+;;
+
+let take_queue = function
+ | { body = Cons { head = x; tail = tl; }; _ } as q ->
+ q.body <- tl;
+ if tl = Nil then q.insert <- Nil; (* Maintain the invariant. *)
+ x
+ | { body = Nil; insert = _; } -> raise Empty_queue
+;;
+
+(* Enter a token in the pretty-printer queue. *)
+let pp_enqueue state ({ length = len; _} as token) =
+ state.pp_right_total <- state.pp_right_total + len;
+ add_queue token state.pp_queue
+;;
+
+let pp_clear_queue state =
+ state.pp_left_total <- 1; state.pp_right_total <- 1;
+ clear_queue state.pp_queue
+;;
+
+(* Pp_infinity: large value for default tokens size.
+
+ Pp_infinity is documented as being greater than 1e10; to avoid
+ confusion about the word 'greater', we choose pp_infinity greater
+ than 1e10 + 1; for correct handling of tests in the algorithm,
+ pp_infinity must be even one more than 1e10 + 1; let's stand on the
+ safe side by choosing 1.e10+10.
+
+ Pp_infinity could probably be 1073741823 that is 2^30 - 1, that is
+ the minimal upper bound for integers; now that max_int is defined,
+ this limit could also be defined as max_int - 1.
+
+ However, before setting pp_infinity to something around max_int, we
+ must carefully double-check all the integer arithmetic operations
+ that involve pp_infinity, since any overflow would wreck havoc the
+ pretty-printing algorithm's invariants. Given that this arithmetic
+ correctness check is difficult and error prone and given that 1e10
+ + 1 is in practice large enough, there is no need to attempt to set
+ pp_infinity to the theoretically maximum limit. It is not worth the
+ burden ! *)
+
+let pp_infinity = 1000000010;;
+
+(* Output functions for the formatter. *)
+let pp_output_string state s = state.pp_out_string s 0 (String.length s)
+and pp_output_newline state = state.pp_out_newline ()
+and pp_output_spaces state n = state.pp_out_spaces n
+
+(* To format a break, indenting a new line. *)
+let break_new_line state offset width =
+ pp_output_newline state;
+ state.pp_is_new_line <- true;
+ let indent = state.pp_margin - width + offset in
+ (* Don't indent more than pp_max_indent. *)
+ let real_indent = min state.pp_max_indent indent in
+ state.pp_current_indent <- real_indent;
+ state.pp_space_left <- state.pp_margin - state.pp_current_indent;
+ pp_output_spaces state state.pp_current_indent
+;;
+
+(* To force a line break inside a block: no offset is added. *)
+let break_line state width = break_new_line state 0 width;;
+
+(* To format a break that fits on the current line. *)
+let break_same_line state width =
+ state.pp_space_left <- state.pp_space_left - width;
+ pp_output_spaces state width
+;;
+
+(* To indent no more than pp_max_indent, if one tries to open a block
+ beyond pp_max_indent, then the block is rejected on the left
+ by simulating a break. *)
+let pp_force_break_line state =
+ match state.pp_format_stack with
+ | Format_elem (bl_ty, width) :: _ ->
+ if width > state.pp_space_left then
+ (match bl_ty with
+ | Pp_fits -> () | Pp_hbox -> ()
+ | Pp_vbox | Pp_hvbox | Pp_hovbox | Pp_box ->
+ break_line state width)
+ | [] -> pp_output_newline state
+;;
+
+(* To skip a token, if the previous line has been broken. *)
+let pp_skip_token state =
+ (* When calling pp_skip_token the queue cannot be empty. *)
+ match take_queue state.pp_queue with
+ | { elem_size = size; length = len; token = _; } ->
+ state.pp_left_total <- state.pp_left_total - len;
+ state.pp_space_left <- state.pp_space_left + int_of_size size
+;;
+
+(**************************************************************
+
+ The main pretty printing functions.
+
+ **************************************************************)
+
+(* To format a token. *)
+let format_pp_token state size = function
+
+ | Pp_text s ->
+ state.pp_space_left <- state.pp_space_left - size;
+ pp_output_string state s;
+ state.pp_is_new_line <- false
+
+ | Pp_begin (off, ty) ->
+ let insertion_point = state.pp_margin - state.pp_space_left in
+ if insertion_point > state.pp_max_indent then
+ (* can not open a block right there. *)
+ begin pp_force_break_line state end;
+ let offset = state.pp_space_left - off in
+ let bl_type =
+ begin match ty with
+ | Pp_vbox -> Pp_vbox
+ | Pp_hbox | Pp_hvbox | Pp_hovbox | Pp_box | Pp_fits ->
+ if size > state.pp_space_left then ty else Pp_fits
+ end in
+ state.pp_format_stack <-
+ Format_elem (bl_type, offset) :: state.pp_format_stack
+
+ | Pp_end ->
+ begin match state.pp_format_stack with
+ | _ :: ls -> state.pp_format_stack <- ls
+ | [] -> () (* No more block to close. *)
+ end
+
+ | Pp_tbegin (Pp_tbox _ as tbox) ->
+ state.pp_tbox_stack <- tbox :: state.pp_tbox_stack
+
+ | Pp_tend ->
+ begin match state.pp_tbox_stack with
+ | _ :: ls -> state.pp_tbox_stack <- ls
+ | [] -> () (* No more tabulation block to close. *)
+ end
+
+ | Pp_stab ->
+ begin match state.pp_tbox_stack with
+ | Pp_tbox tabs :: _ ->
+ let rec add_tab n = function
+ | [] -> [n]
+ | x :: l as ls -> if n < x then n :: ls else x :: add_tab n l in
+ tabs := add_tab (state.pp_margin - state.pp_space_left) !tabs
+ | [] -> () (* No opened tabulation block. *)
+ end
+
+ | Pp_tbreak (n, off) ->
+ let insertion_point = state.pp_margin - state.pp_space_left in
+ begin match state.pp_tbox_stack with
+ | Pp_tbox tabs :: _ ->
+ let rec find n = function
+ | x :: l -> if x >= n then x else find n l
+ | [] -> raise Not_found in
+ let tab =
+ match !tabs with
+ | x :: _ ->
+ begin
+ try find insertion_point !tabs with
+ | Not_found -> x
+ end
+ | _ -> insertion_point in
+ let offset = tab - insertion_point in
+ if offset >= 0
+ then break_same_line state (offset + n)
+ else break_new_line state (tab + off) state.pp_margin
+ | [] -> () (* No opened tabulation block. *)
+ end
+
+ | Pp_newline ->
+ begin match state.pp_format_stack with
+ | Format_elem (_, width) :: _ -> break_line state width
+ | [] -> pp_output_newline state (* No opened block. *)
+ end
+
+ | Pp_if_newline ->
+ if state.pp_current_indent != state.pp_margin - state.pp_space_left
+ then pp_skip_token state
+
+ | Pp_break (n, off) ->
+ begin match state.pp_format_stack with
+ | Format_elem (ty, width) :: _ ->
+ begin match ty with
+ | Pp_hovbox ->
+ if size > state.pp_space_left
+ then break_new_line state off width
+ else break_same_line state n
+ | Pp_box ->
+ (* Have the line just been broken here ? *)
+ if state.pp_is_new_line then break_same_line state n else
+ if size > state.pp_space_left
+ then break_new_line state off width else
+ (* break the line here leads to new indentation ? *)
+ if state.pp_current_indent > state.pp_margin - width + off
+ then break_new_line state off width
+ else break_same_line state n
+ | Pp_hvbox -> break_new_line state off width
+ | Pp_fits -> break_same_line state n
+ | Pp_vbox -> break_new_line state off width
+ | Pp_hbox -> break_same_line state n
+ end
+ | [] -> () (* No opened block. *)
+ end
+
+ | Pp_open_tag tag_name ->
+ let marker = state.pp_mark_open_tag tag_name in
+ pp_output_string state marker;
+ state.pp_mark_stack <- tag_name :: state.pp_mark_stack
+
+ | Pp_close_tag ->
+ begin match state.pp_mark_stack with
+ | tag_name :: tags ->
+ let marker = state.pp_mark_close_tag tag_name in
+ pp_output_string state marker;
+ state.pp_mark_stack <- tags
+ | [] -> () (* No more tag to close. *)
+ end
+;;
+
+(* Print if token size is known or printing is delayed.
+ Size is known when not negative.
+ Printing is delayed when the text waiting in the queue requires
+ more room to format than exists on the current line.
+
+ Note: [advance_loop] must be tail recursive to prevent stack overflows. *)
+let rec advance_loop state =
+ match peek_queue state.pp_queue with
+ | {elem_size = size; token = tok; length = len} ->
+ let size = int_of_size size in
+ if not
+ (size < 0 &&
+ (state.pp_right_total - state.pp_left_total < state.pp_space_left))
+ then begin
+ ignore (take_queue state.pp_queue);
+ format_pp_token state (if size < 0 then pp_infinity else size) tok;
+ state.pp_left_total <- len + state.pp_left_total;
+ advance_loop state
+ end
+;;
+
+let advance_left state =
+ try advance_loop state with
+ | Empty_queue -> ()
+;;
+
+let enqueue_advance state tok = pp_enqueue state tok; advance_left state;;
+
+(* To enqueue a string : try to advance. *)
+let make_queue_elem size tok len =
+ { elem_size = size; token = tok; length = len; }
+;;
+
+let enqueue_string_as state size s =
+ let len = int_of_size size in
+ enqueue_advance state (make_queue_elem size (Pp_text s) len)
+;;
+
+let enqueue_string state s =
+ let len = String.length s in
+ enqueue_string_as state (size_of_int len) s
+;;
+
+(* Routines for scan stack
+ determine sizes of blocks. *)
+
+(* The scan_stack is never empty. *)
+let scan_stack_bottom =
+ let q_elem = make_queue_elem (size_of_int (-1)) (Pp_text "") 0 in
+ [Scan_elem (-1, q_elem)]
+;;
+
+(* Set size of blocks on scan stack:
+ if ty = true then size of break is set else size of block is set;
+ in each case pp_scan_stack is popped. *)
+let clear_scan_stack state = state.pp_scan_stack <- scan_stack_bottom;;
+
+(* Pattern matching on scan stack is exhaustive,
+ since scan_stack is never empty.
+ Pattern matching on token in scan stack is also exhaustive,
+ since scan_push is used on breaks and opening of boxes. *)
+let set_size state ty =
+ match state.pp_scan_stack with
+ | Scan_elem
+ (left_tot,
+ ({ elem_size = size; token = tok; length = _; } as queue_elem)) :: t ->
+ let size = int_of_size size in
+ (* test if scan stack contains any data that is not obsolete. *)
+ if left_tot < state.pp_left_total then clear_scan_stack state else
+ begin match tok with
+ | Pp_break (_, _) | Pp_tbreak (_, _) ->
+ if ty then
+ begin
+ queue_elem.elem_size <- size_of_int (state.pp_right_total + size);
+ state.pp_scan_stack <- t
+ end
+ | Pp_begin (_, _) ->
+ if not ty then
+ begin
+ queue_elem.elem_size <- size_of_int (state.pp_right_total + size);
+ state.pp_scan_stack <- t
+ end
+ | Pp_text _ | Pp_stab | Pp_tbegin _ | Pp_tend | Pp_end
+ | Pp_newline | Pp_if_newline
+ | Pp_open_tag _ | Pp_close_tag ->
+ () (* scan_push is only used for breaks and boxes. *)
+ end
+ | [] -> () (* scan_stack is never empty. *)
+;;
+
+(* Push a token on scan stack. If b is true set_size is called. *)
+let scan_push state b tok =
+ pp_enqueue state tok;
+ if b then set_size state true;
+ state.pp_scan_stack <-
+ Scan_elem (state.pp_right_total, tok) :: state.pp_scan_stack
+;;
+
+(* To open a new block :
+ the user may set the depth bound pp_max_boxes
+ any text nested deeper is printed as the ellipsis string. *)
+let pp_open_box_gen state indent br_ty =
+ state.pp_curr_depth <- state.pp_curr_depth + 1;
+ if state.pp_curr_depth < state.pp_max_boxes then
+ let elem =
+ make_queue_elem
+ (size_of_int (- state.pp_right_total))
+ (Pp_begin (indent, br_ty))
+ 0 in
+ scan_push state false elem else
+ if state.pp_curr_depth = state.pp_max_boxes
+ then enqueue_string state state.pp_ellipsis
+;;
+
+(* The box which is always opened. *)
+let pp_open_sys_box state = pp_open_box_gen state 0 Pp_hovbox;;
+
+(* Close a block, setting sizes of its sub blocks. *)
+let pp_close_box state () =
+ if state.pp_curr_depth > 1 then
+ begin
+ if state.pp_curr_depth < state.pp_max_boxes then
+ begin
+ pp_enqueue state
+ { elem_size = size_of_int 0; token = Pp_end; length = 0; };
+ set_size state true; set_size state false
+ end;
+ state.pp_curr_depth <- state.pp_curr_depth - 1;
+ end
+;;
+
+(* Open a tag, pushing it on the tag stack. *)
+let pp_open_tag state tag_name =
+ if state.pp_print_tags then
+ begin
+ state.pp_tag_stack <- tag_name :: state.pp_tag_stack;
+ state.pp_print_open_tag tag_name
+ end;
+ if state.pp_mark_tags then
+ pp_enqueue state {
+ elem_size = size_of_int 0;
+ token = Pp_open_tag tag_name;
+ length = 0;
+ }
+;;
+
+(* Close a tag, popping it from the tag stack. *)
+let pp_close_tag state () =
+ if state.pp_mark_tags then
+ pp_enqueue state {
+ elem_size = size_of_int 0;
+ token = Pp_close_tag;
+ length = 0;
+ };
+ if state.pp_print_tags then
+ begin
+ match state.pp_tag_stack with
+ | tag_name :: tags ->
+ state.pp_print_close_tag tag_name;
+ state.pp_tag_stack <- tags
+ | _ -> () (* No more tag to close. *)
+ end
+;;
+
+let pp_set_print_tags state b = state.pp_print_tags <- b;;
+let pp_set_mark_tags state b = state.pp_mark_tags <- b;;
+let pp_get_print_tags state () = state.pp_print_tags;;
+let pp_get_mark_tags state () = state.pp_mark_tags;;
+let pp_set_tags state b =
+ pp_set_print_tags state b; pp_set_mark_tags state b
+;;
+
+let pp_get_formatter_tag_functions state () = {
+ mark_open_tag = state.pp_mark_open_tag;
+ mark_close_tag = state.pp_mark_close_tag;
+ print_open_tag = state.pp_print_open_tag;
+ print_close_tag = state.pp_print_close_tag;
+}
+;;
+
+let pp_set_formatter_tag_functions state {
+ mark_open_tag = mot;
+ mark_close_tag = mct;
+ print_open_tag = pot;
+ print_close_tag = pct;
+ } =
+ state.pp_mark_open_tag <- mot;
+ state.pp_mark_close_tag <- mct;
+ state.pp_print_open_tag <- pot;
+ state.pp_print_close_tag <- pct
+;;
+
+(* Initialize pretty-printer. *)
+let pp_rinit state =
+ pp_clear_queue state;
+ clear_scan_stack state;
+ state.pp_format_stack <- [];
+ state.pp_tbox_stack <- [];
+ state.pp_tag_stack <- [];
+ state.pp_mark_stack <- [];
+ state.pp_current_indent <- 0;
+ state.pp_curr_depth <- 0;
+ state.pp_space_left <- state.pp_margin;
+ pp_open_sys_box state
+;;
+
+(* Flushing pretty-printer queue. *)
+let pp_flush_queue state b =
+ while state.pp_curr_depth > 1 do
+ pp_close_box state ()
+ done;
+ state.pp_right_total <- pp_infinity;
+ advance_left state;
+ if b then pp_output_newline state;
+ pp_rinit state
+;;
+
+(**************************************************************
+
+ Procedures to format objects, and use boxes
+
+ **************************************************************)
+
+(* To format a string. *)
+let pp_print_as_size state size s =
+ if state.pp_curr_depth < state.pp_max_boxes
+ then enqueue_string_as state size s
+;;
+
+let pp_print_as state isize s =
+ pp_print_as_size state (size_of_int isize) s
+;;
+
+let pp_print_string state s =
+ pp_print_as state (String.length s) s
+;;
+
+(* To format an integer. *)
+let pp_print_int state i = pp_print_string state (string_of_int i);;
+
+(* To format a float. *)
+let pp_print_float state f = pp_print_string state (string_of_float f);;
+
+(* To format a boolean. *)
+let pp_print_bool state b = pp_print_string state (string_of_bool b);;
+
+(* To format a char. *)
+let pp_print_char state c =
+ pp_print_as state 1 (String.make 1 c)
+;;
+
+(* Opening boxes. *)
+let pp_open_hbox state () = pp_open_box_gen state 0 Pp_hbox
+and pp_open_vbox state indent = pp_open_box_gen state indent Pp_vbox
+
+and pp_open_hvbox state indent = pp_open_box_gen state indent Pp_hvbox
+and pp_open_hovbox state indent = pp_open_box_gen state indent Pp_hovbox
+and pp_open_box state indent = pp_open_box_gen state indent Pp_box
+;;
+
+(* Print a new line after printing all queued text
+ (same for print_flush but without a newline). *)
+let pp_print_newline state () =
+ pp_flush_queue state true; state.pp_out_flush ()
+and pp_print_flush state () =
+ pp_flush_queue state false; state.pp_out_flush ()
+;;
+
+(* To get a newline when one does not want to close the current block. *)
+let pp_force_newline state () =
+ if state.pp_curr_depth < state.pp_max_boxes then
+ enqueue_advance state (make_queue_elem (size_of_int 0) Pp_newline 0)
+;;
+
+(* To format something if the line has just been broken. *)
+let pp_print_if_newline state () =
+ if state.pp_curr_depth < state.pp_max_boxes then
+ enqueue_advance state (make_queue_elem (size_of_int 0) Pp_if_newline 0)
+;;
+
+(* Breaks: indicate where a block may be broken.
+ If line is broken then offset is added to the indentation of the current
+ block else (the value of) width blanks are printed.
+ To do (?) : add a maximum width and offset value. *)
+let pp_print_break state width offset =
+ if state.pp_curr_depth < state.pp_max_boxes then
+ let elem =
+ make_queue_elem
+ (size_of_int (- state.pp_right_total))
+ (Pp_break (width, offset))
+ width in
+ scan_push state true elem
+;;
+
+let pp_print_space state () = pp_print_break state 1 0
+and pp_print_cut state () = pp_print_break state 0 0
+;;
+
+(* Tabulation boxes. *)
+let pp_open_tbox state () =
+ state.pp_curr_depth <- state.pp_curr_depth + 1;
+ if state.pp_curr_depth < state.pp_max_boxes then
+ let elem =
+ make_queue_elem (size_of_int 0) (Pp_tbegin (Pp_tbox (ref []))) 0 in
+ enqueue_advance state elem
+;;
+
+(* Close a tabulation block. *)
+let pp_close_tbox state () =
+ if state.pp_curr_depth > 1 then
+ begin
+ if state.pp_curr_depth < state.pp_max_boxes then
+ let elem = make_queue_elem (size_of_int 0) Pp_tend 0 in
+ enqueue_advance state elem;
+ state.pp_curr_depth <- state.pp_curr_depth - 1
+ end
+;;
+
+(* Print a tabulation break. *)
+let pp_print_tbreak state width offset =
+ if state.pp_curr_depth < state.pp_max_boxes then
+ let elem =
+ make_queue_elem
+ (size_of_int (- state.pp_right_total))
+ (Pp_tbreak (width, offset))
+ width in
+ scan_push state true elem
+;;
+
+let pp_print_tab state () = pp_print_tbreak state 0 0;;
+
+let pp_set_tab state () =
+ if state.pp_curr_depth < state.pp_max_boxes then
+ let elem =
+ make_queue_elem (size_of_int 0) Pp_stab 0 in
+ enqueue_advance state elem
+;;
+
+
+(* Convenience functions *)
+
+(* To format a list *)
+let rec pp_print_list ?(pp_sep = pp_print_cut) pp_v ppf = function
+ | [] -> ()
+ | [v] -> pp_v ppf v
+ | v :: vs ->
+ pp_v ppf v;
+ pp_sep ppf ();
+ pp_print_list ~pp_sep pp_v ppf vs
+
+(* To format free-flowing text *)
+let pp_print_text ppf s =
+ let len = String.length s in
+ let left = ref 0 in
+ let right = ref 0 in
+ let flush () =
+ pp_print_string ppf (String.sub s !left (!right - !left));
+ incr right; left := !right;
+ in
+ while (!right <> len) do
+ match s.[!right] with
+ | '\n' ->
+ flush ();
+ pp_force_newline ppf ()
+ | ' ' ->
+ flush (); pp_print_space ppf ()
+ (* there is no specific support for '\t'
+ as it is unclear what a right semantics would be *)
+ | _ -> incr right
+ done;
+ if !left <> len then flush ()
+
+
+(**************************************************************
+
+ Procedures to control the pretty-printers
+
+ **************************************************************)
+
+(* Fit max_boxes. *)
+let pp_set_max_boxes state n = if n > 1 then state.pp_max_boxes <- n;;
+
+(* To know the current maximum number of boxes allowed. *)
+let pp_get_max_boxes state () = state.pp_max_boxes;;
+
+let pp_over_max_boxes state () = state.pp_curr_depth = state.pp_max_boxes;;
+
+(* Ellipsis. *)
+let pp_set_ellipsis_text state s = state.pp_ellipsis <- s
+and pp_get_ellipsis_text state () = state.pp_ellipsis
+;;
+
+(* To set the margin of pretty-printer. *)
+let pp_limit n =
+ if n < pp_infinity then n else pred pp_infinity
+;;
+
+let pp_set_min_space_left state n =
+ if n >= 1 then
+ let n = pp_limit n in
+ state.pp_min_space_left <- n;
+ state.pp_max_indent <- state.pp_margin - state.pp_min_space_left;
+ pp_rinit state
+;;
+
+(* Initially, we have :
+ pp_max_indent = pp_margin - pp_min_space_left, and
+ pp_space_left = pp_margin. *)
+let pp_set_max_indent state n =
+ pp_set_min_space_left state (state.pp_margin - n)
+;;
+
+let pp_get_max_indent state () = state.pp_max_indent;;
+
+let pp_set_margin state n =
+ if n >= 1 then
+ let n = pp_limit n in
+ state.pp_margin <- n;
+ let new_max_indent =
+ (* Try to maintain max_indent to its actual value. *)
+ if state.pp_max_indent <= state.pp_margin
+ then state.pp_max_indent else
+ (* If possible maintain pp_min_space_left to its actual value,
+ if this leads to a too small max_indent, take half of the
+ new margin, if it is greater than 1. *)
+ max (max (state.pp_margin - state.pp_min_space_left)
+ (state.pp_margin / 2)) 1 in
+ (* Rebuild invariants. *)
+ pp_set_max_indent state new_max_indent
+;;
+
+let pp_get_margin state () = state.pp_margin;;
+
+type formatter_out_functions = {
+ out_string : string -> int -> int -> unit;
+ out_flush : unit -> unit;
+ out_newline : unit -> unit;
+ out_spaces : int -> unit;
+}
+;;
+
+let pp_set_formatter_out_functions state {
+ out_string = f;
+ out_flush = g;
+ out_newline = h;
+ out_spaces = i;
+ } =
+ state.pp_out_string <- f;
+ state.pp_out_flush <- g;
+ state.pp_out_newline <- h;
+ state.pp_out_spaces <- i;
+;;
+
+let pp_get_formatter_out_functions state () = {
+ out_string = state.pp_out_string;
+ out_flush = state.pp_out_flush;
+ out_newline = state.pp_out_newline;
+ out_spaces = state.pp_out_spaces;
+}
+;;
+
+let pp_set_formatter_output_functions state f g =
+ state.pp_out_string <- f; state.pp_out_flush <- g
+;;
+let pp_get_formatter_output_functions state () =
+ (state.pp_out_string, state.pp_out_flush)
+;;
+
+let pp_set_all_formatter_output_functions state
+ ~out:f ~flush:g ~newline:h ~spaces:i =
+ pp_set_formatter_output_functions state f g;
+ state.pp_out_newline <- h;
+ state.pp_out_spaces <- i;
+;;
+let pp_get_all_formatter_output_functions state () =
+ (state.pp_out_string, state.pp_out_flush,
+ state.pp_out_newline, state.pp_out_spaces)
+;;
+
+(* Default function to output new lines. *)
+let display_newline state () = state.pp_out_string "\n" 0 1;;
+
+(* Default function to output spaces. *)
+let blank_line = String.make 80 ' ';;
+let rec display_blanks state n =
+ if n > 0 then
+ if n <= 80 then state.pp_out_string blank_line 0 n else
+ begin
+ state.pp_out_string blank_line 0 80;
+ display_blanks state (n - 80)
+ end
+;;
+
+let pp_set_formatter_out_channel state os =
+ state.pp_out_string <- output_substring os;
+ state.pp_out_flush <- (fun () -> flush os);
+ state.pp_out_newline <- display_newline state;
+ state.pp_out_spaces <- display_blanks state;
+;;
+
+(**************************************************************
+
+ Creation of specific formatters
+
+ **************************************************************)
+
+let default_pp_mark_open_tag s = "<" ^ s ^ ">";;
+let default_pp_mark_close_tag s = "</" ^ s ^ ">";;
+
+let default_pp_print_open_tag = ignore;;
+let default_pp_print_close_tag = ignore;;
+
+let pp_make_formatter f g h i =
+ (* The initial state of the formatter contains a dummy box. *)
+ let pp_q = make_queue () in
+ let sys_tok =
+ make_queue_elem (size_of_int (-1)) (Pp_begin (0, Pp_hovbox)) 0 in
+ add_queue sys_tok pp_q;
+ let sys_scan_stack =
+ (Scan_elem (1, sys_tok)) :: scan_stack_bottom in
+ {
+ pp_scan_stack = sys_scan_stack;
+ pp_format_stack = [];
+ pp_tbox_stack = [];
+ pp_tag_stack = [];
+ pp_mark_stack = [];
+ pp_margin = 78;
+ pp_min_space_left = 10;
+ pp_max_indent = 78 - 10;
+ pp_space_left = 78;
+ pp_current_indent = 0;
+ pp_is_new_line = true;
+ pp_left_total = 1;
+ pp_right_total = 1;
+ pp_curr_depth = 1;
+ pp_max_boxes = max_int;
+ pp_ellipsis = ".";
+ pp_out_string = f;
+ pp_out_flush = g;
+ pp_out_newline = h;
+ pp_out_spaces = i;
+ pp_print_tags = false;
+ pp_mark_tags = false;
+ pp_mark_open_tag = default_pp_mark_open_tag;
+ pp_mark_close_tag = default_pp_mark_close_tag;
+ pp_print_open_tag = default_pp_print_open_tag;
+ pp_print_close_tag = default_pp_print_close_tag;
+ pp_queue = pp_q;
+ }
+;;
+
+(* Make a formatter with default functions to output spaces and new lines. *)
+let make_formatter output flush =
+ let ppf = pp_make_formatter output flush ignore ignore in
+ ppf.pp_out_newline <- display_newline ppf;
+ ppf.pp_out_spaces <- display_blanks ppf;
+ ppf
+;;
+
+let formatter_of_out_channel oc =
+ make_formatter (output_substring oc) (fun () -> flush oc)
+;;
+
+let formatter_of_buffer b =
+ make_formatter (Buffer.add_substring b) ignore
+;;
+
+let stdbuf = Buffer.create 512;;
+
+(* Predefined formatters. *)
+let std_formatter = formatter_of_out_channel Pervasives.stdout
+and err_formatter = formatter_of_out_channel Pervasives.stderr
+and str_formatter = formatter_of_buffer stdbuf
+;;
+
+let flush_buffer_formatter buf ppf =
+ pp_flush_queue ppf false;
+ let s = Buffer.contents buf in
+ Buffer.reset buf;
+ s
+;;
+
+let flush_str_formatter () = flush_buffer_formatter stdbuf str_formatter;;
+
+(**************************************************************
+
+ Basic functions on the standard formatter
+
+ **************************************************************)
+
+let open_hbox = pp_open_hbox std_formatter
+and open_vbox = pp_open_vbox std_formatter
+and open_hvbox = pp_open_hvbox std_formatter
+and open_hovbox = pp_open_hovbox std_formatter
+and open_box = pp_open_box std_formatter
+and close_box = pp_close_box std_formatter
+and open_tag = pp_open_tag std_formatter
+and close_tag = pp_close_tag std_formatter
+and print_as = pp_print_as std_formatter
+and print_string = pp_print_string std_formatter
+and print_int = pp_print_int std_formatter
+and print_float = pp_print_float std_formatter
+and print_char = pp_print_char std_formatter
+and print_bool = pp_print_bool std_formatter
+and print_break = pp_print_break std_formatter
+and print_cut = pp_print_cut std_formatter
+and print_space = pp_print_space std_formatter
+and force_newline = pp_force_newline std_formatter
+and print_flush = pp_print_flush std_formatter
+and print_newline = pp_print_newline std_formatter
+and print_if_newline = pp_print_if_newline std_formatter
+
+and open_tbox = pp_open_tbox std_formatter
+and close_tbox = pp_close_tbox std_formatter
+and print_tbreak = pp_print_tbreak std_formatter
+
+and set_tab = pp_set_tab std_formatter
+and print_tab = pp_print_tab std_formatter
+
+and set_margin = pp_set_margin std_formatter
+and get_margin = pp_get_margin std_formatter
+
+and set_max_indent = pp_set_max_indent std_formatter
+and get_max_indent = pp_get_max_indent std_formatter
+
+and set_max_boxes = pp_set_max_boxes std_formatter
+and get_max_boxes = pp_get_max_boxes std_formatter
+and over_max_boxes = pp_over_max_boxes std_formatter
+
+and set_ellipsis_text = pp_set_ellipsis_text std_formatter
+and get_ellipsis_text = pp_get_ellipsis_text std_formatter
+
+and set_formatter_out_channel =
+ pp_set_formatter_out_channel std_formatter
+
+and set_formatter_out_functions =
+ pp_set_formatter_out_functions std_formatter
+and get_formatter_out_functions =
+ pp_get_formatter_out_functions std_formatter
+
+and set_formatter_output_functions =
+ pp_set_formatter_output_functions std_formatter
+and get_formatter_output_functions =
+ pp_get_formatter_output_functions std_formatter
+
+and set_all_formatter_output_functions =
+ pp_set_all_formatter_output_functions std_formatter
+and get_all_formatter_output_functions =
+ pp_get_all_formatter_output_functions std_formatter
+
+and set_formatter_tag_functions =
+ pp_set_formatter_tag_functions std_formatter
+and get_formatter_tag_functions =
+ pp_get_formatter_tag_functions std_formatter
+and set_print_tags =
+ pp_set_print_tags std_formatter
+and get_print_tags =
+ pp_get_print_tags std_formatter
+and set_mark_tags =
+ pp_set_mark_tags std_formatter
+and get_mark_tags =
+ pp_get_mark_tags std_formatter
+and set_tags =
+ pp_set_tags std_formatter
+;;
+
+ (**************************************************************)
+
+let compute_tag output tag_acc =
+ let buf = Buffer.create 16 in
+ let ppf = formatter_of_buffer buf in
+ let () = output ppf tag_acc in
+ let () = pp_print_flush ppf () in
+ let len = Buffer.length buf in
+ if len < 2 then Buffer.contents buf
+ else Buffer.sub buf 1 (len - 2)
+
+ (**************************************************************
+
+ Defining continuations to be passed as arguments of
+ CamlinternalFormat.make_printf.
+
+ **************************************************************)
+
+open CamlinternalFormatBasics
+open CamlinternalFormat
+
+(* Interpret a formatting entity on a formatter. *)
+let output_formatting_lit ppf fmting_lit = match fmting_lit with
+ | Close_box -> pp_close_box ppf ()
+ | Close_tag -> pp_close_tag ppf ()
+ | Break (_, width, offset) -> pp_print_break ppf width offset
+ | FFlush -> pp_print_flush ppf ()
+ | Force_newline -> pp_force_newline ppf ()
+ | Flush_newline -> pp_print_newline ppf ()
+ | Magic_size (_, _) -> ()
+ | Escaped_at -> pp_print_char ppf '@'
+ | Escaped_percent -> pp_print_char ppf '%'
+ | Scan_indic c -> pp_print_char ppf '@'; pp_print_char ppf c
+
+(* Recursively output an "accumulator" containing a reversed list of
+ printing entities (string, char, flus, ...) in an output_stream. *)
+(* Differ from Printf.output_acc by the interpretation of formatting. *)
+(* Used as a continuation of CamlinternalFormat.make_printf. *)
+let rec output_acc ppf acc = match acc with
+ | Acc_string_literal (Acc_formatting_lit (p, Magic_size (_, size)), s)
+ | Acc_data_string (Acc_formatting_lit (p, Magic_size (_, size)), s) ->
+ output_acc ppf p;
+ pp_print_as_size ppf (size_of_int size) s;
+ | Acc_char_literal (Acc_formatting_lit (p, Magic_size (_, size)), c)
+ | Acc_data_char (Acc_formatting_lit (p, Magic_size (_, size)), c) ->
+ output_acc ppf p;
+ pp_print_as_size ppf (size_of_int size) (String.make 1 c);
+ | Acc_formatting_lit (p, f) ->
+ output_acc ppf p;
+ output_formatting_lit ppf f;
+ | Acc_formatting_gen (p, Acc_open_tag acc') ->
+ output_acc ppf p;
+ pp_open_tag ppf (compute_tag output_acc acc')
+ | Acc_formatting_gen (p, Acc_open_box acc') ->
+ let () = output_acc ppf p in
+ let (indent, bty) = open_box_of_string (compute_tag output_acc acc') in
+ pp_open_box_gen ppf indent bty
+ | Acc_string_literal (p, s)
+ | Acc_data_string (p, s) -> output_acc ppf p; pp_print_string ppf s;
+ | Acc_char_literal (p, c)
+ | Acc_data_char (p, c) -> output_acc ppf p; pp_print_char ppf c;
+ | Acc_delay (p, f) -> output_acc ppf p; f ppf;
+ | Acc_flush p -> output_acc ppf p; pp_print_flush ppf ();
+ | Acc_invalid_arg (p, msg) -> output_acc ppf p; invalid_arg msg;
+ | End_of_acc -> ()
+
+(* Recursively output an "accumulator" containing a reversed list of
+ printing entities (string, char, flus, ...) in a buffer. *)
+(* Differ from Printf.bufput_acc by the interpretation of formatting. *)
+(* Used as a continuation of CamlinternalFormat.make_printf. *)
+let rec strput_acc ppf acc = match acc with
+ | Acc_string_literal (Acc_formatting_lit (p, Magic_size (_, size)), s)
+ | Acc_data_string (Acc_formatting_lit (p, Magic_size (_, size)), s) ->
+ strput_acc ppf p;
+ pp_print_as_size ppf (size_of_int size) s;
+ | Acc_char_literal (Acc_formatting_lit (p, Magic_size (_, size)), c)
+ | Acc_data_char (Acc_formatting_lit (p, Magic_size (_, size)), c) ->
+ strput_acc ppf p;
+ pp_print_as_size ppf (size_of_int size) (String.make 1 c);
+ | Acc_delay (Acc_formatting_lit (p, Magic_size (_, size)), f) ->
+ strput_acc ppf p;
+ pp_print_as_size ppf (size_of_int size) (f ());
+ | Acc_formatting_lit (p, f) ->
+ strput_acc ppf p;
+ output_formatting_lit ppf f;
+ | Acc_formatting_gen (p, Acc_open_tag acc') ->
+ strput_acc ppf p;
+ pp_open_tag ppf (compute_tag strput_acc acc')
+ | Acc_formatting_gen (p, Acc_open_box acc') ->
+ let () = strput_acc ppf p in
+ let (indent, bty) = open_box_of_string (compute_tag strput_acc acc') in
+ pp_open_box_gen ppf indent bty
+ | Acc_string_literal (p, s)
+ | Acc_data_string (p, s) -> strput_acc ppf p; pp_print_string ppf s;
+ | Acc_char_literal (p, c)
+ | Acc_data_char (p, c) -> strput_acc ppf p; pp_print_char ppf c;
+ | Acc_delay (p, f) -> strput_acc ppf p; pp_print_string ppf (f ());
+ | Acc_flush p -> strput_acc ppf p; pp_print_flush ppf ();
+ | Acc_invalid_arg (p, msg) -> strput_acc ppf p; invalid_arg msg;
+ | End_of_acc -> ()
+
+(**************************************************************
+
+ Defining [fprintf] and various flavors of [fprintf].
+
+ **************************************************************)
+
+let kfprintf k ppf (Format (fmt, _)) =
+ make_printf
+ (fun ppf acc -> output_acc ppf acc; k ppf)
+ ppf End_of_acc fmt
+
+and ikfprintf k ppf (Format (fmt, _)) =
+ make_printf
+ (fun _ _ -> k ppf)
+ ppf End_of_acc fmt
+;;
+
+let fprintf ppf = kfprintf ignore ppf;;
+let ifprintf ppf = ikfprintf ignore ppf;;
+let printf fmt = fprintf std_formatter fmt;;
+let eprintf fmt = fprintf err_formatter fmt;;
+
+let ksprintf k (Format (fmt, _)) =
+ let b = Buffer.create 512 in
+ let ppf = formatter_of_buffer b in
+ let k () acc =
+ strput_acc ppf acc;
+ k (flush_buffer_formatter b ppf) in
+ make_printf k () End_of_acc fmt
+;;
+
+let sprintf fmt = ksprintf (fun s -> s) fmt;;
+
+let asprintf (Format (fmt, _)) =
+ let b = Buffer.create 512 in
+ let ppf = formatter_of_buffer b in
+ let k ppf acc =
+ output_acc ppf acc;
+ flush_buffer_formatter b ppf in
+ make_printf k ppf End_of_acc fmt
+;;
+
+(**************************************************************
+
+ Deprecated stuff.
+
+ **************************************************************)
+
+(* Deprecated error prone function bprintf. *)
+let bprintf b (Format (fmt, _) : ('a, formatter, unit) format) =
+ let k ppf acc = output_acc ppf acc; pp_flush_queue ppf false in
+ make_printf k (formatter_of_buffer b) End_of_acc fmt
+;;
+
+(* Deprecated alias for ksprintf. *)
+let kprintf = ksprintf;;
+
+(* Output everything left in the pretty printer queue at end of execution. *)
+at_exit print_flush
+;;
diff --git a/stdlib/format.mli b/stdlib/format.mli
new file mode 100644
index 0000000000..05e153b2e8
--- /dev/null
+++ b/stdlib/format.mli
@@ -0,0 +1,756 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Pretty printing.
+
+ This module implements a pretty-printing facility to format text
+ within 'pretty-printing boxes'. The pretty-printer breaks lines
+ at specified break hints, and indents lines according to the box
+ structure.
+
+ For a gentle introduction to the basics of pretty-printing using
+ [Format], read
+ {{:http://caml.inria.fr/resources/doc/guides/format.en.html}
+ http://caml.inria.fr/resources/doc/guides/format.en.html}.
+
+ You may consider this module as providing an extension to the
+ [printf] facility to provide automatic line breaking. The addition of
+ pretty-printing annotations to your regular [printf] formats gives you
+ fancy indentation and line breaks.
+ Pretty-printing annotations are described below in the documentation of
+ the function {!Format.fprintf}.
+
+ You may also use the explicit box management and printing functions
+ provided by this module. This style is more basic but more verbose
+ than the [fprintf] concise formats.
+
+ For instance, the sequence
+ [open_box 0; print_string "x ="; print_space ();
+ print_int 1; close_box (); print_newline ()]
+ that prints [x = 1] within a pretty-printing box, can be
+ abbreviated as [printf "@[%s@ %i@]@." "x =" 1], or even shorter
+ [printf "@[x =@ %i@]@." 1].
+
+ Rule of thumb for casual users of this library:
+ - use simple boxes (as obtained by [open_box 0]);
+ - use simple break hints (as obtained by [print_cut ()] that outputs a
+ simple break hint, or by [print_space ()] that outputs a space
+ indicating a break hint);
+ - once a box is opened, display its material with basic printing
+ functions (e. g. [print_int] and [print_string]);
+ - when the material for a box has been printed, call [close_box ()] to
+ close the box;
+ - at the end of your routine, flush the pretty-printer to display all the
+ remaining material, e.g. evaluate [print_newline ()].
+
+ The behaviour of pretty-printing commands is unspecified
+ if there is no opened pretty-printing box. Each box opened via
+ one of the [open_] functions below must be closed using [close_box]
+ for proper formatting. Otherwise, some of the material printed in the
+ boxes may not be output, or may be formatted incorrectly.
+
+ In case of interactive use, the system closes all opened boxes and
+ flushes all pending text (as with the [print_newline] function)
+ after each phrase. Each phrase is therefore executed in the initial
+ state of the pretty-printer.
+
+ Warning: the material output by the following functions is delayed
+ in the pretty-printer queue in order to compute the proper line
+ breaking. Hence, you should not mix calls to the printing functions
+ of the basic I/O system with calls to the functions of this module:
+ this could result in some strange output seemingly unrelated with
+ the evaluation order of printing commands.
+*)
+
+(** {6 Boxes} *)
+
+val open_box : int -> unit
+(** [open_box d] opens a new pretty-printing box
+ with offset [d].
+ This box is the general purpose pretty-printing box.
+ Material in this box is displayed 'horizontal or vertical':
+ break hints inside the box may lead to a new line, if there
+ is no more room on the line to print the remainder of the box,
+ or if a new line may lead to a new indentation
+ (demonstrating the indentation of the box).
+ When a new line is printed in the box, [d] is added to the
+ current indentation. *)
+
+val close_box : unit -> unit
+(** Closes the most recently opened pretty-printing box. *)
+
+(** {6 Formatting functions} *)
+
+val print_string : string -> unit
+(** [print_string str] prints [str] in the current box. *)
+
+val print_as : int -> string -> unit
+(** [print_as len str] prints [str] in the
+ current box. The pretty-printer formats [str] as if
+ it were of length [len]. *)
+
+val print_int : int -> unit
+(** Prints an integer in the current box. *)
+
+val print_float : float -> unit
+(** Prints a floating point number in the current box. *)
+
+val print_char : char -> unit
+(** Prints a character in the current box. *)
+
+val print_bool : bool -> unit
+(** Prints a boolean in the current box. *)
+
+(** {6 Break hints} *)
+
+val print_space : unit -> unit
+(** [print_space ()] is used to separate items (typically to print
+ a space between two words).
+ It indicates that the line may be split at this
+ point. It either prints one space or splits the line.
+ It is equivalent to [print_break 1 0]. *)
+
+val print_cut : unit -> unit
+(** [print_cut ()] is used to mark a good break position.
+ It indicates that the line may be split at this
+ point. It either prints nothing or splits the line.
+ This allows line splitting at the current
+ point, without printing spaces or adding indentation.
+ It is equivalent to [print_break 0 0]. *)
+
+val print_break : int -> int -> unit
+(** Inserts a break hint in a pretty-printing box.
+ [print_break nspaces offset] indicates that the line may
+ be split (a newline character is printed) at this point,
+ if the contents of the current box does not fit on the
+ current line.
+ If the line is split at that point, [offset] is added to
+ the current indentation. If the line is not split,
+ [nspaces] spaces are printed. *)
+
+val print_flush : unit -> unit
+(** Flushes the pretty printer: all opened boxes are closed,
+ and all pending text is displayed. *)
+
+val print_newline : unit -> unit
+(** Equivalent to [print_flush] followed by a new line. *)
+
+val force_newline : unit -> unit
+(** Forces a newline in the current box. Not the normal way of
+ pretty-printing, you should prefer break hints. *)
+
+val print_if_newline : unit -> unit
+(** Executes the next formatting command if the preceding line
+ has just been split. Otherwise, ignore the next formatting
+ command. *)
+
+(** {6 Margin} *)
+
+val set_margin : int -> unit
+(** [set_margin d] sets the value of the right margin
+ to [d] (in characters): this value is used to detect line
+ overflows that leads to split lines.
+ Nothing happens if [d] is smaller than 2.
+ If [d] is too large, the right margin is set to the maximum
+ admissible value (which is greater than [10^9]). *)
+
+val get_margin : unit -> int
+(** Returns the position of the right margin. *)
+
+(** {6 Maximum indentation limit} *)
+
+val set_max_indent : int -> unit
+(** [set_max_indent d] sets the value of the maximum
+ indentation limit to [d] (in characters):
+ once this limit is reached, boxes are rejected to the left,
+ if they do not fit on the current line.
+ Nothing happens if [d] is smaller than 2.
+ If [d] is too large, the limit is set to the maximum
+ admissible value (which is greater than [10^9]). *)
+
+val get_max_indent : unit -> int
+(** Return the value of the maximum indentation limit (in characters). *)
+
+(** {6 Formatting depth: maximum number of boxes allowed before ellipsis} *)
+
+val set_max_boxes : int -> unit
+(** [set_max_boxes max] sets the maximum number of boxes simultaneously
+ opened.
+ Material inside boxes nested deeper is printed as an ellipsis (more
+ precisely as the text returned by [get_ellipsis_text ()]).
+ Nothing happens if [max] is smaller than 2. *)
+
+val get_max_boxes : unit -> int
+(** Returns the maximum number of boxes allowed before ellipsis. *)
+
+val over_max_boxes : unit -> bool
+(** Tests if the maximum number of boxes allowed have already been opened. *)
+
+(** {6 Advanced formatting} *)
+
+val open_hbox : unit -> unit
+(** [open_hbox ()] opens a new pretty-printing box.
+ This box is 'horizontal': the line is not split in this box
+ (new lines may still occur inside boxes nested deeper). *)
+
+val open_vbox : int -> unit
+(** [open_vbox d] opens a new pretty-printing box
+ with offset [d].
+ This box is 'vertical': every break hint inside this
+ box leads to a new line.
+ When a new line is printed in the box, [d] is added to the
+ current indentation. *)
+
+val open_hvbox : int -> unit
+(** [open_hvbox d] opens a new pretty-printing box
+ with offset [d].
+ This box is 'horizontal-vertical': it behaves as an
+ 'horizontal' box if it fits on a single line,
+ otherwise it behaves as a 'vertical' box.
+ When a new line is printed in the box, [d] is added to the
+ current indentation. *)
+
+val open_hovbox : int -> unit
+(** [open_hovbox d] opens a new pretty-printing box
+ with offset [d].
+ This box is 'horizontal or vertical': break hints
+ inside this box may lead to a new line, if there is no more room
+ on the line to print the remainder of the box.
+ When a new line is printed in the box, [d] is added to the
+ current indentation. *)
+
+(** {6 Tabulations} *)
+
+val open_tbox : unit -> unit
+(** Opens a tabulation box. *)
+
+val close_tbox : unit -> unit
+(** Closes the most recently opened tabulation box. *)
+
+val print_tbreak : int -> int -> unit
+(** Break hint in a tabulation box.
+ [print_tbreak spaces offset] moves the insertion point to
+ the next tabulation ([spaces] being added to this position).
+ Nothing occurs if insertion point is already on a
+ tabulation mark.
+ If there is no next tabulation on the line, then a newline
+ is printed and the insertion point moves to the first
+ tabulation of the box.
+ If a new line is printed, [offset] is added to the current
+ indentation. *)
+
+val set_tab : unit -> unit
+(** Sets a tabulation mark at the current insertion point. *)
+
+val print_tab : unit -> unit
+(** [print_tab ()] is equivalent to [print_tbreak 0 0]. *)
+
+(** {6 Ellipsis} *)
+
+val set_ellipsis_text : string -> unit
+(** Set the text of the ellipsis printed when too many boxes
+ are opened (a single dot, [.], by default). *)
+
+val get_ellipsis_text : unit -> string
+(** Return the text of the ellipsis. *)
+
+(** {6:tags Semantics Tags} *)
+
+type tag = string
+
+(** {i Semantics tags} (or simply {e tags}) are used to decorate printed
+ entities for user's defined purposes, e.g. setting font and giving size
+ indications for a display device, or marking delimitation of semantics
+ entities (e.g. HTML or TeX elements or terminal escape sequences).
+
+ By default, those tags do not influence line breaking calculation:
+ the tag 'markers' are not considered as part of the printing
+ material that drives line breaking (in other words, the length of
+ those strings is considered as zero for line breaking).
+
+ Thus, tag handling is in some sense transparent to pretty-printing
+ and does not interfere with usual indentation. Hence, a single
+ pretty printing routine can output both simple 'verbatim'
+ material or richer decorated output depending on the treatment of
+ tags. By default, tags are not active, hence the output is not
+ decorated with tag information. Once [set_tags] is set to [true],
+ the pretty printer engine honours tags and decorates the output
+ accordingly.
+
+ When a tag has been opened (or closed), it is both and successively
+ 'printed' and 'marked'. Printing a tag means calling a
+ formatter specific function with the name of the tag as argument:
+ that 'tag printing' function can then print any regular material
+ to the formatter (so that this material is enqueued as usual in the
+ formatter queue for further line-breaking computation). Marking a
+ tag means to output an arbitrary string (the 'tag marker'),
+ directly into the output device of the formatter. Hence, the
+ formatter specific 'tag marking' function must return the tag
+ marker string associated to its tag argument. Being flushed
+ directly into the output device of the formatter, tag marker
+ strings are not considered as part of the printing material that
+ drives line breaking (in other words, the length of the strings
+ corresponding to tag markers is considered as zero for line
+ breaking). In addition, advanced users may take advantage of
+ the specificity of tag markers to be precisely output when the
+ pretty printer has already decided where to break the lines, and
+ precisely when the queue is flushed into the output device.
+
+ In the spirit of HTML tags, the default tag marking functions
+ output tags enclosed in "<" and ">": hence, the opening marker of
+ tag [t] is ["<t>"] and the closing marker ["</t>"].
+
+ Default tag printing functions just do nothing.
+
+ Tag marking and tag printing functions are user definable and can
+ be set by calling [set_formatter_tag_functions]. *)
+
+val open_tag : tag -> unit
+(** [open_tag t] opens the tag named [t]; the [print_open_tag]
+ function of the formatter is called with [t] as argument;
+ the tag marker [mark_open_tag t] will be flushed into the output
+ device of the formatter. *)
+
+val close_tag : unit -> unit
+(** [close_tag ()] closes the most recently opened tag [t].
+ In addition, the [print_close_tag] function of the formatter is called
+ with [t] as argument. The marker [mark_close_tag t] will be flushed
+ into the output device of the formatter. *)
+
+val set_tags : bool -> unit
+(** [set_tags b] turns on or off the treatment of tags (default is off). *)
+
+val set_print_tags : bool -> unit
+(**[set_print_tags b] turns on or off the printing of tags. *)
+
+val set_mark_tags : bool -> unit
+(** [set_mark_tags b] turns on or off the output of tag markers. *)
+
+val get_print_tags : unit -> bool
+(** Return the current status of tags printing. *)
+
+val get_mark_tags : unit -> bool
+(** Return the current status of tags marking. *)
+
+(** {6 Redirecting the standard formatter output} *)
+
+val set_formatter_out_channel : Pervasives.out_channel -> unit
+(** Redirect the pretty-printer output to the given channel.
+ (All the output functions of the standard formatter are set to the
+ default output functions printing to the given channel.) *)
+
+val set_formatter_output_functions :
+ (string -> int -> int -> unit) -> (unit -> unit) -> unit
+(** [set_formatter_output_functions out flush] redirects the
+ pretty-printer output functions to the functions [out] and
+ [flush].
+
+ The [out] function performs all the pretty-printer string output.
+ It is called with a string [s], a start position [p], and a number of
+ characters [n]; it is supposed to output characters [p] to [p + n - 1] of
+ [s].
+
+ The [flush] function is called whenever the pretty-printer is flushed
+ (via conversion [%!], or pretty-printing indications [@?] or [@.], or
+ using low level functions [print_flush] or [print_newline]). *)
+
+val get_formatter_output_functions :
+ unit -> (string -> int -> int -> unit) * (unit -> unit)
+(** Return the current output functions of the pretty-printer. *)
+
+(** {6:meaning Changing the meaning of standard formatter pretty printing} *)
+
+(** The [Format] module is versatile enough to let you completely redefine
+ the meaning of pretty printing: you may provide your own functions to define
+ how to handle indentation, line breaking, and even printing of all the
+ characters that have to be printed! *)
+
+type formatter_out_functions = {
+ out_string : string -> int -> int -> unit;
+ out_flush : unit -> unit;
+ out_newline : unit -> unit;
+ out_spaces : int -> unit;
+}
+
+
+val set_formatter_out_functions : formatter_out_functions -> unit
+(** [set_formatter_out_functions f]
+ Redirect the pretty-printer output to the functions [f.out_string]
+ and [f.out_flush] as described in
+ [set_formatter_output_functions]. In addition, the pretty-printer function
+ that outputs a newline is set to the function [f.out_newline] and
+ the function that outputs indentation spaces is set to the function
+ [f.out_spaces].
+
+ This way, you can change the meaning of indentation (which can be
+ something else than just printing space characters) and the meaning of new
+ lines opening (which can be connected to any other action needed by the
+ application at hand). The two functions [f.out_spaces] and [f.out_newline]
+ are normally connected to [f.out_string] and [f.out_flush]: respective
+ default values for [f.out_space] and [f.out_newline] are
+ [f.out_string (String.make n ' ') 0 n] and [f.out_string "\n" 0 1]. *)
+
+val get_formatter_out_functions : unit -> formatter_out_functions
+(** Return the current output functions of the pretty-printer,
+ including line breaking and indentation functions. Useful to record the
+ current setting and restore it afterwards. *)
+
+(** {6:tagsmeaning Changing the meaning of printing semantics tags} *)
+
+type formatter_tag_functions = {
+ mark_open_tag : tag -> string;
+ mark_close_tag : tag -> string;
+ print_open_tag : tag -> unit;
+ print_close_tag : tag -> unit;
+}
+(** The tag handling functions specific to a formatter:
+ [mark] versions are the 'tag marking' functions that associate a string
+ marker to a tag in order for the pretty-printing engine to flush
+ those markers as 0 length tokens in the output device of the formatter.
+ [print] versions are the 'tag printing' functions that can perform
+ regular printing when a tag is closed or opened. *)
+
+val set_formatter_tag_functions : formatter_tag_functions -> unit
+(** [set_formatter_tag_functions tag_funs] changes the meaning of
+ opening and closing tags to use the functions in [tag_funs].
+
+ When opening a tag name [t], the string [t] is passed to the
+ opening tag marking function (the [mark_open_tag] field of the
+ record [tag_funs]), that must return the opening tag marker for
+ that name. When the next call to [close_tag ()] happens, the tag
+ name [t] is sent back to the closing tag marking function (the
+ [mark_close_tag] field of record [tag_funs]), that must return a
+ closing tag marker for that name.
+
+ The [print_] field of the record contains the functions that are
+ called at tag opening and tag closing time, to output regular
+ material in the pretty-printer queue. *)
+
+val get_formatter_tag_functions : unit -> formatter_tag_functions
+(** Return the current tag functions of the pretty-printer. *)
+
+(** {6 Multiple formatted output} *)
+
+type formatter
+(** Abstract data corresponding to a pretty-printer (also called a
+ formatter) and all its machinery.
+
+ Defining new pretty-printers permits unrelated output of material in
+ parallel on several output channels.
+ All the parameters of a pretty-printer are local to this pretty-printer:
+ margin, maximum indentation limit, maximum number of boxes
+ simultaneously opened, ellipsis, and so on, are specific to
+ each pretty-printer and may be fixed independently.
+ Given a [Pervasives.out_channel] output channel [oc], a new formatter
+ writing to that channel is simply obtained by calling
+ [formatter_of_out_channel oc].
+ Alternatively, the [make_formatter] function allocates a new
+ formatter with explicit output and flushing functions
+ (convenient to output material to strings for instance).
+*)
+
+val formatter_of_out_channel : out_channel -> formatter
+(** [formatter_of_out_channel oc] returns a new formatter that
+ writes to the corresponding channel [oc]. *)
+
+val std_formatter : formatter
+(** The standard formatter used by the formatting functions
+ above. It is defined as [formatter_of_out_channel stdout]. *)
+
+val err_formatter : formatter
+(** A formatter to use with formatting functions below for
+ output to standard error. It is defined as
+ [formatter_of_out_channel stderr]. *)
+
+val formatter_of_buffer : Buffer.t -> formatter
+(** [formatter_of_buffer b] returns a new formatter writing to
+ buffer [b]. As usual, the formatter has to be flushed at
+ the end of pretty printing, using [pp_print_flush] or
+ [pp_print_newline], to display all the pending material. *)
+
+val stdbuf : Buffer.t
+(** The string buffer in which [str_formatter] writes. *)
+
+val str_formatter : formatter
+(** A formatter to use with formatting functions below for
+ output to the [stdbuf] string buffer.
+ [str_formatter] is defined as [formatter_of_buffer stdbuf]. *)
+
+val flush_str_formatter : unit -> string
+(** Returns the material printed with [str_formatter], flushes
+ the formatter and resets the corresponding buffer. *)
+
+val make_formatter :
+ (string -> int -> int -> unit) -> (unit -> unit) -> formatter
+(** [make_formatter out flush] returns a new formatter that writes according
+ to the output function [out], and the flushing function [flush]. For
+ instance, a formatter to the [Pervasives.out_channel] [oc] is returned by
+ [make_formatter (Pervasives.output oc) (fun () -> Pervasives.flush oc)]. *)
+
+(** {6 Basic functions to use with formatters} *)
+
+val pp_open_hbox : formatter -> unit -> unit
+val pp_open_vbox : formatter -> int -> unit
+val pp_open_hvbox : formatter -> int -> unit
+val pp_open_hovbox : formatter -> int -> unit
+val pp_open_box : formatter -> int -> unit
+val pp_close_box : formatter -> unit -> unit
+val pp_open_tag : formatter -> string -> unit
+val pp_close_tag : formatter -> unit -> unit
+val pp_print_string : formatter -> string -> unit
+val pp_print_as : formatter -> int -> string -> unit
+val pp_print_int : formatter -> int -> unit
+val pp_print_float : formatter -> float -> unit
+val pp_print_char : formatter -> char -> unit
+val pp_print_bool : formatter -> bool -> unit
+val pp_print_break : formatter -> int -> int -> unit
+val pp_print_cut : formatter -> unit -> unit
+val pp_print_space : formatter -> unit -> unit
+val pp_force_newline : formatter -> unit -> unit
+val pp_print_flush : formatter -> unit -> unit
+val pp_print_newline : formatter -> unit -> unit
+val pp_print_if_newline : formatter -> unit -> unit
+val pp_open_tbox : formatter -> unit -> unit
+val pp_close_tbox : formatter -> unit -> unit
+val pp_print_tbreak : formatter -> int -> int -> unit
+val pp_set_tab : formatter -> unit -> unit
+val pp_print_tab : formatter -> unit -> unit
+val pp_set_tags : formatter -> bool -> unit
+val pp_set_print_tags : formatter -> bool -> unit
+val pp_set_mark_tags : formatter -> bool -> unit
+val pp_get_print_tags : formatter -> unit -> bool
+val pp_get_mark_tags : formatter -> unit -> bool
+val pp_set_margin : formatter -> int -> unit
+val pp_get_margin : formatter -> unit -> int
+val pp_set_max_indent : formatter -> int -> unit
+val pp_get_max_indent : formatter -> unit -> int
+val pp_set_max_boxes : formatter -> int -> unit
+val pp_get_max_boxes : formatter -> unit -> int
+val pp_over_max_boxes : formatter -> unit -> bool
+val pp_set_ellipsis_text : formatter -> string -> unit
+val pp_get_ellipsis_text : formatter -> unit -> string
+val pp_set_formatter_out_channel :
+ formatter -> Pervasives.out_channel -> unit
+
+val pp_set_formatter_output_functions :
+ formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit
+
+val pp_get_formatter_output_functions :
+ formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)
+
+val pp_set_formatter_tag_functions :
+ formatter -> formatter_tag_functions -> unit
+
+val pp_get_formatter_tag_functions :
+ formatter -> unit -> formatter_tag_functions
+
+val pp_set_formatter_out_functions :
+ formatter -> formatter_out_functions -> unit
+
+val pp_get_formatter_out_functions :
+ formatter -> unit -> formatter_out_functions
+(** These functions are the basic ones: usual functions
+ operating on the standard formatter are defined via partial
+ evaluation of these primitives. For instance,
+ [print_string] is equal to [pp_print_string std_formatter]. *)
+
+(** {6 Convenience formatting functions.} *)
+
+val pp_print_list:
+ ?pp_sep:(formatter -> unit -> unit) ->
+ (formatter -> 'a -> unit) -> (formatter -> 'a list -> unit)
+(** [pp_print_list ?pp_sep pp_v ppf l] prints the list [l]. [pp_v] is
+ used on the elements of [l] and each element is separated by
+ a call to [pp_sep] (defaults to {!pp_print_cut}). Does nothing on
+ empty lists.
+
+ @since 4.02.0
+*)
+
+val pp_print_text : formatter -> string -> unit
+(** [pp_print_text ppf s] prints [s] with spaces and newlines
+ respectively printed with {!pp_print_space} and
+ {!pp_force_newline}.
+
+ @since 4.02.0
+*)
+
+(** {6 [printf] like functions for pretty-printing.} *)
+
+val fprintf : formatter -> ('a, formatter, unit) format -> 'a
+
+(** [fprintf ff fmt arg1 ... argN] formats the arguments [arg1] to [argN]
+ according to the format string [fmt], and outputs the resulting string on
+ the formatter [ff].
+
+ The format [fmt] is a character string which contains three types of
+ objects: plain characters and conversion specifications as specified in
+ the [Printf] module, and pretty-printing indications specific to the
+ [Format] module.
+
+ The pretty-printing indication characters are introduced by
+ a [@] character, and their meanings are:
+ - [@\[]: open a pretty-printing box. The type and offset of the
+ box may be optionally specified with the following syntax:
+ the [<] character, followed by an optional box type indication,
+ then an optional integer offset, and the closing [>] character.
+ Box type is one of [h], [v], [hv], [b], or [hov],
+ which stand respectively for an horizontal box, a vertical box,
+ an 'horizontal-vertical' box, or an 'horizontal or
+ vertical' box ([b] standing for an 'horizontal or
+ vertical' box demonstrating indentation and [hov] standing
+ for a regular'horizontal or vertical' box).
+ For instance, [@\[<hov 2>] opens an 'horizontal or vertical'
+ box with indentation 2 as obtained with [open_hovbox 2].
+ For more details about boxes, see the various box opening
+ functions [open_*box].
+ - [@\]]: close the most recently opened pretty-printing box.
+ - [@,]: output a good break hint, as with [print_cut ()].
+ - [@ ]: output a good break space, as with [print_space ()].
+ - [@;]: output a fully specified good break as with [print_break]. The
+ [nspaces] and [offset] parameters of the break may be
+ optionally specified with the following syntax:
+ the [<] character, followed by an integer [nspaces] value,
+ then an integer [offset], and a closing [>] character.
+ If no parameters are provided, the good break defaults to a
+ good break space.
+ - [@.]: flush the pretty printer and output a new line, as with
+ [print_newline ()].
+ - [@<n>]: print the following item as if it were of length [n].
+ Hence, [printf "@<0>%s" arg] prints [arg] as a zero length string.
+ If [@<n>] is not followed by a conversion specification,
+ then the following character of the format is printed as if
+ it were of length [n].
+ - [@\{]: open a tag. The name of the tag may be optionally
+ specified with the following syntax:
+ the [<] character, followed by an optional string
+ specification, and the closing [>] character. The string
+ specification is any character string that does not contain the
+ closing character ['>']. If omitted, the tag name defaults to the
+ empty string.
+ For more details about tags, see the functions [open_tag] and
+ [close_tag].
+ - [@\}]: close the most recently opened tag.
+ - [@?]: flush the pretty printer as with [print_flush ()].
+ This is equivalent to the conversion [%!].
+ - [@\n]: force a newline, as with [force_newline ()].
+ - [@@]: print a single [@] character.
+
+ Example: [printf "@[%s@ %d@]@." "x =" 1] is equivalent to
+ [open_box (); print_string "x ="; print_space ();
+ print_int 1; close_box (); print_newline ()].
+ It prints [x = 1] within a pretty-printing box.
+
+ Note: If you need to prevent the interpretation of a [@] character as a
+ pretty-printing indication, you can also escape it with a [%] character.
+
+*)
+
+val printf : ('a, formatter, unit) format -> 'a
+(** Same as [fprintf] above, but output on [std_formatter]. *)
+
+val eprintf : ('a, formatter, unit) format -> 'a
+(** Same as [fprintf] above, but output on [err_formatter]. *)
+
+val sprintf : ('a, unit, string) format -> 'a
+(** Same as [printf] above, but instead of printing on a formatter,
+ returns a string containing the result of formatting the arguments.
+ Note that the pretty-printer queue is flushed at the end of {e each
+ call} to [sprintf].
+
+ In case of multiple and related calls to [sprintf] to output
+ material on a single string, you should consider using [fprintf]
+ with the predefined formatter [str_formatter] and call
+ [flush_str_formatter ()] to get the final result.
+
+ Alternatively, you can use [Format.fprintf] with a formatter writing to a
+ buffer of your own: flushing the formatter and the buffer at the end of
+ pretty-printing returns the desired string.
+*)
+
+val asprintf : ('a, formatter, unit, string) format4 -> 'a
+(** Same as [printf] above, but instead of printing on a formatter,
+ returns a string containing the result of formatting the arguments.
+ The type of [asprintf] is general enough to interact nicely with [%a]
+ conversions.
+ @since 4.01.0
+ *)
+
+val ifprintf : formatter -> ('a, formatter, unit) format -> 'a
+(** Same as [fprintf] above, but does not print anything.
+ Useful to ignore some material when conditionally printing.
+ @since 3.10.0
+*)
+
+(** Formatted output functions with continuations. *)
+
+val kfprintf : (formatter -> 'a) -> formatter ->
+ ('b, formatter, unit, 'a) format4 -> 'b
+(** Same as [fprintf] above, but instead of returning immediately,
+ passes the formatter to its first argument at the end of printing. *)
+
+val ikfprintf : (formatter -> 'a) -> formatter ->
+ ('b, formatter, unit, 'a) format4 -> 'b
+(** Same as [kfprintf] above, but does not print anything.
+ Useful to ignore some material when conditionally printing.
+ @since 3.12.0
+*)
+
+val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b
+(** Same as [sprintf] above, but instead of returning the string,
+ passes it to the first argument. *)
+
+(** {6 Deprecated} *)
+
+val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a
+ [@@ocaml.deprecated]
+(** @deprecated This function is error prone. Do not use it.
+
+ If you need to print to some buffer [b], you must first define a
+ formatter writing to [b], using [let to_b = formatter_of_buffer b]; then
+ use regular calls to [Format.fprintf] on formatter [to_b]. *)
+
+val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b
+ [@@ocaml.deprecated "Use Format.ksprintf instead."]
+(** @deprecated An alias for [ksprintf]. *)
+
+val set_all_formatter_output_functions :
+ out:(string -> int -> int -> unit) ->
+ flush:(unit -> unit) ->
+ newline:(unit -> unit) ->
+ spaces:(int -> unit) ->
+ unit
+[@@ocaml.deprecated "Use Format.set_formatter_out_functions instead."]
+(** @deprecated Subsumed by [set_formatter_out_functions]. *)
+
+val get_all_formatter_output_functions :
+ unit ->
+ (string -> int -> int -> unit) *
+ (unit -> unit) *
+ (unit -> unit) *
+ (int -> unit)
+[@@ocaml.deprecated "Use Format.get_formatter_out_functions instead."]
+(** @deprecated Subsumed by [get_formatter_out_functions]. *)
+
+val pp_set_all_formatter_output_functions :
+ formatter -> out:(string -> int -> int -> unit) -> flush:(unit -> unit) ->
+ newline:(unit -> unit) -> spaces:(int -> unit) -> unit
+[@@ocaml.deprecated "Use Format.pp_set_formatter_out_functions instead."]
+(** @deprecated Subsumed by [pp_set_formatter_out_functions]. *)
+
+val pp_get_all_formatter_output_functions :
+ formatter -> unit ->
+ (string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) *
+ (int -> unit)
+[@@ocaml.deprecated "Use Format.pp_get_formatter_out_functions instead."]
+(** @deprecated Subsumed by [pp_get_formatter_out_functions]. *)
diff --git a/stdlib/gc.ml b/stdlib/gc.ml
new file mode 100644
index 0000000000..39bf343db4
--- /dev/null
+++ b/stdlib/gc.ml
@@ -0,0 +1,100 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type stat = {
+ minor_words : float;
+ promoted_words : float;
+ major_words : float;
+ minor_collections : int;
+ major_collections : int;
+ heap_words : int;
+ heap_chunks : int;
+ live_words : int;
+ live_blocks : int;
+ free_words : int;
+ free_blocks : int;
+ largest_free : int;
+ fragments : int;
+ compactions : int;
+ top_heap_words : int;
+ stack_size : int;
+};;
+
+type control = {
+ mutable minor_heap_size : int;
+ mutable major_heap_increment : int;
+ mutable space_overhead : int;
+ mutable verbose : int;
+ mutable max_overhead : int;
+ mutable stack_limit : int;
+ mutable allocation_policy : int;
+};;
+
+external stat : unit -> stat = "caml_gc_stat";;
+external quick_stat : unit -> stat = "caml_gc_quick_stat";;
+external counters : unit -> (float * float * float) = "caml_gc_counters";;
+external get : unit -> control = "caml_gc_get";;
+external set : control -> unit = "caml_gc_set";;
+external minor : unit -> unit = "caml_gc_minor";;
+external major_slice : int -> int = "caml_gc_major_slice";;
+external major : unit -> unit = "caml_gc_major";;
+external full_major : unit -> unit = "caml_gc_full_major";;
+external compact : unit -> unit = "caml_gc_compaction";;
+
+open Printf;;
+
+let print_stat c =
+ let st = stat () in
+ fprintf c "minor_words: %.0f\n" st.minor_words;
+ fprintf c "promoted_words: %.0f\n" st.promoted_words;
+ fprintf c "major_words: %.0f\n" st.major_words;
+ fprintf c "minor_collections: %d\n" st.minor_collections;
+ fprintf c "major_collections: %d\n" st.major_collections;
+ fprintf c "heap_words: %d\n" st.heap_words;
+ fprintf c "heap_chunks: %d\n" st.heap_chunks;
+ fprintf c "top_heap_words: %d\n" st.top_heap_words;
+ fprintf c "live_words: %d\n" st.live_words;
+ fprintf c "live_blocks: %d\n" st.live_blocks;
+ fprintf c "free_words: %d\n" st.free_words;
+ fprintf c "free_blocks: %d\n" st.free_blocks;
+ fprintf c "largest_free: %d\n" st.largest_free;
+ fprintf c "fragments: %d\n" st.fragments;
+ fprintf c "compactions: %d\n" st.compactions;
+;;
+
+let allocated_bytes () =
+ let (mi, pro, ma) = counters () in
+ (mi +. ma -. pro) *. float_of_int (Sys.word_size / 8)
+;;
+
+external finalise : ('a -> unit) -> 'a -> unit = "caml_final_register";;
+external finalise_release : unit -> unit = "caml_final_release";;
+
+
+type alarm = bool ref;;
+type alarm_rec = {active : alarm; f : unit -> unit};;
+
+let rec call_alarm arec =
+ if !(arec.active) then begin
+ finalise call_alarm arec;
+ arec.f ();
+ end;
+;;
+
+let create_alarm f =
+ let arec = { active = ref true; f = f } in
+ finalise call_alarm arec;
+ arec.active
+;;
+
+let delete_alarm a = a := false;;
diff --git a/stdlib/gc.mli b/stdlib/gc.mli
new file mode 100644
index 0000000000..d07b3c1fbe
--- /dev/null
+++ b/stdlib/gc.mli
@@ -0,0 +1,279 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Memory management control and statistics; finalised values. *)
+
+type stat =
+ { minor_words : float;
+ (** Number of words allocated in the minor heap since
+ the program was started. This number is accurate in
+ byte-code programs, but only an approximation in programs
+ compiled to native code. *)
+
+ promoted_words : float;
+ (** Number of words allocated in the minor heap that
+ survived a minor collection and were moved to the major heap
+ since the program was started. *)
+
+ major_words : float;
+ (** Number of words allocated in the major heap, including
+ the promoted words, since the program was started. *)
+
+ minor_collections : int;
+ (** Number of minor collections since the program was started. *)
+
+ major_collections : int;
+ (** Number of major collection cycles completed since the program
+ was started. *)
+
+ heap_words : int;
+ (** Total size of the major heap, in words. *)
+
+ heap_chunks : int;
+ (** Number of contiguous pieces of memory that make up the major heap. *)
+
+ live_words : int;
+ (** Number of words of live data in the major heap, including the header
+ words. *)
+
+ live_blocks : int;
+ (** Number of live blocks in the major heap. *)
+
+ free_words : int;
+ (** Number of words in the free list. *)
+
+ free_blocks : int;
+ (** Number of blocks in the free list. *)
+
+ largest_free : int;
+ (** Size (in words) of the largest block in the free list. *)
+
+ fragments : int;
+ (** Number of wasted words due to fragmentation. These are
+ 1-words free blocks placed between two live blocks. They
+ are not available for allocation. *)
+
+ compactions : int;
+ (** Number of heap compactions since the program was started. *)
+
+ top_heap_words : int;
+ (** Maximum size reached by the major heap, in words. *)
+
+ stack_size: int;
+ (** Current size of the stack, in words. @since 3.12.0 *)
+}
+(** The memory management counters are returned in a [stat] record.
+
+ The total amount of memory allocated by the program since it was started
+ is (in words) [minor_words + major_words - promoted_words]. Multiply by
+ the word size (4 on a 32-bit machine, 8 on a 64-bit machine) to get
+ the number of bytes.
+*)
+
+type control =
+ { mutable minor_heap_size : int;
+ (** The size (in words) of the minor heap. Changing
+ this parameter will trigger a minor collection. Default: 256k. *)
+
+ mutable major_heap_increment : int;
+ (** How much to add to the major heap when increasing it. If this
+ number is less than or equal to 1000, it is a percentage of
+ the current heap size (i.e. setting it to 100 will double the heap
+ size at each increase). If it is more than 1000, it is a fixed
+ number of words that will be added to the heap. Default: 15. *)
+
+ mutable space_overhead : int;
+ (** The major GC speed is computed from this parameter.
+ This is the memory that will be "wasted" because the GC does not
+ immediatly collect unreachable blocks. It is expressed as a
+ percentage of the memory used for live data.
+ The GC will work more (use more CPU time and collect
+ blocks more eagerly) if [space_overhead] is smaller.
+ Default: 80. *)
+
+ mutable verbose : int;
+ (** This value controls the GC messages on standard error output.
+ It is a sum of some of the following flags, to print messages
+ on the corresponding events:
+ - [0x001] Start of major GC cycle.
+ - [0x002] Minor collection and major GC slice.
+ - [0x004] Growing and shrinking of the heap.
+ - [0x008] Resizing of stacks and memory manager tables.
+ - [0x010] Heap compaction.
+ - [0x020] Change of GC parameters.
+ - [0x040] Computation of major GC slice size.
+ - [0x080] Calling of finalisation functions.
+ - [0x100] Bytecode executable and shared library search at start-up.
+ - [0x200] Computation of compaction-triggering condition.
+ Default: 0. *)
+
+ mutable max_overhead : int;
+ (** Heap compaction is triggered when the estimated amount
+ of "wasted" memory is more than [max_overhead] percent of the
+ amount of live data. If [max_overhead] is set to 0, heap
+ compaction is triggered at the end of each major GC cycle
+ (this setting is intended for testing purposes only).
+ If [max_overhead >= 1000000], compaction is never triggered.
+ If compaction is permanently disabled, it is strongly suggested
+ to set [allocation_policy] to 1.
+ Default: 500. *)
+
+ mutable stack_limit : int;
+ (** The maximum size of the stack (in words). This is only
+ relevant to the byte-code runtime, as the native code runtime
+ uses the operating system's stack. Default: 1024k. *)
+
+ mutable allocation_policy : int;
+ (** The policy used for allocating in the heap. Possible
+ values are 0 and 1. 0 is the next-fit policy, which is
+ quite fast but can result in fragmentation. 1 is the
+ first-fit policy, which can be slower in some cases but
+ can be better for programs with fragmentation problems.
+ Default: 0. @since 3.11.0 *)
+}
+(** The GC parameters are given as a [control] record. Note that
+ these parameters can also be initialised by setting the
+ OCAMLRUNPARAM environment variable. See the documentation of
+ [ocamlrun]. *)
+
+external stat : unit -> stat = "caml_gc_stat"
+(** Return the current values of the memory management counters in a
+ [stat] record. This function examines every heap block to get the
+ statistics. *)
+
+external quick_stat : unit -> stat = "caml_gc_quick_stat"
+(** Same as [stat] except that [live_words], [live_blocks], [free_words],
+ [free_blocks], [largest_free], and [fragments] are set to 0. This
+ function is much faster than [stat] because it does not need to go
+ through the heap. *)
+
+external counters : unit -> float * float * float = "caml_gc_counters"
+(** Return [(minor_words, promoted_words, major_words)]. This function
+ is as fast as [quick_stat]. *)
+
+external get : unit -> control = "caml_gc_get"
+(** Return the current values of the GC parameters in a [control] record. *)
+
+external set : control -> unit = "caml_gc_set"
+(** [set r] changes the GC parameters according to the [control] record [r].
+ The normal usage is: [Gc.set { (Gc.get()) with Gc.verbose = 0x00d }] *)
+
+external minor : unit -> unit = "caml_gc_minor"
+(** Trigger a minor collection. *)
+
+external major_slice : int -> int = "caml_gc_major_slice";;
+(** Do a minor collection and a slice of major collection. The argument
+ is the size of the slice, 0 to use the automatically-computed
+ slice size. In all cases, the result is the computed slice size. *)
+
+external major : unit -> unit = "caml_gc_major"
+(** Do a minor collection and finish the current major collection cycle. *)
+
+external full_major : unit -> unit = "caml_gc_full_major"
+(** Do a minor collection, finish the current major collection cycle,
+ and perform a complete new cycle. This will collect all currently
+ unreachable blocks. *)
+
+external compact : unit -> unit = "caml_gc_compaction"
+(** Perform a full major collection and compact the heap. Note that heap
+ compaction is a lengthy operation. *)
+
+val print_stat : out_channel -> unit
+(** Print the current values of the memory management counters (in
+ human-readable form) into the channel argument. *)
+
+val allocated_bytes : unit -> float
+(** Return the total number of bytes allocated since the program was
+ started. It is returned as a [float] to avoid overflow problems
+ with [int] on 32-bit machines. *)
+
+val finalise : ('a -> unit) -> 'a -> unit
+(** [finalise f v] registers [f] as a finalisation function for [v].
+ [v] must be heap-allocated. [f] will be called with [v] as
+ argument at some point between the first time [v] becomes unreachable
+ (including through weak pointers) and the time [v] is collected by
+ the GC. Several functions can
+ be registered for the same value, or even several instances of the
+ same function. Each instance will be called once (or never,
+ if the program terminates before [v] becomes unreachable).
+
+ The GC will call the finalisation functions in the order of
+ deallocation. When several values become unreachable at the
+ same time (i.e. during the same GC cycle), the finalisation
+ functions will be called in the reverse order of the corresponding
+ calls to [finalise]. If [finalise] is called in the same order
+ as the values are allocated, that means each value is finalised
+ before the values it depends upon. Of course, this becomes
+ false if additional dependencies are introduced by assignments.
+
+ In the presence of multiple OCaml threads it should be assumed that
+ any particular finaliser may be executed in any of the threads.
+
+ Anything reachable from the closure of finalisation functions
+ is considered reachable, so the following code will not work
+ as expected:
+ - [ let v = ... in Gc.finalise (fun _ -> ...v...) v ]
+
+ Instead you should make sure that [v] is not in the closure of
+ the finalisation function by writing:
+ - [ let f = fun x -> ... ;; let v = ... in Gc.finalise f v ]
+
+
+ The [f] function can use all features of OCaml, including
+ assignments that make the value reachable again. It can also
+ loop forever (in this case, the other
+ finalisation functions will not be called during the execution of f,
+ unless it calls [finalise_release]).
+ It can call [finalise] on [v] or other values to register other
+ functions or even itself. It can raise an exception; in this case
+ the exception will interrupt whatever the program was doing when
+ the function was called.
+
+
+ [finalise] will raise [Invalid_argument] if [v] is not
+ guaranteed to be heap-allocated. Some examples of values that are not
+ heap-allocated are integers, constant constructors, booleans,
+ the empty array, the empty list, the unit value. The exact list
+ of what is heap-allocated or not is implementation-dependent.
+ Some constant values can be heap-allocated but never deallocated
+ during the lifetime of the program, for example a list of integer
+ constants; this is also implementation-dependent.
+ Note that values of types [float] and ['a lazy] (for any ['a]) are
+ sometimes allocated and sometimes not, so finalising them is unsafe,
+ and [finalise] will also raise [Invalid_argument] for them.
+
+
+ The results of calling {!String.make}, {!Bytes.make}, {!Bytes.create},
+ {!Array.make}, and {!Pervasives.ref} are guaranteed to be
+ heap-allocated and non-constant except when the length argument is [0].
+*)
+
+val finalise_release : unit -> unit;;
+(** A finalisation function may call [finalise_release] to tell the
+ GC that it can launch the next finalisation function without waiting
+ for the current one to return. *)
+
+type alarm
+(** An alarm is a piece of data that calls a user function at the end of
+ each major GC cycle. The following functions are provided to create
+ and delete alarms. *)
+
+val create_alarm : (unit -> unit) -> alarm
+(** [create_alarm f] will arrange for [f] to be called at the end of each
+ major GC cycle, starting with the current cycle or the next one.
+ A value of type [alarm] is returned that you can
+ use to call [delete_alarm]. *)
+
+val delete_alarm : alarm -> unit
+(** [delete_alarm a] will stop the calls to the function associated
+ to [a]. Calling [delete_alarm a] again has no effect. *)
diff --git a/stdlib/genlex.ml b/stdlib/genlex.ml
new file mode 100644
index 0000000000..4f52b18654
--- /dev/null
+++ b/stdlib/genlex.ml
@@ -0,0 +1,199 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type token =
+ Kwd of string
+ | Ident of string
+ | Int of int
+ | Float of float
+ | String of string
+ | Char of char
+
+(* The string buffering machinery *)
+
+let initial_buffer = Bytes.create 32
+
+let buffer = ref initial_buffer
+let bufpos = ref 0
+
+let reset_buffer () = buffer := initial_buffer; bufpos := 0
+
+let store c =
+ if !bufpos >= Bytes.length !buffer then begin
+ let newbuffer = Bytes.create (2 * !bufpos) in
+ Bytes.blit !buffer 0 newbuffer 0 !bufpos;
+ buffer := newbuffer
+ end;
+ Bytes.set !buffer !bufpos c;
+ incr bufpos
+
+let get_string () =
+ let s = Bytes.sub_string !buffer 0 !bufpos in buffer := initial_buffer; s
+
+(* The lexer *)
+
+let make_lexer keywords =
+ let kwd_table = Hashtbl.create 17 in
+ List.iter (fun s -> Hashtbl.add kwd_table s (Kwd s)) keywords;
+ let ident_or_keyword id =
+ try Hashtbl.find kwd_table id with
+ Not_found -> Ident id
+ and keyword_or_error c =
+ let s = String.make 1 c in
+ try Hashtbl.find kwd_table s with
+ Not_found -> raise (Stream.Error ("Illegal character " ^ s))
+ in
+ let rec next_token (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some (' ' | '\010' | '\013' | '\009' | '\026' | '\012') ->
+ Stream.junk strm__; next_token strm__
+ | Some ('A'..'Z' | 'a'..'z' | '_' | '\192'..'\255' as c) ->
+ Stream.junk strm__;
+ let s = strm__ in reset_buffer (); store c; ident s
+ | Some
+ ('!' | '%' | '&' | '$' | '#' | '+' | '/' | ':' | '<' | '=' | '>' |
+ '?' | '@' | '\\' | '~' | '^' | '|' | '*' as c) ->
+ Stream.junk strm__;
+ let s = strm__ in reset_buffer (); store c; ident2 s
+ | Some ('0'..'9' as c) ->
+ Stream.junk strm__;
+ let s = strm__ in reset_buffer (); store c; number s
+ | Some '\'' ->
+ Stream.junk strm__;
+ let c =
+ try char strm__ with
+ Stream.Failure -> raise (Stream.Error "")
+ in
+ begin match Stream.peek strm__ with
+ Some '\'' -> Stream.junk strm__; Some (Char c)
+ | _ -> raise (Stream.Error "")
+ end
+ | Some '\"' ->
+ Stream.junk strm__;
+ let s = strm__ in reset_buffer (); Some (String (string s))
+ | Some '-' -> Stream.junk strm__; neg_number strm__
+ | Some '(' -> Stream.junk strm__; maybe_comment strm__
+ | Some c -> Stream.junk strm__; Some (keyword_or_error c)
+ | _ -> None
+ and ident (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some
+ ('A'..'Z' | 'a'..'z' | '\192'..'\255' | '0'..'9' | '_' | '\'' as c) ->
+ Stream.junk strm__; let s = strm__ in store c; ident s
+ | _ -> Some (ident_or_keyword (get_string ()))
+ and ident2 (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some
+ ('!' | '%' | '&' | '$' | '#' | '+' | '-' | '/' | ':' | '<' | '=' |
+ '>' | '?' | '@' | '\\' | '~' | '^' | '|' | '*' as c) ->
+ Stream.junk strm__; let s = strm__ in store c; ident2 s
+ | _ -> Some (ident_or_keyword (get_string ()))
+ and neg_number (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some ('0'..'9' as c) ->
+ Stream.junk strm__;
+ let s = strm__ in reset_buffer (); store '-'; store c; number s
+ | _ -> let s = strm__ in reset_buffer (); store '-'; ident2 s
+ and number (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some ('0'..'9' as c) ->
+ Stream.junk strm__; let s = strm__ in store c; number s
+ | Some '.' ->
+ Stream.junk strm__; let s = strm__ in store '.'; decimal_part s
+ | Some ('e' | 'E') ->
+ Stream.junk strm__; let s = strm__ in store 'E'; exponent_part s
+ | _ -> Some (Int (int_of_string (get_string ())))
+ and decimal_part (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some ('0'..'9' as c) ->
+ Stream.junk strm__; let s = strm__ in store c; decimal_part s
+ | Some ('e' | 'E') ->
+ Stream.junk strm__; let s = strm__ in store 'E'; exponent_part s
+ | _ -> Some (Float (float_of_string (get_string ())))
+ and exponent_part (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some ('+' | '-' as c) ->
+ Stream.junk strm__; let s = strm__ in store c; end_exponent_part s
+ | _ -> end_exponent_part strm__
+ and end_exponent_part (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some ('0'..'9' as c) ->
+ Stream.junk strm__; let s = strm__ in store c; end_exponent_part s
+ | _ -> Some (Float (float_of_string (get_string ())))
+ and string (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some '\"' -> Stream.junk strm__; get_string ()
+ | Some '\\' ->
+ Stream.junk strm__;
+ let c =
+ try escape strm__ with
+ Stream.Failure -> raise (Stream.Error "")
+ in
+ let s = strm__ in store c; string s
+ | Some c -> Stream.junk strm__; let s = strm__ in store c; string s
+ | _ -> raise Stream.Failure
+ and char (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some '\\' ->
+ Stream.junk strm__;
+ begin try escape strm__ with
+ Stream.Failure -> raise (Stream.Error "")
+ end
+ | Some c -> Stream.junk strm__; c
+ | _ -> raise Stream.Failure
+ and escape (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some 'n' -> Stream.junk strm__; '\n'
+ | Some 'r' -> Stream.junk strm__; '\r'
+ | Some 't' -> Stream.junk strm__; '\t'
+ | Some ('0'..'9' as c1) ->
+ Stream.junk strm__;
+ begin match Stream.peek strm__ with
+ Some ('0'..'9' as c2) ->
+ Stream.junk strm__;
+ begin match Stream.peek strm__ with
+ Some ('0'..'9' as c3) ->
+ Stream.junk strm__;
+ Char.chr
+ ((Char.code c1 - 48) * 100 + (Char.code c2 - 48) * 10 +
+ (Char.code c3 - 48))
+ | _ -> raise (Stream.Error "")
+ end
+ | _ -> raise (Stream.Error "")
+ end
+ | Some c -> Stream.junk strm__; c
+ | _ -> raise Stream.Failure
+ and maybe_comment (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some '*' ->
+ Stream.junk strm__; let s = strm__ in comment s; next_token s
+ | _ -> Some (keyword_or_error '(')
+ and comment (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some '(' -> Stream.junk strm__; maybe_nested_comment strm__
+ | Some '*' -> Stream.junk strm__; maybe_end_comment strm__
+ | Some c -> Stream.junk strm__; comment strm__
+ | _ -> raise Stream.Failure
+ and maybe_nested_comment (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some '*' -> Stream.junk strm__; let s = strm__ in comment s; comment s
+ | Some c -> Stream.junk strm__; comment strm__
+ | _ -> raise Stream.Failure
+ and maybe_end_comment (strm__ : _ Stream.t) =
+ match Stream.peek strm__ with
+ Some ')' -> Stream.junk strm__; ()
+ | Some '*' -> Stream.junk strm__; maybe_end_comment strm__
+ | Some c -> Stream.junk strm__; comment strm__
+ | _ -> raise Stream.Failure
+ in
+ fun input -> Stream.from (fun count -> next_token input)
diff --git a/stdlib/genlex.mli b/stdlib/genlex.mli
new file mode 100644
index 0000000000..7858cbdcc7
--- /dev/null
+++ b/stdlib/genlex.mli
@@ -0,0 +1,71 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** A generic lexical analyzer.
+
+
+ This module implements a simple 'standard' lexical analyzer, presented
+ as a function from character streams to token streams. It implements
+ roughly the lexical conventions of OCaml, but is parameterized by the
+ set of keywords of your language.
+
+
+ Example: a lexer suitable for a desk calculator is obtained by
+ {[ let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"] ]}
+
+ The associated parser would be a function from [token stream]
+ to, for instance, [int], and would have rules such as:
+
+ {[
+ let rec parse_expr = parser
+ | [< n1 = parse_atom; n2 = parse_remainder n1 >] -> n2
+ and parse_atom = parser
+ | [< 'Int n >] -> n
+ | [< 'Kwd "("; n = parse_expr; 'Kwd ")" >] -> n
+ and parse_remainder n1 = parser
+ | [< 'Kwd "+"; n2 = parse_expr >] -> n1+n2
+ | [< >] -> n1
+ ]}
+
+ One should notice that the use of the [parser] keyword and associated
+ notation for streams are only available through camlp4 extensions. This
+ means that one has to preprocess its sources {i e. g.} by using the
+ ["-pp"] command-line switch of the compilers.
+*)
+
+(** The type of tokens. The lexical classes are: [Int] and [Float]
+ for integer and floating-point numbers; [String] for
+ string literals, enclosed in double quotes; [Char] for
+ character literals, enclosed in single quotes; [Ident] for
+ identifiers (either sequences of letters, digits, underscores
+ and quotes, or sequences of 'operator characters' such as
+ [+], [*], etc); and [Kwd] for keywords (either identifiers or
+ single 'special characters' such as [(], [}], etc). *)
+type token =
+ Kwd of string
+ | Ident of string
+ | Int of int
+ | Float of float
+ | String of string
+ | Char of char
+
+val make_lexer : string list -> char Stream.t -> token Stream.t
+(** Construct the lexer function. The first argument is the list of
+ keywords. An identifier [s] is returned as [Kwd s] if [s]
+ belongs to this list, and as [Ident s] otherwise.
+ A special character [s] is returned as [Kwd s] if [s]
+ belongs to this list, and cause a lexical error (exception
+ [Stream.Error] with the offending lexeme as its parameter) otherwise.
+ Blanks and newlines are skipped. Comments delimited by [(*] and [*)]
+ are skipped as well, and can be nested. A [Stream.Failure] exception
+ is raised if end of stream is unexpectedly reached.*)
diff --git a/stdlib/hashtbl.ml b/stdlib/hashtbl.ml
new file mode 100644
index 0000000000..dcca372a5b
--- /dev/null
+++ b/stdlib/hashtbl.ml
@@ -0,0 +1,389 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Hash tables *)
+
+external seeded_hash_param :
+ int -> int -> int -> 'a -> int = "caml_hash" "noalloc"
+external old_hash_param :
+ int -> int -> 'a -> int = "caml_hash_univ_param" "noalloc"
+
+let hash x = seeded_hash_param 10 100 0 x
+let hash_param n1 n2 x = seeded_hash_param n1 n2 0 x
+let seeded_hash seed x = seeded_hash_param 10 100 seed x
+
+(* We do dynamic hashing, and resize the table and rehash the elements
+ when buckets become too long. *)
+
+type ('a, 'b) t =
+ { mutable size: int; (* number of entries *)
+ mutable data: ('a, 'b) bucketlist array; (* the buckets *)
+ mutable seed: int; (* for randomization *)
+ initial_size: int; (* initial array size *)
+ }
+
+and ('a, 'b) bucketlist =
+ Empty
+ | Cons of 'a * 'b * ('a, 'b) bucketlist
+
+(* To pick random seeds if requested *)
+
+let randomized_default =
+ let params =
+ try Sys.getenv "OCAMLRUNPARAM" with Not_found ->
+ try Sys.getenv "CAMLRUNPARAM" with Not_found -> "" in
+ String.contains params 'R'
+
+let randomized = ref randomized_default
+
+let randomize () = randomized := true
+
+let prng = lazy (Random.State.make_self_init())
+
+(* Creating a fresh, empty table *)
+
+let rec power_2_above x n =
+ if x >= n then x
+ else if x * 2 > Sys.max_array_length then x
+ else power_2_above (x * 2) n
+
+let create ?(random = !randomized) initial_size =
+ let s = power_2_above 16 initial_size in
+ let seed = if random then Random.State.bits (Lazy.force prng) else 0 in
+ { initial_size = s; size = 0; seed = seed; data = Array.make s Empty }
+
+let clear h =
+ h.size <- 0;
+ let len = Array.length h.data in
+ for i = 0 to len - 1 do
+ h.data.(i) <- Empty
+ done
+
+let reset h =
+ let len = Array.length h.data in
+ if Obj.size (Obj.repr h) < 4 (* compatibility with old hash tables *)
+ || len = h.initial_size then
+ clear h
+ else begin
+ h.size <- 0;
+ h.data <- Array.make h.initial_size Empty
+ end
+
+let copy h = { h with data = Array.copy h.data }
+
+let length h = h.size
+
+let resize indexfun h =
+ let odata = h.data in
+ let osize = Array.length odata in
+ let nsize = osize * 2 in
+ if nsize < Sys.max_array_length then begin
+ let ndata = Array.make nsize Empty in
+ h.data <- ndata; (* so that indexfun sees the new bucket count *)
+ let rec insert_bucket = function
+ Empty -> ()
+ | Cons(key, data, rest) ->
+ insert_bucket rest; (* preserve original order of elements *)
+ let nidx = indexfun h key in
+ ndata.(nidx) <- Cons(key, data, ndata.(nidx)) in
+ for i = 0 to osize - 1 do
+ insert_bucket odata.(i)
+ done
+ end
+
+let key_index h key =
+ (* compatibility with old hash tables *)
+ if Obj.size (Obj.repr h) >= 3
+ then (seeded_hash_param 10 100 h.seed key) land (Array.length h.data - 1)
+ else (old_hash_param 10 100 key) mod (Array.length h.data)
+
+let add h key info =
+ let i = key_index h key in
+ let bucket = Cons(key, info, h.data.(i)) in
+ h.data.(i) <- bucket;
+ h.size <- h.size + 1;
+ if h.size > Array.length h.data lsl 1 then resize key_index h
+
+let remove h key =
+ let rec remove_bucket = function
+ | Empty ->
+ Empty
+ | Cons(k, i, next) ->
+ if compare k key = 0
+ then begin h.size <- h.size - 1; next end
+ else Cons(k, i, remove_bucket next) in
+ let i = key_index h key in
+ h.data.(i) <- remove_bucket h.data.(i)
+
+let rec find_rec key = function
+ | Empty ->
+ raise Not_found
+ | Cons(k, d, rest) ->
+ if compare key k = 0 then d else find_rec key rest
+
+let find h key =
+ match h.data.(key_index h key) with
+ | Empty -> raise Not_found
+ | Cons(k1, d1, rest1) ->
+ if compare key k1 = 0 then d1 else
+ match rest1 with
+ | Empty -> raise Not_found
+ | Cons(k2, d2, rest2) ->
+ if compare key k2 = 0 then d2 else
+ match rest2 with
+ | Empty -> raise Not_found
+ | Cons(k3, d3, rest3) ->
+ if compare key k3 = 0 then d3 else find_rec key rest3
+
+let find_all h key =
+ let rec find_in_bucket = function
+ | Empty ->
+ []
+ | Cons(k, d, rest) ->
+ if compare k key = 0
+ then d :: find_in_bucket rest
+ else find_in_bucket rest in
+ find_in_bucket h.data.(key_index h key)
+
+let replace h key info =
+ let rec replace_bucket = function
+ | Empty ->
+ raise Not_found
+ | Cons(k, i, next) ->
+ if compare k key = 0
+ then Cons(key, info, next)
+ else Cons(k, i, replace_bucket next) in
+ let i = key_index h key in
+ let l = h.data.(i) in
+ try
+ h.data.(i) <- replace_bucket l
+ with Not_found ->
+ h.data.(i) <- Cons(key, info, l);
+ h.size <- h.size + 1;
+ if h.size > Array.length h.data lsl 1 then resize key_index h
+
+let mem h key =
+ let rec mem_in_bucket = function
+ | Empty ->
+ false
+ | Cons(k, d, rest) ->
+ compare k key = 0 || mem_in_bucket rest in
+ mem_in_bucket h.data.(key_index h key)
+
+let iter f h =
+ let rec do_bucket = function
+ | Empty ->
+ ()
+ | Cons(k, d, rest) ->
+ f k d; do_bucket rest in
+ let d = h.data in
+ for i = 0 to Array.length d - 1 do
+ do_bucket d.(i)
+ done
+
+let fold f h init =
+ let rec do_bucket b accu =
+ match b with
+ Empty ->
+ accu
+ | Cons(k, d, rest) ->
+ do_bucket rest (f k d accu) in
+ let d = h.data in
+ let accu = ref init in
+ for i = 0 to Array.length d - 1 do
+ accu := do_bucket d.(i) !accu
+ done;
+ !accu
+
+type statistics = {
+ num_bindings: int;
+ num_buckets: int;
+ max_bucket_length: int;
+ bucket_histogram: int array
+}
+
+let rec bucket_length accu = function
+ | Empty -> accu
+ | Cons(_, _, rest) -> bucket_length (accu + 1) rest
+
+let stats h =
+ let mbl =
+ Array.fold_left (fun m b -> max m (bucket_length 0 b)) 0 h.data in
+ let histo = Array.make (mbl + 1) 0 in
+ Array.iter
+ (fun b ->
+ let l = bucket_length 0 b in
+ histo.(l) <- histo.(l) + 1)
+ h.data;
+ { num_bindings = h.size;
+ num_buckets = Array.length h.data;
+ max_bucket_length = mbl;
+ bucket_histogram = histo }
+
+(* Functorial interface *)
+
+module type HashedType =
+ sig
+ type t
+ val equal: t -> t -> bool
+ val hash: t -> int
+ end
+
+module type SeededHashedType =
+ sig
+ type t
+ val equal: t -> t -> bool
+ val hash: int -> t -> int
+ end
+
+module type S =
+ sig
+ type key
+ type 'a t
+ val create: int -> 'a t
+ val clear : 'a t -> unit
+ val reset : 'a t -> unit
+ val copy: 'a t -> 'a t
+ val add: 'a t -> key -> 'a -> unit
+ val remove: 'a t -> key -> unit
+ val find: 'a t -> key -> 'a
+ val find_all: 'a t -> key -> 'a list
+ val replace : 'a t -> key -> 'a -> unit
+ val mem : 'a t -> key -> bool
+ val iter: (key -> 'a -> unit) -> 'a t -> unit
+ val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ val length: 'a t -> int
+ val stats: 'a t -> statistics
+ end
+
+module type SeededS =
+ sig
+ type key
+ type 'a t
+ val create : ?random:bool -> int -> 'a t
+ val clear : 'a t -> unit
+ val reset : 'a t -> unit
+ val copy : 'a t -> 'a t
+ val add : 'a t -> key -> 'a -> unit
+ val remove : 'a t -> key -> unit
+ val find : 'a t -> key -> 'a
+ val find_all : 'a t -> key -> 'a list
+ val replace : 'a t -> key -> 'a -> unit
+ val mem : 'a t -> key -> bool
+ val iter : (key -> 'a -> unit) -> 'a t -> unit
+ val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ val length : 'a t -> int
+ val stats: 'a t -> statistics
+ end
+
+module MakeSeeded(H: SeededHashedType): (SeededS with type key = H.t) =
+ struct
+ type key = H.t
+ type 'a hashtbl = (key, 'a) t
+ type 'a t = 'a hashtbl
+ let create = create
+ let clear = clear
+ let reset = reset
+ let copy = copy
+
+ let key_index h key =
+ (H.hash h.seed key) land (Array.length h.data - 1)
+
+ let add h key info =
+ let i = key_index h key in
+ let bucket = Cons(key, info, h.data.(i)) in
+ h.data.(i) <- bucket;
+ h.size <- h.size + 1;
+ if h.size > Array.length h.data lsl 1 then resize key_index h
+
+ let remove h key =
+ let rec remove_bucket = function
+ | Empty ->
+ Empty
+ | Cons(k, i, next) ->
+ if H.equal k key
+ then begin h.size <- h.size - 1; next end
+ else Cons(k, i, remove_bucket next) in
+ let i = key_index h key in
+ h.data.(i) <- remove_bucket h.data.(i)
+
+ let rec find_rec key = function
+ | Empty ->
+ raise Not_found
+ | Cons(k, d, rest) ->
+ if H.equal key k then d else find_rec key rest
+
+ let find h key =
+ match h.data.(key_index h key) with
+ | Empty -> raise Not_found
+ | Cons(k1, d1, rest1) ->
+ if H.equal key k1 then d1 else
+ match rest1 with
+ | Empty -> raise Not_found
+ | Cons(k2, d2, rest2) ->
+ if H.equal key k2 then d2 else
+ match rest2 with
+ | Empty -> raise Not_found
+ | Cons(k3, d3, rest3) ->
+ if H.equal key k3 then d3 else find_rec key rest3
+
+ let find_all h key =
+ let rec find_in_bucket = function
+ | Empty ->
+ []
+ | Cons(k, d, rest) ->
+ if H.equal k key
+ then d :: find_in_bucket rest
+ else find_in_bucket rest in
+ find_in_bucket h.data.(key_index h key)
+
+ let replace h key info =
+ let rec replace_bucket = function
+ | Empty ->
+ raise Not_found
+ | Cons(k, i, next) ->
+ if H.equal k key
+ then Cons(key, info, next)
+ else Cons(k, i, replace_bucket next) in
+ let i = key_index h key in
+ let l = h.data.(i) in
+ try
+ h.data.(i) <- replace_bucket l
+ with Not_found ->
+ h.data.(i) <- Cons(key, info, l);
+ h.size <- h.size + 1;
+ if h.size > Array.length h.data lsl 1 then resize key_index h
+
+ let mem h key =
+ let rec mem_in_bucket = function
+ | Empty ->
+ false
+ | Cons(k, d, rest) ->
+ H.equal k key || mem_in_bucket rest in
+ mem_in_bucket h.data.(key_index h key)
+
+ let iter = iter
+ let fold = fold
+ let length = length
+ let stats = stats
+ end
+
+module Make(H: HashedType): (S with type key = H.t) =
+ struct
+ include MakeSeeded(struct
+ type t = H.t
+ let equal = H.equal
+ let hash (seed: int) x = H.hash x
+ end)
+ let create sz = create ~random:false sz
+ end
diff --git a/stdlib/hashtbl.mli b/stdlib/hashtbl.mli
new file mode 100644
index 0000000000..386f5a6cc9
--- /dev/null
+++ b/stdlib/hashtbl.mli
@@ -0,0 +1,364 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Hash tables and hash functions.
+
+ Hash tables are hashed association tables, with in-place modification.
+*)
+
+
+(** {6 Generic interface} *)
+
+
+type ('a, 'b) t
+(** The type of hash tables from type ['a] to type ['b]. *)
+
+val create : ?random:bool -> int -> ('a, 'b) t
+(** [Hashtbl.create n] creates a new, empty hash table, with
+ initial size [n]. For best results, [n] should be on the
+ order of the expected number of elements that will be in
+ the table. The table grows as needed, so [n] is just an
+ initial guess.
+
+ The optional [random] parameter (a boolean) controls whether
+ the internal organization of the hash table is randomized at each
+ execution of [Hashtbl.create] or deterministic over all executions.
+
+ A hash table that is created with [~random:false] uses a
+ fixed hash function ({!Hashtbl.hash}) to distribute keys among
+ buckets. As a consequence, collisions between keys happen
+ deterministically. In Web-facing applications or other
+ security-sensitive applications, the deterministic collision
+ patterns can be exploited by a malicious user to create a
+ denial-of-service attack: the attacker sends input crafted to
+ create many collisions in the table, slowing the application down.
+
+ A hash table that is created with [~random:true] uses the seeded
+ hash function {!Hashtbl.seeded_hash} with a seed that is randomly
+ chosen at hash table creation time. In effect, the hash function
+ used is randomly selected among [2^{30}] different hash functions.
+ All these hash functions have different collision patterns,
+ rendering ineffective the denial-of-service attack described above.
+ However, because of randomization, enumerating all elements of the
+ hash table using {!Hashtbl.fold} or {!Hashtbl.iter} is no longer
+ deterministic: elements are enumerated in different orders at
+ different runs of the program.
+
+ If no [~random] parameter is given, hash tables are created
+ in non-random mode by default. This default can be changed
+ either programmatically by calling {!Hashtbl.randomize} or by
+ setting the [R] flag in the [OCAMLRUNPARAM] environment variable.
+
+ @before 4.00.0 the [random] parameter was not present and all
+ hash tables were created in non-randomized mode. *)
+
+val clear : ('a, 'b) t -> unit
+(** Empty a hash table. Use [reset] instead of [clear] to shrink the
+ size of the bucket table to its initial size. *)
+
+val reset : ('a, 'b) t -> unit
+(** Empty a hash table and shrink the size of the bucket table
+ to its initial size.
+ @since 4.00.0 *)
+
+val copy : ('a, 'b) t -> ('a, 'b) t
+(** Return a copy of the given hashtable. *)
+
+val add : ('a, 'b) t -> 'a -> 'b -> unit
+(** [Hashtbl.add tbl x y] adds a binding of [x] to [y] in table [tbl].
+ Previous bindings for [x] are not removed, but simply
+ hidden. That is, after performing {!Hashtbl.remove}[ tbl x],
+ the previous binding for [x], if any, is restored.
+ (Same behavior as with association lists.) *)
+
+val find : ('a, 'b) t -> 'a -> 'b
+(** [Hashtbl.find tbl x] returns the current binding of [x] in [tbl],
+ or raises [Not_found] if no such binding exists. *)
+
+val find_all : ('a, 'b) t -> 'a -> 'b list
+(** [Hashtbl.find_all tbl x] returns the list of all data
+ associated with [x] in [tbl].
+ The current binding is returned first, then the previous
+ bindings, in reverse order of introduction in the table. *)
+
+val mem : ('a, 'b) t -> 'a -> bool
+(** [Hashtbl.mem tbl x] checks if [x] is bound in [tbl]. *)
+
+val remove : ('a, 'b) t -> 'a -> unit
+(** [Hashtbl.remove tbl x] removes the current binding of [x] in [tbl],
+ restoring the previous binding if it exists.
+ It does nothing if [x] is not bound in [tbl]. *)
+
+val replace : ('a, 'b) t -> 'a -> 'b -> unit
+(** [Hashtbl.replace tbl x y] replaces the current binding of [x]
+ in [tbl] by a binding of [x] to [y]. If [x] is unbound in [tbl],
+ a binding of [x] to [y] is added to [tbl].
+ This is functionally equivalent to {!Hashtbl.remove}[ tbl x]
+ followed by {!Hashtbl.add}[ tbl x y]. *)
+
+val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
+(** [Hashtbl.iter f tbl] applies [f] to all bindings in table [tbl].
+ [f] receives the key as first argument, and the associated value
+ as second argument. Each binding is presented exactly once to [f].
+
+ The order in which the bindings are passed to [f] is unspecified.
+ However, if the table contains several bindings for the same key,
+ they are passed to [f] in reverse order of introduction, that is,
+ the most recent binding is passed first.
+
+ If the hash table was created in non-randomized mode, the order
+ in which the bindings are enumerated is reproducible between
+ successive runs of the program, and even between minor versions
+ of OCaml. For randomized hash tables, the order of enumeration
+ is entirely random. *)
+
+val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
+(** [Hashtbl.fold f tbl init] computes
+ [(f kN dN ... (f k1 d1 init)...)],
+ where [k1 ... kN] are the keys of all bindings in [tbl],
+ and [d1 ... dN] are the associated values.
+ Each binding is presented exactly once to [f].
+
+ The order in which the bindings are passed to [f] is unspecified.
+ However, if the table contains several bindings for the same key,
+ they are passed to [f] in reverse order of introduction, that is,
+ the most recent binding is passed first.
+
+ If the hash table was created in non-randomized mode, the order
+ in which the bindings are enumerated is reproducible between
+ successive runs of the program, and even between minor versions
+ of OCaml. For randomized hash tables, the order of enumeration
+ is entirely random. *)
+
+val length : ('a, 'b) t -> int
+(** [Hashtbl.length tbl] returns the number of bindings in [tbl].
+ It takes constant time. Multiple bindings are counted once each, so
+ [Hashtbl.length] gives the number of times [Hashtbl.iter] calls its
+ first argument. *)
+
+val randomize : unit -> unit
+(** After a call to [Hashtbl.randomize()], hash tables are created in
+ randomized mode by default: {!Hashtbl.create} returns randomized
+ hash tables, unless the [~random:false] optional parameter is given.
+ The same effect can be achieved by setting the [R] parameter in
+ the [OCAMLRUNPARAM] environment variable.
+
+ It is recommended that applications or Web frameworks that need to
+ protect themselves against the denial-of-service attack described
+ in {!Hashtbl.create} call [Hashtbl.randomize()] at initialization
+ time.
+
+ Note that once [Hashtbl.randomize()] was called, there is no way
+ to revert to the non-randomized default behavior of {!Hashtbl.create}.
+ This is intentional. Non-randomized hash tables can still be
+ created using [Hashtbl.create ~random:false].
+
+ @since 4.00.0 *)
+
+type statistics = {
+ num_bindings: int;
+ (** Number of bindings present in the table.
+ Same value as returned by {!Hashtbl.length}. *)
+ num_buckets: int;
+ (** Number of buckets in the table. *)
+ max_bucket_length: int;
+ (** Maximal number of bindings per bucket. *)
+ bucket_histogram: int array
+ (** Histogram of bucket sizes. This array [histo] has
+ length [max_bucket_length + 1]. The value of
+ [histo.(i)] is the number of buckets whose size is [i]. *)
+}
+
+val stats : ('a, 'b) t -> statistics
+(** [Hashtbl.stats tbl] returns statistics about the table [tbl]:
+ number of buckets, size of the biggest bucket, distribution of
+ buckets by size.
+ @since 4.00.0 *)
+
+(** {6 Functorial interface} *)
+
+(** The functorial interface allows the use of specific comparison
+ and hash functions, either for performance/security concerns,
+ or because keys are not hashable/comparable with the polymorphic builtins.
+
+ For instance, one might want to specialize a table for integer keys:
+ {[
+ module IntHash =
+ struct
+ type t = int
+ let equal i j = i=j
+ let hash i = i land max_int
+ end
+
+ module IntHashtbl = Hashtbl.Make(IntHash)
+
+ let h = IntHashtbl.create 17 in
+ IntHashtbl.add h 12 "hello";;
+ ]}
+
+ This creates a new module [IntHashtbl], with a new type ['a
+ IntHashtbl.t] of tables from [int] to ['a]. In this example, [h]
+ contains [string] values so its type is [string IntHashtbl.t].
+
+ Note that the new type ['a IntHashtbl.t] is not compatible with
+ the type [('a,'b) Hashtbl.t] of the generic interface. For
+ example, [Hashtbl.length h] would not type-check, you must use
+ [IntHashtbl.length].
+*)
+
+module type HashedType =
+ sig
+ type t
+ (** The type of the hashtable keys. *)
+ val equal : t -> t -> bool
+ (** The equality predicate used to compare keys. *)
+ val hash : t -> int
+ (** A hashing function on keys. It must be such that if two keys are
+ equal according to [equal], then they have identical hash values
+ as computed by [hash].
+ Examples: suitable ([equal], [hash]) pairs for arbitrary key
+ types include
+- ([(=)], {!Hashtbl.hash}) for comparing objects by structure
+ (provided objects do not contain floats)
+- ([(fun x y -> compare x y = 0)], {!Hashtbl.hash})
+ for comparing objects by structure
+ and handling {!Pervasives.nan} correctly
+- ([(==)], {!Hashtbl.hash}) for comparing objects by physical
+ equality (e.g. for mutable or cyclic objects). *)
+ end
+(** The input signature of the functor {!Hashtbl.Make}. *)
+
+module type S =
+ sig
+ type key
+ type 'a t
+ val create : int -> 'a t
+ val clear : 'a t -> unit
+ val reset : 'a t -> unit
+ val copy : 'a t -> 'a t
+ val add : 'a t -> key -> 'a -> unit
+ val remove : 'a t -> key -> unit
+ val find : 'a t -> key -> 'a
+ val find_all : 'a t -> key -> 'a list
+ val replace : 'a t -> key -> 'a -> unit
+ val mem : 'a t -> key -> bool
+ val iter : (key -> 'a -> unit) -> 'a t -> unit
+ val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ val length : 'a t -> int
+ val stats: 'a t -> statistics
+ end
+(** The output signature of the functor {!Hashtbl.Make}. *)
+
+module Make (H : HashedType) : S with type key = H.t
+(** Functor building an implementation of the hashtable structure.
+ The functor [Hashtbl.Make] returns a structure containing
+ a type [key] of keys and a type ['a t] of hash tables
+ associating data of type ['a] to keys of type [key].
+ The operations perform similarly to those of the generic
+ interface, but use the hashing and equality functions
+ specified in the functor argument [H] instead of generic
+ equality and hashing. Since the hash function is not seeded,
+ the [create] operation of the result structure always returns
+ non-randomized hash tables. *)
+
+module type SeededHashedType =
+ sig
+ type t
+ (** The type of the hashtable keys. *)
+ val equal: t -> t -> bool
+ (** The equality predicate used to compare keys. *)
+ val hash: int -> t -> int
+ (** A seeded hashing function on keys. The first argument is
+ the seed. It must be the case that if [equal x y] is true,
+ then [hash seed x = hash seed y] for any value of [seed].
+ A suitable choice for [hash] is the function {!Hashtbl.seeded_hash}
+ below. *)
+ end
+(** The input signature of the functor {!Hashtbl.MakeSeeded}.
+ @since 4.00.0 *)
+
+module type SeededS =
+ sig
+ type key
+ type 'a t
+ val create : ?random:bool -> int -> 'a t
+ val clear : 'a t -> unit
+ val reset : 'a t -> unit
+ val copy : 'a t -> 'a t
+ val add : 'a t -> key -> 'a -> unit
+ val remove : 'a t -> key -> unit
+ val find : 'a t -> key -> 'a
+ val find_all : 'a t -> key -> 'a list
+ val replace : 'a t -> key -> 'a -> unit
+ val mem : 'a t -> key -> bool
+ val iter : (key -> 'a -> unit) -> 'a t -> unit
+ val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ val length : 'a t -> int
+ val stats: 'a t -> statistics
+ end
+(** The output signature of the functor {!Hashtbl.MakeSeeded}.
+ @since 4.00.0 *)
+
+module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t
+(** Functor building an implementation of the hashtable structure.
+ The functor [Hashtbl.MakeSeeded] returns a structure containing
+ a type [key] of keys and a type ['a t] of hash tables
+ associating data of type ['a] to keys of type [key].
+ The operations perform similarly to those of the generic
+ interface, but use the seeded hashing and equality functions
+ specified in the functor argument [H] instead of generic
+ equality and hashing. The [create] operation of the
+ result structure supports the [~random] optional parameter
+ and returns randomized hash tables if [~random:true] is passed
+ or if randomization is globally on (see {!Hashtbl.randomize}).
+ @since 4.00.0 *)
+
+
+(** {6 The polymorphic hash functions} *)
+
+
+val hash : 'a -> int
+(** [Hashtbl.hash x] associates a nonnegative integer to any value of
+ any type. It is guaranteed that
+ if [x = y] or [Pervasives.compare x y = 0], then [hash x = hash y].
+ Moreover, [hash] always terminates, even on cyclic structures. *)
+
+val seeded_hash : int -> 'a -> int
+(** A variant of {!Hashtbl.hash} that is further parameterized by
+ an integer seed.
+ @since 4.00.0 *)
+
+val hash_param : int -> int -> 'a -> int
+(** [Hashtbl.hash_param meaningful total x] computes a hash value for [x],
+ with the same properties as for [hash]. The two extra integer
+ parameters [meaningful] and [total] give more precise control over
+ hashing. Hashing performs a breadth-first, left-to-right traversal
+ of the structure [x], stopping after [meaningful] meaningful nodes
+ were encountered, or [total] nodes (meaningful or not) were
+ encountered. If [total] as specified by the user exceeds a certain
+ value, currently 256, then it is capped to that value.
+ Meaningful nodes are: integers; floating-point
+ numbers; strings; characters; booleans; and constant
+ constructors. Larger values of [meaningful] and [total] means that
+ more nodes are taken into account to compute the final hash value,
+ and therefore collisions are less likely to happen. However,
+ hashing takes longer. The parameters [meaningful] and [total]
+ govern the tradeoff between accuracy and speed. As default
+ choices, {!Hashtbl.hash} and {!Hashtbl.seeded_hash} take
+ [meaningful = 10] and [total = 100]. *)
+
+val seeded_hash_param : int -> int -> int -> 'a -> int
+(** A variant of {!Hashtbl.hash_param} that is further parameterized by
+ an integer seed. Usage:
+ [Hashtbl.seeded_hash_param meaningful total seed x].
+ @since 4.00.0 *)
diff --git a/stdlib/header.c b/stdlib/header.c
new file mode 100644
index 0000000000..6f3dc5496a
--- /dev/null
+++ b/stdlib/header.c
@@ -0,0 +1,189 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1998 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* The launcher for bytecode executables (if #! is not working) */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../config/s.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include "../byterun/caml/mlvalues.h"
+#include "../byterun/caml/exec.h"
+
+char * default_runtime_path = RUNTIME_NAME;
+
+#ifndef MAXPATHLEN
+#define MAXPATHLEN 1024
+#endif
+
+#ifndef S_ISREG
+#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
+#endif
+
+#ifndef SEEK_END
+#define SEEK_END 2
+#endif
+
+#ifndef __CYGWIN__
+
+/* Normal Unix search path function */
+
+static char * searchpath(char * name)
+{
+ static char fullname[MAXPATHLEN + 1];
+ char * path;
+ char * p;
+ char * q;
+ struct stat st;
+
+ for (p = name; *p != 0; p++) {
+ if (*p == '/') return name;
+ }
+ path = getenv("PATH");
+ if (path == NULL) return name;
+ while(1) {
+ for (p = fullname; *path != 0 && *path != ':'; p++, path++)
+ if (p < fullname + MAXPATHLEN) *p = *path;
+ if (p != fullname && p < fullname + MAXPATHLEN)
+ *p++ = '/';
+ for (q = name; *q != 0; p++, q++)
+ if (p < fullname + MAXPATHLEN) *p = *q;
+ *p = 0;
+ if (stat(fullname, &st) == 0 && S_ISREG(st.st_mode)) break;
+ if (*path == 0) return name;
+ path++;
+ }
+ return fullname;
+}
+
+#else
+
+/* Special version for Cygwin32: takes care of the ".exe" implicit suffix */
+
+static int file_ok(char * name)
+{
+ int fd;
+ /* Cannot use stat() here because it adds ".exe" implicitly */
+ fd = open(name, O_RDONLY);
+ if (fd == -1) return 0;
+ close(fd);
+ return 1;
+}
+
+static char * searchpath(char * name)
+{
+ char * path, * fullname, * p;
+
+ path = getenv("PATH");
+ fullname = malloc(strlen(name) + (path == NULL ? 0 : strlen(path)) + 6);
+ /* 6 = "/" plus ".exe" plus final "\0" */
+ if (fullname == NULL) return name;
+ /* Check for absolute path name */
+ for (p = name; *p != 0; p++) {
+ if (*p == '/' || *p == '\\') {
+ if (file_ok(name)) return name;
+ strcpy(fullname, name);
+ strcat(fullname, ".exe");
+ if (file_ok(fullname)) return fullname;
+ return name;
+ }
+ }
+ /* Search in path */
+ if (path == NULL) return name;
+ while(1) {
+ for (p = fullname; *path != 0 && *path != ':'; p++, path++) *p = *path;
+ if (p != fullname) *p++ = '/';
+ strcpy(p, name);
+ if (file_ok(fullname)) return fullname;
+ strcat(fullname, ".exe");
+ if (file_ok(fullname)) return fullname;
+ if (*path == 0) break;
+ path++;
+ }
+ return name;
+}
+
+#endif
+
+static unsigned long read_size(char * ptr)
+{
+ unsigned char * p = (unsigned char *) ptr;
+ return ((unsigned long) p[0] << 24) + ((unsigned long) p[1] << 16) +
+ ((unsigned long) p[2] << 8) + p[3];
+}
+
+static char * read_runtime_path(int fd)
+{
+ char buffer[TRAILER_SIZE];
+ static char runtime_path[MAXPATHLEN];
+ int num_sections, i;
+ uint32_t path_size;
+ long ofs;
+
+ lseek(fd, (long) -TRAILER_SIZE, SEEK_END);
+ if (read(fd, buffer, TRAILER_SIZE) < TRAILER_SIZE) return NULL;
+ num_sections = read_size(buffer);
+ ofs = TRAILER_SIZE + num_sections * 8;
+ lseek(fd, -ofs, SEEK_END);
+ path_size = 0;
+ for (i = 0; i < num_sections; i++) {
+ if (read(fd, buffer, 8) < 8) return NULL;
+ if (buffer[0] == 'R' && buffer[1] == 'N' &&
+ buffer[2] == 'T' && buffer[3] == 'M') {
+ path_size = read_size(buffer + 4);
+ ofs += path_size;
+ } else if (path_size > 0)
+ ofs += read_size(buffer + 4);
+ }
+ if (path_size == 0) return default_runtime_path;
+ if (path_size >= MAXPATHLEN) return NULL;
+ lseek(fd, -ofs, SEEK_END);
+ if (read(fd, runtime_path, path_size) != path_size) return NULL;
+ runtime_path[path_size - 1] = 0;
+ return runtime_path;
+}
+
+static void errwrite(char * msg)
+{
+ write(2, msg, strlen(msg));
+}
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+int main(int argc, char ** argv)
+{
+ char * truename, * runtime_path;
+ int fd;
+
+ truename = searchpath(argv[0]);
+ fd = open(truename, O_RDONLY | O_BINARY);
+ if (fd == -1 || (runtime_path = read_runtime_path(fd)) == NULL) {
+ errwrite(truename);
+ errwrite(" not found or is not a bytecode executable file\n");
+ return 2;
+ }
+ argv[0] = truename;
+ execv(runtime_path, argv);
+ errwrite("Cannot exec ");
+ errwrite(runtime_path);
+ errwrite("\n");
+ return 2;
+}
diff --git a/stdlib/headernt.c b/stdlib/headernt.c
new file mode 100644
index 0000000000..e95223dbc1
--- /dev/null
+++ b/stdlib/headernt.c
@@ -0,0 +1,174 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1998 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#define STRICT
+#define WIN32_LEAN_AND_MEAN
+
+#include <windows.h>
+#include "caml/mlvalues.h"
+#include "caml/exec.h"
+
+#ifndef __MINGW32__
+#pragma comment(linker , "/entry:headerentry")
+#pragma comment(linker , "/subsystem:console")
+#pragma comment(lib , "kernel32")
+#endif
+
+char * default_runtime_name = RUNTIME_NAME;
+
+static
+#if _MSC_VER >= 1200
+__forceinline
+#else
+__inline
+#endif
+unsigned long read_size(const char * const ptr)
+{
+ const unsigned char * const p = (const unsigned char * const) ptr;
+ return ((unsigned long) p[0] << 24) | ((unsigned long) p[1] << 16) |
+ ((unsigned long) p[2] << 8) | p[3];
+}
+
+static __inline char * read_runtime_path(HANDLE h)
+{
+ char buffer[TRAILER_SIZE];
+ static char runtime_path[MAX_PATH];
+ DWORD nread;
+ int num_sections, path_size, i;
+ long ofs;
+
+ if (SetFilePointer(h, -TRAILER_SIZE, NULL, FILE_END) == -1) return NULL;
+ if (! ReadFile(h, buffer, TRAILER_SIZE, &nread, NULL)) return NULL;
+ if (nread != TRAILER_SIZE) return NULL;
+ num_sections = read_size(buffer);
+ ofs = TRAILER_SIZE + num_sections * 8;
+ if (SetFilePointer(h, - ofs, NULL, FILE_END) == -1) return NULL;
+ path_size = 0;
+ for (i = 0; i < num_sections; i++) {
+ if (! ReadFile(h, buffer, 8, &nread, NULL) || nread != 8) return NULL;
+ if (buffer[0] == 'R' && buffer[1] == 'N' &&
+ buffer[2] == 'T' && buffer[3] == 'M') {
+ path_size = read_size(buffer + 4);
+ ofs += path_size;
+ } else if (path_size > 0)
+ ofs += read_size(buffer + 4);
+ }
+ if (path_size == 0) return default_runtime_name;
+ if (path_size >= MAX_PATH) return NULL;
+ if (SetFilePointer(h, -ofs, NULL, FILE_END) == -1) return NULL;
+ if (! ReadFile(h, runtime_path, path_size, &nread, NULL)) return NULL;
+ if (nread != path_size) return NULL;
+ runtime_path[path_size - 1] = 0;
+ return runtime_path;
+}
+
+static BOOL WINAPI ctrl_handler(DWORD event)
+{
+ if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT)
+ return TRUE; /* pretend we've handled them */
+ else
+ return FALSE;
+}
+
+#define msg_and_length(msg) msg , (sizeof(msg) - 1)
+
+static __inline void __declspec(noreturn) run_runtime(char * runtime,
+ char * const cmdline)
+{
+ char path[MAX_PATH];
+ STARTUPINFO stinfo;
+ PROCESS_INFORMATION procinfo;
+ DWORD retcode;
+ if (SearchPath(NULL, runtime, ".exe", MAX_PATH, path, &runtime) == 0) {
+ HANDLE errh;
+ DWORD numwritten;
+ errh = GetStdHandle(STD_ERROR_HANDLE);
+ WriteFile(errh, msg_and_length("Cannot exec "), &numwritten, NULL);
+ WriteFile(errh, runtime, strlen(runtime), &numwritten, NULL);
+ WriteFile(errh, msg_and_length("\r\n"), &numwritten, NULL);
+ ExitProcess(2);
+#if _MSC_VER >= 1200
+ __assume(0); /* Not reached */
+#endif
+ }
+ /* Need to ignore ctrl-C and ctrl-break, otherwise we'll die and take
+ the underlying OCaml program with us! */
+ SetConsoleCtrlHandler(ctrl_handler, TRUE);
+
+ stinfo.cb = sizeof(stinfo);
+ stinfo.lpReserved = NULL;
+ stinfo.lpDesktop = NULL;
+ stinfo.lpTitle = NULL;
+ stinfo.dwFlags = 0;
+ stinfo.cbReserved2 = 0;
+ stinfo.lpReserved2 = NULL;
+ if (!CreateProcess(path, cmdline, NULL, NULL, TRUE, 0, NULL, NULL,
+ &stinfo, &procinfo)) {
+ HANDLE errh;
+ DWORD numwritten;
+ errh = GetStdHandle(STD_ERROR_HANDLE);
+ WriteFile(errh, msg_and_length("Cannot exec "), &numwritten, NULL);
+ WriteFile(errh, runtime, strlen(runtime), &numwritten, NULL);
+ WriteFile(errh, msg_and_length("\r\n"), &numwritten, NULL);
+ ExitProcess(2);
+#if _MSC_VER >= 1200
+ __assume(0); /* Not reached */
+#endif
+ }
+ CloseHandle(procinfo.hThread);
+ WaitForSingleObject(procinfo.hProcess , INFINITE);
+ GetExitCodeProcess(procinfo.hProcess , &retcode);
+ CloseHandle(procinfo.hProcess);
+ ExitProcess(retcode);
+#if _MSC_VER >= 1200
+ __assume(0); /* Not reached */
+#endif
+}
+
+#ifdef __MINGW32__
+int main()
+#else
+void __declspec(noreturn) __cdecl headerentry()
+#endif
+{
+ char truename[MAX_PATH];
+ char * cmdline = GetCommandLine();
+ char * runtime_path;
+ HANDLE h;
+
+ GetModuleFileName(NULL, truename, sizeof(truename));
+ h = CreateFile(truename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
+ NULL, OPEN_EXISTING, 0, NULL);
+ if (h == INVALID_HANDLE_VALUE ||
+ (runtime_path = read_runtime_path(h)) == NULL) {
+ HANDLE errh;
+ DWORD numwritten;
+ errh = GetStdHandle(STD_ERROR_HANDLE);
+ WriteFile(errh, truename, strlen(truename), &numwritten, NULL);
+ WriteFile(errh, msg_and_length(" not found or is not a bytecode"
+ " executable file\r\n"),
+ &numwritten, NULL);
+ ExitProcess(2);
+#if _MSC_VER >= 1200
+ __assume(0); /* Not reached */
+#endif
+ }
+ CloseHandle(h);
+ run_runtime(runtime_path , cmdline);
+#if _MSC_VER >= 1200
+ __assume(0); /* Not reached */
+#endif
+#ifdef __MINGW32__
+ return 0;
+#endif
+}
diff --git a/stdlib/int32.ml b/stdlib/int32.ml
new file mode 100644
index 0000000000..63c99e3d42
--- /dev/null
+++ b/stdlib/int32.ml
@@ -0,0 +1,53 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [Int32]: 32-bit integers *)
+
+external neg : int32 -> int32 = "%int32_neg"
+external add : int32 -> int32 -> int32 = "%int32_add"
+external sub : int32 -> int32 -> int32 = "%int32_sub"
+external mul : int32 -> int32 -> int32 = "%int32_mul"
+external div : int32 -> int32 -> int32 = "%int32_div"
+external rem : int32 -> int32 -> int32 = "%int32_mod"
+external logand : int32 -> int32 -> int32 = "%int32_and"
+external logor : int32 -> int32 -> int32 = "%int32_or"
+external logxor : int32 -> int32 -> int32 = "%int32_xor"
+external shift_left : int32 -> int -> int32 = "%int32_lsl"
+external shift_right : int32 -> int -> int32 = "%int32_asr"
+external shift_right_logical : int32 -> int -> int32 = "%int32_lsr"
+external of_int : int -> int32 = "%int32_of_int"
+external to_int : int32 -> int = "%int32_to_int"
+external of_float : float -> int32 = "caml_int32_of_float"
+external to_float : int32 -> float = "caml_int32_to_float"
+external bits_of_float : float -> int32 = "caml_int32_bits_of_float"
+external float_of_bits : int32 -> float = "caml_int32_float_of_bits"
+
+let zero = 0l
+let one = 1l
+let minus_one = -1l
+let succ n = add n 1l
+let pred n = sub n 1l
+let abs n = if n >= 0l then n else neg n
+let min_int = 0x80000000l
+let max_int = 0x7FFFFFFFl
+let lognot n = logxor n (-1l)
+
+external format : string -> int32 -> string = "caml_int32_format"
+let to_string n = format "%d" n
+
+external of_string : string -> int32 = "caml_int32_of_string"
+
+type t = int32
+
+let compare (x: t) (y: t) = Pervasives.compare x y
+let equal (x: t) (y: t) = compare x y = 0
diff --git a/stdlib/int32.mli b/stdlib/int32.mli
new file mode 100644
index 0000000000..4a29e6c0f2
--- /dev/null
+++ b/stdlib/int32.mli
@@ -0,0 +1,166 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** 32-bit integers.
+
+ This module provides operations on the type [int32]
+ of signed 32-bit integers. Unlike the built-in [int] type,
+ the type [int32] is guaranteed to be exactly 32-bit wide on all
+ platforms. All arithmetic operations over [int32] are taken
+ modulo 2{^32}.
+
+ Performance notice: values of type [int32] occupy more memory
+ space than values of type [int], and arithmetic operations on
+ [int32] are generally slower than those on [int]. Use [int32]
+ only when the application requires exact 32-bit arithmetic. *)
+
+val zero : int32
+(** The 32-bit integer 0. *)
+
+val one : int32
+(** The 32-bit integer 1. *)
+
+val minus_one : int32
+(** The 32-bit integer -1. *)
+
+external neg : int32 -> int32 = "%int32_neg"
+(** Unary negation. *)
+
+external add : int32 -> int32 -> int32 = "%int32_add"
+(** Addition. *)
+
+external sub : int32 -> int32 -> int32 = "%int32_sub"
+(** Subtraction. *)
+
+external mul : int32 -> int32 -> int32 = "%int32_mul"
+(** Multiplication. *)
+
+external div : int32 -> int32 -> int32 = "%int32_div"
+(** Integer division. Raise [Division_by_zero] if the second
+ argument is zero. This division rounds the real quotient of
+ its arguments towards zero, as specified for {!Pervasives.(/)}. *)
+
+external rem : int32 -> int32 -> int32 = "%int32_mod"
+(** Integer remainder. If [y] is not zero, the result
+ of [Int32.rem x y] satisfies the following property:
+ [x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)].
+ If [y = 0], [Int32.rem x y] raises [Division_by_zero]. *)
+
+val succ : int32 -> int32
+(** Successor. [Int32.succ x] is [Int32.add x Int32.one]. *)
+
+val pred : int32 -> int32
+(** Predecessor. [Int32.pred x] is [Int32.sub x Int32.one]. *)
+
+val abs : int32 -> int32
+(** Return the absolute value of its argument. *)
+
+val max_int : int32
+(** The greatest representable 32-bit integer, 2{^31} - 1. *)
+
+val min_int : int32
+(** The smallest representable 32-bit integer, -2{^31}. *)
+
+
+external logand : int32 -> int32 -> int32 = "%int32_and"
+(** Bitwise logical and. *)
+
+external logor : int32 -> int32 -> int32 = "%int32_or"
+(** Bitwise logical or. *)
+
+external logxor : int32 -> int32 -> int32 = "%int32_xor"
+(** Bitwise logical exclusive or. *)
+
+val lognot : int32 -> int32
+(** Bitwise logical negation *)
+
+external shift_left : int32 -> int -> int32 = "%int32_lsl"
+(** [Int32.shift_left x y] shifts [x] to the left by [y] bits.
+ The result is unspecified if [y < 0] or [y >= 32]. *)
+
+external shift_right : int32 -> int -> int32 = "%int32_asr"
+(** [Int32.shift_right x y] shifts [x] to the right by [y] bits.
+ This is an arithmetic shift: the sign bit of [x] is replicated
+ and inserted in the vacated bits.
+ The result is unspecified if [y < 0] or [y >= 32]. *)
+
+external shift_right_logical : int32 -> int -> int32 = "%int32_lsr"
+(** [Int32.shift_right_logical x y] shifts [x] to the right by [y] bits.
+ This is a logical shift: zeroes are inserted in the vacated bits
+ regardless of the sign of [x].
+ The result is unspecified if [y < 0] or [y >= 32]. *)
+
+external of_int : int -> int32 = "%int32_of_int"
+(** Convert the given integer (type [int]) to a 32-bit integer
+ (type [int32]). *)
+
+external to_int : int32 -> int = "%int32_to_int"
+(** Convert the given 32-bit integer (type [int32]) to an
+ integer (type [int]). On 32-bit platforms, the 32-bit integer
+ is taken modulo 2{^31}, i.e. the high-order bit is lost
+ during the conversion. On 64-bit platforms, the conversion
+ is exact. *)
+
+external of_float : float -> int32 = "caml_int32_of_float"
+(** Convert the given floating-point number to a 32-bit integer,
+ discarding the fractional part (truncate towards 0).
+ The result of the conversion is undefined if, after truncation,
+ the number is outside the range \[{!Int32.min_int}, {!Int32.max_int}\]. *)
+
+external to_float : int32 -> float = "caml_int32_to_float"
+(** Convert the given 32-bit integer to a floating-point number. *)
+
+external of_string : string -> int32 = "caml_int32_of_string"
+(** Convert the given string to a 32-bit integer.
+ The string is read in decimal (by default) or in hexadecimal,
+ octal or binary if the string begins with [0x], [0o] or [0b]
+ respectively.
+ Raise [Failure "int_of_string"] if the given string is not
+ a valid representation of an integer, or if the integer represented
+ exceeds the range of integers representable in type [int32]. *)
+
+val to_string : int32 -> string
+(** Return the string representation of its argument, in signed decimal. *)
+
+external bits_of_float : float -> int32 = "caml_int32_bits_of_float"
+(** Return the internal representation of the given float according
+ to the IEEE 754 floating-point 'single format' bit layout.
+ Bit 31 of the result represents the sign of the float;
+ bits 30 to 23 represent the (biased) exponent; bits 22 to 0
+ represent the mantissa. *)
+
+external float_of_bits : int32 -> float = "caml_int32_float_of_bits"
+(** Return the floating-point number whose internal representation,
+ according to the IEEE 754 floating-point 'single format' bit layout,
+ is the given [int32]. *)
+
+type t = int32
+(** An alias for the type of 32-bit integers. *)
+
+val compare: t -> t -> int
+(** The comparison function for 32-bit integers, with the same specification as
+ {!Pervasives.compare}. Along with the type [t], this function [compare]
+ allows the module [Int32] to be passed as argument to the functors
+ {!Set.Make} and {!Map.Make}. *)
+
+val equal: t -> t -> bool
+(** The equal function for int32s.
+ @since 4.03.0 *)
+
+(**/**)
+
+(** {6 Deprecated functions} *)
+
+external format : string -> int32 -> string = "caml_int32_format"
+(** Do not use this deprecated function. Instead,
+ used {!Printf.sprintf} with a [%l...] format. *)
diff --git a/stdlib/int64.ml b/stdlib/int64.ml
new file mode 100644
index 0000000000..274a9868d9
--- /dev/null
+++ b/stdlib/int64.ml
@@ -0,0 +1,58 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [Int64]: 64-bit integers *)
+
+external neg : int64 -> int64 = "%int64_neg"
+external add : int64 -> int64 -> int64 = "%int64_add"
+external sub : int64 -> int64 -> int64 = "%int64_sub"
+external mul : int64 -> int64 -> int64 = "%int64_mul"
+external div : int64 -> int64 -> int64 = "%int64_div"
+external rem : int64 -> int64 -> int64 = "%int64_mod"
+external logand : int64 -> int64 -> int64 = "%int64_and"
+external logor : int64 -> int64 -> int64 = "%int64_or"
+external logxor : int64 -> int64 -> int64 = "%int64_xor"
+external shift_left : int64 -> int -> int64 = "%int64_lsl"
+external shift_right : int64 -> int -> int64 = "%int64_asr"
+external shift_right_logical : int64 -> int -> int64 = "%int64_lsr"
+external of_int : int -> int64 = "%int64_of_int"
+external to_int : int64 -> int = "%int64_to_int"
+external of_float : float -> int64 = "caml_int64_of_float"
+external to_float : int64 -> float = "caml_int64_to_float"
+external of_int32 : int32 -> int64 = "%int64_of_int32"
+external to_int32 : int64 -> int32 = "%int64_to_int32"
+external of_nativeint : nativeint -> int64 = "%int64_of_nativeint"
+external to_nativeint : int64 -> nativeint = "%int64_to_nativeint"
+
+let zero = 0L
+let one = 1L
+let minus_one = -1L
+let succ n = add n 1L
+let pred n = sub n 1L
+let abs n = if n >= 0L then n else neg n
+let min_int = 0x8000000000000000L
+let max_int = 0x7FFFFFFFFFFFFFFFL
+let lognot n = logxor n (-1L)
+
+external format : string -> int64 -> string = "caml_int64_format"
+let to_string n = format "%d" n
+
+external of_string : string -> int64 = "caml_int64_of_string"
+
+external bits_of_float : float -> int64 = "caml_int64_bits_of_float"
+external float_of_bits : int64 -> float = "caml_int64_float_of_bits"
+
+type t = int64
+
+let compare (x: t) (y: t) = Pervasives.compare x y
+let equal (x: t) (y: t) = compare x y = 0
diff --git a/stdlib/int64.mli b/stdlib/int64.mli
new file mode 100644
index 0000000000..edd600c690
--- /dev/null
+++ b/stdlib/int64.mli
@@ -0,0 +1,188 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** 64-bit integers.
+
+ This module provides operations on the type [int64] of
+ signed 64-bit integers. Unlike the built-in [int] type,
+ the type [int64] is guaranteed to be exactly 64-bit wide on all
+ platforms. All arithmetic operations over [int64] are taken
+ modulo 2{^64}
+
+ Performance notice: values of type [int64] occupy more memory
+ space than values of type [int], and arithmetic operations on
+ [int64] are generally slower than those on [int]. Use [int64]
+ only when the application requires exact 64-bit arithmetic.
+*)
+
+val zero : int64
+(** The 64-bit integer 0. *)
+
+val one : int64
+(** The 64-bit integer 1. *)
+
+val minus_one : int64
+(** The 64-bit integer -1. *)
+
+external neg : int64 -> int64 = "%int64_neg"
+(** Unary negation. *)
+
+external add : int64 -> int64 -> int64 = "%int64_add"
+(** Addition. *)
+
+external sub : int64 -> int64 -> int64 = "%int64_sub"
+(** Subtraction. *)
+
+external mul : int64 -> int64 -> int64 = "%int64_mul"
+(** Multiplication. *)
+
+external div : int64 -> int64 -> int64 = "%int64_div"
+(** Integer division. Raise [Division_by_zero] if the second
+ argument is zero. This division rounds the real quotient of
+ its arguments towards zero, as specified for {!Pervasives.(/)}. *)
+
+external rem : int64 -> int64 -> int64 = "%int64_mod"
+(** Integer remainder. If [y] is not zero, the result
+ of [Int64.rem x y] satisfies the following property:
+ [x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)].
+ If [y = 0], [Int64.rem x y] raises [Division_by_zero]. *)
+
+val succ : int64 -> int64
+(** Successor. [Int64.succ x] is [Int64.add x Int64.one]. *)
+
+val pred : int64 -> int64
+(** Predecessor. [Int64.pred x] is [Int64.sub x Int64.one]. *)
+
+val abs : int64 -> int64
+(** Return the absolute value of its argument. *)
+
+val max_int : int64
+(** The greatest representable 64-bit integer, 2{^63} - 1. *)
+
+val min_int : int64
+(** The smallest representable 64-bit integer, -2{^63}. *)
+
+external logand : int64 -> int64 -> int64 = "%int64_and"
+(** Bitwise logical and. *)
+
+external logor : int64 -> int64 -> int64 = "%int64_or"
+(** Bitwise logical or. *)
+
+external logxor : int64 -> int64 -> int64 = "%int64_xor"
+(** Bitwise logical exclusive or. *)
+
+val lognot : int64 -> int64
+(** Bitwise logical negation *)
+
+external shift_left : int64 -> int -> int64 = "%int64_lsl"
+(** [Int64.shift_left x y] shifts [x] to the left by [y] bits.
+ The result is unspecified if [y < 0] or [y >= 64]. *)
+
+external shift_right : int64 -> int -> int64 = "%int64_asr"
+(** [Int64.shift_right x y] shifts [x] to the right by [y] bits.
+ This is an arithmetic shift: the sign bit of [x] is replicated
+ and inserted in the vacated bits.
+ The result is unspecified if [y < 0] or [y >= 64]. *)
+
+external shift_right_logical : int64 -> int -> int64 = "%int64_lsr"
+(** [Int64.shift_right_logical x y] shifts [x] to the right by [y] bits.
+ This is a logical shift: zeroes are inserted in the vacated bits
+ regardless of the sign of [x].
+ The result is unspecified if [y < 0] or [y >= 64]. *)
+
+external of_int : int -> int64 = "%int64_of_int"
+(** Convert the given integer (type [int]) to a 64-bit integer
+ (type [int64]). *)
+
+external to_int : int64 -> int = "%int64_to_int"
+(** Convert the given 64-bit integer (type [int64]) to an
+ integer (type [int]). On 64-bit platforms, the 64-bit integer
+ is taken modulo 2{^63}, i.e. the high-order bit is lost
+ during the conversion. On 32-bit platforms, the 64-bit integer
+ is taken modulo 2{^31}, i.e. the top 33 bits are lost
+ during the conversion. *)
+
+external of_float : float -> int64 = "caml_int64_of_float"
+(** Convert the given floating-point number to a 64-bit integer,
+ discarding the fractional part (truncate towards 0).
+ The result of the conversion is undefined if, after truncation,
+ the number is outside the range \[{!Int64.min_int}, {!Int64.max_int}\]. *)
+
+external to_float : int64 -> float = "caml_int64_to_float"
+(** Convert the given 64-bit integer to a floating-point number. *)
+
+
+external of_int32 : int32 -> int64 = "%int64_of_int32"
+(** Convert the given 32-bit integer (type [int32])
+ to a 64-bit integer (type [int64]). *)
+
+external to_int32 : int64 -> int32 = "%int64_to_int32"
+(** Convert the given 64-bit integer (type [int64]) to a
+ 32-bit integer (type [int32]). The 64-bit integer
+ is taken modulo 2{^32}, i.e. the top 32 bits are lost
+ during the conversion. *)
+
+external of_nativeint : nativeint -> int64 = "%int64_of_nativeint"
+(** Convert the given native integer (type [nativeint])
+ to a 64-bit integer (type [int64]). *)
+
+external to_nativeint : int64 -> nativeint = "%int64_to_nativeint"
+(** Convert the given 64-bit integer (type [int64]) to a
+ native integer. On 32-bit platforms, the 64-bit integer
+ is taken modulo 2{^32}. On 64-bit platforms,
+ the conversion is exact. *)
+
+external of_string : string -> int64 = "caml_int64_of_string"
+(** Convert the given string to a 64-bit integer.
+ The string is read in decimal (by default) or in hexadecimal,
+ octal or binary if the string begins with [0x], [0o] or [0b]
+ respectively.
+ Raise [Failure "int_of_string"] if the given string is not
+ a valid representation of an integer, or if the integer represented
+ exceeds the range of integers representable in type [int64]. *)
+
+val to_string : int64 -> string
+(** Return the string representation of its argument, in decimal. *)
+
+external bits_of_float : float -> int64 = "caml_int64_bits_of_float"
+(** Return the internal representation of the given float according
+ to the IEEE 754 floating-point 'double format' bit layout.
+ Bit 63 of the result represents the sign of the float;
+ bits 62 to 52 represent the (biased) exponent; bits 51 to 0
+ represent the mantissa. *)
+
+external float_of_bits : int64 -> float = "caml_int64_float_of_bits"
+(** Return the floating-point number whose internal representation,
+ according to the IEEE 754 floating-point 'double format' bit layout,
+ is the given [int64]. *)
+
+type t = int64
+(** An alias for the type of 64-bit integers. *)
+
+val compare: t -> t -> int
+(** The comparison function for 64-bit integers, with the same specification as
+ {!Pervasives.compare}. Along with the type [t], this function [compare]
+ allows the module [Int64] to be passed as argument to the functors
+ {!Set.Make} and {!Map.Make}. *)
+
+val equal: t -> t -> bool
+(** The equal function for int64s.
+ @since 4.03.0 *)
+
+(**/**)
+
+(** {6 Deprecated functions} *)
+
+external format : string -> int64 -> string = "caml_int64_format"
+(** Do not use this deprecated function. Instead,
+ used {!Printf.sprintf} with a [%L...] format. *)
diff --git a/stdlib/lazy.ml b/stdlib/lazy.ml
new file mode 100644
index 0000000000..590be8fe99
--- /dev/null
+++ b/stdlib/lazy.ml
@@ -0,0 +1,79 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [Lazy]: deferred computations *)
+
+
+(*
+ WARNING: some purple magic is going on here. Do not take this file
+ as an example of how to program in OCaml.
+*)
+
+
+(* We make use of two special tags provided by the runtime:
+ [lazy_tag] and [forward_tag].
+
+ A value of type ['a Lazy.t] can be one of three things:
+ 1. A block of size 1 with tag [lazy_tag]. Its field is a closure of
+ type [unit -> 'a] that computes the value.
+ 2. A block of size 1 with tag [forward_tag]. Its field is the value
+ of type ['a] that was computed.
+ 3. Anything else except a float. This has type ['a] and is the value
+ that was computed.
+ Exceptions are stored in format (1).
+ The GC will magically change things from (2) to (3) according to its
+ fancy.
+
+ We cannot use representation (3) for a [float Lazy.t] because
+ [caml_make_array] assumes that only a [float] value can have tag
+ [Double_tag].
+
+ We have to use the built-in type constructor [lazy_t] to
+ let the compiler implement the special typing and compilation
+ rules for the [lazy] keyword.
+*)
+
+type 'a t = 'a lazy_t;;
+
+exception Undefined = CamlinternalLazy.Undefined;;
+
+external make_forward : 'a -> 'a lazy_t = "caml_lazy_make_forward";;
+
+external force : 'a t -> 'a = "%lazy_force";;
+
+(* let force = force;; *)
+
+let force_val = CamlinternalLazy.force_val;;
+
+let from_fun (f : unit -> 'arg) =
+ let x = Obj.new_block Obj.lazy_tag 1 in
+ Obj.set_field x 0 (Obj.repr f);
+ (Obj.obj x : 'arg t)
+;;
+
+let from_val (v : 'arg) =
+ let t = Obj.tag (Obj.repr v) in
+ if t = Obj.forward_tag || t = Obj.lazy_tag || t = Obj.double_tag then begin
+ make_forward v
+ end else begin
+ (Obj.magic v : 'arg t)
+ end
+;;
+
+let is_val (l : 'arg t) = Obj.tag (Obj.repr l) <> Obj.lazy_tag;;
+
+let lazy_from_fun = from_fun;;
+
+let lazy_from_val = from_val;;
+
+let lazy_is_val = is_val;;
diff --git a/stdlib/lazy.mli b/stdlib/lazy.mli
new file mode 100644
index 0000000000..f2541b7fd3
--- /dev/null
+++ b/stdlib/lazy.mli
@@ -0,0 +1,88 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Deferred computations. *)
+
+type 'a t = 'a lazy_t;;
+(** A value of type ['a Lazy.t] is a deferred computation, called
+ a suspension, that has a result of type ['a]. The special
+ expression syntax [lazy (expr)] makes a suspension of the
+ computation of [expr], without computing [expr] itself yet.
+ "Forcing" the suspension will then compute [expr] and return its
+ result.
+
+ Note: [lazy_t] is the built-in type constructor used by the compiler
+ for the [lazy] keyword. You should not use it directly. Always use
+ [Lazy.t] instead.
+
+ Note: [Lazy.force] is not thread-safe. If you use this module in
+ a multi-threaded program, you will need to add some locks.
+
+ Note: if the program is compiled with the [-rectypes] option,
+ ill-founded recursive definitions of the form [let rec x = lazy x]
+ or [let rec x = lazy(lazy(...(lazy x)))] are accepted by the type-checker
+ and lead, when forced, to ill-formed values that trigger infinite
+ loops in the garbage collector and other parts of the run-time system.
+ Without the [-rectypes] option, such ill-founded recursive definitions
+ are rejected by the type-checker.
+*)
+
+
+exception Undefined;;
+
+(* val force : 'a t -> 'a ;; *)
+external force : 'a t -> 'a = "%lazy_force";;
+(** [force x] forces the suspension [x] and returns its result.
+ If [x] has already been forced, [Lazy.force x] returns the
+ same value again without recomputing it. If it raised an exception,
+ the same exception is raised again.
+ Raise [Undefined] if the forcing of [x] tries to force [x] itself
+ recursively.
+*)
+
+val force_val : 'a t -> 'a;;
+(** [force_val x] forces the suspension [x] and returns its
+ result. If [x] has already been forced, [force_val x]
+ returns the same value again without recomputing it.
+ Raise [Undefined] if the forcing of [x] tries to force [x] itself
+ recursively.
+ If the computation of [x] raises an exception, it is unspecified
+ whether [force_val x] raises the same exception or [Undefined].
+*)
+
+val from_fun : (unit -> 'a) -> 'a t;;
+(** [from_fun f] is the same as [lazy (f ())] but slightly more efficient.
+ @since 4.00.0 *)
+
+val from_val : 'a -> 'a t;;
+(** [from_val v] returns an already-forced suspension of [v].
+ This is for special purposes only and should not be confused with
+ [lazy (v)].
+ @since 4.00.0 *)
+
+val is_val : 'a t -> bool;;
+(** [is_val x] returns [true] if [x] has already been forced and
+ did not raise an exception.
+ @since 4.00.0 *)
+
+val lazy_from_fun : (unit -> 'a) -> 'a t
+ [@@ocaml.deprecated "Use Lazy.from_fun instead."];;
+(** @deprecated synonym for [from_fun]. *)
+
+val lazy_from_val : 'a -> 'a t
+ [@@ocaml.deprecated "Use Lazy.from_val instead."];;
+(** @deprecated synonym for [from_val]. *)
+
+val lazy_is_val : 'a t -> bool
+ [@@ocaml.deprecated "Use Lazy.is_val instead."];;
+(** @deprecated synonym for [is_val]. *)
diff --git a/stdlib/lexing.ml b/stdlib/lexing.ml
new file mode 100644
index 0000000000..d2231fbe9b
--- /dev/null
+++ b/stdlib/lexing.ml
@@ -0,0 +1,230 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* The run-time library for lexers generated by camllex *)
+
+type position = {
+ pos_fname : string;
+ pos_lnum : int;
+ pos_bol : int;
+ pos_cnum : int;
+}
+
+let dummy_pos = {
+ pos_fname = "";
+ pos_lnum = 0;
+ pos_bol = 0;
+ pos_cnum = -1;
+}
+
+type lexbuf =
+ { refill_buff : lexbuf -> unit;
+ mutable lex_buffer : bytes;
+ mutable lex_buffer_len : int;
+ mutable lex_abs_pos : int;
+ mutable lex_start_pos : int;
+ mutable lex_curr_pos : int;
+ mutable lex_last_pos : int;
+ mutable lex_last_action : int;
+ mutable lex_eof_reached : bool;
+ mutable lex_mem : int array;
+ mutable lex_start_p : position;
+ mutable lex_curr_p : position;
+ }
+
+type lex_tables =
+ { lex_base: string;
+ lex_backtrk: string;
+ lex_default: string;
+ lex_trans: string;
+ lex_check: string;
+ lex_base_code : string;
+ lex_backtrk_code : string;
+ lex_default_code : string;
+ lex_trans_code : string;
+ lex_check_code : string;
+ lex_code: string;}
+
+external c_engine : lex_tables -> int -> lexbuf -> int = "caml_lex_engine"
+external c_new_engine : lex_tables -> int -> lexbuf -> int
+ = "caml_new_lex_engine"
+
+let engine tbl state buf =
+ let result = c_engine tbl state buf in
+ if result >= 0 then begin
+ buf.lex_start_p <- buf.lex_curr_p;
+ buf.lex_curr_p <- {buf.lex_curr_p
+ with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos};
+ end;
+ result
+;;
+
+let new_engine tbl state buf =
+ let result = c_new_engine tbl state buf in
+ if result >= 0 then begin
+ buf.lex_start_p <- buf.lex_curr_p;
+ buf.lex_curr_p <- {buf.lex_curr_p
+ with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos};
+ end;
+ result
+;;
+
+let lex_refill read_fun aux_buffer lexbuf =
+ let read =
+ read_fun aux_buffer (Bytes.length aux_buffer) in
+ let n =
+ if read > 0
+ then read
+ else (lexbuf.lex_eof_reached <- true; 0) in
+ (* Current state of the buffer:
+ <-------|---------------------|----------->
+ | junk | valid data | junk |
+ ^ ^ ^ ^
+ 0 start_pos buffer_end Bytes.length buffer
+ *)
+ if lexbuf.lex_buffer_len + n > Bytes.length lexbuf.lex_buffer then begin
+ (* There is not enough space at the end of the buffer *)
+ if lexbuf.lex_buffer_len - lexbuf.lex_start_pos + n
+ <= Bytes.length lexbuf.lex_buffer
+ then begin
+ (* But there is enough space if we reclaim the junk at the beginning
+ of the buffer *)
+ Bytes.blit lexbuf.lex_buffer lexbuf.lex_start_pos
+ lexbuf.lex_buffer 0
+ (lexbuf.lex_buffer_len - lexbuf.lex_start_pos)
+ end else begin
+ (* We must grow the buffer. Doubling its size will provide enough
+ space since n <= String.length aux_buffer <= String.length buffer.
+ Watch out for string length overflow, though. *)
+ let newlen =
+ min (2 * Bytes.length lexbuf.lex_buffer) Sys.max_string_length in
+ if lexbuf.lex_buffer_len - lexbuf.lex_start_pos + n > newlen
+ then failwith "Lexing.lex_refill: cannot grow buffer";
+ let newbuf = Bytes.create newlen in
+ (* Copy the valid data to the beginning of the new buffer *)
+ Bytes.blit lexbuf.lex_buffer lexbuf.lex_start_pos
+ newbuf 0
+ (lexbuf.lex_buffer_len - lexbuf.lex_start_pos);
+ lexbuf.lex_buffer <- newbuf
+ end;
+ (* Reallocation or not, we have shifted the data left by
+ start_pos characters; update the positions *)
+ let s = lexbuf.lex_start_pos in
+ lexbuf.lex_abs_pos <- lexbuf.lex_abs_pos + s;
+ lexbuf.lex_curr_pos <- lexbuf.lex_curr_pos - s;
+ lexbuf.lex_start_pos <- 0;
+ lexbuf.lex_last_pos <- lexbuf.lex_last_pos - s;
+ lexbuf.lex_buffer_len <- lexbuf.lex_buffer_len - s ;
+ let t = lexbuf.lex_mem in
+ for i = 0 to Array.length t-1 do
+ let v = t.(i) in
+ if v >= 0 then
+ t.(i) <- v-s
+ done
+ end;
+ (* There is now enough space at the end of the buffer *)
+ Bytes.blit aux_buffer 0 lexbuf.lex_buffer lexbuf.lex_buffer_len n;
+ lexbuf.lex_buffer_len <- lexbuf.lex_buffer_len + n
+
+let zero_pos = {
+ pos_fname = "";
+ pos_lnum = 1;
+ pos_bol = 0;
+ pos_cnum = 0;
+};;
+
+let from_function f =
+ { refill_buff = lex_refill f (Bytes.create 512);
+ lex_buffer = Bytes.create 1024;
+ lex_buffer_len = 0;
+ lex_abs_pos = 0;
+ lex_start_pos = 0;
+ lex_curr_pos = 0;
+ lex_last_pos = 0;
+ lex_last_action = 0;
+ lex_mem = [||];
+ lex_eof_reached = false;
+ lex_start_p = zero_pos;
+ lex_curr_p = zero_pos;
+ }
+
+let from_channel ic =
+ from_function (fun buf n -> input ic buf 0 n)
+
+let from_string s =
+ { refill_buff = (fun lexbuf -> lexbuf.lex_eof_reached <- true);
+ lex_buffer = Bytes.of_string s; (* have to make a copy for compatibility
+ with unsafe-string mode *)
+ lex_buffer_len = String.length s;
+ lex_abs_pos = 0;
+ lex_start_pos = 0;
+ lex_curr_pos = 0;
+ lex_last_pos = 0;
+ lex_last_action = 0;
+ lex_mem = [||];
+ lex_eof_reached = true;
+ lex_start_p = zero_pos;
+ lex_curr_p = zero_pos;
+ }
+
+let lexeme lexbuf =
+ let len = lexbuf.lex_curr_pos - lexbuf.lex_start_pos in
+ Bytes.sub_string lexbuf.lex_buffer lexbuf.lex_start_pos len
+
+let sub_lexeme lexbuf i1 i2 =
+ let len = i2-i1 in
+ Bytes.sub_string lexbuf.lex_buffer i1 len
+
+let sub_lexeme_opt lexbuf i1 i2 =
+ if i1 >= 0 then begin
+ let len = i2-i1 in
+ Some (Bytes.sub_string lexbuf.lex_buffer i1 len)
+ end else begin
+ None
+ end
+
+let sub_lexeme_char lexbuf i = Bytes.get lexbuf.lex_buffer i
+
+let sub_lexeme_char_opt lexbuf i =
+ if i >= 0 then
+ Some (Bytes.get lexbuf.lex_buffer i)
+ else
+ None
+
+
+let lexeme_char lexbuf i =
+ Bytes.get lexbuf.lex_buffer (lexbuf.lex_start_pos + i)
+
+let lexeme_start lexbuf = lexbuf.lex_start_p.pos_cnum;;
+let lexeme_end lexbuf = lexbuf.lex_curr_p.pos_cnum;;
+
+let lexeme_start_p lexbuf = lexbuf.lex_start_p;;
+let lexeme_end_p lexbuf = lexbuf.lex_curr_p;;
+
+let new_line lexbuf =
+ let lcp = lexbuf.lex_curr_p in
+ lexbuf.lex_curr_p <- { lcp with
+ pos_lnum = lcp.pos_lnum + 1;
+ pos_bol = lcp.pos_cnum;
+ }
+;;
+
+
+(* Discard data left in lexer buffer. *)
+
+let flush_input lb =
+ lb.lex_curr_pos <- 0;
+ lb.lex_abs_pos <- 0;
+ lb.lex_curr_p <- {lb.lex_curr_p with pos_cnum = 0};
+ lb.lex_buffer_len <- 0;
+;;
diff --git a/stdlib/lexing.mli b/stdlib/lexing.mli
new file mode 100644
index 0000000000..30898670b7
--- /dev/null
+++ b/stdlib/lexing.mli
@@ -0,0 +1,174 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** The run-time library for lexers generated by [ocamllex]. *)
+
+(** {6 Positions} *)
+
+type position = {
+ pos_fname : string;
+ pos_lnum : int;
+ pos_bol : int;
+ pos_cnum : int;
+}
+(** A value of type [position] describes a point in a source file.
+ [pos_fname] is the file name; [pos_lnum] is the line number;
+ [pos_bol] is the offset of the beginning of the line (number
+ of characters between the beginning of the lexbuf and the beginning
+ of the line); [pos_cnum] is the offset of the position (number of
+ characters between the beginning of the lexbuf and the position).
+ The difference between [pos_cnum] and [pos_bol] is the character
+ offset within the line (i.e. the column number, assuming each
+ character is one column wide).
+
+ See the documentation of type [lexbuf] for information about
+ how the lexing engine will manage positions.
+ *)
+
+val dummy_pos : position;;
+(** A value of type [position], guaranteed to be different from any
+ valid position.
+ *)
+
+
+(** {6 Lexer buffers} *)
+
+
+type lexbuf =
+ { refill_buff : lexbuf -> unit;
+ mutable lex_buffer : bytes;
+ mutable lex_buffer_len : int;
+ mutable lex_abs_pos : int;
+ mutable lex_start_pos : int;
+ mutable lex_curr_pos : int;
+ mutable lex_last_pos : int;
+ mutable lex_last_action : int;
+ mutable lex_eof_reached : bool;
+ mutable lex_mem : int array;
+ mutable lex_start_p : position;
+ mutable lex_curr_p : position;
+ }
+(** The type of lexer buffers. A lexer buffer is the argument passed
+ to the scanning functions defined by the generated scanners.
+ The lexer buffer holds the current state of the scanner, plus
+ a function to refill the buffer from the input.
+
+ At each token, the lexing engine will copy [lex_curr_p] to
+ [lex_start_p], then change the [pos_cnum] field
+ of [lex_curr_p] by updating it with the number of characters read
+ since the start of the [lexbuf]. The other fields are left
+ unchanged by the lexing engine. In order to keep them
+ accurate, they must be initialised before the first use of the
+ lexbuf, and updated by the relevant lexer actions (i.e. at each
+ end of line -- see also [new_line]).
+ *)
+
+val from_channel : in_channel -> lexbuf
+(** Create a lexer buffer on the given input channel.
+ [Lexing.from_channel inchan] returns a lexer buffer which reads
+ from the input channel [inchan], at the current reading position. *)
+
+val from_string : string -> lexbuf
+(** Create a lexer buffer which reads from
+ the given string. Reading starts from the first character in
+ the string. An end-of-input condition is generated when the
+ end of the string is reached. *)
+
+val from_function : (bytes -> int -> int) -> lexbuf
+(** Create a lexer buffer with the given function as its reading method.
+ When the scanner needs more characters, it will call the given
+ function, giving it a byte sequence [s] and a byte
+ count [n]. The function should put [n] bytes or fewer in [s],
+ starting at index 0, and return the number of bytes
+ provided. A return value of 0 means end of input. *)
+
+
+(** {6 Functions for lexer semantic actions} *)
+
+
+(** The following functions can be called from the semantic actions
+ of lexer definitions (the ML code enclosed in braces that
+ computes the value returned by lexing functions). They give
+ access to the character string matched by the regular expression
+ associated with the semantic action. These functions must be
+ applied to the argument [lexbuf], which, in the code generated by
+ [ocamllex], is bound to the lexer buffer passed to the parsing
+ function. *)
+
+val lexeme : lexbuf -> string
+(** [Lexing.lexeme lexbuf] returns the string matched by
+ the regular expression. *)
+
+val lexeme_char : lexbuf -> int -> char
+(** [Lexing.lexeme_char lexbuf i] returns character number [i] in
+ the matched string. *)
+
+val lexeme_start : lexbuf -> int
+(** [Lexing.lexeme_start lexbuf] returns the offset in the
+ input stream of the first character of the matched string.
+ The first character of the stream has offset 0. *)
+
+val lexeme_end : lexbuf -> int
+(** [Lexing.lexeme_end lexbuf] returns the offset in the input stream
+ of the character following the last character of the matched
+ string. The first character of the stream has offset 0. *)
+
+val lexeme_start_p : lexbuf -> position
+(** Like [lexeme_start], but return a complete [position] instead
+ of an offset. *)
+
+val lexeme_end_p : lexbuf -> position
+(** Like [lexeme_end], but return a complete [position] instead
+ of an offset. *)
+
+val new_line : lexbuf -> unit
+(** Update the [lex_curr_p] field of the lexbuf to reflect the start
+ of a new line. You can call this function in the semantic action
+ of the rule that matches the end-of-line character.
+ @since 3.11.0
+*)
+
+(** {6 Miscellaneous functions} *)
+
+val flush_input : lexbuf -> unit
+(** Discard the contents of the buffer and reset the current
+ position to 0. The next use of the lexbuf will trigger a
+ refill. *)
+
+(**/**)
+
+(** {6 } *)
+
+(** The following definitions are used by the generated scanners only.
+ They are not intended to be used directly by user programs. *)
+
+val sub_lexeme : lexbuf -> int -> int -> string
+val sub_lexeme_opt : lexbuf -> int -> int -> string option
+val sub_lexeme_char : lexbuf -> int -> char
+val sub_lexeme_char_opt : lexbuf -> int -> char option
+
+type lex_tables =
+ { lex_base : string;
+ lex_backtrk : string;
+ lex_default : string;
+ lex_trans : string;
+ lex_check : string;
+ lex_base_code : string;
+ lex_backtrk_code : string;
+ lex_default_code : string;
+ lex_trans_code : string;
+ lex_check_code : string;
+ lex_code: string;}
+
+val engine : lex_tables -> int -> lexbuf -> int
+val new_engine : lex_tables -> int -> lexbuf -> int
diff --git a/stdlib/list.ml b/stdlib/list.ml
new file mode 100644
index 0000000000..e62af44874
--- /dev/null
+++ b/stdlib/list.ml
@@ -0,0 +1,431 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* List operations *)
+
+let rec length_aux len = function
+ [] -> len
+ | a::l -> length_aux (len + 1) l
+
+let length l = length_aux 0 l
+
+let cons a l = a::l
+
+let hd = function
+ [] -> failwith "hd"
+ | a::l -> a
+
+let tl = function
+ [] -> failwith "tl"
+ | a::l -> l
+
+let nth l n =
+ if n < 0 then invalid_arg "List.nth" else
+ let rec nth_aux l n =
+ match l with
+ | [] -> failwith "nth"
+ | a::l -> if n = 0 then a else nth_aux l (n-1)
+ in nth_aux l n
+
+let append = (@)
+
+let rec rev_append l1 l2 =
+ match l1 with
+ [] -> l2
+ | a :: l -> rev_append l (a :: l2)
+
+let rev l = rev_append l []
+
+let rec flatten = function
+ [] -> []
+ | l::r -> l @ flatten r
+
+let concat = flatten
+
+let rec map f = function
+ [] -> []
+ | a::l -> let r = f a in r :: map f l
+
+let rec mapi i f = function
+ [] -> []
+ | a::l -> let r = f i a in r :: mapi (i + 1) f l
+
+let mapi f l = mapi 0 f l
+
+let rev_map f l =
+ let rec rmap_f accu = function
+ | [] -> accu
+ | a::l -> rmap_f (f a :: accu) l
+ in
+ rmap_f [] l
+;;
+
+let rec iter f = function
+ [] -> ()
+ | a::l -> f a; iter f l
+
+let rec iteri i f = function
+ [] -> ()
+ | a::l -> f i a; iteri (i + 1) f l
+
+let iteri f l = iteri 0 f l
+
+let rec fold_left f accu l =
+ match l with
+ [] -> accu
+ | a::l -> fold_left f (f accu a) l
+
+let rec fold_right f l accu =
+ match l with
+ [] -> accu
+ | a::l -> f a (fold_right f l accu)
+
+let rec map2 f l1 l2 =
+ match (l1, l2) with
+ ([], []) -> []
+ | (a1::l1, a2::l2) -> let r = f a1 a2 in r :: map2 f l1 l2
+ | (_, _) -> invalid_arg "List.map2"
+
+let rev_map2 f l1 l2 =
+ let rec rmap2_f accu l1 l2 =
+ match (l1, l2) with
+ | ([], []) -> accu
+ | (a1::l1, a2::l2) -> rmap2_f (f a1 a2 :: accu) l1 l2
+ | (_, _) -> invalid_arg "List.rev_map2"
+ in
+ rmap2_f [] l1 l2
+;;
+
+let rec iter2 f l1 l2 =
+ match (l1, l2) with
+ ([], []) -> ()
+ | (a1::l1, a2::l2) -> f a1 a2; iter2 f l1 l2
+ | (_, _) -> invalid_arg "List.iter2"
+
+let rec fold_left2 f accu l1 l2 =
+ match (l1, l2) with
+ ([], []) -> accu
+ | (a1::l1, a2::l2) -> fold_left2 f (f accu a1 a2) l1 l2
+ | (_, _) -> invalid_arg "List.fold_left2"
+
+let rec fold_right2 f l1 l2 accu =
+ match (l1, l2) with
+ ([], []) -> accu
+ | (a1::l1, a2::l2) -> f a1 a2 (fold_right2 f l1 l2 accu)
+ | (_, _) -> invalid_arg "List.fold_right2"
+
+let rec for_all p = function
+ [] -> true
+ | a::l -> p a && for_all p l
+
+let rec exists p = function
+ [] -> false
+ | a::l -> p a || exists p l
+
+let rec for_all2 p l1 l2 =
+ match (l1, l2) with
+ ([], []) -> true
+ | (a1::l1, a2::l2) -> p a1 a2 && for_all2 p l1 l2
+ | (_, _) -> invalid_arg "List.for_all2"
+
+let rec exists2 p l1 l2 =
+ match (l1, l2) with
+ ([], []) -> false
+ | (a1::l1, a2::l2) -> p a1 a2 || exists2 p l1 l2
+ | (_, _) -> invalid_arg "List.exists2"
+
+let rec mem x = function
+ [] -> false
+ | a::l -> compare a x = 0 || mem x l
+
+let rec memq x = function
+ [] -> false
+ | a::l -> a == x || memq x l
+
+let rec assoc x = function
+ [] -> raise Not_found
+ | (a,b)::l -> if compare a x = 0 then b else assoc x l
+
+let rec assq x = function
+ [] -> raise Not_found
+ | (a,b)::l -> if a == x then b else assq x l
+
+let rec mem_assoc x = function
+ | [] -> false
+ | (a, b) :: l -> compare a x = 0 || mem_assoc x l
+
+let rec mem_assq x = function
+ | [] -> false
+ | (a, b) :: l -> a == x || mem_assq x l
+
+let rec remove_assoc x = function
+ | [] -> []
+ | (a, b as pair) :: l ->
+ if compare a x = 0 then l else pair :: remove_assoc x l
+
+let rec remove_assq x = function
+ | [] -> []
+ | (a, b as pair) :: l -> if a == x then l else pair :: remove_assq x l
+
+let rec find p = function
+ | [] -> raise Not_found
+ | x :: l -> if p x then x else find p l
+
+let find_all p =
+ let rec find accu = function
+ | [] -> rev accu
+ | x :: l -> if p x then find (x :: accu) l else find accu l in
+ find []
+
+let filter = find_all
+
+let partition p l =
+ let rec part yes no = function
+ | [] -> (rev yes, rev no)
+ | x :: l -> if p x then part (x :: yes) no l else part yes (x :: no) l in
+ part [] [] l
+
+let rec split = function
+ [] -> ([], [])
+ | (x,y)::l ->
+ let (rx, ry) = split l in (x::rx, y::ry)
+
+let rec combine l1 l2 =
+ match (l1, l2) with
+ ([], []) -> []
+ | (a1::l1, a2::l2) -> (a1, a2) :: combine l1 l2
+ | (_, _) -> invalid_arg "List.combine"
+
+(** sorting *)
+
+let rec merge cmp l1 l2 =
+ match l1, l2 with
+ | [], l2 -> l2
+ | l1, [] -> l1
+ | h1 :: t1, h2 :: t2 ->
+ if cmp h1 h2 <= 0
+ then h1 :: merge cmp t1 l2
+ else h2 :: merge cmp l1 t2
+;;
+
+let rec chop k l =
+ if k = 0 then l else begin
+ match l with
+ | x::t -> chop (k-1) t
+ | _ -> assert false
+ end
+;;
+
+let stable_sort cmp l =
+ let rec rev_merge l1 l2 accu =
+ match l1, l2 with
+ | [], l2 -> rev_append l2 accu
+ | l1, [] -> rev_append l1 accu
+ | h1::t1, h2::t2 ->
+ if cmp h1 h2 <= 0
+ then rev_merge t1 l2 (h1::accu)
+ else rev_merge l1 t2 (h2::accu)
+ in
+ let rec rev_merge_rev l1 l2 accu =
+ match l1, l2 with
+ | [], l2 -> rev_append l2 accu
+ | l1, [] -> rev_append l1 accu
+ | h1::t1, h2::t2 ->
+ if cmp h1 h2 > 0
+ then rev_merge_rev t1 l2 (h1::accu)
+ else rev_merge_rev l1 t2 (h2::accu)
+ in
+ let rec sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ if cmp x1 x2 <= 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if cmp x1 x2 <= 0 then begin
+ if cmp x2 x3 <= 0 then [x1; x2; x3]
+ else if cmp x1 x3 <= 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ if cmp x1 x3 <= 0 then [x2; x1; x3]
+ else if cmp x2 x3 <= 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ let l2 = chop n1 l in
+ let s1 = rev_sort n1 l in
+ let s2 = rev_sort n2 l2 in
+ rev_merge_rev s1 s2 []
+ and rev_sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ if cmp x1 x2 > 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if cmp x1 x2 > 0 then begin
+ if cmp x2 x3 > 0 then [x1; x2; x3]
+ else if cmp x1 x3 > 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ if cmp x1 x3 > 0 then [x2; x1; x3]
+ else if cmp x2 x3 > 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ let l2 = chop n1 l in
+ let s1 = sort n1 l in
+ let s2 = sort n2 l2 in
+ rev_merge s1 s2 []
+ in
+ let len = length l in
+ if len < 2 then l else sort len l
+;;
+
+let sort = stable_sort;;
+let fast_sort = stable_sort;;
+
+(* Note: on a list of length between about 100000 (depending on the minor
+ heap size and the type of the list) and Sys.max_array_size, it is
+ actually faster to use the following, but it might also use more memory
+ because the argument list cannot be deallocated incrementally.
+
+ Also, there seems to be a bug in this code or in the
+ implementation of obj_truncate.
+
+external obj_truncate : 'a array -> int -> unit = "caml_obj_truncate"
+
+let array_to_list_in_place a =
+ let l = Array.length a in
+ let rec loop accu n p =
+ if p <= 0 then accu else begin
+ if p = n then begin
+ obj_truncate a p;
+ loop (a.(p-1) :: accu) (n-1000) (p-1)
+ end else begin
+ loop (a.(p-1) :: accu) n (p-1)
+ end
+ end
+ in
+ loop [] (l-1000) l
+;;
+
+let stable_sort cmp l =
+ let a = Array.of_list l in
+ Array.stable_sort cmp a;
+ array_to_list_in_place a
+;;
+*)
+
+
+(** sorting + removing duplicates *)
+
+let sort_uniq cmp l =
+ let rec rev_merge l1 l2 accu =
+ match l1, l2 with
+ | [], l2 -> rev_append l2 accu
+ | l1, [] -> rev_append l1 accu
+ | h1::t1, h2::t2 ->
+ let c = cmp h1 h2 in
+ if c = 0 then rev_merge t1 t2 (h1::accu)
+ else if c < 0
+ then rev_merge t1 l2 (h1::accu)
+ else rev_merge l1 t2 (h2::accu)
+ in
+ let rec rev_merge_rev l1 l2 accu =
+ match l1, l2 with
+ | [], l2 -> rev_append l2 accu
+ | l1, [] -> rev_append l1 accu
+ | h1::t1, h2::t2 ->
+ let c = cmp h1 h2 in
+ if c = 0 then rev_merge_rev t1 t2 (h1::accu)
+ else if c > 0
+ then rev_merge_rev t1 l2 (h1::accu)
+ else rev_merge_rev l1 t2 (h2::accu)
+ in
+ let rec sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ let c = cmp x1 x2 in
+ if c = 0 then [x1]
+ else if c < 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ let c = cmp x1 x2 in
+ if c = 0 then begin
+ let c = cmp x2 x3 in
+ if c = 0 then [x2]
+ else if c < 0 then [x2; x3] else [x3; x2]
+ end else if c < 0 then begin
+ let c = cmp x2 x3 in
+ if c = 0 then [x1; x2]
+ else if c < 0 then [x1; x2; x3]
+ else let c = cmp x1 x3 in
+ if c = 0 then [x1; x2]
+ else if c < 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ let c = cmp x1 x3 in
+ if c = 0 then [x2; x1]
+ else if c < 0 then [x2; x1; x3]
+ else let c = cmp x2 x3 in
+ if c = 0 then [x2; x1]
+ else if c < 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ let l2 = chop n1 l in
+ let s1 = rev_sort n1 l in
+ let s2 = rev_sort n2 l2 in
+ rev_merge_rev s1 s2 []
+ and rev_sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ let c = cmp x1 x2 in
+ if c = 0 then [x1]
+ else if c > 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ let c = cmp x1 x2 in
+ if c = 0 then begin
+ let c = cmp x2 x3 in
+ if c = 0 then [x2]
+ else if c > 0 then [x2; x3] else [x3; x2]
+ end else if c > 0 then begin
+ let c = cmp x2 x3 in
+ if c = 0 then [x1; x2]
+ else if c > 0 then [x1; x2; x3]
+ else let c = cmp x1 x3 in
+ if c = 0 then [x1; x2]
+ else if c > 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ let c = cmp x1 x3 in
+ if c = 0 then [x2; x1]
+ else if c > 0 then [x2; x1; x3]
+ else let c = cmp x2 x3 in
+ if c = 0 then [x2; x1]
+ else if c > 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ let l2 = chop n1 l in
+ let s1 = sort n1 l in
+ let s2 = sort n2 l2 in
+ rev_merge s1 s2 []
+ in
+ let len = length l in
+ if len < 2 then l else sort len l
+;;
diff --git a/stdlib/list.mli b/stdlib/list.mli
new file mode 100644
index 0000000000..77cf5d5db6
--- /dev/null
+++ b/stdlib/list.mli
@@ -0,0 +1,298 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** List operations.
+
+ Some functions are flagged as not tail-recursive. A tail-recursive
+ function uses constant stack space, while a non-tail-recursive function
+ uses stack space proportional to the length of its list argument, which
+ can be a problem with very long lists. When the function takes several
+ list arguments, an approximate formula giving stack usage (in some
+ unspecified constant unit) is shown in parentheses.
+
+ The above considerations can usually be ignored if your lists are not
+ longer than about 10000 elements.
+*)
+
+val length : 'a list -> int
+(** Return the length (number of elements) of the given list. *)
+
+val cons : 'a -> 'a list -> 'a list
+(** [cons x xs] is [x :: xs]
+ @since 4.03.0
+*)
+
+val hd : 'a list -> 'a
+(** Return the first element of the given list. Raise
+ [Failure "hd"] if the list is empty. *)
+
+val tl : 'a list -> 'a list
+(** Return the given list without its first element. Raise
+ [Failure "tl"] if the list is empty. *)
+
+val nth : 'a list -> int -> 'a
+(** Return the [n]-th element of the given list.
+ The first element (head of the list) is at position 0.
+ Raise [Failure "nth"] if the list is too short.
+ Raise [Invalid_argument "List.nth"] if [n] is negative. *)
+
+val rev : 'a list -> 'a list
+(** List reversal. *)
+
+val append : 'a list -> 'a list -> 'a list
+(** Catenate two lists. Same function as the infix operator [@].
+ Not tail-recursive (length of the first argument). The [@]
+ operator is not tail-recursive either. *)
+
+val rev_append : 'a list -> 'a list -> 'a list
+(** [List.rev_append l1 l2] reverses [l1] and concatenates it to [l2].
+ This is equivalent to {!List.rev}[ l1 @ l2], but [rev_append] is
+ tail-recursive and more efficient. *)
+
+val concat : 'a list list -> 'a list
+(** Concatenate a list of lists. The elements of the argument are all
+ concatenated together (in the same order) to give the result.
+ Not tail-recursive
+ (length of the argument + length of the longest sub-list). *)
+
+val flatten : 'a list list -> 'a list
+(** Same as [concat]. Not tail-recursive
+ (length of the argument + length of the longest sub-list). *)
+
+
+(** {6 Iterators} *)
+
+
+val iter : ('a -> unit) -> 'a list -> unit
+(** [List.iter f [a1; ...; an]] applies function [f] in turn to
+ [a1; ...; an]. It is equivalent to
+ [begin f a1; f a2; ...; f an; () end]. *)
+
+val iteri : (int -> 'a -> unit) -> 'a list -> unit
+(** Same as {!List.iter}, but the function is applied to the index of
+ the element as first argument (counting from 0), and the element
+ itself as second argument.
+ @since 4.00.0
+*)
+
+val map : ('a -> 'b) -> 'a list -> 'b list
+(** [List.map f [a1; ...; an]] applies function [f] to [a1, ..., an],
+ and builds the list [[f a1; ...; f an]]
+ with the results returned by [f]. Not tail-recursive. *)
+
+val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list
+(** Same as {!List.map}, but the function is applied to the index of
+ the element as first argument (counting from 0), and the element
+ itself as second argument. Not tail-recursive.
+ @since 4.00.0
+*)
+
+val rev_map : ('a -> 'b) -> 'a list -> 'b list
+(** [List.rev_map f l] gives the same result as
+ {!List.rev}[ (]{!List.map}[ f l)], but is tail-recursive and
+ more efficient. *)
+
+val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
+(** [List.fold_left f a [b1; ...; bn]] is
+ [f (... (f (f a b1) b2) ...) bn]. *)
+
+val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
+(** [List.fold_right f [a1; ...; an] b] is
+ [f a1 (f a2 (... (f an b) ...))]. Not tail-recursive. *)
+
+
+(** {6 Iterators on two lists} *)
+
+
+val iter2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit
+(** [List.iter2 f [a1; ...; an] [b1; ...; bn]] calls in turn
+ [f a1 b1; ...; f an bn].
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. *)
+
+val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
+(** [List.map2 f [a1; ...; an] [b1; ...; bn]] is
+ [[f a1 b1; ...; f an bn]].
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. Not tail-recursive. *)
+
+val rev_map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
+(** [List.rev_map2 f l1 l2] gives the same result as
+ {!List.rev}[ (]{!List.map2}[ f l1 l2)], but is tail-recursive and
+ more efficient. *)
+
+val fold_left2 : ('a -> 'b -> 'c -> 'a) -> 'a -> 'b list -> 'c list -> 'a
+(** [List.fold_left2 f a [b1; ...; bn] [c1; ...; cn]] is
+ [f (... (f (f a b1 c1) b2 c2) ...) bn cn].
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. *)
+
+val fold_right2 : ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
+(** [List.fold_right2 f [a1; ...; an] [b1; ...; bn] c] is
+ [f a1 b1 (f a2 b2 (... (f an bn c) ...))].
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. Not tail-recursive. *)
+
+
+(** {6 List scanning} *)
+
+
+val for_all : ('a -> bool) -> 'a list -> bool
+(** [for_all p [a1; ...; an]] checks if all elements of the list
+ satisfy the predicate [p]. That is, it returns
+ [(p a1) && (p a2) && ... && (p an)]. *)
+
+val exists : ('a -> bool) -> 'a list -> bool
+(** [exists p [a1; ...; an]] checks if at least one element of
+ the list satisfies the predicate [p]. That is, it returns
+ [(p a1) || (p a2) || ... || (p an)]. *)
+
+val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
+(** Same as {!List.for_all}, but for a two-argument predicate.
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. *)
+
+val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
+(** Same as {!List.exists}, but for a two-argument predicate.
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. *)
+
+val mem : 'a -> 'a list -> bool
+(** [mem a l] is true if and only if [a] is equal
+ to an element of [l]. *)
+
+val memq : 'a -> 'a list -> bool
+(** Same as {!List.mem}, but uses physical equality instead of structural
+ equality to compare list elements. *)
+
+
+(** {6 List searching} *)
+
+
+val find : ('a -> bool) -> 'a list -> 'a
+(** [find p l] returns the first element of the list [l]
+ that satisfies the predicate [p].
+ Raise [Not_found] if there is no value that satisfies [p] in the
+ list [l]. *)
+
+val filter : ('a -> bool) -> 'a list -> 'a list
+(** [filter p l] returns all the elements of the list [l]
+ that satisfy the predicate [p]. The order of the elements
+ in the input list is preserved. *)
+
+val find_all : ('a -> bool) -> 'a list -> 'a list
+(** [find_all] is another name for {!List.filter}. *)
+
+val partition : ('a -> bool) -> 'a list -> 'a list * 'a list
+(** [partition p l] returns a pair of lists [(l1, l2)], where
+ [l1] is the list of all the elements of [l] that
+ satisfy the predicate [p], and [l2] is the list of all the
+ elements of [l] that do not satisfy [p].
+ The order of the elements in the input list is preserved. *)
+
+
+(** {6 Association lists} *)
+
+
+val assoc : 'a -> ('a * 'b) list -> 'b
+(** [assoc a l] returns the value associated with key [a] in the list of
+ pairs [l]. That is,
+ [assoc a [ ...; (a,b); ...] = b]
+ if [(a,b)] is the leftmost binding of [a] in list [l].
+ Raise [Not_found] if there is no value associated with [a] in the
+ list [l]. *)
+
+val assq : 'a -> ('a * 'b) list -> 'b
+(** Same as {!List.assoc}, but uses physical equality instead of structural
+ equality to compare keys. *)
+
+val mem_assoc : 'a -> ('a * 'b) list -> bool
+(** Same as {!List.assoc}, but simply return true if a binding exists,
+ and false if no bindings exist for the given key. *)
+
+val mem_assq : 'a -> ('a * 'b) list -> bool
+(** Same as {!List.mem_assoc}, but uses physical equality instead of
+ structural equality to compare keys. *)
+
+val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
+(** [remove_assoc a l] returns the list of
+ pairs [l] without the first pair with key [a], if any.
+ Not tail-recursive. *)
+
+val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
+(** Same as {!List.remove_assoc}, but uses physical equality instead
+ of structural equality to compare keys. Not tail-recursive. *)
+
+
+(** {6 Lists of pairs} *)
+
+
+val split : ('a * 'b) list -> 'a list * 'b list
+(** Transform a list of pairs into a pair of lists:
+ [split [(a1,b1); ...; (an,bn)]] is [([a1; ...; an], [b1; ...; bn])].
+ Not tail-recursive.
+*)
+
+val combine : 'a list -> 'b list -> ('a * 'b) list
+(** Transform a pair of lists into a list of pairs:
+ [combine [a1; ...; an] [b1; ...; bn]] is
+ [[(a1,b1); ...; (an,bn)]].
+ Raise [Invalid_argument] if the two lists
+ have different lengths. Not tail-recursive. *)
+
+
+(** {6 Sorting} *)
+
+
+val sort : ('a -> 'a -> int) -> 'a list -> 'a list
+(** Sort a list in increasing order according to a comparison
+ function. The comparison function must return 0 if its arguments
+ compare as equal, a positive integer if the first is greater,
+ and a negative integer if the first is smaller (see Array.sort for
+ a complete specification). For example,
+ {!Pervasives.compare} is a suitable comparison function.
+ The resulting list is sorted in increasing order.
+ [List.sort] is guaranteed to run in constant heap space
+ (in addition to the size of the result list) and logarithmic
+ stack space.
+
+ The current implementation uses Merge Sort. It runs in constant
+ heap space and logarithmic stack space.
+*)
+
+val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list
+(** Same as {!List.sort}, but the sorting algorithm is guaranteed to
+ be stable (i.e. elements that compare equal are kept in their
+ original order) .
+
+ The current implementation uses Merge Sort. It runs in constant
+ heap space and logarithmic stack space.
+*)
+
+val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list
+(** Same as {!List.sort} or {!List.stable_sort}, whichever is faster
+ on typical input. *)
+
+val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list
+(** Same as {!List.sort}, but also remove duplicates.
+ @since 4.02.0 *)
+
+val merge : ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
+(** Merge two lists:
+ Assuming that [l1] and [l2] are sorted according to the
+ comparison function [cmp], [merge cmp l1 l2] will return a
+ sorted list containting all the elements of [l1] and [l2].
+ If several elements compare equal, the elements of [l1] will be
+ before the elements of [l2].
+ Not tail-recursive (sum of the lengths of the arguments).
+*)
diff --git a/stdlib/listLabels.ml b/stdlib/listLabels.ml
new file mode 100644
index 0000000000..1f0684bfc7
--- /dev/null
+++ b/stdlib/listLabels.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [ListLabels]: labelled List module *)
+
+include List
diff --git a/stdlib/listLabels.mli b/stdlib/listLabels.mli
new file mode 100644
index 0000000000..a37056b414
--- /dev/null
+++ b/stdlib/listLabels.mli
@@ -0,0 +1,295 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** List operations.
+
+ Some functions are flagged as not tail-recursive. A tail-recursive
+ function uses constant stack space, while a non-tail-recursive function
+ uses stack space proportional to the length of its list argument, which
+ can be a problem with very long lists. When the function takes several
+ list arguments, an approximate formula giving stack usage (in some
+ unspecified constant unit) is shown in parentheses.
+
+ The above considerations can usually be ignored if your lists are not
+ longer than about 10000 elements.
+*)
+
+val length : 'a list -> int
+(** Return the length (number of elements) of the given list. *)
+
+val hd : 'a list -> 'a
+(** Return the first element of the given list. Raise
+ [Failure "hd"] if the list is empty. *)
+
+val tl : 'a list -> 'a list
+(** Return the given list without its first element. Raise
+ [Failure "tl"] if the list is empty. *)
+
+val nth : 'a list -> int -> 'a
+(** Return the [n]-th element of the given list.
+ The first element (head of the list) is at position 0.
+ Raise [Failure "nth"] if the list is too short.
+ Raise [Invalid_argument "List.nth"] if [n] is negative. *)
+
+val rev : 'a list -> 'a list
+(** List reversal. *)
+
+val append : 'a list -> 'a list -> 'a list
+(** Catenate two lists. Same function as the infix operator [@].
+ Not tail-recursive (length of the first argument). The [@]
+ operator is not tail-recursive either. *)
+
+val rev_append : 'a list -> 'a list -> 'a list
+(** [ListLabels.rev_append l1 l2] reverses [l1] and concatenates it to [l2].
+ This is equivalent to {!ListLabels.rev}[ l1 @ l2], but [rev_append] is
+ tail-recursive and more efficient. *)
+
+val concat : 'a list list -> 'a list
+(** Concatenate a list of lists. The elements of the argument are all
+ concatenated together (in the same order) to give the result.
+ Not tail-recursive
+ (length of the argument + length of the longest sub-list). *)
+
+val flatten : 'a list list -> 'a list
+(** Same as [concat]. Not tail-recursive
+ (length of the argument + length of the longest sub-list). *)
+
+
+(** {6 Iterators} *)
+
+
+val iter : f:('a -> unit) -> 'a list -> unit
+(** [ListLabels.iter f [a1; ...; an]] applies function [f] in turn to
+ [a1; ...; an]. It is equivalent to
+ [begin f a1; f a2; ...; f an; () end]. *)
+
+val iteri : f:(int -> 'a -> unit) -> 'a list -> unit
+(** Same as {!ListLabels.iter}, but the function is applied to the index of
+ the element as first argument (counting from 0), and the element
+ itself as second argument.
+ @since 4.00.0
+*)
+
+val map : f:('a -> 'b) -> 'a list -> 'b list
+(** [ListLabels.map f [a1; ...; an]] applies function [f] to [a1, ..., an],
+ and builds the list [[f a1; ...; f an]]
+ with the results returned by [f]. Not tail-recursive. *)
+
+val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list
+(** Same as {!ListLabels.map}, but the function is applied to the index of
+ the element as first argument (counting from 0), and the element
+ itself as second argument.
+ @since 4.00.0
+*)
+
+val rev_map : f:('a -> 'b) -> 'a list -> 'b list
+(** [ListLabels.rev_map f l] gives the same result as
+ {!ListLabels.rev}[ (]{!ListLabels.map}[ f l)], but is tail-recursive and
+ more efficient. *)
+
+val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a
+(** [ListLabels.fold_left f a [b1; ...; bn]] is
+ [f (... (f (f a b1) b2) ...) bn]. *)
+
+val fold_right : f:('a -> 'b -> 'b) -> 'a list -> init:'b -> 'b
+(** [ListLabels.fold_right f [a1; ...; an] b] is
+ [f a1 (f a2 (... (f an b) ...))]. Not tail-recursive. *)
+
+
+(** {6 Iterators on two lists} *)
+
+
+val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit
+(** [ListLabels.iter2 f [a1; ...; an] [b1; ...; bn]] calls in turn
+ [f a1 b1; ...; f an bn].
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. *)
+
+val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
+(** [ListLabels.map2 f [a1; ...; an] [b1; ...; bn]] is
+ [[f a1 b1; ...; f an bn]].
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. Not tail-recursive. *)
+
+val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
+(** [ListLabels.rev_map2 f l1 l2] gives the same result as
+ {!ListLabels.rev}[ (]{!ListLabels.map2}[ f l1 l2)], but is tail-recursive and
+ more efficient. *)
+
+val fold_left2 :
+ f:('a -> 'b -> 'c -> 'a) -> init:'a -> 'b list -> 'c list -> 'a
+(** [ListLabels.fold_left2 f a [b1; ...; bn] [c1; ...; cn]] is
+ [f (... (f (f a b1 c1) b2 c2) ...) bn cn].
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. *)
+
+val fold_right2 :
+ f:('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> init:'c -> 'c
+(** [ListLabels.fold_right2 f [a1; ...; an] [b1; ...; bn] c] is
+ [f a1 b1 (f a2 b2 (... (f an bn c) ...))].
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. Not tail-recursive. *)
+
+
+(** {6 List scanning} *)
+
+
+val for_all : f:('a -> bool) -> 'a list -> bool
+(** [for_all p [a1; ...; an]] checks if all elements of the list
+ satisfy the predicate [p]. That is, it returns
+ [(p a1) && (p a2) && ... && (p an)]. *)
+
+val exists : f:('a -> bool) -> 'a list -> bool
+(** [exists p [a1; ...; an]] checks if at least one element of
+ the list satisfies the predicate [p]. That is, it returns
+ [(p a1) || (p a2) || ... || (p an)]. *)
+
+val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
+(** Same as {!ListLabels.for_all}, but for a two-argument predicate.
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. *)
+
+val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool
+(** Same as {!ListLabels.exists}, but for a two-argument predicate.
+ Raise [Invalid_argument] if the two lists are determined
+ to have different lengths. *)
+
+val mem : 'a -> set:'a list -> bool
+(** [mem a l] is true if and only if [a] is equal
+ to an element of [l]. *)
+
+val memq : 'a -> set:'a list -> bool
+(** Same as {!ListLabels.mem}, but uses physical equality instead of structural
+ equality to compare list elements. *)
+
+
+(** {6 List searching} *)
+
+
+val find : f:('a -> bool) -> 'a list -> 'a
+(** [find p l] returns the first element of the list [l]
+ that satisfies the predicate [p].
+ Raise [Not_found] if there is no value that satisfies [p] in the
+ list [l]. *)
+
+val filter : f:('a -> bool) -> 'a list -> 'a list
+(** [filter p l] returns all the elements of the list [l]
+ that satisfy the predicate [p]. The order of the elements
+ in the input list is preserved. *)
+
+val find_all : f:('a -> bool) -> 'a list -> 'a list
+(** [find_all] is another name for {!ListLabels.filter}. *)
+
+val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list
+(** [partition p l] returns a pair of lists [(l1, l2)], where
+ [l1] is the list of all the elements of [l] that
+ satisfy the predicate [p], and [l2] is the list of all the
+ elements of [l] that do not satisfy [p].
+ The order of the elements in the input list is preserved. *)
+
+
+(** {6 Association lists} *)
+
+
+val assoc : 'a -> ('a * 'b) list -> 'b
+(** [assoc a l] returns the value associated with key [a] in the list of
+ pairs [l]. That is,
+ [assoc a [ ...; (a,b); ...] = b]
+ if [(a,b)] is the leftmost binding of [a] in list [l].
+ Raise [Not_found] if there is no value associated with [a] in the
+ list [l]. *)
+
+val assq : 'a -> ('a * 'b) list -> 'b
+(** Same as {!ListLabels.assoc}, but uses physical equality instead of
+ structural equality to compare keys. *)
+
+val mem_assoc : 'a -> map:('a * 'b) list -> bool
+(** Same as {!ListLabels.assoc}, but simply return true if a binding exists,
+ and false if no bindings exist for the given key. *)
+
+val mem_assq : 'a -> map:('a * 'b) list -> bool
+(** Same as {!ListLabels.mem_assoc}, but uses physical equality instead of
+ structural equality to compare keys. *)
+
+val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list
+(** [remove_assoc a l] returns the list of
+ pairs [l] without the first pair with key [a], if any.
+ Not tail-recursive. *)
+
+val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list
+(** Same as {!ListLabels.remove_assoc}, but uses physical equality instead
+ of structural equality to compare keys. Not tail-recursive. *)
+
+
+(** {6 Lists of pairs} *)
+
+
+val split : ('a * 'b) list -> 'a list * 'b list
+(** Transform a list of pairs into a pair of lists:
+ [split [(a1,b1); ...; (an,bn)]] is [([a1; ...; an], [b1; ...; bn])].
+ Not tail-recursive.
+*)
+
+val combine : 'a list -> 'b list -> ('a * 'b) list
+(** Transform a pair of lists into a list of pairs:
+ [combine [a1; ...; an] [b1; ...; bn]] is
+ [[(a1,b1); ...; (an,bn)]].
+ Raise [Invalid_argument] if the two lists
+ have different lengths. Not tail-recursive. *)
+
+
+(** {6 Sorting} *)
+
+
+val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
+(** Sort a list in increasing order according to a comparison
+ function. The comparison function must return 0 if its arguments
+ compare as equal, a positive integer if the first is greater,
+ and a negative integer if the first is smaller (see Array.sort for
+ a complete specification). For example,
+ {!Pervasives.compare} is a suitable comparison function.
+ The resulting list is sorted in increasing order.
+ [ListLabels.sort] is guaranteed to run in constant heap space
+ (in addition to the size of the result list) and logarithmic
+ stack space.
+
+ The current implementation uses Merge Sort. It runs in constant
+ heap space and logarithmic stack space.
+*)
+
+val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
+(** Same as {!ListLabels.sort}, but the sorting algorithm is guaranteed to
+ be stable (i.e. elements that compare equal are kept in their
+ original order) .
+
+ The current implementation uses Merge Sort. It runs in constant
+ heap space and logarithmic stack space.
+*)
+
+val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list
+(** Same as {!ListLabels.sort} or {!ListLabels.stable_sort}, whichever is
+ faster on typical input. *)
+
+val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list
+(** Same as {!ListLabels.sort}, but also remove duplicates.
+ @since 4.02.0 *)
+
+val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list
+(** Merge two lists:
+ Assuming that [l1] and [l2] are sorted according to the
+ comparison function [cmp], [merge cmp l1 l2] will return a
+ sorted list containting all the elements of [l1] and [l2].
+ If several elements compare equal, the elements of [l1] will be
+ before the elements of [l2].
+ Not tail-recursive (sum of the lengths of the arguments).
+*)
diff --git a/stdlib/map.ml b/stdlib/map.ml
new file mode 100644
index 0000000000..7d65bc6bc9
--- /dev/null
+++ b/stdlib/map.ml
@@ -0,0 +1,337 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+module type OrderedType =
+ sig
+ type t
+ val compare: t -> t -> int
+ end
+
+module type S =
+ sig
+ type key
+ type +'a t
+ val empty: 'a t
+ val is_empty: 'a t -> bool
+ val mem: key -> 'a t -> bool
+ val add: key -> 'a -> 'a t -> 'a t
+ val singleton: key -> 'a -> 'a t
+ val remove: key -> 'a t -> 'a t
+ val merge:
+ (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
+ val compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int
+ val equal: ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
+ val iter: (key -> 'a -> unit) -> 'a t -> unit
+ val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ val for_all: (key -> 'a -> bool) -> 'a t -> bool
+ val exists: (key -> 'a -> bool) -> 'a t -> bool
+ val filter: (key -> 'a -> bool) -> 'a t -> 'a t
+ val partition: (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
+ val cardinal: 'a t -> int
+ val bindings: 'a t -> (key * 'a) list
+ val min_binding: 'a t -> (key * 'a)
+ val max_binding: 'a t -> (key * 'a)
+ val choose: 'a t -> (key * 'a)
+ val split: key -> 'a t -> 'a t * 'a option * 'a t
+ val find: key -> 'a t -> 'a
+ val map: ('a -> 'b) -> 'a t -> 'b t
+ val mapi: (key -> 'a -> 'b) -> 'a t -> 'b t
+ end
+
+module Make(Ord: OrderedType) = struct
+
+ type key = Ord.t
+
+ type 'a t =
+ Empty
+ | Node of 'a t * key * 'a * 'a t * int
+
+ let height = function
+ Empty -> 0
+ | Node(_,_,_,_,h) -> h
+
+ let create l x d r =
+ let hl = height l and hr = height r in
+ Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
+
+ let singleton x d = Node(Empty, x, d, Empty, 1)
+
+ let bal l x d r =
+ let hl = match l with Empty -> 0 | Node(_,_,_,_,h) -> h in
+ let hr = match r with Empty -> 0 | Node(_,_,_,_,h) -> h in
+ if hl > hr + 2 then begin
+ match l with
+ Empty -> invalid_arg "Map.bal"
+ | Node(ll, lv, ld, lr, _) ->
+ if height ll >= height lr then
+ create ll lv ld (create lr x d r)
+ else begin
+ match lr with
+ Empty -> invalid_arg "Map.bal"
+ | Node(lrl, lrv, lrd, lrr, _)->
+ create (create ll lv ld lrl) lrv lrd (create lrr x d r)
+ end
+ end else if hr > hl + 2 then begin
+ match r with
+ Empty -> invalid_arg "Map.bal"
+ | Node(rl, rv, rd, rr, _) ->
+ if height rr >= height rl then
+ create (create l x d rl) rv rd rr
+ else begin
+ match rl with
+ Empty -> invalid_arg "Map.bal"
+ | Node(rll, rlv, rld, rlr, _) ->
+ create (create l x d rll) rlv rld (create rlr rv rd rr)
+ end
+ end else
+ Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
+
+ let empty = Empty
+
+ let is_empty = function Empty -> true | _ -> false
+
+ let rec add x data = function
+ Empty ->
+ Node(Empty, x, data, Empty, 1)
+ | Node(l, v, d, r, h) ->
+ let c = Ord.compare x v in
+ if c = 0 then
+ Node(l, x, data, r, h)
+ else if c < 0 then
+ bal (add x data l) v d r
+ else
+ bal l v d (add x data r)
+
+ let rec find x = function
+ Empty ->
+ raise Not_found
+ | Node(l, v, d, r, _) ->
+ let c = Ord.compare x v in
+ if c = 0 then d
+ else find x (if c < 0 then l else r)
+
+ let rec mem x = function
+ Empty ->
+ false
+ | Node(l, v, d, r, _) ->
+ let c = Ord.compare x v in
+ c = 0 || mem x (if c < 0 then l else r)
+
+ let rec min_binding = function
+ Empty -> raise Not_found
+ | Node(Empty, x, d, r, _) -> (x, d)
+ | Node(l, x, d, r, _) -> min_binding l
+
+ let rec max_binding = function
+ Empty -> raise Not_found
+ | Node(l, x, d, Empty, _) -> (x, d)
+ | Node(l, x, d, r, _) -> max_binding r
+
+ let rec remove_min_binding = function
+ Empty -> invalid_arg "Map.remove_min_elt"
+ | Node(Empty, x, d, r, _) -> r
+ | Node(l, x, d, r, _) -> bal (remove_min_binding l) x d r
+
+ let merge t1 t2 =
+ match (t1, t2) with
+ (Empty, t) -> t
+ | (t, Empty) -> t
+ | (_, _) ->
+ let (x, d) = min_binding t2 in
+ bal t1 x d (remove_min_binding t2)
+
+ let rec remove x = function
+ Empty ->
+ Empty
+ | Node(l, v, d, r, h) ->
+ let c = Ord.compare x v in
+ if c = 0 then
+ merge l r
+ else if c < 0 then
+ bal (remove x l) v d r
+ else
+ bal l v d (remove x r)
+
+ let rec iter f = function
+ Empty -> ()
+ | Node(l, v, d, r, _) ->
+ iter f l; f v d; iter f r
+
+ let rec map f = function
+ Empty ->
+ Empty
+ | Node(l, v, d, r, h) ->
+ let l' = map f l in
+ let d' = f d in
+ let r' = map f r in
+ Node(l', v, d', r', h)
+
+ let rec mapi f = function
+ Empty ->
+ Empty
+ | Node(l, v, d, r, h) ->
+ let l' = mapi f l in
+ let d' = f v d in
+ let r' = mapi f r in
+ Node(l', v, d', r', h)
+
+ let rec fold f m accu =
+ match m with
+ Empty -> accu
+ | Node(l, v, d, r, _) ->
+ fold f r (f v d (fold f l accu))
+
+ let rec for_all p = function
+ Empty -> true
+ | Node(l, v, d, r, _) -> p v d && for_all p l && for_all p r
+
+ let rec exists p = function
+ Empty -> false
+ | Node(l, v, d, r, _) -> p v d || exists p l || exists p r
+
+ (* Beware: those two functions assume that the added k is *strictly*
+ smaller (or bigger) than all the present keys in the tree; it
+ does not test for equality with the current min (or max) key.
+
+ Indeed, they are only used during the "join" operation which
+ respects this precondition.
+ *)
+
+ let rec add_min_binding k v = function
+ | Empty -> singleton k v
+ | Node (l, x, d, r, h) ->
+ bal (add_min_binding k v l) x d r
+
+ let rec add_max_binding k v = function
+ | Empty -> singleton k v
+ | Node (l, x, d, r, h) ->
+ bal l x d (add_max_binding k v r)
+
+ (* Same as create and bal, but no assumptions are made on the
+ relative heights of l and r. *)
+
+ let rec join l v d r =
+ match (l, r) with
+ (Empty, _) -> add_min_binding v d r
+ | (_, Empty) -> add_max_binding v d l
+ | (Node(ll, lv, ld, lr, lh), Node(rl, rv, rd, rr, rh)) ->
+ if lh > rh + 2 then bal ll lv ld (join lr v d r) else
+ if rh > lh + 2 then bal (join l v d rl) rv rd rr else
+ create l v d r
+
+ (* Merge two trees l and r into one.
+ All elements of l must precede the elements of r.
+ No assumption on the heights of l and r. *)
+
+ let concat t1 t2 =
+ match (t1, t2) with
+ (Empty, t) -> t
+ | (t, Empty) -> t
+ | (_, _) ->
+ let (x, d) = min_binding t2 in
+ join t1 x d (remove_min_binding t2)
+
+ let concat_or_join t1 v d t2 =
+ match d with
+ | Some d -> join t1 v d t2
+ | None -> concat t1 t2
+
+ let rec split x = function
+ Empty ->
+ (Empty, None, Empty)
+ | Node(l, v, d, r, _) ->
+ let c = Ord.compare x v in
+ if c = 0 then (l, Some d, r)
+ else if c < 0 then
+ let (ll, pres, rl) = split x l in (ll, pres, join rl v d r)
+ else
+ let (lr, pres, rr) = split x r in (join l v d lr, pres, rr)
+
+ let rec merge f s1 s2 =
+ match (s1, s2) with
+ (Empty, Empty) -> Empty
+ | (Node (l1, v1, d1, r1, h1), _) when h1 >= height s2 ->
+ let (l2, d2, r2) = split v1 s2 in
+ concat_or_join (merge f l1 l2) v1 (f v1 (Some d1) d2) (merge f r1 r2)
+ | (_, Node (l2, v2, d2, r2, h2)) ->
+ let (l1, d1, r1) = split v2 s1 in
+ concat_or_join (merge f l1 l2) v2 (f v2 d1 (Some d2)) (merge f r1 r2)
+ | _ ->
+ assert false
+
+ let rec filter p = function
+ Empty -> Empty
+ | Node(l, v, d, r, _) ->
+ (* call [p] in the expected left-to-right order *)
+ let l' = filter p l in
+ let pvd = p v d in
+ let r' = filter p r in
+ if pvd then join l' v d r' else concat l' r'
+
+ let rec partition p = function
+ Empty -> (Empty, Empty)
+ | Node(l, v, d, r, _) ->
+ (* call [p] in the expected left-to-right order *)
+ let (lt, lf) = partition p l in
+ let pvd = p v d in
+ let (rt, rf) = partition p r in
+ if pvd
+ then (join lt v d rt, concat lf rf)
+ else (concat lt rt, join lf v d rf)
+
+ type 'a enumeration = End | More of key * 'a * 'a t * 'a enumeration
+
+ let rec cons_enum m e =
+ match m with
+ Empty -> e
+ | Node(l, v, d, r, _) -> cons_enum l (More(v, d, r, e))
+
+ let compare cmp m1 m2 =
+ let rec compare_aux e1 e2 =
+ match (e1, e2) with
+ (End, End) -> 0
+ | (End, _) -> -1
+ | (_, End) -> 1
+ | (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) ->
+ let c = Ord.compare v1 v2 in
+ if c <> 0 then c else
+ let c = cmp d1 d2 in
+ if c <> 0 then c else
+ compare_aux (cons_enum r1 e1) (cons_enum r2 e2)
+ in compare_aux (cons_enum m1 End) (cons_enum m2 End)
+
+ let equal cmp m1 m2 =
+ let rec equal_aux e1 e2 =
+ match (e1, e2) with
+ (End, End) -> true
+ | (End, _) -> false
+ | (_, End) -> false
+ | (More(v1, d1, r1, e1), More(v2, d2, r2, e2)) ->
+ Ord.compare v1 v2 = 0 && cmp d1 d2 &&
+ equal_aux (cons_enum r1 e1) (cons_enum r2 e2)
+ in equal_aux (cons_enum m1 End) (cons_enum m2 End)
+
+ let rec cardinal = function
+ Empty -> 0
+ | Node(l, _, _, r, _) -> cardinal l + 1 + cardinal r
+
+ let rec bindings_aux accu = function
+ Empty -> accu
+ | Node(l, v, d, r, _) -> bindings_aux ((v, d) :: bindings_aux accu r) l
+
+ let bindings s =
+ bindings_aux [] s
+
+ let choose = min_binding
+
+end
diff --git a/stdlib/map.mli b/stdlib/map.mli
new file mode 100644
index 0000000000..abf4531618
--- /dev/null
+++ b/stdlib/map.mli
@@ -0,0 +1,212 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Association tables over ordered types.
+
+ This module implements applicative association tables, also known as
+ finite maps or dictionaries, given a total ordering function
+ over the keys.
+ All operations over maps are purely applicative (no side-effects).
+ The implementation uses balanced binary trees, and therefore searching
+ and insertion take time logarithmic in the size of the map.
+
+ For instance:
+ {[
+ module IntPairs =
+ struct
+ type t = int * int
+ let compare (x0,y0) (x1,y1) =
+ match Pervasives.compare x0 x1 with
+ 0 -> Pervasives.compare y0 y1
+ | c -> c
+ end
+
+ module PairsMap = Map.Make(IntPairs)
+
+ let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world")
+ ]}
+
+ This creates a new module [PairsMap], with a new type ['a PairsMap.t]
+ of maps from [int * int] to ['a]. In this example, [m] contains [string]
+ values so its type is [string PairsMap.t].
+*)
+
+module type OrderedType =
+ sig
+ type t
+ (** The type of the map keys. *)
+ val compare : t -> t -> int
+ (** A total ordering function over the keys.
+ This is a two-argument function [f] such that
+ [f e1 e2] is zero if the keys [e1] and [e2] are equal,
+ [f e1 e2] is strictly negative if [e1] is smaller than [e2],
+ and [f e1 e2] is strictly positive if [e1] is greater than [e2].
+ Example: a suitable ordering function is the generic structural
+ comparison function {!Pervasives.compare}. *)
+ end
+(** Input signature of the functor {!Map.Make}. *)
+
+module type S =
+ sig
+ type key
+ (** The type of the map keys. *)
+
+ type (+'a) t
+ (** The type of maps from type [key] to type ['a]. *)
+
+ val empty: 'a t
+ (** The empty map. *)
+
+ val is_empty: 'a t -> bool
+ (** Test whether a map is empty or not. *)
+
+ val mem: key -> 'a t -> bool
+ (** [mem x m] returns [true] if [m] contains a binding for [x],
+ and [false] otherwise. *)
+
+ val add: key -> 'a -> 'a t -> 'a t
+ (** [add x y m] returns a map containing the same bindings as
+ [m], plus a binding of [x] to [y]. If [x] was already bound
+ in [m], its previous binding disappears. *)
+
+ val singleton: key -> 'a -> 'a t
+ (** [singleton x y] returns the one-element map that contains a binding [y]
+ for [x].
+ @since 3.12.0
+ *)
+
+ val remove: key -> 'a t -> 'a t
+ (** [remove x m] returns a map containing the same bindings as
+ [m], except for [x] which is unbound in the returned map. *)
+
+ val merge:
+ (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
+ (** [merge f m1 m2] computes a map whose keys is a subset of keys of [m1]
+ and of [m2]. The presence of each such binding, and the corresponding
+ value, is determined with the function [f].
+ @since 3.12.0
+ *)
+
+ val compare: ('a -> 'a -> int) -> 'a t -> 'a t -> int
+ (** Total ordering between maps. The first argument is a total ordering
+ used to compare data associated with equal keys in the two maps. *)
+
+ val equal: ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
+ (** [equal cmp m1 m2] tests whether the maps [m1] and [m2] are
+ equal, that is, contain equal keys and associate them with
+ equal data. [cmp] is the equality predicate used to compare
+ the data associated with the keys. *)
+
+ val iter: (key -> 'a -> unit) -> 'a t -> unit
+ (** [iter f m] applies [f] to all bindings in map [m].
+ [f] receives the key as first argument, and the associated value
+ as second argument. The bindings are passed to [f] in increasing
+ order with respect to the ordering over the type of the keys. *)
+
+ val fold: (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ (** [fold f m a] computes [(f kN dN ... (f k1 d1 a)...)],
+ where [k1 ... kN] are the keys of all bindings in [m]
+ (in increasing order), and [d1 ... dN] are the associated data. *)
+
+ val for_all: (key -> 'a -> bool) -> 'a t -> bool
+ (** [for_all p m] checks if all the bindings of the map
+ satisfy the predicate [p].
+ @since 3.12.0
+ *)
+
+ val exists: (key -> 'a -> bool) -> 'a t -> bool
+ (** [exists p m] checks if at least one binding of the map
+ satisfy the predicate [p].
+ @since 3.12.0
+ *)
+
+ val filter: (key -> 'a -> bool) -> 'a t -> 'a t
+ (** [filter p m] returns the map with all the bindings in [m]
+ that satisfy predicate [p].
+ @since 3.12.0
+ *)
+
+ val partition: (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
+ (** [partition p m] returns a pair of maps [(m1, m2)], where
+ [m1] contains all the bindings of [s] that satisfy the
+ predicate [p], and [m2] is the map with all the bindings of
+ [s] that do not satisfy [p].
+ @since 3.12.0
+ *)
+
+ val cardinal: 'a t -> int
+ (** Return the number of bindings of a map.
+ @since 3.12.0
+ *)
+
+ val bindings: 'a t -> (key * 'a) list
+ (** Return the list of all bindings of the given map.
+ The returned list is sorted in increasing order with respect
+ to the ordering [Ord.compare], where [Ord] is the argument
+ given to {!Map.Make}.
+ @since 3.12.0
+ *)
+
+ val min_binding: 'a t -> (key * 'a)
+ (** Return the smallest binding of the given map
+ (with respect to the [Ord.compare] ordering), or raise
+ [Not_found] if the map is empty.
+ @since 3.12.0
+ *)
+
+ val max_binding: 'a t -> (key * 'a)
+ (** Same as {!Map.S.min_binding}, but returns the largest binding
+ of the given map.
+ @since 3.12.0
+ *)
+
+ val choose: 'a t -> (key * 'a)
+ (** Return one binding of the given map, or raise [Not_found] if
+ the map is empty. Which binding is chosen is unspecified,
+ but equal bindings will be chosen for equal maps.
+ @since 3.12.0
+ *)
+
+ val split: key -> 'a t -> 'a t * 'a option * 'a t
+ (** [split x m] returns a triple [(l, data, r)], where
+ [l] is the map with all the bindings of [m] whose key
+ is strictly less than [x];
+ [r] is the map with all the bindings of [m] whose key
+ is strictly greater than [x];
+ [data] is [None] if [m] contains no binding for [x],
+ or [Some v] if [m] binds [v] to [x].
+ @since 3.12.0
+ *)
+
+ val find: key -> 'a t -> 'a
+ (** [find x m] returns the current binding of [x] in [m],
+ or raises [Not_found] if no such binding exists. *)
+
+ val map: ('a -> 'b) -> 'a t -> 'b t
+ (** [map f m] returns a map with same domain as [m], where the
+ associated value [a] of all bindings of [m] has been
+ replaced by the result of the application of [f] to [a].
+ The bindings are passed to [f] in increasing order
+ with respect to the ordering over the type of the keys. *)
+
+ val mapi: (key -> 'a -> 'b) -> 'a t -> 'b t
+ (** Same as {!Map.S.map}, but the function receives as arguments both the
+ key and the associated value for each binding of the map. *)
+
+
+ end
+(** Output signature of the functor {!Map.Make}. *)
+
+module Make (Ord : OrderedType) : S with type key = Ord.t
+(** Functor building an implementation of the map structure
+ given a totally ordered type. *)
diff --git a/stdlib/marshal.ml b/stdlib/marshal.ml
new file mode 100644
index 0000000000..4155595711
--- /dev/null
+++ b/stdlib/marshal.ml
@@ -0,0 +1,66 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type extern_flags =
+ No_sharing
+ | Closures
+ | Compat_32
+(* note: this type definition is used in 'byterun/debugger.c' *)
+
+external to_channel: out_channel -> 'a -> extern_flags list -> unit
+ = "caml_output_value"
+external to_bytes: 'a -> extern_flags list -> bytes
+ = "caml_output_value_to_string"
+external to_string: 'a -> extern_flags list -> string
+ = "caml_output_value_to_string"
+external to_buffer_unsafe:
+ bytes -> int -> int -> 'a -> extern_flags list -> int
+ = "caml_output_value_to_buffer"
+
+let to_buffer buff ofs len v flags =
+ if ofs < 0 || len < 0 || ofs > Bytes.length buff - len
+ then invalid_arg "Marshal.to_buffer: substring out of bounds"
+ else to_buffer_unsafe buff ofs len v flags
+
+(* The functions below use byte sequences as input, never using any
+ mutation. It makes sense to use non-mutated [bytes] rather than
+ [string], because we really work with sequences of bytes, not
+ a text representation.
+*)
+
+external from_channel: in_channel -> 'a = "caml_input_value"
+external from_bytes_unsafe: bytes -> int -> 'a
+ = "caml_input_value_from_string"
+external data_size_unsafe: bytes -> int -> int = "caml_marshal_data_size"
+
+let header_size = 20
+let data_size buff ofs =
+ if ofs < 0 || ofs > Bytes.length buff - header_size
+ then invalid_arg "Marshal.data_size"
+ else data_size_unsafe buff ofs
+let total_size buff ofs = header_size + data_size buff ofs
+
+let from_bytes buff ofs =
+ if ofs < 0 || ofs > Bytes.length buff - header_size
+ then invalid_arg "Marshal.from_bytes"
+ else begin
+ let len = data_size_unsafe buff ofs in
+ if ofs > Bytes.length buff - (header_size + len)
+ then invalid_arg "Marshal.from_bytes"
+ else from_bytes_unsafe buff ofs
+ end
+
+let from_string buff ofs =
+ (* Bytes.unsafe_of_string is safe here, as the produced byte
+ sequence is never mutated *)
+ from_bytes (Bytes.unsafe_of_string buff) ofs
diff --git a/stdlib/marshal.mli b/stdlib/marshal.mli
new file mode 100644
index 0000000000..4f0ed49b78
--- /dev/null
+++ b/stdlib/marshal.mli
@@ -0,0 +1,178 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Marshaling of data structures.
+
+ This module provides functions to encode arbitrary data structures
+ as sequences of bytes, which can then be written on a file or
+ sent over a pipe or network connection. The bytes can then
+ be read back later, possibly in another process, and decoded back
+ into a data structure. The format for the byte sequences
+ is compatible across all machines for a given version of OCaml.
+
+ Warning: marshaling is currently not type-safe. The type
+ of marshaled data is not transmitted along the value of the data,
+ making it impossible to check that the data read back possesses the
+ type expected by the context. In particular, the result type of
+ the [Marshal.from_*] functions is given as ['a], but this is
+ misleading: the returned OCaml value does not possess type ['a]
+ for all ['a]; it has one, unique type which cannot be determined
+ at compile-type. The programmer should explicitly give the expected
+ type of the returned value, using the following syntax:
+ - [(Marshal.from_channel chan : type)].
+ Anything can happen at run-time if the object in the file does not
+ belong to the given type.
+
+ Values of extensible variant types, for example exceptions (of
+ extensible type [exn]), returned by the unmarhsaller should not be
+ pattern-matched over through [match ... with] or [try ... with],
+ because unmarshalling does not preserve the information required for
+ matching their constructors. Structural equalities with other
+ extensible variant values does not work either. Most other uses such
+ as Printexc.to_string, will still work as expected.
+
+ The representation of marshaled values is not human-readable,
+ and uses bytes that are not printable characters. Therefore,
+ input and output channels used in conjunction with [Marshal.to_channel]
+ and [Marshal.from_channel] must be opened in binary mode, using e.g.
+ [open_out_bin] or [open_in_bin]; channels opened in text mode will
+ cause unmarshaling errors on platforms where text channels behave
+ differently than binary channels, e.g. Windows.
+ *)
+
+type extern_flags =
+ No_sharing (** Don't preserve sharing *)
+ | Closures (** Send function closures *)
+ | Compat_32 (** Ensure 32-bit compatibility *)
+(** The flags to the [Marshal.to_*] functions below. *)
+
+val to_channel : out_channel -> 'a -> extern_flags list -> unit
+(** [Marshal.to_channel chan v flags] writes the representation
+ of [v] on channel [chan]. The [flags] argument is a
+ possibly empty list of flags that governs the marshaling
+ behavior with respect to sharing, functional values, and compatibility
+ between 32- and 64-bit platforms.
+
+ If [flags] does not contain [Marshal.No_sharing], circularities
+ and sharing inside the value [v] are detected and preserved
+ in the sequence of bytes produced. In particular, this
+ guarantees that marshaling always terminates. Sharing
+ between values marshaled by successive calls to
+ [Marshal.to_channel] is neither detected nor preserved, though.
+ If [flags] contains [Marshal.No_sharing], sharing is ignored.
+ This results in faster marshaling if [v] contains no shared
+ substructures, but may cause slower marshaling and larger
+ byte representations if [v] actually contains sharing,
+ or even non-termination if [v] contains cycles.
+
+ If [flags] does not contain [Marshal.Closures], marshaling fails
+ when it encounters a functional value inside [v]: only 'pure' data
+ structures, containing neither functions nor objects, can safely be
+ transmitted between different programs. If [flags] contains
+ [Marshal.Closures], functional values will be marshaled as a the
+ position in the code of the program together with the values
+ corresponding to the free variables captured in the closure. In
+ this case, the output of marshaling can only be read back in
+ processes that run exactly the same program, with exactly the same
+ compiled code. (This is checked at un-marshaling time, using an MD5
+ digest of the code transmitted along with the code position.)
+
+ The exact definition of which free variables are captured in a
+ closure is not specified and can very between bytecode and native
+ code (and according to optimization flags). In particular, a
+ function value accessing a global reference may or may not include
+ the reference in its closure. If it does, unmarshaling the
+ corresponding closure will create a new reference, different from
+ the global one.
+
+
+ If [flags] contains [Marshal.Compat_32], marshaling fails when
+ it encounters an integer value outside the range [[-2{^30}, 2{^30}-1]]
+ of integers that are representable on a 32-bit platform. This
+ ensures that marshaled data generated on a 64-bit platform can be
+ safely read back on a 32-bit platform. If [flags] does not
+ contain [Marshal.Compat_32], integer values outside the
+ range [[-2{^30}, 2{^30}-1]] are marshaled, and can be read back on
+ a 64-bit platform, but will cause an error at un-marshaling time
+ when read back on a 32-bit platform. The [Mashal.Compat_32] flag
+ only matters when marshaling is performed on a 64-bit platform;
+ it has no effect if marshaling is performed on a 32-bit platform.
+ *)
+
+external to_bytes :
+ 'a -> extern_flags list -> bytes = "caml_output_value_to_string"
+(** [Marshal.to_bytes v flags] returns a byte sequence containing
+ the representation of [v].
+ The [flags] argument has the same meaning as for
+ {!Marshal.to_channel}.
+ @since 4.02.0 *)
+
+external to_string :
+ 'a -> extern_flags list -> string = "caml_output_value_to_string"
+(** Same as [to_bytes] but return the result as a string instead of
+ a byte sequence. *)
+
+val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int
+(** [Marshal.to_buffer buff ofs len v flags] marshals the value [v],
+ storing its byte representation in the sequence [buff],
+ starting at index [ofs], and writing at most
+ [len] bytes. It returns the number of bytes
+ actually written to the sequence. If the byte representation
+ of [v] does not fit in [len] characters, the exception [Failure]
+ is raised. *)
+
+val from_channel : in_channel -> 'a
+(** [Marshal.from_channel chan] reads from channel [chan] the
+ byte representation of a structured value, as produced by
+ one of the [Marshal.to_*] functions, and reconstructs and
+ returns the corresponding value.*)
+
+val from_bytes : bytes -> int -> 'a
+(** [Marshal.from_bytes buff ofs] unmarshals a structured value
+ like {!Marshal.from_channel} does, except that the byte
+ representation is not read from a channel, but taken from
+ the byte sequence [buff], starting at position [ofs].
+ The byte sequence is not mutated.
+ @since 4.02.0 *)
+
+val from_string : string -> int -> 'a
+(** Same as [from_bytes] but take a string as argument instead of a
+ byte sequence. *)
+
+val header_size : int
+(** The bytes representing a marshaled value are composed of
+ a fixed-size header and a variable-sized data part,
+ whose size can be determined from the header.
+ {!Marshal.header_size} is the size, in bytes, of the header.
+ {!Marshal.data_size}[ buff ofs] is the size, in bytes,
+ of the data part, assuming a valid header is stored in
+ [buff] starting at position [ofs].
+ Finally, {!Marshal.total_size} [buff ofs] is the total size,
+ in bytes, of the marshaled value.
+ Both {!Marshal.data_size} and {!Marshal.total_size} raise [Failure]
+ if [buff], [ofs] does not contain a valid header.
+
+ To read the byte representation of a marshaled value into
+ a byte sequence, the program needs to read first
+ {!Marshal.header_size} bytes into the sequence,
+ then determine the length of the remainder of the
+ representation using {!Marshal.data_size},
+ make sure the sequence is large enough to hold the remaining
+ data, then read it, and finally call {!Marshal.from_bytes}
+ to unmarshal the value. *)
+
+val data_size : bytes -> int -> int
+(** See {!Marshal.header_size}.*)
+
+val total_size : bytes -> int -> int
+(** See {!Marshal.header_size}.*)
diff --git a/stdlib/moreLabels.ml b/stdlib/moreLabels.ml
new file mode 100644
index 0000000000..d7ac158949
--- /dev/null
+++ b/stdlib/moreLabels.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [MoreLabels]: meta-module for compatibility labelled libraries *)
+
+module Hashtbl = Hashtbl
+
+module Map = Map
+
+module Set = Set
diff --git a/stdlib/moreLabels.mli b/stdlib/moreLabels.mli
new file mode 100644
index 0000000000..4e3f1bdcfc
--- /dev/null
+++ b/stdlib/moreLabels.mli
@@ -0,0 +1,167 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Extra labeled libraries.
+
+ This meta-module provides labelized version of the {!Hashtbl},
+ {!Map} and {!Set} modules.
+
+ They only differ by their labels. They are provided to help
+ porting from previous versions of OCaml.
+ The contents of this module are subject to change.
+*)
+
+module Hashtbl : sig
+ type ('a, 'b) t = ('a, 'b) Hashtbl.t
+ val create : ?random:bool -> int -> ('a, 'b) t
+ val clear : ('a, 'b) t -> unit
+ val reset : ('a, 'b) t -> unit
+ val copy : ('a, 'b) t -> ('a, 'b) t
+ val add : ('a, 'b) t -> key:'a -> data:'b -> unit
+ val find : ('a, 'b) t -> 'a -> 'b
+ val find_all : ('a, 'b) t -> 'a -> 'b list
+ val mem : ('a, 'b) t -> 'a -> bool
+ val remove : ('a, 'b) t -> 'a -> unit
+ val replace : ('a, 'b) t -> key:'a -> data:'b -> unit
+ val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit
+ val fold :
+ f:(key:'a -> data:'b -> 'c -> 'c) ->
+ ('a, 'b) t -> init:'c -> 'c
+ val length : ('a, 'b) t -> int
+ val randomize : unit -> unit
+ type statistics = Hashtbl.statistics
+ val stats : ('a, 'b) t -> statistics
+ module type HashedType = Hashtbl.HashedType
+ module type SeededHashedType = Hashtbl.SeededHashedType
+ module type S =
+ sig
+ type key
+ and 'a t
+ val create : int -> 'a t
+ val clear : 'a t -> unit
+ val reset : 'a t -> unit
+ val copy : 'a t -> 'a t
+ val add : 'a t -> key:key -> data:'a -> unit
+ val remove : 'a t -> key -> unit
+ val find : 'a t -> key -> 'a
+ val find_all : 'a t -> key -> 'a list
+ val replace : 'a t -> key:key -> data:'a -> unit
+ val mem : 'a t -> key -> bool
+ val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
+ val fold :
+ f:(key:key -> data:'a -> 'b -> 'b) ->
+ 'a t -> init:'b -> 'b
+ val length : 'a t -> int
+ val stats: 'a t -> statistics
+ end
+ module type SeededS =
+ sig
+ type key
+ and 'a t
+ val create : ?random:bool -> int -> 'a t
+ val clear : 'a t -> unit
+ val reset : 'a t -> unit
+ val copy : 'a t -> 'a t
+ val add : 'a t -> key:key -> data:'a -> unit
+ val remove : 'a t -> key -> unit
+ val find : 'a t -> key -> 'a
+ val find_all : 'a t -> key -> 'a list
+ val replace : 'a t -> key:key -> data:'a -> unit
+ val mem : 'a t -> key -> bool
+ val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
+ val fold :
+ f:(key:key -> data:'a -> 'b -> 'b) ->
+ 'a t -> init:'b -> 'b
+ val length : 'a t -> int
+ val stats: 'a t -> statistics
+ end
+ module Make : functor (H : HashedType) -> S with type key = H.t
+ module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t
+ val hash : 'a -> int
+ val seeded_hash : int -> 'a -> int
+ val hash_param : int -> int -> 'a -> int
+ val seeded_hash_param : int -> int -> int -> 'a -> int
+end
+
+module Map : sig
+ module type OrderedType = Map.OrderedType
+ module type S =
+ sig
+ type key
+ and (+'a) t
+ val empty : 'a t
+ val is_empty: 'a t -> bool
+ val mem : key -> 'a t -> bool
+ val add : key:key -> data:'a -> 'a t -> 'a t
+ val singleton: key -> 'a -> 'a t
+ val remove : key -> 'a t -> 'a t
+ val merge:
+ f:(key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
+ val compare: cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int
+ val equal: cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool
+ val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit
+ val fold :
+ f:(key:key -> data:'a -> 'b -> 'b) ->
+ 'a t -> init:'b -> 'b
+ val for_all: f:(key -> 'a -> bool) -> 'a t -> bool
+ val exists: f:(key -> 'a -> bool) -> 'a t -> bool
+ val filter: f:(key -> 'a -> bool) -> 'a t -> 'a t
+ val partition: f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t
+ val cardinal: 'a t -> int
+ val bindings: 'a t -> (key * 'a) list
+ val min_binding: 'a t -> (key * 'a)
+ val max_binding: 'a t -> (key * 'a)
+ val choose: 'a t -> (key * 'a)
+ val split: key -> 'a t -> 'a t * 'a option * 'a t
+ val find : key -> 'a t -> 'a
+ val map : f:('a -> 'b) -> 'a t -> 'b t
+ val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t
+ end
+ module Make : functor (Ord : OrderedType) -> S with type key = Ord.t
+end
+
+module Set : sig
+ module type OrderedType = Set.OrderedType
+ module type S =
+ sig
+ type elt
+ and t
+ val empty : t
+ val is_empty : t -> bool
+ val mem : elt -> t -> bool
+ val add : elt -> t -> t
+ val singleton : elt -> t
+ val remove : elt -> t -> t
+ val union : t -> t -> t
+ val inter : t -> t -> t
+ val diff : t -> t -> t
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ val subset : t -> t -> bool
+ val iter : f:(elt -> unit) -> t -> unit
+ val fold : f:(elt -> 'a -> 'a) -> t -> init:'a -> 'a
+ val for_all : f:(elt -> bool) -> t -> bool
+ val exists : f:(elt -> bool) -> t -> bool
+ val filter : f:(elt -> bool) -> t -> t
+ val partition : f:(elt -> bool) -> t -> t * t
+ val cardinal : t -> int
+ val elements : t -> elt list
+ val min_elt : t -> elt
+ val max_elt : t -> elt
+ val choose : t -> elt
+ val split: elt -> t -> t * bool * t
+ val find: elt -> t -> elt
+ val of_list: elt list -> t
+ end
+ module Make : functor (Ord : OrderedType) -> S with type elt = Ord.t
+end
diff --git a/stdlib/nativeint.ml b/stdlib/nativeint.ml
new file mode 100644
index 0000000000..7412bca04e
--- /dev/null
+++ b/stdlib/nativeint.ml
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [Nativeint]: processor-native integers *)
+
+external neg: nativeint -> nativeint = "%nativeint_neg"
+external add: nativeint -> nativeint -> nativeint = "%nativeint_add"
+external sub: nativeint -> nativeint -> nativeint = "%nativeint_sub"
+external mul: nativeint -> nativeint -> nativeint = "%nativeint_mul"
+external div: nativeint -> nativeint -> nativeint = "%nativeint_div"
+external rem: nativeint -> nativeint -> nativeint = "%nativeint_mod"
+external logand: nativeint -> nativeint -> nativeint = "%nativeint_and"
+external logor: nativeint -> nativeint -> nativeint = "%nativeint_or"
+external logxor: nativeint -> nativeint -> nativeint = "%nativeint_xor"
+external shift_left: nativeint -> int -> nativeint = "%nativeint_lsl"
+external shift_right: nativeint -> int -> nativeint = "%nativeint_asr"
+external shift_right_logical: nativeint -> int -> nativeint = "%nativeint_lsr"
+external of_int: int -> nativeint = "%nativeint_of_int"
+external to_int: nativeint -> int = "%nativeint_to_int"
+external of_float : float -> nativeint = "caml_nativeint_of_float"
+external to_float : nativeint -> float = "caml_nativeint_to_float"
+external of_int32: int32 -> nativeint = "%nativeint_of_int32"
+external to_int32: nativeint -> int32 = "%nativeint_to_int32"
+
+let zero = 0n
+let one = 1n
+let minus_one = -1n
+let succ n = add n 1n
+let pred n = sub n 1n
+let abs n = if n >= 0n then n else neg n
+let size = Sys.word_size
+let min_int = shift_left 1n (size - 1)
+let max_int = sub min_int 1n
+let lognot n = logxor n (-1n)
+
+external format : string -> nativeint -> string = "caml_nativeint_format"
+let to_string n = format "%d" n
+
+external of_string: string -> nativeint = "caml_nativeint_of_string"
+
+type t = nativeint
+
+let compare (x: t) (y: t) = Pervasives.compare x y
+let equal (x: t) (y: t) = compare x y = 0
diff --git a/stdlib/nativeint.mli b/stdlib/nativeint.mli
new file mode 100644
index 0000000000..ffa57030cd
--- /dev/null
+++ b/stdlib/nativeint.mli
@@ -0,0 +1,188 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Processor-native integers.
+
+ This module provides operations on the type [nativeint] of
+ signed 32-bit integers (on 32-bit platforms) or
+ signed 64-bit integers (on 64-bit platforms).
+ This integer type has exactly the same width as that of a
+ pointer type in the C compiler. All arithmetic operations over
+ [nativeint] are taken modulo 2{^32} or 2{^64} depending
+ on the word size of the architecture.
+
+ Performance notice: values of type [nativeint] occupy more memory
+ space than values of type [int], and arithmetic operations on
+ [nativeint] are generally slower than those on [int]. Use [nativeint]
+ only when the application requires the extra bit of precision
+ over the [int] type.
+*)
+
+val zero : nativeint
+(** The native integer 0.*)
+
+val one : nativeint
+(** The native integer 1.*)
+
+val minus_one : nativeint
+(** The native integer -1.*)
+
+external neg : nativeint -> nativeint = "%nativeint_neg"
+(** Unary negation. *)
+
+external add : nativeint -> nativeint -> nativeint = "%nativeint_add"
+(** Addition. *)
+
+external sub : nativeint -> nativeint -> nativeint = "%nativeint_sub"
+(** Subtraction. *)
+
+external mul : nativeint -> nativeint -> nativeint = "%nativeint_mul"
+(** Multiplication. *)
+
+external div : nativeint -> nativeint -> nativeint = "%nativeint_div"
+(** Integer division. Raise [Division_by_zero] if the second
+ argument is zero. This division rounds the real quotient of
+ its arguments towards zero, as specified for {!Pervasives.(/)}. *)
+
+external rem : nativeint -> nativeint -> nativeint = "%nativeint_mod"
+(** Integer remainder. If [y] is not zero, the result
+ of [Nativeint.rem x y] satisfies the following properties:
+ [Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y] and
+ [x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y)
+ (Nativeint.rem x y)].
+ If [y = 0], [Nativeint.rem x y] raises [Division_by_zero]. *)
+
+val succ : nativeint -> nativeint
+(** Successor.
+ [Nativeint.succ x] is [Nativeint.add x Nativeint.one]. *)
+
+val pred : nativeint -> nativeint
+(** Predecessor.
+ [Nativeint.pred x] is [Nativeint.sub x Nativeint.one]. *)
+
+val abs : nativeint -> nativeint
+(** Return the absolute value of its argument. *)
+
+val size : int
+(** The size in bits of a native integer. This is equal to [32]
+ on a 32-bit platform and to [64] on a 64-bit platform. *)
+
+val max_int : nativeint
+(** The greatest representable native integer,
+ either 2{^31} - 1 on a 32-bit platform,
+ or 2{^63} - 1 on a 64-bit platform. *)
+
+val min_int : nativeint
+(** The greatest representable native integer,
+ either -2{^31} on a 32-bit platform,
+ or -2{^63} on a 64-bit platform. *)
+
+external logand : nativeint -> nativeint -> nativeint = "%nativeint_and"
+(** Bitwise logical and. *)
+
+external logor : nativeint -> nativeint -> nativeint = "%nativeint_or"
+(** Bitwise logical or. *)
+
+external logxor : nativeint -> nativeint -> nativeint = "%nativeint_xor"
+(** Bitwise logical exclusive or. *)
+
+val lognot : nativeint -> nativeint
+(** Bitwise logical negation *)
+
+external shift_left : nativeint -> int -> nativeint = "%nativeint_lsl"
+(** [Nativeint.shift_left x y] shifts [x] to the left by [y] bits.
+ The result is unspecified if [y < 0] or [y >= bitsize],
+ where [bitsize] is [32] on a 32-bit platform and
+ [64] on a 64-bit platform. *)
+
+external shift_right : nativeint -> int -> nativeint = "%nativeint_asr"
+(** [Nativeint.shift_right x y] shifts [x] to the right by [y] bits.
+ This is an arithmetic shift: the sign bit of [x] is replicated
+ and inserted in the vacated bits.
+ The result is unspecified if [y < 0] or [y >= bitsize]. *)
+
+external shift_right_logical :
+ nativeint -> int -> nativeint = "%nativeint_lsr"
+(** [Nativeint.shift_right_logical x y] shifts [x] to the right
+ by [y] bits.
+ This is a logical shift: zeroes are inserted in the vacated bits
+ regardless of the sign of [x].
+ The result is unspecified if [y < 0] or [y >= bitsize]. *)
+
+
+external of_int : int -> nativeint = "%nativeint_of_int"
+(** Convert the given integer (type [int]) to a native integer
+ (type [nativeint]). *)
+
+external to_int : nativeint -> int = "%nativeint_to_int"
+(** Convert the given native integer (type [nativeint]) to an
+ integer (type [int]). The high-order bit is lost during
+ the conversion. *)
+
+external of_float : float -> nativeint = "caml_nativeint_of_float"
+(** Convert the given floating-point number to a native integer,
+ discarding the fractional part (truncate towards 0).
+ The result of the conversion is undefined if, after truncation,
+ the number is outside the range
+ \[{!Nativeint.min_int}, {!Nativeint.max_int}\]. *)
+
+external to_float : nativeint -> float = "caml_nativeint_to_float"
+(** Convert the given native integer to a floating-point number. *)
+
+external of_int32 : int32 -> nativeint = "%nativeint_of_int32"
+(** Convert the given 32-bit integer (type [int32])
+ to a native integer. *)
+
+external to_int32 : nativeint -> int32 = "%nativeint_to_int32"
+(** Convert the given native integer to a
+ 32-bit integer (type [int32]). On 64-bit platforms,
+ the 64-bit native integer is taken modulo 2{^32},
+ i.e. the top 32 bits are lost. On 32-bit platforms,
+ the conversion is exact. *)
+
+external of_string : string -> nativeint = "caml_nativeint_of_string"
+(** Convert the given string to a native integer.
+ The string is read in decimal (by default) or in hexadecimal,
+ octal or binary if the string begins with [0x], [0o] or [0b]
+ respectively.
+ Raise [Failure "int_of_string"] if the given string is not
+ a valid representation of an integer, or if the integer represented
+ exceeds the range of integers representable in type [nativeint]. *)
+
+val to_string : nativeint -> string
+(** Return the string representation of its argument, in decimal. *)
+
+type t = nativeint
+(** An alias for the type of native integers. *)
+
+val compare: t -> t -> int
+(** The comparison function for native integers, with the same specification as
+ {!Pervasives.compare}. Along with the type [t], this function [compare]
+ allows the module [Nativeint] to be passed as argument to the functors
+ {!Set.Make} and {!Map.Make}. *)
+
+val equal: t -> t -> bool
+(** The equal function for natives ints.
+ @since 4.03.0 *)
+
+(**/**)
+
+(** {6 Deprecated functions} *)
+
+external format : string -> nativeint -> string = "caml_nativeint_format"
+(** [Nativeint.format fmt n] return the string representation of the
+ native integer [n] in the format specified by [fmt].
+ [fmt] is a [Printf]-style format consisting of exactly
+ one [%d], [%i], [%u], [%x], [%X] or [%o] conversion specification.
+ This function is deprecated; use {!Printf.sprintf} with a [%nx] format
+ instead. *)
diff --git a/stdlib/obj.ml b/stdlib/obj.ml
new file mode 100644
index 0000000000..5cb970b8e4
--- /dev/null
+++ b/stdlib/obj.ml
@@ -0,0 +1,91 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Operations on internal representations of values *)
+
+type t
+
+external repr : 'a -> t = "%identity"
+external obj : t -> 'a = "%identity"
+external magic : 'a -> 'b = "%identity"
+external is_block : t -> bool = "caml_obj_is_block"
+external is_int : t -> bool = "%obj_is_int"
+external tag : t -> int = "caml_obj_tag"
+external set_tag : t -> int -> unit = "caml_obj_set_tag"
+external size : t -> int = "%obj_size"
+external field : t -> int -> t = "%obj_field"
+external set_field : t -> int -> t -> unit = "%obj_set_field"
+let double_field x i = Array.get (obj x : float array) i
+let set_double_field x i v = Array.set (obj x : float array) i v
+external new_block : int -> int -> t = "caml_obj_block"
+external dup : t -> t = "caml_obj_dup"
+external truncate : t -> int -> unit = "caml_obj_truncate"
+external add_offset : t -> Int32.t -> t = "caml_obj_add_offset"
+
+let marshal (obj : t) =
+ Marshal.to_bytes obj []
+let unmarshal str pos =
+ (Marshal.from_bytes str pos, pos + Marshal.total_size str pos)
+
+let first_non_constant_constructor_tag = 0
+let last_non_constant_constructor_tag = 245
+
+let lazy_tag = 246
+let closure_tag = 247
+let object_tag = 248
+let infix_tag = 249
+let forward_tag = 250
+
+let no_scan_tag = 251
+
+let abstract_tag = 251
+let string_tag = 252
+let double_tag = 253
+let double_array_tag = 254
+let custom_tag = 255
+let final_tag = custom_tag
+
+
+let int_tag = 1000
+let out_of_heap_tag = 1001
+let unaligned_tag = 1002
+
+let extension_slot x =
+ let x = repr x in
+ let slot =
+ if (is_block x) && (tag x) <> object_tag && (size x) >= 1 then field x 0
+ else x
+ in
+ let name =
+ if (is_block slot) && (tag slot) = object_tag then field slot 0
+ else raise Not_found
+ in
+ if (tag name) = string_tag then slot
+ else raise Not_found
+
+let extension_name x =
+ try
+ let slot = extension_slot x in
+ (obj (field slot 0) : string)
+ with Not_found -> invalid_arg "Obj.extension_name"
+
+let extension_id x =
+ try
+ let slot = extension_slot x in
+ (obj (field slot 1) : int)
+ with Not_found -> invalid_arg "Obj.extension_id"
+
+let extension_slot x =
+ try
+ extension_slot x
+ with Not_found -> invalid_arg "Obj.extension_slot"
diff --git a/stdlib/obj.mli b/stdlib/obj.mli
new file mode 100644
index 0000000000..6d06312b4d
--- /dev/null
+++ b/stdlib/obj.mli
@@ -0,0 +1,70 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Operations on internal representations of values.
+
+ Not for the casual user.
+*)
+
+type t
+
+external repr : 'a -> t = "%identity"
+external obj : t -> 'a = "%identity"
+external magic : 'a -> 'b = "%identity"
+external is_block : t -> bool = "caml_obj_is_block"
+external is_int : t -> bool = "%obj_is_int"
+external tag : t -> int = "caml_obj_tag"
+external set_tag : t -> int -> unit = "caml_obj_set_tag"
+external size : t -> int = "%obj_size"
+external field : t -> int -> t = "%obj_field"
+external set_field : t -> int -> t -> unit = "%obj_set_field"
+val double_field : t -> int -> float (* @since 3.11.2 *)
+val set_double_field : t -> int -> float -> unit (* @since 3.11.2 *)
+external new_block : int -> int -> t = "caml_obj_block"
+external dup : t -> t = "caml_obj_dup"
+external truncate : t -> int -> unit = "caml_obj_truncate"
+external add_offset : t -> Int32.t -> t = "caml_obj_add_offset"
+ (* @since 3.12.0 *)
+
+val first_non_constant_constructor_tag : int
+val last_non_constant_constructor_tag : int
+
+val lazy_tag : int
+val closure_tag : int
+val object_tag : int
+val infix_tag : int
+val forward_tag : int
+val no_scan_tag : int
+val abstract_tag : int
+val string_tag : int (* both [string] and [bytes] *)
+val double_tag : int
+val double_array_tag : int
+val custom_tag : int
+val final_tag : int
+ [@@ocaml.deprecated "Replaced by custom_tag."]
+
+val int_tag : int
+val out_of_heap_tag : int
+val unaligned_tag : int (* should never happen @since 3.11.0 *)
+
+val extension_name : 'a -> string
+val extension_id : 'a -> int
+val extension_slot : 'a -> t
+
+(** The following two functions are deprecated. Use module {!Marshal}
+ instead. *)
+
+val marshal : t -> bytes
+ [@@ocaml.deprecated "Use Marshal.to_bytes instead."]
+val unmarshal : bytes -> int -> t * int
+ [@@ocaml.deprecated "Use Marshal.from_bytes and Marshal.total_size instead."]
diff --git a/stdlib/oo.ml b/stdlib/oo.ml
new file mode 100644
index 0000000000..9d00360c74
--- /dev/null
+++ b/stdlib/oo.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+let copy = CamlinternalOO.copy
+external id : < .. > -> int = "%field1"
+let new_method = CamlinternalOO.public_method_label
+let public_method_label = CamlinternalOO.public_method_label
diff --git a/stdlib/oo.mli b/stdlib/oo.mli
new file mode 100644
index 0000000000..d1e5804f42
--- /dev/null
+++ b/stdlib/oo.mli
@@ -0,0 +1,36 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Operations on objects *)
+
+val copy : (< .. > as 'a) -> 'a
+(** [Oo.copy o] returns a copy of object [o], that is a fresh
+ object with the same methods and instance variables as [o]. *)
+
+external id : < .. > -> int = "%field1"
+(** Return an integer identifying this object, unique for
+ the current execution of the program. The generic comparison
+ and hashing functions are based on this integer. When an object
+ is obtained by unmarshaling, the id is refreshed, and thus
+ different from the original object. As a consequence, the internal
+ invariants of data structures such as hash table or sets containing
+ objects are broken after unmarshaling the data structures.
+ *)
+
+(**/**)
+
+(* The following is for system use only. Do not call directly. *)
+
+(** For internal use (CamlIDL) *)
+val new_method : string -> CamlinternalOO.tag
+val public_method_label : string -> CamlinternalOO.tag
diff --git a/stdlib/parsing.ml b/stdlib/parsing.ml
new file mode 100644
index 0000000000..47e151e1b4
--- /dev/null
+++ b/stdlib/parsing.ml
@@ -0,0 +1,209 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* The parsing engine *)
+
+open Lexing
+
+(* Internal interface to the parsing engine *)
+
+type parser_env =
+ { mutable s_stack : int array; (* States *)
+ mutable v_stack : Obj.t array; (* Semantic attributes *)
+ mutable symb_start_stack : position array; (* Start positions *)
+ mutable symb_end_stack : position array; (* End positions *)
+ mutable stacksize : int; (* Size of the stacks *)
+ mutable stackbase : int; (* Base sp for current parse *)
+ mutable curr_char : int; (* Last token read *)
+ mutable lval : Obj.t; (* Its semantic attribute *)
+ mutable symb_start : position; (* Start pos. of the current symbol*)
+ mutable symb_end : position; (* End pos. of the current symbol *)
+ mutable asp : int; (* The stack pointer for attributes *)
+ mutable rule_len : int; (* Number of rhs items in the rule *)
+ mutable rule_number : int; (* Rule number to reduce by *)
+ mutable sp : int; (* Saved sp for parse_engine *)
+ mutable state : int; (* Saved state for parse_engine *)
+ mutable errflag : int } (* Saved error flag for parse_engine *)
+
+type parse_tables =
+ { actions : (parser_env -> Obj.t) array;
+ transl_const : int array;
+ transl_block : int array;
+ lhs : string;
+ len : string;
+ defred : string;
+ dgoto : string;
+ sindex : string;
+ rindex : string;
+ gindex : string;
+ tablesize : int;
+ table : string;
+ check : string;
+ error_function : string -> unit;
+ names_const : string;
+ names_block : string }
+
+exception YYexit of Obj.t
+exception Parse_error
+
+type parser_input =
+ Start
+ | Token_read
+ | Stacks_grown_1
+ | Stacks_grown_2
+ | Semantic_action_computed
+ | Error_detected
+
+type parser_output =
+ Read_token
+ | Raise_parse_error
+ | Grow_stacks_1
+ | Grow_stacks_2
+ | Compute_semantic_action
+ | Call_error_function
+
+(* to avoid warnings *)
+let _ = [Read_token; Raise_parse_error; Grow_stacks_1; Grow_stacks_2;
+ Compute_semantic_action; Call_error_function]
+
+external parse_engine :
+ parse_tables -> parser_env -> parser_input -> Obj.t -> parser_output
+ = "caml_parse_engine"
+
+external set_trace: bool -> bool
+ = "caml_set_parser_trace"
+
+let env =
+ { s_stack = Array.make 100 0;
+ v_stack = Array.make 100 (Obj.repr ());
+ symb_start_stack = Array.make 100 dummy_pos;
+ symb_end_stack = Array.make 100 dummy_pos;
+ stacksize = 100;
+ stackbase = 0;
+ curr_char = 0;
+ lval = Obj.repr ();
+ symb_start = dummy_pos;
+ symb_end = dummy_pos;
+ asp = 0;
+ rule_len = 0;
+ rule_number = 0;
+ sp = 0;
+ state = 0;
+ errflag = 0 }
+
+let grow_stacks() =
+ let oldsize = env.stacksize in
+ let newsize = oldsize * 2 in
+ let new_s = Array.make newsize 0
+ and new_v = Array.make newsize (Obj.repr ())
+ and new_start = Array.make newsize dummy_pos
+ and new_end = Array.make newsize dummy_pos in
+ Array.blit env.s_stack 0 new_s 0 oldsize;
+ env.s_stack <- new_s;
+ Array.blit env.v_stack 0 new_v 0 oldsize;
+ env.v_stack <- new_v;
+ Array.blit env.symb_start_stack 0 new_start 0 oldsize;
+ env.symb_start_stack <- new_start;
+ Array.blit env.symb_end_stack 0 new_end 0 oldsize;
+ env.symb_end_stack <- new_end;
+ env.stacksize <- newsize
+
+let clear_parser() =
+ Array.fill env.v_stack 0 env.stacksize (Obj.repr ());
+ env.lval <- Obj.repr ()
+
+let current_lookahead_fun = ref (fun (x : Obj.t) -> false)
+
+let yyparse tables start lexer lexbuf =
+ let rec loop cmd arg =
+ match parse_engine tables env cmd arg with
+ Read_token ->
+ let t = Obj.repr(lexer lexbuf) in
+ env.symb_start <- lexbuf.lex_start_p;
+ env.symb_end <- lexbuf.lex_curr_p;
+ loop Token_read t
+ | Raise_parse_error ->
+ raise Parse_error
+ | Compute_semantic_action ->
+ let (action, value) =
+ try
+ (Semantic_action_computed, tables.actions.(env.rule_number) env)
+ with Parse_error ->
+ (Error_detected, Obj.repr ()) in
+ loop action value
+ | Grow_stacks_1 ->
+ grow_stacks(); loop Stacks_grown_1 (Obj.repr ())
+ | Grow_stacks_2 ->
+ grow_stacks(); loop Stacks_grown_2 (Obj.repr ())
+ | Call_error_function ->
+ tables.error_function "syntax error";
+ loop Error_detected (Obj.repr ()) in
+ let init_asp = env.asp
+ and init_sp = env.sp
+ and init_stackbase = env.stackbase
+ and init_state = env.state
+ and init_curr_char = env.curr_char
+ and init_lval = env.lval
+ and init_errflag = env.errflag in
+ env.stackbase <- env.sp + 1;
+ env.curr_char <- start;
+ env.symb_end <- lexbuf.lex_curr_p;
+ try
+ loop Start (Obj.repr ())
+ with exn ->
+ let curr_char = env.curr_char in
+ env.asp <- init_asp;
+ env.sp <- init_sp;
+ env.stackbase <- init_stackbase;
+ env.state <- init_state;
+ env.curr_char <- init_curr_char;
+ env.lval <- init_lval;
+ env.errflag <- init_errflag;
+ match exn with
+ YYexit v ->
+ Obj.magic v
+ | _ ->
+ current_lookahead_fun :=
+ (fun tok ->
+ if Obj.is_block tok
+ then tables.transl_block.(Obj.tag tok) = curr_char
+ else tables.transl_const.(Obj.magic tok) = curr_char);
+ raise exn
+
+let peek_val env n =
+ Obj.magic env.v_stack.(env.asp - n)
+
+let symbol_start_pos () =
+ let rec loop i =
+ if i <= 0 then env.symb_end_stack.(env.asp)
+ else begin
+ let st = env.symb_start_stack.(env.asp - i + 1) in
+ let en = env.symb_end_stack.(env.asp - i + 1) in
+ if st <> en then st else loop (i - 1)
+ end
+ in
+ loop env.rule_len
+;;
+let symbol_end_pos () = env.symb_end_stack.(env.asp);;
+let rhs_start_pos n = env.symb_start_stack.(env.asp - (env.rule_len - n));;
+let rhs_end_pos n = env.symb_end_stack.(env.asp - (env.rule_len - n));;
+
+let symbol_start () = (symbol_start_pos ()).pos_cnum;;
+let symbol_end () = (symbol_end_pos ()).pos_cnum;;
+let rhs_start n = (rhs_start_pos n).pos_cnum;;
+let rhs_end n = (rhs_end_pos n).pos_cnum;;
+
+let is_current_lookahead tok =
+ (!current_lookahead_fun)(Obj.repr tok)
+
+let parse_error (msg : string) = ()
diff --git a/stdlib/parsing.mli b/stdlib/parsing.mli
new file mode 100644
index 0000000000..0532be162e
--- /dev/null
+++ b/stdlib/parsing.mli
@@ -0,0 +1,103 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** The run-time library for parsers generated by [ocamlyacc]. *)
+
+val symbol_start : unit -> int
+(** [symbol_start] and {!Parsing.symbol_end} are to be called in the
+ action part of a grammar rule only. They return the offset of the
+ string that matches the left-hand side of the rule: [symbol_start()]
+ returns the offset of the first character; [symbol_end()] returns the
+ offset after the last character. The first character in a file is at
+ offset 0. *)
+
+val symbol_end : unit -> int
+(** See {!Parsing.symbol_start}. *)
+
+val rhs_start : int -> int
+(** Same as {!Parsing.symbol_start} and {!Parsing.symbol_end}, but
+ return the offset of the string matching the [n]th item on the
+ right-hand side of the rule, where [n] is the integer parameter
+ to [rhs_start] and [rhs_end]. [n] is 1 for the leftmost item. *)
+
+val rhs_end : int -> int
+(** See {!Parsing.rhs_start}. *)
+
+val symbol_start_pos : unit -> Lexing.position;;
+(** Same as [symbol_start], but return a [position] instead of an offset. *)
+
+val symbol_end_pos : unit -> Lexing.position
+(** Same as [symbol_end], but return a [position] instead of an offset. *)
+
+val rhs_start_pos : int -> Lexing.position
+(** Same as [rhs_start], but return a [position] instead of an offset. *)
+
+val rhs_end_pos : int -> Lexing.position
+(** Same as [rhs_end], but return a [position] instead of an offset. *)
+
+val clear_parser : unit -> unit
+(** Empty the parser stack. Call it just after a parsing function
+ has returned, to remove all pointers from the parser stack
+ to structures that were built by semantic actions during parsing.
+ This is optional, but lowers the memory requirements of the
+ programs. *)
+
+exception Parse_error
+(** Raised when a parser encounters a syntax error.
+ Can also be raised from the action part of a grammar rule,
+ to initiate error recovery. *)
+
+val set_trace: bool -> bool
+(** Control debugging support for [ocamlyacc]-generated parsers.
+ After [Parsing.set_trace true], the pushdown automaton that
+ executes the parsers prints a trace of its actions (reading a token,
+ shifting a state, reducing by a rule) on standard output.
+ [Parsing.set_trace false] turns this debugging trace off.
+ The boolean returned is the previous state of the trace flag.
+ @since 3.11.0
+*)
+
+(**/**)
+
+(** {6 } *)
+
+(** The following definitions are used by the generated parsers only.
+ They are not intended to be used directly by user programs. *)
+
+type parser_env
+
+type parse_tables =
+ { actions : (parser_env -> Obj.t) array;
+ transl_const : int array;
+ transl_block : int array;
+ lhs : string;
+ len : string;
+ defred : string;
+ dgoto : string;
+ sindex : string;
+ rindex : string;
+ gindex : string;
+ tablesize : int;
+ table : string;
+ check : string;
+ error_function : string -> unit;
+ names_const : string;
+ names_block : string }
+
+exception YYexit of Obj.t
+
+val yyparse :
+ parse_tables -> int -> (Lexing.lexbuf -> 'a) -> Lexing.lexbuf -> 'b
+val peek_val : parser_env -> int -> 'a
+val is_current_lookahead : 'a -> bool
+val parse_error : string -> unit
diff --git a/stdlib/pervasives.ml b/stdlib/pervasives.ml
new file mode 100644
index 0000000000..21d4cbf307
--- /dev/null
+++ b/stdlib/pervasives.ml
@@ -0,0 +1,512 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* type 'a option = None | Some of 'a *)
+
+(* Exceptions *)
+
+external register_named_value : string -> 'a -> unit
+ = "caml_register_named_value"
+
+let () =
+ (* for asmrun/fail.c *)
+ register_named_value "Pervasives.array_bound_error"
+ (Invalid_argument "index out of bounds")
+
+
+external raise : exn -> 'a = "%raise"
+external raise_notrace : exn -> 'a = "%raise_notrace"
+
+let failwith s = raise(Failure s)
+let invalid_arg s = raise(Invalid_argument s)
+
+exception Exit
+
+(* Composition operators *)
+
+external ( |> ) : 'a -> ('a -> 'b) -> 'b = "%revapply"
+external ( @@ ) : ('a -> 'b) -> 'a -> 'b = "%apply"
+
+(* Debugging *)
+
+external __LOC__ : string = "%loc_LOC"
+external __FILE__ : string = "%loc_FILE"
+external __LINE__ : int = "%loc_LINE"
+external __MODULE__ : string = "%loc_MODULE"
+external __POS__ : string * int * int * int = "%loc_POS"
+
+external __LOC_OF__ : 'a -> string * 'a = "%loc_LOC"
+external __LINE_OF__ : 'a -> int * 'a = "%loc_LINE"
+external __POS_OF__ : 'a -> (string * int * int * int) * 'a = "%loc_POS"
+
+(* Comparisons *)
+
+external ( = ) : 'a -> 'a -> bool = "%equal"
+external ( <> ) : 'a -> 'a -> bool = "%notequal"
+external ( < ) : 'a -> 'a -> bool = "%lessthan"
+external ( > ) : 'a -> 'a -> bool = "%greaterthan"
+external ( <= ) : 'a -> 'a -> bool = "%lessequal"
+external ( >= ) : 'a -> 'a -> bool = "%greaterequal"
+external compare : 'a -> 'a -> int = "%compare"
+
+let min x y = if x <= y then x else y
+let max x y = if x >= y then x else y
+
+external ( == ) : 'a -> 'a -> bool = "%eq"
+external ( != ) : 'a -> 'a -> bool = "%noteq"
+
+(* Boolean operations *)
+
+external not : bool -> bool = "%boolnot"
+external ( & ) : bool -> bool -> bool = "%sequand"
+external ( && ) : bool -> bool -> bool = "%sequand"
+external ( or ) : bool -> bool -> bool = "%sequor"
+external ( || ) : bool -> bool -> bool = "%sequor"
+
+(* Integer operations *)
+
+external ( ~- ) : int -> int = "%negint"
+external ( ~+ ) : int -> int = "%identity"
+external succ : int -> int = "%succint"
+external pred : int -> int = "%predint"
+external ( + ) : int -> int -> int = "%addint"
+external ( - ) : int -> int -> int = "%subint"
+external ( * ) : int -> int -> int = "%mulint"
+external ( / ) : int -> int -> int = "%divint"
+external ( mod ) : int -> int -> int = "%modint"
+
+let abs x = if x >= 0 then x else -x
+
+external ( land ) : int -> int -> int = "%andint"
+external ( lor ) : int -> int -> int = "%orint"
+external ( lxor ) : int -> int -> int = "%xorint"
+
+let lnot x = x lxor (-1)
+
+external ( lsl ) : int -> int -> int = "%lslint"
+external ( lsr ) : int -> int -> int = "%lsrint"
+external ( asr ) : int -> int -> int = "%asrint"
+
+let max_int = (-1) lsr 1
+let min_int = max_int + 1
+
+(* Floating-point operations *)
+
+external ( ~-. ) : float -> float = "%negfloat"
+external ( ~+. ) : float -> float = "%identity"
+external ( +. ) : float -> float -> float = "%addfloat"
+external ( -. ) : float -> float -> float = "%subfloat"
+external ( *. ) : float -> float -> float = "%mulfloat"
+external ( /. ) : float -> float -> float = "%divfloat"
+external ( ** ) : float -> float -> float = "caml_power_float" "pow" "float"
+external exp : float -> float = "caml_exp_float" "exp" "float"
+external expm1 : float -> float = "caml_expm1_float" "caml_expm1" "float"
+external acos : float -> float = "caml_acos_float" "acos" "float"
+external asin : float -> float = "caml_asin_float" "asin" "float"
+external atan : float -> float = "caml_atan_float" "atan" "float"
+external atan2 : float -> float -> float = "caml_atan2_float" "atan2" "float"
+external hypot : float -> float -> float
+ = "caml_hypot_float" "caml_hypot" "float"
+external cos : float -> float = "caml_cos_float" "cos" "float"
+external cosh : float -> float = "caml_cosh_float" "cosh" "float"
+external log : float -> float = "caml_log_float" "log" "float"
+external log10 : float -> float = "caml_log10_float" "log10" "float"
+external log1p : float -> float = "caml_log1p_float" "caml_log1p" "float"
+external sin : float -> float = "caml_sin_float" "sin" "float"
+external sinh : float -> float = "caml_sinh_float" "sinh" "float"
+external sqrt : float -> float = "caml_sqrt_float" "sqrt" "float"
+external tan : float -> float = "caml_tan_float" "tan" "float"
+external tanh : float -> float = "caml_tanh_float" "tanh" "float"
+external ceil : float -> float = "caml_ceil_float" "ceil" "float"
+external floor : float -> float = "caml_floor_float" "floor" "float"
+external abs_float : float -> float = "%absfloat"
+external copysign : float -> float -> float
+ = "caml_copysign_float" "caml_copysign" "float"
+external mod_float : float -> float -> float = "caml_fmod_float" "fmod" "float"
+external frexp : float -> float * int = "caml_frexp_float"
+external ldexp : float -> int -> float = "caml_ldexp_float"
+external modf : float -> float * float = "caml_modf_float"
+external float : int -> float = "%floatofint"
+external float_of_int : int -> float = "%floatofint"
+external truncate : float -> int = "%intoffloat"
+external int_of_float : float -> int = "%intoffloat"
+external float_of_bits : int64 -> float = "caml_int64_float_of_bits"
+let infinity =
+ float_of_bits 0x7F_F0_00_00_00_00_00_00L
+let neg_infinity =
+ float_of_bits 0xFF_F0_00_00_00_00_00_00L
+let nan =
+ float_of_bits 0x7F_F0_00_00_00_00_00_01L
+let max_float =
+ float_of_bits 0x7F_EF_FF_FF_FF_FF_FF_FFL
+let min_float =
+ float_of_bits 0x00_10_00_00_00_00_00_00L
+let epsilon_float =
+ float_of_bits 0x3C_B0_00_00_00_00_00_00L
+
+type fpclass =
+ FP_normal
+ | FP_subnormal
+ | FP_zero
+ | FP_infinite
+ | FP_nan
+external classify_float : float -> fpclass = "caml_classify_float"
+
+(* String and byte sequence operations -- more in modules String and Bytes *)
+
+external string_length : string -> int = "%string_length"
+external bytes_length : bytes -> int = "%string_length"
+external bytes_create : int -> bytes = "caml_create_string"
+external string_blit : string -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+external bytes_blit : bytes -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+external bytes_unsafe_to_string : bytes -> string = "%identity"
+external bytes_unsafe_of_string : string -> bytes = "%identity"
+
+let ( ^ ) s1 s2 =
+ let l1 = string_length s1 and l2 = string_length s2 in
+ let s = bytes_create (l1 + l2) in
+ string_blit s1 0 s 0 l1;
+ string_blit s2 0 s l1 l2;
+ bytes_unsafe_to_string s
+
+(* Character operations -- more in module Char *)
+
+external int_of_char : char -> int = "%identity"
+external unsafe_char_of_int : int -> char = "%identity"
+let char_of_int n =
+ if n < 0 || n > 255 then invalid_arg "char_of_int" else unsafe_char_of_int n
+
+(* Unit operations *)
+
+external ignore : 'a -> unit = "%ignore"
+
+(* Pair operations *)
+
+external fst : 'a * 'b -> 'a = "%field0"
+external snd : 'a * 'b -> 'b = "%field1"
+
+(* References *)
+
+type 'a ref = { mutable contents : 'a }
+external ref : 'a -> 'a ref = "%makemutable"
+external ( ! ) : 'a ref -> 'a = "%field0"
+external ( := ) : 'a ref -> 'a -> unit = "%setfield0"
+external incr : int ref -> unit = "%incr"
+external decr : int ref -> unit = "%decr"
+
+(* Result type *)
+
+type ('a,'b) result = Ok of 'a | Error of 'b
+
+(* String conversion functions *)
+
+external format_int : string -> int -> string = "caml_format_int"
+external format_float : string -> float -> string = "caml_format_float"
+
+let string_of_bool b =
+ if b then "true" else "false"
+let bool_of_string = function
+ | "true" -> true
+ | "false" -> false
+ | _ -> invalid_arg "bool_of_string"
+
+let string_of_int n =
+ format_int "%d" n
+
+external int_of_string : string -> int = "caml_int_of_string"
+external string_get : string -> int -> char = "%string_safe_get"
+
+let valid_float_lexem s =
+ let l = string_length s in
+ let rec loop i =
+ if i >= l then s ^ "." else
+ match string_get s i with
+ | '0' .. '9' | '-' -> loop (i + 1)
+ | _ -> s
+ in
+ loop 0
+;;
+
+let string_of_float f = valid_float_lexem (format_float "%.12g" f);;
+
+external float_of_string : string -> float = "caml_float_of_string"
+
+(* List operations -- more in module List *)
+
+let rec ( @ ) l1 l2 =
+ match l1 with
+ [] -> l2
+ | hd :: tl -> hd :: (tl @ l2)
+
+(* Array index operators *)
+external ( .() ) : 'a array -> int -> 'a = "%array_opt_get"
+external ( .() <- ) : 'a array -> int -> 'a -> unit = "%array_opt_set"
+
+(* String index operators *)
+external ( .[] ) : string -> int -> char = "%string_opt_get"
+external ( .[] <- ) : bytes -> int -> char -> unit = "%string_opt_set"
+
+(* I/O operations *)
+
+type in_channel
+type out_channel
+
+external open_descriptor_out : int -> out_channel
+ = "caml_ml_open_descriptor_out"
+external open_descriptor_in : int -> in_channel = "caml_ml_open_descriptor_in"
+
+let stdin = open_descriptor_in 0
+let stdout = open_descriptor_out 1
+let stderr = open_descriptor_out 2
+
+(* General output functions *)
+
+type open_flag =
+ Open_rdonly | Open_wronly | Open_append
+ | Open_creat | Open_trunc | Open_excl
+ | Open_binary | Open_text | Open_nonblock
+
+external open_desc : string -> open_flag list -> int -> int = "caml_sys_open"
+
+external set_out_channel_name: out_channel -> string -> unit =
+ "caml_ml_set_channel_name"
+
+let open_out_gen mode perm name =
+ let c = open_descriptor_out(open_desc name mode perm) in
+ set_out_channel_name c name;
+ c
+
+let open_out name =
+ open_out_gen [Open_wronly; Open_creat; Open_trunc; Open_text] 0o666 name
+
+let open_out_bin name =
+ open_out_gen [Open_wronly; Open_creat; Open_trunc; Open_binary] 0o666 name
+
+external flush : out_channel -> unit = "caml_ml_flush"
+
+external out_channels_list : unit -> out_channel list
+ = "caml_ml_out_channels_list"
+
+let flush_all () =
+ let rec iter = function
+ [] -> ()
+ | a :: l -> (try flush a with _ -> ()); iter l
+ in iter (out_channels_list ())
+
+external unsafe_output : out_channel -> bytes -> int -> int -> unit
+ = "caml_ml_output"
+external unsafe_output_string : out_channel -> string -> int -> int -> unit
+ = "caml_ml_output"
+
+external output_char : out_channel -> char -> unit = "caml_ml_output_char"
+
+let output_bytes oc s =
+ unsafe_output oc s 0 (bytes_length s)
+
+let output_string oc s =
+ unsafe_output_string oc s 0 (string_length s)
+
+let output oc s ofs len =
+ if ofs < 0 || len < 0 || ofs > bytes_length s - len
+ then invalid_arg "output"
+ else unsafe_output oc s ofs len
+
+let output_substring oc s ofs len =
+ if ofs < 0 || len < 0 || ofs > string_length s - len
+ then invalid_arg "output_substring"
+ else unsafe_output_string oc s ofs len
+
+external output_byte : out_channel -> int -> unit = "caml_ml_output_char"
+external output_binary_int : out_channel -> int -> unit = "caml_ml_output_int"
+
+external marshal_to_channel : out_channel -> 'a -> unit list -> unit
+ = "caml_output_value"
+let output_value chan v = marshal_to_channel chan v []
+
+external seek_out : out_channel -> int -> unit = "caml_ml_seek_out"
+external pos_out : out_channel -> int = "caml_ml_pos_out"
+external out_channel_length : out_channel -> int = "caml_ml_channel_size"
+external close_out_channel : out_channel -> unit = "caml_ml_close_channel"
+let close_out oc = flush oc; close_out_channel oc
+let close_out_noerr oc =
+ (try flush oc with _ -> ());
+ (try close_out_channel oc with _ -> ())
+external set_binary_mode_out : out_channel -> bool -> unit
+ = "caml_ml_set_binary_mode"
+
+(* General input functions *)
+
+external set_in_channel_name: in_channel -> string -> unit =
+ "caml_ml_set_channel_name"
+
+let open_in_gen mode perm name =
+ let c = open_descriptor_in(open_desc name mode perm) in
+ set_in_channel_name c name;
+ c
+
+let open_in name =
+ open_in_gen [Open_rdonly; Open_text] 0 name
+
+let open_in_bin name =
+ open_in_gen [Open_rdonly; Open_binary] 0 name
+
+external input_char : in_channel -> char = "caml_ml_input_char"
+
+external unsafe_input : in_channel -> bytes -> int -> int -> int
+ = "caml_ml_input"
+
+let input ic s ofs len =
+ if ofs < 0 || len < 0 || ofs > bytes_length s - len
+ then invalid_arg "input"
+ else unsafe_input ic s ofs len
+
+let rec unsafe_really_input ic s ofs len =
+ if len <= 0 then () else begin
+ let r = unsafe_input ic s ofs len in
+ if r = 0
+ then raise End_of_file
+ else unsafe_really_input ic s (ofs + r) (len - r)
+ end
+
+let really_input ic s ofs len =
+ if ofs < 0 || len < 0 || ofs > bytes_length s - len
+ then invalid_arg "really_input"
+ else unsafe_really_input ic s ofs len
+
+let really_input_string ic len =
+ let s = bytes_create len in
+ really_input ic s 0 len;
+ bytes_unsafe_to_string s
+
+external input_scan_line : in_channel -> int = "caml_ml_input_scan_line"
+
+let input_line chan =
+ let rec build_result buf pos = function
+ [] -> buf
+ | hd :: tl ->
+ let len = bytes_length hd in
+ bytes_blit hd 0 buf (pos - len) len;
+ build_result buf (pos - len) tl in
+ let rec scan accu len =
+ let n = input_scan_line chan in
+ if n = 0 then begin (* n = 0: we are at EOF *)
+ match accu with
+ [] -> raise End_of_file
+ | _ -> build_result (bytes_create len) len accu
+ end else if n > 0 then begin (* n > 0: newline found in buffer *)
+ let res = bytes_create (n - 1) in
+ ignore (unsafe_input chan res 0 (n - 1));
+ ignore (input_char chan); (* skip the newline *)
+ match accu with
+ [] -> res
+ | _ -> let len = len + n - 1 in
+ build_result (bytes_create len) len (res :: accu)
+ end else begin (* n < 0: newline not found *)
+ let beg = bytes_create (-n) in
+ ignore(unsafe_input chan beg 0 (-n));
+ scan (beg :: accu) (len - n)
+ end
+ in bytes_unsafe_to_string (scan [] 0)
+
+external input_byte : in_channel -> int = "caml_ml_input_char"
+external input_binary_int : in_channel -> int = "caml_ml_input_int"
+external input_value : in_channel -> 'a = "caml_input_value"
+external seek_in : in_channel -> int -> unit = "caml_ml_seek_in"
+external pos_in : in_channel -> int = "caml_ml_pos_in"
+external in_channel_length : in_channel -> int = "caml_ml_channel_size"
+external close_in : in_channel -> unit = "caml_ml_close_channel"
+let close_in_noerr ic = (try close_in ic with _ -> ());;
+external set_binary_mode_in : in_channel -> bool -> unit
+ = "caml_ml_set_binary_mode"
+
+(* Output functions on standard output *)
+
+let print_char c = output_char stdout c
+let print_string s = output_string stdout s
+let print_bytes s = output_bytes stdout s
+let print_int i = output_string stdout (string_of_int i)
+let print_float f = output_string stdout (string_of_float f)
+let print_endline s =
+ output_string stdout s; output_char stdout '\n'; flush stdout
+let print_newline () = output_char stdout '\n'; flush stdout
+
+(* Output functions on standard error *)
+
+let prerr_char c = output_char stderr c
+let prerr_string s = output_string stderr s
+let prerr_bytes s = output_bytes stderr s
+let prerr_int i = output_string stderr (string_of_int i)
+let prerr_float f = output_string stderr (string_of_float f)
+let prerr_endline s =
+ output_string stderr s; output_char stderr '\n'; flush stderr
+let prerr_newline () = output_char stderr '\n'; flush stderr
+
+(* Input functions on standard input *)
+
+let read_line () = flush stdout; input_line stdin
+let read_int () = int_of_string(read_line())
+let read_float () = float_of_string(read_line())
+
+(* Operations on large files *)
+
+module LargeFile =
+ struct
+ external seek_out : out_channel -> int64 -> unit = "caml_ml_seek_out_64"
+ external pos_out : out_channel -> int64 = "caml_ml_pos_out_64"
+ external out_channel_length : out_channel -> int64
+ = "caml_ml_channel_size_64"
+ external seek_in : in_channel -> int64 -> unit = "caml_ml_seek_in_64"
+ external pos_in : in_channel -> int64 = "caml_ml_pos_in_64"
+ external in_channel_length : in_channel -> int64 = "caml_ml_channel_size_64"
+ end
+
+(* Formats *)
+
+type ('a, 'b, 'c, 'd, 'e, 'f) format6
+ = ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6
+ = Format of ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.fmt
+ * string
+
+type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6
+
+type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
+
+let string_of_format (Format (fmt, str)) = str
+
+external format_of_string :
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity"
+
+let (^^) (Format (fmt1, str1)) (Format (fmt2, str2)) =
+ Format (CamlinternalFormatBasics.concat_fmt fmt1 fmt2,
+ str1 ^ "%," ^ str2)
+
+(* Miscellaneous *)
+
+external sys_exit : int -> 'a = "caml_sys_exit"
+
+let exit_function = ref flush_all
+
+let at_exit f =
+ let g = !exit_function in
+ exit_function := (fun () -> f(); g())
+
+let do_at_exit () = (!exit_function) ()
+
+let exit retcode =
+ do_at_exit ();
+ sys_exit retcode
+
+let _ = register_named_value "Pervasives.do_at_exit" do_at_exit
diff --git a/stdlib/pervasives.mli b/stdlib/pervasives.mli
new file mode 100644
index 0000000000..4464866c9d
--- /dev/null
+++ b/stdlib/pervasives.mli
@@ -0,0 +1,1118 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** The initially opened module.
+
+ This module provides the basic operations over the built-in types
+ (numbers, booleans, byte sequences, strings, exceptions, references,
+ lists, arrays, input-output channels, ...).
+
+ This module is automatically opened at the beginning of each compilation.
+ All components of this module can therefore be referred by their short
+ name, without prefixing them by [Pervasives].
+*)
+
+
+(** {6 Exceptions} *)
+
+external raise : exn -> 'a = "%raise"
+(** Raise the given exception value *)
+
+external raise_notrace : exn -> 'a = "%raise_notrace"
+(** A faster version [raise] which does not record the backtrace.
+ @since 4.02.0
+*)
+
+val invalid_arg : string -> 'a
+(** Raise exception [Invalid_argument] with the given string. *)
+
+val failwith : string -> 'a
+(** Raise exception [Failure] with the given string. *)
+
+exception Exit
+(** The [Exit] exception is not raised by any library function. It is
+ provided for use in your programs. *)
+
+
+(** {6 Comparisons} *)
+
+external ( = ) : 'a -> 'a -> bool = "%equal"
+(** [e1 = e2] tests for structural equality of [e1] and [e2].
+ Mutable structures (e.g. references and arrays) are equal
+ if and only if their current contents are structurally equal,
+ even if the two mutable objects are not the same physical object.
+ Equality between functional values raises [Invalid_argument].
+ Equality between cyclic data structures may not terminate. *)
+
+external ( <> ) : 'a -> 'a -> bool = "%notequal"
+(** Negation of {!Pervasives.( = )}. *)
+
+external ( < ) : 'a -> 'a -> bool = "%lessthan"
+(** See {!Pervasives.( >= )}. *)
+
+external ( > ) : 'a -> 'a -> bool = "%greaterthan"
+(** See {!Pervasives.( >= )}. *)
+
+external ( <= ) : 'a -> 'a -> bool = "%lessequal"
+(** See {!Pervasives.( >= )}. *)
+
+external ( >= ) : 'a -> 'a -> bool = "%greaterequal"
+(** Structural ordering functions. These functions coincide with
+ the usual orderings over integers, characters, strings, byte sequences
+ and floating-point numbers, and extend them to a
+ total ordering over all types.
+ The ordering is compatible with [( = )]. As in the case
+ of [( = )], mutable structures are compared by contents.
+ Comparison between functional values raises [Invalid_argument].
+ Comparison between cyclic structures may not terminate. *)
+
+external compare : 'a -> 'a -> int = "%compare"
+(** [compare x y] returns [0] if [x] is equal to [y],
+ a negative integer if [x] is less than [y], and a positive integer
+ if [x] is greater than [y]. The ordering implemented by [compare]
+ is compatible with the comparison predicates [=], [<] and [>]
+ defined above, with one difference on the treatment of the float value
+ {!Pervasives.nan}. Namely, the comparison predicates treat [nan]
+ as different from any other float value, including itself;
+ while [compare] treats [nan] as equal to itself and less than any
+ other float value. This treatment of [nan] ensures that [compare]
+ defines a total ordering relation.
+
+ [compare] applied to functional values may raise [Invalid_argument].
+ [compare] applied to cyclic structures may not terminate.
+
+ The [compare] function can be used as the comparison function
+ required by the {!Set.Make} and {!Map.Make} functors, as well as
+ the {!List.sort} and {!Array.sort} functions. *)
+
+val min : 'a -> 'a -> 'a
+(** Return the smaller of the two arguments.
+ The result is unspecified if one of the arguments contains
+ the float value [nan]. *)
+
+val max : 'a -> 'a -> 'a
+(** Return the greater of the two arguments.
+ The result is unspecified if one of the arguments contains
+ the float value [nan]. *)
+
+external ( == ) : 'a -> 'a -> bool = "%eq"
+(** [e1 == e2] tests for physical equality of [e1] and [e2].
+ On mutable types such as references, arrays, byte sequences, records with
+ mutable fields and objects with mutable instance variables,
+ [e1 == e2] is true if and only if physical modification of [e1]
+ also affects [e2].
+ On non-mutable types, the behavior of [( == )] is
+ implementation-dependent; however, it is guaranteed that
+ [e1 == e2] implies [compare e1 e2 = 0]. *)
+
+external ( != ) : 'a -> 'a -> bool = "%noteq"
+(** Negation of {!Pervasives.( == )}. *)
+
+
+(** {6 Boolean operations} *)
+
+external not : bool -> bool = "%boolnot"
+(** The boolean negation. *)
+
+external ( && ) : bool -> bool -> bool = "%sequand"
+(** The boolean 'and'. Evaluation is sequential, left-to-right:
+ in [e1 && e2], [e1] is evaluated first, and if it returns [false],
+ [e2] is not evaluated at all. *)
+
+external ( & ) : bool -> bool -> bool = "%sequand"
+ [@@ocaml.deprecated "Use (&&) instead."]
+(** @deprecated {!Pervasives.( && )} should be used instead. *)
+
+external ( || ) : bool -> bool -> bool = "%sequor"
+(** The boolean 'or'. Evaluation is sequential, left-to-right:
+ in [e1 || e2], [e1] is evaluated first, and if it returns [true],
+ [e2] is not evaluated at all. *)
+
+external ( or ) : bool -> bool -> bool = "%sequor"
+ [@@ocaml.deprecated "Use (||) instead."]
+(** @deprecated {!Pervasives.( || )} should be used instead.*)
+
+(** {6 Debugging} *)
+
+external __LOC__ : string = "%loc_LOC"
+(** [__LOC__] returns the location at which this expression appears in
+ the file currently being parsed by the compiler, with the standard
+ error format of OCaml: "File %S, line %d, characters %d-%d".
+ @since 4.02.0
+ *)
+external __FILE__ : string = "%loc_FILE"
+(** [__FILE__] returns the name of the file currently being
+ parsed by the compiler.
+ @since 4.02.0
+*)
+external __LINE__ : int = "%loc_LINE"
+(** [__LINE__] returns the line number at which this expression
+ appears in the file currently being parsed by the compiler.
+ @since 4.02.0
+ *)
+external __MODULE__ : string = "%loc_MODULE"
+(** [__MODULE__] returns the module name of the file being
+ parsed by the compiler.
+ @since 4.02.0
+ *)
+external __POS__ : string * int * int * int = "%loc_POS"
+(** [__POS__] returns a tuple [(file,lnum,cnum,enum)], corresponding
+ to the location at which this expression appears in the file
+ currently being parsed by the compiler. [file] is the current
+ filename, [lnum] the line number, [cnum] the character position in
+ the line and [enum] the last character position in the line.
+ @since 4.02.0
+ *)
+
+external __LOC_OF__ : 'a -> string * 'a = "%loc_LOC"
+(** [__LOC_OF__ expr] returns a pair [(loc, expr)] where [loc] is the
+ location of [expr] in the file currently being parsed by the
+ compiler, with the standard error format of OCaml: "File %S, line
+ %d, characters %d-%d".
+ @since 4.02.0
+ *)
+external __LINE_OF__ : 'a -> int * 'a = "%loc_LINE"
+(** [__LINE__ expr] returns a pair [(line, expr)], where [line] is the
+ line number at which the expression [expr] appears in the file
+ currently being parsed by the compiler.
+ @since 4.02.0
+ *)
+external __POS_OF__ : 'a -> (string * int * int * int) * 'a = "%loc_POS"
+(** [__POS_OF__ expr] returns a pair [(loc,expr)], where [loc] is a
+ tuple [(file,lnum,cnum,enum)] corresponding to the location at
+ which the expression [expr] appears in the file currently being
+ parsed by the compiler. [file] is the current filename, [lnum] the
+ line number, [cnum] the character position in the line and [enum]
+ the last character position in the line.
+ @since 4.02.0
+ *)
+
+(** {6 Composition operators} *)
+
+external ( |> ) : 'a -> ('a -> 'b) -> 'b = "%revapply"
+(** Reverse-application operator: [x |> f |> g] is exactly equivalent
+ to [g (f (x))].
+ @since 4.01
+*)
+
+external ( @@ ) : ('a -> 'b) -> 'a -> 'b = "%apply"
+(** Application operator: [g @@ f @@ x] is exactly equivalent to
+ [g (f (x))].
+ @since 4.01
+*)
+
+(** {6 Integer arithmetic} *)
+
+(** Integers are 31 bits wide (or 63 bits on 64-bit processors).
+ All operations are taken modulo 2{^31} (or 2{^63}).
+ They do not fail on overflow. *)
+
+external ( ~- ) : int -> int = "%negint"
+(** Unary negation. You can also write [- e] instead of [~- e]. *)
+
+external ( ~+ ) : int -> int = "%identity"
+(** Unary addition. You can also write [+ e] instead of [~+ e].
+ @since 3.12.0
+*)
+
+external succ : int -> int = "%succint"
+(** [succ x] is [x + 1]. *)
+
+external pred : int -> int = "%predint"
+(** [pred x] is [x - 1]. *)
+
+external ( + ) : int -> int -> int = "%addint"
+(** Integer addition. *)
+
+external ( - ) : int -> int -> int = "%subint"
+(** Integer subtraction. *)
+
+external ( * ) : int -> int -> int = "%mulint"
+(** Integer multiplication. *)
+
+external ( / ) : int -> int -> int = "%divint"
+(** Integer division.
+ Raise [Division_by_zero] if the second argument is 0.
+ Integer division rounds the real quotient of its arguments towards zero.
+ More precisely, if [x >= 0] and [y > 0], [x / y] is the greatest integer
+ less than or equal to the real quotient of [x] by [y]. Moreover,
+ [(- x) / y = x / (- y) = - (x / y)]. *)
+
+external ( mod ) : int -> int -> int = "%modint"
+(** Integer remainder. If [y] is not zero, the result
+ of [x mod y] satisfies the following properties:
+ [x = (x / y) * y + x mod y] and
+ [abs(x mod y) <= abs(y) - 1].
+ If [y = 0], [x mod y] raises [Division_by_zero].
+ Note that [x mod y] is negative only if [x < 0].
+ Raise [Division_by_zero] if [y] is zero. *)
+
+val abs : int -> int
+(** Return the absolute value of the argument. Note that this may be
+ negative if the argument is [min_int]. *)
+
+val max_int : int
+(** The greatest representable integer. *)
+
+val min_int : int
+(** The smallest representable integer. *)
+
+
+(** {7 Bitwise operations} *)
+
+external ( land ) : int -> int -> int = "%andint"
+(** Bitwise logical and. *)
+
+external ( lor ) : int -> int -> int = "%orint"
+(** Bitwise logical or. *)
+
+external ( lxor ) : int -> int -> int = "%xorint"
+(** Bitwise logical exclusive or. *)
+
+val lnot : int -> int
+(** Bitwise logical negation. *)
+
+external ( lsl ) : int -> int -> int = "%lslint"
+(** [n lsl m] shifts [n] to the left by [m] bits.
+ The result is unspecified if [m < 0] or [m >= bitsize],
+ where [bitsize] is [32] on a 32-bit platform and
+ [64] on a 64-bit platform. *)
+
+external ( lsr ) : int -> int -> int = "%lsrint"
+(** [n lsr m] shifts [n] to the right by [m] bits.
+ This is a logical shift: zeroes are inserted regardless of
+ the sign of [n].
+ The result is unspecified if [m < 0] or [m >= bitsize]. *)
+
+external ( asr ) : int -> int -> int = "%asrint"
+(** [n asr m] shifts [n] to the right by [m] bits.
+ This is an arithmetic shift: the sign bit of [n] is replicated.
+ The result is unspecified if [m < 0] or [m >= bitsize]. *)
+
+
+(** {6 Floating-point arithmetic}
+
+ OCaml's floating-point numbers follow the
+ IEEE 754 standard, using double precision (64 bits) numbers.
+ Floating-point operations never raise an exception on overflow,
+ underflow, division by zero, etc. Instead, special IEEE numbers
+ are returned as appropriate, such as [infinity] for [1.0 /. 0.0],
+ [neg_infinity] for [-1.0 /. 0.0], and [nan] ('not a number')
+ for [0.0 /. 0.0]. These special numbers then propagate through
+ floating-point computations as expected: for instance,
+ [1.0 /. infinity] is [0.0], and any arithmetic operation with [nan]
+ as argument returns [nan] as result.
+*)
+
+external ( ~-. ) : float -> float = "%negfloat"
+(** Unary negation. You can also write [-. e] instead of [~-. e]. *)
+
+external ( ~+. ) : float -> float = "%identity"
+(** Unary addition. You can also write [+. e] instead of [~+. e].
+ @since 3.12.0
+*)
+
+external ( +. ) : float -> float -> float = "%addfloat"
+(** Floating-point addition *)
+
+external ( -. ) : float -> float -> float = "%subfloat"
+(** Floating-point subtraction *)
+
+external ( *. ) : float -> float -> float = "%mulfloat"
+(** Floating-point multiplication *)
+
+external ( /. ) : float -> float -> float = "%divfloat"
+(** Floating-point division. *)
+
+external ( ** ) : float -> float -> float = "caml_power_float" "pow" "float"
+(** Exponentiation. *)
+
+external sqrt : float -> float = "caml_sqrt_float" "sqrt" "float"
+(** Square root. *)
+
+external exp : float -> float = "caml_exp_float" "exp" "float"
+(** Exponential. *)
+
+external log : float -> float = "caml_log_float" "log" "float"
+(** Natural logarithm. *)
+
+external log10 : float -> float = "caml_log10_float" "log10" "float"
+(** Base 10 logarithm. *)
+
+external expm1 : float -> float = "caml_expm1_float" "caml_expm1" "float"
+(** [expm1 x] computes [exp x -. 1.0], giving numerically-accurate results
+ even if [x] is close to [0.0].
+ @since 3.12.0
+*)
+
+external log1p : float -> float = "caml_log1p_float" "caml_log1p" "float"
+(** [log1p x] computes [log(1.0 +. x)] (natural logarithm),
+ giving numerically-accurate results even if [x] is close to [0.0].
+ @since 3.12.0
+*)
+
+external cos : float -> float = "caml_cos_float" "cos" "float"
+(** Cosine. Argument is in radians. *)
+
+external sin : float -> float = "caml_sin_float" "sin" "float"
+(** Sine. Argument is in radians. *)
+
+external tan : float -> float = "caml_tan_float" "tan" "float"
+(** Tangent. Argument is in radians. *)
+
+external acos : float -> float = "caml_acos_float" "acos" "float"
+(** Arc cosine. The argument must fall within the range [[-1.0, 1.0]].
+ Result is in radians and is between [0.0] and [pi]. *)
+
+external asin : float -> float = "caml_asin_float" "asin" "float"
+(** Arc sine. The argument must fall within the range [[-1.0, 1.0]].
+ Result is in radians and is between [-pi/2] and [pi/2]. *)
+
+external atan : float -> float = "caml_atan_float" "atan" "float"
+(** Arc tangent.
+ Result is in radians and is between [-pi/2] and [pi/2]. *)
+
+external atan2 : float -> float -> float = "caml_atan2_float" "atan2" "float"
+(** [atan2 y x] returns the arc tangent of [y /. x]. The signs of [x]
+ and [y] are used to determine the quadrant of the result.
+ Result is in radians and is between [-pi] and [pi]. *)
+
+external hypot : float -> float -> float
+ = "caml_hypot_float" "caml_hypot" "float"
+(** [hypot x y] returns [sqrt(x *. x + y *. y)], that is, the length
+ of the hypotenuse of a right-angled triangle with sides of length
+ [x] and [y], or, equivalently, the distance of the point [(x,y)]
+ to origin.
+ @since 4.00.0 *)
+
+external cosh : float -> float = "caml_cosh_float" "cosh" "float"
+(** Hyperbolic cosine. Argument is in radians. *)
+
+external sinh : float -> float = "caml_sinh_float" "sinh" "float"
+(** Hyperbolic sine. Argument is in radians. *)
+
+external tanh : float -> float = "caml_tanh_float" "tanh" "float"
+(** Hyperbolic tangent. Argument is in radians. *)
+
+external ceil : float -> float = "caml_ceil_float" "ceil" "float"
+(** Round above to an integer value.
+ [ceil f] returns the least integer value greater than or equal to [f].
+ The result is returned as a float. *)
+
+external floor : float -> float = "caml_floor_float" "floor" "float"
+(** Round below to an integer value.
+ [floor f] returns the greatest integer value less than or
+ equal to [f].
+ The result is returned as a float. *)
+
+external abs_float : float -> float = "%absfloat"
+(** [abs_float f] returns the absolute value of [f]. *)
+
+external copysign : float -> float -> float
+ = "caml_copysign_float" "caml_copysign" "float"
+(** [copysign x y] returns a float whose absolute value is that of [x]
+ and whose sign is that of [y]. If [x] is [nan], returns [nan].
+ If [y] is [nan], returns either [x] or [-. x], but it is not
+ specified which.
+ @since 4.00.0 *)
+
+external mod_float : float -> float -> float = "caml_fmod_float" "fmod" "float"
+(** [mod_float a b] returns the remainder of [a] with respect to
+ [b]. The returned value is [a -. n *. b], where [n]
+ is the quotient [a /. b] rounded towards zero to an integer. *)
+
+external frexp : float -> float * int = "caml_frexp_float"
+(** [frexp f] returns the pair of the significant
+ and the exponent of [f]. When [f] is zero, the
+ significant [x] and the exponent [n] of [f] are equal to
+ zero. When [f] is non-zero, they are defined by
+ [f = x *. 2 ** n] and [0.5 <= x < 1.0]. *)
+
+external ldexp : float -> int -> float = "caml_ldexp_float"
+(** [ldexp x n] returns [x *. 2 ** n]. *)
+
+external modf : float -> float * float = "caml_modf_float"
+(** [modf f] returns the pair of the fractional and integral
+ part of [f]. *)
+
+external float : int -> float = "%floatofint"
+(** Same as {!Pervasives.float_of_int}. *)
+
+external float_of_int : int -> float = "%floatofint"
+(** Convert an integer to floating-point. *)
+
+external truncate : float -> int = "%intoffloat"
+(** Same as {!Pervasives.int_of_float}. *)
+
+external int_of_float : float -> int = "%intoffloat"
+(** Truncate the given floating-point number to an integer.
+ The result is unspecified if the argument is [nan] or falls outside the
+ range of representable integers. *)
+
+val infinity : float
+(** Positive infinity. *)
+
+val neg_infinity : float
+(** Negative infinity. *)
+
+val nan : float
+(** A special floating-point value denoting the result of an
+ undefined operation such as [0.0 /. 0.0]. Stands for
+ 'not a number'. Any floating-point operation with [nan] as
+ argument returns [nan] as result. As for floating-point comparisons,
+ [=], [<], [<=], [>] and [>=] return [false] and [<>] returns [true]
+ if one or both of their arguments is [nan]. *)
+
+val max_float : float
+(** The largest positive finite value of type [float]. *)
+
+val min_float : float
+(** The smallest positive, non-zero, non-denormalized value of type [float]. *)
+
+val epsilon_float : float
+(** The difference between [1.0] and the smallest exactly representable
+ floating-point number greater than [1.0]. *)
+
+type fpclass =
+ FP_normal (** Normal number, none of the below *)
+ | FP_subnormal (** Number very close to 0.0, has reduced precision *)
+ | FP_zero (** Number is 0.0 or -0.0 *)
+ | FP_infinite (** Number is positive or negative infinity *)
+ | FP_nan (** Not a number: result of an undefined operation *)
+(** The five classes of floating-point numbers, as determined by
+ the {!Pervasives.classify_float} function. *)
+
+external classify_float : float -> fpclass = "caml_classify_float"
+(** Return the class of the given floating-point number:
+ normal, subnormal, zero, infinite, or not a number. *)
+
+
+(** {6 String operations}
+
+ More string operations are provided in module {!String}.
+*)
+
+val ( ^ ) : string -> string -> string
+(** String concatenation. *)
+
+
+(** {6 Character operations}
+
+ More character operations are provided in module {!Char}.
+*)
+
+external int_of_char : char -> int = "%identity"
+(** Return the ASCII code of the argument. *)
+
+val char_of_int : int -> char
+(** Return the character with the given ASCII code.
+ Raise [Invalid_argument "char_of_int"] if the argument is
+ outside the range 0--255. *)
+
+
+(** {6 Unit operations} *)
+
+external ignore : 'a -> unit = "%ignore"
+(** Discard the value of its argument and return [()].
+ For instance, [ignore(f x)] discards the result of
+ the side-effecting function [f]. It is equivalent to
+ [f x; ()], except that the latter may generate a
+ compiler warning; writing [ignore(f x)] instead
+ avoids the warning. *)
+
+
+(** {6 String conversion functions} *)
+
+val string_of_bool : bool -> string
+(** Return the string representation of a boolean. As the returned values
+ may be shared, the user should not modify them directly.
+*)
+
+val bool_of_string : string -> bool
+(** Convert the given string to a boolean.
+ Raise [Invalid_argument "bool_of_string"] if the string is not
+ ["true"] or ["false"]. *)
+
+val string_of_int : int -> string
+(** Return the string representation of an integer, in decimal. *)
+
+external int_of_string : string -> int = "caml_int_of_string"
+(** Convert the given string to an integer.
+ The string is read in decimal (by default) or in hexadecimal (if it
+ begins with [0x] or [0X]), octal (if it begins with [0o] or [0O]),
+ or binary (if it begins with [0b] or [0B]).
+ Raise [Failure "int_of_string"] if the given string is not
+ a valid representation of an integer, or if the integer represented
+ exceeds the range of integers representable in type [int]. *)
+
+val string_of_float : float -> string
+(** Return the string representation of a floating-point number. *)
+
+external float_of_string : string -> float = "caml_float_of_string"
+(** Convert the given string to a float. Raise [Failure "float_of_string"]
+ if the given string is not a valid representation of a float. *)
+
+
+(** {6 Pair operations} *)
+
+external fst : 'a * 'b -> 'a = "%field0"
+(** Return the first component of a pair. *)
+
+external snd : 'a * 'b -> 'b = "%field1"
+(** Return the second component of a pair. *)
+
+
+(** {6 List operations}
+
+ More list operations are provided in module {!List}.
+*)
+
+val ( @ ) : 'a list -> 'a list -> 'a list
+(** List concatenation. *)
+
+
+
+
+(** {6 Array index operators} *)
+
+external ( .() ) : 'a array -> int -> 'a = "%array_opt_get"
+(** Parenthesis index operator for arrays.
+ [ a.(index) ] is desugared to [ ( .() ) a index ]. *)
+
+external ( .() <- ) : 'a array -> int -> 'a -> unit = "%array_opt_set"
+(** Parenthesis indexed assignment operator for arrays.
+ [ a.(index) <- val ] is desugared to [ ( .() <- ) a index val ]*)
+
+
+(** {6 String index operators} *)
+
+external ( .[] ) : string -> int -> char = "%string_opt_get"
+(** Bracket index operator for strings.
+ [ a.[index] ] is desugared to [ (.[]) a index ]. *)
+
+external ( .[] <- ) : bytes -> int -> char-> unit = "%string_opt_set"
+(** Bracket indexed assignment operator for bytes.
+ [ a.[index] <- val ] is desugared to [ ( .[]<- ) a index val ]. *)
+
+(** {6 Input/output}
+ Note: all input/output functions can raise [Sys_error] when the system
+ calls they invoke fail. *)
+
+type in_channel
+(** The type of input channel. *)
+
+type out_channel
+(** The type of output channel. *)
+
+val stdin : in_channel
+(** The standard input for the process. *)
+
+val stdout : out_channel
+(** The standard output for the process. *)
+
+val stderr : out_channel
+(** The standard error output for the process. *)
+
+
+(** {7 Output functions on standard output} *)
+
+val print_char : char -> unit
+(** Print a character on standard output. *)
+
+val print_string : string -> unit
+(** Print a string on standard output. *)
+
+val print_bytes : bytes -> unit
+(** Print a byte sequence on standard output.
+ @since 4.02.0 *)
+
+val print_int : int -> unit
+(** Print an integer, in decimal, on standard output. *)
+
+val print_float : float -> unit
+(** Print a floating-point number, in decimal, on standard output. *)
+
+val print_endline : string -> unit
+(** Print a string, followed by a newline character, on
+ standard output and flush standard output. *)
+
+val print_newline : unit -> unit
+(** Print a newline character on standard output, and flush
+ standard output. This can be used to simulate line
+ buffering of standard output. *)
+
+
+(** {7 Output functions on standard error} *)
+
+val prerr_char : char -> unit
+(** Print a character on standard error. *)
+
+val prerr_string : string -> unit
+(** Print a string on standard error. *)
+
+val prerr_bytes : bytes -> unit
+(** Print a byte sequence on standard error.
+ @since 4.02.0 *)
+
+val prerr_int : int -> unit
+(** Print an integer, in decimal, on standard error. *)
+
+val prerr_float : float -> unit
+(** Print a floating-point number, in decimal, on standard error. *)
+
+val prerr_endline : string -> unit
+(** Print a string, followed by a newline character on standard
+ error and flush standard error. *)
+
+val prerr_newline : unit -> unit
+(** Print a newline character on standard error, and flush
+ standard error. *)
+
+
+(** {7 Input functions on standard input} *)
+
+val read_line : unit -> string
+(** Flush standard output, then read characters from standard input
+ until a newline character is encountered. Return the string of
+ all characters read, without the newline character at the end. *)
+
+val read_int : unit -> int
+(** Flush standard output, then read one line from standard input
+ and convert it to an integer. Raise [Failure "int_of_string"]
+ if the line read is not a valid representation of an integer. *)
+
+val read_float : unit -> float
+(** Flush standard output, then read one line from standard input
+ and convert it to a floating-point number.
+ The result is unspecified if the line read is not a valid
+ representation of a floating-point number. *)
+
+
+(** {7 General output functions} *)
+
+type open_flag =
+ Open_rdonly (** open for reading. *)
+ | Open_wronly (** open for writing. *)
+ | Open_append (** open for appending: always write at end of file. *)
+ | Open_creat (** create the file if it does not exist. *)
+ | Open_trunc (** empty the file if it already exists. *)
+ | Open_excl (** fail if Open_creat and the file already exists. *)
+ | Open_binary (** open in binary mode (no conversion). *)
+ | Open_text (** open in text mode (may perform conversions). *)
+ | Open_nonblock (** open in non-blocking mode. *)
+(** Opening modes for {!Pervasives.open_out_gen} and
+ {!Pervasives.open_in_gen}. *)
+
+val open_out : string -> out_channel
+(** Open the named file for writing, and return a new output channel
+ on that file, positionned at the beginning of the file. The
+ file is truncated to zero length if it already exists. It
+ is created if it does not already exists. *)
+
+val open_out_bin : string -> out_channel
+(** Same as {!Pervasives.open_out}, but the file is opened in binary mode,
+ so that no translation takes place during writes. On operating
+ systems that do not distinguish between text mode and binary
+ mode, this function behaves like {!Pervasives.open_out}. *)
+
+val open_out_gen : open_flag list -> int -> string -> out_channel
+(** [open_out_gen mode perm filename] opens the named file for writing,
+ as described above. The extra argument [mode]
+ specify the opening mode. The extra argument [perm] specifies
+ the file permissions, in case the file must be created.
+ {!Pervasives.open_out} and {!Pervasives.open_out_bin} are special
+ cases of this function. *)
+
+val flush : out_channel -> unit
+(** Flush the buffer associated with the given output channel,
+ performing all pending writes on that channel.
+ Interactive programs must be careful about flushing standard
+ output and standard error at the right time. *)
+
+val flush_all : unit -> unit
+(** Flush all open output channels; ignore errors. *)
+
+val output_char : out_channel -> char -> unit
+(** Write the character on the given output channel. *)
+
+val output_string : out_channel -> string -> unit
+(** Write the string on the given output channel. *)
+
+val output_bytes : out_channel -> bytes -> unit
+(** Write the byte sequence on the given output channel.
+ @since 4.02.0 *)
+
+val output : out_channel -> bytes -> int -> int -> unit
+(** [output oc buf pos len] writes [len] characters from byte sequence [buf],
+ starting at offset [pos], to the given output channel [oc].
+ Raise [Invalid_argument "output"] if [pos] and [len] do not
+ designate a valid range of [buf]. *)
+
+val output_substring : out_channel -> string -> int -> int -> unit
+(** Same as [output] but take a string as argument instead of
+ a byte sequence.
+ @since 4.02.0 *)
+
+val output_byte : out_channel -> int -> unit
+(** Write one 8-bit integer (as the single character with that code)
+ on the given output channel. The given integer is taken modulo
+ 256. *)
+
+val output_binary_int : out_channel -> int -> unit
+(** Write one integer in binary format (4 bytes, big-endian)
+ on the given output channel.
+ The given integer is taken modulo 2{^32}.
+ The only reliable way to read it back is through the
+ {!Pervasives.input_binary_int} function. The format is compatible across
+ all machines for a given version of OCaml. *)
+
+val output_value : out_channel -> 'a -> unit
+(** Write the representation of a structured value of any type
+ to a channel. Circularities and sharing inside the value
+ are detected and preserved. The object can be read back,
+ by the function {!Pervasives.input_value}. See the description of module
+ {!Marshal} for more information. {!Pervasives.output_value} is equivalent
+ to {!Marshal.to_channel} with an empty list of flags. *)
+
+val seek_out : out_channel -> int -> unit
+(** [seek_out chan pos] sets the current writing position to [pos]
+ for channel [chan]. This works only for regular files. On
+ files of other kinds (such as terminals, pipes and sockets),
+ the behavior is unspecified. *)
+
+val pos_out : out_channel -> int
+(** Return the current writing position for the given channel. Does
+ not work on channels opened with the [Open_append] flag (returns
+ unspecified results). *)
+
+val out_channel_length : out_channel -> int
+(** Return the size (number of characters) of the regular file
+ on which the given channel is opened. If the channel is opened
+ on a file that is not a regular file, the result is meaningless. *)
+
+val close_out : out_channel -> unit
+(** Close the given channel, flushing all buffered write operations.
+ Output functions raise a [Sys_error] exception when they are
+ applied to a closed output channel, except [close_out] and [flush],
+ which do nothing when applied to an already closed channel.
+ Note that [close_out] may raise [Sys_error] if the operating
+ system signals an error when flushing or closing. *)
+
+val close_out_noerr : out_channel -> unit
+(** Same as [close_out], but ignore all errors. *)
+
+val set_binary_mode_out : out_channel -> bool -> unit
+(** [set_binary_mode_out oc true] sets the channel [oc] to binary
+ mode: no translations take place during output.
+ [set_binary_mode_out oc false] sets the channel [oc] to text
+ mode: depending on the operating system, some translations
+ may take place during output. For instance, under Windows,
+ end-of-lines will be translated from [\n] to [\r\n].
+ This function has no effect under operating systems that
+ do not distinguish between text mode and binary mode. *)
+
+
+(** {7 General input functions} *)
+
+val open_in : string -> in_channel
+(** Open the named file for reading, and return a new input channel
+ on that file, positionned at the beginning of the file. *)
+
+val open_in_bin : string -> in_channel
+(** Same as {!Pervasives.open_in}, but the file is opened in binary mode,
+ so that no translation takes place during reads. On operating
+ systems that do not distinguish between text mode and binary
+ mode, this function behaves like {!Pervasives.open_in}. *)
+
+val open_in_gen : open_flag list -> int -> string -> in_channel
+(** [open_in_gen mode perm filename] opens the named file for reading,
+ as described above. The extra arguments
+ [mode] and [perm] specify the opening mode and file permissions.
+ {!Pervasives.open_in} and {!Pervasives.open_in_bin} are special
+ cases of this function. *)
+
+val input_char : in_channel -> char
+(** Read one character from the given input channel.
+ Raise [End_of_file] if there are no more characters to read. *)
+
+val input_line : in_channel -> string
+(** Read characters from the given input channel, until a
+ newline character is encountered. Return the string of
+ all characters read, without the newline character at the end.
+ Raise [End_of_file] if the end of the file is reached
+ at the beginning of line. *)
+
+val input : in_channel -> bytes -> int -> int -> int
+(** [input ic buf pos len] reads up to [len] characters from
+ the given channel [ic], storing them in byte sequence [buf], starting at
+ character number [pos].
+ It returns the actual number of characters read, between 0 and
+ [len] (inclusive).
+ A return value of 0 means that the end of file was reached.
+ A return value between 0 and [len] exclusive means that
+ not all requested [len] characters were read, either because
+ no more characters were available at that time, or because
+ the implementation found it convenient to do a partial read;
+ [input] must be called again to read the remaining characters,
+ if desired. (See also {!Pervasives.really_input} for reading
+ exactly [len] characters.)
+ Exception [Invalid_argument "input"] is raised if [pos] and [len]
+ do not designate a valid range of [buf]. *)
+
+val really_input : in_channel -> bytes -> int -> int -> unit
+(** [really_input ic buf pos len] reads [len] characters from channel [ic],
+ storing them in byte sequence [buf], starting at character number [pos].
+ Raise [End_of_file] if the end of file is reached before [len]
+ characters have been read.
+ Raise [Invalid_argument "really_input"] if
+ [pos] and [len] do not designate a valid range of [buf]. *)
+
+val really_input_string : in_channel -> int -> string
+(** [really_input_string ic len] reads [len] characters from channel [ic]
+ and returns them in a new string.
+ Raise [End_of_file] if the end of file is reached before [len]
+ characters have been read.
+ @since 4.02.0 *)
+
+val input_byte : in_channel -> int
+(** Same as {!Pervasives.input_char}, but return the 8-bit integer representing
+ the character.
+ Raise [End_of_file] if an end of file was reached. *)
+
+val input_binary_int : in_channel -> int
+(** Read an integer encoded in binary format (4 bytes, big-endian)
+ from the given input channel. See {!Pervasives.output_binary_int}.
+ Raise [End_of_file] if an end of file was reached while reading the
+ integer. *)
+
+val input_value : in_channel -> 'a
+(** Read the representation of a structured value, as produced
+ by {!Pervasives.output_value}, and return the corresponding value.
+ This function is identical to {!Marshal.from_channel};
+ see the description of module {!Marshal} for more information,
+ in particular concerning the lack of type safety. *)
+
+val seek_in : in_channel -> int -> unit
+(** [seek_in chan pos] sets the current reading position to [pos]
+ for channel [chan]. This works only for regular files. On
+ files of other kinds, the behavior is unspecified. *)
+
+val pos_in : in_channel -> int
+(** Return the current reading position for the given channel. *)
+
+val in_channel_length : in_channel -> int
+(** Return the size (number of characters) of the regular file
+ on which the given channel is opened. If the channel is opened
+ on a file that is not a regular file, the result is meaningless.
+ The returned size does not take into account the end-of-line
+ translations that can be performed when reading from a channel
+ opened in text mode. *)
+
+val close_in : in_channel -> unit
+(** Close the given channel. Input functions raise a [Sys_error]
+ exception when they are applied to a closed input channel,
+ except [close_in], which does nothing when applied to an already
+ closed channel. *)
+
+val close_in_noerr : in_channel -> unit
+(** Same as [close_in], but ignore all errors. *)
+
+val set_binary_mode_in : in_channel -> bool -> unit
+(** [set_binary_mode_in ic true] sets the channel [ic] to binary
+ mode: no translations take place during input.
+ [set_binary_mode_out ic false] sets the channel [ic] to text
+ mode: depending on the operating system, some translations
+ may take place during input. For instance, under Windows,
+ end-of-lines will be translated from [\r\n] to [\n].
+ This function has no effect under operating systems that
+ do not distinguish between text mode and binary mode. *)
+
+
+(** {7 Operations on large files} *)
+
+module LargeFile :
+ sig
+ val seek_out : out_channel -> int64 -> unit
+ val pos_out : out_channel -> int64
+ val out_channel_length : out_channel -> int64
+ val seek_in : in_channel -> int64 -> unit
+ val pos_in : in_channel -> int64
+ val in_channel_length : in_channel -> int64
+ end
+(** Operations on large files.
+ This sub-module provides 64-bit variants of the channel functions
+ that manipulate file positions and file sizes. By representing
+ positions and sizes by 64-bit integers (type [int64]) instead of
+ regular integers (type [int]), these alternate functions allow
+ operating on files whose sizes are greater than [max_int]. *)
+
+
+(** {6 References} *)
+
+type 'a ref = { mutable contents : 'a }
+(** The type of references (mutable indirection cells) containing
+ a value of type ['a]. *)
+
+external ref : 'a -> 'a ref = "%makemutable"
+(** Return a fresh reference containing the given value. *)
+
+external ( ! ) : 'a ref -> 'a = "%field0"
+(** [!r] returns the current contents of reference [r].
+ Equivalent to [fun r -> r.contents]. *)
+
+external ( := ) : 'a ref -> 'a -> unit = "%setfield0"
+(** [r := a] stores the value of [a] in reference [r].
+ Equivalent to [fun r v -> r.contents <- v]. *)
+
+external incr : int ref -> unit = "%incr"
+(** Increment the integer contained in the given reference.
+ Equivalent to [fun r -> r := succ !r]. *)
+
+external decr : int ref -> unit = "%decr"
+(** Decrement the integer contained in the given reference.
+ Equivalent to [fun r -> r := pred !r]. *)
+
+(** {6 Result type} *)
+
+type ('a,'b) result = Ok of 'a | Error of 'b
+
+(** {6 Operations on format strings} *)
+
+(** Format strings are character strings with special lexical conventions
+ that defines the functionality of formatted input/output functions. Format
+ strings are used to read data with formatted input functions from module
+ {!Scanf} and to print data with formatted output functions from modules
+ {!Printf} and {!Format}.
+
+ Format strings are made of three kinds of entities:
+ - {e conversions specifications}, introduced by the special character ['%']
+ followed by one or more characters specifying what kind of argument to
+ read or print,
+ - {e formatting indications}, introduced by the special character ['@']
+ followed by one or more characters specifying how to read or print the
+ argument,
+ - {e plain characters} that are regular characters with usual lexical
+ conventions. Plain characters specify string literals to be read in the
+ input or printed in the output.
+
+ There is an additional lexical rule to escape the special characters ['%']
+ and ['@'] in format strings: if a special character follows a ['%']
+ character, it is treated as a plain character. In other words, ["%%"] is
+ considered as a plain ['%'] and ["%@"] as a plain ['@'].
+
+ For more information about conversion specifications and formatting
+ indications available, read the documentation of modules {!Scanf},
+ {!Printf} and {!Format}.
+*)
+
+(** Format strings have a general and highly polymorphic type
+ [('a, 'b, 'c, 'd, 'e, 'f) format6].
+ The two simplified types, [format] and [format4] below are
+ included for backward compatibility with earlier releases of
+ OCaml.
+
+ The meaning of format string type parameters is as follows:
+
+ - ['a] is the type of the parameters of the format for formatted output
+ functions ([printf]-style functions);
+ ['a] is the type of the values read by the format for formatted input
+ functions ([scanf]-style functions).
+
+ - ['b] is the type of input source for formatted input functions and the
+ type of output target for formatted output functions.
+ For [printf]-style functions from module [Printf], ['b] is typically
+ [out_channel];
+ for [printf]-style functions from module [Format], ['b] is typically
+ [Format.formatter];
+ for [scanf]-style functions from module [Scanf], ['b] is typically
+ [Scanf.Scanning.in_channel].
+
+ Type argument ['b] is also the type of the first argument given to
+ user's defined printing functions for [%a] and [%t] conversions,
+ and user's defined reading functions for [%r] conversion.
+
+ - ['c] is the type of the result of the [%a] and [%t] printing
+ functions, and also the type of the argument transmitted to the
+ first argument of [kprintf]-style functions or to the
+ [kscanf]-style functions.
+
+ - ['d] is the type of parameters for the [scanf]-style functions.
+
+ - ['e] is the type of the receiver function for the [scanf]-style functions.
+
+ - ['f] is the final result type of a formatted input/output function
+ invocation: for the [printf]-style functions, it is typically [unit];
+ for the [scanf]-style functions, it is typically the result type of the
+ receiver function.
+*)
+
+type ('a, 'b, 'c, 'd, 'e, 'f) format6 =
+ ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6
+
+type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6
+
+type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4
+
+val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string
+(** Converts a format string into a string. *)
+
+external format_of_string :
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity"
+(** [format_of_string s] returns a format string read from the string
+ literal [s].
+ Note: [format_of_string] can not convert a string argument that is not a
+ literal. If you need this functionality, use the more general
+ {!Scanf.format_from_string} function.
+*)
+
+val ( ^^ ) :
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ ('f, 'b, 'c, 'e, 'g, 'h) format6 ->
+ ('a, 'b, 'c, 'd, 'g, 'h) format6
+(** [f1 ^^ f2] catenates format strings [f1] and [f2]. The result is a
+ format string that behaves as the concatenation of format strings [f1] and
+ [f2]: in case of formatted output, it accepts arguments from [f1], then
+ arguments from [f2]; in case of formatted input, it returns results from
+ [f1], then results from [f2].
+*)
+
+
+(** {6 Program termination} *)
+
+val exit : int -> 'a
+(** Terminate the process, returning the given status code
+ to the operating system: usually 0 to indicate no errors,
+ and a small positive integer to indicate failure.
+ All open output channels are flushed with [flush_all].
+ An implicit [exit 0] is performed each time a program
+ terminates normally. An implicit [exit 2] is performed if the program
+ terminates early because of an uncaught exception. *)
+
+val at_exit : (unit -> unit) -> unit
+(** Register the given function to be called at program
+ termination time. The functions registered with [at_exit]
+ will be called when the program executes {!Pervasives.exit},
+ or terminates, either normally or because of an uncaught exception.
+ The functions are called in 'last in, first out' order:
+ the function most recently added with [at_exit] is called first. *)
+
+(**/**)
+
+(* The following is for system use only. Do not call directly. *)
+
+val valid_float_lexem : string -> string
+
+val unsafe_really_input : in_channel -> bytes -> int -> int -> unit
+
+val do_at_exit : unit -> unit
diff --git a/stdlib/printexc.ml b/stdlib/printexc.ml
new file mode 100644
index 0000000000..4ebb84ceae
--- /dev/null
+++ b/stdlib/printexc.ml
@@ -0,0 +1,295 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open Printf;;
+
+let printers = ref []
+
+let locfmt = format_of_string "File \"%s\", line %d, characters %d-%d: %s";;
+
+let field x i =
+ let f = Obj.field x i in
+ if not (Obj.is_block f) then
+ sprintf "%d" (Obj.magic f : int) (* can also be a char *)
+ else if Obj.tag f = Obj.string_tag then
+ sprintf "%S" (Obj.magic f : string)
+ else if Obj.tag f = Obj.double_tag then
+ string_of_float (Obj.magic f : float)
+ else
+ "_"
+;;
+let rec other_fields x i =
+ if i >= Obj.size x then ""
+ else sprintf ", %s%s" (field x i) (other_fields x (i+1))
+;;
+let fields x =
+ match Obj.size x with
+ | 0 -> ""
+ | 1 -> ""
+ | 2 -> sprintf "(%s)" (field x 1)
+ | n -> sprintf "(%s%s)" (field x 1) (other_fields x 2)
+;;
+
+let to_string x =
+ let rec conv = function
+ | hd :: tl ->
+ (match try hd x with _ -> None with
+ | Some s -> s
+ | None -> conv tl)
+ | [] ->
+ match x with
+ | Out_of_memory -> "Out of memory"
+ | Stack_overflow -> "Stack overflow"
+ | Match_failure(file, line, char) ->
+ sprintf locfmt file line char (char+5) "Pattern matching failed"
+ | Assert_failure(file, line, char) ->
+ sprintf locfmt file line char (char+6) "Assertion failed"
+ | Undefined_recursive_module(file, line, char) ->
+ sprintf locfmt file line char (char+6) "Undefined recursive module"
+ | _ ->
+ let x = Obj.repr x in
+ if Obj.tag x <> 0 then
+ (Obj.magic (Obj.field x 0) : string)
+ else
+ let constructor =
+ (Obj.magic (Obj.field (Obj.field x 0) 0) : string) in
+ constructor ^ (fields x) in
+ conv !printers
+
+let print fct arg =
+ try
+ fct arg
+ with x ->
+ eprintf "Uncaught exception: %s\n" (to_string x);
+ flush stderr;
+ raise x
+
+let catch fct arg =
+ try
+ fct arg
+ with x ->
+ flush stdout;
+ eprintf "Uncaught exception: %s\n" (to_string x);
+ exit 2
+
+type raw_backtrace_slot
+type raw_backtrace = raw_backtrace_slot array
+
+external get_raw_backtrace:
+ unit -> raw_backtrace = "caml_get_exception_raw_backtrace"
+
+type backtrace_slot =
+ | Known_location of bool (* is_raise *)
+ * string (* filename *)
+ * int (* line number *)
+ * int (* start char *)
+ * int (* end char *)
+ | Unknown_location of bool (*is_raise*)
+
+(* to avoid warning *)
+let _ = [Known_location (false, "", 0, 0, 0); Unknown_location false]
+
+external convert_raw_backtrace_slot:
+ raw_backtrace_slot -> backtrace_slot = "caml_convert_raw_backtrace_slot"
+
+let convert_raw_backtrace rbckt =
+ try Some (Array.map convert_raw_backtrace_slot rbckt)
+ with Failure _ -> None
+
+let format_backtrace_slot pos slot =
+ let info is_raise =
+ if is_raise then
+ if pos = 0 then "Raised at" else "Re-raised at"
+ else
+ if pos = 0 then "Raised by primitive operation at" else "Called from"
+ in
+ match slot with
+ | Unknown_location true -> (* compiler-inserted re-raise, skipped *) None
+ | Unknown_location false ->
+ Some (sprintf "%s unknown location" (info false))
+ | Known_location(is_raise, filename, lineno, startchar, endchar) ->
+ Some (sprintf "%s file \"%s\", line %d, characters %d-%d"
+ (info is_raise) filename lineno startchar endchar)
+
+let print_exception_backtrace outchan backtrace =
+ match backtrace with
+ | None ->
+ fprintf outchan
+ "(Program not linked with -g, cannot print stack backtrace)\n"
+ | Some a ->
+ for i = 0 to Array.length a - 1 do
+ match format_backtrace_slot i a.(i) with
+ | None -> ()
+ | Some str -> fprintf outchan "%s\n" str
+ done
+
+let print_raw_backtrace outchan raw_backtrace =
+ print_exception_backtrace outchan (convert_raw_backtrace raw_backtrace)
+
+(* confusingly named: prints the global current backtrace *)
+let print_backtrace outchan =
+ print_raw_backtrace outchan (get_raw_backtrace ())
+
+let backtrace_to_string backtrace =
+ match backtrace with
+ | None ->
+ "(Program not linked with -g, cannot print stack backtrace)\n"
+ | Some a ->
+ let b = Buffer.create 1024 in
+ for i = 0 to Array.length a - 1 do
+ match format_backtrace_slot i a.(i) with
+ | None -> ()
+ | Some str -> bprintf b "%s\n" str
+ done;
+ Buffer.contents b
+
+let raw_backtrace_to_string raw_backtrace =
+ backtrace_to_string (convert_raw_backtrace raw_backtrace)
+
+let backtrace_slot_is_raise = function
+ | Known_location(is_raise, _, _, _, _) -> is_raise
+ | Unknown_location(is_raise) -> is_raise
+
+type location = {
+ filename : string;
+ line_number : int;
+ start_char : int;
+ end_char : int;
+}
+
+let backtrace_slot_location = function
+ | Unknown_location _ -> None
+ | Known_location(_is_raise, filename, line_number,
+ start_char, end_char) ->
+ Some {
+ filename;
+ line_number;
+ start_char;
+ end_char;
+ }
+
+let backtrace_slots raw_backtrace =
+ (* The documentation of this function guarantees that Some is
+ returned only if a part of the trace is usable. This gives us
+ a bit more work than just convert_raw_backtrace, but it makes the
+ API more user-friendly -- otherwise most users would have to
+ reimplement the "Program not linked with -g, sorry" logic
+ themselves. *)
+ match convert_raw_backtrace raw_backtrace with
+ | None -> None
+ | Some backtrace ->
+ let usable_slot = function
+ | Unknown_location _ -> false
+ | Known_location _ -> true in
+ let rec exists_usable = function
+ | (-1) -> false
+ | i -> usable_slot backtrace.(i) || exists_usable (i - 1) in
+ if exists_usable (Array.length backtrace - 1)
+ then Some backtrace
+ else None
+
+module Slot = struct
+ type t = backtrace_slot
+ let format = format_backtrace_slot
+ let is_raise = backtrace_slot_is_raise
+ let location = backtrace_slot_location
+end
+
+let raw_backtrace_length bckt = Array.length bckt
+let get_raw_backtrace_slot bckt i = Array.get bckt i
+
+(* confusingly named:
+ returns the *string* corresponding to the global current backtrace *)
+let get_backtrace () =
+ backtrace_to_string (convert_raw_backtrace (get_raw_backtrace ()))
+
+external record_backtrace: bool -> unit = "caml_record_backtrace"
+external backtrace_status: unit -> bool = "caml_backtrace_status"
+
+let register_printer fn =
+ printers := fn :: !printers
+
+external get_callstack: int -> raw_backtrace = "caml_get_current_callstack"
+
+let exn_slot x =
+ let x = Obj.repr x in
+ if Obj.tag x = 0 then Obj.field x 0 else x
+
+let exn_slot_id x =
+ let slot = exn_slot x in
+ (Obj.obj (Obj.field slot 1) : int)
+
+let exn_slot_name x =
+ let slot = exn_slot x in
+ (Obj.obj (Obj.field slot 0) : string)
+
+
+let uncaught_exception_handler = ref None
+
+let set_uncaught_exception_handler fn = uncaught_exception_handler := Some fn
+
+let empty_backtrace : raw_backtrace = Obj.obj (Obj.new_block Obj.abstract_tag 0)
+
+let try_get_raw_backtrace () =
+ try
+ get_raw_backtrace ()
+ with _ (* Out_of_memory? *) ->
+ empty_backtrace
+
+let handle_uncaught_exception' exn debugger_in_use =
+ try
+ (* Get the backtrace now, in case one of the [at_exit] function
+ destroys it. *)
+ let raw_backtrace =
+ if debugger_in_use (* Same test as in [byterun/printexc.c] *) then
+ empty_backtrace
+ else
+ try_get_raw_backtrace ()
+ in
+ (try Pervasives.do_at_exit () with _ -> ());
+ match !uncaught_exception_handler with
+ | None ->
+ eprintf "Fatal error: exception %s\n" (to_string exn);
+ print_raw_backtrace stderr raw_backtrace;
+ flush stderr
+ | Some handler ->
+ try
+ handler exn raw_backtrace
+ with exn' ->
+ let raw_backtrace' = try_get_raw_backtrace () in
+ eprintf "Fatal error: exception %s\n" (to_string exn);
+ print_raw_backtrace stderr raw_backtrace;
+ eprintf "Fatal error in uncaught exception handler: exception %s\n"
+ (to_string exn');
+ print_raw_backtrace stderr raw_backtrace';
+ flush stderr
+ with
+ | Out_of_memory ->
+ prerr_endline
+ "Fatal error: out of memory in uncaught exception handler"
+
+(* This function is called by [caml_fatal_uncaught_exception] in
+ [byterun/printexc.c] which expects no exception is raised. *)
+let handle_uncaught_exception exn debugger_in_use =
+ try
+ handle_uncaught_exception' exn debugger_in_use
+ with _ ->
+ (* There is not much we can do at this point *)
+ ()
+
+external register_named_value : string -> 'a -> unit
+ = "caml_register_named_value"
+
+let () =
+ register_named_value "Printexc.handle_uncaught_exception"
+ handle_uncaught_exception
diff --git a/stdlib/printexc.mli b/stdlib/printexc.mli
new file mode 100644
index 0000000000..c347b9915b
--- /dev/null
+++ b/stdlib/printexc.mli
@@ -0,0 +1,293 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Facilities for printing exceptions and inspecting current call stack. *)
+
+val to_string: exn -> string
+(** [Printexc.to_string e] returns a string representation of
+ the exception [e]. *)
+
+val print: ('a -> 'b) -> 'a -> 'b
+(** [Printexc.print fn x] applies [fn] to [x] and returns the result.
+ If the evaluation of [fn x] raises any exception, the
+ name of the exception is printed on standard error output,
+ and the exception is raised again.
+ The typical use is to catch and report exceptions that
+ escape a function application. *)
+
+val catch: ('a -> 'b) -> 'a -> 'b
+(** [Printexc.catch fn x] is similar to {!Printexc.print}, but
+ aborts the program with exit code 2 after printing the
+ uncaught exception. This function is deprecated: the runtime
+ system is now able to print uncaught exceptions as precisely
+ as [Printexc.catch] does. Moreover, calling [Printexc.catch]
+ makes it harder to track the location of the exception
+ using the debugger or the stack backtrace facility.
+ So, do not use [Printexc.catch] in new code. *)
+
+val print_backtrace: out_channel -> unit
+(** [Printexc.print_backtrace oc] prints an exception backtrace
+ on the output channel [oc]. The backtrace lists the program
+ locations where the most-recently raised exception was raised
+ and where it was propagated through function calls.
+ @since 3.11.0
+*)
+
+val get_backtrace: unit -> string
+(** [Printexc.get_backtrace ()] returns a string containing the
+ same exception backtrace that [Printexc.print_backtrace] would
+ print.
+ @since 3.11.0
+*)
+
+val record_backtrace: bool -> unit
+(** [Printexc.record_backtrace b] turns recording of exception backtraces
+ on (if [b = true]) or off (if [b = false]). Initially, backtraces
+ are not recorded, unless the [b] flag is given to the program
+ through the [OCAMLRUNPARAM] variable.
+ @since 3.11.0
+*)
+
+val backtrace_status: unit -> bool
+(** [Printexc.backtrace_status()] returns [true] if exception
+ backtraces are currently recorded, [false] if not.
+ @since 3.11.0
+*)
+
+val register_printer: (exn -> string option) -> unit
+(** [Printexc.register_printer fn] registers [fn] as an exception
+ printer. The printer should return [None] or raise an exception
+ if it does not know how to convert the passed exception, and [Some
+ s] with [s] the resulting string if it can convert the passed
+ exception. Exceptions raised by the printer are ignored.
+
+ When converting an exception into a string, the printers will be invoked
+ in the reverse order of their registrations, until a printer returns
+ a [Some s] value (if no such printer exists, the runtime will use a
+ generic printer).
+
+ When using this mechanism, one should be aware that an exception backtrace
+ is attached to the thread that saw it raised, rather than to the exception
+ itself. Practically, it means that the code related to [fn] should not use
+ the backtrace if it has itself raised an exception before.
+ @since 3.11.2
+*)
+
+(** {6 Raw backtraces} *)
+
+type raw_backtrace
+(** The abstract type [raw_backtrace] stores a backtrace in
+ a low-level format, instead of directly exposing them as string as
+ the [get_backtrace()] function does.
+
+ This allows delaying the formatting of backtraces to when they are
+ actually printed, which may be useful if you record more
+ backtraces than you print.
+
+ Raw backtraces cannot be marshalled. If you need marshalling, you
+ should use the array returned by the [backtrace_slots] function of
+ the next section.
+
+ @since 4.01.0
+*)
+
+val get_raw_backtrace: unit -> raw_backtrace
+(** [Printexc.get_raw_backtrace ()] returns the same exception
+ backtrace that [Printexc.print_backtrace] would print, but in
+ a raw format.
+
+ @since 4.01.0
+*)
+
+val print_raw_backtrace: out_channel -> raw_backtrace -> unit
+(** Print a raw backtrace in the same format
+ [Printexc.print_backtrace] uses.
+
+ @since 4.01.0
+*)
+
+val raw_backtrace_to_string: raw_backtrace -> string
+(** Return a string from a raw backtrace, in the same format
+ [Printexc.get_backtrace] uses.
+
+ @since 4.01.0
+*)
+
+(** {6 Current call stack} *)
+
+val get_callstack: int -> raw_backtrace
+(** [Printexc.get_callstack n] returns a description of the top of the
+ call stack on the current program point (for the current thread),
+ with at most [n] entries. (Note: this function is not related to
+ exceptions at all, despite being part of the [Printexc] module.)
+
+ @since 4.01.0
+*)
+
+(** {6 Uncaught exceptions} *)
+
+val set_uncaught_exception_handler: (exn -> raw_backtrace -> unit) -> unit
+(** [Printexc.set_uncaught_exception_handler fn] registers [fn] as the handler
+ for uncaught exceptions. The default handler prints the exception and
+ backtrace on standard error output.
+
+ Note that when [fn] is called all the functions registered with
+ {!Pervasives.at_exit} have already been called. Because of this you must
+ make sure any output channel [fn] writes on is flushed.
+
+ Also note that exceptions raised by user code in the interactive toplevel
+ are not passed to this function as they are caught by the toplevel itself.
+
+ If [fn] raises an exception, both the exceptions passed to [fn] and raised
+ by [fn] will be printed with their respective backtrace.
+
+ @since 4.02.0
+*)
+
+
+(** {6 Manipulation of backtrace information}
+
+ Those function allow to traverse the slots of a raw backtrace,
+ extract information from them in a programmer-friendly format.
+*)
+
+type backtrace_slot
+(** The abstract type [backtrace_slot] represents a single slot of
+ a backtrace.
+
+ @since 4.02
+*)
+
+val backtrace_slots : raw_backtrace -> backtrace_slot array option
+(** Returns the slots of a raw backtrace, or [None] if none of them
+ contain useful information.
+
+ In the return array, the slot at index [0] corresponds to the most
+ recent function call, raise, or primitive [get_backtrace] call in
+ the trace.
+
+ Some possible reasons for returning [None] are as follow:
+ - none of the slots in the trace come from modules compiled with
+ debug information ([-g])
+ - the program is a bytecode program that has not been linked with
+ debug information enabled ([ocamlc -g])
+
+ @since 4.02.0
+*)
+
+type location = {
+ filename : string;
+ line_number : int;
+ start_char : int;
+ end_char : int;
+}
+(** The type of location information found in backtraces. [start_char]
+ and [end_char] are positions relative to the beginning of the
+ line.
+
+ @since 4.02
+*)
+
+module Slot : sig
+ type t = backtrace_slot
+
+ val is_raise : t -> bool
+ (** [is_raise slot] is [true] when [slot] refers to a raising
+ point in the code, and [false] when it comes from a simple
+ function call.
+
+ @since 4.02
+ *)
+
+ val location : t -> location option
+ (** [location slot] returns the location information of the slot,
+ if available, and [None] otherwise.
+
+ Some possible reasons for failing to return a location are as follow:
+ - the slot corresponds to a compiler-inserted raise
+ - the slot corresponds to a part of the program that has not been
+ compiled with debug information ([-g])
+
+ @since 4.02
+ *)
+
+ val format : int -> t -> string option
+ (** [format pos slot] returns the string representation of [slot] as
+ [raw_backtrace_to_string] would format it, assuming it is the
+ [pos]-th element of the backtrace: the [0]-th element is
+ pretty-printed differently than the others.
+
+ Whole-backtrace printing functions also skip some uninformative
+ slots; in that case, [format pos slot] returns [None].
+
+ @since 4.02
+ *)
+end
+
+
+(** {6 Raw backtrace slots} *)
+
+type raw_backtrace_slot
+(** This type allows direct access to raw backtrace slots, without any
+ conversion in an OCaml-usable data-structure. Being
+ process-specific, they must absolutely not be marshalled, and are
+ unsafe to use for this reason (marshalling them may not fail, but
+ un-marshalling and using the result will result in
+ undefined behavior).
+
+ Elements of this type can still be compared and hashed: when two
+ elements are equal, then they represent the same source location
+ (the converse is not necessarily true in presence of inlining,
+ for example).
+
+ @since 4.02.0
+*)
+
+val raw_backtrace_length : raw_backtrace -> int
+(** [raw_backtrace_length bckt] returns the number of slots in the
+ backtrace [bckt].
+
+ @since 4.02
+*)
+
+val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot
+(** [get_slot bckt pos] returns the slot in position [pos] in the
+ backtrace [bckt].
+
+ @since 4.02
+*)
+
+val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot
+(** Extracts the user-friendly [backtrace_slot] from a low-level
+ [raw_backtrace_slot].
+
+ @since 4.02
+*)
+
+
+(** {6 Exception slots} *)
+
+val exn_slot_id: exn -> int
+(** [Printexc.exn_slot_id] returns an integer which uniquely identifies
+ the constructor used to create the exception value [exn]
+ (in the current runtime).
+
+ @since 4.02.0
+*)
+
+val exn_slot_name: exn -> string
+(** [Printexc.exn_slot_id exn] returns the internal name of the constructor
+ used to create the exception value [exn].
+
+ @since 4.02.0
+*)
diff --git a/stdlib/printf.ml b/stdlib/printf.ml
new file mode 100644
index 0000000000..1152429f9a
--- /dev/null
+++ b/stdlib/printf.ml
@@ -0,0 +1,39 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open CamlinternalFormatBasics
+open CamlinternalFormat
+
+let kfprintf k o (Format (fmt, _)) =
+ make_printf (fun o acc -> output_acc o acc; k o) o End_of_acc fmt
+let kbprintf k b (Format (fmt, _)) =
+ make_printf (fun b acc -> bufput_acc b acc; k b) b End_of_acc fmt
+let ikfprintf k oc (Format (fmt, _)) =
+ make_printf (fun oc _ -> k oc) oc End_of_acc fmt
+
+let fprintf oc fmt = kfprintf ignore oc fmt
+let bprintf b fmt = kbprintf ignore b fmt
+let ifprintf oc fmt = ikfprintf ignore oc fmt
+let printf fmt = fprintf stdout fmt
+let eprintf fmt = fprintf stderr fmt
+
+let ksprintf k (Format (fmt, _)) =
+ let k' () acc =
+ let buf = Buffer.create 64 in
+ strput_acc buf acc;
+ k (Buffer.contents buf) in
+ make_printf k' () End_of_acc fmt
+
+let sprintf fmt = ksprintf (fun s -> s) fmt
+
+let kprintf = ksprintf
diff --git a/stdlib/printf.mli b/stdlib/printf.mli
new file mode 100644
index 0000000000..db3f0a9bd4
--- /dev/null
+++ b/stdlib/printf.mli
@@ -0,0 +1,167 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Formatted output functions. *)
+
+val fprintf : out_channel -> ('a, out_channel, unit) format -> 'a
+(** [fprintf outchan format arg1 ... argN] formats the arguments
+ [arg1] to [argN] according to the format string [format], and
+ outputs the resulting string on the channel [outchan].
+
+ The format string is a character string which contains two types of
+ objects: plain characters, which are simply copied to the output
+ channel, and conversion specifications, each of which causes
+ conversion and printing of arguments.
+
+ Conversion specifications have the following form:
+
+ [% [flags] [width] [.precision] type]
+
+ In short, a conversion specification consists in the [%] character,
+ followed by optional modifiers and a type which is made of one or
+ two characters.
+
+ The types and their meanings are:
+
+ - [d], [i]: convert an integer argument to signed decimal.
+ - [u], [n], [l], [L], or [N]: convert an integer argument to
+ unsigned decimal. Warning: [n], [l], [L], and [N] are
+ used for [scanf], and should not be used for [printf].
+ - [x]: convert an integer argument to unsigned hexadecimal,
+ using lowercase letters.
+ - [X]: convert an integer argument to unsigned hexadecimal,
+ using uppercase letters.
+ - [o]: convert an integer argument to unsigned octal.
+ - [s]: insert a string argument.
+ - [S]: convert a string argument to OCaml syntax (double quotes, escapes).
+ - [c]: insert a character argument.
+ - [C]: convert a character argument to OCaml syntax
+ (single quotes, escapes).
+ - [f]: convert a floating-point argument to decimal notation,
+ in the style [dddd.ddd].
+ - [F]: convert a floating-point argument to OCaml syntax ([dddd.]
+ or [dddd.ddd] or [d.ddd e+-dd]).
+ - [e] or [E]: convert a floating-point argument to decimal notation,
+ in the style [d.ddd e+-dd] (mantissa and exponent).
+ - [g] or [G]: convert a floating-point argument to decimal notation,
+ in style [f] or [e], [E] (whichever is more compact).
+ - [B]: convert a boolean argument to the string [true] or [false]
+ - [b]: convert a boolean argument (deprecated; do not use in new
+ programs).
+ - [ld], [li], [lu], [lx], [lX], [lo]: convert an [int32] argument to
+ the format specified by the second letter (decimal, hexadecimal, etc).
+ - [nd], [ni], [nu], [nx], [nX], [no]: convert a [nativeint] argument to
+ the format specified by the second letter.
+ - [Ld], [Li], [Lu], [Lx], [LX], [Lo]: convert an [int64] argument to
+ the format specified by the second letter.
+ - [a]: user-defined printer. Take two arguments and apply the
+ first one to [outchan] (the current output channel) and to the
+ second argument. The first argument must therefore have type
+ [out_channel -> 'b -> unit] and the second ['b].
+ The output produced by the function is inserted in the output of
+ [fprintf] at the current point.
+ - [t]: same as [%a], but take only one argument (with type
+ [out_channel -> unit]) and apply it to [outchan].
+ - [\{ fmt %\}]: convert a format string argument to its type digest.
+ The argument must have the same type as the internal format string
+ [fmt].
+ - [( fmt %)]: format string substitution. Take a format string
+ argument and substitute it to the internal format string [fmt]
+ to print following arguments. The argument must have the same
+ type as the internal format string [fmt].
+ - [!]: take no argument and flush the output.
+ - [%]: take no argument and output one [%] character.
+ - [\@]: take no argument and output one [\@] character.
+ - [,]: take no argument and output nothing: a no-op delimiter for
+ conversion specifications.
+
+ The optional [flags] are:
+ - [-]: left-justify the output (default is right justification).
+ - [0]: for numerical conversions, pad with zeroes instead of spaces.
+ - [+]: for signed numerical conversions, prefix number with a [+]
+ sign if positive.
+ - space: for signed numerical conversions, prefix number with a
+ space if positive.
+ - [#]: request an alternate formatting style for the hexadecimal
+ and octal integer types ([x], [X], [o], [lx], [lX], [lo], [Lx],
+ [LX], [Lo]).
+
+ The optional [width] is an integer indicating the minimal
+ width of the result. For instance, [%6d] prints an integer,
+ prefixing it with spaces to fill at least 6 characters.
+
+ The optional [precision] is a dot [.] followed by an integer
+ indicating how many digits follow the decimal point in the [%f],
+ [%e], and [%E] conversions. For instance, [%.4f] prints a [float] with
+ 4 fractional digits.
+
+ The integer in a [width] or [precision] can also be specified as
+ [*], in which case an extra integer argument is taken to specify
+ the corresponding [width] or [precision]. This integer argument
+ precedes immediately the argument to print.
+ For instance, [%.*f] prints a [float] with as many fractional
+ digits as the value of the argument given before the float. *)
+
+val printf : ('a, out_channel, unit) format -> 'a
+(** Same as {!Printf.fprintf}, but output on [stdout]. *)
+
+val eprintf : ('a, out_channel, unit) format -> 'a
+(** Same as {!Printf.fprintf}, but output on [stderr]. *)
+
+val sprintf : ('a, unit, string) format -> 'a
+(** Same as {!Printf.fprintf}, but instead of printing on an output channel,
+ return a string containing the result of formatting the arguments. *)
+
+val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a
+(** Same as {!Printf.fprintf}, but instead of printing on an output channel,
+ append the formatted arguments to the given extensible buffer
+ (see module {!Buffer}). *)
+
+val ifprintf : 'b -> ('a, 'b, 'c, unit) format4 -> 'a
+(** Same as {!Printf.fprintf}, but does not print anything.
+ Useful to ignore some material when conditionally printing.
+ @since 3.10.0
+*)
+
+(** Formatted output functions with continuations. *)
+
+val kfprintf : (out_channel -> 'd) -> out_channel ->
+ ('a, out_channel, unit, 'd) format4 -> 'a
+(** Same as [fprintf], but instead of returning immediately,
+ passes the out channel to its first argument at the end of printing.
+ @since 3.09.0
+*)
+
+val ikfprintf : ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a
+(** Same as [kfprintf] above, but does not print anything.
+ Useful to ignore some material when conditionally printing.
+ @since 4.0
+*)
+
+val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a
+(** Same as [sprintf] above, but instead of returning the string,
+ passes it to the first argument.
+ @since 3.09.0
+*)
+
+val kbprintf : (Buffer.t -> 'd) -> Buffer.t ->
+ ('a, Buffer.t, unit, 'd) format4 -> 'a
+(** Same as [bprintf], but instead of returning immediately,
+ passes the buffer to its first argument at the end of printing.
+ @since 3.10.0
+*)
+
+(** Deprecated *)
+
+val kprintf : (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a
+(** A deprecated synonym for [ksprintf]. *)
diff --git a/stdlib/queue.ml b/stdlib/queue.ml
new file mode 100644
index 0000000000..fb920d8c9c
--- /dev/null
+++ b/stdlib/queue.ml
@@ -0,0 +1,165 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Francois Pottier, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+exception Empty
+
+(* OCaml currently does not allow the components of a sum type to be
+ mutable. Yet, for optimal space efficiency, we must have cons cells
+ whose [next] field is mutable. This leads us to define a type of
+ cyclic lists, so as to eliminate the [Nil] case and the sum
+ type. *)
+
+type 'a cell = {
+ content: 'a;
+ mutable next: 'a cell
+ }
+
+(* A queue is a reference to either nothing or some cell of a cyclic
+ list. By convention, that cell is to be viewed as the last cell in
+ the queue. The first cell in the queue is then found in constant
+ time: it is the next cell in the cyclic list. The queue's length is
+ also recorded, so as to make [length] a constant-time operation.
+
+ The [tail] field should really be of type ['a cell option], but
+ then it would be [None] when [length] is 0 and [Some] otherwise,
+ leading to redundant memory allocation and accesses. We avoid this
+ overhead by filling [tail] with a dummy value when [length] is 0.
+ Of course, this requires bending the type system's arm slightly,
+ because it does not have dependent sums. *)
+
+type 'a t = {
+ mutable length: int;
+ mutable tail: 'a cell
+ }
+
+let create () = {
+ length = 0;
+ tail = Obj.magic None
+}
+
+let clear q =
+ q.length <- 0;
+ q.tail <- Obj.magic None
+
+let add x q =
+ if q.length = 0 then
+ let rec cell = {
+ content = x;
+ next = cell
+ } in
+ q.length <- 1;
+ q.tail <- cell
+ else
+ let tail = q.tail in
+ let head = tail.next in
+ let cell = {
+ content = x;
+ next = head
+ } in
+ q.length <- q.length + 1;
+ tail.next <- cell;
+ q.tail <- cell
+
+let push =
+ add
+
+let peek q =
+ if q.length = 0 then
+ raise Empty
+ else
+ q.tail.next.content
+
+let top =
+ peek
+
+let take q =
+ if q.length = 0 then raise Empty;
+ q.length <- q.length - 1;
+ let tail = q.tail in
+ let head = tail.next in
+ if head == tail then
+ q.tail <- Obj.magic None
+ else
+ tail.next <- head.next;
+ head.content
+
+let pop =
+ take
+
+let copy q =
+ if q.length = 0 then
+ create()
+ else
+ let tail = q.tail in
+
+ let rec tail' = {
+ content = tail.content;
+ next = tail'
+ } in
+
+ let rec copy prev cell =
+ if cell != tail
+ then let res = {
+ content = cell.content;
+ next = tail'
+ } in prev.next <- res;
+ copy res cell.next in
+
+ copy tail' tail.next;
+ {
+ length = q.length;
+ tail = tail'
+ }
+
+let is_empty q =
+ q.length = 0
+
+let length q =
+ q.length
+
+let iter f q =
+ if q.length > 0 then
+ let tail = q.tail in
+ let rec iter cell =
+ f cell.content;
+ if cell != tail then
+ iter cell.next in
+ iter tail.next
+
+let fold f accu q =
+ if q.length = 0 then
+ accu
+ else
+ let tail = q.tail in
+ let rec fold accu cell =
+ let accu = f accu cell.content in
+ if cell == tail then
+ accu
+ else
+ fold accu cell.next in
+ fold accu tail.next
+
+let transfer q1 q2 =
+ let length1 = q1.length in
+ if length1 > 0 then
+ let tail1 = q1.tail in
+ clear q1;
+ if q2.length > 0 then begin
+ let tail2 = q2.tail in
+ let head1 = tail1.next in
+ let head2 = tail2.next in
+ tail1.next <- head2;
+ tail2.next <- head1
+ end;
+ q2.length <- q2.length + length1;
+ q2.tail <- tail1
diff --git a/stdlib/queue.mli b/stdlib/queue.mli
new file mode 100644
index 0000000000..5cd1136e4c
--- /dev/null
+++ b/stdlib/queue.mli
@@ -0,0 +1,80 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** First-in first-out queues.
+
+ This module implements queues (FIFOs), with in-place modification.
+
+ {b Warning} This module is not thread-safe: each {!Queue.t} value
+ must be protected from concurrent access (e.g. with a [Mutex.t]).
+ Failure to do so can lead to a crash.
+*)
+
+type 'a t
+(** The type of queues containing elements of type ['a]. *)
+
+
+exception Empty
+(** Raised when {!Queue.take} or {!Queue.peek} is applied to an empty queue. *)
+
+
+val create : unit -> 'a t
+(** Return a new queue, initially empty. *)
+
+val add : 'a -> 'a t -> unit
+(** [add x q] adds the element [x] at the end of the queue [q]. *)
+
+val push : 'a -> 'a t -> unit
+(** [push] is a synonym for [add]. *)
+
+val take : 'a t -> 'a
+(** [take q] removes and returns the first element in queue [q],
+ or raises [Empty] if the queue is empty. *)
+
+val pop : 'a t -> 'a
+(** [pop] is a synonym for [take]. *)
+
+val peek : 'a t -> 'a
+(** [peek q] returns the first element in queue [q], without removing
+ it from the queue, or raises [Empty] if the queue is empty. *)
+
+val top : 'a t -> 'a
+(** [top] is a synonym for [peek]. *)
+
+val clear : 'a t -> unit
+(** Discard all elements from a queue. *)
+
+val copy : 'a t -> 'a t
+(** Return a copy of the given queue. *)
+
+val is_empty : 'a t -> bool
+(** Return [true] if the given queue is empty, [false] otherwise. *)
+
+val length : 'a t -> int
+(** Return the number of elements in a queue. *)
+
+val iter : ('a -> unit) -> 'a t -> unit
+(** [iter f q] applies [f] in turn to all elements of [q],
+ from the least recently entered to the most recently entered.
+ The queue itself is unchanged. *)
+
+val fold : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b
+(** [fold f accu q] is equivalent to [List.fold_left f accu l],
+ where [l] is the list of [q]'s elements. The queue remains
+ unchanged. *)
+
+val transfer : 'a t -> 'a t -> unit
+(** [transfer q1 q2] adds all of [q1]'s elements at the end of
+ the queue [q2], then clears [q1]. It is equivalent to the
+ sequence [iter (fun x -> add x q2) q1; clear q1], but runs
+ in constant time. *)
diff --git a/stdlib/random.ml b/stdlib/random.ml
new file mode 100644
index 0000000000..f7b6e3be13
--- /dev/null
+++ b/stdlib/random.ml
@@ -0,0 +1,275 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Pseudo-random number generator
+ This is a lagged-Fibonacci F(55, 24, +) with a modified addition
+ function to enhance the mixing of bits.
+ If we use normal addition, the low-order bit fails tests 1 and 7
+ of the Diehard test suite, and bits 1 and 2 also fail test 7.
+ If we use multiplication as suggested by Marsaglia, it doesn't fare
+ much better.
+ By mixing the bits of one of the numbers before addition (XOR the
+ 5 high-order bits into the low-order bits), we get a generator that
+ passes all the Diehard tests.
+*)
+
+external random_seed: unit -> int array = "caml_sys_random_seed";;
+
+module State = struct
+
+ type t = { st : int array; mutable idx : int };;
+
+ let new_state () = { st = Array.make 55 0; idx = 0 };;
+ let assign st1 st2 =
+ Array.blit st2.st 0 st1.st 0 55;
+ st1.idx <- st2.idx;
+ ;;
+
+ let full_init s seed =
+ let combine accu x = Digest.string (accu ^ string_of_int x) in
+ let extract d =
+ Char.code d.[0] + (Char.code d.[1] lsl 8) + (Char.code d.[2] lsl 16)
+ + (Char.code d.[3] lsl 24)
+ in
+ let seed = if Array.length seed = 0 then [| 0 |] else seed in
+ let l = Array.length seed in
+ for i = 0 to 54 do
+ s.st.(i) <- i;
+ done;
+ let accu = ref "x" in
+ for i = 0 to 54 + max 55 l do
+ let j = i mod 55 in
+ let k = i mod l in
+ accu := combine !accu seed.(k);
+ s.st.(j) <- (s.st.(j) lxor extract !accu) land 0x3FFFFFFF; (* PR#5575 *)
+ done;
+ s.idx <- 0;
+ ;;
+
+ let make seed =
+ let result = new_state () in
+ full_init result seed;
+ result
+ ;;
+
+ let make_self_init () = make (random_seed ());;
+
+ let copy s =
+ let result = new_state () in
+ assign result s;
+ result
+ ;;
+
+ (* Returns 30 random bits as an integer 0 <= x < 1073741824 *)
+ let bits s =
+ s.idx <- (s.idx + 1) mod 55;
+ let curval = s.st.(s.idx) in
+ let newval = s.st.((s.idx + 24) mod 55)
+ + (curval lxor ((curval lsr 25) land 0x1F)) in
+ let newval30 = newval land 0x3FFFFFFF in (* PR#5575 *)
+ s.st.(s.idx) <- newval30;
+ newval30
+ ;;
+
+ let rec intaux s n =
+ let r = bits s in
+ let v = r mod n in
+ if r - v > 0x3FFFFFFF - n + 1 then intaux s n else v
+ ;;
+ let int s bound =
+ if bound > 0x3FFFFFFF || bound <= 0
+ then invalid_arg "Random.int"
+ else intaux s bound
+ ;;
+
+ let rec int32aux s n =
+ let b1 = Int32.of_int (bits s) in
+ let b2 = Int32.shift_left (Int32.of_int (bits s land 1)) 30 in
+ let r = Int32.logor b1 b2 in
+ let v = Int32.rem r n in
+ if Int32.sub r v > Int32.add (Int32.sub Int32.max_int n) 1l
+ then int32aux s n
+ else v
+ ;;
+ let int32 s bound =
+ if bound <= 0l
+ then invalid_arg "Random.int32"
+ else int32aux s bound
+ ;;
+
+ let rec int64aux s n =
+ let b1 = Int64.of_int (bits s) in
+ let b2 = Int64.shift_left (Int64.of_int (bits s)) 30 in
+ let b3 = Int64.shift_left (Int64.of_int (bits s land 7)) 60 in
+ let r = Int64.logor b1 (Int64.logor b2 b3) in
+ let v = Int64.rem r n in
+ if Int64.sub r v > Int64.add (Int64.sub Int64.max_int n) 1L
+ then int64aux s n
+ else v
+ ;;
+ let int64 s bound =
+ if bound <= 0L
+ then invalid_arg "Random.int64"
+ else int64aux s bound
+ ;;
+
+ let nativeint =
+ if Nativeint.size = 32
+ then fun s bound -> Nativeint.of_int32 (int32 s (Nativeint.to_int32 bound))
+ else fun s bound -> Int64.to_nativeint (int64 s (Int64.of_nativeint bound))
+ ;;
+
+ (* Returns a float 0 <= x <= 1 with at most 60 bits of precision. *)
+ let rawfloat s =
+ let scale = 1073741824.0 (* 2^30 *)
+ and r1 = Pervasives.float (bits s)
+ and r2 = Pervasives.float (bits s)
+ in (r1 /. scale +. r2) /. scale
+ ;;
+
+ let float s bound = rawfloat s *. bound;;
+
+ let bool s = (bits s land 1 = 0);;
+
+end;;
+
+(* This is the state you get with [init 27182818] and then applying
+ the "land 0x3FFFFFFF" filter to them. See #5575, #5793, #5977. *)
+let default = {
+ State.st = [|
+ 0x3ae2522b; 0x1d8d4634; 0x15b4fad0; 0x18b14ace; 0x12f8a3c4; 0x3b086c47;
+ 0x16d467d6; 0x101d91c7; 0x321df177; 0x0176c193; 0x1ff72bf1; 0x1e889109;
+ 0x0b464b18; 0x2b86b97c; 0x0891da48; 0x03137463; 0x085ac5a1; 0x15d61f2f;
+ 0x3bced359; 0x29c1c132; 0x3a86766e; 0x366d8c86; 0x1f5b6222; 0x3ce1b59f;
+ 0x2ebf78e1; 0x27cd1b86; 0x258f3dc3; 0x389a8194; 0x02e4c44c; 0x18c43f7d;
+ 0x0f6e534f; 0x1e7df359; 0x055d0b7e; 0x10e84e7e; 0x126198e4; 0x0e7722cb;
+ 0x1cbede28; 0x3391b964; 0x3d40e92a; 0x0c59933d; 0x0b8cd0b7; 0x24efff1c;
+ 0x2803fdaa; 0x08ebc72e; 0x0f522e32; 0x05398edc; 0x2144a04c; 0x0aef3cbd;
+ 0x01ad4719; 0x35b93cd6; 0x2a559d4f; 0x1e6fd768; 0x26e27f36; 0x186f18c3;
+ 0x2fbf967a;
+ |];
+ State.idx = 0;
+};;
+
+let bits () = State.bits default;;
+let int bound = State.int default bound;;
+let int32 bound = State.int32 default bound;;
+let nativeint bound = State.nativeint default bound;;
+let int64 bound = State.int64 default bound;;
+let float scale = State.float default scale;;
+let bool () = State.bool default;;
+
+let full_init seed = State.full_init default seed;;
+let init seed = State.full_init default [| seed |];;
+let self_init () = full_init (random_seed());;
+
+(* Manipulating the current state. *)
+
+let get_state () = State.copy default;;
+let set_state s = State.assign default s;;
+
+(********************
+
+(* Test functions. Not included in the library.
+ The [chisquare] function should be called with n > 10r.
+ It returns a triple (low, actual, high).
+ If low <= actual <= high, the [g] function passed the test,
+ otherwise it failed.
+
+ Some results:
+
+init 27182818; chisquare int 100000 1000;;
+init 27182818; chisquare int 100000 100;;
+init 27182818; chisquare int 100000 5000;;
+init 27182818; chisquare int 1000000 1000;;
+init 27182818; chisquare int 100000 1024;;
+init 299792643; chisquare int 100000 1024;;
+init 14142136; chisquare int 100000 1024;;
+init 27182818; init_diff 1024; chisquare diff 100000 1024;;
+init 27182818; init_diff 100; chisquare diff 100000 100;;
+init 27182818; init_diff2 1024; chisquare diff2 100000 1024;;
+init 27182818; init_diff2 100; chisquare diff2 100000 100;;
+init 14142136; init_diff2 100; chisquare diff2 100000 100;;
+init 299792643; init_diff2 100; chisquare diff2 100000 100;;
+- : float * float * float = (936.754446796632465, 997.5, 1063.24555320336754)
+# - : float * float * float = (80., 89.7400000000052387, 120.)
+# - : float * float * float = (4858.57864376269, 5045.5, 5141.42135623731)
+# - : float * float * float =
+(936.754446796632465, 944.805999999982305, 1063.24555320336754)
+# - : float * float * float = (960., 1019.19744000000355, 1088.)
+# - : float * float * float = (960., 1059.31776000000536, 1088.)
+# - : float * float * float = (960., 1039.98463999999512, 1088.)
+# - : float * float * float = (960., 1054.38207999999577, 1088.)
+# - : float * float * float = (80., 90.096000000005, 120.)
+# - : float * float * float = (960., 1076.78720000000612, 1088.)
+# - : float * float * float = (80., 85.1760000000067521, 120.)
+# - : float * float * float = (80., 85.2160000000003492, 120.)
+# - : float * float * float = (80., 80.6220000000030268, 120.)
+
+*)
+
+(* Return the sum of the squares of v[i0,i1[ *)
+let rec sumsq v i0 i1 =
+ if i0 >= i1 then 0.0
+ else if i1 = i0 + 1 then Pervasives.float v.(i0) *. Pervasives.float v.(i0)
+ else sumsq v i0 ((i0+i1)/2) +. sumsq v ((i0+i1)/2) i1
+;;
+
+let chisquare g n r =
+ if n <= 10 * r then invalid_arg "chisquare";
+ let f = Array.make r 0 in
+ for i = 1 to n do
+ let t = g r in
+ f.(t) <- f.(t) + 1
+ done;
+ let t = sumsq f 0 r
+ and r = Pervasives.float r
+ and n = Pervasives.float n in
+ let sr = 2.0 *. sqrt r in
+ (r -. sr, (r *. t /. n) -. n, r +. sr)
+;;
+
+(* This is to test for linear dependencies between successive random numbers.
+*)
+let st = ref 0;;
+let init_diff r = st := int r;;
+let diff r =
+ let x1 = !st
+ and x2 = int r
+ in
+ st := x2;
+ if x1 >= x2 then
+ x1 - x2
+ else
+ r + x1 - x2
+;;
+
+let st1 = ref 0
+and st2 = ref 0
+;;
+
+(* This is to test for quadratic dependencies between successive random
+ numbers.
+*)
+let init_diff2 r = st1 := int r; st2 := int r;;
+let diff2 r =
+ let x1 = !st1
+ and x2 = !st2
+ and x3 = int r
+ in
+ st1 := x2;
+ st2 := x3;
+ (x3 - x2 - x2 + x1 + 2*r) mod r
+;;
+
+********************)
diff --git a/stdlib/random.mli b/stdlib/random.mli
new file mode 100644
index 0000000000..90f396f06b
--- /dev/null
+++ b/stdlib/random.mli
@@ -0,0 +1,105 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Pseudo-random number generators (PRNG). *)
+
+(** {6 Basic functions} *)
+
+val init : int -> unit
+(** Initialize the generator, using the argument as a seed.
+ The same seed will always yield the same sequence of numbers. *)
+
+val full_init : int array -> unit
+(** Same as {!Random.init} but takes more data as seed. *)
+
+val self_init : unit -> unit
+(** Initialize the generator with a random seed chosen
+ in a system-dependent way. If [/dev/urandom] is available on
+ the host machine, it is used to provide a highly random initial
+ seed. Otherwise, a less random seed is computed from system
+ parameters (current time, process IDs). *)
+
+val bits : unit -> int
+(** Return 30 random bits in a nonnegative integer.
+ @before 3.12.0 used a different algorithm (affects all the following
+ functions)
+*)
+
+val int : int -> int
+(** [Random.int bound] returns a random integer between 0 (inclusive)
+ and [bound] (exclusive). [bound] must be greater than 0 and less
+ than 2{^30}. *)
+
+val int32 : Int32.t -> Int32.t;;
+(** [Random.int32 bound] returns a random integer between 0 (inclusive)
+ and [bound] (exclusive). [bound] must be greater than 0. *)
+
+val nativeint : Nativeint.t -> Nativeint.t;;
+(** [Random.nativeint bound] returns a random integer between 0 (inclusive)
+ and [bound] (exclusive). [bound] must be greater than 0. *)
+
+val int64 : Int64.t -> Int64.t;;
+(** [Random.int64 bound] returns a random integer between 0 (inclusive)
+ and [bound] (exclusive). [bound] must be greater than 0. *)
+
+val float : float -> float
+(** [Random.float bound] returns a random floating-point number
+ between 0 and [bound] (inclusive). If [bound] is
+ negative, the result is negative or zero. If [bound] is 0,
+ the result is 0. *)
+
+val bool : unit -> bool
+(** [Random.bool ()] returns [true] or [false] with probability 0.5 each. *)
+
+
+(** {6 Advanced functions} *)
+
+(** The functions from module [State] manipulate the current state
+ of the random generator explicitly.
+ This allows using one or several deterministic PRNGs,
+ even in a multi-threaded program, without interference from
+ other parts of the program.
+*)
+
+module State : sig
+ type t
+ (** The type of PRNG states. *)
+
+ val make : int array -> t
+ (** Create a new state and initialize it with the given seed. *)
+
+ val make_self_init : unit -> t
+ (** Create a new state and initialize it with a system-dependent
+ low-entropy seed. *)
+
+ val copy : t -> t
+ (** Return a copy of the given state. *)
+
+ val bits : t -> int
+ val int : t -> int -> int
+ val int32 : t -> Int32.t -> Int32.t
+ val nativeint : t -> Nativeint.t -> Nativeint.t
+ val int64 : t -> Int64.t -> Int64.t
+ val float : t -> float -> float
+ val bool : t -> bool
+ (** These functions are the same as the basic functions, except that they
+ use (and update) the given PRNG state instead of the default one.
+ *)
+end;;
+
+
+val get_state : unit -> State.t
+(** Return the current state of the generator used by the basic functions. *)
+
+val set_state : State.t -> unit
+(** Set the state of the generator used by the basic functions. *)
diff --git a/stdlib/scanf.ml b/stdlib/scanf.ml
new file mode 100644
index 0000000000..e606a67465
--- /dev/null
+++ b/stdlib/scanf.ml
@@ -0,0 +1,1425 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+open CamlinternalFormatBasics
+open CamlinternalFormat
+
+(* alias to avoid warning for ambiguity between
+ Pervasives.format6
+ and CamlinternalFormatBasics.format6
+
+ (the former is in fact an alias for the latter,
+ but the ambiguity warning doesn't care)
+*)
+type ('a, 'b, 'c, 'd, 'e, 'f) format6 =
+ ('a, 'b, 'c, 'd, 'e, 'f) Pervasives.format6
+;;
+
+(* The run-time library for scanners. *)
+
+(* Scanning buffers. *)
+module type SCANNING = sig
+
+ type in_channel;;
+
+ type scanbuf = in_channel;;
+
+ type file_name = string;;
+
+ val stdin : in_channel;;
+ (* The scanning buffer reading from [Pervasives.stdin].
+ [stdib] is equivalent to [Scanning.from_channel Pervasives.stdin]. *)
+
+ val stdib : in_channel;;
+ (* An alias for [Scanf.stdin], the scanning buffer reading from
+ [Pervasives.stdin]. *)
+
+ val next_char : scanbuf -> char;;
+ (* [Scanning.next_char ib] advance the scanning buffer for
+ one character.
+ If no more character can be read, sets a end of file condition and
+ returns '\000'. *)
+
+ val invalidate_current_char : scanbuf -> unit;;
+ (* [Scanning.invalidate_current_char ib] mark the current_char as already
+ scanned. *)
+
+ val peek_char : scanbuf -> char;;
+ (* [Scanning.peek_char ib] returns the current char available in
+ the buffer or reads one if necessary (when the current character is
+ already scanned).
+ If no character can be read, sets an end of file condition and
+ returns '\000'. *)
+
+ val checked_peek_char : scanbuf -> char;;
+ (* Same as [Scanning.peek_char] above but always returns a valid char or
+ fails: instead of returning a null char when the reading method of the
+ input buffer has reached an end of file, the function raises exception
+ [End_of_file]. *)
+
+ val store_char : int -> scanbuf -> char -> int;;
+ (* [Scanning.store_char lim ib c] adds [c] to the token buffer
+ of the scanning buffer [ib]. It also advances the scanning buffer for
+ one character and returns [lim - 1], indicating the new limit for the
+ length of the current token. *)
+
+ val skip_char : int -> scanbuf -> int;;
+ (* [Scanning.skip_char lim ib] ignores the current character. *)
+
+ val ignore_char : int -> scanbuf -> int;;
+ (* [Scanning.ignore_char ib lim] ignores the current character and
+ decrements the limit. *)
+
+ val token : scanbuf -> string;;
+ (* [Scanning.token ib] returns the string stored into the token
+ buffer of the scanning buffer: it returns the token matched by the
+ format. *)
+
+ val reset_token : scanbuf -> unit;;
+ (* [Scanning.reset_token ib] resets the token buffer of
+ the given scanning buffer. *)
+
+ val char_count : scanbuf -> int;;
+ (* [Scanning.char_count ib] returns the number of characters
+ read so far from the given buffer. *)
+
+ val line_count : scanbuf -> int;;
+ (* [Scanning.line_count ib] returns the number of new line
+ characters read so far from the given buffer. *)
+
+ val token_count : scanbuf -> int;;
+ (* [Scanning.token_count ib] returns the number of tokens read
+ so far from [ib]. *)
+
+ val eof : scanbuf -> bool;;
+ (* [Scanning.eof ib] returns the end of input condition
+ of the given buffer. *)
+
+ val end_of_input : scanbuf -> bool;;
+ (* [Scanning.end_of_input ib] tests the end of input condition
+ of the given buffer (if no char has ever been read, an attempt to
+ read one is performed). *)
+
+ val beginning_of_input : scanbuf -> bool;;
+ (* [Scanning.beginning_of_input ib] tests the beginning of input
+ condition of the given buffer. *)
+
+ val name_of_input : scanbuf -> string;;
+ (* [Scanning.name_of_input ib] returns the name of the character
+ source for input buffer [ib]. *)
+
+ val open_in : file_name -> in_channel;;
+ val open_in_bin : file_name -> in_channel;;
+ val from_file : file_name -> in_channel;;
+ val from_file_bin : file_name -> in_channel;;
+ val from_string : string -> in_channel;;
+ val from_function : (unit -> char) -> in_channel;;
+ val from_channel : Pervasives.in_channel -> in_channel;;
+
+ val close_in : in_channel -> unit;;
+
+end
+;;
+
+module Scanning : SCANNING = struct
+
+ (* The run-time library for scanf. *)
+
+ type file_name = string;;
+
+ type in_channel_name =
+ | From_file of file_name * Pervasives.in_channel
+ | From_string
+ | From_function
+ | From_channel of Pervasives.in_channel
+ ;;
+
+ type in_channel = {
+ mutable eof : bool;
+ mutable current_char : char;
+ mutable current_char_is_valid : bool;
+ mutable char_count : int;
+ mutable line_count : int;
+ mutable token_count : int;
+ mutable get_next_char : unit -> char;
+ tokbuf : Buffer.t;
+ input_name : in_channel_name;
+ }
+ ;;
+
+ type scanbuf = in_channel;;
+
+ let null_char = '\000';;
+
+ (* Reads a new character from input buffer.
+ Next_char never fails, even in case of end of input:
+ it then simply sets the end of file condition. *)
+ let next_char ib =
+ try
+ let c = ib.get_next_char () in
+ ib.current_char <- c;
+ ib.current_char_is_valid <- true;
+ ib.char_count <- succ ib.char_count;
+ if c = '\n' then ib.line_count <- succ ib.line_count;
+ c with
+ | End_of_file ->
+ let c = null_char in
+ ib.current_char <- c;
+ ib.current_char_is_valid <- false;
+ ib.eof <- true;
+ c
+ ;;
+
+ let peek_char ib =
+ if ib.current_char_is_valid then ib.current_char else next_char ib
+ ;;
+
+ (* Returns a valid current char for the input buffer. In particular
+ no irrelevant null character (as set by [next_char] in case of end
+ of input) is returned, since [End_of_file] is raised when
+ [next_char] sets the end of file condition while trying to read a
+ new character. *)
+ let checked_peek_char ib =
+ let c = peek_char ib in
+ if ib.eof then raise End_of_file;
+ c
+ ;;
+
+ let end_of_input ib =
+ ignore (peek_char ib);
+ ib.eof
+ ;;
+
+ let eof ib = ib.eof;;
+
+ let beginning_of_input ib = ib.char_count = 0;;
+
+ let name_of_input ib =
+ match ib.input_name with
+ | From_file (fname, _ic) -> fname
+ | From_string -> "unnamed character string"
+ | From_function -> "unnamed function"
+ | From_channel _ic -> "unnamed pervasives input channel"
+ ;;
+
+ let char_count ib =
+ if ib.current_char_is_valid then ib.char_count - 1 else ib.char_count
+ ;;
+
+ let line_count ib = ib.line_count;;
+
+ let reset_token ib = Buffer.reset ib.tokbuf;;
+
+ let invalidate_current_char ib = ib.current_char_is_valid <- false;;
+
+ let token ib =
+ let tokbuf = ib.tokbuf in
+ let tok = Buffer.contents tokbuf in
+ Buffer.clear tokbuf;
+ ib.token_count <- succ ib.token_count;
+ tok
+ ;;
+
+ let token_count ib = ib.token_count;;
+
+ let skip_char width ib =
+ invalidate_current_char ib;
+ width
+ ;;
+
+ let ignore_char width ib = skip_char (width - 1) ib;;
+
+ let store_char width ib c =
+ Buffer.add_char ib.tokbuf c;
+ ignore_char width ib
+ ;;
+
+ let default_token_buffer_size = 1024;;
+
+ let create iname next = {
+ eof = false;
+ current_char = null_char;
+ current_char_is_valid = false;
+ char_count = 0;
+ line_count = 0;
+ token_count = 0;
+ get_next_char = next;
+ tokbuf = Buffer.create default_token_buffer_size;
+ input_name = iname;
+ }
+ ;;
+
+ let from_string s =
+ let i = ref 0 in
+ let len = String.length s in
+ let next () =
+ if !i >= len then raise End_of_file else
+ let c = s.[!i] in
+ incr i;
+ c in
+ create From_string next
+ ;;
+
+ let from_function = create From_function;;
+
+ (* Scanning from an input channel. *)
+
+ (* Position of the problem:
+
+ We cannot prevent the scanning mechanism to use one lookahead character,
+ if needed by the semantics of the format string specifications (e.g. a
+ trailing 'skip space' specification in the format string); in this case,
+ the mandatory lookahead character is indeed read from the input and not
+ used to return the token read. It is thus mandatory to be able to store
+ an unused lookahead character somewhere to get it as the first character
+ of the next scan.
+
+ To circumvent this problem, all the scanning functions get a low level
+ input buffer argument where they store the lookahead character when
+ needed; additionally, the input buffer is the only source of character of
+ a scanner. The [scanbuf] input buffers are defined in module {!Scanning}.
+
+ Now we understand that it is extremely important that related successive
+ calls to scanners indeed read from the same input buffer. In effect, if a
+ scanner [scan1] is reading from [ib1] and stores an unused lookahead
+ character [c1] into its input buffer [ib1], then another scanner [scan2]
+ not reading from the same buffer [ib1] will miss the character [c1],
+ seemingly vanished in the air from the point of view of [scan2].
+
+ This mechanism works perfectly to read from strings, from files, and from
+ functions, since in those cases, allocating two buffers reading from the
+ same source is unnatural.
+
+ Still, there is a difficulty in the case of scanning from an input
+ channel. In effect, when scanning from an input channel [ic], this channel
+ may not have been allocated from within this library. Hence, it may be
+ shared (two functions of the user's program may successively read from
+ [ic]). This is highly error prone since, one of the function may seek the
+ input channel, while the other function has still an unused lookahead
+ character in its input buffer. In conclusion, you should never mix direct
+ low level reading and high level scanning from the same input channel.
+
+ This phenomenon of reading mess is even worse when one defines more than
+ one scanning buffer reading from the same input channel [ic].
+ Unfortunately, we have no simple way to get rid of this problem
+ (unless the basic input channel API is modified to offer a 'consider this
+ char as unread' procedure to keep back the unused lookahead character as
+ available in the input channel for further reading).
+
+ To prevent some of the confusion the scanning buffer allocation function
+ is a memo function that never allocates two different scanning buffers for
+ the same input channel. This way, the user can naively perform successive
+ call to [fscanf] below, without allocating a new scanning buffer at each
+ invocation and hence preserving the expected semantics.
+
+ As mentioned above, a more ambitious fix could be to change the input
+ channel API to allow arbitrary mixing of direct and formatted reading from
+ input channels. *)
+
+ (* Perform bufferized input to improve efficiency. *)
+ let file_buffer_size = ref 1024;;
+
+ (* The scanner closes the input channel at end of input. *)
+ let scan_close_at_end ic = Pervasives.close_in ic; raise End_of_file;;
+
+ (* The scanner does not close the input channel at end of input:
+ it just raises [End_of_file]. *)
+ let scan_raise_at_end _ic = raise End_of_file;;
+
+ let from_ic scan_close_ic iname ic =
+ let len = !file_buffer_size in
+ let buf = Bytes.create len in
+ let i = ref 0 in
+ let lim = ref 0 in
+ let eof = ref false in
+ let next () =
+ if !i < !lim then begin let c = Bytes.get buf !i in incr i; c end else
+ if !eof then raise End_of_file else begin
+ lim := input ic buf 0 len;
+ if !lim = 0 then begin eof := true; scan_close_ic ic end else begin
+ i := 1;
+ Bytes.get buf 0
+ end
+ end in
+ create iname next
+ ;;
+
+ let from_ic_close_at_end = from_ic scan_close_at_end;;
+
+ (* The scanning buffer reading from [Pervasives.stdin].
+ One could try to define [stdib] as a scanning buffer reading a character
+ at a time (no bufferization at all), but unfortunately the top-level
+ interaction would be wrong. This is due to some kind of
+ 'race condition' when reading from [Pervasives.stdin],
+ since the interactive compiler and [scanf] will simultaneously read the
+ material they need from [Pervasives.stdin]; then, confusion will result
+ from what should be read by the top-level and what should be read
+ by [scanf].
+ This is even more complicated by the one character lookahead that [scanf]
+ is sometimes obliged to maintain: the lookahead character will be
+ available for the next ([scanf]) entry, seemingly coming from nowhere.
+ Also no [End_of_file] is raised when reading from stdin: if not enough
+ characters have been read, we simply ask to read more. *)
+ let stdin =
+ from_ic scan_raise_at_end
+ (From_file ("-", Pervasives.stdin)) Pervasives.stdin
+ ;;
+
+ let stdib = stdin;;
+
+ let open_in fname =
+ match fname with
+ | "-" -> stdin
+ | fname ->
+ let ic = Pervasives.open_in fname in
+ from_ic_close_at_end (From_file (fname, ic)) ic
+ ;;
+
+ let open_in_bin fname =
+ match fname with
+ | "-" -> stdin
+ | fname ->
+ let ic = Pervasives.open_in_bin fname in
+ from_ic_close_at_end (From_file (fname, ic)) ic
+ ;;
+
+ let from_file = open_in;;
+ let from_file_bin = open_in_bin;;
+
+ module IcIb :
+ Hashtbl.HashedType
+ with type t = Pervasives.in_channel * in_channel =
+ struct
+ type t = Pervasives.in_channel * in_channel;;
+ let equal (ic1, _ib1) (ic2, _ib2) = ic1 == ic2;;
+ let hash (ic, _ib) = Hashtbl.hash ic;;
+ end
+ ;;
+
+ module Memo = Weak.Make (IcIb);;
+
+ let memo_table = Memo.create 10;;
+
+ let memo_from_ic =
+ (fun scan_close_ic ic ->
+ try
+ let _, ib = Memo.find memo_table (ic, stdin) in
+ ib with
+ | Not_found ->
+ let ib = from_ic scan_close_ic (From_channel ic) ic in
+ Memo.add memo_table (ic, ib);
+ ib)
+ ;;
+
+ let from_channel = memo_from_ic scan_raise_at_end;;
+
+ let close_in ib =
+ match ib.input_name with
+ | From_file (_fname, ic) -> Pervasives.close_in ic
+ | From_string | From_function -> ()
+ | From_channel ic ->
+ Memo.remove memo_table (ic, ib);
+ Pervasives.close_in ic
+ ;;
+
+end
+;;
+
+(* Formatted input functions. *)
+
+type ('a, 'b, 'c, 'd) scanner =
+ ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c
+;;
+
+(* Reporting errors. *)
+exception Scan_failure of string;;
+
+let bad_input s = raise (Scan_failure s);;
+
+let bad_input_escape c =
+ bad_input (Printf.sprintf "illegal escape character %C" c)
+;;
+
+let bad_token_length message =
+ bad_input
+ (Printf.sprintf
+ "scanning of %s failed: \
+ the specified length was too short for token"
+ message)
+;;
+
+let bad_end_of_input message =
+ bad_input
+ (Printf.sprintf
+ "scanning of %s failed: \
+ premature end of file occurred before end of token"
+ message)
+;;
+
+let bad_float () =
+ bad_input "no dot or exponent part found in float token"
+;;
+
+let character_mismatch_err c ci =
+ Printf.sprintf "looking for %C, found %C" c ci
+;;
+
+let character_mismatch c ci =
+ bad_input (character_mismatch_err c ci)
+;;
+
+let rec skip_whites ib =
+ let c = Scanning.peek_char ib in
+ if not (Scanning.eof ib) then begin
+ match c with
+ | ' ' | '\t' | '\n' | '\r' ->
+ Scanning.invalidate_current_char ib; skip_whites ib
+ | _ -> ()
+ end
+;;
+
+(* Checking that [c] is indeed in the input, then skips it.
+ In this case, the character [c] has been explicitly specified in the
+ format as being mandatory in the input; hence we should fail with
+ End_of_file in case of end_of_input. (Remember that Scan_failure is raised
+ only when (we can prove by evidence) that the input does not match the
+ format string given. We must thus differentiate End_of_file as an error
+ due to lack of input, and Scan_failure which is due to provably wrong
+ input. I am not sure this is worth the burden: it is complex and somehow
+ subliminal; should be clearer to fail with Scan_failure "Not enough input
+ to complete scanning"!)
+
+ That's why, waiting for a better solution, we use checked_peek_char here.
+ We are also careful to treat "\r\n" in the input as an end of line marker:
+ it always matches a '\n' specification in the input format string. *)
+let rec check_char ib c =
+ match c with
+ | ' ' -> skip_whites ib
+ | '\n' -> check_newline ib
+ | c -> check_this_char ib c
+
+and check_this_char ib c =
+ let ci = Scanning.checked_peek_char ib in
+ if ci = c then Scanning.invalidate_current_char ib else
+ character_mismatch c ci
+
+and check_newline ib =
+ let ci = Scanning.checked_peek_char ib in
+ match ci with
+ | '\n' -> Scanning.invalidate_current_char ib
+ | '\r' -> Scanning.invalidate_current_char ib; check_this_char ib '\n'
+ | _ -> character_mismatch '\n' ci
+;;
+
+(* Extracting tokens from the output token buffer. *)
+
+let token_char ib = (Scanning.token ib).[0];;
+
+let token_string = Scanning.token;;
+
+let token_bool ib =
+ match Scanning.token ib with
+ | "true" -> true
+ | "false" -> false
+ | s -> bad_input (Printf.sprintf "invalid boolean '%s'" s)
+;;
+
+(* Extract an integer literal token.
+ Since the functions Pervasives.*int*_of_string do not accept a leading +,
+ we skip it if necessary. *)
+let token_int_literal conv ib =
+ let tok =
+ match conv with
+ | 'd' | 'i' -> Scanning.token ib
+ | 'u' -> "0u" ^ Scanning.token ib
+ | 'o' -> "0o" ^ Scanning.token ib
+ | 'x' | 'X' -> "0x" ^ Scanning.token ib
+ | 'b' -> "0b" ^ Scanning.token ib
+ | _ -> assert false in
+ let l = String.length tok in
+ if l = 0 || tok.[0] <> '+' then tok else String.sub tok 1 (l - 1)
+;;
+
+(* All the functions that convert a string to a number raise the exception
+ Failure when the conversion is not possible.
+ This exception is then trapped in [kscanf]. *)
+let token_int conv ib = int_of_string (token_int_literal conv ib);;
+
+let token_float ib = float_of_string (Scanning.token ib);;
+
+(* To scan native ints, int32 and int64 integers.
+ We cannot access to conversions to/from strings for those types,
+ Nativeint.of_string, Int32.of_string, and Int64.of_string,
+ since those modules are not available to [Scanf].
+ However, we can bind and use the corresponding primitives that are
+ available in the runtime. *)
+external nativeint_of_string : string -> nativeint
+ = "caml_nativeint_of_string"
+;;
+external int32_of_string : string -> int32
+ = "caml_int32_of_string"
+;;
+external int64_of_string : string -> int64
+ = "caml_int64_of_string"
+;;
+
+let token_nativeint conv ib = nativeint_of_string (token_int_literal conv ib);;
+let token_int32 conv ib = int32_of_string (token_int_literal conv ib);;
+let token_int64 conv ib = int64_of_string (token_int_literal conv ib);;
+
+(* Scanning numbers. *)
+
+(* Digits scanning functions suppose that one character has been checked and
+ is available, since they return at end of file with the currently found
+ token selected.
+
+ Put it in another way, the digits scanning functions scan for a possibly
+ empty sequence of digits, (hence, a successful scanning from one of those
+ functions does not imply that the token is a well-formed number: to get a
+ true number, it is mandatory to check that at least one valid digit is
+ available before calling one of the digit scanning functions). *)
+
+(* The decimal case is treated especially for optimization purposes. *)
+let rec scan_decimal_digits width ib =
+ if width = 0 then width else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then width else
+ match c with
+ | '0' .. '9' as c ->
+ let width = Scanning.store_char width ib c in
+ scan_decimal_digits width ib
+ | '_' ->
+ let width = Scanning.ignore_char width ib in
+ scan_decimal_digits width ib
+ | _ -> width
+;;
+
+let scan_decimal_digits_plus width ib =
+ if width = 0 then bad_token_length "decimal digits" else
+ let c = Scanning.checked_peek_char ib in
+ match c with
+ | '0' .. '9' ->
+ let width = Scanning.store_char width ib c in
+ scan_decimal_digits width ib
+ | c ->
+ bad_input (Printf.sprintf "character %C is not a decimal digit" c)
+;;
+
+let scan_digits_plus basis digitp width ib =
+ (* To scan numbers from other bases, we use a predicate argument to
+ scan_digits. *)
+ let rec scan_digits width =
+ if width = 0 then width else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then width else
+ match c with
+ | c when digitp c ->
+ let width = Scanning.store_char width ib c in
+ scan_digits width
+ | '_' ->
+ let width = Scanning.ignore_char width ib in
+ scan_digits width
+ | _ -> width in
+
+ (* Ensure we have got enough width left,
+ and read at list one digit. *)
+ if width = 0 then bad_token_length "digits" else
+ let c = Scanning.checked_peek_char ib in
+
+ if digitp c then
+ let width = Scanning.store_char width ib c in
+ scan_digits width
+ else
+ bad_input (Printf.sprintf "character %C is not a valid %s digit" c basis)
+;;
+
+let is_binary_digit = function
+ | '0' .. '1' -> true
+ | _ -> false
+;;
+
+let scan_binary_int = scan_digits_plus "binary" is_binary_digit;;
+
+let is_octal_digit = function
+ | '0' .. '7' -> true
+ | _ -> false
+;;
+
+let scan_octal_int = scan_digits_plus "octal" is_octal_digit;;
+
+let is_hexa_digit = function
+ | '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true
+ | _ -> false
+;;
+
+let scan_hexadecimal_int = scan_digits_plus "hexadecimal" is_hexa_digit;;
+
+(* Scan a decimal integer. *)
+let scan_unsigned_decimal_int = scan_decimal_digits_plus;;
+
+let scan_sign width ib =
+ let c = Scanning.checked_peek_char ib in
+ match c with
+ | '+' -> Scanning.store_char width ib c
+ | '-' -> Scanning.store_char width ib c
+ | _ -> width
+;;
+
+let scan_optionally_signed_decimal_int width ib =
+ let width = scan_sign width ib in
+ scan_unsigned_decimal_int width ib
+;;
+
+(* Scan an unsigned integer that could be given in any (common) basis.
+ If digits are prefixed by one of 0x, 0X, 0o, or 0b, the number is
+ assumed to be written respectively in hexadecimal, hexadecimal,
+ octal, or binary. *)
+let scan_unsigned_int width ib =
+ match Scanning.checked_peek_char ib with
+ | '0' as c ->
+ let width = Scanning.store_char width ib c in
+ if width = 0 then width else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then width else
+ begin match c with
+ | 'x' | 'X' -> scan_hexadecimal_int (Scanning.store_char width ib c) ib
+ | 'o' -> scan_octal_int (Scanning.store_char width ib c) ib
+ | 'b' -> scan_binary_int (Scanning.store_char width ib c) ib
+ | _ -> scan_decimal_digits width ib end
+ | _ -> scan_unsigned_decimal_int width ib
+;;
+
+let scan_optionally_signed_int width ib =
+ let width = scan_sign width ib in
+ scan_unsigned_int width ib
+;;
+
+let scan_int_conv conv width ib =
+ match conv with
+ | 'b' -> scan_binary_int width ib
+ | 'd' -> scan_optionally_signed_decimal_int width ib
+ | 'i' -> scan_optionally_signed_int width ib
+ | 'o' -> scan_octal_int width ib
+ | 'u' -> scan_unsigned_decimal_int width ib
+ | 'x' | 'X' -> scan_hexadecimal_int width ib
+ | _ -> assert false
+;;
+
+(* Scanning floating point numbers. *)
+
+(* Fractional part is optional and can be reduced to 0 digits. *)
+let scan_frac_part width ib =
+ if width = 0 then width else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then width else
+ match c with
+ | '0' .. '9' as c ->
+ scan_decimal_digits (Scanning.store_char width ib c) ib
+ | _ -> width
+;;
+
+(* Exp part is optional and can be reduced to 0 digits. *)
+let scan_exp_part width ib =
+ if width = 0 then width else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then width else
+ match c with
+ | 'e' | 'E' as c ->
+ scan_optionally_signed_decimal_int (Scanning.store_char width ib c) ib
+ | _ -> width
+;;
+
+(* Scan the integer part of a floating point number, (not using the
+ OCaml lexical convention since the integer part can be empty):
+ an optional sign, followed by a possibly empty sequence of decimal
+ digits (e.g. -.1). *)
+let scan_int_part width ib =
+ let width = scan_sign width ib in
+ scan_decimal_digits width ib
+;;
+
+(*
+ For the time being we have (as found in scanf.mli):
+ The field width is composed of an optional integer literal
+ indicating the maximal width of the token to read.
+ Unfortunately, the type-checker let the user write an optional precision,
+ since this is valid for printf format strings.
+
+ Thus, the next step for Scanf is to support a full width and precision
+ indication, more or less similar to the one for printf, possibly extended
+ to the specification of a [max, min] range for the width of the token read
+ for strings. Something like the following spec for scanf.mli:
+
+ The optional [width] is an integer indicating the maximal
+ width of the token read. For instance, [%6d] reads an integer,
+ having at most 6 characters.
+
+ The optional [precision] is a dot [.] followed by an integer:
+
+ - in the floating point number conversions ([%f], [%e], [%g], [%F], [%E],
+ and [%F] conversions, the [precision] indicates the maximum number of
+ digits that may follow the decimal point. For instance, [%.4f] reads a
+ [float] with at most 4 fractional digits,
+
+ - in the string conversions ([%s], [%S], [%\[ range \]]), and in the
+ integer number conversions ([%i], [%d], [%u], [%x], [%o], and their
+ [int32], [int64], and [native_int] correspondent), the [precision]
+ indicates the required minimum width of the token read,
+
+ - on all other conversions, the width and precision are meaningless and
+ ignored (FIXME: lead to a runtime error ? type checking error ?).
+*)
+
+let scan_float width precision ib =
+ let width = scan_int_part width ib in
+ if width = 0 then width, precision else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then width, precision else
+ match c with
+ | '.' ->
+ let width = Scanning.store_char width ib c in
+ let precision = min width precision in
+ let width = width - (precision - scan_frac_part precision ib) in
+ scan_exp_part width ib, precision
+ | _ ->
+ scan_exp_part width ib, precision
+;;
+
+let scan_caml_float width precision ib =
+ let width = scan_optionally_signed_decimal_int width ib in
+ if width = 0 then bad_float () else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then bad_float () else
+ match c with
+ | '.' ->
+ let width = Scanning.store_char width ib c in
+ (* The effective width available for scanning the fractional part is
+ the minimum of declared precision and width left. *)
+ let precision = min width precision in
+ (* After scanning the fractional part with [precision] provisional width,
+ [width_precision] is left. *)
+ let width_precision = scan_frac_part precision ib in
+ (* Hence, scanning the fractional part took exactly
+ [precision - width_precision] chars. *)
+ let frac_width = precision - width_precision in
+ (* And new provisional width is [width - width_precision. *)
+ let width = width - frac_width in
+ scan_exp_part width ib
+ | 'e' | 'E' ->
+ scan_exp_part width ib
+ | _ -> bad_float ()
+;;
+
+(* Scan a regular string:
+ stops when encountering a space, if no scanning indication has been given;
+ otherwise, stops when encountering the characters in the scanning
+ indication [stp].
+ It also stops at end of file or when the maximum number of characters has
+ been read. *)
+let scan_string stp width ib =
+ let rec loop width =
+ if width = 0 then width else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then width else
+ match stp with
+ | Some c' when c = c' -> Scanning.skip_char width ib
+ | Some _ -> loop (Scanning.store_char width ib c)
+ | None ->
+ match c with
+ | ' ' | '\t' | '\n' | '\r' -> width
+ | _ -> loop (Scanning.store_char width ib c)
+ in
+ loop width
+;;
+
+(* Scan a char: peek strictly one character in the input, whatsoever. *)
+let scan_char width ib =
+ (* The case width = 0 could not happen here, since it is tested before
+ calling scan_char, in the main scanning function.
+ if width = 0 then bad_token_length "a character" else *)
+ Scanning.store_char width ib (Scanning.checked_peek_char ib)
+;;
+
+let char_for_backslash = function
+ | 'n' -> '\010'
+ | 'r' -> '\013'
+ | 'b' -> '\008'
+ | 't' -> '\009'
+ | c -> c
+;;
+
+(* The integer value corresponding to the facial value of a valid
+ decimal digit character. *)
+let decimal_value_of_char c = int_of_char c - int_of_char '0';;
+
+let char_for_decimal_code c0 c1 c2 =
+ let c =
+ 100 * decimal_value_of_char c0 +
+ 10 * decimal_value_of_char c1 +
+ decimal_value_of_char c2 in
+ if c < 0 || c > 255 then
+ bad_input
+ (Printf.sprintf
+ "bad character decimal encoding \\%c%c%c" c0 c1 c2) else
+ char_of_int c
+;;
+
+(* The integer value corresponding to the facial value of a valid
+ hexadecimal digit character. *)
+let hexadecimal_value_of_char c =
+ let d = int_of_char c in
+ (* Could also be:
+ if d <= int_of_char '9' then d - int_of_char '0' else
+ if d <= int_of_char 'F' then 10 + d - int_of_char 'A' else
+ if d <= int_of_char 'f' then 10 + d - int_of_char 'a' else assert false
+ *)
+ if d >= int_of_char 'a' then
+ d - 87 (* 10 + int_of_char c - int_of_char 'a' *) else
+ if d >= int_of_char 'A' then
+ d - 55 (* 10 + int_of_char c - int_of_char 'A' *) else
+ d - int_of_char '0'
+;;
+
+let char_for_hexadecimal_code c1 c2 =
+ let c =
+ 16 * hexadecimal_value_of_char c1 +
+ hexadecimal_value_of_char c2 in
+ if c < 0 || c > 255 then
+ bad_input
+ (Printf.sprintf "bad character hexadecimal encoding \\%c%c" c1 c2) else
+ char_of_int c
+;;
+
+(* Called in particular when encountering '\\' as starter of a char.
+ Stops before the corresponding '\''. *)
+let check_next_char message width ib =
+ if width = 0 then bad_token_length message else
+ let c = Scanning.peek_char ib in
+ if Scanning.eof ib then bad_end_of_input message else
+ c
+;;
+
+let check_next_char_for_char = check_next_char "a Char";;
+let check_next_char_for_string = check_next_char "a String";;
+
+let scan_backslash_char width ib =
+ match check_next_char_for_char width ib with
+ | '\\' | '\'' | '\"' | 'n' | 't' | 'b' | 'r' as c ->
+ Scanning.store_char width ib (char_for_backslash c)
+ | '0' .. '9' as c ->
+ let get_digit () =
+ let c = Scanning.next_char ib in
+ match c with
+ | '0' .. '9' as c -> c
+ | c -> bad_input_escape c in
+ let c0 = c in
+ let c1 = get_digit () in
+ let c2 = get_digit () in
+ Scanning.store_char (width - 2) ib (char_for_decimal_code c0 c1 c2)
+ | 'x' ->
+ let get_digit () =
+ let c = Scanning.next_char ib in
+ match c with
+ | '0' .. '9' | 'A' .. 'F' | 'a' .. 'f' as c -> c
+ | c -> bad_input_escape c in
+ let c1 = get_digit () in
+ let c2 = get_digit () in
+ Scanning.store_char (width - 2) ib (char_for_hexadecimal_code c1 c2)
+ | c ->
+ bad_input_escape c
+;;
+
+(* Scan a character (an OCaml token). *)
+let scan_caml_char width ib =
+
+ let rec find_start width =
+ match Scanning.checked_peek_char ib with
+ | '\'' -> find_char (Scanning.ignore_char width ib)
+ | c -> character_mismatch '\'' c
+
+ and find_char width =
+ match check_next_char_for_char width ib with
+ | '\\' ->
+ find_stop (scan_backslash_char (Scanning.ignore_char width ib) ib)
+ | c ->
+ find_stop (Scanning.store_char width ib c)
+
+ and find_stop width =
+ match check_next_char_for_char width ib with
+ | '\'' -> Scanning.ignore_char width ib
+ | c -> character_mismatch '\'' c in
+
+ find_start width
+;;
+
+(* Scan a delimited string (an OCaml token). *)
+let scan_caml_string width ib =
+
+ let rec find_start width =
+ match Scanning.checked_peek_char ib with
+ | '\"' -> find_stop (Scanning.ignore_char width ib)
+ | c -> character_mismatch '\"' c
+
+ and find_stop width =
+ match check_next_char_for_string width ib with
+ | '\"' -> Scanning.ignore_char width ib
+ | '\\' -> scan_backslash (Scanning.ignore_char width ib)
+ | c -> find_stop (Scanning.store_char width ib c)
+
+ and scan_backslash width =
+ match check_next_char_for_string width ib with
+ | '\r' -> skip_newline (Scanning.ignore_char width ib)
+ | '\n' -> skip_spaces (Scanning.ignore_char width ib)
+ | _ -> find_stop (scan_backslash_char width ib)
+
+ and skip_newline width =
+ match check_next_char_for_string width ib with
+ | '\n' -> skip_spaces (Scanning.ignore_char width ib)
+ | _ -> find_stop (Scanning.store_char width ib '\r')
+
+ and skip_spaces width =
+ match check_next_char_for_string width ib with
+ | ' ' -> skip_spaces (Scanning.ignore_char width ib)
+ | _ -> find_stop width in
+
+ find_start width
+;;
+
+(* Scan a boolean (an OCaml token). *)
+let scan_bool ib =
+ let c = Scanning.checked_peek_char ib in
+ let m =
+ match c with
+ | 't' -> 4
+ | 'f' -> 5
+ | c ->
+ bad_input
+ (Printf.sprintf "the character %C cannot start a boolean" c) in
+ scan_string None m ib
+
+(* Scan a string containing elements in char_set and terminated by scan_indic
+ if provided. *)
+let scan_chars_in_char_set char_set scan_indic width ib =
+ let rec scan_chars i stp =
+ let c = Scanning.peek_char ib in
+ if i > 0 && not (Scanning.eof ib) && is_in_char_set char_set c &&
+ int_of_char c <> stp then
+ let _ = Scanning.store_char max_int ib c in
+ scan_chars (i - 1) stp;
+ in
+ match scan_indic with
+ | None -> scan_chars width (-1);
+ | Some c ->
+ scan_chars width (int_of_char c);
+ if not (Scanning.eof ib) then
+ let ci = Scanning.peek_char ib in
+ if c = ci then Scanning.invalidate_current_char ib
+ else character_mismatch c ci
+
+(* The global error report function for [Scanf]. *)
+let scanf_bad_input ib = function
+ | Scan_failure s | Failure s ->
+ let i = Scanning.char_count ib in
+ bad_input (Printf.sprintf "scanf: bad input at char number %i: %S" i s)
+ | x -> raise x
+
+(* Get the content of a counter from an input buffer. *)
+let get_counter ib counter = match counter with
+ | Line_counter -> Scanning.line_count ib
+ | Char_counter -> Scanning.char_count ib
+ | Token_counter -> Scanning.token_count ib
+
+(* Compute the width of a padding option (see "%42{" and "%123("). *)
+let width_of_pad_opt pad_opt = match pad_opt with
+ | None -> max_int
+ | Some width -> width
+
+let stopper_of_formatting_lit fmting =
+ if fmting = Escaped_percent then '%', "" else
+ let str = string_of_formatting_lit fmting in
+ let stp = str.[1] in
+ let sub_str = String.sub str 2 (String.length str - 2) in
+ stp, sub_str
+
+(******************************************************************************)
+ (* Readers managment *)
+
+(* A call to take_format_readers on a format is evaluated into functions
+ taking readers as arguments and aggregate them into an heterogeneous list *)
+(* When all readers are taken, finally pass the list of the readers to the
+ continuation k. *)
+let rec take_format_readers : type a c d e f .
+ ((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, e, f) fmt ->
+ d =
+fun k fmt -> match fmt with
+ | Reader fmt_rest ->
+ fun reader ->
+ let new_k readers_rest = k (Cons (reader, readers_rest)) in
+ take_format_readers new_k fmt_rest
+ | Char rest -> take_format_readers k rest
+ | Caml_char rest -> take_format_readers k rest
+ | String (_, rest) -> take_format_readers k rest
+ | Caml_string (_, rest) -> take_format_readers k rest
+ | Int (_, _, _, rest) -> take_format_readers k rest
+ | Int32 (_, _, _, rest) -> take_format_readers k rest
+ | Nativeint (_, _, _, rest) -> take_format_readers k rest
+ | Int64 (_, _, _, rest) -> take_format_readers k rest
+ | Float (_, _, _, rest) -> take_format_readers k rest
+ | Bool rest -> take_format_readers k rest
+ | Alpha rest -> take_format_readers k rest
+ | Theta rest -> take_format_readers k rest
+ | Flush rest -> take_format_readers k rest
+ | String_literal (_, rest) -> take_format_readers k rest
+ | Char_literal (_, rest) -> take_format_readers k rest
+ | Custom (_, _, rest) -> take_format_readers k rest
+
+ | Scan_char_set (_, _, rest) -> take_format_readers k rest
+ | Scan_get_counter (_, rest) -> take_format_readers k rest
+ | Scan_next_char rest -> take_format_readers k rest
+
+ | Formatting_lit (_, rest) -> take_format_readers k rest
+ | Formatting_gen (Open_tag (Format (fmt, _)), rest) ->
+ take_format_readers k (concat_fmt fmt rest)
+ | Formatting_gen (Open_box (Format (fmt, _)), rest) ->
+ take_format_readers k (concat_fmt fmt rest)
+
+ | Format_arg (_, _, rest) -> take_format_readers k rest
+ | Format_subst (_, fmtty, rest) ->
+ take_fmtty_format_readers k (erase_rel (symm fmtty)) rest
+ | Ignored_param (ign, rest) -> take_ignored_format_readers k ign rest
+
+ | End_of_format -> k Nil
+
+(* Take readers associated to an fmtty coming from a Format_subst "%(...%)". *)
+and take_fmtty_format_readers : type x y a c d e f .
+ ((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, x, y) fmtty ->
+ (y, Scanning.in_channel, c, x, e, f) fmt -> d =
+fun k fmtty fmt -> match fmtty with
+ | Reader_ty fmt_rest ->
+ fun reader ->
+ let new_k readers_rest = k (Cons (reader, readers_rest)) in
+ take_fmtty_format_readers new_k fmt_rest fmt
+ | Ignored_reader_ty fmt_rest ->
+ fun reader ->
+ let new_k readers_rest = k (Cons (reader, readers_rest)) in
+ take_fmtty_format_readers new_k fmt_rest fmt
+ | Char_ty rest -> take_fmtty_format_readers k rest fmt
+ | String_ty rest -> take_fmtty_format_readers k rest fmt
+ | Int_ty rest -> take_fmtty_format_readers k rest fmt
+ | Int32_ty rest -> take_fmtty_format_readers k rest fmt
+ | Nativeint_ty rest -> take_fmtty_format_readers k rest fmt
+ | Int64_ty rest -> take_fmtty_format_readers k rest fmt
+ | Float_ty rest -> take_fmtty_format_readers k rest fmt
+ | Bool_ty rest -> take_fmtty_format_readers k rest fmt
+ | Alpha_ty rest -> take_fmtty_format_readers k rest fmt
+ | Theta_ty rest -> take_fmtty_format_readers k rest fmt
+ | Any_ty rest -> take_fmtty_format_readers k rest fmt
+ | Format_arg_ty (_, rest) -> take_fmtty_format_readers k rest fmt
+ | End_of_fmtty -> take_format_readers k fmt
+ | Format_subst_ty (ty1, ty2, rest) ->
+ let ty = trans (symm ty1) ty2 in
+ take_fmtty_format_readers k (concat_fmtty ty rest) fmt
+
+(* Take readers associated to an ignored parameter. *)
+and take_ignored_format_readers : type x y a c d e f .
+ ((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, x, y) ignored ->
+ (y, Scanning.in_channel, c, x, e, f) fmt -> d =
+fun k ign fmt -> match ign with
+ | Ignored_reader ->
+ fun reader ->
+ let new_k readers_rest = k (Cons (reader, readers_rest)) in
+ take_format_readers new_k fmt
+ | Ignored_char -> take_format_readers k fmt
+ | Ignored_caml_char -> take_format_readers k fmt
+ | Ignored_string _ -> take_format_readers k fmt
+ | Ignored_caml_string _ -> take_format_readers k fmt
+ | Ignored_int (_, _) -> take_format_readers k fmt
+ | Ignored_int32 (_, _) -> take_format_readers k fmt
+ | Ignored_nativeint (_, _) -> take_format_readers k fmt
+ | Ignored_int64 (_, _) -> take_format_readers k fmt
+ | Ignored_float (_, _) -> take_format_readers k fmt
+ | Ignored_bool -> take_format_readers k fmt
+ | Ignored_format_arg _ -> take_format_readers k fmt
+ | Ignored_format_subst (_, fmtty) -> take_fmtty_format_readers k fmtty fmt
+ | Ignored_scan_char_set _ -> take_format_readers k fmt
+ | Ignored_scan_get_counter _ -> take_format_readers k fmt
+ | Ignored_scan_next_char -> take_format_readers k fmt
+
+(******************************************************************************)
+ (* Generic scanning *)
+
+(* Make a generic scanning function. *)
+(* Scan a stream according to a format and readers obtained by
+ take_format_readers, and aggegate scanned values into an
+ heterogeneous list. *)
+(* Return the heterogeneous list of scanned values. *)
+let rec make_scanf : type a c d e f .
+ Scanning.in_channel -> (a, Scanning.in_channel, c, d, e, f) fmt ->
+ (d, _) heter_list -> (a, f) heter_list =
+fun ib fmt readers -> match fmt with
+ | Char rest ->
+ let _ = scan_char 0 ib in
+ let c = token_char ib in
+ Cons (c, make_scanf ib rest readers)
+ | Caml_char rest ->
+ let _ = scan_caml_char 0 ib in
+ let c = token_char ib in
+ Cons (c, make_scanf ib rest readers)
+
+ | String (pad, Formatting_lit (fmting_lit, rest)) ->
+ let stp, str = stopper_of_formatting_lit fmting_lit in
+ let scan width _ ib = scan_string (Some stp) width ib in
+ let str_rest = String_literal (str, rest) in
+ pad_prec_scanf ib str_rest readers pad No_precision scan token_string
+ | String (pad, Formatting_gen (Open_tag (Format (fmt', _)), rest)) ->
+ let scan width _ ib = scan_string (Some '{') width ib in
+ pad_prec_scanf ib (concat_fmt fmt' rest) readers pad No_precision scan
+ token_string
+ | String (pad, Formatting_gen (Open_box (Format (fmt', _)), rest)) ->
+ let scan width _ ib = scan_string (Some '[') width ib in
+ pad_prec_scanf ib (concat_fmt fmt' rest) readers pad No_precision scan
+ token_string
+ | String (pad, rest) ->
+ let scan width _ ib = scan_string None width ib in
+ pad_prec_scanf ib rest readers pad No_precision scan token_string
+
+ | Caml_string (pad, rest) ->
+ let scan width _ ib = scan_caml_string width ib in
+ pad_prec_scanf ib rest readers pad No_precision scan token_string
+ | Int (iconv, pad, prec, rest) ->
+ let c = char_of_iconv iconv in
+ let scan width _ ib = scan_int_conv c width ib in
+ pad_prec_scanf ib rest readers pad prec scan (token_int c)
+ | Int32 (iconv, pad, prec, rest) ->
+ let c = char_of_iconv iconv in
+ let scan width _ ib = scan_int_conv c width ib in
+ pad_prec_scanf ib rest readers pad prec scan (token_int32 c)
+ | Nativeint (iconv, pad, prec, rest) ->
+ let c = char_of_iconv iconv in
+ let scan width _ ib = scan_int_conv c width ib in
+ pad_prec_scanf ib rest readers pad prec scan (token_nativeint c)
+ | Int64 (iconv, pad, prec, rest) ->
+ let c = char_of_iconv iconv in
+ let scan width _ ib = scan_int_conv c width ib in
+ pad_prec_scanf ib rest readers pad prec scan (token_int64 c)
+ | Float (Float_F, pad, prec, rest) ->
+ pad_prec_scanf ib rest readers pad prec scan_caml_float token_float
+ | Float ((Float_f | Float_pf | Float_sf | Float_e | Float_pe | Float_se
+ | Float_E | Float_pE | Float_sE | Float_g | Float_pg | Float_sg
+ | Float_G | Float_pG | Float_sG), pad, prec, rest) ->
+ pad_prec_scanf ib rest readers pad prec scan_float token_float
+
+ | Bool rest ->
+ let _ = scan_bool ib in
+ let b = token_bool ib in
+ Cons (b, make_scanf ib rest readers)
+ | Alpha _ ->
+ invalid_arg "scanf: bad conversion \"%a\""
+ | Theta _ ->
+ invalid_arg "scanf: bad conversion \"%t\""
+ | Custom _ ->
+ invalid_arg "scanf: bad conversion \"%?\" (custom converter)"
+ | Reader fmt_rest ->
+ let Cons (reader, readers_rest) = readers in
+ let x = reader ib in
+ Cons (x, make_scanf ib fmt_rest readers_rest)
+ | Flush rest ->
+ if Scanning.end_of_input ib then make_scanf ib rest readers
+ else bad_input "end of input not found"
+
+ | String_literal (str, rest) ->
+ String.iter (check_char ib) str;
+ make_scanf ib rest readers
+ | Char_literal (chr, rest) ->
+ check_char ib chr;
+ make_scanf ib rest readers
+
+ | Format_arg (pad_opt, fmtty, rest) ->
+ let _ = scan_caml_string (width_of_pad_opt pad_opt) ib in
+ let s = token_string ib in
+ let fmt =
+ try format_of_string_fmtty s fmtty
+ with Failure msg -> bad_input msg
+ in
+ Cons (fmt, make_scanf ib rest readers)
+ | Format_subst (pad_opt, fmtty, rest) ->
+ let _ = scan_caml_string (width_of_pad_opt pad_opt) ib in
+ let s = token_string ib in
+ let fmt, fmt' =
+ try
+ let Fmt_EBB fmt = fmt_ebb_of_string s in
+ let Fmt_EBB fmt' = fmt_ebb_of_string s in
+ (* TODO: find a way to avoid reparsing twice *)
+
+ (* TODO: these type-checks below *can* fail because of type
+ ambiguity in presence of ignored-readers: "%_r%d" and "%d%_r"
+ are typed in the same way.
+
+ # Scanf.sscanf "\"%_r%d\"3" "%(%d%_r%)" ignore
+ (fun fmt n -> string_of_format fmt, n);;
+ Exception: CamlinternalFormat.Type_mismatch.
+
+ We should properly catch this exception.
+ *)
+ type_format fmt (erase_rel fmtty),
+ type_format fmt' (erase_rel (symm fmtty))
+ with Failure msg -> bad_input msg
+ in
+ Cons (Format (fmt, s),
+ make_scanf ib (concat_fmt fmt' rest) readers)
+
+ | Scan_char_set (width_opt, char_set, Formatting_lit (fmting_lit, rest)) ->
+ let stp, str = stopper_of_formatting_lit fmting_lit in
+ let width = width_of_pad_opt width_opt in
+ let _ = scan_chars_in_char_set char_set (Some stp) width ib in
+ let s = token_string ib in
+ let str_rest = String_literal (str, rest) in
+ Cons (s, make_scanf ib str_rest readers)
+ | Scan_char_set (width_opt, char_set, rest) ->
+ let width = width_of_pad_opt width_opt in
+ let _ = scan_chars_in_char_set char_set None width ib in
+ let s = token_string ib in
+ Cons (s, make_scanf ib rest readers)
+ | Scan_get_counter (counter, rest) ->
+ let count = get_counter ib counter in
+ Cons (count, make_scanf ib rest readers)
+ | Scan_next_char rest ->
+ let c = Scanning.checked_peek_char ib in
+ Cons (c, make_scanf ib rest readers)
+
+ | Formatting_lit (formatting_lit, rest) ->
+ String.iter (check_char ib) (string_of_formatting_lit formatting_lit);
+ make_scanf ib rest readers
+ | Formatting_gen (Open_tag (Format (fmt', _)), rest) ->
+ check_char ib '@'; check_char ib '{';
+ make_scanf ib (concat_fmt fmt' rest) readers
+ | Formatting_gen (Open_box (Format (fmt', _)), rest) ->
+ check_char ib '@'; check_char ib '[';
+ make_scanf ib (concat_fmt fmt' rest) readers
+
+ | Ignored_param (ign, rest) ->
+ let Param_format_EBB fmt' = param_format_of_ignored_format ign rest in
+ begin match make_scanf ib fmt' readers with
+ | Cons (_, arg_rest) -> arg_rest
+ | Nil -> assert false
+ end
+
+ | End_of_format ->
+ Nil
+
+(* Case analysis on padding and precision. *)
+(* Reject formats containing "%*" or "%.*". *)
+(* Pass padding and precision to the generic scanner `scan'. *)
+and pad_prec_scanf : type a c d e f x y z t .
+ Scanning.in_channel -> (a, Scanning.in_channel, c, d, e, f) fmt ->
+ (d, _) heter_list -> (x, y) padding -> (y, z -> a) precision ->
+ (int -> int -> Scanning.in_channel -> t) ->
+ (Scanning.in_channel -> z) ->
+ (x, f) heter_list =
+fun ib fmt readers pad prec scan token -> match pad, prec with
+ | No_padding, No_precision ->
+ let _ = scan max_int max_int ib in
+ let x = token ib in
+ Cons (x, make_scanf ib fmt readers)
+ | No_padding, Lit_precision p ->
+ let _ = scan max_int p ib in
+ let x = token ib in
+ Cons (x, make_scanf ib fmt readers)
+ | Lit_padding ((Right | Zeros), w), No_precision ->
+ let _ = scan w max_int ib in
+ let x = token ib in
+ Cons (x, make_scanf ib fmt readers)
+ | Lit_padding ((Right | Zeros), w), Lit_precision p ->
+ let _ = scan w p ib in
+ let x = token ib in
+ Cons (x, make_scanf ib fmt readers)
+ | Lit_padding (Left, _), _ ->
+ invalid_arg "scanf: bad conversion \"%-\""
+ | Lit_padding ((Right | Zeros), _), Arg_precision ->
+ invalid_arg "scanf: bad conversion \"%*\""
+ | Arg_padding _, _ ->
+ invalid_arg "scanf: bad conversion \"%*\""
+ | No_padding, Arg_precision ->
+ invalid_arg "scanf: bad conversion \"%*\""
+
+(******************************************************************************)
+ (* Defining [scanf] and various flavors of [scanf] *)
+
+type 'a kscanf_result = Args of 'a | Exc of exn
+
+let kscanf ib ef (Format (fmt, str)) =
+ let rec apply : type a b . a -> (a, b) heter_list -> b =
+ fun f args -> match args with
+ | Cons (x, r) -> apply (f x) r
+ | Nil -> f
+ in
+ let k readers f =
+ Scanning.reset_token ib;
+ match try Args (make_scanf ib fmt readers) with
+ | (Scan_failure _ | Failure _ | End_of_file) as exc -> Exc exc
+ | Invalid_argument msg ->
+ invalid_arg (msg ^ " in format \"" ^ String.escaped str ^ "\"")
+ with
+ | Args args -> apply f args
+ | Exc exc -> ef ib exc
+ in
+ take_format_readers k fmt
+
+let kbscanf = kscanf
+
+(***)
+
+let ksscanf s ef fmt = kbscanf (Scanning.from_string s) ef fmt
+let kfscanf ic ef fmt = kbscanf (Scanning.from_channel ic) ef fmt
+let bscanf ib fmt = kscanf ib scanf_bad_input fmt
+let fscanf ic fmt = kscanf (Scanning.from_channel ic) scanf_bad_input fmt
+let sscanf s fmt = kscanf (Scanning.from_string s) scanf_bad_input fmt
+let scanf fmt = kscanf Scanning.stdib scanf_bad_input fmt
+
+(***)
+
+let bscanf_format : Scanning.in_channel -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g =
+ fun ib format f ->
+ let _ = scan_caml_string max_int ib in
+ let str = token_string ib in
+ let fmt' =
+ try format_of_string_format str format
+ with Failure msg -> bad_input msg
+ in
+ f fmt'
+
+let sscanf_format : string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g =
+ fun s format f -> bscanf_format (Scanning.from_string s) format f
+
+let string_to_String s =
+ let l = String.length s in
+ let b = Buffer.create (l + 2) in
+ Buffer.add_char b '\"';
+ for i = 0 to l - 1 do
+ let c = s.[i] in
+ if c = '\"' then Buffer.add_char b '\\';
+ Buffer.add_char b c;
+ done;
+ Buffer.add_char b '\"';
+ Buffer.contents b
+;;
+
+let format_from_string s fmt =
+ sscanf_format (string_to_String s) fmt (fun x -> x)
+;;
+
+let unescaped s =
+ sscanf ("\"" ^ s ^ "\"") "%S%!" (fun x -> x)
+;;
diff --git a/stdlib/scanf.mli b/stdlib/scanf.mli
new file mode 100644
index 0000000000..f065c4610b
--- /dev/null
+++ b/stdlib/scanf.mli
@@ -0,0 +1,537 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Formatted input functions. *)
+
+(** {6 Introduction} *)
+
+(** {7 Functional input with format strings} *)
+
+(** The module [Scanf] provides formatted input functions or {e scanners}.
+
+ The formatted input functions can read from any kind of input, including
+ strings, files, or anything that can return characters. The more general
+ source of characters is named a {e formatted input channel} (or {e
+ scanning buffer}) and has type {!Scanning.in_channel}. The more general
+ formatted input function reads from any scanning buffer and is named
+ [bscanf].
+
+ Generally speaking, the formatted input functions have 3 arguments:
+ - the first argument is a source of characters for the input,
+ - the second argument is a format string that specifies the values to
+ read,
+ - the third argument is a {e receiver function} that is applied to the
+ values read.
+
+ Hence, a typical call to the formatted input function {!Scanf.bscanf} is
+ [bscanf ic fmt f], where:
+
+ - [ic] is a source of characters (typically a {e
+ formatted input channel} with type {!Scanning.in_channel}),
+
+ - [fmt] is a format string (the same format strings as those used to print
+ material with module {!Printf} or {!Format}),
+
+ - [f] is a function that has as many arguments as the number of values to
+ read in the input.
+*)
+
+(** {7 A simple example} *)
+
+(** As suggested above, the expression [bscanf ic "%d" f] reads a decimal
+ integer [n] from the source of characters [ic] and returns [f n].
+
+ For instance,
+
+ - if we use [stdin] as the source of characters ({!Scanning.stdin} is
+ the predefined formatted input channel that reads from standard input),
+
+ - if we define the receiver [f] as [let f x = x + 1],
+
+ then [bscanf Scanning.stdin "%d" f] reads an integer [n] from the
+ standard input and returns [f n] (that is [n + 1]). Thus, if we
+ evaluate [bscanf stdin "%d" f], and then enter [41] at the
+ keyboard, we get [42] as the final result.
+*)
+
+(** {7 Formatted input as a functional feature} *)
+
+(** The OCaml scanning facility is reminiscent of the corresponding C feature.
+ However, it is also largely different, simpler, and yet more powerful:
+ the formatted input functions are higher-order functionals and the
+ parameter passing mechanism is just the regular function application not
+ the variable assignment based mechanism which is typical for formatted
+ input in imperative languages; the OCaml format strings also feature
+ useful additions to easily define complex tokens; as expected within a
+ functional programming language, the formatted input functions also
+ support polymorphism, in particular arbitrary interaction with
+ polymorphic user-defined scanners. Furthermore, the OCaml formatted input
+ facility is fully type-checked at compile time.
+*)
+
+(** {6 Formatted input channel} *)
+
+module Scanning : sig
+
+type in_channel
+(** The notion of input channel for the [Scanf] module:
+ those channels provide all the machinery necessary to read from a given
+ [Pervasives.in_channel] value.
+ A [Scanf.Scanning.in_channel] value is also called a {i formatted input
+ channel} or equivalently a {i scanning buffer}.
+ The type [scanbuf] below is an alias for [in_channel].
+ @since 3.12.0
+*)
+
+type scanbuf = in_channel
+(** The type of scanning buffers. A scanning buffer is the source from which a
+ formatted input function gets characters. The scanning buffer holds the
+ current state of the scan, plus a function to get the next char from the
+ input, and a token buffer to store the string matched so far.
+
+ Note: a scanning action may often require to examine one character in
+ advance; when this 'lookahead' character does not belong to the token
+ read, it is stored back in the scanning buffer and becomes the next
+ character yet to be read.
+*)
+
+val stdin : in_channel
+(** The standard input notion for the [Scanf] module.
+ [Scanning.stdin] is the formatted input channel attached to
+ [Pervasives.stdin].
+
+ Note: in the interactive system, when input is read from [stdin], the
+ newline character that triggers the evaluation is incorporated in the
+ input; thus, the scanning specifications must properly skip this
+ additional newline character (for instance, simply add a ['\n'] as the
+ last character of the format string).
+ @since 3.12.0
+*)
+
+type file_name = string
+(** A convenient alias to designate a file name.
+ @since 4.00.0
+*)
+
+val open_in : file_name -> in_channel
+(** [Scanning.open_in fname] returns a formatted input channel for bufferized
+ reading in text mode from file [fname].
+
+ Note:
+ [open_in] returns a formatted input channel that efficiently reads
+ characters in large chunks; in contrast, [from_channel] below returns
+ formatted input channels that must read one character at a time, leading
+ to a much slower scanning rate.
+ @since 3.12.0
+*)
+
+val open_in_bin : file_name -> in_channel
+(** [Scanning.open_in_bin fname] returns a formatted input channel for
+ bufferized reading in binary mode from file [fname].
+ @since 3.12.0
+*)
+
+val close_in : in_channel -> unit
+(** Closes the [Pervasives.in_channel] associated with the given
+ [Scanning.in_channel] formatted input channel.
+ @since 3.12.0
+*)
+
+val from_file : file_name -> in_channel
+(** An alias for [open_in] above. *)
+
+val from_file_bin : string -> in_channel
+(** An alias for [open_in_bin] above. *)
+
+val from_string : string -> in_channel
+(** [Scanning.from_string s] returns a formatted input channel which reads
+ from the given string.
+ Reading starts from the first character in the string.
+ The end-of-input condition is set when the end of the string is reached.
+*)
+
+val from_function : (unit -> char) -> in_channel
+(** [Scanning.from_function f] returns a formatted input channel with the
+ given function as its reading method.
+
+ When scanning needs one more character, the given function is called.
+
+ When the function has no more character to provide, it {e must} signal an
+ end-of-input condition by raising the exception [End_of_file].
+*)
+
+val from_channel : Pervasives.in_channel -> in_channel
+(** [Scanning.from_channel ic] returns a formatted input channel which reads
+ from the regular input channel [ic] argument, starting at the current
+ reading position.
+*)
+
+val end_of_input : in_channel -> bool
+(** [Scanning.end_of_input ic] tests the end-of-input condition of the given
+ formatted input channel.
+*)
+
+val beginning_of_input : in_channel -> bool
+(** [Scanning.beginning_of_input ic] tests the beginning of input condition of
+ the given formatted input channel.
+*)
+
+val name_of_input : in_channel -> string
+(** [Scanning.name_of_input ic] returns the name of the character source
+ for the formatted input channel [ic].
+ @since 3.09.0
+*)
+
+val stdib : in_channel
+(** A deprecated alias for [Scanning.stdin], the scanning buffer reading from
+ [Pervasives.stdin].
+*)
+
+end
+
+(** {6 Type of formatted input functions} *)
+
+type ('a, 'b, 'c, 'd) scanner =
+ ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c
+(** The type of formatted input scanners: [('a, 'b, 'c, 'd) scanner]
+ is the type of a formatted input function that reads from some
+ formatted input channel according to some format string; more
+ precisely, if [scan] is some formatted input function, then [scan
+ ic fmt f] applies [f] to the arguments specified by the format
+ string [fmt], when [scan] has read those arguments from the
+ formatted input channel [ic].
+
+ For instance, the [scanf] function below has type [('a, 'b, 'c, 'd)
+ scanner], since it is a formatted input function that reads from
+ [Scanning.stdin]: [scanf fmt f] applies [f] to the arguments specified by
+ [fmt], reading those arguments from [Pervasives.stdin] as expected.
+
+ If the format [fmt] has some [%r] indications, the corresponding input
+ functions must be provided before the receiver [f] argument. For
+ instance, if [read_elem] is an input function for values of type [t],
+ then [bscanf ic "%r;" read_elem f] reads a value [v] of type [t] followed
+ by a [';'] character, and returns [f v].
+ @since 3.10.0
+*)
+
+exception Scan_failure of string
+(** The exception that formatted input functions raise when the input cannot
+ be read according to the given format.
+*)
+
+(** {6 The general formatted input function} *)
+
+val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner
+(** [bscanf ic fmt r1 ... rN f] reads arguments for the function [f], from the
+ formatted input channel [ic], according to the format string [fmt], and
+ applies [f] to these values.
+ The result of this call to [f] is returned as the result of the entire
+ [bscanf] call.
+ For instance, if [f] is the function [fun s i -> i + 1], then
+ [Scanf.sscanf "x= 1" "%s = %i" f] returns [2].
+
+ Arguments [r1] to [rN] are user-defined input functions that read the
+ argument corresponding to the [%r] conversions specified in the format
+ string.
+*)
+
+(** {6 Format string description} *)
+
+(** The format string is a character string which contains three types of
+ objects:
+ - plain characters, which are simply matched with the characters of the
+ input (with a special case for space and line feed, see {!Scanf.space}),
+ - conversion specifications, each of which causes reading and conversion of
+ one argument for the function [f] (see {!Scanf.conversion}),
+ - scanning indications to specify boundaries of tokens
+ (see scanning {!Scanf.indication}).
+*)
+
+(** {7:space The space character in format strings} *)
+
+(** As mentioned above, a plain character in the format string is just
+ matched with the next character of the input; however, two characters are
+ special exceptions to this rule: the space character ([' '] or ASCII code
+ 32) and the line feed character (['\n'] or ASCII code 10).
+ A space does not match a single space character, but any amount of
+ 'whitespace' in the input. More precisely, a space inside the format
+ string matches {e any number} of tab, space, line feed and carriage
+ return characters. Similarly, a line feed character in the format string
+ matches either a single line feed or a carriage return followed by a line
+ feed.
+
+ Matching {e any} amount of whitespace, a space in the format string
+ also matches no amount of whitespace at all; hence, the call [bscanf ib
+ "Price = %d $" (fun p -> p)] succeeds and returns [1] when reading an
+ input with various whitespace in it, such as [Price = 1 $],
+ [Price = 1 $], or even [Price=1$].
+*)
+
+(** {7:conversion Conversion specifications in format strings} *)
+
+(** Conversion specifications consist in the [%] character, followed by
+ an optional flag, an optional field width, and followed by one or
+ two conversion characters. The conversion characters and their
+ meanings are:
+
+ - [d]: reads an optionally signed decimal integer.
+ - [i]: reads an optionally signed integer
+ (usual input conventions for decimal ([0-9]+), hexadecimal
+ ([0x[0-9a-f]+] and [0X[0-9A-F]+]), octal ([0o[0-7]+]), and binary
+ ([0b[0-1]+]) notations are understood).
+ - [u]: reads an unsigned decimal integer.
+ - [x] or [X]: reads an unsigned hexadecimal integer ([[0-9a-fA-F]+]).
+ - [o]: reads an unsigned octal integer ([[0-7]+]).
+ - [s]: reads a string argument that spreads as much as possible, until the
+ following bounding condition holds: {ul
+ {- a whitespace has been found (see {!Scanf.space}),}
+ {- a scanning indication (see scanning {!Scanf.indication}) has been
+ encountered,}
+ {- the end-of-input has been reached.}}
+ Hence, this conversion always succeeds: it returns an empty
+ string if the bounding condition holds when the scan begins.
+ - [S]: reads a delimited string argument (delimiters and special
+ escaped characters follow the lexical conventions of OCaml).
+ - [c]: reads a single character. To test the current input character
+ without reading it, specify a null field width, i.e. use
+ specification [%0c]. Raise [Invalid_argument], if the field width
+ specification is greater than 1.
+ - [C]: reads a single delimited character (delimiters and special
+ escaped characters follow the lexical conventions of OCaml).
+ - [f], [e], [E], [g], [G]: reads an optionally signed
+ floating-point number in decimal notation, in the style [dddd.ddd
+ e/E+-dd].
+ - [F]: reads a floating point number according to the lexical
+ conventions of OCaml (hence the decimal point is mandatory if the
+ exponent part is not mentioned).
+ - [B]: reads a boolean argument ([true] or [false]).
+ - [b]: reads a boolean argument (for backward compatibility; do not use
+ in new programs).
+ - [ld], [li], [lu], [lx], [lX], [lo]: reads an [int32] argument to
+ the format specified by the second letter for regular integers.
+ - [nd], [ni], [nu], [nx], [nX], [no]: reads a [nativeint] argument to
+ the format specified by the second letter for regular integers.
+ - [Ld], [Li], [Lu], [Lx], [LX], [Lo]: reads an [int64] argument to
+ the format specified by the second letter for regular integers.
+ - [[ range ]]: reads characters that matches one of the characters
+ mentioned in the range of characters [range] (or not mentioned in
+ it, if the range starts with [^]). Reads a [string] that can be
+ empty, if the next input character does not match the range. The set of
+ characters from [c1] to [c2] (inclusively) is denoted by [c1-c2].
+ Hence, [%[0-9]] returns a string representing a decimal number
+ or an empty string if no decimal digit is found; similarly,
+ [%[0-9a-f]] returns a string of hexadecimal digits.
+ If a closing bracket appears in a range, it must occur as the
+ first character of the range (or just after the [^] in case of
+ range negation); hence [[\]]] matches a [\]] character and
+ [[^\]]] matches any character that is not [\]].
+ Use [%%] and [%@] to include a [%] or a [@] in a range.
+ - [r]: user-defined reader. Takes the next [ri] formatted input
+ function and applies it to the scanning buffer [ib] to read the
+ next argument. The input function [ri] must therefore have type
+ [Scanning.in_channel -> 'a] and the argument read has type ['a].
+ - [{ fmt %}]: reads a format string argument. The format string
+ read must have the same type as the format string specification
+ [fmt]. For instance, ["%{ %i %}"] reads any format string that
+ can read a value of type [int]; hence, if [s] is the string
+ ["fmt:\"number is %u\""], then [Scanf.sscanf s "fmt: %{%i%}"]
+ succeeds and returns the format string ["number is %u"].
+ - [( fmt %)]: scanning sub-format substitution.
+ Reads a format string [rf] in the input, then goes on scanning with
+ [rf] instead of scanning with [fmt].
+ The format string [rf] must have the same type as the format string
+ specification [fmt] that it replaces.
+ For instance, ["%( %i %)"] reads any format string that can read a value
+ of type [int].
+ The conversion returns the format string read [rf], and then a value
+ read using [rf].
+ Hence, if [s] is the string ["\"%4d\"1234.00"], then
+ [Scanf.sscanf s "%(%i%)" (fun fmt i -> fmt, i)] evaluates to
+ [("%4d", 1234)].
+ This behaviour is not mere format substitution, since the conversion
+ returns the format string read as additional argument. If you need
+ pure format substitution, use special flag [_] to discard the
+ extraneous argument: conversion [%_( fmt %)] reads a format string
+ [rf] and then behaves the same as format string [rf]. Hence, if [s] is
+ the string ["\"%4d\"1234.00"], then [Scanf.sscanf s "%_(%i%)"] is
+ simply equivalent to [Scanf.sscanf "1234.00" "%4d"].
+ - [l]: returns the number of lines read so far.
+ - [n]: returns the number of characters read so far.
+ - [N] or [L]: returns the number of tokens read so far.
+ - [!]: matches the end of input condition.
+ - [%]: matches one [%] character in the input.
+ - [@]: matches one [@] character in the input.
+ - [,]: does nothing.
+
+ Following the [%] character that introduces a conversion, there may be
+ the special flag [_]: the conversion that follows occurs as usual,
+ but the resulting value is discarded.
+ For instance, if [f] is the function [fun i -> i + 1], and [s] is the
+ string ["x = 1"], then [Scanf.sscanf s "%_s = %i" f] returns [2].
+
+ The field width is composed of an optional integer literal
+ indicating the maximal width of the token to read.
+ For instance, [%6d] reads an integer, having at most 6 decimal digits;
+ [%4f] reads a float with at most 4 characters; and [%8[\000-\255]]
+ returns the next 8 characters (or all the characters still available,
+ if fewer than 8 characters are available in the input).
+
+ Notes:
+
+ - as mentioned above, a [%s] conversion always succeeds, even if there is
+ nothing to read in the input: in this case, it simply returns [""].
+
+ - in addition to the relevant digits, ['_'] characters may appear
+ inside numbers (this is reminiscent to the usual OCaml lexical
+ conventions). If stricter scanning is desired, use the range
+ conversion facility instead of the number conversions.
+
+ - the [scanf] facility is not intended for heavy duty lexical
+ analysis and parsing. If it appears not expressive enough for your
+ needs, several alternative exists: regular expressions (module
+ [Str]), stream parsers, [ocamllex]-generated lexers,
+ [ocamlyacc]-generated parsers.
+*)
+
+(** {7:indication Scanning indications in format strings} *)
+
+(** Scanning indications appear just after the string conversions [%s]
+ and [%[ range ]] to delimit the end of the token. A scanning
+ indication is introduced by a [@] character, followed by some
+ plain character [c]. It means that the string token should end
+ just before the next matching [c] (which is skipped). If no [c]
+ character is encountered, the string token spreads as much as
+ possible. For instance, ["%s@\t"] reads a string up to the next
+ tab character or to the end of input. If a [@] character appears
+ anywhere else in the format string, it is treated as a plain character.
+
+ Note:
+
+ - As usual in format strings, [%] and [@] characters must be escaped
+ using [%%] and [%@]; this rule still holds within range specifications
+ and scanning indications.
+ For instance, ["%s@%%"] reads a string up to the next [%] character.
+ - The scanning indications introduce slight differences in the syntax of
+ [Scanf] format strings, compared to those used for the [Printf]
+ module. However, the scanning indications are similar to those used in
+ the [Format] module; hence, when producing formatted text to be scanned
+ by [!Scanf.bscanf], it is wise to use printing functions from the
+ [Format] module (or, if you need to use functions from [Printf], banish
+ or carefully double check the format strings that contain ['@']
+ characters).
+*)
+
+(** {7 Exceptions during scanning} *)
+
+(** Scanners may raise the following exceptions when the input cannot be read
+ according to the format string:
+
+ - Raise [Scanf.Scan_failure] if the input does not match the format.
+
+ - Raise [Failure] if a conversion to a number is not possible.
+
+ - Raise [End_of_file] if the end of input is encountered while some more
+ characters are needed to read the current conversion specification.
+
+ - Raise [Invalid_argument] if the format string is invalid.
+
+ Note:
+
+ - as a consequence, scanning a [%s] conversion never raises exception
+ [End_of_file]: if the end of input is reached the conversion succeeds and
+ simply returns the characters read so far, or [""] if none were ever read.
+*)
+
+(** {6 Specialised formatted input functions} *)
+
+val fscanf : Pervasives.in_channel -> ('a, 'b, 'c, 'd) scanner
+(** Same as {!Scanf.bscanf}, but reads from the given regular input channel.
+
+ Warning: since all formatted input functions operate from a {e formatted
+ input channel}, be aware that each [fscanf] invocation will operate with a
+ formatted input channel reading from the given channel. This extra level
+ of bufferization can lead to a strange scanning behaviour if you use low
+ level primitives on the channel (reading characters, seeking the reading
+ position, and so on).
+
+ As a consequence, never mix direct low level reading and high level
+ scanning from the same regular input channel.
+*)
+
+val sscanf : string -> ('a, 'b, 'c, 'd) scanner
+(** Same as {!Scanf.bscanf}, but reads from the given string. *)
+
+val scanf : ('a, 'b, 'c, 'd) scanner
+(** Same as {!Scanf.bscanf}, but reads from the predefined formatted input
+ channel {!Scanf.Scanning.stdin} that is connected to [Pervasives.stdin].
+*)
+
+val kscanf :
+ Scanning.in_channel -> (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
+(** Same as {!Scanf.bscanf}, but takes an additional function argument
+ [ef] that is called in case of error: if the scanning process or
+ some conversion fails, the scanning function aborts and calls the
+ error handling function [ef] with the formatted input channel and the
+ exception that aborted the scanning process as arguments.
+*)
+
+val ksscanf :
+ string -> (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
+(** Same as {!Scanf.kscanf} but reads from the given string.
+ @since 4.02.0 *)
+
+val kfscanf :
+ Pervasives.in_channel -> (Scanning.in_channel -> exn -> 'd) ->
+ ('a, 'b, 'c, 'd) scanner
+(** Same as {!Scanf.kscanf}, but reads from the given regular input channel.
+ @since 4.02.0 *)
+
+(** {6 Reading format strings from input} *)
+
+val bscanf_format :
+ Scanning.in_channel -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g
+(** [bscanf_format ic fmt f] reads a format string token from the formatted
+ input channel [ic], according to the given format string [fmt], and
+ applies [f] to the resulting format string value.
+ Raise [Scan_failure] if the format string value read does not have the
+ same type as [fmt].
+ @since 3.09.0
+*)
+
+val sscanf_format :
+ string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
+ (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g
+(** Same as {!Scanf.bscanf_format}, but reads from the given string.
+ @since 3.09.0
+*)
+
+val format_from_string :
+ string ->
+ ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6
+(** [format_from_string s fmt] converts a string argument to a format string,
+ according to the given format string [fmt].
+ Raise [Scan_failure] if [s], considered as a format string, does not
+ have the same type as [fmt].
+ @since 3.10.0
+*)
+
+val unescaped : string -> string
+(** Return a copy of the argument with escape sequences, following the
+ lexical conventions of OCaml, replaced by their corresponding
+ special characters. If there is no escape sequence in the
+ argument, still return a copy, contrary to String.escaped.
+ @since 4.00.0
+*)
diff --git a/stdlib/set.ml b/stdlib/set.ml
new file mode 100644
index 0000000000..33386f1796
--- /dev/null
+++ b/stdlib/set.ml
@@ -0,0 +1,403 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Sets over ordered types *)
+
+module type OrderedType =
+ sig
+ type t
+ val compare: t -> t -> int
+ end
+
+module type S =
+ sig
+ type elt
+ type t
+ val empty: t
+ val is_empty: t -> bool
+ val mem: elt -> t -> bool
+ val add: elt -> t -> t
+ val singleton: elt -> t
+ val remove: elt -> t -> t
+ val union: t -> t -> t
+ val inter: t -> t -> t
+ val diff: t -> t -> t
+ val compare: t -> t -> int
+ val equal: t -> t -> bool
+ val subset: t -> t -> bool
+ val iter: (elt -> unit) -> t -> unit
+ val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a
+ val for_all: (elt -> bool) -> t -> bool
+ val exists: (elt -> bool) -> t -> bool
+ val filter: (elt -> bool) -> t -> t
+ val partition: (elt -> bool) -> t -> t * t
+ val cardinal: t -> int
+ val elements: t -> elt list
+ val min_elt: t -> elt
+ val max_elt: t -> elt
+ val choose: t -> elt
+ val split: elt -> t -> t * bool * t
+ val find: elt -> t -> elt
+ val of_list: elt list -> t
+ end
+
+module Make(Ord: OrderedType) =
+ struct
+ type elt = Ord.t
+ type t = Empty | Node of t * elt * t * int
+
+ (* Sets are represented by balanced binary trees (the heights of the
+ children differ by at most 2 *)
+
+ let height = function
+ Empty -> 0
+ | Node(_, _, _, h) -> h
+
+ (* Creates a new node with left son l, value v and right son r.
+ We must have all elements of l < v < all elements of r.
+ l and r must be balanced and | height l - height r | <= 2.
+ Inline expansion of height for better speed. *)
+
+ let create l v r =
+ let hl = match l with Empty -> 0 | Node(_,_,_,h) -> h in
+ let hr = match r with Empty -> 0 | Node(_,_,_,h) -> h in
+ Node(l, v, r, (if hl >= hr then hl + 1 else hr + 1))
+
+ (* Same as create, but performs one step of rebalancing if necessary.
+ Assumes l and r balanced and | height l - height r | <= 3.
+ Inline expansion of create for better speed in the most frequent case
+ where no rebalancing is required. *)
+
+ let bal l v r =
+ let hl = match l with Empty -> 0 | Node(_,_,_,h) -> h in
+ let hr = match r with Empty -> 0 | Node(_,_,_,h) -> h in
+ if hl > hr + 2 then begin
+ match l with
+ Empty -> invalid_arg "Set.bal"
+ | Node(ll, lv, lr, _) ->
+ if height ll >= height lr then
+ create ll lv (create lr v r)
+ else begin
+ match lr with
+ Empty -> invalid_arg "Set.bal"
+ | Node(lrl, lrv, lrr, _)->
+ create (create ll lv lrl) lrv (create lrr v r)
+ end
+ end else if hr > hl + 2 then begin
+ match r with
+ Empty -> invalid_arg "Set.bal"
+ | Node(rl, rv, rr, _) ->
+ if height rr >= height rl then
+ create (create l v rl) rv rr
+ else begin
+ match rl with
+ Empty -> invalid_arg "Set.bal"
+ | Node(rll, rlv, rlr, _) ->
+ create (create l v rll) rlv (create rlr rv rr)
+ end
+ end else
+ Node(l, v, r, (if hl >= hr then hl + 1 else hr + 1))
+
+ (* Insertion of one element *)
+
+ let rec add x = function
+ Empty -> Node(Empty, x, Empty, 1)
+ | Node(l, v, r, _) as t ->
+ let c = Ord.compare x v in
+ if c = 0 then t else
+ if c < 0 then
+ let ll = add x l in
+ if l == ll then t else bal ll v r
+ else
+ let rr = add x r in
+ if r == rr then t else bal l v rr
+
+ let singleton x = Node(Empty, x, Empty, 1)
+
+ (* Beware: those two functions assume that the added v is *strictly*
+ smaller (or bigger) than all the present elements in the tree; it
+ does not test for equality with the current min (or max) element.
+ Indeed, they are only used during the "join" operation which
+ respects this precondition.
+ *)
+
+ let rec add_min_element v = function
+ | Empty -> singleton v
+ | Node (l, x, r, h) ->
+ bal (add_min_element v l) x r
+
+ let rec add_max_element v = function
+ | Empty -> singleton v
+ | Node (l, x, r, h) ->
+ bal l x (add_max_element v r)
+
+ (* Same as create and bal, but no assumptions are made on the
+ relative heights of l and r. *)
+
+ let rec join l v r =
+ match (l, r) with
+ (Empty, _) -> add_min_element v r
+ | (_, Empty) -> add_max_element v l
+ | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->
+ if lh > rh + 2 then bal ll lv (join lr v r) else
+ if rh > lh + 2 then bal (join l v rl) rv rr else
+ create l v r
+
+ (* Smallest and greatest element of a set *)
+
+ let rec min_elt = function
+ Empty -> raise Not_found
+ | Node(Empty, v, r, _) -> v
+ | Node(l, v, r, _) -> min_elt l
+
+ let rec max_elt = function
+ Empty -> raise Not_found
+ | Node(l, v, Empty, _) -> v
+ | Node(l, v, r, _) -> max_elt r
+
+ (* Remove the smallest element of the given set *)
+
+ let rec remove_min_elt = function
+ Empty -> invalid_arg "Set.remove_min_elt"
+ | Node(Empty, v, r, _) -> r
+ | Node(l, v, r, _) -> bal (remove_min_elt l) v r
+
+ (* Merge two trees l and r into one.
+ All elements of l must precede the elements of r.
+ Assume | height l - height r | <= 2. *)
+
+ let merge t1 t2 =
+ match (t1, t2) with
+ (Empty, t) -> t
+ | (t, Empty) -> t
+ | (_, _) -> bal t1 (min_elt t2) (remove_min_elt t2)
+
+ (* Merge two trees l and r into one.
+ All elements of l must precede the elements of r.
+ No assumption on the heights of l and r. *)
+
+ let concat t1 t2 =
+ match (t1, t2) with
+ (Empty, t) -> t
+ | (t, Empty) -> t
+ | (_, _) -> join t1 (min_elt t2) (remove_min_elt t2)
+
+ (* Splitting. split x s returns a triple (l, present, r) where
+ - l is the set of elements of s that are < x
+ - r is the set of elements of s that are > x
+ - present is false if s contains no element equal to x,
+ or true if s contains an element equal to x. *)
+
+ let rec split x = function
+ Empty ->
+ (Empty, false, Empty)
+ | Node(l, v, r, _) ->
+ let c = Ord.compare x v in
+ if c = 0 then (l, true, r)
+ else if c < 0 then
+ let (ll, pres, rl) = split x l in (ll, pres, join rl v r)
+ else
+ let (lr, pres, rr) = split x r in (join l v lr, pres, rr)
+
+ (* Implementation of the set operations *)
+
+ let empty = Empty
+
+ let is_empty = function Empty -> true | _ -> false
+
+ let rec mem x = function
+ Empty -> false
+ | Node(l, v, r, _) ->
+ let c = Ord.compare x v in
+ c = 0 || mem x (if c < 0 then l else r)
+
+ let rec remove x = function
+ Empty -> Empty
+ | (Node(l, v, r, _) as t) ->
+ let c = Ord.compare x v in
+ if c = 0 then merge l r
+ else
+ if c < 0 then
+ let ll = remove x l in
+ if l == ll then t
+ else bal ll v r
+ else
+ let rr = remove x r in
+ if r == rr then t
+ else bal l v rr
+
+ let rec union s1 s2 =
+ match (s1, s2) with
+ (Empty, t2) -> t2
+ | (t1, Empty) -> t1
+ | (Node(l1, v1, r1, h1), Node(l2, v2, r2, h2)) ->
+ if h1 >= h2 then
+ if h2 = 1 then add v2 s1 else begin
+ let (l2, _, r2) = split v1 s2 in
+ join (union l1 l2) v1 (union r1 r2)
+ end
+ else
+ if h1 = 1 then add v1 s2 else begin
+ let (l1, _, r1) = split v2 s1 in
+ join (union l1 l2) v2 (union r1 r2)
+ end
+
+ let rec inter s1 s2 =
+ match (s1, s2) with
+ (Empty, t2) -> Empty
+ | (t1, Empty) -> Empty
+ | (Node(l1, v1, r1, _), t2) ->
+ match split v1 t2 with
+ (l2, false, r2) ->
+ concat (inter l1 l2) (inter r1 r2)
+ | (l2, true, r2) ->
+ join (inter l1 l2) v1 (inter r1 r2)
+
+ let rec diff s1 s2 =
+ match (s1, s2) with
+ (Empty, t2) -> Empty
+ | (t1, Empty) -> t1
+ | (Node(l1, v1, r1, _), t2) ->
+ match split v1 t2 with
+ (l2, false, r2) ->
+ join (diff l1 l2) v1 (diff r1 r2)
+ | (l2, true, r2) ->
+ concat (diff l1 l2) (diff r1 r2)
+
+ type enumeration = End | More of elt * t * enumeration
+
+ let rec cons_enum s e =
+ match s with
+ Empty -> e
+ | Node(l, v, r, _) -> cons_enum l (More(v, r, e))
+
+ let rec compare_aux e1 e2 =
+ match (e1, e2) with
+ (End, End) -> 0
+ | (End, _) -> -1
+ | (_, End) -> 1
+ | (More(v1, r1, e1), More(v2, r2, e2)) ->
+ let c = Ord.compare v1 v2 in
+ if c <> 0
+ then c
+ else compare_aux (cons_enum r1 e1) (cons_enum r2 e2)
+
+ let compare s1 s2 =
+ compare_aux (cons_enum s1 End) (cons_enum s2 End)
+
+ let equal s1 s2 =
+ compare s1 s2 = 0
+
+ let rec subset s1 s2 =
+ match (s1, s2) with
+ Empty, _ ->
+ true
+ | _, Empty ->
+ false
+ | Node (l1, v1, r1, _), (Node (l2, v2, r2, _) as t2) ->
+ let c = Ord.compare v1 v2 in
+ if c = 0 then
+ subset l1 l2 && subset r1 r2
+ else if c < 0 then
+ subset (Node (l1, v1, Empty, 0)) l2 && subset r1 t2
+ else
+ subset (Node (Empty, v1, r1, 0)) r2 && subset l1 t2
+
+ let rec iter f = function
+ Empty -> ()
+ | Node(l, v, r, _) -> iter f l; f v; iter f r
+
+ let rec fold f s accu =
+ match s with
+ Empty -> accu
+ | Node(l, v, r, _) -> fold f r (f v (fold f l accu))
+
+ let rec for_all p = function
+ Empty -> true
+ | Node(l, v, r, _) -> p v && for_all p l && for_all p r
+
+ let rec exists p = function
+ Empty -> false
+ | Node(l, v, r, _) -> p v || exists p l || exists p r
+
+ let rec filter p = function
+ Empty -> Empty
+ | (Node(l, v, r, _)) as t ->
+ (* call [p] in the expected left-to-right order *)
+ let l' = filter p l in
+ let pv = p v in
+ let r' = filter p r in
+ if pv then
+ if l==l' && r==r' then t else join l' v r'
+ else concat l' r'
+
+ let rec partition p = function
+ Empty -> (Empty, Empty)
+ | Node(l, v, r, _) ->
+ (* call [p] in the expected left-to-right order *)
+ let (lt, lf) = partition p l in
+ let pv = p v in
+ let (rt, rf) = partition p r in
+ if pv
+ then (join lt v rt, concat lf rf)
+ else (concat lt rt, join lf v rf)
+
+ let rec cardinal = function
+ Empty -> 0
+ | Node(l, v, r, _) -> cardinal l + 1 + cardinal r
+
+ let rec elements_aux accu = function
+ Empty -> accu
+ | Node(l, v, r, _) -> elements_aux (v :: elements_aux accu r) l
+
+ let elements s =
+ elements_aux [] s
+
+ let choose = min_elt
+
+ let rec find x = function
+ Empty -> raise Not_found
+ | Node(l, v, r, _) ->
+ let c = Ord.compare x v in
+ if c = 0 then v
+ else find x (if c < 0 then l else r)
+
+ let of_sorted_list l =
+ let rec sub n l =
+ match n, l with
+ | 0, l -> Empty, l
+ | 1, x0 :: l -> Node (Empty, x0, Empty, 1), l
+ | 2, x0 :: x1 :: l -> Node (Node(Empty, x0, Empty, 1), x1, Empty, 2), l
+ | 3, x0 :: x1 :: x2 :: l ->
+ Node (Node(Empty, x0, Empty, 1), x1, Node(Empty, x2, Empty, 1), 2),l
+ | n, l ->
+ let nl = n / 2 in
+ let left, l = sub nl l in
+ match l with
+ | [] -> assert false
+ | mid :: l ->
+ let right, l = sub (n - nl - 1) l in
+ create left mid right, l
+ in
+ fst (sub (List.length l) l)
+
+ let of_list l =
+ match l with
+ | [] -> empty
+ | [x0] -> singleton x0
+ | [x0; x1] -> add x1 (singleton x0)
+ | [x0; x1; x2] -> add x2 (add x1 (singleton x0))
+ | [x0; x1; x2; x3] -> add x3 (add x2 (add x1 (singleton x0)))
+ | [x0; x1; x2; x3; x4] -> add x4 (add x3 (add x2 (add x1 (singleton x0))))
+ | _ -> of_sorted_list (List.sort_uniq Ord.compare l)
+ end
diff --git a/stdlib/set.mli b/stdlib/set.mli
new file mode 100644
index 0000000000..eb77a753dc
--- /dev/null
+++ b/stdlib/set.mli
@@ -0,0 +1,191 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Sets over ordered types.
+
+ This module implements the set data structure, given a total ordering
+ function over the set elements. All operations over sets
+ are purely applicative (no side-effects).
+ The implementation uses balanced binary trees, and is therefore
+ reasonably efficient: insertion and membership take time
+ logarithmic in the size of the set, for instance.
+
+ The [Make] functor constructs implementations for any type, given a
+ [compare] function.
+ For instance:
+ {[
+ module IntPairs =
+ struct
+ type t = int * int
+ let compare (x0,y0) (x1,y1) =
+ match Pervasives.compare x0 x1 with
+ 0 -> Pervasives.compare y0 y1
+ | c -> c
+ end
+
+ module PairsSet = Set.Make(IntPairs)
+
+ let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
+ ]}
+
+ This creates a new module [PairsSet], with a new type [PairsSet.t]
+ of sets of [int * int].
+*)
+
+module type OrderedType =
+ sig
+ type t
+ (** The type of the set elements. *)
+ val compare : t -> t -> int
+ (** A total ordering function over the set elements.
+ This is a two-argument function [f] such that
+ [f e1 e2] is zero if the elements [e1] and [e2] are equal,
+ [f e1 e2] is strictly negative if [e1] is smaller than [e2],
+ and [f e1 e2] is strictly positive if [e1] is greater than [e2].
+ Example: a suitable ordering function is the generic structural
+ comparison function {!Pervasives.compare}. *)
+ end
+(** Input signature of the functor {!Set.Make}. *)
+
+module type S =
+ sig
+ type elt
+ (** The type of the set elements. *)
+
+ type t
+ (** The type of sets. *)
+
+ val empty: t
+ (** The empty set. *)
+
+ val is_empty: t -> bool
+ (** Test whether a set is empty or not. *)
+
+ val mem: elt -> t -> bool
+ (** [mem x s] tests whether [x] belongs to the set [s]. *)
+
+ val add: elt -> t -> t
+ (** [add x s] returns a set containing all elements of [s],
+ plus [x]. If [x] was already in [s], [s] is returned unchanged
+ (the result of the function is then physically equal to [s]).
+ @before 4.03 Physical equality was not ensured. *)
+
+ val singleton: elt -> t
+ (** [singleton x] returns the one-element set containing only [x]. *)
+
+ val remove: elt -> t -> t
+ (** [remove x s] returns a set containing all elements of [s],
+ except [x]. If [x] was not in [s], [s] is returned unchanged
+ (the result of the function is then physically equal to [s]).
+ @before 4.03 Physical equality was not ensured. *)
+
+ val union: t -> t -> t
+ (** Set union. *)
+
+ val inter: t -> t -> t
+ (** Set intersection. *)
+
+ val diff: t -> t -> t
+ (** Set difference. *)
+
+ val compare: t -> t -> int
+ (** Total ordering between sets. Can be used as the ordering function
+ for doing sets of sets. *)
+
+ val equal: t -> t -> bool
+ (** [equal s1 s2] tests whether the sets [s1] and [s2] are
+ equal, that is, contain equal elements. *)
+
+ val subset: t -> t -> bool
+ (** [subset s1 s2] tests whether the set [s1] is a subset of
+ the set [s2]. *)
+
+ val iter: (elt -> unit) -> t -> unit
+ (** [iter f s] applies [f] in turn to all elements of [s].
+ The elements of [s] are presented to [f] in increasing order
+ with respect to the ordering over the type of the elements. *)
+
+ val fold: (elt -> 'a -> 'a) -> t -> 'a -> 'a
+ (** [fold f s a] computes [(f xN ... (f x2 (f x1 a))...)],
+ where [x1 ... xN] are the elements of [s], in increasing order. *)
+
+ val for_all: (elt -> bool) -> t -> bool
+ (** [for_all p s] checks if all elements of the set
+ satisfy the predicate [p]. *)
+
+ val exists: (elt -> bool) -> t -> bool
+ (** [exists p s] checks if at least one element of
+ the set satisfies the predicate [p]. *)
+
+ val filter: (elt -> bool) -> t -> t
+ (** [filter p s] returns the set of all elements in [s]
+ that satisfy predicate [p]. If [p] satisfies every element in [s],
+ [s] is returned unchanged (the result of the function is then
+ physically equal to [s]).
+ @before 4.03 Physical equality was not ensured.*)
+
+ val partition: (elt -> bool) -> t -> t * t
+ (** [partition p s] returns a pair of sets [(s1, s2)], where
+ [s1] is the set of all the elements of [s] that satisfy the
+ predicate [p], and [s2] is the set of all the elements of
+ [s] that do not satisfy [p]. *)
+
+ val cardinal: t -> int
+ (** Return the number of elements of a set. *)
+
+ val elements: t -> elt list
+ (** Return the list of all elements of the given set.
+ The returned list is sorted in increasing order with respect
+ to the ordering [Ord.compare], where [Ord] is the argument
+ given to {!Set.Make}. *)
+
+ val min_elt: t -> elt
+ (** Return the smallest element of the given set
+ (with respect to the [Ord.compare] ordering), or raise
+ [Not_found] if the set is empty. *)
+
+ val max_elt: t -> elt
+ (** Same as {!Set.S.min_elt}, but returns the largest element of the
+ given set. *)
+
+ val choose: t -> elt
+ (** Return one element of the given set, or raise [Not_found] if
+ the set is empty. Which element is chosen is unspecified,
+ but equal elements will be chosen for equal sets. *)
+
+ val split: elt -> t -> t * bool * t
+ (** [split x s] returns a triple [(l, present, r)], where
+ [l] is the set of elements of [s] that are
+ strictly less than [x];
+ [r] is the set of elements of [s] that are
+ strictly greater than [x];
+ [present] is [false] if [s] contains no element equal to [x],
+ or [true] if [s] contains an element equal to [x]. *)
+
+ val find: elt -> t -> elt
+ (** [find x s] returns the element of [s] equal to [x] (according
+ to [Ord.compare]), or raise [Not_found] if no such element
+ exists.
+ @since 4.01.0 *)
+
+ val of_list: elt list -> t
+ (** [of_list l] creates a set from a list of elements.
+ This is usually more efficient than folding [add] over the list,
+ except perhaps for lists with many duplicated elements.
+ @since 4.02.0 *)
+ end
+(** Output signature of the functor {!Set.Make}. *)
+
+module Make (Ord : OrderedType) : S with type elt = Ord.t
+(** Functor building an implementation of the set structure
+ given a totally ordered type. *)
diff --git a/stdlib/sharpbang b/stdlib/sharpbang
new file mode 100644
index 0000000000..04c9334b63
--- /dev/null
+++ b/stdlib/sharpbang
@@ -0,0 +1 @@
+#! \ No newline at end of file
diff --git a/stdlib/sort.ml b/stdlib/sort.ml
new file mode 100644
index 0000000000..59c76cb7b0
--- /dev/null
+++ b/stdlib/sort.ml
@@ -0,0 +1,97 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Merging and sorting *)
+
+open Array
+
+let rec merge order l1 l2 =
+ match l1 with
+ [] -> l2
+ | h1 :: t1 ->
+ match l2 with
+ [] -> l1
+ | h2 :: t2 ->
+ if order h1 h2
+ then h1 :: merge order t1 l2
+ else h2 :: merge order l1 t2
+
+let list order l =
+ let rec initlist = function
+ [] -> []
+ | [e] -> [[e]]
+ | e1::e2::rest ->
+ (if order e1 e2 then [e1;e2] else [e2;e1]) :: initlist rest in
+ let rec merge2 = function
+ l1::l2::rest -> merge order l1 l2 :: merge2 rest
+ | x -> x in
+ let rec mergeall = function
+ [] -> []
+ | [l] -> l
+ | llist -> mergeall (merge2 llist) in
+ mergeall(initlist l)
+
+let swap arr i j =
+ let tmp = unsafe_get arr i in
+ unsafe_set arr i (unsafe_get arr j);
+ unsafe_set arr j tmp
+
+(* There is a known performance bug in the code below. If you find
+ it, don't bother reporting it. You're not supposed to use this
+ module anyway. *)
+let array cmp arr =
+ let rec qsort lo hi =
+ if hi - lo >= 6 then begin
+ let mid = (lo + hi) lsr 1 in
+ (* Select median value from among LO, MID, and HI. Rearrange
+ LO and HI so the three values are sorted. This lowers the
+ probability of picking a pathological pivot. It also
+ avoids extra comparisons on i and j in the two tight "while"
+ loops below. *)
+ if cmp (unsafe_get arr mid) (unsafe_get arr lo) then swap arr mid lo;
+ if cmp (unsafe_get arr hi) (unsafe_get arr mid) then begin
+ swap arr mid hi;
+ if cmp (unsafe_get arr mid) (unsafe_get arr lo) then swap arr mid lo
+ end;
+ let pivot = unsafe_get arr mid in
+ let i = ref (lo + 1) and j = ref (hi - 1) in
+ if not (cmp pivot (unsafe_get arr hi))
+ || not (cmp (unsafe_get arr lo) pivot)
+ then raise (Invalid_argument "Sort.array");
+ while !i < !j do
+ while not (cmp pivot (unsafe_get arr !i)) do incr i done;
+ while not (cmp (unsafe_get arr !j) pivot) do decr j done;
+ if !i < !j then swap arr !i !j;
+ incr i; decr j
+ done;
+ (* Recursion on smaller half, tail-call on larger half *)
+ if !j - lo <= hi - !i then begin
+ qsort lo !j; qsort !i hi
+ end else begin
+ qsort !i hi; qsort lo !j
+ end
+ end in
+ qsort 0 (Array.length arr - 1);
+ (* Finish sorting by insertion sort *)
+ for i = 1 to Array.length arr - 1 do
+ let val_i = (unsafe_get arr i) in
+ if not (cmp (unsafe_get arr (i - 1)) val_i) then begin
+ unsafe_set arr i (unsafe_get arr (i - 1));
+ let j = ref (i - 1) in
+ while !j >= 1 && not (cmp (unsafe_get arr (!j - 1)) val_i) do
+ unsafe_set arr !j (unsafe_get arr (!j - 1));
+ decr j
+ done;
+ unsafe_set arr !j val_i
+ end
+ done
diff --git a/stdlib/sort.mli b/stdlib/sort.mli
new file mode 100644
index 0000000000..2da46cd717
--- /dev/null
+++ b/stdlib/sort.mli
@@ -0,0 +1,42 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Sorting and merging lists.
+
+ @deprecated This module is obsolete and exists only for backward
+ compatibility.
+ The sorting functions in {!Array} and {!List} should be used instead.
+ The new functions are faster and use less memory.
+*)
+
+val list : ('a -> 'a -> bool) -> 'a list -> 'a list
+ [@@ocaml.deprecated "Use List.sort instead."]
+(** Sort a list in increasing order according to an ordering predicate.
+ The predicate should return [true] if its first argument is
+ less than or equal to its second argument. *)
+
+val array : ('a -> 'a -> bool) -> 'a array -> unit
+ [@@ocaml.deprecated "Use Array.sort instead."]
+(** Sort an array in increasing order according to an
+ ordering predicate.
+ The predicate should return [true] if its first argument is
+ less than or equal to its second argument.
+ The array is sorted in place. *)
+
+val merge : ('a -> 'a -> bool) -> 'a list -> 'a list -> 'a list
+ [@@ocaml.deprecated "Use List.merge instead."]
+(** Merge two lists according to the given predicate.
+ Assuming the two argument lists are sorted according to the
+ predicate, [merge] returns a sorted list containing the elements
+ from the two lists. The behavior is undefined if the two
+ argument lists were not sorted. *)
diff --git a/stdlib/stack.ml b/stdlib/stack.ml
new file mode 100644
index 0000000000..4db3d5b436
--- /dev/null
+++ b/stdlib/stack.ml
@@ -0,0 +1,40 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+type 'a t = { mutable c : 'a list }
+
+exception Empty
+
+let create () = { c = [] }
+
+let clear s = s.c <- []
+
+let copy s = { c = s.c }
+
+let push x s = s.c <- x :: s.c
+
+let pop s =
+ match s.c with
+ hd::tl -> s.c <- tl; hd
+ | [] -> raise Empty
+
+let top s =
+ match s.c with
+ hd::_ -> hd
+ | [] -> raise Empty
+
+let is_empty s = (s.c = [])
+
+let length s = List.length s.c
+
+let iter f s = List.iter f s.c
diff --git a/stdlib/stack.mli b/stdlib/stack.mli
new file mode 100644
index 0000000000..9b468aa6cc
--- /dev/null
+++ b/stdlib/stack.mli
@@ -0,0 +1,55 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Last-in first-out stacks.
+
+ This module implements stacks (LIFOs), with in-place modification.
+*)
+
+type 'a t
+(** The type of stacks containing elements of type ['a]. *)
+
+exception Empty
+(** Raised when {!Stack.pop} or {!Stack.top} is applied to an empty stack. *)
+
+
+val create : unit -> 'a t
+(** Return a new stack, initially empty. *)
+
+val push : 'a -> 'a t -> unit
+(** [push x s] adds the element [x] at the top of stack [s]. *)
+
+val pop : 'a t -> 'a
+(** [pop s] removes and returns the topmost element in stack [s],
+ or raises [Empty] if the stack is empty. *)
+
+val top : 'a t -> 'a
+(** [top s] returns the topmost element in stack [s],
+ or raises [Empty] if the stack is empty. *)
+
+val clear : 'a t -> unit
+(** Discard all elements from a stack. *)
+
+val copy : 'a t -> 'a t
+(** Return a copy of the given stack. *)
+
+val is_empty : 'a t -> bool
+(** Return [true] if the given stack is empty, [false] otherwise. *)
+
+val length : 'a t -> int
+(** Return the number of elements in a stack. *)
+
+val iter : ('a -> unit) -> 'a t -> unit
+(** [iter f s] applies [f] in turn to all elements of [s],
+ from the element at the top of the stack to the element at the
+ bottom of the stack. The stack itself is unchanged. *)
diff --git a/stdlib/stdLabels.ml b/stdlib/stdLabels.ml
new file mode 100644
index 0000000000..60713ca0cd
--- /dev/null
+++ b/stdlib/stdLabels.ml
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [StdLabels]: meta-module for labelled libraries *)
+
+module Array = ArrayLabels
+
+module List = ListLabels
+
+module String = StringLabels
+
+module Bytes = BytesLabels
diff --git a/stdlib/stdLabels.mli b/stdlib/stdLabels.mli
new file mode 100644
index 0000000000..c607a9987d
--- /dev/null
+++ b/stdlib/stdLabels.mli
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Standard labeled libraries.
+
+ This meta-module provides labelized version of the {!Array},
+ {!Bytes}, {!List} and {!String} modules.
+
+ They only differ by their labels. Detailed interfaces can be found
+ in [arrayLabels.mli], [bytesLabels.mli], [listLabels.mli]
+ and [stringLabels.mli].
+*)
+
+module Array = ArrayLabels
+module Bytes = BytesLabels
+module List = ListLabels
+module String = StringLabels
diff --git a/stdlib/std_exit.ml b/stdlib/std_exit.ml
new file mode 100644
index 0000000000..66d49c9942
--- /dev/null
+++ b/stdlib/std_exit.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Ensure that [at_exit] functions are called at the end of every program *)
+
+let _ = do_at_exit()
diff --git a/stdlib/stdlib.mllib b/stdlib/stdlib.mllib
new file mode 100644
index 0000000000..b41bc2d938
--- /dev/null
+++ b/stdlib/stdlib.mllib
@@ -0,0 +1,48 @@
+# This file lists all standard library modules
+# (in the same order as Makefile.shared).
+# It is used in particular to know what to expunge in toplevels.
+
+Pervasives
+Array
+List
+Char
+String
+Sys
+Hashtbl
+Sort
+Marshal
+Obj
+Int32
+Int64
+Nativeint
+Lexing
+Parsing
+Set
+Map
+Stack
+Queue
+CamlinternalLazy
+Lazy
+Stream
+Buffer
+Printf
+Format
+Scanf
+Arg
+Printexc
+Gc
+Digest
+Random
+Callback
+CamlinternalOO
+Oo
+CamlinternalMod
+Genlex
+Weak
+Filename
+Complex
+ArrayLabels
+ListLabels
+StringLabels
+MoreLabels
+StdLabels
diff --git a/stdlib/stream.ml b/stdlib/stream.ml
new file mode 100644
index 0000000000..751c741a85
--- /dev/null
+++ b/stdlib/stream.ml
@@ -0,0 +1,218 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Daniel de Rauglaudre, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* The fields of type t are not mutable to preserve polymorphism of
+ the empty stream. This is type safe because the empty stream is never
+ patched. *)
+
+type 'a t = { count : int; data : 'a data }
+and 'a data =
+ Sempty
+ | Scons of 'a * 'a data
+ | Sapp of 'a data * 'a data
+ | Slazy of 'a data Lazy.t
+ | Sgen of 'a gen
+ | Sbuffio of buffio
+and 'a gen = { mutable curr : 'a option option; func : int -> 'a option }
+and buffio =
+ { ic : in_channel; buff : bytes; mutable len : int; mutable ind : int }
+;;
+exception Failure;;
+exception Error of string;;
+
+external count : 'a t -> int = "%field0";;
+external set_count : 'a t -> int -> unit = "%setfield0";;
+let set_data (s : 'a t) (d : 'a data) =
+ Obj.set_field (Obj.repr s) 1 (Obj.repr d)
+;;
+
+let fill_buff b =
+ b.len <- input b.ic b.buff 0 (Bytes.length b.buff); b.ind <- 0
+;;
+
+let rec get_data count d = match d with
+ (* Returns either Sempty or Scons(a, _) even when d is a generator
+ or a buffer. In those cases, the item a is seen as extracted from
+ the generator/buffer.
+ The count parameter is used for calling `Sgen-functions'. *)
+ Sempty | Scons (_, _) -> d
+ | Sapp (d1, d2) ->
+ begin match get_data count d1 with
+ Scons (a, d11) -> Scons (a, Sapp (d11, d2))
+ | Sempty -> get_data count d2
+ | _ -> assert false
+ end
+ | Sgen {curr = Some None; func = _ } -> Sempty
+ | Sgen ({curr = Some(Some a); func = f} as g) ->
+ g.curr <- None; Scons(a, d)
+ | Sgen g ->
+ begin match g.func count with
+ None -> g.curr <- Some(None); Sempty
+ | Some a -> Scons(a, d)
+ (* Warning: anyone using g thinks that an item has been read *)
+ end
+ | Sbuffio b ->
+ if b.ind >= b.len then fill_buff b;
+ if b.len == 0 then Sempty else
+ let r = Obj.magic (Bytes.unsafe_get b.buff b.ind) in
+ (* Warning: anyone using g thinks that an item has been read *)
+ b.ind <- succ b.ind; Scons(r, d)
+ | Slazy f -> get_data count (Lazy.force f)
+;;
+
+let rec peek s =
+ (* consult the first item of s *)
+ match s.data with
+ Sempty -> None
+ | Scons (a, _) -> Some a
+ | Sapp (_, _) ->
+ begin match get_data s.count s.data with
+ Scons(a, _) as d -> set_data s d; Some a
+ | Sempty -> None
+ | _ -> assert false
+ end
+ | Slazy f -> set_data s (Lazy.force f); peek s
+ | Sgen {curr = Some a} -> a
+ | Sgen g -> let x = g.func s.count in g.curr <- Some x; x
+ | Sbuffio b ->
+ if b.ind >= b.len then fill_buff b;
+ if b.len == 0 then begin set_data s Sempty; None end
+ else Some (Obj.magic (Bytes.unsafe_get b.buff b.ind))
+;;
+
+let rec junk s =
+ match s.data with
+ Scons (_, d) -> set_count s (succ s.count); set_data s d
+ | Sgen ({curr = Some _} as g) -> set_count s (succ s.count); g.curr <- None
+ | Sbuffio b -> set_count s (succ s.count); b.ind <- succ b.ind
+ | _ ->
+ match peek s with
+ None -> ()
+ | Some _ -> junk s
+;;
+
+let rec nget n s =
+ if n <= 0 then [], s.data, 0
+ else
+ match peek s with
+ Some a ->
+ junk s;
+ let (al, d, k) = nget (pred n) s in a :: al, Scons (a, d), succ k
+ | None -> [], s.data, 0
+;;
+
+let npeek n s =
+ let (al, d, len) = nget n s in set_count s (s.count - len); set_data s d; al
+;;
+
+let next s =
+ match peek s with
+ Some a -> junk s; a
+ | None -> raise Failure
+;;
+
+let empty s =
+ match peek s with
+ Some _ -> raise Failure
+ | None -> ()
+;;
+
+let iter f strm =
+ let rec do_rec () =
+ match peek strm with
+ Some a -> junk strm; ignore(f a); do_rec ()
+ | None -> ()
+ in
+ do_rec ()
+;;
+
+(* Stream building functions *)
+
+let from f = {count = 0; data = Sgen {curr = None; func = f}};;
+
+let of_list l =
+ {count = 0; data = List.fold_right (fun x l -> Scons (x, l)) l Sempty}
+;;
+
+let of_string s =
+ let count = ref 0 in
+ from (fun _ ->
+ (* We cannot use the index passed by the [from] function directly
+ because it returns the current stream count, with absolutely no
+ guarantee that it will start from 0. For example, in the case
+ of [Stream.icons 'c' (Stream.from_string "ab")], the first
+ access to the string will be made with count [1] already.
+ *)
+ let c = !count in
+ if c < String.length s
+ then (incr count; Some s.[c])
+ else None)
+;;
+
+let of_bytes s =
+ let count = ref 0 in
+ from (fun _ ->
+ let c = !count in
+ if c < Bytes.length s
+ then (incr count; Some (Bytes.get s c))
+ else None)
+;;
+
+let of_channel ic =
+ {count = 0;
+ data = Sbuffio {ic = ic; buff = Bytes.create 4096; len = 0; ind = 0}}
+;;
+
+(* Stream expressions builders *)
+
+let iapp i s = {count = 0; data = Sapp (i.data, s.data)};;
+let icons i s = {count = 0; data = Scons (i, s.data)};;
+let ising i = {count = 0; data = Scons (i, Sempty)};;
+
+let lapp f s =
+ {count = 0; data = Slazy (lazy(Sapp ((f ()).data, s.data)))}
+;;
+let lcons f s = {count = 0; data = Slazy (lazy(Scons (f (), s.data)))};;
+let lsing f = {count = 0; data = Slazy (lazy(Scons (f (), Sempty)))};;
+
+let sempty = {count = 0; data = Sempty};;
+let slazy f = {count = 0; data = Slazy (lazy(f ()).data)};;
+
+(* For debugging use *)
+
+let rec dump f s =
+ print_string "{count = ";
+ print_int s.count;
+ print_string "; data = ";
+ dump_data f s.data;
+ print_string "}";
+ print_newline ()
+and dump_data f =
+ function
+ Sempty -> print_string "Sempty"
+ | Scons (a, d) ->
+ print_string "Scons (";
+ f a;
+ print_string ", ";
+ dump_data f d;
+ print_string ")"
+ | Sapp (d1, d2) ->
+ print_string "Sapp (";
+ dump_data f d1;
+ print_string ", ";
+ dump_data f d2;
+ print_string ")"
+ | Slazy _ -> print_string "Slazy"
+ | Sgen _ -> print_string "Sgen"
+ | Sbuffio b -> print_string "Sbuffio"
+;;
diff --git a/stdlib/stream.mli b/stdlib/stream.mli
new file mode 100644
index 0000000000..1957cf60d2
--- /dev/null
+++ b/stdlib/stream.mli
@@ -0,0 +1,108 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Daniel de Rauglaudre, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Streams and parsers. *)
+
+type 'a t
+(** The type of streams holding values of type ['a]. *)
+
+exception Failure
+(** Raised by parsers when none of the first components of the stream
+ patterns is accepted. *)
+
+exception Error of string
+(** Raised by parsers when the first component of a stream pattern is
+ accepted, but one of the following components is rejected. *)
+
+
+(** {6 Stream builders} *)
+
+val from : (int -> 'a option) -> 'a t
+(** [Stream.from f] returns a stream built from the function [f].
+ To create a new stream element, the function [f] is called with
+ the current stream count. The user function [f] must return either
+ [Some <value>] for a value or [None] to specify the end of the
+ stream.
+
+ Do note that the indices passed to [f] may not start at [0] in the
+ general case. For example, [[< '0; '1; Stream.from f >]] would call
+ [f] the first time with count [2].
+*)
+
+val of_list : 'a list -> 'a t
+(** Return the stream holding the elements of the list in the same
+ order. *)
+
+val of_string : string -> char t
+(** Return the stream of the characters of the string parameter. *)
+
+val of_bytes : bytes -> char t
+(** Return the stream of the characters of the bytes parameter.
+ @since 4.02.0 *)
+
+val of_channel : in_channel -> char t
+(** Return the stream of the characters read from the input channel. *)
+
+
+(** {6 Stream iterator} *)
+
+val iter : ('a -> unit) -> 'a t -> unit
+(** [Stream.iter f s] scans the whole stream s, applying function [f]
+ in turn to each stream element encountered. *)
+
+
+(** {6 Predefined parsers} *)
+
+val next : 'a t -> 'a
+(** Return the first element of the stream and remove it from the
+ stream. Raise Stream.Failure if the stream is empty. *)
+
+val empty : 'a t -> unit
+(** Return [()] if the stream is empty, else raise [Stream.Failure]. *)
+
+
+(** {6 Useful functions} *)
+
+val peek : 'a t -> 'a option
+(** Return [Some] of "the first element" of the stream, or [None] if
+ the stream is empty. *)
+
+val junk : 'a t -> unit
+(** Remove the first element of the stream, possibly unfreezing
+ it before. *)
+
+val count : 'a t -> int
+(** Return the current count of the stream elements, i.e. the number
+ of the stream elements discarded. *)
+
+val npeek : int -> 'a t -> 'a list
+(** [npeek n] returns the list of the [n] first elements of
+ the stream, or all its remaining elements if less than [n]
+ elements are available. *)
+
+(**/**)
+
+(* The following is for system use only. Do not call directly. *)
+
+val iapp : 'a t -> 'a t -> 'a t
+val icons : 'a -> 'a t -> 'a t
+val ising : 'a -> 'a t
+
+val lapp : (unit -> 'a t) -> 'a t -> 'a t
+val lcons : (unit -> 'a) -> 'a t -> 'a t
+val lsing : (unit -> 'a) -> 'a t
+
+val sempty : 'a t
+val slazy : (unit -> 'a t) -> 'a t
+
+val dump : ('a -> unit) -> 'a t -> unit
diff --git a/stdlib/string.ml b/stdlib/string.ml
new file mode 100644
index 0000000000..1b9ab0f357
--- /dev/null
+++ b/stdlib/string.ml
@@ -0,0 +1,137 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* String operations, based on byte sequence operations *)
+
+external length : string -> int = "%string_length"
+external get : string -> int -> char = "%string_safe_get"
+external set : bytes -> int -> char -> unit = "%string_safe_set"
+external create : int -> bytes = "caml_create_string"
+external unsafe_get : string -> int -> char = "%string_unsafe_get"
+external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
+external unsafe_blit : string -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+external unsafe_fill : bytes -> int -> int -> char -> unit
+ = "caml_fill_string" "noalloc"
+
+module B = Bytes
+
+let bts = B.unsafe_to_string
+let bos = B.unsafe_of_string
+
+let make n c =
+ B.make n c |> bts
+let init n f =
+ B.init n f |> bts
+let copy s =
+ B.copy (bos s) |> bts
+let sub s ofs len =
+ B.sub (bos s) ofs len |> bts
+let fill =
+ B.fill
+let blit =
+ B.blit_string
+
+let concat sep l =
+ match l with
+ | [] -> ""
+ | hd :: tl ->
+ let num = ref 0 and len = ref 0 in
+ List.iter (fun s -> incr num; len := !len + length s) l;
+ let r = B.create (!len + length sep * (!num - 1)) in
+ unsafe_blit hd 0 r 0 (length hd);
+ let pos = ref(length hd) in
+ List.iter
+ (fun s ->
+ unsafe_blit sep 0 r !pos (length sep);
+ pos := !pos + length sep;
+ unsafe_blit s 0 r !pos (length s);
+ pos := !pos + length s)
+ tl;
+ Bytes.unsafe_to_string r
+
+let iter f s =
+ B.iter f (bos s)
+let iteri f s =
+ B.iteri f (bos s)
+let map f s =
+ B.map f (bos s) |> bts
+let mapi f s =
+ B.mapi f (bos s) |> bts
+
+(* Beware: we cannot use B.trim or B.escape because they always make a
+ copy, but String.mli spells out some cases where we are not allowed
+ to make a copy. *)
+
+let is_space = function
+ | ' ' | '\012' | '\n' | '\r' | '\t' -> true
+ | _ -> false
+
+let trim s =
+ if s = "" then s
+ else if is_space (unsafe_get s 0) || is_space (unsafe_get s (length s - 1))
+ then bts (B.trim (bos s))
+ else s
+
+let escaped s =
+ let rec needs_escape i =
+ if i >= length s then false else
+ match unsafe_get s i with
+ | '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> true
+ | ' ' .. '~' -> needs_escape (i+1)
+ | _ -> true
+ in
+ if needs_escape 0 then
+ bts (B.escaped (bos s))
+ else
+ s
+
+let index s c =
+ B.index (bos s) c
+let rindex s c =
+ B.rindex (bos s) c
+let index_from s i c=
+ B.index_from (bos s) i c
+let rindex_from s i c =
+ B.rindex_from (bos s) i c
+let contains s c =
+ B.contains (bos s) c
+let contains_from s i c =
+ B.contains_from (bos s) i c
+let rcontains_from s i c =
+ B.rcontains_from (bos s) i c
+
+let uppercase_ascii s =
+ B.uppercase_ascii (bos s) |> bts
+let lowercase_ascii s =
+ B.lowercase_ascii (bos s) |> bts
+let capitalize_ascii s =
+ B.capitalize_ascii (bos s) |> bts
+let uncapitalize_ascii s =
+ B.uncapitalize_ascii (bos s) |> bts
+
+type t = string
+
+let compare (x: t) (y: t) = Pervasives.compare x y
+external equal : string -> string -> bool = "caml_string_equal"
+
+(* Deprecated functions implemented via other deprecated functions *)
+[@@@ocaml.warning "-3"]
+let uppercase s =
+ B.uppercase (bos s) |> bts
+let lowercase s =
+ B.lowercase (bos s) |> bts
+let capitalize s =
+ B.capitalize (bos s) |> bts
+let uncapitalize s =
+ B.uncapitalize (bos s) |> bts
diff --git a/stdlib/string.mli b/stdlib/string.mli
new file mode 100644
index 0000000000..5b1233a6cf
--- /dev/null
+++ b/stdlib/string.mli
@@ -0,0 +1,295 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** String operations.
+
+ A string is an immutable data structure that contains a
+ fixed-length sequence of (single-byte) characters. Each character
+ can be accessed in constant time through its index.
+
+ Given a string [s] of length [l], we can access each of the [l]
+ characters of [s] via its index in the sequence. Indexes start at
+ [0], and we will call an index valid in [s] if it falls within the
+ range [[0...l-1]] (inclusive). A position is the point between two
+ characters or at the beginning or end of the string. We call a
+ position valid in [s] if it falls within the range [[0...l]]
+ (inclusive). Note that the character at index [n] is between
+ positions [n] and [n+1].
+
+ Two parameters [start] and [len] are said to designate a valid
+ substring of [s] if [len >= 0] and [start] and [start+len] are
+ valid positions in [s].
+
+ OCaml strings used to be modifiable in place, for instance via the
+ {!String.set} and {!String.blit} functions described below. This
+ usage is deprecated and only possible when the compiler is put in
+ "unsafe-string" mode by giving the [-unsafe-string] command-line
+ option (which is currently the default for reasons of backward
+ compatibility). This is done by making the types [string] and
+ [bytes] (see module {!Bytes}) interchangeable so that functions
+ expecting byte sequences can also accept strings as arguments and
+ modify them.
+
+ All new code should avoid this feature and be compiled with the
+ [-safe-string] command-line option to enforce the separation between
+ the types [string] and [bytes].
+
+ *)
+
+external length : string -> int = "%string_length"
+(** Return the length (number of characters) of the given string. *)
+
+external get : string -> int -> char = "%string_safe_get"
+(** [String.get s n] returns the character at index [n] in string [s].
+ You can also write [s.[n]] instead of [String.get s n].
+
+ Raise [Invalid_argument] if [n] not a valid index in [s]. *)
+
+
+external set : bytes -> int -> char -> unit = "%string_safe_set"
+ [@@ocaml.deprecated "Use Bytes.set instead."]
+(** [String.set s n c] modifies byte sequence [s] in place,
+ replacing the byte at index [n] with [c].
+ You can also write [s.[n] <- c] instead of [String.set s n c].
+
+ Raise [Invalid_argument] if [n] is not a valid index in [s].
+
+ @deprecated This is a deprecated alias of {!Bytes.set}.[ ] *)
+
+external create : int -> bytes = "caml_create_string"
+ [@@ocaml.deprecated "Use Bytes.create instead."]
+(** [String.create n] returns a fresh byte sequence of length [n].
+ The sequence is uninitialized and contains arbitrary bytes.
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}.
+
+ @deprecated This is a deprecated alias of {!Bytes.create}.[ ] *)
+
+val make : int -> char -> string
+(** [String.make n c] returns a fresh string of length [n],
+ filled with the character [c].
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val init : int -> (int -> char) -> string
+(** [String.init n f] returns a string of length [n], with character
+ [i] initialized to the result of [f i] (called in increasing
+ index order).
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}.
+
+ @since 4.02.0
+*)
+
+val copy : string -> string [@@ocaml.deprecated]
+(** Return a copy of the given string.
+
+ @deprecated Because strings are immutable, it doesn't make much
+ sense to make identical copies of them. *)
+
+val sub : string -> int -> int -> string
+(** [String.sub s start len] returns a fresh string of length [len],
+ containing the substring of [s] that starts at position [start] and
+ has length [len].
+
+ Raise [Invalid_argument] if [start] and [len] do not
+ designate a valid substring of [s]. *)
+
+val fill : bytes -> int -> int -> char -> unit
+ [@@ocaml.deprecated "Use Bytes.fill instead."]
+(** [String.fill s start len c] modifies byte sequence [s] in place,
+ replacing [len] bytes with [c], starting at [start].
+
+ Raise [Invalid_argument] if [start] and [len] do not
+ designate a valid range of [s].
+
+ @deprecated This is a deprecated alias of {!Bytes.fill}.[ ] *)
+
+val blit : string -> int -> bytes -> int -> int -> unit
+(** Same as {!Bytes.blit_string}. *)
+
+val concat : string -> string list -> string
+(** [String.concat sep sl] concatenates the list of strings [sl],
+ inserting the separator string [sep] between each.
+
+ Raise [Invalid_argument] if the result is longer than
+ {!Sys.max_string_length} bytes. *)
+
+val iter : (char -> unit) -> string -> unit
+(** [String.iter f s] applies function [f] in turn to all
+ the characters of [s]. It is equivalent to
+ [f s.[0]; f s.[1]; ...; f s.[String.length s - 1]; ()]. *)
+
+val iteri : (int -> char -> unit) -> string -> unit
+(** Same as {!String.iter}, but the
+ function is applied to the index of the element as first argument
+ (counting from 0), and the character itself as second argument.
+ @since 4.00.0 *)
+
+val map : (char -> char) -> string -> string
+(** [String.map f s] applies function [f] in turn to all the
+ characters of [s] (in increasing index order) and stores the
+ results in a new string that is returned.
+ @since 4.00.0 *)
+
+val mapi : (int -> char -> char) -> string -> string
+(** [String.mapi f s] calls [f] with each character of [s] and its
+ index (in increasing index order) and stores the results in a new
+ string that is returned.
+ @since 4.02.0 *)
+
+val trim : string -> string
+(** Return a copy of the argument, without leading and trailing
+ whitespace. The characters regarded as whitespace are: [' '],
+ ['\012'], ['\n'], ['\r'], and ['\t']. If there is neither leading nor
+ trailing whitespace character in the argument, return the original
+ string itself, not a copy.
+ @since 4.00.0 *)
+
+val escaped : string -> string
+(** Return a copy of the argument, with special characters
+ represented by escape sequences, following the lexical
+ conventions of OCaml.
+ All characters outside the ASCII printable range (32..126) are
+ escaped, as well as backslash and double-quote.
+
+ If there is no special character in the argument that needs
+ escaping, return the original string itself, not a copy.
+
+ Raise [Invalid_argument] if the result is longer than
+ {!Sys.max_string_length} bytes.
+
+ The function {!Scanf.unescaped} is a left inverse of [escaped],
+ i.e. [Scanf.unescaped (escaped s) = s] for any string [s] (unless
+ [escape s] fails). *)
+
+val index : string -> char -> int
+(** [String.index s c] returns the index of the first
+ occurrence of character [c] in string [s].
+
+ Raise [Not_found] if [c] does not occur in [s]. *)
+
+val rindex : string -> char -> int
+(** [String.rindex s c] returns the index of the last
+ occurrence of character [c] in string [s].
+
+ Raise [Not_found] if [c] does not occur in [s]. *)
+
+val index_from : string -> int -> char -> int
+(** [String.index_from s i c] returns the index of the
+ first occurrence of character [c] in string [s] after position [i].
+ [String.index s c] is equivalent to [String.index_from s 0 c].
+
+ Raise [Invalid_argument] if [i] is not a valid position in [s].
+ Raise [Not_found] if [c] does not occur in [s] after position [i]. *)
+
+val rindex_from : string -> int -> char -> int
+(** [String.rindex_from s i c] returns the index of the
+ last occurrence of character [c] in string [s] before position [i+1].
+ [String.rindex s c] is equivalent to
+ [String.rindex_from s (String.length s - 1) c].
+
+ Raise [Invalid_argument] if [i+1] is not a valid position in [s].
+ Raise [Not_found] if [c] does not occur in [s] before position [i+1]. *)
+
+val contains : string -> char -> bool
+(** [String.contains s c] tests if character [c]
+ appears in the string [s]. *)
+
+val contains_from : string -> int -> char -> bool
+(** [String.contains_from s start c] tests if character [c]
+ appears in [s] after position [start].
+ [String.contains s c] is equivalent to
+ [String.contains_from s 0 c].
+
+ Raise [Invalid_argument] if [start] is not a valid position in [s]. *)
+
+val rcontains_from : string -> int -> char -> bool
+(** [String.rcontains_from s stop c] tests if character [c]
+ appears in [s] before position [stop+1].
+
+ Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid
+ position in [s]. *)
+
+val uppercase : string -> string
+ [@@ocaml.deprecated "Use String.uppercase_ascii instead."]
+(** Return a copy of the argument, with all lowercase letters
+ translated to uppercase, including accented letters of the ISO
+ Latin-1 (8859-1) character set.
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val lowercase : string -> string
+ [@@ocaml.deprecated "Use String.lowercase_ascii instead."]
+(** Return a copy of the argument, with all uppercase letters
+ translated to lowercase, including accented letters of the ISO
+ Latin-1 (8859-1) character set.
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val capitalize : string -> string
+ [@@ocaml.deprecated "Use String.capitalize_ascii instead."]
+(** Return a copy of the argument, with the first character set to uppercase,
+ using the ISO Latin-1 (8859-1) character set..
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val uncapitalize : string -> string
+ [@@ocaml.deprecated "Use String.uncapitalize_ascii instead."]
+(** Return a copy of the argument, with the first character set to lowercase,
+ using the ISO Latin-1 (8859-1) character set..
+ @deprecated Functions operating on Latin-1 character set are deprecated. *)
+
+val uppercase_ascii : string -> string
+(** Return a copy of the argument, with all lowercase letters
+ translated to uppercase, using the US-ASCII character set.
+ @since 4.03.0 *)
+
+val lowercase_ascii : string -> string
+(** Return a copy of the argument, with all uppercase letters
+ translated to lowercase, using the US-ASCII character set.
+ @since 4.03.0 *)
+
+val capitalize_ascii : string -> string
+(** Return a copy of the argument, with the first character set to uppercase,
+ using the US-ASCII character set.
+ @since 4.03.0 *)
+
+val uncapitalize_ascii : string -> string
+(** Return a copy of the argument, with the first character set to lowercase,
+ using the US-ASCII character set.
+ @since 4.03.0 *)
+
+type t = string
+(** An alias for the type of strings. *)
+
+val compare: t -> t -> int
+(** The comparison function for strings, with the same specification as
+ {!Pervasives.compare}. Along with the type [t], this function [compare]
+ allows the module [String] to be passed as argument to the functors
+ {!Set.Make} and {!Map.Make}. *)
+
+val equal: t -> t -> bool
+(** The equal function for strings.
+ @since 4.03.0 *)
+
+(**/**)
+
+(* The following is for system use only. Do not call directly. *)
+
+external unsafe_get : string -> int -> char = "%string_unsafe_get"
+external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
+ [@@ocaml.deprecated]
+external unsafe_blit :
+ string -> int -> bytes -> int -> int -> unit
+ = "caml_blit_string" "noalloc"
+external unsafe_fill :
+ bytes -> int -> int -> char -> unit = "caml_fill_string" "noalloc"
+ [@@ocaml.deprecated]
diff --git a/stdlib/stringLabels.ml b/stdlib/stringLabels.ml
new file mode 100644
index 0000000000..415dbff5db
--- /dev/null
+++ b/stdlib/stringLabels.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Module [StringLabels]: labelled String module *)
+
+include String
diff --git a/stdlib/stringLabels.mli b/stdlib/stringLabels.mli
new file mode 100644
index 0000000000..6f6f997ea4
--- /dev/null
+++ b/stdlib/stringLabels.mli
@@ -0,0 +1,215 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** String operations. *)
+
+external length : string -> int = "%string_length"
+(** Return the length (number of characters) of the given string. *)
+
+external get : string -> int -> char = "%string_safe_get"
+(** [String.get s n] returns the character at index [n] in string [s].
+ You can also write [s.[n]] instead of [String.get s n].
+
+ Raise [Invalid_argument] if [n] not a valid index in [s]. *)
+
+external set : bytes -> int -> char -> unit = "%string_safe_set"
+ [@@ocaml.deprecated "Use BytesLabels.set instead."]
+(** [String.set s n c] modifies byte sequence [s] in place,
+ replacing the byte at index [n] with [c].
+ You can also write [s.[n] <- c] instead of [String.set s n c].
+
+ Raise [Invalid_argument] if [n] is not a valid index in [s].
+
+ @deprecated This is a deprecated alias of {!BytesLabels.set}. *)
+
+external create : int -> bytes = "caml_create_string"
+ [@@ocaml.deprecated "Use BytesLabels.create instead."]
+(** [String.create n] returns a fresh byte sequence of length [n].
+ The sequence is uninitialized and contains arbitrary bytes.
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}.
+
+ @deprecated This is a deprecated alias of {!BytesLabels.create}. *)
+
+val make : int -> char -> string
+(** [String.make n c] returns a fresh string of length [n],
+ filled with the character [c].
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val init : int -> f:(int -> char) -> string
+(** [init n f] returns a string of length [n],
+ with character [i] initialized to the result of [f i].
+
+ Raise [Invalid_argument] if [n < 0] or [n > ]{!Sys.max_string_length}. *)
+
+val copy : string -> string
+(** Return a copy of the given string. *)
+
+val sub : string -> pos:int -> len:int -> string
+(** [String.sub s start len] returns a fresh string of length [len],
+ containing the substring of [s] that starts at position [start] and
+ has length [len].
+
+ Raise [Invalid_argument] if [start] and [len] do not
+ designate a valid substring of [s]. *)
+
+val fill : bytes -> pos:int -> len:int -> char -> unit
+ [@@ocaml.deprecated "Use BytesLabels.fill instead."]
+(** [String.fill s start len c] modifies byte sequence [s] in place,
+ replacing [len] bytes by [c], starting at [start].
+
+ Raise [Invalid_argument] if [start] and [len] do not
+ designate a valid substring of [s].
+
+ @deprecated This is a deprecated alias of {!BytesLabels.fill}. *)
+
+val blit :
+ src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int
+ -> unit
+(** [String.blit src srcoff dst dstoff len] copies [len] bytes
+ from the string [src], starting at index [srcoff],
+ to byte sequence [dst], starting at character number [dstoff].
+
+ Raise [Invalid_argument] if [srcoff] and [len] do not
+ designate a valid range of [src], or if [dstoff] and [len]
+ do not designate a valid range of [dst]. *)
+
+val concat : sep:string -> string list -> string
+(** [String.concat sep sl] concatenates the list of strings [sl],
+ inserting the separator string [sep] between each. *)
+
+val iter : f:(char -> unit) -> string -> unit
+(** [String.iter f s] applies function [f] in turn to all
+ the characters of [s]. It is equivalent to
+ [f s.[0]; f s.[1]; ...; f s.[String.length s - 1]; ()]. *)
+
+val iteri : f:(int -> char -> unit) -> string -> unit
+(** Same as {!String.iter}, but the
+ function is applied to the index of the element as first argument
+ (counting from 0), and the character itself as second argument.
+ @since 4.00.0 *)
+
+val map : f:(char -> char) -> string -> string
+(** [String.map f s] applies function [f] in turn to all
+ the characters of [s] and stores the results in a new string that
+ is returned.
+ @since 4.00.0 *)
+
+val mapi : f:(int -> char -> char) -> string -> string
+(** [String.mapi f s] calls [f] with each character of [s] and its
+ index (in increasing index order) and stores the results in a new
+ string that is returned.
+ @since 4.02.0 *)
+
+val trim : string -> string
+(** Return a copy of the argument, without leading and trailing
+ whitespace. The characters regarded as whitespace are: [' '],
+ ['\012'], ['\n'], ['\r'], and ['\t']. If there is no leading nor
+ trailing whitespace character in the argument, return the original
+ string itself, not a copy.
+ @since 4.00.0 *)
+
+val escaped : string -> string
+(** Return a copy of the argument, with special characters
+ represented by escape sequences, following the lexical
+ conventions of OCaml. If there is no special
+ character in the argument, return the original string itself,
+ not a copy. Its inverse function is Scanf.unescaped. *)
+
+val index : string -> char -> int
+(** [String.index s c] returns the index of the first
+ occurrence of character [c] in string [s].
+
+ Raise [Not_found] if [c] does not occur in [s]. *)
+
+val rindex : string -> char -> int
+(** [String.rindex s c] returns the index of the last
+ occurrence of character [c] in string [s].
+
+ Raise [Not_found] if [c] does not occur in [s]. *)
+
+val index_from : string -> int -> char -> int
+(** [String.index_from s i c] returns the index of the
+ first occurrence of character [c] in string [s] after position [i].
+ [String.index s c] is equivalent to [String.index_from s 0 c].
+
+ Raise [Invalid_argument] if [i] is not a valid position in [s].
+ Raise [Not_found] if [c] does not occur in [s] after position [i]. *)
+
+val rindex_from : string -> int -> char -> int
+(** [String.rindex_from s i c] returns the index of the
+ last occurrence of character [c] in string [s] before position [i+1].
+ [String.rindex s c] is equivalent to
+ [String.rindex_from s (String.length s - 1) c].
+
+ Raise [Invalid_argument] if [i+1] is not a valid position in [s].
+ Raise [Not_found] if [c] does not occur in [s] before position [i+1]. *)
+
+val contains : string -> char -> bool
+(** [String.contains s c] tests if character [c]
+ appears in the string [s]. *)
+
+val contains_from : string -> int -> char -> bool
+(** [String.contains_from s start c] tests if character [c]
+ appears in [s] after position [start].
+ [String.contains s c] is equivalent to
+ [String.contains_from s 0 c].
+
+ Raise [Invalid_argument] if [start] is not a valid position in [s]. *)
+
+val rcontains_from : string -> int -> char -> bool
+(** [String.rcontains_from s stop c] tests if character [c]
+ appears in [s] before position [stop+1].
+
+ Raise [Invalid_argument] if [stop < 0] or [stop+1] is not a valid
+ position in [s]. *)
+
+val uppercase : string -> string
+(** Return a copy of the argument, with all lowercase letters
+ translated to uppercase, including accented letters of the ISO
+ Latin-1 (8859-1) character set. *)
+
+val lowercase : string -> string
+(** Return a copy of the argument, with all uppercase letters
+ translated to lowercase, including accented letters of the ISO
+ Latin-1 (8859-1) character set. *)
+
+val capitalize : string -> string
+(** Return a copy of the argument, with the first character set to uppercase. *)
+
+val uncapitalize : string -> string
+(** Return a copy of the argument, with the first character set to lowercase. *)
+
+type t = string
+(** An alias for the type of strings. *)
+
+val compare: t -> t -> int
+(** The comparison function for strings, with the same specification as
+ {!Pervasives.compare}. Along with the type [t], this function [compare]
+ allows the module [String] to be passed as argument to the functors
+ {!Set.Make} and {!Map.Make}. *)
+
+(**/**)
+
+(* The following is for system use only. Do not call directly. *)
+
+external unsafe_get : string -> int -> char = "%string_unsafe_get"
+external unsafe_set : bytes -> int -> char -> unit = "%string_unsafe_set"
+ [@@ocaml.deprecated]
+external unsafe_blit :
+ src:string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int ->
+ unit = "caml_blit_string" "noalloc"
+external unsafe_fill :
+ bytes -> pos:int -> len:int -> char -> unit = "caml_fill_string" "noalloc"
+ [@@ocaml.deprecated]
diff --git a/stdlib/sys.mli b/stdlib/sys.mli
new file mode 100644
index 0000000000..f1321b01ec
--- /dev/null
+++ b/stdlib/sys.mli
@@ -0,0 +1,270 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** System interface.
+
+ Every function in this module raises [Sys_error] with an
+ informative message when the underlying system call signal
+ an error.
+*)
+
+val argv : string array
+(** The command line arguments given to the process.
+ The first element is the command name used to invoke the program.
+ The following elements are the command-line arguments
+ given to the program. *)
+
+val executable_name : string
+(** The name of the file containing the executable currently running. *)
+
+external file_exists : string -> bool = "caml_sys_file_exists"
+(** Test if a file with the given name exists. *)
+
+external is_directory : string -> bool = "caml_sys_is_directory"
+(** Returns [true] if the given name refers to a directory,
+ [false] if it refers to another kind of file.
+ Raise [Sys_error] if no file exists with the given name.
+ @since 3.10.0
+*)
+
+external remove : string -> unit = "caml_sys_remove"
+(** Remove the given file name from the file system. *)
+
+external rename : string -> string -> unit = "caml_sys_rename"
+(** Rename a file. The first argument is the old name and the
+ second is the new name. If there is already another file
+ under the new name, [rename] may replace it, or raise an
+ exception, depending on your operating system. *)
+
+external getenv : string -> string = "caml_sys_getenv"
+(** Return the value associated to a variable in the process
+ environment. Raise [Not_found] if the variable is unbound. *)
+
+external command : string -> int = "caml_sys_system_command"
+(** Execute the given shell command and return its exit code. *)
+
+external time : unit -> float = "caml_sys_time"
+(** Return the processor time, in seconds, used by the program
+ since the beginning of execution. *)
+
+external chdir : string -> unit = "caml_sys_chdir"
+(** Change the current working directory of the process. *)
+
+external getcwd : unit -> string = "caml_sys_getcwd"
+(** Return the current working directory of the process. *)
+
+external readdir : string -> string array = "caml_sys_read_directory"
+(** Return the names of all files present in the given directory.
+ Names denoting the current directory and the parent directory
+ (["."] and [".."] in Unix) are not returned. Each string in the
+ result is a file name rather than a complete path. There is no
+ guarantee that the name strings in the resulting array will appear
+ in any specific order; they are not, in particular, guaranteed to
+ appear in alphabetical order. *)
+
+val interactive : bool ref
+(** This reference is initially set to [false] in standalone
+ programs and to [true] if the code is being executed under
+ the interactive toplevel system [ocaml]. *)
+
+val os_type : string
+(** Operating system currently executing the OCaml program. One of
+- ["Unix"] (for all Unix versions, including Linux and Mac OS X),
+- ["Win32"] (for MS-Windows, OCaml compiled with MSVC++ or Mingw),
+- ["Cygwin"] (for MS-Windows, OCaml compiled with Cygwin). *)
+
+val unix : bool
+(** True if [Sys.os_type = "Unix"].
+ @since 4.01.0 *)
+
+val win32 : bool
+(** True if [Sys.os_type = "Win32"].
+ @since 4.01.0 *)
+
+val cygwin : bool
+(** True if [Sys.os_type = "Cygwin"].
+ @since 4.01.0 *)
+
+val word_size : int
+(** Size of one word on the machine currently executing the OCaml
+ program, in bits: 32 or 64. *)
+
+val int_size : int
+(** Size of an int. It is 31 bits (resp. 63 bits) when using the
+ OCaml compiler on a 32 bits (resp. 64 bits) platform. It may
+ differ for other compilers, e.g. it is 32 bits when compiling to
+ JavaScript.
+ @since 4.03.0 *)
+
+val big_endian : bool
+(** Whether the machine currently executing the Caml program is big-endian.
+ @since 4.00.0 *)
+
+val max_string_length : int
+(** Maximum length of strings and byte sequences. *)
+
+val max_array_length : int
+(** Maximum length of a normal array. The maximum length of a float
+ array is [max_array_length/2] on 32-bit machines and
+ [max_array_length] on 64-bit machines. *)
+
+
+(** {6 Signal handling} *)
+
+
+type signal_behavior =
+ Signal_default
+ | Signal_ignore
+ | Signal_handle of (int -> unit) (** *)
+(** What to do when receiving a signal:
+ - [Signal_default]: take the default behavior
+ (usually: abort the program)
+ - [Signal_ignore]: ignore the signal
+ - [Signal_handle f]: call function [f], giving it the signal
+ number as argument. *)
+
+external signal :
+ int -> signal_behavior -> signal_behavior = "caml_install_signal_handler"
+(** Set the behavior of the system on receipt of a given signal. The
+ first argument is the signal number. Return the behavior
+ previously associated with the signal. If the signal number is
+ invalid (or not available on your system), an [Invalid_argument]
+ exception is raised. *)
+
+val set_signal : int -> signal_behavior -> unit
+(** Same as {!Sys.signal} but return value is ignored. *)
+
+
+(** {7 Signal numbers for the standard POSIX signals.} *)
+
+val sigabrt : int
+(** Abnormal termination *)
+
+val sigalrm : int
+(** Timeout *)
+
+val sigfpe : int
+(** Arithmetic exception *)
+
+val sighup : int
+(** Hangup on controlling terminal *)
+
+val sigill : int
+(** Invalid hardware instruction *)
+
+val sigint : int
+(** Interactive interrupt (ctrl-C) *)
+
+val sigkill : int
+(** Termination (cannot be ignored) *)
+
+val sigpipe : int
+(** Broken pipe *)
+
+val sigquit : int
+(** Interactive termination *)
+
+val sigsegv : int
+(** Invalid memory reference *)
+
+val sigterm : int
+(** Termination *)
+
+val sigusr1 : int
+(** Application-defined signal 1 *)
+
+val sigusr2 : int
+(** Application-defined signal 2 *)
+
+val sigchld : int
+(** Child process terminated *)
+
+val sigcont : int
+(** Continue *)
+
+val sigstop : int
+(** Stop *)
+
+val sigtstp : int
+(** Interactive stop *)
+
+val sigttin : int
+(** Terminal read from background process *)
+
+val sigttou : int
+(** Terminal write from background process *)
+
+val sigvtalrm : int
+(** Timeout in virtual time *)
+
+val sigprof : int
+(** Profiling interrupt *)
+
+val sigbus : int
+(** Bus error
+ @since 4.03 *)
+
+val sigpoll : int
+(** Pollable event
+ @since 4.03 *)
+
+val sigsys : int
+(** Bad argument to routine
+ @since 4.03 *)
+
+val sigtrap : int
+(** Trace/breakpoint trap
+ @since 4.03 *)
+
+val sigurg : int
+(** Urgent condition on socket
+ @since 4.03 *)
+
+val sigxcpu : int
+(** Timeout in cpu time
+ @since 4.03 *)
+
+val sigxfsz : int
+(** File size limit exceeded
+ @since 4.03 *)
+
+
+exception Break
+(** Exception raised on interactive interrupt if {!Sys.catch_break}
+ is on. *)
+
+
+val catch_break : bool -> unit
+(** [catch_break] governs whether interactive interrupt (ctrl-C)
+ terminates the program or raises the [Break] exception.
+ Call [catch_break true] to enable raising [Break],
+ and [catch_break false] to let the system
+ terminate the program on user interrupt. *)
+
+
+val ocaml_version : string;;
+(** [ocaml_version] is the version of OCaml.
+ It is a string of the form ["major.minor[.patchlevel][+additional-info]"],
+ where [major], [minor], and [patchlevel] are integers, and
+ [additional-info] is an arbitrary string. The [[.patchlevel]] and
+ [[+additional-info]] parts may be absent. *)
+
+
+val enable_runtime_warnings: bool -> unit
+(** Control whether the OCaml runtime system can emit warnings
+ on stderr. Currently, the only supported warning is triggered
+ when a channel created by [open_*] functions is finalized without
+ being closed. Runtime warnings are enabled by default. *)
+
+val runtime_warnings_enabled: unit -> bool
+(** Return whether runtime warnings are currently enabled. *)
diff --git a/stdlib/sys.mlp b/stdlib/sys.mlp
new file mode 100644
index 0000000000..434f189733
--- /dev/null
+++ b/stdlib/sys.mlp
@@ -0,0 +1,109 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* WARNING: sys.ml is generated from sys.mlp. DO NOT EDIT sys.ml or
+ your changes will be lost.
+*)
+
+(* System interface *)
+
+external get_config: unit -> string * int * bool = "caml_sys_get_config"
+external get_argv: unit -> string * string array = "caml_sys_get_argv"
+external big_endian : unit -> bool = "%big_endian"
+external word_size : unit -> int = "%word_size"
+external int_size : unit -> int = "%int_size"
+external max_wosize : unit -> int = "%max_wosize"
+external unix : unit -> bool = "%ostype_unix"
+external win32 : unit -> bool = "%ostype_win32"
+external cygwin : unit -> bool = "%ostype_cygwin"
+
+let (executable_name, argv) = get_argv()
+let (os_type, _, _) = get_config()
+let big_endian = big_endian ()
+let word_size = word_size ()
+let int_size = int_size ()
+let unix = unix ()
+let win32 = win32 ()
+let cygwin = cygwin ()
+let max_array_length = max_wosize ()
+let max_string_length = word_size / 8 * max_array_length - 1;;
+
+external file_exists: string -> bool = "caml_sys_file_exists"
+external is_directory : string -> bool = "caml_sys_is_directory"
+external remove: string -> unit = "caml_sys_remove"
+external rename : string -> string -> unit = "caml_sys_rename"
+external getenv: string -> string = "caml_sys_getenv"
+external command: string -> int = "caml_sys_system_command"
+external time: unit -> float = "caml_sys_time"
+external chdir: string -> unit = "caml_sys_chdir"
+external getcwd: unit -> string = "caml_sys_getcwd"
+external readdir : string -> string array = "caml_sys_read_directory"
+
+let interactive = ref false
+
+type signal_behavior =
+ Signal_default
+ | Signal_ignore
+ | Signal_handle of (int -> unit)
+
+external signal : int -> signal_behavior -> signal_behavior
+ = "caml_install_signal_handler"
+
+let set_signal sig_num sig_beh = ignore(signal sig_num sig_beh)
+
+let sigabrt = -1
+let sigalrm = -2
+let sigfpe = -3
+let sighup = -4
+let sigill = -5
+let sigint = -6
+let sigkill = -7
+let sigpipe = -8
+let sigquit = -9
+let sigsegv = -10
+let sigterm = -11
+let sigusr1 = -12
+let sigusr2 = -13
+let sigchld = -14
+let sigcont = -15
+let sigstop = -16
+let sigtstp = -17
+let sigttin = -18
+let sigttou = -19
+let sigvtalrm = -20
+let sigprof = -21
+let sigbus = -22
+let sigpoll = -23
+let sigsys = -24
+let sigtrap = -25
+let sigurg = -26
+let sigxcpu = -27
+let sigxfsz = -28
+
+exception Break
+
+let catch_break on =
+ if on then
+ set_signal sigint (Signal_handle(fun _ -> raise Break))
+ else
+ set_signal sigint Signal_default
+
+
+external enable_runtime_warnings: bool -> unit =
+ "caml_ml_enable_runtime_warnings"
+external runtime_warnings_enabled: unit -> bool =
+ "caml_ml_runtime_warnings_enabled"
+
+(* The version string is found in file ../VERSION *)
+
+let ocaml_version = "%%VERSION%%";;
diff --git a/stdlib/weak.ml b/stdlib/weak.ml
new file mode 100644
index 0000000000..71385c9b77
--- /dev/null
+++ b/stdlib/weak.ml
@@ -0,0 +1,305 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Weak array operations *)
+
+type 'a t;;
+
+external create : int -> 'a t = "caml_weak_create";;
+
+let length x = Obj.size(Obj.repr x) - 1;;
+
+external set : 'a t -> int -> 'a option -> unit = "caml_weak_set";;
+external get : 'a t -> int -> 'a option = "caml_weak_get";;
+external get_copy : 'a t -> int -> 'a option = "caml_weak_get_copy";;
+external check : 'a t -> int -> bool = "caml_weak_check";;
+external blit : 'a t -> int -> 'a t -> int -> int -> unit = "caml_weak_blit";;
+(* blit: src srcoff dst dstoff len *)
+
+let fill ar ofs len x =
+ if ofs < 0 || len < 0 || ofs + len > length ar
+ then raise (Invalid_argument "Weak.fill")
+ else begin
+ for i = ofs to (ofs + len - 1) do
+ set ar i x
+ done
+ end
+;;
+
+(** Weak hash tables *)
+
+module type S = sig
+ type data
+ type t
+ val create : int -> t
+ val clear : t -> unit
+ val merge : t -> data -> data
+ val add : t -> data -> unit
+ val remove : t -> data -> unit
+ val find : t -> data -> data
+ val find_all : t -> data -> data list
+ val mem : t -> data -> bool
+ val iter : (data -> unit) -> t -> unit
+ val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a
+ val count : t -> int
+ val stats : t -> int * int * int * int * int * int
+end;;
+
+module Make (H : Hashtbl.HashedType) : (S with type data = H.t) = struct
+
+ type 'a weak_t = 'a t;;
+ let weak_create = create;;
+ let emptybucket = weak_create 0;;
+
+ type data = H.t;;
+
+ type t = {
+ mutable table : data weak_t array;
+ mutable hashes : int array array;
+ mutable limit : int; (* bucket size limit *)
+ mutable oversize : int; (* number of oversize buckets *)
+ mutable rover : int; (* for internal bookkeeping *)
+ };;
+
+ let get_index t h = (h land max_int) mod (Array.length t.table);;
+
+ let limit = 7;;
+ let over_limit = 2;;
+
+ let create sz =
+ let sz = if sz < 7 then 7 else sz in
+ let sz = if sz > Sys.max_array_length then Sys.max_array_length else sz in
+ {
+ table = Array.make sz emptybucket;
+ hashes = Array.make sz [| |];
+ limit = limit;
+ oversize = 0;
+ rover = 0;
+ };;
+
+ let clear t =
+ for i = 0 to Array.length t.table - 1 do
+ t.table.(i) <- emptybucket;
+ t.hashes.(i) <- [| |];
+ done;
+ t.limit <- limit;
+ t.oversize <- 0;
+ ;;
+
+ let fold f t init =
+ let rec fold_bucket i b accu =
+ if i >= length b then accu else
+ match get b i with
+ | Some v -> fold_bucket (i+1) b (f v accu)
+ | None -> fold_bucket (i+1) b accu
+ in
+ Array.fold_right (fold_bucket 0) t.table init
+ ;;
+
+ let iter f t =
+ let rec iter_bucket i b =
+ if i >= length b then () else
+ match get b i with
+ | Some v -> f v; iter_bucket (i+1) b
+ | None -> iter_bucket (i+1) b
+ in
+ Array.iter (iter_bucket 0) t.table
+ ;;
+
+ let iter_weak f t =
+ let rec iter_bucket i j b =
+ if i >= length b then () else
+ match check b i with
+ | true -> f b t.hashes.(j) i; iter_bucket (i+1) j b
+ | false -> iter_bucket (i+1) j b
+ in
+ Array.iteri (iter_bucket 0) t.table
+ ;;
+
+ let rec count_bucket i b accu =
+ if i >= length b then accu else
+ count_bucket (i+1) b (accu + (if check b i then 1 else 0))
+ ;;
+
+ let count t =
+ Array.fold_right (count_bucket 0) t.table 0
+ ;;
+
+ let next_sz n = min (3 * n / 2 + 3) Sys.max_array_length;;
+ let prev_sz n = ((n - 3) * 2 + 2) / 3;;
+
+ let test_shrink_bucket t =
+ let bucket = t.table.(t.rover) in
+ let hbucket = t.hashes.(t.rover) in
+ let len = length bucket in
+ let prev_len = prev_sz len in
+ let live = count_bucket 0 bucket 0 in
+ if live <= prev_len then begin
+ let rec loop i j =
+ if j >= prev_len then begin
+ if check bucket i then loop (i + 1) j
+ else if check bucket j then begin
+ blit bucket j bucket i 1;
+ hbucket.(i) <- hbucket.(j);
+ loop (i + 1) (j - 1);
+ end else loop i (j - 1);
+ end;
+ in
+ loop 0 (length bucket - 1);
+ if prev_len = 0 then begin
+ t.table.(t.rover) <- emptybucket;
+ t.hashes.(t.rover) <- [| |];
+ end else begin
+ Obj.truncate (Obj.repr bucket) (prev_len + 1);
+ Obj.truncate (Obj.repr hbucket) prev_len;
+ end;
+ if len > t.limit && prev_len <= t.limit then t.oversize <- t.oversize - 1;
+ end;
+ t.rover <- (t.rover + 1) mod (Array.length t.table);
+ ;;
+
+ let rec resize t =
+ let oldlen = Array.length t.table in
+ let newlen = next_sz oldlen in
+ if newlen > oldlen then begin
+ let newt = create newlen in
+ let add_weak ob oh oi =
+ let setter nb ni _ = blit ob oi nb ni 1 in
+ let h = oh.(oi) in
+ add_aux newt setter None h (get_index newt h);
+ in
+ iter_weak add_weak t;
+ t.table <- newt.table;
+ t.hashes <- newt.hashes;
+ t.limit <- newt.limit;
+ t.oversize <- newt.oversize;
+ t.rover <- t.rover mod Array.length newt.table;
+ end else begin
+ t.limit <- max_int; (* maximum size already reached *)
+ t.oversize <- 0;
+ end
+
+ and add_aux t setter d h index =
+ let bucket = t.table.(index) in
+ let hashes = t.hashes.(index) in
+ let sz = length bucket in
+ let rec loop i =
+ if i >= sz then begin
+ let newsz = min (3 * sz / 2 + 3) (Sys.max_array_length - 1) in
+ if newsz <= sz then failwith "Weak.Make: hash bucket cannot grow more";
+ let newbucket = weak_create newsz in
+ let newhashes = Array.make newsz 0 in
+ blit bucket 0 newbucket 0 sz;
+ Array.blit hashes 0 newhashes 0 sz;
+ setter newbucket sz d;
+ newhashes.(sz) <- h;
+ t.table.(index) <- newbucket;
+ t.hashes.(index) <- newhashes;
+ if sz <= t.limit && newsz > t.limit then begin
+ t.oversize <- t.oversize + 1;
+ for _i = 0 to over_limit do test_shrink_bucket t done;
+ end;
+ if t.oversize > Array.length t.table / over_limit then resize t;
+ end else if check bucket i then begin
+ loop (i + 1)
+ end else begin
+ setter bucket i d;
+ hashes.(i) <- h;
+ end;
+ in
+ loop 0;
+ ;;
+
+ let add t d =
+ let h = H.hash d in
+ add_aux t set (Some d) h (get_index t h);
+ ;;
+
+ let find_or t d ifnotfound =
+ let h = H.hash d in
+ let index = get_index t h in
+ let bucket = t.table.(index) in
+ let hashes = t.hashes.(index) in
+ let sz = length bucket in
+ let rec loop i =
+ if i >= sz then ifnotfound h index
+ else if h = hashes.(i) then begin
+ match get_copy bucket i with
+ | Some v when H.equal v d
+ -> begin match get bucket i with
+ | Some v -> v
+ | None -> loop (i + 1)
+ end
+ | _ -> loop (i + 1)
+ end else loop (i + 1)
+ in
+ loop 0
+ ;;
+
+ let merge t d =
+ find_or t d (fun h index -> add_aux t set (Some d) h index; d)
+ ;;
+
+ let find t d = find_or t d (fun h index -> raise Not_found);;
+
+ let find_shadow t d iffound ifnotfound =
+ let h = H.hash d in
+ let index = get_index t h in
+ let bucket = t.table.(index) in
+ let hashes = t.hashes.(index) in
+ let sz = length bucket in
+ let rec loop i =
+ if i >= sz then ifnotfound
+ else if h = hashes.(i) then begin
+ match get_copy bucket i with
+ | Some v when H.equal v d -> iffound bucket i
+ | _ -> loop (i + 1)
+ end else loop (i + 1)
+ in
+ loop 0
+ ;;
+
+ let remove t d = find_shadow t d (fun w i -> set w i None) ();;
+
+ let mem t d = find_shadow t d (fun w i -> true) false;;
+
+ let find_all t d =
+ let h = H.hash d in
+ let index = get_index t h in
+ let bucket = t.table.(index) in
+ let hashes = t.hashes.(index) in
+ let sz = length bucket in
+ let rec loop i accu =
+ if i >= sz then accu
+ else if h = hashes.(i) then begin
+ match get_copy bucket i with
+ | Some v when H.equal v d
+ -> begin match get bucket i with
+ | Some v -> loop (i + 1) (v :: accu)
+ | None -> loop (i + 1) accu
+ end
+ | _ -> loop (i + 1) accu
+ end else loop (i + 1) accu
+ in
+ loop 0 []
+ ;;
+
+ let stats t =
+ let len = Array.length t.table in
+ let lens = Array.map length t.table in
+ Array.sort compare lens;
+ let totlen = Array.fold_left ( + ) 0 lens in
+ (len, count t, totlen, lens.(0), lens.(len/2), lens.(len-1))
+ ;;
+
+end;;
diff --git a/stdlib/weak.mli b/stdlib/weak.mli
new file mode 100644
index 0000000000..a27dea5ce7
--- /dev/null
+++ b/stdlib/weak.mli
@@ -0,0 +1,157 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(** Arrays of weak pointers and hash tables of weak pointers. *)
+
+
+(** {6 Low-level functions} *)
+
+type 'a t
+(** The type of arrays of weak pointers (weak arrays). A weak
+ pointer is a value that the garbage collector may erase whenever
+ the value is not used any more (through normal pointers) by the
+ program. Note that finalisation functions are run after the
+ weak pointers are erased.
+
+ A weak pointer is said to be full if it points to a value,
+ empty if the value was erased by the GC.
+
+ Notes:
+ - Integers are not allocated and cannot be stored in weak arrays.
+ - Weak arrays cannot be marshaled using {!Pervasives.output_value}
+ nor the functions of the {!Marshal} module.
+*)
+
+
+val create : int -> 'a t
+(** [Weak.create n] returns a new weak array of length [n].
+ All the pointers are initially empty. Raise [Invalid_argument]
+ if [n] is negative or greater than {!Sys.max_array_length}[-1].*)
+
+val length : 'a t -> int
+(** [Weak.length ar] returns the length (number of elements) of
+ [ar].*)
+
+val set : 'a t -> int -> 'a option -> unit
+(** [Weak.set ar n (Some el)] sets the [n]th cell of [ar] to be a
+ (full) pointer to [el]; [Weak.set ar n None] sets the [n]th
+ cell of [ar] to empty.
+ Raise [Invalid_argument "Weak.set"] if [n] is not in the range
+ 0 to {!Weak.length}[ a - 1].*)
+
+val get : 'a t -> int -> 'a option
+(** [Weak.get ar n] returns None if the [n]th cell of [ar] is
+ empty, [Some x] (where [x] is the value) if it is full.
+ Raise [Invalid_argument "Weak.get"] if [n] is not in the range
+ 0 to {!Weak.length}[ a - 1].*)
+
+val get_copy : 'a t -> int -> 'a option
+(** [Weak.get_copy ar n] returns None if the [n]th cell of [ar] is
+ empty, [Some x] (where [x] is a (shallow) copy of the value) if
+ it is full.
+ In addition to pitfalls with mutable values, the interesting
+ difference with [get] is that [get_copy] does not prevent
+ the incremental GC from erasing the value in its current cycle
+ ([get] may delay the erasure to the next GC cycle).
+ Raise [Invalid_argument "Weak.get"] if [n] is not in the range
+ 0 to {!Weak.length}[ a - 1].*)
+
+
+val check : 'a t -> int -> bool
+(** [Weak.check ar n] returns [true] if the [n]th cell of [ar] is
+ full, [false] if it is empty. Note that even if [Weak.check ar n]
+ returns [true], a subsequent {!Weak.get}[ ar n] can return [None].*)
+
+val fill : 'a t -> int -> int -> 'a option -> unit
+(** [Weak.fill ar ofs len el] sets to [el] all pointers of [ar] from
+ [ofs] to [ofs + len - 1]. Raise [Invalid_argument "Weak.fill"]
+ if [ofs] and [len] do not designate a valid subarray of [a].*)
+
+val blit : 'a t -> int -> 'a t -> int -> int -> unit
+(** [Weak.blit ar1 off1 ar2 off2 len] copies [len] weak pointers
+ from [ar1] (starting at [off1]) to [ar2] (starting at [off2]).
+ It works correctly even if [ar1] and [ar2] are the same.
+ Raise [Invalid_argument "Weak.blit"] if [off1] and [len] do
+ not designate a valid subarray of [ar1], or if [off2] and [len]
+ do not designate a valid subarray of [ar2].*)
+
+
+(** {6 Weak hash tables} *)
+
+(** A weak hash table is a hashed set of values. Each value may
+ magically disappear from the set when it is not used by the
+ rest of the program any more. This is normally used to share
+ data structures without inducing memory leaks.
+ Weak hash tables are defined on values from a {!Hashtbl.HashedType}
+ module; the [equal] relation and [hash] function are taken from that
+ module. We will say that [v] is an instance of [x] if [equal x v]
+ is [true].
+
+ The [equal] relation must be able to work on a shallow copy of
+ the values and give the same result as with the values themselves.
+ *)
+
+module type S = sig
+ type data
+ (** The type of the elements stored in the table. *)
+ type t
+ (** The type of tables that contain elements of type [data].
+ Note that weak hash tables cannot be marshaled using
+ {!Pervasives.output_value} or the functions of the {!Marshal}
+ module. *)
+ val create : int -> t
+ (** [create n] creates a new empty weak hash table, of initial
+ size [n]. The table will grow as needed. *)
+ val clear : t -> unit
+ (** Remove all elements from the table. *)
+ val merge : t -> data -> data
+ (** [merge t x] returns an instance of [x] found in [t] if any,
+ or else adds [x] to [t] and return [x]. *)
+ val add : t -> data -> unit
+ (** [add t x] adds [x] to [t]. If there is already an instance
+ of [x] in [t], it is unspecified which one will be
+ returned by subsequent calls to [find] and [merge]. *)
+ val remove : t -> data -> unit
+ (** [remove t x] removes from [t] one instance of [x]. Does
+ nothing if there is no instance of [x] in [t]. *)
+ val find : t -> data -> data
+ (** [find t x] returns an instance of [x] found in [t].
+ Raise [Not_found] if there is no such element. *)
+ val find_all : t -> data -> data list
+ (** [find_all t x] returns a list of all the instances of [x]
+ found in [t]. *)
+ val mem : t -> data -> bool
+ (** [mem t x] returns [true] if there is at least one instance
+ of [x] in [t], false otherwise. *)
+ val iter : (data -> unit) -> t -> unit
+ (** [iter f t] calls [f] on each element of [t], in some unspecified
+ order. It is not specified what happens if [f] tries to change
+ [t] itself. *)
+ val fold : (data -> 'a -> 'a) -> t -> 'a -> 'a
+ (** [fold f t init] computes [(f d1 (... (f dN init)))] where
+ [d1 ... dN] are the elements of [t] in some unspecified order.
+ It is not specified what happens if [f] tries to change [t]
+ itself. *)
+ val count : t -> int
+ (** Count the number of elements in the table. [count t] gives the
+ same result as [fold (fun _ n -> n+1) t 0] but does not delay the
+ deallocation of the dead elements. *)
+ val stats : t -> int * int * int * int * int * int
+ (** Return statistics on the table. The numbers are, in order:
+ table length, number of entries, sum of bucket lengths,
+ smallest bucket length, median bucket length, biggest bucket length. *)
+end;;
+(** The output signature of the functor {!Weak.Make}. *)
+
+module Make (H : Hashtbl.HashedType) : S with type data = H.t;;
+(** Functor building an implementation of the weak hash table structure. *)
diff --git a/testsuite/.ignore b/testsuite/.ignore
new file mode 100644
index 0000000000..a333a8b0a0
--- /dev/null
+++ b/testsuite/.ignore
@@ -0,0 +1 @@
+_log
diff --git a/testsuite/Makefile b/testsuite/Makefile
new file mode 100644
index 0000000000..668f0833ae
--- /dev/null
+++ b/testsuite/Makefile
@@ -0,0 +1,104 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR := $(shell pwd)
+NO_PRINT=`$(MAKE) empty --no-print-directory >/dev/null 2>&1 \
+ && echo --no-print-directory`
+
+FIND=find
+include ../config/Makefile
+
+.PHONY: default
+default:
+ @echo "Available targets:"
+ @echo " all launch all tests"
+ @echo " list FILE=f launch the tests listed in f (one per line)"
+ @echo " one DIR=p launch the tests located in path p"
+ @echo " promote DIR=p promote the reference files for the tests in p"
+ @echo " lib build library modules"
+ @echo " clean delete generated files"
+ @echo " report print the report for the last execution"
+
+.PHONY: all
+all: lib
+ @for dir in tests/*; do \
+ $(MAKE) $(NO_PRINT) exec-one DIR=$$dir; \
+ done 2>&1 | tee _log
+ @$(MAKE) report
+
+.PHONY: list
+list: lib
+ @if [ -z "$(FILE)" ]; \
+ then echo "No value set for variable 'FILE'."; \
+ exit 1; \
+ fi
+ @while read LINE; do \
+ $(MAKE) $(NO_PRINT) exec-one DIR=$$LINE; \
+ done <$(FILE) 2>&1 | tee _log
+ @$(MAKE) report
+
+.PHONY: one
+one: lib
+ @if [ -z "$(DIR)" ]; then \
+ echo "No value set for variable 'DIR'."; \
+ exit 1; \
+ fi
+ @if [ ! -d $(DIR) ]; then \
+ echo "Directory '$(DIR)' does not exist."; \
+ exit 1; \
+ fi
+ @$(MAKE) $(NO_PRINT) exec-one DIR=$(DIR)
+
+.PHONY: exec-one
+exec-one:
+ @if [ ! -f $(DIR)/Makefile ]; then \
+ for dir in $(DIR)/*; do \
+ if [ -d $$dir ]; then \
+ $(MAKE) exec-one DIR=$$dir; \
+ fi; \
+ done; \
+ else \
+ echo "Running tests from '$$DIR' ..."; \
+ cd $(DIR) && \
+ $(MAKE) TERM=dumb BASEDIR=$(BASEDIR) || echo '=> unexpected error'; \
+ fi
+
+.PHONY: promote
+promote:
+ @if [ -z "$(DIR)" ]; then \
+ echo "No value set for variable 'DIR'."; \
+ exit 1; \
+ fi
+ @if [ ! -d $(DIR) ]; then \
+ echo "Directory '$(DIR)' does not exist."; \
+ exit 1; \
+ fi
+ @cd $(DIR) && $(MAKE) TERM=dumb BASEDIR=$(BASEDIR) promote
+
+.PHONY: lib
+lib:
+ @cd lib && $(MAKE) -s BASEDIR=$(BASEDIR)
+
+.PHONY: clean
+clean:
+ @cd lib && $(MAKE) BASEDIR=$(BASEDIR) clean
+ @for file in `$(FIND) interactive tests -name Makefile`; do \
+ (cd `dirname $$file` && $(MAKE) BASEDIR=$(BASEDIR) clean); \
+ done
+
+.PHONY: report
+report:
+ @if [ ! -f _log ]; then echo "No '_log' file."; exit 1; fi
+ @awk -f makefiles/summarize.awk <_log
+
+.PHONY: empty
+empty:
diff --git a/testsuite/interactive/lib-gc/Makefile b/testsuite/interactive/lib-gc/Makefile
new file mode 100644
index 0000000000..1e4281fb87
--- /dev/null
+++ b/testsuite/interactive/lib-gc/Makefile
@@ -0,0 +1,24 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+default:
+ @$(OCAMLC) -o program.byte alloc.ml
+ @./program.byte
+ @$(OCAMLOPT) -o program.native alloc.ml
+ @./program.native
+
+clean: defaultclean
+ @rm -fr program.*
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/interactive/lib-gc/alloc.ml b/testsuite/interactive/lib-gc/alloc.ml
new file mode 100644
index 0000000000..aadecab28e
--- /dev/null
+++ b/testsuite/interactive/lib-gc/alloc.ml
@@ -0,0 +1,48 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Random allocation test *)
+
+(*
+ Allocate arrays of strings, of random sizes in [0..1000[, and put them
+ into an array of 32768. Replace a randomly-selected array with a new
+ random-length array. Reiterate ad infinitum.
+*)
+
+let l = 32768;;
+let m = 1000;;
+
+let ar = Array.make l "";;
+
+Random.init 1234;;
+
+let compact_flag = ref false;;
+
+let main () =
+ while true do
+ for i = 1 to 100000 do
+ ar.(Random.int l) <- String.create (Random.int m);
+ done;
+ if !compact_flag then Gc.compact () else Gc.full_major ();
+ print_newline ();
+ Gc.print_stat stdout;
+ flush stdout;
+ done
+;;
+
+let argspecs = [
+ "-c", Arg.Set compact_flag, "do heap compactions";
+];;
+
+Arg.parse argspecs (fun _ -> ()) "Usage: alloc [-c]";;
+
+main ();;
diff --git a/testsuite/interactive/lib-graph-2/Makefile b/testsuite/interactive/lib-graph-2/Makefile
new file mode 100644
index 0000000000..836fd90bff
--- /dev/null
+++ b/testsuite/interactive/lib-graph-2/Makefile
@@ -0,0 +1,20 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=graph_test
+#ADD_COMPFLAGS=
+LIBRARIES=graphics
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/interactive/lib-graph-2/graph_test.ml b/testsuite/interactive/lib-graph-2/graph_test.ml
new file mode 100644
index 0000000000..6c9fd49ac6
--- /dev/null
+++ b/testsuite/interactive/lib-graph-2/graph_test.ml
@@ -0,0 +1,287 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* graph_test.ml : tests various drawing and filling primitives of the
+ Graphics library. *)
+
+(* To run this example just load this file into a suitable toplevel.
+ Alternatively execute
+ ocamlc graphics.cma graph_test.ml *)
+
+open Graphics;;
+
+auto_synchronize false;;
+display_mode false;;
+remember_mode true;;
+
+let sz = 450;;
+
+open_graph (Printf.sprintf " %ix%i" sz sz);;
+
+(* To be defined for older versions of OCaml
+ Lineto, moveto and draw_rect.
+
+let rlineto x y =
+ let xc, yc = current_point () in
+ lineto (x + xc) (y + yc);;
+
+let rmoveto x y =
+ let xc, yc = current_point () in
+ moveto (x + xc) (y + yc);;
+
+let draw_rect x y w h =
+ let x0, y0 = current_point () in
+ moveto x y;
+ rlineto w 0;
+ rlineto 0 h;
+ rlineto (- w) 0;
+ rlineto 0 (-h);
+ moveto x0 y0;;
+*)
+
+(* A set of points. *)
+
+set_color foreground;;
+
+let dashes y =
+ for i = 1 to 100 do
+ plot y (2 * i);
+ plot y (3 * i);
+ plot y (4 * i);
+ done;;
+
+dashes 3;;
+
+set_line_width 20;;
+dashes (sz - 20);;
+
+(* Drawing chars *)
+
+draw_char 'C';
+draw_char 'a';
+draw_char 'm';
+draw_char 'l';;
+
+(* More and more red enlarging squares *)
+moveto 10 10;;
+set_line_width 5;;
+
+let carre c =
+ rlineto 0 c;
+ rlineto c 0;
+ rlineto 0 (- c);
+ rlineto (- c) 0;;
+
+for i = 1 to 10 do
+ moveto (10 * i) (10 * i);
+ set_color (rgb (155 + 10 * i) 0 0);
+ carre (10 * i)
+done;;
+
+(* Blue squares in arithmetic progression *)
+moveto 10 210;;
+set_color blue;;
+set_line_width 1;;
+
+for i = 1 to 10 do
+ carre (10 * i)
+done;;
+
+(* Tiny circles filled or not *)
+rmoveto 0 120;;
+(* Must not change the current point *)
+fill_circle 20 190 10;;
+set_color green;;
+rlineto 0 10;;
+rmoveto 50 10;;
+let x, y = current_point () in
+(* Must not change the current point *)
+draw_circle x y 20;;
+set_color black;;
+rlineto 0 20;;
+
+(* Cyan rectangles as a kind of graphical representation *)
+set_color cyan;;
+
+let lw = 15;;
+set_line_width lw;;
+let go_caption l = moveto 210 (130 - lw + l);;
+let go_legend () = go_caption (- 3 * lw);;
+
+go_caption 0;;
+fill_rect 210 130 5 10;;
+fill_rect 220 130 10 20;;
+fill_rect 235 130 15 40;;
+fill_rect 255 130 20 80;;
+fill_rect 280 130 25 160;;
+(* A green rectangle below the graph. *)
+set_color green;;
+rlineto 50 0;;
+
+(* A black frame for each of our rectangles *)
+set_color black;;
+set_line_width (lw / 4);;
+
+draw_rect 210 130 5 10;;
+draw_rect 220 130 10 20;;
+draw_rect 235 130 15 40;;
+draw_rect 255 130 20 80;;
+draw_rect 280 130 25 160;;
+
+(* A black rectangle after the green one, below the graph. *)
+set_line_width lw;;
+rlineto 50 0;;
+
+(* Write a text in yellow on a blue background. *)
+(* x = 210, y = 70 *)
+go_legend ();;
+set_text_size 10;;
+set_color (rgb 150 100 250);;
+let x,y = current_point () in
+fill_rect x (y - 5) (8 * 20) 25;;
+set_color yellow;;
+go_legend ();;
+draw_string "Graphics (OCaml)";;
+
+(* Pie parts in different colors. *)
+let draw_green_string s = set_color green; draw_string s;;
+let draw_red_string s = set_color red; draw_string s;;
+
+moveto 120 210;;
+set_color red;;
+fill_arc 150 260 25 25 60 300;
+draw_green_string "A ";
+draw_red_string "red";
+draw_green_string " pie.";
+
+set_text_size 5;
+moveto 180 240;
+draw_red_string "A "; draw_green_string "green"; draw_red_string " slice.";;
+set_color green;
+fill_arc 200 260 25 25 0 60;
+set_color black;
+set_line_width 2;
+draw_arc 200 260 27 27 0 60;;
+
+(* Should do nothing since this is a line *)
+set_color red;;
+fill_poly [| (40, 10); (150, 70); (150, 10); (40, 10) |];;
+set_color blue;;
+
+(* Drawing polygones. *)
+(* Redefining the draw_poly primitive for the usual library. *)
+let draw_poly v =
+ let l = Array.length v in
+ if l > 0 then begin
+ let x0, y0 = current_point () in
+ let p0 = v.(0) in
+ let x, y = p0 in moveto x y;
+ for i = 1 to l - 1 do
+ let x, y = v.(i) in lineto x y
+ done;
+ lineto x y;
+ moveto x0 y0
+ end;;
+
+draw_poly [| (150, 10); (150, 70); (260, 10); (150, 10) |];;
+
+(* Filling polygones. *)
+(* Two equilateral triangles, one red and one blue, and their inside
+ filled in black. *)
+let equi x y l =
+ [| (x - l / 2, y);
+ (x, y + int_of_float (float_of_int l *. (sqrt 3.0 /. 2.0)));
+ (x + l / 2, y) |];;
+
+set_color black;;
+fill_poly (Array.append (equi 300 20 40) (equi 300 44 (- 40)));;
+
+set_line_width 1;;
+set_color cyan;;
+draw_poly (equi 300 20 40);;
+set_color red;;
+draw_poly (equi 300 44 (- 40));;
+
+(* Drawing and filling ellipses. *)
+let x, y = current_point () in
+rlineto 10 10; moveto x y;
+
+moveto 395 100;;
+
+let x, y = current_point () in
+fill_ellipse x y 25 15;;
+
+set_color (rgb 0xFF 0x00 0xFF);;
+rmoveto 0 (- 50);;
+
+let x, y = current_point () in
+fill_ellipse x y 15 30;;
+
+rmoveto (- 45) 0;;
+let x, y = current_point () in
+draw_ellipse x y 25 10;;
+
+(* Drawing and filling arcs. *)
+
+let draw_arc_ellipse x y r1 r2 =
+ set_color green;
+ draw_arc x y r1 r2 60 120;
+ set_color black;
+ draw_arc x y r1 r2 120 420;;
+
+set_line_width 3;;
+
+let draw_arc_ellipses x y r1 r2 =
+ let step = 5 in
+ for i = 0 to (r1 - step) / (2 * step) do
+ for j = 0 to (r2 - step) / (2 * step) do
+ draw_arc_ellipse x y (3 * i * step) (3 * j * step)
+ done
+ done;;
+
+draw_arc_ellipses 20 128 15 50;;
+
+let fill_arc_ellipse x y r1 r2 c1 c2 =
+ set_color c1;
+ fill_arc x y r1 r2 60 120;
+ set_color c2;
+ fill_arc x y r1 r2 120 420;;
+
+let fill_arc_ellipses x y r1 r2 =
+ let step = 3 in
+ let c1 = ref black
+ and c2 = ref yellow in
+ let exchange r1 r2 = let tmp = !r1 in r1 := !r2; r2 := tmp in
+ for i = r1 / (2 * step) downto 10 do
+ for j = r2 / (2 * step) downto 30 do
+ exchange c1 c2;
+ fill_arc_ellipse x y (3 * i) (3 * j) !c1 !c2
+ done
+ done;;
+
+fill_arc_ellipses 400 240 150 200;;
+
+
+synchronize ();;
+
+(* transparent color drawing *)
+set_color transp;;
+draw_circle 400 240 50;;
+draw_circle 400 240 40;;
+draw_circle 400 240 30;;
+(* try to go back a normal color *)
+set_color red;;
+draw_circle 400 240 20;;
+
+synchronize ();;
+
+ignore (wait_next_event [Key_pressed])
diff --git a/testsuite/interactive/lib-graph-2/graph_test.reference b/testsuite/interactive/lib-graph-2/graph_test.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/interactive/lib-graph-2/graph_test.reference
diff --git a/testsuite/interactive/lib-graph-3/Makefile b/testsuite/interactive/lib-graph-3/Makefile
new file mode 100644
index 0000000000..dd47b82d3d
--- /dev/null
+++ b/testsuite/interactive/lib-graph-3/Makefile
@@ -0,0 +1,20 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=sorts
+ADD_COMPFLAGS=-thread
+LIBRARIES=unix threads graphics
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/interactive/lib-graph-3/sorts.ml b/testsuite/interactive/lib-graph-3/sorts.ml
new file mode 100644
index 0000000000..6e00d25663
--- /dev/null
+++ b/testsuite/interactive/lib-graph-3/sorts.ml
@@ -0,0 +1,240 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Animation of sorting algorithms. *)
+
+open Graphics
+
+(* Information on a given sorting process *)
+
+type graphic_context =
+ { array: int array; (* Data to sort *)
+ x0: int; (* X coordinate, lower left corner *)
+ y0: int; (* Y coordinate, lower left corner *)
+ width: int; (* Width in pixels *)
+ height: int; (* Height in pixels *)
+ nelts: int; (* Number of elements in the array *)
+ maxval: int; (* Max val in the array + 1 *)
+ rad: int (* Dimension of the rectangles *)
+ }
+
+(* Array assignment and exchange with screen update *)
+
+let screen_mutex = Mutex.create()
+
+let draw gc i v =
+ fill_rect (gc.x0 + (gc.width * i) / gc.nelts)
+ (gc.y0 + (gc.height * v) / gc.maxval)
+ gc.rad gc.rad
+
+let assign gc i v =
+ Mutex.lock screen_mutex;
+ set_color background; draw gc i gc.array.(i);
+ set_color foreground; draw gc i v;
+ gc.array.(i) <- v;
+ Mutex.unlock screen_mutex
+
+let exchange gc i j =
+ let val_i = gc.array.(i) in
+ assign gc i gc.array.(j);
+ assign gc j val_i
+
+(* Construction of a graphic context *)
+
+let initialize name array maxval x y w h =
+ let (_, label_height) = text_size name in
+ let rad = (w - 2) / (Array.length array) - 1 in
+ let gc =
+ { array = Array.copy array;
+ x0 = x + 1; (* Leave one pixel left for Y axis *)
+ y0 = y + 1; (* Leave one pixel below for X axis *)
+ width = w - 2; (* 1 pixel left, 1 pixel right *)
+ height = h - 1 - label_height - rad;
+ nelts = Array.length array;
+ maxval = maxval;
+ rad = rad } in
+ moveto (gc.x0 - 1) (gc.y0 + gc.height);
+ lineto (gc.x0 - 1) (gc.y0 - 1);
+ lineto (gc.x0 + gc.width) (gc.y0 - 1);
+ moveto (gc.x0 - 1) (gc.y0 + gc.height);
+ draw_string name;
+ for i = 0 to Array.length array - 1 do
+ draw gc i array.(i)
+ done;
+ gc
+
+(* Main animation function *)
+
+let display functs nelts maxval =
+ let a = Array.make nelts 0 in
+ for i = 0 to nelts - 1 do
+ a.(i) <- Random.int maxval
+ done;
+ let num_finished = ref 0 in
+ let lock_finished = Mutex.create() in
+ let cond_finished = Condition.create() in
+ for i = 0 to Array.length functs - 1 do
+ let (name, funct, x, y, w, h) = functs.(i) in
+ let gc = initialize name a maxval x y w h in
+ Thread.create
+ (fun () ->
+ funct gc;
+ Mutex.lock lock_finished;
+ incr num_finished;
+ Mutex.unlock lock_finished;
+ Condition.signal cond_finished)
+ ()
+ done;
+ Mutex.lock lock_finished;
+ while !num_finished < Array.length functs do
+ Condition.wait cond_finished lock_finished
+ done;
+ Mutex.unlock lock_finished;
+ read_key()
+
+(*****
+ let delay = ref 0 in
+ try
+ while true do
+ let gc = Queue.take q in
+ begin match gc.action with
+ Finished -> ()
+ | Pause f ->
+ gc.action <- f ();
+ for i = 0 to !delay do () done;
+ Queue.add gc q
+ end;
+ if key_pressed() then begin
+ match read_key() with
+ 'q'|'Q' ->
+ raise Exit
+ | '0'..'9' as c ->
+ delay := (Char.code c - 48) * 500
+ | _ ->
+ ()
+ end
+ done
+ with Exit -> ()
+ | Queue.Empty -> read_key(); ()
+*****)
+
+(* The sorting functions. *)
+
+(* Bubble sort *)
+
+let bubble_sort gc =
+ let ordered = ref false in
+ while not !ordered do
+ ordered := true;
+ for i = 0 to Array.length gc.array - 2 do
+ if gc.array.(i+1) < gc.array.(i) then begin
+ exchange gc i (i+1);
+ ordered := false
+ end
+ done
+ done
+
+(* Insertion sort *)
+
+let insertion_sort gc =
+ for i = 1 to Array.length gc.array - 1 do
+ let val_i = gc.array.(i) in
+ let j = ref (i - 1) in
+ while !j >= 0 && val_i < gc.array.(!j) do
+ assign gc (!j + 1) gc.array.(!j);
+ decr j
+ done;
+ assign gc (!j + 1) val_i
+ done
+
+(* Selection sort *)
+
+let selection_sort gc =
+ for i = 0 to Array.length gc.array - 1 do
+ let min = ref i in
+ for j = i+1 to Array.length gc.array - 1 do
+ if gc.array.(j) < gc.array.(!min) then min := j
+ done;
+ exchange gc i !min
+ done
+
+(* Quick sort *)
+
+let quick_sort gc =
+ let rec quick lo hi =
+ if lo < hi then begin
+ let i = ref lo in
+ let j = ref hi in
+ let pivot = gc.array.(hi) in
+ while !i < !j do
+ while !i < hi && gc.array.(!i) <= pivot do incr i done;
+ while !j > lo && gc.array.(!j) >= pivot do decr j done;
+ if !i < !j then exchange gc !i !j
+ done;
+ exchange gc !i hi;
+ quick lo (!i-1);
+ quick (!i+1) hi
+ end
+ in quick 0 (Array.length gc.array - 1)
+
+(* Merge sort *)
+
+let merge_sort gc =
+ let rec merge i l1 l2 =
+ match (l1, l2) with
+ ([], []) ->
+ ()
+ | ([], v2::r2) ->
+ assign gc i v2; merge (i+1) l1 r2
+ | (v1::r1, []) ->
+ assign gc i v1; merge (i+1) r1 l2
+ | (v1::r1, v2::r2) ->
+ if v1 < v2
+ then begin assign gc i v1; merge (i+1) r1 l2 end
+ else begin assign gc i v2; merge (i+1) l1 r2 end in
+ let rec msort start len =
+ if len < 2 then () else begin
+ let m = len / 2 in
+ msort start m;
+ msort (start+m) (len-m);
+ merge start
+ (Array.to_list (Array.sub gc.array start m))
+ (Array.to_list (Array.sub gc.array (start+m) (len-m)))
+ end in
+ msort 0 (Array.length gc.array)
+
+(* Main program *)
+
+let animate() =
+ open_graph "";
+ moveto 0 0; draw_string "Press a key to start...";
+ let seed = ref 0 in
+ while not (key_pressed()) do incr seed done;
+ read_key();
+ Random.init !seed;
+ clear_graph();
+ let prompt = "0: fastest ... 9: slowest, press 'q' to quit" in
+ moveto 0 0; draw_string prompt;
+ let (_, h) = text_size prompt in
+ let sx = size_x() / 2 and sy = (size_y() - h) / 3 in
+ display [| "Bubble", bubble_sort, 0, h, sx, sy;
+ "Insertion", insertion_sort, 0, h+sy, sx, sy;
+ "Selection", selection_sort, 0, h+2*sy, sx, sy;
+ "Quicksort", quick_sort, sx, h, sx, sy;
+ (** "Heapsort", heap_sort, sx, h+sy, sx, sy; **)
+ "Mergesort", merge_sort, sx, h+2*sy, sx, sy |]
+ 100 1000;
+ close_graph()
+
+let _ = if !Sys.interactive then () else begin animate(); exit 0 end
+
+;;
diff --git a/testsuite/interactive/lib-graph-3/sorts.reference b/testsuite/interactive/lib-graph-3/sorts.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/interactive/lib-graph-3/sorts.reference
diff --git a/testsuite/interactive/lib-graph/Makefile b/testsuite/interactive/lib-graph/Makefile
new file mode 100644
index 0000000000..18e90ac079
--- /dev/null
+++ b/testsuite/interactive/lib-graph/Makefile
@@ -0,0 +1,20 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=graph_example
+#ADD_COMPFLAGS=
+LIBRARIES=graphics
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/interactive/lib-graph/graph_example.ml b/testsuite/interactive/lib-graph/graph_example.ml
new file mode 100644
index 0000000000..09f4e4cabf
--- /dev/null
+++ b/testsuite/interactive/lib-graph/graph_example.ml
@@ -0,0 +1,143 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* To run this example:
+ ********************
+ 1. Select all the text in this window.
+ 2. Drag it to the toplevel window.
+ 3. Watch the colors.
+ 4. Drag the mouse over the graphics window and click here and there.
+ 5. Type any key to the graphics window to stop the program.
+*)
+
+open Graphics;;
+open_graph " 480x270";;
+
+let xr = size_x () / 2 - 30
+and yr = size_y () / 2 - 26
+and xg = size_x () / 2 + 30
+and yg = size_y () / 2 - 26
+and xb = size_x () / 2
+and yb = size_y () / 2 + 26
+;;
+
+let point x y =
+ let dr = (x-xr)*(x-xr) + (y-yr)*(y-yr)
+ and dg = (x-xg)*(x-xg) + (y-yg)*(y-yg)
+ and db = (x-xb)*(x-xb) + (y-yb)*(y-yb)
+ in
+ if dr > dg && dr > db then set_color (rgb 255 (255*dg/dr) (255*db/dr))
+ else if dg > db then set_color (rgb (255*dr/dg) 255 (255*db/dg))
+ else set_color (rgb (255*dr/db) (255*dg/db) 255);
+ fill_rect x y 2 2;
+;;
+
+for y = (size_y () - 1) / 2 downto 0 do
+ for x = 0 to (size_x () - 1) / 2 do
+ point (2*x) (2*y);
+ done
+done
+;;
+
+let n = 0x000000
+and w = 0xFFFFFF
+and b = 0xFFCC99
+and y = 0xFFFF00
+and o = 0xCC9966
+and v = 0x00BB00
+and g = 0x888888
+and c = 0xDDDDDD
+and t = transp
+;;
+
+let caml = make_image [|
+ [|t;t;t;t;t;t;t;t;t;t;t;n;n;n;n;n;n;t;t;t;t;t;t;t;t;t;t;t;t;t;t;t;|];
+ [|t;t;t;t;t;t;t;t;t;t;n;n;n;n;n;n;n;n;n;t;t;t;t;t;t;t;t;t;t;t;t;t;|];
+ [|t;t;t;t;t;t;t;t;n;n;n;n;n;n;n;n;n;n;n;n;t;t;t;t;t;t;t;t;t;t;t;t;|];
+ [|n;n;n;n;n;n;t;n;n;n;n;n;b;b;b;b;b;b;b;n;n;t;t;t;t;t;n;n;n;n;n;t;|];
+ [|n;o;o;o;o;o;n;n;n;n;b;b;b;b;b;b;b;b;b;b;b;n;n;n;n;n;n;n;n;n;n;t;|];
+ [|n;o;o;o;o;o;o;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;t;|];
+ [|n;o;o;o;o;o;o;o;n;n;n;g;g;g;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;t;t;|];
+ [|n;n;o;o;o;o;o;o;o;n;n;n;c;c;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;t;t;|];
+ [|t;n;n;o;o;o;o;o;o;o;n;n;n;c;n;n;n;n;n;n;n;b;b;n;n;n;n;n;n;t;t;t;|];
+ [|t;t;n;n;n;o;o;o;o;o;o;n;n;n;n;n;n;n;n;n;b;b;b;b;n;n;n;n;t;t;t;t;|];
+ [|t;t;t;t;n;n;o;o;o;o;o;o;n;n;n;n;n;n;n;n;b;b;b;b;b;b;n;n;t;t;t;t;|];
+ [|t;t;t;t;t;n;n;o;o;o;o;o;o;n;n;n;n;n;n;o;o;b;b;b;b;b;b;n;n;t;t;t;|];
+ [|t;t;t;t;t;n;n;o;o;o;o;o;o;b;b;b;b;b;n;n;o;o;b;b;b;b;b;b;n;n;t;t;|];
+ [|t;t;t;t;n;n;n;o;o;o;o;o;b;b;b;b;b;b;b;n;n;o;o;b;b;b;b;b;b;n;n;t;|];
+ [|t;t;t;t;n;n;n;o;o;o;o;b;b;b;b;b;b;b;b;b;n;n;o;o;b;b;b;b;b;b;n;n;|];
+ [|t;t;t;t;n;n;n;o;o;o;o;b;b;b;b;b;n;n;b;b;b;n;n;o;o;b;b;b;b;b;n;n;|];
+ [|t;t;t;t;n;n;n;o;o;o;o;b;b;b;b;b;n;n;b;b;b;b;n;n;o;o;b;o;b;b;n;n;|];
+ [|t;t;t;t;n;n;n;o;o;o;o;b;b;b;b;b;n;n;b;b;b;b;b;n;n;o;o;o;o;o;n;n;|];
+ [|t;t;t;t;n;n;n;o;o;o;o;b;b;b;b;b;n;n;b;b;b;b;b;b;n;n;o;o;o;o;n;n;|];
+ [|t;t;t;t;n;n;n;o;o;o;o;o;b;b;b;b;n;n;b;b;b;b;b;b;b;n;n;o;o;n;n;n;|];
+ [|t;t;t;t;n;n;n;n;o;o;o;o;o;b;b;b;n;n;n;b;b;b;b;b;b;b;n;n;o;n;b;n;|];
+ [|t;t;t;t;t;n;n;n;o;o;o;o;o;o;b;b;n;n;n;b;b;b;b;b;b;b;b;n;n;n;b;n;|];
+ [|t;t;t;t;t;t;n;n;o;o;o;o;o;o;o;y;v;y;n;b;b;b;b;b;b;b;b;n;n;b;b;n;|];
+ [|t;t;t;t;t;t;t;n;o;o;o;o;o;v;y;o;o;n;n;n;b;b;b;b;b;b;b;n;n;b;b;n;|];
+ [|t;t;t;t;t;t;t;n;o;o;o;y;v;o;o;o;o;n;n;n;n;b;b;b;b;b;b;n;n;b;b;n;|];
+ [|t;t;t;t;t;t;n;n;o;v;y;o;y;o;o;o;o;o;o;n;n;n;b;b;b;b;b;n;n;b;b;n;|];
+ [|t;t;t;t;t;t;n;o;y;y;o;o;v;o;o;o;o;o;o;o;n;n;n;b;b;b;n;n;n;b;n;t;|];
+ [|t;t;t;t;t;n;n;v;o;v;o;o;o;o;o;o;o;o;o;o;o;n;n;n;b;n;n;n;n;b;n;t;|];
+ [|t;t;t;t;t;n;v;o;o;v;o;o;o;o;o;o;o;o;o;o;o;o;n;n;n;n;n;n;n;n;t;t;|];
+ [|t;t;t;t;n;n;o;o;o;o;o;o;o;o;o;o;o;o;o;o;o;n;n;n;n;n;n;t;t;t;t;t;|];
+ [|t;t;t;t;n;o;o;o;o;o;o;o;o;o;o;o;o;o;o;o;n;n;t;t;t;t;t;t;t;t;t;t;|];
+ [|t;t;t;t;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;n;t;t;t;t;t;t;t;t;t;t;t;|];
+|];;
+
+(*
+let x = ref 0 and y = ref 0;;
+let bg = get_image !x !y 32 32;;
+while true do
+ let st = wait_next_event [Mouse_motion; Button_down] in
+ if not st.button then draw_image bg !x !y;
+ x := st.mouse_x;
+ y := st.mouse_y;
+ blit_image bg !x !y;
+ draw_image caml !x !y;
+done;;
+*)
+set_color (rgb 0 0 0);
+remember_mode false;
+try while true do
+ let st = wait_next_event [Mouse_motion; Button_down; Key_pressed] in
+ synchronize ();
+ if st.keypressed then raise Exit;
+ if st.button then begin
+ remember_mode true;
+ draw_image caml st.mouse_x st.mouse_y;
+ remember_mode false;
+ end;
+ let x = st.mouse_x + 16 and y = st.mouse_y + 16 in
+
+ moveto 0 y;
+ lineto (x - 25) y;
+ moveto 10000 y;
+ lineto (x + 25) y;
+
+ moveto x 0;
+ lineto x (y - 25);
+ moveto x 10000;
+ lineto x (y + 25);
+
+ draw_image caml st.mouse_x st.mouse_y;
+done with Exit -> ()
+;;
+
+(* To run this example:
+ ********************
+ 1. Select all the text in this window.
+ 2. Drag it to the toplevel window.
+ 3. Watch the colors.
+ 4. Drag the mouse over the graphics window and click here and there.
+ 5. Type any key to the graphics window to stop the program.
+*)
diff --git a/testsuite/interactive/lib-graph/graph_example.reference b/testsuite/interactive/lib-graph/graph_example.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/interactive/lib-graph/graph_example.reference
diff --git a/testsuite/interactive/lib-signals/Makefile b/testsuite/interactive/lib-signals/Makefile
new file mode 100644
index 0000000000..2751a8b182
--- /dev/null
+++ b/testsuite/interactive/lib-signals/Makefile
@@ -0,0 +1,24 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+default:
+ @$(OCAMLC) -o program.byte signals.ml
+ @./program.byte
+ @$(OCAMLOPT) -o program.native signals.ml
+ @./program.native
+
+clean: defaultclean
+ @rm -fr program.*
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/interactive/lib-signals/signals.ml b/testsuite/interactive/lib-signals/signals.ml
new file mode 100644
index 0000000000..c60f59c625
--- /dev/null
+++ b/testsuite/interactive/lib-signals/signals.ml
@@ -0,0 +1,44 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec tak (x, y, z) =
+ if x > y then tak(tak (x-1, y, z), tak (y-1, z, x), tak (z-1, x, y))
+ else z
+
+let break_handler _ =
+ print_string "Thank you for pressing ctrl-C."; print_newline();
+ print_string "Allocating a bit..."; flush stdout;
+ ignore (tak(18,12,6)); print_string "done."; print_newline()
+
+let stop_handler _ =
+ print_string "Thank you for pressing ctrl-Z."; print_newline();
+ print_string "Now raising an exception..."; print_newline();
+ raise Exit
+
+let _ =
+ ignore (Sys.signal Sys.sigint (Sys.Signal_handle break_handler));
+ ignore (Sys.signal Sys.sigtstp (Sys.Signal_handle stop_handler));
+ begin try
+ print_string "Computing like crazy..."; print_newline();
+ for i = 1 to 1000 do ignore (tak(18,12,6)) done;
+ print_string "Reading on input..."; print_newline();
+ for i = 1 to 5 do
+ try
+ let s = read_line () in
+ print_string ">> "; print_string s; print_newline()
+ with Exit ->
+ print_string "Got Exit, continuing."; print_newline()
+ done
+ with Exit ->
+ print_string "Got Exit, exiting."; print_newline()
+ end;
+ exit 0
diff --git a/testsuite/lib/Makefile b/testsuite/lib/Makefile
new file mode 100644
index 0000000000..3c0ad6a699
--- /dev/null
+++ b/testsuite/lib/Makefile
@@ -0,0 +1,28 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+.PHONY: compile
+compile: compile-targets
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+
+include ../makefiles/Makefile.common
+
+.PHONY: compile-targets
+compile-targets: testing.cmi testing.cmo
+ @if $(BYTECODE_ONLY); then : ; else \
+ $(MAKE) testing.cmx; \
+ fi
diff --git a/testsuite/lib/empty b/testsuite/lib/empty
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/lib/empty
diff --git a/testsuite/lib/testing.ml b/testsuite/lib/testing.ml
new file mode 100644
index 0000000000..0791fa7ecd
--- /dev/null
+++ b/testsuite/lib/testing.ml
@@ -0,0 +1,93 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2006 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Testing auxilliaries. *)
+
+open Scanf;;
+
+let all_tests_ok = ref true;;
+
+let finish () =
+ match !all_tests_ok with
+ | true ->
+ print_endline "\nAll tests succeeded."
+ | _ ->
+ print_endline "\n\n********* Test suite failed. ***********\n";;
+
+at_exit finish;;
+
+let test_num = ref (-1);;
+
+let print_test_number () =
+ print_string " "; print_int !test_num; flush stdout;;
+
+let next_test () =
+ incr test_num;
+ print_test_number ();;
+
+let print_test_fail () =
+ all_tests_ok := false;
+ print_string
+ (Printf.sprintf "\n********* Test number %i failed ***********\n"
+ !test_num);;
+
+let print_failure_test_fail () =
+ all_tests_ok := false;
+ print_string
+ (Printf.sprintf
+ "\n********* Failure Test number %i incorrectly failed ***********\n"
+ !test_num);;
+
+let print_failure_test_succeed () =
+ all_tests_ok := false;
+ print_string
+ (Printf.sprintf
+ "\n********* Failure Test number %i failed to fail ***********\n"
+ !test_num);;
+
+let test b =
+ next_test ();
+ if not b then print_test_fail ();;
+
+(* Applies f to x and checks that the evaluation indeed
+ raises an exception that verifies the predicate [pred]. *)
+let test_raises_exc_p pred f x =
+ next_test ();
+ try
+ ignore (f x);
+ print_failure_test_succeed ();
+ false
+ with
+ | x ->
+ pred x || (print_failure_test_fail (); false);;
+
+(* Applies f to x and checks that the evaluation indeed
+ raises some exception. *)
+let test_raises_some_exc f = test_raises_exc_p (fun _ -> true) f;;
+let test_raises_this_exc exc = test_raises_exc_p (fun x -> x = exc);;
+
+(* Applies f to x and checks that the evaluation indeed
+ raises exception Failure s. *)
+
+let test_raises_this_failure s f x =
+ test_raises_exc_p (fun x -> x = Failure s) f x;;
+
+(* Applies f to x and checks that the evaluation indeed
+ raises the exception Failure. *)
+let test_raises_some_failure f x =
+ test_raises_exc_p (function Failure _ -> true | _ -> false) f x;;
+
+let failure_test f x s = test_raises_this_failure s f x;;
+let any_failure_test = test_raises_some_failure;;
+
+let scan_failure_test f x =
+ test_raises_exc_p (function Scan_failure _ -> true | _ -> false) f x;;
diff --git a/testsuite/lib/testing.mli b/testsuite/lib/testing.mli
new file mode 100644
index 0000000000..68440f729f
--- /dev/null
+++ b/testsuite/lib/testing.mli
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2006 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Testing auxilliaries. *)
+
+val test : bool -> unit;;
+(** [test e] tests that [e] evaluates to [true]. *)
+val failure_test : ('a -> 'b) -> 'a -> string -> bool;;
+(** [failure_test f x s] tests that [f x] raises the exception [Failure s]. *)
+
+val test_raises_some_exc : ('a -> 'b) -> 'a -> bool;;
+(** [test_raises_some_exc f x] tests that [f x] raises an exception. *)
+
+val test_raises_this_exc : exn -> ('a -> 'b) -> 'a -> bool;;
+(** [test_raises_this_exc exc f x] tests that [f x]
+ raises the exception [exc]. *)
+
+val test_raises_exc_p : (exn -> bool) -> ('a -> 'b) -> 'a -> bool;;
+(** [test_raises_exc_p p f x] tests that [f x] raises an exception that
+ verifies predicate [p]. *)
+
+val scan_failure_test : ('a -> 'b) -> 'a -> bool;;
+(** [scan_failure_test f x] tests that [f x] raises [Scanf.Scan_failure]. *)
diff --git a/testsuite/makefiles/Makefile.common b/testsuite/makefiles/Makefile.common
new file mode 100644
index 0000000000..3e6cc588e3
--- /dev/null
+++ b/testsuite/makefiles/Makefile.common
@@ -0,0 +1,134 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+TOPDIR=$(BASEDIR)/..
+WINTOPDIR=`cygpath -m "$(TOPDIR)"`
+
+# TOPDIR is the root directory of the OCaml sources, in Unix syntax.
+# WINTOPDIR is the same directory, in Windows syntax.
+
+OTOPDIR=$(TOPDIR)
+CTOPDIR=$(TOPDIR)
+CYGPATH=echo
+DIFF=diff -q
+CANKILL=true
+SORT=sort
+SET_LD_PATH=CAML_LD_LIBRARY_PATH="$(LD_PATH)"
+
+# The variables above may be overridden by .../config/Makefile
+# OTOPDIR is either TOPDIR or WINTOPDIR, whichever is appropriate for
+# arguments given to the OCaml compiler.
+# CTOPDIR is either TOPDIR or WINTOPDIR, whichever is appropriate for
+# arguments given to the C and Fortran compilers.
+# CYGPATH is the command that translates unix-style file names into
+# whichever syntax is appropriate for arguments of OCaml programs.
+# DIFF is a "diff -q" command that ignores trailing CRs under Windows.
+# CANKILL is true if a script launched by Make can kill an OCaml process,
+# and false for the mingw and MSVC ports.
+# SORT is the Unix "sort" command. Usually a simple command, but may be an
+# absolute name if the Windows "sort" command is in the PATH.
+# SET_LD_PATH is a command prefix that sets the path for dynamic libraries
+# (CAML_LD_LIBRARY_PATH for Unix, PATH for Windows) using the LD_PATH shell
+# variable. Note that for Windows we add Unix-syntax directory names in
+# PATH, and Cygwin will translate it to Windows syntax.
+
+include $(TOPDIR)/config/Makefile
+
+OCAMLRUN=$(TOPDIR)/boot/ocamlrun$(EXE)
+
+OCFLAGS=-nostdlib -I $(OTOPDIR)/stdlib $(COMPFLAGS)
+OCOPTFLAGS=
+
+ifeq ($(SUPPORTS_SHARED_LIBRARIES),false)
+ CUSTOM = -custom
+else
+ CUSTOM =
+endif
+
+OCAML=$(OCAMLRUN) $(OTOPDIR)/ocaml $(OCFLAGS) \
+ -init $(OTOPDIR)/testsuite/lib/empty
+OCAMLC=$(OCAMLRUN) $(OTOPDIR)/ocamlc $(CUSTOM) $(OCFLAGS)
+OCAMLOPT=$(OCAMLRUN) $(OTOPDIR)/ocamlopt $(OCFLAGS)
+OCAMLDOC=$(OCAMLRUN) $(OTOPDIR)/ocamldoc/ocamldoc
+OCAMLLEX=$(OCAMLRUN) $(OTOPDIR)/lex/ocamllex
+OCAMLMKLIB=$(OCAMLRUN) $(OTOPDIR)/tools/ocamlmklib \
+ -ocamlc "$(OTOPDIR)/boot/ocamlrun$(EXE) \
+ $(OTOPDIR)/ocamlc $(OCFLAGS)" \
+ -ocamlopt "$(OTOPDIR)/boot/ocamlrun$(EXE) \
+ $(OTOPDIR)/ocamlopt $(OCFLAGS)"
+OCAMLYACC=$(TOPDIR)/yacc/ocamlyacc$(EXE)
+OCAMLBUILD=$(TOPDIR)/_build/ocamlbuild/ocamlbuild.native
+DUMPOBJ=$(OCAMLRUN) $(OTOPDIR)/tool/dumpobj
+BYTECODE_ONLY=[ "$(ARCH)" = "none" -o "$(ASM)" = "none" ]
+NATIVECODE_ONLY=false
+
+#FORTRAN_COMPILER=
+#FORTRAN_LIBRARY=
+
+UNIXLIBVAR=`case "$(OTHERLIBRARIES)" in *win32unix*) echo win32;; esac`
+
+defaultpromote:
+ @for file in *.reference; do \
+ cp `basename $$file reference`result $$file; \
+ done
+
+defaultclean:
+ @rm -f *.cmo *.cmi *.cmx *.cma *.cmxa *.cmxs *.$(O) *.$(SO) *.$(A)
+ @for dsym in *.dSYM; do \
+ if [ -d $$dsym ]; then \
+ rm -fr $$dsym; \
+ fi \
+ done
+
+.SUFFIXES:
+.SUFFIXES: .mli .ml .mly .mll .cmi .cmo .cmx .cmm .cmxa .s .S .o .so .c .f
+
+.mli.cmi:
+ @$(OCAMLC) -c $(ADD_COMPFLAGS) $<
+
+.ml.cmi:
+ @$(OCAMLC) -c $(ADD_COMPFLAGS) $<
+
+.ml.cmo:
+ @if [ -f $<i ]; then $(OCAMLC) -c $(ADD_COMPFLAGS) $<i; fi
+ @$(OCAMLC) -c $(ADD_COMPFLAGS) $<
+
+.ml.cmx:
+ @$(OCAMLOPT) -c $(ADD_COMPFLAGS) $<
+
+.cmx.so:
+ @$(OCAMLOPT) -o $@ -shared $(ADD_COMPFLAGS) $<
+
+.cmxa.so:
+ @$(OCAMLOPT) -o $@ -shared -linkall $(ADD_COMPFLAGS) $<
+
+%.ml %.mli: %.mly
+ @$(OCAMLYACC) -q $< 2> /dev/null
+
+.mll.ml:
+ @$(OCAMLLEX) -q $< > /dev/null
+
+.cmm.o:
+ @$(OCAMLRUN) ./codegen $*.cmm > $*.s
+ @$(ASM) -o $*.o $*.s
+
+.S.o:
+ @$(ASPP) $(ASPPFLAGS) -DSYS_$(SYSTEM) -DMODEL_$(MODEL) -o $*.o $*.S
+
+.s.o:
+ @$(ASPP) $(ASPPFLAGS) -DSYS_$(SYSTEM) -o $*.o $*.s
+
+.c.o:
+ @$(CC) -c -I$(CTOPDIR)/byterun $*.c -o $*.$(O)
+
+.f.o:
+ @$(FORTRAN_COMPILER) -c -I$(CTOPDIR)/byterun $*.f -o $*.$(O)
diff --git a/testsuite/makefiles/Makefile.dlambda b/testsuite/makefiles/Makefile.dlambda
new file mode 100644
index 0000000000..eebf858c5e
--- /dev/null
+++ b/testsuite/makefiles/Makefile.dlambda
@@ -0,0 +1,31 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# To avoid tests breaking each time the internal name generation
+# changes, we strip -dlambda-produced identifiers of their unique
+# identifier: "x/1234" becomes simply "x".
+
+default:
+ @for file in *.ml; do \
+ $(OCAMLC) -dlambda -c $$file 2>&1 | \
+ sed -e "s|\\([A-Za-z_][A-Za-z_']*\)/[0-9][0-9]*|\\1|g" > $$file.result; \
+ done
+ @for file in *.reference; do \
+ printf " ... testing '$$file':"; \
+ $(DIFF) $$file `basename $$file reference`result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done
+
+promote: defaultpromote
+
+clean: defaultclean
+ @rm -f *.result
diff --git a/testsuite/makefiles/Makefile.dparsetree b/testsuite/makefiles/Makefile.dparsetree
new file mode 100644
index 0000000000..9e219be01b
--- /dev/null
+++ b/testsuite/makefiles/Makefile.dparsetree
@@ -0,0 +1,27 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# Jeremie Dimino, Jane Street Europe #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+default:
+ @for file in *.ml; do \
+ $(OCAMLC) -dparsetree -c $$file 2>$$file.result >/dev/null || true; \
+ done
+ @for file in *.reference; do \
+ printf " ... testing '$$file':"; \
+ $(DIFF) $$file `basename $$file reference`result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done
+
+promote: defaultpromote
+
+clean: defaultclean
+ @rm -f *.result
diff --git a/testsuite/makefiles/Makefile.okbad b/testsuite/makefiles/Makefile.okbad
new file mode 100644
index 0000000000..11ddf95c29
--- /dev/null
+++ b/testsuite/makefiles/Makefile.okbad
@@ -0,0 +1,42 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+.PHONY: default
+default: compile
+
+.PHONY: compile
+compile:
+ @for file in *.ml; do \
+ printf " ... testing '$$file'"; \
+ if [ `echo $$file | grep bad` ]; then \
+ $(OCAMLC) -c -w a $$file 2>/dev/null \
+ && echo " => failed" || echo " => passed"; \
+ else \
+ F="`basename $$file .ml`"; \
+ test -f $$F.mli && $(OCAMLC) -c -w a $$F.mli; \
+ $(OCAMLC) -c -w a $$file 2>/dev/null \
+ && if [ -f $$F.reference ]; then \
+ rm -f program.byte; \
+ $(OCAMLC) $$F.cmo -o program.byte \
+ && $(OCAMLRUN) program.byte >$$F.result \
+ && $(DIFF) $$F.reference $$F.result >/dev/null; \
+ fi \
+ && echo " => passed" || echo " => failed"; \
+ fi; \
+ done
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f program.byte *.cm* *.result
diff --git a/testsuite/makefiles/Makefile.one b/testsuite/makefiles/Makefile.one
new file mode 100644
index 0000000000..cebf7fcc2e
--- /dev/null
+++ b/testsuite/makefiles/Makefile.one
@@ -0,0 +1,85 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+CMI_FILES=$(MODULES:=.cmi)
+CMO_FILES=$(MODULES:=.cmo)
+CMX_FILES=$(MODULES:=.cmx)
+CMA_FILES=$(LIBRARIES:=.cma)
+CMXA_FILES=$(LIBRARIES:=.cmxa)
+ML_LEX_FILES=$(LEX_MODULES:=.ml)
+ML_YACC_FILES=$(YACC_MODULES:=.ml)
+MLI_YACC_FILES=$(YACC_MODULES:=.mli)
+ML_FILES=$(ML_LEX_FILES) $(ML_YACC_FILES)
+O_FILES=$(C_FILES:=.$(O))
+ADD_CMO_FILES=$(ADD_MODULES:=.cmo)
+ADD_CMX_FILES=$(ADD_MODULES:=.cmx)
+
+GENERATED_SOURCES=$(ML_LEX_FILES) $(ML_YACC_FILES) $(MLI_YACC_FILES)
+
+CUSTOM_FLAG=`if [ -n "$(C_FILES)" ]; then echo '-custom'; fi`
+ADD_CFLAGS+=$(CUSTOM_FLAG)
+MYRUNTIME=`if [ -z "$(C_FILES)$(CUSTOM)" ]; then echo '$(OCAMLRUN)'; fi`
+
+CC=$(NATIVECC) $(NATIVECCCOMPOPTS)
+
+.PHONY: default
+default:
+ @$(MAKE) compile
+ @$(SET_LD_PATH) $(MAKE) run
+
+.PHONY: compile
+compile: $(ML_FILES)
+ @for file in $(C_FILES); do \
+ $(NATIVECC) $(NATIVECCCOMPOPTS) -c -I$(CTOPDIR)/byterun $$file.c; \
+ done;
+ @if $(NATIVECODE_ONLY); then : ; else \
+ rm -f program.byte program.byte.exe; \
+ $(MAKE) $(CMO_FILES) $(MAIN_MODULE).cmo; \
+ $(OCAMLC) $(ADD_COMPFLAGS) $(ADD_CFLAGS) -o program.byte$(EXE) \
+ $(O_FILES) $(CMA_FILES) $(CMO_FILES) $(ADD_CMO_FILES) \
+ $(MAIN_MODULE).cmo; \
+ fi
+ @if $(BYTECODE_ONLY); then : ; else \
+ rm -f program.native program.native.exe; \
+ $(MAKE) $(CMX_FILES) $(MAIN_MODULE).cmx; \
+ $(OCAMLOPT) $(ADD_COMPFLAGS) $(ADD_OPTCOMPFLAGS) \
+ -o program.native$(EXE) $(O_FILES) \
+ $(CMXA_FILES) $(CMX_FILES) $(ADD_CMX_FILES) \
+ $(MAIN_MODULE).cmx; \
+ fi
+
+.PHONY: run
+run:
+ @printf " ... testing with"
+ @if $(NATIVECODE_ONLY); then : ; else \
+ printf " ocamlc"; \
+ $(MYRUNTIME) ./program.byte$(EXE) $(EXEC_ARGS) \
+ >$(MAIN_MODULE).result \
+ && $(DIFF) $(MAIN_MODULE).reference $(MAIN_MODULE).result >/dev/null; \
+ fi \
+ && if $(BYTECODE_ONLY); then : ; else \
+ printf " ocamlopt"; \
+ ./program.native$(EXE) $(EXEC_ARGS) > $(MAIN_MODULE).result \
+ && $(DIFF) $(MAIN_MODULE).reference $(MAIN_MODULE).result \
+ >/dev/null; \
+ fi \
+ && echo " => passed" || echo " => failed"
+
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result program.byte program.byte.exe \
+ program.native program.native.exe \
+ $(GENERATED_SOURCES) $(O_FILES) $(TEST_TEMP_FILES)
diff --git a/testsuite/makefiles/Makefile.several b/testsuite/makefiles/Makefile.several
new file mode 100644
index 0000000000..541046306a
--- /dev/null
+++ b/testsuite/makefiles/Makefile.several
@@ -0,0 +1,108 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+CC=$(NATIVECC) $(NATIVECCCOMPOPTS)
+FC=$(FORTAN_COMPILER)
+CMO_FILES=$(MODULES:=.cmo)
+CMX_FILES=$(MODULES:=.cmx)
+CMA_FILES=$(LIBRARIES:=.cma)
+CMXA_FILES=$(LIBRARIES:=.cmxa)
+O_FILES=$(F_FILES:=.o) $(C_FILES:=.o)
+
+CUSTOM_FLAG=`if [ -n "$(C_FILES)" ]; then echo '-custom'; fi`
+ADD_CFLAGS+=$(CUSTOM_FLAG)
+MYRUNTIME=`if [ -z "$(C_FILES)$(CUSTOM)" ]; then echo '$(OCAMLRUN)'; fi`
+FORTRAN_LIB=`if [ -n "$(F_FILES)" ]; then echo $(FORTRAN_LIBRARY); fi`
+ADD_CFLAGS+=$(FORTRAN_LIB)
+ADD_OPTFLAGS+=$(FORTRAN_LIB)
+
+C_INCLUDES+=-I $(CTOPDIR)/byterun -I$(CTOPDIR)/otherlibs/bigarray
+
+.PHONY: check
+check:
+ @if [ -n "$(FORTRAN_COMPILER)" -o -z "$(F_FILES)" ]; then \
+ $(SET_LD_PATH) $(MAKE) run-all; \
+ fi
+
+.PHONY: run-all
+run-all:
+ @for file in $(C_FILES); do \
+ $(CC) $(C_INCLUDES) -c $$file.c; \
+ done;
+ @for file in $(F_FILES); do \
+ $(FORTRAN_COMPILER) -c $$file.f; \
+ done;
+ @for file in *.ml; do \
+ if [ -f `basename $$file ml`precheck ]; then \
+ CANKILL=$(CANKILL) sh `basename $$file ml`precheck || continue; \
+ fi; \
+ printf " ... testing '$$file':"; \
+ $(MAKE) run-file DESC=ocamlc COMP='$(OCAMLC)' \
+ RUNTIME='$(MYRUNTIME)' \
+ COMPFLAGS='-w a $(ADD_COMPFLAGS) $(ADD_CFLAGS) $(O_FILES) \
+ $(CMA_FILES) -I $(OTOPDIR)/testsuite/lib \
+ $(CMO_FILES)' \
+ FILE=$$file PROGRAM_ARGS=$(PROGRAM_ARGS) \
+ && \
+ if $(BYTECODE_ONLY); then : ; else \
+ $(MAKE) run-file DESC=ocamlopt COMP='$(OCAMLOPT)' \
+ RUNTIME= \
+ COMPFLAGS='-w a $(ADD_COMPFLAGS) $(ADD_OPTFLAGS) \
+ $(O_FILES) $(CMXA_FILES) \
+ -I $(OTOPDIR)/testsuite/lib $(CMX_FILES)' \
+ FILE=$$file PROGRAM_ARGS=$(PROGRAM_ARGS); \
+ fi \
+ && \
+ if [ -n "$(UNSAFE)" ]; then \
+ $(MAKE) run-file DESC=ocamlc-unsafe COMP='$(OCAMLC)' \
+ RUNTIME='$(MYRUNTIME)' \
+ COMPFLAGS='-w a -unsafe $(ADD_COMPFLAGS) $(ADD_CFLAGS) \
+ $(O_FILES) $(CMA_FILES) \
+ -I $(OTOPDIR)/testsuite/lib $(CMO_FILES)' \
+ FILE=$$file \
+ && \
+ if $(BYTECODE_ONLY); then : ; else \
+ $(MAKE) run-file DESC=ocamlopt-unsafe COMP='$(OCAMLOPT)' \
+ RUNTIME= \
+ COMPFLAGS='-w a -unsafe $(ADD_COMPFLAGS) $(ADD_OPTFLAGS)\
+ $(O_FILES) $(CMXA_FILES) \
+ -I $(OTOPDIR)/testsuite/lib $(CMX_FILES)' \
+ FILE=$$file; \
+ fi; \
+ fi \
+ && echo " => passed" || echo " => failed"; \
+ done
+
+.PHONY: run-file
+run-file:
+ @printf " $(DESC)"
+ @rm -f program program.exe
+ @$(COMP) $(COMPFLAGS) $(FILE) -o program$(EXE)
+ @F="`basename $(FILE) .ml`"; \
+ if [ -f $$F.runner ]; then \
+ RUNTIME="$(RUNTIME)" sh $$F.runner; \
+ else \
+ $(RUNTIME) ./program$(EXE) $(PROGRAM_ARGS) >$$F.result; \
+ fi \
+ && \
+ if [ -f $$F.checker ]; then \
+ DIFF="$(DIFF)" SORT="$(SORT)" sh $$F.checker; \
+ else \
+ $(DIFF) $$F.reference $$F.result >/dev/null; \
+ fi
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result program program.exe
diff --git a/testsuite/makefiles/Makefile.toplevel b/testsuite/makefiles/Makefile.toplevel
new file mode 100644
index 0000000000..284465fe92
--- /dev/null
+++ b/testsuite/makefiles/Makefile.toplevel
@@ -0,0 +1,31 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+default:
+ @for file in *.ml; do \
+ TERM=dumb $(OCAML) $(TOPFLAGS) <$$file 2>&1 \
+ | grep -v '^ OCaml version' > $$file.result; \
+ if [ -f $$file.principal.reference ]; then \
+ TERM=dumb $(OCAML) $(TOPFLAGS) -principal <$$file 2>&1 \
+ | grep -v '^ OCaml version' > $$file.principal.result; \
+ fi; \
+ done
+ @for file in *.reference; do \
+ printf " ... testing '$$file':"; \
+ $(DIFF) $$file `basename $$file reference`result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done
+
+promote: defaultpromote
+
+clean: defaultclean
+ @rm -f *.result
diff --git a/testsuite/makefiles/summarize.awk b/testsuite/makefiles/summarize.awk
new file mode 100644
index 0000000000..75ab952556
--- /dev/null
+++ b/testsuite/makefiles/summarize.awk
@@ -0,0 +1,117 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+function check() {
+ if (!in_test){
+ printf("error at line %d: found test result without test start\n", NR);
+ errored = 1;
+ }
+}
+
+function clear() {
+ curfile = "";
+ in_test = 0;
+}
+
+function record_pass() {
+ check();
+ ++ passed;
+ clear();
+}
+
+function record_skip() {
+ check();
+ ++ skipped;
+ clear();
+}
+
+function record_fail() {
+ check();
+ ++ failed;
+ fail[failidx++] = sprintf ("%s/%s", curdir, curfile);
+ clear();
+}
+
+function record_unexp() {
+ ++ unexped;
+ unexp[unexpidx++] = sprintf ("%s/%s", curdir, curfile);
+ clear();
+}
+
+/Running tests from '[^']*'/ {
+ if (in_test) record_unexp();
+ match($0, /Running tests from '[^']*'/);
+ curdir = substr($0, RSTART+20, RLENGTH - 21);
+ curfile = "";
+}
+
+/ ... testing.* ... testing/ {
+ printf("error at line %d: found two test results on the same line\n", NR);
+ errored = 1;
+}
+
+/^ ... testing '[^']*'/ {
+ if (in_test) record_unexp();
+ match($0, /... testing '[^']*'/);
+ curfile = substr($0, RSTART+13, RLENGTH-14);
+ in_test = 1;
+}
+
+/^ ... testing with / {
+ if (in_test) record_unexp();
+ in_test = 1;
+}
+
+/=> passed/ {
+ record_pass();
+}
+
+/=> skipped/ {
+ record_skip();
+}
+
+/=> failed/ {
+ record_fail();
+}
+
+/=> unexpected error/ {
+ record_unexp();
+}
+
+# Not displaying "skipped" for the moment, as most of the skipped tests
+# print nothing at all and are not counted.
+
+END {
+ if (errored){
+ printf ("\n#### Some fatal error occurred during testing.\n\n");
+ exit (3);
+ }else{
+ printf("\n");
+ printf("Summary:\n");
+ printf(" %3d test(s) passed\n", passed);
+ printf(" %3d test(s) failed\n", failed);
+ printf(" %3d unexpected error(s)\n", unexped);
+ if (failed != 0){
+ printf("\nList of failed tests:\n");
+ for (i=0; i < failed; i++) printf(" %s\n", fail[i]);
+ }
+ if (unexped != 0){
+ printf("\nList of unexpected errors:\n");
+ for (i=0; i < unexped; i++) printf(" %s\n", unexp[i]);
+ }
+ printf("\n");
+ if (failed || unexped){
+ printf("#### Some tests failed. Exiting with error status.\n\n");
+ exit 4;
+ }
+ }
+}
diff --git a/testsuite/tests/asmcomp/.ignore b/testsuite/tests/asmcomp/.ignore
new file mode 100644
index 0000000000..321dc06109
--- /dev/null
+++ b/testsuite/tests/asmcomp/.ignore
@@ -0,0 +1,7 @@
+codegen
+parsecmm.ml
+parsecmm.mli
+lexcmm.ml
+*.s
+*.out
+*.out.dSYM
diff --git a/testsuite/tests/asmcomp/Makefile b/testsuite/tests/asmcomp/Makefile
new file mode 100644
index 0000000000..1c9f81e7ce
--- /dev/null
+++ b/testsuite/tests/asmcomp/Makefile
@@ -0,0 +1,94 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+CC=$(NATIVECC)
+CFLAGS=$(NATIVECCCOMPOPTS) -g
+
+INCLUDES=\
+ -I $(OTOPDIR)/utils \
+ -I $(OTOPDIR)/typing \
+ -I $(OTOPDIR)/bytecomp \
+ -I $(OTOPDIR)/asmcomp
+
+OTHEROBJS=\
+ $(OTOPDIR)/compilerlibs/ocamlcommon.cma \
+ $(OTOPDIR)/compilerlibs/ocamloptcomp.cma
+
+OBJS=parsecmmaux.cmo parsecmm.cmo lexcmm.cmo
+
+ADD_COMPFLAGS=$(INCLUDES) -g
+
+default:
+ @if $(BYTECODE_ONLY) || [ -z "$(ASPP)" ]; then : ; else \
+ $(MAKE) all; \
+ fi
+
+all:
+ @$(MAKE) arch codegen
+ @$(MAKE) tests
+
+codegen: parsecmm.ml lexcmm.ml $(OBJS:.cmo=.cmi) $(OBJS) main.cmo
+ @$(OCAMLC) $(LINKFLAGS) -o codegen $(OTHEROBJS) $(OBJS) main.cmo
+
+parsecmm.mli parsecmm.ml: parsecmm.mly
+ @$(OCAMLYACC) -q parsecmm.mly
+
+lexcmm.ml: lexcmm.mll
+ @$(OCAMLLEX) -q lexcmm.mll
+
+MLCASES=optargs staticalloc
+
+CASES=fib tak quicksort quicksort2 soli \
+ arith checkbound tagged-fib tagged-integr tagged-quicksort tagged-tak
+ARGS_fib=-DINT_INT -DFUN=fib main.c
+ARGS_tak=-DUNIT_INT -DFUN=takmain main.c
+ARGS_quicksort=-DSORT -DFUN=quicksort main.c
+ARGS_quicksort2=-DSORT -DFUN=quicksort main.c
+ARGS_soli=-DUNIT_INT -DFUN=solitaire main.c
+ARGS_integr=-DINT_FLOAT -DFUN=test main.c
+ARGS_arith=mainarith.c
+ARGS_checkbound=-DCHECKBOUND main.c
+ARGS_tagged-fib=-DINT_INT -DFUN=fib main.c
+ARGS_tagged-integr=-DINT_FLOAT -DFUN=test main.c
+ARGS_tagged-quicksort=-DSORT -DFUN=quicksort main.c
+ARGS_tagged-tak=-DUNIT_INT -DFUN=takmain main.c
+
+tests: $(CASES:=.o)
+ @for c in $(CASES); do \
+ printf " ... testing '$$c':"; \
+ $(MAKE) one CC="$(CC) $(CFLAGS)" NAME=$$c; \
+ done
+ @for c in $(MLCASES); do \
+ printf " ... testing '$$c':"; \
+ $(MAKE) one_ml NAME=$$c; \
+ done
+
+one_ml:
+ @$(OCAMLOPT) -o $(NAME).exe $(NAME).ml && \
+ ./$(NAME).exe && echo " => passed" || echo " => failed"
+
+one:
+ @$(CC) -o $(NAME).out $(ARGS_$(NAME)) $(NAME).o $(ARCH).o \
+ && echo " => passed" || echo " => failed"
+
+clean: defaultclean
+ @rm -f ./codegen *.out *.o *.obj *.exe
+ @rm -f parsecmm.ml parsecmm.mli lexcmm.ml
+ @rm -f $(CASES:=.s)
+
+include $(BASEDIR)/makefiles/Makefile.common
+
+promote:
+
+arch: $(ARCH).o
diff --git a/testsuite/tests/asmcomp/alpha.S b/testsuite/tests/asmcomp/alpha.S
new file mode 100644
index 0000000000..fd5fef1e5f
--- /dev/null
+++ b/testsuite/tests/asmcomp/alpha.S
@@ -0,0 +1,60 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+ .globl call_gen_code
+ .ent call_gen_code
+
+call_gen_code:
+ lda $sp, -80($sp)
+ stq $26, 0($sp)
+ stq $9, 8($sp)
+ stq $10, 16($sp)
+ stq $11, 24($sp)
+ stq $12, 32($sp)
+ stt $f2, 40($sp)
+ stt $f3, 48($sp)
+ stt $f4, 56($sp)
+ stt $f5, 64($sp)
+ mov $16, $27
+ mov $17, $16
+ mov $18, $17
+ mov $19, $18
+ mov $20, $19
+ jsr ($27)
+ ldq $26, 0($sp)
+ ldq $9, 8($sp)
+ ldq $10, 16($sp)
+ ldq $11, 24($sp)
+ ldq $12, 32($sp)
+ ldt $f2, 40($sp)
+ ldt $f3, 48($sp)
+ ldt $f4, 56($sp)
+ ldt $f5, 64($sp)
+ lda $sp, 80($sp)
+ ret ($26)
+
+ .end call_gen_code
+
+ .globl caml_c_call
+ .ent caml_c_call
+caml_c_call:
+ lda $sp, -16($sp)
+ stq $26, 0($sp)
+ stq $gp, 8($sp)
+ mov $25, $27
+ jsr ($25)
+ ldq $26, 0($sp)
+ ldq $gp, 8($sp)
+ lda $sp, 16($sp)
+ ret ($26)
+
+ .end caml_c_call
diff --git a/testsuite/tests/asmcomp/amd64.S b/testsuite/tests/asmcomp/amd64.S
new file mode 100644
index 0000000000..16dbaec11b
--- /dev/null
+++ b/testsuite/tests/asmcomp/amd64.S
@@ -0,0 +1,75 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#ifdef SYS_macosx
+#define ALIGN 4
+#else
+#define ALIGN 16
+#endif
+
+#ifdef SYS_macosx
+#define CALL_GEN_CODE _call_gen_code
+#define CAML_C_CALL _caml_c_call
+#define CAML_NEGF_MASK _caml_negf_mask
+#define CAML_ABSF_MASK _caml_absf_mask
+#else
+#define CALL_GEN_CODE call_gen_code
+#define CAML_C_CALL caml_c_call
+#define CAML_NEGF_MASK caml_negf_mask
+#define CAML_ABSF_MASK caml_absf_mask
+#endif
+
+ .globl CALL_GEN_CODE
+ .align ALIGN
+CALL_GEN_CODE:
+ pushq %rbx
+ pushq %rbp
+ pushq %r12
+ pushq %r13
+ pushq %r14
+ pushq %r15
+ movq %rdi, %r10
+ movq %rsi, %rax
+ movq %rdx, %rbx
+ movq %rcx, %rdi
+ movq %r8, %rsi
+ call *%r10
+ popq %r15
+ popq %r14
+ popq %r13
+ popq %r12
+ popq %rbp
+ popq %rbx
+ ret
+
+ .globl CAML_C_CALL
+ .align ALIGN
+CAML_C_CALL:
+ jmp *%rax
+
+#ifdef SYS_macosx
+ .literal16
+#elif defined(SYS_mingw64) || defined(SYS_cygwin)
+ .section .rodata.cst8
+#else
+ .section .rodata.cst8,"aM",@progbits,8
+#endif
+ .globl CAML_NEGF_MASK
+ .align ALIGN
+CAML_NEGF_MASK:
+ .quad 0x8000000000000000, 0
+ .globl CAML_ABSF_MASK
+ .align ALIGN
+CAML_ABSF_MASK:
+ .quad 0x7FFFFFFFFFFFFFFF, 0
+
+ .comm young_limit, 8
diff --git a/testsuite/tests/asmcomp/arith.cmm b/testsuite/tests/asmcomp/arith.cmm
new file mode 100644
index 0000000000..e5965bc9d1
--- /dev/null
+++ b/testsuite/tests/asmcomp/arith.cmm
@@ -0,0 +1,217 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Regression test for arithmetic instructions *)
+
+(function "testarith" ()
+ (let r "R"
+ (let d "D"
+ (let x (load int "X")
+ (let y (load int "Y")
+ (let f (load float "F")
+ (let g (load float "G")
+ (addraset r 0 0)
+ (addraset r 1 1)
+ (addraset r 2 -1)
+ (addraset r 3 256)
+ (addraset r 4 65536)
+ (addraset r 5 16777216)
+ (addraset r 6 -256)
+ (addraset r 7 -65536)
+ (addraset r 8 -16777216)
+
+ (addraset r 9 (+ x y))
+ (addraset r 10 (+ x 1))
+ (addraset r 11 (+ x -1))
+
+ (addraset r 12 (+a "R" 8))
+ (addraset r 13 (+a "R" y))
+
+ (addraset r 14 (- x y))
+ (addraset r 15 (- x 1))
+ (addraset r 16 (- x -1))
+
+ (addraset r 17 (- "R" 8))
+ (addraset r 18 (- "R" y))
+
+ (addraset r 19 ( * x 2))
+ (addraset r 20 ( * 2 x))
+ (addraset r 21 ( * x 16))
+ (addraset r 22 ( * 16 x))
+ (addraset r 23 ( * x 12345))
+ (addraset r 24 ( * 12345 x))
+ (addraset r 25 ( * x y))
+
+ (addraset r 26 (/ x 2))
+ (addraset r 27 (/ x 16))
+ (addraset r 28 (/ x 7))
+ (addraset r 29 (if (!= y 0) (/ x y) 0))
+
+ (addraset r 30 (mod x 2))
+ (addraset r 31 (mod x 16))
+ (addraset r 32 (if (!= y 0) (mod x y) 0))
+
+ (addraset r 33 (and x y))
+ (addraset r 34 (and x 3))
+ (addraset r 35 (and 3 x))
+
+ (addraset r 36 (or x y))
+ (addraset r 37 (or x 3))
+ (addraset r 38 (or 3 x))
+
+ (addraset r 39 (xor x y))
+ (addraset r 40 (xor x 3))
+ (addraset r 41 (xor 3 x))
+
+ (addraset r 42 (<< x y))
+ (addraset r 43 (<< x 1))
+ (addraset r 44 (<< x 8))
+
+ (addraset r 45 (>>u x y))
+ (addraset r 46 (>>u x 1))
+ (addraset r 47 (>>u x 8))
+
+ (addraset r 48 (>>s x y))
+ (addraset r 49 (>>s x 1))
+ (addraset r 50 (>>s x 8))
+
+ (addraset r 51 (== x y))
+ (addraset r 52 (!= x y))
+ (addraset r 53 (< x y))
+ (addraset r 54 (> x y))
+ (addraset r 55 (<= x y))
+ (addraset r 56 (>= x y))
+ (addraset r 57 (== x 1))
+ (addraset r 58 (!= x 1))
+ (addraset r 59 (< x 1))
+ (addraset r 60 (> x 1))
+ (addraset r 61 (<= x 1))
+ (addraset r 62 (>= x 1))
+
+ (addraset r 63 (==a x y))
+ (addraset r 64 (!=a x y))
+ (addraset r 65 (<a x y))
+ (addraset r 66 (>a x y))
+ (addraset r 67 (<=a x y))
+ (addraset r 68 (>=a x y))
+ (addraset r 69 (==a x 1))
+ (addraset r 70 (!=a x 1))
+ (addraset r 71 (<a x 1))
+ (addraset r 72 (>a x 1))
+ (addraset r 73 (<=a x 1))
+ (addraset r 74 (>=a x 1))
+
+ (addraset r 75 (+ x (<< y 1)))
+ (addraset r 76 (+ x (<< y 2)))
+ (addraset r 77 (+ x (<< y 3)))
+ (addraset r 78 (- x (<< y 1)))
+ (addraset r 79 (- x (<< y 2)))
+ (addraset r 80 (- x (<< y 3)))
+
+ (floataset d 0 0.0)
+ (floataset d 1 1.0)
+ (floataset d 2 -1.0)
+ (floataset d 3 (+f f g))
+ (floataset d 4 (-f f g))
+ (floataset d 5 ( *f f g))
+ (floataset d 6 (/f f g))
+
+ (floataset d 7 (+f f (+f g 1.0)))
+ (floataset d 8 (-f f (+f g 1.0)))
+ (floataset d 9 ( *f f (+f g 1.0)))
+ (floataset d 10 (/f f (+f g 1.0)))
+
+ (floataset d 11 (+f (+f f 1.0) g))
+ (floataset d 12 (-f (+f f 1.0) g))
+ (floataset d 13 ( *f (+f f 1.0) g))
+ (floataset d 14 (/f (+f f 1.0) g))
+
+ (floataset d 15 (+f (+f f 1.0) (+f g 1.0)))
+ (floataset d 16 (-f (+f f 1.0) (+f g 1.0)))
+ (floataset d 17 ( *f (+f f 1.0) (+f g 1.0)))
+ (floataset d 18 (/f (+f f 1.0) (+f g 1.0)))
+
+ (addraset r 81 (==f f g))
+ (addraset r 82 (!=f f g))
+ (addraset r 83 (<f f g))
+ (addraset r 84 (>f f g))
+ (addraset r 85 (<=f f g))
+ (addraset r 86 (>=f f g))
+
+ (floataset d 19 (floatofint x))
+ (addraset r 87 (intoffloat f))
+
+ (if (and (>= x 0) (< x y))
+ (seq (checkbound y x) (addraset r 88 1))
+ (addraset r 88 0))
+
+ (if (< 0 y)
+ (seq (checkbound y 0) (addraset r 89 1))
+ (addraset r 89 0))
+
+ (if (< 5 y)
+ (seq (checkbound y 5) (addraset r 90 1))
+ (addraset r 90 0))
+
+ (addraset r 91 (let res 1 (if (==f f g) [] (assign res 0)) res))
+ (addraset r 92 (let res 1 (if (!=f f g) [] (assign res 0)) res))
+ (addraset r 93 (let res 1 (if (<f f g) [] (assign res 0)) res))
+ (addraset r 94 (let res 1 (if (>f f g) [] (assign res 0)) res))
+ (addraset r 95 (let res 1 (if (<=f f g) [] (assign res 0)) res))
+ (addraset r 96 (let res 1 (if (>=f f g) [] (assign res 0)) res))
+
+ (addraset r 97 (==f (+f f 1.0) (+f g 1.0)))
+ (addraset r 98 (!=f (+f f 1.0) (+f g 1.0)))
+ (addraset r 99 (<f (+f f 1.0) (+f g 1.0)))
+ (addraset r 100 (>f (+f f 1.0) (+f g 1.0)))
+ (addraset r 101 (<=f (+f f 1.0) (+f g 1.0)))
+ (addraset r 102 (>=f (+f f 1.0) (+f g 1.0)))
+
+ (addraset r 103 (==f f (+f g 1.0)))
+ (addraset r 104 (!=f f (+f g 1.0)))
+ (addraset r 105 (<f f (+f g 1.0)))
+ (addraset r 106 (>f f (+f g 1.0)))
+ (addraset r 107 (<=f f (+f g 1.0)))
+ (addraset r 108 (>=f f (+f g 1.0)))
+
+ (addraset r 109 (==f (+f f 1.0) g))
+ (addraset r 110 (!=f (+f f 1.0) g))
+ (addraset r 111 (<f (+f f 1.0) g))
+ (addraset r 112 (>f (+f f 1.0) g))
+ (addraset r 113 (<=f (+f f 1.0) g))
+ (addraset r 114 (>=f (+f f 1.0) g))
+
+ (floataset d 20 (+f (floatofint x) 1.0))
+ (addraset r 115 (intoffloat (+f f 1.0)))
+
+ (floataset d 21 (+f f (load float "G")))
+ (floataset d 22 (+f (load float "G") f))
+ (floataset d 23 (-f f (load float "G")))
+ (floataset d 24 (-f (load float "G") f))
+ (floataset d 25 ( *f f (load float "G")))
+ (floataset d 26 ( *f (load float "G") f))
+ (floataset d 27 (/f f (load float "G")))
+ (floataset d 28 (/f (load float "G") f))
+
+ (floataset d 29 (+f ( *f f 2.0) (load float "G")))
+ (floataset d 30 (+f (load float "G") ( *f f 2.0)))
+ (floataset d 31 (-f ( *f f 2.0) (load float "G")))
+ (floataset d 32 (-f (load float "G") ( *f f 2.0)))
+ (floataset d 33 ( *f ( +f f 2.0) (load float "G")))
+ (floataset d 34 ( *f (load float "G") ( +f f 2.0)))
+ (floataset d 35 (/f ( *f f 2.0) (load float "G")))
+ (floataset d 36 (/f (load float "G") ( *f f 2.0)))
+
+ (floataset d 37 (-f f))
+ (floataset d 38 (absf f))
+
+)))))))
diff --git a/testsuite/tests/asmcomp/arm.S b/testsuite/tests/asmcomp/arm.S
new file mode 100644
index 0000000000..2e364564e1
--- /dev/null
+++ b/testsuite/tests/asmcomp/arm.S
@@ -0,0 +1,37 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1998 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+ .text
+
+ .global call_gen_code
+ .type call_gen_code, %function
+ .align 0
+call_gen_code:
+ mov ip, sp
+ stmfd sp!, {r4, r5, r6, r7, r8, r9, fp, ip, lr, pc}
+ sub fp, ip, #4
+ @ r0 is function to call
+ @ r1, r2, r3 are arguments 1, 2, 3
+ mov r4, r0
+ mov r0, r1
+ mov r1, r2
+ mov r2, r3
+ mov lr, pc
+ mov pc, r4
+ ldmea fp, {r4, r5, r6, r7, r8, r9, fp, sp, pc}
+
+ .global caml_c_call
+ .type caml_c_call, %function
+ .align 0
+caml_c_call:
+ @ function to call is in r10
+ mov pc, r10
diff --git a/testsuite/tests/asmcomp/arm64.S b/testsuite/tests/asmcomp/arm64.S
new file mode 100644
index 0000000000..7b839c44af
--- /dev/null
+++ b/testsuite/tests/asmcomp/arm64.S
@@ -0,0 +1,52 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Gallium, INRIA Rocquencourt */
+/* */
+/* Copyright 2013 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+ .globl call_gen_code
+ .align 2
+call_gen_code:
+ /* Set up stack frame and save callee-save registers */
+ stp x29, x30, [sp, -160]!
+ add x29, sp, #0
+ stp x19, x20, [sp, 16]
+ stp x21, x22, [sp, 32]
+ stp x23, x24, [sp, 48]
+ stp x25, x26, [sp, 64]
+ stp x27, x28, [sp, 80]
+ stp d8, d9, [sp, 96]
+ stp d10, d11, [sp, 112]
+ stp d12, d13, [sp, 128]
+ stp d14, d15, [sp, 144]
+ /* Shuffle arguments */
+ mov x8, x0
+ mov x0, x1
+ mov x1, x2
+ mov x2, x3
+ mov x3, x4
+ /* Call generated asm */
+ blr x8
+ /* Reload callee-save registers and return address */
+ ldp x19, x20, [sp, 16]
+ ldp x21, x22, [sp, 32]
+ ldp x23, x24, [sp, 48]
+ ldp x25, x26, [sp, 64]
+ ldp x27, x28, [sp, 80]
+ ldp d8, d9, [sp, 96]
+ ldp d10, d11, [sp, 112]
+ ldp d12, d13, [sp, 128]
+ ldp d14, d15, [sp, 144]
+ ldp x29, x30, [sp], 160
+ ret
+
+ .globl caml_c_call
+ .align 2
+caml_c_call:
+ br x15
diff --git a/testsuite/tests/asmcomp/checkbound.cmm b/testsuite/tests/asmcomp/checkbound.cmm
new file mode 100644
index 0000000000..1968154bf4
--- /dev/null
+++ b/testsuite/tests/asmcomp/checkbound.cmm
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "checkbound2" (x: int y: int)
+ (checkbound x y))
+
+(function "checkbound1" (x: int)
+ (checkbound x 2))
diff --git a/testsuite/tests/asmcomp/fib.cmm b/testsuite/tests/asmcomp/fib.cmm
new file mode 100644
index 0000000000..db79c6733c
--- /dev/null
+++ b/testsuite/tests/asmcomp/fib.cmm
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "fib" (n: int)
+ (if (< n 2)
+ 1
+ (+ (app "fib" (- n 1) int)
+ (app "fib" (- n 2) int))))
diff --git a/testsuite/tests/asmcomp/hppa.S b/testsuite/tests/asmcomp/hppa.S
new file mode 100644
index 0000000000..5f7455b7cb
--- /dev/null
+++ b/testsuite/tests/asmcomp/hppa.S
@@ -0,0 +1,161 @@
+;*********************************************************************
+;* *
+;* OCaml *
+;* *
+;* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+;* *
+;* Copyright 1996 Institut National de Recherche en Informatique et *
+;* en Automatique. All rights reserved. This file is distributed *
+;* under the terms of the Q Public License version 1.0. *
+;* *
+;*********************************************************************
+
+; Must be preprocessed by cpp
+
+#ifdef SYS_hpux
+#define G(x) x
+#define CODESPACE .code
+#define CODE_ALIGN 4
+#define EXPORT_CODE(x) .export x, entry, priv_lev=3
+#define STARTPROC .proc ! .callinfo frame=0, no_calls ! .entry
+#define ENDPROC .exit ! .procend
+#endif
+
+#ifdef SYS_nextstep
+#define G(x) _##x
+#define CODESPACE .text
+#define CODE_ALIGN 2
+#define EXPORT_CODE(x) .globl x
+#define STARTPROC
+#define ENDPROC
+#endif
+
+#ifdef SYS_hpux
+ .space $PRIVATE$
+ .subspa $DATA$,quad=1,align=8,access=31
+ .subspa $BSS$,quad=1,align=8,access=31,zero,sort=82
+ .space $TEXT$
+ .subspa $LIT$,quad=0,align=8,access=44
+ .subspa $CODE$,quad=0,align=8,access=44,code_only
+ .import $global$, data
+ .import $$dyncall, millicode
+#endif
+
+ CODESPACE
+ .align CODE_ALIGN
+ EXPORT_CODE(G(call_gen_code))
+G(call_gen_code):
+ STARTPROC
+ stw %r2,-20(%r30)
+ ldo 256(%r30), %r30
+; Save the callee-save registers
+ ldo -32(%r30), %r1
+ stws,ma %r3, -4(%r1)
+ stws,ma %r4, -4(%r1)
+ stws,ma %r5, -4(%r1)
+ stws,ma %r6, -4(%r1)
+ stws,ma %r7, -4(%r1)
+ stws,ma %r8, -4(%r1)
+ stws,ma %r9, -4(%r1)
+ stws,ma %r10, -4(%r1)
+ stws,ma %r11, -4(%r1)
+ stws,ma %r12, -4(%r1)
+ stws,ma %r13, -4(%r1)
+ stws,ma %r14, -4(%r1)
+ stws,ma %r15, -4(%r1)
+ stws,ma %r16, -4(%r1)
+ stws,ma %r17, -4(%r1)
+ stws,ma %r18, -4(%r1)
+ fstds,ma %fr12, -8(%r1)
+ fstds,ma %fr13, -8(%r1)
+ fstds,ma %fr14, -8(%r1)
+ fstds,ma %fr15, -8(%r1)
+ fstds,ma %fr16, -8(%r1)
+ fstds,ma %fr17, -8(%r1)
+ fstds,ma %fr18, -8(%r1)
+ fstds,ma %fr19, -8(%r1)
+ fstds,ma %fr20, -8(%r1)
+ fstds,ma %fr21, -8(%r1)
+ fstds,ma %fr22, -8(%r1)
+ fstds,ma %fr23, -8(%r1)
+ fstds,ma %fr24, -8(%r1)
+ fstds,ma %fr25, -8(%r1)
+ fstds,ma %fr26, -8(%r1)
+ fstds,ma %fr27, -8(%r1)
+ fstds,ma %fr28, -8(%r1)
+ fstds,ma %fr29, -8(%r1)
+ fstds,ma %fr30, -8(%r1)
+ fstds,ma %fr31, -8(%r1)
+
+; Shuffle the arguments and call
+ copy %r26, %r22
+ copy %r25, %r26
+ copy %r24, %r25
+ copy %r23, %r24
+ fcpy,dbl %fr5, %fr4
+#ifdef SYS_hpux
+ bl $$dyncall, %r2
+ nop
+#else
+ ble 0(4, %r22)
+ copy %r31, %r2
+#endif
+; Shuffle the results
+ copy %r26, %r28
+; Restore the callee-save registers
+ ldo -32(%r30), %r1
+ ldws,ma -4(%r1), %r3
+ ldws,ma -4(%r1), %r4
+ ldws,ma -4(%r1), %r5
+ ldws,ma -4(%r1), %r6
+ ldws,ma -4(%r1), %r7
+ ldws,ma -4(%r1), %r8
+ ldws,ma -4(%r1), %r9
+ ldws,ma -4(%r1), %r10
+ ldws,ma -4(%r1), %r11
+ ldws,ma -4(%r1), %r12
+ ldws,ma -4(%r1), %r13
+ ldws,ma -4(%r1), %r14
+ ldws,ma -4(%r1), %r15
+ ldws,ma -4(%r1), %r16
+ ldws,ma -4(%r1), %r17
+ ldws,ma -4(%r1), %r18
+ fldds,ma -8(%r1), %fr12
+ fldds,ma -8(%r1), %fr13
+ fldds,ma -8(%r1), %fr14
+ fldds,ma -8(%r1), %fr15
+ fldds,ma -8(%r1), %fr16
+ fldds,ma -8(%r1), %fr17
+ fldds,ma -8(%r1), %fr18
+ fldds,ma -8(%r1), %fr19
+ fldds,ma -8(%r1), %fr20
+ fldds,ma -8(%r1), %fr21
+ fldds,ma -8(%r1), %fr22
+ fldds,ma -8(%r1), %fr23
+ fldds,ma -8(%r1), %fr24
+ fldds,ma -8(%r1), %fr25
+ fldds,ma -8(%r1), %fr26
+ fldds,ma -8(%r1), %fr27
+ fldds,ma -8(%r1), %fr28
+ fldds,ma -8(%r1), %fr29
+ fldds,ma -8(%r1), %fr30
+ fldds,ma -8(%r1), %fr31
+
+ ldo -256(%r30), %r30
+ ldw -20(%r30), %r2
+ bv 0(%r2)
+ nop
+ ENDPROC
+
+ .align CODE_ALIGN
+ EXPORT_CODE(caml_c_call)
+G(caml_c_call):
+ STARTPROC
+#ifdef SYS_hpux
+ bl $$dyncall, %r0
+ nop
+#else
+ bv 0(%r22)
+ nop
+#endif
+ ENDPROC
diff --git a/testsuite/tests/asmcomp/i386.S b/testsuite/tests/asmcomp/i386.S
new file mode 100644
index 0000000000..cc8a363890
--- /dev/null
+++ b/testsuite/tests/asmcomp/i386.S
@@ -0,0 +1,55 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Linux with ELF binaries does not prefix identifiers with _.
+ Linux with a.out binaries, FreeBSD, and NextStep do. */
+
+#if defined(SYS_linux_elf) || defined(SYS_bsd_elf) \
+ || defined(SYS_solaris) || defined(SYS_beos) || defined(SYS_gnu)
+#define G(x) x
+#define FUNCTION_ALIGN 16
+#else
+#define G(x) _##x
+#define FUNCTION_ALIGN 4
+#endif
+
+ .globl G(call_gen_code)
+ .align FUNCTION_ALIGN
+G(call_gen_code):
+ pushl %ebp
+ movl %esp,%ebp
+ pushl %ebx
+ pushl %esi
+ pushl %edi
+ movl 12(%ebp),%eax
+ movl 16(%ebp),%ebx
+ movl 20(%ebp),%ecx
+ movl 24(%ebp),%edx
+ call *8(%ebp)
+ popl %edi
+ popl %esi
+ popl %ebx
+ popl %ebp
+ ret
+
+ .globl G(caml_c_call)
+ .align FUNCTION_ALIGN
+G(caml_c_call):
+ ffree %st(0)
+ ffree %st(1)
+ ffree %st(2)
+ ffree %st(3)
+ jmp *%eax
+
+ .comm G(caml_exception_pointer), 4
+ .comm G(young_ptr), 4
+ .comm G(young_start), 4
diff --git a/testsuite/tests/asmcomp/i386nt.asm b/testsuite/tests/asmcomp/i386nt.asm
new file mode 100644
index 0000000000..618d41c949
--- /dev/null
+++ b/testsuite/tests/asmcomp/i386nt.asm
@@ -0,0 +1,65 @@
+;*********************************************************************;
+; ;
+; OCaml ;
+; ;
+; Xavier Leroy, projet Cristal, INRIA Rocquencourt ;
+; ;
+; Copyright 1996 Institut National de Recherche en Informatique et ;
+; en Automatique. All rights reserved. This file is distributed ;
+; under the terms of the Q Public License version 1.0. ;
+; ;
+;*********************************************************************;
+
+ .386
+ .MODEL FLAT
+
+ .CODE
+ PUBLIC _call_gen_code
+ ALIGN 4
+_call_gen_code:
+ push ebp
+ mov ebp, esp
+ push ebx
+ push esi
+ push edi
+ mov eax, [ebp+12]
+ mov ebx, [ebp+16]
+ mov ecx, [ebp+20]
+ mov edx, [ebp+24]
+ call DWORD PTR [ebp+8]
+ pop edi
+ pop esi
+ pop ebx
+ pop ebp
+ ret
+
+ PUBLIC _caml_c_call
+ ALIGN 4
+_caml_c_call:
+ ffree st(0)
+ ffree st(1)
+ ffree st(2)
+ ffree st(3)
+ jmp eax
+
+ PUBLIC _caml_call_gc
+ PUBLIC _caml_alloc
+ PUBLIC _caml_alloc1
+ PUBLIC _caml_alloc2
+ PUBLIC _caml_alloc3
+_caml_call_gc:
+_caml_alloc:
+_caml_alloc1:
+_caml_alloc2:
+_caml_alloc3:
+ int 3
+
+ .DATA
+ PUBLIC _caml_exception_pointer
+_caml_exception_pointer dword 0
+ PUBLIC _young_ptr
+_young_ptr dword 0
+ PUBLIC _young_limit
+_young_limit dword 0
+
+ END
diff --git a/testsuite/tests/asmcomp/ia64.S b/testsuite/tests/asmcomp/ia64.S
new file mode 100644
index 0000000000..b1aa5e831c
--- /dev/null
+++ b/testsuite/tests/asmcomp/ia64.S
@@ -0,0 +1,116 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#define ST8OFF(a,b,d) st8 [a] = b, d
+#define LD8OFF(a,b,d) ld8 a = [b], d
+#define STFDOFF(a,b,d) stfd [a] = b, d
+#define LDFDOFF(a,b,d) ldfd a = [b], d
+#define STFSPILLOFF(a,b,d) stf.spill [a] = b, d
+#define LDFFILLOFF(a,b,d) ldf.fill a = [b], d
+
+ .text
+ .align 16
+
+ .global call_gen_code#
+ .proc call_gen_code#
+
+call_gen_code:
+ /* Allocate 64 "out" registers (for the OCaml code) and no locals */
+ alloc r3 = ar.pfs, 0, 0, 64, 0
+
+ /* Save PFS, return address and GP on stack */
+ add sp = -368, sp ;;
+ add r2 = 16, sp ;;
+ ST8OFF(r2,r3,8) ;;
+ mov r3 = b0 ;;
+ ST8OFF(r2,r3,8) ;;
+ ST8OFF(r2,gp,8) ;;
+
+ /* Save predicates on stack */
+ mov r3 = pr ;;
+ st8 [r2] = r3
+
+ /* Save callee-save floating-point registers on stack */
+ add r2 = 48, sp
+ add r3 = 64, sp ;;
+ STFSPILLOFF(r2,f2,16) ;;
+ STFSPILLOFF(r3,f3,16) ;;
+ STFSPILLOFF(r2,f4,16) ;;
+ STFSPILLOFF(r3,f5,16) ;;
+ STFSPILLOFF(r2,f16,16) ;;
+ STFSPILLOFF(r3,f17,16) ;;
+ STFSPILLOFF(r2,f18,16) ;;
+ STFSPILLOFF(r3,f19,16) ;;
+ STFSPILLOFF(r2,f20,16) ;;
+ STFSPILLOFF(r3,f21,16) ;;
+ STFSPILLOFF(r2,f22,16) ;;
+ STFSPILLOFF(r3,f23,16) ;;
+ STFSPILLOFF(r2,f24,16) ;;
+ STFSPILLOFF(r3,f25,16) ;;
+ STFSPILLOFF(r2,f26,16) ;;
+ STFSPILLOFF(r3,f27,16) ;;
+ STFSPILLOFF(r2,f28,16) ;;
+ STFSPILLOFF(r3,f29,16) ;;
+ STFSPILLOFF(r2,f30,16) ;;
+ STFSPILLOFF(r3,f31,16) ;;
+
+ /* Recover entry point and gp from the function pointer in in0 */
+ LD8OFF(r2,r32,8) ;;
+ ld8 r3 = [r32] ;;
+ mov b6 = r2
+ mov gp = r3 ;;
+
+ /* Shift arguments r33 ... r35 to r32 ... r34 */
+ mov r32 = r33
+ mov r33 = r34
+ mov r34 = r35
+
+ /* Do the call */
+ br.call.sptk b0 = b6 ;;
+
+ /* Restore the saved floating-point registers */
+ add r2 = 48, sp
+ add r3 = 64, sp ;;
+ LDFFILLOFF(f2,r2,16) ;;
+ LDFFILLOFF(f3,r3,16) ;;
+ LDFFILLOFF(f4,r2,16) ;;
+ LDFFILLOFF(f5,r3,16) ;;
+ LDFFILLOFF(f16,r2,16) ;;
+ LDFFILLOFF(f17,r3,16) ;;
+ LDFFILLOFF(f18,r2,16) ;;
+ LDFFILLOFF(f19,r3,16) ;;
+ LDFFILLOFF(f20,r2,16) ;;
+ LDFFILLOFF(f21,r3,16) ;;
+ LDFFILLOFF(f22,r2,16) ;;
+ LDFFILLOFF(f23,r3,16) ;;
+ LDFFILLOFF(f24,r2,16) ;;
+ LDFFILLOFF(f25,r3,16) ;;
+ LDFFILLOFF(f26,r2,16) ;;
+ LDFFILLOFF(f27,r3,16) ;;
+ LDFFILLOFF(f28,r2,16) ;;
+ LDFFILLOFF(f29,r3,16) ;;
+ LDFFILLOFF(f30,r2,16) ;;
+ LDFFILLOFF(f31,r3,16) ;;
+
+ /* Restore gp, predicates and return */
+ add r2 = 16, sp ;;
+ LD8OFF(r3,r2,8) ;;
+ mov ar.pfs = r3
+ LD8OFF(r3,r2,8) ;;
+ mov b0 = r3
+ LD8OFF(gp,r2,8) ;;
+ LD8OFF(r3,r2,8) ;;
+ mov pr = r3, -1
+
+ br.ret.sptk.many b0 ;;
+
+ .endp call_gen_code#
diff --git a/testsuite/tests/asmcomp/integr.cmm b/testsuite/tests/asmcomp/integr.cmm
new file mode 100644
index 0000000000..61c707a4f1
--- /dev/null
+++ b/testsuite/tests/asmcomp/integr.cmm
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "square" (x: float)
+ ( *f x x))
+
+(function "integr" (f: addr low: float high: float n: int)
+ (let (h (/f (-f high low) (floatofint n))
+ x low
+ s 0.0
+ i n)
+ (while (> i 0)
+ (assign s (+f s (app f x float)))
+ (assign x (+f x h))
+ (assign i (- i 1)))
+ ( *f s h)))
+
+(function "test" (n: int)
+ (app "integr" "square" 0.0 1.0 n float))
diff --git a/testsuite/tests/asmcomp/lexcmm.mli b/testsuite/tests/asmcomp/lexcmm.mli
new file mode 100644
index 0000000000..e395abeb03
--- /dev/null
+++ b/testsuite/tests/asmcomp/lexcmm.mli
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val token: Lexing.lexbuf -> Parsecmm.token
+
+type error =
+ Illegal_character
+ | Unterminated_comment
+ | Unterminated_string
+
+exception Error of error
+
+val report_error: Lexing.lexbuf -> error -> unit
diff --git a/testsuite/tests/asmcomp/lexcmm.mll b/testsuite/tests/asmcomp/lexcmm.mll
new file mode 100644
index 0000000000..473f3d9e0b
--- /dev/null
+++ b/testsuite/tests/asmcomp/lexcmm.mll
@@ -0,0 +1,229 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+{
+open Parsecmm
+
+type error =
+ Illegal_character
+ | Unterminated_comment
+ | Unterminated_string
+
+exception Error of error
+
+(* For nested comments *)
+
+let comment_depth = ref 0
+
+(* The table of keywords *)
+
+let keyword_table =
+ Misc.create_hashtable 149 [
+ "absf", ABSF;
+ "addr", ADDR;
+ "align", ALIGN;
+ "alloc", ALLOC;
+ "and", AND;
+ "app", APPLY;
+ "assign", ASSIGN;
+ "byte", BYTE;
+ "case", CASE;
+ "catch", CATCH;
+ "checkbound", CHECKBOUND;
+ "exit", EXIT;
+ "extcall", EXTCALL;
+ "float", FLOAT;
+ "float32", FLOAT32;
+ "float64", FLOAT64;
+ "floatofint", FLOATOFINT;
+ "function", FUNCTION;
+ "half", HALF;
+ "if", IF;
+ "int", INT;
+ "int32", INT32;
+ "intoffloat", INTOFFLOAT;
+ "string", KSTRING;
+ "let", LET;
+ "load", LOAD;
+ "mod", MODI;
+ "or", OR;
+ "proj", PROJ;
+ "raise", RAISE Lambda.Raise_regular;
+ "reraise", RAISE Lambda.Raise_reraise;
+ "raise_notrace", RAISE Lambda.Raise_notrace;
+ "seq", SEQ;
+ "signed", SIGNED;
+ "skip", SKIP;
+ "store", STORE;
+ "switch", SWITCH;
+ "try", TRY;
+ "unit", UNIT;
+ "unsigned", UNSIGNED;
+ "val", VAL;
+ "while", WHILE;
+ "with", WITH;
+ "xor", XOR;
+ "addraref", ADDRAREF;
+ "intaref", INTAREF;
+ "floataref", FLOATAREF;
+ "addraset", ADDRASET;
+ "intaset", INTASET;
+ "floataset", FLOATASET
+]
+
+(* To buffer string literals *)
+
+let initial_string_buffer = Bytes.create 256
+let string_buff = ref initial_string_buffer
+let string_index = ref 0
+
+let reset_string_buffer () =
+ string_buff := initial_string_buffer;
+ string_index := 0
+
+let store_string_char c =
+ if !string_index >= Bytes.length (!string_buff) then begin
+ let new_buff = Bytes.create (Bytes.length (!string_buff) * 2) in
+ Bytes.blit (!string_buff) 0 new_buff 0 (Bytes.length (!string_buff));
+ string_buff := new_buff
+ end;
+ Bytes.unsafe_set (!string_buff) (!string_index) c;
+ incr string_index
+
+let get_stored_string () =
+ let s = Bytes.sub_string (!string_buff) 0 (!string_index) in
+ string_buff := initial_string_buffer;
+ s
+
+(* To translate escape sequences *)
+
+let char_for_backslash = function
+ 'n' -> '\010'
+ | 'r' -> '\013'
+ | 'b' -> '\008'
+ | 't' -> '\009'
+ | c -> c
+
+let char_for_decimal_code lexbuf i =
+ Char.chr(100 * (Char.code(Lexing.lexeme_char lexbuf i) - 48) +
+ 10 * (Char.code(Lexing.lexeme_char lexbuf (i+1)) - 48) +
+ (Char.code(Lexing.lexeme_char lexbuf (i+2)) - 48))
+
+(* Error report *)
+
+let report_error lexbuf msg =
+ prerr_string "Lexical error around character ";
+ prerr_int (Lexing.lexeme_start lexbuf);
+ match msg with
+ Illegal_character ->
+ prerr_string ": illegal character"
+ | Unterminated_comment ->
+ prerr_string ": unterminated comment"
+ | Unterminated_string ->
+ prerr_string ": unterminated string"
+
+}
+
+rule token = parse
+ [' ' '\010' '\013' '\009' '\012'] +
+ { token lexbuf }
+ | "+a" { ADDA }
+ | "+v" { ADDV }
+ | "+f" { ADDF }
+ | "+" { ADDI }
+ | ">>s" { ASR }
+ | ":" { COLON }
+ | "/f" { DIVF }
+ | "/" { DIVI }
+ | eof { EOF }
+ | "==a" { EQA }
+ | "==f" { EQF }
+ | "==" { EQI }
+ | ">=a" { GEA }
+ | ">=f" { GEF }
+ | ">=" { GEI }
+ | ">a" { GTA }
+ | ">f" { GTF }
+ | ">" { GTI }
+ | "[" { LBRACKET }
+ | "<=a" { LEA }
+ | "<=f" { LEF }
+ | "<=" { LEI }
+ | "(" { LPAREN }
+ | "<<" { LSL }
+ | ">>u" { LSR }
+ | "<a" { LTA }
+ | "<f" { LTF }
+ | "<" { LTI }
+ | "*f" { MULF }
+ | "*" { MULI }
+ | "!=a" { NEA }
+ | "!=f" { NEF }
+ | "!=" { NEI }
+ | "]" { RBRACKET }
+ | ")" { RPAREN }
+ | "*" { STAR }
+ | "-f" { SUBF }
+ | "-" { SUBI }
+ | '-'? (['0'-'9']+ | "0x" ['0'-'9' 'a'-'f' 'A'-'F']+
+ | "0o" ['0'-'7']+ | "0b" ['0'-'1']+)
+ { INTCONST(int_of_string(Lexing.lexeme lexbuf)) }
+ | '-'? ['0'-'9']+ 'a'
+ { let s = Lexing.lexeme lexbuf in
+ POINTER(int_of_string(String.sub s 0 (String.length s - 1))) }
+ | '-'? ['0'-'9']+ ('.' ['0'-'9']*)? (['e' 'E'] ['+' '-']? ['0'-'9']+)?
+ { FLOATCONST(Lexing.lexeme lexbuf) }
+ | ['A'-'Z' 'a'-'z' '\223'-'\246' '\248'-'\255' ]
+ (['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255'
+ '\'' '0'-'9' ]) *
+ { let s = Lexing.lexeme lexbuf in
+ try
+ Hashtbl.find keyword_table s
+ with Not_found ->
+ IDENT s }
+ | "\""
+ { reset_string_buffer();
+ string lexbuf;
+ STRING (get_stored_string()) }
+ | "(*"
+ { comment_depth := 1;
+ comment lexbuf;
+ token lexbuf }
+ | _ { raise(Error(Illegal_character)) }
+
+and comment = parse
+ "(*"
+ { comment_depth := succ !comment_depth; comment lexbuf }
+ | "*)"
+ { comment_depth := pred !comment_depth;
+ if !comment_depth > 0 then comment lexbuf }
+ | eof
+ { raise (Error(Unterminated_comment)) }
+ | _
+ { comment lexbuf }
+
+and string = parse
+ '"'
+ { () }
+ | '\\' [' ' '\010' '\013' '\009' '\026' '\012'] +
+ { string lexbuf }
+ | '\\' ['\\' '"' 'n' 't' 'b' 'r']
+ { store_string_char(char_for_backslash(Lexing.lexeme_char lexbuf 1));
+ string lexbuf }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9']
+ { store_string_char(char_for_decimal_code lexbuf 1);
+ string lexbuf }
+ | eof
+ { raise (Error(Unterminated_string)) }
+ | _
+ { store_string_char(Lexing.lexeme_char lexbuf 0);
+ string lexbuf }
diff --git a/testsuite/tests/asmcomp/m68k.S b/testsuite/tests/asmcomp/m68k.S
new file mode 100644
index 0000000000..4d0f6a3a81
--- /dev/null
+++ b/testsuite/tests/asmcomp/m68k.S
@@ -0,0 +1,57 @@
+|***********************************************************************
+|* *
+|* OCaml *
+|* *
+|* Xavier Leroy, projet Cristal, INRIA Rocquencourt *
+|* *
+|* Copyright 1996 Institut National de Recherche en Informatique et *
+|* en Automatique. All rights reserved. This file is distributed *
+|* under the terms of the Q Public License version 1.0. *
+|* *
+|***********************************************************************
+
+| call_gen_code is used with the following types:
+| unit -> int
+| int -> int
+| int -> double
+| int * int * address -> void
+| int * int -> void
+| unit -> unit
+| Hence arg1 -> d0, arg2 -> d1, arg3 -> a0,
+| and we need a special case for int -> double
+
+ .text
+ .globl _call_gen_code
+_call_gen_code:
+ link a6, #0
+ movem d2-d7/a2-a6, a7@-
+ fmovem fp2-fp7, a7@-
+ movel a6@(8), a1
+ movel a6@(12), d0
+ movel a6@(16), d1
+ movel a6@(20), a0
+ jsr a1@
+ fmovem a7@+, fp2-fp7
+ movem a7@+, d2-d7/a2-a6
+ unlk a6
+ rts
+
+ .globl _call_gen_code_float
+_call_gen_code_float:
+ link a6, #0
+ moveml d2-d7/a2-a6, a7@-
+ fmovem fp2-fp7, a7@-
+ movel a6@(8), a1
+ movel a6@(12), d0
+ jsr a1@
+ fmoved fp0, a7@-
+ movel a7@+, d0
+ movel a7@+, d1
+ fmovem a7@+, fp2-fp7
+ moveml a7@+, d2-d7/a2-a6
+ unlk a6
+ rts
+
+ .globl _caml_c_call
+_caml_c_call:
+ jmp a0@
diff --git a/testsuite/tests/asmcomp/main.c b/testsuite/tests/asmcomp/main.c
new file mode 100644
index 0000000000..0b59b0b826
--- /dev/null
+++ b/testsuite/tests/asmcomp/main.c
@@ -0,0 +1,125 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+void caml_ml_array_bound_error(void)
+{
+ fprintf(stderr, "Fatal error: out-of-bound access in array or string\n");
+ exit(2);
+}
+
+void print_string(char * s)
+{
+ fputs(s, stdout);
+}
+
+void printf_int(char * fmt, int arg)
+{
+ printf(fmt, arg);
+}
+
+#ifdef SORT
+
+int cmpint(const void * i, const void * j)
+{
+ long vi = *((long *) i);
+ long vj = *((long *) j);
+ if (vi == vj) return 0;
+ if (vi < vj) return -1;
+ return 1;
+}
+
+#endif
+
+int main(int argc, char **argv)
+{
+#ifdef UNIT_INT
+ { extern int FUN();
+ extern int call_gen_code();
+ printf("%d\n", call_gen_code(FUN));
+ }
+#else
+ if (argc < 2) {
+ fprintf(stderr, "Usage: %s [int arg]\n", argv[0]);
+ exit(2);
+ }
+#ifdef INT_INT
+ { extern int FUN();
+ extern int call_gen_code();
+ printf("%d\n", call_gen_code(FUN, atoi(argv[1])));
+ }
+#endif
+#ifdef INT_FLOAT
+ { extern double FUN();
+#ifdef __mc68020__
+#define call_gen_code call_gen_code_float
+#endif
+ extern double call_gen_code();
+ printf("%f\n", call_gen_code(FUN, atoi(argv[1])));
+ }
+#endif
+#ifdef SORT
+ { extern void FUN();
+ extern void call_gen_code();
+ long n;
+ long * a, * b;
+ long i;
+
+ srand(argc >= 3 ? atoi(argv[2]) : time((time_t *) 0));
+ n = atoi(argv[1]);
+ a = (long *) malloc(n * sizeof(long));
+ for (i = 0 ; i < n; i++) a[i] = rand() & 0xFFF;
+#ifdef DEBUG
+ for (i = 0; i < n; i++) printf("%ld ", a[i]); printf("\n");
+#endif
+ b = (long *) malloc(n * sizeof(long));
+ for (i = 0; i < n; i++) b[i] = a[i];
+ call_gen_code(FUN, 0, n-1, a);
+#ifdef DEBUG
+ for (i = 0; i < n; i++) printf("%ld ", a[i]); printf("\n");
+#endif
+ qsort(b, n, sizeof(long), cmpint);
+ for (i = 0; i < n; i++) {
+ if (a[i] != b[i]) { printf("Bug!\n"); return 2; }
+ }
+ printf("OK\n");
+ }
+#endif
+#endif
+#ifdef CHECKBOUND
+ { extern void checkbound1(), checkbound2();
+ extern void call_gen_code();
+ long x, y;
+ x = atoi(argv[1]);
+ if (argc >= 3) {
+ y = atoi(argv[2]);
+ if ((unsigned long) x < (unsigned long) y)
+ printf("Should not trap\n");
+ else
+ printf("Should trap\n");
+ call_gen_code(checkbound2, y, x);
+ } else {
+ if (2 < (unsigned long) x)
+ printf("Should not trap\n");
+ else
+ printf("Should trap\n");
+ call_gen_code(checkbound1, x);
+ }
+ printf("OK\n");
+ }
+#endif
+ return 0;
+}
diff --git a/testsuite/tests/asmcomp/main.ml b/testsuite/tests/asmcomp/main.ml
new file mode 100644
index 0000000000..82b699e7dd
--- /dev/null
+++ b/testsuite/tests/asmcomp/main.ml
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Clflags
+
+let compile_file filename =
+ Clflags.dlcode := false;
+ Compilenv.reset "test";
+ Emit.begin_assembly();
+ let ic = open_in filename in
+ let lb = Lexing.from_channel ic in
+ try
+ while true do
+ Asmgen.compile_phrase Format.std_formatter
+ (Parsecmm.phrase Lexcmm.token lb)
+ done
+ with
+ End_of_file ->
+ close_in ic; Emit.end_assembly()
+ | Lexcmm.Error msg ->
+ close_in ic; Lexcmm.report_error lb msg
+ | Parsing.Parse_error ->
+ close_in ic;
+ prerr_string "Syntax error near character ";
+ prerr_int (Lexing.lexeme_start lb);
+ prerr_newline()
+ | Parsecmmaux.Error msg ->
+ close_in ic; Parsecmmaux.report_error msg
+ | x ->
+ close_in ic; raise x
+
+let usage = "Usage: codegen <options> <files>\noptions are:"
+
+let main() =
+ Arg.parse [
+ "-dcmm", Arg.Set dump_cmm, "";
+ "-dsel", Arg.Set dump_selection, "";
+ "-dlive", Arg.Unit(fun () -> dump_live := true;
+ Printmach.print_live := true), "";
+ "-dspill", Arg.Set dump_spill, "";
+ "-dsplit", Arg.Set dump_split, "";
+ "-dinterf", Arg.Set dump_interf, "";
+ "-dprefer", Arg.Set dump_prefer, "";
+ "-dalloc", Arg.Set dump_regalloc, "";
+ "-dreload", Arg.Set dump_reload, "";
+ "-dscheduling", Arg.Set dump_scheduling, "";
+ "-dlinear", Arg.Set dump_linear, ""
+ ] compile_file usage
+
+let _ = (*Printexc.catch*) main (); exit 0
diff --git a/testsuite/tests/asmcomp/mainarith.c b/testsuite/tests/asmcomp/mainarith.c
new file mode 100644
index 0000000000..94ff371e3c
--- /dev/null
+++ b/testsuite/tests/asmcomp/mainarith.c
@@ -0,0 +1,311 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <math.h>
+#include <time.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "../../../byterun/caml/config.h"
+#define FMT ARCH_INTNAT_PRINTF_FORMAT
+
+void caml_ml_array_bound_error(void)
+{
+ fprintf(stderr, "Fatal error: out-of-bound access in array or string\n");
+ exit(2);
+}
+
+intnat R[200];
+double D[40];
+intnat X, Y;
+double F, G;
+
+#define INTTEST(arg,res) \
+ { intnat result = (res); \
+ if (arg != result) \
+ printf("Failed test \"%s == %s\" for X=%"FMT"d and Y=%"FMT"d: " \
+ "result %"FMT"d, expected %"FMT"d\n", \
+ #arg, #res, X, Y, arg, result); \
+ }
+#define INTFLOATTEST(arg,res) \
+ { intnat result = (res); \
+ if (arg != result) \
+ printf("Failed test \"%s == %s\" for F=%.15g and G=%.15g: "\
+ "result %"FMT"d, expected %"FMT"d\n", \
+ #arg, #res, F, G, arg, result); \
+ }
+#define FLOATTEST(arg,res) \
+ { double result = (res); \
+ if (arg < result || arg > result) \
+ printf("Failed test \"%s == %s\" for F=%.15g and G=%.15g: "\
+ "result %.15g, expected %.15g\n", \
+ #arg, #res, F, G, arg, result); \
+ }
+#define FLOATINTTEST(arg,res) \
+ { double result = (res); \
+ if (arg < result || arg > result) \
+ printf("Failed test \"%s == %s\" for X=%"FMT"d and Y=%"FMT"d: "\
+ "result %.15g, expected %.15g\n", \
+ #arg, #res, X, Y, arg, result); \
+ }
+
+extern void call_gen_code();
+extern void testarith();
+
+void do_test(void)
+{
+ call_gen_code(testarith);
+
+ INTTEST(R[0], 0);
+ INTTEST(R[1], 1);
+ INTTEST(R[2], -1);
+ INTTEST(R[3], 256);
+ INTTEST(R[4], 65536);
+ INTTEST(R[5], 16777216);
+ INTTEST(R[6], -256);
+ INTTEST(R[7], -65536);
+ INTTEST(R[8], -16777216);
+
+ INTTEST(R[9], (X + Y));
+ INTTEST(R[10], (X + 1));
+ INTTEST(R[11], (X + -1));
+
+ INTTEST(R[12], ((intnat) ((char *)R + 8)));
+ INTTEST(R[13], ((intnat) ((char *)R + Y)));
+
+ INTTEST(R[14], (X - Y));
+ INTTEST(R[15], (X - 1));
+ INTTEST(R[16], (X - -1));
+
+ INTTEST(R[17], ((intnat) ((char *)R - 8)));
+ INTTEST(R[18], ((intnat) ((char *)R - Y)));
+
+ INTTEST(R[19], (X * 2));
+ INTTEST(R[20], (2 * X));
+ INTTEST(R[21], (X * 16));
+ INTTEST(R[22], (16 * X));
+ INTTEST(R[23], (X * 12345));
+ INTTEST(R[24], (12345 * X));
+ INTTEST(R[25], (X * Y));
+
+ INTTEST(R[26], (X / 2));
+ INTTEST(R[27], (X / 16));
+ INTTEST(R[28], (X / 7));
+ INTTEST(R[29], (Y != 0 ? X / Y : 0));
+
+ INTTEST(R[30], (X % 2));
+ INTTEST(R[31], (X % 16));
+ INTTEST(R[32], (Y != 0 ? X % Y : 0));
+
+ INTTEST(R[33], (X & Y));
+ INTTEST(R[34], (X & 3));
+ INTTEST(R[35], (3 & X));
+
+ INTTEST(R[36], (X | Y));
+ INTTEST(R[37], (X | 3));
+ INTTEST(R[38], (3 | X));
+
+ INTTEST(R[39], (X ^ Y));
+ INTTEST(R[40], (X ^ 3));
+ INTTEST(R[41], (3 ^ X));
+
+ INTTEST(R[42], (X << Y));
+ INTTEST(R[43], (X << 1));
+ INTTEST(R[44], (X << 8));
+
+ INTTEST(R[45], ((uintnat) X >> Y));
+ INTTEST(R[46], ((uintnat) X >> 1));
+ INTTEST(R[47], ((uintnat) X >> 8));
+
+ INTTEST(R[48], (X >> Y));
+ INTTEST(R[49], (X >> 1));
+ INTTEST(R[50], (X >> 8));
+
+ INTTEST(R[51], (X == Y));
+ INTTEST(R[52], (X != Y));
+ INTTEST(R[53], (X < Y));
+ INTTEST(R[54], (X > Y));
+ INTTEST(R[55], (X <= Y));
+ INTTEST(R[56], (X >= Y));
+ INTTEST(R[57], (X == 1));
+ INTTEST(R[58], (X != 1));
+ INTTEST(R[59], (X < 1));
+ INTTEST(R[60], (X > 1));
+ INTTEST(R[61], (X <= 1));
+ INTTEST(R[62], (X >= 1));
+
+ INTTEST(R[63], ((char *)X == (char *)Y));
+ INTTEST(R[64], ((char *)X != (char *)Y));
+ INTTEST(R[65], ((char *)X < (char *)Y));
+ INTTEST(R[66], ((char *)X > (char *)Y));
+ INTTEST(R[67], ((char *)X <= (char *)Y));
+ INTTEST(R[68], ((char *)X >= (char *)Y));
+ INTTEST(R[69], ((char *)X == (char *)1));
+ INTTEST(R[70], ((char *)X != (char *)1));
+ INTTEST(R[71], ((char *)X < (char *)1));
+ INTTEST(R[72], ((char *)X > (char *)1));
+ INTTEST(R[73], ((char *)X <= (char *)1));
+ INTTEST(R[74], ((char *)X >= (char *)1));
+
+ INTTEST(R[75], (X + (Y << 1)));
+ INTTEST(R[76], (X + (Y << 2)));
+ INTTEST(R[77], (X + (Y << 3)));
+ INTTEST(R[78], (X - (Y << 1)));
+ INTTEST(R[79], (X - (Y << 2)));
+ INTTEST(R[80], (X - (Y << 3)));
+
+ FLOATTEST(D[0], 0.0);
+ FLOATTEST(D[1], 1.0);
+ FLOATTEST(D[2], -1.0);
+ FLOATTEST(D[3], (F + G));
+ FLOATTEST(D[4], (F - G));
+ FLOATTEST(D[5], (F * G));
+ FLOATTEST(D[6], F / G);
+
+ FLOATTEST(D[7], (F + (G + 1.0)));
+ FLOATTEST(D[8], (F - (G + 1.0)));
+ FLOATTEST(D[9], (F * (G + 1.0)));
+ FLOATTEST(D[10], F / (G + 1.0));
+
+ FLOATTEST(D[11], ((F + 1.0) + G));
+ FLOATTEST(D[12], ((F + 1.0) - G));
+ FLOATTEST(D[13], ((F + 1.0) * G));
+ FLOATTEST(D[14], (F + 1.0) / G);
+
+ FLOATTEST(D[15], ((F + 1.0) + (G + 1.0)));
+ FLOATTEST(D[16], ((F + 1.0) - (G + 1.0)));
+ FLOATTEST(D[17], ((F + 1.0) * (G + 1.0)));
+ FLOATTEST(D[18], (F + 1.0) / (G + 1.0));
+
+ INTFLOATTEST(R[81], (F == G));
+ INTFLOATTEST(R[82], (F != G));
+ INTFLOATTEST(R[83], (F < G));
+ INTFLOATTEST(R[84], (F > G));
+ INTFLOATTEST(R[85], (F <= G));
+ INTFLOATTEST(R[86], (F >= G));
+
+ FLOATINTTEST(D[19], (double) X);
+ INTFLOATTEST(R[87], (intnat) F);
+
+ INTTEST(R[88], (X >= 0) && (X < Y));
+ INTTEST(R[89], (0 < Y));
+ INTTEST(R[90], (5 < Y));
+
+ INTFLOATTEST(R[91], (F == G));
+ INTFLOATTEST(R[92], (F != G));
+ INTFLOATTEST(R[93], (F < G));
+ INTFLOATTEST(R[94], (F > G));
+ INTFLOATTEST(R[95], (F <= G));
+ INTFLOATTEST(R[96], (F >= G));
+
+ INTFLOATTEST(R[97], (F + 1.0 == G + 1.0));
+ INTFLOATTEST(R[98], (F + 1.0 != G + 1.0));
+ INTFLOATTEST(R[99], (F + 1.0 < G + 1.0));
+ INTFLOATTEST(R[100], (F + 1.0 > G + 1.0));
+ INTFLOATTEST(R[101], (F + 1.0 <= G + 1.0));
+ INTFLOATTEST(R[102], (F + 1.0 >= G + 1.0));
+
+ INTFLOATTEST(R[103], (F == G + 1.0));
+ INTFLOATTEST(R[104], (F != G + 1.0));
+ INTFLOATTEST(R[105], (F < G + 1.0));
+ INTFLOATTEST(R[106], (F > G + 1.0));
+ INTFLOATTEST(R[107], (F <= G + 1.0));
+ INTFLOATTEST(R[108], (F >= G + 1.0));
+
+ INTFLOATTEST(R[109], (F + 1.0 == G));
+ INTFLOATTEST(R[110], (F + 1.0 != G));
+ INTFLOATTEST(R[111], (F + 1.0 < G));
+ INTFLOATTEST(R[112], (F + 1.0 > G));
+ INTFLOATTEST(R[113], (F + 1.0 <= G));
+ INTFLOATTEST(R[114], (F + 1.0 >= G));
+
+ FLOATINTTEST(D[20], ((double) X) + 1.0);
+ INTFLOATTEST(R[115], (intnat)(F + 1.0));
+
+ FLOATTEST(D[21], F + G);
+ FLOATTEST(D[22], G + F);
+ FLOATTEST(D[23], F - G);
+ FLOATTEST(D[24], G - F);
+ FLOATTEST(D[25], F * G);
+ FLOATTEST(D[26], G * F);
+ FLOATTEST(D[27], F / G);
+ FLOATTEST(D[28], G / F);
+
+ FLOATTEST(D[29], (F * 2.0) + G);
+ FLOATTEST(D[30], G + (F * 2.0));
+ FLOATTEST(D[31], (F * 2.0) - G);
+ FLOATTEST(D[32], G - (F * 2.0));
+ FLOATTEST(D[33], (F + 2.0) * G);
+ FLOATTEST(D[34], G * (F + 2.0));
+ FLOATTEST(D[35], (F * 2.0) / G);
+ FLOATTEST(D[36], G / (F * 2.0));
+
+ FLOATTEST(D[37], - F);
+ FLOATTEST(D[38], fabs(F));
+}
+
+#ifdef __i386__
+#ifdef __FreeBSD__
+#include <floatingpoint.h>
+#endif
+#endif
+
+void init_ieee_floats(void)
+{
+#ifdef __i386__
+#ifdef __FreeBSD__
+ fpsetmask(0);
+#endif
+#endif
+}
+
+int main(int argc, char **argv)
+{
+ double weird[4];
+
+ init_ieee_floats();
+
+ if (argc >= 5) {
+ X = atoi(argv[1]);
+ Y = atoi(argv[2]);
+ sscanf(argv[3], "%lf", &F);
+ sscanf(argv[4], "%lf", &G);
+ do_test();
+ return 0;
+ }
+ for(Y = -2; Y <= 2; Y++) {
+ for (X = -2; X <= 2; X++) {
+ F = X; G = Y; do_test();
+ }
+ }
+ if (!(argc >= 2 && strcmp(argv[1], "noinf"))) {
+ weird[0] = 0.0;
+ weird[1] = 1.0 / weird[0]; /* +infty */
+ weird[2] = -1.0 / weird[0]; /* -infty */
+ weird[3] = 0.0 / weird[0]; /* NaN */
+ for (X = 0; X < 4; X++) {
+ for (Y = 0; Y < 4; Y++) {
+ F = weird[X]; G = weird[Y]; do_test();
+ }
+ }
+ }
+ while(1) {
+ X = (rand() & 0x1FFFFFFF) - 0x10000000;
+ Y = (rand() & 0x1FFFFFFF) - 0x10000000;
+ F = X / 1e3;
+ G = Y / 1e3;
+ do_test();
+ printf("."); fflush(stdout);
+ }
+ return 0;
+}
diff --git a/testsuite/tests/asmcomp/mips.s b/testsuite/tests/asmcomp/mips.s
new file mode 100644
index 0000000000..db4f23eabd
--- /dev/null
+++ b/testsuite/tests/asmcomp/mips.s
@@ -0,0 +1,69 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+ .globl call_gen_code
+ .ent call_gen_code
+call_gen_code:
+ subu $sp, $sp, 0x90
+ sd $31, 0x88($sp)
+ /* Save all callee-save registers */
+ sd $16, 0x0($sp)
+ sd $17, 0x8($sp)
+ sd $18, 0x10($sp)
+ sd $19, 0x18($sp)
+ sd $20, 0x20($sp)
+ sd $21, 0x28($sp)
+ sd $22, 0x30($sp)
+ sd $23, 0x38($sp)
+ sd $30, 0x40($sp)
+ s.d $f20, 0x48($sp)
+ s.d $f22, 0x50($sp)
+ s.d $f24, 0x58($sp)
+ s.d $f26, 0x60($sp)
+ s.d $f28, 0x68($sp)
+ s.d $f30, 0x70($sp)
+ /* Shuffle arguments */
+ move $8, $5
+ move $9, $6
+ move $10, $7
+ move $25, $4
+ jal $4
+ /* Restore registers */
+ ld $31, 0x88($sp)
+ ld $16, 0x0($sp)
+ ld $17, 0x8($sp)
+ ld $18, 0x10($sp)
+ ld $19, 0x18($sp)
+ ld $20, 0x20($sp)
+ ld $21, 0x28($sp)
+ ld $22, 0x30($sp)
+ ld $23, 0x38($sp)
+ ld $30, 0x40($sp)
+ l.d $f20, 0x48($sp)
+ l.d $f22, 0x50($sp)
+ l.d $f24, 0x58($sp)
+ l.d $f26, 0x60($sp)
+ l.d $f28, 0x68($sp)
+ l.d $f30, 0x70($sp)
+ addu $sp, $sp, 0x90
+ j $31
+
+ .end call_gen_code
+
+/* Call a C function */
+
+ .globl caml_c_call
+ .ent caml_c_call
+caml_c_call:
+ move $25, $24
+ j $24
+ .end caml_c_call
diff --git a/testsuite/tests/asmcomp/optargs.ml b/testsuite/tests/asmcomp/optargs.ml
new file mode 100644
index 0000000000..92705bd25e
--- /dev/null
+++ b/testsuite/tests/asmcomp/optargs.ml
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Check the effectiveness of inlining the wrapper which fills in
+ default values for optional arguments.
+
+ Ref: http://caml.inria.fr/mantis/view.php?id=6345
+*)
+
+
+let rec f ?(flag = false) ?(acc = 0) = function
+ | [] -> if flag then acc else acc + 1
+ | hd :: tl -> f ~flag ~acc:(acc + hd) tl
+
+let () =
+ let l = [1;2;3;4;5;6;7;8;9] in
+ let x0 = Gc.allocated_bytes () in
+ let x1 = Gc.allocated_bytes () in
+ for i = 1 to 1000 do
+ ignore (f l)
+ done;
+ let x2 = Gc.allocated_bytes () in
+ assert(x1 -. x0 = x2 -. x1)
+ (* check that we have not allocated anything between x1 and x2 *)
diff --git a/testsuite/tests/asmcomp/parsecmm.mly b/testsuite/tests/asmcomp/parsecmm.mly
new file mode 100644
index 0000000000..a987ed08e7
--- /dev/null
+++ b/testsuite/tests/asmcomp/parsecmm.mly
@@ -0,0 +1,329 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* A simple parser for C-- */
+
+%{
+open Cmm
+open Parsecmmaux
+
+let rec make_letdef def body =
+ match def with
+ [] -> body
+ | (id, def) :: rem ->
+ unbind_ident id;
+ Clet(id, def, make_letdef rem body)
+
+let make_switch n selector caselist =
+ let index = Array.make n 0 in
+ let casev = Array.of_list caselist in
+ let actv = Array.make (Array.length casev) (Cexit(0,[])) in
+ for i = 0 to Array.length casev - 1 do
+ let (posl, e) = casev.(i) in
+ List.iter (fun pos -> index.(pos) <- i) posl;
+ actv.(i) <- e
+ done;
+ Cswitch(selector, index, actv)
+
+let access_array base numelt size =
+ match numelt with
+ Cconst_int 0 -> base
+ | Cconst_int n -> Cop(Cadda, [base; Cconst_int(n * size)])
+ | _ -> Cop(Cadda, [base;
+ Cop(Clsl, [numelt; Cconst_int(Misc.log2 size)])])
+
+%}
+
+%token ABSF
+%token ADDA
+%token ADDF
+%token ADDI
+%token ADDV
+%token ADDR
+%token ALIGN
+%token ALLOC
+%token AND
+%token APPLY
+%token ASR
+%token ASSIGN
+%token BYTE
+%token CASE
+%token CATCH
+%token CHECKBOUND
+%token COLON
+%token DIVF
+%token DIVI
+%token EOF
+%token EQA
+%token EQF
+%token EQI
+%token EXIT
+%token EXTCALL
+%token FLOAT
+%token FLOAT32
+%token FLOAT64
+%token <string> FLOATCONST
+%token FLOATOFINT
+%token FUNCTION
+%token GEA
+%token GEF
+%token GEI
+%token GTA
+%token GTF
+%token GTI
+%token HALF
+%token <string> IDENT
+%token IF
+%token INT
+%token INT32
+%token <int> INTCONST
+%token INTOFFLOAT
+%token KSTRING
+%token LBRACKET
+%token LEA
+%token LEF
+%token LEI
+%token LET
+%token LOAD
+%token LPAREN
+%token LSL
+%token LSR
+%token LTA
+%token LTF
+%token LTI
+%token MODI
+%token MULF
+%token MULI
+%token NEA
+%token NEF
+%token NEI
+%token OR
+%token <int> POINTER
+%token PROJ
+%token <Lambda.raise_kind> RAISE
+%token RBRACKET
+%token RPAREN
+%token SEQ
+%token SIGNED
+%token SKIP
+%token STAR
+%token STORE
+%token <string> STRING
+%token SUBF
+%token SUBI
+%token SWITCH
+%token TRY
+%token UNIT
+%token UNSIGNED
+%token VAL
+%token WHILE
+%token WITH
+%token XOR
+%token ADDRAREF
+%token INTAREF
+%token FLOATAREF
+%token ADDRASET
+%token INTASET
+%token FLOATASET
+
+%start phrase
+%type <Cmm.phrase> phrase
+
+%%
+
+phrase:
+ fundecl { Cfunction $1 }
+ | datadecl { Cdata $1 }
+ | EOF { raise End_of_file }
+;
+fundecl:
+ LPAREN FUNCTION STRING LPAREN params RPAREN sequence RPAREN
+ { List.iter (fun (id, ty) -> unbind_ident id) $5;
+ {fun_name = $3; fun_args = $5; fun_body = $7; fun_fast = true;
+ fun_dbg = Debuginfo.none} }
+;
+params:
+ oneparam params { $1 :: $2 }
+ | /**/ { [] }
+;
+oneparam:
+ IDENT COLON machtype { (bind_ident $1, $3) }
+;
+machtype:
+ UNIT { [||] }
+ | componentlist { Array.of_list(List.rev $1) }
+;
+component:
+ VAL { Val }
+ | ADDR { Addr }
+ | INT { Int }
+ | FLOAT { Float }
+;
+componentlist:
+ component { [$1] }
+ | componentlist STAR component { $3 :: $1 }
+;
+expr:
+ INTCONST { Cconst_int $1 }
+ | FLOATCONST { Cconst_float (float_of_string $1) }
+ | STRING { Cconst_symbol $1 }
+ | POINTER { Cconst_pointer $1 }
+ | IDENT { Cvar(find_ident $1) }
+ | LBRACKET RBRACKET { Ctuple [] }
+ | LPAREN LET letdef sequence RPAREN { make_letdef $3 $4 }
+ | LPAREN ASSIGN IDENT expr RPAREN { Cassign(find_ident $3, $4) }
+ | LPAREN APPLY expr exprlist machtype RPAREN
+ { Cop(Capply($5, Debuginfo.none), $3 :: List.rev $4) }
+ | LPAREN EXTCALL STRING exprlist machtype RPAREN
+ { Cop(Cextcall($3, $5, false, Debuginfo.none), List.rev $4) }
+ | LPAREN SUBF expr RPAREN { Cop(Cnegf, [$3]) }
+ | LPAREN SUBF expr expr RPAREN { Cop(Csubf, [$3; $4]) }
+ | LPAREN unaryop expr RPAREN { Cop($2, [$3]) }
+ | LPAREN binaryop expr expr RPAREN { Cop($2, [$3; $4]) }
+ | LPAREN SEQ sequence RPAREN { $3 }
+ | LPAREN IF expr expr expr RPAREN { Cifthenelse($3, $4, $5) }
+ | LPAREN SWITCH INTCONST expr caselist RPAREN { make_switch $3 $4 $5 }
+ | LPAREN WHILE expr sequence RPAREN
+ { let body =
+ match $3 with
+ Cconst_int x when x <> 0 -> $4
+ | _ -> Cifthenelse($3, $4, (Cexit(0,[]))) in
+ Ccatch(0, [], Cloop body, Ctuple []) }
+ | LPAREN CATCH sequence WITH sequence RPAREN { Ccatch(0, [], $3, $5) }
+ | EXIT { Cexit(0,[]) }
+ | LPAREN TRY sequence WITH bind_ident sequence RPAREN
+ { unbind_ident $5; Ctrywith($3, $5, $6) }
+ | LPAREN ADDRAREF expr expr RPAREN
+ { Cop(Cload Word_val, [access_array $3 $4 Arch.size_addr]) }
+ | LPAREN INTAREF expr expr RPAREN
+ { Cop(Cload Word_int, [access_array $3 $4 Arch.size_int]) }
+ | LPAREN FLOATAREF expr expr RPAREN
+ { Cop(Cload Double_u, [access_array $3 $4 Arch.size_float]) }
+ | LPAREN ADDRASET expr expr expr RPAREN
+ { Cop(Cstore Word_val, [access_array $3 $4 Arch.size_addr; $5]) }
+ | LPAREN INTASET expr expr expr RPAREN
+ { Cop(Cstore Word_int, [access_array $3 $4 Arch.size_int; $5]) }
+ | LPAREN FLOATASET expr expr expr RPAREN
+ { Cop(Cstore Double_u, [access_array $3 $4 Arch.size_float; $5]) }
+;
+exprlist:
+ exprlist expr { $2 :: $1 }
+ | /**/ { [] }
+;
+letdef:
+ oneletdef { [$1] }
+ | LPAREN letdefmult RPAREN { $2 }
+;
+letdefmult:
+ /**/ { [] }
+ | oneletdef letdefmult { $1 :: $2 }
+;
+oneletdef:
+ IDENT expr { (bind_ident $1, $2) }
+;
+chunk:
+ UNSIGNED BYTE { Byte_unsigned }
+ | SIGNED BYTE { Byte_signed }
+ | UNSIGNED HALF { Sixteen_unsigned }
+ | SIGNED HALF { Sixteen_signed }
+ | UNSIGNED INT32 { Thirtytwo_unsigned }
+ | SIGNED INT32 { Thirtytwo_signed }
+ | INT { Word_int }
+ | ADDR { Word_val }
+ | FLOAT32 { Single }
+ | FLOAT64 { Double }
+ | FLOAT { Double_u }
+
+;
+unaryop:
+ LOAD chunk { Cload $2 }
+ | ALLOC { Calloc }
+ | FLOATOFINT { Cfloatofint }
+ | INTOFFLOAT { Cintoffloat }
+ | RAISE { Craise ($1, Debuginfo.none) }
+ | ABSF { Cabsf }
+;
+binaryop:
+ STORE chunk { Cstore $2 }
+ | ADDI { Caddi }
+ | SUBI { Csubi }
+ | MULI { Cmuli }
+ | DIVI { Cdivi }
+ | MODI { Cmodi }
+ | AND { Cand }
+ | OR { Cor }
+ | XOR { Cxor }
+ | LSL { Clsl }
+ | LSR { Clsr }
+ | ASR { Casr }
+ | EQI { Ccmpi Ceq }
+ | NEI { Ccmpi Cne }
+ | LTI { Ccmpi Clt }
+ | LEI { Ccmpi Cle }
+ | GTI { Ccmpi Cgt }
+ | GEI { Ccmpi Cge }
+ | ADDA { Cadda }
+ | ADDV { Caddv }
+ | EQA { Ccmpa Ceq }
+ | NEA { Ccmpa Cne }
+ | LTA { Ccmpa Clt }
+ | LEA { Ccmpa Cle }
+ | GTA { Ccmpa Cgt }
+ | GEA { Ccmpa Cge }
+ | ADDF { Caddf }
+ | MULF { Cmulf }
+ | DIVF { Cdivf }
+ | EQF { Ccmpf Ceq }
+ | NEF { Ccmpf Cne }
+ | LTF { Ccmpf Clt }
+ | LEF { Ccmpf Cle }
+ | GTF { Ccmpf Cgt }
+ | GEF { Ccmpf Cge }
+ | CHECKBOUND { Ccheckbound Debuginfo.none }
+;
+sequence:
+ expr sequence { Csequence($1, $2) }
+ | expr { $1 }
+;
+caselist:
+ onecase sequence caselist { ($1, $2) :: $3 }
+ | /**/ { [] }
+;
+onecase:
+ CASE INTCONST COLON onecase { $2 :: $4 }
+ | CASE INTCONST COLON { [$2] }
+;
+bind_ident:
+ IDENT { bind_ident $1 }
+;
+datadecl:
+ LPAREN datalist RPAREN { List.rev $2 }
+;
+datalist:
+ datalist dataitem { $2 :: $1 }
+ | /**/ { [] }
+;
+dataitem:
+ STRING COLON { Cdefine_symbol $1 }
+ | INTCONST COLON { Cdefine_label $1 }
+ | BYTE INTCONST { Cint8 $2 }
+ | HALF INTCONST { Cint16 $2 }
+ | INT INTCONST { Cint(Nativeint.of_int $2) }
+ | FLOAT FLOATCONST { Cdouble (float_of_string $2) }
+ | ADDR STRING { Csymbol_address $2 }
+ | ADDR INTCONST { Clabel_address $2 }
+ | VAL STRING { Csymbol_address $2 }
+ | VAL INTCONST { Clabel_address $2 }
+ | KSTRING STRING { Cstring $2 }
+ | SKIP INTCONST { Cskip $2 }
+ | ALIGN INTCONST { Calign $2 }
+;
diff --git a/testsuite/tests/asmcomp/parsecmmaux.ml b/testsuite/tests/asmcomp/parsecmmaux.ml
new file mode 100644
index 0000000000..1c0848ddfe
--- /dev/null
+++ b/testsuite/tests/asmcomp/parsecmmaux.ml
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliary functions for parsing *)
+
+type error =
+ Unbound of string
+
+exception Error of error
+
+let tbl_ident = (Hashtbl.create 57 : (string, Ident.t) Hashtbl.t)
+
+let bind_ident s =
+ let id = Ident.create s in
+ Hashtbl.add tbl_ident s id;
+ id
+
+let find_ident s =
+ try
+ Hashtbl.find tbl_ident s
+ with Not_found ->
+ raise(Error(Unbound s))
+
+let unbind_ident id =
+ Hashtbl.remove tbl_ident (Ident.name id)
+
+let report_error = function
+ Unbound s ->
+ prerr_string "Unbound identifier "; prerr_string s; prerr_endline "."
diff --git a/testsuite/tests/asmcomp/parsecmmaux.mli b/testsuite/tests/asmcomp/parsecmmaux.mli
new file mode 100644
index 0000000000..0f2e370a16
--- /dev/null
+++ b/testsuite/tests/asmcomp/parsecmmaux.mli
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliary functions for parsing *)
+
+val bind_ident: string -> Ident.t
+val find_ident: string -> Ident.t
+val unbind_ident: Ident.t -> unit
+
+type error =
+ Unbound of string
+
+exception Error of error
+
+val report_error: error -> unit
diff --git a/testsuite/tests/asmcomp/power.S b/testsuite/tests/asmcomp/power.S
new file mode 100644
index 0000000000..d13035a46e
--- /dev/null
+++ b/testsuite/tests/asmcomp/power.S
@@ -0,0 +1,197 @@
+/*********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/*********************************************************************/
+
+#if defined(MODEL_ppc64) || defined(MODEL_ppc64le)
+#define EITHER(a,b) b
+#else
+#define EITHER(a,b) a
+#endif
+
+#define WORD EITHER(4,8)
+#define lg EITHER(lwz,ld)
+#define lgu EITHER(lwzu,ldu)
+#define stg EITHER(stw,std)
+#define stgu EITHER(stwu,stdu)
+
+#if defined(MODEL_ppc)
+#define RESERVED_STACK 16
+#define LR_SAVE_AREA 4
+#endif
+#if defined(MODEL_ppc64)
+#define RESERVED_STACK 48
+#define LR_SAVE_AREA 16
+#endif
+#if defined(MODEL_ppc64le)
+#define RESERVED_STACK 32
+#define LR_SAVE_AREA 16
+#endif
+
+/* Function definitions */
+
+#if defined(MODEL_ppc)
+#define FUNCTION(name) \
+ .section ".text"; \
+ .globl name; \
+ .type name, @function; \
+ .align 2; \
+ name:
+#endif
+
+#if defined(MODEL_ppc64)
+#define FUNCTION(name) \
+ .section ".opd","aw"; \
+ .align 3; \
+ .globl name; \
+ .type name, @function; \
+ name: .quad .L.name,.TOC.@tocbase; \
+ .text; \
+ .align 2; \
+ .L.name:
+#endif
+
+#if defined(MODEL_ppc64le)
+#define FUNCTION(name) \
+ .section ".text"; \
+ .globl name; \
+ .type name, @function; \
+ .align 2; \
+ name: ; \
+ 0: addis 2, 12, (.TOC. - 0b)@ha; \
+ addi 2, 2, (.TOC. - 0b)@l; \
+ .localentry name, . - 0b
+#endif
+
+FUNCTION(call_gen_code)
+ /* Allocate and link stack frame */
+ stgu 1, -(WORD*18 + 8*18 + RESERVED_STACK)(1)
+ /* 18 saved GPRs, 18 saved FPRs */
+ /* Save return address */
+ mflr 0
+ stg 0, (WORD*18 + 8*18 + RESERVED_STACK + LR_SAVE_AREA)(1)
+ /* Save all callee-save registers, starting at RESERVED_STACK */
+ addi 11, 1, RESERVED_STACK - WORD
+ stgu 14, WORD(11)
+ stgu 15, WORD(11)
+ stgu 16, WORD(11)
+ stgu 17, WORD(11)
+ stgu 18, WORD(11)
+ stgu 19, WORD(11)
+ stgu 20, WORD(11)
+ stgu 21, WORD(11)
+ stgu 22, WORD(11)
+ stgu 23, WORD(11)
+ stgu 24, WORD(11)
+ stgu 25, WORD(11)
+ stgu 26, WORD(11)
+ stgu 27, WORD(11)
+ stgu 28, WORD(11)
+ stgu 29, WORD(11)
+ stgu 30, WORD(11)
+ stgu 31, WORD(11)
+ stfdu 14, 8(11)
+ stfdu 15, 8(11)
+ stfdu 16, 8(11)
+ stfdu 17, 8(11)
+ stfdu 18, 8(11)
+ stfdu 19, 8(11)
+ stfdu 20, 8(11)
+ stfdu 21, 8(11)
+ stfdu 22, 8(11)
+ stfdu 23, 8(11)
+ stfdu 24, 8(11)
+ stfdu 25, 8(11)
+ stfdu 26, 8(11)
+ stfdu 27, 8(11)
+ stfdu 28, 8(11)
+ stfdu 29, 8(11)
+ stfdu 30, 8(11)
+ stfdu 31, 8(11)
+ /* Get function pointer in CTR */
+#if defined(MODEL_ppc)
+ mtctr 3
+#elif defined(MODEL_ppc64)
+ ld 0, 0(3)
+ mtctr 0
+ ld 2, 8(3)
+#elif defined(MODEL_ppc64le)
+ mtctr 3
+ mr 12, 3
+#else
+#error "wrong MODEL"
+#endif
+ /* Shuffle arguments */
+ mr 3, 4
+ mr 4, 5
+ mr 5, 6
+ mr 6, 7
+ /* Call the function */
+ bctrl
+ /* Restore callee-save registers */
+ addi 11, 1, RESERVED_STACK - WORD
+ lgu 14, WORD(11)
+ lgu 15, WORD(11)
+ lgu 16, WORD(11)
+ lgu 17, WORD(11)
+ lgu 18, WORD(11)
+ lgu 19, WORD(11)
+ lgu 20, WORD(11)
+ lgu 21, WORD(11)
+ lgu 22, WORD(11)
+ lgu 23, WORD(11)
+ lgu 24, WORD(11)
+ lgu 25, WORD(11)
+ lgu 26, WORD(11)
+ lgu 27, WORD(11)
+ lgu 28, WORD(11)
+ lgu 29, WORD(11)
+ lgu 30, WORD(11)
+ lgu 31, WORD(11)
+ lfdu 14, 8(11)
+ lfdu 15, 8(11)
+ lfdu 16, 8(11)
+ lfdu 17, 8(11)
+ lfdu 18, 8(11)
+ lfdu 19, 8(11)
+ lfdu 20, 8(11)
+ lfdu 21, 8(11)
+ lfdu 22, 8(11)
+ lfdu 23, 8(11)
+ lfdu 24, 8(11)
+ lfdu 25, 8(11)
+ lfdu 26, 8(11)
+ lfdu 27, 8(11)
+ lfdu 28, 8(11)
+ lfdu 29, 8(11)
+ lfdu 30, 8(11)
+ lfdu 31, 8(11)
+ /* Reload return address */
+ lg 0, (WORD*18 + 8*18 + RESERVED_STACK + LR_SAVE_AREA)(1)
+ mtlr 0
+ /* Return */
+ addi 1, 1, (WORD*18 + 8*18 + RESERVED_STACK)
+ blr
+
+FUNCTION(caml_c_call)
+ /* Jump to C function (address in r28) */
+#if defined(MODEL_ppc)
+ mtctr 28
+#elif defined(MODEL_ppc64)
+ ld 0, 0(28)
+ mtctr 0
+ ld 2, 8(28)
+#elif defined(MODEL_ppc64le)
+ mtctr 28
+ mr 12, 28
+#else
+#error "wrong MODEL"
+#endif
+ bctr
diff --git a/testsuite/tests/asmcomp/quicksort.cmm b/testsuite/tests/asmcomp/quicksort.cmm
new file mode 100644
index 0000000000..f60f1f29d8
--- /dev/null
+++ b/testsuite/tests/asmcomp/quicksort.cmm
@@ -0,0 +1,41 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "quicksort" (lo: int hi: int a: val)
+ (if (< lo hi)
+ (let (i lo
+ j hi
+ pivot (addraref a hi))
+ (while (< i j)
+ (catch
+ (while 1
+ (if (>= i hi) exit [])
+ (if (> (addraref a i) pivot) exit [])
+ (assign i (+ i 1)))
+ with [])
+ (catch
+ (while 1
+ (if (<= j lo) exit [])
+ (if (< (addraref a j) pivot) exit [])
+ (assign j (- j 1)))
+ with [])
+ (if (< i j)
+ (let temp (addraref a i)
+ (addraset a i (addraref a j))
+ (addraset a j temp))
+ []))
+ (let temp (addraref a i)
+ (addraset a i (addraref a hi))
+ (addraset a hi temp))
+ (app "quicksort" lo (- i 1) a unit)
+ (app "quicksort" (+ i 1) hi a unit))
+ []))
diff --git a/testsuite/tests/asmcomp/quicksort2.cmm b/testsuite/tests/asmcomp/quicksort2.cmm
new file mode 100644
index 0000000000..04e3c26689
--- /dev/null
+++ b/testsuite/tests/asmcomp/quicksort2.cmm
@@ -0,0 +1,47 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "cmp" (i: int j: int)
+ (- i j))
+
+(function "quick" (lo: int hi: int a: val cmp: val)
+ (if (< lo hi)
+ (let (i lo
+ j hi
+ pivot (intaref a hi))
+ (while (< i j)
+ (catch
+ (while 1
+ (if (>= i hi) exit [])
+ (if (> (app cmp (intaref a i) pivot int) 0) exit [])
+ (assign i (+ i 1)))
+ with [])
+ (catch
+ (while 1
+ (if (<= j lo) exit [])
+ (if (< (app cmp (intaref a j) pivot int) 0) exit [])
+ (assign j (- j 1)))
+ with [])
+ (if (< i j)
+ (let temp (intaref a i)
+ (intaset a i (intaref a j))
+ (intaset a j temp))
+ []))
+ (let temp (intaref a i)
+ (intaset a i (intaref a hi))
+ (intaset a hi temp))
+ (app "quick" lo (- i 1) a cmp unit)
+ (app "quick" (+ i 1) hi a cmp unit))
+ []))
+
+(function "quicksort" (lo: int hi: int a: val)
+ (app "quick" lo hi a "cmp" unit))
diff --git a/testsuite/tests/asmcomp/soli.cmm b/testsuite/tests/asmcomp/soli.cmm
new file mode 100644
index 0000000000..1b42b4e2d4
--- /dev/null
+++ b/testsuite/tests/asmcomp/soli.cmm
@@ -0,0 +1,107 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+("d1": int 0 int 1
+ "d2": int 1 int 0
+ "d3": int 0 int -1
+ "d4": int -1 int 0
+ "dir": val "d1" val "d2" val "d3" val "d4")
+
+("counter": int 0)
+
+(* Out = 0 Empty = 1 Peg = 2 *)
+
+("line0": int 0 int 0 int 0 int 0 int 0 int 0 int 0 int 0 int 0
+ "line1": int 0 int 0 int 0 int 2 int 2 int 2 int 0 int 0 int 0
+ "line2": int 0 int 0 int 0 int 2 int 2 int 2 int 0 int 0 int 0
+ "line3": int 0 int 2 int 2 int 2 int 2 int 2 int 2 int 2 int 0
+ "line4": int 0 int 2 int 2 int 2 int 1 int 2 int 2 int 2 int 0
+ "line5": int 0 int 2 int 2 int 2 int 2 int 2 int 2 int 2 int 0
+ "line6": int 0 int 0 int 0 int 2 int 2 int 2 int 0 int 0 int 0
+ "line7": int 0 int 0 int 0 int 2 int 2 int 2 int 0 int 0 int 0
+ "line8": int 0 int 0 int 0 int 0 int 0 int 0 int 0 int 0 int 0
+ "board": val "line0" val "line1" val "line2" val "line3"
+ val "line4" val "line5" val "line6" val "line7" val "line8")
+
+("format": string "%d\n\000")
+
+(function "solve" (m: int)
+ (store int "counter" (+ (load int "counter") 1))
+ (if (== m 31)
+ (== (intaref (addraref "board" 4) 4) 2)
+ (try
+ (if (== (mod (load int "counter") 500) 0)
+ (extcall "printf_int" "format" (load int "counter") unit)
+ [])
+ (let i 1
+ (while (<= i 7)
+ (let j 1
+ (while (<= j 7)
+ (if (== (intaref (addraref "board" i) j) 2)
+ (seq
+ (let k 0
+ (while (<= k 3)
+ (let (d1 (intaref (addraref "dir" k) 0)
+ d2 (intaref (addraref "dir" k) 1)
+ i1 (+ i d1)
+ i2 (+ i1 d1)
+ j1 (+ j d2)
+ j2 (+ j1 d2))
+ (if (== (intaref (addraref "board" i1) j1) 2)
+ (if (== (intaref (addraref "board" i2) j2) 1)
+ (seq
+ (intaset (addraref "board" i) j 1)
+ (intaset (addraref "board" i1) j1 1)
+ (intaset (addraref "board" i2) j2 2)
+ (if (app "solve" (+ m 1) int)
+ (raise 0a)
+ [])
+ (intaset (addraref "board" i) j 2)
+ (intaset (addraref "board" i1) j1 2)
+ (intaset (addraref "board" i2) j2 1))
+ [])
+ []))
+ (assign k (+ k 1)))))
+ [])
+ (assign j (+ j 1))))
+ (assign i (+ i 1))))
+ 0
+ with bucket
+ 1)))
+
+("format_out": string ".\000")
+("format_empty": string " \000")
+("format_peg": string "$\000")
+("format_newline": string "\n\000")
+
+(function "print_board" ()
+ (let i 0
+ (while (< i 9)
+ (let j 0
+ (while (< j 9)
+ (switch 3 (intaref (addraref "board" i) j)
+ case 0:
+ (extcall "print_string" "format_out" unit)
+ case 1:
+ (extcall "print_string" "format_empty" unit)
+ case 2:
+ (extcall "print_string" "format_peg" unit))
+ (assign j (+ j 1))))
+ (extcall "print_string" "format_newline" unit)
+ (assign i (+ i 1)))))
+
+(function "solitaire" ()
+ (seq
+ (if (app "solve" 0 int)
+ (app "print_board" [] unit)
+ [])
+ 0))
diff --git a/testsuite/tests/asmcomp/sparc.S b/testsuite/tests/asmcomp/sparc.S
new file mode 100644
index 0000000000..f2b9ce2073
--- /dev/null
+++ b/testsuite/tests/asmcomp/sparc.S
@@ -0,0 +1,39 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#if defined(SYS_solaris) || defined(SYS_linux)
+#define Call_gen_code call_gen_code
+#define Caml_c_call caml_c_call
+#else
+#define Call_gen_code _call_gen_code
+#define Caml_c_call _caml_c_call
+#endif
+
+ .global Call_gen_code
+Call_gen_code:
+ save %sp, -96, %sp
+ mov %i0, %l0
+ mov %i1, %i0
+ mov %i2, %i1
+ mov %i3, %i2
+ mov %i4, %i3
+ mov %i5, %i4
+ call %l0
+ nop
+ mov %o0, %i0
+ ret
+ restore
+
+ .global Caml_c_call
+Caml_c_call:
+ jmp %g4
+ nop
diff --git a/testsuite/tests/asmcomp/staticalloc.ml b/testsuite/tests/asmcomp/staticalloc.ml
new file mode 100644
index 0000000000..3186686c7b
--- /dev/null
+++ b/testsuite/tests/asmcomp/staticalloc.ml
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Check the effectiveness of structured constant propagation and
+ static allocation.
+
+ Ref: http://caml.inria.fr/mantis/view.php?id=5779
+*)
+
+let () =
+ let x0 = Gc.allocated_bytes () in
+ let x1 = Gc.allocated_bytes () in
+ let pair x y = (x, y) in
+ let a = pair 1 2 in
+ let b = pair a ["x";"y"] in
+ let g () = (a, fst b) in
+ assert (g () == ((1,2), (1,2)));
+ assert (fst (pair a a) == (1, 2));
+ assert (snd b != ["x"; "y"]); (* mutable "constant", cannot be shared *)
+ let x2 = Gc.allocated_bytes () in
+ assert(x1 -. x0 = x2 -. x1)
+ (* check that we did not allocated anything between x1 and x2 *)
diff --git a/testsuite/tests/asmcomp/tagged-fib.cmm b/testsuite/tests/asmcomp/tagged-fib.cmm
new file mode 100644
index 0000000000..945b1a1dfa
--- /dev/null
+++ b/testsuite/tests/asmcomp/tagged-fib.cmm
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "fib" (n: int)
+ (if (< n 5)
+ 3
+ (- (+ (app "fib" (- n 2) int) (app "fib" (- n 4) int)) 1)))
diff --git a/testsuite/tests/asmcomp/tagged-integr.cmm b/testsuite/tests/asmcomp/tagged-integr.cmm
new file mode 100644
index 0000000000..d93a0b971b
--- /dev/null
+++ b/testsuite/tests/asmcomp/tagged-integr.cmm
@@ -0,0 +1,42 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+("res_square": skip 8)
+("h": skip 8)
+("x": skip 8)
+("s": skip 8)
+("res_integr": skip 8)
+
+(function "square" (x: val)
+ (let r "res_square"
+ (store float r ( *f (load float x) (load float x)))
+ r))
+
+(function "integr" (f: val low: val high: val n: int)
+ (let (h "h" x "x" s "s" i n)
+ (store float h (/f (-f (load float high) (load float low)) (floatofint n)))
+ (store float x (load float low))
+ (store float s 0.0)
+ (while (> i 0)
+ (store float s (+f (load float s) (load float (app f x val))))
+ (store float x (+f (load float x) (load float h)))
+ (assign i (- i 1)))
+ (store float "res_integr" ( *f (load float s) (load float h)))
+ "res_integr"))
+
+("low": skip 8)
+("hi": skip 8)
+
+(function "test" (n: int)
+ (store float "low" 0.0)
+ (store float "hi" 1.0)
+ (load float (app "integr" "square" "low" "hi" n val)))
diff --git a/testsuite/tests/asmcomp/tagged-quicksort.cmm b/testsuite/tests/asmcomp/tagged-quicksort.cmm
new file mode 100644
index 0000000000..6c0035568a
--- /dev/null
+++ b/testsuite/tests/asmcomp/tagged-quicksort.cmm
@@ -0,0 +1,44 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "quick" (lo: int hi: int a: val)
+ (if (< lo hi)
+ (let (i lo
+ j hi
+ pivot (addraref a (>>s hi 1)))
+ (while (< i j)
+ (catch
+ (while 1
+ (if (>= i hi) exit [])
+ (if (> (addraref a (>>s i 1)) pivot) exit [])
+ (assign i (+ i 2)))
+ with [])
+ (catch
+ (while 1
+ (if (<= j lo) exit [])
+ (if (< (addraref a (>>s j 1)) pivot) exit [])
+ (assign j (- j 2)))
+ with [])
+ (if (< i j)
+ (let temp (addraref a (>>s i 1))
+ (addraset a (>>s i 1) (addraref a (>>s j 1)))
+ (addraset a (>>s j 1) temp))
+ []))
+ (let temp (addraref a (>>s i 1))
+ (addraset a (>>s i 1) (addraref a (>>s hi 1)))
+ (addraset a (>>s hi 1) temp))
+ (app "quick" lo (- i 2) a unit)
+ (app "quick" (+ i 2) hi a unit))
+ []))
+
+(function "quicksort" (lo: int hi: int a: val)
+ (app "quick" (+ (<< lo 1) 1) (+ (<< hi 1) 1) a unit))
diff --git a/testsuite/tests/asmcomp/tagged-tak.cmm b/testsuite/tests/asmcomp/tagged-tak.cmm
new file mode 100644
index 0000000000..73e7668484
--- /dev/null
+++ b/testsuite/tests/asmcomp/tagged-tak.cmm
@@ -0,0 +1,21 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "tak" (x:int y:int z:int)
+ (if (> x y)
+ (app "tak" (app "tak" (- x 2) y z int)
+ (app "tak" (- y 2) z x int)
+ (app "tak" (- z 2) x y int) int)
+ z))
+
+(function "takmain" (dummy: int)
+ (app "tak" 37 25 13 int))
diff --git a/testsuite/tests/asmcomp/tak.cmm b/testsuite/tests/asmcomp/tak.cmm
new file mode 100644
index 0000000000..fe71cb8de6
--- /dev/null
+++ b/testsuite/tests/asmcomp/tak.cmm
@@ -0,0 +1,21 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(function "tak" (x:int y:int z:int)
+ (if (> x y)
+ (app "tak" (app "tak" (- x 1) y z int)
+ (app "tak" (- y 1) z x int)
+ (app "tak" (- z 1) x y int) int)
+ z))
+
+(function "takmain" (dummy: int)
+ (app "tak" 18 12 6 int))
diff --git a/testsuite/tests/backtrace/Makefile b/testsuite/tests/backtrace/Makefile
new file mode 100644
index 0000000000..1d638f5427
--- /dev/null
+++ b/testsuite/tests/backtrace/Makefile
@@ -0,0 +1,97 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+EXECNAME=program$(EXE)
+
+ABCDFILES=backtrace.ml
+OTHERFILES=backtrace2.ml raw_backtrace.ml \
+ backtrace_deprecated.ml backtrace_slots.ml
+OTHERFILESNOINLINING=backtraces_and_finalizers.ml
+
+default:
+ @$(MAKE) byte
+ @if $(BYTECODE_ONLY); then : ; else $(MAKE) native; fi
+
+.PHONY: byte
+byte:
+ @for file in $(ABCDFILES); do \
+ rm -f program program.exe; \
+ $(OCAMLC) -g -o $(EXECNAME) $$file; \
+ for arg in a b c d ''; do \
+ printf " ... testing '$$file' with ocamlc and argument '$$arg':"; \
+ F="`basename $$file .ml`"; \
+ (OCAMLRUNPARAM=$$OCAMLRUNPARAM,b=1 \
+ $(OCAMLRUN) $(EXECNAME) $$arg || true) \
+ >$$F.$$arg.byte.result 2>&1; \
+ $(DIFF) $$F.$$arg.reference $$F.$$arg.byte.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done; \
+ done
+ @for file in $(OTHERFILES); do \
+ rm -f program program.exe; \
+ $(OCAMLC) -g -o $(EXECNAME) $$file; \
+ printf " ... testing '$$file' with ocamlc:"; \
+ F="`basename $$file .ml`"; \
+ (OCAMLRUNPARAM=$$OCAMLRUNPARAM,b=1 \
+ $(OCAMLRUN) $(EXECNAME) $$arg || true) \
+ >$$F.byte.result 2>&1; \
+ $(DIFF) $$F.reference $$F.byte.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done
+
+.PHONY: native
+native:
+ @for file in $(ABCDFILES); do \
+ rm -f program program.exe; \
+ $(OCAMLOPT) -g -o $(EXECNAME) $$file; \
+ for arg in a b c d ''; do \
+ printf " ... testing '$$file' with ocamlopt and argument '$$arg':"; \
+ F="`basename $$file .ml`"; \
+ (OCAMLRUNPARAM=$$OCAMLRUNPARAM,b=1 \
+ ./$(EXECNAME) $$arg || true) \
+ >$$F.$$arg.native.result 2>&1; \
+ $(DIFF) $$F.$$arg.reference $$F.$$arg.native.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done; \
+ done
+ @for file in $(OTHERFILES); do \
+ rm -f program program.exe; \
+ $(OCAMLOPT) -g -o $(EXECNAME) $$file; \
+ printf " ... testing '$$file' with ocamlopt:"; \
+ F="`basename $$file .ml`"; \
+ (OCAMLRUNPARAM=$OCAMLRUNPARAM,b=1 \
+ ./$(EXECNAME) $$arg || true) \
+ >$$F.native.result 2>&1; \
+ $(DIFF) $$F.reference $$F.native.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done;
+ @for file in $(OTHERFILESNOINLINING); do \
+ rm -f program program.exe; \
+ $(OCAMLOPT) -inline 0 -g -o $(EXECNAME) $$file; \
+ printf " ... testing '$$file' with ocamlopt:"; \
+ F="`basename $$file .ml`"; \
+ (OCAMLRUNPARAM=$$OCAMLRUNPARAM,b=1 \
+ ./$(EXECNAME) $$arg || true) \
+ >$$F.native.result 2>&1; \
+ $(DIFF) $$F.reference $$F.native.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result program program.exe
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/backtrace/backtrace..reference b/testsuite/tests/backtrace/backtrace..reference
new file mode 100644
index 0000000000..fdbc70feab
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace..reference
@@ -0,0 +1,2 @@
+Fatal error: exception Invalid_argument("index out of bounds")
+Raised by primitive operation at file "backtrace.ml", line 29, characters 12-24
diff --git a/testsuite/tests/backtrace/backtrace.a.reference b/testsuite/tests/backtrace/backtrace.a.reference
new file mode 100644
index 0000000000..7898192261
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace.a.reference
@@ -0,0 +1 @@
+a
diff --git a/testsuite/tests/backtrace/backtrace.b.reference b/testsuite/tests/backtrace/backtrace.b.reference
new file mode 100644
index 0000000000..a93f65ffa5
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace.b.reference
@@ -0,0 +1,11 @@
+b
+Fatal error: exception Backtrace.Error("b")
+Raised at file "backtrace.ml", line 18, characters 21-32
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 22, characters 4-11
+Re-raised at file "backtrace.ml", line 24, characters 68-71
+Called from file "backtrace.ml", line 29, characters 9-25
diff --git a/testsuite/tests/backtrace/backtrace.c.reference b/testsuite/tests/backtrace/backtrace.c.reference
new file mode 100644
index 0000000000..8ca6985fab
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace.c.reference
@@ -0,0 +1,3 @@
+Fatal error: exception Backtrace.Error("c")
+Raised at file "backtrace.ml", line 25, characters 26-37
+Called from file "backtrace.ml", line 29, characters 9-25
diff --git a/testsuite/tests/backtrace/backtrace.d.reference b/testsuite/tests/backtrace/backtrace.d.reference
new file mode 100644
index 0000000000..c4cb390a96
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace.d.reference
@@ -0,0 +1,9 @@
+Fatal error: exception Backtrace.Error("d")
+Raised at file "backtrace.ml", line 18, characters 21-32
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 18, characters 42-53
+Called from file "backtrace.ml", line 22, characters 4-11
+Called from file "backtrace.ml", line 29, characters 9-25
diff --git a/testsuite/tests/backtrace/backtrace.ml b/testsuite/tests/backtrace/backtrace.ml
new file mode 100644
index 0000000000..94fc9476dd
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace.ml
@@ -0,0 +1,29 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A test for stack backtraces *)
+
+exception Error of string
+
+let rec f msg n =
+ if n = 0 then raise(Error msg) else 1 + f msg (n-1)
+
+let g msg =
+ try
+ f msg 5
+ with Error "a" -> print_string "a"; print_newline(); 0
+ | Error "b" as exn -> print_string "b"; print_newline(); raise exn
+ | Error "c" -> raise (Error "c")
+
+let _ =
+ Printexc.record_backtrace true;
+ ignore (g Sys.argv.(1))
diff --git a/testsuite/tests/backtrace/backtrace2.ml b/testsuite/tests/backtrace/backtrace2.ml
new file mode 100644
index 0000000000..25156165a2
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace2.ml
@@ -0,0 +1,40 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2008 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A test for stack backtraces *)
+
+exception Error of string
+
+let rec f msg n =
+ if n = 0 then raise(Error msg) else 1 + f msg (n-1)
+
+let g msg =
+ try
+ f msg 5
+ with Error "a" -> print_string "a"; print_newline(); 0
+ | Error "b" as exn -> print_string "b"; print_newline(); raise exn
+ | Error "c" -> raise (Error "c")
+
+let run args =
+ try
+ ignore (g args.(0)); print_string "No exception\n"
+ with exn ->
+ Printf.printf "Uncaught exception %s\n" (Printexc.to_string exn);
+ Printexc.print_backtrace stdout
+
+let _ =
+ Printexc.record_backtrace true;
+ run [| "a" |];
+ run [| "b" |];
+ run [| "c" |];
+ run [| "d" |];
+ run [| |]
diff --git a/testsuite/tests/backtrace/backtrace2.reference b/testsuite/tests/backtrace/backtrace2.reference
new file mode 100644
index 0000000000..185c673e05
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace2.reference
@@ -0,0 +1,27 @@
+a
+No exception
+b
+Uncaught exception Backtrace2.Error("b")
+Raised at file "backtrace2.ml", line 18, characters 21-32
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 22, characters 4-11
+Re-raised at file "backtrace2.ml", line 24, characters 68-71
+Called from file "backtrace2.ml", line 29, characters 11-23
+Uncaught exception Backtrace2.Error("c")
+Raised at file "backtrace2.ml", line 25, characters 26-37
+Called from file "backtrace2.ml", line 29, characters 11-23
+Uncaught exception Backtrace2.Error("d")
+Raised at file "backtrace2.ml", line 18, characters 21-32
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 18, characters 42-53
+Called from file "backtrace2.ml", line 22, characters 4-11
+Called from file "backtrace2.ml", line 29, characters 11-23
+Uncaught exception Invalid_argument("index out of bounds")
+Raised by primitive operation at file "backtrace2.ml", line 29, characters 14-22
diff --git a/testsuite/tests/backtrace/backtrace_deprecated.ml b/testsuite/tests/backtrace/backtrace_deprecated.ml
new file mode 100644
index 0000000000..7ec5152d0c
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace_deprecated.ml
@@ -0,0 +1,50 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2008 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A test for stack backtraces *)
+
+external get_backtrace : unit -> Printexc.backtrace_slot array option
+ = "caml_get_exception_backtrace"
+
+exception Error of string
+
+let rec f msg n =
+ if n = 0 then raise(Error msg) else 1 + f msg (n-1)
+
+let g msg =
+ try
+ f msg 5
+ with Error "a" -> print_string "a"; print_newline(); 0
+ | Error "b" as exn -> print_string "b"; print_newline(); raise exn
+ | Error "c" -> raise (Error "c")
+
+let run args =
+ try
+ ignore (g args.(0)); print_string "No exception\n"
+ with exn ->
+ Printf.printf "Uncaught exception %s\n" (Printexc.to_string exn);
+ get_backtrace () |> function
+ | None -> ()
+ | Some trace ->
+ Array.iteri
+ (fun i slot -> match Printexc.Slot.format i slot with
+ | None -> ()
+ | Some line -> print_endline line)
+ trace
+
+let _ =
+ Printexc.record_backtrace true;
+ run [| "a" |];
+ run [| "b" |];
+ run [| "c" |];
+ run [| "d" |];
+ run [| |]
diff --git a/testsuite/tests/backtrace/backtrace_deprecated.reference b/testsuite/tests/backtrace/backtrace_deprecated.reference
new file mode 100644
index 0000000000..e9fea9ffe5
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace_deprecated.reference
@@ -0,0 +1,27 @@
+a
+No exception
+b
+Uncaught exception Backtrace_deprecated.Error("b")
+Raised at file "backtrace_deprecated.ml", line 21, characters 21-32
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 25, characters 4-11
+Re-raised at file "backtrace_deprecated.ml", line 27, characters 68-71
+Called from file "backtrace_deprecated.ml", line 32, characters 11-23
+Uncaught exception Backtrace_deprecated.Error("c")
+Raised at file "backtrace_deprecated.ml", line 28, characters 26-37
+Called from file "backtrace_deprecated.ml", line 32, characters 11-23
+Uncaught exception Backtrace_deprecated.Error("d")
+Raised at file "backtrace_deprecated.ml", line 21, characters 21-32
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 21, characters 42-53
+Called from file "backtrace_deprecated.ml", line 25, characters 4-11
+Called from file "backtrace_deprecated.ml", line 32, characters 11-23
+Uncaught exception Invalid_argument("index out of bounds")
+Raised by primitive operation at file "backtrace_deprecated.ml", line 32, characters 14-22
diff --git a/testsuite/tests/backtrace/backtrace_slots.ml b/testsuite/tests/backtrace/backtrace_slots.ml
new file mode 100644
index 0000000000..8419c61905
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace_slots.ml
@@ -0,0 +1,72 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2008 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A test for stack backtraces *)
+
+let get_backtrace () =
+ let raw_backtrace = Printexc.get_raw_backtrace () in
+ let raw_slots =
+ Array.init (Printexc.raw_backtrace_length raw_backtrace)
+ (Printexc.get_raw_backtrace_slot raw_backtrace) in
+ let convert = Printexc.convert_raw_backtrace_slot in
+ let backtrace = Array.map convert raw_slots in
+ (* we'll play with raw slots a bit to check that hashing and comparison work:
+ - create a hashtable that maps slots to their index in the raw backtrace
+ - create a balanced set of all slots
+ *)
+ let table = Hashtbl.create 100 in
+ Array.iteri (fun i slot -> Hashtbl.add table slot i) raw_slots;
+ let module S = Set.Make(struct
+ type t = Printexc.raw_backtrace_slot
+ let compare = Pervasives.compare
+ end) in
+ let slots = Array.fold_right S.add raw_slots S.empty in
+ Array.iteri (fun i slot ->
+ assert (S.mem slot slots);
+ assert (Hashtbl.mem table slot);
+ let j =
+ (* position in the table of the last slot equal to [slot] *)
+ Hashtbl.find table slot in
+ assert (slot = raw_slots.(j));
+ assert (backtrace.(i) = backtrace.(j));
+ ) raw_slots;
+ backtrace
+
+exception Error of string
+
+let rec f msg n =
+ if n = 0 then raise(Error msg) else 1 + f msg (n-1)
+
+let g msg =
+ try
+ f msg 5
+ with Error "a" -> print_string "a"; print_newline(); 0
+ | Error "b" as exn -> print_string "b"; print_newline(); raise exn
+ | Error "c" -> raise (Error "c")
+
+let run args =
+ try
+ ignore (g args.(0)); print_string "No exception\n"
+ with exn ->
+ Printf.printf "Uncaught exception %s\n" (Printexc.to_string exn);
+ get_backtrace () |> Array.iteri
+ (fun i slot -> match Printexc.Slot.format i slot with
+ | None -> ()
+ | Some line -> print_endline line)
+
+let _ =
+ Printexc.record_backtrace true;
+ run [| "a" |];
+ run [| "b" |];
+ run [| "c" |];
+ run [| "d" |];
+ run [| |]
diff --git a/testsuite/tests/backtrace/backtrace_slots.reference b/testsuite/tests/backtrace/backtrace_slots.reference
new file mode 100644
index 0000000000..2336cd5ac3
--- /dev/null
+++ b/testsuite/tests/backtrace/backtrace_slots.reference
@@ -0,0 +1,27 @@
+a
+No exception
+b
+Uncaught exception Backtrace_slots.Error("b")
+Raised at file "backtrace_slots.ml", line 47, characters 21-32
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 51, characters 4-11
+Re-raised at file "backtrace_slots.ml", line 53, characters 68-71
+Called from file "backtrace_slots.ml", line 58, characters 11-23
+Uncaught exception Backtrace_slots.Error("c")
+Raised at file "backtrace_slots.ml", line 54, characters 26-37
+Called from file "backtrace_slots.ml", line 58, characters 11-23
+Uncaught exception Backtrace_slots.Error("d")
+Raised at file "backtrace_slots.ml", line 47, characters 21-32
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 47, characters 42-53
+Called from file "backtrace_slots.ml", line 51, characters 4-11
+Called from file "backtrace_slots.ml", line 58, characters 11-23
+Uncaught exception Invalid_argument("index out of bounds")
+Raised by primitive operation at file "backtrace_slots.ml", line 58, characters 14-22
diff --git a/testsuite/tests/backtrace/backtraces_and_finalizers.ml b/testsuite/tests/backtrace/backtraces_and_finalizers.ml
new file mode 100644
index 0000000000..22acf1af82
--- /dev/null
+++ b/testsuite/tests/backtrace/backtraces_and_finalizers.ml
@@ -0,0 +1,25 @@
+let () = Printexc.record_backtrace true
+
+let finaliser _ = try raise Exit with _ -> ()
+
+let create () =
+ let x = ref () in
+ Gc.finalise finaliser x;
+ x
+
+let f () = raise Exit
+
+let () =
+ let minor_size = (Gc.get ()).Gc.minor_heap_size in
+ for i = 1 to 100 do
+ Gc.minor ();
+ try
+ ignore (create () : unit ref);
+ f ()
+ with _ ->
+ for i = 1 to minor_size / 2 - 1 do
+ ignore (ref ())
+ done;
+ ignore (Printexc.get_backtrace () : string)
+ done;
+ Printf.printf "ok\n"
diff --git a/testsuite/tests/backtrace/backtraces_and_finalizers.reference b/testsuite/tests/backtrace/backtraces_and_finalizers.reference
new file mode 100644
index 0000000000..9766475a41
--- /dev/null
+++ b/testsuite/tests/backtrace/backtraces_and_finalizers.reference
@@ -0,0 +1 @@
+ok
diff --git a/testsuite/tests/backtrace/raw_backtrace.ml b/testsuite/tests/backtrace/raw_backtrace.ml
new file mode 100644
index 0000000000..f271f759d5
--- /dev/null
+++ b/testsuite/tests/backtrace/raw_backtrace.ml
@@ -0,0 +1,52 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2008 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A test for stack backtraces *)
+
+exception Error of string
+
+let rec f msg n =
+ if n = 0 then raise(Error msg) else 1 + f msg (n-1)
+
+let g msg =
+ try
+ f msg 5
+ with Error "a" -> print_string "a"; print_newline(); 0
+ | Error "b" as exn -> print_string "b"; print_newline(); raise exn
+ | Error "c" -> raise (Error "c")
+
+let backtrace args =
+ try
+ ignore (g args.(0)); None
+ with exn ->
+ let exn = Printexc.to_string exn in
+ let trace = Printexc.get_raw_backtrace () in
+ Some (exn, trace)
+
+let run args =
+ match backtrace args with
+ | None -> print_string "No exception\n"
+ | Some (exn, trace) ->
+ begin
+ (* raise another exception to stash the global backtrace *)
+ try ignore (f "c" 5); assert false with Error _ -> ();
+ end;
+ Printf.printf "Uncaught exception %s\n" exn;
+ Printexc.print_raw_backtrace stdout trace
+
+let _ =
+ Printexc.record_backtrace true;
+ run [| "a" |];
+ run [| "b" |];
+ run [| "c" |];
+ run [| "d" |];
+ run [| |]
diff --git a/testsuite/tests/backtrace/raw_backtrace.reference b/testsuite/tests/backtrace/raw_backtrace.reference
new file mode 100644
index 0000000000..96fb60e8c2
--- /dev/null
+++ b/testsuite/tests/backtrace/raw_backtrace.reference
@@ -0,0 +1,27 @@
+a
+No exception
+b
+Uncaught exception Raw_backtrace.Error("b")
+Raised at file "raw_backtrace.ml", line 18, characters 21-32
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 22, characters 4-11
+Re-raised at file "raw_backtrace.ml", line 24, characters 68-71
+Called from file "raw_backtrace.ml", line 29, characters 11-23
+Uncaught exception Raw_backtrace.Error("c")
+Raised at file "raw_backtrace.ml", line 25, characters 26-37
+Called from file "raw_backtrace.ml", line 29, characters 11-23
+Uncaught exception Raw_backtrace.Error("d")
+Raised at file "raw_backtrace.ml", line 18, characters 21-32
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 18, characters 42-53
+Called from file "raw_backtrace.ml", line 22, characters 4-11
+Called from file "raw_backtrace.ml", line 29, characters 11-23
+Uncaught exception Invalid_argument("index out of bounds")
+Raised by primitive operation at file "raw_backtrace.ml", line 29, characters 14-22
diff --git a/testsuite/tests/basic-float/Makefile b/testsuite/tests/basic-float/Makefile
new file mode 100644
index 0000000000..8214dfa227
--- /dev/null
+++ b/testsuite/tests/basic-float/Makefile
@@ -0,0 +1,18 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=float_record
+MAIN_MODULE=tfloat_record
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/basic-float/float_record.ml b/testsuite/tests/basic-float/float_record.ml
new file mode 100644
index 0000000000..65ef1a6535
--- /dev/null
+++ b/testsuite/tests/basic-float/float_record.ml
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type t = float;;
+
+let make f = f;;
+
+let from t = t;;
+
+type s = {f : t};;
diff --git a/testsuite/tests/basic-float/float_record.mli b/testsuite/tests/basic-float/float_record.mli
new file mode 100644
index 0000000000..5dfd7a843b
--- /dev/null
+++ b/testsuite/tests/basic-float/float_record.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type t = private float;;
+
+val make : float -> t;;
+val from : t -> float;;
+
+type s = {f : t};;
diff --git a/testsuite/tests/basic-float/tfloat_record.ml b/testsuite/tests/basic-float/tfloat_record.ml
new file mode 100644
index 0000000000..36fefaf3d4
--- /dev/null
+++ b/testsuite/tests/basic-float/tfloat_record.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let s = { Float_record.f = Float_record.make 1.0 };;
+
+print_float (Float_record.from s.Float_record.f);;
+print_newline ();;
diff --git a/testsuite/tests/basic-float/tfloat_record.reference b/testsuite/tests/basic-float/tfloat_record.reference
new file mode 100644
index 0000000000..d54c6b66bc
--- /dev/null
+++ b/testsuite/tests/basic-float/tfloat_record.reference
@@ -0,0 +1 @@
+1.
diff --git a/testsuite/tests/basic-io-2/Makefile b/testsuite/tests/basic-io-2/Makefile
new file mode 100644
index 0000000000..e810916c93
--- /dev/null
+++ b/testsuite/tests/basic-io-2/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=io
+EXEC_ARGS=io.ml
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/basic-io-2/io.ml b/testsuite/tests/basic-io-2/io.ml
new file mode 100644
index 0000000000..8c71206a83
--- /dev/null
+++ b/testsuite/tests/basic-io-2/io.ml
@@ -0,0 +1,115 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test a file copy function *)
+
+let test msg funct f1 f2 =
+ print_string msg; print_newline();
+ funct f1 f2;
+ if Sys.command ("cmp " ^ f1 ^ " " ^ f2) = 0
+ then print_string "passed"
+ else print_string "FAILED";
+ print_newline()
+
+(* File copy with constant-sized chunks *)
+
+let copy_file sz infile ofile =
+ let ic = open_in_bin infile in
+ let oc = open_out_bin ofile in
+ let buffer = Bytes.create sz in
+ let rec copy () =
+ let n = input ic buffer 0 sz in
+ if n = 0 then () else begin
+ output oc buffer 0 n;
+ copy ()
+ end in
+ copy();
+ close_in ic;
+ close_out oc
+
+(* File copy with random-sized chunks *)
+
+let copy_random sz infile ofile =
+ let ic = open_in_bin infile in
+ let oc = open_out_bin ofile in
+ let buffer = Bytes.create sz in
+ let rec copy () =
+ let s = 1 + Random.int sz in
+ let n = input ic buffer 0 s in
+ if n = 0 then () else begin
+ output oc buffer 0 n;
+ copy ()
+ end in
+ copy();
+ close_in ic;
+ close_out oc
+
+(* File copy line per line *)
+
+let copy_line infile ofile =
+ let ic = open_in_bin infile in
+ let oc = open_out_bin ofile in
+ try
+ while true do
+ output_string oc (input_line ic); output_char oc '\n'
+ done
+ with End_of_file ->
+ close_in ic;
+ close_out oc
+
+(* Backward copy, with lots of seeks *)
+
+let copy_seek chunksize infile ofile =
+ let ic = open_in_bin infile in
+ let oc = open_out_bin ofile in
+ let size = in_channel_length ic in
+ let buffer = Bytes.create chunksize in
+ for i = (size - 1) / chunksize downto 0 do
+ seek_in ic (i * chunksize);
+ seek_out oc (i * chunksize);
+ let n = input ic buffer 0 chunksize in
+ output oc buffer 0 n
+ done;
+ close_in ic;
+ close_out oc
+
+(* Create long lines of text *)
+
+let make_lines ofile =
+ let oc = open_out_bin ofile in
+ for i = 1 to 256 do
+ output_string oc (String.make (i*64) '.'); output_char oc '\n'
+ done;
+ close_out oc
+
+(* The test *)
+
+let _ =
+ let src = Sys.argv.(1) in
+ let testio = Filename.temp_file "testio" "" in
+ let lines = Filename.temp_file "lines" "" in
+ test "16-byte chunks" (copy_file 16) src testio;
+ test "256-byte chunks" (copy_file 256) src testio;
+ test "4096-byte chunks" (copy_file 4096) src testio;
+ test "65536-byte chunks" (copy_file 65536) src testio;
+ test "19-byte chunks" (copy_file 19) src testio;
+ test "263-byte chunks" (copy_file 263) src testio;
+ test "4011-byte chunks" (copy_file 4011) src testio;
+ test "0...8192 byte chunks" (copy_random 8192) src testio;
+ test "line per line, short lines" copy_line "test-file-short-lines" testio;
+ make_lines lines;
+ test "line per line, short and long lines" copy_line lines testio;
+ test "backwards, 4096-byte chunks" (copy_seek 4096) src testio;
+ test "backwards, 64-byte chunks" (copy_seek 64) src testio;
+ Sys.remove lines;
+ Sys.remove testio;
+ exit 0
diff --git a/testsuite/tests/basic-io-2/io.reference b/testsuite/tests/basic-io-2/io.reference
new file mode 100644
index 0000000000..06740020a7
--- /dev/null
+++ b/testsuite/tests/basic-io-2/io.reference
@@ -0,0 +1,24 @@
+16-byte chunks
+passed
+256-byte chunks
+passed
+4096-byte chunks
+passed
+65536-byte chunks
+passed
+19-byte chunks
+passed
+263-byte chunks
+passed
+4011-byte chunks
+passed
+0...8192 byte chunks
+passed
+line per line, short lines
+passed
+line per line, short and long lines
+passed
+backwards, 4096-byte chunks
+passed
+backwards, 64-byte chunks
+passed
diff --git a/testsuite/tests/basic-io-2/test-file-short-lines b/testsuite/tests/basic-io-2/test-file-short-lines
new file mode 100644
index 0000000000..9c0f7b97e8
--- /dev/null
+++ b/testsuite/tests/basic-io-2/test-file-short-lines
@@ -0,0 +1,10 @@
+##
+# Host Database
+#
+# localhost is used to configure the loopback interface
+# when the system is booting. Do not change this entry.
+##
+127.0.0.1 localhost
+255.255.255.255 broadcasthost
+::1 localhost
+fe80::1%lo0 localhost
diff --git a/testsuite/tests/basic-io/Makefile b/testsuite/tests/basic-io/Makefile
new file mode 100644
index 0000000000..3f9c10ed9f
--- /dev/null
+++ b/testsuite/tests/basic-io/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=wc
+EXEC_ARGS=wc.ml
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/basic-io/wc.ml b/testsuite/tests/basic-io/wc.ml
new file mode 100644
index 0000000000..d6655a9460
--- /dev/null
+++ b/testsuite/tests/basic-io/wc.ml
@@ -0,0 +1,66 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Counts characters, lines and words in one or several files. *)
+
+let chars = ref 0
+and words = ref 0
+and lines = ref 0
+
+type state = Inside_word | Outside_word
+
+let count_channel in_channel =
+ let rec count status =
+ let c = input_char in_channel in
+ incr chars;
+ match c with
+ '\n' ->
+ incr lines; count Outside_word
+ | ' ' | '\t' ->
+ count Outside_word
+ | _ ->
+ if status = Outside_word then begin incr words; () end;
+ count Inside_word
+ in
+ try
+ count Outside_word
+ with End_of_file ->
+ ()
+
+let count_file name =
+ let ic = open_in name in
+ count_channel ic;
+ close_in ic
+
+let print_result () =
+ print_int !chars; print_string " characters, ";
+ print_int !words; print_string " words, ";
+ print_int !lines; print_string " lines";
+ print_newline()
+
+let count name =
+ count_file name;
+ print_result ()
+
+let _ =
+try
+ if Array.length Sys.argv <= 1 then
+ count_channel stdin (* No command-line arguments *)
+ else
+ for i = 1 to Array.length Sys.argv - 1 do
+ count_file Sys.argv.(i)
+ done;
+ print_result ()
+with Sys_error s ->
+ print_string "I/O error: ";
+ print_string s;
+ print_newline()
diff --git a/testsuite/tests/basic-io/wc.reference b/testsuite/tests/basic-io/wc.reference
new file mode 100644
index 0000000000..adaaa750b4
--- /dev/null
+++ b/testsuite/tests/basic-io/wc.reference
@@ -0,0 +1 @@
+2013 characters, 233 words, 66 lines
diff --git a/testsuite/tests/basic-manyargs/Makefile b/testsuite/tests/basic-manyargs/Makefile
new file mode 100644
index 0000000000..3cf4a15e80
--- /dev/null
+++ b/testsuite/tests/basic-manyargs/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=manyargs
+C_FILES=manyargsprim
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/basic-manyargs/manyargs.ml b/testsuite/tests/basic-manyargs/manyargs.ml
new file mode 100644
index 0000000000..3defdf201f
--- /dev/null
+++ b/testsuite/tests/basic-manyargs/manyargs.ml
@@ -0,0 +1,57 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let manyargs a b c d e f g h i j k l m n o =
+ print_string "a = "; print_int a; print_newline();
+ print_string "b = "; print_int b; print_newline();
+ print_string "c = "; print_int c; print_newline();
+ print_string "d = "; print_int d; print_newline();
+ print_string "e = "; print_int e; print_newline();
+ print_string "f = "; print_int f; print_newline();
+ print_string "g = "; print_int g; print_newline();
+ print_string "h = "; print_int h; print_newline();
+ print_string "i = "; print_int i; print_newline();
+ print_string "j = "; print_int j; print_newline();
+ print_string "k = "; print_int k; print_newline();
+ print_string "l = "; print_int l; print_newline();
+ print_string "m = "; print_int m; print_newline();
+ print_string "n = "; print_int n; print_newline();
+ print_string "o = "; print_int o; print_newline();
+ print_string "---"; print_newline()
+
+let manyargs_tail1 a b c d e f g h i j k l m n o =
+ print_string "tail1:\n";
+ manyargs a b c d e f g h i j k l m n o
+
+let manyargs_tail2 a b =
+ print_string "tail2:\n";
+ manyargs a b a b a b a b a b a b a b a
+
+let manyargs_tail3 a b c d e f g h i j k l m n o =
+ print_string "tail3:\n";
+ print_string "o = "; print_int o; print_newline();
+ print_string "---"; print_newline()
+
+let _ =
+ manyargs 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15;
+ manyargs_tail1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15;
+ manyargs_tail2 0 1;
+ manyargs_tail3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
+
+external manyargs_ext:
+ int -> int -> int -> int -> int -> int -> int -> int -> int -> int -> int ->
+ int
+ = "manyargs_argv" "manyargs"
+
+let _ =
+ print_string "external:\n"; flush stdout;
+ manyargs_ext 1 2 3 4 5 6 7 8 9 10 11
diff --git a/testsuite/tests/basic-manyargs/manyargs.reference b/testsuite/tests/basic-manyargs/manyargs.reference
new file mode 100644
index 0000000000..24e9d3df3c
--- /dev/null
+++ b/testsuite/tests/basic-manyargs/manyargs.reference
@@ -0,0 +1,65 @@
+a = 1
+b = 2
+c = 3
+d = 4
+e = 5
+f = 6
+g = 7
+h = 8
+i = 9
+j = 10
+k = 11
+l = 12
+m = 13
+n = 14
+o = 15
+---
+tail1:
+a = 1
+b = 2
+c = 3
+d = 4
+e = 5
+f = 6
+g = 7
+h = 8
+i = 9
+j = 10
+k = 11
+l = 12
+m = 13
+n = 14
+o = 15
+---
+tail2:
+a = 0
+b = 1
+c = 0
+d = 1
+e = 0
+f = 1
+g = 0
+h = 1
+i = 0
+j = 1
+k = 0
+l = 1
+m = 0
+n = 1
+o = 0
+---
+tail3:
+o = 15
+---
+external:
+a = 1
+b = 2
+c = 3
+d = 4
+e = 5
+f = 6
+g = 7
+h = 8
+i = 9
+j = 10
+k = 11
diff --git a/testsuite/tests/basic-manyargs/manyargsprim.c b/testsuite/tests/basic-manyargs/manyargsprim.c
new file mode 100644
index 0000000000..55fbc2e03d
--- /dev/null
+++ b/testsuite/tests/basic-manyargs/manyargsprim.c
@@ -0,0 +1,37 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1995 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include "caml/mlvalues.h"
+#include "stdio.h"
+
+value manyargs(value a, value b, value c, value d, value e, value f,
+ value g, value h, value i, value j, value k)
+{
+ printf("a = %d\n", Int_val(a));
+ printf("b = %d\n", Int_val(b));
+ printf("c = %d\n", Int_val(c));
+ printf("d = %d\n", Int_val(d));
+ printf("e = %d\n", Int_val(e));
+ printf("f = %d\n", Int_val(f));
+ printf("g = %d\n", Int_val(g));
+ printf("h = %d\n", Int_val(h));
+ printf("i = %d\n", Int_val(i));
+ printf("j = %d\n", Int_val(j));
+ printf("k = %d\n", Int_val(k));
+ return Val_unit;
+}
+
+value manyargs_argv(value *argv, int argc)
+{
+ return manyargs(argv[0], argv[1], argv[2], argv[3], argv[4],
+ argv[5], argv[6], argv[7], argv[8], argv[9], argv[10]);
+}
diff --git a/testsuite/tests/basic-modules/Makefile b/testsuite/tests/basic-modules/Makefile
new file mode 100644
index 0000000000..4c13f27247
--- /dev/null
+++ b/testsuite/tests/basic-modules/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+MODULES=offset pr6726
+MAIN_MODULE=main
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/basic-modules/main.ml b/testsuite/tests/basic-modules/main.ml
new file mode 100644
index 0000000000..aee809319f
--- /dev/null
+++ b/testsuite/tests/basic-modules/main.ml
@@ -0,0 +1,26 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Nagoya University *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* PR#6435 *)
+
+module F (M : sig
+ type t
+ module Set : Set.S with type elt = t
+ end) =
+struct
+ let test set = Printf.printf "%d\n" (M.Set.cardinal set)
+end
+
+module M = F (Offset)
+
+let () = M.test (Offset.M.Set.singleton "42")
+let v = Pr6726.Test.v
diff --git a/testsuite/tests/basic-modules/main.reference b/testsuite/tests/basic-modules/main.reference
new file mode 100644
index 0000000000..d00491fd7e
--- /dev/null
+++ b/testsuite/tests/basic-modules/main.reference
@@ -0,0 +1 @@
+1
diff --git a/testsuite/tests/basic-modules/offset.ml b/testsuite/tests/basic-modules/offset.ml
new file mode 100644
index 0000000000..a2b380410e
--- /dev/null
+++ b/testsuite/tests/basic-modules/offset.ml
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Nagoya University *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+module M = struct
+ type t = string
+
+ let x = 0
+ let x = 1
+
+ module Set = Set.Make(String)
+end
+
+include M
diff --git a/testsuite/tests/basic-modules/pr6726.ml b/testsuite/tests/basic-modules/pr6726.ml
new file mode 100644
index 0000000000..1c8f150bc0
--- /dev/null
+++ b/testsuite/tests/basic-modules/pr6726.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Nagoya University *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+module ExtUnixAll = struct
+ external unused : unit -> unit = "caml_blit_string"
+ module BigEndian = struct
+ let get_uint8 str off = 33
+ end
+end
+
+module ExtUnix = struct
+ module All = ExtUnixAll
+end
+
+module Test = struct
+ open ExtUnix.All
+ let test_endian_string x =
+ let module B = BigEndian in
+ B.get_uint8 x 0
+ let v = test_endian_string 1
+end
diff --git a/testsuite/tests/basic-more/Makefile b/testsuite/tests/basic-more/Makefile
new file mode 100644
index 0000000000..f6e6659719
--- /dev/null
+++ b/testsuite/tests/basic-more/Makefile
@@ -0,0 +1,18 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=testing
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
+OCOPTFLAGS=-inline 20
diff --git a/testsuite/tests/basic-more/bounds.ml b/testsuite/tests/basic-more/bounds.ml
new file mode 100644
index 0000000000..0b30d834d0
--- /dev/null
+++ b/testsuite/tests/basic-more/bounds.ml
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test bound checks with ocamlopt *)
+
+let a = [| 0; 1; 2 |]
+
+let trail = ref []
+
+let test n =
+ let result =
+ try
+ trail := n :: !trail; ignore a.(n); "doesn't fail"
+ with Invalid_argument s ->
+ (* Check well-formedness of s *)
+ if String.length s = 19
+ && s = "index out of bounds"
+ then "fails"
+ else "bad Invalid_argument"
+ | _ -> "bad exception"
+ in
+ print_int n; print_string ": "; print_string result; print_newline()
+
+let _ =
+ test 0; test 1; test 2; test 3; test 4; test (-1);
+ Gc.full_major();
+ print_string "Trail:";
+ List.iter (fun n -> print_string " "; print_int n) !trail;
+ print_newline()
diff --git a/testsuite/tests/basic-more/bounds.reference b/testsuite/tests/basic-more/bounds.reference
new file mode 100644
index 0000000000..5d34a60254
--- /dev/null
+++ b/testsuite/tests/basic-more/bounds.reference
@@ -0,0 +1,9 @@
+0: doesn't fail
+1: doesn't fail
+2: doesn't fail
+3: fails
+4: fails
+-1: fails
+Trail: -1 4 3 2 1 0
+
+All tests succeeded.
diff --git a/testsuite/tests/basic-more/morematch.ml b/testsuite/tests/basic-more/morematch.ml
new file mode 100644
index 0000000000..e433e0771e
--- /dev/null
+++ b/testsuite/tests/basic-more/morematch.ml
@@ -0,0 +1,1201 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(**************************************************************)
+(* This suite tests the pattern-matching compiler *)
+(* it should just compile and run. *)
+(* While compiling the following messages are normal: *)
+(**************************************************************)
+
+(*
+File "morematch.ml", line 38, characters 10-93:
+Warning: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+0
+File "morematch.ml", line 376, characters 2-15:
+Warning: this match case is unused.
+File "morematch.ml", line 443, characters 2-7:
+Warning: this match case is unused.
+*)
+
+let test msg f arg r =
+ if f arg <> r then begin
+ prerr_endline msg ;
+ failwith "Malaise"
+ end
+;;
+
+type t = A | B | C | D | E | F
+ ;;
+
+let f x = match x with
+| A | B | C -> 1
+| D | E -> 2
+| F -> 3;;
+
+test "un" f C 1 ;
+test "un" f D 2 ;
+test "un" f F 3 ; ()
+;;
+
+let g x = match x with
+ 1 -> 1
+| 2 -> 2
+| 3 -> 3
+| 4 | 5 -> 4
+| 6 -> 5
+| 7 | 8 -> 6
+| 9 -> 7
+| _ -> assert false
+;;
+
+test "deux" g 5 4 ;
+test "deux" g 6 5 ;
+test "deux" g 9 7 ; ()
+;;
+
+
+let g x = match x with
+ 1 -> 1
+| 2 -> 2
+| 3 -> 3
+| 4 | 5 -> 4
+| 6 -> 5
+| 7 | 8 -> 6
+| 9 -> 7
+| _ -> 8;;
+
+test "trois" g 10 8
+;;
+
+let g x= match x with
+ 1 -> 1
+| 2 -> 2
+| 3 -> 3
+| 4 | 5 -> 4
+| 6 -> 5
+| 4|5|7 -> 100
+| 7 | 8 -> 6
+| 9 -> 7
+| _ -> 8;;
+test "quatre" g 4 4 ;
+test "quatre" g 7 100 ; ()
+;;
+
+(*
+File "morematch.ml", line 73, characters 2-5:
+Warning U: this sub-pattern is unused.
+File "morematch.ml", line 74, characters 2-3:
+Warning U: this sub-pattern is unused.
+*)
+
+let h x =
+ match x with
+ (1,1) -> 1
+| (2|3), 1 -> 2
+| 2,(2|3) -> 3
+| (4,4) -> 5
+| _ -> 100
+;;
+
+test "cinq" h (2,2) 3 ;
+test "cinq" h (2,1) 2 ;
+test "cinq" h (2,4) 100 ; ()
+;;
+
+(* idem hh (2,5) *)
+
+let hh x = match x with
+| 1,1 -> 1
+| 2,1 -> 2
+| (2|3),(1|2|3|4) -> 3
+| 2,5 -> 4
+| (4,4) -> 5
+| _ -> 100
+;;
+
+let hhh x = match x with
+| 1,1 -> 1
+| (2|3),1 -> 2
+| 2,2 -> 3
+| _ -> 100
+;;
+
+let h x =
+ match x with
+ (1,1) -> 1
+| 3,1 -> 2
+| 2,(2|3) -> 3
+| (4,4) -> 5
+| _ -> 100
+;;
+
+let h x = match x with
+ 1 -> 1
+| 2|3 -> 2
+| 4 -> 4
+| 5 -> 5
+| 6|7 -> 6
+| 8 -> 8
+| _ -> 100
+;;
+let f x = match x with
+| ((1|2),(3|4))|((3|4),(1|2)) -> 1
+| (3,(5|6)) -> 2
+| _ -> 3
+;;
+
+test "six" f (1,3) 1 ;
+test "six" f (3,2) 1 ;
+test "six" f (3,5) 2 ;
+test "six" f (3,7) 3 ; ()
+;;
+
+type tt = {a : bool list ; b : bool}
+
+let f = function
+ | {a=([]|[true])} -> 1
+ | {a=false::_}|{b=(true|false)} -> 2
+;;
+
+test "sept" f {a=[] ; b = true} 1 ;
+test "sept" f {a=[true] ; b = false} 1 ;
+test "sept" f {a=[false ; true] ; b = true} 2 ;
+test "sept" f {a=[false] ; b = false} 2 ; ()
+;;
+
+let f = function
+ | (([]|[true]),_) -> 1
+ | (false::_,_)|(_,(true|false)) -> 2
+;;
+
+test "huit" f ([],true) 1 ;
+test "huit" f ([true],false) 1 ;
+test "huit" f ([false ; true], true) 2 ;
+test "huit" f ([false], false) 2 ; ()
+;;
+
+
+let split_cases = function
+ | `Nil | `Cons _ as x -> `A x
+ | `Snoc _ as x -> `B x
+;;
+
+test "oubli" split_cases `Nil (`A `Nil);
+test "oubli" split_cases (`Cons 1) (`A (`Cons 1));
+test "oubli" split_cases (`Snoc 1) (`B (`Snoc 1)) ; ()
+;;
+
+type t1 = A of int | B of int
+let f1 = function
+ | (A x | B x) -> x
+;;
+
+test "neuf" f1 (A 1) 1 ;
+test "neuf" f1 (B 1) 1 ;
+;;
+
+type coucou = A of int | B of int * int | C
+;;
+
+
+let g = function
+ | (A x | B (_,x)) -> x
+ | C -> 0
+;;
+
+
+test "dix" g (A 1) 1 ;
+test "dix" g (B (1,2)) 2 ;
+;;
+
+
+
+let h = function
+ | ([x]|[1 ; x ]|[1 ; 2 ; x]) -> x
+ | _ -> 0
+;;
+
+test "encore" h [1] 1 ;
+test "encore" h [1;2] 2 ;
+test "encore" h [1;2;3] 3 ;
+test "encore" h [0 ; 0] 0 ; ()
+;;
+
+let f = function
+| (x,(0 as y)) | (y,x) -> y-x
+;;
+
+test "foo1" f (1,0) (-1);
+test "foo1" f (1,2) (-1)
+;;
+
+
+let f = function (([]|[_]) as x)|(_::([] as x))|(_::_::x) -> x
+;;
+
+test "zob" f [] [] ;
+test "zob" f [1] [1] ;
+test "zob" f [1;2;3] [3]
+;;
+
+
+type zob = A | B | C | D of zob * int | E of zob * zob
+
+let rec f = function
+ | (A | B | C) -> A
+ | D (x,i) -> D (f x,i)
+ | E (x,_) -> D (f x,0)
+;;
+
+
+test "fin" f B A ;
+test "fin" f (D (C,1)) (D (A,1)) ;
+test "fin" f (E (C,A)) (D (A,0)) ; ()
+;;
+
+type length =
+ Char of int | Pixel of int | Percent of int | No of string | Default
+
+let length = function
+ | Char n -> n | Pixel n -> n
+ | _ -> 0
+;;
+
+test "length" length (Char 10) 10 ;
+test "length" length (Pixel 20) 20 ;
+test "length" length Default 0 ;
+test "length" length (Percent 100) 0 ; ()
+;;
+
+let length2 = function
+ | Char n -> n | Percent n -> n
+ | _ -> 0
+;;
+
+test "length2" length2 (Char 10) 10 ;
+test "length2" length2 (Pixel 20) 0 ;
+test "length2" length2 Default 0 ;
+test "length2" length2(Percent 100) 100 ; ()
+;;
+
+let length3 = function
+ | Char _ | No _ -> true
+ | _ -> false
+;;
+
+test "length3" length3 (Char 10) true ;
+test "length3" length3 (No "") true ;
+test "length3" length3 (Pixel 20) false ;
+test "length3" length3 Default false ;
+test "length3" length3(Percent 100) false ; ()
+;;
+
+type hevea = A | B | C
+
+let h x = match x with
+| A -> 1
+| B|C -> 2
+;;
+
+test "hevea" h A 1 ;
+test "hevea" h B 2 ;
+test "hevea" h B 2 ; ()
+;;
+type lambda =
+ Lvar of int
+ | Lconst of int
+ | Lapply of lambda * lambda list
+ | Lfunction of bool * int list * lambda
+ | Llet of bool * int * lambda * lambda
+ | Lletrec of (int * lambda) list * lambda
+ | Lprim of string * lambda list
+ | Lswitch of lambda * lambda_switch
+ | Lstaticfail
+ | Lcatch of lambda * lambda
+ | Lstaticraise of int * lambda list
+ | Lstaticcatch of lambda * (int * int list) * lambda
+ | Ltrywith of lambda * int * lambda
+ | Lifthenelse of lambda * lambda * lambda
+ | Lsequence of lambda * lambda
+ | Lwhile of lambda * lambda
+ | Lfor of int * lambda * lambda * bool * lambda
+ | Lassign of int * lambda
+ | Lsend of lambda * lambda * lambda list
+ | Levent of lambda * lambda_event
+ | Lifused of int * lambda
+and lambda_switch =
+ { sw_numconsts: int; (* Number of integer cases *)
+ sw_consts: (int * lambda) list; (* Integer cases *)
+ sw_numblocks: int; (* Number of tag block cases *)
+ sw_blocks: (int * lambda) list; (* Tag block cases *)
+ sw_checked: bool ; (* True if bound checks needed *)
+ sw_nofail: bool} (* True if should not fail *)
+and lambda_event =
+ { lev_loc: int;
+ lev_kind: bool ;
+ lev_repr: int ref option;
+ lev_env: int list }
+
+let rec approx_present v l = true
+
+let rec lower_bind v arg lam = match lam with
+| Lifthenelse (cond, ifso, ifnot) -> 1
+| Lswitch (ls,({sw_consts=[i,act] ; sw_blocks = []} as _sw))
+ when not (approx_present v ls) -> 2
+| Lswitch (ls,({sw_consts=[] ; sw_blocks = [i,act]} as _sw))
+ when not (approx_present v ls) -> 3
+| Llet (true , vv, lv, l) -> 4
+| _ -> 5
+;;
+
+test "lower_bind" (lower_bind 0 0) (Llet (true,0, Lvar 1, Lvar 2)) 4 ;
+test "lower_bind" (lower_bind 0 0) (Lvar 0) 5 ;
+test "lower_bind" (lower_bind 0 0) (Lifthenelse (Lvar 0, Lvar 1, Lvar 2)) 1
+;;
+
+
+type field_kind =
+ Fvar of field_kind option ref
+ | Fpresent
+ | Fabsent
+
+let unify_kind (k1, k2) = match k1, k2 with
+ (Fvar r, (Fvar _ | Fpresent)) -> 1
+ | (Fpresent, Fvar r) -> 2
+ | (Fpresent, Fpresent) -> 3
+ | _ -> 4
+
+
+let r = ref (Some Fpresent)
+;;
+
+test "unify" unify_kind (Fvar r, Fpresent) 1 ;
+test "unify" unify_kind (Fvar r, Fvar r) 1 ;
+test "unify" unify_kind (Fvar r, Fabsent) 4 ;
+test "unify" unify_kind (Fpresent, Fvar r) 2 ;
+test "unify" unify_kind (Fpresent, Fpresent) 3 ;
+test "unify" unify_kind (Fabsent, Fpresent) 4 ; ()
+;;
+
+
+type youyou = A | B | C | D of youyou
+
+let foo (k1, k2) = match k1,k2 with
+| D _, (A|D _) -> 1
+| (A|B),D _ -> 2
+| C,_ -> 3
+| _, (A|B|C) -> 4
+;;
+
+test "foo2" foo (D A,A) 1 ;
+test "foo2" foo (D A,B) 4 ;
+test "foo2" foo (A,A) 4 ; ()
+;;
+
+type yaya = A | B
+;;
+
+let yaya = function
+| A,_,_ -> 1
+| _,A,_ -> 2
+| B,B,_ -> 3
+| A,_,(100|103) -> 5
+;;
+
+test "yaya" yaya (A,A,0) 1 ;
+test "yaya" yaya (B,A,0) 2 ;
+test "yaya" yaya (B,B,100) 3 ; ()
+;;
+
+(*
+let yoyo = function
+| [],_,_ -> 1
+| _,[],_ -> 2
+| _::_,_::_,_ -> 3
+| [],_,(100|103|104) -> 5
+| [],_,(100|103) -> 6
+| [],_,(1000|1001|1002|20000) -> 7
+;;
+
+test "yoyo" yoyo ([],[],0) 1 ;
+test "yoyo" yoyo ([1],[],0) 2 ;
+test "yoyo" yoyo ([1],[1],100) 3 ; ()
+;;
+
+let youyou = function
+ | (100|103|104) -> 1
+ | (100|103|101) -> 2
+ | (1000|1001|1002|20000) -> 3
+ | _ -> -1
+;;
+
+test "youyou" youyou 100 1 ;
+test "youyou" youyou 101 2 ;
+test "youyou" youyou 1000 3
+;;
+*)
+type autre =
+ | C | D | E of autre | F of autre * autre | H of autre | I | J | K of string
+
+let rec autre = function
+| C,_,_ -> 1
+| _,C,_ -> 2
+| D,D,_ -> 3
+| (D|F (_,_)|H _|K _),_,_ -> 4
+| (_, (D|I|E _|F (_, _)|H _|K _), _) -> 8
+| (J,J,((C|D) as x |E x|F (_,x))) | (J,_,((C|J) as x)) -> autre (x,x,x)
+| (J, J, (I|H _|K _)) -> 9
+| I,_,_ -> 6
+| E _,_,_ -> 7
+;;
+(*
+File "morematch.ml", line 437, characters 43-44:
+Warning U: this sub-pattern is unused.
+*)
+test "autre" autre (J,J,F (D,D)) 3 ;
+test "autre" autre (J,J,D) 3 ;
+test "autre" autre (J,J,I) 9 ;
+test "autre" autre (H I,I,I) 4 ;
+test "autre" autre (J,J,H I) 9 ; ()
+;;
+
+
+type youpi = YA | YB | YC
+and hola = X | Y | Z | T of hola | U of hola | V of hola
+
+let xyz = function
+| YA,_,_ -> 1
+| _,YA,_ -> 2
+| YB,YB,_ -> 3
+| ((YB|YC), (YB|YC), (X|Y|Z|V _|T _)) -> 6
+| _,_,(X|U _) -> 8
+| _,_,Y -> 5
+;;
+(*
+File "morematch.ml", line 459, characters 7-8:
+Warning U: this sub-pattern is unused.
+File "morematch.ml", line 460, characters 2-7:
+Warning U: this match case is unused.
+*)
+test "xyz" xyz (YC,YC,X) 6 ;
+test "xyz" xyz (YC,YB,U X) 8 ;
+test "xyz" xyz (YB,YC,X) 6 ; ()
+;;
+
+
+(* Ce test est pour le compilo lui-meme *)
+let eq (x,y) = x=y
+;;
+
+test "eq" eq ("coucou", "coucou") true ; ()
+;;
+
+(* Test des gardes, non trivial *)
+
+let is_none = function
+ | None -> true
+ | _ -> false
+
+let garde x = match x with
+| (Some _, _) when is_none (snd x) -> 1
+| (Some (pc, _), Some pc') when pc = pc' -> 2
+| _ -> 3
+;;
+
+test "garde" garde (Some (1,1),None) 1 ;
+test "garde" garde (Some (1,1),Some 1) 2 ;
+test "garde" garde (Some (2,1),Some 1) 3 ; ()
+;;
+
+let orstring = function
+ | ("A"|"B"|"C") -> 2
+ | "D" -> 3
+ | _ -> 4
+;;
+
+test "orstring" orstring "A" 2 ;
+test "orstring" orstring "B" 2 ;
+test "orstring" orstring "C" 2 ;
+test "orstring" orstring "D" 3 ;
+test "orstring" orstring "E" 4 ; ()
+;;
+
+type var_t = [`Variant of [ `Some of string | `None | `Foo] ]
+
+let crash (pat:var_t) =
+ match pat with
+ | `Variant (`Some tag) -> tag
+ | `Variant (`None) -> "none"
+ | _ -> "foo"
+
+;;
+
+test "crash" crash (`Variant `None) "none" ;
+test "crash" crash (`Variant (`Some "coucou")) "coucou" ;
+test "crash" crash (`Variant (`Foo)) "foo" ; ()
+;;
+
+let flatgarde c =
+let x,y = c in
+match x,y with
+| (1,2)|(2,3) when y=2 -> 1
+| (1,_)|(_,3) -> 2
+| _ -> 3
+;;
+
+test "flatgarde" flatgarde (1,2) 1 ;
+test "flatgarde" flatgarde (1,3) 2 ;
+test "flatgarde" flatgarde (2,3) 2 ;
+test "flatgarde" flatgarde (2,4) 3 ; ()
+;;
+
+
+(* Les bugs de jerome *)
+type f =
+ | ABSENT
+ | FILE
+ | SYMLINK
+ | DIRECTORY
+
+type r =
+ | Unchanged
+ | Deleted
+ | Modified
+ | PropsChanged
+ | Created
+
+let replicaContent2shortString rc =
+ let (typ, status) = rc in
+ match typ, status with
+ _, Unchanged -> " "
+ | ABSENT, Deleted -> "deleted "
+ | FILE, Created -> "new file"
+ | FILE, Modified -> "changed "
+ | FILE, PropsChanged -> "props "
+ | SYMLINK, Created -> "new link"
+ | SYMLINK, Modified -> "chgd lnk"
+ | DIRECTORY, Created -> "new dir "
+ | DIRECTORY, Modified -> "chgd dir"
+ | DIRECTORY, PropsChanged -> "props "
+ (* Cases that can't happen... *)
+
+ | ABSENT, (Created | Modified | PropsChanged)
+ | SYMLINK, PropsChanged
+ | (FILE|SYMLINK|DIRECTORY), Deleted
+ -> "assert false"
+;;
+
+
+test "jerome_constr"
+ replicaContent2shortString (ABSENT, Unchanged) " " ;
+test "jerome_constr"
+ replicaContent2shortString (ABSENT, Deleted) "deleted " ;
+test "jerome_constr"
+ replicaContent2shortString (FILE, Modified) "changed " ;
+test "jerome_constr"
+ replicaContent2shortString (DIRECTORY, PropsChanged) "props " ;
+test "jerome_constr"
+ replicaContent2shortString (FILE, Deleted) "assert false" ;
+test "jerome_constr"
+ replicaContent2shortString (SYMLINK, Deleted) "assert false" ;
+test "jerome_constr"
+ replicaContent2shortString (SYMLINK, PropsChanged) "assert false" ;
+test "jerome_constr"
+ replicaContent2shortString (DIRECTORY, Deleted) "assert false" ;
+test "jerome_constr"
+ replicaContent2shortString (ABSENT, Created) "assert false" ;
+test "jerome_constr"
+ replicaContent2shortString (ABSENT, Modified) "assert false" ;
+test "jerome_constr"
+ replicaContent2shortString (ABSENT, PropsChanged) "assert false" ;
+;;
+
+
+let replicaContent2shortString rc =
+ let (typ, status) = rc in
+ match typ, status with
+ _, `Unchanged -> " "
+ | `ABSENT, `Deleted -> "deleted "
+ | `FILE, `Created -> "new file"
+ | `FILE, `Modified -> "changed "
+ | `FILE, `PropsChanged -> "props "
+ | `SYMLINK, `Created -> "new link"
+ | `SYMLINK, `Modified -> "chgd lnk"
+ | `DIRECTORY, `Created -> "new dir "
+ | `DIRECTORY, `Modified -> "chgd dir"
+ | `DIRECTORY, `PropsChanged -> "props "
+ (* Cases that can't happen... *)
+
+ | `ABSENT, (`Created | `Modified | `PropsChanged)
+ | `SYMLINK, `PropsChanged
+ | (`FILE|`SYMLINK|`DIRECTORY), `Deleted
+ -> "assert false"
+;;
+
+
+test "jerome_variant"
+ replicaContent2shortString (`ABSENT, `Unchanged) " " ;
+test "jerome_variant"
+ replicaContent2shortString (`ABSENT, `Deleted) "deleted " ;
+test "jerome_variant"
+ replicaContent2shortString (`FILE, `Modified) "changed " ;
+test "jerome_variant"
+ replicaContent2shortString (`DIRECTORY, `PropsChanged) "props " ;
+test "jerome_variant"
+ replicaContent2shortString (`FILE, `Deleted) "assert false" ;
+test "jerome_variant"
+ replicaContent2shortString (`SYMLINK, `Deleted) "assert false" ;
+test "jerome_variant"
+ replicaContent2shortString (`SYMLINK, `PropsChanged) "assert false" ;
+test "jerome_variant"
+ replicaContent2shortString (`DIRECTORY, `Deleted) "assert false" ;
+test "jerome_variant"
+ replicaContent2shortString (`ABSENT, `Created) "assert false" ;
+test "jerome_variant"
+ replicaContent2shortString (`ABSENT, `Modified) "assert false" ;
+test "jerome_variant"
+ replicaContent2shortString (`ABSENT, `PropsChanged) "assert false" ;
+;;
+
+(* bug 319 *)
+
+type ab = A of int | B of int
+type cd = C | D
+
+let ohl = function
+ | (A (p) | B (p)), C -> p
+ | (A (p) | B (p)), D -> p
+;;
+
+test "ohl" ohl (A 0,C) 0 ;
+test "ohl" ohl (B 0,D) 0 ; ()
+;;
+
+(* bug 324 *)
+type pottier =
+ | A
+ | B
+;;
+
+let pottier x =
+ match x with
+ | (( (A, 1) | (B, 2)),A) -> false
+ | _ -> true
+;;
+
+test "pottier" pottier ((B,2),A) false ;
+test "pottier" pottier ((B,2),B) true ;
+test "pottier" pottier ((A,2),A) true ; ()
+;;
+
+(* bug 325 in bytecode compiler *)
+let coquery q = match q with
+| y,0,([modu;defs]| [defs;modu;_]) -> y+defs-modu
+| _ -> 0
+;;
+
+test "coquery" coquery (1,0,[1 ; 2 ; 3]) 0 ;
+test "coquery" coquery (1,0,[1 ; 2]) 2 ; ()
+;;
+
+(*
+ Two other variable in or-pat tests
+*)
+type vars = A of int | B of (int * int) | C
+;;
+
+
+let vars1 = function
+ | (A x | B (_,x)) -> x
+ | C -> 0
+;;
+
+test "vars1" vars1 (A 1) 1 ;
+test "vars1" vars1 (B (1,2)) 2 ; ()
+;;
+
+let vars2 = function
+ | ([x]|[1 ; x ]|[1 ; 2 ; x]) -> x
+ | _ -> 0
+;;
+
+test"vars2" vars2 [1] 1 ;
+test"vars2" vars2 [1;2] 2 ;
+test"vars2" vars2 [1;2;3] 3 ;
+test"vars2" vars2 [0 ; 0] 0 ; ()
+;;
+
+(* Bug 342 *)
+type eber = {x:int; y: int; z:bool}
+
+let eber = function
+ | {x=a; z=true}
+ | {y=a; z=false} -> a
+;;
+
+test "eber" eber {x=0 ; y=1 ; z=true} 0 ;
+test "eber" eber {x=1 ; y=0 ; z=false} 0 ; ()
+;;
+
+
+(* Enchainement des test d'intervalle *)
+
+let escaped = function
+ | '\"' | '\\' | '\n' | '\t' -> 2
+ | c -> 1
+;;
+
+test "escaped" escaped '\"' 2 ;
+test "escaped" escaped '\\' 2 ;
+test "escaped" escaped '\n' 2 ;
+test "escaped" escaped '\t' 2 ;
+test "escaped" escaped '\000' 1 ;
+test "escaped" escaped ' ' 1 ;
+test "escaped" escaped '\000' 1 ;
+test "escaped" escaped '[' 1 ;
+test "escaped" escaped ']' 1 ;
+test "escaped" escaped '!' 1 ;
+test "escaped" escaped '#' 1 ;
+()
+;;
+
+(* For compilation speed (due to J. Garigue) *)
+exception Unknown_Reply of int
+
+type command_reply =
+ RPL_TRYAGAIN
+ | RPL_TRACEEND
+ | RPL_TRACELOG
+ | RPL_ADMINEMAIL
+ | RPL_ADMINLOC2
+ | RPL_ADMINLOC1
+ | RPL_ADMINME
+ | RPL_LUSERME
+ | RPL_LUSERCHANNELS
+ | RPL_LUSERUNKNOWN
+ | RPL_LUSEROP
+ | RPL_LUSERCLIENT
+ | RPL_STATSDLINE
+ | RPL_STATSDEBUG
+ | RPL_STATSDEFINE
+ | RPL_STATSBLINE
+ | RPL_STATSPING
+ | RPL_STATSSLINE
+ | RPL_STATSHLINE
+ | RPL_STATSOLINE
+ | RPL_STATSUPTIME
+ | RPL_STATSLLINE
+ | RPL_STATSVLINE
+ | RPL_SERVLISTEND
+ | RPL_SERVLIST
+ | RPL_SERVICE
+ | RPL_ENDOFSERVICES
+ | RPL_SERVICEINFO
+ | RPL_UMODEIS
+ | RPL_ENDOFSTATS
+ | RPL_STATSYLINE
+ | RPL_STATSQLINE
+ | RPL_STATSKLINE
+ | RPL_STATSILINE
+ | RPL_STATSNLINE
+ | RPL_STATSCLINE
+ | RPL_STATSCOMMANDS
+ | RPL_STATSLINKINFO
+ | RPL_TRACERECONNECT
+ | RPL_TRACECLASS
+ | RPL_TRACENEWTYPE
+ | RPL_TRACESERVICE
+ | RPL_TRACESERVER
+ | RPL_TRACEUSER
+ | RPL_TRACEOPERATOR
+ | RPL_TRACEUNKNOWN
+ | RPL_TRACEHANDSHAKE
+ | RPL_TRACECONNECTING
+ | RPL_TRACELINK
+ | RPL_NOUSERS
+ | RPL_ENDOFUSERS
+ | RPL_USERS
+ | RPL_USERSSTART
+ | RPL_TIME
+ | RPL_NOTOPERANYMORE
+ | RPL_MYPORTIS
+ | RPL_YOURESERVICE
+ | RPL_REHASHING
+ | RPL_YOUREOPER
+ | RPL_ENDOFMOTD
+ | RPL_MOTDSTART
+ | RPL_ENDOFINFO
+ | RPL_INFOSTART
+ | RPL_MOTD
+ | RPL_INFO
+ | RPL_ENDOFBANLIST
+ | RPL_BANLIST
+ | RPL_ENDOFLINKS
+ | RPL_LINKS
+ | RPL_CLOSEEND
+ | RPL_CLOSING
+ | RPL_KILLDONE
+ | RPL_ENDOFNAMES
+ | RPL_NAMREPLY
+ | RPL_ENDOFWHO
+ | RPL_WHOREPLY
+ | RPL_VERSION
+ | RPL_SUMMONING
+ | RPL_INVITING
+ | RPL_TOPIC
+ | RPL_NOTOPIC
+ | RPL_CHANNELMODEIS
+ | RPL_LISTEND
+ | RPL_LIST
+ | RPL_LISTSTART
+ | RPL_WHOISCHANNELS
+ | RPL_ENDOFWHOIS
+ | RPL_WHOISIDLE
+ | RPL_WHOISCHANOP
+ | RPL_ENDOFWHOWAS
+ | RPL_WHOWASUSER
+ | RPL_WHOISOPERATOR
+ | RPL_WHOISSERVER
+ | RPL_WHOISUSER
+ | RPL_NOWAWAY
+ | RPL_UNAWAY
+ | RPL_TEXT
+ | RPL_ISON
+ | RPL_USERHOST
+ | RPL_AWAY
+ | RPL_NONE
+
+let get_command_reply n =
+match n with
+ 263 -> RPL_TRYAGAIN
+ | 319 -> RPL_WHOISCHANNELS
+ | 318 -> RPL_ENDOFWHOIS
+ | 317 -> RPL_WHOISIDLE
+ | 316 -> RPL_WHOISCHANOP
+ | 369 -> RPL_ENDOFWHOWAS
+ | 314 -> RPL_WHOWASUSER
+ | 313 -> RPL_WHOISOPERATOR
+ | 312 -> RPL_WHOISSERVER
+ | 311 -> RPL_WHOISUSER
+ | 262 -> RPL_TRACEEND
+ | 261 -> RPL_TRACELOG
+ | 259 -> RPL_ADMINEMAIL
+ | 258 -> RPL_ADMINLOC2
+ | 257 -> RPL_ADMINLOC1
+ | 256 -> RPL_ADMINME
+ | 255 -> RPL_LUSERME
+ | 254 -> RPL_LUSERCHANNELS
+ | 253 -> RPL_LUSERUNKNOWN
+ | 252 -> RPL_LUSEROP
+ | 251 -> RPL_LUSERCLIENT
+ | 250 -> RPL_STATSDLINE
+ | 249 -> RPL_STATSDEBUG
+ | 248 -> RPL_STATSDEFINE
+ | 247 -> RPL_STATSBLINE
+ | 246 -> RPL_STATSPING
+ | 245 -> RPL_STATSSLINE
+ | 244 -> RPL_STATSHLINE
+ | 243 -> RPL_STATSOLINE
+ | 242 -> RPL_STATSUPTIME
+ | 241 -> RPL_STATSLLINE
+ | 240 -> RPL_STATSVLINE
+ | 235 -> RPL_SERVLISTEND
+ | 234 -> RPL_SERVLIST
+ | 233 -> RPL_SERVICE
+ | 232 -> RPL_ENDOFSERVICES
+ | 231 -> RPL_SERVICEINFO
+ | 221 -> RPL_UMODEIS
+ | 219 -> RPL_ENDOFSTATS
+ | 218 -> RPL_STATSYLINE
+ | 217 -> RPL_STATSQLINE
+ | 216 -> RPL_STATSKLINE
+ | 215 -> RPL_STATSILINE
+ | 214 -> RPL_STATSNLINE
+ | 213 -> RPL_STATSCLINE
+ | 212 -> RPL_STATSCOMMANDS
+ | 211 -> RPL_STATSLINKINFO
+ | 210 -> RPL_TRACERECONNECT
+ | 209 -> RPL_TRACECLASS
+ | 208 -> RPL_TRACENEWTYPE
+ | 207 -> RPL_TRACESERVICE
+ | 206 -> RPL_TRACESERVER
+ | 205 -> RPL_TRACEUSER
+ | 204 -> RPL_TRACEOPERATOR
+ | 203 -> RPL_TRACEUNKNOWN
+ | 202 -> RPL_TRACEHANDSHAKE
+ | 201 -> RPL_TRACECONNECTING
+ | 200 -> RPL_TRACELINK
+ | 395 -> RPL_NOUSERS
+ | 394 -> RPL_ENDOFUSERS
+ | 393 -> RPL_USERS
+ | 392 -> RPL_USERSSTART
+ | 391 -> RPL_TIME
+ | 385 -> RPL_NOTOPERANYMORE
+ | 384 -> RPL_MYPORTIS
+ | 383 -> RPL_YOURESERVICE
+ | 382 -> RPL_REHASHING
+ | 381 -> RPL_YOUREOPER
+ | 376 -> RPL_ENDOFMOTD
+ | 375 -> RPL_MOTDSTART
+ | 374 -> RPL_ENDOFINFO
+ | 373 -> RPL_INFOSTART
+ | 372 -> RPL_MOTD
+ | 371 -> RPL_INFO
+ | 368 -> RPL_ENDOFBANLIST
+ | 367 -> RPL_BANLIST
+ | 365 -> RPL_ENDOFLINKS
+ | 364 -> RPL_LINKS
+ | 363 -> RPL_CLOSEEND
+ | 362 -> RPL_CLOSING
+ | 361 -> RPL_KILLDONE
+ | 366 -> RPL_ENDOFNAMES
+ | 353 -> RPL_NAMREPLY
+ | 315 -> RPL_ENDOFWHO
+ | 352 -> RPL_WHOREPLY
+ | 351 -> RPL_VERSION
+ | 342 -> RPL_SUMMONING
+ | 341 -> RPL_INVITING
+ | 332 -> RPL_TOPIC
+ | 331 -> RPL_NOTOPIC
+ | 324 -> RPL_CHANNELMODEIS
+ | 323 -> RPL_LISTEND
+ | 322 -> RPL_LIST
+ | 321 -> RPL_LISTSTART
+ | 306 -> RPL_NOWAWAY
+ | 305 -> RPL_UNAWAY
+ | 304 -> RPL_TEXT
+ | 303 -> RPL_ISON
+ | 302 -> RPL_USERHOST
+ | 301 -> RPL_AWAY
+ | 300 -> RPL_NONE
+ | _ -> raise (Unknown_Reply n)
+
+(* Bug 454 *)
+type habert_a=
+ | A of habert_c
+ | B of habert_c
+
+and habert_c= {lvar:int; lassoc: habert_c;lnb:int}
+
+
+let habert=function
+ | (A {lnb=i}|B {lnb=i}) when i=0 -> 1
+ | A {lassoc=({lnb=j});lnb=i} -> 2
+ | _ -> 3
+;;
+
+let rec ex0 = {lvar=0 ; lnb=0 ; lassoc=ex1}
+and ex1 = {lvar=1 ; lnb=1 ; lassoc=ex0} in
+
+test "habert" habert (A ex0) 1 ;
+test "habert" habert (B ex0) 1 ;
+test "habert" habert (A ex1) 2 ;
+test "habert" habert (B ex1) 3 ;
+
+(* Problems with interval test in arithmetic mod 2^31, bug #359 *)
+(* From manuel Fahndrich *)
+
+type type_expr = [
+ | `TTuple of type_expr list
+ | `TConstr of type_expr list
+ | `TVar of string
+ | `TVariant of string list
+ | `TBlock of int
+ | `TCopy of type_expr
+ ]
+
+and recurs_type_expr = [
+ | `TTuple of type_expr list
+ | `TConstr of type_expr list
+ | `TVariant of string list
+ ]
+
+
+let rec maf te =
+ match te with
+ | `TCopy te -> 1
+ | `TVar _ -> 2
+ | `TBlock _ -> 2
+ | #recurs_type_expr as desc ->
+
+ let te =
+ (match desc with
+ `TTuple tl ->
+ 4
+ | `TConstr tl ->
+ 5
+ | `TVariant (row) ->
+ 6
+ )
+ in
+
+ te
+;;
+
+let base = `TBlock 0
+;;
+
+test "maf" maf (`TCopy base) 1 ;
+test "maf" maf (`TVar "test") 2 ;
+test "maf" maf (`TBlock 0) 2 ;
+test "maf" maf (`TTuple []) 4 ;
+test "maf" maf (`TConstr []) 5 ;
+test "maf" maf (`TVariant []) 6
+;;
+
+(* PR#1310
+ Using ``get_args'' in place or an ad-hoc ``matcher'' function for tuples.
+ Has made the compiler [3.05] to fail.
+*)
+type t_seb = Uin | Uout
+;;
+
+let rec seb = function
+ | ((i, Uin) | (i, Uout)), Uout -> 1
+ | ((j, Uin) | (j, Uout)), Uin -> 2
+;;
+
+test "seb" seb ((0,Uin),Uout) 1 ;
+test "seb" seb ((0,Uout),Uin) 2 ;
+()
+;;
+
+(* Talk with Jacques
+ - type 'b is still open ??
+ - better case generation, accept intervals of size 1 when ok_inter is
+ false (in Switch)
+*)
+
+(*
+File "morematch.ml", line 1060, characters 8-65:
+Warning: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+A `D
+*)
+type ('a, 'b) t_j = A of 'a | B of 'b * 'a | C
+
+let f = function
+ | A (`A|`C) -> 0
+ | B (`B,`D) -> 1
+ | C -> 2
+
+let g x = try f x with Match_failure _ -> 3
+
+let _ =
+ test "jacques" g (A `A) 0 ;
+ test "jacques" g (A `C) 0 ;
+ test "jacques" g (B (`B,`D)) 1 ;
+ test "jacaues" g C 2 ;
+(* test "jacques" g (B (`A,`D)) 3 ; (* type incorrect expected behavior ? *)*)
+ ()
+
+(*
+ Compilation bug, segfault, because of incorrect compilation
+ of unused match case .. -> "11"
+*)
+
+type t_l = A | B
+
+let f = function
+ | _, _, _, _, _, _, _, _, _, _, _, _, _, B, _, _ -> "0"
+ | _, _, _, B, A, _, _, _, _, _, _, _, _, _, _, _ -> "1"
+ | _, _, _, B, _, A, _, _, A, _, _, _, _, _, _, _ -> "2"
+ | _, _, _, _, _, _, _, _, _, _, B, A, _, A, _, _ -> "3"
+ | _, _, _, _, _, _, _, B, _, _, _, _, B, _, A, A -> "4"
+ | A, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ -> "5"
+ | _, _, _, _, _, _, _, B, _, B, _, _, _, _, _, _ -> "6"
+ | _, B, _, _, _, _, _, _, _, _, _, _, _, _, _, _ -> "7"
+ | _, A, A, _, A, _, B, _, _, _, _, _, _, _, _, B -> "8"
+ | _, _, _, _, B, _, _, _, _, _, _, _, _, _, B, _ -> "9"
+ | _, _, _, _, _, _, _, _, _, _, _, B, _, _, _, _ -> "10"
+ | _, _, _, _, _, A, _, _, _, _, B, _, _, _, _, _ -> "11"
+ | B, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ -> "12"
+ | _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ -> "13"
+
+(*
+File "morematch.ml", line 1094, characters 5-51:
+Warning: this match case is unused.
+File "morematch.ml", line 1096, characters 5-51:
+Warning: this match case is unused.
+*)
+let _ =
+ test "luc" f (B, A, A, A, A, A, A, A, A, A, A, B, A, A, A, A) "10" ;
+ test "luc" f (B, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A) "12" ;
+ ()
+
+(*
+ By Gilles Peskine, compilation raised some assert false i make_failactionneg
+*)
+
+type bg = [
+ | `False
+ | `True
+ ]
+
+type vg = [
+ | `A
+ | `B
+ | `U of int
+ | `V of int
+ ]
+
+type tg = {
+ v : vg;
+ x : bg;
+ }
+
+let predg x = true
+
+let rec gilles o = match o with
+ | {v = (`U data | `V data); x = `False} when predg o -> 1
+ | {v = (`A|`B) ; x = `False}
+ | {v = (`U _ | `V _); x = `False}
+ | {v = _ ; x = `True}
+ -> 2
+
+(*
+ Match in trywith should always have a default case
+*)
+
+exception Found of string * int
+exception Error of string
+
+
+let lucexn e =
+ try
+ try raise e with Error msg -> msg
+ with Found (s,r) -> s^string_of_int r
+
+let () =
+ test "lucexn1" lucexn (Error "coucou") "coucou" ;
+ test "lucexn2" lucexn (Found ("int: ",0)) "int: 0" ;
+ ()
+
+(*
+ PR#5758: different representations of floats
+*)
+
+let pr5758 x str =
+ match (x, str) with
+ | (1. , "A") -> "Matched A"
+ | (1.0, "B") -> "Matched B"
+ | (1. , "C") -> "Matched C"
+ | result ->
+ match result with
+ | (1., "A") -> "Failed match A then later matched"
+ | _ -> "Failed twice"
+;;
+
+let () =
+ test "pr5758" (pr5758 1.) "A" "Matched A"
+;;
diff --git a/testsuite/tests/basic-more/morematch.reference b/testsuite/tests/basic-more/morematch.reference
new file mode 100644
index 0000000000..197c928071
--- /dev/null
+++ b/testsuite/tests/basic-more/morematch.reference
@@ -0,0 +1,2 @@
+
+All tests succeeded.
diff --git a/testsuite/tests/basic-more/pr2719.ml b/testsuite/tests/basic-more/pr2719.ml
new file mode 100644
index 0000000000..f0a9d6a4f9
--- /dev/null
+++ b/testsuite/tests/basic-more/pr2719.ml
@@ -0,0 +1,17 @@
+open Printf
+
+let bug () =
+ let mat = [| [|false|] |]
+ and test = ref false in
+ printf "Value of test at the beginning : %b\n" !test; flush stdout;
+ (try let _ = mat.(0).(-1) in
+ (test := true;
+ printf "Am I going through this block of instructions ?\n";
+ flush stdout)
+ with Invalid_argument _ -> printf "Value of test now : %b\n" !test
+ );
+ (try if mat.(0).(-1) then ()
+ with Invalid_argument _ -> ()
+ )
+
+let () = bug ()
diff --git a/testsuite/tests/basic-more/pr2719.reference b/testsuite/tests/basic-more/pr2719.reference
new file mode 100644
index 0000000000..073d0916d9
--- /dev/null
+++ b/testsuite/tests/basic-more/pr2719.reference
@@ -0,0 +1,4 @@
+Value of test at the beginning : false
+Value of test now : false
+
+All tests succeeded.
diff --git a/testsuite/tests/basic-more/pr6216.ml b/testsuite/tests/basic-more/pr6216.ml
new file mode 100644
index 0000000000..71844f1494
--- /dev/null
+++ b/testsuite/tests/basic-more/pr6216.ml
@@ -0,0 +1,12 @@
+(* PR6216: wrong inlining of GADT match *)
+
+type _ t =
+ | Float : float t
+ | String : string t
+
+let f : type a . a t -> a -> unit = fun t a ->
+ match t with
+ | Float -> ()
+ | String -> ignore (String.length a : int)
+
+let _g (kind : float t) (x : float) : unit = f kind (x *. 13.)
diff --git a/testsuite/tests/basic-more/pr6216.reference b/testsuite/tests/basic-more/pr6216.reference
new file mode 100644
index 0000000000..197c928071
--- /dev/null
+++ b/testsuite/tests/basic-more/pr6216.reference
@@ -0,0 +1,2 @@
+
+All tests succeeded.
diff --git a/testsuite/tests/basic-more/tbuffer.ml b/testsuite/tests/basic-more/tbuffer.ml
new file mode 100644
index 0000000000..75f49dd10f
--- /dev/null
+++ b/testsuite/tests/basic-more/tbuffer.ml
@@ -0,0 +1,38 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Estime, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2009 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+(* Dummy substitute function. *)
+
+open Testing;;
+open Buffer;;
+
+let identity s = s;;
+
+let b = Buffer.create 100;;
+
+(* Pattern with a '\\' character in it. *)
+let pat0 = "\\\\a" in
+let n0 = String.length pat0 in
+
+Buffer.add_substitute b identity pat0;
+
+test (String.length (Buffer.contents b) = n0)
+;;
+
+(* Pattern with a '\\' character at the end. *)
+let pat1 = "b\\" in
+let n1 = String.length pat1 in
+
+Buffer.clear b;
+Buffer.add_substitute b identity pat1;
+test (String.length (Buffer.contents b) = n1)
+;;
diff --git a/testsuite/tests/basic-more/tbuffer.reference b/testsuite/tests/basic-more/tbuffer.reference
new file mode 100644
index 0000000000..f0f683477f
--- /dev/null
+++ b/testsuite/tests/basic-more/tbuffer.reference
@@ -0,0 +1,2 @@
+ 0 1
+All tests succeeded.
diff --git a/testsuite/tests/basic-more/testrandom.ml b/testsuite/tests/basic-more/testrandom.ml
new file mode 100644
index 0000000000..76acd4c23e
--- /dev/null
+++ b/testsuite/tests/basic-more/testrandom.ml
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Random
+
+let _ =
+ for i = 0 to 20 do
+ print_char ' '; print_int (int 1000);
+ done;
+ print_newline (); print_newline ();
+ for i = 0 to 20 do
+ print_char ' '; print_float (float 1000.);
+ done
+
+let _ = exit 0
diff --git a/testsuite/tests/basic-more/testrandom.reference b/testsuite/tests/basic-more/testrandom.reference
new file mode 100644
index 0000000000..943addd1bd
--- /dev/null
+++ b/testsuite/tests/basic-more/testrandom.reference
@@ -0,0 +1,4 @@
+ 344 685 182 641 439 500 104 20 921 370 217 885 949 678 615 412 401 606 428 869 289
+
+ 122.128067547 461.324792129 360.006556146 768.75882284 396.500946942 190.217751234 567.660068681 403.59226778 59.8488223602 363.816246826 764.705761642 172.627051105 481.861849093 399.173195422 629.424106752 391.547032203 676.701133948 174.382120878 994.425675487 585.00027757 34.3270777955
+All tests succeeded.
diff --git a/testsuite/tests/basic-more/tformat.ml b/testsuite/tests/basic-more/tformat.ml
new file mode 100644
index 0000000000..64176d88f8
--- /dev/null
+++ b/testsuite/tests/basic-more/tformat.ml
@@ -0,0 +1,33 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Estime, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2009 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+(*
+
+A testbed file for the module Format.
+
+*)
+
+open Testing;;
+
+open Format;;
+
+(* BR#4769 *)
+let test0 () =
+ let b = Buffer.create 10 in
+ let msg = "Hello world!" in
+ Format.bprintf b "%s" msg;
+ let s = Buffer.contents b in
+ s = msg
+;;
+
+test (test0 ())
+;;
diff --git a/testsuite/tests/basic-more/tformat.reference b/testsuite/tests/basic-more/tformat.reference
new file mode 100644
index 0000000000..819c5ba693
--- /dev/null
+++ b/testsuite/tests/basic-more/tformat.reference
@@ -0,0 +1,2 @@
+ 0
+All tests succeeded.
diff --git a/testsuite/tests/basic-more/tprintf.ml b/testsuite/tests/basic-more/tprintf.ml
new file mode 100644
index 0000000000..5777739fe5
--- /dev/null
+++ b/testsuite/tests/basic-more/tprintf.ml
@@ -0,0 +1,87 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2006 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Testing;;
+
+open Printf;;
+
+(* Padding floating point numbers.
+ Testing * width specifications. *)
+let test0 () =
+ sprintf "%.0f" 1.0 = "1" &&
+ sprintf "%.0f." 1.7 = "2." &&
+ sprintf "%.1f." 1.0 = "1.0." &&
+ (*sprintf "%0.1f." 12.0 = "12.0." &&*)
+ (* >> '0' w/o padding *)
+ sprintf "%3.1f." 12.0 = "12.0." &&
+ sprintf "%5.1f." 12.0 = " 12.0." &&
+ sprintf "%10.1f." 12.0 = " 12.0." &&
+ sprintf "%010.1f." 12.0 = "00000012.0." &&
+ sprintf "% 10.1f." 12.0 = " 12.0." &&
+ sprintf "%+10.1f." 12.0 = " +12.0." &&
+ sprintf "%+10.1f." (-12.0) = " -12.0." &&
+
+ sprintf "%010.5f." 12.0 = "0012.00000." &&
+ sprintf "%010.0f." 12.0 = "0000000012." &&
+ sprintf "% 10.0f." 12.0 = " 12." &&
+
+ (*sprintf "%0.1f." 12.0 = "12.0." &&*)
+ (* >> '0' w/o padding *)
+ sprintf "%10.1f." 1.001 = " 1.0." &&
+ sprintf "%05.1f." 1.001 = "001.0."
+;;
+
+test (test0 ());;
+
+(* Padding integers (cf bug 3955).
+ Testing * width specifications. *)
+let test1 () =
+ sprintf "%d\n" 1 = "1\n" &&
+ sprintf "%05d\n" 1 = "00001\n" &&
+ sprintf "%*d\n" 5 1 = " 1\n" &&
+ sprintf "%0*d\n" 5 1 = "00001\n";;
+
+test (test1 ());;
+
+(* FIXME: when positional specification will be OK. *)
+let test2 () = true
+(* sprintf "%1$d\n" 5 1 = " 1\n" &&
+ sprintf "%01$d\n" 5 1 = "00001\n" *);;
+
+test (test2 ());;
+
+(* Testing meta format string printing. *)
+let test3 () =
+ sprintf "%{toto %S titi.\n%}" "Bonjour %S." = "%s" &&
+ sprintf "%{Bonjour %S.%}" "toto %S titi.\n" = "%s"
+;;
+test (test3 ());;
+
+(* Testing meta format string arguments. *)
+let test4 () =
+ sprintf "%(%s%)" "Bonjour %s" "toto" = "Bonjour toto" &&
+ sprintf "%(%s%)" "Bonjour %s." "vous" = "Bonjour vous." &&
+ sprintf "%(%s%)" "Hello %s." "you" = "Hello you."
+;;
+
+test (test4 ());;
+
+let test5 () =
+ sprintf "%(toto %s titi.\n%)"
+ "Bonjour %s." "vous" = "Bonjour vous." &&
+ sprintf "%(toto %s titi.\n%).\n"
+ "Bonjour %s" "toto" = "Bonjour toto.\n" &&
+ sprintf "%(toto %s titi.\n%)%s\n"
+ "Bonjour %s." "toto" " Ca va?" = "Bonjour toto. Ca va?\n"
+;;
+
+test (test5 ());;
diff --git a/testsuite/tests/basic-more/tprintf.reference b/testsuite/tests/basic-more/tprintf.reference
new file mode 100644
index 0000000000..1fb209d42c
--- /dev/null
+++ b/testsuite/tests/basic-more/tprintf.reference
@@ -0,0 +1,2 @@
+ 0 1 2 3 4 5
+All tests succeeded.
diff --git a/testsuite/tests/basic-multdef/Makefile b/testsuite/tests/basic-multdef/Makefile
new file mode 100644
index 0000000000..1405f30569
--- /dev/null
+++ b/testsuite/tests/basic-multdef/Makefile
@@ -0,0 +1,18 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=multdef
+MAIN_MODULE=usemultdef
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/basic-multdef/multdef.ml b/testsuite/tests/basic-multdef/multdef.ml
new file mode 100644
index 0000000000..46957d02e3
--- /dev/null
+++ b/testsuite/tests/basic-multdef/multdef.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let f x = x + 1
+external g : string -> int = "caml_int_of_string"
diff --git a/testsuite/tests/basic-multdef/multdef.mli b/testsuite/tests/basic-multdef/multdef.mli
new file mode 100644
index 0000000000..0785dfc25c
--- /dev/null
+++ b/testsuite/tests/basic-multdef/multdef.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val f : int -> int
+val f : int -> int
+val g : string -> int
diff --git a/testsuite/tests/basic-multdef/usemultdef.ml b/testsuite/tests/basic-multdef/usemultdef.ml
new file mode 100644
index 0000000000..1b44e7b9bf
--- /dev/null
+++ b/testsuite/tests/basic-multdef/usemultdef.ml
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let _ = print_int(Multdef.f 1); print_newline(); exit 0
diff --git a/testsuite/tests/basic-multdef/usemultdef.reference b/testsuite/tests/basic-multdef/usemultdef.reference
new file mode 100644
index 0000000000..0cfbf08886
--- /dev/null
+++ b/testsuite/tests/basic-multdef/usemultdef.reference
@@ -0,0 +1 @@
+2
diff --git a/testsuite/tests/basic-private/Makefile b/testsuite/tests/basic-private/Makefile
new file mode 100644
index 0000000000..bd36ccb765
--- /dev/null
+++ b/testsuite/tests/basic-private/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+MODULES=length
+MAIN_MODULE=tlength
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/basic-private/length.ml b/testsuite/tests/basic-private/length.ml
new file mode 100644
index 0000000000..df055f0051
--- /dev/null
+++ b/testsuite/tests/basic-private/length.ml
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*
+
+A testbed file for private type abbreviation definitions.
+
+We define a Length module to implement positive integers.
+
+*)
+
+type t = int;;
+
+let make x =
+ if x >= 0 then x else
+ failwith (Printf.sprintf "cannot build negative length : %i" x)
+;;
+
+external from : t -> int = "%identity";;
diff --git a/testsuite/tests/basic-private/length.mli b/testsuite/tests/basic-private/length.mli
new file mode 100644
index 0000000000..b26b92b06f
--- /dev/null
+++ b/testsuite/tests/basic-private/length.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*
+
+A testbed file for private type abbreviation definitions.
+
+We define a Length module to implement positive integers.
+
+*)
+
+type t = private int;;
+
+val make : int -> t;;
+
+external from : t -> int = "%identity";;
diff --git a/testsuite/tests/basic-private/tlength.ml b/testsuite/tests/basic-private/tlength.ml
new file mode 100644
index 0000000000..3beea60bf1
--- /dev/null
+++ b/testsuite/tests/basic-private/tlength.ml
@@ -0,0 +1,35 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*
+
+A testbed file for private type abbreviation definitions.
+
+We test the Length module that implements positive integers.
+
+*)
+
+(* We can build a null length. *)
+let l = Length.make 0;;
+
+
+(* We cannot build a negative length. *)
+try ignore (Length.make (-1)); assert false with
+| Failure _ -> ()
+;;
+
+
+(* We can build a positive length. *)
+let l3 = Length.make 3 in
+
+(* and use the associated injection and projection functions. *)
+Length.make (Length.from l3 + Length.from l3);;
diff --git a/testsuite/tests/basic-private/tlength.reference b/testsuite/tests/basic-private/tlength.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/basic-private/tlength.reference
diff --git a/testsuite/tests/basic/Makefile b/testsuite/tests/basic/Makefile
new file mode 100644
index 0000000000..299656b246
--- /dev/null
+++ b/testsuite/tests/basic/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/basic/arrays.ml b/testsuite/tests/basic/arrays.ml
new file mode 100644
index 0000000000..b56893f5e0
--- /dev/null
+++ b/testsuite/tests/basic/arrays.ml
@@ -0,0 +1,146 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let bigarray n = [|
+n+0; n+1; n+2; n+3; n+4; n+5; n+6; n+7; n+8; n+9; n+10; n+11; n+12;
+n+13; n+14; n+15; n+16; n+17; n+18; n+19; n+20; n+21; n+22; n+23;
+n+24; n+25; n+26; n+27; n+28; n+29; n+30; n+31; n+32; n+33; n+34;
+n+35; n+36; n+37; n+38; n+39; n+40; n+41; n+42; n+43; n+44; n+45;
+n+46; n+47; n+48; n+49; n+50; n+51; n+52; n+53; n+54; n+55; n+56;
+n+57; n+58; n+59; n+60; n+61; n+62; n+63; n+64; n+65; n+66; n+67;
+n+68; n+69; n+70; n+71; n+72; n+73; n+74; n+75; n+76; n+77; n+78;
+n+79; n+80; n+81; n+82; n+83; n+84; n+85; n+86; n+87; n+88; n+89;
+n+90; n+91; n+92; n+93; n+94; n+95; n+96; n+97; n+98; n+99; n+100;
+n+101; n+102; n+103; n+104; n+105; n+106; n+107; n+108; n+109; n+110;
+n+111; n+112; n+113; n+114; n+115; n+116; n+117; n+118; n+119; n+120;
+n+121; n+122; n+123; n+124; n+125; n+126; n+127; n+128; n+129; n+130;
+n+131; n+132; n+133; n+134; n+135; n+136; n+137; n+138; n+139; n+140;
+n+141; n+142; n+143; n+144; n+145; n+146; n+147; n+148; n+149; n+150;
+n+151; n+152; n+153; n+154; n+155; n+156; n+157; n+158; n+159; n+160;
+n+161; n+162; n+163; n+164; n+165; n+166; n+167; n+168; n+169; n+170;
+n+171; n+172; n+173; n+174; n+175; n+176; n+177; n+178; n+179; n+180;
+n+181; n+182; n+183; n+184; n+185; n+186; n+187; n+188; n+189; n+190;
+n+191; n+192; n+193; n+194; n+195; n+196; n+197; n+198; n+199; n+200;
+n+201; n+202; n+203; n+204; n+205; n+206; n+207; n+208; n+209; n+210;
+n+211; n+212; n+213; n+214; n+215; n+216; n+217; n+218; n+219; n+220;
+n+221; n+222; n+223; n+224; n+225; n+226; n+227; n+228; n+229; n+230;
+n+231; n+232; n+233; n+234; n+235; n+236; n+237; n+238; n+239; n+240;
+n+241; n+242; n+243; n+244; n+245; n+246; n+247; n+248; n+249; n+250;
+n+251; n+252; n+253; n+254; n+255; n+256; n+257; n+258; n+259; n+260;
+n+261; n+262; n+263; n+264; n+265; n+266; n+267; n+268; n+269; n+270;
+n+271; n+272; n+273; n+274; n+275; n+276; n+277; n+278; n+279; n+280;
+n+281; n+282; n+283; n+284; n+285; n+286; n+287; n+288; n+289; n+290;
+n+291; n+292; n+293; n+294; n+295; n+296; n+297; n+298; n+299
+|]
+
+let test1 () =
+ let a = bigarray 12345 in
+ Gc.full_major();
+ for i = 0 to Array.length a - 1 do
+ if a.(i) <> 12345 + i then print_string "Test1: error\n"
+ done
+
+let testcopy a =
+ Array.copy a = a
+
+let test2 () =
+ if not (testcopy [|1;2;3;4;5|]) then
+ print_string "Test2: failed on int array\n";
+ if not (testcopy [|1.2;2.3;3.4;4.5|]) then
+ print_string "Test2: failed on float array\n";
+ if not (testcopy [|"un"; "deux"; "trois"|]) then
+ print_string "Test2: failed on string array\n";
+ if not (testcopy (bigarray 42)) then
+ print_string "Test2: failed on big array\n"
+
+module AbstractFloat =
+ (struct
+ type t = float
+ let to_float x = x
+ let from_float x = x
+ end :
+ sig
+ type t
+ val to_float: t -> float
+ val from_float: float -> t
+ end)
+
+let test3 () =
+ let t1 = AbstractFloat.from_float 1.0
+ and t2 = AbstractFloat.from_float 2.0
+ and t3 = AbstractFloat.from_float 3.0 in
+ let v = [|t1;t2;t3|] in
+ let w = Array.make 2 t1 in
+ let u = Array.copy v in
+ if not (AbstractFloat.to_float v.(0) = 1.0 &&
+ AbstractFloat.to_float v.(1) = 2.0 &&
+ AbstractFloat.to_float v.(2) = 3.0) then
+ print_string "Test3: failed on v\n";
+ if not (AbstractFloat.to_float w.(0) = 1.0 &&
+ AbstractFloat.to_float w.(1) = 1.0) then
+ print_string "Test3: failed on w\n";
+ if not (AbstractFloat.to_float u.(0) = 1.0 &&
+ AbstractFloat.to_float u.(1) = 2.0 &&
+ AbstractFloat.to_float u.(2) = 3.0) then
+ print_string "Test3: failed on u\n"
+
+let test4 () =
+ let a = bigarray 0 in
+ let b = Array.sub a 50 10 in
+ if b <> [| 50;51;52;53;54;55;56;57;58;59 |] then
+ print_string "Test4: failed\n"
+
+let test5 () =
+ if Array.append [| 1;2;3 |] [| 4;5 |] <> [| 1;2;3;4;5 |] then
+ print_string "Test5: failed on int arrays\n";
+ if Array.append [| 1.0;2.0;3.0 |] [| 4.0;5.0 |] <> [| 1.0;2.0;3.0;4.0;5.0 |]
+ then
+ print_string "Test5: failed on float arrays\n"
+
+let test6 () =
+ let a = [| 0;1;2;3;4;5;6;7;8;9 |] in
+ let b = Array.concat [a;a;a;a;a;a;a;a;a;a] in
+ if not (Array.length b = 100 && b.(6) = 6 && b.(42) = 2 && b.(99) = 9) then
+ print_string "Test6: failed\n"
+
+let test7 () =
+ let a = Array.make 10 "a" in
+ let b = [| "b1"; "b2"; "b3" |] in
+ Array.blit b 0 a 5 3;
+ if a <> [|"a"; "a"; "a"; "a"; "a"; "b1"; "b2"; "b3"; "a"; "a"|]
+ || b <> [|"b1"; "b2"; "b3"|]
+ then print_string "Test7: failed(1)\n";
+ Array.blit a 5 a 6 4;
+ if a <> [|"a"; "a"; "a"; "a"; "a"; "b1"; "b1"; "b2"; "b3"; "a"|]
+ then print_string "Test7: failed(2)\n"
+
+let test8 () =
+ (try
+ ignore (Array.sub [||] 0 1); print_string "Test 8.1: failed\n"
+ with Invalid_argument _ -> ());
+ (try
+ ignore (Array.sub [|3;4|] 1 (-1)); print_string "Test 8.2: failed\n"
+ with Invalid_argument _ -> ());
+ (try
+ ignore (Array.sub [|3;4|] max_int 1); print_string "Test 8.3: failed\n"
+ with Invalid_argument _ -> ())
+
+let _ =
+ test1();
+ test2();
+ test3();
+ test4();
+ test5();
+ test6();
+ test7();
+ test8();
+ exit 0
diff --git a/testsuite/tests/basic/arrays.reference b/testsuite/tests/basic/arrays.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/basic/arrays.reference
diff --git a/testsuite/tests/basic/bigints.ml b/testsuite/tests/basic/bigints.ml
new file mode 100644
index 0000000000..e7bb8faa8f
--- /dev/null
+++ b/testsuite/tests/basic/bigints.ml
@@ -0,0 +1,37 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let _ =
+ match Sys.word_size with
+ | 32 ->
+ print_int (1 * 1000000000); print_newline();
+ print_string "10000000000"; print_newline();
+ print_string "100000000000"; print_newline();
+ print_string "1000000000000"; print_newline();
+ print_string "10000000000000"; print_newline();
+ print_string "100000000000000"; print_newline();
+ print_string "1000000000000000"; print_newline();
+ print_string "10000000000000000"; print_newline();
+ print_string "100000000000000000"; print_newline();
+ print_string "1000000000000000000"; print_newline();
+ | 64 ->
+ print_int (1 * 1000000000); print_newline();
+ print_int (10 * 1000000000); print_newline();
+ print_int (100 * 1000000000); print_newline();
+ print_int (1000 * 1000000000); print_newline();
+ print_int (10000 * 1000000000); print_newline();
+ print_int (100000 * 1000000000); print_newline();
+ print_int (1000000 * 1000000000); print_newline();
+ print_int (10000000 * 1000000000); print_newline();
+ print_int (100000000 * 1000000000); print_newline();
+ print_int (1000000000 * 1000000000); print_newline()
+ | _ -> assert false
diff --git a/testsuite/tests/basic/bigints.reference b/testsuite/tests/basic/bigints.reference
new file mode 100644
index 0000000000..512fd476b2
--- /dev/null
+++ b/testsuite/tests/basic/bigints.reference
@@ -0,0 +1,10 @@
+1000000000
+10000000000
+100000000000
+1000000000000
+10000000000000
+100000000000000
+1000000000000000
+10000000000000000
+100000000000000000
+1000000000000000000
diff --git a/testsuite/tests/basic/boxedints.ml b/testsuite/tests/basic/boxedints.ml
new file mode 100644
index 0000000000..bcb0b8230f
--- /dev/null
+++ b/testsuite/tests/basic/boxedints.ml
@@ -0,0 +1,593 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test the types nativeint, int32, int64 *)
+
+open Printf
+
+let error_occurred = ref false
+
+let function_tested = ref ""
+
+let testing_function s =
+ function_tested := s;
+ print_newline();
+ print_string s;
+ print_newline()
+
+let test test_number answer correct_answer =
+ flush stdout;
+ flush stderr;
+ if answer <> correct_answer then begin
+ eprintf "*** Bad result (%s, test %d)\n" !function_tested test_number;
+ flush stderr;
+ error_occurred := true
+ end else begin
+ printf " %d..." test_number
+ end
+
+(***** Tests on 32 bit arithmetic *****)
+
+module type TESTSIG = sig
+ type t
+ module Ops : sig
+ val neg: t -> t
+ val add: t -> t -> t
+ val sub: t -> t -> t
+ val mul: t -> t -> t
+ val div: t -> t -> t
+ val rem: t -> t -> t
+ val logand: t -> t -> t
+ val logor: t -> t -> t
+ val logxor: t -> t -> t
+ val shift_left: t -> int -> t
+ val shift_right: t -> int -> t
+ val shift_right_logical: t -> int -> t
+ val of_int: int -> t
+ val to_int: t -> int
+ val of_float: float -> t
+ val to_float: t -> float
+ val zero: t
+ val one: t
+ val minus_one: t
+ val min_int: t
+ val max_int: t
+ val format : string -> t -> string
+ val to_string: t -> string
+ val of_string: string -> t
+ end
+ val testcomp: t -> t -> bool*bool*bool*bool*bool*bool*int
+ val skip_float_tests: bool
+end
+
+module Test32(M: TESTSIG) =
+struct
+ open M
+ open Ops
+
+ let _ =
+ testing_function "of_int, to_int";
+ test 1 (to_int (of_int 0)) 0;
+ test 2 (to_int (of_int 123)) 123;
+ test 3 (to_int (of_int (-456))) (-456);
+ test 4 (to_int (of_int 0x3FFFFFFF)) 0x3FFFFFFF;
+ test 5 (to_int (of_int (-0x40000000))) (-0x40000000);
+
+ testing_function "of_string";
+ test 1 (of_string "0") (of_int 0);
+ test 2 (of_string "123") (of_int 123);
+ test 3 (of_string "-456") (of_int (-456));
+ test 4 (of_string "123456789") (of_int 123456789);
+ test 5 (of_string "0xABCDEF") (of_int 0xABCDEF);
+ test 6 (of_string "-0o1234567012") (of_int (- 0o1234567012));
+ test 7 (of_string "0b01010111111000001100")
+ (of_int 0b01010111111000001100);
+ test 8 (of_string "0x7FFFFFFF") max_int;
+ test 9 (of_string "-0x80000000") min_int;
+ test 10 (of_string "0x80000000") min_int;
+ test 11 (of_string "0xFFFFFFFF") minus_one;
+
+ testing_function "to_string, format";
+ List.iter (fun (n, s) -> test n (to_string (of_string s)) s)
+ [1, "0"; 2, "123"; 3, "-456"; 4, "1234567890";
+ 5, "1073741824"; 6, "2147483647"; 7, "-2147483648"];
+ List.iter (fun (n, s) -> test n (format "0x%X" (of_string s)) s)
+ [8, "0x0"; 9, "0x123"; 10, "0xABCDEF"; 11, "0x12345678";
+ 12, "0x7FFFFFFF"; 13, "0x80000000"; 14, "0xFFFFFFFF"];
+ test 15 (to_string max_int) "2147483647";
+ test 16 (to_string min_int) "-2147483648";
+ test 17 (to_string zero) "0";
+ test 18 (to_string one) "1";
+ test 19 (to_string minus_one) "-1";
+
+ testing_function "neg";
+ test 1 (neg (of_int 0)) (of_int 0);
+ test 2 (neg (of_int 123)) (of_int (-123));
+ test 3 (neg (of_int (-456))) (of_int 456);
+ test 4 (neg (of_int 123456789)) (of_int (-123456789));
+ test 5 (neg max_int) (of_string "-0x7FFFFFFF");
+ test 6 (neg min_int) min_int;
+
+ testing_function "add";
+ test 1 (add (of_int 0) (of_int 0)) (of_int 0);
+ test 2 (add (of_int 123) (of_int 0)) (of_int 123);
+ test 3 (add (of_int 0) (of_int 456)) (of_int 456);
+ test 4 (add (of_int 123) (of_int 456)) (of_int 579);
+ test 5 (add (of_int (-123)) (of_int 456)) (of_int 333);
+ test 6 (add (of_int 123) (of_int (-456))) (of_int (-333));
+ test 7 (add (of_int (-123)) (of_int (-456))) (of_int (-579));
+ test 8 (add (of_string "0x12345678") (of_string "0x9ABCDEF"))
+ (of_string "0x1be02467");
+ test 9 (add max_int max_int) (of_int (-2));
+ test 10 (add min_int min_int) zero;
+ test 11 (add max_int one) min_int;
+ test 12 (add min_int minus_one) max_int;
+ test 13 (add max_int min_int) minus_one;
+
+ testing_function "sub";
+ test 1 (sub (of_int 0) (of_int 0)) (of_int 0);
+ test 2 (sub (of_int 123) (of_int 0)) (of_int 123);
+ test 3 (sub (of_int 0) (of_int 456)) (of_int (-456));
+ test 4 (sub (of_int 123) (of_int 456)) (of_int (-333));
+ test 5 (sub (of_int (-123)) (of_int 456)) (of_int (-579));
+ test 6 (sub (of_int 123) (of_int (-456))) (of_int 579);
+ test 7 (sub (of_int (-123)) (of_int (-456))) (of_int 333);
+ test 8 (sub (of_string "0x12345678") (of_string "0x9ABCDEF"))
+ (of_string "0x8888889");
+ test 9 (sub max_int min_int) minus_one;
+ test 10 (sub min_int max_int) one;
+ test 11 (sub min_int one) max_int;
+ test 12 (sub max_int minus_one) min_int;
+
+ testing_function "mul";
+ test 1 (mul (of_int 0) (of_int 0)) (of_int 0);
+ test 2 (mul (of_int 123) (of_int 0)) (of_int 0);
+ test 3 (mul (of_int 0) (of_int (-456))) (of_int 0);
+ test 4 (mul (of_int 123) (of_int 1)) (of_int 123);
+ test 5 (mul (of_int 1) (of_int (-456))) (of_int (-456));
+ test 6 (mul (of_int 123) (of_int (-1))) (of_int (-123));
+ test 7 (mul (of_int (-1)) (of_int (-456))) (of_int 456);
+ test 8 (mul (of_int 123) (of_int 456)) (of_int 56088);
+ test 9 (mul (of_int (-123)) (of_int 456)) (of_int (-56088));
+ test 10 (mul (of_int 123) (of_int (-456))) (of_int (-56088));
+ test 11 (mul (of_int (-123)) (of_int (-456))) (of_int 56088);
+ test 12 (mul (of_string "0x12345678") (of_string "0x9ABCDEF"))
+ (of_string "0xe242d208");
+ test 13 (mul max_int max_int) one;
+
+ testing_function "div";
+ List.iter
+ (fun (n, a, b) -> test n (div (of_int a) (of_int b)) (of_int (a / b)))
+ [1, 0, 2;
+ 2, 123, 1;
+ 3, -123, 1;
+ 4, 123, -1;
+ 5, -123, -1;
+ 6, 127531236, 365;
+ 7, 16384, 256;
+ 8, -127531236, 365;
+ 9, 127531236, -365;
+ 10, 1234567, 12345678;
+ 11, 1234567, -12345678];
+ test 12 (div min_int (of_int (-1))) min_int;
+
+ testing_function "mod";
+ List.iter
+ (fun (n, a, b) -> test n (rem (of_int a) (of_int b)) (of_int (a mod b)))
+ [1, 0, 2;
+ 2, 123, 1;
+ 3, -123, 1;
+ 4, 123, -1;
+ 5, -123, -1;
+ 6, 127531236, 365;
+ 7, 16384, 256;
+ 8, -127531236, 365;
+ 9, 127531236, -365;
+ 10, 1234567, 12345678;
+ 11, 1234567, -12345678];
+ test 12 (rem min_int (of_int (-1))) (of_int 0);
+
+ testing_function "and";
+ List.iter
+ (fun (n, a, b, c) -> test n (logand (of_string a) (of_string b))
+ (of_string c))
+ [1, "0x12345678", "0x9abcdef0", "0x12345670";
+ 2, "0x12345678", "0x0fedcba9", "0x2244228";
+ 3, "0xFFFFFFFF", "0x12345678", "0x12345678";
+ 4, "0", "0x12345678", "0";
+ 5, "0x55555555", "0xAAAAAAAA", "0"];
+
+ testing_function "or";
+ List.iter
+ (fun (n, a, b, c) -> test n (logor (of_string a) (of_string b))
+ (of_string c))
+ [1, "0x12345678", "0x9abcdef0", "0x9abcdef8";
+ 2, "0x12345678", "0x0fedcba9", "0x1ffddff9";
+ 3, "0xFFFFFFFF", "0x12345678", "0xFFFFFFFF";
+ 4, "0", "0x12345678", "0x12345678";
+ 5, "0x55555555", "0xAAAAAAAA", "0xFFFFFFFF"];
+
+ testing_function "xor";
+ List.iter
+ (fun (n, a, b, c) -> test n (logxor (of_string a) (of_string b))
+ (of_string c))
+ [1, "0x12345678", "0x9abcdef0", "0x88888888";
+ 2, "0x12345678", "0x0fedcba9", "0x1dd99dd1";
+ 3, "0xFFFFFFFF", "0x12345678", "0xedcba987";
+ 4, "0", "0x12345678", "0x12345678";
+ 5, "0x55555555", "0xAAAAAAAA", "0xFFFFFFFF"];
+
+ testing_function "shift_left";
+ List.iter
+ (fun (n, a, b, c) -> test n (shift_left (of_string a) b) (of_string c))
+ [1, "1", 1, "2";
+ 2, "1", 2, "4";
+ 3, "1", 4, "0x10";
+ 4, "1", 30, "0x40000000";
+ 5, "1", 31, "0x80000000";
+ 6, "0x16236", 7, "0xb11b00";
+ 7, "0x10", 27, "0x80000000";
+ 8, "0x10", 28, "0"];
+
+ testing_function "shift_right";
+ List.iter
+ (fun (n, a, b, c) -> test n (shift_right (of_string a) b) (of_string c))
+ [1, "2", 1, "1";
+ 2, "4", 2, "1";
+ 3, "0x10", 4, "1";
+ 4, "0x40000000", 10, "0x100000";
+ 5, "0x80000000", 31, "-1";
+ 6, "0xb11b00", 7, "0x16236";
+ 7, "-0xb11b00", 7, "-90678"];
+
+ testing_function "shift_right_logical";
+ List.iter
+ (fun (n, a, b, c) -> test n (shift_right_logical (of_string a) b)
+ (of_string c))
+ [1, "2", 1, "1";
+ 2, "4", 2, "1";
+ 3, "0x10", 4, "1";
+ 4, "0x40000000", 10, "0x100000";
+ 5, "0x80000000", 31, "1";
+ 6, "0xb11b00", 7, "0x16236";
+ 7, "-0xb11b00", 7, "0x1fe9dca"];
+
+ if not (skip_float_tests) then begin
+ testing_function "of_float";
+ test 1 (of_float 0.0) (of_int 0);
+ test 2 (of_float 123.0) (of_int 123);
+ test 3 (of_float 123.456) (of_int 123);
+ test 4 (of_float 123.999) (of_int 123);
+ test 5 (of_float (-456.0)) (of_int (-456));
+ test 6 (of_float (-456.123)) (of_int (-456));
+ test 7 (of_float (-456.789)) (of_int (-456));
+
+ testing_function "to_float";
+ test 1 (to_float (of_int 0)) 0.0;
+ test 2 (to_float (of_int 123)) 123.0;
+ test 3 (to_float (of_int (-456))) (-456.0);
+ test 4 (to_float (of_int 0x3FFFFFFF)) 1073741823.0;
+ test 5 (to_float (of_int (-0x40000000))) (-1073741824.0)
+ end;
+
+ testing_function "Comparisons";
+ test 1 (testcomp (of_int 0) (of_int 0))
+ (true,false,false,false,true,true,0);
+ test 2 (testcomp (of_int 1234567) (of_int 1234567))
+ (true,false,false,false,true,true,0);
+ test 3 (testcomp (of_int 0) (of_int 1))
+ (false,true,true,false,true,false,-1);
+ test 4 (testcomp (of_int (-1)) (of_int 0))
+ (false,true,true,false,true,false,-1);
+ test 5 (testcomp (of_int 1) (of_int 0))
+ (false,true,false,true,false,true,1);
+ test 6 (testcomp (of_int 0) (of_int (-1)))
+ (false,true,false,true,false,true,1);
+ test 7 (testcomp max_int min_int)
+ (false,true,false,true,false,true,1);
+
+ ()
+end
+
+(********* Tests on 64-bit arithmetic ***********)
+
+module Test64(M: TESTSIG) =
+struct
+ open M
+ open Ops
+
+ let _ =
+ testing_function "of_int, to_int";
+ test 1 (to_int (of_int 0)) 0;
+ test 2 (to_int (of_int 123)) 123;
+ test 3 (to_int (of_int (-456))) (-456);
+ test 4 (to_int (of_int 0x3FFFFFFF)) 0x3FFFFFFF;
+ test 5 (to_int (of_int (-0x40000000))) (-0x40000000);
+
+ testing_function "of_string";
+ test 1 (of_string "0") (of_int 0);
+ test 2 (of_string "123") (of_int 123);
+ test 3 (of_string "-456") (of_int (-456));
+ test 4 (of_string "123456789") (of_int 123456789);
+ test 5 (of_string "0xABCDEF") (of_int 0xABCDEF);
+ test 6 (of_string "-0o1234567012") (of_int (- 0o1234567012));
+ test 7 (of_string "0b01010111111000001100")
+ (of_int 0b01010111111000001100);
+ test 8 (of_string "0x7FFFFFFFFFFFFFFF") max_int;
+ test 9 (of_string "-0x8000000000000000") min_int;
+ test 10 (of_string "0x8000000000000000") min_int;
+ test 11 (of_string "0xFFFFFFFFFFFFFFFF") minus_one;
+
+ testing_function "to_string, format";
+ List.iter (fun (n, s) -> test n (to_string (of_string s)) s)
+ [1, "0"; 2, "123"; 3, "-456"; 4, "1234567890";
+ 5, "1234567890123456789";
+ 6, "9223372036854775807";
+ 7, "-9223372036854775808"];
+ List.iter (fun (n, s) -> test n ("0x" ^ format "%X" (of_string s)) s)
+ [8, "0x0"; 9, "0x123"; 10, "0xABCDEF"; 11, "0x1234567812345678";
+ 12, "0x7FFFFFFFFFFFFFFF"; 13, "0x8000000000000000";
+ 14, "0xFFFFFFFFFFFFFFFF"];
+ test 15 (to_string max_int) "9223372036854775807";
+ test 16 (to_string min_int) "-9223372036854775808";
+ test 17 (to_string zero) "0";
+ test 18 (to_string one) "1";
+ test 19 (to_string minus_one) "-1";
+
+ testing_function "neg";
+ test 1 (neg (of_int 0)) (of_int 0);
+ test 2 (neg (of_int 123)) (of_int (-123));
+ test 3 (neg (of_int (-456))) (of_int 456);
+ test 4 (neg (of_int 123456789)) (of_int (-123456789));
+ test 5 (neg max_int) (of_string "-0x7FFFFFFFFFFFFFFF");
+ test 6 (neg min_int) min_int;
+
+ testing_function "add";
+ test 1 (add (of_int 0) (of_int 0)) (of_int 0);
+ test 2 (add (of_int 123) (of_int 0)) (of_int 123);
+ test 3 (add (of_int 0) (of_int 456)) (of_int 456);
+ test 4 (add (of_int 123) (of_int 456)) (of_int 579);
+ test 5 (add (of_int (-123)) (of_int 456)) (of_int 333);
+ test 6 (add (of_int 123) (of_int (-456))) (of_int (-333));
+ test 7 (add (of_int (-123)) (of_int (-456))) (of_int (-579));
+ test 8 (add (of_string "0x1234567812345678")
+ (of_string "0x9ABCDEF09ABCDEF"))
+ (of_string "0x1be024671be02467");
+ test 9 (add max_int max_int) (of_int (-2));
+ test 10 (add min_int min_int) zero;
+ test 11 (add max_int one) min_int;
+ test 12 (add min_int minus_one) max_int;
+ test 13 (add max_int min_int) minus_one;
+
+ testing_function "sub";
+ test 1 (sub (of_int 0) (of_int 0)) (of_int 0);
+ test 2 (sub (of_int 123) (of_int 0)) (of_int 123);
+ test 3 (sub (of_int 0) (of_int 456)) (of_int (-456));
+ test 4 (sub (of_int 123) (of_int 456)) (of_int (-333));
+ test 5 (sub (of_int (-123)) (of_int 456)) (of_int (-579));
+ test 6 (sub (of_int 123) (of_int (-456))) (of_int 579);
+ test 7 (sub (of_int (-123)) (of_int (-456))) (of_int 333);
+ test 8 (sub (of_string "0x1234567812345678")
+ (of_string "0x9ABCDEF09ABCDEF"))
+ (of_string "0x888888908888889");
+ test 9 (sub max_int min_int) minus_one;
+ test 10 (sub min_int max_int) one;
+ test 11 (sub min_int one) max_int;
+ test 12 (sub max_int minus_one) min_int;
+
+ testing_function "mul";
+ test 1 (mul (of_int 0) (of_int 0)) (of_int 0);
+ test 2 (mul (of_int 123) (of_int 0)) (of_int 0);
+ test 3 (mul (of_int 0) (of_int (-456))) (of_int 0);
+ test 4 (mul (of_int 123) (of_int 1)) (of_int 123);
+ test 5 (mul (of_int 1) (of_int (-456))) (of_int (-456));
+ test 6 (mul (of_int 123) (of_int (-1))) (of_int (-123));
+ test 7 (mul (of_int (-1)) (of_int (-456))) (of_int 456);
+ test 8 (mul (of_int 123) (of_int 456)) (of_int 56088);
+ test 9 (mul (of_int (-123)) (of_int 456)) (of_int (-56088));
+ test 10 (mul (of_int 123) (of_int (-456))) (of_int (-56088));
+ test 11 (mul (of_int (-123)) (of_int (-456))) (of_int 56088);
+ test 12 (mul (of_string "0x12345678") (of_string "0x9ABCDEF"))
+ (of_string "0xb00ea4e242d208");
+ test 13 (mul max_int max_int) one;
+
+ testing_function "div";
+ List.iter
+ (fun (n, a, b) -> test n (div (of_int a) (of_int b)) (of_int (a / b)))
+ [1, 0, 2;
+ 2, 123, 1;
+ 3, -123, 1;
+ 4, 123, -1;
+ 5, -123, -1;
+ 6, 127531236, 365;
+ 7, 16384, 256;
+ 8, -127531236, 365;
+ 9, 127531236, -365;
+ 10, 1234567, 12345678;
+ 11, 1234567, -12345678];
+ test 12 (div min_int (of_int (-1))) min_int;
+
+ testing_function "mod";
+ List.iter
+ (fun (n, a, b) -> test n (rem (of_int a) (of_int b)) (of_int (a mod b)))
+ [1, 0, 2;
+ 2, 123, 1;
+ 3, -123, 1;
+ 4, 123, -1;
+ 5, -123, -1;
+ 6, 127531236, 365;
+ 7, 16384, 256;
+ 8, -127531236, 365;
+ 9, 127531236, -365;
+ 10, 1234567, 12345678;
+ 11, 1234567, -12345678];
+ test 12 (rem min_int (of_int (-1))) (of_int 0);
+
+ testing_function "and";
+ List.iter
+ (fun (n, a, b, c) -> test n (logand (of_string a) (of_string b))
+ (of_string c))
+ [1, "0x1234567812345678", "0x9abcdef09abcdef0", "0x1234567012345670";
+ 2, "0x1234567812345678", "0x0fedcba90fedcba9", "0x224422802244228";
+ 3, "0xFFFFFFFFFFFFFFFF", "0x1234000012345678", "0x1234000012345678";
+ 4, "0", "0x1234567812345678", "0";
+ 5, "0x5555555555555555", "0xAAAAAAAAAAAAAAAA", "0"];
+
+ testing_function "or";
+ List.iter
+ (fun (n, a, b, c) -> test n (logor (of_string a) (of_string b))
+ (of_string c))
+ [1, "0x1234567812345678", "0x9abcdef09abcdef0", "0x9abcdef89abcdef8";
+ 2, "0x1234567812345678", "0x0fedcba90fedcba9", "0x1ffddff91ffddff9";
+ 3, "0xFFFFFFFFFFFFFFFF", "0x12345678", "0xFFFFFFFFFFFFFFFF";
+ 4, "0", "0x1234567812340000", "0x1234567812340000";
+ 5, "0x5555555555555555", "0xAAAAAAAAAAAAAAAA", "0xFFFFFFFFFFFFFFFF"];
+
+ testing_function "xor";
+ List.iter
+ (fun (n, a, b, c) -> test n (logxor (of_string a) (of_string b))
+ (of_string c))
+ [1, "0x1234567812345678", "0x9abcdef09abcdef0", "0x8888888888888888";
+ 2, "0x1234567812345678", "0x0fedcba90fedcba9", "0x1dd99dd11dd99dd1";
+ 3, "0xFFFFFFFFFFFFFFFF", "0x123456789ABCDEF", "0xfedcba9876543210";
+ 4, "0", "0x1234567812340000", "0x1234567812340000";
+ 5, "0x5555555555555555", "0xAAAAAAAAAAAAAAAA", "0xFFFFFFFFFFFFFFFF"];
+
+ testing_function "shift_left";
+ List.iter
+ (fun (n, a, b, c) -> test n (shift_left (of_string a) b) (of_string c))
+ [1, "1", 1, "2";
+ 2, "1", 2, "4";
+ 3, "1", 4, "0x10";
+ 4, "1", 62, "0x4000000000000000";
+ 5, "1", 63, "0x8000000000000000";
+ 6, "0x16236ABD45673", 7, "0xb11b55ea2b3980";
+ 7, "0x10", 59, "0x8000000000000000";
+ 8, "0x10", 60, "0"];
+
+ testing_function "shift_right";
+ List.iter
+ (fun (n, a, b, c) -> test n (shift_right (of_string a) b) (of_string c))
+ [1, "2", 1, "1";
+ 2, "4", 2, "1";
+ 3, "0x10", 4, "1";
+ 4, "0x40000000", 10, "0x100000";
+ 5, "0x8000000000000000", 63, "-1";
+ 6, "0xb11b55ea2b3980", 7, "0x16236ABD45673";
+ 7, "-0xb11b55ea2b3980", 7, "-389461927286387"];
+
+ testing_function "shift_right_logical";
+ List.iter
+ (fun (n, a, b, c) -> test n (shift_right_logical (of_string a) b)
+ (of_string c))
+ [1, "2", 1, "1";
+ 2, "4", 2, "1";
+ 3, "0x10", 4, "1";
+ 4, "0x40000000", 10, "0x100000";
+ 5, "0x8000000000000000", 63, "1";
+ 6, "0xb11b55ea2b3980", 7, "0x16236ABD45673";
+ 7, "-0xb11b55ea2b3980", 7, "0x1fe9dc9542ba98d"];
+
+ testing_function "Comparisons";
+ test 1 (testcomp (of_int 0) (of_int 0))
+ (true,false,false,false,true,true,0);
+ test 2 (testcomp (of_int 1234567) (of_int 1234567))
+ (true,false,false,false,true,true,0);
+ test 3 (testcomp (of_int 0) (of_int 1))
+ (false,true,true,false,true,false,-1);
+ test 4 (testcomp (of_int (-1)) (of_int 0))
+ (false,true,true,false,true,false,-1);
+ test 5 (testcomp (of_int 1) (of_int 0))
+ (false,true,false,true,false,true,1);
+ test 6 (testcomp (of_int 0) (of_int (-1)))
+ (false,true,false,true,false,true,1);
+ test 7 (testcomp max_int min_int)
+ (false,true,false,true,false,true,1);
+
+ ()
+end
+
+(******** The test proper **********)
+
+let testcomp_int32 (a : int32) (b : int32) =
+ (a = b, a <> b, a < b, a > b, a <= b, a >= b, compare a b)
+let testcomp_int64 (a : int64) (b : int64) =
+ (a = b, a <> b, a < b, a > b, a <= b, a >= b, compare a b)
+let testcomp_nativeint (a : nativeint) (b : nativeint) =
+ (a = b, a <> b, a < b, a > b, a <= b, a >= b, compare a b)
+
+let _ =
+ testing_function "-------- Int32 --------";
+ let module A = Test32(struct type t = int32
+ module Ops = Int32
+ let testcomp = testcomp_int32
+ let skip_float_tests = false end) in
+ print_newline(); testing_function "-------- Int64 --------";
+ let module B = Test64(struct type t = int64
+ module Ops = Int64
+ let testcomp = testcomp_int64
+ let skip_float_tests = false end) in
+ print_newline(); testing_function "-------- Nativeint --------";
+ begin match Sys.word_size with
+ 32 ->
+ let module C =
+ Test32(struct type t = nativeint
+ module Ops = Nativeint
+ let testcomp = testcomp_nativeint
+ let skip_float_tests = true end)
+ in ()
+ | 64 ->
+ let module C =
+ Test64(struct type t = nativeint
+ module Ops = Nativeint
+ let testcomp = testcomp_nativeint
+ let skip_float_tests = true end)
+ in ()
+ | _ ->
+ assert false
+ end;
+ print_newline(); testing_function "--------- Conversions -----------";
+ testing_function "nativeint of/to int32";
+ test 1 (Nativeint.of_int32 (Int32.of_string "0x12345678"))
+ (Nativeint.of_string "0x12345678");
+ test 2 (Nativeint.to_int32 (Nativeint.of_string "0x12345678"))
+ (Int32.of_string "0x12345678");
+ if Sys.word_size = 64 then
+ test 3 (Nativeint.to_int32 (Nativeint.of_string "0x123456789ABCDEF0"))
+ (Int32.of_string "0x9ABCDEF0")
+ else
+ test 3 0 0; (* placeholder to have the same output on 32-bit and 64-bit *)
+ testing_function "int64 of/to int32";
+ test 1 (Int64.of_int32 (Int32.of_string "-0x12345678"))
+ (Int64.of_string "-0x12345678");
+ test 2 (Int64.to_int32 (Int64.of_string "-0x12345678"))
+ (Int32.of_string "-0x12345678");
+ test 3 (Int64.to_int32 (Int64.of_string "0x123456789ABCDEF0"))
+ (Int32.of_string "0x9ABCDEF0");
+ testing_function "int64 of/to nativeint";
+ test 1 (Int64.of_nativeint (Nativeint.of_string "0x12345678"))
+ (Int64.of_string "0x12345678");
+ test 2 (Int64.to_nativeint (Int64.of_string "-0x12345678"))
+ (Nativeint.of_string "-0x12345678");
+ test 3 (Int64.to_nativeint (Int64.of_string "0x123456789ABCDEF0"))
+ (if Sys.word_size = 64
+ then Nativeint.of_string "0x123456789ABCDEF0"
+ else Nativeint.of_string "0x9ABCDEF0")
+
+(********* End of test *********)
+
+let _ =
+ print_newline();
+ if !error_occurred then begin
+ prerr_endline "************* TEST FAILED ****************"; exit 2
+ end else
+ exit 0
diff --git a/testsuite/tests/basic/boxedints.reference b/testsuite/tests/basic/boxedints.reference
new file mode 100644
index 0000000000..009390faee
--- /dev/null
+++ b/testsuite/tests/basic/boxedints.reference
@@ -0,0 +1,118 @@
+
+-------- Int32 --------
+
+of_int, to_int
+ 1... 2... 3... 4... 5...
+of_string
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11...
+to_string, format
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19...
+neg
+ 1... 2... 3... 4... 5... 6...
+add
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13...
+sub
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+mul
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13...
+div
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+mod
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+and
+ 1... 2... 3... 4... 5...
+or
+ 1... 2... 3... 4... 5...
+xor
+ 1... 2... 3... 4... 5...
+shift_left
+ 1... 2... 3... 4... 5... 6... 7... 8...
+shift_right
+ 1... 2... 3... 4... 5... 6... 7...
+shift_right_logical
+ 1... 2... 3... 4... 5... 6... 7...
+of_float
+ 1... 2... 3... 4... 5... 6... 7...
+to_float
+ 1... 2... 3... 4... 5...
+Comparisons
+ 1... 2... 3... 4... 5... 6... 7...
+
+-------- Int64 --------
+
+of_int, to_int
+ 1... 2... 3... 4... 5...
+of_string
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11...
+to_string, format
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19...
+neg
+ 1... 2... 3... 4... 5... 6...
+add
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13...
+sub
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+mul
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13...
+div
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+mod
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+and
+ 1... 2... 3... 4... 5...
+or
+ 1... 2... 3... 4... 5...
+xor
+ 1... 2... 3... 4... 5...
+shift_left
+ 1... 2... 3... 4... 5... 6... 7... 8...
+shift_right
+ 1... 2... 3... 4... 5... 6... 7...
+shift_right_logical
+ 1... 2... 3... 4... 5... 6... 7...
+Comparisons
+ 1... 2... 3... 4... 5... 6... 7...
+
+-------- Nativeint --------
+
+of_int, to_int
+ 1... 2... 3... 4... 5...
+of_string
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11...
+to_string, format
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19...
+neg
+ 1... 2... 3... 4... 5... 6...
+add
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13...
+sub
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+mul
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13...
+div
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+mod
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+and
+ 1... 2... 3... 4... 5...
+or
+ 1... 2... 3... 4... 5...
+xor
+ 1... 2... 3... 4... 5...
+shift_left
+ 1... 2... 3... 4... 5... 6... 7... 8...
+shift_right
+ 1... 2... 3... 4... 5... 6... 7...
+shift_right_logical
+ 1... 2... 3... 4... 5... 6... 7...
+Comparisons
+ 1... 2... 3... 4... 5... 6... 7...
+
+--------- Conversions -----------
+
+nativeint of/to int32
+ 1... 2... 3...
+int64 of/to int32
+ 1... 2... 3...
+int64 of/to nativeint
+ 1... 2... 3...
diff --git a/testsuite/tests/basic/constprop.ml b/testsuite/tests/basic/constprop.ml
new file mode 100644
index 0000000000..62bf5f25c7
--- /dev/null
+++ b/testsuite/tests/basic/constprop.ml
@@ -0,0 +1,116 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test constant propagation through inlining *)
+
+(* constprop.ml is generated from constprop.mlp using
+ cpp constprop.mlp > constprop.ml
+*)
+let do_test msg res1 res2 =
+ Printf.printf "%s: %s\n" msg (if res1 = res2 then "passed" else "FAILED")
+(* Hide a constant from the optimizer, preventing constant propagation *)
+let hide x = List.nth [x] 0
+let _ =
+ begin
+ let x = true and y = false in
+ let xh = hide x and yh = hide y in
+ do_test "booleans" ((x && y, x || y, not x)) ((xh && yh, xh || yh, not xh))
+ end;
+ begin
+ let x = 89809344 and y = 457455773 and s = 7 in
+ let xh = hide x and yh = hide y and sh = hide s in
+ do_test "integers"
+ ((-x, x + y, x - y, x * y, x / y, x mod y, x land y,
+ x lor y, x lxor y, x lsl s, x lsr s, x asr s, x = y,
+ x <> y, x < y, x <= y, x > y, x >= y, succ x, pred y))
+ ((-xh, xh + yh, xh - yh, xh * yh, xh / yh, xh mod yh, xh land yh,
+ xh lor yh, xh lxor yh, xh lsl sh, xh lsr sh, xh asr sh, xh = yh,
+ xh <> yh, xh < yh, xh <= yh, xh > yh, xh >= yh, succ xh, pred yh))
+ end;
+ begin
+ let x = 3.141592654 and y = 0.341638588598232096 in
+ let xh = hide x and yh = hide y in
+ do_test "floats"
+ ((int_of_float x, x +. y, x -. y, x *. y, x /. y, x = y,
+ x <> y, x < y, x <= y, x > y, x >= y))
+ ((int_of_float xh, xh +. yh, xh -. yh, xh *. yh, xh /. yh, xh = yh,
+ xh <> yh, xh < yh, xh <= yh, xh > yh, xh >= yh))
+ end;
+ begin
+ let x = 781944104l and y = 308219921l and s = 3 in
+ let xh = hide x and yh = hide y and sh = hide s in
+ do_test "32-bit integers"
+ (Int32.(neg x, add x y, sub x y, mul x y, div x y, rem x y,
+ logand x y, logor x y, logxor x y, shift_left x s,
+ shift_right x s, shift_right_logical x s, x = y, x <> y,
+ x < y, x <= y, x > y, x >= y))
+ (Int32.(neg xh, add xh yh, sub xh yh, mul xh yh, div xh yh, rem xh yh,
+ logand xh yh, logor xh yh, logxor xh yh, shift_left xh sh,
+ shift_right xh sh, shift_right_logical xh sh, xh = yh, xh <> yh,
+ xh < yh, xh <= yh, xh > yh, xh >= yh))
+ end;
+ begin
+ let x = 1828697041n and y = -521695949n and s = 8 in
+ let xh = hide x and yh = hide y and sh = hide s in
+ do_test "native integers"
+ (Nativeint.(neg x, add x y, sub x y, mul x y, div x y,
+ rem x y, logand x y, logor x y, logxor x y,
+ shift_left x s, shift_right x s,
+ shift_right_logical x s, x = y, x <> y, x < y,
+ x <= y, x > y, x >= y))
+ (Nativeint.(neg xh, add xh yh, sub xh yh, mul xh yh, div xh yh,
+ rem xh yh, logand xh yh, logor xh yh, logxor xh yh,
+ shift_left xh sh, shift_right xh sh,
+ shift_right_logical xh sh, xh = yh, xh <> yh, xh < yh,
+ xh <= yh, xh > yh, xh >= yh))
+ end;
+ begin
+ let x = 1511491586921138079L and y = 6677538715441746158L and s = 17 in
+ let xh = hide x and yh = hide y and sh = hide s in
+ do_test "64-bit integers"
+ (Int64.(neg x, add x y, sub x y, mul x y, div x y, rem x y,
+ logand x y, logor x y, logxor x y, shift_left x s,
+ shift_right x s, shift_right_logical x s, x = y, x <> y,
+ x < y, x <= y, x > y, x >= y))
+ (Int64.(neg xh, add xh yh, sub xh yh, mul xh yh, div xh yh, rem xh yh,
+ logand xh yh, logor xh yh, logxor xh yh, shift_left xh sh,
+ shift_right xh sh, shift_right_logical xh sh, xh = yh, xh <> yh,
+ xh < yh, xh <= yh, xh > yh, xh >= yh))
+ end;
+ begin
+ let x = 1000807289 in
+ let xh = hide x in
+ do_test "integer conversions"
+ ((float_of_int x, Int32.of_int x, Nativeint.of_int x, Int64.of_int x))
+ ((float_of_int xh, Int32.of_int xh, Nativeint.of_int xh, Int64.of_int xh))
+ end;
+ begin
+ let x = 10486393l in
+ let xh = hide x in
+ do_test "32-bit integer conversions"
+ ((Int32.to_int x, Nativeint.of_int32 x, Int64.of_int32 x))
+ ((Int32.to_int xh, Nativeint.of_int32 xh, Int64.of_int32 xh))
+ end;
+ begin
+ let x = -131134014n in
+ let xh = hide x in
+ do_test "native integer conversions"
+ ((Nativeint.to_int x, Nativeint.to_int32 x, Int64.of_nativeint x))
+ ((Nativeint.to_int xh, Nativeint.to_int32 xh, Int64.of_nativeint xh))
+ end;
+ begin
+ let x = 531871273453404175L in
+ let xh = hide x in
+ do_test "64-bit integer conversions"
+ ((Int64.to_int x, Int64.to_int32 x, Int64.to_nativeint x))
+ ((Int64.to_int xh, Int64.to_int32 xh, Int64.to_nativeint xh))
+ end
diff --git a/testsuite/tests/basic/constprop.mlp b/testsuite/tests/basic/constprop.mlp
new file mode 100644
index 0000000000..40bcf42389
--- /dev/null
+++ b/testsuite/tests/basic/constprop.mlp
@@ -0,0 +1,129 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test constant propagation through inlining *)
+
+(* constprop.ml is generated from constprop.mlp using
+ cpp constprop.mlp > constprop.ml
+*)
+
+#define tbool(x,y) \
+ (x && y, x || y, not x)
+
+#define tint(x,y,s) \
+ (-x, x + y, x - y, x * y, x / y, x mod y, \
+ x land y, x lor y, x lxor y, \
+ x lsl s, x lsr s, x asr s, \
+ x = y, x <> y, x < y, x <= y, x > y, x >= y, \
+ succ x, pred y)
+
+#define tfloat(x,y) \
+ (int_of_float x, \
+ x +. y, x -. y, x *. y, x /. y, \
+ x = y, x <> y, x < y, x <= y, x > y, x >= y)
+
+#define tconvint(i) \
+ (float_of_int i, \
+ Int32.of_int i, \
+ Nativeint.of_int i, \
+ Int64.of_int i)
+
+#define tconvint32(i) \
+ (Int32.to_int i, \
+ Nativeint.of_int32 i, \
+ Int64.of_int32 i)
+
+#define tconvnativeint(i) \
+ (Nativeint.to_int i, \
+ Nativeint.to_int32 i, \
+ Int64.of_nativeint i)
+
+#define tconvint64(i) \
+ (Int64.to_int i, \
+ Int64.to_int32 i, \
+ Int64.to_nativeint i) \
+
+#define tint32(x,y,s) \
+ Int32.(neg x, add x y, sub x y, mul x y, div x y, rem x y, \
+ logand x y, logor x y, logxor x y, \
+ shift_left x s, shift_right x s, shift_right_logical x s, \
+ x = y, x <> y, x < y, x <= y, x > y, x >= y)
+
+#define tnativeint(x,y,s) \
+ Nativeint.(neg x, add x y, sub x y, mul x y, div x y, rem x y, \
+ logand x y, logor x y, logxor x y, \
+ shift_left x s, shift_right x s, shift_right_logical x s, \
+ x = y, x <> y, x < y, x <= y, x > y, x >= y)
+
+#define tint64(x,y,s) \
+ Int64.(neg x, add x y, sub x y, mul x y, div x y, rem x y, \
+ logand x y, logor x y, logxor x y, \
+ shift_left x s, shift_right x s, shift_right_logical x s, \
+ x = y, x <> y, x < y, x <= y, x > y, x >= y)
+
+let do_test msg res1 res2 =
+ Printf.printf "%s: %s\n" msg (if res1 = res2 then "passed" else "FAILED")
+
+(* Hide a constant from the optimizer, preventing constant propagation *)
+let hide x = List.nth [x] 0
+
+let _ =
+ begin
+ let x = true and y = false in
+ let xh = hide x and yh = hide y in
+ do_test "booleans" (tbool(x, y)) (tbool(xh,yh))
+ end;
+ begin
+ let x = 89809344 and y = 457455773 and s = 7 in
+ let xh = hide x and yh = hide y and sh = hide s in
+ do_test "integers" (tint(x, y, s)) (tint(xh,yh,sh))
+ end;
+ begin
+ let x = 3.141592654 and y = 0.341638588598232096 in
+ let xh = hide x and yh = hide y in
+ do_test "floats" (tfloat(x, y)) (tfloat(xh, yh))
+ end;
+ begin
+ let x = 781944104l and y = 308219921l and s = 3 in
+ let xh = hide x and yh = hide y and sh = hide s in
+ do_test "32-bit integers" (tint32(x, y, s)) (tint32(xh, yh, sh))
+ end;
+ begin
+ let x = 1828697041n and y = -521695949n and s = 8 in
+ let xh = hide x and yh = hide y and sh = hide s in
+ do_test "native integers" (tnativeint(x, y, s)) (tnativeint(xh, yh, sh))
+ end;
+ begin
+ let x = 1511491586921138079L and y = 6677538715441746158L and s = 17 in
+ let xh = hide x and yh = hide y and sh = hide s in
+ do_test "64-bit integers" (tint64(x, y, s)) (tint64(xh, yh, sh))
+ end;
+ begin
+ let x = 1000807289 in
+ let xh = hide x in
+ do_test "integer conversions" (tconvint(x)) (tconvint(xh))
+ end;
+ begin
+ let x = 10486393l in
+ let xh = hide x in
+ do_test "32-bit integer conversions" (tconvint32(x)) (tconvint32(xh))
+ end;
+ begin
+ let x = -131134014n in
+ let xh = hide x in
+ do_test "native integer conversions" (tconvnativeint(x))(tconvnativeint(xh))
+ end;
+ begin
+ let x = 531871273453404175L in
+ let xh = hide x in
+ do_test "64-bit integer conversions" (tconvint64(x)) (tconvint64(xh))
+ end
diff --git a/testsuite/tests/basic/constprop.reference b/testsuite/tests/basic/constprop.reference
new file mode 100644
index 0000000000..59590530ae
--- /dev/null
+++ b/testsuite/tests/basic/constprop.reference
@@ -0,0 +1,10 @@
+booleans: passed
+integers: passed
+floats: passed
+32-bit integers: passed
+native integers: passed
+64-bit integers: passed
+integer conversions: passed
+32-bit integer conversions: passed
+native integer conversions: passed
+64-bit integer conversions: passed
diff --git a/testsuite/tests/basic/divint.ml b/testsuite/tests/basic/divint.ml
new file mode 100644
index 0000000000..e5a3d59dd1
--- /dev/null
+++ b/testsuite/tests/basic/divint.ml
@@ -0,0 +1,152 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+
+(* Test integer division and modulus, esp. ocamlopt's optimization
+ when the divisor is a constant. *)
+
+let error = ref false
+
+module WithInt = struct
+
+let d = ref 0
+let divref n = n / !d
+let modref n = n mod !d
+
+let test_one (df: int -> int) (mf: int -> int) x =
+ if not (df x = divref x && mf x = modref x) then begin
+ printf "mismatch for %d\n" x;
+ error := true
+ end
+
+let do_test divisor (df: int -> int) (mf: int -> int) =
+ d := divisor;
+ List.iter (test_one df mf)
+ [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10;
+ 100; 1000; 10000; 100000; 1000000; max_int - 1; max_int;
+ -1; -2; -3; -4; -5; -6; -7; -8; -9; -10;
+ -100; -1000; -10000; -100000; -1000000; min_int + 1; min_int];
+ let seed = ref 0 in
+ for i = 1 to 1000 do
+ seed := !seed * 69069 + 25173;
+ test_one df mf !seed
+ done
+
+end
+
+module WithNat = struct
+
+let d = ref 0n
+let divref n = Nativeint.div n !d
+let modref n = Nativeint.rem n !d
+
+let test_one (df: nativeint -> nativeint) (mf: nativeint -> nativeint) x =
+ if not (df x = divref x && mf x = modref x) then begin
+ printf "mismatch for %nd\n" x;
+ error := true
+ end
+
+let do_test divisor (df: nativeint -> nativeint) (mf: nativeint -> nativeint) =
+ d := Nativeint.of_int divisor;
+ List.iter (test_one df mf)
+ [0n; 1n; 2n; 3n; 4n; 5n; 6n; 7n; 8n; 9n; 10n;
+ 100n; 1000n; 10000n; 100000n; 1000000n;
+ Nativeint.(pred max_int); Nativeint.max_int;
+ -1n; -2n; -3n; -4n; -5n; -6n; -7n; -8n; -9n; -10n;
+ -100n; -1000n; -10000n; -100000n; -1000000n;
+ Nativeint.(succ min_int); Nativeint.min_int];
+ let seed = ref 0n in
+ for i = 1 to 1000 do
+ seed := Nativeint.(add (mul !seed 69069n) 25173n);
+ test_one df mf !seed
+ done
+
+end
+
+let _ =
+ printf "1 int\n"; WithInt.do_test 1 (fun x -> x / 1)(fun x -> x mod 1);
+ printf "2 int\n"; WithInt.do_test 2 (fun x -> x / 2)(fun x -> x mod 2);
+ printf "3 int\n"; WithInt.do_test 3 (fun x -> x / 3)(fun x -> x mod 3);
+ printf "4 int\n"; WithInt.do_test 4 (fun x -> x / 4)(fun x -> x mod 4);
+ printf "5 int\n"; WithInt.do_test 5 (fun x -> x / 5)(fun x -> x mod 5);
+ printf "6 int\n"; WithInt.do_test 6 (fun x -> x / 6)(fun x -> x mod 6);
+ printf "7 int\n"; WithInt.do_test 7 (fun x -> x / 7)(fun x -> x mod 7);
+ printf "9 int\n"; WithInt.do_test 9 (fun x -> x / 9)(fun x -> x mod 9);
+ printf "10 int\n"; WithInt.do_test 10 (fun x -> x / 10)(fun x -> x mod 10);
+ printf "11 int\n"; WithInt.do_test 11 (fun x -> x / 11)(fun x -> x mod 11);
+ printf "12 int\n"; WithInt.do_test 12 (fun x -> x / 12)(fun x -> x mod 12);
+ printf "25 int\n"; WithInt.do_test 25 (fun x -> x / 25)(fun x -> x mod 25);
+ printf "55 int\n"; WithInt.do_test 55 (fun x -> x / 55)(fun x -> x mod 55);
+ printf "125 int\n";
+ WithInt.do_test 125 (fun x -> x / 125)(fun x -> x mod 125);
+ printf "625 int\n";
+ WithInt.do_test 625 (fun x -> x / 625)(fun x -> x mod 625);
+ printf "-1 int\n";
+ WithInt.do_test (-1) (fun x -> x / (-1))(fun x -> x mod (-1));
+ printf "-2 int\n";
+ WithInt.do_test (-2) (fun x -> x / (-2))(fun x -> x mod (-2));
+ printf "-3 int\n";
+ WithInt.do_test (-3) (fun x -> x / (-3))(fun x -> x mod (-3));
+
+ printf "1 nat\n";
+ WithNat.do_test 1 (fun x -> Nativeint.div x 1n)(fun x -> Nativeint.rem x 1n);
+ printf "2 nat\n";
+ WithNat.do_test 2 (fun x -> Nativeint.div x 2n)(fun x -> Nativeint.rem x 2n);
+ printf "3 nat\n";
+ WithNat.do_test 3 (fun x -> Nativeint.div x 3n)(fun x -> Nativeint.rem x 3n);
+ printf "4 nat\n";
+ WithNat.do_test 4 (fun x -> Nativeint.div x 4n)(fun x -> Nativeint.rem x 4n);
+ printf "5 nat\n";
+ WithNat.do_test 5 (fun x -> Nativeint.div x 5n)(fun x -> Nativeint.rem x 5n);
+ printf "6 nat\n";
+ WithNat.do_test 6 (fun x -> Nativeint.div x 6n)(fun x -> Nativeint.rem x 6n);
+ printf "7 nat\n";
+ WithNat.do_test 7 (fun x -> Nativeint.div x 7n)(fun x -> Nativeint.rem x 7n);
+ printf "9 nat\n";
+ WithNat.do_test 9 (fun x -> Nativeint.div x 9n)(fun x -> Nativeint.rem x 9n);
+ printf "10 nat\n";
+ WithNat.do_test 10 (fun x -> Nativeint.div x 10n)
+ (fun x -> Nativeint.rem x 10n);
+ printf "11 nat\n";
+ WithNat.do_test 11 (fun x -> Nativeint.div x 11n)
+ (fun x -> Nativeint.rem x 11n);
+ printf "12 nat\n";
+ WithNat.do_test 12 (fun x -> Nativeint.div x 12n)
+ (fun x -> Nativeint.rem x 12n);
+ printf "25 nat\n";
+ WithNat.do_test 25 (fun x -> Nativeint.div x 25n)
+ (fun x -> Nativeint.rem x 25n);
+ printf "55 nat\n";
+ WithNat.do_test 55 (fun x -> Nativeint.div x 55n)
+ (fun x -> Nativeint.rem x 55n);
+ printf "125 nat\n";
+ WithNat.do_test 125 (fun x -> Nativeint.div x 125n)
+ (fun x -> Nativeint.rem x 125n);
+ printf "625 nat\n";
+ WithNat.do_test 625 (fun x -> Nativeint.div x 625n)
+ (fun x -> Nativeint.rem x 625n);
+ printf "-1 nat\n";
+ WithNat.do_test (-1) (fun x -> Nativeint.div x (-1n))
+ (fun x -> Nativeint.rem x (-1n));
+ printf "-2 nat\n";
+ WithNat.do_test (-2) (fun x -> Nativeint.div x (-2n))
+ (fun x -> Nativeint.rem x (-2n));
+ printf "-3 nat\n";
+ WithNat.do_test (-3) (fun x -> Nativeint.div x (-3n))
+ (fun x -> Nativeint.rem x (-3n));
+
+ if !error then printf "TEST FAILED.\n" else printf "Test passed.\n"
+
+(* PR#6879 *)
+let f n = assert (1 mod n = 0)
+let () = f 1
diff --git a/testsuite/tests/basic/divint.reference b/testsuite/tests/basic/divint.reference
new file mode 100644
index 0000000000..e9a6387fa8
--- /dev/null
+++ b/testsuite/tests/basic/divint.reference
@@ -0,0 +1,37 @@
+1 int
+2 int
+3 int
+4 int
+5 int
+6 int
+7 int
+9 int
+10 int
+11 int
+12 int
+25 int
+55 int
+125 int
+625 int
+-1 int
+-2 int
+-3 int
+1 nat
+2 nat
+3 nat
+4 nat
+5 nat
+6 nat
+7 nat
+9 nat
+10 nat
+11 nat
+12 nat
+25 nat
+55 nat
+125 nat
+625 nat
+-1 nat
+-2 nat
+-3 nat
+Test passed.
diff --git a/testsuite/tests/basic/equality.ml b/testsuite/tests/basic/equality.ml
new file mode 100644
index 0000000000..ad72e5d02a
--- /dev/null
+++ b/testsuite/tests/basic/equality.ml
@@ -0,0 +1,116 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let test n check res =
+ print_string "Test "; print_int n;
+ if check res then print_string " passed.\n" else print_string " FAILED.\n";
+ flush stderr
+
+let eq0 = function 0 -> true | _ -> false
+let eqm1 = function -1 -> true | _ -> false
+let eq1 = function 1 -> true | _ -> false
+let eqtrue (b:bool) = b
+let eqftffff =
+ function (false,true,false,false,false,false) -> true | _ -> false
+
+let x = [1;2;3]
+
+let f x = 1 :: 2 :: 3 :: x
+
+let mklist len =
+ let l = ref [] in
+ for i = 1 to len do l := i :: !l done;
+ !l
+
+type tree = Dummy | Leaf | Node of tree * tree
+
+let rec mktree depth =
+ if depth <= 0 then Leaf else Node(mktree(depth - 1), mktree(depth - 1))
+
+type 'a leftlist = Nil | Cons of 'a leftlist * 'a
+
+let mkleftlist len =
+ let l = ref Nil in
+ for i = 1 to len do l := Cons(!l, i) done;
+ !l
+
+let _ =
+ test 1 eq0 (compare 0 0);
+ test 2 eqm1 (compare 0 1);
+ test 3 eq1 (compare 1 0);
+ test 4 eq0 (compare max_int max_int);
+ test 5 eqm1 (compare min_int max_int);
+ test 6 eq1 (compare max_int min_int);
+ test 7 eq0 (compare "foo" "foo");
+ test 8 eqm1 (compare "foo" "zorglub");
+ test 9 eqm1 (compare "abcdef" "foo");
+ test 10 eqm1 (compare "abcdefghij" "abcdefghijkl");
+ test 11 eq1 (compare "abcdefghij" "abcdefghi");
+ test 12 eq0 (compare (0,1) (0,1));
+ test 13 eqm1 (compare (0,1) (0,2));
+ test 14 eqm1 (compare (0,1) (1,0));
+ test 15 eq1 (compare (0,1) (0,0));
+ test 16 eq1 (compare (1,0) (0,1));
+ test 17 eq0 (compare 0.0 0.0);
+ test 18 eqm1 (compare 0.0 1.0);
+ test 19 eqm1 (compare (-1.0) 0.0);
+ test 20 eq0 (compare [| 0.0; 1.0; 2.0 |] [| 0.0; 1.0; 2.0 |]);
+ test 21 eqm1 (compare [| 0.0; 1.0; 2.0 |] [| 0.0; 1.0; 3.0 |]);
+ test 22 eq1 (compare [| 0.0; 5.0; 2.0 |] [| 0.0; 1.0; 2.0 |]);
+ test 23 eq0 (compare [1;2;3;4] [1;2;3;4]);
+ test 24 eqm1 (compare [1;2;3;4] [1;2;5;6]);
+ test 25 eqm1 (compare [1;2;3;4] [1;2;3;4;5]);
+ test 26 eq1 (compare [1;2;3;4] [1;2;3]);
+ test 27 eq1 (compare [1;2;3;4] [1;2;0;4]);
+ test 28 eq0 (compare (mklist 1000) (mklist 1000));
+ test 29 eq0 (compare (mkleftlist 1000) (mkleftlist 1000));
+ test 30 eq0 (compare (mktree 12) (mktree 12));
+ test 31 eqtrue (x = f []);
+ test 32 eqtrue (stdout <> stderr);
+ test 33 eqm1 (compare nan 0.0);
+ test 34 eqm1 (compare nan neg_infinity);
+ test 35 eq0 (compare nan nan);
+ test 36 eqm1 (compare (0.0, nan) (0.0, 0.0));
+ test 37 eqm1 (compare (0.0, nan) (0.0, neg_infinity));
+ test 38 eq0 (compare (nan, 0.0) (nan, 0.0));
+ let cmpgen x y = (x=y, x<>y, x<y, x<=y, x>y, x>=y) in
+ let cmpfloat (x:float) (y:float) = (x=y, x<>y, x<y, x<=y, x>y, x>=y) in
+ test 39 eqftffff (cmpgen nan nan);
+ test 40 eqftffff (cmpgen nan 0.0);
+ test 41 eqftffff (cmpfloat nan nan);
+ test 42 eqftffff (cmpfloat nan 0.0);
+ test 43 eqtrue ([||] = [||]);
+ (* Convoluted forms to test both the "positive" and "negative" cases
+ of float tests *)
+ let cmpfloatpos (x:float) (y:float) =
+ ((let r = ref false in (if x = y then r := true); !r),
+ (let r = ref false in (if x <> y then r := true); !r),
+ (let r = ref false in (if x < y then r := true); !r),
+ (let r = ref false in (if x <= y then r := true); !r),
+ (let r = ref false in (if x > y then r := true); !r),
+ (let r = ref false in (if x >= y then r := true); !r))
+ and cmpfloatneg (x:float) (y:float) =
+ ((let r = ref true in (if not (x = y) then r := false); !r),
+ (let r = ref true in (if not (x <> y) then r := false); !r),
+ (let r = ref true in (if not (x < y) then r := false); !r),
+ (let r = ref true in (if not (x <= y) then r := false); !r),
+ (let r = ref true in (if not (x > y) then r := false); !r),
+ (let r = ref true in (if not (x >= y) then r := false); !r)) in
+ let testcmpfloat x y =
+ cmpfloatpos x y = cmpgen x y &&
+ cmpfloatneg x y = cmpgen x y in
+ test 50 eqtrue (testcmpfloat nan nan);
+ test 51 eqtrue (testcmpfloat nan 0.0);
+ test 52 eqtrue (testcmpfloat 0.0 nan);
+ test 53 eqtrue (testcmpfloat 0.0 0.0);
+ test 54 eqtrue (testcmpfloat 1.0 0.0);
+ test 55 eqtrue (testcmpfloat 0.0 1.0)
diff --git a/testsuite/tests/basic/equality.reference b/testsuite/tests/basic/equality.reference
new file mode 100644
index 0000000000..6070a6b0a0
--- /dev/null
+++ b/testsuite/tests/basic/equality.reference
@@ -0,0 +1,49 @@
+Test 1 passed.
+Test 2 passed.
+Test 3 passed.
+Test 4 passed.
+Test 5 passed.
+Test 6 passed.
+Test 7 passed.
+Test 8 passed.
+Test 9 passed.
+Test 10 passed.
+Test 11 passed.
+Test 12 passed.
+Test 13 passed.
+Test 14 passed.
+Test 15 passed.
+Test 16 passed.
+Test 17 passed.
+Test 18 passed.
+Test 19 passed.
+Test 20 passed.
+Test 21 passed.
+Test 22 passed.
+Test 23 passed.
+Test 24 passed.
+Test 25 passed.
+Test 26 passed.
+Test 27 passed.
+Test 28 passed.
+Test 29 passed.
+Test 30 passed.
+Test 31 passed.
+Test 32 passed.
+Test 33 passed.
+Test 34 passed.
+Test 35 passed.
+Test 36 passed.
+Test 37 passed.
+Test 38 passed.
+Test 39 passed.
+Test 40 passed.
+Test 41 passed.
+Test 42 passed.
+Test 43 passed.
+Test 50 passed.
+Test 51 passed.
+Test 52 passed.
+Test 53 passed.
+Test 54 passed.
+Test 55 passed.
diff --git a/testsuite/tests/basic/float.ml b/testsuite/tests/basic/float.ml
new file mode 100644
index 0000000000..e10059e2b2
--- /dev/null
+++ b/testsuite/tests/basic/float.ml
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocqencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+Printf.printf "1./.0. = %f\n" (1.0 /. 0.0);;
diff --git a/testsuite/tests/basic/float.reference b/testsuite/tests/basic/float.reference
new file mode 100644
index 0000000000..3e7bab44dd
--- /dev/null
+++ b/testsuite/tests/basic/float.reference
@@ -0,0 +1 @@
+1./.0. = inf
diff --git a/testsuite/tests/basic/includestruct.ml b/testsuite/tests/basic/includestruct.ml
new file mode 100644
index 0000000000..ae68381070
--- /dev/null
+++ b/testsuite/tests/basic/includestruct.ml
@@ -0,0 +1,103 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test for "include <module-expr>" inside structures *)
+
+module A =
+ struct
+ type t = int
+ let x = (1 : t)
+ let y = (2 : t)
+ let f (z : t) = (x + z : t)
+ end
+
+module B =
+ struct
+ include A
+ type u = t * t
+ let p = ((x, y) : u)
+ let g ((x, y) : u) = ((f x, f y) : u)
+ end
+
+let _ =
+ let print_pair (x,y) =
+ print_int x; print_string ", "; print_int y; print_newline() in
+ print_pair B.p;
+ print_pair (B.g B.p);
+ print_pair (B.g (123, 456))
+
+module H =
+ struct
+ include A
+ let f (z : t) = (x - 1 : t)
+ end
+
+let _ =
+ print_int (H.f H.x); print_newline()
+
+module C =
+ struct
+ include (A : sig type t val f : t -> int val x : t end)
+ let z = f x
+ end
+
+let _ =
+ print_int C.z; print_newline();
+ print_int (C.f C.x); print_newline()
+
+(* Toplevel inclusion *)
+
+include A
+
+let _ =
+ print_int x; print_newline();
+ print_int (f y); print_newline()
+
+(* With a functor *)
+
+module F(X: sig end) =
+ struct
+ let _ = print_string "F is called"; print_newline()
+ type t = A | B of int
+ let print_t = function A -> print_string "A"
+ | B x -> print_int x
+ end
+
+module D =
+ struct
+ include F(struct end)
+ let test() = print_t A; print_newline(); print_t (B 42); print_newline()
+ end
+
+let _ =
+ D.test();
+ D.print_t D.A; print_newline(); D.print_t (D.B 42); print_newline()
+
+(* Exceptions and classes *)
+
+module E =
+ struct
+ exception Exn of string
+ class c = object method m = 1 end
+ end
+
+module G =
+ struct
+ include E
+ let _ =
+ begin try raise (Exn "foo") with Exn s -> print_string s end;
+ print_int ((new c)#m); print_newline()
+ end
+
+let _ =
+ begin try raise (G.Exn "foo") with G.Exn s -> print_string s end;
+ print_int ((new G.c)#m); print_newline()
diff --git a/testsuite/tests/basic/includestruct.reference b/testsuite/tests/basic/includestruct.reference
new file mode 100644
index 0000000000..a7756837ec
--- /dev/null
+++ b/testsuite/tests/basic/includestruct.reference
@@ -0,0 +1,15 @@
+1, 2
+2, 3
+124, 457
+0
+2
+2
+1
+3
+F is called
+A
+42
+A
+42
+foo1
+foo1
diff --git a/testsuite/tests/basic/maps.ml b/testsuite/tests/basic/maps.ml
new file mode 100644
index 0000000000..38b0d2b0c1
--- /dev/null
+++ b/testsuite/tests/basic/maps.ml
@@ -0,0 +1,36 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+module IntMap = Map.Make(struct type t = int let compare x y = x-y end)
+
+let m1 = IntMap.add 4 "Y" (IntMap.singleton 3 "X1")
+let m2 = IntMap.add 4 "Y" (IntMap.singleton 5 "X2")
+
+let show m = IntMap.iter (fun k v -> Printf.printf "%d %s\n" k v) m
+
+let () =
+ print_endline "Union+concat";
+ let f1 _ l r =
+ match l, r with
+ | Some x, None | None, Some x -> Some x
+ | Some x, Some y -> Some (x ^ x)
+ | _ -> assert false
+ in
+ show (IntMap.merge f1 m1 m2);
+ print_endline "Inter";
+ let f2 _ l r =
+ match l, r with
+ | Some x, Some y when x = y -> Some x
+ | _ -> None
+ in
+ show (IntMap.merge f2 m1 m2);
+ ()
diff --git a/testsuite/tests/basic/maps.reference b/testsuite/tests/basic/maps.reference
new file mode 100644
index 0000000000..c7b0c08339
--- /dev/null
+++ b/testsuite/tests/basic/maps.reference
@@ -0,0 +1,6 @@
+Union+concat
+3 X1
+4 YY
+5 X2
+Inter
+4 Y
diff --git a/testsuite/tests/basic/patmatch.ml b/testsuite/tests/basic/patmatch.ml
new file mode 100644
index 0000000000..0f759bc408
--- /dev/null
+++ b/testsuite/tests/basic/patmatch.ml
@@ -0,0 +1,1612 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Tests for matchings on integers and characters *)
+
+(* Dense integer switch *)
+
+let f = function 1 -> 1 | 2 -> 2 | 3 -> 3 | 4 -> 4 | 5 -> 5 | 6 -> 6 | _ -> 0
+
+(* Sparse integer switch *)
+
+let g = function 303 -> 1 | 401 -> 2 | _ -> 0
+
+(* Very sparse integer switch *)
+
+let iszero = function 0 -> true | _ -> false
+
+(* Simple matching on characters *)
+
+let h = function
+ 'a' -> "a"
+ | 'e' -> "e"
+ | 'i' -> "i"
+ | 'o' -> "o"
+ | 'u' -> "u"
+ | _ -> "?"
+
+(* Matching with orpats *)
+
+let k = function
+ ' ' | '\t' | '\n' | '\r' -> "blk"
+ | 'A'..'Z' | 'a'..'z' | '\192'..'\255' -> "letr"
+ | '0'..'9' -> "dig"
+ | '!'|'%'|'&'|'$'|'#'|'+'|'/'|':'|'<'|'='|'>'|'?'|'@'|'\\'|
+ '~'|'^'|'|'|'*' -> "oper"
+ | _ -> "othr"
+
+(* Matching on arrays *)
+
+let p = function [| x |] -> x | _ -> assert false
+
+let q = function [| x |] -> x | _ -> 0
+
+let r = function [| x |] -> x | _ -> 0.0
+
+let l = function
+ [||] -> 0
+ | [|x|] -> x + 1
+ | [|x;y|] -> x + y
+ | [|x;y;z|] -> x + y + z
+ | _ -> assert false
+
+(* The test *)
+
+open Printf
+
+external string_create: int -> string = "caml_create_string"
+external unsafe_chr: int -> char = "%identity"
+external string_unsafe_set : string -> int -> char -> unit
+ = "%string_unsafe_set"
+
+(* The following function is roughly equivalent to Char.escaped,
+ except that it is locale-independent. *)
+let escaped = function
+ | '\'' -> "\\'"
+ | '\\' -> "\\\\"
+ | '\n' -> "\\n"
+ | '\t' -> "\\t"
+ | '\r' -> "\\r"
+ | '\b' -> "\\b"
+ | c ->
+ if ((k c) <> "othr") && ((Char.code c) <= 191) then begin
+ let s = string_create 1 in
+ string_unsafe_set s 0 c;
+ s
+ end else begin
+ let n = Char.code c in
+ let s = string_create 4 in
+ string_unsafe_set s 0 '\\';
+ string_unsafe_set s 1 (unsafe_chr (48 + n / 100));
+ string_unsafe_set s 2 (unsafe_chr (48 + (n / 10) mod 10));
+ string_unsafe_set s 3 (unsafe_chr (48 + n mod 10));
+ s
+ end
+
+let _ =
+ for i = -5 to 10 do printf "f(%d) = %d\n" i (f i) done;
+ List.iter (fun i -> printf "g(%d) = %d\n" i (g i))
+ [0;300;303;305;400;401;402;999];
+ for i = -2 to 2 do printf "iszero(%d) = %B\n" i (iszero i) done;
+ for i = 97 to 126 do
+ let c = Char.chr i in
+ printf "h(%c) = %s\n" c (h c)
+ done;
+ for i = 0 to 255 do
+ let c = Char.chr i in
+ printf "\tk(%s) = %s" (escaped c) (k c)
+ done;
+ printf "\n";
+ printf "p([|\"hello\"|]) = %s\n" (p [|"hello"|]);
+ printf "p([|1.0|]) = %f\n" (p [|1.0|]);
+ printf "q([|2|]) = %d\n" (q [|2|]);
+ printf "r([|3.0|]) = %f\n" (r [|3.0|]);
+ printf "l([||]) = %d\n" (l [||]);
+ printf "l([|1|]) = %d\n" (l [|1|]);
+ printf "l([|2;3|]) = %d\n" (l [|2;3|]);
+ printf "l([|4;5;6|]) = %d\n" (l [|4;5;6|])
+
+(* PR #5992 *)
+(* Was segfaulting *)
+
+let f = function
+ | lazy (), _, {contents=None} -> 0
+ | _, lazy (), {contents=Some x} -> 1
+
+let s = ref None
+let set_true = lazy (s := Some 1)
+let set_false = lazy (s := None)
+
+let () =
+ let _r = try f (set_true, set_false, s) with Match_failure _ -> 2 in
+ printf "PR#5992=Ok\n"
+
+(* PR #5788, was giving wrong result 3 *)
+exception Foo
+exception Bar = Foo
+
+let test e b =
+ match e, b with
+ | Foo, true -> 1
+ | Bar, false -> 2
+ | _, _ -> 3
+
+let () =
+ let r = test Bar false in
+ if r = 2 then printf "PR#5788=Ok\n"
+
+let test e b =
+ match e, b with
+ | Bar, false -> 0
+ | (Foo|Bar), true -> 1
+ | Foo, false -> 2
+ | _, _ -> 3
+
+
+let () =
+ let r = test Foo false in
+ if r = 0 then printf "PR#5788=Ok\n"
+
+
+(* No string sharing PR#6322 *)
+let test x = match x with
+ | true -> "a"
+ | false -> "a"
+
+let () =
+ let s1 = test true in
+ let s2 = test false in
+ s1.[0] <- 'p';
+ if s1 <> s2 then printf "PR#6322=Ok\n%!"
+
+(* PR#6646 Avoid explosion of default cases when there are many constructors *)
+
+(* This took forever to compile *)
+
+type token =
+ | Abs
+ | Acload
+ | After
+ | And
+ | Annotate
+ | Apply
+ | Arc
+ | Array
+ | Arraymacro
+ | Arrayrelatedinfo
+ | Arraysite
+ | Assign
+ | Atleast
+ | Atmost
+ | Author
+ | Basearray
+ | Becomes
+ | Between
+ | Block
+ | Boolean
+ | Booleandisplay
+ | Booleanmap
+ | Booleanvalue
+ | Borderpattern
+ | Borderwidth
+ | Boundingbox
+ | Ceiling
+ | Cell
+ | Cellref
+ | Celltype
+ | Change
+ | Circle
+ | Color
+ | Comment
+ | Commentgraphics
+ | Compound
+ | Concat
+ | Connectlocation
+ | Constant
+ | Constraint
+ | Contents
+ | Cornertype
+ | Criticality
+ | Currentmap
+ | Curve
+ | Cycle
+ | Dataorigin
+ | Dcfaninload
+ | Dcfanoutload
+ | Dcmaxfanin
+ | Dcmaxfanout
+ | Delay
+ | Delta
+ | Derivation
+ | Design
+ | Designator
+ | Difference
+ | Direction
+ | Display
+ | Divide
+ | Dominates
+ | Dot
+ | Duration
+ | E
+ | Edif
+ | Ediflevel
+ | Edifversion
+ | Else
+ | Enclosuredistance
+ | Endtype
+ | Entry
+ | Equal
+ | Escape
+ | Event
+ | Exactly
+ | External
+ | Fabricate
+ | False
+ | Figure
+ | Figurearea
+ | Figuregroup
+ | Figuregroupobject
+ | Figuregroupoverride
+ | Figuregroupref
+ | Figureperimeter
+ | Figurewidth
+ | Fillpattern
+ | Fix
+ | Floor
+ | Follow
+ | Forbiddenevent
+ | Form
+ | Globalportref
+ | Greaterthan
+ | Gridmap
+ | If
+ | Ignore
+ | Includefiguregroup
+ | Increasing
+ | Initial
+ | Instance
+ | Instancebackannotate
+ | Instancegroup
+ | Instancemap
+ | Instancenamedef
+ | Instanceref
+ | Integer
+ | Integerdisplay
+ | Interface
+ | Interfiguregroupspacing
+ | Intersection
+ | Intrafiguregroupspacing
+ | Inverse
+ | Isolated
+ | Iterate
+ | Joined
+ | Justify
+ | Keyworddisplay
+ | Keywordlevel
+ | Keywordmap
+ | Lessthan
+ | Library
+ | Libraryref
+ | Listofnets
+ | Listofports
+ | Loaddelay
+ | Logicassign
+ | Logicinput
+ | Logiclist
+ | Logicmapinput
+ | Logicmapoutput
+ | Logiconeof
+ | Logicoutput
+ | Logicport
+ | Logicref
+ | Logicvalue
+ | Logicwaveform
+ | Maintain
+ | Match
+ | Max
+ | Member
+ | Min
+ | Minomax
+ | Minomaxdisplay
+ | Mnm
+ | Mod
+ | Multiplevalueset
+ | Mustjoin
+ | Name
+ | Negate
+ | Net
+ | Netbackannotate
+ | Netbundle
+ | Netdelay
+ | Netgroup
+ | Netmap
+ | Netref
+ | Nochange
+ | Nonpermutable
+ | Not
+ | Notallowed
+ | Notchspacing
+ | Number
+ | Numberdefinition
+ | Numberdisplay
+ | Offpageconnector
+ | Offsetevent
+ | Openshape
+ | Or
+ | Orientation
+ | Origin
+ | Overhangdistance
+ | Overlapdistance
+ | Oversize
+ | Owner
+ | Page
+ | Pagesize
+ | Parameter
+ | Parameterassign
+ | Parameterdisplay
+ | Path
+ | Pathdelay
+ | Pathwidth
+ | Permutable
+ | Physicaldesignrule
+ | Plug
+ | Point
+ | Pointdisplay
+ | Pointlist
+ | Pointsubtract
+ | Pointsum
+ | Polygon
+ | Port
+ | Portbackannotate
+ | Portbundle
+ | Portdelay
+ | Portgroup
+ | Portimplementation
+ | Portinstance
+ | Portlist
+ | Portlistalias
+ | Portmap
+ | Portref
+ | Product
+ | Program
+ | Property
+ | Propertydisplay
+ | Protectionframe
+ | Pt
+ | Rangevector
+ | Rectangle
+ | Rectanglesize
+ | Rename
+ | Resolves
+ | Scale
+ | Scalex
+ | Scaley
+ | Section
+ | Shape
+ | Simulate
+ | Simulationinfo
+ | Singlevalueset
+ | Site
+ | Socket
+ | Socketset
+ | Statement
+ | Status
+ | Steady
+ | Strictlyincreasing
+ | String
+ | Stringdisplay
+ | Strong
+ | Subtract
+ | Sum
+ | Symbol
+ | Symmetry
+ | Table
+ | Tabledefault
+ | Technology
+ | Textheight
+ | Then
+ | Timeinterval
+ | Timestamp
+ | Timing
+ | Transform
+ | Transition
+ | Trigger
+ | True
+ | Typedvalue
+ | Unconstrained
+ | Undefined
+ | Union
+ | Unit
+ | Unused
+ | Userdata
+ | Valuenameref
+ | Variable
+ | Version
+ | View
+ | Viewlist
+ | Viewmap
+ | Viewref
+ | Viewtype
+ | Visible
+ | Voltagemap
+ | Wavevalue
+ | Weak
+ | Weakjoined
+ | When
+ | While
+ | Written
+ | Xcoord
+ | Xor
+ | Ycoord
+ | ILLEGAL of (char)
+ | ID of (string)
+ | TLIST of (token list)
+ | TLIST2 of (token list*token list)
+ | ITEM of (token*token)
+ | ITEM2 of (token*token*token)
+ | STRING of (string)
+ | INT of (int)
+ | ENDOFFILE
+ | EOL
+ | LPAREN
+ | RPAREN
+ | EMPTY
+
+let test_match tok = match tok with
+ | ITEM2(Array, ITEM (Rename, TLIST [ID id; STRING str]), INT idx) ->
+ 1
+ | ITEM2(Cellref, TLIST [ID id], TLIST lst) ->
+ 2
+ | ITEM2(Cell, TLIST [ID cellid], TLIST lst) ->
+ 3
+ | ITEM2(Contents, TLIST lst1, TLIST lst2) ->
+ 4
+ | ITEM2(Design, TLIST [ID id], TLIST lst) ->
+ 5
+ | ITEM2(Edif, TLIST [ID id], TLIST lst) ->
+ 6
+ | ITEM2(Instance,
+ TLIST [ID instid],
+ TLIST[ITEM2(Viewref, TLIST [ID netlist],
+ TLIST[ITEM(Cellref, TLIST [ID cellid])])]) ->
+ 7
+
+
+ | ITEM2(Instance,
+ TLIST [ID instid],
+ TLIST[ITEM2(Viewref, TLIST [ID netlist],
+ TLIST[ITEM2(Cellref, TLIST [ID cellid],
+ TLIST [ITEM (Libraryref,
+ TLIST [ID libid])])])]) ->
+ 8
+(* *)
+ | ITEM2(Instance, TLIST [ID instid],
+ TLIST [ITEM2(viewref,
+ TLIST [ID netlist],
+ TLIST [ITEM2(cellref,
+ TLIST [ID cellid],
+ TLIST [ITEM(libraryref,
+ TLIST [ID libid])])]);
+ ITEM2(property, TLIST [ID xstlib],
+ TLIST [ITEM2(bool1,
+ TLIST [],
+ TLIST [ITEM(True, TLIST [])]);
+ ITEM(owner, TLIST [str])])]) -> 9
+(* *)
+ | ITEM2(Interface, TLIST [], TLIST lst) -> 100
+ | ITEM2(Joined, TLIST [], TLIST lst) -> 10
+ | ITEM2(Keywordmap, TLIST lst1, TLIST lst2) -> 11
+ | ITEM2(Library, TLIST [], TLIST lst) -> 12
+ | ITEM2(Library, TLIST [ID libid], TLIST lst) -> 13
+ | ITEM2(Net, TLIST [], TLIST [ITEM (Rename, TLIST [ID oldid; STRING newid]);
+ ITEM2(Joined, TLIST [],
+ TLIST portlst)]) -> 14
+ | ITEM2(Net, TLIST [ID netid], TLIST [ITEM2(Joined, TLIST [],
+ TLIST portlst)]) -> 15
+ | ITEM2(Net, _, _) -> 16
+ | ITEM2(Port, TLIST [], TLIST lst) -> 17
+ | ITEM2(Port, TLIST [ID id], TLIST lst) -> 18
+ | ITEM2(Portref, TLIST [ID id], TLIST [ITEM (Instanceref, TLIST [ID ref])]) ->
+ 19
+ | ITEM2(Portref, TLIST [], TLIST [ITEM (Member, TLIST [ID mref; INT idx])]) ->
+ 20
+ | ITEM2(Portref, TLIST [], TLIST[ITEM (Member, TLIST [ID mref; INT idx]);
+ ITEM (Instanceref, TLIST [ID instref])]) ->
+ 21
+ | ITEM2(Program, TLIST [STRING progid], TLIST lst) ->21
+ | ITEM2(Property, TLIST [ID part], TLIST lst) -> 22
+ | ITEM2(Status, TLIST lst1, TLIST lst2) -> 23
+ | ITEM2(Technology, TLIST lst1, TLIST lst2) -> 24
+ | ITEM2(View, TLIST [ID netlist], TLIST lst) -> 25
+ | ITEM2(Viewref, TLIST [ID "netlist"], TLIST lst) -> 26
+ | ITEM2(Written, TLIST lst1, TLIST lst2) -> 27
+ | ITEM2(External, TLIST lst1, TLIST lst2) -> 28
+ | ITEM(Integer, TLIST [INT n]) -> 29
+ | ITEM (Author, TLIST [STRING author]) -> 30
+ | ITEM (Cellref, TLIST [ID id]) -> 31
+ | ITEM (Celltype, TLIST [ID "GENERIC"]) -> 32
+ | ITEM (Direction, TLIST [ID dir]) -> 32 (* print_endline dir *)
+ | ITEM (Ediflevel, TLIST [INT 0]) -> 32
+ | ITEM (Edifversion, TLIST [INT 2; INT 0; INT 0]) -> 32
+ | ITEM (Instanceref, TLIST [ID id]) -> 32
+ | ITEM (Keywordlevel, TLIST [INT 0]) -> 32
+ | ITEM (Libraryref, TLIST [ID "work"]) -> 32
+ | ITEM (Libraryref, TLIST [ID "xilinx"]) -> 32
+ | ITEM (Member, TLIST [ID id; INT n]) -> 32
+ | ITEM (Numberdefinition, TLIST []) -> 32
+ | ITEM (Owner, TLIST [STRING "\"Xilinx\""]) -> 32
+ | ITEM (Portref, TLIST [ID id]) -> 32
+ | ITEM (Rename, TLIST [ID id; STRING str]) -> 33
+ | ITEM (String, TLIST [STRING str]) -> 32
+ | ITEM (String, TLIST lst) -> 34
+ | ITEM (Timestamp, TLIST [INT yr; INT mon; INT day; INT hour; INT min;
+ INT sec]) ->
+ 32
+ | ITEM (Version, TLIST [STRING str]) -> 32
+ | ITEM (Viewtype, TLIST [ID "NETLIST"]) -> 32
+ | ITEM (Designator, TLIST lst) -> 34
+ | Abs -> failwith " Abs "
+ | Acload -> failwith " Acload "
+ | After -> failwith " After "
+ | And -> failwith " And "
+ | Annotate -> failwith " Annotate "
+ | Apply -> failwith " Apply "
+ | Arc -> failwith " Arc "
+ | Array -> failwith " Array "
+ | Arraymacro -> failwith " Arraymacro "
+ | Arrayrelatedinfo -> failwith " Arrayrelatedinfo "
+ | Arraysite -> failwith " Arraysite "
+ | Assign -> failwith " Assign "
+ | Atleast -> failwith " Atleast "
+ | Atmost -> failwith " Atmost "
+ | Author -> failwith " Author "
+ | Basearray -> failwith " Basearray "
+ | Becomes -> failwith " Becomes "
+ | Between -> failwith " Between "
+ | Block -> failwith " Block "
+ | Boolean -> failwith " Boolean "
+ | Booleandisplay -> failwith " Booleandisplay "
+ | Booleanmap -> failwith " Booleanmap "
+ | Booleanvalue -> failwith " Booleanvalue "
+ | Borderpattern -> failwith " Borderpattern "
+ | Borderwidth -> failwith " Borderwidth "
+ | Boundingbox -> failwith " Boundingbox "
+ | Ceiling -> failwith " Ceiling "
+ | Cell -> failwith " Cell "
+ | Cellref -> failwith " Cellref "
+ | Celltype -> failwith " Celltype "
+ | Change -> failwith " Change "
+ | Circle -> failwith " Circle "
+ | Color -> failwith " Color "
+ | Comment -> failwith " Comment "
+ | Commentgraphics -> failwith " Commentgraphics "
+ | Compound -> failwith " Compound "
+ | Concat -> failwith " Concat "
+ | Connectlocation -> failwith " Connectlocation "
+ | Constant -> failwith " Constant "
+ | Constraint -> failwith " Constraint "
+ | Contents -> failwith " Contents "
+ | Cornertype -> failwith " Cornertype "
+ | Criticality -> failwith " Criticality "
+ | Currentmap -> failwith " Currentmap "
+ | Curve -> failwith " Curve "
+ | Cycle -> failwith " Cycle "
+ | Dataorigin -> failwith " Dataorigin "
+ | Dcfaninload -> failwith " Dcfaninload "
+ | Dcfanoutload -> failwith " Dcfanoutload "
+ | Dcmaxfanin -> failwith " Dcmaxfanin "
+ | Dcmaxfanout -> failwith " Dcmaxfanout "
+ | Delay -> failwith " Delay "
+ | Delta -> failwith " Delta "
+ | Derivation -> failwith " Derivation "
+ | Design -> failwith " Design "
+ | Designator -> failwith " Designator "
+ | Difference -> failwith " Difference "
+ | Direction -> failwith " Direction "
+ | Display -> failwith " Display "
+ | Divide -> failwith " Divide "
+ | Dominates -> failwith " Dominates "
+ | Dot -> failwith " Dot "
+ | Duration -> failwith " Duration "
+ | E -> failwith " E "
+ | Edif -> failwith " Edif "
+ | Ediflevel -> failwith " Ediflevel "
+ | Edifversion -> failwith " Edifversion "
+ | Else -> failwith " Else "
+ | Enclosuredistance -> failwith " Enclosuredistance "
+ | Endtype -> failwith " Endtype "
+ | Entry -> failwith " Entry "
+ | Equal -> failwith " Equal "
+ | Escape -> failwith " Escape "
+ | Event -> failwith " Event "
+ | Exactly -> failwith " Exactly "
+ | External -> failwith " External "
+ | Fabricate -> failwith " Fabricate "
+ | False -> failwith " False "
+ | Figure -> failwith " Figure "
+ | Figurearea -> failwith " Figurearea "
+ | Figuregroup -> failwith " Figuregroup "
+ | Figuregroupobject -> failwith " Figuregroupobject "
+ | Figuregroupoverride -> failwith " Figuregroupoverride "
+ | Figuregroupref -> failwith " Figuregroupref "
+ | Figureperimeter -> failwith " Figureperimeter "
+ | Figurewidth -> failwith " Figurewidth "
+ | Fillpattern -> failwith " Fillpattern "
+ | Fix -> failwith " Fix "
+ | Floor -> failwith " Floor "
+ | Follow -> failwith " Follow "
+ | Forbiddenevent -> failwith " Forbiddenevent "
+ | Form -> failwith " Form "
+ | Globalportref -> failwith " Globalportref "
+ | Greaterthan -> failwith " Greaterthan "
+ | Gridmap -> failwith " Gridmap "
+ | If -> failwith " If "
+ | Ignore -> failwith " Ignore "
+ | Includefiguregroup -> failwith " Includefiguregroup "
+ | Increasing -> failwith " Increasing "
+ | Initial -> failwith " Initial "
+ | Instance -> failwith " Instance "
+ | Instancebackannotate -> failwith " Instancebackannotate "
+ | Instancegroup -> failwith " Instancegroup "
+ | Instancemap -> failwith " Instancemap "
+ | Instancenamedef -> failwith " Instancenamedef "
+ | Instanceref -> failwith " Instanceref "
+ | Integer -> failwith " Integer "
+ | Integerdisplay -> failwith " Integerdisplay "
+ | Interface -> failwith " Interface "
+ | Interfiguregroupspacing -> failwith " Interfiguregroupspacing "
+ | Intersection -> failwith " Intersection "
+ | Intrafiguregroupspacing -> failwith " Intrafiguregroupspacing "
+ | Inverse -> failwith " Inverse "
+ | Isolated -> failwith " Isolated "
+ | Iterate -> failwith " Iterate "
+ | Joined -> failwith " Joined "
+ | Justify -> failwith " Justify "
+ | Keyworddisplay -> failwith " Keyworddisplay "
+ | Keywordlevel -> failwith " Keywordlevel "
+ | Keywordmap -> failwith " Keywordmap "
+ | Lessthan -> failwith " Lessthan "
+ | Library -> failwith " Library "
+ | Libraryref -> failwith " Libraryref "
+ | Listofnets -> failwith " Listofnets "
+ | Listofports -> failwith " Listofports "
+ | Loaddelay -> failwith " Loaddelay "
+ | Logicassign -> failwith " Logicassign "
+ | Logicinput -> failwith " Logicinput "
+ | Logiclist -> failwith " Logiclist "
+ | Logicmapinput -> failwith " Logicmapinput "
+ | Logicmapoutput -> failwith " Logicmapoutput "
+ | Logiconeof -> failwith " Logiconeof "
+ | Logicoutput -> failwith " Logicoutput "
+ | Logicport -> failwith " Logicport "
+ | Logicref -> failwith " Logicref "
+ | Logicvalue -> failwith " Logicvalue "
+ | Logicwaveform -> failwith " Logicwaveform "
+ | Maintain -> failwith " Maintain "
+ | Match -> failwith " Match "
+ | Max -> failwith " Max "
+ | Member -> failwith " Member "
+ | Min -> failwith " Min "
+ | Minomax -> failwith " Minomax "
+ | Minomaxdisplay -> failwith " Minomaxdisplay "
+ | Mnm -> failwith " Mnm "
+ | Mod -> failwith " Mod "
+ | Multiplevalueset -> failwith " Multiplevalueset "
+ | Mustjoin -> failwith " Mustjoin "
+ | Name -> failwith " Name "
+ | Negate -> failwith " Negate "
+ | Net -> failwith " Net "
+ | Netbackannotate -> failwith " Netbackannotate "
+ | Netbundle -> failwith " Netbundle "
+ | Netdelay -> failwith " Netdelay "
+ | Netgroup -> failwith " Netgroup "
+ | Netmap -> failwith " Netmap "
+ | Netref -> failwith " Netref "
+ | Nochange -> failwith " Nochange "
+ | Nonpermutable -> failwith " Nonpermutable "
+ | Not -> failwith " Not "
+ | Notallowed -> failwith " Notallowed "
+ | Notchspacing -> failwith " Notchspacing "
+ | Number -> failwith " Number "
+ | Numberdefinition -> failwith " Numberdefinition "
+ | Numberdisplay -> failwith " Numberdisplay "
+ | Offpageconnector -> failwith " Offpageconnector "
+ | Offsetevent -> failwith " Offsetevent "
+ | Openshape -> failwith " Openshape "
+ | Or -> failwith " Or "
+ | Orientation -> failwith " Orientation "
+ | Origin -> failwith " Origin "
+ | Overhangdistance -> failwith " Overhangdistance "
+ | Overlapdistance -> failwith " Overlapdistance "
+ | Oversize -> failwith " Oversize "
+ | Owner -> failwith " Owner "
+ | Page -> failwith " Page "
+ | Pagesize -> failwith " Pagesize "
+ | Parameter -> failwith " Parameter "
+ | Parameterassign -> failwith " Parameterassign "
+ | Parameterdisplay -> failwith " Parameterdisplay "
+ | Path -> failwith " Path "
+ | Pathdelay -> failwith " Pathdelay "
+ | Pathwidth -> failwith " Pathwidth "
+ | Permutable -> failwith " Permutable "
+ | Physicaldesignrule -> failwith " Physicaldesignrule "
+ | Plug -> failwith " Plug "
+ | Point -> failwith " Point "
+ | Pointdisplay -> failwith " Pointdisplay "
+ | Pointlist -> failwith " Pointlist "
+ | Pointsubtract -> failwith " Pointsubtract "
+ | Pointsum -> failwith " Pointsum "
+ | Polygon -> failwith " Polygon "
+ | Port -> failwith " Port "
+ | Portbackannotate -> failwith " Portbackannotate "
+ | Portbundle -> failwith " Portbundle "
+ | Portdelay -> failwith " Portdelay "
+ | Portgroup -> failwith " Portgroup "
+ | Portimplementation -> failwith " Portimplementation "
+ | Portinstance -> failwith " Portinstance "
+ | Portlist -> failwith " Portlist "
+ | Portlistalias -> failwith " Portlistalias "
+ | Portmap -> failwith " Portmap "
+ | Portref -> failwith " Portref "
+ | Product -> failwith " Product "
+ | Program -> failwith " Program "
+ | Property -> failwith " Property "
+ | Propertydisplay -> failwith " Propertydisplay "
+ | Protectionframe -> failwith " Protectionframe "
+ | Pt -> failwith " Pt "
+ | Rangevector -> failwith " Rangevector "
+ | Rectangle -> failwith " Rectangle "
+ | Rectanglesize -> failwith " Rectanglesize "
+ | Rename -> failwith " Rename "
+ | Resolves -> failwith " Resolves "
+ | Scale -> failwith " Scale "
+ | Scalex -> failwith " Scalex "
+ | Scaley -> failwith " Scaley "
+ | Section -> failwith " Section "
+ | Shape -> failwith " Shape "
+ | Simulate -> failwith " Simulate "
+ | Simulationinfo -> failwith " Simulationinfo "
+ | Singlevalueset -> failwith " Singlevalueset "
+ | Site -> failwith " Site "
+ | Socket -> failwith " Socket "
+ | Socketset -> failwith " Socketset "
+ | Statement -> failwith " Statement "
+ | Status -> failwith " Status "
+ | Steady -> failwith " Steady "
+ | Strictlyincreasing -> failwith " Strictlyincreasing "
+ | String -> failwith " String "
+ | Stringdisplay -> failwith " Stringdisplay "
+ | Strong -> failwith " Strong "
+ | Subtract -> failwith " Subtract "
+ | Sum -> failwith " Sum "
+ | Symbol -> failwith " Symbol "
+ | Symmetry -> failwith " Symmetry "
+ | Table -> failwith " Table "
+ | Tabledefault -> failwith " Tabledefault "
+ | Technology -> failwith " Technology "
+ | Textheight -> failwith " Textheight "
+ | Then -> failwith " Then "
+ | Timeinterval -> failwith " Timeinterval "
+ | Timestamp -> failwith " Timestamp "
+ | Timing -> failwith " Timing "
+ | Transform -> failwith " Transform "
+ | Transition -> failwith " Transition "
+ | Trigger -> failwith " Trigger "
+ | True -> failwith " True "
+ | Typedvalue -> failwith " Typedvalue "
+ | Unconstrained -> failwith " Unconstrained "
+ | Undefined -> failwith " Undefined "
+ | Union -> failwith " Union "
+ | Unit -> failwith " Unit "
+ | Unused -> failwith " Unused "
+ | Userdata -> failwith " Userdata "
+ | Valuenameref -> failwith " Valuenameref "
+ | Variable -> failwith " Variable "
+ | Version -> failwith " Version "
+ | View -> failwith " View "
+ | Viewlist -> failwith " Viewlist "
+ | Viewmap -> failwith " Viewmap "
+ | Viewref -> failwith " Viewref "
+ | Viewtype -> failwith " Viewtype "
+ | Visible -> failwith " Visible "
+ | Voltagemap -> failwith " Voltagemap "
+ | Wavevalue -> failwith " Wavevalue "
+ | Weak -> failwith " Weak "
+ | Weakjoined -> failwith " Weakjoined "
+ | When -> failwith " When "
+ | While -> failwith " While "
+ | Written -> failwith " Written "
+ | Xcoord -> failwith " Xcoord "
+ | Xor -> failwith " Xor "
+ | Ycoord -> failwith " Ycoord "
+ | ILLEGAL _ -> failwith " ILLEGAL _ "
+ | ID _ -> failwith " ID _ "
+ | TLIST _ -> failwith " TLIST _ "
+ | TLIST2 _ -> failwith " TLIST2 _ "
+ | STRING _ -> failwith " STRING _ "
+ | INT _ -> failwith " INT _ "
+ | ENDOFFILE -> failwith " ENDOFFILE "
+ | EOL -> failwith " EOL "
+ | LPAREN -> failwith " LPAREN "
+ | RPAREN -> failwith " RPAREN "
+ | EMPTY -> failwith " EMPTY "
+
+ | ITEM2(Abs, _, _) -> failwith " ITEM2(Abs, _, _) "
+ | ITEM2(Acload, _, _) -> failwith " ITEM2(Acload, _, _) "
+ | ITEM2(After, _, _) -> failwith " ITEM2(After, _, _) "
+ | ITEM2(And, _, _) -> failwith " ITEM2(And, _, _) "
+ | ITEM2(Annotate, _, _) -> failwith " ITEM2(Annotate, _, _) "
+ | ITEM2(Apply, _, _) -> failwith " ITEM2(Apply, _, _) "
+ | ITEM2(Arc, _, _) -> failwith " ITEM2(Arc, _, _) "
+ | ITEM2(Array, _, _) -> failwith " ITEM2(Array, _, _) "
+ | ITEM2(Arraymacro, _, _) -> failwith " ITEM2(Arraymacro, _, _) "
+ | ITEM2(Arrayrelatedinfo, _, _) -> failwith " ITEM2(Arrayrelatedinfo, _, _) "
+ | ITEM2(Arraysite, _, _) -> failwith " ITEM2(Arraysite, _, _) "
+ | ITEM2(Assign, _, _) -> failwith " ITEM2(Assign, _, _) "
+ | ITEM2(Atleast, _, _) -> failwith " ITEM2(Atleast, _, _) "
+ | ITEM2(Atmost, _, _) -> failwith " ITEM2(Atmost, _, _) "
+ | ITEM2(Author, _, _) -> failwith " ITEM2(Author, _, _) "
+ | ITEM2(Basearray, _, _) -> failwith " ITEM2(Basearray, _, _) "
+ | ITEM2(Becomes, _, _) -> failwith " ITEM2(Becomes, _, _) "
+ | ITEM2(Between, _, _) -> failwith " ITEM2(Between, _, _) "
+ | ITEM2(Block, _, _) -> failwith " ITEM2(Block, _, _) "
+ | ITEM2(Boolean, _, _) -> failwith " ITEM2(Boolean, _, _) "
+ | ITEM2(Booleandisplay, _, _) -> failwith " ITEM2(Booleandisplay, _, _) "
+ | ITEM2(Booleanmap, _, _) -> failwith " ITEM2(Booleanmap, _, _) "
+ | ITEM2(Booleanvalue, _, _) -> failwith " ITEM2(Booleanvalue, _, _) "
+ | ITEM2(Borderpattern, _, _) -> failwith " ITEM2(Borderpattern, _, _) "
+ | ITEM2(Borderwidth, _, _) -> failwith " ITEM2(Borderwidth, _, _) "
+ | ITEM2(Boundingbox, _, _) -> failwith " ITEM2(Boundingbox, _, _) "
+ | ITEM2(Ceiling, _, _) -> failwith " ITEM2(Ceiling, _, _) "
+ | ITEM2(Cell, _, _) -> failwith " ITEM2(Cell, _, _) "
+ | ITEM2(Cellref, _, _) -> failwith " ITEM2(Cellref, _, _) "
+ | ITEM2(Celltype, _, _) -> failwith " ITEM2(Celltype, _, _) "
+ | ITEM2(Change, _, _) -> failwith " ITEM2(Change, _, _) "
+ | ITEM2(Circle, _, _) -> failwith " ITEM2(Circle, _, _) "
+ | ITEM2(Color, _, _) -> failwith " ITEM2(Color, _, _) "
+ | ITEM2(Comment, _, _) -> failwith " ITEM2(Comment, _, _) "
+ | ITEM2(Commentgraphics, _, _) -> failwith " ITEM2(Commentgraphics, _, _) "
+ | ITEM2(Compound, _, _) -> failwith " ITEM2(Compound, _, _) "
+ | ITEM2(Concat, _, _) -> failwith " ITEM2(Concat, _, _) "
+ | ITEM2(Connectlocation, _, _) -> failwith " ITEM2(Connectlocation, _, _) "
+ | ITEM2(Constant, _, _) -> failwith " ITEM2(Constant, _, _) "
+ | ITEM2(Constraint, _, _) -> failwith " ITEM2(Constraint, _, _) "
+ | ITEM2(Contents, _, _) -> failwith " ITEM2(Contents, _, _) "
+ | ITEM2(Cornertype, _, _) -> failwith " ITEM2(Cornertype, _, _) "
+ | ITEM2(Criticality, _, _) -> failwith " ITEM2(Criticality, _, _) "
+ | ITEM2(Currentmap, _, _) -> failwith " ITEM2(Currentmap, _, _) "
+ | ITEM2(Curve, _, _) -> failwith " ITEM2(Curve, _, _) "
+ | ITEM2(Cycle, _, _) -> failwith " ITEM2(Cycle, _, _) "
+ | ITEM2(Dataorigin, _, _) -> failwith " ITEM2(Dataorigin, _, _) "
+ | ITEM2(Dcfaninload, _, _) -> failwith " ITEM2(Dcfaninload, _, _) "
+ | ITEM2(Dcfanoutload, _, _) -> failwith " ITEM2(Dcfanoutload, _, _) "
+ | ITEM2(Dcmaxfanin, _, _) -> failwith " ITEM2(Dcmaxfanin, _, _) "
+ | ITEM2(Dcmaxfanout, _, _) -> failwith " ITEM2(Dcmaxfanout, _, _) "
+ | ITEM2(Delay, _, _) -> failwith " ITEM2(Delay, _, _) "
+ | ITEM2(Delta, _, _) -> failwith " ITEM2(Delta, _, _) "
+ | ITEM2(Derivation, _, _) -> failwith " ITEM2(Derivation, _, _) "
+ | ITEM2(Design, _, _) -> failwith " ITEM2(Design, _, _) "
+ | ITEM2(Designator, _, _) -> failwith " ITEM2(Designator, _, _) "
+ | ITEM2(Difference, _, _) -> failwith " ITEM2(Difference, _, _) "
+ | ITEM2(Direction, _, _) -> failwith " ITEM2(Direction, _, _) "
+ | ITEM2(Display, _, _) -> failwith " ITEM2(Display, _, _) "
+ | ITEM2(Divide, _, _) -> failwith " ITEM2(Divide, _, _) "
+ | ITEM2(Dominates, _, _) -> failwith " ITEM2(Dominates, _, _) "
+ | ITEM2(Dot, _, _) -> failwith " ITEM2(Dot, _, _) "
+ | ITEM2(Duration, _, _) -> failwith " ITEM2(Duration, _, _) "
+ | ITEM2(E, _, _) -> failwith " ITEM2(E, _, _) "
+ | ITEM2(Edif, _, _) -> failwith " ITEM2(Edif, _, _) "
+ | ITEM2(Ediflevel, _, _) -> failwith " ITEM2(Ediflevel, _, _) "
+ | ITEM2(Edifversion, _, _) -> failwith " ITEM2(Edifversion, _, _) "
+ | ITEM2(Else, _, _) -> failwith " ITEM2(Else, _, _) "
+ | ITEM2(Enclosuredistance, _, _) ->
+ failwith " ITEM2(Enclosuredistance, _, _) "
+ | ITEM2(Endtype, _, _) -> failwith " ITEM2(Endtype, _, _) "
+ | ITEM2(Entry, _, _) -> failwith " ITEM2(Entry, _, _) "
+ | ITEM2(Equal, _, _) -> failwith " ITEM2(Equal, _, _) "
+ | ITEM2(Escape, _, _) -> failwith " ITEM2(Escape, _, _) "
+ | ITEM2(Event, _, _) -> failwith " ITEM2(Event, _, _) "
+ | ITEM2(Exactly, _, _) -> failwith " ITEM2(Exactly, _, _) "
+ | ITEM2(External, _, _) -> failwith " ITEM2(External, _, _) "
+ | ITEM2(Fabricate, _, _) -> failwith " ITEM2(Fabricate, _, _) "
+ | ITEM2(False, _, _) -> failwith " ITEM2(False, _, _) "
+ | ITEM2(Figure, _, _) -> failwith " ITEM2(Figure, _, _) "
+ | ITEM2(Figurearea, _, _) -> failwith " ITEM2(Figurearea, _, _) "
+ | ITEM2(Figuregroup, _, _) -> failwith " ITEM2(Figuregroup, _, _) "
+ | ITEM2(Figuregroupobject, _, _) ->
+ failwith " ITEM2(Figuregroupobject, _, _) "
+ | ITEM2(Figuregroupoverride, _, _) ->
+ failwith " ITEM2(Figuregroupoverride, _, _) "
+ | ITEM2(Figuregroupref, _, _) -> failwith " ITEM2(Figuregroupref, _, _) "
+ | ITEM2(Figureperimeter, _, _) -> failwith " ITEM2(Figureperimeter, _, _) "
+ | ITEM2(Figurewidth, _, _) -> failwith " ITEM2(Figurewidth, _, _) "
+ | ITEM2(Fillpattern, _, _) -> failwith " ITEM2(Fillpattern, _, _) "
+ | ITEM2(Fix, _, _) -> failwith " ITEM2(Fix, _, _) "
+ | ITEM2(Floor, _, _) -> failwith " ITEM2(Floor, _, _) "
+ | ITEM2(Follow, _, _) -> failwith " ITEM2(Follow, _, _) "
+ | ITEM2(Forbiddenevent, _, _) -> failwith " ITEM2(Forbiddenevent, _, _) "
+ | ITEM2(Form, _, _) -> failwith " ITEM2(Form, _, _) "
+ | ITEM2(Globalportref, _, _) -> failwith " ITEM2(Globalportref, _, _) "
+ | ITEM2(Greaterthan, _, _) -> failwith " ITEM2(Greaterthan, _, _) "
+ | ITEM2(Gridmap, _, _) -> failwith " ITEM2(Gridmap, _, _) "
+ | ITEM2(If, _, _) -> failwith " ITEM2(If, _, _) "
+ | ITEM2(Ignore, _, _) -> failwith " ITEM2(Ignore, _, _) "
+ | ITEM2(Includefiguregroup, _, _) ->
+ failwith " ITEM2(Includefiguregroup, _, _) "
+ | ITEM2(Increasing, _, _) -> failwith " ITEM2(Increasing, _, _) "
+ | ITEM2(Initial, _, _) -> failwith " ITEM2(Initial, _, _) "
+ | ITEM2(Instance, arg1, arg2) -> failwith (" ITEM2(Instance, ) ")
+ | ITEM2(Instancebackannotate, _, _) ->
+ failwith " ITEM2(Instancebackannotate, _, _) "
+ | ITEM2(Instancegroup, _, _) -> failwith " ITEM2(Instancegroup, _, _) "
+ | ITEM2(Instancemap, _, _) -> failwith " ITEM2(Instancemap, _, _) "
+ | ITEM2(Instancenamedef, _, _) -> failwith " ITEM2(Instancenamedef, _, _) "
+ | ITEM2(Instanceref, _, _) -> failwith " ITEM2(Instanceref, _, _) "
+ | ITEM2(Integer, _, _) -> failwith " ITEM2(Integer, _, _) "
+ | ITEM2(Integerdisplay, _, _) -> failwith " ITEM2(Integerdisplay, _, _) "
+ | ITEM2(Interface, _, _) -> failwith " ITEM2(Interface, _, _) "
+ | ITEM2(Interfiguregroupspacing, _, _) ->
+ failwith " ITEM2(Interfiguregroupspacing, _, _) "
+ | ITEM2(Intersection, _, _) -> failwith " ITEM2(Intersection, _, _) "
+ | ITEM2(Intrafiguregroupspacing, _, _) ->
+ failwith " ITEM2(Intrafiguregroupspacing, _, _) "
+ | ITEM2(Inverse, _, _) -> failwith " ITEM2(Inverse, _, _) "
+ | ITEM2(Isolated, _, _) -> failwith " ITEM2(Isolated, _, _) "
+ | ITEM2(Iterate, _, _) -> failwith " ITEM2(Iterate, _, _) "
+ | ITEM2(Joined, _, _) -> failwith " ITEM2(Joined, _, _) "
+ | ITEM2(Justify, _, _) -> failwith " ITEM2(Justify, _, _) "
+ | ITEM2(Keyworddisplay, _, _) -> failwith " ITEM2(Keyworddisplay, _, _) "
+ | ITEM2(Keywordlevel, _, _) -> failwith " ITEM2(Keywordlevel, _, _) "
+ | ITEM2(Keywordmap, _, _) -> failwith " ITEM2(Keywordmap, _, _) "
+ | ITEM2(Lessthan, _, _) -> failwith " ITEM2(Lessthan, _, _) "
+ | ITEM2(Library, _, _) -> failwith " ITEM2(Library, _, _) "
+ | ITEM2(Libraryref, _, _) -> failwith " ITEM2(Libraryref, _, _) "
+ | ITEM2(Listofnets, _, _) -> failwith " ITEM2(Listofnets, _, _) "
+ | ITEM2(Listofports, _, _) -> failwith " ITEM2(Listofports, _, _) "
+ | ITEM2(Loaddelay, _, _) -> failwith " ITEM2(Loaddelay, _, _) "
+ | ITEM2(Logicassign, _, _) -> failwith " ITEM2(Logicassign, _, _) "
+ | ITEM2(Logicinput, _, _) -> failwith " ITEM2(Logicinput, _, _) "
+ | ITEM2(Logiclist, _, _) -> failwith " ITEM2(Logiclist, _, _) "
+ | ITEM2(Logicmapinput, _, _) -> failwith " ITEM2(Logicmapinput, _, _) "
+ | ITEM2(Logicmapoutput, _, _) -> failwith " ITEM2(Logicmapoutput, _, _) "
+ | ITEM2(Logiconeof, _, _) -> failwith " ITEM2(Logiconeof, _, _) "
+ | ITEM2(Logicoutput, _, _) -> failwith " ITEM2(Logicoutput, _, _) "
+ | ITEM2(Logicport, _, _) -> failwith " ITEM2(Logicport, _, _) "
+ | ITEM2(Logicref, _, _) -> failwith " ITEM2(Logicref, _, _) "
+ | ITEM2(Logicvalue, _, _) -> failwith " ITEM2(Logicvalue, _, _) "
+ | ITEM2(Logicwaveform, _, _) -> failwith " ITEM2(Logicwaveform, _, _) "
+ | ITEM2(Maintain, _, _) -> failwith " ITEM2(Maintain, _, _) "
+ | ITEM2(Match, _, _) -> failwith " ITEM2(Match, _, _) "
+ | ITEM2(Max, _, _) -> failwith " ITEM2(Max, _, _) "
+ | ITEM2(Member, _, _) -> failwith " ITEM2(Member, _, _) "
+ | ITEM2(Min, _, _) -> failwith " ITEM2(Min, _, _) "
+ | ITEM2(Minomax, _, _) -> failwith " ITEM2(Minomax, _, _) "
+ | ITEM2(Minomaxdisplay, _, _) -> failwith " ITEM2(Minomaxdisplay, _, _) "
+ | ITEM2(Mnm, _, _) -> failwith " ITEM2(Mnm, _, _) "
+ | ITEM2(Mod, _, _) -> failwith " ITEM2(Mod, _, _) "
+ | ITEM2(Multiplevalueset, _, _) -> failwith " ITEM2(Multiplevalueset, _, _) "
+ | ITEM2(Mustjoin, _, _) -> failwith " ITEM2(Mustjoin, _, _) "
+ | ITEM2(Name, _, _) -> failwith " ITEM2(Name, _, _) "
+ | ITEM2(Negate, _, _) -> failwith " ITEM2(Negate, _, _) "
+(*
+ | ITEM2(Net, _, _) -> failwith " ITEM2(Net, _, _) "
+*)
+ | ITEM2(Netbackannotate, _, _) -> failwith " ITEM2(Netbackannotate, _, _) "
+ | ITEM2(Netbundle, _, _) -> failwith " ITEM2(Netbundle, _, _) "
+ | ITEM2(Netdelay, _, _) -> failwith " ITEM2(Netdelay, _, _) "
+ | ITEM2(Netgroup, _, _) -> failwith " ITEM2(Netgroup, _, _) "
+ | ITEM2(Netmap, _, _) -> failwith " ITEM2(Netmap, _, _) "
+ | ITEM2(Netref, _, _) -> failwith " ITEM2(Netref, _, _) "
+ | ITEM2(Nochange, _, _) -> failwith " ITEM2(Nochange, _, _) "
+ | ITEM2(Nonpermutable, _, _) -> failwith " ITEM2(Nonpermutable, _, _) "
+ | ITEM2(Not, _, _) -> failwith " ITEM2(Not, _, _) "
+ | ITEM2(Notallowed, _, _) -> failwith " ITEM2(Notallowed, _, _) "
+ | ITEM2(Notchspacing, _, _) -> failwith " ITEM2(Notchspacing, _, _) "
+ | ITEM2(Number, _, _) -> failwith " ITEM2(Number, _, _) "
+ | ITEM2(Numberdefinition, _, _) -> failwith " ITEM2(Numberdefinition, _, _) "
+ | ITEM2(Numberdisplay, _, _) -> failwith " ITEM2(Numberdisplay, _, _) "
+ | ITEM2(Offpageconnector, _, _) -> failwith " ITEM2(Offpageconnector, _, _) "
+ | ITEM2(Offsetevent, _, _) -> failwith " ITEM2(Offsetevent, _, _) "
+ | ITEM2(Openshape, _, _) -> failwith " ITEM2(Openshape, _, _) "
+ | ITEM2(Or, _, _) -> failwith " ITEM2(Or, _, _) "
+ | ITEM2(Orientation, _, _) -> failwith " ITEM2(Orientation, _, _) "
+ | ITEM2(Origin, _, _) -> failwith " ITEM2(Origin, _, _) "
+ | ITEM2(Overhangdistance, _, _) -> failwith " ITEM2(Overhangdistance, _, _) "
+ | ITEM2(Overlapdistance, _, _) -> failwith " ITEM2(Overlapdistance, _, _) "
+ | ITEM2(Oversize, _, _) -> failwith " ITEM2(Oversize, _, _) "
+ | ITEM2(Owner, _, _) -> failwith " ITEM2(Owner, _, _) "
+ | ITEM2(Page, _, _) -> failwith " ITEM2(Page, _, _) "
+ | ITEM2(Pagesize, _, _) -> failwith " ITEM2(Pagesize, _, _) "
+ | ITEM2(Parameter, _, _) -> failwith " ITEM2(Parameter, _, _) "
+ | ITEM2(Parameterassign, _, _) -> failwith " ITEM2(Parameterassign, _, _) "
+ | ITEM2(Parameterdisplay, _, _) -> failwith " ITEM2(Parameterdisplay, _, _) "
+ | ITEM2(Path, _, _) -> failwith " ITEM2(Path, _, _) "
+ | ITEM2(Pathdelay, _, _) -> failwith " ITEM2(Pathdelay, _, _) "
+ | ITEM2(Pathwidth, _, _) -> failwith " ITEM2(Pathwidth, _, _) "
+ | ITEM2(Permutable, _, _) -> failwith " ITEM2(Permutable, _, _) "
+ | ITEM2(Physicaldesignrule, _, _) ->
+ failwith " ITEM2(Physicaldesignrule, _, _) "
+ | ITEM2(Plug, _, _) -> failwith " ITEM2(Plug, _, _) "
+ | ITEM2(Point, _, _) -> failwith " ITEM2(Point, _, _) "
+ | ITEM2(Pointdisplay, _, _) -> failwith " ITEM2(Pointdisplay, _, _) "
+ | ITEM2(Pointlist, _, _) -> failwith " ITEM2(Pointlist, _, _) "
+ | ITEM2(Pointsubtract, _, _) -> failwith " ITEM2(Pointsubtract, _, _) "
+ | ITEM2(Pointsum, _, _) -> failwith " ITEM2(Pointsum, _, _) "
+ | ITEM2(Polygon, _, _) -> failwith " ITEM2(Polygon, _, _) "
+ | ITEM2(Port, _, _) -> failwith " ITEM2(Port, _, _) "
+ | ITEM2(Portbackannotate, _, _) -> failwith " ITEM2(Portbackannotate, _, _) "
+ | ITEM2(Portbundle, _, _) -> failwith " ITEM2(Portbundle, _, _) "
+ | ITEM2(Portdelay, _, _) -> failwith " ITEM2(Portdelay, _, _) "
+ | ITEM2(Portgroup, _, _) -> failwith " ITEM2(Portgroup, _, _) "
+ | ITEM2(Portimplementation, _, _) ->
+ failwith " ITEM2(Portimplementation, _, _) "
+ | ITEM2(Portinstance, _, _) -> failwith " ITEM2(Portinstance, _, _) "
+ | ITEM2(Portlist, _, _) -> failwith " ITEM2(Portlist, _, _) "
+ | ITEM2(Portlistalias, _, _) -> failwith " ITEM2(Portlistalias, _, _) "
+ | ITEM2(Portmap, _, _) -> failwith " ITEM2(Portmap, _, _) "
+ | ITEM2(Portref, _, _) -> failwith " ITEM2(Portref, _, _) "
+ | ITEM2(Product, _, _) -> failwith " ITEM2(Product, _, _) "
+ | ITEM2(Program, _, _) -> failwith " ITEM2(Program, _, _) "
+ | ITEM2(Property, _, _) -> failwith " ITEM2(Property, _, _) "
+ | ITEM2(Propertydisplay, _, _) -> failwith " ITEM2(Propertydisplay, _, _) "
+ | ITEM2(Protectionframe, _, _) -> failwith " ITEM2(Protectionframe, _, _) "
+ | ITEM2(Pt, _, _) -> failwith " ITEM2(Pt, _, _) "
+ | ITEM2(Rangevector, _, _) -> failwith " ITEM2(Rangevector, _, _) "
+ | ITEM2(Rectangle, _, _) -> failwith " ITEM2(Rectangle, _, _) "
+ | ITEM2(Rectanglesize, _, _) -> failwith " ITEM2(Rectanglesize, _, _) "
+ | ITEM2(Rename, _, _) -> failwith " ITEM2(Rename, _, _) "
+ | ITEM2(Resolves, _, _) -> failwith " ITEM2(Resolves, _, _) "
+ | ITEM2(Scale, _, _) -> failwith " ITEM2(Scale, _, _) "
+ | ITEM2(Scalex, _, _) -> failwith " ITEM2(Scalex, _, _) "
+ | ITEM2(Scaley, _, _) -> failwith " ITEM2(Scaley, _, _) "
+ | ITEM2(Section, _, _) -> failwith " ITEM2(Section, _, _) "
+ | ITEM2(Shape, _, _) -> failwith " ITEM2(Shape, _, _) "
+ | ITEM2(Simulate, _, _) -> failwith " ITEM2(Simulate, _, _) "
+ | ITEM2(Simulationinfo, _, _) -> failwith " ITEM2(Simulationinfo, _, _) "
+ | ITEM2(Singlevalueset, _, _) -> failwith " ITEM2(Singlevalueset, _, _) "
+ | ITEM2(Site, _, _) -> failwith " ITEM2(Site, _, _) "
+ | ITEM2(Socket, _, _) -> failwith " ITEM2(Socket, _, _) "
+ | ITEM2(Socketset, _, _) -> failwith " ITEM2(Socketset, _, _) "
+ | ITEM2(Statement, _, _) -> failwith " ITEM2(Statement, _, _) "
+ | ITEM2(Status, _, _) -> failwith " ITEM2(Status, _, _) "
+ | ITEM2(Steady, _, _) -> failwith " ITEM2(Steady, _, _) "
+ | ITEM2(Strictlyincreasing, _, _) ->
+ failwith " ITEM2(Strictlyincreasing, _, _) "
+ | ITEM2(String, _, _) -> failwith " ITEM2(String, _, _) "
+ | ITEM2(Stringdisplay, _, _) -> failwith " ITEM2(Stringdisplay, _, _) "
+ | ITEM2(Strong, _, _) -> failwith " ITEM2(Strong, _, _) "
+ | ITEM2(Subtract, _, _) -> failwith " ITEM2(Subtract, _, _) "
+ | ITEM2(Sum, _, _) -> failwith " ITEM2(Sum, _, _) "
+ | ITEM2(Symbol, _, _) -> failwith " ITEM2(Symbol, _, _) "
+ | ITEM2(Symmetry, _, _) -> failwith " ITEM2(Symmetry, _, _) "
+ | ITEM2(Table, _, _) -> failwith " ITEM2(Table, _, _) "
+ | ITEM2(Tabledefault, _, _) -> failwith " ITEM2(Tabledefault, _, _) "
+ | ITEM2(Technology, _, _) -> failwith " ITEM2(Technology, _, _) "
+ | ITEM2(Textheight, _, _) -> failwith " ITEM2(Textheight, _, _) "
+ | ITEM2(Then, _, _) -> failwith " ITEM2(Then, _, _) "
+ | ITEM2(Timeinterval, _, _) -> failwith " ITEM2(Timeinterval, _, _) "
+ | ITEM2(Timestamp, _, _) -> failwith " ITEM2(Timestamp, _, _) "
+ | ITEM2(Timing, _, _) -> failwith " ITEM2(Timing, _, _) "
+ | ITEM2(Transform, _, _) -> failwith " ITEM2(Transform, _, _) "
+ | ITEM2(Transition, _, _) -> failwith " ITEM2(Transition, _, _) "
+ | ITEM2(Trigger, _, _) -> failwith " ITEM2(Trigger, _, _) "
+ | ITEM2(True, _, _) -> failwith " ITEM2(True, _, _) "
+ | ITEM2(Typedvalue, _, _) -> failwith " ITEM2(Typedvalue, _, _) "
+ | ITEM2(Unconstrained, _, _) -> failwith " ITEM2(Unconstrained, _, _) "
+ | ITEM2(Undefined, _, _) -> failwith " ITEM2(Undefined, _, _) "
+ | ITEM2(Union, _, _) -> failwith " ITEM2(Union, _, _) "
+ | ITEM2(Unit, _, _) -> failwith " ITEM2(Unit, _, _) "
+ | ITEM2(Unused, _, _) -> failwith " ITEM2(Unused, _, _) "
+ | ITEM2(Userdata, _, _) -> failwith " ITEM2(Userdata, _, _) "
+ | ITEM2(Valuenameref, _, _) -> failwith " ITEM2(Valuenameref, _, _) "
+ | ITEM2(Variable, _, _) -> failwith " ITEM2(Variable, _, _) "
+ | ITEM2(Version, _, _) -> failwith " ITEM2(Version, _, _) "
+ | ITEM2(View, _, _) -> failwith " ITEM2(View, _, _) "
+ | ITEM2(Viewlist, _, _) -> failwith " ITEM2(Viewlist, _, _) "
+ | ITEM2(Viewmap, _, _) -> failwith " ITEM2(Viewmap, _, _) "
+ | ITEM2(Viewref, _, _) -> failwith " ITEM2(Viewref, _, _) "
+ | ITEM2(Viewtype, _, _) -> failwith " ITEM2(Viewtype, _, _) "
+ | ITEM2(Visible, _, _) -> failwith " ITEM2(Visible, _, _) "
+ | ITEM2(Voltagemap, _, _) -> failwith " ITEM2(Voltagemap, _, _) "
+ | ITEM2(Wavevalue, _, _) -> failwith " ITEM2(Wavevalue, _, _) "
+ | ITEM2(Weak, _, _) -> failwith " ITEM2(Weak, _, _) "
+ | ITEM2(Weakjoined, _, _) -> failwith " ITEM2(Weakjoined, _, _) "
+ | ITEM2(When, _, _) -> failwith " ITEM2(When, _, _) "
+ | ITEM2(While, _, _) -> failwith " ITEM2(While, _, _) "
+ | ITEM2(Written, _, _) -> failwith " ITEM2(Written, _, _) "
+ | ITEM2(Xcoord, _, _) -> failwith " ITEM2(Xcoord, _, _) "
+ | ITEM2(Xor, _, _) -> failwith " ITEM2(Xor, _, _) "
+ | ITEM2(Ycoord, _, _) -> failwith " ITEM2(Ycoord, _, _) "
+ | ITEM2(ILLEGAL _, _, _) -> failwith " ITEM2(ILLEGAL _, _, _) "
+ | ITEM2(ID _, _, _) -> failwith " ITEM2(ID _, _, _) "
+ | ITEM2(TLIST _, _, _) -> failwith " ITEM2(TLIST _, _, _) "
+ | ITEM2(TLIST2 _, _, _) -> failwith " ITEM2(TLIST2 _, _, _) "
+ | ITEM2(STRING _, _, _) -> failwith " ITEM2(STRING _, _, _) "
+ | ITEM2(INT _, _, _) -> failwith " ITEM2(INT _, _, _) "
+ | ITEM2(ENDOFFILE, _, _) -> failwith " ITEM2(ENDOFFILE, _, _) "
+ | ITEM2(EOL, _, _) -> failwith " ITEM2(EOL, _, _) "
+ | ITEM2(LPAREN, _, _) -> failwith " ITEM2(LPAREN, _, _) "
+ | ITEM2(RPAREN, _, _) -> failwith " ITEM2(RPAREN, _, _) "
+ | ITEM2(EMPTY, _, _) -> failwith " ITEM2(EMPTY, _, _) "
+
+ | ITEM(Abs, _) -> failwith " ITEM(Abs, _) "
+ | ITEM(Acload, _) -> failwith " ITEM(Acload, _) "
+ | ITEM(After, _) -> failwith " ITEM(After, _) "
+ | ITEM(And, _) -> failwith " ITEM(And, _) "
+ | ITEM(Annotate, _) -> failwith " ITEM(Annotate, _) "
+ | ITEM(Apply, _) -> failwith " ITEM(Apply, _) "
+ | ITEM(Arc, _) -> failwith " ITEM(Arc, _) "
+ | ITEM(Array, _) -> failwith " ITEM(Array, _) "
+ | ITEM(Arraymacro, _) -> failwith " ITEM(Arraymacro, _) "
+ | ITEM(Arrayrelatedinfo, _) -> failwith " ITEM(Arrayrelatedinfo, _) "
+ | ITEM(Arraysite, _) -> failwith " ITEM(Arraysite, _) "
+ | ITEM(Assign, _) -> failwith " ITEM(Assign, _) "
+ | ITEM(Atleast, _) -> failwith " ITEM(Atleast, _) "
+ | ITEM(Atmost, _) -> failwith " ITEM(Atmost, _) "
+ | ITEM(Author, _) -> failwith " ITEM(Author, _) "
+ | ITEM(Basearray, _) -> failwith " ITEM(Basearray, _) "
+ | ITEM(Becomes, _) -> failwith " ITEM(Becomes, _) "
+ | ITEM(Between, _) -> failwith " ITEM(Between, _) "
+ | ITEM(Block, _) -> failwith " ITEM(Block, _) "
+ | ITEM(Boolean, _) -> failwith " ITEM(Boolean, _) "
+ | ITEM(Booleandisplay, _) -> failwith " ITEM(Booleandisplay, _) "
+ | ITEM(Booleanmap, _) -> failwith " ITEM(Booleanmap, _) "
+ | ITEM(Booleanvalue, _) -> failwith " ITEM(Booleanvalue, _) "
+ | ITEM(Borderpattern, _) -> failwith " ITEM(Borderpattern, _) "
+ | ITEM(Borderwidth, _) -> failwith " ITEM(Borderwidth, _) "
+ | ITEM(Boundingbox, _) -> failwith " ITEM(Boundingbox, _) "
+ | ITEM(Ceiling, _) -> failwith " ITEM(Ceiling, _) "
+ | ITEM(Cell, _) -> failwith " ITEM(Cell, _) "
+ | ITEM(Cellref, _) -> failwith " ITEM(Cellref, _) "
+ | ITEM(Celltype, _) -> failwith " ITEM(Celltype, _) "
+ | ITEM(Change, _) -> failwith " ITEM(Change, _) "
+ | ITEM(Circle, _) -> failwith " ITEM(Circle, _) "
+ | ITEM(Color, _) -> failwith " ITEM(Color, _) "
+ | ITEM(Comment, _) -> 32
+ | ITEM(Commentgraphics, _) -> failwith " ITEM(Commentgraphics, _) "
+ | ITEM(Compound, _) -> failwith " ITEM(Compound, _) "
+ | ITEM(Concat, _) -> failwith " ITEM(Concat, _) "
+ | ITEM(Connectlocation, _) -> failwith " ITEM(Connectlocation, _) "
+ | ITEM(Constant, _) -> failwith " ITEM(Constant, _) "
+ | ITEM(Constraint, _) -> failwith " ITEM(Constraint, _) "
+ | ITEM(Contents, _) -> failwith " ITEM(Contents, _) "
+ | ITEM(Cornertype, _) -> failwith " ITEM(Cornertype, _) "
+ | ITEM(Criticality, _) -> failwith " ITEM(Criticality, _) "
+ | ITEM(Currentmap, _) -> failwith " ITEM(Currentmap, _) "
+ | ITEM(Curve, _) -> failwith " ITEM(Curve, _) "
+ | ITEM(Cycle, _) -> failwith " ITEM(Cycle, _) "
+ | ITEM(Dataorigin, _) -> failwith " ITEM(Dataorigin, _) "
+ | ITEM(Dcfaninload, _) -> failwith " ITEM(Dcfaninload, _) "
+ | ITEM(Dcfanoutload, _) -> failwith " ITEM(Dcfanoutload, _) "
+ | ITEM(Dcmaxfanin, _) -> failwith " ITEM(Dcmaxfanin, _) "
+ | ITEM(Dcmaxfanout, _) -> failwith " ITEM(Dcmaxfanout, _) "
+ | ITEM(Delay, _) -> failwith " ITEM(Delay, _) "
+ | ITEM(Delta, _) -> failwith " ITEM(Delta, _) "
+ | ITEM(Derivation, _) -> failwith " ITEM(Derivation, _) "
+ | ITEM(Design, _) -> failwith " ITEM(Design, _) "
+ | ITEM(Designator, _) -> failwith " ITEM(Designator, _) "
+ | ITEM(Difference, _) -> failwith " ITEM(Difference, _) "
+ | ITEM(Direction, _) -> failwith " ITEM(Direction, _) "
+ | ITEM(Display, _) -> failwith " ITEM(Display, _) "
+ | ITEM(Divide, _) -> failwith " ITEM(Divide, _) "
+ | ITEM(Dominates, _) -> failwith " ITEM(Dominates, _) "
+ | ITEM(Dot, _) -> failwith " ITEM(Dot, _) "
+ | ITEM(Duration, _) -> failwith " ITEM(Duration, _) "
+ | ITEM(E, _) -> failwith " ITEM(E, _) "
+ | ITEM(Edif, _) -> failwith " ITEM(Edif, _) "
+ | ITEM(Ediflevel, _) -> failwith " ITEM(Ediflevel, _) "
+ | ITEM(Edifversion, _) -> failwith " ITEM(Edifversion, _) "
+ | ITEM(Else, _) -> failwith " ITEM(Else, _) "
+ | ITEM(Enclosuredistance, _) -> failwith " ITEM(Enclosuredistance, _) "
+ | ITEM(Endtype, _) -> failwith " ITEM(Endtype, _) "
+ | ITEM(Entry, _) -> failwith " ITEM(Entry, _) "
+ | ITEM(Equal, _) -> failwith " ITEM(Equal, _) "
+ | ITEM(Escape, _) -> failwith " ITEM(Escape, _) "
+ | ITEM(Event, _) -> failwith " ITEM(Event, _) "
+ | ITEM(Exactly, _) -> failwith " ITEM(Exactly, _) "
+ | ITEM(External, _) -> failwith " ITEM(External, _) "
+ | ITEM(Fabricate, _) -> failwith " ITEM(Fabricate, _) "
+ | ITEM(False, _) -> failwith " ITEM(False, _) "
+ | ITEM(Figure, _) -> failwith " ITEM(Figure, _) "
+ | ITEM(Figurearea, _) -> failwith " ITEM(Figurearea, _) "
+ | ITEM(Figuregroup, _) -> failwith " ITEM(Figuregroup, _) "
+ | ITEM(Figuregroupobject, _) -> failwith " ITEM(Figuregroupobject, _) "
+ | ITEM(Figuregroupoverride, _) -> failwith " ITEM(Figuregroupoverride, _) "
+ | ITEM(Figuregroupref, _) -> failwith " ITEM(Figuregroupref, _) "
+ | ITEM(Figureperimeter, _) -> failwith " ITEM(Figureperimeter, _) "
+ | ITEM(Figurewidth, _) -> failwith " ITEM(Figurewidth, _) "
+ | ITEM(Fillpattern, _) -> failwith " ITEM(Fillpattern, _) "
+ | ITEM(Fix, _) -> failwith " ITEM(Fix, _) "
+ | ITEM(Floor, _) -> failwith " ITEM(Floor, _) "
+ | ITEM(Follow, _) -> failwith " ITEM(Follow, _) "
+ | ITEM(Forbiddenevent, _) -> failwith " ITEM(Forbiddenevent, _) "
+ | ITEM(Form, _) -> failwith " ITEM(Form, _) "
+ | ITEM(Globalportref, _) -> failwith " ITEM(Globalportref, _) "
+ | ITEM(Greaterthan, _) -> failwith " ITEM(Greaterthan, _) "
+ | ITEM(Gridmap, _) -> failwith " ITEM(Gridmap, _) "
+ | ITEM(If, _) -> failwith " ITEM(If, _) "
+ | ITEM(Ignore, _) -> failwith " ITEM(Ignore, _) "
+ | ITEM(Includefiguregroup, _) -> failwith " ITEM(Includefiguregroup, _) "
+ | ITEM(Increasing, _) -> failwith " ITEM(Increasing, _) "
+ | ITEM(Initial, _) -> failwith " ITEM(Initial, _) "
+ | ITEM(Instance, _) -> failwith " ITEM(Instance, _) "
+ | ITEM(Instancebackannotate, _) -> failwith " ITEM(Instancebackannotate, _) "
+ | ITEM(Instancegroup, _) -> failwith " ITEM(Instancegroup, _) "
+ | ITEM(Instancemap, _) -> failwith " ITEM(Instancemap, _) "
+ | ITEM(Instancenamedef, _) -> failwith " ITEM(Instancenamedef, _) "
+ | ITEM(Instanceref, _) -> failwith " ITEM(Instanceref, _) "
+ | ITEM(Integer, _) -> failwith " ITEM(Integer, _) "
+ | ITEM(Integerdisplay, _) -> failwith " ITEM(Integerdisplay, _) "
+ | ITEM(Interface, _) -> failwith " ITEM(Interface, _) "
+ | ITEM(Interfiguregroupspacing, _) ->
+ failwith " ITEM(Interfiguregroupspacing, _) "
+ | ITEM(Intersection, _) -> failwith " ITEM(Intersection, _) "
+ | ITEM(Intrafiguregroupspacing, _) ->
+ failwith " ITEM(Intrafiguregroupspacing, _) "
+ | ITEM(Inverse, _) -> failwith " ITEM(Inverse, _) "
+ | ITEM(Isolated, _) -> failwith " ITEM(Isolated, _) "
+ | ITEM(Iterate, _) -> failwith " ITEM(Iterate, _) "
+ | ITEM(Joined, _) -> failwith " ITEM(Joined, _) "
+ | ITEM(Justify, _) -> failwith " ITEM(Justify, _) "
+ | ITEM(Keyworddisplay, _) -> failwith " ITEM(Keyworddisplay, _) "
+ | ITEM(Keywordlevel, _) -> failwith " ITEM(Keywordlevel, _) "
+ | ITEM(Keywordmap, _) -> failwith " ITEM(Keywordmap, _) "
+ | ITEM(Lessthan, _) -> failwith " ITEM(Lessthan, _) "
+ | ITEM(Library, _) -> failwith " ITEM(Library, _) "
+ | ITEM(Libraryref, _) -> failwith " ITEM(Libraryref, _) "
+ | ITEM(Listofnets, _) -> failwith " ITEM(Listofnets, _) "
+ | ITEM(Listofports, _) -> failwith " ITEM(Listofports, _) "
+ | ITEM(Loaddelay, _) -> failwith " ITEM(Loaddelay, _) "
+ | ITEM(Logicassign, _) -> failwith " ITEM(Logicassign, _) "
+ | ITEM(Logicinput, _) -> failwith " ITEM(Logicinput, _) "
+ | ITEM(Logiclist, _) -> failwith " ITEM(Logiclist, _) "
+ | ITEM(Logicmapinput, _) -> failwith " ITEM(Logicmapinput, _) "
+ | ITEM(Logicmapoutput, _) -> failwith " ITEM(Logicmapoutput, _) "
+ | ITEM(Logiconeof, _) -> failwith " ITEM(Logiconeof, _) "
+ | ITEM(Logicoutput, _) -> failwith " ITEM(Logicoutput, _) "
+ | ITEM(Logicport, _) -> failwith " ITEM(Logicport, _) "
+ | ITEM(Logicref, _) -> failwith " ITEM(Logicref, _) "
+ | ITEM(Logicvalue, _) -> failwith " ITEM(Logicvalue, _) "
+ | ITEM(Logicwaveform, _) -> failwith " ITEM(Logicwaveform, _) "
+ | ITEM(Maintain, _) -> failwith " ITEM(Maintain, _) "
+ | ITEM(Match, _) -> failwith " ITEM(Match, _) "
+ | ITEM(Max, _) -> failwith " ITEM(Max, _) "
+ | ITEM(Member, _) -> failwith " ITEM(Member, _) "
+ | ITEM(Min, _) -> failwith " ITEM(Min, _) "
+ | ITEM(Minomax, _) -> failwith " ITEM(Minomax, _) "
+ | ITEM(Minomaxdisplay, _) -> failwith " ITEM(Minomaxdisplay, _) "
+ | ITEM(Mnm, _) -> failwith " ITEM(Mnm, _) "
+ | ITEM(Mod, _) -> failwith " ITEM(Mod, _) "
+ | ITEM(Multiplevalueset, _) -> failwith " ITEM(Multiplevalueset, _) "
+ | ITEM(Mustjoin, _) -> failwith " ITEM(Mustjoin, _) "
+ | ITEM(Name, _) -> failwith " ITEM(Name, _) "
+ | ITEM(Negate, _) -> failwith " ITEM(Negate, _) "
+ | ITEM(Net, _) -> failwith " ITEM(Net, _) "
+ | ITEM(Netbackannotate, _) -> failwith " ITEM(Netbackannotate, _) "
+ | ITEM(Netbundle, _) -> failwith " ITEM(Netbundle, _) "
+ | ITEM(Netdelay, _) -> failwith " ITEM(Netdelay, _) "
+ | ITEM(Netgroup, _) -> failwith " ITEM(Netgroup, _) "
+ | ITEM(Netmap, _) -> failwith " ITEM(Netmap, _) "
+ | ITEM(Netref, _) -> failwith " ITEM(Netref, _) "
+ | ITEM(Nochange, _) -> failwith " ITEM(Nochange, _) "
+ | ITEM(Nonpermutable, _) -> failwith " ITEM(Nonpermutable, _) "
+ | ITEM(Not, _) -> failwith " ITEM(Not, _) "
+ | ITEM(Notallowed, _) -> failwith " ITEM(Notallowed, _) "
+ | ITEM(Notchspacing, _) -> failwith " ITEM(Notchspacing, _) "
+ | ITEM(Number, _) -> failwith " ITEM(Number, _) "
+ | ITEM(Numberdefinition, _) -> failwith " ITEM(Numberdefinition, _) "
+ | ITEM(Numberdisplay, _) -> failwith " ITEM(Numberdisplay, _) "
+ | ITEM(Offpageconnector, _) -> failwith " ITEM(Offpageconnector, _) "
+ | ITEM(Offsetevent, _) -> failwith " ITEM(Offsetevent, _) "
+ | ITEM(Openshape, _) -> failwith " ITEM(Openshape, _) "
+ | ITEM(Or, _) -> failwith " ITEM(Or, _) "
+ | ITEM(Orientation, _) -> failwith " ITEM(Orientation, _) "
+ | ITEM(Origin, _) -> failwith " ITEM(Origin, _) "
+ | ITEM(Overhangdistance, _) -> failwith " ITEM(Overhangdistance, _) "
+ | ITEM(Overlapdistance, _) -> failwith " ITEM(Overlapdistance, _) "
+ | ITEM(Oversize, _) -> failwith " ITEM(Oversize, _) "
+ | ITEM(Owner, _) -> failwith " ITEM(Owner, _) "
+ | ITEM(Page, _) -> failwith " ITEM(Page, _) "
+ | ITEM(Pagesize, _) -> failwith " ITEM(Pagesize, _) "
+ | ITEM(Parameter, _) -> failwith " ITEM(Parameter, _) "
+ | ITEM(Parameterassign, _) -> failwith " ITEM(Parameterassign, _) "
+ | ITEM(Parameterdisplay, _) -> failwith " ITEM(Parameterdisplay, _) "
+ | ITEM(Path, _) -> failwith " ITEM(Path, _) "
+ | ITEM(Pathdelay, _) -> failwith " ITEM(Pathdelay, _) "
+ | ITEM(Pathwidth, _) -> failwith " ITEM(Pathwidth, _) "
+ | ITEM(Permutable, _) -> failwith " ITEM(Permutable, _) "
+ | ITEM(Physicaldesignrule, _) -> failwith " ITEM(Physicaldesignrule, _) "
+ | ITEM(Plug, _) -> failwith " ITEM(Plug, _) "
+ | ITEM(Point, _) -> failwith " ITEM(Point, _) "
+ | ITEM(Pointdisplay, _) -> failwith " ITEM(Pointdisplay, _) "
+ | ITEM(Pointlist, _) -> failwith " ITEM(Pointlist, _) "
+ | ITEM(Pointsubtract, _) -> failwith " ITEM(Pointsubtract, _) "
+ | ITEM(Pointsum, _) -> failwith " ITEM(Pointsum, _) "
+ | ITEM(Polygon, _) -> failwith " ITEM(Polygon, _) "
+ | ITEM(Port, _) -> failwith " ITEM(Port, _) "
+ | ITEM(Portbackannotate, _) -> failwith " ITEM(Portbackannotate, _) "
+ | ITEM(Portbundle, _) -> failwith " ITEM(Portbundle, _) "
+ | ITEM(Portdelay, _) -> failwith " ITEM(Portdelay, _) "
+ | ITEM(Portgroup, _) -> failwith " ITEM(Portgroup, _) "
+ | ITEM(Portimplementation, _) -> failwith " ITEM(Portimplementation, _) "
+ | ITEM(Portinstance, _) -> failwith " ITEM(Portinstance, _) "
+ | ITEM(Portlist, _) -> failwith " ITEM(Portlist, _) "
+ | ITEM(Portlistalias, _) -> failwith " ITEM(Portlistalias, _) "
+ | ITEM(Portmap, _) -> failwith " ITEM(Portmap, _) "
+ | ITEM(Portref, _) -> failwith " ITEM(Portref, _) "
+ | ITEM(Product, _) -> failwith " ITEM(Product, _) "
+ | ITEM(Program, _) -> failwith " ITEM(Program, _) "
+ | ITEM(Property, _) -> failwith " ITEM(Property, _) "
+ | ITEM(Propertydisplay, _) -> failwith " ITEM(Propertydisplay, _) "
+ | ITEM(Protectionframe, _) -> failwith " ITEM(Protectionframe, _) "
+ | ITEM(Pt, _) -> failwith " ITEM(Pt, _) "
+ | ITEM(Rangevector, _) -> failwith " ITEM(Rangevector, _) "
+ | ITEM(Rectangle, _) -> failwith " ITEM(Rectangle, _) "
+ | ITEM(Rectanglesize, _) -> failwith " ITEM(Rectanglesize, _) "
+ | ITEM(Rename, _) -> failwith " ITEM(Rename, _) "
+ | ITEM(Resolves, _) -> failwith " ITEM(Resolves, _) "
+ | ITEM(Scale, _) -> failwith " ITEM(Scale, _) "
+ | ITEM(Scalex, _) -> failwith " ITEM(Scalex, _) "
+ | ITEM(Scaley, _) -> failwith " ITEM(Scaley, _) "
+ | ITEM(Section, _) -> failwith " ITEM(Section, _) "
+ | ITEM(Shape, _) -> failwith " ITEM(Shape, _) "
+ | ITEM(Simulate, _) -> failwith " ITEM(Simulate, _) "
+ | ITEM(Simulationinfo, _) -> failwith " ITEM(Simulationinfo, _) "
+ | ITEM(Singlevalueset, _) -> failwith " ITEM(Singlevalueset, _) "
+ | ITEM(Site, _) -> failwith " ITEM(Site, _) "
+ | ITEM(Socket, _) -> failwith " ITEM(Socket, _) "
+ | ITEM(Socketset, _) -> failwith " ITEM(Socketset, _) "
+ | ITEM(Statement, _) -> failwith " ITEM(Statement, _) "
+ | ITEM(Status, _) -> failwith " ITEM(Status, _) "
+ | ITEM(Steady, _) -> failwith " ITEM(Steady, _) "
+ | ITEM(Strictlyincreasing, _) -> failwith " ITEM(Strictlyincreasing, _) "
+ | ITEM(String, _) -> failwith " ITEM(String, _) "
+ | ITEM(Stringdisplay, _) -> failwith " ITEM(Stringdisplay, _) "
+ | ITEM(Strong, _) -> failwith " ITEM(Strong, _) "
+ | ITEM(Subtract, _) -> failwith " ITEM(Subtract, _) "
+ | ITEM(Sum, _) -> failwith " ITEM(Sum, _) "
+ | ITEM(Symbol, _) -> failwith " ITEM(Symbol, _) "
+ | ITEM(Symmetry, _) -> failwith " ITEM(Symmetry, _) "
+ | ITEM(Table, _) -> failwith " ITEM(Table, _) "
+ | ITEM(Tabledefault, _) -> failwith " ITEM(Tabledefault, _) "
+ | ITEM(Technology, _) -> failwith " ITEM(Technology, _) "
+ | ITEM(Textheight, _) -> failwith " ITEM(Textheight, _) "
+ | ITEM(Then, _) -> failwith " ITEM(Then, _) "
+ | ITEM(Timeinterval, _) -> failwith " ITEM(Timeinterval, _) "
+ | ITEM(Timestamp, _) -> failwith " ITEM(Timestamp, _) "
+ | ITEM(Timing, _) -> failwith " ITEM(Timing, _) "
+ | ITEM(Transform, _) -> failwith " ITEM(Transform, _) "
+ | ITEM(Transition, _) -> failwith " ITEM(Transition, _) "
+ | ITEM(Trigger, _) -> failwith " ITEM(Trigger, _) "
+ | ITEM(True, _) -> failwith " ITEM(True, _) "
+ | ITEM(Typedvalue, _) -> failwith " ITEM(Typedvalue, _) "
+ | ITEM(Unconstrained, _) -> failwith " ITEM(Unconstrained, _) "
+ | ITEM(Undefined, _) -> failwith " ITEM(Undefined, _) "
+ | ITEM(Union, _) -> failwith " ITEM(Union, _) "
+ | ITEM(Unit, _) -> failwith " ITEM(Unit, _) "
+ | ITEM(Unused, _) -> failwith " ITEM(Unused, _) "
+ | ITEM(Userdata, _) -> failwith " ITEM(Userdata, _) "
+ | ITEM(Valuenameref, _) -> failwith " ITEM(Valuenameref, _) "
+ | ITEM(Variable, _) -> failwith " ITEM(Variable, _) "
+ | ITEM(Version, _) -> failwith " ITEM(Version, _) "
+ | ITEM(View, _) -> failwith " ITEM(View, _) "
+ | ITEM(Viewlist, _) -> failwith " ITEM(Viewlist, _) "
+ | ITEM(Viewmap, _) -> failwith " ITEM(Viewmap, _) "
+ | ITEM(Viewref, _) -> failwith " ITEM(Viewref, _) "
+ | ITEM(Viewtype, _) -> failwith " ITEM(Viewtype, _) "
+ | ITEM(Visible, _) -> failwith " ITEM(Visible, _) "
+ | ITEM(Voltagemap, _) -> failwith " ITEM(Voltagemap, _) "
+ | ITEM(Wavevalue, _) -> failwith " ITEM(Wavevalue, _) "
+ | ITEM(Weak, _) -> failwith " ITEM(Weak, _) "
+ | ITEM(Weakjoined, _) -> failwith " ITEM(Weakjoined, _) "
+ | ITEM(When, _) -> failwith " ITEM(When, _) "
+ | ITEM(While, _) -> failwith " ITEM(While, _) "
+ | ITEM(Written, _) -> failwith " ITEM(Written, _) "
+ | ITEM(Xcoord, _) -> failwith " ITEM(Xcoord, _) "
+ | ITEM(Xor, _) -> failwith " ITEM(Xor, _) "
+ | ITEM(Ycoord, _) -> failwith " ITEM(Ycoord, _) "
+ | ITEM(ILLEGAL _, _) -> failwith " ITEM(ILLEGAL _, _) "
+ | ITEM(ID _, _) -> failwith " ITEM(ID _, _) "
+ | ITEM(TLIST _, _) -> failwith " ITEM(TLIST _, _) "
+ | ITEM(TLIST2 _, _) -> failwith " ITEM(TLIST2 _, _) "
+ | ITEM(STRING _, _) -> failwith " ITEM(STRING _, _) "
+ | ITEM(INT _, _) -> failwith " ITEM(INT _, _) "
+ | ITEM(ENDOFFILE, _) -> failwith " ITEM(ENDOFFILE, _) "
+ | ITEM(EOL, _) -> failwith " ITEM(EOL, _) "
+ | ITEM(LPAREN, _) -> failwith " ITEM(LPAREN, _) "
+ | ITEM(RPAREN, _) -> failwith " ITEM(RPAREN, _) "
+ | ITEM(EMPTY, _) -> failwith " ITEM(EMPTY, _) "
+ | ITEM ((ITEM _|ITEM2 _), _) -> failwith " ITEM ((ITEM _|ITEM2 _), _) "
+ | ITEM2 ((ITEM _|ITEM2 _), _, _) ->
+ failwith " ITEM2 ((ITEM _|ITEM2 _), _, _) "
+
+let () = printf "PR#6646=Ok\n%!"
+
+(* Simplified example, with application test *)
+
+type t =
+ | B of int
+ | C of int
+ | I of t list
+ | A00
+ | A01
+ | A02
+ | A03
+ | A04
+ | A05
+ | A06
+ | A07
+ | A08
+ | A09
+ | A10
+ | A11
+ | A12
+ | A13
+ | A14
+ | A15
+ | A16
+ | A17
+ | A18
+ | A19
+ | A20
+ | A21
+ | A22
+ | A23
+ | A24
+ | A25
+ | A26
+ | A27
+ | A28
+ | A29
+ | A30
+ | A31
+ | A32
+ | A33
+ | A34
+ | A35
+ | A36
+ | A37
+ | A38
+ | A39
+ | A40
+ | A41
+ | A42
+ | A43
+ | A44
+ | A45
+ | A46
+ | A47
+ | A48
+ | A49
+ | A50
+ | A51
+ | A52
+ | A53
+ | A54
+ | A55
+ | A56
+ | A57
+ | A58
+ | A59
+ | A60
+ | A61
+ | A62
+ | A63
+ | A64
+ | A65
+ | A66
+ | A67
+ | A68
+ | A69
+ | A70
+ | A71
+ | A72
+ | A73
+ | A74
+ | A75
+ | A76
+ | A77
+ | A78
+ | A79
+ | A80
+ | A81
+ | A82
+ | A83
+ | A84
+ | A85
+ | A86
+ | A87
+ | A88
+ | A89
+ | A90
+ | A91
+ | A92
+ | A93
+ | A94
+ | A95
+ | A96
+ | A97
+ | A98
+ | A99
+
+
+let test = function
+ | I [A00;I [I [A00;I [A00]]]] -> 1
+ | I [A00;I [I [A00;I [A01]]]] -> 2
+ | I [A00;I [I [A00;I [A02]]]] -> 3
+ | I [A00;I [I [A00;I [A03]]]] -> -3
+ | I [A00;I [I [A00;I [A04]]]] -> 4
+ | I [A00;I [I [A00;I [A05]]]] -> 5
+ | I [A00;I [I [A00;I [A06]]]] -> 6
+ | I [A00;I [I [A00;I [A07]]]] -> 7
+ | I [A00;I [I [A00;I [A08]]]] -> 8
+ | I [A00;I [I [A00;I [A09]]]] -> 9
+
+ | I [A00;I [I [_ ; I [A00]]]] -> 11
+ | I [A00;I [I [_ ; I [A01]]]] -> 12
+ | I [A00;I [I [_ ; I [A02]]]] -> 13
+ | _ -> -1
+
+
+let () =
+ assert (test (I [A00;I [I [A00;I [A00]]]]) = 1) ;
+ assert (test (I [A00;I [I [A20;I [A00]]]]) = 11) ;
+ assert (test (I [A00;I [I [A00;I [A01]]]]) = 2) ;
+ assert (test (I [A00;I [I [A20;I [A01]]]]) = 12) ;
+ assert (test (I [A00;I [I [A00;I [A02]]]]) = 3) ;
+ assert (test (I [A00;I [I [A20;I [A02]]]]) = 13) ;
+ assert (test (I [A00;I [I [A00;I [A03]]]]) = -3) ;
+ assert (test (I [A00;I [I [A20;I [A03]]]]) = -1) ;
+ printf "PR#6646=Ok\n%!"
+
+(* PR#6674, a compilation failure introduced by correcting PR#6646 *)
+
+type t6674 =
+ | A1
+ | A2
+ | A3
+ | A4
+ | A5
+ | A6
+ | A7
+ | A8
+ | A9
+ | A10
+ | A11
+ | A12
+ | A13
+ | A14
+ | A15
+ | A16
+ | A17
+ | A18
+ | A19
+ | A20
+ | A21
+ | A22
+ | A23
+ | A24
+ | A25
+ | A26
+ | A27
+ | A28
+ | A29
+ | A30
+ | A31
+ | A32
+ | X of string
+
+let f = function
+ | X _ -> true
+ | _ -> false
+
+let () = printf "PR#6676=Ok\n%!"
diff --git a/testsuite/tests/basic/patmatch.reference b/testsuite/tests/basic/patmatch.reference
new file mode 100644
index 0000000000..aafc1b5c4f
--- /dev/null
+++ b/testsuite/tests/basic/patmatch.reference
@@ -0,0 +1,75 @@
+f(-5) = 0
+f(-4) = 0
+f(-3) = 0
+f(-2) = 0
+f(-1) = 0
+f(0) = 0
+f(1) = 1
+f(2) = 2
+f(3) = 3
+f(4) = 4
+f(5) = 5
+f(6) = 6
+f(7) = 0
+f(8) = 0
+f(9) = 0
+f(10) = 0
+g(0) = 0
+g(300) = 0
+g(303) = 1
+g(305) = 0
+g(400) = 0
+g(401) = 2
+g(402) = 0
+g(999) = 0
+iszero(-2) = false
+iszero(-1) = false
+iszero(0) = true
+iszero(1) = false
+iszero(2) = false
+h(a) = a
+h(b) = ?
+h(c) = ?
+h(d) = ?
+h(e) = e
+h(f) = ?
+h(g) = ?
+h(h) = ?
+h(i) = i
+h(j) = ?
+h(k) = ?
+h(l) = ?
+h(m) = ?
+h(n) = ?
+h(o) = o
+h(p) = ?
+h(q) = ?
+h(r) = ?
+h(s) = ?
+h(t) = ?
+h(u) = u
+h(v) = ?
+h(w) = ?
+h(x) = ?
+h(y) = ?
+h(z) = ?
+h({) = ?
+h(|) = ?
+h(}) = ?
+h(~) = ?
+ k(\000) = othr k(\001) = othr k(\002) = othr k(\003) = othr k(\004) = othr k(\005) = othr k(\006) = othr k(\007) = othr k(\b) = othr k(\t) = blk k(\n) = blk k(\011) = othr k(\012) = othr k(\r) = blk k(\014) = othr k(\015) = othr k(\016) = othr k(\017) = othr k(\018) = othr k(\019) = othr k(\020) = othr k(\021) = othr k(\022) = othr k(\023) = othr k(\024) = othr k(\025) = othr k(\026) = othr k(\027) = othr k(\028) = othr k(\029) = othr k(\030) = othr k(\031) = othr k( ) = blk k(!) = oper k(\034) = othr k(#) = oper k($) = oper k(%) = oper k(&) = oper k(\') = othr k(\040) = othr k(\041) = othr k(*) = oper k(+) = oper k(\044) = othr k(\045) = othr k(\046) = othr k(/) = oper k(0) = dig k(1) = dig k(2) = dig k(3) = dig k(4) = dig k(5) = dig k(6) = dig k(7) = dig k(8) = dig k(9) = dig k(:) = oper k(\059) = othr k(<) = oper k(=) = oper k(>) = oper k(?) = oper k(@) = oper k(A) = letr k(B) = letr k(C) = letr k(D) = letr k(E) = letr k(F) = letr k(G) = letr k(H) = letr k(I) = letr k(J) = letr k(K) = letr k(L) = letr k(M) = letr k(N) = letr k(O) = letr k(P) = letr k(Q) = letr k(R) = letr k(S) = letr k(T) = letr k(U) = letr k(V) = letr k(W) = letr k(X) = letr k(Y) = letr k(Z) = letr k(\091) = othr k(\\) = oper k(\093) = othr k(^) = oper k(\095) = othr k(\096) = othr k(a) = letr k(b) = letr k(c) = letr k(d) = letr k(e) = letr k(f) = letr k(g) = letr k(h) = letr k(i) = letr k(j) = letr k(k) = letr k(l) = letr k(m) = letr k(n) = letr k(o) = letr k(p) = letr k(q) = letr k(r) = letr k(s) = letr k(t) = letr k(u) = letr k(v) = letr k(w) = letr k(x) = letr k(y) = letr k(z) = letr k(\123) = othr k(|) = oper k(\125) = othr k(~) = oper k(\127) = othr k(\128) = othr k(\129) = othr k(\130) = othr k(\131) = othr k(\132) = othr k(\133) = othr k(\134) = othr k(\135) = othr k(\136) = othr k(\137) = othr k(\138) = othr k(\139) = othr k(\140) = othr k(\141) = othr k(\142) = othr k(\143) = othr k(\144) = othr k(\145) = othr k(\146) = othr k(\147) = othr k(\148) = othr k(\149) = othr k(\150) = othr k(\151) = othr k(\152) = othr k(\153) = othr k(\154) = othr k(\155) = othr k(\156) = othr k(\157) = othr k(\158) = othr k(\159) = othr k(\160) = othr k(\161) = othr k(\162) = othr k(\163) = othr k(\164) = othr k(\165) = othr k(\166) = othr k(\167) = othr k(\168) = othr k(\169) = othr k(\170) = othr k(\171) = othr k(\172) = othr k(\173) = othr k(\174) = othr k(\175) = othr k(\176) = othr k(\177) = othr k(\178) = othr k(\179) = othr k(\180) = othr k(\181) = othr k(\182) = othr k(\183) = othr k(\184) = othr k(\185) = othr k(\186) = othr k(\187) = othr k(\188) = othr k(\189) = othr k(\190) = othr k(\191) = othr k(\192) = letr k(\193) = letr k(\194) = letr k(\195) = letr k(\196) = letr k(\197) = letr k(\198) = letr k(\199) = letr k(\200) = letr k(\201) = letr k(\202) = letr k(\203) = letr k(\204) = letr k(\205) = letr k(\206) = letr k(\207) = letr k(\208) = letr k(\209) = letr k(\210) = letr k(\211) = letr k(\212) = letr k(\213) = letr k(\214) = letr k(\215) = letr k(\216) = letr k(\217) = letr k(\218) = letr k(\219) = letr k(\220) = letr k(\221) = letr k(\222) = letr k(\223) = letr k(\224) = letr k(\225) = letr k(\226) = letr k(\227) = letr k(\228) = letr k(\229) = letr k(\230) = letr k(\231) = letr k(\232) = letr k(\233) = letr k(\234) = letr k(\235) = letr k(\236) = letr k(\237) = letr k(\238) = letr k(\239) = letr k(\240) = letr k(\241) = letr k(\242) = letr k(\243) = letr k(\244) = letr k(\245) = letr k(\246) = letr k(\247) = letr k(\248) = letr k(\249) = letr k(\250) = letr k(\251) = letr k(\252) = letr k(\253) = letr k(\254) = letr k(\255) = letr
+p([|"hello"|]) = hello
+p([|1.0|]) = 1.000000
+q([|2|]) = 2
+r([|3.0|]) = 3.000000
+l([||]) = 0
+l([|1|]) = 2
+l([|2;3|]) = 5
+l([|4;5;6|]) = 15
+PR#5992=Ok
+PR#5788=Ok
+PR#5788=Ok
+PR#6322=Ok
+PR#6646=Ok
+PR#6646=Ok
+PR#6676=Ok
diff --git a/testsuite/tests/basic/recvalues.ml b/testsuite/tests/basic/recvalues.ml
new file mode 100644
index 0000000000..4893b1057b
--- /dev/null
+++ b/testsuite/tests/basic/recvalues.ml
@@ -0,0 +1,50 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Recursive value definitions *)
+
+let _ =
+ let rec x = 1 :: x in
+ if match x with
+ 1 :: x' -> x == x'
+ | _ -> false
+ then print_string "Test 1: passed\n"
+ else print_string "Test 1: FAILED\n";
+ let one = 1 in
+ let rec y = (one, one+1) :: y in
+ if match y with
+ (1,2) :: y' -> y == y'
+ | _ -> false
+ then print_string "Test 2: passed\n"
+ else print_string "Test 2: FAILED\n";
+ let rec z = (Gc.minor(); (one, one+1)) :: z in
+ (* Trash the minor generation *)
+ for i = 0 to 50000 do ignore (ref 0) done;
+ if match z with
+ (1,2) :: z' -> z == z'
+ | _ -> false
+ then print_string "Test 3: passed\n"
+ else print_string "Test 3: FAILED\n";
+;;
+
+let rec s = "bar"
+and idx = 1
+and x1 = let f x = Printf.printf "%s\n" x in f "foo"; s, x4
+and x2 = [| x1; x1 |]
+and x3 = (fun () -> fst (x2.(idx))) :: x3
+and x4 = {contents = x3}
+;;
+
+Gc.minor ();;
+if (List.hd (!(snd (x2.(0))))) () == s
+then print_string "Test 4: passed\n"
+else print_string "Test 4: FAILED\n"
diff --git a/testsuite/tests/basic/recvalues.reference b/testsuite/tests/basic/recvalues.reference
new file mode 100644
index 0000000000..ac71fc1da6
--- /dev/null
+++ b/testsuite/tests/basic/recvalues.reference
@@ -0,0 +1,5 @@
+Test 1: passed
+Test 2: passed
+Test 3: passed
+foo
+Test 4: passed
diff --git a/testsuite/tests/basic/sets.ml b/testsuite/tests/basic/sets.ml
new file mode 100644
index 0000000000..d5eb3b717b
--- /dev/null
+++ b/testsuite/tests/basic/sets.ml
@@ -0,0 +1,37 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+module IntSet = Set.Make(struct type t = int let compare x y = x-y end)
+
+let even = List.fold_right IntSet.add [0; -2; 2; 4; 6; -10] IntSet.empty
+
+let odd = List.fold_right IntSet.add [9; -7; 5; 1; -3] IntSet.empty
+
+let _ =
+ for i = -10 to 10 do
+ Printf.printf "%d %B %B\n" i (IntSet.mem i even) (IntSet.mem i odd)
+ done
+
+module PowerSet(BaseSet: Set.S)
+ (SetOrd: functor(S: Set.S) -> Set.OrderedType) =
+ Set.Make(SetOrd(BaseSet))
+
+module IntSetSet = PowerSet(IntSet)(functor (S: Set.S) -> S)
+
+let setofset = List.fold_right IntSetSet.add [even; odd] IntSetSet.empty
+
+let _ =
+ List.iter
+ (fun s -> Printf.printf "%B\n" (IntSetSet.mem s setofset))
+ [IntSet.empty; even; odd; IntSet.union even odd]
+
+let _ = exit 0
diff --git a/testsuite/tests/basic/sets.reference b/testsuite/tests/basic/sets.reference
new file mode 100644
index 0000000000..2d4ebc2468
--- /dev/null
+++ b/testsuite/tests/basic/sets.reference
@@ -0,0 +1,25 @@
+-10 true false
+-9 false false
+-8 false false
+-7 false true
+-6 false false
+-5 false false
+-4 false false
+-3 false true
+-2 true false
+-1 false false
+0 true false
+1 false true
+2 true false
+3 false false
+4 true false
+5 false true
+6 true false
+7 false false
+8 false false
+9 false true
+10 false false
+false
+true
+true
+false
diff --git a/testsuite/tests/basic/stringmatch.ml b/testsuite/tests/basic/stringmatch.ml
new file mode 100644
index 0000000000..c0bbbaae57
--- /dev/null
+++ b/testsuite/tests/basic/stringmatch.ml
@@ -0,0 +1,750 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Luc Maranget, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Empty string oddities *)
+
+let rec tst01 s = match s with
+| "" -> 0
+| _ -> 1
+
+let () =
+ assert (tst01 "" = 0) ;
+ assert (tst01 "\000\000\000\003" = 1) ;
+ assert (tst01 "\000\000\000\000\000\000\000\007" = 1) ;
+ ()
+
+(* A few when clauses *)
+
+let tst02 s =
+ let len = String.length s in
+ match s with
+ | "" when len < 0 -> assert false
+ | "" -> 1
+ | _ when len = 0 -> assert false
+ | "A" -> 2
+ | _ -> 3
+
+let () =
+ assert (tst02 "" = 1) ;
+ assert (tst02 "A" = 2) ;
+ assert (tst02 "B" = 3) ;
+ assert (tst02 "\000\000\000\000\000\000\000\007" = 3) ;
+ assert (tst02 "\000\000\000\003" = 3) ;
+ ()
+
+(* Keword reckognition *)
+
+let s00 = "get_const"
+let t00 = "set_congt"
+let s01 = "get_var"
+let t01 = "gat_ver"
+let s02 = "get_env"
+let t02 = "get_env"
+let s03 = "get_meth"
+let t03 = "met_geth"
+let s04 = "set_var"
+let t04 = "sev_tar"
+let s05 = "app_const"
+let t05 = "ppa_const"
+let s06 = "app_var"
+let t06 = "app_var"
+let s07 = "app_env"
+let t07 = "epp_anv"
+let s08 = "app_meth"
+let t08 = "atp_meph"
+let s09 = "app_const_const"
+let t09 = "app_const_const"
+let s10 = "app_const_var"
+let t10 = "atp_consp_var"
+let s11 = "app_const_env"
+let t11 = "app_constne_v"
+let s12 = "app_const_meth"
+let t12 = "spp_conat_meth"
+let s13 = "app_var_const"
+let t13 = "app_va_rconst"
+let s14 = "app_env_const"
+let t14 = "app_env_const"
+let s15 = "app_meth_const"
+let t15 = "app_teth_consm"
+let s16 = "meth_app_const"
+let t16 = "math_epp_const"
+let s17 = "meth_app_var"
+let t17 = "meth_app_var"
+let s18 = "meth_app_env"
+let t18 = "eeth_app_mnv"
+let s19 = "meth_app_meth"
+let t19 = "meth_apt_meph"
+let s20 = "send_const"
+let t20 = "tend_conss"
+let s21 = "send_var"
+let t21 = "serd_van"
+let s22 = "send_env"
+let t22 = "sen_denv"
+let s23 = "send_meth"
+let t23 = "tend_mesh"
+
+let tst03 s = match s with
+| "get_const" -> 0
+| "get_var" -> 1
+| "get_env" -> 2
+| "get_meth" -> 3
+| "set_var" -> 4
+| "app_const" -> 5
+| "app_var" -> 6
+| "app_env" -> 7
+| "app_meth" -> 8
+| "app_const_const" -> 9
+| "app_const_var" -> 10
+| "app_const_env" -> 11
+| "app_const_meth" -> 12
+| "app_var_const" -> 13
+| "app_env_const" -> 14
+| "app_meth_const" -> 15
+| "meth_app_const" -> 16
+| "meth_app_var" -> 17
+| "meth_app_env" -> 18
+| "meth_app_meth" -> 19
+| "send_const" -> 20
+| "send_var" -> 21
+| "send_env" -> 22
+| "send_meth" -> 23
+| _ -> -1
+
+let () =
+ assert (tst03 s00 = 0) ;
+ assert (tst03 t00 = -1) ;
+ assert (tst03 s01 = 1) ;
+ assert (tst03 t01 = -1) ;
+ assert (tst03 s02 = 2) ;
+ assert (tst03 t02 = 2) ;
+ assert (tst03 s03 = 3) ;
+ assert (tst03 t03 = -1) ;
+ assert (tst03 s04 = 4) ;
+ assert (tst03 t04 = -1) ;
+ assert (tst03 s05 = 5) ;
+ assert (tst03 t05 = -1) ;
+ assert (tst03 s06 = 6) ;
+ assert (tst03 t06 = 6) ;
+ assert (tst03 s07 = 7) ;
+ assert (tst03 t07 = -1) ;
+ assert (tst03 s08 = 8) ;
+ assert (tst03 t08 = -1) ;
+ assert (tst03 s09 = 9) ;
+ assert (tst03 t09 = 9) ;
+ assert (tst03 s10 = 10) ;
+ assert (tst03 t10 = -1) ;
+ assert (tst03 s11 = 11) ;
+ assert (tst03 t11 = -1) ;
+ assert (tst03 s12 = 12) ;
+ assert (tst03 t12 = -1) ;
+ assert (tst03 s13 = 13) ;
+ assert (tst03 t13 = -1) ;
+ assert (tst03 s14 = 14) ;
+ assert (tst03 t14 = 14) ;
+ assert (tst03 s15 = 15) ;
+ assert (tst03 t15 = -1) ;
+ assert (tst03 s16 = 16) ;
+ assert (tst03 t16 = -1) ;
+ assert (tst03 s17 = 17) ;
+ assert (tst03 t17 = 17) ;
+ assert (tst03 s18 = 18) ;
+ assert (tst03 t18 = -1) ;
+ assert (tst03 s19 = 19) ;
+ assert (tst03 t19 = -1) ;
+ assert (tst03 s20 = 20) ;
+ assert (tst03 t20 = -1) ;
+ assert (tst03 s21 = 21) ;
+ assert (tst03 t21 = -1) ;
+ assert (tst03 s22 = 22) ;
+ assert (tst03 t22 = -1) ;
+ assert (tst03 s23 = 23) ;
+ assert (tst03 t23 = -1) ;
+ ()
+
+(* Activate the test first column first heuristics *)
+
+let s00 = "AAAAAAAA"
+let s01 = "AAAAAAAAAAAAAAAA"
+let s02 = "AAAAAAAAAAAAAAAAAAAAAAAA"
+let s03 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s04 = "BBBBBBBB"
+let s05 = "BBBBBBBBBBBBBBBB"
+let s06 = "BBBBBBBBBBBBBBBBBBBBBBBB"
+let s07 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
+let s08 = "CCCCCCCC"
+let s09 = "CCCCCCCCCCCCCCCC"
+let s10 = "CCCCCCCCCCCCCCCCCCCCCCCC"
+let s11 = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
+
+let tst04 s = match s with
+| "AAAAAAAA" -> 0
+| "AAAAAAAAAAAAAAAA" -> 1
+| "AAAAAAAAAAAAAAAAAAAAAAAA" -> 2
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 3
+| "BBBBBBBB" -> 4
+| "BBBBBBBBBBBBBBBB" -> 5
+| "BBBBBBBBBBBBBBBBBBBBBBBB" -> 6
+| "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" -> 7
+| "CCCCCCCC" -> 8
+| "CCCCCCCCCCCCCCCC" -> 9
+| "CCCCCCCCCCCCCCCCCCCCCCCC" -> 10
+| "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" -> 11
+| _ -> -1
+
+let () =
+ assert (tst04 s00 = 0) ;
+ assert (tst04 s01 = 1) ;
+ assert (tst04 s02 = 2) ;
+ assert (tst04 s03 = 3) ;
+ assert (tst04 s04 = 4) ;
+ assert (tst04 s05 = 5) ;
+ assert (tst04 s06 = 6) ;
+ assert (tst04 s07 = 7) ;
+ assert (tst04 s08 = 8) ;
+ assert (tst04 s09 = 9) ;
+ assert (tst04 s10 = 10) ;
+ assert (tst04 s11 = 11) ;
+ assert (tst04 "" = -1) ;
+ assert (tst04 "DDD" = -1) ;
+ assert (tst04 "DDDDDDD" = -1) ;
+ assert (tst04 "AAADDDD" = -1) ;
+ assert (tst04 "AAAAAAADDDDDDDD" = -1) ;
+ assert (tst04 "AAAAAAADDDD" = -1) ;
+ assert (tst04 "AAAAAAAAAAAAAAADDDD" = -1) ;
+ ()
+
+(* Similar *)
+
+let s00 = "AAA"
+let s01 = "AAAA"
+let s02 = "AAAAA"
+let s03 = "AAAAAA"
+let s04 = "AAAAAAA"
+let s05 = "AAAAAAAAAAAA"
+let s06 = "AAAAAAAAAAAAAAAA"
+let s07 = "AAAAAAAAAAAAAAAAAAAA"
+let s08 = "BBB"
+let s09 = "BBBB"
+let s10 = "BBBBB"
+let s11 = "BBBBBB"
+let s12 = "BBBBBBB"
+
+let tst05 s = match s with
+| "AAA" -> 0
+| "AAAA" -> 1
+| "AAAAA" -> 2
+| "AAAAAA" -> 3
+| "AAAAAAA" -> 4
+| "AAAAAAAAAAAA" -> 5
+| "AAAAAAAAAAAAAAAA" -> 6
+| "AAAAAAAAAAAAAAAAAAAA" -> 7
+| "BBB" -> 8
+| "BBBB" -> 9
+| "BBBBB" -> 10
+| "BBBBBB" -> 11
+| "BBBBBBB" -> 12
+| _ -> -1
+
+let () =
+ assert (tst05 s00 = 0) ;
+ assert (tst05 s01 = 1) ;
+ assert (tst05 s02 = 2) ;
+ assert (tst05 s03 = 3) ;
+ assert (tst05 s04 = 4) ;
+ assert (tst05 s05 = 5) ;
+ assert (tst05 s06 = 6) ;
+ assert (tst05 s07 = 7) ;
+ assert (tst05 s08 = 8) ;
+ assert (tst05 s09 = 9) ;
+ assert (tst05 s10 = 10) ;
+ assert (tst05 s11 = 11) ;
+ assert (tst05 s12 = 12) ;
+ assert (tst05 "" = -1) ;
+ assert (tst05 "AAD" = -1) ;
+ assert (tst05 "AAAD" = -1) ;
+ assert (tst05 "AAAAAAD" = -1) ;
+ assert (tst05 "AAAAAAAD" = -1) ;
+ assert (tst05 "BBD" = -1) ;
+ assert (tst05 "BBBD" = -1) ;
+ assert (tst05 "BBBBBBD" = -1) ;
+ assert (tst05 "BBBBBBBD" = -1) ;
+ ()
+
+(* Big test *)
+
+let s00 = "and"
+let t00 = "nad"
+let s01 = "as"
+let t01 = "sa"
+let s02 = "assert"
+let t02 = "asesrt"
+let s03 = "begin"
+let t03 = "negib"
+let s04 = "class"
+let t04 = "lcass"
+let s05 = "constraint"
+let t05 = "constiarnt"
+let s06 = "do"
+let t06 = "od"
+let s07 = "done"
+let t07 = "eond"
+let s08 = "downto"
+let t08 = "dowtno"
+let s09 = "else"
+let t09 = "lese"
+let s10 = "end"
+let t10 = "edn"
+let s11 = "exception"
+let t11 = "exception"
+let s12 = "external"
+let t12 = "external"
+let s13 = "false"
+let t13 = "fslae"
+let s14 = "for"
+let t14 = "ofr"
+let s15 = "fun"
+let t15 = "fnu"
+let s16 = "function"
+let t16 = "function"
+let s17 = "functor"
+let t17 = "ounctfr"
+let s18 = "if"
+let t18 = "fi"
+let s19 = "in"
+let t19 = "in"
+let s20 = "include"
+let t20 = "inculde"
+let s21 = "inherit"
+let t21 = "iehnrit"
+let s22 = "initializer"
+let t22 = "enitializir"
+let s23 = "lazy"
+let t23 = "zaly"
+let s24 = "let"
+let t24 = "elt"
+let s25 = "match"
+let t25 = "match"
+let s26 = "method"
+let t26 = "methdo"
+let s27 = "module"
+let t27 = "modelu"
+let s28 = "mutable"
+let t28 = "butamle"
+let s29 = "new"
+let t29 = "wen"
+let s30 = "object"
+let t30 = "objcet"
+let s31 = "of"
+let t31 = "of"
+let s32 = "open"
+let t32 = "epon"
+let s33 = "or"
+let t33 = "ro"
+let s34 = "private"
+let t34 = "privaet"
+let s35 = "rec"
+let t35 = "rec"
+let s36 = "sig"
+let t36 = "gis"
+let s37 = "struct"
+let t37 = "scrutt"
+let s38 = "then"
+let t38 = "hten"
+let s39 = "to"
+let t39 = "to"
+let s40 = "true"
+let t40 = "teur"
+let s41 = "try"
+let t41 = "try"
+let s42 = "type"
+let t42 = "pyte"
+let s43 = "val"
+let t43 = "val"
+let s44 = "virtual"
+let t44 = "vritual"
+let s45 = "when"
+let t45 = "whne"
+let s46 = "while"
+let t46 = "wlihe"
+let s47 = "with"
+let t47 = "iwth"
+let s48 = "mod"
+let t48 = "mod"
+let s49 = "land"
+let t49 = "alnd"
+let s50 = "lor"
+let t50 = "rol"
+let s51 = "lxor"
+let t51 = "lxor"
+let s52 = "lsl"
+let t52 = "lsl"
+let s53 = "lsr"
+let t53 = "lsr"
+let s54 = "asr"
+let t54 = "sar"
+let s55 = "A"
+let t55 = "A"
+let s56 = "AA"
+let t56 = "AA"
+let s57 = "AAA"
+let t57 = "AAA"
+let s58 = "AAAA"
+let t58 = "AAAA"
+let s59 = "AAAAA"
+let t59 = "AAAAA"
+let s60 = "AAAAAA"
+let t60 = "AAAAAA"
+let s61 = "AAAAAAA"
+let t61 = "AAAAAAA"
+let s62 = "AAAAAAAA"
+let t62 = "AAAAAAAA"
+let s63 = "AAAAAAAAA"
+let t63 = "AAAAAAAAA"
+let s64 = "AAAAAAAAAA"
+let t64 = "AAAAAAAAAA"
+let s65 = "AAAAAAAAAAA"
+let t65 = "AAAAAAAAAAA"
+let s66 = "AAAAAAAAAAAA"
+let t66 = "AAAAAAAAAAAA"
+let s67 = "AAAAAAAAAAAAA"
+let t67 = "AAAAAAAAAAAAA"
+let s68 = "AAAAAAAAAAAAAA"
+let t68 = "AAAAAAAAAAAAAA"
+let s69 = "AAAAAAAAAAAAAAA"
+let t69 = "AAAAAAAAAAAAAAA"
+let s70 = "AAAAAAAAAAAAAAAA"
+let t70 = "AAAAAAAAAAAAAAAA"
+let s71 = "AAAAAAAAAAAAAAAAA"
+let t71 = "AAAAAAAAAAAAAAAAA"
+let s72 = "AAAAAAAAAAAAAAAAAA"
+let t72 = "AAAAAAAAAAAAAAAAAA"
+let s73 = "AAAAAAAAAAAAAAAAAAA"
+let t73 = "AAAAAAAAAAAAAAAAAAA"
+let s74 = "AAAAAAAAAAAAAAAAAAAA"
+let t74 = "AAAAAAAAAAAAAAAAAAAA"
+let s75 = "AAAAAAAAAAAAAAAAAAAAA"
+let t75 = "AAAAAAAAAAAAAAAAAAAAA"
+let s76 = "AAAAAAAAAAAAAAAAAAAAAA"
+let t76 = "AAAAAAAAAAAAAAAAAAAAAA"
+let s77 = "AAAAAAAAAAAAAAAAAAAAAAA"
+let t77 = "AAAAAAAAAAAAAAAAAAAAAAA"
+let s78 = "AAAAAAAAAAAAAAAAAAAAAAAA"
+let t78 = "AAAAAAAAAAAAAAAAAAAAAAAA"
+let s79 = "AAAAAAAAAAAAAAAAAAAAAAAAA"
+let t79 = "AAAAAAAAAAAAAAAAAAAAAAAAA"
+let s80 = "AAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t80 = "AAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s81 = "AAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t81 = "AAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s82 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t82 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s83 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t83 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s84 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t84 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s85 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t85 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s86 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t86 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s87 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t87 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s88 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let t88 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+let s89 = "BBBBBBBBBBBBBBB"
+let t89 = "BBBBBBBBBBBBBBB"
+let s90 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
+let t90 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
+let s91 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
+let t91 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
+
+let tst06 s = match s with
+| "and" -> 0
+| "as" -> 1
+| "assert" -> 2
+| "begin" -> 3
+| "class" -> 4
+| "constraint" -> 5
+| "do" -> 6
+| "done" -> 7
+| "downto" -> 8
+| "else" -> 9
+| "end" -> 10
+| "exception" -> 11
+| "external" -> 12
+| "false" -> 13
+| "for" -> 14
+| "fun" -> 15
+| "function" -> 16
+| "functor" -> 17
+| "if" -> 18
+| "in" -> 19
+| "include" -> 20
+| "inherit" -> 21
+| "initializer" -> 22
+| "lazy" -> 23
+| "let" -> 24
+| "match" -> 25
+| "method" -> 26
+| "module" -> 27
+| "mutable" -> 28
+| "new" -> 29
+| "object" -> 30
+| "of" -> 31
+| "open" -> 32
+| "or" -> 33
+| "private" -> 34
+| "rec" -> 35
+| "sig" -> 36
+| "struct" -> 37
+| "then" -> 38
+| "to" -> 39
+| "true" -> 40
+| "try" -> 41
+| "type" -> 42
+| "val" -> 43
+| "virtual" -> 44
+| "when" -> 45
+| "while" -> 46
+| "with" -> 47
+| "mod" -> 48
+| "land" -> 49
+| "lor" -> 50
+| "lxor" -> 51
+| "lsl" -> 52
+| "lsr" -> 53
+| "asr" -> 54
+| "A" -> 55
+| "AA" -> 56
+| "AAA" -> 57
+| "AAAA" -> 58
+| "AAAAA" -> 59
+| "AAAAAA" -> 60
+| "AAAAAAA" -> 61
+| "AAAAAAAA" -> 62
+| "AAAAAAAAA" -> 63
+| "AAAAAAAAAA" -> 64
+| "AAAAAAAAAAA" -> 65
+| "AAAAAAAAAAAA" -> 66
+| "AAAAAAAAAAAAA" -> 67
+| "AAAAAAAAAAAAAA" -> 68
+| "AAAAAAAAAAAAAAA" -> 69
+| "AAAAAAAAAAAAAAAA" -> 70
+| "AAAAAAAAAAAAAAAAA" -> 71
+| "AAAAAAAAAAAAAAAAAA" -> 72
+| "AAAAAAAAAAAAAAAAAAA" -> 73
+| "AAAAAAAAAAAAAAAAAAAA" -> 74
+| "AAAAAAAAAAAAAAAAAAAAA" -> 75
+| "AAAAAAAAAAAAAAAAAAAAAA" -> 76
+| "AAAAAAAAAAAAAAAAAAAAAAA" -> 77
+| "AAAAAAAAAAAAAAAAAAAAAAAA" -> 78
+| "AAAAAAAAAAAAAAAAAAAAAAAAA" -> 79
+| "AAAAAAAAAAAAAAAAAAAAAAAAAA" -> 80
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 81
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 82
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 83
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 84
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 85
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 86
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 87
+| "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" -> 88
+| "BBBBBBBBBBBBBBB" -> 89
+| "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" -> 90
+| "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" -> 91
+| _ -> -1
+
+let () =
+ assert (tst06 s00 = 0) ;
+ assert (tst06 t00 = -1) ;
+ assert (tst06 s01 = 1) ;
+ assert (tst06 t01 = -1) ;
+ assert (tst06 s02 = 2) ;
+ assert (tst06 t02 = -1) ;
+ assert (tst06 s03 = 3) ;
+ assert (tst06 t03 = -1) ;
+ assert (tst06 s04 = 4) ;
+ assert (tst06 t04 = -1) ;
+ assert (tst06 s05 = 5) ;
+ assert (tst06 t05 = -1) ;
+ assert (tst06 s06 = 6) ;
+ assert (tst06 t06 = -1) ;
+ assert (tst06 s07 = 7) ;
+ assert (tst06 t07 = -1) ;
+ assert (tst06 s08 = 8) ;
+ assert (tst06 t08 = -1) ;
+ assert (tst06 s09 = 9) ;
+ assert (tst06 t09 = -1) ;
+ assert (tst06 s10 = 10) ;
+ assert (tst06 t10 = -1) ;
+ assert (tst06 s11 = 11) ;
+ assert (tst06 t11 = 11) ;
+ assert (tst06 s12 = 12) ;
+ assert (tst06 t12 = 12) ;
+ assert (tst06 s13 = 13) ;
+ assert (tst06 t13 = -1) ;
+ assert (tst06 s14 = 14) ;
+ assert (tst06 t14 = -1) ;
+ assert (tst06 s15 = 15) ;
+ assert (tst06 t15 = -1) ;
+ assert (tst06 s16 = 16) ;
+ assert (tst06 t16 = 16) ;
+ assert (tst06 s17 = 17) ;
+ assert (tst06 t17 = -1) ;
+ assert (tst06 s18 = 18) ;
+ assert (tst06 t18 = -1) ;
+ assert (tst06 s19 = 19) ;
+ assert (tst06 t19 = 19) ;
+ assert (tst06 s20 = 20) ;
+ assert (tst06 t20 = -1) ;
+ assert (tst06 s21 = 21) ;
+ assert (tst06 t21 = -1) ;
+ assert (tst06 s22 = 22) ;
+ assert (tst06 t22 = -1) ;
+ assert (tst06 s23 = 23) ;
+ assert (tst06 t23 = -1) ;
+ assert (tst06 s24 = 24) ;
+ assert (tst06 t24 = -1) ;
+ assert (tst06 s25 = 25) ;
+ assert (tst06 t25 = 25) ;
+ assert (tst06 s26 = 26) ;
+ assert (tst06 t26 = -1) ;
+ assert (tst06 s27 = 27) ;
+ assert (tst06 t27 = -1) ;
+ assert (tst06 s28 = 28) ;
+ assert (tst06 t28 = -1) ;
+ assert (tst06 s29 = 29) ;
+ assert (tst06 t29 = -1) ;
+ assert (tst06 s30 = 30) ;
+ assert (tst06 t30 = -1) ;
+ assert (tst06 s31 = 31) ;
+ assert (tst06 t31 = 31) ;
+ assert (tst06 s32 = 32) ;
+ assert (tst06 t32 = -1) ;
+ assert (tst06 s33 = 33) ;
+ assert (tst06 t33 = -1) ;
+ assert (tst06 s34 = 34) ;
+ assert (tst06 t34 = -1) ;
+ assert (tst06 s35 = 35) ;
+ assert (tst06 t35 = 35) ;
+ assert (tst06 s36 = 36) ;
+ assert (tst06 t36 = -1) ;
+ assert (tst06 s37 = 37) ;
+ assert (tst06 t37 = -1) ;
+ assert (tst06 s38 = 38) ;
+ assert (tst06 t38 = -1) ;
+ assert (tst06 s39 = 39) ;
+ assert (tst06 t39 = 39) ;
+ assert (tst06 s40 = 40) ;
+ assert (tst06 t40 = -1) ;
+ assert (tst06 s41 = 41) ;
+ assert (tst06 t41 = 41) ;
+ assert (tst06 s42 = 42) ;
+ assert (tst06 t42 = -1) ;
+ assert (tst06 s43 = 43) ;
+ assert (tst06 t43 = 43) ;
+ assert (tst06 s44 = 44) ;
+ assert (tst06 t44 = -1) ;
+ assert (tst06 s45 = 45) ;
+ assert (tst06 t45 = -1) ;
+ assert (tst06 s46 = 46) ;
+ assert (tst06 t46 = -1) ;
+ assert (tst06 s47 = 47) ;
+ assert (tst06 t47 = -1) ;
+ assert (tst06 s48 = 48) ;
+ assert (tst06 t48 = 48) ;
+ assert (tst06 s49 = 49) ;
+ assert (tst06 t49 = -1) ;
+ assert (tst06 s50 = 50) ;
+ assert (tst06 t50 = -1) ;
+ assert (tst06 s51 = 51) ;
+ assert (tst06 t51 = 51) ;
+ assert (tst06 s52 = 52) ;
+ assert (tst06 t52 = 52) ;
+ assert (tst06 s53 = 53) ;
+ assert (tst06 t53 = 53) ;
+ assert (tst06 s54 = 54) ;
+ assert (tst06 t54 = -1) ;
+ assert (tst06 s55 = 55) ;
+ assert (tst06 t55 = 55) ;
+ assert (tst06 s56 = 56) ;
+ assert (tst06 t56 = 56) ;
+ assert (tst06 s57 = 57) ;
+ assert (tst06 t57 = 57) ;
+ assert (tst06 s58 = 58) ;
+ assert (tst06 t58 = 58) ;
+ assert (tst06 s59 = 59) ;
+ assert (tst06 t59 = 59) ;
+ assert (tst06 s60 = 60) ;
+ assert (tst06 t60 = 60) ;
+ assert (tst06 s61 = 61) ;
+ assert (tst06 t61 = 61) ;
+ assert (tst06 s62 = 62) ;
+ assert (tst06 t62 = 62) ;
+ assert (tst06 s63 = 63) ;
+ assert (tst06 t63 = 63) ;
+ assert (tst06 s64 = 64) ;
+ assert (tst06 t64 = 64) ;
+ assert (tst06 s65 = 65) ;
+ assert (tst06 t65 = 65) ;
+ assert (tst06 s66 = 66) ;
+ assert (tst06 t66 = 66) ;
+ assert (tst06 s67 = 67) ;
+ assert (tst06 t67 = 67) ;
+ assert (tst06 s68 = 68) ;
+ assert (tst06 t68 = 68) ;
+ assert (tst06 s69 = 69) ;
+ assert (tst06 t69 = 69) ;
+ assert (tst06 s70 = 70) ;
+ assert (tst06 t70 = 70) ;
+ assert (tst06 s71 = 71) ;
+ assert (tst06 t71 = 71) ;
+ assert (tst06 s72 = 72) ;
+ assert (tst06 t72 = 72) ;
+ assert (tst06 s73 = 73) ;
+ assert (tst06 t73 = 73) ;
+ assert (tst06 s74 = 74) ;
+ assert (tst06 t74 = 74) ;
+ assert (tst06 s75 = 75) ;
+ assert (tst06 t75 = 75) ;
+ assert (tst06 s76 = 76) ;
+ assert (tst06 t76 = 76) ;
+ assert (tst06 s77 = 77) ;
+ assert (tst06 t77 = 77) ;
+ assert (tst06 s78 = 78) ;
+ assert (tst06 t78 = 78) ;
+ assert (tst06 s79 = 79) ;
+ assert (tst06 t79 = 79) ;
+ assert (tst06 s80 = 80) ;
+ assert (tst06 t80 = 80) ;
+ assert (tst06 s81 = 81) ;
+ assert (tst06 t81 = 81) ;
+ assert (tst06 s82 = 82) ;
+ assert (tst06 t82 = 82) ;
+ assert (tst06 s83 = 83) ;
+ assert (tst06 t83 = 83) ;
+ assert (tst06 s84 = 84) ;
+ assert (tst06 t84 = 84) ;
+ assert (tst06 s85 = 85) ;
+ assert (tst06 t85 = 85) ;
+ assert (tst06 s86 = 86) ;
+ assert (tst06 t86 = 86) ;
+ assert (tst06 s87 = 87) ;
+ assert (tst06 t87 = 87) ;
+ assert (tst06 s88 = 88) ;
+ assert (tst06 t88 = 88) ;
+ assert (tst06 s89 = 89) ;
+ assert (tst06 t89 = 89) ;
+ assert (tst06 s90 = 90) ;
+ assert (tst06 t90 = 90) ;
+ assert (tst06 s91 = 91) ;
+ assert (tst06 t91 = 91) ;
+ assert (tst06 "" = -1) ;
+ ()
diff --git a/testsuite/tests/basic/stringmatch.reference b/testsuite/tests/basic/stringmatch.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/basic/stringmatch.reference
diff --git a/testsuite/tests/basic/tailcalls.ml b/testsuite/tests/basic/tailcalls.ml
new file mode 100644
index 0000000000..4b33206ee3
--- /dev/null
+++ b/testsuite/tests/basic/tailcalls.ml
@@ -0,0 +1,53 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec tailcall4 a b c d =
+ if a < 0
+ then b
+ else tailcall4 (a-1) (b+1) (c+2) (d+3)
+
+let rec tailcall8 a b c d e f g h =
+ if a < 0
+ then b
+ else tailcall8 (a-1) (b+1) (c+2) (d+3) (e+4) (f+5) (g+6) (h+7)
+
+let rec tailcall16 a b c d e f g h i j k l m n o p =
+ if a < 0
+ then b
+ else tailcall16 (a-1) (b+1) (c+2) (d+3) (e+4) (f+5) (g+6) (h+7)
+ (i+8) (j+9) (k+10) (l+11) (m+12) (n+13) (o+14) (p+15)
+
+let indtailcall8 fn a b c d e f g h =
+ fn a b c d e f g h
+
+let indtailcall16 fn a b c d e f g h i j k l m n o p =
+ fn a b c d e f g h i j k l m n o p
+
+(* regression test for PR#6441: *)
+let rec tailcall16_value_closures a b c d e f g h i j k l m n o p =
+ if a < 0
+ then b
+ else tailcall16_value_closures
+ (a-1) (b+1) (c+2) (d+3) (e+4) (f+5) (g+6) (h+7)
+ (i+8) (j+9) (k+10) (l+11) (m+12) (n+13) (o+14) (p+15)
+and fs = [tailcall16_value_closures]
+
+let _ =
+ print_int (tailcall4 10000000 0 0 0); print_newline();
+ print_int (tailcall8 10000000 0 0 0 0 0 0 0); print_newline();
+ print_int (tailcall16 10000000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0);
+ print_newline();
+ print_int (indtailcall8 tailcall8 10 0 0 0 0 0 0 0); print_newline();
+ print_int (indtailcall16 tailcall16 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0);
+ print_newline();
+ print_int (tailcall16_value_closures 10000000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0);
+ print_newline()
diff --git a/testsuite/tests/basic/tailcalls.reference b/testsuite/tests/basic/tailcalls.reference
new file mode 100644
index 0000000000..c7117bc954
--- /dev/null
+++ b/testsuite/tests/basic/tailcalls.reference
@@ -0,0 +1,6 @@
+10000001
+10000001
+10000001
+11
+11
+10000001
diff --git a/testsuite/tests/callback/Makefile b/testsuite/tests/callback/Makefile
new file mode 100644
index 0000000000..d89c532635
--- /dev/null
+++ b/testsuite/tests/callback/Makefile
@@ -0,0 +1,59 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+CC=$(NATIVECC) -I $(CTOPDIR)/byterun
+COMPFLAGS=-I $(OTOPDIR)/otherlibs/unix
+LD_PATH=$(TOPDIR)/otherlibs/unix
+
+.PHONY: default
+default:
+ @case " $(OTHERLIBRARIES) " in \
+ *' unix '*) $(SET_LD_PATH) $(MAKE) run-byte; \
+ $(SET_LD_PATH) $(MAKE) run-opt;; \
+ esac
+
+.PHONY: common
+common:
+ @$(CC) -c callbackprim.c
+
+.PHONY: run-byte
+run-byte: common
+ @printf " ... testing 'bytecode':"
+ @$(OCAMLC) $(COMPFLAGS) -c tcallback.ml
+ @$(OCAMLC) $(COMPFLAGS) -o ./program$(EXE) -custom unix.cma \
+ callbackprim.$(O) tcallback.cmo
+ @./program$(EXE) >bytecode.result
+ @$(DIFF) reference bytecode.result \
+ && echo " => passed" || echo " => failed"
+
+.PHONY: run-opt
+run-opt: common
+ @if $(BYTECODE_ONLY); then : ; else \
+ printf " ... testing 'native':"; \
+ $(OCAMLOPT) $(COMPFLAGS) -c tcallback.ml; \
+ $(OCAMLOPT) $(COMPFLAGS) -o ./program$(EXE) unix.cmxa \
+ callbackprim.$(O) tcallback.cmx; \
+ ./program$(EXE) >native.result; \
+ $(DIFF) reference native.result \
+ && echo " => passed" || echo " => failed"; \
+ fi
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result ./program$(EXE)
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/callback/callbackprim.c b/testsuite/tests/callback/callbackprim.c
new file mode 100644
index 0000000000..71a123d18e
--- /dev/null
+++ b/testsuite/tests/callback/callbackprim.c
@@ -0,0 +1,66 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1995 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+#include "caml/callback.h"
+
+value mycallback1(value fun, value arg)
+{
+ value res;
+ res = callback(fun, arg);
+ return res;
+}
+
+value mycallback2(value fun, value arg1, value arg2)
+{
+ value res;
+ res = callback2(fun, arg1, arg2);
+ return res;
+}
+
+value mycallback3(value fun, value arg1, value arg2, value arg3)
+{
+ value res;
+ res = callback3(fun, arg1, arg2, arg3);
+ return res;
+}
+
+value mycallback4(value fun, value arg1, value arg2, value arg3, value arg4)
+{
+ value args[4];
+ value res;
+ args[0] = arg1;
+ args[1] = arg2;
+ args[2] = arg3;
+ args[3] = arg4;
+ res = callbackN(fun, 4, args);
+ return res;
+}
+
+value mypushroot(value v, value fun, value arg)
+{
+ Begin_root(v)
+ callback(fun, arg);
+ End_roots();
+ return v;
+}
+
+value mycamlparam (value v, value fun, value arg)
+{
+ CAMLparam3 (v, fun, arg);
+ CAMLlocal2 (x, y);
+ x = v;
+ y = callback (fun, arg);
+ v = x;
+ CAMLreturn (v);
+}
diff --git a/testsuite/tests/callback/reference b/testsuite/tests/callback/reference
new file mode 100644
index 0000000000..b35993aa2c
--- /dev/null
+++ b/testsuite/tests/callback/reference
@@ -0,0 +1,8 @@
+7
+7
+7
+7
+7
+aaaaa
+aaaaa
+bbbbb
diff --git a/testsuite/tests/callback/tcallback.ml b/testsuite/tests/callback/tcallback.ml
new file mode 100644
index 0000000000..69cae5c2fc
--- /dev/null
+++ b/testsuite/tests/callback/tcallback.ml
@@ -0,0 +1,81 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1995 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+external mycallback1 : ('a -> 'b) -> 'a -> 'b = "mycallback1"
+external mycallback2 : ('a -> 'b -> 'c) -> 'a -> 'b -> 'c = "mycallback2"
+external mycallback3 : ('a -> 'b -> 'c -> 'd) -> 'a -> 'b -> 'c -> 'd
+ = "mycallback3"
+external mycallback4 :
+ ('a -> 'b -> 'c -> 'd -> 'e) -> 'a -> 'b -> 'c -> 'd -> 'e = "mycallback4"
+
+let rec tak (x, y, z as _tuple) =
+ if x > y then tak(tak (x-1, y, z), tak (y-1, z, x), tak (z-1, x, y))
+ else z
+
+let tak2 x (y, z) = tak (x, y, z)
+
+let tak3 x y z = tak (x, y, z)
+
+let tak4 x y z u = tak (x, y, z + u)
+
+let raise_exit () = (raise Exit : unit)
+
+let trapexit () =
+ begin try
+ mycallback1 raise_exit ()
+ with Exit ->
+ ()
+ end;
+ tak (18, 12, 6)
+
+external mypushroot : 'a -> ('b -> 'c) -> 'b -> 'a = "mypushroot"
+external mycamlparam : 'a -> ('b -> 'c) -> 'b -> 'a = "mycamlparam"
+
+let tripwire f =
+ let s = String.make 5 'a' in
+ f s trapexit ()
+
+(* Test callbacks performed to handle signals *)
+
+let sighandler signo =
+(*
+ print_string "Got signal, triggering garbage collection...";
+ print_newline();
+*)
+ (* Thoroughly wipe the minor heap *)
+ ignore (tak (18, 12, 6))
+
+external unix_getpid : unit -> int = "unix_getpid" "noalloc"
+external unix_kill : int -> int -> unit = "unix_kill" "noalloc"
+
+let callbacksig () =
+ let pid = unix_getpid() in
+ (* Allocate a block in the minor heap *)
+ let s = String.make 5 'b' in
+ (* Send a signal to self. We want s to remain in a register and
+ not be spilled on the stack, hence we declare unix_kill
+ "noalloc". *)
+ unix_kill pid Sys.sigusr1;
+ (* Allocate some more so that the signal will be tested *)
+ let u = (s, s) in
+ fst u
+
+let _ =
+ print_int(mycallback1 tak (18, 12, 6)); print_newline();
+ print_int(mycallback2 tak2 18 (12, 6)); print_newline();
+ print_int(mycallback3 tak3 18 12 6); print_newline();
+ print_int(mycallback4 tak4 18 12 3 3); print_newline();
+ print_int(trapexit ()); print_newline();
+ print_string(tripwire mypushroot); print_newline();
+ print_string(tripwire mycamlparam); print_newline();
+ Sys.set_signal Sys.sigusr1 (Sys.Signal_handle sighandler);
+ print_string(callbacksig ()); print_newline()
diff --git a/testsuite/tests/embedded/.ignore b/testsuite/tests/embedded/.ignore
new file mode 100644
index 0000000000..97d78c3d3c
--- /dev/null
+++ b/testsuite/tests/embedded/.ignore
@@ -0,0 +1 @@
+caml
diff --git a/testsuite/tests/embedded/Makefile b/testsuite/tests/embedded/Makefile
new file mode 100644
index 0000000000..088b021656
--- /dev/null
+++ b/testsuite/tests/embedded/Makefile
@@ -0,0 +1,41 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+.PHONY: default
+default:
+ $(MAKE) compile
+ $(MAKE) run
+
+.PHONY: compile
+compile:
+ @$(OCAMLC) -ccopt -I -ccopt $(CTOPDIR)/byterun cmstub.c
+ @$(OCAMLC) -ccopt -I -ccopt $(CTOPDIR)/byterun cmmain.c
+ @$(OCAMLC) -c cmcaml.ml
+ @$(OCAMLC) -custom -o program cmstub.$(O) cmcaml.cmo cmmain.$(O)
+
+.PHONY: run
+run:
+ @printf " ... testing 'cmmain':"
+ @./program >program.result
+ @$(DIFF) program.reference program.result >/dev/null \
+ && echo " => passed" || echo " => failed"
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result program
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/embedded/cmcaml.ml b/testsuite/tests/embedded/cmcaml.ml
new file mode 100644
index 0000000000..b3e9b7e29d
--- /dev/null
+++ b/testsuite/tests/embedded/cmcaml.ml
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* OCaml part of the code *)
+
+let rec fib n =
+ if n < 2 then 1 else fib(n-1) + fib(n-2)
+
+let format_result n =
+ let r = "Result = " ^ string_of_int n in
+ (* Allocate gratuitously to test GC *)
+ for i = 1 to 1500 do ignore (Bytes.create 256) done;
+ r
+
+(* Registration *)
+
+let _ =
+ Callback.register "fib" fib;
+ Callback.register "format_result" format_result
diff --git a/testsuite/tests/embedded/cmmain.c b/testsuite/tests/embedded/cmmain.c
new file mode 100644
index 0000000000..04ed07286a
--- /dev/null
+++ b/testsuite/tests/embedded/cmmain.c
@@ -0,0 +1,35 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* Main program -- in C */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <caml/callback.h>
+
+extern int fib(int n);
+extern char * format_result(int n);
+
+int main(int argc, char ** argv)
+{
+ printf("Initializing OCaml code...\n");
+#ifdef NO_BYTECODE_FILE
+ caml_startup(argv);
+#else
+ caml_main(argv);
+#endif
+ printf("Back in C code...\n");
+ printf("Computing fib(20)...\n");
+ printf("%s\n", format_result(fib(20)));
+ return 0;
+}
diff --git a/testsuite/tests/embedded/cmstub.c b/testsuite/tests/embedded/cmstub.c
new file mode 100644
index 0000000000..4eea82a6f3
--- /dev/null
+++ b/testsuite/tests/embedded/cmstub.c
@@ -0,0 +1,30 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+#include <string.h>
+#include <caml/mlvalues.h>
+#include <caml/callback.h>
+
+/* Functions callable directly from C */
+
+int fib(int n)
+{
+ value * fib_closure = caml_named_value("fib");
+ return Int_val(callback(*fib_closure, Val_int(n)));
+}
+
+char * format_result(int n)
+{
+ value * format_result_closure = caml_named_value("format_result");
+ return strdup(String_val(callback(*format_result_closure, Val_int(n))));
+}
diff --git a/testsuite/tests/embedded/program.reference b/testsuite/tests/embedded/program.reference
new file mode 100644
index 0000000000..4f27810ca9
--- /dev/null
+++ b/testsuite/tests/embedded/program.reference
@@ -0,0 +1,4 @@
+Initializing OCaml code...
+Back in C code...
+Computing fib(20)...
+Result = 10946
diff --git a/testsuite/tests/exotic-syntax/Makefile b/testsuite/tests/exotic-syntax/Makefile
new file mode 100644
index 0000000000..38acec51cb
--- /dev/null
+++ b/testsuite/tests/exotic-syntax/Makefile
@@ -0,0 +1,17 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MAIN_MODULE=exotic
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/exotic-syntax/exotic.ml b/testsuite/tests/exotic-syntax/exotic.ml
new file mode 100644
index 0000000000..873bf33932
--- /dev/null
+++ b/testsuite/tests/exotic-syntax/exotic.ml
@@ -0,0 +1,157 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Exotic OCaml syntax constructs found in the manual that are not *)
+(* used in the source of the OCaml distribution (even in the tests). *)
+
+(* Spaces between the parts of the ?label: token in a typexpr.
+ (used in bin-prot) *)
+type t1 = ? label : int -> int -> int;;
+
+(* Lazy in a pattern. (used in advi) *)
+function lazy y -> y;;
+
+(* Spaces between the parts of the ?label: token in a class-type. *)
+class c1 =
+ (fun ?label:x y -> object end : ? label : int -> int -> object end)
+;;
+
+(* type-class annotation in class-expr *)
+class c2 = (object end : object end);;
+
+(* virtual object field *)
+class virtual c3 = object val virtual x : int end;;
+class virtual c4 = object val mutable virtual x : int end;;
+
+(* abstract module type in a signature *)
+module type T = sig
+ module type U
+end;;
+
+(* associativity rules for patterns *)
+function Some Some x -> x | _ -> 0;;
+function Some `Tag x -> x | _ -> 0;;
+function `Tag Some x -> x | _ -> 0;;
+function `Tag `Tag x -> x | _ -> 0;;
+
+(* negative int32, int64, nativeint constants in patterns *)
+function -1l -> () | _ -> ();;
+function -1L -> () | _ -> ();;
+function -1n -> () | _ -> ();;
+
+(* surprising places where you can use an operator as a variable name *)
+function (+) -> (+);;
+function _ as (+) -> (+);;
+for (+) = 0 to 1 do () done;;
+
+(* access a class-type through an extended-module-path *)
+module F (X : sig end) = struct
+ class type t = object end
+end;;
+module M1 = struct end;;
+class type u = F(M1).t;;
+
+(* conjunctive constraints on tags (used by the compiler to print some
+ inferred types) *)
+type 'a t2 = [< `A of int & int & int ] as 'a;;
+
+(* same for a parameterless tag (triggers a very strange error message) *)
+(*type ('a, 'b) t3 = [< `A of & 'b ] as 'a;;*)
+
+(* negative float constant in a pattern *)
+function -1.0 -> 1 | _ -> 2;;
+
+(* combining language extensions (sec. 7.13 and 7.17) *)
+class c5 = object method f = 1 end;;
+object
+ inherit c5
+ method! f : type t . int = 2
+end;;
+
+(* private polymorphic method with local type *)
+object method private f : type t . int = 1 end;;
+
+
+(* More exotic: not even found in the manual (up to version 4.00),
+ but used in some programs found in the wild.
+*)
+
+(* local functor *)
+let module M (M1 : sig end) = struct end in ();;
+
+(* let-binding with a type coercion *)
+let x :> int = 1;;
+let x : int :> int = 1;;
+
+(* "begin end" as an alias for "()" *)
+begin end;;
+
+(* putting "virtual" before "mutable" or "private" *)
+class type virtual ct = object
+ val mutable virtual x : int
+ val virtual mutable y : int
+ method private virtual f : int
+ method virtual private g : int
+end;;
+class virtual c = object
+ val mutable virtual x : int
+ val virtual mutable y : int
+ method private virtual f : int
+ method virtual private g : int
+end;;
+
+(* Double-semicolon at the beginning of a module body [ocp-indent] *)
+module M2 = struct ;; end;;
+
+
+(**********************
+
+(* Most exotic: not found in the manual (up to 4.00) and not used
+ deliberately by anyone, but still implemented by the compiler. *)
+
+(* whitespace inside val!, method!, inherit! [found in ocamlspot] *)
+object
+ val x = 1
+ val ! x = 2
+ method m = 1
+ method ! m = 2
+ inherit ! object val x = 3 end
+end;;
+
+(* Using () as a constructor name [found in gettext] *)
+type t = ();;
+let x : t = ();;
+
+(* Using :: as a constructor name *)
+type t = :: of int * int;;
+
+(* Prefix syntax for :: in expressions *)
+(::) (1, 1);;
+
+(* Prefix syntax for :: in patterns *)
+function (::) (_, _) -> 1;;
+
+(* Unary plus in expressions (ints and float) *)
++1;;
++1l;;
++1L;;
++1n;;
++1.0;;
+
+(* Unary plus in patterns (ints and floats) *)
+function +1 -> ();;
+function +1l -> ();;
+function +1L -> ();;
+function +1n -> ();;
+function +1.0 -> ();;
+
+**********************)
diff --git a/testsuite/tests/exotic-syntax/exotic.reference b/testsuite/tests/exotic-syntax/exotic.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/exotic-syntax/exotic.reference
diff --git a/testsuite/tests/float-unboxing/Makefile b/testsuite/tests/float-unboxing/Makefile
new file mode 100644
index 0000000000..6852411858
--- /dev/null
+++ b/testsuite/tests/float-unboxing/Makefile
@@ -0,0 +1,7 @@
+BASEDIR=../..
+MODULES=
+MAIN_MODULE=float_subst_boxed_number
+ADD_OPTCOMPFLAGS=-inline 20
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/float-unboxing/float_subst_boxed_number.ml b/testsuite/tests/float-unboxing/float_subst_boxed_number.ml
new file mode 100644
index 0000000000..ce175ceb6b
--- /dev/null
+++ b/testsuite/tests/float-unboxing/float_subst_boxed_number.ml
@@ -0,0 +1,52 @@
+module PR_6686 = struct
+ type t =
+ | A of float
+ | B of (int * int)
+
+ let rec foo = function
+ | A x -> x
+ | B (x, y) -> float x +. float y
+
+ let (_ : float) = foo (A 4.)
+end
+
+module PR_6770 = struct
+ type t =
+ | Constant of float
+ | Exponent of (float * float)
+
+ let to_string = function
+ | Exponent (_b, _e) ->
+ ignore _b;
+ ignore _e;
+ ""
+ | Constant _ -> ""
+
+ let _ = to_string (Constant 4.)
+end
+
+
+module GPR_109 = struct
+
+ let f () =
+ let r = ref 0. in
+ for i = 1 to 1000 do
+ r := !r +. float i
+ done;
+ !r
+
+ let test () =
+ let a0 = Gc.allocated_bytes () in
+ let a1 = Gc.allocated_bytes () in
+ let _x = f () in
+ let a2 = Gc.allocated_bytes () in
+ let alloc = (a2 -. 2. *. a1 +. a0) in
+ assert(alloc < 100.)
+
+ let () =
+ (* is there a better to test whether we run in native code? *)
+ match Filename.basename Sys.argv.(0) with
+ | "program.byte" | "program.byte.exe" -> ()
+ | "program.native" | "program.native.exe" -> test ()
+ | _ -> assert false
+end
diff --git a/testsuite/tests/float-unboxing/float_subst_boxed_number.reference b/testsuite/tests/float-unboxing/float_subst_boxed_number.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/float-unboxing/float_subst_boxed_number.reference
diff --git a/testsuite/tests/formats-transition/Makefile b/testsuite/tests/formats-transition/Makefile
new file mode 100644
index 0000000000..9625a3fbc3
--- /dev/null
+++ b/testsuite/tests/formats-transition/Makefile
@@ -0,0 +1,3 @@
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/formats-transition/deprecated_unsigned_printers.ml b/testsuite/tests/formats-transition/deprecated_unsigned_printers.ml
new file mode 100644
index 0000000000..3127d773af
--- /dev/null
+++ b/testsuite/tests/formats-transition/deprecated_unsigned_printers.ml
@@ -0,0 +1,22 @@
+(* %n, %l, %N and %L have a scanf-specific semantics, but are supposed
+ to be interpreted by Printf and Format as %u, despite this
+ interpretation being mildly deprecated *)
+
+let test format = (Printf.sprintf format (-3) : string)
+;;
+
+let () = Printf.printf "%%n: %B\n"
+ (test "%n" = test "%u")
+;;
+
+let () = Printf.printf "%%l: %B\n"
+ (test "%l" = test "%u")
+;;
+
+let () = Printf.printf "%%N: %B\n"
+ (test "%N" = test "%u")
+;;
+
+let () = Printf.printf "%%L: %B\n"
+ (test "%L" = test "%u")
+;;
diff --git a/testsuite/tests/formats-transition/deprecated_unsigned_printers.ml.reference b/testsuite/tests/formats-transition/deprecated_unsigned_printers.ml.reference
new file mode 100644
index 0000000000..0afeaa2be1
--- /dev/null
+++ b/testsuite/tests/formats-transition/deprecated_unsigned_printers.ml.reference
@@ -0,0 +1,7 @@
+
+# * * val test : (int -> string, unit, string) format -> string = <fun>
+# %n: true
+# %l: true
+# %N: true
+# %L: true
+#
diff --git a/testsuite/tests/formats-transition/ignored_scan_counters.ml b/testsuite/tests/formats-transition/ignored_scan_counters.ml
new file mode 100644
index 0000000000..307f8a59cf
--- /dev/null
+++ b/testsuite/tests/formats-transition/ignored_scan_counters.ml
@@ -0,0 +1,30 @@
+(* Benoit's patch did not support %_[nlNL]; test their behavior *)
+
+(* not supported by Printf or Format: fails at runtime *)
+let () = Printf.printf "%_n"
+;;
+let () = Printf.printf "%_N"
+;;
+let () = Printf.printf "%_l"
+;;
+let () = Printf.printf "%_L"
+;;
+
+let () = Format.printf "%_n"
+;;
+let () = Format.printf "%_N"
+;;
+let () = Format.printf "%_l"
+;;
+let () = Format.printf "%_L"
+;;
+
+(* identity for Scanf *)
+let () = print_endline (Scanf.sscanf "" "%_n" "Hello World!")
+;;
+let () = print_endline (Scanf.sscanf "" "%_N" "Hello World!")
+;;
+let () = print_endline (Scanf.sscanf "" "%_l" "Hello World!")
+;;
+let () = print_endline (Scanf.sscanf "" "%_L" "Hello World!")
+;;
diff --git a/testsuite/tests/formats-transition/ignored_scan_counters.ml.reference b/testsuite/tests/formats-transition/ignored_scan_counters.ml.reference
new file mode 100644
index 0000000000..6d8d098b5a
--- /dev/null
+++ b/testsuite/tests/formats-transition/ignored_scan_counters.ml.reference
@@ -0,0 +1,14 @@
+
+# Exception: Invalid_argument "Printf: bad conversion %_".
+# Exception: Invalid_argument "Printf: bad conversion %_".
+# Exception: Invalid_argument "Printf: bad conversion %_".
+# Exception: Invalid_argument "Printf: bad conversion %_".
+# Exception: Invalid_argument "Printf: bad conversion %_".
+# Exception: Invalid_argument "Printf: bad conversion %_".
+# Exception: Invalid_argument "Printf: bad conversion %_".
+# Exception: Invalid_argument "Printf: bad conversion %_".
+# Hello World!
+# Hello World!
+# Hello World!
+# Hello World!
+#
diff --git a/testsuite/tests/formats-transition/legacy_incompatible_flags.ml b/testsuite/tests/formats-transition/legacy_incompatible_flags.ml
new file mode 100644
index 0000000000..53cf5c26c7
--- /dev/null
+++ b/testsuite/tests/formats-transition/legacy_incompatible_flags.ml
@@ -0,0 +1,20 @@
+(* the legacy parser ignores flags on formatters on which they make no
+ sense *)
+
+let () = Printf.printf "%+s\n" "toto"
+;;
+let () = Printf.printf "%#s\n" "toto"
+;;
+let () = Printf.printf "% s\n" "toto"
+;;
+let () = Printf.printf "%03s\n" "toto"
+;;
+let () = Printf.printf "%03S\n" "toto"
+;;
+let () = Printf.printf "%.3s\n" "toto"
+;;
+
+(* it still fails on flags used with ignored formats (%_d, etc.),
+ but it's unclear how to test that in a backward-compatible way,
+ if we accept that the error message may have changed
+*)
diff --git a/testsuite/tests/formats-transition/legacy_unfinished_modifiers.ml b/testsuite/tests/formats-transition/legacy_unfinished_modifiers.ml
new file mode 100644
index 0000000000..16eca40c17
--- /dev/null
+++ b/testsuite/tests/formats-transition/legacy_unfinished_modifiers.ml
@@ -0,0 +1,18 @@
+(* test whether padding modifiers are accepted without any padding
+ size
+
+ the precision modifier is accepted without precision setting, but it
+ defaults to 0, which is not the same thing as not having precision:
+ %.0f 3.5 => 3
+ %.f 3.5 => 3
+ %f 3.5 => 3.5
+*)
+
+let () = Printf.printf "%0d\n" 3
+;;
+let () = Printf.printf "%-d\n" 3
+;;
+let () = Printf.printf "%.d\n" 3
+;;
+let () = Printf.printf "%.f\n" 3.
+;;
diff --git a/testsuite/tests/formats-transition/legacy_unfinished_modifiers.ml.reference b/testsuite/tests/formats-transition/legacy_unfinished_modifiers.ml.reference
new file mode 100644
index 0000000000..81c05c0dd5
--- /dev/null
+++ b/testsuite/tests/formats-transition/legacy_unfinished_modifiers.ml.reference
@@ -0,0 +1,6 @@
+
+# * * * * * * * * 3
+# 3
+# 3
+# 3
+#
diff --git a/testsuite/tests/gc-roots/Makefile b/testsuite/tests/gc-roots/Makefile
new file mode 100644
index 0000000000..a10895381f
--- /dev/null
+++ b/testsuite/tests/gc-roots/Makefile
@@ -0,0 +1,20 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=globroots
+C_FILES=globrootsprim
+ADD_COMPFLAGS=-w a
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/gc-roots/globroots.ml b/testsuite/tests/gc-roots/globroots.ml
new file mode 100644
index 0000000000..029bc900b4
--- /dev/null
+++ b/testsuite/tests/gc-roots/globroots.ml
@@ -0,0 +1,92 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+module type GLOBREF = sig
+ type t
+ val register: string -> t
+ val get: t -> string
+ val set: t -> string -> unit
+ val remove: t -> unit
+end
+
+module Classic : GLOBREF = struct
+ type t
+ external register: string -> t = "gb_classic_register"
+ external get: t -> string = "gb_get"
+ external set: t -> string -> unit = "gb_classic_set"
+ external remove: t -> unit = "gb_classic_remove"
+end
+
+module Generational : GLOBREF = struct
+ type t
+ external register: string -> t = "gb_generational_register"
+ external get: t -> string = "gb_get"
+ external set: t -> string -> unit = "gb_generational_set"
+ external remove: t -> unit = "gb_generational_remove"
+end
+
+module Test(G: GLOBREF) = struct
+
+ let size = 1024
+
+ let vals = Array.init size string_of_int
+
+ let a = Array.init size (fun i -> G.register (string_of_int i))
+
+ let check () =
+ for i = 0 to size - 1 do
+ if G.get a.(i) <> vals.(i) then begin
+ print_string "Error on "; print_int i; print_string ": ";
+ print_string (String.escaped (G.get a.(i))); print_newline()
+ end
+ done
+
+ let change () =
+ match Random.int 37 with
+ | 0 ->
+ Gc.full_major()
+ | 1|2|3|4 ->
+ Gc.minor()
+ | 5|6|7|8|9|10|11|12 -> (* update with young value *)
+ let i = Random.int size in
+ G.set a.(i) (string_of_int i)
+ | 13|14|15|16|17|18|19|20 -> (* update with old value *)
+ let i = Random.int size in
+ G.set a.(i) vals.(i)
+ | 21|22|23|24|25|26|27|28 -> (* re-register young value *)
+ let i = Random.int size in
+ G.remove a.(i);
+ a.(i) <- G.register (string_of_int i)
+ | (*29|30|31|32|33|34|35|36*) _ -> (* re-register old value *)
+ let i = Random.int size in
+ G.remove a.(i);
+ a.(i) <- G.register vals.(i)
+
+ let test n =
+ for i = 1 to n do
+ change();
+ print_string "."; flush stdout
+ done
+end
+
+module TestClassic = Test(Classic)
+module TestGenerational = Test(Generational)
+
+let _ =
+ let n =
+ if Array.length Sys.argv < 2 then 10000 else int_of_string Sys.argv.(1) in
+ print_string "Non-generational API\n";
+ TestClassic.test n;
+ print_newline();
+ print_string "Generational API\n";
+ TestGenerational.test n;
+ print_newline()
diff --git a/testsuite/tests/gc-roots/globroots.reference b/testsuite/tests/gc-roots/globroots.reference
new file mode 100644
index 0000000000..aae90b2230
--- /dev/null
+++ b/testsuite/tests/gc-roots/globroots.reference
@@ -0,0 +1,4 @@
+Non-generational API
+................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
+Generational API
+................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
diff --git a/testsuite/tests/gc-roots/globrootsprim.c b/testsuite/tests/gc-roots/globrootsprim.c
new file mode 100644
index 0000000000..5c540acf55
--- /dev/null
+++ b/testsuite/tests/gc-roots/globrootsprim.c
@@ -0,0 +1,71 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the GNU Library General Public License, with */
+/* the special exception on linking described in file ../LICENSE. */
+/* */
+/***********************************************************************/
+
+/* For testing global root registration */
+
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+#include "caml/alloc.h"
+#include "caml/gc.h"
+
+struct block { value header; value v; };
+
+#define Block_val(v) ((struct block*) &((value*) v)[-1])
+#define Val_block(b) ((value) &((b)->v))
+
+value gb_get(value vblock)
+{
+ return Block_val(vblock)->v;
+}
+
+value gb_classic_register(value v)
+{
+ struct block * b = caml_stat_alloc(sizeof(struct block));
+ b->header = Make_header(1, 0, Caml_black);
+ b->v = v;
+ caml_register_global_root(&(b->v));
+ return Val_block(b);
+}
+
+value gb_classic_set(value vblock, value newval)
+{
+ Block_val(vblock)->v = newval;
+ return Val_unit;
+}
+
+value gb_classic_remove(value vblock)
+{
+ caml_remove_global_root(&(Block_val(vblock)->v));
+ return Val_unit;
+}
+
+value gb_generational_register(value v)
+{
+ struct block * b = caml_stat_alloc(sizeof(struct block));
+ b->header = Make_header(1, 0, Caml_black);
+ b->v = v;
+ caml_register_generational_global_root(&(b->v));
+ return Val_block(b);
+}
+
+value gb_generational_set(value vblock, value newval)
+{
+ caml_modify_generational_global_root(&(Block_val(vblock)->v), newval);
+ return Val_unit;
+}
+
+value gb_generational_remove(value vblock)
+{
+ caml_remove_generational_global_root(&(Block_val(vblock)->v));
+ return Val_unit;
+}
diff --git a/testsuite/tests/int64-unboxing/Makefile b/testsuite/tests/int64-unboxing/Makefile
new file mode 100644
index 0000000000..cdf41c09d5
--- /dev/null
+++ b/testsuite/tests/int64-unboxing/Makefile
@@ -0,0 +1,21 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Jeremie Dimino, Jane Street Europe #
+# #
+# Copyright 2015 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=
+MAIN_MODULE=test
+C_FILES=stubs
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
+
+NATIVECODE_ONLY=true
diff --git a/testsuite/tests/int64-unboxing/stubs.c b/testsuite/tests/int64-unboxing/stubs.c
new file mode 100644
index 0000000000..61b753039c
--- /dev/null
+++ b/testsuite/tests/int64-unboxing/stubs.c
@@ -0,0 +1,22 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Jeremie Dimino, Jane Street Europe */
+/* */
+/* Copyright 2015 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+
+int64_t test_int64_add(int64_t x, int64_t y) { return (x + y); }
+int64_t test_int64_sub(int64_t x, int64_t y) { return (x - y); }
+int64_t test_int64_mul(int64_t x, int64_t y) { return (x * y); }
+
+value test_ignore_int64(int64_t x)
+{
+ return Val_unit;
+}
diff --git a/testsuite/tests/int64-unboxing/test.ml b/testsuite/tests/int64-unboxing/test.ml
new file mode 100644
index 0000000000..e0af54ca7b
--- /dev/null
+++ b/testsuite/tests/int64-unboxing/test.ml
@@ -0,0 +1,37 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jeremie Dimino, Jane Street Europe *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+external ( + ) : (int64 [@unboxed]) -> (int64 [@unboxed]) -> (int64 [@unboxed])
+ = "" "noalloc" "test_int64_add"
+external ( - ) : (int64 [@unboxed]) -> (int64 [@unboxed]) -> (int64 [@unboxed])
+ = "" "noalloc" "test_int64_sub"
+external ( * ) : (int64 [@unboxed]) -> (int64 [@unboxed]) -> (int64 [@unboxed])
+ = "" "noalloc" "test_int64_mul"
+
+external ignore_int64 :
+ (int64 [@unboxed]) -> unit = "" "noalloc" "test_ignore_int64"
+
+let f () =
+ let r = ref 1L in
+ for i = 0 to 100000 do
+ let n = !r + !r in
+ r := n * n
+ done;
+ ignore_int64 !r
+
+let () =
+ let a0 = Gc.allocated_bytes () in
+ let a1 = Gc.allocated_bytes () in
+ let _x = f () in
+ let a2 = Gc.allocated_bytes () in
+ let alloc = (a2 -. 2. *. a1 +. a0) in
+ assert(alloc = 0.)
diff --git a/testsuite/tests/int64-unboxing/test.reference b/testsuite/tests/int64-unboxing/test.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/int64-unboxing/test.reference
diff --git a/testsuite/tests/letrec/Makefile b/testsuite/tests/letrec/Makefile
new file mode 100644
index 0000000000..6e8d01ff87
--- /dev/null
+++ b/testsuite/tests/letrec/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/letrec/backreferences.ml b/testsuite/tests/letrec/backreferences.ml
new file mode 100644
index 0000000000..2fdf14ea77
--- /dev/null
+++ b/testsuite/tests/letrec/backreferences.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* testing backreferences; some compilation scheme may handle
+ differently recursive references to a mutually-recursive RHS
+ depending on whether it is before or after in the bindings list *)
+type t = { x : t; y : t; z : t }
+
+let test =
+ let rec x = { x; y; z }
+ and y = { x; y; z }
+ and z = { x; y; z }
+ in
+ List.iter (fun (f, t_ref) ->
+ List.iter (fun t -> assert (f t == t_ref)) [x; y; z]
+ )
+ [
+ (fun t -> t.x), x;
+ (fun t -> t.y), y;
+ (fun t -> t.z), z;
+ ]
diff --git a/testsuite/tests/letrec/backreferences.reference b/testsuite/tests/letrec/backreferences.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/letrec/backreferences.reference
diff --git a/testsuite/tests/letrec/class_1.ml b/testsuite/tests/letrec/class_1.ml
new file mode 100644
index 0000000000..93bcc807bc
--- /dev/null
+++ b/testsuite/tests/letrec/class_1.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* class expression are compiled to recursive bindings *)
+class test =
+object
+ method x = 1
+end
diff --git a/testsuite/tests/letrec/class_1.reference b/testsuite/tests/letrec/class_1.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/letrec/class_1.reference
diff --git a/testsuite/tests/letrec/class_2.ml b/testsuite/tests/letrec/class_2.ml
new file mode 100644
index 0000000000..19d03a4391
--- /dev/null
+++ b/testsuite/tests/letrec/class_2.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* class expressions may also contain local recursive bindings *)
+class test =
+ let rec f = print_endline "f"; fun x -> g x
+ and g = print_endline "g"; fun x -> f x in
+object
+ method f : 'a 'b. 'a -> 'b = f
+ method g : 'a 'b. 'a -> 'b = g
+end
diff --git a/testsuite/tests/letrec/class_2.reference b/testsuite/tests/letrec/class_2.reference
new file mode 100644
index 0000000000..ab713757f4
--- /dev/null
+++ b/testsuite/tests/letrec/class_2.reference
@@ -0,0 +1,2 @@
+f
+g
diff --git a/testsuite/tests/letrec/evaluation_order_1.ml b/testsuite/tests/letrec/evaluation_order_1.ml
new file mode 100644
index 0000000000..2cd5ac5621
--- /dev/null
+++ b/testsuite/tests/letrec/evaluation_order_1.ml
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* test evaluation order
+
+ 'y' is translated into a constant, and is therefore considered
+ non-recursive. With the current letrec compilation method,
+ it should be evaluated before x and z.
+*)
+type tree = Tree of tree list
+
+let test =
+ let rec x = (print_endline "x"; Tree [y; z])
+ and y = (print_endline "y"; Tree [])
+ and z = (print_endline "z"; Tree [x])
+ in
+ match (x, y, z) with
+ | (Tree [y1; z1], Tree[], Tree[x1]) ->
+ assert (y1 == y);
+ assert (z1 == z);
+ assert (x1 == x)
+ | _ ->
+ assert false
diff --git a/testsuite/tests/letrec/evaluation_order_1.reference b/testsuite/tests/letrec/evaluation_order_1.reference
new file mode 100644
index 0000000000..f471662b7d
--- /dev/null
+++ b/testsuite/tests/letrec/evaluation_order_1.reference
@@ -0,0 +1,3 @@
+y
+x
+z
diff --git a/testsuite/tests/letrec/evaluation_order_2.ml b/testsuite/tests/letrec/evaluation_order_2.ml
new file mode 100644
index 0000000000..54a8b129b9
--- /dev/null
+++ b/testsuite/tests/letrec/evaluation_order_2.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A variant of evaluation_order_1.ml where the side-effects
+ are inside the blocks. Note that this changes the evaluation
+ order, as y is considered recursive.
+*)
+type tree = Tree of tree list
+
+let test =
+ let rec x = (Tree [(print_endline "x"; y); z])
+ and y = Tree (print_endline "y"; [])
+ and z = Tree (print_endline "z"; [x])
+ in
+ match (x, y, z) with
+ | (Tree [y1; z1], Tree[], Tree[x1]) ->
+ assert (y1 == y);
+ assert (z1 == z);
+ assert (x1 == x)
+ | _ ->
+ assert false
diff --git a/testsuite/tests/letrec/evaluation_order_2.reference b/testsuite/tests/letrec/evaluation_order_2.reference
new file mode 100644
index 0000000000..04ec35a6dc
--- /dev/null
+++ b/testsuite/tests/letrec/evaluation_order_2.reference
@@ -0,0 +1,3 @@
+x
+y
+z
diff --git a/testsuite/tests/letrec/evaluation_order_3.ml b/testsuite/tests/letrec/evaluation_order_3.ml
new file mode 100644
index 0000000000..5efaf1af4d
--- /dev/null
+++ b/testsuite/tests/letrec/evaluation_order_3.ml
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type t = { x : t; y : t }
+
+let p = print_endline
+
+let test =
+ let rec x = p "x"; { x = (p "x_x"; x); y = (p "x_y"; y) }
+ and y = p "y"; { x = (p "y_x"; x); y = (p "y_y"; y) }
+ in
+ assert (x.x == x); assert (x.y == y);
+ assert (y.x == x); assert (y.y == y);
+ ()
diff --git a/testsuite/tests/letrec/evaluation_order_3.reference b/testsuite/tests/letrec/evaluation_order_3.reference
new file mode 100644
index 0000000000..5b8c549eca
--- /dev/null
+++ b/testsuite/tests/letrec/evaluation_order_3.reference
@@ -0,0 +1,6 @@
+x
+x_y
+x_x
+y
+y_y
+y_x
diff --git a/testsuite/tests/letrec/float_block_1.ml b/testsuite/tests/letrec/float_block_1.ml
new file mode 100644
index 0000000000..34f314316f
--- /dev/null
+++ b/testsuite/tests/letrec/float_block_1.ml
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* a bug in cmmgen.ml provokes a change in compilation order between
+ ocamlc and ocamlopt in certain letrec-bindings involving float
+ arrays *)
+let test =
+ let rec x = print_endline "x"; [| 1; 2; 3 |]
+ and y = print_endline "y"; [| 1.; 2.; 3. |]
+ in
+ assert (x = [| 1; 2; 3 |]);
+ assert (y = [| 1.; 2.; 3. |]);
+ ()
diff --git a/testsuite/tests/letrec/float_block_1.reference b/testsuite/tests/letrec/float_block_1.reference
new file mode 100644
index 0000000000..b77b4eb1d9
--- /dev/null
+++ b/testsuite/tests/letrec/float_block_1.reference
@@ -0,0 +1,2 @@
+x
+y
diff --git a/testsuite/tests/letrec/float_block_2.ml b/testsuite/tests/letrec/float_block_2.ml
new file mode 100644
index 0000000000..ad8ec61f87
--- /dev/null
+++ b/testsuite/tests/letrec/float_block_2.ml
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* a bug in cmmgen.ml provokes a segfault in certain natively compiled
+ letrec-bindings involving float arrays *)
+let test =
+ let rec x = [| y; y |] and y = 1. in
+ assert (x = [| 1.; 1. |]);
+ assert (y = 1.);
+ ()
diff --git a/testsuite/tests/letrec/float_block_2.reference b/testsuite/tests/letrec/float_block_2.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/letrec/float_block_2.reference
diff --git a/testsuite/tests/letrec/lists.ml b/testsuite/tests/letrec/lists.ml
new file mode 100644
index 0000000000..f9dec61525
--- /dev/null
+++ b/testsuite/tests/letrec/lists.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* a test with lists, because cyclic lists are fun *)
+let test =
+ let rec li = 0::1::2::3::4::5::6::7::8::9::li in
+ match li with
+ | 0::1::2::3::4::5::6::7::8::9::
+ 0::1::2::3::4::5::6::7::8::9::li' ->
+ assert (li == li')
+ | _ -> assert false
diff --git a/testsuite/tests/letrec/lists.reference b/testsuite/tests/letrec/lists.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/letrec/lists.reference
diff --git a/testsuite/tests/letrec/mixing_value_closures_1.ml b/testsuite/tests/letrec/mixing_value_closures_1.ml
new file mode 100644
index 0000000000..6e274346a3
--- /dev/null
+++ b/testsuite/tests/letrec/mixing_value_closures_1.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* mixing values and closures may exercise interesting code paths *)
+type t = A of (int -> int)
+let test =
+ let rec x = A f
+ and f = function
+ | 0 -> 2
+ | n -> match x with A g -> g 0
+ in assert (f 1 = 2)
diff --git a/testsuite/tests/letrec/mixing_value_closures_1.reference b/testsuite/tests/letrec/mixing_value_closures_1.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/letrec/mixing_value_closures_1.reference
diff --git a/testsuite/tests/letrec/mixing_value_closures_2.ml b/testsuite/tests/letrec/mixing_value_closures_2.ml
new file mode 100644
index 0000000000..8a684defc1
--- /dev/null
+++ b/testsuite/tests/letrec/mixing_value_closures_2.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* a polymorphic variant of test3.ml; found a real bug once *)
+let test =
+ let rec x = `A f
+ and f = function
+ | 0 -> 2
+ | n -> match x with `A g -> g 0
+ in
+ assert (f 1 = 2)
diff --git a/testsuite/tests/letrec/mixing_value_closures_2.reference b/testsuite/tests/letrec/mixing_value_closures_2.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/letrec/mixing_value_closures_2.reference
diff --git a/testsuite/tests/letrec/mutual_functions.ml b/testsuite/tests/letrec/mutual_functions.ml
new file mode 100644
index 0000000000..875758b3da
--- /dev/null
+++ b/testsuite/tests/letrec/mutual_functions.ml
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* a simple test with mutually recursive functions *)
+let test =
+ let rec even = function
+ | 0 -> true
+ | n -> odd (n - 1)
+ and odd = function
+ | 0 -> false
+ | n -> even (n - 1)
+ in
+ List.iter (fun i -> assert (even i <> odd i && even i = (i mod 2 = 0)))
+ [0;1;2;3;4;5;6]
diff --git a/testsuite/tests/letrec/mutual_functions.reference b/testsuite/tests/letrec/mutual_functions.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/letrec/mutual_functions.reference
diff --git a/testsuite/tests/letrec/record_with.ml b/testsuite/tests/letrec/record_with.ml
new file mode 100644
index 0000000000..daaa88c474
--- /dev/null
+++ b/testsuite/tests/letrec/record_with.ml
@@ -0,0 +1,37 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+
+(* A regression test for both PR#4141 and PR#5819: when a recursive
+ variable is defined by a { record with ... } expression.
+*)
+
+type t = {
+ self : t;
+ t0 : int;
+ t1 : int;
+ t2 : int;
+ t3 : int;
+ t4 : int;
+};;
+let rec t = {
+ self = t;
+ t0 = 42;
+ t1 = 42;
+ t2 = 42;
+ t3 = 42;
+ t4 = 42;
+};;
+
+let rec self = { t with self=self } in
+Printf.printf "%d\n" self.self.t0
+;;
diff --git a/testsuite/tests/letrec/record_with.reference b/testsuite/tests/letrec/record_with.reference
new file mode 100644
index 0000000000..d81cc0710e
--- /dev/null
+++ b/testsuite/tests/letrec/record_with.reference
@@ -0,0 +1 @@
+42
diff --git a/testsuite/tests/lib-bigarray-2/Makefile b/testsuite/tests/lib-bigarray-2/Makefile
new file mode 100644
index 0000000000..a438c9a321
--- /dev/null
+++ b/testsuite/tests/lib-bigarray-2/Makefile
@@ -0,0 +1,21 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+LIBRARIES=unix bigarray
+C_FILES=bigarrfstub
+F_FILES=bigarrf
+ADD_COMPFLAGS=-I $(OTOPDIR)/otherlibs/bigarray \
+ -I $(OTOPDIR)/otherlibs/$(UNIXLIB)
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-bigarray-2/bigarrf.f b/testsuite/tests/lib-bigarray-2/bigarrf.f
new file mode 100644
index 0000000000..ff52de1d9f
--- /dev/null
+++ b/testsuite/tests/lib-bigarray-2/bigarrf.f
@@ -0,0 +1,26 @@
+ subroutine filltab()
+
+ integer dimx, dimy
+ parameter (dimx = 8, dimy = 6)
+ real ftab(dimx, dimy)
+ common /ftab/ ftab
+ integer x, y
+
+ do 100 x = 1, dimx
+ do 110 y = 1, dimy
+ ftab(x, y) = x * 100 + y
+ 110 continue
+ 100 continue
+ end
+
+ subroutine printtab(tab, dimx, dimy)
+
+ integer dimx, dimy
+ real tab(dimx, dimy)
+ integer x, y
+
+ do 200 x = 1, dimx
+ print 300, x, (tab(x, y), y = 1, dimy)
+ 300 format(/1X, I3, 2X, 10F6.1/)
+ 200 continue
+ end
diff --git a/testsuite/tests/lib-bigarray-2/bigarrfml.ml b/testsuite/tests/lib-bigarray-2/bigarrfml.ml
new file mode 100644
index 0000000000..d73f1555f0
--- /dev/null
+++ b/testsuite/tests/lib-bigarray-2/bigarrfml.ml
@@ -0,0 +1,78 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Bigarray
+open Printf
+
+(* Test harness *)
+
+let error_occurred = ref false
+
+let function_tested = ref ""
+
+let testing_function s =
+ function_tested := s;
+ print_newline();
+ print_string s;
+ print_newline()
+
+let test test_number answer correct_answer =
+ flush stdout;
+ flush stderr;
+ if answer <> correct_answer then begin
+ eprintf "*** Bad result (%s, test %d)\n" !function_tested test_number;
+ flush stderr;
+ error_occurred := true
+ end else begin
+ printf " %d..." test_number
+ end
+
+(* External C and Fortran functions *)
+
+external c_filltab :
+ unit -> (float, float64_elt, c_layout) Array2.t = "c_filltab"
+external c_printtab :
+ (float, float64_elt, c_layout) Array2.t -> unit = "c_printtab"
+external fortran_filltab :
+ unit -> (float, float32_elt, fortran_layout) Array2.t = "fortran_filltab"
+external fortran_printtab :
+ (float, float32_elt, fortran_layout) Array2.t -> unit = "fortran_printtab"
+
+let _ =
+
+ let make_array2 kind layout ind0 dim1 dim2 fromint =
+ let a = Array2.create kind layout dim1 dim2 in
+ for i = ind0 to dim1 - 1 + ind0 do
+ for j = ind0 to dim2 - 1 + ind0 do
+ a.{i,j} <- (fromint (i * 1000 + j))
+ done
+ done;
+ a in
+
+ print_newline();
+ testing_function "------ Foreign function interface --------";
+ testing_function "Passing an array to C";
+ c_printtab (make_array2 float64 c_layout 0 6 8 float);
+ testing_function "Accessing a C array";
+ let a = c_filltab () in
+ test 1 a.{0,0} 0.0;
+ test 2 a.{1,0} 100.0;
+ test 3 a.{0,1} 1.0;
+ test 4 a.{5,4} 504.0;
+ testing_function "Passing an array to Fortran";
+ fortran_printtab (make_array2 float32 fortran_layout 1 5 4 float);
+ testing_function "Accessing a Fortran array";
+ let a = fortran_filltab () in
+ test 1 a.{1,1} 101.0;
+ test 2 a.{2,1} 201.0;
+ test 3 a.{1,2} 102.0;
+ test 4 a.{5,4} 504.0;
diff --git a/testsuite/tests/lib-bigarray-2/bigarrfml.reference b/testsuite/tests/lib-bigarray-2/bigarrfml.reference
new file mode 100644
index 0000000000..8368d5aba0
--- /dev/null
+++ b/testsuite/tests/lib-bigarray-2/bigarrfml.reference
@@ -0,0 +1,27 @@
+
+
+------ Foreign function interface --------
+
+Passing an array to C
+
+Accessing a C array
+ 1... 2... 3... 4...
+Passing an array to Fortran
+ 0 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0
+ 1 1000.0 1001.0 1002.0 1003.0 1004.0 1005.0 1006.0 1007.0
+ 2 2000.0 2001.0 2002.0 2003.0 2004.0 2005.0 2006.0 2007.0
+ 3 3000.0 3001.0 3002.0 3003.0 3004.0 3005.0 3006.0 3007.0
+ 4 4000.0 4001.0 4002.0 4003.0 4004.0 4005.0 4006.0 4007.0
+ 5 5000.0 5001.0 5002.0 5003.0 5004.0 5005.0 5006.0 5007.0
+
+Accessing a Fortran array
+ 1... 2... 3... 4...
+ 1 1001.01002.01003.01004.0
+
+ 2 2001.02002.02003.02004.0
+
+ 3 3001.03002.03003.03004.0
+
+ 4 4001.04002.04003.04004.0
+
+ 5 5001.05002.05003.05004.0
diff --git a/testsuite/tests/lib-bigarray-2/bigarrfstub.c b/testsuite/tests/lib-bigarray-2/bigarrfstub.c
new file mode 100644
index 0000000000..7287298746
--- /dev/null
+++ b/testsuite/tests/lib-bigarray-2/bigarrfstub.c
@@ -0,0 +1,71 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2000 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <caml/mlvalues.h>
+#include <bigarray.h>
+
+extern void filltab_(void);
+extern void printtab_(float * data, int * dimx, int * dimy);
+extern float ftab_[];
+
+#define DIMX 6
+#define DIMY 8
+
+double ctab[DIMX][DIMY];
+
+void filltab(void)
+{
+ int x, y;
+ for (x = 0; x < DIMX; x++)
+ for (y = 0; y < DIMY; y++)
+ ctab[x][y] = x * 100 + y;
+}
+
+void printtab(double tab[DIMX][DIMY])
+{
+ int x, y;
+ for (x = 0; x < DIMX; x++) {
+ printf("%3d", x);
+ for (y = 0; y < DIMY; y++)
+ printf(" %6.1f", tab[x][y]);
+ printf("\n");
+ }
+}
+
+value c_filltab(value unit)
+{
+ filltab();
+ return alloc_bigarray_dims(BIGARRAY_FLOAT64 | BIGARRAY_C_LAYOUT,
+ 2, ctab, DIMX, DIMY);
+}
+
+value c_printtab(value ba)
+{
+ printtab(Data_bigarray_val(ba));
+ return Val_unit;
+}
+
+value fortran_filltab(value unit)
+{
+ filltab_();
+ return alloc_bigarray_dims(BIGARRAY_FLOAT32 | BIGARRAY_FORTRAN_LAYOUT,
+ 2, ftab_, 8, 6);
+}
+
+value fortran_printtab(value ba)
+{
+ int dimx = Bigarray_val(ba)->dim[0];
+ int dimy = Bigarray_val(ba)->dim[1];
+ printtab_(Data_bigarray_val(ba), &dimx, &dimy);
+ return Val_unit;
+}
diff --git a/testsuite/tests/lib-bigarray/Makefile b/testsuite/tests/lib-bigarray/Makefile
new file mode 100644
index 0000000000..31ba474fa0
--- /dev/null
+++ b/testsuite/tests/lib-bigarray/Makefile
@@ -0,0 +1,20 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+LIBRARIES=unix bigarray
+ADD_COMPFLAGS=-I $(OTOPDIR)/otherlibs/$(UNIXLIBVAR)unix \
+ -I $(OTOPDIR)/otherlibs/bigarray
+LD_PATH=$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix:$(TOPDIR)/otherlibs/bigarray
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-bigarray/bigarrays.ml b/testsuite/tests/lib-bigarray/bigarrays.ml
new file mode 100644
index 0000000000..1f2b5ccbed
--- /dev/null
+++ b/testsuite/tests/lib-bigarray/bigarrays.ml
@@ -0,0 +1,880 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Bigarray
+open Printf
+open Complex
+
+(* Test harness *)
+
+let error_occurred = ref false
+
+let function_tested = ref ""
+
+let testing_function s =
+ function_tested := s;
+ print_newline();
+ print_string s;
+ print_newline()
+
+let test test_number answer correct_answer =
+ flush stdout;
+ flush stderr;
+ if answer <> correct_answer then begin
+ eprintf "*** Bad result (%s, test %d)\n" !function_tested test_number;
+ flush stderr;
+ error_occurred := true
+ end else begin
+ printf " %d..." test_number
+ end
+
+(* One-dimensional arrays *)
+
+let _ =
+ testing_function "------ Array1 --------";
+ testing_function "create/set/get";
+ let test_setget kind vals =
+ let rec set a i = function
+ [] -> ()
+ | (v1, v2) :: tl -> a.{i} <- v1; set a (i+1) tl in
+ let rec test a i = function
+ [] -> true
+ | (v1, v2) :: tl -> a.{i} = v2 && test a (i+1) tl in
+ let ca = Array1.create kind c_layout (List.length vals) in
+ let fa = Array1.create kind fortran_layout (List.length vals) in
+ set ca 0 vals;
+ set fa 1 vals;
+ test ca 0 vals && test fa 1 vals in
+ test 1 true
+ (test_setget int8_signed
+ [0, 0;
+ 123, 123;
+ -123, -123;
+ 456, -56;
+ 0x101, 1]);
+ test 2 true
+ (test_setget int8_unsigned
+ [0, 0;
+ 123, 123;
+ -123, 133;
+ 456, 0xc8;
+ 0x101, 1]);
+ test 3 true
+ (test_setget int16_signed
+ [0, 0;
+ 123, 123;
+ -123, -123;
+ 31456, 31456;
+ -31456, -31456;
+ 65432, -104;
+ 0x10001, 1]);
+ test 4 true
+ (test_setget int16_unsigned
+ [0, 0;
+ 123, 123;
+ -123, 65413;
+ 31456, 31456;
+ -31456, 34080;
+ 65432, 65432;
+ 0x10001, 1]);
+ test 5 true
+ (test_setget int
+ [0, 0;
+ 123, 123;
+ -456, -456;
+ max_int, max_int;
+ min_int, min_int;
+ 0x12345678, 0x12345678;
+ -0x12345678, -0x12345678]);
+ test 6 true
+ (test_setget int32
+ [Int32.zero, Int32.zero;
+ Int32.of_int 123, Int32.of_int 123;
+ Int32.of_int (-456), Int32.of_int (-456);
+ Int32.max_int, Int32.max_int;
+ Int32.min_int, Int32.min_int;
+ Int32.of_string "0x12345678", Int32.of_string "0x12345678"]);
+ test 7 true
+ (test_setget int64
+ [Int64.zero, Int64.zero;
+ Int64.of_int 123, Int64.of_int 123;
+ Int64.of_int (-456), Int64.of_int (-456);
+ Int64.max_int, Int64.max_int;
+ Int64.min_int, Int64.min_int;
+ Int64.of_string "0x123456789ABCDEF0",
+ Int64.of_string "0x123456789ABCDEF0"]);
+ test 8 true
+ (test_setget nativeint
+ [Nativeint.zero, Nativeint.zero;
+ Nativeint.of_int 123, Nativeint.of_int 123;
+ Nativeint.of_int (-456), Nativeint.of_int (-456);
+ Nativeint.max_int, Nativeint.max_int;
+ Nativeint.min_int, Nativeint.min_int;
+ Nativeint.of_string "0x12345678",
+ Nativeint.of_string "0x12345678"]);
+ test 9 true
+ (test_setget float32
+ [0.0, 0.0;
+ 4.0, 4.0;
+ -0.5, -0.5;
+ 655360.0, 655360.0]);
+ test 10 true
+ (test_setget float64
+ [0.0, 0.0;
+ 4.0, 4.0;
+ -0.5, -0.5;
+ 1.2345678, 1.2345678;
+ 3.1415e10, 3.1415e10]);
+ test 11 true
+ (test_setget complex32
+ [Complex.zero, Complex.zero;
+ Complex.one, Complex.one;
+ Complex.i, Complex.i;
+ {im = 0.5; re = -2.0}, {im = 0.5; re = -2.0}]);
+ test 12 true
+ (test_setget complex64
+ [Complex.zero, Complex.zero;
+ Complex.one, Complex.one;
+ Complex.i, Complex.i;
+ {im=0.5;re= -2.0}, {im=0.5;re= -2.0};
+ {im=3.1415;re=1.2345678}, {im=3.1415;re=1.2345678}]);
+
+ let from_list kind vals =
+ let a = Array1.create kind c_layout (List.length vals) in
+ let rec set i = function
+ [] -> ()
+ | hd :: tl -> a.{i} <- hd; set (i+1) tl in
+ set 0 vals;
+ a in
+ let from_list_fortran kind vals =
+ let a = Array1.create kind fortran_layout (List.length vals) in
+ let rec set i = function
+ [] -> ()
+ | hd :: tl -> a.{i} <- hd; set (i+1) tl in
+ set 1 vals;
+ a in
+
+ (* Test indexing arrays. This test has to be copy-pasted, otherwise
+ indexing may not use the optimizations in
+ Cmmgen.bigarray_indexing. *)
+ begin
+ let v = 123 in
+ let cb = Array1.create int8_signed c_layout 1000 in
+ let fb = Array1.create int8_signed fortran_layout 1000 in
+ Array1.fill cb v;
+ Array1.fill fb v;
+ let return = ref true in
+ for i = 1 to 99 do
+ let i = i * 10 in
+ return := !return
+ && Array1.unsafe_get cb (i - 10) = v
+ && Array1.unsafe_get cb (i ) = v
+ && Array1.unsafe_get cb (i + 9) = v
+ && Array1.unsafe_get fb (i - 9) = v
+ && Array1.unsafe_get fb (i ) = v
+ && Array1.unsafe_get fb (i + 10) = v
+ done;
+ test 13 true !return
+ end;
+ begin
+ let v = 123 in
+ let cb = Array1.create int16_unsigned c_layout 1000 in
+ let fb = Array1.create int16_unsigned fortran_layout 1000 in
+ Array1.fill cb v;
+ Array1.fill fb v;
+ let return = ref true in
+ for i = 1 to 99 do
+ let i = i * 10 in
+ return := !return
+ && Array1.unsafe_get cb (i - 10) = v
+ && Array1.unsafe_get cb (i ) = v
+ && Array1.unsafe_get cb (i + 9) = v
+ && Array1.unsafe_get fb (i - 9) = v
+ && Array1.unsafe_get fb (i ) = v
+ && Array1.unsafe_get fb (i + 10) = v
+ done;
+ test 14 true !return
+ end;
+ begin
+ let v = 123. in
+ let cb = Array1.create float32 c_layout 1000 in
+ let fb = Array1.create float32 fortran_layout 1000 in
+ Array1.fill cb v;
+ Array1.fill fb v;
+ let return = ref true in
+ for i = 1 to 99 do
+ let i = i * 10 in
+ return := !return
+ && Array1.unsafe_get cb (i - 10) = v
+ && Array1.unsafe_get cb (i ) = v
+ && Array1.unsafe_get cb (i + 9) = v
+ && Array1.unsafe_get fb (i - 9) = v
+ && Array1.unsafe_get fb (i ) = v
+ && Array1.unsafe_get fb (i + 10) = v
+ done;
+ test 15 true !return
+ end;
+
+ begin
+ let v = 123. in
+ let cb = Array1.create float64 c_layout 1000 in
+ let fb = Array1.create float64 fortran_layout 1000 in
+ Array1.fill cb v;
+ Array1.fill fb v;
+ let return = ref true in
+ for i = 1 to 99 do
+ let i = i * 10 in
+ return := !return
+ && Array1.unsafe_get cb (i - 10) = v
+ && Array1.unsafe_get cb (i ) = v
+ && Array1.unsafe_get cb (i + 9) = v
+ && Array1.unsafe_get fb (i - 9) = v
+ && Array1.unsafe_get fb (i ) = v
+ && Array1.unsafe_get fb (i + 10) = v
+ done;
+ test 16 true !return
+ end;
+
+ testing_function "set/get (specialized)";
+ let a = Array1.create int c_layout 3 in
+ for i = 0 to 2 do a.{i} <- i done;
+ for i = 0 to 2 do test (i+1) a.{i} i done;
+ test 4 true (try ignore a.{3}; false with Invalid_argument _ -> true);
+ test 5 true (try ignore a.{-1}; false with Invalid_argument _ -> true);
+
+ let b = Array1.create float64 fortran_layout 3 in
+ for i = 1 to 3 do b.{i} <- float i done;
+ for i = 1 to 3 do test (5 + i) b.{i} (float i) done;
+ test 8 true (try ignore b.{4}; false with Invalid_argument _ -> true);
+ test 9 true (try ignore b.{0}; false with Invalid_argument _ -> true);
+
+ let c = Array1.create complex64 c_layout 3 in
+ for i = 0 to 2 do c.{i} <- {re=float i; im=0.0} done;
+ for i = 0 to 2 do test (10 + i) c.{i} {re=float i; im=0.0} done;
+ test 13 true (try ignore c.{3}; false with Invalid_argument _ -> true);
+ test 14 true (try ignore c.{-1}; false with Invalid_argument _ -> true);
+
+ let d = Array1.create complex32 fortran_layout 3 in
+ for i = 1 to 3 do d.{i} <- {re=float i; im=0.0} done;
+ for i = 1 to 3 do test (14 + i) d.{i} {re=float i; im=0.0} done;
+ test 18 true (try ignore d.{4}; false with Invalid_argument _ -> true);
+ test 19 true (try ignore d.{0}; false with Invalid_argument _ -> true);
+
+ testing_function "set/get (unsafe, specialized)";
+ let a = Array1.create int c_layout 3 in
+ for i = 0 to 2 do Array1.unsafe_set a i i done;
+ for i = 0 to 2 do test (i+1) (Array1.unsafe_get a i) i done;
+
+ let b = Array1.create float64 fortran_layout 3 in
+ for i = 1 to 3 do Array1.unsafe_set b i (float i) done;
+ for i = 1 to 3 do test (5 + i) (Array1.unsafe_get b i) (float i) done;
+
+ testing_function "comparisons";
+ let normalize_comparison n =
+ if n = 0 then 0 else if n < 0 then -1 else 1 in
+ test 1 0 (normalize_comparison (compare
+ (from_list int8_signed [1;2;3;-4;127;-128])
+ (from_list int8_signed [1;2;3;-4;127;-128])));
+ test 2 (-1) (normalize_comparison (compare
+ (from_list int8_signed [1;2;3;-4;127;-128])
+ (from_list int8_signed [1;2;3;4;127;-128])));
+ test 3 1 (normalize_comparison (compare
+ (from_list int8_signed [1;2;3;-4;127;-128])
+ (from_list int8_signed [1;2;3;-4;42;-128])));
+ test 4 (-1) (normalize_comparison (compare
+ (from_list int8_signed [1;2;3;-4])
+ (from_list int8_signed [1;2;3;4;127;-128])));
+ test 5 1 (normalize_comparison (compare
+ (from_list int8_signed [1;2;3;4;127;-128])
+ (from_list int8_signed [1;2;3;-4])));
+
+ test 6 0 (normalize_comparison (compare
+ (from_list int8_unsigned [1;2;3;-4;127;-128])
+ (from_list int8_unsigned [1;2;3;-4;127;-128])));
+ test 7 1 (normalize_comparison (compare
+ (from_list int8_unsigned [1;2;3;-4;127;-128])
+ (from_list int8_unsigned [1;2;3;4;127;-128])));
+ test 8 1 (normalize_comparison (compare
+ (from_list int8_unsigned [1;2;3;-4;127;-128])
+ (from_list int8_unsigned [1;2;3;-4;42;-128])));
+
+ test 9 0 (normalize_comparison (compare
+ (from_list int16_signed [1;2;3;-4;127;-128])
+ (from_list int16_signed [1;2;3;-4;127;-128])));
+ test 10 (-1) (normalize_comparison (compare
+ (from_list int16_signed [1;2;3;-4;127;-128])
+ (from_list int16_signed [1;2;3;4;127;-128])));
+ test 11 1 (normalize_comparison (compare
+ (from_list int16_signed [1;2;3;-4;127;-128])
+ (from_list int16_signed [1;2;3;-4;42;-128])));
+
+ test 12 0 (normalize_comparison (compare
+ (from_list int16_unsigned [1;2;3;-4;127;-128])
+ (from_list int16_unsigned [1;2;3;-4;127;-128])));
+ test 13 (-1) (normalize_comparison (compare
+ (from_list int16_unsigned [1;2;3;4;127;-128])
+ (from_list int16_unsigned [1;2;3;0xFFFF;127;-128])));
+ test 14 1 (normalize_comparison (compare
+ (from_list int16_unsigned [1;2;3;-4;127;-128])
+ (from_list int16_unsigned [1;2;3;-4;42;-128])));
+
+ test 15 0 (normalize_comparison (compare
+ (from_list int [1;2;3;-4;127;-128])
+ (from_list int [1;2;3;-4;127;-128])));
+ test 16 (-1) (normalize_comparison (compare
+ (from_list int [1;2;3;-4;127;-128])
+ (from_list int [1;2;3;4;127;-128])));
+ test 17 1 (normalize_comparison (compare
+ (from_list int [1;2;3;-4;127;-128])
+ (from_list int [1;2;3;-4;42;-128])));
+
+ test 18 0 (normalize_comparison (compare
+ (from_list int32 (List.map Int32.of_int [1;2;3;-4;127;-128]))
+ (from_list int32 (List.map Int32.of_int [1;2;3;-4;127;-128]))));
+ test 19 (-1) (normalize_comparison (compare
+ (from_list int32 (List.map Int32.of_int [1;2;3;-4;127;-128]))
+ (from_list int32 (List.map Int32.of_int [1;2;3;4;127;-128]))));
+ test 20 1 (normalize_comparison (compare
+ (from_list int32 (List.map Int32.of_int [1;2;3;-4;127;-128]))
+ (from_list int32 (List.map Int32.of_int [1;2;3;-4;42;-128]))));
+
+ test 21 0 (normalize_comparison (compare
+ (from_list int64 (List.map Int64.of_int [1;2;3;-4;127;-128]))
+ (from_list int64 (List.map Int64.of_int [1;2;3;-4;127;-128]))));
+ test 22 (-1) (normalize_comparison (compare
+ (from_list int64 (List.map Int64.of_int [1;2;3;-4;127;-128]))
+ (from_list int64 (List.map Int64.of_int [1;2;3;4;127;-128]))));
+ test 23 1 (normalize_comparison (compare
+ (from_list int64 (List.map Int64.of_int [1;2;3;-4;127;-128]))
+ (from_list int64 (List.map Int64.of_int [1;2;3;-4;42;-128]))));
+
+ test 24 0 (normalize_comparison (compare
+ (from_list nativeint (List.map Nativeint.of_int [1;2;3;-4;127;-128]))
+ (from_list nativeint (List.map Nativeint.of_int [1;2;3;-4;127;-128]))));
+ test 25 (-1) (normalize_comparison (compare
+ (from_list nativeint (List.map Nativeint.of_int [1;2;3;-4;127;-128]))
+ (from_list nativeint (List.map Nativeint.of_int [1;2;3;4;127;-128]))));
+ test 26 1 (normalize_comparison (compare
+ (from_list nativeint (List.map Nativeint.of_int [1;2;3;-4;127;-128]))
+ (from_list nativeint (List.map Nativeint.of_int [1;2;3;-4;42;-128]))));
+
+ test 27 0 (normalize_comparison (compare
+ (from_list float32 [0.0; 0.25; -4.0; 3.141592654])
+ (from_list float32 [0.0; 0.25; -4.0; 3.141592654])));
+ test 28 (-1) (normalize_comparison (compare
+ (from_list float32 [0.0; 0.25; -4.0])
+ (from_list float32 [0.0; 0.25; 3.14159])));
+ test 29 1 (normalize_comparison (compare
+ (from_list float32 [0.0; 2.718; -4.0])
+ (from_list float32 [0.0; 0.25; 3.14159])));
+
+ test 30 0 (normalize_comparison (compare
+ (from_list float64 [0.0; 0.25; -4.0; 3.141592654])
+ (from_list float64 [0.0; 0.25; -4.0; 3.141592654])));
+ test 31 (-1) (normalize_comparison (compare
+ (from_list float64 [0.0; 0.25; -4.0])
+ (from_list float64 [0.0; 0.25; 3.14159])));
+ test 32 1 (normalize_comparison (compare
+ (from_list float64 [0.0; 2.718; -4.0])
+ (from_list float64 [0.0; 0.25; 3.14159])));
+
+ test 44 0 (normalize_comparison (compare
+ (from_list complex32 [Complex.zero; Complex.one; Complex.i])
+ (from_list complex32 [Complex.zero; Complex.one; Complex.i])));
+ test 45 (-1) (normalize_comparison (compare
+ (from_list complex32 [Complex.zero; Complex.one; Complex.i])
+ (from_list complex32 [Complex.zero; Complex.one; Complex.one])));
+ test 46 1 (normalize_comparison (compare
+ (from_list complex32 [Complex.zero; Complex.one; Complex.one])
+ (from_list complex32 [Complex.zero; Complex.one; Complex.i])));
+
+ test 47 0 (normalize_comparison (compare
+ (from_list complex64 [Complex.zero; Complex.one; Complex.i])
+ (from_list complex64 [Complex.zero; Complex.one; Complex.i])));
+ test 48 (-1) (normalize_comparison (compare
+ (from_list complex64 [Complex.zero; Complex.one; Complex.i])
+ (from_list complex64 [Complex.zero; Complex.one; Complex.one])));
+ test 49 1 (normalize_comparison (compare
+ (from_list complex64 [Complex.zero; Complex.one; Complex.one])
+ (from_list complex64 [Complex.zero; Complex.one; Complex.i])));
+
+ testing_function "dim";
+ test 1 (Array1.dim (from_list int [1;2;3;4;5])) 5;
+ test 2 (Array1.dim (from_list_fortran int [1;2;3])) 3;
+
+ testing_function "kind & layout";
+ let a = from_list int [1;2;3] in
+ test 1 (Array1.kind a) int;
+ test 2 (Array1.layout a) c_layout;
+ let a = from_list_fortran float32 [1.0;2.0;3.0] in
+ test 1 (Array1.kind a) float32;
+ test 2 (Array1.layout a) fortran_layout;
+
+ testing_function "sub";
+ let a = from_list int [1;2;3;4;5;6;7;8] in
+ test 1 (Array1.sub a 2 5)
+ (from_list int [3;4;5;6;7]);
+ test 2 (Array1.sub a 0 2)
+ (from_list int [1;2]);
+ test 3 (Array1.sub a 0 8)
+ (from_list int [1;2;3;4;5;6;7;8]);
+ let a = from_list float64 [1.0;2.0;3.0;4.0;5.0;6.0;7.0;8.0] in
+ test 4 (Array1.sub a 2 5)
+ (from_list float64 [3.0;4.0;5.0;6.0;7.0]);
+ test 5 (Array1.sub a 0 2)
+ (from_list float64 [1.0;2.0]);
+ test 6 (Array1.sub a 0 8)
+ (from_list float64 [1.0;2.0;3.0;4.0;5.0;6.0;7.0;8.0]);
+ let a = from_list_fortran float64 [1.0;2.0;3.0;4.0;5.0;6.0;7.0;8.0] in
+ test 7 (Array1.sub a 2 5)
+ (from_list_fortran float64 [2.0;3.0;4.0;5.0;6.0]);
+ test 8 (Array1.sub a 1 2)
+ (from_list_fortran float64 [1.0;2.0]);
+ test 9 (Array1.sub a 1 8)
+ (from_list_fortran float64 [1.0;2.0;3.0;4.0;5.0;6.0;7.0;8.0]);
+ Gc.full_major(); (* test GC of proxies *)
+
+ testing_function "blit, fill";
+ let test_blit_fill kind data initval ofs len =
+ let a = from_list kind data in
+ let b = Array1.create kind c_layout (List.length data) in
+ Array1.blit a b;
+ (a = b) &&
+ (Array1.fill (Array1.sub b ofs len) initval;
+ let rec check i = function
+ [] -> true
+ | hd :: tl -> b.{i} = (if i >= ofs && i < ofs + len
+ then initval else hd)
+ && check (i+1) tl
+ in check 0 data) in
+ test 1 true (test_blit_fill int8_signed [1;2;5;8;-100;127] 7 3 2);
+ test 2 true (test_blit_fill int8_unsigned [1;2;5;8;-100;212] 7 3 2);
+ test 3 true (test_blit_fill int16_signed [1;2;5;8;-100;212] 7 3 2);
+ test 4 true (test_blit_fill int16_unsigned [1;2;5;8;-100;212] 7 3 2);
+ test 5 true (test_blit_fill int [1;2;5;8;-100;212] 7 3 2);
+ test 6 true (test_blit_fill int32 (List.map Int32.of_int [1;2;5;8;-100;212])
+ (Int32.of_int 7) 3 2);
+ test 7 true (test_blit_fill int64 (List.map Int64.of_int [1;2;5;8;-100;212])
+ (Int64.of_int 7) 3 2);
+ test 8 true (test_blit_fill nativeint
+ (List.map Nativeint.of_int [1;2;5;8;-100;212])
+ (Nativeint.of_int 7) 3 2);
+ test 9 true (test_blit_fill float32 [1.0;2.0;0.5;0.125;256.0;512.0]
+ 0.25 3 2);
+ test 10 true (test_blit_fill float64 [1.0;2.0;5.0;8.123;-100.456;212e19]
+ 3.1415 3 2);
+ test 11 true (test_blit_fill complex32 [Complex.zero; Complex.one; Complex.i]
+ Complex.i 1 1);
+ test 12 true (test_blit_fill complex64 [Complex.zero; Complex.one; Complex.i]
+ Complex.i 1 1);
+
+(* Bi-dimensional arrays *)
+
+ print_newline();
+ testing_function "------ Array2 --------";
+ testing_function "create/set/get";
+ let make_array2 kind layout ind0 dim1 dim2 fromint =
+ let a = Array2.create kind layout dim1 dim2 in
+ for i = ind0 to dim1 - 1 + ind0 do
+ for j = ind0 to dim2 - 1 + ind0 do
+ a.{i,j} <- (fromint (i * 1000 + j))
+ done
+ done;
+ a in
+ let check_array2 a ind0 dim1 dim2 fromint =
+ try
+ for i = ind0 to dim1 - 1 + ind0 do
+ for j = ind0 to dim2 - 1 + ind0 do
+ if a.{i,j} <> (fromint (i * 1000 + j)) then raise Exit
+ done
+ done;
+ true
+ with Exit -> false in
+ let id x = x in
+ test 1 true
+ (check_array2 (make_array2 int16_signed c_layout 0 10 20 id) 0 10 20 id);
+ test 2 true
+ (check_array2 (make_array2 int c_layout 0 10 20 id) 0 10 20 id);
+ test 3 true
+ (check_array2 (make_array2 int32 c_layout 0 10 20 Int32.of_int)
+ 0 10 20 Int32.of_int);
+ test 4 true
+ (check_array2 (make_array2 float32 c_layout 0 10 20 float)
+ 0 10 20 float);
+ test 5 true
+ (check_array2 (make_array2 float64 c_layout 0 10 20 float)
+ 0 10 20 float);
+ test 6 true
+ (check_array2 (make_array2 int16_signed fortran_layout 1 10 20 id)
+ 1 10 20 id);
+ test 7 true
+ (check_array2 (make_array2 int fortran_layout 1 10 20 id) 1 10 20 id);
+ test 8 true
+ (check_array2 (make_array2 int32 fortran_layout 1 10 20 Int32.of_int)
+ 1 10 20 Int32.of_int);
+ test 9 true
+ (check_array2 (make_array2 float32 fortran_layout 1 10 20 float)
+ 1 10 20 float);
+ test 10 true
+ (check_array2 (make_array2 float64 fortran_layout 1 10 20 float)
+ 1 10 20 float);
+ let makecomplex i = {re = float i; im = float (-i)} in
+ test 11 true
+ (check_array2 (make_array2 complex32 c_layout 0 10 20 makecomplex)
+ 0 10 20 makecomplex);
+ test 12 true
+ (check_array2 (make_array2 complex64 c_layout 0 10 20 makecomplex)
+ 0 10 20 makecomplex);
+ test 13 true
+ (check_array2 (make_array2 complex32 fortran_layout 1 10 20 makecomplex)
+ 1 10 20 makecomplex);
+ test 14 true
+ (check_array2 (make_array2 complex64 fortran_layout 1 10 20 makecomplex)
+ 1 10 20 makecomplex);
+
+ testing_function "set/get (specialized)";
+ let a = Array2.create int16_signed c_layout 3 3 in
+ for i = 0 to 2 do for j = 0 to 2 do a.{i,j} <- i-j done done;
+ let ok = ref true in
+ for i = 0 to 2 do
+ for j = 0 to 2 do if a.{i,j} <> i-j then ok := false done
+ done;
+ test 1 true !ok;
+ test 2 true (try ignore a.{3,0}; false with Invalid_argument _ -> true);
+ test 3 true (try ignore a.{-1,0}; false with Invalid_argument _ -> true);
+ test 4 true (try ignore a.{0,3}; false with Invalid_argument _ -> true);
+ test 5 true (try ignore a.{0,-1}; false with Invalid_argument _ -> true);
+
+ let b = Array2.create float32 fortran_layout 3 3 in
+ for i = 1 to 3 do for j = 1 to 3 do b.{i,j} <- float(i-j) done done;
+ let ok = ref true in
+ for i = 1 to 3 do
+ for j = 1 to 3 do if b.{i,j} <> float(i-j) then ok := false done
+ done;
+ test 6 true !ok;
+ test 7 true (try ignore b.{4,1}; false with Invalid_argument _ -> true);
+ test 8 true (try ignore b.{0,1}; false with Invalid_argument _ -> true);
+ test 9 true (try ignore b.{1,4}; false with Invalid_argument _ -> true);
+ test 10 true (try ignore b.{1,0}; false with Invalid_argument _ -> true);
+
+ testing_function "set/get (unsafe, specialized)";
+ let a = Array2.create int16_signed c_layout 3 3 in
+ for i = 0 to 2 do for j = 0 to 2 do Array2.unsafe_set a i j (i-j) done done;
+ let ok = ref true in
+ for i = 0 to 2 do
+ for j = 0 to 2 do if Array2.unsafe_get a i j <> i-j then ok := false done
+ done;
+ test 1 true !ok;
+
+ let b = Array2.create float32 fortran_layout 3 3 in
+ for i = 1 to 3 do
+ for j = 1 to 3 do Array2.unsafe_set b i j (float(i-j)) done
+ done;
+ let ok = ref true in
+ for i = 1 to 3 do
+ for j = 1 to 3 do
+ if Array2.unsafe_get b i j <> float(i-j) then ok := false
+ done
+ done;
+ test 2 true !ok;
+
+ testing_function "dim";
+ let a = (make_array2 int c_layout 0 4 6 id) in
+ test 1 (Array2.dim1 a) 4;
+ test 2 (Array2.dim2 a) 6;
+ let b = (make_array2 int fortran_layout 1 4 6 id) in
+ test 3 (Array2.dim1 b) 4;
+ test 4 (Array2.dim2 b) 6;
+
+ testing_function "sub";
+ let a = make_array2 int c_layout 0 5 3 id in
+ let b = Array2.sub_left a 2 2 in
+ test 1 true
+ (b.{0,0} = 2000 &&
+ b.{0,1} = 2001 &&
+ b.{0,2} = 2002 &&
+ b.{1,0} = 3000 &&
+ b.{1,1} = 3001 &&
+ b.{1,2} = 3002);
+ let a = make_array2 int fortran_layout 1 5 3 id in
+ let b = Array2.sub_right a 2 2 in
+ test 2 true
+ (b.{1,1} = 1002 &&
+ b.{1,2} = 1003 &&
+ b.{2,1} = 2002 &&
+ b.{2,2} = 2003 &&
+ b.{3,1} = 3002 &&
+ b.{3,2} = 3003 &&
+ b.{4,1} = 4002 &&
+ b.{4,2} = 4003 &&
+ b.{5,1} = 5002 &&
+ b.{5,2} = 5003);
+
+ testing_function "slice";
+ let a = make_array2 int c_layout 0 5 3 id in
+ test 1 (Array2.slice_left a 0) (from_list int [0;1;2]);
+ test 2 (Array2.slice_left a 1) (from_list int [1000;1001;1002]);
+ test 3 (Array2.slice_left a 2) (from_list int [2000;2001;2002]);
+ test 4 (Array2.slice_left a 3) (from_list int [3000;3001;3002]);
+ test 5 (Array2.slice_left a 4) (from_list int [4000;4001;4002]);
+ let a = make_array2 int fortran_layout 1 5 3 id in
+ test 6 (Array2.slice_right a 1)
+ (from_list_fortran int [1001;2001;3001;4001;5001]);
+ test 7 (Array2.slice_right a 2)
+ (from_list_fortran int [1002;2002;3002;4002;5002]);
+ test 8 (Array2.slice_right a 3)
+ (from_list_fortran int [1003;2003;3003;4003;5003]);
+
+(* Tri-dimensional arrays *)
+
+ print_newline();
+ testing_function "------ Array3 --------";
+ testing_function "create/set/get";
+ let make_array3 kind layout ind0 dim1 dim2 dim3 fromint =
+ let a = Array3.create kind layout dim1 dim2 dim3 in
+ for i = ind0 to dim1 - 1 + ind0 do
+ for j = ind0 to dim2 - 1 + ind0 do
+ for k = ind0 to dim3 - 1 + ind0 do
+ a.{i, j, k} <- (fromint (i * 100 + j * 10 + k))
+ done
+ done
+ done;
+ a in
+ let check_array3 a ind0 dim1 dim2 dim3 fromint =
+ try
+ for i = ind0 to dim1 - 1 + ind0 do
+ for j = ind0 to dim2 - 1 + ind0 do
+ for k = ind0 to dim3 - 1 + ind0 do
+ if a.{i, j, k} <> (fromint (i * 100 + j * 10 + k))
+ then raise Exit
+ done
+ done
+ done;
+ true
+ with Exit -> false in
+ let id x = x in
+ test 1 true
+ (check_array3 (make_array3 int16_signed c_layout 0 4 5 6 id) 0 4 5 6 id);
+ test 2 true
+ (check_array3 (make_array3 int c_layout 0 4 5 6 id) 0 4 5 6 id);
+ test 3 true
+ (check_array3 (make_array3 int32 c_layout 0 4 5 6 Int32.of_int)
+ 0 4 5 6 Int32.of_int);
+ test 4 true
+ (check_array3 (make_array3 float32 c_layout 0 4 5 6 float)
+ 0 4 5 6 float);
+ test 5 true
+ (check_array3 (make_array3 float64 c_layout 0 4 5 6 float)
+ 0 4 5 6 float);
+ test 6 true
+ (check_array3 (make_array3 int16_signed fortran_layout 1 4 5 6 id)
+ 1 4 5 6 id);
+ test 7 true
+ (check_array3 (make_array3 int fortran_layout 1 4 5 6 id) 1 4 5 6 id);
+ test 8 true
+ (check_array3 (make_array3 int32 fortran_layout 1 4 5 6 Int32.of_int)
+ 1 4 5 6 Int32.of_int);
+ test 9 true
+ (check_array3 (make_array3 float32 fortran_layout 1 4 5 6 float)
+ 1 4 5 6 float);
+ test 10 true
+ (check_array3 (make_array3 float64 fortran_layout 1 4 5 6 float)
+ 1 4 5 6 float);
+ test 11 true
+ (check_array3 (make_array3 complex32 c_layout 0 4 5 6 makecomplex)
+ 0 4 5 6 makecomplex);
+ test 12 true
+ (check_array3 (make_array3 complex64 c_layout 0 4 5 6 makecomplex)
+ 0 4 5 6 makecomplex);
+ test 13 true
+ (check_array3 (make_array3 complex32 fortran_layout 1 4 5 6 makecomplex)
+ 1 4 5 6 makecomplex);
+ test 14 true
+ (check_array3 (make_array3 complex64 fortran_layout 1 4 5 6 makecomplex)
+ 1 4 5 6 makecomplex);
+
+
+ testing_function "set/get (specialized)";
+ let a = Array3.create int32 c_layout 2 3 4 in
+ for i = 0 to 1 do for j = 0 to 2 do for k = 0 to 3 do
+ a.{i,j,k} <- Int32.of_int((i lsl 4) + (j lsl 2) + k)
+ done done done;
+ let ok = ref true in
+ for i = 0 to 1 do for j = 0 to 2 do for k = 0 to 3 do
+ if Int32.to_int a.{i,j,k} <> (i lsl 4) + (j lsl 2) + k then ok := false
+ done done done;
+ test 1 true !ok;
+
+ let b = Array3.create int64 fortran_layout 2 3 4 in
+ for i = 1 to 2 do for j = 1 to 3 do for k = 1 to 4 do
+ b.{i,j,k} <- Int64.of_int((i lsl 4) + (j lsl 2) + k)
+ done done done;
+ let ok = ref true in
+ for i = 1 to 2 do for j = 1 to 3 do for k = 1 to 4 do
+ if Int64.to_int b.{i,j,k} <> (i lsl 4) + (j lsl 2) + k then ok := false
+ done done done;
+ test 2 true !ok;
+
+ testing_function "set/get (unsafe, specialized)";
+ let a = Array3.create int32 c_layout 2 3 4 in
+ for i = 0 to 1 do for j = 0 to 2 do for k = 0 to 3 do
+ Array3.unsafe_set a i j k (Int32.of_int((i lsl 4) + (j lsl 2) + k))
+ done done done;
+ let ok = ref true in
+ for i = 0 to 1 do for j = 0 to 2 do for k = 0 to 3 do
+ if Int32.to_int (Array3.unsafe_get a i j k) <> (i lsl 4) + (j lsl 2) + k
+ then ok := false
+ done done done;
+ test 1 true !ok;
+
+ testing_function "dim";
+ let a = (make_array3 int c_layout 0 4 5 6 id) in
+ test 1 (Array3.dim1 a) 4;
+ test 2 (Array3.dim2 a) 5;
+ test 3 (Array3.dim3 a) 6;
+ let b = (make_array3 int fortran_layout 1 4 5 6 id) in
+ test 4 (Array3.dim1 b) 4;
+ test 5 (Array3.dim2 b) 5;
+ test 6 (Array3.dim3 b) 6;
+
+ testing_function "slice1";
+ let a = make_array3 int c_layout 0 3 3 3 id in
+ test 1 (Array3.slice_left_1 a 0 0) (from_list int [0;1;2]);
+ test 2 (Array3.slice_left_1 a 0 1) (from_list int [10;11;12]);
+ test 3 (Array3.slice_left_1 a 0 2) (from_list int [20;21;22]);
+ test 4 (Array3.slice_left_1 a 1 1) (from_list int [110;111;112]);
+ test 5 (Array3.slice_left_1 a 2 1) (from_list int [210;211;212]);
+ let a = make_array3 int fortran_layout 1 3 3 3 id in
+ test 6 (Array3.slice_right_1 a 1 2) (from_list_fortran int [112;212;312]);
+ test 7 (Array3.slice_right_1 a 3 1) (from_list_fortran int [131;231;331]);
+
+(* Reshaping *)
+ print_newline();
+ testing_function "------ Reshaping --------";
+ testing_function "reshape_1";
+ let a = make_array2 int c_layout 0 3 4 id in
+ let b = make_array2 int fortran_layout 1 3 4 id in
+ let c = reshape_1 (genarray_of_array2 a) 12 in
+ test 1 c (from_list int [0;1;2;3;1000;1001;1002;1003;2000;2001;2002;2003]);
+ let d = reshape_1 (genarray_of_array2 b) 12 in
+ test 2 d (from_list_fortran int
+ [1001;2001;3001;1002;2002;3002;1003;2003;3003;1004;2004;3004]);
+ testing_function "reshape_2";
+ let c = reshape_2 (genarray_of_array2 a) 4 3 in
+ test 1 (Array2.slice_left c 0) (from_list int [0;1;2]);
+ test 2 (Array2.slice_left c 1) (from_list int [3;1000;1001]);
+ test 3 (Array2.slice_left c 2) (from_list int [1002;1003;2000]);
+ test 4 (Array2.slice_left c 3) (from_list int [2001;2002;2003]);
+ let d = reshape_2 (genarray_of_array2 b) 4 3 in
+ test 5 (Array2.slice_right d 1) (from_list_fortran int [1001;2001;3001;1002]);
+ test 6 (Array2.slice_right d 2) (from_list_fortran int [2002;3002;1003;2003]);
+ test 7 (Array2.slice_right d 3) (from_list_fortran int [3003;1004;2004;3004]);
+
+(* I/O *)
+
+ print_newline();
+ testing_function "------ I/O --------";
+ testing_function "output_value/input_value";
+ let test_structured_io testno value =
+ let tmp = Filename.temp_file "bigarray" ".data" in
+ let oc = open_out_bin tmp in
+ output_value oc value;
+ close_out oc;
+ let ic = open_in_bin tmp in
+ let value' = input_value ic in
+ close_in ic;
+ Sys.remove tmp;
+ test testno value value' in
+ test_structured_io 1 (from_list int8_signed [1;2;3;-4;127;-128]);
+ test_structured_io 2 (from_list int16_signed [1;2;3;-4;127;-128]);
+ test_structured_io 3 (from_list int [1;2;3;-4;127;-128]);
+ test_structured_io 4
+ (from_list int32 (List.map Int32.of_int [1;2;3;-4;127;-128]));
+ test_structured_io 5
+ (from_list int64 (List.map Int64.of_int [1;2;3;-4;127;-128]));
+ test_structured_io 6
+ (from_list nativeint (List.map Nativeint.of_int [1;2;3;-4;127;-128]));
+ test_structured_io 7 (from_list float32 [0.0; 0.25; -4.0; 3.141592654]);
+ test_structured_io 8 (from_list float64 [0.0; 0.25; -4.0; 3.141592654]);
+ test_structured_io 9 (make_array2 int c_layout 0 100 100 id);
+ test_structured_io 10 (make_array2 float64 fortran_layout 1 200 200 float);
+ test_structured_io 11 (make_array3 int32 c_layout 0 20 30 40 Int32.of_int);
+ test_structured_io 12 (make_array3 float32 fortran_layout 1 10 50 100 float);
+ test_structured_io 13 (make_array2 complex32 c_layout 0 100 100 makecomplex);
+ test_structured_io 14 (make_array3 complex64 fortran_layout 1 10 20 30
+ makecomplex);
+
+ testing_function "map_file";
+ let mapped_file = Filename.temp_file "bigarray" ".data" in
+ begin
+ let fd =
+ Unix.openfile mapped_file
+ [Unix.O_RDWR; Unix.O_TRUNC; Unix.O_CREAT] 0o666 in
+ let a = Array1.map_file fd float64 c_layout true 10000 in
+ Unix.close fd;
+ for i = 0 to 9999 do a.{i} <- float i done;
+ let fd = Unix.openfile mapped_file [Unix.O_RDONLY] 0 in
+ let b = Array2.map_file fd float64 fortran_layout false 100 (-1) in
+ Unix.close fd;
+ let ok = ref true in
+ for i = 0 to 99 do
+ for j = 0 to 99 do
+ if b.{j+1,i+1} <> float (100 * i + j) then ok := false
+ done
+ done;
+ test 1 !ok true;
+ b.{50,50} <- (-1.0);
+ let fd = Unix.openfile mapped_file [Unix.O_RDONLY] 0 in
+ let c = Array2.map_file fd float64 c_layout false (-1) 100 in
+ Unix.close fd;
+ let ok = ref true in
+ for i = 0 to 99 do
+ for j = 0 to 99 do
+ if c.{i,j} <> float (100 * i + j) then ok := false
+ done
+ done;
+ test 2 !ok true;
+ let fd = Unix.openfile mapped_file [Unix.O_RDONLY] 0 in
+ let c = Array2.map_file fd ~pos:800L float64 c_layout false (-1) 100 in
+ Unix.close fd;
+ let ok = ref true in
+ for i = 1 to 99 do
+ for j = 0 to 99 do
+ if c.{i-1,j} <> float (100 * i + j) then ok := false
+ done
+ done;
+ test 3 !ok true;
+ let fd = Unix.openfile mapped_file [Unix.O_RDONLY] 0 in
+ let c = Array2.map_file fd ~pos:79200L float64 c_layout false (-1) 100 in
+ Unix.close fd;
+ let ok = ref true in
+ for j = 0 to 99 do
+ if c.{0,j} <> float (100 * 99 + j) then ok := false
+ done;
+ test 4 !ok true
+ end;
+ (* Force garbage collection of the mapped bigarrays above, otherwise
+ Win32 doesn't let us erase the file. Notice the begin...end above
+ so that the VM doesn't keep stack references to the mapped bigarrays. *)
+ Gc.full_major();
+ Sys.remove mapped_file;
+
+ ()
+
+(********* End of test *********)
+
+let _ =
+ print_newline();
+ if !error_occurred then begin
+ prerr_endline "************* TEST FAILED ****************"; exit 2
+ end else
+ exit 0
diff --git a/testsuite/tests/lib-bigarray/bigarrays.reference b/testsuite/tests/lib-bigarray/bigarrays.reference
new file mode 100644
index 0000000000..af05f4ca54
--- /dev/null
+++ b/testsuite/tests/lib-bigarray/bigarrays.reference
@@ -0,0 +1,61 @@
+
+------ Array1 --------
+
+create/set/get
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16...
+set/get (specialized)
+ 1... 2... 3... 4... 5... 6... 7... 8... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19...
+set/get (unsafe, specialized)
+ 1... 2... 3... 6... 7... 8...
+comparisons
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19... 20... 21... 22... 23... 24... 25... 26... 27... 28... 29... 30... 31... 32... 44... 45... 46... 47... 48... 49...
+dim
+ 1... 2...
+kind & layout
+ 1... 2... 1... 2...
+sub
+ 1... 2... 3... 4... 5... 6... 7... 8... 9...
+blit, fill
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12...
+
+------ Array2 --------
+
+create/set/get
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14...
+set/get (specialized)
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10...
+set/get (unsafe, specialized)
+ 1... 2...
+dim
+ 1... 2... 3... 4...
+sub
+ 1... 2...
+slice
+ 1... 2... 3... 4... 5... 6... 7... 8...
+
+------ Array3 --------
+
+create/set/get
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14...
+set/get (specialized)
+ 1... 2...
+set/get (unsafe, specialized)
+ 1...
+dim
+ 1... 2... 3... 4... 5... 6...
+slice1
+ 1... 2... 3... 4... 5... 6... 7...
+
+------ Reshaping --------
+
+reshape_1
+ 1... 2...
+reshape_2
+ 1... 2... 3... 4... 5... 6... 7...
+
+------ I/O --------
+
+output_value/input_value
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14...
+map_file
+ 1... 2... 3... 4...
diff --git a/testsuite/tests/lib-bigarray/fftba.ml b/testsuite/tests/lib-bigarray/fftba.ml
new file mode 100644
index 0000000000..801553f37b
--- /dev/null
+++ b/testsuite/tests/lib-bigarray/fftba.ml
@@ -0,0 +1,194 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Bigarray
+
+let pi = 3.14159265358979323846
+
+let tpi = 2.0 *. pi
+
+let fft (px : (float, float64_elt, c_layout) Array1.t)
+ (py : (float, float64_elt, c_layout) Array1.t) np =
+ let i = ref 2 in
+ let m = ref 1 in
+
+ while (!i < np) do
+ i := !i + !i;
+ m := !m + 1
+ done;
+
+ let n = !i in
+
+ if n <> np then begin
+ for i = np+1 to n do
+ px.{i} <- 0.0;
+ py.{i} <- 0.0
+ done;
+ print_string "Use "; print_int n;
+ print_string " point fft"; print_newline()
+ end;
+
+ let n2 = ref(n+n) in
+ for k = 1 to !m-1 do
+ n2 := !n2 / 2;
+ let n4 = !n2 / 4 in
+ let e = tpi /. float !n2 in
+
+ for j = 1 to n4 do
+ let a = e *. float(j - 1) in
+ let a3 = 3.0 *. a in
+ let cc1 = cos(a) in
+ let ss1 = sin(a) in
+ let cc3 = cos(a3) in
+ let ss3 = sin(a3) in
+ let is = ref j in
+ let id = ref(2 * !n2) in
+
+ while !is < n do
+ let i0r = ref !is in
+ while !i0r < n do
+ let i0 = !i0r in
+ let i1 = i0 + n4 in
+ let i2 = i1 + n4 in
+ let i3 = i2 + n4 in
+ let r1 = px.{i0} -. px.{i2} in
+ px.{i0} <- px.{i0} +. px.{i2};
+ let r2 = px.{i1} -. px.{i3} in
+ px.{i1} <- px.{i1} +. px.{i3};
+ let s1 = py.{i0} -. py.{i2} in
+ py.{i0} <- py.{i0} +. py.{i2};
+ let s2 = py.{i1} -. py.{i3} in
+ py.{i1} <- py.{i1} +. py.{i3};
+ let s3 = r1 -. s2 in
+ let r1 = r1 +. s2 in
+ let s2 = r2 -. s1 in
+ let r2 = r2 +. s1 in
+ px.{i2} <- r1*.cc1 -. s2*.ss1;
+ py.{i2} <- -.s2*.cc1 -. r1*.ss1;
+ px.{i3} <- s3*.cc3 +. r2*.ss3;
+ py.{i3} <- r2*.cc3 -. s3*.ss3;
+ i0r := i0 + !id
+ done;
+ is := 2 * !id - !n2 + j;
+ id := 4 * !id
+ done
+ done
+ done;
+
+(************************************)
+(* Last stage, length=2 butterfly *)
+(************************************)
+
+ let is = ref 1 in
+ let id = ref 4 in
+
+ while !is < n do
+ let i0r = ref !is in
+ while !i0r <= n do
+ let i0 = !i0r in
+ let i1 = i0 + 1 in
+ let r1 = px.{i0} in
+ px.{i0} <- r1 +. px.{i1};
+ px.{i1} <- r1 -. px.{i1};
+ let r1 = py.{i0} in
+ py.{i0} <- r1 +. py.{i1};
+ py.{i1} <- r1 -. py.{i1};
+ i0r := i0 + !id
+ done;
+ is := 2 * !id - 1;
+ id := 4 * !id
+ done;
+
+(*************************)
+(* Bit reverse counter *)
+(*************************)
+
+ let j = ref 1 in
+
+ for i = 1 to n - 1 do
+ if i < !j then begin
+ let xt = px.{!j} in
+ px.{!j} <- px.{i};
+ px.{i} <- xt;
+ let xt = py.{!j} in
+ py.{!j} <- py.{i};
+ py.{i} <- xt
+ end;
+ let k = ref(n / 2) in
+ while !k < !j do
+ j := !j - !k;
+ k := !k / 2
+ done;
+ j := !j + !k
+ done;
+
+ n
+
+
+let test np =
+ print_int np; print_string "... "; flush stdout;
+ let enp = float np in
+ let npm = np / 2 - 1 in
+ let pxr = Array1.create float64 c_layout (np+2)
+ and pxi = Array1.create float64 c_layout (np+2) in
+ let t = pi /. enp in
+ pxr.{1} <- (enp -. 1.0) *. 0.5;
+ pxi.{1} <- 0.0;
+ let n2 = np / 2 in
+ pxr.{n2+1} <- -0.5;
+ pxi.{n2+1} <- 0.0;
+
+ for i = 1 to npm do
+ let j = np - i in
+ pxr.{i+1} <- -0.5;
+ pxr.{j+1} <- -0.5;
+ let z = t *. float i in
+ let y = -0.5 *. (cos(z)/.sin(z)) in
+ pxi.{i+1} <- y;
+ pxi.{j+1} <- -.y
+ done;
+(**
+ print_newline();
+ for i=0 to 15 do Printf.printf "%d %f %f\n" i pxr.{i+1} pxi.{i+1} done;
+**)
+ let _ = fft pxr pxi np in
+(**
+ for i=0 to 15 do Printf.printf "%d %f %f\n" i pxr.{i+1} pxi.{i+1} done;
+**)
+ let zr = ref 0.0 in
+ let zi = ref 0.0 in
+ let kr = ref 0 in
+ let ki = ref 0 in
+ for i = 0 to np-1 do
+ let a = abs_float(pxr.{i+1} -. float i) in
+ if !zr < a then begin
+ zr := a;
+ kr := i
+ end;
+ let a = abs_float(pxi.{i+1}) in
+ if !zi < a then begin
+ zi := a;
+ ki := i
+ end
+ done;
+(*
+ let zm = if abs_float !zr < abs_float !zi then !zi else !zr in
+ print_float zm; print_newline()
+*)
+ if abs_float !zr <= 1e-9 && abs_float !zi <= 1e-9
+ then print_string "ok"
+ else print_string "ERROR";
+ print_newline()
+
+
+let _ =
+ let np = ref 16 in for i = 1 to 13 do test !np; np := !np*2 done
diff --git a/testsuite/tests/lib-bigarray/fftba.reference b/testsuite/tests/lib-bigarray/fftba.reference
new file mode 100644
index 0000000000..71017f70fc
--- /dev/null
+++ b/testsuite/tests/lib-bigarray/fftba.reference
@@ -0,0 +1,13 @@
+16... ok
+32... ok
+64... ok
+128... ok
+256... ok
+512... ok
+1024... ok
+2048... ok
+4096... ok
+8192... ok
+16384... ok
+32768... ok
+65536... ok
diff --git a/testsuite/tests/lib-bigarray/pr5115.ml b/testsuite/tests/lib-bigarray/pr5115.ml
new file mode 100644
index 0000000000..27afaf56e7
--- /dev/null
+++ b/testsuite/tests/lib-bigarray/pr5115.ml
@@ -0,0 +1,24 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2010 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* PR#5115 - multiple evaluation of bigarray expr *)
+
+open Bigarray
+
+let f y0 =
+ Printf.printf "***EXEC***\n%!";
+ y0
+
+let _ =
+ let y = Array1.of_array float64 fortran_layout [| 1. |] in
+ (f y).{1};
+ (f y).{1} <- 3.14
diff --git a/testsuite/tests/lib-bigarray/pr5115.reference b/testsuite/tests/lib-bigarray/pr5115.reference
new file mode 100644
index 0000000000..63f719ac56
--- /dev/null
+++ b/testsuite/tests/lib-bigarray/pr5115.reference
@@ -0,0 +1,2 @@
+***EXEC***
+***EXEC***
diff --git a/testsuite/tests/lib-digest/Makefile b/testsuite/tests/lib-digest/Makefile
new file mode 100644
index 0000000000..adda276594
--- /dev/null
+++ b/testsuite/tests/lib-digest/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=md5
+ADD_COMPFLAGS=-w a
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-digest/md5.ml b/testsuite/tests/lib-digest/md5.ml
new file mode 100644
index 0000000000..f9bcf9289f
--- /dev/null
+++ b/testsuite/tests/lib-digest/md5.ml
@@ -0,0 +1,243 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2003 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test int32 arithmetic and optimizations using the MD5 algorithm *)
+
+open Printf
+
+type context =
+ { buf: string;
+ mutable pos: int;
+ mutable a: int32;
+ mutable b: int32;
+ mutable c: int32;
+ mutable d: int32;
+ mutable bits: int64 }
+
+let step1 w x y z data s =
+ let w =
+ Int32.add (Int32.add w data)
+ (Int32.logxor z (Int32.logand x (Int32.logxor y z))) in
+ Int32.add x
+ (Int32.logor (Int32.shift_left w s) (Int32.shift_right_logical w (32-s)))
+
+let step2 w x y z data s =
+ let w =
+ Int32.add (Int32.add w data)
+ (Int32.logxor y (Int32.logand z (Int32.logxor x y))) in
+ Int32.add x
+ (Int32.logor (Int32.shift_left w s) (Int32.shift_right_logical w (32-s)))
+
+let step3 w x y z data s =
+ let w =
+ Int32.add (Int32.add w data)
+ (Int32.logxor x (Int32.logxor y z)) in
+ Int32.add x
+ (Int32.logor (Int32.shift_left w s) (Int32.shift_right_logical w (32-s)))
+
+let step4 w x y z data s =
+ let w =
+ Int32.add (Int32.add w data)
+ (Int32.logxor y (Int32.logor x (Int32.logxor z (-1l)))) in
+ Int32.add x
+ (Int32.logor (Int32.shift_left w s) (Int32.shift_right_logical w (32-s)))
+
+let transform ctx data =
+ let a = ctx.a and b = ctx.b and c = ctx.c and d = ctx.d in
+
+ let a = step1 a b c d (Int32.add data.(0) 0xd76aa478l) 7 in
+ let d = step1 d a b c (Int32.add data.(1) 0xe8c7b756l) 12 in
+ let c = step1 c d a b (Int32.add data.(2) 0x242070dbl) 17 in
+ let b = step1 b c d a (Int32.add data.(3) 0xc1bdceeel) 22 in
+ let a = step1 a b c d (Int32.add data.(4) 0xf57c0fafl) 7 in
+ let d = step1 d a b c (Int32.add data.(5) 0x4787c62al) 12 in
+ let c = step1 c d a b (Int32.add data.(6) 0xa8304613l) 17 in
+ let b = step1 b c d a (Int32.add data.(7) 0xfd469501l) 22 in
+ let a = step1 a b c d (Int32.add data.(8) 0x698098d8l) 7 in
+ let d = step1 d a b c (Int32.add data.(9) 0x8b44f7afl) 12 in
+ let c = step1 c d a b (Int32.add data.(10) 0xffff5bb1l) 17 in
+ let b = step1 b c d a (Int32.add data.(11) 0x895cd7bel) 22 in
+ let a = step1 a b c d (Int32.add data.(12) 0x6b901122l) 7 in
+ let d = step1 d a b c (Int32.add data.(13) 0xfd987193l) 12 in
+ let c = step1 c d a b (Int32.add data.(14) 0xa679438el) 17 in
+ let b = step1 b c d a (Int32.add data.(15) 0x49b40821l) 22 in
+
+ let a = step2 a b c d (Int32.add data.(1) 0xf61e2562l) 5 in
+ let d = step2 d a b c (Int32.add data.(6) 0xc040b340l) 9 in
+ let c = step2 c d a b (Int32.add data.(11) 0x265e5a51l) 14 in
+ let b = step2 b c d a (Int32.add data.(0) 0xe9b6c7aal) 20 in
+ let a = step2 a b c d (Int32.add data.(5) 0xd62f105dl) 5 in
+ let d = step2 d a b c (Int32.add data.(10) 0x02441453l) 9 in
+ let c = step2 c d a b (Int32.add data.(15) 0xd8a1e681l) 14 in
+ let b = step2 b c d a (Int32.add data.(4) 0xe7d3fbc8l) 20 in
+ let a = step2 a b c d (Int32.add data.(9) 0x21e1cde6l) 5 in
+ let d = step2 d a b c (Int32.add data.(14) 0xc33707d6l) 9 in
+ let c = step2 c d a b (Int32.add data.(3) 0xf4d50d87l) 14 in
+ let b = step2 b c d a (Int32.add data.(8) 0x455a14edl) 20 in
+ let a = step2 a b c d (Int32.add data.(13) 0xa9e3e905l) 5 in
+ let d = step2 d a b c (Int32.add data.(2) 0xfcefa3f8l) 9 in
+ let c = step2 c d a b (Int32.add data.(7) 0x676f02d9l) 14 in
+ let b = step2 b c d a (Int32.add data.(12) 0x8d2a4c8al) 20 in
+
+ let a = step3 a b c d (Int32.add data.(5) 0xfffa3942l) 4 in
+ let d = step3 d a b c (Int32.add data.(8) 0x8771f681l) 11 in
+ let c = step3 c d a b (Int32.add data.(11) 0x6d9d6122l) 16 in
+ let b = step3 b c d a (Int32.add data.(14) 0xfde5380cl) 23 in
+ let a = step3 a b c d (Int32.add data.(1) 0xa4beea44l) 4 in
+ let d = step3 d a b c (Int32.add data.(4) 0x4bdecfa9l) 11 in
+ let c = step3 c d a b (Int32.add data.(7) 0xf6bb4b60l) 16 in
+ let b = step3 b c d a (Int32.add data.(10) 0xbebfbc70l) 23 in
+ let a = step3 a b c d (Int32.add data.(13) 0x289b7ec6l) 4 in
+ let d = step3 d a b c (Int32.add data.(0) 0xeaa127fal) 11 in
+ let c = step3 c d a b (Int32.add data.(3) 0xd4ef3085l) 16 in
+ let b = step3 b c d a (Int32.add data.(6) 0x04881d05l) 23 in
+ let a = step3 a b c d (Int32.add data.(9) 0xd9d4d039l) 4 in
+ let d = step3 d a b c (Int32.add data.(12) 0xe6db99e5l) 11 in
+ let c = step3 c d a b (Int32.add data.(15) 0x1fa27cf8l) 16 in
+ let b = step3 b c d a (Int32.add data.(2) 0xc4ac5665l) 23 in
+
+ let a = step4 a b c d (Int32.add data.(0) 0xf4292244l) 6 in
+ let d = step4 d a b c (Int32.add data.(7) 0x432aff97l) 10 in
+ let c = step4 c d a b (Int32.add data.(14) 0xab9423a7l) 15 in
+ let b = step4 b c d a (Int32.add data.(5) 0xfc93a039l) 21 in
+ let a = step4 a b c d (Int32.add data.(12) 0x655b59c3l) 6 in
+ let d = step4 d a b c (Int32.add data.(3) 0x8f0ccc92l) 10 in
+ let c = step4 c d a b (Int32.add data.(10) 0xffeff47dl) 15 in
+ let b = step4 b c d a (Int32.add data.(1) 0x85845dd1l) 21 in
+ let a = step4 a b c d (Int32.add data.(8) 0x6fa87e4fl) 6 in
+ let d = step4 d a b c (Int32.add data.(15) 0xfe2ce6e0l) 10 in
+ let c = step4 c d a b (Int32.add data.(6) 0xa3014314l) 15 in
+ let b = step4 b c d a (Int32.add data.(13) 0x4e0811a1l) 21 in
+ let a = step4 a b c d (Int32.add data.(4) 0xf7537e82l) 6 in
+ let d = step4 d a b c (Int32.add data.(11) 0xbd3af235l) 10 in
+ let c = step4 c d a b (Int32.add data.(2) 0x2ad7d2bbl) 15 in
+ let b = step4 b c d a (Int32.add data.(9) 0xeb86d391l) 21 in
+
+ ctx.a <- Int32.add ctx.a a;
+ ctx.b <- Int32.add ctx.b b;
+ ctx.c <- Int32.add ctx.c c;
+ ctx.d <- Int32.add ctx.d d
+
+let string_to_data s =
+ let data = Array.make 16 0l in
+ for i = 0 to 15 do
+ let j = i lsl 2 in
+ data.(i) <-
+ Int32.logor (Int32.shift_left (Int32.of_int (Char.code s.[j+3])) 24)
+ (Int32.logor (Int32.shift_left (Int32.of_int (Char.code s.[j+2])) 16)
+ (Int32.logor (Int32.shift_left (Int32.of_int (Char.code s.[j+1])) 8)
+ (Int32.of_int (Char.code s.[j]))))
+ done;
+ data
+
+let int32_to_string n s i =
+ s.[i+3] <- Char.chr (Int32.to_int (Int32.shift_right n 24) land 0xFF);
+ s.[i+2] <- Char.chr (Int32.to_int (Int32.shift_right n 16) land 0xFF);
+ s.[i+1] <- Char.chr (Int32.to_int (Int32.shift_right n 8) land 0xFF);
+ s.[i] <- Char.chr (Int32.to_int n land 0xFF)
+
+let init () =
+ { buf = String.create 64;
+ pos = 0;
+ a = 0x67452301l;
+ b = 0xefcdab89l;
+ c = 0x98badcfel;
+ d = 0x10325476l;
+ bits = 0L }
+
+let update ctx input ofs len =
+ let rec upd ofs len =
+ if len <= 0 then () else
+ if ctx.pos + len < 64 then begin
+ (* Just buffer the data *)
+ String.blit input ofs ctx.buf ctx.pos len;
+ ctx.pos <- ctx.pos + len
+ end else begin
+ (* Fill the buffer *)
+ let len' = 64 - ctx.pos in
+ if len' > 0 then String.blit input ofs ctx.buf ctx.pos len';
+ (* Transform 64 bytes *)
+ transform ctx (string_to_data ctx.buf);
+ ctx.pos <- 0;
+ upd (ofs + len') (len - len')
+ end in
+ upd ofs len;
+ ctx.bits <- Int64.add ctx.bits (Int64.of_int (len lsl 3))
+
+
+let finish ctx =
+ let padding = String.make 64 '\000' in
+ padding.[0] <- '\x80';
+ let numbits = ctx.bits in
+ if ctx.pos < 56 then begin
+ update ctx padding 0 (56 - ctx.pos)
+ end else begin
+ update ctx padding 0 (64 + 56 - ctx.pos)
+ end;
+ assert (ctx.pos = 56);
+ let data = string_to_data ctx.buf in
+ data.(14) <- (Int64.to_int32 numbits);
+ data.(15) <- (Int64.to_int32 (Int64.shift_right_logical numbits 32));
+ transform ctx data;
+ let res = String.create 16 in
+ int32_to_string ctx.a res 0;
+ int32_to_string ctx.b res 4;
+ int32_to_string ctx.c res 8;
+ int32_to_string ctx.d res 12;
+ res
+
+let test hex s =
+ let ctx = init() in
+ update ctx s 0 (String.length s);
+ let res = finish ctx in
+ let exp = Digest.string s in
+ let ok = res = exp && Digest.to_hex exp = hex in
+ if not ok then
+ Printf.printf "Failure for %S : %S %S %S %S\n" s res exp
+ (Digest.to_hex exp) hex;
+ ok
+
+let time msg iter fn =
+ let start = Sys.time() in
+ for i = 1 to iter do fn () done;
+ let stop = Sys.time() in
+ printf "%s: %.2f s\n" msg (stop -. start)
+
+let _ =
+ (* Test *)
+ if test "d41d8cd98f00b204e9800998ecf8427e" ""
+ && test "0cc175b9c0f1b6a831c399e269772661" "a"
+ && test "900150983cd24fb0d6963f7d28e17f72" "abc"
+ && test "8215ef0796a20bcaaae116d3876c664a"
+ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
+ && test "7707d6ae4e027c70eea2a935c2296f21" (String.make 1_000_000 'a')
+ && test "f96b697d7cb7938d525a2f31aaf161d0" "message digest"
+ && test "d174ab98d277d9f5a5611c2c9f419d9f"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
+ && test "9e107d9d372bb6826bd81d3542a419d6"
+ "The quick brown fox jumps over the lazy dog"
+ && test "e4d909c290d0fb1ca068ffaddf22cbd0"
+ "The quick brown fox jumps over the lazy dog."
+ then printf "Test vectors passed.\n";
+ flush stdout;
+ (* Benchmark *)
+ if (Array.length Sys.argv) > 1 && (Sys.argv.(1) = "-benchmark") then begin
+ let s = String.make 50000 'a' in
+ let num_iter = 1000 in
+ time "OCaml implementation" num_iter
+ (fun () ->
+ let ctx = init() in
+ update ctx s 0 (String.length s);
+ ignore (finish ctx));
+ time "C implementation" num_iter
+ (fun () -> ignore (Digest.string s))
+ end
diff --git a/testsuite/tests/lib-digest/md5.reference b/testsuite/tests/lib-digest/md5.reference
new file mode 100644
index 0000000000..956ac65448
--- /dev/null
+++ b/testsuite/tests/lib-digest/md5.reference
@@ -0,0 +1 @@
+Test vectors passed.
diff --git a/testsuite/tests/lib-dynlink-bytecode/.ignore b/testsuite/tests/lib-dynlink-bytecode/.ignore
new file mode 100644
index 0000000000..06b6473695
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/.ignore
@@ -0,0 +1,6 @@
+main
+static
+custom
+custom.exe
+marshal.data
+caml
diff --git a/testsuite/tests/lib-dynlink-bytecode/Makefile b/testsuite/tests/lib-dynlink-bytecode/Makefile
new file mode 100644
index 0000000000..28d6f1402f
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/Makefile
@@ -0,0 +1,70 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+COMPFLAGS=-I $(OTOPDIR)/otherlibs/dynlink
+LD_PATH=.:$(TOPDIR)/otherlibs/dynlink
+
+.PHONY: default
+default:
+ @if ! $(SUPPORTS_SHARED_LIBRARIES); then \
+ echo 'skipped (shared libraries not available)'; \
+ else \
+ $(SET_LD_PATH) $(MAKE) compile run; \
+ fi
+
+.PHONY: compile
+compile:
+ @$(OCAMLC) -c registry.ml
+ @for file in stub*.c; do \
+ $(OCAMLC) -ccopt -I -ccopt $(CTOPDIR)/byterun -c $$file; \
+ $(OCAMLMKLIB) -o `echo $$file | sed -e 's/stub/plug/' -e 's/\.c//'` \
+ `basename $$file c`$(O); \
+ done
+ @for file in plug*.ml; do \
+ $(OCAMLC) -c $$file; \
+ $(OCAMLMKLIB) -o `basename $$file .ml` `basename $$file ml`cmo; \
+ done
+ @$(OCAMLC) -c main.ml
+ @rm -f main static custom custom.exe
+ @$(OCAMLC) -o main dynlink.cma registry.cmo main.cmo
+ @$(OCAMLC) -o static -linkall registry.cmo plug1.cma plug2.cma \
+ -use-runtime $(OTOPDIR)/boot/ocamlrun$(EXE)
+ @$(OCAMLC) -o custom$(EXE) -custom -linkall registry.cmo plug2.cma \
+ plug1.cma -I .
+
+.PHONY: run
+run:
+ @printf " ... testing 'main'"
+ @$(OCAMLRUN) ./main plug1.cma plug2.cma >main.result
+ @$(DIFF) main.reference main.result >/dev/null \
+ && echo " => passed" || echo " => failed"
+
+ @printf " ... testing 'static'"
+ @$(OCAMLRUN) ./static >static.result
+ @$(DIFF) static.reference static.result >/dev/null \
+ && echo " => passed" || echo " => failed"
+
+ @printf " ... testing 'custom'"
+ @./custom$(EXE) >custom.result
+ @$(DIFF) custom.reference custom.result >/dev/null \
+ && echo " => passed" || echo " => failed"
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f main static custom custom.exe *.result marshal.data
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-dynlink-bytecode/custom.reference b/testsuite/tests/lib-dynlink-bytecode/custom.reference
new file mode 100644
index 0000000000..c9d2b57582
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/custom.reference
@@ -0,0 +1,5 @@
+This is stub2, calling stub1:
+This is stub1!
+Ok!
+This is stub1!
+ABCDEF
diff --git a/testsuite/tests/lib-dynlink-bytecode/main.ml b/testsuite/tests/lib-dynlink-bytecode/main.ml
new file mode 100644
index 0000000000..936553353f
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/main.ml
@@ -0,0 +1,49 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let f x = print_string "This is Main.f\n"; x
+
+let () = Registry.register f
+
+let _ =
+ Dynlink.init ();
+ Dynlink.allow_unsafe_modules true;
+ for i = 1 to Array.length Sys.argv - 1 do
+ let name = Sys.argv.(i) in
+ Printf.printf "Loading %s\n" name; flush stdout;
+ try
+ if name.[0] = '-'
+ then Dynlink.loadfile_private
+ (String.sub name 1 (String.length name - 1))
+ else Dynlink.loadfile name
+ with
+ | Dynlink.Error err ->
+ Printf.printf "Dynlink error: %s\n"
+ (Dynlink.error_message err)
+ | exn ->
+ Printf.printf "Error: %s\n" (Printexc.to_string exn)
+ done;
+ flush stdout;
+ try
+ let oc = open_out_bin "marshal.data" in
+ Marshal.to_channel oc (Registry.get_functions()) [Marshal.Closures];
+ close_out oc;
+ let ic = open_in_bin "marshal.data" in
+ let l = (Marshal.from_channel ic : (int -> int) list) in
+ close_in ic;
+ List.iter
+ (fun f ->
+ let res = f 0 in
+ Printf.printf "Result is: %d\n" res)
+ l
+ with Failure s ->
+ Printf.printf "Failure: %s\n" s
diff --git a/testsuite/tests/lib-dynlink-bytecode/main.reference b/testsuite/tests/lib-dynlink-bytecode/main.reference
new file mode 100644
index 0000000000..577292f9aa
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/main.reference
@@ -0,0 +1,13 @@
+Loading plug1.cma
+This is stub1!
+ABCDEF
+Loading plug2.cma
+This is stub2, calling stub1:
+This is stub1!
+Ok!
+This is Plug2.f
+Result is: 2
+This is Plug1.f
+Result is: 1
+This is Main.f
+Result is: 0
diff --git a/testsuite/tests/lib-dynlink-bytecode/plug1.ml b/testsuite/tests/lib-dynlink-bytecode/plug1.ml
new file mode 100644
index 0000000000..6ff307624d
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/plug1.ml
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+external stub1: unit -> string = "stub1"
+
+let f x = print_string "This is Plug1.f\n"; x + 1
+
+let () = Registry.register f
+
+let () = print_endline (stub1 ())
diff --git a/testsuite/tests/lib-dynlink-bytecode/plug2.ml b/testsuite/tests/lib-dynlink-bytecode/plug2.ml
new file mode 100644
index 0000000000..e83275e524
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/plug2.ml
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+external stub2: unit -> unit = "stub2"
+
+let f x = print_string "This is Plug2.f\n"; x + 2
+
+let () = Registry.register f
+
+let () = stub2 ()
diff --git a/testsuite/tests/lib-dynlink-bytecode/registry.ml b/testsuite/tests/lib-dynlink-bytecode/registry.ml
new file mode 100644
index 0000000000..46915a1bfd
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/registry.ml
@@ -0,0 +1,19 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let functions = ref ([]: (int -> int) list)
+
+let register f =
+ functions := f :: !functions
+
+let get_functions () =
+ !functions
diff --git a/testsuite/tests/lib-dynlink-bytecode/static.reference b/testsuite/tests/lib-dynlink-bytecode/static.reference
new file mode 100644
index 0000000000..4faa129c34
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/static.reference
@@ -0,0 +1,5 @@
+This is stub1!
+ABCDEF
+This is stub2, calling stub1:
+This is stub1!
+Ok!
diff --git a/testsuite/tests/lib-dynlink-bytecode/stub1.c b/testsuite/tests/lib-dynlink-bytecode/stub1.c
new file mode 100644
index 0000000000..60c8ab35ae
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/stub1.c
@@ -0,0 +1,24 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Alain Frisch, LexiFi */
+/* */
+/* Copyright 2007 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+#include "caml/alloc.h"
+#include <stdio.h>
+
+value stub1() {
+ CAMLparam0();
+ CAMLlocal1(x);
+ printf("This is stub1!\n"); fflush(stdout);
+ x = caml_copy_string("ABCDEF");
+ CAMLreturn(x);
+}
diff --git a/testsuite/tests/lib-dynlink-bytecode/stub2.c b/testsuite/tests/lib-dynlink-bytecode/stub2.c
new file mode 100644
index 0000000000..4064a75eec
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-bytecode/stub2.c
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Alain Frisch, LexiFi */
+/* */
+/* Copyright 2007 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+#include "caml/alloc.h"
+#include <stdio.h>
+
+extern value stub1();
+
+value stub2() {
+ printf("This is stub2, calling stub1:\n"); fflush(stdout);
+ stub1();
+ printf("Ok!\n"); fflush(stdout);
+ return Val_unit;
+}
diff --git a/testsuite/tests/lib-dynlink-csharp/Makefile b/testsuite/tests/lib-dynlink-csharp/Makefile
new file mode 100644
index 0000000000..c576a09909
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-csharp/Makefile
@@ -0,0 +1,101 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+CSC=csc
+
+COMPFLAGS=-I $(OTOPDIR)/otherlibs/bigarray
+LD_PATH=$(TOPDIR)/otherlibs/bigarray
+
+.PHONY: default
+default:
+ @if ! $(SUPPORTS_SHARED_LIBRARIES); then \
+ echo 'skipped (shared libraries not available)'; \
+ elif $(BYTECODE_ONLY); then \
+ echo 'skipped (native compiler not available)' ; \
+ else \
+ $(SET_LD_PATH) $(MAKE) all; \
+ fi
+
+.PHONY: all
+all: prepare bytecode bytecode-dll native native-dll
+
+.PHONY: prepare
+prepare:
+ @$(OCAMLC) -c plugin.ml
+ @$(OCAMLOPT) -o plugin.cmxs -shared plugin.ml
+
+.PHONY: bytecode
+bytecode:
+ @printf " ... testing 'bytecode':"
+ @if [ ! `which $(CSC) >/dev/null 2>&1` ]; then \
+ echo " => skipped"; \
+ else \
+ $(OCAMLC) -output-obj -o main.dll dynlink.cma main.ml entry.c; \
+ $(CSC) /out:main.exe main.cs; \
+ ./main.exe > bytecode.result; \
+ $(DIFF) bytecode.reference bytecode.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ fi
+
+.PHONY: bytecode-dll
+bytecode-dll:
+ @printf " ... testing 'bytecode-dll':"
+ @if [ ! `which $(CSC) > /dev/null 2>&1` ]; then \
+ echo " => skipped"; \
+ else \
+ $(OCAMLC) -output-obj -o main_obj.$(O) dynlink.cma entry.c main.ml; \
+ $(MKDLL) -maindll -o main.dll main_obj.$(O) entry.$(O) \
+ ../../byterun/libcamlrun.$(A) $(BYTECCLIBS) -v; \
+ $(CSC) /out:main.exe main.cs; \
+ ./main.exe >bytecode.result; \
+ $(DIFF) bytecode.reference bytecode.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ fi
+
+.PHONY: native
+native:
+ @printf " ... testing 'native':"
+ @if [ ! `which $(CSC) > /dev/null 2>&1` ]; then \
+ echo " => skipped"; \
+ else \
+ $(OCAMLOPT) -output-obj -o main.dll dynlink.cmxa entry.c main.ml; \
+ $(CSC) /out:main.exe main.cs; \
+ ./main.exe > native.result; \
+ $(DIFF) native.reference native.result > /dev/null \
+ && echo " => passed" || echo " => failed"; \
+ fi
+
+.PHONY: native-dll
+native-dll:
+ @printf " ... testing 'native-dll':"
+ @if [ ! `which $(CSC) > /dev/null 2>&1` ]; then \
+ echo " => skipped"; \
+ else \
+ $(OCAMLOPT) -output-obj -o main_obj.$(O) dynlink.cmxa entry.c \
+ main.ml; \
+ $(MKDLL) -maindll -o main.dll main_obj.$(O) entry.$(O) \
+ ../../asmrun/libasmrun.lib -v; \
+ $(CSC) /out:main.exe main.cs; \
+ ./main.exe > native.result; \
+ $(DIFF) native.reference native.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ fi
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result *.exe *.dll *.so *.obj *.o
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-dynlink-csharp/bytecode.reference b/testsuite/tests/lib-dynlink-csharp/bytecode.reference
new file mode 100644
index 0000000000..a76daa2309
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-csharp/bytecode.reference
@@ -0,0 +1,7 @@
+Now starting the OCaml engine.
+Main is running.
+Loading ../../../otherlibs/bigarray/bigarray.cma
+I'm the plugin.
+Loading plugin.cmo
+I'm the plugin.
+OK.
diff --git a/testsuite/tests/lib-dynlink-csharp/entry.c b/testsuite/tests/lib-dynlink-csharp/entry.c
new file mode 100755
index 0000000000..b5d11636ef
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-csharp/entry.c
@@ -0,0 +1,41 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Alain Frisch, LexiFi */
+/* */
+/* Copyright 2007 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <caml/memory.h>
+#include <caml/alloc.h>
+#include <caml/mlvalues.h>
+#include <caml/callback.h>
+#include <caml/custom.h>
+#include <caml/fail.h>
+
+#if !defined(OPENSTEP) && (defined(__WIN32__) && !defined(__CYGWIN__))
+# if defined(_MSC_VER) || defined(__MINGW32__)
+# define _DLLAPI __declspec(dllexport)
+# else
+# define _DLLAPI extern
+# endif
+# if defined(__MINGW32__) || defined(UNDER_CE)
+# define _CALLPROC
+# else
+# define _CALLPROC __stdcall
+# endif
+#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 303
+# define _DLLAPI __attribute__((visibility("default")))
+# define _CALLPROC
+#endif /* WIN32 && !CYGWIN */
+
+_DLLAPI void _CALLPROC start_caml_engine() {
+ char * argv[2];
+ argv[0] = "--";
+ argv[1] = NULL;
+ caml_startup(argv);
+}
diff --git a/testsuite/tests/lib-dynlink-csharp/main.cs b/testsuite/tests/lib-dynlink-csharp/main.cs
new file mode 100755
index 0000000000..5cbb8e8689
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-csharp/main.cs
@@ -0,0 +1,11 @@
+using System.Runtime.InteropServices;
+
+public class M {
+ [DllImport("main.dll")]
+ public static extern void start_caml_engine();
+
+ public static void Main() {
+ System.Console.WriteLine("Now starting the OCaml engine.");
+ start_caml_engine();
+ }
+}
diff --git a/testsuite/tests/lib-dynlink-csharp/main.ml b/testsuite/tests/lib-dynlink-csharp/main.ml
new file mode 100755
index 0000000000..079e3deb3e
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-csharp/main.ml
@@ -0,0 +1,34 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let load s =
+ Printf.printf "Loading %s\n%!" s;
+ try
+ Dynlink.loadfile s
+ with Dynlink.Error e ->
+ print_endline (Dynlink.error_message e)
+
+let () =
+ print_endline "Main is running.";
+ Dynlink.init ();
+ Dynlink.allow_unsafe_modules true;
+ let s1,s2 =
+ if Dynlink.is_native then
+ "../../../otherlibs/bigarray/bigarray.cmxs",
+ "plugin.cmxs"
+ else
+ "../../../otherlibs/bigarray/bigarray.cma",
+ "plugin.cmo"
+ in
+ load s1;
+ load s2;
+ print_endline "OK."
diff --git a/testsuite/tests/lib-dynlink-csharp/native.reference b/testsuite/tests/lib-dynlink-csharp/native.reference
new file mode 100644
index 0000000000..684f979a8f
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-csharp/native.reference
@@ -0,0 +1,7 @@
+Now starting the OCaml engine.
+Main is running.
+Loading ../../../otherlibs/bigarray/bigarray.cmxs
+I'm the plugin.
+Loading plugin.cmxs
+I'm the plugin.
+OK.
diff --git a/testsuite/tests/lib-dynlink-csharp/plugin.ml b/testsuite/tests/lib-dynlink-csharp/plugin.ml
new file mode 100755
index 0000000000..71f2790cdf
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-csharp/plugin.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+open Bigarray
+let f x = x.{2}
+
+let () =
+ print_endline "I'm the plugin."
diff --git a/testsuite/tests/lib-dynlink-native/.ignore b/testsuite/tests/lib-dynlink-native/.ignore
new file mode 100644
index 0000000000..2dd2c724a8
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/.ignore
@@ -0,0 +1,7 @@
+mypack.pack.s
+mypack.pack.asm
+result
+main
+main.exe
+marshal.data
+caml
diff --git a/testsuite/tests/lib-dynlink-native/Makefile b/testsuite/tests/lib-dynlink-native/Makefile
new file mode 100644
index 0000000000..38d298e8e6
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/Makefile
@@ -0,0 +1,122 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+COMPFLAGS=-I $(OTOPDIR)/otherlibs/$(UNIXLIBVAR)unix \
+ -I $(OTOPDIR)/otherlibs/systhreads \
+ -I $(OTOPDIR)/otherlibs/dynlink
+LD_PATH = $(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix:$(TOPDIR)/otherlibs/systhreads\
+:$(TOPDIR)/otherlibs/dynlink
+
+.PHONY: default
+default:
+ @if ! $(SUPPORTS_SHARED_LIBRARIES); then \
+ echo 'skipped (shared libraries not available)'; \
+ elif $(BYTECODE_ONLY); then \
+ echo 'skipped (native compiler not available)' ; \
+ else \
+ $(SET_LD_PATH) $(MAKE) all; \
+ fi
+
+.PHONY: all
+all: compile run
+
+PLUGINS=plugin.so plugin2.so sub/plugin.so sub/plugin3.so plugin4.so \
+ mypack.so packed1.so packed1_client.so pack_client.so plugin_ref.so \
+ plugin_high_arity.so plugin_ext.so plugin_simple.so bug.so \
+ plugin_thread.so plugin4_unix.so a.so b.so c.so
+
+ADD_COMPFLAGS=-thread
+
+.PHONY: compile
+compile: $(PLUGINS) main$(EXE) mylib.so
+
+.PHONY: run
+run:
+ @printf " ... testing 'main'"
+ @./main$(EXE) plugin.so plugin2.so plugin_thread.so > result
+ @$(DIFF) reference result >/dev/null \
+ && echo " => passed" || echo " => failed"
+
+main$(EXE): api.cmx main.cmx
+ @$(OCAMLOPT) -thread -o main$(EXE) -linkall unix.cmxa threads.cmxa \
+ dynlink.cmxa api.cmx main.cmx
+
+main_ext$(EXE): api.cmx main.cmx factorial.$(O)
+ @$(OCAMLOPT) -o main_ext$(EXE) dynlink.cmxa api.cmx main.cmx \
+ factorial.$(O)
+
+sub/plugin3.cmx: sub/api.cmi sub/api.cmx sub/plugin3.ml
+ @cd sub; \
+ mv api.cmx api.cmx.bak; \
+ $(OCAMLOPT) -c plugin3.ml; \
+ mv api.cmx.bak api.cmx
+
+plugin2.cmx: api.cmx plugin.cmi plugin.cmx
+ @mv plugin.cmx plugin.cmx.bak;
+ @$(OCAMLOPT) -c plugin2.ml
+ @mv plugin.cmx.bak plugin.cmx
+
+sub/api.so: sub/api.cmi sub/api.ml
+ @cd sub; $(OCAMLOPT) -c $(SHARED) api.ml
+
+sub/api.cmi: sub/api.mli
+ @cd sub; $(OCAMLOPT) -c api.mli
+
+sub/api.cmx: sub/api.cmi sub/api.ml
+ @cd sub; $(OCAMLOPT) -c api.ml
+
+plugin.cmx: api.cmx plugin.cmi
+sub/plugin.cmx: api.cmx
+plugin4.cmx: api.cmx
+main.cmx: api.cmx
+plugin_ext.cmx: api.cmx plugin_ext.ml
+ @$(OCAMLOPT) -c plugin_ext.ml
+
+plugin_ext.so: factorial.$(O) plugin_ext.cmx
+ @$(OCAMLOPT) -shared -o plugin_ext.so factorial.$(O) \
+ plugin_ext.cmx
+
+plugin4_unix.so: plugin4.cmx
+ @$(OCAMLOPT) -shared -o plugin4_unix.so unix.cmxa plugin4.cmx
+
+packed1_client.cmx: packed1.cmx
+
+pack_client.cmx: mypack.cmx
+
+packed1.cmx: api.cmx packed1.ml
+ @$(OCAMLOPT) -c $(COMPFLAGS) -for-pack Mypack packed1.ml
+
+mypack.cmx: packed1.cmx
+ @$(OCAMLOPT) $(COMPFLAGS) -S -pack -o mypack.cmx packed1.cmx
+
+mylib.cmxa: plugin.cmx plugin2.cmx
+ @$(OCAMLOPT) $(COMPFLAGS) -a -o mylib.cmxa plugin.cmx plugin2.cmx
+
+factorial.$(O): factorial.c
+ @$(OCAMLOPT) -c -ccopt "$(SHAREDCCCOMPOPTS)" -ccopt -I \
+ -ccopt $(CTOPDIR)/byterun \
+ factorial.c
+
+.PHONY: promote
+promote:
+ @cp result reference
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f result *.so *.o *.cm* main main_ext *.exe *.s *.asm *.obj
+ @rm -f *.a *.lib
+ @rm -f sub/*.so sub/*.o sub/*.cm* sub/*.s sub/*.asm sub/*.obj
+ @rm -f marshal.data
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-dynlink-native/a.ml b/testsuite/tests/lib-dynlink-native/a.ml
new file mode 100755
index 0000000000..c84f96803f
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/a.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let x = ref 0
+let u = Random.int 1000
+
+let () =
+ Printf.printf "A is running (%i)\n%!" u
diff --git a/testsuite/tests/lib-dynlink-native/api.ml b/testsuite/tests/lib-dynlink-native/api.ml
new file mode 100644
index 0000000000..8415000282
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/api.ml
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let mods = ref []
+
+let reg_mod name =
+ if List.mem name !mods then
+ Printf.printf "Reloading module %s\n" name
+ else (
+ mods := name :: !mods;
+ Printf.printf "Registering module %s\n" name
+ )
+
+
+let cbs = ref []
+
+let add_cb f = cbs := f :: !cbs
+let runall () = List.iter (fun f -> f ()) !cbs
+
+(*
+let () =
+ at_exit runall
+*)
diff --git a/testsuite/tests/lib-dynlink-native/b.ml b/testsuite/tests/lib-dynlink-native/b.ml
new file mode 100755
index 0000000000..02091da408
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/b.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ print_endline "B is running";
+ incr A.x;
+ Printf.printf "A.x = %i\n" !A.x
diff --git a/testsuite/tests/lib-dynlink-native/bug.ml b/testsuite/tests/lib-dynlink-native/bug.ml
new file mode 100644
index 0000000000..8965c928f1
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/bug.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () = try raise (Invalid_argument "X") with Invalid_argument s ->
+ raise (Invalid_argument (s ^ s))
diff --git a/testsuite/tests/lib-dynlink-native/c.ml b/testsuite/tests/lib-dynlink-native/c.ml
new file mode 100755
index 0000000000..a9bfc8b606
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/c.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ print_endline "C is running";
+ incr A.x;
+ Printf.printf "A.x = %i\n" !A.x
diff --git a/testsuite/tests/lib-dynlink-native/factorial.c b/testsuite/tests/lib-dynlink-native/factorial.c
new file mode 100644
index 0000000000..941227dd58
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/factorial.c
@@ -0,0 +1,30 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Alain Frisch, LexiFi */
+/* */
+/* Copyright 2007 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include "caml/mlvalues.h"
+#include "caml/memory.h"
+#include "caml/alloc.h"
+#include <stdio.h>
+
+value factorial(value n){
+ CAMLparam1(n);
+ CAMLlocal1(s);
+
+ static char buf[256];
+ int x = 1;
+ int i;
+ int m = Int_val(n);
+ for (i = 1; i <= m; i++) x *= i;
+ sprintf(buf,"%i",x);
+ s = copy_string(buf);
+ CAMLreturn (s);
+}
diff --git a/testsuite/tests/lib-dynlink-native/main.ml b/testsuite/tests/lib-dynlink-native/main.ml
new file mode 100644
index 0000000000..01ed2295ca
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/main.ml
@@ -0,0 +1,44 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ Api.add_cb (fun () -> print_endline "Callback from main")
+
+let () =
+ Dynlink.init ();
+ Dynlink.allow_unsafe_modules true;
+ for i = 1 to Array.length Sys.argv - 1 do
+ let name = Sys.argv.(i) in
+ Printf.printf "Loading %s\n" name; flush stdout;
+ try
+ if name.[0] = '-'
+ then Dynlink.loadfile_private
+ (String.sub name 1 (String.length name - 1))
+ else Dynlink.loadfile name
+ with
+ | Dynlink.Error err ->
+ Printf.printf "Dynlink error: %s\n"
+ (Dynlink.error_message err)
+ | exn ->
+ Printf.printf "Error: %s\n" (Printexc.to_string exn)
+ done;
+ flush stdout;
+ try
+ let oc = open_out_bin "marshal.data" in
+ Marshal.to_channel oc !Api.cbs [Marshal.Closures];
+ close_out oc;
+ let ic = open_in_bin "marshal.data" in
+ let l = (Marshal.from_channel ic : (unit -> unit) list) in
+ close_in ic;
+ List.iter (fun f -> f()) l
+ with Failure s ->
+ Printf.printf "Failure: %s\n" s
diff --git a/testsuite/tests/lib-dynlink-native/pack_client.ml b/testsuite/tests/lib-dynlink-native/pack_client.ml
new file mode 100644
index 0000000000..354d3694bc
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/pack_client.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ print_endline Mypack.Packed1.mykey
diff --git a/testsuite/tests/lib-dynlink-native/packed1.ml b/testsuite/tests/lib-dynlink-native/packed1.ml
new file mode 100644
index 0000000000..845a3c24d4
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/packed1.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ Api.reg_mod "Packed1"
+
+let bla = Sys.argv.(0) ^ "XXX"
+let mykey = Sys.argv.(0)
diff --git a/testsuite/tests/lib-dynlink-native/packed1_client.ml b/testsuite/tests/lib-dynlink-native/packed1_client.ml
new file mode 100644
index 0000000000..5950b66835
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/packed1_client.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ Api.reg_mod "Packed1_client";
+ print_endline Packed1.mykey
diff --git a/testsuite/tests/lib-dynlink-native/plugin.ml b/testsuite/tests/lib-dynlink-native/plugin.ml
new file mode 100644
index 0000000000..302ba30a69
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin.ml
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec f x = ignore ([x]); f x
+
+let rec fact n = if n = 0 then 1 else n * fact (n - 1)
+
+let facts = [ fact 1; fact 2; fact 3; fact (Random.int 4) ]
+
+let () =
+ Api.reg_mod "Plugin";
+ Api.add_cb (fun () -> print_endline "Callback from plugin");
+ print_endline "COUCOU";
+ ()
diff --git a/testsuite/tests/lib-dynlink-native/plugin.mli b/testsuite/tests/lib-dynlink-native/plugin.mli
new file mode 100644
index 0000000000..5ce837bf20
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin.mli
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val facts: int list
diff --git a/testsuite/tests/lib-dynlink-native/plugin2.ml b/testsuite/tests/lib-dynlink-native/plugin2.ml
new file mode 100644
index 0000000000..e7e9fb3c50
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin2.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*external ex: int -> int = "caml_ex"*)
+
+let () =
+ Api.reg_mod "Plugin2";
+ Api.add_cb (fun () -> print_endline "Callback from plugin2");
+(* let i = ex 3 in*)
+ List.iter (fun i -> Printf.printf "%i\n" i) Plugin.facts;
+ Printf.printf "XXX\n"
diff --git a/testsuite/tests/lib-dynlink-native/plugin4.ml b/testsuite/tests/lib-dynlink-native/plugin4.ml
new file mode 100644
index 0000000000..5d0d33eb48
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin4.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ Printf.printf "time = %f\n" (Unix.time ());
+ Api.reg_mod "Plugin"
diff --git a/testsuite/tests/lib-dynlink-native/plugin_ext.ml b/testsuite/tests/lib-dynlink-native/plugin_ext.ml
new file mode 100644
index 0000000000..ea9ec85ce1
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin_ext.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+external fact: int -> string = "factorial"
+
+let () =
+ Api.reg_mod "plugin_ext";
+ Printf.printf "fact 10 = %s\n" (fact 10)
diff --git a/testsuite/tests/lib-dynlink-native/plugin_high_arity.ml b/testsuite/tests/lib-dynlink-native/plugin_high_arity.ml
new file mode 100644
index 0000000000..49a5fde9e7
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin_high_arity.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let f x x x x x x x x x x x x x = ()
+
+let g x = f x x x x x x x x
+
+let () =
+ Api.reg_mod "HA"
diff --git a/testsuite/tests/lib-dynlink-native/plugin_ref.ml b/testsuite/tests/lib-dynlink-native/plugin_ref.ml
new file mode 100644
index 0000000000..df98431bd2
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin_ref.ml
@@ -0,0 +1,22 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let x = ref 0
+
+let () =
+ Api.reg_mod "Plugin_ref";
+
+ Api.add_cb
+ (fun () ->
+ Printf.printf "current value for ref = %i\n" !x;
+ incr x
+ )
diff --git a/testsuite/tests/lib-dynlink-native/plugin_simple.ml b/testsuite/tests/lib-dynlink-native/plugin_simple.ml
new file mode 100644
index 0000000000..cc87b3b915
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin_simple.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let facts = [ (Random.int 4) ]
+
+let () = print_endline "COUCOU"; print_char '\n'
diff --git a/testsuite/tests/lib-dynlink-native/plugin_thread.ml b/testsuite/tests/lib-dynlink-native/plugin_thread.ml
new file mode 100644
index 0000000000..725d5a1019
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/plugin_thread.ml
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ Api.reg_mod "Plugin_thread";
+ let _t =
+ Thread.create
+ (fun () ->
+ for i = 1 to 5 do
+ print_endline "Thread"; flush stdout;
+ Thread.delay 1.;
+ done
+ ) ()
+ in
+ for i = 1 to 10 do
+ print_endline "Thread"; flush stdout;
+ Thread.delay 0.50;
+ done
diff --git a/testsuite/tests/lib-dynlink-native/reference b/testsuite/tests/lib-dynlink-native/reference
new file mode 100644
index 0000000000..e9e4ee45dd
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/reference
@@ -0,0 +1,30 @@
+Loading plugin.so
+Registering module Plugin
+COUCOU
+Loading plugin2.so
+Registering module Plugin2
+1
+2
+6
+1
+XXX
+Loading plugin_thread.so
+Registering module Plugin_thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Thread
+Callback from plugin2
+Callback from plugin
+Callback from main
diff --git a/testsuite/tests/lib-dynlink-native/sub/api.ml b/testsuite/tests/lib-dynlink-native/sub/api.ml
new file mode 100644
index 0000000000..476103ed61
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/sub/api.ml
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let f i =
+ Printf.printf "Sub/api: f called with %i\n" i;
+ i + 1
diff --git a/testsuite/tests/lib-dynlink-native/sub/api.mli b/testsuite/tests/lib-dynlink-native/sub/api.mli
new file mode 100644
index 0000000000..c4bb98bb64
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/sub/api.mli
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val f : int -> int
diff --git a/testsuite/tests/lib-dynlink-native/sub/plugin.ml b/testsuite/tests/lib-dynlink-native/sub/plugin.ml
new file mode 100644
index 0000000000..fb1039d982
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/sub/plugin.ml
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec fact n = if n = 0 then 1 else n * fact (n - 1)
+
+let facts = [ fact 1; fact 2; fact 3; fact 4; fact 5 ]
+
+let () =
+ Api.reg_mod "Plugin'"
diff --git a/testsuite/tests/lib-dynlink-native/sub/plugin3.ml b/testsuite/tests/lib-dynlink-native/sub/plugin3.ml
new file mode 100644
index 0000000000..e06fc38eaf
--- /dev/null
+++ b/testsuite/tests/lib-dynlink-native/sub/plugin3.ml
@@ -0,0 +1,14 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let () =
+ ignore (Api.f 10)
diff --git a/testsuite/tests/lib-format/Makefile b/testsuite/tests/lib-format/Makefile
new file mode 100644
index 0000000000..9805d2db42
--- /dev/null
+++ b/testsuite/tests/lib-format/Makefile
@@ -0,0 +1,17 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=testing
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-format/pr6824.ml b/testsuite/tests/lib-format/pr6824.ml
new file mode 100644
index 0000000000..aa5e7eed6d
--- /dev/null
+++ b/testsuite/tests/lib-format/pr6824.ml
@@ -0,0 +1,7 @@
+let f = Format.sprintf "[%i]";;
+print_endline (f 1);;
+print_endline (f 2);;
+
+let f = Format.asprintf "[%i]";;
+print_endline (f 1);;
+print_endline (f 2);;
diff --git a/testsuite/tests/lib-format/pr6824.reference b/testsuite/tests/lib-format/pr6824.reference
new file mode 100644
index 0000000000..69035c7649
--- /dev/null
+++ b/testsuite/tests/lib-format/pr6824.reference
@@ -0,0 +1,6 @@
+[1]
+[2]
+[1]
+[2]
+
+All tests succeeded.
diff --git a/testsuite/tests/lib-format/tformat.ml b/testsuite/tests/lib-format/tformat.ml
new file mode 100644
index 0000000000..13c6094bd1
--- /dev/null
+++ b/testsuite/tests/lib-format/tformat.ml
@@ -0,0 +1,511 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Pomdapi, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2011 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+(*
+
+A test file for the Format module.
+
+*)
+
+open Testing;;
+open Format;;
+
+let say s = Printf.printf s;;
+
+try
+
+ say "d/i positive\n%!";
+ test (sprintf "%d/%i" 42 43 = "42/43");
+ test (sprintf "%-4d/%-5i" 42 43 = "42 /43 ");
+ test (sprintf "%04d/%05i" 42 43 = "0042/00043");
+ test (sprintf "%+d/%+i" 42 43 = "+42/+43");
+ test (sprintf "% d/% i" 42 43 = " 42/ 43");
+ test (sprintf "%#d/%#i" 42 43 = "42/43");
+ test (sprintf "%4d/%5i" 42 43 = " 42/ 43");
+ test (sprintf "%*d" (-4) 42 = "42 ");
+ test (sprintf "%*d/%*i" 4 42 5 43 = " 42/ 43");
+ test (sprintf "%-0+#4d/%-0 #5i" 42 43 = "+42 / 43 ");
+
+ say "\nd/i negative\n%!";
+ test (sprintf "%d/%i" (-42) (-43) = "-42/-43");
+ test (sprintf "%-4d/%-5i" (-42) (-43) = "-42 /-43 ");
+ test (sprintf "%04d/%05i" (-42) (-43) = "-042/-0043");
+ test (sprintf "%+d/%+i" (-42) (-43) = "-42/-43");
+ test (sprintf "% d/% i" (-42) (-43) = "-42/-43");
+ test (sprintf "%#d/%#i" (-42) (-43) = "-42/-43");
+ test (sprintf "%4d/%5i" (-42) (-43) = " -42/ -43");
+ test (sprintf "%*d" (-4) (-42) = "-42 ");
+ test (sprintf "%*d/%*i" 4 (-42) 5 (-43) = " -42/ -43");
+ test (sprintf "%-0+ #4d/%-0+ #5i" (-42) (-43) = "-42 /-43 ");
+
+ say "\nu positive\n%!";
+ test (sprintf "%u" 42 = "42");
+ test (sprintf "%-4u" 42 = "42 ");
+ test (sprintf "%04u" 42 = "0042");
+ test (sprintf "%+u" 42 = "42");
+ test (sprintf "% u" 42 = "42");
+ test (sprintf "%#u" 42 = "42");
+ test (sprintf "%4u" 42 = " 42");
+ test (sprintf "%*u" 4 42 = " 42");
+ test (sprintf "%*u" (-4) 42 = "42 ");
+
+ say "\nu negative\n%!";
+ begin match Sys.word_size with
+ | 32 ->
+ test (sprintf "%u" (-1) = "2147483647");
+ | 64 ->
+ test (sprintf "%u" (-1) = "9223372036854775807");
+ | _ -> test false
+ end;
+
+ say "\nx positive\n%!";
+ test (sprintf "%x" 42 = "2a");
+ test (sprintf "%-4x" 42 = "2a ");
+ test (sprintf "%04x" 42 = "002a");
+ test (sprintf "%+x" 42 = "2a");
+ test (sprintf "% x" 42 = "2a");
+ test (sprintf "%#x" 42 = "0x2a");
+ test (sprintf "%4x" 42 = " 2a");
+ test (sprintf "%*x" 5 42 = " 2a");
+ test (sprintf "%*x" (-5) 42 = "2a ");
+ test (sprintf "%#*x" 5 42 = " 0x2a");
+ test (sprintf "%#*x" (-5) 42 = "0x2a ");
+ test (sprintf "%#-*x" 5 42 = "0x2a ");
+ test (sprintf "%-0+ #*x" 5 42 = "0x2a ");
+
+ say "\nx negative\n%!";
+ begin match Sys.word_size with
+ | 32 ->
+ test (sprintf "%x" (-42) = "7fffffd6");
+ | 64 ->
+ test (sprintf "%x" (-42) = "7fffffffffffffd6");
+ | _ -> test false
+ end;
+
+ say "\nX positive\n%!";
+ test (sprintf "%X" 42 = "2A");
+ test (sprintf "%-4X" 42 = "2A ");
+ test (sprintf "%04X" 42 = "002A");
+ test (sprintf "%+X" 42 = "2A");
+ test (sprintf "% X" 42 = "2A");
+ test (sprintf "%#X" 42 = "0X2A");
+ test (sprintf "%4X" 42 = " 2A");
+ test (sprintf "%*X" 5 42 = " 2A");
+ test (sprintf "%-0+ #*X" 5 42 = "0X2A ");
+
+ say "\nx negative\n%!";
+ begin match Sys.word_size with
+ | 32 ->
+ test (sprintf "%X" (-42) = "7FFFFFD6");
+ | 64 ->
+ test (sprintf "%X" (-42) = "7FFFFFFFFFFFFFD6");
+ | _ -> test false
+ end;
+
+ say "\no positive\n%!";
+ test (sprintf "%o" 42 = "52");
+ test (sprintf "%-4o" 42 = "52 ");
+ test (sprintf "%04o" 42 = "0052");
+ test (sprintf "%+o" 42 = "52");
+ test (sprintf "% o" 42 = "52");
+ test (sprintf "%#o" 42 = "052");
+ test (sprintf "%4o" 42 = " 52");
+ test (sprintf "%*o" 5 42 = " 52");
+ test (sprintf "%-0+ #*o" 5 42 = "052 ");
+
+ say "\no negative\n%!";
+ begin match Sys.word_size with
+ | 32 ->
+ test (sprintf "%o" (-42) = "17777777726");
+ | 64 ->
+ test (sprintf "%o" (-42) = "777777777777777777726");
+ | _ -> test false
+ end;
+
+ say "\ns\n%!";
+ test (sprintf "%s" "foo" = "foo");
+ test (sprintf "%-5s" "foo" = "foo ");
+ test (sprintf "%05s" "foo" = " foo");
+ test (sprintf "%+s" "foo" = "foo");
+ test (sprintf "% s" "foo" = "foo");
+ test (sprintf "%#s" "foo" = "foo");
+ test (sprintf "%5s" "foo" = " foo");
+ test (sprintf "%1s" "foo" = "foo");
+ test (sprintf "%*s" 6 "foo" = " foo");
+ test (sprintf "%*s" (-6) "foo" = "foo ");
+ test (sprintf "%*s" 2 "foo" = "foo");
+ test (sprintf "%-0+ #5s" "foo" = "foo ");
+ test (sprintf "%s@@" "foo" = "foo@");
+ test (sprintf "%s@@inria.fr" "foo" = "foo@inria.fr");
+ test (sprintf "%s@@%s" "foo" "inria.fr" = "foo@inria.fr");
+
+ say "\nS\n%!";
+ test (sprintf "%S" "fo\"o" = "\"fo\\\"o\"");
+ test (sprintf "%-7S" "foo" = "\"foo\" ");
+(* test (sprintf "%07S" "foo" = " \"foo\""); *)
+ (* %S is incompatible with '0' *)
+ test (sprintf "%+S" "foo" = "\"foo\"");
+ test (sprintf "% S" "foo" = "\"foo\"");
+ test (sprintf "%#S" "foo" = "\"foo\"");
+ test (sprintf "%7S" "foo" = " \"foo\"");
+ test (sprintf "%1S" "foo" = "\"foo\"");
+ test (sprintf "%*S" 8 "foo" = " \"foo\"");
+ test (sprintf "%*S" (-8) "foo" = "\"foo\" ");
+ test (sprintf "%*S" 2 "foo" = "\"foo\"");
+(* test (sprintf "%-0+ #5S" "foo" = "\"foo\" "); padding not done *)
+ (* %S is incompatible with '0','+' and ' ' *)
+ test (sprintf "%S@@" "foo" = "\"foo\"@");
+ test (sprintf "%S@@inria.fr" "foo" = "\"foo\"@inria.fr");
+ test (sprintf "%S@@%S" "foo" "inria.fr" = "\"foo\"@\"inria.fr\"");
+
+ say "\nc\n%!";
+ test (sprintf "%c" 'c' = "c");
+(* test (sprintf "%-4c" 'c' = "c "); padding not done *)
+(* test (sprintf "%04c" 'c' = " c"); padding not done *)
+ test (sprintf "%+c" 'c' = "c");
+ test (sprintf "% c" 'c' = "c");
+ test (sprintf "%#c" 'c' = "c");
+(* test (sprintf "%4c" 'c' = " c"); padding not done *)
+(* test (sprintf "%*c" 2 'c' = " c"); padding not done *)
+(* test (sprintf "%-0+ #4c" 'c' = "c "); padding not done *)
+
+ say "\nC\n%!";
+ test (sprintf "%C" 'c' = "'c'");
+ test (sprintf "%C" '\'' = "'\\''");
+(* test (sprintf "%-4C" 'c' = "c "); padding not done *)
+(* test (sprintf "%04C" 'c' = " c"); padding not done *)
+ test (sprintf "%+C" 'c' = "'c'");
+ test (sprintf "% C" 'c' = "'c'");
+ test (sprintf "%#C" 'c' = "'c'");
+(* test (sprintf "%4C" 'c' = " c"); padding not done *)
+(* test (sprintf "%*C" 2 'c' = " c"); padding not done *)
+(* test (sprintf "%-0+ #4C" 'c' = "c "); padding not done *)
+
+ say "\nf\n%!";
+ test (sprintf "%f" (-42.42) = "-42.420000");
+ test (sprintf "%-13f" (-42.42) = "-42.420000 ");
+ test (sprintf "%013f" (-42.42) = "-00042.420000");
+ test (sprintf "%+f" 42.42 = "+42.420000");
+ test (sprintf "% f" 42.42 = " 42.420000");
+ test (sprintf "%#f" 42.42 = "42.420000");
+ test (sprintf "%13f" 42.42 = " 42.420000");
+ test (sprintf "%*f" 12 42.42 = " 42.420000");
+ test (sprintf "%-0+ #12f" 42.42 = "+42.420000 ");
+ test (sprintf "%.3f" (-42.42) = "-42.420");
+ test (sprintf "%-13.3f" (-42.42) = "-42.420 ");
+ test (sprintf "%013.3f" (-42.42) = "-00000042.420");
+ test (sprintf "%+.3f" 42.42 = "+42.420");
+ test (sprintf "% .3f" 42.42 = " 42.420");
+ test (sprintf "%#.3f" 42.42 = "42.420");
+ test (sprintf "%13.3f" 42.42 = " 42.420");
+ test (sprintf "%*.*f" 12 3 42.42 = " 42.420");
+ test (sprintf "%-0+ #12.3f" 42.42 = "+42.420 ");
+
+ (* Under Windows (mingw and maybe also MSVC), the stdlib uses three
+ digits for the exponent instead of the two used by Linux and BSD.
+ Check that the two strings are equal, except that there may be an
+ extra zero, and if there is one, there may be a missing space or
+ zero. All in the first string relative to the second. *)
+ let ( =* ) s1 s2 =
+ let ss1 = s1 ^ "$" in
+ let ss2 = s2 ^ "$" in
+ let rec loop i1 i2 extra missing =
+ if i1 = String.length ss1 && i2 = String.length ss2 then begin
+ if extra then true else not missing
+ end else if i1 = String.length ss1 || i2 = String.length ss2 then
+ false
+ else begin
+ match ss1.[i1], ss2.[i2] with
+ | x, y when x = y -> loop (i1+1) (i2+1) extra missing
+ | '0', _ when not extra -> loop (i1+1) i2 true missing
+ | _, (' '|'0') when not missing -> loop i1 (i2+1) extra true
+ | _, _ -> false
+ end
+ in
+ loop 0 0 false false
+ in
+
+ say "\nF\n%!";
+ test (sprintf "%F" 42.42 = "42.42");
+ test (sprintf "%F" 42.42e42 =* "4.242e+43");
+ test (sprintf "%F" 42.00 = "42.");
+ test (sprintf "%F" 0.042 = "0.042");
+ test (sprintf "%4F" 3. = " 3.");
+ test (sprintf "%-4F" 3. = "3. ");
+ test (sprintf "%04F" 3. = "003.");
+(* plus-padding unsupported
+ test (sprintf "%+4F" 3. = " +3.");
+*)
+(* no precision
+ test (sprintf "%.3F" 42.42 = "42.420");
+ test (sprintf "%12.3F" 42.42e42 = " 4.242e+43");
+ test (sprintf "%.3F" 42.00 = "42.000");
+ test (sprintf "%.3F" 0.0042 = "0.004");
+*)
+
+ say "\ne\n%!";
+ test (sprintf "%e" (-42.42) =* "-4.242000e+01");
+ test (sprintf "%-15e" (-42.42) =* "-4.242000e+01 ");
+ test (sprintf "%015e" (-42.42) =* "-004.242000e+01");
+ test (sprintf "%+e" 42.42 =* "+4.242000e+01");
+ test (sprintf "% e" 42.42 =* " 4.242000e+01");
+ test (sprintf "%#e" 42.42 =* "4.242000e+01");
+ test (sprintf "%15e" 42.42 =* " 4.242000e+01");
+ test (sprintf "%*e" 14 42.42 =* " 4.242000e+01");
+ test (sprintf "%-0+ #14e" 42.42 =* "+4.242000e+01 ");
+ test (sprintf "%.3e" (-42.42) =* "-4.242e+01");
+ test (sprintf "%-15.3e" (-42.42) =* "-4.242e+01 ");
+ test (sprintf "%015.3e" (-42.42) =* "-000004.242e+01");
+ test (sprintf "%+.3e" 42.42 =* "+4.242e+01");
+ test (sprintf "% .3e" 42.42 =* " 4.242e+01");
+ test (sprintf "%#.3e" 42.42 =* "4.242e+01");
+ test (sprintf "%15.3e" 42.42 =* " 4.242e+01");
+ test (sprintf "%*.*e" 11 3 42.42 =* " 4.242e+01");
+ test (sprintf "%-0+ #14.3e" 42.42 =* "+4.242e+01 ");
+
+ say "\nE\n%!";
+ test (sprintf "%E" (-42.42) =* "-4.242000E+01");
+ test (sprintf "%-15E" (-42.42) =* "-4.242000E+01 ");
+ test (sprintf "%015E" (-42.42) =* "-004.242000E+01");
+ test (sprintf "%+E" 42.42 =* "+4.242000E+01");
+ test (sprintf "% E" 42.42 =* " 4.242000E+01");
+ test (sprintf "%#E" 42.42 =* "4.242000E+01");
+ test (sprintf "%15E" 42.42 =* " 4.242000E+01");
+ test (sprintf "%*E" 14 42.42 =* " 4.242000E+01");
+ test (sprintf "%-0+ #14E" 42.42 =* "+4.242000E+01 ");
+ test (sprintf "%.3E" (-42.42) =* "-4.242E+01");
+ test (sprintf "%-15.3E" (-42.42) =* "-4.242E+01 ");
+ test (sprintf "%015.3E" (-42.42) =* "-000004.242E+01");
+ test (sprintf "%+.3E" 42.42 =* "+4.242E+01");
+ test (sprintf "% .3E" 42.42 =* " 4.242E+01");
+ test (sprintf "%#.3E" 42.42 =* "4.242E+01");
+ test (sprintf "%15.3E" 42.42 =* " 4.242E+01");
+ test (sprintf "%*.*E" 11 3 42.42 =* " 4.242E+01");
+ test (sprintf "%-0+ #14.3E" 42.42 =* "+4.242E+01 ");
+
+(* %g gives strange results that correspond to neither %f nor %e
+ say "\ng\n%!";
+ test (sprintf "%g" (-42.42) = "-42.42000");
+ test (sprintf "%-15g" (-42.42) = "-42.42000 ");
+ test (sprintf "%015g" (-42.42) = "-00000042.42000");
+ test (sprintf "%+g" 42.42 = "+42.42000");
+ test (sprintf "% g" 42.42 = " 42.42000");
+ test (sprintf "%#g" 42.42 = "42.42000");
+ test (sprintf "%15g" 42.42 = " 42.42000");
+ test (sprintf "%*g" 14 42.42 = " 42.42000");
+ test (sprintf "%-0+ #14g" 42.42 = "+42.42000 ");
+ test (sprintf "%.3g" (-42.42) = "-42.420");
+*)
+
+(* Same for %G
+ say "\nG\n%!";
+*)
+
+ say "\nB\n%!";
+ test (sprintf "%B" true = "true");
+ test (sprintf "%B" false = "false");
+ (* test (sprintf "%8B" false = " false"); *)
+ (* padding not done *)
+
+ say "\nld/li positive\n%!";
+ test (sprintf "%ld/%li" 42l 43l = "42/43");
+ test (sprintf "%-4ld/%-5li" 42l 43l = "42 /43 ");
+ test (sprintf "%04ld/%05li" 42l 43l = "0042/00043");
+ test (sprintf "%+ld/%+li" 42l 43l = "+42/+43");
+ test (sprintf "% ld/% li" 42l 43l = " 42/ 43");
+ test (sprintf "%#ld/%#li" 42l 43l = "42/43");
+ test (sprintf "%4ld/%5li" 42l 43l = " 42/ 43");
+ test (sprintf "%*ld/%*li" 4 42l 5 43l = " 42/ 43");
+ test (sprintf "%-0+#4ld/%-0 #5li" 42l 43l = "+42 / 43 ");
+
+ say "\nld/li negative\n%!";
+ test (sprintf "%ld/%li" (-42l) (-43l) = "-42/-43");
+ test (sprintf "%-4ld/%-5li" (-42l) (-43l) = "-42 /-43 ");
+ test (sprintf "%04ld/%05li" (-42l) (-43l) = "-042/-0043");
+ test (sprintf "%+ld/%+li" (-42l) (-43l) = "-42/-43");
+ test (sprintf "% ld/% li" (-42l) (-43l) = "-42/-43");
+ test (sprintf "%#ld/%#li" (-42l) (-43l) = "-42/-43");
+ test (sprintf "%4ld/%5li" (-42l) (-43l) = " -42/ -43");
+ test (sprintf "%*ld/%*li" 4 (-42l) 5 (-43l) = " -42/ -43");
+ test (sprintf "%-0+ #4ld/%-0+ #5li" (-42l) (-43l) = "-42 /-43 ");
+
+ say "\nlu positive\n%!";
+ test (sprintf "%lu" 42l = "42");
+ test (sprintf "%-4lu" 42l = "42 ");
+ test (sprintf "%04lu" 42l = "0042");
+ test (sprintf "%+lu" 42l = "42");
+ test (sprintf "% lu" 42l = "42");
+ test (sprintf "%#lu" 42l = "42");
+ test (sprintf "%4lu" 42l = " 42");
+ test (sprintf "%*lu" 4 42l = " 42");
+ test (sprintf "%-0+ #6ld" 42l = "+42 ");
+
+ say "\nlu negative\n%!";
+ test (sprintf "%lu" (-1l) = "4294967295");
+
+ say "\nlx positive\n%!";
+ test (sprintf "%lx" 42l = "2a");
+ test (sprintf "%-4lx" 42l = "2a ");
+ test (sprintf "%04lx" 42l = "002a");
+ test (sprintf "%+lx" 42l = "2a");
+ test (sprintf "% lx" 42l = "2a");
+ test (sprintf "%#lx" 42l = "0x2a");
+ test (sprintf "%4lx" 42l = " 2a");
+ test (sprintf "%*lx" 5 42l = " 2a");
+ test (sprintf "%-0+ #*lx" 5 42l = "0x2a ");
+
+ say "\nlx negative\n%!";
+ test (sprintf "%lx" (-42l) = "ffffffd6");
+
+ say "\nlX positive\n%!";
+ test (sprintf "%lX" 42l = "2A");
+ test (sprintf "%-4lX" 42l = "2A ");
+ test (sprintf "%04lX" 42l = "002A");
+ test (sprintf "%+lX" 42l = "2A");
+ test (sprintf "% lX" 42l = "2A");
+ test (sprintf "%#lX" 42l = "0X2A");
+ test (sprintf "%4lX" 42l = " 2A");
+ test (sprintf "%*lX" 5 42l = " 2A");
+ test (sprintf "%-0+ #*lX" 5 42l = "0X2A ");
+
+ say "\nlx negative\n%!";
+ test (sprintf "%lX" (-42l) = "FFFFFFD6");
+
+ say "\nlo positive\n%!";
+ test (sprintf "%lo" 42l = "52");
+ test (sprintf "%-4lo" 42l = "52 ");
+ test (sprintf "%04lo" 42l = "0052");
+ test (sprintf "%+lo" 42l = "52");
+ test (sprintf "% lo" 42l = "52");
+ test (sprintf "%#lo" 42l = "052");
+ test (sprintf "%4lo" 42l = " 52");
+ test (sprintf "%*lo" 5 42l = " 52");
+ test (sprintf "%-0+ #*lo" 5 42l = "052 ");
+
+ say "\nlo negative\n%!";
+ test (sprintf "%lo" (-42l) = "37777777726");
+
+ (* Nativeint not tested: looks like too much work, and anyway it should
+ work like Int32 or Int64. *)
+
+ say "\nLd/Li positive\n%!";
+ test (sprintf "%Ld/%Li" 42L 43L = "42/43");
+ test (sprintf "%-4Ld/%-5Li" 42L 43L = "42 /43 ");
+ test (sprintf "%04Ld/%05Li" 42L 43L = "0042/00043");
+ test (sprintf "%+Ld/%+Li" 42L 43L = "+42/+43");
+ test (sprintf "% Ld/% Li" 42L 43L = " 42/ 43");
+ test (sprintf "%#Ld/%#Li" 42L 43L = "42/43");
+ test (sprintf "%4Ld/%5Li" 42L 43L = " 42/ 43");
+ test (sprintf "%*Ld/%*Li" 4 42L 5 43L = " 42/ 43");
+ test (sprintf "%-0+#4Ld/%-0 #5Li" 42L 43L = "+42 / 43 ");
+
+ say "\nLd/Li negative\n%!";
+ test (sprintf "%Ld/%Li" (-42L) (-43L) = "-42/-43");
+ test (sprintf "%-4Ld/%-5Li" (-42L) (-43L) = "-42 /-43 ");
+ test (sprintf "%04Ld/%05Li" (-42L) (-43L) = "-042/-0043");
+ test (sprintf "%+Ld/%+Li" (-42L) (-43L) = "-42/-43");
+ test (sprintf "% Ld/% Li" (-42L) (-43L) = "-42/-43");
+ test (sprintf "%#Ld/%#Li" (-42L) (-43L) = "-42/-43");
+ test (sprintf "%4Ld/%5Li" (-42L) (-43L) = " -42/ -43");
+ test (sprintf "%*Ld/%*Li" 4 (-42L) 5 (-43L) = " -42/ -43");
+ test (sprintf "%-0+ #4Ld/%-0+ #5Li" (-42L) (-43L) = "-42 /-43 ");
+
+ say "\nLu positive\n%!";
+ test (sprintf "%Lu" 42L = "42");
+ test (sprintf "%-4Lu" 42L = "42 ");
+ test (sprintf "%04Lu" 42L = "0042");
+ test (sprintf "%+Lu" 42L = "42");
+ test (sprintf "% Lu" 42L = "42");
+ test (sprintf "%#Lu" 42L = "42");
+ test (sprintf "%4Lu" 42L = " 42");
+ test (sprintf "%*Lu" 4 42L = " 42");
+ test (sprintf "%-0+ #6Ld" 42L = "+42 ");
+
+ say "\nLu negative\n%!";
+ test (sprintf "%Lu" (-1L) = "18446744073709551615");
+
+ say "\nLx positive\n%!";
+ test (sprintf "%Lx" 42L = "2a");
+ test (sprintf "%-4Lx" 42L = "2a ");
+ test (sprintf "%04Lx" 42L = "002a");
+ test (sprintf "%+Lx" 42L = "2a");
+ test (sprintf "% Lx" 42L = "2a");
+ test (sprintf "%#Lx" 42L = "0x2a");
+ test (sprintf "%4Lx" 42L = " 2a");
+ test (sprintf "%*Lx" 5 42L = " 2a");
+ test (sprintf "%-0+ #*Lx" 5 42L = "0x2a ");
+
+ say "\nLx negative\n%!";
+ test (sprintf "%Lx" (-42L) = "ffffffffffffffd6");
+
+ say "\nLX positive\n%!";
+ test (sprintf "%LX" 42L = "2A");
+ test (sprintf "%-4LX" 42L = "2A ");
+ test (sprintf "%04LX" 42L = "002A");
+ test (sprintf "%+LX" 42L = "2A");
+ test (sprintf "% LX" 42L = "2A");
+ test (sprintf "%#LX" 42L = "0X2A");
+ test (sprintf "%4LX" 42L = " 2A");
+ test (sprintf "%*LX" 5 42L = " 2A");
+ test (sprintf "%-0+ #*LX" 5 42L = "0X2A ");
+
+ say "\nLx negative\n%!";
+ test (sprintf "%LX" (-42L) = "FFFFFFFFFFFFFFD6");
+
+ say "\nLo positive\n%!";
+ test (sprintf "%Lo" 42L = "52");
+ test (sprintf "%-4Lo" 42L = "52 ");
+ test (sprintf "%04Lo" 42L = "0052");
+ test (sprintf "%+Lo" 42L = "52");
+ test (sprintf "% Lo" 42L = "52");
+ test (sprintf "%#Lo" 42L = "052");
+ test (sprintf "%4Lo" 42L = " 52");
+ test (sprintf "%*Lo" 5 42L = " 52");
+ test (sprintf "%-0+ #*Lo" 5 42L = "052 ");
+
+ say "\nLo negative\n%!";
+ test (sprintf "%Lo" (-42L) = "1777777777777777777726");
+
+ say "\na\n%!";
+ let x = ref () in
+ let f () y = if y == x then "ok" else "wrong" in
+ test (sprintf "%a" f x = "ok");
+
+ say "\nt\n%!";
+ let f () = "ok" in
+ test (sprintf "%t" f = "ok");
+
+(* %{ fmt %} prints the signature of [fmt], i.e. a canonical representation
+ of the conversions present in [fmt].
+*)
+ say "\n{...%%}\n%!";
+ let f = format_of_string "%f/%s" in
+ test (sprintf "%{%f%s%}" f = "%f%s");
+
+ say "\n(...%%)\n%!";
+ let f = format_of_string "%d/foo/%s" in
+ test (sprintf "%(%d%s%)" f 42 "bar" = "42/foo/bar");
+
+ say "\n! %% @ , and constants\n%!";
+ test (sprintf "%!" = "");
+ test (sprintf "%%" = "%");
+ test (sprintf "%@" = "@");
+ test (sprintf "%," = "");
+ test (sprintf "@@" = "@");
+ test (sprintf "@@@@" = "@@");
+ test (sprintf "@@%%" = "@%");
+ say "\nend of tests\n%!";
+
+with e ->
+ say "unexpected exception: %s\n%!" (Printexc.to_string e);
+ test false;
+;;
diff --git a/testsuite/tests/lib-format/tformat.reference b/testsuite/tests/lib-format/tformat.reference
new file mode 100644
index 0000000000..cf2b241ce7
--- /dev/null
+++ b/testsuite/tests/lib-format/tformat.reference
@@ -0,0 +1,91 @@
+d/i positive
+ 0 1 2 3 4 5 6 7 8 9
+d/i negative
+ 10 11 12 13 14 15 16 17 18 19
+u positive
+ 20 21 22 23 24 25 26 27 28
+u negative
+ 29
+x positive
+ 30 31 32 33 34 35 36 37 38 39 40 41 42
+x negative
+ 43
+X positive
+ 44 45 46 47 48 49 50 51 52
+x negative
+ 53
+o positive
+ 54 55 56 57 58 59 60 61 62
+o negative
+ 63
+s
+ 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
+S
+ 79 80 81 82 83 84 85 86 87 88 89 90 91
+c
+ 92 93 94 95
+C
+ 96 97 98 99 100
+f
+ 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
+F
+ 119 120 121 122 123 124 125
+e
+ 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
+E
+ 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
+B
+ 162 163
+ld/li positive
+ 164 165 166 167 168 169 170 171 172
+ld/li negative
+ 173 174 175 176 177 178 179 180 181
+lu positive
+ 182 183 184 185 186 187 188 189 190
+lu negative
+ 191
+lx positive
+ 192 193 194 195 196 197 198 199 200
+lx negative
+ 201
+lX positive
+ 202 203 204 205 206 207 208 209 210
+lx negative
+ 211
+lo positive
+ 212 213 214 215 216 217 218 219 220
+lo negative
+ 221
+Ld/Li positive
+ 222 223 224 225 226 227 228 229 230
+Ld/Li negative
+ 231 232 233 234 235 236 237 238 239
+Lu positive
+ 240 241 242 243 244 245 246 247 248
+Lu negative
+ 249
+Lx positive
+ 250 251 252 253 254 255 256 257 258
+Lx negative
+ 259
+LX positive
+ 260 261 262 263 264 265 266 267 268
+Lx negative
+ 269
+Lo positive
+ 270 271 272 273 274 275 276 277 278
+Lo negative
+ 279
+a
+ 280
+t
+ 281
+{...%}
+ 282
+(...%)
+ 283
+! % @ , and constants
+ 284 285 286 287 288 289 290
+end of tests
+
+All tests succeeded.
diff --git a/testsuite/tests/lib-hashtbl/Makefile b/testsuite/tests/lib-hashtbl/Makefile
new file mode 100644
index 0000000000..299656b246
--- /dev/null
+++ b/testsuite/tests/lib-hashtbl/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-hashtbl/hfun.ml b/testsuite/tests/lib-hashtbl/hfun.ml
new file mode 100644
index 0000000000..8a3c1cfc0d
--- /dev/null
+++ b/testsuite/tests/lib-hashtbl/hfun.ml
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2011 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Testing the hash function Hashtbl.hash *)
+(* What is tested:
+ - reproducibility on various platforms, esp. 32/64 bit issues
+ - equal values hash equally, esp NaNs. *)
+
+open Printf
+
+let _ =
+ printf "-- Strings:\n";
+ printf "\"\"\t\t%08x\n" (Hashtbl.hash "");
+ printf "\"Hello world\"\t%08x\n" (Hashtbl.hash "Hello world");
+
+ printf "-- Integers:\n";
+ printf "0\t\t%08x\n" (Hashtbl.hash 0);
+ printf "-1\t\t%08x\n" (Hashtbl.hash (-1));
+ printf "42\t\t%08x\n" (Hashtbl.hash 42);
+ printf "2^30-1\t\t%08x\n" (Hashtbl.hash 0x3FFF_FFFF);
+ printf "-2^30\t\t%08x\n" (Hashtbl.hash (-0x4000_0000));
+
+ printf "-- Floats:\n";
+ printf "+0.0\t\t%08x\n" (Hashtbl.hash 0.0);
+ printf "-0.0\t\t%08x\n" (Hashtbl.hash (-. 0.0));
+ printf "+infty\t\t%08x\n" (Hashtbl.hash infinity);
+ printf "-infty\t\t%08x\n" (Hashtbl.hash neg_infinity);
+ printf "NaN\t\t%08x\n" (Hashtbl.hash nan);
+ printf "NaN#2\t\t%08x\n"
+ (Hashtbl.hash (Int64.float_of_bits 0xFF_F0_00_12_34_56_78_9AL));
+ printf "NaN#3\t\t%08x\n" (Hashtbl.hash (0.0 /. 0.0));
+
+ printf "-- Native integers:\n";
+ printf "0\t\t%08x\n" (Hashtbl.hash 0n);
+ printf "-1\t\t%08x\n" (Hashtbl.hash (-1n));
+ printf "42\t\t%08x\n" (Hashtbl.hash 42n);
+ printf "2^30-1\t\t%08x\n" (Hashtbl.hash 0x3FFF_FFFFn);
+ printf "-2^30\t\t%08x\n" (Hashtbl.hash (-0x4000_0000n));
+
+ printf "-- Lists:\n";
+ printf "[0..10]\t\t%08x\n" (Hashtbl.hash [0;1;2;3;4;5;6;7;8;9;10]);
+ printf "[0..12]\t\t%08x\n" (Hashtbl.hash [0;1;2;3;4;5;6;7;8;9;10;11;12]);
+ printf "[10..0]\t\t%08x\n" (Hashtbl.hash [10;9;8;7;6;5;4;3;2;1;0]);
+
+ ()
diff --git a/testsuite/tests/lib-hashtbl/hfun.reference b/testsuite/tests/lib-hashtbl/hfun.reference
new file mode 100644
index 0000000000..2e92cf439d
--- /dev/null
+++ b/testsuite/tests/lib-hashtbl/hfun.reference
@@ -0,0 +1,27 @@
+-- Strings:
+"" 00000000
+"Hello world" 364b8272
+-- Integers:
+0 07be548a
+-1 3653e015
+42 1792870b
+2^30-1 23c392d0
+-2^30 0c66fde3
+-- Floats:
++0.0 0f478b8c
+-0.0 0f478b8c
++infty 23ea56fb
+-infty 059f7872
+NaN 3228858d
+NaN#2 3228858d
+NaN#3 3228858d
+-- Native integers:
+0 3f19274a
+-1 3653e015
+42 3e33aef8
+2^30-1 3711bf46
+-2^30 2e71f39c
+-- Lists:
+[0..10] 0ade0fc9
+[0..12] 0ade0fc9
+[10..0] 0cd6259d
diff --git a/testsuite/tests/lib-hashtbl/htbl.ml b/testsuite/tests/lib-hashtbl/htbl.ml
new file mode 100644
index 0000000000..bd5f33a656
--- /dev/null
+++ b/testsuite/tests/lib-hashtbl/htbl.ml
@@ -0,0 +1,204 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2011 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Hashtable operations, using maps as a reference *)
+
+open Printf
+
+module Test(H: Hashtbl.S) (M: Map.S with type key = H.key) = struct
+
+ let incl_mh m h =
+ try
+ M.iter
+ (fun k d ->
+ let d' = H.find h k in if d <> d' then raise Exit)
+ m;
+ true
+ with Exit | Not_found -> false
+
+ let domain_hm h m =
+ try
+ H.iter
+ (fun k d -> if not (M.mem k m) then raise Exit)
+ h;
+ true
+ with Exit -> false
+
+ let incl_hm h m =
+ try
+ H.iter
+ (fun k d ->
+ let d' = M.find k m in if d <> d' then raise Exit)
+ h;
+ true
+ with Exit | Not_found -> false
+
+ let test data =
+ let n = Array.length data in
+ let h = H.create 51 and m = ref M.empty in
+ (* Insert all data with H.add *)
+ Array.iter
+ (fun (k, d) -> H.add h k d; m := M.add k d !m)
+ data;
+ printf "Insertion: %s\n"
+ (if incl_mh !m h && domain_hm h !m then "passed" else "FAILED");
+ (* Insert all data with H.replace *)
+ H.clear h; m := M.empty;
+ Array.iter
+ (fun (k, d) -> H.replace h k d; m := M.add k d !m)
+ data;
+ printf "Insertion: %s\n"
+ (if incl_mh !m h && incl_hm h !m then "passed" else "FAILED");
+ (* Remove some of the data *)
+ for i = 0 to n/3 - 1 do
+ let (k, _) = data.(i) in H.remove h k; m := M.remove k !m
+ done;
+ printf "Removal: %s\n"
+ (if incl_mh !m h && incl_hm h !m then "passed" else "FAILED")
+
+end
+
+module MS = Map.Make(struct type t = string
+ let compare (x:t) (y:t) = Pervasives.compare x y
+ end)
+module MI = Map.Make(struct type t = int
+ let compare (x:t) (y:t) = Pervasives.compare x y
+ end)
+
+module MSP = Map.Make(struct type t = string*string
+ let compare (x:t) (y:t) = Pervasives.compare x y
+ end)
+
+module MSL = Map.Make(struct type t = string list
+ let compare (x:t) (y:t) = Pervasives.compare x y
+ end)
+
+(* Generic hash wrapped as a functorial hash *)
+
+module HofM (M: Map.S) : Hashtbl.S with type key = M.key =
+ struct
+ type key = M.key
+ type 'a t = (key, 'a) Hashtbl.t
+ let create s = Hashtbl.create s
+ let clear = Hashtbl.clear
+ let reset = Hashtbl.reset
+ let copy = Hashtbl.copy
+ let add = Hashtbl.add
+ let remove = Hashtbl.remove
+ let find = Hashtbl.find
+ let find_all = Hashtbl.find_all
+ let replace = Hashtbl.replace
+ let mem = Hashtbl.mem
+ let iter = Hashtbl.iter
+ let fold = Hashtbl.fold
+ let length = Hashtbl.length
+ let stats = Hashtbl.stats
+ end
+
+module HS1 = HofM(MS)
+module HI1 = HofM(MI)
+module HSP = HofM(MSP)
+module HSL = HofM(MSL)
+
+(* Specific functorial hashes *)
+
+module HS2 = Hashtbl.Make(struct type t = string
+ let equal (x:t) (y:t) = x=y
+ let hash = Hashtbl.hash end)
+
+module HI2 = Hashtbl.Make(struct type t = int
+ let equal (x:t) (y:t) = x=y
+ let hash = Hashtbl.hash end)
+(* Instantiating the test *)
+
+module TS1 = Test(HS1)(MS)
+module TS2 = Test(HS2)(MS)
+module TI1 = Test(HI1)(MI)
+module TI2 = Test(HI2)(MI)
+module TSP = Test(HSP)(MSP)
+module TSL = Test(HSL)(MSL)
+
+(* Data set: strings from a file, associated with their line number *)
+
+let file_data filename =
+ let ic = open_in filename in
+ let lineno = ref 0 in
+ let data = ref [] in
+ begin try
+ while true do
+ let l = input_line ic in
+ incr lineno;
+ data := (l, !lineno) :: !data
+ done
+ with End_of_file -> ()
+ end;
+ close_in ic;
+ Array.of_list !data
+
+(* Data set: fixed strings *)
+
+let string_data = [|
+ "Si", 0; "non", 1; "e", 2; "vero", 3; "e", 4; "ben", 5; "trovato", 6;
+ "An", 10; "apple", 11; "a", 12; "day", 13; "keeps", 14; "the", 15;
+ "doctor", 16; "away", 17;
+ "Pierre", 20; "qui", 21; "roule", 22; "n'amasse", 23; "pas", 24; "mousse", 25;
+ "Asinus", 30; "asinum", 31; "fricat", 32
+|]
+
+(* Data set: random integers *)
+
+let random_integers num range =
+ let data = Array.make num (0,0) in
+ for i = 0 to num - 1 do
+ data.(i) <- (Random.int range, i)
+ done;
+ data
+
+(* Data set: pairs *)
+
+let pair_data data =
+ Array.map (fun (k, d) -> ((k, k), d)) data
+
+(* Data set: lists *)
+
+let list_data data =
+ let d = Array.make (Array.length data / 10) ([], 0) in
+ let j = ref 0 in
+ let rec mklist n =
+ if n <= 0 || !j >= Array.length data then [] else begin
+ let hd = fst data.(!j) in
+ incr j;
+ let tl = mklist (n-1) in
+ hd :: tl
+ end in
+ for i = 0 to Array.length d - 1 do
+ d.(i) <- (mklist (Random.int 16), i)
+ done;
+ d
+
+(* The test *)
+
+let _ =
+ printf "-- Random integers, large range\n%!";
+ TI1.test (random_integers 100_000 1_000_000);
+ printf "-- Random integers, narrow range\n%!";
+ TI2.test (random_integers 100_000 1_000);
+ let d =
+ try file_data "../../LICENSE" with Sys_error _ -> string_data in
+ printf "-- Strings, generic interface\n%!";
+ TS1.test d;
+ printf "-- Strings, functorial interface\n%!";
+ TS2.test d;
+ printf "-- Pairs of strings\n%!";
+ TSP.test (pair_data d);
+ printf "-- Lists of strings\n%!";
+ TSL.test (list_data d)
diff --git a/testsuite/tests/lib-hashtbl/htbl.reference b/testsuite/tests/lib-hashtbl/htbl.reference
new file mode 100644
index 0000000000..08ca22f07d
--- /dev/null
+++ b/testsuite/tests/lib-hashtbl/htbl.reference
@@ -0,0 +1,24 @@
+-- Random integers, large range
+Insertion: passed
+Insertion: passed
+Removal: passed
+-- Random integers, narrow range
+Insertion: passed
+Insertion: passed
+Removal: passed
+-- Strings, generic interface
+Insertion: passed
+Insertion: passed
+Removal: passed
+-- Strings, functorial interface
+Insertion: passed
+Insertion: passed
+Removal: passed
+-- Pairs of strings
+Insertion: passed
+Insertion: passed
+Removal: passed
+-- Lists of strings
+Insertion: passed
+Insertion: passed
+Removal: passed
diff --git a/testsuite/tests/lib-marshal/Makefile b/testsuite/tests/lib-marshal/Makefile
new file mode 100644
index 0000000000..34b67dc811
--- /dev/null
+++ b/testsuite/tests/lib-marshal/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=intext
+C_FILES=intextaux
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-marshal/intext.ml b/testsuite/tests/lib-marshal/intext.ml
new file mode 100644
index 0000000000..27ffd64d24
--- /dev/null
+++ b/testsuite/tests/lib-marshal/intext.ml
@@ -0,0 +1,587 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test for output_value / input_value *)
+
+let max_data_depth = 500000
+
+type t = A | B of int | C of float | D of string | E of char
+ | F of t | G of t * t | H of int * t | I of t * float | J
+
+let longstring =
+"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+let verylongstring =
+"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+ 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+ 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+ 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+ 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+ 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+ 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
+ 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+
+let bigint = Int64.to_int 0x123456789ABCDEF0L
+
+let rec fib n =
+ if n < 2 then 1 else fib(n-1) + fib(n-2)
+
+let test_out filename =
+ let oc = open_out_bin filename in
+ output_value oc 1;
+ output_value oc (-1);
+ output_value oc 258;
+ output_value oc 20000;
+ output_value oc 0x12345678;
+ output_value oc bigint;
+ output_value oc "foobargeebuz";
+ output_value oc longstring;
+ output_value oc verylongstring;
+ output_value oc 3.141592654;
+ output_value oc ();
+ output_value oc A;
+ output_value oc (B 1);
+ output_value oc (C 2.718);
+ output_value oc (D "hello, world!");
+ output_value oc (E 'l');
+ output_value oc (F(B 1));
+ output_value oc (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e')))));
+ output_value oc (H(1, A));
+ output_value oc (I(B 2, 1e-6));
+ let x = D "sharing" in
+ let y = G(x, x) in
+ let z = G(y, G(x, y)) in
+ output_value oc z;
+ output_value oc [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|];
+ let rec big n = if n <= 0 then A else H(n, big(n-1)) in
+ output_value oc (big 1000);
+ Marshal.to_channel oc y [Marshal.No_sharing];
+ Marshal.to_channel oc fib [Marshal.Closures];
+ output_value oc (Int32.of_string "0");
+ output_value oc (Int32.of_string "123456");
+ output_value oc (Int32.of_string "-123456");
+ output_value oc (Int64.of_string "0");
+ output_value oc (Int64.of_string "123456789123456");
+ output_value oc (Int64.of_string "-123456789123456");
+ output_value oc (Nativeint.of_string "0");
+ output_value oc (Nativeint.of_string "123456");
+ output_value oc (Nativeint.of_string "-123456");
+ output_value oc (Nativeint.shift_left (Nativeint.of_string "123456789") 32);
+ output_value oc (Nativeint.shift_left (Nativeint.of_string "-123456789") 32);
+ let i = Int64.of_string "123456789123456" in output_value oc (i,i);
+ close_out oc
+
+
+let test n b =
+ print_string "Test "; print_int n;
+ if b then print_string " passed.\n" else print_string " FAILED.\n";
+ flush stderr
+
+let test_in filename =
+ let ic = open_in_bin filename in
+ test 1 (input_value ic = 1);
+ test 2 (input_value ic = (-1));
+ test 3 (input_value ic = 258);
+ test 4 (input_value ic = 20000);
+ test 5 (input_value ic = 0x12345678);
+ test 6 (input_value ic = bigint);
+ test 7 (input_value ic = "foobargeebuz");
+ test 8 (input_value ic = longstring);
+ test 9 (input_value ic = verylongstring);
+ test 10 (input_value ic = 3.141592654);
+ test 11 (input_value ic = ());
+ test 12 (match input_value ic with
+ A -> true
+ | _ -> false);
+ test 13 (match input_value ic with
+ (B 1) -> true
+ | _ -> false);
+ test 14 (match input_value ic with
+ (C f) -> f = 2.718
+ | _ -> false);
+ test 15 (match input_value ic with
+ (D "hello, world!") -> true
+ | _ -> false);
+ test 16 (match input_value ic with
+ (E 'l') -> true
+ | _ -> false);
+ test 17 (match input_value ic with
+ (F(B 1)) -> true
+ | _ -> false);
+ test 18 (match input_value ic with
+ (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
+ | _ -> false);
+ test 19 (match input_value ic with
+ (H(1, A)) -> true
+ | _ -> false);
+ test 20 (match input_value ic with
+ (I(B 2, 1e-6)) -> true
+ | _ -> false);
+ test 21 (match input_value ic with
+ G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
+ t1 == t2 && t3 == t5 && t4 == t1
+ | _ -> false);
+ test 22 (input_value ic = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
+ let rec check_big n t =
+ if n <= 0 then
+ test 23 (match t with A -> true | _ -> false)
+ else
+ match t with H(m, s) -> if m = n then check_big (n-1) s
+ else test 23 false
+ | _ -> test 23 false
+ in
+ check_big 1000 (input_value ic);
+ test 24 (match input_value ic with
+ G((D "sharing" as t1), (D "sharing" as t2)) -> t1 != t2
+ | _ -> false);
+ test 25 (let fib = (input_value ic : int -> int) in fib 5 = 8 && fib 10 = 89);
+ test 26 (input_value ic = Int32.of_string "0");
+ test 27 (input_value ic = Int32.of_string "123456");
+ test 28 (input_value ic = Int32.of_string "-123456");
+ test 29 (input_value ic = Int64.of_string "0");
+ test 30 (input_value ic = Int64.of_string "123456789123456");
+ test 31 (input_value ic = Int64.of_string "-123456789123456");
+ test 32 (input_value ic = Nativeint.of_string "0");
+ test 33 (input_value ic = Nativeint.of_string "123456");
+ test 34 (input_value ic = Nativeint.of_string "-123456");
+ test 35 (input_value ic =
+ Nativeint.shift_left (Nativeint.of_string "123456789") 32);
+ test 36 (input_value ic =
+ Nativeint.shift_left (Nativeint.of_string "-123456789") 32);
+ let ((i, j) : int64 * int64) = input_value ic in
+ test 37 (i = Int64.of_string "123456789123456");
+ test 38 (j = Int64.of_string "123456789123456");
+ test 39 (i == j);
+ close_in ic
+
+let test_string () =
+ let s = Marshal.to_string 1 [] in
+ test 101 (Marshal.from_string s 0 = 1);
+ let s = Marshal.to_string (-1) [] in
+ test 102 (Marshal.from_string s 0 = (-1));
+ let s = Marshal.to_string 258 [] in
+ test 103 (Marshal.from_string s 0 = 258);
+ let s = Marshal.to_string 20000 [] in
+ test 104 (Marshal.from_string s 0 = 20000);
+ let s = Marshal.to_string 0x12345678 [] in
+ test 105 (Marshal.from_string s 0 = 0x12345678);
+ let s = Marshal.to_string bigint [] in
+ test 106 (Marshal.from_string s 0 = bigint);
+ let s = Marshal.to_string "foobargeebuz" [] in
+ test 107 (Marshal.from_string s 0 = "foobargeebuz");
+ let s = Marshal.to_string longstring [] in
+ test 108 (Marshal.from_string s 0 = longstring);
+ let s = Marshal.to_string verylongstring [] in
+ test 109 (Marshal.from_string s 0 = verylongstring);
+ let s = Marshal.to_string 3.141592654 [] in
+ test 110 (Marshal.from_string s 0 = 3.141592654);
+ let s = Marshal.to_string () [] in
+ test 111 (Marshal.from_string s 0 = ());
+ let s = Marshal.to_string A [] in
+ test 112 (match Marshal.from_string s 0 with
+ A -> true
+ | _ -> false);
+ let s = Marshal.to_string (B 1) [] in
+ test 113 (match Marshal.from_string s 0 with
+ (B 1) -> true
+ | _ -> false);
+ let s = Marshal.to_string (C 2.718) [] in
+ test 114 (match Marshal.from_string s 0 with
+ (C f) -> f = 2.718
+ | _ -> false);
+ let s = Marshal.to_string (D "hello, world!") [] in
+ test 115 (match Marshal.from_string s 0 with
+ (D "hello, world!") -> true
+ | _ -> false);
+ let s = Marshal.to_string (E 'l') [] in
+ test 116 (match Marshal.from_string s 0 with
+ (E 'l') -> true
+ | _ -> false);
+ let s = Marshal.to_string (F(B 1)) [] in
+ test 117 (match Marshal.from_string s 0 with
+ (F(B 1)) -> true
+ | _ -> false);
+ let s = Marshal.to_string (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [] in
+ test 118 (match Marshal.from_string s 0 with
+ (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
+ | _ -> false);
+ let s = Marshal.to_string (H(1, A)) [] in
+ test 119 (match Marshal.from_string s 0 with
+ (H(1, A)) -> true
+ | _ -> false);
+ let s = Marshal.to_string (I(B 2, 1e-6)) [] in
+ test 120 (match Marshal.from_string s 0 with
+ (I(B 2, 1e-6)) -> true
+ | _ -> false);
+ let x = D "sharing" in
+ let y = G(x, x) in
+ let z = G(y, G(x, y)) in
+ let s = Marshal.to_string z [] in
+ test 121 (match Marshal.from_string s 0 with
+ G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
+ t1 == t2 && t3 == t5 && t4 == t1
+ | _ -> false);
+ let s = Marshal.to_string [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [] in
+ test 122
+ (Marshal.from_string s 0 = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
+ let rec big n = if n <= 0 then A else H(n, big(n-1)) in
+ let s = Marshal.to_string (big 1000) [] in
+ let rec check_big n t =
+ if n <= 0 then
+ test 123 (match t with A -> true | _ -> false)
+ else
+ match t with H(m, s) -> if m = n then check_big (n-1) s
+ else test 123 false
+ | _ -> test 123 false
+ in
+ check_big 1000 (Marshal.from_string s 0)
+
+let marshal_to_buffer s start len v flags =
+ ignore (Marshal.to_buffer s start len v flags)
+;;
+
+let test_buffer () =
+ let s = Bytes.create 512 in
+ marshal_to_buffer s 0 512 1 [];
+ test 201 (Marshal.from_bytes s 0 = 1);
+ marshal_to_buffer s 0 512 (-1) [];
+ test 202 (Marshal.from_bytes s 0 = (-1));
+ marshal_to_buffer s 0 512 258 [];
+ test 203 (Marshal.from_bytes s 0 = 258);
+ marshal_to_buffer s 0 512 20000 [];
+ test 204 (Marshal.from_bytes s 0 = 20000);
+ marshal_to_buffer s 0 512 0x12345678 [];
+ test 205 (Marshal.from_bytes s 0 = 0x12345678);
+ marshal_to_buffer s 0 512 bigint [];
+ test 206 (Marshal.from_bytes s 0 = bigint);
+ marshal_to_buffer s 0 512 "foobargeebuz" [];
+ test 207 (Marshal.from_bytes s 0 = "foobargeebuz");
+ marshal_to_buffer s 0 512 longstring [];
+ test 208 (Marshal.from_bytes s 0 = longstring);
+ test 209
+ (try marshal_to_buffer s 0 512 verylongstring []; false
+ with Failure "Marshal.to_buffer: buffer overflow" -> true);
+ marshal_to_buffer s 0 512 3.141592654 [];
+ test 210 (Marshal.from_bytes s 0 = 3.141592654);
+ marshal_to_buffer s 0 512 () [];
+ test 211 (Marshal.from_bytes s 0 = ());
+ marshal_to_buffer s 0 512 A [];
+ test 212 (match Marshal.from_bytes s 0 with
+ A -> true
+ | _ -> false);
+ marshal_to_buffer s 0 512 (B 1) [];
+ test 213 (match Marshal.from_bytes s 0 with
+ (B 1) -> true
+ | _ -> false);
+ marshal_to_buffer s 0 512 (C 2.718) [];
+ test 214 (match Marshal.from_bytes s 0 with
+ (C f) -> f = 2.718
+ | _ -> false);
+ marshal_to_buffer s 0 512 (D "hello, world!") [];
+ test 215 (match Marshal.from_bytes s 0 with
+ (D "hello, world!") -> true
+ | _ -> false);
+ marshal_to_buffer s 0 512 (E 'l') [];
+ test 216 (match Marshal.from_bytes s 0 with
+ (E 'l') -> true
+ | _ -> false);
+ marshal_to_buffer s 0 512 (F(B 1)) [];
+ test 217 (match Marshal.from_bytes s 0 with
+ (F(B 1)) -> true
+ | _ -> false);
+ marshal_to_buffer s 0 512 (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [];
+ test 218 (match Marshal.from_bytes s 0 with
+ (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
+ | _ -> false);
+ marshal_to_buffer s 0 512 (H(1, A)) [];
+ test 219 (match Marshal.from_bytes s 0 with
+ (H(1, A)) -> true
+ | _ -> false);
+ marshal_to_buffer s 0 512 (I(B 2, 1e-6)) [];
+ test 220 (match Marshal.from_bytes s 0 with
+ (I(B 2, 1e-6)) -> true
+ | _ -> false);
+ let x = D "sharing" in
+ let y = G(x, x) in
+ let z = G(y, G(x, y)) in
+ marshal_to_buffer s 0 512 z [];
+ test 221 (match Marshal.from_bytes s 0 with
+ G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
+ t1 == t2 && t3 == t5 && t4 == t1
+ | _ -> false);
+ marshal_to_buffer s 0 512 [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [];
+ test 222
+ (Marshal.from_bytes s 0 = [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
+ let rec big n = if n <= 0 then A else H(n, big(n-1)) in
+ test 223
+ (try marshal_to_buffer s 0 512 (big 1000) []; false
+ with Failure "Marshal.to_buffer: buffer overflow" -> true)
+
+let test_size() =
+ let s = Marshal.to_string (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [] in
+ test 300 (Marshal.header_size + Marshal.data_size s 0 = String.length s)
+
+external marshal_to_block
+ : string -> int -> 'a -> Marshal.extern_flags list -> unit
+ = "marshal_to_block"
+external marshal_from_block : string -> int -> 'a = "marshal_from_block"
+external static_alloc : int -> string = "caml_static_alloc"
+
+let test_block () =
+ let s = static_alloc 512 in
+ marshal_to_block s 512 1 [];
+ test 401 (marshal_from_block s 512 = 1);
+ marshal_to_block s 512 (-1) [];
+ test 402 (marshal_from_block s 512 = (-1));
+ marshal_to_block s 512 258 [];
+ test 403 (marshal_from_block s 512 = 258);
+ marshal_to_block s 512 20000 [];
+ test 404 (marshal_from_block s 512 = 20000);
+ marshal_to_block s 512 0x12345678 [];
+ test 405 (marshal_from_block s 512 = 0x12345678);
+ marshal_to_block s 512 bigint [];
+ test 406 (marshal_from_block s 512 = bigint);
+ marshal_to_block s 512 "foobargeebuz" [];
+ test 407 (marshal_from_block s 512 = "foobargeebuz");
+ marshal_to_block s 512 longstring [];
+ test 408 (marshal_from_block s 512 = longstring);
+ test 409
+ (try marshal_to_block s 512 verylongstring []; false
+ with Failure "Marshal.to_buffer: buffer overflow" -> true);
+ marshal_to_block s 512 3.141592654 [];
+ test 410 (marshal_from_block s 512 = 3.141592654);
+ marshal_to_block s 512 () [];
+ test 411 (marshal_from_block s 512 = ());
+ marshal_to_block s 512 A [];
+ test 412 (match marshal_from_block s 512 with
+ A -> true
+ | _ -> false);
+ marshal_to_block s 512 (B 1) [];
+ test 413 (match marshal_from_block s 512 with
+ (B 1) -> true
+ | _ -> false);
+ marshal_to_block s 512 (C 2.718) [];
+ test 414 (match marshal_from_block s 512 with
+ (C f) -> f = 2.718
+ | _ -> false);
+ marshal_to_block s 512 (D "hello, world!") [];
+ test 415 (match marshal_from_block s 512 with
+ (D "hello, world!") -> true
+ | _ -> false);
+ marshal_to_block s 512 (E 'l') [];
+ test 416 (match marshal_from_block s 512 with
+ (E 'l') -> true
+ | _ -> false);
+ marshal_to_block s 512 (F(B 1)) [];
+ test 417 (match marshal_from_block s 512 with
+ (F(B 1)) -> true
+ | _ -> false);
+ marshal_to_block s 512 (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) [];
+ test 418 (match marshal_from_block s 512 with
+ (G(A, G(B 2, G(C 3.14, G(D "glop", E 'e'))))) -> true
+ | _ -> false);
+ marshal_to_block s 512 (H(1, A)) [];
+ test 419 (match marshal_from_block s 512 with
+ (H(1, A)) -> true
+ | _ -> false);
+ marshal_to_block s 512 (I(B 2, 1e-6)) [];
+ test 420 (match marshal_from_block s 512 with
+ (I(B 2, 1e-6)) -> true
+ | _ -> false);
+ let x = D "sharing" in
+ let y = G(x, x) in
+ let z = G(y, G(x, y)) in
+ marshal_to_block s 512 z [];
+ test 421 (match marshal_from_block s 512 with
+ G((G((D "sharing" as t1), t2) as t3), G(t4, t5)) ->
+ t1 == t2 && t3 == t5 && t4 == t1
+ | _ -> false);
+ marshal_to_block s 512 [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|] [];
+ test 422 (marshal_from_block s 512 =
+ [|1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16|]);
+ let rec big n = if n <= 0 then A else H(n, big(n-1)) in
+ test 423
+ (try marshal_to_block s 512 (big 1000) []; false
+ with Failure _ -> true);
+ test 424
+ (try marshal_to_block s 512 "Hello, world!" [];
+ ignore (marshal_from_block s 8);
+ false
+ with Failure _ -> true)
+
+(* Test for really big objects *)
+
+let counter = ref 0
+
+let rec make_big n =
+ if n <= 0 then begin
+ incr counter; B !counter
+ end else begin
+ let l = make_big (n-1) in
+ let r = make_big (n-1) in
+ G(l, r)
+ end
+
+let rec check_big n x =
+ if n <= 0 then begin
+ match x with
+ B k -> incr counter; k = !counter
+ | _ -> false
+ end else begin
+ match x with
+ G(l, r) -> check_big (n-1) l && check_big (n-1) r
+ | _ -> false
+ end
+
+(* Test for really deep data structures *)
+let test_deep () =
+ (* Right-leaning *)
+ let rec loop acc i =
+ if i < max_data_depth
+ then loop (i :: acc) (i+1)
+ else acc in
+ let x = loop [] 0 in
+ let s = Marshal.to_string x [] in
+ test 425 (Marshal.from_string s 0 = x);
+ (* Left-leaning *)
+ let rec loop acc i =
+ if i < max_data_depth
+ then loop (G(acc, B i)) (i+1)
+ else acc in
+ let x = loop A 0 in
+ let s = Marshal.to_string x [] in
+ test 426 (Marshal.from_string s 0 = x)
+
+(* Test for objects *)
+class foo = object (self : 'self)
+ val data1 = "foo"
+ val data2 = "bar"
+ val data3 = 42L
+ method test1 = data1 ^ data2
+ method test2 = false
+ method test3 = self#test1
+ method test4 = data3
+end
+
+class bar = object (self : 'self)
+ inherit foo as super
+ val! data2 = "test5"
+ val data4 = "test3"
+ val data5 = "test4"
+ method test1 =
+ data1
+ ^ data2
+ ^ data4
+ ^ data5
+ ^ Int64.to_string self#test4
+end
+
+class foobar = object (self : 'self)
+ inherit foo as super
+ inherit! bar
+end
+
+(* Test for objects *)
+let test_objects () =
+ let x = new foo in
+ let s = Marshal.to_string x [Marshal.Closures] in
+ let x = Marshal.from_string s 0 in
+ test 500 (x#test1 = "foobar");
+ test 501 (x#test2 = false);
+ test 502 (x#test3 = "foobar");
+ test 503 (x#test4 = 42L);
+ let x = new bar in
+ let s = Marshal.to_string x [Marshal.Closures] in
+ let x = Marshal.from_string s 0 in
+ test 504 (x#test1 = "footest5test3test442");
+ test 505 (x#test2 = false);
+ test 506 (x#test3 = "footest5test3test442");
+ test 507 (x#test4 = 42L);
+ let x0 = new foobar in
+ let s = Marshal.to_string x0 [Marshal.Closures] in
+ let x = Marshal.from_string s 0 in
+ test 508 (x#test1 = "footest5test3test442");
+ test 509 (x#test2 = false);
+ test 510 (x#test3 = "footest5test3test442");
+ test 511 (x#test4 = 42L);
+ test 512 (Oo.id x = Oo.id x0 + 1) (* PR#5610 *)
+
+(* Test for infix pointers *)
+let test_infix () =
+ let t = true and
+ f = false in
+ let rec odd n =
+ if n = 0
+ then f
+ else even (n-1)
+ and even n =
+ if n = 0
+ then t
+ else odd (n-1)
+ in
+ let s = Marshal.to_string (odd, even) [Marshal.Closures] in
+ let (odd', even': (int -> bool) * (int -> bool)) = Marshal.from_string s 0 in
+ test 600 (odd' 41 = true);
+ test 601 (odd' 41 = odd 41);
+ test 602 (odd' 142 = false);
+ test 603 (odd' 142 = odd 142);
+ test 604 (even' 41 = false);
+ test 605 (even' 41 = even 41);
+ test 606 (even' 142 = true);
+ test 607 (even' 142 = even 142)
+
+
+let test_mutual_rec_regression () =
+ (* this regression was reported by Cedric Pasteur in PR#5772 *)
+ let rec test_one q x = x > 3
+ and test_list q = List.for_all (test_one q) q in
+ let g () = () in
+ let f q = if test_list q then g () in
+
+ test 700 (try ignore (Marshal.to_string f [Marshal.Closures]); true
+ with _ -> false)
+
+let main() =
+ if Array.length Sys.argv <= 2 then begin
+ test_out "intext.data"; test_in "intext.data";
+ test_out "intext.data"; test_in "intext.data";
+ Sys.remove "intext.data";
+ test_string();
+ test_buffer();
+ test_size();
+ test_block();
+ test_deep();
+ test_objects();
+ test_infix ();
+ test_mutual_rec_regression ();
+ end else
+ if Sys.argv.(1) = "make" then begin
+ let n = int_of_string Sys.argv.(2) in
+ let oc = open_out_bin "intext.data" in
+ counter := 0;
+ output_value oc (make_big n);
+ close_out oc
+ end else
+ if Sys.argv.(1) = "test" then begin
+ let n = int_of_string Sys.argv.(2) in
+ let ic = open_in_bin "intext.data" in
+ let b = (input_value ic : t) in
+ Gc.full_major();
+ close_in ic;
+ counter := 0;
+ if check_big n b then
+ Printf.printf "Test big %d passed" n
+ else
+ Printf.printf "Test big %d FAILED" n;
+ print_newline()
+ end
+
+let _ = Printexc.catch main (); exit 0
diff --git a/testsuite/tests/lib-marshal/intext.reference b/testsuite/tests/lib-marshal/intext.reference
new file mode 100644
index 0000000000..af16fa3786
--- /dev/null
+++ b/testsuite/tests/lib-marshal/intext.reference
@@ -0,0 +1,173 @@
+Test 1 passed.
+Test 2 passed.
+Test 3 passed.
+Test 4 passed.
+Test 5 passed.
+Test 6 passed.
+Test 7 passed.
+Test 8 passed.
+Test 9 passed.
+Test 10 passed.
+Test 11 passed.
+Test 12 passed.
+Test 13 passed.
+Test 14 passed.
+Test 15 passed.
+Test 16 passed.
+Test 17 passed.
+Test 18 passed.
+Test 19 passed.
+Test 20 passed.
+Test 21 passed.
+Test 22 passed.
+Test 23 passed.
+Test 24 passed.
+Test 25 passed.
+Test 26 passed.
+Test 27 passed.
+Test 28 passed.
+Test 29 passed.
+Test 30 passed.
+Test 31 passed.
+Test 32 passed.
+Test 33 passed.
+Test 34 passed.
+Test 35 passed.
+Test 36 passed.
+Test 37 passed.
+Test 38 passed.
+Test 39 passed.
+Test 1 passed.
+Test 2 passed.
+Test 3 passed.
+Test 4 passed.
+Test 5 passed.
+Test 6 passed.
+Test 7 passed.
+Test 8 passed.
+Test 9 passed.
+Test 10 passed.
+Test 11 passed.
+Test 12 passed.
+Test 13 passed.
+Test 14 passed.
+Test 15 passed.
+Test 16 passed.
+Test 17 passed.
+Test 18 passed.
+Test 19 passed.
+Test 20 passed.
+Test 21 passed.
+Test 22 passed.
+Test 23 passed.
+Test 24 passed.
+Test 25 passed.
+Test 26 passed.
+Test 27 passed.
+Test 28 passed.
+Test 29 passed.
+Test 30 passed.
+Test 31 passed.
+Test 32 passed.
+Test 33 passed.
+Test 34 passed.
+Test 35 passed.
+Test 36 passed.
+Test 37 passed.
+Test 38 passed.
+Test 39 passed.
+Test 101 passed.
+Test 102 passed.
+Test 103 passed.
+Test 104 passed.
+Test 105 passed.
+Test 106 passed.
+Test 107 passed.
+Test 108 passed.
+Test 109 passed.
+Test 110 passed.
+Test 111 passed.
+Test 112 passed.
+Test 113 passed.
+Test 114 passed.
+Test 115 passed.
+Test 116 passed.
+Test 117 passed.
+Test 118 passed.
+Test 119 passed.
+Test 120 passed.
+Test 121 passed.
+Test 122 passed.
+Test 123 passed.
+Test 201 passed.
+Test 202 passed.
+Test 203 passed.
+Test 204 passed.
+Test 205 passed.
+Test 206 passed.
+Test 207 passed.
+Test 208 passed.
+Test 209 passed.
+Test 210 passed.
+Test 211 passed.
+Test 212 passed.
+Test 213 passed.
+Test 214 passed.
+Test 215 passed.
+Test 216 passed.
+Test 217 passed.
+Test 218 passed.
+Test 219 passed.
+Test 220 passed.
+Test 221 passed.
+Test 222 passed.
+Test 223 passed.
+Test 300 passed.
+Test 401 passed.
+Test 402 passed.
+Test 403 passed.
+Test 404 passed.
+Test 405 passed.
+Test 406 passed.
+Test 407 passed.
+Test 408 passed.
+Test 409 passed.
+Test 410 passed.
+Test 411 passed.
+Test 412 passed.
+Test 413 passed.
+Test 414 passed.
+Test 415 passed.
+Test 416 passed.
+Test 417 passed.
+Test 418 passed.
+Test 419 passed.
+Test 420 passed.
+Test 421 passed.
+Test 422 passed.
+Test 423 passed.
+Test 424 passed.
+Test 425 passed.
+Test 426 passed.
+Test 500 passed.
+Test 501 passed.
+Test 502 passed.
+Test 503 passed.
+Test 504 passed.
+Test 505 passed.
+Test 506 passed.
+Test 507 passed.
+Test 508 passed.
+Test 509 passed.
+Test 510 passed.
+Test 511 passed.
+Test 512 passed.
+Test 600 passed.
+Test 601 passed.
+Test 602 passed.
+Test 603 passed.
+Test 604 passed.
+Test 605 passed.
+Test 606 passed.
+Test 607 passed.
+Test 700 passed.
diff --git a/testsuite/tests/lib-marshal/intextaux.c b/testsuite/tests/lib-marshal/intextaux.c
new file mode 100644
index 0000000000..03688462d6
--- /dev/null
+++ b/testsuite/tests/lib-marshal/intextaux.c
@@ -0,0 +1,25 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 2001 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/intext.h>
+
+value marshal_to_block(value vbuf, value vlen, value v, value vflags)
+{
+ return Val_long(output_value_to_block(v, vflags,
+ (char *) vbuf, Long_val(vlen)));
+}
+
+value marshal_from_block(value vbuf, value vlen)
+{
+ return input_value_from_block((char *) vbuf, Long_val(vlen));
+}
diff --git a/testsuite/tests/lib-num-2/Makefile b/testsuite/tests/lib-num-2/Makefile
new file mode 100644
index 0000000000..142e5d654d
--- /dev/null
+++ b/testsuite/tests/lib-num-2/Makefile
@@ -0,0 +1,20 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+LIBRARIES=nums
+ADD_COMPFLAGS=-I $(OTOPDIR)/otherlibs/num
+LD_PATH=$(TOPDIR)/otherlibs/num
+PROGRAM_ARGS=1000
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-num-2/pi_big_int.ml b/testsuite/tests/lib-num-2/pi_big_int.ml
new file mode 100644
index 0000000000..acf9af623e
--- /dev/null
+++ b/testsuite/tests/lib-num-2/pi_big_int.ml
@@ -0,0 +1,90 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Estime, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2008 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+(* Pi digits computed with the sreaming algorithm given on pages 4, 6
+ & 7 of "Unbounded Spigot Algorithms for the Digits of Pi", Jeremy
+ Gibbons, August 2004. *)
+
+open Printf;;
+open Big_int;;
+
+let ( !$ ) = Big_int.big_int_of_int
+and ( +$ ) = Big_int.add_big_int
+and ( *$ ) = Big_int.mult_big_int
+and ( =$ ) = Big_int.eq_big_int
+;;
+
+let zero = Big_int.zero_big_int
+and one = Big_int.unit_big_int
+and three = !$ 3
+and four = !$ 4
+and ten = !$ 10
+and neg_ten = !$(-10)
+;;
+
+(* Linear Fractional (aka M=F6bius) Transformations *)
+module LFT = struct
+
+ let floor_ev (q, r, s, t) x = div_big_int (q *$ x +$ r) (s *$ x +$ t);;
+
+ let unit = (one, zero, zero, one);;
+
+ let comp (q, r, s, t) (q', r', s', t') =
+ (q *$ q' +$ r *$ s', q *$ r' +$ r *$ t',
+ s *$ q' +$ t *$ s', s *$ r' +$ t *$ t')
+;;
+
+end
+;;
+
+let next z = LFT.floor_ev z three
+and safe z n = (n =$ LFT.floor_ev z four)
+and prod z n = LFT.comp (ten, neg_ten *$ n, zero, one) z
+and cons z k =
+ let den = 2 * k + 1 in
+ LFT.comp z (!$ k, !$(2 * den), zero, !$ den)
+;;
+
+let rec digit k z n row col =
+ if n > 0 then
+ let y = next z in
+ if safe z y then
+ if col = 10 then (
+ let row = row + 10 in
+ printf "\t:%i\n%s" row (string_of_big_int y);
+ digit k (prod z y) (n - 1) row 1
+ )
+ else (
+ print_string(string_of_big_int y);
+ digit k (prod z y) (n - 1) row (col + 1)
+ )
+ else digit (k + 1) (cons z k) n row col
+ else
+ printf "%*s\t:%i\n" (10 - col) "" (row + col)
+;;
+
+let digits n = digit 1 LFT.unit n 0 0
+;;
+
+let usage () =
+ prerr_endline "Usage: pi_big_int <number of digits to compute for pi>";
+ exit 2
+;;
+
+let main () =
+ let args = Sys.argv in
+ if Array.length args <> 2 then usage () else
+ digits (int_of_string Sys.argv.(1))
+;;
+
+main ()
+;;
diff --git a/testsuite/tests/lib-num-2/pi_big_int.reference b/testsuite/tests/lib-num-2/pi_big_int.reference
new file mode 100644
index 0000000000..ad4dc9962b
--- /dev/null
+++ b/testsuite/tests/lib-num-2/pi_big_int.reference
@@ -0,0 +1,100 @@
+3141592653 :10
+5897932384 :20
+6264338327 :30
+9502884197 :40
+1693993751 :50
+0582097494 :60
+4592307816 :70
+4062862089 :80
+9862803482 :90
+5342117067 :100
+9821480865 :110
+1328230664 :120
+7093844609 :130
+5505822317 :140
+2535940812 :150
+8481117450 :160
+2841027019 :170
+3852110555 :180
+9644622948 :190
+9549303819 :200
+6442881097 :210
+5665933446 :220
+1284756482 :230
+3378678316 :240
+5271201909 :250
+1456485669 :260
+2346034861 :270
+0454326648 :280
+2133936072 :290
+6024914127 :300
+3724587006 :310
+6063155881 :320
+7488152092 :330
+0962829254 :340
+0917153643 :350
+6789259036 :360
+0011330530 :370
+5488204665 :380
+2138414695 :390
+1941511609 :400
+4330572703 :410
+6575959195 :420
+3092186117 :430
+3819326117 :440
+9310511854 :450
+8074462379 :460
+9627495673 :470
+5188575272 :480
+4891227938 :490
+1830119491 :500
+2983367336 :510
+2440656643 :520
+0860213949 :530
+4639522473 :540
+7190702179 :550
+8609437027 :560
+7053921717 :570
+6293176752 :580
+3846748184 :590
+6766940513 :600
+2000568127 :610
+1452635608 :620
+2778577134 :630
+2757789609 :640
+1736371787 :650
+2146844090 :660
+1224953430 :670
+1465495853 :680
+7105079227 :690
+9689258923 :700
+5420199561 :710
+1212902196 :720
+0864034418 :730
+1598136297 :740
+7477130996 :750
+0518707211 :760
+3499999983 :770
+7297804995 :780
+1059731732 :790
+8160963185 :800
+9502445945 :810
+5346908302 :820
+6425223082 :830
+5334468503 :840
+5261931188 :850
+1710100031 :860
+3783875288 :870
+6587533208 :880
+3814206171 :890
+7766914730 :900
+3598253490 :910
+4287554687 :920
+3115956286 :930
+3882353787 :940
+5937519577 :950
+8185778053 :960
+2171226806 :970
+6130019278 :980
+7661119590 :990
+9216420198 :1000
diff --git a/testsuite/tests/lib-num-2/pi_num.ml b/testsuite/tests/lib-num-2/pi_num.ml
new file mode 100644
index 0000000000..a0651a8781
--- /dev/null
+++ b/testsuite/tests/lib-num-2/pi_num.ml
@@ -0,0 +1,84 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Estime, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2008 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+(* Pi digits computed with the sreaming algorithm given on pages 4, 6
+ & 7 of "Unbounded Spigot Algorithms for the Digits of Pi", Jeremy
+ Gibbons, August 2004. *)
+
+open Printf;;
+open Num;;
+
+let zero = num_of_int 0
+and one = num_of_int 1
+and three = num_of_int 3
+and four = num_of_int 4
+and ten = num_of_int 10
+and neg_ten = num_of_int(-10)
+;;
+
+(* Linear Fractional Transformation *)
+module LFT = struct
+
+ let floor_ev (q, r, s, t) x = quo_num (q */ x +/ r) (s */ x +/ t);;
+
+ let unit = (one, zero, zero, one);;
+
+ let comp (q, r, s, t) (q', r', s', t') =
+ (q */ q' +/ r */ s', q */ r' +/ r */ t',
+ s */ q' +/ t */ s', s */ r' +/ t */ t')
+;;
+
+end
+;;
+
+let next z = LFT.floor_ev z three
+and safe z n = (n =/ LFT.floor_ev z four)
+and prod z n = LFT.comp (ten, neg_ten */ n, zero, one) z
+and cons z k =
+ let den = 2 * k + 1 in
+ LFT.comp z (num_of_int k, num_of_int(2 * den), zero, num_of_int den)
+;;
+
+let rec digit k z n row col =
+ if n > 0 then
+ let y = next z in
+ if safe z y then
+ if col = 10 then (
+ let row = row + 10 in
+ printf "\t:%i\n%s" row (string_of_num y);
+ digit k (prod z y) (n-1) row 1
+ )
+ else (
+ print_string(string_of_num y);
+ digit k (prod z y) (n-1) row (col + 1)
+ )
+ else digit (k + 1) (cons z k) n row col
+ else
+ printf "%*s\t:%i\n" (10 - col) "" (row + col)
+;;
+
+let digits n = digit 1 LFT.unit n 0 0
+;;
+
+let usage () =
+ prerr_endline "Usage: pi_num <number of digits to compute for pi>";
+ exit 2
+;;
+
+let main () =
+ let args = Sys.argv in
+ if Array.length args <> 2 then usage () else
+ digits (int_of_string Sys.argv.(1))
+;;
+
+main ()
+;;
diff --git a/testsuite/tests/lib-num-2/pi_num.reference b/testsuite/tests/lib-num-2/pi_num.reference
new file mode 100644
index 0000000000..ad4dc9962b
--- /dev/null
+++ b/testsuite/tests/lib-num-2/pi_num.reference
@@ -0,0 +1,100 @@
+3141592653 :10
+5897932384 :20
+6264338327 :30
+9502884197 :40
+1693993751 :50
+0582097494 :60
+4592307816 :70
+4062862089 :80
+9862803482 :90
+5342117067 :100
+9821480865 :110
+1328230664 :120
+7093844609 :130
+5505822317 :140
+2535940812 :150
+8481117450 :160
+2841027019 :170
+3852110555 :180
+9644622948 :190
+9549303819 :200
+6442881097 :210
+5665933446 :220
+1284756482 :230
+3378678316 :240
+5271201909 :250
+1456485669 :260
+2346034861 :270
+0454326648 :280
+2133936072 :290
+6024914127 :300
+3724587006 :310
+6063155881 :320
+7488152092 :330
+0962829254 :340
+0917153643 :350
+6789259036 :360
+0011330530 :370
+5488204665 :380
+2138414695 :390
+1941511609 :400
+4330572703 :410
+6575959195 :420
+3092186117 :430
+3819326117 :440
+9310511854 :450
+8074462379 :460
+9627495673 :470
+5188575272 :480
+4891227938 :490
+1830119491 :500
+2983367336 :510
+2440656643 :520
+0860213949 :530
+4639522473 :540
+7190702179 :550
+8609437027 :560
+7053921717 :570
+6293176752 :580
+3846748184 :590
+6766940513 :600
+2000568127 :610
+1452635608 :620
+2778577134 :630
+2757789609 :640
+1736371787 :650
+2146844090 :660
+1224953430 :670
+1465495853 :680
+7105079227 :690
+9689258923 :700
+5420199561 :710
+1212902196 :720
+0864034418 :730
+1598136297 :740
+7477130996 :750
+0518707211 :760
+3499999983 :770
+7297804995 :780
+1059731732 :790
+8160963185 :800
+9502445945 :810
+5346908302 :820
+6425223082 :830
+5334468503 :840
+5261931188 :850
+1710100031 :860
+3783875288 :870
+6587533208 :880
+3814206171 :890
+7766914730 :900
+3598253490 :910
+4287554687 :920
+3115956286 :930
+3882353787 :940
+5937519577 :950
+8185778053 :960
+2171226806 :970
+6130019278 :980
+7661119590 :990
+9216420198 :1000
diff --git a/testsuite/tests/lib-num/Makefile b/testsuite/tests/lib-num/Makefile
new file mode 100644
index 0000000000..eaa5df7355
--- /dev/null
+++ b/testsuite/tests/lib-num/Makefile
@@ -0,0 +1,21 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=test test_nats test_big_ints test_ratios test_nums test_io
+MAIN_MODULE=end_test
+LIBRARIES=nums
+ADD_COMPFLAGS=-w a -I $(OTOPDIR)/otherlibs/num
+LD_PATH=$(TOPDIR)/otherlibs/num
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-num/end_test.ml b/testsuite/tests/lib-num/end_test.ml
new file mode 100644
index 0000000000..b22ebd8d9d
--- /dev/null
+++ b/testsuite/tests/lib-num/end_test.ml
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+Test.end_tests ();;
diff --git a/testsuite/tests/lib-num/end_test.reference b/testsuite/tests/lib-num/end_test.reference
new file mode 100644
index 0000000000..ab99ae015d
--- /dev/null
+++ b/testsuite/tests/lib-num/end_test.reference
@@ -0,0 +1,170 @@
+
+num_digits_nat
+ -1... 0... 1...
+length_nat
+ 1...
+equal_nat
+ 1... 2... 3... 4...
+incr_nat
+ 1... 2... 3... 4...
+decr_nat
+ 1... 2... 3... 4...
+is_zero_nat
+ 1... 2... 3... 4...
+string_of_nat
+ 1... 2...
+string_of_nat && nat_of_string
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19... 20... 21... 22...
+gcd_nat
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19... 20...
+sqrt_nat
+ 1... 2... 3... 4... 5...
+compare_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13...
+pred_big_int
+ 1... 2... 3...
+succ_big_int
+ 1... 2... 3...
+add_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17...
+sub_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17...
+mult_int_big_int
+ 1... 2... 3... 4...
+mult_big_int
+ 1... 2... 3... 4... 5...
+quomod_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19... 20... 21... 22... 23... 24... 25...
+gcd_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19... 20... 21... 22... 23... 24... 25... 26... 27... 28...
+int_of_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8...
+is_int_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10...
+sys_string_of_big_int
+ 1...
+big_int_of_string
+ 1... 2... 4... 5... 6... 7... 9... 10... 18... 19... 20... 21...
+power_base_int
+ 1... 2... 3...
+base_power_big_int
+ 1... 2... 3...
+power_int_positive_big_int
+ 1... 2... 3... 4... 5... 6... 7...
+power_big_int_positive_int
+ 1... 2... 3... 4... 5...
+power_big_int_positive_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8... 9...
+square_big_int
+ 1... 2... 3... 4...
+big_int_of_nativeint
+ 1... 2... 3...
+nativeint_of_big_int
+ 1... 2... 2...
+big_int_of_int32
+ 1... 2... 3...
+int32_of_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8...
+big_int_of_int64
+ 1... 2... 3... 4... 5... 6... 7... 8...
+int64_of_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8...
+and_big_int
+ 1... 2... 3... 4... 5... 6...
+or_big_int
+ 1... 2... 3... 4... 5... 6...
+xor_big_int
+ 1... 2... 3... 4... 5... 6...
+shift_left_big_int
+ 1... 2... 2... 3... 4... 5... 6...
+shift_right_big_int
+ 1... 2... 3... 4... 5... 6...
+shift_right_towards_zero_big_int
+ 1... 2...
+extract_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10...
+hashing of big integers
+ 1... 2... 3... 4... 5... 6...
+float_of_big_int
+ 1... 2... 3... 4... 5... 6... 7... 8...
+create_ratio
+ 1... 2... 3... 4... 5... 6... 7... 8...
+create_normalized_ratio
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10...
+null_denominator
+ 1... 2...
+sign_ratio
+ 1... 2... 3...
+normalize_ratio
+ 1... 2... 3... 4...
+report_sign_ratio
+ 1... 2...
+is_integer_ratio
+ 1... 2...
+add_ratio
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 1... 2... 3... 4...
+sub_ratio
+ 1... 2... 3... 4... 5... 6... 7... 8...
+mult_ratio
+ 1... 2... 3... 4... 5... 6... 7... 8...
+div_ratio
+ 1... 2... 3... 4... 5... 6... 7... 8...
+integer_ratio
+ 1... 2... 3... 4... 5...
+floor_ratio
+ 1... 2... 3... 4... 5...
+round_ratio
+ 1... 2... 3... 4... 5...
+ceiling_ratio
+ 1... 2... 3... 4... 5... 6...
+eq_ratio
+ 1... 2... 3... 4... 5...
+compare_ratio
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19... 20... 21... 22... 23... 24... 25... 26... 27... 28... 29... 30... 31... 32... 33... 34... 35... 36...
+eq_big_int_ratio
+ 1... 2... 3... 4... 5...
+compare_big_int_ratio
+ 1... 2... 3... 4... 5... 6... 7... 8... 9...
+int_of_ratio
+ 1... 2... 3... 4... 5...
+ratio_of_int
+ 1... 2...
+nat_of_ratio
+ 1... 2... 3... 4...
+ratio_of_big_int
+ 1...
+big_int_of_ratio
+ 1... 2... 3...
+string_of_ratio
+ 1... 2... 3... 4...
+ratio_of_string
+ 1... 6... 7... 8...
+round_futur_last_digit
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14... 15... 16... 17... 18... 19... 20... 21... 22... 23... 24...
+approx_ratio_fix
+ 1... 2... 3... 4... 5... 6... 7... 8... 9... 10... 11... 12... 13... 14...
+approx_ratio_exp
+ 1... 2... 3... 4... 5... 6... 7... 8... 9...
+float_of_ratio
+ 1...
+add_num
+ 1... 2... 3... 4... 5... 6... 7... 8... 9...
+sub_num
+ 1... 2... 3... 4... 5... 7... 8... 9... 10...
+mult_num
+ 1... 2... 3... 4... 5... 6... 7... 8... 9...
+div_num
+ 1... 2... 3... 4... 5... 6... 7... 8... 9...
+is_integer_num
+ 1... 2... 3... 4...
+num_of_ratio
+ 1... 2... 3...
+num_of_string
+ 1... 7... 8... 11... 12... 13... 14... 15...
+output_value/input_value on nats
+ 1... 2... 3... 4... 5... 6... 7...
+output_value/input_value on big ints
+ 1... 2... 3... 4... 5...
+output_value/input_value on nums
+ 1... 2... 3... 4... 5... 6... 7... 8...
+************* TESTS COMPLETED SUCCESSFULLY ****************
diff --git a/testsuite/tests/lib-num/test.ml b/testsuite/tests/lib-num/test.ml
new file mode 100644
index 0000000000..b04815388b
--- /dev/null
+++ b/testsuite/tests/lib-num/test.ml
@@ -0,0 +1,114 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf;;
+
+let flush_all () = flush stdout; flush stderr;;
+
+let message s = print_string s; print_newline ();;
+
+let error_occurred = ref false;;
+let immediate_failure = ref true;;
+
+let error () =
+ if !immediate_failure then exit 2 else begin
+ error_occurred := true;
+ flush_all ();
+ false
+ end;;
+
+let success () = flush_all (); true;;
+
+let function_tested = ref "";;
+
+let testing_function s =
+ flush_all ();
+ function_tested := s;
+ print_newline();
+ message s;;
+
+let test test_number eq_fun (answer, correct_answer) =
+ flush_all ();
+ if not (eq_fun answer correct_answer) then begin
+ fprintf stderr ">>> Bad result (%s, test %d)\n" !function_tested test_number;
+ error ()
+ end else begin
+ printf " %d..." test_number;
+ success ()
+ end;;
+
+let failure_test test_number fun_to_test arg =
+ flush_all ();
+ try
+ fun_to_test arg;
+ fprintf stderr ">>> Failure expected (%s, test %d)\n"
+ !function_tested test_number;
+ error ()
+ with _ ->
+ printf " %d..." test_number;
+ success ();;
+
+let failwith_test test_number fun_to_test arg correct_failure =
+ flush_all ();
+ try
+ fun_to_test arg;
+ fprintf stderr ">>> Failure expected (%s, test %d)\n"
+ !function_tested test_number;
+ error ()
+ with x ->
+ if x = correct_failure then begin
+ printf " %d..." test_number;
+ success ()
+ end else begin
+ fprintf stderr ">>> Bad failure (%s, test %d)\n"
+ !function_tested test_number;
+ error ()
+ end;;
+
+let end_tests () =
+ flush_all ();
+ print_newline ();
+ if !error_occurred then begin
+ print_endline "************* TESTS FAILED ****************"; exit 2
+ end else begin
+ print_endline "************* TESTS COMPLETED SUCCESSFULLY ****************";
+ exit 0
+ end;;
+
+let eq = (==);;
+let eq_int (i: int) (j: int) = (i = j);;
+let eq_string (i: string) (j: string) = (i = j);;
+let eq_nativeint (i: nativeint) (j: nativeint) = (i = j);;
+let eq_int32 (i: int32) (j: int32) = (i = j);;
+let eq_int64 (i: int64) (j: int64) = (i = j);;
+let eq_float (x: float) (y: float) = Pervasives.compare x y = 0;;
+
+let sixtyfour = (1 lsl 31) <> 0;;
+
+let rec gcd_int i1 i2 =
+ if i2 = 0 then abs i1 else gcd_int i2 (i1 mod i2);;
+
+let rec num_bits_int_aux n =
+ if n = 0 then 0 else succ(num_bits_int_aux (n lsr 1));;
+
+let num_bits_int n = num_bits_int_aux (abs n);;
+
+let sign_int i = if i = 0 then 0 else if i > 0 then 1 else -1;;
+
+let length_of_int = Sys.word_size - 2;;
+
+let monster_int = 1 lsl length_of_int;;
+let biggest_int = monster_int - 1;;
+let least_int = - biggest_int;;
+
+let compare_int n1 n2 =
+ if n1 == n2 then 0 else if n1 > n2 then 1 else -1;;
diff --git a/testsuite/tests/lib-num/test_big_ints.ml b/testsuite/tests/lib-num/test_big_ints.ml
new file mode 100644
index 0000000000..96b71ca570
--- /dev/null
+++ b/testsuite/tests/lib-num/test_big_ints.ml
@@ -0,0 +1,1042 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Test;;
+open Nat;;
+open Big_int;;
+open List;;
+
+testing_function "compare_big_int";;
+
+test 1
+eq_int (compare_big_int zero_big_int zero_big_int, 0);;
+test 2
+eq_int (compare_big_int zero_big_int (big_int_of_int 1), (-1));;
+test 3
+eq_int (compare_big_int zero_big_int (big_int_of_int (-1)), 1);;
+test 4
+eq_int (compare_big_int (big_int_of_int 1) zero_big_int, 1);;
+test 5
+eq_int (compare_big_int (big_int_of_int (-1)) zero_big_int, (-1));;
+test 6
+eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int 1), 0);;
+test 7
+eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int (-1)), 0);;
+test 8
+eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int (-1)), 1);;
+test 9
+eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int 1), (-1));;
+test 10
+eq_int (compare_big_int (big_int_of_int 1) (big_int_of_int 2), (-1));;
+test 11
+eq_int (compare_big_int (big_int_of_int 2) (big_int_of_int 1), 1);;
+test 12
+eq_int (compare_big_int (big_int_of_int (-1)) (big_int_of_int (-2)), 1);;
+test 13
+eq_int (compare_big_int (big_int_of_int (-2)) (big_int_of_int (-1)), (-1));;
+
+
+testing_function "pred_big_int";;
+
+test 1
+eq_big_int (pred_big_int zero_big_int, big_int_of_int (-1));;
+test 2
+eq_big_int (pred_big_int unit_big_int, zero_big_int);;
+test 3
+eq_big_int (pred_big_int (big_int_of_int (-1)), big_int_of_int (-2));;
+
+testing_function "succ_big_int";;
+
+test 1
+eq_big_int (succ_big_int zero_big_int, unit_big_int);;
+test 2
+eq_big_int (succ_big_int unit_big_int, big_int_of_int 2);;
+test 3
+eq_big_int (succ_big_int (big_int_of_int (-1)), zero_big_int);;
+
+testing_function "add_big_int";;
+
+test 1
+eq_big_int (add_big_int zero_big_int zero_big_int, zero_big_int);;
+test 2
+eq_big_int (add_big_int zero_big_int (big_int_of_int 1),
+ big_int_of_int 1);;
+test 3
+eq_big_int (add_big_int (big_int_of_int 1) zero_big_int,
+ big_int_of_int 1);;
+test 4
+eq_big_int (add_big_int zero_big_int (big_int_of_int (-1)),
+ big_int_of_int (-1));;
+test 5
+eq_big_int (add_big_int (big_int_of_int (-1)) zero_big_int,
+ big_int_of_int (-1));;
+test 6
+eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int 1),
+ big_int_of_int 2);;
+test 7
+eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int 2),
+ big_int_of_int 3);;
+test 8
+eq_big_int (add_big_int (big_int_of_int 2) (big_int_of_int 1),
+ big_int_of_int 3);;
+test 9
+eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int (-1)),
+ big_int_of_int (-2));;
+test 10
+eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int (-2)),
+ big_int_of_int (-3));;
+test 11
+eq_big_int (add_big_int (big_int_of_int (-2)) (big_int_of_int (-1)),
+ big_int_of_int (-3));;
+test 12
+eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int (-1)),
+ zero_big_int);;
+test 13
+eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int 1),
+ zero_big_int);;
+test 14
+eq_big_int (add_big_int (big_int_of_int 1) (big_int_of_int (-2)),
+ big_int_of_int (-1));;
+test 15
+eq_big_int (add_big_int (big_int_of_int (-2)) (big_int_of_int 1),
+ big_int_of_int (-1));;
+test 16
+eq_big_int (add_big_int (big_int_of_int (-1)) (big_int_of_int 2),
+ big_int_of_int 1);;
+test 17
+eq_big_int (add_big_int (big_int_of_int 2) (big_int_of_int (-1)),
+ big_int_of_int 1);;
+
+
+testing_function "sub_big_int";;
+
+test 1
+eq_big_int (sub_big_int zero_big_int zero_big_int, zero_big_int);;
+test 2
+eq_big_int (sub_big_int zero_big_int (big_int_of_int 1),
+ big_int_of_int (-1));;
+test 3
+eq_big_int (sub_big_int (big_int_of_int 1) zero_big_int,
+ big_int_of_int 1);;
+test 4
+eq_big_int (sub_big_int zero_big_int (big_int_of_int (-1)),
+ big_int_of_int 1);;
+test 5
+eq_big_int (sub_big_int (big_int_of_int (-1)) zero_big_int,
+ big_int_of_int (-1));;
+test 6
+eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int 1),
+ zero_big_int);;
+test 7
+eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int 2),
+ big_int_of_int (-1));;
+test 8
+eq_big_int (sub_big_int (big_int_of_int 2) (big_int_of_int 1),
+ big_int_of_int 1);;
+test 9
+eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int (-1)),
+ zero_big_int);;
+test 10
+eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int (-2)),
+ big_int_of_int 1);;
+test 11
+eq_big_int (sub_big_int (big_int_of_int (-2)) (big_int_of_int (-1)),
+ big_int_of_int (-1));;
+test 12
+eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int (-1)),
+ big_int_of_int 2);;
+test 13
+eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int 1),
+ big_int_of_int (-2));;
+test 14
+eq_big_int (sub_big_int (big_int_of_int 1) (big_int_of_int (-2)),
+ big_int_of_int 3);;
+test 15
+eq_big_int (sub_big_int (big_int_of_int (-2)) (big_int_of_int 1),
+ big_int_of_int (-3));;
+test 16
+eq_big_int (sub_big_int (big_int_of_int (-1)) (big_int_of_int 2),
+ big_int_of_int (-3));;
+test 17
+eq_big_int (sub_big_int (big_int_of_int 2) (big_int_of_int (-1)),
+ big_int_of_int 3);;
+
+testing_function "mult_int_big_int";;
+
+test 1
+eq_big_int (mult_int_big_int 0 (big_int_of_int 3), zero_big_int);;
+test 2
+eq_big_int (mult_int_big_int 1 (big_int_of_int 3), big_int_of_int 3);;
+test 3
+eq_big_int (mult_int_big_int 1 zero_big_int, zero_big_int);;
+test 4
+eq_big_int (mult_int_big_int 2 (big_int_of_int 3), big_int_of_int 6);;
+
+testing_function "mult_big_int";;
+
+test 1
+eq_big_int (mult_big_int zero_big_int zero_big_int,
+ zero_big_int);;
+test 2
+eq_big_int (mult_big_int (big_int_of_int 2) (big_int_of_int 3),
+ big_int_of_int 6);;
+test 3
+eq_big_int (mult_big_int (big_int_of_int 2) (big_int_of_int (-3)),
+ big_int_of_int (-6));;
+test 4
+eq_big_int (mult_big_int (big_int_of_string "12724951")
+ (big_int_of_string "81749606400"),
+ big_int_of_string "1040259735709286400");;
+test 5
+eq_big_int (mult_big_int (big_int_of_string "26542080")
+ (big_int_of_string "81749606400"),
+ big_int_of_string "2169804593037312000");;
+
+testing_function "quomod_big_int";;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int 1) (big_int_of_int 1) in
+ test 1 eq_big_int (quotient, big_int_of_int 1) &&
+ test 2 eq_big_int (modulo, zero_big_int);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int 1) (big_int_of_int (-1)) in
+ test 3 eq_big_int (quotient, big_int_of_int (-1)) &&
+ test 4 eq_big_int (modulo, zero_big_int);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int (-1)) (big_int_of_int 1) in
+ test 5 eq_big_int (quotient, big_int_of_int (-1)) &&
+ test 6 eq_big_int (modulo, zero_big_int);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int 3) (big_int_of_int 2) in
+ test 7 eq_big_int (quotient, big_int_of_int 1) &&
+ test 8 eq_big_int (modulo, big_int_of_int 1);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int 5) (big_int_of_int 3) in
+ test 9 eq_big_int (quotient, big_int_of_int 1) &&
+ test 10 eq_big_int (modulo, big_int_of_int 2);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int (-5)) (big_int_of_int 3) in
+ test 11 eq_big_int (quotient, big_int_of_int (-2)) &&
+ test 12 eq_big_int (modulo, big_int_of_int 1);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int 1) (big_int_of_int 2) in
+ test 13 eq_big_int (quotient, zero_big_int) &&
+ test 14 eq_big_int (modulo, big_int_of_int 1);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int (-1)) (big_int_of_int 3) in
+ test 15 eq_big_int (quotient, minus_big_int unit_big_int) &&
+ test 16 eq_big_int (modulo, big_int_of_int 2);;
+
+failwith_test 17
+(quomod_big_int (big_int_of_int 1)) zero_big_int
+Division_by_zero
+;;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int 10) (big_int_of_int 20) in
+ test 18 eq_big_int (quotient, big_int_of_int 0) &&
+ test 19 eq_big_int (modulo, big_int_of_int 10);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int (-10)) (big_int_of_int 20) in
+ test 20 eq_big_int (quotient, big_int_of_int (-1)) &&
+ test 21 eq_big_int (modulo, big_int_of_int 10);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int 10) (big_int_of_int (-20)) in
+ test 22 eq_big_int (quotient, big_int_of_int 0) &&
+ test 23 eq_big_int (modulo, big_int_of_int 10);;
+
+let (quotient, modulo) =
+ quomod_big_int (big_int_of_int (-10)) (big_int_of_int (-20)) in
+ test 24 eq_big_int (quotient, big_int_of_int 1) &&
+ test 25 eq_big_int (modulo, big_int_of_int 10);;
+
+
+testing_function "gcd_big_int";;
+
+test 1
+eq_big_int (gcd_big_int zero_big_int zero_big_int,
+ zero_big_int);;
+test 2
+eq_big_int (gcd_big_int zero_big_int (big_int_of_int 1),
+ big_int_of_int 1);;
+test 3
+eq_big_int (gcd_big_int (big_int_of_int 1) zero_big_int,
+ big_int_of_int 1);;
+test 4
+eq_big_int (gcd_big_int (big_int_of_int 1) (big_int_of_int 2),
+ big_int_of_int 1);;
+test 5
+eq_big_int (gcd_big_int (big_int_of_int 2) (big_int_of_int 1),
+ big_int_of_int 1);;
+test 6
+eq_big_int (gcd_big_int (big_int_of_int 1) (big_int_of_int 1),
+ big_int_of_int 1);;
+test 7
+eq_big_int (gcd_big_int (big_int_of_int 9) (big_int_of_int 16),
+ big_int_of_int 1);;
+test 8
+eq_big_int (gcd_big_int (big_int_of_int 12) (big_int_of_int 16),
+ big_int_of_int 4);;
+
+for i = 9 to 28 do
+ let n1 = Random.int 1000000000
+ and n2 = Random.int 100000 in
+ let _ =
+ test i eq
+ (int_of_big_int (gcd_big_int (big_int_of_int n1) (big_int_of_int n2)),
+ gcd_int n1 n2) in
+ ()
+done;;
+
+testing_function "int_of_big_int";;
+
+test 1
+eq_int (int_of_big_int (big_int_of_int 1), 1);;
+test 2
+eq_int (int_of_big_int (big_int_of_int(-1)), -1);;
+test 3
+eq_int (int_of_big_int zero_big_int, 0);;
+test 4
+eq_int (int_of_big_int (big_int_of_int max_int), max_int);;
+test 5
+eq_int (int_of_big_int (big_int_of_int min_int), min_int);;
+failwith_test 6
+ (fun () -> int_of_big_int (succ_big_int (big_int_of_int max_int)))
+ () (Failure "int_of_big_int");;
+failwith_test 7
+ (fun () -> int_of_big_int (pred_big_int (big_int_of_int min_int)))
+ () (Failure "int_of_big_int");;
+failwith_test 8
+ (fun () -> int_of_big_int (mult_big_int (big_int_of_int min_int)
+ (big_int_of_int 2)))
+ () (Failure "int_of_big_int");;
+
+
+testing_function "is_int_big_int";;
+
+test 1
+eq (is_int_big_int (big_int_of_int 1), true);;
+test 2
+eq (is_int_big_int (big_int_of_int (-1)), true);;
+test 3
+eq (is_int_big_int (succ_big_int (big_int_of_int biggest_int)), false);;
+test 4
+eq (int_of_big_int (big_int_of_int monster_int), monster_int);;
+(* Should be true *)
+test 5
+eq (is_int_big_int (big_int_of_string (string_of_int biggest_int)), true);;
+test 6
+eq (is_int_big_int (big_int_of_string (string_of_int least_int)), true);;
+test 7
+eq (is_int_big_int (big_int_of_string (string_of_int monster_int)), true);;
+
+(* Should be false *)
+(* Successor of biggest_int is not an int *)
+test 8
+eq (is_int_big_int (succ_big_int (big_int_of_int (biggest_int))), false);;
+test 9
+eq (is_int_big_int
+ (succ_big_int (succ_big_int (big_int_of_int (biggest_int)))), false);;
+(* Negation of monster_int (as a big_int) is not an int *)
+test 10
+eq (is_int_big_int
+ (minus_big_int (big_int_of_string (string_of_int monster_int))), false);;
+
+
+testing_function "sys_string_of_big_int";;
+
+test 1
+eq_string (string_of_big_int (big_int_of_int 1), "1");;
+
+
+testing_function "big_int_of_string";;
+
+test 1
+eq_big_int (big_int_of_string "1", big_int_of_int 1);;
+test 2
+eq_big_int (big_int_of_string "-1", big_int_of_int (-1));;
+test 4
+eq_big_int (big_int_of_string "0", zero_big_int);;
+
+failwith_test 5 big_int_of_string "sdjdkfighdgf"
+ (Failure "invalid digit");;
+
+test 6
+eq_big_int (big_int_of_string "123", big_int_of_int 123);;
+test 7
+eq_big_int (big_int_of_string "+3456", big_int_of_int 3456);;
+
+test 9
+eq_big_int (big_int_of_string "-3456", big_int_of_int (-3456));;
+
+
+let implode = List.fold_left (^) "";; (* Au diable l'efficacite *)
+
+let l = rev [
+"174679877494298468451661416292903906557638850173895426081611831060970135303";
+"044177587617233125776581034213405720474892937404345377707655788096850784519";
+"539374048533324740018513057210881137248587265169064879918339714405948322501";
+"445922724181830422326068913963858377101914542266807281471620827145038901025";
+"322784396182858865537924078131032036927586614781817695777639491934361211399";
+"888524140253852859555118862284235219972858420374290985423899099648066366558";
+"238523612660414395240146528009203942793935957539186742012316630755300111472";
+"852707974927265572257203394961525316215198438466177260614187266288417996647";
+"132974072337956513457924431633191471716899014677585762010115338540738783163";
+"739223806648361958204720897858193606022290696766988489073354139289154127309";
+"916985231051926209439373780384293513938376175026016587144157313996556653811";
+"793187841050456120649717382553450099049321059330947779485538381272648295449";
+"847188233356805715432460040567660999184007627415398722991790542115164516290";
+"619821378529926683447345857832940144982437162642295073360087284113248737998";
+"046564369129742074737760485635495880623324782103052289938185453627547195245";
+"688272436219215066430533447287305048225780425168823659431607654712261368560";
+"702129351210471250717394128044019490336608558608922841794819375031757643448";
+"32"
+] in
+
+let bi1 = big_int_of_string (implode (rev l)) in
+
+let bi2 = big_int_of_string (implode (rev ("3" :: tl l))) in
+
+test 10
+eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "10"))
+ (big_int_of_string "2")))
+(* test 11
+ &&
+eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "10e0"))
+ (big_int_of_string "20e-1"))) &&
+test 12
+eq_big_int (minus_big_int bi1,
+ (add_big_int (mult_big_int bi2 (big_int_of_string "-10e0"))
+ (big_int_of_string "-20e-1"))) &&
+test 13
+eq_big_int (bi1, (add_big_int (mult_big_int bi2 (big_int_of_string "+10e0"))
+ (big_int_of_string "+20e-1"))) &&
+test 14
+eq_big_int (minus_big_int bi1,
+ (add_big_int (mult_big_int bi2 (big_int_of_string "-10e+0"))
+ (big_int_of_string "-20e-1"))) &&
+test 15
+eq_big_int (minus_big_int bi1,
+ (add_big_int (mult_big_int bi2 (big_int_of_string "-1e+1"))
+ (big_int_of_string "-2e-0"))) &&
+test 16
+eq_big_int (minus_big_int bi1,
+ (add_big_int (mult_big_int bi2 (big_int_of_string "-0.1e+2"))
+ (big_int_of_string "-2.0e-0"))) &&
+test 17
+eq_big_int (minus_big_int bi1,
+ (add_big_int (mult_big_int bi2 (big_int_of_string "-1.000e+1"))
+ (big_int_of_string "-0.02e2")))*)
+;;
+
+test 18
+eq_big_int (big_int_of_string "0xAbC", big_int_of_int 0xABC);;
+
+test 19
+eq_big_int (big_int_of_string "-0o452", big_int_of_int (-0o452));;
+
+test 20
+eq_big_int (big_int_of_string "0B110101", big_int_of_int 53);;
+
+test 21
+eq_big_int (big_int_of_string "0b11_01_01", big_int_of_int 53);;
+
+testing_function "power_base_int";;
+
+test 1
+eq_big_int (big_int_of_nat (power_base_int 10 0), unit_big_int)
+;;
+test 2
+eq_big_int (big_int_of_nat (power_base_int 10 8), big_int_of_int 100000000)
+;;
+test 3
+eq_big_int (big_int_of_nat (power_base_int 2 (length_of_int + 2)),
+ big_int_of_nat (let nat = make_nat 2 in
+ set_digit_nat nat 1 1;
+ nat))
+;;
+
+testing_function "base_power_big_int";;
+
+test 1
+eq_big_int (base_power_big_int 10 0 (big_int_of_int 2), big_int_of_int 2);;
+test 2
+eq_big_int (base_power_big_int 10 2 (big_int_of_int 2), big_int_of_int 200);;
+test 3
+eq_big_int (base_power_big_int 10 1 (big_int_of_int 123), big_int_of_int 1230)
+;;
+
+testing_function "power_int_positive_big_int";;
+
+test 1
+eq_big_int (power_int_positive_big_int 2 (big_int_of_int 10),
+ big_int_of_int 1024);;
+test 2
+eq_big_int
+ (power_int_positive_big_int 2 (big_int_of_int 65),
+ big_int_of_string "36893488147419103232");;
+
+test 3
+eq_big_int
+ (power_int_positive_big_int 3 (big_int_of_string "47"),
+ big_int_of_string "26588814358957503287787");;
+
+test 4
+eq_big_int
+ (power_int_positive_big_int 1 (big_int_of_string "1000000000000000000000"),
+ big_int_of_int 1);;
+
+test 5
+eq_big_int
+ (power_int_positive_big_int (-1) (big_int_of_string "1000000000000000000000"),
+ big_int_of_int 1);;
+
+test 6
+eq_big_int
+ (power_int_positive_big_int (-1) (big_int_of_string "1000000000000000000001"),
+ big_int_of_int (-1));;
+
+test 7
+eq_big_int
+ (power_int_positive_big_int 0 (big_int_of_string "1000000000000000000000"),
+ big_int_of_int 0);;
+
+testing_function "power_big_int_positive_int";;
+
+test 1
+eq_big_int (power_big_int_positive_int (big_int_of_int 2) 10,
+ big_int_of_int 1024);;
+test 2
+eq_big_int
+ (power_big_int_positive_int (big_int_of_int 100) 20,
+ big_int_of_string "10000000000000000000000000000000000000000");;
+
+test 3
+eq_big_int
+ (power_big_int_positive_int (big_int_of_string "3") 47,
+ big_int_of_string "26588814358957503287787");;
+
+test 4
+eq_big_int
+ (power_big_int_positive_int (big_int_of_string "200000000000000") 34,
+ big_int_of_string
+"17179869184000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000");;
+
+test 5
+eq_big_int
+ (power_big_int_positive_int (big_int_of_string "2197609328765") 243,
+ big_int_of_string
+"12415638672345366257764851943822299490113545698929764576040102857365\
+27920436565335427676982530274588056944387957287793378051852205028658\
+73008292720317554332284838709453634119919368441951233982592586680844\
+20765201140575612595182857026804842796931784944918059630667794516774\
+58498235838834599150657873894983300999081942159304585449505963892008\
+97855706440206825609657816209327492197604711437269361628626691080334\
+38432768885637928268354258860147333786379766583179851226375449161073\
+10396958979998161989562418169797611757651190037273397850239552735199\
+63719988832594486235837899145390948533078339399890545062510060406048\
+61331200657727576638170520036143007285549092686618686739320973444703\
+33342725604091818763255601206325426337211467746377586080108631634250\
+11232258578207762608797108802386708549785680783113606089879687396654\
+54004281165259352412815385041917713969718327109245777066079665194617\
+29230093411050053217775067781725651590160086483960457766025246936489\
+92234225900994076609973190516835778346886551506344097474301175288686\
+25662752919718480402972207084177612056491949911377568680526080633587\
+33230060757162252611388973328501680433819585006035301408574879645573\
+47126018243568976860515247053858204554293343161581801846081341003624\
+22906934772131205632200433218165757307182816260714026614324014553342\
+77303133877636489457498062819003614421295692889321460150481573909330\
+77301946991278225819671075907191359721824291923283322225480199446258\
+03302645587072103949599624444368321734975586414930425964782010567575\
+43333331963876294983400462908871215572514487548352925949663431718284\
+14589547315559936497408670231851521193150991888789948397029796279240\
+53117024758684807981605608837291399377902947471927467827290844733264\
+70881963357258978768427852958888430774360783419404195056122644913454\
+24537375432013012467418602205343636983874410969339344956536142566292\
+67710105053213729008973121773436382170956191942409859915563249876601\
+97309463059908818473774872128141896864070835259683384180928526600888\
+17480854811931632353621014638284918544379784608050029606475137979896\
+79160729736625134310450643341951675749112836007180865039256361941093\
+99844921135320096085772541537129637055451495234892640418746420370197\
+76655592198723057553855194566534999101921182723711243608938705766658\
+35660299983828999383637476407321955462859142012030390036241831962713\
+40429407146441598507165243069127531565881439971034178400174881243483\
+00001434950666035560134867554719667076133414445044258086968145695386\
+00575860256380332451841441394317283433596457253185221717167880159573\
+60478649571700878049257386910142909926740023800166057094445463624601\
+79490246367497489548435683835329410376623483996271147060314994344869\
+89606855219181727424853876740423210027967733989284801813769926906846\
+45570461348452758744643550541290031199432061998646306091218518879810\
+17848488755494879341886158379140088252013009193050706458824793551984\
+39285914868159111542391208521561221610797141925061986437418522494485\
+59871215531081904861310222368465288125816137210222223075106739997863\
+76953125");;
+
+testing_function "power_big_int_positive_big_int";;
+
+test 1
+eq_big_int
+ (power_big_int_positive_big_int (big_int_of_int 2) (big_int_of_int 10),
+ big_int_of_int 1024);;
+
+test 2
+eq_big_int
+ (power_big_int_positive_big_int (big_int_of_int 2) (big_int_of_int 65),
+ big_int_of_string "36893488147419103232");;
+
+test 3
+eq_big_int
+ (power_big_int_positive_big_int
+ (big_int_of_string "3") (big_int_of_string "47"),
+ big_int_of_string "26588814358957503287787");;
+
+test 4
+eq_big_int
+ (power_big_int_positive_big_int
+ (big_int_of_string "200000000000000") (big_int_of_int 34),
+ big_int_of_string
+"17179869184000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000000000000000000000000000000000000000000000000000000000000\
+00000000000");;
+
+test 5
+eq_big_int
+ (power_big_int_positive_big_int (big_int_of_string "2197609328765")
+ (big_int_of_string "243"),
+ big_int_of_string
+"12415638672345366257764851943822299490113545698929764576040102857365\
+27920436565335427676982530274588056944387957287793378051852205028658\
+73008292720317554332284838709453634119919368441951233982592586680844\
+20765201140575612595182857026804842796931784944918059630667794516774\
+58498235838834599150657873894983300999081942159304585449505963892008\
+97855706440206825609657816209327492197604711437269361628626691080334\
+38432768885637928268354258860147333786379766583179851226375449161073\
+10396958979998161989562418169797611757651190037273397850239552735199\
+63719988832594486235837899145390948533078339399890545062510060406048\
+61331200657727576638170520036143007285549092686618686739320973444703\
+33342725604091818763255601206325426337211467746377586080108631634250\
+11232258578207762608797108802386708549785680783113606089879687396654\
+54004281165259352412815385041917713969718327109245777066079665194617\
+29230093411050053217775067781725651590160086483960457766025246936489\
+92234225900994076609973190516835778346886551506344097474301175288686\
+25662752919718480402972207084177612056491949911377568680526080633587\
+33230060757162252611388973328501680433819585006035301408574879645573\
+47126018243568976860515247053858204554293343161581801846081341003624\
+22906934772131205632200433218165757307182816260714026614324014553342\
+77303133877636489457498062819003614421295692889321460150481573909330\
+77301946991278225819671075907191359721824291923283322225480199446258\
+03302645587072103949599624444368321734975586414930425964782010567575\
+43333331963876294983400462908871215572514487548352925949663431718284\
+14589547315559936497408670231851521193150991888789948397029796279240\
+53117024758684807981605608837291399377902947471927467827290844733264\
+70881963357258978768427852958888430774360783419404195056122644913454\
+24537375432013012467418602205343636983874410969339344956536142566292\
+67710105053213729008973121773436382170956191942409859915563249876601\
+97309463059908818473774872128141896864070835259683384180928526600888\
+17480854811931632353621014638284918544379784608050029606475137979896\
+79160729736625134310450643341951675749112836007180865039256361941093\
+99844921135320096085772541537129637055451495234892640418746420370197\
+76655592198723057553855194566534999101921182723711243608938705766658\
+35660299983828999383637476407321955462859142012030390036241831962713\
+40429407146441598507165243069127531565881439971034178400174881243483\
+00001434950666035560134867554719667076133414445044258086968145695386\
+00575860256380332451841441394317283433596457253185221717167880159573\
+60478649571700878049257386910142909926740023800166057094445463624601\
+79490246367497489548435683835329410376623483996271147060314994344869\
+89606855219181727424853876740423210027967733989284801813769926906846\
+45570461348452758744643550541290031199432061998646306091218518879810\
+17848488755494879341886158379140088252013009193050706458824793551984\
+39285914868159111542391208521561221610797141925061986437418522494485\
+59871215531081904861310222368465288125816137210222223075106739997863\
+76953125");;
+
+test 6
+eq_big_int
+ (power_big_int_positive_big_int (big_int_of_int 1)
+ (big_int_of_string "1000000000000000000000"),
+ big_int_of_int 1);;
+
+test 7
+eq_big_int
+ (power_big_int_positive_big_int (big_int_of_int (-1))
+ (big_int_of_string "1000000000000000000000"),
+ big_int_of_int 1);;
+
+test 8
+eq_big_int
+ (power_big_int_positive_big_int (big_int_of_int (-1))
+ (big_int_of_string "1000000000000000000001"),
+ big_int_of_int (-1));;
+
+test 9
+eq_big_int
+ (power_big_int_positive_big_int (big_int_of_int 0)
+ (big_int_of_string "1000000000000000000000"),
+ big_int_of_int 0);;
+
+testing_function "square_big_int";;
+
+test 1 eq_big_int
+ (square_big_int (big_int_of_string "0"), big_int_of_string "0");;
+test 2 eq_big_int
+ (square_big_int (big_int_of_string "1"), big_int_of_string "1");;
+test 3 eq_big_int
+ (square_big_int (big_int_of_string "-1"), big_int_of_string "1");;
+test 4 eq_big_int
+ (square_big_int (big_int_of_string "-7"), big_int_of_string "49");;
+
+
+testing_function "big_int_of_nativeint";;
+
+test 1 eq_big_int
+ (big_int_of_nativeint 0n, zero_big_int);;
+test 2 eq_big_int
+ (big_int_of_nativeint 1234n, big_int_of_string "1234");;
+test 3 eq_big_int
+ (big_int_of_nativeint (-1234n), big_int_of_string "-1234");;
+
+testing_function "nativeint_of_big_int";;
+
+test 1 eq_nativeint
+ (nativeint_of_big_int zero_big_int, 0n);;
+test 2 eq_nativeint
+ (nativeint_of_big_int (big_int_of_string "1234"), 1234n);;
+test 2 eq_nativeint
+ (nativeint_of_big_int (big_int_of_string "-1234"), -1234n);;
+
+testing_function "big_int_of_int32";;
+
+test 1 eq_big_int
+ (big_int_of_int32 0l, zero_big_int);;
+test 2 eq_big_int
+ (big_int_of_int32 2147483647l, big_int_of_string "2147483647");;
+test 3 eq_big_int
+ (big_int_of_int32 (-2147483648l), big_int_of_string "-2147483648");;
+
+testing_function "int32_of_big_int";;
+
+test 1 eq_int32
+ (int32_of_big_int zero_big_int, 0l);;
+test 2 eq_int32
+ (int32_of_big_int (big_int_of_string "2147483647"), 2147483647l);;
+test 3 eq_int32
+ (int32_of_big_int (big_int_of_string "-2147483648"), -2147483648l);;
+test 4 eq_int32
+ (int32_of_big_int (big_int_of_string "-2147"), -2147l);;
+let should_fail s =
+ try ignore (int32_of_big_int (big_int_of_string s)); 0
+ with Failure _ -> 1;;
+test 5 eq_int
+ (should_fail "2147483648", 1);;
+test 6 eq_int
+ (should_fail "-2147483649", 1);;
+test 7 eq_int
+ (should_fail "4294967296", 1);;
+test 8 eq_int
+ (should_fail "18446744073709551616", 1);;
+
+testing_function "big_int_of_int64";;
+
+test 1 eq_big_int
+ (big_int_of_int64 0L, zero_big_int);;
+test 2 eq_big_int
+ (big_int_of_int64 9223372036854775807L,
+ big_int_of_string "9223372036854775807");;
+test 3 eq_big_int
+ (big_int_of_int64 (-9223372036854775808L),
+ big_int_of_string "-9223372036854775808");;
+test 4 eq_big_int (*PR#4792*)
+ (big_int_of_int64 (Int64.of_int32 Int32.min_int),
+ big_int_of_string "-2147483648");;
+test 5 eq_big_int
+ (big_int_of_int64 1234L, big_int_of_string "1234");;
+test 6 eq_big_int
+ (big_int_of_int64 0x1234567890ABCDEFL,
+ big_int_of_string "1311768467294899695");;
+test 7 eq_big_int
+ (big_int_of_int64 (-1234L), big_int_of_string "-1234");;
+test 8 eq_big_int
+ (big_int_of_int64 (-0x1234567890ABCDEFL),
+ big_int_of_string "-1311768467294899695");;
+
+testing_function "int64_of_big_int";;
+
+test 1 eq_int64
+ (int64_of_big_int zero_big_int, 0L);;
+test 2 eq_int64
+ (int64_of_big_int (big_int_of_string "9223372036854775807"),
+ 9223372036854775807L);;
+test 3 eq_int64
+ (int64_of_big_int (big_int_of_string "-9223372036854775808"),
+ -9223372036854775808L);;
+test 4 eq_int64
+ (int64_of_big_int (big_int_of_string "-9223372036854775"),
+ -9223372036854775L);;
+test 5 eq_int64 (* PR#4804 *)
+ (int64_of_big_int (big_int_of_string "2147483648"), 2147483648L);;
+let should_fail s =
+ try ignore (int64_of_big_int (big_int_of_string s)); 0
+ with Failure _ -> 1;;
+test 6 eq_int
+ (should_fail "9223372036854775808", 1);;
+test 7 eq_int
+ (should_fail "-9223372036854775809", 1);;
+test 8 eq_int
+ (should_fail "18446744073709551616", 1);;
+
+(* build a 128-bit big int from two int64 *)
+
+let big_int_128 hi lo =
+ add_big_int (mult_big_int (big_int_of_int64 hi)
+ (big_int_of_string "18446744073709551616"))
+ (big_int_of_int64 lo);;
+let h1 = 0x7fd05b7ee46a29f8L
+and h2 = 0x64b28b8ee70b6e6dL
+and h3 = 0x58546e563f5b44f0L
+and h4 = 0x1db72f6377ff3ec6L
+and h5 = 0x4f9bb0a19c543cb1L;;
+
+testing_function "and_big_int";;
+
+test 1 eq_big_int
+ (and_big_int unit_big_int zero_big_int, zero_big_int);;
+test 2 eq_big_int
+ (and_big_int zero_big_int unit_big_int, zero_big_int);;
+test 3 eq_big_int
+ (and_big_int unit_big_int unit_big_int, unit_big_int);;
+test 4 eq_big_int
+ (and_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
+ big_int_128 (Int64.logand h1 h3) (Int64.logand h2 h4));;
+test 5 eq_big_int
+ (and_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
+ big_int_of_int64 (Int64.logand h2 h5));;
+test 6 eq_big_int
+ (and_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
+ big_int_of_int64 (Int64.logand h5 h4));;
+
+testing_function "or_big_int";;
+
+test 1 eq_big_int
+ (or_big_int unit_big_int zero_big_int, unit_big_int);;
+test 2 eq_big_int
+ (or_big_int zero_big_int unit_big_int, unit_big_int);;
+test 3 eq_big_int
+ (or_big_int unit_big_int unit_big_int, unit_big_int);;
+test 4 eq_big_int
+ (or_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
+ big_int_128 (Int64.logor h1 h3) (Int64.logor h2 h4));;
+test 5 eq_big_int
+ (or_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
+ big_int_128 h1 (Int64.logor h2 h5));;
+test 6 eq_big_int
+ (or_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
+ big_int_128 h3 (Int64.logor h5 h4));;
+
+testing_function "xor_big_int";;
+
+test 1 eq_big_int
+ (xor_big_int unit_big_int zero_big_int, unit_big_int);;
+test 2 eq_big_int
+ (xor_big_int zero_big_int unit_big_int, unit_big_int);;
+test 3 eq_big_int
+ (xor_big_int unit_big_int unit_big_int, zero_big_int);;
+test 4 eq_big_int
+ (xor_big_int (big_int_128 h1 h2) (big_int_128 h3 h4),
+ big_int_128 (Int64.logxor h1 h3) (Int64.logxor h2 h4));;
+test 5 eq_big_int
+ (xor_big_int (big_int_128 h1 h2) (big_int_of_int64 h5),
+ big_int_128 h1 (Int64.logxor h2 h5));;
+test 6 eq_big_int
+ (xor_big_int (big_int_of_int64 h5) (big_int_128 h3 h4) ,
+ big_int_128 h3 (Int64.logxor h5 h4));;
+
+testing_function "shift_left_big_int";;
+
+test 1 eq_big_int
+ (shift_left_big_int unit_big_int 0,
+ unit_big_int);;
+test 2 eq_big_int
+ (shift_left_big_int unit_big_int 1,
+ big_int_of_int 2);;
+test 2 eq_big_int
+ (shift_left_big_int unit_big_int 31,
+ big_int_of_string "2147483648");;
+test 3 eq_big_int
+ (shift_left_big_int unit_big_int 64,
+ big_int_of_string "18446744073709551616");;
+test 4 eq_big_int
+ (shift_left_big_int unit_big_int 95,
+ big_int_of_string "39614081257132168796771975168");;
+test 5 eq_big_int
+ (shift_left_big_int (big_int_of_string "39614081257132168796771975168") 67,
+ big_int_of_string "5846006549323611672814739330865132078623730171904");;
+test 6 eq_big_int
+ (shift_left_big_int (big_int_of_string "-39614081257132168796771975168") 67,
+ big_int_of_string "-5846006549323611672814739330865132078623730171904");;
+
+testing_function "shift_right_big_int";;
+
+test 1 eq_big_int
+ (shift_right_big_int unit_big_int 0,
+ unit_big_int);;
+test 2 eq_big_int
+ (shift_right_big_int (big_int_of_int 12345678) 3,
+ big_int_of_int 1543209);;
+test 3 eq_big_int
+ (shift_right_big_int (big_int_of_string "5299989648942") 32,
+ big_int_of_int 1234);;
+test 4 eq_big_int
+ (shift_right_big_int (big_int_of_string
+ "5846006549323611672814739330865132078623730171904")
+ 67,
+ big_int_of_string "39614081257132168796771975168");;
+test 5 eq_big_int
+ (shift_right_big_int (big_int_of_string "-5299989648942") 32,
+ big_int_of_int (-1235));;
+test 6 eq_big_int
+ (shift_right_big_int (big_int_of_string "-16570089876543209725755392") 27,
+ big_int_of_string "-123456790123456789");;
+
+testing_function "shift_right_towards_zero_big_int";;
+
+test 1 eq_big_int
+ (shift_right_towards_zero_big_int (big_int_of_string "-5299989648942") 32,
+ big_int_of_int (-1234));;
+test 2 eq_big_int
+ (shift_right_towards_zero_big_int (big_int_of_string
+ "-16570089876543209725755392")
+ 27,
+ big_int_of_string "-123456790123456789");;
+
+testing_function "extract_big_int";;
+
+test 1 eq_big_int
+ (extract_big_int (big_int_of_int64 0x123456789ABCDEFL) 3 13,
+ big_int_of_int 6589);;
+test 2 eq_big_int
+ (extract_big_int (big_int_128 h1 h2) 67 12,
+ big_int_of_int 1343);;
+test 3 eq_big_int
+ (extract_big_int (big_int_of_string "-1844674407370955178") 37 9,
+ big_int_of_int 307);;
+test 4 eq_big_int
+ (extract_big_int unit_big_int 2048 254,
+ zero_big_int);;
+test 5 eq_big_int
+ (extract_big_int (big_int_of_int64 0x123456789ABCDEFL) 0 32,
+ big_int_of_int64 2309737967L);;
+test 6 eq_big_int
+ (extract_big_int (big_int_of_int (-1)) 0 16,
+ big_int_of_int 0xFFFF);;
+test 7 eq_big_int
+ (extract_big_int (big_int_of_int (-1)) 1027 12,
+ big_int_of_int 0xFFF);;
+test 8 eq_big_int
+ (extract_big_int (big_int_of_int (-1234567)) 0 16,
+ big_int_of_int 10617);;
+test 9 eq_big_int
+ (extract_big_int (minus_big_int (power_int_positive_int 2 64)) 64 20,
+ big_int_of_int 0xFFFFF);;
+test 10 eq_big_int
+ (extract_big_int (pred_big_int (minus_big_int (power_int_positive_int 2 64)))
+ 64 20,
+ big_int_of_int 0xFFFFE);;
+
+testing_function "hashing of big integers";;
+
+test 1 eq_int (Hashtbl.hash zero_big_int,
+ 955772237);;
+test 2 eq_int (Hashtbl.hash unit_big_int,
+ 992063522);;
+test 3 eq_int (Hashtbl.hash (minus_big_int unit_big_int),
+ 161678167);;
+test 4 eq_int (Hashtbl.hash (big_int_of_string "123456789123456789"),
+ 755417385);;
+test 5 eq_int (Hashtbl.hash (sub_big_int
+ (big_int_of_string "123456789123456789")
+ (big_int_of_string "123456789123456789")),
+ 955772237);;
+test 6 eq_int (Hashtbl.hash (sub_big_int
+ (big_int_of_string "123456789123456789")
+ (big_int_of_string "123456789123456788")),
+ 992063522);;
+
+testing_function "float_of_big_int";;
+
+test 1 eq_float (float_of_big_int zero_big_int, 0.0);;
+test 2 eq_float (float_of_big_int unit_big_int, 1.0);;
+test 3 eq_float (float_of_big_int (minus_big_int unit_big_int), -1.0);;
+test 4 eq_float (float_of_big_int (shift_left_big_int unit_big_int 1024),
+ infinity);;
+test 5 eq_float (float_of_big_int (shift_left_big_int unit_big_int 1023),
+ ldexp 1.0 1023);;
+(* Some random int64 values *)
+let ok = ref true in
+for i = 1 to 100 do
+ let n = Random.int64 Int64.max_int in
+ if not (eq_float (float_of_big_int (big_int_of_int64 n)) (Int64.to_float n))
+ then ok := false;
+ let n = Int64.neg n in
+ if not (eq_float (float_of_big_int (big_int_of_int64 n)) (Int64.to_float n))
+ then ok := false
+done;
+test 6 eq (!ok, true);;
+(* Some random int64 values scaled by some random power of 2 *)
+let ok = ref true in
+for i = 1 to 1000 do
+ let n = Random.int64 Int64.max_int in
+ let exp = Random.int 1200 in
+ if not (eq_float
+ (float_of_big_int
+ (shift_left_big_int (big_int_of_int64 n) exp))
+ (ldexp (Int64.to_float n) exp))
+ then ok := false;
+ let n = Int64.neg n in
+ if not (eq_float
+ (float_of_big_int
+ (shift_left_big_int (big_int_of_int64 n) exp))
+ (ldexp (Int64.to_float n) exp))
+ then ok := false
+done;
+test 7 eq (!ok, true);;
+(* Round to nearest even *)
+let ok = ref true in
+for i = 0 to 15 do
+ let n = Int64.(add 0xfffffffffffff0L (of_int i)) in
+ if not (eq_float
+ (float_of_big_int
+ (shift_left_big_int (big_int_of_int64 n) 32))
+ (ldexp (Int64.to_float n) 32))
+ then ok := false
+done;
+test 8 eq (!ok, true);;
diff --git a/testsuite/tests/lib-num/test_io.ml b/testsuite/tests/lib-num/test_io.ml
new file mode 100644
index 0000000000..c21ad37fe4
--- /dev/null
+++ b/testsuite/tests/lib-num/test_io.ml
@@ -0,0 +1,76 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Test
+open Nat
+open Big_int
+open Num
+
+let intern_extern obj =
+ let f = Filename.temp_file "testnum" ".data" in
+ let oc = open_out_bin f in
+ output_value oc obj;
+ close_out oc;
+ let ic = open_in_bin f in
+ let res = input_value ic in
+ close_in ic;
+ Sys.remove f;
+ res
+;;
+
+testing_function "output_value/input_value on nats";;
+
+let equal_nat n1 n2 =
+ eq_nat n1 0 (length_nat n1) n2 0 (length_nat n2)
+;;
+
+List.iter
+ (fun (i, s) ->
+ let n = nat_of_string s in
+ ignore(test i equal_nat (n, intern_extern n)))
+ [1, "0";
+ 2, "1234";
+ 3, "8589934592";
+ 4, "340282366920938463463374607431768211455";
+ 5, String.make 100 '3';
+ 6, String.make 1000 '9';
+ 7, String.make 20000 '8']
+;;
+
+testing_function "output_value/input_value on big ints";;
+
+List.iter
+ (fun (i, s) ->
+ let b = big_int_of_string s in
+ ignore(test i eq_big_int (b, intern_extern b)))
+ [1, "0";
+ 2, "1234";
+ 3, "-1234";
+ 4, "1040259735709286400";
+ 5, "-" ^ String.make 20000 '7']
+;;
+
+testing_function "output_value/input_value on nums";;
+
+List.iter
+ (fun (i, s) ->
+ let n = num_of_string s in
+ ignore(test i eq_num (n, intern_extern n)))
+ [1, "0";
+ 2, "1234";
+ 3, "-1234";
+ 4, "159873568791325097646845892426782";
+ 5, "1/4";
+ 6, "-15/2";
+ 7, "159873568791325097646845892426782/24098772507410987265987";
+ 8, String.make 10000 '3' ^ "/" ^ String.make 5000 '7']
+;;
diff --git a/testsuite/tests/lib-num/test_nats.ml b/testsuite/tests/lib-num/test_nats.ml
new file mode 100644
index 0000000000..541dd4c697
--- /dev/null
+++ b/testsuite/tests/lib-num/test_nats.ml
@@ -0,0 +1,161 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Test;;
+open Nat;;
+
+(* Can compare nats less than 2**32 *)
+let equal_nat n1 n2 =
+ eq_nat n1 0 (num_digits_nat n1 0 1)
+ n2 0 (num_digits_nat n2 0 1);;
+
+testing_function "num_digits_nat";;
+
+test (-1) eq (false,not true);;
+test 0 eq (true,not false);;
+
+test 1
+eq_int
+(let r = make_nat 2 in
+ set_digit_nat r 1 1;
+ num_digits_nat r 0 1,1);;
+
+testing_function "length_nat";;
+
+test 1
+eq_int
+(let r = make_nat 2 in
+ set_digit_nat r 0 1;
+ length_nat r,2);;
+
+testing_function "equal_nat";;
+
+let zero_nat = make_nat 1 in
+
+test 1
+equal_nat (zero_nat,zero_nat);;
+test 2
+equal_nat (nat_of_int 1,nat_of_int 1);;
+
+test 3
+equal_nat (nat_of_string "2",nat_of_string "2");;
+test 4
+eq (equal_nat (nat_of_string "2")(nat_of_string "3"),false);;
+
+testing_function "incr_nat";;
+
+let zero = nat_of_int 0 in
+let res = incr_nat zero 0 1 1 in
+ test 1
+ equal_nat (zero, nat_of_int 1) &&
+ test 2
+ eq (res,0);;
+
+let n = nat_of_int 1 in
+let res = incr_nat n 0 1 1 in
+ test 3
+ equal_nat (n, nat_of_int 2) &&
+ test 4
+ eq (res,0);;
+
+
+testing_function "decr_nat";;
+
+let n = nat_of_int 1 in
+let res = decr_nat n 0 1 0 in
+ test 1
+ equal_nat (n, nat_of_int 0) &&
+ test 2
+ eq (res,1);;
+
+let n = nat_of_int 2 in
+let res = decr_nat n 0 1 0 in
+ test 3
+ equal_nat (n, nat_of_int 1) &&
+ test 4
+ eq (res,1);;
+
+testing_function "is_zero_nat";;
+
+let n = nat_of_int 1 in
+test 1 eq (is_zero_nat n 0 1,false) &&
+test 2 eq (is_zero_nat (make_nat 1) 0 1, true) &&
+test 3 eq (is_zero_nat (make_nat 2) 0 2, true) &&
+(let r = make_nat 2 in
+ set_digit_nat r 1 1;
+ test 4 eq (is_zero_nat r 0 1, true))
+;;
+
+testing_function "string_of_nat";;
+
+let n = make_nat 4;;
+
+test 1 eq_string (string_of_nat n, "0");;
+
+complement_nat n 0 (if sixtyfour then 2 else 4);;
+
+test 2 eq_string (string_of_nat n, "340282366920938463463374607431768211455");;
+
+testing_function "string_of_nat && nat_of_string";;
+
+for i = 1 to 20 do
+ let s = String.make i '0' in
+ String.set s 0 '1';
+ ignore (test i eq_string (string_of_nat (nat_of_string s), s))
+done;;
+
+let set_mult_digit_nat n1 d1 l1 n2 d2 l2 n3 d3 =
+ ignore (mult_digit_nat n1 d1 l1 n2 d2 l2 n3 d3)
+;;
+
+let s =
+ "33333333333333333333333333333333333333333333333333333333333333333333\
+ 33333333333333333333333333333333333333333333333333333333333333333333"
+in
+test 21 equal_nat (
+nat_of_string s,
+(let nat = make_nat 15 in
+ set_digit_nat nat 0 3;
+ set_mult_digit_nat nat 0 15
+ (nat_of_string (String.sub s 0 135)) 0 14
+ (nat_of_int 10) 0;
+ nat))
+;;
+
+test 22 eq_string (string_of_nat(nat_of_string "1073741824"), "1073741824");;
+
+testing_function "gcd_nat";;
+
+for i = 1 to 20 do
+ let n1 = Random.int 1000000000
+ and n2 = Random.int 100000 in
+ let nat1 = nat_of_int n1
+ and nat2 = nat_of_int n2 in
+ ignore (gcd_nat nat1 0 1 nat2 0 1);
+ ignore (test i eq (int_of_nat nat1, gcd_int n1 n2))
+done
+;;
+
+testing_function "sqrt_nat";;
+
+test 1 equal_nat (sqrt_nat (nat_of_int 1) 0 1, nat_of_int 1);;
+test 2 equal_nat (let n = nat_of_string "8589934592" in
+ sqrt_nat n 0 (length_nat n),
+ nat_of_string "92681");;
+test 3 equal_nat (let n = nat_of_string "4294967295" in
+ sqrt_nat n 0 (length_nat n),
+ nat_of_string "65535");;
+test 4 equal_nat (let n = nat_of_string "18446744065119617025" in
+ sqrt_nat n 0 (length_nat n),
+ nat_of_string "4294967295");;
+test 5 equal_nat (sqrt_nat (nat_of_int 15) 0 1,
+ nat_of_int 3);;
diff --git a/testsuite/tests/lib-num/test_nums.ml b/testsuite/tests/lib-num/test_nums.ml
new file mode 100644
index 0000000000..6f419b35bc
--- /dev/null
+++ b/testsuite/tests/lib-num/test_nums.ml
@@ -0,0 +1,246 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Test;;
+open Nat;;
+open Big_int;;
+open Ratio;;
+open Num;;
+open Arith_status;;
+
+testing_function "add_num";;
+
+test 1
+eq_num (add_num (Int 1) (Int 3), Int 4);;
+test 2
+eq_num (add_num (Int 1) (Big_int (big_int_of_int 3)), Int 4);;
+test 3
+eq_num (add_num (Int 1) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "7/4"));;
+test 4
+eq_num (add_num (Big_int (big_int_of_int 1)) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "7/4"));;
+test 5
+eq_num (add_num (Big_int (big_int_of_int 1)) (Big_int (big_int_of_int 3)),
+ Int 4);;
+test 6
+eq_num (add_num (Big_int (big_int_of_int 1)) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "7/4"));;
+test 7
+eq_num (add_num (Ratio (ratio_of_string "2/3")) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "17/12"));;
+test 8
+eq_num (add_num (Int least_int) (Int 1),
+ Int (- (pred biggest_int)));;
+test 9
+eq_num (add_num (Int biggest_int) (Int 1),
+ Big_int (minus_big_int (pred_big_int (big_int_of_int least_int))));;
+
+testing_function "sub_num";;
+
+test 1
+eq_num (sub_num (Int 1) (Int 3), Int (-2));;
+test 2
+eq_num (sub_num (Int 1) (Big_int (big_int_of_int 3)), Int (-2));;
+test 3
+eq_num (sub_num (Int 1) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "1/4"));;
+test 4
+eq_num (sub_num (Big_int (big_int_of_int 1)) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "1/4"));;
+test 5
+eq_num (sub_num (Big_int (big_int_of_int 1)) (Big_int (big_int_of_int 3)),
+ Int (-2));;
+test 7
+eq_num (sub_num (Big_int (big_int_of_int 1)) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "1/4"));;
+test 8
+eq_num (sub_num (Ratio (ratio_of_string "2/3")) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "-1/12"));;
+test 9
+eq_num (sub_num (Int least_int) (Int (-1)),
+ Int (- (pred biggest_int)));;
+test 10
+eq_num (sub_num (Int (-1)) (Int biggest_int), pred_num (Int least_int));;
+
+testing_function "mult_num";;
+
+test 1
+eq_num (mult_num (Int 2) (Int 3), Int 6);;
+test 2
+eq_num (mult_num (Int 127) (Int (int_of_string "257")),
+ Int (int_of_string "32639"));;
+test 3
+eq_num (mult_num (Int 257) (Int (int_of_string "260")),
+ Big_int (big_int_of_string "66820"));;
+test 4
+eq_num (mult_num (Int 2) (Big_int (big_int_of_int 3)), Int 6);;
+test 5
+eq_num (mult_num (Int 10) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "15/2"));;
+test 6
+eq_num (mult_num (Big_int (big_int_of_int 10)) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "15/2"));;
+test 7
+eq_num (mult_num (Big_int (big_int_of_int 2)) (Big_int (big_int_of_int 3)),
+ Int 6);;
+test 8
+eq_num (mult_num (Big_int (big_int_of_int 10)) (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "15/2"));;
+test 9
+eq_num (mult_num (Ratio (ratio_of_string "2/3")) (Ratio (ratio_of_string "3/4"))
+ , Ratio (ratio_of_string "1/2"));;
+
+testing_function "div_num";;
+
+test 1
+eq_num (div_num (Int 6) (Int 3), Int 2);;
+test 2
+eq_num (div_num (Int (int_of_string "32639"))
+ (Int (int_of_string "257")), Int 127);;
+test 3
+eq_num (div_num (Big_int (big_int_of_string "66820"))
+ (Int (int_of_string "257")),
+ Int 260);;
+test 4
+eq_num (div_num (Int 6) (Big_int (big_int_of_int 3)), Int 2);;
+test 5
+eq_num (div_num (Ratio (ratio_of_string "15/2"))
+ (Int 10),
+ Ratio (ratio_of_string "3/4"));;
+test 6
+eq_num (div_num (Big_int (big_int_of_int 6)) (Big_int (big_int_of_int 3)),
+ Int 2);;
+test 7
+eq_num (div_num (Ratio (ratio_of_string "15/2"))
+ (Big_int (big_int_of_int 10)),
+ Ratio (ratio_of_string "3/4"));;
+test 8
+eq_num (div_num (Ratio (ratio_of_string "15/2"))
+ (Ratio (ratio_of_string "3/4")),
+ Big_int (big_int_of_int 10));;
+test 9
+eq_num (div_num (Ratio (ratio_of_string "1/2"))
+ (Ratio (ratio_of_string "3/4")),
+ Ratio (ratio_of_string "2/3"));;
+
+testing_function "is_integer_num";;
+
+test 1
+eq (is_integer_num (Int 3),true);;
+test 2
+eq (is_integer_num (Big_int (big_int_of_string "1234567890")),true);;
+test 3
+eq (not (is_integer_num (Ratio (ratio_of_string "1/2"))),true);;
+test 4
+eq (is_integer_num (Ratio (ratio_of_string "1073774590/32770")),true);;
+
+testing_function "num_of_ratio";;
+
+test 1
+eq_num (num_of_ratio (ratio_of_string "4/2"), Int 2);;
+test 2
+eq_num (num_of_ratio (ratio_of_string "11811160075/11"),
+ Big_int (big_int_of_string "1073741825"));;
+test 3
+eq_num (num_of_ratio (ratio_of_string "123456789012/1234"),
+ Ratio (ratio_of_string "61728394506/617"));;
+
+testing_function "num_of_string";;
+
+test 1
+eq_num (num_of_string "123/3456", Ratio (ratio_of_string "123/3456"));;
+(*********
+test 2
+eq_num (num_of_string "12.3/34.56", Ratio (ratio_of_string "1230/3456"));;
+test 3
+eq_num (num_of_string "1.23/325.6", Ratio (ratio_of_string "123/32560"));;
+test 4
+eq_num (num_of_string "12.3/345.6", Ratio (ratio_of_string "123/3456"));;
+set_error_when_null_denominator false;;
+test 5
+eq_num (num_of_string "12.3/0.0", Ratio (ratio_of_string "123/0"));;
+test 6
+eq_num (num_of_string "0/0", Ratio (ratio_of_string "0/0"));;
+set_error_when_null_denominator true;;
+*********)
+test 7
+eq_num (num_of_string "1234567890",
+ Big_int (big_int_of_string "1234567890"));;
+test 8
+eq_num (num_of_string "12345", Int (int_of_string "12345"));;
+(*********
+test 9
+eq_num (num_of_string "0.23", Ratio (ratio_of_string "23/100"));;
+test 10
+eq_num (num_of_string "0.23", Ratio (ratio_of_string "0.23/1"));;
+********)
+
+failwith_test 11
+num_of_string ("frlshjkurty") (Failure "num_of_string");;
+
+test 12
+eq_num (num_of_string "0xAbCdEf",
+ Big_int (big_int_of_int 0xabcdef));;
+
+test 13
+eq_num (num_of_string "0b1101/0O1765",
+ Ratio (ratio_of_string "0b1101/0o1765"));;
+
+test 14
+eq_num (num_of_string "-12_34_56",
+ Big_int (big_int_of_int (-123456)));;
+
+test 15
+eq_num (num_of_string "0B101010", Big_int (big_int_of_int 42));;
+
+(*******
+
+testing_function "immediate numbers";;
+
+standard arith false;;
+
+let x = (1/2) in
+test 0 eq_string (string_of_num x, "1/2");;
+
+let y = 12345678901 in
+test 1 eq_string (string_of_num y, "12345678901");;
+testing_function "immediate numbers";;
+
+let x = (1/2) in
+test 0 eq_string (string_of_num x, "1/2");;
+
+let y = 12345678901 in
+test 1 eq_string (string_of_num y, "12345678901");;
+
+testing_function "pattern_matching on nums";;
+
+let f1 = function 0 -> true | _ -> false;;
+
+test 1 eq (f1 0, true);;
+
+test 2 eq (f1 1, false);;
+
+test 3 eq (f1 (0/1), true);;
+
+test 4 eq (f1 (let n = num_of_string "2000000000000000000000000" in n-n) ,
+ true);;
+
+test 5 eq (f1 (let n = num_of_string "2000000000000000000000000" in n/n-1) ,
+ true);;
+
+test 6 eq (f1 (let n = num_of_string "2000000000000000000000000" in n+1) ,
+ false);;
+
+test 7 eq (f1 (1/2), false);;
+
+**************)
diff --git a/testsuite/tests/lib-num/test_ratios.ml b/testsuite/tests/lib-num/test_ratios.ml
new file mode 100644
index 0000000000..087d0fcae0
--- /dev/null
+++ b/testsuite/tests/lib-num/test_ratios.ml
@@ -0,0 +1,1207 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Valerie Menissier-Morain, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Test;;
+open Nat;;
+open Big_int;;
+open Ratio;;
+open Arith_status;;
+
+set_error_when_null_denominator false
+;;
+
+let infinite_failure = "infinite or undefined rational number";;
+
+testing_function "create_ratio"
+;;
+
+let r = create_ratio (big_int_of_int 1) (big_int_of_int (-2)) in
+test 1 eq_big_int (numerator_ratio r, big_int_of_int (-1)) &&
+test 2 eq_big_int (denominator_ratio r, big_int_of_int 2)
+;;
+
+let r = create_ratio (big_int_of_int 2) (big_int_of_int 3) in
+test 3 eq_big_int (numerator_ratio r, big_int_of_int 2) &&
+test 4 eq_big_int (denominator_ratio r, big_int_of_int 3)
+;;
+
+set_normalize_ratio true
+;;
+
+let r = create_ratio (big_int_of_int 12) (big_int_of_int (-16)) in
+test 5 eq_big_int (numerator_ratio r, big_int_of_int (-3)) &&
+test 6 eq_big_int (denominator_ratio r, big_int_of_int 4)
+;;
+
+set_normalize_ratio false
+;;
+
+let r = create_ratio (big_int_of_int 0) (big_int_of_int 0) in
+test 7 eq_big_int (numerator_ratio r, big_int_of_int 0) &&
+test 8 eq_big_int (denominator_ratio r, big_int_of_int 0)
+;;
+
+testing_function "create_normalized_ratio"
+;;
+
+let r = create_normalized_ratio (big_int_of_int 1) (big_int_of_int (-2)) in
+test 1 eq_big_int (numerator_ratio r, big_int_of_int (-1)) &&
+test 2 eq_big_int (denominator_ratio r, big_int_of_int 2)
+;;
+
+let r = create_normalized_ratio (big_int_of_int 2) (big_int_of_int 3) in
+test 3 eq_big_int (numerator_ratio r, big_int_of_int 2) &&
+test 4 eq_big_int (denominator_ratio r, big_int_of_int 3)
+;;
+
+set_normalize_ratio true
+;;
+
+let r = create_normalized_ratio (big_int_of_int 12) (big_int_of_int (-16)) in
+test 5 eq_big_int (numerator_ratio r, big_int_of_int (-12)) &&
+test 6 eq_big_int (denominator_ratio r, big_int_of_int 16)
+;;
+
+set_normalize_ratio false
+;;
+
+let r = create_normalized_ratio (big_int_of_int 1) (big_int_of_int 0) in
+test 7 eq_big_int (numerator_ratio r, big_int_of_int 1) &&
+test 8 eq_big_int (denominator_ratio r, big_int_of_int 0)
+;;
+
+let r = create_normalized_ratio (big_int_of_int 0) (big_int_of_int 0) in
+test 9 eq_big_int (numerator_ratio r, big_int_of_int 0) &&
+test 10 eq_big_int (denominator_ratio r, big_int_of_int 0)
+;;
+
+testing_function "null_denominator"
+;;
+
+test 1
+ eq (null_denominator (create_ratio (big_int_of_int 1) (big_int_of_int (-2))),
+ false)
+;;
+test 2 eq
+ (null_denominator (create_ratio (big_int_of_int 1) zero_big_int),true)
+;;
+
+(*****
+testing_function "verify_null_denominator"
+;;
+
+test 1
+ eq (verify_null_denominator (ratio_of_string "0/1"), false)
+;;
+test 2
+ eq (verify_null_denominator (ratio_of_string "0/0"), true)
+;;
+*****)
+
+testing_function "sign_ratio"
+;;
+
+test 1
+eq_int (sign_ratio (create_ratio (big_int_of_int (-2)) (big_int_of_int (-3))),
+ 1)
+;;
+test 2
+eq_int (sign_ratio (create_ratio (big_int_of_int 2) (big_int_of_int (-3))),
+ (-1))
+;;
+test 3
+eq_int (sign_ratio (create_ratio zero_big_int (big_int_of_int (-3))), 0)
+;;
+
+testing_function "normalize_ratio"
+;;
+
+let r = create_ratio (big_int_of_int 12) (big_int_of_int (-16)) in
+ignore (normalize_ratio r);
+test 1 eq_big_int (numerator_ratio r, big_int_of_int (-3)) &&
+test 2 eq_big_int (denominator_ratio r, big_int_of_int 4)
+;;
+
+let r = create_ratio (big_int_of_int (-1)) zero_big_int in
+ignore (normalize_ratio r);
+test 3 eq_big_int (numerator_ratio r, big_int_of_int (-1)) &&
+test 4 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+testing_function "report_sign_ratio"
+;;
+
+test 1
+eq_big_int (report_sign_ratio
+ (create_ratio (big_int_of_int 2) (big_int_of_int (-3)))
+ (big_int_of_int 1),
+ big_int_of_int (-1))
+;;
+test 2
+eq_big_int (report_sign_ratio
+ (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (big_int_of_int 1),
+ big_int_of_int 1)
+;;
+
+testing_function "is_integer_ratio"
+;;
+
+test 1 eq
+ (is_integer_ratio (create_ratio (big_int_of_int 2) (big_int_of_int (-1))),
+ true)
+;;
+test 2 eq
+ (is_integer_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)),
+ false)
+;;
+
+testing_function "add_ratio"
+;;
+
+let r = add_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 2))
+ (create_ratio (big_int_of_int 2) (big_int_of_int 3)) in
+test 1 eq_big_int (numerator_ratio r, big_int_of_int 7) &&
+test 2 eq_big_int (denominator_ratio r, big_int_of_int 6)
+;;
+
+let r = add_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in
+test 3 eq_big_int (numerator_ratio r, big_int_of_int 1) &&
+test 4 eq_big_int (denominator_ratio r, big_int_of_int 6)
+;;
+
+let r = add_ratio (create_ratio (big_int_of_int 2) zero_big_int)
+ (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in
+test 5 eq_big_int (numerator_ratio r, big_int_of_int 4) &&
+test 6 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+let r = add_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 1) zero_big_int) in
+test 7 eq_big_int (numerator_ratio r, big_int_of_int 3) &&
+test 8 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+let r = add_ratio (create_ratio (big_int_of_int 2) zero_big_int)
+ (create_ratio (big_int_of_int 1) zero_big_int) in
+test 9 eq_big_int (numerator_ratio r, zero_big_int) &&
+test 10 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+let r = add_ratio (create_ratio (big_int_of_string "12724951")
+ (big_int_of_string "26542080"))
+ (create_ratio (big_int_of_string "-1")
+ (big_int_of_string "81749606400")) in
+test 11 eq_big_int (numerator_ratio r,
+ big_int_of_string "1040259735682744320") &&
+test 12 eq_big_int (denominator_ratio r,
+ big_int_of_string "2169804593037312000")
+;;
+
+let r1,r2 =
+ (create_ratio (big_int_of_string "12724951")
+ (big_int_of_string "26542080"),
+ create_ratio (big_int_of_string "-1")
+ (big_int_of_string "81749606400")) in
+
+let bi1 = mult_big_int (numerator_ratio r1) (denominator_ratio r2)
+and bi2 = mult_big_int (numerator_ratio r2) (denominator_ratio r1)
+in
+test 1
+eq_big_int (bi1,
+ big_int_of_string "1040259735709286400")
+&&
+test 2
+eq_big_int (bi2,
+ big_int_of_string "-26542080")
+&& test 3
+eq_big_int (mult_big_int (denominator_ratio r1) (denominator_ratio r2),
+ big_int_of_string "2169804593037312000")
+&& test 4
+eq_big_int (add_big_int bi1 bi2,
+ big_int_of_string "1040259735682744320")
+;;
+
+testing_function "sub_ratio"
+;;
+
+let r = sub_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 1) (big_int_of_int 2)) in
+test 1 eq_big_int (numerator_ratio r, big_int_of_int 1) &&
+test 2 eq_big_int (denominator_ratio r, big_int_of_int 6)
+;;
+
+let r = sub_ratio (create_ratio (big_int_of_int 2) zero_big_int)
+ (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in
+test 3 eq_big_int (numerator_ratio r, big_int_of_int 4) &&
+test 4 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+let r = sub_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 1) zero_big_int) in
+test 5 eq_big_int (numerator_ratio r, big_int_of_int (-3)) &&
+test 6 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+let r = sub_ratio (create_ratio (big_int_of_int 2) zero_big_int)
+ (create_ratio (big_int_of_int 1) zero_big_int) in
+test 7 eq_big_int (numerator_ratio r, zero_big_int) &&
+test 8 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+testing_function "mult_ratio"
+;;
+
+let r = mult_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 7) (big_int_of_int 5)) in
+test 1 eq_big_int (numerator_ratio r, big_int_of_int 14) &&
+test 2 eq_big_int (denominator_ratio r, big_int_of_int 15)
+;;
+
+let r = mult_ratio (create_ratio (big_int_of_int 2) zero_big_int)
+ (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in
+test 3 eq_big_int (numerator_ratio r, big_int_of_int (-2)) &&
+test 4 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+let r = mult_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 1) zero_big_int) in
+test 5 eq_big_int (numerator_ratio r, big_int_of_int 2) &&
+test 6 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+let r = mult_ratio (create_ratio (big_int_of_int 2) zero_big_int)
+ (create_ratio (big_int_of_int 1) zero_big_int) in
+test 7 eq_big_int (numerator_ratio r, big_int_of_int 2) &&
+test 8 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+testing_function "div_ratio"
+;;
+
+let r = div_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 5) (big_int_of_int 7)) in
+test 1 eq_big_int (numerator_ratio r, big_int_of_int 14) &&
+test 2 eq_big_int (denominator_ratio r, big_int_of_int 15)
+;;
+
+let r = div_ratio (create_ratio (big_int_of_int 2) zero_big_int)
+ (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in
+test 3 eq_big_int (numerator_ratio r, big_int_of_int (-4)) &&
+test 4 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+let r = div_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 1) zero_big_int) in
+test 5 eq_big_int (numerator_ratio r, zero_big_int) &&
+test 6 eq_big_int (denominator_ratio r, big_int_of_int 3)
+;;
+
+let r = div_ratio (create_ratio (big_int_of_int 2) zero_big_int)
+ (create_ratio (big_int_of_int 1) zero_big_int) in
+test 7 eq_big_int (numerator_ratio r, zero_big_int) &&
+test 8 eq_big_int (denominator_ratio r, zero_big_int)
+;;
+
+testing_function "integer_ratio"
+;;
+
+test 1
+eq_big_int (integer_ratio
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ big_int_of_int 1)
+;;
+test 2
+eq_big_int (integer_ratio
+ (create_ratio (big_int_of_int 5) (big_int_of_int (-3))),
+ big_int_of_int (-1))
+;;
+test 3
+eq_big_int (integer_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int 2)),
+ big_int_of_int 1)
+;;
+test 4
+eq_big_int (integer_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int (-2))),
+ big_int_of_int (-1))
+;;
+
+failwith_test 5
+integer_ratio (create_ratio (big_int_of_int 3) zero_big_int)
+(Failure("integer_ratio "^infinite_failure))
+;;
+
+testing_function "floor_ratio"
+;;
+
+test 1
+eq_big_int (floor_ratio
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ big_int_of_int 1)
+;;
+test 2
+eq_big_int (floor_ratio
+ (create_ratio (big_int_of_int 5) (big_int_of_int (-3))),
+ big_int_of_int (-2))
+;;
+test 3
+eq_big_int (floor_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int 2)),
+ big_int_of_int 1)
+;;
+test 4
+eq_big_int (floor_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int (-2))),
+ big_int_of_int (-2))
+;;
+
+failwith_test 5 floor_ratio (create_ratio (big_int_of_int 3) zero_big_int)
+Division_by_zero
+;;
+
+
+testing_function "round_ratio"
+;;
+
+test 1
+eq_big_int (round_ratio
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ big_int_of_int 2)
+;;
+test 2
+eq_big_int (round_ratio
+ (create_ratio (big_int_of_int 5) (big_int_of_int (-3))),
+ big_int_of_int (-2))
+;;
+test 3
+eq_big_int (round_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int 2)),
+ big_int_of_int 2)
+;;
+test 4
+eq_big_int (round_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int (-2))),
+ big_int_of_int (-2))
+;;
+
+failwith_test 5
+round_ratio (create_ratio (big_int_of_int 3) zero_big_int)
+Division_by_zero
+;;
+
+
+testing_function "ceiling_ratio"
+;;
+
+test 1
+eq_big_int (ceiling_ratio
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ big_int_of_int 2)
+;;
+test 2
+eq_big_int (ceiling_ratio
+ (create_ratio (big_int_of_int 5) (big_int_of_int (-3))),
+ big_int_of_int (-1))
+;;
+test 3
+eq_big_int (ceiling_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int 2)),
+ big_int_of_int 2)
+;;
+test 4
+eq_big_int (ceiling_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int (-2))),
+ big_int_of_int (-1))
+;;
+test 5
+eq_big_int (ceiling_ratio
+ (create_ratio (big_int_of_int 4) (big_int_of_int 2)),
+ big_int_of_int 2)
+;;
+failwith_test 6
+ceiling_ratio (create_ratio (big_int_of_int 3) zero_big_int)
+Division_by_zero
+;;
+
+testing_function "eq_ratio"
+;;
+
+test 1
+eq_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3),
+ create_ratio (big_int_of_int (-20)) (big_int_of_int (-12)))
+;;
+test 2
+eq_ratio (create_ratio (big_int_of_int 1) zero_big_int,
+ create_ratio (big_int_of_int 2) zero_big_int)
+;;
+
+let neq_ratio x y = not (eq_ratio x y);;
+
+test 3
+neq_ratio (create_ratio (big_int_of_int 1) zero_big_int,
+ create_ratio (big_int_of_int (-1)) zero_big_int)
+;;
+test 4
+neq_ratio (create_ratio (big_int_of_int 1) zero_big_int,
+ create_ratio zero_big_int zero_big_int)
+;;
+test 5
+eq_ratio (create_ratio zero_big_int zero_big_int,
+ create_ratio zero_big_int zero_big_int)
+;;
+
+testing_function "compare_ratio"
+;;
+
+test 1
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 0)),
+ 0)
+;;
+test 2
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 1) (big_int_of_int 0)),
+ 0)
+;;
+test 3
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+ (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)),
+ 0)
+;;
+test 4
+eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 0)),
+ 0)
+;;
+test 5
+eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 0)),
+ 0)
+;;
+test 6
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ 0)
+;;
+test 7
+eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 0)),
+ 0)
+;;
+test 8
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+ (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)),
+ 0)
+;;
+test 9
+eq_int (compare_ratio (create_ratio (big_int_of_int (-5)) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 0)),
+ 0)
+;;
+test 10
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 1)),
+ 0)
+;;
+test 11
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 1))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 0)),
+ 0)
+;;
+test 12
+eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 1) (big_int_of_int 0)),
+ 0)
+;;
+test 13
+eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 2) (big_int_of_int 0)),
+ 0)
+;;
+test 14
+eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+ (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)),
+ 1)
+;;
+test 15
+eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 1) (big_int_of_int 0)),
+ (-1))
+;;
+test 16
+eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 1) (big_int_of_int 0)),
+ (-1))
+;;
+test 17
+eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ 1)
+;;
+test 18
+eq_int (compare_ratio (create_ratio (big_int_of_int (-5)) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 1) (big_int_of_int 0)),
+ (-1))
+;;
+test 19
+eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+ (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)),
+ 1)
+;;
+test 20
+eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 3)),
+ 1)
+;;
+test 21
+eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0))
+ (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)),
+ 0)
+;;
+test 22
+eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0))
+ (create_ratio (big_int_of_int (-2)) (big_int_of_int 0)),
+ 0)
+;;
+test 23
+eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3))
+ (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)),
+ 1)
+;;
+test 24
+eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ (-1))
+;;
+test 25
+eq_int (compare_ratio (create_ratio (big_int_of_int (-5)) (big_int_of_int 3))
+ (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)),
+ 1)
+;;
+test 26
+eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0))
+ (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)),
+ (-1))
+;;
+test 27
+eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 3)),
+ (-1))
+;;
+test 28
+eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3))
+ (create_ratio (big_int_of_int 3) (big_int_of_int 2)),
+ 1)
+;;
+test 29
+eq_int (compare_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2))
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ (-1))
+;;
+test 30
+eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3))
+ (create_ratio (big_int_of_int (-3)) (big_int_of_int 2)),
+ 1)
+;;
+test 31
+eq_int (compare_ratio (create_ratio (big_int_of_int (-3)) (big_int_of_int 2))
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ (-1))
+;;
+test 32
+eq_int (compare_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 3)),
+ 1)
+;;
+test 33
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 2))
+ (create_ratio (big_int_of_int 5) (big_int_of_int 3)),
+ (-1))
+;;
+test 34
+eq_int (compare_ratio (create_ratio (big_int_of_int (-3)) (big_int_of_int 2))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 3)),
+ (-1))
+;;
+test 35
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 2))
+ (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)),
+ 1)
+;;
+test 36
+eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 2))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 3)),
+ 0)
+;;
+
+testing_function "eq_big_int_ratio"
+;;
+
+test 1
+eq_big_int_ratio (big_int_of_int 3,
+ (create_ratio (big_int_of_int 3) (big_int_of_int 1)))
+;;
+test 2
+eq
+(not (eq_big_int_ratio (big_int_of_int 1)
+ (create_ratio (big_int_of_int 3) (big_int_of_int 1))),
+true)
+;;
+
+test 3
+eq
+(not (eq_big_int_ratio (big_int_of_int 1)
+ (create_ratio (big_int_of_int 3) (big_int_of_int 2))),
+ true)
+;;
+
+test 4
+eq
+(not (eq_big_int_ratio (big_int_of_int 1)
+ (create_ratio (big_int_of_int 3) (big_int_of_int 0))),
+ true)
+;;
+
+test 5
+eq
+(not (eq_big_int_ratio (big_int_of_int 1)
+ (create_ratio (big_int_of_int (-3)) (big_int_of_int 2))),
+ true)
+;;
+
+testing_function "compare_big_int_ratio"
+;;
+
+test 1
+eq_int (compare_big_int_ratio
+ (big_int_of_int 1)
+ (create_ratio (big_int_of_int 3) (big_int_of_int 0)), (-1))
+;;
+test 2
+eq_int (compare_big_int_ratio
+ (big_int_of_int 1)
+ (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0)
+;;
+test 3
+eq_int (compare_big_int_ratio
+ (big_int_of_int 1)
+ (create_ratio (big_int_of_int (-3)) (big_int_of_int 0)), 1)
+;;
+test 4
+eq_int (compare_big_int_ratio
+ (big_int_of_int (-1))
+ (create_ratio (big_int_of_int 3) (big_int_of_int 0)), (-1))
+;;
+test 5
+eq_int (compare_big_int_ratio
+ (big_int_of_int (-1))
+ (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0)
+;;
+test 6
+eq_int (compare_big_int_ratio
+ (big_int_of_int (-1))
+ (create_ratio (big_int_of_int (-3)) (big_int_of_int 0)), 1)
+;;
+test 7
+eq_int (compare_big_int_ratio
+ (big_int_of_int 1)
+ (create_ratio (big_int_of_int 1) (big_int_of_int 1)), 0)
+;;
+test 8
+eq_int (compare_big_int_ratio
+ (big_int_of_int 1)
+ (create_ratio (big_int_of_int 3) (big_int_of_int 2)), (-1))
+;;
+test 9
+eq_int (compare_big_int_ratio
+ (big_int_of_int 1)
+ (create_ratio (big_int_of_int 2) (big_int_of_int 3)), 1)
+;;
+
+
+
+testing_function "int_of_ratio"
+;;
+
+test 1
+eq_int (int_of_ratio (create_ratio (big_int_of_int 4) (big_int_of_int 2)),
+ 2)
+;;
+
+test 2
+eq_int (int_of_ratio
+ (create_ratio (big_int_of_int biggest_int) (big_int_of_int 1)),
+ biggest_int)
+;;
+
+failwith_test 3
+int_of_ratio (create_ratio (big_int_of_int 4) (big_int_of_int 0))
+(Failure "integer argument required")
+;;
+
+failwith_test 4
+int_of_ratio (create_ratio (succ_big_int (big_int_of_int biggest_int))
+ (big_int_of_int 1))
+(Failure "integer argument required")
+;;
+
+failwith_test 5
+int_of_ratio (create_ratio (big_int_of_int 4) (big_int_of_int 3))
+(Failure "integer argument required")
+;;
+
+testing_function "ratio_of_int"
+;;
+
+test 1
+eq_ratio (ratio_of_int 3,
+ create_ratio (big_int_of_int 3) (big_int_of_int 1))
+;;
+
+test 2
+eq_ratio (ratio_of_nat (nat_of_int 2),
+ create_ratio (big_int_of_int 2) (big_int_of_int 1))
+;;
+
+testing_function "nat_of_ratio"
+;;
+
+let nat1 = nat_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 1))
+and nat2 = nat_of_int 3 in
+test 1
+eq (eq_nat nat1 0 (length_nat nat1) nat2 0 (length_nat nat2), true)
+;;
+
+failwith_test 2
+nat_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 0))
+(Failure "nat_of_ratio")
+;;
+
+failwith_test 3
+nat_of_ratio (create_ratio (big_int_of_int (-3)) (big_int_of_int 1))
+(Failure "nat_of_ratio")
+;;
+
+failwith_test 4
+nat_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2))
+(Failure "nat_of_ratio")
+;;
+
+testing_function "ratio_of_big_int"
+;;
+
+test 1
+eq_ratio (ratio_of_big_int (big_int_of_int 3),
+ create_ratio (big_int_of_int 3) (big_int_of_int 1))
+;;
+
+testing_function "big_int_of_ratio"
+;;
+
+test 1
+eq_big_int (big_int_of_ratio
+ (create_ratio (big_int_of_int 3) (big_int_of_int 1)),
+ big_int_of_int 3)
+;;
+test 2
+eq_big_int (big_int_of_ratio
+ (create_ratio (big_int_of_int (-3)) (big_int_of_int 1)),
+ big_int_of_int (-3))
+;;
+
+failwith_test 3
+big_int_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 0))
+(Failure "big_int_of_ratio")
+;;
+
+testing_function "string_of_ratio"
+;;
+
+test 1
+eq_string (string_of_ratio
+ (create_ratio (big_int_of_int 43) (big_int_of_int 35)),
+ "43/35")
+;;
+test 2
+eq_string (string_of_ratio
+ (create_ratio (big_int_of_int 42) (big_int_of_int 0)),
+ "1/0")
+;;
+
+set_normalize_ratio_when_printing false
+;;
+
+test 3
+eq_string (string_of_ratio
+ (create_ratio (big_int_of_int 42) (big_int_of_int 35)),
+ "42/35")
+;;
+
+set_normalize_ratio_when_printing true
+;;
+
+test 4
+eq_string (string_of_ratio
+ (create_ratio (big_int_of_int 42) (big_int_of_int 35)),
+ "6/5")
+;;
+
+testing_function "ratio_of_string"
+;;
+
+test 1
+eq_ratio (ratio_of_string ("123/3456"),
+ create_ratio (big_int_of_int 123) (big_int_of_int 3456))
+;;
+
+(***********
+test 2
+eq_ratio (ratio_of_string ("12.3/34.56"),
+ create_ratio (big_int_of_int 1230) (big_int_of_int 3456))
+;;
+test 3
+eq_ratio (ratio_of_string ("1.23/325.6"),
+ create_ratio (big_int_of_int 123) (big_int_of_int 32560))
+;;
+test 4
+eq_ratio (ratio_of_string ("12.3/345.6"),
+ create_ratio (big_int_of_int 123) (big_int_of_int 3456))
+;;
+test 5
+eq_ratio (ratio_of_string ("12.3/0.0"),
+ create_ratio (big_int_of_int 123) (big_int_of_int 0))
+;;
+***********)
+test 6
+eq_ratio (ratio_of_string ("0/0"),
+ create_ratio (big_int_of_int 0) (big_int_of_int 0))
+;;
+
+test 7
+eq_ratio (ratio_of_string "1234567890",
+ create_ratio (big_int_of_string "1234567890") unit_big_int)
+;;
+failwith_test 8
+ratio_of_string "frlshjkurty" (Failure "invalid digit");;
+
+(***********
+testing_function "msd_ratio"
+;;
+
+test 1
+eq_int (msd_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 1)),
+ 0)
+;;
+test 2
+eq_int (msd_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 12)),
+ (-2))
+;;
+test 3
+eq_int (msd_ratio (create_ratio (big_int_of_int 12) (big_int_of_int 1)),
+ 1)
+;;
+test 4
+eq_int (msd_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 2)),
+ (-1))
+;;
+test 5
+eq_int (msd_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 1)),
+ 0)
+;;
+test 6
+eq_int (msd_ratio (create_ratio (big_int_of_int 25) (big_int_of_int 21)),
+ 0)
+;;
+test 7
+eq_int (msd_ratio (create_ratio (big_int_of_int 35) (big_int_of_int 21)),
+ 0)
+;;
+test 8
+eq_int (msd_ratio (create_ratio (big_int_of_int 215) (big_int_of_int 31)),
+ 0)
+;;
+test 9
+eq_int (msd_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 30)),
+ (-2))
+;;
+test 10
+eq_int (msd_ratio (create_ratio (big_int_of_int 2345)
+ (big_int_of_int 23456)),
+ (-2))
+;;
+test 11
+eq_int (msd_ratio (create_ratio (big_int_of_int 2345)
+ (big_int_of_int 2346)),
+ (-1))
+;;
+test 12
+eq_int (msd_ratio (create_ratio (big_int_of_int 2345)
+ (big_int_of_int 2344)),
+ 0)
+;;
+test 13
+eq_int (msd_ratio (create_ratio (big_int_of_int 23456)
+ (big_int_of_int 2345)),
+ 1)
+;;
+test 14
+eq_int (msd_ratio (create_ratio (big_int_of_int 23467)
+ (big_int_of_int 2345)),
+ 1)
+;;
+failwith_test 15
+msd_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+("msd_ratio "^infinite_failure)
+;;
+failwith_test 16
+msd_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0))
+("msd_ratio "^infinite_failure)
+;;
+failwith_test 17
+msd_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+("msd_ratio "^infinite_failure)
+;;
+*************************)
+
+testing_function "round_futur_last_digit"
+;;
+
+let s = "+123456" in
+test 1 eq (round_futur_last_digit s 1 (pred (String.length s)),
+ false) &&
+test 2 eq_string (s, "+123466")
+;;
+
+let s = "123456" in
+test 3 eq (round_futur_last_digit s 0 (String.length s), false) &&
+test 4 eq_string (s, "123466")
+;;
+
+let s = "-123456" in
+test 5 eq (round_futur_last_digit s 1 (pred (String.length s)),
+ false) &&
+test 6 eq_string (s, "-123466")
+;;
+
+let s = "+123496" in
+test 7 eq (round_futur_last_digit s 1 (pred (String.length s)),
+ false) &&
+test 8 eq_string (s, "+123506")
+;;
+
+let s = "123496" in
+test 9 eq (round_futur_last_digit s 0 (String.length s), false) &&
+test 10 eq_string (s, "123506")
+;;
+
+let s = "-123496" in
+test 11 eq (round_futur_last_digit s 1 (pred (String.length s)),
+ false) &&
+test 12 eq_string (s, "-123506")
+;;
+
+let s = "+996" in
+test 13 eq (round_futur_last_digit s 1 (pred (String.length s)),
+ true) &&
+test 14 eq_string (s, "+006")
+;;
+
+let s = "996" in
+test 15 eq (round_futur_last_digit s 0 (String.length s), true) &&
+test 16 eq_string (s, "006")
+;;
+
+let s = "-996" in
+test 17 eq (round_futur_last_digit s 1 (pred (String.length s)),
+ true) &&
+test 18 eq_string (s, "-006")
+;;
+
+let s = "+6666666" in
+test 19 eq (round_futur_last_digit s 1 (pred (String.length s)),
+ false) &&
+test 20 eq_string (s, "+6666676")
+;;
+
+let s = "6666666" in
+test 21 eq (round_futur_last_digit s 0 (String.length s), false) &&
+test 22 eq_string (s, "6666676")
+;;
+
+let s = "-6666666" in
+test 23 eq (round_futur_last_digit s 1 (pred (String.length s)),
+ false) &&
+test 24 eq_string (s, "-6666676")
+;;
+
+testing_function "approx_ratio_fix"
+;;
+
+let s = approx_ratio_fix 5
+ (create_ratio (big_int_of_int 2)
+ (big_int_of_int 3)) in
+test 1
+eq_string (s, "+0.66667")
+;;
+
+test 2
+eq_string (approx_ratio_fix 5
+ (create_ratio (big_int_of_int 20)
+ (big_int_of_int 3)),
+ "+6.66667")
+;;
+test 3
+eq_string (approx_ratio_fix 5
+ (create_ratio (big_int_of_int 2)
+ (big_int_of_int 30)),
+ "+0.06667")
+;;
+test 4
+eq_string (approx_ratio_fix 5
+ (create_ratio (big_int_of_string "999996")
+ (big_int_of_string "1000000")),
+ "+1.00000")
+;;
+test 5
+eq_string (approx_ratio_fix 5
+ (create_ratio (big_int_of_string "299996")
+ (big_int_of_string "100000")),
+ "+2.99996")
+;;
+test 6
+eq_string (approx_ratio_fix 5
+ (create_ratio (big_int_of_string "2999996")
+ (big_int_of_string "1000000")),
+ "+3.00000")
+;;
+test 7
+eq_string (approx_ratio_fix 4
+ (create_ratio (big_int_of_string "299996")
+ (big_int_of_string "100000")),
+ "+3.0000")
+;;
+test 8
+eq_string (approx_ratio_fix 5
+ (create_ratio (big_int_of_int 29996)
+ (big_int_of_string "100000")),
+ "+0.29996")
+;;
+test 9
+eq_string (approx_ratio_fix 5
+ (create_ratio (big_int_of_int 0)
+ (big_int_of_int 1)),
+ "+0")
+;;
+failwith_test 10
+(approx_ratio_fix 5) (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+(Failure "approx_ratio_fix infinite or undefined rational number")
+;;
+failwith_test 11
+(approx_ratio_fix 5) (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+(Failure "approx_ratio_fix infinite or undefined rational number")
+;;
+
+(* PR#4566 *)
+test 12
+eq_string (approx_ratio_fix 8
+ (create_ratio (big_int_of_int 9603)
+ (big_int_of_string "100000000000")),
+
+ "+0.00000010")
+;;
+test 13
+eq_string (approx_ratio_fix 1
+ (create_ratio (big_int_of_int 94)
+ (big_int_of_int 1000)),
+ "+0.1")
+;;
+test 14
+eq_string (approx_ratio_fix 1
+ (create_ratio (big_int_of_int 49)
+ (big_int_of_int 1000)),
+ "+0.0")
+;;
+
+testing_function "approx_ratio_exp"
+;;
+
+test 1
+eq_string (approx_ratio_exp 5
+ (create_ratio (big_int_of_int 2)
+ (big_int_of_int 3)),
+ "+0.66667e0")
+;;
+test 2
+eq_string (approx_ratio_exp 5
+ (create_ratio (big_int_of_int 20)
+ (big_int_of_int 3)),
+ "+0.66667e1")
+;;
+test 3
+eq_string (approx_ratio_exp 5
+ (create_ratio (big_int_of_int 2)
+ (big_int_of_int 30)),
+ "+0.66667e-1")
+;;
+test 4
+eq_string (approx_ratio_exp 5
+ (create_ratio (big_int_of_string "999996")
+ (big_int_of_string "1000000")),
+ "+1.00000e0")
+;;
+test 5
+eq_string (approx_ratio_exp 5
+ (create_ratio (big_int_of_string "299996")
+ (big_int_of_string "100000")),
+ "+0.30000e1")
+;;
+test 6
+eq_string (approx_ratio_exp 5
+ (create_ratio (big_int_of_int 29996)
+ (big_int_of_string "100000")),
+ "+0.29996e0")
+;;
+test 7
+eq_string (approx_ratio_exp 5
+ (create_ratio (big_int_of_int 0)
+ (big_int_of_int 1)),
+ "+0.00000e0")
+;;
+failwith_test 8
+(approx_ratio_exp 5) (create_ratio (big_int_of_int 1) (big_int_of_int 0))
+(Failure "approx_ratio_exp infinite or undefined rational number")
+;;
+failwith_test 9
+(approx_ratio_exp 5) (create_ratio (big_int_of_int 0) (big_int_of_int 0))
+(Failure "approx_ratio_exp infinite or undefined rational number")
+;;
+
+testing_function "float_of_ratio";;
+let ok = ref true in
+for i = 1 to 100 do
+ let p = Random.int64 0x20000000000000L
+ and pexp = Random.int 100
+ and q = Random.int64 0x20000000000000L
+ and qexp = Random.int 100 in
+ if not (eq_float
+ (float_of_ratio
+ (create_ratio
+ (shift_left_big_int (big_int_of_int64 p) pexp)
+ (shift_left_big_int (big_int_of_int64 q) qexp)))
+ (ldexp (Int64.to_float p) pexp /.
+ ldexp (Int64.to_float q) qexp))
+ then ok := false
+done;
+test 1 eq (!ok, true)
+;;
diff --git a/testsuite/tests/lib-printf/Makefile b/testsuite/tests/lib-printf/Makefile
new file mode 100644
index 0000000000..4a74a3fdcb
--- /dev/null
+++ b/testsuite/tests/lib-printf/Makefile
@@ -0,0 +1,17 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+MODULES=testing
+BASEDIR=../..
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-printf/pr6534.ml b/testsuite/tests/lib-printf/pr6534.ml
new file mode 100644
index 0000000000..a356d52114
--- /dev/null
+++ b/testsuite/tests/lib-printf/pr6534.ml
@@ -0,0 +1,19 @@
+(* these are not valid under -strict-formats, but we test them here
+ for backward-compatibility *)
+open Printf
+
+let () =
+ printf "1 [%.5s]\n" "foo";
+ printf "2 [%.*s]\n" 5 "foo";
+ printf "3 [%.-5s]\n" "foo";
+ printf "4 [%-.5s]\n" "foo";
+ printf "5 [%-.*s]\n" 5 "foo";
+ printf "6 [%.*s]\n" (-5) "foo";
+
+ printf "1 [%.7S]\n" "foo";
+ printf "2 [%.*S]\n" 7 "foo";
+ printf "3 [%.-7S]\n" "foo";
+ printf "4 [%-.7S]\n" "foo";
+ printf "5 [%-.*S]\n" 7 "foo";
+ printf "6 [%.*S]\n" (-7) "foo";
+ ()
diff --git a/testsuite/tests/lib-printf/pr6534.reference b/testsuite/tests/lib-printf/pr6534.reference
new file mode 100644
index 0000000000..c3e2a7ffd4
--- /dev/null
+++ b/testsuite/tests/lib-printf/pr6534.reference
@@ -0,0 +1,14 @@
+1 [ foo]
+2 [ foo]
+3 [foo ]
+4 [foo ]
+5 [foo ]
+6 [foo ]
+1 [ "foo"]
+2 [ "foo"]
+3 ["foo" ]
+4 ["foo" ]
+5 ["foo" ]
+6 ["foo" ]
+
+All tests succeeded.
diff --git a/testsuite/tests/lib-printf/pr6938.ml b/testsuite/tests/lib-printf/pr6938.ml
new file mode 100644
index 0000000000..b081b4ce44
--- /dev/null
+++ b/testsuite/tests/lib-printf/pr6938.ml
@@ -0,0 +1,42 @@
+(* these are not valid under -strict-formats, but we test them here
+ for backward-compatibility *)
+
+Printf.printf "%047.27d\n" 1036201459;;
+Printf.printf "%047.27ld\n" 1036201459l;;
+Printf.printf "%047.27Ld\n" 1036201459L;;
+Printf.printf "%047.27nd\n" 1036201459n;;
+
+print_newline ();;
+
+Printf.printf "%047.27i\n" 1036201459;;
+Printf.printf "%047.27li\n" 1036201459l;;
+Printf.printf "%047.27Li\n" 1036201459L;;
+Printf.printf "%047.27ni\n" 1036201459n;;
+
+print_newline ();;
+
+Printf.printf "%047.27u\n" 1036201459;;
+Printf.printf "%047.27lu\n" 1036201459l;;
+Printf.printf "%047.27Lu\n" 1036201459L;;
+Printf.printf "%047.27nu\n" 1036201459n;;
+
+print_newline ();;
+
+Printf.printf "%047.27x\n" 1036201459;;
+Printf.printf "%047.27lx\n" 1036201459l;;
+Printf.printf "%047.27Lx\n" 1036201459L;;
+Printf.printf "%047.27nx\n" 1036201459n;;
+
+print_newline ();;
+
+Printf.printf "%047.27X\n" 1036201459;;
+Printf.printf "%047.27lX\n" 1036201459l;;
+Printf.printf "%047.27LX\n" 1036201459L;;
+Printf.printf "%047.27nX\n" 1036201459n;;
+
+print_newline ();;
+
+Printf.printf "%047.27o\n" 1036201459;;
+Printf.printf "%047.27lo\n" 1036201459l;;
+Printf.printf "%047.27Lo\n" 1036201459L;;
+Printf.printf "%047.27no\n" 1036201459n;;
diff --git a/testsuite/tests/lib-printf/pr6938.reference b/testsuite/tests/lib-printf/pr6938.reference
new file mode 100644
index 0000000000..3e5e220d95
--- /dev/null
+++ b/testsuite/tests/lib-printf/pr6938.reference
@@ -0,0 +1,31 @@
+ 000000000000000001036201459
+ 000000000000000001036201459
+ 000000000000000001036201459
+ 000000000000000001036201459
+
+ 000000000000000001036201459
+ 000000000000000001036201459
+ 000000000000000001036201459
+ 000000000000000001036201459
+
+ 000000000000000001036201459
+ 000000000000000001036201459
+ 000000000000000001036201459
+ 000000000000000001036201459
+
+ 00000000000000000003dc32df3
+ 00000000000000000003dc32df3
+ 00000000000000000003dc32df3
+ 00000000000000000003dc32df3
+
+ 00000000000000000003DC32DF3
+ 00000000000000000003DC32DF3
+ 00000000000000000003DC32DF3
+ 00000000000000000003DC32DF3
+
+ 000000000000000007560626763
+ 000000000000000007560626763
+ 000000000000000007560626763
+ 000000000000000007560626763
+
+All tests succeeded.
diff --git a/testsuite/tests/lib-printf/tprintf.ml b/testsuite/tests/lib-printf/tprintf.ml
new file mode 100644
index 0000000000..cb4ee657b8
--- /dev/null
+++ b/testsuite/tests/lib-printf/tprintf.ml
@@ -0,0 +1,591 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2011 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+(*
+
+A test file for the Printf module.
+
+*)
+
+open Testing;;
+open Printf;;
+
+try
+
+ printf "d/i positive\n%!";
+ test (sprintf "%d/%i" 42 43 = "42/43");
+ test (sprintf "%-4d/%-5i" 42 43 = "42 /43 ");
+ test (sprintf "%04d/%05i" 42 43 = "0042/00043");
+ test (sprintf "%+d/%+i" 42 43 = "+42/+43");
+ test (sprintf "% d/% i" 42 43 = " 42/ 43");
+ (*test (sprintf "%#d/%#i" 42 43 = "42/43");*)
+ (* >> '#' is incompatible with 'd' *)
+ test (sprintf "%4d/%5i" 42 43 = " 42/ 43");
+ test (sprintf "%*d" (-4) 42 = "42 ");
+ test (sprintf "%*d/%*i" 4 42 5 43 = " 42/ 43");
+ (*test (sprintf "%-0+#4d/%-0 #5i" 42 43 = "+42 / 43 ");*)
+ (* >> '#' is incompatible with 'd' *)
+
+ printf "\nd/i negative\n%!";
+ test (sprintf "%d/%i" (-42) (-43) = "-42/-43");
+ test (sprintf "%-4d/%-5i" (-42) (-43) = "-42 /-43 ");
+ test (sprintf "%04d/%05i" (-42) (-43) = "-042/-0043");
+ test (sprintf "%+d/%+i" (-42) (-43) = "-42/-43");
+ test (sprintf "% d/% i" (-42) (-43) = "-42/-43");
+ (*test (sprintf "%#d/%#i" (-42) (-43) = "-42/-43");*)
+ (* >> '#' is incompatible with 'd' *)
+ test (sprintf "%4d/%5i" (-42) (-43) = " -42/ -43");
+ test (sprintf "%*d" (-4) (-42) = "-42 ");
+ test (sprintf "%*d/%*i" 4 (-42) 5 (-43) = " -42/ -43");
+ (*test (sprintf "%-0+ #4d/%-0+ #5i" (-42) (-43) = "-42 /-43 ");*)
+ (* >> '0' is incompatible with '-', '#' is incompatible with 'd' *)
+
+ printf "\nu positive\n%!";
+ test (sprintf "%u" 42 = "42");
+ test (sprintf "%-4u" 42 = "42 ");
+ test (sprintf "%04u" 42 = "0042");
+ (*test (sprintf "%+u" 42 = "42");*)
+ (* >> '+' is incompatible with 'u' *)
+ (*test (sprintf "% u" 42 = "42");*)
+ (* >> ' ' is incompatible with 'u' *)
+ (*test (sprintf "%#u" 42 = "42");*)
+ (* >> '#' is incompatible with 'u' *)
+ test (sprintf "%4u" 42 = " 42");
+ test (sprintf "%*u" 4 42 = " 42");
+ test (sprintf "%*u" (-4) 42 = "42 ");
+
+ printf "\nu negative\n%!";
+ begin match Sys.word_size with
+ | 32 ->
+ test (sprintf "%u" (-1) = "2147483647");
+ | 64 ->
+ test (sprintf "%u" (-1) = "9223372036854775807");
+ | _ -> test false
+ end;
+
+ printf "\nx positive\n%!";
+ test (sprintf "%x" 42 = "2a");
+ test (sprintf "%-4x" 42 = "2a ");
+ test (sprintf "%04x" 42 = "002a");
+ (*test (sprintf "%+x" 42 = "2a");*)
+ (* >> '+' is incompatible with 'x' *)
+ (*test (sprintf "% x" 42 = "2a");*)
+ (* >> ' ' is incompatible with 'x' *)
+ test (sprintf "%#x" 42 = "0x2a");
+ test (sprintf "%4x" 42 = " 2a");
+ test (sprintf "%*x" 5 42 = " 2a");
+ test (sprintf "%*x" (-5) 42 = "2a ");
+ test (sprintf "%#*x" 5 42 = " 0x2a");
+ test (sprintf "%#*x" (-5) 42 = "0x2a ");
+ test (sprintf "%#-*x" 5 42 = "0x2a ");
+ test (sprintf "%-0+ #*x" 5 42 = "0x2a ");
+
+ printf "\nx negative\n%!";
+ begin match Sys.word_size with
+ | 32 ->
+ test (sprintf "%x" (-42) = "7fffffd6");
+ | 64 ->
+ test (sprintf "%x" (-42) = "7fffffffffffffd6");
+ | _ -> test false
+ end;
+
+ printf "\nX positive\n%!";
+ test (sprintf "%X" 42 = "2A");
+ test (sprintf "%-4X" 42 = "2A ");
+ test (sprintf "%04X" 42 = "002A");
+ (*test (sprintf "%+X" 42 = "2A");*)
+ (* >> '+' is incompatible with 'X' *)
+ (*test (sprintf "% X" 42 = "2A");*)
+ (* >> ' ' is incompatible with 'X' *)
+ test (sprintf "%#X" 42 = "0X2A");
+ test (sprintf "%4X" 42 = " 2A");
+ test (sprintf "%*X" 5 42 = " 2A");
+ (*test (sprintf "%-0+ #*X" 5 42 = "0X2A ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nx negative\n%!";
+ begin match Sys.word_size with
+ | 32 ->
+ test (sprintf "%X" (-42) = "7FFFFFD6");
+ | 64 ->
+ test (sprintf "%X" (-42) = "7FFFFFFFFFFFFFD6");
+ | _ -> test false
+ end;
+
+ printf "\no positive\n%!";
+ test (sprintf "%o" 42 = "52");
+ test (sprintf "%-4o" 42 = "52 ");
+ test (sprintf "%04o" 42 = "0052");
+ (*test (sprintf "%+o" 42 = "52");*)
+ (* >> '+' is incompatible with 'o' *)
+ (*test (sprintf "% o" 42 = "52");*)
+ (* >> '+' is incompatible with 'o' *)
+ test (sprintf "%#o" 42 = "052");
+ test (sprintf "%4o" 42 = " 52");
+ test (sprintf "%*o" 5 42 = " 52");
+ (*test (sprintf "%-0+ #*o" 5 42 = "052 ");*)
+ (* >> '-' is incompatible with 'o' *)
+
+ printf "\no negative\n%!";
+ begin match Sys.word_size with
+ | 32 ->
+ test (sprintf "%o" (-42) = "17777777726");
+ | 64 ->
+ test (sprintf "%o" (-42) = "777777777777777777726");
+ | _ -> test false
+ end;
+
+ printf "\ns\n%!";
+ test (sprintf "%s" "foo" = "foo");
+ test (sprintf "%-5s" "foo" = "foo ");
+ (*test (sprintf "%05s" "foo" = " foo");*)
+ (* >> '0' is incompatible with 's' *)
+ (*test (sprintf "%+s" "foo" = "foo");*)
+ (* >> '+' is incompatible with 's' *)
+ (*test (sprintf "% s" "foo" = "foo");*)
+ (* >> ' ' is incompatible with 's' *)
+ (*test (sprintf "%#s" "foo" = "foo");*)
+ (* >> '#' is incompatible with 's' *)
+ test (sprintf "%5s" "foo" = " foo");
+ test (sprintf "%1s" "foo" = "foo");
+ test (sprintf "%*s" 6 "foo" = " foo");
+ test (sprintf "%*s" (-6) "foo" = "foo ");
+ test (sprintf "%*s" 2 "foo" = "foo");
+ (*test (sprintf "%-0+ #5s" "foo" = "foo ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 's' *)
+ test (sprintf "%s@" "foo" = "foo@");
+ test (sprintf "%s@inria.fr" "foo" = "foo@inria.fr");
+ test (sprintf "%s@%s" "foo" "inria.fr" = "foo@inria.fr");
+
+ printf "\nS\n%!";
+ test (sprintf "%S" "fo\"o" = "\"fo\\\"o\"");
+(* test (sprintf "%-5S" "foo" = "\"foo\" "); padding not done *)
+(* test (sprintf "%05S" "foo" = " \"foo\""); padding not done *)
+ (*test (sprintf "%+S" "foo" = "\"foo\"");*)
+ (* >> '#' is incompatible with 'S' *)
+ (*test (sprintf "% S" "foo" = "\"foo\"");*)
+ (* >> '#' is incompatible with 'S' *)
+ (*test (sprintf "%#S" "foo" = "\"foo\"");*)
+ (* >> '#' is incompatible with 'S' *)
+(* test (sprintf "%5S" "foo" = " \"foo\""); padding not done *)
+ test (sprintf "%1S" "foo" = "\"foo\"");
+ test (sprintf "%*S" 8 "foo" = " \"foo\"");
+ test (sprintf "%*S" (-8) "foo" = "\"foo\" ");
+ test (sprintf "%*S" 2 "foo" = "\"foo\"");
+(* test (sprintf "%-0+ #5S" "foo" = "\"foo\" "); padding not done *)
+ test (sprintf "%S@" "foo" = "\"foo\"@");
+ test (sprintf "%S@inria.fr" "foo" = "\"foo\"@inria.fr");
+ test (sprintf "%S@%S" "foo" "inria.fr" = "\"foo\"@\"inria.fr\"");
+
+ printf "\nc\n%!";
+ test (sprintf "%c" 'c' = "c");
+(* test (sprintf "%-4c" 'c' = "c "); padding not done *)
+(* test (sprintf "%04c" 'c' = " c"); padding not done *)
+ (*test (sprintf "%+c" 'c' = "c");*)
+ (* >> '#' is incompatible with 'c' *)
+ (*test (sprintf "% c" 'c' = "c");*)
+ (* >> '#' is incompatible with 'c' *)
+ (*test (sprintf "%#c" 'c' = "c");*)
+ (* >> '#' is incompatible with 'c' *)
+(* test (sprintf "%4c" 'c' = " c"); padding not done *)
+(* test (sprintf "%*c" 2 'c' = " c"); padding not done *)
+(* test (sprintf "%-0+ #4c" 'c' = "c "); padding not done *)
+
+ printf "\nC\n%!";
+ test (sprintf "%C" 'c' = "'c'");
+ test (sprintf "%C" '\'' = "'\\''");
+(* test (sprintf "%-4C" 'c' = "c "); padding not done *)
+(* test (sprintf "%04C" 'c' = " c"); padding not done *)
+ (*test (sprintf "%+C" 'c' = "'c'");*)
+ (* >> '+' is incompatible with 'C' *)
+ (*test (sprintf "% C" 'c' = "'c'");*)
+ (* >> ' ' is incompatible with 'C' *)
+ (*test (sprintf "%#C" 'c' = "'c'");*)
+ (* >> '#' is incompatible with 'C' *)
+(* test (sprintf "%4C" 'c' = " c"); padding not done *)
+(* test (sprintf "%*C" 2 'c' = " c"); padding not done *)
+(* test (sprintf "%-0+ #4C" 'c' = "c "); padding not done *)
+
+ printf "\nf\n%!";
+ test (sprintf "%f" (-42.42) = "-42.420000");
+ test (sprintf "%-13f" (-42.42) = "-42.420000 ");
+ test (sprintf "%013f" (-42.42) = "-00042.420000");
+ test (sprintf "%+f" 42.42 = "+42.420000");
+ test (sprintf "% f" 42.42 = " 42.420000");
+ (*test (sprintf "%#f" 42.42 = "42.420000");*)
+ (* >> '#' is incompatible with 'f' *)
+ test (sprintf "%13f" 42.42 = " 42.420000");
+ test (sprintf "%*f" 12 42.42 = " 42.420000");
+ (*test (sprintf "%-0+ #12f" 42.42 = "+42.420000 ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 'f' *)
+ test (sprintf "%.3f" (-42.42) = "-42.420");
+ test (sprintf "%.*f" (-3) 42.42 = "42.420");
+ (* dynamically-provided negative precisions are currently silently
+ turned into their absolute value; we could error on this
+ in the future (the behavior is unspecified), but the previous
+ buggy output "%.0-3f-" is not desirable. *)
+ test (sprintf "%-13.3f" (-42.42) = "-42.420 ");
+ test (sprintf "%013.3f" (-42.42) = "-00000042.420");
+ test (sprintf "%+.3f" 42.42 = "+42.420");
+ test (sprintf "% .3f" 42.42 = " 42.420");
+ (*test (sprintf "%#.3f" 42.42 = "42.420");*)
+ (* >> '#' is incompatible with 'f' *)
+ test (sprintf "%13.3f" 42.42 = " 42.420");
+ test (sprintf "%*.*f" 12 3 42.42 = " 42.420");
+ (*test (sprintf "%-0+ #12.3f" 42.42 = "+42.420 ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 'f' *)
+
+ (* Under Windows (mingw and maybe also MSVC), the stdlib uses three
+ digits for the exponent instead of the two used by Linux and BSD.
+ Check that the two strings are equal, except that there may be an
+ extra zero, and if there is one, there may be a missing space or
+ zero. All in the first string relative to the second. *)
+ let ( =* ) s1 s2 =
+ let ss1 = s1 ^ "$" in
+ let ss2 = s2 ^ "$" in
+ let rec loop i1 i2 extra missing =
+ if i1 = String.length ss1 && i2 = String.length ss2 then begin
+ if extra then true else not missing
+ end else if i1 = String.length ss1 || i2 = String.length ss2 then
+ false
+ else begin
+ match ss1.[i1], ss2.[i2] with
+ | x, y when x = y -> loop (i1+1) (i2+1) extra missing
+ | '0', _ when not extra -> loop (i1+1) i2 true missing
+ | _, (' '|'0') when not missing -> loop i1 (i2+1) extra true
+ | _, _ -> false
+ end
+ in
+ loop 0 0 false false
+ in
+
+ printf "\nF\n%!";
+ test (sprintf "%F" 42.42 = "42.42");
+ test (sprintf "%F" 42.42e42 =* "4.242e+43");
+ test (sprintf "%F" 42.00 = "42.");
+ test (sprintf "%F" 0.042 = "0.042");
+ test (sprintf "%4F" 3. = " 3.");
+ test (sprintf "%-4F" 3. = "3. ");
+ test (sprintf "%04F" 3. = "003.");
+(* plus-padding unsupported
+ test (sprintf "%+4F" 3. = " +3.");
+*)
+(* no precision
+ test (sprintf "%.3F" 42.42 = "42.420");
+ test (sprintf "%12.3F" 42.42e42 = " 4.242e+43");
+ test (sprintf "%.3F" 42.00 = "42.000");
+ test (sprintf "%.3F" 0.0042 = "0.004");
+*)
+
+ printf "\ne\n%!";
+ test (sprintf "%e" (-42.42) =* "-4.242000e+01");
+ test (sprintf "%-15e" (-42.42) =* "-4.242000e+01 ");
+ test (sprintf "%015e" (-42.42) =* "-004.242000e+01");
+ test (sprintf "%+e" 42.42 =* "+4.242000e+01");
+ test (sprintf "% e" 42.42 =* " 4.242000e+01");
+ (*test (sprintf "%#e" 42.42 =* "4.242000e+01");*)
+ (* >> '#' is incompatible with 'e' *)
+ test (sprintf "%15e" 42.42 =* " 4.242000e+01");
+ test (sprintf "%*e" 14 42.42 =* " 4.242000e+01");
+ (*test (sprintf "%-0+ #14e" 42.42 =* "+4.242000e+01 ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 'e' *)
+ test (sprintf "%.3e" (-42.42) =* "-4.242e+01");
+ test (sprintf "%-15.3e" (-42.42) =* "-4.242e+01 ");
+ test (sprintf "%015.3e" (-42.42) =* "-000004.242e+01");
+ test (sprintf "%+.3e" 42.42 =* "+4.242e+01");
+ test (sprintf "% .3e" 42.42 =* " 4.242e+01");
+ (*test (sprintf "%#.3e" 42.42 =* "4.242e+01");*)
+ (* >> '#' is incompatible with 'e' *)
+ test (sprintf "%15.3e" 42.42 =* " 4.242e+01");
+ test (sprintf "%*.*e" 11 3 42.42 =* " 4.242e+01");
+ (*test (sprintf "%-0+ #14.3e" 42.42 =* "+4.242e+01 ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 'e' *)
+
+ printf "\nE\n%!";
+ test (sprintf "%E" (-42.42) =* "-4.242000E+01");
+ test (sprintf "%-15E" (-42.42) =* "-4.242000E+01 ");
+ test (sprintf "%015E" (-42.42) =* "-004.242000E+01");
+ test (sprintf "%+E" 42.42 =* "+4.242000E+01");
+ test (sprintf "% E" 42.42 =* " 4.242000E+01");
+ (*test (sprintf "%#E" 42.42 =* "4.242000E+01");*)
+ (* >> '#' is incompatible with 'E' *)
+ test (sprintf "%15E" 42.42 =* " 4.242000E+01");
+ test (sprintf "%*E" 14 42.42 =* " 4.242000E+01");
+ (*test (sprintf "%-0+ #14E" 42.42 =* "+4.242000E+01 ");*)
+ (* >> '#' is incompatible with 'E' *)
+ test (sprintf "%.3E" (-42.42) =* "-4.242E+01");
+ test (sprintf "%-15.3E" (-42.42) =* "-4.242E+01 ");
+ test (sprintf "%015.3E" (-42.42) =* "-000004.242E+01");
+ test (sprintf "%+.3E" 42.42 =* "+4.242E+01");
+ test (sprintf "% .3E" 42.42 =* " 4.242E+01");
+ (*test (sprintf "%#.3E" 42.42 =* "4.242E+01");*)
+ (* >> '#' is incompatible with 'E' *)
+ test (sprintf "%15.3E" 42.42 =* " 4.242E+01");
+ test (sprintf "%*.*E" 11 3 42.42 =* " 4.242E+01");
+ (*test (sprintf "%-0+ #14.3E" 42.42 =* "+4.242E+01 ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 'E' *)
+
+(* %g gives strange results that correspond to neither %f nor %e
+ printf "\ng\n%!";
+ test (sprintf "%g" (-42.42) = "-42.42000");
+ test (sprintf "%-15g" (-42.42) = "-42.42000 ");
+ test (sprintf "%015g" (-42.42) = "-00000042.42000");
+ test (sprintf "%+g" 42.42 = "+42.42000");
+ test (sprintf "% g" 42.42 = " 42.42000");
+ test (sprintf "%#g" 42.42 = "42.42000");
+ test (sprintf "%15g" 42.42 = " 42.42000");
+ test (sprintf "%*g" 14 42.42 = " 42.42000");
+ test (sprintf "%-0+ #14g" 42.42 = "+42.42000 ");
+ test (sprintf "%.3g" (-42.42) = "-42.420");
+*)
+
+(* Same for %G
+ printf "\nG\n%!";
+*)
+
+ printf "\nB\n%!";
+ test (sprintf "%B" true = "true");
+ test (sprintf "%B" false = "false");
+
+ printf "\nld/li positive\n%!";
+ test (sprintf "%ld/%li" 42l 43l = "42/43");
+ test (sprintf "%-4ld/%-5li" 42l 43l = "42 /43 ");
+ test (sprintf "%04ld/%05li" 42l 43l = "0042/00043");
+ test (sprintf "%+ld/%+li" 42l 43l = "+42/+43");
+ test (sprintf "% ld/% li" 42l 43l = " 42/ 43");
+ (*test (sprintf "%#ld/%#li" 42l 43l = "42/43");*)
+ (* >> '#' is incompatible with 'ld' *)
+ test (sprintf "%4ld/%5li" 42l 43l = " 42/ 43");
+ test (sprintf "%*ld/%*li" 4 42l 5 43l = " 42/ 43");
+ (*test (sprintf "%-0+#4ld/%-0 #5li" 42l 43l = "+42 / 43 ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 'ld' *)
+
+ printf "\nld/li negative\n%!";
+ test (sprintf "%ld/%li" (-42l) (-43l) = "-42/-43");
+ test (sprintf "%-4ld/%-5li" (-42l) (-43l) = "-42 /-43 ");
+ test (sprintf "%04ld/%05li" (-42l) (-43l) = "-042/-0043");
+ test (sprintf "%+ld/%+li" (-42l) (-43l) = "-42/-43");
+ test (sprintf "% ld/% li" (-42l) (-43l) = "-42/-43");
+ (*test (sprintf "%#ld/%#li" (-42l) (-43l) = "-42/-43");*)
+ (* >> '#' is incompatible with 'ld' *)
+ test (sprintf "%4ld/%5li" (-42l) (-43l) = " -42/ -43");
+ test (sprintf "%*ld/%*li" 4 (-42l) 5 (-43l) = " -42/ -43");
+ (*test (sprintf "%-0+ #4ld/%-0+ #5li" (-42l) (-43l) = "-42 /-43 ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 'ld' *)
+
+ printf "\nlu positive\n%!";
+ test (sprintf "%lu" 42l = "42");
+ test (sprintf "%-4lu" 42l = "42 ");
+ test (sprintf "%04lu" 42l = "0042");
+ (*test (sprintf "%+lu" 42l = "42");*)
+ (* >> '+' is incompatible with 'lu' *)
+ (*test (sprintf "% lu" 42l = "42");*)
+ (* >> ' ' is incompatible with 'lu' *)
+ (*test (sprintf "%#lu" 42l = "42");*)
+ (* >> '#' is incompatible with 'lu' *)
+ test (sprintf "%4lu" 42l = " 42");
+ test (sprintf "%*lu" 4 42l = " 42");
+ (*test (sprintf "%-0+ #6ld" 42l = "+42 ");*)
+ (* >> '-' is incompatible with '0', '#' is incompatible with 'ld' *)
+
+ printf "\nlu negative\n%!";
+ test (sprintf "%lu" (-1l) = "4294967295");
+
+ printf "\nlx positive\n%!";
+ test (sprintf "%lx" 42l = "2a");
+ test (sprintf "%-4lx" 42l = "2a ");
+ test (sprintf "%04lx" 42l = "002a");
+ (*test (sprintf "%+lx" 42l = "2a");*)
+ (* >> '+' is incompatible with 'lx' *)
+ (*test (sprintf "% lx" 42l = "2a");*)
+ (* >> ' ' is incompatible with 'lx' *)
+ test (sprintf "%#lx" 42l = "0x2a");
+ test (sprintf "%4lx" 42l = " 2a");
+ test (sprintf "%*lx" 5 42l = " 2a");
+ (*test (sprintf "%-0+ #*lx" 5 42l = "0x2a ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nlx negative\n%!";
+ test (sprintf "%lx" (-42l) = "ffffffd6");
+
+ printf "\nlX positive\n%!";
+ test (sprintf "%lX" 42l = "2A");
+ test (sprintf "%-4lX" 42l = "2A ");
+ test (sprintf "%04lX" 42l = "002A");
+ (*test (sprintf "%+lX" 42l = "2A");*)
+ (* >> '+' is incompatible with 'lX' *)
+ (*test (sprintf "% lX" 42l = "2A");*)
+ (* >> ' ' is incompatible with 'lX' *)
+ test (sprintf "%#lX" 42l = "0X2A");
+ test (sprintf "%4lX" 42l = " 2A");
+ test (sprintf "%*lX" 5 42l = " 2A");
+ (*test (sprintf "%-0+ #*lX" 5 42l = "0X2A ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nlx negative\n%!";
+ test (sprintf "%lX" (-42l) = "FFFFFFD6");
+
+ printf "\nlo positive\n%!";
+ test (sprintf "%lo" 42l = "52");
+ test (sprintf "%-4lo" 42l = "52 ");
+ test (sprintf "%04lo" 42l = "0052");
+ (*test (sprintf "%+lo" 42l = "52");*)
+ (* >> '+' is incompatible with 'lo' *)
+ (*test (sprintf "% lo" 42l = "52");*)
+ (* >> ' ' is incompatible with 'lo' *)
+ test (sprintf "%#lo" 42l = "052");
+ test (sprintf "%4lo" 42l = " 52");
+ test (sprintf "%*lo" 5 42l = " 52");
+ (*test (sprintf "%-0+ #*lo" 5 42l = "052 ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nlo negative\n%!";
+ test (sprintf "%lo" (-42l) = "37777777726");
+
+ (* Nativeint not tested: looks like too much work, and anyway it should
+ work like Int32 or Int64. *)
+
+ printf "\nLd/Li positive\n%!";
+ test (sprintf "%Ld/%Li" 42L 43L = "42/43");
+ test (sprintf "%-4Ld/%-5Li" 42L 43L = "42 /43 ");
+ test (sprintf "%04Ld/%05Li" 42L 43L = "0042/00043");
+ (*test (sprintf "%+Ld/%+Li" 42L 43L = "+42/+43");*)
+ (* >> '+' is incompatible with 'Ld' *)
+ (*test (sprintf "% Ld/% Li" 42L 43L = " 42/ 43");*)
+ (* >> ' ' is incompatible with 'Ld' *)
+ (*test (sprintf "%#Ld/%#Li" 42L 43L = "42/43");*)
+ (* >> '#' is incompatible with 'Ld' *)
+ test (sprintf "%4Ld/%5Li" 42L 43L = " 42/ 43");
+ test (sprintf "%*Ld/%*Li" 4 42L 5 43L = " 42/ 43");
+ (*test (sprintf "%-0+#4Ld/%-0 #5Li" 42L 43L = "+42 / 43 ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nLd/Li negative\n%!";
+ test (sprintf "%Ld/%Li" (-42L) (-43L) = "-42/-43");
+ test (sprintf "%-4Ld/%-5Li" (-42L) (-43L) = "-42 /-43 ");
+ test (sprintf "%04Ld/%05Li" (-42L) (-43L) = "-042/-0043");
+ (*test (sprintf "%+Ld/%+Li" (-42L) (-43L) = "-42/-43");*)
+ (* >> '+' is incompatible with 'Ld' *)
+ (*test (sprintf "% Ld/% Li" (-42L) (-43L) = "-42/-43");*)
+ (* >> ' ' is incompatible with 'Ld' *)
+ (*test (sprintf "%#Ld/%#Li" (-42L) (-43L) = "-42/-43");*)
+ (* >> '#' is incompatible with 'Ld' *)
+ test (sprintf "%4Ld/%5Li" (-42L) (-43L) = " -42/ -43");
+ test (sprintf "%*Ld/%*Li" 4 (-42L) 5 (-43L) = " -42/ -43");
+ (*test (sprintf "%-0+ #4Ld/%-0+ #5Li" (-42L) (-43L) = "-42 /-43 ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nLu positive\n%!";
+ test (sprintf "%Lu" 42L = "42");
+ test (sprintf "%-4Lu" 42L = "42 ");
+ test (sprintf "%04Lu" 42L = "0042");
+ (*test (sprintf "%+Lu" 42L = "42");*)
+ (* >> '+' is incompatible with 'Lu' *)
+ (*test (sprintf "% Lu" 42L = "42");*)
+ (* >> ' ' is incompatible with 'Lu' *)
+ (*test (sprintf "%#Lu" 42L = "42");*)
+ (* >> '#' is incompatible with 'Lu' *)
+ test (sprintf "%4Lu" 42L = " 42");
+ test (sprintf "%*Lu" 4 42L = " 42");
+ (*test (sprintf "%-0+ #6Ld" 42L = "+42 ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nLu negative\n%!";
+ test (sprintf "%Lu" (-1L) = "18446744073709551615");
+
+ printf "\nLx positive\n%!";
+ test (sprintf "%Lx" 42L = "2a");
+ test (sprintf "%-4Lx" 42L = "2a ");
+ test (sprintf "%04Lx" 42L = "002a");
+ (*test (sprintf "%+Lx" 42L = "2a");*)
+ (* >> '+' is incompatible with 'Lx' *)
+ (*test (sprintf "% Lx" 42L = "2a");*)
+ (* >> ' ' is incompatible with 'Lx' *)
+ test (sprintf "%#Lx" 42L = "0x2a");
+ test (sprintf "%4Lx" 42L = " 2a");
+ test (sprintf "%*Lx" 5 42L = " 2a");
+ (*test (sprintf "%-0+ #*Lx" 5 42L = "0x2a ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nLx negative\n%!";
+ test (sprintf "%Lx" (-42L) = "ffffffffffffffd6");
+
+ printf "\nLX positive\n%!";
+ test (sprintf "%LX" 42L = "2A");
+ test (sprintf "%-4LX" 42L = "2A ");
+ test (sprintf "%04LX" 42L = "002A");
+ (*test (sprintf "%+LX" 42L = "2A");*)
+ (* >> '+' is incompatible with 'LX' *)
+ (*test (sprintf "% LX" 42L = "2A");*)
+ (* >> ' ' is incompatible with 'LX' *)
+ test (sprintf "%#LX" 42L = "0X2A");
+ test (sprintf "%4LX" 42L = " 2A");
+ test (sprintf "%*LX" 5 42L = " 2A");
+ (*test (sprintf "%-0+ #*LX" 5 42L = "0X2A ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nLx negative\n%!";
+ test (sprintf "%LX" (-42L) = "FFFFFFFFFFFFFFD6");
+
+ printf "\nLo positive\n%!";
+ test (sprintf "%Lo" 42L = "52");
+ test (sprintf "%-4Lo" 42L = "52 ");
+ test (sprintf "%04Lo" 42L = "0052");
+ (*test (sprintf "%+Lo" 42L = "52");*)
+ (* >> '+' is incompatible with 'Lo' *)
+ (*test (sprintf "% Lo" 42L = "52");*)
+ (* >> ' ' is incompatible with 'Lo' *)
+ test (sprintf "%#Lo" 42L = "052");
+ test (sprintf "%4Lo" 42L = " 52");
+ test (sprintf "%*Lo" 5 42L = " 52");
+ (*test (sprintf "%-0+ #*Lo" 5 42L = "052 ");*)
+ (* >> '-' is incompatible with '0' *)
+
+ printf "\nLo negative\n%!";
+ test (sprintf "%Lo" (-42L) = "1777777777777777777726");
+
+ printf "\na\n%!";
+ let x = ref () in
+ let f () y = if y == x then "ok" else "wrong" in
+ test (sprintf "%a" f x = "ok");
+
+ printf "\nt\n%!";
+ let f () = "ok" in
+ test (sprintf "%t" f = "ok");
+
+ (* Work as expected. Prints the format string type digest.
+ If you want to print the contents of the format string,
+ do not use a meta format; simply convert the format string
+ to a string and print it using %s. *)
+
+ printf "\n{...%%}\n%!";
+ let f = format_of_string "%4g/%s" in
+ test (sprintf "%{%.4F%5S%}" f = "%f%s");
+
+ printf "\n(...%%)\n%!";
+ let f = format_of_string "%d/foo/%s" in
+ test (sprintf "%(%d%s%)" f 42 "bar" = "42/foo/bar");
+
+ printf "\n! %% @ , and constants\n%!";
+ test (sprintf "%!" = "");
+ test (sprintf "%%" = "%");
+ test (sprintf "%@" = "@");
+ test (sprintf "%," = "");
+ test (sprintf "@" = "@");
+ test (sprintf "@@" = "@@");
+ test (sprintf "@%%" = "@%");
+
+ printf "\nend of tests\n%!";
+with e ->
+ printf "unexpected exception: %s\n%!" (Printexc.to_string e);
+ test false;
+;;
diff --git a/testsuite/tests/lib-printf/tprintf.reference b/testsuite/tests/lib-printf/tprintf.reference
new file mode 100644
index 0000000000..3a6c3f0dbc
--- /dev/null
+++ b/testsuite/tests/lib-printf/tprintf.reference
@@ -0,0 +1,91 @@
+d/i positive
+ 0 1 2 3 4 5 6 7
+d/i negative
+ 8 9 10 11 12 13 14 15
+u positive
+ 16 17 18 19 20 21
+u negative
+ 22
+x positive
+ 23 24 25 26 27 28 29 30 31 32 33
+x negative
+ 34
+X positive
+ 35 36 37 38 39 40
+x negative
+ 41
+o positive
+ 42 43 44 45 46 47
+o negative
+ 48
+s
+ 49 50 51 52 53 54 55 56 57 58
+S
+ 59 60 61 62 63 64 65 66
+c
+ 67
+C
+ 68 69
+f
+ 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
+F
+ 85 86 87 88 89 90 91
+e
+ 92 93 94 95 96 97 98 99 100 101 102 103 104 105
+E
+ 106 107 108 109 110 111 112 113 114 115 116 117 118 119
+B
+ 120 121
+ld/li positive
+ 122 123 124 125 126 127 128
+ld/li negative
+ 129 130 131 132 133 134 135
+lu positive
+ 136 137 138 139 140
+lu negative
+ 141
+lx positive
+ 142 143 144 145 146 147
+lx negative
+ 148
+lX positive
+ 149 150 151 152 153 154
+lx negative
+ 155
+lo positive
+ 156 157 158 159 160 161
+lo negative
+ 162
+Ld/Li positive
+ 163 164 165 166 167
+Ld/Li negative
+ 168 169 170 171 172
+Lu positive
+ 173 174 175 176 177
+Lu negative
+ 178
+Lx positive
+ 179 180 181 182 183 184
+Lx negative
+ 185
+LX positive
+ 186 187 188 189 190 191
+Lx negative
+ 192
+Lo positive
+ 193 194 195 196 197 198
+Lo negative
+ 199
+a
+ 200
+t
+ 201
+{...%}
+ 202
+(...%)
+ 203
+! % @ , and constants
+ 204 205 206 207 208 209 210
+end of tests
+
+All tests succeeded.
diff --git a/testsuite/tests/lib-random/Makefile b/testsuite/tests/lib-random/Makefile
new file mode 100644
index 0000000000..299656b246
--- /dev/null
+++ b/testsuite/tests/lib-random/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-random/rand.ml b/testsuite/tests/lib-random/rand.ml
new file mode 100644
index 0000000000..e8c5cb8bc7
--- /dev/null
+++ b/testsuite/tests/lib-random/rand.ml
@@ -0,0 +1,6 @@
+let () =
+ Random.self_init ();
+ let x = Random.int 10000 in
+ Random.self_init ();
+ let y = Random.int 1000 in
+ if x = y then print_endline "FAILED" else print_endline "PASSED"
diff --git a/testsuite/tests/lib-random/rand.reference b/testsuite/tests/lib-random/rand.reference
new file mode 100644
index 0000000000..53cdf1e939
--- /dev/null
+++ b/testsuite/tests/lib-random/rand.reference
@@ -0,0 +1 @@
+PASSED
diff --git a/testsuite/tests/lib-scanf-2/Makefile b/testsuite/tests/lib-scanf-2/Makefile
new file mode 100644
index 0000000000..b41f72c9b5
--- /dev/null
+++ b/testsuite/tests/lib-scanf-2/Makefile
@@ -0,0 +1,60 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+COMPFLAGS=-I $(OTOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+LD_PATH=$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+
+MYRUNTIME=`if [ -z "$(CUSTOM)" ]; then echo '$(OCAMLRUN)'; fi`
+
+.PHONY: default
+default:
+ @$(MAKE) compile
+ @$(SET_LD_PATH) $(MAKE) run
+
+.PHONY: compile
+compile: tscanf2_io.cmo
+ @rm -f master.byte master.native master.native.exe
+ @rm -f slave.byte slave.native slave.native.exe
+ @$(OCAMLC) unix.cma tscanf2_io.cmo -o master.byte tscanf2_master.ml
+ @$(OCAMLC) tscanf2_io.cmo -o slave.byte tscanf2_slave.ml
+ @if $(BYTECODE_ONLY); then : ; else \
+ $(MAKE) tscanf2_io.cmx; \
+ $(OCAMLOPT) unix.cmxa tscanf2_io.cmx -o master.native$(EXE) \
+ tscanf2_master.ml; \
+ $(OCAMLOPT) tscanf2_io.cmx -o slave.native$(EXE) tscanf2_slave.ml; \
+ fi
+
+run:
+ @printf " ... testing with ocamlc"
+ @$(MYRUNTIME) ./master.byte "$(OTOPDIR)/boot/ocamlrun$(EXE) \
+ `$(CYGPATH) ./slave.byte`" \
+ >result.byte 2>&1
+ @$(DIFF) reference result.byte >/dev/null \
+ && if $(BYTECODE_ONLY); then : ; else \
+ printf " ocamlopt"; \
+ ./master.native$(EXE) "`$(CYGPATH) ./slave.native`" \
+ >result.native 2>&1; \
+ $(DIFF) reference result.native >/dev/null; \
+ fi \
+ && echo " => passed" || echo " => failed"
+
+.PHONY: promote
+promote:
+ @cp result.byte reference
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f master.* slave.* result.*
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-scanf-2/reference b/testsuite/tests/lib-scanf-2/reference
new file mode 100644
index 0000000000..4b8d53fce4
--- /dev/null
+++ b/testsuite/tests/lib-scanf-2/reference
@@ -0,0 +1,2 @@
+ Ping-pong Ping-pong Ping-pong Ping-pong Ping-pong Ping-pong Ping-pong Ping-pong!
+Test OK.
diff --git a/testsuite/tests/lib-scanf-2/tscanf2_io.ml b/testsuite/tests/lib-scanf-2/tscanf2_io.ml
new file mode 100644
index 0000000000..b06ed87708
--- /dev/null
+++ b/testsuite/tests/lib-scanf-2/tscanf2_io.ml
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2005 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A very simple communication module using buffers. It should help detecting
+ advanced character reading by Scanf when using stdin. *)
+
+let send_flush send ob oc t =
+ send ob t;
+ Buffer.output_buffer oc ob;
+ Buffer.clear ob;
+ flush oc
+;;
+
+(* The correct sending format for the test should be "%S\n",
+ but to avoid problems when Scanf ask too early for the next character,
+ "%S\n\n" is fine. *)
+let send_string = send_flush (fun ob -> Printf.bprintf ob "%S\n");;
+
+(* The correct reading format for the test should be "%S\n",
+ but to avoid problems when Scanf ask too early for the next character,
+ " %S\n" is fine. *)
+let receive_string ib = Scanf.bscanf ib "%S\n" (fun s -> s);;
diff --git a/testsuite/tests/lib-scanf-2/tscanf2_master.ml b/testsuite/tests/lib-scanf-2/tscanf2_master.ml
new file mode 100644
index 0000000000..a34cd013f4
--- /dev/null
+++ b/testsuite/tests/lib-scanf-2/tscanf2_master.ml
@@ -0,0 +1,63 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2005 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A very simple master:
+ - first launch a slave process,
+ - then repeat a random number of times:
+ + print the string " Ping" on stderr,
+ + send it to the slave,
+ + and wait for its answer "-pong",
+ - finally send the string "stop" to the slave
+ and wait for its answer "OK, bye!"
+ and die.
+
+ Use the communication module Tscanf2_io.
+
+ Usage: test_master <slave_name> *)
+
+open Tscanf2_io;;
+
+let slave = Sys.argv.(1);;
+let ic, oc = Unix.open_process slave;;
+let ib = Scanf.Scanning.from_channel ic;;
+let ob = Buffer.create 1024;;
+
+let send_string_ping ob = send_string ob oc " Ping";;
+let send_string_stop ob = send_string ob oc "stop";;
+
+let interact i =
+ Printf.eprintf " Ping"; flush stderr;
+ send_string_ping ob;
+ let s = receive_string ib in
+ if s <> "-pong" then failwith ("Master: unbound string " ^ s)
+;;
+
+begin
+(*
+ Random.self_init ();
+ let n = max (Random.int 8) 1 in
+*)
+ let n = 8 in
+ let rec loop i =
+ if i > 0 then (interact i; loop (i - 1)) in
+ loop n
+end
+;;
+
+begin
+ send_string_stop ob;
+ let ack = receive_string ib in
+ if ack = "OK, bye!"
+ then (print_endline "Test OK."; exit 0)
+ else (print_endline "Test Failed!"; exit 2)
+end
+;;
diff --git a/testsuite/tests/lib-scanf-2/tscanf2_slave.ml b/testsuite/tests/lib-scanf-2/tscanf2_slave.ml
new file mode 100644
index 0000000000..a444df18ae
--- /dev/null
+++ b/testsuite/tests/lib-scanf-2/tscanf2_slave.ml
@@ -0,0 +1,40 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2005 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* A very simple slave:
+ - read the string " Ping" on stdin,
+ - then print the string "-pong" on stderr,
+ - and send it back on stdout
+ - until reading the string "stop" on stdin,
+ - then print the string "!\n" on stderr,
+ - send back the string "OK, bye!" on stdout,
+ - and die.
+
+ Use the communication module Test_scanf2_io. *)
+
+open Tscanf2_io;;
+
+let ib = Scanf.Scanning.from_channel stdin;;
+let ob = Buffer.create 1024
+and oc = stdout;;
+
+let send_string_pong ob = send_string ob oc "-pong";;
+let send_string_okbye ob = send_string ob oc "OK, bye!";;
+
+while true do
+ let s = receive_string ib in
+ match s with
+ | " Ping" -> Printf.eprintf "-pong"; flush stderr; send_string_pong ob
+ | "stop" -> Printf.eprintf "!\n"; flush stderr; send_string_okbye ob; exit 0
+ | s -> failwith ("Slave: unbound string " ^ s)
+done
+;;
diff --git a/testsuite/tests/lib-scanf/.ignore b/testsuite/tests/lib-scanf/.ignore
new file mode 100644
index 0000000000..a940814e01
--- /dev/null
+++ b/testsuite/tests/lib-scanf/.ignore
@@ -0,0 +1 @@
+tscanf_data
diff --git a/testsuite/tests/lib-scanf/Makefile b/testsuite/tests/lib-scanf/Makefile
new file mode 100644
index 0000000000..55b0c00521
--- /dev/null
+++ b/testsuite/tests/lib-scanf/Makefile
@@ -0,0 +1,21 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=tscanf
+ADD_COMPFLAGS=-I $(OTOPDIR)/testsuite/lib
+ADD_MODULES=testing
+TEST_TEMP_FILES=tscanf_data
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-scanf/tscanf.ml b/testsuite/tests/lib-scanf/tscanf.ml
new file mode 100644
index 0000000000..a93637ec04
--- /dev/null
+++ b/testsuite/tests/lib-scanf/tscanf.ml
@@ -0,0 +1,1491 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+(*
+
+A testbed file for the module Scanf.
+
+*)
+
+open Testing;;
+
+open Scanf;;
+
+(* The ``continuation'' that returns the scanned value. *)
+let id x = x;;
+
+(* Testing space scanning. *)
+let test0 () =
+ (sscanf "" "" id) 1 +
+ (sscanf "" " " id) 2 +
+ (sscanf " " " " id) 3 +
+ (sscanf "\t" " " id) 4 +
+ (sscanf "\n" " " id) 5 +
+ (sscanf "\n\t 6" " %d" id)
+;;
+
+test (test0 () = 21)
+;;
+
+(* Testing integer scanning %i and %d. *)
+let test1 () =
+ sscanf "1" "%d" id +
+ sscanf " 2" " %d" id +
+ sscanf " -2" " %d" id +
+ sscanf " +2" " %d" id +
+ sscanf " 2a " " %da" id
+;;
+
+test (test1 () = 5)
+;;
+
+let test2 () =
+ sscanf "123" "%2i" id +
+ sscanf "245" "%d" id +
+ sscanf " 2a " " %1da" id
+;;
+
+test (test2 () = 259)
+;;
+
+let test3 () =
+ sscanf "0xff" "%3i" id +
+ sscanf "0XEF" "%3i" id +
+ sscanf "x=-245" " x = %d" id +
+ sscanf " 2a " " %1da" id
+;;
+
+test (test3 () = -214)
+;;
+
+(* Testing float scanning. *)
+(* f style. *)
+let test4 () =
+ bscanf (Scanning.from_string "1")
+ "%f" (fun b0 -> b0 = 1.0) &&
+ bscanf (Scanning.from_string "-1")
+ "%f" (fun b0 -> b0 = -1.0) &&
+ bscanf (Scanning.from_string "+1")
+ "%f" (fun b0 -> b0 = 1.0) &&
+ bscanf (Scanning.from_string "1.")
+ "%f" (fun b0 -> b0 = 1.0) &&
+ bscanf (Scanning.from_string ".1")
+ "%f" (fun b0 -> b0 = 0.1) &&
+ bscanf (Scanning.from_string "-.1")
+ "%f" (fun b0 -> b0 = -0.1) &&
+ bscanf (Scanning.from_string "+.1")
+ "%f" (fun b0 -> b0 = 0.1) &&
+ bscanf (Scanning.from_string "+1.")
+ "%f" (fun b0 -> b0 = 1.0) &&
+ bscanf (Scanning.from_string "-1.")
+ "%f" (fun b0 -> b0 = -1.0) &&
+ bscanf (Scanning.from_string "0 1. 1.3")
+ "%f %f %f" (fun b0 b1 b2 -> b0 = 0.0 && b1 = 1.0 && b2 = 1.3) &&
+ bscanf (Scanning.from_string "0.113")
+ "%4f" (fun b0 -> b0 = 0.11) &&
+ bscanf (Scanning.from_string "0.113")
+ "%5f" (fun b0 -> b0 = 0.113) &&
+ bscanf (Scanning.from_string "000.113")
+ "%15f" (fun b0 -> b0 = 0.113) &&
+ bscanf (Scanning.from_string "+000.113")
+ "%15f" (fun b0 -> b0 = 0.113) &&
+ bscanf (Scanning.from_string "-000.113")
+ "%15f" (fun b0 -> b0 = -0.113)
+;;
+test (test4 ())
+;;
+
+(* e style. *)
+let test5 () =
+ bscanf (Scanning.from_string "1e1")
+ "%e" (fun b -> b = 10.0) &&
+ bscanf (Scanning.from_string "1e+1")
+ "%e" (fun b -> b = 10.0) &&
+ bscanf (Scanning.from_string "10e-1")
+ "%e" (fun b -> b = 1.0) &&
+ bscanf (Scanning.from_string "10.e-1")
+ "%e" (fun b -> b = 1.0) &&
+ bscanf (Scanning.from_string "1e1 1.e+1 1.3e-1")
+ "%e %e %e" (fun b1 b2 b3 -> b1 = 10.0 && b2 = b1 && b3 = 0.13) &&
+
+(* g style. *)
+ bscanf (Scanning.from_string "1 1.1 0e+1 1.3e-1")
+ "%g %g %g %g"
+ (fun b1 b2 b3 b4 ->
+ b1 = 1.0 && b2 = 1.1 && b3 = 0.0 && b4 = 0.13)
+;;
+
+test (test5 ())
+;;
+
+(* Testing boolean scanning. *)
+let test6 () =
+ bscanf (Scanning.from_string "truetrue") "%B%B"
+ (fun b1 b2 -> (b1, b2) = (true, true)) &&
+ bscanf (Scanning.from_string "truefalse") "%B%B"
+ (fun b1 b2 -> (b1, b2) = (true, false)) &&
+ bscanf (Scanning.from_string "falsetrue") "%B%B"
+ (fun b1 b2 -> (b1, b2) = (false, true)) &&
+ bscanf (Scanning.from_string "falsefalse") "%B%B"
+ (fun b1 b2 -> (b1, b2) = (false, false)) &&
+ bscanf (Scanning.from_string "true false") "%B %B"
+ (fun b1 b2 -> (b1, b2) = (true, false))
+;;
+
+test (test6 ())
+;;
+
+(* Testing char scanning. *)
+
+let test7 () =
+ bscanf (Scanning.from_string "'a' '\n' '\t' '\000' '\032'")
+ "%C %C %C %C %C"
+ (fun c1 c2 c3 c4 c5 ->
+ c1 = 'a' && c2 = '\n' && c3 = '\t' && c4 = '\000' && c5 = '\032') &&
+
+(* Here \n, \t, and \032 are skipped due to the space semantics of scanf. *)
+ bscanf (Scanning.from_string "a \n \t \000 \032b")
+ "%c %c %c "
+ (fun c1 c2 c3 ->
+ c1 = 'a' && c2 = '\000' && c3 = 'b')
+;;
+
+test (test7 ())
+;;
+
+let verify_read c =
+ let s = Printf.sprintf "%C" c in
+ let ib = Scanning.from_string s in
+ assert (bscanf ib "%C" id = c)
+;;
+
+let verify_scan_Chars () =
+ for i = 0 to 255 do verify_read (char_of_int i) done
+;;
+
+let test8 () = verify_scan_Chars () = ();;
+
+test (test8 ())
+;;
+
+(* Testing string scanning. *)
+
+(* %S and %s styles. *)
+let unit fmt s =
+ let ib = Scanning.from_string (Printf.sprintf "%S" s) in
+ Scanf.bscanf ib fmt id
+;;
+
+let test_fmt fmt s = unit fmt s = s;;
+
+let test9_string = "\239\187\191";;
+
+let test_S = test_fmt "%S";;
+let test9 () =
+ test_S "poi" &&
+ test_S "a\"b" &&
+ test_S "a\nb" &&
+ test_S "a\010b" &&
+ test_S "a\\\n\
+ b \\\n\
+ c\010\\\n\
+ b" &&
+ test_S "a\\\n\
+ \\\n\
+ \\\n\
+ b \\\n\
+ c\010\\\n\
+ b" &&
+ test_S "\xef" &&
+ test_S "\\xef" &&
+ Scanf.sscanf "\"\\xef\"" "%S" (fun s -> s) =
+ "\xef" &&
+ Scanf.sscanf "\"\\xef\\xbb\\xbf\"" "%S" (fun s -> s) =
+ test9_string &&
+ Scanf.sscanf "\"\\xef\\xbb\\xbf\"" "%S" (fun s -> s) =
+ "\239\187\191" &&
+ Scanf.sscanf "\"\xef\xbb\xbf\"" "%S" (fun s -> s) =
+ test9_string &&
+ Scanf.sscanf "\"\\\\xef\\\\xbb\\\\xbf\"" "%S" (fun s -> s) =
+ "\\xef\\xbb\\xbf" &&
+ Scanf.sscanf "\"\ \"" "%S" (fun s -> s) =
+ "\ "
+;;
+
+test (test9 ())
+;;
+
+let test10 () =
+ let unit s =
+ let ib = Scanning.from_string s in
+ Scanf.bscanf ib "%S" id in
+
+ let res =
+ sscanf "Une chaine: \"celle-ci\" et \"celle-la\"!"
+ "%s %s %S %s %S %s"
+ (fun s1 s2 s3 s4 s5 s6 -> s1 ^ s2 ^ s3 ^ s4 ^ s5 ^ s6) in
+ res = "Unechaine:celle-cietcelle-la!" &&
+ (* Testing the result of reading a %S string. *)
+ unit "\"a\\\n b\"" = "ab" &&
+ unit "\"\\\n ab\"" = "ab" &&
+ unit "\"\n\\\n ab\"" = "\nab" &&
+ unit "\"\n\\\n a\nb\"" = "\na\nb" &&
+ unit "\"\n\\\n \\\n a\nb\"" = "\na\nb" &&
+ unit "\"\n\\\n a\n\\\nb\\\n\"" = "\na\nb" &&
+ unit "\"a\\\n \"" = "a" &&
+ true
+;;
+
+test (test10 ())
+;;
+
+(* %[] style *)
+let test11 () =
+ sscanf "Pierre\tWeis\t70" "%s %s %s"
+ (fun prenom nom poids ->
+ prenom = "Pierre" && nom = "Weis" && int_of_string poids = 70)
+ &&
+ sscanf "Jean-Luc\tde Leage\t68" "%[^\t] %[^\t] %d"
+ (fun prenom nom poids ->
+ prenom = "Jean-Luc" && nom = "de Leage" && poids = 68)
+ &&
+ sscanf "Daniel\tde Rauglaudre\t66" "%s@\t %s@\t %d"
+ (fun prenom nom poids ->
+ prenom = "Daniel" && nom = "de Rauglaudre" && poids = 66)
+;;
+
+(* Empty string (end of input) testing. *)
+let test110 () =
+ sscanf "" " " (fun x -> x) "" = "" &&
+ sscanf "" "%s" (fun x -> x = "") &&
+ sscanf "" "%s%s" (fun x y -> x = "" && y = "") &&
+ sscanf "" "%s " (fun x -> x = "") &&
+ sscanf "" " %s" (fun x -> x = "") &&
+ sscanf "" " %s " (fun x -> x = "") &&
+ sscanf "" "%[^\n]" (fun x -> x = "") &&
+ sscanf "" "%[^\n] " (fun x -> x = "") &&
+ sscanf " " "%s" (fun x -> x = "") &&
+ sscanf " " "%s%s" (fun x y -> x = "" && y = "") &&
+ sscanf " " " %s " (fun x -> x = "") &&
+ sscanf " " " %s %s" (fun x y -> x = "" && x = y) &&
+ sscanf " " " %s@ %s" (fun x y -> x = "" && x = y) &&
+ sscanf " poi !" " %s@ %s@." (fun x y -> x = "poi" && y = "!") &&
+ sscanf " poi !" "%s@ %s@." (fun x y -> x = "" && y = "poi !")
+;;
+
+let test111 () = sscanf "" "%[^\n]@\n" (fun x -> x = "");;
+
+test (test11 () && test110 () && test111 ())
+;;
+
+(* Scanning lists. *)
+let ib () = Scanning.from_string "[1;2;3;4; ]";;
+
+(* Statically known lists can be scanned directly. *)
+let f ib =
+ bscanf ib " [" ();
+ bscanf ib " %i;" (fun i ->
+ bscanf ib " %i;" (fun j ->
+ bscanf ib " %i;" (fun k ->
+ bscanf ib " %i;" (fun l ->
+ bscanf ib " ]" ();
+ [i; j; k; l]))));;
+
+let test12 () = f (ib ()) = [1; 2; 3; 4];;
+
+test (test12 ())
+;;
+
+(* A general list scanner that always fails to succeed. *)
+let rec scan_elems ib accu =
+ try bscanf ib " %i;" (fun i -> scan_elems ib (i :: accu)) with
+ | _ -> accu
+;;
+
+let g ib = bscanf ib "[ " (); List.rev (scan_elems ib []);;
+
+let test13 () = g (ib ()) = [1; 2; 3; 4];;
+
+test (test13 ())
+;;
+
+(* A general int list scanner. *)
+let rec scan_int_list ib =
+ bscanf ib "[ " ();
+ let accu = scan_elems ib [] in
+ bscanf ib " ]" ();
+ List.rev accu
+;;
+
+let test14 () = scan_int_list (ib ()) = [1; 2; 3; 4];;
+
+test (test14 ())
+;;
+
+(* A general list scanner that always succeeds. *)
+let rec scan_elems ib accu =
+ bscanf ib " %i %c"
+ (fun i -> function
+ | ';' -> scan_elems ib (i :: accu)
+ | ']' -> List.rev (i :: accu)
+ | c -> failwith "scan_elems")
+;;
+
+let rec scan_int_list ib =
+ bscanf ib "[ " ();
+ scan_elems ib []
+;;
+
+let test15 () =
+ scan_int_list (Scanning.from_string "[1;2;3;4]") = [1; 2; 3; 4];;
+
+test (test15 ())
+;;
+
+let rec scan_elems ib accu =
+ try
+ bscanf ib "%c %i"
+ (fun c i ->
+ match c with
+ | ';' -> scan_elems ib (i :: accu)
+ | ']' -> List.rev (i :: accu)
+ | '[' when accu = [] -> scan_elems ib (i :: accu)
+ | c -> print_endline (String.make 1 c); failwith "scan_elems")
+ with
+ | Scan_failure _ -> bscanf ib "]" (); accu
+ | End_of_file -> accu
+;;
+
+let scan_int_list ib = scan_elems ib [];;
+
+let test16 () =
+ scan_int_list (Scanning.from_string "[]") = List.rev [] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4]") = List.rev [1;2;3;4] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4; ]") = List.rev [1;2;3;4] &&
+ (* Should fail but succeeds! *)
+ scan_int_list (Scanning.from_string "[1;2;3;4") = List.rev [1;2;3;4];;
+
+test (test16 ())
+;;
+
+let rec scan_elems ib accu =
+ bscanf ib " %i%[]; \t\n\r]"
+ (fun i s ->
+ match s with
+ | ";" -> scan_elems ib (i :: accu)
+ | "]" -> List.rev (i :: accu)
+ | s -> List.rev (i :: accu))
+;;
+
+let scan_int_list ib =
+ bscanf ib " [" ();
+ scan_elems ib []
+;;
+
+let test17 () =
+ scan_int_list (Scanning.from_string "[1;2;3;4]") = [1;2;3;4] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4; ]") = [1;2;3;4] &&
+ (* Should fail but succeeds! *)
+ scan_int_list (Scanning.from_string "[1;2;3;4 5]") = [1;2;3;4];;
+
+test (test17 ())
+;;
+
+let rec scan_elems ib accu =
+ bscanf ib " %c " (fun c ->
+ match c with
+ | '[' when accu = [] ->
+ (* begginning of list: could find either
+ - an int, if the list is not empty,
+ - the char ], if the list is empty. *)
+ bscanf ib "%[]]"
+ (function
+ | "]" -> accu
+ | _ ->
+ bscanf ib " %i " (fun i ->
+ scan_rest ib (i :: accu)))
+ | _ -> failwith "scan_elems")
+
+and scan_rest ib accu =
+ bscanf ib " %c " (fun c ->
+ match c with
+ | ';' ->
+ bscanf ib "%[]]"
+ (function
+ | "]" -> accu
+ | _ ->
+ bscanf ib " %i " (fun i ->
+ scan_rest ib (i :: accu)))
+ | ']' -> accu
+ | _ -> failwith "scan_rest")
+;;
+
+let scan_int_list ib = List.rev (scan_elems ib []);;
+
+let test18 () =
+ scan_int_list (Scanning.from_string "[]") = [] &&
+ scan_int_list (Scanning.from_string "[ ]") = [] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4]") = [1;2;3;4] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4; ]") = [1;2;3;4];;
+
+test (test18 ())
+;;
+
+(* Those properly fail *)
+
+let test19 () =
+ failure_test
+ scan_int_list (Scanning.from_string "[1;2;3;4 5]")
+ "scan_rest"
+;;
+
+(test19 ())
+;;
+
+let test20 () =
+ scan_failure_test
+ scan_int_list (Scanning.from_string "[1;2;3;4;; 5]");;
+
+(test20 ())
+;;
+
+let test21 () =
+ scan_failure_test
+ scan_int_list (Scanning.from_string "[1;2;3;4;;");;
+
+(test21 ())
+;;
+
+let rec scan_elems ib accu =
+ bscanf ib "%1[];]" (function
+ | "]" -> accu
+ | ";" -> scan_rest ib accu
+ | _ ->
+ failwith
+ (Printf.sprintf "scan_int_list" (*
+ "scan_int_list: char %i waiting for ']' or ';' but found %c"
+ (Scanning.char_count ib) (Scanning.peek_char ib)*)))
+
+and scan_rest ib accu =
+ bscanf ib "%[]]" (function
+ | "]" -> accu
+ | _ -> scan_elem ib accu)
+
+and scan_elem ib accu =
+ bscanf ib " %i " (fun i -> scan_elems ib (i :: accu))
+;;
+
+let scan_int_list ib =
+ bscanf ib " [ " ();
+ List.rev (scan_rest ib [])
+;;
+
+let test22 () =
+ scan_int_list (Scanning.from_string "[]") = [] &&
+ scan_int_list (Scanning.from_string "[ ]") = [] &&
+ scan_int_list (Scanning.from_string "[1]") = [1] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4]") = [1;2;3;4] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4;]") = [1;2;3;4];;
+
+test (test22 ())
+;;
+
+(* Should work but does not with this version of scan_int_list!
+scan_int_list (Scanning.from_string "[1;2;3;4; ]");;
+(* Should lead to a bad input error. *)
+scan_int_list (Scanning.from_string "[1;2;3;4 5]");;
+scan_int_list (Scanning.from_string "[1;2;3;4;;");;
+scan_int_list (Scanning.from_string "[1;2;3;4;; 5]");;
+scan_int_list (Scanning.from_string "[1;2;3;4;; 23]");;
+*)
+
+let rec scan_elems ib accu =
+ try bscanf ib " %i %1[;]" (fun i s ->
+ if s = "" then i :: accu else scan_elems ib (i :: accu)) with
+ | Scan_failure _ -> accu
+;;
+
+(* The general int list scanner. *)
+let rec scan_int_list ib =
+ bscanf ib "[ " ();
+ let accu = scan_elems ib [] in
+ bscanf ib " ]" ();
+ List.rev accu
+;;
+
+(* The general HO list scanner.
+ This version does not fix the separator, nor the spacing before and after
+ the separator (it uses the functional argument [scan_elem] to parse the
+ separator, its spacing, and the item).
+ *)
+let rec scan_elems ib scan_elem accu =
+ try scan_elem ib (fun i s ->
+ let accu = i :: accu in
+ if s = "" then accu else scan_elems ib scan_elem accu) with
+ | Scan_failure _ -> accu
+;;
+
+let scan_list scan_elem ib =
+ bscanf ib "[ " ();
+ let accu = scan_elems ib scan_elem [] in
+ bscanf ib " ]" ();
+ List.rev accu
+;;
+
+(* Deriving particular list scanners from the HO list scanner. *)
+let scan_int_elem ib = bscanf ib " %i %1[;]";;
+let scan_int_list = scan_list scan_int_elem;;
+
+let test23 () =
+ scan_int_list (Scanning.from_string "[]") = [] &&
+ scan_int_list (Scanning.from_string "[ ]") = [] &&
+ scan_int_list (Scanning.from_string "[1]") = [1] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4]") = [1;2;3;4] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4;]") = [1;2;3;4];;
+
+test (test23 ())
+;;
+
+let test24 () =
+ scan_failure_test scan_int_list (Scanning.from_string "[1;2;3;4 5]")
+and test25 () =
+ scan_failure_test scan_int_list (Scanning.from_string "[1;2;3;4;;")
+and test26 () =
+ scan_failure_test scan_int_list (Scanning.from_string "[1;2;3;4;; 5]")
+and test27 () =
+ scan_failure_test scan_int_list (Scanning.from_string "[1;2;3;4;; 23]");;
+
+ (test24 ()) &&
+ (test25 ()) &&
+ (test26 ()) &&
+ (test27 ())
+;;
+
+(* To scan an OCaml string:
+ the format is "\"%s@\"".
+ A better way would be to add a %S (String.escaped), a %C (Char.escaped).
+ This is now available. *)
+let scan_string_elem ib = bscanf ib " \"%s@\" %1[;]";;
+let scan_string_list = scan_list scan_string_elem;;
+
+let scan_String_elem ib = bscanf ib " %S %1[;]";;
+let scan_String_list = scan_list scan_String_elem;;
+
+let test28 () =
+ scan_string_list (Scanning.from_string "[]") = [] &&
+ scan_string_list (Scanning.from_string "[\"Le\"]") = ["Le"] &&
+ scan_string_list
+ (Scanning.from_string "[\"Le\";\"langage\";\"Objective\";\"Caml\"]") =
+ ["Le"; "langage"; "Objective"; "Caml"] &&
+ scan_string_list
+ (Scanning.from_string "[\"Le\";\"langage\";\"Objective\";\"Caml\"; ]") =
+ ["Le"; "langage"; "Objective"; "Caml"] &&
+
+ scan_String_list (Scanning.from_string "[]") = [] &&
+ scan_String_list (Scanning.from_string "[\"Le\"]") = ["Le"] &&
+ scan_String_list
+ (Scanning.from_string "[\"Le\";\"langage\";\"Objective\";\"Caml\"]") =
+ ["Le"; "langage"; "Objective"; "Caml"] &&
+ scan_String_list
+ (Scanning.from_string "[\"Le\";\"langage\";\"Objective\";\"Caml\"; ]") =
+ ["Le"; "langage"; "Objective"; "Caml"];;
+
+test (test28 ())
+;;
+
+(* The general HO list scanner with continuations. *)
+let rec scan_elems ib scan_elem accu =
+ scan_elem ib
+ (fun i s ->
+ let accu = i :: accu in
+ if s = "" then accu else scan_elems ib scan_elem accu)
+ (fun ib exc -> accu)
+;;
+
+let scan_list scan_elem ib =
+ bscanf ib "[ " ();
+ let accu = scan_elems ib scan_elem [] in
+ bscanf ib " ]" ();
+ List.rev accu
+;;
+
+(* Deriving particular list scanners from the HO list scanner. *)
+let scan_int_elem ib f ek = kscanf ib ek " %i %1[;]" f;;
+let scan_int_list = scan_list scan_int_elem;;
+
+let test29 () =
+ scan_int_list (Scanning.from_string "[]") = [] &&
+ scan_int_list (Scanning.from_string "[ ]") = [] &&
+ scan_int_list (Scanning.from_string "[1]") = [1] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4]") = [1;2;3;4] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4;]") = [1;2;3;4];;
+
+test (test29 ())
+;;
+
+let scan_string_elem ib f ek = kscanf ib ek " %S %1[;]" f;;
+let scan_string_list = scan_list scan_string_elem;;
+
+let test30 () =
+ scan_string_list (Scanning.from_string "[]") = [] &&
+ scan_string_list (Scanning.from_string "[ ]") = [] &&
+ scan_string_list (Scanning.from_string "[ \"1\" ]") = ["1"] &&
+ scan_string_list
+ (Scanning.from_string "[\"1\"; \"2\"; \"3\"; \"4\"]") =
+ ["1"; "2"; "3"; "4"] &&
+ scan_string_list
+ (Scanning.from_string "[\"1\"; \"2\"; \"3\"; \"4\";]") =
+ ["1"; "2"; "3"; "4"];;
+
+test (test30 ())
+;;
+
+(* A generic polymorphic item scanner, *)
+let scan_elem fmt ib f ek = kscanf ib ek fmt f;;
+
+(* Derivation of list scanners from the generic polymorphic item scanner
+ applications. *)
+let scan_int_list = scan_list (scan_elem " %i %1[;]");;
+let scan_string_list = scan_list (scan_elem " %S %1[;]");;
+let scan_bool_list = scan_list (scan_elem " %B %1[;]");;
+let scan_char_list = scan_list (scan_elem " %C %1[;]");;
+let scan_float_list = scan_list (scan_elem " %f %1[;]");;
+
+(* In this version the [scan_elem] function should be a [kscanf] like
+ scanning function: we give it an error continuation.
+
+ The [scan_elem] argument, probably use some partial application of the
+ following generic [scan_elem]:
+
+ let scan_elem fmt ib f ek = kscanf ib ek fmt f;;
+
+ For instance, a suitable [scan_elem] for integers could be:
+
+ let scan_integer_elem = scan_elem " %i";;
+
+*)
+let rec scan_elems ib scan_elem accu =
+ scan_elem ib
+ (fun i ->
+ let accu = i :: accu in
+ kscanf ib
+ (fun ib exc -> accu)
+ " %1[;]"
+ (fun s -> if s = "" then accu else scan_elems ib scan_elem accu))
+ (fun ib exc -> accu)
+;;
+
+let scan_list scan_elem ib =
+ bscanf ib "[ " ();
+ let accu = scan_elems ib scan_elem [] in
+ bscanf ib " ]" ();
+ List.rev accu
+;;
+
+let scan_int_list = scan_list (scan_elem " %i");;
+let scan_string_list = scan_list (scan_elem " %S");;
+let scan_bool_list = scan_list (scan_elem " %B");;
+let scan_char_list = scan_list (scan_elem " %C");;
+let scan_float_list = scan_list (scan_elem " %f");;
+
+let test31 () =
+ scan_int_list (Scanning.from_string "[]") = [] &&
+ scan_int_list (Scanning.from_string "[ ]") = [] &&
+ scan_int_list (Scanning.from_string "[1]") = [1] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4]") = [1;2;3;4] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4;]") = [1;2;3;4];;
+
+test (test31 ())
+;;
+
+let test32 () =
+ scan_string_list (Scanning.from_string "[]") = [] &&
+ scan_string_list (Scanning.from_string "[ ]") = [] &&
+ scan_string_list (Scanning.from_string "[ \"1\" ]") = ["1"] &&
+ scan_string_list
+ (Scanning.from_string "[\"1\"; \"2\"; \"3\"; \"4\"]") =
+ ["1"; "2"; "3"; "4"] &&
+ scan_string_list
+ (Scanning.from_string "[\"1\"; \"2\"; \"3\"; \"4\";]") =
+ ["1"; "2"; "3"; "4"];;
+
+test (test32 ())
+;;
+
+(* Using [kscanf] only.
+
+ We use format values to stand for ``functional'' specifications to scan
+ the elements of lists.
+
+ The list item separator and the separator spacing are builtin into the
+ [scan_elems] iterator and thus are conveniently omitted from the
+ definitional format for item scanning.
+*)
+let rec scan_elems ib scan_elem_fmt accu =
+ kscanf ib (fun ib exc -> accu)
+ scan_elem_fmt
+ (fun i ->
+ let accu = i :: accu in
+ bscanf ib
+ " %1[;] "
+ (function
+ | "" -> accu
+ | _ -> scan_elems ib scan_elem_fmt accu)
+ )
+;;
+
+let scan_list scan_elem_fmt ib =
+ bscanf ib "[ " ();
+ let accu = scan_elems ib scan_elem_fmt [] in
+ bscanf ib " ]" ();
+ List.rev accu
+;;
+
+let scan_int_list = scan_list "%i";;
+let scan_string_list = scan_list "%S";;
+let scan_bool_list = scan_list "%B";;
+let scan_char_list = scan_list "%C";;
+let scan_float_list = scan_list "%f";;
+
+let test33 () =
+ scan_int_list (Scanning.from_string "[]") = [] &&
+ scan_int_list (Scanning.from_string "[ ]") = [] &&
+ scan_int_list (Scanning.from_string "[ 1 ]") = [1] &&
+ scan_int_list (Scanning.from_string "[ 1; 2; 3; 4 ]") = [1; 2; 3; 4] &&
+ scan_int_list (Scanning.from_string "[1;2;3;4;]") = [1; 2; 3; 4];;
+
+test (test33 ())
+;;
+
+let test34 () =
+ scan_string_list (Scanning.from_string "[]") = [] &&
+ scan_string_list (Scanning.from_string "[ ]") = [] &&
+ scan_string_list (Scanning.from_string "[ \"1\" ]") = ["1"] &&
+ scan_string_list
+ (Scanning.from_string "[\"1\"; \"2\"; \"3\"; \"4\"]") =
+ ["1"; "2"; "3"; "4"] &&
+ scan_string_list
+ (Scanning.from_string "[\"1\"; \"2\"; \"3\"; \"4\";]") =
+ ["1"; "2"; "3"; "4"];;
+
+test (test34 ())
+;;
+
+(* Using kscanf only.
+
+ Same as the preceding functional, except that we no more use format values
+ to scan items: we use scanners that scan elements of the list on the
+ fly.
+*)
+(* This version cannot handle empty lists!
+let rec scan_elems ib scan_elem accu =
+ scan_elem ib
+ (fun elem ->
+ let accu = elem :: accu in
+ kscanf ib (fun ib exc -> accu)
+ " %1[;] "
+ (function
+ | "" -> accu
+ | _ -> scan_elems ib scan_elem accu))
+;;
+*)
+
+(* We use [kscanf] with a [%r] format ! *)
+let rec scan_elems scan_elem accu ib =
+ kscanf ib (fun ib exc -> accu)
+ "%r"
+ (function ib ->
+ scan_elem ib
+ (function elem ->
+ let accu = elem :: accu in
+ bscanf ib
+ " %1[;] "
+ (function
+ | "" -> accu
+ | _ -> scan_elems scan_elem accu ib)))
+ (function l -> l)
+;;
+
+let scan_list scan_elem ib =
+ bscanf ib "[ " ();
+ let accu = scan_elems scan_elem [] ib in
+ bscanf ib " ]" ();
+ List.rev accu
+;;
+
+(* We may also try a version with only one format:
+ We also changed the type of [scan_elem] to partially apply it to its
+ ``natural'' continuation.
+let rec scan_elems scan_elem accu ib =
+ (* We use [kscanf], so that:
+ if the element reader fails, we can return the list of elements read so
+ far. *)
+ kscanf ib (fun ib exc -> accu)
+ (* The format string for [kscanf]: we read an element using [scan_elem],
+ then find a semi-colon if any, in order to decide if we stop reading
+ or go on with other elements. *)
+ "%r %1[;] "
+ (* The reader: once an element has been read it returns the new accu. *)
+ (scan_elem (function elem -> elem :: accu))
+ (fun accu s ->
+ (* Cannot find a semi-colon: no more elements to read. *)
+ if s = "" then accu
+ (* We found a semi-colon: go on with the new accu. *)
+ else scan_elems scan_elem accu ib)
+;;
+
+let scan_list scan_elem ib =
+ bscanf ib "[ %r ]" (scan_elems scan_elem []) List.rev
+;;
+
+(* For instance:
+let scan_float f ib = Scanf.bscanf ib "%f" f;;
+# scan_list scan_float;;
+- : Scanf.Scanning.scanbuf -> float list = <fun>
+*)
+
+(* The element scanner builder. *)
+let make_scan_elem fmt f ib = Scanf.bscanf ib fmt f;;
+
+(* Promote an element reader format to an element list reader. *)
+let list_scanner fmt = scan_list (make_scan_elem fmt);;
+
+let scan_float = make_scan_elem "%f";;
+
+scan_list scan_float;;
+
+list_scanner "%f";;
+- : Scanf.Scanning.scanbuf -> float list = <fun>
+*)
+
+(* The prototype of a [scan_elem] function for the generic [scan_list]
+ functional.
+ This [scan_elem] scans a floating point number. *)
+let scan_float ib = Scanf.bscanf ib "%f";;
+let scan_float_list = scan_list scan_float;;
+
+(* In the following list scanners, we directly give the [scan_elem] function
+ as an immediate function value argument to the polymorphic
+ [scan_list]. *)
+let scan_int_list = scan_list (fun ib -> Scanf.bscanf ib "%i");;
+let scan_string_list = scan_list (fun ib -> Scanf.bscanf ib "%S");;
+let scan_bool_list = scan_list (fun ib -> Scanf.bscanf ib "%B");;
+let scan_char_list = scan_list (fun ib -> Scanf.bscanf ib "%C");;
+
+(* [scan_list] is truely polymorphic: scanning a list of lists of items
+ is a one liner!
+
+ Here we scan list of lists of floats. *)
+let scan_float_list_list =
+ scan_list
+ (fun ib k -> k (scan_list (fun ib -> Scanf.bscanf ib "%f") ib))
+;;
+
+let scan_float_list_list =
+ scan_list
+ (fun ib k -> k (scan_list scan_float ib))
+;;
+
+let scan_float_list_list =
+ scan_list
+ (fun ib k -> k (scan_float_list ib))
+;;
+
+(* The killer way to define [scan_float_list_list]. *)
+(* let scan_float_list_list = scan_list scan_float_list;; *)
+
+let test340 () =
+ scan_float_list_list
+ (Scanning.from_string "[[1.0] ; []; [2.0; 3; 5.0; 6.];]") =
+ [[1.]; []; [2.; 3.; 5.; 6.]]
+;;
+
+(* A general scan_list_list functional. *)
+let scan_list_list scan_elems ib =
+ scan_list
+ (fun ib k -> k (scan_elems ib)) ib
+;;
+
+let scan_float_list_list = scan_list_list scan_float_list;;
+
+(* Programming with continuations :) *)
+let scan_float_item ib k = k (scan_float ib (fun x -> x));;
+let scan_float_list ib k = k (scan_list scan_float_item ib);;
+let scan_float_list_list ib k = k (scan_list scan_float_list ib);;
+
+(* Testing the %N format. *)
+let test35 () =
+ sscanf "" "%N" (fun x -> x) = 0 &&
+ sscanf "456" "%N" (fun x -> x) = 0 &&
+ sscanf "456" "%d%N" (fun x y -> x, y) = (456, 1) &&
+ sscanf " " "%N%s%N" (fun x s y -> x, s, y) = (0, "", 1)
+;;
+
+test (test340 () && test35 ())
+;;
+
+(* The prefered reader functionnals. *)
+
+(* To read a list as in OCaml (elements are ``blank + semicolon + blank''
+ separated, and the list is enclosed in brackets). *)
+let rec read_elems read_elem accu ib =
+ kscanf ib (fun ib exc -> accu)
+ "%r %1[;] "
+ (read_elem (function elem -> elem :: accu))
+ (fun accu s -> if s = "" then accu else read_elems read_elem accu ib)
+;;
+
+let read_list read_elem ib =
+ bscanf ib "[ %r ]" (read_elems read_elem []) List.rev
+;;
+
+(* The element reader builder. *)
+let make_read_elem fmt f ib = Scanf.bscanf ib fmt f;;
+
+(* Promote an element reader format to an element list reader. *)
+let scan_List fmt = read_list (make_read_elem fmt);;
+
+(* Example for list of floatting point numbers. *)
+(*
+scan_List "%f";;
+- : Scanf.Scanning.scanbuf -> float list = <fun>
+
+(* To read a list as a succession of elements separated by a blank. *)
+let rec read_elems read_elem accu ib =
+ kscanf ib (fun ib exc -> accu)
+ "%r "
+ (read_elem (function elem -> elem :: accu))
+ (fun accu -> read_elems read_elem accu ib)
+;;
+
+let read_list read_elem ib =
+ List.rev (read_elems read_elem [] ib)
+;;
+
+(* Promote an element reader format to an element list reader. *)
+let scan_list fmt = read_list (make_read_elem fmt);;
+
+scan_list "%f";;
+*)
+
+(* Testing the %n format. *)
+let test36 () =
+ sscanf "" "%n" (fun x -> x) = 0 &&
+ sscanf "456" "%n" (fun x -> x) = 0 &&
+ sscanf "456" "%d%n" (fun x y -> x, y) = (456, 3) &&
+ sscanf " " "%n%s%n" (fun x s y -> x, s, y) = (0, "", 0)
+;;
+
+test (test36 ())
+;;
+
+(* Weird tests to empty strings or formats. *)
+let test37 () =
+ sscanf "" "" true &&
+ sscanf "" "" (fun x -> x) 1 = 1 &&
+ sscanf "123" "" (fun x -> x) 1 = 1
+;;
+
+test (test37 ())
+;;
+
+(* Testing end of input condition. *)
+let test38 () =
+ sscanf "a" "a%!" true &&
+ sscanf "a" "a%!%!" true &&
+ sscanf " a" " a%!" true &&
+ sscanf "a " "a %!" true &&
+ sscanf "" "%!" true &&
+ sscanf " " " %!" true &&
+ sscanf "" " %!" true &&
+ sscanf "" " %!%!" true
+;;
+
+test (test38 ())
+;;
+
+(* Weird tests on empty buffers. *)
+let test39 () =
+ let is_empty_buff ib =
+ Scanning.beginning_of_input ib &&
+ Scanning.end_of_input ib in
+
+ let ib = Scanning.from_string "" in
+ is_empty_buff ib &&
+ (* Do it twice since testing empty buff could incorrectly
+ thraw an exception or wrongly change the beginning_of_input condition. *)
+ is_empty_buff ib
+;;
+
+test (test39 ())
+;;
+
+(* Testing ranges. *)
+let test40 () =
+ let s = "cba" in
+ let ib = Scanning.from_string s in
+ bscanf ib "%[^ab]%s%!" (fun s1 s2 -> s1 = "c" && s2 = "ba")
+;;
+
+test (test40 ())
+;;
+
+let test41 () =
+ let s = "cba" in
+ let ib = Scanning.from_string s in
+ bscanf ib "%[^abc]%[cba]%!" (fun s1 s2 -> s1 = "" && s2 = "cba")
+;;
+
+test (test41 ())
+;;
+
+let test42 () =
+ let s = "defcbaaghi" in
+ let ib = Scanning.from_string s in
+ bscanf ib "%[^abc]%[abc]%s%!" (fun s1 s2 s3 ->
+ s1 = "def" && s2 = "cbaa" && s3 = "ghi") &&
+ let ib = Scanning.from_string s in
+ bscanf ib "%s@\t" (fun s -> s = "defcbaaghi")
+;;
+
+test (test42 ())
+;;
+
+(* Testing end of file condition (bug found). *)
+let test43, test44 =
+ let s = "" in
+ let ib = Scanning.from_string s in
+ (fun () -> bscanf ib "%i%!" (fun i -> i)),
+ (fun () -> bscanf ib "%!%i" (fun i -> i))
+;;
+
+test_raises_this_exc End_of_file test43 () &&
+test_raises_this_exc End_of_file test44 ()
+;;
+
+(* Testing small range scanning (bug found once). *)
+let test45 () =
+ let s = "12.2" in
+ let ib = Scanning.from_string s in
+ bscanf ib "%[0-9].%[0-9]%s%!" (fun s1 s2 s3 ->
+ s1 = "12" && s2 = "2" && s3 = "")
+;;
+
+test (test45 ())
+;;
+
+(* Testing printing of meta formats. *)
+
+let test46, test47 =
+ (fun () ->
+ Printf.sprintf "%i %(%s%)."
+ 1 "spells one, %s" "in english"),
+ (fun () ->
+ Printf.sprintf "%i %{%s%}, %s."
+ 1 "spells one %s" "in english")
+;;
+
+test (test46 () = "1 spells one, in english.")
+;;
+test (test47 () = "1 %s, in english.")
+;;
+
+(* Testing scanning of meta formats. *)
+let test48 () =
+ (* Testing format_from_string. *)
+ let test_meta_read s fmt efmt = format_from_string s fmt = efmt in
+ (* Test if format %i is indeed read as %i. *)
+ let s, fmt = "%i", format_of_string "%i" in
+ test_meta_read s fmt fmt &&
+ (* Test if format %i is compatible with %d and indeed read as %i. *)
+ let s, fmt = "%i", format_of_string "%d" in
+ test_meta_read s fmt "%i" &&
+ (* Complex test of scanning a meta format specified in the scanner input
+ format string and extraction of its specification from a string. *)
+ sscanf "12 \"%i\"89 " "%i %{%d%}%s %!"
+ (fun i f s -> i = 12 && f = "%i" && s = "89") &&
+ (* Testing scanf format string replacement *)
+ let k s =
+ Scanf.sscanf s
+ "%(%f%)" (fun _fmt i -> i) in
+ k "\" : %1f\": 987654321" = 9.0 &&
+ k "\" : %2f\": 987654321" = 98.0 &&
+ k "\" : %3f\": 9.87654321" = 9.8 &&
+ k "\" : %4f\": 9.87654321" = 9.87 &&
+
+ let h s =
+ Scanf.sscanf s
+ "Read integers with %(%i%)" (fun _fmt i -> i) in
+ h "Read integers with \"%1d\"987654321" = 9 &&
+ h "Read integers with \"%2d\"987654321" = 98 &&
+ h "Read integers with \"%3u\"987654321" = 987 &&
+ h "Read integers with \"%4x\"987654321" = 39030 &&
+
+ let i s =
+ Scanf.sscanf s
+ "with %(%i %s%)" (fun _fmt amount currency -> amount, currency) in
+ i "with \" : %d %s\" : 21 euros" = (21, "euros") &&
+ i "with \" : %d %s\" : 987654321 dollars" = (987654321, "dollars") &&
+ i "with \" : %u %s\" : 54321 pounds" = (54321, "pounds") &&
+ i "with \" : %x %s\" : 321 yens" = (801, "yens") &&
+
+ let j s =
+ Scanf.sscanf s
+ "with %(%i %_s %s%)" (fun _fmt amount currency -> amount, currency) in
+ j "with \" : %1d %_s %s\" : 987654321 euros" = (9, "euros") &&
+ j "with \" : %2d %_s %s\" : 987654321 dollars" = (98, "dollars") &&
+ j "with \" : %3u %_s %s\" : 987654321 pounds" = (987, "pounds") &&
+ j "with \" : %4x %_s %s\" : 987654321 yens" = (39030, "yens")
+;;
+
+test (test48 ())
+;;
+
+(* Testing stoppers after ranges. *)
+let test49 () =
+ sscanf "as" "%[\\]" (fun s -> s = "") &&
+ sscanf "as" "%[\\]%s" (fun s t -> s = "" && t = "as") &&
+ sscanf "as" "%[\\]%s%!" (fun s t -> s = "" && t = "as") &&
+ sscanf "as" "%[a..z]" (fun s -> s = "a") &&
+ sscanf "as" "%[a-z]" (fun s -> s = "as") &&
+ sscanf "as" "%[a..z]%s" (fun s t -> s = "a" && t = "s") &&
+ sscanf "as" "%[a-z]%s" (fun s t -> s = "as" && t = "") &&
+ sscanf "-as" "%[-a-z]" (fun s -> s = "-as") &&
+ sscanf "-as" "%[-a-z]@s" (fun s -> s = "-a") &&
+ sscanf "-as" "-%[a]@s" (fun s -> s = "a") &&
+ sscanf "-asb" "-%[a]@sb%!" (fun s -> s = "a") &&
+ sscanf "-asb" "-%[a]@s%s" (fun s t -> s = "a" && t = "b")
+;;
+
+test (test49 ())
+;;
+
+(* Testing buffers defined via functions
+ + co-routines that read and write from the same buffers
+ + range chars and proper handling of \n
+ + the end of file condition. *)
+let next_char ob () =
+ let s = Buffer.contents ob in
+ let len = String.length s in
+ if len = 0 then raise End_of_file else
+ let c = s.[0] in
+ Buffer.clear ob;
+ Buffer.add_string ob (String.sub s 1 (len - 1));
+ c
+;;
+
+let send_string ob s =
+ Buffer.add_string ob s; Buffer.add_char ob '\n';;
+let send_int ob i = send_string ob (string_of_int i);;
+
+let rec reader =
+ let count = ref 0 in
+ (fun ib ob ->
+ if Scanf.Scanning.beginning_of_input ib then begin
+ count := 0; send_string ob "start"; writer ib ob end else
+ Scanf.bscanf ib "%[^\n]\n" (function
+ | "stop" -> send_string ob "stop"; writer ib ob
+ | s ->
+ let l = String.length s in
+ count := l + !count;
+ if !count >= 100 then begin
+ send_string ob "stop";
+ send_int ob !count
+ end else
+ send_int ob l;
+ writer ib ob))
+
+and writer ib ob =
+ Scanf.bscanf ib "%s\n" (function
+ | "start" -> send_string ob "Hello World!"; reader ib ob
+ | "stop" -> Scanf.bscanf ib "%i" (function i -> i)
+ | s -> send_int ob (int_of_string s); reader ib ob);;
+
+let go () =
+ let ob = Buffer.create 17 in
+ let ib = Scanf.Scanning.from_function (next_char ob) in
+ reader ib ob
+;;
+
+let test50 () = go () = 100;;
+
+test (test50 ())
+;;
+
+(* Simple tests may also fail!
+ Ensure this is not the case with the current version for module [Scanf]. *)
+let test51 () =
+ sscanf "Hello" "%s" id = "Hello" &&
+ sscanf "Hello\n" "%s\n" id = "Hello" &&
+ sscanf "Hello\n" "%s%s\n" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "") &&
+ sscanf "Hello\nWorld" "%s\n%s%!" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "World") &&
+ sscanf "Hello\nWorld!" "%s\n%s" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "World!") &&
+ sscanf "Hello\n" "%s@\n%s" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "") &&
+ sscanf "Hello \n" "%s@\n%s" (fun s1 s2 ->
+ s1 = "Hello " && s2 = "")
+;;
+
+test (test51 ())
+;;
+
+(* Tests that indeed the [%s@c] format works properly.
+ Also tests the difference between [\n] and [@\n] is correctly handled.
+ In particular, tests that if no [c] character can be found in the
+ input, then the token obtained for [%s@c] spreads to the end of
+ input. *)
+let test52 () =
+ sscanf "Hello\n" "%s@\n" id = "Hello" &&
+ sscanf "Hello" "%s@\n" id = "Hello" &&
+ sscanf "Hello" "%s%s@\n" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "") &&
+ sscanf "Hello\nWorld" "%s@\n%s%!" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "World") &&
+ sscanf "Hello\nWorld!" "%s@\n%s@\n" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "World!") &&
+ sscanf "Hello\n" "%s@\n%s" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "") &&
+ sscanf "Hello \n" "%s%s@\n" (fun s1 s2 ->
+ s1 = "Hello" && s2 = " ") &&
+sscanf "Hello \n" "%s%s%_1[ ]\n" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "") &&
+ sscanf "Hello \n" "%s%_1[ ]%s\n" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "") &&
+ sscanf "Hello\nWorld" "%s\n%s%!" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "World") &&
+ sscanf "Hello\nWorld!" "%s\n%s%!" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "World!") &&
+ sscanf "Hello\nWorld!" "%s\n%s@!%!" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "World") &&
+ (* PR#6791 *)
+ sscanf "Hello{foo}" "%s@{%s" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "foo}") &&
+ sscanf "Hello[foo]" "%s@[%s" (fun s1 s2 ->
+ s1 = "Hello" && s2 = "foo]")
+;;
+
+test (test52 ())
+;;
+
+(* Reading native, int32 and int64 numbers. *)
+let test53 () =
+ sscanf "123" "%nd" id = 123n &&
+ sscanf "124" "%nd" (fun i -> Nativeint.pred i = 123n) &&
+
+ sscanf "123" "%ld" id = 123l &&
+ sscanf "124" "%ld" (fun i -> Int32.succ i = 125l) &&
+
+ sscanf "123" "%Ld" id = 123L &&
+ sscanf "124" "%Ld" (fun i -> Int64.pred i = 123L)
+;;
+
+test (test53 ())
+;;
+
+(* Routines to create the file that tscanf uses as a testbed case. *)
+let create_tscanf_data ob lines =
+ let add_line (p, e) =
+ Buffer.add_string ob (Printf.sprintf "%S" p);
+ Buffer.add_string ob " -> ";
+ Buffer.add_string ob (Printf.sprintf "%S" e);
+ Buffer.add_string ob ";\n" in
+ List.iter add_line lines
+;;
+
+let write_tscanf_data_file fname lines =
+ let oc = open_out fname in
+ let ob = Buffer.create 42 in
+ create_tscanf_data ob lines;
+ Buffer.output_buffer oc ob;
+ close_out oc
+;;
+
+(* The tscanf testbed case file name. *)
+let tscanf_data_file = "tscanf_data";;
+(* The contents of the tscanf testbed case file. *)
+let tscanf_data_file_lines = [
+ "Objective", "Caml";
+]
+;;
+(* We write the tscanf testbed case file. *)
+write_tscanf_data_file tscanf_data_file tscanf_data_file_lines
+;;
+
+(* Then we verify that its contents is indeed correct:
+ the lines written into the [tscanf_data] file should be the same as the
+ lines read from it. *)
+
+(* Reading back tscanf_data_file_lines (hence, testing data file reading as
+ well). *)
+let get_lines fname =
+ let ib = Scanf.Scanning.from_file fname in
+ let l = ref [] in
+ try
+ while not (Scanf.Scanning.end_of_input ib) do
+ Scanf.bscanf ib " %S -> %S; " (fun x y ->
+ l := (x, y) :: !l)
+ done;
+ List.rev !l
+ with
+ | Scanf.Scan_failure s ->
+ failwith (Printf.sprintf "in file %s, %s" fname s)
+ | End_of_file ->
+ failwith (Printf.sprintf "in file %s, unexpected end of file" fname)
+;;
+
+(* Simply test that the list of lines read from the file is the list of lines
+ written to it!. *)
+let test54 () =
+ get_lines tscanf_data_file = tscanf_data_file_lines
+;;
+
+test (test54 ())
+;;
+
+(* Creating digests for files. *)
+let add_digest_ib ob ib =
+ let digest s = String.uppercase_ascii (Digest.to_hex (Digest.string s)) in
+ let scan_line ib f = Scanf.bscanf ib "%[^\n\r]\n" f in
+ let output_line_digest s =
+ Buffer.add_string ob s;
+ Buffer.add_char ob '#'; Buffer.add_string ob (digest s);
+ Buffer.add_char ob '\n' in
+ try while true do scan_line ib output_line_digest done; with
+ | End_of_file -> ()
+;;
+
+let digest_file fname =
+ let ib = Scanf.Scanning.from_file fname in
+ let ob = Buffer.create 42 in
+ add_digest_ib ob ib;
+ Buffer.contents ob
+;;
+
+let test55 () =
+ let ob = Buffer.create 42 in
+ let ib =
+ create_tscanf_data ob tscanf_data_file_lines;
+ let s = Buffer.contents ob in
+ Buffer.clear ob;
+ Scanning.from_string s in
+ let tscanf_data_file_lines_digest = add_digest_ib ob ib; Buffer.contents ob in
+ digest_file tscanf_data_file = tscanf_data_file_lines_digest
+;;
+
+test (test55 ())
+;;
+
+(* Testing the number of characters read. *)
+let test56 () =
+ let g s = Scanf.sscanf s "%d%n" (fun i n -> (i, n)) in
+ g "99" = (99, 2) &&
+ g "99 syntaxes all in a row" = (99, 2) &&
+ g "-20 degrees Celsius" = (-20, 3)
+;;
+
+test (test56 ())
+;;
+
+(* Testing the scanning of formats. *)
+let test57 () =
+ (* Testing format_from_string. *)
+ let test_format_scan s fmt efmt =
+ format_from_string s fmt = efmt in
+ (* Test if format %i is indeed read as %i. *)
+ let s, fmt = " %i ", format_of_string "%i" in
+ test_format_scan s fmt " %i " &&
+ (* Test if format %i is compatible with %d and indeed read as %i. *)
+ let s, fmt = "%i", format_of_string "%d" in
+ test_format_scan s fmt "%i" &&
+
+ let s, fmt =
+ "Read an int %i then a string %s.",
+ format_of_string "Spec%difi%scation" in
+ test_format_scan s fmt "Read an int %i then a string %s." &&
+
+ let s, fmt =
+ "Read an int %i then a string \"%s\".",
+ format_of_string "Spec%difi%Scation" in
+ test_format_scan s fmt "Read an int %i then a string \"%s\"." &&
+
+ let s, fmt =
+ "Read an int %i then a string \"%s\".",
+ format_of_string "Spec%difi%scation" in
+ test_format_scan s fmt "Read an int %i then a string \"%s\"." &&
+
+ (* Complex test of scanning a meta format specified in the scanner input
+ format string and extraction of its specification from a string. *)
+ sscanf "12 \"%i\"89 " "%i %{%d%}%s %!"
+ (fun i f s -> i = 12 && f = "%i" && s = "89")
+;;
+
+test (test57 ())
+;;
+
+let test58 () =
+ sscanf "string1%string2" "%s@%%s" id = "string1"
+ && sscanf "string1%string2" "%s@%%%s" (^) = "string1string2"
+ && sscanf "string1@string2" "%[a-z0-9]@%s" (^) = "string1string2"
+ && sscanf "string1@%string2" "%[a-z0-9]%@%%%s" (^) = "string1string2"
+;;
+
+test (test58 ())
+;;
+
+(* skip test number "59" which is commented below *)
+let () = test (true);;
+(*
+let test59 () =
+;;
+
+test (test59 ())
+;;
+*)
+
+(* To be continued ...
+(* Trying to scan records. *)
+let rec scan_fields ib scan_field accu =
+ kscanf ib (fun ib exc -> accu)
+ scan_field
+ (fun i ->
+ let accu = i :: accu in
+ kscanf ib (fun ib exc -> accu)
+ " %1[;] "
+ (fun s ->
+ if s = "" then accu else scan_fields ib scan_field accu))
+;;
+
+let scan_record scan_field ib =
+ bscanf ib "{ " ();
+ let accu = scan_fields ib scan_field [] in
+ bscanf ib " }" ();
+ List.rev accu
+;;
+
+let scan_field ib =
+ bscanf ib "%s = %[^;]" (fun finame ficont -> finame, ficont);;
+*)
+
+(* testing formats that do not consume their input *)
+let test60 () =
+ sscanf "abc" "%0c%0c%c%n" (fun c1 c2 c3 n ->
+ c1 = 'a' && c2 = 'a' && c3 = 'a' && n = 1)
+ &&
+ sscanf "abc" "%0s%s" (fun s1 s2 -> s1 = "" && s2 = "abc")
+ &&
+ sscanf "abc" "%1s%s" (fun s1 s2 -> s1 = "a" && s2 = "bc")
+;;
+
+test (test60 ());
diff --git a/testsuite/tests/lib-scanf/tscanf.reference b/testsuite/tests/lib-scanf/tscanf.reference
new file mode 100644
index 0000000000..5b2859cb86
--- /dev/null
+++ b/testsuite/tests/lib-scanf/tscanf.reference
@@ -0,0 +1,2 @@
+ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
+All tests succeeded.
diff --git a/testsuite/tests/lib-set/Makefile b/testsuite/tests/lib-set/Makefile
new file mode 100644
index 0000000000..299656b246
--- /dev/null
+++ b/testsuite/tests/lib-set/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-set/testmap.ml b/testsuite/tests/lib-set/testmap.ml
new file mode 100644
index 0000000000..8eee5e5f24
--- /dev/null
+++ b/testsuite/tests/lib-set/testmap.ml
@@ -0,0 +1,134 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+module M = Map.Make(struct type t = int let compare (x:t) y = compare x y end)
+
+let img x m = try Some(M.find x m) with Not_found -> None
+
+let testvals = [0;1;2;3;4;5;6;7;8;9]
+
+let check msg cond =
+ if not (List.for_all cond testvals) then
+ Printf.printf "Test %s FAILED\n%!" msg
+
+let checkbool msg b =
+ if not b then
+ Printf.printf "Test %s FAILED\n%!" msg
+
+let uncurry (f: 'a -> 'b -> 'c) (x, y: 'a * 'b) : 'c = f x y
+
+let test x v s1 s2 =
+
+ checkbool "is_empty"
+ (M.is_empty s1 = List.for_all (fun i -> img i s1 = None) testvals);
+
+ check "mem"
+ (fun i -> M.mem i s1 = (img i s1 <> None));
+
+ check "add"
+ (let s = M.add x v s1 in
+ fun i -> img i s = (if i = x then Some v else img i s1));
+
+ check "singleton"
+ (let s = M.singleton x v in
+ fun i -> img i s = (if i = x then Some v else None));
+
+ check "remove"
+ (let s = M.remove x s1 in
+ fun i -> img i s = (if i = x then None else img i s1));
+
+ check "merge-union"
+ (let f _ o1 o2 =
+ match o1, o2 with
+ | Some v1, Some v2 -> Some (v1 +. v2)
+ | None, _ -> o2
+ | _, None -> o1 in
+ let s = M.merge f s1 s2 in
+ fun i -> img i s = f i (img i s1) (img i s2));
+
+ check "merge-inter"
+ (let f _ o1 o2 =
+ match o1, o2 with
+ | Some v1, Some v2 -> Some (v1 -. v2)
+ | _, _ -> None in
+ let s = M.merge f s1 s2 in
+ fun i -> img i s = f i (img i s1) (img i s2));
+
+ checkbool "bindings"
+ (let rec extract = function
+ | [] -> []
+ | hd :: tl ->
+ match img hd s1 with
+ | None -> extract tl
+ | Some v ->(hd, v) :: extract tl in
+ M.bindings s1 = extract testvals);
+
+ checkbool "for_all"
+ (let p x y = x mod 2 = 0 in
+ M.for_all p s1 = List.for_all (uncurry p) (M.bindings s1));
+
+ checkbool "exists"
+ (let p x y = x mod 3 = 0 in
+ M.exists p s1 = List.exists (uncurry p) (M.bindings s1));
+
+ checkbool "filter"
+ (let p x y = x >= 3 && x <= 6 in
+ M.bindings(M.filter p s1) = List.filter (uncurry p) (M.bindings s1));
+
+ checkbool "partition"
+ (let p x y = x >= 3 && x <= 6 in
+ let (st,sf) = M.partition p s1
+ and (lt,lf) = List.partition (uncurry p) (M.bindings s1) in
+ M.bindings st = lt && M.bindings sf = lf);
+
+ checkbool "cardinal"
+ (M.cardinal s1 = List.length (M.bindings s1));
+
+ checkbool "min_binding"
+ (try
+ let (k,v) = M.min_binding s1 in
+ img k s1 = Some v && M.for_all (fun i _ -> k <= i) s1
+ with Not_found ->
+ M.is_empty s1);
+
+ checkbool "max_binding"
+ (try
+ let (k,v) = M.max_binding s1 in
+ img k s1 = Some v && M.for_all (fun i _ -> k >= i) s1
+ with Not_found ->
+ M.is_empty s1);
+
+ checkbool "choose"
+ (try
+ let (x,v) = M.choose s1 in img x s1 = Some v
+ with Not_found ->
+ M.is_empty s1);
+
+ check "split"
+ (let (l, p, r) = M.split x s1 in
+ fun i ->
+ if i < x then img i l = img i s1
+ else if i > x then img i r = img i s1
+ else p = img i s1)
+
+let rkey() = Random.int 10
+
+let rdata() = Random.float 1.0
+
+let rmap() =
+ let s = ref M.empty in
+ for i = 1 to Random.int 10 do s := M.add (rkey()) (rdata()) !s done;
+ !s
+
+let _ =
+ Random.init 42;
+ for i = 1 to 25000 do test (rkey()) (rdata()) (rmap()) (rmap()) done
diff --git a/testsuite/tests/lib-set/testmap.reference b/testsuite/tests/lib-set/testmap.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/lib-set/testmap.reference
diff --git a/testsuite/tests/lib-set/testset.ml b/testsuite/tests/lib-set/testset.ml
new file mode 100644
index 0000000000..5881332061
--- /dev/null
+++ b/testsuite/tests/lib-set/testset.ml
@@ -0,0 +1,170 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+module S = Set.Make(struct type t = int let compare (x:t) y = compare x y end)
+
+let testvals = [0;1;2;3;4;5;6;7;8;9]
+
+let check msg cond =
+ if not (List.for_all cond testvals) then
+ Printf.printf "Test %s FAILED\n%!" msg
+
+let checkbool msg b =
+ if not b then
+ Printf.printf "Test %s FAILED\n%!" msg
+
+let normalize_cmp c =
+ if c = 0 then 0 else if c > 0 then 1 else -1
+
+let test x s1 s2 =
+
+ checkbool "is_empty"
+ (S.is_empty s1 = List.for_all (fun i -> not (S.mem i s1)) testvals);
+
+ check "add"
+ (let s = S.add x s1 in
+ fun i -> S.mem i s = (S.mem i s1 || i = x));
+
+ check "singleton"
+ (let s = S.singleton x in
+ fun i -> S.mem i s = (i = x));
+
+ check "remove"
+ (let s = S.remove x s1 in
+ fun i -> S.mem i s = (S.mem i s1 && i <> x));
+
+ check "union"
+ (let s = S.union s1 s2 in
+ fun i -> S.mem i s = (S.mem i s1 || S.mem i s2));
+
+ check "inter"
+ (let s = S.inter s1 s2 in
+ fun i -> S.mem i s = (S.mem i s1 && S.mem i s2));
+
+ check "diff"
+ (let s = S.diff s1 s2 in
+ fun i -> S.mem i s = (S.mem i s1 && not (S.mem i s2)));
+
+ checkbool "elements"
+ (S.elements s1 = List.filter (fun i -> S.mem i s1) testvals);
+
+ checkbool "compare"
+ (normalize_cmp (S.compare s1 s2)
+ = normalize_cmp (compare (S.elements s1) (S.elements s2)));
+
+ checkbool "equal"
+ (S.equal s1 s2 = (S.elements s1 = S.elements s2));
+
+ check "subset"
+ (let b = S.subset s1 s2 in
+ fun i -> if b && S.mem i s1 then S.mem i s2 else true);
+
+ checkbool "subset2"
+ (let b = S.subset s1 s2 in
+ b || not (S.is_empty (S.diff s1 s2)));
+
+ checkbool "for_all"
+ (let p x = x mod 2 = 0 in
+ S.for_all p s1 = List.for_all p (S.elements s1));
+
+ checkbool "exists"
+ (let p x = x mod 3 = 0 in
+ S.exists p s1 = List.exists p (S.elements s1));
+
+ checkbool "filter"
+ (let p x = x >= 3 && x <= 6 in
+ S.elements(S.filter p s1) = List.filter p (S.elements s1));
+
+ checkbool "partition"
+ (let p x = x >= 3 && x <= 6 in
+ let (st,sf) = S.partition p s1
+ and (lt,lf) = List.partition p (S.elements s1) in
+ S.elements st = lt && S.elements sf = lf);
+
+ checkbool "cardinal"
+ (S.cardinal s1 = List.length (S.elements s1));
+
+ checkbool "min_elt"
+ (try
+ let m = S.min_elt s1 in
+ S.mem m s1 && S.for_all (fun i -> m <= i) s1
+ with Not_found ->
+ S.is_empty s1);
+
+ checkbool "max_elt"
+ (try
+ let m = S.max_elt s1 in
+ S.mem m s1 && S.for_all (fun i -> m >= i) s1
+ with Not_found ->
+ S.is_empty s1);
+
+ checkbool "choose"
+ (try
+ let x = S.choose s1 in S.mem x s1
+ with Not_found ->
+ S.is_empty s1);
+
+ check "split"
+ (let (l, p, r) = S.split x s1 in
+ fun i ->
+ if i < x then S.mem i l = S.mem i s1
+ else if i > x then S.mem i r = S.mem i s1
+ else p = S.mem i s1)
+
+let relt() = Random.int 10
+
+let rset() =
+ let s = ref S.empty in
+ for i = 1 to Random.int 10 do s := S.add (relt()) !s done;
+ !s
+
+let _ =
+ Random.init 42;
+ for i = 1 to 25000 do test (relt()) (rset()) (rset()) done
+
+let () =
+ (* #6645: check that adding an element to set that already contains
+ it doesn't allocate and return the original set. *)
+ let s1 = ref S.empty in
+ for i = 1 to 10 do s1 := S.add i !s1 done;
+ let s2 = ref !s1 in
+
+ let a0 = Gc.allocated_bytes () in
+ let a1 = Gc.allocated_bytes () in
+ for i = 1 to 10 do s2 := S.add i !s2 done;
+ let a2 = Gc.allocated_bytes () in
+
+ assert (!s2 == !s1);
+ assert(a2 -. a1 = a1 -. a0)
+
+let () =
+ (* check that removing an element from a set that is not present in this set
+ (1) doesn't allocate and (2) return the original set *)
+ let s1 = ref S.empty in
+ for i = 1 to 10 do s1 := S.add i !s1 done;
+ let s2 = ref !s1 in
+
+ let a0 = Gc.allocated_bytes () in
+ let a1 = Gc.allocated_bytes () in
+ for i = 11 to 30 do s2 := S.remove i !s2 done;
+ let a2 = Gc.allocated_bytes () in
+
+ assert (!s2 == !s1);
+ assert(a2 -. a1 = a1 -. a0)
+
+let () =
+ (* check that filtering a set where all elements are satisfied by
+ the given predicate return the original set *)
+ let s1 = ref S.empty in
+ for i = 1 to 10 do s1 := S.add i !s1 done;
+ let s2 = S.filter (fun e -> e >= 0) !s1 in
+ assert (s2 == !s1)
diff --git a/testsuite/tests/lib-set/testset.reference b/testsuite/tests/lib-set/testset.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/lib-set/testset.reference
diff --git a/testsuite/tests/lib-str/Makefile b/testsuite/tests/lib-str/Makefile
new file mode 100644
index 0000000000..6ae7266b0c
--- /dev/null
+++ b/testsuite/tests/lib-str/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+LIBRARIES=str
+ADD_COMPFLAGS=-I $(OTOPDIR)/otherlibs/str
+LD_PATH=$(TOPDIR)/otherlibs/str
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-str/t01.ml b/testsuite/tests/lib-str/t01.ml
new file mode 100644
index 0000000000..1f9ebd2426
--- /dev/null
+++ b/testsuite/tests/lib-str/t01.ml
@@ -0,0 +1,1075 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+
+let build_result ngroups input =
+ let res = Array.make (ngroups + 1) "~" in
+ for i = 0 to ngroups do
+ try
+ res.(i) <- Str.matched_group i input
+ with Not_found -> ()
+ done;
+ res
+
+let search_forward re ng input start =
+ try
+ ignore(Str.search_forward re input start);
+ build_result ng input
+ with Not_found ->
+ [||]
+
+let search_backward re ng input start =
+ try
+ ignore(Str.search_backward re input start);
+ build_result ng input
+ with Not_found ->
+ [||]
+
+let partial_match re ng input start =
+ if Str.string_partial_match re input start
+ then build_result ng input
+ else [||]
+
+let start_test msg =
+ print_newline(); printf "%s\n " msg
+
+let num_failures = ref 0
+
+let test res1 res2 =
+ if res1 = res2
+ then print_char '.'
+ else begin print_string " FAIL "; incr num_failures end
+
+let test_search_forward r ng s exp =
+ test (search_forward r ng s 0) exp
+
+let test_search_backward r ng s exp =
+ test (search_backward r ng s (String.length s)) exp
+
+let test_partial_match r ng s exp =
+ test (partial_match r ng s 0) exp
+
+let end_test () =
+ print_newline();
+ if !num_failures = 0 then
+ printf "All tests passed\n"
+ else begin
+ printf "TEST FAILED: %d failure(s)\n" !num_failures;
+ exit 2
+ end
+
+let automated_test() =
+
+ (** Forward searches *)
+ start_test "Search for /the quick brown fox/";
+ let r = Str.regexp "the quick brown fox" in
+ let n = 0 in
+ test_search_forward r n "the quick brown fox"
+ [|"the quick brown fox"|];
+ test_search_forward r n "What do you know about the quick brown fox?"
+ [|"the quick brown fox"|];
+ test_search_forward r n "The quick brown FOX"
+ [||];
+ test_search_forward r n "What do you know about THE QUICK BROWN FOX?"
+ [||];
+
+ start_test "Search for /the quick brown fox/ (case-insensitive)";
+ let r = Str.regexp_case_fold "the quick brown fox" in
+ let n = 0 in
+ test_search_forward r n "the quick brown fox"
+ [|"the quick brown fox"|];
+ test_search_forward r n "What do you know about the quick brown fox?"
+ [|"the quick brown fox"|];
+ test_search_forward r n "The quick brown FOX"
+ [|"The quick brown FOX"|];
+ test_search_forward r n "What do you know about THE QUICK BROWN FOX?"
+ [|"THE QUICK BROWN FOX"|];
+ test_search_forward r n "The slow white snail"
+ [||];
+
+ start_test "Search for /a*abc?xyz+pqrrrabbb*xyyyyy?pq?q?q?q?q?q?AB*zz/";
+ let r = Str.regexp "a*abc?xyz+pqrrrabbb*xyyyyy?pq?q?q?q?q?q?AB*zz" in
+ let n = 0 in
+ test_search_forward r n "abxyzpqrrrabbxyyyypqAzz"
+ [|"abxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "abxyzpqrrrabbxyyyypqAzz"
+ [|"abxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aabxyzpqrrrabbxyyyypqAzz"
+ [|"aabxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaabxyzpqrrrabbxyyyypqAzz"
+ [|"aaabxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaaabxyzpqrrrabbxyyyypqAzz"
+ [|"aaaabxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "abcxyzpqrrrabbxyyyypqAzz"
+ [|"abcxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aabcxyzpqrrrabbxyyyypqAzz"
+ [|"aabcxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypAzz"
+ [|"aaabcxyzpqrrrabbxyyyypAzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypqAzz"
+ [|"aaabcxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypqqAzz"
+ [|"aaabcxyzpqrrrabbxyyyypqqAzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypqqqAzz"
+ [|"aaabcxyzpqrrrabbxyyyypqqqAzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypqqqqAzz"
+ [|"aaabcxyzpqrrrabbxyyyypqqqqAzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypqqqqqAzz"
+ [|"aaabcxyzpqrrrabbxyyyypqqqqqAzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypqqqqqqAzz"
+ [|"aaabcxyzpqrrrabbxyyyypqqqqqqAzz"|];
+ test_search_forward r n "aaaabcxyzpqrrrabbxyyyypqAzz"
+ [|"aaaabcxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "abxyzzpqrrrabbxyyyypqAzz"
+ [|"abxyzzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aabxyzzzpqrrrabbxyyyypqAzz"
+ [|"aabxyzzzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaabxyzzzzpqrrrabbxyyyypqAzz"
+ [|"aaabxyzzzzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaaabxyzzzzpqrrrabbxyyyypqAzz"
+ [|"aaaabxyzzzzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "abcxyzzpqrrrabbxyyyypqAzz"
+ [|"abcxyzzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aabcxyzzzpqrrrabbxyyyypqAzz"
+ [|"aabcxyzzzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaabcxyzzzzpqrrrabbxyyyypqAzz"
+ [|"aaabcxyzzzzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaaabcxyzzzzpqrrrabbxyyyypqAzz"
+ [|"aaaabcxyzzzzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "aaaabcxyzzzzpqrrrabbbxyyyypqAzz"
+ [|"aaaabcxyzzzzpqrrrabbbxyyyypqAzz"|];
+ test_search_forward r n "aaaabcxyzzzzpqrrrabbbxyyyyypqAzz"
+ [|"aaaabcxyzzzzpqrrrabbbxyyyyypqAzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypABzz"
+ [|"aaabcxyzpqrrrabbxyyyypABzz"|];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypABBzz"
+ [|"aaabcxyzpqrrrabbxyyyypABBzz"|];
+ test_search_forward r n ">>>aaabxyzpqrrrabbxyyyypqAzz"
+ [|"aaabxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n ">aaaabxyzpqrrrabbxyyyypqAzz"
+ [|"aaaabxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n ">>>>abcxyzpqrrrabbxyyyypqAzz"
+ [|"abcxyzpqrrrabbxyyyypqAzz"|];
+ test_search_forward r n "abxyzpqrrabbxyyyypqAzz"
+ [||];
+ test_search_forward r n "abxyzpqrrrrabbxyyyypqAzz"
+ [||];
+ test_search_forward r n "abxyzpqrrrabxyyyypqAzz"
+ [||];
+ test_search_forward r n "aaaabcxyzzzzpqrrrabbbxyyyyyypqAzz"
+ [||];
+ test_search_forward r n "aaaabcxyzzzzpqrrrabbbxyyypqAzz"
+ [||];
+ test_search_forward r n "aaabcxyzpqrrrabbxyyyypqqqqqqqAzz"
+ [||];
+
+ start_test "Search for /^abc\\(abc\\)?zz/";
+ let r = Str.regexp "^abc\\(abc\\)?zz" in
+ let n = 1 in
+ test_search_forward r n "abczz"
+ [|"abczz"; "~"|];
+ test_search_forward r n "abcabczz"
+ [|"abcabczz"; "abc"|];
+ test_search_forward r n "zz"
+ [||];
+ test_search_forward r n "abcabcabczz"
+ [||];
+ test_search_forward r n ">>abczz"
+ [||];
+
+ start_test "Search for /^\\(b+\\|a\\)\\(b+\\|a\\)?c/";
+ let r = Str.regexp "^\\(b+\\|a\\)\\(b+\\|a\\)?c" in
+ let n = 2 in
+ test_search_forward r n "bc"
+ [|"bc"; "b"; "~"|];
+ test_search_forward r n "bbc"
+ [|"bbc"; "bb"; "~"|];
+ test_search_forward r n "bbbc"
+ [|"bbbc"; "bbb"; "~"|];
+ test_search_forward r n "bac"
+ [|"bac"; "b"; "a"|];
+ test_search_forward r n "bbac"
+ [|"bbac"; "bb"; "a"|];
+ test_search_forward r n "aac"
+ [|"aac"; "a"; "a"|];
+ test_search_forward r n "abbbbbbbbbbbc"
+ [|"abbbbbbbbbbbc"; "a"; "bbbbbbbbbbb"|];
+ test_search_forward r n "bbbbbbbbbbbac"
+ [|"bbbbbbbbbbbac"; "bbbbbbbbbbb"; "a"|];
+ test_search_forward r n "aaac"
+ [||];
+ test_search_forward r n "abbbbbbbbbbbac"
+ [||];
+
+ start_test "Search for /r\\(\\(g*\\|k\\)y?\\)*A/";
+ let r = Str.regexp "r\\(\\(g*\\|k\\)y?\\)*A" in
+ let n = 2 in
+ test_search_forward r n "ArA"
+ [|"rA"; "~"; "~"|];
+ test_search_forward r n "ArkA"
+ [|"rkA"; "k"; "k"|];
+ test_search_forward r n "AryA"
+ [|"ryA"; "y"; ""|];
+ test_search_forward r n "ArgggkyggkA"
+ [|"rgggkyggkA"; "k"; "k"|];
+
+ start_test "Search for /A\\(\\(t\\|v\\)\\(q?\\|n\\)\\)*A/";
+ let r = Str.regexp "A\\(\\(t\\|v\\)\\(q?\\|n\\)\\)*A" in
+ let n = 3 in
+ test_search_forward r n "AvA"
+ [|"AvA"; "v"; "v"; ""|];
+
+ start_test "Search for /A\\(\\(b\\(\\(d\\|l*\\)?\\|w\\)\\)*a\\)A/";
+ let r = Str.regexp "A\\(\\(b\\(\\(d\\|l*\\)?\\|w\\)\\)*a\\)A" in
+ let n = 4 in
+ test_search_forward r n "AbbaA"
+ [|"AbbaA"; "bba"; "b"; ""; ""|];
+
+ start_test "Search for /\\(\\|f\\)*x/";
+ let r = Str.regexp "\\(\\|f\\)*x" in
+ let n = 1 in
+ test_search_forward r n "abcd"
+ [||];
+ test_search_forward r n "fffff"
+ [||];
+ test_search_forward r n "fffxab"
+ [|"fffx"; "f"|];
+ test_search_forward r n "zzzxab"
+ [|"x"; "~"|];
+
+ start_test "Search for /\\(\\|f\\)+x/";
+ let r = Str.regexp "\\(\\|f\\)+x" in
+ let n = 1 in
+ test_search_forward r n "abcd"
+ [||];
+ test_search_forward r n "fffff"
+ [||];
+ test_search_forward r n "fffxab"
+ [|"fffx"; "f"|];
+ test_search_forward r n "zzzxab"
+ [|"x"; ""|];
+
+ start_test "Search for /A\\(.?\\)*A/";
+ let r = Str.regexp "A\\(.?\\)*A" in
+ let n = 1 in
+ test_search_forward r n "AA"
+ [|"AA"; "~"|];
+ test_search_forward r n "AAA"
+ [|"AAA"; "A"|];
+ test_search_forward r n "AbA"
+ [|"AbA"; "b"|];
+ test_search_forward r n "A"
+ [||];
+
+ start_test "Search for /\\([ab]*\\)\\1+c/";
+ let r = Str.regexp "\\([ab]*\\)\\1+c" in
+ let n = 1 in
+ test_search_forward r n "abababc"
+ [| "abababc"; "ab" |];
+ test_search_forward r n "abbc"
+ [| "bbc"; "b" |];
+ test_search_forward r n "abc"
+ [| "c"; "" |];
+
+ start_test "Search for /^\\(\\(b+\\|a\\)\\(b+\\|a\\)?\\)?bc/";
+ let r = Str.regexp "^\\(\\(b+\\|a\\)\\(b+\\|a\\)?\\)?bc" in
+ let n = 3 in
+ test_search_forward r n "bbc"
+ [|"bbc"; "b"; "b"; "~"|];
+
+ start_test "Search for /^\\(\\(b*\\|ba\\)\\(b*\\|ba\\)?\\)?bc/";
+ let r = Str.regexp "^\\(\\(b*\\|ba\\)\\(b*\\|ba\\)?\\)?bc" in
+ let n = 3 in
+ test_search_forward r n "babc"
+ [|"babc"; "ba"; ""; "ba"|];
+ test_search_forward r n "bbabc"
+ [|"bbabc"; "bba"; "b"; "ba"|];
+ test_search_forward r n "bababc"
+ [|"bababc"; "baba"; "ba"; "ba"|];
+ test_search_forward r n "bababbc"
+ [||];
+ test_search_forward r n "babababc"
+ [||];
+
+ start_test "Search for /[^a]/";
+ let r = Str.regexp "[^a]" in
+ let n = 0 in
+ test_search_forward r n "athing" [|"t"|];
+ test_search_forward r n "Athing" [|"A"|];
+
+ start_test "Search for /[^a]/ (case-insensitive)";
+ let r = Str.regexp_case_fold "[^a]" in
+ let n = 0 in
+ test_search_forward r n "athing" [|"t"|];
+ test_search_forward r n "Athing" [|"t"|];
+
+ start_test "Search for /^[]abcde]/";
+ let r = Str.regexp "^[]abcde]" in
+ let n = 0 in
+ test_search_forward r n "athing"
+ [|"a"|];
+ test_search_forward r n "bthing"
+ [|"b"|];
+ test_search_forward r n "]thing"
+ [|"]"|];
+ test_search_forward r n "cthing"
+ [|"c"|];
+ test_search_forward r n "dthing"
+ [|"d"|];
+ test_search_forward r n "ething"
+ [|"e"|];
+ test_search_forward r n "fthing"
+ [||];
+ test_search_forward r n "[thing"
+ [||];
+ test_search_forward r n "\\\\thing"
+ [||];
+
+ start_test "Search for /^[]cde]/";
+ let r = Str.regexp "^[]cde]" in
+ let n = 0 in
+ test_search_forward r n "]thing"
+ [|"]"|];
+ test_search_forward r n "cthing"
+ [|"c"|];
+ test_search_forward r n "dthing"
+ [|"d"|];
+ test_search_forward r n "ething"
+ [|"e"|];
+ test_search_forward r n "athing"
+ [||];
+ test_search_forward r n "fthing"
+ [||];
+
+ start_test "Search for /^[^]abcde]/";
+ let r = Str.regexp "^[^]abcde]" in
+ let n = 0 in
+ test_search_forward r n "fthing"
+ [|"f"|];
+ test_search_forward r n "[thing"
+ [|"["|];
+ test_search_forward r n "\\\\thing"
+ [|"\\"|];
+ test_search_forward r n "athing"
+ [||];
+ test_search_forward r n "bthing"
+ [||];
+ test_search_forward r n "]thing"
+ [||];
+ test_search_forward r n "cthing"
+ [||];
+ test_search_forward r n "dthing"
+ [||];
+ test_search_forward r n "ething"
+ [||];
+
+ start_test "Search for /^[^]cde]/";
+ let r = Str.regexp "^[^]cde]" in
+ let n = 0 in
+ test_search_forward r n "athing"
+ [|"a"|];
+ test_search_forward r n "fthing"
+ [|"f"|];
+ test_search_forward r n "]thing"
+ [||];
+ test_search_forward r n "cthing"
+ [||];
+ test_search_forward r n "dthing"
+ [||];
+ test_search_forward r n "ething"
+ [||];
+
+ start_test "Search for /^ÿ/";
+ let r = Str.regexp "^ÿ" in
+ let n = 0 in
+ test_search_forward r n "ÿ"
+ [|"ÿ"|];
+
+ start_test "Search for /^[0-9]+$/";
+ let r = Str.regexp "^[0-9]+$" in
+ let n = 0 in
+ test_search_forward r n "0"
+ [|"0"|];
+ test_search_forward r n "1"
+ [|"1"|];
+ test_search_forward r n "2"
+ [|"2"|];
+ test_search_forward r n "3"
+ [|"3"|];
+ test_search_forward r n "4"
+ [|"4"|];
+ test_search_forward r n "5"
+ [|"5"|];
+ test_search_forward r n "6"
+ [|"6"|];
+ test_search_forward r n "7"
+ [|"7"|];
+ test_search_forward r n "8"
+ [|"8"|];
+ test_search_forward r n "9"
+ [|"9"|];
+ test_search_forward r n "10"
+ [|"10"|];
+ test_search_forward r n "100"
+ [|"100"|];
+ test_search_forward r n "abc"
+ [||];
+
+ start_test "Search for /^.*nter/";
+ let r = Str.regexp "^.*nter" in
+ let n = 0 in
+ test_search_forward r n "enter"
+ [|"enter"|];
+ test_search_forward r n "inter"
+ [|"inter"|];
+ test_search_forward r n "uponter"
+ [|"uponter"|];
+
+ start_test "Search for /^xxx[0-9]+$/";
+ let r = Str.regexp "^xxx[0-9]+$" in
+ let n = 0 in
+ test_search_forward r n "xxx0"
+ [|"xxx0"|];
+ test_search_forward r n "xxx1234"
+ [|"xxx1234"|];
+ test_search_forward r n "xxx"
+ [||];
+
+ start_test "Search for /^.+[0-9][0-9][0-9]$/";
+ let r = Str.regexp "^.+[0-9][0-9][0-9]$" in
+ let n = 0 in
+ test_search_forward r n "x123"
+ [|"x123"|];
+ test_search_forward r n "xx123"
+ [|"xx123"|];
+ test_search_forward r n "123456"
+ [|"123456"|];
+ test_search_forward r n "123"
+ [||];
+ test_search_forward r n "x123x"
+ [||];
+
+ start_test "Search for /^\\([^!]+\\)!\\(.+\\)=apquxz\\.ixr\\.zzz\\.ac\\.uk$/";
+ let r = Str.regexp "^\\([^!]+\\)!\\(.+\\)=apquxz\\.ixr\\.zzz\\.ac\\.uk$" in
+ let n = 2 in
+ test_search_forward r n "abc!pqr=apquxz.ixr.zzz.ac.uk"
+ [|"abc!pqr=apquxz.ixr.zzz.ac.uk"; "abc"; "pqr"|];
+ test_search_forward r n "!pqr=apquxz.ixr.zzz.ac.uk"
+ [||];
+ test_search_forward r n "abc!=apquxz.ixr.zzz.ac.uk"
+ [||];
+ test_search_forward r n "abc!pqr=apquxz:ixr.zzz.ac.uk"
+ [||];
+ test_search_forward r n "abc!pqr=apquxz.ixr.zzz.ac.ukk"
+ [||];
+
+ start_test "Search for /\\([0-9a-f:]+\\)$/";
+ let r = Str.regexp_case_fold "\\([0-9a-f:]+\\)$" in
+ let n = 1 in
+ test_search_forward r n "0abc"
+ [|"0abc"; "0abc"|];
+ test_search_forward r n "abc"
+ [|"abc"; "abc"|];
+ test_search_forward r n "fed"
+ [|"fed"; "fed"|];
+ test_search_forward r n "E"
+ [|"E"; "E"|];
+ test_search_forward r n "::"
+ [|"::"; "::"|];
+ test_search_forward r n "5f03:12C0::932e"
+ [|"5f03:12C0::932e"; "5f03:12C0::932e"|];
+ test_search_forward r n "fed def"
+ [|"def"; "def"|];
+ test_search_forward r n "Any old stuff"
+ [|"ff"; "ff"|];
+ test_search_forward r n "0zzz"
+ [||];
+ test_search_forward r n "gzzz"
+ [||];
+ test_search_forward r n "fed "
+ [||];
+ test_search_forward r n "Any old rubbish"
+ [||];
+
+ start_test "Search for /^[a-z0-9][a-z0-9-]*\\(\\.[a-z0-9][A-Z0-9-]*\\)*\\.$/";
+ let r =
+ Str.regexp_case_fold "^[a-z0-9][a-z0-9-]*\\(\\.[a-z0-9][A-Z0-9-]*\\)*\\.$"
+ in
+ let n = 1 in
+ test_search_forward r n "a."
+ [|"a."; "~"|];
+ test_search_forward r n "Z."
+ [|"Z."; "~"|];
+ test_search_forward r n "2."
+ [|"2."; "~"|];
+ test_search_forward r n "ab-c."
+ [|"ab-c."; "~"|];
+ test_search_forward r n "ab-c.pq-r."
+ [|"ab-c.pq-r."; ".pq-r"|];
+ test_search_forward r n "sxk.zzz.ac.uk."
+ [|"sxk.zzz.ac.uk."; ".uk"|];
+ test_search_forward r n "sxk.ZZZ.ac.UK."
+ [|"sxk.ZZZ.ac.UK."; ".UK"|];
+ test_search_forward r n "x-.y-."
+ [|"x-.y-."; ".y-"|];
+ test_search_forward r n "-abc.peq."
+ [||];
+
+ start_test "Search for /^\\*\\.[a-z]\\([a-z0-9-]*[a-z0-9]+\\)?\
+ \\(\\.[a-z]\\([a-z0-9-]*[a-z0-9]+\\)?\\)*$/";
+ let r =
+ Str.regexp "^\\*\\.[a-z]\\([a-z0-9-]*[a-z0-9]+\\)?\
+ \\(\\.[a-z]\\([a-z0-9-]*[a-z0-9]+\\)?\\)*$"
+ in
+ let n = 3 in
+ test_search_forward r n "*.a"
+ [|"*.a"; "~"; "~"; "~"|];
+ test_search_forward r n "*.b0-a"
+ [|"*.b0-a"; "0-a"; "~"; "~"|];
+ test_search_forward r n "*.c3-b.c"
+ [|"*.c3-b.c"; "3-b"; ".c"; "~"|];
+ test_search_forward r n "*.c-a.b-c"
+ [|"*.c-a.b-c"; "-a"; ".b-c"; "-c"|];
+ test_search_forward r n "*.0"
+ [||];
+ test_search_forward r n "*.a-"
+ [||];
+ test_search_forward r n "*.a-b.c-"
+ [||];
+ test_search_forward r n "*.c-a.0-c"
+ [||];
+
+ start_test "Search for /^[0-9a-fA-F]\\(\\.[0-9a-fA-F]\\)*$/";
+ let r = Str.regexp "^[0-9a-fA-F]\\(\\.[0-9a-fA-F]\\)*$" in
+ let n = 1 in
+ test_search_forward r n "a.b.c.d"
+ [|"a.b.c.d"; ".d"|];
+ test_search_forward r n "A.B.C.D"
+ [|"A.B.C.D"; ".D"|];
+ test_search_forward r n "a.b.c.1.2.3.C"
+ [|"a.b.c.1.2.3.C"; ".C"|];
+ test_search_forward r n "a.b.c.dz"
+ [||];
+ test_search_forward r n "za"
+ [||];
+
+ start_test "Search for /^\\\".*\\\" *\\(;.*\\)?$/";
+ let r = Str.regexp "^\\\".*\\\" *\\(;.*\\)?$" in
+ let n = 1 in
+ test_search_forward r n "\"1234\""
+ [|"\"1234\""; "~"|];
+ test_search_forward r n "\"abcd\" ;"
+ [|"\"abcd\" ;"; ";"|];
+ test_search_forward r n "\"\" ; rhubarb"
+ [|"\"\" ; rhubarb"; "; rhubarb"|];
+ test_search_forward r n "\"1234\" : things"
+ [||];
+
+ start_test "Search for /^\\(a\\(b\\(c\\)\\)\\)\\(d\\(e\\(f\\)\\)\\)\
+ \\(h\\(i\\(j\\)\\)\\)$/";
+ let r =
+ Str.regexp "^\\(a\\(b\\(c\\)\\)\\)\\(d\\(e\\(f\\)\\)\\)\
+ \\(h\\(i\\(j\\)\\)\\)$"
+ in
+ let n = 9 in
+ test_search_forward r n "abcdefhij"
+ [|"abcdefhij"; "abc"; "bc"; "c"; "def"; "ef"; "f"; "hij"; "ij"; "j"|];
+
+ start_test "Search for /^[.^$|()*+?{,}]+/";
+ let r = Str.regexp "^[.^$|()*+?{,}]+" in
+ let n = 0 in
+ test_search_forward r n ".^$*(+)|{?,?}"
+ [|".^$*(+)|{?,?}"|];
+
+ start_test "Search for /\\(cat\\(a\\(ract\\|tonic\\)\\|erpillar\\)\\) \
+ \\1\\(\\)2\\(3\\)/";
+ let r =
+ Str.regexp "\\(cat\\(a\\(ract\\|tonic\\)\\|erpillar\\)\\) \\1\\(\\)2\\(3\\)"
+ in
+ let n = 5 in
+ test_search_forward r n "cataract cataract23"
+ [|"cataract cataract23"; "cataract"; "aract"; "ract"; ""; "3"|];
+ test_search_forward r n "catatonic catatonic23"
+ [|"catatonic catatonic23"; "catatonic"; "atonic"; "tonic"; ""; "3"|];
+ test_search_forward r n "caterpillar caterpillar23"
+ [|"caterpillar caterpillar23"; "caterpillar"; "erpillar"; "~"; ""; "3"|];
+
+ start_test "Search for /^From +\\([^ ]+\\) +[a-zA-Z][a-zA-Z][a-zA-Z] \
+ +[a-zA-Z][a-zA-Z][a-zA-Z] +[0-9]?[0-9] +[0-9][0-9]:[0-9][0-9]/";
+ let r =
+ Str.regexp "^From +\\([^ ]+\\) +[a-zA-Z][a-zA-Z][a-zA-Z] \
+ +[a-zA-Z][a-zA-Z][a-zA-Z] +[0-9]?[0-9] +[0-9][0-9]:[0-9][0-9]"
+ in
+ let n = 1 in
+ test_search_forward r n "From abcd Mon Sep 01 12:33:02 1997"
+ [|"From abcd Mon Sep 01 12:33"; "abcd"|];
+
+ start_test "Search for /\\ba/";
+ let r = Str.regexp "\\ba" in
+ let n = 0 in
+ test_search_forward r n "a2cd"
+ [|"a"|];
+ test_search_forward r n "the a"
+ [|"a"|];
+ test_search_forward r n ".ab"
+ [|"a"|];
+ test_search_forward r n "bad"
+ [||];
+ test_search_forward r n "the ba"
+ [||];
+ test_search_forward r n "ba."
+ [||];
+
+ start_test "Search for /a\\b/";
+ let r = Str.regexp "a\\b" in
+ let n = 0 in
+ test_search_forward r n "a"
+ [|"a"|];
+ test_search_forward r n "bc_a"
+ [|"a"|];
+ test_search_forward r n "a foo"
+ [|"a"|];
+ test_search_forward r n "a."
+ [|"a"|];
+ test_search_forward r n "bad"
+ [||];
+ test_search_forward r n "ab"
+ [||];
+
+ start_test "Search for /\\([a-z]*\\)b/";
+ let r = Str.regexp "\\([a-z]*\\)b" in
+ let n = 1 in
+ test_search_forward r n "abbb"
+ [|"abbb"; "abb"|];
+
+ start_test "Search for /\\([a-z]+\\)b/";
+ let r = Str.regexp "\\([a-z]+\\)b" in
+ let n = 1 in
+ test_search_forward r n "abbb"
+ [|"abbb"; "abb"|];
+
+ start_test "Search for /\\([a-z]?\\)b/";
+ let r = Str.regexp "\\([a-z]?\\)b" in
+ let n = 1 in
+ test_search_forward r n "bbbb"
+ [|"bb"; "b"|];
+
+ start_test "Search for /^a/";
+ let r = Str.regexp "^a" in
+ let n = 0 in
+ test_search_forward r n "abcdef"
+ [|"a"|];
+ test_search_forward r n "zzzz\nabcdef"
+ [|"a"|];
+
+ start_test "Search for /a$/";
+ let r = Str.regexp "a$" in
+ let n = 0 in
+ test_search_forward r n "xyza"
+ [|"a"|];
+ test_search_forward r n "xyza\nbcdef"
+ [|"a"|];
+
+ start_test "Null characters in regexps";
+ let r = Str.regexp "ab\000cd" in
+ let n = 0 in
+ test_search_forward r n "qerpoiuab\000cdwerltkh"
+ [| "ab\000cd" |];
+ let r = Str.regexp "\000cd" in
+ let n = 0 in
+ test_search_forward r n "qerpoiuab\000cdwerltkh"
+ [| "\000cd" |];
+
+ (** Backward searches *)
+ start_test "Backward search for /the quick/";
+ let r = Str.regexp "the quick" in
+ let n = 0 in
+ test_search_backward r n "the quick brown fox"
+ [|"the quick"|];
+ test_search_backward r n "What do you know about the quick brown fox?"
+ [|"the quick"|];
+ test_search_backward r n "The quick brown FOX"
+ [||];
+ test_search_backward r n "What do you know about THE QUICK BROWN FOX?"
+ [||];
+
+ start_test "Backward search for /a\\([0-9]+\\)/";
+ let r = Str.regexp "a\\([0-9]+\\)" in
+ let n = 1 in
+ test_search_backward r n "a123 a456zzzz"
+ [|"a456"; "456"|];
+ test_search_backward r n "ab123"
+ [||];
+
+ (** Partial match searches *)
+
+ start_test "Partial match for /partial match/";
+ let r = Str.regexp "partial match" in
+ let n = 0 in
+ test_partial_match r n ""
+ [|""|];
+ test_partial_match r n "partial matching"
+ [|"partial match"|];
+ test_partial_match r n "partial m"
+ [|"partial m"|];
+
+ start_test "Partial match for /\\(partial\\)\\|\\(match\\)/";
+ let r = Str.regexp "\\(partial\\)\\|\\(match\\)" in
+ let n = 2 in
+ test_partial_match r n ""
+ [|""; "~"; "~"|];
+ test_partial_match r n "part"
+ [|"part"; "~"; "~"|];
+ test_partial_match r n "partial"
+ [|"partial"; "partial"; "~"|];
+ test_partial_match r n "matching"
+ [|"match"; "~"; "match"|];
+ test_partial_match r n "mat"
+ [|"mat"; "~"; "~"|];
+ test_partial_match r n "zorglub"
+ [||];
+
+ (** Replacement *)
+ start_test "Global replacement";
+ test (Str.global_replace (Str.regexp "[aeiou]") ".."
+ "abcdefghijklmnopqrstuvwxyz")
+ "..bcd..fgh..jklmn..pqrst..vwxyz";
+ test (Str.global_replace (Str.regexp "[0-9]\\([0-9]*\\)") "-\\0-\\1-"
+ "abc012def3ghi45")
+ "abc-012-12-def-3--ghi-45-5-";
+ test (Str.global_replace (Str.regexp "[0-9]?") "."
+ "abc012def3ghi45")
+ ".a.b.c....d.e.f..g.h.i...";
+
+ start_test "First replacement";
+ test (Str.replace_first (Str.regexp "[eiou]") ".."
+ "abcdefghijklmnopqrstuvwxyz")
+ "abcd..fghijklmnopqrstuvwxyz";
+ test (Str.replace_first (Str.regexp "[0-9]\\([0-9]*\\)") "-\\0-\\1-"
+ "abc012def3ghi45")
+ "abc-012-12-def3ghi45";
+
+ (** Splitting *)
+ start_test "Splitting";
+ test (Str.split (Str.regexp "[ \t]+") "si non e vero")
+ ["si"; "non"; "e"; "vero"];
+ test (Str.split (Str.regexp "[ \t]+") " si non\te vero\t")
+ ["si"; "non"; "e"; "vero"];
+ test (Str.bounded_split (Str.regexp "[ \t]+") " si non e vero " 3)
+ ["si"; "non"; "e vero "];
+ test (Str.split (Str.regexp "[ \t]*") "si non e vero")
+ ["s"; "i"; "n"; "o"; "n"; "e"; "v"; "e"; "r"; "o"];
+ test (Str.split_delim (Str.regexp "[ \t]+") " si non e vero\t")
+ [""; "si"; "non"; "e"; "vero"; ""];
+ test (Str.full_split (Str.regexp "[ \t]+") " si non\te vero\t")
+ [Str.Delim " "; Str.Text "si";
+ Str.Delim " "; Str.Text "non";
+ Str.Delim "\t"; Str.Text "e";
+ Str.Delim " "; Str.Text "vero"; Str.Delim "\t"];
+
+ (** XML tokenization *)
+ (* See "REX: XML Shallow Parsing with Regular Expressions",
+ Robert D. Cameron, Simon Fraser University, CMPT TR 1998-17. *)
+ start_test "XML tokenization";
+ begin
+ let _TextSE = "[^<]+" in
+ let _UntilHyphen = "[^-]*-" in
+ let _Until2Hyphens = _UntilHyphen ^ "\\([^-]" ^ _UntilHyphen ^ "\\)*-" in
+ let _CommentCE = _Until2Hyphens ^ ">?" in
+ let _UntilRSBs = "[^]]*]\\([^]]+]\\)*]+" in
+ let _CDATA_CE = _UntilRSBs ^ "\\([^]>]" ^ _UntilRSBs ^ "\\)*>" in
+ let _S = "[ \n\t\r]+" in
+ let _NameStrt = "[A-Za-z_:]\\|[^\x00-\x7F]" in
+ let _NameChar = "[A-Za-z0-9_:.-]\\|[^\x00-\x7F]" in
+ let _Name = "\\(" ^ _NameStrt ^ "\\)\\(" ^ _NameChar ^ "\\)*" in
+ let _QuoteSE = "\"[^\"]*\"\\|'[^']*'" in
+ let _DT_IdentSE =
+ _S ^ _Name ^ "\\(" ^ _S ^ "\\(" ^ _Name ^ "\\|" ^ _QuoteSE ^ "\\)\\)*"
+ in
+ let _MarkupDeclCE = "\\([^]\"'><]\\|" ^ _QuoteSE ^ "\\)*>" in
+ let _S1 = "[\n\r\t ]" in
+ let _UntilQMs = "[^?]*\\?+" in
+ let _PI_Tail =
+ "\\?>\\|" ^ _S1 ^ _UntilQMs ^ "\\([^>?]" ^ _UntilQMs ^ "\\)*>"
+ in
+ let _DT_ItemSE =
+ "<\\(!\\(--" ^ _Until2Hyphens ^ ">\\|[^-]" ^ _MarkupDeclCE ^ "\\)\\|\\?"
+ ^ _Name ^ "\\(" ^ _PI_Tail ^ "\\)\\)\\|%" ^ _Name ^ ";\\|" ^ _S1
+ in
+ let _DocTypeCE =
+ _DT_IdentSE ^ "\\(" ^ _S ^ "\\)?\\(\\[\\(" ^ _DT_ItemSE ^ "\\)*]\\("
+ ^ _S ^ "\\)?\\)?>?"
+ in
+ let _DeclCE =
+ "--\\(" ^ _CommentCE ^ "\\)?\\|\\[_CDATA\\[\\(" ^ _CDATA_CE
+ ^ "\\)?\\|_DOCTYPE\\(" ^ _DocTypeCE ^ "\\)?"
+ in
+ let _PI_CE = _Name ^ "\\(" ^ _PI_Tail ^ "\\)?" in
+ let _EndTagCE = _Name ^ "\\(" ^ _S ^ "\\)?>?" in
+ let _AttValSE = "\"[^<\"]*\"\\|'[^<']*'" in
+ let _ElemTagCE =
+ _Name ^ "\\(" ^ _S ^ _Name ^ "\\(" ^ _S ^ "\\)?=\\(" ^ _S ^ "\\)?\\("
+ ^ _AttValSE ^ "\\)\\)*\\(" ^ _S ^ "\\)?/?>?"
+ in
+ let _MarkupSPE =
+ "<\\(!\\(" ^ _DeclCE ^ "\\)?\\|\\?\\(" ^ _PI_CE ^ "\\)?\\|/\\("
+ ^ _EndTagCE ^ "\\)?\\|\\(" ^ _ElemTagCE ^ "\\)?\\)"
+ in
+ let _XML_SPE = _TextSE ^ "\\|" ^ _MarkupSPE in
+ let input = "\
+<?xml version=\"1.0\"?>
+<?xml-stylesheet type=\"text/css\" href=\"nutrition.css\"?>
+<!DOCTYPE root [
+ <!ELEMENT root (stem)>
+ <!ELEMENT stem EMPTY>
+]>
+<!ELEMENT name (#PCDATA)>
+<![CDATA[my
+escaped text]]>
+<nutrition>
+<daily-values>
+ <total-fat units=\"g\">65</total-fat>
+ <saturated-fat units=\"g\">20</saturated-fat>
+ <cholesterol units=\"mg\">300</cholesterol>
+ <sodium units=\"mg\">2400</sodium>
+ <carb units=\"g\">300</carb>
+ <fiber units=\"g\">25</fiber>
+ <protein units=\"g\">50</protein>
+</daily-values>
+<food>
+ <name>Avocado Dip</name>
+ <mfr>Sunnydale</mfr>
+ <serving units=\"g\">29</serving>
+ <calories total=\"110\" fat=\"100\"/>
+ <total-fat>11</total-fat>
+ <saturated-fat>3</saturated-fat>
+ <cholesterol>5</cholesterol>
+ <sodium>210</sodium>
+ <carb>2</carb>
+ <fiber>0</fiber>
+ <protein>1</protein>
+ <vitamins>
+ <a>0</a>
+ <c>0</c>
+ </vitamins>
+ <minerals>
+ <ca>0</ca>
+ <fe>0</fe>
+ </minerals>
+</food>
+<!--
+<food>
+ <name></name>
+ <mfr></mfr>
+ <serving units=\"g\"></serving>
+ <calories total=\"\" fat=\"\"/>
+ <total-fat></total-fat>
+ <saturated-fat></saturated-fat>
+ <cholesterol></cholesterol>
+ <sodium></sodium>
+ <carb></carb>
+ <fiber></fiber>
+ <protein></protein>
+ <vitamins>
+ <a></a>
+ <c></c>
+ </vitamins>
+ <minerals>
+ <ca></ca>
+ <fe></fe>
+ </minerals>
+</food>
+-->
+" in
+ let result = [
+ "<?xml version=\"1.0\"?>";
+ "\n";
+ "<?xml-stylesheet type=\"text/css\" href=\"nutrition.css\"?>";
+ "\n";
+ "<!";
+ "DOCTYPE root [\n ";
+ "<!";
+ "ELEMENT root (stem)>\n ";
+ "<!";
+ "ELEMENT stem EMPTY>\n]>\n";
+ "<!";
+ "ELEMENT name (#PCDATA)>\n";
+ "<!";
+ "[CDATA[my\nescaped text]]> \n";
+ "<nutrition>";
+ "\n";
+ "<daily-values>";
+ "\n\t";
+ "<total-fat units=\"g\">";
+ "65";
+ "</total-fat>";
+ "\n\t";
+ "<saturated-fat units=\"g\">";
+ "20";
+ "</saturated-fat>";
+ "\n\t";
+ "<cholesterol units=\"mg\">";
+ "300";
+ "</cholesterol>";
+ "\n\t";
+ "<sodium units=\"mg\">";
+ "2400";
+ "</sodium>";
+ "\n\t";
+ "<carb units=\"g\">";
+ "300";
+ "</carb>";
+ "\n\t";
+ "<fiber units=\"g\">";
+ "25";
+ "</fiber>";
+ "\n\t";
+ "<protein units=\"g\">";
+ "50";
+ "</protein>";
+ "\n";
+ "</daily-values>";
+ "\n";
+ "<food>";
+ "\n\t";
+ "<name>";
+ "Avocado Dip";
+ "</name>";
+ "\n\t";
+ "<mfr>";
+ "Sunnydale";
+ "</mfr>";
+ "\n\t";
+ "<serving units=\"g\">";
+ "29";
+ "</serving>";
+ "\n\t";
+ "<calories total=\"110\" fat=\"100\"/>";
+ "\n\t";
+ "<total-fat>";
+ "11";
+ "</total-fat>";
+ "\n\t";
+ "<saturated-fat>";
+ "3";
+ "</saturated-fat>";
+ "\n\t";
+ "<cholesterol>";
+ "5";
+ "</cholesterol>";
+ "\n\t";
+ "<sodium>";
+ "210";
+ "</sodium>";
+ "\n\t";
+ "<carb>";
+ "2";
+ "</carb>";
+ "\n\t";
+ "<fiber>";
+ "0";
+ "</fiber>";
+ "\n\t";
+ "<protein>";
+ "1";
+ "</protein>";
+ "\n\t";
+ "<vitamins>";
+ "\n\t\t";
+ "<a>";
+ "0";
+ "</a>";
+ "\n\t\t";
+ "<c>";
+ "0";
+ "</c>";
+ "\n\t";
+ "</vitamins>";
+ "\n\t";
+ "<minerals>";
+ "\n\t\t";
+ "<ca>";
+ "0";
+ "</ca>";
+ "\n\t\t";
+ "<fe>";
+ "0";
+ "</fe>";
+ "\n\t";
+ "</minerals>";
+ "\n";
+ "</food>";
+ "\n";
+ "<!--\n\
+ <food>\n\
+ \t<name></name>\n\
+ \t<mfr></mfr>\n\
+ \t<serving units=\"g\"></serving>\n\
+ \t<calories total=\"\" fat=\"\"/>\n\
+ \t<total-fat></total-fat>\n\
+ \t<saturated-fat></saturated-fat>\n\
+ \t<cholesterol></cholesterol>\n\
+ \t<sodium></sodium>\n\
+ \t<carb></carb>\n\
+ \t<fiber></fiber>\n\
+ \t<protein></protein>\n\
+ \t<vitamins>\n\
+ \t\t<a></a>\n\
+ \t\t<c></c>\n\
+ \t</vitamins>\n\
+ \t<minerals>\n\
+ \t\t<ca></ca>\n\
+ \t\t<fe></fe>\n\
+ \t</minerals>\n\
+ </food>\n\
+ -->";
+ "\n"] in
+ let re = Str.regexp _XML_SPE in
+ let rec process i l =
+ let j = try Str.search_forward re input i with Not_found -> (-1) in
+ if j < 0 then begin
+ test l []
+ end else begin
+ match l with
+ [] -> test 0 1 (* failure *)
+ | hd :: tl ->
+ test (Str.matched_string input) hd; process (Str.match_end()) tl
+ end in
+ process 0 result
+ end;
+
+ end_test()
+
+let manual_test regexp text =
+ try
+ ignore (Str.search_forward (Str.regexp regexp) text 0);
+ printf "Matched,";
+ begin try
+ for i = 0 to 31 do
+ try
+ let s = Str.matched_group i text in
+ printf " \\%d=%s" i s
+ with Not_found ->
+ ()
+ done
+ with Invalid_argument "Str.matched_group" -> (*yuck*)
+ ()
+ end;
+ print_newline()
+ with Not_found ->
+ printf "Not matched\n"
+
+let _ =
+ if Array.length Sys.argv >= 3
+ then manual_test Sys.argv.(1) Sys.argv.(2)
+ else automated_test()
diff --git a/testsuite/tests/lib-str/t01.reference b/testsuite/tests/lib-str/t01.reference
new file mode 100644
index 0000000000..ade95deaef
--- /dev/null
+++ b/testsuite/tests/lib-str/t01.reference
@@ -0,0 +1,104 @@
+
+Search for /the quick brown fox/
+ ....
+Search for /the quick brown fox/ (case-insensitive)
+ .....
+Search for /a*abc?xyz+pqrrrabbb*xyyyyy?pq?q?q?q?q?q?AB*zz/
+ ....................................
+Search for /^abc\(abc\)?zz/
+ .....
+Search for /^\(b+\|a\)\(b+\|a\)?c/
+ ..........
+Search for /r\(\(g*\|k\)y?\)*A/
+ ....
+Search for /A\(\(t\|v\)\(q?\|n\)\)*A/
+ .
+Search for /A\(\(b\(\(d\|l*\)?\|w\)\)*a\)A/
+ .
+Search for /\(\|f\)*x/
+ ....
+Search for /\(\|f\)+x/
+ ....
+Search for /A\(.?\)*A/
+ ....
+Search for /\([ab]*\)\1+c/
+ ...
+Search for /^\(\(b+\|a\)\(b+\|a\)?\)?bc/
+ .
+Search for /^\(\(b*\|ba\)\(b*\|ba\)?\)?bc/
+ .....
+Search for /[^a]/
+ ..
+Search for /[^a]/ (case-insensitive)
+ ..
+Search for /^[]abcde]/
+ .........
+Search for /^[]cde]/
+ ......
+Search for /^[^]abcde]/
+ .........
+Search for /^[^]cde]/
+ ......
+Search for /^ÿ/
+ .
+Search for /^[0-9]+$/
+ .............
+Search for /^.*nter/
+ ...
+Search for /^xxx[0-9]+$/
+ ...
+Search for /^.+[0-9][0-9][0-9]$/
+ .....
+Search for /^\([^!]+\)!\(.+\)=apquxz\.ixr\.zzz\.ac\.uk$/
+ .....
+Search for /\([0-9a-f:]+\)$/
+ ............
+Search for /^[a-z0-9][a-z0-9-]*\(\.[a-z0-9][A-Z0-9-]*\)*\.$/
+ .........
+Search for /^\*\.[a-z]\([a-z0-9-]*[a-z0-9]+\)?\(\.[a-z]\([a-z0-9-]*[a-z0-9]+\)?\)*$/
+ ........
+Search for /^[0-9a-fA-F]\(\.[0-9a-fA-F]\)*$/
+ .....
+Search for /^\".*\" *\(;.*\)?$/
+ ....
+Search for /^\(a\(b\(c\)\)\)\(d\(e\(f\)\)\)\(h\(i\(j\)\)\)$/
+ .
+Search for /^[.^$|()*+?{,}]+/
+ .
+Search for /\(cat\(a\(ract\|tonic\)\|erpillar\)\) \1\(\)2\(3\)/
+ ...
+Search for /^From +\([^ ]+\) +[a-zA-Z][a-zA-Z][a-zA-Z] +[a-zA-Z][a-zA-Z][a-zA-Z] +[0-9]?[0-9] +[0-9][0-9]:[0-9][0-9]/
+ .
+Search for /\ba/
+ ......
+Search for /a\b/
+ ......
+Search for /\([a-z]*\)b/
+ .
+Search for /\([a-z]+\)b/
+ .
+Search for /\([a-z]?\)b/
+ .
+Search for /^a/
+ ..
+Search for /a$/
+ ..
+Null characters in regexps
+ ..
+Backward search for /the quick/
+ ....
+Backward search for /a\([0-9]+\)/
+ ..
+Partial match for /partial match/
+ ...
+Partial match for /\(partial\)\|\(match\)/
+ ......
+Global replacement
+ ...
+First replacement
+ ..
+Splitting
+ ......
+XML tokenization
+ .........................................................................................................................
+All tests passed
diff --git a/testsuite/tests/lib-stream/Makefile b/testsuite/tests/lib-stream/Makefile
new file mode 100644
index 0000000000..e5bd381a22
--- /dev/null
+++ b/testsuite/tests/lib-stream/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=testing
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-stream/count_concat_bug.ml b/testsuite/tests/lib-stream/count_concat_bug.ml
new file mode 100644
index 0000000000..986a2ea01c
--- /dev/null
+++ b/testsuite/tests/lib-stream/count_concat_bug.ml
@@ -0,0 +1,69 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Gabriel Scherer, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let is_empty s =
+ try Stream.empty s; true with Stream.Failure -> false
+
+let test_icons =
+ let s = Stream.of_string "ab" in
+ let s = Stream.icons 'c' s in
+ Testing.test (Stream.next s = 'c');
+ Testing.test (Stream.next s = 'a');
+ Testing.test (Stream.next s = 'b');
+ Testing.test (is_empty s);
+ ()
+
+let test_lcons =
+ let s = Stream.of_string "ab" in
+ let s = Stream.lcons (fun () -> 'c') s in
+ Testing.test (Stream.next s = 'c');
+ Testing.test (Stream.next s = 'a');
+ Testing.test (Stream.next s = 'b');
+ Testing.test (is_empty s);
+ ()
+
+let test_iapp =
+ let s = Stream.of_string "ab" in
+ let s = Stream.iapp (Stream.of_list ['c']) s in
+ Testing.test (Stream.next s = 'c');
+ Testing.test (Stream.next s = 'a');
+ Testing.test (Stream.next s = 'b');
+ Testing.test (is_empty s);
+ ()
+
+let test_lapp_right =
+ let s1 = Stream.of_list ['c'] in
+ let s2 = Stream.of_string "ab" in
+ let s = Stream.lapp (fun () -> s1) s2 in
+ Testing.test (Stream.next s = 'c');
+ Testing.test (Stream.next s = 'a');
+ Testing.test (Stream.next s = 'b');
+ Testing.test (is_empty s);
+ ()
+
+let test_lapp_left =
+ let s1 = Stream.of_string "bc" in
+ let s2 = Stream.of_list ['a'] in
+ Testing.test (Stream.next s1 = 'b');
+ let s = Stream.lapp (fun () -> s1) s2 in
+ Testing.test (Stream.next s = 'c');
+ Testing.test (Stream.next s = 'a');
+ Testing.test (is_empty s);
+ ()
+
+let test_slazy =
+ let s = Stream.of_string "ab" in
+ Testing.test (Stream.next s = 'a');
+ let s = Stream.slazy (fun () -> s) in
+ Testing.test (Stream.next s = 'b');
+ Testing.test (is_empty s);
+ ()
diff --git a/testsuite/tests/lib-stream/count_concat_bug.reference b/testsuite/tests/lib-stream/count_concat_bug.reference
new file mode 100644
index 0000000000..52e367eabc
--- /dev/null
+++ b/testsuite/tests/lib-stream/count_concat_bug.reference
@@ -0,0 +1,2 @@
+ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
+All tests succeeded.
diff --git a/testsuite/tests/lib-string/Makefile b/testsuite/tests/lib-string/Makefile
new file mode 100644
index 0000000000..6ae7266b0c
--- /dev/null
+++ b/testsuite/tests/lib-string/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+LIBRARIES=str
+ADD_COMPFLAGS=-I $(OTOPDIR)/otherlibs/str
+LD_PATH=$(TOPDIR)/otherlibs/str
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-string/test_string.ml b/testsuite/tests/lib-string/test_string.ml
new file mode 100644
index 0000000000..17fdb3bd94
--- /dev/null
+++ b/testsuite/tests/lib-string/test_string.ml
@@ -0,0 +1,35 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, Jane Street Group, LLC *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec build_string f n accu =
+ if n <= 0
+ then String.concat "" accu
+ else build_string f (n-1) (f (n-1) :: accu)
+;;
+
+let char n = String.make 1 (Char.chr n);;
+
+let reference n =
+ if n = 8 then "\\b"
+ else if n = 9 then "\\t"
+ else if n = 10 then "\\n"
+ else if n = 13 then "\\r"
+ else if n = Char.code '\"' then "\\\""
+ else if n = Char.code '\\' then "\\\\"
+ else if n < 32 || n > 126 then Printf.sprintf "\\%03d" n
+ else char n
+;;
+
+let raw_string = build_string char 256 [];;
+let ref_string = build_string reference 256 [];;
+
+if String.escaped raw_string <> ref_string then failwith "test:String.escaped";;
diff --git a/testsuite/tests/lib-string/test_string.reference b/testsuite/tests/lib-string/test_string.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/lib-string/test_string.reference
diff --git a/testsuite/tests/lib-systhreads/Makefile b/testsuite/tests/lib-systhreads/Makefile
new file mode 100644
index 0000000000..fc098713f3
--- /dev/null
+++ b/testsuite/tests/lib-systhreads/Makefile
@@ -0,0 +1,20 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+LIBRARIES=unix threads
+ADD_COMPFLAGS=-thread -I $(OTOPDIR)/otherlibs/systhreads \
+ -I $(OTOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+LD_PATH=$(TOPDIR)/otherlibs/systhreads:$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-systhreads/testfork.ml b/testsuite/tests/lib-systhreads/testfork.ml
new file mode 100644
index 0000000000..843e5ed258
--- /dev/null
+++ b/testsuite/tests/lib-systhreads/testfork.ml
@@ -0,0 +1,43 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* POSIX threads and fork() *)
+
+let compute_thread c = ignore c
+(*
+ while true do
+ print_char c; flush stdout;
+ for i = 1 to 100000 do ignore(ref []) done
+ done
+*)
+
+let main () =
+ ignore(Thread.create compute_thread '1');
+ Thread.delay 1.0;
+ print_string "Forking..."; print_newline();
+ match Unix.fork() with
+ | 0 ->
+ Thread.delay 0.5;
+ print_string "In child..."; print_newline();
+ Gc.minor();
+ print_string "Child did minor GC."; print_newline();
+ ignore(Thread.create compute_thread '2');
+ Thread.delay 1.0;
+ print_string "Child is exiting."; print_newline();
+ exit 0
+ | pid ->
+ print_string "In parent..."; print_newline();
+ Thread.delay 4.0;
+ print_string "Parent is exiting."; print_newline();
+ exit 0
+
+let _ = main()
diff --git a/testsuite/tests/lib-systhreads/testfork.precheck b/testsuite/tests/lib-systhreads/testfork.precheck
new file mode 100644
index 0000000000..f93abf1a69
--- /dev/null
+++ b/testsuite/tests/lib-systhreads/testfork.precheck
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+case `sed -n -e '/OTHERLIBRARIES=/s// /p' ../../../config/Makefile` in
+ *' unix '*) exit 0;;
+ *) exit 3;;
+esac
diff --git a/testsuite/tests/lib-systhreads/testfork.reference b/testsuite/tests/lib-systhreads/testfork.reference
new file mode 100644
index 0000000000..fb7a3c299d
--- /dev/null
+++ b/testsuite/tests/lib-systhreads/testfork.reference
@@ -0,0 +1,6 @@
+Forking...
+In parent...
+In child...
+Child did minor GC.
+Child is exiting.
+Parent is exiting.
diff --git a/testsuite/tests/lib-threads/.ignore b/testsuite/tests/lib-threads/.ignore
new file mode 100644
index 0000000000..e6d9e45b70
--- /dev/null
+++ b/testsuite/tests/lib-threads/.ignore
@@ -0,0 +1 @@
+*.byt
diff --git a/testsuite/tests/lib-threads/Makefile b/testsuite/tests/lib-threads/Makefile
new file mode 100644
index 0000000000..fc098713f3
--- /dev/null
+++ b/testsuite/tests/lib-threads/Makefile
@@ -0,0 +1,20 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+LIBRARIES=unix threads
+ADD_COMPFLAGS=-thread -I $(OTOPDIR)/otherlibs/systhreads \
+ -I $(OTOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+LD_PATH=$(TOPDIR)/otherlibs/systhreads:$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/lib-threads/close.ml b/testsuite/tests/lib-threads/close.ml
new file mode 100644
index 0000000000..01b90afdc2
--- /dev/null
+++ b/testsuite/tests/lib-threads/close.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let main () =
+ let (rd, wr) = Unix.pipe() in
+ let t = Thread.create
+ (fun () ->
+ Thread.delay 1.0;
+ print_endline "closing fd...";
+ Unix.close wr;
+ )
+ () in
+ let buf = String.create 10 in
+ print_endline "reading...";
+ begin try ignore (Unix.read rd buf 0 10) with Unix.Unix_error _ -> () end;
+ print_endline "read returned";
+ t
+
+let t = Unix.handle_unix_error main ()
+
+let _ = Thread.join t
diff --git a/testsuite/tests/lib-threads/close.reference b/testsuite/tests/lib-threads/close.reference
new file mode 100644
index 0000000000..bb5061c8c7
--- /dev/null
+++ b/testsuite/tests/lib-threads/close.reference
@@ -0,0 +1,3 @@
+reading...
+closing fd...
+read returned
diff --git a/testsuite/tests/lib-threads/sieve.ml b/testsuite/tests/lib-threads/sieve.ml
new file mode 100644
index 0000000000..ac3a9d2f97
--- /dev/null
+++ b/testsuite/tests/lib-threads/sieve.ml
@@ -0,0 +1,45 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+open Thread
+
+let rec integers n ch =
+ Event.sync (Event.send ch n);
+ integers (n+1) ch
+
+let rec sieve n chin chout =
+ let m = Event.sync (Event.receive chin)
+ in if m mod n = 0
+ then sieve n chin chout
+ else Event.sync (Event.send chout m);
+ sieve n chin chout
+
+let rec print_primes ch max =
+ let n = Event.sync (Event.receive ch)
+ in if n > max
+ then ()
+ else begin
+ printf "%d\n" n; flush stdout;
+ let ch_after_n = Event.new_channel ()
+ in Thread.create (sieve n ch) ch_after_n;
+ print_primes ch_after_n max
+ end
+
+let go max =
+ let ch = Event.new_channel ()
+ in Thread.create (integers 2) ch;
+ print_primes ch max;;
+
+let _ = go 500
+
+;;
diff --git a/testsuite/tests/lib-threads/sieve.reference b/testsuite/tests/lib-threads/sieve.reference
new file mode 100644
index 0000000000..3e7998db49
--- /dev/null
+++ b/testsuite/tests/lib-threads/sieve.reference
@@ -0,0 +1,95 @@
+2
+3
+5
+7
+11
+13
+17
+19
+23
+29
+31
+37
+41
+43
+47
+53
+59
+61
+67
+71
+73
+79
+83
+89
+97
+101
+103
+107
+109
+113
+127
+131
+137
+139
+149
+151
+157
+163
+167
+173
+179
+181
+191
+193
+197
+199
+211
+223
+227
+229
+233
+239
+241
+251
+257
+263
+269
+271
+277
+281
+283
+293
+307
+311
+313
+317
+331
+337
+347
+349
+353
+359
+367
+373
+379
+383
+389
+397
+401
+409
+419
+421
+431
+433
+439
+443
+449
+457
+461
+463
+467
+479
+487
+491
+499
diff --git a/testsuite/tests/lib-threads/test-file-short-lines b/testsuite/tests/lib-threads/test-file-short-lines
new file mode 100644
index 0000000000..35abe7ca2e
--- /dev/null
+++ b/testsuite/tests/lib-threads/test-file-short-lines
@@ -0,0 +1,10 @@
+##
+# Host Database
+#
+# localhost is used to configure the loopback interface
+# when the system is booting. Do not change this entry.
+##
+127.0.0.1 localhost
+255.255.255.255 broadcasthost
+::1 localhost
+fe80::1%lo0 localhost
diff --git a/testsuite/tests/lib-threads/test1.checker b/testsuite/tests/lib-threads/test1.checker
new file mode 100644
index 0000000000..94778f234d
--- /dev/null
+++ b/testsuite/tests/lib-threads/test1.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+LC_ALL=C $SORT test1.result | $DIFF test1.reference -
diff --git a/testsuite/tests/lib-threads/test1.ml b/testsuite/tests/lib-threads/test1.ml
new file mode 100644
index 0000000000..c551fbc5dd
--- /dev/null
+++ b/testsuite/tests/lib-threads/test1.ml
@@ -0,0 +1,75 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Classic producer-consumer *)
+
+type 'a prodcons =
+ { buffer: 'a array;
+ lock: Mutex.t;
+ mutable readpos: int;
+ mutable writepos: int;
+ notempty: Condition.t;
+ notfull: Condition.t }
+
+let create size init =
+ { buffer = Array.make size init;
+ lock = Mutex.create();
+ readpos = 0;
+ writepos = 0;
+ notempty = Condition.create();
+ notfull = Condition.create() }
+
+let output_lock = Mutex.create()
+
+let put p data =
+ Mutex.lock p.lock;
+ while (p.writepos + 1) mod Array.length p.buffer = p.readpos do
+ Condition.wait p.notfull p.lock
+ done;
+ p.buffer.(p.writepos) <- data;
+ p.writepos <- (p.writepos + 1) mod Array.length p.buffer;
+ Condition.signal p.notempty;
+ Mutex.unlock p.lock
+
+let get p =
+ Mutex.lock p.lock;
+ while p.writepos = p.readpos do
+ Condition.wait p.notempty p.lock
+ done;
+ let data = p.buffer.(p.readpos) in
+ p.readpos <- (p.readpos + 1) mod Array.length p.buffer;
+ Condition.signal p.notfull;
+ Mutex.unlock p.lock;
+ data
+
+(* Test *)
+
+let buff = create 20 0
+
+let rec produce n =
+ Mutex.lock output_lock;
+ print_int n; print_string "-->"; print_newline();
+ Mutex.unlock output_lock;
+ put buff n;
+ if n < 10000 then produce (n+1)
+
+let rec consume () =
+ let n = get buff in
+ Mutex.lock output_lock;
+ print_string "-->"; print_int n; print_newline();
+ Mutex.unlock output_lock;
+ if n < 10000 then consume ()
+
+let t1 = Thread.create produce 0
+let _ = consume ()
+
+;;
diff --git a/testsuite/tests/lib-threads/test1.reference b/testsuite/tests/lib-threads/test1.reference
new file mode 100644
index 0000000000..febf6610b7
--- /dev/null
+++ b/testsuite/tests/lib-threads/test1.reference
@@ -0,0 +1,20002 @@
+-->0
+-->1
+-->10
+-->100
+-->1000
+-->10000
+-->1001
+-->1002
+-->1003
+-->1004
+-->1005
+-->1006
+-->1007
+-->1008
+-->1009
+-->101
+-->1010
+-->1011
+-->1012
+-->1013
+-->1014
+-->1015
+-->1016
+-->1017
+-->1018
+-->1019
+-->102
+-->1020
+-->1021
+-->1022
+-->1023
+-->1024
+-->1025
+-->1026
+-->1027
+-->1028
+-->1029
+-->103
+-->1030
+-->1031
+-->1032
+-->1033
+-->1034
+-->1035
+-->1036
+-->1037
+-->1038
+-->1039
+-->104
+-->1040
+-->1041
+-->1042
+-->1043
+-->1044
+-->1045
+-->1046
+-->1047
+-->1048
+-->1049
+-->105
+-->1050
+-->1051
+-->1052
+-->1053
+-->1054
+-->1055
+-->1056
+-->1057
+-->1058
+-->1059
+-->106
+-->1060
+-->1061
+-->1062
+-->1063
+-->1064
+-->1065
+-->1066
+-->1067
+-->1068
+-->1069
+-->107
+-->1070
+-->1071
+-->1072
+-->1073
+-->1074
+-->1075
+-->1076
+-->1077
+-->1078
+-->1079
+-->108
+-->1080
+-->1081
+-->1082
+-->1083
+-->1084
+-->1085
+-->1086
+-->1087
+-->1088
+-->1089
+-->109
+-->1090
+-->1091
+-->1092
+-->1093
+-->1094
+-->1095
+-->1096
+-->1097
+-->1098
+-->1099
+-->11
+-->110
+-->1100
+-->1101
+-->1102
+-->1103
+-->1104
+-->1105
+-->1106
+-->1107
+-->1108
+-->1109
+-->111
+-->1110
+-->1111
+-->1112
+-->1113
+-->1114
+-->1115
+-->1116
+-->1117
+-->1118
+-->1119
+-->112
+-->1120
+-->1121
+-->1122
+-->1123
+-->1124
+-->1125
+-->1126
+-->1127
+-->1128
+-->1129
+-->113
+-->1130
+-->1131
+-->1132
+-->1133
+-->1134
+-->1135
+-->1136
+-->1137
+-->1138
+-->1139
+-->114
+-->1140
+-->1141
+-->1142
+-->1143
+-->1144
+-->1145
+-->1146
+-->1147
+-->1148
+-->1149
+-->115
+-->1150
+-->1151
+-->1152
+-->1153
+-->1154
+-->1155
+-->1156
+-->1157
+-->1158
+-->1159
+-->116
+-->1160
+-->1161
+-->1162
+-->1163
+-->1164
+-->1165
+-->1166
+-->1167
+-->1168
+-->1169
+-->117
+-->1170
+-->1171
+-->1172
+-->1173
+-->1174
+-->1175
+-->1176
+-->1177
+-->1178
+-->1179
+-->118
+-->1180
+-->1181
+-->1182
+-->1183
+-->1184
+-->1185
+-->1186
+-->1187
+-->1188
+-->1189
+-->119
+-->1190
+-->1191
+-->1192
+-->1193
+-->1194
+-->1195
+-->1196
+-->1197
+-->1198
+-->1199
+-->12
+-->120
+-->1200
+-->1201
+-->1202
+-->1203
+-->1204
+-->1205
+-->1206
+-->1207
+-->1208
+-->1209
+-->121
+-->1210
+-->1211
+-->1212
+-->1213
+-->1214
+-->1215
+-->1216
+-->1217
+-->1218
+-->1219
+-->122
+-->1220
+-->1221
+-->1222
+-->1223
+-->1224
+-->1225
+-->1226
+-->1227
+-->1228
+-->1229
+-->123
+-->1230
+-->1231
+-->1232
+-->1233
+-->1234
+-->1235
+-->1236
+-->1237
+-->1238
+-->1239
+-->124
+-->1240
+-->1241
+-->1242
+-->1243
+-->1244
+-->1245
+-->1246
+-->1247
+-->1248
+-->1249
+-->125
+-->1250
+-->1251
+-->1252
+-->1253
+-->1254
+-->1255
+-->1256
+-->1257
+-->1258
+-->1259
+-->126
+-->1260
+-->1261
+-->1262
+-->1263
+-->1264
+-->1265
+-->1266
+-->1267
+-->1268
+-->1269
+-->127
+-->1270
+-->1271
+-->1272
+-->1273
+-->1274
+-->1275
+-->1276
+-->1277
+-->1278
+-->1279
+-->128
+-->1280
+-->1281
+-->1282
+-->1283
+-->1284
+-->1285
+-->1286
+-->1287
+-->1288
+-->1289
+-->129
+-->1290
+-->1291
+-->1292
+-->1293
+-->1294
+-->1295
+-->1296
+-->1297
+-->1298
+-->1299
+-->13
+-->130
+-->1300
+-->1301
+-->1302
+-->1303
+-->1304
+-->1305
+-->1306
+-->1307
+-->1308
+-->1309
+-->131
+-->1310
+-->1311
+-->1312
+-->1313
+-->1314
+-->1315
+-->1316
+-->1317
+-->1318
+-->1319
+-->132
+-->1320
+-->1321
+-->1322
+-->1323
+-->1324
+-->1325
+-->1326
+-->1327
+-->1328
+-->1329
+-->133
+-->1330
+-->1331
+-->1332
+-->1333
+-->1334
+-->1335
+-->1336
+-->1337
+-->1338
+-->1339
+-->134
+-->1340
+-->1341
+-->1342
+-->1343
+-->1344
+-->1345
+-->1346
+-->1347
+-->1348
+-->1349
+-->135
+-->1350
+-->1351
+-->1352
+-->1353
+-->1354
+-->1355
+-->1356
+-->1357
+-->1358
+-->1359
+-->136
+-->1360
+-->1361
+-->1362
+-->1363
+-->1364
+-->1365
+-->1366
+-->1367
+-->1368
+-->1369
+-->137
+-->1370
+-->1371
+-->1372
+-->1373
+-->1374
+-->1375
+-->1376
+-->1377
+-->1378
+-->1379
+-->138
+-->1380
+-->1381
+-->1382
+-->1383
+-->1384
+-->1385
+-->1386
+-->1387
+-->1388
+-->1389
+-->139
+-->1390
+-->1391
+-->1392
+-->1393
+-->1394
+-->1395
+-->1396
+-->1397
+-->1398
+-->1399
+-->14
+-->140
+-->1400
+-->1401
+-->1402
+-->1403
+-->1404
+-->1405
+-->1406
+-->1407
+-->1408
+-->1409
+-->141
+-->1410
+-->1411
+-->1412
+-->1413
+-->1414
+-->1415
+-->1416
+-->1417
+-->1418
+-->1419
+-->142
+-->1420
+-->1421
+-->1422
+-->1423
+-->1424
+-->1425
+-->1426
+-->1427
+-->1428
+-->1429
+-->143
+-->1430
+-->1431
+-->1432
+-->1433
+-->1434
+-->1435
+-->1436
+-->1437
+-->1438
+-->1439
+-->144
+-->1440
+-->1441
+-->1442
+-->1443
+-->1444
+-->1445
+-->1446
+-->1447
+-->1448
+-->1449
+-->145
+-->1450
+-->1451
+-->1452
+-->1453
+-->1454
+-->1455
+-->1456
+-->1457
+-->1458
+-->1459
+-->146
+-->1460
+-->1461
+-->1462
+-->1463
+-->1464
+-->1465
+-->1466
+-->1467
+-->1468
+-->1469
+-->147
+-->1470
+-->1471
+-->1472
+-->1473
+-->1474
+-->1475
+-->1476
+-->1477
+-->1478
+-->1479
+-->148
+-->1480
+-->1481
+-->1482
+-->1483
+-->1484
+-->1485
+-->1486
+-->1487
+-->1488
+-->1489
+-->149
+-->1490
+-->1491
+-->1492
+-->1493
+-->1494
+-->1495
+-->1496
+-->1497
+-->1498
+-->1499
+-->15
+-->150
+-->1500
+-->1501
+-->1502
+-->1503
+-->1504
+-->1505
+-->1506
+-->1507
+-->1508
+-->1509
+-->151
+-->1510
+-->1511
+-->1512
+-->1513
+-->1514
+-->1515
+-->1516
+-->1517
+-->1518
+-->1519
+-->152
+-->1520
+-->1521
+-->1522
+-->1523
+-->1524
+-->1525
+-->1526
+-->1527
+-->1528
+-->1529
+-->153
+-->1530
+-->1531
+-->1532
+-->1533
+-->1534
+-->1535
+-->1536
+-->1537
+-->1538
+-->1539
+-->154
+-->1540
+-->1541
+-->1542
+-->1543
+-->1544
+-->1545
+-->1546
+-->1547
+-->1548
+-->1549
+-->155
+-->1550
+-->1551
+-->1552
+-->1553
+-->1554
+-->1555
+-->1556
+-->1557
+-->1558
+-->1559
+-->156
+-->1560
+-->1561
+-->1562
+-->1563
+-->1564
+-->1565
+-->1566
+-->1567
+-->1568
+-->1569
+-->157
+-->1570
+-->1571
+-->1572
+-->1573
+-->1574
+-->1575
+-->1576
+-->1577
+-->1578
+-->1579
+-->158
+-->1580
+-->1581
+-->1582
+-->1583
+-->1584
+-->1585
+-->1586
+-->1587
+-->1588
+-->1589
+-->159
+-->1590
+-->1591
+-->1592
+-->1593
+-->1594
+-->1595
+-->1596
+-->1597
+-->1598
+-->1599
+-->16
+-->160
+-->1600
+-->1601
+-->1602
+-->1603
+-->1604
+-->1605
+-->1606
+-->1607
+-->1608
+-->1609
+-->161
+-->1610
+-->1611
+-->1612
+-->1613
+-->1614
+-->1615
+-->1616
+-->1617
+-->1618
+-->1619
+-->162
+-->1620
+-->1621
+-->1622
+-->1623
+-->1624
+-->1625
+-->1626
+-->1627
+-->1628
+-->1629
+-->163
+-->1630
+-->1631
+-->1632
+-->1633
+-->1634
+-->1635
+-->1636
+-->1637
+-->1638
+-->1639
+-->164
+-->1640
+-->1641
+-->1642
+-->1643
+-->1644
+-->1645
+-->1646
+-->1647
+-->1648
+-->1649
+-->165
+-->1650
+-->1651
+-->1652
+-->1653
+-->1654
+-->1655
+-->1656
+-->1657
+-->1658
+-->1659
+-->166
+-->1660
+-->1661
+-->1662
+-->1663
+-->1664
+-->1665
+-->1666
+-->1667
+-->1668
+-->1669
+-->167
+-->1670
+-->1671
+-->1672
+-->1673
+-->1674
+-->1675
+-->1676
+-->1677
+-->1678
+-->1679
+-->168
+-->1680
+-->1681
+-->1682
+-->1683
+-->1684
+-->1685
+-->1686
+-->1687
+-->1688
+-->1689
+-->169
+-->1690
+-->1691
+-->1692
+-->1693
+-->1694
+-->1695
+-->1696
+-->1697
+-->1698
+-->1699
+-->17
+-->170
+-->1700
+-->1701
+-->1702
+-->1703
+-->1704
+-->1705
+-->1706
+-->1707
+-->1708
+-->1709
+-->171
+-->1710
+-->1711
+-->1712
+-->1713
+-->1714
+-->1715
+-->1716
+-->1717
+-->1718
+-->1719
+-->172
+-->1720
+-->1721
+-->1722
+-->1723
+-->1724
+-->1725
+-->1726
+-->1727
+-->1728
+-->1729
+-->173
+-->1730
+-->1731
+-->1732
+-->1733
+-->1734
+-->1735
+-->1736
+-->1737
+-->1738
+-->1739
+-->174
+-->1740
+-->1741
+-->1742
+-->1743
+-->1744
+-->1745
+-->1746
+-->1747
+-->1748
+-->1749
+-->175
+-->1750
+-->1751
+-->1752
+-->1753
+-->1754
+-->1755
+-->1756
+-->1757
+-->1758
+-->1759
+-->176
+-->1760
+-->1761
+-->1762
+-->1763
+-->1764
+-->1765
+-->1766
+-->1767
+-->1768
+-->1769
+-->177
+-->1770
+-->1771
+-->1772
+-->1773
+-->1774
+-->1775
+-->1776
+-->1777
+-->1778
+-->1779
+-->178
+-->1780
+-->1781
+-->1782
+-->1783
+-->1784
+-->1785
+-->1786
+-->1787
+-->1788
+-->1789
+-->179
+-->1790
+-->1791
+-->1792
+-->1793
+-->1794
+-->1795
+-->1796
+-->1797
+-->1798
+-->1799
+-->18
+-->180
+-->1800
+-->1801
+-->1802
+-->1803
+-->1804
+-->1805
+-->1806
+-->1807
+-->1808
+-->1809
+-->181
+-->1810
+-->1811
+-->1812
+-->1813
+-->1814
+-->1815
+-->1816
+-->1817
+-->1818
+-->1819
+-->182
+-->1820
+-->1821
+-->1822
+-->1823
+-->1824
+-->1825
+-->1826
+-->1827
+-->1828
+-->1829
+-->183
+-->1830
+-->1831
+-->1832
+-->1833
+-->1834
+-->1835
+-->1836
+-->1837
+-->1838
+-->1839
+-->184
+-->1840
+-->1841
+-->1842
+-->1843
+-->1844
+-->1845
+-->1846
+-->1847
+-->1848
+-->1849
+-->185
+-->1850
+-->1851
+-->1852
+-->1853
+-->1854
+-->1855
+-->1856
+-->1857
+-->1858
+-->1859
+-->186
+-->1860
+-->1861
+-->1862
+-->1863
+-->1864
+-->1865
+-->1866
+-->1867
+-->1868
+-->1869
+-->187
+-->1870
+-->1871
+-->1872
+-->1873
+-->1874
+-->1875
+-->1876
+-->1877
+-->1878
+-->1879
+-->188
+-->1880
+-->1881
+-->1882
+-->1883
+-->1884
+-->1885
+-->1886
+-->1887
+-->1888
+-->1889
+-->189
+-->1890
+-->1891
+-->1892
+-->1893
+-->1894
+-->1895
+-->1896
+-->1897
+-->1898
+-->1899
+-->19
+-->190
+-->1900
+-->1901
+-->1902
+-->1903
+-->1904
+-->1905
+-->1906
+-->1907
+-->1908
+-->1909
+-->191
+-->1910
+-->1911
+-->1912
+-->1913
+-->1914
+-->1915
+-->1916
+-->1917
+-->1918
+-->1919
+-->192
+-->1920
+-->1921
+-->1922
+-->1923
+-->1924
+-->1925
+-->1926
+-->1927
+-->1928
+-->1929
+-->193
+-->1930
+-->1931
+-->1932
+-->1933
+-->1934
+-->1935
+-->1936
+-->1937
+-->1938
+-->1939
+-->194
+-->1940
+-->1941
+-->1942
+-->1943
+-->1944
+-->1945
+-->1946
+-->1947
+-->1948
+-->1949
+-->195
+-->1950
+-->1951
+-->1952
+-->1953
+-->1954
+-->1955
+-->1956
+-->1957
+-->1958
+-->1959
+-->196
+-->1960
+-->1961
+-->1962
+-->1963
+-->1964
+-->1965
+-->1966
+-->1967
+-->1968
+-->1969
+-->197
+-->1970
+-->1971
+-->1972
+-->1973
+-->1974
+-->1975
+-->1976
+-->1977
+-->1978
+-->1979
+-->198
+-->1980
+-->1981
+-->1982
+-->1983
+-->1984
+-->1985
+-->1986
+-->1987
+-->1988
+-->1989
+-->199
+-->1990
+-->1991
+-->1992
+-->1993
+-->1994
+-->1995
+-->1996
+-->1997
+-->1998
+-->1999
+-->2
+-->20
+-->200
+-->2000
+-->2001
+-->2002
+-->2003
+-->2004
+-->2005
+-->2006
+-->2007
+-->2008
+-->2009
+-->201
+-->2010
+-->2011
+-->2012
+-->2013
+-->2014
+-->2015
+-->2016
+-->2017
+-->2018
+-->2019
+-->202
+-->2020
+-->2021
+-->2022
+-->2023
+-->2024
+-->2025
+-->2026
+-->2027
+-->2028
+-->2029
+-->203
+-->2030
+-->2031
+-->2032
+-->2033
+-->2034
+-->2035
+-->2036
+-->2037
+-->2038
+-->2039
+-->204
+-->2040
+-->2041
+-->2042
+-->2043
+-->2044
+-->2045
+-->2046
+-->2047
+-->2048
+-->2049
+-->205
+-->2050
+-->2051
+-->2052
+-->2053
+-->2054
+-->2055
+-->2056
+-->2057
+-->2058
+-->2059
+-->206
+-->2060
+-->2061
+-->2062
+-->2063
+-->2064
+-->2065
+-->2066
+-->2067
+-->2068
+-->2069
+-->207
+-->2070
+-->2071
+-->2072
+-->2073
+-->2074
+-->2075
+-->2076
+-->2077
+-->2078
+-->2079
+-->208
+-->2080
+-->2081
+-->2082
+-->2083
+-->2084
+-->2085
+-->2086
+-->2087
+-->2088
+-->2089
+-->209
+-->2090
+-->2091
+-->2092
+-->2093
+-->2094
+-->2095
+-->2096
+-->2097
+-->2098
+-->2099
+-->21
+-->210
+-->2100
+-->2101
+-->2102
+-->2103
+-->2104
+-->2105
+-->2106
+-->2107
+-->2108
+-->2109
+-->211
+-->2110
+-->2111
+-->2112
+-->2113
+-->2114
+-->2115
+-->2116
+-->2117
+-->2118
+-->2119
+-->212
+-->2120
+-->2121
+-->2122
+-->2123
+-->2124
+-->2125
+-->2126
+-->2127
+-->2128
+-->2129
+-->213
+-->2130
+-->2131
+-->2132
+-->2133
+-->2134
+-->2135
+-->2136
+-->2137
+-->2138
+-->2139
+-->214
+-->2140
+-->2141
+-->2142
+-->2143
+-->2144
+-->2145
+-->2146
+-->2147
+-->2148
+-->2149
+-->215
+-->2150
+-->2151
+-->2152
+-->2153
+-->2154
+-->2155
+-->2156
+-->2157
+-->2158
+-->2159
+-->216
+-->2160
+-->2161
+-->2162
+-->2163
+-->2164
+-->2165
+-->2166
+-->2167
+-->2168
+-->2169
+-->217
+-->2170
+-->2171
+-->2172
+-->2173
+-->2174
+-->2175
+-->2176
+-->2177
+-->2178
+-->2179
+-->218
+-->2180
+-->2181
+-->2182
+-->2183
+-->2184
+-->2185
+-->2186
+-->2187
+-->2188
+-->2189
+-->219
+-->2190
+-->2191
+-->2192
+-->2193
+-->2194
+-->2195
+-->2196
+-->2197
+-->2198
+-->2199
+-->22
+-->220
+-->2200
+-->2201
+-->2202
+-->2203
+-->2204
+-->2205
+-->2206
+-->2207
+-->2208
+-->2209
+-->221
+-->2210
+-->2211
+-->2212
+-->2213
+-->2214
+-->2215
+-->2216
+-->2217
+-->2218
+-->2219
+-->222
+-->2220
+-->2221
+-->2222
+-->2223
+-->2224
+-->2225
+-->2226
+-->2227
+-->2228
+-->2229
+-->223
+-->2230
+-->2231
+-->2232
+-->2233
+-->2234
+-->2235
+-->2236
+-->2237
+-->2238
+-->2239
+-->224
+-->2240
+-->2241
+-->2242
+-->2243
+-->2244
+-->2245
+-->2246
+-->2247
+-->2248
+-->2249
+-->225
+-->2250
+-->2251
+-->2252
+-->2253
+-->2254
+-->2255
+-->2256
+-->2257
+-->2258
+-->2259
+-->226
+-->2260
+-->2261
+-->2262
+-->2263
+-->2264
+-->2265
+-->2266
+-->2267
+-->2268
+-->2269
+-->227
+-->2270
+-->2271
+-->2272
+-->2273
+-->2274
+-->2275
+-->2276
+-->2277
+-->2278
+-->2279
+-->228
+-->2280
+-->2281
+-->2282
+-->2283
+-->2284
+-->2285
+-->2286
+-->2287
+-->2288
+-->2289
+-->229
+-->2290
+-->2291
+-->2292
+-->2293
+-->2294
+-->2295
+-->2296
+-->2297
+-->2298
+-->2299
+-->23
+-->230
+-->2300
+-->2301
+-->2302
+-->2303
+-->2304
+-->2305
+-->2306
+-->2307
+-->2308
+-->2309
+-->231
+-->2310
+-->2311
+-->2312
+-->2313
+-->2314
+-->2315
+-->2316
+-->2317
+-->2318
+-->2319
+-->232
+-->2320
+-->2321
+-->2322
+-->2323
+-->2324
+-->2325
+-->2326
+-->2327
+-->2328
+-->2329
+-->233
+-->2330
+-->2331
+-->2332
+-->2333
+-->2334
+-->2335
+-->2336
+-->2337
+-->2338
+-->2339
+-->234
+-->2340
+-->2341
+-->2342
+-->2343
+-->2344
+-->2345
+-->2346
+-->2347
+-->2348
+-->2349
+-->235
+-->2350
+-->2351
+-->2352
+-->2353
+-->2354
+-->2355
+-->2356
+-->2357
+-->2358
+-->2359
+-->236
+-->2360
+-->2361
+-->2362
+-->2363
+-->2364
+-->2365
+-->2366
+-->2367
+-->2368
+-->2369
+-->237
+-->2370
+-->2371
+-->2372
+-->2373
+-->2374
+-->2375
+-->2376
+-->2377
+-->2378
+-->2379
+-->238
+-->2380
+-->2381
+-->2382
+-->2383
+-->2384
+-->2385
+-->2386
+-->2387
+-->2388
+-->2389
+-->239
+-->2390
+-->2391
+-->2392
+-->2393
+-->2394
+-->2395
+-->2396
+-->2397
+-->2398
+-->2399
+-->24
+-->240
+-->2400
+-->2401
+-->2402
+-->2403
+-->2404
+-->2405
+-->2406
+-->2407
+-->2408
+-->2409
+-->241
+-->2410
+-->2411
+-->2412
+-->2413
+-->2414
+-->2415
+-->2416
+-->2417
+-->2418
+-->2419
+-->242
+-->2420
+-->2421
+-->2422
+-->2423
+-->2424
+-->2425
+-->2426
+-->2427
+-->2428
+-->2429
+-->243
+-->2430
+-->2431
+-->2432
+-->2433
+-->2434
+-->2435
+-->2436
+-->2437
+-->2438
+-->2439
+-->244
+-->2440
+-->2441
+-->2442
+-->2443
+-->2444
+-->2445
+-->2446
+-->2447
+-->2448
+-->2449
+-->245
+-->2450
+-->2451
+-->2452
+-->2453
+-->2454
+-->2455
+-->2456
+-->2457
+-->2458
+-->2459
+-->246
+-->2460
+-->2461
+-->2462
+-->2463
+-->2464
+-->2465
+-->2466
+-->2467
+-->2468
+-->2469
+-->247
+-->2470
+-->2471
+-->2472
+-->2473
+-->2474
+-->2475
+-->2476
+-->2477
+-->2478
+-->2479
+-->248
+-->2480
+-->2481
+-->2482
+-->2483
+-->2484
+-->2485
+-->2486
+-->2487
+-->2488
+-->2489
+-->249
+-->2490
+-->2491
+-->2492
+-->2493
+-->2494
+-->2495
+-->2496
+-->2497
+-->2498
+-->2499
+-->25
+-->250
+-->2500
+-->2501
+-->2502
+-->2503
+-->2504
+-->2505
+-->2506
+-->2507
+-->2508
+-->2509
+-->251
+-->2510
+-->2511
+-->2512
+-->2513
+-->2514
+-->2515
+-->2516
+-->2517
+-->2518
+-->2519
+-->252
+-->2520
+-->2521
+-->2522
+-->2523
+-->2524
+-->2525
+-->2526
+-->2527
+-->2528
+-->2529
+-->253
+-->2530
+-->2531
+-->2532
+-->2533
+-->2534
+-->2535
+-->2536
+-->2537
+-->2538
+-->2539
+-->254
+-->2540
+-->2541
+-->2542
+-->2543
+-->2544
+-->2545
+-->2546
+-->2547
+-->2548
+-->2549
+-->255
+-->2550
+-->2551
+-->2552
+-->2553
+-->2554
+-->2555
+-->2556
+-->2557
+-->2558
+-->2559
+-->256
+-->2560
+-->2561
+-->2562
+-->2563
+-->2564
+-->2565
+-->2566
+-->2567
+-->2568
+-->2569
+-->257
+-->2570
+-->2571
+-->2572
+-->2573
+-->2574
+-->2575
+-->2576
+-->2577
+-->2578
+-->2579
+-->258
+-->2580
+-->2581
+-->2582
+-->2583
+-->2584
+-->2585
+-->2586
+-->2587
+-->2588
+-->2589
+-->259
+-->2590
+-->2591
+-->2592
+-->2593
+-->2594
+-->2595
+-->2596
+-->2597
+-->2598
+-->2599
+-->26
+-->260
+-->2600
+-->2601
+-->2602
+-->2603
+-->2604
+-->2605
+-->2606
+-->2607
+-->2608
+-->2609
+-->261
+-->2610
+-->2611
+-->2612
+-->2613
+-->2614
+-->2615
+-->2616
+-->2617
+-->2618
+-->2619
+-->262
+-->2620
+-->2621
+-->2622
+-->2623
+-->2624
+-->2625
+-->2626
+-->2627
+-->2628
+-->2629
+-->263
+-->2630
+-->2631
+-->2632
+-->2633
+-->2634
+-->2635
+-->2636
+-->2637
+-->2638
+-->2639
+-->264
+-->2640
+-->2641
+-->2642
+-->2643
+-->2644
+-->2645
+-->2646
+-->2647
+-->2648
+-->2649
+-->265
+-->2650
+-->2651
+-->2652
+-->2653
+-->2654
+-->2655
+-->2656
+-->2657
+-->2658
+-->2659
+-->266
+-->2660
+-->2661
+-->2662
+-->2663
+-->2664
+-->2665
+-->2666
+-->2667
+-->2668
+-->2669
+-->267
+-->2670
+-->2671
+-->2672
+-->2673
+-->2674
+-->2675
+-->2676
+-->2677
+-->2678
+-->2679
+-->268
+-->2680
+-->2681
+-->2682
+-->2683
+-->2684
+-->2685
+-->2686
+-->2687
+-->2688
+-->2689
+-->269
+-->2690
+-->2691
+-->2692
+-->2693
+-->2694
+-->2695
+-->2696
+-->2697
+-->2698
+-->2699
+-->27
+-->270
+-->2700
+-->2701
+-->2702
+-->2703
+-->2704
+-->2705
+-->2706
+-->2707
+-->2708
+-->2709
+-->271
+-->2710
+-->2711
+-->2712
+-->2713
+-->2714
+-->2715
+-->2716
+-->2717
+-->2718
+-->2719
+-->272
+-->2720
+-->2721
+-->2722
+-->2723
+-->2724
+-->2725
+-->2726
+-->2727
+-->2728
+-->2729
+-->273
+-->2730
+-->2731
+-->2732
+-->2733
+-->2734
+-->2735
+-->2736
+-->2737
+-->2738
+-->2739
+-->274
+-->2740
+-->2741
+-->2742
+-->2743
+-->2744
+-->2745
+-->2746
+-->2747
+-->2748
+-->2749
+-->275
+-->2750
+-->2751
+-->2752
+-->2753
+-->2754
+-->2755
+-->2756
+-->2757
+-->2758
+-->2759
+-->276
+-->2760
+-->2761
+-->2762
+-->2763
+-->2764
+-->2765
+-->2766
+-->2767
+-->2768
+-->2769
+-->277
+-->2770
+-->2771
+-->2772
+-->2773
+-->2774
+-->2775
+-->2776
+-->2777
+-->2778
+-->2779
+-->278
+-->2780
+-->2781
+-->2782
+-->2783
+-->2784
+-->2785
+-->2786
+-->2787
+-->2788
+-->2789
+-->279
+-->2790
+-->2791
+-->2792
+-->2793
+-->2794
+-->2795
+-->2796
+-->2797
+-->2798
+-->2799
+-->28
+-->280
+-->2800
+-->2801
+-->2802
+-->2803
+-->2804
+-->2805
+-->2806
+-->2807
+-->2808
+-->2809
+-->281
+-->2810
+-->2811
+-->2812
+-->2813
+-->2814
+-->2815
+-->2816
+-->2817
+-->2818
+-->2819
+-->282
+-->2820
+-->2821
+-->2822
+-->2823
+-->2824
+-->2825
+-->2826
+-->2827
+-->2828
+-->2829
+-->283
+-->2830
+-->2831
+-->2832
+-->2833
+-->2834
+-->2835
+-->2836
+-->2837
+-->2838
+-->2839
+-->284
+-->2840
+-->2841
+-->2842
+-->2843
+-->2844
+-->2845
+-->2846
+-->2847
+-->2848
+-->2849
+-->285
+-->2850
+-->2851
+-->2852
+-->2853
+-->2854
+-->2855
+-->2856
+-->2857
+-->2858
+-->2859
+-->286
+-->2860
+-->2861
+-->2862
+-->2863
+-->2864
+-->2865
+-->2866
+-->2867
+-->2868
+-->2869
+-->287
+-->2870
+-->2871
+-->2872
+-->2873
+-->2874
+-->2875
+-->2876
+-->2877
+-->2878
+-->2879
+-->288
+-->2880
+-->2881
+-->2882
+-->2883
+-->2884
+-->2885
+-->2886
+-->2887
+-->2888
+-->2889
+-->289
+-->2890
+-->2891
+-->2892
+-->2893
+-->2894
+-->2895
+-->2896
+-->2897
+-->2898
+-->2899
+-->29
+-->290
+-->2900
+-->2901
+-->2902
+-->2903
+-->2904
+-->2905
+-->2906
+-->2907
+-->2908
+-->2909
+-->291
+-->2910
+-->2911
+-->2912
+-->2913
+-->2914
+-->2915
+-->2916
+-->2917
+-->2918
+-->2919
+-->292
+-->2920
+-->2921
+-->2922
+-->2923
+-->2924
+-->2925
+-->2926
+-->2927
+-->2928
+-->2929
+-->293
+-->2930
+-->2931
+-->2932
+-->2933
+-->2934
+-->2935
+-->2936
+-->2937
+-->2938
+-->2939
+-->294
+-->2940
+-->2941
+-->2942
+-->2943
+-->2944
+-->2945
+-->2946
+-->2947
+-->2948
+-->2949
+-->295
+-->2950
+-->2951
+-->2952
+-->2953
+-->2954
+-->2955
+-->2956
+-->2957
+-->2958
+-->2959
+-->296
+-->2960
+-->2961
+-->2962
+-->2963
+-->2964
+-->2965
+-->2966
+-->2967
+-->2968
+-->2969
+-->297
+-->2970
+-->2971
+-->2972
+-->2973
+-->2974
+-->2975
+-->2976
+-->2977
+-->2978
+-->2979
+-->298
+-->2980
+-->2981
+-->2982
+-->2983
+-->2984
+-->2985
+-->2986
+-->2987
+-->2988
+-->2989
+-->299
+-->2990
+-->2991
+-->2992
+-->2993
+-->2994
+-->2995
+-->2996
+-->2997
+-->2998
+-->2999
+-->3
+-->30
+-->300
+-->3000
+-->3001
+-->3002
+-->3003
+-->3004
+-->3005
+-->3006
+-->3007
+-->3008
+-->3009
+-->301
+-->3010
+-->3011
+-->3012
+-->3013
+-->3014
+-->3015
+-->3016
+-->3017
+-->3018
+-->3019
+-->302
+-->3020
+-->3021
+-->3022
+-->3023
+-->3024
+-->3025
+-->3026
+-->3027
+-->3028
+-->3029
+-->303
+-->3030
+-->3031
+-->3032
+-->3033
+-->3034
+-->3035
+-->3036
+-->3037
+-->3038
+-->3039
+-->304
+-->3040
+-->3041
+-->3042
+-->3043
+-->3044
+-->3045
+-->3046
+-->3047
+-->3048
+-->3049
+-->305
+-->3050
+-->3051
+-->3052
+-->3053
+-->3054
+-->3055
+-->3056
+-->3057
+-->3058
+-->3059
+-->306
+-->3060
+-->3061
+-->3062
+-->3063
+-->3064
+-->3065
+-->3066
+-->3067
+-->3068
+-->3069
+-->307
+-->3070
+-->3071
+-->3072
+-->3073
+-->3074
+-->3075
+-->3076
+-->3077
+-->3078
+-->3079
+-->308
+-->3080
+-->3081
+-->3082
+-->3083
+-->3084
+-->3085
+-->3086
+-->3087
+-->3088
+-->3089
+-->309
+-->3090
+-->3091
+-->3092
+-->3093
+-->3094
+-->3095
+-->3096
+-->3097
+-->3098
+-->3099
+-->31
+-->310
+-->3100
+-->3101
+-->3102
+-->3103
+-->3104
+-->3105
+-->3106
+-->3107
+-->3108
+-->3109
+-->311
+-->3110
+-->3111
+-->3112
+-->3113
+-->3114
+-->3115
+-->3116
+-->3117
+-->3118
+-->3119
+-->312
+-->3120
+-->3121
+-->3122
+-->3123
+-->3124
+-->3125
+-->3126
+-->3127
+-->3128
+-->3129
+-->313
+-->3130
+-->3131
+-->3132
+-->3133
+-->3134
+-->3135
+-->3136
+-->3137
+-->3138
+-->3139
+-->314
+-->3140
+-->3141
+-->3142
+-->3143
+-->3144
+-->3145
+-->3146
+-->3147
+-->3148
+-->3149
+-->315
+-->3150
+-->3151
+-->3152
+-->3153
+-->3154
+-->3155
+-->3156
+-->3157
+-->3158
+-->3159
+-->316
+-->3160
+-->3161
+-->3162
+-->3163
+-->3164
+-->3165
+-->3166
+-->3167
+-->3168
+-->3169
+-->317
+-->3170
+-->3171
+-->3172
+-->3173
+-->3174
+-->3175
+-->3176
+-->3177
+-->3178
+-->3179
+-->318
+-->3180
+-->3181
+-->3182
+-->3183
+-->3184
+-->3185
+-->3186
+-->3187
+-->3188
+-->3189
+-->319
+-->3190
+-->3191
+-->3192
+-->3193
+-->3194
+-->3195
+-->3196
+-->3197
+-->3198
+-->3199
+-->32
+-->320
+-->3200
+-->3201
+-->3202
+-->3203
+-->3204
+-->3205
+-->3206
+-->3207
+-->3208
+-->3209
+-->321
+-->3210
+-->3211
+-->3212
+-->3213
+-->3214
+-->3215
+-->3216
+-->3217
+-->3218
+-->3219
+-->322
+-->3220
+-->3221
+-->3222
+-->3223
+-->3224
+-->3225
+-->3226
+-->3227
+-->3228
+-->3229
+-->323
+-->3230
+-->3231
+-->3232
+-->3233
+-->3234
+-->3235
+-->3236
+-->3237
+-->3238
+-->3239
+-->324
+-->3240
+-->3241
+-->3242
+-->3243
+-->3244
+-->3245
+-->3246
+-->3247
+-->3248
+-->3249
+-->325
+-->3250
+-->3251
+-->3252
+-->3253
+-->3254
+-->3255
+-->3256
+-->3257
+-->3258
+-->3259
+-->326
+-->3260
+-->3261
+-->3262
+-->3263
+-->3264
+-->3265
+-->3266
+-->3267
+-->3268
+-->3269
+-->327
+-->3270
+-->3271
+-->3272
+-->3273
+-->3274
+-->3275
+-->3276
+-->3277
+-->3278
+-->3279
+-->328
+-->3280
+-->3281
+-->3282
+-->3283
+-->3284
+-->3285
+-->3286
+-->3287
+-->3288
+-->3289
+-->329
+-->3290
+-->3291
+-->3292
+-->3293
+-->3294
+-->3295
+-->3296
+-->3297
+-->3298
+-->3299
+-->33
+-->330
+-->3300
+-->3301
+-->3302
+-->3303
+-->3304
+-->3305
+-->3306
+-->3307
+-->3308
+-->3309
+-->331
+-->3310
+-->3311
+-->3312
+-->3313
+-->3314
+-->3315
+-->3316
+-->3317
+-->3318
+-->3319
+-->332
+-->3320
+-->3321
+-->3322
+-->3323
+-->3324
+-->3325
+-->3326
+-->3327
+-->3328
+-->3329
+-->333
+-->3330
+-->3331
+-->3332
+-->3333
+-->3334
+-->3335
+-->3336
+-->3337
+-->3338
+-->3339
+-->334
+-->3340
+-->3341
+-->3342
+-->3343
+-->3344
+-->3345
+-->3346
+-->3347
+-->3348
+-->3349
+-->335
+-->3350
+-->3351
+-->3352
+-->3353
+-->3354
+-->3355
+-->3356
+-->3357
+-->3358
+-->3359
+-->336
+-->3360
+-->3361
+-->3362
+-->3363
+-->3364
+-->3365
+-->3366
+-->3367
+-->3368
+-->3369
+-->337
+-->3370
+-->3371
+-->3372
+-->3373
+-->3374
+-->3375
+-->3376
+-->3377
+-->3378
+-->3379
+-->338
+-->3380
+-->3381
+-->3382
+-->3383
+-->3384
+-->3385
+-->3386
+-->3387
+-->3388
+-->3389
+-->339
+-->3390
+-->3391
+-->3392
+-->3393
+-->3394
+-->3395
+-->3396
+-->3397
+-->3398
+-->3399
+-->34
+-->340
+-->3400
+-->3401
+-->3402
+-->3403
+-->3404
+-->3405
+-->3406
+-->3407
+-->3408
+-->3409
+-->341
+-->3410
+-->3411
+-->3412
+-->3413
+-->3414
+-->3415
+-->3416
+-->3417
+-->3418
+-->3419
+-->342
+-->3420
+-->3421
+-->3422
+-->3423
+-->3424
+-->3425
+-->3426
+-->3427
+-->3428
+-->3429
+-->343
+-->3430
+-->3431
+-->3432
+-->3433
+-->3434
+-->3435
+-->3436
+-->3437
+-->3438
+-->3439
+-->344
+-->3440
+-->3441
+-->3442
+-->3443
+-->3444
+-->3445
+-->3446
+-->3447
+-->3448
+-->3449
+-->345
+-->3450
+-->3451
+-->3452
+-->3453
+-->3454
+-->3455
+-->3456
+-->3457
+-->3458
+-->3459
+-->346
+-->3460
+-->3461
+-->3462
+-->3463
+-->3464
+-->3465
+-->3466
+-->3467
+-->3468
+-->3469
+-->347
+-->3470
+-->3471
+-->3472
+-->3473
+-->3474
+-->3475
+-->3476
+-->3477
+-->3478
+-->3479
+-->348
+-->3480
+-->3481
+-->3482
+-->3483
+-->3484
+-->3485
+-->3486
+-->3487
+-->3488
+-->3489
+-->349
+-->3490
+-->3491
+-->3492
+-->3493
+-->3494
+-->3495
+-->3496
+-->3497
+-->3498
+-->3499
+-->35
+-->350
+-->3500
+-->3501
+-->3502
+-->3503
+-->3504
+-->3505
+-->3506
+-->3507
+-->3508
+-->3509
+-->351
+-->3510
+-->3511
+-->3512
+-->3513
+-->3514
+-->3515
+-->3516
+-->3517
+-->3518
+-->3519
+-->352
+-->3520
+-->3521
+-->3522
+-->3523
+-->3524
+-->3525
+-->3526
+-->3527
+-->3528
+-->3529
+-->353
+-->3530
+-->3531
+-->3532
+-->3533
+-->3534
+-->3535
+-->3536
+-->3537
+-->3538
+-->3539
+-->354
+-->3540
+-->3541
+-->3542
+-->3543
+-->3544
+-->3545
+-->3546
+-->3547
+-->3548
+-->3549
+-->355
+-->3550
+-->3551
+-->3552
+-->3553
+-->3554
+-->3555
+-->3556
+-->3557
+-->3558
+-->3559
+-->356
+-->3560
+-->3561
+-->3562
+-->3563
+-->3564
+-->3565
+-->3566
+-->3567
+-->3568
+-->3569
+-->357
+-->3570
+-->3571
+-->3572
+-->3573
+-->3574
+-->3575
+-->3576
+-->3577
+-->3578
+-->3579
+-->358
+-->3580
+-->3581
+-->3582
+-->3583
+-->3584
+-->3585
+-->3586
+-->3587
+-->3588
+-->3589
+-->359
+-->3590
+-->3591
+-->3592
+-->3593
+-->3594
+-->3595
+-->3596
+-->3597
+-->3598
+-->3599
+-->36
+-->360
+-->3600
+-->3601
+-->3602
+-->3603
+-->3604
+-->3605
+-->3606
+-->3607
+-->3608
+-->3609
+-->361
+-->3610
+-->3611
+-->3612
+-->3613
+-->3614
+-->3615
+-->3616
+-->3617
+-->3618
+-->3619
+-->362
+-->3620
+-->3621
+-->3622
+-->3623
+-->3624
+-->3625
+-->3626
+-->3627
+-->3628
+-->3629
+-->363
+-->3630
+-->3631
+-->3632
+-->3633
+-->3634
+-->3635
+-->3636
+-->3637
+-->3638
+-->3639
+-->364
+-->3640
+-->3641
+-->3642
+-->3643
+-->3644
+-->3645
+-->3646
+-->3647
+-->3648
+-->3649
+-->365
+-->3650
+-->3651
+-->3652
+-->3653
+-->3654
+-->3655
+-->3656
+-->3657
+-->3658
+-->3659
+-->366
+-->3660
+-->3661
+-->3662
+-->3663
+-->3664
+-->3665
+-->3666
+-->3667
+-->3668
+-->3669
+-->367
+-->3670
+-->3671
+-->3672
+-->3673
+-->3674
+-->3675
+-->3676
+-->3677
+-->3678
+-->3679
+-->368
+-->3680
+-->3681
+-->3682
+-->3683
+-->3684
+-->3685
+-->3686
+-->3687
+-->3688
+-->3689
+-->369
+-->3690
+-->3691
+-->3692
+-->3693
+-->3694
+-->3695
+-->3696
+-->3697
+-->3698
+-->3699
+-->37
+-->370
+-->3700
+-->3701
+-->3702
+-->3703
+-->3704
+-->3705
+-->3706
+-->3707
+-->3708
+-->3709
+-->371
+-->3710
+-->3711
+-->3712
+-->3713
+-->3714
+-->3715
+-->3716
+-->3717
+-->3718
+-->3719
+-->372
+-->3720
+-->3721
+-->3722
+-->3723
+-->3724
+-->3725
+-->3726
+-->3727
+-->3728
+-->3729
+-->373
+-->3730
+-->3731
+-->3732
+-->3733
+-->3734
+-->3735
+-->3736
+-->3737
+-->3738
+-->3739
+-->374
+-->3740
+-->3741
+-->3742
+-->3743
+-->3744
+-->3745
+-->3746
+-->3747
+-->3748
+-->3749
+-->375
+-->3750
+-->3751
+-->3752
+-->3753
+-->3754
+-->3755
+-->3756
+-->3757
+-->3758
+-->3759
+-->376
+-->3760
+-->3761
+-->3762
+-->3763
+-->3764
+-->3765
+-->3766
+-->3767
+-->3768
+-->3769
+-->377
+-->3770
+-->3771
+-->3772
+-->3773
+-->3774
+-->3775
+-->3776
+-->3777
+-->3778
+-->3779
+-->378
+-->3780
+-->3781
+-->3782
+-->3783
+-->3784
+-->3785
+-->3786
+-->3787
+-->3788
+-->3789
+-->379
+-->3790
+-->3791
+-->3792
+-->3793
+-->3794
+-->3795
+-->3796
+-->3797
+-->3798
+-->3799
+-->38
+-->380
+-->3800
+-->3801
+-->3802
+-->3803
+-->3804
+-->3805
+-->3806
+-->3807
+-->3808
+-->3809
+-->381
+-->3810
+-->3811
+-->3812
+-->3813
+-->3814
+-->3815
+-->3816
+-->3817
+-->3818
+-->3819
+-->382
+-->3820
+-->3821
+-->3822
+-->3823
+-->3824
+-->3825
+-->3826
+-->3827
+-->3828
+-->3829
+-->383
+-->3830
+-->3831
+-->3832
+-->3833
+-->3834
+-->3835
+-->3836
+-->3837
+-->3838
+-->3839
+-->384
+-->3840
+-->3841
+-->3842
+-->3843
+-->3844
+-->3845
+-->3846
+-->3847
+-->3848
+-->3849
+-->385
+-->3850
+-->3851
+-->3852
+-->3853
+-->3854
+-->3855
+-->3856
+-->3857
+-->3858
+-->3859
+-->386
+-->3860
+-->3861
+-->3862
+-->3863
+-->3864
+-->3865
+-->3866
+-->3867
+-->3868
+-->3869
+-->387
+-->3870
+-->3871
+-->3872
+-->3873
+-->3874
+-->3875
+-->3876
+-->3877
+-->3878
+-->3879
+-->388
+-->3880
+-->3881
+-->3882
+-->3883
+-->3884
+-->3885
+-->3886
+-->3887
+-->3888
+-->3889
+-->389
+-->3890
+-->3891
+-->3892
+-->3893
+-->3894
+-->3895
+-->3896
+-->3897
+-->3898
+-->3899
+-->39
+-->390
+-->3900
+-->3901
+-->3902
+-->3903
+-->3904
+-->3905
+-->3906
+-->3907
+-->3908
+-->3909
+-->391
+-->3910
+-->3911
+-->3912
+-->3913
+-->3914
+-->3915
+-->3916
+-->3917
+-->3918
+-->3919
+-->392
+-->3920
+-->3921
+-->3922
+-->3923
+-->3924
+-->3925
+-->3926
+-->3927
+-->3928
+-->3929
+-->393
+-->3930
+-->3931
+-->3932
+-->3933
+-->3934
+-->3935
+-->3936
+-->3937
+-->3938
+-->3939
+-->394
+-->3940
+-->3941
+-->3942
+-->3943
+-->3944
+-->3945
+-->3946
+-->3947
+-->3948
+-->3949
+-->395
+-->3950
+-->3951
+-->3952
+-->3953
+-->3954
+-->3955
+-->3956
+-->3957
+-->3958
+-->3959
+-->396
+-->3960
+-->3961
+-->3962
+-->3963
+-->3964
+-->3965
+-->3966
+-->3967
+-->3968
+-->3969
+-->397
+-->3970
+-->3971
+-->3972
+-->3973
+-->3974
+-->3975
+-->3976
+-->3977
+-->3978
+-->3979
+-->398
+-->3980
+-->3981
+-->3982
+-->3983
+-->3984
+-->3985
+-->3986
+-->3987
+-->3988
+-->3989
+-->399
+-->3990
+-->3991
+-->3992
+-->3993
+-->3994
+-->3995
+-->3996
+-->3997
+-->3998
+-->3999
+-->4
+-->40
+-->400
+-->4000
+-->4001
+-->4002
+-->4003
+-->4004
+-->4005
+-->4006
+-->4007
+-->4008
+-->4009
+-->401
+-->4010
+-->4011
+-->4012
+-->4013
+-->4014
+-->4015
+-->4016
+-->4017
+-->4018
+-->4019
+-->402
+-->4020
+-->4021
+-->4022
+-->4023
+-->4024
+-->4025
+-->4026
+-->4027
+-->4028
+-->4029
+-->403
+-->4030
+-->4031
+-->4032
+-->4033
+-->4034
+-->4035
+-->4036
+-->4037
+-->4038
+-->4039
+-->404
+-->4040
+-->4041
+-->4042
+-->4043
+-->4044
+-->4045
+-->4046
+-->4047
+-->4048
+-->4049
+-->405
+-->4050
+-->4051
+-->4052
+-->4053
+-->4054
+-->4055
+-->4056
+-->4057
+-->4058
+-->4059
+-->406
+-->4060
+-->4061
+-->4062
+-->4063
+-->4064
+-->4065
+-->4066
+-->4067
+-->4068
+-->4069
+-->407
+-->4070
+-->4071
+-->4072
+-->4073
+-->4074
+-->4075
+-->4076
+-->4077
+-->4078
+-->4079
+-->408
+-->4080
+-->4081
+-->4082
+-->4083
+-->4084
+-->4085
+-->4086
+-->4087
+-->4088
+-->4089
+-->409
+-->4090
+-->4091
+-->4092
+-->4093
+-->4094
+-->4095
+-->4096
+-->4097
+-->4098
+-->4099
+-->41
+-->410
+-->4100
+-->4101
+-->4102
+-->4103
+-->4104
+-->4105
+-->4106
+-->4107
+-->4108
+-->4109
+-->411
+-->4110
+-->4111
+-->4112
+-->4113
+-->4114
+-->4115
+-->4116
+-->4117
+-->4118
+-->4119
+-->412
+-->4120
+-->4121
+-->4122
+-->4123
+-->4124
+-->4125
+-->4126
+-->4127
+-->4128
+-->4129
+-->413
+-->4130
+-->4131
+-->4132
+-->4133
+-->4134
+-->4135
+-->4136
+-->4137
+-->4138
+-->4139
+-->414
+-->4140
+-->4141
+-->4142
+-->4143
+-->4144
+-->4145
+-->4146
+-->4147
+-->4148
+-->4149
+-->415
+-->4150
+-->4151
+-->4152
+-->4153
+-->4154
+-->4155
+-->4156
+-->4157
+-->4158
+-->4159
+-->416
+-->4160
+-->4161
+-->4162
+-->4163
+-->4164
+-->4165
+-->4166
+-->4167
+-->4168
+-->4169
+-->417
+-->4170
+-->4171
+-->4172
+-->4173
+-->4174
+-->4175
+-->4176
+-->4177
+-->4178
+-->4179
+-->418
+-->4180
+-->4181
+-->4182
+-->4183
+-->4184
+-->4185
+-->4186
+-->4187
+-->4188
+-->4189
+-->419
+-->4190
+-->4191
+-->4192
+-->4193
+-->4194
+-->4195
+-->4196
+-->4197
+-->4198
+-->4199
+-->42
+-->420
+-->4200
+-->4201
+-->4202
+-->4203
+-->4204
+-->4205
+-->4206
+-->4207
+-->4208
+-->4209
+-->421
+-->4210
+-->4211
+-->4212
+-->4213
+-->4214
+-->4215
+-->4216
+-->4217
+-->4218
+-->4219
+-->422
+-->4220
+-->4221
+-->4222
+-->4223
+-->4224
+-->4225
+-->4226
+-->4227
+-->4228
+-->4229
+-->423
+-->4230
+-->4231
+-->4232
+-->4233
+-->4234
+-->4235
+-->4236
+-->4237
+-->4238
+-->4239
+-->424
+-->4240
+-->4241
+-->4242
+-->4243
+-->4244
+-->4245
+-->4246
+-->4247
+-->4248
+-->4249
+-->425
+-->4250
+-->4251
+-->4252
+-->4253
+-->4254
+-->4255
+-->4256
+-->4257
+-->4258
+-->4259
+-->426
+-->4260
+-->4261
+-->4262
+-->4263
+-->4264
+-->4265
+-->4266
+-->4267
+-->4268
+-->4269
+-->427
+-->4270
+-->4271
+-->4272
+-->4273
+-->4274
+-->4275
+-->4276
+-->4277
+-->4278
+-->4279
+-->428
+-->4280
+-->4281
+-->4282
+-->4283
+-->4284
+-->4285
+-->4286
+-->4287
+-->4288
+-->4289
+-->429
+-->4290
+-->4291
+-->4292
+-->4293
+-->4294
+-->4295
+-->4296
+-->4297
+-->4298
+-->4299
+-->43
+-->430
+-->4300
+-->4301
+-->4302
+-->4303
+-->4304
+-->4305
+-->4306
+-->4307
+-->4308
+-->4309
+-->431
+-->4310
+-->4311
+-->4312
+-->4313
+-->4314
+-->4315
+-->4316
+-->4317
+-->4318
+-->4319
+-->432
+-->4320
+-->4321
+-->4322
+-->4323
+-->4324
+-->4325
+-->4326
+-->4327
+-->4328
+-->4329
+-->433
+-->4330
+-->4331
+-->4332
+-->4333
+-->4334
+-->4335
+-->4336
+-->4337
+-->4338
+-->4339
+-->434
+-->4340
+-->4341
+-->4342
+-->4343
+-->4344
+-->4345
+-->4346
+-->4347
+-->4348
+-->4349
+-->435
+-->4350
+-->4351
+-->4352
+-->4353
+-->4354
+-->4355
+-->4356
+-->4357
+-->4358
+-->4359
+-->436
+-->4360
+-->4361
+-->4362
+-->4363
+-->4364
+-->4365
+-->4366
+-->4367
+-->4368
+-->4369
+-->437
+-->4370
+-->4371
+-->4372
+-->4373
+-->4374
+-->4375
+-->4376
+-->4377
+-->4378
+-->4379
+-->438
+-->4380
+-->4381
+-->4382
+-->4383
+-->4384
+-->4385
+-->4386
+-->4387
+-->4388
+-->4389
+-->439
+-->4390
+-->4391
+-->4392
+-->4393
+-->4394
+-->4395
+-->4396
+-->4397
+-->4398
+-->4399
+-->44
+-->440
+-->4400
+-->4401
+-->4402
+-->4403
+-->4404
+-->4405
+-->4406
+-->4407
+-->4408
+-->4409
+-->441
+-->4410
+-->4411
+-->4412
+-->4413
+-->4414
+-->4415
+-->4416
+-->4417
+-->4418
+-->4419
+-->442
+-->4420
+-->4421
+-->4422
+-->4423
+-->4424
+-->4425
+-->4426
+-->4427
+-->4428
+-->4429
+-->443
+-->4430
+-->4431
+-->4432
+-->4433
+-->4434
+-->4435
+-->4436
+-->4437
+-->4438
+-->4439
+-->444
+-->4440
+-->4441
+-->4442
+-->4443
+-->4444
+-->4445
+-->4446
+-->4447
+-->4448
+-->4449
+-->445
+-->4450
+-->4451
+-->4452
+-->4453
+-->4454
+-->4455
+-->4456
+-->4457
+-->4458
+-->4459
+-->446
+-->4460
+-->4461
+-->4462
+-->4463
+-->4464
+-->4465
+-->4466
+-->4467
+-->4468
+-->4469
+-->447
+-->4470
+-->4471
+-->4472
+-->4473
+-->4474
+-->4475
+-->4476
+-->4477
+-->4478
+-->4479
+-->448
+-->4480
+-->4481
+-->4482
+-->4483
+-->4484
+-->4485
+-->4486
+-->4487
+-->4488
+-->4489
+-->449
+-->4490
+-->4491
+-->4492
+-->4493
+-->4494
+-->4495
+-->4496
+-->4497
+-->4498
+-->4499
+-->45
+-->450
+-->4500
+-->4501
+-->4502
+-->4503
+-->4504
+-->4505
+-->4506
+-->4507
+-->4508
+-->4509
+-->451
+-->4510
+-->4511
+-->4512
+-->4513
+-->4514
+-->4515
+-->4516
+-->4517
+-->4518
+-->4519
+-->452
+-->4520
+-->4521
+-->4522
+-->4523
+-->4524
+-->4525
+-->4526
+-->4527
+-->4528
+-->4529
+-->453
+-->4530
+-->4531
+-->4532
+-->4533
+-->4534
+-->4535
+-->4536
+-->4537
+-->4538
+-->4539
+-->454
+-->4540
+-->4541
+-->4542
+-->4543
+-->4544
+-->4545
+-->4546
+-->4547
+-->4548
+-->4549
+-->455
+-->4550
+-->4551
+-->4552
+-->4553
+-->4554
+-->4555
+-->4556
+-->4557
+-->4558
+-->4559
+-->456
+-->4560
+-->4561
+-->4562
+-->4563
+-->4564
+-->4565
+-->4566
+-->4567
+-->4568
+-->4569
+-->457
+-->4570
+-->4571
+-->4572
+-->4573
+-->4574
+-->4575
+-->4576
+-->4577
+-->4578
+-->4579
+-->458
+-->4580
+-->4581
+-->4582
+-->4583
+-->4584
+-->4585
+-->4586
+-->4587
+-->4588
+-->4589
+-->459
+-->4590
+-->4591
+-->4592
+-->4593
+-->4594
+-->4595
+-->4596
+-->4597
+-->4598
+-->4599
+-->46
+-->460
+-->4600
+-->4601
+-->4602
+-->4603
+-->4604
+-->4605
+-->4606
+-->4607
+-->4608
+-->4609
+-->461
+-->4610
+-->4611
+-->4612
+-->4613
+-->4614
+-->4615
+-->4616
+-->4617
+-->4618
+-->4619
+-->462
+-->4620
+-->4621
+-->4622
+-->4623
+-->4624
+-->4625
+-->4626
+-->4627
+-->4628
+-->4629
+-->463
+-->4630
+-->4631
+-->4632
+-->4633
+-->4634
+-->4635
+-->4636
+-->4637
+-->4638
+-->4639
+-->464
+-->4640
+-->4641
+-->4642
+-->4643
+-->4644
+-->4645
+-->4646
+-->4647
+-->4648
+-->4649
+-->465
+-->4650
+-->4651
+-->4652
+-->4653
+-->4654
+-->4655
+-->4656
+-->4657
+-->4658
+-->4659
+-->466
+-->4660
+-->4661
+-->4662
+-->4663
+-->4664
+-->4665
+-->4666
+-->4667
+-->4668
+-->4669
+-->467
+-->4670
+-->4671
+-->4672
+-->4673
+-->4674
+-->4675
+-->4676
+-->4677
+-->4678
+-->4679
+-->468
+-->4680
+-->4681
+-->4682
+-->4683
+-->4684
+-->4685
+-->4686
+-->4687
+-->4688
+-->4689
+-->469
+-->4690
+-->4691
+-->4692
+-->4693
+-->4694
+-->4695
+-->4696
+-->4697
+-->4698
+-->4699
+-->47
+-->470
+-->4700
+-->4701
+-->4702
+-->4703
+-->4704
+-->4705
+-->4706
+-->4707
+-->4708
+-->4709
+-->471
+-->4710
+-->4711
+-->4712
+-->4713
+-->4714
+-->4715
+-->4716
+-->4717
+-->4718
+-->4719
+-->472
+-->4720
+-->4721
+-->4722
+-->4723
+-->4724
+-->4725
+-->4726
+-->4727
+-->4728
+-->4729
+-->473
+-->4730
+-->4731
+-->4732
+-->4733
+-->4734
+-->4735
+-->4736
+-->4737
+-->4738
+-->4739
+-->474
+-->4740
+-->4741
+-->4742
+-->4743
+-->4744
+-->4745
+-->4746
+-->4747
+-->4748
+-->4749
+-->475
+-->4750
+-->4751
+-->4752
+-->4753
+-->4754
+-->4755
+-->4756
+-->4757
+-->4758
+-->4759
+-->476
+-->4760
+-->4761
+-->4762
+-->4763
+-->4764
+-->4765
+-->4766
+-->4767
+-->4768
+-->4769
+-->477
+-->4770
+-->4771
+-->4772
+-->4773
+-->4774
+-->4775
+-->4776
+-->4777
+-->4778
+-->4779
+-->478
+-->4780
+-->4781
+-->4782
+-->4783
+-->4784
+-->4785
+-->4786
+-->4787
+-->4788
+-->4789
+-->479
+-->4790
+-->4791
+-->4792
+-->4793
+-->4794
+-->4795
+-->4796
+-->4797
+-->4798
+-->4799
+-->48
+-->480
+-->4800
+-->4801
+-->4802
+-->4803
+-->4804
+-->4805
+-->4806
+-->4807
+-->4808
+-->4809
+-->481
+-->4810
+-->4811
+-->4812
+-->4813
+-->4814
+-->4815
+-->4816
+-->4817
+-->4818
+-->4819
+-->482
+-->4820
+-->4821
+-->4822
+-->4823
+-->4824
+-->4825
+-->4826
+-->4827
+-->4828
+-->4829
+-->483
+-->4830
+-->4831
+-->4832
+-->4833
+-->4834
+-->4835
+-->4836
+-->4837
+-->4838
+-->4839
+-->484
+-->4840
+-->4841
+-->4842
+-->4843
+-->4844
+-->4845
+-->4846
+-->4847
+-->4848
+-->4849
+-->485
+-->4850
+-->4851
+-->4852
+-->4853
+-->4854
+-->4855
+-->4856
+-->4857
+-->4858
+-->4859
+-->486
+-->4860
+-->4861
+-->4862
+-->4863
+-->4864
+-->4865
+-->4866
+-->4867
+-->4868
+-->4869
+-->487
+-->4870
+-->4871
+-->4872
+-->4873
+-->4874
+-->4875
+-->4876
+-->4877
+-->4878
+-->4879
+-->488
+-->4880
+-->4881
+-->4882
+-->4883
+-->4884
+-->4885
+-->4886
+-->4887
+-->4888
+-->4889
+-->489
+-->4890
+-->4891
+-->4892
+-->4893
+-->4894
+-->4895
+-->4896
+-->4897
+-->4898
+-->4899
+-->49
+-->490
+-->4900
+-->4901
+-->4902
+-->4903
+-->4904
+-->4905
+-->4906
+-->4907
+-->4908
+-->4909
+-->491
+-->4910
+-->4911
+-->4912
+-->4913
+-->4914
+-->4915
+-->4916
+-->4917
+-->4918
+-->4919
+-->492
+-->4920
+-->4921
+-->4922
+-->4923
+-->4924
+-->4925
+-->4926
+-->4927
+-->4928
+-->4929
+-->493
+-->4930
+-->4931
+-->4932
+-->4933
+-->4934
+-->4935
+-->4936
+-->4937
+-->4938
+-->4939
+-->494
+-->4940
+-->4941
+-->4942
+-->4943
+-->4944
+-->4945
+-->4946
+-->4947
+-->4948
+-->4949
+-->495
+-->4950
+-->4951
+-->4952
+-->4953
+-->4954
+-->4955
+-->4956
+-->4957
+-->4958
+-->4959
+-->496
+-->4960
+-->4961
+-->4962
+-->4963
+-->4964
+-->4965
+-->4966
+-->4967
+-->4968
+-->4969
+-->497
+-->4970
+-->4971
+-->4972
+-->4973
+-->4974
+-->4975
+-->4976
+-->4977
+-->4978
+-->4979
+-->498
+-->4980
+-->4981
+-->4982
+-->4983
+-->4984
+-->4985
+-->4986
+-->4987
+-->4988
+-->4989
+-->499
+-->4990
+-->4991
+-->4992
+-->4993
+-->4994
+-->4995
+-->4996
+-->4997
+-->4998
+-->4999
+-->5
+-->50
+-->500
+-->5000
+-->5001
+-->5002
+-->5003
+-->5004
+-->5005
+-->5006
+-->5007
+-->5008
+-->5009
+-->501
+-->5010
+-->5011
+-->5012
+-->5013
+-->5014
+-->5015
+-->5016
+-->5017
+-->5018
+-->5019
+-->502
+-->5020
+-->5021
+-->5022
+-->5023
+-->5024
+-->5025
+-->5026
+-->5027
+-->5028
+-->5029
+-->503
+-->5030
+-->5031
+-->5032
+-->5033
+-->5034
+-->5035
+-->5036
+-->5037
+-->5038
+-->5039
+-->504
+-->5040
+-->5041
+-->5042
+-->5043
+-->5044
+-->5045
+-->5046
+-->5047
+-->5048
+-->5049
+-->505
+-->5050
+-->5051
+-->5052
+-->5053
+-->5054
+-->5055
+-->5056
+-->5057
+-->5058
+-->5059
+-->506
+-->5060
+-->5061
+-->5062
+-->5063
+-->5064
+-->5065
+-->5066
+-->5067
+-->5068
+-->5069
+-->507
+-->5070
+-->5071
+-->5072
+-->5073
+-->5074
+-->5075
+-->5076
+-->5077
+-->5078
+-->5079
+-->508
+-->5080
+-->5081
+-->5082
+-->5083
+-->5084
+-->5085
+-->5086
+-->5087
+-->5088
+-->5089
+-->509
+-->5090
+-->5091
+-->5092
+-->5093
+-->5094
+-->5095
+-->5096
+-->5097
+-->5098
+-->5099
+-->51
+-->510
+-->5100
+-->5101
+-->5102
+-->5103
+-->5104
+-->5105
+-->5106
+-->5107
+-->5108
+-->5109
+-->511
+-->5110
+-->5111
+-->5112
+-->5113
+-->5114
+-->5115
+-->5116
+-->5117
+-->5118
+-->5119
+-->512
+-->5120
+-->5121
+-->5122
+-->5123
+-->5124
+-->5125
+-->5126
+-->5127
+-->5128
+-->5129
+-->513
+-->5130
+-->5131
+-->5132
+-->5133
+-->5134
+-->5135
+-->5136
+-->5137
+-->5138
+-->5139
+-->514
+-->5140
+-->5141
+-->5142
+-->5143
+-->5144
+-->5145
+-->5146
+-->5147
+-->5148
+-->5149
+-->515
+-->5150
+-->5151
+-->5152
+-->5153
+-->5154
+-->5155
+-->5156
+-->5157
+-->5158
+-->5159
+-->516
+-->5160
+-->5161
+-->5162
+-->5163
+-->5164
+-->5165
+-->5166
+-->5167
+-->5168
+-->5169
+-->517
+-->5170
+-->5171
+-->5172
+-->5173
+-->5174
+-->5175
+-->5176
+-->5177
+-->5178
+-->5179
+-->518
+-->5180
+-->5181
+-->5182
+-->5183
+-->5184
+-->5185
+-->5186
+-->5187
+-->5188
+-->5189
+-->519
+-->5190
+-->5191
+-->5192
+-->5193
+-->5194
+-->5195
+-->5196
+-->5197
+-->5198
+-->5199
+-->52
+-->520
+-->5200
+-->5201
+-->5202
+-->5203
+-->5204
+-->5205
+-->5206
+-->5207
+-->5208
+-->5209
+-->521
+-->5210
+-->5211
+-->5212
+-->5213
+-->5214
+-->5215
+-->5216
+-->5217
+-->5218
+-->5219
+-->522
+-->5220
+-->5221
+-->5222
+-->5223
+-->5224
+-->5225
+-->5226
+-->5227
+-->5228
+-->5229
+-->523
+-->5230
+-->5231
+-->5232
+-->5233
+-->5234
+-->5235
+-->5236
+-->5237
+-->5238
+-->5239
+-->524
+-->5240
+-->5241
+-->5242
+-->5243
+-->5244
+-->5245
+-->5246
+-->5247
+-->5248
+-->5249
+-->525
+-->5250
+-->5251
+-->5252
+-->5253
+-->5254
+-->5255
+-->5256
+-->5257
+-->5258
+-->5259
+-->526
+-->5260
+-->5261
+-->5262
+-->5263
+-->5264
+-->5265
+-->5266
+-->5267
+-->5268
+-->5269
+-->527
+-->5270
+-->5271
+-->5272
+-->5273
+-->5274
+-->5275
+-->5276
+-->5277
+-->5278
+-->5279
+-->528
+-->5280
+-->5281
+-->5282
+-->5283
+-->5284
+-->5285
+-->5286
+-->5287
+-->5288
+-->5289
+-->529
+-->5290
+-->5291
+-->5292
+-->5293
+-->5294
+-->5295
+-->5296
+-->5297
+-->5298
+-->5299
+-->53
+-->530
+-->5300
+-->5301
+-->5302
+-->5303
+-->5304
+-->5305
+-->5306
+-->5307
+-->5308
+-->5309
+-->531
+-->5310
+-->5311
+-->5312
+-->5313
+-->5314
+-->5315
+-->5316
+-->5317
+-->5318
+-->5319
+-->532
+-->5320
+-->5321
+-->5322
+-->5323
+-->5324
+-->5325
+-->5326
+-->5327
+-->5328
+-->5329
+-->533
+-->5330
+-->5331
+-->5332
+-->5333
+-->5334
+-->5335
+-->5336
+-->5337
+-->5338
+-->5339
+-->534
+-->5340
+-->5341
+-->5342
+-->5343
+-->5344
+-->5345
+-->5346
+-->5347
+-->5348
+-->5349
+-->535
+-->5350
+-->5351
+-->5352
+-->5353
+-->5354
+-->5355
+-->5356
+-->5357
+-->5358
+-->5359
+-->536
+-->5360
+-->5361
+-->5362
+-->5363
+-->5364
+-->5365
+-->5366
+-->5367
+-->5368
+-->5369
+-->537
+-->5370
+-->5371
+-->5372
+-->5373
+-->5374
+-->5375
+-->5376
+-->5377
+-->5378
+-->5379
+-->538
+-->5380
+-->5381
+-->5382
+-->5383
+-->5384
+-->5385
+-->5386
+-->5387
+-->5388
+-->5389
+-->539
+-->5390
+-->5391
+-->5392
+-->5393
+-->5394
+-->5395
+-->5396
+-->5397
+-->5398
+-->5399
+-->54
+-->540
+-->5400
+-->5401
+-->5402
+-->5403
+-->5404
+-->5405
+-->5406
+-->5407
+-->5408
+-->5409
+-->541
+-->5410
+-->5411
+-->5412
+-->5413
+-->5414
+-->5415
+-->5416
+-->5417
+-->5418
+-->5419
+-->542
+-->5420
+-->5421
+-->5422
+-->5423
+-->5424
+-->5425
+-->5426
+-->5427
+-->5428
+-->5429
+-->543
+-->5430
+-->5431
+-->5432
+-->5433
+-->5434
+-->5435
+-->5436
+-->5437
+-->5438
+-->5439
+-->544
+-->5440
+-->5441
+-->5442
+-->5443
+-->5444
+-->5445
+-->5446
+-->5447
+-->5448
+-->5449
+-->545
+-->5450
+-->5451
+-->5452
+-->5453
+-->5454
+-->5455
+-->5456
+-->5457
+-->5458
+-->5459
+-->546
+-->5460
+-->5461
+-->5462
+-->5463
+-->5464
+-->5465
+-->5466
+-->5467
+-->5468
+-->5469
+-->547
+-->5470
+-->5471
+-->5472
+-->5473
+-->5474
+-->5475
+-->5476
+-->5477
+-->5478
+-->5479
+-->548
+-->5480
+-->5481
+-->5482
+-->5483
+-->5484
+-->5485
+-->5486
+-->5487
+-->5488
+-->5489
+-->549
+-->5490
+-->5491
+-->5492
+-->5493
+-->5494
+-->5495
+-->5496
+-->5497
+-->5498
+-->5499
+-->55
+-->550
+-->5500
+-->5501
+-->5502
+-->5503
+-->5504
+-->5505
+-->5506
+-->5507
+-->5508
+-->5509
+-->551
+-->5510
+-->5511
+-->5512
+-->5513
+-->5514
+-->5515
+-->5516
+-->5517
+-->5518
+-->5519
+-->552
+-->5520
+-->5521
+-->5522
+-->5523
+-->5524
+-->5525
+-->5526
+-->5527
+-->5528
+-->5529
+-->553
+-->5530
+-->5531
+-->5532
+-->5533
+-->5534
+-->5535
+-->5536
+-->5537
+-->5538
+-->5539
+-->554
+-->5540
+-->5541
+-->5542
+-->5543
+-->5544
+-->5545
+-->5546
+-->5547
+-->5548
+-->5549
+-->555
+-->5550
+-->5551
+-->5552
+-->5553
+-->5554
+-->5555
+-->5556
+-->5557
+-->5558
+-->5559
+-->556
+-->5560
+-->5561
+-->5562
+-->5563
+-->5564
+-->5565
+-->5566
+-->5567
+-->5568
+-->5569
+-->557
+-->5570
+-->5571
+-->5572
+-->5573
+-->5574
+-->5575
+-->5576
+-->5577
+-->5578
+-->5579
+-->558
+-->5580
+-->5581
+-->5582
+-->5583
+-->5584
+-->5585
+-->5586
+-->5587
+-->5588
+-->5589
+-->559
+-->5590
+-->5591
+-->5592
+-->5593
+-->5594
+-->5595
+-->5596
+-->5597
+-->5598
+-->5599
+-->56
+-->560
+-->5600
+-->5601
+-->5602
+-->5603
+-->5604
+-->5605
+-->5606
+-->5607
+-->5608
+-->5609
+-->561
+-->5610
+-->5611
+-->5612
+-->5613
+-->5614
+-->5615
+-->5616
+-->5617
+-->5618
+-->5619
+-->562
+-->5620
+-->5621
+-->5622
+-->5623
+-->5624
+-->5625
+-->5626
+-->5627
+-->5628
+-->5629
+-->563
+-->5630
+-->5631
+-->5632
+-->5633
+-->5634
+-->5635
+-->5636
+-->5637
+-->5638
+-->5639
+-->564
+-->5640
+-->5641
+-->5642
+-->5643
+-->5644
+-->5645
+-->5646
+-->5647
+-->5648
+-->5649
+-->565
+-->5650
+-->5651
+-->5652
+-->5653
+-->5654
+-->5655
+-->5656
+-->5657
+-->5658
+-->5659
+-->566
+-->5660
+-->5661
+-->5662
+-->5663
+-->5664
+-->5665
+-->5666
+-->5667
+-->5668
+-->5669
+-->567
+-->5670
+-->5671
+-->5672
+-->5673
+-->5674
+-->5675
+-->5676
+-->5677
+-->5678
+-->5679
+-->568
+-->5680
+-->5681
+-->5682
+-->5683
+-->5684
+-->5685
+-->5686
+-->5687
+-->5688
+-->5689
+-->569
+-->5690
+-->5691
+-->5692
+-->5693
+-->5694
+-->5695
+-->5696
+-->5697
+-->5698
+-->5699
+-->57
+-->570
+-->5700
+-->5701
+-->5702
+-->5703
+-->5704
+-->5705
+-->5706
+-->5707
+-->5708
+-->5709
+-->571
+-->5710
+-->5711
+-->5712
+-->5713
+-->5714
+-->5715
+-->5716
+-->5717
+-->5718
+-->5719
+-->572
+-->5720
+-->5721
+-->5722
+-->5723
+-->5724
+-->5725
+-->5726
+-->5727
+-->5728
+-->5729
+-->573
+-->5730
+-->5731
+-->5732
+-->5733
+-->5734
+-->5735
+-->5736
+-->5737
+-->5738
+-->5739
+-->574
+-->5740
+-->5741
+-->5742
+-->5743
+-->5744
+-->5745
+-->5746
+-->5747
+-->5748
+-->5749
+-->575
+-->5750
+-->5751
+-->5752
+-->5753
+-->5754
+-->5755
+-->5756
+-->5757
+-->5758
+-->5759
+-->576
+-->5760
+-->5761
+-->5762
+-->5763
+-->5764
+-->5765
+-->5766
+-->5767
+-->5768
+-->5769
+-->577
+-->5770
+-->5771
+-->5772
+-->5773
+-->5774
+-->5775
+-->5776
+-->5777
+-->5778
+-->5779
+-->578
+-->5780
+-->5781
+-->5782
+-->5783
+-->5784
+-->5785
+-->5786
+-->5787
+-->5788
+-->5789
+-->579
+-->5790
+-->5791
+-->5792
+-->5793
+-->5794
+-->5795
+-->5796
+-->5797
+-->5798
+-->5799
+-->58
+-->580
+-->5800
+-->5801
+-->5802
+-->5803
+-->5804
+-->5805
+-->5806
+-->5807
+-->5808
+-->5809
+-->581
+-->5810
+-->5811
+-->5812
+-->5813
+-->5814
+-->5815
+-->5816
+-->5817
+-->5818
+-->5819
+-->582
+-->5820
+-->5821
+-->5822
+-->5823
+-->5824
+-->5825
+-->5826
+-->5827
+-->5828
+-->5829
+-->583
+-->5830
+-->5831
+-->5832
+-->5833
+-->5834
+-->5835
+-->5836
+-->5837
+-->5838
+-->5839
+-->584
+-->5840
+-->5841
+-->5842
+-->5843
+-->5844
+-->5845
+-->5846
+-->5847
+-->5848
+-->5849
+-->585
+-->5850
+-->5851
+-->5852
+-->5853
+-->5854
+-->5855
+-->5856
+-->5857
+-->5858
+-->5859
+-->586
+-->5860
+-->5861
+-->5862
+-->5863
+-->5864
+-->5865
+-->5866
+-->5867
+-->5868
+-->5869
+-->587
+-->5870
+-->5871
+-->5872
+-->5873
+-->5874
+-->5875
+-->5876
+-->5877
+-->5878
+-->5879
+-->588
+-->5880
+-->5881
+-->5882
+-->5883
+-->5884
+-->5885
+-->5886
+-->5887
+-->5888
+-->5889
+-->589
+-->5890
+-->5891
+-->5892
+-->5893
+-->5894
+-->5895
+-->5896
+-->5897
+-->5898
+-->5899
+-->59
+-->590
+-->5900
+-->5901
+-->5902
+-->5903
+-->5904
+-->5905
+-->5906
+-->5907
+-->5908
+-->5909
+-->591
+-->5910
+-->5911
+-->5912
+-->5913
+-->5914
+-->5915
+-->5916
+-->5917
+-->5918
+-->5919
+-->592
+-->5920
+-->5921
+-->5922
+-->5923
+-->5924
+-->5925
+-->5926
+-->5927
+-->5928
+-->5929
+-->593
+-->5930
+-->5931
+-->5932
+-->5933
+-->5934
+-->5935
+-->5936
+-->5937
+-->5938
+-->5939
+-->594
+-->5940
+-->5941
+-->5942
+-->5943
+-->5944
+-->5945
+-->5946
+-->5947
+-->5948
+-->5949
+-->595
+-->5950
+-->5951
+-->5952
+-->5953
+-->5954
+-->5955
+-->5956
+-->5957
+-->5958
+-->5959
+-->596
+-->5960
+-->5961
+-->5962
+-->5963
+-->5964
+-->5965
+-->5966
+-->5967
+-->5968
+-->5969
+-->597
+-->5970
+-->5971
+-->5972
+-->5973
+-->5974
+-->5975
+-->5976
+-->5977
+-->5978
+-->5979
+-->598
+-->5980
+-->5981
+-->5982
+-->5983
+-->5984
+-->5985
+-->5986
+-->5987
+-->5988
+-->5989
+-->599
+-->5990
+-->5991
+-->5992
+-->5993
+-->5994
+-->5995
+-->5996
+-->5997
+-->5998
+-->5999
+-->6
+-->60
+-->600
+-->6000
+-->6001
+-->6002
+-->6003
+-->6004
+-->6005
+-->6006
+-->6007
+-->6008
+-->6009
+-->601
+-->6010
+-->6011
+-->6012
+-->6013
+-->6014
+-->6015
+-->6016
+-->6017
+-->6018
+-->6019
+-->602
+-->6020
+-->6021
+-->6022
+-->6023
+-->6024
+-->6025
+-->6026
+-->6027
+-->6028
+-->6029
+-->603
+-->6030
+-->6031
+-->6032
+-->6033
+-->6034
+-->6035
+-->6036
+-->6037
+-->6038
+-->6039
+-->604
+-->6040
+-->6041
+-->6042
+-->6043
+-->6044
+-->6045
+-->6046
+-->6047
+-->6048
+-->6049
+-->605
+-->6050
+-->6051
+-->6052
+-->6053
+-->6054
+-->6055
+-->6056
+-->6057
+-->6058
+-->6059
+-->606
+-->6060
+-->6061
+-->6062
+-->6063
+-->6064
+-->6065
+-->6066
+-->6067
+-->6068
+-->6069
+-->607
+-->6070
+-->6071
+-->6072
+-->6073
+-->6074
+-->6075
+-->6076
+-->6077
+-->6078
+-->6079
+-->608
+-->6080
+-->6081
+-->6082
+-->6083
+-->6084
+-->6085
+-->6086
+-->6087
+-->6088
+-->6089
+-->609
+-->6090
+-->6091
+-->6092
+-->6093
+-->6094
+-->6095
+-->6096
+-->6097
+-->6098
+-->6099
+-->61
+-->610
+-->6100
+-->6101
+-->6102
+-->6103
+-->6104
+-->6105
+-->6106
+-->6107
+-->6108
+-->6109
+-->611
+-->6110
+-->6111
+-->6112
+-->6113
+-->6114
+-->6115
+-->6116
+-->6117
+-->6118
+-->6119
+-->612
+-->6120
+-->6121
+-->6122
+-->6123
+-->6124
+-->6125
+-->6126
+-->6127
+-->6128
+-->6129
+-->613
+-->6130
+-->6131
+-->6132
+-->6133
+-->6134
+-->6135
+-->6136
+-->6137
+-->6138
+-->6139
+-->614
+-->6140
+-->6141
+-->6142
+-->6143
+-->6144
+-->6145
+-->6146
+-->6147
+-->6148
+-->6149
+-->615
+-->6150
+-->6151
+-->6152
+-->6153
+-->6154
+-->6155
+-->6156
+-->6157
+-->6158
+-->6159
+-->616
+-->6160
+-->6161
+-->6162
+-->6163
+-->6164
+-->6165
+-->6166
+-->6167
+-->6168
+-->6169
+-->617
+-->6170
+-->6171
+-->6172
+-->6173
+-->6174
+-->6175
+-->6176
+-->6177
+-->6178
+-->6179
+-->618
+-->6180
+-->6181
+-->6182
+-->6183
+-->6184
+-->6185
+-->6186
+-->6187
+-->6188
+-->6189
+-->619
+-->6190
+-->6191
+-->6192
+-->6193
+-->6194
+-->6195
+-->6196
+-->6197
+-->6198
+-->6199
+-->62
+-->620
+-->6200
+-->6201
+-->6202
+-->6203
+-->6204
+-->6205
+-->6206
+-->6207
+-->6208
+-->6209
+-->621
+-->6210
+-->6211
+-->6212
+-->6213
+-->6214
+-->6215
+-->6216
+-->6217
+-->6218
+-->6219
+-->622
+-->6220
+-->6221
+-->6222
+-->6223
+-->6224
+-->6225
+-->6226
+-->6227
+-->6228
+-->6229
+-->623
+-->6230
+-->6231
+-->6232
+-->6233
+-->6234
+-->6235
+-->6236
+-->6237
+-->6238
+-->6239
+-->624
+-->6240
+-->6241
+-->6242
+-->6243
+-->6244
+-->6245
+-->6246
+-->6247
+-->6248
+-->6249
+-->625
+-->6250
+-->6251
+-->6252
+-->6253
+-->6254
+-->6255
+-->6256
+-->6257
+-->6258
+-->6259
+-->626
+-->6260
+-->6261
+-->6262
+-->6263
+-->6264
+-->6265
+-->6266
+-->6267
+-->6268
+-->6269
+-->627
+-->6270
+-->6271
+-->6272
+-->6273
+-->6274
+-->6275
+-->6276
+-->6277
+-->6278
+-->6279
+-->628
+-->6280
+-->6281
+-->6282
+-->6283
+-->6284
+-->6285
+-->6286
+-->6287
+-->6288
+-->6289
+-->629
+-->6290
+-->6291
+-->6292
+-->6293
+-->6294
+-->6295
+-->6296
+-->6297
+-->6298
+-->6299
+-->63
+-->630
+-->6300
+-->6301
+-->6302
+-->6303
+-->6304
+-->6305
+-->6306
+-->6307
+-->6308
+-->6309
+-->631
+-->6310
+-->6311
+-->6312
+-->6313
+-->6314
+-->6315
+-->6316
+-->6317
+-->6318
+-->6319
+-->632
+-->6320
+-->6321
+-->6322
+-->6323
+-->6324
+-->6325
+-->6326
+-->6327
+-->6328
+-->6329
+-->633
+-->6330
+-->6331
+-->6332
+-->6333
+-->6334
+-->6335
+-->6336
+-->6337
+-->6338
+-->6339
+-->634
+-->6340
+-->6341
+-->6342
+-->6343
+-->6344
+-->6345
+-->6346
+-->6347
+-->6348
+-->6349
+-->635
+-->6350
+-->6351
+-->6352
+-->6353
+-->6354
+-->6355
+-->6356
+-->6357
+-->6358
+-->6359
+-->636
+-->6360
+-->6361
+-->6362
+-->6363
+-->6364
+-->6365
+-->6366
+-->6367
+-->6368
+-->6369
+-->637
+-->6370
+-->6371
+-->6372
+-->6373
+-->6374
+-->6375
+-->6376
+-->6377
+-->6378
+-->6379
+-->638
+-->6380
+-->6381
+-->6382
+-->6383
+-->6384
+-->6385
+-->6386
+-->6387
+-->6388
+-->6389
+-->639
+-->6390
+-->6391
+-->6392
+-->6393
+-->6394
+-->6395
+-->6396
+-->6397
+-->6398
+-->6399
+-->64
+-->640
+-->6400
+-->6401
+-->6402
+-->6403
+-->6404
+-->6405
+-->6406
+-->6407
+-->6408
+-->6409
+-->641
+-->6410
+-->6411
+-->6412
+-->6413
+-->6414
+-->6415
+-->6416
+-->6417
+-->6418
+-->6419
+-->642
+-->6420
+-->6421
+-->6422
+-->6423
+-->6424
+-->6425
+-->6426
+-->6427
+-->6428
+-->6429
+-->643
+-->6430
+-->6431
+-->6432
+-->6433
+-->6434
+-->6435
+-->6436
+-->6437
+-->6438
+-->6439
+-->644
+-->6440
+-->6441
+-->6442
+-->6443
+-->6444
+-->6445
+-->6446
+-->6447
+-->6448
+-->6449
+-->645
+-->6450
+-->6451
+-->6452
+-->6453
+-->6454
+-->6455
+-->6456
+-->6457
+-->6458
+-->6459
+-->646
+-->6460
+-->6461
+-->6462
+-->6463
+-->6464
+-->6465
+-->6466
+-->6467
+-->6468
+-->6469
+-->647
+-->6470
+-->6471
+-->6472
+-->6473
+-->6474
+-->6475
+-->6476
+-->6477
+-->6478
+-->6479
+-->648
+-->6480
+-->6481
+-->6482
+-->6483
+-->6484
+-->6485
+-->6486
+-->6487
+-->6488
+-->6489
+-->649
+-->6490
+-->6491
+-->6492
+-->6493
+-->6494
+-->6495
+-->6496
+-->6497
+-->6498
+-->6499
+-->65
+-->650
+-->6500
+-->6501
+-->6502
+-->6503
+-->6504
+-->6505
+-->6506
+-->6507
+-->6508
+-->6509
+-->651
+-->6510
+-->6511
+-->6512
+-->6513
+-->6514
+-->6515
+-->6516
+-->6517
+-->6518
+-->6519
+-->652
+-->6520
+-->6521
+-->6522
+-->6523
+-->6524
+-->6525
+-->6526
+-->6527
+-->6528
+-->6529
+-->653
+-->6530
+-->6531
+-->6532
+-->6533
+-->6534
+-->6535
+-->6536
+-->6537
+-->6538
+-->6539
+-->654
+-->6540
+-->6541
+-->6542
+-->6543
+-->6544
+-->6545
+-->6546
+-->6547
+-->6548
+-->6549
+-->655
+-->6550
+-->6551
+-->6552
+-->6553
+-->6554
+-->6555
+-->6556
+-->6557
+-->6558
+-->6559
+-->656
+-->6560
+-->6561
+-->6562
+-->6563
+-->6564
+-->6565
+-->6566
+-->6567
+-->6568
+-->6569
+-->657
+-->6570
+-->6571
+-->6572
+-->6573
+-->6574
+-->6575
+-->6576
+-->6577
+-->6578
+-->6579
+-->658
+-->6580
+-->6581
+-->6582
+-->6583
+-->6584
+-->6585
+-->6586
+-->6587
+-->6588
+-->6589
+-->659
+-->6590
+-->6591
+-->6592
+-->6593
+-->6594
+-->6595
+-->6596
+-->6597
+-->6598
+-->6599
+-->66
+-->660
+-->6600
+-->6601
+-->6602
+-->6603
+-->6604
+-->6605
+-->6606
+-->6607
+-->6608
+-->6609
+-->661
+-->6610
+-->6611
+-->6612
+-->6613
+-->6614
+-->6615
+-->6616
+-->6617
+-->6618
+-->6619
+-->662
+-->6620
+-->6621
+-->6622
+-->6623
+-->6624
+-->6625
+-->6626
+-->6627
+-->6628
+-->6629
+-->663
+-->6630
+-->6631
+-->6632
+-->6633
+-->6634
+-->6635
+-->6636
+-->6637
+-->6638
+-->6639
+-->664
+-->6640
+-->6641
+-->6642
+-->6643
+-->6644
+-->6645
+-->6646
+-->6647
+-->6648
+-->6649
+-->665
+-->6650
+-->6651
+-->6652
+-->6653
+-->6654
+-->6655
+-->6656
+-->6657
+-->6658
+-->6659
+-->666
+-->6660
+-->6661
+-->6662
+-->6663
+-->6664
+-->6665
+-->6666
+-->6667
+-->6668
+-->6669
+-->667
+-->6670
+-->6671
+-->6672
+-->6673
+-->6674
+-->6675
+-->6676
+-->6677
+-->6678
+-->6679
+-->668
+-->6680
+-->6681
+-->6682
+-->6683
+-->6684
+-->6685
+-->6686
+-->6687
+-->6688
+-->6689
+-->669
+-->6690
+-->6691
+-->6692
+-->6693
+-->6694
+-->6695
+-->6696
+-->6697
+-->6698
+-->6699
+-->67
+-->670
+-->6700
+-->6701
+-->6702
+-->6703
+-->6704
+-->6705
+-->6706
+-->6707
+-->6708
+-->6709
+-->671
+-->6710
+-->6711
+-->6712
+-->6713
+-->6714
+-->6715
+-->6716
+-->6717
+-->6718
+-->6719
+-->672
+-->6720
+-->6721
+-->6722
+-->6723
+-->6724
+-->6725
+-->6726
+-->6727
+-->6728
+-->6729
+-->673
+-->6730
+-->6731
+-->6732
+-->6733
+-->6734
+-->6735
+-->6736
+-->6737
+-->6738
+-->6739
+-->674
+-->6740
+-->6741
+-->6742
+-->6743
+-->6744
+-->6745
+-->6746
+-->6747
+-->6748
+-->6749
+-->675
+-->6750
+-->6751
+-->6752
+-->6753
+-->6754
+-->6755
+-->6756
+-->6757
+-->6758
+-->6759
+-->676
+-->6760
+-->6761
+-->6762
+-->6763
+-->6764
+-->6765
+-->6766
+-->6767
+-->6768
+-->6769
+-->677
+-->6770
+-->6771
+-->6772
+-->6773
+-->6774
+-->6775
+-->6776
+-->6777
+-->6778
+-->6779
+-->678
+-->6780
+-->6781
+-->6782
+-->6783
+-->6784
+-->6785
+-->6786
+-->6787
+-->6788
+-->6789
+-->679
+-->6790
+-->6791
+-->6792
+-->6793
+-->6794
+-->6795
+-->6796
+-->6797
+-->6798
+-->6799
+-->68
+-->680
+-->6800
+-->6801
+-->6802
+-->6803
+-->6804
+-->6805
+-->6806
+-->6807
+-->6808
+-->6809
+-->681
+-->6810
+-->6811
+-->6812
+-->6813
+-->6814
+-->6815
+-->6816
+-->6817
+-->6818
+-->6819
+-->682
+-->6820
+-->6821
+-->6822
+-->6823
+-->6824
+-->6825
+-->6826
+-->6827
+-->6828
+-->6829
+-->683
+-->6830
+-->6831
+-->6832
+-->6833
+-->6834
+-->6835
+-->6836
+-->6837
+-->6838
+-->6839
+-->684
+-->6840
+-->6841
+-->6842
+-->6843
+-->6844
+-->6845
+-->6846
+-->6847
+-->6848
+-->6849
+-->685
+-->6850
+-->6851
+-->6852
+-->6853
+-->6854
+-->6855
+-->6856
+-->6857
+-->6858
+-->6859
+-->686
+-->6860
+-->6861
+-->6862
+-->6863
+-->6864
+-->6865
+-->6866
+-->6867
+-->6868
+-->6869
+-->687
+-->6870
+-->6871
+-->6872
+-->6873
+-->6874
+-->6875
+-->6876
+-->6877
+-->6878
+-->6879
+-->688
+-->6880
+-->6881
+-->6882
+-->6883
+-->6884
+-->6885
+-->6886
+-->6887
+-->6888
+-->6889
+-->689
+-->6890
+-->6891
+-->6892
+-->6893
+-->6894
+-->6895
+-->6896
+-->6897
+-->6898
+-->6899
+-->69
+-->690
+-->6900
+-->6901
+-->6902
+-->6903
+-->6904
+-->6905
+-->6906
+-->6907
+-->6908
+-->6909
+-->691
+-->6910
+-->6911
+-->6912
+-->6913
+-->6914
+-->6915
+-->6916
+-->6917
+-->6918
+-->6919
+-->692
+-->6920
+-->6921
+-->6922
+-->6923
+-->6924
+-->6925
+-->6926
+-->6927
+-->6928
+-->6929
+-->693
+-->6930
+-->6931
+-->6932
+-->6933
+-->6934
+-->6935
+-->6936
+-->6937
+-->6938
+-->6939
+-->694
+-->6940
+-->6941
+-->6942
+-->6943
+-->6944
+-->6945
+-->6946
+-->6947
+-->6948
+-->6949
+-->695
+-->6950
+-->6951
+-->6952
+-->6953
+-->6954
+-->6955
+-->6956
+-->6957
+-->6958
+-->6959
+-->696
+-->6960
+-->6961
+-->6962
+-->6963
+-->6964
+-->6965
+-->6966
+-->6967
+-->6968
+-->6969
+-->697
+-->6970
+-->6971
+-->6972
+-->6973
+-->6974
+-->6975
+-->6976
+-->6977
+-->6978
+-->6979
+-->698
+-->6980
+-->6981
+-->6982
+-->6983
+-->6984
+-->6985
+-->6986
+-->6987
+-->6988
+-->6989
+-->699
+-->6990
+-->6991
+-->6992
+-->6993
+-->6994
+-->6995
+-->6996
+-->6997
+-->6998
+-->6999
+-->7
+-->70
+-->700
+-->7000
+-->7001
+-->7002
+-->7003
+-->7004
+-->7005
+-->7006
+-->7007
+-->7008
+-->7009
+-->701
+-->7010
+-->7011
+-->7012
+-->7013
+-->7014
+-->7015
+-->7016
+-->7017
+-->7018
+-->7019
+-->702
+-->7020
+-->7021
+-->7022
+-->7023
+-->7024
+-->7025
+-->7026
+-->7027
+-->7028
+-->7029
+-->703
+-->7030
+-->7031
+-->7032
+-->7033
+-->7034
+-->7035
+-->7036
+-->7037
+-->7038
+-->7039
+-->704
+-->7040
+-->7041
+-->7042
+-->7043
+-->7044
+-->7045
+-->7046
+-->7047
+-->7048
+-->7049
+-->705
+-->7050
+-->7051
+-->7052
+-->7053
+-->7054
+-->7055
+-->7056
+-->7057
+-->7058
+-->7059
+-->706
+-->7060
+-->7061
+-->7062
+-->7063
+-->7064
+-->7065
+-->7066
+-->7067
+-->7068
+-->7069
+-->707
+-->7070
+-->7071
+-->7072
+-->7073
+-->7074
+-->7075
+-->7076
+-->7077
+-->7078
+-->7079
+-->708
+-->7080
+-->7081
+-->7082
+-->7083
+-->7084
+-->7085
+-->7086
+-->7087
+-->7088
+-->7089
+-->709
+-->7090
+-->7091
+-->7092
+-->7093
+-->7094
+-->7095
+-->7096
+-->7097
+-->7098
+-->7099
+-->71
+-->710
+-->7100
+-->7101
+-->7102
+-->7103
+-->7104
+-->7105
+-->7106
+-->7107
+-->7108
+-->7109
+-->711
+-->7110
+-->7111
+-->7112
+-->7113
+-->7114
+-->7115
+-->7116
+-->7117
+-->7118
+-->7119
+-->712
+-->7120
+-->7121
+-->7122
+-->7123
+-->7124
+-->7125
+-->7126
+-->7127
+-->7128
+-->7129
+-->713
+-->7130
+-->7131
+-->7132
+-->7133
+-->7134
+-->7135
+-->7136
+-->7137
+-->7138
+-->7139
+-->714
+-->7140
+-->7141
+-->7142
+-->7143
+-->7144
+-->7145
+-->7146
+-->7147
+-->7148
+-->7149
+-->715
+-->7150
+-->7151
+-->7152
+-->7153
+-->7154
+-->7155
+-->7156
+-->7157
+-->7158
+-->7159
+-->716
+-->7160
+-->7161
+-->7162
+-->7163
+-->7164
+-->7165
+-->7166
+-->7167
+-->7168
+-->7169
+-->717
+-->7170
+-->7171
+-->7172
+-->7173
+-->7174
+-->7175
+-->7176
+-->7177
+-->7178
+-->7179
+-->718
+-->7180
+-->7181
+-->7182
+-->7183
+-->7184
+-->7185
+-->7186
+-->7187
+-->7188
+-->7189
+-->719
+-->7190
+-->7191
+-->7192
+-->7193
+-->7194
+-->7195
+-->7196
+-->7197
+-->7198
+-->7199
+-->72
+-->720
+-->7200
+-->7201
+-->7202
+-->7203
+-->7204
+-->7205
+-->7206
+-->7207
+-->7208
+-->7209
+-->721
+-->7210
+-->7211
+-->7212
+-->7213
+-->7214
+-->7215
+-->7216
+-->7217
+-->7218
+-->7219
+-->722
+-->7220
+-->7221
+-->7222
+-->7223
+-->7224
+-->7225
+-->7226
+-->7227
+-->7228
+-->7229
+-->723
+-->7230
+-->7231
+-->7232
+-->7233
+-->7234
+-->7235
+-->7236
+-->7237
+-->7238
+-->7239
+-->724
+-->7240
+-->7241
+-->7242
+-->7243
+-->7244
+-->7245
+-->7246
+-->7247
+-->7248
+-->7249
+-->725
+-->7250
+-->7251
+-->7252
+-->7253
+-->7254
+-->7255
+-->7256
+-->7257
+-->7258
+-->7259
+-->726
+-->7260
+-->7261
+-->7262
+-->7263
+-->7264
+-->7265
+-->7266
+-->7267
+-->7268
+-->7269
+-->727
+-->7270
+-->7271
+-->7272
+-->7273
+-->7274
+-->7275
+-->7276
+-->7277
+-->7278
+-->7279
+-->728
+-->7280
+-->7281
+-->7282
+-->7283
+-->7284
+-->7285
+-->7286
+-->7287
+-->7288
+-->7289
+-->729
+-->7290
+-->7291
+-->7292
+-->7293
+-->7294
+-->7295
+-->7296
+-->7297
+-->7298
+-->7299
+-->73
+-->730
+-->7300
+-->7301
+-->7302
+-->7303
+-->7304
+-->7305
+-->7306
+-->7307
+-->7308
+-->7309
+-->731
+-->7310
+-->7311
+-->7312
+-->7313
+-->7314
+-->7315
+-->7316
+-->7317
+-->7318
+-->7319
+-->732
+-->7320
+-->7321
+-->7322
+-->7323
+-->7324
+-->7325
+-->7326
+-->7327
+-->7328
+-->7329
+-->733
+-->7330
+-->7331
+-->7332
+-->7333
+-->7334
+-->7335
+-->7336
+-->7337
+-->7338
+-->7339
+-->734
+-->7340
+-->7341
+-->7342
+-->7343
+-->7344
+-->7345
+-->7346
+-->7347
+-->7348
+-->7349
+-->735
+-->7350
+-->7351
+-->7352
+-->7353
+-->7354
+-->7355
+-->7356
+-->7357
+-->7358
+-->7359
+-->736
+-->7360
+-->7361
+-->7362
+-->7363
+-->7364
+-->7365
+-->7366
+-->7367
+-->7368
+-->7369
+-->737
+-->7370
+-->7371
+-->7372
+-->7373
+-->7374
+-->7375
+-->7376
+-->7377
+-->7378
+-->7379
+-->738
+-->7380
+-->7381
+-->7382
+-->7383
+-->7384
+-->7385
+-->7386
+-->7387
+-->7388
+-->7389
+-->739
+-->7390
+-->7391
+-->7392
+-->7393
+-->7394
+-->7395
+-->7396
+-->7397
+-->7398
+-->7399
+-->74
+-->740
+-->7400
+-->7401
+-->7402
+-->7403
+-->7404
+-->7405
+-->7406
+-->7407
+-->7408
+-->7409
+-->741
+-->7410
+-->7411
+-->7412
+-->7413
+-->7414
+-->7415
+-->7416
+-->7417
+-->7418
+-->7419
+-->742
+-->7420
+-->7421
+-->7422
+-->7423
+-->7424
+-->7425
+-->7426
+-->7427
+-->7428
+-->7429
+-->743
+-->7430
+-->7431
+-->7432
+-->7433
+-->7434
+-->7435
+-->7436
+-->7437
+-->7438
+-->7439
+-->744
+-->7440
+-->7441
+-->7442
+-->7443
+-->7444
+-->7445
+-->7446
+-->7447
+-->7448
+-->7449
+-->745
+-->7450
+-->7451
+-->7452
+-->7453
+-->7454
+-->7455
+-->7456
+-->7457
+-->7458
+-->7459
+-->746
+-->7460
+-->7461
+-->7462
+-->7463
+-->7464
+-->7465
+-->7466
+-->7467
+-->7468
+-->7469
+-->747
+-->7470
+-->7471
+-->7472
+-->7473
+-->7474
+-->7475
+-->7476
+-->7477
+-->7478
+-->7479
+-->748
+-->7480
+-->7481
+-->7482
+-->7483
+-->7484
+-->7485
+-->7486
+-->7487
+-->7488
+-->7489
+-->749
+-->7490
+-->7491
+-->7492
+-->7493
+-->7494
+-->7495
+-->7496
+-->7497
+-->7498
+-->7499
+-->75
+-->750
+-->7500
+-->7501
+-->7502
+-->7503
+-->7504
+-->7505
+-->7506
+-->7507
+-->7508
+-->7509
+-->751
+-->7510
+-->7511
+-->7512
+-->7513
+-->7514
+-->7515
+-->7516
+-->7517
+-->7518
+-->7519
+-->752
+-->7520
+-->7521
+-->7522
+-->7523
+-->7524
+-->7525
+-->7526
+-->7527
+-->7528
+-->7529
+-->753
+-->7530
+-->7531
+-->7532
+-->7533
+-->7534
+-->7535
+-->7536
+-->7537
+-->7538
+-->7539
+-->754
+-->7540
+-->7541
+-->7542
+-->7543
+-->7544
+-->7545
+-->7546
+-->7547
+-->7548
+-->7549
+-->755
+-->7550
+-->7551
+-->7552
+-->7553
+-->7554
+-->7555
+-->7556
+-->7557
+-->7558
+-->7559
+-->756
+-->7560
+-->7561
+-->7562
+-->7563
+-->7564
+-->7565
+-->7566
+-->7567
+-->7568
+-->7569
+-->757
+-->7570
+-->7571
+-->7572
+-->7573
+-->7574
+-->7575
+-->7576
+-->7577
+-->7578
+-->7579
+-->758
+-->7580
+-->7581
+-->7582
+-->7583
+-->7584
+-->7585
+-->7586
+-->7587
+-->7588
+-->7589
+-->759
+-->7590
+-->7591
+-->7592
+-->7593
+-->7594
+-->7595
+-->7596
+-->7597
+-->7598
+-->7599
+-->76
+-->760
+-->7600
+-->7601
+-->7602
+-->7603
+-->7604
+-->7605
+-->7606
+-->7607
+-->7608
+-->7609
+-->761
+-->7610
+-->7611
+-->7612
+-->7613
+-->7614
+-->7615
+-->7616
+-->7617
+-->7618
+-->7619
+-->762
+-->7620
+-->7621
+-->7622
+-->7623
+-->7624
+-->7625
+-->7626
+-->7627
+-->7628
+-->7629
+-->763
+-->7630
+-->7631
+-->7632
+-->7633
+-->7634
+-->7635
+-->7636
+-->7637
+-->7638
+-->7639
+-->764
+-->7640
+-->7641
+-->7642
+-->7643
+-->7644
+-->7645
+-->7646
+-->7647
+-->7648
+-->7649
+-->765
+-->7650
+-->7651
+-->7652
+-->7653
+-->7654
+-->7655
+-->7656
+-->7657
+-->7658
+-->7659
+-->766
+-->7660
+-->7661
+-->7662
+-->7663
+-->7664
+-->7665
+-->7666
+-->7667
+-->7668
+-->7669
+-->767
+-->7670
+-->7671
+-->7672
+-->7673
+-->7674
+-->7675
+-->7676
+-->7677
+-->7678
+-->7679
+-->768
+-->7680
+-->7681
+-->7682
+-->7683
+-->7684
+-->7685
+-->7686
+-->7687
+-->7688
+-->7689
+-->769
+-->7690
+-->7691
+-->7692
+-->7693
+-->7694
+-->7695
+-->7696
+-->7697
+-->7698
+-->7699
+-->77
+-->770
+-->7700
+-->7701
+-->7702
+-->7703
+-->7704
+-->7705
+-->7706
+-->7707
+-->7708
+-->7709
+-->771
+-->7710
+-->7711
+-->7712
+-->7713
+-->7714
+-->7715
+-->7716
+-->7717
+-->7718
+-->7719
+-->772
+-->7720
+-->7721
+-->7722
+-->7723
+-->7724
+-->7725
+-->7726
+-->7727
+-->7728
+-->7729
+-->773
+-->7730
+-->7731
+-->7732
+-->7733
+-->7734
+-->7735
+-->7736
+-->7737
+-->7738
+-->7739
+-->774
+-->7740
+-->7741
+-->7742
+-->7743
+-->7744
+-->7745
+-->7746
+-->7747
+-->7748
+-->7749
+-->775
+-->7750
+-->7751
+-->7752
+-->7753
+-->7754
+-->7755
+-->7756
+-->7757
+-->7758
+-->7759
+-->776
+-->7760
+-->7761
+-->7762
+-->7763
+-->7764
+-->7765
+-->7766
+-->7767
+-->7768
+-->7769
+-->777
+-->7770
+-->7771
+-->7772
+-->7773
+-->7774
+-->7775
+-->7776
+-->7777
+-->7778
+-->7779
+-->778
+-->7780
+-->7781
+-->7782
+-->7783
+-->7784
+-->7785
+-->7786
+-->7787
+-->7788
+-->7789
+-->779
+-->7790
+-->7791
+-->7792
+-->7793
+-->7794
+-->7795
+-->7796
+-->7797
+-->7798
+-->7799
+-->78
+-->780
+-->7800
+-->7801
+-->7802
+-->7803
+-->7804
+-->7805
+-->7806
+-->7807
+-->7808
+-->7809
+-->781
+-->7810
+-->7811
+-->7812
+-->7813
+-->7814
+-->7815
+-->7816
+-->7817
+-->7818
+-->7819
+-->782
+-->7820
+-->7821
+-->7822
+-->7823
+-->7824
+-->7825
+-->7826
+-->7827
+-->7828
+-->7829
+-->783
+-->7830
+-->7831
+-->7832
+-->7833
+-->7834
+-->7835
+-->7836
+-->7837
+-->7838
+-->7839
+-->784
+-->7840
+-->7841
+-->7842
+-->7843
+-->7844
+-->7845
+-->7846
+-->7847
+-->7848
+-->7849
+-->785
+-->7850
+-->7851
+-->7852
+-->7853
+-->7854
+-->7855
+-->7856
+-->7857
+-->7858
+-->7859
+-->786
+-->7860
+-->7861
+-->7862
+-->7863
+-->7864
+-->7865
+-->7866
+-->7867
+-->7868
+-->7869
+-->787
+-->7870
+-->7871
+-->7872
+-->7873
+-->7874
+-->7875
+-->7876
+-->7877
+-->7878
+-->7879
+-->788
+-->7880
+-->7881
+-->7882
+-->7883
+-->7884
+-->7885
+-->7886
+-->7887
+-->7888
+-->7889
+-->789
+-->7890
+-->7891
+-->7892
+-->7893
+-->7894
+-->7895
+-->7896
+-->7897
+-->7898
+-->7899
+-->79
+-->790
+-->7900
+-->7901
+-->7902
+-->7903
+-->7904
+-->7905
+-->7906
+-->7907
+-->7908
+-->7909
+-->791
+-->7910
+-->7911
+-->7912
+-->7913
+-->7914
+-->7915
+-->7916
+-->7917
+-->7918
+-->7919
+-->792
+-->7920
+-->7921
+-->7922
+-->7923
+-->7924
+-->7925
+-->7926
+-->7927
+-->7928
+-->7929
+-->793
+-->7930
+-->7931
+-->7932
+-->7933
+-->7934
+-->7935
+-->7936
+-->7937
+-->7938
+-->7939
+-->794
+-->7940
+-->7941
+-->7942
+-->7943
+-->7944
+-->7945
+-->7946
+-->7947
+-->7948
+-->7949
+-->795
+-->7950
+-->7951
+-->7952
+-->7953
+-->7954
+-->7955
+-->7956
+-->7957
+-->7958
+-->7959
+-->796
+-->7960
+-->7961
+-->7962
+-->7963
+-->7964
+-->7965
+-->7966
+-->7967
+-->7968
+-->7969
+-->797
+-->7970
+-->7971
+-->7972
+-->7973
+-->7974
+-->7975
+-->7976
+-->7977
+-->7978
+-->7979
+-->798
+-->7980
+-->7981
+-->7982
+-->7983
+-->7984
+-->7985
+-->7986
+-->7987
+-->7988
+-->7989
+-->799
+-->7990
+-->7991
+-->7992
+-->7993
+-->7994
+-->7995
+-->7996
+-->7997
+-->7998
+-->7999
+-->8
+-->80
+-->800
+-->8000
+-->8001
+-->8002
+-->8003
+-->8004
+-->8005
+-->8006
+-->8007
+-->8008
+-->8009
+-->801
+-->8010
+-->8011
+-->8012
+-->8013
+-->8014
+-->8015
+-->8016
+-->8017
+-->8018
+-->8019
+-->802
+-->8020
+-->8021
+-->8022
+-->8023
+-->8024
+-->8025
+-->8026
+-->8027
+-->8028
+-->8029
+-->803
+-->8030
+-->8031
+-->8032
+-->8033
+-->8034
+-->8035
+-->8036
+-->8037
+-->8038
+-->8039
+-->804
+-->8040
+-->8041
+-->8042
+-->8043
+-->8044
+-->8045
+-->8046
+-->8047
+-->8048
+-->8049
+-->805
+-->8050
+-->8051
+-->8052
+-->8053
+-->8054
+-->8055
+-->8056
+-->8057
+-->8058
+-->8059
+-->806
+-->8060
+-->8061
+-->8062
+-->8063
+-->8064
+-->8065
+-->8066
+-->8067
+-->8068
+-->8069
+-->807
+-->8070
+-->8071
+-->8072
+-->8073
+-->8074
+-->8075
+-->8076
+-->8077
+-->8078
+-->8079
+-->808
+-->8080
+-->8081
+-->8082
+-->8083
+-->8084
+-->8085
+-->8086
+-->8087
+-->8088
+-->8089
+-->809
+-->8090
+-->8091
+-->8092
+-->8093
+-->8094
+-->8095
+-->8096
+-->8097
+-->8098
+-->8099
+-->81
+-->810
+-->8100
+-->8101
+-->8102
+-->8103
+-->8104
+-->8105
+-->8106
+-->8107
+-->8108
+-->8109
+-->811
+-->8110
+-->8111
+-->8112
+-->8113
+-->8114
+-->8115
+-->8116
+-->8117
+-->8118
+-->8119
+-->812
+-->8120
+-->8121
+-->8122
+-->8123
+-->8124
+-->8125
+-->8126
+-->8127
+-->8128
+-->8129
+-->813
+-->8130
+-->8131
+-->8132
+-->8133
+-->8134
+-->8135
+-->8136
+-->8137
+-->8138
+-->8139
+-->814
+-->8140
+-->8141
+-->8142
+-->8143
+-->8144
+-->8145
+-->8146
+-->8147
+-->8148
+-->8149
+-->815
+-->8150
+-->8151
+-->8152
+-->8153
+-->8154
+-->8155
+-->8156
+-->8157
+-->8158
+-->8159
+-->816
+-->8160
+-->8161
+-->8162
+-->8163
+-->8164
+-->8165
+-->8166
+-->8167
+-->8168
+-->8169
+-->817
+-->8170
+-->8171
+-->8172
+-->8173
+-->8174
+-->8175
+-->8176
+-->8177
+-->8178
+-->8179
+-->818
+-->8180
+-->8181
+-->8182
+-->8183
+-->8184
+-->8185
+-->8186
+-->8187
+-->8188
+-->8189
+-->819
+-->8190
+-->8191
+-->8192
+-->8193
+-->8194
+-->8195
+-->8196
+-->8197
+-->8198
+-->8199
+-->82
+-->820
+-->8200
+-->8201
+-->8202
+-->8203
+-->8204
+-->8205
+-->8206
+-->8207
+-->8208
+-->8209
+-->821
+-->8210
+-->8211
+-->8212
+-->8213
+-->8214
+-->8215
+-->8216
+-->8217
+-->8218
+-->8219
+-->822
+-->8220
+-->8221
+-->8222
+-->8223
+-->8224
+-->8225
+-->8226
+-->8227
+-->8228
+-->8229
+-->823
+-->8230
+-->8231
+-->8232
+-->8233
+-->8234
+-->8235
+-->8236
+-->8237
+-->8238
+-->8239
+-->824
+-->8240
+-->8241
+-->8242
+-->8243
+-->8244
+-->8245
+-->8246
+-->8247
+-->8248
+-->8249
+-->825
+-->8250
+-->8251
+-->8252
+-->8253
+-->8254
+-->8255
+-->8256
+-->8257
+-->8258
+-->8259
+-->826
+-->8260
+-->8261
+-->8262
+-->8263
+-->8264
+-->8265
+-->8266
+-->8267
+-->8268
+-->8269
+-->827
+-->8270
+-->8271
+-->8272
+-->8273
+-->8274
+-->8275
+-->8276
+-->8277
+-->8278
+-->8279
+-->828
+-->8280
+-->8281
+-->8282
+-->8283
+-->8284
+-->8285
+-->8286
+-->8287
+-->8288
+-->8289
+-->829
+-->8290
+-->8291
+-->8292
+-->8293
+-->8294
+-->8295
+-->8296
+-->8297
+-->8298
+-->8299
+-->83
+-->830
+-->8300
+-->8301
+-->8302
+-->8303
+-->8304
+-->8305
+-->8306
+-->8307
+-->8308
+-->8309
+-->831
+-->8310
+-->8311
+-->8312
+-->8313
+-->8314
+-->8315
+-->8316
+-->8317
+-->8318
+-->8319
+-->832
+-->8320
+-->8321
+-->8322
+-->8323
+-->8324
+-->8325
+-->8326
+-->8327
+-->8328
+-->8329
+-->833
+-->8330
+-->8331
+-->8332
+-->8333
+-->8334
+-->8335
+-->8336
+-->8337
+-->8338
+-->8339
+-->834
+-->8340
+-->8341
+-->8342
+-->8343
+-->8344
+-->8345
+-->8346
+-->8347
+-->8348
+-->8349
+-->835
+-->8350
+-->8351
+-->8352
+-->8353
+-->8354
+-->8355
+-->8356
+-->8357
+-->8358
+-->8359
+-->836
+-->8360
+-->8361
+-->8362
+-->8363
+-->8364
+-->8365
+-->8366
+-->8367
+-->8368
+-->8369
+-->837
+-->8370
+-->8371
+-->8372
+-->8373
+-->8374
+-->8375
+-->8376
+-->8377
+-->8378
+-->8379
+-->838
+-->8380
+-->8381
+-->8382
+-->8383
+-->8384
+-->8385
+-->8386
+-->8387
+-->8388
+-->8389
+-->839
+-->8390
+-->8391
+-->8392
+-->8393
+-->8394
+-->8395
+-->8396
+-->8397
+-->8398
+-->8399
+-->84
+-->840
+-->8400
+-->8401
+-->8402
+-->8403
+-->8404
+-->8405
+-->8406
+-->8407
+-->8408
+-->8409
+-->841
+-->8410
+-->8411
+-->8412
+-->8413
+-->8414
+-->8415
+-->8416
+-->8417
+-->8418
+-->8419
+-->842
+-->8420
+-->8421
+-->8422
+-->8423
+-->8424
+-->8425
+-->8426
+-->8427
+-->8428
+-->8429
+-->843
+-->8430
+-->8431
+-->8432
+-->8433
+-->8434
+-->8435
+-->8436
+-->8437
+-->8438
+-->8439
+-->844
+-->8440
+-->8441
+-->8442
+-->8443
+-->8444
+-->8445
+-->8446
+-->8447
+-->8448
+-->8449
+-->845
+-->8450
+-->8451
+-->8452
+-->8453
+-->8454
+-->8455
+-->8456
+-->8457
+-->8458
+-->8459
+-->846
+-->8460
+-->8461
+-->8462
+-->8463
+-->8464
+-->8465
+-->8466
+-->8467
+-->8468
+-->8469
+-->847
+-->8470
+-->8471
+-->8472
+-->8473
+-->8474
+-->8475
+-->8476
+-->8477
+-->8478
+-->8479
+-->848
+-->8480
+-->8481
+-->8482
+-->8483
+-->8484
+-->8485
+-->8486
+-->8487
+-->8488
+-->8489
+-->849
+-->8490
+-->8491
+-->8492
+-->8493
+-->8494
+-->8495
+-->8496
+-->8497
+-->8498
+-->8499
+-->85
+-->850
+-->8500
+-->8501
+-->8502
+-->8503
+-->8504
+-->8505
+-->8506
+-->8507
+-->8508
+-->8509
+-->851
+-->8510
+-->8511
+-->8512
+-->8513
+-->8514
+-->8515
+-->8516
+-->8517
+-->8518
+-->8519
+-->852
+-->8520
+-->8521
+-->8522
+-->8523
+-->8524
+-->8525
+-->8526
+-->8527
+-->8528
+-->8529
+-->853
+-->8530
+-->8531
+-->8532
+-->8533
+-->8534
+-->8535
+-->8536
+-->8537
+-->8538
+-->8539
+-->854
+-->8540
+-->8541
+-->8542
+-->8543
+-->8544
+-->8545
+-->8546
+-->8547
+-->8548
+-->8549
+-->855
+-->8550
+-->8551
+-->8552
+-->8553
+-->8554
+-->8555
+-->8556
+-->8557
+-->8558
+-->8559
+-->856
+-->8560
+-->8561
+-->8562
+-->8563
+-->8564
+-->8565
+-->8566
+-->8567
+-->8568
+-->8569
+-->857
+-->8570
+-->8571
+-->8572
+-->8573
+-->8574
+-->8575
+-->8576
+-->8577
+-->8578
+-->8579
+-->858
+-->8580
+-->8581
+-->8582
+-->8583
+-->8584
+-->8585
+-->8586
+-->8587
+-->8588
+-->8589
+-->859
+-->8590
+-->8591
+-->8592
+-->8593
+-->8594
+-->8595
+-->8596
+-->8597
+-->8598
+-->8599
+-->86
+-->860
+-->8600
+-->8601
+-->8602
+-->8603
+-->8604
+-->8605
+-->8606
+-->8607
+-->8608
+-->8609
+-->861
+-->8610
+-->8611
+-->8612
+-->8613
+-->8614
+-->8615
+-->8616
+-->8617
+-->8618
+-->8619
+-->862
+-->8620
+-->8621
+-->8622
+-->8623
+-->8624
+-->8625
+-->8626
+-->8627
+-->8628
+-->8629
+-->863
+-->8630
+-->8631
+-->8632
+-->8633
+-->8634
+-->8635
+-->8636
+-->8637
+-->8638
+-->8639
+-->864
+-->8640
+-->8641
+-->8642
+-->8643
+-->8644
+-->8645
+-->8646
+-->8647
+-->8648
+-->8649
+-->865
+-->8650
+-->8651
+-->8652
+-->8653
+-->8654
+-->8655
+-->8656
+-->8657
+-->8658
+-->8659
+-->866
+-->8660
+-->8661
+-->8662
+-->8663
+-->8664
+-->8665
+-->8666
+-->8667
+-->8668
+-->8669
+-->867
+-->8670
+-->8671
+-->8672
+-->8673
+-->8674
+-->8675
+-->8676
+-->8677
+-->8678
+-->8679
+-->868
+-->8680
+-->8681
+-->8682
+-->8683
+-->8684
+-->8685
+-->8686
+-->8687
+-->8688
+-->8689
+-->869
+-->8690
+-->8691
+-->8692
+-->8693
+-->8694
+-->8695
+-->8696
+-->8697
+-->8698
+-->8699
+-->87
+-->870
+-->8700
+-->8701
+-->8702
+-->8703
+-->8704
+-->8705
+-->8706
+-->8707
+-->8708
+-->8709
+-->871
+-->8710
+-->8711
+-->8712
+-->8713
+-->8714
+-->8715
+-->8716
+-->8717
+-->8718
+-->8719
+-->872
+-->8720
+-->8721
+-->8722
+-->8723
+-->8724
+-->8725
+-->8726
+-->8727
+-->8728
+-->8729
+-->873
+-->8730
+-->8731
+-->8732
+-->8733
+-->8734
+-->8735
+-->8736
+-->8737
+-->8738
+-->8739
+-->874
+-->8740
+-->8741
+-->8742
+-->8743
+-->8744
+-->8745
+-->8746
+-->8747
+-->8748
+-->8749
+-->875
+-->8750
+-->8751
+-->8752
+-->8753
+-->8754
+-->8755
+-->8756
+-->8757
+-->8758
+-->8759
+-->876
+-->8760
+-->8761
+-->8762
+-->8763
+-->8764
+-->8765
+-->8766
+-->8767
+-->8768
+-->8769
+-->877
+-->8770
+-->8771
+-->8772
+-->8773
+-->8774
+-->8775
+-->8776
+-->8777
+-->8778
+-->8779
+-->878
+-->8780
+-->8781
+-->8782
+-->8783
+-->8784
+-->8785
+-->8786
+-->8787
+-->8788
+-->8789
+-->879
+-->8790
+-->8791
+-->8792
+-->8793
+-->8794
+-->8795
+-->8796
+-->8797
+-->8798
+-->8799
+-->88
+-->880
+-->8800
+-->8801
+-->8802
+-->8803
+-->8804
+-->8805
+-->8806
+-->8807
+-->8808
+-->8809
+-->881
+-->8810
+-->8811
+-->8812
+-->8813
+-->8814
+-->8815
+-->8816
+-->8817
+-->8818
+-->8819
+-->882
+-->8820
+-->8821
+-->8822
+-->8823
+-->8824
+-->8825
+-->8826
+-->8827
+-->8828
+-->8829
+-->883
+-->8830
+-->8831
+-->8832
+-->8833
+-->8834
+-->8835
+-->8836
+-->8837
+-->8838
+-->8839
+-->884
+-->8840
+-->8841
+-->8842
+-->8843
+-->8844
+-->8845
+-->8846
+-->8847
+-->8848
+-->8849
+-->885
+-->8850
+-->8851
+-->8852
+-->8853
+-->8854
+-->8855
+-->8856
+-->8857
+-->8858
+-->8859
+-->886
+-->8860
+-->8861
+-->8862
+-->8863
+-->8864
+-->8865
+-->8866
+-->8867
+-->8868
+-->8869
+-->887
+-->8870
+-->8871
+-->8872
+-->8873
+-->8874
+-->8875
+-->8876
+-->8877
+-->8878
+-->8879
+-->888
+-->8880
+-->8881
+-->8882
+-->8883
+-->8884
+-->8885
+-->8886
+-->8887
+-->8888
+-->8889
+-->889
+-->8890
+-->8891
+-->8892
+-->8893
+-->8894
+-->8895
+-->8896
+-->8897
+-->8898
+-->8899
+-->89
+-->890
+-->8900
+-->8901
+-->8902
+-->8903
+-->8904
+-->8905
+-->8906
+-->8907
+-->8908
+-->8909
+-->891
+-->8910
+-->8911
+-->8912
+-->8913
+-->8914
+-->8915
+-->8916
+-->8917
+-->8918
+-->8919
+-->892
+-->8920
+-->8921
+-->8922
+-->8923
+-->8924
+-->8925
+-->8926
+-->8927
+-->8928
+-->8929
+-->893
+-->8930
+-->8931
+-->8932
+-->8933
+-->8934
+-->8935
+-->8936
+-->8937
+-->8938
+-->8939
+-->894
+-->8940
+-->8941
+-->8942
+-->8943
+-->8944
+-->8945
+-->8946
+-->8947
+-->8948
+-->8949
+-->895
+-->8950
+-->8951
+-->8952
+-->8953
+-->8954
+-->8955
+-->8956
+-->8957
+-->8958
+-->8959
+-->896
+-->8960
+-->8961
+-->8962
+-->8963
+-->8964
+-->8965
+-->8966
+-->8967
+-->8968
+-->8969
+-->897
+-->8970
+-->8971
+-->8972
+-->8973
+-->8974
+-->8975
+-->8976
+-->8977
+-->8978
+-->8979
+-->898
+-->8980
+-->8981
+-->8982
+-->8983
+-->8984
+-->8985
+-->8986
+-->8987
+-->8988
+-->8989
+-->899
+-->8990
+-->8991
+-->8992
+-->8993
+-->8994
+-->8995
+-->8996
+-->8997
+-->8998
+-->8999
+-->9
+-->90
+-->900
+-->9000
+-->9001
+-->9002
+-->9003
+-->9004
+-->9005
+-->9006
+-->9007
+-->9008
+-->9009
+-->901
+-->9010
+-->9011
+-->9012
+-->9013
+-->9014
+-->9015
+-->9016
+-->9017
+-->9018
+-->9019
+-->902
+-->9020
+-->9021
+-->9022
+-->9023
+-->9024
+-->9025
+-->9026
+-->9027
+-->9028
+-->9029
+-->903
+-->9030
+-->9031
+-->9032
+-->9033
+-->9034
+-->9035
+-->9036
+-->9037
+-->9038
+-->9039
+-->904
+-->9040
+-->9041
+-->9042
+-->9043
+-->9044
+-->9045
+-->9046
+-->9047
+-->9048
+-->9049
+-->905
+-->9050
+-->9051
+-->9052
+-->9053
+-->9054
+-->9055
+-->9056
+-->9057
+-->9058
+-->9059
+-->906
+-->9060
+-->9061
+-->9062
+-->9063
+-->9064
+-->9065
+-->9066
+-->9067
+-->9068
+-->9069
+-->907
+-->9070
+-->9071
+-->9072
+-->9073
+-->9074
+-->9075
+-->9076
+-->9077
+-->9078
+-->9079
+-->908
+-->9080
+-->9081
+-->9082
+-->9083
+-->9084
+-->9085
+-->9086
+-->9087
+-->9088
+-->9089
+-->909
+-->9090
+-->9091
+-->9092
+-->9093
+-->9094
+-->9095
+-->9096
+-->9097
+-->9098
+-->9099
+-->91
+-->910
+-->9100
+-->9101
+-->9102
+-->9103
+-->9104
+-->9105
+-->9106
+-->9107
+-->9108
+-->9109
+-->911
+-->9110
+-->9111
+-->9112
+-->9113
+-->9114
+-->9115
+-->9116
+-->9117
+-->9118
+-->9119
+-->912
+-->9120
+-->9121
+-->9122
+-->9123
+-->9124
+-->9125
+-->9126
+-->9127
+-->9128
+-->9129
+-->913
+-->9130
+-->9131
+-->9132
+-->9133
+-->9134
+-->9135
+-->9136
+-->9137
+-->9138
+-->9139
+-->914
+-->9140
+-->9141
+-->9142
+-->9143
+-->9144
+-->9145
+-->9146
+-->9147
+-->9148
+-->9149
+-->915
+-->9150
+-->9151
+-->9152
+-->9153
+-->9154
+-->9155
+-->9156
+-->9157
+-->9158
+-->9159
+-->916
+-->9160
+-->9161
+-->9162
+-->9163
+-->9164
+-->9165
+-->9166
+-->9167
+-->9168
+-->9169
+-->917
+-->9170
+-->9171
+-->9172
+-->9173
+-->9174
+-->9175
+-->9176
+-->9177
+-->9178
+-->9179
+-->918
+-->9180
+-->9181
+-->9182
+-->9183
+-->9184
+-->9185
+-->9186
+-->9187
+-->9188
+-->9189
+-->919
+-->9190
+-->9191
+-->9192
+-->9193
+-->9194
+-->9195
+-->9196
+-->9197
+-->9198
+-->9199
+-->92
+-->920
+-->9200
+-->9201
+-->9202
+-->9203
+-->9204
+-->9205
+-->9206
+-->9207
+-->9208
+-->9209
+-->921
+-->9210
+-->9211
+-->9212
+-->9213
+-->9214
+-->9215
+-->9216
+-->9217
+-->9218
+-->9219
+-->922
+-->9220
+-->9221
+-->9222
+-->9223
+-->9224
+-->9225
+-->9226
+-->9227
+-->9228
+-->9229
+-->923
+-->9230
+-->9231
+-->9232
+-->9233
+-->9234
+-->9235
+-->9236
+-->9237
+-->9238
+-->9239
+-->924
+-->9240
+-->9241
+-->9242
+-->9243
+-->9244
+-->9245
+-->9246
+-->9247
+-->9248
+-->9249
+-->925
+-->9250
+-->9251
+-->9252
+-->9253
+-->9254
+-->9255
+-->9256
+-->9257
+-->9258
+-->9259
+-->926
+-->9260
+-->9261
+-->9262
+-->9263
+-->9264
+-->9265
+-->9266
+-->9267
+-->9268
+-->9269
+-->927
+-->9270
+-->9271
+-->9272
+-->9273
+-->9274
+-->9275
+-->9276
+-->9277
+-->9278
+-->9279
+-->928
+-->9280
+-->9281
+-->9282
+-->9283
+-->9284
+-->9285
+-->9286
+-->9287
+-->9288
+-->9289
+-->929
+-->9290
+-->9291
+-->9292
+-->9293
+-->9294
+-->9295
+-->9296
+-->9297
+-->9298
+-->9299
+-->93
+-->930
+-->9300
+-->9301
+-->9302
+-->9303
+-->9304
+-->9305
+-->9306
+-->9307
+-->9308
+-->9309
+-->931
+-->9310
+-->9311
+-->9312
+-->9313
+-->9314
+-->9315
+-->9316
+-->9317
+-->9318
+-->9319
+-->932
+-->9320
+-->9321
+-->9322
+-->9323
+-->9324
+-->9325
+-->9326
+-->9327
+-->9328
+-->9329
+-->933
+-->9330
+-->9331
+-->9332
+-->9333
+-->9334
+-->9335
+-->9336
+-->9337
+-->9338
+-->9339
+-->934
+-->9340
+-->9341
+-->9342
+-->9343
+-->9344
+-->9345
+-->9346
+-->9347
+-->9348
+-->9349
+-->935
+-->9350
+-->9351
+-->9352
+-->9353
+-->9354
+-->9355
+-->9356
+-->9357
+-->9358
+-->9359
+-->936
+-->9360
+-->9361
+-->9362
+-->9363
+-->9364
+-->9365
+-->9366
+-->9367
+-->9368
+-->9369
+-->937
+-->9370
+-->9371
+-->9372
+-->9373
+-->9374
+-->9375
+-->9376
+-->9377
+-->9378
+-->9379
+-->938
+-->9380
+-->9381
+-->9382
+-->9383
+-->9384
+-->9385
+-->9386
+-->9387
+-->9388
+-->9389
+-->939
+-->9390
+-->9391
+-->9392
+-->9393
+-->9394
+-->9395
+-->9396
+-->9397
+-->9398
+-->9399
+-->94
+-->940
+-->9400
+-->9401
+-->9402
+-->9403
+-->9404
+-->9405
+-->9406
+-->9407
+-->9408
+-->9409
+-->941
+-->9410
+-->9411
+-->9412
+-->9413
+-->9414
+-->9415
+-->9416
+-->9417
+-->9418
+-->9419
+-->942
+-->9420
+-->9421
+-->9422
+-->9423
+-->9424
+-->9425
+-->9426
+-->9427
+-->9428
+-->9429
+-->943
+-->9430
+-->9431
+-->9432
+-->9433
+-->9434
+-->9435
+-->9436
+-->9437
+-->9438
+-->9439
+-->944
+-->9440
+-->9441
+-->9442
+-->9443
+-->9444
+-->9445
+-->9446
+-->9447
+-->9448
+-->9449
+-->945
+-->9450
+-->9451
+-->9452
+-->9453
+-->9454
+-->9455
+-->9456
+-->9457
+-->9458
+-->9459
+-->946
+-->9460
+-->9461
+-->9462
+-->9463
+-->9464
+-->9465
+-->9466
+-->9467
+-->9468
+-->9469
+-->947
+-->9470
+-->9471
+-->9472
+-->9473
+-->9474
+-->9475
+-->9476
+-->9477
+-->9478
+-->9479
+-->948
+-->9480
+-->9481
+-->9482
+-->9483
+-->9484
+-->9485
+-->9486
+-->9487
+-->9488
+-->9489
+-->949
+-->9490
+-->9491
+-->9492
+-->9493
+-->9494
+-->9495
+-->9496
+-->9497
+-->9498
+-->9499
+-->95
+-->950
+-->9500
+-->9501
+-->9502
+-->9503
+-->9504
+-->9505
+-->9506
+-->9507
+-->9508
+-->9509
+-->951
+-->9510
+-->9511
+-->9512
+-->9513
+-->9514
+-->9515
+-->9516
+-->9517
+-->9518
+-->9519
+-->952
+-->9520
+-->9521
+-->9522
+-->9523
+-->9524
+-->9525
+-->9526
+-->9527
+-->9528
+-->9529
+-->953
+-->9530
+-->9531
+-->9532
+-->9533
+-->9534
+-->9535
+-->9536
+-->9537
+-->9538
+-->9539
+-->954
+-->9540
+-->9541
+-->9542
+-->9543
+-->9544
+-->9545
+-->9546
+-->9547
+-->9548
+-->9549
+-->955
+-->9550
+-->9551
+-->9552
+-->9553
+-->9554
+-->9555
+-->9556
+-->9557
+-->9558
+-->9559
+-->956
+-->9560
+-->9561
+-->9562
+-->9563
+-->9564
+-->9565
+-->9566
+-->9567
+-->9568
+-->9569
+-->957
+-->9570
+-->9571
+-->9572
+-->9573
+-->9574
+-->9575
+-->9576
+-->9577
+-->9578
+-->9579
+-->958
+-->9580
+-->9581
+-->9582
+-->9583
+-->9584
+-->9585
+-->9586
+-->9587
+-->9588
+-->9589
+-->959
+-->9590
+-->9591
+-->9592
+-->9593
+-->9594
+-->9595
+-->9596
+-->9597
+-->9598
+-->9599
+-->96
+-->960
+-->9600
+-->9601
+-->9602
+-->9603
+-->9604
+-->9605
+-->9606
+-->9607
+-->9608
+-->9609
+-->961
+-->9610
+-->9611
+-->9612
+-->9613
+-->9614
+-->9615
+-->9616
+-->9617
+-->9618
+-->9619
+-->962
+-->9620
+-->9621
+-->9622
+-->9623
+-->9624
+-->9625
+-->9626
+-->9627
+-->9628
+-->9629
+-->963
+-->9630
+-->9631
+-->9632
+-->9633
+-->9634
+-->9635
+-->9636
+-->9637
+-->9638
+-->9639
+-->964
+-->9640
+-->9641
+-->9642
+-->9643
+-->9644
+-->9645
+-->9646
+-->9647
+-->9648
+-->9649
+-->965
+-->9650
+-->9651
+-->9652
+-->9653
+-->9654
+-->9655
+-->9656
+-->9657
+-->9658
+-->9659
+-->966
+-->9660
+-->9661
+-->9662
+-->9663
+-->9664
+-->9665
+-->9666
+-->9667
+-->9668
+-->9669
+-->967
+-->9670
+-->9671
+-->9672
+-->9673
+-->9674
+-->9675
+-->9676
+-->9677
+-->9678
+-->9679
+-->968
+-->9680
+-->9681
+-->9682
+-->9683
+-->9684
+-->9685
+-->9686
+-->9687
+-->9688
+-->9689
+-->969
+-->9690
+-->9691
+-->9692
+-->9693
+-->9694
+-->9695
+-->9696
+-->9697
+-->9698
+-->9699
+-->97
+-->970
+-->9700
+-->9701
+-->9702
+-->9703
+-->9704
+-->9705
+-->9706
+-->9707
+-->9708
+-->9709
+-->971
+-->9710
+-->9711
+-->9712
+-->9713
+-->9714
+-->9715
+-->9716
+-->9717
+-->9718
+-->9719
+-->972
+-->9720
+-->9721
+-->9722
+-->9723
+-->9724
+-->9725
+-->9726
+-->9727
+-->9728
+-->9729
+-->973
+-->9730
+-->9731
+-->9732
+-->9733
+-->9734
+-->9735
+-->9736
+-->9737
+-->9738
+-->9739
+-->974
+-->9740
+-->9741
+-->9742
+-->9743
+-->9744
+-->9745
+-->9746
+-->9747
+-->9748
+-->9749
+-->975
+-->9750
+-->9751
+-->9752
+-->9753
+-->9754
+-->9755
+-->9756
+-->9757
+-->9758
+-->9759
+-->976
+-->9760
+-->9761
+-->9762
+-->9763
+-->9764
+-->9765
+-->9766
+-->9767
+-->9768
+-->9769
+-->977
+-->9770
+-->9771
+-->9772
+-->9773
+-->9774
+-->9775
+-->9776
+-->9777
+-->9778
+-->9779
+-->978
+-->9780
+-->9781
+-->9782
+-->9783
+-->9784
+-->9785
+-->9786
+-->9787
+-->9788
+-->9789
+-->979
+-->9790
+-->9791
+-->9792
+-->9793
+-->9794
+-->9795
+-->9796
+-->9797
+-->9798
+-->9799
+-->98
+-->980
+-->9800
+-->9801
+-->9802
+-->9803
+-->9804
+-->9805
+-->9806
+-->9807
+-->9808
+-->9809
+-->981
+-->9810
+-->9811
+-->9812
+-->9813
+-->9814
+-->9815
+-->9816
+-->9817
+-->9818
+-->9819
+-->982
+-->9820
+-->9821
+-->9822
+-->9823
+-->9824
+-->9825
+-->9826
+-->9827
+-->9828
+-->9829
+-->983
+-->9830
+-->9831
+-->9832
+-->9833
+-->9834
+-->9835
+-->9836
+-->9837
+-->9838
+-->9839
+-->984
+-->9840
+-->9841
+-->9842
+-->9843
+-->9844
+-->9845
+-->9846
+-->9847
+-->9848
+-->9849
+-->985
+-->9850
+-->9851
+-->9852
+-->9853
+-->9854
+-->9855
+-->9856
+-->9857
+-->9858
+-->9859
+-->986
+-->9860
+-->9861
+-->9862
+-->9863
+-->9864
+-->9865
+-->9866
+-->9867
+-->9868
+-->9869
+-->987
+-->9870
+-->9871
+-->9872
+-->9873
+-->9874
+-->9875
+-->9876
+-->9877
+-->9878
+-->9879
+-->988
+-->9880
+-->9881
+-->9882
+-->9883
+-->9884
+-->9885
+-->9886
+-->9887
+-->9888
+-->9889
+-->989
+-->9890
+-->9891
+-->9892
+-->9893
+-->9894
+-->9895
+-->9896
+-->9897
+-->9898
+-->9899
+-->99
+-->990
+-->9900
+-->9901
+-->9902
+-->9903
+-->9904
+-->9905
+-->9906
+-->9907
+-->9908
+-->9909
+-->991
+-->9910
+-->9911
+-->9912
+-->9913
+-->9914
+-->9915
+-->9916
+-->9917
+-->9918
+-->9919
+-->992
+-->9920
+-->9921
+-->9922
+-->9923
+-->9924
+-->9925
+-->9926
+-->9927
+-->9928
+-->9929
+-->993
+-->9930
+-->9931
+-->9932
+-->9933
+-->9934
+-->9935
+-->9936
+-->9937
+-->9938
+-->9939
+-->994
+-->9940
+-->9941
+-->9942
+-->9943
+-->9944
+-->9945
+-->9946
+-->9947
+-->9948
+-->9949
+-->995
+-->9950
+-->9951
+-->9952
+-->9953
+-->9954
+-->9955
+-->9956
+-->9957
+-->9958
+-->9959
+-->996
+-->9960
+-->9961
+-->9962
+-->9963
+-->9964
+-->9965
+-->9966
+-->9967
+-->9968
+-->9969
+-->997
+-->9970
+-->9971
+-->9972
+-->9973
+-->9974
+-->9975
+-->9976
+-->9977
+-->9978
+-->9979
+-->998
+-->9980
+-->9981
+-->9982
+-->9983
+-->9984
+-->9985
+-->9986
+-->9987
+-->9988
+-->9989
+-->999
+-->9990
+-->9991
+-->9992
+-->9993
+-->9994
+-->9995
+-->9996
+-->9997
+-->9998
+-->9999
+0-->
+1-->
+10-->
+100-->
+1000-->
+10000-->
+1001-->
+1002-->
+1003-->
+1004-->
+1005-->
+1006-->
+1007-->
+1008-->
+1009-->
+101-->
+1010-->
+1011-->
+1012-->
+1013-->
+1014-->
+1015-->
+1016-->
+1017-->
+1018-->
+1019-->
+102-->
+1020-->
+1021-->
+1022-->
+1023-->
+1024-->
+1025-->
+1026-->
+1027-->
+1028-->
+1029-->
+103-->
+1030-->
+1031-->
+1032-->
+1033-->
+1034-->
+1035-->
+1036-->
+1037-->
+1038-->
+1039-->
+104-->
+1040-->
+1041-->
+1042-->
+1043-->
+1044-->
+1045-->
+1046-->
+1047-->
+1048-->
+1049-->
+105-->
+1050-->
+1051-->
+1052-->
+1053-->
+1054-->
+1055-->
+1056-->
+1057-->
+1058-->
+1059-->
+106-->
+1060-->
+1061-->
+1062-->
+1063-->
+1064-->
+1065-->
+1066-->
+1067-->
+1068-->
+1069-->
+107-->
+1070-->
+1071-->
+1072-->
+1073-->
+1074-->
+1075-->
+1076-->
+1077-->
+1078-->
+1079-->
+108-->
+1080-->
+1081-->
+1082-->
+1083-->
+1084-->
+1085-->
+1086-->
+1087-->
+1088-->
+1089-->
+109-->
+1090-->
+1091-->
+1092-->
+1093-->
+1094-->
+1095-->
+1096-->
+1097-->
+1098-->
+1099-->
+11-->
+110-->
+1100-->
+1101-->
+1102-->
+1103-->
+1104-->
+1105-->
+1106-->
+1107-->
+1108-->
+1109-->
+111-->
+1110-->
+1111-->
+1112-->
+1113-->
+1114-->
+1115-->
+1116-->
+1117-->
+1118-->
+1119-->
+112-->
+1120-->
+1121-->
+1122-->
+1123-->
+1124-->
+1125-->
+1126-->
+1127-->
+1128-->
+1129-->
+113-->
+1130-->
+1131-->
+1132-->
+1133-->
+1134-->
+1135-->
+1136-->
+1137-->
+1138-->
+1139-->
+114-->
+1140-->
+1141-->
+1142-->
+1143-->
+1144-->
+1145-->
+1146-->
+1147-->
+1148-->
+1149-->
+115-->
+1150-->
+1151-->
+1152-->
+1153-->
+1154-->
+1155-->
+1156-->
+1157-->
+1158-->
+1159-->
+116-->
+1160-->
+1161-->
+1162-->
+1163-->
+1164-->
+1165-->
+1166-->
+1167-->
+1168-->
+1169-->
+117-->
+1170-->
+1171-->
+1172-->
+1173-->
+1174-->
+1175-->
+1176-->
+1177-->
+1178-->
+1179-->
+118-->
+1180-->
+1181-->
+1182-->
+1183-->
+1184-->
+1185-->
+1186-->
+1187-->
+1188-->
+1189-->
+119-->
+1190-->
+1191-->
+1192-->
+1193-->
+1194-->
+1195-->
+1196-->
+1197-->
+1198-->
+1199-->
+12-->
+120-->
+1200-->
+1201-->
+1202-->
+1203-->
+1204-->
+1205-->
+1206-->
+1207-->
+1208-->
+1209-->
+121-->
+1210-->
+1211-->
+1212-->
+1213-->
+1214-->
+1215-->
+1216-->
+1217-->
+1218-->
+1219-->
+122-->
+1220-->
+1221-->
+1222-->
+1223-->
+1224-->
+1225-->
+1226-->
+1227-->
+1228-->
+1229-->
+123-->
+1230-->
+1231-->
+1232-->
+1233-->
+1234-->
+1235-->
+1236-->
+1237-->
+1238-->
+1239-->
+124-->
+1240-->
+1241-->
+1242-->
+1243-->
+1244-->
+1245-->
+1246-->
+1247-->
+1248-->
+1249-->
+125-->
+1250-->
+1251-->
+1252-->
+1253-->
+1254-->
+1255-->
+1256-->
+1257-->
+1258-->
+1259-->
+126-->
+1260-->
+1261-->
+1262-->
+1263-->
+1264-->
+1265-->
+1266-->
+1267-->
+1268-->
+1269-->
+127-->
+1270-->
+1271-->
+1272-->
+1273-->
+1274-->
+1275-->
+1276-->
+1277-->
+1278-->
+1279-->
+128-->
+1280-->
+1281-->
+1282-->
+1283-->
+1284-->
+1285-->
+1286-->
+1287-->
+1288-->
+1289-->
+129-->
+1290-->
+1291-->
+1292-->
+1293-->
+1294-->
+1295-->
+1296-->
+1297-->
+1298-->
+1299-->
+13-->
+130-->
+1300-->
+1301-->
+1302-->
+1303-->
+1304-->
+1305-->
+1306-->
+1307-->
+1308-->
+1309-->
+131-->
+1310-->
+1311-->
+1312-->
+1313-->
+1314-->
+1315-->
+1316-->
+1317-->
+1318-->
+1319-->
+132-->
+1320-->
+1321-->
+1322-->
+1323-->
+1324-->
+1325-->
+1326-->
+1327-->
+1328-->
+1329-->
+133-->
+1330-->
+1331-->
+1332-->
+1333-->
+1334-->
+1335-->
+1336-->
+1337-->
+1338-->
+1339-->
+134-->
+1340-->
+1341-->
+1342-->
+1343-->
+1344-->
+1345-->
+1346-->
+1347-->
+1348-->
+1349-->
+135-->
+1350-->
+1351-->
+1352-->
+1353-->
+1354-->
+1355-->
+1356-->
+1357-->
+1358-->
+1359-->
+136-->
+1360-->
+1361-->
+1362-->
+1363-->
+1364-->
+1365-->
+1366-->
+1367-->
+1368-->
+1369-->
+137-->
+1370-->
+1371-->
+1372-->
+1373-->
+1374-->
+1375-->
+1376-->
+1377-->
+1378-->
+1379-->
+138-->
+1380-->
+1381-->
+1382-->
+1383-->
+1384-->
+1385-->
+1386-->
+1387-->
+1388-->
+1389-->
+139-->
+1390-->
+1391-->
+1392-->
+1393-->
+1394-->
+1395-->
+1396-->
+1397-->
+1398-->
+1399-->
+14-->
+140-->
+1400-->
+1401-->
+1402-->
+1403-->
+1404-->
+1405-->
+1406-->
+1407-->
+1408-->
+1409-->
+141-->
+1410-->
+1411-->
+1412-->
+1413-->
+1414-->
+1415-->
+1416-->
+1417-->
+1418-->
+1419-->
+142-->
+1420-->
+1421-->
+1422-->
+1423-->
+1424-->
+1425-->
+1426-->
+1427-->
+1428-->
+1429-->
+143-->
+1430-->
+1431-->
+1432-->
+1433-->
+1434-->
+1435-->
+1436-->
+1437-->
+1438-->
+1439-->
+144-->
+1440-->
+1441-->
+1442-->
+1443-->
+1444-->
+1445-->
+1446-->
+1447-->
+1448-->
+1449-->
+145-->
+1450-->
+1451-->
+1452-->
+1453-->
+1454-->
+1455-->
+1456-->
+1457-->
+1458-->
+1459-->
+146-->
+1460-->
+1461-->
+1462-->
+1463-->
+1464-->
+1465-->
+1466-->
+1467-->
+1468-->
+1469-->
+147-->
+1470-->
+1471-->
+1472-->
+1473-->
+1474-->
+1475-->
+1476-->
+1477-->
+1478-->
+1479-->
+148-->
+1480-->
+1481-->
+1482-->
+1483-->
+1484-->
+1485-->
+1486-->
+1487-->
+1488-->
+1489-->
+149-->
+1490-->
+1491-->
+1492-->
+1493-->
+1494-->
+1495-->
+1496-->
+1497-->
+1498-->
+1499-->
+15-->
+150-->
+1500-->
+1501-->
+1502-->
+1503-->
+1504-->
+1505-->
+1506-->
+1507-->
+1508-->
+1509-->
+151-->
+1510-->
+1511-->
+1512-->
+1513-->
+1514-->
+1515-->
+1516-->
+1517-->
+1518-->
+1519-->
+152-->
+1520-->
+1521-->
+1522-->
+1523-->
+1524-->
+1525-->
+1526-->
+1527-->
+1528-->
+1529-->
+153-->
+1530-->
+1531-->
+1532-->
+1533-->
+1534-->
+1535-->
+1536-->
+1537-->
+1538-->
+1539-->
+154-->
+1540-->
+1541-->
+1542-->
+1543-->
+1544-->
+1545-->
+1546-->
+1547-->
+1548-->
+1549-->
+155-->
+1550-->
+1551-->
+1552-->
+1553-->
+1554-->
+1555-->
+1556-->
+1557-->
+1558-->
+1559-->
+156-->
+1560-->
+1561-->
+1562-->
+1563-->
+1564-->
+1565-->
+1566-->
+1567-->
+1568-->
+1569-->
+157-->
+1570-->
+1571-->
+1572-->
+1573-->
+1574-->
+1575-->
+1576-->
+1577-->
+1578-->
+1579-->
+158-->
+1580-->
+1581-->
+1582-->
+1583-->
+1584-->
+1585-->
+1586-->
+1587-->
+1588-->
+1589-->
+159-->
+1590-->
+1591-->
+1592-->
+1593-->
+1594-->
+1595-->
+1596-->
+1597-->
+1598-->
+1599-->
+16-->
+160-->
+1600-->
+1601-->
+1602-->
+1603-->
+1604-->
+1605-->
+1606-->
+1607-->
+1608-->
+1609-->
+161-->
+1610-->
+1611-->
+1612-->
+1613-->
+1614-->
+1615-->
+1616-->
+1617-->
+1618-->
+1619-->
+162-->
+1620-->
+1621-->
+1622-->
+1623-->
+1624-->
+1625-->
+1626-->
+1627-->
+1628-->
+1629-->
+163-->
+1630-->
+1631-->
+1632-->
+1633-->
+1634-->
+1635-->
+1636-->
+1637-->
+1638-->
+1639-->
+164-->
+1640-->
+1641-->
+1642-->
+1643-->
+1644-->
+1645-->
+1646-->
+1647-->
+1648-->
+1649-->
+165-->
+1650-->
+1651-->
+1652-->
+1653-->
+1654-->
+1655-->
+1656-->
+1657-->
+1658-->
+1659-->
+166-->
+1660-->
+1661-->
+1662-->
+1663-->
+1664-->
+1665-->
+1666-->
+1667-->
+1668-->
+1669-->
+167-->
+1670-->
+1671-->
+1672-->
+1673-->
+1674-->
+1675-->
+1676-->
+1677-->
+1678-->
+1679-->
+168-->
+1680-->
+1681-->
+1682-->
+1683-->
+1684-->
+1685-->
+1686-->
+1687-->
+1688-->
+1689-->
+169-->
+1690-->
+1691-->
+1692-->
+1693-->
+1694-->
+1695-->
+1696-->
+1697-->
+1698-->
+1699-->
+17-->
+170-->
+1700-->
+1701-->
+1702-->
+1703-->
+1704-->
+1705-->
+1706-->
+1707-->
+1708-->
+1709-->
+171-->
+1710-->
+1711-->
+1712-->
+1713-->
+1714-->
+1715-->
+1716-->
+1717-->
+1718-->
+1719-->
+172-->
+1720-->
+1721-->
+1722-->
+1723-->
+1724-->
+1725-->
+1726-->
+1727-->
+1728-->
+1729-->
+173-->
+1730-->
+1731-->
+1732-->
+1733-->
+1734-->
+1735-->
+1736-->
+1737-->
+1738-->
+1739-->
+174-->
+1740-->
+1741-->
+1742-->
+1743-->
+1744-->
+1745-->
+1746-->
+1747-->
+1748-->
+1749-->
+175-->
+1750-->
+1751-->
+1752-->
+1753-->
+1754-->
+1755-->
+1756-->
+1757-->
+1758-->
+1759-->
+176-->
+1760-->
+1761-->
+1762-->
+1763-->
+1764-->
+1765-->
+1766-->
+1767-->
+1768-->
+1769-->
+177-->
+1770-->
+1771-->
+1772-->
+1773-->
+1774-->
+1775-->
+1776-->
+1777-->
+1778-->
+1779-->
+178-->
+1780-->
+1781-->
+1782-->
+1783-->
+1784-->
+1785-->
+1786-->
+1787-->
+1788-->
+1789-->
+179-->
+1790-->
+1791-->
+1792-->
+1793-->
+1794-->
+1795-->
+1796-->
+1797-->
+1798-->
+1799-->
+18-->
+180-->
+1800-->
+1801-->
+1802-->
+1803-->
+1804-->
+1805-->
+1806-->
+1807-->
+1808-->
+1809-->
+181-->
+1810-->
+1811-->
+1812-->
+1813-->
+1814-->
+1815-->
+1816-->
+1817-->
+1818-->
+1819-->
+182-->
+1820-->
+1821-->
+1822-->
+1823-->
+1824-->
+1825-->
+1826-->
+1827-->
+1828-->
+1829-->
+183-->
+1830-->
+1831-->
+1832-->
+1833-->
+1834-->
+1835-->
+1836-->
+1837-->
+1838-->
+1839-->
+184-->
+1840-->
+1841-->
+1842-->
+1843-->
+1844-->
+1845-->
+1846-->
+1847-->
+1848-->
+1849-->
+185-->
+1850-->
+1851-->
+1852-->
+1853-->
+1854-->
+1855-->
+1856-->
+1857-->
+1858-->
+1859-->
+186-->
+1860-->
+1861-->
+1862-->
+1863-->
+1864-->
+1865-->
+1866-->
+1867-->
+1868-->
+1869-->
+187-->
+1870-->
+1871-->
+1872-->
+1873-->
+1874-->
+1875-->
+1876-->
+1877-->
+1878-->
+1879-->
+188-->
+1880-->
+1881-->
+1882-->
+1883-->
+1884-->
+1885-->
+1886-->
+1887-->
+1888-->
+1889-->
+189-->
+1890-->
+1891-->
+1892-->
+1893-->
+1894-->
+1895-->
+1896-->
+1897-->
+1898-->
+1899-->
+19-->
+190-->
+1900-->
+1901-->
+1902-->
+1903-->
+1904-->
+1905-->
+1906-->
+1907-->
+1908-->
+1909-->
+191-->
+1910-->
+1911-->
+1912-->
+1913-->
+1914-->
+1915-->
+1916-->
+1917-->
+1918-->
+1919-->
+192-->
+1920-->
+1921-->
+1922-->
+1923-->
+1924-->
+1925-->
+1926-->
+1927-->
+1928-->
+1929-->
+193-->
+1930-->
+1931-->
+1932-->
+1933-->
+1934-->
+1935-->
+1936-->
+1937-->
+1938-->
+1939-->
+194-->
+1940-->
+1941-->
+1942-->
+1943-->
+1944-->
+1945-->
+1946-->
+1947-->
+1948-->
+1949-->
+195-->
+1950-->
+1951-->
+1952-->
+1953-->
+1954-->
+1955-->
+1956-->
+1957-->
+1958-->
+1959-->
+196-->
+1960-->
+1961-->
+1962-->
+1963-->
+1964-->
+1965-->
+1966-->
+1967-->
+1968-->
+1969-->
+197-->
+1970-->
+1971-->
+1972-->
+1973-->
+1974-->
+1975-->
+1976-->
+1977-->
+1978-->
+1979-->
+198-->
+1980-->
+1981-->
+1982-->
+1983-->
+1984-->
+1985-->
+1986-->
+1987-->
+1988-->
+1989-->
+199-->
+1990-->
+1991-->
+1992-->
+1993-->
+1994-->
+1995-->
+1996-->
+1997-->
+1998-->
+1999-->
+2-->
+20-->
+200-->
+2000-->
+2001-->
+2002-->
+2003-->
+2004-->
+2005-->
+2006-->
+2007-->
+2008-->
+2009-->
+201-->
+2010-->
+2011-->
+2012-->
+2013-->
+2014-->
+2015-->
+2016-->
+2017-->
+2018-->
+2019-->
+202-->
+2020-->
+2021-->
+2022-->
+2023-->
+2024-->
+2025-->
+2026-->
+2027-->
+2028-->
+2029-->
+203-->
+2030-->
+2031-->
+2032-->
+2033-->
+2034-->
+2035-->
+2036-->
+2037-->
+2038-->
+2039-->
+204-->
+2040-->
+2041-->
+2042-->
+2043-->
+2044-->
+2045-->
+2046-->
+2047-->
+2048-->
+2049-->
+205-->
+2050-->
+2051-->
+2052-->
+2053-->
+2054-->
+2055-->
+2056-->
+2057-->
+2058-->
+2059-->
+206-->
+2060-->
+2061-->
+2062-->
+2063-->
+2064-->
+2065-->
+2066-->
+2067-->
+2068-->
+2069-->
+207-->
+2070-->
+2071-->
+2072-->
+2073-->
+2074-->
+2075-->
+2076-->
+2077-->
+2078-->
+2079-->
+208-->
+2080-->
+2081-->
+2082-->
+2083-->
+2084-->
+2085-->
+2086-->
+2087-->
+2088-->
+2089-->
+209-->
+2090-->
+2091-->
+2092-->
+2093-->
+2094-->
+2095-->
+2096-->
+2097-->
+2098-->
+2099-->
+21-->
+210-->
+2100-->
+2101-->
+2102-->
+2103-->
+2104-->
+2105-->
+2106-->
+2107-->
+2108-->
+2109-->
+211-->
+2110-->
+2111-->
+2112-->
+2113-->
+2114-->
+2115-->
+2116-->
+2117-->
+2118-->
+2119-->
+212-->
+2120-->
+2121-->
+2122-->
+2123-->
+2124-->
+2125-->
+2126-->
+2127-->
+2128-->
+2129-->
+213-->
+2130-->
+2131-->
+2132-->
+2133-->
+2134-->
+2135-->
+2136-->
+2137-->
+2138-->
+2139-->
+214-->
+2140-->
+2141-->
+2142-->
+2143-->
+2144-->
+2145-->
+2146-->
+2147-->
+2148-->
+2149-->
+215-->
+2150-->
+2151-->
+2152-->
+2153-->
+2154-->
+2155-->
+2156-->
+2157-->
+2158-->
+2159-->
+216-->
+2160-->
+2161-->
+2162-->
+2163-->
+2164-->
+2165-->
+2166-->
+2167-->
+2168-->
+2169-->
+217-->
+2170-->
+2171-->
+2172-->
+2173-->
+2174-->
+2175-->
+2176-->
+2177-->
+2178-->
+2179-->
+218-->
+2180-->
+2181-->
+2182-->
+2183-->
+2184-->
+2185-->
+2186-->
+2187-->
+2188-->
+2189-->
+219-->
+2190-->
+2191-->
+2192-->
+2193-->
+2194-->
+2195-->
+2196-->
+2197-->
+2198-->
+2199-->
+22-->
+220-->
+2200-->
+2201-->
+2202-->
+2203-->
+2204-->
+2205-->
+2206-->
+2207-->
+2208-->
+2209-->
+221-->
+2210-->
+2211-->
+2212-->
+2213-->
+2214-->
+2215-->
+2216-->
+2217-->
+2218-->
+2219-->
+222-->
+2220-->
+2221-->
+2222-->
+2223-->
+2224-->
+2225-->
+2226-->
+2227-->
+2228-->
+2229-->
+223-->
+2230-->
+2231-->
+2232-->
+2233-->
+2234-->
+2235-->
+2236-->
+2237-->
+2238-->
+2239-->
+224-->
+2240-->
+2241-->
+2242-->
+2243-->
+2244-->
+2245-->
+2246-->
+2247-->
+2248-->
+2249-->
+225-->
+2250-->
+2251-->
+2252-->
+2253-->
+2254-->
+2255-->
+2256-->
+2257-->
+2258-->
+2259-->
+226-->
+2260-->
+2261-->
+2262-->
+2263-->
+2264-->
+2265-->
+2266-->
+2267-->
+2268-->
+2269-->
+227-->
+2270-->
+2271-->
+2272-->
+2273-->
+2274-->
+2275-->
+2276-->
+2277-->
+2278-->
+2279-->
+228-->
+2280-->
+2281-->
+2282-->
+2283-->
+2284-->
+2285-->
+2286-->
+2287-->
+2288-->
+2289-->
+229-->
+2290-->
+2291-->
+2292-->
+2293-->
+2294-->
+2295-->
+2296-->
+2297-->
+2298-->
+2299-->
+23-->
+230-->
+2300-->
+2301-->
+2302-->
+2303-->
+2304-->
+2305-->
+2306-->
+2307-->
+2308-->
+2309-->
+231-->
+2310-->
+2311-->
+2312-->
+2313-->
+2314-->
+2315-->
+2316-->
+2317-->
+2318-->
+2319-->
+232-->
+2320-->
+2321-->
+2322-->
+2323-->
+2324-->
+2325-->
+2326-->
+2327-->
+2328-->
+2329-->
+233-->
+2330-->
+2331-->
+2332-->
+2333-->
+2334-->
+2335-->
+2336-->
+2337-->
+2338-->
+2339-->
+234-->
+2340-->
+2341-->
+2342-->
+2343-->
+2344-->
+2345-->
+2346-->
+2347-->
+2348-->
+2349-->
+235-->
+2350-->
+2351-->
+2352-->
+2353-->
+2354-->
+2355-->
+2356-->
+2357-->
+2358-->
+2359-->
+236-->
+2360-->
+2361-->
+2362-->
+2363-->
+2364-->
+2365-->
+2366-->
+2367-->
+2368-->
+2369-->
+237-->
+2370-->
+2371-->
+2372-->
+2373-->
+2374-->
+2375-->
+2376-->
+2377-->
+2378-->
+2379-->
+238-->
+2380-->
+2381-->
+2382-->
+2383-->
+2384-->
+2385-->
+2386-->
+2387-->
+2388-->
+2389-->
+239-->
+2390-->
+2391-->
+2392-->
+2393-->
+2394-->
+2395-->
+2396-->
+2397-->
+2398-->
+2399-->
+24-->
+240-->
+2400-->
+2401-->
+2402-->
+2403-->
+2404-->
+2405-->
+2406-->
+2407-->
+2408-->
+2409-->
+241-->
+2410-->
+2411-->
+2412-->
+2413-->
+2414-->
+2415-->
+2416-->
+2417-->
+2418-->
+2419-->
+242-->
+2420-->
+2421-->
+2422-->
+2423-->
+2424-->
+2425-->
+2426-->
+2427-->
+2428-->
+2429-->
+243-->
+2430-->
+2431-->
+2432-->
+2433-->
+2434-->
+2435-->
+2436-->
+2437-->
+2438-->
+2439-->
+244-->
+2440-->
+2441-->
+2442-->
+2443-->
+2444-->
+2445-->
+2446-->
+2447-->
+2448-->
+2449-->
+245-->
+2450-->
+2451-->
+2452-->
+2453-->
+2454-->
+2455-->
+2456-->
+2457-->
+2458-->
+2459-->
+246-->
+2460-->
+2461-->
+2462-->
+2463-->
+2464-->
+2465-->
+2466-->
+2467-->
+2468-->
+2469-->
+247-->
+2470-->
+2471-->
+2472-->
+2473-->
+2474-->
+2475-->
+2476-->
+2477-->
+2478-->
+2479-->
+248-->
+2480-->
+2481-->
+2482-->
+2483-->
+2484-->
+2485-->
+2486-->
+2487-->
+2488-->
+2489-->
+249-->
+2490-->
+2491-->
+2492-->
+2493-->
+2494-->
+2495-->
+2496-->
+2497-->
+2498-->
+2499-->
+25-->
+250-->
+2500-->
+2501-->
+2502-->
+2503-->
+2504-->
+2505-->
+2506-->
+2507-->
+2508-->
+2509-->
+251-->
+2510-->
+2511-->
+2512-->
+2513-->
+2514-->
+2515-->
+2516-->
+2517-->
+2518-->
+2519-->
+252-->
+2520-->
+2521-->
+2522-->
+2523-->
+2524-->
+2525-->
+2526-->
+2527-->
+2528-->
+2529-->
+253-->
+2530-->
+2531-->
+2532-->
+2533-->
+2534-->
+2535-->
+2536-->
+2537-->
+2538-->
+2539-->
+254-->
+2540-->
+2541-->
+2542-->
+2543-->
+2544-->
+2545-->
+2546-->
+2547-->
+2548-->
+2549-->
+255-->
+2550-->
+2551-->
+2552-->
+2553-->
+2554-->
+2555-->
+2556-->
+2557-->
+2558-->
+2559-->
+256-->
+2560-->
+2561-->
+2562-->
+2563-->
+2564-->
+2565-->
+2566-->
+2567-->
+2568-->
+2569-->
+257-->
+2570-->
+2571-->
+2572-->
+2573-->
+2574-->
+2575-->
+2576-->
+2577-->
+2578-->
+2579-->
+258-->
+2580-->
+2581-->
+2582-->
+2583-->
+2584-->
+2585-->
+2586-->
+2587-->
+2588-->
+2589-->
+259-->
+2590-->
+2591-->
+2592-->
+2593-->
+2594-->
+2595-->
+2596-->
+2597-->
+2598-->
+2599-->
+26-->
+260-->
+2600-->
+2601-->
+2602-->
+2603-->
+2604-->
+2605-->
+2606-->
+2607-->
+2608-->
+2609-->
+261-->
+2610-->
+2611-->
+2612-->
+2613-->
+2614-->
+2615-->
+2616-->
+2617-->
+2618-->
+2619-->
+262-->
+2620-->
+2621-->
+2622-->
+2623-->
+2624-->
+2625-->
+2626-->
+2627-->
+2628-->
+2629-->
+263-->
+2630-->
+2631-->
+2632-->
+2633-->
+2634-->
+2635-->
+2636-->
+2637-->
+2638-->
+2639-->
+264-->
+2640-->
+2641-->
+2642-->
+2643-->
+2644-->
+2645-->
+2646-->
+2647-->
+2648-->
+2649-->
+265-->
+2650-->
+2651-->
+2652-->
+2653-->
+2654-->
+2655-->
+2656-->
+2657-->
+2658-->
+2659-->
+266-->
+2660-->
+2661-->
+2662-->
+2663-->
+2664-->
+2665-->
+2666-->
+2667-->
+2668-->
+2669-->
+267-->
+2670-->
+2671-->
+2672-->
+2673-->
+2674-->
+2675-->
+2676-->
+2677-->
+2678-->
+2679-->
+268-->
+2680-->
+2681-->
+2682-->
+2683-->
+2684-->
+2685-->
+2686-->
+2687-->
+2688-->
+2689-->
+269-->
+2690-->
+2691-->
+2692-->
+2693-->
+2694-->
+2695-->
+2696-->
+2697-->
+2698-->
+2699-->
+27-->
+270-->
+2700-->
+2701-->
+2702-->
+2703-->
+2704-->
+2705-->
+2706-->
+2707-->
+2708-->
+2709-->
+271-->
+2710-->
+2711-->
+2712-->
+2713-->
+2714-->
+2715-->
+2716-->
+2717-->
+2718-->
+2719-->
+272-->
+2720-->
+2721-->
+2722-->
+2723-->
+2724-->
+2725-->
+2726-->
+2727-->
+2728-->
+2729-->
+273-->
+2730-->
+2731-->
+2732-->
+2733-->
+2734-->
+2735-->
+2736-->
+2737-->
+2738-->
+2739-->
+274-->
+2740-->
+2741-->
+2742-->
+2743-->
+2744-->
+2745-->
+2746-->
+2747-->
+2748-->
+2749-->
+275-->
+2750-->
+2751-->
+2752-->
+2753-->
+2754-->
+2755-->
+2756-->
+2757-->
+2758-->
+2759-->
+276-->
+2760-->
+2761-->
+2762-->
+2763-->
+2764-->
+2765-->
+2766-->
+2767-->
+2768-->
+2769-->
+277-->
+2770-->
+2771-->
+2772-->
+2773-->
+2774-->
+2775-->
+2776-->
+2777-->
+2778-->
+2779-->
+278-->
+2780-->
+2781-->
+2782-->
+2783-->
+2784-->
+2785-->
+2786-->
+2787-->
+2788-->
+2789-->
+279-->
+2790-->
+2791-->
+2792-->
+2793-->
+2794-->
+2795-->
+2796-->
+2797-->
+2798-->
+2799-->
+28-->
+280-->
+2800-->
+2801-->
+2802-->
+2803-->
+2804-->
+2805-->
+2806-->
+2807-->
+2808-->
+2809-->
+281-->
+2810-->
+2811-->
+2812-->
+2813-->
+2814-->
+2815-->
+2816-->
+2817-->
+2818-->
+2819-->
+282-->
+2820-->
+2821-->
+2822-->
+2823-->
+2824-->
+2825-->
+2826-->
+2827-->
+2828-->
+2829-->
+283-->
+2830-->
+2831-->
+2832-->
+2833-->
+2834-->
+2835-->
+2836-->
+2837-->
+2838-->
+2839-->
+284-->
+2840-->
+2841-->
+2842-->
+2843-->
+2844-->
+2845-->
+2846-->
+2847-->
+2848-->
+2849-->
+285-->
+2850-->
+2851-->
+2852-->
+2853-->
+2854-->
+2855-->
+2856-->
+2857-->
+2858-->
+2859-->
+286-->
+2860-->
+2861-->
+2862-->
+2863-->
+2864-->
+2865-->
+2866-->
+2867-->
+2868-->
+2869-->
+287-->
+2870-->
+2871-->
+2872-->
+2873-->
+2874-->
+2875-->
+2876-->
+2877-->
+2878-->
+2879-->
+288-->
+2880-->
+2881-->
+2882-->
+2883-->
+2884-->
+2885-->
+2886-->
+2887-->
+2888-->
+2889-->
+289-->
+2890-->
+2891-->
+2892-->
+2893-->
+2894-->
+2895-->
+2896-->
+2897-->
+2898-->
+2899-->
+29-->
+290-->
+2900-->
+2901-->
+2902-->
+2903-->
+2904-->
+2905-->
+2906-->
+2907-->
+2908-->
+2909-->
+291-->
+2910-->
+2911-->
+2912-->
+2913-->
+2914-->
+2915-->
+2916-->
+2917-->
+2918-->
+2919-->
+292-->
+2920-->
+2921-->
+2922-->
+2923-->
+2924-->
+2925-->
+2926-->
+2927-->
+2928-->
+2929-->
+293-->
+2930-->
+2931-->
+2932-->
+2933-->
+2934-->
+2935-->
+2936-->
+2937-->
+2938-->
+2939-->
+294-->
+2940-->
+2941-->
+2942-->
+2943-->
+2944-->
+2945-->
+2946-->
+2947-->
+2948-->
+2949-->
+295-->
+2950-->
+2951-->
+2952-->
+2953-->
+2954-->
+2955-->
+2956-->
+2957-->
+2958-->
+2959-->
+296-->
+2960-->
+2961-->
+2962-->
+2963-->
+2964-->
+2965-->
+2966-->
+2967-->
+2968-->
+2969-->
+297-->
+2970-->
+2971-->
+2972-->
+2973-->
+2974-->
+2975-->
+2976-->
+2977-->
+2978-->
+2979-->
+298-->
+2980-->
+2981-->
+2982-->
+2983-->
+2984-->
+2985-->
+2986-->
+2987-->
+2988-->
+2989-->
+299-->
+2990-->
+2991-->
+2992-->
+2993-->
+2994-->
+2995-->
+2996-->
+2997-->
+2998-->
+2999-->
+3-->
+30-->
+300-->
+3000-->
+3001-->
+3002-->
+3003-->
+3004-->
+3005-->
+3006-->
+3007-->
+3008-->
+3009-->
+301-->
+3010-->
+3011-->
+3012-->
+3013-->
+3014-->
+3015-->
+3016-->
+3017-->
+3018-->
+3019-->
+302-->
+3020-->
+3021-->
+3022-->
+3023-->
+3024-->
+3025-->
+3026-->
+3027-->
+3028-->
+3029-->
+303-->
+3030-->
+3031-->
+3032-->
+3033-->
+3034-->
+3035-->
+3036-->
+3037-->
+3038-->
+3039-->
+304-->
+3040-->
+3041-->
+3042-->
+3043-->
+3044-->
+3045-->
+3046-->
+3047-->
+3048-->
+3049-->
+305-->
+3050-->
+3051-->
+3052-->
+3053-->
+3054-->
+3055-->
+3056-->
+3057-->
+3058-->
+3059-->
+306-->
+3060-->
+3061-->
+3062-->
+3063-->
+3064-->
+3065-->
+3066-->
+3067-->
+3068-->
+3069-->
+307-->
+3070-->
+3071-->
+3072-->
+3073-->
+3074-->
+3075-->
+3076-->
+3077-->
+3078-->
+3079-->
+308-->
+3080-->
+3081-->
+3082-->
+3083-->
+3084-->
+3085-->
+3086-->
+3087-->
+3088-->
+3089-->
+309-->
+3090-->
+3091-->
+3092-->
+3093-->
+3094-->
+3095-->
+3096-->
+3097-->
+3098-->
+3099-->
+31-->
+310-->
+3100-->
+3101-->
+3102-->
+3103-->
+3104-->
+3105-->
+3106-->
+3107-->
+3108-->
+3109-->
+311-->
+3110-->
+3111-->
+3112-->
+3113-->
+3114-->
+3115-->
+3116-->
+3117-->
+3118-->
+3119-->
+312-->
+3120-->
+3121-->
+3122-->
+3123-->
+3124-->
+3125-->
+3126-->
+3127-->
+3128-->
+3129-->
+313-->
+3130-->
+3131-->
+3132-->
+3133-->
+3134-->
+3135-->
+3136-->
+3137-->
+3138-->
+3139-->
+314-->
+3140-->
+3141-->
+3142-->
+3143-->
+3144-->
+3145-->
+3146-->
+3147-->
+3148-->
+3149-->
+315-->
+3150-->
+3151-->
+3152-->
+3153-->
+3154-->
+3155-->
+3156-->
+3157-->
+3158-->
+3159-->
+316-->
+3160-->
+3161-->
+3162-->
+3163-->
+3164-->
+3165-->
+3166-->
+3167-->
+3168-->
+3169-->
+317-->
+3170-->
+3171-->
+3172-->
+3173-->
+3174-->
+3175-->
+3176-->
+3177-->
+3178-->
+3179-->
+318-->
+3180-->
+3181-->
+3182-->
+3183-->
+3184-->
+3185-->
+3186-->
+3187-->
+3188-->
+3189-->
+319-->
+3190-->
+3191-->
+3192-->
+3193-->
+3194-->
+3195-->
+3196-->
+3197-->
+3198-->
+3199-->
+32-->
+320-->
+3200-->
+3201-->
+3202-->
+3203-->
+3204-->
+3205-->
+3206-->
+3207-->
+3208-->
+3209-->
+321-->
+3210-->
+3211-->
+3212-->
+3213-->
+3214-->
+3215-->
+3216-->
+3217-->
+3218-->
+3219-->
+322-->
+3220-->
+3221-->
+3222-->
+3223-->
+3224-->
+3225-->
+3226-->
+3227-->
+3228-->
+3229-->
+323-->
+3230-->
+3231-->
+3232-->
+3233-->
+3234-->
+3235-->
+3236-->
+3237-->
+3238-->
+3239-->
+324-->
+3240-->
+3241-->
+3242-->
+3243-->
+3244-->
+3245-->
+3246-->
+3247-->
+3248-->
+3249-->
+325-->
+3250-->
+3251-->
+3252-->
+3253-->
+3254-->
+3255-->
+3256-->
+3257-->
+3258-->
+3259-->
+326-->
+3260-->
+3261-->
+3262-->
+3263-->
+3264-->
+3265-->
+3266-->
+3267-->
+3268-->
+3269-->
+327-->
+3270-->
+3271-->
+3272-->
+3273-->
+3274-->
+3275-->
+3276-->
+3277-->
+3278-->
+3279-->
+328-->
+3280-->
+3281-->
+3282-->
+3283-->
+3284-->
+3285-->
+3286-->
+3287-->
+3288-->
+3289-->
+329-->
+3290-->
+3291-->
+3292-->
+3293-->
+3294-->
+3295-->
+3296-->
+3297-->
+3298-->
+3299-->
+33-->
+330-->
+3300-->
+3301-->
+3302-->
+3303-->
+3304-->
+3305-->
+3306-->
+3307-->
+3308-->
+3309-->
+331-->
+3310-->
+3311-->
+3312-->
+3313-->
+3314-->
+3315-->
+3316-->
+3317-->
+3318-->
+3319-->
+332-->
+3320-->
+3321-->
+3322-->
+3323-->
+3324-->
+3325-->
+3326-->
+3327-->
+3328-->
+3329-->
+333-->
+3330-->
+3331-->
+3332-->
+3333-->
+3334-->
+3335-->
+3336-->
+3337-->
+3338-->
+3339-->
+334-->
+3340-->
+3341-->
+3342-->
+3343-->
+3344-->
+3345-->
+3346-->
+3347-->
+3348-->
+3349-->
+335-->
+3350-->
+3351-->
+3352-->
+3353-->
+3354-->
+3355-->
+3356-->
+3357-->
+3358-->
+3359-->
+336-->
+3360-->
+3361-->
+3362-->
+3363-->
+3364-->
+3365-->
+3366-->
+3367-->
+3368-->
+3369-->
+337-->
+3370-->
+3371-->
+3372-->
+3373-->
+3374-->
+3375-->
+3376-->
+3377-->
+3378-->
+3379-->
+338-->
+3380-->
+3381-->
+3382-->
+3383-->
+3384-->
+3385-->
+3386-->
+3387-->
+3388-->
+3389-->
+339-->
+3390-->
+3391-->
+3392-->
+3393-->
+3394-->
+3395-->
+3396-->
+3397-->
+3398-->
+3399-->
+34-->
+340-->
+3400-->
+3401-->
+3402-->
+3403-->
+3404-->
+3405-->
+3406-->
+3407-->
+3408-->
+3409-->
+341-->
+3410-->
+3411-->
+3412-->
+3413-->
+3414-->
+3415-->
+3416-->
+3417-->
+3418-->
+3419-->
+342-->
+3420-->
+3421-->
+3422-->
+3423-->
+3424-->
+3425-->
+3426-->
+3427-->
+3428-->
+3429-->
+343-->
+3430-->
+3431-->
+3432-->
+3433-->
+3434-->
+3435-->
+3436-->
+3437-->
+3438-->
+3439-->
+344-->
+3440-->
+3441-->
+3442-->
+3443-->
+3444-->
+3445-->
+3446-->
+3447-->
+3448-->
+3449-->
+345-->
+3450-->
+3451-->
+3452-->
+3453-->
+3454-->
+3455-->
+3456-->
+3457-->
+3458-->
+3459-->
+346-->
+3460-->
+3461-->
+3462-->
+3463-->
+3464-->
+3465-->
+3466-->
+3467-->
+3468-->
+3469-->
+347-->
+3470-->
+3471-->
+3472-->
+3473-->
+3474-->
+3475-->
+3476-->
+3477-->
+3478-->
+3479-->
+348-->
+3480-->
+3481-->
+3482-->
+3483-->
+3484-->
+3485-->
+3486-->
+3487-->
+3488-->
+3489-->
+349-->
+3490-->
+3491-->
+3492-->
+3493-->
+3494-->
+3495-->
+3496-->
+3497-->
+3498-->
+3499-->
+35-->
+350-->
+3500-->
+3501-->
+3502-->
+3503-->
+3504-->
+3505-->
+3506-->
+3507-->
+3508-->
+3509-->
+351-->
+3510-->
+3511-->
+3512-->
+3513-->
+3514-->
+3515-->
+3516-->
+3517-->
+3518-->
+3519-->
+352-->
+3520-->
+3521-->
+3522-->
+3523-->
+3524-->
+3525-->
+3526-->
+3527-->
+3528-->
+3529-->
+353-->
+3530-->
+3531-->
+3532-->
+3533-->
+3534-->
+3535-->
+3536-->
+3537-->
+3538-->
+3539-->
+354-->
+3540-->
+3541-->
+3542-->
+3543-->
+3544-->
+3545-->
+3546-->
+3547-->
+3548-->
+3549-->
+355-->
+3550-->
+3551-->
+3552-->
+3553-->
+3554-->
+3555-->
+3556-->
+3557-->
+3558-->
+3559-->
+356-->
+3560-->
+3561-->
+3562-->
+3563-->
+3564-->
+3565-->
+3566-->
+3567-->
+3568-->
+3569-->
+357-->
+3570-->
+3571-->
+3572-->
+3573-->
+3574-->
+3575-->
+3576-->
+3577-->
+3578-->
+3579-->
+358-->
+3580-->
+3581-->
+3582-->
+3583-->
+3584-->
+3585-->
+3586-->
+3587-->
+3588-->
+3589-->
+359-->
+3590-->
+3591-->
+3592-->
+3593-->
+3594-->
+3595-->
+3596-->
+3597-->
+3598-->
+3599-->
+36-->
+360-->
+3600-->
+3601-->
+3602-->
+3603-->
+3604-->
+3605-->
+3606-->
+3607-->
+3608-->
+3609-->
+361-->
+3610-->
+3611-->
+3612-->
+3613-->
+3614-->
+3615-->
+3616-->
+3617-->
+3618-->
+3619-->
+362-->
+3620-->
+3621-->
+3622-->
+3623-->
+3624-->
+3625-->
+3626-->
+3627-->
+3628-->
+3629-->
+363-->
+3630-->
+3631-->
+3632-->
+3633-->
+3634-->
+3635-->
+3636-->
+3637-->
+3638-->
+3639-->
+364-->
+3640-->
+3641-->
+3642-->
+3643-->
+3644-->
+3645-->
+3646-->
+3647-->
+3648-->
+3649-->
+365-->
+3650-->
+3651-->
+3652-->
+3653-->
+3654-->
+3655-->
+3656-->
+3657-->
+3658-->
+3659-->
+366-->
+3660-->
+3661-->
+3662-->
+3663-->
+3664-->
+3665-->
+3666-->
+3667-->
+3668-->
+3669-->
+367-->
+3670-->
+3671-->
+3672-->
+3673-->
+3674-->
+3675-->
+3676-->
+3677-->
+3678-->
+3679-->
+368-->
+3680-->
+3681-->
+3682-->
+3683-->
+3684-->
+3685-->
+3686-->
+3687-->
+3688-->
+3689-->
+369-->
+3690-->
+3691-->
+3692-->
+3693-->
+3694-->
+3695-->
+3696-->
+3697-->
+3698-->
+3699-->
+37-->
+370-->
+3700-->
+3701-->
+3702-->
+3703-->
+3704-->
+3705-->
+3706-->
+3707-->
+3708-->
+3709-->
+371-->
+3710-->
+3711-->
+3712-->
+3713-->
+3714-->
+3715-->
+3716-->
+3717-->
+3718-->
+3719-->
+372-->
+3720-->
+3721-->
+3722-->
+3723-->
+3724-->
+3725-->
+3726-->
+3727-->
+3728-->
+3729-->
+373-->
+3730-->
+3731-->
+3732-->
+3733-->
+3734-->
+3735-->
+3736-->
+3737-->
+3738-->
+3739-->
+374-->
+3740-->
+3741-->
+3742-->
+3743-->
+3744-->
+3745-->
+3746-->
+3747-->
+3748-->
+3749-->
+375-->
+3750-->
+3751-->
+3752-->
+3753-->
+3754-->
+3755-->
+3756-->
+3757-->
+3758-->
+3759-->
+376-->
+3760-->
+3761-->
+3762-->
+3763-->
+3764-->
+3765-->
+3766-->
+3767-->
+3768-->
+3769-->
+377-->
+3770-->
+3771-->
+3772-->
+3773-->
+3774-->
+3775-->
+3776-->
+3777-->
+3778-->
+3779-->
+378-->
+3780-->
+3781-->
+3782-->
+3783-->
+3784-->
+3785-->
+3786-->
+3787-->
+3788-->
+3789-->
+379-->
+3790-->
+3791-->
+3792-->
+3793-->
+3794-->
+3795-->
+3796-->
+3797-->
+3798-->
+3799-->
+38-->
+380-->
+3800-->
+3801-->
+3802-->
+3803-->
+3804-->
+3805-->
+3806-->
+3807-->
+3808-->
+3809-->
+381-->
+3810-->
+3811-->
+3812-->
+3813-->
+3814-->
+3815-->
+3816-->
+3817-->
+3818-->
+3819-->
+382-->
+3820-->
+3821-->
+3822-->
+3823-->
+3824-->
+3825-->
+3826-->
+3827-->
+3828-->
+3829-->
+383-->
+3830-->
+3831-->
+3832-->
+3833-->
+3834-->
+3835-->
+3836-->
+3837-->
+3838-->
+3839-->
+384-->
+3840-->
+3841-->
+3842-->
+3843-->
+3844-->
+3845-->
+3846-->
+3847-->
+3848-->
+3849-->
+385-->
+3850-->
+3851-->
+3852-->
+3853-->
+3854-->
+3855-->
+3856-->
+3857-->
+3858-->
+3859-->
+386-->
+3860-->
+3861-->
+3862-->
+3863-->
+3864-->
+3865-->
+3866-->
+3867-->
+3868-->
+3869-->
+387-->
+3870-->
+3871-->
+3872-->
+3873-->
+3874-->
+3875-->
+3876-->
+3877-->
+3878-->
+3879-->
+388-->
+3880-->
+3881-->
+3882-->
+3883-->
+3884-->
+3885-->
+3886-->
+3887-->
+3888-->
+3889-->
+389-->
+3890-->
+3891-->
+3892-->
+3893-->
+3894-->
+3895-->
+3896-->
+3897-->
+3898-->
+3899-->
+39-->
+390-->
+3900-->
+3901-->
+3902-->
+3903-->
+3904-->
+3905-->
+3906-->
+3907-->
+3908-->
+3909-->
+391-->
+3910-->
+3911-->
+3912-->
+3913-->
+3914-->
+3915-->
+3916-->
+3917-->
+3918-->
+3919-->
+392-->
+3920-->
+3921-->
+3922-->
+3923-->
+3924-->
+3925-->
+3926-->
+3927-->
+3928-->
+3929-->
+393-->
+3930-->
+3931-->
+3932-->
+3933-->
+3934-->
+3935-->
+3936-->
+3937-->
+3938-->
+3939-->
+394-->
+3940-->
+3941-->
+3942-->
+3943-->
+3944-->
+3945-->
+3946-->
+3947-->
+3948-->
+3949-->
+395-->
+3950-->
+3951-->
+3952-->
+3953-->
+3954-->
+3955-->
+3956-->
+3957-->
+3958-->
+3959-->
+396-->
+3960-->
+3961-->
+3962-->
+3963-->
+3964-->
+3965-->
+3966-->
+3967-->
+3968-->
+3969-->
+397-->
+3970-->
+3971-->
+3972-->
+3973-->
+3974-->
+3975-->
+3976-->
+3977-->
+3978-->
+3979-->
+398-->
+3980-->
+3981-->
+3982-->
+3983-->
+3984-->
+3985-->
+3986-->
+3987-->
+3988-->
+3989-->
+399-->
+3990-->
+3991-->
+3992-->
+3993-->
+3994-->
+3995-->
+3996-->
+3997-->
+3998-->
+3999-->
+4-->
+40-->
+400-->
+4000-->
+4001-->
+4002-->
+4003-->
+4004-->
+4005-->
+4006-->
+4007-->
+4008-->
+4009-->
+401-->
+4010-->
+4011-->
+4012-->
+4013-->
+4014-->
+4015-->
+4016-->
+4017-->
+4018-->
+4019-->
+402-->
+4020-->
+4021-->
+4022-->
+4023-->
+4024-->
+4025-->
+4026-->
+4027-->
+4028-->
+4029-->
+403-->
+4030-->
+4031-->
+4032-->
+4033-->
+4034-->
+4035-->
+4036-->
+4037-->
+4038-->
+4039-->
+404-->
+4040-->
+4041-->
+4042-->
+4043-->
+4044-->
+4045-->
+4046-->
+4047-->
+4048-->
+4049-->
+405-->
+4050-->
+4051-->
+4052-->
+4053-->
+4054-->
+4055-->
+4056-->
+4057-->
+4058-->
+4059-->
+406-->
+4060-->
+4061-->
+4062-->
+4063-->
+4064-->
+4065-->
+4066-->
+4067-->
+4068-->
+4069-->
+407-->
+4070-->
+4071-->
+4072-->
+4073-->
+4074-->
+4075-->
+4076-->
+4077-->
+4078-->
+4079-->
+408-->
+4080-->
+4081-->
+4082-->
+4083-->
+4084-->
+4085-->
+4086-->
+4087-->
+4088-->
+4089-->
+409-->
+4090-->
+4091-->
+4092-->
+4093-->
+4094-->
+4095-->
+4096-->
+4097-->
+4098-->
+4099-->
+41-->
+410-->
+4100-->
+4101-->
+4102-->
+4103-->
+4104-->
+4105-->
+4106-->
+4107-->
+4108-->
+4109-->
+411-->
+4110-->
+4111-->
+4112-->
+4113-->
+4114-->
+4115-->
+4116-->
+4117-->
+4118-->
+4119-->
+412-->
+4120-->
+4121-->
+4122-->
+4123-->
+4124-->
+4125-->
+4126-->
+4127-->
+4128-->
+4129-->
+413-->
+4130-->
+4131-->
+4132-->
+4133-->
+4134-->
+4135-->
+4136-->
+4137-->
+4138-->
+4139-->
+414-->
+4140-->
+4141-->
+4142-->
+4143-->
+4144-->
+4145-->
+4146-->
+4147-->
+4148-->
+4149-->
+415-->
+4150-->
+4151-->
+4152-->
+4153-->
+4154-->
+4155-->
+4156-->
+4157-->
+4158-->
+4159-->
+416-->
+4160-->
+4161-->
+4162-->
+4163-->
+4164-->
+4165-->
+4166-->
+4167-->
+4168-->
+4169-->
+417-->
+4170-->
+4171-->
+4172-->
+4173-->
+4174-->
+4175-->
+4176-->
+4177-->
+4178-->
+4179-->
+418-->
+4180-->
+4181-->
+4182-->
+4183-->
+4184-->
+4185-->
+4186-->
+4187-->
+4188-->
+4189-->
+419-->
+4190-->
+4191-->
+4192-->
+4193-->
+4194-->
+4195-->
+4196-->
+4197-->
+4198-->
+4199-->
+42-->
+420-->
+4200-->
+4201-->
+4202-->
+4203-->
+4204-->
+4205-->
+4206-->
+4207-->
+4208-->
+4209-->
+421-->
+4210-->
+4211-->
+4212-->
+4213-->
+4214-->
+4215-->
+4216-->
+4217-->
+4218-->
+4219-->
+422-->
+4220-->
+4221-->
+4222-->
+4223-->
+4224-->
+4225-->
+4226-->
+4227-->
+4228-->
+4229-->
+423-->
+4230-->
+4231-->
+4232-->
+4233-->
+4234-->
+4235-->
+4236-->
+4237-->
+4238-->
+4239-->
+424-->
+4240-->
+4241-->
+4242-->
+4243-->
+4244-->
+4245-->
+4246-->
+4247-->
+4248-->
+4249-->
+425-->
+4250-->
+4251-->
+4252-->
+4253-->
+4254-->
+4255-->
+4256-->
+4257-->
+4258-->
+4259-->
+426-->
+4260-->
+4261-->
+4262-->
+4263-->
+4264-->
+4265-->
+4266-->
+4267-->
+4268-->
+4269-->
+427-->
+4270-->
+4271-->
+4272-->
+4273-->
+4274-->
+4275-->
+4276-->
+4277-->
+4278-->
+4279-->
+428-->
+4280-->
+4281-->
+4282-->
+4283-->
+4284-->
+4285-->
+4286-->
+4287-->
+4288-->
+4289-->
+429-->
+4290-->
+4291-->
+4292-->
+4293-->
+4294-->
+4295-->
+4296-->
+4297-->
+4298-->
+4299-->
+43-->
+430-->
+4300-->
+4301-->
+4302-->
+4303-->
+4304-->
+4305-->
+4306-->
+4307-->
+4308-->
+4309-->
+431-->
+4310-->
+4311-->
+4312-->
+4313-->
+4314-->
+4315-->
+4316-->
+4317-->
+4318-->
+4319-->
+432-->
+4320-->
+4321-->
+4322-->
+4323-->
+4324-->
+4325-->
+4326-->
+4327-->
+4328-->
+4329-->
+433-->
+4330-->
+4331-->
+4332-->
+4333-->
+4334-->
+4335-->
+4336-->
+4337-->
+4338-->
+4339-->
+434-->
+4340-->
+4341-->
+4342-->
+4343-->
+4344-->
+4345-->
+4346-->
+4347-->
+4348-->
+4349-->
+435-->
+4350-->
+4351-->
+4352-->
+4353-->
+4354-->
+4355-->
+4356-->
+4357-->
+4358-->
+4359-->
+436-->
+4360-->
+4361-->
+4362-->
+4363-->
+4364-->
+4365-->
+4366-->
+4367-->
+4368-->
+4369-->
+437-->
+4370-->
+4371-->
+4372-->
+4373-->
+4374-->
+4375-->
+4376-->
+4377-->
+4378-->
+4379-->
+438-->
+4380-->
+4381-->
+4382-->
+4383-->
+4384-->
+4385-->
+4386-->
+4387-->
+4388-->
+4389-->
+439-->
+4390-->
+4391-->
+4392-->
+4393-->
+4394-->
+4395-->
+4396-->
+4397-->
+4398-->
+4399-->
+44-->
+440-->
+4400-->
+4401-->
+4402-->
+4403-->
+4404-->
+4405-->
+4406-->
+4407-->
+4408-->
+4409-->
+441-->
+4410-->
+4411-->
+4412-->
+4413-->
+4414-->
+4415-->
+4416-->
+4417-->
+4418-->
+4419-->
+442-->
+4420-->
+4421-->
+4422-->
+4423-->
+4424-->
+4425-->
+4426-->
+4427-->
+4428-->
+4429-->
+443-->
+4430-->
+4431-->
+4432-->
+4433-->
+4434-->
+4435-->
+4436-->
+4437-->
+4438-->
+4439-->
+444-->
+4440-->
+4441-->
+4442-->
+4443-->
+4444-->
+4445-->
+4446-->
+4447-->
+4448-->
+4449-->
+445-->
+4450-->
+4451-->
+4452-->
+4453-->
+4454-->
+4455-->
+4456-->
+4457-->
+4458-->
+4459-->
+446-->
+4460-->
+4461-->
+4462-->
+4463-->
+4464-->
+4465-->
+4466-->
+4467-->
+4468-->
+4469-->
+447-->
+4470-->
+4471-->
+4472-->
+4473-->
+4474-->
+4475-->
+4476-->
+4477-->
+4478-->
+4479-->
+448-->
+4480-->
+4481-->
+4482-->
+4483-->
+4484-->
+4485-->
+4486-->
+4487-->
+4488-->
+4489-->
+449-->
+4490-->
+4491-->
+4492-->
+4493-->
+4494-->
+4495-->
+4496-->
+4497-->
+4498-->
+4499-->
+45-->
+450-->
+4500-->
+4501-->
+4502-->
+4503-->
+4504-->
+4505-->
+4506-->
+4507-->
+4508-->
+4509-->
+451-->
+4510-->
+4511-->
+4512-->
+4513-->
+4514-->
+4515-->
+4516-->
+4517-->
+4518-->
+4519-->
+452-->
+4520-->
+4521-->
+4522-->
+4523-->
+4524-->
+4525-->
+4526-->
+4527-->
+4528-->
+4529-->
+453-->
+4530-->
+4531-->
+4532-->
+4533-->
+4534-->
+4535-->
+4536-->
+4537-->
+4538-->
+4539-->
+454-->
+4540-->
+4541-->
+4542-->
+4543-->
+4544-->
+4545-->
+4546-->
+4547-->
+4548-->
+4549-->
+455-->
+4550-->
+4551-->
+4552-->
+4553-->
+4554-->
+4555-->
+4556-->
+4557-->
+4558-->
+4559-->
+456-->
+4560-->
+4561-->
+4562-->
+4563-->
+4564-->
+4565-->
+4566-->
+4567-->
+4568-->
+4569-->
+457-->
+4570-->
+4571-->
+4572-->
+4573-->
+4574-->
+4575-->
+4576-->
+4577-->
+4578-->
+4579-->
+458-->
+4580-->
+4581-->
+4582-->
+4583-->
+4584-->
+4585-->
+4586-->
+4587-->
+4588-->
+4589-->
+459-->
+4590-->
+4591-->
+4592-->
+4593-->
+4594-->
+4595-->
+4596-->
+4597-->
+4598-->
+4599-->
+46-->
+460-->
+4600-->
+4601-->
+4602-->
+4603-->
+4604-->
+4605-->
+4606-->
+4607-->
+4608-->
+4609-->
+461-->
+4610-->
+4611-->
+4612-->
+4613-->
+4614-->
+4615-->
+4616-->
+4617-->
+4618-->
+4619-->
+462-->
+4620-->
+4621-->
+4622-->
+4623-->
+4624-->
+4625-->
+4626-->
+4627-->
+4628-->
+4629-->
+463-->
+4630-->
+4631-->
+4632-->
+4633-->
+4634-->
+4635-->
+4636-->
+4637-->
+4638-->
+4639-->
+464-->
+4640-->
+4641-->
+4642-->
+4643-->
+4644-->
+4645-->
+4646-->
+4647-->
+4648-->
+4649-->
+465-->
+4650-->
+4651-->
+4652-->
+4653-->
+4654-->
+4655-->
+4656-->
+4657-->
+4658-->
+4659-->
+466-->
+4660-->
+4661-->
+4662-->
+4663-->
+4664-->
+4665-->
+4666-->
+4667-->
+4668-->
+4669-->
+467-->
+4670-->
+4671-->
+4672-->
+4673-->
+4674-->
+4675-->
+4676-->
+4677-->
+4678-->
+4679-->
+468-->
+4680-->
+4681-->
+4682-->
+4683-->
+4684-->
+4685-->
+4686-->
+4687-->
+4688-->
+4689-->
+469-->
+4690-->
+4691-->
+4692-->
+4693-->
+4694-->
+4695-->
+4696-->
+4697-->
+4698-->
+4699-->
+47-->
+470-->
+4700-->
+4701-->
+4702-->
+4703-->
+4704-->
+4705-->
+4706-->
+4707-->
+4708-->
+4709-->
+471-->
+4710-->
+4711-->
+4712-->
+4713-->
+4714-->
+4715-->
+4716-->
+4717-->
+4718-->
+4719-->
+472-->
+4720-->
+4721-->
+4722-->
+4723-->
+4724-->
+4725-->
+4726-->
+4727-->
+4728-->
+4729-->
+473-->
+4730-->
+4731-->
+4732-->
+4733-->
+4734-->
+4735-->
+4736-->
+4737-->
+4738-->
+4739-->
+474-->
+4740-->
+4741-->
+4742-->
+4743-->
+4744-->
+4745-->
+4746-->
+4747-->
+4748-->
+4749-->
+475-->
+4750-->
+4751-->
+4752-->
+4753-->
+4754-->
+4755-->
+4756-->
+4757-->
+4758-->
+4759-->
+476-->
+4760-->
+4761-->
+4762-->
+4763-->
+4764-->
+4765-->
+4766-->
+4767-->
+4768-->
+4769-->
+477-->
+4770-->
+4771-->
+4772-->
+4773-->
+4774-->
+4775-->
+4776-->
+4777-->
+4778-->
+4779-->
+478-->
+4780-->
+4781-->
+4782-->
+4783-->
+4784-->
+4785-->
+4786-->
+4787-->
+4788-->
+4789-->
+479-->
+4790-->
+4791-->
+4792-->
+4793-->
+4794-->
+4795-->
+4796-->
+4797-->
+4798-->
+4799-->
+48-->
+480-->
+4800-->
+4801-->
+4802-->
+4803-->
+4804-->
+4805-->
+4806-->
+4807-->
+4808-->
+4809-->
+481-->
+4810-->
+4811-->
+4812-->
+4813-->
+4814-->
+4815-->
+4816-->
+4817-->
+4818-->
+4819-->
+482-->
+4820-->
+4821-->
+4822-->
+4823-->
+4824-->
+4825-->
+4826-->
+4827-->
+4828-->
+4829-->
+483-->
+4830-->
+4831-->
+4832-->
+4833-->
+4834-->
+4835-->
+4836-->
+4837-->
+4838-->
+4839-->
+484-->
+4840-->
+4841-->
+4842-->
+4843-->
+4844-->
+4845-->
+4846-->
+4847-->
+4848-->
+4849-->
+485-->
+4850-->
+4851-->
+4852-->
+4853-->
+4854-->
+4855-->
+4856-->
+4857-->
+4858-->
+4859-->
+486-->
+4860-->
+4861-->
+4862-->
+4863-->
+4864-->
+4865-->
+4866-->
+4867-->
+4868-->
+4869-->
+487-->
+4870-->
+4871-->
+4872-->
+4873-->
+4874-->
+4875-->
+4876-->
+4877-->
+4878-->
+4879-->
+488-->
+4880-->
+4881-->
+4882-->
+4883-->
+4884-->
+4885-->
+4886-->
+4887-->
+4888-->
+4889-->
+489-->
+4890-->
+4891-->
+4892-->
+4893-->
+4894-->
+4895-->
+4896-->
+4897-->
+4898-->
+4899-->
+49-->
+490-->
+4900-->
+4901-->
+4902-->
+4903-->
+4904-->
+4905-->
+4906-->
+4907-->
+4908-->
+4909-->
+491-->
+4910-->
+4911-->
+4912-->
+4913-->
+4914-->
+4915-->
+4916-->
+4917-->
+4918-->
+4919-->
+492-->
+4920-->
+4921-->
+4922-->
+4923-->
+4924-->
+4925-->
+4926-->
+4927-->
+4928-->
+4929-->
+493-->
+4930-->
+4931-->
+4932-->
+4933-->
+4934-->
+4935-->
+4936-->
+4937-->
+4938-->
+4939-->
+494-->
+4940-->
+4941-->
+4942-->
+4943-->
+4944-->
+4945-->
+4946-->
+4947-->
+4948-->
+4949-->
+495-->
+4950-->
+4951-->
+4952-->
+4953-->
+4954-->
+4955-->
+4956-->
+4957-->
+4958-->
+4959-->
+496-->
+4960-->
+4961-->
+4962-->
+4963-->
+4964-->
+4965-->
+4966-->
+4967-->
+4968-->
+4969-->
+497-->
+4970-->
+4971-->
+4972-->
+4973-->
+4974-->
+4975-->
+4976-->
+4977-->
+4978-->
+4979-->
+498-->
+4980-->
+4981-->
+4982-->
+4983-->
+4984-->
+4985-->
+4986-->
+4987-->
+4988-->
+4989-->
+499-->
+4990-->
+4991-->
+4992-->
+4993-->
+4994-->
+4995-->
+4996-->
+4997-->
+4998-->
+4999-->
+5-->
+50-->
+500-->
+5000-->
+5001-->
+5002-->
+5003-->
+5004-->
+5005-->
+5006-->
+5007-->
+5008-->
+5009-->
+501-->
+5010-->
+5011-->
+5012-->
+5013-->
+5014-->
+5015-->
+5016-->
+5017-->
+5018-->
+5019-->
+502-->
+5020-->
+5021-->
+5022-->
+5023-->
+5024-->
+5025-->
+5026-->
+5027-->
+5028-->
+5029-->
+503-->
+5030-->
+5031-->
+5032-->
+5033-->
+5034-->
+5035-->
+5036-->
+5037-->
+5038-->
+5039-->
+504-->
+5040-->
+5041-->
+5042-->
+5043-->
+5044-->
+5045-->
+5046-->
+5047-->
+5048-->
+5049-->
+505-->
+5050-->
+5051-->
+5052-->
+5053-->
+5054-->
+5055-->
+5056-->
+5057-->
+5058-->
+5059-->
+506-->
+5060-->
+5061-->
+5062-->
+5063-->
+5064-->
+5065-->
+5066-->
+5067-->
+5068-->
+5069-->
+507-->
+5070-->
+5071-->
+5072-->
+5073-->
+5074-->
+5075-->
+5076-->
+5077-->
+5078-->
+5079-->
+508-->
+5080-->
+5081-->
+5082-->
+5083-->
+5084-->
+5085-->
+5086-->
+5087-->
+5088-->
+5089-->
+509-->
+5090-->
+5091-->
+5092-->
+5093-->
+5094-->
+5095-->
+5096-->
+5097-->
+5098-->
+5099-->
+51-->
+510-->
+5100-->
+5101-->
+5102-->
+5103-->
+5104-->
+5105-->
+5106-->
+5107-->
+5108-->
+5109-->
+511-->
+5110-->
+5111-->
+5112-->
+5113-->
+5114-->
+5115-->
+5116-->
+5117-->
+5118-->
+5119-->
+512-->
+5120-->
+5121-->
+5122-->
+5123-->
+5124-->
+5125-->
+5126-->
+5127-->
+5128-->
+5129-->
+513-->
+5130-->
+5131-->
+5132-->
+5133-->
+5134-->
+5135-->
+5136-->
+5137-->
+5138-->
+5139-->
+514-->
+5140-->
+5141-->
+5142-->
+5143-->
+5144-->
+5145-->
+5146-->
+5147-->
+5148-->
+5149-->
+515-->
+5150-->
+5151-->
+5152-->
+5153-->
+5154-->
+5155-->
+5156-->
+5157-->
+5158-->
+5159-->
+516-->
+5160-->
+5161-->
+5162-->
+5163-->
+5164-->
+5165-->
+5166-->
+5167-->
+5168-->
+5169-->
+517-->
+5170-->
+5171-->
+5172-->
+5173-->
+5174-->
+5175-->
+5176-->
+5177-->
+5178-->
+5179-->
+518-->
+5180-->
+5181-->
+5182-->
+5183-->
+5184-->
+5185-->
+5186-->
+5187-->
+5188-->
+5189-->
+519-->
+5190-->
+5191-->
+5192-->
+5193-->
+5194-->
+5195-->
+5196-->
+5197-->
+5198-->
+5199-->
+52-->
+520-->
+5200-->
+5201-->
+5202-->
+5203-->
+5204-->
+5205-->
+5206-->
+5207-->
+5208-->
+5209-->
+521-->
+5210-->
+5211-->
+5212-->
+5213-->
+5214-->
+5215-->
+5216-->
+5217-->
+5218-->
+5219-->
+522-->
+5220-->
+5221-->
+5222-->
+5223-->
+5224-->
+5225-->
+5226-->
+5227-->
+5228-->
+5229-->
+523-->
+5230-->
+5231-->
+5232-->
+5233-->
+5234-->
+5235-->
+5236-->
+5237-->
+5238-->
+5239-->
+524-->
+5240-->
+5241-->
+5242-->
+5243-->
+5244-->
+5245-->
+5246-->
+5247-->
+5248-->
+5249-->
+525-->
+5250-->
+5251-->
+5252-->
+5253-->
+5254-->
+5255-->
+5256-->
+5257-->
+5258-->
+5259-->
+526-->
+5260-->
+5261-->
+5262-->
+5263-->
+5264-->
+5265-->
+5266-->
+5267-->
+5268-->
+5269-->
+527-->
+5270-->
+5271-->
+5272-->
+5273-->
+5274-->
+5275-->
+5276-->
+5277-->
+5278-->
+5279-->
+528-->
+5280-->
+5281-->
+5282-->
+5283-->
+5284-->
+5285-->
+5286-->
+5287-->
+5288-->
+5289-->
+529-->
+5290-->
+5291-->
+5292-->
+5293-->
+5294-->
+5295-->
+5296-->
+5297-->
+5298-->
+5299-->
+53-->
+530-->
+5300-->
+5301-->
+5302-->
+5303-->
+5304-->
+5305-->
+5306-->
+5307-->
+5308-->
+5309-->
+531-->
+5310-->
+5311-->
+5312-->
+5313-->
+5314-->
+5315-->
+5316-->
+5317-->
+5318-->
+5319-->
+532-->
+5320-->
+5321-->
+5322-->
+5323-->
+5324-->
+5325-->
+5326-->
+5327-->
+5328-->
+5329-->
+533-->
+5330-->
+5331-->
+5332-->
+5333-->
+5334-->
+5335-->
+5336-->
+5337-->
+5338-->
+5339-->
+534-->
+5340-->
+5341-->
+5342-->
+5343-->
+5344-->
+5345-->
+5346-->
+5347-->
+5348-->
+5349-->
+535-->
+5350-->
+5351-->
+5352-->
+5353-->
+5354-->
+5355-->
+5356-->
+5357-->
+5358-->
+5359-->
+536-->
+5360-->
+5361-->
+5362-->
+5363-->
+5364-->
+5365-->
+5366-->
+5367-->
+5368-->
+5369-->
+537-->
+5370-->
+5371-->
+5372-->
+5373-->
+5374-->
+5375-->
+5376-->
+5377-->
+5378-->
+5379-->
+538-->
+5380-->
+5381-->
+5382-->
+5383-->
+5384-->
+5385-->
+5386-->
+5387-->
+5388-->
+5389-->
+539-->
+5390-->
+5391-->
+5392-->
+5393-->
+5394-->
+5395-->
+5396-->
+5397-->
+5398-->
+5399-->
+54-->
+540-->
+5400-->
+5401-->
+5402-->
+5403-->
+5404-->
+5405-->
+5406-->
+5407-->
+5408-->
+5409-->
+541-->
+5410-->
+5411-->
+5412-->
+5413-->
+5414-->
+5415-->
+5416-->
+5417-->
+5418-->
+5419-->
+542-->
+5420-->
+5421-->
+5422-->
+5423-->
+5424-->
+5425-->
+5426-->
+5427-->
+5428-->
+5429-->
+543-->
+5430-->
+5431-->
+5432-->
+5433-->
+5434-->
+5435-->
+5436-->
+5437-->
+5438-->
+5439-->
+544-->
+5440-->
+5441-->
+5442-->
+5443-->
+5444-->
+5445-->
+5446-->
+5447-->
+5448-->
+5449-->
+545-->
+5450-->
+5451-->
+5452-->
+5453-->
+5454-->
+5455-->
+5456-->
+5457-->
+5458-->
+5459-->
+546-->
+5460-->
+5461-->
+5462-->
+5463-->
+5464-->
+5465-->
+5466-->
+5467-->
+5468-->
+5469-->
+547-->
+5470-->
+5471-->
+5472-->
+5473-->
+5474-->
+5475-->
+5476-->
+5477-->
+5478-->
+5479-->
+548-->
+5480-->
+5481-->
+5482-->
+5483-->
+5484-->
+5485-->
+5486-->
+5487-->
+5488-->
+5489-->
+549-->
+5490-->
+5491-->
+5492-->
+5493-->
+5494-->
+5495-->
+5496-->
+5497-->
+5498-->
+5499-->
+55-->
+550-->
+5500-->
+5501-->
+5502-->
+5503-->
+5504-->
+5505-->
+5506-->
+5507-->
+5508-->
+5509-->
+551-->
+5510-->
+5511-->
+5512-->
+5513-->
+5514-->
+5515-->
+5516-->
+5517-->
+5518-->
+5519-->
+552-->
+5520-->
+5521-->
+5522-->
+5523-->
+5524-->
+5525-->
+5526-->
+5527-->
+5528-->
+5529-->
+553-->
+5530-->
+5531-->
+5532-->
+5533-->
+5534-->
+5535-->
+5536-->
+5537-->
+5538-->
+5539-->
+554-->
+5540-->
+5541-->
+5542-->
+5543-->
+5544-->
+5545-->
+5546-->
+5547-->
+5548-->
+5549-->
+555-->
+5550-->
+5551-->
+5552-->
+5553-->
+5554-->
+5555-->
+5556-->
+5557-->
+5558-->
+5559-->
+556-->
+5560-->
+5561-->
+5562-->
+5563-->
+5564-->
+5565-->
+5566-->
+5567-->
+5568-->
+5569-->
+557-->
+5570-->
+5571-->
+5572-->
+5573-->
+5574-->
+5575-->
+5576-->
+5577-->
+5578-->
+5579-->
+558-->
+5580-->
+5581-->
+5582-->
+5583-->
+5584-->
+5585-->
+5586-->
+5587-->
+5588-->
+5589-->
+559-->
+5590-->
+5591-->
+5592-->
+5593-->
+5594-->
+5595-->
+5596-->
+5597-->
+5598-->
+5599-->
+56-->
+560-->
+5600-->
+5601-->
+5602-->
+5603-->
+5604-->
+5605-->
+5606-->
+5607-->
+5608-->
+5609-->
+561-->
+5610-->
+5611-->
+5612-->
+5613-->
+5614-->
+5615-->
+5616-->
+5617-->
+5618-->
+5619-->
+562-->
+5620-->
+5621-->
+5622-->
+5623-->
+5624-->
+5625-->
+5626-->
+5627-->
+5628-->
+5629-->
+563-->
+5630-->
+5631-->
+5632-->
+5633-->
+5634-->
+5635-->
+5636-->
+5637-->
+5638-->
+5639-->
+564-->
+5640-->
+5641-->
+5642-->
+5643-->
+5644-->
+5645-->
+5646-->
+5647-->
+5648-->
+5649-->
+565-->
+5650-->
+5651-->
+5652-->
+5653-->
+5654-->
+5655-->
+5656-->
+5657-->
+5658-->
+5659-->
+566-->
+5660-->
+5661-->
+5662-->
+5663-->
+5664-->
+5665-->
+5666-->
+5667-->
+5668-->
+5669-->
+567-->
+5670-->
+5671-->
+5672-->
+5673-->
+5674-->
+5675-->
+5676-->
+5677-->
+5678-->
+5679-->
+568-->
+5680-->
+5681-->
+5682-->
+5683-->
+5684-->
+5685-->
+5686-->
+5687-->
+5688-->
+5689-->
+569-->
+5690-->
+5691-->
+5692-->
+5693-->
+5694-->
+5695-->
+5696-->
+5697-->
+5698-->
+5699-->
+57-->
+570-->
+5700-->
+5701-->
+5702-->
+5703-->
+5704-->
+5705-->
+5706-->
+5707-->
+5708-->
+5709-->
+571-->
+5710-->
+5711-->
+5712-->
+5713-->
+5714-->
+5715-->
+5716-->
+5717-->
+5718-->
+5719-->
+572-->
+5720-->
+5721-->
+5722-->
+5723-->
+5724-->
+5725-->
+5726-->
+5727-->
+5728-->
+5729-->
+573-->
+5730-->
+5731-->
+5732-->
+5733-->
+5734-->
+5735-->
+5736-->
+5737-->
+5738-->
+5739-->
+574-->
+5740-->
+5741-->
+5742-->
+5743-->
+5744-->
+5745-->
+5746-->
+5747-->
+5748-->
+5749-->
+575-->
+5750-->
+5751-->
+5752-->
+5753-->
+5754-->
+5755-->
+5756-->
+5757-->
+5758-->
+5759-->
+576-->
+5760-->
+5761-->
+5762-->
+5763-->
+5764-->
+5765-->
+5766-->
+5767-->
+5768-->
+5769-->
+577-->
+5770-->
+5771-->
+5772-->
+5773-->
+5774-->
+5775-->
+5776-->
+5777-->
+5778-->
+5779-->
+578-->
+5780-->
+5781-->
+5782-->
+5783-->
+5784-->
+5785-->
+5786-->
+5787-->
+5788-->
+5789-->
+579-->
+5790-->
+5791-->
+5792-->
+5793-->
+5794-->
+5795-->
+5796-->
+5797-->
+5798-->
+5799-->
+58-->
+580-->
+5800-->
+5801-->
+5802-->
+5803-->
+5804-->
+5805-->
+5806-->
+5807-->
+5808-->
+5809-->
+581-->
+5810-->
+5811-->
+5812-->
+5813-->
+5814-->
+5815-->
+5816-->
+5817-->
+5818-->
+5819-->
+582-->
+5820-->
+5821-->
+5822-->
+5823-->
+5824-->
+5825-->
+5826-->
+5827-->
+5828-->
+5829-->
+583-->
+5830-->
+5831-->
+5832-->
+5833-->
+5834-->
+5835-->
+5836-->
+5837-->
+5838-->
+5839-->
+584-->
+5840-->
+5841-->
+5842-->
+5843-->
+5844-->
+5845-->
+5846-->
+5847-->
+5848-->
+5849-->
+585-->
+5850-->
+5851-->
+5852-->
+5853-->
+5854-->
+5855-->
+5856-->
+5857-->
+5858-->
+5859-->
+586-->
+5860-->
+5861-->
+5862-->
+5863-->
+5864-->
+5865-->
+5866-->
+5867-->
+5868-->
+5869-->
+587-->
+5870-->
+5871-->
+5872-->
+5873-->
+5874-->
+5875-->
+5876-->
+5877-->
+5878-->
+5879-->
+588-->
+5880-->
+5881-->
+5882-->
+5883-->
+5884-->
+5885-->
+5886-->
+5887-->
+5888-->
+5889-->
+589-->
+5890-->
+5891-->
+5892-->
+5893-->
+5894-->
+5895-->
+5896-->
+5897-->
+5898-->
+5899-->
+59-->
+590-->
+5900-->
+5901-->
+5902-->
+5903-->
+5904-->
+5905-->
+5906-->
+5907-->
+5908-->
+5909-->
+591-->
+5910-->
+5911-->
+5912-->
+5913-->
+5914-->
+5915-->
+5916-->
+5917-->
+5918-->
+5919-->
+592-->
+5920-->
+5921-->
+5922-->
+5923-->
+5924-->
+5925-->
+5926-->
+5927-->
+5928-->
+5929-->
+593-->
+5930-->
+5931-->
+5932-->
+5933-->
+5934-->
+5935-->
+5936-->
+5937-->
+5938-->
+5939-->
+594-->
+5940-->
+5941-->
+5942-->
+5943-->
+5944-->
+5945-->
+5946-->
+5947-->
+5948-->
+5949-->
+595-->
+5950-->
+5951-->
+5952-->
+5953-->
+5954-->
+5955-->
+5956-->
+5957-->
+5958-->
+5959-->
+596-->
+5960-->
+5961-->
+5962-->
+5963-->
+5964-->
+5965-->
+5966-->
+5967-->
+5968-->
+5969-->
+597-->
+5970-->
+5971-->
+5972-->
+5973-->
+5974-->
+5975-->
+5976-->
+5977-->
+5978-->
+5979-->
+598-->
+5980-->
+5981-->
+5982-->
+5983-->
+5984-->
+5985-->
+5986-->
+5987-->
+5988-->
+5989-->
+599-->
+5990-->
+5991-->
+5992-->
+5993-->
+5994-->
+5995-->
+5996-->
+5997-->
+5998-->
+5999-->
+6-->
+60-->
+600-->
+6000-->
+6001-->
+6002-->
+6003-->
+6004-->
+6005-->
+6006-->
+6007-->
+6008-->
+6009-->
+601-->
+6010-->
+6011-->
+6012-->
+6013-->
+6014-->
+6015-->
+6016-->
+6017-->
+6018-->
+6019-->
+602-->
+6020-->
+6021-->
+6022-->
+6023-->
+6024-->
+6025-->
+6026-->
+6027-->
+6028-->
+6029-->
+603-->
+6030-->
+6031-->
+6032-->
+6033-->
+6034-->
+6035-->
+6036-->
+6037-->
+6038-->
+6039-->
+604-->
+6040-->
+6041-->
+6042-->
+6043-->
+6044-->
+6045-->
+6046-->
+6047-->
+6048-->
+6049-->
+605-->
+6050-->
+6051-->
+6052-->
+6053-->
+6054-->
+6055-->
+6056-->
+6057-->
+6058-->
+6059-->
+606-->
+6060-->
+6061-->
+6062-->
+6063-->
+6064-->
+6065-->
+6066-->
+6067-->
+6068-->
+6069-->
+607-->
+6070-->
+6071-->
+6072-->
+6073-->
+6074-->
+6075-->
+6076-->
+6077-->
+6078-->
+6079-->
+608-->
+6080-->
+6081-->
+6082-->
+6083-->
+6084-->
+6085-->
+6086-->
+6087-->
+6088-->
+6089-->
+609-->
+6090-->
+6091-->
+6092-->
+6093-->
+6094-->
+6095-->
+6096-->
+6097-->
+6098-->
+6099-->
+61-->
+610-->
+6100-->
+6101-->
+6102-->
+6103-->
+6104-->
+6105-->
+6106-->
+6107-->
+6108-->
+6109-->
+611-->
+6110-->
+6111-->
+6112-->
+6113-->
+6114-->
+6115-->
+6116-->
+6117-->
+6118-->
+6119-->
+612-->
+6120-->
+6121-->
+6122-->
+6123-->
+6124-->
+6125-->
+6126-->
+6127-->
+6128-->
+6129-->
+613-->
+6130-->
+6131-->
+6132-->
+6133-->
+6134-->
+6135-->
+6136-->
+6137-->
+6138-->
+6139-->
+614-->
+6140-->
+6141-->
+6142-->
+6143-->
+6144-->
+6145-->
+6146-->
+6147-->
+6148-->
+6149-->
+615-->
+6150-->
+6151-->
+6152-->
+6153-->
+6154-->
+6155-->
+6156-->
+6157-->
+6158-->
+6159-->
+616-->
+6160-->
+6161-->
+6162-->
+6163-->
+6164-->
+6165-->
+6166-->
+6167-->
+6168-->
+6169-->
+617-->
+6170-->
+6171-->
+6172-->
+6173-->
+6174-->
+6175-->
+6176-->
+6177-->
+6178-->
+6179-->
+618-->
+6180-->
+6181-->
+6182-->
+6183-->
+6184-->
+6185-->
+6186-->
+6187-->
+6188-->
+6189-->
+619-->
+6190-->
+6191-->
+6192-->
+6193-->
+6194-->
+6195-->
+6196-->
+6197-->
+6198-->
+6199-->
+62-->
+620-->
+6200-->
+6201-->
+6202-->
+6203-->
+6204-->
+6205-->
+6206-->
+6207-->
+6208-->
+6209-->
+621-->
+6210-->
+6211-->
+6212-->
+6213-->
+6214-->
+6215-->
+6216-->
+6217-->
+6218-->
+6219-->
+622-->
+6220-->
+6221-->
+6222-->
+6223-->
+6224-->
+6225-->
+6226-->
+6227-->
+6228-->
+6229-->
+623-->
+6230-->
+6231-->
+6232-->
+6233-->
+6234-->
+6235-->
+6236-->
+6237-->
+6238-->
+6239-->
+624-->
+6240-->
+6241-->
+6242-->
+6243-->
+6244-->
+6245-->
+6246-->
+6247-->
+6248-->
+6249-->
+625-->
+6250-->
+6251-->
+6252-->
+6253-->
+6254-->
+6255-->
+6256-->
+6257-->
+6258-->
+6259-->
+626-->
+6260-->
+6261-->
+6262-->
+6263-->
+6264-->
+6265-->
+6266-->
+6267-->
+6268-->
+6269-->
+627-->
+6270-->
+6271-->
+6272-->
+6273-->
+6274-->
+6275-->
+6276-->
+6277-->
+6278-->
+6279-->
+628-->
+6280-->
+6281-->
+6282-->
+6283-->
+6284-->
+6285-->
+6286-->
+6287-->
+6288-->
+6289-->
+629-->
+6290-->
+6291-->
+6292-->
+6293-->
+6294-->
+6295-->
+6296-->
+6297-->
+6298-->
+6299-->
+63-->
+630-->
+6300-->
+6301-->
+6302-->
+6303-->
+6304-->
+6305-->
+6306-->
+6307-->
+6308-->
+6309-->
+631-->
+6310-->
+6311-->
+6312-->
+6313-->
+6314-->
+6315-->
+6316-->
+6317-->
+6318-->
+6319-->
+632-->
+6320-->
+6321-->
+6322-->
+6323-->
+6324-->
+6325-->
+6326-->
+6327-->
+6328-->
+6329-->
+633-->
+6330-->
+6331-->
+6332-->
+6333-->
+6334-->
+6335-->
+6336-->
+6337-->
+6338-->
+6339-->
+634-->
+6340-->
+6341-->
+6342-->
+6343-->
+6344-->
+6345-->
+6346-->
+6347-->
+6348-->
+6349-->
+635-->
+6350-->
+6351-->
+6352-->
+6353-->
+6354-->
+6355-->
+6356-->
+6357-->
+6358-->
+6359-->
+636-->
+6360-->
+6361-->
+6362-->
+6363-->
+6364-->
+6365-->
+6366-->
+6367-->
+6368-->
+6369-->
+637-->
+6370-->
+6371-->
+6372-->
+6373-->
+6374-->
+6375-->
+6376-->
+6377-->
+6378-->
+6379-->
+638-->
+6380-->
+6381-->
+6382-->
+6383-->
+6384-->
+6385-->
+6386-->
+6387-->
+6388-->
+6389-->
+639-->
+6390-->
+6391-->
+6392-->
+6393-->
+6394-->
+6395-->
+6396-->
+6397-->
+6398-->
+6399-->
+64-->
+640-->
+6400-->
+6401-->
+6402-->
+6403-->
+6404-->
+6405-->
+6406-->
+6407-->
+6408-->
+6409-->
+641-->
+6410-->
+6411-->
+6412-->
+6413-->
+6414-->
+6415-->
+6416-->
+6417-->
+6418-->
+6419-->
+642-->
+6420-->
+6421-->
+6422-->
+6423-->
+6424-->
+6425-->
+6426-->
+6427-->
+6428-->
+6429-->
+643-->
+6430-->
+6431-->
+6432-->
+6433-->
+6434-->
+6435-->
+6436-->
+6437-->
+6438-->
+6439-->
+644-->
+6440-->
+6441-->
+6442-->
+6443-->
+6444-->
+6445-->
+6446-->
+6447-->
+6448-->
+6449-->
+645-->
+6450-->
+6451-->
+6452-->
+6453-->
+6454-->
+6455-->
+6456-->
+6457-->
+6458-->
+6459-->
+646-->
+6460-->
+6461-->
+6462-->
+6463-->
+6464-->
+6465-->
+6466-->
+6467-->
+6468-->
+6469-->
+647-->
+6470-->
+6471-->
+6472-->
+6473-->
+6474-->
+6475-->
+6476-->
+6477-->
+6478-->
+6479-->
+648-->
+6480-->
+6481-->
+6482-->
+6483-->
+6484-->
+6485-->
+6486-->
+6487-->
+6488-->
+6489-->
+649-->
+6490-->
+6491-->
+6492-->
+6493-->
+6494-->
+6495-->
+6496-->
+6497-->
+6498-->
+6499-->
+65-->
+650-->
+6500-->
+6501-->
+6502-->
+6503-->
+6504-->
+6505-->
+6506-->
+6507-->
+6508-->
+6509-->
+651-->
+6510-->
+6511-->
+6512-->
+6513-->
+6514-->
+6515-->
+6516-->
+6517-->
+6518-->
+6519-->
+652-->
+6520-->
+6521-->
+6522-->
+6523-->
+6524-->
+6525-->
+6526-->
+6527-->
+6528-->
+6529-->
+653-->
+6530-->
+6531-->
+6532-->
+6533-->
+6534-->
+6535-->
+6536-->
+6537-->
+6538-->
+6539-->
+654-->
+6540-->
+6541-->
+6542-->
+6543-->
+6544-->
+6545-->
+6546-->
+6547-->
+6548-->
+6549-->
+655-->
+6550-->
+6551-->
+6552-->
+6553-->
+6554-->
+6555-->
+6556-->
+6557-->
+6558-->
+6559-->
+656-->
+6560-->
+6561-->
+6562-->
+6563-->
+6564-->
+6565-->
+6566-->
+6567-->
+6568-->
+6569-->
+657-->
+6570-->
+6571-->
+6572-->
+6573-->
+6574-->
+6575-->
+6576-->
+6577-->
+6578-->
+6579-->
+658-->
+6580-->
+6581-->
+6582-->
+6583-->
+6584-->
+6585-->
+6586-->
+6587-->
+6588-->
+6589-->
+659-->
+6590-->
+6591-->
+6592-->
+6593-->
+6594-->
+6595-->
+6596-->
+6597-->
+6598-->
+6599-->
+66-->
+660-->
+6600-->
+6601-->
+6602-->
+6603-->
+6604-->
+6605-->
+6606-->
+6607-->
+6608-->
+6609-->
+661-->
+6610-->
+6611-->
+6612-->
+6613-->
+6614-->
+6615-->
+6616-->
+6617-->
+6618-->
+6619-->
+662-->
+6620-->
+6621-->
+6622-->
+6623-->
+6624-->
+6625-->
+6626-->
+6627-->
+6628-->
+6629-->
+663-->
+6630-->
+6631-->
+6632-->
+6633-->
+6634-->
+6635-->
+6636-->
+6637-->
+6638-->
+6639-->
+664-->
+6640-->
+6641-->
+6642-->
+6643-->
+6644-->
+6645-->
+6646-->
+6647-->
+6648-->
+6649-->
+665-->
+6650-->
+6651-->
+6652-->
+6653-->
+6654-->
+6655-->
+6656-->
+6657-->
+6658-->
+6659-->
+666-->
+6660-->
+6661-->
+6662-->
+6663-->
+6664-->
+6665-->
+6666-->
+6667-->
+6668-->
+6669-->
+667-->
+6670-->
+6671-->
+6672-->
+6673-->
+6674-->
+6675-->
+6676-->
+6677-->
+6678-->
+6679-->
+668-->
+6680-->
+6681-->
+6682-->
+6683-->
+6684-->
+6685-->
+6686-->
+6687-->
+6688-->
+6689-->
+669-->
+6690-->
+6691-->
+6692-->
+6693-->
+6694-->
+6695-->
+6696-->
+6697-->
+6698-->
+6699-->
+67-->
+670-->
+6700-->
+6701-->
+6702-->
+6703-->
+6704-->
+6705-->
+6706-->
+6707-->
+6708-->
+6709-->
+671-->
+6710-->
+6711-->
+6712-->
+6713-->
+6714-->
+6715-->
+6716-->
+6717-->
+6718-->
+6719-->
+672-->
+6720-->
+6721-->
+6722-->
+6723-->
+6724-->
+6725-->
+6726-->
+6727-->
+6728-->
+6729-->
+673-->
+6730-->
+6731-->
+6732-->
+6733-->
+6734-->
+6735-->
+6736-->
+6737-->
+6738-->
+6739-->
+674-->
+6740-->
+6741-->
+6742-->
+6743-->
+6744-->
+6745-->
+6746-->
+6747-->
+6748-->
+6749-->
+675-->
+6750-->
+6751-->
+6752-->
+6753-->
+6754-->
+6755-->
+6756-->
+6757-->
+6758-->
+6759-->
+676-->
+6760-->
+6761-->
+6762-->
+6763-->
+6764-->
+6765-->
+6766-->
+6767-->
+6768-->
+6769-->
+677-->
+6770-->
+6771-->
+6772-->
+6773-->
+6774-->
+6775-->
+6776-->
+6777-->
+6778-->
+6779-->
+678-->
+6780-->
+6781-->
+6782-->
+6783-->
+6784-->
+6785-->
+6786-->
+6787-->
+6788-->
+6789-->
+679-->
+6790-->
+6791-->
+6792-->
+6793-->
+6794-->
+6795-->
+6796-->
+6797-->
+6798-->
+6799-->
+68-->
+680-->
+6800-->
+6801-->
+6802-->
+6803-->
+6804-->
+6805-->
+6806-->
+6807-->
+6808-->
+6809-->
+681-->
+6810-->
+6811-->
+6812-->
+6813-->
+6814-->
+6815-->
+6816-->
+6817-->
+6818-->
+6819-->
+682-->
+6820-->
+6821-->
+6822-->
+6823-->
+6824-->
+6825-->
+6826-->
+6827-->
+6828-->
+6829-->
+683-->
+6830-->
+6831-->
+6832-->
+6833-->
+6834-->
+6835-->
+6836-->
+6837-->
+6838-->
+6839-->
+684-->
+6840-->
+6841-->
+6842-->
+6843-->
+6844-->
+6845-->
+6846-->
+6847-->
+6848-->
+6849-->
+685-->
+6850-->
+6851-->
+6852-->
+6853-->
+6854-->
+6855-->
+6856-->
+6857-->
+6858-->
+6859-->
+686-->
+6860-->
+6861-->
+6862-->
+6863-->
+6864-->
+6865-->
+6866-->
+6867-->
+6868-->
+6869-->
+687-->
+6870-->
+6871-->
+6872-->
+6873-->
+6874-->
+6875-->
+6876-->
+6877-->
+6878-->
+6879-->
+688-->
+6880-->
+6881-->
+6882-->
+6883-->
+6884-->
+6885-->
+6886-->
+6887-->
+6888-->
+6889-->
+689-->
+6890-->
+6891-->
+6892-->
+6893-->
+6894-->
+6895-->
+6896-->
+6897-->
+6898-->
+6899-->
+69-->
+690-->
+6900-->
+6901-->
+6902-->
+6903-->
+6904-->
+6905-->
+6906-->
+6907-->
+6908-->
+6909-->
+691-->
+6910-->
+6911-->
+6912-->
+6913-->
+6914-->
+6915-->
+6916-->
+6917-->
+6918-->
+6919-->
+692-->
+6920-->
+6921-->
+6922-->
+6923-->
+6924-->
+6925-->
+6926-->
+6927-->
+6928-->
+6929-->
+693-->
+6930-->
+6931-->
+6932-->
+6933-->
+6934-->
+6935-->
+6936-->
+6937-->
+6938-->
+6939-->
+694-->
+6940-->
+6941-->
+6942-->
+6943-->
+6944-->
+6945-->
+6946-->
+6947-->
+6948-->
+6949-->
+695-->
+6950-->
+6951-->
+6952-->
+6953-->
+6954-->
+6955-->
+6956-->
+6957-->
+6958-->
+6959-->
+696-->
+6960-->
+6961-->
+6962-->
+6963-->
+6964-->
+6965-->
+6966-->
+6967-->
+6968-->
+6969-->
+697-->
+6970-->
+6971-->
+6972-->
+6973-->
+6974-->
+6975-->
+6976-->
+6977-->
+6978-->
+6979-->
+698-->
+6980-->
+6981-->
+6982-->
+6983-->
+6984-->
+6985-->
+6986-->
+6987-->
+6988-->
+6989-->
+699-->
+6990-->
+6991-->
+6992-->
+6993-->
+6994-->
+6995-->
+6996-->
+6997-->
+6998-->
+6999-->
+7-->
+70-->
+700-->
+7000-->
+7001-->
+7002-->
+7003-->
+7004-->
+7005-->
+7006-->
+7007-->
+7008-->
+7009-->
+701-->
+7010-->
+7011-->
+7012-->
+7013-->
+7014-->
+7015-->
+7016-->
+7017-->
+7018-->
+7019-->
+702-->
+7020-->
+7021-->
+7022-->
+7023-->
+7024-->
+7025-->
+7026-->
+7027-->
+7028-->
+7029-->
+703-->
+7030-->
+7031-->
+7032-->
+7033-->
+7034-->
+7035-->
+7036-->
+7037-->
+7038-->
+7039-->
+704-->
+7040-->
+7041-->
+7042-->
+7043-->
+7044-->
+7045-->
+7046-->
+7047-->
+7048-->
+7049-->
+705-->
+7050-->
+7051-->
+7052-->
+7053-->
+7054-->
+7055-->
+7056-->
+7057-->
+7058-->
+7059-->
+706-->
+7060-->
+7061-->
+7062-->
+7063-->
+7064-->
+7065-->
+7066-->
+7067-->
+7068-->
+7069-->
+707-->
+7070-->
+7071-->
+7072-->
+7073-->
+7074-->
+7075-->
+7076-->
+7077-->
+7078-->
+7079-->
+708-->
+7080-->
+7081-->
+7082-->
+7083-->
+7084-->
+7085-->
+7086-->
+7087-->
+7088-->
+7089-->
+709-->
+7090-->
+7091-->
+7092-->
+7093-->
+7094-->
+7095-->
+7096-->
+7097-->
+7098-->
+7099-->
+71-->
+710-->
+7100-->
+7101-->
+7102-->
+7103-->
+7104-->
+7105-->
+7106-->
+7107-->
+7108-->
+7109-->
+711-->
+7110-->
+7111-->
+7112-->
+7113-->
+7114-->
+7115-->
+7116-->
+7117-->
+7118-->
+7119-->
+712-->
+7120-->
+7121-->
+7122-->
+7123-->
+7124-->
+7125-->
+7126-->
+7127-->
+7128-->
+7129-->
+713-->
+7130-->
+7131-->
+7132-->
+7133-->
+7134-->
+7135-->
+7136-->
+7137-->
+7138-->
+7139-->
+714-->
+7140-->
+7141-->
+7142-->
+7143-->
+7144-->
+7145-->
+7146-->
+7147-->
+7148-->
+7149-->
+715-->
+7150-->
+7151-->
+7152-->
+7153-->
+7154-->
+7155-->
+7156-->
+7157-->
+7158-->
+7159-->
+716-->
+7160-->
+7161-->
+7162-->
+7163-->
+7164-->
+7165-->
+7166-->
+7167-->
+7168-->
+7169-->
+717-->
+7170-->
+7171-->
+7172-->
+7173-->
+7174-->
+7175-->
+7176-->
+7177-->
+7178-->
+7179-->
+718-->
+7180-->
+7181-->
+7182-->
+7183-->
+7184-->
+7185-->
+7186-->
+7187-->
+7188-->
+7189-->
+719-->
+7190-->
+7191-->
+7192-->
+7193-->
+7194-->
+7195-->
+7196-->
+7197-->
+7198-->
+7199-->
+72-->
+720-->
+7200-->
+7201-->
+7202-->
+7203-->
+7204-->
+7205-->
+7206-->
+7207-->
+7208-->
+7209-->
+721-->
+7210-->
+7211-->
+7212-->
+7213-->
+7214-->
+7215-->
+7216-->
+7217-->
+7218-->
+7219-->
+722-->
+7220-->
+7221-->
+7222-->
+7223-->
+7224-->
+7225-->
+7226-->
+7227-->
+7228-->
+7229-->
+723-->
+7230-->
+7231-->
+7232-->
+7233-->
+7234-->
+7235-->
+7236-->
+7237-->
+7238-->
+7239-->
+724-->
+7240-->
+7241-->
+7242-->
+7243-->
+7244-->
+7245-->
+7246-->
+7247-->
+7248-->
+7249-->
+725-->
+7250-->
+7251-->
+7252-->
+7253-->
+7254-->
+7255-->
+7256-->
+7257-->
+7258-->
+7259-->
+726-->
+7260-->
+7261-->
+7262-->
+7263-->
+7264-->
+7265-->
+7266-->
+7267-->
+7268-->
+7269-->
+727-->
+7270-->
+7271-->
+7272-->
+7273-->
+7274-->
+7275-->
+7276-->
+7277-->
+7278-->
+7279-->
+728-->
+7280-->
+7281-->
+7282-->
+7283-->
+7284-->
+7285-->
+7286-->
+7287-->
+7288-->
+7289-->
+729-->
+7290-->
+7291-->
+7292-->
+7293-->
+7294-->
+7295-->
+7296-->
+7297-->
+7298-->
+7299-->
+73-->
+730-->
+7300-->
+7301-->
+7302-->
+7303-->
+7304-->
+7305-->
+7306-->
+7307-->
+7308-->
+7309-->
+731-->
+7310-->
+7311-->
+7312-->
+7313-->
+7314-->
+7315-->
+7316-->
+7317-->
+7318-->
+7319-->
+732-->
+7320-->
+7321-->
+7322-->
+7323-->
+7324-->
+7325-->
+7326-->
+7327-->
+7328-->
+7329-->
+733-->
+7330-->
+7331-->
+7332-->
+7333-->
+7334-->
+7335-->
+7336-->
+7337-->
+7338-->
+7339-->
+734-->
+7340-->
+7341-->
+7342-->
+7343-->
+7344-->
+7345-->
+7346-->
+7347-->
+7348-->
+7349-->
+735-->
+7350-->
+7351-->
+7352-->
+7353-->
+7354-->
+7355-->
+7356-->
+7357-->
+7358-->
+7359-->
+736-->
+7360-->
+7361-->
+7362-->
+7363-->
+7364-->
+7365-->
+7366-->
+7367-->
+7368-->
+7369-->
+737-->
+7370-->
+7371-->
+7372-->
+7373-->
+7374-->
+7375-->
+7376-->
+7377-->
+7378-->
+7379-->
+738-->
+7380-->
+7381-->
+7382-->
+7383-->
+7384-->
+7385-->
+7386-->
+7387-->
+7388-->
+7389-->
+739-->
+7390-->
+7391-->
+7392-->
+7393-->
+7394-->
+7395-->
+7396-->
+7397-->
+7398-->
+7399-->
+74-->
+740-->
+7400-->
+7401-->
+7402-->
+7403-->
+7404-->
+7405-->
+7406-->
+7407-->
+7408-->
+7409-->
+741-->
+7410-->
+7411-->
+7412-->
+7413-->
+7414-->
+7415-->
+7416-->
+7417-->
+7418-->
+7419-->
+742-->
+7420-->
+7421-->
+7422-->
+7423-->
+7424-->
+7425-->
+7426-->
+7427-->
+7428-->
+7429-->
+743-->
+7430-->
+7431-->
+7432-->
+7433-->
+7434-->
+7435-->
+7436-->
+7437-->
+7438-->
+7439-->
+744-->
+7440-->
+7441-->
+7442-->
+7443-->
+7444-->
+7445-->
+7446-->
+7447-->
+7448-->
+7449-->
+745-->
+7450-->
+7451-->
+7452-->
+7453-->
+7454-->
+7455-->
+7456-->
+7457-->
+7458-->
+7459-->
+746-->
+7460-->
+7461-->
+7462-->
+7463-->
+7464-->
+7465-->
+7466-->
+7467-->
+7468-->
+7469-->
+747-->
+7470-->
+7471-->
+7472-->
+7473-->
+7474-->
+7475-->
+7476-->
+7477-->
+7478-->
+7479-->
+748-->
+7480-->
+7481-->
+7482-->
+7483-->
+7484-->
+7485-->
+7486-->
+7487-->
+7488-->
+7489-->
+749-->
+7490-->
+7491-->
+7492-->
+7493-->
+7494-->
+7495-->
+7496-->
+7497-->
+7498-->
+7499-->
+75-->
+750-->
+7500-->
+7501-->
+7502-->
+7503-->
+7504-->
+7505-->
+7506-->
+7507-->
+7508-->
+7509-->
+751-->
+7510-->
+7511-->
+7512-->
+7513-->
+7514-->
+7515-->
+7516-->
+7517-->
+7518-->
+7519-->
+752-->
+7520-->
+7521-->
+7522-->
+7523-->
+7524-->
+7525-->
+7526-->
+7527-->
+7528-->
+7529-->
+753-->
+7530-->
+7531-->
+7532-->
+7533-->
+7534-->
+7535-->
+7536-->
+7537-->
+7538-->
+7539-->
+754-->
+7540-->
+7541-->
+7542-->
+7543-->
+7544-->
+7545-->
+7546-->
+7547-->
+7548-->
+7549-->
+755-->
+7550-->
+7551-->
+7552-->
+7553-->
+7554-->
+7555-->
+7556-->
+7557-->
+7558-->
+7559-->
+756-->
+7560-->
+7561-->
+7562-->
+7563-->
+7564-->
+7565-->
+7566-->
+7567-->
+7568-->
+7569-->
+757-->
+7570-->
+7571-->
+7572-->
+7573-->
+7574-->
+7575-->
+7576-->
+7577-->
+7578-->
+7579-->
+758-->
+7580-->
+7581-->
+7582-->
+7583-->
+7584-->
+7585-->
+7586-->
+7587-->
+7588-->
+7589-->
+759-->
+7590-->
+7591-->
+7592-->
+7593-->
+7594-->
+7595-->
+7596-->
+7597-->
+7598-->
+7599-->
+76-->
+760-->
+7600-->
+7601-->
+7602-->
+7603-->
+7604-->
+7605-->
+7606-->
+7607-->
+7608-->
+7609-->
+761-->
+7610-->
+7611-->
+7612-->
+7613-->
+7614-->
+7615-->
+7616-->
+7617-->
+7618-->
+7619-->
+762-->
+7620-->
+7621-->
+7622-->
+7623-->
+7624-->
+7625-->
+7626-->
+7627-->
+7628-->
+7629-->
+763-->
+7630-->
+7631-->
+7632-->
+7633-->
+7634-->
+7635-->
+7636-->
+7637-->
+7638-->
+7639-->
+764-->
+7640-->
+7641-->
+7642-->
+7643-->
+7644-->
+7645-->
+7646-->
+7647-->
+7648-->
+7649-->
+765-->
+7650-->
+7651-->
+7652-->
+7653-->
+7654-->
+7655-->
+7656-->
+7657-->
+7658-->
+7659-->
+766-->
+7660-->
+7661-->
+7662-->
+7663-->
+7664-->
+7665-->
+7666-->
+7667-->
+7668-->
+7669-->
+767-->
+7670-->
+7671-->
+7672-->
+7673-->
+7674-->
+7675-->
+7676-->
+7677-->
+7678-->
+7679-->
+768-->
+7680-->
+7681-->
+7682-->
+7683-->
+7684-->
+7685-->
+7686-->
+7687-->
+7688-->
+7689-->
+769-->
+7690-->
+7691-->
+7692-->
+7693-->
+7694-->
+7695-->
+7696-->
+7697-->
+7698-->
+7699-->
+77-->
+770-->
+7700-->
+7701-->
+7702-->
+7703-->
+7704-->
+7705-->
+7706-->
+7707-->
+7708-->
+7709-->
+771-->
+7710-->
+7711-->
+7712-->
+7713-->
+7714-->
+7715-->
+7716-->
+7717-->
+7718-->
+7719-->
+772-->
+7720-->
+7721-->
+7722-->
+7723-->
+7724-->
+7725-->
+7726-->
+7727-->
+7728-->
+7729-->
+773-->
+7730-->
+7731-->
+7732-->
+7733-->
+7734-->
+7735-->
+7736-->
+7737-->
+7738-->
+7739-->
+774-->
+7740-->
+7741-->
+7742-->
+7743-->
+7744-->
+7745-->
+7746-->
+7747-->
+7748-->
+7749-->
+775-->
+7750-->
+7751-->
+7752-->
+7753-->
+7754-->
+7755-->
+7756-->
+7757-->
+7758-->
+7759-->
+776-->
+7760-->
+7761-->
+7762-->
+7763-->
+7764-->
+7765-->
+7766-->
+7767-->
+7768-->
+7769-->
+777-->
+7770-->
+7771-->
+7772-->
+7773-->
+7774-->
+7775-->
+7776-->
+7777-->
+7778-->
+7779-->
+778-->
+7780-->
+7781-->
+7782-->
+7783-->
+7784-->
+7785-->
+7786-->
+7787-->
+7788-->
+7789-->
+779-->
+7790-->
+7791-->
+7792-->
+7793-->
+7794-->
+7795-->
+7796-->
+7797-->
+7798-->
+7799-->
+78-->
+780-->
+7800-->
+7801-->
+7802-->
+7803-->
+7804-->
+7805-->
+7806-->
+7807-->
+7808-->
+7809-->
+781-->
+7810-->
+7811-->
+7812-->
+7813-->
+7814-->
+7815-->
+7816-->
+7817-->
+7818-->
+7819-->
+782-->
+7820-->
+7821-->
+7822-->
+7823-->
+7824-->
+7825-->
+7826-->
+7827-->
+7828-->
+7829-->
+783-->
+7830-->
+7831-->
+7832-->
+7833-->
+7834-->
+7835-->
+7836-->
+7837-->
+7838-->
+7839-->
+784-->
+7840-->
+7841-->
+7842-->
+7843-->
+7844-->
+7845-->
+7846-->
+7847-->
+7848-->
+7849-->
+785-->
+7850-->
+7851-->
+7852-->
+7853-->
+7854-->
+7855-->
+7856-->
+7857-->
+7858-->
+7859-->
+786-->
+7860-->
+7861-->
+7862-->
+7863-->
+7864-->
+7865-->
+7866-->
+7867-->
+7868-->
+7869-->
+787-->
+7870-->
+7871-->
+7872-->
+7873-->
+7874-->
+7875-->
+7876-->
+7877-->
+7878-->
+7879-->
+788-->
+7880-->
+7881-->
+7882-->
+7883-->
+7884-->
+7885-->
+7886-->
+7887-->
+7888-->
+7889-->
+789-->
+7890-->
+7891-->
+7892-->
+7893-->
+7894-->
+7895-->
+7896-->
+7897-->
+7898-->
+7899-->
+79-->
+790-->
+7900-->
+7901-->
+7902-->
+7903-->
+7904-->
+7905-->
+7906-->
+7907-->
+7908-->
+7909-->
+791-->
+7910-->
+7911-->
+7912-->
+7913-->
+7914-->
+7915-->
+7916-->
+7917-->
+7918-->
+7919-->
+792-->
+7920-->
+7921-->
+7922-->
+7923-->
+7924-->
+7925-->
+7926-->
+7927-->
+7928-->
+7929-->
+793-->
+7930-->
+7931-->
+7932-->
+7933-->
+7934-->
+7935-->
+7936-->
+7937-->
+7938-->
+7939-->
+794-->
+7940-->
+7941-->
+7942-->
+7943-->
+7944-->
+7945-->
+7946-->
+7947-->
+7948-->
+7949-->
+795-->
+7950-->
+7951-->
+7952-->
+7953-->
+7954-->
+7955-->
+7956-->
+7957-->
+7958-->
+7959-->
+796-->
+7960-->
+7961-->
+7962-->
+7963-->
+7964-->
+7965-->
+7966-->
+7967-->
+7968-->
+7969-->
+797-->
+7970-->
+7971-->
+7972-->
+7973-->
+7974-->
+7975-->
+7976-->
+7977-->
+7978-->
+7979-->
+798-->
+7980-->
+7981-->
+7982-->
+7983-->
+7984-->
+7985-->
+7986-->
+7987-->
+7988-->
+7989-->
+799-->
+7990-->
+7991-->
+7992-->
+7993-->
+7994-->
+7995-->
+7996-->
+7997-->
+7998-->
+7999-->
+8-->
+80-->
+800-->
+8000-->
+8001-->
+8002-->
+8003-->
+8004-->
+8005-->
+8006-->
+8007-->
+8008-->
+8009-->
+801-->
+8010-->
+8011-->
+8012-->
+8013-->
+8014-->
+8015-->
+8016-->
+8017-->
+8018-->
+8019-->
+802-->
+8020-->
+8021-->
+8022-->
+8023-->
+8024-->
+8025-->
+8026-->
+8027-->
+8028-->
+8029-->
+803-->
+8030-->
+8031-->
+8032-->
+8033-->
+8034-->
+8035-->
+8036-->
+8037-->
+8038-->
+8039-->
+804-->
+8040-->
+8041-->
+8042-->
+8043-->
+8044-->
+8045-->
+8046-->
+8047-->
+8048-->
+8049-->
+805-->
+8050-->
+8051-->
+8052-->
+8053-->
+8054-->
+8055-->
+8056-->
+8057-->
+8058-->
+8059-->
+806-->
+8060-->
+8061-->
+8062-->
+8063-->
+8064-->
+8065-->
+8066-->
+8067-->
+8068-->
+8069-->
+807-->
+8070-->
+8071-->
+8072-->
+8073-->
+8074-->
+8075-->
+8076-->
+8077-->
+8078-->
+8079-->
+808-->
+8080-->
+8081-->
+8082-->
+8083-->
+8084-->
+8085-->
+8086-->
+8087-->
+8088-->
+8089-->
+809-->
+8090-->
+8091-->
+8092-->
+8093-->
+8094-->
+8095-->
+8096-->
+8097-->
+8098-->
+8099-->
+81-->
+810-->
+8100-->
+8101-->
+8102-->
+8103-->
+8104-->
+8105-->
+8106-->
+8107-->
+8108-->
+8109-->
+811-->
+8110-->
+8111-->
+8112-->
+8113-->
+8114-->
+8115-->
+8116-->
+8117-->
+8118-->
+8119-->
+812-->
+8120-->
+8121-->
+8122-->
+8123-->
+8124-->
+8125-->
+8126-->
+8127-->
+8128-->
+8129-->
+813-->
+8130-->
+8131-->
+8132-->
+8133-->
+8134-->
+8135-->
+8136-->
+8137-->
+8138-->
+8139-->
+814-->
+8140-->
+8141-->
+8142-->
+8143-->
+8144-->
+8145-->
+8146-->
+8147-->
+8148-->
+8149-->
+815-->
+8150-->
+8151-->
+8152-->
+8153-->
+8154-->
+8155-->
+8156-->
+8157-->
+8158-->
+8159-->
+816-->
+8160-->
+8161-->
+8162-->
+8163-->
+8164-->
+8165-->
+8166-->
+8167-->
+8168-->
+8169-->
+817-->
+8170-->
+8171-->
+8172-->
+8173-->
+8174-->
+8175-->
+8176-->
+8177-->
+8178-->
+8179-->
+818-->
+8180-->
+8181-->
+8182-->
+8183-->
+8184-->
+8185-->
+8186-->
+8187-->
+8188-->
+8189-->
+819-->
+8190-->
+8191-->
+8192-->
+8193-->
+8194-->
+8195-->
+8196-->
+8197-->
+8198-->
+8199-->
+82-->
+820-->
+8200-->
+8201-->
+8202-->
+8203-->
+8204-->
+8205-->
+8206-->
+8207-->
+8208-->
+8209-->
+821-->
+8210-->
+8211-->
+8212-->
+8213-->
+8214-->
+8215-->
+8216-->
+8217-->
+8218-->
+8219-->
+822-->
+8220-->
+8221-->
+8222-->
+8223-->
+8224-->
+8225-->
+8226-->
+8227-->
+8228-->
+8229-->
+823-->
+8230-->
+8231-->
+8232-->
+8233-->
+8234-->
+8235-->
+8236-->
+8237-->
+8238-->
+8239-->
+824-->
+8240-->
+8241-->
+8242-->
+8243-->
+8244-->
+8245-->
+8246-->
+8247-->
+8248-->
+8249-->
+825-->
+8250-->
+8251-->
+8252-->
+8253-->
+8254-->
+8255-->
+8256-->
+8257-->
+8258-->
+8259-->
+826-->
+8260-->
+8261-->
+8262-->
+8263-->
+8264-->
+8265-->
+8266-->
+8267-->
+8268-->
+8269-->
+827-->
+8270-->
+8271-->
+8272-->
+8273-->
+8274-->
+8275-->
+8276-->
+8277-->
+8278-->
+8279-->
+828-->
+8280-->
+8281-->
+8282-->
+8283-->
+8284-->
+8285-->
+8286-->
+8287-->
+8288-->
+8289-->
+829-->
+8290-->
+8291-->
+8292-->
+8293-->
+8294-->
+8295-->
+8296-->
+8297-->
+8298-->
+8299-->
+83-->
+830-->
+8300-->
+8301-->
+8302-->
+8303-->
+8304-->
+8305-->
+8306-->
+8307-->
+8308-->
+8309-->
+831-->
+8310-->
+8311-->
+8312-->
+8313-->
+8314-->
+8315-->
+8316-->
+8317-->
+8318-->
+8319-->
+832-->
+8320-->
+8321-->
+8322-->
+8323-->
+8324-->
+8325-->
+8326-->
+8327-->
+8328-->
+8329-->
+833-->
+8330-->
+8331-->
+8332-->
+8333-->
+8334-->
+8335-->
+8336-->
+8337-->
+8338-->
+8339-->
+834-->
+8340-->
+8341-->
+8342-->
+8343-->
+8344-->
+8345-->
+8346-->
+8347-->
+8348-->
+8349-->
+835-->
+8350-->
+8351-->
+8352-->
+8353-->
+8354-->
+8355-->
+8356-->
+8357-->
+8358-->
+8359-->
+836-->
+8360-->
+8361-->
+8362-->
+8363-->
+8364-->
+8365-->
+8366-->
+8367-->
+8368-->
+8369-->
+837-->
+8370-->
+8371-->
+8372-->
+8373-->
+8374-->
+8375-->
+8376-->
+8377-->
+8378-->
+8379-->
+838-->
+8380-->
+8381-->
+8382-->
+8383-->
+8384-->
+8385-->
+8386-->
+8387-->
+8388-->
+8389-->
+839-->
+8390-->
+8391-->
+8392-->
+8393-->
+8394-->
+8395-->
+8396-->
+8397-->
+8398-->
+8399-->
+84-->
+840-->
+8400-->
+8401-->
+8402-->
+8403-->
+8404-->
+8405-->
+8406-->
+8407-->
+8408-->
+8409-->
+841-->
+8410-->
+8411-->
+8412-->
+8413-->
+8414-->
+8415-->
+8416-->
+8417-->
+8418-->
+8419-->
+842-->
+8420-->
+8421-->
+8422-->
+8423-->
+8424-->
+8425-->
+8426-->
+8427-->
+8428-->
+8429-->
+843-->
+8430-->
+8431-->
+8432-->
+8433-->
+8434-->
+8435-->
+8436-->
+8437-->
+8438-->
+8439-->
+844-->
+8440-->
+8441-->
+8442-->
+8443-->
+8444-->
+8445-->
+8446-->
+8447-->
+8448-->
+8449-->
+845-->
+8450-->
+8451-->
+8452-->
+8453-->
+8454-->
+8455-->
+8456-->
+8457-->
+8458-->
+8459-->
+846-->
+8460-->
+8461-->
+8462-->
+8463-->
+8464-->
+8465-->
+8466-->
+8467-->
+8468-->
+8469-->
+847-->
+8470-->
+8471-->
+8472-->
+8473-->
+8474-->
+8475-->
+8476-->
+8477-->
+8478-->
+8479-->
+848-->
+8480-->
+8481-->
+8482-->
+8483-->
+8484-->
+8485-->
+8486-->
+8487-->
+8488-->
+8489-->
+849-->
+8490-->
+8491-->
+8492-->
+8493-->
+8494-->
+8495-->
+8496-->
+8497-->
+8498-->
+8499-->
+85-->
+850-->
+8500-->
+8501-->
+8502-->
+8503-->
+8504-->
+8505-->
+8506-->
+8507-->
+8508-->
+8509-->
+851-->
+8510-->
+8511-->
+8512-->
+8513-->
+8514-->
+8515-->
+8516-->
+8517-->
+8518-->
+8519-->
+852-->
+8520-->
+8521-->
+8522-->
+8523-->
+8524-->
+8525-->
+8526-->
+8527-->
+8528-->
+8529-->
+853-->
+8530-->
+8531-->
+8532-->
+8533-->
+8534-->
+8535-->
+8536-->
+8537-->
+8538-->
+8539-->
+854-->
+8540-->
+8541-->
+8542-->
+8543-->
+8544-->
+8545-->
+8546-->
+8547-->
+8548-->
+8549-->
+855-->
+8550-->
+8551-->
+8552-->
+8553-->
+8554-->
+8555-->
+8556-->
+8557-->
+8558-->
+8559-->
+856-->
+8560-->
+8561-->
+8562-->
+8563-->
+8564-->
+8565-->
+8566-->
+8567-->
+8568-->
+8569-->
+857-->
+8570-->
+8571-->
+8572-->
+8573-->
+8574-->
+8575-->
+8576-->
+8577-->
+8578-->
+8579-->
+858-->
+8580-->
+8581-->
+8582-->
+8583-->
+8584-->
+8585-->
+8586-->
+8587-->
+8588-->
+8589-->
+859-->
+8590-->
+8591-->
+8592-->
+8593-->
+8594-->
+8595-->
+8596-->
+8597-->
+8598-->
+8599-->
+86-->
+860-->
+8600-->
+8601-->
+8602-->
+8603-->
+8604-->
+8605-->
+8606-->
+8607-->
+8608-->
+8609-->
+861-->
+8610-->
+8611-->
+8612-->
+8613-->
+8614-->
+8615-->
+8616-->
+8617-->
+8618-->
+8619-->
+862-->
+8620-->
+8621-->
+8622-->
+8623-->
+8624-->
+8625-->
+8626-->
+8627-->
+8628-->
+8629-->
+863-->
+8630-->
+8631-->
+8632-->
+8633-->
+8634-->
+8635-->
+8636-->
+8637-->
+8638-->
+8639-->
+864-->
+8640-->
+8641-->
+8642-->
+8643-->
+8644-->
+8645-->
+8646-->
+8647-->
+8648-->
+8649-->
+865-->
+8650-->
+8651-->
+8652-->
+8653-->
+8654-->
+8655-->
+8656-->
+8657-->
+8658-->
+8659-->
+866-->
+8660-->
+8661-->
+8662-->
+8663-->
+8664-->
+8665-->
+8666-->
+8667-->
+8668-->
+8669-->
+867-->
+8670-->
+8671-->
+8672-->
+8673-->
+8674-->
+8675-->
+8676-->
+8677-->
+8678-->
+8679-->
+868-->
+8680-->
+8681-->
+8682-->
+8683-->
+8684-->
+8685-->
+8686-->
+8687-->
+8688-->
+8689-->
+869-->
+8690-->
+8691-->
+8692-->
+8693-->
+8694-->
+8695-->
+8696-->
+8697-->
+8698-->
+8699-->
+87-->
+870-->
+8700-->
+8701-->
+8702-->
+8703-->
+8704-->
+8705-->
+8706-->
+8707-->
+8708-->
+8709-->
+871-->
+8710-->
+8711-->
+8712-->
+8713-->
+8714-->
+8715-->
+8716-->
+8717-->
+8718-->
+8719-->
+872-->
+8720-->
+8721-->
+8722-->
+8723-->
+8724-->
+8725-->
+8726-->
+8727-->
+8728-->
+8729-->
+873-->
+8730-->
+8731-->
+8732-->
+8733-->
+8734-->
+8735-->
+8736-->
+8737-->
+8738-->
+8739-->
+874-->
+8740-->
+8741-->
+8742-->
+8743-->
+8744-->
+8745-->
+8746-->
+8747-->
+8748-->
+8749-->
+875-->
+8750-->
+8751-->
+8752-->
+8753-->
+8754-->
+8755-->
+8756-->
+8757-->
+8758-->
+8759-->
+876-->
+8760-->
+8761-->
+8762-->
+8763-->
+8764-->
+8765-->
+8766-->
+8767-->
+8768-->
+8769-->
+877-->
+8770-->
+8771-->
+8772-->
+8773-->
+8774-->
+8775-->
+8776-->
+8777-->
+8778-->
+8779-->
+878-->
+8780-->
+8781-->
+8782-->
+8783-->
+8784-->
+8785-->
+8786-->
+8787-->
+8788-->
+8789-->
+879-->
+8790-->
+8791-->
+8792-->
+8793-->
+8794-->
+8795-->
+8796-->
+8797-->
+8798-->
+8799-->
+88-->
+880-->
+8800-->
+8801-->
+8802-->
+8803-->
+8804-->
+8805-->
+8806-->
+8807-->
+8808-->
+8809-->
+881-->
+8810-->
+8811-->
+8812-->
+8813-->
+8814-->
+8815-->
+8816-->
+8817-->
+8818-->
+8819-->
+882-->
+8820-->
+8821-->
+8822-->
+8823-->
+8824-->
+8825-->
+8826-->
+8827-->
+8828-->
+8829-->
+883-->
+8830-->
+8831-->
+8832-->
+8833-->
+8834-->
+8835-->
+8836-->
+8837-->
+8838-->
+8839-->
+884-->
+8840-->
+8841-->
+8842-->
+8843-->
+8844-->
+8845-->
+8846-->
+8847-->
+8848-->
+8849-->
+885-->
+8850-->
+8851-->
+8852-->
+8853-->
+8854-->
+8855-->
+8856-->
+8857-->
+8858-->
+8859-->
+886-->
+8860-->
+8861-->
+8862-->
+8863-->
+8864-->
+8865-->
+8866-->
+8867-->
+8868-->
+8869-->
+887-->
+8870-->
+8871-->
+8872-->
+8873-->
+8874-->
+8875-->
+8876-->
+8877-->
+8878-->
+8879-->
+888-->
+8880-->
+8881-->
+8882-->
+8883-->
+8884-->
+8885-->
+8886-->
+8887-->
+8888-->
+8889-->
+889-->
+8890-->
+8891-->
+8892-->
+8893-->
+8894-->
+8895-->
+8896-->
+8897-->
+8898-->
+8899-->
+89-->
+890-->
+8900-->
+8901-->
+8902-->
+8903-->
+8904-->
+8905-->
+8906-->
+8907-->
+8908-->
+8909-->
+891-->
+8910-->
+8911-->
+8912-->
+8913-->
+8914-->
+8915-->
+8916-->
+8917-->
+8918-->
+8919-->
+892-->
+8920-->
+8921-->
+8922-->
+8923-->
+8924-->
+8925-->
+8926-->
+8927-->
+8928-->
+8929-->
+893-->
+8930-->
+8931-->
+8932-->
+8933-->
+8934-->
+8935-->
+8936-->
+8937-->
+8938-->
+8939-->
+894-->
+8940-->
+8941-->
+8942-->
+8943-->
+8944-->
+8945-->
+8946-->
+8947-->
+8948-->
+8949-->
+895-->
+8950-->
+8951-->
+8952-->
+8953-->
+8954-->
+8955-->
+8956-->
+8957-->
+8958-->
+8959-->
+896-->
+8960-->
+8961-->
+8962-->
+8963-->
+8964-->
+8965-->
+8966-->
+8967-->
+8968-->
+8969-->
+897-->
+8970-->
+8971-->
+8972-->
+8973-->
+8974-->
+8975-->
+8976-->
+8977-->
+8978-->
+8979-->
+898-->
+8980-->
+8981-->
+8982-->
+8983-->
+8984-->
+8985-->
+8986-->
+8987-->
+8988-->
+8989-->
+899-->
+8990-->
+8991-->
+8992-->
+8993-->
+8994-->
+8995-->
+8996-->
+8997-->
+8998-->
+8999-->
+9-->
+90-->
+900-->
+9000-->
+9001-->
+9002-->
+9003-->
+9004-->
+9005-->
+9006-->
+9007-->
+9008-->
+9009-->
+901-->
+9010-->
+9011-->
+9012-->
+9013-->
+9014-->
+9015-->
+9016-->
+9017-->
+9018-->
+9019-->
+902-->
+9020-->
+9021-->
+9022-->
+9023-->
+9024-->
+9025-->
+9026-->
+9027-->
+9028-->
+9029-->
+903-->
+9030-->
+9031-->
+9032-->
+9033-->
+9034-->
+9035-->
+9036-->
+9037-->
+9038-->
+9039-->
+904-->
+9040-->
+9041-->
+9042-->
+9043-->
+9044-->
+9045-->
+9046-->
+9047-->
+9048-->
+9049-->
+905-->
+9050-->
+9051-->
+9052-->
+9053-->
+9054-->
+9055-->
+9056-->
+9057-->
+9058-->
+9059-->
+906-->
+9060-->
+9061-->
+9062-->
+9063-->
+9064-->
+9065-->
+9066-->
+9067-->
+9068-->
+9069-->
+907-->
+9070-->
+9071-->
+9072-->
+9073-->
+9074-->
+9075-->
+9076-->
+9077-->
+9078-->
+9079-->
+908-->
+9080-->
+9081-->
+9082-->
+9083-->
+9084-->
+9085-->
+9086-->
+9087-->
+9088-->
+9089-->
+909-->
+9090-->
+9091-->
+9092-->
+9093-->
+9094-->
+9095-->
+9096-->
+9097-->
+9098-->
+9099-->
+91-->
+910-->
+9100-->
+9101-->
+9102-->
+9103-->
+9104-->
+9105-->
+9106-->
+9107-->
+9108-->
+9109-->
+911-->
+9110-->
+9111-->
+9112-->
+9113-->
+9114-->
+9115-->
+9116-->
+9117-->
+9118-->
+9119-->
+912-->
+9120-->
+9121-->
+9122-->
+9123-->
+9124-->
+9125-->
+9126-->
+9127-->
+9128-->
+9129-->
+913-->
+9130-->
+9131-->
+9132-->
+9133-->
+9134-->
+9135-->
+9136-->
+9137-->
+9138-->
+9139-->
+914-->
+9140-->
+9141-->
+9142-->
+9143-->
+9144-->
+9145-->
+9146-->
+9147-->
+9148-->
+9149-->
+915-->
+9150-->
+9151-->
+9152-->
+9153-->
+9154-->
+9155-->
+9156-->
+9157-->
+9158-->
+9159-->
+916-->
+9160-->
+9161-->
+9162-->
+9163-->
+9164-->
+9165-->
+9166-->
+9167-->
+9168-->
+9169-->
+917-->
+9170-->
+9171-->
+9172-->
+9173-->
+9174-->
+9175-->
+9176-->
+9177-->
+9178-->
+9179-->
+918-->
+9180-->
+9181-->
+9182-->
+9183-->
+9184-->
+9185-->
+9186-->
+9187-->
+9188-->
+9189-->
+919-->
+9190-->
+9191-->
+9192-->
+9193-->
+9194-->
+9195-->
+9196-->
+9197-->
+9198-->
+9199-->
+92-->
+920-->
+9200-->
+9201-->
+9202-->
+9203-->
+9204-->
+9205-->
+9206-->
+9207-->
+9208-->
+9209-->
+921-->
+9210-->
+9211-->
+9212-->
+9213-->
+9214-->
+9215-->
+9216-->
+9217-->
+9218-->
+9219-->
+922-->
+9220-->
+9221-->
+9222-->
+9223-->
+9224-->
+9225-->
+9226-->
+9227-->
+9228-->
+9229-->
+923-->
+9230-->
+9231-->
+9232-->
+9233-->
+9234-->
+9235-->
+9236-->
+9237-->
+9238-->
+9239-->
+924-->
+9240-->
+9241-->
+9242-->
+9243-->
+9244-->
+9245-->
+9246-->
+9247-->
+9248-->
+9249-->
+925-->
+9250-->
+9251-->
+9252-->
+9253-->
+9254-->
+9255-->
+9256-->
+9257-->
+9258-->
+9259-->
+926-->
+9260-->
+9261-->
+9262-->
+9263-->
+9264-->
+9265-->
+9266-->
+9267-->
+9268-->
+9269-->
+927-->
+9270-->
+9271-->
+9272-->
+9273-->
+9274-->
+9275-->
+9276-->
+9277-->
+9278-->
+9279-->
+928-->
+9280-->
+9281-->
+9282-->
+9283-->
+9284-->
+9285-->
+9286-->
+9287-->
+9288-->
+9289-->
+929-->
+9290-->
+9291-->
+9292-->
+9293-->
+9294-->
+9295-->
+9296-->
+9297-->
+9298-->
+9299-->
+93-->
+930-->
+9300-->
+9301-->
+9302-->
+9303-->
+9304-->
+9305-->
+9306-->
+9307-->
+9308-->
+9309-->
+931-->
+9310-->
+9311-->
+9312-->
+9313-->
+9314-->
+9315-->
+9316-->
+9317-->
+9318-->
+9319-->
+932-->
+9320-->
+9321-->
+9322-->
+9323-->
+9324-->
+9325-->
+9326-->
+9327-->
+9328-->
+9329-->
+933-->
+9330-->
+9331-->
+9332-->
+9333-->
+9334-->
+9335-->
+9336-->
+9337-->
+9338-->
+9339-->
+934-->
+9340-->
+9341-->
+9342-->
+9343-->
+9344-->
+9345-->
+9346-->
+9347-->
+9348-->
+9349-->
+935-->
+9350-->
+9351-->
+9352-->
+9353-->
+9354-->
+9355-->
+9356-->
+9357-->
+9358-->
+9359-->
+936-->
+9360-->
+9361-->
+9362-->
+9363-->
+9364-->
+9365-->
+9366-->
+9367-->
+9368-->
+9369-->
+937-->
+9370-->
+9371-->
+9372-->
+9373-->
+9374-->
+9375-->
+9376-->
+9377-->
+9378-->
+9379-->
+938-->
+9380-->
+9381-->
+9382-->
+9383-->
+9384-->
+9385-->
+9386-->
+9387-->
+9388-->
+9389-->
+939-->
+9390-->
+9391-->
+9392-->
+9393-->
+9394-->
+9395-->
+9396-->
+9397-->
+9398-->
+9399-->
+94-->
+940-->
+9400-->
+9401-->
+9402-->
+9403-->
+9404-->
+9405-->
+9406-->
+9407-->
+9408-->
+9409-->
+941-->
+9410-->
+9411-->
+9412-->
+9413-->
+9414-->
+9415-->
+9416-->
+9417-->
+9418-->
+9419-->
+942-->
+9420-->
+9421-->
+9422-->
+9423-->
+9424-->
+9425-->
+9426-->
+9427-->
+9428-->
+9429-->
+943-->
+9430-->
+9431-->
+9432-->
+9433-->
+9434-->
+9435-->
+9436-->
+9437-->
+9438-->
+9439-->
+944-->
+9440-->
+9441-->
+9442-->
+9443-->
+9444-->
+9445-->
+9446-->
+9447-->
+9448-->
+9449-->
+945-->
+9450-->
+9451-->
+9452-->
+9453-->
+9454-->
+9455-->
+9456-->
+9457-->
+9458-->
+9459-->
+946-->
+9460-->
+9461-->
+9462-->
+9463-->
+9464-->
+9465-->
+9466-->
+9467-->
+9468-->
+9469-->
+947-->
+9470-->
+9471-->
+9472-->
+9473-->
+9474-->
+9475-->
+9476-->
+9477-->
+9478-->
+9479-->
+948-->
+9480-->
+9481-->
+9482-->
+9483-->
+9484-->
+9485-->
+9486-->
+9487-->
+9488-->
+9489-->
+949-->
+9490-->
+9491-->
+9492-->
+9493-->
+9494-->
+9495-->
+9496-->
+9497-->
+9498-->
+9499-->
+95-->
+950-->
+9500-->
+9501-->
+9502-->
+9503-->
+9504-->
+9505-->
+9506-->
+9507-->
+9508-->
+9509-->
+951-->
+9510-->
+9511-->
+9512-->
+9513-->
+9514-->
+9515-->
+9516-->
+9517-->
+9518-->
+9519-->
+952-->
+9520-->
+9521-->
+9522-->
+9523-->
+9524-->
+9525-->
+9526-->
+9527-->
+9528-->
+9529-->
+953-->
+9530-->
+9531-->
+9532-->
+9533-->
+9534-->
+9535-->
+9536-->
+9537-->
+9538-->
+9539-->
+954-->
+9540-->
+9541-->
+9542-->
+9543-->
+9544-->
+9545-->
+9546-->
+9547-->
+9548-->
+9549-->
+955-->
+9550-->
+9551-->
+9552-->
+9553-->
+9554-->
+9555-->
+9556-->
+9557-->
+9558-->
+9559-->
+956-->
+9560-->
+9561-->
+9562-->
+9563-->
+9564-->
+9565-->
+9566-->
+9567-->
+9568-->
+9569-->
+957-->
+9570-->
+9571-->
+9572-->
+9573-->
+9574-->
+9575-->
+9576-->
+9577-->
+9578-->
+9579-->
+958-->
+9580-->
+9581-->
+9582-->
+9583-->
+9584-->
+9585-->
+9586-->
+9587-->
+9588-->
+9589-->
+959-->
+9590-->
+9591-->
+9592-->
+9593-->
+9594-->
+9595-->
+9596-->
+9597-->
+9598-->
+9599-->
+96-->
+960-->
+9600-->
+9601-->
+9602-->
+9603-->
+9604-->
+9605-->
+9606-->
+9607-->
+9608-->
+9609-->
+961-->
+9610-->
+9611-->
+9612-->
+9613-->
+9614-->
+9615-->
+9616-->
+9617-->
+9618-->
+9619-->
+962-->
+9620-->
+9621-->
+9622-->
+9623-->
+9624-->
+9625-->
+9626-->
+9627-->
+9628-->
+9629-->
+963-->
+9630-->
+9631-->
+9632-->
+9633-->
+9634-->
+9635-->
+9636-->
+9637-->
+9638-->
+9639-->
+964-->
+9640-->
+9641-->
+9642-->
+9643-->
+9644-->
+9645-->
+9646-->
+9647-->
+9648-->
+9649-->
+965-->
+9650-->
+9651-->
+9652-->
+9653-->
+9654-->
+9655-->
+9656-->
+9657-->
+9658-->
+9659-->
+966-->
+9660-->
+9661-->
+9662-->
+9663-->
+9664-->
+9665-->
+9666-->
+9667-->
+9668-->
+9669-->
+967-->
+9670-->
+9671-->
+9672-->
+9673-->
+9674-->
+9675-->
+9676-->
+9677-->
+9678-->
+9679-->
+968-->
+9680-->
+9681-->
+9682-->
+9683-->
+9684-->
+9685-->
+9686-->
+9687-->
+9688-->
+9689-->
+969-->
+9690-->
+9691-->
+9692-->
+9693-->
+9694-->
+9695-->
+9696-->
+9697-->
+9698-->
+9699-->
+97-->
+970-->
+9700-->
+9701-->
+9702-->
+9703-->
+9704-->
+9705-->
+9706-->
+9707-->
+9708-->
+9709-->
+971-->
+9710-->
+9711-->
+9712-->
+9713-->
+9714-->
+9715-->
+9716-->
+9717-->
+9718-->
+9719-->
+972-->
+9720-->
+9721-->
+9722-->
+9723-->
+9724-->
+9725-->
+9726-->
+9727-->
+9728-->
+9729-->
+973-->
+9730-->
+9731-->
+9732-->
+9733-->
+9734-->
+9735-->
+9736-->
+9737-->
+9738-->
+9739-->
+974-->
+9740-->
+9741-->
+9742-->
+9743-->
+9744-->
+9745-->
+9746-->
+9747-->
+9748-->
+9749-->
+975-->
+9750-->
+9751-->
+9752-->
+9753-->
+9754-->
+9755-->
+9756-->
+9757-->
+9758-->
+9759-->
+976-->
+9760-->
+9761-->
+9762-->
+9763-->
+9764-->
+9765-->
+9766-->
+9767-->
+9768-->
+9769-->
+977-->
+9770-->
+9771-->
+9772-->
+9773-->
+9774-->
+9775-->
+9776-->
+9777-->
+9778-->
+9779-->
+978-->
+9780-->
+9781-->
+9782-->
+9783-->
+9784-->
+9785-->
+9786-->
+9787-->
+9788-->
+9789-->
+979-->
+9790-->
+9791-->
+9792-->
+9793-->
+9794-->
+9795-->
+9796-->
+9797-->
+9798-->
+9799-->
+98-->
+980-->
+9800-->
+9801-->
+9802-->
+9803-->
+9804-->
+9805-->
+9806-->
+9807-->
+9808-->
+9809-->
+981-->
+9810-->
+9811-->
+9812-->
+9813-->
+9814-->
+9815-->
+9816-->
+9817-->
+9818-->
+9819-->
+982-->
+9820-->
+9821-->
+9822-->
+9823-->
+9824-->
+9825-->
+9826-->
+9827-->
+9828-->
+9829-->
+983-->
+9830-->
+9831-->
+9832-->
+9833-->
+9834-->
+9835-->
+9836-->
+9837-->
+9838-->
+9839-->
+984-->
+9840-->
+9841-->
+9842-->
+9843-->
+9844-->
+9845-->
+9846-->
+9847-->
+9848-->
+9849-->
+985-->
+9850-->
+9851-->
+9852-->
+9853-->
+9854-->
+9855-->
+9856-->
+9857-->
+9858-->
+9859-->
+986-->
+9860-->
+9861-->
+9862-->
+9863-->
+9864-->
+9865-->
+9866-->
+9867-->
+9868-->
+9869-->
+987-->
+9870-->
+9871-->
+9872-->
+9873-->
+9874-->
+9875-->
+9876-->
+9877-->
+9878-->
+9879-->
+988-->
+9880-->
+9881-->
+9882-->
+9883-->
+9884-->
+9885-->
+9886-->
+9887-->
+9888-->
+9889-->
+989-->
+9890-->
+9891-->
+9892-->
+9893-->
+9894-->
+9895-->
+9896-->
+9897-->
+9898-->
+9899-->
+99-->
+990-->
+9900-->
+9901-->
+9902-->
+9903-->
+9904-->
+9905-->
+9906-->
+9907-->
+9908-->
+9909-->
+991-->
+9910-->
+9911-->
+9912-->
+9913-->
+9914-->
+9915-->
+9916-->
+9917-->
+9918-->
+9919-->
+992-->
+9920-->
+9921-->
+9922-->
+9923-->
+9924-->
+9925-->
+9926-->
+9927-->
+9928-->
+9929-->
+993-->
+9930-->
+9931-->
+9932-->
+9933-->
+9934-->
+9935-->
+9936-->
+9937-->
+9938-->
+9939-->
+994-->
+9940-->
+9941-->
+9942-->
+9943-->
+9944-->
+9945-->
+9946-->
+9947-->
+9948-->
+9949-->
+995-->
+9950-->
+9951-->
+9952-->
+9953-->
+9954-->
+9955-->
+9956-->
+9957-->
+9958-->
+9959-->
+996-->
+9960-->
+9961-->
+9962-->
+9963-->
+9964-->
+9965-->
+9966-->
+9967-->
+9968-->
+9969-->
+997-->
+9970-->
+9971-->
+9972-->
+9973-->
+9974-->
+9975-->
+9976-->
+9977-->
+9978-->
+9979-->
+998-->
+9980-->
+9981-->
+9982-->
+9983-->
+9984-->
+9985-->
+9986-->
+9987-->
+9988-->
+9989-->
+999-->
+9990-->
+9991-->
+9992-->
+9993-->
+9994-->
+9995-->
+9996-->
+9997-->
+9998-->
+9999-->
diff --git a/testsuite/tests/lib-threads/test2.checker b/testsuite/tests/lib-threads/test2.checker
new file mode 100644
index 0000000000..75f6cf5666
--- /dev/null
+++ b/testsuite/tests/lib-threads/test2.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+sed -e 1q test2.result | grep -q '^[ab]*'
diff --git a/testsuite/tests/lib-threads/test2.ml b/testsuite/tests/lib-threads/test2.ml
new file mode 100644
index 0000000000..85a5e65a7f
--- /dev/null
+++ b/testsuite/tests/lib-threads/test2.ml
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let yield = ref false
+
+let print_message c =
+ for i = 1 to 10000 do
+ print_char c; flush stdout;
+ if !yield then Thread.yield()
+ done
+
+let _ = yield := (Array.length Sys.argv > 1)
+let t1 = Thread.create print_message 'a'
+let t2 = Thread.create print_message 'b'
+let _ = Thread.join t1
+let _ = Thread.join t2
+
+;;
diff --git a/testsuite/tests/lib-threads/test3.checker b/testsuite/tests/lib-threads/test3.checker
new file mode 100644
index 0000000000..88fa4934d4
--- /dev/null
+++ b/testsuite/tests/lib-threads/test3.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+sed -e 1q test3.result | grep -q '^[ab]*'
diff --git a/testsuite/tests/lib-threads/test3.ml b/testsuite/tests/lib-threads/test3.ml
new file mode 100644
index 0000000000..1540363c5b
--- /dev/null
+++ b/testsuite/tests/lib-threads/test3.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let print_message delay c =
+ while true do
+ print_char c; flush stdout; Thread.delay delay
+ done
+
+let _ =
+ Thread.create (print_message 0.6666666666) 'a';
+ print_message 1.0 'b'
diff --git a/testsuite/tests/lib-threads/test3.precheck b/testsuite/tests/lib-threads/test3.precheck
new file mode 100644
index 0000000000..aa357092af
--- /dev/null
+++ b/testsuite/tests/lib-threads/test3.precheck
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/test3.runner b/testsuite/tests/lib-threads/test3.runner
new file mode 100644
index 0000000000..dc04062a1b
--- /dev/null
+++ b/testsuite/tests/lib-threads/test3.runner
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$RUNTIME ./program >test3.result &
+pid=$!
+sleep 5
+kill -9 $pid
diff --git a/testsuite/tests/lib-threads/test4.checker b/testsuite/tests/lib-threads/test4.checker
new file mode 100644
index 0000000000..38cc61865c
--- /dev/null
+++ b/testsuite/tests/lib-threads/test4.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+LC_ALL=C $SORT -u test4.result | $DIFF test4.reference -
diff --git a/testsuite/tests/lib-threads/test4.data b/testsuite/tests/lib-threads/test4.data
new file mode 100644
index 0000000000..8edb37e36d
--- /dev/null
+++ b/testsuite/tests/lib-threads/test4.data
@@ -0,0 +1,3 @@
+abc
+def
+ghi
diff --git a/testsuite/tests/lib-threads/test4.ml b/testsuite/tests/lib-threads/test4.ml
new file mode 100644
index 0000000000..7fb789c761
--- /dev/null
+++ b/testsuite/tests/lib-threads/test4.ml
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let output_lock = Mutex.create()
+
+let rec fib n = if n <= 2 then 1 else fib(n-1) + fib(n-2)
+
+let fibtask n =
+ while true do
+ let res = fib n in
+ Mutex.lock output_lock;
+ print_int res; print_newline();
+ Mutex.unlock output_lock
+ done
+
+let _ =
+ Thread.create fibtask 28;
+ Thread.delay 1.0;
+ while true do
+ let l = read_line () in
+ Mutex.lock output_lock;
+ print_string ">> "; print_string l; print_newline();
+ Mutex.unlock output_lock
+ done
diff --git a/testsuite/tests/lib-threads/test4.reference b/testsuite/tests/lib-threads/test4.reference
new file mode 100644
index 0000000000..dfcd2b5277
--- /dev/null
+++ b/testsuite/tests/lib-threads/test4.reference
@@ -0,0 +1,4 @@
+317811
+>> abc
+>> def
+>> ghi
diff --git a/testsuite/tests/lib-threads/test4.runner b/testsuite/tests/lib-threads/test4.runner
new file mode 100644
index 0000000000..43ac563295
--- /dev/null
+++ b/testsuite/tests/lib-threads/test4.runner
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$RUNTIME ./program <test4.data >test4.result 2>/dev/null || true
diff --git a/testsuite/tests/lib-threads/test5.checker b/testsuite/tests/lib-threads/test5.checker
new file mode 100644
index 0000000000..5eef50b1c4
--- /dev/null
+++ b/testsuite/tests/lib-threads/test5.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+LC_ALL=C $SORT -u test5.result | $DIFF test5.reference -
diff --git a/testsuite/tests/lib-threads/test5.ml b/testsuite/tests/lib-threads/test5.ml
new file mode 100644
index 0000000000..24591919d7
--- /dev/null
+++ b/testsuite/tests/lib-threads/test5.ml
@@ -0,0 +1,31 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Event
+
+let ch = (new_channel() : string channel)
+
+let rec sender msg =
+ sync (send ch msg);
+ sender msg
+
+let rec receiver name =
+ print_string (name ^ ": " ^ sync (receive ch) ^ "\n");
+ flush stdout;
+ receiver name
+
+let _ =
+ Thread.create sender "hello";
+ Thread.create sender "world";
+ Thread.create receiver "A";
+ receiver "B";
+ exit 0
diff --git a/testsuite/tests/lib-threads/test5.precheck b/testsuite/tests/lib-threads/test5.precheck
new file mode 100644
index 0000000000..aa357092af
--- /dev/null
+++ b/testsuite/tests/lib-threads/test5.precheck
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/test5.reference b/testsuite/tests/lib-threads/test5.reference
new file mode 100644
index 0000000000..a66a57b28e
--- /dev/null
+++ b/testsuite/tests/lib-threads/test5.reference
@@ -0,0 +1,4 @@
+A: hello
+A: world
+B: hello
+B: world
diff --git a/testsuite/tests/lib-threads/test5.runner b/testsuite/tests/lib-threads/test5.runner
new file mode 100644
index 0000000000..80dfe37eac
--- /dev/null
+++ b/testsuite/tests/lib-threads/test5.runner
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$RUNTIME ./program >test5.result &
+pid=$!
+sleep 3
+kill -9 $pid
diff --git a/testsuite/tests/lib-threads/test6.checker b/testsuite/tests/lib-threads/test6.checker
new file mode 100644
index 0000000000..cc00a6310e
--- /dev/null
+++ b/testsuite/tests/lib-threads/test6.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+LC_ALL=C $SORT -u test6.result | $DIFF test6.reference -
diff --git a/testsuite/tests/lib-threads/test6.ml b/testsuite/tests/lib-threads/test6.ml
new file mode 100644
index 0000000000..1db9911d47
--- /dev/null
+++ b/testsuite/tests/lib-threads/test6.ml
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Event
+
+let ch = (new_channel() : string channel)
+
+let rec f tag msg =
+ select [
+ send ch msg;
+ wrap (receive ch) (fun x -> print_string(tag ^ ": " ^ x); print_newline())
+ ];
+ f tag msg
+
+let _ =
+ Thread.create (f "A") "hello";
+ f "B" "world";
+ exit 0
diff --git a/testsuite/tests/lib-threads/test6.precheck b/testsuite/tests/lib-threads/test6.precheck
new file mode 100644
index 0000000000..aa357092af
--- /dev/null
+++ b/testsuite/tests/lib-threads/test6.precheck
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/test6.reference b/testsuite/tests/lib-threads/test6.reference
new file mode 100644
index 0000000000..e4a148983d
--- /dev/null
+++ b/testsuite/tests/lib-threads/test6.reference
@@ -0,0 +1,2 @@
+A: world
+B: hello
diff --git a/testsuite/tests/lib-threads/test6.runner b/testsuite/tests/lib-threads/test6.runner
new file mode 100644
index 0000000000..50f88d8c0a
--- /dev/null
+++ b/testsuite/tests/lib-threads/test6.runner
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$RUNTIME ./program >test6.result &
+pid=$!
+sleep 1
+kill -9 $pid
diff --git a/testsuite/tests/lib-threads/test7.checker b/testsuite/tests/lib-threads/test7.checker
new file mode 100644
index 0000000000..4c4b2b4d69
--- /dev/null
+++ b/testsuite/tests/lib-threads/test7.checker
@@ -0,0 +1,14 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+test `grep -E '^-?[0123456789]+$' test7.result | wc -l` \
+ = `cat test7.result | wc -l`
diff --git a/testsuite/tests/lib-threads/test7.ml b/testsuite/tests/lib-threads/test7.ml
new file mode 100644
index 0000000000..9dae688f21
--- /dev/null
+++ b/testsuite/tests/lib-threads/test7.ml
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Event
+
+let add_ch = new_channel()
+let sub_ch = new_channel()
+let read_ch = new_channel()
+
+let rec accu n =
+ select [
+ wrap (receive add_ch) (fun x -> accu (n+x));
+ wrap (receive sub_ch) (fun x -> accu (n-x));
+ wrap (send read_ch n) (fun () -> accu n)
+ ]
+
+let rec sender chan value =
+ sync(send chan value); sender chan value
+
+let read () =
+ print_int(sync(receive read_ch)); print_newline()
+
+let main () =
+ Thread.create accu 0;
+ Thread.create (sender add_ch) 1;
+ Thread.create (sender sub_ch) 1;
+ while true do read() done
+
+let _ = Printexc.catch main ()
diff --git a/testsuite/tests/lib-threads/test7.precheck b/testsuite/tests/lib-threads/test7.precheck
new file mode 100644
index 0000000000..aa357092af
--- /dev/null
+++ b/testsuite/tests/lib-threads/test7.precheck
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/test7.runner b/testsuite/tests/lib-threads/test7.runner
new file mode 100644
index 0000000000..ccd56a31d6
--- /dev/null
+++ b/testsuite/tests/lib-threads/test7.runner
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$RUNTIME ./program >test7.result &
+pid=$!
+sleep 1
+kill -9 $pid
diff --git a/testsuite/tests/lib-threads/test8.ml b/testsuite/tests/lib-threads/test8.ml
new file mode 100644
index 0000000000..b3d1025dbb
--- /dev/null
+++ b/testsuite/tests/lib-threads/test8.ml
@@ -0,0 +1,63 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Event
+
+type 'a buffer_channel = {
+ input: 'a channel;
+ output: 'a channel;
+ thread: Thread.t;
+}
+
+let new_buffer_channel() =
+ let ic = new_channel() in
+ let oc = new_channel() in
+ let rec buffer_process front rear =
+ match (front, rear) with
+ | (["EOF"], []) -> Thread.exit ()
+ | ([], []) -> buffer_process [sync(receive ic)] []
+ | (hd::tl, _) ->
+ select [
+ wrap (receive ic) (fun x -> buffer_process front (x::rear));
+ wrap (send oc hd) (fun () -> buffer_process tl rear)
+ ]
+ | ([], _) -> buffer_process (List.rev rear) [] in
+ let t = Thread.create (buffer_process []) [] in
+ { input = ic; output = oc; thread = t }
+
+let buffer_send bc data =
+ sync(send bc.input data)
+
+let buffer_receive bc =
+ receive bc.output
+
+(* Test *)
+
+let box = new_buffer_channel()
+let ch = new_channel()
+
+let f () =
+ buffer_send box "un";
+ buffer_send box "deux";
+ sync (send ch 3)
+
+let g () =
+ print_int (sync(receive ch)); print_newline();
+ print_string (sync(buffer_receive box)); print_newline();
+ print_string (sync(buffer_receive box)); print_newline()
+
+let _ =
+ let t = Thread.create f () in
+ g();
+ buffer_send box "EOF";
+ Thread.join box.thread;
+ Thread.join t
diff --git a/testsuite/tests/lib-threads/test8.precheck b/testsuite/tests/lib-threads/test8.precheck
new file mode 100644
index 0000000000..aa357092af
--- /dev/null
+++ b/testsuite/tests/lib-threads/test8.precheck
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/test8.reference b/testsuite/tests/lib-threads/test8.reference
new file mode 100644
index 0000000000..35c80454f0
--- /dev/null
+++ b/testsuite/tests/lib-threads/test8.reference
@@ -0,0 +1,3 @@
+3
+un
+deux
diff --git a/testsuite/tests/lib-threads/test9.checker b/testsuite/tests/lib-threads/test9.checker
new file mode 100644
index 0000000000..09dd0e2547
--- /dev/null
+++ b/testsuite/tests/lib-threads/test9.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+LC_ALL=C $SORT test9.result | $DIFF test9.reference -
diff --git a/testsuite/tests/lib-threads/test9.ml b/testsuite/tests/lib-threads/test9.ml
new file mode 100644
index 0000000000..16d61e0433
--- /dev/null
+++ b/testsuite/tests/lib-threads/test9.ml
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Event
+
+type 'a swap_chan = ('a * 'a channel) channel
+
+let swap msg_out ch =
+ guard (fun () ->
+ let ic = new_channel() in
+ choose [
+ wrap (receive ch) (fun (msg_in, oc) -> sync (send oc msg_out); msg_in);
+ wrap (send ch (msg_out, ic)) (fun () -> sync (receive ic))
+ ])
+
+let ch = new_channel()
+
+let f () =
+ let res = sync (swap "F" ch) in
+ print_string "f "; print_string res; print_newline()
+
+let g () =
+ let res = sync (swap "G" ch) in
+ print_string "g "; print_string res; print_newline()
+
+let _ =
+ let id = Thread.create f () in
+ g ();
+ Thread.join id
diff --git a/testsuite/tests/lib-threads/test9.precheck b/testsuite/tests/lib-threads/test9.precheck
new file mode 100644
index 0000000000..aa357092af
--- /dev/null
+++ b/testsuite/tests/lib-threads/test9.precheck
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/test9.reference b/testsuite/tests/lib-threads/test9.reference
new file mode 100644
index 0000000000..58dc8b586d
--- /dev/null
+++ b/testsuite/tests/lib-threads/test9.reference
@@ -0,0 +1,2 @@
+f G
+g F
diff --git a/testsuite/tests/lib-threads/testA.checker b/testsuite/tests/lib-threads/testA.checker
new file mode 100644
index 0000000000..00fdfb7ad4
--- /dev/null
+++ b/testsuite/tests/lib-threads/testA.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+LC_ALL=C $SORT testA.result | $DIFF testA.reference -
diff --git a/testsuite/tests/lib-threads/testA.ml b/testsuite/tests/lib-threads/testA.ml
new file mode 100644
index 0000000000..30efd6d398
--- /dev/null
+++ b/testsuite/tests/lib-threads/testA.ml
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let private_data = (Hashtbl.create 17 : (Thread.t, string) Hashtbl.t)
+let private_data_lock = Mutex.create()
+let output_lock = Mutex.create()
+
+let set_private_data data =
+ Mutex.lock private_data_lock;
+ Hashtbl.add private_data (Thread.self()) data;
+ Mutex.unlock private_data_lock
+
+let get_private_data () =
+ Hashtbl.find private_data (Thread.self())
+
+let process id data =
+ set_private_data data;
+ Mutex.lock output_lock;
+ print_int id; print_string " --> "; print_string(get_private_data());
+ print_newline();
+ Mutex.unlock output_lock
+
+let _ =
+ let t1 = Thread.create (process 1) "un" in
+ let t2 = Thread.create (process 2) "deux" in
+ let t3 = Thread.create (process 3) "trois" in
+ let t4 = Thread.create (process 4) "quatre" in
+ let t5 = Thread.create (process 5) "cinq" in
+ List.iter Thread.join [t1;t2;t3;t4;t5]
diff --git a/testsuite/tests/lib-threads/testA.reference b/testsuite/tests/lib-threads/testA.reference
new file mode 100644
index 0000000000..5ff9295d60
--- /dev/null
+++ b/testsuite/tests/lib-threads/testA.reference
@@ -0,0 +1,5 @@
+1 --> un
+2 --> deux
+3 --> trois
+4 --> quatre
+5 --> cinq
diff --git a/testsuite/tests/lib-threads/testexit.checker b/testsuite/tests/lib-threads/testexit.checker
new file mode 100644
index 0000000000..55dcd7ba38
--- /dev/null
+++ b/testsuite/tests/lib-threads/testexit.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+LC_ALL=C $SORT testexit.result | $DIFF testexit.reference -
diff --git a/testsuite/tests/lib-threads/testexit.ml b/testsuite/tests/lib-threads/testexit.ml
new file mode 100644
index 0000000000..b0cb80d61f
--- /dev/null
+++ b/testsuite/tests/lib-threads/testexit.ml
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test Thread.exit *)
+
+let somethread (name, limit, last) =
+ let counter = ref 0 in
+ while true do
+ incr counter;
+ if !counter >= limit then begin
+ print_string (name ^ " exiting\n");
+ flush stdout;
+ if last then exit 0 else Thread.exit()
+ end;
+ print_string (name ^ ": " ^ string_of_int !counter ^ "\n");
+ flush stdout;
+ Thread.delay 0.5
+ done
+
+let _ =
+ let _ = Thread.create somethread ("A", 5, false) in
+ let _ = Thread.create somethread ("B", 8, false) in
+ let _ = Thread.create somethread ("C", 11, true) in
+ somethread ("Main", 3, false)
diff --git a/testsuite/tests/lib-threads/testexit.reference b/testsuite/tests/lib-threads/testexit.reference
new file mode 100644
index 0000000000..46ee762216
--- /dev/null
+++ b/testsuite/tests/lib-threads/testexit.reference
@@ -0,0 +1,27 @@
+A exiting
+A: 1
+A: 2
+A: 3
+A: 4
+B exiting
+B: 1
+B: 2
+B: 3
+B: 4
+B: 5
+B: 6
+B: 7
+C exiting
+C: 1
+C: 10
+C: 2
+C: 3
+C: 4
+C: 5
+C: 6
+C: 7
+C: 8
+C: 9
+Main exiting
+Main: 1
+Main: 2
diff --git a/testsuite/tests/lib-threads/testio.ml b/testsuite/tests/lib-threads/testio.ml
new file mode 100644
index 0000000000..de0e41362f
--- /dev/null
+++ b/testsuite/tests/lib-threads/testio.ml
@@ -0,0 +1,132 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test a file copy function *)
+
+let test msg producer consumer src dst =
+ print_string msg; print_newline();
+ let ic = open_in_bin src in
+ let oc = open_out_bin dst in
+ let (in_fd, out_fd) = Unix.pipe() in
+ let ipipe = Unix.in_channel_of_descr in_fd in
+ let opipe = Unix.out_channel_of_descr out_fd in
+ let prod = Thread.create producer (ic, opipe) in
+ let cons = Thread.create consumer (ipipe, oc) in
+ Thread.join prod;
+ Thread.join cons;
+ if Unix.system ("cmp " ^ src ^ " " ^ dst) = Unix.WEXITED 0
+ then print_string "passed"
+ else print_string "FAILED";
+ print_newline()
+
+(* File copy with constant-sized chunks *)
+
+let copy_file sz (ic, oc) =
+ let buffer = String.create sz in
+ let rec copy () =
+ let n = input ic buffer 0 sz in
+ if n = 0 then () else begin
+ output oc buffer 0 n;
+ copy ()
+ end in
+ copy();
+ close_in ic;
+ close_out oc
+
+(* File copy with random-sized chunks *)
+
+let copy_random sz (ic, oc) =
+ let buffer = String.create sz in
+ let rec copy () =
+ let s = 1 + Random.int sz in
+ let n = input ic buffer 0 s in
+ if n = 0 then () else begin
+ output oc buffer 0 n;
+ copy ()
+ end in
+ copy();
+ close_in ic;
+ close_out oc
+
+(* File copy line per line *)
+
+let copy_line (ic, oc) =
+ try
+ while true do
+ output_string oc (input_line ic); output_char oc '\n'
+ done
+ with End_of_file ->
+ close_in ic;
+ close_out oc
+
+(* Create long lines of text *)
+
+let make_lines ofile =
+ let oc = open_out ofile in
+ for i = 1 to 256 do
+ output_string oc (String.make (i*16) '.'); output_char oc '\n'
+ done;
+ close_out oc
+
+(* Test input_line on truncated lines *)
+
+let test_trunc_line ofile =
+ print_string "truncated line"; print_newline();
+ let oc = open_out ofile in
+ output_string oc "A line without newline!";
+ close_out oc;
+ try
+ let ic = open_in ofile in
+ let s = input_line ic in
+ close_in ic;
+ if s = "A line without newline!"
+ then print_string "passed"
+ else print_string "FAILED";
+ print_newline()
+ with End_of_file ->
+ print_string "FAILED"; print_newline()
+
+(* The test *)
+
+let main() =
+ let ifile = try Sys.argv.(1) with _ -> "testio.ml" in
+ let ofile = Filename.temp_file "testio" "" in
+ test "256-byte chunks, 256-byte chunks"
+ (copy_file 256) (copy_file 256) ifile ofile;
+ test "4096-byte chunks, 4096-byte chunks"
+ (copy_file 4096) (copy_file 4096) ifile ofile;
+ test "65536-byte chunks, 65536-byte chunks"
+ (copy_file 65536) (copy_file 65536) ifile ofile;
+ test "256-byte chunks, 4096-byte chunks"
+ (copy_file 256) (copy_file 4096) ifile ofile;
+ test "4096-byte chunks, 256-byte chunks"
+ (copy_file 4096) (copy_file 256) ifile ofile;
+ test "4096-byte chunks, 65536-byte chunks"
+ (copy_file 4096) (copy_file 65536) ifile ofile;
+ test "263-byte chunks, 4011-byte chunks"
+ (copy_file 263) (copy_file 4011) ifile ofile;
+ test "613-byte chunks, 1027-byte chunks"
+ (copy_file 613) (copy_file 1027) ifile ofile;
+ test "0...8192 byte chunks"
+ (copy_random 8192) (copy_random 8192) ifile ofile;
+ test "line per line, short lines"
+ copy_line copy_line "test-file-short-lines" ofile;
+ let linesfile = Filename.temp_file "lines" "" in
+ make_lines linesfile;
+ test "line per line, short and long lines"
+ copy_line copy_line linesfile ofile;
+ test_trunc_line ofile;
+ Sys.remove linesfile;
+ Sys.remove ofile;
+ exit 0
+
+let _ = Unix.handle_unix_error main (); exit 0
diff --git a/testsuite/tests/lib-threads/testio.reference b/testsuite/tests/lib-threads/testio.reference
new file mode 100644
index 0000000000..26de848f73
--- /dev/null
+++ b/testsuite/tests/lib-threads/testio.reference
@@ -0,0 +1,24 @@
+256-byte chunks, 256-byte chunks
+passed
+4096-byte chunks, 4096-byte chunks
+passed
+65536-byte chunks, 65536-byte chunks
+passed
+256-byte chunks, 4096-byte chunks
+passed
+4096-byte chunks, 256-byte chunks
+passed
+4096-byte chunks, 65536-byte chunks
+passed
+263-byte chunks, 4011-byte chunks
+passed
+613-byte chunks, 1027-byte chunks
+passed
+0...8192 byte chunks
+passed
+line per line, short lines
+passed
+line per line, short and long lines
+passed
+truncated line
+passed
diff --git a/testsuite/tests/lib-threads/testsieve.ml b/testsuite/tests/lib-threads/testsieve.ml
new file mode 100644
index 0000000000..6979f80318
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsieve.ml
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let sieve primes=
+ Event.sync (Event.send primes 0);
+ Event.sync (Event.send primes 1);
+ Event.sync (Event.send primes 2);
+ let integers = Event.new_channel () in
+ let rec enumerate n=
+ Event.sync (Event.send integers n);
+ enumerate (n + 2)
+ and filter inpout =
+ let n = Event.sync (Event.receive inpout)
+ (* On prepare le terrain pour l'appel recursif *)
+ and output = Event.new_channel () in
+ (* Celui qui etait en tete du crible est premier *)
+ Event.sync (Event.send primes n);
+ Thread.create filter output;
+ (* On elimine de la sortie ceux qui sont des multiples de n *)
+ while true do
+ let m = Event.sync (Event.receive inpout) in
+ (* print_int n; print_string ": "; print_int m; print_newline(); *)
+ if (m mod n) = 0
+ then ()
+ else ((Event.sync (Event.send output m));())
+ done in
+ Thread.create filter integers;
+ Thread.create enumerate 3
+
+let premiers = Event.new_channel ()
+
+let main _ =
+ Thread.create sieve premiers;
+ while true do
+ for i = 1 to 100 do
+ let n = Event.sync (Event.receive premiers) in
+ print_int n; print_newline()
+ done;
+ exit 0
+ done
+
+
+let _ =
+ try main ()
+ with _ -> exit 0;;
diff --git a/testsuite/tests/lib-threads/testsieve.reference b/testsuite/tests/lib-threads/testsieve.reference
new file mode 100644
index 0000000000..b6b8c06e59
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsieve.reference
@@ -0,0 +1,100 @@
+0
+1
+2
+3
+5
+7
+11
+13
+17
+19
+23
+29
+31
+37
+41
+43
+47
+53
+59
+61
+67
+71
+73
+79
+83
+89
+97
+101
+103
+107
+109
+113
+127
+131
+137
+139
+149
+151
+157
+163
+167
+173
+179
+181
+191
+193
+197
+199
+211
+223
+227
+229
+233
+239
+241
+251
+257
+263
+269
+271
+277
+281
+283
+293
+307
+311
+313
+317
+331
+337
+347
+349
+353
+359
+367
+373
+379
+383
+389
+397
+401
+409
+419
+421
+431
+433
+439
+443
+449
+457
+461
+463
+467
+479
+487
+491
+499
+503
+509
+521
diff --git a/testsuite/tests/lib-threads/testsignal.checker b/testsuite/tests/lib-threads/testsignal.checker
new file mode 100644
index 0000000000..3febbff492
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsignal.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+sed -e 1q testsignal.result | grep -q '^[ab]*Got ctrl-C, exiting...$'
diff --git a/testsuite/tests/lib-threads/testsignal.ml b/testsuite/tests/lib-threads/testsignal.ml
new file mode 100644
index 0000000000..67fa75f742
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsignal.ml
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let sighandler _ =
+ print_string "Got ctrl-C, exiting..."; print_newline();
+ exit 0
+
+let print_message delay c =
+ while true do
+ print_char c; flush stdout; Thread.delay delay
+ done
+
+let _ =
+ Sys.signal Sys.sigint (Sys.Signal_handle sighandler);
+ Thread.create (print_message 0.6666666666) 'a';
+ print_message 1.0 'b'
diff --git a/testsuite/tests/lib-threads/testsignal.precheck b/testsuite/tests/lib-threads/testsignal.precheck
new file mode 100644
index 0000000000..aa357092af
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsignal.precheck
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/testsignal.runner b/testsuite/tests/lib-threads/testsignal.runner
new file mode 100644
index 0000000000..ed4e9279e0
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsignal.runner
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$RUNTIME ./program >testsignal.result &
+pid=$!
+sleep 3
+kill -INT $pid
diff --git a/testsuite/tests/lib-threads/testsignal2.checker b/testsuite/tests/lib-threads/testsignal2.checker
new file mode 100644
index 0000000000..47ede35860
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsignal2.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+sed -e 1q testsignal2.result | grep -q '^[ab]*'
diff --git a/testsuite/tests/lib-threads/testsignal2.ml b/testsuite/tests/lib-threads/testsignal2.ml
new file mode 100644
index 0000000000..e59a8557ab
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsignal2.ml
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let print_message delay c =
+ while true do
+ print_char c; flush stdout; Thread.delay delay
+ done
+
+let _ =
+ Thread.sigmask Unix.SIG_BLOCK [Sys.sigint; Sys.sigterm];
+ let th1 = Thread.create (print_message 0.6666666666) 'a' in
+ let th2 = Thread.create (print_message 1.0) 'b' in
+ let s = Thread.wait_signal [Sys.sigint; Sys.sigterm] in
+ Printf.printf "Got signal %d, exiting...\n" s
diff --git a/testsuite/tests/lib-threads/testsignal2.precheck b/testsuite/tests/lib-threads/testsignal2.precheck
new file mode 100644
index 0000000000..aa357092af
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsignal2.precheck
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/testsignal2.runner b/testsuite/tests/lib-threads/testsignal2.runner
new file mode 100644
index 0000000000..19a3942f97
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsignal2.runner
@@ -0,0 +1,18 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$RUNTIME ./program >testsignal2.result &
+pid=$!
+sleep 3
+kill -INT $pid
+sleep 1
+kill -9 $pid 2>&- || true
diff --git a/testsuite/tests/lib-threads/testsocket.ml b/testsuite/tests/lib-threads/testsocket.ml
new file mode 100644
index 0000000000..6b2b0b0495
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsocket.ml
@@ -0,0 +1,48 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Unix
+
+let engine verbose number address =
+ print_int number; print_string "> connecting"; print_newline();
+ let (ic, oc) = open_connection (ADDR_INET(address, 80)) in
+ print_int number; print_string "> connected"; print_newline();
+ output_string oc "GET / HTTP1.0\r\n\r\n"; flush oc;
+ try
+ while true do
+ let s = input_line ic in
+ if verbose then begin
+ print_int number; print_string ">"; print_string s; print_newline()
+ end
+ done;
+ with End_of_file ->
+ close_out oc;
+ print_int number; print_string "> data retrieved"; print_newline()
+
+let main() =
+ let verbose, argv =
+ match Sys.argv with
+ | [| _ |] -> false, [| Sys.argv.(0); "caml.inria.fr" |]
+ | _ -> true, Sys.argv in
+ let addresses = Array.make (Array.length argv - 1) inet_addr_any in
+ for i = 1 to Array.length argv - 1 do
+ addresses.(i - 1) <- (gethostbyname argv.(i)).h_addr_list.(0)
+ done;
+ let processes = Array.make (Array.length addresses) (Thread.self()) in
+ for i = 0 to Array.length addresses - 1 do
+ processes.(i) <- Thread.create (engine verbose i) addresses.(i)
+ done;
+ for i = 0 to Array.length processes - 1 do
+ Thread.join processes.(i)
+ done
+
+let _ = Printexc.catch main (); exit 0
diff --git a/testsuite/tests/lib-threads/testsocket.precheck b/testsuite/tests/lib-threads/testsocket.precheck
new file mode 100644
index 0000000000..6d41158efb
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsocket.precheck
@@ -0,0 +1,23 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+
+##########################################
+##########################################
+#### TEMPORARY ####
+##########################################
+##########################################
+
+# disable this test on Windows non-cygwin ports until we decide
+# how to fix PR#5325 and PR#5578
+
+$CANKILL
diff --git a/testsuite/tests/lib-threads/testsocket.reference b/testsuite/tests/lib-threads/testsocket.reference
new file mode 100644
index 0000000000..ce52141825
--- /dev/null
+++ b/testsuite/tests/lib-threads/testsocket.reference
@@ -0,0 +1,3 @@
+0> connecting
+0> connected
+0> data retrieved
diff --git a/testsuite/tests/lib-threads/token1.ml b/testsuite/tests/lib-threads/token1.ml
new file mode 100644
index 0000000000..d0a7528b08
--- /dev/null
+++ b/testsuite/tests/lib-threads/token1.ml
@@ -0,0 +1,48 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Performance test for mutexes and conditions *)
+
+let mut = Mutex.create()
+
+let niter = ref 0
+
+let token = ref 0
+
+let process (n, conds, nprocs) =
+ while true do
+ Mutex.lock mut;
+ while !token <> n do
+ (* Printf.printf "Thread %d waiting (token = %d)\n" n !token; *)
+ Condition.wait conds.(n) mut
+ done;
+ (* Printf.printf "Thread %d got token %d\n" n !token; *)
+ incr token;
+ if !token >= nprocs then token := 0;
+ if n = 0 then begin
+ decr niter;
+ if !niter <= 0 then exit 0
+ end;
+ Condition.signal conds.(!token);
+ Mutex.unlock mut
+ done
+
+let main() =
+ let nprocs = try int_of_string Sys.argv.(1) with _ -> 100 in
+ let iter = try int_of_string Sys.argv.(2) with _ -> 1000 in
+ let conds = Array.make nprocs (Condition.create()) in
+ for i = 1 to nprocs - 1 do conds.(i) <- Condition.create() done;
+ niter := iter;
+ for i = 0 to nprocs - 1 do Thread.create process (i, conds, nprocs) done;
+ Thread.delay 3600.
+
+let _ = main()
diff --git a/testsuite/tests/lib-threads/token1.reference b/testsuite/tests/lib-threads/token1.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/lib-threads/token1.reference
diff --git a/testsuite/tests/lib-threads/token2.ml b/testsuite/tests/lib-threads/token2.ml
new file mode 100644
index 0000000000..c3548fb0f2
--- /dev/null
+++ b/testsuite/tests/lib-threads/token2.ml
@@ -0,0 +1,51 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Performance test for I/O scheduling *)
+
+let mut = Mutex.create()
+
+let niter = ref 0
+
+let token = ref 0
+
+let process (n, ins, outs, nprocs) =
+ let buf = String.make 1 '.' in
+ while buf <> "-" do
+ Unix.read ins.(n) buf 0 1;
+ (* Printf.printf "Thread %d got the token\n" n; *)
+ if n = 0 then begin
+ decr niter;
+ if !niter <= 0 then buf.[0] <- '-';
+ end;
+ let next = if n + 1 >= nprocs then 0 else n + 1 in
+ (* Printf.printf "Thread %d sending token to thread %d\n" n next; *)
+ Unix.write outs.(next) buf 0 1
+ done
+
+let main() =
+ let nprocs = try int_of_string Sys.argv.(1) with _ -> 100 in
+ let iter = try int_of_string Sys.argv.(2) with _ -> 1000 in
+ let ins = Array.make nprocs Unix.stdin in
+ let outs = Array.make nprocs Unix.stdout in
+ let threads = Array.make nprocs (Thread.self ()) in
+ for n = 0 to nprocs - 1 do
+ let (i, o) = Unix.pipe() in ins.(n) <- i; outs.(n) <- o
+ done;
+ niter := iter;
+ for i = 0 to nprocs - 1 do
+ threads.(i) <- Thread.create process (i, ins, outs, nprocs)
+ done;
+ Unix.write outs.(0) "X" 0 1;
+ for i = 0 to nprocs - 1 do Thread.join threads.(i) done
+
+let _ = main()
diff --git a/testsuite/tests/lib-threads/token2.reference b/testsuite/tests/lib-threads/token2.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/lib-threads/token2.reference
diff --git a/testsuite/tests/lib-threads/torture.data b/testsuite/tests/lib-threads/torture.data
new file mode 100644
index 0000000000..8edb37e36d
--- /dev/null
+++ b/testsuite/tests/lib-threads/torture.data
@@ -0,0 +1,3 @@
+abc
+def
+ghi
diff --git a/testsuite/tests/lib-threads/torture.ml b/testsuite/tests/lib-threads/torture.ml
new file mode 100644
index 0000000000..0c1a3a3a0e
--- /dev/null
+++ b/testsuite/tests/lib-threads/torture.ml
@@ -0,0 +1,66 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Torture test - lots of GC *)
+
+let finished = ref false;;
+
+let gc_thread () =
+ while not !finished do
+(* print_string "gc"; print_newline(); *)
+ Gc.minor();
+ Thread.yield()
+ done
+
+let stdin_thread () =
+ while not !finished do
+ print_string ">"; flush stdout;
+ let s = read_line() in
+ print_string " >>> "; print_string s; print_newline()
+ done
+
+let writer_thread (oc, size) =
+ while not !finished do
+(* print_string "writer "; print_int size; print_newline(); *)
+ let buff = String.make size 'a' in
+ Unix.write oc buff 0 size
+ done;
+ let buff = String.make size 'b' in
+ Unix.write oc buff 0 size
+
+let reader_thread (ic, size) =
+ while true do
+(* print_string "reader "; print_int size; print_newline(); *)
+ let buff = String.create size in
+ let n = Unix.read ic buff 0 size in
+(* print_string "reader "; print_int n; print_newline(); *)
+ for i = 0 to n-1 do
+ if buff.[i] = 'b' then raise Exit
+ else if buff.[i] <> 'a' then prerr_endline "error in reader_thread"
+ done
+ done
+
+let main() =
+ let t1 = Thread.create gc_thread () in
+ let (out1, in1) = Unix.pipe() in
+ let t2 = Thread.create writer_thread (in1, 4096) in
+ let t3 = Thread.create reader_thread (out1, 4096) in
+ let (out2, in2) = Unix.pipe() in
+ let t4 = Thread.create writer_thread (in2, 16) in
+ let t5 = Thread.create reader_thread (out2, 16) in
+ try
+ stdin_thread()
+ with _ ->
+ finished := true;
+ List.iter Thread.join [t1; t2; t3; t4; t5]
+
+let _ = main()
diff --git a/testsuite/tests/lib-threads/torture.reference b/testsuite/tests/lib-threads/torture.reference
new file mode 100644
index 0000000000..f726cc4682
--- /dev/null
+++ b/testsuite/tests/lib-threads/torture.reference
@@ -0,0 +1,4 @@
+> >>> abc
+> >>> def
+> >>> ghi
+> \ No newline at end of file
diff --git a/testsuite/tests/lib-threads/torture.runner b/testsuite/tests/lib-threads/torture.runner
new file mode 100644
index 0000000000..fc1ed3879e
--- /dev/null
+++ b/testsuite/tests/lib-threads/torture.runner
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$RUNTIME ./program <torture.data >torture.result 2>/dev/null || true
diff --git a/testsuite/tests/match-exception-warnings/Makefile b/testsuite/tests/match-exception-warnings/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/match-exception-warnings/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/match-exception-warnings/exhaustiveness_warnings.ml b/testsuite/tests/match-exception-warnings/exhaustiveness_warnings.ml
new file mode 100644
index 0000000000..742038db49
--- /dev/null
+++ b/testsuite/tests/match-exception-warnings/exhaustiveness_warnings.ml
@@ -0,0 +1,12 @@
+(** Test exhaustiveness.
+
+ match clauses should continue to give warnings about inexhaustive
+ value-matching clauses when there is an exception-matching clause
+ *)
+
+let test_match_exhaustiveness () =
+ match None with
+ | exception e -> ()
+ | Some false -> ()
+ | None -> ()
+;;
diff --git a/testsuite/tests/match-exception-warnings/exhaustiveness_warnings.ml.reference b/testsuite/tests/match-exception-warnings/exhaustiveness_warnings.ml.reference
new file mode 100644
index 0000000000..f1e30bc56c
--- /dev/null
+++ b/testsuite/tests/match-exception-warnings/exhaustiveness_warnings.ml.reference
@@ -0,0 +1,11 @@
+
+# * * * * Characters 210-289:
+ ....match None with
+ | exception e -> ()
+ | Some false -> ()
+ | None -> ()
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Some true
+val test_match_exhaustiveness : unit -> unit = <fun>
+#
diff --git a/testsuite/tests/match-exception/Makefile b/testsuite/tests/match-exception/Makefile
new file mode 100644
index 0000000000..299656b246
--- /dev/null
+++ b/testsuite/tests/match-exception/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/match-exception/allocation.ml b/testsuite/tests/match-exception/allocation.ml
new file mode 100644
index 0000000000..72055c3a2e
--- /dev/null
+++ b/testsuite/tests/match-exception/allocation.ml
@@ -0,0 +1,25 @@
+(** Test that matching multiple values doesn't allocate a block. *)
+
+let f x y =
+ match x, y with
+ | Some x, None
+ | None, Some x -> x + 1
+ | None, None -> 0
+ | Some x, Some y -> x + y
+ | exception _ -> -1
+
+let test_multiple_match_does_not_allocate =
+ let allocated_bytes = Gc.allocated_bytes () in
+ let allocated_bytes' = Gc.allocated_bytes () in
+ let a = Some 3 and b = None in
+ let allocated_bytes'' = Gc.allocated_bytes () in
+ let _ = f a b in
+ let allocated_bytes''' = Gc.allocated_bytes () in
+ if allocated_bytes' -. allocated_bytes
+ = allocated_bytes''' -. allocated_bytes''
+ then
+ Printf.printf "no allocations for multiple-value match\n"
+ else
+ Printf.printf "multiple-value match allocated %f bytes\n"
+ ((allocated_bytes''' -. allocated_bytes'') -.
+ (allocated_bytes' -. allocated_bytes))
diff --git a/testsuite/tests/match-exception/allocation.reference b/testsuite/tests/match-exception/allocation.reference
new file mode 100644
index 0000000000..98056ce6e8
--- /dev/null
+++ b/testsuite/tests/match-exception/allocation.reference
@@ -0,0 +1 @@
+no allocations for multiple-value match
diff --git a/testsuite/tests/match-exception/exception_propagation.ml b/testsuite/tests/match-exception/exception_propagation.ml
new file mode 100644
index 0000000000..eedde78417
--- /dev/null
+++ b/testsuite/tests/match-exception/exception_propagation.ml
@@ -0,0 +1,17 @@
+(**
+ Test that match allows exceptions to propagate.
+*)
+let () =
+ try
+ match
+ (let _ = raise Not_found in
+ assert false)
+ with
+ | _ -> assert false
+ | exception Invalid_argument _ -> assert false
+ with
+ Not_found ->
+ print_endline "caught expected exception (Not_found)"
+ | _ ->
+ assert false
+;;
diff --git a/testsuite/tests/match-exception/exception_propagation.reference b/testsuite/tests/match-exception/exception_propagation.reference
new file mode 100644
index 0000000000..a119b6813e
--- /dev/null
+++ b/testsuite/tests/match-exception/exception_propagation.reference
@@ -0,0 +1 @@
+caught expected exception (Not_found)
diff --git a/testsuite/tests/match-exception/match_failure.ml b/testsuite/tests/match-exception/match_failure.ml
new file mode 100644
index 0000000000..40c60595f7
--- /dev/null
+++ b/testsuite/tests/match-exception/match_failure.ml
@@ -0,0 +1,19 @@
+(**
+ Test that value match failure in a match block raises Match_failure.
+*)
+let return_some_3 () = Some (1 + 2)
+;;
+
+let test_match_partial_match =
+ try
+ let _ = (match return_some_3 () with
+ | Some x when x < 3 -> "Some x"
+ | exception Failure _ -> "failure"
+ | exception Invalid_argument _ -> "invalid argument"
+ | None -> "None"
+ ) in
+ assert false
+ with
+ Match_failure _ ->
+ print_endline "match failure, as expected"
+;;
diff --git a/testsuite/tests/match-exception/match_failure.reference b/testsuite/tests/match-exception/match_failure.reference
new file mode 100644
index 0000000000..6e17840fe3
--- /dev/null
+++ b/testsuite/tests/match-exception/match_failure.reference
@@ -0,0 +1 @@
+match failure, as expected
diff --git a/testsuite/tests/match-exception/nested_handlers.ml b/testsuite/tests/match-exception/nested_handlers.ml
new file mode 100644
index 0000000000..7f2a6514c3
--- /dev/null
+++ b/testsuite/tests/match-exception/nested_handlers.ml
@@ -0,0 +1,45 @@
+(*
+ Test that multiple handlers coexist happily.
+*)
+
+let test_multiple_handlers =
+ let trace = ref [] in
+ let collect v = trace := v :: !trace in
+ let _ =
+ match
+ begin
+ match
+ begin
+ collect "one";
+ failwith "two"
+ end
+ with
+ () -> collect "failure one"
+ | exception (Failure x) ->
+ collect x;
+ failwith "three"
+ end
+ with
+ () ->
+ collect "failure two";
+ | exception (Failure x) ->
+ collect x;
+ match
+ begin
+ collect "four";
+ failwith "five"
+ end
+ with
+ () -> collect "failure three"
+ | exception (Failure x) ->
+ collect x
+ in
+ print_endline (String.concat " " !trace);
+ assert (!trace = [
+ "five";
+ "four";
+ "three";
+ "two";
+ "one";
+ ])
+;;
diff --git a/testsuite/tests/match-exception/nested_handlers.reference b/testsuite/tests/match-exception/nested_handlers.reference
new file mode 100644
index 0000000000..e305286698
--- /dev/null
+++ b/testsuite/tests/match-exception/nested_handlers.reference
@@ -0,0 +1 @@
+five four three two one
diff --git a/testsuite/tests/match-exception/raise_from_success_continuation.ml b/testsuite/tests/match-exception/raise_from_success_continuation.ml
new file mode 100644
index 0000000000..34fb647143
--- /dev/null
+++ b/testsuite/tests/match-exception/raise_from_success_continuation.ml
@@ -0,0 +1,15 @@
+(**
+ Test raising exceptions from a value-matching branch.
+*)
+let test_raise_from_val_handler =
+ let () = print_endline "test raise from val handler" in
+ let g () = List.find ((=)2) [1;2;4] in
+ let h () =
+ match
+ g ()
+ with exception _ -> 10
+ | _ -> raise Not_found
+ in
+ assert ((try h () with Not_found -> 20) = 20);
+ print_endline "raise from val handler succeeded"
+;;
diff --git a/testsuite/tests/match-exception/raise_from_success_continuation.reference b/testsuite/tests/match-exception/raise_from_success_continuation.reference
new file mode 100644
index 0000000000..4cfe216083
--- /dev/null
+++ b/testsuite/tests/match-exception/raise_from_success_continuation.reference
@@ -0,0 +1,2 @@
+test raise from val handler
+raise from val handler succeeded
diff --git a/testsuite/tests/match-exception/streams.ml b/testsuite/tests/match-exception/streams.ml
new file mode 100644
index 0000000000..43a3151055
--- /dev/null
+++ b/testsuite/tests/match-exception/streams.ml
@@ -0,0 +1,37 @@
+(**
+ Test the stream example .
+*)
+type stream = Stream of (int * stream Lazy.t)
+;;
+
+exception End_of_stream
+;;
+
+let make_stream_up_to n =
+ let rec loop i =
+ if i = n then Stream (i, lazy (raise End_of_stream))
+ else Stream (i, lazy (loop (i + 1)))
+ in loop 0
+;;
+
+let stream_get (Stream (x, s)) = (x, Lazy.force s)
+;;
+
+let rec iter_stream_match f s =
+ match stream_get s
+ with exception End_of_stream -> ()
+ | (x, s') ->
+ begin
+ f x;
+ iter_stream_match f s'
+ end
+;;
+
+let test_iter_stream =
+ let limit = 10000000 in
+ try
+ iter_stream_match ignore (make_stream_up_to limit);
+ print_endline "iter_stream with handler case (match) is tail recursive"
+ with Stack_overflow ->
+ assert false
+;;
diff --git a/testsuite/tests/match-exception/streams.reference b/testsuite/tests/match-exception/streams.reference
new file mode 100644
index 0000000000..13df46408a
--- /dev/null
+++ b/testsuite/tests/match-exception/streams.reference
@@ -0,0 +1 @@
+iter_stream with handler case (match) is tail recursive
diff --git a/testsuite/tests/match-exception/tail_calls.ml b/testsuite/tests/match-exception/tail_calls.ml
new file mode 100644
index 0000000000..61cf026648
--- /dev/null
+++ b/testsuite/tests/match-exception/tail_calls.ml
@@ -0,0 +1,21 @@
+(**
+ The success continuation expression is in tail position.
+*)
+
+let count_to_tr_match n =
+ let rec loop i =
+ match
+ i < n
+ with exception Not_found -> ()
+ | false -> ()
+ | true -> loop (i + 1)
+ in loop 0
+;;
+
+let test_tail_recursion =
+ try
+ count_to_tr_match 10000000;
+ print_endline "handler-case (match) is tail recursive"
+ with _ ->
+ assert false
+;;
diff --git a/testsuite/tests/match-exception/tail_calls.reference b/testsuite/tests/match-exception/tail_calls.reference
new file mode 100644
index 0000000000..342bf24a29
--- /dev/null
+++ b/testsuite/tests/match-exception/tail_calls.reference
@@ -0,0 +1 @@
+handler-case (match) is tail recursive
diff --git a/testsuite/tests/misc-kb/Makefile b/testsuite/tests/misc-kb/Makefile
new file mode 100644
index 0000000000..98bcd7c503
--- /dev/null
+++ b/testsuite/tests/misc-kb/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=terms equations orderings kb
+MAIN_MODULE=kbmain
+ADD_COMPFLAGS=-w a
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/misc-kb/equations.ml b/testsuite/tests/misc-kb/equations.ml
new file mode 100644
index 0000000000..0ea3bb111b
--- /dev/null
+++ b/testsuite/tests/misc-kb/equations.ml
@@ -0,0 +1,112 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(****************** Equation manipulations *************)
+
+open Terms
+
+type rule =
+ { number: int;
+ numvars: int;
+ lhs: term;
+ rhs: term }
+
+(* standardizes an equation so its variables are 1,2,... *)
+
+let mk_rule num m n =
+ let all_vars = union (vars m) (vars n) in
+ let counter = ref 0 in
+ let subst =
+ List.map (fun v -> incr counter; (v, Var !counter)) (List.rev all_vars) in
+ { number = num;
+ numvars = !counter;
+ lhs = substitute subst m;
+ rhs = substitute subst n }
+
+
+(* checks that rules are numbered in sequence and returns their number *)
+
+let check_rules rules =
+ let counter = ref 0 in
+ List.iter (fun r -> incr counter;
+ if r.number <> !counter
+ then failwith "Rule numbers not in sequence")
+ rules;
+ !counter
+
+
+let pretty_rule rule =
+ print_int rule.number; print_string " : ";
+ pretty_term rule.lhs; print_string " = "; pretty_term rule.rhs;
+ print_newline()
+
+
+let pretty_rules rules = List.iter pretty_rule rules
+
+(****************** Rewriting **************************)
+
+(* Top-level rewriting. Let eq:L=R be an equation, M be a term such that L<=M.
+ With sigma = matching L M, we define the image of M by eq as sigma(R) *)
+let reduce l m r =
+ substitute (matching l m) r
+
+(* Test whether m can be reduced by l, i.e. m contains an instance of l. *)
+
+let can_match l m =
+ try let _ = matching l m in true
+ with Failure _ -> false
+
+let rec reducible l m =
+ can_match l m ||
+ (match m with
+ | Term(_,sons) -> List.exists (reducible l) sons
+ | _ -> false)
+
+(* Top-level rewriting with multiple rules. *)
+
+let rec mreduce rules m =
+ match rules with
+ [] -> failwith "mreduce"
+ | rule::rest ->
+ try
+ reduce rule.lhs m rule.rhs
+ with Failure _ ->
+ mreduce rest m
+
+
+(* One step of rewriting in leftmost-outermost strategy,
+ with multiple rules. Fails if no redex is found *)
+
+let rec mrewrite1 rules m =
+ try
+ mreduce rules m
+ with Failure _ ->
+ match m with
+ Var n -> failwith "mrewrite1"
+ | Term(f, sons) -> Term(f, mrewrite1_sons rules sons)
+
+and mrewrite1_sons rules = function
+ [] -> failwith "mrewrite1"
+ | son::rest ->
+ try
+ mrewrite1 rules son :: rest
+ with Failure _ ->
+ son :: mrewrite1_sons rules rest
+
+
+(* Iterating rewrite1. Returns a normal form. May loop forever *)
+
+let rec mrewrite_all rules m =
+ try
+ mrewrite_all rules (mrewrite1 rules m)
+ with Failure _ ->
+ m
diff --git a/testsuite/tests/misc-kb/equations.mli b/testsuite/tests/misc-kb/equations.mli
new file mode 100644
index 0000000000..db80f48163
--- /dev/null
+++ b/testsuite/tests/misc-kb/equations.mli
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Terms
+
+type rule =
+ { number: int;
+ numvars: int;
+ lhs: term;
+ rhs: term }
+
+val mk_rule: int -> term -> term -> rule
+val check_rules: rule list -> int
+val pretty_rule: rule -> unit
+val pretty_rules: rule list -> unit
+val reduce: term -> term -> term -> term
+val reducible: term -> term -> bool
+val mreduce: rule list -> term -> term
+val mrewrite1: rule list -> term -> term
+val mrewrite1_sons: rule list -> term list -> term list
+val mrewrite_all: rule list -> term -> term
diff --git a/testsuite/tests/misc-kb/kb.ml b/testsuite/tests/misc-kb/kb.ml
new file mode 100644
index 0000000000..0892a90c85
--- /dev/null
+++ b/testsuite/tests/misc-kb/kb.ml
@@ -0,0 +1,185 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Terms
+open Equations
+
+(****************** Critical pairs *********************)
+
+(* All (u,subst) such that N/u (&var) unifies with M,
+ with principal unifier subst *)
+
+let rec super m = function
+ Term(_,sons) as n ->
+ let rec collate n = function
+ [] -> []
+ | son::rest ->
+ List.map (fun (u, subst) -> (n::u, subst)) (super m son)
+ @ collate (n+1) rest in
+ let insides = collate 1 sons in
+ begin try
+ ([], unify m n) :: insides
+ with Failure _ ->
+ insides
+ end
+ | _ -> []
+
+
+(* Ex :
+let (m,_) = <<F(A,B)>>
+and (n,_) = <<H(F(A,x),F(x,y))>> in super m n
+==> [[1],[2,Term ("B",[])]; x <- B
+ [2],[2,Term ("A",[]); 1,Term ("B",[])]] x <- A y <- B
+*)
+
+(* All (u,subst), u&[], such that n/u unifies with m *)
+
+let super_strict m = function
+ Term(_,sons) ->
+ let rec collate n = function
+ [] -> []
+ | son::rest ->
+ List.map (fun (u, subst) -> (n::u, subst)) (super m son)
+ @ collate (n+1) rest in
+ collate 1 sons
+ | _ -> []
+
+
+(* Critical pairs of l1=r1 with l2=r2 *)
+(* critical_pairs : term_pair -> term_pair -> term_pair list *)
+let critical_pairs (l1,r1) (l2,r2) =
+ let mk_pair (u,subst) =
+ substitute subst (replace l2 u r1), substitute subst r2 in
+ List.map mk_pair (super l1 l2)
+
+(* Strict critical pairs of l1=r1 with l2=r2 *)
+(* strict_critical_pairs : term_pair -> term_pair -> term_pair list *)
+let strict_critical_pairs (l1,r1) (l2,r2) =
+ let mk_pair (u,subst) =
+ substitute subst (replace l2 u r1), substitute subst r2 in
+ List.map mk_pair (super_strict l1 l2)
+
+
+(* All critical pairs of eq1 with eq2 *)
+let mutual_critical_pairs eq1 eq2 =
+ (strict_critical_pairs eq1 eq2) @ (critical_pairs eq2 eq1)
+
+(* Renaming of variables *)
+
+let rename n (t1,t2) =
+ let rec ren_rec = function
+ Var k -> Var(k+n)
+ | Term(op,sons) -> Term(op, List.map ren_rec sons) in
+ (ren_rec t1, ren_rec t2)
+
+
+(************************ Completion ******************************)
+
+let deletion_message rule =
+ print_string "Rule ";print_int rule.number; print_string " deleted";
+ print_newline()
+
+
+(* Generate failure message *)
+let non_orientable (m,n) =
+ pretty_term m; print_string " = "; pretty_term n; print_newline()
+
+
+let rec partition p = function
+ [] -> ([], [])
+ | x::l -> let (l1, l2) = partition p l in
+ if p x then (x::l1, l2) else (l1, x::l2)
+
+
+let rec get_rule n = function
+ [] -> raise Not_found
+ | r::l -> if n = r.number then r else get_rule n l
+
+
+(* Improved Knuth-Bendix completion procedure *)
+
+let kb_completion greater =
+ let rec kbrec j rules =
+ let rec process failures (k,l) eqs =
+(****
+ print_string "***kb_completion "; print_int j; print_newline();
+ pretty_rules rules;
+ List.iter non_orientable failures;
+ print_int k; print_string " "; print_int l; print_newline();
+ List.iter non_orientable eqs;
+***)
+ match eqs with
+ [] ->
+ if k<l then next_criticals failures (k+1,l) else
+ if l<j then next_criticals failures (1,l+1) else
+ begin match failures with
+ [] -> rules (* successful completion *)
+ | _ -> print_string "Non-orientable equations :"; print_newline();
+ List.iter non_orientable failures;
+ failwith "kb_completion"
+ end
+ | (m,n)::eqs ->
+ let m' = mrewrite_all rules m
+ and n' = mrewrite_all rules n
+ and enter_rule(left,right) =
+ let new_rule = mk_rule (j+1) left right in
+ pretty_rule new_rule;
+ let left_reducible rule = reducible left rule.lhs in
+ let (redl,irredl) = partition left_reducible rules in
+ List.iter deletion_message redl;
+ let right_reduce rule =
+ mk_rule rule.number rule.lhs
+ (mrewrite_all (new_rule::rules) rule.rhs) in
+ let irreds = List.map right_reduce irredl in
+ let eqs' = List.map (fun rule -> (rule.lhs, rule.rhs)) redl in
+ kbrec (j+1) (new_rule::irreds) [] (k,l) (eqs @ eqs' @ failures) in
+(***
+ print_string "--- Considering "; non_orientable (m', n');
+***)
+ if m' = n' then process failures (k,l) eqs else
+ if greater(m',n') then enter_rule(m',n') else
+ if greater(n',m') then enter_rule(n',m') else
+ process ((m',n')::failures) (k,l) eqs
+
+ and next_criticals failures (k,l) =
+(****
+ print_string "***next_criticals ";
+ print_int k; print_string " "; print_int l ; print_newline();
+****)
+ try
+ let rl = get_rule l rules in
+ let el = (rl.lhs, rl.rhs) in
+ if k=l then
+ process failures (k,l)
+ (strict_critical_pairs el (rename rl.numvars el))
+ else
+ try
+ let rk = get_rule k rules in
+ let ek = (rk.lhs, rk.rhs) in
+ process failures (k,l)
+ (mutual_critical_pairs el (rename rl.numvars ek))
+ with Not_found -> next_criticals failures (k+1,l)
+ with Not_found -> next_criticals failures (1,l+1)
+ in process
+ in kbrec
+
+
+(* complete_rules is assumed locally confluent, and checked Noetherian with
+ ordering greater, rules is any list of rules *)
+
+let kb_complete greater complete_rules rules =
+ let n = check_rules complete_rules
+ and eqs = List.map (fun rule -> (rule.lhs, rule.rhs)) rules in
+ let completed_rules =
+ kb_completion greater n complete_rules [] (n,n) eqs in
+ print_string "Canonical set found :"; print_newline();
+ pretty_rules (List.rev completed_rules)
diff --git a/testsuite/tests/misc-kb/kb.mli b/testsuite/tests/misc-kb/kb.mli
new file mode 100644
index 0000000000..246bc8198e
--- /dev/null
+++ b/testsuite/tests/misc-kb/kb.mli
@@ -0,0 +1,29 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Terms
+open Equations
+
+val super: term -> term -> (int list * (int * term) list) list
+val super_strict: term -> term -> (int list * (int * term) list) list
+val critical_pairs: term * term -> term * term -> (term * term) list
+val strict_critical_pairs: term * term -> term * term -> (term * term) list
+val mutual_critical_pairs: term * term -> term * term -> (term * term) list
+val rename: int -> term * term -> term * term
+val deletion_message: rule -> unit
+val non_orientable: term * term -> unit
+val partition: ('a -> bool) -> 'a list -> 'a list * 'a list
+val get_rule: int -> rule list -> rule
+val kb_completion:
+ (term * term -> bool) -> int -> rule list -> (term * term) list
+ -> int * int -> (term * term) list -> rule list
+val kb_complete: (term * term -> bool) -> rule list -> rule list -> unit
diff --git a/testsuite/tests/misc-kb/kbmain.ml b/testsuite/tests/misc-kb/kbmain.ml
new file mode 100644
index 0000000000..753f73533c
--- /dev/null
+++ b/testsuite/tests/misc-kb/kbmain.ml
@@ -0,0 +1,79 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Terms
+open Equations
+open Orderings
+open Kb
+
+(****
+let group_rules = [
+ { number = 1; numvars = 1;
+ lhs = Term("*", [Term("U",[]); Var 1]); rhs = Var 1 };
+ { number = 2; numvars = 1;
+ lhs = Term("*", [Term("I",[Var 1]); Var 1]); rhs = Term("U",[]) };
+ { number = 3; numvars = 3;
+ lhs = Term("*", [Term("*", [Var 1; Var 2]); Var 3]);
+ rhs = Term("*", [Var 1; Term("*", [Var 2; Var 3])]) }
+]
+****)
+
+let geom_rules = [
+ { number = 1; numvars = 1;
+ lhs = Term ("*",[(Term ("U",[])); (Var 1)]);
+ rhs = Var 1 };
+ { number = 2; numvars = 1;
+ lhs = Term ("*",[(Term ("I",[(Var 1)])); (Var 1)]);
+ rhs = Term ("U",[]) };
+ { number = 3; numvars = 3;
+ lhs = Term ("*",[(Term ("*",[(Var 1); (Var 2)])); (Var 3)]);
+ rhs = Term ("*",[(Var 1); (Term ("*",[(Var 2); (Var 3)]))]) };
+ { number = 4; numvars = 0;
+ lhs = Term ("*",[(Term ("A",[])); (Term ("B",[]))]);
+ rhs = Term ("*",[(Term ("B",[])); (Term ("A",[]))]) };
+ { number = 5; numvars = 0;
+ lhs = Term ("*",[(Term ("C",[])); (Term ("C",[]))]);
+ rhs = Term ("U",[]) };
+ { number = 6; numvars = 0;
+ lhs = Term("*",
+ [(Term ("C",[]));
+ (Term ("*",[(Term ("A",[])); (Term ("I",[(Term ("C",[]))]))]))]);
+ rhs = Term ("I",[(Term ("A",[]))]) };
+ { number = 7; numvars = 0;
+ lhs = Term("*",
+ [(Term ("C",[]));
+ (Term ("*",[(Term ("B",[])); (Term ("I",[(Term ("C",[]))]))]))]);
+ rhs = Term ("B",[]) }
+]
+
+let group_rank = function
+ "U" -> 0
+ | "*" -> 1
+ | "I" -> 2
+ | "B" -> 3
+ | "C" -> 4
+ | "A" -> 5
+ | _ -> assert false
+
+let group_precedence op1 op2 =
+ let r1 = group_rank op1
+ and r2 = group_rank op2 in
+ if r1 = r2 then Equal else
+ if r1 > r2 then Greater else NotGE
+
+let group_order = rpo group_precedence lex_ext
+
+let greater pair =
+ match group_order pair with Greater -> true | _ -> false
+
+let _ =
+ for i = 1 to 20 do kb_complete greater [] geom_rules done
diff --git a/testsuite/tests/misc-kb/kbmain.reference b/testsuite/tests/misc-kb/kbmain.reference
new file mode 100644
index 0000000000..2789a669bb
--- /dev/null
+++ b/testsuite/tests/misc-kb/kbmain.reference
@@ -0,0 +1,5460 @@
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*I(C))
+7 : C*(B*I(C)) = B
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+11 : C*(A*(I(C)*A)) = U
+12 : C*(B*(I(C)*v1)) = B*v1
+13 : I(U)*v1 = v1
+14 : I(I(v1))*U = v1
+15 : I(v3*v2)*(v3*(v2*v1)) = v1
+16 : C*(A*(I(C)*(B*A))) = B
+17 : I(C)*U = C
+18 : C*(A*(I(C)*(A*v1))) = v1
+19 : I(C)*B = B*I(C)
+20 : I(I(v2))*v1 = v2*v1
+Rule 14 deleted
+21 : v1*U = v1
+Rule 17 deleted
+22 : I(C) = C
+Rule 19 deleted
+Rule 18 deleted
+Rule 16 deleted
+Rule 12 deleted
+Rule 11 deleted
+Rule 7 deleted
+23 : C*B = B*C
+24 : C*(A*(C*(A*v1))) = v1
+25 : C*(A*(C*(B*A))) = B
+26 : C*(B*(C*v1)) = B*v1
+27 : C*(A*(C*A)) = U
+28 : C*(B*C) = B
+29 : C*(A*(C*(B*(A*v1)))) = B*v1
+30 : I(I(v2*v1)*v2) = v1
+31 : I(v2*I(v1))*v2 = v1
+32 : I(v4*(v3*v2))*(v4*(v3*(v2*v1))) = v1
+33 : I(v1*A)*(v1*(B*A)) = B
+34 : I(v1*C)*v1 = C
+35 : I(v3*I(v2))*(v3*v1) = v2*v1
+36 : I(v2*A)*(v2*(B*(A*v1))) = B*v1
+37 : I(v2*C)*(v2*v1) = C*v1
+38 : v1*I(v1) = U
+39 : I(C*(A*C))*v1 = A*v1
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+Rule 13 deleted
+42 : I(I(v1)) = v1
+Rule 20 deleted
+43 : C*(B*v1) = B*(C*v1)
+Rule 29 deleted
+Rule 28 deleted
+Rule 26 deleted
+Rule 25 deleted
+44 : A*(C*(A*v1)) = C*v1
+Rule 24 deleted
+45 : A*(C*A) = C
+Rule 27 deleted
+46 : v2*(I(v1*v2)*v1) = U
+47 : I(I(v3*(v2*v1))*(v3*v2)) = v1
+48 : I(I(B*A)*A) = B
+49 : v3*(I(v2*v3)*(v2*v1)) = v1
+50 : I(I(v1)*I(v2)) = v2*v1
+51 : I(I(B*(A*v1))*A) = B*v1
+52 : I(I(v1)*C) = C*v1
+53 : I(v2*I(v1*v2)) = v1
+54 : I(v3*(v2*I(v1)))*(v3*v2) = v1
+55 : I(v1*(C*(A*C)))*v1 = A
+56 : v2*I(I(v1)*v2) = v1
+57 : I(v2*(I(v3*v1)*v3))*v2 = v1
+58 : I(v5*(v4*(v3*v2)))*(v5*(v4*(v3*(v2*v1)))) = v1
+59 : I(v2*(v1*A))*(v2*(v1*(B*A))) = B
+60 : I(v2*(v1*C))*(v2*v1) = C
+61 : I(v4*(v3*I(v2)))*(v4*(v3*v1)) = v2*v1
+62 : I(v3*(v2*A))*(v3*(v2*(B*(A*v1)))) = B*v1
+63 : I(v3*(v2*C))*(v3*(v2*v1)) = C*v1
+64 : I(v3*(I(v4*v2)*v4))*(v3*v1) = v2*v1
+65 : v4*(I(v3*(v2*v4))*(v3*(v2*v1))) = v1
+66 : I(I(B)*A)*A = B
+67 : I(A*A)*(B*(A*A)) = B
+68 : v1*(I(A*v1)*(B*A)) = B
+69 : I(I(v1*A)*(v1*B))*B = A
+70 : v1*I(C*v1) = C
+71 : I(A*I(v1))*(B*A) = v1*B
+72 : I(C*I(v1)) = v1*C
+73 : I(v2*(C*(A*C)))*(v2*v1) = A*v1
+74 : I(A*I(v2))*(B*(A*v1)) = v2*(B*v1)
+75 : v3*(I(I(v2)*v3)*v1) = v2*v1
+76 : I(I(B*I(v1))*A)*(v1*A) = B
+77 : I(v1*A)*(v1*(B*(B*A))) = B*B
+78 : I(I(B)*A)*(A*v1) = B*v1
+79 : I(A*A)*(B*(A*(A*v1))) = B*v1
+80 : I(v2*A)*(v2*(B*(B*(A*v1)))) = B*(B*v1)
+81 : v2*(I(A*v2)*(B*(A*v1))) = B*v1
+82 : I(I(v2*A)*(v2*B))*(B*v1) = A*v1
+83 : I(I(B*I(v2))*A)*(v2*(A*v1)) = B*v1
+84 : I(A*C)*(B*A) = B*C
+85 : I(A*C)*(B*(A*v1)) = B*(C*v1)
+86 : v2*(I(C*v2)*v1) = C*v1
+87 : I(I(B*C)*A)*(C*A) = B
+88 : I(I(B*C)*A)*(C*(A*v1)) = B*v1
+89 : v2*(v1*I(v2*v1)) = U
+90 : B*(A*I(B)) = A
+91 : I(v2*v1)*v2 = I(v1)
+Rule 64 deleted
+Rule 57 deleted
+Rule 55 deleted
+Rule 46 deleted
+Rule 34 deleted
+Rule 31 deleted
+Rule 30 deleted
+92 : I(C*(A*C)) = A
+Rule 39 deleted
+93 : I(v3*(v2*v1))*(v3*v2) = I(v1)
+Rule 60 deleted
+Rule 54 deleted
+Rule 47 deleted
+94 : I(v1*I(v2)) = v2*I(v1)
+Rule 83 deleted
+Rule 76 deleted
+Rule 74 deleted
+Rule 72 deleted
+Rule 71 deleted
+Rule 53 deleted
+Rule 50 deleted
+Rule 35 deleted
+95 : I(v2*(I(B)*A))*(v2*(A*v1)) = B*v1
+96 : I(v1*(I(B)*A))*(v1*A) = B
+97 : I(v1*A)*(v1*B) = B*(C*(A*C))
+Rule 82 deleted
+Rule 69 deleted
+98 : I(v1*C) = C*I(v1)
+Rule 88 deleted
+Rule 87 deleted
+Rule 85 deleted
+Rule 84 deleted
+Rule 52 deleted
+Rule 37 deleted
+99 : v3*(v2*(I(v3*v2)*v1)) = v1
+100 : B*(A*(I(B)*v1)) = A*v1
+101 : I(v3*v2)*(v3*v1) = I(v2)*v1
+Rule 97 deleted
+Rule 96 deleted
+Rule 95 deleted
+Rule 93 deleted
+Rule 80 deleted
+Rule 77 deleted
+Rule 73 deleted
+Rule 65 deleted
+Rule 63 deleted
+Rule 62 deleted
+Rule 61 deleted
+Rule 59 deleted
+Rule 58 deleted
+Rule 49 deleted
+Rule 36 deleted
+Rule 33 deleted
+Rule 32 deleted
+Rule 15 deleted
+102 : B*(C*I(B)) = C
+103 : B*(C*(I(B)*v1)) = C*v1
+104 : B*(I(B*A)*A) = U
+105 : B*(I(B*A)*(A*v1)) = v1
+106 : I(B*A)*A = I(B)
+Rule 104 deleted
+Rule 48 deleted
+107 : B*(v1*(I(B*(A*v1))*A)) = U
+108 : I(I(B*(B*A))*A) = B*B
+109 : B*(v2*(I(B*(A*v2))*(A*v1))) = v1
+110 : I(I(B*(B*(A*v1)))*A) = B*(B*v1)
+111 : I(I(B)*A) = B*(C*(A*C))
+Rule 78 deleted
+Rule 66 deleted
+112 : I(I(B*v1)*A) = B*(C*(A*(C*v1)))
+Rule 110 deleted
+Rule 108 deleted
+Rule 51 deleted
+113 : v3*(v2*I(I(v1)*(v3*v2))) = v1
+114 : v1*I(C*(A*(C*v1))) = A
+115 : I(I(v1)*v2) = I(v2)*v1
+Rule 113 deleted
+Rule 112 deleted
+Rule 111 deleted
+Rule 75 deleted
+Rule 56 deleted
+116 : v2*(v1*(I(A*(v2*v1))*(B*A))) = B
+117 : I(A*v1)*(B*A) = I(v1)*B
+Rule 116 deleted
+Rule 68 deleted
+118 : v2*(v1*I(C*(v2*v1))) = C
+119 : I(C*v1) = I(v1)*C
+Rule 118 deleted
+Rule 114 deleted
+Rule 92 deleted
+Rule 86 deleted
+Rule 70 deleted
+120 : v1*(I(A*(C*v1))*C) = A
+121 : I(A*A)*(B*(B*(A*A))) = B*B
+122 : I(A*A)*(B*(B*(A*(A*v1)))) = B*(B*v1)
+123 : I(A*A)*(B*(A*v1)) = B*(C*(A*(C*v1)))
+Rule 79 deleted
+Rule 67 deleted
+124 : v3*(v2*(I(A*(v3*v2))*(B*(A*v1)))) = B*v1
+125 : v1*(I(A*v1)*(B*(B*A))) = B*B
+126 : I(A*v2)*(B*(A*v1)) = I(v2)*(B*v1)
+Rule 124 deleted
+Rule 123 deleted
+Rule 81 deleted
+127 : v3*(v2*(v1*I(v3*(v2*v1)))) = U
+128 : v2*I(v1*v2) = I(v1)
+Rule 89 deleted
+129 : A*I(B) = I(B)*A
+Rule 90 deleted
+130 : I(v1*v2) = I(v2)*I(v1)
+Rule 128 deleted
+Rule 127 deleted
+Rule 126 deleted
+Rule 125 deleted
+Rule 122 deleted
+Rule 121 deleted
+Rule 120 deleted
+Rule 119 deleted
+Rule 117 deleted
+Rule 115 deleted
+Rule 109 deleted
+Rule 107 deleted
+Rule 106 deleted
+Rule 105 deleted
+Rule 101 deleted
+Rule 99 deleted
+Rule 98 deleted
+Rule 94 deleted
+Rule 91 deleted
+131 : B*(C*(A*(C*(I(B)*(A*v1))))) = v1
+132 : B*(C*(A*(C*(I(B)*A)))) = U
+133 : C*(A*(C*(I(B)*A))) = I(B)
+Rule 132 deleted
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+Rule 100 deleted
+135 : C*I(B) = I(B)*C
+Rule 102 deleted
+136 : C*(I(B)*v1) = I(B)*(C*v1)
+Rule 133 deleted
+Rule 131 deleted
+Rule 103 deleted
+Canonical set found :
+1 : U*v1 = v1
+2 : I(v1)*v1 = U
+3 : (v3*v2)*v1 = v3*(v2*v1)
+4 : A*B = B*A
+5 : C*C = U
+6 : I(A) = C*(A*C)
+8 : I(v2)*(v2*v1) = v1
+9 : A*(B*v1) = B*(A*v1)
+10 : C*(C*v1) = v1
+21 : v1*U = v1
+22 : I(C) = C
+23 : C*B = B*C
+38 : v1*I(v1) = U
+40 : v2*(I(v2)*v1) = v1
+41 : I(U) = U
+42 : I(I(v1)) = v1
+43 : C*(B*v1) = B*(C*v1)
+44 : A*(C*(A*v1)) = C*v1
+45 : A*(C*A) = C
+129 : A*I(B) = I(B)*A
+130 : I(v1*v2) = I(v2)*I(v1)
+134 : A*(I(B)*v1) = I(B)*(A*v1)
+135 : C*I(B) = I(B)*C
+136 : C*(I(B)*v1) = I(B)*(C*v1)
diff --git a/testsuite/tests/misc-kb/orderings.ml b/testsuite/tests/misc-kb/orderings.ml
new file mode 100644
index 0000000000..488f870373
--- /dev/null
+++ b/testsuite/tests/misc-kb/orderings.ml
@@ -0,0 +1,96 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(*********************** Recursive Path Ordering ****************************)
+
+open Terms
+
+type ordering =
+ Greater
+ | Equal
+ | NotGE
+
+let ge_ord order pair = match order pair with NotGE -> false | _ -> true
+and gt_ord order pair = match order pair with Greater -> true | _ -> false
+and eq_ord order pair = match order pair with Equal -> true | _ -> false
+
+
+let rec rem_eq equiv x = function
+ [] -> failwith "rem_eq"
+ | y::l -> if equiv (x,y) then l else y :: rem_eq equiv x l
+
+
+let diff_eq equiv (x,y) =
+ let rec diffrec = function
+ ([],_) as p -> p
+ | (h::t, y) -> try
+ diffrec (t, rem_eq equiv h y)
+ with Failure _ ->
+ let (x',y') = diffrec (t,y) in (h::x',y') in
+ if List.length x > List.length y then diffrec(y,x) else diffrec(x,y)
+
+
+(* Multiset extension of order *)
+
+let mult_ext order = function
+ Term(_,sons1), Term(_,sons2) ->
+ begin match diff_eq (eq_ord order) (sons1,sons2) with
+ ([],[]) -> Equal
+ | (l1,l2) ->
+ if List.for_all
+ (fun n -> List.exists (fun m -> gt_ord order (m,n)) l1) l2
+ then Greater else NotGE
+ end
+ | _ -> failwith "mult_ext"
+
+
+(* Lexicographic extension of order *)
+
+let lex_ext order = function
+ (Term(_,sons1) as m), (Term(_,sons2) as n) ->
+ let rec lexrec = function
+ ([] , []) -> Equal
+ | ([] , _ ) -> NotGE
+ | ( _ , []) -> Greater
+ | (x1::l1, x2::l2) ->
+ match order (x1,x2) with
+ Greater -> if List.for_all (fun n' -> gt_ord order (m,n')) l2
+ then Greater else NotGE
+ | Equal -> lexrec (l1,l2)
+ | NotGE -> if List.exists (fun m' -> ge_ord order (m',n)) l1
+ then Greater else NotGE in
+ lexrec (sons1, sons2)
+ | _ -> failwith "lex_ext"
+
+
+(* Recursive path ordering *)
+
+let rpo op_order ext =
+ let rec rporec (m,n) =
+ if m = n then Equal else
+ match m with
+ Var vm -> NotGE
+ | Term(op1,sons1) ->
+ match n with
+ Var vn ->
+ if occurs vn m then Greater else NotGE
+ | Term(op2,sons2) ->
+ match (op_order op1 op2) with
+ Greater ->
+ if List.for_all (fun n' -> gt_ord rporec (m,n')) sons2
+ then Greater else NotGE
+ | Equal ->
+ ext rporec (m,n)
+ | NotGE ->
+ if List.exists (fun m' -> ge_ord rporec (m',n)) sons1
+ then Greater else NotGE
+ in rporec
diff --git a/testsuite/tests/misc-kb/orderings.mli b/testsuite/tests/misc-kb/orderings.mli
new file mode 100644
index 0000000000..d67e3796d6
--- /dev/null
+++ b/testsuite/tests/misc-kb/orderings.mli
@@ -0,0 +1,29 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Terms
+
+type ordering =
+ Greater
+ | Equal
+ | NotGE
+
+val ge_ord: ('a -> ordering) -> 'a -> bool
+val gt_ord: ('a -> ordering) -> 'a -> bool
+val eq_ord: ('a -> ordering) -> 'a -> bool
+val rem_eq: ('a * 'b -> bool) -> 'a -> 'b list -> 'b list
+val diff_eq: ('a * 'a -> bool) -> 'a list * 'a list -> 'a list * 'a list
+val mult_ext: (term * term -> ordering) -> term * term -> ordering
+val lex_ext: (term * term -> ordering) -> term * term -> ordering
+val rpo: (string -> string -> ordering) ->
+ ((term * term -> ordering) -> term * term -> ordering) ->
+ term * term -> ordering
diff --git a/testsuite/tests/misc-kb/terms.ml b/testsuite/tests/misc-kb/terms.ml
new file mode 100644
index 0000000000..b490c81fa4
--- /dev/null
+++ b/testsuite/tests/misc-kb/terms.ml
@@ -0,0 +1,133 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(****************** Term manipulations *****************)
+
+type term =
+ Var of int
+ | Term of string * term list
+
+let rec union l1 l2 =
+ match l1 with
+ [] -> l2
+ | a::r -> if List.mem a l2 then union r l2 else a :: union r l2
+
+
+let rec vars = function
+ Var n -> [n]
+ | Term(_,l) -> vars_of_list l
+and vars_of_list = function
+ [] -> []
+ | t::r -> union (vars t) (vars_of_list r)
+
+
+let rec substitute subst = function
+ Term(oper,sons) -> Term(oper, List.map (substitute subst) sons)
+ | Var(n) as t -> try List.assoc n subst with Not_found -> t
+
+
+(* Term replacement: replace M u N is M[u<-N]. *)
+
+let rec replace m u n =
+ match (u, m) with
+ [], _ -> n
+ | i::u, Term(oper, sons) -> Term(oper, replace_nth i sons u n)
+ | _ -> failwith "replace"
+
+and replace_nth i sons u n =
+ match sons with
+ s::r -> if i = 1
+ then replace s u n :: r
+ else s :: replace_nth (i-1) r u n
+ | [] -> failwith "replace_nth"
+
+
+(* Term matching. *)
+
+let matching term1 term2 =
+ let rec match_rec subst t1 t2 =
+ match (t1, t2) with
+ Var v, _ ->
+ if List.mem_assoc v subst then
+ if t2 = List.assoc v subst then subst else failwith "matching"
+ else
+ (v, t2) :: subst
+ | Term(op1,sons1), Term(op2,sons2) ->
+ if op1 = op2
+ then List.fold_left2 match_rec subst sons1 sons2
+ else failwith "matching"
+ | _ -> failwith "matching" in
+ match_rec [] term1 term2
+
+
+(* A naive unification algorithm. *)
+
+let compsubst subst1 subst2 =
+ (List.map (fun (v,t) -> (v, substitute subst1 t)) subst2) @ subst1
+
+
+let rec occurs n = function
+ Var m -> m = n
+ | Term(_,sons) -> List.exists (occurs n) sons
+
+
+let rec unify term1 term2 =
+ match (term1, term2) with
+ Var n1, _ ->
+ if term1 = term2 then []
+ else if occurs n1 term2 then failwith "unify"
+ else [n1, term2]
+ | term1, Var n2 ->
+ if occurs n2 term1 then failwith "unify"
+ else [n2, term1]
+ | Term(op1,sons1), Term(op2,sons2) ->
+ if op1 = op2 then
+ List.fold_left2 (fun s t1 t2 -> compsubst (unify (substitute s t1)
+ (substitute s t2)) s)
+ [] sons1 sons2
+ else failwith "unify"
+
+
+(* We need to print terms with variables independently from input terms
+ obtained by parsing. We give arbitrary names v1,v2,... to their variables.
+*)
+
+let infixes = ["+";"*"]
+
+let rec pretty_term = function
+ Var n ->
+ print_string "v"; print_int n
+ | Term (oper,sons) ->
+ if List.mem oper infixes then begin
+ match sons with
+ [s1;s2] ->
+ pretty_close s1; print_string oper; pretty_close s2
+ | _ ->
+ failwith "pretty_term : infix arity <> 2"
+ end else begin
+ print_string oper;
+ match sons with
+ [] -> ()
+ | t::lt -> print_string "(";
+ pretty_term t;
+ List.iter (fun t -> print_string ","; pretty_term t) lt;
+ print_string ")"
+ end
+
+and pretty_close = function
+ Term(oper, _) as m ->
+ if List.mem oper infixes then begin
+ print_string "("; pretty_term m; print_string ")"
+ end else
+ pretty_term m
+ | m ->
+ pretty_term m
diff --git a/testsuite/tests/misc-kb/terms.mli b/testsuite/tests/misc-kb/terms.mli
new file mode 100644
index 0000000000..aa1dd2cdce
--- /dev/null
+++ b/testsuite/tests/misc-kb/terms.mli
@@ -0,0 +1,29 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type term =
+ Var of int
+ | Term of string * term list
+
+val union: 'a list -> 'a list -> 'a list
+val vars: term -> int list
+val vars_of_list: term list -> int list
+val substitute: (int * term) list -> term -> term
+val replace: term -> int list -> term -> term
+val replace_nth: int -> term list -> int list -> term -> term list
+val matching: term -> term -> (int * term) list
+val compsubst: (int * term) list -> (int * term) list -> (int * term) list
+val occurs: int -> term -> bool
+val unify: term -> term -> (int * term) list
+val infixes: string list
+val pretty_term: term -> unit
+val pretty_close: term -> unit
diff --git a/testsuite/tests/misc-unsafe/Makefile b/testsuite/tests/misc-unsafe/Makefile
new file mode 100644
index 0000000000..4a70866f6d
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+UNSAFE=ON
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/misc-unsafe/almabench.ml b/testsuite/tests/misc-unsafe/almabench.ml
new file mode 100644
index 0000000000..2fe54177e6
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/almabench.ml
@@ -0,0 +1,325 @@
+(*
+ * ALMABENCH 1.0.1
+ * OCaml version
+ *
+ * A number-crunching benchmark designed for cross-language and vendor
+ * comparisons.
+ *
+ * Written by Shawn Wagner, from Scott Robert Ladd's versions for
+ * C++ and java.
+ *
+ * No rights reserved. This is public domain software, for use by anyone.
+ *
+ * This program calculates the daily ephemeris (at noon) for the years
+ * 2000-2099 using an algorithm developed by J.L. Simon, P. Bretagnon, J.
+ * Chapront, M. Chapront-Touze, G. Francou and J. Laskar of the Bureau des
+ * Longitudes, Paris, France), as detailed in Astronomy & Astrophysics
+ * 282, 663 (1994)
+ *
+ * Note that the code herein is design for the purpose of testing
+ * computational performance; error handling and other such "niceties"
+ * is virtually non-existent.
+ *
+ * Actual (and oft-updated) benchmark results can be found at:
+ * http://www.coyotegulch.com
+ *
+ * Please do not use this information or algorithm in any way that might
+ * upset the balance of the universe or otherwise cause planets to impact
+ * upon one another.
+ *)
+
+let pic = 3.14159265358979323846
+and j2000 = 2451545.0
+and jcentury = 36525.0
+and jmillenia = 365250.0
+
+let twopi = 2.0 *. pic
+and a2r = pic /. 648000.0
+and r2h = 12.0 /. pic
+and r2d = 180.0 /. pic
+and gaussk = 0.01720209895
+
+(* number of days to include in test *)
+let test_loops = 5 (* was: 20 *)
+and test_length = 36525
+
+(* sin and cos of j2000 mean obliquity (iau 1976) *)
+and sineps = 0.3977771559319137
+and coseps = 0.9174820620691818
+
+and amas = [| 6023600.0; 408523.5; 328900.5; 3098710.0;
+ 1047.355; 3498.5; 22869.0; 19314.0 |]
+
+(*
+ * tables giving the mean keplerian elements, limited to t**2 terms:
+ * a semi-major axis (au)
+ * dlm mean longitude (degree and arcsecond)
+ * e eccentricity
+ * pi longitude of the perihelion (degree and arcsecond)
+ * dinc inclination (degree and arcsecond)
+ * omega longitude of the ascending node (degree and arcsecond)
+ *)
+and a = [|
+ [| 0.3870983098; 0.0; 0.0 |];
+ [| 0.7233298200; 0.0; 0.0 |];
+ [| 1.0000010178; 0.0; 0.0 |];
+ [| 1.5236793419; 3e-10; 0.0 |];
+ [| 5.2026032092; 19132e-10; -39e-10 |];
+ [| 9.5549091915; -0.0000213896; 444e-10 |];
+ [| 19.2184460618; -3716e-10; 979e-10 |];
+ [| 30.1103868694; -16635e-10; 686e-10 |] |]
+
+and dlm =
+ [| [| 252.25090552; 5381016286.88982; -1.92789 |];
+ [| 181.97980085; 2106641364.33548; 0.59381 |];
+ [| 100.46645683; 1295977422.83429; -2.04411 |];
+ [| 355.43299958; 689050774.93988; 0.94264 |];
+ [| 34.35151874; 109256603.77991; -30.60378 |];
+ [| 50.07744430; 43996098.55732; 75.61614 |];
+ [| 314.05500511; 15424811.93933; -1.75083 |];
+ [| 304.34866548; 7865503.20744; 0.21103 |] |]
+
+and e =
+ [| [| 0.2056317526; 0.0002040653; -28349e-10 |];
+ [| 0.0067719164; -0.0004776521; 98127e-10 |];
+ [| 0.0167086342; -0.0004203654; -0.0000126734 |];
+ [| 0.0934006477; 0.0009048438; -80641e-10 |];
+ [| 0.0484979255; 0.0016322542; -0.0000471366 |];
+ [| 0.0555481426; -0.0034664062; -0.0000643639 |];
+ [| 0.0463812221; -0.0002729293; 0.0000078913 |];
+ [| 0.0094557470; 0.0000603263; 0.0 |] |]
+
+and pi =
+ [| [| 77.45611904; 5719.11590; -4.83016 |];
+ [| 131.56370300; 175.48640; -498.48184 |];
+ [| 102.93734808; 11612.35290; 53.27577 |];
+ [| 336.06023395; 15980.45908; -62.32800 |];
+ [| 14.33120687; 7758.75163; 259.95938 |];
+ [| 93.05723748; 20395.49439; 190.25952 |];
+ [| 173.00529106; 3215.56238; -34.09288 |];
+ [| 48.12027554; 1050.71912; 27.39717 |] |]
+and dinc =
+ [| [| 7.00498625; -214.25629; 0.28977 |];
+ [| 3.39466189; -30.84437; -11.67836 |];
+ [| 0.0; 469.97289; -3.35053 |];
+ [| 1.84972648; -293.31722; -8.11830 |];
+ [| 1.30326698; -71.55890; 11.95297 |];
+ [| 2.48887878; 91.85195; -17.66225 |];
+ [| 0.77319689; -60.72723; 1.25759 |];
+ [| 1.76995259; 8.12333; 0.08135 |] |]
+
+and omega =
+ [| [| 48.33089304; -4515.21727; -31.79892 |];
+ [| 76.67992019; -10008.48154; -51.32614 |];
+ [| 174.87317577; -8679.27034; 15.34191 |];
+ [| 49.55809321; -10620.90088; -230.57416 |];
+ [| 100.46440702; 6362.03561; 326.52178 |];
+ [| 113.66550252; -9240.19942; -66.23743 |];
+ [| 74.00595701; 2669.15033; 145.93964 |];
+ [| 131.78405702; -221.94322; -0.78728 |] |]
+
+(* tables for trigonometric terms to be added to the mean elements
+ of the semi-major axes. *)
+and kp =
+ [| [| 69613.0; 75645.0; 88306.0; 59899.0; 15746.0; 71087.0; 142173.0; 3086.0; 0.0 |];
+ [| 21863.0; 32794.0; 26934.0; 10931.0; 26250.0; 43725.0; 53867.0; 28939.0; 0.0 |];
+ [| 16002.0; 21863.0; 32004.0; 10931.0; 14529.0; 16368.0; 15318.0; 32794.0; 0.0 |];
+ [| 6345.0; 7818.0; 15636.0; 7077.0; 8184.0; 14163.0; 1107.0; 4872.0; 0.0 |];
+ [| 1760.0; 1454.0; 1167.0; 880.0; 287.0; 2640.0; 19.0; 2047.0; 1454.0 |];
+ [| 574.0; 0.0; 880.0; 287.0; 19.0; 1760.0; 1167.0; 306.0; 574.0 |];
+ [| 204.0; 0.0; 177.0; 1265.0; 4.0; 385.0; 200.0; 208.0; 204.0 |];
+ [| 0.0; 102.0; 106.0; 4.0; 98.0; 1367.0; 487.0; 204.0; 0.0 |] |]
+
+and ca =
+ [| [| 4.0; -13.0; 11.0; -9.0; -9.0; -3.0; -1.0; 4.0; 0.0 |];
+ [| -156.0; 59.0; -42.0; 6.0; 19.0; -20.0; -10.0; -12.0; 0.0 |];
+ [| 64.0; -152.0; 62.0; -8.0; 32.0; -41.0; 19.0; -11.0; 0.0 |];
+ [| 124.0; 621.0; -145.0; 208.0; 54.0; -57.0; 30.0; 15.0; 0.0 |];
+ [| -23437.0; -2634.0; 6601.0; 6259.0; -1507.0; -1821.0; 2620.0; -2115.0;-1489.0 |];
+ [| 62911.0;-119919.0; 79336.0; 17814.0;-24241.0; 12068.0; 8306.0; -4893.0; 8902.0 |];
+ [| 389061.0;-262125.0;-44088.0; 8387.0;-22976.0; -2093.0; -615.0; -9720.0; 6633.0 |];
+ [| -412235.0;-157046.0;-31430.0; 37817.0; -9740.0; -13.0; -7449.0; 9644.0; 0.0 |] |]
+
+and sa =
+ [| [| -29.0; -1.0; 9.0; 6.0; -6.0; 5.0; 4.0; 0.0; 0.0 |];
+ [| -48.0; -125.0; -26.0; -37.0; 18.0; -13.0; -20.0; -2.0; 0.0 |];
+ [| -150.0; -46.0; 68.0; 54.0; 14.0; 24.0; -28.0; 22.0; 0.0 |];
+ [| -621.0; 532.0; -694.0; -20.0; 192.0; -94.0; 71.0; -73.0; 0.0 |];
+ [| -14614.0;-19828.0; -5869.0; 1881.0; -4372.0; -2255.0; 782.0; 930.0; 913.0 |];
+ [| 139737.0; 0.0; 24667.0; 51123.0; -5102.0; 7429.0; -4095.0; -1976.0;-9566.0 |];
+ [| -138081.0; 0.0; 37205.0;-49039.0;-41901.0;-33872.0;-27037.0;-12474.0;18797.0 |];
+ [| 0.0; 28492.0;133236.0; 69654.0; 52322.0;-49577.0;-26430.0; -3593.0; 0.0 |] |]
+
+(* tables giving the trigonometric terms to be added to the mean elements of
+ the mean longitudes . *)
+and kq =
+ [| [| 3086.0; 15746.0; 69613.0; 59899.0; 75645.0; 88306.0; 12661.0; 2658.0; 0.0; 0.0 |];
+ [| 21863.0; 32794.0; 10931.0; 73.0; 4387.0; 26934.0; 1473.0; 2157.0; 0.0; 0.0 |];
+ [| 10.0; 16002.0; 21863.0; 10931.0; 1473.0; 32004.0; 4387.0; 73.0; 0.0; 0.0 |];
+ [| 10.0; 6345.0; 7818.0; 1107.0; 15636.0; 7077.0; 8184.0; 532.0; 10.0; 0.0 |];
+ [| 19.0; 1760.0; 1454.0; 287.0; 1167.0; 880.0; 574.0; 2640.0; 19.0;1454.0 |];
+ [| 19.0; 574.0; 287.0; 306.0; 1760.0; 12.0; 31.0; 38.0; 19.0; 574.0 |];
+ [| 4.0; 204.0; 177.0; 8.0; 31.0; 200.0; 1265.0; 102.0; 4.0; 204.0 |];
+ [| 4.0; 102.0; 106.0; 8.0; 98.0; 1367.0; 487.0; 204.0; 4.0; 102.0 |] |]
+
+and cl =
+ [| [| 21.0; -95.0; -157.0; 41.0; -5.0; 42.0; 23.0; 30.0; 0.0; 0.0 |];
+ [| -160.0; -313.0; -235.0; 60.0; -74.0; -76.0; -27.0; 34.0; 0.0; 0.0 |];
+ [| -325.0; -322.0; -79.0; 232.0; -52.0; 97.0; 55.0; -41.0; 0.0; 0.0 |];
+ [| 2268.0; -979.0; 802.0; 602.0; -668.0; -33.0; 345.0; 201.0; -55.0; 0.0 |];
+ [| 7610.0; -4997.0;-7689.0;-5841.0;-2617.0; 1115.0; -748.0; -607.0; 6074.0; 354.0 |];
+ [| -18549.0; 30125.0;20012.0; -730.0; 824.0; 23.0; 1289.0; -352.0;-14767.0;-2062.0 |];
+ [| -135245.0;-14594.0; 4197.0;-4030.0;-5630.0;-2898.0; 2540.0; -306.0; 2939.0; 1986.0 |];
+ [| 89948.0; 2103.0; 8963.0; 2695.0; 3682.0; 1648.0; 866.0; -154.0; -1963.0; -283.0 |] |]
+
+and sl =
+ [| [| -342.0; 136.0; -23.0; 62.0; 66.0; -52.0; -33.0; 17.0; 0.0; 0.0 |];
+ [| 524.0; -149.0; -35.0; 117.0; 151.0; 122.0; -71.0; -62.0; 0.0; 0.0 |];
+ [| -105.0; -137.0; 258.0; 35.0; -116.0; -88.0; -112.0; -80.0; 0.0; 0.0 |];
+ [| 854.0; -205.0; -936.0; -240.0; 140.0; -341.0; -97.0; -232.0; 536.0; 0.0 |];
+ [| -56980.0; 8016.0; 1012.0; 1448.0;-3024.0;-3710.0; 318.0; 503.0; 3767.0; 577.0 |];
+ [| 138606.0;-13478.0;-4964.0; 1441.0;-1319.0;-1482.0; 427.0; 1236.0; -9167.0;-1918.0 |];
+ [| 71234.0;-41116.0; 5334.0;-4935.0;-1848.0; 66.0; 434.0;-1748.0; 3780.0; -701.0 |];
+ [| -47645.0; 11647.0; 2166.0; 3194.0; 679.0; 0.0; -244.0; -419.0; -2531.0; 48.0 |] |]
+
+
+(* Normalize angle into the range -pi <= A < +pi. *)
+let anpm a =
+ let w = mod_float a twopi in
+ if abs_float w >= pic then begin
+ if a < 0.0 then
+ w +. twopi
+ else
+ w -. twopi
+ end else
+ w
+
+(* The reference frame is equatorial and is with respect to the
+ * mean equator and equinox of epoch j2000. *)
+let planetpv epoch np pv =
+ (* time: julian millennia since j2000. *)
+ let t = ((epoch.(0) -. j2000) +. epoch.(1)) /. jmillenia in
+ (* compute the mean elements. *)
+ let da = ref (a.(np).(0) +. (a.(np).(1) +. a.(np).(2) *. t ) *. t)
+ and dl = ref ((3600.0 *. dlm.(np).(0) +. (dlm.(np).(1) +. dlm.(np).(2) *. t ) *. t) *. a2r)
+ and de = e.(np).(0) +. (e.(np).(1) +. e.(np).(2) *. t ) *. t
+ and dp = anpm ((3600.0 *. pi.(np).(0) +. (pi.(np).(1) +. pi.(np).(2) *. t ) *. t ) *. a2r )
+ and di = (3600.0 *. dinc.(np).(0) +. (dinc.(np).(1) +. dinc.(np).(2) *. t ) *. t ) *. a2r
+ and doh = anpm ((3600.0 *. omega.(np).(0) +. (omega.(np).(1) +. omega.(np).(2) *. t ) *. t ) *. a2r )
+ (* apply the trigonometric terms. *)
+ and dmu = 0.35953620 *. t in
+
+ (* loop invariant *)
+ let kp = kp.(np) and kq = kq.(np) and ca = ca.(np) and sa = sa.(np)
+ and cl = cl.(np) and sl = sl.(np) in
+ for k = 0 to 7 do
+ let arga = kp.(k) *. dmu
+ and argl = kq.(k) *. dmu in
+ da := !da +. (ca.(k) *. cos arga +. sa.(k) *. sin arga) *. 0.0000001;
+ dl := !dl +. (cl.(k) *. cos argl +. sl.(k) *. sin argl) *. 0.0000001
+ done;
+ begin let arga = kp.(8) *. dmu in
+ da := !da +. t *. (ca.(8) *. cos arga +. sa.(8) *. sin arga ) *. 0.0000001;
+ for k = 8 to 9 do
+ let argl = kq.(k) *. dmu in
+ dl := !dl +. t *. ( cl.(k) *. cos argl +. sl.(k) *. sin argl ) *. 0.0000001
+ done;
+ end;
+
+
+ dl := mod_float !dl twopi;
+
+ (* iterative solution of kepler's equation to get eccentric anomaly. *)
+ let am = !dl -. dp in
+ let ae = ref (am +. de *. sin am)
+ and k = ref 0 in
+ let dae = ref ((am -. !ae +. de *. sin !ae) /. (1.0 -. de *. cos !ae)) in
+ ae := !ae +. !dae;
+ incr k;
+ while !k < 10 or abs_float !dae >= 1e-12 do
+ dae := (am -. !ae +. de *. sin !ae) /. (1.0 -. de *. cos !ae);
+ ae := !ae +. !dae;
+ incr k
+ done;
+
+ (* true anomaly. *)
+ let ae2 = !ae /. 2.0 in
+ let at = 2.0 *. atan2 (sqrt ((1.0 +. de) /. (1.0 -. de)) *. sin ae2) (cos ae2)
+ (* distance (au) and speed (radians per day). *)
+ and r = !da *. (1.0 -. de *. cos !ae)
+ and v = gaussk *. sqrt ((1.0 +. 1.0 /. amas.(np) ) /. (!da *. !da *. !da))
+ and si2 = sin (di /. 2.0) in
+ let xq = si2 *. cos doh
+ and xp = si2 *. sin doh
+ and tl = at +. dp in
+ let xsw = sin tl
+ and xcw = cos tl in
+ let xm2 = 2.0 *. (xp *. xcw -. xq *. xsw )
+ and xf = !da /. sqrt (1.0 -. de *. de)
+ and ci2 = cos (di /. 2.0) in
+ let xms = (de *. sin dp +. xsw) *. xf
+ and xmc = (de *. cos dp +. xcw) *. xf
+ and xpxq2 = 2.0 *. xp *. xq in
+
+ (* position (j2000 ecliptic x,y,z in au). *)
+ let x = r *. (xcw -. xm2 *. xp)
+ and y = r *. (xsw +. xm2 *. xq)
+ and z = r *. (-.xm2 *. ci2) in
+
+ (* rotate to equatorial. *)
+ pv.(0).(0) <- x;
+ pv.(0).(1) <- y *. coseps -. z *. sineps;
+ pv.(0).(2) <- y *. sineps +. z *. coseps;
+
+ (* velocity (j2000 ecliptic xdot,ydot,zdot in au/d). *)
+ let x = v *. ((-1.0 +. 2.0 *. xp *. xp) *. xms +. xpxq2 *. xmc)
+ and y = v *. (( 1.0 -. 2.0 *. xq *. xq ) *. xmc -. xpxq2 *. xms)
+ and z = v *. (2.0 *. ci2 *. (xp *. xms +. xq *. xmc)) in
+
+ (* rotate to equatorial *)
+ pv.(1).(0) <- x;
+ pv.(1).(1) <- y *. coseps -. z *. sineps;
+ pv.(1).(2) <- y *. sineps +. z *. coseps
+
+
+(* Computes RA, Declination, and distance from a state vector returned by
+ * planetpv. *)
+let radecdist state rdd =
+ (* Distance *)
+ rdd.(2) <- sqrt (state.(0).(0) *. state.(0).(0)
+ +. state.(0).(1) *. state.(0).(1)
+ +. state.(0).(2) *. state.(0).(2));
+ (* RA *)
+ rdd.(0) <- atan2 state.(0).(1) state.(0).(0) *. r2h;
+ if rdd.(0) < 0.0 then rdd.(0) <- rdd.(0) +. 24.0;
+
+ (* Declination *)
+ rdd.(1) <- asin (state.(0).(2) /. rdd.(2)) *. r2d
+
+
+
+(* Entry point. Calculate RA and Dec for noon on every day in 1900-2100 *)
+let _ =
+ let jd = [| 0.0; 0.0 |]
+ and pv = [| [| 0.0; 0.0; 0.0 |]; [| 0.0; 0.0; 0.0 |] |]
+ and position = [| 0.0; 0.0; 0.0 |] in
+ (* Test *)
+ jd.(0) <- j2000;
+ jd.(1) <- 1.0;
+ for p = 0 to 7 do
+ planetpv jd p pv;
+ radecdist pv position;
+ Printf.printf "%d %.2f %.2f\n%!" p position.(0) position.(1)
+ done;
+ (* Benchmark *)
+ for i = 0 to test_loops - 1 do
+ jd.(0) <- j2000;
+ jd.(1) <- 0.0;
+ for n = 0 to test_length - 1 do
+ jd.(0) <- jd.(0) +. 1.0;
+ for p = 0 to 7 do
+ planetpv jd p pv;
+ radecdist pv position;
+ done
+ done
+ done
diff --git a/testsuite/tests/misc-unsafe/almabench.reference b/testsuite/tests/misc-unsafe/almabench.reference
new file mode 100644
index 0000000000..5c1d8b89c4
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/almabench.reference
@@ -0,0 +1,8 @@
+0 17.00 -26.06
+1 12.34 1.29
+2 6.83 22.95
+3 0.04 -1.26
+4 2.30 12.54
+5 2.93 14.35
+6 21.27 -16.57
+7 20.41 -19.04
diff --git a/testsuite/tests/misc-unsafe/fft.ml b/testsuite/tests/misc-unsafe/fft.ml
new file mode 100644
index 0000000000..7e2442b0b0
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/fft.ml
@@ -0,0 +1,186 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let pi = 3.14159265358979323846
+
+let tpi = 2.0 *. pi
+
+let fft px py np =
+ let i = ref 2 in
+ let m = ref 1 in
+
+ while (!i < np) do
+ i := !i + !i;
+ m := !m + 1
+ done;
+
+ let n = !i in
+
+ if n <> np then begin
+ for i = np+1 to n do
+ px.(i) <- 0.0;
+ py.(i) <- 0.0
+ done;
+ print_string "Use "; print_int n;
+ print_string " point fft"; print_newline()
+ end;
+
+ let n2 = ref(n+n) in
+ for k = 1 to !m-1 do
+ n2 := !n2 / 2;
+ let n4 = !n2 / 4 in
+ let e = tpi /. float !n2 in
+
+ for j = 1 to n4 do
+ let a = e *. float(j - 1) in
+ let a3 = 3.0 *. a in
+ let cc1 = cos(a) in
+ let ss1 = sin(a) in
+ let cc3 = cos(a3) in
+ let ss3 = sin(a3) in
+ let is = ref j in
+ let id = ref(2 * !n2) in
+
+ while !is < n do
+ let i0r = ref !is in
+ while !i0r < n do
+ let i0 = !i0r in
+ let i1 = i0 + n4 in
+ let i2 = i1 + n4 in
+ let i3 = i2 + n4 in
+ let r1 = px.(i0) -. px.(i2) in
+ px.(i0) <- px.(i0) +. px.(i2);
+ let r2 = px.(i1) -. px.(i3) in
+ px.(i1) <- px.(i1) +. px.(i3);
+ let s1 = py.(i0) -. py.(i2) in
+ py.(i0) <- py.(i0) +. py.(i2);
+ let s2 = py.(i1) -. py.(i3) in
+ py.(i1) <- py.(i1) +. py.(i3);
+ let s3 = r1 -. s2 in
+ let r1 = r1 +. s2 in
+ let s2 = r2 -. s1 in
+ let r2 = r2 +. s1 in
+ px.(i2) <- r1*.cc1 -. s2*.ss1;
+ py.(i2) <- -.s2*.cc1 -. r1*.ss1;
+ px.(i3) <- s3*.cc3 +. r2*.ss3;
+ py.(i3) <- r2*.cc3 -. s3*.ss3;
+ i0r := i0 + !id
+ done;
+ is := 2 * !id - !n2 + j;
+ id := 4 * !id
+ done
+ done
+ done;
+
+(************************************)
+(* Last stage, length=2 butterfly *)
+(************************************)
+
+ let is = ref 1 in
+ let id = ref 4 in
+
+ while !is < n do
+ let i0r = ref !is in
+ while !i0r <= n do
+ let i0 = !i0r in
+ let i1 = i0 + 1 in
+ let r1 = px.(i0) in
+ px.(i0) <- r1 +. px.(i1);
+ px.(i1) <- r1 -. px.(i1);
+ let r1 = py.(i0) in
+ py.(i0) <- r1 +. py.(i1);
+ py.(i1) <- r1 -. py.(i1);
+ i0r := i0 + !id
+ done;
+ is := 2 * !id - 1;
+ id := 4 * !id
+ done;
+
+(*************************)
+(* Bit reverse counter *)
+(*************************)
+
+ let j = ref 1 in
+
+ for i = 1 to n - 1 do
+ if i < !j then begin
+ let xt = px.(!j) in
+ px.(!j) <- px.(i);
+ px.(i) <- xt;
+ let xt = py.(!j) in
+ py.(!j) <- py.(i);
+ py.(i) <- xt
+ end;
+ let k = ref(n / 2) in
+ while !k < !j do
+ j := !j - !k;
+ k := !k / 2
+ done;
+ j := !j + !k
+ done;
+
+ n
+
+
+let test np =
+ print_int np; print_string "... "; flush stdout;
+ let enp = float np in
+ let npm = np / 2 - 1 in
+ let pxr = Array.make (np+2) 0.0
+ and pxi = Array.make (np+2) 0.0 in
+ let t = pi /. enp in
+ pxr.(1) <- (enp -. 1.0) *. 0.5;
+ pxi.(1) <- 0.0;
+ let n2 = np / 2 in
+ pxr.(n2+1) <- -0.5;
+ pxi.(n2+1) <- 0.0;
+
+ for i = 1 to npm do
+ let j = np - i in
+ pxr.(i+1) <- -0.5;
+ pxr.(j+1) <- -0.5;
+ let z = t *. float i in
+ let y = -0.5*.(cos(z)/.sin(z)) in
+ pxi.(i+1) <- y;
+ pxi.(j+1) <- -.y
+ done;
+(**
+ print_newline();
+ for i=0 to 15 do Printf.printf "%d %f %f\n" i pxr.(i+1) pxi.(i+1) done;
+**)
+ let _ = fft pxr pxi np in
+(**
+ for i=0 to 15 do Printf.printf "%d %f %f\n" i pxr.(i+1) pxi.(i+1) done;
+**)
+ let zr = ref 0.0 in
+ let zi = ref 0.0 in
+ let kr = ref 0 in
+ let ki = ref 0 in
+ for i = 0 to np-1 do
+ let a = abs_float(pxr.(i+1) -. float i) in
+ if !zr < a then begin
+ zr := a;
+ kr := i
+ end;
+ let a = abs_float(pxi.(i+1)) in
+ if !zi < a then begin
+ zi := a;
+ ki := i
+ end
+ done;
+ if abs_float !zr <= 1e-9 && abs_float !zi <= 1e-9
+ then print_string "ok"
+ else print_string "ERROR";
+ print_newline()
+
+let _ =
+ let np = ref 16 in for i = 1 to 16 do test !np; np := !np*2 done
diff --git a/testsuite/tests/misc-unsafe/fft.reference b/testsuite/tests/misc-unsafe/fft.reference
new file mode 100644
index 0000000000..b0f1238b85
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/fft.reference
@@ -0,0 +1,16 @@
+16... ok
+32... ok
+64... ok
+128... ok
+256... ok
+512... ok
+1024... ok
+2048... ok
+4096... ok
+8192... ok
+16384... ok
+32768... ok
+65536... ok
+131072... ok
+262144... ok
+524288... ok
diff --git a/testsuite/tests/misc-unsafe/quicksort.ml b/testsuite/tests/misc-unsafe/quicksort.ml
new file mode 100644
index 0000000000..8879d95291
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/quicksort.ml
@@ -0,0 +1,90 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Good test for loops. Best compiled with -unsafe. *)
+
+let rec qsort lo hi (a : int array) =
+ if lo < hi then begin
+ let i = ref lo in
+ let j = ref hi in
+ let pivot = a.(hi) in
+ while !i < !j do
+ while !i < hi && a.(!i) <= pivot do incr i done;
+ while !j > lo && a.(!j) >= pivot do decr j done;
+ if !i < !j then begin
+ let temp = a.(!i) in a.(!i) <- a.(!j); a.(!j) <- temp
+ end
+ done;
+ let temp = a.(!i) in a.(!i) <- a.(hi); a.(hi) <- temp;
+ qsort lo (!i-1) a;
+ qsort (!i+1) hi a
+ end
+
+
+(* Same but abstract over the comparison to force spilling *)
+
+let cmp i j = i - j
+
+let rec qsort2 lo hi (a : int array) =
+ if lo < hi then begin
+ let i = ref lo in
+ let j = ref hi in
+ let pivot = a.(hi) in
+ while !i < !j do
+ while !i < hi && cmp a.(!i) pivot <= 0 do incr i done;
+ while !j > lo && cmp a.(!j) pivot >= 0 do decr j done;
+ if !i < !j then begin
+ let temp = a.(!i) in a.(!i) <- a.(!j); a.(!j) <- temp
+ end
+ done;
+ let temp = a.(!i) in a.(!i) <- a.(hi); a.(hi) <- temp;
+ qsort2 lo (!i-1) a;
+ qsort2 (!i+1) hi a
+ end
+
+
+(* Test *)
+
+let seed = ref 0
+
+let random() =
+ seed := !seed * 25173 + 17431; !seed land 0xFFF
+
+
+exception Failed
+
+let test_sort sort_fun size =
+ let a = Array.make size 0 in
+ let check = Array.make 4096 0 in
+ for i = 0 to size-1 do
+ let n = random() in a.(i) <- n; check.(n) <- check.(n)+1
+ done;
+ sort_fun 0 (size-1) a;
+ try
+ check.(a.(0)) <- check.(a.(0)) - 1;
+ for i = 1 to size-1 do
+ if a.(i-1) > a.(i) then raise Failed;
+ check.(a.(i)) <- check.(a.(i)) - 1
+ done;
+ for i = 0 to 4095 do
+ if check.(i) <> 0 then raise Failed
+ done;
+ print_string "OK"; print_newline()
+ with Failed ->
+ print_string "failed"; print_newline()
+
+
+let main () =
+ test_sort qsort 500000;
+ test_sort qsort2 500000
+
+let _ = main(); exit 0
diff --git a/testsuite/tests/misc-unsafe/quicksort.reference b/testsuite/tests/misc-unsafe/quicksort.reference
new file mode 100644
index 0000000000..2c94e48371
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/quicksort.reference
@@ -0,0 +1,2 @@
+OK
+OK
diff --git a/testsuite/tests/misc-unsafe/soli.ml b/testsuite/tests/misc-unsafe/soli.ml
new file mode 100644
index 0000000000..e4aa721571
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/soli.ml
@@ -0,0 +1,108 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type peg = Out | Empty | Peg
+
+let board = [|
+ [| Out; Out; Out; Out; Out; Out; Out; Out; Out|];
+ [| Out; Out; Out; Peg; Peg; Peg; Out; Out; Out|];
+ [| Out; Out; Out; Peg; Peg; Peg; Out; Out; Out|];
+ [| Out; Peg; Peg; Peg; Peg; Peg; Peg; Peg; Out|];
+ [| Out; Peg; Peg; Peg; Empty; Peg; Peg; Peg; Out|];
+ [| Out; Peg; Peg; Peg; Peg; Peg; Peg; Peg; Out|];
+ [| Out; Out; Out; Peg; Peg; Peg; Out; Out; Out|];
+ [| Out; Out; Out; Peg; Peg; Peg; Out; Out; Out|];
+ [| Out; Out; Out; Out; Out; Out; Out; Out; Out|]
+|]
+
+
+let print_peg = function
+ Out -> print_string "."
+ | Empty -> print_string " "
+ | Peg -> print_string "$"
+
+
+let print_board board =
+ for i=0 to 8 do
+ for j=0 to 8 do
+ print_peg board.(i).(j)
+ done;
+ print_newline()
+ done
+
+
+type direction = { dx: int; dy: int }
+
+let dir = [| {dx = 0; dy = 1}; {dx = 1; dy = 0};
+ {dx = 0; dy = -1}; {dx = -1; dy = 0} |]
+
+type move = { x1: int; y1: int; x2: int; y2: int }
+
+let moves = Array.create 31 {x1=0;y1=0;x2=0;y2=0}
+
+let counter = ref 0
+
+exception Found
+
+let rec solve m =
+ counter := !counter + 1;
+ if m = 31 then
+ begin match board.(4).(4) with Peg -> true | _ -> false end
+ else
+ try
+ if !counter mod 500 = 0 then begin
+ print_int !counter; print_newline()
+ end;
+ for i=1 to 7 do
+ for j=1 to 7 do
+ match board.(i).(j) with
+ Peg ->
+ for k=0 to 3 do
+ let d1 = dir.(k).dx in
+ let d2 = dir.(k).dy in
+ let i1 = i+d1 in
+ let i2 = i1+d1 in
+ let j1 = j+d2 in
+ let j2 = j1+d2 in
+ match board.(i1).(j1) with
+ Peg ->
+ begin match board.(i2).(j2) with
+ Empty ->
+(*
+ print_int i; print_string ", ";
+ print_int j; print_string ") dir ";
+ print_int k; print_string "\n";
+*)
+ board.(i).(j) <- Empty;
+ board.(i1).(j1) <- Empty;
+ board.(i2).(j2) <- Peg;
+ if solve(m+1) then begin
+ moves.(m) <- { x1=i; y1=j; x2=i2; y2=j2 };
+ raise Found
+ end;
+ board.(i).(j) <- Peg;
+ board.(i1).(j1) <- Peg;
+ board.(i2).(j2) <- Empty
+ | _ -> ()
+ end
+ | _ -> ()
+ done
+ | _ ->
+ ()
+ done
+ done;
+ false
+ with Found ->
+ true
+
+
+let _ = if solve 0 then (print_string "\n"; print_board board)
diff --git a/testsuite/tests/misc-unsafe/soli.reference b/testsuite/tests/misc-unsafe/soli.reference
new file mode 100644
index 0000000000..b94045c39f
--- /dev/null
+++ b/testsuite/tests/misc-unsafe/soli.reference
@@ -0,0 +1,50 @@
+500
+1000
+1500
+2000
+2500
+3000
+3500
+4000
+4500
+5000
+5500
+6000
+6500
+7000
+7500
+8000
+8500
+9000
+9500
+10000
+10500
+11000
+11500
+12000
+12500
+13000
+13500
+14000
+14500
+15000
+15500
+16000
+16500
+17000
+17500
+18000
+18500
+19000
+19500
+20000
+
+.........
+... ...
+... ...
+. .
+. $ .
+. .
+... ...
+... ...
+.........
diff --git a/testsuite/tests/misc/Makefile b/testsuite/tests/misc/Makefile
new file mode 100644
index 0000000000..299656b246
--- /dev/null
+++ b/testsuite/tests/misc/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/misc/bdd.ml b/testsuite/tests/misc/bdd.ml
new file mode 100644
index 0000000000..297eb68e45
--- /dev/null
+++ b/testsuite/tests/misc/bdd.ml
@@ -0,0 +1,229 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Translated to OCaml by Xavier Leroy *)
+(* Original code written in SML by ... *)
+
+type bdd = One | Zero | Node of bdd * int * int * bdd
+
+let rec eval bdd vars =
+ match bdd with
+ Zero -> false
+ | One -> true
+ | Node(l, v, _, h) ->
+ if vars.(v) then eval h vars else eval l vars
+
+let getId bdd =
+ match bdd with
+ Node(_,_,id,_) -> id
+ | Zero -> 0
+ | One -> 1
+
+let initSize_1 = 8*1024 - 1
+let nodeC = ref 1
+let sz_1 = ref initSize_1
+let htab = ref(Array.make (!sz_1+1) [])
+let n_items = ref 0
+let hashVal x y v = x lsl 1 + y + v lsl 2
+
+let resize newSize =
+ let arr = !htab in
+ let newSz_1 = newSize-1 in
+ let newArr = Array.make newSize [] in
+ let rec copyBucket bucket =
+ match bucket with
+ [] -> ()
+ | n :: ns ->
+ match n with
+ | Node(l,v,_,h) ->
+ let ind = hashVal (getId l) (getId h) v land newSz_1
+ in
+ newArr.(ind) <- (n :: newArr.(ind));
+ copyBucket ns
+ | _ -> assert false
+ in
+ for n = 0 to !sz_1 do
+ copyBucket(arr.(n))
+ done;
+ htab := newArr;
+ sz_1 := newSz_1
+
+
+let rec insert idl idh v ind bucket newNode =
+ if !n_items <= !sz_1
+ then ( (!htab).(ind) <- (newNode :: bucket);
+ incr n_items )
+ else ( resize(!sz_1 + !sz_1 + 2);
+ let ind = hashVal idl idh v land (!sz_1)
+ in
+ (!htab).(ind) <- newNode :: (!htab).(ind)
+ )
+
+
+let resetUnique () = (
+ sz_1 := initSize_1;
+ htab := Array.make (!sz_1+1) [];
+ n_items := 0;
+ nodeC := 1
+ )
+
+let mkNode low v high =
+ let idl = getId low in
+ let idh = getId high
+ in
+ if idl = idh
+ then low
+ else let ind = hashVal idl idh v land (!sz_1) in
+ let bucket = (!htab).(ind) in
+ let rec lookup b =
+ match b with
+ [] -> let n = Node(low, v, (incr nodeC; !nodeC), high)
+ in
+ insert (getId low) (getId high) v ind bucket n; n
+ | n :: ns ->
+ match n with
+ | Node(l,v',id,h) ->
+ if v = v' && idl = getId l && idh = getId h
+ then n else lookup ns
+ | _ -> assert false
+ in
+ lookup bucket
+
+
+type ordering = LESS | EQUAL | GREATER
+
+let cmpVar (x : int) (y : int) =
+ if x<y then LESS else if x>y then GREATER else EQUAL
+
+let zero = Zero
+let one = One
+
+let mkVar x = mkNode zero x one
+
+
+let cacheSize = 1999
+let andslot1 = Array.make cacheSize 0
+let andslot2 = Array.make cacheSize 0
+let andslot3 = Array.make cacheSize zero
+let xorslot1 = Array.make cacheSize 0
+let xorslot2 = Array.make cacheSize 0
+let xorslot3 = Array.make cacheSize zero
+let notslot1 = Array.make cacheSize 0
+let notslot2 = Array.make cacheSize one
+let hash x y = ((x lsl 1)+y) mod cacheSize
+
+let rec not n =
+match n with
+ Zero -> One
+| One -> Zero
+| Node(l, v, id, r) -> let h = id mod cacheSize
+ in
+ if id=notslot1.(h) then notslot2.(h)
+ else let f = mkNode (not l) v (not r)
+ in
+ notslot1.(h) <- id; notslot2.(h) <- f; f
+
+let rec and2 n1 n2 =
+match n1 with
+ Node(l1, v1, i1, r1)
+ -> (match n2 with
+ Node(l2, v2, i2, r2)
+ -> let h = hash i1 i2
+ in
+ if i1=andslot1.(h) && i2=andslot2.(h) then andslot3.(h)
+ else let f = match cmpVar v1 v2 with
+ EQUAL -> mkNode (and2 l1 l2) v1 (and2 r1 r2)
+ | LESS -> mkNode (and2 l1 n2) v1 (and2 r1 n2)
+ | GREATER -> mkNode (and2 n1 l2) v2 (and2 n1 r2)
+ in
+ andslot1.(h) <- i1;
+ andslot2.(h) <- i2;
+ andslot3.(h) <- f;
+ f
+ | Zero -> Zero
+ | One -> n1)
+| Zero -> Zero
+| One -> n2
+
+
+let rec xor n1 n2 =
+match n1 with
+ Node(l1, v1, i1, r1)
+ -> (match n2 with
+ Node(l2, v2, i2, r2)
+ -> let h = hash i1 i2
+ in
+ if i1=andslot1.(h) && i2=andslot2.(h) then andslot3.(h)
+ else let f = match cmpVar v1 v2 with
+ EQUAL -> mkNode (xor l1 l2) v1 (xor r1 r2)
+ | LESS -> mkNode (xor l1 n2) v1 (xor r1 n2)
+ | GREATER -> mkNode (xor n1 l2) v2 (xor n1 r2)
+ in
+ andslot1.(h) <- i1;
+ andslot2.(h) <- i2;
+ andslot3.(h) <- f;
+ f
+ | Zero -> n1
+ | One -> not n1)
+| Zero -> n2
+| One -> not n2
+
+let hwb n =
+ let rec h i j = if i=j
+ then mkVar i
+ else xor (and2 (not(mkVar j)) (h i (j-1)))
+ (and2 (mkVar j) (g i (j-1)))
+ and g i j = if i=j
+ then mkVar i
+ else xor (and2 (not(mkVar i)) (h (i+1) j))
+ (and2 (mkVar i) (g (i+1) j))
+ in
+ h 0 (n-1)
+
+(* Testing *)
+let seed = ref 0
+
+let random() =
+ seed := !seed * 25173 + 17431; !seed land 1 > 0
+
+let random_vars n =
+ let vars = Array.make n false in
+ for i = 0 to n - 1 do vars.(i) <- random() done;
+ vars
+
+let test_hwb bdd vars =
+ (* We should have
+ eval bdd vars = vars.(n-1) if n > 0
+ eval bdd vars = false if n = 0
+ where n is the number of "true" elements in vars. *)
+ let ntrue = ref 0 in
+ for i = 0 to Array.length vars - 1 do
+ if vars.(i) then incr ntrue
+ done;
+ eval bdd vars = (if !ntrue > 0 then vars.(!ntrue-1) else false)
+
+let main () =
+ let n =
+ if Array.length Sys.argv >= 2 then int_of_string Sys.argv.(1) else 22 in
+ let ntests =
+ if Array.length Sys.argv >= 3 then int_of_string Sys.argv.(2) else 100 in
+ let bdd = hwb n in
+ let succeeded = ref true in
+ for i = 1 to ntests do
+ succeeded := !succeeded && test_hwb bdd (random_vars n)
+ done;
+ if !succeeded
+ then print_string "OK\n"
+ else print_string "FAILED\n";
+ exit 0
+
+let _ = main()
diff --git a/testsuite/tests/misc/bdd.reference b/testsuite/tests/misc/bdd.reference
new file mode 100644
index 0000000000..d86bac9de5
--- /dev/null
+++ b/testsuite/tests/misc/bdd.reference
@@ -0,0 +1 @@
+OK
diff --git a/testsuite/tests/misc/boyer.ml b/testsuite/tests/misc/boyer.ml
new file mode 100644
index 0000000000..09bfd649f0
--- /dev/null
+++ b/testsuite/tests/misc/boyer.ml
@@ -0,0 +1,909 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Manipulations over terms *)
+
+type term =
+ Var of int
+ | Prop of head * term list
+and head =
+ { name: string;
+ mutable props: (term * term) list }
+
+let rec print_term = function
+ Var v ->
+ print_string "v"; print_int v
+ | Prop (head,argl) ->
+ print_string "(";
+ print_string head.name;
+ List.iter (fun t -> print_string " "; print_term t) argl;
+ print_string ")"
+
+let lemmas = ref ([] : head list)
+
+(* Replacement for property lists *)
+
+let get name =
+ let rec get_rec = function
+ hd1::hdl ->
+ if hd1.name = name then hd1 else get_rec hdl
+ | [] ->
+ let entry = {name = name; props = []} in
+ lemmas := entry :: !lemmas;
+ entry
+ in get_rec !lemmas
+
+let add_lemma = function
+ | Prop(_, [(Prop(headl,_) as left); right]) ->
+ headl.props <- (left, right) :: headl.props
+ | _ -> assert false
+
+(* Substitutions *)
+
+type subst = Bind of int * term
+
+let get_binding v list =
+ let rec get_rec = function
+ [] -> failwith "unbound"
+ | Bind(w,t)::rest -> if v = w then t else get_rec rest
+ in get_rec list
+
+let apply_subst alist term =
+ let rec as_rec = function
+ Var v -> begin try get_binding v alist with Failure _ -> term end
+ | Prop (head,argl) -> Prop (head, List.map as_rec argl)
+ in as_rec term
+
+exception Unify
+
+let rec unify term1 term2 =
+ unify1 term1 term2 []
+
+and unify1 term1 term2 unify_subst =
+ match term2 with
+ Var v ->
+ begin try
+ if get_binding v unify_subst = term1
+ then unify_subst
+ else raise Unify
+ with Failure _ ->
+ Bind(v,term1) :: unify_subst
+ end
+ | Prop (head2, argl2) ->
+ match term1 with
+ Var _ -> raise Unify
+ | Prop (head1,argl1) ->
+ if head1 == head2
+ then unify1_lst argl1 argl2 unify_subst
+ else raise Unify
+
+and unify1_lst l1 l2 unify_subst =
+ match (l1, l2) with
+ ([], []) -> unify_subst
+ | (h1::r1, h2::r2) -> unify1_lst r1 r2 (unify1 h1 h2 unify_subst)
+ | _ -> raise Unify
+
+
+let rec rewrite = function
+ Var _ as term -> term
+ | Prop (head, argl) ->
+ rewrite_with_lemmas (Prop (head, List.map rewrite argl)) head.props
+and rewrite_with_lemmas term lemmas =
+ match lemmas with
+ [] ->
+ term
+ | (t1,t2)::rest ->
+ try
+ rewrite (apply_subst (unify term t1) t2)
+ with Unify ->
+ rewrite_with_lemmas term rest
+
+type cterm = CVar of int | CProp of string * cterm list
+
+let rec cterm_to_term = function
+ CVar v -> Var v
+ | CProp(p, l) -> Prop(get p, List.map cterm_to_term l)
+
+let add t = add_lemma (cterm_to_term t)
+
+let _ =
+add (CProp
+("equal",
+ [CProp ("compile",[CVar 5]);
+ CProp
+ ("reverse",
+ [CProp ("codegen",[CProp ("optimize",[CVar 5]); CProp ("nil",[])])])]));
+add (CProp
+("equal",
+ [CProp ("eqp",[CVar 23; CVar 24]);
+ CProp ("equal",[CProp ("fix",[CVar 23]); CProp ("fix",[CVar 24])])]));
+add (CProp
+("equal",
+ [CProp ("gt",[CVar 23; CVar 24]); CProp ("lt",[CVar 24; CVar 23])]));
+add (CProp
+("equal",
+ [CProp ("le",[CVar 23; CVar 24]); CProp ("ge",[CVar 24; CVar 23])]));
+add (CProp
+("equal",
+ [CProp ("ge",[CVar 23; CVar 24]); CProp ("le",[CVar 24; CVar 23])]));
+add (CProp
+("equal",
+ [CProp ("boolean",[CVar 23]);
+ CProp
+ ("or",
+ [CProp ("equal",[CVar 23; CProp ("true",[])]);
+ CProp ("equal",[CVar 23; CProp ("false",[])])])]));
+add (CProp
+("equal",
+ [CProp ("iff",[CVar 23; CVar 24]);
+ CProp
+ ("and",
+ [CProp ("implies",[CVar 23; CVar 24]);
+ CProp ("implies",[CVar 24; CVar 23])])]));
+add (CProp
+("equal",
+ [CProp ("even1",[CVar 23]);
+ CProp
+ ("if",
+ [CProp ("zerop",[CVar 23]); CProp ("true",[]);
+ CProp ("odd",[CProp ("sub1",[CVar 23])])])]));
+add (CProp
+("equal",
+ [CProp ("countps_",[CVar 11; CVar 15]);
+ CProp ("countps_loop",[CVar 11; CVar 15; CProp ("zero",[])])]));
+add (CProp
+("equal",
+ [CProp ("fact_",[CVar 8]);
+ CProp ("fact_loop",[CVar 8; CProp ("one",[])])]));
+add (CProp
+("equal",
+ [CProp ("reverse_",[CVar 23]);
+ CProp ("reverse_loop",[CVar 23; CProp ("nil",[])])]));
+add (CProp
+("equal",
+ [CProp ("divides",[CVar 23; CVar 24]);
+ CProp ("zerop",[CProp ("remainder",[CVar 24; CVar 23])])]));
+add (CProp
+("equal",
+ [CProp ("assume_true",[CVar 21; CVar 0]);
+ CProp ("cons",[CProp ("cons",[CVar 21; CProp ("true",[])]); CVar 0])]));
+add (CProp
+("equal",
+ [CProp ("assume_false",[CVar 21; CVar 0]);
+ CProp ("cons",[CProp ("cons",[CVar 21; CProp ("false",[])]); CVar 0])]));
+add (CProp
+("equal",
+ [CProp ("tautology_checker",[CVar 23]);
+ CProp ("tautologyp",[CProp ("normalize",[CVar 23]); CProp ("nil",[])])]));
+add (CProp
+("equal",
+ [CProp ("falsify",[CVar 23]);
+ CProp ("falsify1",[CProp ("normalize",[CVar 23]); CProp ("nil",[])])]));
+add (CProp
+("equal",
+ [CProp ("prime",[CVar 23]);
+ CProp
+ ("and",
+ [CProp ("not",[CProp ("zerop",[CVar 23])]);
+ CProp
+ ("not",
+ [CProp ("equal",[CVar 23; CProp ("add1",[CProp ("zero",[])])])]);
+ CProp ("prime1",[CVar 23; CProp ("sub1",[CVar 23])])])]));
+add (CProp
+("equal",
+ [CProp ("and",[CVar 15; CVar 16]);
+ CProp
+ ("if",
+ [CVar 15;
+ CProp ("if",[CVar 16; CProp ("true",[]); CProp ("false",[])]);
+ CProp ("false",[])])]));
+add (CProp
+("equal",
+ [CProp ("or",[CVar 15; CVar 16]);
+ CProp
+ ("if",
+ [CVar 15; CProp ("true",[]);
+ CProp ("if",[CVar 16; CProp ("true",[]); CProp ("false",[])]);
+ CProp ("false",[])])]));
+add (CProp
+("equal",
+ [CProp ("not",[CVar 15]);
+ CProp ("if",[CVar 15; CProp ("false",[]); CProp ("true",[])])]));
+add (CProp
+("equal",
+ [CProp ("implies",[CVar 15; CVar 16]);
+ CProp
+ ("if",
+ [CVar 15;
+ CProp ("if",[CVar 16; CProp ("true",[]); CProp ("false",[])]);
+ CProp ("true",[])])]));
+add (CProp
+("equal",
+ [CProp ("fix",[CVar 23]);
+ CProp ("if",[CProp ("numberp",[CVar 23]); CVar 23; CProp ("zero",[])])]));
+add (CProp
+("equal",
+ [CProp ("if",[CProp ("if",[CVar 0; CVar 1; CVar 2]); CVar 3; CVar 4]);
+ CProp
+ ("if",
+ [CVar 0; CProp ("if",[CVar 1; CVar 3; CVar 4]);
+ CProp ("if",[CVar 2; CVar 3; CVar 4])])]));
+add (CProp
+("equal",
+ [CProp ("zerop",[CVar 23]);
+ CProp
+ ("or",
+ [CProp ("equal",[CVar 23; CProp ("zero",[])]);
+ CProp ("not",[CProp ("numberp",[CVar 23])])])]));
+add (CProp
+("equal",
+ [CProp ("plus",[CProp ("plus",[CVar 23; CVar 24]); CVar 25]);
+ CProp ("plus",[CVar 23; CProp ("plus",[CVar 24; CVar 25])])]));
+add (CProp
+("equal",
+ [CProp ("equal",[CProp ("plus",[CVar 0; CVar 1]); CProp ("zero",[])]);
+ CProp ("and",[CProp ("zerop",[CVar 0]); CProp ("zerop",[CVar 1])])]));
+add (CProp
+("equal",[CProp ("difference",[CVar 23; CVar 23]); CProp ("zero",[])]));
+add (CProp
+("equal",
+ [CProp
+ ("equal",
+ [CProp ("plus",[CVar 0; CVar 1]); CProp ("plus",[CVar 0; CVar 2])]);
+ CProp ("equal",[CProp ("fix",[CVar 1]); CProp ("fix",[CVar 2])])]));
+add (CProp
+("equal",
+ [CProp
+ ("equal",[CProp ("zero",[]); CProp ("difference",[CVar 23; CVar 24])]);
+ CProp ("not",[CProp ("gt",[CVar 24; CVar 23])])]));
+add (CProp
+("equal",
+ [CProp ("equal",[CVar 23; CProp ("difference",[CVar 23; CVar 24])]);
+ CProp
+ ("and",
+ [CProp ("numberp",[CVar 23]);
+ CProp
+ ("or",
+ [CProp ("equal",[CVar 23; CProp ("zero",[])]);
+ CProp ("zerop",[CVar 24])])])]));
+add (CProp
+("equal",
+ [CProp
+ ("meaning",
+ [CProp ("plus_tree",[CProp ("append",[CVar 23; CVar 24])]); CVar 0]);
+ CProp
+ ("plus",
+ [CProp ("meaning",[CProp ("plus_tree",[CVar 23]); CVar 0]);
+ CProp ("meaning",[CProp ("plus_tree",[CVar 24]); CVar 0])])]));
+add (CProp
+("equal",
+ [CProp
+ ("meaning",
+ [CProp ("plus_tree",[CProp ("plus_fringe",[CVar 23])]); CVar 0]);
+ CProp ("fix",[CProp ("meaning",[CVar 23; CVar 0])])]));
+add (CProp
+("equal",
+ [CProp ("append",[CProp ("append",[CVar 23; CVar 24]); CVar 25]);
+ CProp ("append",[CVar 23; CProp ("append",[CVar 24; CVar 25])])]));
+add (CProp
+("equal",
+ [CProp ("reverse",[CProp ("append",[CVar 0; CVar 1])]);
+ CProp
+ ("append",[CProp ("reverse",[CVar 1]); CProp ("reverse",[CVar 0])])]));
+add (CProp
+("equal",
+ [CProp ("times",[CVar 23; CProp ("plus",[CVar 24; CVar 25])]);
+ CProp
+ ("plus",
+ [CProp ("times",[CVar 23; CVar 24]);
+ CProp ("times",[CVar 23; CVar 25])])]));
+add (CProp
+("equal",
+ [CProp ("times",[CProp ("times",[CVar 23; CVar 24]); CVar 25]);
+ CProp ("times",[CVar 23; CProp ("times",[CVar 24; CVar 25])])]));
+add (CProp
+("equal",
+ [CProp
+ ("equal",[CProp ("times",[CVar 23; CVar 24]); CProp ("zero",[])]);
+ CProp ("or",[CProp ("zerop",[CVar 23]); CProp ("zerop",[CVar 24])])]));
+add (CProp
+("equal",
+ [CProp ("exec",[CProp ("append",[CVar 23; CVar 24]); CVar 15; CVar 4]);
+ CProp
+ ("exec",[CVar 24; CProp ("exec",[CVar 23; CVar 15; CVar 4]); CVar 4])]));
+add (CProp
+("equal",
+ [CProp ("mc_flatten",[CVar 23; CVar 24]);
+ CProp ("append",[CProp ("flatten",[CVar 23]); CVar 24])]));
+add (CProp
+("equal",
+ [CProp ("member",[CVar 23; CProp ("append",[CVar 0; CVar 1])]);
+ CProp
+ ("or",
+ [CProp ("member",[CVar 23; CVar 0]);
+ CProp ("member",[CVar 23; CVar 1])])]));
+add (CProp
+("equal",
+ [CProp ("member",[CVar 23; CProp ("reverse",[CVar 24])]);
+ CProp ("member",[CVar 23; CVar 24])]));
+add (CProp
+("equal",
+ [CProp ("length",[CProp ("reverse",[CVar 23])]);
+ CProp ("length",[CVar 23])]));
+add (CProp
+("equal",
+ [CProp ("member",[CVar 0; CProp ("intersect",[CVar 1; CVar 2])]);
+ CProp
+ ("and",
+ [CProp ("member",[CVar 0; CVar 1]); CProp ("member",[CVar 0; CVar 2])])]));
+add (CProp
+("equal",[CProp ("nth",[CProp ("zero",[]); CVar 8]); CProp ("zero",[])]));
+add (CProp
+("equal",
+ [CProp ("exp",[CVar 8; CProp ("plus",[CVar 9; CVar 10])]);
+ CProp
+ ("times",
+ [CProp ("exp",[CVar 8; CVar 9]); CProp ("exp",[CVar 8; CVar 10])])]));
+add (CProp
+("equal",
+ [CProp ("exp",[CVar 8; CProp ("times",[CVar 9; CVar 10])]);
+ CProp ("exp",[CProp ("exp",[CVar 8; CVar 9]); CVar 10])]));
+add (CProp
+("equal",
+ [CProp ("reverse_loop",[CVar 23; CVar 24]);
+ CProp ("append",[CProp ("reverse",[CVar 23]); CVar 24])]));
+add (CProp
+("equal",
+ [CProp ("reverse_loop",[CVar 23; CProp ("nil",[])]);
+ CProp ("reverse",[CVar 23])]));
+add (CProp
+("equal",
+ [CProp ("count_list",[CVar 25; CProp ("sort_lp",[CVar 23; CVar 24])]);
+ CProp
+ ("plus",
+ [CProp ("count_list",[CVar 25; CVar 23]);
+ CProp ("count_list",[CVar 25; CVar 24])])]));
+add (CProp
+("equal",
+ [CProp
+ ("equal",
+ [CProp ("append",[CVar 0; CVar 1]); CProp ("append",[CVar 0; CVar 2])]);
+ CProp ("equal",[CVar 1; CVar 2])]));
+add (CProp
+("equal",
+ [CProp
+ ("plus",
+ [CProp ("remainder",[CVar 23; CVar 24]);
+ CProp ("times",[CVar 24; CProp ("quotient",[CVar 23; CVar 24])])]);
+ CProp ("fix",[CVar 23])]));
+add (CProp
+("equal",
+ [CProp
+ ("power_eval",[CProp ("big_plus",[CVar 11; CVar 8; CVar 1]); CVar 1]);
+ CProp ("plus",[CProp ("power_eval",[CVar 11; CVar 1]); CVar 8])]));
+add (CProp
+("equal",
+ [CProp
+ ("power_eval",
+ [CProp ("big_plus",[CVar 23; CVar 24; CVar 8; CVar 1]); CVar 1]);
+ CProp
+ ("plus",
+ [CVar 8;
+ CProp
+ ("plus",
+ [CProp ("power_eval",[CVar 23; CVar 1]);
+ CProp ("power_eval",[CVar 24; CVar 1])])])]));
+add (CProp
+("equal",
+ [CProp ("remainder",[CVar 24; CProp ("one",[])]); CProp ("zero",[])]));
+add (CProp
+("equal",
+ [CProp ("lt",[CProp ("remainder",[CVar 23; CVar 24]); CVar 24]);
+ CProp ("not",[CProp ("zerop",[CVar 24])])]));
+add (CProp
+("equal",[CProp ("remainder",[CVar 23; CVar 23]); CProp ("zero",[])]));
+add (CProp
+("equal",
+ [CProp ("lt",[CProp ("quotient",[CVar 8; CVar 9]); CVar 8]);
+ CProp
+ ("and",
+ [CProp ("not",[CProp ("zerop",[CVar 8])]);
+ CProp
+ ("or",
+ [CProp ("zerop",[CVar 9]);
+ CProp ("not",[CProp ("equal",[CVar 9; CProp ("one",[])])])])])]));
+add (CProp
+("equal",
+ [CProp ("lt",[CProp ("remainder",[CVar 23; CVar 24]); CVar 23]);
+ CProp
+ ("and",
+ [CProp ("not",[CProp ("zerop",[CVar 24])]);
+ CProp ("not",[CProp ("zerop",[CVar 23])]);
+ CProp ("not",[CProp ("lt",[CVar 23; CVar 24])])])]));
+add (CProp
+("equal",
+ [CProp ("power_eval",[CProp ("power_rep",[CVar 8; CVar 1]); CVar 1]);
+ CProp ("fix",[CVar 8])]));
+add (CProp
+("equal",
+ [CProp
+ ("power_eval",
+ [CProp
+ ("big_plus",
+ [CProp ("power_rep",[CVar 8; CVar 1]);
+ CProp ("power_rep",[CVar 9; CVar 1]); CProp ("zero",[]);
+ CVar 1]);
+ CVar 1]);
+ CProp ("plus",[CVar 8; CVar 9])]));
+add (CProp
+("equal",
+ [CProp ("gcd",[CVar 23; CVar 24]); CProp ("gcd",[CVar 24; CVar 23])]));
+add (CProp
+("equal",
+ [CProp ("nth",[CProp ("append",[CVar 0; CVar 1]); CVar 8]);
+ CProp
+ ("append",
+ [CProp ("nth",[CVar 0; CVar 8]);
+ CProp
+ ("nth",
+ [CVar 1; CProp ("difference",[CVar 8; CProp ("length",[CVar 0])])])])]));
+add (CProp
+("equal",
+ [CProp ("difference",[CProp ("plus",[CVar 23; CVar 24]); CVar 23]);
+ CProp ("fix",[CVar 24])]));
+add (CProp
+("equal",
+ [CProp ("difference",[CProp ("plus",[CVar 24; CVar 23]); CVar 23]);
+ CProp ("fix",[CVar 24])]));
+add (CProp
+("equal",
+ [CProp
+ ("difference",
+ [CProp ("plus",[CVar 23; CVar 24]); CProp ("plus",[CVar 23; CVar 25])]);
+ CProp ("difference",[CVar 24; CVar 25])]));
+add (CProp
+("equal",
+ [CProp ("times",[CVar 23; CProp ("difference",[CVar 2; CVar 22])]);
+ CProp
+ ("difference",
+ [CProp ("times",[CVar 2; CVar 23]);
+ CProp ("times",[CVar 22; CVar 23])])]));
+add (CProp
+("equal",
+ [CProp ("remainder",[CProp ("times",[CVar 23; CVar 25]); CVar 25]);
+ CProp ("zero",[])]));
+add (CProp
+("equal",
+ [CProp
+ ("difference",
+ [CProp ("plus",[CVar 1; CProp ("plus",[CVar 0; CVar 2])]); CVar 0]);
+ CProp ("plus",[CVar 1; CVar 2])]));
+add (CProp
+("equal",
+ [CProp
+ ("difference",
+ [CProp ("add1",[CProp ("plus",[CVar 24; CVar 25])]); CVar 25]);
+ CProp ("add1",[CVar 24])]));
+add (CProp
+("equal",
+ [CProp
+ ("lt",
+ [CProp ("plus",[CVar 23; CVar 24]); CProp ("plus",[CVar 23; CVar 25])]);
+ CProp ("lt",[CVar 24; CVar 25])]));
+add (CProp
+("equal",
+ [CProp
+ ("lt",
+ [CProp ("times",[CVar 23; CVar 25]);
+ CProp ("times",[CVar 24; CVar 25])]);
+ CProp
+ ("and",
+ [CProp ("not",[CProp ("zerop",[CVar 25])]);
+ CProp ("lt",[CVar 23; CVar 24])])]));
+add (CProp
+("equal",
+ [CProp ("lt",[CVar 24; CProp ("plus",[CVar 23; CVar 24])]);
+ CProp ("not",[CProp ("zerop",[CVar 23])])]));
+add (CProp
+("equal",
+ [CProp
+ ("gcd",
+ [CProp ("times",[CVar 23; CVar 25]);
+ CProp ("times",[CVar 24; CVar 25])]);
+ CProp ("times",[CVar 25; CProp ("gcd",[CVar 23; CVar 24])])]));
+add (CProp
+("equal",
+ [CProp ("value",[CProp ("normalize",[CVar 23]); CVar 0]);
+ CProp ("value",[CVar 23; CVar 0])]));
+add (CProp
+("equal",
+ [CProp
+ ("equal",
+ [CProp ("flatten",[CVar 23]);
+ CProp ("cons",[CVar 24; CProp ("nil",[])])]);
+ CProp
+ ("and",
+ [CProp ("nlistp",[CVar 23]); CProp ("equal",[CVar 23; CVar 24])])]));
+add (CProp
+("equal",
+ [CProp ("listp",[CProp ("gother",[CVar 23])]);
+ CProp ("listp",[CVar 23])]));
+add (CProp
+("equal",
+ [CProp ("samefringe",[CVar 23; CVar 24]);
+ CProp
+ ("equal",[CProp ("flatten",[CVar 23]); CProp ("flatten",[CVar 24])])]));
+add (CProp
+("equal",
+ [CProp
+ ("equal",
+ [CProp ("greatest_factor",[CVar 23; CVar 24]); CProp ("zero",[])]);
+ CProp
+ ("and",
+ [CProp
+ ("or",
+ [CProp ("zerop",[CVar 24]);
+ CProp ("equal",[CVar 24; CProp ("one",[])])]);
+ CProp ("equal",[CVar 23; CProp ("zero",[])])])]));
+add (CProp
+("equal",
+ [CProp
+ ("equal",
+ [CProp ("greatest_factor",[CVar 23; CVar 24]); CProp ("one",[])]);
+ CProp ("equal",[CVar 23; CProp ("one",[])])]));
+add (CProp
+("equal",
+ [CProp ("numberp",[CProp ("greatest_factor",[CVar 23; CVar 24])]);
+ CProp
+ ("not",
+ [CProp
+ ("and",
+ [CProp
+ ("or",
+ [CProp ("zerop",[CVar 24]);
+ CProp ("equal",[CVar 24; CProp ("one",[])])]);
+ CProp ("not",[CProp ("numberp",[CVar 23])])])])]));
+add (CProp
+("equal",
+ [CProp ("times_list",[CProp ("append",[CVar 23; CVar 24])]);
+ CProp
+ ("times",
+ [CProp ("times_list",[CVar 23]); CProp ("times_list",[CVar 24])])]));
+add (CProp
+("equal",
+ [CProp ("prime_list",[CProp ("append",[CVar 23; CVar 24])]);
+ CProp
+ ("and",
+ [CProp ("prime_list",[CVar 23]); CProp ("prime_list",[CVar 24])])]));
+add (CProp
+("equal",
+ [CProp ("equal",[CVar 25; CProp ("times",[CVar 22; CVar 25])]);
+ CProp
+ ("and",
+ [CProp ("numberp",[CVar 25]);
+ CProp
+ ("or",
+ [CProp ("equal",[CVar 25; CProp ("zero",[])]);
+ CProp ("equal",[CVar 22; CProp ("one",[])])])])]));
+add (CProp
+("equal",
+ [CProp ("ge",[CVar 23; CVar 24]);
+ CProp ("not",[CProp ("lt",[CVar 23; CVar 24])])]));
+add (CProp
+("equal",
+ [CProp ("equal",[CVar 23; CProp ("times",[CVar 23; CVar 24])]);
+ CProp
+ ("or",
+ [CProp ("equal",[CVar 23; CProp ("zero",[])]);
+ CProp
+ ("and",
+ [CProp ("numberp",[CVar 23]);
+ CProp ("equal",[CVar 24; CProp ("one",[])])])])]));
+add (CProp
+("equal",
+ [CProp ("remainder",[CProp ("times",[CVar 24; CVar 23]); CVar 24]);
+ CProp ("zero",[])]));
+add (CProp
+("equal",
+ [CProp ("equal",[CProp ("times",[CVar 0; CVar 1]); CProp ("one",[])]);
+ CProp
+ ("and",
+ [CProp ("not",[CProp ("equal",[CVar 0; CProp ("zero",[])])]);
+ CProp ("not",[CProp ("equal",[CVar 1; CProp ("zero",[])])]);
+ CProp ("numberp",[CVar 0]); CProp ("numberp",[CVar 1]);
+ CProp ("equal",[CProp ("sub1",[CVar 0]); CProp ("zero",[])]);
+ CProp ("equal",[CProp ("sub1",[CVar 1]); CProp ("zero",[])])])]));
+add (CProp
+("equal",
+ [CProp
+ ("lt",
+ [CProp ("length",[CProp ("delete",[CVar 23; CVar 11])]);
+ CProp ("length",[CVar 11])]);
+ CProp ("member",[CVar 23; CVar 11])]));
+add (CProp
+("equal",
+ [CProp ("sort2",[CProp ("delete",[CVar 23; CVar 11])]);
+ CProp ("delete",[CVar 23; CProp ("sort2",[CVar 11])])]));
+add (CProp ("equal",[CProp ("dsort",[CVar 23]); CProp ("sort2",[CVar 23])]));
+add (CProp
+("equal",
+ [CProp
+ ("length",
+ [CProp
+ ("cons",
+ [CVar 0;
+ CProp
+ ("cons",
+ [CVar 1;
+ CProp
+ ("cons",
+ [CVar 2;
+ CProp
+ ("cons",
+ [CVar 3;
+ CProp ("cons",[CVar 4; CProp ("cons",[CVar 5; CVar 6])])])])])])])
+ ; CProp ("plus",[CProp ("six",[]); CProp ("length",[CVar 6])])]));
+add (CProp
+("equal",
+ [CProp
+ ("difference",
+ [CProp ("add1",[CProp ("add1",[CVar 23])]); CProp ("two",[])]);
+ CProp ("fix",[CVar 23])]));
+add (CProp
+("equal",
+ [CProp
+ ("quotient",
+ [CProp ("plus",[CVar 23; CProp ("plus",[CVar 23; CVar 24])]);
+ CProp ("two",[])]);
+ CProp
+ ("plus",[CVar 23; CProp ("quotient",[CVar 24; CProp ("two",[])])])]));
+add (CProp
+("equal",
+ [CProp ("sigma",[CProp ("zero",[]); CVar 8]);
+ CProp
+ ("quotient",
+ [CProp ("times",[CVar 8; CProp ("add1",[CVar 8])]); CProp ("two",[])])]));
+add (CProp
+("equal",
+ [CProp ("plus",[CVar 23; CProp ("add1",[CVar 24])]);
+ CProp
+ ("if",
+ [CProp ("numberp",[CVar 24]);
+ CProp ("add1",[CProp ("plus",[CVar 23; CVar 24])]);
+ CProp ("add1",[CVar 23])])]));
+add (CProp
+("equal",
+ [CProp
+ ("equal",
+ [CProp ("difference",[CVar 23; CVar 24]);
+ CProp ("difference",[CVar 25; CVar 24])]);
+ CProp
+ ("if",
+ [CProp ("lt",[CVar 23; CVar 24]);
+ CProp ("not",[CProp ("lt",[CVar 24; CVar 25])]);
+ CProp
+ ("if",
+ [CProp ("lt",[CVar 25; CVar 24]);
+ CProp ("not",[CProp ("lt",[CVar 24; CVar 23])]);
+ CProp ("equal",[CProp ("fix",[CVar 23]); CProp ("fix",[CVar 25])])])])])
+);
+add (CProp
+("equal",
+ [CProp
+ ("meaning",
+ [CProp ("plus_tree",[CProp ("delete",[CVar 23; CVar 24])]); CVar 0]);
+ CProp
+ ("if",
+ [CProp ("member",[CVar 23; CVar 24]);
+ CProp
+ ("difference",
+ [CProp ("meaning",[CProp ("plus_tree",[CVar 24]); CVar 0]);
+ CProp ("meaning",[CVar 23; CVar 0])]);
+ CProp ("meaning",[CProp ("plus_tree",[CVar 24]); CVar 0])])]));
+add (CProp
+("equal",
+ [CProp ("times",[CVar 23; CProp ("add1",[CVar 24])]);
+ CProp
+ ("if",
+ [CProp ("numberp",[CVar 24]);
+ CProp
+ ("plus",
+ [CVar 23; CProp ("times",[CVar 23; CVar 24]);
+ CProp ("fix",[CVar 23])])])]));
+add (CProp
+("equal",
+ [CProp ("nth",[CProp ("nil",[]); CVar 8]);
+ CProp
+ ("if",[CProp ("zerop",[CVar 8]); CProp ("nil",[]); CProp ("zero",[])])]));
+add (CProp
+("equal",
+ [CProp ("last",[CProp ("append",[CVar 0; CVar 1])]);
+ CProp
+ ("if",
+ [CProp ("listp",[CVar 1]); CProp ("last",[CVar 1]);
+ CProp
+ ("if",
+ [CProp ("listp",[CVar 0]);
+ CProp ("cons",[CProp ("car",[CProp ("last",[CVar 0])]); CVar 1]);
+ CVar 1])])]));
+add (CProp
+("equal",
+ [CProp ("equal",[CProp ("lt",[CVar 23; CVar 24]); CVar 25]);
+ CProp
+ ("if",
+ [CProp ("lt",[CVar 23; CVar 24]);
+ CProp ("equal",[CProp ("true",[]); CVar 25]);
+ CProp ("equal",[CProp ("false",[]); CVar 25])])]));
+add (CProp
+("equal",
+ [CProp ("assignment",[CVar 23; CProp ("append",[CVar 0; CVar 1])]);
+ CProp
+ ("if",
+ [CProp ("assignedp",[CVar 23; CVar 0]);
+ CProp ("assignment",[CVar 23; CVar 0]);
+ CProp ("assignment",[CVar 23; CVar 1])])]));
+add (CProp
+("equal",
+ [CProp ("car",[CProp ("gother",[CVar 23])]);
+ CProp
+ ("if",
+ [CProp ("listp",[CVar 23]);
+ CProp ("car",[CProp ("flatten",[CVar 23])]); CProp ("zero",[])])]));
+add (CProp
+("equal",
+ [CProp ("flatten",[CProp ("cdr",[CProp ("gother",[CVar 23])])]);
+ CProp
+ ("if",
+ [CProp ("listp",[CVar 23]);
+ CProp ("cdr",[CProp ("flatten",[CVar 23])]);
+ CProp ("cons",[CProp ("zero",[]); CProp ("nil",[])])])]));
+add (CProp
+("equal",
+ [CProp ("quotient",[CProp ("times",[CVar 24; CVar 23]); CVar 24]);
+ CProp
+ ("if",
+ [CProp ("zerop",[CVar 24]); CProp ("zero",[]);
+ CProp ("fix",[CVar 23])])]));
+add (CProp
+("equal",
+ [CProp ("get",[CVar 9; CProp ("set",[CVar 8; CVar 21; CVar 12])]);
+ CProp
+ ("if",
+ [CProp ("eqp",[CVar 9; CVar 8]); CVar 21;
+ CProp ("get",[CVar 9; CVar 12])])]))
+
+(* Tautology checker *)
+
+let truep x lst =
+ match x with
+ Prop(head, _) ->
+ head.name = "true" || List.mem x lst
+ | _ ->
+ List.mem x lst
+
+and falsep x lst =
+ match x with
+ Prop(head, _) ->
+ head.name = "false" || List.mem x lst
+ | _ ->
+ List.mem x lst
+
+
+let rec tautologyp x true_lst false_lst =
+ if truep x true_lst then true else
+ if falsep x false_lst then false else begin
+(*
+ print_term x; print_newline();
+*)
+ match x with
+ Var _ -> false
+ | Prop (head,[test; yes; no]) ->
+ if head.name = "if" then
+ if truep test true_lst then
+ tautologyp yes true_lst false_lst
+ else if falsep test false_lst then
+ tautologyp no true_lst false_lst
+ else tautologyp yes (test::true_lst) false_lst &&
+ tautologyp no true_lst (test::false_lst)
+ else
+ false
+ | _ -> assert false
+ end
+
+
+let tautp x =
+(* print_term x; print_string"\n"; *)
+ let y = rewrite x in
+(* print_term y; print_string "\n"; *)
+ tautologyp y [] []
+
+(* the benchmark *)
+
+let subst =
+[Bind(23, cterm_to_term(
+ CProp
+ ("f",
+ [CProp
+ ("plus",
+ [CProp ("plus",[CVar 0; CVar 1]);
+ CProp ("plus",[CVar 2; CProp ("zero",[])])])])));
+ Bind(24, cterm_to_term(
+ CProp
+ ("f",
+ [CProp
+ ("times",
+ [CProp ("times",[CVar 0; CVar 1]);
+ CProp ("plus",[CVar 2; CVar 3])])])));
+ Bind(25, cterm_to_term(
+ CProp
+ ("f",
+ [CProp
+ ("reverse",
+ [CProp
+ ("append",
+ [CProp ("append",[CVar 0; CVar 1]);
+ CProp ("nil",[])])])])));
+ Bind(20, cterm_to_term(
+ CProp
+ ("equal",
+ [CProp ("plus",[CVar 0; CVar 1]);
+ CProp ("difference",[CVar 23; CVar 24])])));
+ Bind(22, cterm_to_term(
+ CProp
+ ("lt",
+ [CProp ("remainder",[CVar 0; CVar 1]);
+ CProp ("member",[CVar 0; CProp ("length",[CVar 1])])])))]
+
+let term = cterm_to_term(
+ CProp
+ ("implies",
+ [CProp
+ ("and",
+ [CProp ("implies",[CVar 23; CVar 24]);
+ CProp
+ ("and",
+ [CProp ("implies",[CVar 24; CVar 25]);
+ CProp
+ ("and",
+ [CProp ("implies",[CVar 25; CVar 20]);
+ CProp ("implies",[CVar 20; CVar 22])])])]);
+ CProp ("implies",[CVar 23; CVar 22])]))
+
+let _ =
+ let ok = ref true in
+ for i = 1 to 50 do
+ if not (tautp (apply_subst subst term)) then ok := false
+ done;
+ if !ok then
+ print_string "Proved!\n"
+ else
+ print_string "Cannot prove!\n";
+ exit 0
+
+(*********
+with
+ failure s ->
+ print_string "Exception failure("; print_string s; print_string ")\n"
+ | Unify ->
+ print_string "Exception Unify\n"
+ | match_failure(file,start,stop) ->
+ print_string "Exception match_failure(";
+ print_string file;
+ print_string ",";
+ print_int start;
+ print_string ",";
+ print_int stop;
+ print_string ")\n"
+ | _ ->
+ print_string "Exception ?\n"
+
+**********)
diff --git a/testsuite/tests/misc/boyer.reference b/testsuite/tests/misc/boyer.reference
new file mode 100644
index 0000000000..f38e3263b1
--- /dev/null
+++ b/testsuite/tests/misc/boyer.reference
@@ -0,0 +1 @@
+Proved!
diff --git a/testsuite/tests/misc/fib.ml b/testsuite/tests/misc/fib.ml
new file mode 100644
index 0000000000..adaf54885a
--- /dev/null
+++ b/testsuite/tests/misc/fib.ml
@@ -0,0 +1,21 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec fib n =
+ if n < 2 then 1 else fib(n-1) + fib(n-2)
+
+let _ =
+ let n =
+ if Array.length Sys.argv >= 2
+ then int_of_string Sys.argv.(1)
+ else 40 in
+ print_int(fib n); print_newline(); exit 0
diff --git a/testsuite/tests/misc/fib.reference b/testsuite/tests/misc/fib.reference
new file mode 100644
index 0000000000..1d7ca9c61f
--- /dev/null
+++ b/testsuite/tests/misc/fib.reference
@@ -0,0 +1 @@
+165580141
diff --git a/testsuite/tests/misc/hamming.ml b/testsuite/tests/misc/hamming.ml
new file mode 100644
index 0000000000..7c49c2b4ce
--- /dev/null
+++ b/testsuite/tests/misc/hamming.ml
@@ -0,0 +1,103 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* We cannot use bignums because we don't do custom runtimes, but
+ int64 is a bit short, so we roll our own 37-digit numbers...
+*)
+
+let n0 = Int64.of_int 0;;
+let n1 = Int64.of_int 1;;
+let n2 = Int64.of_int 2;;
+let n3 = Int64.of_int 3;;
+let n5 = Int64.of_int 5;;
+
+let ( % ) = Int64.rem;;
+let ( * ) = Int64.mul;;
+let ( / ) = Int64.div;;
+let ( + ) = Int64.add;;
+let digit = Int64.of_string "1000000000000000000";;
+
+let mul n (pl, ph) = ((n * pl) % digit, n * ph + (n * pl) / digit);;
+let cmp (nl, nh) (pl, ph) =
+ if nh < ph then -1
+ else if nh > ph then 1
+ else if nl < pl then -1
+ else if nl > pl then 1
+ else 0
+;;
+
+let x2 = fun p -> mul n2 p;;
+let x3 = fun p -> mul n3 p;;
+let x5 = fun p -> mul n5 p;;
+
+let nn1 = (n1, n0);;
+
+let pr (nl, nh) =
+ if compare nh n0 = 0
+ then Printf.printf "%Ld\n" nl
+ else Printf.printf "%Ld%018Ld\n" nh nl
+;;
+
+(*
+ (* bignum version *)
+open Num;;
+let nn1 = num_of_int 1;;
+let x2 = fun p -> (num_of_int 2) */ p;;
+let x3 = fun p -> (num_of_int 3) */ p;;
+let x5 = fun p -> (num_of_int 5) */ p;;
+let cmp n p = sign_num (n -/ p);;
+let pr n = Printf.printf "%s\n" (string_of_num n);;
+*)
+
+
+(* This is where the interesting stuff begins. *)
+
+open Lazy;;
+
+type 'a lcons = Cons of 'a * 'a lcons Lazy.t;;
+type 'a llist = 'a lcons Lazy.t;;
+
+let rec map f l =
+ lazy (
+ match force l with
+ | Cons (x, ll) -> Cons (f x, map f ll)
+ )
+;;
+
+let rec merge cmp l1 l2 =
+ lazy (
+ match force l1, force l2 with
+ | Cons (x1, ll1), Cons (x2, ll2)
+ -> let c = cmp x1 x2 in
+ if c = 0
+ then Cons (x1, merge cmp ll1 ll2)
+ else if c < 0
+ then Cons (x1, merge cmp ll1 l2)
+ else Cons (x2, merge cmp l1 ll2)
+ )
+;;
+
+let rec iter_interval f l (start, stop) =
+ if stop = 0 then ()
+ else match force l with
+ | Cons (x, ll)
+ -> if start <= 0 then f x;
+ iter_interval f ll (start-1, stop-1)
+;;
+
+let rec hamming = lazy (Cons (nn1, merge cmp ham2 (merge cmp ham3 ham5)))
+ and ham2 = lazy (force (map x2 hamming))
+ and ham3 = lazy (force (map x3 hamming))
+ and ham5 = lazy (force (map x5 hamming))
+;;
+
+iter_interval pr hamming (88000, 88100);;
diff --git a/testsuite/tests/misc/hamming.reference b/testsuite/tests/misc/hamming.reference
new file mode 100644
index 0000000000..af1339ef5e
--- /dev/null
+++ b/testsuite/tests/misc/hamming.reference
@@ -0,0 +1,100 @@
+6726050156250000000000000000000000000
+6729216728661136606575523242669244416
+6730293634611118019721084375000000000
+6731430439413948088320000000000000000
+6733644878411293029785156250000000000
+6736815026358904613608094481682268160
+6739031236724077363200000000000000000
+6743282904874568941599068856042651648
+6744421903677486140423997176256921600
+6746640616477458432000000000000000000
+6750000000000000000000000000000000000
+6750897085400702945836103937453588480
+6752037370304563380023474956271616000
+6754258588364960445000000000000000000
+6755399441055744000000000000000000000
+6757621765136718750000000000000000000
+6758519863481752323552044362431792300
+6759661435938757375539248533340160000
+6761885162088395001166534423828125000
+6763027302973440000000000000000000000
+6765252136392518877983093261718750000
+6767294110289640371843415775641600000
+6768437164792816653010961694720000000
+6770663777894400000000000000000000000
+6774935403077748181101173538816000000
+6776079748261363229431903027200000000
+6778308875544000000000000000000000000
+6782585324034592562287109312160000000
+6783730961356018699387011072000000000
+6785962605658597412109375000000000000
+6789341568946838378906250000000000000
+6791390813820928754681118720000000000
+6794772480000000000000000000000000000
+6799059315411241693033267200000000000
+6800207735332289107722240000000000000
+6802444800000000000000000000000000000
+6806736475893120841673472000000000000
+6807886192552970708582400000000000000
+6810125783203125000000000000000000000
+6814422305043756994967597929687500000
+6815573319906622439424000000000000000
+6817815439391434192657470703125000000
+6821025214188390921278195662703296512
+6821210263296961784362792968750000000
+6823269127183128330240000000000000000
+6828727177473454717179297140960133120
+6830973624183426662400000000000000000
+6834375000000000000000000000000000000
+6835283298968211732659055236671758336
+6836437837433370422273768393225011200
+6838686820719522450562500000000000000
+6839841934068940800000000000000000000
+6842092037200927734375000000000000000
+6844157203887991842733489140006912000
+6845313241232438768082197309030400000
+6847565144260608000000000000000000000
+6849817788097425363957881927490234375
+6851885286668260876491458472837120000
+6853042629352726861173598715904000000
+6855297075118080000000000000000000000
+6859622095616220033364938208051200000
+6860780745114630269799801815040000000
+6863037736488300000000000000000000000
+6866455078125000000000000000000000000
+6867367640585024969315698178562000000
+6868527598372968933129348710400000000
+6870787138229329879760742187500000000
+6871947673600000000000000000000000000
+6874208338558673858642578125000000000
+6876283198993690364114632704000000000
+6879707136000000000000000000000000000
+6884047556853882214196183040000000000
+6885210332023942721568768000000000000
+6887475360000000000000000000000000000
+6891820681841784852194390400000000000
+6892984769959882842439680000000000000
+6895252355493164062500000000000000000
+6899602583856803957404692903808593750
+6900767986405455219916800000000000000
+6903038132383827120065689086914062500
+6906475391588173806667327880859375000
+6908559991272917434368000000000000000
+6912000000000000000000000000000000000
+6914086267191872901144038355222134784
+6916360794485719495680000000000000000
+6917529027641081856000000000000000000
+6919804687500000000000000000000000000
+6921893310401287552552190498140323840
+6924170405978516481194531250000000000
+6925339958244802560000000000000000000
+6927618187665939331054687500000000000
+6929709168936591740767657754256998400
+6930879656747844252683224775393280000
+6933159708563865600000000000000000000
+6937533852751614137447601703747584000
+6938705662219635946938268699852800000
+6940988288557056000000000000000000000
+6945367371811422783781999935651840000
+6946540504428563148172299337728000000
+6948825708194403750000000000000000000
diff --git a/testsuite/tests/misc/nucleic.ml b/testsuite/tests/misc/nucleic.ml
new file mode 100644
index 0000000000..6b5b196f55
--- /dev/null
+++ b/testsuite/tests/misc/nucleic.ml
@@ -0,0 +1,3236 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Use floating-point arithmetic *)
+
+external (+) : float -> float -> float = "%addfloat"
+external (-) : float -> float -> float = "%subfloat"
+external ( * ) : float -> float -> float = "%mulfloat"
+external (/) : float -> float -> float = "%divfloat"
+
+(* -- MATH UTILITIES --------------------------------------------------------*)
+
+let constant_pi = 3.14159265358979323846
+let constant_minus_pi = -3.14159265358979323846
+let constant_pi2 = 1.57079632679489661923
+let constant_minus_pi2 = -1.57079632679489661923
+
+(* -- POINTS ----------------------------------------------------------------*)
+
+type pt = { x : float; y : float; z : float }
+
+let
+pt_sub p1 p2
+ = { x = p1.x - p2.x; y = p1.y - p2.y; z = p1.z - p2.z }
+
+let
+pt_dist p1 p2
+ = let dx = p1.x - p2.x
+ and dy = p1.y - p2.y
+ and dz = p1.z - p2.z
+ in
+ sqrt ((dx * dx) + (dy * dy) + (dz * dz))
+
+let
+pt_phi p
+ = let b = atan2 p.x p.z
+ in
+ atan2 ((cos b) * p.z + (sin b) * p.x) p.y
+
+let
+pt_theta p
+ = atan2 p.x p.z
+
+(* -- COORDINATE TRANSFORMATIONS --------------------------------------------*)
+
+(*
+ The notation for the transformations follows "Paul, R.P. (1981) Robot
+ Manipulators. MIT Press." with the exception that our transformation
+ matrices don't have the perspective terms and are the transpose of
+ Paul's one. See also "M\"antyl\"a, M. (1985) An Introduction to
+ Solid Modeling, Computer Science Press" Appendix A.
+
+ The components of a transformation matrix are named like this:
+
+ a b c
+ d e f
+ g h i
+ tx ty tz
+
+ The components tx, ty, and tz are the translation vector.
+*)
+
+type tfo =
+ {a: float; b: float; c: float;
+ d: float; e: float; f: float;
+ g: float; h: float; i: float;
+ tx: float; ty: float; tz: float}
+
+let tfo_id =
+ {a=1.0; b=0.0; c=0.0;
+ d=0.0; e=1.0; f=0.0;
+ g=0.0; h=0.0; i=1.0;
+ tx=0.0; ty=0.0; tz=0.0}
+
+(*
+ The function "tfo-apply" multiplies a transformation matrix, tfo, by a
+ point vector, p. The result is a new point.
+*)
+
+let
+tfo_apply t p
+ = { x = ((p.x * t.a) + (p.y * t.d) + (p.z * t.g) + t.tx);
+ y = ((p.x * t.b) + (p.y * t.e) + (p.z * t.h) + t.ty);
+ z = ((p.x * t.c) + (p.y * t.f) + (p.z * t.i) + t.tz) }
+
+(*
+ The function "tfo-combine" multiplies two transformation matrices A and B.
+ The result is a new matrix which cumulates the transformations described
+ by A and B.
+*)
+
+let
+tfo_combine a b =
+(* <HAND_CSE> *)
+ (* Hand elimination of common subexpressions.
+ Assumes lots of float registers (32 is perfect, 16 still OK).
+ Loses on the I386, of course. *)
+ let a_a = a.a and a_b = a.b and a_c = a.c and a_d = a.d
+ and a_e = a.e and a_f = a.f and a_g = a.g and a_h = a.h
+ and a_i = a.i and a_tx = a.tx and a_ty = a.ty and a_tz = a.tz
+ and b_a = b.a and b_b = b.b and b_c = b.c and b_d = b.d
+ and b_e = b.e and b_f = b.f and b_g = b.g and b_h = b.h
+ and b_i = b.i and b_tx = b.tx and b_ty = b.ty and b_tz = b.tz in
+ { a = ((a_a * b_a) + (a_b * b_d) + (a_c * b_g));
+ b = ((a_a * b_b) + (a_b * b_e) + (a_c * b_h));
+ c = ((a_a * b_c) + (a_b * b_f) + (a_c * b_i));
+ d = ((a_d * b_a) + (a_e * b_d) + (a_f * b_g));
+ e = ((a_d * b_b) + (a_e * b_e) + (a_f * b_h));
+ f = ((a_d * b_c) + (a_e * b_f) + (a_f * b_i));
+ g = ((a_g * b_a) + (a_h * b_d) + (a_i * b_g));
+ h = ((a_g * b_b) + (a_h * b_e) + (a_i * b_h));
+ i = ((a_g * b_c) + (a_h * b_f) + (a_i * b_i));
+ tx = ((a_tx * b_a) + (a_ty * b_d) + (a_tz * b_g) + b_tx);
+ ty = ((a_tx * b_b) + (a_ty * b_e) + (a_tz * b_h) + b_ty);
+ tz = ((a_tx * b_c) + (a_ty * b_f) + (a_tz * b_i) + b_tz)
+ }
+(* </HAND_CSE> *)
+ (* Original without CSE *)
+(* <NO_CSE> *) (***
+ { a = ((a.a * b.a) + (a.b * b.d) + (a.c * b.g));
+ b = ((a.a * b.b) + (a.b * b.e) + (a.c * b.h));
+ c = ((a.a * b.c) + (a.b * b.f) + (a.c * b.i));
+ d = ((a.d * b.a) + (a.e * b.d) + (a.f * b.g));
+ e = ((a.d * b.b) + (a.e * b.e) + (a.f * b.h));
+ f = ((a.d * b.c) + (a.e * b.f) + (a.f * b.i));
+ g = ((a.g * b.a) + (a.h * b.d) + (a.i * b.g));
+ h = ((a.g * b.b) + (a.h * b.e) + (a.i * b.h));
+ i = ((a.g * b.c) + (a.h * b.f) + (a.i * b.i));
+ tx = ((a.tx * b.a) + (a.ty * b.d) + (a.tz * b.g) + b.tx);
+ ty = ((a.tx * b.b) + (a.ty * b.e) + (a.tz * b.h) + b.ty);
+ tz = ((a.tx * b.c) + (a.ty * b.f) + (a.tz * b.i) + b.tz)
+ }
+ ***) (* </NO_CSE> *)
+
+(*
+ The function "tfo-inv-ortho" computes the inverse of a homogeneous
+ transformation matrix.
+*)
+
+let
+tfo_inv_ortho t =
+ { a = t.a; b = t.d; c = t.g;
+ d = t.b; e = t.e; f = t.h;
+ g = t.c; h = t.f; i = t.i;
+ tx = (-.((t.a * t.tx) + (t.b * t.ty) + (t.c * t.tz)));
+ ty = (-.((t.d * t.tx) + (t.e * t.ty) + (t.f * t.tz)));
+ tz = (-.((t.g * t.tx) + (t.h * t.ty) + (t.i * t.tz)))
+ }
+
+(*
+ Given three points p1, p2, and p3, the function "tfo-align" computes
+ a transformation matrix such that point p1 gets mapped to (0,0,0), p2 gets
+ mapped to the Y axis and p3 gets mapped to the YZ plane.
+*)
+
+let
+tfo_align p1 p2 p3
+ = let x31 = p3.x - p1.x in
+ let y31 = p3.y - p1.y in
+ let z31 = p3.z - p1.z in
+ let rotpy = pt_sub p2 p1 in
+ let phi = pt_phi rotpy in
+ let theta = pt_theta rotpy in
+ let sinp = sin phi in
+ let sint = sin theta in
+ let cosp = cos phi in
+ let cost = cos theta in
+ let sinpsint = sinp * sint in
+ let sinpcost = sinp * cost in
+ let cospsint = cosp * sint in
+ let cospcost = cosp * cost in
+ let rotpz =
+ { x = ((cost * x31) - (sint * z31));
+ y = ((sinpsint * x31) + (cosp * y31) + (sinpcost * z31));
+ z = ((cospsint * x31) + (-.(sinp * y31)) + (cospcost * z31)) } in
+ let rho = pt_theta rotpz in
+ let cosr = cos rho in
+ let sinr = sin rho in
+ let x = (-.(p1.x * cost)) + (p1.z * sint) in
+ let y = ((-.(p1.x * sinpsint)) - (p1.y * cosp)) - (p1.z * sinpcost) in
+ let z = ((-.(p1.x * cospsint) + (p1.y * sinp))) - (p1.z * cospcost) in
+ { a = ((cost * cosr) - (cospsint * sinr));
+ b = sinpsint;
+ c = ((cost * sinr) + (cospsint * cosr));
+ d = (sinp * sinr);
+ e = cosp;
+ f = (-.(sinp * cosr));
+ g = ((-.(sint * cosr)) - (cospcost * sinr));
+ h = sinpcost;
+ i = ((-.(sint * sinr) + (cospcost * cosr)));
+ tx = ((x * cosr) - (z * sinr));
+ ty = y;
+ tz = ((x * sinr + (z * cosr)))
+ }
+
+(* -- NUCLEIC ACID CONFORMATIONS DATA BASE ----------------------------------*)
+
+(*
+ Numbering of atoms follows the paper:
+
+ IUPAC-IUB Joint Commission on Biochemical Nomenclature (JCBN)
+ (1983) Abbreviations and Symbols for the Description of
+ Conformations of Polynucleotide Chains. Eur. J. Biochem 131,
+ 9-15.
+*)
+
+(* Define remaining atoms for each nucleotide type. *)
+
+type nuc_specific =
+ A of pt*pt*pt*pt*pt*pt*pt*pt
+| C of pt*pt*pt*pt*pt*pt
+| G of pt*pt*pt*pt*pt*pt*pt*pt*pt
+| U of pt*pt*pt*pt*pt
+
+(*
+ A n6 n7 n9 c8 h2 h61 h62 h8
+ C n4 o2 h41 h42 h5 h6
+ G n2 n7 n9 c8 o6 h1 h21 h22 h8
+ U o2 o4 h3 h5 h6
+*)
+
+(* Define part common to all 4 nucleotide types. *)
+
+type nuc =
+ N of tfo*tfo*tfo*tfo*
+ pt*pt*pt*pt*pt*pt*pt*pt*pt*pt*pt*pt*
+ pt*pt*pt*pt*pt*pt*pt*pt*pt*pt*pt*pt*
+ pt*nuc_specific
+
+(*
+ dgf_base_tfo ; defines the standard position for wc and wc_dumas
+ p_o3'_275_tfo ; defines the standard position for the connect function
+ p_o3'_180_tfo
+ p_o3'_60_tfo
+ p o1p o2p o5' c5' h5' h5'' c4' h4' o4' c1' h1' c2' h2'' o2' h2' c3'
+ h3' o3' n1 n3 c2 c4 c5 c6
+*)
+
+let is_A = function
+ N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,A(_,_,_,_,_,_,_,_)) -> true
+ | _ -> false
+
+let is_C = function
+ N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,C(_,_,_,_,_,_)) -> true
+ | _ -> false
+
+let is_G = function
+ N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,G(_,_,_,_,_,_,_,_,_)) -> true
+ | _ -> false
+
+let
+nuc_C1'
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = c1'
+
+let
+nuc_C2
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = c2
+
+let
+nuc_C3'
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = c3'
+
+let
+nuc_C4
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = c4
+
+let
+nuc_C4'
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = c4'
+
+let
+nuc_N1
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = n1
+
+let
+nuc_O3'
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = o3'
+
+let
+nuc_P
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = p
+
+let
+nuc_dgf_base_tfo
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = dgf_base_tfo
+
+let
+nuc_p_o3'_180_tfo
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = p_o3'_180_tfo
+
+let
+nuc_p_o3'_275_tfo
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = p_o3'_275_tfo
+
+let
+nuc_p_o3'_60_tfo
+(N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,_))
+ = p_o3'_60_tfo
+
+let
+rA_N9 = function
+| (N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,A (n6,n7,n9,c8,h2,h61,h62,h8))) -> n9
+| _ -> assert false
+
+
+let
+rG_N9 = function
+| (N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,G (n2,n7,n9,c8,o6,h1,h21,h22,h8))) -> n9
+| _ -> assert false
+
+(* Database of nucleotide conformations: *)
+
+let rA
+ = N(
+ { a= -0.0018; b= -0.8207; c=0.5714; (* dgf_base_tfo *)
+ d=0.2679; e= -0.5509; f= -0.7904;
+ g=0.9634; h=0.1517; i=0.2209;
+ tx=0.0073; ty=8.4030; tz=0.6232 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 5.4550; y = 8.2120; z = -2.8810 }, (* C5' *)
+ { x = 5.4546; y = 8.8508; z = -1.9978 }, (* H5' *)
+ { x = 5.7588; y = 8.6625; z = -3.8259 }, (* H5'' *)
+ { x = 6.4970; y = 7.1480; z = -2.5980 }, (* C4' *)
+ { x = 7.4896; y = 7.5919; z = -2.5214 }, (* H4' *)
+ { x = 6.1630; y = 6.4860; z = -1.3440 }, (* O4' *)
+ { x = 6.5400; y = 5.1200; z = -1.4190 }, (* C1' *)
+ { x = 7.2763; y = 4.9681; z = -0.6297 }, (* H1' *)
+ { x = 7.1940; y = 4.8830; z = -2.7770 }, (* C2' *)
+ { x = 6.8667; y = 3.9183; z = -3.1647 }, (* H2'' *)
+ { x = 8.5860; y = 5.0910; z = -2.6140 }, (* O2' *)
+ { x = 8.9510; y = 4.7626; z = -1.7890 }, (* H2' *)
+ { x = 6.5720; y = 6.0040; z = -3.6090 }, (* C3' *)
+ { x = 5.5636; y = 5.7066; z = -3.8966 }, (* H3' *)
+ { x = 7.3801; y = 6.3562; z = -4.7350 }, (* O3' *)
+ { x = 4.7150; y = 0.4910; z = -0.1360 }, (* N1 *)
+ { x = 6.3490; y = 2.1730; z = -0.6020 }, (* N3 *)
+ { x = 5.9530; y = 0.9650; z = -0.2670 }, (* C2 *)
+ { x = 5.2900; y = 2.9790; z = -0.8260 }, (* C4 *)
+ { x = 3.9720; y = 2.6390; z = -0.7330 }, (* C5 *)
+ { x = 3.6770; y = 1.3160; z = -0.3660 }, (* C6 *)
+ (A (
+ { x = 2.4280; y = 0.8450; z = -0.2360 }, (* N6 *)
+ { x = 3.1660; y = 3.7290; z = -1.0360 }, (* N7 *)
+ { x = 5.3170; y = 4.2990; z = -1.1930 }, (* N9 *)
+ { x = 4.0100; y = 4.6780; z = -1.2990 }, (* C8 *)
+ { x = 6.6890; y = 0.1903; z = -0.0518 }, (* H2 *)
+ { x = 1.6470; y = 1.4460; z = -0.4040 }, (* H61 *)
+ { x = 2.2780; y = -0.1080; z = -0.0280 }, (* H62 *)
+ { x = 3.4421; y = 5.5744; z = -1.5482 }) (* H8 *)
+ )
+ )
+
+let rA01
+ = N(
+ { a= -0.0043; b= -0.8175; c=0.5759; (* dgf_base_tfo *)
+ d=0.2617; e= -0.5567; f= -0.7884;
+ g=0.9651; h=0.1473; i=0.2164;
+ tx=0.0359; ty=8.3929; tz=0.5532 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 5.4352; y = 8.2183; z = -2.7757 }, (* C5' *)
+ { x = 5.3830; y = 8.7883; z = -1.8481 }, (* H5' *)
+ { x = 5.7729; y = 8.7436; z = -3.6691 }, (* H5'' *)
+ { x = 6.4830; y = 7.1518; z = -2.5252 }, (* C4' *)
+ { x = 7.4749; y = 7.5972; z = -2.4482 }, (* H4' *)
+ { x = 6.1626; y = 6.4620; z = -1.2827 }, (* O4' *)
+ { x = 6.5431; y = 5.0992; z = -1.3905 }, (* C1' *)
+ { x = 7.2871; y = 4.9328; z = -0.6114 }, (* H1' *)
+ { x = 7.1852; y = 4.8935; z = -2.7592 }, (* C2' *)
+ { x = 6.8573; y = 3.9363; z = -3.1645 }, (* H2'' *)
+ { x = 8.5780; y = 5.1025; z = -2.6046 }, (* O2' *)
+ { x = 8.9516; y = 4.7577; z = -1.7902 }, (* H2' *)
+ { x = 6.5522; y = 6.0300; z = -3.5612 }, (* C3' *)
+ { x = 5.5420; y = 5.7356; z = -3.8459 }, (* H3' *)
+ { x = 7.3487; y = 6.4089; z = -4.6867 }, (* O3' *)
+ { x = 4.7442; y = 0.4514; z = -0.1390 }, (* N1 *)
+ { x = 6.3687; y = 2.1459; z = -0.5926 }, (* N3 *)
+ { x = 5.9795; y = 0.9335; z = -0.2657 }, (* C2 *)
+ { x = 5.3052; y = 2.9471; z = -0.8125 }, (* C4 *)
+ { x = 3.9891; y = 2.5987; z = -0.7230 }, (* C5 *)
+ { x = 3.7016; y = 1.2717; z = -0.3647 }, (* C6 *)
+ (A (
+ { x = 2.4553; y = 0.7925; z = -0.2390 }, (* N6 *)
+ { x = 3.1770; y = 3.6859; z = -1.0198 }, (* N7 *)
+ { x = 5.3247; y = 4.2695; z = -1.1710 }, (* N9 *)
+ { x = 4.0156; y = 4.6415; z = -1.2759 }, (* C8 *)
+ { x = 6.7198; y = 0.1618; z = -0.0547 }, (* H2 *)
+ { x = 1.6709; y = 1.3900; z = -0.4039 }, (* H61 *)
+ { x = 2.3107; y = -0.1627; z = -0.0373 }, (* H62 *)
+ { x = 3.4426; y = 5.5361; z = -1.5199 }) (* H8 *)
+ )
+ )
+
+let rA02
+ = N(
+ { a=0.5566; b=0.0449; c=0.8296; (* dgf_base_tfo *)
+ d=0.5125; e=0.7673; f= -0.3854;
+ g= -0.6538; h=0.6397; i=0.4041;
+ tx= -9.1161; ty= -3.7679; tz= -2.9968 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 4.5778; y = 6.6594; z = -4.0364 }, (* C5' *)
+ { x = 4.9220; y = 7.1963; z = -4.9204 }, (* H5' *)
+ { x = 3.7996; y = 5.9091; z = -4.1764 }, (* H5'' *)
+ { x = 5.7873; y = 5.8869; z = -3.5482 }, (* C4' *)
+ { x = 6.0405; y = 5.0875; z = -4.2446 }, (* H4' *)
+ { x = 6.9135; y = 6.8036; z = -3.4310 }, (* O4' *)
+ { x = 7.7293; y = 6.4084; z = -2.3392 }, (* C1' *)
+ { x = 8.7078; y = 6.1815; z = -2.7624 }, (* H1' *)
+ { x = 7.1305; y = 5.1418; z = -1.7347 }, (* C2' *)
+ { x = 7.2040; y = 5.1982; z = -0.6486 }, (* H2'' *)
+ { x = 7.7417; y = 4.0392; z = -2.3813 }, (* O2' *)
+ { x = 8.6785; y = 4.1443; z = -2.5630 }, (* H2' *)
+ { x = 5.6666; y = 5.2728; z = -2.1536 }, (* C3' *)
+ { x = 5.1747; y = 5.9805; z = -1.4863 }, (* H3' *)
+ { x = 4.9997; y = 4.0086; z = -2.1973 }, (* O3' *)
+ { x = 10.3245; y = 8.5459; z = 1.5467 }, (* N1 *)
+ { x = 9.8051; y = 6.9432; z = -0.1497 }, (* N3 *)
+ { x = 10.5175; y = 7.4328; z = 0.8408 }, (* C2 *)
+ { x = 8.7523; y = 7.7422; z = -0.4228 }, (* C4 *)
+ { x = 8.4257; y = 8.9060; z = 0.2099 }, (* C5 *)
+ { x = 9.2665; y = 9.3242; z = 1.2540 }, (* C6 *)
+ (A (
+ { x = 9.0664; y = 10.4462; z = 1.9610 }, (* N6 *)
+ { x = 7.2750; y = 9.4537; z = -0.3428 }, (* N7 *)
+ { x = 7.7962; y = 7.5519; z = -1.3859 }, (* N9 *)
+ { x = 6.9479; y = 8.6157; z = -1.2771 }, (* C8 *)
+ { x = 11.4063; y = 6.9047; z = 1.1859 }, (* H2 *)
+ { x = 8.2845; y = 11.0341; z = 1.7552 }, (* H61 *)
+ { x = 9.6584; y = 10.6647; z = 2.7198 }, (* H62 *)
+ { x = 6.0430; y = 8.9853; z = -1.7594 }) (* H8 *)
+ )
+ )
+let rA03
+ = N(
+ { a= -0.5021; b=0.0731; c=0.8617; (* dgf_base_tfo *)
+ d= -0.8112; e=0.3054; f= -0.4986;
+ g= -0.2996; h= -0.9494; i= -0.0940;
+ tx=6.4273; ty= -5.1944; tz= -3.7807 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 4.1214; y = 6.7116; z = -1.9049 }, (* C5' *)
+ { x = 3.3465; y = 5.9610; z = -2.0607 }, (* H5' *)
+ { x = 4.0789; y = 7.2928; z = -0.9837 }, (* H5'' *)
+ { x = 5.4170; y = 5.9293; z = -1.8186 }, (* C4' *)
+ { x = 5.4506; y = 5.3400; z = -0.9023 }, (* H4' *)
+ { x = 5.5067; y = 5.0417; z = -2.9703 }, (* O4' *)
+ { x = 6.8650; y = 4.9152; z = -3.3612 }, (* C1' *)
+ { x = 7.1090; y = 3.8577; z = -3.2603 }, (* H1' *)
+ { x = 7.7152; y = 5.7282; z = -2.3894 }, (* C2' *)
+ { x = 8.5029; y = 6.2356; z = -2.9463 }, (* H2'' *)
+ { x = 8.1036; y = 4.8568; z = -1.3419 }, (* O2' *)
+ { x = 8.3270; y = 3.9651; z = -1.6184 }, (* H2' *)
+ { x = 6.7003; y = 6.7565; z = -1.8911 }, (* C3' *)
+ { x = 6.5898; y = 7.5329; z = -2.6482 }, (* H3' *)
+ { x = 7.0505; y = 7.2878; z = -0.6105 }, (* O3' *)
+ { x = 9.6740; y = 4.7656; z = -7.6614 }, (* N1 *)
+ { x = 9.0739; y = 4.3013; z = -5.3941 }, (* N3 *)
+ { x = 9.8416; y = 4.2192; z = -6.4581 }, (* C2 *)
+ { x = 7.9885; y = 5.0632; z = -5.6446 }, (* C4 *)
+ { x = 7.6822; y = 5.6856; z = -6.8194 }, (* C5 *)
+ { x = 8.5831; y = 5.5215; z = -7.8840 }, (* C6 *)
+ (A (
+ { x = 8.4084; y = 6.0747; z = -9.0933 }, (* N6 *)
+ { x = 6.4857; y = 6.3816; z = -6.7035 }, (* N7 *)
+ { x = 6.9740; y = 5.3703; z = -4.7760 }, (* N9 *)
+ { x = 6.1133; y = 6.1613; z = -5.4808 }, (* C8 *)
+ { x = 10.7627; y = 3.6375; z = -6.4220 }, (* H2 *)
+ { x = 7.6031; y = 6.6390; z = -9.2733 }, (* H61 *)
+ { x = 9.1004; y = 5.9708; z = -9.7893 }, (* H62 *)
+ { x = 5.1705; y = 6.6830; z = -5.3167 }) (* H8 *)
+ )
+ )
+
+let rA04
+ = N(
+ { a= -0.5426; b= -0.8175; c=0.1929; (* dgf_base_tfo *)
+ d=0.8304; e= -0.5567; f= -0.0237;
+ g=0.1267; h=0.1473; i=0.9809;
+ tx= -0.5075; ty=8.3929; tz=0.2229 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 5.4352; y = 8.2183; z = -2.7757 }, (* C5' *)
+ { x = 5.3830; y = 8.7883; z = -1.8481 }, (* H5' *)
+ { x = 5.7729; y = 8.7436; z = -3.6691 }, (* H5'' *)
+ { x = 6.4830; y = 7.1518; z = -2.5252 }, (* C4' *)
+ { x = 7.4749; y = 7.5972; z = -2.4482 }, (* H4' *)
+ { x = 6.1626; y = 6.4620; z = -1.2827 }, (* O4' *)
+ { x = 6.5431; y = 5.0992; z = -1.3905 }, (* C1' *)
+ { x = 7.2871; y = 4.9328; z = -0.6114 }, (* H1' *)
+ { x = 7.1852; y = 4.8935; z = -2.7592 }, (* C2' *)
+ { x = 6.8573; y = 3.9363; z = -3.1645 }, (* H2'' *)
+ { x = 8.5780; y = 5.1025; z = -2.6046 }, (* O2' *)
+ { x = 8.9516; y = 4.7577; z = -1.7902 }, (* H2' *)
+ { x = 6.5522; y = 6.0300; z = -3.5612 }, (* C3' *)
+ { x = 5.5420; y = 5.7356; z = -3.8459 }, (* H3' *)
+ { x = 7.3487; y = 6.4089; z = -4.6867 }, (* O3' *)
+ { x = 3.6343; y = 2.6680; z = 2.0783 }, (* N1 *)
+ { x = 5.4505; y = 3.9805; z = 1.2446 }, (* N3 *)
+ { x = 4.7540; y = 3.3816; z = 2.1851 }, (* C2 *)
+ { x = 4.8805; y = 3.7951; z = 0.0354 }, (* C4 *)
+ { x = 3.7416; y = 3.0925; z = -0.2305 }, (* C5 *)
+ { x = 3.0873; y = 2.4980; z = 0.8606 }, (* C6 *)
+ (A (
+ { x = 1.9600; y = 1.7805; z = 0.7462 }, (* N6 *)
+ { x = 3.4605; y = 3.1184; z = -1.5906 }, (* N7 *)
+ { x = 5.3247; y = 4.2695; z = -1.1710 }, (* N9 *)
+ { x = 4.4244; y = 3.8244; z = -2.0953 }, (* C8 *)
+ { x = 5.0814; y = 3.4352; z = 3.2234 }, (* H2 *)
+ { x = 1.5423; y = 1.6454; z = -0.1520 }, (* H61 *)
+ { x = 1.5716; y = 1.3398; z = 1.5392 }, (* H62 *)
+ { x = 4.2675; y = 3.8876; z = -3.1721 }) (* H8 *)
+ )
+ )
+
+let rA05
+ = N(
+ { a= -0.5891; b=0.0449; c=0.8068; (* dgf_base_tfo *)
+ d=0.5375; e=0.7673; f=0.3498;
+ g= -0.6034; h=0.6397; i= -0.4762;
+ tx= -0.3019; ty= -3.7679; tz= -9.5913 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 4.5778; y = 6.6594; z = -4.0364 }, (* C5' *)
+ { x = 4.9220; y = 7.1963; z = -4.9204 }, (* H5' *)
+ { x = 3.7996; y = 5.9091; z = -4.1764 }, (* H5'' *)
+ { x = 5.7873; y = 5.8869; z = -3.5482 }, (* C4' *)
+ { x = 6.0405; y = 5.0875; z = -4.2446 }, (* H4' *)
+ { x = 6.9135; y = 6.8036; z = -3.4310 }, (* O4' *)
+ { x = 7.7293; y = 6.4084; z = -2.3392 }, (* C1' *)
+ { x = 8.7078; y = 6.1815; z = -2.7624 }, (* H1' *)
+ { x = 7.1305; y = 5.1418; z = -1.7347 }, (* C2' *)
+ { x = 7.2040; y = 5.1982; z = -0.6486 }, (* H2'' *)
+ { x = 7.7417; y = 4.0392; z = -2.3813 }, (* O2' *)
+ { x = 8.6785; y = 4.1443; z = -2.5630 }, (* H2' *)
+ { x = 5.6666; y = 5.2728; z = -2.1536 }, (* C3' *)
+ { x = 5.1747; y = 5.9805; z = -1.4863 }, (* H3' *)
+ { x = 4.9997; y = 4.0086; z = -2.1973 }, (* O3' *)
+ { x = 10.2594; y = 10.6774; z = -1.0056 }, (* N1 *)
+ { x = 9.7528; y = 8.7080; z = -2.2631 }, (* N3 *)
+ { x = 10.4471; y = 9.7876; z = -1.9791 }, (* C2 *)
+ { x = 8.7271; y = 8.5575; z = -1.3991 }, (* C4 *)
+ { x = 8.4100; y = 9.3803; z = -0.3580 }, (* C5 *)
+ { x = 9.2294; y = 10.5030; z = -0.1574 }, (* C6 *)
+ (A (
+ { x = 9.0349; y = 11.3951; z = 0.8250 }, (* N6 *)
+ { x = 7.2891; y = 8.9068; z = 0.3121 }, (* N7 *)
+ { x = 7.7962; y = 7.5519; z = -1.3859 }, (* N9 *)
+ { x = 6.9702; y = 7.8292; z = -0.3353 }, (* C8 *)
+ { x = 11.3132; y = 10.0537; z = -2.5851 }, (* H2 *)
+ { x = 8.2741; y = 11.2784; z = 1.4629 }, (* H61 *)
+ { x = 9.6733; y = 12.1368; z = 0.9529 }, (* H62 *)
+ { x = 6.0888; y = 7.3990; z = 0.1403 }) (* H8 *)
+ )
+ )
+
+let rA06
+ = N(
+ { a= -0.9815; b=0.0731; c= -0.1772; (* dgf_base_tfo *)
+ d=0.1912; e=0.3054; f= -0.9328;
+ g= -0.0141; h= -0.9494; i= -0.3137;
+ tx=5.7506; ty= -5.1944; tz=4.7470 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 4.1214; y = 6.7116; z = -1.9049 }, (* C5' *)
+ { x = 3.3465; y = 5.9610; z = -2.0607 }, (* H5' *)
+ { x = 4.0789; y = 7.2928; z = -0.9837 }, (* H5'' *)
+ { x = 5.4170; y = 5.9293; z = -1.8186 }, (* C4' *)
+ { x = 5.4506; y = 5.3400; z = -0.9023 }, (* H4' *)
+ { x = 5.5067; y = 5.0417; z = -2.9703 }, (* O4' *)
+ { x = 6.8650; y = 4.9152; z = -3.3612 }, (* C1' *)
+ { x = 7.1090; y = 3.8577; z = -3.2603 }, (* H1' *)
+ { x = 7.7152; y = 5.7282; z = -2.3894 }, (* C2' *)
+ { x = 8.5029; y = 6.2356; z = -2.9463 }, (* H2'' *)
+ { x = 8.1036; y = 4.8568; z = -1.3419 }, (* O2' *)
+ { x = 8.3270; y = 3.9651; z = -1.6184 }, (* H2' *)
+ { x = 6.7003; y = 6.7565; z = -1.8911 }, (* C3' *)
+ { x = 6.5898; y = 7.5329; z = -2.6482 }, (* H3' *)
+ { x = 7.0505; y = 7.2878; z = -0.6105 }, (* O3' *)
+ { x = 6.6624; y = 3.5061; z = -8.2986 }, (* N1 *)
+ { x = 6.5810; y = 3.2570; z = -5.9221 }, (* N3 *)
+ { x = 6.5151; y = 2.8263; z = -7.1625 }, (* C2 *)
+ { x = 6.8364; y = 4.5817; z = -5.8882 }, (* C4 *)
+ { x = 7.0116; y = 5.4064; z = -6.9609 }, (* C5 *)
+ { x = 6.9173; y = 4.8260; z = -8.2361 }, (* C6 *)
+ (A (
+ { x = 7.0668; y = 5.5163; z = -9.3763 }, (* N6 *)
+ { x = 7.2573; y = 6.7070; z = -6.5394 }, (* N7 *)
+ { x = 6.9740; y = 5.3703; z = -4.7760 }, (* N9 *)
+ { x = 7.2238; y = 6.6275; z = -5.2453 }, (* C8 *)
+ { x = 6.3146; y = 1.7741; z = -7.3641 }, (* H2 *)
+ { x = 7.2568; y = 6.4972; z = -9.3456 }, (* H61 *)
+ { x = 7.0437; y = 5.0478; z = -10.2446 }, (* H62 *)
+ { x = 7.4108; y = 7.6227; z = -4.8418 }) (* H8 *)
+ )
+ )
+
+let rA07
+ = N(
+ { a=0.2379; b=0.1310; c= -0.9624; (* dgf_base_tfo *)
+ d= -0.5876; e= -0.7696; f= -0.2499;
+ g= -0.7734; h=0.6249; i= -0.1061;
+ tx=30.9870; ty= -26.9344; tz=42.6416 },
+ { a=0.7529; b=0.1548; c=0.6397; (* P_O3'_275_tfo *)
+ d=0.2952; e= -0.9481; f= -0.1180;
+ g=0.5882; h=0.2777; i= -0.7595;
+ tx= -58.8919; ty= -11.3095; tz=6.0866 },
+ { a= -0.0239; b=0.9667; c= -0.2546; (* P_O3'_180_tfo *)
+ d=0.9731; e= -0.0359; f= -0.2275;
+ g= -0.2290; h= -0.2532; i= -0.9399;
+ tx=3.5401; ty= -29.7913; tz=52.2796 },
+ { a= -0.8912; b= -0.4531; c=0.0242; (* P_O3'_60_tfo *)
+ d= -0.1183; e=0.1805; f= -0.9764;
+ g=0.4380; h= -0.8730; i= -0.2145;
+ tx=19.9023; ty=54.8054; tz=15.2799 },
+ { x = 41.8210; y = 8.3880; z = 43.5890 }, (* P *)
+ { x = 42.5400; y = 8.0450; z = 44.8330 }, (* O1P *)
+ { x = 42.2470; y = 9.6920; z = 42.9910 }, (* O2P *)
+ { x = 40.2550; y = 8.2030; z = 43.7340 }, (* O5' *)
+ { x = 39.3505; y = 8.4697; z = 42.6565 }, (* C5' *)
+ { x = 39.1377; y = 7.5433; z = 42.1230 }, (* H5' *)
+ { x = 39.7203; y = 9.3119; z = 42.0717 }, (* H5'' *)
+ { x = 38.0405; y = 8.9195; z = 43.2869 }, (* C4' *)
+ { x = 37.3687; y = 9.3036; z = 42.5193 }, (* H4' *)
+ { x = 37.4319; y = 7.8146; z = 43.9387 }, (* O4' *)
+ { x = 37.1959; y = 8.1354; z = 45.3237 }, (* C1' *)
+ { x = 36.1788; y = 8.5202; z = 45.3970 }, (* H1' *)
+ { x = 38.1721; y = 9.2328; z = 45.6504 }, (* C2' *)
+ { x = 39.1555; y = 8.7939; z = 45.8188 }, (* H2'' *)
+ { x = 37.7862; y = 10.0617; z = 46.7013 }, (* O2' *)
+ { x = 37.3087; y = 9.6229; z = 47.4092 }, (* H2' *)
+ { x = 38.1844; y = 10.0268; z = 44.3367 }, (* C3' *)
+ { x = 39.1578; y = 10.5054; z = 44.2289 }, (* H3' *)
+ { x = 37.0547; y = 10.9127; z = 44.3441 }, (* O3' *)
+ { x = 34.8811; y = 4.2072; z = 47.5784 }, (* N1 *)
+ { x = 35.1084; y = 6.1336; z = 46.1818 }, (* N3 *)
+ { x = 34.4108; y = 5.1360; z = 46.7207 }, (* C2 *)
+ { x = 36.3908; y = 6.1224; z = 46.6053 }, (* C4 *)
+ { x = 36.9819; y = 5.2334; z = 47.4697 }, (* C5 *)
+ { x = 36.1786; y = 4.1985; z = 48.0035 }, (* C6 *)
+ (A (
+ { x = 36.6103; y = 3.2749; z = 48.8452 }, (* N6 *)
+ { x = 38.3236; y = 5.5522; z = 47.6595 }, (* N7 *)
+ { x = 37.3887; y = 7.0024; z = 46.2437 }, (* N9 *)
+ { x = 38.5055; y = 6.6096; z = 46.9057 }, (* C8 *)
+ { x = 33.3553; y = 5.0152; z = 46.4771 }, (* H2 *)
+ { x = 37.5730; y = 3.2804; z = 49.1507 }, (* H61 *)
+ { x = 35.9775; y = 2.5638; z = 49.1828 }, (* H62 *)
+ { x = 39.5461; y = 6.9184; z = 47.0041 }) (* H8 *)
+ )
+ )
+
+let rA08
+ = N(
+ { a=0.1084; b= -0.0895; c= -0.9901; (* dgf_base_tfo *)
+ d=0.9789; e= -0.1638; f=0.1220;
+ g= -0.1731; h= -0.9824; i=0.0698;
+ tx= -2.9039; ty=47.2655; tz=33.0094 },
+ { a=0.7529; b=0.1548; c=0.6397; (* P_O3'_275_tfo *)
+ d=0.2952; e= -0.9481; f= -0.1180;
+ g=0.5882; h=0.2777; i= -0.7595;
+ tx= -58.8919; ty= -11.3095; tz=6.0866 },
+ { a= -0.0239; b=0.9667; c= -0.2546; (* P_O3'_180_tfo *)
+ d=0.9731; e= -0.0359; f= -0.2275;
+ g= -0.2290; h= -0.2532; i= -0.9399;
+ tx=3.5401; ty= -29.7913; tz=52.2796 },
+ { a= -0.8912; b= -0.4531; c=0.0242; (* P_O3'_60_tfo *)
+ d= -0.1183; e=0.1805; f= -0.9764;
+ g=0.4380; h= -0.8730; i= -0.2145;
+ tx=19.9023; ty=54.8054; tz=15.2799 },
+ { x = 41.8210; y = 8.3880; z = 43.5890 }, (* P *)
+ { x = 42.5400; y = 8.0450; z = 44.8330 }, (* O1P *)
+ { x = 42.2470; y = 9.6920; z = 42.9910 }, (* O2P *)
+ { x = 40.2550; y = 8.2030; z = 43.7340 }, (* O5' *)
+ { x = 39.4850; y = 8.9301; z = 44.6977 }, (* C5' *)
+ { x = 39.0638; y = 9.8199; z = 44.2296 }, (* H5' *)
+ { x = 40.0757; y = 9.0713; z = 45.6029 }, (* H5'' *)
+ { x = 38.3102; y = 8.0414; z = 45.0789 }, (* C4' *)
+ { x = 37.7842; y = 8.4637; z = 45.9351 }, (* H4' *)
+ { x = 37.4200; y = 7.9453; z = 43.9769 }, (* O4' *)
+ { x = 37.2249; y = 6.5609; z = 43.6273 }, (* C1' *)
+ { x = 36.3360; y = 6.2168; z = 44.1561 }, (* H1' *)
+ { x = 38.4347; y = 5.8414; z = 44.1590 }, (* C2' *)
+ { x = 39.2688; y = 5.9974; z = 43.4749 }, (* H2'' *)
+ { x = 38.2344; y = 4.4907; z = 44.4348 }, (* O2' *)
+ { x = 37.6374; y = 4.0386; z = 43.8341 }, (* H2' *)
+ { x = 38.6926; y = 6.6079; z = 45.4637 }, (* C3' *)
+ { x = 39.7585; y = 6.5640; z = 45.6877 }, (* H3' *)
+ { x = 37.8238; y = 6.0705; z = 46.4723 }, (* O3' *)
+ { x = 33.9162; y = 6.2598; z = 39.7758 }, (* N1 *)
+ { x = 34.6709; y = 6.5759; z = 42.0215 }, (* N3 *)
+ { x = 33.7257; y = 6.5186; z = 41.0858 }, (* C2 *)
+ { x = 35.8935; y = 6.3324; z = 41.5018 }, (* C4 *)
+ { x = 36.2105; y = 6.0601; z = 40.1932 }, (* C5 *)
+ { x = 35.1538; y = 6.0151; z = 39.2537 }, (* C6 *)
+ (A (
+ { x = 35.3088; y = 5.7642; z = 37.9649 }, (* N6 *)
+ { x = 37.5818; y = 5.8677; z = 40.0507 }, (* N7 *)
+ { x = 37.0932; y = 6.3197; z = 42.1810 }, (* N9 *)
+ { x = 38.0509; y = 6.0354; z = 41.2635 }, (* C8 *)
+ { x = 32.6830; y = 6.6898; z = 41.3532 }, (* H2 *)
+ { x = 36.2305; y = 5.5855; z = 37.5925 }, (* H61 *)
+ { x = 34.5056; y = 5.7512; z = 37.3528 }, (* H62 *)
+ { x = 39.1318; y = 5.8993; z = 41.2285 }) (* H8 *)
+ )
+ )
+
+let rA09
+ = N(
+ { a=0.8467; b=0.4166; c= -0.3311; (* dgf_base_tfo *)
+ d= -0.3962; e=0.9089; f=0.1303;
+ g=0.3552; h=0.0209; i=0.9346;
+ tx= -42.7319; ty= -26.6223; tz= -29.8163 },
+ { a=0.7529; b=0.1548; c=0.6397; (* P_O3'_275_tfo *)
+ d=0.2952; e= -0.9481; f= -0.1180;
+ g=0.5882; h=0.2777; i= -0.7595;
+ tx= -58.8919; ty= -11.3095; tz=6.0866 },
+ { a= -0.0239; b=0.9667; c= -0.2546; (* P_O3'_180_tfo *)
+ d=0.9731; e= -0.0359; f= -0.2275;
+ g= -0.2290; h= -0.2532; i= -0.9399;
+ tx=3.5401; ty= -29.7913; tz=52.2796 },
+ { a= -0.8912; b= -0.4531; c=0.0242; (* P_O3'_60_tfo *)
+ d= -0.1183; e=0.1805; f= -0.9764;
+ g=0.4380; h= -0.8730; i= -0.2145;
+ tx=19.9023; ty=54.8054; tz=15.2799 },
+ { x = 41.8210; y = 8.3880; z = 43.5890 }, (* P *)
+ { x = 42.5400; y = 8.0450; z = 44.8330 }, (* O1P *)
+ { x = 42.2470; y = 9.6920; z = 42.9910 }, (* O2P *)
+ { x = 40.2550; y = 8.2030; z = 43.7340 }, (* O5' *)
+ { x = 39.3505; y = 8.4697; z = 42.6565 }, (* C5' *)
+ { x = 39.1377; y = 7.5433; z = 42.1230 }, (* H5' *)
+ { x = 39.7203; y = 9.3119; z = 42.0717 }, (* H5'' *)
+ { x = 38.0405; y = 8.9195; z = 43.2869 }, (* C4' *)
+ { x = 37.6479; y = 8.1347; z = 43.9335 }, (* H4' *)
+ { x = 38.2691; y = 10.0933; z = 44.0524 }, (* O4' *)
+ { x = 37.3999; y = 11.1488; z = 43.5973 }, (* C1' *)
+ { x = 36.5061; y = 11.1221; z = 44.2206 }, (* H1' *)
+ { x = 37.0364; y = 10.7838; z = 42.1836 }, (* C2' *)
+ { x = 37.8636; y = 11.0489; z = 41.5252 }, (* H2'' *)
+ { x = 35.8275; y = 11.3133; z = 41.7379 }, (* O2' *)
+ { x = 35.6214; y = 12.1896; z = 42.0714 }, (* H2' *)
+ { x = 36.9316; y = 9.2556; z = 42.2837 }, (* C3' *)
+ { x = 37.1778; y = 8.8260; z = 41.3127 }, (* H3' *)
+ { x = 35.6285; y = 8.9334; z = 42.7926 }, (* O3' *)
+ { x = 38.1482; y = 15.2833; z = 46.4641 }, (* N1 *)
+ { x = 37.3641; y = 13.0968; z = 45.9007 }, (* N3 *)
+ { x = 37.5032; y = 14.1288; z = 46.7300 }, (* C2 *)
+ { x = 37.9570; y = 13.3377; z = 44.7113 }, (* C4 *)
+ { x = 38.6397; y = 14.4660; z = 44.3267 }, (* C5 *)
+ { x = 38.7473; y = 15.5229; z = 45.2609 }, (* C6 *)
+ (A (
+ { x = 39.3720; y = 16.6649; z = 45.0297 }, (* N6 *)
+ { x = 39.1079; y = 14.3351; z = 43.0223 }, (* N7 *)
+ { x = 38.0132; y = 12.4868; z = 43.6280 }, (* N9 *)
+ { x = 38.7058; y = 13.1402; z = 42.6620 }, (* C8 *)
+ { x = 37.0731; y = 14.0857; z = 47.7306 }, (* H2 *)
+ { x = 39.8113; y = 16.8281; z = 44.1350 }, (* H61 *)
+ { x = 39.4100; y = 17.3741; z = 45.7478 }, (* H62 *)
+ { x = 39.0412; y = 12.9660; z = 41.6397 }) (* H8 *)
+ )
+ )
+
+let rA10
+ = N(
+ { a=0.7063; b=0.6317; c= -0.3196; (* dgf_base_tfo *)
+ d= -0.0403; e= -0.4149; f= -0.9090;
+ g= -0.7068; h=0.6549; i= -0.2676;
+ tx=6.4402; ty= -52.1496; tz=30.8246 },
+ { a=0.7529; b=0.1548; c=0.6397; (* P_O3'_275_tfo *)
+ d=0.2952; e= -0.9481; f= -0.1180;
+ g=0.5882; h=0.2777; i= -0.7595;
+ tx= -58.8919; ty= -11.3095; tz=6.0866 },
+ { a= -0.0239; b=0.9667; c= -0.2546; (* P_O3'_180_tfo *)
+ d=0.9731; e= -0.0359; f= -0.2275;
+ g= -0.2290; h= -0.2532; i= -0.9399;
+ tx=3.5401; ty= -29.7913; tz=52.2796 },
+ { a= -0.8912; b= -0.4531; c=0.0242; (* P_O3'_60_tfo *)
+ d= -0.1183; e=0.1805; f= -0.9764;
+ g=0.4380; h= -0.8730; i= -0.2145;
+ tx=19.9023; ty=54.8054; tz=15.2799 },
+ { x = 41.8210; y = 8.3880; z = 43.5890 }, (* P *)
+ { x = 42.5400; y = 8.0450; z = 44.8330 }, (* O1P *)
+ { x = 42.2470; y = 9.6920; z = 42.9910 }, (* O2P *)
+ { x = 40.2550; y = 8.2030; z = 43.7340 }, (* O5' *)
+ { x = 39.4850; y = 8.9301; z = 44.6977 }, (* C5' *)
+ { x = 39.0638; y = 9.8199; z = 44.2296 }, (* H5' *)
+ { x = 40.0757; y = 9.0713; z = 45.6029 }, (* H5'' *)
+ { x = 38.3102; y = 8.0414; z = 45.0789 }, (* C4' *)
+ { x = 37.7099; y = 7.8166; z = 44.1973 }, (* H4' *)
+ { x = 38.8012; y = 6.8321; z = 45.6380 }, (* O4' *)
+ { x = 38.2431; y = 6.6413; z = 46.9529 }, (* C1' *)
+ { x = 37.3505; y = 6.0262; z = 46.8385 }, (* H1' *)
+ { x = 37.8484; y = 8.0156; z = 47.4214 }, (* C2' *)
+ { x = 38.7381; y = 8.5406; z = 47.7690 }, (* H2'' *)
+ { x = 36.8286; y = 8.0368; z = 48.3701 }, (* O2' *)
+ { x = 36.8392; y = 7.3063; z = 48.9929 }, (* H2' *)
+ { x = 37.3576; y = 8.6512; z = 46.1132 }, (* C3' *)
+ { x = 37.5207; y = 9.7275; z = 46.1671 }, (* H3' *)
+ { x = 35.9985; y = 8.2392; z = 45.9032 }, (* O3' *)
+ { x = 39.9117; y = 2.2278; z = 48.8527 }, (* N1 *)
+ { x = 38.6207; y = 3.6941; z = 47.4757 }, (* N3 *)
+ { x = 38.9872; y = 2.4888; z = 47.9057 }, (* C2 *)
+ { x = 39.2961; y = 4.6720; z = 48.1174 }, (* C4 *)
+ { x = 40.2546; y = 4.5307; z = 49.0912 }, (* C5 *)
+ { x = 40.5932; y = 3.2189; z = 49.4985 }, (* C6 *)
+ (A (
+ { x = 41.4938; y = 2.9317; z = 50.4229 }, (* N6 *)
+ { x = 40.7195; y = 5.7755; z = 49.5060 }, (* N7 *)
+ { x = 39.1730; y = 6.0305; z = 47.9170 }, (* N9 *)
+ { x = 40.0413; y = 6.6250; z = 48.7728 }, (* C8 *)
+ { x = 38.5257; y = 1.5960; z = 47.4838 }, (* H2 *)
+ { x = 41.9907; y = 3.6753; z = 50.8921 }, (* H61 *)
+ { x = 41.6848; y = 1.9687; z = 50.6599 }, (* H62 *)
+ { x = 40.3571; y = 7.6321; z = 49.0452 }) (* H8 *)
+ )
+ )
+
+let rAs = [rA01;rA02;rA03;rA04;rA05;rA06;rA07;rA08;rA09;rA10]
+
+let rC
+ = N(
+ { a= -0.0359; b= -0.8071; c=0.5894; (* dgf_base_tfo *)
+ d= -0.2669; e=0.5761; f=0.7726;
+ g= -0.9631; h= -0.1296; i= -0.2361;
+ tx=0.1584; ty=8.3434; tz=0.5434 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 5.2430; y = -8.2420; z = 2.8260 }, (* C5' *)
+ { x = 5.1974; y = -8.8497; z = 1.9223 }, (* H5' *)
+ { x = 5.5548; y = -8.7348; z = 3.7469 }, (* H5'' *)
+ { x = 6.3140; y = -7.2060; z = 2.5510 }, (* C4' *)
+ { x = 7.2954; y = -7.6762; z = 2.4898 }, (* H4' *)
+ { x = 6.0140; y = -6.5420; z = 1.2890 }, (* O4' *)
+ { x = 6.4190; y = -5.1840; z = 1.3620 }, (* C1' *)
+ { x = 7.1608; y = -5.0495; z = 0.5747 }, (* H1' *)
+ { x = 7.0760; y = -4.9560; z = 2.7270 }, (* C2' *)
+ { x = 6.7770; y = -3.9803; z = 3.1099 }, (* H2'' *)
+ { x = 8.4500; y = -5.1930; z = 2.5810 }, (* O2' *)
+ { x = 8.8309; y = -4.8755; z = 1.7590 }, (* H2' *)
+ { x = 6.4060; y = -6.0590; z = 3.5580 }, (* C3' *)
+ { x = 5.4021; y = -5.7313; z = 3.8281 }, (* H3' *)
+ { x = 7.1570; y = -6.4240; z = 4.7070 }, (* O3' *)
+ { x = 5.2170; y = -4.3260; z = 1.1690 }, (* N1 *)
+ { x = 4.2960; y = -2.2560; z = 0.6290 }, (* N3 *)
+ { x = 5.4330; y = -3.0200; z = 0.7990 }, (* C2 *)
+ { x = 2.9930; y = -2.6780; z = 0.7940 }, (* C4 *)
+ { x = 2.8670; y = -4.0630; z = 1.1830 }, (* C5 *)
+ { x = 3.9570; y = -4.8300; z = 1.3550 }, (* C6 *)
+ (C (
+ { x = 2.0187; y = -1.8047; z = 0.5874 }, (* N4 *)
+ { x = 6.5470; y = -2.5560; z = 0.6290 }, (* O2 *)
+ { x = 1.0684; y = -2.1236; z = 0.7109 }, (* H41 *)
+ { x = 2.2344; y = -0.8560; z = 0.3162 }, (* H42 *)
+ { x = 1.8797; y = -4.4972; z = 1.3404 }, (* H5 *)
+ { x = 3.8479; y = -5.8742; z = 1.6480 }) (* H6 *)
+ )
+ )
+
+let rC01
+ = N(
+ { a= -0.0137; b= -0.8012; c=0.5983; (* dgf_base_tfo *)
+ d= -0.2523; e=0.5817; f=0.7733;
+ g= -0.9675; h= -0.1404; i= -0.2101;
+ tx=0.2031; ty=8.3874; tz=0.4228 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 5.2416; y = -8.2422; z = 2.8181 }, (* C5' *)
+ { x = 5.2050; y = -8.8128; z = 1.8901 }, (* H5' *)
+ { x = 5.5368; y = -8.7738; z = 3.7227 }, (* H5'' *)
+ { x = 6.3232; y = -7.2037; z = 2.6002 }, (* C4' *)
+ { x = 7.3048; y = -7.6757; z = 2.5577 }, (* H4' *)
+ { x = 6.0635; y = -6.5092; z = 1.3456 }, (* O4' *)
+ { x = 6.4697; y = -5.1547; z = 1.4629 }, (* C1' *)
+ { x = 7.2354; y = -5.0043; z = 0.7018 }, (* H1' *)
+ { x = 7.0856; y = -4.9610; z = 2.8521 }, (* C2' *)
+ { x = 6.7777; y = -3.9935; z = 3.2487 }, (* H2'' *)
+ { x = 8.4627; y = -5.1992; z = 2.7423 }, (* O2' *)
+ { x = 8.8693; y = -4.8638; z = 1.9399 }, (* H2' *)
+ { x = 6.3877; y = -6.0809; z = 3.6362 }, (* C3' *)
+ { x = 5.3770; y = -5.7562; z = 3.8834 }, (* H3' *)
+ { x = 7.1024; y = -6.4754; z = 4.7985 }, (* O3' *)
+ { x = 5.2764; y = -4.2883; z = 1.2538 }, (* N1 *)
+ { x = 4.3777; y = -2.2062; z = 0.7229 }, (* N3 *)
+ { x = 5.5069; y = -2.9779; z = 0.9088 }, (* C2 *)
+ { x = 3.0693; y = -2.6246; z = 0.8500 }, (* C4 *)
+ { x = 2.9279; y = -4.0146; z = 1.2149 }, (* C5 *)
+ { x = 4.0101; y = -4.7892; z = 1.4017 }, (* C6 *)
+ (C (
+ { x = 2.1040; y = -1.7437; z = 0.6331 }, (* N4 *)
+ { x = 6.6267; y = -2.5166; z = 0.7728 }, (* O2 *)
+ { x = 1.1496; y = -2.0600; z = 0.7287 }, (* H41 *)
+ { x = 2.3303; y = -0.7921; z = 0.3815 }, (* H42 *)
+ { x = 1.9353; y = -4.4465; z = 1.3419 }, (* H5 *)
+ { x = 3.8895; y = -5.8371; z = 1.6762 }) (* H6 *)
+ )
+ )
+
+let rC02
+ = N(
+ { a=0.5141; b=0.0246; c=0.8574; (* dgf_base_tfo *)
+ d= -0.5547; e= -0.7529; f=0.3542;
+ g=0.6542; h= -0.6577; i= -0.3734;
+ tx= -9.1111; ty= -3.4598; tz= -3.2939 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 4.3825; y = -6.6585; z = 4.0489 }, (* C5' *)
+ { x = 4.6841; y = -7.2019; z = 4.9443 }, (* H5' *)
+ { x = 3.6189; y = -5.8889; z = 4.1625 }, (* H5'' *)
+ { x = 5.6255; y = -5.9175; z = 3.5998 }, (* C4' *)
+ { x = 5.8732; y = -5.1228; z = 4.3034 }, (* H4' *)
+ { x = 6.7337; y = -6.8605; z = 3.5222 }, (* O4' *)
+ { x = 7.5932; y = -6.4923; z = 2.4548 }, (* C1' *)
+ { x = 8.5661; y = -6.2983; z = 2.9064 }, (* H1' *)
+ { x = 7.0527; y = -5.2012; z = 1.8322 }, (* C2' *)
+ { x = 7.1627; y = -5.2525; z = 0.7490 }, (* H2'' *)
+ { x = 7.6666; y = -4.1249; z = 2.4880 }, (* O2' *)
+ { x = 8.5944; y = -4.2543; z = 2.6981 }, (* H2' *)
+ { x = 5.5661; y = -5.3029; z = 2.2009 }, (* C3' *)
+ { x = 5.0841; y = -6.0018; z = 1.5172 }, (* H3' *)
+ { x = 4.9062; y = -4.0452; z = 2.2042 }, (* O3' *)
+ { x = 7.6298; y = -7.6136; z = 1.4752 }, (* N1 *)
+ { x = 8.6945; y = -8.7046; z = -0.2857 }, (* N3 *)
+ { x = 8.6943; y = -7.6514; z = 0.6066 }, (* C2 *)
+ { x = 7.7426; y = -9.6987; z = -0.3801 }, (* C4 *)
+ { x = 6.6642; y = -9.5742; z = 0.5722 }, (* C5 *)
+ { x = 6.6391; y = -8.5592; z = 1.4526 }, (* C6 *)
+ (C (
+ { x = 7.9033; y = -10.6371; z = -1.3010 }, (* N4 *)
+ { x = 9.5840; y = -6.8186; z = 0.6136 }, (* O2 *)
+ { x = 7.2009; y = -11.3604; z = -1.3619 }, (* H41 *)
+ { x = 8.7058; y = -10.6168; z = -1.9140 }, (* H42 *)
+ { x = 5.8585; y = -10.3083; z = 0.5822 }, (* H5 *)
+ { x = 5.8197; y = -8.4773; z = 2.1667 }) (* H6 *)
+ )
+ )
+
+let rC03
+ = N(
+ { a= -0.4993; b=0.0476; c=0.8651; (* dgf_base_tfo *)
+ d=0.8078; e= -0.3353; f=0.4847;
+ g=0.3132; h=0.9409; i=0.1290;
+ tx=6.2989; ty= -5.2303; tz= -3.8577 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 3.9938; y = -6.7042; z = 1.9023 }, (* C5' *)
+ { x = 3.2332; y = -5.9343; z = 2.0319 }, (* H5' *)
+ { x = 3.9666; y = -7.2863; z = 0.9812 }, (* H5'' *)
+ { x = 5.3098; y = -5.9546; z = 1.8564 }, (* C4' *)
+ { x = 5.3863; y = -5.3702; z = 0.9395 }, (* H4' *)
+ { x = 5.3851; y = -5.0642; z = 3.0076 }, (* O4' *)
+ { x = 6.7315; y = -4.9724; z = 3.4462 }, (* C1' *)
+ { x = 7.0033; y = -3.9202; z = 3.3619 }, (* H1' *)
+ { x = 7.5997; y = -5.8018; z = 2.4948 }, (* C2' *)
+ { x = 8.3627; y = -6.3254; z = 3.0707 }, (* H2'' *)
+ { x = 8.0410; y = -4.9501; z = 1.4724 }, (* O2' *)
+ { x = 8.2781; y = -4.0644; z = 1.7570 }, (* H2' *)
+ { x = 6.5701; y = -6.8129; z = 1.9714 }, (* C3' *)
+ { x = 6.4186; y = -7.5809; z = 2.7299 }, (* H3' *)
+ { x = 6.9357; y = -7.3841; z = 0.7235 }, (* O3' *)
+ { x = 6.8024; y = -5.4718; z = 4.8475 }, (* N1 *)
+ { x = 7.9218; y = -5.5700; z = 6.8877 }, (* N3 *)
+ { x = 7.8908; y = -5.0886; z = 5.5944 }, (* C2 *)
+ { x = 6.9789; y = -6.3827; z = 7.4823 }, (* C4 *)
+ { x = 5.8742; y = -6.7319; z = 6.6202 }, (* C5 *)
+ { x = 5.8182; y = -6.2769; z = 5.3570 }, (* C6 *)
+ (C (
+ { x = 7.1702; y = -6.7511; z = 8.7402 }, (* N4 *)
+ { x = 8.7747; y = -4.3728; z = 5.1568 }, (* O2 *)
+ { x = 6.4741; y = -7.3461; z = 9.1662 }, (* H41 *)
+ { x = 7.9889; y = -6.4396; z = 9.2429 }, (* H42 *)
+ { x = 5.0736; y = -7.3713; z = 6.9922 }, (* H5 *)
+ { x = 4.9784; y = -6.5473; z = 4.7170 }) (* H6 *)
+ )
+ )
+
+let rC04
+ = N(
+ { a= -0.5669; b= -0.8012; c=0.1918; (* dgf_base_tfo *)
+ d= -0.8129; e=0.5817; f=0.0273;
+ g= -0.1334; h= -0.1404; i= -0.9811;
+ tx= -0.3279; ty=8.3874; tz=0.3355 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 5.2416; y = -8.2422; z = 2.8181 }, (* C5' *)
+ { x = 5.2050; y = -8.8128; z = 1.8901 }, (* H5' *)
+ { x = 5.5368; y = -8.7738; z = 3.7227 }, (* H5'' *)
+ { x = 6.3232; y = -7.2037; z = 2.6002 }, (* C4' *)
+ { x = 7.3048; y = -7.6757; z = 2.5577 }, (* H4' *)
+ { x = 6.0635; y = -6.5092; z = 1.3456 }, (* O4' *)
+ { x = 6.4697; y = -5.1547; z = 1.4629 }, (* C1' *)
+ { x = 7.2354; y = -5.0043; z = 0.7018 }, (* H1' *)
+ { x = 7.0856; y = -4.9610; z = 2.8521 }, (* C2' *)
+ { x = 6.7777; y = -3.9935; z = 3.2487 }, (* H2'' *)
+ { x = 8.4627; y = -5.1992; z = 2.7423 }, (* O2' *)
+ { x = 8.8693; y = -4.8638; z = 1.9399 }, (* H2' *)
+ { x = 6.3877; y = -6.0809; z = 3.6362 }, (* C3' *)
+ { x = 5.3770; y = -5.7562; z = 3.8834 }, (* H3' *)
+ { x = 7.1024; y = -6.4754; z = 4.7985 }, (* O3' *)
+ { x = 5.2764; y = -4.2883; z = 1.2538 }, (* N1 *)
+ { x = 3.8961; y = -3.0896; z = -0.1893 }, (* N3 *)
+ { x = 5.0095; y = -3.8907; z = -0.0346 }, (* C2 *)
+ { x = 3.0480; y = -2.6632; z = 0.8116 }, (* C4 *)
+ { x = 3.4093; y = -3.1310; z = 2.1292 }, (* C5 *)
+ { x = 4.4878; y = -3.9124; z = 2.3088 }, (* C6 *)
+ (C (
+ { x = 2.0216; y = -1.8941; z = 0.4804 }, (* N4 *)
+ { x = 5.7005; y = -4.2164; z = -0.9842 }, (* O2 *)
+ { x = 1.4067; y = -1.5873; z = 1.2205 }, (* H41 *)
+ { x = 1.8721; y = -1.6319; z = -0.4835 }, (* H42 *)
+ { x = 2.8048; y = -2.8507; z = 2.9918 }, (* H5 *)
+ { x = 4.7491; y = -4.2593; z = 3.3085 }) (* H6 *)
+ )
+ )
+
+let rC05
+ = N(
+ { a= -0.6298; b=0.0246; c=0.7763; (* dgf_base_tfo *)
+ d= -0.5226; e= -0.7529; f= -0.4001;
+ g=0.5746; h= -0.6577; i=0.4870;
+ tx= -0.0208; ty= -3.4598; tz= -9.6882 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 4.3825; y = -6.6585; z = 4.0489 }, (* C5' *)
+ { x = 4.6841; y = -7.2019; z = 4.9443 }, (* H5' *)
+ { x = 3.6189; y = -5.8889; z = 4.1625 }, (* H5'' *)
+ { x = 5.6255; y = -5.9175; z = 3.5998 }, (* C4' *)
+ { x = 5.8732; y = -5.1228; z = 4.3034 }, (* H4' *)
+ { x = 6.7337; y = -6.8605; z = 3.5222 }, (* O4' *)
+ { x = 7.5932; y = -6.4923; z = 2.4548 }, (* C1' *)
+ { x = 8.5661; y = -6.2983; z = 2.9064 }, (* H1' *)
+ { x = 7.0527; y = -5.2012; z = 1.8322 }, (* C2' *)
+ { x = 7.1627; y = -5.2525; z = 0.7490 }, (* H2'' *)
+ { x = 7.6666; y = -4.1249; z = 2.4880 }, (* O2' *)
+ { x = 8.5944; y = -4.2543; z = 2.6981 }, (* H2' *)
+ { x = 5.5661; y = -5.3029; z = 2.2009 }, (* C3' *)
+ { x = 5.0841; y = -6.0018; z = 1.5172 }, (* H3' *)
+ { x = 4.9062; y = -4.0452; z = 2.2042 }, (* O3' *)
+ { x = 7.6298; y = -7.6136; z = 1.4752 }, (* N1 *)
+ { x = 8.5977; y = -9.5977; z = 0.7329 }, (* N3 *)
+ { x = 8.5951; y = -8.5745; z = 1.6594 }, (* C2 *)
+ { x = 7.7372; y = -9.7371; z = -0.3364 }, (* C4 *)
+ { x = 6.7596; y = -8.6801; z = -0.4476 }, (* C5 *)
+ { x = 6.7338; y = -7.6721; z = 0.4408 }, (* C6 *)
+ (C (
+ { x = 7.8849; y = -10.7881; z = -1.1289 }, (* N4 *)
+ { x = 9.3993; y = -8.5377; z = 2.5743 }, (* O2 *)
+ { x = 7.2499; y = -10.8809; z = -1.9088 }, (* H41 *)
+ { x = 8.6122; y = -11.4649; z = -0.9468 }, (* H42 *)
+ { x = 6.0317; y = -8.6941; z = -1.2588 }, (* H5 *)
+ { x = 5.9901; y = -6.8809; z = 0.3459 }) (* H6 *)
+ )
+ )
+
+let rC06
+ = N(
+ { a= -0.9837; b=0.0476; c= -0.1733; (* dgf_base_tfo *)
+ d= -0.1792; e= -0.3353; f=0.9249;
+ g= -0.0141; h=0.9409; i=0.3384;
+ tx=5.7793; ty= -5.2303; tz=4.5997 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 3.9938; y = -6.7042; z = 1.9023 }, (* C5' *)
+ { x = 3.2332; y = -5.9343; z = 2.0319 }, (* H5' *)
+ { x = 3.9666; y = -7.2863; z = 0.9812 }, (* H5'' *)
+ { x = 5.3098; y = -5.9546; z = 1.8564 }, (* C4' *)
+ { x = 5.3863; y = -5.3702; z = 0.9395 }, (* H4' *)
+ { x = 5.3851; y = -5.0642; z = 3.0076 }, (* O4' *)
+ { x = 6.7315; y = -4.9724; z = 3.4462 }, (* C1' *)
+ { x = 7.0033; y = -3.9202; z = 3.3619 }, (* H1' *)
+ { x = 7.5997; y = -5.8018; z = 2.4948 }, (* C2' *)
+ { x = 8.3627; y = -6.3254; z = 3.0707 }, (* H2'' *)
+ { x = 8.0410; y = -4.9501; z = 1.4724 }, (* O2' *)
+ { x = 8.2781; y = -4.0644; z = 1.7570 }, (* H2' *)
+ { x = 6.5701; y = -6.8129; z = 1.9714 }, (* C3' *)
+ { x = 6.4186; y = -7.5809; z = 2.7299 }, (* H3' *)
+ { x = 6.9357; y = -7.3841; z = 0.7235 }, (* O3' *)
+ { x = 6.8024; y = -5.4718; z = 4.8475 }, (* N1 *)
+ { x = 6.6920; y = -5.0495; z = 7.1354 }, (* N3 *)
+ { x = 6.6201; y = -4.5500; z = 5.8506 }, (* C2 *)
+ { x = 6.9254; y = -6.3614; z = 7.4926 }, (* C4 *)
+ { x = 7.1046; y = -7.2543; z = 6.3718 }, (* C5 *)
+ { x = 7.0391; y = -6.7951; z = 5.1106 }, (* C6 *)
+ (C (
+ { x = 6.9614; y = -6.6648; z = 8.7815 }, (* N4 *)
+ { x = 6.4083; y = -3.3696; z = 5.6340 }, (* O2 *)
+ { x = 7.1329; y = -7.6280; z = 9.0324 }, (* H41 *)
+ { x = 6.8204; y = -5.9469; z = 9.4777 }, (* H42 *)
+ { x = 7.2954; y = -8.3135; z = 6.5440 }, (* H5 *)
+ { x = 7.1753; y = -7.4798; z = 4.2735 }) (* H6 *)
+ )
+ )
+
+let rC07
+ = N(
+ { a=0.0033; b=0.2720; c= -0.9623; (* dgf_base_tfo *)
+ d=0.3013; e= -0.9179; f= -0.2584;
+ g= -0.9535; h= -0.2891; i= -0.0850;
+ tx=43.0403; ty=13.7233; tz=34.5710 },
+ { a=0.9187; b=0.2887; c=0.2694; (* P_O3'_275_tfo *)
+ d=0.0302; e= -0.7316; f=0.6811;
+ g=0.3938; h= -0.6176; i= -0.6808;
+ tx= -48.4330; ty=26.3254; tz=13.6383 },
+ { a= -0.1504; b=0.7744; c= -0.6145; (* P_O3'_180_tfo *)
+ d=0.7581; e=0.4893; f=0.4311;
+ g=0.6345; h= -0.4010; i= -0.6607;
+ tx= -31.9784; ty= -13.4285; tz=44.9650 },
+ { a= -0.6236; b= -0.7810; c= -0.0337; (* P_O3'_60_tfo *)
+ d= -0.6890; e=0.5694; f= -0.4484;
+ g=0.3694; h= -0.2564; i= -0.8932;
+ tx=12.1105; ty=30.8774; tz=46.0946 },
+ { x = 33.3400; y = 11.0980; z = 46.1750 }, (* P *)
+ { x = 34.5130; y = 10.2320; z = 46.4660 }, (* O1P *)
+ { x = 33.4130; y = 12.3960; z = 46.9340 }, (* O2P *)
+ { x = 31.9810; y = 10.3390; z = 46.4820 }, (* O5' *)
+ { x = 30.8152; y = 11.1619; z = 46.2003 }, (* C5' *)
+ { x = 30.4519; y = 10.9454; z = 45.1957 }, (* H5' *)
+ { x = 31.0379; y = 12.2016; z = 46.4400 }, (* H5'' *)
+ { x = 29.7081; y = 10.7448; z = 47.1428 }, (* C4' *)
+ { x = 28.8710; y = 11.4416; z = 47.0982 }, (* H4' *)
+ { x = 29.2550; y = 9.4394; z = 46.8162 }, (* O4' *)
+ { x = 29.3907; y = 8.5625; z = 47.9460 }, (* C1' *)
+ { x = 28.4416; y = 8.5669; z = 48.4819 }, (* H1' *)
+ { x = 30.4468; y = 9.2031; z = 48.7952 }, (* C2' *)
+ { x = 31.4222; y = 8.9651; z = 48.3709 }, (* H2'' *)
+ { x = 30.3701; y = 8.9157; z = 50.1624 }, (* O2' *)
+ { x = 30.0652; y = 8.0304; z = 50.3740 }, (* H2' *)
+ { x = 30.1622; y = 10.6879; z = 48.6120 }, (* C3' *)
+ { x = 31.0952; y = 11.2399; z = 48.7254 }, (* H3' *)
+ { x = 29.1076; y = 11.1535; z = 49.4702 }, (* O3' *)
+ { x = 29.7883; y = 7.2209; z = 47.5235 }, (* N1 *)
+ { x = 29.1825; y = 5.0438; z = 46.8275 }, (* N3 *)
+ { x = 28.8008; y = 6.2912; z = 47.2263 }, (* C2 *)
+ { x = 30.4888; y = 4.6890; z = 46.7186 }, (* C4 *)
+ { x = 31.5034; y = 5.6405; z = 47.0249 }, (* C5 *)
+ { x = 31.1091; y = 6.8691; z = 47.4156 }, (* C6 *)
+ (C (
+ { x = 30.8109; y = 3.4584; z = 46.3336 }, (* N4 *)
+ { x = 27.6171; y = 6.5989; z = 47.3189 }, (* O2 *)
+ { x = 31.7923; y = 3.2301; z = 46.2638 }, (* H41 *)
+ { x = 30.0880; y = 2.7857; z = 46.1215 }, (* H42 *)
+ { x = 32.5542; y = 5.3634; z = 46.9395 }, (* H5 *)
+ { x = 31.8523; y = 7.6279; z = 47.6603 }) (* H6 *)
+ )
+ )
+
+let rC08
+ = N(
+ { a=0.0797; b= -0.6026; c= -0.7941; (* dgf_base_tfo *)
+ d=0.7939; e=0.5201; f= -0.3150;
+ g=0.6028; h= -0.6054; i=0.5198;
+ tx= -36.8341; ty=41.5293; tz=1.6628 },
+ { a=0.9187; b=0.2887; c=0.2694; (* P_O3'_275_tfo *)
+ d=0.0302; e= -0.7316; f=0.6811;
+ g=0.3938; h= -0.6176; i= -0.6808;
+ tx= -48.4330; ty=26.3254; tz=13.6383 },
+ { a= -0.1504; b=0.7744; c= -0.6145; (* P_O3'_180_tfo *)
+ d=0.7581; e=0.4893; f=0.4311;
+ g=0.6345; h= -0.4010; i= -0.6607;
+ tx= -31.9784; ty= -13.4285; tz=44.9650 },
+ { a= -0.6236; b= -0.7810; c= -0.0337; (* P_O3'_60_tfo *)
+ d= -0.6890; e=0.5694; f= -0.4484;
+ g=0.3694; h= -0.2564; i= -0.8932;
+ tx=12.1105; ty=30.8774; tz=46.0946 },
+ { x = 33.3400; y = 11.0980; z = 46.1750 }, (* P *)
+ { x = 34.5130; y = 10.2320; z = 46.4660 }, (* O1P *)
+ { x = 33.4130; y = 12.3960; z = 46.9340 }, (* O2P *)
+ { x = 31.9810; y = 10.3390; z = 46.4820 }, (* O5' *)
+ { x = 31.8779; y = 9.9369; z = 47.8760 }, (* C5' *)
+ { x = 31.3239; y = 10.6931; z = 48.4322 }, (* H5' *)
+ { x = 32.8647; y = 9.6624; z = 48.2489 }, (* H5'' *)
+ { x = 31.0429; y = 8.6773; z = 47.9401 }, (* C4' *)
+ { x = 31.0779; y = 8.2331; z = 48.9349 }, (* H4' *)
+ { x = 29.6956; y = 8.9669; z = 47.5983 }, (* O4' *)
+ { x = 29.2784; y = 8.1700; z = 46.4782 }, (* C1' *)
+ { x = 28.8006; y = 7.2731; z = 46.8722 }, (* H1' *)
+ { x = 30.5544; y = 7.7940; z = 45.7875 }, (* C2' *)
+ { x = 30.8837; y = 8.6410; z = 45.1856 }, (* H2'' *)
+ { x = 30.5100; y = 6.6007; z = 45.0582 }, (* O2' *)
+ { x = 29.6694; y = 6.4168; z = 44.6326 }, (* H2' *)
+ { x = 31.5146; y = 7.5954; z = 46.9527 }, (* C3' *)
+ { x = 32.5255; y = 7.8261; z = 46.6166 }, (* H3' *)
+ { x = 31.3876; y = 6.2951; z = 47.5516 }, (* O3' *)
+ { x = 28.3976; y = 8.9302; z = 45.5933 }, (* N1 *)
+ { x = 26.2155; y = 9.6135; z = 44.9910 }, (* N3 *)
+ { x = 27.0281; y = 8.8961; z = 45.8192 }, (* C2 *)
+ { x = 26.7044; y = 10.3489; z = 43.9595 }, (* C4 *)
+ { x = 28.1088; y = 10.3837; z = 43.7247 }, (* C5 *)
+ { x = 28.8978; y = 9.6708; z = 44.5535 }, (* C6 *)
+ (C (
+ { x = 25.8715; y = 11.0249; z = 43.1749 }, (* N4 *)
+ { x = 26.5733; y = 8.2371; z = 46.7484 }, (* O2 *)
+ { x = 26.2707; y = 11.5609; z = 42.4177 }, (* H41 *)
+ { x = 24.8760; y = 10.9939; z = 43.3427 }, (* H42 *)
+ { x = 28.5089; y = 10.9722; z = 42.8990 }, (* H5 *)
+ { x = 29.9782; y = 9.6687; z = 44.4097 }) (* H6 *)
+ )
+ )
+
+let rC09
+ = N(
+ { a=0.8727; b=0.4760; c= -0.1091; (* dgf_base_tfo *)
+ d= -0.4188; e=0.6148; f= -0.6682;
+ g= -0.2510; h=0.6289; i=0.7359;
+ tx= -8.1687; ty= -52.0761; tz= -25.0726 },
+ { a=0.9187; b=0.2887; c=0.2694; (* P_O3'_275_tfo *)
+ d=0.0302; e= -0.7316; f=0.6811;
+ g=0.3938; h= -0.6176; i= -0.6808;
+ tx= -48.4330; ty=26.3254; tz=13.6383 },
+ { a= -0.1504; b=0.7744; c= -0.6145; (* P_O3'_180_tfo *)
+ d=0.7581; e=0.4893; f=0.4311;
+ g=0.6345; h= -0.4010; i= -0.6607;
+ tx= -31.9784; ty= -13.4285; tz=44.9650 },
+ { a= -0.6236; b= -0.7810; c= -0.0337; (* P_O3'_60_tfo *)
+ d= -0.6890; e=0.5694; f= -0.4484;
+ g=0.3694; h= -0.2564; i= -0.8932;
+ tx=12.1105; ty=30.8774; tz=46.0946 },
+ { x = 33.3400; y = 11.0980; z = 46.1750 }, (* P *)
+ { x = 34.5130; y = 10.2320; z = 46.4660 }, (* O1P *)
+ { x = 33.4130; y = 12.3960; z = 46.9340 }, (* O2P *)
+ { x = 31.9810; y = 10.3390; z = 46.4820 }, (* O5' *)
+ { x = 30.8152; y = 11.1619; z = 46.2003 }, (* C5' *)
+ { x = 30.4519; y = 10.9454; z = 45.1957 }, (* H5' *)
+ { x = 31.0379; y = 12.2016; z = 46.4400 }, (* H5'' *)
+ { x = 29.7081; y = 10.7448; z = 47.1428 }, (* C4' *)
+ { x = 29.4506; y = 9.6945; z = 47.0059 }, (* H4' *)
+ { x = 30.1045; y = 10.9634; z = 48.4885 }, (* O4' *)
+ { x = 29.1794; y = 11.8418; z = 49.1490 }, (* C1' *)
+ { x = 28.4388; y = 11.2210; z = 49.6533 }, (* H1' *)
+ { x = 28.5211; y = 12.6008; z = 48.0367 }, (* C2' *)
+ { x = 29.1947; y = 13.3949; z = 47.7147 }, (* H2'' *)
+ { x = 27.2316; y = 13.0683; z = 48.3134 }, (* O2' *)
+ { x = 27.0851; y = 13.3391; z = 49.2227 }, (* H2' *)
+ { x = 28.4131; y = 11.5507; z = 46.9391 }, (* C3' *)
+ { x = 28.4451; y = 12.0512; z = 45.9713 }, (* H3' *)
+ { x = 27.2707; y = 10.6955; z = 47.1097 }, (* O3' *)
+ { x = 29.8751; y = 12.7405; z = 50.0682 }, (* N1 *)
+ { x = 30.7172; y = 13.1841; z = 52.2328 }, (* N3 *)
+ { x = 30.0617; y = 12.3404; z = 51.3847 }, (* C2 *)
+ { x = 31.1834; y = 14.3941; z = 51.8297 }, (* C4 *)
+ { x = 30.9913; y = 14.8074; z = 50.4803 }, (* C5 *)
+ { x = 30.3434; y = 13.9610; z = 49.6548 }, (* C6 *)
+ (C (
+ { x = 31.8090; y = 15.1847; z = 52.6957 }, (* N4 *)
+ { x = 29.6470; y = 11.2494; z = 51.7616 }, (* O2 *)
+ { x = 32.1422; y = 16.0774; z = 52.3606 }, (* H41 *)
+ { x = 31.9392; y = 14.8893; z = 53.6527 }, (* H42 *)
+ { x = 31.3632; y = 15.7771; z = 50.1491 }, (* H5 *)
+ { x = 30.1742; y = 14.2374; z = 48.6141 }) (* H6 *)
+ )
+ )
+
+let rC10
+ = N(
+ { a=0.1549; b=0.8710; c= -0.4663; (* dgf_base_tfo *)
+ d=0.6768; e= -0.4374; f= -0.5921;
+ g= -0.7197; h= -0.2239; i= -0.6572;
+ tx=25.2447; ty= -14.1920; tz=50.3201 },
+ { a=0.9187; b=0.2887; c=0.2694; (* P_O3'_275_tfo *)
+ d=0.0302; e= -0.7316; f=0.6811;
+ g=0.3938; h= -0.6176; i= -0.6808;
+ tx= -48.4330; ty=26.3254; tz=13.6383 },
+ { a= -0.1504; b=0.7744; c= -0.6145; (* P_O3'_180_tfo *)
+ d=0.7581; e=0.4893; f=0.4311;
+ g=0.6345; h= -0.4010; i= -0.6607;
+ tx= -31.9784; ty= -13.4285; tz=44.9650 },
+ { a= -0.6236; b= -0.7810; c= -0.0337; (* P_O3'_60_tfo *)
+ d= -0.6890; e=0.5694; f= -0.4484;
+ g=0.3694; h= -0.2564; i= -0.8932;
+ tx=12.1105; ty=30.8774; tz=46.0946 },
+ { x = 33.3400; y = 11.0980; z = 46.1750 }, (* P *)
+ { x = 34.5130; y = 10.2320; z = 46.4660 }, (* O1P *)
+ { x = 33.4130; y = 12.3960; z = 46.9340 }, (* O2P *)
+ { x = 31.9810; y = 10.3390; z = 46.4820 }, (* O5' *)
+ { x = 31.8779; y = 9.9369; z = 47.8760 }, (* C5' *)
+ { x = 31.3239; y = 10.6931; z = 48.4322 }, (* H5' *)
+ { x = 32.8647; y = 9.6624; z = 48.2489 }, (* H5'' *)
+ { x = 31.0429; y = 8.6773; z = 47.9401 }, (* C4' *)
+ { x = 30.0440; y = 8.8473; z = 47.5383 }, (* H4' *)
+ { x = 31.6749; y = 7.6351; z = 47.2119 }, (* O4' *)
+ { x = 31.9159; y = 6.5022; z = 48.0616 }, (* C1' *)
+ { x = 31.0691; y = 5.8243; z = 47.9544 }, (* H1' *)
+ { x = 31.9300; y = 7.0685; z = 49.4493 }, (* C2' *)
+ { x = 32.9024; y = 7.5288; z = 49.6245 }, (* H2'' *)
+ { x = 31.5672; y = 6.1750; z = 50.4632 }, (* O2' *)
+ { x = 31.8416; y = 5.2663; z = 50.3200 }, (* H2' *)
+ { x = 30.8618; y = 8.1514; z = 49.3749 }, (* C3' *)
+ { x = 31.1122; y = 8.9396; z = 50.0850 }, (* H3' *)
+ { x = 29.5351; y = 7.6245; z = 49.5409 }, (* O3' *)
+ { x = 33.1890; y = 5.8629; z = 47.7343 }, (* N1 *)
+ { x = 34.4004; y = 4.2636; z = 46.4828 }, (* N3 *)
+ { x = 33.2062; y = 4.8497; z = 46.7851 }, (* C2 *)
+ { x = 35.5600; y = 4.6374; z = 47.0822 }, (* C4 *)
+ { x = 35.5444; y = 5.6751; z = 48.0577 }, (* C5 *)
+ { x = 34.3565; y = 6.2450; z = 48.3432 }, (* C6 *)
+ (C (
+ { x = 36.6977; y = 4.0305; z = 46.7598 }, (* N4 *)
+ { x = 32.1661; y = 4.5034; z = 46.2348 }, (* O2 *)
+ { x = 37.5405; y = 4.3347; z = 47.2259 }, (* H41 *)
+ { x = 36.7033; y = 3.2923; z = 46.0706 }, (* H42 *)
+ { x = 36.4713; y = 5.9811; z = 48.5428 }, (* H5 *)
+ { x = 34.2986; y = 7.0426; z = 49.0839 }) (* H6 *)
+ )
+ )
+
+let rCs = [rC01;rC02;rC03;rC04;rC05;rC06;rC07;rC08;rC09;rC10]
+
+let rG
+ = N(
+ { a= -0.0018; b= -0.8207; c=0.5714; (* dgf_base_tfo *)
+ d=0.2679; e= -0.5509; f= -0.7904;
+ g=0.9634; h=0.1517; i=0.2209;
+ tx=0.0073; ty=8.4030; tz=0.6232 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 5.4550; y = 8.2120; z = -2.8810 }, (* C5' *)
+ { x = 5.4546; y = 8.8508; z = -1.9978 }, (* H5' *)
+ { x = 5.7588; y = 8.6625; z = -3.8259 }, (* H5'' *)
+ { x = 6.4970; y = 7.1480; z = -2.5980 }, (* C4' *)
+ { x = 7.4896; y = 7.5919; z = -2.5214 }, (* H4' *)
+ { x = 6.1630; y = 6.4860; z = -1.3440 }, (* O4' *)
+ { x = 6.5400; y = 5.1200; z = -1.4190 }, (* C1' *)
+ { x = 7.2763; y = 4.9681; z = -0.6297 }, (* H1' *)
+ { x = 7.1940; y = 4.8830; z = -2.7770 }, (* C2' *)
+ { x = 6.8667; y = 3.9183; z = -3.1647 }, (* H2'' *)
+ { x = 8.5860; y = 5.0910; z = -2.6140 }, (* O2' *)
+ { x = 8.9510; y = 4.7626; z = -1.7890 }, (* H2' *)
+ { x = 6.5720; y = 6.0040; z = -3.6090 }, (* C3' *)
+ { x = 5.5636; y = 5.7066; z = -3.8966 }, (* H3' *)
+ { x = 7.3801; y = 6.3562; z = -4.7350 }, (* O3' *)
+ { x = 4.7150; y = 0.4910; z = -0.1360 }, (* N1 *)
+ { x = 6.3490; y = 2.1730; z = -0.6020 }, (* N3 *)
+ { x = 5.9530; y = 0.9650; z = -0.2670 }, (* C2 *)
+ { x = 5.2900; y = 2.9790; z = -0.8260 }, (* C4 *)
+ { x = 3.9720; y = 2.6390; z = -0.7330 }, (* C5 *)
+ { x = 3.6770; y = 1.3160; z = -0.3660 }, (* C6 *)
+ (G (
+ { x = 6.8426; y = 0.0056; z = -0.0019 }, (* N2 *)
+ { x = 3.1660; y = 3.7290; z = -1.0360 }, (* N7 *)
+ { x = 5.3170; y = 4.2990; z = -1.1930 }, (* N9 *)
+ { x = 4.0100; y = 4.6780; z = -1.2990 }, (* C8 *)
+ { x = 2.4280; y = 0.8450; z = -0.2360 }, (* O6 *)
+ { x = 4.6151; y = -0.4677; z = 0.1305 }, (* H1 *)
+ { x = 6.6463; y = -0.9463; z = 0.2729 }, (* H21 *)
+ { x = 7.8170; y = 0.2642; z = -0.0640 }, (* H22 *)
+ { x = 3.4421; y = 5.5744; z = -1.5482 }) (* H8 *)
+ )
+ )
+
+let rG01
+ = N(
+ { a= -0.0043; b= -0.8175; c=0.5759; (* dgf_base_tfo *)
+ d=0.2617; e= -0.5567; f= -0.7884;
+ g=0.9651; h=0.1473; i=0.2164;
+ tx=0.0359; ty=8.3929; tz=0.5532 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 5.4352; y = 8.2183; z = -2.7757 }, (* C5' *)
+ { x = 5.3830; y = 8.7883; z = -1.8481 }, (* H5' *)
+ { x = 5.7729; y = 8.7436; z = -3.6691 }, (* H5'' *)
+ { x = 6.4830; y = 7.1518; z = -2.5252 }, (* C4' *)
+ { x = 7.4749; y = 7.5972; z = -2.4482 }, (* H4' *)
+ { x = 6.1626; y = 6.4620; z = -1.2827 }, (* O4' *)
+ { x = 6.5431; y = 5.0992; z = -1.3905 }, (* C1' *)
+ { x = 7.2871; y = 4.9328; z = -0.6114 }, (* H1' *)
+ { x = 7.1852; y = 4.8935; z = -2.7592 }, (* C2' *)
+ { x = 6.8573; y = 3.9363; z = -3.1645 }, (* H2'' *)
+ { x = 8.5780; y = 5.1025; z = -2.6046 }, (* O2' *)
+ { x = 8.9516; y = 4.7577; z = -1.7902 }, (* H2' *)
+ { x = 6.5522; y = 6.0300; z = -3.5612 }, (* C3' *)
+ { x = 5.5420; y = 5.7356; z = -3.8459 }, (* H3' *)
+ { x = 7.3487; y = 6.4089; z = -4.6867 }, (* O3' *)
+ { x = 4.7442; y = 0.4514; z = -0.1390 }, (* N1 *)
+ { x = 6.3687; y = 2.1459; z = -0.5926 }, (* N3 *)
+ { x = 5.9795; y = 0.9335; z = -0.2657 }, (* C2 *)
+ { x = 5.3052; y = 2.9471; z = -0.8125 }, (* C4 *)
+ { x = 3.9891; y = 2.5987; z = -0.7230 }, (* C5 *)
+ { x = 3.7016; y = 1.2717; z = -0.3647 }, (* C6 *)
+ (G (
+ { x = 6.8745; y = -0.0224; z = -0.0058 }, (* N2 *)
+ { x = 3.1770; y = 3.6859; z = -1.0198 }, (* N7 *)
+ { x = 5.3247; y = 4.2695; z = -1.1710 }, (* N9 *)
+ { x = 4.0156; y = 4.6415; z = -1.2759 }, (* C8 *)
+ { x = 2.4553; y = 0.7925; z = -0.2390 }, (* O6 *)
+ { x = 4.6497; y = -0.5095; z = 0.1212 }, (* H1 *)
+ { x = 6.6836; y = -0.9771; z = 0.2627 }, (* H21 *)
+ { x = 7.8474; y = 0.2424; z = -0.0653 }, (* H22 *)
+ { x = 3.4426; y = 5.5361; z = -1.5199 }) (* H8 *)
+ )
+ )
+
+let rG02
+ = N(
+ { a=0.5566; b=0.0449; c=0.8296; (* dgf_base_tfo *)
+ d=0.5125; e=0.7673; f= -0.3854;
+ g= -0.6538; h=0.6397; i=0.4041;
+ tx= -9.1161; ty= -3.7679; tz= -2.9968 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 4.5778; y = 6.6594; z = -4.0364 }, (* C5' *)
+ { x = 4.9220; y = 7.1963; z = -4.9204 }, (* H5' *)
+ { x = 3.7996; y = 5.9091; z = -4.1764 }, (* H5'' *)
+ { x = 5.7873; y = 5.8869; z = -3.5482 }, (* C4' *)
+ { x = 6.0405; y = 5.0875; z = -4.2446 }, (* H4' *)
+ { x = 6.9135; y = 6.8036; z = -3.4310 }, (* O4' *)
+ { x = 7.7293; y = 6.4084; z = -2.3392 }, (* C1' *)
+ { x = 8.7078; y = 6.1815; z = -2.7624 }, (* H1' *)
+ { x = 7.1305; y = 5.1418; z = -1.7347 }, (* C2' *)
+ { x = 7.2040; y = 5.1982; z = -0.6486 }, (* H2'' *)
+ { x = 7.7417; y = 4.0392; z = -2.3813 }, (* O2' *)
+ { x = 8.6785; y = 4.1443; z = -2.5630 }, (* H2' *)
+ { x = 5.6666; y = 5.2728; z = -2.1536 }, (* C3' *)
+ { x = 5.1747; y = 5.9805; z = -1.4863 }, (* H3' *)
+ { x = 4.9997; y = 4.0086; z = -2.1973 }, (* O3' *)
+ { x = 10.3245; y = 8.5459; z = 1.5467 }, (* N1 *)
+ { x = 9.8051; y = 6.9432; z = -0.1497 }, (* N3 *)
+ { x = 10.5175; y = 7.4328; z = 0.8408 }, (* C2 *)
+ { x = 8.7523; y = 7.7422; z = -0.4228 }, (* C4 *)
+ { x = 8.4257; y = 8.9060; z = 0.2099 }, (* C5 *)
+ { x = 9.2665; y = 9.3242; z = 1.2540 }, (* C6 *)
+ (G (
+ { x = 11.6077; y = 6.7966; z = 1.2752 }, (* N2 *)
+ { x = 7.2750; y = 9.4537; z = -0.3428 }, (* N7 *)
+ { x = 7.7962; y = 7.5519; z = -1.3859 }, (* N9 *)
+ { x = 6.9479; y = 8.6157; z = -1.2771 }, (* C8 *)
+ { x = 9.0664; y = 10.4462; z = 1.9610 }, (* O6 *)
+ { x = 10.9838; y = 8.7524; z = 2.2697 }, (* H1 *)
+ { x = 12.2274; y = 7.0896; z = 2.0170 }, (* H21 *)
+ { x = 11.8502; y = 5.9398; z = 0.7984 }, (* H22 *)
+ { x = 6.0430; y = 8.9853; z = -1.7594 }) (* H8 *)
+ )
+ )
+
+let rG03
+ = N(
+ { a= -0.5021; b=0.0731; c=0.8617; (* dgf_base_tfo *)
+ d= -0.8112; e=0.3054; f= -0.4986;
+ g= -0.2996; h= -0.9494; i= -0.0940;
+ tx=6.4273; ty= -5.1944; tz= -3.7807 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 4.1214; y = 6.7116; z = -1.9049 }, (* C5' *)
+ { x = 3.3465; y = 5.9610; z = -2.0607 }, (* H5' *)
+ { x = 4.0789; y = 7.2928; z = -0.9837 }, (* H5'' *)
+ { x = 5.4170; y = 5.9293; z = -1.8186 }, (* C4' *)
+ { x = 5.4506; y = 5.3400; z = -0.9023 }, (* H4' *)
+ { x = 5.5067; y = 5.0417; z = -2.9703 }, (* O4' *)
+ { x = 6.8650; y = 4.9152; z = -3.3612 }, (* C1' *)
+ { x = 7.1090; y = 3.8577; z = -3.2603 }, (* H1' *)
+ { x = 7.7152; y = 5.7282; z = -2.3894 }, (* C2' *)
+ { x = 8.5029; y = 6.2356; z = -2.9463 }, (* H2'' *)
+ { x = 8.1036; y = 4.8568; z = -1.3419 }, (* O2' *)
+ { x = 8.3270; y = 3.9651; z = -1.6184 }, (* H2' *)
+ { x = 6.7003; y = 6.7565; z = -1.8911 }, (* C3' *)
+ { x = 6.5898; y = 7.5329; z = -2.6482 }, (* H3' *)
+ { x = 7.0505; y = 7.2878; z = -0.6105 }, (* O3' *)
+ { x = 9.6740; y = 4.7656; z = -7.6614 }, (* N1 *)
+ { x = 9.0739; y = 4.3013; z = -5.3941 }, (* N3 *)
+ { x = 9.8416; y = 4.2192; z = -6.4581 }, (* C2 *)
+ { x = 7.9885; y = 5.0632; z = -5.6446 }, (* C4 *)
+ { x = 7.6822; y = 5.6856; z = -6.8194 }, (* C5 *)
+ { x = 8.5831; y = 5.5215; z = -7.8840 }, (* C6 *)
+ (G (
+ { x = 10.9733; y = 3.5117; z = -6.4286 }, (* N2 *)
+ { x = 6.4857; y = 6.3816; z = -6.7035 }, (* N7 *)
+ { x = 6.9740; y = 5.3703; z = -4.7760 }, (* N9 *)
+ { x = 6.1133; y = 6.1613; z = -5.4808 }, (* C8 *)
+ { x = 8.4084; y = 6.0747; z = -9.0933 }, (* O6 *)
+ { x = 10.3759; y = 4.5855; z = -8.3504 }, (* H1 *)
+ { x = 11.6254; y = 3.3761; z = -7.1879 }, (* H21 *)
+ { x = 11.1917; y = 3.0460; z = -5.5593 }, (* H22 *)
+ { x = 5.1705; y = 6.6830; z = -5.3167 }) (* H8 *)
+ )
+ )
+
+let rG04
+ = N(
+ { a= -0.5426; b= -0.8175; c=0.1929; (* dgf_base_tfo *)
+ d=0.8304; e= -0.5567; f= -0.0237;
+ g=0.1267; h=0.1473; i=0.9809;
+ tx= -0.5075; ty=8.3929; tz=0.2229 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 5.4352; y = 8.2183; z = -2.7757 }, (* C5' *)
+ { x = 5.3830; y = 8.7883; z = -1.8481 }, (* H5' *)
+ { x = 5.7729; y = 8.7436; z = -3.6691 }, (* H5'' *)
+ { x = 6.4830; y = 7.1518; z = -2.5252 }, (* C4' *)
+ { x = 7.4749; y = 7.5972; z = -2.4482 }, (* H4' *)
+ { x = 6.1626; y = 6.4620; z = -1.2827 }, (* O4' *)
+ { x = 6.5431; y = 5.0992; z = -1.3905 }, (* C1' *)
+ { x = 7.2871; y = 4.9328; z = -0.6114 }, (* H1' *)
+ { x = 7.1852; y = 4.8935; z = -2.7592 }, (* C2' *)
+ { x = 6.8573; y = 3.9363; z = -3.1645 }, (* H2'' *)
+ { x = 8.5780; y = 5.1025; z = -2.6046 }, (* O2' *)
+ { x = 8.9516; y = 4.7577; z = -1.7902 }, (* H2' *)
+ { x = 6.5522; y = 6.0300; z = -3.5612 }, (* C3' *)
+ { x = 5.5420; y = 5.7356; z = -3.8459 }, (* H3' *)
+ { x = 7.3487; y = 6.4089; z = -4.6867 }, (* O3' *)
+ { x = 3.6343; y = 2.6680; z = 2.0783 }, (* N1 *)
+ { x = 5.4505; y = 3.9805; z = 1.2446 }, (* N3 *)
+ { x = 4.7540; y = 3.3816; z = 2.1851 }, (* C2 *)
+ { x = 4.8805; y = 3.7951; z = 0.0354 }, (* C4 *)
+ { x = 3.7416; y = 3.0925; z = -0.2305 }, (* C5 *)
+ { x = 3.0873; y = 2.4980; z = 0.8606 }, (* C6 *)
+ (G (
+ { x = 5.1433; y = 3.4373; z = 3.4609 }, (* N2 *)
+ { x = 3.4605; y = 3.1184; z = -1.5906 }, (* N7 *)
+ { x = 5.3247; y = 4.2695; z = -1.1710 }, (* N9 *)
+ { x = 4.4244; y = 3.8244; z = -2.0953 }, (* C8 *)
+ { x = 1.9600; y = 1.7805; z = 0.7462 }, (* O6 *)
+ { x = 3.2489; y = 2.2879; z = 2.9191 }, (* H1 *)
+ { x = 4.6785; y = 3.0243; z = 4.2568 }, (* H21 *)
+ { x = 5.9823; y = 3.9654; z = 3.6539 }, (* H22 *)
+ { x = 4.2675; y = 3.8876; z = -3.1721 }) (* H8 *)
+ )
+ )
+
+let rG05
+ = N(
+ { a= -0.5891; b=0.0449; c=0.8068; (* dgf_base_tfo *)
+ d=0.5375; e=0.7673; f=0.3498;
+ g= -0.6034; h=0.6397; i= -0.4762;
+ tx= -0.3019; ty= -3.7679; tz= -9.5913 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 4.5778; y = 6.6594; z = -4.0364 }, (* C5' *)
+ { x = 4.9220; y = 7.1963; z = -4.9204 }, (* H5' *)
+ { x = 3.7996; y = 5.9091; z = -4.1764 }, (* H5'' *)
+ { x = 5.7873; y = 5.8869; z = -3.5482 }, (* C4' *)
+ { x = 6.0405; y = 5.0875; z = -4.2446 }, (* H4' *)
+ { x = 6.9135; y = 6.8036; z = -3.4310 }, (* O4' *)
+ { x = 7.7293; y = 6.4084; z = -2.3392 }, (* C1' *)
+ { x = 8.7078; y = 6.1815; z = -2.7624 }, (* H1' *)
+ { x = 7.1305; y = 5.1418; z = -1.7347 }, (* C2' *)
+ { x = 7.2040; y = 5.1982; z = -0.6486 }, (* H2'' *)
+ { x = 7.7417; y = 4.0392; z = -2.3813 }, (* O2' *)
+ { x = 8.6785; y = 4.1443; z = -2.5630 }, (* H2' *)
+ { x = 5.6666; y = 5.2728; z = -2.1536 }, (* C3' *)
+ { x = 5.1747; y = 5.9805; z = -1.4863 }, (* H3' *)
+ { x = 4.9997; y = 4.0086; z = -2.1973 }, (* O3' *)
+ { x = 10.2594; y = 10.6774; z = -1.0056 }, (* N1 *)
+ { x = 9.7528; y = 8.7080; z = -2.2631 }, (* N3 *)
+ { x = 10.4471; y = 9.7876; z = -1.9791 }, (* C2 *)
+ { x = 8.7271; y = 8.5575; z = -1.3991 }, (* C4 *)
+ { x = 8.4100; y = 9.3803; z = -0.3580 }, (* C5 *)
+ { x = 9.2294; y = 10.5030; z = -0.1574 }, (* C6 *)
+ (G (
+ { x = 11.5110; y = 10.1256; z = -2.7114 }, (* N2 *)
+ { x = 7.2891; y = 8.9068; z = 0.3121 }, (* N7 *)
+ { x = 7.7962; y = 7.5519; z = -1.3859 }, (* N9 *)
+ { x = 6.9702; y = 7.8292; z = -0.3353 }, (* C8 *)
+ { x = 9.0349; y = 11.3951; z = 0.8250 }, (* O6 *)
+ { x = 10.9013; y = 11.4422; z = -0.9512 }, (* H1 *)
+ { x = 12.1031; y = 10.9341; z = -2.5861 }, (* H21 *)
+ { x = 11.7369; y = 9.5180; z = -3.4859 }, (* H22 *)
+ { x = 6.0888; y = 7.3990; z = 0.1403 }) (* H8 *)
+ )
+ )
+
+let rG06
+ = N(
+ { a= -0.9815; b=0.0731; c= -0.1772; (* dgf_base_tfo *)
+ d=0.1912; e=0.3054; f= -0.9328;
+ g= -0.0141; h= -0.9494; i= -0.3137;
+ tx=5.7506; ty= -5.1944; tz=4.7470 },
+ { a= -0.8143; b= -0.5091; c= -0.2788; (* P_O3'_275_tfo *)
+ d= -0.0433; e= -0.4257; f=0.9038;
+ g= -0.5788; h=0.7480; i=0.3246;
+ tx=1.5227; ty=6.9114; tz= -7.0765 },
+ { a=0.3822; b= -0.7477; c=0.5430; (* P_O3'_180_tfo *)
+ d=0.4552; e=0.6637; f=0.5935;
+ g= -0.8042; h=0.0203; i=0.5941;
+ tx= -6.9472; ty= -4.1186; tz= -5.9108 },
+ { a=0.5640; b=0.8007; c= -0.2022; (* P_O3'_60_tfo *)
+ d= -0.8247; e=0.5587; f= -0.0878;
+ g=0.0426; h=0.2162; i=0.9754;
+ tx=6.2694; ty= -7.0540; tz=3.3316 },
+ { x = 2.8930; y = 8.5380; z = -3.3280 }, (* P *)
+ { x = 1.6980; y = 7.6960; z = -3.5570 }, (* O1P *)
+ { x = 3.2260; y = 9.5010; z = -4.4020 }, (* O2P *)
+ { x = 4.1590; y = 7.6040; z = -3.0340 }, (* O5' *)
+ { x = 4.1214; y = 6.7116; z = -1.9049 }, (* C5' *)
+ { x = 3.3465; y = 5.9610; z = -2.0607 }, (* H5' *)
+ { x = 4.0789; y = 7.2928; z = -0.9837 }, (* H5'' *)
+ { x = 5.4170; y = 5.9293; z = -1.8186 }, (* C4' *)
+ { x = 5.4506; y = 5.3400; z = -0.9023 }, (* H4' *)
+ { x = 5.5067; y = 5.0417; z = -2.9703 }, (* O4' *)
+ { x = 6.8650; y = 4.9152; z = -3.3612 }, (* C1' *)
+ { x = 7.1090; y = 3.8577; z = -3.2603 }, (* H1' *)
+ { x = 7.7152; y = 5.7282; z = -2.3894 }, (* C2' *)
+ { x = 8.5029; y = 6.2356; z = -2.9463 }, (* H2'' *)
+ { x = 8.1036; y = 4.8568; z = -1.3419 }, (* O2' *)
+ { x = 8.3270; y = 3.9651; z = -1.6184 }, (* H2' *)
+ { x = 6.7003; y = 6.7565; z = -1.8911 }, (* C3' *)
+ { x = 6.5898; y = 7.5329; z = -2.6482 }, (* H3' *)
+ { x = 7.0505; y = 7.2878; z = -0.6105 }, (* O3' *)
+ { x = 6.6624; y = 3.5061; z = -8.2986 }, (* N1 *)
+ { x = 6.5810; y = 3.2570; z = -5.9221 }, (* N3 *)
+ { x = 6.5151; y = 2.8263; z = -7.1625 }, (* C2 *)
+ { x = 6.8364; y = 4.5817; z = -5.8882 }, (* C4 *)
+ { x = 7.0116; y = 5.4064; z = -6.9609 }, (* C5 *)
+ { x = 6.9173; y = 4.8260; z = -8.2361 }, (* C6 *)
+ (G (
+ { x = 6.2717; y = 1.5402; z = -7.4250 }, (* N2 *)
+ { x = 7.2573; y = 6.7070; z = -6.5394 }, (* N7 *)
+ { x = 6.9740; y = 5.3703; z = -4.7760 }, (* N9 *)
+ { x = 7.2238; y = 6.6275; z = -5.2453 }, (* C8 *)
+ { x = 7.0668; y = 5.5163; z = -9.3763 }, (* O6 *)
+ { x = 6.5754; y = 2.9964; z = -9.1545 }, (* H1 *)
+ { x = 6.1908; y = 1.1105; z = -8.3354 }, (* H21 *)
+ { x = 6.1346; y = 0.9352; z = -6.6280 }, (* H22 *)
+ { x = 7.4108; y = 7.6227; z = -4.8418 }) (* H8 *)
+ )
+ )
+
+let rG07
+ = N(
+ { a=0.0894; b= -0.6059; c=0.7905; (* dgf_base_tfo *)
+ d= -0.6810; e=0.5420; f=0.4924;
+ g= -0.7268; h= -0.5824; i= -0.3642;
+ tx=34.1424; ty=45.9610; tz= -11.8600 },
+ { a= -0.8644; b= -0.4956; c= -0.0851; (* P_O3'_275_tfo *)
+ d= -0.0427; e=0.2409; f= -0.9696;
+ g=0.5010; h= -0.8345; i= -0.2294;
+ tx=4.0167; ty=54.5377; tz=12.4779 },
+ { a=0.3706; b= -0.6167; c=0.6945; (* P_O3'_180_tfo *)
+ d= -0.2867; e= -0.7872; f= -0.5460;
+ g=0.8834; h=0.0032; i= -0.4686;
+ tx= -52.9020; ty=18.6313; tz= -0.6709 },
+ { a=0.4155; b=0.9025; c= -0.1137; (* P_O3'_60_tfo *)
+ d=0.9040; e= -0.4236; f= -0.0582;
+ g= -0.1007; h= -0.0786; i= -0.9918;
+ tx= -7.6624; ty= -25.2080; tz=49.5181 },
+ { x = 31.3810; y = 0.1400; z = 47.5810 }, (* P *)
+ { x = 29.9860; y = 0.6630; z = 47.6290 }, (* O1P *)
+ { x = 31.7210; y = -0.6460; z = 48.8090 }, (* O2P *)
+ { x = 32.4940; y = 1.2540; z = 47.2740 }, (* O5' *)
+ { x = 33.8709; y = 0.7918; z = 47.2113 }, (* C5' *)
+ { x = 34.1386; y = 0.5870; z = 46.1747 }, (* H5' *)
+ { x = 34.0186; y = -0.0095; z = 47.9353 }, (* H5'' *)
+ { x = 34.7297; y = 1.9687; z = 47.6685 }, (* C4' *)
+ { x = 35.7723; y = 1.6845; z = 47.8113 }, (* H4' *)
+ { x = 34.6455; y = 2.9768; z = 46.6660 }, (* O4' *)
+ { x = 34.1690; y = 4.1829; z = 47.2627 }, (* C1' *)
+ { x = 35.0437; y = 4.7633; z = 47.5560 }, (* H1' *)
+ { x = 33.4145; y = 3.7532; z = 48.4954 }, (* C2' *)
+ { x = 32.4340; y = 3.3797; z = 48.2001 }, (* H2'' *)
+ { x = 33.3209; y = 4.6953; z = 49.5217 }, (* O2' *)
+ { x = 33.2374; y = 5.6059; z = 49.2295 }, (* H2' *)
+ { x = 34.2724; y = 2.5970; z = 48.9773 }, (* C3' *)
+ { x = 33.6373; y = 1.8935; z = 49.5157 }, (* H3' *)
+ { x = 35.3453; y = 3.1884; z = 49.7285 }, (* O3' *)
+ { x = 34.0511; y = 7.8930; z = 43.7791 }, (* N1 *)
+ { x = 34.9937; y = 6.3369; z = 45.3199 }, (* N3 *)
+ { x = 35.0882; y = 7.3126; z = 44.4200 }, (* C2 *)
+ { x = 33.7190; y = 5.9650; z = 45.5374 }, (* C4 *)
+ { x = 32.5845; y = 6.4770; z = 44.9458 }, (* C5 *)
+ { x = 32.7430; y = 7.5179; z = 43.9914 }, (* C6 *)
+ (G (
+ { x = 36.3030; y = 7.7827; z = 44.1036 }, (* N2 *)
+ { x = 31.4499; y = 5.8335; z = 45.4368 }, (* N7 *)
+ { x = 33.2760; y = 4.9817; z = 46.4043 }, (* N9 *)
+ { x = 31.9235; y = 4.9639; z = 46.2934 }, (* C8 *)
+ { x = 31.8602; y = 8.1000; z = 43.3695 }, (* O6 *)
+ { x = 34.2623; y = 8.6223; z = 43.1283 }, (* H1 *)
+ { x = 36.5188; y = 8.5081; z = 43.4347 }, (* H21 *)
+ { x = 37.0888; y = 7.3524; z = 44.5699 }, (* H22 *)
+ { x = 31.0815; y = 4.4201; z = 46.7218 }) (* H8 *)
+ )
+ )
+
+let rG08
+ = N(
+ { a=0.2224; b=0.6335; c=0.7411; (* dgf_base_tfo *)
+ d= -0.3644; e= -0.6510; f=0.6659;
+ g=0.9043; h= -0.4181; i=0.0861;
+ tx= -47.6824; ty= -0.5823; tz= -31.7554 },
+ { a= -0.8644; b= -0.4956; c= -0.0851; (* P_O3'_275_tfo *)
+ d= -0.0427; e=0.2409; f= -0.9696;
+ g=0.5010; h= -0.8345; i= -0.2294;
+ tx=4.0167; ty=54.5377; tz=12.4779 },
+ { a=0.3706; b= -0.6167; c=0.6945; (* P_O3'_180_tfo *)
+ d= -0.2867; e= -0.7872; f= -0.5460;
+ g=0.8834; h=0.0032; i= -0.4686;
+ tx= -52.9020; ty=18.6313; tz= -0.6709 },
+ { a=0.4155; b=0.9025; c= -0.1137; (* P_O3'_60_tfo *)
+ d=0.9040; e= -0.4236; f= -0.0582;
+ g= -0.1007; h= -0.0786; i= -0.9918;
+ tx= -7.6624; ty= -25.2080; tz=49.5181 },
+ { x = 31.3810; y = 0.1400; z = 47.5810 }, (* P *)
+ { x = 29.9860; y = 0.6630; z = 47.6290 }, (* O1P *)
+ { x = 31.7210; y = -0.6460; z = 48.8090 }, (* O2P *)
+ { x = 32.4940; y = 1.2540; z = 47.2740 }, (* O5' *)
+ { x = 32.5924; y = 2.3488; z = 48.2255 }, (* C5' *)
+ { x = 33.3674; y = 2.1246; z = 48.9584 }, (* H5' *)
+ { x = 31.5994; y = 2.5917; z = 48.6037 }, (* H5'' *)
+ { x = 33.0722; y = 3.5577; z = 47.4258 }, (* C4' *)
+ { x = 33.0310; y = 4.4778; z = 48.0089 }, (* H4' *)
+ { x = 34.4173; y = 3.3055; z = 47.0316 }, (* O4' *)
+ { x = 34.5056; y = 3.3910; z = 45.6094 }, (* C1' *)
+ { x = 34.7881; y = 4.4152; z = 45.3663 }, (* H1' *)
+ { x = 33.1122; y = 3.1198; z = 45.1010 }, (* C2' *)
+ { x = 32.9230; y = 2.0469; z = 45.1369 }, (* H2'' *)
+ { x = 32.7946; y = 3.6590; z = 43.8529 }, (* O2' *)
+ { x = 33.5170; y = 3.6707; z = 43.2207 }, (* H2' *)
+ { x = 32.2730; y = 3.8173; z = 46.1566 }, (* C3' *)
+ { x = 31.3094; y = 3.3123; z = 46.2244 }, (* H3' *)
+ { x = 32.2391; y = 5.2039; z = 45.7807 }, (* O3' *)
+ { x = 39.3337; y = 2.7157; z = 44.1441 }, (* N1 *)
+ { x = 37.4430; y = 3.8242; z = 45.0824 }, (* N3 *)
+ { x = 38.7276; y = 3.7646; z = 44.7403 }, (* C2 *)
+ { x = 36.7791; y = 2.6963; z = 44.7704 }, (* C4 *)
+ { x = 37.2860; y = 1.5653; z = 44.1678 }, (* C5 *)
+ { x = 38.6647; y = 1.5552; z = 43.8235 }, (* C6 *)
+ (G (
+ { x = 39.5123; y = 4.8216; z = 44.9936 }, (* N2 *)
+ { x = 36.2829; y = 0.6110; z = 44.0078 }, (* N7 *)
+ { x = 35.4394; y = 2.4314; z = 44.9931 }, (* N9 *)
+ { x = 35.2180; y = 1.1815; z = 44.5128 }, (* C8 *)
+ { x = 39.2907; y = 0.6514; z = 43.2796 }, (* O6 *)
+ { x = 40.3076; y = 2.8048; z = 43.9352 }, (* H1 *)
+ { x = 40.4994; y = 4.9066; z = 44.7977 }, (* H21 *)
+ { x = 39.0738; y = 5.6108; z = 45.4464 }, (* H22 *)
+ { x = 34.3856; y = 0.4842; z = 44.4185 }) (* H8 *)
+ )
+ )
+
+let rG09
+ = N(
+ { a= -0.9699; b= -0.1688; c= -0.1753; (* dgf_base_tfo *)
+ d= -0.1050; e= -0.3598; f=0.9271;
+ g= -0.2196; h=0.9176; i=0.3312;
+ tx=45.6217; ty= -38.9484; tz= -12.3208 },
+ { a= -0.8644; b= -0.4956; c= -0.0851; (* P_O3'_275_tfo *)
+ d= -0.0427; e=0.2409; f= -0.9696;
+ g=0.5010; h= -0.8345; i= -0.2294;
+ tx=4.0167; ty=54.5377; tz=12.4779 },
+ { a=0.3706; b= -0.6167; c=0.6945; (* P_O3'_180_tfo *)
+ d= -0.2867; e= -0.7872; f= -0.5460;
+ g=0.8834; h=0.0032; i= -0.4686;
+ tx= -52.9020; ty=18.6313; tz= -0.6709 },
+ { a=0.4155; b=0.9025; c= -0.1137; (* P_O3'_60_tfo *)
+ d=0.9040; e= -0.4236; f= -0.0582;
+ g= -0.1007; h= -0.0786; i= -0.9918;
+ tx= -7.6624; ty= -25.2080; tz=49.5181 },
+ { x = 31.3810; y = 0.1400; z = 47.5810 }, (* P *)
+ { x = 29.9860; y = 0.6630; z = 47.6290 }, (* O1P *)
+ { x = 31.7210; y = -0.6460; z = 48.8090 }, (* O2P *)
+ { x = 32.4940; y = 1.2540; z = 47.2740 }, (* O5' *)
+ { x = 33.8709; y = 0.7918; z = 47.2113 }, (* C5' *)
+ { x = 34.1386; y = 0.5870; z = 46.1747 }, (* H5' *)
+ { x = 34.0186; y = -0.0095; z = 47.9353 }, (* H5'' *)
+ { x = 34.7297; y = 1.9687; z = 47.6685 }, (* C4' *)
+ { x = 34.5880; y = 2.8482; z = 47.0404 }, (* H4' *)
+ { x = 34.3575; y = 2.2770; z = 49.0081 }, (* O4' *)
+ { x = 35.5157; y = 2.1993; z = 49.8389 }, (* C1' *)
+ { x = 35.9424; y = 3.2010; z = 49.8893 }, (* H1' *)
+ { x = 36.4701; y = 1.2820; z = 49.1169 }, (* C2' *)
+ { x = 36.1545; y = 0.2498; z = 49.2683 }, (* H2'' *)
+ { x = 37.8262; y = 1.4547; z = 49.4008 }, (* O2' *)
+ { x = 38.0227; y = 1.6945; z = 50.3094 }, (* H2' *)
+ { x = 36.2242; y = 1.6797; z = 47.6725 }, (* C3' *)
+ { x = 36.4297; y = 0.8197; z = 47.0351 }, (* H3' *)
+ { x = 37.0289; y = 2.8480; z = 47.4426 }, (* O3' *)
+ { x = 34.3005; y = 3.5042; z = 54.6070 }, (* N1 *)
+ { x = 34.7693; y = 3.7936; z = 52.2874 }, (* N3 *)
+ { x = 34.4484; y = 4.2541; z = 53.4939 }, (* C2 *)
+ { x = 34.9354; y = 2.4584; z = 52.2785 }, (* C4 *)
+ { x = 34.8092; y = 1.5915; z = 53.3422 }, (* C5 *)
+ { x = 34.4646; y = 2.1367; z = 54.6085 }, (* C6 *)
+ (G (
+ { x = 34.2514; y = 5.5708; z = 53.6503 }, (* N2 *)
+ { x = 35.0641; y = 0.2835; z = 52.9337 }, (* N7 *)
+ { x = 35.2669; y = 1.6690; z = 51.1915 }, (* N9 *)
+ { x = 35.3288; y = 0.3954; z = 51.6563 }, (* C8 *)
+ { x = 34.3151; y = 1.5317; z = 55.6650 }, (* O6 *)
+ { x = 34.0623; y = 3.9797; z = 55.4539 }, (* H1 *)
+ { x = 33.9950; y = 6.0502; z = 54.5016 }, (* H21 *)
+ { x = 34.3512; y = 6.1432; z = 52.8242 }, (* H22 *)
+ { x = 35.5414; y = -0.6006; z = 51.2679 }) (* H8 *)
+ )
+ )
+
+let rG10
+ = N(
+ { a= -0.0980; b= -0.9723; c=0.2122; (* dgf_base_tfo *)
+ d= -0.9731; e=0.1383; f=0.1841;
+ g= -0.2083; h= -0.1885; i= -0.9597;
+ tx=17.8469; ty=38.8265; tz=37.0475 },
+ { a= -0.8644; b= -0.4956; c= -0.0851; (* P_O3'_275_tfo *)
+ d= -0.0427; e=0.2409; f= -0.9696;
+ g=0.5010; h= -0.8345; i= -0.2294;
+ tx=4.0167; ty=54.5377; tz=12.4779 },
+ { a=0.3706; b= -0.6167; c=0.6945; (* P_O3'_180_tfo *)
+ d= -0.2867; e= -0.7872; f= -0.5460;
+ g=0.8834; h=0.0032; i= -0.4686;
+ tx= -52.9020; ty=18.6313; tz= -0.6709 },
+ { a=0.4155; b=0.9025; c= -0.1137; (* P_O3'_60_tfo *)
+ d=0.9040; e= -0.4236; f= -0.0582;
+ g= -0.1007; h= -0.0786; i= -0.9918;
+ tx= -7.6624; ty= -25.2080; tz=49.5181 },
+ { x = 31.3810; y = 0.1400; z = 47.5810 }, (* P *)
+ { x = 29.9860; y = 0.6630; z = 47.6290 }, (* O1P *)
+ { x = 31.7210; y = -0.6460; z = 48.8090 }, (* O2P *)
+ { x = 32.4940; y = 1.2540; z = 47.2740 }, (* O5' *)
+ { x = 32.5924; y = 2.3488; z = 48.2255 }, (* C5' *)
+ { x = 33.3674; y = 2.1246; z = 48.9584 }, (* H5' *)
+ { x = 31.5994; y = 2.5917; z = 48.6037 }, (* H5'' *)
+ { x = 33.0722; y = 3.5577; z = 47.4258 }, (* C4' *)
+ { x = 34.0333; y = 3.3761; z = 46.9447 }, (* H4' *)
+ { x = 32.0890; y = 3.8338; z = 46.4332 }, (* O4' *)
+ { x = 31.6377; y = 5.1787; z = 46.5914 }, (* C1' *)
+ { x = 32.2499; y = 5.8016; z = 45.9392 }, (* H1' *)
+ { x = 31.9167; y = 5.5319; z = 48.0305 }, (* C2' *)
+ { x = 31.1507; y = 5.0820; z = 48.6621 }, (* H2'' *)
+ { x = 32.0865; y = 6.8890; z = 48.3114 }, (* O2' *)
+ { x = 31.5363; y = 7.4819; z = 47.7942 }, (* H2' *)
+ { x = 33.2398; y = 4.8224; z = 48.2563 }, (* C3' *)
+ { x = 33.3166; y = 4.5570; z = 49.3108 }, (* H3' *)
+ { x = 34.2528; y = 5.7056; z = 47.7476 }, (* O3' *)
+ { x = 28.2782; y = 6.3049; z = 42.9364 }, (* N1 *)
+ { x = 30.4001; y = 5.8547; z = 43.9258 }, (* N3 *)
+ { x = 29.6195; y = 6.1568; z = 42.8913 }, (* C2 *)
+ { x = 29.7005; y = 5.7006; z = 45.0649 }, (* C4 *)
+ { x = 28.3383; y = 5.8221; z = 45.2343 }, (* C5 *)
+ { x = 27.5519; y = 6.1461; z = 44.0958 }, (* C6 *)
+ (G (
+ { x = 30.1838; y = 6.3385; z = 41.6890 }, (* N2 *)
+ { x = 27.9936; y = 5.5926; z = 46.5651 }, (* N7 *)
+ { x = 30.2046; y = 5.3825; z = 46.3136 }, (* N9 *)
+ { x = 29.1371; y = 5.3398; z = 47.1506 }, (* C8 *)
+ { x = 26.3361; y = 6.3024; z = 44.0495 }, (* O6 *)
+ { x = 27.8122; y = 6.5394; z = 42.0833 }, (* H1 *)
+ { x = 29.7125; y = 6.5595; z = 40.8235 }, (* H21 *)
+ { x = 31.1859; y = 6.2231; z = 41.6389 }, (* H22 *)
+ { x = 28.9406; y = 5.1504; z = 48.2059 }) (* H8 *)
+ )
+ )
+
+let rGs = [rG01;rG02;rG03;rG04;rG05;rG06;rG07;rG08;rG09;rG10]
+
+let rU
+ = N(
+ { a= -0.0359; b= -0.8071; c=0.5894; (* dgf_base_tfo *)
+ d= -0.2669; e=0.5761; f=0.7726;
+ g= -0.9631; h= -0.1296; i= -0.2361;
+ tx=0.1584; ty=8.3434; tz=0.5434 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 5.2430; y = -8.2420; z = 2.8260 }, (* C5' *)
+ { x = 5.1974; y = -8.8497; z = 1.9223 }, (* H5' *)
+ { x = 5.5548; y = -8.7348; z = 3.7469 }, (* H5'' *)
+ { x = 6.3140; y = -7.2060; z = 2.5510 }, (* C4' *)
+ { x = 7.2954; y = -7.6762; z = 2.4898 }, (* H4' *)
+ { x = 6.0140; y = -6.5420; z = 1.2890 }, (* O4' *)
+ { x = 6.4190; y = -5.1840; z = 1.3620 }, (* C1' *)
+ { x = 7.1608; y = -5.0495; z = 0.5747 }, (* H1' *)
+ { x = 7.0760; y = -4.9560; z = 2.7270 }, (* C2' *)
+ { x = 6.7770; y = -3.9803; z = 3.1099 }, (* H2'' *)
+ { x = 8.4500; y = -5.1930; z = 2.5810 }, (* O2' *)
+ { x = 8.8309; y = -4.8755; z = 1.7590 }, (* H2' *)
+ { x = 6.4060; y = -6.0590; z = 3.5580 }, (* C3' *)
+ { x = 5.4021; y = -5.7313; z = 3.8281 }, (* H3' *)
+ { x = 7.1570; y = -6.4240; z = 4.7070 }, (* O3' *)
+ { x = 5.2170; y = -4.3260; z = 1.1690 }, (* N1 *)
+ { x = 4.2960; y = -2.2560; z = 0.6290 }, (* N3 *)
+ { x = 5.4330; y = -3.0200; z = 0.7990 }, (* C2 *)
+ { x = 2.9930; y = -2.6780; z = 0.7940 }, (* C4 *)
+ { x = 2.8670; y = -4.0630; z = 1.1830 }, (* C5 *)
+ { x = 3.9570; y = -4.8300; z = 1.3550 }, (* C6 *)
+ (U (
+ { x = 6.5470; y = -2.5560; z = 0.6290 }, (* O2 *)
+ { x = 2.0540; y = -1.9000; z = 0.6130 }, (* O4 *)
+ { x = 4.4300; y = -1.3020; z = 0.3600 }, (* H3 *)
+ { x = 1.9590; y = -4.4570; z = 1.3250 }, (* H5 *)
+ { x = 3.8460; y = -5.7860; z = 1.6240 }) (* H6 *)
+ )
+ )
+
+let rU01
+ = N(
+ { a= -0.0137; b= -0.8012; c=0.5983; (* dgf_base_tfo *)
+ d= -0.2523; e=0.5817; f=0.7733;
+ g= -0.9675; h= -0.1404; i= -0.2101;
+ tx=0.2031; ty=8.3874; tz=0.4228 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 5.2416; y = -8.2422; z = 2.8181 }, (* C5' *)
+ { x = 5.2050; y = -8.8128; z = 1.8901 }, (* H5' *)
+ { x = 5.5368; y = -8.7738; z = 3.7227 }, (* H5'' *)
+ { x = 6.3232; y = -7.2037; z = 2.6002 }, (* C4' *)
+ { x = 7.3048; y = -7.6757; z = 2.5577 }, (* H4' *)
+ { x = 6.0635; y = -6.5092; z = 1.3456 }, (* O4' *)
+ { x = 6.4697; y = -5.1547; z = 1.4629 }, (* C1' *)
+ { x = 7.2354; y = -5.0043; z = 0.7018 }, (* H1' *)
+ { x = 7.0856; y = -4.9610; z = 2.8521 }, (* C2' *)
+ { x = 6.7777; y = -3.9935; z = 3.2487 }, (* H2'' *)
+ { x = 8.4627; y = -5.1992; z = 2.7423 }, (* O2' *)
+ { x = 8.8693; y = -4.8638; z = 1.9399 }, (* H2' *)
+ { x = 6.3877; y = -6.0809; z = 3.6362 }, (* C3' *)
+ { x = 5.3770; y = -5.7562; z = 3.8834 }, (* H3' *)
+ { x = 7.1024; y = -6.4754; z = 4.7985 }, (* O3' *)
+ { x = 5.2764; y = -4.2883; z = 1.2538 }, (* N1 *)
+ { x = 4.3777; y = -2.2062; z = 0.7229 }, (* N3 *)
+ { x = 5.5069; y = -2.9779; z = 0.9088 }, (* C2 *)
+ { x = 3.0693; y = -2.6246; z = 0.8500 }, (* C4 *)
+ { x = 2.9279; y = -4.0146; z = 1.2149 }, (* C5 *)
+ { x = 4.0101; y = -4.7892; z = 1.4017 }, (* C6 *)
+ (U (
+ { x = 6.6267; y = -2.5166; z = 0.7728 }, (* O2 *)
+ { x = 2.1383; y = -1.8396; z = 0.6581 }, (* O4 *)
+ { x = 4.5223; y = -1.2489; z = 0.4716 }, (* H3 *)
+ { x = 2.0151; y = -4.4065; z = 1.3290 }, (* H5 *)
+ { x = 3.8886; y = -5.7486; z = 1.6535 }) (* H6 *)
+ )
+ )
+
+let rU02
+ = N(
+ { a=0.5141; b=0.0246; c=0.8574; (* dgf_base_tfo *)
+ d= -0.5547; e= -0.7529; f=0.3542;
+ g=0.6542; h= -0.6577; i= -0.3734;
+ tx= -9.1111; ty= -3.4598; tz= -3.2939 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 4.3825; y = -6.6585; z = 4.0489 }, (* C5' *)
+ { x = 4.6841; y = -7.2019; z = 4.9443 }, (* H5' *)
+ { x = 3.6189; y = -5.8889; z = 4.1625 }, (* H5'' *)
+ { x = 5.6255; y = -5.9175; z = 3.5998 }, (* C4' *)
+ { x = 5.8732; y = -5.1228; z = 4.3034 }, (* H4' *)
+ { x = 6.7337; y = -6.8605; z = 3.5222 }, (* O4' *)
+ { x = 7.5932; y = -6.4923; z = 2.4548 }, (* C1' *)
+ { x = 8.5661; y = -6.2983; z = 2.9064 }, (* H1' *)
+ { x = 7.0527; y = -5.2012; z = 1.8322 }, (* C2' *)
+ { x = 7.1627; y = -5.2525; z = 0.7490 }, (* H2'' *)
+ { x = 7.6666; y = -4.1249; z = 2.4880 }, (* O2' *)
+ { x = 8.5944; y = -4.2543; z = 2.6981 }, (* H2' *)
+ { x = 5.5661; y = -5.3029; z = 2.2009 }, (* C3' *)
+ { x = 5.0841; y = -6.0018; z = 1.5172 }, (* H3' *)
+ { x = 4.9062; y = -4.0452; z = 2.2042 }, (* O3' *)
+ { x = 7.6298; y = -7.6136; z = 1.4752 }, (* N1 *)
+ { x = 8.6945; y = -8.7046; z = -0.2857 }, (* N3 *)
+ { x = 8.6943; y = -7.6514; z = 0.6066 }, (* C2 *)
+ { x = 7.7426; y = -9.6987; z = -0.3801 }, (* C4 *)
+ { x = 6.6642; y = -9.5742; z = 0.5722 }, (* C5 *)
+ { x = 6.6391; y = -8.5592; z = 1.4526 }, (* C6 *)
+ (U (
+ { x = 9.5840; y = -6.8186; z = 0.6136 }, (* O2 *)
+ { x = 7.8505; y = -10.5925; z = -1.2223 }, (* O4 *)
+ { x = 9.4601; y = -8.7514; z = -0.9277 }, (* H3 *)
+ { x = 5.9281; y = -10.2509; z = 0.5782 }, (* H5 *)
+ { x = 5.8831; y = -8.4931; z = 2.1028 }) (* H6 *)
+ )
+ )
+
+let rU03
+ = N(
+ { a= -0.4993; b=0.0476; c=0.8651; (* dgf_base_tfo *)
+ d=0.8078; e= -0.3353; f=0.4847;
+ g=0.3132; h=0.9409; i=0.1290;
+ tx=6.2989; ty= -5.2303; tz= -3.8577 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 3.9938; y = -6.7042; z = 1.9023 }, (* C5' *)
+ { x = 3.2332; y = -5.9343; z = 2.0319 }, (* H5' *)
+ { x = 3.9666; y = -7.2863; z = 0.9812 }, (* H5'' *)
+ { x = 5.3098; y = -5.9546; z = 1.8564 }, (* C4' *)
+ { x = 5.3863; y = -5.3702; z = 0.9395 }, (* H4' *)
+ { x = 5.3851; y = -5.0642; z = 3.0076 }, (* O4' *)
+ { x = 6.7315; y = -4.9724; z = 3.4462 }, (* C1' *)
+ { x = 7.0033; y = -3.9202; z = 3.3619 }, (* H1' *)
+ { x = 7.5997; y = -5.8018; z = 2.4948 }, (* C2' *)
+ { x = 8.3627; y = -6.3254; z = 3.0707 }, (* H2'' *)
+ { x = 8.0410; y = -4.9501; z = 1.4724 }, (* O2' *)
+ { x = 8.2781; y = -4.0644; z = 1.7570 }, (* H2' *)
+ { x = 6.5701; y = -6.8129; z = 1.9714 }, (* C3' *)
+ { x = 6.4186; y = -7.5809; z = 2.7299 }, (* H3' *)
+ { x = 6.9357; y = -7.3841; z = 0.7235 }, (* O3' *)
+ { x = 6.8024; y = -5.4718; z = 4.8475 }, (* N1 *)
+ { x = 7.9218; y = -5.5700; z = 6.8877 }, (* N3 *)
+ { x = 7.8908; y = -5.0886; z = 5.5944 }, (* C2 *)
+ { x = 6.9789; y = -6.3827; z = 7.4823 }, (* C4 *)
+ { x = 5.8742; y = -6.7319; z = 6.6202 }, (* C5 *)
+ { x = 5.8182; y = -6.2769; z = 5.3570 }, (* C6 *)
+ (U (
+ { x = 8.7747; y = -4.3728; z = 5.1568 }, (* O2 *)
+ { x = 7.1154; y = -6.7509; z = 8.6509 }, (* O4 *)
+ { x = 8.7055; y = -5.3037; z = 7.4491 }, (* H3 *)
+ { x = 5.1416; y = -7.3178; z = 6.9665 }, (* H5 *)
+ { x = 5.0441; y = -6.5310; z = 4.7784 }) (* H6 *)
+ )
+ )
+
+let rU04
+ = N(
+ { a= -0.5669; b= -0.8012; c=0.1918; (* dgf_base_tfo *)
+ d= -0.8129; e=0.5817; f=0.0273;
+ g= -0.1334; h= -0.1404; i= -0.9811;
+ tx= -0.3279; ty=8.3874; tz=0.3355 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 5.2416; y = -8.2422; z = 2.8181 }, (* C5' *)
+ { x = 5.2050; y = -8.8128; z = 1.8901 }, (* H5' *)
+ { x = 5.5368; y = -8.7738; z = 3.7227 }, (* H5'' *)
+ { x = 6.3232; y = -7.2037; z = 2.6002 }, (* C4' *)
+ { x = 7.3048; y = -7.6757; z = 2.5577 }, (* H4' *)
+ { x = 6.0635; y = -6.5092; z = 1.3456 }, (* O4' *)
+ { x = 6.4697; y = -5.1547; z = 1.4629 }, (* C1' *)
+ { x = 7.2354; y = -5.0043; z = 0.7018 }, (* H1' *)
+ { x = 7.0856; y = -4.9610; z = 2.8521 }, (* C2' *)
+ { x = 6.7777; y = -3.9935; z = 3.2487 }, (* H2'' *)
+ { x = 8.4627; y = -5.1992; z = 2.7423 }, (* O2' *)
+ { x = 8.8693; y = -4.8638; z = 1.9399 }, (* H2' *)
+ { x = 6.3877; y = -6.0809; z = 3.6362 }, (* C3' *)
+ { x = 5.3770; y = -5.7562; z = 3.8834 }, (* H3' *)
+ { x = 7.1024; y = -6.4754; z = 4.7985 }, (* O3' *)
+ { x = 5.2764; y = -4.2883; z = 1.2538 }, (* N1 *)
+ { x = 3.8961; y = -3.0896; z = -0.1893 }, (* N3 *)
+ { x = 5.0095; y = -3.8907; z = -0.0346 }, (* C2 *)
+ { x = 3.0480; y = -2.6632; z = 0.8116 }, (* C4 *)
+ { x = 3.4093; y = -3.1310; z = 2.1292 }, (* C5 *)
+ { x = 4.4878; y = -3.9124; z = 2.3088 }, (* C6 *)
+ (U (
+ { x = 5.7005; y = -4.2164; z = -0.9842 }, (* O2 *)
+ { x = 2.0800; y = -1.9458; z = 0.5503 }, (* O4 *)
+ { x = 3.6834; y = -2.7882; z = -1.1190 }, (* H3 *)
+ { x = 2.8508; y = -2.8721; z = 2.9172 }, (* H5 *)
+ { x = 4.7188; y = -4.2247; z = 3.2295 }) (* H6 *)
+ )
+ )
+
+let rU05
+ = N(
+ { a= -0.6298; b=0.0246; c=0.7763; (* dgf_base_tfo *)
+ d= -0.5226; e= -0.7529; f= -0.4001;
+ g=0.5746; h= -0.6577; i=0.4870;
+ tx= -0.0208; ty= -3.4598; tz= -9.6882 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 4.3825; y = -6.6585; z = 4.0489 }, (* C5' *)
+ { x = 4.6841; y = -7.2019; z = 4.9443 }, (* H5' *)
+ { x = 3.6189; y = -5.8889; z = 4.1625 }, (* H5'' *)
+ { x = 5.6255; y = -5.9175; z = 3.5998 }, (* C4' *)
+ { x = 5.8732; y = -5.1228; z = 4.3034 }, (* H4' *)
+ { x = 6.7337; y = -6.8605; z = 3.5222 }, (* O4' *)
+ { x = 7.5932; y = -6.4923; z = 2.4548 }, (* C1' *)
+ { x = 8.5661; y = -6.2983; z = 2.9064 }, (* H1' *)
+ { x = 7.0527; y = -5.2012; z = 1.8322 }, (* C2' *)
+ { x = 7.1627; y = -5.2525; z = 0.7490 }, (* H2'' *)
+ { x = 7.6666; y = -4.1249; z = 2.4880 }, (* O2' *)
+ { x = 8.5944; y = -4.2543; z = 2.6981 }, (* H2' *)
+ { x = 5.5661; y = -5.3029; z = 2.2009 }, (* C3' *)
+ { x = 5.0841; y = -6.0018; z = 1.5172 }, (* H3' *)
+ { x = 4.9062; y = -4.0452; z = 2.2042 }, (* O3' *)
+ { x = 7.6298; y = -7.6136; z = 1.4752 }, (* N1 *)
+ { x = 8.5977; y = -9.5977; z = 0.7329 }, (* N3 *)
+ { x = 8.5951; y = -8.5745; z = 1.6594 }, (* C2 *)
+ { x = 7.7372; y = -9.7371; z = -0.3364 }, (* C4 *)
+ { x = 6.7596; y = -8.6801; z = -0.4476 }, (* C5 *)
+ { x = 6.7338; y = -7.6721; z = 0.4408 }, (* C6 *)
+ (U (
+ { x = 9.3993; y = -8.5377; z = 2.5743 }, (* O2 *)
+ { x = 7.8374; y = -10.6990; z = -1.1008 }, (* O4 *)
+ { x = 9.2924; y = -10.3081; z = 0.8477 }, (* H3 *)
+ { x = 6.0932; y = -8.6982; z = -1.1929 }, (* H5 *)
+ { x = 6.0481; y = -6.9515; z = 0.3446 }) (* H6 *)
+ )
+ )
+
+let rU06
+ = N(
+ { a= -0.9837; b=0.0476; c= -0.1733; (* dgf_base_tfo *)
+ d= -0.1792; e= -0.3353; f=0.9249;
+ g= -0.0141; h=0.9409; i=0.3384;
+ tx=5.7793; ty= -5.2303; tz=4.5997 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 3.9938; y = -6.7042; z = 1.9023 }, (* C5' *)
+ { x = 3.2332; y = -5.9343; z = 2.0319 }, (* H5' *)
+ { x = 3.9666; y = -7.2863; z = 0.9812 }, (* H5'' *)
+ { x = 5.3098; y = -5.9546; z = 1.8564 }, (* C4' *)
+ { x = 5.3863; y = -5.3702; z = 0.9395 }, (* H4' *)
+ { x = 5.3851; y = -5.0642; z = 3.0076 }, (* O4' *)
+ { x = 6.7315; y = -4.9724; z = 3.4462 }, (* C1' *)
+ { x = 7.0033; y = -3.9202; z = 3.3619 }, (* H1' *)
+ { x = 7.5997; y = -5.8018; z = 2.4948 }, (* C2' *)
+ { x = 8.3627; y = -6.3254; z = 3.0707 }, (* H2'' *)
+ { x = 8.0410; y = -4.9501; z = 1.4724 }, (* O2' *)
+ { x = 8.2781; y = -4.0644; z = 1.7570 }, (* H2' *)
+ { x = 6.5701; y = -6.8129; z = 1.9714 }, (* C3' *)
+ { x = 6.4186; y = -7.5809; z = 2.7299 }, (* H3' *)
+ { x = 6.9357; y = -7.3841; z = 0.7235 }, (* O3' *)
+ { x = 6.8024; y = -5.4718; z = 4.8475 }, (* N1 *)
+ { x = 6.6920; y = -5.0495; z = 7.1354 }, (* N3 *)
+ { x = 6.6201; y = -4.5500; z = 5.8506 }, (* C2 *)
+ { x = 6.9254; y = -6.3614; z = 7.4926 }, (* C4 *)
+ { x = 7.1046; y = -7.2543; z = 6.3718 }, (* C5 *)
+ { x = 7.0391; y = -6.7951; z = 5.1106 }, (* C6 *)
+ (U (
+ { x = 6.4083; y = -3.3696; z = 5.6340 }, (* O2 *)
+ { x = 6.9679; y = -6.6901; z = 8.6800 }, (* O4 *)
+ { x = 6.5626; y = -4.3957; z = 7.8812 }, (* H3 *)
+ { x = 7.2781; y = -8.2254; z = 6.5350 }, (* H5 *)
+ { x = 7.1657; y = -7.4312; z = 4.3503 }) (* H6 *)
+ )
+ )
+
+let rU07
+ = N(
+ { a= -0.9434; b=0.3172; c=0.0971; (* dgf_base_tfo *)
+ d=0.2294; e=0.4125; f=0.8816;
+ g=0.2396; h=0.8539; i= -0.4619;
+ tx=8.3625; ty= -52.7147; tz=1.3745 },
+ { a=0.2765; b= -0.1121; c= -0.9545; (* P_O3'_275_tfo *)
+ d= -0.8297; e=0.4733; f= -0.2959;
+ g=0.4850; h=0.8737; i=0.0379;
+ tx= -14.7774; ty= -45.2464; tz=21.9088 },
+ { a=0.1063; b= -0.6334; c= -0.7665; (* P_O3'_180_tfo *)
+ d= -0.5932; e= -0.6591; f=0.4624;
+ g= -0.7980; h=0.4055; i= -0.4458;
+ tx=43.7634; ty=4.3296; tz=28.4890 },
+ { a=0.7136; b= -0.5032; c= -0.4873; (* P_O3'_60_tfo *)
+ d=0.6803; e=0.3317; f=0.6536;
+ g= -0.1673; h= -0.7979; i=0.5791;
+ tx= -17.1858; ty=41.4390; tz= -27.0751 },
+ { x = 21.3880; y = 15.0780; z = 45.5770 }, (* P *)
+ { x = 21.9980; y = 14.5500; z = 46.8210 }, (* O1P *)
+ { x = 21.1450; y = 14.0270; z = 44.5420 }, (* O2P *)
+ { x = 22.1250; y = 16.3600; z = 44.9460 }, (* O5' *)
+ { x = 21.5037; y = 16.8594; z = 43.7323 }, (* C5' *)
+ { x = 20.8147; y = 17.6663; z = 43.9823 }, (* H5' *)
+ { x = 21.1086; y = 16.0230; z = 43.1557 }, (* H5'' *)
+ { x = 22.5654; y = 17.4874; z = 42.8616 }, (* C4' *)
+ { x = 22.1584; y = 17.7243; z = 41.8785 }, (* H4' *)
+ { x = 23.0557; y = 18.6826; z = 43.4751 }, (* O4' *)
+ { x = 24.4788; y = 18.6151; z = 43.6455 }, (* C1' *)
+ { x = 24.9355; y = 19.0840; z = 42.7739 }, (* H1' *)
+ { x = 24.7958; y = 17.1427; z = 43.6474 }, (* C2' *)
+ { x = 24.5652; y = 16.7400; z = 44.6336 }, (* H2'' *)
+ { x = 26.1041; y = 16.8773; z = 43.2455 }, (* O2' *)
+ { x = 26.7516; y = 17.5328; z = 43.5149 }, (* H2' *)
+ { x = 23.8109; y = 16.5979; z = 42.6377 }, (* C3' *)
+ { x = 23.5756; y = 15.5686; z = 42.9084 }, (* H3' *)
+ { x = 24.2890; y = 16.7447; z = 41.2729 }, (* O3' *)
+ { x = 24.9420; y = 19.2174; z = 44.8923 }, (* N1 *)
+ { x = 25.2655; y = 20.5636; z = 44.8883 }, (* N3 *)
+ { x = 25.1663; y = 21.2219; z = 43.8561 }, (* C2 *)
+ { x = 25.6911; y = 21.1219; z = 46.0494 }, (* C4 *)
+ { x = 25.8051; y = 20.4068; z = 47.2048 }, (* C5 *)
+ { x = 26.2093; y = 20.9962; z = 48.2534 }, (* C6 *)
+ (U (
+ { x = 25.4692; y = 19.0221; z = 47.2053 }, (* O2 *)
+ { x = 25.0502; y = 18.4827; z = 46.0370 }, (* O4 *)
+ { x = 25.9599; y = 22.1772; z = 46.0966 }, (* H3 *)
+ { x = 25.5545; y = 18.4409; z = 48.1234 }, (* H5 *)
+ { x = 24.7854; y = 17.4265; z = 45.9883 }) (* H6 *)
+ )
+ )
+
+let rU08
+ = N(
+ { a= -0.0080; b= -0.7928; c=0.6094; (* dgf_base_tfo *)
+ d= -0.7512; e=0.4071; f=0.5197;
+ g= -0.6601; h= -0.4536; i= -0.5988;
+ tx=44.1482; ty=30.7036; tz=2.1088 },
+ { a=0.2765; b= -0.1121; c= -0.9545; (* P_O3'_275_tfo *)
+ d= -0.8297; e=0.4733; f= -0.2959;
+ g=0.4850; h=0.8737; i=0.0379;
+ tx= -14.7774; ty= -45.2464; tz=21.9088 },
+ { a=0.1063; b= -0.6334; c= -0.7665; (* P_O3'_180_tfo *)
+ d= -0.5932; e= -0.6591; f=0.4624;
+ g= -0.7980; h=0.4055; i= -0.4458;
+ tx=43.7634; ty=4.3296; tz=28.4890 },
+ { a=0.7136; b= -0.5032; c= -0.4873; (* P_O3'_60_tfo *)
+ d=0.6803; e=0.3317; f=0.6536;
+ g= -0.1673; h= -0.7979; i=0.5791;
+ tx= -17.1858; ty=41.4390; tz= -27.0751 },
+ { x = 21.3880; y = 15.0780; z = 45.5770 }, (* P *)
+ { x = 21.9980; y = 14.5500; z = 46.8210 }, (* O1P *)
+ { x = 21.1450; y = 14.0270; z = 44.5420 }, (* O2P *)
+ { x = 22.1250; y = 16.3600; z = 44.9460 }, (* O5' *)
+ { x = 23.5096; y = 16.1227; z = 44.5783 }, (* C5' *)
+ { x = 23.5649; y = 15.8588; z = 43.5222 }, (* H5' *)
+ { x = 23.9621; y = 15.4341; z = 45.2919 }, (* H5'' *)
+ { x = 24.2805; y = 17.4138; z = 44.7151 }, (* C4' *)
+ { x = 25.3492; y = 17.2309; z = 44.6030 }, (* H4' *)
+ { x = 23.8497; y = 18.3471; z = 43.7208 }, (* O4' *)
+ { x = 23.4090; y = 19.5681; z = 44.3321 }, (* C1' *)
+ { x = 24.2595; y = 20.2496; z = 44.3524 }, (* H1' *)
+ { x = 23.0418; y = 19.1813; z = 45.7407 }, (* C2' *)
+ { x = 22.0532; y = 18.7224; z = 45.7273 }, (* H2'' *)
+ { x = 23.1307; y = 20.2521; z = 46.6291 }, (* O2' *)
+ { x = 22.8888; y = 21.1051; z = 46.2611 }, (* H2' *)
+ { x = 24.0799; y = 18.1326; z = 46.0700 }, (* C3' *)
+ { x = 23.6490; y = 17.4370; z = 46.7900 }, (* H3' *)
+ { x = 25.3329; y = 18.7227; z = 46.5109 }, (* O3' *)
+ { x = 22.2515; y = 20.1624; z = 43.6698 }, (* N1 *)
+ { x = 22.4760; y = 21.0609; z = 42.6406 }, (* N3 *)
+ { x = 23.6229; y = 21.3462; z = 42.3061 }, (* C2 *)
+ { x = 21.3986; y = 21.6081; z = 42.0236 }, (* C4 *)
+ { x = 20.1189; y = 21.3012; z = 42.3804 }, (* C5 *)
+ { x = 19.1599; y = 21.8516; z = 41.7578 }, (* C6 *)
+ (U (
+ { x = 19.8919; y = 20.3745; z = 43.4387 }, (* O2 *)
+ { x = 20.9790; y = 19.8423; z = 44.0440 }, (* O4 *)
+ { x = 21.5235; y = 22.3222; z = 41.2097 }, (* H3 *)
+ { x = 18.8732; y = 20.1200; z = 43.7312 }, (* H5 *)
+ { x = 20.8545; y = 19.1313; z = 44.8608 }) (* H6 *)
+ )
+ )
+
+let rU09
+ = N(
+ { a= -0.0317; b=0.1374; c=0.9900; (* dgf_base_tfo *)
+ d= -0.3422; e= -0.9321; f=0.1184;
+ g=0.9391; h= -0.3351; i=0.0765;
+ tx= -32.1929; ty=25.8198; tz= -28.5088 },
+ { a=0.2765; b= -0.1121; c= -0.9545; (* P_O3'_275_tfo *)
+ d= -0.8297; e=0.4733; f= -0.2959;
+ g=0.4850; h=0.8737; i=0.0379;
+ tx= -14.7774; ty= -45.2464; tz=21.9088 },
+ { a=0.1063; b= -0.6334; c= -0.7665; (* P_O3'_180_tfo *)
+ d= -0.5932; e= -0.6591; f=0.4624;
+ g= -0.7980; h=0.4055; i= -0.4458;
+ tx=43.7634; ty=4.3296; tz=28.4890 },
+ { a=0.7136; b= -0.5032; c= -0.4873; (* P_O3'_60_tfo *)
+ d=0.6803; e=0.3317; f=0.6536;
+ g= -0.1673; h= -0.7979; i=0.5791;
+ tx= -17.1858; ty=41.4390; tz= -27.0751 },
+ { x = 21.3880; y = 15.0780; z = 45.5770 }, (* P *)
+ { x = 21.9980; y = 14.5500; z = 46.8210 }, (* O1P *)
+ { x = 21.1450; y = 14.0270; z = 44.5420 }, (* O2P *)
+ { x = 22.1250; y = 16.3600; z = 44.9460 }, (* O5' *)
+ { x = 21.5037; y = 16.8594; z = 43.7323 }, (* C5' *)
+ { x = 20.8147; y = 17.6663; z = 43.9823 }, (* H5' *)
+ { x = 21.1086; y = 16.0230; z = 43.1557 }, (* H5'' *)
+ { x = 22.5654; y = 17.4874; z = 42.8616 }, (* C4' *)
+ { x = 23.0565; y = 18.3036; z = 43.3915 }, (* H4' *)
+ { x = 23.5375; y = 16.5054; z = 42.4925 }, (* O4' *)
+ { x = 23.6574; y = 16.4257; z = 41.0649 }, (* C1' *)
+ { x = 24.4701; y = 17.0882; z = 40.7671 }, (* H1' *)
+ { x = 22.3525; y = 16.9643; z = 40.5396 }, (* C2' *)
+ { x = 21.5993; y = 16.1799; z = 40.6133 }, (* H2'' *)
+ { x = 22.4693; y = 17.4849; z = 39.2515 }, (* O2' *)
+ { x = 23.0899; y = 17.0235; z = 38.6827 }, (* H2' *)
+ { x = 22.0341; y = 18.0633; z = 41.5279 }, (* C3' *)
+ { x = 20.9509; y = 18.1709; z = 41.5846 }, (* H3' *)
+ { x = 22.7249; y = 19.3020; z = 41.2100 }, (* O3' *)
+ { x = 23.8580; y = 15.0648; z = 40.5757 }, (* N1 *)
+ { x = 25.1556; y = 14.5982; z = 40.4523 }, (* N3 *)
+ { x = 26.1047; y = 15.3210; z = 40.7448 }, (* C2 *)
+ { x = 25.3391; y = 13.3315; z = 40.0020 }, (* C4 *)
+ { x = 24.2974; y = 12.5148; z = 39.6749 }, (* C5 *)
+ { x = 24.5450; y = 11.3410; z = 39.2610 }, (* C6 *)
+ (U (
+ { x = 22.9633; y = 12.9979; z = 39.8053 }, (* O2 *)
+ { x = 22.8009; y = 14.2648; z = 40.2524 }, (* O4 *)
+ { x = 26.3414; y = 12.9194; z = 39.8855 }, (* H3 *)
+ { x = 22.1227; y = 12.3533; z = 39.5486 }, (* H5 *)
+ { x = 21.7989; y = 14.6788; z = 40.3650 }) (* H6 *)
+ )
+ )
+
+let rU10
+ = N(
+ { a= -0.9674; b=0.1021; c= -0.2318; (* dgf_base_tfo *)
+ d= -0.2514; e= -0.2766; f=0.9275;
+ g=0.0306; h=0.9555; i=0.2933;
+ tx=27.8571; ty= -42.1305; tz= -24.4563 },
+ { a=0.2765; b= -0.1121; c= -0.9545; (* P_O3'_275_tfo *)
+ d= -0.8297; e=0.4733; f= -0.2959;
+ g=0.4850; h=0.8737; i=0.0379;
+ tx= -14.7774; ty= -45.2464; tz=21.9088 },
+ { a=0.1063; b= -0.6334; c= -0.7665; (* P_O3'_180_tfo *)
+ d= -0.5932; e= -0.6591; f=0.4624;
+ g= -0.7980; h=0.4055; i= -0.4458;
+ tx=43.7634; ty=4.3296; tz=28.4890 },
+ { a=0.7136; b= -0.5032; c= -0.4873; (* P_O3'_60_tfo *)
+ d=0.6803; e=0.3317; f=0.6536;
+ g= -0.1673; h= -0.7979; i=0.5791;
+ tx= -17.1858; ty=41.4390; tz= -27.0751 },
+ { x = 21.3880; y = 15.0780; z = 45.5770 }, (* P *)
+ { x = 21.9980; y = 14.5500; z = 46.8210 }, (* O1P *)
+ { x = 21.1450; y = 14.0270; z = 44.5420 }, (* O2P *)
+ { x = 22.1250; y = 16.3600; z = 44.9460 }, (* O5' *)
+ { x = 23.5096; y = 16.1227; z = 44.5783 }, (* C5' *)
+ { x = 23.5649; y = 15.8588; z = 43.5222 }, (* H5' *)
+ { x = 23.9621; y = 15.4341; z = 45.2919 }, (* H5'' *)
+ { x = 24.2805; y = 17.4138; z = 44.7151 }, (* C4' *)
+ { x = 23.8509; y = 18.1819; z = 44.0720 }, (* H4' *)
+ { x = 24.2506; y = 17.8583; z = 46.0741 }, (* O4' *)
+ { x = 25.5830; y = 18.0320; z = 46.5775 }, (* C1' *)
+ { x = 25.8569; y = 19.0761; z = 46.4256 }, (* H1' *)
+ { x = 26.4410; y = 17.1555; z = 45.7033 }, (* C2' *)
+ { x = 26.3459; y = 16.1253; z = 46.0462 }, (* H2'' *)
+ { x = 27.7649; y = 17.5888; z = 45.6478 }, (* O2' *)
+ { x = 28.1004; y = 17.9719; z = 46.4616 }, (* H2' *)
+ { x = 25.7796; y = 17.2997; z = 44.3513 }, (* C3' *)
+ { x = 25.9478; y = 16.3824; z = 43.7871 }, (* H3' *)
+ { x = 26.2154; y = 18.4984; z = 43.6541 }, (* O3' *)
+ { x = 25.7321; y = 17.6281; z = 47.9726 }, (* N1 *)
+ { x = 25.5136; y = 18.5779; z = 48.9560 }, (* N3 *)
+ { x = 25.2079; y = 19.7276; z = 48.6503 }, (* C2 *)
+ { x = 25.6482; y = 18.1987; z = 50.2518 }, (* C4 *)
+ { x = 25.9847; y = 16.9266; z = 50.6092 }, (* C5 *)
+ { x = 26.0918; y = 16.6439; z = 51.8416 }, (* C6 *)
+ (U (
+ { x = 26.2067; y = 15.9515; z = 49.5943 }, (* O2 *)
+ { x = 26.0713; y = 16.3497; z = 48.3080 }, (* O4 *)
+ { x = 25.4890; y = 18.9105; z = 51.0618 }, (* H3 *)
+ { x = 26.4742; y = 14.9310; z = 49.8682 }, (* H5 *)
+ { x = 26.2346; y = 15.6394; z = 47.4975 }) (* H6 *)
+ )
+ )
+
+let rUs = [rU01;rU02;rU03;rU04;rU05;rU06;rU07;rU08;rU09;rU10]
+
+let rG'
+ = N(
+ { a= -0.2067; b= -0.0264; c=0.9780; (* dgf_base_tfo *)
+ d=0.9770; e= -0.0586; f=0.2049;
+ g=0.0519; h=0.9979; i=0.0379;
+ tx=1.0331; ty= -46.8078; tz= -36.4742 },
+ { a= -0.8644; b= -0.4956; c= -0.0851; (* P_O3'_275_tfo *)
+ d= -0.0427; e=0.2409; f= -0.9696;
+ g=0.5010; h= -0.8345; i= -0.2294;
+ tx=4.0167; ty=54.5377; tz=12.4779 },
+ { a=0.3706; b= -0.6167; c=0.6945; (* P_O3'_180_tfo *)
+ d= -0.2867; e= -0.7872; f= -0.5460;
+ g=0.8834; h=0.0032; i= -0.4686;
+ tx= -52.9020; ty=18.6313; tz= -0.6709 },
+ { a=0.4155; b=0.9025; c= -0.1137; (* P_O3'_60_tfo *)
+ d=0.9040; e= -0.4236; f= -0.0582;
+ g= -0.1007; h= -0.0786; i= -0.9918;
+ tx= -7.6624; ty= -25.2080; tz=49.5181 },
+ { x = 31.3810; y = 0.1400; z = 47.5810 }, (* P *)
+ { x = 29.9860; y = 0.6630; z = 47.6290 }, (* O1P *)
+ { x = 31.7210; y = -0.6460; z = 48.8090 }, (* O2P *)
+ { x = 32.4940; y = 1.2540; z = 47.2740 }, (* O5' *)
+ { x = 32.1610; y = 2.2370; z = 46.2560 }, (* C5' *)
+ { x = 31.2986; y = 2.8190; z = 46.5812 }, (* H5' *)
+ { x = 32.0980; y = 1.7468; z = 45.2845 }, (* H5'' *)
+ { x = 33.3476; y = 3.1959; z = 46.1947 }, (* C4' *)
+ { x = 33.2668; y = 3.8958; z = 45.3630 }, (* H4' *)
+ { x = 33.3799; y = 3.9183; z = 47.4216 }, (* O4' *)
+ { x = 34.6515; y = 3.7222; z = 48.0398 }, (* C1' *)
+ { x = 35.2947; y = 4.5412; z = 47.7180 }, (* H1' *)
+ { x = 35.1756; y = 2.4228; z = 47.4827 }, (* C2' *)
+ { x = 34.6778; y = 1.5937; z = 47.9856 }, (* H2'' *)
+ { x = 36.5631; y = 2.2672; z = 47.4798 }, (* O2' *)
+ { x = 37.0163; y = 2.6579; z = 48.2305 }, (* H2' *)
+ { x = 34.6953; y = 2.5043; z = 46.0448 }, (* C3' *)
+ { x = 34.5444; y = 1.4917; z = 45.6706 }, (* H3' *)
+ { x = 35.6679; y = 3.3009; z = 45.3487 }, (* O3' *)
+ { x = 37.4804; y = 4.0914; z = 52.2559 }, (* N1 *)
+ { x = 36.9670; y = 4.1312; z = 49.9281 }, (* N3 *)
+ { x = 37.8045; y = 4.2519; z = 50.9550 }, (* C2 *)
+ { x = 35.7171; y = 3.8264; z = 50.3222 }, (* C4 *)
+ { x = 35.2668; y = 3.6420; z = 51.6115 }, (* C5 *)
+ { x = 36.2037; y = 3.7829; z = 52.6706 }, (* C6 *)
+ (G (
+ { x = 39.0869; y = 4.5552; z = 50.7092 }, (* N2 *)
+ { x = 33.9075; y = 3.3338; z = 51.6102 }, (* N7 *)
+ { x = 34.6126; y = 3.6358; z = 49.5108 }, (* N9 *)
+ { x = 33.5805; y = 3.3442; z = 50.3425 }, (* C8 *)
+ { x = 35.9958; y = 3.6512; z = 53.8724 }, (* O6 *)
+ { x = 38.2106; y = 4.2053; z = 52.9295 }, (* H1 *)
+ { x = 39.8218; y = 4.6863; z = 51.3896 }, (* H21 *)
+ { x = 39.3420; y = 4.6857; z = 49.7407 }, (* H22 *)
+ { x = 32.5194; y = 3.1070; z = 50.2664 }) (* H8 *)
+ )
+ )
+
+let rU'
+ = N(
+ { a= -0.0109; b=0.5907; c=0.8068; (* dgf_base_tfo *)
+ d=0.2217; e= -0.7853; f=0.5780;
+ g=0.9751; h=0.1852; i= -0.1224;
+ tx= -1.4225; ty= -11.0956; tz= -2.5217 },
+ { a= -0.8313; b= -0.4738; c= -0.2906; (* P_O3'_275_tfo *)
+ d=0.0649; e=0.4366; f= -0.8973;
+ g=0.5521; h= -0.7648; i= -0.3322;
+ tx=1.6833; ty=6.8060; tz= -7.0011 },
+ { a=0.3445; b= -0.7630; c=0.5470; (* P_O3'_180_tfo *)
+ d= -0.4628; e= -0.6450; f= -0.6082;
+ g=0.8168; h= -0.0436; i= -0.5753;
+ tx= -6.8179; ty= -3.9778; tz= -5.9887 },
+ { a=0.5855; b=0.7931; c= -0.1682; (* P_O3'_60_tfo *)
+ d=0.8103; e= -0.5790; f=0.0906;
+ g= -0.0255; h= -0.1894; i= -0.9816;
+ tx=6.1203; ty= -7.1051; tz=3.1984 },
+ { x = 2.6760; y = -8.4960; z = 3.2880 }, (* P *)
+ { x = 1.4950; y = -7.6230; z = 3.4770 }, (* O1P *)
+ { x = 2.9490; y = -9.4640; z = 4.3740 }, (* O2P *)
+ { x = 3.9730; y = -7.5950; z = 3.0340 }, (* O5' *)
+ { x = 5.2430; y = -8.2420; z = 2.8260 }, (* C5' *)
+ { x = 5.1974; y = -8.8497; z = 1.9223 }, (* H5' *)
+ { x = 5.5548; y = -8.7348; z = 3.7469 }, (* H5'' *)
+ { x = 6.3140; y = -7.2060; z = 2.5510 }, (* C4' *)
+ { x = 5.8744; y = -6.2116; z = 2.4731 }, (* H4' *)
+ { x = 7.2798; y = -7.2260; z = 3.6420 }, (* O4' *)
+ { x = 8.5733; y = -6.9410; z = 3.1329 }, (* C1' *)
+ { x = 8.9047; y = -6.0374; z = 3.6446 }, (* H1' *)
+ { x = 8.4429; y = -6.6596; z = 1.6327 }, (* C2' *)
+ { x = 9.2880; y = -7.1071; z = 1.1096 }, (* H2'' *)
+ { x = 8.2502; y = -5.2799; z = 1.4754 }, (* O2' *)
+ { x = 8.7676; y = -4.7284; z = 2.0667 }, (* H2' *)
+ { x = 7.1642; y = -7.4416; z = 1.3021 }, (* C3' *)
+ { x = 7.4125; y = -8.5002; z = 1.2260 }, (* H3' *)
+ { x = 6.5160; y = -6.9772; z = 0.1267 }, (* O3' *)
+ { x = 9.4531; y = -8.1107; z = 3.4087 }, (* N1 *)
+ { x = 11.5931; y = -9.0015; z = 3.6357 }, (* N3 *)
+ { x = 10.8101; y = -7.8950; z = 3.3748 }, (* C2 *)
+ { x = 11.1439; y = -10.2744; z = 3.9206 }, (* C4 *)
+ { x = 9.7056; y = -10.4026; z = 3.9332 }, (* C5 *)
+ { x = 8.9192; y = -9.3419; z = 3.6833 }, (* C6 *)
+ (U (
+ { x = 11.3013; y = -6.8063; z = 3.1326 }, (* O2 *)
+ { x = 11.9431; y = -11.1876; z = 4.1375 }, (* O4 *)
+ { x = 12.5840; y = -8.8673; z = 3.6158 }, (* H3 *)
+ { x = 9.2891; y = -11.2898; z = 4.1313 }, (* H5 *)
+ { x = 7.9263; y = -9.4537; z = 3.6977 }) (* H6 *)
+ )
+ )
+
+(* -- PARTIAL INSTANTIATIONS ------------------------------------------------*)
+
+type variable =
+ { id : int;
+ t : tfo;
+ n : nuc }
+
+let mk_var i t n = { id = i; t = t; n = n }
+
+let absolute_pos v p = tfo_apply v.t p
+
+let atom_pos atom v = absolute_pos v (atom v.n)
+
+let rec get_var id = function
+ | (v::lst) -> if id = v.id then v else get_var id lst
+ | _ -> assert false
+
+(* -- SEARCH ----------------------------------------------------------------*)
+
+(* Sequential backtracking algorithm *)
+
+let rec search (partial_inst : variable list) l constr =
+ match l with
+ [] -> [partial_inst]
+ | (h::t) ->
+ let rec try_assignments = function
+ [] -> []
+ | v::vs ->
+ if constr v partial_inst then
+ (search (v::partial_inst) t constr) @ (try_assignments vs)
+ else
+ try_assignments vs
+ in
+ try_assignments (h partial_inst)
+
+
+(* -- DOMAINS ---------------------------------------------------------------*)
+
+(* Primary structure: strand A CUGCCACGUCUG, strand B CAGACGUGGCAG
+
+ Secondary structure: strand A CUGCCACGUCUG
+ ||||||||||||
+ GACGGUGCAGAC strand B
+
+ Tertiary structure:
+
+ 5' end of strand A C1----G12 3' end of strand B
+ U2-------A11
+ G3-------C10
+ C4-----G9
+ C5---G8
+ A6
+ G6-C7
+ C5----G8
+ A4-------U9
+ G3--------C10
+ A2-------U11
+ 5' end of strand B C1----G12 3' end of strand A
+
+ "helix", "stacked" and "connected" describe the spatial relationship
+ between two consecutive nucleotides. E.g. the nucleotides C1 and U2
+ from the strand A.
+
+ "wc" (stands for Watson-Crick and is a type of base-pairing),
+ and "wc-dumas" describe the spatial relationship between
+ nucleotides from two chains that are growing in opposite directions.
+ E.g. the nucleotides C1 from strand A and G12 from strand B.
+*)
+
+(* Dynamic Domains *)
+
+(* Given,
+ "refnuc" a nucleotide which is already positioned,
+ "nucl" the nucleotide to be placed,
+ and "tfo" a transformation matrix which expresses the desired
+ relationship between "refnuc" and "nucl",
+ the function "dgf-base" computes the transformation matrix that
+ places the nucleotide "nucl" in the given relationship to "refnuc".
+*)
+
+let
+dgf_base tfo v nucl
+ = let x = if is_A v.n then
+ tfo_align (atom_pos nuc_C1' v)
+ (atom_pos rA_N9 v)
+ (atom_pos nuc_C4 v)
+ else if is_C v.n then
+ tfo_align (atom_pos nuc_C1' v)
+ (atom_pos nuc_N1 v)
+ (atom_pos nuc_C2 v)
+ else if is_G v.n then
+ tfo_align (atom_pos nuc_C1' v)
+ (atom_pos rG_N9 v)
+ (atom_pos nuc_C4 v)
+ else
+ tfo_align (atom_pos nuc_C1' v)
+ (atom_pos nuc_N1 v)
+ (atom_pos nuc_C2 v)
+ in
+ tfo_combine (nuc_dgf_base_tfo nucl)
+ (tfo_combine tfo (tfo_inv_ortho x))
+
+(* Placement of first nucleotide. *)
+
+let
+reference n i partial_inst = [ mk_var i tfo_id n ]
+
+(* The transformation matrix for wc is from:
+
+ Chandrasekaran R. et al (1989) A Re-Examination of the Crystal
+ Structure of A-DNA Using Fiber Diffraction Data. J. Biomol.
+ Struct. & Dynamics 6(6):1189-1202.
+*)
+
+let wc_tfo
+ = (
+ { a= -1.0000; b=0.0028; c= -0.0019;
+ d=0.0028; e=0.3468; f= -0.9379;
+ g= -0.0019; h= -0.9379; i= -0.3468;
+ tx= -0.0080; ty=6.0730; tz=8.7208 }
+ )
+
+let
+wc nucl i j partial_inst
+ = [ mk_var i (dgf_base wc_tfo (get_var j partial_inst) nucl) nucl ]
+
+let wc_dumas_tfo
+ = (
+ { a= -0.9737; b= -0.1834; c=0.1352;
+ d= -0.1779; e=0.2417; f= -0.9539;
+ g=0.1422; h= -0.9529; i= -0.2679;
+ tx=0.4837; ty=6.2649; tz=8.0285 }
+ )
+
+let
+wc_dumas nucl i j partial_inst
+ = [ mk_var i (dgf_base wc_dumas_tfo (get_var j partial_inst) nucl) nucl ]
+
+let helix5'_tfo
+ = (
+ { a=0.9886; b= -0.0961; c=0.1156;
+ d=0.1424; e=0.8452; f= -0.5152;
+ g= -0.0482; h=0.5258; i=0.8492;
+ tx= -3.8737; ty=0.5480; tz=3.8024 }
+ )
+
+let
+helix5' nucl i j partial_inst
+ = [ mk_var i (dgf_base helix5'_tfo (get_var j partial_inst) nucl) nucl ]
+
+let helix3'_tfo
+ = (
+ { a=0.9886; b=0.1424; c= -0.0482;
+ d= -0.0961; e=0.8452; f=0.5258;
+ g=0.1156; h= -0.5152; i=0.8492;
+ tx=3.4426; ty=2.0474; tz= -3.7042 }
+ )
+
+let
+helix3' nucl i j partial_inst
+ = [ mk_var i (dgf_base helix3'_tfo (get_var j partial_inst) nucl) nucl ]
+
+let g37_a38_tfo
+ = (
+ { a=0.9991; b=0.0164; c= -0.0387;
+ d= -0.0375; e=0.7616; f= -0.6470;
+ g=0.0189; h=0.6478; i=0.7615;
+ tx= -3.3018; ty=0.9975; tz=2.5585 }
+ )
+
+let
+g37_a38 nucl i j partial_inst
+ = mk_var i (dgf_base g37_a38_tfo (get_var j partial_inst) nucl) nucl
+
+let
+stacked5' nucl i j partial_inst
+ = (g37_a38 nucl i j partial_inst) :: (helix5' nucl i j partial_inst)
+
+let a38_g37_tfo
+ = (
+ { a=0.9991; b= -0.0375; c=0.0189;
+ d=0.0164; e=0.7616; f=0.6478;
+ g= -0.0387; h= -0.6470; i=0.7615;
+ tx=3.3819; ty=0.7718; tz= -2.5321 }
+ )
+
+let
+a38_g37 nucl i j partial_inst
+ = mk_var i (dgf_base a38_g37_tfo (get_var j partial_inst) nucl) nucl
+
+let
+stacked3' nucl i j partial_inst
+ = (a38_g37 nucl i j partial_inst) :: (helix3' nucl i j partial_inst)
+
+let
+p_o3' nucls i j partial_inst
+ = let refnuc = get_var j partial_inst in
+ let align = tfo_inv_ortho
+ (tfo_align (atom_pos nuc_O3' refnuc)
+ (atom_pos nuc_C3' refnuc)
+ (atom_pos nuc_C4' refnuc)) in
+ let rec generate domains = function
+ [] -> domains
+ | n::ns ->
+ generate
+ ((mk_var i (tfo_combine (nuc_p_o3'_60_tfo n) align) n)::
+ (mk_var i (tfo_combine (nuc_p_o3'_180_tfo n) align) n)::
+ (mk_var i (tfo_combine (nuc_p_o3'_275_tfo n) align) n)::domains)
+ ns
+ in
+ generate [] nucls
+
+(* -- PROBLEM STATEMENT -----------------------------------------------------*)
+
+(* Define anticodon problem -- Science 253:1255 Figure 3a, 3b and 3c *)
+
+let
+anticodon_domains
+ = [
+ reference rC 27;
+ helix5' rC 28 27;
+ helix5' rA 29 28;
+ helix5' rG 30 29;
+ helix5' rA 31 30;
+ wc rU 39 31;
+ helix5' rC 40 39;
+ helix5' rU 41 40;
+ helix5' rG 42 41;
+ helix5' rG 43 42;
+ stacked3' rA 38 39;
+ stacked3' rG 37 38;
+ stacked3' rA 36 37;
+ stacked3' rA 35 36;
+ stacked3' rG 34 35; (* <-. Distance *)
+ p_o3' rCs 32 31; (* | Constraint *)
+ p_o3' rUs 33 32 (* <-' 3.0 Angstroms *)
+ ]
+
+(* Anticodon constraint *)
+
+let
+anticodon_constraint v partial_inst =
+ let rec dist j = let p = atom_pos nuc_P (get_var j partial_inst) in
+ let o3' = atom_pos nuc_O3' v in
+ pt_dist p o3'
+ in
+ if v.id = 33 then
+ (dist 34) <= 3.0
+ else
+ true
+
+let
+anticodon () = search [] anticodon_domains anticodon_constraint
+
+(* Define pseudoknot problem -- Science 253:1255 Figure 4a and 4b *)
+
+let
+pseudoknot_domains
+ = [
+ reference rA 23;
+ wc_dumas rU 8 23;
+ helix3' rG 22 23;
+ wc_dumas rC 9 22;
+ helix3' rG 21 22;
+ wc_dumas rC 10 21;
+ helix3' rC 20 21;
+ wc_dumas rG 11 20;
+ helix3' rU' 19 20; (* <-. *)
+ wc_dumas rA 12 19; (* | Distance *)
+(* | Constraint *)
+(* Helix 1 | 4.0 Angstroms *)
+ helix3' rC 3 19; (* | *)
+ wc_dumas rG 13 3; (* | *)
+ helix3' rC 2 3; (* | *)
+ wc_dumas rG 14 2; (* | *)
+ helix3' rC 1 2; (* | *)
+ wc_dumas rG' 15 1; (* | *)
+(* | *)
+(* L2 LOOP | *)
+ p_o3' rUs 16 15; (* | *)
+ p_o3' rCs 17 16; (* | *)
+ p_o3' rAs 18 17; (* <-' *)
+(* *)
+(* L1 LOOP *)
+ helix3' rU 7 8; (* <-. *)
+ p_o3' rCs 4 3; (* | Constraint *)
+ stacked5' rU 5 4; (* | 4.5 Angstroms *)
+ stacked5' rC 6 5 (* <-' *)
+ ]
+
+(* Pseudoknot constraint *)
+
+let
+pseudoknot_constraint v partial_inst =
+ let rec dist j =
+ let p = atom_pos nuc_P (get_var j partial_inst) in
+ let o3' = atom_pos nuc_O3' v in
+ pt_dist p o3'
+ in
+ if v.id = 18 then
+ (dist 19) <= 4.0
+ else if v.id = 6 then
+ (dist 7) <= 4.5
+ else
+ true
+
+let
+pseudoknot () = search [] pseudoknot_domains pseudoknot_constraint
+
+(* -- TESTING ---------------------------------------------------------------*)
+
+let list_of_atoms = function
+ (N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,
+ A (n6,n7,n9,c8,h2,h61,h62,h8)))
+ -> [|p;o1p;o2p;o5';c5';h5';h5'';c4';h4';o4';c1';h1';c2';h2'';o2';h2';c3';
+ h3';o3';n1;n3;c2;c4;c5;c6;n6;n7;n9;c8;h2;h61;h62;h8|]
+
+| (N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,
+ C (n4,o2,h41,h42,h5,h6)))
+ -> [|p;o1p;o2p;o5';c5';h5';h5'';c4';h4';o4';c1';h1';c2';h2'';o2';h2';c3';
+ h3';o3';n1;n3;c2;c4;c5;c6;n4;o2;h41;h42;h5;h6|]
+
+| (N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,
+ G (n2,n7,n9,c8,o6,h1,h21,h22,h8)))
+ -> [|p;o1p;o2p;o5';c5';h5';h5'';c4';h4';o4';c1';h1';c2';h2'';o2';h2';c3';
+ h3';o3';n1;n3;c2;c4;c5;c6;n2;n7;n9;c8;o6;h1;h21;h22;h8|]
+
+| (N(dgf_base_tfo,p_o3'_275_tfo,p_o3'_180_tfo,p_o3'_60_tfo,
+ p,o1p,o2p,o5',c5',h5',h5'',c4',h4',o4',c1',h1',c2',h2'',o2',h2',
+ c3',h3',o3',n1,n3,c2,c4,c5,c6,
+ U (o2,o4,h3,h5,h6)))
+ -> [|p;o1p;o2p;o5';c5';h5';h5'';c4';h4';o4';c1';h1';c2';h2'';o2';h2';c3';
+ h3';o3';n1;n3;c2;c4;c5;c6;o2;o4;h3;h5;h6|]
+
+let maximum = function
+ | x::xs ->
+ let rec iter m = function
+ [] -> m
+ | (a::b) -> iter (if a > m then a else m) b
+ in
+ iter x xs
+ | _ -> assert false
+
+let
+var_most_distant_atom v =
+ let atoms = list_of_atoms v.n in
+ let max_dist = ref 0.0 in
+ for i = 0 to pred (Array.length atoms) do
+ let p = atoms.(i) in
+ let distance =
+ let pos = absolute_pos v p
+ in sqrt ((pos.x * pos.x) + (pos.y * pos.y) + (pos.z * pos.z)) in
+ if distance > !max_dist then max_dist := distance
+ done;
+ !max_dist
+
+let
+sol_most_distant_atom s = maximum (List.map var_most_distant_atom s)
+
+let
+most_distant_atom sols = maximum (List.map sol_most_distant_atom sols)
+
+let
+check () = List.length (pseudoknot ())
+
+let
+run () = most_distant_atom (pseudoknot ())
+
+let main () =
+ for i = 1 to 50 do ignore(run()) done;
+ Printf.printf "%.4f" (run ()); print_newline()
+
+let _ = main ()
diff --git a/testsuite/tests/misc/nucleic.reference b/testsuite/tests/misc/nucleic.reference
new file mode 100644
index 0000000000..14689cdb97
--- /dev/null
+++ b/testsuite/tests/misc/nucleic.reference
@@ -0,0 +1 @@
+33.7976
diff --git a/testsuite/tests/misc/sieve.ml b/testsuite/tests/misc/sieve.ml
new file mode 100644
index 0000000000..7d8d21bdbe
--- /dev/null
+++ b/testsuite/tests/misc/sieve.ml
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Eratosthene's sieve *)
+
+(* interval min max = [min; min+1; ...; max-1; max] *)
+
+let rec interval min max =
+ if min > max then [] else min :: interval (min + 1) max
+
+
+(* filter p L returns the list of the elements in list L
+ that satisfy predicate p *)
+
+let rec filter p = function
+ [] -> []
+ | a::r -> if p a then a :: filter p r else filter p r
+
+
+(* Application: removing all numbers multiple of n from a list of integers *)
+
+let remove_multiples_of n =
+ filter (fun m -> m mod n <> 0)
+
+
+(* The sieve itself *)
+
+let sieve max =
+ let rec filter_again = function
+ [] -> []
+ | n::r as l ->
+ if n*n > max then l else n :: filter_again (remove_multiples_of n r)
+ in
+ filter_again (interval 2 max)
+
+
+let rec do_list f = function
+ [] -> ()
+ | a::l -> f a; do_list f l
+
+
+let _ =
+ do_list (fun n -> print_string " "; print_int n) (sieve 50000);
+ print_newline();
+ exit 0
diff --git a/testsuite/tests/misc/sieve.reference b/testsuite/tests/misc/sieve.reference
new file mode 100644
index 0000000000..24f5cc544a
--- /dev/null
+++ b/testsuite/tests/misc/sieve.reference
@@ -0,0 +1 @@
+ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 1229 1231 1237 1249 1259 1277 1279 1283 1289 1291 1297 1301 1303 1307 1319 1321 1327 1361 1367 1373 1381 1399 1409 1423 1427 1429 1433 1439 1447 1451 1453 1459 1471 1481 1483 1487 1489 1493 1499 1511 1523 1531 1543 1549 1553 1559 1567 1571 1579 1583 1597 1601 1607 1609 1613 1619 1621 1627 1637 1657 1663 1667 1669 1693 1697 1699 1709 1721 1723 1733 1741 1747 1753 1759 1777 1783 1787 1789 1801 1811 1823 1831 1847 1861 1867 1871 1873 1877 1879 1889 1901 1907 1913 1931 1933 1949 1951 1973 1979 1987 1993 1997 1999 2003 2011 2017 2027 2029 2039 2053 2063 2069 2081 2083 2087 2089 2099 2111 2113 2129 2131 2137 2141 2143 2153 2161 2179 2203 2207 2213 2221 2237 2239 2243 2251 2267 2269 2273 2281 2287 2293 2297 2309 2311 2333 2339 2341 2347 2351 2357 2371 2377 2381 2383 2389 2393 2399 2411 2417 2423 2437 2441 2447 2459 2467 2473 2477 2503 2521 2531 2539 2543 2549 2551 2557 2579 2591 2593 2609 2617 2621 2633 2647 2657 2659 2663 2671 2677 2683 2687 2689 2693 2699 2707 2711 2713 2719 2729 2731 2741 2749 2753 2767 2777 2789 2791 2797 2801 2803 2819 2833 2837 2843 2851 2857 2861 2879 2887 2897 2903 2909 2917 2927 2939 2953 2957 2963 2969 2971 2999 3001 3011 3019 3023 3037 3041 3049 3061 3067 3079 3083 3089 3109 3119 3121 3137 3163 3167 3169 3181 3187 3191 3203 3209 3217 3221 3229 3251 3253 3257 3259 3271 3299 3301 3307 3313 3319 3323 3329 3331 3343 3347 3359 3361 3371 3373 3389 3391 3407 3413 3433 3449 3457 3461 3463 3467 3469 3491 3499 3511 3517 3527 3529 3533 3539 3541 3547 3557 3559 3571 3581 3583 3593 3607 3613 3617 3623 3631 3637 3643 3659 3671 3673 3677 3691 3697 3701 3709 3719 3727 3733 3739 3761 3767 3769 3779 3793 3797 3803 3821 3823 3833 3847 3851 3853 3863 3877 3881 3889 3907 3911 3917 3919 3923 3929 3931 3943 3947 3967 3989 4001 4003 4007 4013 4019 4021 4027 4049 4051 4057 4073 4079 4091 4093 4099 4111 4127 4129 4133 4139 4153 4157 4159 4177 4201 4211 4217 4219 4229 4231 4241 4243 4253 4259 4261 4271 4273 4283 4289 4297 4327 4337 4339 4349 4357 4363 4373 4391 4397 4409 4421 4423 4441 4447 4451 4457 4463 4481 4483 4493 4507 4513 4517 4519 4523 4547 4549 4561 4567 4583 4591 4597 4603 4621 4637 4639 4643 4649 4651 4657 4663 4673 4679 4691 4703 4721 4723 4729 4733 4751 4759 4783 4787 4789 4793 4799 4801 4813 4817 4831 4861 4871 4877 4889 4903 4909 4919 4931 4933 4937 4943 4951 4957 4967 4969 4973 4987 4993 4999 5003 5009 5011 5021 5023 5039 5051 5059 5077 5081 5087 5099 5101 5107 5113 5119 5147 5153 5167 5171 5179 5189 5197 5209 5227 5231 5233 5237 5261 5273 5279 5281 5297 5303 5309 5323 5333 5347 5351 5381 5387 5393 5399 5407 5413 5417 5419 5431 5437 5441 5443 5449 5471 5477 5479 5483 5501 5503 5507 5519 5521 5527 5531 5557 5563 5569 5573 5581 5591 5623 5639 5641 5647 5651 5653 5657 5659 5669 5683 5689 5693 5701 5711 5717 5737 5741 5743 5749 5779 5783 5791 5801 5807 5813 5821 5827 5839 5843 5849 5851 5857 5861 5867 5869 5879 5881 5897 5903 5923 5927 5939 5953 5981 5987 6007 6011 6029 6037 6043 6047 6053 6067 6073 6079 6089 6091 6101 6113 6121 6131 6133 6143 6151 6163 6173 6197 6199 6203 6211 6217 6221 6229 6247 6257 6263 6269 6271 6277 6287 6299 6301 6311 6317 6323 6329 6337 6343 6353 6359 6361 6367 6373 6379 6389 6397 6421 6427 6449 6451 6469 6473 6481 6491 6521 6529 6547 6551 6553 6563 6569 6571 6577 6581 6599 6607 6619 6637 6653 6659 6661 6673 6679 6689 6691 6701 6703 6709 6719 6733 6737 6761 6763 6779 6781 6791 6793 6803 6823 6827 6829 6833 6841 6857 6863 6869 6871 6883 6899 6907 6911 6917 6947 6949 6959 6961 6967 6971 6977 6983 6991 6997 7001 7013 7019 7027 7039 7043 7057 7069 7079 7103 7109 7121 7127 7129 7151 7159 7177 7187 7193 7207 7211 7213 7219 7229 7237 7243 7247 7253 7283 7297 7307 7309 7321 7331 7333 7349 7351 7369 7393 7411 7417 7433 7451 7457 7459 7477 7481 7487 7489 7499 7507 7517 7523 7529 7537 7541 7547 7549 7559 7561 7573 7577 7583 7589 7591 7603 7607 7621 7639 7643 7649 7669 7673 7681 7687 7691 7699 7703 7717 7723 7727 7741 7753 7757 7759 7789 7793 7817 7823 7829 7841 7853 7867 7873 7877 7879 7883 7901 7907 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081 8087 8089 8093 8101 8111 8117 8123 8147 8161 8167 8171 8179 8191 8209 8219 8221 8231 8233 8237 8243 8263 8269 8273 8287 8291 8293 8297 8311 8317 8329 8353 8363 8369 8377 8387 8389 8419 8423 8429 8431 8443 8447 8461 8467 8501 8513 8521 8527 8537 8539 8543 8563 8573 8581 8597 8599 8609 8623 8627 8629 8641 8647 8663 8669 8677 8681 8689 8693 8699 8707 8713 8719 8731 8737 8741 8747 8753 8761 8779 8783 8803 8807 8819 8821 8831 8837 8839 8849 8861 8863 8867 8887 8893 8923 8929 8933 8941 8951 8963 8969 8971 8999 9001 9007 9011 9013 9029 9041 9043 9049 9059 9067 9091 9103 9109 9127 9133 9137 9151 9157 9161 9173 9181 9187 9199 9203 9209 9221 9227 9239 9241 9257 9277 9281 9283 9293 9311 9319 9323 9337 9341 9343 9349 9371 9377 9391 9397 9403 9413 9419 9421 9431 9433 9437 9439 9461 9463 9467 9473 9479 9491 9497 9511 9521 9533 9539 9547 9551 9587 9601 9613 9619 9623 9629 9631 9643 9649 9661 9677 9679 9689 9697 9719 9721 9733 9739 9743 9749 9767 9769 9781 9787 9791 9803 9811 9817 9829 9833 9839 9851 9857 9859 9871 9883 9887 9901 9907 9923 9929 9931 9941 9949 9967 9973 10007 10009 10037 10039 10061 10067 10069 10079 10091 10093 10099 10103 10111 10133 10139 10141 10151 10159 10163 10169 10177 10181 10193 10211 10223 10243 10247 10253 10259 10267 10271 10273 10289 10301 10303 10313 10321 10331 10333 10337 10343 10357 10369 10391 10399 10427 10429 10433 10453 10457 10459 10463 10477 10487 10499 10501 10513 10529 10531 10559 10567 10589 10597 10601 10607 10613 10627 10631 10639 10651 10657 10663 10667 10687 10691 10709 10711 10723 10729 10733 10739 10753 10771 10781 10789 10799 10831 10837 10847 10853 10859 10861 10867 10883 10889 10891 10903 10909 10937 10939 10949 10957 10973 10979 10987 10993 11003 11027 11047 11057 11059 11069 11071 11083 11087 11093 11113 11117 11119 11131 11149 11159 11161 11171 11173 11177 11197 11213 11239 11243 11251 11257 11261 11273 11279 11287 11299 11311 11317 11321 11329 11351 11353 11369 11383 11393 11399 11411 11423 11437 11443 11447 11467 11471 11483 11489 11491 11497 11503 11519 11527 11549 11551 11579 11587 11593 11597 11617 11621 11633 11657 11677 11681 11689 11699 11701 11717 11719 11731 11743 11777 11779 11783 11789 11801 11807 11813 11821 11827 11831 11833 11839 11863 11867 11887 11897 11903 11909 11923 11927 11933 11939 11941 11953 11959 11969 11971 11981 11987 12007 12011 12037 12041 12043 12049 12071 12073 12097 12101 12107 12109 12113 12119 12143 12149 12157 12161 12163 12197 12203 12211 12227 12239 12241 12251 12253 12263 12269 12277 12281 12289 12301 12323 12329 12343 12347 12373 12377 12379 12391 12401 12409 12413 12421 12433 12437 12451 12457 12473 12479 12487 12491 12497 12503 12511 12517 12527 12539 12541 12547 12553 12569 12577 12583 12589 12601 12611 12613 12619 12637 12641 12647 12653 12659 12671 12689 12697 12703 12713 12721 12739 12743 12757 12763 12781 12791 12799 12809 12821 12823 12829 12841 12853 12889 12893 12899 12907 12911 12917 12919 12923 12941 12953 12959 12967 12973 12979 12983 13001 13003 13007 13009 13033 13037 13043 13049 13063 13093 13099 13103 13109 13121 13127 13147 13151 13159 13163 13171 13177 13183 13187 13217 13219 13229 13241 13249 13259 13267 13291 13297 13309 13313 13327 13331 13337 13339 13367 13381 13397 13399 13411 13417 13421 13441 13451 13457 13463 13469 13477 13487 13499 13513 13523 13537 13553 13567 13577 13591 13597 13613 13619 13627 13633 13649 13669 13679 13681 13687 13691 13693 13697 13709 13711 13721 13723 13729 13751 13757 13759 13763 13781 13789 13799 13807 13829 13831 13841 13859 13873 13877 13879 13883 13901 13903 13907 13913 13921 13931 13933 13963 13967 13997 13999 14009 14011 14029 14033 14051 14057 14071 14081 14083 14087 14107 14143 14149 14153 14159 14173 14177 14197 14207 14221 14243 14249 14251 14281 14293 14303 14321 14323 14327 14341 14347 14369 14387 14389 14401 14407 14411 14419 14423 14431 14437 14447 14449 14461 14479 14489 14503 14519 14533 14537 14543 14549 14551 14557 14561 14563 14591 14593 14621 14627 14629 14633 14639 14653 14657 14669 14683 14699 14713 14717 14723 14731 14737 14741 14747 14753 14759 14767 14771 14779 14783 14797 14813 14821 14827 14831 14843 14851 14867 14869 14879 14887 14891 14897 14923 14929 14939 14947 14951 14957 14969 14983 15013 15017 15031 15053 15061 15073 15077 15083 15091 15101 15107 15121 15131 15137 15139 15149 15161 15173 15187 15193 15199 15217 15227 15233 15241 15259 15263 15269 15271 15277 15287 15289 15299 15307 15313 15319 15329 15331 15349 15359 15361 15373 15377 15383 15391 15401 15413 15427 15439 15443 15451 15461 15467 15473 15493 15497 15511 15527 15541 15551 15559 15569 15581 15583 15601 15607 15619 15629 15641 15643 15647 15649 15661 15667 15671 15679 15683 15727 15731 15733 15737 15739 15749 15761 15767 15773 15787 15791 15797 15803 15809 15817 15823 15859 15877 15881 15887 15889 15901 15907 15913 15919 15923 15937 15959 15971 15973 15991 16001 16007 16033 16057 16061 16063 16067 16069 16073 16087 16091 16097 16103 16111 16127 16139 16141 16183 16187 16189 16193 16217 16223 16229 16231 16249 16253 16267 16273 16301 16319 16333 16339 16349 16361 16363 16369 16381 16411 16417 16421 16427 16433 16447 16451 16453 16477 16481 16487 16493 16519 16529 16547 16553 16561 16567 16573 16603 16607 16619 16631 16633 16649 16651 16657 16661 16673 16691 16693 16699 16703 16729 16741 16747 16759 16763 16787 16811 16823 16829 16831 16843 16871 16879 16883 16889 16901 16903 16921 16927 16931 16937 16943 16963 16979 16981 16987 16993 17011 17021 17027 17029 17033 17041 17047 17053 17077 17093 17099 17107 17117 17123 17137 17159 17167 17183 17189 17191 17203 17207 17209 17231 17239 17257 17291 17293 17299 17317 17321 17327 17333 17341 17351 17359 17377 17383 17387 17389 17393 17401 17417 17419 17431 17443 17449 17467 17471 17477 17483 17489 17491 17497 17509 17519 17539 17551 17569 17573 17579 17581 17597 17599 17609 17623 17627 17657 17659 17669 17681 17683 17707 17713 17729 17737 17747 17749 17761 17783 17789 17791 17807 17827 17837 17839 17851 17863 17881 17891 17903 17909 17911 17921 17923 17929 17939 17957 17959 17971 17977 17981 17987 17989 18013 18041 18043 18047 18049 18059 18061 18077 18089 18097 18119 18121 18127 18131 18133 18143 18149 18169 18181 18191 18199 18211 18217 18223 18229 18233 18251 18253 18257 18269 18287 18289 18301 18307 18311 18313 18329 18341 18353 18367 18371 18379 18397 18401 18413 18427 18433 18439 18443 18451 18457 18461 18481 18493 18503 18517 18521 18523 18539 18541 18553 18583 18587 18593 18617 18637 18661 18671 18679 18691 18701 18713 18719 18731 18743 18749 18757 18773 18787 18793 18797 18803 18839 18859 18869 18899 18911 18913 18917 18919 18947 18959 18973 18979 19001 19009 19013 19031 19037 19051 19069 19073 19079 19081 19087 19121 19139 19141 19157 19163 19181 19183 19207 19211 19213 19219 19231 19237 19249 19259 19267 19273 19289 19301 19309 19319 19333 19373 19379 19381 19387 19391 19403 19417 19421 19423 19427 19429 19433 19441 19447 19457 19463 19469 19471 19477 19483 19489 19501 19507 19531 19541 19543 19553 19559 19571 19577 19583 19597 19603 19609 19661 19681 19687 19697 19699 19709 19717 19727 19739 19751 19753 19759 19763 19777 19793 19801 19813 19819 19841 19843 19853 19861 19867 19889 19891 19913 19919 19927 19937 19949 19961 19963 19973 19979 19991 19993 19997 20011 20021 20023 20029 20047 20051 20063 20071 20089 20101 20107 20113 20117 20123 20129 20143 20147 20149 20161 20173 20177 20183 20201 20219 20231 20233 20249 20261 20269 20287 20297 20323 20327 20333 20341 20347 20353 20357 20359 20369 20389 20393 20399 20407 20411 20431 20441 20443 20477 20479 20483 20507 20509 20521 20533 20543 20549 20551 20563 20593 20599 20611 20627 20639 20641 20663 20681 20693 20707 20717 20719 20731 20743 20747 20749 20753 20759 20771 20773 20789 20807 20809 20849 20857 20873 20879 20887 20897 20899 20903 20921 20929 20939 20947 20959 20963 20981 20983 21001 21011 21013 21017 21019 21023 21031 21059 21061 21067 21089 21101 21107 21121 21139 21143 21149 21157 21163 21169 21179 21187 21191 21193 21211 21221 21227 21247 21269 21277 21283 21313 21317 21319 21323 21341 21347 21377 21379 21383 21391 21397 21401 21407 21419 21433 21467 21481 21487 21491 21493 21499 21503 21517 21521 21523 21529 21557 21559 21563 21569 21577 21587 21589 21599 21601 21611 21613 21617 21647 21649 21661 21673 21683 21701 21713 21727 21737 21739 21751 21757 21767 21773 21787 21799 21803 21817 21821 21839 21841 21851 21859 21863 21871 21881 21893 21911 21929 21937 21943 21961 21977 21991 21997 22003 22013 22027 22031 22037 22039 22051 22063 22067 22073 22079 22091 22093 22109 22111 22123 22129 22133 22147 22153 22157 22159 22171 22189 22193 22229 22247 22259 22271 22273 22277 22279 22283 22291 22303 22307 22343 22349 22367 22369 22381 22391 22397 22409 22433 22441 22447 22453 22469 22481 22483 22501 22511 22531 22541 22543 22549 22567 22571 22573 22613 22619 22621 22637 22639 22643 22651 22669 22679 22691 22697 22699 22709 22717 22721 22727 22739 22741 22751 22769 22777 22783 22787 22807 22811 22817 22853 22859 22861 22871 22877 22901 22907 22921 22937 22943 22961 22963 22973 22993 23003 23011 23017 23021 23027 23029 23039 23041 23053 23057 23059 23063 23071 23081 23087 23099 23117 23131 23143 23159 23167 23173 23189 23197 23201 23203 23209 23227 23251 23269 23279 23291 23293 23297 23311 23321 23327 23333 23339 23357 23369 23371 23399 23417 23431 23447 23459 23473 23497 23509 23531 23537 23539 23549 23557 23561 23563 23567 23581 23593 23599 23603 23609 23623 23627 23629 23633 23663 23669 23671 23677 23687 23689 23719 23741 23743 23747 23753 23761 23767 23773 23789 23801 23813 23819 23827 23831 23833 23857 23869 23873 23879 23887 23893 23899 23909 23911 23917 23929 23957 23971 23977 23981 23993 24001 24007 24019 24023 24029 24043 24049 24061 24071 24077 24083 24091 24097 24103 24107 24109 24113 24121 24133 24137 24151 24169 24179 24181 24197 24203 24223 24229 24239 24247 24251 24281 24317 24329 24337 24359 24371 24373 24379 24391 24407 24413 24419 24421 24439 24443 24469 24473 24481 24499 24509 24517 24527 24533 24547 24551 24571 24593 24611 24623 24631 24659 24671 24677 24683 24691 24697 24709 24733 24749 24763 24767 24781 24793 24799 24809 24821 24841 24847 24851 24859 24877 24889 24907 24917 24919 24923 24943 24953 24967 24971 24977 24979 24989 25013 25031 25033 25037 25057 25073 25087 25097 25111 25117 25121 25127 25147 25153 25163 25169 25171 25183 25189 25219 25229 25237 25243 25247 25253 25261 25301 25303 25307 25309 25321 25339 25343 25349 25357 25367 25373 25391 25409 25411 25423 25439 25447 25453 25457 25463 25469 25471 25523 25537 25541 25561 25577 25579 25583 25589 25601 25603 25609 25621 25633 25639 25643 25657 25667 25673 25679 25693 25703 25717 25733 25741 25747 25759 25763 25771 25793 25799 25801 25819 25841 25847 25849 25867 25873 25889 25903 25913 25919 25931 25933 25939 25943 25951 25969 25981 25997 25999 26003 26017 26021 26029 26041 26053 26083 26099 26107 26111 26113 26119 26141 26153 26161 26171 26177 26183 26189 26203 26209 26227 26237 26249 26251 26261 26263 26267 26293 26297 26309 26317 26321 26339 26347 26357 26371 26387 26393 26399 26407 26417 26423 26431 26437 26449 26459 26479 26489 26497 26501 26513 26539 26557 26561 26573 26591 26597 26627 26633 26641 26647 26669 26681 26683 26687 26693 26699 26701 26711 26713 26717 26723 26729 26731 26737 26759 26777 26783 26801 26813 26821 26833 26839 26849 26861 26863 26879 26881 26891 26893 26903 26921 26927 26947 26951 26953 26959 26981 26987 26993 27011 27017 27031 27043 27059 27061 27067 27073 27077 27091 27103 27107 27109 27127 27143 27179 27191 27197 27211 27239 27241 27253 27259 27271 27277 27281 27283 27299 27329 27337 27361 27367 27397 27407 27409 27427 27431 27437 27449 27457 27479 27481 27487 27509 27527 27529 27539 27541 27551 27581 27583 27611 27617 27631 27647 27653 27673 27689 27691 27697 27701 27733 27737 27739 27743 27749 27751 27763 27767 27773 27779 27791 27793 27799 27803 27809 27817 27823 27827 27847 27851 27883 27893 27901 27917 27919 27941 27943 27947 27953 27961 27967 27983 27997 28001 28019 28027 28031 28051 28057 28069 28081 28087 28097 28099 28109 28111 28123 28151 28163 28181 28183 28201 28211 28219 28229 28277 28279 28283 28289 28297 28307 28309 28319 28349 28351 28387 28393 28403 28409 28411 28429 28433 28439 28447 28463 28477 28493 28499 28513 28517 28537 28541 28547 28549 28559 28571 28573 28579 28591 28597 28603 28607 28619 28621 28627 28631 28643 28649 28657 28661 28663 28669 28687 28697 28703 28711 28723 28729 28751 28753 28759 28771 28789 28793 28807 28813 28817 28837 28843 28859 28867 28871 28879 28901 28909 28921 28927 28933 28949 28961 28979 29009 29017 29021 29023 29027 29033 29059 29063 29077 29101 29123 29129 29131 29137 29147 29153 29167 29173 29179 29191 29201 29207 29209 29221 29231 29243 29251 29269 29287 29297 29303 29311 29327 29333 29339 29347 29363 29383 29387 29389 29399 29401 29411 29423 29429 29437 29443 29453 29473 29483 29501 29527 29531 29537 29567 29569 29573 29581 29587 29599 29611 29629 29633 29641 29663 29669 29671 29683 29717 29723 29741 29753 29759 29761 29789 29803 29819 29833 29837 29851 29863 29867 29873 29879 29881 29917 29921 29927 29947 29959 29983 29989 30011 30013 30029 30047 30059 30071 30089 30091 30097 30103 30109 30113 30119 30133 30137 30139 30161 30169 30181 30187 30197 30203 30211 30223 30241 30253 30259 30269 30271 30293 30307 30313 30319 30323 30341 30347 30367 30389 30391 30403 30427 30431 30449 30467 30469 30491 30493 30497 30509 30517 30529 30539 30553 30557 30559 30577 30593 30631 30637 30643 30649 30661 30671 30677 30689 30697 30703 30707 30713 30727 30757 30763 30773 30781 30803 30809 30817 30829 30839 30841 30851 30853 30859 30869 30871 30881 30893 30911 30931 30937 30941 30949 30971 30977 30983 31013 31019 31033 31039 31051 31063 31069 31079 31081 31091 31121 31123 31139 31147 31151 31153 31159 31177 31181 31183 31189 31193 31219 31223 31231 31237 31247 31249 31253 31259 31267 31271 31277 31307 31319 31321 31327 31333 31337 31357 31379 31387 31391 31393 31397 31469 31477 31481 31489 31511 31513 31517 31531 31541 31543 31547 31567 31573 31583 31601 31607 31627 31643 31649 31657 31663 31667 31687 31699 31721 31723 31727 31729 31741 31751 31769 31771 31793 31799 31817 31847 31849 31859 31873 31883 31891 31907 31957 31963 31973 31981 31991 32003 32009 32027 32029 32051 32057 32059 32063 32069 32077 32083 32089 32099 32117 32119 32141 32143 32159 32173 32183 32189 32191 32203 32213 32233 32237 32251 32257 32261 32297 32299 32303 32309 32321 32323 32327 32341 32353 32359 32363 32369 32371 32377 32381 32401 32411 32413 32423 32429 32441 32443 32467 32479 32491 32497 32503 32507 32531 32533 32537 32561 32563 32569 32573 32579 32587 32603 32609 32611 32621 32633 32647 32653 32687 32693 32707 32713 32717 32719 32749 32771 32779 32783 32789 32797 32801 32803 32831 32833 32839 32843 32869 32887 32909 32911 32917 32933 32939 32941 32957 32969 32971 32983 32987 32993 32999 33013 33023 33029 33037 33049 33053 33071 33073 33083 33091 33107 33113 33119 33149 33151 33161 33179 33181 33191 33199 33203 33211 33223 33247 33287 33289 33301 33311 33317 33329 33331 33343 33347 33349 33353 33359 33377 33391 33403 33409 33413 33427 33457 33461 33469 33479 33487 33493 33503 33521 33529 33533 33547 33563 33569 33577 33581 33587 33589 33599 33601 33613 33617 33619 33623 33629 33637 33641 33647 33679 33703 33713 33721 33739 33749 33751 33757 33767 33769 33773 33791 33797 33809 33811 33827 33829 33851 33857 33863 33871 33889 33893 33911 33923 33931 33937 33941 33961 33967 33997 34019 34031 34033 34039 34057 34061 34123 34127 34129 34141 34147 34157 34159 34171 34183 34211 34213 34217 34231 34253 34259 34261 34267 34273 34283 34297 34301 34303 34313 34319 34327 34337 34351 34361 34367 34369 34381 34403 34421 34429 34439 34457 34469 34471 34483 34487 34499 34501 34511 34513 34519 34537 34543 34549 34583 34589 34591 34603 34607 34613 34631 34649 34651 34667 34673 34679 34687 34693 34703 34721 34729 34739 34747 34757 34759 34763 34781 34807 34819 34841 34843 34847 34849 34871 34877 34883 34897 34913 34919 34939 34949 34961 34963 34981 35023 35027 35051 35053 35059 35069 35081 35083 35089 35099 35107 35111 35117 35129 35141 35149 35153 35159 35171 35201 35221 35227 35251 35257 35267 35279 35281 35291 35311 35317 35323 35327 35339 35353 35363 35381 35393 35401 35407 35419 35423 35437 35447 35449 35461 35491 35507 35509 35521 35527 35531 35533 35537 35543 35569 35573 35591 35593 35597 35603 35617 35671 35677 35729 35731 35747 35753 35759 35771 35797 35801 35803 35809 35831 35837 35839 35851 35863 35869 35879 35897 35899 35911 35923 35933 35951 35963 35969 35977 35983 35993 35999 36007 36011 36013 36017 36037 36061 36067 36073 36083 36097 36107 36109 36131 36137 36151 36161 36187 36191 36209 36217 36229 36241 36251 36263 36269 36277 36293 36299 36307 36313 36319 36341 36343 36353 36373 36383 36389 36433 36451 36457 36467 36469 36473 36479 36493 36497 36523 36527 36529 36541 36551 36559 36563 36571 36583 36587 36599 36607 36629 36637 36643 36653 36671 36677 36683 36691 36697 36709 36713 36721 36739 36749 36761 36767 36779 36781 36787 36791 36793 36809 36821 36833 36847 36857 36871 36877 36887 36899 36901 36913 36919 36923 36929 36931 36943 36947 36973 36979 36997 37003 37013 37019 37021 37039 37049 37057 37061 37087 37097 37117 37123 37139 37159 37171 37181 37189 37199 37201 37217 37223 37243 37253 37273 37277 37307 37309 37313 37321 37337 37339 37357 37361 37363 37369 37379 37397 37409 37423 37441 37447 37463 37483 37489 37493 37501 37507 37511 37517 37529 37537 37547 37549 37561 37567 37571 37573 37579 37589 37591 37607 37619 37633 37643 37649 37657 37663 37691 37693 37699 37717 37747 37781 37783 37799 37811 37813 37831 37847 37853 37861 37871 37879 37889 37897 37907 37951 37957 37963 37967 37987 37991 37993 37997 38011 38039 38047 38053 38069 38083 38113 38119 38149 38153 38167 38177 38183 38189 38197 38201 38219 38231 38237 38239 38261 38273 38281 38287 38299 38303 38317 38321 38327 38329 38333 38351 38371 38377 38393 38431 38447 38449 38453 38459 38461 38501 38543 38557 38561 38567 38569 38593 38603 38609 38611 38629 38639 38651 38653 38669 38671 38677 38693 38699 38707 38711 38713 38723 38729 38737 38747 38749 38767 38783 38791 38803 38821 38833 38839 38851 38861 38867 38873 38891 38903 38917 38921 38923 38933 38953 38959 38971 38977 38993 39019 39023 39041 39043 39047 39079 39089 39097 39103 39107 39113 39119 39133 39139 39157 39161 39163 39181 39191 39199 39209 39217 39227 39229 39233 39239 39241 39251 39293 39301 39313 39317 39323 39341 39343 39359 39367 39371 39373 39383 39397 39409 39419 39439 39443 39451 39461 39499 39503 39509 39511 39521 39541 39551 39563 39569 39581 39607 39619 39623 39631 39659 39667 39671 39679 39703 39709 39719 39727 39733 39749 39761 39769 39779 39791 39799 39821 39827 39829 39839 39841 39847 39857 39863 39869 39877 39883 39887 39901 39929 39937 39953 39971 39979 39983 39989 40009 40013 40031 40037 40039 40063 40087 40093 40099 40111 40123 40127 40129 40151 40153 40163 40169 40177 40189 40193 40213 40231 40237 40241 40253 40277 40283 40289 40343 40351 40357 40361 40387 40423 40427 40429 40433 40459 40471 40483 40487 40493 40499 40507 40519 40529 40531 40543 40559 40577 40583 40591 40597 40609 40627 40637 40639 40693 40697 40699 40709 40739 40751 40759 40763 40771 40787 40801 40813 40819 40823 40829 40841 40847 40849 40853 40867 40879 40883 40897 40903 40927 40933 40939 40949 40961 40973 40993 41011 41017 41023 41039 41047 41051 41057 41077 41081 41113 41117 41131 41141 41143 41149 41161 41177 41179 41183 41189 41201 41203 41213 41221 41227 41231 41233 41243 41257 41263 41269 41281 41299 41333 41341 41351 41357 41381 41387 41389 41399 41411 41413 41443 41453 41467 41479 41491 41507 41513 41519 41521 41539 41543 41549 41579 41593 41597 41603 41609 41611 41617 41621 41627 41641 41647 41651 41659 41669 41681 41687 41719 41729 41737 41759 41761 41771 41777 41801 41809 41813 41843 41849 41851 41863 41879 41887 41893 41897 41903 41911 41927 41941 41947 41953 41957 41959 41969 41981 41983 41999 42013 42017 42019 42023 42043 42061 42071 42073 42083 42089 42101 42131 42139 42157 42169 42179 42181 42187 42193 42197 42209 42221 42223 42227 42239 42257 42281 42283 42293 42299 42307 42323 42331 42337 42349 42359 42373 42379 42391 42397 42403 42407 42409 42433 42437 42443 42451 42457 42461 42463 42467 42473 42487 42491 42499 42509 42533 42557 42569 42571 42577 42589 42611 42641 42643 42649 42667 42677 42683 42689 42697 42701 42703 42709 42719 42727 42737 42743 42751 42767 42773 42787 42793 42797 42821 42829 42839 42841 42853 42859 42863 42899 42901 42923 42929 42937 42943 42953 42961 42967 42979 42989 43003 43013 43019 43037 43049 43051 43063 43067 43093 43103 43117 43133 43151 43159 43177 43189 43201 43207 43223 43237 43261 43271 43283 43291 43313 43319 43321 43331 43391 43397 43399 43403 43411 43427 43441 43451 43457 43481 43487 43499 43517 43541 43543 43573 43577 43579 43591 43597 43607 43609 43613 43627 43633 43649 43651 43661 43669 43691 43711 43717 43721 43753 43759 43777 43781 43783 43787 43789 43793 43801 43853 43867 43889 43891 43913 43933 43943 43951 43961 43963 43969 43973 43987 43991 43997 44017 44021 44027 44029 44041 44053 44059 44071 44087 44089 44101 44111 44119 44123 44129 44131 44159 44171 44179 44189 44201 44203 44207 44221 44249 44257 44263 44267 44269 44273 44279 44281 44293 44351 44357 44371 44381 44383 44389 44417 44449 44453 44483 44491 44497 44501 44507 44519 44531 44533 44537 44543 44549 44563 44579 44587 44617 44621 44623 44633 44641 44647 44651 44657 44683 44687 44699 44701 44711 44729 44741 44753 44771 44773 44777 44789 44797 44809 44819 44839 44843 44851 44867 44879 44887 44893 44909 44917 44927 44939 44953 44959 44963 44971 44983 44987 45007 45013 45053 45061 45077 45083 45119 45121 45127 45131 45137 45139 45161 45179 45181 45191 45197 45233 45247 45259 45263 45281 45289 45293 45307 45317 45319 45329 45337 45341 45343 45361 45377 45389 45403 45413 45427 45433 45439 45481 45491 45497 45503 45523 45533 45541 45553 45557 45569 45587 45589 45599 45613 45631 45641 45659 45667 45673 45677 45691 45697 45707 45737 45751 45757 45763 45767 45779 45817 45821 45823 45827 45833 45841 45853 45863 45869 45887 45893 45943 45949 45953 45959 45971 45979 45989 46021 46027 46049 46051 46061 46073 46091 46093 46099 46103 46133 46141 46147 46153 46171 46181 46183 46187 46199 46219 46229 46237 46261 46271 46273 46279 46301 46307 46309 46327 46337 46349 46351 46381 46399 46411 46439 46441 46447 46451 46457 46471 46477 46489 46499 46507 46511 46523 46549 46559 46567 46573 46589 46591 46601 46619 46633 46639 46643 46649 46663 46679 46681 46687 46691 46703 46723 46727 46747 46751 46757 46769 46771 46807 46811 46817 46819 46829 46831 46853 46861 46867 46877 46889 46901 46919 46933 46957 46993 46997 47017 47041 47051 47057 47059 47087 47093 47111 47119 47123 47129 47137 47143 47147 47149 47161 47189 47207 47221 47237 47251 47269 47279 47287 47293 47297 47303 47309 47317 47339 47351 47353 47363 47381 47387 47389 47407 47417 47419 47431 47441 47459 47491 47497 47501 47507 47513 47521 47527 47533 47543 47563 47569 47581 47591 47599 47609 47623 47629 47639 47653 47657 47659 47681 47699 47701 47711 47713 47717 47737 47741 47743 47777 47779 47791 47797 47807 47809 47819 47837 47843 47857 47869 47881 47903 47911 47917 47933 47939 47947 47951 47963 47969 47977 47981 48017 48023 48029 48049 48073 48079 48091 48109 48119 48121 48131 48157 48163 48179 48187 48193 48197 48221 48239 48247 48259 48271 48281 48299 48311 48313 48337 48341 48353 48371 48383 48397 48407 48409 48413 48437 48449 48463 48473 48479 48481 48487 48491 48497 48523 48527 48533 48539 48541 48563 48571 48589 48593 48611 48619 48623 48647 48649 48661 48673 48677 48679 48731 48733 48751 48757 48761 48767 48779 48781 48787 48799 48809 48817 48821 48823 48847 48857 48859 48869 48871 48883 48889 48907 48947 48953 48973 48989 48991 49003 49009 49019 49031 49033 49037 49043 49057 49069 49081 49103 49109 49117 49121 49123 49139 49157 49169 49171 49177 49193 49199 49201 49207 49211 49223 49253 49261 49277 49279 49297 49307 49331 49333 49339 49363 49367 49369 49391 49393 49409 49411 49417 49429 49433 49451 49459 49463 49477 49481 49499 49523 49529 49531 49537 49547 49549 49559 49597 49603 49613 49627 49633 49639 49663 49667 49669 49681 49697 49711 49727 49739 49741 49747 49757 49783 49787 49789 49801 49807 49811 49823 49831 49843 49853 49871 49877 49891 49919 49921 49927 49937 49939 49943 49957 49991 49993 49999
diff --git a/testsuite/tests/misc/sorts.ml b/testsuite/tests/misc/sorts.ml
new file mode 100644
index 0000000000..db9ecae585
--- /dev/null
+++ b/testsuite/tests/misc/sorts.ml
@@ -0,0 +1,4489 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Test bench for sorting algorithms. *)
+
+
+(*
+ ocamlopt -noassert sorts.ml -cclib -lunix
+*)
+
+open Printf;;
+
+(*
+ Criteres:
+ 0. overhead en pile: doit etre logn au maximum.
+ 1. stable ou non.
+ 2. overhead en espace.
+ 3. vitesse.
+*)
+
+(************************************************************************)
+(* auxiliary functions *)
+
+let rec exp2 n = if n <= 0 then 1 else 2 * exp2 (n-1);;
+let id x = x;;
+let postl x y = Array.of_list y;;
+let posta x y = x;;
+
+let mkconst n = Array.make n 0;;
+let chkconst _ n a = (a = mkconst n);;
+
+let mksorted n =
+ let a = Array.make n 0 in
+ for i = 0 to n - 1 do
+ a.(i) <- i;
+ done;
+ a
+;;
+let chksorted _ n a = (a = mksorted n);;
+
+let mkrev n =
+ let a = Array.make n 0 in
+ for i = 0 to n - 1 do
+ a.(i) <- n - 1 - i;
+ done;
+ a
+;;
+let chkrev _ n a = (a = mksorted n);;
+
+let seed = ref 0;;
+let random_reinit () = Random.init !seed;;
+
+let random_get_state () =
+ let a = Array.make 55 0 in
+ for i = 0 to 54 do a.(i) <- Random.bits (); done;
+ Random.full_init a;
+ a
+;;
+let random_set_state a = Random.full_init a;;
+
+let chkgen mke cmp rstate n a =
+ let marks = Array.make n (-1) in
+ let skipmarks l =
+ if marks.(l) = -1 then l else begin
+ let m = ref marks.(l) in
+ while marks.(!m) <> -1 do incr m; done;
+ marks.(l) <- !m;
+ !m
+ end
+ in
+ let linear e l =
+ let l = skipmarks l in
+ let rec loop l =
+ if cmp a.(l) e > 0 then raise Exit
+ else if e = a.(l) then marks.(l) <- l+1
+ else loop (l+1)
+ in loop l
+ in
+ let rec dicho e l r =
+ if l = r then linear e l
+ else begin
+ assert (l < r);
+ let m = (l + r) / 2 in
+ if cmp a.(m) e >= 0 then dicho e l m else dicho e (m + 1) r
+ end
+ in
+ try
+ for i = 0 to n-2 do if cmp a.(i) a.(i+1) > 0 then raise Exit; done;
+ random_set_state rstate;
+ for i = 0 to n-1 do dicho (mke i) 0 (Array.length a - 1); done;
+ true
+ with Exit | Invalid_argument _ -> false;
+;;
+
+let mkrand_dup n =
+ let a = Array.make n 0 in
+ for i = 0 to (n-1) do a.(i) <- Random.int n; done;
+ a
+;;
+
+let chkrand_dup rstate n a =
+ chkgen (fun i -> Random.int n) compare rstate n a
+;;
+
+let mkrand_nodup n =
+ let a = Array.make n 0 in
+ for i = 0 to (n-1) do a.(i) <- Random.bits (); done;
+ a
+;;
+
+let chkrand_nodup rstate n a =
+ chkgen (fun i -> Random.bits ()) compare rstate n a
+;;
+
+let mkfloats n =
+ let a = Array.make n 0.0 in
+ for i = 0 to (n-1) do a.(i) <- Random.float 1.0; done;
+ a
+;;
+
+let chkfloats rstate n a =
+ chkgen (fun i -> Random.float 1.0) compare rstate n a
+;;
+
+type record = {
+ s1 : string;
+ s2 : string;
+ i1 : int;
+ i2 : int;
+};;
+
+let rand_string () =
+ let len = Random.int 10 in
+ let s = String.create len in
+ for i = 0 to len-1 do
+ s.[i] <- Char.chr (Random.int 256);
+ done;
+ s
+;;
+
+let mkrec1 b i = {
+ s1 = rand_string ();
+ s2 = rand_string ();
+ i1 = Random.int b;
+ i2 = i;
+};;
+
+let mkrecs b n = Array.init n (mkrec1 b);;
+
+let mkrec1_rev b i = {
+ s1 = rand_string ();
+ s2 = rand_string ();
+ i1 = - i;
+ i2 = i;
+};;
+
+let mkrecs_rev n = Array.init n (mkrec1_rev 0);;
+
+let cmpstr r1 r2 =
+ let c1 = compare r1.s1 r2.s1 in
+ if c1 = 0 then compare r1.s2 r2.s2 else c1
+;;
+let lestr r1 r2 =
+ let c1 = compare r1.s1 r2.s1 in
+ if c1 = 0 then r1.s2 <= r2.s2 else (c1 < 0)
+;;
+let chkstr b rstate n a = chkgen (mkrec1 b) cmpstr rstate n a;;
+
+let cmpint r1 r2 = compare r1.i1 r2.i1;;
+let leint r1 r2 = r1.i1 <= r2.i1;;
+let chkint b rstate n a = chkgen (mkrec1 b) cmpint rstate n a;;
+
+let cmplex r1 r2 =
+ let c1 = compare r1.i1 r2.i1 in
+ if c1 = 0 then compare r1.i2 r2.i2 else c1
+;;
+let lelex r1 r2 =
+ let c1 = compare r1.i1 r2.i1 in
+ if c1 = 0 then r1.i2 <= r2.i2 else (c1 < 0)
+;;
+let chklex b rstate n a = chkgen (mkrec1 b) cmplex rstate n a;;
+
+(************************************************************************)
+
+let lens = [
+ 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 28;
+ 100; 127; 128; 129; 191; 192; 193; 506;
+ 1000; 1023; 1024; 1025; 1535; 1536; 1537; 2323;
+ 4000; 4094; 4096; 4098; 5123;
+];;
+
+type ('a, 'b, 'c, 'd) aux = {
+ prepf : ('a -> 'a -> int) -> ('a -> 'a -> bool) -> 'b;
+ prepd : 'a array -> 'c;
+ postd : 'a array -> 'd -> 'a array;
+};;
+
+let ll = { prepf = (fun x y -> y); prepd = Array.to_list; postd = postl };;
+let lc = { prepf = (fun x y -> x); prepd = Array.to_list; postd = postl };;
+let al = { prepf = (fun x y -> y); prepd = id; postd = posta };;
+let ac = { prepf = (fun x y -> x); prepd = id; postd = posta };;
+
+type 'a outcome = Value of 'a | Exception of exn;;
+
+let numfailed = ref 0;;
+
+let test1 name f prepdata postdata cmp desc mk chk =
+ random_reinit ();
+ printf " %s with %s" name desc;
+ let i = ref 0 in
+ List.iter (fun n ->
+ if !i = 0 then printf "\n "; incr i; if !i > 11 then i := 0;
+ printf "%5d" n; flush stdout;
+ let rstate = random_get_state () in
+ let a = mk n in
+ let input = prepdata a in
+ let output = try Value (f cmp input) with e -> Exception e in
+ printf "."; flush stdout;
+ begin match output with
+ | Value v ->
+ if not (chk rstate n (postdata a v))
+ then (incr numfailed; printf "\n*** FAIL\n")
+ | Exception e ->
+ incr numfailed; printf "\n*** %s\n" (Printexc.to_string e)
+ end;
+ flush stdout;
+ ) lens;
+ printf "\n";
+;;
+
+let test name stable f1 f2 aux1 aux2 =
+ printf "Testing %s...\n" name;
+ let t a b c d = test1 name f1 aux1.prepd aux1.postd a b c d in
+ let cmp = aux1.prepf compare (<=) in
+ t cmp "constant ints" mkconst chkconst;
+ t cmp "sorted ints" mksorted chksorted;
+ t cmp "reverse-sorted ints" mkrev chkrev;
+ t cmp "random ints (many dups)" mkrand_dup chkrand_dup;
+ t cmp "random ints (few dups)" mkrand_nodup chkrand_nodup;
+(*
+ let t a b c d = test1 name f3 aux3.prepd aux3.postd a b c d in
+ t cmp "random floats" mkfloats chkfloats;
+*)
+ let t a b c d = test1 name f2 aux2.prepd aux2.postd a b c d in
+ let cmp = aux2.prepf cmpstr lestr in
+ t cmp "records (str)" (mkrecs 1) (chkstr 1);
+ let cmp = aux2.prepf cmpint leint in
+ List.iter (fun m -> t cmp (sprintf "records (int[%d])" m) (mkrecs m)
+ (chkint m)
+ ) [1; 10; 100; 1000];
+ if stable then
+ List.iter (fun m -> t cmp (sprintf "records (int[%d]) [stable]" m)
+ (mkrecs m) (chklex m)
+ ) [1; 10; 100; 1000];
+;;
+
+(************************************************************************)
+
+(* Warning: rpt_timer cannot be used for the array sorts because
+ the sorting functions have effects.
+*)
+
+let rpt_timer1 repeat f x =
+ Gc.compact ();
+ ignore (f x);
+ let st = Sys.time () in
+ for i = 1 to repeat do ignore (f x); done;
+ let en = Sys.time () in
+ en -. st
+;;
+
+let rpt_timer f x =
+ let repeat = ref 1 in
+ let t = ref (rpt_timer1 !repeat f x) in
+ while !t < 0.2 do
+ repeat := 10 * !repeat;
+ t := rpt_timer1 !repeat f x;
+ done;
+ if !t < 2.0 then begin
+ repeat := (int_of_float (10. *. (float !repeat) /. !t) + 1);
+ t := rpt_timer1 !repeat f x;
+ end;
+ !t /. (float !repeat)
+;;
+
+let timer f x =
+ let st = Sys.time () in
+ ignore (f x);
+ let en = Sys.time () in
+ (en -. st)
+;;
+
+let table1 limit f mkarg =
+ printf " %10s %9s %9s %9s %9s %9s\n" "n" "t1" "t2" "t3" "t4" "t5";
+ let sz = ref 49151 in
+ while !sz < int_of_float (2. ** float limit) do
+ begin try
+ printf " %10d " !sz; flush stdout;
+ for i = 0 to 4 do
+ let arg = mkarg !sz in
+ let t = timer f arg in
+ printf " %.2e " t; flush stdout;
+ done;
+ printf "\n";
+ with e -> printf "*** %s\n" (Printexc.to_string e);
+ end;
+ flush stdout;
+ sz := 2 * !sz + 1;
+ done;
+;;
+
+let table2 limit f mkarg =
+ printf " %10s %9s %9s %9s %9s %9s\n"
+ " n" "t" "t/n" "t/nlogn" "t/nlog^2n" "t/n^2";
+ let sz = ref 49151 in
+ while float !sz < 2. ** float limit do
+ begin try
+ printf " %10d " !sz; flush stdout;
+ Gc.compact ();
+ let arg = mkarg !sz in
+ let t = timer f arg in
+ let n = float !sz in
+ let logn = log (float !sz) /. log 2. in
+ printf "%.2e %.2e %.2e %.2e %.2e\n"
+ t (t/.n) (t/.n/.logn) (t/.n/.logn/.logn) (t/.n/.n);
+ with e -> printf "*** %s\n" (Printexc.to_string e);
+ end;
+ flush stdout;
+ sz := 2 * !sz + 1;
+ done;
+;;
+
+let table3 limit f mkarg =
+ printf " %10s %9s %9s %9s %9s %9s\n" "n" "t1" "t2" "t3" "t4" "t5";
+ let sz = ref 2 in
+ while float !sz < 2. ** float limit do
+ begin try
+ printf " %10d " !sz; flush stdout;
+ for i = 0 to 4 do
+ let arg = mkarg !sz in
+ let t = rpt_timer f arg in
+ printf " %.2e " t; flush stdout;
+ done;
+ printf "\n";
+ with e -> printf "*** %s\n" (Printexc.to_string e);
+ end;
+ flush stdout;
+ sz := 2 * !sz + 1;
+ done;
+;;
+
+(************************************************************************)
+
+(* benchmarks:
+ 1a. random records, sorted with two keys
+ 1b. random integers
+ 1c. random floats
+
+ 2a. integers, constant
+ 2b. integers, already sorted
+ 2c. integers, reverse sorted
+
+ only for short lists:
+ 3a. random records, sorted with two keys
+ 3b. random integers
+ 3c. random floats
+*)
+let bench1a limit name f aux =
+
+ (* Don't do benchmarks with assertions enabled. *)
+ assert (not true);
+
+ random_reinit ();
+
+ printf "\n%s with random records [10]:\n" name;
+ let cmp = aux.prepf cmplex lelex in
+ table1 limit (f cmp) (fun n -> aux.prepd (mkrecs 10 n));
+;;
+
+let bench1b limit name f aux =
+
+ (* Don't do benchmarks with assertions enabled. *)
+ assert (not true);
+
+ random_reinit ();
+
+ printf "\n%s with random integers:\n" name;
+ let cmp = aux.prepf (-) (<=) in
+ table1 limit (f cmp) (fun n -> aux.prepd (mkrand_nodup n));
+;;
+
+let bench1c limit name f aux =
+
+ (* Don't do benchmarks with assertions enabled. *)
+ assert (not true);
+
+ random_reinit ();
+
+ printf "\n%s with random floats:\n" name;
+ let cmp = aux.prepf compare (<=) in
+ table1 limit (f cmp) (fun n -> aux.prepd (mkfloats n));
+;;
+
+let bench2 limit name f aux =
+
+ (* Don't do benchmarks with assertions enabled. *)
+ assert (not true);
+
+ printf "\n%s with constant integers:\n" name;
+ let cmp = aux.prepf compare (<=) in
+ table2 limit (f cmp) (fun n -> aux.prepd (mkconst n));
+
+ printf "\n%s with sorted integers:\n" name;
+ let cmp = aux.prepf compare (<=) in
+ table2 limit (f cmp) (fun n -> aux.prepd (mksorted n));
+
+ printf "\n%s with reverse-sorted integers:\n" name;
+ let cmp = aux.prepf compare (<=) in
+ table2 limit (f cmp) (fun n -> aux.prepd (mkrev n));
+;;
+
+let bench3a limit name f aux =
+
+ (* Don't do benchmarks with assertions enabled. *)
+ assert (not true);
+
+ random_reinit ();
+
+ printf "\n%s with random records [10]:\n" name;
+ let cmp = aux.prepf cmplex lelex in
+ table3 limit (f cmp) (fun n -> aux.prepd (mkrecs 10 n));
+;;
+
+let bench3b limit name f aux =
+
+ (* Don't do benchmarks with assertions enabled. *)
+ assert (not true);
+
+ random_reinit ();
+
+ printf "\n%s with random integers:\n" name;
+ let cmp = aux.prepf (-) (<=) in
+ table3 limit (f cmp) (fun n -> aux.prepd (mkrand_nodup n));
+;;
+
+let bench3c limit name f aux =
+
+ (* Don't do benchmarks with assertions enabled. *)
+ assert (not true);
+
+ random_reinit ();
+
+ printf "\n%s with random floats:\n" name;
+ let cmp = aux.prepf compare (<=) in
+ table3 limit (f cmp) (fun n -> aux.prepd (mkfloats n));
+;;
+
+(************************************************************************)
+(* merge sort on lists *)
+
+(* FIXME to do: cutoff
+ to do: cascader les pattern-matchings (enlever les paires)
+ to do: fermeture intermediaire pour merge
+*)
+let (@@) = List.rev_append;;
+
+let lmerge_1a cmp l =
+ let rec init accu = function
+ | [] -> accu
+ | e::rest -> init ([e] :: accu) rest
+ in
+ let rec merge rest accu2 accu l1 l2 = (* l1,l2,rest are forward;
+ accu,accu2 are rev *)
+ match l1, l2 with
+ | [] , _ -> mergepairs ((l2 @@ accu)::accu2) rest
+ | _ , [] -> mergepairs ((l1 @@ accu)::accu2) rest
+ | h1::t1, h2::t2 -> if cmp h1 h2 <= 0
+ then merge rest accu2 (h1::accu) t1 l2
+ else merge rest accu2 (h2::accu) l1 t2
+ and merge_rev rest accu2 accu l1 l2 = (* accu, accu2 are forward;
+ l1,l2,rest are rev *)
+ match l1, l2 with
+ | [] , _ -> mergepairs_rev ((l2 @@ accu)::accu2) rest
+ | _ , [] -> mergepairs_rev ((l1 @@ accu)::accu2) rest
+ | h1::t1, h2::t2 -> if cmp h2 h1 <= 0
+ then merge_rev rest accu2 (h1::accu) t1 l2
+ else merge_rev rest accu2 (h2::accu) l1 t2
+ and mergepairs accu = function (* accu is rev, arg is forward *)
+ | [] -> mergeall_rev accu
+ | [l] -> mergeall_rev ((List.rev l)::accu)
+ | l1::l2::rest -> merge rest accu [] l1 l2
+ and mergepairs_rev accu = function (* accu is forward, arg is rev *)
+ | [] -> mergeall accu
+ | [l] -> mergeall ((List.rev l)::accu)
+ | l1::l2::rest -> merge_rev rest accu [] l1 l2
+ and mergeall = function (* arg is forward *)
+ | [] -> []
+ | [l] -> l
+ | llist -> mergepairs [] llist
+ and mergeall_rev = function (* arg is rev *)
+ | [] -> []
+ | [l] -> List.rev l
+ | llist -> mergepairs_rev [] llist
+ in
+ mergeall_rev (init [] l)
+;;
+
+let lmerge_1b cmp l =
+ let rec init accu = function
+ | [] -> accu
+ | [e] -> [e] :: accu
+ | e1::e2::rest ->
+ init ((if cmp e1 e2 <= 0 then [e2;e1] else [e1;e2])::accu) rest
+ in
+ let rec merge rest accu2 accu l1 l2 = (* l1,l2,rest are forward;
+ accu,accu2 are rev *)
+ match l1, l2 with
+ | [] , _ -> mergepairs ((l2 @@ accu)::accu2) rest
+ | _ , [] -> mergepairs ((l1 @@ accu)::accu2) rest
+ | h1::t1, h2::t2 -> if cmp h1 h2 <= 0
+ then merge rest accu2 (h1::accu) t1 l2
+ else merge rest accu2 (h2::accu) l1 t2
+ and merge_rev rest accu2 accu l1 l2 = (* accu, accu2 are forward;
+ l1,l2,rest are rev *)
+ match l1, l2 with
+ | [] , _ -> mergepairs_rev ((l2 @@ accu)::accu2) rest
+ | _ , [] -> mergepairs_rev ((l1 @@ accu)::accu2) rest
+ | h1::t1, h2::t2 -> if cmp h2 h1 <= 0
+ then merge_rev rest accu2 (h1::accu) t1 l2
+ else merge_rev rest accu2 (h2::accu) l1 t2
+ and mergepairs accu = function (* accu is rev, arg is forward *)
+ | [] -> mergeall_rev accu
+ | [l] -> mergeall_rev ((List.rev l)::accu)
+ | l1::l2::rest -> merge rest accu [] l1 l2
+ and mergepairs_rev accu = function (* accu is forward, arg is rev *)
+ | [] -> mergeall accu
+ | [l] -> mergeall ((List.rev l)::accu)
+ | l1::l2::rest -> merge_rev rest accu [] l1 l2
+ and mergeall = function (* arg is forward *)
+ | [] -> []
+ | [l] -> l
+ | llist -> mergepairs [] llist
+ and mergeall_rev = function (* arg is rev *)
+ | [] -> []
+ | [l] -> List.rev l
+ | llist -> mergepairs_rev [] llist
+ in
+ mergeall_rev (init [] l)
+;;
+
+let lmerge_1c cmp l =
+ let rec init accu = function
+ | [] -> accu
+ | [e] -> [e] :: accu
+ | e1::e2::rest ->
+ init ((if cmp e1 e2 <= 0 then [e2;e1] else [e1;e2])::accu) rest
+ in
+ let rec merge rest accu2 accu l1 l2 = (* l1,l2,rest are forward;
+ accu,accu2 are rev *)
+ match l1 with
+ | [] -> mergepairs ((l2 @@ accu)::accu2) rest
+ | h1::t1 ->
+ match l2 with
+ | [] -> mergepairs ((l1 @@ accu)::accu2) rest
+ | h2::t2 -> if cmp h1 h2 <= 0
+ then merge rest accu2 (h1::accu) t1 l2
+ else merge rest accu2 (h2::accu) l1 t2
+ and merge_rev rest accu2 accu l1 l2 = (* accu, accu2 are forward;
+ l1,l2,rest are rev *)
+ match l1 with
+ | [] -> mergepairs_rev ((l2 @@ accu)::accu2) rest
+ | h1::t1 ->
+ match l2 with
+ | [] -> mergepairs_rev ((l1 @@ accu)::accu2) rest
+ | h2::t2 -> if cmp h2 h1 <= 0
+ then merge_rev rest accu2 (h1::accu) t1 l2
+ else merge_rev rest accu2 (h2::accu) l1 t2
+ and mergepairs accu = function (* accu is rev, arg is forward *)
+ | [] -> mergeall_rev accu
+ | [l] -> mergeall_rev ((List.rev l)::accu)
+ | l1::l2::rest -> merge rest accu [] l1 l2
+ and mergepairs_rev accu = function (* accu is forward, arg is rev *)
+ | [] -> mergeall accu
+ | [l] -> mergeall ((List.rev l)::accu)
+ | l1::l2::rest -> merge_rev rest accu [] l1 l2
+ and mergeall = function (* arg is forward *)
+ | [] -> []
+ | [l] -> l
+ | llist -> mergepairs [] llist
+ and mergeall_rev = function (* arg is rev *)
+ | [] -> []
+ | [l] -> List.rev l
+ | llist -> mergepairs_rev [] llist
+ in
+ mergeall_rev (init [] l)
+;;
+
+let lmerge_1d cmp l =
+ let rec init accu = function
+ | [] -> accu
+ | [e] -> [e] :: accu
+ | e1::e2::rest ->
+ init ((if cmp e1 e2 <= 0 then [e2;e1] else [e1;e2])::accu) rest
+ in
+ let rec merge rest accu2 accu l1 l2 = (* l1,l2,rest are forward;
+ accu,accu2 are rev *)
+ let merge_rest_accu2 accu l1 l2 =
+ match l1 with
+ | [] -> mergepairs ((l2 @@ accu)::accu2) rest
+ | h1::t1 ->
+ match l2 with
+ | [] -> mergepairs ((l1 @@ accu)::accu2) rest
+ | h2::t2 -> if cmp h1 h2 <= 0
+ then merge rest accu2 (h1::accu) t1 l2
+ else merge rest accu2 (h2::accu) l1 t2
+ in merge_rest_accu2 accu l1 l2
+ and merge_rev rest accu2 accu l1 l2 = (* accu, accu2 are forward;
+ l1,l2,rest are rev *)
+ let merge_rev_rest_accu2 accu l1 l2 =
+ match l1 with
+ | [] -> mergepairs_rev ((l2 @@ accu)::accu2) rest
+ | h1::t1 ->
+ match l2 with
+ | [] -> mergepairs_rev ((l1 @@ accu)::accu2) rest
+ | h2::t2 -> if cmp h2 h1 <= 0
+ then merge_rev rest accu2 (h1::accu) t1 l2
+ else merge_rev rest accu2 (h2::accu) l1 t2
+ in merge_rev_rest_accu2 accu l1 l2
+ and mergepairs accu = function (* accu is rev, arg is forward *)
+ | [] -> mergeall_rev accu
+ | [l] -> mergeall_rev ((List.rev l)::accu)
+ | l1::l2::rest -> merge rest accu [] l1 l2
+ and mergepairs_rev accu = function (* accu is forward, arg is rev *)
+ | [] -> mergeall accu
+ | [l] -> mergeall ((List.rev l)::accu)
+ | l1::l2::rest -> merge_rev rest accu [] l1 l2
+ and mergeall = function (* arg is forward *)
+ | [] -> []
+ | [l] -> l
+ | llist -> mergepairs [] llist
+ and mergeall_rev = function (* arg is rev *)
+ | [] -> []
+ | [l] -> List.rev l
+ | llist -> mergepairs_rev [] llist
+ in
+ mergeall_rev (init [] l)
+;;
+
+(************************************************************************)
+(* merge sort on lists, user-contributed (NOT STABLE) *)
+
+(* BEGIN code contributed by Yann Coscoy *)
+
+ let rec rev_merge_append order l1 l2 acc =
+ match l1 with
+ [] -> List.rev_append l2 acc
+ | h1 :: t1 ->
+ match l2 with
+ [] -> List.rev_append l1 acc
+ | h2 :: t2 ->
+ if order h1 h2
+ then rev_merge_append order t1 l2 (h1::acc)
+ else rev_merge_append order l1 t2 (h2::acc)
+
+ let rev_merge order l1 l2 = rev_merge_append order l1 l2 []
+
+ let rec rev_merge_append' order l1 l2 acc =
+ match l1 with
+ | [] -> List.rev_append l2 acc
+ | h1 :: t1 ->
+ match l2 with
+ | [] -> List.rev_append l1 acc
+ | h2 :: t2 ->
+ if order h2 h1
+ then rev_merge_append' order t1 l2 (h1::acc)
+ else rev_merge_append' order l1 t2 (h2::acc)
+
+ let rev_merge' order l1 l2 = rev_merge_append' order l1 l2 []
+
+ let lmerge_3 order l =
+ let rec initlist l acc = match l with
+ | e1::e2::rest ->
+ initlist rest
+ ((if order e1 e2 then [e1;e2] else [e2;e1])::acc)
+ | [e] -> [e]::acc
+ | [] -> acc
+ in
+ let rec merge2 ll acc = match ll with
+ | [] -> acc
+ | [l] -> [List.rev l]@acc
+ | l1::l2::rest ->
+ merge2 rest (rev_merge order l1 l2::acc)
+ in
+ let rec merge2' ll acc = match ll with
+ | [] -> acc
+ | [l] -> [List.rev l]@acc
+ | l1::l2::rest ->
+ merge2' rest (rev_merge' order l1 l2::acc)
+ in
+ let rec mergeall rev = function
+ | [] -> []
+ | [l] -> if rev then List.rev l else l
+ | llist ->
+ mergeall
+ (not rev) ((if rev then merge2' else merge2) llist [])
+ in
+ mergeall false (initlist l [])
+
+(* END code contributed by Yann Coscoy *)
+
+(************************************************************************)
+(* merge sort on short lists, Francois Pottier *)
+
+(* BEGIN code contributed by Francois Pottier *)
+
+ (* [chop k l] returns the list [l] deprived of its [k] first
+ elements. The length of the list [l] must be [k] at least. *)
+
+ let rec chop k l =
+ match k, l with
+ | 0, _ -> l
+ | _, x :: l -> chop (k-1) l
+ | _, _ -> assert false
+ ;;
+
+ let rec merge order l1 l2 =
+ match l1 with
+ [] -> l2
+ | h1 :: t1 ->
+ match l2 with
+ [] -> l1
+ | h2 :: t2 ->
+ if order h1 h2
+ then h1 :: merge order t1 l2
+ else h2 :: merge order l1 t2
+ ;;
+
+ let rec lmerge_4a order l =
+ match l with
+ | []
+ | [ _ ] -> l
+ | _ ->
+ let rec sort k l = (* k > 1 *)
+ match k, l with
+ | 2, x1 :: x2 :: _ ->
+ if order x1 x2 then [ x1; x2 ] else [ x2; x1 ]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if order x1 x2 then
+ if order x2 x3 then
+ [ x1 ; x2 ; x3 ]
+ else
+ if order x1 x3 then [ x1 ; x3 ; x2 ] else [ x3; x1; x2 ]
+ else
+ if order x1 x3 then
+ [ x2; x1; x3 ]
+ else
+ if order x2 x3 then [ x2; x3; x1 ] else [ x3; x2; x1 ]
+ | _, _ ->
+ let k1 = k / 2 in
+ let k2 = k - k1 in
+ merge order (sort k1 l) (sort k2 (chop k1 l))
+ in
+ sort (List.length l) l
+ ;;
+(* END code contributed by Francois Pottier *)
+
+(************************************************************************)
+(* merge sort on short lists, Francois Pottier,
+ adapted to new-style interface *)
+
+(* BEGIN code contributed by Francois Pottier *)
+
+ (* [chop k l] returns the list [l] deprived of its [k] first
+ elements. The length of the list [l] must be [k] at least. *)
+
+ let rec chop k l =
+ match k, l with
+ | 0, _ -> l
+ | _, x :: l -> chop (k-1) l
+ | _, _ -> assert false
+ ;;
+
+ let rec merge order l1 l2 =
+ match l1 with
+ [] -> l2
+ | h1 :: t1 ->
+ match l2 with
+ [] -> l1
+ | h2 :: t2 ->
+ if order h1 h2 <= 0
+ then h1 :: merge order t1 l2
+ else h2 :: merge order l1 t2
+ ;;
+
+ let rec lmerge_4b order l =
+ match l with
+ | []
+ | [ _ ] -> l
+ | _ ->
+ let rec sort k l = (* k > 1 *)
+ match k, l with
+ | 2, x1 :: x2 :: _ ->
+ if order x1 x2 <= 0 then [ x1; x2 ] else [ x2; x1 ]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if order x1 x2 <= 0 then
+ if order x2 x3 <= 0 then
+ [ x1 ; x2 ; x3 ]
+ else
+ if order x1 x3 <= 0 then [ x1 ; x3 ; x2 ] else [ x3; x1; x2 ]
+ else
+ if order x1 x3 <= 0 then
+ [ x2; x1; x3 ]
+ else
+ if order x2 x3 <= 0 then [ x2; x3; x1 ] else [ x3; x2; x1 ]
+ | _, _ ->
+ let k1 = k / 2 in
+ let k2 = k - k1 in
+ merge order (sort k1 l) (sort k2 (chop k1 l))
+ in
+ sort (List.length l) l
+ ;;
+(* END code contributed by Francois Pottier *)
+
+(************************************************************************)
+(* merge sort on short lists a la Pottier, modified merge *)
+
+let rec chop k l =
+ if k = 0 then l else begin
+ match l with
+ | x::t -> chop (k-1) t
+ | _ -> assert false
+ end
+;;
+
+let lmerge_4c cmp l =
+ let rec merge1 h1 t1 l2 =
+ match l2 with
+ | [] -> h1 :: t1
+ | h2 :: t2 ->
+ if cmp h1 h2 <= 0
+ then h1 :: (merge2 t1 h2 t2)
+ else h2 :: (merge1 h1 t1 t2)
+ and merge2 l1 h2 t2 =
+ match l1 with
+ | [] -> h2 :: t2
+ | h1 :: t1 ->
+ if cmp h1 h2 <= 0
+ then h1 :: (merge2 t1 h2 t2)
+ else h2 :: (merge1 h1 t1 t2)
+ in
+ let merge l1 = function
+ | [] -> l1
+ | h2 :: t2 -> merge2 l1 h2 t2
+ in
+ let rec sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ if cmp x1 x2 <= 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if cmp x1 x2 <= 0 then begin
+ if cmp x2 x3 <= 0 then [x1; x2; x3]
+ else if cmp x1 x3 <= 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ if cmp x1 x3 <= 0 then [x2; x1; x3]
+ else if cmp x2 x3 <= 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ merge (sort n1 l) (sort n2 (chop n1 l))
+ in
+ let len = List.length l in
+ if len < 2 then l else sort len l
+;;
+
+(************************************************************************)
+(* merge sort on short lists a la Pottier, logarithmic stack space *)
+
+let rec chop k l =
+ if k = 0 then l else begin
+ match l with
+ | x::t -> chop (k-1) t
+ | _ -> assert false
+ end
+;;
+
+let lmerge_4d cmp l =
+ let rec rev_merge l1 l2 accu =
+ match l1, l2 with
+ | [], l2 -> l2 @@ accu
+ | l1, [] -> l1 @@ accu
+ | h1::t1, h2::t2 ->
+ if cmp h1 h2 <= 0
+ then rev_merge t1 l2 (h1::accu)
+ else rev_merge l1 t2 (h2::accu)
+ in
+ let rec rev_merge_rev l1 l2 accu =
+ match l1, l2 with
+ | [], l2 -> l2 @@ accu
+ | l1, [] -> l1 @@ accu
+ | h1::t1, h2::t2 ->
+ if cmp h1 h2 > 0
+ then rev_merge_rev t1 l2 (h1::accu)
+ else rev_merge_rev l1 t2 (h2::accu)
+ in
+ let rec sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ if cmp x1 x2 <= 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if cmp x1 x2 <= 0 then begin
+ if cmp x2 x3 <= 0 then [x1; x2; x3]
+ else if cmp x1 x3 <= 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ if cmp x1 x3 <= 0 then [x2; x1; x3]
+ else if cmp x2 x3 <= 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ rev_merge_rev (rev_sort n1 l) (rev_sort n2 (chop n1 l)) []
+ and rev_sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ if cmp x1 x2 > 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if cmp x1 x2 > 0 then begin
+ if cmp x2 x3 > 0 then [x1; x2; x3]
+ else if cmp x1 x3 > 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ if cmp x1 x3 > 0 then [x2; x1; x3]
+ else if cmp x2 x3 > 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ rev_merge (sort n1 l) (sort n2 (chop n1 l)) []
+ in
+ let len = List.length l in
+ if len < 2 then l else sort len l
+;;
+
+
+(************************************************************************)
+(* merge sort on short lists a la Pottier, logarithmic stack space,
+ in place: input list is freed as the output is being computed. *)
+
+let rec chop k l =
+ if k = 0 then l else begin
+ match l with
+ | x::t -> chop (k-1) t
+ | _ -> assert false
+ end
+;;
+
+let lmerge_4e cmp l =
+ let rec rev_merge l1 l2 accu =
+ match l1, l2 with
+ | [], l2 -> l2 @@ accu
+ | l1, [] -> l1 @@ accu
+ | h1::t1, h2::t2 ->
+ if cmp h1 h2 <= 0
+ then rev_merge t1 l2 (h1::accu)
+ else rev_merge l1 t2 (h2::accu)
+ in
+ let rec rev_merge_rev l1 l2 accu =
+ match l1, l2 with
+ | [], l2 -> l2 @@ accu
+ | l1, [] -> l1 @@ accu
+ | h1::t1, h2::t2 ->
+ if cmp h1 h2 > 0
+ then rev_merge_rev t1 l2 (h1::accu)
+ else rev_merge_rev l1 t2 (h2::accu)
+ in
+ let rec sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ if cmp x1 x2 <= 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if cmp x1 x2 <= 0 then begin
+ if cmp x2 x3 <= 0 then [x1; x2; x3]
+ else if cmp x1 x3 <= 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ if cmp x1 x3 <= 0 then [x2; x1; x3]
+ else if cmp x2 x3 <= 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ let l2 = chop n1 l in
+ let s1 = rev_sort n1 l in
+ let s2 = rev_sort n2 l2 in
+ rev_merge_rev s1 s2 []
+ and rev_sort n l =
+ match n, l with
+ | 2, x1 :: x2 :: _ ->
+ if cmp x1 x2 > 0 then [x1; x2] else [x2; x1]
+ | 3, x1 :: x2 :: x3 :: _ ->
+ if cmp x1 x2 > 0 then begin
+ if cmp x2 x3 > 0 then [x1; x2; x3]
+ else if cmp x1 x3 > 0 then [x1; x3; x2]
+ else [x3; x1; x2]
+ end else begin
+ if cmp x1 x3 > 0 then [x2; x1; x3]
+ else if cmp x2 x3 > 0 then [x2; x3; x1]
+ else [x3; x2; x1]
+ end
+ | n, l ->
+ let n1 = n asr 1 in
+ let n2 = n - n1 in
+ let l2 = chop n1 l in
+ let s1 = sort n1 l in
+ let s2 = sort n2 l2 in
+ rev_merge s1 s2 []
+ in
+ let len = List.length l in
+ if len < 2 then l else sort len l
+;;
+
+(************************************************************************)
+(* chop-free version of Pottier's code, binary version *)
+
+let rec merge cmp l1 l2 =
+ match l1, l2 with
+ | [], l2 -> l2
+ | l1, [] -> l1
+ | h1 :: t1, h2 :: t2 ->
+ if cmp h1 h2 <= 0
+ then h1 :: merge cmp t1 l2
+ else h2 :: merge cmp l1 t2
+;;
+
+let lmerge_5a cmp l =
+ let rem = ref l in
+ let rec sort_prefix n =
+ if n <= 1 then begin
+ match !rem with
+ | [] -> []
+ | [x] as l -> rem := []; l
+ | x::y::t -> rem := t; if cmp x y <= 0 then [x;y] else [y;x]
+ end else if !rem = [] then []
+ else begin
+ let l1 = sort_prefix (n-1) in
+ let l2 = sort_prefix (n-1) in
+ merge cmp l1 l2
+ end
+ in
+ let len = ref (List.length l) in
+ let i = ref 0 in
+ while !len > 0 do incr i; len := !len lsr 1; done;
+ sort_prefix !i
+;;
+
+(************************************************************************)
+(* chop-free version of Pottier's code, dichotomic version,
+ ground cases 1 & 2 *)
+
+let rec merge cmp l1 l2 =
+ match l1, l2 with
+ | [], l2 -> l2
+ | l1, [] -> l1
+ | h1 :: t1, h2 :: t2 ->
+ if cmp h1 h2 <= 0
+ then h1 :: merge cmp t1 l2
+ else h2 :: merge cmp l1 t2
+;;
+
+let lmerge_5b cmp l =
+ let rem = ref l in
+ let rec sort_prefix n =
+ match n, !rem with
+ | 1, x::t -> rem := t; [x]
+ | 2, x::y::t -> rem := t; if cmp x y <= 0 then [x;y] else [y;x]
+ | n, _ ->
+ let n1 = n/2 in
+ let n2 = n - n1 in
+ let l1 = sort_prefix n1 in
+ let l2 = sort_prefix n2 in
+ merge cmp l1 l2
+ in
+ let len = List.length l in
+ if len <= 1 then l else sort_prefix len
+;;
+
+(************************************************************************)
+(* chop-free version of Pottier's code, dichotomic version,
+ ground cases 2 & 3 *)
+
+let rec merge cmp l1 l2 =
+ match l1, l2 with
+ | [], l2 -> l2
+ | l1, [] -> l1
+ | h1 :: t1, h2 :: t2 ->
+ if cmp h1 h2 <= 0
+ then h1 :: merge cmp t1 l2
+ else h2 :: merge cmp l1 t2
+;;
+
+let lmerge_5c cmp l =
+ let rem = ref l in
+ let rec sort_prefix n =
+ match n, !rem with
+ | 2, x::y::t -> rem := t; if cmp x y <= 0 then [x;y] else [y;x]
+ | 3, x::y::z::t ->
+ rem := t;
+ if cmp x y <= 0 then
+ if cmp y z <= 0 then [x; y; z]
+ else if cmp x z <= 0 then [x; z; y]
+ else [z; x; y]
+ else
+ if cmp x z <= 0 then [y; x; z]
+ else if cmp y z <= 0 then [y; z; x]
+ else [z; y; x]
+ | n, _ ->
+ let n1 = n/2 in
+ let n2 = n - n1 in
+ let l1 = sort_prefix n1 in
+ let l2 = sort_prefix n2 in
+ merge cmp l1 l2
+ in
+ let len = List.length l in
+ if len <= 1 then l else sort_prefix len
+;;
+
+(************************************************************************)
+(* chop-free, ref-free version of Pottier's code, dichotomic version,
+ ground cases 2 & 3, modified merge *)
+
+let lmerge_5d cmp l =
+ let rec merge1 h1 t1 l2 =
+ match l2 with
+ | [] -> h1::t1
+ | h2 :: t2 ->
+ if cmp h1 h2 <= 0
+ then h1 :: merge2 t1 h2 t2
+ else h2 :: merge1 h1 t1 t2
+ and merge2 l1 h2 t2 =
+ match l1 with
+ | [] -> h2::t2
+ | h1 :: t1 ->
+ if cmp h1 h2 <= 0
+ then h1 :: merge2 t1 h2 t2
+ else h2 :: merge1 h1 t1 t2
+ in
+ let rec sort_prefix n l =
+ match n, l with
+ | 2, x::y::t -> ((if cmp x y <= 0 then [x;y] else [y;x]), t)
+ | 3, x::y::z::t ->
+ ((if cmp x y <= 0 then
+ if cmp y z <= 0 then [x; y; z]
+ else if cmp x z <= 0 then [x; z; y]
+ else [z; x; y]
+ else
+ if cmp x z <= 0 then [y; x; z]
+ else if cmp y z <= 0 then [y; z; x]
+ else [z; y; x]),
+ t)
+ | n, _ ->
+ let n1 = n/2 in
+ let n2 = n - n1 in
+ let (l1, rest1) = sort_prefix n1 l in
+ match sort_prefix n2 rest1 with
+ | (h2::t2, rest2) -> ((merge2 l1 h2 t2), rest2)
+ | _ -> assert false
+ in
+ let len = List.length l in
+ if len <= 1 then l else fst (sort_prefix len l)
+;;
+
+(************************************************************************)
+(* merge sort on arrays, merge with tail-rec function *)
+
+let amerge_1a cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let rec sortto srcofs dst dstofs len =
+ assert (len > 0);
+ if len = 1 then dst.(dstofs) <- a.(srcofs)
+ else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= 1 then ()
+ else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let amerge_1b cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let rec sortto srcofs dst dstofs len =
+ assert (len > 0);
+ if len = 1 then dst.(dstofs) <- a.(srcofs)
+ else if len = 2 then begin
+ if cmp a.(srcofs) a.(srcofs+1) <= 0 then begin
+ dst.(dstofs) <- a.(srcofs);
+ dst.(dstofs+1) <- a.(srcofs+1);
+ end else begin
+ dst.(dstofs) <- a.(srcofs+1);
+ dst.(dstofs+1) <- a.(srcofs);
+ end;
+ end else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= 1 then ()
+ else if l = 2 then begin
+ if cmp a.(0) a.(1) > 0 then begin
+ let e = a.(0) in
+ a.(0) <- a.(1);
+ a.(1) <- e;
+ end;
+ end else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 3;;
+let amerge_1c cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = a.(srcofs + i) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 4;;
+let amerge_1d cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = a.(srcofs + i) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 5;;
+let amerge_1e cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = a.(srcofs + i) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 6;;
+let amerge_1f cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = a.(srcofs + i) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 7;;
+let amerge_1g cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = a.(srcofs + i) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 8;;
+let amerge_1h cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = a.(srcofs + i) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 9;;
+let amerge_1i cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = a.(srcofs + i) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 10;;
+let amerge_1j cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let src1r = src1ofs + src1len and src2r = src2ofs + src2len in
+ let rec loop i1 s1 i2 s2 d =
+ if cmp s1 s2 <= 0 then begin
+ dst.(d) <- s1;
+ let i1 = i1 + 1 in
+ if i1 < src1r then
+ loop i1 a.(i1) i2 s2 (d + 1)
+ else
+ Array.blit src2 i2 dst (d + 1) (src2r - i2)
+ end else begin
+ dst.(d) <- s2;
+ let i2 = i2 + 1 in
+ if i2 < src2r then
+ loop i1 s1 i2 src2.(i2) (d + 1)
+ else
+ Array.blit a i1 dst (d + 1) (src1r - i1)
+ end
+ in loop src1ofs a.(src1ofs) src2ofs src2.(src2ofs) dstofs;
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len - 1 do
+ let e = a.(srcofs + i) in
+ let j = ref (dstofs + i - 1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs + l1) dst (dstofs + l1) l2;
+ sortto srcofs a (srcofs + l2) l1;
+ merge (srcofs + l2) l1 dst (dstofs + l1) l2 dst dstofs;
+ end;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+(* FIXME a essayer: *)
+(* list->array->list direct et array->list->array direct *)
+(* overhead = 1/3, 1/4, etc. *)
+(* overhead = sqrt (n) *)
+(* overhead = n/3 jusqu'a 30k, 30k jusqu'a 900M, sqrt (n) au-dela *)
+
+(************************************************************************)
+(* merge sort on arrays, merge with loop *)
+
+(* cutoff = 1 *)
+let amerge_3a cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let rec sortto srcofs dst dstofs len =
+ assert (len > 0);
+ if len = 1 then dst.(dstofs) <- a.(srcofs) else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= 1 then () else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let amerge_3b cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let rec sortto srcofs dst dstofs len =
+ assert (len > 0);
+ if len = 1 then dst.(dstofs) <- a.(srcofs)
+ else if len = 2 then begin
+ if cmp a.(srcofs) a.(srcofs+1) <= 0 then begin
+ dst.(dstofs) <- a.(srcofs);
+ dst.(dstofs+1) <- a.(srcofs+1);
+ end else begin
+ dst.(dstofs) <- a.(srcofs+1);
+ dst.(dstofs+1) <- a.(srcofs);
+ end
+ end else begin
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ end
+ in
+ let l = Array.length a in
+ if l <= 1 then ()
+ else if l = 2 then begin
+ if cmp a.(0) a.(1) > 0 then begin
+ let e = a.(0) in
+ a.(0) <- a.(1);
+ a.(1) <- e;
+ end;
+ end else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 3;;
+let amerge_3c cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len-1 do
+ let e = a.(srcofs+i) in
+ let j = ref (dstofs+i-1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 4;;
+let amerge_3d cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len-1 do
+ let e = a.(srcofs+i) in
+ let j = ref (dstofs+i-1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 5;;
+let amerge_3e cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len-1 do
+ let e = a.(srcofs+i) in
+ let j = ref (dstofs+i-1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 6;;
+let amerge_3f cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len-1 do
+ let e = a.(srcofs+i) in
+ let j = ref (dstofs+i-1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 7;;
+let amerge_3g cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len-1 do
+ let e = a.(srcofs+i) in
+ let j = ref (dstofs+i-1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 8;;
+let amerge_3h cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len-1 do
+ let e = a.(srcofs+i) in
+ let j = ref (dstofs+i-1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 9;;
+let amerge_3i cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len-1 do
+ let e = a.(srcofs+i) in
+ let j = ref (dstofs+i-1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+let cutoff = 10;;
+let amerge_3j cmp a =
+ let merge src1ofs src1len src2 src2ofs src2len dst dstofs =
+ let i1 = ref src1ofs
+ and i2 = ref src2ofs
+ and d = ref dstofs
+ and src1r = src1ofs + src1len
+ and src2r = src2ofs + src2len
+ in
+ while !i1 < src1r && !i2 < src2r do
+ let s1 = a.(!i1) and s2 = src2.(!i2) in
+ if cmp s1 s2 <= 0 then begin
+ dst.(!d) <- s1;
+ incr i1;
+ end else begin
+ dst.(!d) <- s2;
+ incr i2;
+ end;
+ incr d;
+ done;
+ if !i1 < src1r then
+ Array.blit a !i1 dst !d (src1r - !i1)
+ else
+ Array.blit src2 !i2 dst !d (src2r - !i2)
+ in
+ let isortto srcofs dst dstofs len =
+ for i = 0 to len-1 do
+ let e = a.(srcofs+i) in
+ let j = ref (dstofs+i-1) in
+ while (!j >= dstofs && cmp dst.(!j) e > 0) do
+ dst.(!j + 1) <- dst.(!j);
+ decr j;
+ done;
+ dst.(!j + 1) <- e;
+ done;
+ in
+ let rec sortto srcofs dst dstofs len =
+ if len <= cutoff then isortto srcofs dst dstofs len else
+ let l1 = len / 2 in
+ let l2 = len - l1 in
+ sortto (srcofs+l1) dst (dstofs+l1) l2;
+ sortto srcofs a (srcofs+l2) l1;
+ merge (srcofs+l2) l1 dst (dstofs+l1) l2 dst dstofs;
+ in
+ let l = Array.length a in
+ if l <= cutoff then isortto 0 a 0 l else begin
+ let l1 = l / 2 in
+ let l2 = l - l1 in
+ let t = Array.make l2 a.(0) in
+ sortto l1 t 0 l2;
+ sortto 0 a l2 l1;
+ merge l2 l1 t 0 l2 a 0;
+ end;
+;;
+
+(* FIXME essayer bottom-up merge on arrays ? *)
+
+(************************************************************************)
+(* Shell sort on arrays *)
+
+let ashell_1 cmp a =
+ let l = Array.length a in
+ let step = ref 1 in
+ while !step < l do step := !step * 3 + 1; done;
+ step := !step / 3;
+ while !step > 0 do
+ for j = !step to l-1 do
+ let e = a.(j) in
+ let k = ref (j - !step) in
+ let k1 = ref j in
+ while !k >= 0 && cmp a.(!k) e > 0 do
+ a.(!k1) <- a.(!k);
+ k1 := !k;
+ k := !k - !step;
+ done;
+ a.(!k1) <- e;
+ done;
+ step := !step / 3;
+ done;
+;;
+
+let ashell_2 cmp a =
+ let l = Array.length a in
+ let step = ref 1 in
+ while !step < l do step := !step * 3 + 1; done;
+ step := !step / 3;
+ while !step > 0 do
+ for j = !step to l-1 do
+ let e = a.(j) in
+ let k = ref (j - !step) in
+ while !k >= 0 && cmp a.(!k) e > 0 do
+ a.(!k + !step) <- a.(!k);
+ k := !k - !step;
+ done;
+ a.(!k + !step) <- e;
+ done;
+ step := !step / 3;
+ done;
+;;
+
+let ashell_3 cmp a =
+ let l = Array.length a in
+ let step = ref 1 in
+ while !step < l do step := !step * 3 + 1; done;
+ step := !step / 3;
+ while !step > 0 do
+ for i = 0 to !step - 1 do
+ let j = ref (i + !step) in
+ while !j < l do
+ let e = ref a.(!j) in
+ let k = ref (!j - !step) in
+ if cmp !e a.(i) < 0 then begin
+ let x = !e in e := a.(i); a.(i) <- x;
+ end;
+ while cmp a.(!k) !e > 0 do
+ a.(!k + !step) <- a.(!k);
+ k := !k - !step;
+ done;
+ a.(!k + !step) <- !e;
+ j := !j + !step;
+ done;
+ done;
+ step := !step / 3;
+ done;
+;;
+
+let force = Lazy.force;;
+
+type iilist = Cons of int * iilist Lazy.t;;
+
+let rec mult n (Cons (x,l)) = Cons (n*x, lazy (mult n (force l)))
+
+let rec merge (Cons (x1, t1) as l1) (Cons (x2, t2) as l2) =
+ if x1 = x2 then Cons (x1, lazy (merge (force t1) (force t2)))
+ else if x1 < x2 then Cons (x1, lazy (merge (force t1) l2))
+ else Cons (x2, lazy (merge l1 (force t2)))
+;;
+
+let rec scale = Cons (1, lazy (merge (mult 2 scale) (mult 3 scale)));;
+
+let ashell_4 cmp a =
+ let l = Array.length a in
+ let rec loop1 accu (Cons (x, t)) =
+ if x > l then accu else loop1 (x::accu) (force t)
+ in
+ let sc = loop1 [] scale in
+ let rec loop2 = function
+ | [] -> ()
+ | step::t ->
+ for i = 0 to step - 1 do
+ let j = ref (i + step) in
+ while !j < l do
+ let e = a.(!j) in
+ let k = ref (!j - step) in
+ while !k >= 0 && cmp a.(!k) e > 0 do
+ a.(!k + step) <- a.(!k);
+ k := !k - step;
+ done;
+ a.(!k + step) <- e;
+ j := !j + step;
+ done;
+ done;
+ loop2 t;
+ in
+ loop2 sc;
+;;
+
+(************************************************************************)
+(* Quicksort on arrays *)
+let cutoff = 1;;
+let aquick_1a cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref (r - 1) in
+ while !p2 <= !p3 do
+ let e = a.(!p3) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ end else if c < 0 then begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- e;
+ incr p2;
+ end;
+ done;
+ incr p3;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 1 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 2;;
+let aquick_1b cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref (r - 1) in
+ while !p2 <= !p3 do
+ let e = a.(!p3) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ end else if c < 0 then begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- e;
+ incr p2;
+ end;
+ done;
+ incr p3;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 1 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 3;;
+let aquick_1c cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref (r - 1) in
+ while !p2 <= !p3 do
+ let e = a.(!p3) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ end else if c < 0 then begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- e;
+ incr p2;
+ end;
+ done;
+ incr p3;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 1 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 4;;
+let aquick_1d cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref (r - 1) in
+ while !p2 <= !p3 do
+ let e = a.(!p3) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ end else if c < 0 then begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- e;
+ incr p2;
+ end;
+ done;
+ incr p3;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 1 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 5;;
+let aquick_1e cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref (r - 1) in
+ while !p2 <= !p3 do
+ let e = a.(!p3) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ end else if c < 0 then begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- e;
+ incr p2;
+ end;
+ done;
+ incr p3;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 1 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 6;;
+let aquick_1f cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref (r - 1) in
+ while !p2 <= !p3 do
+ let e = a.(!p3) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ end else if c < 0 then begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- e;
+ incr p2;
+ end;
+ done;
+ incr p3;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 1 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 7;;
+let aquick_1g cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref (r - 1) in
+ while !p2 <= !p3 do
+ let e = a.(!p3) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ end else if c < 0 then begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ a.(!p3) <- a.(!p2);
+ a.(!p2) <- e;
+ incr p2;
+ end;
+ done;
+ incr p3;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 1 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 1;;
+let aquick_2a cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ incr p2;
+ end;
+ done;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 2;;
+let aquick_2b cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ incr p2;
+ end;
+ done;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 3;;
+let aquick_2c cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ incr p2;
+ end;
+ done;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 4;;
+let aquick_2d cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ incr p2;
+ end;
+ done;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 5;;
+let aquick_2e cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ incr p2;
+ end;
+ done;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 6;;
+let aquick_2f cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ incr p2;
+ end;
+ done;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 7;;
+let aquick_2g cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end else begin
+ incr p2;
+ end;
+ done;
+ let len1 = !p1 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p1; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p1)
+ end else qsort l !p1
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 1;;
+let aquick_3a cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 2;;
+let aquick_3b cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 3;;
+let aquick_3c cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 4;;
+let aquick_3d cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 5;;
+let aquick_3e cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 6;;
+let aquick_3f cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 7;;
+let aquick_3g cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 8;;
+let aquick_3h cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 9;;
+let aquick_3i cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+let cutoff = 10;;
+let aquick_3j cmp a =
+ let rec qsort l r = (* ASSUMES r - l >= 2 *)
+ let m = (l + r) / 2 in
+ let al = a.(l) and am = a.(m) and ar = a.(r - 1) in
+ let pivot = if cmp al am <= 0 then
+ if cmp am ar <= 0 then am
+ else if cmp al ar <= 0 then ar
+ else al
+ else
+ if cmp al ar <= 0 then al
+ else if cmp am ar <= 0 then ar
+ else am
+ in
+ let p1 = ref l and p2 = ref l and p3 = ref r in
+ while !p2 < !p3 do
+ let e = a.(!p2) in
+ let c = cmp e pivot in
+ if c > 0 then begin
+ decr p3;
+ a.(!p2) <- a.(!p3);
+ a.(!p3) <- e;
+ end else if c < 0 then begin
+ incr p2;
+ end else begin
+ a.(!p2) <- a.(!p1);
+ a.(!p1) <- e;
+ incr p1;
+ incr p2;
+ end
+ done;
+ while !p1 > l do
+ decr p1;
+ decr p2;
+ let e = a.(!p1) in a.(!p1) <- a.(!p2); a.(!p2) <- e;
+ done;
+ let len1 = !p2 - l and len2 = r - !p3 in
+ if len1 > cutoff then
+ if len2 > cutoff then begin
+ if len1 < len2
+ then (qsort l !p2; qsort !p3 r)
+ else (qsort !p3 r; qsort l !p2)
+ end else qsort l !p2
+ else if len2 > cutoff then qsort !p3 r;
+ in
+ let l = Array.length a in
+ if l > 1 then begin
+ qsort 0 l;
+ let mini = ref 0 in
+ for i = 0 to (min l cutoff) - 1 do
+ if cmp a.(i) a.(!mini) < 0 then mini := i;
+ done;
+ let e = a.(0) in a.(0) <- a.(!mini); a.(!mini) <- e;
+ for i = 1 to l - 1 do
+ let e = a.(i) in
+ let j = ref (i - 1) in
+ while cmp a.(!j) e > 0 do
+ a.(!j + 1) <- a.(!j);
+ decr j;
+ done;
+ a.(!j + 1) <- e;
+ done;
+ end;
+;;
+
+(************************************************************************)
+(* Heap sort on arrays (top-down, ternary) *)
+
+let aheap_1 cmp a =
+ let l = ref (Array.length a) in
+ let l3 = ref ((!l + 1) / 3) in (* l3 is the first element without sons *)
+ let maxson i = (* ASSUMES i < !l3 *)
+ let i31 = i+i+i+1 in
+ let x = ref i31 in
+ if i31+2 < !l then begin
+ if cmp a.(i31) a.(i31+1) < 0 then x := i31+1;
+ if cmp a.(!x) a.(i31+2) < 0 then x := i31+2;
+ !x
+ end else begin
+ if i31+1 < !l && cmp a.(i31) a.(i31+1) < 0
+ then i31+1
+ else i31
+ end
+ in
+ let rec trickledown i e = (* ASSUMES i < !l3 *)
+ let j = maxson i in
+ if cmp a.(j) e > 0 then begin
+ a.(i) <- a.(j);
+ if j < !l3 then trickledown j e else a.(j) <- e;
+ end else begin
+ a.(i) <- e;
+ end;
+ in
+ for i = !l3 - 1 downto 0 do trickledown i a.(i); done;
+ let m = ref (!l + 1 - 3 * !l3) in
+ while !l > 2 do
+ decr l;
+ if !m = 0 then (m := 2; decr l3) else decr m;
+ let e = a.(!l) in
+ a.(!l) <- a.(0);
+ trickledown 0 e;
+ done;
+ if !l > 1 then begin let e = a.(1) in a.(1) <- a.(0); a.(0) <- e; end;
+;;
+
+(************************************************************************)
+(* Heap sort on arrays (top-down, binary) *)
+
+(* FIXME essayer application partielle de trickledown (merge avec down) *)
+(* FIXME essayer expanser maxson dans trickledown; supprimer l'exception. *)
+
+let aheap_2 cmp a =
+ let maxson l i e =
+ let i21 = i + i + 1 in
+ if i21 + 1 < l && cmp a.(i21) a.(i21+1) < 0
+ then i21 + 1
+ else if i21 < l then i21 else (a.(i) <- e; raise Exit)
+ in
+ let rec trickledown l i e =
+ let j = maxson l i e in
+ if cmp a.(j) e > 0 then begin
+ a.(i) <- a.(j);
+ trickledown l j e;
+ end else begin
+ a.(i) <- e;
+ end;
+ in
+ let down l i e = try trickledown l i e with Exit -> () in
+ let l = Array.length a in
+ for i = l / 2 -1 downto 0 do down l i a.(i); done;
+ for i = l - 1 downto 1 do
+ let e = a.(i) in
+ a.(i) <- a.(0);
+ down i 0 e;
+ done;
+;;
+
+(************************************************************************)
+(* Heap sort on arrays (bottom-up, ternary) *)
+
+exception Bottom of int;;
+
+let aheap_3 cmp a =
+ let maxson l i =
+ let i31 = i+i+i+1 in
+ let x = ref i31 in
+ if i31+2 < l then begin
+ if cmp a.(i31) a.(i31+1) < 0 then x := i31+1;
+ if cmp a.(!x) a.(i31+2) < 0 then x := i31+2;
+ !x
+ end else
+ if i31+1 < l && cmp a.(i31) a.(i31+1) < 0
+ then i31+1
+ else if i31 < l then i31 else raise (Bottom i)
+ in
+ let rec trickledown l i e =
+ let j = maxson l i in
+ if cmp a.(j) e > 0 then begin
+ a.(i) <- a.(j);
+ trickledown l j e;
+ end else begin
+ a.(i) <- e;
+ end;
+ in
+ let rec trickle l i e = try trickledown l i e with Bottom i -> a.(i) <- e in
+ let rec bubbledown l i =
+ let j = maxson l i in
+ a.(i) <- a.(j);
+ bubbledown l j;
+ in
+ let bubble l i = try bubbledown l i with Bottom i -> i in
+ let rec trickleup i e =
+ let father = (i - 1) / 3 in
+ assert (i <> father);
+ if cmp a.(father) e < 0 then begin
+ a.(i) <- a.(father);
+ if father > 0 then trickleup father e else a.(0) <- e;
+ end else begin
+ a.(i) <- e;
+ end;
+ in
+ let l = Array.length a in
+ for i = (l + 1) / 3 - 1 downto 0 do trickle l i a.(i); done;
+ for i = l - 1 downto 2 do
+ let e = a.(i) in
+ a.(i) <- a.(0);
+ trickleup (bubble i 0) e;
+ done;
+ if l > 1 then (let e = a.(1) in a.(1) <- a.(0); a.(0) <- e);
+;;
+
+(************************************************************************)
+(* Heap sort on arrays (bottom-up, binary) *)
+
+let aheap_4 cmp a =
+ let maxson l i =
+ let i21 = i + i + 1 in
+ if i21 + 1 < l && cmp a.(i21) a.(i21 + 1) < 0
+ then i21 + 1
+ else if i21 < l then i21 else raise (Bottom i)
+ in
+ let rec trickledown l i e =
+ let j = maxson l i in
+ if cmp a.(j) e > 0 then begin
+ a.(i) <- a.(j);
+ trickledown l j e;
+ end else begin
+ a.(i) <- e;
+ end;
+ in
+ let trickle l i e = try trickledown l i e with Bottom i -> a.(i) <- e in
+ let rec bubbledown l i =
+ let j = maxson l i in
+ a.(i) <- a.(j);
+ bubbledown l j;
+ in
+ let bubble l i = try bubbledown l i with Bottom i -> i in
+ let rec trickleup i e =
+ let father = (i - 1) / 2 in
+ assert (i <> father);
+ if cmp a.(father) e < 0 then begin
+ a.(i) <- a.(father);
+ if father > 0 then trickleup father e else a.(0) <- e;
+ end else begin
+ a.(i) <- e;
+ end;
+ in
+ let l = Array.length a in
+ for i = l / 2 - 1 downto 0 do trickle l i a.(i); done;
+ for i = l - 1 downto 2 do
+ let e = a.(i) in
+ a.(i) <- a.(0);
+ trickleup (bubble i 0) e;
+ done;
+ if l > 1 then (let e = a.(1) in a.(1) <- a.(0); a.(0) <- e);
+;;
+
+(************************************************************************)
+(* heap sort, top-down, ternary, recursive final loop *)
+
+let aheap_5 cmp a =
+ let maxson l i = (* ASSUMES i < (l+1)/3 *)
+ let i31 = i+i+i+1 in
+ let x = ref i31 in
+ if i31+2 < l then begin
+ if cmp a.(i31) a.(i31+1) < 0 then x := i31+1;
+ if cmp a.(!x) a.(i31+2) < 0 then x := i31+2;
+ !x
+ end else begin
+ if i31+1 < l && cmp a.(i31) a.(i31+1) < 0
+ then i31+1
+ else i31
+ end
+ in
+ let rec trickledown l l3 i e = (* ASSUMES i < l3 *)
+ let j = maxson l i in
+ if cmp a.(j) e > 0 then begin
+ a.(i) <- a.(j);
+ if j < l3 then trickledown l l3 j e else a.(j) <- e;
+ end else begin
+ a.(i) <- e;
+ end;
+ in
+ let l = Array.length a in
+ let l3 = (l + 1) / 3 in
+ for i = l3 - 1 downto 0 do trickledown l l3 i a.(i); done;
+ let rec loop0 l l3 =
+ let e = a.(l) in
+ a.(l) <- a.(0);
+ trickledown l l3 0 e;
+ loop2 (l-1) (l3-1);
+ and loop1 l l3 =
+ let e = a.(l) in
+ a.(l) <- a.(0);
+ trickledown l l3 0 e;
+ loop0 (l-1) l3;
+ and loop2 l l3 =
+ if l > 1 then begin
+ let e = a.(l) in
+ a.(l) <- a.(0);
+ trickledown l l3 0 e;
+ loop1 (l-1) l3;
+ end else begin
+ let e = a.(1) in a.(1) <- a.(0); a.(0) <- e;
+ end;
+ in
+ if l > 1 then
+ match l + 1 - 3 * l3 with
+ | 0 -> loop2 (l-1) (l3-1);
+ | 1 -> loop0 (l-1) l3;
+ | 2 -> loop1 (l-1) l3;
+ | _ -> assert false;
+;;
+
+(************************************************************************)
+(* heap sort, top-down, ternary, with exception *)
+
+let aheap_6 cmp a =
+ let maxson e l i =
+ let i31 = i + i + i + 1 in
+ let x = ref i31 in
+ if i31+2 < l then begin
+ if cmp a.(i31) a.(i31+1) < 0 then x := i31+1;
+ if cmp a.(!x) a.(i31+2) < 0 then x := i31+2;
+ !x
+ end else begin
+ if i31+1 < l && cmp a.(i31) a.(i31+1) < 0
+ then i31+1
+ else if i31 < l then i31 else (a.(i) <- e; raise Exit)
+ end
+ in
+ let rec trickledown e l i =
+ let j = maxson e l i in
+ if cmp a.(j) e > 0 then begin
+ a.(i) <- a.(j);
+ trickledown e l j;
+ end else begin
+ a.(i) <- e;
+ end;
+ in
+ let down e l i = try trickledown e l i with Exit -> (); in
+ let l = Array.length a in
+ for i = (l + 1) / 3 - 1 downto 0 do down a.(i) l i; done;
+ for i = l - 1 downto 2 do
+ let e = a.(i) in
+ a.(i) <- a.(0);
+ down e i 0;
+ done;
+ if l > 1 then (let e = a.(1) in a.(1) <- a.(0); a.(0) <- e);
+;;
+
+(* FIXME essayer cutoff pour heapsort *)
+
+(************************************************************************)
+(* Insertion sort with dichotomic search *)
+
+let ainsertion_1 cmp a =
+ let rec dicho l r e =
+ if l = r then l else begin
+ let m = (l + r) / 2 in
+ if cmp a.(m) e <= 0
+ then dicho (m+1) r e
+ else dicho l m e
+ end
+ in
+ for i = 1 to Array.length a - 1 do
+ let e = a.(i) in
+ let j = dicho 0 i e in
+ Array.blit a j a (j + 1) (i - j);
+ a.(j) <- e;
+ done;
+;;
+
+(************************************************************************)
+(* merge sort on lists via arrays *)
+
+let array_to_list_in_place a =
+ let l = Array.length a in
+ let rec loop accu n p =
+ if p <= 0 then accu else begin
+ if p = n then begin
+ Obj.truncate (Obj.repr a) p;
+ loop (a.(p-1) :: accu) (n-1000) (p-1)
+ end else begin
+ loop (a.(p-1) :: accu) n (p-1)
+ end
+ end
+ in
+ loop [] l l
+;;
+
+let array_of_list l len =
+ match l with
+ | [] -> [| |]
+ | h::t ->
+ let a = Array.make len h in
+ let rec loop i l =
+ match l with
+ | [] -> ()
+ | h::t -> a.(i) <- h; loop (i+1) t
+ in
+ loop 1 t;
+ a
+;;
+
+let lmerge_0a cmp l =
+ let a = Array.of_list l in
+ amerge_1e cmp a;
+ array_to_list_in_place a
+;;
+
+let lmerge_0b cmp l =
+ let len = List.length l in
+ if len > 256 then Gc.minor ();
+ let a = array_of_list l len in
+ amerge_1e cmp a;
+ array_to_list_in_place a
+;;
+
+let lshell_0 cmp l =
+ let a = Array.of_list l in
+ ashell_2 cmp a;
+ array_to_list_in_place a
+;;
+
+let lquick_0 cmp l =
+ let a = Array.of_list l in
+ aquick_3f cmp a;
+ array_to_list_in_place a
+;;
+
+(************************************************************************)
+(* merge sort on arrays via lists *)
+
+let amerge_0 cmp a = (* cutoff is not yet used *)
+ let l = lmerge_4e cmp (Array.to_list a) in
+ let rec loop i = function
+ | [] -> ()
+ | h::t -> a.(i) <- h; loop (i + 1) t
+ in
+ loop 0 l
+;;
+
+(************************************************************************)
+
+let lold = [
+ "Sort.list", Sort.list, true;
+ "lmerge_3", lmerge_3, false;
+ "lmerge_4a", lmerge_4a, true;
+];;
+
+let lnew = [
+ "List.stable_sort", List.stable_sort, true;
+
+ "lmerge_0a", lmerge_0a, true;
+ "lmerge_0b", lmerge_0b, true;
+ "lshell_0", lshell_0, false;
+ "lquick_0", lquick_0, false;
+
+ "lmerge_1a", lmerge_1a, true;
+ "lmerge_1b", lmerge_1b, true;
+ "lmerge_1c", lmerge_1c, true;
+ "lmerge_1d", lmerge_1d, true;
+
+ "lmerge_4b", lmerge_4b, true;
+ "lmerge_4c", lmerge_4c, true;
+ "lmerge_4d", lmerge_4d, true;
+ "lmerge_4e", lmerge_4e, true;
+
+ "lmerge_5a", lmerge_5a, true;
+ "lmerge_5b", lmerge_5b, true;
+ "lmerge_5c", lmerge_5c, true;
+ "lmerge_5d", lmerge_5d, true;
+];;
+let anew = [
+ "Array.stable_sort", Array.stable_sort, true;
+ "Array.sort", Array.sort, false;
+
+ "amerge_0", amerge_0, true;
+
+ "amerge_1a", amerge_1a, true;
+ "amerge_1b", amerge_1b, true;
+ "amerge_1c", amerge_1c, true;
+ "amerge_1d", amerge_1d, true;
+ "amerge_1e", amerge_1e, true;
+ "amerge_1f", amerge_1f, true;
+ "amerge_1g", amerge_1g, true;
+ "amerge_1h", amerge_1h, true;
+ "amerge_1i", amerge_1i, true;
+ "amerge_1j", amerge_1j, true;
+
+ "amerge_3a", amerge_3a, true;
+ "amerge_3b", amerge_3b, true;
+ "amerge_3c", amerge_3c, true;
+ "amerge_3d", amerge_3d, true;
+ "amerge_3e", amerge_3e, true;
+ "amerge_3f", amerge_3f, true;
+ "amerge_3g", amerge_3g, true;
+ "amerge_3h", amerge_3h, true;
+ "amerge_3i", amerge_3i, true;
+ "amerge_3j", amerge_3j, true;
+
+ "ashell_1", ashell_1, false;
+ "ashell_2", ashell_2, false;
+ "ashell_3", ashell_3, false;
+ "ashell_4", ashell_4, false;
+
+ "aquick_1a", aquick_1a, false;
+ "aquick_1b", aquick_1b, false;
+ "aquick_1c", aquick_1c, false;
+ "aquick_1d", aquick_1d, false;
+ "aquick_1e", aquick_1e, false;
+ "aquick_1f", aquick_1f, false;
+ "aquick_1g", aquick_1g, false;
+
+ "aquick_2a", aquick_2a, false;
+ "aquick_2b", aquick_2b, false;
+ "aquick_2c", aquick_2c, false;
+ "aquick_2d", aquick_2d, false;
+ "aquick_2e", aquick_2e, false;
+ "aquick_2f", aquick_2f, false;
+ "aquick_2g", aquick_2g, false;
+
+ "aquick_3a", aquick_3a, false;
+ "aquick_3b", aquick_3b, false;
+ "aquick_3c", aquick_3c, false;
+ "aquick_3d", aquick_3d, false;
+ "aquick_3e", aquick_3e, false;
+ "aquick_3f", aquick_3f, false;
+ "aquick_3g", aquick_3g, false;
+ "aquick_3h", aquick_3h, false;
+ "aquick_3i", aquick_3i, false;
+ "aquick_3j", aquick_3j, false;
+
+ "aheap_1", aheap_1, false;
+ "aheap_2", aheap_2, false;
+ "aheap_3", aheap_3, false;
+ "aheap_4", aheap_4, false;
+ "aheap_5", aheap_5, false;
+ "aheap_6", aheap_6, false;
+
+ "ainsertion_1", ainsertion_1, true;
+];;
+
+(************************************************************************)
+(* main program *)
+
+type mode = Test_std | Test | Bench1 | Bench2 | Bench3;;
+
+let size = ref 22
+and mem = ref 0
+and mode = ref Test_std
+and only = ref []
+;;
+
+let usage = "Usage: sorts [-size <table size>] [-mem <memory size>]\n\
+ \032 [-seed <random seed>] [-test|-bench]"
+;;
+
+let options = [
+ "-size", Arg.Int ((:=) size), " Maximum size for benchmarks (default 22)";
+ "-meg",Arg.Int ((:=) mem)," How many megabytes to preallocate (default 0)";
+ "-seed", Arg.Int ((:=) seed), " PRNG seed (default 0)";
+ "-teststd", Arg.Unit (fun () -> mode := Test_std), " Test stdlib (default)";
+ "-test", Arg.Unit (fun () -> mode := Test), " Select test mode";
+ "-bench1", Arg.Unit (fun () -> mode := Bench1), " Select bench mode 1";
+ "-bench2", Arg.Unit (fun () -> mode := Bench2), " Select bench mode 2";
+ "-bench3", Arg.Unit (fun () -> mode := Bench3), " Select bench mode 3";
+ "-fn", Arg.String (fun x -> only := x :: !only),
+ " <function> Test/Bench this function (default all)";
+];;
+let anonymous x = raise (Arg.Bad ("unrecognised option "^x));;
+
+let main () =
+ Arg.parse options anonymous usage;
+
+ Printf.printf "Command line arguments are:";
+ for i = 1 to Array.length Sys.argv - 1 do
+ Printf.printf " %s" Sys.argv.(i);
+ done;
+ Printf.printf "\n";
+
+ ignore (String.create (1048576 * !mem));
+ Gc.full_major ();
+(*
+ let a2l = Array.to_list in
+ let l2ak x y = Array.of_list x in
+ let id = fun x -> x in
+ let fst x y = x in
+ let snd x y = y in
+*)
+ let benchonly f x y z t =
+ match !only with
+ | [] -> f x y z t
+ | l -> if List.mem y l then f x y z t
+ in
+ let testonly x1 x2 x3 x4 x5 x6 =
+ match !only with
+ | [] -> test x1 x2 x3 x4 x5 x6
+ | l -> if List.mem x1 l then test x1 x2 x3 x4 x5 x6
+ in
+
+ match !mode with
+ | Test_std -> begin
+ testonly "List.sort" false List.sort List.sort lc lc;
+ testonly "List.stable_sort" true List.stable_sort List.stable_sort lc lc;
+ testonly "Array.sort" false Array.sort Array.sort ac ac;
+ testonly "Array.stable_sort" true Array.stable_sort Array.stable_sort
+ ac ac;
+ printf "Number of tests failed: %d\n" !numfailed;
+ end;
+ | Test -> begin
+ for i = 0 to List.length lold - 1 do
+ let (name, f1, stable) = List.nth lold i in
+ let (_, f2, _) = List.nth lold i in
+ testonly name stable f1 f2 ll ll;
+ done;
+ testonly "Sort.array" false Sort.array Sort.array al al;
+ for i = 0 to List.length lnew - 1 do
+ let (name, f1, stable) = List.nth lnew i in
+ let (_, f2, _) = List.nth lnew i in
+ testonly name stable f1 f2 lc lc;
+ done;
+ for i = 0 to List.length anew - 1 do
+ let (name, f1, stable) = List.nth anew i in
+ let (_, f2, _) = List.nth anew i in
+ testonly name stable f1 f2 ac ac;
+ done;
+ printf "Number of tests failed: %d\n" !numfailed;
+ end;
+ | Bench1 -> begin
+ let ba = fun x y z -> benchonly bench1a !size x y z
+ and bb = fun x y z -> benchonly bench1b !size x y z
+ and bc = fun x y z -> benchonly bench1c !size x y z
+ in
+ for i = 0 to List.length lold - 1 do
+ let (name, f, stable) = List.nth lold i in ba name f ll;
+ let (name, f, stable) = List.nth lold i in bb name f ll;
+ let (name, f, stable) = List.nth lold i in bc name f ll;
+ done;
+ ba "Sort.array" Sort.array al;
+ bb "Sort.array" Sort.array al;
+ bc "Sort.array" Sort.array al;
+ for i = 0 to List.length lnew - 1 do
+ let (name, f, stable) = List.nth lnew i in ba name f lc;
+ let (name, f, stable) = List.nth lnew i in bb name f lc;
+ let (name, f, stable) = List.nth lnew i in bc name f lc;
+ done;
+ for i = 0 to List.length anew - 1 do
+ let (name, f, stable) = List.nth anew i in ba name f ac;
+ let (name, f, stable) = List.nth anew i in bb name f ac;
+ let (name, f, stable) = List.nth anew i in bc name f ac;
+ done;
+ end;
+ | Bench2 -> begin
+ let b = fun x y z -> benchonly bench2 !size x y z in
+ for i = 0 to List.length lold - 1 do
+ let (name, f, stable) = List.nth lold i in b name f ll;
+ done;
+ b "Sort.array" Sort.array al;
+ for i = 0 to List.length lnew - 1 do
+ let (name, f, stable) = List.nth lnew i in b name f lc;
+ done;
+ for i = 0 to List.length anew - 1 do
+ let (name, f, stable) = List.nth anew i in b name f ac;
+ done;
+ end;
+ | Bench3 -> begin
+ let ba = fun x y z -> benchonly bench3a !size x y z
+ and bb = fun x y z -> benchonly bench3b !size x y z
+ and bc = fun x y z -> benchonly bench3c !size x y z
+ in
+ for i = 0 to List.length lold - 1 do
+ let (name, f, stable) = List.nth lold i in ba name f ll;
+ let (name, f, stable) = List.nth lold i in bb name f ll;
+ let (name, f, stable) = List.nth lold i in bc name f ll;
+ done;
+ for i = 0 to List.length lnew - 1 do
+ let (name, f, stable) = List.nth lnew i in ba name f lc;
+ let (name, f, stable) = List.nth lnew i in bb name f lc;
+ let (name, f, stable) = List.nth lnew i in bc name f lc;
+ done;
+ end;
+;;
+
+if not !Sys.interactive then Printexc.catch main ();;
diff --git a/testsuite/tests/misc/sorts.reference b/testsuite/tests/misc/sorts.reference
new file mode 100644
index 0000000000..fa0cc04806
--- /dev/null
+++ b/testsuite/tests/misc/sorts.reference
@@ -0,0 +1,198 @@
+Command line arguments are:
+Testing List.sort...
+ List.sort with constant ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with sorted ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with reverse-sorted ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with random ints (many dups)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with random ints (few dups)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with records (str)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with records (int[1])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with records (int[10])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with records (int[100])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.sort with records (int[1000])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+Testing List.stable_sort...
+ List.stable_sort with constant ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with sorted ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with reverse-sorted ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with random ints (many dups)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with random ints (few dups)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (str)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (int[1])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (int[10])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (int[100])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (int[1000])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (int[1]) [stable]
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (int[10]) [stable]
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (int[100]) [stable]
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ List.stable_sort with records (int[1000]) [stable]
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+Testing Array.sort...
+ Array.sort with constant ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with sorted ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with reverse-sorted ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with random ints (many dups)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with random ints (few dups)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with records (str)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with records (int[1])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with records (int[10])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with records (int[100])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.sort with records (int[1000])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+Testing Array.stable_sort...
+ Array.stable_sort with constant ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with sorted ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with reverse-sorted ints
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with random ints (many dups)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with random ints (few dups)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (str)
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (int[1])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (int[10])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (int[100])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (int[1000])
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (int[1]) [stable]
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (int[10]) [stable]
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (int[100]) [stable]
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+ Array.stable_sort with records (int[1000]) [stable]
+ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
+ 12. 13. 28. 100. 127. 128. 129. 191. 192. 193. 506. 1000.
+ 1023. 1024. 1025. 1535. 1536. 1537. 2323. 4000. 4094. 4096. 4098. 5123.
+Number of tests failed: 0
diff --git a/testsuite/tests/misc/takc.ml b/testsuite/tests/misc/takc.ml
new file mode 100644
index 0000000000..667ff5a749
--- /dev/null
+++ b/testsuite/tests/misc/takc.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec tak x y z =
+ if x > y then tak (tak (x-1) y z) (tak (y-1) z x) (tak (z-1) x y)
+ else z
+
+let rec repeat n =
+ if n <= 0 then 0 else tak 18 12 6 + repeat(n-1)
+
+let _ = print_int (repeat 2000); print_newline(); exit 0
diff --git a/testsuite/tests/misc/takc.reference b/testsuite/tests/misc/takc.reference
new file mode 100644
index 0000000000..bfed819398
--- /dev/null
+++ b/testsuite/tests/misc/takc.reference
@@ -0,0 +1 @@
+14000
diff --git a/testsuite/tests/misc/taku.ml b/testsuite/tests/misc/taku.ml
new file mode 100644
index 0000000000..47d94c88bd
--- /dev/null
+++ b/testsuite/tests/misc/taku.ml
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec tak (x, y, z) =
+ if x > y then tak(tak (x-1, y, z), tak (y-1, z, x), tak (z-1, x, y))
+ else z
+
+let rec repeat n =
+ if n <= 0 then 0 else tak(18,12,6) + repeat(n-1)
+
+let _ = print_int (repeat 2000); print_newline(); exit 0
diff --git a/testsuite/tests/misc/taku.reference b/testsuite/tests/misc/taku.reference
new file mode 100644
index 0000000000..bfed819398
--- /dev/null
+++ b/testsuite/tests/misc/taku.reference
@@ -0,0 +1 @@
+14000
diff --git a/testsuite/tests/misc/weaklifetime.ml b/testsuite/tests/misc/weaklifetime.ml
new file mode 100644
index 0000000000..d6b23f3d22
--- /dev/null
+++ b/testsuite/tests/misc/weaklifetime.ml
@@ -0,0 +1,74 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, Jane Street Group, LLC *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+Random.init 12345;;
+
+let size = 1000;;
+
+type block = int array;;
+
+type objdata =
+ | Present of block
+ | Absent of int (* GC count at time of erase *)
+;;
+
+type bunch = {
+ objs : objdata array;
+ wp : block Weak.t;
+};;
+
+let data =
+ Array.init size (fun i ->
+ let n = 1 + Random.int size in
+ {
+ objs = Array.make n (Absent 0);
+ wp = Weak.create n;
+ }
+ )
+;;
+
+let gccount () = (Gc.quick_stat ()).Gc.major_collections;;
+
+(* Check the correctness condition on the data at (i,j):
+ 1. if the block is present, the weak pointer must be full
+ 2. if the block was removed at GC n, and the weak pointer is still
+ full, then the current GC must be at most n+1.
+
+ Then modify the data in one of the following ways:
+ 1. if the block and weak pointer are absent, fill them
+ 2. if the block and weak pointer are present, randomly erase the block
+*)
+let check_and_change i j =
+ let gc1 = gccount () in
+ match data.(i).objs.(j), Weak.check data.(i).wp j with
+ | Present x, false -> assert false
+ | Absent n, true -> assert (gc1 <= n+1)
+ | Absent _, false ->
+ let x = Array.make (1 + Random.int 10) 42 in
+ data.(i).objs.(j) <- Present x;
+ Weak.set data.(i).wp j (Some x);
+ | Present _, true ->
+ if Random.int 10 = 0 then begin
+ data.(i).objs.(j) <- Absent gc1;
+ let gc2 = gccount () in
+ if gc1 <> gc2 then data.(i).objs.(j) <- Absent gc2;
+ end
+;;
+
+let dummy = ref [||];;
+
+while gccount () < 20 do
+ dummy := Array.make (Random.int 300) 0;
+ let i = Random.int size in
+ let j = Random.int (Array.length data.(i).objs) in
+ check_and_change i j;
+done
diff --git a/testsuite/tests/misc/weaklifetime.reference b/testsuite/tests/misc/weaklifetime.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/misc/weaklifetime.reference
diff --git a/testsuite/tests/misc/weaktest.ml b/testsuite/tests/misc/weaktest.ml
new file mode 100644
index 0000000000..ffeabf29ef
--- /dev/null
+++ b/testsuite/tests/misc/weaktest.ml
@@ -0,0 +1,83 @@
+(*************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2008 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(*************************************************************************)
+
+let debug = false;;
+
+open Printf;;
+
+module Hashed = struct
+ type t = string list;;
+ let equal x y =
+ eprintf "equal: %s / %s\n" (List.hd x) (List.hd y);
+ x = y
+ ;;
+ let hash x = Hashtbl.hash (List.hd x);;
+end;;
+
+module HT = Weak.Make (Hashed);;
+
+let tbl = HT.create 7;;
+
+let r = ref [];;
+
+let bunch =
+ if Array.length Sys.argv < 2
+ then 10000
+ else int_of_string Sys.argv.(1)
+;;
+
+Random.init 314;;
+
+let random_string n =
+ let result = String.create n in
+ for i = 0 to n - 1 do
+ result.[i] <- Char.chr (32 + Random.int 95);
+ done;
+ result
+;;
+
+let added = ref 0;;
+let mistakes = ref 0;;
+
+let print_status () =
+ let (len, entries, sumbuck, buckmin, buckmed, buckmax) = HT.stats tbl in
+ if entries > bunch * (!added + 1) then begin
+ if debug then begin
+ printf "\n===================\n";
+ printf "len = %d\n" len;
+ printf "entries = %d\n" entries;
+ printf "sum of bucket sizes = %d\n" sumbuck;
+ printf "min bucket = %d\n" buckmin;
+ printf "med bucket = %d\n" buckmed;
+ printf "max bucket = %d\n" buckmax;
+ printf "GC count = %d\n" (Gc.quick_stat ()).Gc.major_collections;
+ flush stdout;
+ end;
+ incr mistakes;
+ end;
+ added := 0;
+;;
+
+Gc.create_alarm print_status;;
+
+for j = 0 to 99 do
+ r := [];
+ incr added;
+
+ for i = 1 to bunch do
+ let c = random_string 7 in
+ r := c :: !r;
+ HT.add tbl !r;
+ done;
+done;;
+
+if !mistakes < 5 then printf "pass\n" else printf "fail\n";;
diff --git a/testsuite/tests/misc/weaktest.reference b/testsuite/tests/misc/weaktest.reference
new file mode 100644
index 0000000000..2ae28399f5
--- /dev/null
+++ b/testsuite/tests/misc/weaktest.reference
@@ -0,0 +1 @@
+pass
diff --git a/testsuite/tests/parsing/Makefile b/testsuite/tests/parsing/Makefile
new file mode 100644
index 0000000000..c8de7609d1
--- /dev/null
+++ b/testsuite/tests/parsing/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Jeremie Dimino, Jane Street Europe #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+TOPFLAGS+=-dparsetree
+include $(BASEDIR)/makefiles/Makefile.dparsetree
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/parsing/pr6865.ml b/testsuite/tests/parsing/pr6865.ml
new file mode 100644
index 0000000000..78cd602feb
--- /dev/null
+++ b/testsuite/tests/parsing/pr6865.ml
@@ -0,0 +1,3 @@
+let%foo x = 42
+let%foo _ = () and _ = ()
+let%foo _ = ()
diff --git a/testsuite/tests/parsing/pr6865.ml.reference b/testsuite/tests/parsing/pr6865.ml.reference
new file mode 100644
index 0000000000..0dc38fb240
--- /dev/null
+++ b/testsuite/tests/parsing/pr6865.ml.reference
@@ -0,0 +1,47 @@
+[
+ structure_item (pr6865.ml[1,0+0]..[1,0+14]) ghost
+ Pstr_extension "foo"
+ [
+ structure_item (pr6865.ml[1,0+0]..[1,0+14])
+ Pstr_value Nonrec
+ [
+ <def>
+ pattern (pr6865.ml[1,0+8]..[1,0+9])
+ Ppat_var "x" (pr6865.ml[1,0+8]..[1,0+9])
+ expression (pr6865.ml[1,0+12]..[1,0+14])
+ Pexp_constant Const_int 42
+ ]
+ ]
+ structure_item (pr6865.ml[2,15+0]..[2,15+25]) ghost
+ Pstr_extension "foo"
+ [
+ structure_item (pr6865.ml[2,15+0]..[2,15+25])
+ Pstr_value Nonrec
+ [
+ <def>
+ pattern (pr6865.ml[2,15+8]..[2,15+9])
+ Ppat_any
+ expression (pr6865.ml[2,15+12]..[2,15+14])
+ Pexp_construct "()" (pr6865.ml[2,15+12]..[2,15+14])
+ None
+ <def>
+ pattern (pr6865.ml[2,15+19]..[2,15+20])
+ Ppat_any
+ expression (pr6865.ml[2,15+23]..[2,15+25])
+ Pexp_construct "()" (pr6865.ml[2,15+23]..[2,15+25])
+ None
+ ]
+ ]
+ structure_item (pr6865.ml[3,41+0]..[3,41+14]) ghost
+ Pstr_extension "foo"
+ [
+ structure_item (pr6865.ml[3,41+0]..[3,41+14])
+ Pstr_eval
+ expression (pr6865.ml[3,41+12]..[3,41+14])
+ Pexp_construct "()" (pr6865.ml[3,41+12]..[3,41+14])
+ None
+ ]
+]
+
+File "pr6865.ml", line 1, characters 4-7:
+Uninterpreted extension 'foo'.
diff --git a/testsuite/tests/ppx-attributes/Makefile b/testsuite/tests/ppx-attributes/Makefile
new file mode 100644
index 0000000000..e94bb069b1
--- /dev/null
+++ b/testsuite/tests/ppx-attributes/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Peter Zotov #
+# #
+# Copyright 2014 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/ppx-attributes/warning.ml b/testsuite/tests/ppx-attributes/warning.ml
new file mode 100644
index 0000000000..f50c3d6048
--- /dev/null
+++ b/testsuite/tests/ppx-attributes/warning.ml
@@ -0,0 +1,47 @@
+[@@@ocaml.warning "@A"]
+
+(* Fixture *)
+
+module type DEPRECATED = sig end
+[@@ocaml.deprecated]
+
+module T = struct
+ type deprecated
+ [@@ocaml.deprecated]
+end
+
+(* Structure items *)
+
+let _ = let x = 1 in ()
+[@@ocaml.warning "-26"]
+
+include (struct let _ = let x = 1 in () end)
+[@@ocaml.warning "-26"]
+
+module A = struct let _ = let x = 1 in () end
+[@@ocaml.warning "-26"]
+
+module rec B : sig type t end = struct type t = T.deprecated end
+[@@ocaml.warning "-3"]
+
+module type T = sig type t = T.deprecated end
+[@@ocaml.warning "-3"]
+
+(* Signature items *)
+
+module type S = sig
+ val x : T.deprecated
+ [@@ocaml.warning "-3"]
+
+ module AA : sig type t = T.deprecated end
+ [@@ocaml.warning "-3"]
+
+ module rec BB : sig type t = T.deprecated end
+ [@@ocaml.warning "-3"]
+
+ module type T = sig type t = T.deprecated end
+ [@@ocaml.warning "-3"]
+
+ include DEPRECATED
+ [@@ocaml.warning "-3"]
+end
diff --git a/testsuite/tests/ppx-attributes/warning.reference b/testsuite/tests/ppx-attributes/warning.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/ppx-attributes/warning.reference
diff --git a/testsuite/tests/prim-bigstring/Makefile b/testsuite/tests/prim-bigstring/Makefile
new file mode 100644
index 0000000000..379dba99c9
--- /dev/null
+++ b/testsuite/tests/prim-bigstring/Makefile
@@ -0,0 +1,8 @@
+BASEDIR=../..
+LIBRARIES=unix bigarray
+ADD_COMPFLAGS=-I $(OTOPDIR)/otherlibs/$(UNIXLIBVAR)unix \
+ -I $(OTOPDIR)/otherlibs/bigarray
+LD_PATH=$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix:$(TOPDIR)/otherlibs/bigarray
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/prim-bigstring/bigstring_access.ml b/testsuite/tests/prim-bigstring/bigstring_access.ml
new file mode 100644
index 0000000000..512181f088
--- /dev/null
+++ b/testsuite/tests/prim-bigstring/bigstring_access.ml
@@ -0,0 +1,119 @@
+
+open Bigarray
+type bigstring = (char, int8_unsigned_elt, c_layout) Array1.t
+
+external caml_bigstring_get_16 :
+ bigstring -> int -> int = "%caml_bigstring_get16"
+external caml_bigstring_get_32 :
+ bigstring -> int -> int32 = "%caml_bigstring_get32"
+external caml_bigstring_get_64 :
+ bigstring -> int -> int64 = "%caml_bigstring_get64"
+
+external caml_bigstring_set_16 :
+ bigstring -> int -> int -> unit = "%caml_bigstring_set16"
+external caml_bigstring_set_32 :
+ bigstring -> int -> int32 -> unit = "%caml_bigstring_set32"
+external caml_bigstring_set_64 :
+ bigstring -> int -> int64 -> unit = "%caml_bigstring_set64"
+
+let bigstring_of_string s =
+ let a = Array1.create char c_layout (String.length s) in
+ for i = 0 to String.length s - 1 do
+ a.{i} <- s.[i]
+ done;
+ a
+
+let s = bigstring_of_string (String.make 10 '\x00')
+let empty_s = bigstring_of_string ""
+
+let assert_bound_check2 f v1 v2 =
+ try
+ ignore(f v1 v2);
+ assert false
+ with
+ | Invalid_argument("index out of bounds") -> ()
+
+let assert_bound_check3 f v1 v2 v3 =
+ try
+ ignore(f v1 v2 v3);
+ assert false
+ with
+ | Invalid_argument("index out of bounds") -> ()
+
+let () =
+ assert_bound_check2 caml_bigstring_get_16 s (-1);
+ assert_bound_check2 caml_bigstring_get_16 s 9;
+ assert_bound_check2 caml_bigstring_get_32 s (-1);
+ assert_bound_check2 caml_bigstring_get_32 s 7;
+ assert_bound_check2 caml_bigstring_get_64 s (-1);
+ assert_bound_check2 caml_bigstring_get_64 s 3;
+
+ assert_bound_check3 caml_bigstring_set_16 s (-1) 0;
+ assert_bound_check3 caml_bigstring_set_16 s 9 0;
+ assert_bound_check3 caml_bigstring_set_32 s (-1) 0l;
+ assert_bound_check3 caml_bigstring_set_32 s 7 0l;
+ assert_bound_check3 caml_bigstring_set_64 s (-1) 0L;
+ assert_bound_check3 caml_bigstring_set_64 s 3 0L;
+
+ assert_bound_check2 caml_bigstring_get_16 empty_s 0;
+ assert_bound_check2 caml_bigstring_get_32 empty_s 0;
+ assert_bound_check2 caml_bigstring_get_64 empty_s 0;
+
+ assert_bound_check3 caml_bigstring_set_16 empty_s 0 0;
+ assert_bound_check3 caml_bigstring_set_32 empty_s 0 0l;
+ assert_bound_check3 caml_bigstring_set_64 empty_s 0 0L
+
+external bswap16: int -> int = "%bswap16"
+external bswap32: int32 -> int32 = "%bswap_int32"
+external bswap64: int64 -> int64 = "%bswap_int64"
+
+let swap16 x =
+ if Sys.big_endian
+ then bswap16 x
+ else x
+
+let swap32 x =
+ if Sys.big_endian
+ then bswap32 x
+ else x
+
+let swap64 x =
+ if Sys.big_endian
+ then bswap64 x
+ else x
+
+let () =
+ caml_bigstring_set_16 s 0 (swap16 0x1234);
+ Printf.printf "%x %x %x\n%!"
+ (swap16 (caml_bigstring_get_16 s 0))
+ (swap16 (caml_bigstring_get_16 s 1))
+ (swap16 (caml_bigstring_get_16 s 2));
+ caml_bigstring_set_16 s 0 (swap16 0xFEDC);
+ Printf.printf "%x %x %x\n%!"
+ (swap16 (caml_bigstring_get_16 s 0))
+ (swap16 (caml_bigstring_get_16 s 1))
+ (swap16 (caml_bigstring_get_16 s 2))
+
+let () =
+ caml_bigstring_set_32 s 0 (swap32 0x12345678l);
+ Printf.printf "%lx %lx %lx\n%!"
+ (swap32 (caml_bigstring_get_32 s 0))
+ (swap32 (caml_bigstring_get_32 s 1))
+ (swap32 (caml_bigstring_get_32 s 2));
+ caml_bigstring_set_32 s 0 (swap32 0xFEDCBA09l);
+ Printf.printf "%lx %lx %lx\n%!"
+ (swap32 (caml_bigstring_get_32 s 0))
+ (swap32 (caml_bigstring_get_32 s 1))
+ (swap32 (caml_bigstring_get_32 s 2))
+
+let () =
+ caml_bigstring_set_64 s 0 (swap64 0x1234567890ABCDEFL);
+ Printf.printf "%Lx %Lx %Lx\n%!"
+ (swap64 (caml_bigstring_get_64 s 0))
+ (swap64 (caml_bigstring_get_64 s 1))
+ (swap64 (caml_bigstring_get_64 s 2));
+ caml_bigstring_set_64 s 0 (swap64 0xFEDCBA0987654321L);
+ Printf.printf "%Lx %Lx %Lx\n%!"
+ (swap64 (caml_bigstring_get_64 s 0))
+ (swap64 (caml_bigstring_get_64 s 1))
+ (swap64 (caml_bigstring_get_64 s 2))
diff --git a/testsuite/tests/prim-bigstring/bigstring_access.reference b/testsuite/tests/prim-bigstring/bigstring_access.reference
new file mode 100644
index 0000000000..22b25addf3
--- /dev/null
+++ b/testsuite/tests/prim-bigstring/bigstring_access.reference
@@ -0,0 +1,6 @@
+1234 12 0
+fedc fe 0
+12345678 123456 1234
+fedcba09 fedcba fedc
+1234567890abcdef 1234567890abcd 1234567890ab
+fedcba0987654321 fedcba09876543 fedcba098765
diff --git a/testsuite/tests/prim-bigstring/string_access.ml b/testsuite/tests/prim-bigstring/string_access.ml
new file mode 100644
index 0000000000..48964c0b33
--- /dev/null
+++ b/testsuite/tests/prim-bigstring/string_access.ml
@@ -0,0 +1,106 @@
+
+external caml_string_get_16 : string -> int -> int = "%caml_string_get16"
+external caml_string_get_32 : string -> int -> int32 = "%caml_string_get32"
+external caml_string_get_64 : string -> int -> int64 = "%caml_string_get64"
+
+external caml_string_set_16 : string -> int -> int -> unit =
+ "%caml_string_set16"
+external caml_string_set_32 : string -> int -> int32 -> unit =
+ "%caml_string_set32"
+external caml_string_set_64 : string -> int -> int64 -> unit =
+ "%caml_string_set64"
+
+let s = String.make 10 '\x00'
+let empty_s = ""
+
+let assert_bound_check2 f v1 v2 =
+ try
+ ignore(f v1 v2);
+ assert false
+ with
+ | Invalid_argument("index out of bounds") -> ()
+
+let assert_bound_check3 f v1 v2 v3 =
+ try
+ ignore(f v1 v2 v3);
+ assert false
+ with
+ | Invalid_argument("index out of bounds") -> ()
+
+let () =
+ assert_bound_check2 caml_string_get_16 s (-1);
+ assert_bound_check2 caml_string_get_16 s 9;
+ assert_bound_check2 caml_string_get_32 s (-1);
+ assert_bound_check2 caml_string_get_32 s 7;
+ assert_bound_check2 caml_string_get_64 s (-1);
+ assert_bound_check2 caml_string_get_64 s 3;
+
+ assert_bound_check3 caml_string_set_16 s (-1) 0;
+ assert_bound_check3 caml_string_set_16 s 9 0;
+ assert_bound_check3 caml_string_set_32 s (-1) 0l;
+ assert_bound_check3 caml_string_set_32 s 7 0l;
+ assert_bound_check3 caml_string_set_64 s (-1) 0L;
+ assert_bound_check3 caml_string_set_64 s 3 0L;
+
+ assert_bound_check2 caml_string_get_16 empty_s 0;
+ assert_bound_check2 caml_string_get_32 empty_s 0;
+ assert_bound_check2 caml_string_get_64 empty_s 0;
+
+ assert_bound_check3 caml_string_set_16 empty_s 0 0;
+ assert_bound_check3 caml_string_set_32 empty_s 0 0l;
+ assert_bound_check3 caml_string_set_64 empty_s 0 0L
+
+external bswap16: int -> int = "%bswap16"
+external bswap32: int32 -> int32 = "%bswap_int32"
+external bswap64: int64 -> int64 = "%bswap_int64"
+
+let swap16 x =
+ if Sys.big_endian
+ then bswap16 x
+ else x
+
+let swap32 x =
+ if Sys.big_endian
+ then bswap32 x
+ else x
+
+let swap64 x =
+ if Sys.big_endian
+ then bswap64 x
+ else x
+
+let () =
+ caml_string_set_16 s 0 (swap16 0x1234);
+ Printf.printf "%x %x %x\n%!"
+ (swap16 (caml_string_get_16 s 0))
+ (swap16 (caml_string_get_16 s 1))
+ (swap16 (caml_string_get_16 s 2));
+ caml_string_set_16 s 0 (swap16 0xFEDC);
+ Printf.printf "%x %x %x\n%!"
+ (swap16 (caml_string_get_16 s 0))
+ (swap16 (caml_string_get_16 s 1))
+ (swap16 (caml_string_get_16 s 2))
+
+let () =
+ caml_string_set_32 s 0 (swap32 0x12345678l);
+ Printf.printf "%lx %lx %lx\n%!"
+ (swap32 (caml_string_get_32 s 0))
+ (swap32 (caml_string_get_32 s 1))
+ (swap32 (caml_string_get_32 s 2));
+ caml_string_set_32 s 0 (swap32 0xFEDCBA09l);
+ Printf.printf "%lx %lx %lx\n%!"
+ (swap32 (caml_string_get_32 s 0))
+ (swap32 (caml_string_get_32 s 1))
+ (swap32 (caml_string_get_32 s 2))
+
+let () =
+ caml_string_set_64 s 0 (swap64 0x1234567890ABCDEFL);
+ Printf.printf "%Lx %Lx %Lx\n%!"
+ (swap64 (caml_string_get_64 s 0))
+ (swap64 (caml_string_get_64 s 1))
+ (swap64 (caml_string_get_64 s 2));
+ caml_string_set_64 s 0 (swap64 0xFEDCBA0987654321L);
+ Printf.printf "%Lx %Lx %Lx\n%!"
+ (swap64 (caml_string_get_64 s 0))
+ (swap64 (caml_string_get_64 s 1))
+ (swap64 (caml_string_get_64 s 2))
diff --git a/testsuite/tests/prim-bigstring/string_access.reference b/testsuite/tests/prim-bigstring/string_access.reference
new file mode 100644
index 0000000000..22b25addf3
--- /dev/null
+++ b/testsuite/tests/prim-bigstring/string_access.reference
@@ -0,0 +1,6 @@
+1234 12 0
+fedc fe 0
+12345678 123456 1234
+fedcba09 fedcba fedc
+1234567890abcdef 1234567890abcd 1234567890ab
+fedcba0987654321 fedcba09876543 fedcba098765
diff --git a/testsuite/tests/prim-bswap/Makefile b/testsuite/tests/prim-bswap/Makefile
new file mode 100644
index 0000000000..956ab4a72f
--- /dev/null
+++ b/testsuite/tests/prim-bswap/Makefile
@@ -0,0 +1,17 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Benedikt Meurer, os-cillation GmbH #
+# #
+# Copyright 1998 Institut National de Recherche en Informatique #
+# et en Automatique. Copyright 2013 Benedikt Meurer. All rights #
+# reserved. This file is distributed under the terms of the Q #
+# Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/prim-bswap/bswap.ml b/testsuite/tests/prim-bswap/bswap.ml
new file mode 100644
index 0000000000..40ab21ff80
--- /dev/null
+++ b/testsuite/tests/prim-bswap/bswap.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Benedikt Meurer, os-cillation GmbH *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique *)
+(* et en Automatique. Copyright 2013 Benedikt Meurer. All rights *)
+(* reserved. This file is distributed under the terms of the Q *)
+(* Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+
+external bswap16: int -> int = "%bswap16"
+external bswap32: int32 -> int32 = "%bswap_int32"
+external bswap64: int64 -> int64 = "%bswap_int64"
+
+let d16 = [0x11223344;
+ 0x0000f0f0]
+let d32 = [0x11223344l;
+ 0xf0f0f0f0l]
+let d64 = [0x1122334455667788L;
+ 0xf0f0f0f0f0f0f0f0L]
+
+let _ =
+ List.iter (fun x -> printf "%x\n" (bswap16 x)) d16;
+ List.iter (fun x -> printf "%lx\n" (bswap32 x)) d32;
+ List.iter (fun x -> printf "%Lx\n" (bswap64 x)) d64
diff --git a/testsuite/tests/prim-bswap/bswap.reference b/testsuite/tests/prim-bswap/bswap.reference
new file mode 100644
index 0000000000..c08abb7f18
--- /dev/null
+++ b/testsuite/tests/prim-bswap/bswap.reference
@@ -0,0 +1,6 @@
+4433
+f0f0
+44332211
+f0f0f0f0
+8877665544332211
+f0f0f0f0f0f0f0f0
diff --git a/testsuite/tests/prim-revapply/Makefile b/testsuite/tests/prim-revapply/Makefile
new file mode 100644
index 0000000000..6e8d01ff87
--- /dev/null
+++ b/testsuite/tests/prim-revapply/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/prim-revapply/apply.ml b/testsuite/tests/prim-revapply/apply.ml
new file mode 100644
index 0000000000..e873c48458
--- /dev/null
+++ b/testsuite/tests/prim-revapply/apply.ml
@@ -0,0 +1,48 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+external ( @@ ) : ('a -> 'b) -> 'a -> 'b = "%apply"
+
+let f x = x + x
+let g x = x * x
+let h x = x + 1
+let add x y = x + y
+
+let _ =
+ List.iter (fun x ->
+ print_int x; print_newline ()
+ )
+ [
+ f @@ 3; (* 6 *)
+ g @@ f @@ 3; (* 36 *)
+ f @@ g @@ 3; (* 18 *)
+ h @@ g @@ f @@ 3; (* 37 *)
+ add 4 @@ g @@ f @@ add 3 @@ add 2 @@ 3; (* 260 *)
+ ]
+external ( @@ ) : ('a -> 'b) -> 'a -> 'b = "%apply"
+
+let f x = x + x
+let g x = x * x
+let h x = x + 1
+let add x y = x + y
+
+let _ =
+ List.iter (fun x ->
+ print_int x; print_newline ()
+ )
+ [
+ f @@ 3; (* 6 *)
+ g @@ f @@ 3; (* 36 *)
+ f @@ g @@ 3; (* 18 *)
+ h @@ g @@ f @@ 3; (* 37 *)
+ add 4 @@ g @@ f @@ add 3 @@ add 2 @@ 3; (* 260 *)
+ ]
diff --git a/testsuite/tests/prim-revapply/apply.reference b/testsuite/tests/prim-revapply/apply.reference
new file mode 100644
index 0000000000..07fc0dc4ce
--- /dev/null
+++ b/testsuite/tests/prim-revapply/apply.reference
@@ -0,0 +1,10 @@
+6
+36
+18
+37
+260
+6
+36
+18
+37
+260
diff --git a/testsuite/tests/prim-revapply/revapply.ml b/testsuite/tests/prim-revapply/revapply.ml
new file mode 100644
index 0000000000..d869163e05
--- /dev/null
+++ b/testsuite/tests/prim-revapply/revapply.ml
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+external ( |> ) : 'a -> ('a -> 'b) -> 'b = "%revapply"
+
+let f x = x + x
+let g x = x * x
+let h x = x + 1
+let add x y = x + y
+
+let _ =
+ List.iter (fun x ->
+ print_int x; print_newline ()
+ )
+ [
+ 3 |> f; (* 6 *)
+ 3 |> f |> g; (* 36 *)
+ 3 |> g |> f; (* 18 *)
+ 3 |> f |> g |> h; (* 37 *)
+ 3 |> add 2 |> add 3 |> f |> g |> add 4; (* 260 *)
+ ]
diff --git a/testsuite/tests/prim-revapply/revapply.reference b/testsuite/tests/prim-revapply/revapply.reference
new file mode 100644
index 0000000000..fbca4428dd
--- /dev/null
+++ b/testsuite/tests/prim-revapply/revapply.reference
@@ -0,0 +1,5 @@
+6
+36
+18
+37
+260
diff --git a/testsuite/tests/regression/pr3612/Makefile b/testsuite/tests/regression/pr3612/Makefile
new file mode 100644
index 0000000000..032420d278
--- /dev/null
+++ b/testsuite/tests/regression/pr3612/Makefile
@@ -0,0 +1,18 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Pierre Chambart, OCamlPro #
+# #
+# Copyright 2014 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+MAIN_MODULE=pr3612
+C_FILES=custom_finalize
+
+BASEDIR=../../..
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/regression/pr3612/custom_finalize.c b/testsuite/tests/regression/pr3612/custom_finalize.c
new file mode 100644
index 0000000000..ad117409a9
--- /dev/null
+++ b/testsuite/tests/regression/pr3612/custom_finalize.c
@@ -0,0 +1,62 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Pierre Chambart, OCamlPro */
+/* */
+/* Copyright 2014 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <caml/custom.h>
+
+static int free_counter = 0;
+static int alloc_counter = 0;
+
+static void caml_test_finalize(value v)
+{
+ free_counter++;
+}
+
+static void caml_test_serialize(value v,
+ uintnat * wsize_32,
+ uintnat * wsize_64)
+{
+ *wsize_32 = 0;
+ *wsize_64 = 0;
+}
+
+uintnat caml_test_deserialize(void * dst)
+{
+ alloc_counter++;
+ return 0;
+}
+
+static struct custom_operations caml_test_ops = {
+ "_test",
+ caml_test_finalize,
+ custom_compare_default,
+ custom_hash_default,
+ caml_test_serialize,
+ caml_test_deserialize,
+ custom_compare_ext_default
+};
+
+value caml_test_pr3612_alloc(value unit)
+{
+ return caml_alloc_custom(&caml_test_ops, 0, 0, 1);
+}
+
+value caml_test_pr3612_counter(value unit)
+{
+ return Val_int(alloc_counter-free_counter);
+}
+
+CAMLprim value caml_test_pr3612_init(value unit)
+{
+ caml_register_custom_operations(&caml_test_ops);
+ return Val_unit;
+}
diff --git a/testsuite/tests/regression/pr3612/pr3612.ml b/testsuite/tests/regression/pr3612/pr3612.ml
new file mode 100644
index 0000000000..8369a59178
--- /dev/null
+++ b/testsuite/tests/regression/pr3612/pr3612.ml
@@ -0,0 +1,32 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Chambart, OCamlPro *)
+(* *)
+(* Copyright 2014 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type t
+
+external test_alloc : unit -> t = "caml_test_pr3612_alloc"
+external get_counter : unit -> int = "caml_test_pr3612_counter"
+(* The number of deserialized blocs minus the number of freed blocs *)
+
+external init : unit -> unit = "caml_test_pr3612_init"
+
+let test s =
+ for i = 0 to 1_000_000 do
+ ignore (Marshal.from_string s 0)
+ done
+
+let () =
+ init ();
+ let s = Marshal.to_string (test_alloc ()) [] in
+ test s;
+ Gc.full_major ();
+ print_int (get_counter ());
+ print_newline ()
diff --git a/testsuite/tests/regression/pr3612/pr3612.reference b/testsuite/tests/regression/pr3612/pr3612.reference
new file mode 100644
index 0000000000..3a2e3f4984
--- /dev/null
+++ b/testsuite/tests/regression/pr3612/pr3612.reference
@@ -0,0 +1 @@
+-1
diff --git a/testsuite/tests/regression/pr5080-notes/Makefile b/testsuite/tests/regression/pr5080-notes/Makefile
new file mode 100644
index 0000000000..8079539b62
--- /dev/null
+++ b/testsuite/tests/regression/pr5080-notes/Makefile
@@ -0,0 +1,17 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+ADD_COMPFLAGS = -pp 'camlp4o pa_macro.cmo'
+MAIN_MODULE = pr5080_notes_ok
+
+include ../../../makefiles/Makefile.okbad
+include ../../../makefiles/Makefile.common
diff --git a/testsuite/tests/regression/pr5080-notes/pr5080_notes_ok.ml b/testsuite/tests/regression/pr5080-notes/pr5080_notes_ok.ml
new file mode 100644
index 0000000000..f043f397bc
--- /dev/null
+++ b/testsuite/tests/regression/pr5080-notes/pr5080_notes_ok.ml
@@ -0,0 +1,16 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2011 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let marshal_int f =
+ match [] with
+ | _ :: `INT n :: _ -> f n
+ | _ -> failwith "marshal_int"
diff --git a/testsuite/tests/regression/pr5233/Makefile b/testsuite/tests/regression/pr5233/Makefile
new file mode 100644
index 0000000000..7c875051ba
--- /dev/null
+++ b/testsuite/tests/regression/pr5233/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+MAIN_MODULE=pr5233
+
+include ../../../makefiles/Makefile.one
+include ../../../makefiles/Makefile.common
diff --git a/testsuite/tests/regression/pr5233/pr5233.ml b/testsuite/tests/regression/pr5233/pr5233.ml
new file mode 100644
index 0000000000..75aec4f935
--- /dev/null
+++ b/testsuite/tests/regression/pr5233/pr5233.ml
@@ -0,0 +1,62 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf;;
+
+(* PR#5233: Create a dangling pointer and use it to access random parts
+ of the heap. *)
+
+(* The buggy weak array will end up in smuggle. *)
+let smuggle = ref (Weak.create 1);;
+
+(* This will be the weak array (W). *)
+let t = ref (Weak.create 1);;
+
+(* Set a finalisation function on W. *)
+Gc.finalise (fun w -> smuggle := w) !t;;
+
+(* Free W and run its finalisation function. *)
+t := Weak.create 1;;
+Gc.full_major ();;
+
+(* smuggle now contains W, whose pointers are not erased, even
+ when the contents is deallocated. *)
+
+let size = 1_000_000;;
+
+let check o =
+ printf "checking...";
+ match o with
+ | None -> printf " no value\n";
+ | Some s ->
+ printf " value found / testing...";
+ for i = 0 to size - 1 do
+ if s.[i] != ' ' then failwith "bad";
+ done;
+ printf " ok\n";
+;;
+
+Weak.set !smuggle 0 (Some (String.make size ' '));;
+
+(* Check the data just to make sure. *)
+check (Weak.get !smuggle 0);;
+
+(* Get a dangling pointer in W. *)
+Gc.full_major ();;
+
+(* Fill the heap with other stuff. *)
+let rec fill n accu = if n = 0 then accu else fill (n-1) (123 :: accu);;
+let r = fill ((Gc.stat ()).Gc.heap_words / 3) [];;
+Gc.minor ();;
+
+(* Now follow the dangling pointer and exhibit the problem. *)
+check (Weak.get !smuggle 0);;
diff --git a/testsuite/tests/regression/pr5233/pr5233.reference b/testsuite/tests/regression/pr5233/pr5233.reference
new file mode 100644
index 0000000000..ef728f633a
--- /dev/null
+++ b/testsuite/tests/regression/pr5233/pr5233.reference
@@ -0,0 +1,2 @@
+checking... value found / testing... ok
+checking... no value
diff --git a/testsuite/tests/regression/pr5757/Makefile b/testsuite/tests/regression/pr5757/Makefile
new file mode 100644
index 0000000000..d0eb05424c
--- /dev/null
+++ b/testsuite/tests/regression/pr5757/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+MAIN_MODULE=pr5757
+
+include ../../../makefiles/Makefile.one
+include ../../../makefiles/Makefile.common
diff --git a/testsuite/tests/regression/pr5757/pr5757.ml b/testsuite/tests/regression/pr5757/pr5757.ml
new file mode 100644
index 0000000000..3a40bb51f9
--- /dev/null
+++ b/testsuite/tests/regression/pr5757/pr5757.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+Random.init 3;;
+for i = 0 to 100_000 do
+ ignore (Bytes.create (Random.int 1_000_000))
+done;;
+Printf.printf "hello world\n";;
diff --git a/testsuite/tests/regression/pr5757/pr5757.reference b/testsuite/tests/regression/pr5757/pr5757.reference
new file mode 100644
index 0000000000..3b18e512db
--- /dev/null
+++ b/testsuite/tests/regression/pr5757/pr5757.reference
@@ -0,0 +1 @@
+hello world
diff --git a/testsuite/tests/regression/pr6024/Makefile b/testsuite/tests/regression/pr6024/Makefile
new file mode 100644
index 0000000000..3426801f57
--- /dev/null
+++ b/testsuite/tests/regression/pr6024/Makefile
@@ -0,0 +1,17 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+MAIN_MODULE=pr6024
+
+BASEDIR=../../..
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/regression/pr6024/pr6024.ml b/testsuite/tests/regression/pr6024/pr6024.ml
new file mode 100644
index 0000000000..b440cb2df7
--- /dev/null
+++ b/testsuite/tests/regression/pr6024/pr6024.ml
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2013 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+Format.printf "@[%@-@@-@]@.";;
diff --git a/testsuite/tests/regression/pr6024/pr6024.reference b/testsuite/tests/regression/pr6024/pr6024.reference
new file mode 100644
index 0000000000..67182723a7
--- /dev/null
+++ b/testsuite/tests/regression/pr6024/pr6024.reference
@@ -0,0 +1 @@
+@-@-
diff --git a/testsuite/tests/runtime-errors/.ignore b/testsuite/tests/runtime-errors/.ignore
new file mode 100644
index 0000000000..fa628eaab6
--- /dev/null
+++ b/testsuite/tests/runtime-errors/.ignore
@@ -0,0 +1 @@
+*.bytecode
diff --git a/testsuite/tests/runtime-errors/Makefile b/testsuite/tests/runtime-errors/Makefile
new file mode 100644
index 0000000000..2c0bed9b63
--- /dev/null
+++ b/testsuite/tests/runtime-errors/Makefile
@@ -0,0 +1,57 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+
+.PHONY: default
+default:
+ $(MAKE) compile
+ $(MAKE) run
+
+.PHONY: compile
+compile:
+ @for f in *.ml; do \
+ F=`basename $$f .ml`; \
+ rm -f $$F.bytecode $$F.native $$F.native.exe; \
+ $(OCAMLC) -w a -o $$F.bytecode $$f; \
+ if $(BYTECODE_ONLY); then : ; else \
+ $(OCAMLOPT) -w a -o $$F.native$(EXE) $$f; \
+ fi; \
+ done
+ @grep -q HAS_STACK_OVERFLOW_DETECTION $(TOPDIR)/config/s.h \
+ || rm -f stackoverflow.native$(EXE)
+
+.PHONY: run
+run:
+ @ulimit -s 1024; \
+ for f in *.bytecode; do \
+ printf " ... testing '$$f':"; \
+ $(OCAMLRUN) ./$$f >$$f.result 2>&1 || true; \
+ DIFF="$(DIFF)" sh $$f.checker \
+ && echo " => passed" || echo " => failed"; \
+ fn=`basename $$f bytecode`native; \
+ if $(BYTECODE_ONLY) || [ ! -f "$${fn}$(EXE)" ] ; then : ; else \
+ printf " ... testing '$$fn':"; \
+ ./$${fn}$(EXE) >$$fn.result 2>&1 || true; \
+ DIFF="$(DIFF)" sh $$fn.checker \
+ && echo " => passed" || echo " => failed"; \
+ fi; \
+ done
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.bytecode *.native *.native.exe *.result
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/runtime-errors/stackoverflow.bytecode.checker b/testsuite/tests/runtime-errors/stackoverflow.bytecode.checker
new file mode 100644
index 0000000000..b4f86ac69d
--- /dev/null
+++ b/testsuite/tests/runtime-errors/stackoverflow.bytecode.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$DIFF stackoverflow.bytecode.reference stackoverflow.bytecode.result
diff --git a/testsuite/tests/runtime-errors/stackoverflow.bytecode.reference b/testsuite/tests/runtime-errors/stackoverflow.bytecode.reference
new file mode 100644
index 0000000000..a5bbdea33c
--- /dev/null
+++ b/testsuite/tests/runtime-errors/stackoverflow.bytecode.reference
@@ -0,0 +1,4 @@
+x = 20000
+x = 10000
+x = 0
+Stack overflow caught
diff --git a/testsuite/tests/runtime-errors/stackoverflow.ml b/testsuite/tests/runtime-errors/stackoverflow.ml
new file mode 100644
index 0000000000..21fe04bd27
--- /dev/null
+++ b/testsuite/tests/runtime-errors/stackoverflow.ml
@@ -0,0 +1,27 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let rec f x =
+ if not (x = 0 || x = 10000 || x = 20000)
+ then 1 + f (x + 1)
+ else
+ try
+ 1 + f (x + 1)
+ with Stack_overflow ->
+ print_string "x = "; print_int x; print_newline();
+ raise Stack_overflow
+
+let _ =
+ try
+ ignore(f 0)
+ with Stack_overflow ->
+ print_string "Stack overflow caught"; print_newline()
diff --git a/testsuite/tests/runtime-errors/stackoverflow.native.checker b/testsuite/tests/runtime-errors/stackoverflow.native.checker
new file mode 100644
index 0000000000..26c2ccf14e
--- /dev/null
+++ b/testsuite/tests/runtime-errors/stackoverflow.native.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$DIFF stackoverflow.native.reference stackoverflow.native.result
diff --git a/testsuite/tests/runtime-errors/stackoverflow.native.reference b/testsuite/tests/runtime-errors/stackoverflow.native.reference
new file mode 100644
index 0000000000..a5bbdea33c
--- /dev/null
+++ b/testsuite/tests/runtime-errors/stackoverflow.native.reference
@@ -0,0 +1,4 @@
+x = 20000
+x = 10000
+x = 0
+Stack overflow caught
diff --git a/testsuite/tests/runtime-errors/syserror.bytecode.checker b/testsuite/tests/runtime-errors/syserror.bytecode.checker
new file mode 100644
index 0000000000..a1cb88a527
--- /dev/null
+++ b/testsuite/tests/runtime-errors/syserror.bytecode.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+grep 'Fatal error: exception Sys_error' syserror.bytecode.result >/dev/null
diff --git a/testsuite/tests/runtime-errors/syserror.bytecode.reference b/testsuite/tests/runtime-errors/syserror.bytecode.reference
new file mode 100644
index 0000000000..3f6219a225
--- /dev/null
+++ b/testsuite/tests/runtime-errors/syserror.bytecode.reference
@@ -0,0 +1 @@
+Fatal error: exception Sys_error("titi:/toto: No such file or directory")
diff --git a/testsuite/tests/runtime-errors/syserror.ml b/testsuite/tests/runtime-errors/syserror.ml
new file mode 100644
index 0000000000..cf16ca0c74
--- /dev/null
+++ b/testsuite/tests/runtime-errors/syserror.ml
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let channel = open_out "titi:/toto"
diff --git a/testsuite/tests/runtime-errors/syserror.native.checker b/testsuite/tests/runtime-errors/syserror.native.checker
new file mode 100644
index 0000000000..5d8ed3c38b
--- /dev/null
+++ b/testsuite/tests/runtime-errors/syserror.native.checker
@@ -0,0 +1,13 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+grep 'Fatal error: exception Sys_error' syserror.native.result >/dev/null
diff --git a/testsuite/tests/runtime-errors/syserror.native.reference b/testsuite/tests/runtime-errors/syserror.native.reference
new file mode 100644
index 0000000000..3f6219a225
--- /dev/null
+++ b/testsuite/tests/runtime-errors/syserror.native.reference
@@ -0,0 +1 @@
+Fatal error: exception Sys_error("titi:/toto: No such file or directory")
diff --git a/testsuite/tests/tool-debugger/basic/.ignore b/testsuite/tests/tool-debugger/basic/.ignore
new file mode 100644
index 0000000000..e09cf9eb6e
--- /dev/null
+++ b/testsuite/tests/tool-debugger/basic/.ignore
@@ -0,0 +1 @@
+compiler-libs
diff --git a/testsuite/tests/tool-debugger/basic/Makefile b/testsuite/tests/tool-debugger/basic/Makefile
new file mode 100644
index 0000000000..3c1713906c
--- /dev/null
+++ b/testsuite/tests/tool-debugger/basic/Makefile
@@ -0,0 +1,58 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, EPI Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../../..
+MAIN_MODULE=debuggee
+ADD_COMPFLAGS=-g -custom
+LD_PATH=$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+
+.PHONY: default
+default:
+ @if ! $(SUPPORTS_SHARED_LIBRARIES); then \
+ echo 'skipped (shared libraries not available)'; \
+ else \
+ $(MAKE) compile; \
+ $(SET_LD_PATH) OCAMLLIB=. $(MAKE) run; \
+ fi
+
+.PHONY: compile
+compile: $(ML_FILES) $(CMO_FILES) $(MAIN_MODULE).cmo
+ @rm -f program.byte program.byte.exe
+ @$(OCAMLC) $(ADD_COMPFLAGS) $(ADD_CFLAGS) -o program.byte$(EXE) \
+ $(O_FILES) $(CMA_FILES) $(CMO_FILES) $(ADD_CMO_FILES) \
+ $(MAIN_MODULE).cmo
+ @mkdir -p compiler-libs
+ @cp $(TOPDIR)/toplevel/topdirs.cmi compiler-libs/
+
+.PHONY: run
+run:
+ @printf " ... testing with ocamlc"
+ @rm -f $(MAIN_MODULE).result
+ @echo 'source input_script' | \
+ $(OCAMLRUN) `$(CYGPATH) $(TOPDIR)/debugger/ocamldebug$(EXE)` \
+ program.byte$(EXE) >$(MAIN_MODULE).raw.result 2>&1 \
+ && sed -e '/Debugger version/d' -e '/^Time:/d' -e '$$d' \
+ $(MAIN_MODULE).raw.result >$(MAIN_MODULE).result \
+ && $(DIFF) $(MAIN_MODULE).reference $(MAIN_MODULE).result >/dev/null \
+ && echo " => passed" || echo " => failed"
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result program.byte program.byte.exe \
+ program.native program.native.exe \
+ $(GENERATED_SOURCES) $(O_FILES) $(TEST_TEMP_FILES)
+ @rm -rf compiler-libs
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/tool-debugger/basic/debuggee.ml b/testsuite/tests/tool-debugger/basic/debuggee.ml
new file mode 100644
index 0000000000..341d0b369f
--- /dev/null
+++ b/testsuite/tests/tool-debugger/basic/debuggee.ml
@@ -0,0 +1,2 @@
+print_endline Sys.argv.(1);;
+print_endline (Sys.getenv "foo");;
diff --git a/testsuite/tests/tool-debugger/basic/debuggee.reference b/testsuite/tests/tool-debugger/basic/debuggee.reference
new file mode 100644
index 0000000000..e998926c3d
--- /dev/null
+++ b/testsuite/tests/tool-debugger/basic/debuggee.reference
@@ -0,0 +1,5 @@
+
+(ocd) Loading program... done.
+arg1
+notbar
+Program exit.
diff --git a/testsuite/tests/tool-debugger/basic/input_script b/testsuite/tests/tool-debugger/basic/input_script
new file mode 100755
index 0000000000..2caf06dd4d
--- /dev/null
+++ b/testsuite/tests/tool-debugger/basic/input_script
@@ -0,0 +1,5 @@
+set arguments arg1 arg2
+environment foo=bar
+environment foo=notbar
+run
+quit
diff --git a/testsuite/tests/tool-debugger/find-artifacts/.ignore b/testsuite/tests/tool-debugger/find-artifacts/.ignore
new file mode 100644
index 0000000000..0a2c0c40cf
--- /dev/null
+++ b/testsuite/tests/tool-debugger/find-artifacts/.ignore
@@ -0,0 +1,2 @@
+compiler-libs
+out
diff --git a/testsuite/tests/tool-debugger/find-artifacts/Makefile b/testsuite/tests/tool-debugger/find-artifacts/Makefile
new file mode 100644
index 0000000000..f313d86424
--- /dev/null
+++ b/testsuite/tests/tool-debugger/find-artifacts/Makefile
@@ -0,0 +1,67 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, EPI Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../../..
+MAIN_MODULE=debuggee
+ADD_COMPFLAGS=-g -custom
+LD_PATH=$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+
+.PHONY: default
+default:
+ @if ! $(SUPPORTS_SHARED_LIBRARIES); then \
+ echo 'skipped (shared libraries not available)'; \
+ else \
+ $(MAKE) compile; \
+ $(SET_LD_PATH) OCAMLLIB=. $(MAKE) run; \
+ fi
+
+.PHONY: compile
+compile: $(ML_FILES) $(CMO_FILES)
+ @rm -rf out
+ @rm -f program.byte program.byte.exe
+ @mkdir out
+ @$(OCAMLC) $(ADD_COMPFLAGS) $(ADD_CFLAGS) -o out/blah.cmo -c \
+ $(O_FILES) $(CMA_FILES) $(CMO_FILES) $(ADD_CMO_FILES) \
+ in/blah.ml
+ @$(OCAMLC) $(ADD_COMPFLAGS) $(ADD_CFLAGS) -o out/foo.cmo -c \
+ $(O_FILES) $(CMA_FILES) $(CMO_FILES) $(ADD_CMO_FILES) \
+ -I out in/foo.ml
+ @$(OCAMLC) $(ADD_COMPFLAGS) $(ADD_CFLAGS) -o program.byte$(EXE) \
+ $(O_FILES) $(CMA_FILES) $(CMO_FILES) $(ADD_CMO_FILES) \
+ out/blah.cmo out/foo.cmo
+ @mkdir -p compiler-libs
+ @cp $(TOPDIR)/toplevel/topdirs.cmi compiler-libs/
+
+.PHONY: run
+run:
+ @printf " ... testing with ocamlc"
+ @rm -f $(MAIN_MODULE).result
+ @echo 'source input_script' | \
+ $(OCAMLRUN) `$(CYGPATH) $(TOPDIR)/debugger/ocamldebug$(EXE)` \
+ program.byte$(EXE) >$(MAIN_MODULE).raw.result 2>&1 \
+ && sed -e '/Debugger version/d' -e '/^Time:/d' \
+ -e '/Breakpoint [0-9]* at [0-9]*:/d' -e '$$d' \
+ $(MAIN_MODULE).raw.result >$(MAIN_MODULE).result \
+ && $(DIFF) $(MAIN_MODULE).reference $(MAIN_MODULE).result >/dev/null \
+ && echo " => passed" || echo " => failed"
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result program.byte program.byte.exe \
+ program.native program.native.exe \
+ $(GENERATED_SOURCES) $(O_FILES) $(TEST_TEMP_FILES)
+ @rm -rf compiler-libs out
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/tool-debugger/find-artifacts/debuggee.reference b/testsuite/tests/tool-debugger/find-artifacts/debuggee.reference
new file mode 100644
index 0000000000..06564f90bb
--- /dev/null
+++ b/testsuite/tests/tool-debugger/find-artifacts/debuggee.reference
@@ -0,0 +1,6 @@
+
+(ocd) Loading program... done.
+Breakpoint: 1
+10 <|b|>print x;
+x: Blah.blah = Foo
+y: Blah.blah = Bar "hi"
diff --git a/testsuite/tests/tool-debugger/find-artifacts/in/blah.ml b/testsuite/tests/tool-debugger/find-artifacts/in/blah.ml
new file mode 100644
index 0000000000..462c07b2e1
--- /dev/null
+++ b/testsuite/tests/tool-debugger/find-artifacts/in/blah.ml
@@ -0,0 +1,3 @@
+type blah =
+ | Foo
+ | Bar of string
diff --git a/testsuite/tests/tool-debugger/find-artifacts/in/foo.ml b/testsuite/tests/tool-debugger/find-artifacts/in/foo.ml
new file mode 100644
index 0000000000..8d992673be
--- /dev/null
+++ b/testsuite/tests/tool-debugger/find-artifacts/in/foo.ml
@@ -0,0 +1,13 @@
+open Blah
+
+let print = function
+ | Foo -> print_endline "Foo";
+ | Bar s -> print_endline ("Bar(" ^ s ^ ")")
+
+let main () =
+ let x = Foo in
+ let y = Bar "hi" in
+ print x;
+ print y
+
+let _ = main ()
diff --git a/testsuite/tests/tool-debugger/find-artifacts/input_script b/testsuite/tests/tool-debugger/find-artifacts/input_script
new file mode 100644
index 0000000000..4b907c5ae6
--- /dev/null
+++ b/testsuite/tests/tool-debugger/find-artifacts/input_script
@@ -0,0 +1,5 @@
+break @ Foo 10
+run
+print x
+print y
+quit
diff --git a/testsuite/tests/tool-debugger/no_debug_event/.ignore b/testsuite/tests/tool-debugger/no_debug_event/.ignore
new file mode 100644
index 0000000000..cfbcf5c6d3
--- /dev/null
+++ b/testsuite/tests/tool-debugger/no_debug_event/.ignore
@@ -0,0 +1,4 @@
+compiler-libs
+out
+c
+c.exe
diff --git a/testsuite/tests/tool-debugger/no_debug_event/Makefile b/testsuite/tests/tool-debugger/no_debug_event/Makefile
new file mode 100644
index 0000000000..c9a08d256b
--- /dev/null
+++ b/testsuite/tests/tool-debugger/no_debug_event/Makefile
@@ -0,0 +1,57 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, EPI Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2013 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../../..
+ADD_COMPFLAGS=-g -custom
+LD_PATH=$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix
+
+.PHONY: default
+default:
+ @if ! $(SUPPORTS_SHARED_LIBRARIES); then \
+ echo 'skipped (shared libraries not available)'; \
+ else \
+ $(MAKE) compile; \
+ $(SET_LD_PATH) OCAMLLIB=. $(MAKE) run; \
+ fi
+
+.PHONY: compile
+compile: $(ML_FILES) $(CMO_FILES)
+ @rm -f c$(EXE)
+ @$(OCAMLC) $(ADD_COMPFLAGS) -c a.ml -for-pack foo
+ @$(OCAMLC) $(ADD_COMPFLAGS) a.cmo -pack -o foo.cmo
+ @$(OCAMLC) $(ADD_COMPFLAGS) -c b.ml
+ @$(OCAMLC) $(ADD_COMPFLAGS) foo.cmo b.cmo -o c$(EXE)
+ @mkdir -p compiler-libs
+ @cp $(TOPDIR)/toplevel/topdirs.cmi compiler-libs/
+
+.PHONY: run
+run:
+ @printf " ... testing with ocamlc"
+ @rm -f noev.result
+ @echo 'source input_script' | \
+ $(OCAMLRUN) `$(CYGPATH) $(TOPDIR)/debugger/ocamldebug$(EXE)` \
+ c$(EXE) >noev.raw.result 2>&1 \
+ && sed -e '/Debugger version/d' -e '/^Time:/d' \
+ -e '/Breakpoint [0-9]* at [0-9]*:/d' -e '$$d' \
+ noev.raw.result >noev.result \
+ && $(DIFF) noev.reference noev.result >/dev/null \
+ && echo " => passed" || echo " => failed"
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result *.cm* c$(EXE)
+ @rm -rf compiler-libs
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/tool-debugger/no_debug_event/a.ml b/testsuite/tests/tool-debugger/no_debug_event/a.ml
new file mode 100644
index 0000000000..0547b3d0ee
--- /dev/null
+++ b/testsuite/tests/tool-debugger/no_debug_event/a.ml
@@ -0,0 +1 @@
+let x = 1
diff --git a/testsuite/tests/tool-debugger/no_debug_event/b.ml b/testsuite/tests/tool-debugger/no_debug_event/b.ml
new file mode 100644
index 0000000000..83502097a9
--- /dev/null
+++ b/testsuite/tests/tool-debugger/no_debug_event/b.ml
@@ -0,0 +1,3 @@
+let () =
+ print_int Foo.A.x;
+ print_newline ()
diff --git a/testsuite/tests/tool-debugger/no_debug_event/input_script b/testsuite/tests/tool-debugger/no_debug_event/input_script
new file mode 100644
index 0000000000..58afc787f5
--- /dev/null
+++ b/testsuite/tests/tool-debugger/no_debug_event/input_script
@@ -0,0 +1,2 @@
+run
+quit
diff --git a/testsuite/tests/tool-debugger/no_debug_event/noev.reference b/testsuite/tests/tool-debugger/no_debug_event/noev.reference
new file mode 100644
index 0000000000..d4a69fc90e
--- /dev/null
+++ b/testsuite/tests/tool-debugger/no_debug_event/noev.reference
@@ -0,0 +1,4 @@
+
+(ocd) Loading program... done.
+1
+Program exit.
diff --git a/testsuite/tests/tool-lexyacc/.ignore b/testsuite/tests/tool-lexyacc/.ignore
new file mode 100644
index 0000000000..6bcc85147e
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/.ignore
@@ -0,0 +1,3 @@
+scanner.ml
+grammar.mli
+grammar.ml
diff --git a/testsuite/tests/tool-lexyacc/Makefile b/testsuite/tests/tool-lexyacc/Makefile
new file mode 100644
index 0000000000..082db4dc12
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/Makefile
@@ -0,0 +1,22 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=syntax gram_aux grammar scan_aux scanner lexgen output
+MAIN_MODULE=main
+LEX_MODULES=scanner
+YACC_MODULES=grammar
+ADD_COMPFLAGS=-w a
+EXEC_ARGS=input
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/tool-lexyacc/gram_aux.ml b/testsuite/tests/tool-lexyacc/gram_aux.ml
new file mode 100644
index 0000000000..255f58f3ed
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/gram_aux.ml
@@ -0,0 +1,44 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliaries for the parser. *)
+
+open Syntax
+
+let regexp_for_string s =
+ let l = String.length s in
+ if l = 0 then
+ Epsilon
+ else begin
+ let re = ref(Characters [String.get s (l - 1)]) in
+ for i = l - 2 downto 0 do
+ re := Sequence(Characters [String.get s i], !re)
+ done;
+ !re
+ end
+
+
+let char_class c1 c2 =
+ let cl = ref [] in
+ for i = Char.code c2 downto Char.code c1 do
+ cl := Char.chr i :: !cl
+ done;
+ !cl
+
+
+let all_chars = char_class '\001' '\255'
+
+
+let rec subtract l1 l2 =
+ match l1 with
+ [] -> []
+ | a::l -> if List.mem a l2 then subtract l l2 else a :: subtract l l2
diff --git a/testsuite/tests/tool-lexyacc/grammar.mly b/testsuite/tests/tool-lexyacc/grammar.mly
new file mode 100644
index 0000000000..a182136761
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/grammar.mly
@@ -0,0 +1,111 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* The grammar for lexer definitions */
+
+%{
+open Syntax
+open Gram_aux
+%}
+
+%token <string> Tident
+%token <char> Tchar
+%token <string> Tstring
+%token <Syntax.location> Taction
+%token Trule Tparse Tand Tequal Tend Tor Tunderscore Teof Tlbracket Trbracket
+%token Tstar Tmaybe Tplus Tlparen Trparen Tcaret Tdash
+
+%left Tor
+%left CONCAT
+%nonassoc Tmaybe
+%left Tstar
+%left Tplus
+
+%start lexer_definition
+%type <Syntax.lexer_definition> lexer_definition
+
+%%
+
+lexer_definition:
+ header Trule definition other_definitions Tend
+ { Lexdef($1, $3::(List.rev $4)) }
+;
+header:
+ Taction
+ { $1 }
+ |
+ { Location(0,0) }
+;
+other_definitions:
+ other_definitions Tand definition
+ { $3::$1 }
+ |
+ { [] }
+;
+definition:
+ Tident Tequal entry
+ { ($1,$3) }
+;
+entry:
+ Tparse case rest_of_entry
+ { $2 :: List.rev $3 }
+;
+rest_of_entry:
+ rest_of_entry Tor case
+ { $3::$1 }
+ |
+ { [] }
+;
+case:
+ regexp Taction
+ { ($1,$2) }
+;
+regexp:
+ Tunderscore
+ { Characters all_chars }
+ | Teof
+ { Characters ['\000'] }
+ | Tchar
+ { Characters [$1] }
+ | Tstring
+ { regexp_for_string $1 }
+ | Tlbracket char_class Trbracket
+ { Characters $2 }
+ | regexp Tstar
+ { Repetition $1 }
+ | regexp Tmaybe
+ { Alternative($1, Epsilon) }
+ | regexp Tplus
+ { Sequence($1, Repetition $1) }
+ | regexp Tor regexp
+ { Alternative($1,$3) }
+ | regexp regexp %prec CONCAT
+ { Sequence($1,$2) }
+ | Tlparen regexp Trparen
+ { $2 }
+;
+char_class:
+ Tcaret char_class1
+ { subtract all_chars $2 }
+ | char_class1
+ { $1 }
+;
+char_class1:
+ Tchar Tdash Tchar
+ { char_class $1 $3 }
+ | Tchar
+ { [$1] }
+ | char_class char_class %prec CONCAT
+ { $1 @ $2 }
+;
+
+%%
diff --git a/testsuite/tests/tool-lexyacc/input b/testsuite/tests/tool-lexyacc/input
new file mode 100644
index 0000000000..c0d7859456
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/input
@@ -0,0 +1,131 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexical analyzer for lexer definitions. *)
+
+{
+open Syntax
+open Grammar
+open Scan_aux
+}
+
+rule main = parse
+ [' ' '\010' '\013' '\009' ] +
+ { main lexbuf }
+ | "(*"
+ { comment_depth := 1;
+ comment lexbuf;
+ main lexbuf }
+ | (['A'-'Z' 'a'-'z'] | '_' ['A'-'Z' 'a'-'z' '\'' '0'-'9'])
+ ( '_' ? ['A'-'Z' 'a'-'z' ''' '0'-'9'] ) *
+ { match Lexing.lexeme lexbuf with
+ "rule" -> Trule
+ | "parse" -> Tparse
+ | "and" -> Tand
+ | "eof" -> Teof
+ | s -> Tident s }
+ | '"'
+ { reset_string_buffer();
+ string lexbuf;
+ Tstring(get_stored_string()) }
+ | "'"
+ { Tchar(char lexbuf) }
+ | '{'
+ { let n1 = Lexing.lexeme_end lexbuf in
+ brace_depth := 1;
+ let n2 = action lexbuf in
+ Taction(Location(n1, n2)) }
+ | '=' { Tequal }
+ | ";;" { Tend }
+ | '|' { Tor }
+ | '_' { Tunderscore }
+ | "eof" { Teof }
+ | '[' { Tlbracket }
+ | ']' { Trbracket }
+ | '*' { Tstar }
+ | '?' { Tmaybe }
+ | '+' { Tplus }
+ | '(' { Tlparen }
+ | ')' { Trparen }
+ | '^' { Tcaret }
+ | '-' { Tdash }
+ | eof
+ { raise(Lexical_error "unterminated lexer definition") }
+ | _
+ { raise(Lexical_error("illegal character " ^ Lexing.lexeme lexbuf)) }
+
+and action = parse
+ '{'
+ { incr brace_depth;
+ action lexbuf }
+ | '}'
+ { decr brace_depth;
+ if !brace_depth = 0 then Lexing.lexeme_start lexbuf else action lexbuf }
+ | '"'
+ { reset_string_buffer();
+ string lexbuf;
+ reset_string_buffer();
+ action lexbuf }
+ | '\''
+ { let _ = char lexbuf in action lexbuf }
+ | "(*"
+ { comment_depth := 1;
+ comment lexbuf;
+ action lexbuf }
+ | eof
+ { raise (Lexical_error "unterminated action") }
+ | _
+ { action lexbuf }
+
+and string = parse
+ '"'
+ { () }
+ | '\\' [' ' '\010' '\013' '\009' '\026' '\012'] +
+ { string lexbuf }
+ | '\\' ['\\' '"' 'n' 't' 'b' 'r']
+ { store_string_char(char_for_backslash(Lexing.lexeme_char lexbuf 1));
+ string lexbuf }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9']
+ { store_string_char(char_for_decimal_code lexbuf 1);
+ string lexbuf }
+ | eof
+ { raise(Lexical_error "unterminated string") }
+ | _
+ { store_string_char(Lexing.lexeme_char lexbuf 0);
+ string lexbuf }
+
+and char = parse
+ [^ '\\'] "'"
+ { Lexing.lexeme_char lexbuf 0 }
+ | '\\' ['\\' '\'' 'n' 't' 'b' 'r'] "'"
+ { char_for_backslash (Lexing.lexeme_char lexbuf 1) }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
+ { char_for_decimal_code lexbuf 1 }
+ | _
+ { raise(Lexical_error "bad character constant") }
+
+and comment = parse
+ "(*"
+ { incr comment_depth; comment lexbuf }
+ | "*)"
+ { decr comment_depth;
+ if !comment_depth = 0 then () else comment lexbuf }
+ | '"'
+ { reset_string_buffer();
+ string lexbuf;
+ reset_string_buffer();
+ comment lexbuf }
+ | eof
+ { raise(Lexical_error "unterminated comment") }
+ | _
+ { comment lexbuf }
+;;
diff --git a/testsuite/tests/tool-lexyacc/lexgen.ml b/testsuite/tests/tool-lexyacc/lexgen.ml
new file mode 100644
index 0000000000..005ea68d9b
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/lexgen.ml
@@ -0,0 +1,268 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compiling a lexer definition *)
+
+open Syntax
+
+(* Deep abstract syntax for regular expressions *)
+
+type regexp =
+ Empty
+ | Chars of int
+ | Action of int
+ | Seq of regexp * regexp
+ | Alt of regexp * regexp
+ | Star of regexp
+
+(* From shallow to deep syntax *)
+
+(***
+
+let print_char_class c =
+ let print_interval low high =
+ prerr_int low;
+ if high - 1 > low then begin
+ prerr_char '-';
+ prerr_int (high-1)
+ end;
+ prerr_char ' ' in
+ let rec print_class first next = function
+ [] -> print_interval first next
+ | c::l ->
+ if char.code c = next
+ then print_class first (next+1) l
+ else begin
+ print_interval first next;
+ print_class (char.code c) (char.code c + 1) l
+ end in
+ match c with
+ [] -> prerr_newline()
+ | c::l -> print_class (char.code c) (char.code c + 1) l; prerr_newline()
+
+
+let rec print_regexp = function
+ Empty -> prerr_string "Empty"
+ | Chars n -> prerr_string "Chars "; prerr_int n
+ | Action n -> prerr_string "Action "; prerr_int n
+ | Seq(r1,r2) -> print_regexp r1; prerr_string "; "; print_regexp r2
+ | Alt(r1,r2) ->
+ prerr_string "("; print_regexp r1; prerr_string " | "; print_regexp r2;
+ prerr_string ")"
+ | Star r -> prerr_string "("; print_regexp r; prerr_string ")*"
+
+***)
+
+let chars = ref ([] : char list list)
+let chars_count = ref 0
+let actions = ref ([] : (int * location) list)
+let actions_count = ref 0
+
+let rec encode_regexp = function
+ Epsilon -> Empty
+ | Characters cl ->
+ let n = !chars_count in
+(*** prerr_int n; prerr_char ' '; print_char_class cl; ***)
+ chars := cl :: !chars;
+ chars_count := !chars_count + 1;
+ Chars(n)
+ | Sequence(r1,r2) ->
+ Seq(encode_regexp r1, encode_regexp r2)
+ | Alternative(r1,r2) ->
+ Alt(encode_regexp r1, encode_regexp r2)
+ | Repetition r ->
+ Star (encode_regexp r)
+
+
+let encode_casedef =
+ List.fold_left
+ (fun reg (expr,act) ->
+ let act_num = !actions_count in
+ actions_count := !actions_count + 1;
+ actions := (act_num, act) :: !actions;
+ Alt(reg, Seq(encode_regexp expr, Action act_num)))
+ Empty
+
+
+let encode_lexdef (Lexdef(_, ld)) =
+ chars := [];
+ chars_count := 0;
+ actions := [];
+ actions_count := 0;
+ let name_regexp_list =
+ List.map (fun (name, casedef) -> (name, encode_casedef casedef)) ld in
+(* List.iter print_char_class chars; *)
+ let chr = Array.of_list (List.rev !chars)
+ and act = !actions in
+ chars := [];
+ actions := [];
+ (chr, name_regexp_list, act)
+
+
+(* To generate directly a NFA from a regular expression.
+ Confer Aho-Sethi-Ullman, dragon book, chap. 3 *)
+
+type transition =
+ OnChars of int
+ | ToAction of int
+
+
+let rec merge_trans l1 l2 =
+ match (l1, l2) with
+ ([], s2) -> s2
+ | (s1, []) -> s1
+ | ((OnChars n1 as t1) :: r1 as s1), ((OnChars n2 as t2) :: r2 as s2) ->
+ if n1 = n2 then t1 :: merge_trans r1 r2 else
+ if n1 < n2 then t1 :: merge_trans r1 s2 else
+ t2 :: merge_trans s1 r2
+ | ((ToAction n1 as t1) :: r1 as s1), ((ToAction n2 as t2) :: r2 as s2) ->
+ if n1 = n2 then t1 :: merge_trans r1 r2 else
+ if n1 < n2 then t1 :: merge_trans r1 s2 else
+ t2 :: merge_trans s1 r2
+ | ((OnChars n1 as t1) :: r1), ((ToAction n2) :: r2 as s2) ->
+ t1 :: merge_trans r1 s2
+ | ((ToAction n1) :: r1 as s1), ((OnChars n2 as t2) :: r2) ->
+ t2 :: merge_trans s1 r2
+
+
+let rec nullable = function
+ Empty -> true
+ | Chars _ -> false
+ | Action _ -> false
+ | Seq(r1,r2) -> nullable r1 && nullable r2
+ | Alt(r1,r2) -> nullable r1 || nullable r2
+ | Star r -> true
+
+
+let rec firstpos = function
+ Empty -> []
+ | Chars pos -> [OnChars pos]
+ | Action act -> [ToAction act]
+ | Seq(r1,r2) -> if nullable r1
+ then merge_trans (firstpos r1) (firstpos r2)
+ else firstpos r1
+ | Alt(r1,r2) -> merge_trans (firstpos r1) (firstpos r2)
+ | Star r -> firstpos r
+
+
+let rec lastpos = function
+ Empty -> []
+ | Chars pos -> [OnChars pos]
+ | Action act -> [ToAction act]
+ | Seq(r1,r2) -> if nullable r2
+ then merge_trans (lastpos r1) (lastpos r2)
+ else lastpos r2
+ | Alt(r1,r2) -> merge_trans (lastpos r1) (lastpos r2)
+ | Star r -> lastpos r
+
+
+let followpos size name_regexp_list =
+ let v = Array.make size [] in
+ let fill_pos first = function
+ OnChars pos -> v.(pos) <- merge_trans first v.(pos); ()
+ | ToAction _ -> () in
+ let rec fill = function
+ Seq(r1,r2) ->
+ fill r1; fill r2;
+ List.iter (fill_pos (firstpos r2)) (lastpos r1)
+ | Alt(r1,r2) ->
+ fill r1; fill r2
+ | Star r ->
+ fill r;
+ List.iter (fill_pos (firstpos r)) (lastpos r)
+ | _ -> () in
+ List.iter (fun (name, regexp) -> fill regexp) name_regexp_list;
+ v
+
+
+let no_action = 0x3FFFFFFF
+
+let split_trans_set =
+ List.fold_left
+ (fun (act, pos_set as act_pos_set) trans ->
+ match trans with
+ OnChars pos -> (act, pos :: pos_set)
+ | ToAction act1 -> if act1 < act then (act1, pos_set)
+ else act_pos_set)
+ (no_action, [])
+
+
+let memory = (Hashtbl.create 131 : (transition list, int) Hashtbl.t)
+let todo = ref ([] : (transition list * int) list)
+let next = ref 0
+
+let get_state st =
+ try
+ Hashtbl.find memory st
+ with Not_found ->
+ let nbr = !next in
+ next := !next + 1;
+ Hashtbl.add memory st nbr;
+ todo := (st, nbr) :: !todo;
+ nbr
+
+let rec map_on_states f =
+ match !todo with
+ [] -> []
+ | (st,i)::r -> todo := r; let res = f st in (res,i) :: map_on_states f
+
+let number_of_states () = !next
+
+let goto_state = function
+ [] -> Backtrack
+ | ps -> Goto (get_state ps)
+
+
+let transition_from chars follow pos_set =
+ let tr = Array.make 256 []
+ and shift = Array.make 256 Backtrack in
+ List.iter
+ (fun pos ->
+ List.iter
+ (fun c ->
+ tr.(Char.code c) <-
+ merge_trans tr.(Char.code c) follow.(pos))
+ chars.(pos))
+ pos_set;
+ for i = 0 to 255 do
+ shift.(i) <- goto_state tr.(i)
+ done;
+ shift
+
+
+let translate_state chars follow state =
+ match split_trans_set state with
+ n, [] -> Perform n
+ | n, ps -> Shift( (if n = no_action then No_remember else Remember n),
+ transition_from chars follow ps)
+
+
+let make_dfa lexdef =
+ let (chars, name_regexp_list, actions) =
+ encode_lexdef lexdef in
+(**
+ List.iter (fun (name, regexp) ->
+ prerr_string name; prerr_string " = "; print_regexp regexp;
+ prerr_newline())
+ name_regexp_list;
+**)
+ let follow =
+ followpos (Array.length chars) name_regexp_list in
+ let initial_states =
+ List.map (fun (name, regexp) -> (name, get_state(firstpos regexp)))
+ name_regexp_list in
+ let states =
+ map_on_states (translate_state chars follow) in
+ let v =
+ Array.make (number_of_states()) (Perform 0) in
+ List.iter (fun (auto, i) -> v.(i) <- auto) states;
+ (initial_states, v, actions)
diff --git a/testsuite/tests/tool-lexyacc/main.ml b/testsuite/tests/tool-lexyacc/main.ml
new file mode 100644
index 0000000000..529eb12d70
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/main.ml
@@ -0,0 +1,117 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexer generator. Command-line parsing. *)
+
+open Syntax
+open Scanner
+open Grammar
+open Lexgen
+open Output
+
+let main () =
+ if Array.length Sys.argv <> 2 then begin
+ prerr_string "Usage: camllex <input file>\n";
+ exit 2
+ end;
+ let source_name = Sys.argv.(1) in
+ let dest_name =
+ if Filename.check_suffix source_name ".mll" then
+ Filename.chop_suffix source_name ".mll" ^ ".ml"
+ else
+ source_name ^ ".ml" in
+ ic := open_in source_name;
+(* oc := open_out dest_name; *) ignore dest_name;
+ oc := stdout;
+ let lexbuf = Lexing.from_channel !ic in
+ let (Lexdef(header,_) as def) =
+ try
+ Grammar.lexer_definition Scanner.main lexbuf
+ with
+ Parsing.Parse_error ->
+ prerr_string "Syntax error around char ";
+ prerr_int (Lexing.lexeme_start lexbuf);
+ prerr_endline ".";
+ exit 2
+ | Scan_aux.Lexical_error s ->
+ prerr_string "Lexical error around char ";
+ prerr_int (Lexing.lexeme_start lexbuf);
+ prerr_string ": ";
+ prerr_string s;
+ prerr_endline ".";
+ exit 2 in
+ let ((init, states, acts) as dfa) = make_dfa def in
+ output_lexdef header dfa;
+ close_in !ic;
+ close_out !oc
+
+let _ = main(); exit 0
+
+
+(*****
+let main () =
+ ic := stdin;
+ oc := stdout;
+ let lexbuf = lexing.from_channel ic in
+ let (Lexdef(header,_) as def) =
+ try
+ grammar.lexer_definition scanner.main lexbuf
+ with
+ parsing.Parse_error x ->
+ prerr_string "Syntax error around char ";
+ prerr_int (lexing.lexeme_start lexbuf);
+ prerr_endline ".";
+ sys.exit 2
+ | scan_aux.Lexical_error s ->
+ prerr_string "Lexical error around char ";
+ prerr_int (lexing.lexeme_start lexbuf);
+ prerr_string ": ";
+ prerr_string s;
+ prerr_endline ".";
+ sys.exit 2 in
+ let ((init, states, acts) as dfa) = make_dfa def in
+ output_lexdef header dfa
+
+****)
+
+(****
+let debug_scanner lexbuf =
+ let tok = scanner.main lexbuf in
+ begin match tok with
+ Tident s -> prerr_string "Tident "; prerr_string s
+ | Tchar c -> prerr_string "Tchar "; prerr_char c
+ | Tstring s -> prerr_string "Tstring "; prerr_string s
+ | Taction(Location(i1,i2)) ->
+ prerr_string "Taction "; prerr_int i1; prerr_string "-";
+ prerr_int i2
+ | Trule -> prerr_string "Trule"
+ | Tparse -> prerr_string "Tparse"
+ | Tand -> prerr_string "Tand"
+ | Tequal -> prerr_string "Tequal"
+ | Tend -> prerr_string "Tend"
+ | Tor -> prerr_string "Tor"
+ | Tunderscore -> prerr_string "Tunderscore"
+ | Teof -> prerr_string "Teof"
+ | Tlbracket -> prerr_string "Tlbracket"
+ | Trbracket -> prerr_string "Trbracket"
+ | Tstar -> prerr_string "Tstar"
+ | Tmaybe -> prerr_string "Tmaybe"
+ | Tplus -> prerr_string "Tplus"
+ | Tlparen -> prerr_string "Tlparen"
+ | Trparen -> prerr_string "Trparen"
+ | Tcaret -> prerr_string "Tcaret"
+ | Tdash -> prerr_string "Tdash"
+ end;
+ prerr_newline();
+ tok
+
+****)
diff --git a/testsuite/tests/tool-lexyacc/main.reference b/testsuite/tests/tool-lexyacc/main.reference
new file mode 100644
index 0000000000..f3dac42291
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/main.reference
@@ -0,0 +1,312 @@
+66 states, 44 actions.
+
+open Syntax
+open Grammar
+open Scan_aux
+
+let rec action_43 lexbuf = (
+ comment lexbuf )
+and action_42 lexbuf = (
+ raise(Lexical_error "unterminated comment") )
+and action_41 lexbuf = (
+ reset_string_buffer();
+ string lexbuf;
+ reset_string_buffer();
+ comment lexbuf )
+and action_40 lexbuf = (
+ decr comment_depth;
+ if !comment_depth = 0 then () else comment lexbuf )
+and action_39 lexbuf = (
+ incr comment_depth; comment lexbuf )
+and action_38 lexbuf = (
+ raise(Lexical_error "bad character constant") )
+and action_37 lexbuf = (
+ char_for_decimal_code lexbuf 1 )
+and action_36 lexbuf = (
+ char_for_backslash (Lexing.lexeme_char lexbuf 1) )
+and action_35 lexbuf = (
+ Lexing.lexeme_char lexbuf 0 )
+and action_34 lexbuf = (
+ store_string_char(Lexing.lexeme_char lexbuf 0);
+ string lexbuf )
+and action_33 lexbuf = (
+ raise(Lexical_error "unterminated string") )
+and action_32 lexbuf = (
+ store_string_char(char_for_decimal_code lexbuf 1);
+ string lexbuf )
+and action_31 lexbuf = (
+ store_string_char(char_for_backslash(Lexing.lexeme_char lexbuf 1));
+ string lexbuf )
+and action_30 lexbuf = (
+ string lexbuf )
+and action_29 lexbuf = (
+ () )
+and action_28 lexbuf = (
+ action lexbuf )
+and action_27 lexbuf = (
+ raise (Lexical_error "unterminated action") )
+and action_26 lexbuf = (
+ comment_depth := 1;
+ comment lexbuf;
+ action lexbuf )
+and action_25 lexbuf = (
+ let _ = char lexbuf in action lexbuf )
+and action_24 lexbuf = (
+ reset_string_buffer();
+ string lexbuf;
+ reset_string_buffer();
+ action lexbuf )
+and action_23 lexbuf = (
+ decr brace_depth;
+ if !brace_depth = 0 then Lexing.lexeme_start lexbuf else action lexbuf )
+and action_22 lexbuf = (
+ incr brace_depth;
+ action lexbuf )
+and action_21 lexbuf = (
+ raise(Lexical_error("illegal character " ^ Lexing.lexeme lexbuf)) )
+and action_20 lexbuf = (
+ raise(Lexical_error "unterminated lexer definition") )
+and action_19 lexbuf = (
+ Tdash )
+and action_18 lexbuf = (
+ Tcaret )
+and action_17 lexbuf = (
+ Trparen )
+and action_16 lexbuf = (
+ Tlparen )
+and action_15 lexbuf = (
+ Tplus )
+and action_14 lexbuf = (
+ Tmaybe )
+and action_13 lexbuf = (
+ Tstar )
+and action_12 lexbuf = (
+ Trbracket )
+and action_11 lexbuf = (
+ Tlbracket )
+and action_10 lexbuf = (
+ Teof )
+and action_9 lexbuf = (
+ Tunderscore )
+and action_8 lexbuf = (
+ Tor )
+and action_7 lexbuf = (
+ Tend )
+and action_6 lexbuf = (
+ Tequal )
+and action_5 lexbuf = (
+ let n1 = Lexing.lexeme_end lexbuf in
+ brace_depth := 1;
+ let n2 = action lexbuf in
+ Taction(Location(n1, n2)) )
+and action_4 lexbuf = (
+ Tchar(char lexbuf) )
+and action_3 lexbuf = (
+ reset_string_buffer();
+ string lexbuf;
+ Tstring(get_stored_string()) )
+and action_2 lexbuf = (
+ match Lexing.lexeme lexbuf with
+ "rule" -> Trule
+ | "parse" -> Tparse
+ | "and" -> Tand
+ | "eof" -> Teof
+ | s -> Tident s )
+and action_1 lexbuf = (
+ comment_depth := 1;
+ comment lexbuf;
+ main lexbuf )
+and action_0 lexbuf = (
+ main lexbuf )
+and state_0 lexbuf =
+ match lexing.next_char lexbuf with
+ 'z'|'y'|'x'|'w'|'v'|'u'|'t'|'s'|'r'|'q'|'p'|'o'|'n'|'m'|'l'|'k'|'j'|'i'|'h'|'g'|'f'|'d'|'c'|'b'|'a'|'Z'|'Y'|'X'|'W'|'V'|'U'|'T'|'S'|'R'|'Q'|'P'|'O'|'N'|'M'|'L'|'K'|'J'|'I'|'H'|'G'|'F'|'E'|'D'|'C'|'B'|'A' -> state_51 lexbuf
+ | ' '|'\013'|'\n'|'\t' -> state_40 lexbuf
+ | '|' -> action_8 lexbuf
+ | '{' -> action_5 lexbuf
+ | 'e' -> state_56 lexbuf
+ | '_' -> state_55 lexbuf
+ | '^' -> action_18 lexbuf
+ | ']' -> action_12 lexbuf
+ | '[' -> action_11 lexbuf
+ | '?' -> action_14 lexbuf
+ | '=' -> action_6 lexbuf
+ | ';' -> state_48 lexbuf
+ | '-' -> action_19 lexbuf
+ | '+' -> action_15 lexbuf
+ | '*' -> action_13 lexbuf
+ | ')' -> action_17 lexbuf
+ | '(' -> state_43 lexbuf
+ | '\'' -> action_4 lexbuf
+ | '"' -> action_3 lexbuf
+ | '\000' -> action_20 lexbuf
+ | _ -> action_21 lexbuf
+and state_1 lexbuf =
+ match lexing.next_char lexbuf with
+ '}' -> action_23 lexbuf
+ | '{' -> action_22 lexbuf
+ | '(' -> state_34 lexbuf
+ | '\'' -> action_25 lexbuf
+ | '"' -> action_24 lexbuf
+ | '\000' -> action_27 lexbuf
+ | _ -> action_28 lexbuf
+and state_2 lexbuf =
+ match lexing.next_char lexbuf with
+ '\\' -> state_24 lexbuf
+ | '"' -> action_29 lexbuf
+ | '\000' -> action_33 lexbuf
+ | _ -> action_34 lexbuf
+and state_3 lexbuf =
+ match lexing.next_char lexbuf with
+ '\\' -> state_13 lexbuf
+ | '\000' -> lexing.backtrack lexbuf
+ | _ -> state_12 lexbuf
+and state_4 lexbuf =
+ match lexing.next_char lexbuf with
+ '*' -> state_9 lexbuf
+ | '(' -> state_8 lexbuf
+ | '"' -> action_41 lexbuf
+ | '\000' -> action_42 lexbuf
+ | _ -> action_43 lexbuf
+and state_8 lexbuf =
+ Lexing.set_backtrack lexbuf action_43;
+ match lexing.next_char lexbuf with
+ '*' -> action_39 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_9 lexbuf =
+ Lexing.set_backtrack lexbuf action_43;
+ match lexing.next_char lexbuf with
+ ')' -> action_40 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_12 lexbuf =
+ Lexing.set_backtrack lexbuf action_38;
+ match lexing.next_char lexbuf with
+ '\'' -> action_35 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_13 lexbuf =
+ Lexing.set_backtrack lexbuf action_38;
+ match lexing.next_char lexbuf with
+ '9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0' -> state_15 lexbuf
+ | 't'|'r'|'n'|'b'|'\\'|'\'' -> state_14 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_14 lexbuf =
+ match lexing.next_char lexbuf with
+ '\'' -> action_36 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_15 lexbuf =
+ match lexing.next_char lexbuf with
+ '9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0' -> state_16 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_16 lexbuf =
+ match lexing.next_char lexbuf with
+ '9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0' -> state_17 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_17 lexbuf =
+ match lexing.next_char lexbuf with
+ '\'' -> action_37 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_24 lexbuf =
+ Lexing.set_backtrack lexbuf action_34;
+ match lexing.next_char lexbuf with
+ '9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0' -> state_27 lexbuf
+ | 't'|'r'|'n'|'b'|'\\'|'"' -> action_31 lexbuf
+ | ' '|'\026'|'\013'|'\012'|'\n'|'\t' -> state_25 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_25 lexbuf =
+ Lexing.set_backtrack lexbuf action_30;
+ match lexing.next_char lexbuf with
+ ' '|'\026'|'\013'|'\012'|'\n'|'\t' -> state_25 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_27 lexbuf =
+ match lexing.next_char lexbuf with
+ '9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0' -> state_28 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_28 lexbuf =
+ match lexing.next_char lexbuf with
+ '9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0' -> action_32 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_34 lexbuf =
+ Lexing.set_backtrack lexbuf action_28;
+ match lexing.next_char lexbuf with
+ '*' -> action_26 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_40 lexbuf =
+ Lexing.set_backtrack lexbuf action_0;
+ match lexing.next_char lexbuf with
+ ' '|'\013'|'\n'|'\t' -> state_65 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_43 lexbuf =
+ Lexing.set_backtrack lexbuf action_16;
+ match lexing.next_char lexbuf with
+ '*' -> action_1 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_48 lexbuf =
+ Lexing.set_backtrack lexbuf action_21;
+ match lexing.next_char lexbuf with
+ ';' -> action_7 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_51 lexbuf =
+ Lexing.set_backtrack lexbuf action_2;
+ match lexing.next_char lexbuf with
+ 'z'|'y'|'x'|'w'|'v'|'u'|'t'|'s'|'r'|'q'|'p'|'o'|'n'|'m'|'l'|'k'|'j'|'i'|'h'|'g'|'f'|'e'|'d'|'c'|'b'|'a'|'Z'|'Y'|'X'|'W'|'V'|'U'|'T'|'S'|'R'|'Q'|'P'|'O'|'N'|'M'|'L'|'K'|'J'|'I'|'H'|'G'|'F'|'E'|'D'|'C'|'B'|'A'|'9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0'|'\'' -> state_59 lexbuf
+ | '_' -> state_60 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_55 lexbuf =
+ Lexing.set_backtrack lexbuf action_9;
+ match lexing.next_char lexbuf with
+ 'z'|'y'|'x'|'w'|'v'|'u'|'t'|'s'|'r'|'q'|'p'|'o'|'n'|'m'|'l'|'k'|'j'|'i'|'h'|'g'|'f'|'e'|'d'|'c'|'b'|'a'|'Z'|'Y'|'X'|'W'|'V'|'U'|'T'|'S'|'R'|'Q'|'P'|'O'|'N'|'M'|'L'|'K'|'J'|'I'|'H'|'G'|'F'|'E'|'D'|'C'|'B'|'A'|'9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0'|'\'' -> state_59 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_56 lexbuf =
+ Lexing.set_backtrack lexbuf action_2;
+ match lexing.next_char lexbuf with
+ 'z'|'y'|'x'|'w'|'v'|'u'|'t'|'s'|'r'|'q'|'p'|'n'|'m'|'l'|'k'|'j'|'i'|'h'|'g'|'f'|'e'|'d'|'c'|'b'|'a'|'Z'|'Y'|'X'|'W'|'V'|'U'|'T'|'S'|'R'|'Q'|'P'|'O'|'N'|'M'|'L'|'K'|'J'|'I'|'H'|'G'|'F'|'E'|'D'|'C'|'B'|'A'|'9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0'|'\'' -> state_59 lexbuf
+ | 'o' -> state_61 lexbuf
+ | '_' -> state_60 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_59 lexbuf =
+ Lexing.set_backtrack lexbuf action_2;
+ match lexing.next_char lexbuf with
+ 'z'|'y'|'x'|'w'|'v'|'u'|'t'|'s'|'r'|'q'|'p'|'o'|'n'|'m'|'l'|'k'|'j'|'i'|'h'|'g'|'f'|'e'|'d'|'c'|'b'|'a'|'Z'|'Y'|'X'|'W'|'V'|'U'|'T'|'S'|'R'|'Q'|'P'|'O'|'N'|'M'|'L'|'K'|'J'|'I'|'H'|'G'|'F'|'E'|'D'|'C'|'B'|'A'|'9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0'|'\'' -> state_59 lexbuf
+ | '_' -> state_60 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_60 lexbuf =
+ match lexing.next_char lexbuf with
+ 'z'|'y'|'x'|'w'|'v'|'u'|'t'|'s'|'r'|'q'|'p'|'o'|'n'|'m'|'l'|'k'|'j'|'i'|'h'|'g'|'f'|'e'|'d'|'c'|'b'|'a'|'Z'|'Y'|'X'|'W'|'V'|'U'|'T'|'S'|'R'|'Q'|'P'|'O'|'N'|'M'|'L'|'K'|'J'|'I'|'H'|'G'|'F'|'E'|'D'|'C'|'B'|'A'|'9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0'|'\'' -> state_59 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_61 lexbuf =
+ Lexing.set_backtrack lexbuf action_2;
+ match lexing.next_char lexbuf with
+ 'z'|'y'|'x'|'w'|'v'|'u'|'t'|'s'|'r'|'q'|'p'|'o'|'n'|'m'|'l'|'k'|'j'|'i'|'h'|'g'|'e'|'d'|'c'|'b'|'a'|'Z'|'Y'|'X'|'W'|'V'|'U'|'T'|'S'|'R'|'Q'|'P'|'O'|'N'|'M'|'L'|'K'|'J'|'I'|'H'|'G'|'F'|'E'|'D'|'C'|'B'|'A'|'9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0'|'\'' -> state_59 lexbuf
+ | 'f' -> state_62 lexbuf
+ | '_' -> state_60 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_62 lexbuf =
+ Lexing.set_backtrack lexbuf action_2;
+ match lexing.next_char lexbuf with
+ 'z'|'y'|'x'|'w'|'v'|'u'|'t'|'s'|'r'|'q'|'p'|'o'|'n'|'m'|'l'|'k'|'j'|'i'|'h'|'g'|'f'|'e'|'d'|'c'|'b'|'a'|'Z'|'Y'|'X'|'W'|'V'|'U'|'T'|'S'|'R'|'Q'|'P'|'O'|'N'|'M'|'L'|'K'|'J'|'I'|'H'|'G'|'F'|'E'|'D'|'C'|'B'|'A'|'9'|'8'|'7'|'6'|'5'|'4'|'3'|'2'|'1'|'0'|'\'' -> state_59 lexbuf
+ | '_' -> state_60 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and state_65 lexbuf =
+ Lexing.set_backtrack lexbuf action_0;
+ match lexing.next_char lexbuf with
+ ' '|'\013'|'\n'|'\t' -> state_65 lexbuf
+ | _ -> lexing.backtrack lexbuf
+and main lexbuf =
+ Lexing.init lexbuf;
+ state_0 lexbuf
+
+and action lexbuf =
+ Lexing.init lexbuf;
+ state_1 lexbuf
+
+and string lexbuf =
+ Lexing.init lexbuf;
+ state_2 lexbuf
+
+and char lexbuf =
+ Lexing.init lexbuf;
+ state_3 lexbuf
+
+and comment lexbuf =
+ Lexing.init lexbuf;
+ state_4 lexbuf
diff --git a/testsuite/tests/tool-lexyacc/output.ml b/testsuite/tests/tool-lexyacc/output.ml
new file mode 100644
index 0000000000..d8e854402c
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/output.ml
@@ -0,0 +1,164 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Generating a DFA as a set of mutually recursive functions *)
+
+open Syntax
+
+let ic = ref stdin
+let oc = ref stdout
+
+(* 1- Generating the actions *)
+
+let copy_buffer = String.create 1024
+
+let copy_chunk (Location(start,stop)) =
+ seek_in !ic start;
+ let tocopy = ref(stop - start) in
+ while !tocopy > 0 do
+ let m =
+ input !ic copy_buffer 0 (min !tocopy (String.length copy_buffer)) in
+ output !oc copy_buffer 0 m;
+ tocopy := !tocopy - m
+ done
+
+
+let output_action (i,act) =
+ output_string !oc ("action_" ^ string_of_int i ^ " lexbuf = (\n");
+ copy_chunk act;
+ output_string !oc ")\nand "
+
+
+(* 2- Generating the states *)
+
+let states = ref ([||] : automata array)
+
+type occurrence =
+ { mutable pos: int list;
+ mutable freq: int }
+
+let enumerate_vect v =
+ let env = ref [] in
+ for pos = 0 to Array.length v - 1 do
+ try
+ let occ = List.assoc v.(pos) !env in
+ occ.pos <- pos :: occ.pos;
+ occ.freq <- occ.freq + 1
+ with Not_found ->
+ env := (v.(pos), {pos = [pos]; freq = 1 }) :: !env
+ done;
+ Sort.list (fun (e1, occ1) (e2, occ2) -> occ1.freq >= occ2.freq) !env
+
+
+let output_move = function
+ Backtrack ->
+ output_string !oc "lexing.backtrack lexbuf"
+ | Goto dest ->
+ match !states.(dest) with
+ Perform act_num ->
+ output_string !oc ("action_" ^ string_of_int act_num ^ " lexbuf")
+ | _ ->
+ output_string !oc ("state_" ^ string_of_int dest ^ " lexbuf")
+
+
+(* Cannot use standard char_for_read because the characters to escape
+ are not the same in CL6 and CL1999. *)
+
+let output_char_lit oc = function
+ '\'' -> output_string oc "\\'"
+ | '\\' -> output_string oc "\\\\"
+ | '\n' -> output_string oc "\\n"
+ | '\t' -> output_string oc "\\t"
+ | c -> if Char.code c >= 32 && Char.code c < 128 then
+ output_char oc c
+ else begin
+ let n = Char.code c in
+ output_char oc '\\';
+ output_char oc (Char.chr (48 + n / 100));
+ output_char oc (Char.chr (48 + (n / 10) mod 10));
+ output_char oc (Char.chr (48 + n mod 10))
+ end
+
+let rec output_chars = function
+ [] ->
+ failwith "output_chars"
+ | [c] ->
+ output_string !oc "'";
+ output_char_lit !oc (Char.chr c);
+ output_string !oc "'"
+ | c::cl ->
+ output_string !oc "'";
+ output_char_lit !oc (Char.chr c);
+ output_string !oc "'|";
+ output_chars cl
+
+let output_one_trans (dest, occ) =
+ output_chars occ.pos;
+ output_string !oc " -> ";
+ output_move dest;
+ output_string !oc "\n | "
+
+let output_all_trans trans =
+ output_string !oc " match lexing.next_char lexbuf with\n ";
+ match enumerate_vect trans with
+ [] ->
+ failwith "output_all_trans"
+ | (default, _) :: rest ->
+ List.iter output_one_trans rest;
+ output_string !oc "_ -> ";
+ output_move default;
+ output_string !oc "\nand "
+
+let output_state state_num = function
+ Perform i ->
+ ()
+ | Shift(what_to_do, moves) ->
+ output_string !oc
+ ("state_" ^ string_of_int state_num ^ " lexbuf =\n");
+ begin match what_to_do with
+ No_remember -> ()
+ | Remember i ->
+ output_string !oc
+ (" Lexing.set_backtrack lexbuf action_" ^
+ string_of_int i ^ ";\n")
+ end;
+ output_all_trans moves
+
+
+(* 3- Generating the entry points *)
+
+let rec output_entries = function
+ [] -> failwith "output_entries"
+ | (name,state_num) :: rest ->
+ output_string !oc (name ^ " lexbuf =\n");
+ output_string !oc " Lexing.init lexbuf;\n";
+ output_string !oc (" state_" ^ string_of_int state_num ^
+ " lexbuf\n");
+ match rest with
+ [] -> ()
+ | _ -> output_string !oc "\nand "; output_entries rest
+
+
+(* All together *)
+
+let output_lexdef header (initial_st, st, actions) =
+ print_int (Array.length st); print_string " states, ";
+ print_int (List.length actions); print_string " actions.";
+ print_newline();
+ copy_chunk header;
+ output_string !oc "\nlet rec ";
+ states := st;
+ List.iter output_action actions;
+ for i = 0 to Array.length st - 1 do
+ output_state i st.(i)
+ done;
+ output_entries initial_st
diff --git a/testsuite/tests/tool-lexyacc/scan_aux.ml b/testsuite/tests/tool-lexyacc/scan_aux.ml
new file mode 100644
index 0000000000..81168f3364
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/scan_aux.ml
@@ -0,0 +1,57 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Auxiliaries for the lexical analyzer *)
+
+let brace_depth = ref 0
+let comment_depth = ref 0
+
+exception Lexical_error of string
+
+let initial_string_buffer = String.create 256
+let string_buff = ref initial_string_buffer
+let string_index = ref 0
+
+let reset_string_buffer () =
+ string_buff := initial_string_buffer;
+ string_index := 0
+
+
+let store_string_char c =
+ begin
+ if !string_index >= String.length !string_buff then begin
+ let new_buff = String.create (String.length !string_buff * 2) in
+ String.blit new_buff 0 !string_buff 0 (String.length !string_buff);
+ string_buff := new_buff
+ end
+ end;
+ String.unsafe_set !string_buff !string_index c;
+ incr string_index
+
+let get_stored_string () =
+ let s = String.sub !string_buff 0 !string_index in
+ string_buff := initial_string_buffer;
+ s
+
+
+let char_for_backslash = function
+ 'n' -> '\010' (* '\n' when bootstrapped *)
+ | 't' -> '\009' (* '\t' *)
+ | 'b' -> '\008' (* '\b' *)
+ | 'r' -> '\013' (* '\r' *)
+ | c -> c
+
+
+let char_for_decimal_code lexbuf i =
+ Char.chr(100 * (Char.code(Lexing.lexeme_char lexbuf i) - 48) +
+ 10 * (Char.code(Lexing.lexeme_char lexbuf (i+1)) - 48) +
+ (Char.code(Lexing.lexeme_char lexbuf (i+2)) - 48))
diff --git a/testsuite/tests/tool-lexyacc/scanner.mll b/testsuite/tests/tool-lexyacc/scanner.mll
new file mode 100644
index 0000000000..7d71c68522
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/scanner.mll
@@ -0,0 +1,130 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexical analyzer for lexer definitions. *)
+
+{
+open Syntax
+open Grammar
+open Scan_aux
+}
+
+rule main = parse
+ [' ' '\010' '\013' '\009' ] +
+ { main lexbuf }
+ | "(*"
+ { comment_depth := 1;
+ comment lexbuf;
+ main lexbuf }
+ | (['A'-'Z' 'a'-'z'] | '_' ['A'-'Z' 'a'-'z' '\'' '0'-'9'])
+ ( '_' ? ['A'-'Z' 'a'-'z' ''' '0'-'9'] ) *
+ { match Lexing.lexeme lexbuf with
+ "rule" -> Trule
+ | "parse" -> Tparse
+ | "and" -> Tand
+ | "eof" -> Teof
+ | s -> Tident s }
+ | '"'
+ { reset_string_buffer();
+ string lexbuf;
+ Tstring(get_stored_string()) }
+ | "'"
+ { Tchar(char lexbuf) }
+ | '{'
+ { let n1 = Lexing.lexeme_end lexbuf in
+ brace_depth := 1;
+ let n2 = action lexbuf in
+ Taction(Location(n1, n2)) }
+ | '=' { Tequal }
+ | ";;" { Tend }
+ | '|' { Tor }
+ | '_' { Tunderscore }
+ | "eof" { Teof }
+ | '[' { Tlbracket }
+ | ']' { Trbracket }
+ | '*' { Tstar }
+ | '?' { Tmaybe }
+ | '+' { Tplus }
+ | '(' { Tlparen }
+ | ')' { Trparen }
+ | '^' { Tcaret }
+ | '-' { Tdash }
+ | eof
+ { raise(Lexical_error "unterminated lexer definition") }
+ | _
+ { raise(Lexical_error("illegal character " ^ Lexing.lexeme lexbuf)) }
+
+and action = parse
+ '{'
+ { incr brace_depth;
+ action lexbuf }
+ | '}'
+ { decr brace_depth;
+ if !brace_depth = 0 then Lexing.lexeme_start lexbuf else action lexbuf }
+ | '"'
+ { reset_string_buffer();
+ string lexbuf;
+ reset_string_buffer();
+ action lexbuf }
+ | '\''
+ { let _ = char lexbuf in action lexbuf }
+ | "(*"
+ { comment_depth := 1;
+ comment lexbuf;
+ action lexbuf }
+ | eof
+ { raise (Lexical_error "unterminated action") }
+ | _
+ { action lexbuf }
+
+and string = parse
+ '"'
+ { () }
+ | '\\' [' ' '\010' '\013' '\009' '\026' '\012'] +
+ { string lexbuf }
+ | '\\' ['\\' '"' 'n' 't' 'b' 'r']
+ { store_string_char(char_for_backslash(Lexing.lexeme_char lexbuf 1));
+ string lexbuf }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9']
+ { store_string_char(char_for_decimal_code lexbuf 1);
+ string lexbuf }
+ | eof
+ { raise(Lexical_error "unterminated string") }
+ | _
+ { store_string_char(Lexing.lexeme_char lexbuf 0);
+ string lexbuf }
+
+and char = parse
+ [^ '\\'] "'"
+ { Lexing.lexeme_char lexbuf 0 }
+ | '\\' ['\\' '\'' 'n' 't' 'b' 'r'] "'"
+ { char_for_backslash (Lexing.lexeme_char lexbuf 1) }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
+ { char_for_decimal_code lexbuf 1 }
+ | _
+ { raise(Lexical_error "bad character constant") }
+
+and comment = parse
+ "(*"
+ { incr comment_depth; comment lexbuf }
+ | "*)"
+ { decr comment_depth;
+ if !comment_depth = 0 then () else comment lexbuf }
+ | '"'
+ { reset_string_buffer();
+ string lexbuf;
+ reset_string_buffer();
+ comment lexbuf }
+ | eof
+ { raise(Lexical_error "unterminated comment") }
+ | _
+ { comment lexbuf }
diff --git a/testsuite/tests/tool-lexyacc/syntax.ml b/testsuite/tests/tool-lexyacc/syntax.ml
new file mode 100644
index 0000000000..8f634466b1
--- /dev/null
+++ b/testsuite/tests/tool-lexyacc/syntax.ml
@@ -0,0 +1,38 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The shallow abstract syntax *)
+
+type location =
+ Location of int * int
+
+type regular_expression =
+ Epsilon
+ | Characters of char list
+ | Sequence of regular_expression * regular_expression
+ | Alternative of regular_expression * regular_expression
+ | Repetition of regular_expression
+
+type lexer_definition =
+ Lexdef of location * (string * (regular_expression * location) list) list
+
+(* Representation of automata *)
+
+type automata =
+ Perform of int
+ | Shift of automata_trans * automata_move array
+and automata_trans =
+ No_remember
+ | Remember of int
+and automata_move =
+ Backtrack
+ | Goto of int
diff --git a/testsuite/tests/tool-ocaml/Makefile b/testsuite/tests/tool-ocaml/Makefile
new file mode 100644
index 0000000000..e1d92c88c4
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/Makefile
@@ -0,0 +1,33 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+SHOULD_FAIL=t060-raise.ml
+
+compile: lib.cmo
+ @for file in t*.ml; do \
+ printf " ... testing '$$file'"; \
+ if [ `echo $(SHOULD_FAIL) | grep $$file` ]; then \
+ $(OCAML) -w a lib.cmo $$file 2>/dev/null \
+ && echo " => failed" || echo " => passed"; \
+ else \
+ $(OCAML) -w a lib.cmo $$file 2>/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ fi; \
+ done
+
+promote:
+
+clean: defaultclean
+ @rm -f ./a.out
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/tool-ocaml/lib.ml b/testsuite/tests/tool-ocaml/lib.ml
new file mode 100644
index 0000000000..9ab7427190
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/lib.ml
@@ -0,0 +1,42 @@
+external raise : exn -> 'a = "%raise"
+
+external not : bool -> bool = "%boolnot"
+
+external (=) : 'a -> 'a -> bool = "%equal"
+external (<>) : 'a -> 'a -> bool = "%notequal"
+external (<) : 'a -> 'a -> bool = "%lessthan"
+external (>) : 'a -> 'a -> bool = "%greaterthan"
+external (<=) : 'a -> 'a -> bool = "%lessequal"
+external (>=) : 'a -> 'a -> bool = "%greaterequal"
+
+external (~-) : int -> int = "%negint"
+external (+) : int -> int -> int = "%addint"
+external (-) : int -> int -> int = "%subint"
+external ( * ) : int -> int -> int = "%mulint"
+external (/) : int -> int -> int = "%divint"
+external (mod) : int -> int -> int = "%modint"
+
+external (land) : int -> int -> int = "%andint"
+external (lor) : int -> int -> int = "%orint"
+external (lxor) : int -> int -> int = "%xorint"
+external (lsl) : int -> int -> int = "%lslint"
+external (lsr) : int -> int -> int = "%lsrint"
+external (asr) : int -> int -> int = "%asrint"
+
+external ignore : 'a -> unit = "%ignore"
+
+type 'a ref = { mutable contents: 'a }
+external ref : 'a -> 'a ref = "%makemutable"
+external (!) : 'a ref -> 'a = "%field0"
+external (:=) : 'a ref -> 'a -> unit = "%setfield0"
+external incr : int ref -> unit = "%incr"
+external decr : int ref -> unit = "%decr"
+
+type 'a option = None | Some of 'a
+
+type 'a weak_t;;
+external weak_create: int -> 'a weak_t = "caml_weak_create";;
+external weak_set : 'a weak_t -> int -> 'a option -> unit = "caml_weak_set";;
+external weak_get: 'a weak_t -> int -> 'a option = "caml_weak_get";;
+
+let x = 42;;
diff --git a/testsuite/tests/tool-ocaml/t000.ml b/testsuite/tests/tool-ocaml/t000.ml
new file mode 100644
index 0000000000..fafa1c89fd
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t000.ml
@@ -0,0 +1,7 @@
+(* empty file *)
+
+(**
+ 0 ATOM0
+ 1 SETGLOBAL T000
+ 3 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t010-const0.ml b/testsuite/tests/tool-ocaml/t010-const0.ml
new file mode 100644
index 0000000000..73ecbb1f18
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t010-const0.ml
@@ -0,0 +1,8 @@
+0;;
+
+(**
+ 0 CONST0
+ 1 ATOM0
+ 2 SETGLOBAL T010-const0
+ 4 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t010-const1.ml b/testsuite/tests/tool-ocaml/t010-const1.ml
new file mode 100644
index 0000000000..75a00d5787
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t010-const1.ml
@@ -0,0 +1,8 @@
+1;;
+
+(**
+ 0 CONST1
+ 1 ATOM0
+ 2 SETGLOBAL T010-const1
+ 4 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t010-const2.ml b/testsuite/tests/tool-ocaml/t010-const2.ml
new file mode 100644
index 0000000000..f0ed8e7df1
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t010-const2.ml
@@ -0,0 +1,8 @@
+2;;
+
+(**
+ 0 CONST2
+ 1 ATOM0
+ 2 SETGLOBAL T010-const2
+ 4 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t010-const3.ml b/testsuite/tests/tool-ocaml/t010-const3.ml
new file mode 100644
index 0000000000..4f034c4b52
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t010-const3.ml
@@ -0,0 +1,8 @@
+3;;
+
+(**
+ 0 CONST3
+ 1 ATOM0
+ 2 SETGLOBAL T010-const3
+ 4 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t011-constint.ml b/testsuite/tests/tool-ocaml/t011-constint.ml
new file mode 100644
index 0000000000..9ece6c53bd
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t011-constint.ml
@@ -0,0 +1,8 @@
+4;;
+
+(**
+ 0 CONSTINT 4
+ 2 ATOM0
+ 3 SETGLOBAL T011-constint
+ 5 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t020.ml b/testsuite/tests/tool-ocaml/t020.ml
new file mode 100644
index 0000000000..5d6a3cfc9f
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t020.ml
@@ -0,0 +1,10 @@
+let _ = () in ();;
+
+(**
+ 0 CONST0
+ 1 PUSHCONST0
+ 2 POP 1
+ 4 ATOM0
+ 5 SETGLOBAL T020
+ 7 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t021-pushconst1.ml b/testsuite/tests/tool-ocaml/t021-pushconst1.ml
new file mode 100644
index 0000000000..075997a830
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t021-pushconst1.ml
@@ -0,0 +1,10 @@
+let _ = () in 1;;
+
+(**
+ 0 CONST0
+ 1 PUSHCONST1
+ 2 POP 1
+ 4 ATOM0
+ 5 SETGLOBAL T021-pushconst1
+ 7 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t021-pushconst2.ml b/testsuite/tests/tool-ocaml/t021-pushconst2.ml
new file mode 100644
index 0000000000..17adb5075b
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t021-pushconst2.ml
@@ -0,0 +1,10 @@
+let _ = () in 2;;
+
+(**
+ 0 CONST0
+ 1 PUSHCONST2
+ 2 POP 1
+ 4 ATOM0
+ 5 SETGLOBAL T021-pushconst2
+ 7 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t021-pushconst3.ml b/testsuite/tests/tool-ocaml/t021-pushconst3.ml
new file mode 100644
index 0000000000..563c609324
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t021-pushconst3.ml
@@ -0,0 +1,10 @@
+let _ = () in 3;;
+
+(**
+ 0 CONST0
+ 1 PUSHCONST3
+ 2 POP 1
+ 4 ATOM0
+ 5 SETGLOBAL T021-pushconst3
+ 7 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t022-pushconstint.ml b/testsuite/tests/tool-ocaml/t022-pushconstint.ml
new file mode 100644
index 0000000000..1b766a5723
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t022-pushconstint.ml
@@ -0,0 +1,10 @@
+let _ = () in -1;;
+
+(**
+ 0 CONST0
+ 1 PUSHCONSTINT -1
+ 3 POP 1
+ 5 ATOM0
+ 6 SETGLOBAL T022-pushconstint
+ 8 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t040-makeblock1.ml b/testsuite/tests/tool-ocaml/t040-makeblock1.ml
new file mode 100644
index 0000000000..71516606b6
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t040-makeblock1.ml
@@ -0,0 +1,13 @@
+type t = {
+ mutable a : int;
+};;
+
+{ a = 0 };;
+
+(**
+ 0 CONST0
+ 1 MAKEBLOCK1 0
+ 3 ATOM0
+ 4 SETGLOBAL T040-makeblock1
+ 6 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t040-makeblock2.ml b/testsuite/tests/tool-ocaml/t040-makeblock2.ml
new file mode 100644
index 0000000000..e7c745b9c2
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t040-makeblock2.ml
@@ -0,0 +1,15 @@
+type t = {
+ mutable a : int;
+ mutable b : int;
+};;
+
+{ a = 0; b = 0 };;
+
+(**
+ 0 CONST0
+ 1 PUSHCONST0
+ 2 MAKEBLOCK2 0
+ 4 ATOM0
+ 5 SETGLOBAL T040-makeblock2
+ 7 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t040-makeblock3.ml b/testsuite/tests/tool-ocaml/t040-makeblock3.ml
new file mode 100644
index 0000000000..8fb56054e3
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t040-makeblock3.ml
@@ -0,0 +1,17 @@
+type t = {
+ mutable a : int;
+ mutable b : int;
+ mutable c : int;
+};;
+
+{ a = 0; b = 0; c = 0 };;
+
+(**
+ 0 CONST0
+ 1 PUSHCONST0
+ 2 PUSHCONST0
+ 3 MAKEBLOCK3 0
+ 5 ATOM0
+ 6 SETGLOBAL T040-makeblock3
+ 8 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t041-makeblock.ml b/testsuite/tests/tool-ocaml/t041-makeblock.ml
new file mode 100644
index 0000000000..5ae255d6ee
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t041-makeblock.ml
@@ -0,0 +1,19 @@
+type t = {
+ mutable a : int;
+ mutable b : int;
+ mutable c : int;
+ mutable d : int;
+};;
+
+{ a = 0; b = 0; c = 0; d = 0 };;
+
+(**
+ 0 CONST0
+ 1 PUSHCONST0
+ 2 PUSHCONST0
+ 3 PUSHCONST0
+ 4 MAKEBLOCK 4, 0
+ 7 ATOM0
+ 8 SETGLOBAL T041-makeblock
+ 10 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t050-getglobal.ml b/testsuite/tests/tool-ocaml/t050-getglobal.ml
new file mode 100644
index 0000000000..f10393cf62
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t050-getglobal.ml
@@ -0,0 +1,8 @@
+[1];;
+
+(**
+ 0 GETGLOBAL <0>(1, 0)
+ 2 ATOM0
+ 3 SETGLOBAL T050-getglobal
+ 5 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t050-pushgetglobal.ml b/testsuite/tests/tool-ocaml/t050-pushgetglobal.ml
new file mode 100644
index 0000000000..e1172cc350
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t050-pushgetglobal.ml
@@ -0,0 +1,10 @@
+let _ = () in 0.01;;
+
+(**
+ 0 CONST0
+ 1 PUSHGETGLOBAL 0.01
+ 3 POP 1
+ 5 ATOM0
+ 6 SETGLOBAL T050-pushgetglobal
+ 8 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t051-getglobalfield.ml b/testsuite/tests/tool-ocaml/t051-getglobalfield.ml
new file mode 100644
index 0000000000..45d9ccea22
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t051-getglobalfield.ml
@@ -0,0 +1,13 @@
+Lib.x;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBALFIELD Lib, 0
+ 12 ATOM0
+ 13 SETGLOBAL T051-getglobalfield
+ 15 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t051-pushgetglobalfield.ml b/testsuite/tests/tool-ocaml/t051-pushgetglobalfield.ml
new file mode 100644
index 0000000000..2012a2573d
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t051-pushgetglobalfield.ml
@@ -0,0 +1,15 @@
+let _ = () in Lib.x;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHGETGLOBALFIELD Lib, 0
+ 13 POP 1
+ 15 ATOM0
+ 16 SETGLOBAL T051-pushgetglobalfield
+ 18 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t060-raise.ml b/testsuite/tests/tool-ocaml/t060-raise.ml
new file mode 100644
index 0000000000..1aa484667a
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t060-raise.ml
@@ -0,0 +1,15 @@
+open Lib;;
+raise End_of_file;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL End_of_file
+ 11 MAKEBLOCK1 0
+ 13 RAISE
+ 14 SETGLOBAL T060-raise
+ 16 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t070-branch.ml b/testsuite/tests/tool-ocaml/t070-branch.ml
new file mode 100644
index 0000000000..4fc52d426b
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t070-branch.ml
@@ -0,0 +1,20 @@
+open Lib;;
+if true then 0 else raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 BRANCHIFNOT 15
+ 12 CONST0
+ 13 BRANCH 20
+ 15 GETGLOBAL Not_found
+ 17 MAKEBLOCK1 0
+ 19 RAISE
+ 20 ATOM0
+ 21 SETGLOBAL T070-branch
+ 23 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t070-branchif.ml b/testsuite/tests/tool-ocaml/t070-branchif.ml
new file mode 100644
index 0000000000..c256248c80
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t070-branchif.ml
@@ -0,0 +1,20 @@
+open Lib;;
+if not false then 0 else raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 BRANCHIF 15
+ 12 CONST0
+ 13 BRANCH 20
+ 15 GETGLOBAL Not_found
+ 17 MAKEBLOCK1 0
+ 19 RAISE
+ 20 ATOM0
+ 21 SETGLOBAL T070-branchif
+ 23 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t070-branchifnot.ml b/testsuite/tests/tool-ocaml/t070-branchifnot.ml
new file mode 100644
index 0000000000..9e6e4e8ba3
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t070-branchifnot.ml
@@ -0,0 +1,18 @@
+open Lib;;
+if false then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 BRANCHIFNOT 17
+ 12 GETGLOBAL Not_found
+ 14 MAKEBLOCK1 0
+ 16 RAISE
+ 17 ATOM0
+ 18 SETGLOBAL T070-branchifnot
+ 20 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t071-boolnot.ml b/testsuite/tests/tool-ocaml/t071-boolnot.ml
new file mode 100644
index 0000000000..b4a81943c6
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t071-boolnot.ml
@@ -0,0 +1,19 @@
+open Lib;;
+if not true then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 BOOLNOT
+ 11 BRANCHIFNOT 18
+ 13 GETGLOBAL Not_found
+ 15 MAKEBLOCK1 0
+ 17 RAISE
+ 18 ATOM0
+ 19 SETGLOBAL T071-boolnot
+ 21 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t080-eq.ml b/testsuite/tests/tool-ocaml/t080-eq.ml
new file mode 100644
index 0000000000..3ee735f088
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t080-eq.ml
@@ -0,0 +1,21 @@
+open Lib;;
+if not (0 = 0) then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST0
+ 11 EQ
+ 12 BOOLNOT
+ 13 BRANCHIFNOT 20
+ 15 GETGLOBAL Not_found
+ 17 MAKEBLOCK1 0
+ 19 RAISE
+ 20 ATOM0
+ 21 SETGLOBAL T080-eq
+ 23 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t080-geint.ml b/testsuite/tests/tool-ocaml/t080-geint.ml
new file mode 100644
index 0000000000..a220b7e9a4
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t080-geint.ml
@@ -0,0 +1,21 @@
+open Lib;;
+if not (0 >= 0) then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST0
+ 11 GEINT
+ 12 BOOLNOT
+ 13 BRANCHIFNOT 20
+ 15 GETGLOBAL Not_found
+ 17 MAKEBLOCK1 0
+ 19 RAISE
+ 20 ATOM0
+ 21 SETGLOBAL T080-geint
+ 23 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t080-gtint.ml b/testsuite/tests/tool-ocaml/t080-gtint.ml
new file mode 100644
index 0000000000..32d573217f
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t080-gtint.ml
@@ -0,0 +1,20 @@
+open Lib;;
+if 0 > 0 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST0
+ 11 GTINT
+ 12 BRANCHIFNOT 19
+ 14 GETGLOBAL Not_found
+ 16 MAKEBLOCK1 0
+ 18 RAISE
+ 19 ATOM0
+ 20 SETGLOBAL T080-gtint
+ 22 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t080-leint.ml b/testsuite/tests/tool-ocaml/t080-leint.ml
new file mode 100644
index 0000000000..cc983a0836
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t080-leint.ml
@@ -0,0 +1,21 @@
+open Lib;;
+if not (0 <= 0) then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST0
+ 11 LEINT
+ 12 BOOLNOT
+ 13 BRANCHIFNOT 20
+ 15 GETGLOBAL Not_found
+ 17 MAKEBLOCK1 0
+ 19 RAISE
+ 20 ATOM0
+ 21 SETGLOBAL T080-leint
+ 23 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t080-ltint.ml b/testsuite/tests/tool-ocaml/t080-ltint.ml
new file mode 100644
index 0000000000..ae7d240ae8
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t080-ltint.ml
@@ -0,0 +1,20 @@
+open Lib;;
+if 0 < 0 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST0
+ 11 LTINT
+ 12 BRANCHIFNOT 19
+ 14 GETGLOBAL Not_found
+ 16 MAKEBLOCK1 0
+ 18 RAISE
+ 19 ATOM0
+ 20 SETGLOBAL T080-ltint
+ 22 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t080-neq.ml b/testsuite/tests/tool-ocaml/t080-neq.ml
new file mode 100644
index 0000000000..5066e9cbcc
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t080-neq.ml
@@ -0,0 +1,20 @@
+open Lib;;
+if 0 <> 0 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST0
+ 11 NEQ
+ 12 BRANCHIFNOT 19
+ 14 GETGLOBAL Not_found
+ 16 MAKEBLOCK1 0
+ 18 RAISE
+ 19 ATOM0
+ 20 SETGLOBAL T080-neq
+ 22 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t090-acc0.ml b/testsuite/tests/tool-ocaml/t090-acc0.ml
new file mode 100644
index 0000000000..74accecad4
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t090-acc0.ml
@@ -0,0 +1,25 @@
+open Lib;;
+let x = true in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 ACC0
+ 12 BOOLNOT
+ 13 BRANCHIFNOT 20
+ 15 GETGLOBAL Not_found
+ 17 MAKEBLOCK1 0
+ 19 RAISE
+ 20 POP 1
+ 22 ATOM0
+ 23 SETGLOBAL T090-acc0
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t090-acc1.ml b/testsuite/tests/tool-ocaml/t090-acc1.ml
new file mode 100644
index 0000000000..fc9b0254dd
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t090-acc1.ml
@@ -0,0 +1,27 @@
+open Lib;;
+let x = true in
+let y = false in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHCONST0
+ 12 ACC1
+ 13 BOOLNOT
+ 14 BRANCHIFNOT 21
+ 16 GETGLOBAL Not_found
+ 18 MAKEBLOCK1 0
+ 20 RAISE
+ 21 POP 2
+ 23 ATOM0
+ 24 SETGLOBAL T090-acc1
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t090-acc2.ml b/testsuite/tests/tool-ocaml/t090-acc2.ml
new file mode 100644
index 0000000000..4865944938
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t090-acc2.ml
@@ -0,0 +1,29 @@
+open Lib;;
+let x = true in
+let y = false in
+let z = false in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHCONST0
+ 12 PUSHCONST0
+ 13 ACC2
+ 14 BOOLNOT
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 POP 3
+ 24 ATOM0
+ 25 SETGLOBAL T090-acc2
+ 27 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t090-acc3.ml b/testsuite/tests/tool-ocaml/t090-acc3.ml
new file mode 100644
index 0000000000..9622456a64
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t090-acc3.ml
@@ -0,0 +1,31 @@
+open Lib;;
+let x = true in
+let y = false in
+let z = false in
+let a = false in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHCONST0
+ 12 PUSHCONST0
+ 13 PUSHCONST0
+ 14 ACC3
+ 15 BOOLNOT
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 POP 4
+ 25 ATOM0
+ 26 SETGLOBAL T090-acc3
+ 28 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t090-acc4.ml b/testsuite/tests/tool-ocaml/t090-acc4.ml
new file mode 100644
index 0000000000..992559b7da
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t090-acc4.ml
@@ -0,0 +1,33 @@
+open Lib;;
+let x = true in
+let y = false in
+let z = false in
+let a = false in
+let b = false in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHCONST0
+ 12 PUSHCONST0
+ 13 PUSHCONST0
+ 14 PUSHCONST0
+ 15 ACC4
+ 16 BOOLNOT
+ 17 BRANCHIFNOT 24
+ 19 GETGLOBAL Not_found
+ 21 MAKEBLOCK1 0
+ 23 RAISE
+ 24 POP 5
+ 26 ATOM0
+ 27 SETGLOBAL T090-acc4
+ 29 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t090-acc5.ml b/testsuite/tests/tool-ocaml/t090-acc5.ml
new file mode 100644
index 0000000000..57f7453b1e
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t090-acc5.ml
@@ -0,0 +1,35 @@
+open Lib;;
+let x = true in
+let y = false in
+let z = false in
+let a = false in
+let b = false in
+let c = false in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHCONST0
+ 12 PUSHCONST0
+ 13 PUSHCONST0
+ 14 PUSHCONST0
+ 15 PUSHCONST0
+ 16 ACC5
+ 17 BOOLNOT
+ 18 BRANCHIFNOT 25
+ 20 GETGLOBAL Not_found
+ 22 MAKEBLOCK1 0
+ 24 RAISE
+ 25 POP 6
+ 27 ATOM0
+ 28 SETGLOBAL T090-acc5
+ 30 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t090-acc6.ml b/testsuite/tests/tool-ocaml/t090-acc6.ml
new file mode 100644
index 0000000000..f9400282ea
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t090-acc6.ml
@@ -0,0 +1,37 @@
+open Lib;;
+let x = true in
+let y = false in
+let z = false in
+let a = false in
+let b = false in
+let c = false in
+let d = false in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHCONST0
+ 12 PUSHCONST0
+ 13 PUSHCONST0
+ 14 PUSHCONST0
+ 15 PUSHCONST0
+ 16 PUSHCONST0
+ 17 ACC6
+ 18 BOOLNOT
+ 19 BRANCHIFNOT 26
+ 21 GETGLOBAL Not_found
+ 23 MAKEBLOCK1 0
+ 25 RAISE
+ 26 POP 7
+ 28 ATOM0
+ 29 SETGLOBAL T090-acc6
+ 31 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t090-acc7.ml b/testsuite/tests/tool-ocaml/t090-acc7.ml
new file mode 100644
index 0000000000..366191bf14
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t090-acc7.ml
@@ -0,0 +1,39 @@
+open Lib;;
+let x = true in
+let y = false in
+let z = false in
+let a = false in
+let b = false in
+let c = false in
+let d = false in
+let e = false in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHCONST0
+ 12 PUSHCONST0
+ 13 PUSHCONST0
+ 14 PUSHCONST0
+ 15 PUSHCONST0
+ 16 PUSHCONST0
+ 17 PUSHCONST0
+ 18 ACC7
+ 19 BOOLNOT
+ 20 BRANCHIFNOT 27
+ 22 GETGLOBAL Not_found
+ 24 MAKEBLOCK1 0
+ 26 RAISE
+ 27 POP 8
+ 29 ATOM0
+ 30 SETGLOBAL T090-acc7
+ 32 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t091-acc.ml b/testsuite/tests/tool-ocaml/t091-acc.ml
new file mode 100644
index 0000000000..26b003f668
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t091-acc.ml
@@ -0,0 +1,41 @@
+open Lib;;
+let x = true in
+let y = false in
+let z = false in
+let a = false in
+let b = false in
+let c = false in
+let d = false in
+let e = false in
+let f = false in
+();
+if not x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHCONST0
+ 12 PUSHCONST0
+ 13 PUSHCONST0
+ 14 PUSHCONST0
+ 15 PUSHCONST0
+ 16 PUSHCONST0
+ 17 PUSHCONST0
+ 18 PUSHCONST0
+ 19 ACC 8
+ 21 BOOLNOT
+ 22 BRANCHIFNOT 29
+ 24 GETGLOBAL Not_found
+ 26 MAKEBLOCK1 0
+ 28 RAISE
+ 29 POP 9
+ 31 ATOM0
+ 32 SETGLOBAL T091-acc
+ 34 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc.ml b/testsuite/tests/tool-ocaml/t092-pushacc.ml
new file mode 100644
index 0000000000..c21561ec04
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc.ml
@@ -0,0 +1,38 @@
+open Lib;;
+let x = false in
+let y = true in
+let z = true in
+let a = true in
+let b = true in
+let c = true in
+let d = true in
+let e = true in
+let f = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHCONST1
+ 12 PUSHCONST1
+ 13 PUSHCONST1
+ 14 PUSHCONST1
+ 15 PUSHCONST1
+ 16 PUSHCONST1
+ 17 PUSHCONST1
+ 18 PUSHACC 8
+ 20 BRANCHIFNOT 27
+ 22 GETGLOBAL Not_found
+ 24 MAKEBLOCK1 0
+ 26 RAISE
+ 27 POP 9
+ 29 ATOM0
+ 30 SETGLOBAL T092-pushacc
+ 32 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc0.ml b/testsuite/tests/tool-ocaml/t092-pushacc0.ml
new file mode 100644
index 0000000000..ffdc3b0404
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc0.ml
@@ -0,0 +1,22 @@
+open Lib;;
+let x = false in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHACC0
+ 11 BRANCHIFNOT 18
+ 13 GETGLOBAL Not_found
+ 15 MAKEBLOCK1 0
+ 17 RAISE
+ 18 POP 1
+ 20 ATOM0
+ 21 SETGLOBAL T092-pushacc0
+ 23 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc1.ml b/testsuite/tests/tool-ocaml/t092-pushacc1.ml
new file mode 100644
index 0000000000..b923f4fc8c
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc1.ml
@@ -0,0 +1,24 @@
+open Lib;;
+let x = false in
+let y = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHACC1
+ 12 BRANCHIFNOT 19
+ 14 GETGLOBAL Not_found
+ 16 MAKEBLOCK1 0
+ 18 RAISE
+ 19 POP 2
+ 21 ATOM0
+ 22 SETGLOBAL T092-pushacc1
+ 24 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc2.ml b/testsuite/tests/tool-ocaml/t092-pushacc2.ml
new file mode 100644
index 0000000000..f6249783ab
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc2.ml
@@ -0,0 +1,26 @@
+open Lib;;
+let x = false in
+let y = true in
+let z = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHCONST1
+ 12 PUSHACC2
+ 13 BRANCHIFNOT 20
+ 15 GETGLOBAL Not_found
+ 17 MAKEBLOCK1 0
+ 19 RAISE
+ 20 POP 3
+ 22 ATOM0
+ 23 SETGLOBAL T092-pushacc2
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc3.ml b/testsuite/tests/tool-ocaml/t092-pushacc3.ml
new file mode 100644
index 0000000000..5984fec733
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc3.ml
@@ -0,0 +1,28 @@
+open Lib;;
+let x = false in
+let y = true in
+let z = true in
+let a = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHCONST1
+ 12 PUSHCONST1
+ 13 PUSHACC3
+ 14 BRANCHIFNOT 21
+ 16 GETGLOBAL Not_found
+ 18 MAKEBLOCK1 0
+ 20 RAISE
+ 21 POP 4
+ 23 ATOM0
+ 24 SETGLOBAL T092-pushacc3
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc4.ml b/testsuite/tests/tool-ocaml/t092-pushacc4.ml
new file mode 100644
index 0000000000..ce20e0b9de
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc4.ml
@@ -0,0 +1,30 @@
+open Lib;;
+let x = false in
+let y = true in
+let z = true in
+let a = true in
+let b = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHCONST1
+ 12 PUSHCONST1
+ 13 PUSHCONST1
+ 14 PUSHACC4
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 POP 5
+ 24 ATOM0
+ 25 SETGLOBAL T092-pushacc4
+ 27 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc5.ml b/testsuite/tests/tool-ocaml/t092-pushacc5.ml
new file mode 100644
index 0000000000..030f3f04b0
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc5.ml
@@ -0,0 +1,32 @@
+open Lib;;
+let x = false in
+let y = true in
+let z = true in
+let a = true in
+let b = true in
+let c = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHCONST1
+ 12 PUSHCONST1
+ 13 PUSHCONST1
+ 14 PUSHCONST1
+ 15 PUSHACC5
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 POP 6
+ 25 ATOM0
+ 26 SETGLOBAL T092-pushacc5
+ 28 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc6.ml b/testsuite/tests/tool-ocaml/t092-pushacc6.ml
new file mode 100644
index 0000000000..9c67b808e4
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc6.ml
@@ -0,0 +1,34 @@
+open Lib;;
+let x = false in
+let y = true in
+let z = true in
+let a = true in
+let b = true in
+let c = true in
+let d = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHCONST1
+ 12 PUSHCONST1
+ 13 PUSHCONST1
+ 14 PUSHCONST1
+ 15 PUSHCONST1
+ 16 PUSHACC6
+ 17 BRANCHIFNOT 24
+ 19 GETGLOBAL Not_found
+ 21 MAKEBLOCK1 0
+ 23 RAISE
+ 24 POP 7
+ 26 ATOM0
+ 27 SETGLOBAL T092-pushacc6
+ 29 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t092-pushacc7.ml b/testsuite/tests/tool-ocaml/t092-pushacc7.ml
new file mode 100644
index 0000000000..09fbbcaff0
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t092-pushacc7.ml
@@ -0,0 +1,36 @@
+open Lib;;
+let x = false in
+let y = true in
+let z = true in
+let a = true in
+let b = true in
+let c = true in
+let d = true in
+let e = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHCONST1
+ 12 PUSHCONST1
+ 13 PUSHCONST1
+ 14 PUSHCONST1
+ 15 PUSHCONST1
+ 16 PUSHCONST1
+ 17 PUSHACC7
+ 18 BRANCHIFNOT 25
+ 20 GETGLOBAL Not_found
+ 22 MAKEBLOCK1 0
+ 24 RAISE
+ 25 POP 8
+ 27 ATOM0
+ 28 SETGLOBAL T092-pushacc7
+ 30 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t093-pushacc.ml b/testsuite/tests/tool-ocaml/t093-pushacc.ml
new file mode 100644
index 0000000000..00a969adbe
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t093-pushacc.ml
@@ -0,0 +1,38 @@
+open Lib;;
+let x = false in
+let y = true in
+let z = true in
+let a = true in
+let b = true in
+let c = true in
+let d = true in
+let e = true in
+let f = true in
+if x then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST1
+ 11 PUSHCONST1
+ 12 PUSHCONST1
+ 13 PUSHCONST1
+ 14 PUSHCONST1
+ 15 PUSHCONST1
+ 16 PUSHCONST1
+ 17 PUSHCONST1
+ 18 PUSHACC 8
+ 20 BRANCHIFNOT 27
+ 22 GETGLOBAL Not_found
+ 24 MAKEBLOCK1 0
+ 26 RAISE
+ 27 POP 9
+ 29 ATOM0
+ 30 SETGLOBAL T093-pushacc
+ 32 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t100-pushtrap.ml b/testsuite/tests/tool-ocaml/t100-pushtrap.ml
new file mode 100644
index 0000000000..7b02a86276
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t100-pushtrap.ml
@@ -0,0 +1,21 @@
+open Lib;;
+try raise Not_found
+with _ -> ()
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 PUSHTRAP 16
+ 11 GETGLOBAL Not_found
+ 13 MAKEBLOCK1 0
+ 15 RAISE
+ 16 PUSHCONST0
+ 17 POP 1
+ 19 ATOM0
+ 20 SETGLOBAL T100-pushtrap
+ 22 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t101-poptrap.ml b/testsuite/tests/tool-ocaml/t101-poptrap.ml
new file mode 100644
index 0000000000..3a754a06fb
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t101-poptrap.ml
@@ -0,0 +1,21 @@
+open Lib;;
+try ()
+with _ -> ()
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 PUSHTRAP 15
+ 11 CONST0
+ 12 POPTRAP
+ 13 BRANCH 18
+ 15 PUSHCONST0
+ 16 POP 1
+ 18 ATOM0
+ 19 SETGLOBAL T101-poptrap
+ 21 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-addint.ml b/testsuite/tests/tool-ocaml/t110-addint.ml
new file mode 100644
index 0000000000..5d683c5735
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-addint.ml
@@ -0,0 +1,26 @@
+open Lib;;
+let x = 1 in
+if 1 + x <> 2 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST2
+ 11 PUSHACC1
+ 12 PUSHCONST1
+ 13 ADDINT
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 POP 1
+ 24 ATOM0
+ 25 SETGLOBAL T110-addint
+ 27 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-andint.ml b/testsuite/tests/tool-ocaml/t110-andint.ml
new file mode 100644
index 0000000000..016dc3cddd
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-andint.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if (3 land 6) <> 2 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST2
+ 10 PUSHCONSTINT 6
+ 12 PUSHCONST3
+ 13 ANDINT
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T110-andint
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-asrint-1.ml b/testsuite/tests/tool-ocaml/t110-asrint-1.ml
new file mode 100644
index 0000000000..173bdca29d
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-asrint-1.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if (-2 asr 1) <> -1 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT -1
+ 11 PUSHCONST1
+ 12 PUSHCONSTINT -2
+ 14 ASRINT
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 ATOM0
+ 24 SETGLOBAL T110-asrint-1
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-asrint-2.ml b/testsuite/tests/tool-ocaml/t110-asrint-2.ml
new file mode 100644
index 0000000000..386fc64cf8
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-asrint-2.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if (3 asr 1) <> 1 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST1
+ 11 PUSHCONST3
+ 12 ASRINT
+ 13 NEQ
+ 14 BRANCHIFNOT 21
+ 16 GETGLOBAL Not_found
+ 18 MAKEBLOCK1 0
+ 20 RAISE
+ 21 ATOM0
+ 22 SETGLOBAL T110-asrint-2
+ 24 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-divint-1.ml b/testsuite/tests/tool-ocaml/t110-divint-1.ml
new file mode 100644
index 0000000000..5cde135d24
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-divint-1.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if 2 / 2 <> 1 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST2
+ 11 PUSHCONST2
+ 12 DIVINT
+ 13 NEQ
+ 14 BRANCHIFNOT 21
+ 16 GETGLOBAL Not_found
+ 18 MAKEBLOCK1 0
+ 20 RAISE
+ 21 ATOM0
+ 22 SETGLOBAL T110-divint-1
+ 24 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-divint-2.ml b/testsuite/tests/tool-ocaml/t110-divint-2.ml
new file mode 100644
index 0000000000..34f5b00c66
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-divint-2.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if 3 / 2 <> 1 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST2
+ 11 PUSHCONST3
+ 12 DIVINT
+ 13 NEQ
+ 14 BRANCHIFNOT 21
+ 16 GETGLOBAL Not_found
+ 18 MAKEBLOCK1 0
+ 20 RAISE
+ 21 ATOM0
+ 22 SETGLOBAL T110-divint-2
+ 24 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-divint-3.ml b/testsuite/tests/tool-ocaml/t110-divint-3.ml
new file mode 100644
index 0000000000..cbb2bff1f5
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-divint-3.ml
@@ -0,0 +1,33 @@
+open Lib;;
+try
+ ignore (3 / 0);
+ raise Not_found;
+with Division_by_zero -> ()
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 PUSHTRAP 19
+ 11 CONST0
+ 12 PUSHCONST3
+ 13 DIVINT
+ 14 GETGLOBAL Not_found
+ 16 MAKEBLOCK1 0
+ 18 RAISE
+ 19 PUSHGETGLOBAL Division_by_zero
+ 21 PUSHACC1
+ 22 GETFIELD0
+ 23 EQ
+ 24 BRANCHIFNOT 29
+ 26 CONST0
+ 27 BRANCH 31
+ 29 ACC0
+ 30 RAISE
+ 31 POP 1
+ 33 ATOM0
+ 34 SETGLOBAL T110-divint-3
+ 36 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-lslint.ml b/testsuite/tests/tool-ocaml/t110-lslint.ml
new file mode 100644
index 0000000000..9dd197b467
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-lslint.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if (3 lsl 2) <> 12 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 12
+ 11 PUSHCONST2
+ 12 PUSHCONST3
+ 13 LSLINT
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T110-lslint
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-lsrint.ml b/testsuite/tests/tool-ocaml/t110-lsrint.ml
new file mode 100644
index 0000000000..9777815ccc
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-lsrint.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if (14 lsr 2) <> 3 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST3
+ 10 PUSHCONST2
+ 11 PUSHCONSTINT 14
+ 13 LSRINT
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T110-lsrint
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-modint-1.ml b/testsuite/tests/tool-ocaml/t110-modint-1.ml
new file mode 100644
index 0000000000..2a690c0896
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-modint-1.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if 20 mod 3 <> 2 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST2
+ 10 PUSHCONST3
+ 11 PUSHCONSTINT 20
+ 13 MODINT
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T110-modint-1
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-modint-2.ml b/testsuite/tests/tool-ocaml/t110-modint-2.ml
new file mode 100644
index 0000000000..0bc3be0c3c
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-modint-2.ml
@@ -0,0 +1,34 @@
+open Lib;;
+try
+ ignore (2 mod 0);
+ raise Not_found;
+with Division_by_zero -> ()
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 PUSHTRAP 19
+ 11 CONST0
+ 12 PUSHCONST2
+ 13 MODINT
+ 14 GETGLOBAL Not_found
+ 16 MAKEBLOCK1 0
+ 18 RAISE
+ 19 PUSHGETGLOBAL Division_by_zero
+ 21 PUSHACC1
+ 22 GETFIELD0
+ 23 EQ
+ 24 BRANCHIFNOT 29
+ 26 CONST0
+ 27 BRANCH 31
+ 29 ACC0
+ 30 RAISE
+ 31 POP 1
+ 33 ATOM0
+ 34 SETGLOBAL T110-modint-2
+ 36 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-mulint.ml b/testsuite/tests/tool-ocaml/t110-mulint.ml
new file mode 100644
index 0000000000..97c1cf1413
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-mulint.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if 2 * 2 <> 4 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 4
+ 11 PUSHCONST2
+ 12 PUSHCONST2
+ 13 MULINT
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T110-mulint
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-negint.ml b/testsuite/tests/tool-ocaml/t110-negint.ml
new file mode 100644
index 0000000000..069a34b200
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-negint.ml
@@ -0,0 +1,25 @@
+open Lib;;
+let x = 1 in
+if -x <> -1 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONSTINT -1
+ 12 PUSHACC1
+ 13 NEGINT
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 POP 1
+ 24 ATOM0
+ 25 SETGLOBAL T110-negint
+ 27 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-offsetint.ml b/testsuite/tests/tool-ocaml/t110-offsetint.ml
new file mode 100644
index 0000000000..925159e38d
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-offsetint.ml
@@ -0,0 +1,21 @@
+open Lib;;
+if 2 + 2 <> 4 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 4
+ 11 PUSHCONST2
+ 12 OFFSETINT 2
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T110-offsetint
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-orint.ml b/testsuite/tests/tool-ocaml/t110-orint.ml
new file mode 100644
index 0000000000..56b63d80b1
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-orint.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if (3 lor 6) <> 7 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 7
+ 11 PUSHCONSTINT 6
+ 13 PUSHCONST3
+ 14 ORINT
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 ATOM0
+ 24 SETGLOBAL T110-orint
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-subint.ml b/testsuite/tests/tool-ocaml/t110-subint.ml
new file mode 100644
index 0000000000..f626cd0d60
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-subint.ml
@@ -0,0 +1,26 @@
+open Lib;;
+let x = 1 in
+if 1 - x <> 0 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST0
+ 11 PUSHACC1
+ 12 PUSHCONST1
+ 13 SUBINT
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 POP 1
+ 24 ATOM0
+ 25 SETGLOBAL T110-subint
+ 27 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t110-xorint.ml b/testsuite/tests/tool-ocaml/t110-xorint.ml
new file mode 100644
index 0000000000..dfb278b7a8
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t110-xorint.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if (3 lxor 6) <> 5 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 5
+ 11 PUSHCONSTINT 6
+ 13 PUSHCONST3
+ 14 XORINT
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 ATOM0
+ 24 SETGLOBAL T110-xorint
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t120-getstringchar.ml b/testsuite/tests/tool-ocaml/t120-getstringchar.ml
new file mode 100644
index 0000000000..aaff2022d4
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t120-getstringchar.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if "foo".[2] <> 'o' then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 111
+ 11 PUSHCONST2
+ 12 PUSHGETGLOBAL "foo"
+ 14 GETSTRINGCHAR
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 ATOM0
+ 24 SETGLOBAL T120-getstringchar
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t121-setstringchar.ml b/testsuite/tests/tool-ocaml/t121-setstringchar.ml
new file mode 100644
index 0000000000..882d6e0812
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t121-setstringchar.ml
@@ -0,0 +1,31 @@
+open Lib;;
+let x = "foo" in
+x.[2] <- 'x';
+if x.[2] <> 'x' then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL "foo"
+ 11 PUSHCONSTINT 120
+ 13 PUSHCONST2
+ 14 PUSHACC2
+ 15 SETSTRINGCHAR
+ 16 CONSTINT 120
+ 18 PUSHCONST2
+ 19 PUSHACC2
+ 20 GETSTRINGCHAR
+ 21 NEQ
+ 22 BRANCHIFNOT 29
+ 24 GETGLOBAL Not_found
+ 26 MAKEBLOCK1 0
+ 28 RAISE
+ 29 POP 1
+ 31 ATOM0
+ 32 SETGLOBAL T121-setstringchar
+ 34 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t130-getvectitem.ml b/testsuite/tests/tool-ocaml/t130-getvectitem.ml
new file mode 100644
index 0000000000..d290379592
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t130-getvectitem.ml
@@ -0,0 +1,24 @@
+open Lib;;
+if [| 1; 2 |].(1) <> 2 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST2
+ 10 PUSHCONST1
+ 11 PUSHCONST2
+ 12 PUSHCONST1
+ 13 MAKEBLOCK2 0
+ 15 GETVECTITEM
+ 16 NEQ
+ 17 BRANCHIFNOT 24
+ 19 GETGLOBAL Not_found
+ 21 MAKEBLOCK1 0
+ 23 RAISE
+ 24 ATOM0
+ 25 SETGLOBAL T130-getvectitem
+ 27 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t130-vectlength.ml b/testsuite/tests/tool-ocaml/t130-vectlength.ml
new file mode 100644
index 0000000000..ce0da0e420
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t130-vectlength.ml
@@ -0,0 +1,23 @@
+open Lib;;
+if Array.length [| 1; 2 |] <> 2 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST2
+ 10 PUSHCONST2
+ 11 PUSHCONST1
+ 12 MAKEBLOCK2 0
+ 14 VECTLENGTH
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 ATOM0
+ 24 SETGLOBAL T130-vectlength
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t131-setvectitem.ml b/testsuite/tests/tool-ocaml/t131-setvectitem.ml
new file mode 100644
index 0000000000..f544a3e0a1
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t131-setvectitem.ml
@@ -0,0 +1,33 @@
+open Lib;;
+let x = [| 1; 2 |] in
+x.(0) <- 3;
+if x.(0) <> 3 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST2
+ 10 PUSHCONST1
+ 11 MAKEBLOCK2 0
+ 13 PUSHCONST3
+ 14 PUSHCONST0
+ 15 PUSHACC2
+ 16 SETVECTITEM
+ 17 CONST3
+ 18 PUSHCONST0
+ 19 PUSHACC2
+ 20 GETVECTITEM
+ 21 NEQ
+ 22 BRANCHIFNOT 29
+ 24 GETGLOBAL Not_found
+ 26 MAKEBLOCK1 0
+ 28 RAISE
+ 29 POP 1
+ 31 ATOM0
+ 32 SETGLOBAL T131-setvectitem
+ 34 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t140-switch-1.ml b/testsuite/tests/tool-ocaml/t140-switch-1.ml
new file mode 100644
index 0000000000..b2d7352156
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t140-switch-1.ml
@@ -0,0 +1,32 @@
+open Lib;;
+match 0 with
+| 0 -> ()
+| 1 -> raise Not_found
+| _ -> raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHACC0
+ 11 SWITCH
+ int 0 -> 17
+ int 1 -> 20
+ 15 BRANCH 25
+ 17 CONST0
+ 18 BRANCH 30
+ 20 GETGLOBAL Not_found
+ 22 MAKEBLOCK1 0
+ 24 RAISE
+ 25 GETGLOBAL Not_found
+ 27 MAKEBLOCK1 0
+ 29 RAISE
+ 30 POP 1
+ 32 ATOM0
+ 33 SETGLOBAL T140-switch-1
+ 35 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t140-switch-2.ml b/testsuite/tests/tool-ocaml/t140-switch-2.ml
new file mode 100644
index 0000000000..9004fa66bb
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t140-switch-2.ml
@@ -0,0 +1,32 @@
+open Lib;;
+match 1 with
+| 0 -> raise Not_found
+| 1 -> ()
+| _ -> raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHACC0
+ 11 SWITCH
+ int 0 -> 17
+ int 1 -> 22
+ 15 BRANCH 25
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 CONST0
+ 23 BRANCH 30
+ 25 GETGLOBAL Not_found
+ 27 MAKEBLOCK1 0
+ 29 RAISE
+ 30 POP 1
+ 32 ATOM0
+ 33 SETGLOBAL T140-switch-2
+ 35 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t140-switch-3.ml b/testsuite/tests/tool-ocaml/t140-switch-3.ml
new file mode 100644
index 0000000000..b0c4bc8f75
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t140-switch-3.ml
@@ -0,0 +1,31 @@
+open Lib;;
+match 2 with
+| 0 -> raise Not_found
+| 1 -> raise Not_found
+| _ -> ()
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST2
+ 10 PUSHACC0
+ 11 SWITCH
+ int 0 -> 17
+ int 1 -> 22
+ 15 BRANCH 27
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 GETGLOBAL Not_found
+ 24 MAKEBLOCK1 0
+ 26 RAISE
+ 27 CONST0
+ 28 POP 1
+ 30 ATOM0
+ 31 SETGLOBAL T140-switch-3
+ 33 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t140-switch-4.ml b/testsuite/tests/tool-ocaml/t140-switch-4.ml
new file mode 100644
index 0000000000..1826b09e5d
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t140-switch-4.ml
@@ -0,0 +1,31 @@
+open Lib;;
+match -1 with
+| 0 -> raise Not_found
+| 1 -> raise Not_found
+| _ -> ()
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT -1
+ 11 PUSHACC0
+ 12 SWITCH
+ int 0 -> 18
+ int 1 -> 23
+ 16 BRANCH 28
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 GETGLOBAL Not_found
+ 25 MAKEBLOCK1 0
+ 27 RAISE
+ 28 CONST0
+ 29 POP 1
+ 31 ATOM0
+ 32 SETGLOBAL T140-switch-4
+ 34 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t141-switch-5.ml b/testsuite/tests/tool-ocaml/t141-switch-5.ml
new file mode 100644
index 0000000000..ca44849e22
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t141-switch-5.ml
@@ -0,0 +1,38 @@
+open Lib;;
+type t =
+ | A of int
+ | B of int
+ | C of int
+;;
+
+match A 0 with
+| A _ -> ()
+| B _ -> raise Not_found
+| _ -> raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL <0>(0)
+ 11 PUSHACC0
+ 12 SWITCH
+ tag 0 -> 17
+ tag 1 -> 20
+ tag 2 -> 25
+ 17 CONST0
+ 18 BRANCH 30
+ 20 GETGLOBAL Not_found
+ 22 MAKEBLOCK1 0
+ 24 RAISE
+ 25 GETGLOBAL Not_found
+ 27 MAKEBLOCK1 0
+ 29 RAISE
+ 30 POP 1
+ 32 ATOM0
+ 33 SETGLOBAL T141-switch-5
+ 35 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t141-switch-6.ml b/testsuite/tests/tool-ocaml/t141-switch-6.ml
new file mode 100644
index 0000000000..c48e80b5f7
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t141-switch-6.ml
@@ -0,0 +1,38 @@
+open Lib;;
+type t =
+ | A of int
+ | B of int
+ | C of int
+;;
+
+match B 0 with
+| A _ -> raise Not_found
+| B _ -> ()
+| _ -> raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL <1>(0)
+ 11 PUSHACC0
+ 12 SWITCH
+ tag 0 -> 17
+ tag 1 -> 22
+ tag 2 -> 25
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 CONST0
+ 23 BRANCH 30
+ 25 GETGLOBAL Not_found
+ 27 MAKEBLOCK1 0
+ 29 RAISE
+ 30 POP 1
+ 32 ATOM0
+ 33 SETGLOBAL T141-switch-6
+ 35 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t141-switch-7.ml b/testsuite/tests/tool-ocaml/t141-switch-7.ml
new file mode 100644
index 0000000000..00f4873cdf
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t141-switch-7.ml
@@ -0,0 +1,37 @@
+open Lib;;
+type t =
+ | A of int
+ | B of int
+ | C of int
+;;
+
+match C 0 with
+| A _ -> raise Not_found
+| B _ -> raise Not_found
+| _ -> ()
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL <2>(0)
+ 11 PUSHACC0
+ 12 SWITCH
+ tag 0 -> 17
+ tag 1 -> 22
+ tag 2 -> 27
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 GETGLOBAL Not_found
+ 24 MAKEBLOCK1 0
+ 26 RAISE
+ 27 CONST0
+ 28 POP 1
+ 30 ATOM0
+ 31 SETGLOBAL T141-switch-7
+ 33 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t142-switch-8.ml b/testsuite/tests/tool-ocaml/t142-switch-8.ml
new file mode 100644
index 0000000000..51459130a5
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t142-switch-8.ml
@@ -0,0 +1,34 @@
+open Lib;;
+type t =
+ | A
+ | B of int
+ | C of int
+;;
+
+match A with
+| A -> ()
+| _ -> raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHACC0
+ 11 SWITCH
+ int 0 -> 16
+ tag 0 -> 19
+ tag 1 -> 19
+ 16 CONST0
+ 17 BRANCH 24
+ 19 GETGLOBAL Not_found
+ 21 MAKEBLOCK1 0
+ 23 RAISE
+ 24 POP 1
+ 26 ATOM0
+ 27 SETGLOBAL T142-switch-8
+ 29 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t142-switch-9.ml b/testsuite/tests/tool-ocaml/t142-switch-9.ml
new file mode 100644
index 0000000000..a0e43d3217
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t142-switch-9.ml
@@ -0,0 +1,34 @@
+open Lib;;
+type t =
+ | A
+ | B of int
+ | C of int
+;;
+
+match B 0 with
+| B _ -> ()
+| _ -> raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL <0>(0)
+ 11 PUSHACC0
+ 12 SWITCH
+ int 0 -> 20
+ tag 0 -> 17
+ tag 1 -> 20
+ 17 CONST0
+ 18 BRANCH 25
+ 20 GETGLOBAL Not_found
+ 22 MAKEBLOCK1 0
+ 24 RAISE
+ 25 POP 1
+ 27 ATOM0
+ 28 SETGLOBAL T142-switch-9
+ 30 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t142-switch-A.ml b/testsuite/tests/tool-ocaml/t142-switch-A.ml
new file mode 100644
index 0000000000..4f66aec587
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t142-switch-A.ml
@@ -0,0 +1,34 @@
+open Lib;;
+type t =
+ | A
+ | B of int
+ | C of int
+;;
+
+match C 0 with
+| C _ -> ()
+| _ -> raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL <1>(0)
+ 11 PUSHACC0
+ 12 SWITCH
+ int 0 -> 20
+ tag 0 -> 20
+ tag 1 -> 17
+ 17 CONST0
+ 18 BRANCH 25
+ 20 GETGLOBAL Not_found
+ 22 MAKEBLOCK1 0
+ 24 RAISE
+ 25 POP 1
+ 27 ATOM0
+ 28 SETGLOBAL T142-switch-A
+ 30 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t150-push-1.ml b/testsuite/tests/tool-ocaml/t150-push-1.ml
new file mode 100644
index 0000000000..9264927777
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t150-push-1.ml
@@ -0,0 +1,24 @@
+open Lib;;
+let _ = 0 in
+try 0 with _ -> 0
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSH
+ 11 PUSHTRAP 17
+ 13 CONST0
+ 14 POPTRAP
+ 15 BRANCH 20
+ 17 PUSHCONST0
+ 18 POP 1
+ 20 POP 1
+ 22 ATOM0
+ 23 SETGLOBAL T150-push-1
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t150-push-2.ml b/testsuite/tests/tool-ocaml/t150-push-2.ml
new file mode 100644
index 0000000000..d6f5107260
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t150-push-2.ml
@@ -0,0 +1,39 @@
+open Lib;;
+let x = 1 in
+try if x <> 1 then raise Not_found
+with End_of_file -> ()
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSH
+ 11 PUSHTRAP 26
+ 13 CONST1
+ 14 PUSHACC5
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 POPTRAP
+ 24 BRANCH 40
+ 26 PUSHGETGLOBAL End_of_file
+ 28 PUSHACC1
+ 29 GETFIELD0
+ 30 EQ
+ 31 BRANCHIFNOT 36
+ 33 CONST0
+ 34 BRANCH 38
+ 36 ACC0
+ 37 RAISE
+ 38 POP 1
+ 40 POP 1
+ 42 ATOM0
+ 43 SETGLOBAL T150-push-2
+ 45 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t160-closure.ml b/testsuite/tests/tool-ocaml/t160-closure.ml
new file mode 100644
index 0000000000..5eb612865a
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t160-closure.ml
@@ -0,0 +1,19 @@
+open Lib;;
+let f () = ();;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 14
+ 11 CONST0
+ 12 RETURN 1
+ 14 CLOSURE 0, 11
+ 17 PUSHACC0
+ 18 MAKEBLOCK1 0
+ 20 POP 1
+ 22 SETGLOBAL T160-closure
+ 24 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t161-apply1.ml b/testsuite/tests/tool-ocaml/t161-apply1.ml
new file mode 100644
index 0000000000..5138c5f581
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t161-apply1.ml
@@ -0,0 +1,42 @@
+open Lib;;
+let f _ = raise End_of_file in
+try
+ f 0;
+ raise Not_found;
+with End_of_file -> 0
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 16
+ 11 GETGLOBAL End_of_file
+ 13 MAKEBLOCK1 0
+ 15 RAISE
+ 16 CLOSURE 0, 11
+ 19 PUSH
+ 20 PUSHTRAP 30
+ 22 CONST0
+ 23 PUSHACC5
+ 24 APPLY1
+ 25 GETGLOBAL Not_found
+ 27 MAKEBLOCK1 0
+ 29 RAISE
+ 30 PUSHGETGLOBAL End_of_file
+ 32 PUSHACC1
+ 33 GETFIELD0
+ 34 EQ
+ 35 BRANCHIFNOT 40
+ 37 CONST0
+ 38 BRANCH 42
+ 40 ACC0
+ 41 RAISE
+ 42 POP 1
+ 44 POP 1
+ 46 ATOM0
+ 47 SETGLOBAL T161-apply1
+ 49 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t162-return.ml b/testsuite/tests/tool-ocaml/t162-return.ml
new file mode 100644
index 0000000000..1059c9fea2
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t162-return.ml
@@ -0,0 +1,21 @@
+open Lib;;
+let f _ = 0 in f 0;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 14
+ 11 CONST0
+ 12 RETURN 1
+ 14 CLOSURE 0, 11
+ 17 PUSHCONST0
+ 18 PUSHACC1
+ 19 APPLY1
+ 20 POP 1
+ 22 ATOM0
+ 23 SETGLOBAL T162-return
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t163.ml b/testsuite/tests/tool-ocaml/t163.ml
new file mode 100644
index 0000000000..9ec7790c53
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t163.ml
@@ -0,0 +1,23 @@
+open Lib;;
+let f _ _ = 0 in f 0;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 17
+ 11 RESTART
+ 12 GRAB 1
+ 14 CONST0
+ 15 RETURN 2
+ 17 CLOSURE 0, 12
+ 20 PUSHCONST0
+ 21 PUSHACC1
+ 22 APPLY1
+ 23 POP 1
+ 25 ATOM0
+ 26 SETGLOBAL T163
+ 28 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t164-apply2.ml b/testsuite/tests/tool-ocaml/t164-apply2.ml
new file mode 100644
index 0000000000..7fbe7d9974
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t164-apply2.ml
@@ -0,0 +1,24 @@
+open Lib;;
+let f _ _ = 0 in f 0 0;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 17
+ 11 RESTART
+ 12 GRAB 1
+ 14 CONST0
+ 15 RETURN 2
+ 17 CLOSURE 0, 12
+ 20 PUSHCONST0
+ 21 PUSHCONST0
+ 22 PUSHACC2
+ 23 APPLY2
+ 24 POP 1
+ 26 ATOM0
+ 27 SETGLOBAL T164-apply2
+ 29 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t164-apply3.ml b/testsuite/tests/tool-ocaml/t164-apply3.ml
new file mode 100644
index 0000000000..e7ebc3a400
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t164-apply3.ml
@@ -0,0 +1,25 @@
+open Lib;;
+let f _ _ _ = 0 in f 0 0 0;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 17
+ 11 RESTART
+ 12 GRAB 2
+ 14 CONST0
+ 15 RETURN 3
+ 17 CLOSURE 0, 12
+ 20 PUSHCONST0
+ 21 PUSHCONST0
+ 22 PUSHCONST0
+ 23 PUSHACC3
+ 24 APPLY3
+ 25 POP 1
+ 27 ATOM0
+ 28 SETGLOBAL T164-apply3
+ 30 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t165-apply.ml b/testsuite/tests/tool-ocaml/t165-apply.ml
new file mode 100644
index 0000000000..9d66855061
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t165-apply.ml
@@ -0,0 +1,28 @@
+open Lib;;
+let f _ _ _ _ = 0 in f 0 0 0 0;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 17
+ 11 RESTART
+ 12 GRAB 3
+ 14 CONST0
+ 15 RETURN 4
+ 17 CLOSURE 0, 12
+ 20 PUSH
+ 21 PUSH_RETADDR 30
+ 23 CONST0
+ 24 PUSHCONST0
+ 25 PUSHCONST0
+ 26 PUSHCONST0
+ 27 PUSHACC7
+ 28 APPLY 4
+ 30 POP 1
+ 32 ATOM0
+ 33 SETGLOBAL T165-apply
+ 35 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t170-envacc2.ml b/testsuite/tests/tool-ocaml/t170-envacc2.ml
new file mode 100644
index 0000000000..3a37366723
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t170-envacc2.ml
@@ -0,0 +1,37 @@
+open Lib;;
+let x = 5 in
+let y = 2 in
+let f _ = ignore x; y in
+if f 0 <> 2 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 16
+ 11 ENVACC1
+ 12 CONST0
+ 13 ENVACC2
+ 14 RETURN 1
+ 16 CONSTINT 5
+ 18 PUSHCONST2
+ 19 PUSHACC0
+ 20 PUSHACC2
+ 21 CLOSURE 2, 11
+ 24 PUSHCONST2
+ 25 PUSHCONST0
+ 26 PUSHACC2
+ 27 APPLY1
+ 28 NEQ
+ 29 BRANCHIFNOT 36
+ 31 GETGLOBAL Not_found
+ 33 MAKEBLOCK1 0
+ 35 RAISE
+ 36 POP 3
+ 38 ATOM0
+ 39 SETGLOBAL T170-envacc2
+ 41 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t170-envacc3.ml b/testsuite/tests/tool-ocaml/t170-envacc3.ml
new file mode 100644
index 0000000000..9a2b8b5a8f
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t170-envacc3.ml
@@ -0,0 +1,42 @@
+open Lib;;
+let x = 5 in
+let y = 2 in
+let z = 1 in
+let f _ = ignore x; ignore y; z in
+if f 0 <> 1 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 18
+ 11 ENVACC1
+ 12 CONST0
+ 13 ENVACC2
+ 14 CONST0
+ 15 ENVACC3
+ 16 RETURN 1
+ 18 CONSTINT 5
+ 20 PUSHCONST2
+ 21 PUSHCONST1
+ 22 PUSHACC0
+ 23 PUSHACC2
+ 24 PUSHACC4
+ 25 CLOSURE 3, 11
+ 28 PUSHCONST1
+ 29 PUSHCONST0
+ 30 PUSHACC2
+ 31 APPLY1
+ 32 NEQ
+ 33 BRANCHIFNOT 40
+ 35 GETGLOBAL Not_found
+ 37 MAKEBLOCK1 0
+ 39 RAISE
+ 40 POP 4
+ 42 ATOM0
+ 43 SETGLOBAL T170-envacc3
+ 45 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t170-envacc4.ml b/testsuite/tests/tool-ocaml/t170-envacc4.ml
new file mode 100644
index 0000000000..215e322078
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t170-envacc4.ml
@@ -0,0 +1,47 @@
+open Lib;;
+let x = 5 in
+let y = 2 in
+let z = 1 in
+let a = 4 in
+let f _ = ignore x; ignore y; ignore z; a in
+if f 0 <> 4 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 20
+ 11 ENVACC1
+ 12 CONST0
+ 13 ENVACC2
+ 14 CONST0
+ 15 ENVACC3
+ 16 CONST0
+ 17 ENVACC4
+ 18 RETURN 1
+ 20 CONSTINT 5
+ 22 PUSHCONST2
+ 23 PUSHCONST1
+ 24 PUSHCONSTINT 4
+ 26 PUSHACC0
+ 27 PUSHACC2
+ 28 PUSHACC4
+ 29 PUSHACC6
+ 30 CLOSURE 4, 11
+ 33 PUSHCONSTINT 4
+ 35 PUSHCONST0
+ 36 PUSHACC2
+ 37 APPLY1
+ 38 NEQ
+ 39 BRANCHIFNOT 46
+ 41 GETGLOBAL Not_found
+ 43 MAKEBLOCK1 0
+ 45 RAISE
+ 46 POP 5
+ 48 ATOM0
+ 49 SETGLOBAL T170-envacc4
+ 51 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t171-envacc.ml b/testsuite/tests/tool-ocaml/t171-envacc.ml
new file mode 100644
index 0000000000..4c4a3dfac9
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t171-envacc.ml
@@ -0,0 +1,52 @@
+open Lib;;
+let x = 5 in
+let y = 2 in
+let z = 1 in
+let a = 4 in
+let b = 3 in
+let f _ = ignore x; ignore y; ignore z; ignore a; b in
+if f 0 <> 3 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 23
+ 11 ENVACC1
+ 12 CONST0
+ 13 ENVACC2
+ 14 CONST0
+ 15 ENVACC3
+ 16 CONST0
+ 17 ENVACC4
+ 18 CONST0
+ 19 ENVACC 5
+ 21 RETURN 1
+ 23 CONSTINT 5
+ 25 PUSHCONST2
+ 26 PUSHCONST1
+ 27 PUSHCONSTINT 4
+ 29 PUSHCONST3
+ 30 PUSHACC0
+ 31 PUSHACC2
+ 32 PUSHACC4
+ 33 PUSHACC6
+ 34 PUSHACC 8
+ 36 CLOSURE 5, 11
+ 39 PUSHCONST3
+ 40 PUSHCONST0
+ 41 PUSHACC2
+ 42 APPLY1
+ 43 NEQ
+ 44 BRANCHIFNOT 51
+ 46 GETGLOBAL Not_found
+ 48 MAKEBLOCK1 0
+ 50 RAISE
+ 51 POP 6
+ 53 ATOM0
+ 54 SETGLOBAL T171-envacc
+ 56 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t172-pushenvacc1.ml b/testsuite/tests/tool-ocaml/t172-pushenvacc1.ml
new file mode 100644
index 0000000000..06c4011a01
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t172-pushenvacc1.ml
@@ -0,0 +1,34 @@
+open Lib;;
+let x = 5 in
+let f _ = x + x in
+if f 0 <> 10 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 16
+ 11 ENVACC1
+ 12 PUSHENVACC1
+ 13 ADDINT
+ 14 RETURN 1
+ 16 CONSTINT 5
+ 18 PUSHACC0
+ 19 CLOSURE 1, 11
+ 22 PUSHCONSTINT 10
+ 24 PUSHCONST0
+ 25 PUSHACC2
+ 26 APPLY1
+ 27 NEQ
+ 28 BRANCHIFNOT 35
+ 30 GETGLOBAL Not_found
+ 32 MAKEBLOCK1 0
+ 34 RAISE
+ 35 POP 2
+ 37 ATOM0
+ 38 SETGLOBAL T172-pushenvacc1
+ 40 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t172-pushenvacc2.ml b/testsuite/tests/tool-ocaml/t172-pushenvacc2.ml
new file mode 100644
index 0000000000..c25e40a71a
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t172-pushenvacc2.ml
@@ -0,0 +1,37 @@
+open Lib;;
+let x = 5 in
+let y = 4 in
+let f _ = y + x in
+if f 0 <> 9 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 16
+ 11 ENVACC1
+ 12 PUSHENVACC2
+ 13 ADDINT
+ 14 RETURN 1
+ 16 CONSTINT 5
+ 18 PUSHCONSTINT 4
+ 20 PUSHACC0
+ 21 PUSHACC2
+ 22 CLOSURE 2, 11
+ 25 PUSHCONSTINT 9
+ 27 PUSHCONST0
+ 28 PUSHACC2
+ 29 APPLY1
+ 30 NEQ
+ 31 BRANCHIFNOT 38
+ 33 GETGLOBAL Not_found
+ 35 MAKEBLOCK1 0
+ 37 RAISE
+ 38 POP 3
+ 40 ATOM0
+ 41 SETGLOBAL T172-pushenvacc2
+ 43 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t172-pushenvacc3.ml b/testsuite/tests/tool-ocaml/t172-pushenvacc3.ml
new file mode 100644
index 0000000000..093f7f1e4e
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t172-pushenvacc3.ml
@@ -0,0 +1,42 @@
+open Lib;;
+let x = 5 in
+let y = 4 in
+let z = 3 in
+let f _ = z + y + x in
+if f 0 <> 12 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 18
+ 11 ENVACC1
+ 12 PUSHENVACC2
+ 13 PUSHENVACC3
+ 14 ADDINT
+ 15 ADDINT
+ 16 RETURN 1
+ 18 CONSTINT 5
+ 20 PUSHCONSTINT 4
+ 22 PUSHCONST3
+ 23 PUSHACC0
+ 24 PUSHACC2
+ 25 PUSHACC4
+ 26 CLOSURE 3, 11
+ 29 PUSHCONSTINT 12
+ 31 PUSHCONST0
+ 32 PUSHACC2
+ 33 APPLY1
+ 34 NEQ
+ 35 BRANCHIFNOT 42
+ 37 GETGLOBAL Not_found
+ 39 MAKEBLOCK1 0
+ 41 RAISE
+ 42 POP 4
+ 44 ATOM0
+ 45 SETGLOBAL T172-pushenvacc3
+ 47 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t172-pushenvacc4.ml b/testsuite/tests/tool-ocaml/t172-pushenvacc4.ml
new file mode 100644
index 0000000000..154c4a4715
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t172-pushenvacc4.ml
@@ -0,0 +1,47 @@
+open Lib;;
+let x = 5 in
+let y = 4 in
+let z = 3 in
+let a = 2 in
+let f _ = a + z + y + x in
+if f 0 <> 14 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 21
+ 11 ENVACC1
+ 12 PUSHENVACC2
+ 13 PUSHENVACC3
+ 14 PUSHENVACC 4
+ 16 ADDINT
+ 17 ADDINT
+ 18 ADDINT
+ 19 RETURN 1
+ 21 CONSTINT 5
+ 23 PUSHCONSTINT 4
+ 25 PUSHCONST3
+ 26 PUSHCONST2
+ 27 PUSHACC0
+ 28 PUSHACC2
+ 29 PUSHACC4
+ 30 PUSHACC6
+ 31 CLOSURE 4, 11
+ 34 PUSHCONSTINT 14
+ 36 PUSHCONST0
+ 37 PUSHACC2
+ 38 APPLY1
+ 39 NEQ
+ 40 BRANCHIFNOT 47
+ 42 GETGLOBAL Not_found
+ 44 MAKEBLOCK1 0
+ 46 RAISE
+ 47 POP 5
+ 49 ATOM0
+ 50 SETGLOBAL T172-pushenvacc4
+ 52 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t173-pushenvacc.ml b/testsuite/tests/tool-ocaml/t173-pushenvacc.ml
new file mode 100644
index 0000000000..0d858b4aa2
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t173-pushenvacc.ml
@@ -0,0 +1,52 @@
+open Lib;;
+let x = 5 in
+let y = 4 in
+let z = 3 in
+let a = 2 in
+let b = 1 in
+let f _ = b + a + z + y + x in
+if f 0 <> 15 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 24
+ 11 ENVACC1
+ 12 PUSHENVACC2
+ 13 PUSHENVACC3
+ 14 PUSHENVACC 4
+ 16 PUSHENVACC 5
+ 18 ADDINT
+ 19 ADDINT
+ 20 ADDINT
+ 21 ADDINT
+ 22 RETURN 1
+ 24 CONSTINT 5
+ 26 PUSHCONSTINT 4
+ 28 PUSHCONST3
+ 29 PUSHCONST2
+ 30 PUSHCONST1
+ 31 PUSHACC0
+ 32 PUSHACC2
+ 33 PUSHACC4
+ 34 PUSHACC6
+ 35 PUSHACC 8
+ 37 CLOSURE 5, 11
+ 40 PUSHCONSTINT 15
+ 42 PUSHCONST0
+ 43 PUSHACC2
+ 44 APPLY1
+ 45 NEQ
+ 46 BRANCHIFNOT 53
+ 48 GETGLOBAL Not_found
+ 50 MAKEBLOCK1 0
+ 52 RAISE
+ 53 POP 6
+ 55 ATOM0
+ 56 SETGLOBAL T173-pushenvacc
+ 58 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t180-appterm1.ml b/testsuite/tests/tool-ocaml/t180-appterm1.ml
new file mode 100644
index 0000000000..6b82f51b61
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t180-appterm1.ml
@@ -0,0 +1,35 @@
+open Lib;;
+let f _ = 12 in
+let g _ = f 0 in
+if g 0 <> 12 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 19
+ 11 CONST0
+ 12 PUSHENVACC1
+ 13 APPTERM1 2
+ 15 CONSTINT 12
+ 17 RETURN 1
+ 19 CLOSURE 0, 15
+ 22 PUSHACC0
+ 23 CLOSURE 1, 11
+ 26 PUSHCONSTINT 12
+ 28 PUSHCONST0
+ 29 PUSHACC2
+ 30 APPLY1
+ 31 NEQ
+ 32 BRANCHIFNOT 39
+ 34 GETGLOBAL Not_found
+ 36 MAKEBLOCK1 0
+ 38 RAISE
+ 39 POP 2
+ 41 ATOM0
+ 42 SETGLOBAL T180-appterm1
+ 44 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t180-appterm2.ml b/testsuite/tests/tool-ocaml/t180-appterm2.ml
new file mode 100644
index 0000000000..28f32a9336
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t180-appterm2.ml
@@ -0,0 +1,38 @@
+open Lib;;
+let f _ _ = 12 in
+let g _ = f 0 0 in
+if g 0 <> 12 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 23
+ 11 CONST0
+ 12 PUSHCONST0
+ 13 PUSHENVACC1
+ 14 APPTERM2 3
+ 16 RESTART
+ 17 GRAB 1
+ 19 CONSTINT 12
+ 21 RETURN 2
+ 23 CLOSURE 0, 17
+ 26 PUSHACC0
+ 27 CLOSURE 1, 11
+ 30 PUSHCONSTINT 12
+ 32 PUSHCONST0
+ 33 PUSHACC2
+ 34 APPLY1
+ 35 NEQ
+ 36 BRANCHIFNOT 43
+ 38 GETGLOBAL Not_found
+ 40 MAKEBLOCK1 0
+ 42 RAISE
+ 43 POP 2
+ 45 ATOM0
+ 46 SETGLOBAL T180-appterm2
+ 48 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t180-appterm3.ml b/testsuite/tests/tool-ocaml/t180-appterm3.ml
new file mode 100644
index 0000000000..fe8a0bd5cf
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t180-appterm3.ml
@@ -0,0 +1,39 @@
+open Lib;;
+let f _ _ _ = 13 in
+let g _ = f 0 0 0 in
+if g 0 <> 13 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 24
+ 11 CONST0
+ 12 PUSHCONST0
+ 13 PUSHCONST0
+ 14 PUSHENVACC1
+ 15 APPTERM3 4
+ 17 RESTART
+ 18 GRAB 2
+ 20 CONSTINT 13
+ 22 RETURN 3
+ 24 CLOSURE 0, 18
+ 27 PUSHACC0
+ 28 CLOSURE 1, 11
+ 31 PUSHCONSTINT 13
+ 33 PUSHCONST0
+ 34 PUSHACC2
+ 35 APPLY1
+ 36 NEQ
+ 37 BRANCHIFNOT 44
+ 39 GETGLOBAL Not_found
+ 41 MAKEBLOCK1 0
+ 43 RAISE
+ 44 POP 2
+ 46 ATOM0
+ 47 SETGLOBAL T180-appterm3
+ 49 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t181-appterm.ml b/testsuite/tests/tool-ocaml/t181-appterm.ml
new file mode 100644
index 0000000000..03127bc8d3
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t181-appterm.ml
@@ -0,0 +1,40 @@
+open Lib;;
+let f _ _ _ _ = -10 in
+let g _ = f 0 0 0 0 in
+if g 0 <> -10 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 26
+ 11 CONST0
+ 12 PUSHCONST0
+ 13 PUSHCONST0
+ 14 PUSHCONST0
+ 15 PUSHENVACC1
+ 16 APPTERM 4, 5
+ 19 RESTART
+ 20 GRAB 3
+ 22 CONSTINT -10
+ 24 RETURN 4
+ 26 CLOSURE 0, 20
+ 29 PUSHACC0
+ 30 CLOSURE 1, 11
+ 33 PUSHCONSTINT -10
+ 35 PUSHCONST0
+ 36 PUSHACC2
+ 37 APPLY1
+ 38 NEQ
+ 39 BRANCHIFNOT 46
+ 41 GETGLOBAL Not_found
+ 43 MAKEBLOCK1 0
+ 45 RAISE
+ 46 POP 2
+ 48 ATOM0
+ 49 SETGLOBAL T181-appterm
+ 51 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t190-makefloatblock-1.ml b/testsuite/tests/tool-ocaml/t190-makefloatblock-1.ml
new file mode 100644
index 0000000000..f63c6cd8f9
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t190-makefloatblock-1.ml
@@ -0,0 +1,17 @@
+open Lib;;
+let x = 0.0 in [| x |];;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL 0
+ 11 PUSHACC0
+ 12 MAKEFLOATBLOCK 1
+ 14 POP 1
+ 16 ATOM0
+ 17 SETGLOBAL T190-makefloatblock-1
+ 19 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t190-makefloatblock-2.ml b/testsuite/tests/tool-ocaml/t190-makefloatblock-2.ml
new file mode 100644
index 0000000000..53b97f5d51
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t190-makefloatblock-2.ml
@@ -0,0 +1,18 @@
+open Lib;;
+let x = 0.0 in [| x; x |];;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL 0
+ 11 PUSHACC0
+ 12 PUSHACC1
+ 13 MAKEFLOATBLOCK 2
+ 15 POP 1
+ 17 ATOM0
+ 18 SETGLOBAL T190-makefloatblock-2
+ 20 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t190-makefloatblock-3.ml b/testsuite/tests/tool-ocaml/t190-makefloatblock-3.ml
new file mode 100644
index 0000000000..cebccaa38d
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t190-makefloatblock-3.ml
@@ -0,0 +1,19 @@
+open Lib;;
+let x = 0.0 in [| x; x; x |];;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL 0
+ 11 PUSHACC0
+ 12 PUSHACC1
+ 13 PUSHACC2
+ 14 MAKEFLOATBLOCK 3
+ 16 POP 1
+ 18 ATOM0
+ 19 SETGLOBAL T190-makefloatblock-3
+ 21 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t191-vectlength.ml b/testsuite/tests/tool-ocaml/t191-vectlength.ml
new file mode 100644
index 0000000000..16f7d783b1
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t191-vectlength.ml
@@ -0,0 +1,26 @@
+open Lib;;
+let x = 0.0 in
+if Array.length [| x |] <> 1 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL 0
+ 11 PUSHCONST1
+ 12 PUSHACC1
+ 13 MAKEFLOATBLOCK 1
+ 15 VECTLENGTH
+ 16 NEQ
+ 17 BRANCHIFNOT 24
+ 19 GETGLOBAL Not_found
+ 21 MAKEBLOCK1 0
+ 23 RAISE
+ 24 POP 1
+ 26 ATOM0
+ 27 SETGLOBAL T191-vectlength
+ 29 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t192-getfloatfield-1.ml b/testsuite/tests/tool-ocaml/t192-getfloatfield-1.ml
new file mode 100644
index 0000000000..ba002b20b1
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t192-getfloatfield-1.ml
@@ -0,0 +1,23 @@
+open Lib;;
+type t = { a : float; b : float };;
+
+if { a = 0.1; b = 0.2 }.a <> 0.1 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL 0.1
+ 11 PUSHGETGLOBAL [|0.1, 0.2|]
+ 13 GETFLOATFIELD 0
+ 15 C_CALL2 neq_float
+ 17 BRANCHIFNOT 24
+ 19 GETGLOBAL Not_found
+ 21 MAKEBLOCK1 0
+ 23 RAISE
+ 24 ATOM0
+ 25 SETGLOBAL T192-getfloatfield-1
+ 27 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t192-getfloatfield-2.ml b/testsuite/tests/tool-ocaml/t192-getfloatfield-2.ml
new file mode 100644
index 0000000000..89230da397
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t192-getfloatfield-2.ml
@@ -0,0 +1,23 @@
+open Lib;;
+type t = { a : float; b : float };;
+
+if { a = 0.1; b = 0.2 }.b <> 0.2 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL 0.2
+ 11 PUSHGETGLOBAL [|0.1, 0.2|]
+ 13 GETFLOATFIELD 1
+ 15 C_CALL2 neq_float
+ 17 BRANCHIFNOT 24
+ 19 GETGLOBAL Not_found
+ 21 MAKEBLOCK1 0
+ 23 RAISE
+ 24 ATOM0
+ 25 SETGLOBAL T192-getfloatfield-2
+ 27 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t193-setfloatfield-1.ml b/testsuite/tests/tool-ocaml/t193-setfloatfield-1.ml
new file mode 100644
index 0000000000..b488e7daad
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t193-setfloatfield-1.ml
@@ -0,0 +1,36 @@
+open Lib;;
+type t = {
+ mutable a : float;
+ mutable b : float;
+};;
+
+let x = { a = 0.1; b = 0.2 } in
+x.a <- 0.3;
+if x.a <> 0.3 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL 0.2
+ 11 PUSHGETGLOBAL 0.1
+ 13 MAKEFLOATBLOCK 2
+ 15 PUSHGETGLOBAL 0.3
+ 17 PUSHACC1
+ 18 SETFLOATFIELD 0
+ 20 GETGLOBAL 0.3
+ 22 PUSHACC1
+ 23 GETFLOATFIELD 0
+ 25 C_CALL2 neq_float
+ 27 BRANCHIFNOT 34
+ 29 GETGLOBAL Not_found
+ 31 MAKEBLOCK1 0
+ 33 RAISE
+ 34 POP 1
+ 36 ATOM0
+ 37 SETGLOBAL T193-setfloatfield-1
+ 39 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t193-setfloatfield-2.ml b/testsuite/tests/tool-ocaml/t193-setfloatfield-2.ml
new file mode 100644
index 0000000000..7dde0a2cf5
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t193-setfloatfield-2.ml
@@ -0,0 +1,36 @@
+open Lib;;
+type t = {
+ mutable a : float;
+ mutable b : float;
+};;
+
+let x = { a = 0.1; b = 0.2 } in
+x.b <- 0.3;
+if x.b <> 0.3 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL 0.2
+ 11 PUSHGETGLOBAL 0.1
+ 13 MAKEFLOATBLOCK 2
+ 15 PUSHGETGLOBAL 0.3
+ 17 PUSHACC1
+ 18 SETFLOATFIELD 1
+ 20 GETGLOBAL 0.3
+ 22 PUSHACC1
+ 23 GETFLOATFIELD 1
+ 25 C_CALL2 neq_float
+ 27 BRANCHIFNOT 34
+ 29 GETGLOBAL Not_found
+ 31 MAKEBLOCK1 0
+ 33 RAISE
+ 34 POP 1
+ 36 ATOM0
+ 37 SETGLOBAL T193-setfloatfield-2
+ 39 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t200-getfield0.ml b/testsuite/tests/tool-ocaml/t200-getfield0.ml
new file mode 100644
index 0000000000..14ce1d547d
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t200-getfield0.ml
@@ -0,0 +1,25 @@
+open Lib;;
+type t = {
+ a : int;
+};;
+
+if { a = 7 }.a <> 7 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 7
+ 11 PUSHGETGLOBAL <0>(7)
+ 13 GETFIELD0
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T200-getfield0
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t200-getfield1.ml b/testsuite/tests/tool-ocaml/t200-getfield1.ml
new file mode 100644
index 0000000000..f4e2e01907
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t200-getfield1.ml
@@ -0,0 +1,26 @@
+open Lib;;
+type t = {
+ a : int;
+ b : int;
+};;
+
+if { a = 7; b = 6 }.b <> 6 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 6
+ 11 PUSHGETGLOBAL <0>(7, 6)
+ 13 GETFIELD1
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T200-getfield1
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t200-getfield2.ml b/testsuite/tests/tool-ocaml/t200-getfield2.ml
new file mode 100644
index 0000000000..df5c7172d0
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t200-getfield2.ml
@@ -0,0 +1,27 @@
+open Lib;;
+type t = {
+ a : int;
+ b : int;
+ c : int;
+};;
+
+if { a = 7; b = 6; c = 5 }.c <> 5 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 5
+ 11 PUSHGETGLOBAL <0>(7, 6, 5)
+ 13 GETFIELD2
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T200-getfield2
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t200-getfield3.ml b/testsuite/tests/tool-ocaml/t200-getfield3.ml
new file mode 100644
index 0000000000..a0376a1fcf
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t200-getfield3.ml
@@ -0,0 +1,28 @@
+open Lib;;
+type t = {
+ a : int;
+ b : int;
+ c : int;
+ d : int;
+};;
+
+if { a = 7; b = 6; c = 5; d = 4 }.d <> 4 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 4
+ 11 PUSHGETGLOBAL <0>(7, 6, 5, 4)
+ 13 GETFIELD3
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T200-getfield3
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t201-getfield.ml b/testsuite/tests/tool-ocaml/t201-getfield.ml
new file mode 100644
index 0000000000..0fbbc63fee
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t201-getfield.ml
@@ -0,0 +1,29 @@
+open Lib;;
+type t = {
+ a : int;
+ b : int;
+ c : int;
+ d : int;
+ e : int;
+};;
+
+if { a = 7; b = 6; c = 5; d = 4; e = 3 }.e <> 3 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST3
+ 10 PUSHGETGLOBAL <0>(7, 6, 5, 4, 3)
+ 12 GETFIELD 4
+ 14 NEQ
+ 15 BRANCHIFNOT 22
+ 17 GETGLOBAL Not_found
+ 19 MAKEBLOCK1 0
+ 21 RAISE
+ 22 ATOM0
+ 23 SETGLOBAL T201-getfield
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t210-setfield0.ml b/testsuite/tests/tool-ocaml/t210-setfield0.ml
new file mode 100644
index 0000000000..aa31d41fe4
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t210-setfield0.ml
@@ -0,0 +1,36 @@
+open Lib;;
+type t = {
+ mutable a : int;
+};;
+
+let x = {a = 7} in
+x.a <- 11;
+if x.a <> 11 then raise Not_found;
+x
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 7
+ 11 MAKEBLOCK1 0
+ 13 PUSHCONSTINT 11
+ 15 PUSHACC1
+ 16 SETFIELD0
+ 17 CONSTINT 11
+ 19 PUSHACC1
+ 20 GETFIELD0
+ 21 NEQ
+ 22 BRANCHIFNOT 29
+ 24 GETGLOBAL Not_found
+ 26 MAKEBLOCK1 0
+ 28 RAISE
+ 29 ACC0
+ 30 POP 1
+ 32 ATOM0
+ 33 SETGLOBAL T210-setfield0
+ 35 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t210-setfield1.ml b/testsuite/tests/tool-ocaml/t210-setfield1.ml
new file mode 100644
index 0000000000..0d8e16762c
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t210-setfield1.ml
@@ -0,0 +1,38 @@
+open Lib;;
+type t = {
+ mutable a : int;
+ mutable b : int;
+};;
+
+let x = {a = 7; b = 6} in
+x.b <- 11;
+if x.b <> 11 then raise Not_found;
+x
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 6
+ 11 PUSHCONSTINT 7
+ 13 MAKEBLOCK2 0
+ 15 PUSHCONSTINT 11
+ 17 PUSHACC1
+ 18 SETFIELD1
+ 19 CONSTINT 11
+ 21 PUSHACC1
+ 22 GETFIELD1
+ 23 NEQ
+ 24 BRANCHIFNOT 31
+ 26 GETGLOBAL Not_found
+ 28 MAKEBLOCK1 0
+ 30 RAISE
+ 31 ACC0
+ 32 POP 1
+ 34 ATOM0
+ 35 SETGLOBAL T210-setfield1
+ 37 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t210-setfield2.ml b/testsuite/tests/tool-ocaml/t210-setfield2.ml
new file mode 100644
index 0000000000..727691d113
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t210-setfield2.ml
@@ -0,0 +1,40 @@
+open Lib;;
+type t = {
+ mutable a : int;
+ mutable b : int;
+ mutable c : int;
+};;
+
+let x = {a = 7; b = 6; c = 5} in
+x.c <- 11;
+if x.c <> 11 then raise Not_found;
+x
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 5
+ 11 PUSHCONSTINT 6
+ 13 PUSHCONSTINT 7
+ 15 MAKEBLOCK3 0
+ 17 PUSHCONSTINT 11
+ 19 PUSHACC1
+ 20 SETFIELD2
+ 21 CONSTINT 11
+ 23 PUSHACC1
+ 24 GETFIELD2
+ 25 NEQ
+ 26 BRANCHIFNOT 33
+ 28 GETGLOBAL Not_found
+ 30 MAKEBLOCK1 0
+ 32 RAISE
+ 33 ACC0
+ 34 POP 1
+ 36 ATOM0
+ 37 SETGLOBAL T210-setfield2
+ 39 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t210-setfield3.ml b/testsuite/tests/tool-ocaml/t210-setfield3.ml
new file mode 100644
index 0000000000..d50d2c2a63
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t210-setfield3.ml
@@ -0,0 +1,42 @@
+open Lib;;
+type t = {
+ mutable a : int;
+ mutable b : int;
+ mutable c : int;
+ mutable d : int;
+};;
+
+let x = {a = 7; b = 6; c = 5; d = 4} in
+x.d <- 11;
+if x.d <> 11 then raise Not_found;
+x
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 4
+ 11 PUSHCONSTINT 5
+ 13 PUSHCONSTINT 6
+ 15 PUSHCONSTINT 7
+ 17 MAKEBLOCK 4, 0
+ 20 PUSHCONSTINT 11
+ 22 PUSHACC1
+ 23 SETFIELD3
+ 24 CONSTINT 11
+ 26 PUSHACC1
+ 27 GETFIELD3
+ 28 NEQ
+ 29 BRANCHIFNOT 36
+ 31 GETGLOBAL Not_found
+ 33 MAKEBLOCK1 0
+ 35 RAISE
+ 36 ACC0
+ 37 POP 1
+ 39 ATOM0
+ 40 SETGLOBAL T210-setfield3
+ 42 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t211-setfield.ml b/testsuite/tests/tool-ocaml/t211-setfield.ml
new file mode 100644
index 0000000000..69c445e10b
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t211-setfield.ml
@@ -0,0 +1,44 @@
+open Lib;;
+type t = {
+ mutable a : int;
+ mutable b : int;
+ mutable c : int;
+ mutable d : int;
+ mutable e : int;
+};;
+
+let x = {a = 7; b = 6; c = 5; d = 4; e = 5} in
+x.e <- 11;
+if x.e <> 11 then raise Not_found;
+x
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 5
+ 11 PUSHCONSTINT 4
+ 13 PUSHCONSTINT 5
+ 15 PUSHCONSTINT 6
+ 17 PUSHCONSTINT 7
+ 19 MAKEBLOCK 5, 0
+ 22 PUSHCONSTINT 11
+ 24 PUSHACC1
+ 25 SETFIELD 4
+ 27 CONSTINT 11
+ 29 PUSHACC1
+ 30 GETFIELD 4
+ 32 NEQ
+ 33 BRANCHIFNOT 40
+ 35 GETGLOBAL Not_found
+ 37 MAKEBLOCK1 0
+ 39 RAISE
+ 40 ACC0
+ 41 POP 1
+ 43 ATOM0
+ 44 SETGLOBAL T211-setfield
+ 46 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t220-assign.ml b/testsuite/tests/tool-ocaml/t220-assign.ml
new file mode 100644
index 0000000000..769f8fb22c
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t220-assign.ml
@@ -0,0 +1,27 @@
+open Lib;;
+let x = ref 1 in
+x := 3;
+if !x <> 3 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST1
+ 10 PUSHCONST3
+ 11 ASSIGN 0
+ 13 CONST3
+ 14 PUSHACC1
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 POP 1
+ 25 ATOM0
+ 26 SETGLOBAL T220-assign
+ 28 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t230-check_signals.ml b/testsuite/tests/tool-ocaml/t230-check_signals.ml
new file mode 100644
index 0000000000..2c2b5d7731
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t230-check_signals.ml
@@ -0,0 +1,28 @@
+open Lib;;
+for i = 0 to 0 do () done;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 PUSHCONST0
+ 11 PUSH
+ 12 BRANCH 21
+ 14 CHECK_SIGNALS
+ 15 CONST0
+ 16 ACC1
+ 17 OFFSETINT 1
+ 19 ASSIGN 1
+ 21 ACC0
+ 22 PUSHACC2
+ 23 LEINT
+ 24 BRANCHIF 14
+ 26 CONST0
+ 27 POP 2
+ 29 ATOM0
+ 30 SETGLOBAL T230-check_signals
+ 32 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t240-c_call1.ml b/testsuite/tests/tool-ocaml/t240-c_call1.ml
new file mode 100644
index 0000000000..7bb2df97e9
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t240-c_call1.ml
@@ -0,0 +1,27 @@
+open Lib;;
+if Pervasives.int_of_string "123" <> 123 then raise Not_found;;
+(** test for fix of bug 6649: http://caml.inria.fr/mantis/view.php?id=6649 *)
+if Pervasives.int_of_string "+123" <> 123 then raise Not_found;;
+
+if Int32.of_string "+123" <> Int32.of_int 123 then raise Not_found;;
+if Int64.of_string "+123" <> Int64.of_int 123 then raise Not_found;;
+if Nativeint.of_string "+123" <> Nativeint.of_int 123 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 123
+ 11 PUSHGETGLOBAL "123"
+ 13 C_CALL1 int_of_string
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 ATOM0
+ 24 SETGLOBAL T240-c_call1
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t240-c_call2.ml b/testsuite/tests/tool-ocaml/t240-c_call2.ml
new file mode 100644
index 0000000000..23c984369f
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t240-c_call2.ml
@@ -0,0 +1,22 @@
+open Lib;;
+if Pervasives.compare 1 2 <> -1 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT -1
+ 11 PUSHCONST2
+ 12 PUSHCONST1
+ 13 C_CALL2 compare
+ 15 NEQ
+ 16 BRANCHIFNOT 23
+ 18 GETGLOBAL Not_found
+ 20 MAKEBLOCK1 0
+ 22 RAISE
+ 23 ATOM0
+ 24 SETGLOBAL T240-c_call2
+ 26 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t240-c_call3.ml b/testsuite/tests/tool-ocaml/t240-c_call3.ml
new file mode 100644
index 0000000000..a34e1dcf96
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t240-c_call3.ml
@@ -0,0 +1,23 @@
+open Lib;;
+if Hashtbl.hash_param 5 6 [1;2;3] <> 697606130 then raise Not_found;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 196799
+ 11 PUSHGETGLOBAL <0>(1, <0>(2, <0>(3, 0)))
+ 13 PUSHCONSTINT 6
+ 15 PUSHCONSTINT 5
+ 17 C_CALL3 hash_univ_param
+ 19 NEQ
+ 20 BRANCHIFNOT 27
+ 22 GETGLOBAL Not_found
+ 24 MAKEBLOCK1 0
+ 26 RAISE
+ 27 ATOM0
+ 28 SETGLOBAL T240-c_call3
+ 30 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t240-c_call4.ml b/testsuite/tests/tool-ocaml/t240-c_call4.ml
new file mode 100644
index 0000000000..2ab62d86e0
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t240-c_call4.ml
@@ -0,0 +1,32 @@
+open Lib;;
+let s = "abcdefgh" in
+String.unsafe_fill s 0 6 'x';
+if s.[5] <> 'x' then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL "abcdefgh"
+ 11 PUSHCONSTINT 120
+ 13 PUSHCONSTINT 6
+ 15 PUSHCONST0
+ 16 PUSHACC3
+ 17 C_CALL4 fill_string
+ 19 CONSTINT 120
+ 21 PUSHCONSTINT 5
+ 23 PUSHACC2
+ 24 GETSTRINGCHAR
+ 25 NEQ
+ 26 BRANCHIFNOT 33
+ 28 GETGLOBAL Not_found
+ 30 MAKEBLOCK1 0
+ 32 RAISE
+ 33 POP 1
+ 35 ATOM0
+ 36 SETGLOBAL T240-c_call4
+ 38 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t240-c_call5.ml b/testsuite/tests/tool-ocaml/t240-c_call5.ml
new file mode 100644
index 0000000000..e817d55028
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t240-c_call5.ml
@@ -0,0 +1,33 @@
+open Lib;;
+let s = "abcdefgh" in
+String.unsafe_blit s 3 s 0 3;
+if s.[0] <> 'd' then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 GETGLOBAL "abcdefgh"
+ 11 PUSHCONST3
+ 12 PUSHCONST0
+ 13 PUSHACC2
+ 14 PUSHCONST3
+ 15 PUSHACC4
+ 16 C_CALL5 blit_string
+ 18 CONSTINT 100
+ 20 PUSHCONST0
+ 21 PUSHACC2
+ 22 GETSTRINGCHAR
+ 23 NEQ
+ 24 BRANCHIFNOT 31
+ 26 GETGLOBAL Not_found
+ 28 MAKEBLOCK1 0
+ 30 RAISE
+ 31 POP 1
+ 33 ATOM0
+ 34 SETGLOBAL T240-c_call5
+ 36 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t250-closurerec-1.ml b/testsuite/tests/tool-ocaml/t250-closurerec-1.ml
new file mode 100644
index 0000000000..ded5036e69
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t250-closurerec-1.ml
@@ -0,0 +1,19 @@
+open Lib;;
+let rec f _ = 0;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 14
+ 11 CONST0
+ 12 RETURN 1
+ 14 CLOSUREREC 0, 11
+ 18 ACC0
+ 19 MAKEBLOCK1 0
+ 21 POP 1
+ 23 SETGLOBAL T250-closurerec-1
+ 25 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t250-closurerec-2.ml b/testsuite/tests/tool-ocaml/t250-closurerec-2.ml
new file mode 100644
index 0000000000..97eac0c791
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t250-closurerec-2.ml
@@ -0,0 +1,29 @@
+open Lib;;
+let rec f _ = 23 in
+if f 0 <> 23 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 15
+ 11 CONSTINT 23
+ 13 RETURN 1
+ 15 CLOSUREREC 0, 11
+ 19 CONSTINT 23
+ 21 PUSHCONST0
+ 22 PUSHACC2
+ 23 APPLY1
+ 24 NEQ
+ 25 BRANCHIFNOT 32
+ 27 GETGLOBAL Not_found
+ 29 MAKEBLOCK1 0
+ 31 RAISE
+ 32 POP 1
+ 34 ATOM0
+ 35 SETGLOBAL T250-closurerec-2
+ 37 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t251-pushoffsetclosure0.ml b/testsuite/tests/tool-ocaml/t251-pushoffsetclosure0.ml
new file mode 100644
index 0000000000..b1c25555ea
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t251-pushoffsetclosure0.ml
@@ -0,0 +1,39 @@
+open Lib;;
+let rec f = function
+ | 0 -> 13
+ | n -> f 0
+in
+if f 5 <> 13 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 24
+ 11 CONST0
+ 12 PUSHACC1
+ 13 EQ
+ 14 BRANCHIFNOT 20
+ 16 CONSTINT 13
+ 18 RETURN 1
+ 20 CONST0
+ 21 PUSHOFFSETCLOSURE0
+ 22 APPTERM1 2
+ 24 CLOSUREREC 0, 11
+ 28 CONSTINT 13
+ 30 PUSHCONSTINT 5
+ 32 PUSHACC2
+ 33 APPLY1
+ 34 NEQ
+ 35 BRANCHIFNOT 42
+ 37 GETGLOBAL Not_found
+ 39 MAKEBLOCK1 0
+ 41 RAISE
+ 42 POP 1
+ 44 ATOM0
+ 45 SETGLOBAL T251-pushoffsetclosure0
+ 47 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t251-pushoffsetclosure2.ml b/testsuite/tests/tool-ocaml/t251-pushoffsetclosure2.ml
new file mode 100644
index 0000000000..0fbdd6eae7
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t251-pushoffsetclosure2.ml
@@ -0,0 +1,34 @@
+open Lib;;
+let rec f _ = g 0
+ and g _ = 4
+in
+if f 5 <> 4 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 19
+ 11 CONST0
+ 12 PUSHOFFSETCLOSURE2
+ 13 APPTERM1 2
+ 15 CONSTINT 4
+ 17 RETURN 1
+ 19 CLOSUREREC 0, 11, 15
+ 24 CONSTINT 4
+ 26 PUSHCONSTINT 5
+ 28 PUSHACC3
+ 29 APPLY1
+ 30 NEQ
+ 31 BRANCHIFNOT 38
+ 33 GETGLOBAL Not_found
+ 35 MAKEBLOCK1 0
+ 37 RAISE
+ 38 POP 2
+ 40 ATOM0
+ 41 SETGLOBAL T251-pushoffsetclosure2
+ 43 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t251-pushoffsetclosurem2.ml b/testsuite/tests/tool-ocaml/t251-pushoffsetclosurem2.ml
new file mode 100644
index 0000000000..41ec196c35
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t251-pushoffsetclosurem2.ml
@@ -0,0 +1,34 @@
+open Lib;;
+let rec f _ = 4
+ and g _ = f 2
+in
+if g 5 <> 4 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 19
+ 11 CONSTINT 4
+ 13 RETURN 1
+ 15 CONST2
+ 16 PUSHOFFSETCLOSUREM2
+ 17 APPTERM1 2
+ 19 CLOSUREREC 0, 11, 15
+ 24 CONSTINT 4
+ 26 PUSHCONSTINT 5
+ 28 PUSHACC2
+ 29 APPLY1
+ 30 NEQ
+ 31 BRANCHIFNOT 38
+ 33 GETGLOBAL Not_found
+ 35 MAKEBLOCK1 0
+ 37 RAISE
+ 38 POP 2
+ 40 ATOM0
+ 41 SETGLOBAL T251-pushoffsetclosurem2
+ 43 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t252-pushoffsetclosure.ml b/testsuite/tests/tool-ocaml/t252-pushoffsetclosure.ml
new file mode 100644
index 0000000000..1887133453
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t252-pushoffsetclosure.ml
@@ -0,0 +1,38 @@
+open Lib;;
+let rec f x = x
+ and g _ = f 4
+ and h _ = f 6
+in
+if h 1 <> 6 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 25
+ 11 ACC0
+ 12 RETURN 1
+ 14 CONSTINT 4
+ 16 PUSHOFFSETCLOSUREM2
+ 17 APPTERM1 2
+ 19 CONSTINT 6
+ 21 PUSHOFFSETCLOSURE -4
+ 23 APPTERM1 2
+ 25 CLOSUREREC 0, 11, 14, 19
+ 31 CONSTINT 6
+ 33 PUSHCONST1
+ 34 PUSHACC2
+ 35 APPLY1
+ 36 NEQ
+ 37 BRANCHIFNOT 44
+ 39 GETGLOBAL Not_found
+ 41 MAKEBLOCK1 0
+ 43 RAISE
+ 44 POP 3
+ 46 ATOM0
+ 47 SETGLOBAL T252-pushoffsetclosure
+ 49 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t253-offsetclosure0.ml b/testsuite/tests/tool-ocaml/t253-offsetclosure0.ml
new file mode 100644
index 0000000000..f6d12c6db0
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t253-offsetclosure0.ml
@@ -0,0 +1,34 @@
+open Lib;;
+let rec f _ = g f
+ and g _ = 10
+in
+if f 3 <> 10 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 19
+ 11 OFFSETCLOSURE0
+ 12 PUSHOFFSETCLOSURE2
+ 13 APPTERM1 2
+ 15 CONSTINT 10
+ 17 RETURN 1
+ 19 CLOSUREREC 0, 11, 15
+ 24 CONSTINT 10
+ 26 PUSHCONST3
+ 27 PUSHACC3
+ 28 APPLY1
+ 29 NEQ
+ 30 BRANCHIFNOT 37
+ 32 GETGLOBAL Not_found
+ 34 MAKEBLOCK1 0
+ 36 RAISE
+ 37 POP 2
+ 39 ATOM0
+ 40 SETGLOBAL T253-offsetclosure0
+ 42 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t253-offsetclosure2.ml b/testsuite/tests/tool-ocaml/t253-offsetclosure2.ml
new file mode 100644
index 0000000000..be940611fe
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t253-offsetclosure2.ml
@@ -0,0 +1,34 @@
+open Lib;;
+let rec f _ = g
+ and g _ = 10
+in
+if f 3 4 <> 10 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 18
+ 11 OFFSETCLOSURE2
+ 12 RETURN 1
+ 14 CONSTINT 10
+ 16 RETURN 1
+ 18 CLOSUREREC 0, 11, 14
+ 23 CONSTINT 10
+ 25 PUSHCONSTINT 4
+ 27 PUSHCONST3
+ 28 PUSHACC4
+ 29 APPLY2
+ 30 NEQ
+ 31 BRANCHIFNOT 38
+ 33 GETGLOBAL Not_found
+ 35 MAKEBLOCK1 0
+ 37 RAISE
+ 38 POP 2
+ 40 ATOM0
+ 41 SETGLOBAL T253-offsetclosure2
+ 43 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t253-offsetclosurem2.ml b/testsuite/tests/tool-ocaml/t253-offsetclosurem2.ml
new file mode 100644
index 0000000000..cec37931e7
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t253-offsetclosurem2.ml
@@ -0,0 +1,34 @@
+open Lib;;
+let rec f _ = 11
+ and g _ = f
+in
+if g 3 4 <> 11 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 18
+ 11 CONSTINT 11
+ 13 RETURN 1
+ 15 OFFSETCLOSUREM2
+ 16 RETURN 1
+ 18 CLOSUREREC 0, 11, 15
+ 23 CONSTINT 11
+ 25 PUSHCONSTINT 4
+ 27 PUSHCONST3
+ 28 PUSHACC3
+ 29 APPLY2
+ 30 NEQ
+ 31 BRANCHIFNOT 38
+ 33 GETGLOBAL Not_found
+ 35 MAKEBLOCK1 0
+ 37 RAISE
+ 38 POP 2
+ 40 ATOM0
+ 41 SETGLOBAL T253-offsetclosurem2
+ 43 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t254-offsetclosure.ml b/testsuite/tests/tool-ocaml/t254-offsetclosure.ml
new file mode 100644
index 0000000000..6da8c28c90
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t254-offsetclosure.ml
@@ -0,0 +1,37 @@
+open Lib;;
+let rec f _ = 11
+ and g _ = 0
+ and h _ = f
+in
+if h 3 4 <> 11 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 22
+ 11 CONSTINT 11
+ 13 RETURN 1
+ 15 CONST0
+ 16 RETURN 1
+ 18 OFFSETCLOSURE -4
+ 20 RETURN 1
+ 22 CLOSUREREC 0, 11, 15, 18
+ 28 CONSTINT 11
+ 30 PUSHCONSTINT 4
+ 32 PUSHCONST3
+ 33 PUSHACC3
+ 34 APPLY2
+ 35 NEQ
+ 36 BRANCHIFNOT 43
+ 38 GETGLOBAL Not_found
+ 40 MAKEBLOCK1 0
+ 42 RAISE
+ 43 POP 3
+ 45 ATOM0
+ 46 SETGLOBAL T254-offsetclosure
+ 48 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t260-offsetref.ml b/testsuite/tests/tool-ocaml/t260-offsetref.ml
new file mode 100644
index 0000000000..968892ef11
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t260-offsetref.ml
@@ -0,0 +1,31 @@
+open Lib;;
+let x = ref 32 in
+incr x;
+if !x <> 33 then raise Not_found;
+x
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONSTINT 32
+ 11 MAKEBLOCK1 0
+ 13 PUSHACC0
+ 14 OFFSETREF 1
+ 16 CONSTINT 33
+ 18 PUSHACC1
+ 19 GETFIELD0
+ 20 NEQ
+ 21 BRANCHIFNOT 28
+ 23 GETGLOBAL Not_found
+ 25 MAKEBLOCK1 0
+ 27 RAISE
+ 28 ACC0
+ 29 POP 1
+ 31 ATOM0
+ 32 SETGLOBAL T260-offsetref
+ 34 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t270-push_retaddr.ml b/testsuite/tests/tool-ocaml/t270-push_retaddr.ml
new file mode 100644
index 0000000000..0c7fb369bf
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t270-push_retaddr.ml
@@ -0,0 +1,36 @@
+open Lib;;
+let f a b c d = 123 in
+if f 0 1 2 3 <> 123 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 18
+ 11 RESTART
+ 12 GRAB 3
+ 14 CONSTINT 123
+ 16 RETURN 4
+ 18 CLOSURE 0, 12
+ 21 PUSHCONSTINT 123
+ 23 PUSH
+ 24 PUSH_RETADDR 34
+ 26 CONST3
+ 27 PUSHCONST2
+ 28 PUSHCONST1
+ 29 PUSHCONST0
+ 30 PUSHACC 8
+ 32 APPLY 4
+ 34 NEQ
+ 35 BRANCHIFNOT 42
+ 37 GETGLOBAL Not_found
+ 39 MAKEBLOCK1 0
+ 41 RAISE
+ 42 POP 1
+ 44 ATOM0
+ 45 SETGLOBAL T270-push_retaddr
+ 47 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t300-getmethod.ml b/testsuite/tests/tool-ocaml/t300-getmethod.ml
new file mode 100644
index 0000000000..e7894735c1
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t300-getmethod.ml
@@ -0,0 +1,5885 @@
+open Lib;;
+
+class c = object
+ method m = 23
+end;;
+
+let o = new c in
+if o#m <> 23 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 BRANCH 2177
+ 1199 RESTART
+ 1200 GRAB 1
+ 1202 ACC1
+ 1203 BRANCHIFNOT 1213
+ 1205 ACC1
+ 1206 GETFIELD1
+ 1207 PUSHACC1
+ 1208 OFFSETINT 1
+ 1210 PUSHOFFSETCLOSURE0
+ 1211 APPTERM2 4
+ 1213 ACC0
+ 1214 RETURN 2
+ 1216 RESTART
+ 1217 GRAB 1
+ 1219 ACC0
+ 1220 BRANCHIFNOT 1251
+ 1222 CONST0
+ 1223 PUSHACC2
+ 1224 EQ
+ 1225 BRANCHIFNOT 1231
+ 1227 ACC0
+ 1228 GETFIELD0
+ 1229 RETURN 2
+ 1231 CONST0
+ 1232 PUSHACC2
+ 1233 GTINT
+ 1234 BRANCHIFNOT 1244
+ 1236 ACC1
+ 1237 OFFSETINT -1
+ 1239 PUSHACC1
+ 1240 GETFIELD1
+ 1241 PUSHOFFSETCLOSURE0
+ 1242 APPTERM2 4
+ 1244 GETGLOBAL "List.nth"
+ 1246 PUSHGETGLOBALFIELD Pervasives, 2
+ 1249 APPTERM1 3
+ 1251 GETGLOBAL "nth"
+ 1253 PUSHGETGLOBALFIELD Pervasives, 3
+ 1256 APPTERM1 3
+ 1258 RESTART
+ 1259 GRAB 1
+ 1261 ACC0
+ 1262 BRANCHIFNOT 1274
+ 1264 ACC1
+ 1265 PUSHACC1
+ 1266 GETFIELD0
+ 1267 MAKEBLOCK2 0
+ 1269 PUSHACC1
+ 1270 GETFIELD1
+ 1271 PUSHOFFSETCLOSURE0
+ 1272 APPTERM2 4
+ 1274 ACC1
+ 1275 RETURN 2
+ 1277 ACC0
+ 1278 BRANCHIFNOT 1291
+ 1280 ACC0
+ 1281 GETFIELD1
+ 1282 PUSHOFFSETCLOSURE0
+ 1283 APPLY1
+ 1284 PUSHACC1
+ 1285 GETFIELD0
+ 1286 PUSHGETGLOBALFIELD Pervasives, 16
+ 1289 APPTERM2 3
+ 1291 RETURN 1
+ 1293 RESTART
+ 1294 GRAB 1
+ 1296 ACC1
+ 1297 BRANCHIFNOT 1313
+ 1299 ACC1
+ 1300 GETFIELD0
+ 1301 PUSHACC1
+ 1302 APPLY1
+ 1303 PUSHACC2
+ 1304 GETFIELD1
+ 1305 PUSHACC2
+ 1306 PUSHOFFSETCLOSURE0
+ 1307 APPLY2
+ 1308 PUSHACC1
+ 1309 MAKEBLOCK2 0
+ 1311 POP 1
+ 1313 RETURN 2
+ 1315 RESTART
+ 1316 GRAB 1
+ 1318 ACC1
+ 1319 BRANCHIFNOT 1331
+ 1321 ACC1
+ 1322 GETFIELD0
+ 1323 PUSHACC1
+ 1324 APPLY1
+ 1325 ACC1
+ 1326 GETFIELD1
+ 1327 PUSHACC1
+ 1328 PUSHOFFSETCLOSURE0
+ 1329 APPTERM2 4
+ 1331 RETURN 2
+ 1333 RESTART
+ 1334 GRAB 2
+ 1336 ACC2
+ 1337 BRANCHIFNOT 1350
+ 1339 ACC2
+ 1340 GETFIELD1
+ 1341 PUSHACC3
+ 1342 GETFIELD0
+ 1343 PUSHACC3
+ 1344 PUSHACC3
+ 1345 APPLY2
+ 1346 PUSHACC2
+ 1347 PUSHOFFSETCLOSURE0
+ 1348 APPTERM3 6
+ 1350 ACC1
+ 1351 RETURN 3
+ 1353 RESTART
+ 1354 GRAB 2
+ 1356 ACC1
+ 1357 BRANCHIFNOT 1370
+ 1359 ACC2
+ 1360 PUSHACC2
+ 1361 GETFIELD1
+ 1362 PUSHACC2
+ 1363 PUSHOFFSETCLOSURE0
+ 1364 APPLY3
+ 1365 PUSHACC2
+ 1366 GETFIELD0
+ 1367 PUSHACC2
+ 1368 APPTERM2 5
+ 1370 ACC2
+ 1371 RETURN 3
+ 1373 RESTART
+ 1374 GRAB 2
+ 1376 ACC1
+ 1377 BRANCHIFNOT 1400
+ 1379 ACC2
+ 1380 BRANCHIFNOT 1407
+ 1382 ACC2
+ 1383 GETFIELD0
+ 1384 PUSHACC2
+ 1385 GETFIELD0
+ 1386 PUSHACC2
+ 1387 APPLY2
+ 1388 PUSHACC3
+ 1389 GETFIELD1
+ 1390 PUSHACC3
+ 1391 GETFIELD1
+ 1392 PUSHACC3
+ 1393 PUSHOFFSETCLOSURE0
+ 1394 APPLY3
+ 1395 PUSHACC1
+ 1396 MAKEBLOCK2 0
+ 1398 RETURN 4
+ 1400 ACC2
+ 1401 BRANCHIFNOT 1405
+ 1403 BRANCH 1407
+ 1405 RETURN 3
+ 1407 GETGLOBAL "List.map2"
+ 1409 PUSHGETGLOBALFIELD Pervasives, 2
+ 1412 APPTERM1 4
+ 1414 RESTART
+ 1415 GRAB 2
+ 1417 ACC1
+ 1418 BRANCHIFNOT 1437
+ 1420 ACC2
+ 1421 BRANCHIFNOT 1444
+ 1423 ACC2
+ 1424 GETFIELD0
+ 1425 PUSHACC2
+ 1426 GETFIELD0
+ 1427 PUSHACC2
+ 1428 APPLY2
+ 1429 ACC2
+ 1430 GETFIELD1
+ 1431 PUSHACC2
+ 1432 GETFIELD1
+ 1433 PUSHACC2
+ 1434 PUSHOFFSETCLOSURE0
+ 1435 APPTERM3 6
+ 1437 ACC2
+ 1438 BRANCHIFNOT 1442
+ 1440 BRANCH 1444
+ 1442 RETURN 3
+ 1444 GETGLOBAL "List.iter2"
+ 1446 PUSHGETGLOBALFIELD Pervasives, 2
+ 1449 APPTERM1 4
+ 1451 RESTART
+ 1452 GRAB 3
+ 1454 ACC2
+ 1455 BRANCHIFNOT 1476
+ 1457 ACC3
+ 1458 BRANCHIFNOT 1482
+ 1460 ACC3
+ 1461 GETFIELD1
+ 1462 PUSHACC3
+ 1463 GETFIELD1
+ 1464 PUSHACC5
+ 1465 GETFIELD0
+ 1466 PUSHACC5
+ 1467 GETFIELD0
+ 1468 PUSHACC5
+ 1469 PUSHACC5
+ 1470 APPLY3
+ 1471 PUSHACC3
+ 1472 PUSHOFFSETCLOSURE0
+ 1473 APPTERM 4, 8
+ 1476 ACC3
+ 1477 BRANCHIF 1482
+ 1479 ACC1
+ 1480 RETURN 4
+ 1482 GETGLOBAL "List.fold_left2"
+ 1484 PUSHGETGLOBALFIELD Pervasives, 2
+ 1487 APPTERM1 5
+ 1489 RESTART
+ 1490 GRAB 3
+ 1492 ACC1
+ 1493 BRANCHIFNOT 1516
+ 1495 ACC2
+ 1496 BRANCHIFNOT 1522
+ 1498 PUSH_RETADDR 1509
+ 1500 ACC6
+ 1501 PUSHACC6
+ 1502 GETFIELD1
+ 1503 PUSHACC6
+ 1504 GETFIELD1
+ 1505 PUSHACC6
+ 1506 PUSHOFFSETCLOSURE0
+ 1507 APPLY 4
+ 1509 PUSHACC3
+ 1510 GETFIELD0
+ 1511 PUSHACC3
+ 1512 GETFIELD0
+ 1513 PUSHACC3
+ 1514 APPTERM3 7
+ 1516 ACC2
+ 1517 BRANCHIF 1522
+ 1519 ACC3
+ 1520 RETURN 4
+ 1522 GETGLOBAL "List.fold_right2"
+ 1524 PUSHGETGLOBALFIELD Pervasives, 2
+ 1527 APPTERM1 5
+ 1529 RESTART
+ 1530 GRAB 1
+ 1532 ACC1
+ 1533 BRANCHIFNOT 1549
+ 1535 ACC1
+ 1536 GETFIELD0
+ 1537 PUSHACC1
+ 1538 APPLY1
+ 1539 BRANCHIFNOT 1547
+ 1541 ACC1
+ 1542 GETFIELD1
+ 1543 PUSHACC1
+ 1544 PUSHOFFSETCLOSURE0
+ 1545 APPTERM2 4
+ 1547 RETURN 2
+ 1549 CONST1
+ 1550 RETURN 2
+ 1552 RESTART
+ 1553 GRAB 1
+ 1555 ACC1
+ 1556 BRANCHIFNOT 1570
+ 1558 ACC1
+ 1559 GETFIELD0
+ 1560 PUSHACC1
+ 1561 APPLY1
+ 1562 BRANCHIF 1570
+ 1564 ACC1
+ 1565 GETFIELD1
+ 1566 PUSHACC1
+ 1567 PUSHOFFSETCLOSURE0
+ 1568 APPTERM2 4
+ 1570 RETURN 2
+ 1572 RESTART
+ 1573 GRAB 2
+ 1575 ACC1
+ 1576 BRANCHIFNOT 1599
+ 1578 ACC2
+ 1579 BRANCHIFNOT 1605
+ 1581 ACC2
+ 1582 GETFIELD0
+ 1583 PUSHACC2
+ 1584 GETFIELD0
+ 1585 PUSHACC2
+ 1586 APPLY2
+ 1587 BRANCHIFNOT 1597
+ 1589 ACC2
+ 1590 GETFIELD1
+ 1591 PUSHACC2
+ 1592 GETFIELD1
+ 1593 PUSHACC2
+ 1594 PUSHOFFSETCLOSURE0
+ 1595 APPTERM3 6
+ 1597 RETURN 3
+ 1599 ACC2
+ 1600 BRANCHIF 1605
+ 1602 CONST1
+ 1603 RETURN 3
+ 1605 GETGLOBAL "List.for_all2"
+ 1607 PUSHGETGLOBALFIELD Pervasives, 2
+ 1610 APPTERM1 4
+ 1612 RESTART
+ 1613 GRAB 2
+ 1615 ACC1
+ 1616 BRANCHIFNOT 1639
+ 1618 ACC2
+ 1619 BRANCHIFNOT 1646
+ 1621 ACC2
+ 1622 GETFIELD0
+ 1623 PUSHACC2
+ 1624 GETFIELD0
+ 1625 PUSHACC2
+ 1626 APPLY2
+ 1627 BRANCHIF 1637
+ 1629 ACC2
+ 1630 GETFIELD1
+ 1631 PUSHACC2
+ 1632 GETFIELD1
+ 1633 PUSHACC2
+ 1634 PUSHOFFSETCLOSURE0
+ 1635 APPTERM3 6
+ 1637 RETURN 3
+ 1639 ACC2
+ 1640 BRANCHIFNOT 1644
+ 1642 BRANCH 1646
+ 1644 RETURN 3
+ 1646 GETGLOBAL "List.exists2"
+ 1648 PUSHGETGLOBALFIELD Pervasives, 2
+ 1651 APPTERM1 4
+ 1653 RESTART
+ 1654 GRAB 1
+ 1656 ACC1
+ 1657 BRANCHIFNOT 1672
+ 1659 ACC0
+ 1660 PUSHACC2
+ 1661 GETFIELD0
+ 1662 C_CALL2 equal
+ 1664 BRANCHIF 1672
+ 1666 ACC1
+ 1667 GETFIELD1
+ 1668 PUSHACC1
+ 1669 PUSHOFFSETCLOSURE0
+ 1670 APPTERM2 4
+ 1672 RETURN 2
+ 1674 RESTART
+ 1675 GRAB 1
+ 1677 ACC1
+ 1678 BRANCHIFNOT 1692
+ 1680 ACC0
+ 1681 PUSHACC2
+ 1682 GETFIELD0
+ 1683 EQ
+ 1684 BRANCHIF 1692
+ 1686 ACC1
+ 1687 GETFIELD1
+ 1688 PUSHACC1
+ 1689 PUSHOFFSETCLOSURE0
+ 1690 APPTERM2 4
+ 1692 RETURN 2
+ 1694 RESTART
+ 1695 GRAB 1
+ 1697 ACC1
+ 1698 BRANCHIFNOT 1719
+ 1700 ACC1
+ 1701 GETFIELD0
+ 1702 PUSHACC1
+ 1703 PUSHACC1
+ 1704 GETFIELD0
+ 1705 C_CALL2 equal
+ 1707 BRANCHIFNOT 1713
+ 1709 ACC0
+ 1710 GETFIELD1
+ 1711 RETURN 3
+ 1713 ACC2
+ 1714 GETFIELD1
+ 1715 PUSHACC2
+ 1716 PUSHOFFSETCLOSURE0
+ 1717 APPTERM2 5
+ 1719 GETGLOBAL Not_found
+ 1721 MAKEBLOCK1 0
+ 1723 RAISE
+ 1724 RESTART
+ 1725 GRAB 1
+ 1727 ACC1
+ 1728 BRANCHIFNOT 1748
+ 1730 ACC1
+ 1731 GETFIELD0
+ 1732 PUSHACC1
+ 1733 PUSHACC1
+ 1734 GETFIELD0
+ 1735 EQ
+ 1736 BRANCHIFNOT 1742
+ 1738 ACC0
+ 1739 GETFIELD1
+ 1740 RETURN 3
+ 1742 ACC2
+ 1743 GETFIELD1
+ 1744 PUSHACC2
+ 1745 PUSHOFFSETCLOSURE0
+ 1746 APPTERM2 5
+ 1748 GETGLOBAL Not_found
+ 1750 MAKEBLOCK1 0
+ 1752 RAISE
+ 1753 RESTART
+ 1754 GRAB 1
+ 1756 ACC1
+ 1757 BRANCHIFNOT 1773
+ 1759 ACC0
+ 1760 PUSHACC2
+ 1761 GETFIELD0
+ 1762 GETFIELD0
+ 1763 C_CALL2 equal
+ 1765 BRANCHIF 1773
+ 1767 ACC1
+ 1768 GETFIELD1
+ 1769 PUSHACC1
+ 1770 PUSHOFFSETCLOSURE0
+ 1771 APPTERM2 4
+ 1773 RETURN 2
+ 1775 RESTART
+ 1776 GRAB 1
+ 1778 ACC1
+ 1779 BRANCHIFNOT 1794
+ 1781 ACC0
+ 1782 PUSHACC2
+ 1783 GETFIELD0
+ 1784 GETFIELD0
+ 1785 EQ
+ 1786 BRANCHIF 1794
+ 1788 ACC1
+ 1789 GETFIELD1
+ 1790 PUSHACC1
+ 1791 PUSHOFFSETCLOSURE0
+ 1792 APPTERM2 4
+ 1794 RETURN 2
+ 1796 RESTART
+ 1797 GRAB 1
+ 1799 ACC1
+ 1800 BRANCHIFNOT 1825
+ 1802 ACC1
+ 1803 GETFIELD0
+ 1804 PUSHACC2
+ 1805 GETFIELD1
+ 1806 PUSHACC2
+ 1807 PUSHACC2
+ 1808 GETFIELD0
+ 1809 C_CALL2 equal
+ 1811 BRANCHIFNOT 1816
+ 1813 ACC0
+ 1814 RETURN 4
+ 1816 ACC0
+ 1817 PUSHACC3
+ 1818 PUSHOFFSETCLOSURE0
+ 1819 APPLY2
+ 1820 PUSHACC2
+ 1821 MAKEBLOCK2 0
+ 1823 POP 2
+ 1825 RETURN 2
+ 1827 RESTART
+ 1828 GRAB 1
+ 1830 ACC1
+ 1831 BRANCHIFNOT 1855
+ 1833 ACC1
+ 1834 GETFIELD0
+ 1835 PUSHACC2
+ 1836 GETFIELD1
+ 1837 PUSHACC2
+ 1838 PUSHACC2
+ 1839 GETFIELD0
+ 1840 EQ
+ 1841 BRANCHIFNOT 1846
+ 1843 ACC0
+ 1844 RETURN 4
+ 1846 ACC0
+ 1847 PUSHACC3
+ 1848 PUSHOFFSETCLOSURE0
+ 1849 APPLY2
+ 1850 PUSHACC2
+ 1851 MAKEBLOCK2 0
+ 1853 POP 2
+ 1855 RETURN 2
+ 1857 RESTART
+ 1858 GRAB 1
+ 1860 ACC1
+ 1861 BRANCHIFNOT 1879
+ 1863 ACC1
+ 1864 GETFIELD0
+ 1865 PUSHACC0
+ 1866 PUSHACC2
+ 1867 APPLY1
+ 1868 BRANCHIFNOT 1873
+ 1870 ACC0
+ 1871 RETURN 3
+ 1873 ACC2
+ 1874 GETFIELD1
+ 1875 PUSHACC2
+ 1876 PUSHOFFSETCLOSURE0
+ 1877 APPTERM2 5
+ 1879 GETGLOBAL Not_found
+ 1881 MAKEBLOCK1 0
+ 1883 RAISE
+ 1884 RESTART
+ 1885 GRAB 2
+ 1887 ACC2
+ 1888 BRANCHIFNOT 1917
+ 1890 ACC2
+ 1891 GETFIELD0
+ 1892 PUSHACC3
+ 1893 GETFIELD1
+ 1894 PUSHACC1
+ 1895 PUSHENVACC2
+ 1896 APPLY1
+ 1897 BRANCHIFNOT 1908
+ 1899 ACC0
+ 1900 PUSHACC4
+ 1901 PUSHACC4
+ 1902 PUSHACC4
+ 1903 MAKEBLOCK2 0
+ 1905 PUSHOFFSETCLOSURE0
+ 1906 APPTERM3 8
+ 1908 ACC0
+ 1909 PUSHACC4
+ 1910 PUSHACC3
+ 1911 MAKEBLOCK2 0
+ 1913 PUSHACC4
+ 1914 PUSHOFFSETCLOSURE0
+ 1915 APPTERM3 8
+ 1917 ACC1
+ 1918 PUSHENVACC1
+ 1919 APPLY1
+ 1920 PUSHACC1
+ 1921 PUSHENVACC1
+ 1922 APPLY1
+ 1923 MAKEBLOCK2 0
+ 1925 RETURN 3
+ 1927 RESTART
+ 1928 GRAB 1
+ 1930 ACC0
+ 1931 PUSHENVACC1
+ 1932 CLOSUREREC 2, 1885
+ 1936 ACC2
+ 1937 PUSHCONST0
+ 1938 PUSHCONST0
+ 1939 PUSHACC3
+ 1940 APPTERM3 6
+ 1942 ACC0
+ 1943 BRANCHIFNOT 1967
+ 1945 ACC0
+ 1946 GETFIELD0
+ 1947 PUSHACC1
+ 1948 GETFIELD1
+ 1949 PUSHOFFSETCLOSURE0
+ 1950 APPLY1
+ 1951 PUSHACC0
+ 1952 GETFIELD1
+ 1953 PUSHACC2
+ 1954 GETFIELD1
+ 1955 MAKEBLOCK2 0
+ 1957 PUSHACC1
+ 1958 GETFIELD0
+ 1959 PUSHACC3
+ 1960 GETFIELD0
+ 1961 MAKEBLOCK2 0
+ 1963 MAKEBLOCK2 0
+ 1965 RETURN 3
+ 1967 GETGLOBAL <0>(0, 0)
+ 1969 RETURN 1
+ 1971 RESTART
+ 1972 GRAB 1
+ 1974 ACC0
+ 1975 BRANCHIFNOT 1996
+ 1977 ACC1
+ 1978 BRANCHIFNOT 2003
+ 1980 ACC1
+ 1981 GETFIELD1
+ 1982 PUSHACC1
+ 1983 GETFIELD1
+ 1984 PUSHOFFSETCLOSURE0
+ 1985 APPLY2
+ 1986 PUSHACC2
+ 1987 GETFIELD0
+ 1988 PUSHACC2
+ 1989 GETFIELD0
+ 1990 MAKEBLOCK2 0
+ 1992 MAKEBLOCK2 0
+ 1994 RETURN 2
+ 1996 ACC1
+ 1997 BRANCHIFNOT 2001
+ 1999 BRANCH 2003
+ 2001 RETURN 2
+ 2003 GETGLOBAL "List.combine"
+ 2005 PUSHGETGLOBALFIELD Pervasives, 2
+ 2008 APPTERM1 3
+ 2010 RESTART
+ 2011 GRAB 1
+ 2013 ACC1
+ 2014 BRANCHIFNOT 2038
+ 2016 ACC1
+ 2017 GETFIELD0
+ 2018 PUSHACC2
+ 2019 GETFIELD1
+ 2020 PUSHACC1
+ 2021 PUSHENVACC2
+ 2022 APPLY1
+ 2023 BRANCHIFNOT 2033
+ 2025 ACC0
+ 2026 PUSHACC3
+ 2027 PUSHACC3
+ 2028 MAKEBLOCK2 0
+ 2030 PUSHOFFSETCLOSURE0
+ 2031 APPTERM2 6
+ 2033 ACC0
+ 2034 PUSHACC3
+ 2035 PUSHOFFSETCLOSURE0
+ 2036 APPTERM2 6
+ 2038 ACC0
+ 2039 PUSHENVACC1
+ 2040 APPTERM1 3
+ 2042 ACC0
+ 2043 PUSHENVACC1
+ 2044 CLOSUREREC 2, 2011
+ 2048 CONST0
+ 2049 PUSHACC1
+ 2050 APPTERM1 3
+ 2052 RESTART
+ 2053 GRAB 2
+ 2055 ACC1
+ 2056 BRANCHIFNOT 2077
+ 2058 ACC2
+ 2059 BRANCHIFNOT 2084
+ 2061 ACC2
+ 2062 GETFIELD1
+ 2063 PUSHACC2
+ 2064 GETFIELD1
+ 2065 PUSHACC2
+ 2066 PUSHACC5
+ 2067 GETFIELD0
+ 2068 PUSHACC5
+ 2069 GETFIELD0
+ 2070 PUSHENVACC1
+ 2071 APPLY2
+ 2072 MAKEBLOCK2 0
+ 2074 PUSHOFFSETCLOSURE0
+ 2075 APPTERM3 6
+ 2077 ACC2
+ 2078 BRANCHIFNOT 2082
+ 2080 BRANCH 2084
+ 2082 RETURN 3
+ 2084 GETGLOBAL "List.rev_map2"
+ 2086 PUSHGETGLOBALFIELD Pervasives, 2
+ 2089 APPTERM1 4
+ 2091 RESTART
+ 2092 GRAB 2
+ 2094 ACC0
+ 2095 CLOSUREREC 1, 2053
+ 2099 ACC3
+ 2100 PUSHACC3
+ 2101 PUSHCONST0
+ 2102 PUSHACC3
+ 2103 APPTERM3 7
+ 2105 RESTART
+ 2106 GRAB 1
+ 2108 ACC1
+ 2109 BRANCHIFNOT 2123
+ 2111 ACC1
+ 2112 GETFIELD1
+ 2113 PUSHACC1
+ 2114 PUSHACC3
+ 2115 GETFIELD0
+ 2116 PUSHENVACC1
+ 2117 APPLY1
+ 2118 MAKEBLOCK2 0
+ 2120 PUSHOFFSETCLOSURE0
+ 2121 APPTERM2 4
+ 2123 ACC0
+ 2124 RETURN 2
+ 2126 RESTART
+ 2127 GRAB 1
+ 2129 ACC0
+ 2130 CLOSUREREC 1, 2106
+ 2134 ACC2
+ 2135 PUSHCONST0
+ 2136 PUSHACC2
+ 2137 APPTERM2 5
+ 2139 CONST0
+ 2140 PUSHACC1
+ 2141 PUSHENVACC1
+ 2142 APPTERM2 3
+ 2144 ACC0
+ 2145 BRANCHIFNOT 2151
+ 2147 ACC0
+ 2148 GETFIELD1
+ 2149 RETURN 1
+ 2151 GETGLOBAL "tl"
+ 2153 PUSHGETGLOBALFIELD Pervasives, 3
+ 2156 APPTERM1 2
+ 2158 ACC0
+ 2159 BRANCHIFNOT 2165
+ 2161 ACC0
+ 2162 GETFIELD0
+ 2163 RETURN 1
+ 2165 GETGLOBAL "hd"
+ 2167 PUSHGETGLOBALFIELD Pervasives, 3
+ 2170 APPTERM1 2
+ 2172 ACC0
+ 2173 PUSHCONST0
+ 2174 PUSHENVACC1
+ 2175 APPTERM2 3
+ 2177 CLOSUREREC 0, 1200
+ 2181 ACC0
+ 2182 CLOSURE 1, 2172
+ 2185 PUSH
+ 2186 CLOSURE 0, 2158
+ 2189 PUSH
+ 2190 CLOSURE 0, 2144
+ 2193 PUSH
+ 2194 CLOSUREREC 0, 1217
+ 2198 GETGLOBALFIELD Pervasives, 16
+ 2201 PUSH
+ 2202 CLOSUREREC 0, 1259
+ 2206 ACC0
+ 2207 CLOSURE 1, 2139
+ 2210 PUSH
+ 2211 CLOSUREREC 0, 1277
+ 2215 CLOSUREREC 0, 1294
+ 2219 CLOSURE 0, 2127
+ 2222 PUSH
+ 2223 CLOSUREREC 0, 1316
+ 2227 CLOSUREREC 0, 1334
+ 2231 CLOSUREREC 0, 1354
+ 2235 CLOSUREREC 0, 1374
+ 2239 CLOSURE 0, 2092
+ 2242 PUSH
+ 2243 CLOSUREREC 0, 1415
+ 2247 CLOSUREREC 0, 1452
+ 2251 CLOSUREREC 0, 1490
+ 2255 CLOSUREREC 0, 1530
+ 2259 CLOSUREREC 0, 1553
+ 2263 CLOSUREREC 0, 1573
+ 2267 CLOSUREREC 0, 1613
+ 2271 CLOSUREREC 0, 1654
+ 2275 CLOSUREREC 0, 1675
+ 2279 CLOSUREREC 0, 1695
+ 2283 CLOSUREREC 0, 1725
+ 2287 CLOSUREREC 0, 1754
+ 2291 CLOSUREREC 0, 1776
+ 2295 CLOSUREREC 0, 1797
+ 2299 CLOSUREREC 0, 1828
+ 2303 CLOSUREREC 0, 1858
+ 2307 ACC 24
+ 2309 CLOSURE 1, 2042
+ 2312 PUSHACC 25
+ 2314 CLOSUREREC 1, 1928
+ 2318 CLOSUREREC 0, 1942
+ 2322 CLOSUREREC 0, 1972
+ 2326 ACC0
+ 2327 PUSHACC2
+ 2328 PUSHACC7
+ 2329 PUSHACC 9
+ 2331 PUSHACC 11
+ 2333 PUSHACC 13
+ 2335 PUSHACC 15
+ 2337 PUSHACC 17
+ 2339 PUSHACC 10
+ 2341 PUSHACC 12
+ 2343 PUSHACC 13
+ 2345 PUSHACC 15
+ 2347 PUSHACC 23
+ 2349 PUSHACC 25
+ 2351 PUSHACC 27
+ 2353 PUSHACC 29
+ 2355 PUSHACC 31
+ 2357 PUSHACC 33
+ 2359 PUSHACC 35
+ 2361 PUSHACC 37
+ 2363 PUSHACC 40
+ 2365 PUSHACC 42
+ 2367 PUSHACC 41
+ 2369 PUSHACC 45
+ 2371 PUSHACC 47
+ 2373 PUSHACC 50
+ 2375 PUSHACC 52
+ 2377 PUSHACC 51
+ 2379 PUSHACC 55
+ 2381 PUSHACC 56
+ 2383 PUSHACC 59
+ 2385 PUSHACC 61
+ 2387 PUSHACC 60
+ 2389 PUSHACC 64
+ 2391 PUSHACC 66
+ 2393 PUSHACC 68
+ 2395 PUSHACC 70
+ 2397 MAKEBLOCK 37, 0
+ 2400 POP 36
+ 2402 SETGLOBAL List
+ 2404 BRANCH 3341
+ 2406 RESTART
+ 2407 GRAB 2
+ 2409 ACC2
+ 2410 PUSHACC2
+ 2411 VECTLENGTH
+ 2412 OFFSETINT -1
+ 2414 PUSHCONST0
+ 2415 PUSH
+ 2416 BRANCH 2433
+ 2418 CHECK_SIGNALS
+ 2419 ACC2
+ 2420 PUSHACC2
+ 2421 PUSHACC6
+ 2422 C_CALL2 array_unsafe_get
+ 2424 PUSHACC5
+ 2425 APPLY2
+ 2426 ASSIGN 2
+ 2428 ACC1
+ 2429 OFFSETINT -1
+ 2431 ASSIGN 1
+ 2433 ACC0
+ 2434 PUSHACC2
+ 2435 GEINT
+ 2436 BRANCHIF 2418
+ 2438 CONST0
+ 2439 POP 2
+ 2441 ACC0
+ 2442 RETURN 4
+ 2444 RESTART
+ 2445 GRAB 2
+ 2447 ACC1
+ 2448 PUSHCONST0
+ 2449 PUSHACC4
+ 2450 VECTLENGTH
+ 2451 OFFSETINT -1
+ 2453 PUSH
+ 2454 BRANCH 2471
+ 2456 CHECK_SIGNALS
+ 2457 ACC1
+ 2458 PUSHACC6
+ 2459 C_CALL2 array_unsafe_get
+ 2461 PUSHACC3
+ 2462 PUSHACC5
+ 2463 APPLY2
+ 2464 ASSIGN 2
+ 2466 ACC1
+ 2467 OFFSETINT 1
+ 2469 ASSIGN 1
+ 2471 ACC0
+ 2472 PUSHACC2
+ 2473 LEINT
+ 2474 BRANCHIF 2456
+ 2476 CONST0
+ 2477 POP 2
+ 2479 ACC0
+ 2480 RETURN 4
+ 2482 RESTART
+ 2483 GRAB 1
+ 2485 ACC1
+ 2486 BRANCHIFNOT 2502
+ 2488 ACC1
+ 2489 GETFIELD0
+ 2490 PUSHACC1
+ 2491 PUSHENVACC1
+ 2492 C_CALL3 array_unsafe_set
+ 2494 ACC1
+ 2495 GETFIELD1
+ 2496 PUSHACC1
+ 2497 OFFSETINT 1
+ 2499 PUSHOFFSETCLOSURE0
+ 2500 APPTERM2 4
+ 2502 ENVACC1
+ 2503 RETURN 2
+ 2505 ACC0
+ 2506 BRANCHIFNOT 2531
+ 2508 ACC0
+ 2509 GETFIELD1
+ 2510 PUSHACC1
+ 2511 GETFIELD0
+ 2512 PUSHACC1
+ 2513 PUSHGETGLOBALFIELD List, 0
+ 2516 APPLY1
+ 2517 OFFSETINT 1
+ 2519 C_CALL2 make_vect
+ 2521 PUSHACC0
+ 2522 CLOSUREREC 1, 2483
+ 2526 ACC2
+ 2527 PUSHCONST1
+ 2528 PUSHACC2
+ 2529 APPTERM2 6
+ 2531 ATOM0
+ 2532 RETURN 1
+ 2534 RESTART
+ 2535 GRAB 1
+ 2537 CONST0
+ 2538 PUSHACC1
+ 2539 LTINT
+ 2540 BRANCHIFNOT 2545
+ 2542 ACC1
+ 2543 RETURN 2
+ 2545 ACC1
+ 2546 PUSHACC1
+ 2547 PUSHENVACC1
+ 2548 C_CALL2 array_unsafe_get
+ 2550 MAKEBLOCK2 0
+ 2552 PUSHACC1
+ 2553 OFFSETINT -1
+ 2555 PUSHOFFSETCLOSURE0
+ 2556 APPTERM2 4
+ 2558 ACC0
+ 2559 CLOSUREREC 1, 2535
+ 2563 CONST0
+ 2564 PUSHACC2
+ 2565 VECTLENGTH
+ 2566 OFFSETINT -1
+ 2568 PUSHACC2
+ 2569 APPTERM2 4
+ 2571 RESTART
+ 2572 GRAB 1
+ 2574 ACC1
+ 2575 VECTLENGTH
+ 2576 PUSHCONST0
+ 2577 PUSHACC1
+ 2578 EQ
+ 2579 BRANCHIFNOT 2584
+ 2581 ATOM0
+ 2582 RETURN 3
+ 2584 CONST0
+ 2585 PUSHACC3
+ 2586 C_CALL2 array_unsafe_get
+ 2588 PUSHCONST0
+ 2589 PUSHACC3
+ 2590 APPLY2
+ 2591 PUSHACC1
+ 2592 C_CALL2 make_vect
+ 2594 PUSHCONST1
+ 2595 PUSHACC2
+ 2596 OFFSETINT -1
+ 2598 PUSH
+ 2599 BRANCH 2618
+ 2601 CHECK_SIGNALS
+ 2602 ACC1
+ 2603 PUSHACC6
+ 2604 C_CALL2 array_unsafe_get
+ 2606 PUSHACC2
+ 2607 PUSHACC6
+ 2608 APPLY2
+ 2609 PUSHACC2
+ 2610 PUSHACC4
+ 2611 C_CALL3 array_unsafe_set
+ 2613 ACC1
+ 2614 OFFSETINT 1
+ 2616 ASSIGN 1
+ 2618 ACC0
+ 2619 PUSHACC2
+ 2620 LEINT
+ 2621 BRANCHIF 2601
+ 2623 CONST0
+ 2624 POP 2
+ 2626 ACC0
+ 2627 RETURN 4
+ 2629 RESTART
+ 2630 GRAB 1
+ 2632 CONST0
+ 2633 PUSHACC2
+ 2634 VECTLENGTH
+ 2635 OFFSETINT -1
+ 2637 PUSH
+ 2638 BRANCH 2653
+ 2640 CHECK_SIGNALS
+ 2641 ACC1
+ 2642 PUSHACC4
+ 2643 C_CALL2 array_unsafe_get
+ 2645 PUSHACC2
+ 2646 PUSHACC4
+ 2647 APPLY2
+ 2648 ACC1
+ 2649 OFFSETINT 1
+ 2651 ASSIGN 1
+ 2653 ACC0
+ 2654 PUSHACC2
+ 2655 LEINT
+ 2656 BRANCHIF 2640
+ 2658 CONST0
+ 2659 RETURN 4
+ 2661 RESTART
+ 2662 GRAB 1
+ 2664 ACC1
+ 2665 VECTLENGTH
+ 2666 PUSHCONST0
+ 2667 PUSHACC1
+ 2668 EQ
+ 2669 BRANCHIFNOT 2674
+ 2671 ATOM0
+ 2672 RETURN 3
+ 2674 CONST0
+ 2675 PUSHACC3
+ 2676 C_CALL2 array_unsafe_get
+ 2678 PUSHACC2
+ 2679 APPLY1
+ 2680 PUSHACC1
+ 2681 C_CALL2 make_vect
+ 2683 PUSHCONST1
+ 2684 PUSHACC2
+ 2685 OFFSETINT -1
+ 2687 PUSH
+ 2688 BRANCH 2706
+ 2690 CHECK_SIGNALS
+ 2691 ACC1
+ 2692 PUSHACC6
+ 2693 C_CALL2 array_unsafe_get
+ 2695 PUSHACC5
+ 2696 APPLY1
+ 2697 PUSHACC2
+ 2698 PUSHACC4
+ 2699 C_CALL3 array_unsafe_set
+ 2701 ACC1
+ 2702 OFFSETINT 1
+ 2704 ASSIGN 1
+ 2706 ACC0
+ 2707 PUSHACC2
+ 2708 LEINT
+ 2709 BRANCHIF 2690
+ 2711 CONST0
+ 2712 POP 2
+ 2714 ACC0
+ 2715 RETURN 4
+ 2717 RESTART
+ 2718 GRAB 1
+ 2720 CONST0
+ 2721 PUSHACC2
+ 2722 VECTLENGTH
+ 2723 OFFSETINT -1
+ 2725 PUSH
+ 2726 BRANCH 2740
+ 2728 CHECK_SIGNALS
+ 2729 ACC1
+ 2730 PUSHACC4
+ 2731 C_CALL2 array_unsafe_get
+ 2733 PUSHACC3
+ 2734 APPLY1
+ 2735 ACC1
+ 2736 OFFSETINT 1
+ 2738 ASSIGN 1
+ 2740 ACC0
+ 2741 PUSHACC2
+ 2742 LEINT
+ 2743 BRANCHIF 2728
+ 2745 CONST0
+ 2746 RETURN 4
+ 2748 RESTART
+ 2749 GRAB 4
+ 2751 CONST0
+ 2752 PUSHACC5
+ 2753 LTINT
+ 2754 BRANCHIF 2782
+ 2756 CONST0
+ 2757 PUSHACC2
+ 2758 LTINT
+ 2759 BRANCHIF 2782
+ 2761 ACC0
+ 2762 VECTLENGTH
+ 2763 PUSHACC5
+ 2764 PUSHACC3
+ 2765 ADDINT
+ 2766 GTINT
+ 2767 BRANCHIF 2782
+ 2769 CONST0
+ 2770 PUSHACC4
+ 2771 LTINT
+ 2772 BRANCHIF 2782
+ 2774 ACC2
+ 2775 VECTLENGTH
+ 2776 PUSHACC5
+ 2777 PUSHACC5
+ 2778 ADDINT
+ 2779 GTINT
+ 2780 BRANCHIFNOT 2789
+ 2782 GETGLOBAL "Array.blit"
+ 2784 PUSHGETGLOBALFIELD Pervasives, 2
+ 2787 APPTERM1 6
+ 2789 ACC3
+ 2790 PUSHACC2
+ 2791 LTINT
+ 2792 BRANCHIFNOT 2827
+ 2794 ACC4
+ 2795 OFFSETINT -1
+ 2797 PUSHCONST0
+ 2798 PUSH
+ 2799 BRANCH 2819
+ 2801 CHECK_SIGNALS
+ 2802 ACC1
+ 2803 PUSHACC4
+ 2804 ADDINT
+ 2805 PUSHACC3
+ 2806 C_CALL2 array_unsafe_get
+ 2808 PUSHACC2
+ 2809 PUSHACC7
+ 2810 ADDINT
+ 2811 PUSHACC6
+ 2812 C_CALL3 array_unsafe_set
+ 2814 ACC1
+ 2815 OFFSETINT -1
+ 2817 ASSIGN 1
+ 2819 ACC0
+ 2820 PUSHACC2
+ 2821 GEINT
+ 2822 BRANCHIF 2801
+ 2824 CONST0
+ 2825 RETURN 7
+ 2827 CONST0
+ 2828 PUSHACC5
+ 2829 OFFSETINT -1
+ 2831 PUSH
+ 2832 BRANCH 2852
+ 2834 CHECK_SIGNALS
+ 2835 ACC1
+ 2836 PUSHACC4
+ 2837 ADDINT
+ 2838 PUSHACC3
+ 2839 C_CALL2 array_unsafe_get
+ 2841 PUSHACC2
+ 2842 PUSHACC7
+ 2843 ADDINT
+ 2844 PUSHACC6
+ 2845 C_CALL3 array_unsafe_set
+ 2847 ACC1
+ 2848 OFFSETINT 1
+ 2850 ASSIGN 1
+ 2852 ACC0
+ 2853 PUSHACC2
+ 2854 LEINT
+ 2855 BRANCHIF 2834
+ 2857 CONST0
+ 2858 RETURN 7
+ 2860 RESTART
+ 2861 GRAB 3
+ 2863 CONST0
+ 2864 PUSHACC2
+ 2865 LTINT
+ 2866 BRANCHIF 2881
+ 2868 CONST0
+ 2869 PUSHACC3
+ 2870 LTINT
+ 2871 BRANCHIF 2881
+ 2873 ACC0
+ 2874 VECTLENGTH
+ 2875 PUSHACC3
+ 2876 PUSHACC3
+ 2877 ADDINT
+ 2878 GTINT
+ 2879 BRANCHIFNOT 2888
+ 2881 GETGLOBAL "Array.fill"
+ 2883 PUSHGETGLOBALFIELD Pervasives, 2
+ 2886 APPTERM1 5
+ 2888 ACC1
+ 2889 PUSHACC3
+ 2890 PUSHACC3
+ 2891 ADDINT
+ 2892 OFFSETINT -1
+ 2894 PUSH
+ 2895 BRANCH 2908
+ 2897 CHECK_SIGNALS
+ 2898 ACC5
+ 2899 PUSHACC2
+ 2900 PUSHACC4
+ 2901 C_CALL3 array_unsafe_set
+ 2903 ACC1
+ 2904 OFFSETINT 1
+ 2906 ASSIGN 1
+ 2908 ACC0
+ 2909 PUSHACC2
+ 2910 LEINT
+ 2911 BRANCHIF 2897
+ 2913 CONST0
+ 2914 RETURN 6
+ 2916 RESTART
+ 2917 GRAB 2
+ 2919 CONST0
+ 2920 PUSHACC2
+ 2921 LTINT
+ 2922 BRANCHIF 2937
+ 2924 CONST0
+ 2925 PUSHACC3
+ 2926 LTINT
+ 2927 BRANCHIF 2937
+ 2929 ACC0
+ 2930 VECTLENGTH
+ 2931 PUSHACC3
+ 2932 PUSHACC3
+ 2933 ADDINT
+ 2934 GTINT
+ 2935 BRANCHIFNOT 2944
+ 2937 GETGLOBAL "Array.sub"
+ 2939 PUSHGETGLOBALFIELD Pervasives, 2
+ 2942 APPTERM1 4
+ 2944 CONST0
+ 2945 PUSHACC3
+ 2946 EQ
+ 2947 BRANCHIFNOT 2952
+ 2949 ATOM0
+ 2950 RETURN 3
+ 2952 ACC1
+ 2953 PUSHACC1
+ 2954 C_CALL2 array_unsafe_get
+ 2956 PUSHACC3
+ 2957 C_CALL2 make_vect
+ 2959 PUSHCONST1
+ 2960 PUSHACC4
+ 2961 OFFSETINT -1
+ 2963 PUSH
+ 2964 BRANCH 2982
+ 2966 CHECK_SIGNALS
+ 2967 ACC1
+ 2968 PUSHACC5
+ 2969 ADDINT
+ 2970 PUSHACC4
+ 2971 C_CALL2 array_unsafe_get
+ 2973 PUSHACC2
+ 2974 PUSHACC4
+ 2975 C_CALL3 array_unsafe_set
+ 2977 ACC1
+ 2978 OFFSETINT 1
+ 2980 ASSIGN 1
+ 2982 ACC0
+ 2983 PUSHACC2
+ 2984 LEINT
+ 2985 BRANCHIF 2966
+ 2987 CONST0
+ 2988 POP 2
+ 2990 ACC0
+ 2991 RETURN 4
+ 2993 ACC0
+ 2994 BRANCHIFNOT 3017
+ 2996 ACC0
+ 2997 GETFIELD0
+ 2998 PUSHCONST0
+ 2999 PUSHACC1
+ 3000 VECTLENGTH
+ 3001 GTINT
+ 3002 BRANCHIFNOT 3012
+ 3004 ENVACC2
+ 3005 PUSHCONST0
+ 3006 PUSHACC2
+ 3007 C_CALL2 array_unsafe_get
+ 3009 PUSHENVACC1
+ 3010 APPTERM2 4
+ 3012 ACC1
+ 3013 GETFIELD1
+ 3014 PUSHOFFSETCLOSURE0
+ 3015 APPTERM1 3
+ 3017 ATOM0
+ 3018 RETURN 1
+ 3020 ACC0
+ 3021 PUSHENVACC1
+ 3022 CLOSUREREC 2, 2993
+ 3026 ACC1
+ 3027 PUSHACC1
+ 3028 APPTERM1 3
+ 3030 CONST0
+ 3031 PUSHACC1
+ 3032 VECTLENGTH
+ 3033 OFFSETINT -1
+ 3035 PUSH
+ 3036 BRANCH 3056
+ 3038 CHECK_SIGNALS
+ 3039 ACC1
+ 3040 PUSHACC3
+ 3041 C_CALL2 array_unsafe_get
+ 3043 PUSHENVACC2
+ 3044 GETFIELD0
+ 3045 PUSHENVACC1
+ 3046 C_CALL3 array_unsafe_set
+ 3048 ENVACC2
+ 3049 OFFSETREF 1
+ 3051 ACC1
+ 3052 OFFSETINT 1
+ 3054 ASSIGN 1
+ 3056 ACC0
+ 3057 PUSHACC2
+ 3058 LEINT
+ 3059 BRANCHIF 3038
+ 3061 CONST0
+ 3062 RETURN 3
+ 3064 RESTART
+ 3065 GRAB 1
+ 3067 ACC1
+ 3068 VECTLENGTH
+ 3069 PUSHACC1
+ 3070 ADDINT
+ 3071 RETURN 2
+ 3073 RESTART
+ 3074 GRAB 1
+ 3076 ACC1
+ 3077 PUSHCONST0
+ 3078 PUSH
+ 3079 CLOSURE 0, 3065
+ 3082 PUSHGETGLOBALFIELD List, 12
+ 3085 APPLY3
+ 3086 PUSHACC1
+ 3087 PUSHACC1
+ 3088 C_CALL2 make_vect
+ 3090 PUSHCONST0
+ 3091 MAKEBLOCK1 0
+ 3093 PUSHACC4
+ 3094 PUSHACC1
+ 3095 PUSHACC3
+ 3096 CLOSURE 2, 3030
+ 3099 PUSHGETGLOBALFIELD List, 9
+ 3102 APPLY2
+ 3103 ACC1
+ 3104 RETURN 5
+ 3106 RESTART
+ 3107 GRAB 1
+ 3109 ACC0
+ 3110 VECTLENGTH
+ 3111 PUSHACC2
+ 3112 VECTLENGTH
+ 3113 PUSHCONST0
+ 3114 PUSHACC2
+ 3115 EQ
+ 3116 BRANCHIFNOT 3126
+ 3118 CONST0
+ 3119 PUSHACC1
+ 3120 EQ
+ 3121 BRANCHIFNOT 3126
+ 3123 ATOM0
+ 3124 RETURN 4
+ 3126 CONST0
+ 3127 PUSHCONST0
+ 3128 PUSHACC3
+ 3129 GTINT
+ 3130 BRANCHIFNOT 3135
+ 3132 ACC3
+ 3133 BRANCH 3136
+ 3135 ACC4
+ 3136 C_CALL2 array_unsafe_get
+ 3138 PUSHACC1
+ 3139 PUSHACC3
+ 3140 ADDINT
+ 3141 C_CALL2 make_vect
+ 3143 PUSHCONST0
+ 3144 PUSHACC3
+ 3145 OFFSETINT -1
+ 3147 PUSH
+ 3148 BRANCH 3164
+ 3150 CHECK_SIGNALS
+ 3151 ACC1
+ 3152 PUSHACC6
+ 3153 C_CALL2 array_unsafe_get
+ 3155 PUSHACC2
+ 3156 PUSHACC4
+ 3157 C_CALL3 array_unsafe_set
+ 3159 ACC1
+ 3160 OFFSETINT 1
+ 3162 ASSIGN 1
+ 3164 ACC0
+ 3165 PUSHACC2
+ 3166 LEINT
+ 3167 BRANCHIF 3150
+ 3169 CONST0
+ 3170 POP 2
+ 3172 CONST0
+ 3173 PUSHACC2
+ 3174 OFFSETINT -1
+ 3176 PUSH
+ 3177 BRANCH 3195
+ 3179 CHECK_SIGNALS
+ 3180 ACC1
+ 3181 PUSHACC7
+ 3182 C_CALL2 array_unsafe_get
+ 3184 PUSHACC5
+ 3185 PUSHACC3
+ 3186 ADDINT
+ 3187 PUSHACC4
+ 3188 C_CALL3 array_unsafe_set
+ 3190 ACC1
+ 3191 OFFSETINT 1
+ 3193 ASSIGN 1
+ 3195 ACC0
+ 3196 PUSHACC2
+ 3197 LEINT
+ 3198 BRANCHIF 3179
+ 3200 CONST0
+ 3201 POP 2
+ 3203 ACC0
+ 3204 RETURN 5
+ 3206 ACC0
+ 3207 VECTLENGTH
+ 3208 PUSHCONST0
+ 3209 PUSHACC1
+ 3210 EQ
+ 3211 BRANCHIFNOT 3216
+ 3213 ATOM0
+ 3214 RETURN 2
+ 3216 CONST0
+ 3217 PUSHACC2
+ 3218 C_CALL2 array_unsafe_get
+ 3220 PUSHACC1
+ 3221 C_CALL2 make_vect
+ 3223 PUSHCONST1
+ 3224 PUSHACC2
+ 3225 OFFSETINT -1
+ 3227 PUSH
+ 3228 BRANCH 3244
+ 3230 CHECK_SIGNALS
+ 3231 ACC1
+ 3232 PUSHACC5
+ 3233 C_CALL2 array_unsafe_get
+ 3235 PUSHACC2
+ 3236 PUSHACC4
+ 3237 C_CALL3 array_unsafe_set
+ 3239 ACC1
+ 3240 OFFSETINT 1
+ 3242 ASSIGN 1
+ 3244 ACC0
+ 3245 PUSHACC2
+ 3246 LEINT
+ 3247 BRANCHIF 3230
+ 3249 CONST0
+ 3250 POP 2
+ 3252 ACC0
+ 3253 RETURN 3
+ 3255 RESTART
+ 3256 GRAB 2
+ 3258 ATOM0
+ 3259 PUSHACC1
+ 3260 C_CALL2 make_vect
+ 3262 PUSHCONST0
+ 3263 PUSHACC2
+ 3264 OFFSETINT -1
+ 3266 PUSH
+ 3267 BRANCH 3282
+ 3269 CHECK_SIGNALS
+ 3270 ACC5
+ 3271 PUSHACC5
+ 3272 C_CALL2 make_vect
+ 3274 PUSHACC2
+ 3275 PUSHACC4
+ 3276 SETVECTITEM
+ 3277 ACC1
+ 3278 OFFSETINT 1
+ 3280 ASSIGN 1
+ 3282 ACC0
+ 3283 PUSHACC2
+ 3284 LEINT
+ 3285 BRANCHIF 3269
+ 3287 CONST0
+ 3288 POP 2
+ 3290 ACC0
+ 3291 RETURN 4
+ 3293 RESTART
+ 3294 GRAB 1
+ 3296 CONST0
+ 3297 PUSHACC1
+ 3298 EQ
+ 3299 BRANCHIFNOT 3304
+ 3301 ATOM0
+ 3302 RETURN 2
+ 3304 CONST0
+ 3305 PUSHACC2
+ 3306 APPLY1
+ 3307 PUSHACC1
+ 3308 C_CALL2 make_vect
+ 3310 PUSHCONST1
+ 3311 PUSHACC2
+ 3312 OFFSETINT -1
+ 3314 PUSH
+ 3315 BRANCH 3330
+ 3317 CHECK_SIGNALS
+ 3318 ACC1
+ 3319 PUSHACC5
+ 3320 APPLY1
+ 3321 PUSHACC2
+ 3322 PUSHACC4
+ 3323 C_CALL3 array_unsafe_set
+ 3325 ACC1
+ 3326 OFFSETINT 1
+ 3328 ASSIGN 1
+ 3330 ACC0
+ 3331 PUSHACC2
+ 3332 LEINT
+ 3333 BRANCHIF 3317
+ 3335 CONST0
+ 3336 POP 2
+ 3338 ACC0
+ 3339 RETURN 3
+ 3341 CLOSURE 0, 3294
+ 3344 PUSH
+ 3345 CLOSURE 0, 3256
+ 3348 PUSH
+ 3349 CLOSURE 0, 3206
+ 3352 PUSH
+ 3353 CLOSURE 0, 3107
+ 3356 PUSH
+ 3357 CLOSURE 0, 3074
+ 3360 PUSHACC0
+ 3361 CLOSURE 1, 3020
+ 3364 PUSH
+ 3365 CLOSURE 0, 2917
+ 3368 PUSH
+ 3369 CLOSURE 0, 2861
+ 3372 PUSH
+ 3373 CLOSURE 0, 2749
+ 3376 PUSH
+ 3377 CLOSURE 0, 2718
+ 3380 PUSH
+ 3381 CLOSURE 0, 2662
+ 3384 PUSH
+ 3385 CLOSURE 0, 2630
+ 3388 PUSH
+ 3389 CLOSURE 0, 2572
+ 3392 PUSH
+ 3393 CLOSURE 0, 2558
+ 3396 PUSH
+ 3397 CLOSURE 0, 2505
+ 3400 PUSH
+ 3401 CLOSURE 0, 2445
+ 3404 PUSH
+ 3405 CLOSURE 0, 2407
+ 3408 PUSHACC0
+ 3409 PUSHACC2
+ 3410 PUSHACC6
+ 3411 PUSHACC 8
+ 3413 PUSHACC 10
+ 3415 PUSHACC 12
+ 3417 PUSHACC 8
+ 3419 PUSHACC 10
+ 3421 PUSHACC 16
+ 3423 PUSHACC 18
+ 3425 PUSHACC 24
+ 3427 PUSHACC 21
+ 3429 PUSHACC 23
+ 3431 PUSHACC 26
+ 3433 PUSHACC 29
+ 3435 PUSHACC 30
+ 3437 PUSHACC 32
+ 3439 MAKEBLOCK 17, 0
+ 3442 POP 17
+ 3444 SETGLOBAL Array
+ 3446 BRANCH 3480
+ 3448 ENVACC1
+ 3449 MAKEBLOCK1 0
+ 3451 RAISE
+ 3452 ACC0
+ 3453 BRANCHIFNOT 3465
+ 3455 ENVACC3
+ 3456 CLOSURE 1, 3448
+ 3459 MAKEBLOCK1 0
+ 3461 PUSHENVACC2
+ 3462 PUSHENVACC1
+ 3463 APPTERM2 3
+ 3465 CONST0
+ 3466 PUSHENVACC2
+ 3467 PUSHENVACC1
+ 3468 APPTERM2 3
+ 3470 RESTART
+ 3471 GRAB 1
+ 3473 ACC1
+ 3474 PUSHACC1
+ 3475 C_CALL2 install_signal_handler
+ 3477 CONST0
+ 3478 RETURN 2
+ 3480 CONST0
+ 3481 C_CALL1 sys_get_argv
+ 3483 PUSHCONST0
+ 3484 C_CALL1 sys_get_config
+ 3486 PUSHACC0
+ 3487 GETFIELD1
+ 3488 PUSHACC0
+ 3489 OFFSETINT -10
+ 3491 PUSHCONST1
+ 3492 LSLINT
+ 3493 OFFSETINT -1
+ 3495 PUSHACC0
+ 3496 PUSHCONSTINT 8
+ 3498 PUSHACC3
+ 3499 DIVINT
+ 3500 MULINT
+ 3501 OFFSETINT -1
+ 3503 PUSHCONST0
+ 3504 MAKEBLOCK1 0
+ 3506 PUSH
+ 3507 CLOSURE 0, 3471
+ 3510 PUSHCONSTINT -1
+ 3512 PUSHCONSTINT -2
+ 3514 PUSHCONSTINT -3
+ 3516 PUSHCONSTINT -4
+ 3518 PUSHCONSTINT -5
+ 3520 PUSHCONSTINT -6
+ 3522 PUSHCONSTINT -7
+ 3524 PUSHCONSTINT -8
+ 3526 PUSHCONSTINT -9
+ 3528 PUSHCONSTINT -10
+ 3530 PUSHCONSTINT -11
+ 3532 PUSHCONSTINT -12
+ 3534 PUSHCONSTINT -13
+ 3536 PUSHCONSTINT -14
+ 3538 PUSHCONSTINT -15
+ 3540 PUSHCONSTINT -16
+ 3542 PUSHCONSTINT -17
+ 3544 PUSHCONSTINT -18
+ 3546 PUSHCONSTINT -19
+ 3548 PUSHCONSTINT -20
+ 3550 PUSHCONSTINT -21
+ 3552 PUSHGETGLOBAL "Sys.Break"
+ 3554 MAKEBLOCK1 0
+ 3556 PUSHACC0
+ 3557 PUSHACC 17
+ 3559 PUSHACC 24
+ 3561 CLOSURE 3, 3452
+ 3564 PUSHACC0
+ 3565 PUSHACC2
+ 3566 PUSHACC4
+ 3567 PUSHACC6
+ 3568 PUSHACC 8
+ 3570 PUSHACC 10
+ 3572 PUSHACC 12
+ 3574 PUSHACC 14
+ 3576 PUSHACC 16
+ 3578 PUSHACC 18
+ 3580 PUSHACC 20
+ 3582 PUSHACC 22
+ 3584 PUSHACC 24
+ 3586 PUSHACC 26
+ 3588 PUSHACC 28
+ 3590 PUSHACC 30
+ 3592 PUSHACC 32
+ 3594 PUSHACC 34
+ 3596 PUSHACC 36
+ 3598 PUSHACC 38
+ 3600 PUSHACC 40
+ 3602 PUSHACC 42
+ 3604 PUSHACC 44
+ 3606 PUSHACC 46
+ 3608 PUSHACC 50
+ 3610 PUSHACC 50
+ 3612 PUSHACC 53
+ 3614 PUSHACC 55
+ 3616 GETFIELD0
+ 3617 PUSHACC 52
+ 3619 PUSHACC 58
+ 3621 MAKEBLOCK 30, 0
+ 3624 POP 30
+ 3626 SETGLOBAL Sys
+ 3628 BRANCH 4510
+ 3630 RESTART
+ 3631 GRAB 1
+ 3633 CONST0
+ 3634 PUSHACC1
+ 3635 LTINT
+ 3636 BRANCHIFNOT 3641
+ 3638 CONST1
+ 3639 RETURN 2
+ 3641 ACC1
+ 3642 BRANCHIFNOT 3652
+ 3644 ACC1
+ 3645 GETFIELD2
+ 3646 PUSHACC1
+ 3647 OFFSETINT -1
+ 3649 PUSHOFFSETCLOSURE0
+ 3650 APPTERM2 4
+ 3652 RETURN 2
+ 3654 ACC0
+ 3655 BRANCHIFNOT 3670
+ 3657 ENVACC2
+ 3658 PUSHACC1
+ 3659 GETFIELD0
+ 3660 PUSHENVACC1
+ 3661 GETFIELD0
+ 3662 APPLY2
+ 3663 BRANCHIF 3670
+ 3665 ACC0
+ 3666 GETFIELD2
+ 3667 PUSHOFFSETCLOSURE0
+ 3668 APPTERM1 2
+ 3670 RETURN 1
+ 3672 RESTART
+ 3673 GRAB 1
+ 3675 ACC1
+ 3676 PUSHENVACC1
+ 3677 CLOSUREREC 2, 3654
+ 3681 ACC1
+ 3682 GETFIELD1
+ 3683 VECTLENGTH
+ 3684 PUSHACC3
+ 3685 PUSHENVACC1
+ 3686 GETFIELD1
+ 3687 APPLY1
+ 3688 MODINT
+ 3689 PUSHACC2
+ 3690 GETFIELD1
+ 3691 C_CALL2 array_get_addr
+ 3693 PUSHACC1
+ 3694 APPTERM1 4
+ 3696 ACC0
+ 3697 BRANCHIFNOT 3722
+ 3699 ACC0
+ 3700 GETFIELD2
+ 3701 PUSHENVACC2
+ 3702 PUSHACC2
+ 3703 GETFIELD0
+ 3704 PUSHENVACC1
+ 3705 GETFIELD0
+ 3706 APPLY2
+ 3707 BRANCHIFNOT 3718
+ 3709 ACC0
+ 3710 PUSHOFFSETCLOSURE0
+ 3711 APPLY1
+ 3712 PUSHACC2
+ 3713 GETFIELD1
+ 3714 MAKEBLOCK2 0
+ 3716 RETURN 2
+ 3718 ACC0
+ 3719 PUSHOFFSETCLOSURE0
+ 3720 APPTERM1 3
+ 3722 RETURN 1
+ 3724 RESTART
+ 3725 GRAB 1
+ 3727 ACC1
+ 3728 PUSHENVACC1
+ 3729 CLOSUREREC 2, 3696
+ 3733 ACC1
+ 3734 GETFIELD1
+ 3735 VECTLENGTH
+ 3736 PUSHACC3
+ 3737 PUSHENVACC1
+ 3738 GETFIELD1
+ 3739 APPLY1
+ 3740 MODINT
+ 3741 PUSHACC2
+ 3742 GETFIELD1
+ 3743 C_CALL2 array_get_addr
+ 3745 PUSHACC1
+ 3746 APPTERM1 4
+ 3748 ACC0
+ 3749 BRANCHIFNOT 3768
+ 3751 ACC0
+ 3752 GETFIELD0
+ 3753 PUSHENVACC2
+ 3754 PUSHENVACC1
+ 3755 GETFIELD0
+ 3756 APPLY2
+ 3757 BRANCHIFNOT 3763
+ 3759 ACC0
+ 3760 GETFIELD1
+ 3761 RETURN 1
+ 3763 ACC0
+ 3764 GETFIELD2
+ 3765 PUSHOFFSETCLOSURE0
+ 3766 APPTERM1 2
+ 3768 GETGLOBAL Not_found
+ 3770 MAKEBLOCK1 0
+ 3772 RAISE
+ 3773 RESTART
+ 3774 GRAB 1
+ 3776 ACC0
+ 3777 GETFIELD1
+ 3778 VECTLENGTH
+ 3779 PUSHACC2
+ 3780 PUSHENVACC1
+ 3781 GETFIELD1
+ 3782 APPLY1
+ 3783 MODINT
+ 3784 PUSHACC1
+ 3785 GETFIELD1
+ 3786 C_CALL2 array_get_addr
+ 3788 PUSHACC0
+ 3789 BRANCHIFNOT 3858
+ 3791 ACC0
+ 3792 GETFIELD2
+ 3793 PUSHACC1
+ 3794 GETFIELD0
+ 3795 PUSHACC4
+ 3796 PUSHENVACC1
+ 3797 GETFIELD0
+ 3798 APPLY2
+ 3799 BRANCHIFNOT 3805
+ 3801 ACC1
+ 3802 GETFIELD1
+ 3803 RETURN 4
+ 3805 ACC0
+ 3806 BRANCHIFNOT 3853
+ 3808 ACC0
+ 3809 GETFIELD2
+ 3810 PUSHACC1
+ 3811 GETFIELD0
+ 3812 PUSHACC5
+ 3813 PUSHENVACC1
+ 3814 GETFIELD0
+ 3815 APPLY2
+ 3816 BRANCHIFNOT 3822
+ 3818 ACC1
+ 3819 GETFIELD1
+ 3820 RETURN 5
+ 3822 ACC0
+ 3823 BRANCHIFNOT 3848
+ 3825 ACC0
+ 3826 GETFIELD0
+ 3827 PUSHACC5
+ 3828 PUSHENVACC1
+ 3829 GETFIELD0
+ 3830 APPLY2
+ 3831 BRANCHIFNOT 3837
+ 3833 ACC0
+ 3834 GETFIELD1
+ 3835 RETURN 5
+ 3837 ACC4
+ 3838 PUSHENVACC1
+ 3839 CLOSUREREC 2, 3748
+ 3843 ACC1
+ 3844 GETFIELD2
+ 3845 PUSHACC1
+ 3846 APPTERM1 7
+ 3848 GETGLOBAL Not_found
+ 3850 MAKEBLOCK1 0
+ 3852 RAISE
+ 3853 GETGLOBAL Not_found
+ 3855 MAKEBLOCK1 0
+ 3857 RAISE
+ 3858 GETGLOBAL Not_found
+ 3860 MAKEBLOCK1 0
+ 3862 RAISE
+ 3863 ACC0
+ 3864 BRANCHIFNOT 3890
+ 3866 ACC0
+ 3867 GETFIELD0
+ 3868 PUSHACC1
+ 3869 GETFIELD2
+ 3870 PUSHENVACC2
+ 3871 PUSHACC2
+ 3872 PUSHENVACC1
+ 3873 GETFIELD0
+ 3874 APPLY2
+ 3875 BRANCHIFNOT 3880
+ 3877 ACC0
+ 3878 RETURN 3
+ 3880 ACC0
+ 3881 PUSHOFFSETCLOSURE0
+ 3882 APPLY1
+ 3883 PUSHACC3
+ 3884 GETFIELD1
+ 3885 PUSHACC3
+ 3886 MAKEBLOCK3 0
+ 3888 POP 2
+ 3890 RETURN 1
+ 3892 RESTART
+ 3893 GRAB 1
+ 3895 ACC1
+ 3896 PUSHENVACC1
+ 3897 CLOSUREREC 2, 3863
+ 3901 ACC1
+ 3902 GETFIELD1
+ 3903 VECTLENGTH
+ 3904 PUSHACC3
+ 3905 PUSHENVACC1
+ 3906 GETFIELD1
+ 3907 APPLY1
+ 3908 MODINT
+ 3909 PUSHACC0
+ 3910 PUSHACC3
+ 3911 GETFIELD1
+ 3912 C_CALL2 array_get_addr
+ 3914 PUSHACC2
+ 3915 APPLY1
+ 3916 PUSHACC1
+ 3917 PUSHACC4
+ 3918 GETFIELD1
+ 3919 C_CALL3 array_set_addr
+ 3921 RETURN 4
+ 3923 RESTART
+ 3924 GRAB 2
+ 3926 ACC0
+ 3927 GETFIELD1
+ 3928 VECTLENGTH
+ 3929 PUSHACC2
+ 3930 PUSHENVACC3
+ 3931 GETFIELD1
+ 3932 APPLY1
+ 3933 MODINT
+ 3934 PUSHACC0
+ 3935 PUSHACC2
+ 3936 GETFIELD1
+ 3937 C_CALL2 array_get_addr
+ 3939 PUSHACC4
+ 3940 PUSHACC4
+ 3941 MAKEBLOCK3 0
+ 3943 PUSHACC0
+ 3944 PUSHACC2
+ 3945 PUSHACC4
+ 3946 GETFIELD1
+ 3947 C_CALL3 array_set_addr
+ 3949 ACC0
+ 3950 PUSHACC3
+ 3951 GETFIELD0
+ 3952 PUSHENVACC2
+ 3953 APPLY2
+ 3954 BRANCHIFNOT 3962
+ 3956 ACC2
+ 3957 PUSHENVACC3
+ 3958 GETFIELD1
+ 3959 PUSHENVACC1
+ 3960 APPTERM2 7
+ 3962 RETURN 5
+ 3964 ACC0
+ 3965 PUSHENVACC 4
+ 3967 PUSHENVACC3
+ 3968 CLOSURE 3, 3924
+ 3971 PUSHACC1
+ 3972 CLOSURE 1, 3893
+ 3975 PUSHACC2
+ 3976 CLOSURE 1, 3774
+ 3979 PUSHACC3
+ 3980 CLOSURE 1, 3725
+ 3983 PUSHACC4
+ 3984 CLOSURE 1, 3673
+ 3987 PUSHENVACC 5
+ 3989 PUSHACC1
+ 3990 PUSHACC3
+ 3991 PUSHACC5
+ 3992 PUSHACC7
+ 3993 PUSHACC 9
+ 3995 PUSHENVACC2
+ 3996 PUSHENVACC1
+ 3997 MAKEBLOCK 8, 0
+ 4000 RETURN 6
+ 4002 ACC0
+ 4003 BRANCHIFNOT 4016
+ 4005 ACC0
+ 4006 GETFIELD1
+ 4007 PUSHACC1
+ 4008 GETFIELD0
+ 4009 PUSHENVACC1
+ 4010 APPLY2
+ 4011 ACC0
+ 4012 GETFIELD2
+ 4013 PUSHOFFSETCLOSURE0
+ 4014 APPTERM1 2
+ 4016 RETURN 1
+ 4018 RESTART
+ 4019 GRAB 1
+ 4021 ACC0
+ 4022 CLOSUREREC 1, 4002
+ 4026 ACC2
+ 4027 GETFIELD1
+ 4028 PUSHCONST0
+ 4029 PUSHACC1
+ 4030 VECTLENGTH
+ 4031 OFFSETINT -1
+ 4033 PUSH
+ 4034 BRANCH 4048
+ 4036 CHECK_SIGNALS
+ 4037 ACC1
+ 4038 PUSHACC3
+ 4039 C_CALL2 array_get_addr
+ 4041 PUSHACC4
+ 4042 APPLY1
+ 4043 ACC1
+ 4044 OFFSETINT 1
+ 4046 ASSIGN 1
+ 4048 ACC0
+ 4049 PUSHACC2
+ 4050 LEINT
+ 4051 BRANCHIF 4036
+ 4053 CONST0
+ 4054 RETURN 6
+ 4056 ACC0
+ 4057 BRANCHIFNOT 4071
+ 4059 ENVACC1
+ 4060 PUSHACC1
+ 4061 GETFIELD0
+ 4062 C_CALL2 equal
+ 4064 BRANCHIF 4071
+ 4066 ACC0
+ 4067 GETFIELD2
+ 4068 PUSHOFFSETCLOSURE0
+ 4069 APPTERM1 2
+ 4071 RETURN 1
+ 4073 RESTART
+ 4074 GRAB 1
+ 4076 ACC1
+ 4077 CLOSUREREC 1, 4056
+ 4081 ACC1
+ 4082 GETFIELD1
+ 4083 VECTLENGTH
+ 4084 PUSHACC3
+ 4085 PUSHENVACC1
+ 4086 APPLY1
+ 4087 MODINT
+ 4088 PUSHACC2
+ 4089 GETFIELD1
+ 4090 C_CALL2 array_get_addr
+ 4092 PUSHACC1
+ 4093 APPTERM1 4
+ 4095 ACC0
+ 4096 BRANCHIFNOT 4120
+ 4098 ACC0
+ 4099 GETFIELD2
+ 4100 PUSHENVACC1
+ 4101 PUSHACC2
+ 4102 GETFIELD0
+ 4103 C_CALL2 equal
+ 4105 BRANCHIFNOT 4116
+ 4107 ACC0
+ 4108 PUSHOFFSETCLOSURE0
+ 4109 APPLY1
+ 4110 PUSHACC2
+ 4111 GETFIELD1
+ 4112 MAKEBLOCK2 0
+ 4114 RETURN 2
+ 4116 ACC0
+ 4117 PUSHOFFSETCLOSURE0
+ 4118 APPTERM1 3
+ 4120 RETURN 1
+ 4122 RESTART
+ 4123 GRAB 1
+ 4125 ACC1
+ 4126 CLOSUREREC 1, 4095
+ 4130 ACC1
+ 4131 GETFIELD1
+ 4132 VECTLENGTH
+ 4133 PUSHACC3
+ 4134 PUSHENVACC1
+ 4135 APPLY1
+ 4136 MODINT
+ 4137 PUSHACC2
+ 4138 GETFIELD1
+ 4139 C_CALL2 array_get_addr
+ 4141 PUSHACC1
+ 4142 APPTERM1 4
+ 4144 ACC0
+ 4145 BRANCHIFNOT 4163
+ 4147 ACC0
+ 4148 GETFIELD0
+ 4149 PUSHENVACC1
+ 4150 C_CALL2 equal
+ 4152 BRANCHIFNOT 4158
+ 4154 ACC0
+ 4155 GETFIELD1
+ 4156 RETURN 1
+ 4158 ACC0
+ 4159 GETFIELD2
+ 4160 PUSHOFFSETCLOSURE0
+ 4161 APPTERM1 2
+ 4163 GETGLOBAL Not_found
+ 4165 MAKEBLOCK1 0
+ 4167 RAISE
+ 4168 RESTART
+ 4169 GRAB 1
+ 4171 ACC0
+ 4172 GETFIELD1
+ 4173 VECTLENGTH
+ 4174 PUSHACC2
+ 4175 PUSHENVACC1
+ 4176 APPLY1
+ 4177 MODINT
+ 4178 PUSHACC1
+ 4179 GETFIELD1
+ 4180 C_CALL2 array_get_addr
+ 4182 PUSHACC0
+ 4183 BRANCHIFNOT 4248
+ 4185 ACC0
+ 4186 GETFIELD2
+ 4187 PUSHACC1
+ 4188 GETFIELD0
+ 4189 PUSHACC4
+ 4190 C_CALL2 equal
+ 4192 BRANCHIFNOT 4198
+ 4194 ACC1
+ 4195 GETFIELD1
+ 4196 RETURN 4
+ 4198 ACC0
+ 4199 BRANCHIFNOT 4243
+ 4201 ACC0
+ 4202 GETFIELD2
+ 4203 PUSHACC1
+ 4204 GETFIELD0
+ 4205 PUSHACC5
+ 4206 C_CALL2 equal
+ 4208 BRANCHIFNOT 4214
+ 4210 ACC1
+ 4211 GETFIELD1
+ 4212 RETURN 5
+ 4214 ACC0
+ 4215 BRANCHIFNOT 4238
+ 4217 ACC0
+ 4218 GETFIELD0
+ 4219 PUSHACC5
+ 4220 C_CALL2 equal
+ 4222 BRANCHIFNOT 4228
+ 4224 ACC0
+ 4225 GETFIELD1
+ 4226 RETURN 5
+ 4228 ACC4
+ 4229 CLOSUREREC 1, 4144
+ 4233 ACC1
+ 4234 GETFIELD2
+ 4235 PUSHACC1
+ 4236 APPTERM1 7
+ 4238 GETGLOBAL Not_found
+ 4240 MAKEBLOCK1 0
+ 4242 RAISE
+ 4243 GETGLOBAL Not_found
+ 4245 MAKEBLOCK1 0
+ 4247 RAISE
+ 4248 GETGLOBAL Not_found
+ 4250 MAKEBLOCK1 0
+ 4252 RAISE
+ 4253 ACC0
+ 4254 BRANCHIFNOT 4279
+ 4256 ACC0
+ 4257 GETFIELD0
+ 4258 PUSHACC1
+ 4259 GETFIELD2
+ 4260 PUSHENVACC1
+ 4261 PUSHACC2
+ 4262 C_CALL2 equal
+ 4264 BRANCHIFNOT 4269
+ 4266 ACC0
+ 4267 RETURN 3
+ 4269 ACC0
+ 4270 PUSHOFFSETCLOSURE0
+ 4271 APPLY1
+ 4272 PUSHACC3
+ 4273 GETFIELD1
+ 4274 PUSHACC3
+ 4275 MAKEBLOCK3 0
+ 4277 POP 2
+ 4279 RETURN 1
+ 4281 RESTART
+ 4282 GRAB 1
+ 4284 ACC1
+ 4285 CLOSUREREC 1, 4253
+ 4289 ACC1
+ 4290 GETFIELD1
+ 4291 VECTLENGTH
+ 4292 PUSHACC3
+ 4293 PUSHENVACC1
+ 4294 APPLY1
+ 4295 MODINT
+ 4296 PUSHACC0
+ 4297 PUSHACC3
+ 4298 GETFIELD1
+ 4299 C_CALL2 array_get_addr
+ 4301 PUSHACC2
+ 4302 APPLY1
+ 4303 PUSHACC1
+ 4304 PUSHACC4
+ 4305 GETFIELD1
+ 4306 C_CALL3 array_set_addr
+ 4308 RETURN 4
+ 4310 RESTART
+ 4311 GRAB 2
+ 4313 ACC0
+ 4314 GETFIELD1
+ 4315 VECTLENGTH
+ 4316 PUSHACC2
+ 4317 PUSHENVACC1
+ 4318 APPLY1
+ 4319 MODINT
+ 4320 PUSHACC0
+ 4321 PUSHACC2
+ 4322 GETFIELD1
+ 4323 C_CALL2 array_get_addr
+ 4325 PUSHACC4
+ 4326 PUSHACC4
+ 4327 MAKEBLOCK3 0
+ 4329 PUSHACC0
+ 4330 PUSHACC2
+ 4331 PUSHACC4
+ 4332 GETFIELD1
+ 4333 C_CALL3 array_set_addr
+ 4335 ACC0
+ 4336 PUSHACC3
+ 4337 GETFIELD0
+ 4338 PUSHENVACC3
+ 4339 APPLY2
+ 4340 BRANCHIFNOT 4347
+ 4342 ACC2
+ 4343 PUSHENVACC1
+ 4344 PUSHENVACC2
+ 4345 APPTERM2 7
+ 4347 RETURN 5
+ 4349 ACC0
+ 4350 BRANCHIFNOT 4378
+ 4352 ACC0
+ 4353 GETFIELD0
+ 4354 PUSHACC1
+ 4355 GETFIELD2
+ 4356 PUSHOFFSETCLOSURE0
+ 4357 APPLY1
+ 4358 ENVACC2
+ 4359 PUSHACC1
+ 4360 PUSHENVACC1
+ 4361 APPLY1
+ 4362 MODINT
+ 4363 PUSHACC0
+ 4364 PUSHENVACC3
+ 4365 C_CALL2 array_get_addr
+ 4367 PUSHACC3
+ 4368 GETFIELD1
+ 4369 PUSHACC3
+ 4370 MAKEBLOCK3 0
+ 4372 PUSHACC1
+ 4373 PUSHENVACC3
+ 4374 C_CALL3 array_set_addr
+ 4376 POP 2
+ 4378 RETURN 1
+ 4380 RESTART
+ 4381 GRAB 1
+ 4383 ACC1
+ 4384 GETFIELD1
+ 4385 PUSHACC0
+ 4386 VECTLENGTH
+ 4387 PUSHACC0
+ 4388 PUSHCONST2
+ 4389 MULINT
+ 4390 OFFSETINT 1
+ 4392 PUSHCONST0
+ 4393 PUSHACC1
+ 4394 C_CALL2 make_vect
+ 4396 PUSHACC0
+ 4397 PUSHACC2
+ 4398 PUSHACC6
+ 4399 CLOSUREREC 3, 4349
+ 4403 CONST0
+ 4404 PUSHACC4
+ 4405 OFFSETINT -1
+ 4407 PUSH
+ 4408 BRANCH 4422
+ 4410 CHECK_SIGNALS
+ 4411 ACC1
+ 4412 PUSHACC7
+ 4413 C_CALL2 array_get_addr
+ 4415 PUSHACC3
+ 4416 APPLY1
+ 4417 ACC1
+ 4418 OFFSETINT 1
+ 4420 ASSIGN 1
+ 4422 ACC0
+ 4423 PUSHACC2
+ 4424 LEINT
+ 4425 BRANCHIF 4410
+ 4427 CONST0
+ 4428 POP 2
+ 4430 ACC1
+ 4431 PUSHACC7
+ 4432 SETFIELD1
+ 4433 ACC6
+ 4434 GETFIELD0
+ 4435 PUSHCONST2
+ 4436 MULINT
+ 4437 PUSHACC7
+ 4438 SETFIELD0
+ 4439 RETURN 7
+ 4441 CONST0
+ 4442 PUSHACC1
+ 4443 GETFIELD1
+ 4444 VECTLENGTH
+ 4445 OFFSETINT -1
+ 4447 PUSH
+ 4448 BRANCH 4462
+ 4450 CHECK_SIGNALS
+ 4451 CONST0
+ 4452 PUSHACC2
+ 4453 PUSHACC4
+ 4454 GETFIELD1
+ 4455 C_CALL3 array_set_addr
+ 4457 ACC1
+ 4458 OFFSETINT 1
+ 4460 ASSIGN 1
+ 4462 ACC0
+ 4463 PUSHACC2
+ 4464 LEINT
+ 4465 BRANCHIF 4450
+ 4467 CONST0
+ 4468 RETURN 3
+ 4470 CONST1
+ 4471 PUSHACC1
+ 4472 LTINT
+ 4473 BRANCHIFNOT 4478
+ 4475 CONST1
+ 4476 BRANCH 4479
+ 4478 ACC0
+ 4479 PUSHGETGLOBALFIELD Sys, 5
+ 4482 PUSHACC1
+ 4483 GTINT
+ 4484 BRANCHIFNOT 4491
+ 4486 GETGLOBALFIELD Sys, 5
+ 4489 BRANCH 4492
+ 4491 ACC0
+ 4492 PUSHCONST0
+ 4493 PUSHACC1
+ 4494 C_CALL2 make_vect
+ 4496 PUSHCONST3
+ 4497 MAKEBLOCK2 0
+ 4499 RETURN 3
+ 4501 ACC0
+ 4502 PUSHCONSTINT 100
+ 4504 PUSHCONSTINT 10
+ 4506 C_CALL3 hash_univ_param
+ 4508 RETURN 1
+ 4510 CLOSURE 0, 4501
+ 4513 PUSH
+ 4514 CLOSURE 0, 4470
+ 4517 PUSH
+ 4518 CLOSURE 0, 4441
+ 4521 PUSH
+ 4522 CLOSURE 0, 4381
+ 4525 PUSH
+ 4526 CLOSUREREC 0, 3631
+ 4530 ACC0
+ 4531 PUSHACC2
+ 4532 PUSHACC6
+ 4533 CLOSURE 3, 4311
+ 4536 PUSHACC5
+ 4537 CLOSURE 1, 4282
+ 4540 PUSHACC6
+ 4541 CLOSURE 1, 4169
+ 4544 PUSHACC7
+ 4545 CLOSURE 1, 4123
+ 4548 PUSHACC 8
+ 4550 CLOSURE 1, 4074
+ 4553 PUSH
+ 4554 CLOSURE 0, 4019
+ 4557 PUSHACC0
+ 4558 PUSHACC7
+ 4559 PUSHACC 9
+ 4561 PUSHACC 11
+ 4563 PUSHACC 13
+ 4565 CLOSURE 5, 3964
+ 4568 PUSHACC 11
+ 4570 PUSHACC1
+ 4571 PUSHACC3
+ 4572 PUSHACC 8
+ 4574 PUSHACC6
+ 4575 PUSHACC 8
+ 4577 PUSHACC 10
+ 4579 PUSHACC 13
+ 4581 PUSHACC 17
+ 4583 PUSHACC 19
+ 4585 MAKEBLOCK 10, 0
+ 4588 POP 12
+ 4590 SETGLOBAL Hashtbl
+ 4592 BRANCH 5073
+ 4594 RESTART
+ 4595 GRAB 2
+ 4597 ACC1
+ 4598 BRANCHIFNOT 4638
+ 4600 ACC1
+ 4601 GETFIELD0
+ 4602 PUSHACC3
+ 4603 BRANCHIFNOT 4635
+ 4605 ACC3
+ 4606 GETFIELD0
+ 4607 PUSHACC0
+ 4608 PUSHACC2
+ 4609 PUSHACC4
+ 4610 APPLY2
+ 4611 BRANCHIFNOT 4624
+ 4613 ACC4
+ 4614 PUSHACC4
+ 4615 GETFIELD1
+ 4616 PUSHACC4
+ 4617 PUSHOFFSETCLOSURE0
+ 4618 APPLY3
+ 4619 PUSHACC2
+ 4620 MAKEBLOCK2 0
+ 4622 RETURN 5
+ 4624 ACC4
+ 4625 GETFIELD1
+ 4626 PUSHACC4
+ 4627 PUSHACC4
+ 4628 PUSHOFFSETCLOSURE0
+ 4629 APPLY3
+ 4630 PUSHACC1
+ 4631 MAKEBLOCK2 0
+ 4633 RETURN 5
+ 4635 ACC2
+ 4636 RETURN 4
+ 4638 ACC2
+ 4639 RETURN 3
+ 4641 RESTART
+ 4642 GRAB 1
+ 4644 CONSTINT 6
+ 4646 PUSHACC1
+ 4647 PUSHACC3
+ 4648 SUBINT
+ 4649 GEINT
+ 4650 BRANCHIFNOT 4809
+ 4652 CONST1
+ 4653 PUSHACC2
+ 4654 PUSHACC2
+ 4655 ADDINT
+ 4656 LSRINT
+ 4657 PUSHACC1
+ 4658 PUSHENVACC3
+ 4659 C_CALL2 array_unsafe_get
+ 4661 PUSHACC1
+ 4662 PUSHENVACC3
+ 4663 C_CALL2 array_unsafe_get
+ 4665 PUSHENVACC2
+ 4666 APPLY2
+ 4667 BRANCHIFNOT 4674
+ 4669 ACC1
+ 4670 PUSHACC1
+ 4671 PUSHENVACC3
+ 4672 PUSHENVACC1
+ 4673 APPLY3
+ 4674 ACC0
+ 4675 PUSHENVACC3
+ 4676 C_CALL2 array_unsafe_get
+ 4678 PUSHACC3
+ 4679 PUSHENVACC3
+ 4680 C_CALL2 array_unsafe_get
+ 4682 PUSHENVACC2
+ 4683 APPLY2
+ 4684 BRANCHIFNOT 4708
+ 4686 ACC2
+ 4687 PUSHACC1
+ 4688 PUSHENVACC3
+ 4689 PUSHENVACC1
+ 4690 APPLY3
+ 4691 ACC1
+ 4692 PUSHENVACC3
+ 4693 C_CALL2 array_unsafe_get
+ 4695 PUSHACC1
+ 4696 PUSHENVACC3
+ 4697 C_CALL2 array_unsafe_get
+ 4699 PUSHENVACC2
+ 4700 APPLY2
+ 4701 BRANCHIFNOT 4708
+ 4703 ACC1
+ 4704 PUSHACC1
+ 4705 PUSHENVACC3
+ 4706 PUSHENVACC1
+ 4707 APPLY3
+ 4708 ACC0
+ 4709 PUSHENVACC3
+ 4710 C_CALL2 array_unsafe_get
+ 4712 PUSHACC2
+ 4713 OFFSETINT 1
+ 4715 PUSHACC4
+ 4716 OFFSETINT -1
+ 4718 PUSH
+ 4719 BRANCH 4777
+ 4721 CHECK_SIGNALS
+ 4722 BRANCH 4730
+ 4724 CHECK_SIGNALS
+ 4725 ACC1
+ 4726 OFFSETINT 1
+ 4728 ASSIGN 1
+ 4730 ACC1
+ 4731 PUSHENVACC3
+ 4732 C_CALL2 array_unsafe_get
+ 4734 PUSHACC3
+ 4735 PUSHENVACC2
+ 4736 APPLY2
+ 4737 BRANCHIFNOT 4724
+ 4739 CONST0
+ 4740 BRANCH 4748
+ 4742 CHECK_SIGNALS
+ 4743 ACC0
+ 4744 OFFSETINT -1
+ 4746 ASSIGN 0
+ 4748 ACC2
+ 4749 PUSHACC1
+ 4750 PUSHENVACC3
+ 4751 C_CALL2 array_unsafe_get
+ 4753 PUSHENVACC2
+ 4754 APPLY2
+ 4755 BRANCHIFNOT 4742
+ 4757 ACC0
+ 4758 PUSHACC2
+ 4759 LTINT
+ 4760 BRANCHIFNOT 4767
+ 4762 ACC0
+ 4763 PUSHACC2
+ 4764 PUSHENVACC3
+ 4765 PUSHENVACC1
+ 4766 APPLY3
+ 4767 ACC1
+ 4768 OFFSETINT 1
+ 4770 ASSIGN 1
+ 4772 ACC0
+ 4773 OFFSETINT -1
+ 4775 ASSIGN 0
+ 4777 ACC0
+ 4778 PUSHACC2
+ 4779 LTINT
+ 4780 BRANCHIF 4721
+ 4782 ACC1
+ 4783 PUSHACC6
+ 4784 SUBINT
+ 4785 PUSHACC5
+ 4786 PUSHACC2
+ 4787 SUBINT
+ 4788 LEINT
+ 4789 BRANCHIFNOT 4800
+ 4791 ACC0
+ 4792 PUSHACC5
+ 4793 PUSHOFFSETCLOSURE0
+ 4794 APPLY2
+ 4795 ACC5
+ 4796 PUSHACC2
+ 4797 PUSHOFFSETCLOSURE0
+ 4798 APPTERM2 8
+ 4800 ACC5
+ 4801 PUSHACC2
+ 4802 PUSHOFFSETCLOSURE0
+ 4803 APPLY2
+ 4804 ACC0
+ 4805 PUSHACC5
+ 4806 PUSHOFFSETCLOSURE0
+ 4807 APPTERM2 8
+ 4809 RETURN 2
+ 4811 RESTART
+ 4812 GRAB 1
+ 4814 ACC1
+ 4815 PUSHACC1
+ 4816 PUSHENVACC1
+ 4817 CLOSUREREC 3, 4642
+ 4821 ACC2
+ 4822 VECTLENGTH
+ 4823 OFFSETINT -1
+ 4825 PUSHCONST0
+ 4826 PUSHACC2
+ 4827 APPLY2
+ 4828 CONST1
+ 4829 PUSHACC3
+ 4830 VECTLENGTH
+ 4831 OFFSETINT -1
+ 4833 PUSH
+ 4834 BRANCH 4918
+ 4836 CHECK_SIGNALS
+ 4837 ACC1
+ 4838 PUSHACC5
+ 4839 C_CALL2 array_unsafe_get
+ 4841 PUSHACC0
+ 4842 PUSHACC3
+ 4843 OFFSETINT -1
+ 4845 PUSHACC7
+ 4846 C_CALL2 array_unsafe_get
+ 4848 PUSHACC6
+ 4849 APPLY2
+ 4850 BOOLNOT
+ 4851 BRANCHIFNOT 4911
+ 4853 ACC2
+ 4854 OFFSETINT -1
+ 4856 PUSHACC6
+ 4857 C_CALL2 array_unsafe_get
+ 4859 PUSHACC3
+ 4860 PUSHACC7
+ 4861 C_CALL3 array_unsafe_set
+ 4863 ACC2
+ 4864 OFFSETINT -1
+ 4866 PUSH
+ 4867 BRANCH 4886
+ 4869 CHECK_SIGNALS
+ 4870 ACC0
+ 4871 OFFSETINT -1
+ 4873 PUSHACC7
+ 4874 C_CALL2 array_unsafe_get
+ 4876 PUSHACC1
+ 4877 PUSHACC 8
+ 4879 C_CALL3 array_unsafe_set
+ 4881 ACC0
+ 4882 OFFSETINT -1
+ 4884 ASSIGN 0
+ 4886 CONST1
+ 4887 PUSHACC1
+ 4888 GEINT
+ 4889 BRANCHIFNOT 4903
+ 4891 ACC1
+ 4892 PUSHACC1
+ 4893 OFFSETINT -1
+ 4895 PUSHACC 8
+ 4897 C_CALL2 array_unsafe_get
+ 4899 PUSHACC7
+ 4900 APPLY2
+ 4901 BRANCHIFNOT 4869
+ 4903 ACC1
+ 4904 PUSHACC1
+ 4905 PUSHACC 8
+ 4907 C_CALL3 array_unsafe_set
+ 4909 POP 1
+ 4911 POP 1
+ 4913 ACC1
+ 4914 OFFSETINT 1
+ 4916 ASSIGN 1
+ 4918 ACC0
+ 4919 PUSHACC2
+ 4920 LEINT
+ 4921 BRANCHIF 4836
+ 4923 CONST0
+ 4924 RETURN 5
+ 4926 RESTART
+ 4927 GRAB 2
+ 4929 ACC1
+ 4930 PUSHACC1
+ 4931 C_CALL2 array_unsafe_get
+ 4933 PUSHACC3
+ 4934 PUSHACC2
+ 4935 C_CALL2 array_unsafe_get
+ 4937 PUSHACC3
+ 4938 PUSHACC3
+ 4939 C_CALL3 array_unsafe_set
+ 4941 ACC0
+ 4942 PUSHACC4
+ 4943 PUSHACC3
+ 4944 C_CALL3 array_unsafe_set
+ 4946 RETURN 4
+ 4948 ACC0
+ 4949 BRANCHIFNOT 4999
+ 4951 ACC0
+ 4952 GETFIELD0
+ 4953 PUSHACC1
+ 4954 GETFIELD1
+ 4955 PUSHACC0
+ 4956 BRANCHIFNOT 4990
+ 4958 ACC0
+ 4959 GETFIELD0
+ 4960 PUSHACC1
+ 4961 GETFIELD1
+ 4962 PUSHOFFSETCLOSURE0
+ 4963 APPLY1
+ 4964 PUSHACC1
+ 4965 PUSHACC4
+ 4966 PUSHENVACC1
+ 4967 APPLY2
+ 4968 BRANCHIFNOT 4979
+ 4970 CONST0
+ 4971 PUSHACC2
+ 4972 MAKEBLOCK2 0
+ 4974 PUSHACC4
+ 4975 MAKEBLOCK2 0
+ 4977 BRANCH 4986
+ 4979 CONST0
+ 4980 PUSHACC4
+ 4981 MAKEBLOCK2 0
+ 4983 PUSHACC2
+ 4984 MAKEBLOCK2 0
+ 4986 MAKEBLOCK2 0
+ 4988 RETURN 4
+ 4990 CONST0
+ 4991 PUSHCONST0
+ 4992 PUSHACC3
+ 4993 MAKEBLOCK2 0
+ 4995 MAKEBLOCK2 0
+ 4997 POP 2
+ 4999 RETURN 1
+ 5001 ACC0
+ 5002 BRANCHIFNOT 5028
+ 5004 ACC0
+ 5005 GETFIELD1
+ 5006 PUSHACC0
+ 5007 BRANCHIFNOT 5024
+ 5009 ACC0
+ 5010 GETFIELD1
+ 5011 PUSHOFFSETCLOSURE0
+ 5012 APPLY1
+ 5013 PUSHACC1
+ 5014 GETFIELD0
+ 5015 PUSHACC3
+ 5016 GETFIELD0
+ 5017 PUSHENVACC2
+ 5018 PUSHENVACC1
+ 5019 APPLY3
+ 5020 MAKEBLOCK2 0
+ 5022 RETURN 2
+ 5024 POP 1
+ 5026 BRANCH 5028
+ 5028 ACC0
+ 5029 RETURN 1
+ 5031 ACC0
+ 5032 BRANCHIFNOT 5040
+ 5034 ACC0
+ 5035 GETFIELD1
+ 5036 BRANCHIF 5042
+ 5038 ACC0
+ 5039 GETFIELD0
+ 5040 RETURN 1
+ 5042 ACC0
+ 5043 PUSHENVACC1
+ 5044 APPLY1
+ 5045 PUSHOFFSETCLOSURE0
+ 5046 APPTERM1 2
+ 5048 RESTART
+ 5049 GRAB 1
+ 5051 ACC0
+ 5052 CLOSUREREC 1, 4948
+ 5056 ACC1
+ 5057 PUSHENVACC1
+ 5058 CLOSUREREC 2, 5001
+ 5062 ACC0
+ 5063 CLOSUREREC 1, 5031
+ 5067 ACC4
+ 5068 PUSHACC3
+ 5069 APPLY1
+ 5070 PUSHACC1
+ 5071 APPTERM1 6
+ 5073 CLOSUREREC 0, 4595
+ 5077 ACC0
+ 5078 CLOSURE 1, 5049
+ 5081 PUSH
+ 5082 CLOSURE 0, 4927
+ 5085 PUSHACC0
+ 5086 CLOSURE 1, 4812
+ 5089 PUSHACC3
+ 5090 PUSHACC1
+ 5091 PUSHACC4
+ 5092 MAKEBLOCK3 0
+ 5094 POP 4
+ 5096 SETGLOBAL Sort
+ 5098 BRANCH 5847
+ 5100 ACC0
+ 5101 PUSHENVACC1
+ 5102 APPLY1
+ 5103 PUSHACC0
+ 5104 GETFIELD 11
+ 5106 PUSHACC1
+ 5107 GETFIELD 10
+ 5109 PUSHACC2
+ 5110 GETFIELD 9
+ 5112 PUSHACC3
+ 5113 GETFIELD 6
+ 5115 PUSHACC4
+ 5116 GETFIELD 8
+ 5118 PUSHACC5
+ 5119 GETFIELD 5
+ 5121 PUSHACC6
+ 5122 GETFIELD 4
+ 5124 PUSHACC7
+ 5125 GETFIELD0
+ 5126 MAKEBLOCK 8, 0
+ 5129 RETURN 2
+ 5131 RESTART
+ 5132 GRAB 2
+ 5134 ACC2
+ 5135 BRANCHIFNOT 5201
+ 5137 ACC2
+ 5138 GETFIELD0
+ 5139 PUSHACC3
+ 5140 GETFIELD1
+ 5141 PUSHACC4
+ 5142 GETFIELD2
+ 5143 PUSHACC5
+ 5144 GETFIELD3
+ 5145 PUSHACC2
+ 5146 PUSHACC5
+ 5147 PUSHENVACC1
+ 5148 GETFIELD0
+ 5149 APPLY2
+ 5150 PUSHCONST0
+ 5151 PUSHACC1
+ 5152 EQ
+ 5153 BRANCHIFNOT 5170
+ 5155 ACC7
+ 5156 GETFIELD 4
+ 5158 PUSHACC2
+ 5159 PUSHACC 8
+ 5161 PUSHACC 8
+ 5163 PUSHACC 8
+ 5165 MAKEBLOCK 5, 0
+ 5168 RETURN 8
+ 5170 CONST0
+ 5171 PUSHACC1
+ 5172 LTINT
+ 5173 BRANCHIFNOT 5189
+ 5175 ACC1
+ 5176 PUSHACC3
+ 5177 PUSHACC5
+ 5178 PUSHACC7
+ 5179 PUSHACC 10
+ 5181 PUSHACC 10
+ 5183 PUSHOFFSETCLOSURE0
+ 5184 APPLY3
+ 5185 PUSHENVACC2
+ 5186 APPTERM 4, 12
+ 5189 ACC1
+ 5190 PUSHACC7
+ 5191 PUSHACC7
+ 5192 PUSHOFFSETCLOSURE0
+ 5193 APPLY3
+ 5194 PUSHACC3
+ 5195 PUSHACC5
+ 5196 PUSHACC7
+ 5197 PUSHENVACC2
+ 5198 APPTERM 4, 12
+ 5201 CONST1
+ 5202 PUSHCONST0
+ 5203 PUSHACC3
+ 5204 PUSHACC3
+ 5205 PUSHCONST0
+ 5206 MAKEBLOCK 5, 0
+ 5209 RETURN 3
+ 5211 RESTART
+ 5212 GRAB 1
+ 5214 ACC1
+ 5215 BRANCHIFNOT 5247
+ 5217 ACC1
+ 5218 GETFIELD1
+ 5219 PUSHACC1
+ 5220 PUSHENVACC1
+ 5221 GETFIELD0
+ 5222 APPLY2
+ 5223 PUSHCONST0
+ 5224 PUSHACC1
+ 5225 EQ
+ 5226 BRANCHIFNOT 5232
+ 5228 ACC2
+ 5229 GETFIELD2
+ 5230 RETURN 3
+ 5232 CONST0
+ 5233 PUSHACC1
+ 5234 LTINT
+ 5235 BRANCHIFNOT 5241
+ 5237 ACC2
+ 5238 GETFIELD0
+ 5239 BRANCH 5243
+ 5241 ACC2
+ 5242 GETFIELD3
+ 5243 PUSHACC2
+ 5244 PUSHOFFSETCLOSURE0
+ 5245 APPTERM2 5
+ 5247 GETGLOBAL Not_found
+ 5249 MAKEBLOCK1 0
+ 5251 RAISE
+ 5252 RESTART
+ 5253 GRAB 1
+ 5255 ACC1
+ 5256 BRANCHIFNOT 5286
+ 5258 ACC1
+ 5259 GETFIELD1
+ 5260 PUSHACC1
+ 5261 PUSHENVACC1
+ 5262 GETFIELD0
+ 5263 APPLY2
+ 5264 PUSHCONST0
+ 5265 PUSHACC1
+ 5266 EQ
+ 5267 BRANCHIF 5284
+ 5269 CONST0
+ 5270 PUSHACC1
+ 5271 LTINT
+ 5272 BRANCHIFNOT 5278
+ 5274 ACC2
+ 5275 GETFIELD0
+ 5276 BRANCH 5280
+ 5278 ACC2
+ 5279 GETFIELD3
+ 5280 PUSHACC2
+ 5281 PUSHOFFSETCLOSURE0
+ 5282 APPTERM2 5
+ 5284 POP 1
+ 5286 RETURN 2
+ 5288 RESTART
+ 5289 GRAB 1
+ 5291 ACC0
+ 5292 BRANCHIF 5297
+ 5294 ACC1
+ 5295 RETURN 2
+ 5297 ACC1
+ 5298 BRANCHIF 5303
+ 5300 ACC0
+ 5301 RETURN 2
+ 5303 ACC0
+ 5304 BRANCHIFNOT 5336
+ 5306 ACC1
+ 5307 BRANCHIFNOT 5336
+ 5309 PUSH_RETADDR 5326
+ 5311 ACC4
+ 5312 GETFIELD3
+ 5313 PUSHACC5
+ 5314 GETFIELD2
+ 5315 PUSHACC6
+ 5316 GETFIELD1
+ 5317 PUSHACC7
+ 5318 GETFIELD0
+ 5319 PUSHACC7
+ 5320 GETFIELD3
+ 5321 PUSHOFFSETCLOSURE0
+ 5322 APPLY2
+ 5323 PUSHENVACC1
+ 5324 APPLY 4
+ 5326 PUSHACC1
+ 5327 GETFIELD2
+ 5328 PUSHACC2
+ 5329 GETFIELD1
+ 5330 PUSHACC3
+ 5331 GETFIELD0
+ 5332 PUSHENVACC1
+ 5333 APPTERM 4, 6
+ 5336 GETGLOBAL <0>("map.ml", 3614, 3797)
+ 5338 PUSHGETGLOBAL Match_failure
+ 5340 MAKEBLOCK2 0
+ 5342 RAISE
+ 5343 RESTART
+ 5344 GRAB 1
+ 5346 ACC1
+ 5347 BRANCHIFNOT 5400
+ 5349 ACC1
+ 5350 GETFIELD0
+ 5351 PUSHACC2
+ 5352 GETFIELD1
+ 5353 PUSHACC3
+ 5354 GETFIELD2
+ 5355 PUSHACC4
+ 5356 GETFIELD3
+ 5357 PUSHACC2
+ 5358 PUSHACC5
+ 5359 PUSHENVACC1
+ 5360 GETFIELD0
+ 5361 APPLY2
+ 5362 PUSHCONST0
+ 5363 PUSHACC1
+ 5364 EQ
+ 5365 BRANCHIFNOT 5372
+ 5367 ACC1
+ 5368 PUSHACC5
+ 5369 PUSHENVACC3
+ 5370 APPTERM2 9
+ 5372 CONST0
+ 5373 PUSHACC1
+ 5374 LTINT
+ 5375 BRANCHIFNOT 5389
+ 5377 ACC1
+ 5378 PUSHACC3
+ 5379 PUSHACC5
+ 5380 PUSHACC7
+ 5381 PUSHACC 9
+ 5383 PUSHOFFSETCLOSURE0
+ 5384 APPLY2
+ 5385 PUSHENVACC2
+ 5386 APPTERM 4, 11
+ 5389 ACC1
+ 5390 PUSHACC6
+ 5391 PUSHOFFSETCLOSURE0
+ 5392 APPLY2
+ 5393 PUSHACC3
+ 5394 PUSHACC5
+ 5395 PUSHACC7
+ 5396 PUSHENVACC2
+ 5397 APPTERM 4, 11
+ 5400 RETURN 2
+ 5402 RESTART
+ 5403 GRAB 1
+ 5405 ACC1
+ 5406 BRANCHIFNOT 5425
+ 5408 ACC1
+ 5409 GETFIELD0
+ 5410 PUSHACC1
+ 5411 PUSHOFFSETCLOSURE0
+ 5412 APPLY2
+ 5413 ACC1
+ 5414 GETFIELD2
+ 5415 PUSHACC2
+ 5416 GETFIELD1
+ 5417 PUSHACC2
+ 5418 APPLY2
+ 5419 ACC1
+ 5420 GETFIELD3
+ 5421 PUSHACC1
+ 5422 PUSHOFFSETCLOSURE0
+ 5423 APPTERM2 4
+ 5425 RETURN 2
+ 5427 RESTART
+ 5428 GRAB 1
+ 5430 ACC1
+ 5431 BRANCHIFNOT 5455
+ 5433 ACC1
+ 5434 GETFIELD 4
+ 5436 PUSHACC2
+ 5437 GETFIELD3
+ 5438 PUSHACC2
+ 5439 PUSHOFFSETCLOSURE0
+ 5440 APPLY2
+ 5441 PUSHACC3
+ 5442 GETFIELD2
+ 5443 PUSHACC3
+ 5444 APPLY1
+ 5445 PUSHACC4
+ 5446 GETFIELD1
+ 5447 PUSHACC5
+ 5448 GETFIELD0
+ 5449 PUSHACC5
+ 5450 PUSHOFFSETCLOSURE0
+ 5451 APPLY2
+ 5452 MAKEBLOCK 5, 0
+ 5455 RETURN 2
+ 5457 RESTART
+ 5458 GRAB 2
+ 5460 ACC1
+ 5461 BRANCHIFNOT 5481
+ 5463 ACC2
+ 5464 PUSHACC2
+ 5465 GETFIELD3
+ 5466 PUSHACC2
+ 5467 PUSHOFFSETCLOSURE0
+ 5468 APPLY3
+ 5469 PUSHACC2
+ 5470 GETFIELD2
+ 5471 PUSHACC3
+ 5472 GETFIELD1
+ 5473 PUSHACC3
+ 5474 APPLY3
+ 5475 PUSHACC2
+ 5476 GETFIELD0
+ 5477 PUSHACC2
+ 5478 PUSHOFFSETCLOSURE0
+ 5479 APPTERM3 6
+ 5481 ACC2
+ 5482 RETURN 3
+ 5484 RESTART
+ 5485 GRAB 3
+ 5487 ACC0
+ 5488 BRANCHIFNOT 5495
+ 5490 ACC0
+ 5491 GETFIELD 4
+ 5493 BRANCH 5496
+ 5495 CONST0
+ 5496 PUSHACC4
+ 5497 BRANCHIFNOT 5504
+ 5499 ACC4
+ 5500 GETFIELD 4
+ 5502 BRANCH 5505
+ 5504 CONST0
+ 5505 PUSHACC0
+ 5506 OFFSETINT 2
+ 5508 PUSHACC2
+ 5509 GTINT
+ 5510 BRANCHIFNOT 5603
+ 5512 ACC2
+ 5513 BRANCHIFNOT 5596
+ 5515 ACC2
+ 5516 GETFIELD0
+ 5517 PUSHACC3
+ 5518 GETFIELD1
+ 5519 PUSHACC4
+ 5520 GETFIELD2
+ 5521 PUSHACC5
+ 5522 GETFIELD3
+ 5523 PUSHACC0
+ 5524 PUSHENVACC1
+ 5525 APPLY1
+ 5526 PUSHACC4
+ 5527 PUSHENVACC1
+ 5528 APPLY1
+ 5529 GEINT
+ 5530 BRANCHIFNOT 5551
+ 5532 PUSH_RETADDR 5544
+ 5534 ACC 12
+ 5536 PUSHACC 12
+ 5538 PUSHACC 12
+ 5540 PUSHACC6
+ 5541 PUSHENVACC2
+ 5542 APPLY 4
+ 5544 PUSHACC2
+ 5545 PUSHACC4
+ 5546 PUSHACC6
+ 5547 PUSHENVACC2
+ 5548 APPTERM 4, 14
+ 5551 ACC0
+ 5552 BRANCHIFNOT 5589
+ 5554 PUSH_RETADDR 5567
+ 5556 ACC 12
+ 5558 PUSHACC 12
+ 5560 PUSHACC 12
+ 5562 PUSHACC6
+ 5563 GETFIELD3
+ 5564 PUSHENVACC2
+ 5565 APPLY 4
+ 5567 PUSHACC1
+ 5568 GETFIELD2
+ 5569 PUSHACC2
+ 5570 GETFIELD1
+ 5571 PUSH
+ 5572 PUSH_RETADDR 5585
+ 5574 ACC6
+ 5575 GETFIELD0
+ 5576 PUSHACC 8
+ 5578 PUSHACC 10
+ 5580 PUSHACC 12
+ 5582 PUSHENVACC2
+ 5583 APPLY 4
+ 5585 PUSHENVACC2
+ 5586 APPTERM 4, 14
+ 5589 GETGLOBAL "Map.bal"
+ 5591 PUSHGETGLOBALFIELD Pervasives, 2
+ 5594 APPTERM1 11
+ 5596 GETGLOBAL "Map.bal"
+ 5598 PUSHGETGLOBALFIELD Pervasives, 2
+ 5601 APPTERM1 7
+ 5603 ACC1
+ 5604 OFFSETINT 2
+ 5606 PUSHACC1
+ 5607 GTINT
+ 5608 BRANCHIFNOT 5703
+ 5610 ACC5
+ 5611 BRANCHIFNOT 5696
+ 5613 ACC5
+ 5614 GETFIELD0
+ 5615 PUSHACC6
+ 5616 GETFIELD1
+ 5617 PUSHACC7
+ 5618 GETFIELD2
+ 5619 PUSHACC 8
+ 5621 GETFIELD3
+ 5622 PUSHACC3
+ 5623 PUSHENVACC1
+ 5624 APPLY1
+ 5625 PUSHACC1
+ 5626 PUSHENVACC1
+ 5627 APPLY1
+ 5628 GEINT
+ 5629 BRANCHIFNOT 5652
+ 5631 ACC0
+ 5632 PUSHACC2
+ 5633 PUSHACC4
+ 5634 PUSH
+ 5635 PUSH_RETADDR 5648
+ 5637 ACC 9
+ 5639 PUSHACC 15
+ 5641 PUSHACC 15
+ 5643 PUSHACC 15
+ 5645 PUSHENVACC2
+ 5646 APPLY 4
+ 5648 PUSHENVACC2
+ 5649 APPTERM 4, 14
+ 5652 ACC3
+ 5653 BRANCHIFNOT 5689
+ 5655 PUSH_RETADDR 5666
+ 5657 ACC3
+ 5658 PUSHACC5
+ 5659 PUSHACC7
+ 5660 PUSHACC 9
+ 5662 GETFIELD3
+ 5663 PUSHENVACC2
+ 5664 APPLY 4
+ 5666 PUSHACC4
+ 5667 GETFIELD2
+ 5668 PUSHACC5
+ 5669 GETFIELD1
+ 5670 PUSH
+ 5671 PUSH_RETADDR 5685
+ 5673 ACC 9
+ 5675 GETFIELD0
+ 5676 PUSHACC 15
+ 5678 PUSHACC 15
+ 5680 PUSHACC 15
+ 5682 PUSHENVACC2
+ 5683 APPLY 4
+ 5685 PUSHENVACC2
+ 5686 APPTERM 4, 14
+ 5689 GETGLOBAL "Map.bal"
+ 5691 PUSHGETGLOBALFIELD Pervasives, 2
+ 5694 APPTERM1 11
+ 5696 GETGLOBAL "Map.bal"
+ 5698 PUSHGETGLOBALFIELD Pervasives, 2
+ 5701 APPTERM1 7
+ 5703 ACC0
+ 5704 PUSHACC2
+ 5705 GEINT
+ 5706 BRANCHIFNOT 5713
+ 5708 ACC1
+ 5709 OFFSETINT 1
+ 5711 BRANCH 5716
+ 5713 ACC0
+ 5714 OFFSETINT 1
+ 5716 PUSHACC6
+ 5717 PUSHACC6
+ 5718 PUSHACC6
+ 5719 PUSHACC6
+ 5720 MAKEBLOCK 5, 0
+ 5723 RETURN 6
+ 5725 RESTART
+ 5726 GRAB 3
+ 5728 ACC0
+ 5729 PUSHENVACC1
+ 5730 APPLY1
+ 5731 PUSHACC4
+ 5732 PUSHENVACC1
+ 5733 APPLY1
+ 5734 PUSHACC0
+ 5735 PUSHACC2
+ 5736 GEINT
+ 5737 BRANCHIFNOT 5744
+ 5739 ACC1
+ 5740 OFFSETINT 1
+ 5742 BRANCH 5747
+ 5744 ACC0
+ 5745 OFFSETINT 1
+ 5747 PUSHACC6
+ 5748 PUSHACC6
+ 5749 PUSHACC6
+ 5750 PUSHACC6
+ 5751 MAKEBLOCK 5, 0
+ 5754 RETURN 6
+ 5756 ACC0
+ 5757 BRANCHIFNOT 5764
+ 5759 ACC0
+ 5760 GETFIELD 4
+ 5762 RETURN 1
+ 5764 CONST0
+ 5765 RETURN 1
+ 5767 CONST0
+ 5768 PUSH
+ 5769 CLOSURE 0, 5756
+ 5772 PUSHACC0
+ 5773 CLOSURE 1, 5726
+ 5776 PUSHACC0
+ 5777 PUSHACC2
+ 5778 CLOSURE 2, 5485
+ 5781 PUSHACC0
+ 5782 PUSHACC5
+ 5783 CLOSUREREC 2, 5132
+ 5787 ACC5
+ 5788 CLOSUREREC 1, 5212
+ 5792 ACC6
+ 5793 CLOSUREREC 1, 5253
+ 5797 ACC3
+ 5798 CLOSUREREC 1, 5289
+ 5802 ACC0
+ 5803 PUSHACC5
+ 5804 PUSHACC 10
+ 5806 CLOSUREREC 3, 5344
+ 5810 CLOSUREREC 0, 5403
+ 5814 CLOSUREREC 0, 5428
+ 5818 CLOSUREREC 0, 5458
+ 5822 ACC0
+ 5823 PUSHACC2
+ 5824 PUSHACC4
+ 5825 PUSHACC6
+ 5826 PUSHACC 8
+ 5828 PUSHACC 10
+ 5830 PUSHACC 12
+ 5832 PUSHACC 14
+ 5834 PUSHACC 16
+ 5836 PUSHACC 18
+ 5838 PUSHACC 20
+ 5840 PUSHACC 22
+ 5842 MAKEBLOCK 12, 0
+ 5845 RETURN 13
+ 5847 CLOSURE 0, 5767
+ 5850 PUSHACC0
+ 5851 CLOSURE 1, 5100
+ 5854 MAKEBLOCK1 0
+ 5856 POP 1
+ 5858 SETGLOBAL Map
+ 5860 BRANCH 5957
+ 5862 CONSTINT 16
+ 5864 C_CALL1 create_string
+ 5866 PUSH
+ 5867 PUSH_RETADDR 5879
+ 5869 CONSTINT 16
+ 5871 PUSHCONST0
+ 5872 PUSHACC5
+ 5873 PUSHACC7
+ 5874 PUSHGETGLOBALFIELD Pervasives, 56
+ 5877 APPLY 4
+ 5879 ACC0
+ 5880 RETURN 2
+ 5882 RESTART
+ 5883 GRAB 1
+ 5885 CONSTINT 16
+ 5887 PUSHCONST0
+ 5888 PUSHACC3
+ 5889 PUSHACC3
+ 5890 PUSHGETGLOBALFIELD Pervasives, 41
+ 5893 APPTERM 4, 6
+ 5896 ACC0
+ 5897 PUSHGETGLOBALFIELD Pervasives, 51
+ 5900 APPLY1
+ 5901 PUSHACC0
+ 5902 PUSHGETGLOBALFIELD Pervasives, 62
+ 5905 APPLY1
+ 5906 PUSHACC1
+ 5907 C_CALL2 md5_chan
+ 5909 PUSHACC1
+ 5910 PUSHGETGLOBALFIELD Pervasives, 63
+ 5913 APPLY1
+ 5914 ACC0
+ 5915 RETURN 3
+ 5917 RESTART
+ 5918 GRAB 2
+ 5920 CONST0
+ 5921 PUSHACC2
+ 5922 LTINT
+ 5923 BRANCHIF 5934
+ 5925 ACC0
+ 5926 C_CALL1 ml_string_length
+ 5928 PUSHACC3
+ 5929 PUSHACC3
+ 5930 ADDINT
+ 5931 GTINT
+ 5932 BRANCHIFNOT 5941
+ 5934 GETGLOBAL "Digest.substring"
+ 5936 PUSHGETGLOBALFIELD Pervasives, 2
+ 5939 APPTERM1 4
+ 5941 ACC2
+ 5942 PUSHACC2
+ 5943 PUSHACC2
+ 5944 C_CALL3 md5_string
+ 5946 RETURN 3
+ 5948 ACC0
+ 5949 C_CALL1 ml_string_length
+ 5951 PUSHCONST0
+ 5952 PUSHACC2
+ 5953 C_CALL3 md5_string
+ 5955 RETURN 1
+ 5957 CLOSURE 0, 5948
+ 5960 PUSH
+ 5961 CLOSURE 0, 5918
+ 5964 PUSH
+ 5965 CLOSURE 0, 5896
+ 5968 PUSH
+ 5969 CLOSURE 0, 5883
+ 5972 PUSH
+ 5973 CLOSURE 0, 5862
+ 5976 PUSHACC0
+ 5977 PUSHACC2
+ 5978 PUSHACC4
+ 5979 PUSHACC6
+ 5980 PUSHACC 8
+ 5982 MAKEBLOCK 5, 0
+ 5985 POP 5
+ 5987 SETGLOBAL Digest
+ 5989 BRANCH 6245
+ 5991 CONST0
+ 5992 PUSHENVACC1
+ 5993 APPLY1
+ 5994 PUSHACC1
+ 5995 PUSHACC1
+ 5996 GEINT
+ 5997 BRANCHIFNOT 6003
+ 5999 ACC1
+ 6000 PUSHOFFSETCLOSURE0
+ 6001 APPTERM1 3
+ 6003 ACC0
+ 6004 RETURN 2
+ 6006 CONST0
+ 6007 C_CALL1 sys_random_seed
+ 6009 PUSHENVACC1
+ 6010 APPTERM1 2
+ 6012 CONSTINT 27182818
+ 6014 PUSHENVACC2
+ 6015 APPLY1
+ 6016 CONST0
+ 6017 PUSHACC1
+ 6018 VECTLENGTH
+ 6019 OFFSETINT -1
+ 6021 PUSH
+ 6022 BRANCH 6046
+ 6024 CHECK_SIGNALS
+ 6025 CONSTINT 55
+ 6027 PUSHACC2
+ 6028 MODINT
+ 6029 PUSHACC2
+ 6030 PUSHACC4
+ 6031 GETVECTITEM
+ 6032 PUSHACC1
+ 6033 PUSHENVACC1
+ 6034 GETVECTITEM
+ 6035 ADDINT
+ 6036 PUSHACC1
+ 6037 PUSHENVACC1
+ 6038 SETVECTITEM
+ 6039 POP 1
+ 6041 ACC1
+ 6042 OFFSETINT 1
+ 6044 ASSIGN 1
+ 6046 ACC0
+ 6047 PUSHACC2
+ 6048 LEINT
+ 6049 BRANCHIF 6024
+ 6051 CONST0
+ 6052 RETURN 3
+ 6054 ENVACC1
+ 6055 GETFIELD0
+ 6056 OFFSETINT 1
+ 6058 PUSHENVACC1
+ 6059 SETFIELD0
+ 6060 ENVACC1
+ 6061 GETFIELD0
+ 6062 PUSHGETGLOBALFIELD Pervasives, 14
+ 6065 APPLY1
+ 6066 PUSHGETGLOBALFIELD Digest, 0
+ 6069 APPLY1
+ 6070 PUSHCONSTINT 22
+ 6072 PUSHCONST3
+ 6073 PUSHACC2
+ 6074 C_CALL2 string_get
+ 6076 LSLINT
+ 6077 PUSHCONSTINT 16
+ 6079 PUSHCONST2
+ 6080 PUSHACC3
+ 6081 C_CALL2 string_get
+ 6083 LSLINT
+ 6084 PUSHCONSTINT 8
+ 6086 PUSHCONST1
+ 6087 PUSHACC4
+ 6088 C_CALL2 string_get
+ 6090 LSLINT
+ 6091 PUSHCONST0
+ 6092 PUSHACC4
+ 6093 C_CALL2 string_get
+ 6095 ADDINT
+ 6096 ADDINT
+ 6097 XORINT
+ 6098 RETURN 2
+ 6100 ACC0
+ 6101 MAKEBLOCK1 0
+ 6103 PUSHACC0
+ 6104 CLOSURE 1, 6054
+ 6107 PUSHCONST0
+ 6108 PUSHCONSTINT 54
+ 6110 PUSH
+ 6111 BRANCH 6125
+ 6113 CHECK_SIGNALS
+ 6114 CONST0
+ 6115 PUSHACC3
+ 6116 APPLY1
+ 6117 PUSHACC2
+ 6118 PUSHENVACC1
+ 6119 SETVECTITEM
+ 6120 ACC1
+ 6121 OFFSETINT 1
+ 6123 ASSIGN 1
+ 6125 ACC0
+ 6126 PUSHACC2
+ 6127 LEINT
+ 6128 BRANCHIF 6113
+ 6130 CONST0
+ 6131 POP 2
+ 6133 CONST0
+ 6134 PUSHENVACC2
+ 6135 SETFIELD0
+ 6136 RETURN 3
+ 6138 ACC0
+ 6139 PUSHCONST0
+ 6140 PUSHENVACC1
+ 6141 APPLY1
+ 6142 C_CALL2 mul_float
+ 6144 RETURN 1
+ 6146 CONSTINT 1073741823
+ 6148 PUSHACC1
+ 6149 GTINT
+ 6150 BRANCHIF 6157
+ 6152 CONST0
+ 6153 PUSHACC1
+ 6154 LEINT
+ 6155 BRANCHIFNOT 6164
+ 6157 GETGLOBAL "Random.int"
+ 6159 PUSHGETGLOBALFIELD Pervasives, 2
+ 6162 APPTERM1 2
+ 6164 ACC0
+ 6165 PUSHACC1
+ 6166 PUSHACC2
+ 6167 PUSHCONSTINT 1073741823
+ 6169 DIVINT
+ 6170 MULINT
+ 6171 PUSHENVACC1
+ 6172 APPLY1
+ 6173 MODINT
+ 6174 RETURN 1
+ 6176 GETGLOBAL 1073741824
+ 6178 PUSHCONST0
+ 6179 PUSHENVACC1
+ 6180 APPLY1
+ 6181 C_CALL1 float_of_int
+ 6183 PUSHCONST0
+ 6184 PUSHENVACC1
+ 6185 APPLY1
+ 6186 C_CALL1 float_of_int
+ 6188 PUSHCONST0
+ 6189 PUSHENVACC1
+ 6190 APPLY1
+ 6191 C_CALL1 float_of_int
+ 6193 PUSHACC3
+ 6194 PUSHACC1
+ 6195 PUSHACC5
+ 6196 PUSHACC4
+ 6197 PUSHACC7
+ 6198 PUSHACC7
+ 6199 C_CALL2 div_float
+ 6201 C_CALL2 add_float
+ 6203 C_CALL2 div_float
+ 6205 C_CALL2 add_float
+ 6207 C_CALL2 div_float
+ 6209 RETURN 5
+ 6211 CONSTINT 55
+ 6213 PUSHENVACC2
+ 6214 GETFIELD0
+ 6215 OFFSETINT 1
+ 6217 MODINT
+ 6218 PUSHENVACC2
+ 6219 SETFIELD0
+ 6220 ENVACC2
+ 6221 GETFIELD0
+ 6222 PUSHENVACC1
+ 6223 GETVECTITEM
+ 6224 PUSHCONSTINT 55
+ 6226 PUSHENVACC2
+ 6227 GETFIELD0
+ 6228 OFFSETINT 24
+ 6230 MODINT
+ 6231 PUSHENVACC1
+ 6232 GETVECTITEM
+ 6233 ADDINT
+ 6234 PUSHACC0
+ 6235 PUSHENVACC2
+ 6236 GETFIELD0
+ 6237 PUSHENVACC1
+ 6238 SETVECTITEM
+ 6239 CONSTINT 1073741823
+ 6241 PUSHACC1
+ 6242 ANDINT
+ 6243 RETURN 2
+ 6245 CONSTINT 440266690
+ 6247 PUSHCONSTINT 124177607
+ 6249 PUSHCONSTINT 414576093
+ 6251 PUSHCONSTINT 180326017
+ 6253 PUSHCONSTINT 33747835
+ 6255 PUSHCONSTINT 896816596
+ 6257 PUSHCONSTINT 21528564
+ 6259 PUSHCONSTINT 414383108
+ 6261 PUSHCONSTINT 514922558
+ 6263 PUSHCONSTINT 979459837
+ 6265 PUSHCONSTINT 146577263
+ 6267 PUSHCONSTINT 714526560
+ 6269 PUSHCONSTINT 187230644
+ 6271 PUSHCONSTINT 22990936
+ 6273 PUSHCONSTINT 310632349
+ 6275 PUSHCONSTINT 781847598
+ 6277 PUSHCONSTINT 854580894
+ 6279 PUSHCONSTINT 804670393
+ 6281 PUSHCONSTINT 268309077
+ 6283 PUSHCONSTINT 4136554
+ 6285 PUSHCONSTINT 567327260
+ 6287 PUSHCONSTINT 768795410
+ 6289 PUSHCONSTINT 868098973
+ 6291 PUSHCONSTINT 462134267
+ 6293 PUSHCONSTINT 32881167
+ 6295 PUSHCONSTINT 708896334
+ 6297 PUSHCONSTINT 572927557
+ 6299 PUSHCONSTINT 933858406
+ 6301 PUSHCONSTINT 965168955
+ 6303 PUSHCONSTINT 233350272
+ 6305 PUSHCONSTINT 878960411
+ 6307 PUSHCONSTINT 971004788
+ 6309 PUSHCONSTINT 762624501
+ 6311 PUSHCONSTINT 796925167
+ 6313 PUSHCONSTINT 206134737
+ 6315 PUSHCONSTINT 281896889
+ 6317 PUSHCONSTINT 814302728
+ 6319 PUSHCONSTINT 477485839
+ 6321 PUSHCONSTINT 998499212
+ 6323 PUSHCONSTINT 473370118
+ 6325 PUSHCONSTINT 66770770
+ 6327 PUSHCONSTINT 337696531
+ 6329 PUSHCONSTINT 848741663
+ 6331 PUSHCONSTINT 71648846
+ 6333 PUSHCONSTINT 869261341
+ 6335 PUSHCONSTINT 951240904
+ 6337 PUSHCONSTINT 147054819
+ 6339 PUSHCONSTINT 486882977
+ 6341 PUSHCONSTINT 552627506
+ 6343 PUSHCONSTINT 615350359
+ 6345 PUSHCONSTINT 1023641486
+ 6347 PUSHCONSTINT 9858203
+ 6349 PUSHCONSTINT 764306064
+ 6351 PUSHCONSTINT 1051173471
+ 6353 PUSHCONSTINT 561073064
+ 6355 MAKEBLOCK 55, 0
+ 6358 PUSHCONST0
+ 6359 MAKEBLOCK1 0
+ 6361 PUSHACC0
+ 6362 PUSHACC2
+ 6363 CLOSURE 2, 6211
+ 6366 PUSHACC0
+ 6367 CLOSURE 1, 6176
+ 6370 PUSHACC1
+ 6371 CLOSUREREC 1, 5991
+ 6375 ACC0
+ 6376 CLOSURE 1, 6146
+ 6379 PUSHACC2
+ 6380 CLOSURE 1, 6138
+ 6383 PUSHACC5
+ 6384 PUSHACC7
+ 6385 CLOSURE 2, 6100
+ 6388 PUSHACC0
+ 6389 PUSHACC 8
+ 6391 CLOSURE 2, 6012
+ 6394 PUSHACC1
+ 6395 CLOSURE 1, 6006
+ 6398 PUSHACC3
+ 6399 PUSHACC5
+ 6400 PUSHACC 9
+ 6402 PUSHACC3
+ 6403 PUSHACC5
+ 6404 PUSHACC7
+ 6405 MAKEBLOCK 6, 0
+ 6408 POP 10
+ 6410 SETGLOBAL Random
+ 6412 BRANCH 8038
+ 6414 RESTART
+ 6415 GRAB 1
+ 6417 ACC1
+ 6418 BRANCHIFNOT 6441
+ 6420 ACC1
+ 6421 GETFIELD0
+ 6422 PUSHACC2
+ 6423 GETFIELD1
+ 6424 PUSHACC1
+ 6425 PUSHACC3
+ 6426 EQ
+ 6427 BRANCHIFNOT 6432
+ 6429 ACC0
+ 6430 RETURN 4
+ 6432 ACC0
+ 6433 PUSHACC3
+ 6434 PUSHOFFSETCLOSURE0
+ 6435 APPLY2
+ 6436 PUSHACC2
+ 6437 MAKEBLOCK2 0
+ 6439 POP 2
+ 6441 RETURN 2
+ 6443 RESTART
+ 6444 GRAB 1
+ 6446 CONST0
+ 6447 PUSHACC2
+ 6448 GTINT
+ 6449 BRANCHIFNOT 6512
+ 6451 CONST0
+ 6452 PUSHENVACC2
+ 6453 GETFIELD0
+ 6454 GTINT
+ 6455 BRANCHIFNOT 6512
+ 6457 ENVACC2
+ 6458 GETFIELD0
+ 6459 PUSHGETGLOBALFIELD Random, 4
+ 6462 APPLY1
+ 6463 PUSHACC0
+ 6464 PUSHENVACC1
+ 6465 GETFIELD0
+ 6466 C_CALL2 array_get_addr
+ 6468 PUSHENVACC 5
+ 6470 APPLY1
+ 6471 BRANCHIF 6482
+ 6473 ACC0
+ 6474 PUSHENVACC 4
+ 6476 APPLY1
+ 6477 ACC2
+ 6478 PUSHACC2
+ 6479 PUSHOFFSETCLOSURE0
+ 6480 APPTERM2 5
+ 6482 PUSHTRAP 6496
+ 6484 ACC5
+ 6485 PUSHACC5
+ 6486 PUSHENVACC1
+ 6487 GETFIELD0
+ 6488 C_CALL2 array_get_addr
+ 6490 PUSHENVACC 7
+ 6492 APPLY2
+ 6493 POPTRAP
+ 6494 RETURN 3
+ 6496 PUSHENVACC 6
+ 6498 PUSHACC1
+ 6499 GETFIELD0
+ 6500 EQ
+ 6501 BRANCHIFNOT 6510
+ 6503 ACC3
+ 6504 OFFSETINT -1
+ 6506 PUSHACC3
+ 6507 PUSHOFFSETCLOSURE0
+ 6508 APPTERM2 6
+ 6510 ACC0
+ 6511 RAISE
+ 6512 ACC0
+ 6513 PUSHENVACC3
+ 6514 APPLY1
+ 6515 ACC0
+ 6516 RETURN 2
+ 6518 RESTART
+ 6519 GRAB 1
+ 6521 ACC1
+ 6522 BRANCHIFNOT 6534
+ 6524 ACC0
+ 6525 PUSHACC2
+ 6526 GETFIELD0
+ 6527 APPLY1
+ 6528 ACC1
+ 6529 GETFIELD1
+ 6530 PUSHACC1
+ 6531 PUSHOFFSETCLOSURE0
+ 6532 APPTERM2 4
+ 6534 RETURN 2
+ 6536 CONST0
+ 6537 PUSHENVACC1
+ 6538 OFFSETINT -1
+ 6540 PUSH
+ 6541 BRANCH 6567
+ 6543 CHECK_SIGNALS
+ 6544 ENVACC2
+ 6545 PUSHACC2
+ 6546 PUSHACC4
+ 6547 C_CALL2 array_get
+ 6549 EQ
+ 6550 BRANCHIFNOT 6556
+ 6552 CONSTINT 46
+ 6554 BRANCH 6558
+ 6556 CONSTINT 42
+ 6558 PUSHGETGLOBALFIELD Pervasives, 20
+ 6561 APPLY1
+ 6562 ACC1
+ 6563 OFFSETINT 1
+ 6565 ASSIGN 1
+ 6567 ACC0
+ 6568 PUSHACC2
+ 6569 LEINT
+ 6570 BRANCHIF 6543
+ 6572 CONST0
+ 6573 POP 2
+ 6575 CONST0
+ 6576 PUSHGETGLOBALFIELD Pervasives, 25
+ 6579 APPTERM1 2
+ 6581 ENVACC3
+ 6582 GETFIELD0
+ 6583 PUSHENVACC 4
+ 6585 APPLY1
+ 6586 PUSHENVACC2
+ 6587 PUSHENVACC1
+ 6588 CLOSURE 2, 6536
+ 6591 PUSHGETGLOBALFIELD List, 9
+ 6594 APPTERM2 3
+ 6596 ACC0
+ 6597 GETFIELD1
+ 6598 RETURN 1
+ 6600 RESTART
+ 6601 GRAB 1
+ 6603 ACC1
+ 6604 GETFIELD0
+ 6605 PUSHACC1
+ 6606 GETFIELD0
+ 6607 LEINT
+ 6608 RETURN 2
+ 6610 ACC0
+ 6611 PUSHACC1
+ 6612 PUSHENVACC1
+ 6613 APPLY1
+ 6614 MAKEBLOCK2 0
+ 6616 RETURN 1
+ 6618 ACC0
+ 6619 PUSHENVACC1
+ 6620 CLOSURE 1, 6610
+ 6623 PUSHGETGLOBALFIELD List, 10
+ 6626 APPLY2
+ 6627 PUSH
+ 6628 CLOSURE 0, 6601
+ 6631 PUSHGETGLOBALFIELD Sort, 0
+ 6634 APPLY2
+ 6635 PUSH
+ 6636 CLOSURE 0, 6596
+ 6639 PUSHGETGLOBALFIELD List, 10
+ 6642 APPTERM2 3
+ 6644 ENVACC3
+ 6645 GETFIELD0
+ 6646 VECTLENGTH
+ 6647 PUSHENVACC 4
+ 6649 GETFIELD0
+ 6650 PUSHCONST0
+ 6651 PUSHENVACC 8
+ 6653 APPLY1
+ 6654 PUSHENVACC2
+ 6655 GETFIELD0
+ 6656 PUSHGETGLOBALFIELD List, 0
+ 6659 APPLY1
+ 6660 PUSHENVACC 7
+ 6662 GETFIELD0
+ 6663 PUSHENVACC 6
+ 6665 GETFIELD0
+ 6666 PUSHENVACC1
+ 6667 GETFIELD0
+ 6668 PUSHENVACC 5
+ 6670 GETFIELD0
+ 6671 MAKEBLOCK 8, 0
+ 6674 RETURN 1
+ 6676 ACC0
+ 6677 PUSHENVACC1
+ 6678 APPLY1
+ 6679 PUSHACC0
+ 6680 OFFSETINT -1
+ 6682 PUSHENVACC2
+ 6683 C_CALL2 array_get_addr
+ 6685 OFFSETINT 1
+ 6687 PUSHACC1
+ 6688 OFFSETINT -1
+ 6690 PUSHENVACC2
+ 6691 C_CALL3 array_set_addr
+ 6693 RETURN 2
+ 6695 CONST0
+ 6696 PUSHCONSTINT 32
+ 6698 C_CALL2 make_vect
+ 6700 PUSHENVACC1
+ 6701 GETFIELD0
+ 6702 PUSHACC1
+ 6703 PUSHENVACC2
+ 6704 CLOSURE 2, 6676
+ 6707 PUSHGETGLOBALFIELD List, 9
+ 6710 APPLY2
+ 6711 ACC0
+ 6712 RETURN 2
+ 6714 RESTART
+ 6715 GRAB 1
+ 6717 ACC1
+ 6718 PUSHENVACC1
+ 6719 APPLY1
+ 6720 PUSHACC1
+ 6721 PUSHACC1
+ 6722 GETFIELD1
+ 6723 PUSHACC2
+ 6724 GETFIELD0
+ 6725 PUSHCONST0
+ 6726 PUSHACC5
+ 6727 C_CALL2 array_get_addr
+ 6729 C_CALL2 array_get_addr
+ 6731 C_CALL2 array_get_addr
+ 6733 APPTERM1 4
+ 6735 ACC0
+ 6736 GETFIELD0
+ 6737 C_CALL1 obj_dup
+ 6739 PUSHENVACC1
+ 6740 PUSHACC1
+ 6741 PUSHENVACC2
+ 6742 APPLY2
+ 6743 ACC1
+ 6744 GETFIELD2
+ 6745 PUSHACC1
+ 6746 PUSHENVACC3
+ 6747 APPLY2
+ 6748 ACC0
+ 6749 RETURN 2
+ 6751 RESTART
+ 6752 GRAB 1
+ 6754 ACC1
+ 6755 GETFIELD 7
+ 6757 PUSHCONST0
+ 6758 PUSHACC1
+ 6759 NEQ
+ 6760 BRANCHIFNOT 6767
+ 6762 ACC0
+ 6763 PUSHACC2
+ 6764 PUSHENVACC1
+ 6765 APPTERM2 5
+ 6767 RETURN 3
+ 6769 ACC0
+ 6770 GETFIELD0
+ 6771 PUSHENVACC1
+ 6772 C_CALL2 obj_block
+ 6774 PUSHACC1
+ 6775 GETFIELD1
+ 6776 PUSHCONST0
+ 6777 PUSHACC2
+ 6778 C_CALL3 array_unsafe_set
+ 6780 ENVACC2
+ 6781 PUSHACC1
+ 6782 PUSHENVACC3
+ 6783 APPLY2
+ 6784 ACC0
+ 6785 RETURN 2
+ 6787 ACC0
+ 6788 GETFIELD0
+ 6789 PUSHENVACC3
+ 6790 GETFIELD0
+ 6791 ADDINT
+ 6792 OFFSETINT -1
+ 6794 PUSHENVACC3
+ 6795 SETFIELD0
+ 6796 ENVACC1
+ 6797 GETFIELD0
+ 6798 BRANCHIFNOT 6804
+ 6800 ACC0
+ 6801 GETFIELD1
+ 6802 PUSHENVACC2
+ 6803 APPLY1
+ 6804 ACC0
+ 6805 GETFIELD 7
+ 6807 PUSHGETGLOBALFIELD List, 4
+ 6810 APPLY1
+ 6811 PUSHACC1
+ 6812 SETFIELD 7
+ 6814 RETURN 1
+ 6816 ACC0
+ 6817 PUSHENVACC1
+ 6818 APPLY1
+ 6819 PUSHENVACC 4
+ 6821 GETFIELD2
+ 6822 PUSHACC1
+ 6823 PUSHACC3
+ 6824 PUSHENVACC2
+ 6825 GETFIELD1
+ 6826 APPLY3
+ 6827 PUSHENVACC 4
+ 6829 SETFIELD2
+ 6830 ENVACC4
+ 6831 GETFIELD3
+ 6832 PUSHCONST1
+ 6833 PUSHACC2
+ 6834 PUSHENVACC3
+ 6835 GETFIELD1
+ 6836 APPLY3
+ 6837 PUSHENVACC 4
+ 6839 SETFIELD3
+ 6840 RETURN 2
+ 6842 CONST0
+ 6843 PUSHENVACC 4
+ 6845 APPLY1
+ 6846 PUSHACC1
+ 6847 PUSHACC1
+ 6848 PUSHENVACC3
+ 6849 PUSHENVACC2
+ 6850 PUSHENVACC1
+ 6851 CLOSURE 4, 6816
+ 6854 PUSHGETGLOBALFIELD List, 9
+ 6857 APPLY2
+ 6858 ACC0
+ 6859 RETURN 2
+ 6861 RESTART
+ 6862 GRAB 1
+ 6864 ACC0
+ 6865 GETFIELD 7
+ 6867 PUSHACC2
+ 6868 MAKEBLOCK2 0
+ 6870 PUSHACC1
+ 6871 SETFIELD 7
+ 6873 RETURN 2
+ 6875 ENVACC1
+ 6876 PUSHENVACC3
+ 6877 PUSH
+ 6878 BRANCH 6895
+ 6880 CHECK_SIGNALS
+ 6881 ACC1
+ 6882 PUSHENVACC2
+ 6883 GETVECTITEM
+ 6884 PUSHENVACC 4
+ 6886 PUSHACC3
+ 6887 ADDINT
+ 6888 PUSHACC4
+ 6889 SETVECTITEM
+ 6890 ACC1
+ 6891 OFFSETINT 1
+ 6893 ASSIGN 1
+ 6895 ACC0
+ 6896 PUSHACC2
+ 6897 LEINT
+ 6898 BRANCHIF 6880
+ 6900 CONST0
+ 6901 RETURN 3
+ 6903 ENVACC2
+ 6904 GETFIELD0
+ 6905 PUSHENVACC2
+ 6906 GETFIELD2
+ 6907 GETFIELD0
+ 6908 OFFSETINT -1
+ 6910 PUSHENVACC3
+ 6911 GETFIELD0
+ 6912 OFFSETINT -1
+ 6914 PUSHACC1
+ 6915 PUSHACC1
+ 6916 SUBINT
+ 6917 PUSHACC0
+ 6918 PUSHACC3
+ 6919 PUSHACC5
+ 6920 PUSHENVACC1
+ 6921 CLOSURE 4, 6875
+ 6924 RETURN 5
+ 6926 RESTART
+ 6927 GRAB 1
+ 6929 CONST0
+ 6930 ACC1
+ 6931 PUSHACC1
+ 6932 PUSHENVACC1
+ 6933 CLOSURE 3, 6903
+ 6936 RETURN 2
+ 6938 RESTART
+ 6939 GRAB 1
+ 6941 ACC0
+ 6942 GETFIELD 6
+ 6944 PUSHACC2
+ 6945 PUSHENVACC1
+ 6946 GETFIELD2
+ 6947 APPTERM2 4
+ 6949 RESTART
+ 6950 GRAB 1
+ 6952 ACC0
+ 6953 PUSHENVACC2
+ 6954 APPLY1
+ 6955 PUSHACC1
+ 6956 GETFIELD 6
+ 6958 PUSHACC1
+ 6959 PUSHACC4
+ 6960 PUSHENVACC1
+ 6961 GETFIELD1
+ 6962 APPLY3
+ 6963 PUSHACC2
+ 6964 SETFIELD 6
+ 6966 ACC0
+ 6967 RETURN 3
+ 6969 ACC0
+ 6970 GETFIELD0
+ 6971 PUSHACC0
+ 6972 OFFSETINT 1
+ 6974 PUSHACC2
+ 6975 SETFIELD0
+ 6976 ACC0
+ 6977 RETURN 2
+ 6979 RESTART
+ 6980 GRAB 1
+ 6982 CONST0
+ 6983 PUSHACC1
+ 6984 PUSHACC3
+ 6985 GETFIELD1
+ 6986 APPTERM2 4
+ 6988 RESTART
+ 6989 GRAB 1
+ 6991 ENVACC1
+ 6992 GETFIELD 4
+ 6994 PUSHACC1
+ 6995 GETFIELD0
+ 6996 PUSHGETGLOBALFIELD List, 23
+ 6999 APPLY2
+ 7000 BRANCHIFNOT 7005
+ 7002 ACC1
+ 7003 RETURN 2
+ 7005 ACC1
+ 7006 PUSHACC1
+ 7007 MAKEBLOCK2 0
+ 7009 RETURN 2
+ 7011 RESTART
+ 7012 GRAB 1
+ 7014 ACC0
+ 7015 PUSHENVACC2
+ 7016 GETFIELD 6
+ 7018 PUSHACC3
+ 7019 PUSHENVACC1
+ 7020 GETFIELD2
+ 7021 APPLY2
+ 7022 PUSHACC3
+ 7023 PUSHENVACC1
+ 7024 GETFIELD1
+ 7025 APPTERM3 5
+ 7027 ACC0
+ 7028 GETFIELD 4
+ 7030 PUSHGETGLOBALFIELD List, 1
+ 7033 APPLY1
+ 7034 PUSHACC1
+ 7035 GETFIELD 4
+ 7037 PUSHGETGLOBALFIELD List, 2
+ 7040 APPLY1
+ 7041 PUSHACC2
+ 7042 SETFIELD 4
+ 7044 ACC0
+ 7045 GETFIELD 5
+ 7047 PUSHACC1
+ 7048 GETFIELD3
+ 7049 PUSHACC3
+ 7050 PUSHENVACC1
+ 7051 CLOSURE 2, 7012
+ 7054 PUSHGETGLOBALFIELD List, 12
+ 7057 APPLY3
+ 7058 PUSHACC2
+ 7059 SETFIELD 6
+ 7061 ACC0
+ 7062 GETFIELD0
+ 7063 PUSHACC2
+ 7064 SETFIELD2
+ 7065 ACC0
+ 7066 GETFIELD1
+ 7067 PUSHACC2
+ 7068 SETFIELD3
+ 7069 ACC0
+ 7070 GETFIELD2
+ 7071 PUSHACC2
+ 7072 GETFIELD 5
+ 7074 PUSHACC2
+ 7075 CLOSURE 1, 6989
+ 7078 PUSHGETGLOBALFIELD List, 13
+ 7081 APPLY3
+ 7082 PUSHACC2
+ 7083 SETFIELD 5
+ 7085 RETURN 2
+ 7087 RESTART
+ 7088 GRAB 1
+ 7090 ENVACC1
+ 7091 PUSHACC1
+ 7092 GETFIELD0
+ 7093 PUSHGETGLOBALFIELD List, 23
+ 7096 APPLY2
+ 7097 BRANCHIFNOT 7102
+ 7099 ACC1
+ 7100 RETURN 2
+ 7102 ACC1
+ 7103 PUSHACC1
+ 7104 MAKEBLOCK2 0
+ 7106 RETURN 2
+ 7108 RESTART
+ 7109 GRAB 1
+ 7111 ENVACC3
+ 7112 GETFIELD0
+ 7113 PUSHACC2
+ 7114 PUSHACC2
+ 7115 PUSHENVACC1
+ 7116 GETFIELD1
+ 7117 APPLY3
+ 7118 PUSHENVACC3
+ 7119 SETFIELD0
+ 7120 ENVACC4
+ 7121 GETFIELD0
+ 7122 PUSHCONST0
+ 7123 PUSHACC3
+ 7124 PUSHENVACC2
+ 7125 GETFIELD1
+ 7126 APPLY3
+ 7127 PUSHENVACC 4
+ 7129 SETFIELD0
+ 7130 RETURN 2
+ 7132 ACC0
+ 7133 PUSHENVACC 4
+ 7135 PUSHENVACC3
+ 7136 APPLY2
+ 7137 PUSHENVACC 5
+ 7139 GETFIELD0
+ 7140 PUSHACC1
+ 7141 PUSHACC3
+ 7142 PUSHENVACC1
+ 7143 GETFIELD1
+ 7144 APPLY3
+ 7145 PUSHENVACC 5
+ 7147 SETFIELD0
+ 7148 ENVACC 6
+ 7150 GETFIELD0
+ 7151 PUSH
+ 7152 PUSHTRAP 7163
+ 7154 ENVACC4
+ 7155 GETFIELD3
+ 7156 PUSHACC6
+ 7157 PUSHENVACC2
+ 7158 GETFIELD2
+ 7159 APPLY2
+ 7160 POPTRAP
+ 7161 BRANCH 7177
+ 7163 PUSHGETGLOBAL Not_found
+ 7165 PUSHACC1
+ 7166 GETFIELD0
+ 7167 EQ
+ 7168 BRANCHIFNOT 7173
+ 7170 CONST1
+ 7171 BRANCH 7175
+ 7173 ACC0
+ 7174 RAISE
+ 7175 POP 1
+ 7177 PUSHACC2
+ 7178 PUSHENVACC2
+ 7179 GETFIELD1
+ 7180 APPLY3
+ 7181 PUSHENVACC 6
+ 7183 SETFIELD0
+ 7184 RETURN 2
+ 7186 RESTART
+ 7187 GRAB 3
+ 7189 ACC2
+ 7190 PUSHACC1
+ 7191 PUSHENVACC 4
+ 7193 APPLY1
+ 7194 PUSHGETGLOBALFIELD List, 10
+ 7197 APPLY2
+ 7198 PUSHACC1
+ 7199 GETFIELD 4
+ 7201 PUSHACC3
+ 7202 PUSHACC2
+ 7203 PUSHACC4
+ 7204 GETFIELD 6
+ 7206 PUSHACC5
+ 7207 GETFIELD 5
+ 7209 PUSHACC6
+ 7210 GETFIELD3
+ 7211 PUSHACC7
+ 7212 GETFIELD2
+ 7213 MAKEBLOCK 6, 0
+ 7216 MAKEBLOCK2 0
+ 7218 PUSHACC2
+ 7219 SETFIELD 4
+ 7221 ENVACC1
+ 7222 GETFIELD0
+ 7223 PUSHACC2
+ 7224 SETFIELD 6
+ 7226 ENVACC2
+ 7227 GETFIELD0
+ 7228 MAKEBLOCK1 0
+ 7230 PUSHENVACC3
+ 7231 GETFIELD0
+ 7232 MAKEBLOCK1 0
+ 7234 PUSHACC6
+ 7235 PUSHACC1
+ 7236 PUSHACC3
+ 7237 PUSHACC6
+ 7238 PUSHENVACC 4
+ 7240 PUSHENVACC3
+ 7241 PUSHENVACC2
+ 7242 CLOSURE 6, 7132
+ 7245 PUSHGETGLOBALFIELD List, 9
+ 7248 APPLY2
+ 7249 ACC2
+ 7250 PUSHACC6
+ 7251 PUSHACC2
+ 7252 PUSHACC4
+ 7253 PUSHENVACC3
+ 7254 PUSHENVACC2
+ 7255 CLOSURE 4, 7109
+ 7258 PUSHGETGLOBALFIELD List, 14
+ 7261 APPLY3
+ 7262 ACC1
+ 7263 GETFIELD0
+ 7264 PUSHACC4
+ 7265 SETFIELD2
+ 7266 ACC0
+ 7267 GETFIELD0
+ 7268 PUSHACC4
+ 7269 SETFIELD3
+ 7270 CONST0
+ 7271 PUSHACC4
+ 7272 GETFIELD 5
+ 7274 PUSHACC4
+ 7275 CLOSURE 1, 7088
+ 7278 PUSHGETGLOBALFIELD List, 13
+ 7281 APPLY3
+ 7282 PUSHACC4
+ 7283 SETFIELD 5
+ 7285 RETURN 7
+ 7287 RESTART
+ 7288 GRAB 1
+ 7290 PUSHTRAP 7303
+ 7292 ACC4
+ 7293 GETFIELD 5
+ 7295 PUSHACC6
+ 7296 PUSHGETGLOBALFIELD List, 29
+ 7299 APPLY2
+ 7300 POPTRAP
+ 7301 RETURN 2
+ 7303 PUSHGETGLOBAL Not_found
+ 7305 PUSHACC1
+ 7306 GETFIELD0
+ 7307 EQ
+ 7308 BRANCHIFNOT 7325
+ 7310 ACC2
+ 7311 PUSHENVACC1
+ 7312 APPLY1
+ 7313 PUSHACC0
+ 7314 GETFIELD1
+ 7315 PUSHACC1
+ 7316 GETFIELD0
+ 7317 PUSHACC4
+ 7318 GETFIELD1
+ 7319 C_CALL2 array_get_addr
+ 7321 C_CALL2 array_get
+ 7323 RETURN 4
+ 7325 ACC0
+ 7326 RAISE
+ 7327 RESTART
+ 7328 GRAB 2
+ 7330 ENVACC3
+ 7331 OFFSETREF 1
+ 7333 ACC0
+ 7334 GETFIELD3
+ 7335 PUSHACC2
+ 7336 PUSHENVACC1
+ 7337 GETFIELD2
+ 7338 APPLY2
+ 7339 BRANCHIFNOT 7347
+ 7341 ACC2
+ 7342 PUSHACC2
+ 7343 PUSHACC2
+ 7344 PUSHENVACC2
+ 7345 APPTERM3 6
+ 7347 ACC0
+ 7348 GETFIELD 5
+ 7350 PUSHACC3
+ 7351 PUSHACC3
+ 7352 MAKEBLOCK2 0
+ 7354 MAKEBLOCK2 0
+ 7356 PUSHACC1
+ 7357 SETFIELD 5
+ 7359 RETURN 3
+ 7361 RESTART
+ 7362 GRAB 1
+ 7364 PUSHTRAP 7375
+ 7366 ACC4
+ 7367 GETFIELD2
+ 7368 PUSHACC6
+ 7369 PUSHENVACC2
+ 7370 GETFIELD2
+ 7371 APPLY2
+ 7372 POPTRAP
+ 7373 RETURN 2
+ 7375 PUSHGETGLOBAL Not_found
+ 7377 PUSHACC1
+ 7378 GETFIELD0
+ 7379 EQ
+ 7380 BRANCHIFNOT 7406
+ 7382 CONST0
+ 7383 PUSHENVACC1
+ 7384 APPLY1
+ 7385 PUSHACC2
+ 7386 GETFIELD2
+ 7387 PUSHACC1
+ 7388 PUSHACC5
+ 7389 PUSHENVACC2
+ 7390 GETFIELD1
+ 7391 APPLY3
+ 7392 PUSHACC3
+ 7393 SETFIELD2
+ 7394 ACC2
+ 7395 GETFIELD3
+ 7396 PUSHCONST1
+ 7397 PUSHACC2
+ 7398 PUSHENVACC3
+ 7399 GETFIELD1
+ 7400 APPLY3
+ 7401 PUSHACC3
+ 7402 SETFIELD3
+ 7403 ACC0
+ 7404 RETURN 4
+ 7406 ACC0
+ 7407 RAISE
+ 7408 RESTART
+ 7409 GRAB 2
+ 7411 ACC1
+ 7412 PUSHENVACC1
+ 7413 APPLY1
+ 7414 PUSHACC0
+ 7415 GETFIELD0
+ 7416 PUSHACC0
+ 7417 OFFSETINT 1
+ 7419 PUSHACC3
+ 7420 PUSHENVACC 4
+ 7422 APPLY2
+ 7423 ACC0
+ 7424 PUSHACC3
+ 7425 GETFIELD1
+ 7426 C_CALL2 array_get_addr
+ 7428 PUSHENVACC2
+ 7429 PUSHACC1
+ 7430 EQ
+ 7431 BRANCHIFNOT 7444
+ 7433 CONST0
+ 7434 PUSHENVACC3
+ 7435 APPLY1
+ 7436 ASSIGN 0
+ 7438 ACC0
+ 7439 PUSHACC2
+ 7440 PUSHACC5
+ 7441 GETFIELD1
+ 7442 C_CALL3 array_set_addr
+ 7444 ACC5
+ 7445 PUSHACC3
+ 7446 GETFIELD1
+ 7447 PUSHACC2
+ 7448 C_CALL3 array_set
+ 7450 RETURN 6
+ 7452 RESTART
+ 7453 GRAB 1
+ 7455 ACC0
+ 7456 GETFIELD1
+ 7457 VECTLENGTH
+ 7458 PUSHACC0
+ 7459 PUSHACC3
+ 7460 GTINT
+ 7461 BRANCHIFNOT 7487
+ 7463 ENVACC1
+ 7464 PUSHACC3
+ 7465 C_CALL2 make_vect
+ 7467 PUSH
+ 7468 PUSH_RETADDR 7482
+ 7470 ACC4
+ 7471 PUSHCONST0
+ 7472 PUSHACC5
+ 7473 PUSHCONST0
+ 7474 PUSHACC 9
+ 7476 GETFIELD1
+ 7477 PUSHGETGLOBALFIELD Array, 8
+ 7480 APPLY 5
+ 7482 ACC0
+ 7483 PUSHACC3
+ 7484 SETFIELD1
+ 7485 POP 1
+ 7487 RETURN 3
+ 7489 ENVACC 5
+ 7491 OFFSETREF 1
+ 7493 CONST0
+ 7494 PUSHENVACC2
+ 7495 GETFIELD0
+ 7496 PUSHCONST0
+ 7497 PUSHCONST0
+ 7498 PUSHENVACC 4
+ 7500 GETFIELD0
+ 7501 PUSHENVACC3
+ 7502 GETFIELD0
+ 7503 PUSH
+ 7504 ATOM0
+ 7505 PUSHENVACC1
+ 7506 MAKEBLOCK 8, 0
+ 7509 RETURN 1
+ 7511 RESTART
+ 7512 GRAB 1
+ 7514 ACC1
+ 7515 PUSHACC1
+ 7516 C_CALL2 compare
+ 7518 RETURN 2
+ 7520 RESTART
+ 7521 GRAB 1
+ 7523 ACC1
+ 7524 PUSHACC1
+ 7525 C_CALL2 compare
+ 7527 RETURN 2
+ 7529 RESTART
+ 7530 GRAB 1
+ 7532 ACC1
+ 7533 PUSHACC1
+ 7534 C_CALL2 compare
+ 7536 RETURN 2
+ 7538 PUSHTRAP 7549
+ 7540 ACC4
+ 7541 PUSHENVACC1
+ 7542 PUSHGETGLOBALFIELD Hashtbl, 3
+ 7545 APPLY2
+ 7546 POPTRAP
+ 7547 RETURN 1
+ 7549 PUSHGETGLOBAL Not_found
+ 7551 PUSHACC1
+ 7552 GETFIELD0
+ 7553 EQ
+ 7554 BRANCHIFNOT 7569
+ 7556 CONST0
+ 7557 PUSHENVACC2
+ 7558 APPLY1
+ 7559 PUSHACC0
+ 7560 PUSHACC3
+ 7561 PUSHENVACC1
+ 7562 PUSHGETGLOBALFIELD Hashtbl, 2
+ 7565 APPLY3
+ 7566 ACC0
+ 7567 RETURN 3
+ 7569 ACC0
+ 7570 RAISE
+ 7571 ENVACC2
+ 7572 GETFIELD0
+ 7573 PUSHENVACC2
+ 7574 GETFIELD0
+ 7575 PUSHENVACC1
+ 7576 APPLY1
+ 7577 PUSHENVACC2
+ 7578 SETFIELD0
+ 7579 ACC0
+ 7580 RETURN 2
+ 7582 ENVACC1
+ 7583 PUSHACC1
+ 7584 VECTLENGTH
+ 7585 OFFSETINT -1
+ 7587 PUSH
+ 7588 BRANCH 7606
+ 7590 CHECK_SIGNALS
+ 7591 ACC1
+ 7592 PUSHACC3
+ 7593 C_CALL2 array_get_addr
+ 7595 PUSHENVACC2
+ 7596 APPLY1
+ 7597 PUSHACC2
+ 7598 PUSHACC4
+ 7599 C_CALL3 array_set_addr
+ 7601 ACC1
+ 7602 OFFSETINT 1
+ 7604 ASSIGN 1
+ 7606 ACC0
+ 7607 PUSHACC2
+ 7608 LEINT
+ 7609 BRANCHIF 7590
+ 7611 CONST0
+ 7612 RETURN 3
+ 7614 ENVACC4
+ 7615 PUSHACC1
+ 7616 NEQ
+ 7617 BRANCHIFNOT 7640
+ 7619 ENVACC2
+ 7620 GETFIELD0
+ 7621 PUSHACC1
+ 7622 PUSHENVACC3
+ 7623 APPLY1
+ 7624 EQ
+ 7625 BRANCHIFNOT 7640
+ 7627 ACC0
+ 7628 PUSHENVACC 5
+ 7630 APPLY1
+ 7631 BRANCHIFNOT 7640
+ 7633 ENVACC1
+ 7634 GETFIELD3
+ 7635 PUSHACC1
+ 7636 PUSHENVACC 6
+ 7638 APPTERM2 3
+ 7640 ACC0
+ 7641 RETURN 1
+ 7643 RESTART
+ 7644 GRAB 1
+ 7646 CONST0
+ 7647 PUSHENVACC1
+ 7648 OFFSETINT -1
+ 7650 PUSH
+ 7651 BRANCH 7690
+ 7653 CHECK_SIGNALS
+ 7654 ENVACC2
+ 7655 PUSHACC2
+ 7656 PUSHACC5
+ 7657 C_CALL2 array_get
+ 7659 NEQ
+ 7660 BRANCHIFNOT 7679
+ 7662 ENVACC2
+ 7663 PUSHACC2
+ 7664 PUSHACC4
+ 7665 C_CALL2 array_get
+ 7667 NEQ
+ 7668 BRANCHIFNOT 7679
+ 7670 ACC1
+ 7671 PUSHACC3
+ 7672 C_CALL2 array_get
+ 7674 PUSHACC2
+ 7675 PUSHACC5
+ 7676 C_CALL2 array_get
+ 7678 NEQ
+ 7679 BRANCHIFNOT 7685
+ 7681 ENVACC4
+ 7682 MAKEBLOCK1 0
+ 7684 RAISE
+ 7685 ACC1
+ 7686 OFFSETINT 1
+ 7688 ASSIGN 1
+ 7690 ACC0
+ 7691 PUSHACC2
+ 7692 LEINT
+ 7693 BRANCHIF 7653
+ 7695 CONST0
+ 7696 POP 2
+ 7698 CONST0
+ 7699 PUSHENVACC1
+ 7700 OFFSETINT -1
+ 7702 PUSH
+ 7703 BRANCH 7727
+ 7705 CHECK_SIGNALS
+ 7706 ENVACC2
+ 7707 PUSHACC2
+ 7708 PUSHACC5
+ 7709 C_CALL2 array_get
+ 7711 NEQ
+ 7712 BRANCHIFNOT 7722
+ 7714 ACC1
+ 7715 PUSHACC4
+ 7716 C_CALL2 array_get
+ 7718 PUSHACC2
+ 7719 PUSHACC4
+ 7720 C_CALL3 array_set
+ 7722 ACC1
+ 7723 OFFSETINT 1
+ 7725 ASSIGN 1
+ 7727 ACC0
+ 7728 PUSHACC2
+ 7729 LEINT
+ 7730 BRANCHIF 7705
+ 7732 CONST0
+ 7733 POP 2
+ 7735 ENVACC3
+ 7736 GETFIELD0
+ 7737 PUSHACC2
+ 7738 PUSHENVACC 5
+ 7740 APPLY2
+ 7741 PUSHENVACC3
+ 7742 SETFIELD0
+ 7743 ACC0
+ 7744 RETURN 2
+ 7746 ENVACC1
+ 7747 GETFIELD 4
+ 7749 PUSHACC1
+ 7750 PUSHENVACC2
+ 7751 APPLY1
+ 7752 LEINT
+ 7753 RETURN 1
+ 7755 CONST0
+ 7756 PUSHCONST0
+ 7757 PUSHENVACC1
+ 7758 OFFSETINT -1
+ 7760 PUSH
+ 7761 BRANCH 7782
+ 7763 CHECK_SIGNALS
+ 7764 ENVACC2
+ 7765 PUSHACC2
+ 7766 PUSHACC5
+ 7767 C_CALL2 array_get
+ 7769 NEQ
+ 7770 BRANCHIFNOT 7777
+ 7772 ACC2
+ 7773 OFFSETINT 1
+ 7775 ASSIGN 2
+ 7777 ACC1
+ 7778 OFFSETINT 1
+ 7780 ASSIGN 1
+ 7782 ACC0
+ 7783 PUSHACC2
+ 7784 LEINT
+ 7785 BRANCHIF 7763
+ 7787 CONST0
+ 7788 POP 2
+ 7790 ACC0
+ 7791 RETURN 2
+ 7793 ENVACC2
+ 7794 GETFIELD0
+ 7795 OFFSETINT -1
+ 7797 PUSHENVACC1
+ 7798 GETFIELD0
+ 7799 C_CALL2 array_get_addr
+ 7801 PUSHACC1
+ 7802 PUSHENVACC1
+ 7803 GETFIELD0
+ 7804 C_CALL3 array_set_addr
+ 7806 ENVACC2
+ 7807 OFFSETREF -1
+ 7809 RETURN 1
+ 7811 ENVACC1
+ 7812 GETFIELD0
+ 7813 VECTLENGTH
+ 7814 PUSHACC0
+ 7815 PUSHENVACC2
+ 7816 GETFIELD0
+ 7817 GEINT
+ 7818 BRANCHIFNOT 7845
+ 7820 ATOM0
+ 7821 PUSHACC1
+ 7822 PUSHCONST2
+ 7823 MULINT
+ 7824 C_CALL2 make_vect
+ 7826 PUSH
+ 7827 PUSH_RETADDR 7840
+ 7829 ACC4
+ 7830 PUSHCONST0
+ 7831 PUSHACC5
+ 7832 PUSHCONST0
+ 7833 PUSHENVACC1
+ 7834 GETFIELD0
+ 7835 PUSHGETGLOBALFIELD Array, 8
+ 7838 APPLY 5
+ 7840 ACC0
+ 7841 PUSHENVACC1
+ 7842 SETFIELD0
+ 7843 POP 1
+ 7845 ACC1
+ 7846 PUSHENVACC2
+ 7847 GETFIELD0
+ 7848 PUSHENVACC1
+ 7849 GETFIELD0
+ 7850 C_CALL3 array_set_addr
+ 7852 ENVACC2
+ 7853 OFFSETREF 1
+ 7855 RETURN 2
+ 7857 ACC0
+ 7858 GETFIELD0
+ 7859 PUSHENVACC1
+ 7860 APPLY1
+ 7861 PUSHENVACC2
+ 7862 PUSHACC1
+ 7863 GETFIELD0
+ 7864 EQ
+ 7865 BRANCHIFNOT 7874
+ 7867 ACC1
+ 7868 GETFIELD1
+ 7869 PUSHACC1
+ 7870 GETFIELD1
+ 7871 PUSHENVACC3
+ 7872 C_CALL3 array_set
+ 7874 RETURN 2
+ 7876 RESTART
+ 7877 GRAB 1
+ 7879 CONST0
+ 7880 PUSHENVACC2
+ 7881 APPLY1
+ 7882 PUSHACC2
+ 7883 PUSHGETGLOBALFIELD List, 4
+ 7886 APPLY1
+ 7887 PUSHACC1
+ 7888 PUSHACC3
+ 7889 PUSHENVACC1
+ 7890 CLOSURE 3, 7857
+ 7893 PUSHGETGLOBALFIELD List, 9
+ 7896 APPLY2
+ 7897 ACC0
+ 7898 RETURN 3
+ 7900 ACC0
+ 7901 PUSHGETGLOBALFIELD Array, 6
+ 7904 APPLY1
+ 7905 PUSHACC0
+ 7906 PUSHENVACC3
+ 7907 APPLY1
+ 7908 ENVACC2
+ 7909 GETFIELD0
+ 7910 PUSHENVACC1
+ 7911 PUSHACC2
+ 7912 C_CALL3 array_set
+ 7914 ENVACC4
+ 7915 GETFIELD0
+ 7916 PUSHACC1
+ 7917 MAKEBLOCK2 0
+ 7919 PUSHENVACC 4
+ 7921 SETFIELD0
+ 7922 ACC0
+ 7923 RETURN 2
+ 7925 ENVACC2
+ 7926 PUSHENVACC1
+ 7927 OFFSETINT 1
+ 7929 C_CALL2 make_vect
+ 7931 PUSHACC0
+ 7932 PUSHENVACC3
+ 7933 APPLY1
+ 7934 ENVACC4
+ 7935 GETFIELD0
+ 7936 PUSHACC1
+ 7937 MAKEBLOCK2 0
+ 7939 PUSHENVACC 4
+ 7941 SETFIELD0
+ 7942 ACC0
+ 7943 RETURN 2
+ 7945 ENVACC1
+ 7946 PUSHACC1
+ 7947 C_CALL2 array_get
+ 7949 RETURN 1
+ 7951 ENVACC2
+ 7952 GETFIELD0
+ 7953 PUSHENVACC1
+ 7954 PUSHACC2
+ 7955 C_CALL3 array_set
+ 7957 RETURN 1
+ 7959 ENVACC1
+ 7960 PUSHENVACC2
+ 7961 PUSHENVACC1
+ 7962 MULINT
+ 7963 PUSHACC2
+ 7964 MODINT
+ 7965 DIVINT
+ 7966 PUSHENVACC1
+ 7967 PUSHCONSTINT 65536
+ 7969 PUSHACC3
+ 7970 DIVINT
+ 7971 DIVINT
+ 7972 MAKEBLOCK2 0
+ 7974 RETURN 1
+ 7976 ENVACC3
+ 7977 OFFSETREF 1
+ 7979 ENVACC1
+ 7980 PUSHACC1
+ 7981 ADDINT
+ 7982 PUSHCONST0
+ 7983 PUSHENVACC2
+ 7984 PUSHENVACC1
+ 7985 MULINT
+ 7986 PUSHACC2
+ 7987 MODINT
+ 7988 EQ
+ 7989 BRANCHIFNOT 8001
+ 7991 ENVACC2
+ 7992 PUSHCONSTINT 65536
+ 7994 SUBINT
+ 7995 PUSHENVACC1
+ 7996 MULINT
+ 7997 PUSHACC1
+ 7998 ADDINT
+ 7999 RETURN 2
+ 8001 ACC0
+ 8002 RETURN 2
+ 8004 ACC0
+ 8005 C_CALL1 obj_dup
+ 8007 PUSHENVACC1
+ 8008 PUSHACC1
+ 8009 PUSHENVACC2
+ 8010 APPLY2
+ 8011 ACC0
+ 8012 RETURN 2
+ 8014 RESTART
+ 8015 GRAB 1
+ 8017 ACC1
+ 8018 GETFIELD0
+ 8019 PUSHACC0
+ 8020 PUSHCONST1
+ 8021 PUSHACC3
+ 8022 SETVECTITEM
+ 8023 ACC0
+ 8024 OFFSETINT 1
+ 8026 PUSHACC3
+ 8027 SETFIELD0
+ 8028 RETURN 3
+ 8030 ENVACC1
+ 8031 GETFIELD0
+ 8032 PUSHENVACC1
+ 8033 OFFSETREF 1
+ 8035 ACC0
+ 8036 RETURN 2
+ 8038 CONSTINT 248
+ 8040 PUSHCONST0
+ 8041 MAKEBLOCK1 0
+ 8043 PUSHACC0
+ 8044 CLOSURE 1, 8030
+ 8047 PUSH
+ 8048 CLOSURE 0, 8015
+ 8051 PUSHACC0
+ 8052 PUSHACC3
+ 8053 CLOSURE 2, 8004
+ 8056 PUSHCONSTINT 16
+ 8058 PUSHCONST3
+ 8059 PUSHCONST1
+ 8060 PUSHCONST1
+ 8061 PUSHCONST1
+ 8062 MAKEBLOCK 5, 0
+ 8065 PUSHCONSTINT 16
+ 8067 PUSHGETGLOBALFIELD Sys, 3
+ 8070 DIVINT
+ 8071 PUSHCONST0
+ 8072 PUSHCONSTINT 32
+ 8074 PUSHCONST2
+ 8075 PUSHCONST0
+ 8076 MAKEBLOCK1 0
+ 8078 PUSHACC0
+ 8079 PUSHACC3
+ 8080 PUSHACC6
+ 8081 CLOSURE 3, 7976
+ 8084 PUSHACC3
+ 8085 PUSHACC6
+ 8086 CLOSURE 2, 7959
+ 8089 PUSHCONST0
+ 8090 PUSHCONST0
+ 8091 MAKEBLOCK1 0
+ 8093 PUSHACC0
+ 8094 PUSHACC7
+ 8095 CLOSURE 2, 7951
+ 8098 PUSHACC7
+ 8099 CLOSURE 1, 7945
+ 8102 PUSHCONST0
+ 8103 MAKEBLOCK1 0
+ 8105 PUSH
+ 8106 ATOM0
+ 8107 PUSHACC1
+ 8108 PUSHACC4
+ 8109 PUSHACC7
+ 8110 PUSHACC 13
+ 8112 CLOSURE 4, 7925
+ 8115 PUSHACC2
+ 8116 PUSHACC5
+ 8117 PUSHACC7
+ 8118 PUSHACC 14
+ 8120 CLOSURE 4, 7900
+ 8123 PUSHACC1
+ 8124 PUSHACC 9
+ 8126 CLOSURE 2, 7877
+ 8129 PUSH
+ 8130 ATOM0
+ 8131 PUSHCONSTINT 10
+ 8133 C_CALL2 make_vect
+ 8135 MAKEBLOCK1 0
+ 8137 PUSHCONST0
+ 8138 MAKEBLOCK1 0
+ 8140 PUSHACC0
+ 8141 PUSHACC2
+ 8142 CLOSURE 2, 7811
+ 8145 PUSHACC1
+ 8146 PUSHACC3
+ 8147 CLOSURE 2, 7793
+ 8150 PUSHACC 12
+ 8152 PUSHACC 18
+ 8154 CLOSURE 2, 7755
+ 8157 PUSHACC0
+ 8158 PUSHACC 22
+ 8160 CLOSURE 2, 7746
+ 8163 PUSHGETGLOBAL "Oo.Failed"
+ 8165 MAKEBLOCK1 0
+ 8167 PUSH
+ 8168 CLOSUREREC 0, 6415
+ 8172 ACC0
+ 8173 PUSHACC2
+ 8174 PUSHACC 14
+ 8176 PUSHACC 19
+ 8178 PUSHACC 25
+ 8180 CLOSURE 5, 7644
+ 8183 PUSHACC0
+ 8184 PUSHACC3
+ 8185 PUSHACC5
+ 8186 PUSHACC 8
+ 8188 PUSHACC 10
+ 8190 PUSHACC 12
+ 8192 PUSHACC 14
+ 8194 CLOSUREREC 7, 6444
+ 8198 ACC0
+ 8199 PUSHACC5
+ 8200 PUSHACC 15
+ 8202 PUSHACC 18
+ 8204 PUSHACC 21
+ 8206 PUSHACC 31
+ 8208 CLOSURE 6, 7614
+ 8211 PUSHACC0
+ 8212 PUSHACC 26
+ 8214 CLOSURE 2, 7582
+ 8217 PUSHACC 27
+ 8219 PUSHCONSTINT 65536
+ 8221 PUSHACC 28
+ 8223 MULINT
+ 8224 MULINT
+ 8225 PUSHACC0
+ 8226 MAKEBLOCK1 0
+ 8228 PUSHCONSTINT 101
+ 8230 PUSHGETGLOBALFIELD Hashtbl, 0
+ 8233 APPLY1
+ 8234 PUSHACC1
+ 8235 PUSHACC 26
+ 8237 CLOSURE 2, 7571
+ 8240 PUSHACC0
+ 8241 PUSHACC2
+ 8242 CLOSURE 2, 7538
+ 8245 PUSH
+ 8246 CLOSURE 0, 7530
+ 8249 PUSHACC0
+ 8250 MAKEBLOCK1 0
+ 8252 POP 1
+ 8254 PUSHGETGLOBALFIELD Map, 0
+ 8257 APPLY1
+ 8258 PUSH
+ 8259 CLOSURE 0, 7521
+ 8262 PUSHACC0
+ 8263 MAKEBLOCK1 0
+ 8265 POP 1
+ 8267 PUSHGETGLOBALFIELD Map, 0
+ 8270 APPLY1
+ 8271 PUSH
+ 8272 CLOSURE 0, 7512
+ 8275 PUSHACC0
+ 8276 MAKEBLOCK1 0
+ 8278 POP 1
+ 8280 PUSHGETGLOBALFIELD Map, 0
+ 8283 APPLY1
+ 8284 PUSHCONST0
+ 8285 MAKEBLOCK1 0
+ 8287 PUSHACC0
+ 8288 PUSHACC2
+ 8289 PUSHACC4
+ 8290 PUSHACC6
+ 8291 PUSHACC 37
+ 8293 CLOSURE 5, 7489
+ 8296 PUSHACC 25
+ 8298 CLOSURE 1, 7453
+ 8301 PUSHACC0
+ 8302 PUSHACC 26
+ 8304 PUSHACC 28
+ 8306 PUSHACC 35
+ 8308 CLOSURE 4, 7409
+ 8311 PUSHCONST0
+ 8312 MAKEBLOCK1 0
+ 8314 PUSHCONST0
+ 8315 MAKEBLOCK1 0
+ 8317 PUSHACC6
+ 8318 PUSHACC 8
+ 8320 PUSHACC 12
+ 8322 CLOSURE 3, 7362
+ 8325 PUSHACC2
+ 8326 PUSHACC4
+ 8327 PUSHACC 9
+ 8329 CLOSURE 3, 7328
+ 8332 PUSHACC 37
+ 8334 CLOSURE 1, 7288
+ 8337 PUSHACC2
+ 8338 PUSHACC 10
+ 8340 PUSHACC 12
+ 8342 PUSHACC 14
+ 8344 CLOSURE 4, 7187
+ 8347 PUSHACC 12
+ 8349 CLOSURE 1, 7027
+ 8352 PUSH
+ 8353 CLOSURE 0, 6980
+ 8356 PUSH
+ 8357 CLOSURE 0, 6969
+ 8360 PUSHACC0
+ 8361 PUSHACC 16
+ 8363 CLOSURE 2, 6950
+ 8366 PUSHACC 16
+ 8368 CLOSURE 1, 6939
+ 8371 PUSHACC 47
+ 8373 CLOSURE 1, 6927
+ 8376 PUSH
+ 8377 CLOSURE 0, 6862
+ 8380 PUSHACC 15
+ 8382 PUSHACC 18
+ 8384 PUSHACC 20
+ 8386 PUSHACC 23
+ 8388 CLOSURE 4, 6842
+ 8391 PUSHACC 12
+ 8393 PUSHACC 27
+ 8395 PUSHACC 56
+ 8397 CLOSURE 3, 6787
+ 8400 PUSHACC 57
+ 8402 PUSHACC 60
+ 8404 PUSHACC 62
+ 8406 CLOSURE 3, 6769
+ 8409 PUSH
+ 8410 CLOSUREREC 0, 6519
+ 8414 ACC0
+ 8415 CLOSURE 1, 6752
+ 8418 PUSHACC0
+ 8419 PUSHACC 61
+ 8421 PUSHACC 64
+ 8423 CLOSURE 3, 6735
+ 8426 PUSHACC 52
+ 8428 CLOSURE 1, 6715
+ 8431 PUSHACC 39
+ 8433 PUSHACC 49
+ 8435 CLOSURE 2, 6695
+ 8438 PUSHACC0
+ 8439 PUSHACC 20
+ 8441 PUSHACC 22
+ 8443 PUSHACC 27
+ 8445 PUSHACC 47
+ 8447 PUSHACC 49
+ 8449 PUSHACC 55
+ 8451 PUSHACC 63
+ 8453 CLOSURE 8, 6644
+ 8456 PUSHACC 41
+ 8458 CLOSURE 1, 6618
+ 8461 PUSHACC0
+ 8462 PUSHACC 52
+ 8464 PUSHACC 57
+ 8466 PUSHACC 63
+ 8468 CLOSURE 4, 6581
+ 8471 PUSHACC0
+ 8472 PUSHACC3
+ 8473 PUSHACC 66
+ 8475 PUSHACC7
+ 8476 PUSHACC 9
+ 8478 PUSHACC 11
+ 8480 PUSHACC 14
+ 8482 PUSHACC 16
+ 8484 PUSHACC 18
+ 8486 PUSHACC 20
+ 8488 PUSHACC 27
+ 8490 PUSHACC 29
+ 8492 PUSHACC 32
+ 8494 PUSHACC 32
+ 8496 PUSHACC 35
+ 8498 PUSHACC 27
+ 8500 PUSHACC 29
+ 8502 PUSHACC 31
+ 8504 PUSHACC 34
+ 8506 PUSHACC 50
+ 8508 PUSHACC 85
+ 8510 MAKEBLOCK 21, 0
+ 8513 POP 70
+ 8515 SETGLOBAL Oo
+ 8517 BRANCH 8568
+ 8519 ACC0
+ 8520 BRANCHIFNOT 8525
+ 8522 ACC0
+ 8523 BRANCH 8530
+ 8525 ENVACC1
+ 8526 PUSHGETGLOBALFIELD Oo, 14
+ 8529 APPLY1
+ 8530 PUSHCONST0
+ 8531 ACC1
+ 8532 BRANCHIFNOT 8537
+ 8534 CONST0
+ 8535 BRANCH 8543
+ 8537 ENVACC1
+ 8538 PUSHACC1
+ 8539 PUSHGETGLOBALFIELD Oo, 15
+ 8542 APPLY2
+ 8543 ACC0
+ 8544 RETURN 2
+ 8546 CONSTINT 23
+ 8548 RETURN 1
+ 8550 CLOSURE 0, 8546
+ 8553 PUSHACC0
+ 8554 POP 1
+ 8556 PUSHENVACC1
+ 8557 PUSHACC2
+ 8558 PUSHGETGLOBALFIELD Oo, 8
+ 8561 APPLY3
+ 8562 ACC0
+ 8563 CLOSURE 1, 8519
+ 8566 RETURN 1
+ 8568 GETGLOBALFIELD Oo, 1
+ 8571 PUSHGETGLOBAL "m"
+ 8573 PUSHACC1
+ 8574 APPLY1
+ 8575 PUSHCONST3
+ 8576 C_CALL1 alloc_dummy
+ 8578 PUSHGETGLOBAL <0>("m", 0)
+ 8580 PUSHGETGLOBALFIELD Oo, 12
+ 8583 APPLY1
+ 8584 PUSHACC2
+ 8585 CLOSURE 1, 8550
+ 8588 PUSHACC1
+ 8589 PUSHACC1
+ 8590 APPLY1
+ 8591 PUSHACC2
+ 8592 PUSHGETGLOBALFIELD Oo, 13
+ 8595 APPLY1
+ 8596 ACC2
+ 8597 PUSHACC2
+ 8598 PUSHACC2
+ 8599 MAKEBLOCK3 0
+ 8601 POP 3
+ 8603 PUSHACC1
+ 8604 C_CALL2 update_dummy
+ 8606 CONST0
+ 8607 PUSHACC1
+ 8608 GETFIELD0
+ 8609 APPLY1
+ 8610 PUSHCONSTINT 23
+ 8612 PUSHACC1
+ 8613 PUSHACC4
+ 8614 GETMETHOD
+ 8615 APPLY1
+ 8616 NEQ
+ 8617 BRANCHIFNOT 8624
+ 8619 GETGLOBAL Not_found
+ 8621 MAKEBLOCK1 0
+ 8623 RAISE
+ 8624 POP 1
+ 8626 ACC0
+ 8627 MAKEBLOCK1 0
+ 8629 POP 3
+ 8631 SETGLOBAL T300-getmethod
+ 8633 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t301-object.ml b/testsuite/tests/tool-ocaml/t301-object.ml
new file mode 100644
index 0000000000..ac4a4e03d4
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t301-object.ml
@@ -0,0 +1,25 @@
+(**** file testinterp/t301-object.ml
+ suggested by Jacques Garrigue to Basile Starynkevitch
+
+ compilable with
+ocamlc -nostdlib -I ../../stdlib \
+ ../../stdlib/pervasives.cmo ../../stdlib/camlinternalOO.cmo \
+ t301-object.ml -o t301-object.byte
+
+***)
+
+class c = object (self)
+ method pubmet = 1
+ method privmet = self#pubmet + 1
+ val o = object method a = 3 method m = 4 end
+ method dynmet = o#m
+end;;
+
+let f () =
+ let c = new c in
+ (c#pubmet, c#privmet, c#dynmet);;
+
+let (x,y,z) = f () in
+ if x <> 1 then raise Not_found;
+ if y <> 2 then raise Not_found;
+ if z <> 4 then raise Not_found;;
diff --git a/testsuite/tests/tool-ocaml/t310-alloc-1.ml b/testsuite/tests/tool-ocaml/t310-alloc-1.ml
new file mode 100644
index 0000000000..c438cc972d
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t310-alloc-1.ml
@@ -0,0 +1,1587 @@
+open Lib;;
+let rec f a n =
+ if n <= 0 then a
+ else f (1::a) (n-1)
+in
+let l = f [] 30000 in
+if List.fold_left (+) 0 l <> 30000 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 BRANCH 2177
+ 1199 RESTART
+ 1200 GRAB 1
+ 1202 ACC1
+ 1203 BRANCHIFNOT 1213
+ 1205 ACC1
+ 1206 GETFIELD1
+ 1207 PUSHACC1
+ 1208 OFFSETINT 1
+ 1210 PUSHOFFSETCLOSURE0
+ 1211 APPTERM2 4
+ 1213 ACC0
+ 1214 RETURN 2
+ 1216 RESTART
+ 1217 GRAB 1
+ 1219 ACC0
+ 1220 BRANCHIFNOT 1251
+ 1222 CONST0
+ 1223 PUSHACC2
+ 1224 EQ
+ 1225 BRANCHIFNOT 1231
+ 1227 ACC0
+ 1228 GETFIELD0
+ 1229 RETURN 2
+ 1231 CONST0
+ 1232 PUSHACC2
+ 1233 GTINT
+ 1234 BRANCHIFNOT 1244
+ 1236 ACC1
+ 1237 OFFSETINT -1
+ 1239 PUSHACC1
+ 1240 GETFIELD1
+ 1241 PUSHOFFSETCLOSURE0
+ 1242 APPTERM2 4
+ 1244 GETGLOBAL "List.nth"
+ 1246 PUSHGETGLOBALFIELD Pervasives, 2
+ 1249 APPTERM1 3
+ 1251 GETGLOBAL "nth"
+ 1253 PUSHGETGLOBALFIELD Pervasives, 3
+ 1256 APPTERM1 3
+ 1258 RESTART
+ 1259 GRAB 1
+ 1261 ACC0
+ 1262 BRANCHIFNOT 1274
+ 1264 ACC1
+ 1265 PUSHACC1
+ 1266 GETFIELD0
+ 1267 MAKEBLOCK2 0
+ 1269 PUSHACC1
+ 1270 GETFIELD1
+ 1271 PUSHOFFSETCLOSURE0
+ 1272 APPTERM2 4
+ 1274 ACC1
+ 1275 RETURN 2
+ 1277 ACC0
+ 1278 BRANCHIFNOT 1291
+ 1280 ACC0
+ 1281 GETFIELD1
+ 1282 PUSHOFFSETCLOSURE0
+ 1283 APPLY1
+ 1284 PUSHACC1
+ 1285 GETFIELD0
+ 1286 PUSHGETGLOBALFIELD Pervasives, 16
+ 1289 APPTERM2 3
+ 1291 RETURN 1
+ 1293 RESTART
+ 1294 GRAB 1
+ 1296 ACC1
+ 1297 BRANCHIFNOT 1313
+ 1299 ACC1
+ 1300 GETFIELD0
+ 1301 PUSHACC1
+ 1302 APPLY1
+ 1303 PUSHACC2
+ 1304 GETFIELD1
+ 1305 PUSHACC2
+ 1306 PUSHOFFSETCLOSURE0
+ 1307 APPLY2
+ 1308 PUSHACC1
+ 1309 MAKEBLOCK2 0
+ 1311 POP 1
+ 1313 RETURN 2
+ 1315 RESTART
+ 1316 GRAB 1
+ 1318 ACC1
+ 1319 BRANCHIFNOT 1331
+ 1321 ACC1
+ 1322 GETFIELD0
+ 1323 PUSHACC1
+ 1324 APPLY1
+ 1325 ACC1
+ 1326 GETFIELD1
+ 1327 PUSHACC1
+ 1328 PUSHOFFSETCLOSURE0
+ 1329 APPTERM2 4
+ 1331 RETURN 2
+ 1333 RESTART
+ 1334 GRAB 2
+ 1336 ACC2
+ 1337 BRANCHIFNOT 1350
+ 1339 ACC2
+ 1340 GETFIELD1
+ 1341 PUSHACC3
+ 1342 GETFIELD0
+ 1343 PUSHACC3
+ 1344 PUSHACC3
+ 1345 APPLY2
+ 1346 PUSHACC2
+ 1347 PUSHOFFSETCLOSURE0
+ 1348 APPTERM3 6
+ 1350 ACC1
+ 1351 RETURN 3
+ 1353 RESTART
+ 1354 GRAB 2
+ 1356 ACC1
+ 1357 BRANCHIFNOT 1370
+ 1359 ACC2
+ 1360 PUSHACC2
+ 1361 GETFIELD1
+ 1362 PUSHACC2
+ 1363 PUSHOFFSETCLOSURE0
+ 1364 APPLY3
+ 1365 PUSHACC2
+ 1366 GETFIELD0
+ 1367 PUSHACC2
+ 1368 APPTERM2 5
+ 1370 ACC2
+ 1371 RETURN 3
+ 1373 RESTART
+ 1374 GRAB 2
+ 1376 ACC1
+ 1377 BRANCHIFNOT 1400
+ 1379 ACC2
+ 1380 BRANCHIFNOT 1407
+ 1382 ACC2
+ 1383 GETFIELD0
+ 1384 PUSHACC2
+ 1385 GETFIELD0
+ 1386 PUSHACC2
+ 1387 APPLY2
+ 1388 PUSHACC3
+ 1389 GETFIELD1
+ 1390 PUSHACC3
+ 1391 GETFIELD1
+ 1392 PUSHACC3
+ 1393 PUSHOFFSETCLOSURE0
+ 1394 APPLY3
+ 1395 PUSHACC1
+ 1396 MAKEBLOCK2 0
+ 1398 RETURN 4
+ 1400 ACC2
+ 1401 BRANCHIFNOT 1405
+ 1403 BRANCH 1407
+ 1405 RETURN 3
+ 1407 GETGLOBAL "List.map2"
+ 1409 PUSHGETGLOBALFIELD Pervasives, 2
+ 1412 APPTERM1 4
+ 1414 RESTART
+ 1415 GRAB 2
+ 1417 ACC1
+ 1418 BRANCHIFNOT 1437
+ 1420 ACC2
+ 1421 BRANCHIFNOT 1444
+ 1423 ACC2
+ 1424 GETFIELD0
+ 1425 PUSHACC2
+ 1426 GETFIELD0
+ 1427 PUSHACC2
+ 1428 APPLY2
+ 1429 ACC2
+ 1430 GETFIELD1
+ 1431 PUSHACC2
+ 1432 GETFIELD1
+ 1433 PUSHACC2
+ 1434 PUSHOFFSETCLOSURE0
+ 1435 APPTERM3 6
+ 1437 ACC2
+ 1438 BRANCHIFNOT 1442
+ 1440 BRANCH 1444
+ 1442 RETURN 3
+ 1444 GETGLOBAL "List.iter2"
+ 1446 PUSHGETGLOBALFIELD Pervasives, 2
+ 1449 APPTERM1 4
+ 1451 RESTART
+ 1452 GRAB 3
+ 1454 ACC2
+ 1455 BRANCHIFNOT 1476
+ 1457 ACC3
+ 1458 BRANCHIFNOT 1482
+ 1460 ACC3
+ 1461 GETFIELD1
+ 1462 PUSHACC3
+ 1463 GETFIELD1
+ 1464 PUSHACC5
+ 1465 GETFIELD0
+ 1466 PUSHACC5
+ 1467 GETFIELD0
+ 1468 PUSHACC5
+ 1469 PUSHACC5
+ 1470 APPLY3
+ 1471 PUSHACC3
+ 1472 PUSHOFFSETCLOSURE0
+ 1473 APPTERM 4, 8
+ 1476 ACC3
+ 1477 BRANCHIF 1482
+ 1479 ACC1
+ 1480 RETURN 4
+ 1482 GETGLOBAL "List.fold_left2"
+ 1484 PUSHGETGLOBALFIELD Pervasives, 2
+ 1487 APPTERM1 5
+ 1489 RESTART
+ 1490 GRAB 3
+ 1492 ACC1
+ 1493 BRANCHIFNOT 1516
+ 1495 ACC2
+ 1496 BRANCHIFNOT 1522
+ 1498 PUSH_RETADDR 1509
+ 1500 ACC6
+ 1501 PUSHACC6
+ 1502 GETFIELD1
+ 1503 PUSHACC6
+ 1504 GETFIELD1
+ 1505 PUSHACC6
+ 1506 PUSHOFFSETCLOSURE0
+ 1507 APPLY 4
+ 1509 PUSHACC3
+ 1510 GETFIELD0
+ 1511 PUSHACC3
+ 1512 GETFIELD0
+ 1513 PUSHACC3
+ 1514 APPTERM3 7
+ 1516 ACC2
+ 1517 BRANCHIF 1522
+ 1519 ACC3
+ 1520 RETURN 4
+ 1522 GETGLOBAL "List.fold_right2"
+ 1524 PUSHGETGLOBALFIELD Pervasives, 2
+ 1527 APPTERM1 5
+ 1529 RESTART
+ 1530 GRAB 1
+ 1532 ACC1
+ 1533 BRANCHIFNOT 1549
+ 1535 ACC1
+ 1536 GETFIELD0
+ 1537 PUSHACC1
+ 1538 APPLY1
+ 1539 BRANCHIFNOT 1547
+ 1541 ACC1
+ 1542 GETFIELD1
+ 1543 PUSHACC1
+ 1544 PUSHOFFSETCLOSURE0
+ 1545 APPTERM2 4
+ 1547 RETURN 2
+ 1549 CONST1
+ 1550 RETURN 2
+ 1552 RESTART
+ 1553 GRAB 1
+ 1555 ACC1
+ 1556 BRANCHIFNOT 1570
+ 1558 ACC1
+ 1559 GETFIELD0
+ 1560 PUSHACC1
+ 1561 APPLY1
+ 1562 BRANCHIF 1570
+ 1564 ACC1
+ 1565 GETFIELD1
+ 1566 PUSHACC1
+ 1567 PUSHOFFSETCLOSURE0
+ 1568 APPTERM2 4
+ 1570 RETURN 2
+ 1572 RESTART
+ 1573 GRAB 2
+ 1575 ACC1
+ 1576 BRANCHIFNOT 1599
+ 1578 ACC2
+ 1579 BRANCHIFNOT 1605
+ 1581 ACC2
+ 1582 GETFIELD0
+ 1583 PUSHACC2
+ 1584 GETFIELD0
+ 1585 PUSHACC2
+ 1586 APPLY2
+ 1587 BRANCHIFNOT 1597
+ 1589 ACC2
+ 1590 GETFIELD1
+ 1591 PUSHACC2
+ 1592 GETFIELD1
+ 1593 PUSHACC2
+ 1594 PUSHOFFSETCLOSURE0
+ 1595 APPTERM3 6
+ 1597 RETURN 3
+ 1599 ACC2
+ 1600 BRANCHIF 1605
+ 1602 CONST1
+ 1603 RETURN 3
+ 1605 GETGLOBAL "List.for_all2"
+ 1607 PUSHGETGLOBALFIELD Pervasives, 2
+ 1610 APPTERM1 4
+ 1612 RESTART
+ 1613 GRAB 2
+ 1615 ACC1
+ 1616 BRANCHIFNOT 1639
+ 1618 ACC2
+ 1619 BRANCHIFNOT 1646
+ 1621 ACC2
+ 1622 GETFIELD0
+ 1623 PUSHACC2
+ 1624 GETFIELD0
+ 1625 PUSHACC2
+ 1626 APPLY2
+ 1627 BRANCHIF 1637
+ 1629 ACC2
+ 1630 GETFIELD1
+ 1631 PUSHACC2
+ 1632 GETFIELD1
+ 1633 PUSHACC2
+ 1634 PUSHOFFSETCLOSURE0
+ 1635 APPTERM3 6
+ 1637 RETURN 3
+ 1639 ACC2
+ 1640 BRANCHIFNOT 1644
+ 1642 BRANCH 1646
+ 1644 RETURN 3
+ 1646 GETGLOBAL "List.exists2"
+ 1648 PUSHGETGLOBALFIELD Pervasives, 2
+ 1651 APPTERM1 4
+ 1653 RESTART
+ 1654 GRAB 1
+ 1656 ACC1
+ 1657 BRANCHIFNOT 1672
+ 1659 ACC0
+ 1660 PUSHACC2
+ 1661 GETFIELD0
+ 1662 C_CALL2 equal
+ 1664 BRANCHIF 1672
+ 1666 ACC1
+ 1667 GETFIELD1
+ 1668 PUSHACC1
+ 1669 PUSHOFFSETCLOSURE0
+ 1670 APPTERM2 4
+ 1672 RETURN 2
+ 1674 RESTART
+ 1675 GRAB 1
+ 1677 ACC1
+ 1678 BRANCHIFNOT 1692
+ 1680 ACC0
+ 1681 PUSHACC2
+ 1682 GETFIELD0
+ 1683 EQ
+ 1684 BRANCHIF 1692
+ 1686 ACC1
+ 1687 GETFIELD1
+ 1688 PUSHACC1
+ 1689 PUSHOFFSETCLOSURE0
+ 1690 APPTERM2 4
+ 1692 RETURN 2
+ 1694 RESTART
+ 1695 GRAB 1
+ 1697 ACC1
+ 1698 BRANCHIFNOT 1719
+ 1700 ACC1
+ 1701 GETFIELD0
+ 1702 PUSHACC1
+ 1703 PUSHACC1
+ 1704 GETFIELD0
+ 1705 C_CALL2 equal
+ 1707 BRANCHIFNOT 1713
+ 1709 ACC0
+ 1710 GETFIELD1
+ 1711 RETURN 3
+ 1713 ACC2
+ 1714 GETFIELD1
+ 1715 PUSHACC2
+ 1716 PUSHOFFSETCLOSURE0
+ 1717 APPTERM2 5
+ 1719 GETGLOBAL Not_found
+ 1721 MAKEBLOCK1 0
+ 1723 RAISE
+ 1724 RESTART
+ 1725 GRAB 1
+ 1727 ACC1
+ 1728 BRANCHIFNOT 1748
+ 1730 ACC1
+ 1731 GETFIELD0
+ 1732 PUSHACC1
+ 1733 PUSHACC1
+ 1734 GETFIELD0
+ 1735 EQ
+ 1736 BRANCHIFNOT 1742
+ 1738 ACC0
+ 1739 GETFIELD1
+ 1740 RETURN 3
+ 1742 ACC2
+ 1743 GETFIELD1
+ 1744 PUSHACC2
+ 1745 PUSHOFFSETCLOSURE0
+ 1746 APPTERM2 5
+ 1748 GETGLOBAL Not_found
+ 1750 MAKEBLOCK1 0
+ 1752 RAISE
+ 1753 RESTART
+ 1754 GRAB 1
+ 1756 ACC1
+ 1757 BRANCHIFNOT 1773
+ 1759 ACC0
+ 1760 PUSHACC2
+ 1761 GETFIELD0
+ 1762 GETFIELD0
+ 1763 C_CALL2 equal
+ 1765 BRANCHIF 1773
+ 1767 ACC1
+ 1768 GETFIELD1
+ 1769 PUSHACC1
+ 1770 PUSHOFFSETCLOSURE0
+ 1771 APPTERM2 4
+ 1773 RETURN 2
+ 1775 RESTART
+ 1776 GRAB 1
+ 1778 ACC1
+ 1779 BRANCHIFNOT 1794
+ 1781 ACC0
+ 1782 PUSHACC2
+ 1783 GETFIELD0
+ 1784 GETFIELD0
+ 1785 EQ
+ 1786 BRANCHIF 1794
+ 1788 ACC1
+ 1789 GETFIELD1
+ 1790 PUSHACC1
+ 1791 PUSHOFFSETCLOSURE0
+ 1792 APPTERM2 4
+ 1794 RETURN 2
+ 1796 RESTART
+ 1797 GRAB 1
+ 1799 ACC1
+ 1800 BRANCHIFNOT 1825
+ 1802 ACC1
+ 1803 GETFIELD0
+ 1804 PUSHACC2
+ 1805 GETFIELD1
+ 1806 PUSHACC2
+ 1807 PUSHACC2
+ 1808 GETFIELD0
+ 1809 C_CALL2 equal
+ 1811 BRANCHIFNOT 1816
+ 1813 ACC0
+ 1814 RETURN 4
+ 1816 ACC0
+ 1817 PUSHACC3
+ 1818 PUSHOFFSETCLOSURE0
+ 1819 APPLY2
+ 1820 PUSHACC2
+ 1821 MAKEBLOCK2 0
+ 1823 POP 2
+ 1825 RETURN 2
+ 1827 RESTART
+ 1828 GRAB 1
+ 1830 ACC1
+ 1831 BRANCHIFNOT 1855
+ 1833 ACC1
+ 1834 GETFIELD0
+ 1835 PUSHACC2
+ 1836 GETFIELD1
+ 1837 PUSHACC2
+ 1838 PUSHACC2
+ 1839 GETFIELD0
+ 1840 EQ
+ 1841 BRANCHIFNOT 1846
+ 1843 ACC0
+ 1844 RETURN 4
+ 1846 ACC0
+ 1847 PUSHACC3
+ 1848 PUSHOFFSETCLOSURE0
+ 1849 APPLY2
+ 1850 PUSHACC2
+ 1851 MAKEBLOCK2 0
+ 1853 POP 2
+ 1855 RETURN 2
+ 1857 RESTART
+ 1858 GRAB 1
+ 1860 ACC1
+ 1861 BRANCHIFNOT 1879
+ 1863 ACC1
+ 1864 GETFIELD0
+ 1865 PUSHACC0
+ 1866 PUSHACC2
+ 1867 APPLY1
+ 1868 BRANCHIFNOT 1873
+ 1870 ACC0
+ 1871 RETURN 3
+ 1873 ACC2
+ 1874 GETFIELD1
+ 1875 PUSHACC2
+ 1876 PUSHOFFSETCLOSURE0
+ 1877 APPTERM2 5
+ 1879 GETGLOBAL Not_found
+ 1881 MAKEBLOCK1 0
+ 1883 RAISE
+ 1884 RESTART
+ 1885 GRAB 2
+ 1887 ACC2
+ 1888 BRANCHIFNOT 1917
+ 1890 ACC2
+ 1891 GETFIELD0
+ 1892 PUSHACC3
+ 1893 GETFIELD1
+ 1894 PUSHACC1
+ 1895 PUSHENVACC2
+ 1896 APPLY1
+ 1897 BRANCHIFNOT 1908
+ 1899 ACC0
+ 1900 PUSHACC4
+ 1901 PUSHACC4
+ 1902 PUSHACC4
+ 1903 MAKEBLOCK2 0
+ 1905 PUSHOFFSETCLOSURE0
+ 1906 APPTERM3 8
+ 1908 ACC0
+ 1909 PUSHACC4
+ 1910 PUSHACC3
+ 1911 MAKEBLOCK2 0
+ 1913 PUSHACC4
+ 1914 PUSHOFFSETCLOSURE0
+ 1915 APPTERM3 8
+ 1917 ACC1
+ 1918 PUSHENVACC1
+ 1919 APPLY1
+ 1920 PUSHACC1
+ 1921 PUSHENVACC1
+ 1922 APPLY1
+ 1923 MAKEBLOCK2 0
+ 1925 RETURN 3
+ 1927 RESTART
+ 1928 GRAB 1
+ 1930 ACC0
+ 1931 PUSHENVACC1
+ 1932 CLOSUREREC 2, 1885
+ 1936 ACC2
+ 1937 PUSHCONST0
+ 1938 PUSHCONST0
+ 1939 PUSHACC3
+ 1940 APPTERM3 6
+ 1942 ACC0
+ 1943 BRANCHIFNOT 1967
+ 1945 ACC0
+ 1946 GETFIELD0
+ 1947 PUSHACC1
+ 1948 GETFIELD1
+ 1949 PUSHOFFSETCLOSURE0
+ 1950 APPLY1
+ 1951 PUSHACC0
+ 1952 GETFIELD1
+ 1953 PUSHACC2
+ 1954 GETFIELD1
+ 1955 MAKEBLOCK2 0
+ 1957 PUSHACC1
+ 1958 GETFIELD0
+ 1959 PUSHACC3
+ 1960 GETFIELD0
+ 1961 MAKEBLOCK2 0
+ 1963 MAKEBLOCK2 0
+ 1965 RETURN 3
+ 1967 GETGLOBAL <0>(0, 0)
+ 1969 RETURN 1
+ 1971 RESTART
+ 1972 GRAB 1
+ 1974 ACC0
+ 1975 BRANCHIFNOT 1996
+ 1977 ACC1
+ 1978 BRANCHIFNOT 2003
+ 1980 ACC1
+ 1981 GETFIELD1
+ 1982 PUSHACC1
+ 1983 GETFIELD1
+ 1984 PUSHOFFSETCLOSURE0
+ 1985 APPLY2
+ 1986 PUSHACC2
+ 1987 GETFIELD0
+ 1988 PUSHACC2
+ 1989 GETFIELD0
+ 1990 MAKEBLOCK2 0
+ 1992 MAKEBLOCK2 0
+ 1994 RETURN 2
+ 1996 ACC1
+ 1997 BRANCHIFNOT 2001
+ 1999 BRANCH 2003
+ 2001 RETURN 2
+ 2003 GETGLOBAL "List.combine"
+ 2005 PUSHGETGLOBALFIELD Pervasives, 2
+ 2008 APPTERM1 3
+ 2010 RESTART
+ 2011 GRAB 1
+ 2013 ACC1
+ 2014 BRANCHIFNOT 2038
+ 2016 ACC1
+ 2017 GETFIELD0
+ 2018 PUSHACC2
+ 2019 GETFIELD1
+ 2020 PUSHACC1
+ 2021 PUSHENVACC2
+ 2022 APPLY1
+ 2023 BRANCHIFNOT 2033
+ 2025 ACC0
+ 2026 PUSHACC3
+ 2027 PUSHACC3
+ 2028 MAKEBLOCK2 0
+ 2030 PUSHOFFSETCLOSURE0
+ 2031 APPTERM2 6
+ 2033 ACC0
+ 2034 PUSHACC3
+ 2035 PUSHOFFSETCLOSURE0
+ 2036 APPTERM2 6
+ 2038 ACC0
+ 2039 PUSHENVACC1
+ 2040 APPTERM1 3
+ 2042 ACC0
+ 2043 PUSHENVACC1
+ 2044 CLOSUREREC 2, 2011
+ 2048 CONST0
+ 2049 PUSHACC1
+ 2050 APPTERM1 3
+ 2052 RESTART
+ 2053 GRAB 2
+ 2055 ACC1
+ 2056 BRANCHIFNOT 2077
+ 2058 ACC2
+ 2059 BRANCHIFNOT 2084
+ 2061 ACC2
+ 2062 GETFIELD1
+ 2063 PUSHACC2
+ 2064 GETFIELD1
+ 2065 PUSHACC2
+ 2066 PUSHACC5
+ 2067 GETFIELD0
+ 2068 PUSHACC5
+ 2069 GETFIELD0
+ 2070 PUSHENVACC1
+ 2071 APPLY2
+ 2072 MAKEBLOCK2 0
+ 2074 PUSHOFFSETCLOSURE0
+ 2075 APPTERM3 6
+ 2077 ACC2
+ 2078 BRANCHIFNOT 2082
+ 2080 BRANCH 2084
+ 2082 RETURN 3
+ 2084 GETGLOBAL "List.rev_map2"
+ 2086 PUSHGETGLOBALFIELD Pervasives, 2
+ 2089 APPTERM1 4
+ 2091 RESTART
+ 2092 GRAB 2
+ 2094 ACC0
+ 2095 CLOSUREREC 1, 2053
+ 2099 ACC3
+ 2100 PUSHACC3
+ 2101 PUSHCONST0
+ 2102 PUSHACC3
+ 2103 APPTERM3 7
+ 2105 RESTART
+ 2106 GRAB 1
+ 2108 ACC1
+ 2109 BRANCHIFNOT 2123
+ 2111 ACC1
+ 2112 GETFIELD1
+ 2113 PUSHACC1
+ 2114 PUSHACC3
+ 2115 GETFIELD0
+ 2116 PUSHENVACC1
+ 2117 APPLY1
+ 2118 MAKEBLOCK2 0
+ 2120 PUSHOFFSETCLOSURE0
+ 2121 APPTERM2 4
+ 2123 ACC0
+ 2124 RETURN 2
+ 2126 RESTART
+ 2127 GRAB 1
+ 2129 ACC0
+ 2130 CLOSUREREC 1, 2106
+ 2134 ACC2
+ 2135 PUSHCONST0
+ 2136 PUSHACC2
+ 2137 APPTERM2 5
+ 2139 CONST0
+ 2140 PUSHACC1
+ 2141 PUSHENVACC1
+ 2142 APPTERM2 3
+ 2144 ACC0
+ 2145 BRANCHIFNOT 2151
+ 2147 ACC0
+ 2148 GETFIELD1
+ 2149 RETURN 1
+ 2151 GETGLOBAL "tl"
+ 2153 PUSHGETGLOBALFIELD Pervasives, 3
+ 2156 APPTERM1 2
+ 2158 ACC0
+ 2159 BRANCHIFNOT 2165
+ 2161 ACC0
+ 2162 GETFIELD0
+ 2163 RETURN 1
+ 2165 GETGLOBAL "hd"
+ 2167 PUSHGETGLOBALFIELD Pervasives, 3
+ 2170 APPTERM1 2
+ 2172 ACC0
+ 2173 PUSHCONST0
+ 2174 PUSHENVACC1
+ 2175 APPTERM2 3
+ 2177 CLOSUREREC 0, 1200
+ 2181 ACC0
+ 2182 CLOSURE 1, 2172
+ 2185 PUSH
+ 2186 CLOSURE 0, 2158
+ 2189 PUSH
+ 2190 CLOSURE 0, 2144
+ 2193 PUSH
+ 2194 CLOSUREREC 0, 1217
+ 2198 GETGLOBALFIELD Pervasives, 16
+ 2201 PUSH
+ 2202 CLOSUREREC 0, 1259
+ 2206 ACC0
+ 2207 CLOSURE 1, 2139
+ 2210 PUSH
+ 2211 CLOSUREREC 0, 1277
+ 2215 CLOSUREREC 0, 1294
+ 2219 CLOSURE 0, 2127
+ 2222 PUSH
+ 2223 CLOSUREREC 0, 1316
+ 2227 CLOSUREREC 0, 1334
+ 2231 CLOSUREREC 0, 1354
+ 2235 CLOSUREREC 0, 1374
+ 2239 CLOSURE 0, 2092
+ 2242 PUSH
+ 2243 CLOSUREREC 0, 1415
+ 2247 CLOSUREREC 0, 1452
+ 2251 CLOSUREREC 0, 1490
+ 2255 CLOSUREREC 0, 1530
+ 2259 CLOSUREREC 0, 1553
+ 2263 CLOSUREREC 0, 1573
+ 2267 CLOSUREREC 0, 1613
+ 2271 CLOSUREREC 0, 1654
+ 2275 CLOSUREREC 0, 1675
+ 2279 CLOSUREREC 0, 1695
+ 2283 CLOSUREREC 0, 1725
+ 2287 CLOSUREREC 0, 1754
+ 2291 CLOSUREREC 0, 1776
+ 2295 CLOSUREREC 0, 1797
+ 2299 CLOSUREREC 0, 1828
+ 2303 CLOSUREREC 0, 1858
+ 2307 ACC 24
+ 2309 CLOSURE 1, 2042
+ 2312 PUSHACC 25
+ 2314 CLOSUREREC 1, 1928
+ 2318 CLOSUREREC 0, 1942
+ 2322 CLOSUREREC 0, 1972
+ 2326 ACC0
+ 2327 PUSHACC2
+ 2328 PUSHACC7
+ 2329 PUSHACC 9
+ 2331 PUSHACC 11
+ 2333 PUSHACC 13
+ 2335 PUSHACC 15
+ 2337 PUSHACC 17
+ 2339 PUSHACC 10
+ 2341 PUSHACC 12
+ 2343 PUSHACC 13
+ 2345 PUSHACC 15
+ 2347 PUSHACC 23
+ 2349 PUSHACC 25
+ 2351 PUSHACC 27
+ 2353 PUSHACC 29
+ 2355 PUSHACC 31
+ 2357 PUSHACC 33
+ 2359 PUSHACC 35
+ 2361 PUSHACC 37
+ 2363 PUSHACC 40
+ 2365 PUSHACC 42
+ 2367 PUSHACC 41
+ 2369 PUSHACC 45
+ 2371 PUSHACC 47
+ 2373 PUSHACC 50
+ 2375 PUSHACC 52
+ 2377 PUSHACC 51
+ 2379 PUSHACC 55
+ 2381 PUSHACC 56
+ 2383 PUSHACC 59
+ 2385 PUSHACC 61
+ 2387 PUSHACC 60
+ 2389 PUSHACC 64
+ 2391 PUSHACC 66
+ 2393 PUSHACC 68
+ 2395 PUSHACC 70
+ 2397 MAKEBLOCK 37, 0
+ 2400 POP 36
+ 2402 SETGLOBAL List
+ 2404 BRANCH 2435
+ 2406 RESTART
+ 2407 GRAB 1
+ 2409 CONST0
+ 2410 PUSHACC2
+ 2411 LEINT
+ 2412 BRANCHIFNOT 2417
+ 2414 ACC0
+ 2415 RETURN 2
+ 2417 ACC1
+ 2418 OFFSETINT -1
+ 2420 PUSHACC1
+ 2421 PUSHCONST1
+ 2422 MAKEBLOCK2 0
+ 2424 PUSHOFFSETCLOSURE0
+ 2425 APPTERM2 4
+ 2427 RESTART
+ 2428 GRAB 1
+ 2430 ACC1
+ 2431 PUSHACC1
+ 2432 ADDINT
+ 2433 RETURN 2
+ 2435 CLOSUREREC 0, 2407
+ 2439 CONSTINT 30000
+ 2441 PUSHCONST0
+ 2442 PUSHACC2
+ 2443 APPLY2
+ 2444 PUSHCONSTINT 30000
+ 2446 PUSHACC1
+ 2447 PUSHCONST0
+ 2448 PUSH
+ 2449 CLOSURE 0, 2428
+ 2452 PUSHGETGLOBALFIELD List, 12
+ 2455 APPLY3
+ 2456 NEQ
+ 2457 BRANCHIFNOT 2464
+ 2459 GETGLOBAL Not_found
+ 2461 MAKEBLOCK1 0
+ 2463 RAISE
+ 2464 POP 2
+ 2466 ATOM0
+ 2467 SETGLOBAL T310-alloc-1
+ 2469 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t310-alloc-2.ml b/testsuite/tests/tool-ocaml/t310-alloc-2.ml
new file mode 100644
index 0000000000..81034e78ab
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t310-alloc-2.ml
@@ -0,0 +1,2313 @@
+open Lib;;
+let v = Array.make 200000 2 in
+let t = ref 0 in
+Array.iter (fun x -> t := !t + x) v;
+if !t <> 400000 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 BRANCH 2177
+ 1199 RESTART
+ 1200 GRAB 1
+ 1202 ACC1
+ 1203 BRANCHIFNOT 1213
+ 1205 ACC1
+ 1206 GETFIELD1
+ 1207 PUSHACC1
+ 1208 OFFSETINT 1
+ 1210 PUSHOFFSETCLOSURE0
+ 1211 APPTERM2 4
+ 1213 ACC0
+ 1214 RETURN 2
+ 1216 RESTART
+ 1217 GRAB 1
+ 1219 ACC0
+ 1220 BRANCHIFNOT 1251
+ 1222 CONST0
+ 1223 PUSHACC2
+ 1224 EQ
+ 1225 BRANCHIFNOT 1231
+ 1227 ACC0
+ 1228 GETFIELD0
+ 1229 RETURN 2
+ 1231 CONST0
+ 1232 PUSHACC2
+ 1233 GTINT
+ 1234 BRANCHIFNOT 1244
+ 1236 ACC1
+ 1237 OFFSETINT -1
+ 1239 PUSHACC1
+ 1240 GETFIELD1
+ 1241 PUSHOFFSETCLOSURE0
+ 1242 APPTERM2 4
+ 1244 GETGLOBAL "List.nth"
+ 1246 PUSHGETGLOBALFIELD Pervasives, 2
+ 1249 APPTERM1 3
+ 1251 GETGLOBAL "nth"
+ 1253 PUSHGETGLOBALFIELD Pervasives, 3
+ 1256 APPTERM1 3
+ 1258 RESTART
+ 1259 GRAB 1
+ 1261 ACC0
+ 1262 BRANCHIFNOT 1274
+ 1264 ACC1
+ 1265 PUSHACC1
+ 1266 GETFIELD0
+ 1267 MAKEBLOCK2 0
+ 1269 PUSHACC1
+ 1270 GETFIELD1
+ 1271 PUSHOFFSETCLOSURE0
+ 1272 APPTERM2 4
+ 1274 ACC1
+ 1275 RETURN 2
+ 1277 ACC0
+ 1278 BRANCHIFNOT 1291
+ 1280 ACC0
+ 1281 GETFIELD1
+ 1282 PUSHOFFSETCLOSURE0
+ 1283 APPLY1
+ 1284 PUSHACC1
+ 1285 GETFIELD0
+ 1286 PUSHGETGLOBALFIELD Pervasives, 16
+ 1289 APPTERM2 3
+ 1291 RETURN 1
+ 1293 RESTART
+ 1294 GRAB 1
+ 1296 ACC1
+ 1297 BRANCHIFNOT 1313
+ 1299 ACC1
+ 1300 GETFIELD0
+ 1301 PUSHACC1
+ 1302 APPLY1
+ 1303 PUSHACC2
+ 1304 GETFIELD1
+ 1305 PUSHACC2
+ 1306 PUSHOFFSETCLOSURE0
+ 1307 APPLY2
+ 1308 PUSHACC1
+ 1309 MAKEBLOCK2 0
+ 1311 POP 1
+ 1313 RETURN 2
+ 1315 RESTART
+ 1316 GRAB 1
+ 1318 ACC1
+ 1319 BRANCHIFNOT 1331
+ 1321 ACC1
+ 1322 GETFIELD0
+ 1323 PUSHACC1
+ 1324 APPLY1
+ 1325 ACC1
+ 1326 GETFIELD1
+ 1327 PUSHACC1
+ 1328 PUSHOFFSETCLOSURE0
+ 1329 APPTERM2 4
+ 1331 RETURN 2
+ 1333 RESTART
+ 1334 GRAB 2
+ 1336 ACC2
+ 1337 BRANCHIFNOT 1350
+ 1339 ACC2
+ 1340 GETFIELD1
+ 1341 PUSHACC3
+ 1342 GETFIELD0
+ 1343 PUSHACC3
+ 1344 PUSHACC3
+ 1345 APPLY2
+ 1346 PUSHACC2
+ 1347 PUSHOFFSETCLOSURE0
+ 1348 APPTERM3 6
+ 1350 ACC1
+ 1351 RETURN 3
+ 1353 RESTART
+ 1354 GRAB 2
+ 1356 ACC1
+ 1357 BRANCHIFNOT 1370
+ 1359 ACC2
+ 1360 PUSHACC2
+ 1361 GETFIELD1
+ 1362 PUSHACC2
+ 1363 PUSHOFFSETCLOSURE0
+ 1364 APPLY3
+ 1365 PUSHACC2
+ 1366 GETFIELD0
+ 1367 PUSHACC2
+ 1368 APPTERM2 5
+ 1370 ACC2
+ 1371 RETURN 3
+ 1373 RESTART
+ 1374 GRAB 2
+ 1376 ACC1
+ 1377 BRANCHIFNOT 1400
+ 1379 ACC2
+ 1380 BRANCHIFNOT 1407
+ 1382 ACC2
+ 1383 GETFIELD0
+ 1384 PUSHACC2
+ 1385 GETFIELD0
+ 1386 PUSHACC2
+ 1387 APPLY2
+ 1388 PUSHACC3
+ 1389 GETFIELD1
+ 1390 PUSHACC3
+ 1391 GETFIELD1
+ 1392 PUSHACC3
+ 1393 PUSHOFFSETCLOSURE0
+ 1394 APPLY3
+ 1395 PUSHACC1
+ 1396 MAKEBLOCK2 0
+ 1398 RETURN 4
+ 1400 ACC2
+ 1401 BRANCHIFNOT 1405
+ 1403 BRANCH 1407
+ 1405 RETURN 3
+ 1407 GETGLOBAL "List.map2"
+ 1409 PUSHGETGLOBALFIELD Pervasives, 2
+ 1412 APPTERM1 4
+ 1414 RESTART
+ 1415 GRAB 2
+ 1417 ACC1
+ 1418 BRANCHIFNOT 1437
+ 1420 ACC2
+ 1421 BRANCHIFNOT 1444
+ 1423 ACC2
+ 1424 GETFIELD0
+ 1425 PUSHACC2
+ 1426 GETFIELD0
+ 1427 PUSHACC2
+ 1428 APPLY2
+ 1429 ACC2
+ 1430 GETFIELD1
+ 1431 PUSHACC2
+ 1432 GETFIELD1
+ 1433 PUSHACC2
+ 1434 PUSHOFFSETCLOSURE0
+ 1435 APPTERM3 6
+ 1437 ACC2
+ 1438 BRANCHIFNOT 1442
+ 1440 BRANCH 1444
+ 1442 RETURN 3
+ 1444 GETGLOBAL "List.iter2"
+ 1446 PUSHGETGLOBALFIELD Pervasives, 2
+ 1449 APPTERM1 4
+ 1451 RESTART
+ 1452 GRAB 3
+ 1454 ACC2
+ 1455 BRANCHIFNOT 1476
+ 1457 ACC3
+ 1458 BRANCHIFNOT 1482
+ 1460 ACC3
+ 1461 GETFIELD1
+ 1462 PUSHACC3
+ 1463 GETFIELD1
+ 1464 PUSHACC5
+ 1465 GETFIELD0
+ 1466 PUSHACC5
+ 1467 GETFIELD0
+ 1468 PUSHACC5
+ 1469 PUSHACC5
+ 1470 APPLY3
+ 1471 PUSHACC3
+ 1472 PUSHOFFSETCLOSURE0
+ 1473 APPTERM 4, 8
+ 1476 ACC3
+ 1477 BRANCHIF 1482
+ 1479 ACC1
+ 1480 RETURN 4
+ 1482 GETGLOBAL "List.fold_left2"
+ 1484 PUSHGETGLOBALFIELD Pervasives, 2
+ 1487 APPTERM1 5
+ 1489 RESTART
+ 1490 GRAB 3
+ 1492 ACC1
+ 1493 BRANCHIFNOT 1516
+ 1495 ACC2
+ 1496 BRANCHIFNOT 1522
+ 1498 PUSH_RETADDR 1509
+ 1500 ACC6
+ 1501 PUSHACC6
+ 1502 GETFIELD1
+ 1503 PUSHACC6
+ 1504 GETFIELD1
+ 1505 PUSHACC6
+ 1506 PUSHOFFSETCLOSURE0
+ 1507 APPLY 4
+ 1509 PUSHACC3
+ 1510 GETFIELD0
+ 1511 PUSHACC3
+ 1512 GETFIELD0
+ 1513 PUSHACC3
+ 1514 APPTERM3 7
+ 1516 ACC2
+ 1517 BRANCHIF 1522
+ 1519 ACC3
+ 1520 RETURN 4
+ 1522 GETGLOBAL "List.fold_right2"
+ 1524 PUSHGETGLOBALFIELD Pervasives, 2
+ 1527 APPTERM1 5
+ 1529 RESTART
+ 1530 GRAB 1
+ 1532 ACC1
+ 1533 BRANCHIFNOT 1549
+ 1535 ACC1
+ 1536 GETFIELD0
+ 1537 PUSHACC1
+ 1538 APPLY1
+ 1539 BRANCHIFNOT 1547
+ 1541 ACC1
+ 1542 GETFIELD1
+ 1543 PUSHACC1
+ 1544 PUSHOFFSETCLOSURE0
+ 1545 APPTERM2 4
+ 1547 RETURN 2
+ 1549 CONST1
+ 1550 RETURN 2
+ 1552 RESTART
+ 1553 GRAB 1
+ 1555 ACC1
+ 1556 BRANCHIFNOT 1570
+ 1558 ACC1
+ 1559 GETFIELD0
+ 1560 PUSHACC1
+ 1561 APPLY1
+ 1562 BRANCHIF 1570
+ 1564 ACC1
+ 1565 GETFIELD1
+ 1566 PUSHACC1
+ 1567 PUSHOFFSETCLOSURE0
+ 1568 APPTERM2 4
+ 1570 RETURN 2
+ 1572 RESTART
+ 1573 GRAB 2
+ 1575 ACC1
+ 1576 BRANCHIFNOT 1599
+ 1578 ACC2
+ 1579 BRANCHIFNOT 1605
+ 1581 ACC2
+ 1582 GETFIELD0
+ 1583 PUSHACC2
+ 1584 GETFIELD0
+ 1585 PUSHACC2
+ 1586 APPLY2
+ 1587 BRANCHIFNOT 1597
+ 1589 ACC2
+ 1590 GETFIELD1
+ 1591 PUSHACC2
+ 1592 GETFIELD1
+ 1593 PUSHACC2
+ 1594 PUSHOFFSETCLOSURE0
+ 1595 APPTERM3 6
+ 1597 RETURN 3
+ 1599 ACC2
+ 1600 BRANCHIF 1605
+ 1602 CONST1
+ 1603 RETURN 3
+ 1605 GETGLOBAL "List.for_all2"
+ 1607 PUSHGETGLOBALFIELD Pervasives, 2
+ 1610 APPTERM1 4
+ 1612 RESTART
+ 1613 GRAB 2
+ 1615 ACC1
+ 1616 BRANCHIFNOT 1639
+ 1618 ACC2
+ 1619 BRANCHIFNOT 1646
+ 1621 ACC2
+ 1622 GETFIELD0
+ 1623 PUSHACC2
+ 1624 GETFIELD0
+ 1625 PUSHACC2
+ 1626 APPLY2
+ 1627 BRANCHIF 1637
+ 1629 ACC2
+ 1630 GETFIELD1
+ 1631 PUSHACC2
+ 1632 GETFIELD1
+ 1633 PUSHACC2
+ 1634 PUSHOFFSETCLOSURE0
+ 1635 APPTERM3 6
+ 1637 RETURN 3
+ 1639 ACC2
+ 1640 BRANCHIFNOT 1644
+ 1642 BRANCH 1646
+ 1644 RETURN 3
+ 1646 GETGLOBAL "List.exists2"
+ 1648 PUSHGETGLOBALFIELD Pervasives, 2
+ 1651 APPTERM1 4
+ 1653 RESTART
+ 1654 GRAB 1
+ 1656 ACC1
+ 1657 BRANCHIFNOT 1672
+ 1659 ACC0
+ 1660 PUSHACC2
+ 1661 GETFIELD0
+ 1662 C_CALL2 equal
+ 1664 BRANCHIF 1672
+ 1666 ACC1
+ 1667 GETFIELD1
+ 1668 PUSHACC1
+ 1669 PUSHOFFSETCLOSURE0
+ 1670 APPTERM2 4
+ 1672 RETURN 2
+ 1674 RESTART
+ 1675 GRAB 1
+ 1677 ACC1
+ 1678 BRANCHIFNOT 1692
+ 1680 ACC0
+ 1681 PUSHACC2
+ 1682 GETFIELD0
+ 1683 EQ
+ 1684 BRANCHIF 1692
+ 1686 ACC1
+ 1687 GETFIELD1
+ 1688 PUSHACC1
+ 1689 PUSHOFFSETCLOSURE0
+ 1690 APPTERM2 4
+ 1692 RETURN 2
+ 1694 RESTART
+ 1695 GRAB 1
+ 1697 ACC1
+ 1698 BRANCHIFNOT 1719
+ 1700 ACC1
+ 1701 GETFIELD0
+ 1702 PUSHACC1
+ 1703 PUSHACC1
+ 1704 GETFIELD0
+ 1705 C_CALL2 equal
+ 1707 BRANCHIFNOT 1713
+ 1709 ACC0
+ 1710 GETFIELD1
+ 1711 RETURN 3
+ 1713 ACC2
+ 1714 GETFIELD1
+ 1715 PUSHACC2
+ 1716 PUSHOFFSETCLOSURE0
+ 1717 APPTERM2 5
+ 1719 GETGLOBAL Not_found
+ 1721 MAKEBLOCK1 0
+ 1723 RAISE
+ 1724 RESTART
+ 1725 GRAB 1
+ 1727 ACC1
+ 1728 BRANCHIFNOT 1748
+ 1730 ACC1
+ 1731 GETFIELD0
+ 1732 PUSHACC1
+ 1733 PUSHACC1
+ 1734 GETFIELD0
+ 1735 EQ
+ 1736 BRANCHIFNOT 1742
+ 1738 ACC0
+ 1739 GETFIELD1
+ 1740 RETURN 3
+ 1742 ACC2
+ 1743 GETFIELD1
+ 1744 PUSHACC2
+ 1745 PUSHOFFSETCLOSURE0
+ 1746 APPTERM2 5
+ 1748 GETGLOBAL Not_found
+ 1750 MAKEBLOCK1 0
+ 1752 RAISE
+ 1753 RESTART
+ 1754 GRAB 1
+ 1756 ACC1
+ 1757 BRANCHIFNOT 1773
+ 1759 ACC0
+ 1760 PUSHACC2
+ 1761 GETFIELD0
+ 1762 GETFIELD0
+ 1763 C_CALL2 equal
+ 1765 BRANCHIF 1773
+ 1767 ACC1
+ 1768 GETFIELD1
+ 1769 PUSHACC1
+ 1770 PUSHOFFSETCLOSURE0
+ 1771 APPTERM2 4
+ 1773 RETURN 2
+ 1775 RESTART
+ 1776 GRAB 1
+ 1778 ACC1
+ 1779 BRANCHIFNOT 1794
+ 1781 ACC0
+ 1782 PUSHACC2
+ 1783 GETFIELD0
+ 1784 GETFIELD0
+ 1785 EQ
+ 1786 BRANCHIF 1794
+ 1788 ACC1
+ 1789 GETFIELD1
+ 1790 PUSHACC1
+ 1791 PUSHOFFSETCLOSURE0
+ 1792 APPTERM2 4
+ 1794 RETURN 2
+ 1796 RESTART
+ 1797 GRAB 1
+ 1799 ACC1
+ 1800 BRANCHIFNOT 1825
+ 1802 ACC1
+ 1803 GETFIELD0
+ 1804 PUSHACC2
+ 1805 GETFIELD1
+ 1806 PUSHACC2
+ 1807 PUSHACC2
+ 1808 GETFIELD0
+ 1809 C_CALL2 equal
+ 1811 BRANCHIFNOT 1816
+ 1813 ACC0
+ 1814 RETURN 4
+ 1816 ACC0
+ 1817 PUSHACC3
+ 1818 PUSHOFFSETCLOSURE0
+ 1819 APPLY2
+ 1820 PUSHACC2
+ 1821 MAKEBLOCK2 0
+ 1823 POP 2
+ 1825 RETURN 2
+ 1827 RESTART
+ 1828 GRAB 1
+ 1830 ACC1
+ 1831 BRANCHIFNOT 1855
+ 1833 ACC1
+ 1834 GETFIELD0
+ 1835 PUSHACC2
+ 1836 GETFIELD1
+ 1837 PUSHACC2
+ 1838 PUSHACC2
+ 1839 GETFIELD0
+ 1840 EQ
+ 1841 BRANCHIFNOT 1846
+ 1843 ACC0
+ 1844 RETURN 4
+ 1846 ACC0
+ 1847 PUSHACC3
+ 1848 PUSHOFFSETCLOSURE0
+ 1849 APPLY2
+ 1850 PUSHACC2
+ 1851 MAKEBLOCK2 0
+ 1853 POP 2
+ 1855 RETURN 2
+ 1857 RESTART
+ 1858 GRAB 1
+ 1860 ACC1
+ 1861 BRANCHIFNOT 1879
+ 1863 ACC1
+ 1864 GETFIELD0
+ 1865 PUSHACC0
+ 1866 PUSHACC2
+ 1867 APPLY1
+ 1868 BRANCHIFNOT 1873
+ 1870 ACC0
+ 1871 RETURN 3
+ 1873 ACC2
+ 1874 GETFIELD1
+ 1875 PUSHACC2
+ 1876 PUSHOFFSETCLOSURE0
+ 1877 APPTERM2 5
+ 1879 GETGLOBAL Not_found
+ 1881 MAKEBLOCK1 0
+ 1883 RAISE
+ 1884 RESTART
+ 1885 GRAB 2
+ 1887 ACC2
+ 1888 BRANCHIFNOT 1917
+ 1890 ACC2
+ 1891 GETFIELD0
+ 1892 PUSHACC3
+ 1893 GETFIELD1
+ 1894 PUSHACC1
+ 1895 PUSHENVACC2
+ 1896 APPLY1
+ 1897 BRANCHIFNOT 1908
+ 1899 ACC0
+ 1900 PUSHACC4
+ 1901 PUSHACC4
+ 1902 PUSHACC4
+ 1903 MAKEBLOCK2 0
+ 1905 PUSHOFFSETCLOSURE0
+ 1906 APPTERM3 8
+ 1908 ACC0
+ 1909 PUSHACC4
+ 1910 PUSHACC3
+ 1911 MAKEBLOCK2 0
+ 1913 PUSHACC4
+ 1914 PUSHOFFSETCLOSURE0
+ 1915 APPTERM3 8
+ 1917 ACC1
+ 1918 PUSHENVACC1
+ 1919 APPLY1
+ 1920 PUSHACC1
+ 1921 PUSHENVACC1
+ 1922 APPLY1
+ 1923 MAKEBLOCK2 0
+ 1925 RETURN 3
+ 1927 RESTART
+ 1928 GRAB 1
+ 1930 ACC0
+ 1931 PUSHENVACC1
+ 1932 CLOSUREREC 2, 1885
+ 1936 ACC2
+ 1937 PUSHCONST0
+ 1938 PUSHCONST0
+ 1939 PUSHACC3
+ 1940 APPTERM3 6
+ 1942 ACC0
+ 1943 BRANCHIFNOT 1967
+ 1945 ACC0
+ 1946 GETFIELD0
+ 1947 PUSHACC1
+ 1948 GETFIELD1
+ 1949 PUSHOFFSETCLOSURE0
+ 1950 APPLY1
+ 1951 PUSHACC0
+ 1952 GETFIELD1
+ 1953 PUSHACC2
+ 1954 GETFIELD1
+ 1955 MAKEBLOCK2 0
+ 1957 PUSHACC1
+ 1958 GETFIELD0
+ 1959 PUSHACC3
+ 1960 GETFIELD0
+ 1961 MAKEBLOCK2 0
+ 1963 MAKEBLOCK2 0
+ 1965 RETURN 3
+ 1967 GETGLOBAL <0>(0, 0)
+ 1969 RETURN 1
+ 1971 RESTART
+ 1972 GRAB 1
+ 1974 ACC0
+ 1975 BRANCHIFNOT 1996
+ 1977 ACC1
+ 1978 BRANCHIFNOT 2003
+ 1980 ACC1
+ 1981 GETFIELD1
+ 1982 PUSHACC1
+ 1983 GETFIELD1
+ 1984 PUSHOFFSETCLOSURE0
+ 1985 APPLY2
+ 1986 PUSHACC2
+ 1987 GETFIELD0
+ 1988 PUSHACC2
+ 1989 GETFIELD0
+ 1990 MAKEBLOCK2 0
+ 1992 MAKEBLOCK2 0
+ 1994 RETURN 2
+ 1996 ACC1
+ 1997 BRANCHIFNOT 2001
+ 1999 BRANCH 2003
+ 2001 RETURN 2
+ 2003 GETGLOBAL "List.combine"
+ 2005 PUSHGETGLOBALFIELD Pervasives, 2
+ 2008 APPTERM1 3
+ 2010 RESTART
+ 2011 GRAB 1
+ 2013 ACC1
+ 2014 BRANCHIFNOT 2038
+ 2016 ACC1
+ 2017 GETFIELD0
+ 2018 PUSHACC2
+ 2019 GETFIELD1
+ 2020 PUSHACC1
+ 2021 PUSHENVACC2
+ 2022 APPLY1
+ 2023 BRANCHIFNOT 2033
+ 2025 ACC0
+ 2026 PUSHACC3
+ 2027 PUSHACC3
+ 2028 MAKEBLOCK2 0
+ 2030 PUSHOFFSETCLOSURE0
+ 2031 APPTERM2 6
+ 2033 ACC0
+ 2034 PUSHACC3
+ 2035 PUSHOFFSETCLOSURE0
+ 2036 APPTERM2 6
+ 2038 ACC0
+ 2039 PUSHENVACC1
+ 2040 APPTERM1 3
+ 2042 ACC0
+ 2043 PUSHENVACC1
+ 2044 CLOSUREREC 2, 2011
+ 2048 CONST0
+ 2049 PUSHACC1
+ 2050 APPTERM1 3
+ 2052 RESTART
+ 2053 GRAB 2
+ 2055 ACC1
+ 2056 BRANCHIFNOT 2077
+ 2058 ACC2
+ 2059 BRANCHIFNOT 2084
+ 2061 ACC2
+ 2062 GETFIELD1
+ 2063 PUSHACC2
+ 2064 GETFIELD1
+ 2065 PUSHACC2
+ 2066 PUSHACC5
+ 2067 GETFIELD0
+ 2068 PUSHACC5
+ 2069 GETFIELD0
+ 2070 PUSHENVACC1
+ 2071 APPLY2
+ 2072 MAKEBLOCK2 0
+ 2074 PUSHOFFSETCLOSURE0
+ 2075 APPTERM3 6
+ 2077 ACC2
+ 2078 BRANCHIFNOT 2082
+ 2080 BRANCH 2084
+ 2082 RETURN 3
+ 2084 GETGLOBAL "List.rev_map2"
+ 2086 PUSHGETGLOBALFIELD Pervasives, 2
+ 2089 APPTERM1 4
+ 2091 RESTART
+ 2092 GRAB 2
+ 2094 ACC0
+ 2095 CLOSUREREC 1, 2053
+ 2099 ACC3
+ 2100 PUSHACC3
+ 2101 PUSHCONST0
+ 2102 PUSHACC3
+ 2103 APPTERM3 7
+ 2105 RESTART
+ 2106 GRAB 1
+ 2108 ACC1
+ 2109 BRANCHIFNOT 2123
+ 2111 ACC1
+ 2112 GETFIELD1
+ 2113 PUSHACC1
+ 2114 PUSHACC3
+ 2115 GETFIELD0
+ 2116 PUSHENVACC1
+ 2117 APPLY1
+ 2118 MAKEBLOCK2 0
+ 2120 PUSHOFFSETCLOSURE0
+ 2121 APPTERM2 4
+ 2123 ACC0
+ 2124 RETURN 2
+ 2126 RESTART
+ 2127 GRAB 1
+ 2129 ACC0
+ 2130 CLOSUREREC 1, 2106
+ 2134 ACC2
+ 2135 PUSHCONST0
+ 2136 PUSHACC2
+ 2137 APPTERM2 5
+ 2139 CONST0
+ 2140 PUSHACC1
+ 2141 PUSHENVACC1
+ 2142 APPTERM2 3
+ 2144 ACC0
+ 2145 BRANCHIFNOT 2151
+ 2147 ACC0
+ 2148 GETFIELD1
+ 2149 RETURN 1
+ 2151 GETGLOBAL "tl"
+ 2153 PUSHGETGLOBALFIELD Pervasives, 3
+ 2156 APPTERM1 2
+ 2158 ACC0
+ 2159 BRANCHIFNOT 2165
+ 2161 ACC0
+ 2162 GETFIELD0
+ 2163 RETURN 1
+ 2165 GETGLOBAL "hd"
+ 2167 PUSHGETGLOBALFIELD Pervasives, 3
+ 2170 APPTERM1 2
+ 2172 ACC0
+ 2173 PUSHCONST0
+ 2174 PUSHENVACC1
+ 2175 APPTERM2 3
+ 2177 CLOSUREREC 0, 1200
+ 2181 ACC0
+ 2182 CLOSURE 1, 2172
+ 2185 PUSH
+ 2186 CLOSURE 0, 2158
+ 2189 PUSH
+ 2190 CLOSURE 0, 2144
+ 2193 PUSH
+ 2194 CLOSUREREC 0, 1217
+ 2198 GETGLOBALFIELD Pervasives, 16
+ 2201 PUSH
+ 2202 CLOSUREREC 0, 1259
+ 2206 ACC0
+ 2207 CLOSURE 1, 2139
+ 2210 PUSH
+ 2211 CLOSUREREC 0, 1277
+ 2215 CLOSUREREC 0, 1294
+ 2219 CLOSURE 0, 2127
+ 2222 PUSH
+ 2223 CLOSUREREC 0, 1316
+ 2227 CLOSUREREC 0, 1334
+ 2231 CLOSUREREC 0, 1354
+ 2235 CLOSUREREC 0, 1374
+ 2239 CLOSURE 0, 2092
+ 2242 PUSH
+ 2243 CLOSUREREC 0, 1415
+ 2247 CLOSUREREC 0, 1452
+ 2251 CLOSUREREC 0, 1490
+ 2255 CLOSUREREC 0, 1530
+ 2259 CLOSUREREC 0, 1553
+ 2263 CLOSUREREC 0, 1573
+ 2267 CLOSUREREC 0, 1613
+ 2271 CLOSUREREC 0, 1654
+ 2275 CLOSUREREC 0, 1675
+ 2279 CLOSUREREC 0, 1695
+ 2283 CLOSUREREC 0, 1725
+ 2287 CLOSUREREC 0, 1754
+ 2291 CLOSUREREC 0, 1776
+ 2295 CLOSUREREC 0, 1797
+ 2299 CLOSUREREC 0, 1828
+ 2303 CLOSUREREC 0, 1858
+ 2307 ACC 24
+ 2309 CLOSURE 1, 2042
+ 2312 PUSHACC 25
+ 2314 CLOSUREREC 1, 1928
+ 2318 CLOSUREREC 0, 1942
+ 2322 CLOSUREREC 0, 1972
+ 2326 ACC0
+ 2327 PUSHACC2
+ 2328 PUSHACC7
+ 2329 PUSHACC 9
+ 2331 PUSHACC 11
+ 2333 PUSHACC 13
+ 2335 PUSHACC 15
+ 2337 PUSHACC 17
+ 2339 PUSHACC 10
+ 2341 PUSHACC 12
+ 2343 PUSHACC 13
+ 2345 PUSHACC 15
+ 2347 PUSHACC 23
+ 2349 PUSHACC 25
+ 2351 PUSHACC 27
+ 2353 PUSHACC 29
+ 2355 PUSHACC 31
+ 2357 PUSHACC 33
+ 2359 PUSHACC 35
+ 2361 PUSHACC 37
+ 2363 PUSHACC 40
+ 2365 PUSHACC 42
+ 2367 PUSHACC 41
+ 2369 PUSHACC 45
+ 2371 PUSHACC 47
+ 2373 PUSHACC 50
+ 2375 PUSHACC 52
+ 2377 PUSHACC 51
+ 2379 PUSHACC 55
+ 2381 PUSHACC 56
+ 2383 PUSHACC 59
+ 2385 PUSHACC 61
+ 2387 PUSHACC 60
+ 2389 PUSHACC 64
+ 2391 PUSHACC 66
+ 2393 PUSHACC 68
+ 2395 PUSHACC 70
+ 2397 MAKEBLOCK 37, 0
+ 2400 POP 36
+ 2402 SETGLOBAL List
+ 2404 BRANCH 3341
+ 2406 RESTART
+ 2407 GRAB 2
+ 2409 ACC2
+ 2410 PUSHACC2
+ 2411 VECTLENGTH
+ 2412 OFFSETINT -1
+ 2414 PUSHCONST0
+ 2415 PUSH
+ 2416 BRANCH 2433
+ 2418 CHECK_SIGNALS
+ 2419 ACC2
+ 2420 PUSHACC2
+ 2421 PUSHACC6
+ 2422 C_CALL2 array_unsafe_get
+ 2424 PUSHACC5
+ 2425 APPLY2
+ 2426 ASSIGN 2
+ 2428 ACC1
+ 2429 OFFSETINT -1
+ 2431 ASSIGN 1
+ 2433 ACC0
+ 2434 PUSHACC2
+ 2435 GEINT
+ 2436 BRANCHIF 2418
+ 2438 CONST0
+ 2439 POP 2
+ 2441 ACC0
+ 2442 RETURN 4
+ 2444 RESTART
+ 2445 GRAB 2
+ 2447 ACC1
+ 2448 PUSHCONST0
+ 2449 PUSHACC4
+ 2450 VECTLENGTH
+ 2451 OFFSETINT -1
+ 2453 PUSH
+ 2454 BRANCH 2471
+ 2456 CHECK_SIGNALS
+ 2457 ACC1
+ 2458 PUSHACC6
+ 2459 C_CALL2 array_unsafe_get
+ 2461 PUSHACC3
+ 2462 PUSHACC5
+ 2463 APPLY2
+ 2464 ASSIGN 2
+ 2466 ACC1
+ 2467 OFFSETINT 1
+ 2469 ASSIGN 1
+ 2471 ACC0
+ 2472 PUSHACC2
+ 2473 LEINT
+ 2474 BRANCHIF 2456
+ 2476 CONST0
+ 2477 POP 2
+ 2479 ACC0
+ 2480 RETURN 4
+ 2482 RESTART
+ 2483 GRAB 1
+ 2485 ACC1
+ 2486 BRANCHIFNOT 2502
+ 2488 ACC1
+ 2489 GETFIELD0
+ 2490 PUSHACC1
+ 2491 PUSHENVACC1
+ 2492 C_CALL3 array_unsafe_set
+ 2494 ACC1
+ 2495 GETFIELD1
+ 2496 PUSHACC1
+ 2497 OFFSETINT 1
+ 2499 PUSHOFFSETCLOSURE0
+ 2500 APPTERM2 4
+ 2502 ENVACC1
+ 2503 RETURN 2
+ 2505 ACC0
+ 2506 BRANCHIFNOT 2531
+ 2508 ACC0
+ 2509 GETFIELD1
+ 2510 PUSHACC1
+ 2511 GETFIELD0
+ 2512 PUSHACC1
+ 2513 PUSHGETGLOBALFIELD List, 0
+ 2516 APPLY1
+ 2517 OFFSETINT 1
+ 2519 C_CALL2 make_vect
+ 2521 PUSHACC0
+ 2522 CLOSUREREC 1, 2483
+ 2526 ACC2
+ 2527 PUSHCONST1
+ 2528 PUSHACC2
+ 2529 APPTERM2 6
+ 2531 ATOM0
+ 2532 RETURN 1
+ 2534 RESTART
+ 2535 GRAB 1
+ 2537 CONST0
+ 2538 PUSHACC1
+ 2539 LTINT
+ 2540 BRANCHIFNOT 2545
+ 2542 ACC1
+ 2543 RETURN 2
+ 2545 ACC1
+ 2546 PUSHACC1
+ 2547 PUSHENVACC1
+ 2548 C_CALL2 array_unsafe_get
+ 2550 MAKEBLOCK2 0
+ 2552 PUSHACC1
+ 2553 OFFSETINT -1
+ 2555 PUSHOFFSETCLOSURE0
+ 2556 APPTERM2 4
+ 2558 ACC0
+ 2559 CLOSUREREC 1, 2535
+ 2563 CONST0
+ 2564 PUSHACC2
+ 2565 VECTLENGTH
+ 2566 OFFSETINT -1
+ 2568 PUSHACC2
+ 2569 APPTERM2 4
+ 2571 RESTART
+ 2572 GRAB 1
+ 2574 ACC1
+ 2575 VECTLENGTH
+ 2576 PUSHCONST0
+ 2577 PUSHACC1
+ 2578 EQ
+ 2579 BRANCHIFNOT 2584
+ 2581 ATOM0
+ 2582 RETURN 3
+ 2584 CONST0
+ 2585 PUSHACC3
+ 2586 C_CALL2 array_unsafe_get
+ 2588 PUSHCONST0
+ 2589 PUSHACC3
+ 2590 APPLY2
+ 2591 PUSHACC1
+ 2592 C_CALL2 make_vect
+ 2594 PUSHCONST1
+ 2595 PUSHACC2
+ 2596 OFFSETINT -1
+ 2598 PUSH
+ 2599 BRANCH 2618
+ 2601 CHECK_SIGNALS
+ 2602 ACC1
+ 2603 PUSHACC6
+ 2604 C_CALL2 array_unsafe_get
+ 2606 PUSHACC2
+ 2607 PUSHACC6
+ 2608 APPLY2
+ 2609 PUSHACC2
+ 2610 PUSHACC4
+ 2611 C_CALL3 array_unsafe_set
+ 2613 ACC1
+ 2614 OFFSETINT 1
+ 2616 ASSIGN 1
+ 2618 ACC0
+ 2619 PUSHACC2
+ 2620 LEINT
+ 2621 BRANCHIF 2601
+ 2623 CONST0
+ 2624 POP 2
+ 2626 ACC0
+ 2627 RETURN 4
+ 2629 RESTART
+ 2630 GRAB 1
+ 2632 CONST0
+ 2633 PUSHACC2
+ 2634 VECTLENGTH
+ 2635 OFFSETINT -1
+ 2637 PUSH
+ 2638 BRANCH 2653
+ 2640 CHECK_SIGNALS
+ 2641 ACC1
+ 2642 PUSHACC4
+ 2643 C_CALL2 array_unsafe_get
+ 2645 PUSHACC2
+ 2646 PUSHACC4
+ 2647 APPLY2
+ 2648 ACC1
+ 2649 OFFSETINT 1
+ 2651 ASSIGN 1
+ 2653 ACC0
+ 2654 PUSHACC2
+ 2655 LEINT
+ 2656 BRANCHIF 2640
+ 2658 CONST0
+ 2659 RETURN 4
+ 2661 RESTART
+ 2662 GRAB 1
+ 2664 ACC1
+ 2665 VECTLENGTH
+ 2666 PUSHCONST0
+ 2667 PUSHACC1
+ 2668 EQ
+ 2669 BRANCHIFNOT 2674
+ 2671 ATOM0
+ 2672 RETURN 3
+ 2674 CONST0
+ 2675 PUSHACC3
+ 2676 C_CALL2 array_unsafe_get
+ 2678 PUSHACC2
+ 2679 APPLY1
+ 2680 PUSHACC1
+ 2681 C_CALL2 make_vect
+ 2683 PUSHCONST1
+ 2684 PUSHACC2
+ 2685 OFFSETINT -1
+ 2687 PUSH
+ 2688 BRANCH 2706
+ 2690 CHECK_SIGNALS
+ 2691 ACC1
+ 2692 PUSHACC6
+ 2693 C_CALL2 array_unsafe_get
+ 2695 PUSHACC5
+ 2696 APPLY1
+ 2697 PUSHACC2
+ 2698 PUSHACC4
+ 2699 C_CALL3 array_unsafe_set
+ 2701 ACC1
+ 2702 OFFSETINT 1
+ 2704 ASSIGN 1
+ 2706 ACC0
+ 2707 PUSHACC2
+ 2708 LEINT
+ 2709 BRANCHIF 2690
+ 2711 CONST0
+ 2712 POP 2
+ 2714 ACC0
+ 2715 RETURN 4
+ 2717 RESTART
+ 2718 GRAB 1
+ 2720 CONST0
+ 2721 PUSHACC2
+ 2722 VECTLENGTH
+ 2723 OFFSETINT -1
+ 2725 PUSH
+ 2726 BRANCH 2740
+ 2728 CHECK_SIGNALS
+ 2729 ACC1
+ 2730 PUSHACC4
+ 2731 C_CALL2 array_unsafe_get
+ 2733 PUSHACC3
+ 2734 APPLY1
+ 2735 ACC1
+ 2736 OFFSETINT 1
+ 2738 ASSIGN 1
+ 2740 ACC0
+ 2741 PUSHACC2
+ 2742 LEINT
+ 2743 BRANCHIF 2728
+ 2745 CONST0
+ 2746 RETURN 4
+ 2748 RESTART
+ 2749 GRAB 4
+ 2751 CONST0
+ 2752 PUSHACC5
+ 2753 LTINT
+ 2754 BRANCHIF 2782
+ 2756 CONST0
+ 2757 PUSHACC2
+ 2758 LTINT
+ 2759 BRANCHIF 2782
+ 2761 ACC0
+ 2762 VECTLENGTH
+ 2763 PUSHACC5
+ 2764 PUSHACC3
+ 2765 ADDINT
+ 2766 GTINT
+ 2767 BRANCHIF 2782
+ 2769 CONST0
+ 2770 PUSHACC4
+ 2771 LTINT
+ 2772 BRANCHIF 2782
+ 2774 ACC2
+ 2775 VECTLENGTH
+ 2776 PUSHACC5
+ 2777 PUSHACC5
+ 2778 ADDINT
+ 2779 GTINT
+ 2780 BRANCHIFNOT 2789
+ 2782 GETGLOBAL "Array.blit"
+ 2784 PUSHGETGLOBALFIELD Pervasives, 2
+ 2787 APPTERM1 6
+ 2789 ACC3
+ 2790 PUSHACC2
+ 2791 LTINT
+ 2792 BRANCHIFNOT 2827
+ 2794 ACC4
+ 2795 OFFSETINT -1
+ 2797 PUSHCONST0
+ 2798 PUSH
+ 2799 BRANCH 2819
+ 2801 CHECK_SIGNALS
+ 2802 ACC1
+ 2803 PUSHACC4
+ 2804 ADDINT
+ 2805 PUSHACC3
+ 2806 C_CALL2 array_unsafe_get
+ 2808 PUSHACC2
+ 2809 PUSHACC7
+ 2810 ADDINT
+ 2811 PUSHACC6
+ 2812 C_CALL3 array_unsafe_set
+ 2814 ACC1
+ 2815 OFFSETINT -1
+ 2817 ASSIGN 1
+ 2819 ACC0
+ 2820 PUSHACC2
+ 2821 GEINT
+ 2822 BRANCHIF 2801
+ 2824 CONST0
+ 2825 RETURN 7
+ 2827 CONST0
+ 2828 PUSHACC5
+ 2829 OFFSETINT -1
+ 2831 PUSH
+ 2832 BRANCH 2852
+ 2834 CHECK_SIGNALS
+ 2835 ACC1
+ 2836 PUSHACC4
+ 2837 ADDINT
+ 2838 PUSHACC3
+ 2839 C_CALL2 array_unsafe_get
+ 2841 PUSHACC2
+ 2842 PUSHACC7
+ 2843 ADDINT
+ 2844 PUSHACC6
+ 2845 C_CALL3 array_unsafe_set
+ 2847 ACC1
+ 2848 OFFSETINT 1
+ 2850 ASSIGN 1
+ 2852 ACC0
+ 2853 PUSHACC2
+ 2854 LEINT
+ 2855 BRANCHIF 2834
+ 2857 CONST0
+ 2858 RETURN 7
+ 2860 RESTART
+ 2861 GRAB 3
+ 2863 CONST0
+ 2864 PUSHACC2
+ 2865 LTINT
+ 2866 BRANCHIF 2881
+ 2868 CONST0
+ 2869 PUSHACC3
+ 2870 LTINT
+ 2871 BRANCHIF 2881
+ 2873 ACC0
+ 2874 VECTLENGTH
+ 2875 PUSHACC3
+ 2876 PUSHACC3
+ 2877 ADDINT
+ 2878 GTINT
+ 2879 BRANCHIFNOT 2888
+ 2881 GETGLOBAL "Array.fill"
+ 2883 PUSHGETGLOBALFIELD Pervasives, 2
+ 2886 APPTERM1 5
+ 2888 ACC1
+ 2889 PUSHACC3
+ 2890 PUSHACC3
+ 2891 ADDINT
+ 2892 OFFSETINT -1
+ 2894 PUSH
+ 2895 BRANCH 2908
+ 2897 CHECK_SIGNALS
+ 2898 ACC5
+ 2899 PUSHACC2
+ 2900 PUSHACC4
+ 2901 C_CALL3 array_unsafe_set
+ 2903 ACC1
+ 2904 OFFSETINT 1
+ 2906 ASSIGN 1
+ 2908 ACC0
+ 2909 PUSHACC2
+ 2910 LEINT
+ 2911 BRANCHIF 2897
+ 2913 CONST0
+ 2914 RETURN 6
+ 2916 RESTART
+ 2917 GRAB 2
+ 2919 CONST0
+ 2920 PUSHACC2
+ 2921 LTINT
+ 2922 BRANCHIF 2937
+ 2924 CONST0
+ 2925 PUSHACC3
+ 2926 LTINT
+ 2927 BRANCHIF 2937
+ 2929 ACC0
+ 2930 VECTLENGTH
+ 2931 PUSHACC3
+ 2932 PUSHACC3
+ 2933 ADDINT
+ 2934 GTINT
+ 2935 BRANCHIFNOT 2944
+ 2937 GETGLOBAL "Array.sub"
+ 2939 PUSHGETGLOBALFIELD Pervasives, 2
+ 2942 APPTERM1 4
+ 2944 CONST0
+ 2945 PUSHACC3
+ 2946 EQ
+ 2947 BRANCHIFNOT 2952
+ 2949 ATOM0
+ 2950 RETURN 3
+ 2952 ACC1
+ 2953 PUSHACC1
+ 2954 C_CALL2 array_unsafe_get
+ 2956 PUSHACC3
+ 2957 C_CALL2 make_vect
+ 2959 PUSHCONST1
+ 2960 PUSHACC4
+ 2961 OFFSETINT -1
+ 2963 PUSH
+ 2964 BRANCH 2982
+ 2966 CHECK_SIGNALS
+ 2967 ACC1
+ 2968 PUSHACC5
+ 2969 ADDINT
+ 2970 PUSHACC4
+ 2971 C_CALL2 array_unsafe_get
+ 2973 PUSHACC2
+ 2974 PUSHACC4
+ 2975 C_CALL3 array_unsafe_set
+ 2977 ACC1
+ 2978 OFFSETINT 1
+ 2980 ASSIGN 1
+ 2982 ACC0
+ 2983 PUSHACC2
+ 2984 LEINT
+ 2985 BRANCHIF 2966
+ 2987 CONST0
+ 2988 POP 2
+ 2990 ACC0
+ 2991 RETURN 4
+ 2993 ACC0
+ 2994 BRANCHIFNOT 3017
+ 2996 ACC0
+ 2997 GETFIELD0
+ 2998 PUSHCONST0
+ 2999 PUSHACC1
+ 3000 VECTLENGTH
+ 3001 GTINT
+ 3002 BRANCHIFNOT 3012
+ 3004 ENVACC2
+ 3005 PUSHCONST0
+ 3006 PUSHACC2
+ 3007 C_CALL2 array_unsafe_get
+ 3009 PUSHENVACC1
+ 3010 APPTERM2 4
+ 3012 ACC1
+ 3013 GETFIELD1
+ 3014 PUSHOFFSETCLOSURE0
+ 3015 APPTERM1 3
+ 3017 ATOM0
+ 3018 RETURN 1
+ 3020 ACC0
+ 3021 PUSHENVACC1
+ 3022 CLOSUREREC 2, 2993
+ 3026 ACC1
+ 3027 PUSHACC1
+ 3028 APPTERM1 3
+ 3030 CONST0
+ 3031 PUSHACC1
+ 3032 VECTLENGTH
+ 3033 OFFSETINT -1
+ 3035 PUSH
+ 3036 BRANCH 3056
+ 3038 CHECK_SIGNALS
+ 3039 ACC1
+ 3040 PUSHACC3
+ 3041 C_CALL2 array_unsafe_get
+ 3043 PUSHENVACC2
+ 3044 GETFIELD0
+ 3045 PUSHENVACC1
+ 3046 C_CALL3 array_unsafe_set
+ 3048 ENVACC2
+ 3049 OFFSETREF 1
+ 3051 ACC1
+ 3052 OFFSETINT 1
+ 3054 ASSIGN 1
+ 3056 ACC0
+ 3057 PUSHACC2
+ 3058 LEINT
+ 3059 BRANCHIF 3038
+ 3061 CONST0
+ 3062 RETURN 3
+ 3064 RESTART
+ 3065 GRAB 1
+ 3067 ACC1
+ 3068 VECTLENGTH
+ 3069 PUSHACC1
+ 3070 ADDINT
+ 3071 RETURN 2
+ 3073 RESTART
+ 3074 GRAB 1
+ 3076 ACC1
+ 3077 PUSHCONST0
+ 3078 PUSH
+ 3079 CLOSURE 0, 3065
+ 3082 PUSHGETGLOBALFIELD List, 12
+ 3085 APPLY3
+ 3086 PUSHACC1
+ 3087 PUSHACC1
+ 3088 C_CALL2 make_vect
+ 3090 PUSHCONST0
+ 3091 MAKEBLOCK1 0
+ 3093 PUSHACC4
+ 3094 PUSHACC1
+ 3095 PUSHACC3
+ 3096 CLOSURE 2, 3030
+ 3099 PUSHGETGLOBALFIELD List, 9
+ 3102 APPLY2
+ 3103 ACC1
+ 3104 RETURN 5
+ 3106 RESTART
+ 3107 GRAB 1
+ 3109 ACC0
+ 3110 VECTLENGTH
+ 3111 PUSHACC2
+ 3112 VECTLENGTH
+ 3113 PUSHCONST0
+ 3114 PUSHACC2
+ 3115 EQ
+ 3116 BRANCHIFNOT 3126
+ 3118 CONST0
+ 3119 PUSHACC1
+ 3120 EQ
+ 3121 BRANCHIFNOT 3126
+ 3123 ATOM0
+ 3124 RETURN 4
+ 3126 CONST0
+ 3127 PUSHCONST0
+ 3128 PUSHACC3
+ 3129 GTINT
+ 3130 BRANCHIFNOT 3135
+ 3132 ACC3
+ 3133 BRANCH 3136
+ 3135 ACC4
+ 3136 C_CALL2 array_unsafe_get
+ 3138 PUSHACC1
+ 3139 PUSHACC3
+ 3140 ADDINT
+ 3141 C_CALL2 make_vect
+ 3143 PUSHCONST0
+ 3144 PUSHACC3
+ 3145 OFFSETINT -1
+ 3147 PUSH
+ 3148 BRANCH 3164
+ 3150 CHECK_SIGNALS
+ 3151 ACC1
+ 3152 PUSHACC6
+ 3153 C_CALL2 array_unsafe_get
+ 3155 PUSHACC2
+ 3156 PUSHACC4
+ 3157 C_CALL3 array_unsafe_set
+ 3159 ACC1
+ 3160 OFFSETINT 1
+ 3162 ASSIGN 1
+ 3164 ACC0
+ 3165 PUSHACC2
+ 3166 LEINT
+ 3167 BRANCHIF 3150
+ 3169 CONST0
+ 3170 POP 2
+ 3172 CONST0
+ 3173 PUSHACC2
+ 3174 OFFSETINT -1
+ 3176 PUSH
+ 3177 BRANCH 3195
+ 3179 CHECK_SIGNALS
+ 3180 ACC1
+ 3181 PUSHACC7
+ 3182 C_CALL2 array_unsafe_get
+ 3184 PUSHACC5
+ 3185 PUSHACC3
+ 3186 ADDINT
+ 3187 PUSHACC4
+ 3188 C_CALL3 array_unsafe_set
+ 3190 ACC1
+ 3191 OFFSETINT 1
+ 3193 ASSIGN 1
+ 3195 ACC0
+ 3196 PUSHACC2
+ 3197 LEINT
+ 3198 BRANCHIF 3179
+ 3200 CONST0
+ 3201 POP 2
+ 3203 ACC0
+ 3204 RETURN 5
+ 3206 ACC0
+ 3207 VECTLENGTH
+ 3208 PUSHCONST0
+ 3209 PUSHACC1
+ 3210 EQ
+ 3211 BRANCHIFNOT 3216
+ 3213 ATOM0
+ 3214 RETURN 2
+ 3216 CONST0
+ 3217 PUSHACC2
+ 3218 C_CALL2 array_unsafe_get
+ 3220 PUSHACC1
+ 3221 C_CALL2 make_vect
+ 3223 PUSHCONST1
+ 3224 PUSHACC2
+ 3225 OFFSETINT -1
+ 3227 PUSH
+ 3228 BRANCH 3244
+ 3230 CHECK_SIGNALS
+ 3231 ACC1
+ 3232 PUSHACC5
+ 3233 C_CALL2 array_unsafe_get
+ 3235 PUSHACC2
+ 3236 PUSHACC4
+ 3237 C_CALL3 array_unsafe_set
+ 3239 ACC1
+ 3240 OFFSETINT 1
+ 3242 ASSIGN 1
+ 3244 ACC0
+ 3245 PUSHACC2
+ 3246 LEINT
+ 3247 BRANCHIF 3230
+ 3249 CONST0
+ 3250 POP 2
+ 3252 ACC0
+ 3253 RETURN 3
+ 3255 RESTART
+ 3256 GRAB 2
+ 3258 ATOM0
+ 3259 PUSHACC1
+ 3260 C_CALL2 make_vect
+ 3262 PUSHCONST0
+ 3263 PUSHACC2
+ 3264 OFFSETINT -1
+ 3266 PUSH
+ 3267 BRANCH 3282
+ 3269 CHECK_SIGNALS
+ 3270 ACC5
+ 3271 PUSHACC5
+ 3272 C_CALL2 make_vect
+ 3274 PUSHACC2
+ 3275 PUSHACC4
+ 3276 SETVECTITEM
+ 3277 ACC1
+ 3278 OFFSETINT 1
+ 3280 ASSIGN 1
+ 3282 ACC0
+ 3283 PUSHACC2
+ 3284 LEINT
+ 3285 BRANCHIF 3269
+ 3287 CONST0
+ 3288 POP 2
+ 3290 ACC0
+ 3291 RETURN 4
+ 3293 RESTART
+ 3294 GRAB 1
+ 3296 CONST0
+ 3297 PUSHACC1
+ 3298 EQ
+ 3299 BRANCHIFNOT 3304
+ 3301 ATOM0
+ 3302 RETURN 2
+ 3304 CONST0
+ 3305 PUSHACC2
+ 3306 APPLY1
+ 3307 PUSHACC1
+ 3308 C_CALL2 make_vect
+ 3310 PUSHCONST1
+ 3311 PUSHACC2
+ 3312 OFFSETINT -1
+ 3314 PUSH
+ 3315 BRANCH 3330
+ 3317 CHECK_SIGNALS
+ 3318 ACC1
+ 3319 PUSHACC5
+ 3320 APPLY1
+ 3321 PUSHACC2
+ 3322 PUSHACC4
+ 3323 C_CALL3 array_unsafe_set
+ 3325 ACC1
+ 3326 OFFSETINT 1
+ 3328 ASSIGN 1
+ 3330 ACC0
+ 3331 PUSHACC2
+ 3332 LEINT
+ 3333 BRANCHIF 3317
+ 3335 CONST0
+ 3336 POP 2
+ 3338 ACC0
+ 3339 RETURN 3
+ 3341 CLOSURE 0, 3294
+ 3344 PUSH
+ 3345 CLOSURE 0, 3256
+ 3348 PUSH
+ 3349 CLOSURE 0, 3206
+ 3352 PUSH
+ 3353 CLOSURE 0, 3107
+ 3356 PUSH
+ 3357 CLOSURE 0, 3074
+ 3360 PUSHACC0
+ 3361 CLOSURE 1, 3020
+ 3364 PUSH
+ 3365 CLOSURE 0, 2917
+ 3368 PUSH
+ 3369 CLOSURE 0, 2861
+ 3372 PUSH
+ 3373 CLOSURE 0, 2749
+ 3376 PUSH
+ 3377 CLOSURE 0, 2718
+ 3380 PUSH
+ 3381 CLOSURE 0, 2662
+ 3384 PUSH
+ 3385 CLOSURE 0, 2630
+ 3388 PUSH
+ 3389 CLOSURE 0, 2572
+ 3392 PUSH
+ 3393 CLOSURE 0, 2558
+ 3396 PUSH
+ 3397 CLOSURE 0, 2505
+ 3400 PUSH
+ 3401 CLOSURE 0, 2445
+ 3404 PUSH
+ 3405 CLOSURE 0, 2407
+ 3408 PUSHACC0
+ 3409 PUSHACC2
+ 3410 PUSHACC6
+ 3411 PUSHACC 8
+ 3413 PUSHACC 10
+ 3415 PUSHACC 12
+ 3417 PUSHACC 8
+ 3419 PUSHACC 10
+ 3421 PUSHACC 16
+ 3423 PUSHACC 18
+ 3425 PUSHACC 24
+ 3427 PUSHACC 21
+ 3429 PUSHACC 23
+ 3431 PUSHACC 26
+ 3433 PUSHACC 29
+ 3435 PUSHACC 30
+ 3437 PUSHACC 32
+ 3439 MAKEBLOCK 17, 0
+ 3442 POP 17
+ 3444 SETGLOBAL Array
+ 3446 BRANCH 3456
+ 3448 ACC0
+ 3449 PUSHENVACC1
+ 3450 GETFIELD0
+ 3451 ADDINT
+ 3452 PUSHENVACC1
+ 3453 SETFIELD0
+ 3454 RETURN 1
+ 3456 CONST2
+ 3457 PUSHCONSTINT 200000
+ 3459 C_CALL2 make_vect
+ 3461 PUSHCONST0
+ 3462 MAKEBLOCK1 0
+ 3464 PUSHACC1
+ 3465 PUSHACC1
+ 3466 CLOSURE 1, 3448
+ 3469 PUSHGETGLOBALFIELD Array, 11
+ 3472 APPLY2
+ 3473 CONSTINT 400000
+ 3475 PUSHACC1
+ 3476 GETFIELD0
+ 3477 NEQ
+ 3478 BRANCHIFNOT 3485
+ 3480 GETGLOBAL Not_found
+ 3482 MAKEBLOCK1 0
+ 3484 RAISE
+ 3485 POP 2
+ 3487 ATOM0
+ 3488 SETGLOBAL T310-alloc-2
+ 3490 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t320-gc-1.ml b/testsuite/tests/tool-ocaml/t320-gc-1.ml
new file mode 100644
index 0000000000..4d5d6d966d
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t320-gc-1.ml
@@ -0,0 +1,1589 @@
+open Lib;;
+let rec f n =
+ if n <= 0 then []
+ else n :: f (n-1)
+in
+let l = f 300 in
+Gc.minor ();
+if List.fold_left (+) 0 l <> 301 * 150 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 BRANCH 2177
+ 1199 RESTART
+ 1200 GRAB 1
+ 1202 ACC1
+ 1203 BRANCHIFNOT 1213
+ 1205 ACC1
+ 1206 GETFIELD1
+ 1207 PUSHACC1
+ 1208 OFFSETINT 1
+ 1210 PUSHOFFSETCLOSURE0
+ 1211 APPTERM2 4
+ 1213 ACC0
+ 1214 RETURN 2
+ 1216 RESTART
+ 1217 GRAB 1
+ 1219 ACC0
+ 1220 BRANCHIFNOT 1251
+ 1222 CONST0
+ 1223 PUSHACC2
+ 1224 EQ
+ 1225 BRANCHIFNOT 1231
+ 1227 ACC0
+ 1228 GETFIELD0
+ 1229 RETURN 2
+ 1231 CONST0
+ 1232 PUSHACC2
+ 1233 GTINT
+ 1234 BRANCHIFNOT 1244
+ 1236 ACC1
+ 1237 OFFSETINT -1
+ 1239 PUSHACC1
+ 1240 GETFIELD1
+ 1241 PUSHOFFSETCLOSURE0
+ 1242 APPTERM2 4
+ 1244 GETGLOBAL "List.nth"
+ 1246 PUSHGETGLOBALFIELD Pervasives, 2
+ 1249 APPTERM1 3
+ 1251 GETGLOBAL "nth"
+ 1253 PUSHGETGLOBALFIELD Pervasives, 3
+ 1256 APPTERM1 3
+ 1258 RESTART
+ 1259 GRAB 1
+ 1261 ACC0
+ 1262 BRANCHIFNOT 1274
+ 1264 ACC1
+ 1265 PUSHACC1
+ 1266 GETFIELD0
+ 1267 MAKEBLOCK2 0
+ 1269 PUSHACC1
+ 1270 GETFIELD1
+ 1271 PUSHOFFSETCLOSURE0
+ 1272 APPTERM2 4
+ 1274 ACC1
+ 1275 RETURN 2
+ 1277 ACC0
+ 1278 BRANCHIFNOT 1291
+ 1280 ACC0
+ 1281 GETFIELD1
+ 1282 PUSHOFFSETCLOSURE0
+ 1283 APPLY1
+ 1284 PUSHACC1
+ 1285 GETFIELD0
+ 1286 PUSHGETGLOBALFIELD Pervasives, 16
+ 1289 APPTERM2 3
+ 1291 RETURN 1
+ 1293 RESTART
+ 1294 GRAB 1
+ 1296 ACC1
+ 1297 BRANCHIFNOT 1313
+ 1299 ACC1
+ 1300 GETFIELD0
+ 1301 PUSHACC1
+ 1302 APPLY1
+ 1303 PUSHACC2
+ 1304 GETFIELD1
+ 1305 PUSHACC2
+ 1306 PUSHOFFSETCLOSURE0
+ 1307 APPLY2
+ 1308 PUSHACC1
+ 1309 MAKEBLOCK2 0
+ 1311 POP 1
+ 1313 RETURN 2
+ 1315 RESTART
+ 1316 GRAB 1
+ 1318 ACC1
+ 1319 BRANCHIFNOT 1331
+ 1321 ACC1
+ 1322 GETFIELD0
+ 1323 PUSHACC1
+ 1324 APPLY1
+ 1325 ACC1
+ 1326 GETFIELD1
+ 1327 PUSHACC1
+ 1328 PUSHOFFSETCLOSURE0
+ 1329 APPTERM2 4
+ 1331 RETURN 2
+ 1333 RESTART
+ 1334 GRAB 2
+ 1336 ACC2
+ 1337 BRANCHIFNOT 1350
+ 1339 ACC2
+ 1340 GETFIELD1
+ 1341 PUSHACC3
+ 1342 GETFIELD0
+ 1343 PUSHACC3
+ 1344 PUSHACC3
+ 1345 APPLY2
+ 1346 PUSHACC2
+ 1347 PUSHOFFSETCLOSURE0
+ 1348 APPTERM3 6
+ 1350 ACC1
+ 1351 RETURN 3
+ 1353 RESTART
+ 1354 GRAB 2
+ 1356 ACC1
+ 1357 BRANCHIFNOT 1370
+ 1359 ACC2
+ 1360 PUSHACC2
+ 1361 GETFIELD1
+ 1362 PUSHACC2
+ 1363 PUSHOFFSETCLOSURE0
+ 1364 APPLY3
+ 1365 PUSHACC2
+ 1366 GETFIELD0
+ 1367 PUSHACC2
+ 1368 APPTERM2 5
+ 1370 ACC2
+ 1371 RETURN 3
+ 1373 RESTART
+ 1374 GRAB 2
+ 1376 ACC1
+ 1377 BRANCHIFNOT 1400
+ 1379 ACC2
+ 1380 BRANCHIFNOT 1407
+ 1382 ACC2
+ 1383 GETFIELD0
+ 1384 PUSHACC2
+ 1385 GETFIELD0
+ 1386 PUSHACC2
+ 1387 APPLY2
+ 1388 PUSHACC3
+ 1389 GETFIELD1
+ 1390 PUSHACC3
+ 1391 GETFIELD1
+ 1392 PUSHACC3
+ 1393 PUSHOFFSETCLOSURE0
+ 1394 APPLY3
+ 1395 PUSHACC1
+ 1396 MAKEBLOCK2 0
+ 1398 RETURN 4
+ 1400 ACC2
+ 1401 BRANCHIFNOT 1405
+ 1403 BRANCH 1407
+ 1405 RETURN 3
+ 1407 GETGLOBAL "List.map2"
+ 1409 PUSHGETGLOBALFIELD Pervasives, 2
+ 1412 APPTERM1 4
+ 1414 RESTART
+ 1415 GRAB 2
+ 1417 ACC1
+ 1418 BRANCHIFNOT 1437
+ 1420 ACC2
+ 1421 BRANCHIFNOT 1444
+ 1423 ACC2
+ 1424 GETFIELD0
+ 1425 PUSHACC2
+ 1426 GETFIELD0
+ 1427 PUSHACC2
+ 1428 APPLY2
+ 1429 ACC2
+ 1430 GETFIELD1
+ 1431 PUSHACC2
+ 1432 GETFIELD1
+ 1433 PUSHACC2
+ 1434 PUSHOFFSETCLOSURE0
+ 1435 APPTERM3 6
+ 1437 ACC2
+ 1438 BRANCHIFNOT 1442
+ 1440 BRANCH 1444
+ 1442 RETURN 3
+ 1444 GETGLOBAL "List.iter2"
+ 1446 PUSHGETGLOBALFIELD Pervasives, 2
+ 1449 APPTERM1 4
+ 1451 RESTART
+ 1452 GRAB 3
+ 1454 ACC2
+ 1455 BRANCHIFNOT 1476
+ 1457 ACC3
+ 1458 BRANCHIFNOT 1482
+ 1460 ACC3
+ 1461 GETFIELD1
+ 1462 PUSHACC3
+ 1463 GETFIELD1
+ 1464 PUSHACC5
+ 1465 GETFIELD0
+ 1466 PUSHACC5
+ 1467 GETFIELD0
+ 1468 PUSHACC5
+ 1469 PUSHACC5
+ 1470 APPLY3
+ 1471 PUSHACC3
+ 1472 PUSHOFFSETCLOSURE0
+ 1473 APPTERM 4, 8
+ 1476 ACC3
+ 1477 BRANCHIF 1482
+ 1479 ACC1
+ 1480 RETURN 4
+ 1482 GETGLOBAL "List.fold_left2"
+ 1484 PUSHGETGLOBALFIELD Pervasives, 2
+ 1487 APPTERM1 5
+ 1489 RESTART
+ 1490 GRAB 3
+ 1492 ACC1
+ 1493 BRANCHIFNOT 1516
+ 1495 ACC2
+ 1496 BRANCHIFNOT 1522
+ 1498 PUSH_RETADDR 1509
+ 1500 ACC6
+ 1501 PUSHACC6
+ 1502 GETFIELD1
+ 1503 PUSHACC6
+ 1504 GETFIELD1
+ 1505 PUSHACC6
+ 1506 PUSHOFFSETCLOSURE0
+ 1507 APPLY 4
+ 1509 PUSHACC3
+ 1510 GETFIELD0
+ 1511 PUSHACC3
+ 1512 GETFIELD0
+ 1513 PUSHACC3
+ 1514 APPTERM3 7
+ 1516 ACC2
+ 1517 BRANCHIF 1522
+ 1519 ACC3
+ 1520 RETURN 4
+ 1522 GETGLOBAL "List.fold_right2"
+ 1524 PUSHGETGLOBALFIELD Pervasives, 2
+ 1527 APPTERM1 5
+ 1529 RESTART
+ 1530 GRAB 1
+ 1532 ACC1
+ 1533 BRANCHIFNOT 1549
+ 1535 ACC1
+ 1536 GETFIELD0
+ 1537 PUSHACC1
+ 1538 APPLY1
+ 1539 BRANCHIFNOT 1547
+ 1541 ACC1
+ 1542 GETFIELD1
+ 1543 PUSHACC1
+ 1544 PUSHOFFSETCLOSURE0
+ 1545 APPTERM2 4
+ 1547 RETURN 2
+ 1549 CONST1
+ 1550 RETURN 2
+ 1552 RESTART
+ 1553 GRAB 1
+ 1555 ACC1
+ 1556 BRANCHIFNOT 1570
+ 1558 ACC1
+ 1559 GETFIELD0
+ 1560 PUSHACC1
+ 1561 APPLY1
+ 1562 BRANCHIF 1570
+ 1564 ACC1
+ 1565 GETFIELD1
+ 1566 PUSHACC1
+ 1567 PUSHOFFSETCLOSURE0
+ 1568 APPTERM2 4
+ 1570 RETURN 2
+ 1572 RESTART
+ 1573 GRAB 2
+ 1575 ACC1
+ 1576 BRANCHIFNOT 1599
+ 1578 ACC2
+ 1579 BRANCHIFNOT 1605
+ 1581 ACC2
+ 1582 GETFIELD0
+ 1583 PUSHACC2
+ 1584 GETFIELD0
+ 1585 PUSHACC2
+ 1586 APPLY2
+ 1587 BRANCHIFNOT 1597
+ 1589 ACC2
+ 1590 GETFIELD1
+ 1591 PUSHACC2
+ 1592 GETFIELD1
+ 1593 PUSHACC2
+ 1594 PUSHOFFSETCLOSURE0
+ 1595 APPTERM3 6
+ 1597 RETURN 3
+ 1599 ACC2
+ 1600 BRANCHIF 1605
+ 1602 CONST1
+ 1603 RETURN 3
+ 1605 GETGLOBAL "List.for_all2"
+ 1607 PUSHGETGLOBALFIELD Pervasives, 2
+ 1610 APPTERM1 4
+ 1612 RESTART
+ 1613 GRAB 2
+ 1615 ACC1
+ 1616 BRANCHIFNOT 1639
+ 1618 ACC2
+ 1619 BRANCHIFNOT 1646
+ 1621 ACC2
+ 1622 GETFIELD0
+ 1623 PUSHACC2
+ 1624 GETFIELD0
+ 1625 PUSHACC2
+ 1626 APPLY2
+ 1627 BRANCHIF 1637
+ 1629 ACC2
+ 1630 GETFIELD1
+ 1631 PUSHACC2
+ 1632 GETFIELD1
+ 1633 PUSHACC2
+ 1634 PUSHOFFSETCLOSURE0
+ 1635 APPTERM3 6
+ 1637 RETURN 3
+ 1639 ACC2
+ 1640 BRANCHIFNOT 1644
+ 1642 BRANCH 1646
+ 1644 RETURN 3
+ 1646 GETGLOBAL "List.exists2"
+ 1648 PUSHGETGLOBALFIELD Pervasives, 2
+ 1651 APPTERM1 4
+ 1653 RESTART
+ 1654 GRAB 1
+ 1656 ACC1
+ 1657 BRANCHIFNOT 1672
+ 1659 ACC0
+ 1660 PUSHACC2
+ 1661 GETFIELD0
+ 1662 C_CALL2 equal
+ 1664 BRANCHIF 1672
+ 1666 ACC1
+ 1667 GETFIELD1
+ 1668 PUSHACC1
+ 1669 PUSHOFFSETCLOSURE0
+ 1670 APPTERM2 4
+ 1672 RETURN 2
+ 1674 RESTART
+ 1675 GRAB 1
+ 1677 ACC1
+ 1678 BRANCHIFNOT 1692
+ 1680 ACC0
+ 1681 PUSHACC2
+ 1682 GETFIELD0
+ 1683 EQ
+ 1684 BRANCHIF 1692
+ 1686 ACC1
+ 1687 GETFIELD1
+ 1688 PUSHACC1
+ 1689 PUSHOFFSETCLOSURE0
+ 1690 APPTERM2 4
+ 1692 RETURN 2
+ 1694 RESTART
+ 1695 GRAB 1
+ 1697 ACC1
+ 1698 BRANCHIFNOT 1719
+ 1700 ACC1
+ 1701 GETFIELD0
+ 1702 PUSHACC1
+ 1703 PUSHACC1
+ 1704 GETFIELD0
+ 1705 C_CALL2 equal
+ 1707 BRANCHIFNOT 1713
+ 1709 ACC0
+ 1710 GETFIELD1
+ 1711 RETURN 3
+ 1713 ACC2
+ 1714 GETFIELD1
+ 1715 PUSHACC2
+ 1716 PUSHOFFSETCLOSURE0
+ 1717 APPTERM2 5
+ 1719 GETGLOBAL Not_found
+ 1721 MAKEBLOCK1 0
+ 1723 RAISE
+ 1724 RESTART
+ 1725 GRAB 1
+ 1727 ACC1
+ 1728 BRANCHIFNOT 1748
+ 1730 ACC1
+ 1731 GETFIELD0
+ 1732 PUSHACC1
+ 1733 PUSHACC1
+ 1734 GETFIELD0
+ 1735 EQ
+ 1736 BRANCHIFNOT 1742
+ 1738 ACC0
+ 1739 GETFIELD1
+ 1740 RETURN 3
+ 1742 ACC2
+ 1743 GETFIELD1
+ 1744 PUSHACC2
+ 1745 PUSHOFFSETCLOSURE0
+ 1746 APPTERM2 5
+ 1748 GETGLOBAL Not_found
+ 1750 MAKEBLOCK1 0
+ 1752 RAISE
+ 1753 RESTART
+ 1754 GRAB 1
+ 1756 ACC1
+ 1757 BRANCHIFNOT 1773
+ 1759 ACC0
+ 1760 PUSHACC2
+ 1761 GETFIELD0
+ 1762 GETFIELD0
+ 1763 C_CALL2 equal
+ 1765 BRANCHIF 1773
+ 1767 ACC1
+ 1768 GETFIELD1
+ 1769 PUSHACC1
+ 1770 PUSHOFFSETCLOSURE0
+ 1771 APPTERM2 4
+ 1773 RETURN 2
+ 1775 RESTART
+ 1776 GRAB 1
+ 1778 ACC1
+ 1779 BRANCHIFNOT 1794
+ 1781 ACC0
+ 1782 PUSHACC2
+ 1783 GETFIELD0
+ 1784 GETFIELD0
+ 1785 EQ
+ 1786 BRANCHIF 1794
+ 1788 ACC1
+ 1789 GETFIELD1
+ 1790 PUSHACC1
+ 1791 PUSHOFFSETCLOSURE0
+ 1792 APPTERM2 4
+ 1794 RETURN 2
+ 1796 RESTART
+ 1797 GRAB 1
+ 1799 ACC1
+ 1800 BRANCHIFNOT 1825
+ 1802 ACC1
+ 1803 GETFIELD0
+ 1804 PUSHACC2
+ 1805 GETFIELD1
+ 1806 PUSHACC2
+ 1807 PUSHACC2
+ 1808 GETFIELD0
+ 1809 C_CALL2 equal
+ 1811 BRANCHIFNOT 1816
+ 1813 ACC0
+ 1814 RETURN 4
+ 1816 ACC0
+ 1817 PUSHACC3
+ 1818 PUSHOFFSETCLOSURE0
+ 1819 APPLY2
+ 1820 PUSHACC2
+ 1821 MAKEBLOCK2 0
+ 1823 POP 2
+ 1825 RETURN 2
+ 1827 RESTART
+ 1828 GRAB 1
+ 1830 ACC1
+ 1831 BRANCHIFNOT 1855
+ 1833 ACC1
+ 1834 GETFIELD0
+ 1835 PUSHACC2
+ 1836 GETFIELD1
+ 1837 PUSHACC2
+ 1838 PUSHACC2
+ 1839 GETFIELD0
+ 1840 EQ
+ 1841 BRANCHIFNOT 1846
+ 1843 ACC0
+ 1844 RETURN 4
+ 1846 ACC0
+ 1847 PUSHACC3
+ 1848 PUSHOFFSETCLOSURE0
+ 1849 APPLY2
+ 1850 PUSHACC2
+ 1851 MAKEBLOCK2 0
+ 1853 POP 2
+ 1855 RETURN 2
+ 1857 RESTART
+ 1858 GRAB 1
+ 1860 ACC1
+ 1861 BRANCHIFNOT 1879
+ 1863 ACC1
+ 1864 GETFIELD0
+ 1865 PUSHACC0
+ 1866 PUSHACC2
+ 1867 APPLY1
+ 1868 BRANCHIFNOT 1873
+ 1870 ACC0
+ 1871 RETURN 3
+ 1873 ACC2
+ 1874 GETFIELD1
+ 1875 PUSHACC2
+ 1876 PUSHOFFSETCLOSURE0
+ 1877 APPTERM2 5
+ 1879 GETGLOBAL Not_found
+ 1881 MAKEBLOCK1 0
+ 1883 RAISE
+ 1884 RESTART
+ 1885 GRAB 2
+ 1887 ACC2
+ 1888 BRANCHIFNOT 1917
+ 1890 ACC2
+ 1891 GETFIELD0
+ 1892 PUSHACC3
+ 1893 GETFIELD1
+ 1894 PUSHACC1
+ 1895 PUSHENVACC2
+ 1896 APPLY1
+ 1897 BRANCHIFNOT 1908
+ 1899 ACC0
+ 1900 PUSHACC4
+ 1901 PUSHACC4
+ 1902 PUSHACC4
+ 1903 MAKEBLOCK2 0
+ 1905 PUSHOFFSETCLOSURE0
+ 1906 APPTERM3 8
+ 1908 ACC0
+ 1909 PUSHACC4
+ 1910 PUSHACC3
+ 1911 MAKEBLOCK2 0
+ 1913 PUSHACC4
+ 1914 PUSHOFFSETCLOSURE0
+ 1915 APPTERM3 8
+ 1917 ACC1
+ 1918 PUSHENVACC1
+ 1919 APPLY1
+ 1920 PUSHACC1
+ 1921 PUSHENVACC1
+ 1922 APPLY1
+ 1923 MAKEBLOCK2 0
+ 1925 RETURN 3
+ 1927 RESTART
+ 1928 GRAB 1
+ 1930 ACC0
+ 1931 PUSHENVACC1
+ 1932 CLOSUREREC 2, 1885
+ 1936 ACC2
+ 1937 PUSHCONST0
+ 1938 PUSHCONST0
+ 1939 PUSHACC3
+ 1940 APPTERM3 6
+ 1942 ACC0
+ 1943 BRANCHIFNOT 1967
+ 1945 ACC0
+ 1946 GETFIELD0
+ 1947 PUSHACC1
+ 1948 GETFIELD1
+ 1949 PUSHOFFSETCLOSURE0
+ 1950 APPLY1
+ 1951 PUSHACC0
+ 1952 GETFIELD1
+ 1953 PUSHACC2
+ 1954 GETFIELD1
+ 1955 MAKEBLOCK2 0
+ 1957 PUSHACC1
+ 1958 GETFIELD0
+ 1959 PUSHACC3
+ 1960 GETFIELD0
+ 1961 MAKEBLOCK2 0
+ 1963 MAKEBLOCK2 0
+ 1965 RETURN 3
+ 1967 GETGLOBAL <0>(0, 0)
+ 1969 RETURN 1
+ 1971 RESTART
+ 1972 GRAB 1
+ 1974 ACC0
+ 1975 BRANCHIFNOT 1996
+ 1977 ACC1
+ 1978 BRANCHIFNOT 2003
+ 1980 ACC1
+ 1981 GETFIELD1
+ 1982 PUSHACC1
+ 1983 GETFIELD1
+ 1984 PUSHOFFSETCLOSURE0
+ 1985 APPLY2
+ 1986 PUSHACC2
+ 1987 GETFIELD0
+ 1988 PUSHACC2
+ 1989 GETFIELD0
+ 1990 MAKEBLOCK2 0
+ 1992 MAKEBLOCK2 0
+ 1994 RETURN 2
+ 1996 ACC1
+ 1997 BRANCHIFNOT 2001
+ 1999 BRANCH 2003
+ 2001 RETURN 2
+ 2003 GETGLOBAL "List.combine"
+ 2005 PUSHGETGLOBALFIELD Pervasives, 2
+ 2008 APPTERM1 3
+ 2010 RESTART
+ 2011 GRAB 1
+ 2013 ACC1
+ 2014 BRANCHIFNOT 2038
+ 2016 ACC1
+ 2017 GETFIELD0
+ 2018 PUSHACC2
+ 2019 GETFIELD1
+ 2020 PUSHACC1
+ 2021 PUSHENVACC2
+ 2022 APPLY1
+ 2023 BRANCHIFNOT 2033
+ 2025 ACC0
+ 2026 PUSHACC3
+ 2027 PUSHACC3
+ 2028 MAKEBLOCK2 0
+ 2030 PUSHOFFSETCLOSURE0
+ 2031 APPTERM2 6
+ 2033 ACC0
+ 2034 PUSHACC3
+ 2035 PUSHOFFSETCLOSURE0
+ 2036 APPTERM2 6
+ 2038 ACC0
+ 2039 PUSHENVACC1
+ 2040 APPTERM1 3
+ 2042 ACC0
+ 2043 PUSHENVACC1
+ 2044 CLOSUREREC 2, 2011
+ 2048 CONST0
+ 2049 PUSHACC1
+ 2050 APPTERM1 3
+ 2052 RESTART
+ 2053 GRAB 2
+ 2055 ACC1
+ 2056 BRANCHIFNOT 2077
+ 2058 ACC2
+ 2059 BRANCHIFNOT 2084
+ 2061 ACC2
+ 2062 GETFIELD1
+ 2063 PUSHACC2
+ 2064 GETFIELD1
+ 2065 PUSHACC2
+ 2066 PUSHACC5
+ 2067 GETFIELD0
+ 2068 PUSHACC5
+ 2069 GETFIELD0
+ 2070 PUSHENVACC1
+ 2071 APPLY2
+ 2072 MAKEBLOCK2 0
+ 2074 PUSHOFFSETCLOSURE0
+ 2075 APPTERM3 6
+ 2077 ACC2
+ 2078 BRANCHIFNOT 2082
+ 2080 BRANCH 2084
+ 2082 RETURN 3
+ 2084 GETGLOBAL "List.rev_map2"
+ 2086 PUSHGETGLOBALFIELD Pervasives, 2
+ 2089 APPTERM1 4
+ 2091 RESTART
+ 2092 GRAB 2
+ 2094 ACC0
+ 2095 CLOSUREREC 1, 2053
+ 2099 ACC3
+ 2100 PUSHACC3
+ 2101 PUSHCONST0
+ 2102 PUSHACC3
+ 2103 APPTERM3 7
+ 2105 RESTART
+ 2106 GRAB 1
+ 2108 ACC1
+ 2109 BRANCHIFNOT 2123
+ 2111 ACC1
+ 2112 GETFIELD1
+ 2113 PUSHACC1
+ 2114 PUSHACC3
+ 2115 GETFIELD0
+ 2116 PUSHENVACC1
+ 2117 APPLY1
+ 2118 MAKEBLOCK2 0
+ 2120 PUSHOFFSETCLOSURE0
+ 2121 APPTERM2 4
+ 2123 ACC0
+ 2124 RETURN 2
+ 2126 RESTART
+ 2127 GRAB 1
+ 2129 ACC0
+ 2130 CLOSUREREC 1, 2106
+ 2134 ACC2
+ 2135 PUSHCONST0
+ 2136 PUSHACC2
+ 2137 APPTERM2 5
+ 2139 CONST0
+ 2140 PUSHACC1
+ 2141 PUSHENVACC1
+ 2142 APPTERM2 3
+ 2144 ACC0
+ 2145 BRANCHIFNOT 2151
+ 2147 ACC0
+ 2148 GETFIELD1
+ 2149 RETURN 1
+ 2151 GETGLOBAL "tl"
+ 2153 PUSHGETGLOBALFIELD Pervasives, 3
+ 2156 APPTERM1 2
+ 2158 ACC0
+ 2159 BRANCHIFNOT 2165
+ 2161 ACC0
+ 2162 GETFIELD0
+ 2163 RETURN 1
+ 2165 GETGLOBAL "hd"
+ 2167 PUSHGETGLOBALFIELD Pervasives, 3
+ 2170 APPTERM1 2
+ 2172 ACC0
+ 2173 PUSHCONST0
+ 2174 PUSHENVACC1
+ 2175 APPTERM2 3
+ 2177 CLOSUREREC 0, 1200
+ 2181 ACC0
+ 2182 CLOSURE 1, 2172
+ 2185 PUSH
+ 2186 CLOSURE 0, 2158
+ 2189 PUSH
+ 2190 CLOSURE 0, 2144
+ 2193 PUSH
+ 2194 CLOSUREREC 0, 1217
+ 2198 GETGLOBALFIELD Pervasives, 16
+ 2201 PUSH
+ 2202 CLOSUREREC 0, 1259
+ 2206 ACC0
+ 2207 CLOSURE 1, 2139
+ 2210 PUSH
+ 2211 CLOSUREREC 0, 1277
+ 2215 CLOSUREREC 0, 1294
+ 2219 CLOSURE 0, 2127
+ 2222 PUSH
+ 2223 CLOSUREREC 0, 1316
+ 2227 CLOSUREREC 0, 1334
+ 2231 CLOSUREREC 0, 1354
+ 2235 CLOSUREREC 0, 1374
+ 2239 CLOSURE 0, 2092
+ 2242 PUSH
+ 2243 CLOSUREREC 0, 1415
+ 2247 CLOSUREREC 0, 1452
+ 2251 CLOSUREREC 0, 1490
+ 2255 CLOSUREREC 0, 1530
+ 2259 CLOSUREREC 0, 1553
+ 2263 CLOSUREREC 0, 1573
+ 2267 CLOSUREREC 0, 1613
+ 2271 CLOSUREREC 0, 1654
+ 2275 CLOSUREREC 0, 1675
+ 2279 CLOSUREREC 0, 1695
+ 2283 CLOSUREREC 0, 1725
+ 2287 CLOSUREREC 0, 1754
+ 2291 CLOSUREREC 0, 1776
+ 2295 CLOSUREREC 0, 1797
+ 2299 CLOSUREREC 0, 1828
+ 2303 CLOSUREREC 0, 1858
+ 2307 ACC 24
+ 2309 CLOSURE 1, 2042
+ 2312 PUSHACC 25
+ 2314 CLOSUREREC 1, 1928
+ 2318 CLOSUREREC 0, 1942
+ 2322 CLOSUREREC 0, 1972
+ 2326 ACC0
+ 2327 PUSHACC2
+ 2328 PUSHACC7
+ 2329 PUSHACC 9
+ 2331 PUSHACC 11
+ 2333 PUSHACC 13
+ 2335 PUSHACC 15
+ 2337 PUSHACC 17
+ 2339 PUSHACC 10
+ 2341 PUSHACC 12
+ 2343 PUSHACC 13
+ 2345 PUSHACC 15
+ 2347 PUSHACC 23
+ 2349 PUSHACC 25
+ 2351 PUSHACC 27
+ 2353 PUSHACC 29
+ 2355 PUSHACC 31
+ 2357 PUSHACC 33
+ 2359 PUSHACC 35
+ 2361 PUSHACC 37
+ 2363 PUSHACC 40
+ 2365 PUSHACC 42
+ 2367 PUSHACC 41
+ 2369 PUSHACC 45
+ 2371 PUSHACC 47
+ 2373 PUSHACC 50
+ 2375 PUSHACC 52
+ 2377 PUSHACC 51
+ 2379 PUSHACC 55
+ 2381 PUSHACC 56
+ 2383 PUSHACC 59
+ 2385 PUSHACC 61
+ 2387 PUSHACC 60
+ 2389 PUSHACC 64
+ 2391 PUSHACC 66
+ 2393 PUSHACC 68
+ 2395 PUSHACC 70
+ 2397 MAKEBLOCK 37, 0
+ 2400 POP 36
+ 2402 SETGLOBAL List
+ 2404 BRANCH 2432
+ 2406 CONST0
+ 2407 PUSHACC1
+ 2408 LEINT
+ 2409 BRANCHIFNOT 2414
+ 2411 CONST0
+ 2412 RETURN 1
+ 2414 ACC0
+ 2415 OFFSETINT -1
+ 2417 PUSHOFFSETCLOSURE0
+ 2418 APPLY1
+ 2419 PUSHACC1
+ 2420 MAKEBLOCK2 0
+ 2422 RETURN 1
+ 2424 RESTART
+ 2425 GRAB 1
+ 2427 ACC1
+ 2428 PUSHACC1
+ 2429 ADDINT
+ 2430 RETURN 2
+ 2432 CLOSUREREC 0, 2406
+ 2436 CONSTINT 300
+ 2438 PUSHACC1
+ 2439 APPLY1
+ 2440 PUSHCONST0
+ 2441 C_CALL1 gc_minor
+ 2443 CONSTINT 150
+ 2445 PUSHCONSTINT 301
+ 2447 MULINT
+ 2448 PUSHACC1
+ 2449 PUSHCONST0
+ 2450 PUSH
+ 2451 CLOSURE 0, 2425
+ 2454 PUSHGETGLOBALFIELD List, 12
+ 2457 APPLY3
+ 2458 NEQ
+ 2459 BRANCHIFNOT 2466
+ 2461 GETGLOBAL Not_found
+ 2463 MAKEBLOCK1 0
+ 2465 RAISE
+ 2466 POP 2
+ 2468 ATOM0
+ 2469 SETGLOBAL T320-gc-1
+ 2471 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t320-gc-2.ml b/testsuite/tests/tool-ocaml/t320-gc-2.ml
new file mode 100644
index 0000000000..f607f65125
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t320-gc-2.ml
@@ -0,0 +1,1589 @@
+open Lib;;
+let rec f n =
+ if n <= 0 then []
+ else n :: f (n-1)
+in
+let l = f 300 in
+Gc.major ();
+if List.fold_left (+) 0 l <> 301 * 150 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 BRANCH 2177
+ 1199 RESTART
+ 1200 GRAB 1
+ 1202 ACC1
+ 1203 BRANCHIFNOT 1213
+ 1205 ACC1
+ 1206 GETFIELD1
+ 1207 PUSHACC1
+ 1208 OFFSETINT 1
+ 1210 PUSHOFFSETCLOSURE0
+ 1211 APPTERM2 4
+ 1213 ACC0
+ 1214 RETURN 2
+ 1216 RESTART
+ 1217 GRAB 1
+ 1219 ACC0
+ 1220 BRANCHIFNOT 1251
+ 1222 CONST0
+ 1223 PUSHACC2
+ 1224 EQ
+ 1225 BRANCHIFNOT 1231
+ 1227 ACC0
+ 1228 GETFIELD0
+ 1229 RETURN 2
+ 1231 CONST0
+ 1232 PUSHACC2
+ 1233 GTINT
+ 1234 BRANCHIFNOT 1244
+ 1236 ACC1
+ 1237 OFFSETINT -1
+ 1239 PUSHACC1
+ 1240 GETFIELD1
+ 1241 PUSHOFFSETCLOSURE0
+ 1242 APPTERM2 4
+ 1244 GETGLOBAL "List.nth"
+ 1246 PUSHGETGLOBALFIELD Pervasives, 2
+ 1249 APPTERM1 3
+ 1251 GETGLOBAL "nth"
+ 1253 PUSHGETGLOBALFIELD Pervasives, 3
+ 1256 APPTERM1 3
+ 1258 RESTART
+ 1259 GRAB 1
+ 1261 ACC0
+ 1262 BRANCHIFNOT 1274
+ 1264 ACC1
+ 1265 PUSHACC1
+ 1266 GETFIELD0
+ 1267 MAKEBLOCK2 0
+ 1269 PUSHACC1
+ 1270 GETFIELD1
+ 1271 PUSHOFFSETCLOSURE0
+ 1272 APPTERM2 4
+ 1274 ACC1
+ 1275 RETURN 2
+ 1277 ACC0
+ 1278 BRANCHIFNOT 1291
+ 1280 ACC0
+ 1281 GETFIELD1
+ 1282 PUSHOFFSETCLOSURE0
+ 1283 APPLY1
+ 1284 PUSHACC1
+ 1285 GETFIELD0
+ 1286 PUSHGETGLOBALFIELD Pervasives, 16
+ 1289 APPTERM2 3
+ 1291 RETURN 1
+ 1293 RESTART
+ 1294 GRAB 1
+ 1296 ACC1
+ 1297 BRANCHIFNOT 1313
+ 1299 ACC1
+ 1300 GETFIELD0
+ 1301 PUSHACC1
+ 1302 APPLY1
+ 1303 PUSHACC2
+ 1304 GETFIELD1
+ 1305 PUSHACC2
+ 1306 PUSHOFFSETCLOSURE0
+ 1307 APPLY2
+ 1308 PUSHACC1
+ 1309 MAKEBLOCK2 0
+ 1311 POP 1
+ 1313 RETURN 2
+ 1315 RESTART
+ 1316 GRAB 1
+ 1318 ACC1
+ 1319 BRANCHIFNOT 1331
+ 1321 ACC1
+ 1322 GETFIELD0
+ 1323 PUSHACC1
+ 1324 APPLY1
+ 1325 ACC1
+ 1326 GETFIELD1
+ 1327 PUSHACC1
+ 1328 PUSHOFFSETCLOSURE0
+ 1329 APPTERM2 4
+ 1331 RETURN 2
+ 1333 RESTART
+ 1334 GRAB 2
+ 1336 ACC2
+ 1337 BRANCHIFNOT 1350
+ 1339 ACC2
+ 1340 GETFIELD1
+ 1341 PUSHACC3
+ 1342 GETFIELD0
+ 1343 PUSHACC3
+ 1344 PUSHACC3
+ 1345 APPLY2
+ 1346 PUSHACC2
+ 1347 PUSHOFFSETCLOSURE0
+ 1348 APPTERM3 6
+ 1350 ACC1
+ 1351 RETURN 3
+ 1353 RESTART
+ 1354 GRAB 2
+ 1356 ACC1
+ 1357 BRANCHIFNOT 1370
+ 1359 ACC2
+ 1360 PUSHACC2
+ 1361 GETFIELD1
+ 1362 PUSHACC2
+ 1363 PUSHOFFSETCLOSURE0
+ 1364 APPLY3
+ 1365 PUSHACC2
+ 1366 GETFIELD0
+ 1367 PUSHACC2
+ 1368 APPTERM2 5
+ 1370 ACC2
+ 1371 RETURN 3
+ 1373 RESTART
+ 1374 GRAB 2
+ 1376 ACC1
+ 1377 BRANCHIFNOT 1400
+ 1379 ACC2
+ 1380 BRANCHIFNOT 1407
+ 1382 ACC2
+ 1383 GETFIELD0
+ 1384 PUSHACC2
+ 1385 GETFIELD0
+ 1386 PUSHACC2
+ 1387 APPLY2
+ 1388 PUSHACC3
+ 1389 GETFIELD1
+ 1390 PUSHACC3
+ 1391 GETFIELD1
+ 1392 PUSHACC3
+ 1393 PUSHOFFSETCLOSURE0
+ 1394 APPLY3
+ 1395 PUSHACC1
+ 1396 MAKEBLOCK2 0
+ 1398 RETURN 4
+ 1400 ACC2
+ 1401 BRANCHIFNOT 1405
+ 1403 BRANCH 1407
+ 1405 RETURN 3
+ 1407 GETGLOBAL "List.map2"
+ 1409 PUSHGETGLOBALFIELD Pervasives, 2
+ 1412 APPTERM1 4
+ 1414 RESTART
+ 1415 GRAB 2
+ 1417 ACC1
+ 1418 BRANCHIFNOT 1437
+ 1420 ACC2
+ 1421 BRANCHIFNOT 1444
+ 1423 ACC2
+ 1424 GETFIELD0
+ 1425 PUSHACC2
+ 1426 GETFIELD0
+ 1427 PUSHACC2
+ 1428 APPLY2
+ 1429 ACC2
+ 1430 GETFIELD1
+ 1431 PUSHACC2
+ 1432 GETFIELD1
+ 1433 PUSHACC2
+ 1434 PUSHOFFSETCLOSURE0
+ 1435 APPTERM3 6
+ 1437 ACC2
+ 1438 BRANCHIFNOT 1442
+ 1440 BRANCH 1444
+ 1442 RETURN 3
+ 1444 GETGLOBAL "List.iter2"
+ 1446 PUSHGETGLOBALFIELD Pervasives, 2
+ 1449 APPTERM1 4
+ 1451 RESTART
+ 1452 GRAB 3
+ 1454 ACC2
+ 1455 BRANCHIFNOT 1476
+ 1457 ACC3
+ 1458 BRANCHIFNOT 1482
+ 1460 ACC3
+ 1461 GETFIELD1
+ 1462 PUSHACC3
+ 1463 GETFIELD1
+ 1464 PUSHACC5
+ 1465 GETFIELD0
+ 1466 PUSHACC5
+ 1467 GETFIELD0
+ 1468 PUSHACC5
+ 1469 PUSHACC5
+ 1470 APPLY3
+ 1471 PUSHACC3
+ 1472 PUSHOFFSETCLOSURE0
+ 1473 APPTERM 4, 8
+ 1476 ACC3
+ 1477 BRANCHIF 1482
+ 1479 ACC1
+ 1480 RETURN 4
+ 1482 GETGLOBAL "List.fold_left2"
+ 1484 PUSHGETGLOBALFIELD Pervasives, 2
+ 1487 APPTERM1 5
+ 1489 RESTART
+ 1490 GRAB 3
+ 1492 ACC1
+ 1493 BRANCHIFNOT 1516
+ 1495 ACC2
+ 1496 BRANCHIFNOT 1522
+ 1498 PUSH_RETADDR 1509
+ 1500 ACC6
+ 1501 PUSHACC6
+ 1502 GETFIELD1
+ 1503 PUSHACC6
+ 1504 GETFIELD1
+ 1505 PUSHACC6
+ 1506 PUSHOFFSETCLOSURE0
+ 1507 APPLY 4
+ 1509 PUSHACC3
+ 1510 GETFIELD0
+ 1511 PUSHACC3
+ 1512 GETFIELD0
+ 1513 PUSHACC3
+ 1514 APPTERM3 7
+ 1516 ACC2
+ 1517 BRANCHIF 1522
+ 1519 ACC3
+ 1520 RETURN 4
+ 1522 GETGLOBAL "List.fold_right2"
+ 1524 PUSHGETGLOBALFIELD Pervasives, 2
+ 1527 APPTERM1 5
+ 1529 RESTART
+ 1530 GRAB 1
+ 1532 ACC1
+ 1533 BRANCHIFNOT 1549
+ 1535 ACC1
+ 1536 GETFIELD0
+ 1537 PUSHACC1
+ 1538 APPLY1
+ 1539 BRANCHIFNOT 1547
+ 1541 ACC1
+ 1542 GETFIELD1
+ 1543 PUSHACC1
+ 1544 PUSHOFFSETCLOSURE0
+ 1545 APPTERM2 4
+ 1547 RETURN 2
+ 1549 CONST1
+ 1550 RETURN 2
+ 1552 RESTART
+ 1553 GRAB 1
+ 1555 ACC1
+ 1556 BRANCHIFNOT 1570
+ 1558 ACC1
+ 1559 GETFIELD0
+ 1560 PUSHACC1
+ 1561 APPLY1
+ 1562 BRANCHIF 1570
+ 1564 ACC1
+ 1565 GETFIELD1
+ 1566 PUSHACC1
+ 1567 PUSHOFFSETCLOSURE0
+ 1568 APPTERM2 4
+ 1570 RETURN 2
+ 1572 RESTART
+ 1573 GRAB 2
+ 1575 ACC1
+ 1576 BRANCHIFNOT 1599
+ 1578 ACC2
+ 1579 BRANCHIFNOT 1605
+ 1581 ACC2
+ 1582 GETFIELD0
+ 1583 PUSHACC2
+ 1584 GETFIELD0
+ 1585 PUSHACC2
+ 1586 APPLY2
+ 1587 BRANCHIFNOT 1597
+ 1589 ACC2
+ 1590 GETFIELD1
+ 1591 PUSHACC2
+ 1592 GETFIELD1
+ 1593 PUSHACC2
+ 1594 PUSHOFFSETCLOSURE0
+ 1595 APPTERM3 6
+ 1597 RETURN 3
+ 1599 ACC2
+ 1600 BRANCHIF 1605
+ 1602 CONST1
+ 1603 RETURN 3
+ 1605 GETGLOBAL "List.for_all2"
+ 1607 PUSHGETGLOBALFIELD Pervasives, 2
+ 1610 APPTERM1 4
+ 1612 RESTART
+ 1613 GRAB 2
+ 1615 ACC1
+ 1616 BRANCHIFNOT 1639
+ 1618 ACC2
+ 1619 BRANCHIFNOT 1646
+ 1621 ACC2
+ 1622 GETFIELD0
+ 1623 PUSHACC2
+ 1624 GETFIELD0
+ 1625 PUSHACC2
+ 1626 APPLY2
+ 1627 BRANCHIF 1637
+ 1629 ACC2
+ 1630 GETFIELD1
+ 1631 PUSHACC2
+ 1632 GETFIELD1
+ 1633 PUSHACC2
+ 1634 PUSHOFFSETCLOSURE0
+ 1635 APPTERM3 6
+ 1637 RETURN 3
+ 1639 ACC2
+ 1640 BRANCHIFNOT 1644
+ 1642 BRANCH 1646
+ 1644 RETURN 3
+ 1646 GETGLOBAL "List.exists2"
+ 1648 PUSHGETGLOBALFIELD Pervasives, 2
+ 1651 APPTERM1 4
+ 1653 RESTART
+ 1654 GRAB 1
+ 1656 ACC1
+ 1657 BRANCHIFNOT 1672
+ 1659 ACC0
+ 1660 PUSHACC2
+ 1661 GETFIELD0
+ 1662 C_CALL2 equal
+ 1664 BRANCHIF 1672
+ 1666 ACC1
+ 1667 GETFIELD1
+ 1668 PUSHACC1
+ 1669 PUSHOFFSETCLOSURE0
+ 1670 APPTERM2 4
+ 1672 RETURN 2
+ 1674 RESTART
+ 1675 GRAB 1
+ 1677 ACC1
+ 1678 BRANCHIFNOT 1692
+ 1680 ACC0
+ 1681 PUSHACC2
+ 1682 GETFIELD0
+ 1683 EQ
+ 1684 BRANCHIF 1692
+ 1686 ACC1
+ 1687 GETFIELD1
+ 1688 PUSHACC1
+ 1689 PUSHOFFSETCLOSURE0
+ 1690 APPTERM2 4
+ 1692 RETURN 2
+ 1694 RESTART
+ 1695 GRAB 1
+ 1697 ACC1
+ 1698 BRANCHIFNOT 1719
+ 1700 ACC1
+ 1701 GETFIELD0
+ 1702 PUSHACC1
+ 1703 PUSHACC1
+ 1704 GETFIELD0
+ 1705 C_CALL2 equal
+ 1707 BRANCHIFNOT 1713
+ 1709 ACC0
+ 1710 GETFIELD1
+ 1711 RETURN 3
+ 1713 ACC2
+ 1714 GETFIELD1
+ 1715 PUSHACC2
+ 1716 PUSHOFFSETCLOSURE0
+ 1717 APPTERM2 5
+ 1719 GETGLOBAL Not_found
+ 1721 MAKEBLOCK1 0
+ 1723 RAISE
+ 1724 RESTART
+ 1725 GRAB 1
+ 1727 ACC1
+ 1728 BRANCHIFNOT 1748
+ 1730 ACC1
+ 1731 GETFIELD0
+ 1732 PUSHACC1
+ 1733 PUSHACC1
+ 1734 GETFIELD0
+ 1735 EQ
+ 1736 BRANCHIFNOT 1742
+ 1738 ACC0
+ 1739 GETFIELD1
+ 1740 RETURN 3
+ 1742 ACC2
+ 1743 GETFIELD1
+ 1744 PUSHACC2
+ 1745 PUSHOFFSETCLOSURE0
+ 1746 APPTERM2 5
+ 1748 GETGLOBAL Not_found
+ 1750 MAKEBLOCK1 0
+ 1752 RAISE
+ 1753 RESTART
+ 1754 GRAB 1
+ 1756 ACC1
+ 1757 BRANCHIFNOT 1773
+ 1759 ACC0
+ 1760 PUSHACC2
+ 1761 GETFIELD0
+ 1762 GETFIELD0
+ 1763 C_CALL2 equal
+ 1765 BRANCHIF 1773
+ 1767 ACC1
+ 1768 GETFIELD1
+ 1769 PUSHACC1
+ 1770 PUSHOFFSETCLOSURE0
+ 1771 APPTERM2 4
+ 1773 RETURN 2
+ 1775 RESTART
+ 1776 GRAB 1
+ 1778 ACC1
+ 1779 BRANCHIFNOT 1794
+ 1781 ACC0
+ 1782 PUSHACC2
+ 1783 GETFIELD0
+ 1784 GETFIELD0
+ 1785 EQ
+ 1786 BRANCHIF 1794
+ 1788 ACC1
+ 1789 GETFIELD1
+ 1790 PUSHACC1
+ 1791 PUSHOFFSETCLOSURE0
+ 1792 APPTERM2 4
+ 1794 RETURN 2
+ 1796 RESTART
+ 1797 GRAB 1
+ 1799 ACC1
+ 1800 BRANCHIFNOT 1825
+ 1802 ACC1
+ 1803 GETFIELD0
+ 1804 PUSHACC2
+ 1805 GETFIELD1
+ 1806 PUSHACC2
+ 1807 PUSHACC2
+ 1808 GETFIELD0
+ 1809 C_CALL2 equal
+ 1811 BRANCHIFNOT 1816
+ 1813 ACC0
+ 1814 RETURN 4
+ 1816 ACC0
+ 1817 PUSHACC3
+ 1818 PUSHOFFSETCLOSURE0
+ 1819 APPLY2
+ 1820 PUSHACC2
+ 1821 MAKEBLOCK2 0
+ 1823 POP 2
+ 1825 RETURN 2
+ 1827 RESTART
+ 1828 GRAB 1
+ 1830 ACC1
+ 1831 BRANCHIFNOT 1855
+ 1833 ACC1
+ 1834 GETFIELD0
+ 1835 PUSHACC2
+ 1836 GETFIELD1
+ 1837 PUSHACC2
+ 1838 PUSHACC2
+ 1839 GETFIELD0
+ 1840 EQ
+ 1841 BRANCHIFNOT 1846
+ 1843 ACC0
+ 1844 RETURN 4
+ 1846 ACC0
+ 1847 PUSHACC3
+ 1848 PUSHOFFSETCLOSURE0
+ 1849 APPLY2
+ 1850 PUSHACC2
+ 1851 MAKEBLOCK2 0
+ 1853 POP 2
+ 1855 RETURN 2
+ 1857 RESTART
+ 1858 GRAB 1
+ 1860 ACC1
+ 1861 BRANCHIFNOT 1879
+ 1863 ACC1
+ 1864 GETFIELD0
+ 1865 PUSHACC0
+ 1866 PUSHACC2
+ 1867 APPLY1
+ 1868 BRANCHIFNOT 1873
+ 1870 ACC0
+ 1871 RETURN 3
+ 1873 ACC2
+ 1874 GETFIELD1
+ 1875 PUSHACC2
+ 1876 PUSHOFFSETCLOSURE0
+ 1877 APPTERM2 5
+ 1879 GETGLOBAL Not_found
+ 1881 MAKEBLOCK1 0
+ 1883 RAISE
+ 1884 RESTART
+ 1885 GRAB 2
+ 1887 ACC2
+ 1888 BRANCHIFNOT 1917
+ 1890 ACC2
+ 1891 GETFIELD0
+ 1892 PUSHACC3
+ 1893 GETFIELD1
+ 1894 PUSHACC1
+ 1895 PUSHENVACC2
+ 1896 APPLY1
+ 1897 BRANCHIFNOT 1908
+ 1899 ACC0
+ 1900 PUSHACC4
+ 1901 PUSHACC4
+ 1902 PUSHACC4
+ 1903 MAKEBLOCK2 0
+ 1905 PUSHOFFSETCLOSURE0
+ 1906 APPTERM3 8
+ 1908 ACC0
+ 1909 PUSHACC4
+ 1910 PUSHACC3
+ 1911 MAKEBLOCK2 0
+ 1913 PUSHACC4
+ 1914 PUSHOFFSETCLOSURE0
+ 1915 APPTERM3 8
+ 1917 ACC1
+ 1918 PUSHENVACC1
+ 1919 APPLY1
+ 1920 PUSHACC1
+ 1921 PUSHENVACC1
+ 1922 APPLY1
+ 1923 MAKEBLOCK2 0
+ 1925 RETURN 3
+ 1927 RESTART
+ 1928 GRAB 1
+ 1930 ACC0
+ 1931 PUSHENVACC1
+ 1932 CLOSUREREC 2, 1885
+ 1936 ACC2
+ 1937 PUSHCONST0
+ 1938 PUSHCONST0
+ 1939 PUSHACC3
+ 1940 APPTERM3 6
+ 1942 ACC0
+ 1943 BRANCHIFNOT 1967
+ 1945 ACC0
+ 1946 GETFIELD0
+ 1947 PUSHACC1
+ 1948 GETFIELD1
+ 1949 PUSHOFFSETCLOSURE0
+ 1950 APPLY1
+ 1951 PUSHACC0
+ 1952 GETFIELD1
+ 1953 PUSHACC2
+ 1954 GETFIELD1
+ 1955 MAKEBLOCK2 0
+ 1957 PUSHACC1
+ 1958 GETFIELD0
+ 1959 PUSHACC3
+ 1960 GETFIELD0
+ 1961 MAKEBLOCK2 0
+ 1963 MAKEBLOCK2 0
+ 1965 RETURN 3
+ 1967 GETGLOBAL <0>(0, 0)
+ 1969 RETURN 1
+ 1971 RESTART
+ 1972 GRAB 1
+ 1974 ACC0
+ 1975 BRANCHIFNOT 1996
+ 1977 ACC1
+ 1978 BRANCHIFNOT 2003
+ 1980 ACC1
+ 1981 GETFIELD1
+ 1982 PUSHACC1
+ 1983 GETFIELD1
+ 1984 PUSHOFFSETCLOSURE0
+ 1985 APPLY2
+ 1986 PUSHACC2
+ 1987 GETFIELD0
+ 1988 PUSHACC2
+ 1989 GETFIELD0
+ 1990 MAKEBLOCK2 0
+ 1992 MAKEBLOCK2 0
+ 1994 RETURN 2
+ 1996 ACC1
+ 1997 BRANCHIFNOT 2001
+ 1999 BRANCH 2003
+ 2001 RETURN 2
+ 2003 GETGLOBAL "List.combine"
+ 2005 PUSHGETGLOBALFIELD Pervasives, 2
+ 2008 APPTERM1 3
+ 2010 RESTART
+ 2011 GRAB 1
+ 2013 ACC1
+ 2014 BRANCHIFNOT 2038
+ 2016 ACC1
+ 2017 GETFIELD0
+ 2018 PUSHACC2
+ 2019 GETFIELD1
+ 2020 PUSHACC1
+ 2021 PUSHENVACC2
+ 2022 APPLY1
+ 2023 BRANCHIFNOT 2033
+ 2025 ACC0
+ 2026 PUSHACC3
+ 2027 PUSHACC3
+ 2028 MAKEBLOCK2 0
+ 2030 PUSHOFFSETCLOSURE0
+ 2031 APPTERM2 6
+ 2033 ACC0
+ 2034 PUSHACC3
+ 2035 PUSHOFFSETCLOSURE0
+ 2036 APPTERM2 6
+ 2038 ACC0
+ 2039 PUSHENVACC1
+ 2040 APPTERM1 3
+ 2042 ACC0
+ 2043 PUSHENVACC1
+ 2044 CLOSUREREC 2, 2011
+ 2048 CONST0
+ 2049 PUSHACC1
+ 2050 APPTERM1 3
+ 2052 RESTART
+ 2053 GRAB 2
+ 2055 ACC1
+ 2056 BRANCHIFNOT 2077
+ 2058 ACC2
+ 2059 BRANCHIFNOT 2084
+ 2061 ACC2
+ 2062 GETFIELD1
+ 2063 PUSHACC2
+ 2064 GETFIELD1
+ 2065 PUSHACC2
+ 2066 PUSHACC5
+ 2067 GETFIELD0
+ 2068 PUSHACC5
+ 2069 GETFIELD0
+ 2070 PUSHENVACC1
+ 2071 APPLY2
+ 2072 MAKEBLOCK2 0
+ 2074 PUSHOFFSETCLOSURE0
+ 2075 APPTERM3 6
+ 2077 ACC2
+ 2078 BRANCHIFNOT 2082
+ 2080 BRANCH 2084
+ 2082 RETURN 3
+ 2084 GETGLOBAL "List.rev_map2"
+ 2086 PUSHGETGLOBALFIELD Pervasives, 2
+ 2089 APPTERM1 4
+ 2091 RESTART
+ 2092 GRAB 2
+ 2094 ACC0
+ 2095 CLOSUREREC 1, 2053
+ 2099 ACC3
+ 2100 PUSHACC3
+ 2101 PUSHCONST0
+ 2102 PUSHACC3
+ 2103 APPTERM3 7
+ 2105 RESTART
+ 2106 GRAB 1
+ 2108 ACC1
+ 2109 BRANCHIFNOT 2123
+ 2111 ACC1
+ 2112 GETFIELD1
+ 2113 PUSHACC1
+ 2114 PUSHACC3
+ 2115 GETFIELD0
+ 2116 PUSHENVACC1
+ 2117 APPLY1
+ 2118 MAKEBLOCK2 0
+ 2120 PUSHOFFSETCLOSURE0
+ 2121 APPTERM2 4
+ 2123 ACC0
+ 2124 RETURN 2
+ 2126 RESTART
+ 2127 GRAB 1
+ 2129 ACC0
+ 2130 CLOSUREREC 1, 2106
+ 2134 ACC2
+ 2135 PUSHCONST0
+ 2136 PUSHACC2
+ 2137 APPTERM2 5
+ 2139 CONST0
+ 2140 PUSHACC1
+ 2141 PUSHENVACC1
+ 2142 APPTERM2 3
+ 2144 ACC0
+ 2145 BRANCHIFNOT 2151
+ 2147 ACC0
+ 2148 GETFIELD1
+ 2149 RETURN 1
+ 2151 GETGLOBAL "tl"
+ 2153 PUSHGETGLOBALFIELD Pervasives, 3
+ 2156 APPTERM1 2
+ 2158 ACC0
+ 2159 BRANCHIFNOT 2165
+ 2161 ACC0
+ 2162 GETFIELD0
+ 2163 RETURN 1
+ 2165 GETGLOBAL "hd"
+ 2167 PUSHGETGLOBALFIELD Pervasives, 3
+ 2170 APPTERM1 2
+ 2172 ACC0
+ 2173 PUSHCONST0
+ 2174 PUSHENVACC1
+ 2175 APPTERM2 3
+ 2177 CLOSUREREC 0, 1200
+ 2181 ACC0
+ 2182 CLOSURE 1, 2172
+ 2185 PUSH
+ 2186 CLOSURE 0, 2158
+ 2189 PUSH
+ 2190 CLOSURE 0, 2144
+ 2193 PUSH
+ 2194 CLOSUREREC 0, 1217
+ 2198 GETGLOBALFIELD Pervasives, 16
+ 2201 PUSH
+ 2202 CLOSUREREC 0, 1259
+ 2206 ACC0
+ 2207 CLOSURE 1, 2139
+ 2210 PUSH
+ 2211 CLOSUREREC 0, 1277
+ 2215 CLOSUREREC 0, 1294
+ 2219 CLOSURE 0, 2127
+ 2222 PUSH
+ 2223 CLOSUREREC 0, 1316
+ 2227 CLOSUREREC 0, 1334
+ 2231 CLOSUREREC 0, 1354
+ 2235 CLOSUREREC 0, 1374
+ 2239 CLOSURE 0, 2092
+ 2242 PUSH
+ 2243 CLOSUREREC 0, 1415
+ 2247 CLOSUREREC 0, 1452
+ 2251 CLOSUREREC 0, 1490
+ 2255 CLOSUREREC 0, 1530
+ 2259 CLOSUREREC 0, 1553
+ 2263 CLOSUREREC 0, 1573
+ 2267 CLOSUREREC 0, 1613
+ 2271 CLOSUREREC 0, 1654
+ 2275 CLOSUREREC 0, 1675
+ 2279 CLOSUREREC 0, 1695
+ 2283 CLOSUREREC 0, 1725
+ 2287 CLOSUREREC 0, 1754
+ 2291 CLOSUREREC 0, 1776
+ 2295 CLOSUREREC 0, 1797
+ 2299 CLOSUREREC 0, 1828
+ 2303 CLOSUREREC 0, 1858
+ 2307 ACC 24
+ 2309 CLOSURE 1, 2042
+ 2312 PUSHACC 25
+ 2314 CLOSUREREC 1, 1928
+ 2318 CLOSUREREC 0, 1942
+ 2322 CLOSUREREC 0, 1972
+ 2326 ACC0
+ 2327 PUSHACC2
+ 2328 PUSHACC7
+ 2329 PUSHACC 9
+ 2331 PUSHACC 11
+ 2333 PUSHACC 13
+ 2335 PUSHACC 15
+ 2337 PUSHACC 17
+ 2339 PUSHACC 10
+ 2341 PUSHACC 12
+ 2343 PUSHACC 13
+ 2345 PUSHACC 15
+ 2347 PUSHACC 23
+ 2349 PUSHACC 25
+ 2351 PUSHACC 27
+ 2353 PUSHACC 29
+ 2355 PUSHACC 31
+ 2357 PUSHACC 33
+ 2359 PUSHACC 35
+ 2361 PUSHACC 37
+ 2363 PUSHACC 40
+ 2365 PUSHACC 42
+ 2367 PUSHACC 41
+ 2369 PUSHACC 45
+ 2371 PUSHACC 47
+ 2373 PUSHACC 50
+ 2375 PUSHACC 52
+ 2377 PUSHACC 51
+ 2379 PUSHACC 55
+ 2381 PUSHACC 56
+ 2383 PUSHACC 59
+ 2385 PUSHACC 61
+ 2387 PUSHACC 60
+ 2389 PUSHACC 64
+ 2391 PUSHACC 66
+ 2393 PUSHACC 68
+ 2395 PUSHACC 70
+ 2397 MAKEBLOCK 37, 0
+ 2400 POP 36
+ 2402 SETGLOBAL List
+ 2404 BRANCH 2432
+ 2406 CONST0
+ 2407 PUSHACC1
+ 2408 LEINT
+ 2409 BRANCHIFNOT 2414
+ 2411 CONST0
+ 2412 RETURN 1
+ 2414 ACC0
+ 2415 OFFSETINT -1
+ 2417 PUSHOFFSETCLOSURE0
+ 2418 APPLY1
+ 2419 PUSHACC1
+ 2420 MAKEBLOCK2 0
+ 2422 RETURN 1
+ 2424 RESTART
+ 2425 GRAB 1
+ 2427 ACC1
+ 2428 PUSHACC1
+ 2429 ADDINT
+ 2430 RETURN 2
+ 2432 CLOSUREREC 0, 2406
+ 2436 CONSTINT 300
+ 2438 PUSHACC1
+ 2439 APPLY1
+ 2440 PUSHCONST0
+ 2441 C_CALL1 gc_major
+ 2443 CONSTINT 150
+ 2445 PUSHCONSTINT 301
+ 2447 MULINT
+ 2448 PUSHACC1
+ 2449 PUSHCONST0
+ 2450 PUSH
+ 2451 CLOSURE 0, 2425
+ 2454 PUSHGETGLOBALFIELD List, 12
+ 2457 APPLY3
+ 2458 NEQ
+ 2459 BRANCHIFNOT 2466
+ 2461 GETGLOBAL Not_found
+ 2463 MAKEBLOCK1 0
+ 2465 RAISE
+ 2466 POP 2
+ 2468 ATOM0
+ 2469 SETGLOBAL T320-gc-2
+ 2471 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t320-gc-3.ml b/testsuite/tests/tool-ocaml/t320-gc-3.ml
new file mode 100644
index 0000000000..7c33d2fd16
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t320-gc-3.ml
@@ -0,0 +1,1589 @@
+open Lib;;
+let rec f n =
+ if n <= 0 then []
+ else n :: f (n-1)
+in
+let l = f 300 in
+Gc.full_major ();
+if List.fold_left (+) 0 l <> 301 * 150 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 BRANCH 2177
+ 1199 RESTART
+ 1200 GRAB 1
+ 1202 ACC1
+ 1203 BRANCHIFNOT 1213
+ 1205 ACC1
+ 1206 GETFIELD1
+ 1207 PUSHACC1
+ 1208 OFFSETINT 1
+ 1210 PUSHOFFSETCLOSURE0
+ 1211 APPTERM2 4
+ 1213 ACC0
+ 1214 RETURN 2
+ 1216 RESTART
+ 1217 GRAB 1
+ 1219 ACC0
+ 1220 BRANCHIFNOT 1251
+ 1222 CONST0
+ 1223 PUSHACC2
+ 1224 EQ
+ 1225 BRANCHIFNOT 1231
+ 1227 ACC0
+ 1228 GETFIELD0
+ 1229 RETURN 2
+ 1231 CONST0
+ 1232 PUSHACC2
+ 1233 GTINT
+ 1234 BRANCHIFNOT 1244
+ 1236 ACC1
+ 1237 OFFSETINT -1
+ 1239 PUSHACC1
+ 1240 GETFIELD1
+ 1241 PUSHOFFSETCLOSURE0
+ 1242 APPTERM2 4
+ 1244 GETGLOBAL "List.nth"
+ 1246 PUSHGETGLOBALFIELD Pervasives, 2
+ 1249 APPTERM1 3
+ 1251 GETGLOBAL "nth"
+ 1253 PUSHGETGLOBALFIELD Pervasives, 3
+ 1256 APPTERM1 3
+ 1258 RESTART
+ 1259 GRAB 1
+ 1261 ACC0
+ 1262 BRANCHIFNOT 1274
+ 1264 ACC1
+ 1265 PUSHACC1
+ 1266 GETFIELD0
+ 1267 MAKEBLOCK2 0
+ 1269 PUSHACC1
+ 1270 GETFIELD1
+ 1271 PUSHOFFSETCLOSURE0
+ 1272 APPTERM2 4
+ 1274 ACC1
+ 1275 RETURN 2
+ 1277 ACC0
+ 1278 BRANCHIFNOT 1291
+ 1280 ACC0
+ 1281 GETFIELD1
+ 1282 PUSHOFFSETCLOSURE0
+ 1283 APPLY1
+ 1284 PUSHACC1
+ 1285 GETFIELD0
+ 1286 PUSHGETGLOBALFIELD Pervasives, 16
+ 1289 APPTERM2 3
+ 1291 RETURN 1
+ 1293 RESTART
+ 1294 GRAB 1
+ 1296 ACC1
+ 1297 BRANCHIFNOT 1313
+ 1299 ACC1
+ 1300 GETFIELD0
+ 1301 PUSHACC1
+ 1302 APPLY1
+ 1303 PUSHACC2
+ 1304 GETFIELD1
+ 1305 PUSHACC2
+ 1306 PUSHOFFSETCLOSURE0
+ 1307 APPLY2
+ 1308 PUSHACC1
+ 1309 MAKEBLOCK2 0
+ 1311 POP 1
+ 1313 RETURN 2
+ 1315 RESTART
+ 1316 GRAB 1
+ 1318 ACC1
+ 1319 BRANCHIFNOT 1331
+ 1321 ACC1
+ 1322 GETFIELD0
+ 1323 PUSHACC1
+ 1324 APPLY1
+ 1325 ACC1
+ 1326 GETFIELD1
+ 1327 PUSHACC1
+ 1328 PUSHOFFSETCLOSURE0
+ 1329 APPTERM2 4
+ 1331 RETURN 2
+ 1333 RESTART
+ 1334 GRAB 2
+ 1336 ACC2
+ 1337 BRANCHIFNOT 1350
+ 1339 ACC2
+ 1340 GETFIELD1
+ 1341 PUSHACC3
+ 1342 GETFIELD0
+ 1343 PUSHACC3
+ 1344 PUSHACC3
+ 1345 APPLY2
+ 1346 PUSHACC2
+ 1347 PUSHOFFSETCLOSURE0
+ 1348 APPTERM3 6
+ 1350 ACC1
+ 1351 RETURN 3
+ 1353 RESTART
+ 1354 GRAB 2
+ 1356 ACC1
+ 1357 BRANCHIFNOT 1370
+ 1359 ACC2
+ 1360 PUSHACC2
+ 1361 GETFIELD1
+ 1362 PUSHACC2
+ 1363 PUSHOFFSETCLOSURE0
+ 1364 APPLY3
+ 1365 PUSHACC2
+ 1366 GETFIELD0
+ 1367 PUSHACC2
+ 1368 APPTERM2 5
+ 1370 ACC2
+ 1371 RETURN 3
+ 1373 RESTART
+ 1374 GRAB 2
+ 1376 ACC1
+ 1377 BRANCHIFNOT 1400
+ 1379 ACC2
+ 1380 BRANCHIFNOT 1407
+ 1382 ACC2
+ 1383 GETFIELD0
+ 1384 PUSHACC2
+ 1385 GETFIELD0
+ 1386 PUSHACC2
+ 1387 APPLY2
+ 1388 PUSHACC3
+ 1389 GETFIELD1
+ 1390 PUSHACC3
+ 1391 GETFIELD1
+ 1392 PUSHACC3
+ 1393 PUSHOFFSETCLOSURE0
+ 1394 APPLY3
+ 1395 PUSHACC1
+ 1396 MAKEBLOCK2 0
+ 1398 RETURN 4
+ 1400 ACC2
+ 1401 BRANCHIFNOT 1405
+ 1403 BRANCH 1407
+ 1405 RETURN 3
+ 1407 GETGLOBAL "List.map2"
+ 1409 PUSHGETGLOBALFIELD Pervasives, 2
+ 1412 APPTERM1 4
+ 1414 RESTART
+ 1415 GRAB 2
+ 1417 ACC1
+ 1418 BRANCHIFNOT 1437
+ 1420 ACC2
+ 1421 BRANCHIFNOT 1444
+ 1423 ACC2
+ 1424 GETFIELD0
+ 1425 PUSHACC2
+ 1426 GETFIELD0
+ 1427 PUSHACC2
+ 1428 APPLY2
+ 1429 ACC2
+ 1430 GETFIELD1
+ 1431 PUSHACC2
+ 1432 GETFIELD1
+ 1433 PUSHACC2
+ 1434 PUSHOFFSETCLOSURE0
+ 1435 APPTERM3 6
+ 1437 ACC2
+ 1438 BRANCHIFNOT 1442
+ 1440 BRANCH 1444
+ 1442 RETURN 3
+ 1444 GETGLOBAL "List.iter2"
+ 1446 PUSHGETGLOBALFIELD Pervasives, 2
+ 1449 APPTERM1 4
+ 1451 RESTART
+ 1452 GRAB 3
+ 1454 ACC2
+ 1455 BRANCHIFNOT 1476
+ 1457 ACC3
+ 1458 BRANCHIFNOT 1482
+ 1460 ACC3
+ 1461 GETFIELD1
+ 1462 PUSHACC3
+ 1463 GETFIELD1
+ 1464 PUSHACC5
+ 1465 GETFIELD0
+ 1466 PUSHACC5
+ 1467 GETFIELD0
+ 1468 PUSHACC5
+ 1469 PUSHACC5
+ 1470 APPLY3
+ 1471 PUSHACC3
+ 1472 PUSHOFFSETCLOSURE0
+ 1473 APPTERM 4, 8
+ 1476 ACC3
+ 1477 BRANCHIF 1482
+ 1479 ACC1
+ 1480 RETURN 4
+ 1482 GETGLOBAL "List.fold_left2"
+ 1484 PUSHGETGLOBALFIELD Pervasives, 2
+ 1487 APPTERM1 5
+ 1489 RESTART
+ 1490 GRAB 3
+ 1492 ACC1
+ 1493 BRANCHIFNOT 1516
+ 1495 ACC2
+ 1496 BRANCHIFNOT 1522
+ 1498 PUSH_RETADDR 1509
+ 1500 ACC6
+ 1501 PUSHACC6
+ 1502 GETFIELD1
+ 1503 PUSHACC6
+ 1504 GETFIELD1
+ 1505 PUSHACC6
+ 1506 PUSHOFFSETCLOSURE0
+ 1507 APPLY 4
+ 1509 PUSHACC3
+ 1510 GETFIELD0
+ 1511 PUSHACC3
+ 1512 GETFIELD0
+ 1513 PUSHACC3
+ 1514 APPTERM3 7
+ 1516 ACC2
+ 1517 BRANCHIF 1522
+ 1519 ACC3
+ 1520 RETURN 4
+ 1522 GETGLOBAL "List.fold_right2"
+ 1524 PUSHGETGLOBALFIELD Pervasives, 2
+ 1527 APPTERM1 5
+ 1529 RESTART
+ 1530 GRAB 1
+ 1532 ACC1
+ 1533 BRANCHIFNOT 1549
+ 1535 ACC1
+ 1536 GETFIELD0
+ 1537 PUSHACC1
+ 1538 APPLY1
+ 1539 BRANCHIFNOT 1547
+ 1541 ACC1
+ 1542 GETFIELD1
+ 1543 PUSHACC1
+ 1544 PUSHOFFSETCLOSURE0
+ 1545 APPTERM2 4
+ 1547 RETURN 2
+ 1549 CONST1
+ 1550 RETURN 2
+ 1552 RESTART
+ 1553 GRAB 1
+ 1555 ACC1
+ 1556 BRANCHIFNOT 1570
+ 1558 ACC1
+ 1559 GETFIELD0
+ 1560 PUSHACC1
+ 1561 APPLY1
+ 1562 BRANCHIF 1570
+ 1564 ACC1
+ 1565 GETFIELD1
+ 1566 PUSHACC1
+ 1567 PUSHOFFSETCLOSURE0
+ 1568 APPTERM2 4
+ 1570 RETURN 2
+ 1572 RESTART
+ 1573 GRAB 2
+ 1575 ACC1
+ 1576 BRANCHIFNOT 1599
+ 1578 ACC2
+ 1579 BRANCHIFNOT 1605
+ 1581 ACC2
+ 1582 GETFIELD0
+ 1583 PUSHACC2
+ 1584 GETFIELD0
+ 1585 PUSHACC2
+ 1586 APPLY2
+ 1587 BRANCHIFNOT 1597
+ 1589 ACC2
+ 1590 GETFIELD1
+ 1591 PUSHACC2
+ 1592 GETFIELD1
+ 1593 PUSHACC2
+ 1594 PUSHOFFSETCLOSURE0
+ 1595 APPTERM3 6
+ 1597 RETURN 3
+ 1599 ACC2
+ 1600 BRANCHIF 1605
+ 1602 CONST1
+ 1603 RETURN 3
+ 1605 GETGLOBAL "List.for_all2"
+ 1607 PUSHGETGLOBALFIELD Pervasives, 2
+ 1610 APPTERM1 4
+ 1612 RESTART
+ 1613 GRAB 2
+ 1615 ACC1
+ 1616 BRANCHIFNOT 1639
+ 1618 ACC2
+ 1619 BRANCHIFNOT 1646
+ 1621 ACC2
+ 1622 GETFIELD0
+ 1623 PUSHACC2
+ 1624 GETFIELD0
+ 1625 PUSHACC2
+ 1626 APPLY2
+ 1627 BRANCHIF 1637
+ 1629 ACC2
+ 1630 GETFIELD1
+ 1631 PUSHACC2
+ 1632 GETFIELD1
+ 1633 PUSHACC2
+ 1634 PUSHOFFSETCLOSURE0
+ 1635 APPTERM3 6
+ 1637 RETURN 3
+ 1639 ACC2
+ 1640 BRANCHIFNOT 1644
+ 1642 BRANCH 1646
+ 1644 RETURN 3
+ 1646 GETGLOBAL "List.exists2"
+ 1648 PUSHGETGLOBALFIELD Pervasives, 2
+ 1651 APPTERM1 4
+ 1653 RESTART
+ 1654 GRAB 1
+ 1656 ACC1
+ 1657 BRANCHIFNOT 1672
+ 1659 ACC0
+ 1660 PUSHACC2
+ 1661 GETFIELD0
+ 1662 C_CALL2 equal
+ 1664 BRANCHIF 1672
+ 1666 ACC1
+ 1667 GETFIELD1
+ 1668 PUSHACC1
+ 1669 PUSHOFFSETCLOSURE0
+ 1670 APPTERM2 4
+ 1672 RETURN 2
+ 1674 RESTART
+ 1675 GRAB 1
+ 1677 ACC1
+ 1678 BRANCHIFNOT 1692
+ 1680 ACC0
+ 1681 PUSHACC2
+ 1682 GETFIELD0
+ 1683 EQ
+ 1684 BRANCHIF 1692
+ 1686 ACC1
+ 1687 GETFIELD1
+ 1688 PUSHACC1
+ 1689 PUSHOFFSETCLOSURE0
+ 1690 APPTERM2 4
+ 1692 RETURN 2
+ 1694 RESTART
+ 1695 GRAB 1
+ 1697 ACC1
+ 1698 BRANCHIFNOT 1719
+ 1700 ACC1
+ 1701 GETFIELD0
+ 1702 PUSHACC1
+ 1703 PUSHACC1
+ 1704 GETFIELD0
+ 1705 C_CALL2 equal
+ 1707 BRANCHIFNOT 1713
+ 1709 ACC0
+ 1710 GETFIELD1
+ 1711 RETURN 3
+ 1713 ACC2
+ 1714 GETFIELD1
+ 1715 PUSHACC2
+ 1716 PUSHOFFSETCLOSURE0
+ 1717 APPTERM2 5
+ 1719 GETGLOBAL Not_found
+ 1721 MAKEBLOCK1 0
+ 1723 RAISE
+ 1724 RESTART
+ 1725 GRAB 1
+ 1727 ACC1
+ 1728 BRANCHIFNOT 1748
+ 1730 ACC1
+ 1731 GETFIELD0
+ 1732 PUSHACC1
+ 1733 PUSHACC1
+ 1734 GETFIELD0
+ 1735 EQ
+ 1736 BRANCHIFNOT 1742
+ 1738 ACC0
+ 1739 GETFIELD1
+ 1740 RETURN 3
+ 1742 ACC2
+ 1743 GETFIELD1
+ 1744 PUSHACC2
+ 1745 PUSHOFFSETCLOSURE0
+ 1746 APPTERM2 5
+ 1748 GETGLOBAL Not_found
+ 1750 MAKEBLOCK1 0
+ 1752 RAISE
+ 1753 RESTART
+ 1754 GRAB 1
+ 1756 ACC1
+ 1757 BRANCHIFNOT 1773
+ 1759 ACC0
+ 1760 PUSHACC2
+ 1761 GETFIELD0
+ 1762 GETFIELD0
+ 1763 C_CALL2 equal
+ 1765 BRANCHIF 1773
+ 1767 ACC1
+ 1768 GETFIELD1
+ 1769 PUSHACC1
+ 1770 PUSHOFFSETCLOSURE0
+ 1771 APPTERM2 4
+ 1773 RETURN 2
+ 1775 RESTART
+ 1776 GRAB 1
+ 1778 ACC1
+ 1779 BRANCHIFNOT 1794
+ 1781 ACC0
+ 1782 PUSHACC2
+ 1783 GETFIELD0
+ 1784 GETFIELD0
+ 1785 EQ
+ 1786 BRANCHIF 1794
+ 1788 ACC1
+ 1789 GETFIELD1
+ 1790 PUSHACC1
+ 1791 PUSHOFFSETCLOSURE0
+ 1792 APPTERM2 4
+ 1794 RETURN 2
+ 1796 RESTART
+ 1797 GRAB 1
+ 1799 ACC1
+ 1800 BRANCHIFNOT 1825
+ 1802 ACC1
+ 1803 GETFIELD0
+ 1804 PUSHACC2
+ 1805 GETFIELD1
+ 1806 PUSHACC2
+ 1807 PUSHACC2
+ 1808 GETFIELD0
+ 1809 C_CALL2 equal
+ 1811 BRANCHIFNOT 1816
+ 1813 ACC0
+ 1814 RETURN 4
+ 1816 ACC0
+ 1817 PUSHACC3
+ 1818 PUSHOFFSETCLOSURE0
+ 1819 APPLY2
+ 1820 PUSHACC2
+ 1821 MAKEBLOCK2 0
+ 1823 POP 2
+ 1825 RETURN 2
+ 1827 RESTART
+ 1828 GRAB 1
+ 1830 ACC1
+ 1831 BRANCHIFNOT 1855
+ 1833 ACC1
+ 1834 GETFIELD0
+ 1835 PUSHACC2
+ 1836 GETFIELD1
+ 1837 PUSHACC2
+ 1838 PUSHACC2
+ 1839 GETFIELD0
+ 1840 EQ
+ 1841 BRANCHIFNOT 1846
+ 1843 ACC0
+ 1844 RETURN 4
+ 1846 ACC0
+ 1847 PUSHACC3
+ 1848 PUSHOFFSETCLOSURE0
+ 1849 APPLY2
+ 1850 PUSHACC2
+ 1851 MAKEBLOCK2 0
+ 1853 POP 2
+ 1855 RETURN 2
+ 1857 RESTART
+ 1858 GRAB 1
+ 1860 ACC1
+ 1861 BRANCHIFNOT 1879
+ 1863 ACC1
+ 1864 GETFIELD0
+ 1865 PUSHACC0
+ 1866 PUSHACC2
+ 1867 APPLY1
+ 1868 BRANCHIFNOT 1873
+ 1870 ACC0
+ 1871 RETURN 3
+ 1873 ACC2
+ 1874 GETFIELD1
+ 1875 PUSHACC2
+ 1876 PUSHOFFSETCLOSURE0
+ 1877 APPTERM2 5
+ 1879 GETGLOBAL Not_found
+ 1881 MAKEBLOCK1 0
+ 1883 RAISE
+ 1884 RESTART
+ 1885 GRAB 2
+ 1887 ACC2
+ 1888 BRANCHIFNOT 1917
+ 1890 ACC2
+ 1891 GETFIELD0
+ 1892 PUSHACC3
+ 1893 GETFIELD1
+ 1894 PUSHACC1
+ 1895 PUSHENVACC2
+ 1896 APPLY1
+ 1897 BRANCHIFNOT 1908
+ 1899 ACC0
+ 1900 PUSHACC4
+ 1901 PUSHACC4
+ 1902 PUSHACC4
+ 1903 MAKEBLOCK2 0
+ 1905 PUSHOFFSETCLOSURE0
+ 1906 APPTERM3 8
+ 1908 ACC0
+ 1909 PUSHACC4
+ 1910 PUSHACC3
+ 1911 MAKEBLOCK2 0
+ 1913 PUSHACC4
+ 1914 PUSHOFFSETCLOSURE0
+ 1915 APPTERM3 8
+ 1917 ACC1
+ 1918 PUSHENVACC1
+ 1919 APPLY1
+ 1920 PUSHACC1
+ 1921 PUSHENVACC1
+ 1922 APPLY1
+ 1923 MAKEBLOCK2 0
+ 1925 RETURN 3
+ 1927 RESTART
+ 1928 GRAB 1
+ 1930 ACC0
+ 1931 PUSHENVACC1
+ 1932 CLOSUREREC 2, 1885
+ 1936 ACC2
+ 1937 PUSHCONST0
+ 1938 PUSHCONST0
+ 1939 PUSHACC3
+ 1940 APPTERM3 6
+ 1942 ACC0
+ 1943 BRANCHIFNOT 1967
+ 1945 ACC0
+ 1946 GETFIELD0
+ 1947 PUSHACC1
+ 1948 GETFIELD1
+ 1949 PUSHOFFSETCLOSURE0
+ 1950 APPLY1
+ 1951 PUSHACC0
+ 1952 GETFIELD1
+ 1953 PUSHACC2
+ 1954 GETFIELD1
+ 1955 MAKEBLOCK2 0
+ 1957 PUSHACC1
+ 1958 GETFIELD0
+ 1959 PUSHACC3
+ 1960 GETFIELD0
+ 1961 MAKEBLOCK2 0
+ 1963 MAKEBLOCK2 0
+ 1965 RETURN 3
+ 1967 GETGLOBAL <0>(0, 0)
+ 1969 RETURN 1
+ 1971 RESTART
+ 1972 GRAB 1
+ 1974 ACC0
+ 1975 BRANCHIFNOT 1996
+ 1977 ACC1
+ 1978 BRANCHIFNOT 2003
+ 1980 ACC1
+ 1981 GETFIELD1
+ 1982 PUSHACC1
+ 1983 GETFIELD1
+ 1984 PUSHOFFSETCLOSURE0
+ 1985 APPLY2
+ 1986 PUSHACC2
+ 1987 GETFIELD0
+ 1988 PUSHACC2
+ 1989 GETFIELD0
+ 1990 MAKEBLOCK2 0
+ 1992 MAKEBLOCK2 0
+ 1994 RETURN 2
+ 1996 ACC1
+ 1997 BRANCHIFNOT 2001
+ 1999 BRANCH 2003
+ 2001 RETURN 2
+ 2003 GETGLOBAL "List.combine"
+ 2005 PUSHGETGLOBALFIELD Pervasives, 2
+ 2008 APPTERM1 3
+ 2010 RESTART
+ 2011 GRAB 1
+ 2013 ACC1
+ 2014 BRANCHIFNOT 2038
+ 2016 ACC1
+ 2017 GETFIELD0
+ 2018 PUSHACC2
+ 2019 GETFIELD1
+ 2020 PUSHACC1
+ 2021 PUSHENVACC2
+ 2022 APPLY1
+ 2023 BRANCHIFNOT 2033
+ 2025 ACC0
+ 2026 PUSHACC3
+ 2027 PUSHACC3
+ 2028 MAKEBLOCK2 0
+ 2030 PUSHOFFSETCLOSURE0
+ 2031 APPTERM2 6
+ 2033 ACC0
+ 2034 PUSHACC3
+ 2035 PUSHOFFSETCLOSURE0
+ 2036 APPTERM2 6
+ 2038 ACC0
+ 2039 PUSHENVACC1
+ 2040 APPTERM1 3
+ 2042 ACC0
+ 2043 PUSHENVACC1
+ 2044 CLOSUREREC 2, 2011
+ 2048 CONST0
+ 2049 PUSHACC1
+ 2050 APPTERM1 3
+ 2052 RESTART
+ 2053 GRAB 2
+ 2055 ACC1
+ 2056 BRANCHIFNOT 2077
+ 2058 ACC2
+ 2059 BRANCHIFNOT 2084
+ 2061 ACC2
+ 2062 GETFIELD1
+ 2063 PUSHACC2
+ 2064 GETFIELD1
+ 2065 PUSHACC2
+ 2066 PUSHACC5
+ 2067 GETFIELD0
+ 2068 PUSHACC5
+ 2069 GETFIELD0
+ 2070 PUSHENVACC1
+ 2071 APPLY2
+ 2072 MAKEBLOCK2 0
+ 2074 PUSHOFFSETCLOSURE0
+ 2075 APPTERM3 6
+ 2077 ACC2
+ 2078 BRANCHIFNOT 2082
+ 2080 BRANCH 2084
+ 2082 RETURN 3
+ 2084 GETGLOBAL "List.rev_map2"
+ 2086 PUSHGETGLOBALFIELD Pervasives, 2
+ 2089 APPTERM1 4
+ 2091 RESTART
+ 2092 GRAB 2
+ 2094 ACC0
+ 2095 CLOSUREREC 1, 2053
+ 2099 ACC3
+ 2100 PUSHACC3
+ 2101 PUSHCONST0
+ 2102 PUSHACC3
+ 2103 APPTERM3 7
+ 2105 RESTART
+ 2106 GRAB 1
+ 2108 ACC1
+ 2109 BRANCHIFNOT 2123
+ 2111 ACC1
+ 2112 GETFIELD1
+ 2113 PUSHACC1
+ 2114 PUSHACC3
+ 2115 GETFIELD0
+ 2116 PUSHENVACC1
+ 2117 APPLY1
+ 2118 MAKEBLOCK2 0
+ 2120 PUSHOFFSETCLOSURE0
+ 2121 APPTERM2 4
+ 2123 ACC0
+ 2124 RETURN 2
+ 2126 RESTART
+ 2127 GRAB 1
+ 2129 ACC0
+ 2130 CLOSUREREC 1, 2106
+ 2134 ACC2
+ 2135 PUSHCONST0
+ 2136 PUSHACC2
+ 2137 APPTERM2 5
+ 2139 CONST0
+ 2140 PUSHACC1
+ 2141 PUSHENVACC1
+ 2142 APPTERM2 3
+ 2144 ACC0
+ 2145 BRANCHIFNOT 2151
+ 2147 ACC0
+ 2148 GETFIELD1
+ 2149 RETURN 1
+ 2151 GETGLOBAL "tl"
+ 2153 PUSHGETGLOBALFIELD Pervasives, 3
+ 2156 APPTERM1 2
+ 2158 ACC0
+ 2159 BRANCHIFNOT 2165
+ 2161 ACC0
+ 2162 GETFIELD0
+ 2163 RETURN 1
+ 2165 GETGLOBAL "hd"
+ 2167 PUSHGETGLOBALFIELD Pervasives, 3
+ 2170 APPTERM1 2
+ 2172 ACC0
+ 2173 PUSHCONST0
+ 2174 PUSHENVACC1
+ 2175 APPTERM2 3
+ 2177 CLOSUREREC 0, 1200
+ 2181 ACC0
+ 2182 CLOSURE 1, 2172
+ 2185 PUSH
+ 2186 CLOSURE 0, 2158
+ 2189 PUSH
+ 2190 CLOSURE 0, 2144
+ 2193 PUSH
+ 2194 CLOSUREREC 0, 1217
+ 2198 GETGLOBALFIELD Pervasives, 16
+ 2201 PUSH
+ 2202 CLOSUREREC 0, 1259
+ 2206 ACC0
+ 2207 CLOSURE 1, 2139
+ 2210 PUSH
+ 2211 CLOSUREREC 0, 1277
+ 2215 CLOSUREREC 0, 1294
+ 2219 CLOSURE 0, 2127
+ 2222 PUSH
+ 2223 CLOSUREREC 0, 1316
+ 2227 CLOSUREREC 0, 1334
+ 2231 CLOSUREREC 0, 1354
+ 2235 CLOSUREREC 0, 1374
+ 2239 CLOSURE 0, 2092
+ 2242 PUSH
+ 2243 CLOSUREREC 0, 1415
+ 2247 CLOSUREREC 0, 1452
+ 2251 CLOSUREREC 0, 1490
+ 2255 CLOSUREREC 0, 1530
+ 2259 CLOSUREREC 0, 1553
+ 2263 CLOSUREREC 0, 1573
+ 2267 CLOSUREREC 0, 1613
+ 2271 CLOSUREREC 0, 1654
+ 2275 CLOSUREREC 0, 1675
+ 2279 CLOSUREREC 0, 1695
+ 2283 CLOSUREREC 0, 1725
+ 2287 CLOSUREREC 0, 1754
+ 2291 CLOSUREREC 0, 1776
+ 2295 CLOSUREREC 0, 1797
+ 2299 CLOSUREREC 0, 1828
+ 2303 CLOSUREREC 0, 1858
+ 2307 ACC 24
+ 2309 CLOSURE 1, 2042
+ 2312 PUSHACC 25
+ 2314 CLOSUREREC 1, 1928
+ 2318 CLOSUREREC 0, 1942
+ 2322 CLOSUREREC 0, 1972
+ 2326 ACC0
+ 2327 PUSHACC2
+ 2328 PUSHACC7
+ 2329 PUSHACC 9
+ 2331 PUSHACC 11
+ 2333 PUSHACC 13
+ 2335 PUSHACC 15
+ 2337 PUSHACC 17
+ 2339 PUSHACC 10
+ 2341 PUSHACC 12
+ 2343 PUSHACC 13
+ 2345 PUSHACC 15
+ 2347 PUSHACC 23
+ 2349 PUSHACC 25
+ 2351 PUSHACC 27
+ 2353 PUSHACC 29
+ 2355 PUSHACC 31
+ 2357 PUSHACC 33
+ 2359 PUSHACC 35
+ 2361 PUSHACC 37
+ 2363 PUSHACC 40
+ 2365 PUSHACC 42
+ 2367 PUSHACC 41
+ 2369 PUSHACC 45
+ 2371 PUSHACC 47
+ 2373 PUSHACC 50
+ 2375 PUSHACC 52
+ 2377 PUSHACC 51
+ 2379 PUSHACC 55
+ 2381 PUSHACC 56
+ 2383 PUSHACC 59
+ 2385 PUSHACC 61
+ 2387 PUSHACC 60
+ 2389 PUSHACC 64
+ 2391 PUSHACC 66
+ 2393 PUSHACC 68
+ 2395 PUSHACC 70
+ 2397 MAKEBLOCK 37, 0
+ 2400 POP 36
+ 2402 SETGLOBAL List
+ 2404 BRANCH 2432
+ 2406 CONST0
+ 2407 PUSHACC1
+ 2408 LEINT
+ 2409 BRANCHIFNOT 2414
+ 2411 CONST0
+ 2412 RETURN 1
+ 2414 ACC0
+ 2415 OFFSETINT -1
+ 2417 PUSHOFFSETCLOSURE0
+ 2418 APPLY1
+ 2419 PUSHACC1
+ 2420 MAKEBLOCK2 0
+ 2422 RETURN 1
+ 2424 RESTART
+ 2425 GRAB 1
+ 2427 ACC1
+ 2428 PUSHACC1
+ 2429 ADDINT
+ 2430 RETURN 2
+ 2432 CLOSUREREC 0, 2406
+ 2436 CONSTINT 300
+ 2438 PUSHACC1
+ 2439 APPLY1
+ 2440 PUSHCONST0
+ 2441 C_CALL1 gc_full_major
+ 2443 CONSTINT 150
+ 2445 PUSHCONSTINT 301
+ 2447 MULINT
+ 2448 PUSHACC1
+ 2449 PUSHCONST0
+ 2450 PUSH
+ 2451 CLOSURE 0, 2425
+ 2454 PUSHGETGLOBALFIELD List, 12
+ 2457 APPLY3
+ 2458 NEQ
+ 2459 BRANCHIFNOT 2466
+ 2461 GETGLOBAL Not_found
+ 2463 MAKEBLOCK1 0
+ 2465 RAISE
+ 2466 POP 2
+ 2468 ATOM0
+ 2469 SETGLOBAL T320-gc-3
+ 2471 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t330-compact-1.ml b/testsuite/tests/tool-ocaml/t330-compact-1.ml
new file mode 100644
index 0000000000..efa958fd29
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t330-compact-1.ml
@@ -0,0 +1,15 @@
+open Lib;;
+Gc.compact ();;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 CONST0
+ 10 C_CALL1 gc_compaction
+ 12 ATOM0
+ 13 SETGLOBAL T330-compact-1
+ 15 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t330-compact-2.ml b/testsuite/tests/tool-ocaml/t330-compact-2.ml
new file mode 100644
index 0000000000..62ab0141d5
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t330-compact-2.ml
@@ -0,0 +1,755 @@
+open Lib;;
+Gc.compact ();;
+let _ = Pervasives.do_at_exit();;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 CONST0
+ 1198 C_CALL1 gc_compaction
+ 1200 CONST0
+ 1201 PUSHGETGLOBALFIELD Pervasives, 68
+ 1204 APPLY1
+ 1205 ATOM0
+ 1206 SETGLOBAL T330-compact-2
+ 1208 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t330-compact-3.ml b/testsuite/tests/tool-ocaml/t330-compact-3.ml
new file mode 100644
index 0000000000..f25c64ef0a
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t330-compact-3.ml
@@ -0,0 +1,1589 @@
+open Lib;;
+let rec f n =
+ if n <= 0 then []
+ else n :: f (n-1)
+in
+let l = f 300 in
+Gc.compact ();
+if List.fold_left (+) 0 l <> 301 * 150 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 BRANCH 2177
+ 1199 RESTART
+ 1200 GRAB 1
+ 1202 ACC1
+ 1203 BRANCHIFNOT 1213
+ 1205 ACC1
+ 1206 GETFIELD1
+ 1207 PUSHACC1
+ 1208 OFFSETINT 1
+ 1210 PUSHOFFSETCLOSURE0
+ 1211 APPTERM2 4
+ 1213 ACC0
+ 1214 RETURN 2
+ 1216 RESTART
+ 1217 GRAB 1
+ 1219 ACC0
+ 1220 BRANCHIFNOT 1251
+ 1222 CONST0
+ 1223 PUSHACC2
+ 1224 EQ
+ 1225 BRANCHIFNOT 1231
+ 1227 ACC0
+ 1228 GETFIELD0
+ 1229 RETURN 2
+ 1231 CONST0
+ 1232 PUSHACC2
+ 1233 GTINT
+ 1234 BRANCHIFNOT 1244
+ 1236 ACC1
+ 1237 OFFSETINT -1
+ 1239 PUSHACC1
+ 1240 GETFIELD1
+ 1241 PUSHOFFSETCLOSURE0
+ 1242 APPTERM2 4
+ 1244 GETGLOBAL "List.nth"
+ 1246 PUSHGETGLOBALFIELD Pervasives, 2
+ 1249 APPTERM1 3
+ 1251 GETGLOBAL "nth"
+ 1253 PUSHGETGLOBALFIELD Pervasives, 3
+ 1256 APPTERM1 3
+ 1258 RESTART
+ 1259 GRAB 1
+ 1261 ACC0
+ 1262 BRANCHIFNOT 1274
+ 1264 ACC1
+ 1265 PUSHACC1
+ 1266 GETFIELD0
+ 1267 MAKEBLOCK2 0
+ 1269 PUSHACC1
+ 1270 GETFIELD1
+ 1271 PUSHOFFSETCLOSURE0
+ 1272 APPTERM2 4
+ 1274 ACC1
+ 1275 RETURN 2
+ 1277 ACC0
+ 1278 BRANCHIFNOT 1291
+ 1280 ACC0
+ 1281 GETFIELD1
+ 1282 PUSHOFFSETCLOSURE0
+ 1283 APPLY1
+ 1284 PUSHACC1
+ 1285 GETFIELD0
+ 1286 PUSHGETGLOBALFIELD Pervasives, 16
+ 1289 APPTERM2 3
+ 1291 RETURN 1
+ 1293 RESTART
+ 1294 GRAB 1
+ 1296 ACC1
+ 1297 BRANCHIFNOT 1313
+ 1299 ACC1
+ 1300 GETFIELD0
+ 1301 PUSHACC1
+ 1302 APPLY1
+ 1303 PUSHACC2
+ 1304 GETFIELD1
+ 1305 PUSHACC2
+ 1306 PUSHOFFSETCLOSURE0
+ 1307 APPLY2
+ 1308 PUSHACC1
+ 1309 MAKEBLOCK2 0
+ 1311 POP 1
+ 1313 RETURN 2
+ 1315 RESTART
+ 1316 GRAB 1
+ 1318 ACC1
+ 1319 BRANCHIFNOT 1331
+ 1321 ACC1
+ 1322 GETFIELD0
+ 1323 PUSHACC1
+ 1324 APPLY1
+ 1325 ACC1
+ 1326 GETFIELD1
+ 1327 PUSHACC1
+ 1328 PUSHOFFSETCLOSURE0
+ 1329 APPTERM2 4
+ 1331 RETURN 2
+ 1333 RESTART
+ 1334 GRAB 2
+ 1336 ACC2
+ 1337 BRANCHIFNOT 1350
+ 1339 ACC2
+ 1340 GETFIELD1
+ 1341 PUSHACC3
+ 1342 GETFIELD0
+ 1343 PUSHACC3
+ 1344 PUSHACC3
+ 1345 APPLY2
+ 1346 PUSHACC2
+ 1347 PUSHOFFSETCLOSURE0
+ 1348 APPTERM3 6
+ 1350 ACC1
+ 1351 RETURN 3
+ 1353 RESTART
+ 1354 GRAB 2
+ 1356 ACC1
+ 1357 BRANCHIFNOT 1370
+ 1359 ACC2
+ 1360 PUSHACC2
+ 1361 GETFIELD1
+ 1362 PUSHACC2
+ 1363 PUSHOFFSETCLOSURE0
+ 1364 APPLY3
+ 1365 PUSHACC2
+ 1366 GETFIELD0
+ 1367 PUSHACC2
+ 1368 APPTERM2 5
+ 1370 ACC2
+ 1371 RETURN 3
+ 1373 RESTART
+ 1374 GRAB 2
+ 1376 ACC1
+ 1377 BRANCHIFNOT 1400
+ 1379 ACC2
+ 1380 BRANCHIFNOT 1407
+ 1382 ACC2
+ 1383 GETFIELD0
+ 1384 PUSHACC2
+ 1385 GETFIELD0
+ 1386 PUSHACC2
+ 1387 APPLY2
+ 1388 PUSHACC3
+ 1389 GETFIELD1
+ 1390 PUSHACC3
+ 1391 GETFIELD1
+ 1392 PUSHACC3
+ 1393 PUSHOFFSETCLOSURE0
+ 1394 APPLY3
+ 1395 PUSHACC1
+ 1396 MAKEBLOCK2 0
+ 1398 RETURN 4
+ 1400 ACC2
+ 1401 BRANCHIFNOT 1405
+ 1403 BRANCH 1407
+ 1405 RETURN 3
+ 1407 GETGLOBAL "List.map2"
+ 1409 PUSHGETGLOBALFIELD Pervasives, 2
+ 1412 APPTERM1 4
+ 1414 RESTART
+ 1415 GRAB 2
+ 1417 ACC1
+ 1418 BRANCHIFNOT 1437
+ 1420 ACC2
+ 1421 BRANCHIFNOT 1444
+ 1423 ACC2
+ 1424 GETFIELD0
+ 1425 PUSHACC2
+ 1426 GETFIELD0
+ 1427 PUSHACC2
+ 1428 APPLY2
+ 1429 ACC2
+ 1430 GETFIELD1
+ 1431 PUSHACC2
+ 1432 GETFIELD1
+ 1433 PUSHACC2
+ 1434 PUSHOFFSETCLOSURE0
+ 1435 APPTERM3 6
+ 1437 ACC2
+ 1438 BRANCHIFNOT 1442
+ 1440 BRANCH 1444
+ 1442 RETURN 3
+ 1444 GETGLOBAL "List.iter2"
+ 1446 PUSHGETGLOBALFIELD Pervasives, 2
+ 1449 APPTERM1 4
+ 1451 RESTART
+ 1452 GRAB 3
+ 1454 ACC2
+ 1455 BRANCHIFNOT 1476
+ 1457 ACC3
+ 1458 BRANCHIFNOT 1482
+ 1460 ACC3
+ 1461 GETFIELD1
+ 1462 PUSHACC3
+ 1463 GETFIELD1
+ 1464 PUSHACC5
+ 1465 GETFIELD0
+ 1466 PUSHACC5
+ 1467 GETFIELD0
+ 1468 PUSHACC5
+ 1469 PUSHACC5
+ 1470 APPLY3
+ 1471 PUSHACC3
+ 1472 PUSHOFFSETCLOSURE0
+ 1473 APPTERM 4, 8
+ 1476 ACC3
+ 1477 BRANCHIF 1482
+ 1479 ACC1
+ 1480 RETURN 4
+ 1482 GETGLOBAL "List.fold_left2"
+ 1484 PUSHGETGLOBALFIELD Pervasives, 2
+ 1487 APPTERM1 5
+ 1489 RESTART
+ 1490 GRAB 3
+ 1492 ACC1
+ 1493 BRANCHIFNOT 1516
+ 1495 ACC2
+ 1496 BRANCHIFNOT 1522
+ 1498 PUSH_RETADDR 1509
+ 1500 ACC6
+ 1501 PUSHACC6
+ 1502 GETFIELD1
+ 1503 PUSHACC6
+ 1504 GETFIELD1
+ 1505 PUSHACC6
+ 1506 PUSHOFFSETCLOSURE0
+ 1507 APPLY 4
+ 1509 PUSHACC3
+ 1510 GETFIELD0
+ 1511 PUSHACC3
+ 1512 GETFIELD0
+ 1513 PUSHACC3
+ 1514 APPTERM3 7
+ 1516 ACC2
+ 1517 BRANCHIF 1522
+ 1519 ACC3
+ 1520 RETURN 4
+ 1522 GETGLOBAL "List.fold_right2"
+ 1524 PUSHGETGLOBALFIELD Pervasives, 2
+ 1527 APPTERM1 5
+ 1529 RESTART
+ 1530 GRAB 1
+ 1532 ACC1
+ 1533 BRANCHIFNOT 1549
+ 1535 ACC1
+ 1536 GETFIELD0
+ 1537 PUSHACC1
+ 1538 APPLY1
+ 1539 BRANCHIFNOT 1547
+ 1541 ACC1
+ 1542 GETFIELD1
+ 1543 PUSHACC1
+ 1544 PUSHOFFSETCLOSURE0
+ 1545 APPTERM2 4
+ 1547 RETURN 2
+ 1549 CONST1
+ 1550 RETURN 2
+ 1552 RESTART
+ 1553 GRAB 1
+ 1555 ACC1
+ 1556 BRANCHIFNOT 1570
+ 1558 ACC1
+ 1559 GETFIELD0
+ 1560 PUSHACC1
+ 1561 APPLY1
+ 1562 BRANCHIF 1570
+ 1564 ACC1
+ 1565 GETFIELD1
+ 1566 PUSHACC1
+ 1567 PUSHOFFSETCLOSURE0
+ 1568 APPTERM2 4
+ 1570 RETURN 2
+ 1572 RESTART
+ 1573 GRAB 2
+ 1575 ACC1
+ 1576 BRANCHIFNOT 1599
+ 1578 ACC2
+ 1579 BRANCHIFNOT 1605
+ 1581 ACC2
+ 1582 GETFIELD0
+ 1583 PUSHACC2
+ 1584 GETFIELD0
+ 1585 PUSHACC2
+ 1586 APPLY2
+ 1587 BRANCHIFNOT 1597
+ 1589 ACC2
+ 1590 GETFIELD1
+ 1591 PUSHACC2
+ 1592 GETFIELD1
+ 1593 PUSHACC2
+ 1594 PUSHOFFSETCLOSURE0
+ 1595 APPTERM3 6
+ 1597 RETURN 3
+ 1599 ACC2
+ 1600 BRANCHIF 1605
+ 1602 CONST1
+ 1603 RETURN 3
+ 1605 GETGLOBAL "List.for_all2"
+ 1607 PUSHGETGLOBALFIELD Pervasives, 2
+ 1610 APPTERM1 4
+ 1612 RESTART
+ 1613 GRAB 2
+ 1615 ACC1
+ 1616 BRANCHIFNOT 1639
+ 1618 ACC2
+ 1619 BRANCHIFNOT 1646
+ 1621 ACC2
+ 1622 GETFIELD0
+ 1623 PUSHACC2
+ 1624 GETFIELD0
+ 1625 PUSHACC2
+ 1626 APPLY2
+ 1627 BRANCHIF 1637
+ 1629 ACC2
+ 1630 GETFIELD1
+ 1631 PUSHACC2
+ 1632 GETFIELD1
+ 1633 PUSHACC2
+ 1634 PUSHOFFSETCLOSURE0
+ 1635 APPTERM3 6
+ 1637 RETURN 3
+ 1639 ACC2
+ 1640 BRANCHIFNOT 1644
+ 1642 BRANCH 1646
+ 1644 RETURN 3
+ 1646 GETGLOBAL "List.exists2"
+ 1648 PUSHGETGLOBALFIELD Pervasives, 2
+ 1651 APPTERM1 4
+ 1653 RESTART
+ 1654 GRAB 1
+ 1656 ACC1
+ 1657 BRANCHIFNOT 1672
+ 1659 ACC0
+ 1660 PUSHACC2
+ 1661 GETFIELD0
+ 1662 C_CALL2 equal
+ 1664 BRANCHIF 1672
+ 1666 ACC1
+ 1667 GETFIELD1
+ 1668 PUSHACC1
+ 1669 PUSHOFFSETCLOSURE0
+ 1670 APPTERM2 4
+ 1672 RETURN 2
+ 1674 RESTART
+ 1675 GRAB 1
+ 1677 ACC1
+ 1678 BRANCHIFNOT 1692
+ 1680 ACC0
+ 1681 PUSHACC2
+ 1682 GETFIELD0
+ 1683 EQ
+ 1684 BRANCHIF 1692
+ 1686 ACC1
+ 1687 GETFIELD1
+ 1688 PUSHACC1
+ 1689 PUSHOFFSETCLOSURE0
+ 1690 APPTERM2 4
+ 1692 RETURN 2
+ 1694 RESTART
+ 1695 GRAB 1
+ 1697 ACC1
+ 1698 BRANCHIFNOT 1719
+ 1700 ACC1
+ 1701 GETFIELD0
+ 1702 PUSHACC1
+ 1703 PUSHACC1
+ 1704 GETFIELD0
+ 1705 C_CALL2 equal
+ 1707 BRANCHIFNOT 1713
+ 1709 ACC0
+ 1710 GETFIELD1
+ 1711 RETURN 3
+ 1713 ACC2
+ 1714 GETFIELD1
+ 1715 PUSHACC2
+ 1716 PUSHOFFSETCLOSURE0
+ 1717 APPTERM2 5
+ 1719 GETGLOBAL Not_found
+ 1721 MAKEBLOCK1 0
+ 1723 RAISE
+ 1724 RESTART
+ 1725 GRAB 1
+ 1727 ACC1
+ 1728 BRANCHIFNOT 1748
+ 1730 ACC1
+ 1731 GETFIELD0
+ 1732 PUSHACC1
+ 1733 PUSHACC1
+ 1734 GETFIELD0
+ 1735 EQ
+ 1736 BRANCHIFNOT 1742
+ 1738 ACC0
+ 1739 GETFIELD1
+ 1740 RETURN 3
+ 1742 ACC2
+ 1743 GETFIELD1
+ 1744 PUSHACC2
+ 1745 PUSHOFFSETCLOSURE0
+ 1746 APPTERM2 5
+ 1748 GETGLOBAL Not_found
+ 1750 MAKEBLOCK1 0
+ 1752 RAISE
+ 1753 RESTART
+ 1754 GRAB 1
+ 1756 ACC1
+ 1757 BRANCHIFNOT 1773
+ 1759 ACC0
+ 1760 PUSHACC2
+ 1761 GETFIELD0
+ 1762 GETFIELD0
+ 1763 C_CALL2 equal
+ 1765 BRANCHIF 1773
+ 1767 ACC1
+ 1768 GETFIELD1
+ 1769 PUSHACC1
+ 1770 PUSHOFFSETCLOSURE0
+ 1771 APPTERM2 4
+ 1773 RETURN 2
+ 1775 RESTART
+ 1776 GRAB 1
+ 1778 ACC1
+ 1779 BRANCHIFNOT 1794
+ 1781 ACC0
+ 1782 PUSHACC2
+ 1783 GETFIELD0
+ 1784 GETFIELD0
+ 1785 EQ
+ 1786 BRANCHIF 1794
+ 1788 ACC1
+ 1789 GETFIELD1
+ 1790 PUSHACC1
+ 1791 PUSHOFFSETCLOSURE0
+ 1792 APPTERM2 4
+ 1794 RETURN 2
+ 1796 RESTART
+ 1797 GRAB 1
+ 1799 ACC1
+ 1800 BRANCHIFNOT 1825
+ 1802 ACC1
+ 1803 GETFIELD0
+ 1804 PUSHACC2
+ 1805 GETFIELD1
+ 1806 PUSHACC2
+ 1807 PUSHACC2
+ 1808 GETFIELD0
+ 1809 C_CALL2 equal
+ 1811 BRANCHIFNOT 1816
+ 1813 ACC0
+ 1814 RETURN 4
+ 1816 ACC0
+ 1817 PUSHACC3
+ 1818 PUSHOFFSETCLOSURE0
+ 1819 APPLY2
+ 1820 PUSHACC2
+ 1821 MAKEBLOCK2 0
+ 1823 POP 2
+ 1825 RETURN 2
+ 1827 RESTART
+ 1828 GRAB 1
+ 1830 ACC1
+ 1831 BRANCHIFNOT 1855
+ 1833 ACC1
+ 1834 GETFIELD0
+ 1835 PUSHACC2
+ 1836 GETFIELD1
+ 1837 PUSHACC2
+ 1838 PUSHACC2
+ 1839 GETFIELD0
+ 1840 EQ
+ 1841 BRANCHIFNOT 1846
+ 1843 ACC0
+ 1844 RETURN 4
+ 1846 ACC0
+ 1847 PUSHACC3
+ 1848 PUSHOFFSETCLOSURE0
+ 1849 APPLY2
+ 1850 PUSHACC2
+ 1851 MAKEBLOCK2 0
+ 1853 POP 2
+ 1855 RETURN 2
+ 1857 RESTART
+ 1858 GRAB 1
+ 1860 ACC1
+ 1861 BRANCHIFNOT 1879
+ 1863 ACC1
+ 1864 GETFIELD0
+ 1865 PUSHACC0
+ 1866 PUSHACC2
+ 1867 APPLY1
+ 1868 BRANCHIFNOT 1873
+ 1870 ACC0
+ 1871 RETURN 3
+ 1873 ACC2
+ 1874 GETFIELD1
+ 1875 PUSHACC2
+ 1876 PUSHOFFSETCLOSURE0
+ 1877 APPTERM2 5
+ 1879 GETGLOBAL Not_found
+ 1881 MAKEBLOCK1 0
+ 1883 RAISE
+ 1884 RESTART
+ 1885 GRAB 2
+ 1887 ACC2
+ 1888 BRANCHIFNOT 1917
+ 1890 ACC2
+ 1891 GETFIELD0
+ 1892 PUSHACC3
+ 1893 GETFIELD1
+ 1894 PUSHACC1
+ 1895 PUSHENVACC2
+ 1896 APPLY1
+ 1897 BRANCHIFNOT 1908
+ 1899 ACC0
+ 1900 PUSHACC4
+ 1901 PUSHACC4
+ 1902 PUSHACC4
+ 1903 MAKEBLOCK2 0
+ 1905 PUSHOFFSETCLOSURE0
+ 1906 APPTERM3 8
+ 1908 ACC0
+ 1909 PUSHACC4
+ 1910 PUSHACC3
+ 1911 MAKEBLOCK2 0
+ 1913 PUSHACC4
+ 1914 PUSHOFFSETCLOSURE0
+ 1915 APPTERM3 8
+ 1917 ACC1
+ 1918 PUSHENVACC1
+ 1919 APPLY1
+ 1920 PUSHACC1
+ 1921 PUSHENVACC1
+ 1922 APPLY1
+ 1923 MAKEBLOCK2 0
+ 1925 RETURN 3
+ 1927 RESTART
+ 1928 GRAB 1
+ 1930 ACC0
+ 1931 PUSHENVACC1
+ 1932 CLOSUREREC 2, 1885
+ 1936 ACC2
+ 1937 PUSHCONST0
+ 1938 PUSHCONST0
+ 1939 PUSHACC3
+ 1940 APPTERM3 6
+ 1942 ACC0
+ 1943 BRANCHIFNOT 1967
+ 1945 ACC0
+ 1946 GETFIELD0
+ 1947 PUSHACC1
+ 1948 GETFIELD1
+ 1949 PUSHOFFSETCLOSURE0
+ 1950 APPLY1
+ 1951 PUSHACC0
+ 1952 GETFIELD1
+ 1953 PUSHACC2
+ 1954 GETFIELD1
+ 1955 MAKEBLOCK2 0
+ 1957 PUSHACC1
+ 1958 GETFIELD0
+ 1959 PUSHACC3
+ 1960 GETFIELD0
+ 1961 MAKEBLOCK2 0
+ 1963 MAKEBLOCK2 0
+ 1965 RETURN 3
+ 1967 GETGLOBAL <0>(0, 0)
+ 1969 RETURN 1
+ 1971 RESTART
+ 1972 GRAB 1
+ 1974 ACC0
+ 1975 BRANCHIFNOT 1996
+ 1977 ACC1
+ 1978 BRANCHIFNOT 2003
+ 1980 ACC1
+ 1981 GETFIELD1
+ 1982 PUSHACC1
+ 1983 GETFIELD1
+ 1984 PUSHOFFSETCLOSURE0
+ 1985 APPLY2
+ 1986 PUSHACC2
+ 1987 GETFIELD0
+ 1988 PUSHACC2
+ 1989 GETFIELD0
+ 1990 MAKEBLOCK2 0
+ 1992 MAKEBLOCK2 0
+ 1994 RETURN 2
+ 1996 ACC1
+ 1997 BRANCHIFNOT 2001
+ 1999 BRANCH 2003
+ 2001 RETURN 2
+ 2003 GETGLOBAL "List.combine"
+ 2005 PUSHGETGLOBALFIELD Pervasives, 2
+ 2008 APPTERM1 3
+ 2010 RESTART
+ 2011 GRAB 1
+ 2013 ACC1
+ 2014 BRANCHIFNOT 2038
+ 2016 ACC1
+ 2017 GETFIELD0
+ 2018 PUSHACC2
+ 2019 GETFIELD1
+ 2020 PUSHACC1
+ 2021 PUSHENVACC2
+ 2022 APPLY1
+ 2023 BRANCHIFNOT 2033
+ 2025 ACC0
+ 2026 PUSHACC3
+ 2027 PUSHACC3
+ 2028 MAKEBLOCK2 0
+ 2030 PUSHOFFSETCLOSURE0
+ 2031 APPTERM2 6
+ 2033 ACC0
+ 2034 PUSHACC3
+ 2035 PUSHOFFSETCLOSURE0
+ 2036 APPTERM2 6
+ 2038 ACC0
+ 2039 PUSHENVACC1
+ 2040 APPTERM1 3
+ 2042 ACC0
+ 2043 PUSHENVACC1
+ 2044 CLOSUREREC 2, 2011
+ 2048 CONST0
+ 2049 PUSHACC1
+ 2050 APPTERM1 3
+ 2052 RESTART
+ 2053 GRAB 2
+ 2055 ACC1
+ 2056 BRANCHIFNOT 2077
+ 2058 ACC2
+ 2059 BRANCHIFNOT 2084
+ 2061 ACC2
+ 2062 GETFIELD1
+ 2063 PUSHACC2
+ 2064 GETFIELD1
+ 2065 PUSHACC2
+ 2066 PUSHACC5
+ 2067 GETFIELD0
+ 2068 PUSHACC5
+ 2069 GETFIELD0
+ 2070 PUSHENVACC1
+ 2071 APPLY2
+ 2072 MAKEBLOCK2 0
+ 2074 PUSHOFFSETCLOSURE0
+ 2075 APPTERM3 6
+ 2077 ACC2
+ 2078 BRANCHIFNOT 2082
+ 2080 BRANCH 2084
+ 2082 RETURN 3
+ 2084 GETGLOBAL "List.rev_map2"
+ 2086 PUSHGETGLOBALFIELD Pervasives, 2
+ 2089 APPTERM1 4
+ 2091 RESTART
+ 2092 GRAB 2
+ 2094 ACC0
+ 2095 CLOSUREREC 1, 2053
+ 2099 ACC3
+ 2100 PUSHACC3
+ 2101 PUSHCONST0
+ 2102 PUSHACC3
+ 2103 APPTERM3 7
+ 2105 RESTART
+ 2106 GRAB 1
+ 2108 ACC1
+ 2109 BRANCHIFNOT 2123
+ 2111 ACC1
+ 2112 GETFIELD1
+ 2113 PUSHACC1
+ 2114 PUSHACC3
+ 2115 GETFIELD0
+ 2116 PUSHENVACC1
+ 2117 APPLY1
+ 2118 MAKEBLOCK2 0
+ 2120 PUSHOFFSETCLOSURE0
+ 2121 APPTERM2 4
+ 2123 ACC0
+ 2124 RETURN 2
+ 2126 RESTART
+ 2127 GRAB 1
+ 2129 ACC0
+ 2130 CLOSUREREC 1, 2106
+ 2134 ACC2
+ 2135 PUSHCONST0
+ 2136 PUSHACC2
+ 2137 APPTERM2 5
+ 2139 CONST0
+ 2140 PUSHACC1
+ 2141 PUSHENVACC1
+ 2142 APPTERM2 3
+ 2144 ACC0
+ 2145 BRANCHIFNOT 2151
+ 2147 ACC0
+ 2148 GETFIELD1
+ 2149 RETURN 1
+ 2151 GETGLOBAL "tl"
+ 2153 PUSHGETGLOBALFIELD Pervasives, 3
+ 2156 APPTERM1 2
+ 2158 ACC0
+ 2159 BRANCHIFNOT 2165
+ 2161 ACC0
+ 2162 GETFIELD0
+ 2163 RETURN 1
+ 2165 GETGLOBAL "hd"
+ 2167 PUSHGETGLOBALFIELD Pervasives, 3
+ 2170 APPTERM1 2
+ 2172 ACC0
+ 2173 PUSHCONST0
+ 2174 PUSHENVACC1
+ 2175 APPTERM2 3
+ 2177 CLOSUREREC 0, 1200
+ 2181 ACC0
+ 2182 CLOSURE 1, 2172
+ 2185 PUSH
+ 2186 CLOSURE 0, 2158
+ 2189 PUSH
+ 2190 CLOSURE 0, 2144
+ 2193 PUSH
+ 2194 CLOSUREREC 0, 1217
+ 2198 GETGLOBALFIELD Pervasives, 16
+ 2201 PUSH
+ 2202 CLOSUREREC 0, 1259
+ 2206 ACC0
+ 2207 CLOSURE 1, 2139
+ 2210 PUSH
+ 2211 CLOSUREREC 0, 1277
+ 2215 CLOSUREREC 0, 1294
+ 2219 CLOSURE 0, 2127
+ 2222 PUSH
+ 2223 CLOSUREREC 0, 1316
+ 2227 CLOSUREREC 0, 1334
+ 2231 CLOSUREREC 0, 1354
+ 2235 CLOSUREREC 0, 1374
+ 2239 CLOSURE 0, 2092
+ 2242 PUSH
+ 2243 CLOSUREREC 0, 1415
+ 2247 CLOSUREREC 0, 1452
+ 2251 CLOSUREREC 0, 1490
+ 2255 CLOSUREREC 0, 1530
+ 2259 CLOSUREREC 0, 1553
+ 2263 CLOSUREREC 0, 1573
+ 2267 CLOSUREREC 0, 1613
+ 2271 CLOSUREREC 0, 1654
+ 2275 CLOSUREREC 0, 1675
+ 2279 CLOSUREREC 0, 1695
+ 2283 CLOSUREREC 0, 1725
+ 2287 CLOSUREREC 0, 1754
+ 2291 CLOSUREREC 0, 1776
+ 2295 CLOSUREREC 0, 1797
+ 2299 CLOSUREREC 0, 1828
+ 2303 CLOSUREREC 0, 1858
+ 2307 ACC 24
+ 2309 CLOSURE 1, 2042
+ 2312 PUSHACC 25
+ 2314 CLOSUREREC 1, 1928
+ 2318 CLOSUREREC 0, 1942
+ 2322 CLOSUREREC 0, 1972
+ 2326 ACC0
+ 2327 PUSHACC2
+ 2328 PUSHACC7
+ 2329 PUSHACC 9
+ 2331 PUSHACC 11
+ 2333 PUSHACC 13
+ 2335 PUSHACC 15
+ 2337 PUSHACC 17
+ 2339 PUSHACC 10
+ 2341 PUSHACC 12
+ 2343 PUSHACC 13
+ 2345 PUSHACC 15
+ 2347 PUSHACC 23
+ 2349 PUSHACC 25
+ 2351 PUSHACC 27
+ 2353 PUSHACC 29
+ 2355 PUSHACC 31
+ 2357 PUSHACC 33
+ 2359 PUSHACC 35
+ 2361 PUSHACC 37
+ 2363 PUSHACC 40
+ 2365 PUSHACC 42
+ 2367 PUSHACC 41
+ 2369 PUSHACC 45
+ 2371 PUSHACC 47
+ 2373 PUSHACC 50
+ 2375 PUSHACC 52
+ 2377 PUSHACC 51
+ 2379 PUSHACC 55
+ 2381 PUSHACC 56
+ 2383 PUSHACC 59
+ 2385 PUSHACC 61
+ 2387 PUSHACC 60
+ 2389 PUSHACC 64
+ 2391 PUSHACC 66
+ 2393 PUSHACC 68
+ 2395 PUSHACC 70
+ 2397 MAKEBLOCK 37, 0
+ 2400 POP 36
+ 2402 SETGLOBAL List
+ 2404 BRANCH 2432
+ 2406 CONST0
+ 2407 PUSHACC1
+ 2408 LEINT
+ 2409 BRANCHIFNOT 2414
+ 2411 CONST0
+ 2412 RETURN 1
+ 2414 ACC0
+ 2415 OFFSETINT -1
+ 2417 PUSHOFFSETCLOSURE0
+ 2418 APPLY1
+ 2419 PUSHACC1
+ 2420 MAKEBLOCK2 0
+ 2422 RETURN 1
+ 2424 RESTART
+ 2425 GRAB 1
+ 2427 ACC1
+ 2428 PUSHACC1
+ 2429 ADDINT
+ 2430 RETURN 2
+ 2432 CLOSUREREC 0, 2406
+ 2436 CONSTINT 300
+ 2438 PUSHACC1
+ 2439 APPLY1
+ 2440 PUSHCONST0
+ 2441 C_CALL1 gc_compaction
+ 2443 CONSTINT 150
+ 2445 PUSHCONSTINT 301
+ 2447 MULINT
+ 2448 PUSHACC1
+ 2449 PUSHCONST0
+ 2450 PUSH
+ 2451 CLOSURE 0, 2425
+ 2454 PUSHGETGLOBALFIELD List, 12
+ 2457 APPLY3
+ 2458 NEQ
+ 2459 BRANCHIFNOT 2466
+ 2461 GETGLOBAL Not_found
+ 2463 MAKEBLOCK1 0
+ 2465 RAISE
+ 2466 POP 2
+ 2468 ATOM0
+ 2469 SETGLOBAL T330-compact-3
+ 2471 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t330-compact-4.ml b/testsuite/tests/tool-ocaml/t330-compact-4.ml
new file mode 100644
index 0000000000..1c190f7505
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t330-compact-4.ml
@@ -0,0 +1,1589 @@
+open Lib;;
+let rec f n =
+ if n <= 0 then []
+ else n :: f (n-1)
+in
+Gc.compact ();
+let l = f 300 in
+if List.fold_left (+) 0 l <> 301 * 150 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 746
+ 11 RESTART
+ 12 GRAB 1
+ 14 ACC0
+ 15 BRANCHIFNOT 28
+ 17 ACC1
+ 18 PUSHACC1
+ 19 GETFIELD1
+ 20 PUSHOFFSETCLOSURE0
+ 21 APPLY2
+ 22 PUSHACC1
+ 23 GETFIELD0
+ 24 MAKEBLOCK2 0
+ 26 RETURN 2
+ 28 ACC1
+ 29 RETURN 2
+ 31 RESTART
+ 32 GRAB 3
+ 34 CONST0
+ 35 PUSHACC4
+ 36 LEINT
+ 37 BRANCHIFNOT 42
+ 39 CONST0
+ 40 RETURN 4
+ 42 ACC3
+ 43 PUSHACC3
+ 44 PUSHACC3
+ 45 PUSHACC3
+ 46 C_CALL4 caml_input
+ 48 PUSHCONST0
+ 49 PUSHACC1
+ 50 EQ
+ 51 BRANCHIFNOT 58
+ 53 GETGLOBAL End_of_file
+ 55 MAKEBLOCK1 0
+ 57 RAISE
+ 58 ACC0
+ 59 PUSHACC5
+ 60 SUBINT
+ 61 PUSHACC1
+ 62 PUSHACC5
+ 63 ADDINT
+ 64 PUSHACC4
+ 65 PUSHACC4
+ 66 PUSHOFFSETCLOSURE0
+ 67 APPTERM 4, 9
+ 70 ACC0
+ 71 C_CALL1 caml_input_scan_line
+ 73 PUSHCONST0
+ 74 PUSHACC1
+ 75 EQ
+ 76 BRANCHIFNOT 83
+ 78 GETGLOBAL End_of_file
+ 80 MAKEBLOCK1 0
+ 82 RAISE
+ 83 CONST0
+ 84 PUSHACC1
+ 85 GTINT
+ 86 BRANCHIFNOT 107
+ 88 ACC0
+ 89 OFFSETINT -1
+ 91 C_CALL1 create_string
+ 93 PUSHACC1
+ 94 OFFSETINT -1
+ 96 PUSHCONST0
+ 97 PUSHACC2
+ 98 PUSHACC5
+ 99 C_CALL4 caml_input
+ 101 ACC2
+ 102 C_CALL1 caml_input_char
+ 104 ACC0
+ 105 RETURN 3
+ 107 ACC0
+ 108 NEGINT
+ 109 C_CALL1 create_string
+ 111 PUSHACC1
+ 112 NEGINT
+ 113 PUSHCONST0
+ 114 PUSHACC2
+ 115 PUSHACC5
+ 116 C_CALL4 caml_input
+ 118 CONST0
+ 119 PUSHTRAP 130
+ 121 ACC6
+ 122 PUSHOFFSETCLOSURE0
+ 123 APPLY1
+ 124 PUSHACC5
+ 125 PUSHENVACC1
+ 126 APPLY2
+ 127 POPTRAP
+ 128 RETURN 3
+ 130 PUSHGETGLOBAL End_of_file
+ 132 PUSHACC1
+ 133 GETFIELD0
+ 134 EQ
+ 135 BRANCHIFNOT 140
+ 137 ACC1
+ 138 RETURN 4
+ 140 ACC0
+ 141 RAISE
+ 142 ACC0
+ 143 C_CALL1 caml_flush
+ 145 RETURN 1
+ 147 RESTART
+ 148 GRAB 1
+ 150 ACC1
+ 151 PUSHACC1
+ 152 C_CALL2 caml_output_char
+ 154 RETURN 2
+ 156 RESTART
+ 157 GRAB 1
+ 159 ACC1
+ 160 PUSHACC1
+ 161 C_CALL2 caml_output_char
+ 163 RETURN 2
+ 165 RESTART
+ 166 GRAB 1
+ 168 ACC1
+ 169 PUSHACC1
+ 170 C_CALL2 caml_output_int
+ 172 RETURN 2
+ 174 RESTART
+ 175 GRAB 1
+ 177 ACC1
+ 178 PUSHACC1
+ 179 C_CALL2 caml_seek_out
+ 181 RETURN 2
+ 183 ACC0
+ 184 C_CALL1 caml_pos_out
+ 186 RETURN 1
+ 188 ACC0
+ 189 C_CALL1 caml_channel_size
+ 191 RETURN 1
+ 193 RESTART
+ 194 GRAB 1
+ 196 ACC1
+ 197 PUSHACC1
+ 198 C_CALL2 caml_set_binary_mode
+ 200 RETURN 2
+ 202 ACC0
+ 203 C_CALL1 caml_input_char
+ 205 RETURN 1
+ 207 ACC0
+ 208 C_CALL1 caml_input_char
+ 210 RETURN 1
+ 212 ACC0
+ 213 C_CALL1 caml_input_int
+ 215 RETURN 1
+ 217 ACC0
+ 218 C_CALL1 input_value
+ 220 RETURN 1
+ 222 RESTART
+ 223 GRAB 1
+ 225 ACC1
+ 226 PUSHACC1
+ 227 C_CALL2 caml_seek_in
+ 229 RETURN 2
+ 231 ACC0
+ 232 C_CALL1 caml_pos_in
+ 234 RETURN 1
+ 236 ACC0
+ 237 C_CALL1 caml_channel_size
+ 239 RETURN 1
+ 241 ACC0
+ 242 C_CALL1 caml_close_channel
+ 244 RETURN 1
+ 246 RESTART
+ 247 GRAB 1
+ 249 ACC1
+ 250 PUSHACC1
+ 251 C_CALL2 caml_set_binary_mode
+ 253 RETURN 2
+ 255 CONST0
+ 256 PUSHENVACC1
+ 257 APPLY1
+ 258 ACC0
+ 259 C_CALL1 sys_exit
+ 261 RETURN 1
+ 263 CONST0
+ 264 PUSHENVACC1
+ 265 GETFIELD0
+ 266 APPTERM1 2
+ 268 CONST0
+ 269 PUSHENVACC1
+ 270 APPLY1
+ 271 CONST0
+ 272 PUSHENVACC2
+ 273 APPTERM1 2
+ 275 ENVACC1
+ 276 GETFIELD0
+ 277 PUSHACC0
+ 278 PUSHACC2
+ 279 CLOSURE 2, 268
+ 282 PUSHENVACC1
+ 283 SETFIELD0
+ 284 RETURN 2
+ 286 ENVACC1
+ 287 C_CALL1 caml_flush
+ 289 ENVACC2
+ 290 C_CALL1 caml_flush
+ 292 RETURN 1
+ 294 CONST0
+ 295 PUSHENVACC1
+ 296 APPLY1
+ 297 C_CALL1 float_of_string
+ 299 RETURN 1
+ 301 CONST0
+ 302 PUSHENVACC1
+ 303 APPLY1
+ 304 C_CALL1 int_of_string
+ 306 RETURN 1
+ 308 ENVACC2
+ 309 C_CALL1 caml_flush
+ 311 ENVACC1
+ 312 PUSHENVACC3
+ 313 APPTERM1 2
+ 315 CONSTINT 13
+ 317 PUSHENVACC1
+ 318 C_CALL2 caml_output_char
+ 320 ENVACC1
+ 321 C_CALL1 caml_flush
+ 323 RETURN 1
+ 325 ACC0
+ 326 PUSHENVACC1
+ 327 PUSHENVACC2
+ 328 APPLY2
+ 329 CONSTINT 13
+ 331 PUSHENVACC1
+ 332 C_CALL2 caml_output_char
+ 334 ENVACC1
+ 335 C_CALL1 caml_flush
+ 337 RETURN 1
+ 339 ACC0
+ 340 PUSHENVACC1
+ 341 APPLY1
+ 342 PUSHENVACC2
+ 343 PUSHENVACC3
+ 344 APPTERM2 3
+ 346 ACC0
+ 347 PUSHENVACC1
+ 348 APPLY1
+ 349 PUSHENVACC2
+ 350 PUSHENVACC3
+ 351 APPTERM2 3
+ 353 ACC0
+ 354 PUSHENVACC1
+ 355 PUSHENVACC2
+ 356 APPTERM2 3
+ 358 ACC0
+ 359 PUSHENVACC1
+ 360 C_CALL2 caml_output_char
+ 362 RETURN 1
+ 364 CONSTINT 13
+ 366 PUSHENVACC1
+ 367 C_CALL2 caml_output_char
+ 369 ENVACC1
+ 370 C_CALL1 caml_flush
+ 372 RETURN 1
+ 374 ACC0
+ 375 PUSHENVACC1
+ 376 PUSHENVACC2
+ 377 APPLY2
+ 378 CONSTINT 13
+ 380 PUSHENVACC1
+ 381 C_CALL2 caml_output_char
+ 383 RETURN 1
+ 385 ACC0
+ 386 PUSHENVACC1
+ 387 APPLY1
+ 388 PUSHENVACC2
+ 389 PUSHENVACC3
+ 390 APPTERM2 3
+ 392 ACC0
+ 393 PUSHENVACC1
+ 394 APPLY1
+ 395 PUSHENVACC2
+ 396 PUSHENVACC3
+ 397 APPTERM2 3
+ 399 ACC0
+ 400 PUSHENVACC1
+ 401 PUSHENVACC2
+ 402 APPTERM2 3
+ 404 ACC0
+ 405 PUSHENVACC1
+ 406 C_CALL2 caml_output_char
+ 408 RETURN 1
+ 410 RESTART
+ 411 GRAB 3
+ 413 CONST0
+ 414 PUSHACC3
+ 415 LTINT
+ 416 BRANCHIF 427
+ 418 ACC1
+ 419 C_CALL1 ml_string_length
+ 421 PUSHACC4
+ 422 PUSHACC4
+ 423 ADDINT
+ 424 GTINT
+ 425 BRANCHIFNOT 432
+ 427 GETGLOBAL "really_input"
+ 429 PUSHENVACC1
+ 430 APPTERM1 5
+ 432 ACC3
+ 433 PUSHACC3
+ 434 PUSHACC3
+ 435 PUSHACC3
+ 436 PUSHENVACC2
+ 437 APPTERM 4, 8
+ 440 RESTART
+ 441 GRAB 3
+ 443 CONST0
+ 444 PUSHACC3
+ 445 LTINT
+ 446 BRANCHIF 457
+ 448 ACC1
+ 449 C_CALL1 ml_string_length
+ 451 PUSHACC4
+ 452 PUSHACC4
+ 453 ADDINT
+ 454 GTINT
+ 455 BRANCHIFNOT 462
+ 457 GETGLOBAL "input"
+ 459 PUSHENVACC1
+ 460 APPTERM1 5
+ 462 ACC3
+ 463 PUSHACC3
+ 464 PUSHACC3
+ 465 PUSHACC3
+ 466 C_CALL4 caml_input
+ 468 RETURN 4
+ 470 ACC0
+ 471 PUSHCONST0
+ 472 PUSHGETGLOBAL <0>(0, <0>(6, 0))
+ 474 PUSHENVACC1
+ 475 APPTERM3 4
+ 477 ACC0
+ 478 PUSHCONST0
+ 479 PUSHGETGLOBAL <0>(0, <0>(7, 0))
+ 481 PUSHENVACC1
+ 482 APPTERM3 4
+ 484 RESTART
+ 485 GRAB 2
+ 487 ACC1
+ 488 PUSHACC1
+ 489 PUSHACC4
+ 490 C_CALL3 sys_open
+ 492 C_CALL1 caml_open_descriptor
+ 494 RETURN 3
+ 496 ACC0
+ 497 C_CALL1 caml_flush
+ 499 ACC0
+ 500 C_CALL1 caml_close_channel
+ 502 RETURN 1
+ 504 RESTART
+ 505 GRAB 1
+ 507 CONST0
+ 508 PUSHACC2
+ 509 PUSHACC2
+ 510 C_CALL3 output_value
+ 512 RETURN 2
+ 514 RESTART
+ 515 GRAB 3
+ 517 CONST0
+ 518 PUSHACC3
+ 519 LTINT
+ 520 BRANCHIF 531
+ 522 ACC1
+ 523 C_CALL1 ml_string_length
+ 525 PUSHACC4
+ 526 PUSHACC4
+ 527 ADDINT
+ 528 GTINT
+ 529 BRANCHIFNOT 536
+ 531 GETGLOBAL "output"
+ 533 PUSHENVACC1
+ 534 APPTERM1 5
+ 536 ACC3
+ 537 PUSHACC3
+ 538 PUSHACC3
+ 539 PUSHACC3
+ 540 C_CALL4 caml_output
+ 542 RETURN 4
+ 544 RESTART
+ 545 GRAB 1
+ 547 ACC1
+ 548 C_CALL1 ml_string_length
+ 550 PUSHCONST0
+ 551 PUSHACC3
+ 552 PUSHACC3
+ 553 C_CALL4 caml_output
+ 555 RETURN 2
+ 557 ACC0
+ 558 PUSHCONSTINT 438
+ 560 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(6, 0))))
+ 562 PUSHENVACC1
+ 563 APPTERM3 4
+ 565 ACC0
+ 566 PUSHCONSTINT 438
+ 568 PUSHGETGLOBAL <0>(1, <0>(3, <0>(4, <0>(7, 0))))
+ 570 PUSHENVACC1
+ 571 APPTERM3 4
+ 573 RESTART
+ 574 GRAB 2
+ 576 ACC1
+ 577 PUSHACC1
+ 578 PUSHACC4
+ 579 C_CALL3 sys_open
+ 581 C_CALL1 caml_open_descriptor
+ 583 RETURN 3
+ 585 ACC0
+ 586 PUSHGETGLOBAL "%.12g"
+ 588 C_CALL2 format_float
+ 590 RETURN 1
+ 592 ACC0
+ 593 PUSHGETGLOBAL "%d"
+ 595 C_CALL2 format_int
+ 597 RETURN 1
+ 599 GETGLOBAL "false"
+ 601 PUSHACC1
+ 602 C_CALL2 string_equal
+ 604 BRANCHIFNOT 609
+ 606 CONST0
+ 607 RETURN 1
+ 609 GETGLOBAL "true"
+ 611 PUSHACC1
+ 612 C_CALL2 string_equal
+ 614 BRANCHIFNOT 619
+ 616 CONST1
+ 617 RETURN 1
+ 619 GETGLOBAL "bool_of_string"
+ 621 PUSHENVACC1
+ 622 APPTERM1 2
+ 624 ACC0
+ 625 BRANCHIFNOT 631
+ 627 GETGLOBAL "true"
+ 629 RETURN 1
+ 631 GETGLOBAL "false"
+ 633 RETURN 1
+ 635 CONST0
+ 636 PUSHACC1
+ 637 LTINT
+ 638 BRANCHIF 646
+ 640 CONSTINT 255
+ 642 PUSHACC1
+ 643 GTINT
+ 644 BRANCHIFNOT 651
+ 646 GETGLOBAL "char_of_int"
+ 648 PUSHENVACC1
+ 649 APPTERM1 2
+ 651 ACC0
+ 652 RETURN 1
+ 654 RESTART
+ 655 GRAB 1
+ 657 ACC0
+ 658 C_CALL1 ml_string_length
+ 660 PUSHACC2
+ 661 C_CALL1 ml_string_length
+ 663 PUSHACC0
+ 664 PUSHACC2
+ 665 ADDINT
+ 666 C_CALL1 create_string
+ 668 PUSHACC2
+ 669 PUSHCONST0
+ 670 PUSHACC2
+ 671 PUSHCONST0
+ 672 PUSHACC7
+ 673 C_CALL5 blit_string
+ 675 ACC1
+ 676 PUSHACC3
+ 677 PUSHACC2
+ 678 PUSHCONST0
+ 679 PUSHACC 8
+ 681 C_CALL5 blit_string
+ 683 ACC0
+ 684 RETURN 5
+ 686 CONSTINT -1
+ 688 PUSHACC1
+ 689 XORINT
+ 690 RETURN 1
+ 692 CONST0
+ 693 PUSHACC1
+ 694 GEINT
+ 695 BRANCHIFNOT 700
+ 697 ACC0
+ 698 RETURN 1
+ 700 ACC0
+ 701 NEGINT
+ 702 RETURN 1
+ 704 RESTART
+ 705 GRAB 1
+ 707 ACC1
+ 708 PUSHACC1
+ 709 C_CALL2 greaterequal
+ 711 BRANCHIFNOT 716
+ 713 ACC0
+ 714 RETURN 2
+ 716 ACC1
+ 717 RETURN 2
+ 719 RESTART
+ 720 GRAB 1
+ 722 ACC1
+ 723 PUSHACC1
+ 724 C_CALL2 lessequal
+ 726 BRANCHIFNOT 731
+ 728 ACC0
+ 729 RETURN 2
+ 731 ACC1
+ 732 RETURN 2
+ 734 ACC0
+ 735 PUSHGETGLOBAL Invalid_argument
+ 737 MAKEBLOCK2 0
+ 739 RAISE
+ 740 ACC0
+ 741 PUSHGETGLOBAL Failure
+ 743 MAKEBLOCK2 0
+ 745 RAISE
+ 746 CLOSURE 0, 740
+ 749 PUSH
+ 750 CLOSURE 0, 734
+ 753 PUSHGETGLOBAL "Pervasives.Exit"
+ 755 MAKEBLOCK1 0
+ 757 PUSHGETGLOBAL "Pervasives.Assert_failure"
+ 759 MAKEBLOCK1 0
+ 761 PUSH
+ 762 CLOSURE 0, 720
+ 765 PUSH
+ 766 CLOSURE 0, 705
+ 769 PUSH
+ 770 CLOSURE 0, 692
+ 773 PUSH
+ 774 CLOSURE 0, 686
+ 777 PUSHCONST0
+ 778 PUSHCONSTINT 31
+ 780 PUSHCONST1
+ 781 LSLINT
+ 782 EQ
+ 783 BRANCHIFNOT 789
+ 785 CONSTINT 30
+ 787 BRANCH 791
+ 789 CONSTINT 62
+ 791 PUSHCONST1
+ 792 LSLINT
+ 793 PUSHACC0
+ 794 OFFSETINT -1
+ 796 PUSH
+ 797 CLOSURE 0, 655
+ 800 PUSHACC 9
+ 802 CLOSURE 1, 635
+ 805 PUSH
+ 806 CLOSURE 0, 624
+ 809 PUSHACC 11
+ 811 CLOSURE 1, 599
+ 814 PUSH
+ 815 CLOSURE 0, 592
+ 818 PUSH
+ 819 CLOSURE 0, 585
+ 822 PUSH
+ 823 CLOSUREREC 0, 12
+ 827 CONST0
+ 828 C_CALL1 caml_open_descriptor
+ 830 PUSHCONST1
+ 831 C_CALL1 caml_open_descriptor
+ 833 PUSHCONST2
+ 834 C_CALL1 caml_open_descriptor
+ 836 PUSH
+ 837 CLOSURE 0, 574
+ 840 PUSHACC0
+ 841 CLOSURE 1, 565
+ 844 PUSHACC1
+ 845 CLOSURE 1, 557
+ 848 PUSH
+ 849 CLOSURE 0, 545
+ 852 PUSHACC 22
+ 854 CLOSURE 1, 515
+ 857 PUSH
+ 858 CLOSURE 0, 505
+ 861 PUSH
+ 862 CLOSURE 0, 496
+ 865 PUSH
+ 866 CLOSURE 0, 485
+ 869 PUSHACC0
+ 870 CLOSURE 1, 477
+ 873 PUSHACC1
+ 874 CLOSURE 1, 470
+ 877 PUSHACC 28
+ 879 CLOSURE 1, 441
+ 882 PUSH
+ 883 CLOSUREREC 0, 32
+ 887 ACC0
+ 888 PUSHACC 31
+ 890 CLOSURE 2, 411
+ 893 PUSHACC 22
+ 895 CLOSUREREC 1, 70
+ 899 ACC 15
+ 901 CLOSURE 1, 404
+ 904 PUSHACC 11
+ 906 PUSHACC 17
+ 908 CLOSURE 2, 399
+ 911 PUSHACC 12
+ 913 PUSHACC 18
+ 915 PUSHACC 23
+ 917 CLOSURE 3, 392
+ 920 PUSHACC 13
+ 922 PUSHACC 19
+ 924 PUSHACC 23
+ 926 CLOSURE 3, 385
+ 929 PUSHACC 14
+ 931 PUSHACC 20
+ 933 CLOSURE 2, 374
+ 936 PUSHACC 20
+ 938 CLOSURE 1, 364
+ 941 PUSHACC 20
+ 943 CLOSURE 1, 358
+ 946 PUSHACC 17
+ 948 PUSHACC 22
+ 950 CLOSURE 2, 353
+ 953 PUSHACC 18
+ 955 PUSHACC 23
+ 957 PUSHACC 29
+ 959 CLOSURE 3, 346
+ 962 PUSHACC 19
+ 964 PUSHACC 24
+ 966 PUSHACC 29
+ 968 CLOSURE 3, 339
+ 971 PUSHACC 20
+ 973 PUSHACC 25
+ 975 CLOSURE 2, 325
+ 978 PUSHACC 25
+ 980 CLOSURE 1, 315
+ 983 PUSHACC 12
+ 985 PUSHACC 28
+ 987 PUSHACC 30
+ 989 CLOSURE 3, 308
+ 992 PUSHACC0
+ 993 CLOSURE 1, 301
+ 996 PUSHACC1
+ 997 CLOSURE 1, 294
+ 1000 PUSHACC 29
+ 1002 PUSHACC 31
+ 1004 CLOSURE 2, 286
+ 1007 MAKEBLOCK1 0
+ 1009 PUSHACC0
+ 1010 CLOSURE 1, 275
+ 1013 PUSHACC1
+ 1014 CLOSURE 1, 263
+ 1017 PUSHACC0
+ 1018 CLOSURE 1, 255
+ 1021 PUSHACC1
+ 1022 PUSHACC 22
+ 1024 PUSHACC4
+ 1025 PUSHACC3
+ 1026 PUSH
+ 1027 CLOSURE 0, 247
+ 1030 PUSH
+ 1031 CLOSURE 0, 241
+ 1034 PUSH
+ 1035 CLOSURE 0, 236
+ 1038 PUSH
+ 1039 CLOSURE 0, 231
+ 1042 PUSH
+ 1043 CLOSURE 0, 223
+ 1046 PUSH
+ 1047 CLOSURE 0, 217
+ 1050 PUSH
+ 1051 CLOSURE 0, 212
+ 1054 PUSH
+ 1055 CLOSURE 0, 207
+ 1058 PUSHACC 32
+ 1060 PUSHACC 35
+ 1062 PUSHACC 33
+ 1064 PUSH
+ 1065 CLOSURE 0, 202
+ 1068 PUSHACC 41
+ 1070 PUSHACC 40
+ 1072 PUSHACC 42
+ 1074 PUSH
+ 1075 CLOSURE 0, 194
+ 1078 PUSHACC 46
+ 1080 PUSH
+ 1081 CLOSURE 0, 188
+ 1084 PUSH
+ 1085 CLOSURE 0, 183
+ 1088 PUSH
+ 1089 CLOSURE 0, 175
+ 1092 PUSHACC 51
+ 1094 PUSH
+ 1095 CLOSURE 0, 166
+ 1098 PUSH
+ 1099 CLOSURE 0, 157
+ 1102 PUSHACC 55
+ 1104 PUSHACC 57
+ 1106 PUSH
+ 1107 CLOSURE 0, 148
+ 1110 PUSH
+ 1111 CLOSURE 0, 142
+ 1114 PUSHACC 63
+ 1116 PUSHACC 62
+ 1118 PUSHACC 64
+ 1120 PUSHACC 38
+ 1122 PUSHACC 40
+ 1124 PUSHACC 42
+ 1126 PUSHACC 44
+ 1128 PUSHACC 46
+ 1130 PUSHACC 48
+ 1132 PUSHACC 50
+ 1134 PUSHACC 52
+ 1136 PUSHACC 54
+ 1138 PUSHACC 56
+ 1140 PUSHACC 58
+ 1142 PUSHACC 60
+ 1144 PUSHACC 62
+ 1146 PUSHACC 64
+ 1148 PUSHACC 66
+ 1150 PUSHACC 82
+ 1152 PUSHACC 84
+ 1154 PUSHACC 86
+ 1156 PUSHACC 88
+ 1158 PUSHACC 90
+ 1160 PUSHACC 92
+ 1162 PUSHACC 94
+ 1164 PUSHACC 96
+ 1166 PUSHACC 98
+ 1168 PUSHACC 100
+ 1170 PUSHACC 104
+ 1172 PUSHACC 104
+ 1174 PUSHACC 104
+ 1176 PUSHACC 108
+ 1178 PUSHACC 110
+ 1180 PUSHACC 112
+ 1182 PUSHACC 117
+ 1184 PUSHACC 117
+ 1186 PUSHACC 117
+ 1188 PUSHACC 117
+ 1190 MAKEBLOCK 69, 0
+ 1193 POP 53
+ 1195 SETGLOBAL Pervasives
+ 1197 BRANCH 2177
+ 1199 RESTART
+ 1200 GRAB 1
+ 1202 ACC1
+ 1203 BRANCHIFNOT 1213
+ 1205 ACC1
+ 1206 GETFIELD1
+ 1207 PUSHACC1
+ 1208 OFFSETINT 1
+ 1210 PUSHOFFSETCLOSURE0
+ 1211 APPTERM2 4
+ 1213 ACC0
+ 1214 RETURN 2
+ 1216 RESTART
+ 1217 GRAB 1
+ 1219 ACC0
+ 1220 BRANCHIFNOT 1251
+ 1222 CONST0
+ 1223 PUSHACC2
+ 1224 EQ
+ 1225 BRANCHIFNOT 1231
+ 1227 ACC0
+ 1228 GETFIELD0
+ 1229 RETURN 2
+ 1231 CONST0
+ 1232 PUSHACC2
+ 1233 GTINT
+ 1234 BRANCHIFNOT 1244
+ 1236 ACC1
+ 1237 OFFSETINT -1
+ 1239 PUSHACC1
+ 1240 GETFIELD1
+ 1241 PUSHOFFSETCLOSURE0
+ 1242 APPTERM2 4
+ 1244 GETGLOBAL "List.nth"
+ 1246 PUSHGETGLOBALFIELD Pervasives, 2
+ 1249 APPTERM1 3
+ 1251 GETGLOBAL "nth"
+ 1253 PUSHGETGLOBALFIELD Pervasives, 3
+ 1256 APPTERM1 3
+ 1258 RESTART
+ 1259 GRAB 1
+ 1261 ACC0
+ 1262 BRANCHIFNOT 1274
+ 1264 ACC1
+ 1265 PUSHACC1
+ 1266 GETFIELD0
+ 1267 MAKEBLOCK2 0
+ 1269 PUSHACC1
+ 1270 GETFIELD1
+ 1271 PUSHOFFSETCLOSURE0
+ 1272 APPTERM2 4
+ 1274 ACC1
+ 1275 RETURN 2
+ 1277 ACC0
+ 1278 BRANCHIFNOT 1291
+ 1280 ACC0
+ 1281 GETFIELD1
+ 1282 PUSHOFFSETCLOSURE0
+ 1283 APPLY1
+ 1284 PUSHACC1
+ 1285 GETFIELD0
+ 1286 PUSHGETGLOBALFIELD Pervasives, 16
+ 1289 APPTERM2 3
+ 1291 RETURN 1
+ 1293 RESTART
+ 1294 GRAB 1
+ 1296 ACC1
+ 1297 BRANCHIFNOT 1313
+ 1299 ACC1
+ 1300 GETFIELD0
+ 1301 PUSHACC1
+ 1302 APPLY1
+ 1303 PUSHACC2
+ 1304 GETFIELD1
+ 1305 PUSHACC2
+ 1306 PUSHOFFSETCLOSURE0
+ 1307 APPLY2
+ 1308 PUSHACC1
+ 1309 MAKEBLOCK2 0
+ 1311 POP 1
+ 1313 RETURN 2
+ 1315 RESTART
+ 1316 GRAB 1
+ 1318 ACC1
+ 1319 BRANCHIFNOT 1331
+ 1321 ACC1
+ 1322 GETFIELD0
+ 1323 PUSHACC1
+ 1324 APPLY1
+ 1325 ACC1
+ 1326 GETFIELD1
+ 1327 PUSHACC1
+ 1328 PUSHOFFSETCLOSURE0
+ 1329 APPTERM2 4
+ 1331 RETURN 2
+ 1333 RESTART
+ 1334 GRAB 2
+ 1336 ACC2
+ 1337 BRANCHIFNOT 1350
+ 1339 ACC2
+ 1340 GETFIELD1
+ 1341 PUSHACC3
+ 1342 GETFIELD0
+ 1343 PUSHACC3
+ 1344 PUSHACC3
+ 1345 APPLY2
+ 1346 PUSHACC2
+ 1347 PUSHOFFSETCLOSURE0
+ 1348 APPTERM3 6
+ 1350 ACC1
+ 1351 RETURN 3
+ 1353 RESTART
+ 1354 GRAB 2
+ 1356 ACC1
+ 1357 BRANCHIFNOT 1370
+ 1359 ACC2
+ 1360 PUSHACC2
+ 1361 GETFIELD1
+ 1362 PUSHACC2
+ 1363 PUSHOFFSETCLOSURE0
+ 1364 APPLY3
+ 1365 PUSHACC2
+ 1366 GETFIELD0
+ 1367 PUSHACC2
+ 1368 APPTERM2 5
+ 1370 ACC2
+ 1371 RETURN 3
+ 1373 RESTART
+ 1374 GRAB 2
+ 1376 ACC1
+ 1377 BRANCHIFNOT 1400
+ 1379 ACC2
+ 1380 BRANCHIFNOT 1407
+ 1382 ACC2
+ 1383 GETFIELD0
+ 1384 PUSHACC2
+ 1385 GETFIELD0
+ 1386 PUSHACC2
+ 1387 APPLY2
+ 1388 PUSHACC3
+ 1389 GETFIELD1
+ 1390 PUSHACC3
+ 1391 GETFIELD1
+ 1392 PUSHACC3
+ 1393 PUSHOFFSETCLOSURE0
+ 1394 APPLY3
+ 1395 PUSHACC1
+ 1396 MAKEBLOCK2 0
+ 1398 RETURN 4
+ 1400 ACC2
+ 1401 BRANCHIFNOT 1405
+ 1403 BRANCH 1407
+ 1405 RETURN 3
+ 1407 GETGLOBAL "List.map2"
+ 1409 PUSHGETGLOBALFIELD Pervasives, 2
+ 1412 APPTERM1 4
+ 1414 RESTART
+ 1415 GRAB 2
+ 1417 ACC1
+ 1418 BRANCHIFNOT 1437
+ 1420 ACC2
+ 1421 BRANCHIFNOT 1444
+ 1423 ACC2
+ 1424 GETFIELD0
+ 1425 PUSHACC2
+ 1426 GETFIELD0
+ 1427 PUSHACC2
+ 1428 APPLY2
+ 1429 ACC2
+ 1430 GETFIELD1
+ 1431 PUSHACC2
+ 1432 GETFIELD1
+ 1433 PUSHACC2
+ 1434 PUSHOFFSETCLOSURE0
+ 1435 APPTERM3 6
+ 1437 ACC2
+ 1438 BRANCHIFNOT 1442
+ 1440 BRANCH 1444
+ 1442 RETURN 3
+ 1444 GETGLOBAL "List.iter2"
+ 1446 PUSHGETGLOBALFIELD Pervasives, 2
+ 1449 APPTERM1 4
+ 1451 RESTART
+ 1452 GRAB 3
+ 1454 ACC2
+ 1455 BRANCHIFNOT 1476
+ 1457 ACC3
+ 1458 BRANCHIFNOT 1482
+ 1460 ACC3
+ 1461 GETFIELD1
+ 1462 PUSHACC3
+ 1463 GETFIELD1
+ 1464 PUSHACC5
+ 1465 GETFIELD0
+ 1466 PUSHACC5
+ 1467 GETFIELD0
+ 1468 PUSHACC5
+ 1469 PUSHACC5
+ 1470 APPLY3
+ 1471 PUSHACC3
+ 1472 PUSHOFFSETCLOSURE0
+ 1473 APPTERM 4, 8
+ 1476 ACC3
+ 1477 BRANCHIF 1482
+ 1479 ACC1
+ 1480 RETURN 4
+ 1482 GETGLOBAL "List.fold_left2"
+ 1484 PUSHGETGLOBALFIELD Pervasives, 2
+ 1487 APPTERM1 5
+ 1489 RESTART
+ 1490 GRAB 3
+ 1492 ACC1
+ 1493 BRANCHIFNOT 1516
+ 1495 ACC2
+ 1496 BRANCHIFNOT 1522
+ 1498 PUSH_RETADDR 1509
+ 1500 ACC6
+ 1501 PUSHACC6
+ 1502 GETFIELD1
+ 1503 PUSHACC6
+ 1504 GETFIELD1
+ 1505 PUSHACC6
+ 1506 PUSHOFFSETCLOSURE0
+ 1507 APPLY 4
+ 1509 PUSHACC3
+ 1510 GETFIELD0
+ 1511 PUSHACC3
+ 1512 GETFIELD0
+ 1513 PUSHACC3
+ 1514 APPTERM3 7
+ 1516 ACC2
+ 1517 BRANCHIF 1522
+ 1519 ACC3
+ 1520 RETURN 4
+ 1522 GETGLOBAL "List.fold_right2"
+ 1524 PUSHGETGLOBALFIELD Pervasives, 2
+ 1527 APPTERM1 5
+ 1529 RESTART
+ 1530 GRAB 1
+ 1532 ACC1
+ 1533 BRANCHIFNOT 1549
+ 1535 ACC1
+ 1536 GETFIELD0
+ 1537 PUSHACC1
+ 1538 APPLY1
+ 1539 BRANCHIFNOT 1547
+ 1541 ACC1
+ 1542 GETFIELD1
+ 1543 PUSHACC1
+ 1544 PUSHOFFSETCLOSURE0
+ 1545 APPTERM2 4
+ 1547 RETURN 2
+ 1549 CONST1
+ 1550 RETURN 2
+ 1552 RESTART
+ 1553 GRAB 1
+ 1555 ACC1
+ 1556 BRANCHIFNOT 1570
+ 1558 ACC1
+ 1559 GETFIELD0
+ 1560 PUSHACC1
+ 1561 APPLY1
+ 1562 BRANCHIF 1570
+ 1564 ACC1
+ 1565 GETFIELD1
+ 1566 PUSHACC1
+ 1567 PUSHOFFSETCLOSURE0
+ 1568 APPTERM2 4
+ 1570 RETURN 2
+ 1572 RESTART
+ 1573 GRAB 2
+ 1575 ACC1
+ 1576 BRANCHIFNOT 1599
+ 1578 ACC2
+ 1579 BRANCHIFNOT 1605
+ 1581 ACC2
+ 1582 GETFIELD0
+ 1583 PUSHACC2
+ 1584 GETFIELD0
+ 1585 PUSHACC2
+ 1586 APPLY2
+ 1587 BRANCHIFNOT 1597
+ 1589 ACC2
+ 1590 GETFIELD1
+ 1591 PUSHACC2
+ 1592 GETFIELD1
+ 1593 PUSHACC2
+ 1594 PUSHOFFSETCLOSURE0
+ 1595 APPTERM3 6
+ 1597 RETURN 3
+ 1599 ACC2
+ 1600 BRANCHIF 1605
+ 1602 CONST1
+ 1603 RETURN 3
+ 1605 GETGLOBAL "List.for_all2"
+ 1607 PUSHGETGLOBALFIELD Pervasives, 2
+ 1610 APPTERM1 4
+ 1612 RESTART
+ 1613 GRAB 2
+ 1615 ACC1
+ 1616 BRANCHIFNOT 1639
+ 1618 ACC2
+ 1619 BRANCHIFNOT 1646
+ 1621 ACC2
+ 1622 GETFIELD0
+ 1623 PUSHACC2
+ 1624 GETFIELD0
+ 1625 PUSHACC2
+ 1626 APPLY2
+ 1627 BRANCHIF 1637
+ 1629 ACC2
+ 1630 GETFIELD1
+ 1631 PUSHACC2
+ 1632 GETFIELD1
+ 1633 PUSHACC2
+ 1634 PUSHOFFSETCLOSURE0
+ 1635 APPTERM3 6
+ 1637 RETURN 3
+ 1639 ACC2
+ 1640 BRANCHIFNOT 1644
+ 1642 BRANCH 1646
+ 1644 RETURN 3
+ 1646 GETGLOBAL "List.exists2"
+ 1648 PUSHGETGLOBALFIELD Pervasives, 2
+ 1651 APPTERM1 4
+ 1653 RESTART
+ 1654 GRAB 1
+ 1656 ACC1
+ 1657 BRANCHIFNOT 1672
+ 1659 ACC0
+ 1660 PUSHACC2
+ 1661 GETFIELD0
+ 1662 C_CALL2 equal
+ 1664 BRANCHIF 1672
+ 1666 ACC1
+ 1667 GETFIELD1
+ 1668 PUSHACC1
+ 1669 PUSHOFFSETCLOSURE0
+ 1670 APPTERM2 4
+ 1672 RETURN 2
+ 1674 RESTART
+ 1675 GRAB 1
+ 1677 ACC1
+ 1678 BRANCHIFNOT 1692
+ 1680 ACC0
+ 1681 PUSHACC2
+ 1682 GETFIELD0
+ 1683 EQ
+ 1684 BRANCHIF 1692
+ 1686 ACC1
+ 1687 GETFIELD1
+ 1688 PUSHACC1
+ 1689 PUSHOFFSETCLOSURE0
+ 1690 APPTERM2 4
+ 1692 RETURN 2
+ 1694 RESTART
+ 1695 GRAB 1
+ 1697 ACC1
+ 1698 BRANCHIFNOT 1719
+ 1700 ACC1
+ 1701 GETFIELD0
+ 1702 PUSHACC1
+ 1703 PUSHACC1
+ 1704 GETFIELD0
+ 1705 C_CALL2 equal
+ 1707 BRANCHIFNOT 1713
+ 1709 ACC0
+ 1710 GETFIELD1
+ 1711 RETURN 3
+ 1713 ACC2
+ 1714 GETFIELD1
+ 1715 PUSHACC2
+ 1716 PUSHOFFSETCLOSURE0
+ 1717 APPTERM2 5
+ 1719 GETGLOBAL Not_found
+ 1721 MAKEBLOCK1 0
+ 1723 RAISE
+ 1724 RESTART
+ 1725 GRAB 1
+ 1727 ACC1
+ 1728 BRANCHIFNOT 1748
+ 1730 ACC1
+ 1731 GETFIELD0
+ 1732 PUSHACC1
+ 1733 PUSHACC1
+ 1734 GETFIELD0
+ 1735 EQ
+ 1736 BRANCHIFNOT 1742
+ 1738 ACC0
+ 1739 GETFIELD1
+ 1740 RETURN 3
+ 1742 ACC2
+ 1743 GETFIELD1
+ 1744 PUSHACC2
+ 1745 PUSHOFFSETCLOSURE0
+ 1746 APPTERM2 5
+ 1748 GETGLOBAL Not_found
+ 1750 MAKEBLOCK1 0
+ 1752 RAISE
+ 1753 RESTART
+ 1754 GRAB 1
+ 1756 ACC1
+ 1757 BRANCHIFNOT 1773
+ 1759 ACC0
+ 1760 PUSHACC2
+ 1761 GETFIELD0
+ 1762 GETFIELD0
+ 1763 C_CALL2 equal
+ 1765 BRANCHIF 1773
+ 1767 ACC1
+ 1768 GETFIELD1
+ 1769 PUSHACC1
+ 1770 PUSHOFFSETCLOSURE0
+ 1771 APPTERM2 4
+ 1773 RETURN 2
+ 1775 RESTART
+ 1776 GRAB 1
+ 1778 ACC1
+ 1779 BRANCHIFNOT 1794
+ 1781 ACC0
+ 1782 PUSHACC2
+ 1783 GETFIELD0
+ 1784 GETFIELD0
+ 1785 EQ
+ 1786 BRANCHIF 1794
+ 1788 ACC1
+ 1789 GETFIELD1
+ 1790 PUSHACC1
+ 1791 PUSHOFFSETCLOSURE0
+ 1792 APPTERM2 4
+ 1794 RETURN 2
+ 1796 RESTART
+ 1797 GRAB 1
+ 1799 ACC1
+ 1800 BRANCHIFNOT 1825
+ 1802 ACC1
+ 1803 GETFIELD0
+ 1804 PUSHACC2
+ 1805 GETFIELD1
+ 1806 PUSHACC2
+ 1807 PUSHACC2
+ 1808 GETFIELD0
+ 1809 C_CALL2 equal
+ 1811 BRANCHIFNOT 1816
+ 1813 ACC0
+ 1814 RETURN 4
+ 1816 ACC0
+ 1817 PUSHACC3
+ 1818 PUSHOFFSETCLOSURE0
+ 1819 APPLY2
+ 1820 PUSHACC2
+ 1821 MAKEBLOCK2 0
+ 1823 POP 2
+ 1825 RETURN 2
+ 1827 RESTART
+ 1828 GRAB 1
+ 1830 ACC1
+ 1831 BRANCHIFNOT 1855
+ 1833 ACC1
+ 1834 GETFIELD0
+ 1835 PUSHACC2
+ 1836 GETFIELD1
+ 1837 PUSHACC2
+ 1838 PUSHACC2
+ 1839 GETFIELD0
+ 1840 EQ
+ 1841 BRANCHIFNOT 1846
+ 1843 ACC0
+ 1844 RETURN 4
+ 1846 ACC0
+ 1847 PUSHACC3
+ 1848 PUSHOFFSETCLOSURE0
+ 1849 APPLY2
+ 1850 PUSHACC2
+ 1851 MAKEBLOCK2 0
+ 1853 POP 2
+ 1855 RETURN 2
+ 1857 RESTART
+ 1858 GRAB 1
+ 1860 ACC1
+ 1861 BRANCHIFNOT 1879
+ 1863 ACC1
+ 1864 GETFIELD0
+ 1865 PUSHACC0
+ 1866 PUSHACC2
+ 1867 APPLY1
+ 1868 BRANCHIFNOT 1873
+ 1870 ACC0
+ 1871 RETURN 3
+ 1873 ACC2
+ 1874 GETFIELD1
+ 1875 PUSHACC2
+ 1876 PUSHOFFSETCLOSURE0
+ 1877 APPTERM2 5
+ 1879 GETGLOBAL Not_found
+ 1881 MAKEBLOCK1 0
+ 1883 RAISE
+ 1884 RESTART
+ 1885 GRAB 2
+ 1887 ACC2
+ 1888 BRANCHIFNOT 1917
+ 1890 ACC2
+ 1891 GETFIELD0
+ 1892 PUSHACC3
+ 1893 GETFIELD1
+ 1894 PUSHACC1
+ 1895 PUSHENVACC2
+ 1896 APPLY1
+ 1897 BRANCHIFNOT 1908
+ 1899 ACC0
+ 1900 PUSHACC4
+ 1901 PUSHACC4
+ 1902 PUSHACC4
+ 1903 MAKEBLOCK2 0
+ 1905 PUSHOFFSETCLOSURE0
+ 1906 APPTERM3 8
+ 1908 ACC0
+ 1909 PUSHACC4
+ 1910 PUSHACC3
+ 1911 MAKEBLOCK2 0
+ 1913 PUSHACC4
+ 1914 PUSHOFFSETCLOSURE0
+ 1915 APPTERM3 8
+ 1917 ACC1
+ 1918 PUSHENVACC1
+ 1919 APPLY1
+ 1920 PUSHACC1
+ 1921 PUSHENVACC1
+ 1922 APPLY1
+ 1923 MAKEBLOCK2 0
+ 1925 RETURN 3
+ 1927 RESTART
+ 1928 GRAB 1
+ 1930 ACC0
+ 1931 PUSHENVACC1
+ 1932 CLOSUREREC 2, 1885
+ 1936 ACC2
+ 1937 PUSHCONST0
+ 1938 PUSHCONST0
+ 1939 PUSHACC3
+ 1940 APPTERM3 6
+ 1942 ACC0
+ 1943 BRANCHIFNOT 1967
+ 1945 ACC0
+ 1946 GETFIELD0
+ 1947 PUSHACC1
+ 1948 GETFIELD1
+ 1949 PUSHOFFSETCLOSURE0
+ 1950 APPLY1
+ 1951 PUSHACC0
+ 1952 GETFIELD1
+ 1953 PUSHACC2
+ 1954 GETFIELD1
+ 1955 MAKEBLOCK2 0
+ 1957 PUSHACC1
+ 1958 GETFIELD0
+ 1959 PUSHACC3
+ 1960 GETFIELD0
+ 1961 MAKEBLOCK2 0
+ 1963 MAKEBLOCK2 0
+ 1965 RETURN 3
+ 1967 GETGLOBAL <0>(0, 0)
+ 1969 RETURN 1
+ 1971 RESTART
+ 1972 GRAB 1
+ 1974 ACC0
+ 1975 BRANCHIFNOT 1996
+ 1977 ACC1
+ 1978 BRANCHIFNOT 2003
+ 1980 ACC1
+ 1981 GETFIELD1
+ 1982 PUSHACC1
+ 1983 GETFIELD1
+ 1984 PUSHOFFSETCLOSURE0
+ 1985 APPLY2
+ 1986 PUSHACC2
+ 1987 GETFIELD0
+ 1988 PUSHACC2
+ 1989 GETFIELD0
+ 1990 MAKEBLOCK2 0
+ 1992 MAKEBLOCK2 0
+ 1994 RETURN 2
+ 1996 ACC1
+ 1997 BRANCHIFNOT 2001
+ 1999 BRANCH 2003
+ 2001 RETURN 2
+ 2003 GETGLOBAL "List.combine"
+ 2005 PUSHGETGLOBALFIELD Pervasives, 2
+ 2008 APPTERM1 3
+ 2010 RESTART
+ 2011 GRAB 1
+ 2013 ACC1
+ 2014 BRANCHIFNOT 2038
+ 2016 ACC1
+ 2017 GETFIELD0
+ 2018 PUSHACC2
+ 2019 GETFIELD1
+ 2020 PUSHACC1
+ 2021 PUSHENVACC2
+ 2022 APPLY1
+ 2023 BRANCHIFNOT 2033
+ 2025 ACC0
+ 2026 PUSHACC3
+ 2027 PUSHACC3
+ 2028 MAKEBLOCK2 0
+ 2030 PUSHOFFSETCLOSURE0
+ 2031 APPTERM2 6
+ 2033 ACC0
+ 2034 PUSHACC3
+ 2035 PUSHOFFSETCLOSURE0
+ 2036 APPTERM2 6
+ 2038 ACC0
+ 2039 PUSHENVACC1
+ 2040 APPTERM1 3
+ 2042 ACC0
+ 2043 PUSHENVACC1
+ 2044 CLOSUREREC 2, 2011
+ 2048 CONST0
+ 2049 PUSHACC1
+ 2050 APPTERM1 3
+ 2052 RESTART
+ 2053 GRAB 2
+ 2055 ACC1
+ 2056 BRANCHIFNOT 2077
+ 2058 ACC2
+ 2059 BRANCHIFNOT 2084
+ 2061 ACC2
+ 2062 GETFIELD1
+ 2063 PUSHACC2
+ 2064 GETFIELD1
+ 2065 PUSHACC2
+ 2066 PUSHACC5
+ 2067 GETFIELD0
+ 2068 PUSHACC5
+ 2069 GETFIELD0
+ 2070 PUSHENVACC1
+ 2071 APPLY2
+ 2072 MAKEBLOCK2 0
+ 2074 PUSHOFFSETCLOSURE0
+ 2075 APPTERM3 6
+ 2077 ACC2
+ 2078 BRANCHIFNOT 2082
+ 2080 BRANCH 2084
+ 2082 RETURN 3
+ 2084 GETGLOBAL "List.rev_map2"
+ 2086 PUSHGETGLOBALFIELD Pervasives, 2
+ 2089 APPTERM1 4
+ 2091 RESTART
+ 2092 GRAB 2
+ 2094 ACC0
+ 2095 CLOSUREREC 1, 2053
+ 2099 ACC3
+ 2100 PUSHACC3
+ 2101 PUSHCONST0
+ 2102 PUSHACC3
+ 2103 APPTERM3 7
+ 2105 RESTART
+ 2106 GRAB 1
+ 2108 ACC1
+ 2109 BRANCHIFNOT 2123
+ 2111 ACC1
+ 2112 GETFIELD1
+ 2113 PUSHACC1
+ 2114 PUSHACC3
+ 2115 GETFIELD0
+ 2116 PUSHENVACC1
+ 2117 APPLY1
+ 2118 MAKEBLOCK2 0
+ 2120 PUSHOFFSETCLOSURE0
+ 2121 APPTERM2 4
+ 2123 ACC0
+ 2124 RETURN 2
+ 2126 RESTART
+ 2127 GRAB 1
+ 2129 ACC0
+ 2130 CLOSUREREC 1, 2106
+ 2134 ACC2
+ 2135 PUSHCONST0
+ 2136 PUSHACC2
+ 2137 APPTERM2 5
+ 2139 CONST0
+ 2140 PUSHACC1
+ 2141 PUSHENVACC1
+ 2142 APPTERM2 3
+ 2144 ACC0
+ 2145 BRANCHIFNOT 2151
+ 2147 ACC0
+ 2148 GETFIELD1
+ 2149 RETURN 1
+ 2151 GETGLOBAL "tl"
+ 2153 PUSHGETGLOBALFIELD Pervasives, 3
+ 2156 APPTERM1 2
+ 2158 ACC0
+ 2159 BRANCHIFNOT 2165
+ 2161 ACC0
+ 2162 GETFIELD0
+ 2163 RETURN 1
+ 2165 GETGLOBAL "hd"
+ 2167 PUSHGETGLOBALFIELD Pervasives, 3
+ 2170 APPTERM1 2
+ 2172 ACC0
+ 2173 PUSHCONST0
+ 2174 PUSHENVACC1
+ 2175 APPTERM2 3
+ 2177 CLOSUREREC 0, 1200
+ 2181 ACC0
+ 2182 CLOSURE 1, 2172
+ 2185 PUSH
+ 2186 CLOSURE 0, 2158
+ 2189 PUSH
+ 2190 CLOSURE 0, 2144
+ 2193 PUSH
+ 2194 CLOSUREREC 0, 1217
+ 2198 GETGLOBALFIELD Pervasives, 16
+ 2201 PUSH
+ 2202 CLOSUREREC 0, 1259
+ 2206 ACC0
+ 2207 CLOSURE 1, 2139
+ 2210 PUSH
+ 2211 CLOSUREREC 0, 1277
+ 2215 CLOSUREREC 0, 1294
+ 2219 CLOSURE 0, 2127
+ 2222 PUSH
+ 2223 CLOSUREREC 0, 1316
+ 2227 CLOSUREREC 0, 1334
+ 2231 CLOSUREREC 0, 1354
+ 2235 CLOSUREREC 0, 1374
+ 2239 CLOSURE 0, 2092
+ 2242 PUSH
+ 2243 CLOSUREREC 0, 1415
+ 2247 CLOSUREREC 0, 1452
+ 2251 CLOSUREREC 0, 1490
+ 2255 CLOSUREREC 0, 1530
+ 2259 CLOSUREREC 0, 1553
+ 2263 CLOSUREREC 0, 1573
+ 2267 CLOSUREREC 0, 1613
+ 2271 CLOSUREREC 0, 1654
+ 2275 CLOSUREREC 0, 1675
+ 2279 CLOSUREREC 0, 1695
+ 2283 CLOSUREREC 0, 1725
+ 2287 CLOSUREREC 0, 1754
+ 2291 CLOSUREREC 0, 1776
+ 2295 CLOSUREREC 0, 1797
+ 2299 CLOSUREREC 0, 1828
+ 2303 CLOSUREREC 0, 1858
+ 2307 ACC 24
+ 2309 CLOSURE 1, 2042
+ 2312 PUSHACC 25
+ 2314 CLOSUREREC 1, 1928
+ 2318 CLOSUREREC 0, 1942
+ 2322 CLOSUREREC 0, 1972
+ 2326 ACC0
+ 2327 PUSHACC2
+ 2328 PUSHACC7
+ 2329 PUSHACC 9
+ 2331 PUSHACC 11
+ 2333 PUSHACC 13
+ 2335 PUSHACC 15
+ 2337 PUSHACC 17
+ 2339 PUSHACC 10
+ 2341 PUSHACC 12
+ 2343 PUSHACC 13
+ 2345 PUSHACC 15
+ 2347 PUSHACC 23
+ 2349 PUSHACC 25
+ 2351 PUSHACC 27
+ 2353 PUSHACC 29
+ 2355 PUSHACC 31
+ 2357 PUSHACC 33
+ 2359 PUSHACC 35
+ 2361 PUSHACC 37
+ 2363 PUSHACC 40
+ 2365 PUSHACC 42
+ 2367 PUSHACC 41
+ 2369 PUSHACC 45
+ 2371 PUSHACC 47
+ 2373 PUSHACC 50
+ 2375 PUSHACC 52
+ 2377 PUSHACC 51
+ 2379 PUSHACC 55
+ 2381 PUSHACC 56
+ 2383 PUSHACC 59
+ 2385 PUSHACC 61
+ 2387 PUSHACC 60
+ 2389 PUSHACC 64
+ 2391 PUSHACC 66
+ 2393 PUSHACC 68
+ 2395 PUSHACC 70
+ 2397 MAKEBLOCK 37, 0
+ 2400 POP 36
+ 2402 SETGLOBAL List
+ 2404 BRANCH 2432
+ 2406 CONST0
+ 2407 PUSHACC1
+ 2408 LEINT
+ 2409 BRANCHIFNOT 2414
+ 2411 CONST0
+ 2412 RETURN 1
+ 2414 ACC0
+ 2415 OFFSETINT -1
+ 2417 PUSHOFFSETCLOSURE0
+ 2418 APPLY1
+ 2419 PUSHACC1
+ 2420 MAKEBLOCK2 0
+ 2422 RETURN 1
+ 2424 RESTART
+ 2425 GRAB 1
+ 2427 ACC1
+ 2428 PUSHACC1
+ 2429 ADDINT
+ 2430 RETURN 2
+ 2432 CLOSUREREC 0, 2406
+ 2436 CONST0
+ 2437 C_CALL1 gc_compaction
+ 2439 CONSTINT 300
+ 2441 PUSHACC1
+ 2442 APPLY1
+ 2443 PUSHCONSTINT 150
+ 2445 PUSHCONSTINT 301
+ 2447 MULINT
+ 2448 PUSHACC1
+ 2449 PUSHCONST0
+ 2450 PUSH
+ 2451 CLOSURE 0, 2425
+ 2454 PUSHGETGLOBALFIELD List, 12
+ 2457 APPLY3
+ 2458 NEQ
+ 2459 BRANCHIFNOT 2466
+ 2461 GETGLOBAL Not_found
+ 2463 MAKEBLOCK1 0
+ 2465 RAISE
+ 2466 POP 2
+ 2468 ATOM0
+ 2469 SETGLOBAL T330-compact-4
+ 2471 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t340-weak.ml b/testsuite/tests/tool-ocaml/t340-weak.ml
new file mode 100644
index 0000000000..7ced585dcc
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t340-weak.ml
@@ -0,0 +1,24 @@
+open Lib;;
+let x = Array.make 20 "" in
+let w = weak_create 20 in
+for i = 0 to 19 do
+ x.(i) <- String.make 20 's';
+ weak_set w i (Some x.(i));
+done;
+Gc.full_major ();
+for i = 0 to 19 do
+ match weak_get w i with
+ | None -> raise Not_found
+ | _ -> ()
+done;
+for i = 0 to 19 do
+ if i mod 2 = 0 then x.(i) <- ""
+done;
+Gc.full_major ();
+for i = 0 to 19 do
+ match weak_get w i with
+ | None when i mod 2 = 0 -> ()
+ | Some s when i mod 2 = 1 -> if s.[5] <> 's' then raise Not_found
+ | _ -> raise Not_found
+done
+;;
diff --git a/testsuite/tests/tool-ocaml/t350-heapcheck.ml b/testsuite/tests/tool-ocaml/t350-heapcheck.ml
new file mode 100644
index 0000000000..45295eaaca
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t350-heapcheck.ml
@@ -0,0 +1,25 @@
+open Lib;;
+ignore (Gc.stat ());
+let x = Array.make 20 "" in
+let w = weak_create 20 in
+for i = 0 to 19 do
+ x.(i) <- String.make 20 's';
+ weak_set w i (Some x.(i));
+done;
+Gc.full_major ();
+for i = 0 to 19 do
+ match weak_get w i with
+ | None -> raise Not_found
+ | _ -> ()
+done;
+for i = 0 to 19 do
+ if i mod 2 = 0 then x.(i) <- ""
+done;
+Gc.full_major ();
+for i = 0 to 19 do
+ match weak_get w i with
+ | None when i mod 2 = 0 -> ()
+ | Some s when i mod 2 = 1 -> if s.[5] <> 's' then raise Not_found
+ | _ -> raise Not_found
+done
+;;
diff --git a/testsuite/tests/tool-ocaml/t360-stacks-1.ml b/testsuite/tests/tool-ocaml/t360-stacks-1.ml
new file mode 100644
index 0000000000..100fbabb2b
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t360-stacks-1.ml
@@ -0,0 +1,43 @@
+open Lib;;
+let rec f n =
+ if n <= 0 then 12
+ else 1 + f (n-1)
+in
+if f 30000 <> 30012 then raise Not_found
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 29
+ 11 CONST0
+ 12 PUSHACC1
+ 13 LEINT
+ 14 BRANCHIFNOT 20
+ 16 CONSTINT 12
+ 18 RETURN 1
+ 20 ACC0
+ 21 OFFSETINT -1
+ 23 PUSHOFFSETCLOSURE0
+ 24 APPLY1
+ 25 PUSHCONST1
+ 26 ADDINT
+ 27 RETURN 1
+ 29 CLOSUREREC 0, 11
+ 33 CONSTINT 30012
+ 35 PUSHCONSTINT 30000
+ 37 PUSHACC2
+ 38 APPLY1
+ 39 NEQ
+ 40 BRANCHIFNOT 47
+ 42 GETGLOBAL Not_found
+ 44 MAKEBLOCK1 0
+ 46 RAISE
+ 47 POP 1
+ 49 ATOM0
+ 50 SETGLOBAL T360-stacks-1
+ 52 STOP
+**)
diff --git a/testsuite/tests/tool-ocaml/t360-stacks-2.ml b/testsuite/tests/tool-ocaml/t360-stacks-2.ml
new file mode 100644
index 0000000000..8d13c7d7fc
--- /dev/null
+++ b/testsuite/tests/tool-ocaml/t360-stacks-2.ml
@@ -0,0 +1,54 @@
+open Lib;;
+let rec f n =
+ if n <= 0 then 12
+ else 1 + f (n-1)
+in
+try
+ ignore (f 3000000);
+ raise Not_found
+with Stack_overflow -> ()
+;;
+
+(**
+ 0 CONSTINT 42
+ 2 PUSHACC0
+ 3 MAKEBLOCK1 0
+ 5 POP 1
+ 7 SETGLOBAL Lib
+ 9 BRANCH 29
+ 11 CONST0
+ 12 PUSHACC1
+ 13 LEINT
+ 14 BRANCHIFNOT 20
+ 16 CONSTINT 12
+ 18 RETURN 1
+ 20 ACC0
+ 21 OFFSETINT -1
+ 23 PUSHOFFSETCLOSURE0
+ 24 APPLY1
+ 25 PUSHCONST1
+ 26 ADDINT
+ 27 RETURN 1
+ 29 CLOSUREREC 0, 11
+ 33 PUSHTRAP 44
+ 35 CONSTINT 3000000
+ 37 PUSHACC5
+ 38 APPLY1
+ 39 GETGLOBAL Not_found
+ 41 MAKEBLOCK1 0
+ 43 RAISE
+ 44 PUSHGETGLOBAL Stack_overflow
+ 46 PUSHACC1
+ 47 GETFIELD0
+ 48 EQ
+ 49 BRANCHIFNOT 54
+ 51 CONST0
+ 52 BRANCH 56
+ 54 ACC0
+ 55 RAISE
+ 56 POP 1
+ 58 POP 1
+ 60 ATOM0
+ 61 SETGLOBAL T360-stacks-2
+ 63 STOP
+**)
diff --git a/testsuite/tests/tool-ocamldoc/.ignore b/testsuite/tests/tool-ocamldoc/.ignore
new file mode 100644
index 0000000000..866d4be886
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/.ignore
@@ -0,0 +1,4 @@
+*.html
+*.sty
+*.css
+ocamldoc.out
diff --git a/testsuite/tests/tool-ocamldoc/Makefile b/testsuite/tests/tool-ocamldoc/Makefile
new file mode 100644
index 0000000000..976010e5f0
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/Makefile
@@ -0,0 +1,49 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+CUSTOM_MODULE=odoc_test
+COMPFLAGS=-I $(OTOPDIR)/ocamldoc
+LD_PATH=$(TOPDIR)/otherlibs/$(UNIXLIBVAR)unix:$(TOPDIR)/otherlibs/str
+DOCFLAGS=-I $(OTOPDIR)/stdlib $(COMPFLAGS)
+
+.PHONY: default
+default:
+ @if ! $(SUPPORTS_SHARED_LIBRARIES); then \
+ echo 'skipped (shared libraries not available)'; \
+ else \
+ $(SET_LD_PATH) $(MAKE) run; \
+ fi
+
+.PHONY: run
+run: $(CUSTOM_MODULE).cmo
+ @for file in t*.ml; do \
+ printf " ... testing '$$file'"; \
+ F="`basename $$file .ml`"; \
+ $(OCAMLDOC) $(DOCFLAGS) -hide-warnings -g $(CUSTOM_MODULE).cmo \
+ -o $$F.result $$file; \
+ $(DIFF) $$F.reference $$F.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done;
+ @$(OCAMLDOC) $(DOCFLAGS) -hide-warnings -html t*.ml 2>&1 \
+ | grep -v test_types_display || true
+ @$(OCAMLDOC) $(DOCFLAGS) -hide-warnings -latex t*.ml 2>&1 \
+ | grep -v test_types_display || true
+
+.PHONY: promote
+promote: defaultpromote
+
+.PHONY: clean
+clean: defaultclean
+ @rm -f *.result *.html *.tex *.log *.out *.sty *.toc *.css *.aux
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/tool-ocamldoc/odoc_test.ml b/testsuite/tests/tool-ocamldoc/odoc_test.ml
new file mode 100644
index 0000000000..9e34bb2a1c
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/odoc_test.ml
@@ -0,0 +1,128 @@
+(***********************************************************************)
+(* *)
+(* OCamldoc *)
+(* *)
+(* Maxence Guesdon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2004 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Custom generator to perform test on ocamldoc. *)
+
+open Odoc_info
+open Odoc_info.Module
+open Odoc_info.Type
+
+type test_kind =
+ Types_display
+
+let p = Format.fprintf
+
+class string_gen =
+ object(self)
+ inherit Odoc_info.Scan.scanner
+
+ val mutable test_kinds = []
+ val mutable fmt = Format.str_formatter
+
+ method must_display_types = List.mem Types_display test_kinds
+
+ method set_test_kinds_from_module m =
+ test_kinds <- List.fold_left
+ (fun acc (s, _) ->
+ match s with
+ "test_types_display" -> Types_display :: acc
+ | _ -> acc
+ )
+ []
+ (
+ match m.m_info with
+ None -> []
+ | Some i -> i.i_custom
+ )
+ method! scan_type t =
+ match test_kinds with
+ [] -> ()
+ | _ ->
+ p fmt "# type %s:\n" t.ty_name;
+ if self#must_display_types then
+ (
+ p fmt "# manifest (Odoc_info.string_of_type_expr):\n<[%s]>\n"
+ (match t.ty_manifest with
+ None -> "None"
+ | Some (Other e) -> Odoc_info.string_of_type_expr e
+ | Some (Object_type fields) ->
+ let b = Buffer.create 256 in
+ Buffer.add_string b "<";
+ List.iter
+ (fun fd ->
+ Printf.bprintf b " %s: %s ;"
+ fd.of_name
+ (Odoc_info.string_of_type_expr fd.of_type)
+ )
+ fields;
+ Buffer.add_string b " >";
+ Buffer.contents b
+ );
+ );
+
+
+ method! scan_module_pre m =
+ p fmt "#\n# module %s:\n" m.m_name ;
+ if self#must_display_types then
+ (
+ p fmt "# Odoc_info.string_of_module_type:\n<[%s]>\n"
+ (Odoc_info.string_of_module_type m.m_type);
+ p fmt "# Odoc_info.string_of_module_type ~complete: true :\n<[%s]>\n"
+ (Odoc_info.string_of_module_type ~complete: true m.m_type);
+ );
+ true
+
+ method! scan_module_type_pre m =
+ p fmt "#\n# module type %s:\n" m.mt_name ;
+ if self#must_display_types then
+ (
+ p fmt "# Odoc_info.string_of_module_type:\n<[%s]>\n"
+ (match m.mt_type with
+ None -> "None"
+ | Some t -> Odoc_info.string_of_module_type t
+ );
+ p fmt "# Odoc_info.string_of_module_type ~complete: true :\n<[%s]>\n"
+ (match m.mt_type with
+ None -> "None"
+ | Some t -> Odoc_info.string_of_module_type ~complete: true t
+ );
+ );
+ true
+
+ method generate (module_list: Odoc_info.Module.t_module list) =
+ let oc = open_out !Odoc_info.Global.out_file in
+ fmt <- Format.formatter_of_out_channel oc;
+ (
+ try
+ List.iter
+ (fun m ->
+ self#set_test_kinds_from_module m;
+ self#scan_module_list [m];
+ )
+ module_list
+ with
+ e ->
+ prerr_endline (Printexc.to_string e)
+ );
+ Format.pp_print_flush fmt ();
+ close_out oc
+ end
+
+let _ =
+ let module My_generator = struct
+ class generator =
+ let inst = new string_gen in
+ object
+ method generate = inst#generate
+ end
+ end in
+ Odoc_args.set_generator (Odoc_gen.Base (module My_generator : Odoc_gen.Base))
diff --git a/testsuite/tests/tool-ocamldoc/t01.ml b/testsuite/tests/tool-ocamldoc/t01.ml
new file mode 100644
index 0000000000..ee291b900b
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/t01.ml
@@ -0,0 +1,22 @@
+(** Testing display of types.
+
+ @test_types_display
+ *)
+
+let x = 1
+
+
+module M = struct
+ let y = 2
+
+end
+
+module type MT = sig
+ type t = string -> int -> string -> (string * string * string) ->
+ (string * string * string) ->
+ (string * string * string) -> unit
+ val y : int
+
+ type obj_type =
+ < foo : int ; bar : float -> string ; gee : int -> (int * string) >
+end
diff --git a/testsuite/tests/tool-ocamldoc/t01.reference b/testsuite/tests/tool-ocamldoc/t01.reference
new file mode 100644
index 0000000000..d5159bdfc9
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/t01.reference
@@ -0,0 +1,38 @@
+#
+# module T01:
+# Odoc_info.string_of_module_type:
+<[sig end]>
+# Odoc_info.string_of_module_type ~complete: true :
+<[sig end]>
+#
+# module T01.M:
+# Odoc_info.string_of_module_type:
+<[sig end]>
+# Odoc_info.string_of_module_type ~complete: true :
+<[sig val y : int end]>
+#
+# module type T01.MT:
+# Odoc_info.string_of_module_type:
+<[sig end]>
+# Odoc_info.string_of_module_type ~complete: true :
+<[sig
+ type t =
+ string ->
+ int ->
+ string ->
+ string * string * string ->
+ string * string * string -> string * string * string -> unit
+ val y : int
+ type obj_type =
+ < bar : float -> string; foo : int; gee : int -> int * string >
+end]>
+# type T01.MT.t:
+# manifest (Odoc_info.string_of_type_expr):
+<[string ->
+ int ->
+ string ->
+ string * string * string ->
+ string * string * string -> string * string * string -> unit]>
+# type T01.MT.obj_type:
+# manifest (Odoc_info.string_of_type_expr):
+<[< bar: float -> string ; foo: int ; gee: int -> int * string ; >]>
diff --git a/testsuite/tests/tool-ocamldoc/t02.ml b/testsuite/tests/tool-ocamldoc/t02.ml
new file mode 100644
index 0000000000..d7c9742134
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/t02.ml
@@ -0,0 +1,10 @@
+module Foo = struct type u type t = int let x = 1 end;;
+module type TFoo = module type of Foo;;
+
+module type TBar = TFoo with type u := float;;
+
+module type Gee =
+ sig
+ module M : module type of Foo
+ include module type of Foo
+ end
diff --git a/testsuite/tests/tool-ocamldoc/t02.reference b/testsuite/tests/tool-ocamldoc/t02.reference
new file mode 100644
index 0000000000..f1e7de43dd
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/t02.reference
@@ -0,0 +1,12 @@
+#
+# module T02:
+#
+# module T02.Foo:
+#
+# module type T02.TFoo:
+#
+# module type T02.TBar:
+#
+# module type T02.Gee:
+#
+# module T02.Gee.M:
diff --git a/testsuite/tests/tool-ocamldoc/t03.ml b/testsuite/tests/tool-ocamldoc/t03.ml
new file mode 100644
index 0000000000..9d9e1593b4
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/t03.ml
@@ -0,0 +1,12 @@
+module Foo = struct type t = int let x = 1 end;;
+module type MT = module type of Foo;;
+module Bar = struct type t = int let x = 2 end;;
+
+module type MT2 = sig type t val x : t end;;
+module type Gee = MT2 with type t = float ;;
+module T = (val
+ (if true
+ then (module Foo:MT2 with type t = int)
+ else (module Bar: MT2 with type t = int))
+ : MT2 with type t = int)
+;;
diff --git a/testsuite/tests/tool-ocamldoc/t03.reference b/testsuite/tests/tool-ocamldoc/t03.reference
new file mode 100644
index 0000000000..174e21991c
--- /dev/null
+++ b/testsuite/tests/tool-ocamldoc/t03.reference
@@ -0,0 +1,14 @@
+#
+# module T03:
+#
+# module T03.Foo:
+#
+# module type T03.MT:
+#
+# module T03.Bar:
+#
+# module type T03.MT2:
+#
+# module type T03.Gee:
+#
+# module T03.T:
diff --git a/testsuite/tests/tool-toplevel/Makefile b/testsuite/tests/tool-toplevel/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/tool-toplevel/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/tool-toplevel/tracing.ml b/testsuite/tests/tool-toplevel/tracing.ml
new file mode 100644
index 0000000000..5acaff238c
--- /dev/null
+++ b/testsuite/tests/tool-toplevel/tracing.ml
@@ -0,0 +1,4 @@
+List.fold_left;;
+#trace List.fold_left;;
+0;;
+List.fold_left (+) 0 [1;2;3];;
diff --git a/testsuite/tests/tool-toplevel/tracing.ml.reference b/testsuite/tests/tool-toplevel/tracing.ml.reference
new file mode 100644
index 0000000000..e6eda8d7f9
--- /dev/null
+++ b/testsuite/tests/tool-toplevel/tracing.ml.reference
@@ -0,0 +1,30 @@
+
+# - : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a = <fun>
+# List.fold_left is now traced.
+# - : int = 0
+# List.fold_left <-- <fun>
+List.fold_left --> <fun>
+List.fold_left* <-- <poly>
+List.fold_left* --> <fun>
+List.fold_left** <-- [<poly>; <poly>; <poly>]
+List.fold_left <-- <fun>
+List.fold_left --> <fun>
+List.fold_left* <-- <poly>
+List.fold_left* --> <fun>
+List.fold_left** <-- [<poly>; <poly>]
+List.fold_left <-- <fun>
+List.fold_left --> <fun>
+List.fold_left* <-- <poly>
+List.fold_left* --> <fun>
+List.fold_left** <-- [<poly>]
+List.fold_left <-- <fun>
+List.fold_left --> <fun>
+List.fold_left* <-- <poly>
+List.fold_left* --> <fun>
+List.fold_left** <-- []
+List.fold_left** --> <poly>
+List.fold_left** --> <poly>
+List.fold_left** --> <poly>
+List.fold_left** --> <poly>
+- : int = 6
+#
diff --git a/testsuite/tests/translprim/Makefile b/testsuite/tests/translprim/Makefile
new file mode 100644
index 0000000000..c4223d4522
--- /dev/null
+++ b/testsuite/tests/translprim/Makefile
@@ -0,0 +1,4 @@
+BASEDIR=../..
+TOPFLAGS+=-dlambda
+include $(BASEDIR)/makefiles/Makefile.dlambda
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/translprim/array_spec.ml b/testsuite/tests/translprim/array_spec.ml
new file mode 100644
index 0000000000..e78c96343c
--- /dev/null
+++ b/testsuite/tests/translprim/array_spec.ml
@@ -0,0 +1,62 @@
+external len : 'a array -> int = "%array_length"
+external safe_get : 'a array -> int -> 'a = "%array_safe_get"
+external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
+external safe_set : 'a array -> int -> 'a -> unit = "%array_safe_set"
+external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
+
+(* Specialization in application *)
+
+let int_a = [|1;2;3|];;
+let float_a = [|1.;2.;3.|];;
+let addr_a = [|"a";"b";"c"|];;
+
+len int_a;;
+len float_a;;
+len addr_a;;
+(fun a -> len a);;
+
+safe_get int_a 0;;
+safe_get float_a 0;;
+safe_get addr_a 0;;
+(fun a -> safe_get a 0);;
+
+unsafe_get int_a 0;;
+unsafe_get float_a 0;;
+unsafe_get addr_a 0;;
+(fun a -> unsafe_get a 0);;
+
+safe_set int_a 0 1;;
+safe_set float_a 0 1.;;
+safe_set addr_a 0 "a";;
+(fun a x -> safe_set a 0 x);;
+
+unsafe_set int_a 0 1;;
+unsafe_set float_a 0 1.;;
+unsafe_set addr_a 0 "a";;
+(fun a x -> unsafe_set a 0 x);;
+
+(* Specialization during eta-expansion *)
+
+let eta_gen_len : 'a array -> _ = len;;
+let eta_gen_safe_get : 'a array -> int -> 'a = safe_get;;
+let eta_gen_unsafe_get : 'a array -> int -> 'a = unsafe_get;;
+let eta_gen_safe_set : 'a array -> int -> 'a -> unit = safe_set;;
+let eta_gen_unsafe_set : 'a array -> int -> 'a -> unit = unsafe_set;;
+
+let eta_int_len : int array -> _ = len;;
+let eta_int_safe_get : int array -> int -> int = safe_get;;
+let eta_int_unsafe_get : int array -> int -> int = unsafe_get;;
+let eta_int_safe_set : int array -> int -> int -> unit = safe_set;;
+let eta_int_unsafe_set : int array -> int -> int -> unit = unsafe_set;;
+
+let eta_float_len : float array -> _ = len;;
+let eta_float_safe_get : float array -> int -> float = safe_get;;
+let eta_float_unsafe_get : float array -> int -> float = unsafe_get;;
+let eta_float_safe_set : float array -> int -> float -> unit = safe_set;;
+let eta_float_unsafe_set : float array -> int -> float -> unit = unsafe_set;;
+
+let eta_addr_len : string array -> _ = len;;
+let eta_addr_safe_get : string array -> int -> string = safe_get;;
+let eta_addr_unsafe_get : string array -> int -> string = unsafe_get;;
+let eta_addr_safe_set : string array -> int -> string -> unit = safe_set;;
+let eta_addr_unsafe_set : string array -> int -> string -> unit = unsafe_set;;
diff --git a/testsuite/tests/translprim/array_spec.ml.reference b/testsuite/tests/translprim/array_spec.ml.reference
new file mode 100644
index 0000000000..7b48cfdde5
--- /dev/null
+++ b/testsuite/tests/translprim/array_spec.ml.reference
@@ -0,0 +1,88 @@
+(setglobal Array_spec!
+ (let
+ (int_a = (makearray[int] 1 2 3)
+ float_a = (makearray[float] 1. 2. 3.)
+ addr_a = (makearray[addr] "a" "b" "c"))
+ (seq (array.length[int] int_a) (array.length[float] float_a)
+ (array.length[addr] addr_a)
+ (function a (array.length[gen] a))
+ (array.get[int] int_a 0) (array.get[float] float_a 0)
+ (array.get[addr] addr_a 0)
+ (function a (array.get[gen] a 0))
+ (array.unsafe_get[int] int_a 0)
+ (array.unsafe_get[float] float_a 0)
+ (array.unsafe_get[addr] addr_a 0)
+ (function a (array.unsafe_get[gen] a 0))
+ (array.set[int] int_a 0 1) (array.set[float] float_a 0 1.)
+ (array.set[addr] addr_a 0 "a")
+ (function a x (array.set[gen] a 0 x))
+ (array.unsafe_set[int] int_a 0 1)
+ (array.unsafe_set[float] float_a 0 1.)
+ (array.unsafe_set[addr] addr_a 0 "a")
+ (function a x (array.unsafe_set[gen] a 0 x))
+ (let
+ (eta_gen_len =
+ (function prim (array.length[gen] prim))
+ eta_gen_safe_get =
+ (function prim prim
+ (array.get[gen] prim prim))
+ eta_gen_unsafe_get =
+ (function prim prim
+ (array.unsafe_get[gen] prim prim))
+ eta_gen_safe_set =
+ (function prim prim prim
+ (array.set[gen] prim prim prim))
+ eta_gen_unsafe_set =
+ (function prim prim prim
+ (array.unsafe_set[gen] prim prim prim))
+ eta_int_len =
+ (function prim (array.length[int] prim))
+ eta_int_safe_get =
+ (function prim prim
+ (array.get[int] prim prim))
+ eta_int_unsafe_get =
+ (function prim prim
+ (array.unsafe_get[int] prim prim))
+ eta_int_safe_set =
+ (function prim prim prim
+ (array.set[int] prim prim prim))
+ eta_int_unsafe_set =
+ (function prim prim prim
+ (array.unsafe_set[int] prim prim prim))
+ eta_float_len =
+ (function prim (array.length[float] prim))
+ eta_float_safe_get =
+ (function prim prim
+ (array.get[float] prim prim))
+ eta_float_unsafe_get =
+ (function prim prim
+ (array.unsafe_get[float] prim prim))
+ eta_float_safe_set =
+ (function prim prim prim
+ (array.set[float] prim prim prim))
+ eta_float_unsafe_set =
+ (function prim prim prim
+ (array.unsafe_set[float] prim prim prim))
+ eta_addr_len =
+ (function prim (array.length[addr] prim))
+ eta_addr_safe_get =
+ (function prim prim
+ (array.get[addr] prim prim))
+ eta_addr_unsafe_get =
+ (function prim prim
+ (array.unsafe_get[addr] prim prim))
+ eta_addr_safe_set =
+ (function prim prim prim
+ (array.set[addr] prim prim prim))
+ eta_addr_unsafe_set =
+ (function prim prim prim
+ (array.unsafe_set[addr] prim prim prim)))
+ (makeblock 0 int_a float_a addr_a eta_gen_len
+ eta_gen_safe_get eta_gen_unsafe_get eta_gen_safe_set
+ eta_gen_unsafe_set eta_int_len eta_int_safe_get
+ eta_int_unsafe_get eta_int_safe_set
+ eta_int_unsafe_set eta_float_len eta_float_safe_get
+ eta_float_unsafe_get eta_float_safe_set
+ eta_float_unsafe_set eta_addr_len eta_addr_safe_get
+ eta_addr_unsafe_get eta_addr_safe_set
+ eta_addr_unsafe_set)))))
diff --git a/testsuite/tests/translprim/comparison_table.ml b/testsuite/tests/translprim/comparison_table.ml
new file mode 100644
index 0000000000..129ea5c55f
--- /dev/null
+++ b/testsuite/tests/translprim/comparison_table.ml
@@ -0,0 +1,239 @@
+external cmp : 'a -> 'a -> int = "%compare";;
+external eq : 'a -> 'a -> bool = "%equal";;
+external ne : 'a -> 'a -> bool = "%notequal";;
+external lt : 'a -> 'a -> bool = "%lessthan";;
+external gt : 'a -> 'a -> bool = "%greaterthan";;
+external le : 'a -> 'a -> bool = "%lessequal";;
+external ge : 'a -> 'a -> bool = "%greaterequal";;
+
+type intlike = A | B | C | D
+
+(* Check specialization in explicit application *)
+
+let gen_cmp x y = cmp x y;;
+let int_cmp (x : int) y = cmp x y;;
+let bool_cmp (x : bool) y = cmp x y;;
+let intlike_cmp (x : intlike) y = cmp x y;;
+let float_cmp (x : float) y = cmp x y;;
+let string_cmp (x : string) y = cmp x y;;
+let int32_cmp (x : int32) y = cmp x y;;
+let int64_cmp (x : int64) y = cmp x y;;
+let nativeint_cmp (x : nativeint) y = cmp x y;;
+
+let gen_eq x y = eq x y;;
+let int_eq (x : int) y = eq x y;;
+let bool_eq (x : bool) y = eq x y;;
+let intlike_eq (x : intlike) y = eq x y;;
+let float_eq (x : float) y = eq x y;;
+let string_eq (x : string) y = eq x y;;
+let int32_eq (x : int32) y = eq x y;;
+let int64_eq (x : int64) y = eq x y;;
+let nativeint_eq (x : nativeint) y = eq x y;;
+
+let gen_ne x y = ne x y;;
+let int_ne (x : int) y = ne x y;;
+let bool_ne (x : bool) y = ne x y;;
+let intlike_ne (x : intlike) y = ne x y;;
+let float_ne (x : float) y = ne x y;;
+let string_ne (x : string) y = ne x y;;
+let int32_ne (x : int32) y = ne x y;;
+let int64_ne (x : int64) y = ne x y;;
+let nativeint_ne (x : nativeint) y = ne x y;;
+
+let gen_lt x y = lt x y;;
+let int_lt (x : int) y = lt x y;;
+let bool_lt (x : bool) y = lt x y;;
+let intlike_lt (x : intlike) y = lt x y;;
+let float_lt (x : float) y = lt x y;;
+let string_lt (x : string) y = lt x y;;
+let int32_lt (x : int32) y = lt x y;;
+let int64_lt (x : int64) y = lt x y;;
+let nativeint_lt (x : nativeint) y = lt x y;;
+
+let gen_gt x y = gt x y;;
+let int_gt (x : int) y = gt x y;;
+let bool_gt (x : bool) y = gt x y;;
+let intlike_gt (x : intlike) y = gt x y;;
+let float_gt (x : float) y = gt x y;;
+let string_gt (x : string) y = gt x y;;
+let int32_gt (x : int32) y = gt x y;;
+let int64_gt (x : int64) y = gt x y;;
+let nativeint_gt (x : nativeint) y = gt x y;;
+
+let gen_le x y = le x y;;
+let int_le (x : int) y = le x y;;
+let bool_le (x : bool) y = le x y;;
+let intlike_le (x : intlike) y = le x y;;
+let float_le (x : float) y = le x y;;
+let string_le (x : string) y = le x y;;
+let int32_le (x : int32) y = le x y;;
+let int64_le (x : int64) y = le x y;;
+let nativeint_le (x : nativeint) y = le x y;;
+
+let gen_ge x y = ge x y;;
+let int_ge (x : int) y = ge x y;;
+let bool_ge (x : bool) y = ge x y;;
+let intlike_ge (x : intlike) y = ge x y;;
+let float_ge (x : float) y = ge x y;;
+let string_ge (x : string) y = ge x y;;
+let int32_ge (x : int32) y = ge x y;;
+let int64_ge (x : int64) y = ge x y;;
+let nativeint_ge (x : nativeint) y = ge x y;;
+
+(* Check specialization in eta-expansion *)
+
+let eta_gen_cmp : 'a -> _ = cmp;;
+let eta_int_cmp : int -> _ = cmp;;
+let eta_bool_cmp : bool -> _ = cmp;;
+let eta_intlike_cmp : intlike -> _ = cmp;;
+let eta_float_cmp : float -> _ = cmp;;
+let eta_string_cmp : string -> _ = cmp;;
+let eta_int32_cmp : int32 -> _ = cmp;;
+let eta_int64_cmp : int64 -> _ = cmp;;
+let eta_nativeint_cmp : nativeint -> _ = cmp;;
+
+let eta_gen_eq : 'a -> _ = eq;;
+let eta_int_eq : int -> _ = eq;;
+let eta_bool_eq : bool -> _ = eq;;
+let eta_intlike_eq : intlike -> _ = eq;;
+let eta_float_eq : float -> _ = eq;;
+let eta_string_eq : string -> _ = eq;;
+let eta_int32_eq : int32 -> _ = eq;;
+let eta_int64_eq : int64 -> _ = eq;;
+let eta_nativeint_eq : nativeint -> _ = eq;;
+
+let eta_gen_ne : 'a -> _ = ne;;
+let eta_int_ne : int -> _ = ne;;
+let eta_bool_ne : bool -> _ = ne;;
+let eta_intlike_ne : intlike -> _ = ne;;
+let eta_float_ne : float -> _ = ne;;
+let eta_string_ne : string -> _ = ne;;
+let eta_int32_ne : int32 -> _ = ne;;
+let eta_int64_ne : int64 -> _ = ne;;
+let eta_nativeint_ne : nativeint -> _ = ne;;
+
+let eta_gen_lt : 'a -> _ = lt;;
+let eta_int_lt : int -> _ = lt;;
+let eta_bool_lt : bool -> _ = lt;;
+let eta_intlike_lt : intlike -> _ = lt;;
+let eta_float_lt : float -> _ = lt;;
+let eta_string_lt : string -> _ = lt;;
+let eta_int32_lt : int32 -> _ = lt;;
+let eta_int64_lt : int64 -> _ = lt;;
+let eta_nativeint_lt : nativeint -> _ = lt;;
+
+let eta_gen_gt : 'a -> _ = gt;;
+let eta_int_gt : int -> _ = gt;;
+let eta_bool_gt : bool -> _ = gt;;
+let eta_intlike_gt : intlike -> _ = gt;;
+let eta_float_gt : float -> _ = gt;;
+let eta_string_gt : string -> _ = gt;;
+let eta_int32_gt : int32 -> _ = gt;;
+let eta_int64_gt : int64 -> _ = gt;;
+let eta_nativeint_gt : nativeint -> _ = gt;;
+
+let eta_gen_le : 'a -> _ = le;;
+let eta_int_le : int -> _ = le;;
+let eta_bool_le : bool -> _ = le;;
+let eta_intlike_le : intlike -> _ = le;;
+let eta_float_le : float -> _ = le;;
+let eta_string_le : string -> _ = le;;
+let eta_int32_le : int32 -> _ = le;;
+let eta_int64_le : int64 -> _ = le;;
+let eta_nativeint_le : nativeint -> _ = le;;
+
+let eta_gen_ge : 'a -> _ = ge;;
+let eta_int_ge : int -> _ = ge;;
+let eta_bool_ge : bool -> _ = ge;;
+let eta_intlike_ge : intlike -> _ = ge;;
+let eta_float_ge : float -> _ = ge;;
+let eta_string_ge : string -> _ = ge;;
+let eta_int32_ge : int32 -> _ = ge;;
+let eta_int64_ge : int64 -> _ = ge;;
+let eta_nativeint_ge : nativeint -> _ = ge;;
+
+(* Check results of computations *)
+
+let int_vec = [(1,1);(1,2);(2,1)];;
+let bool_vec = [(false,false);(false,true);(true,false)];;
+let intlike_vec = [(A,A);(A,B);(B,A)];;
+let float_vec = [(1.,1.);(1.,2.);(2.,1.)];;
+let string_vec = [("1","1");("1","2");("2","1")];;
+let int32_vec = [(1l,1l);(1l,2l);(2l,1l)];;
+let int64_vec = [(1L,1L);(1L,2L);(2L,1L)];;
+let nativeint_vec = [(1n,1n);(1n,2n);(2n,1n)];;
+
+let test_vec cmp eq ne lt gt le ge vec =
+ let uncurry f (x,y) = f x y in
+ let map f l = List.map (uncurry f) l in
+ (map gen_cmp vec, map cmp vec),
+ (map (fun gen spec -> map gen vec, map spec vec)
+ [gen_eq,eq; gen_ne,ne; gen_lt,lt; gen_gt,gt; gen_le,le; gen_ge,ge])
+;;
+
+test_vec
+ int_cmp int_eq int_ne int_lt int_gt int_le int_ge
+ int_vec;;
+test_vec
+ bool_cmp bool_eq bool_ne bool_lt bool_gt bool_le bool_ge
+ bool_vec;;
+test_vec
+ intlike_cmp intlike_eq intlike_ne intlike_lt intlike_gt intlike_le intlike_ge
+ intlike_vec;;
+test_vec
+ float_cmp float_eq float_ne float_lt float_gt float_le float_ge
+ float_vec;;
+test_vec
+ string_cmp string_eq string_ne string_lt string_gt string_le string_ge
+ string_vec;;
+test_vec
+ int32_cmp int32_eq int32_ne int32_lt int32_gt int32_le int32_ge
+ int32_vec;;
+test_vec
+ int64_cmp int64_eq int64_ne int64_lt int64_gt int64_le int64_ge
+ int64_vec;;
+test_vec
+ nativeint_cmp nativeint_eq nativeint_ne
+ nativeint_lt nativeint_gt nativeint_le nativeint_ge
+ nativeint_vec;;
+
+let eta_test_vec cmp eq ne lt gt le ge vec =
+ let uncurry f (x,y) = f x y in
+ let map f l = List.map (uncurry f) l in
+ (map eta_gen_cmp vec, map cmp vec),
+ (map (fun gen spec -> map gen vec, map spec vec)
+ [eta_gen_eq,eq; eta_gen_ne,ne; eta_gen_lt,lt;
+ eta_gen_gt,gt; eta_gen_le,le; eta_gen_ge,ge])
+;;
+
+eta_test_vec
+ eta_int_cmp eta_int_eq eta_int_ne eta_int_lt eta_int_gt eta_int_le eta_int_ge
+ int_vec;;
+eta_test_vec
+ eta_bool_cmp eta_bool_eq eta_bool_ne eta_bool_lt eta_bool_gt
+ eta_bool_le eta_bool_ge
+ bool_vec;;
+eta_test_vec
+ eta_intlike_cmp eta_intlike_eq eta_intlike_ne eta_intlike_lt eta_intlike_gt
+ eta_intlike_le eta_intlike_ge
+ intlike_vec;;
+eta_test_vec
+ eta_float_cmp eta_float_eq eta_float_ne eta_float_lt eta_float_gt
+ eta_float_le eta_float_ge
+ float_vec;;
+eta_test_vec
+ eta_string_cmp eta_string_eq eta_string_ne eta_string_lt eta_string_gt
+ eta_string_le eta_string_ge
+ string_vec;;
+eta_test_vec
+ eta_int32_cmp eta_int32_eq eta_int32_ne eta_int32_lt eta_int32_gt
+ eta_int32_le eta_int32_ge
+ int32_vec;;
+eta_test_vec
+ eta_int64_cmp eta_int64_eq eta_int64_ne eta_int64_lt eta_int64_gt
+ eta_int64_le eta_int64_ge
+ int64_vec;;
+eta_test_vec
+ eta_nativeint_cmp eta_nativeint_eq eta_nativeint_ne
+ eta_nativeint_lt eta_nativeint_gt eta_nativeint_le eta_nativeint_ge
+ nativeint_vec;;
diff --git a/testsuite/tests/translprim/comparison_table.ml.reference b/testsuite/tests/translprim/comparison_table.ml.reference
new file mode 100644
index 0000000000..525ff898cf
--- /dev/null
+++ b/testsuite/tests/translprim/comparison_table.ml.reference
@@ -0,0 +1,364 @@
+(setglobal Comparison_table!
+ (let
+ (gen_cmp = (function x y (caml_compare x y))
+ int_cmp = (function x y (caml_int_compare x y))
+ bool_cmp =
+ (function x y (caml_int_compare x y))
+ intlike_cmp =
+ (function x y (caml_int_compare x y))
+ float_cmp =
+ (function x y (caml_float_compare x y))
+ string_cmp =
+ (function x y (caml_string_compare x y))
+ int32_cmp =
+ (function x y (caml_int32_compare x y))
+ int64_cmp =
+ (function x y (caml_int64_compare x y))
+ nativeint_cmp =
+ (function x y (caml_nativeint_compare x y))
+ gen_eq = (function x y (caml_equal x y))
+ int_eq = (function x y (== x y))
+ bool_eq = (function x y (== x y))
+ intlike_eq = (function x y (== x y))
+ float_eq = (function x y (==. x y))
+ string_eq =
+ (function x y (caml_string_equal x y))
+ int32_eq = (function x y (Int32.== x y))
+ int64_eq = (function x y (Int64.== x y))
+ nativeint_eq =
+ (function x y (Nativeint.== x y))
+ gen_ne = (function x y (caml_notequal x y))
+ int_ne = (function x y (!= x y))
+ bool_ne = (function x y (!= x y))
+ intlike_ne = (function x y (!= x y))
+ float_ne = (function x y (!=. x y))
+ string_ne =
+ (function x y (caml_string_notequal x y))
+ int32_ne = (function x y (Int32.!= x y))
+ int64_ne = (function x y (Int64.!= x y))
+ nativeint_ne =
+ (function x y (Nativeint.!= x y))
+ gen_lt = (function x y (caml_lessthan x y))
+ int_lt = (function x y (< x y))
+ bool_lt = (function x y (< x y))
+ intlike_lt = (function x y (< x y))
+ float_lt = (function x y (<. x y))
+ string_lt =
+ (function x y (caml_string_lessthan x y))
+ int32_lt = (function x y (Int32.< x y))
+ int64_lt = (function x y (Int64.< x y))
+ nativeint_lt = (function x y (Nativeint.< x y))
+ gen_gt = (function x y (caml_greaterthan x y))
+ int_gt = (function x y (> x y))
+ bool_gt = (function x y (> x y))
+ intlike_gt = (function x y (> x y))
+ float_gt = (function x y (>. x y))
+ string_gt =
+ (function x y (caml_string_greaterthan x y))
+ int32_gt = (function x y (Int32.> x y))
+ int64_gt = (function x y (Int64.> x y))
+ nativeint_gt = (function x y (Nativeint.> x y))
+ gen_le = (function x y (caml_lessequal x y))
+ int_le = (function x y (<= x y))
+ bool_le = (function x y (<= x y))
+ intlike_le = (function x y (<= x y))
+ float_le = (function x y (<=. x y))
+ string_le =
+ (function x y (caml_string_lessequal x y))
+ int32_le = (function x y (Int32.<= x y))
+ int64_le = (function x y (Int64.<= x y))
+ nativeint_le =
+ (function x y (Nativeint.<= x y))
+ gen_ge = (function x y (caml_greaterequal x y))
+ int_ge = (function x y (>= x y))
+ bool_ge = (function x y (>= x y))
+ intlike_ge = (function x y (>= x y))
+ float_ge = (function x y (>=. x y))
+ string_ge =
+ (function x y (caml_string_greaterequal x y))
+ int32_ge = (function x y (Int32.>= x y))
+ int64_ge = (function x y (Int64.>= x y))
+ nativeint_ge =
+ (function x y (Nativeint.>= x y))
+ eta_gen_cmp =
+ (function prim prim (caml_compare prim prim))
+ eta_int_cmp =
+ (function prim prim (caml_int_compare prim prim))
+ eta_bool_cmp =
+ (function prim prim (caml_int_compare prim prim))
+ eta_intlike_cmp =
+ (function prim prim (caml_int_compare prim prim))
+ eta_float_cmp =
+ (function prim prim
+ (caml_float_compare prim prim))
+ eta_string_cmp =
+ (function prim prim
+ (caml_string_compare prim prim))
+ eta_int32_cmp =
+ (function prim prim
+ (caml_int32_compare prim prim))
+ eta_int64_cmp =
+ (function prim prim
+ (caml_int64_compare prim prim))
+ eta_nativeint_cmp =
+ (function prim prim
+ (caml_nativeint_compare prim prim))
+ eta_gen_eq =
+ (function prim prim (caml_equal prim prim))
+ eta_int_eq =
+ (function prim prim (== prim prim))
+ eta_bool_eq =
+ (function prim prim (== prim prim))
+ eta_intlike_eq =
+ (function prim prim (== prim prim))
+ eta_float_eq =
+ (function prim prim (==. prim prim))
+ eta_string_eq =
+ (function prim prim (caml_string_equal prim prim))
+ eta_int32_eq =
+ (function prim prim (Int32.== prim prim))
+ eta_int64_eq =
+ (function prim prim (Int64.== prim prim))
+ eta_nativeint_eq =
+ (function prim prim (Nativeint.== prim prim))
+ eta_gen_ne =
+ (function prim prim (caml_notequal prim prim))
+ eta_int_ne =
+ (function prim prim (!= prim prim))
+ eta_bool_ne =
+ (function prim prim (!= prim prim))
+ eta_intlike_ne =
+ (function prim prim (!= prim prim))
+ eta_float_ne =
+ (function prim prim (!=. prim prim))
+ eta_string_ne =
+ (function prim prim
+ (caml_string_notequal prim prim))
+ eta_int32_ne =
+ (function prim prim (Int32.!= prim prim))
+ eta_int64_ne =
+ (function prim prim (Int64.!= prim prim))
+ eta_nativeint_ne =
+ (function prim prim (Nativeint.!= prim prim))
+ eta_gen_lt =
+ (function prim prim (caml_lessthan prim prim))
+ eta_int_lt = (function prim prim (< prim prim))
+ eta_bool_lt =
+ (function prim prim (< prim prim))
+ eta_intlike_lt =
+ (function prim prim (< prim prim))
+ eta_float_lt =
+ (function prim prim (<. prim prim))
+ eta_string_lt =
+ (function prim prim
+ (caml_string_lessthan prim prim))
+ eta_int32_lt =
+ (function prim prim (Int32.< prim prim))
+ eta_int64_lt =
+ (function prim prim (Int64.< prim prim))
+ eta_nativeint_lt =
+ (function prim prim (Nativeint.< prim prim))
+ eta_gen_gt =
+ (function prim prim (caml_greaterthan prim prim))
+ eta_int_gt = (function prim prim (> prim prim))
+ eta_bool_gt =
+ (function prim prim (> prim prim))
+ eta_intlike_gt =
+ (function prim prim (> prim prim))
+ eta_float_gt =
+ (function prim prim (>. prim prim))
+ eta_string_gt =
+ (function prim prim
+ (caml_string_greaterthan prim prim))
+ eta_int32_gt =
+ (function prim prim (Int32.> prim prim))
+ eta_int64_gt =
+ (function prim prim (Int64.> prim prim))
+ eta_nativeint_gt =
+ (function prim prim (Nativeint.> prim prim))
+ eta_gen_le =
+ (function prim prim (caml_lessequal prim prim))
+ eta_int_le =
+ (function prim prim (<= prim prim))
+ eta_bool_le =
+ (function prim prim (<= prim prim))
+ eta_intlike_le =
+ (function prim prim (<= prim prim))
+ eta_float_le =
+ (function prim prim (<=. prim prim))
+ eta_string_le =
+ (function prim prim
+ (caml_string_lessequal prim prim))
+ eta_int32_le =
+ (function prim prim (Int32.<= prim prim))
+ eta_int64_le =
+ (function prim prim (Int64.<= prim prim))
+ eta_nativeint_le =
+ (function prim prim (Nativeint.<= prim prim))
+ eta_gen_ge =
+ (function prim prim (caml_greaterequal prim prim))
+ eta_int_ge =
+ (function prim prim (>= prim prim))
+ eta_bool_ge =
+ (function prim prim (>= prim prim))
+ eta_intlike_ge =
+ (function prim prim (>= prim prim))
+ eta_float_ge =
+ (function prim prim (>=. prim prim))
+ eta_string_ge =
+ (function prim prim
+ (caml_string_greaterequal prim prim))
+ eta_int32_ge =
+ (function prim prim (Int32.>= prim prim))
+ eta_int64_ge =
+ (function prim prim (Int64.>= prim prim))
+ eta_nativeint_ge =
+ (function prim prim (Nativeint.>= prim prim))
+ int_vec = [0: [0: 1 1] [0: [0: 1 2] [0: [0: 2 1] 0a]]]
+ bool_vec = [0: [0: 0a 0a] [0: [0: 0a 1a] [0: [0: 1a 0a] 0a]]]
+ intlike_vec = [0: [0: 0a 0a] [0: [0: 0a 1a] [0: [0: 1a 0a] 0a]]]
+ float_vec = [0: [0: 1. 1.] [0: [0: 1. 2.] [0: [0: 2. 1.] 0a]]]
+ string_vec =
+ [0: [0: "1" "1"] [0: [0: "1" "2"] [0: [0: "2" "1"] 0a]]]
+ int32_vec = [0: [0: 1l 1l] [0: [0: 1l 2l] [0: [0: 2l 1l] 0a]]]
+ int64_vec = [0: [0: 1L 1L] [0: [0: 1L 2L] [0: [0: 2L 1L] 0a]]]
+ nativeint_vec = [0: [0: 1n 1n] [0: [0: 1n 2n] [0: [0: 2n 1n] 0a]]]
+ test_vec =
+ (function cmp eq ne lt gt le ge
+ vec
+ (let
+ (uncurry =
+ (function f param
+ (apply f (field 0 param) (field 1 param)))
+ map =
+ (function f l
+ (apply (field 12 (global List!)) (apply uncurry f)
+ l)))
+ (makeblock 0
+ (makeblock 0 (apply map gen_cmp vec)
+ (apply map cmp vec))
+ (apply map
+ (function gen spec
+ (makeblock 0 (apply map gen vec)
+ (apply map spec vec)))
+ (makeblock 0 (makeblock 0 gen_eq eq)
+ (makeblock 0 (makeblock 0 gen_ne ne)
+ (makeblock 0 (makeblock 0 gen_lt lt)
+ (makeblock 0 (makeblock 0 gen_gt gt)
+ (makeblock 0 (makeblock 0 gen_le le)
+ (makeblock 0 (makeblock 0 gen_ge ge) 0a)))))))))))
+ (seq
+ (apply test_vec int_cmp int_eq int_ne int_lt
+ int_gt int_le int_ge int_vec)
+ (apply test_vec bool_cmp bool_eq bool_ne
+ bool_lt bool_gt bool_le bool_ge bool_vec)
+ (apply test_vec intlike_cmp intlike_eq intlike_ne
+ intlike_lt intlike_gt intlike_le intlike_ge
+ intlike_vec)
+ (apply test_vec float_cmp float_eq float_ne
+ float_lt float_gt float_le float_ge
+ float_vec)
+ (apply test_vec string_cmp string_eq string_ne
+ string_lt string_gt string_le string_ge
+ string_vec)
+ (apply test_vec int32_cmp int32_eq int32_ne
+ int32_lt int32_gt int32_le int32_ge
+ int32_vec)
+ (apply test_vec int64_cmp int64_eq int64_ne
+ int64_lt int64_gt int64_le int64_ge
+ int64_vec)
+ (apply test_vec nativeint_cmp nativeint_eq
+ nativeint_ne nativeint_lt nativeint_gt
+ nativeint_le nativeint_ge nativeint_vec)
+ (let
+ (eta_test_vec =
+ (function cmp eq ne lt gt le ge
+ vec
+ (let
+ (uncurry =
+ (function f param
+ (apply f (field 0 param) (field 1 param)))
+ map =
+ (function f l
+ (apply (field 12 (global List!))
+ (apply uncurry f) l)))
+ (makeblock 0
+ (makeblock 0 (apply map eta_gen_cmp vec)
+ (apply map cmp vec))
+ (apply map
+ (function gen spec
+ (makeblock 0 (apply map gen vec)
+ (apply map spec vec)))
+ (makeblock 0 (makeblock 0 eta_gen_eq eq)
+ (makeblock 0 (makeblock 0 eta_gen_ne ne)
+ (makeblock 0 (makeblock 0 eta_gen_lt lt)
+ (makeblock 0 (makeblock 0 eta_gen_gt gt)
+ (makeblock 0 (makeblock 0 eta_gen_le le)
+ (makeblock 0
+ (makeblock 0 eta_gen_ge ge) 0a)))))))))))
+ (seq
+ (apply eta_test_vec eta_int_cmp eta_int_eq
+ eta_int_ne eta_int_lt eta_int_gt eta_int_le
+ eta_int_ge int_vec)
+ (apply eta_test_vec eta_bool_cmp eta_bool_eq
+ eta_bool_ne eta_bool_lt eta_bool_gt
+ eta_bool_le eta_bool_ge bool_vec)
+ (apply eta_test_vec eta_intlike_cmp eta_intlike_eq
+ eta_intlike_ne eta_intlike_lt eta_intlike_gt
+ eta_intlike_le eta_intlike_ge intlike_vec)
+ (apply eta_test_vec eta_float_cmp eta_float_eq
+ eta_float_ne eta_float_lt eta_float_gt
+ eta_float_le eta_float_ge float_vec)
+ (apply eta_test_vec eta_string_cmp eta_string_eq
+ eta_string_ne eta_string_lt eta_string_gt
+ eta_string_le eta_string_ge string_vec)
+ (apply eta_test_vec eta_int32_cmp eta_int32_eq
+ eta_int32_ne eta_int32_lt eta_int32_gt
+ eta_int32_le eta_int32_ge int32_vec)
+ (apply eta_test_vec eta_int64_cmp eta_int64_eq
+ eta_int64_ne eta_int64_lt eta_int64_gt
+ eta_int64_le eta_int64_ge int64_vec)
+ (apply eta_test_vec eta_nativeint_cmp
+ eta_nativeint_eq eta_nativeint_ne eta_nativeint_lt
+ eta_nativeint_gt eta_nativeint_le eta_nativeint_ge
+ nativeint_vec)
+ (makeblock 0 gen_cmp int_cmp bool_cmp
+ intlike_cmp float_cmp string_cmp int32_cmp
+ int64_cmp nativeint_cmp gen_eq int_eq
+ bool_eq intlike_eq float_eq string_eq
+ int32_eq int64_eq nativeint_eq gen_ne
+ int_ne bool_ne intlike_ne float_ne
+ string_ne int32_ne int64_ne nativeint_ne
+ gen_lt int_lt bool_lt intlike_lt
+ float_lt string_lt int32_lt int64_lt
+ nativeint_lt gen_gt int_gt bool_gt
+ intlike_gt float_gt string_gt int32_gt
+ int64_gt nativeint_gt gen_le int_le
+ bool_le intlike_le float_le string_le
+ int32_le int64_le nativeint_le gen_ge
+ int_ge bool_ge intlike_ge float_ge
+ string_ge int32_ge int64_ge nativeint_ge
+ eta_gen_cmp eta_int_cmp eta_bool_cmp
+ eta_intlike_cmp eta_float_cmp eta_string_cmp
+ eta_int32_cmp eta_int64_cmp eta_nativeint_cmp
+ eta_gen_eq eta_int_eq eta_bool_eq
+ eta_intlike_eq eta_float_eq eta_string_eq
+ eta_int32_eq eta_int64_eq eta_nativeint_eq
+ eta_gen_ne eta_int_ne eta_bool_ne
+ eta_intlike_ne eta_float_ne eta_string_ne
+ eta_int32_ne eta_int64_ne eta_nativeint_ne
+ eta_gen_lt eta_int_lt eta_bool_lt
+ eta_intlike_lt eta_float_lt eta_string_lt
+ eta_int32_lt eta_int64_lt eta_nativeint_lt
+ eta_gen_gt eta_int_gt eta_bool_gt
+ eta_intlike_gt eta_float_gt eta_string_gt
+ eta_int32_gt eta_int64_gt eta_nativeint_gt
+ eta_gen_le eta_int_le eta_bool_le
+ eta_intlike_le eta_float_le eta_string_le
+ eta_int32_le eta_int64_le eta_nativeint_le
+ eta_gen_ge eta_int_ge eta_bool_ge
+ eta_intlike_ge eta_float_ge eta_string_ge
+ eta_int32_ge eta_int64_ge eta_nativeint_ge
+ int_vec bool_vec intlike_vec float_vec
+ string_vec int32_vec int64_vec nativeint_vec
+ test_vec eta_test_vec))))))
diff --git a/testsuite/tests/translprim/module_coercion.ml b/testsuite/tests/translprim/module_coercion.ml
new file mode 100644
index 0000000000..041b30341f
--- /dev/null
+++ b/testsuite/tests/translprim/module_coercion.ml
@@ -0,0 +1,37 @@
+module M = struct
+ external len : 'a array -> int = "%array_length"
+ external safe_get : 'a array -> int -> 'a = "%array_safe_get"
+ external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
+ external safe_set : 'a array -> int -> 'a -> unit = "%array_safe_set"
+ external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
+ external cmp : 'a -> 'a -> int = "%compare";;
+ external eq : 'a -> 'a -> bool = "%equal";;
+ external ne : 'a -> 'a -> bool = "%notequal";;
+ external lt : 'a -> 'a -> bool = "%lessthan";;
+ external gt : 'a -> 'a -> bool = "%greaterthan";;
+ external le : 'a -> 'a -> bool = "%lessequal";;
+ external ge : 'a -> 'a -> bool = "%greaterequal";;
+end;;
+
+module type T = sig
+ type t
+ val len : t array -> int
+ val safe_get : t array -> int -> t
+ val unsafe_get : t array -> int -> t
+ val safe_set : t array -> int -> t -> unit
+ val unsafe_set : t array -> int -> t -> unit
+ val cmp : t -> t -> int
+ val eq : t -> t -> bool
+ val ne : t -> t -> bool
+ val lt : t -> t -> bool
+ val gt : t -> t -> bool
+ val le : t -> t -> bool
+ val ge : t -> t -> bool
+end;;
+
+module M_int : T with type t := int = M;;
+module M_float : T with type t := float = M;;
+module M_string : T with type t := string = M;;
+module M_int32 : T with type t := int32 = M;;
+module M_int64 : T with type t := int64 = M;;
+module M_nativeint : T with type t := nativeint = M;;
diff --git a/testsuite/tests/translprim/module_coercion.ml.reference b/testsuite/tests/translprim/module_coercion.ml.reference
new file mode 100644
index 0000000000..b84637f440
--- /dev/null
+++ b/testsuite/tests/translprim/module_coercion.ml.reference
@@ -0,0 +1,104 @@
+(setglobal Module_coercion!
+ (let (M = (makeblock 0))
+ (makeblock 0 M
+ (makeblock 0 (function prim (array.length[int] prim))
+ (function prim prim (array.get[int] prim prim))
+ (function prim prim
+ (array.unsafe_get[int] prim prim))
+ (function prim prim prim
+ (array.set[int] prim prim prim))
+ (function prim prim prim
+ (array.unsafe_set[int] prim prim prim))
+ (function prim prim (caml_int_compare prim prim))
+ (function prim prim (== prim prim))
+ (function prim prim (!= prim prim))
+ (function prim prim (< prim prim))
+ (function prim prim (> prim prim))
+ (function prim prim (<= prim prim))
+ (function prim prim (>= prim prim)))
+ (makeblock 0 (function prim (array.length[float] prim))
+ (function prim prim (array.get[float] prim prim))
+ (function prim prim
+ (array.unsafe_get[float] prim prim))
+ (function prim prim prim
+ (array.set[float] prim prim prim))
+ (function prim prim prim
+ (array.unsafe_set[float] prim prim prim))
+ (function prim prim
+ (caml_float_compare prim prim))
+ (function prim prim (==. prim prim))
+ (function prim prim (!=. prim prim))
+ (function prim prim (<. prim prim))
+ (function prim prim (>. prim prim))
+ (function prim prim (<=. prim prim))
+ (function prim prim (>=. prim prim)))
+ (makeblock 0 (function prim (array.length[addr] prim))
+ (function prim prim (array.get[addr] prim prim))
+ (function prim prim
+ (array.unsafe_get[addr] prim prim))
+ (function prim prim prim
+ (array.set[addr] prim prim prim))
+ (function prim prim prim
+ (array.unsafe_set[addr] prim prim prim))
+ (function prim prim
+ (caml_string_compare prim prim))
+ (function prim prim
+ (caml_string_equal prim prim))
+ (function prim prim
+ (caml_string_notequal prim prim))
+ (function prim prim
+ (caml_string_lessthan prim prim))
+ (function prim prim
+ (caml_string_greaterthan prim prim))
+ (function prim prim
+ (caml_string_lessequal prim prim))
+ (function prim prim
+ (caml_string_greaterequal prim prim)))
+ (makeblock 0 (function prim (array.length[addr] prim))
+ (function prim prim (array.get[addr] prim prim))
+ (function prim prim
+ (array.unsafe_get[addr] prim prim))
+ (function prim prim prim
+ (array.set[addr] prim prim prim))
+ (function prim prim prim
+ (array.unsafe_set[addr] prim prim prim))
+ (function prim prim
+ (caml_int32_compare prim prim))
+ (function prim prim (Int32.== prim prim))
+ (function prim prim (Int32.!= prim prim))
+ (function prim prim (Int32.< prim prim))
+ (function prim prim (Int32.> prim prim))
+ (function prim prim (Int32.<= prim prim))
+ (function prim prim (Int32.>= prim prim)))
+ (makeblock 0 (function prim (array.length[addr] prim))
+ (function prim prim (array.get[addr] prim prim))
+ (function prim prim
+ (array.unsafe_get[addr] prim prim))
+ (function prim prim prim
+ (array.set[addr] prim prim prim))
+ (function prim prim prim
+ (array.unsafe_set[addr] prim prim prim))
+ (function prim prim
+ (caml_int64_compare prim prim))
+ (function prim prim (Int64.== prim prim))
+ (function prim prim (Int64.!= prim prim))
+ (function prim prim (Int64.< prim prim))
+ (function prim prim (Int64.> prim prim))
+ (function prim prim (Int64.<= prim prim))
+ (function prim prim (Int64.>= prim prim)))
+ (makeblock 0 (function prim (array.length[addr] prim))
+ (function prim prim (array.get[addr] prim prim))
+ (function prim prim
+ (array.unsafe_get[addr] prim prim))
+ (function prim prim prim
+ (array.set[addr] prim prim prim))
+ (function prim prim prim
+ (array.unsafe_set[addr] prim prim prim))
+ (function prim prim
+ (caml_nativeint_compare prim prim))
+ (function prim prim (Nativeint.== prim prim))
+ (function prim prim (Nativeint.!= prim prim))
+ (function prim prim (Nativeint.< prim prim))
+ (function prim prim (Nativeint.> prim prim))
+ (function prim prim (Nativeint.<= prim prim))
+ (function prim prim (Nativeint.>= prim prim))))))
diff --git a/testsuite/tests/translprim/ref_spec.ml b/testsuite/tests/translprim/ref_spec.ml
new file mode 100644
index 0000000000..37553ef914
--- /dev/null
+++ b/testsuite/tests/translprim/ref_spec.ml
@@ -0,0 +1,42 @@
+type 'a custom_rec = { x : unit; mutable y : 'a }
+type float_rec = { w : float; mutable z : float }
+
+type cst = A | B
+type gen = C | D of string
+
+type var = [ `A | `B ]
+type vargen = [ `A | `B of int | `C ]
+
+let int_ref = ref 1;;
+let var_ref : var ref = ref `A;;
+let vargen_ref : vargen ref = ref `A;;
+let cst_ref = ref A;;
+let gen_ref = ref C;;
+let flt_ref = ref 0.;;
+
+int_ref := 2;;
+var_ref := `B;;
+vargen_ref := `B 0;;
+vargen_ref := `C;;
+cst_ref := B;;
+gen_ref := D "foo";;
+gen_ref := C;;
+flt_ref := 1.;;
+
+let int_rec = { x = (); y = 1 };;
+let var_rec : var custom_rec = { x = (); y = `A };;
+let vargen_rec : vargen custom_rec = { x = (); y = `A };;
+let cst_rec = { x = (); y = A };;
+let gen_rec = { x = (); y = C };;
+let flt_rec = { x = (); y = 0. };;
+let flt_rec' = { w = 0.; z = 0. };;
+
+int_rec.y <- 2;;
+var_rec.y <- `B;;
+vargen_rec.y <- `B 0;;
+vargen_rec.y <- `C;;
+cst_rec.y <- B;;
+gen_rec.y <- D "foo";;
+gen_rec.y <- C;;
+flt_rec.y <- 1.;;
+flt_rec'.z <- 1.;;
diff --git a/testsuite/tests/translprim/ref_spec.ml.reference b/testsuite/tests/translprim/ref_spec.ml.reference
new file mode 100644
index 0000000000..ff0753dc6c
--- /dev/null
+++ b/testsuite/tests/translprim/ref_spec.ml.reference
@@ -0,0 +1,33 @@
+(setglobal Ref_spec!
+ (let
+ (int_ref = (makemutable 0 1)
+ var_ref = (makemutable 0 65a)
+ vargen_ref = (makemutable 0 65a)
+ cst_ref = (makemutable 0 0a)
+ gen_ref = (makemutable 0 0a)
+ flt_ref = (makemutable 0 0.))
+ (seq (setfield_imm 0 int_ref 2) (setfield_ptr 0 var_ref 66a)
+ (setfield_ptr 0 vargen_ref [0: 66 0])
+ (setfield_ptr 0 vargen_ref 67a) (setfield_imm 0 cst_ref 1a)
+ (setfield_ptr 0 gen_ref [0: "foo"])
+ (setfield_ptr 0 gen_ref 0a) (setfield_ptr 0 flt_ref 1.)
+ (let
+ (int_rec = (makemutable 0 0a 1)
+ var_rec = (makemutable 0 0a 65a)
+ vargen_rec = (makemutable 0 0a 65a)
+ cst_rec = (makemutable 0 0a 0a)
+ gen_rec = (makemutable 0 0a 0a)
+ flt_rec = (makemutable 0 0a 0.)
+ flt_rec' = (makearray[float] 0. 0.))
+ (seq (setfield_imm 1 int_rec 2)
+ (setfield_ptr 1 var_rec 66a)
+ (setfield_ptr 1 vargen_rec [0: 66 0])
+ (setfield_ptr 1 vargen_rec 67a)
+ (setfield_imm 1 cst_rec 1a)
+ (setfield_ptr 1 gen_rec [0: "foo"])
+ (setfield_ptr 1 gen_rec 0a) (setfield_ptr 1 flt_rec 1.)
+ (setfloatfield 1 flt_rec' 1.)
+ (makeblock 0 int_ref var_ref vargen_ref cst_ref
+ gen_ref flt_ref int_rec var_rec
+ vargen_rec cst_rec gen_rec flt_rec
+ flt_rec'))))))
diff --git a/testsuite/tests/typing-extensions/Makefile b/testsuite/tests/typing-extensions/Makefile
new file mode 100644
index 0000000000..9625a3fbc3
--- /dev/null
+++ b/testsuite/tests/typing-extensions/Makefile
@@ -0,0 +1,3 @@
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-extensions/cast.ml b/testsuite/tests/typing-extensions/cast.ml
new file mode 100644
index 0000000000..855f4df76c
--- /dev/null
+++ b/testsuite/tests/typing-extensions/cast.ml
@@ -0,0 +1,97 @@
+
+(* By using two types we can have a recursive constraint *)
+type 'a class_name = .. constraint 'a = < cast: 'a. 'a name -> 'a; ..>
+and 'a name =
+ Class : 'a class_name -> (< cast: 'a. 'a name -> 'a; ..> as 'a) name
+;;
+
+exception Bad_cast
+;;
+
+class type castable =
+object
+ method cast: 'a.'a name -> 'a
+end
+;;
+
+(* Lets create a castable class with a name*)
+
+class type foo_t =
+object
+ inherit castable
+ method foo: string
+end
+;;
+
+type 'a class_name += Foo: foo_t class_name
+;;
+
+class foo: foo_t =
+object(self)
+ method cast: type a. a name -> a =
+ function
+ Class Foo -> (self :> foo_t)
+ | _ -> ((raise Bad_cast) : a)
+ method foo = "foo"
+end
+;;
+
+(* Now we can create a subclass of foo *)
+
+class type bar_t =
+object
+ inherit foo
+ method bar: string
+end
+;;
+
+type 'a class_name += Bar: bar_t class_name
+;;
+
+class bar: bar_t =
+object(self)
+ inherit foo as super
+ method cast: type a. a name -> a =
+ function
+ Class Bar -> (self :> bar_t)
+ | other -> super#cast other
+ method bar = "bar"
+end
+;;
+
+(* Now lets create a mutable list of castable objects *)
+
+let clist :castable list ref = ref []
+;;
+
+let push_castable (c: #castable) =
+ clist := (c :> castable) :: !clist
+;;
+
+let pop_castable () =
+ match !clist with
+ c :: rest ->
+ clist := rest;
+ c
+ | [] -> raise Not_found
+;;
+
+(* We can add foos and bars to this list, and retrive them *)
+
+push_castable (new foo);;
+push_castable (new bar);;
+push_castable (new foo);;
+
+let c1: castable = pop_castable ();;
+let c2: castable = pop_castable ();;
+let c3: castable = pop_castable ();;
+
+(* We can also downcast these values to foos and bars *)
+
+let f1: foo = c1#cast (Class Foo);; (* Ok *)
+let f2: foo = c2#cast (Class Foo);; (* Ok *)
+let f3: foo = c3#cast (Class Foo);; (* Ok *)
+
+let b1: bar = c1#cast (Class Bar);; (* Exception Bad_cast *)
+let b2: bar = c2#cast (Class Bar);; (* Ok *)
+let b3: bar = c3#cast (Class Bar);; (* Exception Bad_cast *)
diff --git a/testsuite/tests/typing-extensions/cast.ml.reference b/testsuite/tests/typing-extensions/cast.ml.reference
new file mode 100644
index 0000000000..468a7c9454
--- /dev/null
+++ b/testsuite/tests/typing-extensions/cast.ml.reference
@@ -0,0 +1,33 @@
+
+# type 'b class_name = .. constraint 'b = < cast : 'a. 'a name -> 'a; .. >
+and 'a name =
+ Class : 'a class_name -> (< cast : 'a0. 'a0 name -> 'a0; .. > as 'a) name
+# exception Bad_cast
+# class type castable = object method cast : 'a name -> 'a end
+# class type foo_t = object method cast : 'a name -> 'a method foo : string end
+# type 'b class_name += Foo : foo_t class_name
+# class foo : foo_t
+# class type bar_t =
+ object
+ method bar : string
+ method cast : 'a name -> 'a
+ method foo : string
+ end
+# type 'b class_name += Bar : bar_t class_name
+# class bar : bar_t
+# val clist : castable list ref = {contents = []}
+# val push_castable : #castable -> unit = <fun>
+# val pop_castable : unit -> castable = <fun>
+# - : unit = ()
+# - : unit = ()
+# - : unit = ()
+# val c1 : castable = <obj>
+# val c2 : castable = <obj>
+# val c3 : castable = <obj>
+# val f1 : foo = <obj>
+# val f2 : foo = <obj>
+# val f3 : foo = <obj>
+# Exception: Bad_cast.
+# val b2 : bar = <obj>
+# Exception: Bad_cast.
+#
diff --git a/testsuite/tests/typing-extensions/extensions.ml b/testsuite/tests/typing-extensions/extensions.ml
new file mode 100644
index 0000000000..3539be332f
--- /dev/null
+++ b/testsuite/tests/typing-extensions/extensions.ml
@@ -0,0 +1,323 @@
+
+type foo = ..
+;;
+
+type foo +=
+ A
+ | B of int
+;;
+
+let is_a x =
+ match x with
+ A -> true
+ | _ -> false
+;;
+
+(* The type must be open to create extension *)
+
+type foo
+;;
+
+type foo += A of int (* Error type is not open *)
+;;
+
+(* The type parameters must match *)
+
+type 'a foo = ..
+;;
+
+type ('a, 'b) foo += A of int (* Error: type parameter mismatch *)
+;;
+
+(* In a signature the type does not have to be open *)
+
+module type S =
+sig
+ type foo
+ type foo += A of float
+end
+;;
+
+(* But it must still be extensible *)
+
+module type S =
+sig
+ type foo = A of int
+ type foo += B of float (* Error foo does not have an extensible type *)
+end
+;;
+
+(* Signatures can change the grouping of extensions *)
+
+type foo = ..
+;;
+
+module M = struct
+ type foo +=
+ A of int
+ | B of string
+
+ type foo +=
+ C of int
+ | D of float
+end
+;;
+
+module type S = sig
+ type foo +=
+ B of string
+ | C of int
+
+ type foo += D of float
+
+ type foo += A of int
+end
+;;
+
+module M_S = (M : S)
+;;
+
+(* Extensions can be GADTs *)
+
+type 'a foo = ..
+;;
+
+type _ foo +=
+ A : int -> int foo
+ | B : int foo
+;;
+
+let get_num : type a. a foo -> a -> a option = fun f i1 ->
+ match f with
+ A i2 -> Some (i1 + i2)
+ | _ -> None
+;;
+
+(* Extensions must obey constraints *)
+
+type 'a foo = .. constraint 'a = [> `Var ]
+;;
+
+type 'a foo += A of 'a
+;;
+
+let a = A 9 (* ERROR: Constraints not met *)
+;;
+
+type 'a foo += B : int foo (* ERROR: Constraints not met *)
+;;
+
+(* Signatures can make an extension private *)
+
+type foo = ..
+;;
+
+module M = struct type foo += A of int end
+;;
+
+let a1 = M.A 10
+;;
+
+module type S = sig type foo += private A of int end
+;;
+
+module M_S = (M : S)
+;;
+
+let is_s x =
+ match x with
+ M_S.A _ -> true
+ | _ -> false
+;;
+
+let a2 = M_S.A 20 (* ERROR: Cannot create a value using a private constructor *)
+;;
+
+(* Extensions can be rebound *)
+
+type foo = ..
+;;
+
+module M = struct type foo += A1 of int end
+;;
+
+type foo += A2 = M.A1
+;;
+
+type bar = ..
+;;
+
+type bar += A3 = M.A1 (* Error: rebind wrong type *)
+;;
+
+module M = struct type foo += private B1 of int end
+;;
+
+type foo += private B2 = M.B1
+;;
+
+type foo += B3 = M.B1 (* Error: rebind private extension *)
+;;
+
+type foo += C = Unknown (* Error: unbound extension *)
+;;
+
+(* Extensions can be rebound even if type is closed *)
+
+module M : sig type foo type foo += A1 of int end
+ = struct type foo = .. type foo += A1 of int end
+
+type M.foo += A2 = M.A1
+
+(* Rebinding handles abbreviations *)
+
+type 'a foo = ..
+;;
+
+type 'a foo1 = 'a foo = ..
+;;
+
+type 'a foo2 = 'a foo = ..
+;;
+
+type 'a foo1 +=
+ A of int
+ | B of 'a
+ | C : int foo1
+;;
+
+type 'a foo2 +=
+ D = A
+ | E = B
+ | F = C
+;;
+
+(* Extensions must obey variances *)
+
+type +'a foo = ..
+;;
+
+type 'a foo += A of (int -> 'a)
+;;
+
+type 'a foo += B of ('a -> int)
+ (* ERROR: Parameter variances are not satisfied *)
+;;
+
+type _ foo += C : ('a -> int) -> 'a foo
+ (* ERROR: Parameter variances are not satisfied *)
+;;
+
+type 'a bar = ..
+;;
+
+type +'a bar += D of (int -> 'a) (* ERROR: type variances do not match *)
+;;
+
+(* Exceptions are compatible with extensions *)
+
+module M : sig
+ type exn +=
+ Foo of int * float
+ | Bar : 'a list -> exn
+end = struct
+ exception Bar : 'a list -> exn
+ exception Foo of int * float
+end
+;;
+
+module M : sig
+ exception Bar : 'a list -> exn
+ exception Foo of int * float
+end = struct
+ type exn +=
+ Foo of int * float
+ | Bar : 'a list -> exn
+end
+;;
+
+exception Foo of int * float
+;;
+
+exception Bar : 'a list -> exn
+;;
+
+module M : sig
+ type exn +=
+ Foo of int * float
+ | Bar : 'a list -> exn
+end = struct
+ exception Bar = Bar
+ exception Foo = Foo
+end
+;;
+
+(* Test toplevel printing *)
+
+type foo = ..
+;;
+
+type foo +=
+ Foo of int * int option
+ | Bar of int option
+;;
+
+let x = Foo(3, Some 4), Bar(Some 5) (* Prints Foo and Bar successfully *)
+;;
+
+type foo += Foo of string
+;;
+
+let y = x (* Prints Bar but not Foo (which has been shadowed) *)
+;;
+
+exception Foo of int * int option
+;;
+
+exception Bar of int option
+;;
+
+let x = Foo(3, Some 4), Bar(Some 5) (* Prints Foo and Bar successfully *)
+;;
+
+type foo += Foo of string
+;;
+
+let y = x (* Prints Bar and part of Foo (which has been shadowed) *)
+;;
+
+(* Test Obj functions *)
+
+type foo = ..
+;;
+
+type foo +=
+ Foo
+ | Bar of int
+;;
+
+let n1 = Obj.extension_name Foo
+;;
+
+let n2 = Obj.extension_name (Bar 1)
+;;
+
+let t = (Obj.extension_id (Bar 2)) = (Obj.extension_id (Bar 3)) (* true *)
+;;
+
+let f = (Obj.extension_id (Bar 2)) = (Obj.extension_id Foo) (* false *)
+;;
+
+let is_foo x = (Obj.extension_id Foo) = (Obj.extension_id x)
+
+type foo += Foo
+;;
+
+let f = is_foo Foo
+;;
+
+let _ = Obj.extension_name 7 (* Invald_arg *)
+;;
+
+let _ = Obj.extension_id (object method m = 3 end) (* Invald_arg *)
+;;
diff --git a/testsuite/tests/typing-extensions/extensions.ml.reference b/testsuite/tests/typing-extensions/extensions.ml.reference
new file mode 100644
index 0000000000..2f827076ec
--- /dev/null
+++ b/testsuite/tests/typing-extensions/extensions.ml.reference
@@ -0,0 +1,131 @@
+
+# type foo = ..
+# type foo += A | B of int
+# val is_a : foo -> bool = <fun>
+# type foo
+# Characters 13-21:
+ type foo += A of int (* Error type is not open *)
+ ^^^^^^^^
+Error: Cannot extend type definition foo
+# type 'a foo = ..
+# Characters 1-30:
+ type ('a, 'b) foo += A of int (* Error: type parameter mismatch *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This extension does not match the definition of type foo
+ They have different arities.
+# module type S = sig type foo type foo += A of float end
+# Characters 84-106:
+ type foo += B of float (* Error foo does not have an extensible type *)
+ ^^^^^^^^^^^^^^^^^^^^^^
+Error: Type foo is not extensible
+# type foo = ..
+# module M :
+ sig
+ type foo += A of int | B of string
+ type foo += C of int | D of float
+
+ end
+# module type S =
+ sig
+ type foo += B of string | C of int
+ type foo += D of float
+ type foo += A of int
+ end
+# module M_S : S
+# type 'a foo = ..
+# type _ foo += A : int -> int foo | B : int foo
+# val get_num : 'a foo -> 'a -> 'a option = <fun>
+# type 'a foo = .. constraint 'a = [> `Var ]
+# type 'a foo += A of 'a
+# Characters 11-12:
+ let a = A 9 (* ERROR: Constraints not met *)
+ ^
+Error: This expression has type int but an expression was expected of type
+ [> `Var ]
+# Characters 20-23:
+ type 'a foo += B : int foo (* ERROR: Constraints not met *)
+ ^^^
+Error: This type int should be an instance of type [> `Var ]
+# type foo = ..
+# module M : sig type foo += A of int end
+# val a1 : foo = M.A 10
+# module type S = sig type foo += private A of int end
+# module M_S : S
+# val is_s : foo -> bool = <fun>
+# Characters 10-18:
+ let a2 = M_S.A 20 (* ERROR: Cannot create a value using a private constructor *)
+ ^^^^^^^^
+Error: Cannot create values of the private type foo
+# type foo = ..
+# module M : sig type foo += A1 of int end
+# type foo += A2 of int
+# type bar = ..
+# Characters 18-22:
+ type bar += A3 = M.A1 (* Error: rebind wrong type *)
+ ^^^^
+Error: The constructor M.A1 has type foo but was expected to be of type bar
+# module M : sig type foo += private B1 of int end
+# type foo += private B2 of int
+# Characters 18-22:
+ type foo += B3 = M.B1 (* Error: rebind private extension *)
+ ^^^^
+Error: The constructor M.B1 is private
+# Characters 13-24:
+ type foo += C = Unknown (* Error: unbound extension *)
+ ^^^^^^^^^^^
+Error: Unbound constructor Unknown
+# module M : sig type foo type foo += A1 of int end
+type M.foo += A2 of int
+type 'a foo = ..
+# type 'a foo1 = 'a foo = ..
+# type 'a foo2 = 'a foo = ..
+# type 'a foo1 += A of int | B of 'a | C : int foo1
+# type 'a foo2 += D of int | E of 'a | F : int foo2
+# type +'a foo = ..
+# type 'a foo += A of (int -> 'a)
+# Characters 1-32:
+ type 'a foo += B of ('a -> int)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, expected parameter variances are not satisfied.
+ The 1st type parameter was expected to be covariant,
+ but it is injective contravariant.
+# Characters 1-40:
+ type _ foo += C : ('a -> int) -> 'a foo
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, expected parameter variances are not satisfied.
+ The 1st type parameter was expected to be covariant,
+ but it is injective contravariant.
+# type 'a bar = ..
+# Characters 1-33:
+ type +'a bar += D of (int -> 'a) (* ERROR: type variances do not match *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This extension does not match the definition of type bar
+ Their variances do not agree.
+# module M : sig type exn += Foo of int * float | Bar : 'a list -> exn end
+# module M :
+ sig exception Bar : 'a list -> exn exception Foo of int * float end
+# exception Foo of int * float
+# exception Bar : 'a list -> exn
+# module M : sig type exn += Foo of int * float | Bar : 'a list -> exn end
+# type foo = ..
+# type foo += Foo of int * int option | Bar of int option
+# val x : foo * foo = (Foo (3, Some 4), Bar (Some 5))
+# type foo += Foo of string
+# val y : foo * foo = (<extension>, Bar (Some 5))
+# exception Foo of int * int option
+# exception Bar of int option
+# val x : exn * exn = (Foo (3, Some 4), Bar (Some 5))
+# type foo += Foo of string
+# val y : exn * exn = (Foo (3, _), Bar (Some 5))
+# type foo = ..
+# type foo += Foo | Bar of int
+# val n1 : string = "Foo"
+# val n2 : string = "Bar"
+# val t : bool = true
+# val f : bool = false
+# val is_foo : 'a -> bool = <fun>
+type foo += Foo
+# val f : bool = false
+# Exception: Invalid_argument "Obj.extension_name".
+# Exception: Invalid_argument "Obj.extension_id".
+#
diff --git a/testsuite/tests/typing-extensions/msg.ml b/testsuite/tests/typing-extensions/msg.ml
new file mode 100644
index 0000000000..ef1c12fb4c
--- /dev/null
+++ b/testsuite/tests/typing-extensions/msg.ml
@@ -0,0 +1,131 @@
+(* Typed names *)
+
+module Msg : sig
+
+ type 'a tag
+
+ type result = Result : 'a tag * 'a -> result
+
+ val write : 'a tag -> 'a -> unit
+
+ val read : unit -> result
+
+ type 'a tag += Int : int tag
+
+ module type Desc = sig
+ type t
+ val label : string
+ val write : t -> string
+ val read : string -> t
+ end
+
+ module Define (D : Desc) : sig
+ type 'a tag += C : D.t tag
+ end
+
+end = struct
+
+ type 'a tag = ..
+
+ type ktag = T : 'a tag -> ktag
+
+ type 'a kind =
+ { tag : 'a tag;
+ label : string;
+ write : 'a -> string;
+ read : string -> 'a; }
+
+ type rkind = K : 'a kind -> rkind
+
+ type wkind = { f : 'a . 'a tag -> 'a kind }
+
+ let readTbl : (string, rkind) Hashtbl.t = Hashtbl.create 13
+
+ let writeTbl : (ktag, wkind) Hashtbl.t = Hashtbl.create 13
+
+ let read_raw () : string * string = raise (Failure "Not implemented")
+
+ type result = Result : 'a tag * 'a -> result
+
+ let read () =
+ let label, content = read_raw () in
+ let K k = Hashtbl.find readTbl label in
+ let body = k.read content in
+ Result(k.tag, body)
+
+ let write_raw (label : string) (content : string) =
+ raise (Failure "Not implemented")
+
+ let write (tag : 'a tag) (body : 'a) =
+ let {f} = Hashtbl.find writeTbl (T tag) in
+ let k = f tag in
+ let content = k.write body in
+ write_raw k.label content
+
+ (* Add int kind *)
+
+ type 'a tag += Int : int tag
+
+ let ik =
+ { tag = Int;
+ label = "int";
+ write = string_of_int;
+ read = int_of_string }
+
+ let () = Hashtbl.add readTbl "int" (K ik)
+
+ let () =
+ let f (type t) (i : t tag) : t kind =
+ match i with
+ Int -> ik
+ | _ -> assert false
+ in
+ Hashtbl.add writeTbl (T Int) {f}
+
+ (* Support user defined kinds *)
+
+ module type Desc = sig
+ type t
+ val label : string
+ val write : t -> string
+ val read : string -> t
+ end
+
+ module Define (D : Desc) = struct
+ type 'a tag += C : D.t tag
+ let k =
+ { tag = C;
+ label = D.label;
+ write = D.write;
+ read = D.read }
+ let () = Hashtbl.add readTbl D.label (K k)
+ let () =
+ let f (type t) (c : t tag) : t kind =
+ match c with
+ C -> k
+ | _ -> assert false
+ in
+ Hashtbl.add writeTbl (T C) {f}
+ end
+
+end;;
+
+let write_int i = Msg.write Msg.Int i;;
+
+module StrM = Msg.Define(struct
+ type t = string
+ let label = "string"
+ let read s = s
+ let write s = s
+end);;
+
+type 'a Msg.tag += String = StrM.C;;
+
+let write_string s = Msg.write String s;;
+
+let read_one () =
+ let Msg.Result(tag, body) = Msg.read () in
+ match tag with
+ Msg.Int -> print_int body
+ | String -> print_string body
+ | _ -> print_string "Unknown";;
diff --git a/testsuite/tests/typing-extensions/msg.ml.reference b/testsuite/tests/typing-extensions/msg.ml.reference
new file mode 100644
index 0000000000..e7f1a8f248
--- /dev/null
+++ b/testsuite/tests/typing-extensions/msg.ml.reference
@@ -0,0 +1,23 @@
+
+# module Msg :
+ sig
+ type 'a tag
+ type result = Result : 'a tag * 'a -> result
+ val write : 'a tag -> 'a -> unit
+ val read : unit -> result
+ type 'a tag += Int : int tag
+ module type Desc =
+ sig
+ type t
+ val label : string
+ val write : t -> string
+ val read : string -> t
+ end
+ module Define : functor (D : Desc) -> sig type 'a tag += C : D.t tag end
+ end
+# val write_int : int -> unit = <fun>
+# module StrM : sig type 'a Msg.tag += C : string Msg.tag end
+# type 'a Msg.tag += String : string Msg.tag
+# val write_string : string -> unit = <fun>
+# val read_one : unit -> unit = <fun>
+#
diff --git a/testsuite/tests/typing-extensions/open_types.ml b/testsuite/tests/typing-extensions/open_types.ml
new file mode 100644
index 0000000000..766bee0434
--- /dev/null
+++ b/testsuite/tests/typing-extensions/open_types.ml
@@ -0,0 +1,117 @@
+type foo = ..
+;;
+
+(* Check that abbreviations work *)
+
+type bar = foo = ..
+;;
+
+type baz = foo = ..
+;;
+
+type bar += Bar1 of int
+;;
+
+type baz += Bar2 of int
+;;
+
+module M = struct type bar += Foo of float end
+;;
+
+module type S = sig type baz += Foo of float end
+;;
+
+module M_S = (M : S)
+;;
+
+(* Abbreviations need to be made open *)
+
+type foo = ..
+;;
+
+type bar = foo
+;;
+
+type bar += Bar of int (* Error: type is not open *)
+;;
+
+type baz = bar = .. (* Error: type kinds don't match *)
+;;
+
+(* Abbreviations need to match parameters *)
+
+type 'a foo = ..
+;;
+
+type ('a, 'b) bar = 'a foo = .. (* Error: arrities do not match *)
+;;
+
+type ('a, 'b) foo = ..
+;;
+
+type ('a, 'b) bar = ('a, 'a) foo = .. (* Error: constraints do not match *)
+;;
+
+(* Private abstract types cannot be open *)
+
+type foo = ..
+;;
+
+type bar = private foo = .. (* ERROR: Private abstract types cannot be open *)
+;;
+
+(* Check that signatures can hide open-ness *)
+
+module M = struct type foo = .. end
+;;
+
+module type S = sig type foo end
+;;
+
+module M_S = (M : S)
+;;
+
+type M_S.foo += Foo (* ERROR: Cannot extend a type that isn't "open" *)
+;;
+
+(* Check that signatures cannot add open-ness *)
+
+module M = struct type foo end
+;;
+
+module type S = sig type foo = .. end
+;;
+
+module M_S = (M : S) (* ERROR: Signatures are not compatible *)
+;;
+
+(* Check that signatures maintain variances *)
+
+module M = struct type +'a foo = .. type 'a bar = 'a foo = .. end
+;;
+
+module type S = sig type 'a foo = .. type 'a bar = 'a foo = .. end
+;;
+
+module M_S = (M : S) (* ERROR: Signatures are not compatible *)
+;;
+
+(* Exn is an open type *)
+
+type exn2 = exn = ..
+;;
+
+(* Exhaustiveness *)
+
+type foo = ..
+type foo += Foo
+let f = function Foo -> ()
+;; (* warn *)
+
+(* More complex exhaustiveness *)
+
+let f = function
+ | [Foo] -> 1
+ | _::_::_ -> 3
+ | [] -> 2
+;; (* warn *)
diff --git a/testsuite/tests/typing-extensions/open_types.ml.reference b/testsuite/tests/typing-extensions/open_types.ml.reference
new file mode 100644
index 0000000000..8e86ec0937
--- /dev/null
+++ b/testsuite/tests/typing-extensions/open_types.ml.reference
@@ -0,0 +1,96 @@
+
+# type foo = ..
+# type bar = foo = ..
+# type baz = foo = ..
+# type bar += Bar1 of int
+# type baz += Bar2 of int
+# module M : sig type bar += Foo of float end
+# module type S = sig type baz += Foo of float end
+# module M_S : S
+# type foo = ..
+# type bar = foo
+# Characters 13-23:
+ type bar += Bar of int (* Error: type is not open *)
+ ^^^^^^^^^^
+Error: Cannot extend type definition bar
+# Characters 1-20:
+ type baz = bar = .. (* Error: type kinds don't match *)
+ ^^^^^^^^^^^^^^^^^^^
+Error: This variant or record definition does not match that of type bar
+ Their kinds differ.
+# type 'a foo = ..
+# Characters 1-32:
+ type ('a, 'b) bar = 'a foo = .. (* Error: arrities do not match *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This variant or record definition does not match that of type 'a foo
+ They have different arities.
+# type ('a, 'b) foo = ..
+# Characters 1-38:
+ type ('a, 'b) bar = ('a, 'a) foo = .. (* Error: constraints do not match *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This variant or record definition does not match that of type
+ ('a, 'a) foo
+ Their constraints differ.
+# type foo = ..
+# Characters 24-25:
+ type bar = private foo = .. (* ERROR: Private abstract types cannot be open *)
+ ^
+Error: Syntax error
+# module M : sig type foo = .. end
+# module type S = sig type foo end
+# module M_S : S
+# Characters 17-20:
+ type M_S.foo += Foo (* ERROR: Cannot extend a type that isn't "open" *)
+ ^^^
+Error: Cannot extend type definition M_S.foo
+# module M : sig type foo end
+# module type S = sig type foo = .. end
+# Characters 15-16:
+ module M_S = (M : S) (* ERROR: Signatures are not compatible *)
+ ^
+Error: Signature mismatch:
+ Modules do not match: sig type foo = M.foo end is not included in S
+ Type declarations do not match:
+ type foo = M.foo
+ is not included in
+ type foo = ..
+ Their kinds differ.
+# module M : sig type +'a foo = .. type 'a bar = 'a foo = .. end
+# module type S = sig type 'a foo = .. type 'a bar = 'a foo = .. end
+# Characters 15-16:
+ module M_S = (M : S) (* ERROR: Signatures are not compatible *)
+ ^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type 'a foo = 'a M.foo = .. type 'a bar = 'a foo = .. end
+ is not included in
+ S
+ Type declarations do not match:
+ type 'a foo = 'a M.foo = ..
+ is not included in
+ type 'a foo = ..
+ Their variances do not agree.
+# type exn2 = exn = ..
+# Characters 61-79:
+ let f = function Foo -> ()
+ ^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+*extension*
+Matching over values of extensible variant types (the *extension* above)
+must include a wild card pattern in order to be exhaustive.
+type foo = ..
+type foo += Foo
+val f : foo -> unit = <fun>
+# Characters 44-96:
+ ........function
+ | [Foo] -> 1
+ | _::_::_ -> 3
+ | [] -> 2
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+*extension*::[]
+Matching over values of extensible variant types (the *extension* above)
+must include a wild card pattern in order to be exhaustive.
+val f : foo list -> int = <fun>
+#
diff --git a/testsuite/tests/typing-fstclassmod/Makefile b/testsuite/tests/typing-fstclassmod/Makefile
new file mode 100644
index 0000000000..e779183677
--- /dev/null
+++ b/testsuite/tests/typing-fstclassmod/Makefile
@@ -0,0 +1,19 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+#MODULES=
+MAIN_MODULE=fstclassmod
+ADD_COMPFLAGS=-w A -warn-error A
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-fstclassmod/fstclassmod.ml b/testsuite/tests/typing-fstclassmod/fstclassmod.ml
new file mode 100644
index 0000000000..a291a4c7a8
--- /dev/null
+++ b/testsuite/tests/typing-fstclassmod/fstclassmod.ml
@@ -0,0 +1,167 @@
+(* Example of algorithm parametrized with modules *)
+
+let sort (type s) set l =
+ let module Set = (val set : Set.S with type elt = s) in
+ Set.elements (List.fold_right Set.add l Set.empty)
+
+let make_set (type s) cmp =
+ let module S = Set.Make(struct
+ type t = s
+ let compare = cmp
+ end) in
+ (module S : Set.S with type elt = s)
+
+let both l =
+ List.map
+ (fun set -> sort set l)
+ [ make_set compare; make_set (fun x y -> compare y x) ]
+
+let () =
+ print_endline (String.concat " " (List.map (String.concat "/")
+ (both ["abc";"xyz";"def"])))
+
+
+(* Hiding the internal representation *)
+
+module type S = sig
+ type t
+ val to_string: t -> string
+ val apply: t -> t
+ val x: t
+end
+
+let create (type s) to_string apply x =
+ let module M = struct
+ type t = s
+ let to_string = to_string
+ let apply = apply
+ let x = x
+ end in
+ (module M : S with type t = s)
+
+let forget (type s) x =
+ let module M = (val x : S with type t = s) in
+ (module M : S)
+
+let print x =
+ let module M = (val x : S) in
+ print_endline (M.to_string M.x)
+
+let apply x =
+ let module M = (val x : S) in
+ let module N = struct
+ include M
+ let x = apply x
+ end in
+ (module N : S)
+
+let () =
+ let int = forget (create string_of_int succ 0) in
+ let str = forget (create (fun s -> s) (fun s -> s ^ s) "X") in
+ List.iter print (List.map apply [int; apply int; apply (apply str)])
+
+
+(* Existential types + type equality witnesses -> pseudo GADT *)
+
+module TypEq : sig
+ type ('a, 'b) t
+ val apply: ('a, 'b) t -> 'a -> 'b
+ val refl: ('a, 'a) t
+ val sym: ('a, 'b) t -> ('b, 'a) t
+end = struct
+ type ('a, 'b) t = unit
+ let apply _ = Obj.magic
+ let refl = ()
+ let sym () = ()
+end
+
+
+module rec Typ : sig
+ module type PAIR = sig
+ type t
+ type t1
+ type t2
+ val eq: (t, t1 * t2) TypEq.t
+ val t1: t1 Typ.typ
+ val t2: t2 Typ.typ
+ end
+
+ type 'a typ =
+ | Int of ('a, int) TypEq.t
+ | String of ('a, string) TypEq.t
+ | Pair of (module PAIR with type t = 'a)
+end = struct
+ module type PAIR = sig
+ type t
+ type t1
+ type t2
+ val eq: (t, t1 * t2) TypEq.t
+ val t1: t1 Typ.typ
+ val t2: t2 Typ.typ
+ end
+
+ type 'a typ =
+ | Int of ('a, int) TypEq.t
+ | String of ('a, string) TypEq.t
+ | Pair of (module PAIR with type t = 'a)
+end
+
+open Typ
+
+let int = Int TypEq.refl
+
+let str = String TypEq.refl
+
+let pair (type s1) (type s2) t1 t2 =
+ let module P = struct
+ type t = s1 * s2
+ type t1 = s1
+ type t2 = s2
+ let eq = TypEq.refl
+ let t1 = t1
+ let t2 = t2
+ end in
+ let pair = (module P : PAIR with type t = s1 * s2) in
+ Pair pair
+
+module rec Print : sig
+ val to_string: 'a Typ.typ -> 'a -> string
+end = struct
+ let to_string (type s) t x =
+ match t with
+ | Int eq -> string_of_int (TypEq.apply eq x)
+ | String eq -> Printf.sprintf "%S" (TypEq.apply eq x)
+ | Pair p ->
+ let module P = (val p : PAIR with type t = s) in
+ let (x1, x2) = TypEq.apply P.eq x in
+ Printf.sprintf "(%s,%s)" (Print.to_string P.t1 x1)
+ (Print.to_string P.t2 x2)
+end
+
+let () =
+ print_endline (Print.to_string int 10);
+ print_endline (Print.to_string (pair int (pair str int)) (123, ("A", 456)))
+
+
+(* #6262: first-class modules and module type aliases *)
+
+module type S1 = sig end
+module type S2 = S1
+
+let _f (x : (module S1)) : (module S2) = x
+
+module X = struct
+ module type S
+end
+module Y = struct include X end
+
+let _f (x : (module X.S)) : (module Y.S) = x
+
+(* PR#6194, main example *)
+module type S3 = sig val x : bool end;;
+let f = function
+ | Some (module M : S3) when M.x ->1
+ | Some _ -> 2
+ | None -> 3
+;;
+print_endline (string_of_int (f (Some (module struct let x = false end))));;
diff --git a/testsuite/tests/typing-fstclassmod/fstclassmod.reference b/testsuite/tests/typing-fstclassmod/fstclassmod.reference
new file mode 100644
index 0000000000..ec517d7893
--- /dev/null
+++ b/testsuite/tests/typing-fstclassmod/fstclassmod.reference
@@ -0,0 +1,7 @@
+abc/def/xyz xyz/def/abc
+1
+2
+XXXXXXXX
+10
+(123,("A",456))
+2
diff --git a/testsuite/tests/typing-gadts/Makefile b/testsuite/tests/typing-gadts/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-gadts/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-gadts/didier.ml b/testsuite/tests/typing-gadts/didier.ml
new file mode 100644
index 0000000000..f34ecb678d
--- /dev/null
+++ b/testsuite/tests/typing-gadts/didier.ml
@@ -0,0 +1,47 @@
+type 'a ty =
+ | Int : int ty
+ | Bool : bool ty
+
+let fbool (type t) (x : t) (tag : t ty) =
+ match tag with
+ | Bool -> x
+;;
+(* val fbool : 'a -> 'a ty -> 'a = <fun> *)
+(** OK: the return value is x of type t **)
+
+let fint (type t) (x : t) (tag : t ty) =
+ match tag with
+ | Int -> x > 0
+;;
+(* val fint : 'a -> 'a ty -> bool = <fun> *)
+(** OK: the return value is x > 0 of type bool;
+This has used the equation t = bool, not visible in the return type **)
+
+let f (type t) (x : t) (tag : t ty) =
+ match tag with
+ | Int -> x > 0
+ | Bool -> x
+(* val f : 'a -> 'a ty -> bool = <fun> *)
+
+
+let g (type t) (x : t) (tag : t ty) =
+ match tag with
+ | Bool -> x
+ | Int -> x > 0
+(* Error: This expression has type bool but an expression was expected of type
+t = int *)
+
+let id x = x;;
+let idb1 = (fun id -> let _ = id true in id) id;;
+let idb2 : bool -> bool = id;;
+let idb3 ( _ : bool ) = false;;
+
+let g (type t) (x : t) (tag : t ty) =
+ match tag with
+ | Bool -> idb3 x
+ | Int -> x > 0
+
+let g (type t) (x : t) (tag : t ty) =
+ match tag with
+ | Bool -> idb2 x
+ | Int -> x > 0
diff --git a/testsuite/tests/typing-gadts/dynamic_frisch.ml b/testsuite/tests/typing-gadts/dynamic_frisch.ml
new file mode 100644
index 0000000000..2636d5b424
--- /dev/null
+++ b/testsuite/tests/typing-gadts/dynamic_frisch.ml
@@ -0,0 +1,475 @@
+(* Encoding generics using GADTs *)
+(* (c) Alain Frisch / Lexifi *)
+(* cf. http://www.lexifi.com/blog/dynamic-types *)
+
+(* Basic tag *)
+
+type 'a ty =
+ | Int: int ty
+ | String: string ty
+ | List: 'a ty -> 'a list ty
+ | Pair: ('a ty * 'b ty) -> ('a * 'b) ty
+;;
+
+(* Tagging data *)
+
+type variant =
+ | VInt of int
+ | VString of string
+ | VList of variant list
+ | VPair of variant * variant
+
+let rec variantize: type t. t ty -> t -> variant =
+ fun ty x ->
+ (* type t is abstract here *)
+ match ty with
+ | Int -> VInt x (* in this branch: t = int *)
+ | String -> VString x (* t = string *)
+ | List ty1 ->
+ VList (List.map (variantize ty1) x)
+ (* t = 'a list for some 'a *)
+ | Pair (ty1, ty2) ->
+ VPair (variantize ty1 (fst x), variantize ty2 (snd x))
+ (* t = ('a, 'b) for some 'a and 'b *)
+
+exception VariantMismatch
+
+let rec devariantize: type t. t ty -> variant -> t =
+ fun ty v ->
+ match ty, v with
+ | Int, VInt x -> x
+ | String, VString x -> x
+ | List ty1, VList vl ->
+ List.map (devariantize ty1) vl
+ | Pair (ty1, ty2), VPair (x1, x2) ->
+ (devariantize ty1 x1, devariantize ty2 x2)
+ | _ -> raise VariantMismatch
+;;
+
+(* Handling records *)
+
+type 'a ty =
+ | Int: int ty
+ | String: string ty
+ | List: 'a ty -> 'a list ty
+ | Pair: ('a ty * 'b ty) -> ('a * 'b) ty
+ | Record: 'a record -> 'a ty
+
+and 'a record =
+ {
+ path: string;
+ fields: 'a field_ list;
+ }
+
+and 'a field_ =
+ | Field: ('a, 'b) field -> 'a field_
+
+and ('a, 'b) field =
+ {
+ label: string;
+ field_type: 'b ty;
+ get: ('a -> 'b);
+ }
+;;
+
+(* Again *)
+
+type variant =
+ | VInt of int
+ | VString of string
+ | VList of variant list
+ | VPair of variant * variant
+ | VRecord of (string * variant) list
+
+let rec variantize: type t. t ty -> t -> variant =
+ fun ty x ->
+ (* type t is abstract here *)
+ match ty with
+ | Int -> VInt x (* in this branch: t = int *)
+ | String -> VString x (* t = string *)
+ | List ty1 ->
+ VList (List.map (variantize ty1) x)
+ (* t = 'a list for some 'a *)
+ | Pair (ty1, ty2) ->
+ VPair (variantize ty1 (fst x), variantize ty2 (snd x))
+ (* t = ('a, 'b) for some 'a and 'b *)
+ | Record {fields} ->
+ VRecord
+ (List.map (fun (Field{field_type; label; get}) ->
+ (label, variantize field_type (get x))) fields)
+;;
+
+(* Extraction *)
+
+type 'a ty =
+ | Int: int ty
+ | String: string ty
+ | List: 'a ty -> 'a list ty
+ | Pair: ('a ty * 'b ty) -> ('a * 'b) ty
+ | Record: ('a, 'builder) record -> 'a ty
+
+and ('a, 'builder) record =
+ {
+ path: string;
+ fields: ('a, 'builder) field list;
+ create_builder: (unit -> 'builder);
+ of_builder: ('builder -> 'a);
+ }
+
+and ('a, 'builder) field =
+ | Field: ('a, 'builder, 'b) field_ -> ('a, 'builder) field
+
+and ('a, 'builder, 'b) field_ =
+ {
+ label: string;
+ field_type: 'b ty;
+ get: ('a -> 'b);
+ set: ('builder -> 'b -> unit);
+ }
+
+let rec devariantize: type t. t ty -> variant -> t =
+ fun ty v ->
+ match ty, v with
+ | Int, VInt x -> x
+ | String, VString x -> x
+ | List ty1, VList vl ->
+ List.map (devariantize ty1) vl
+ | Pair (ty1, ty2), VPair (x1, x2) ->
+ (devariantize ty1 x1, devariantize ty2 x2)
+ | Record {fields; create_builder; of_builder}, VRecord fl ->
+ if List.length fields <> List.length fl then raise VariantMismatch;
+ let builder = create_builder () in
+ List.iter2
+ (fun (Field {label; field_type; set}) (lab, v) ->
+ if label <> lab then raise VariantMismatch;
+ set builder (devariantize field_type v)
+ )
+ fields fl;
+ of_builder builder
+ | _ -> raise VariantMismatch
+;;
+
+type my_record =
+ {
+ a: int;
+ b: string list;
+ }
+
+let my_record =
+ let fields =
+ [
+ Field {label = "a"; field_type = Int;
+ get = (fun {a} -> a);
+ set = (fun (r, _) x -> r := Some x)};
+ Field {label = "b"; field_type = List String;
+ get = (fun {b} -> b);
+ set = (fun (_, r) x -> r := Some x)};
+ ]
+ in
+ let create_builder () = (ref None, ref None) in
+ let of_builder (a, b) =
+ match !a, !b with
+ | Some a, Some b -> {a; b}
+ | _ -> failwith "Some fields are missing in record of type my_record"
+ in
+ Record {path = "My_module.my_record"; fields; create_builder; of_builder}
+;;
+
+(* Extension to recursive types and polymorphic variants *)
+(* by Jacques Garrigue *)
+
+type noarg = Noarg
+
+type (_,_) ty =
+ | Int: (int,_) ty
+ | String: (string,_) ty
+ | List: ('a,'e) ty -> ('a list, 'e) ty
+ | Option: ('a,'e) ty -> ('a option, 'e) ty
+ | Pair: (('a,'e) ty * ('b,'e) ty) -> ('a * 'b,'e) ty
+ (* Support for type variables and recursive types *)
+ | Var: ('a, 'a -> 'e) ty
+ | Rec: ('a, 'a -> 'e) ty -> ('a,'e) ty
+ | Pop: ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ (* Change the representation of a type *)
+ | Conv: string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ (* Sum types (both normal sums and polymorphic variants) *)
+ | Sum: ('a, 'e, 'b) ty_sum -> ('a, 'e) ty
+
+and ('a, 'e, 'b) ty_sum =
+ { sum_proj: 'a -> string * 'e ty_dyn option;
+ sum_cases: (string * ('e,'b) ty_case) list;
+ sum_inj: 'c. ('b,'c) ty_sel * 'c -> 'a; }
+
+and 'e ty_dyn = (* dynamic type *)
+ | Tdyn : ('a,'e) ty * 'a -> 'e ty_dyn
+
+and (_,_) ty_sel = (* selector from a list of types *)
+ | Thd : ('a -> 'b, 'a) ty_sel
+ | Ttl : ('b -> 'c, 'd) ty_sel -> ('a -> 'b -> 'c, 'd) ty_sel
+
+and (_,_) ty_case = (* type a sum case *)
+ | TCarg : ('b,'a) ty_sel * ('a,'e) ty -> ('e,'b) ty_case
+ | TCnoarg : ('b,noarg) ty_sel -> ('e,'b) ty_case
+;;
+
+type _ ty_env = (* type variable substitution *)
+ | Enil : unit ty_env
+ | Econs : ('a,'e) ty * 'e ty_env -> ('a -> 'e) ty_env
+;;
+
+(* Comparing selectors *)
+type (_,_) eq = Eq: ('a,'a) eq
+
+let rec eq_sel : type a b c. (a,b) ty_sel -> (a,c) ty_sel -> (b,c) eq option =
+ fun s1 s2 ->
+ match s1, s2 with
+ | Thd, Thd -> Some Eq
+ | Ttl s1, Ttl s2 ->
+ (match eq_sel s1 s2 with None -> None | Some Eq -> Some Eq)
+ | _ -> None
+
+(* Auxiliary function to get the type of a case from its selector *)
+let rec get_case : type a b e.
+ (b, a) ty_sel -> (string * (e,b) ty_case) list -> string * (a, e) ty option =
+ fun sel cases ->
+ match cases with
+ | (name, TCnoarg sel') :: rem ->
+ begin match eq_sel sel sel' with
+ | None -> get_case sel rem
+ | Some Eq -> name, None
+ end
+ | (name, TCarg (sel', ty)) :: rem ->
+ begin match eq_sel sel sel' with
+ | None -> get_case sel rem
+ | Some Eq -> name, Some ty
+ end
+ | [] -> raise Not_found
+;;
+
+(* Untyped representation of values *)
+type variant =
+ | VInt of int
+ | VString of string
+ | VList of variant list
+ | VOption of variant option
+ | VPair of variant * variant
+ | VConv of string * variant
+ | VSum of string * variant option
+
+let may_map f = function Some x -> Some (f x) | None -> None
+
+let rec variantize : type a e. e ty_env -> (a,e) ty -> a -> variant =
+ fun e ty v ->
+ match ty with
+ | Int -> VInt v
+ | String -> VString v
+ | List t -> VList (List.map (variantize e t) v)
+ | Option t -> VOption (may_map (variantize e t) v)
+ | Pair (t1, t2) -> VPair (variantize e t1 (fst v), variantize e t2 (snd v))
+ | Rec t -> variantize (Econs (ty, e)) t v
+ | Pop t -> (match e with Econs (_, e') -> variantize e' t v)
+ | Var -> (match e with Econs (t, e') -> variantize e' t v)
+ | Conv (s, proj, inj, t) -> VConv (s, variantize e t (proj v))
+ | Sum ops ->
+ let tag, arg = ops.sum_proj v in
+ VSum (tag, may_map (function Tdyn (ty,arg) -> variantize e ty arg) arg)
+;;
+
+let rec devariantize : type t e. e ty_env -> (t, e) ty -> variant -> t =
+ fun e ty v ->
+ match ty, v with
+ | Int, VInt x -> x
+ | String, VString x -> x
+ | List ty1, VList vl ->
+ List.map (devariantize e ty1) vl
+ | Pair (ty1, ty2), VPair (x1, x2) ->
+ (devariantize e ty1 x1, devariantize e ty2 x2)
+ | Rec t, _ -> devariantize (Econs (ty, e)) t v
+ | Pop t, _ -> (match e with Econs (_, e') -> devariantize e' t v)
+ | Var, _ -> (match e with Econs (t, e') -> devariantize e' t v)
+ | Conv (s, proj, inj, t), VConv (s', v) when s = s' ->
+ inj (devariantize e t v)
+ | Sum ops, VSum (tag, a) ->
+ begin try match List.assoc tag ops.sum_cases, a with
+ | TCarg (sel, t), Some a -> ops.sum_inj (sel, devariantize e t a)
+ | TCnoarg sel, None -> ops.sum_inj (sel, Noarg)
+ | _ -> raise VariantMismatch
+ with Not_found -> raise VariantMismatch
+ end
+ | _ -> raise VariantMismatch
+;;
+
+(* First attempt: represent 1-constructor variants using Conv *)
+let wrap_A t = Conv ("`A", (fun (`A x) -> x), (fun x -> `A x), t);;
+
+let ty a = Rec (wrap_A (Option (Pair (a, Var)))) ;;
+let v = variantize Enil (ty Int);;
+let x = v (`A (Some (1, `A (Some (2, `A None))))) ;;
+
+(* Can also use it to decompose a tuple *)
+
+let triple t1 t2 t3 =
+ Conv ("Triple", (fun (a,b,c) -> (a,(b,c))),
+ (fun (a,(b,c)) -> (a,b,c)), Pair (t1, Pair (t2, t3)))
+
+let v = variantize Enil (triple String Int Int) ("A", 2, 3) ;;
+
+(* Second attempt: introduce a real sum construct *)
+let ty_abc =
+ (* Could also use [get_case] for proj, but direct definition is shorter *)
+ let proj = function
+ `A n -> "A", Some (Tdyn (Int, n))
+ | `B s -> "B", Some (Tdyn (String, s))
+ | `C -> "C", None
+ (* Define inj in advance to be able to write the type annotation easily *)
+ and inj : type c. (int -> string -> noarg -> unit, c) ty_sel * c ->
+ [`A of int | `B of string | `C] = function
+ Thd, v -> `A v
+ | Ttl Thd, v -> `B v
+ | Ttl (Ttl Thd), Noarg -> `C
+ in
+ (* Coherence of sum_inj and sum_cases is checked by the typing *)
+ Sum { sum_proj = proj; sum_inj = inj; sum_cases =
+ [ "A", TCarg (Thd, Int); "B", TCarg (Ttl Thd, String);
+ "C", TCnoarg (Ttl (Ttl Thd)) ] }
+;;
+
+let v = variantize Enil ty_abc (`A 3)
+let a = devariantize Enil ty_abc v
+
+(* And an example with recursion... *)
+type 'a vlist = [`Nil | `Cons of 'a * 'a vlist]
+
+let ty_list : type a e. (a, e) ty -> (a vlist, e) ty = fun t ->
+ let tcons = Pair (Pop t, Var) in
+ Rec (Sum {
+ sum_proj = (function
+ `Nil -> "Nil", None
+ | `Cons p -> "Cons", Some (Tdyn (tcons, p)));
+ sum_cases = ["Nil", TCnoarg Thd; "Cons", TCarg (Ttl Thd, tcons)];
+ sum_inj = fun (type c) ->
+ (function
+ | Thd, Noarg -> `Nil
+ | Ttl Thd, v -> `Cons v
+ : (noarg -> a * a vlist -> unit, c) ty_sel * c -> a vlist)
+ (* One can also write the type annotation directly *)
+ })
+
+let v = variantize Enil (ty_list Int) (`Cons (1, `Cons (2, `Nil))) ;;
+
+
+(* Simpler but weaker approach *)
+
+type (_,_) ty =
+ | Int: (int,_) ty
+ | String: (string,_) ty
+ | List: ('a,'e) ty -> ('a list, 'e) ty
+ | Option: ('a,'e) ty -> ('a option, 'e) ty
+ | Pair: (('a,'e) ty * ('b,'e) ty) -> ('a * 'b,'e) ty
+ | Var: ('a, 'a -> 'e) ty
+ | Rec: ('a, 'a -> 'e) ty -> ('a,'e) ty
+ | Pop: ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ | Conv: string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ | Sum: ('a -> string * 'e ty_dyn option) * (string * 'e ty_dyn option -> 'a)
+ -> ('a, 'e) ty
+and 'e ty_dyn =
+ | Tdyn : ('a,'e) ty * 'a -> 'e ty_dyn
+
+let ty_abc : ([`A of int | `B of string | `C],'e) ty =
+ (* Could also use [get_case] for proj, but direct definition is shorter *)
+ Sum (
+ (function
+ `A n -> "A", Some (Tdyn (Int, n))
+ | `B s -> "B", Some (Tdyn (String, s))
+ | `C -> "C", None),
+ (function
+ "A", Some (Tdyn (Int, n)) -> `A n
+ | "B", Some (Tdyn (String, s)) -> `B s
+ | "C", None -> `C
+ | _ -> invalid_arg "ty_abc"))
+;;
+
+(* Breaks: no way to pattern-match on a full recursive type *)
+let ty_list : type a e. (a,e) ty -> (a vlist,e) ty = fun t ->
+ let targ = Pair (Pop t, Var) in
+ Rec (Sum (
+ (function `Nil -> "Nil", None
+ | `Cons p -> "Cons", Some (Tdyn (targ, p))),
+ (function "Nil", None -> `Nil
+ | "Cons", Some (Tdyn (Pair (_, Var), (p : a * a vlist))) -> `Cons p)))
+;;
+
+(* Define Sum using object instead of record for first-class polymorphism *)
+
+type (_,_) ty =
+ | Int: (int,_) ty
+ | String: (string,_) ty
+ | List: ('a,'e) ty -> ('a list, 'e) ty
+ | Option: ('a,'e) ty -> ('a option, 'e) ty
+ | Pair: (('a,'e) ty * ('b,'e) ty) -> ('a * 'b,'e) ty
+ | Var: ('a, 'a -> 'e) ty
+ | Rec: ('a, 'a -> 'e) ty -> ('a,'e) ty
+ | Pop: ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ | Conv: string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ | Sum: < proj: 'a -> string * 'e ty_dyn option;
+ cases: (string * ('e,'b) ty_case) list;
+ inj: 'c. ('b,'c) ty_sel * 'c -> 'a >
+ -> ('a, 'e) ty
+
+and 'e ty_dyn =
+ | Tdyn : ('a,'e) ty * 'a -> 'e ty_dyn
+
+and (_,_) ty_sel =
+ | Thd : ('a -> 'b, 'a) ty_sel
+ | Ttl : ('b -> 'c, 'd) ty_sel -> ('a -> 'b -> 'c, 'd) ty_sel
+
+and (_,_) ty_case =
+ | TCarg : ('b,'a) ty_sel * ('a,'e) ty -> ('e,'b) ty_case
+ | TCnoarg : ('b,noarg) ty_sel -> ('e,'b) ty_case
+;;
+
+let ty_abc : ([`A of int | `B of string | `C] as 'a, 'e) ty =
+ Sum (object
+ method proj = function
+ `A n -> "A", Some (Tdyn (Int, n))
+ | `B s -> "B", Some (Tdyn (String, s))
+ | `C -> "C", None
+ method cases =
+ [ "A", TCarg (Thd, Int); "B", TCarg (Ttl Thd, String);
+ "C", TCnoarg (Ttl (Ttl Thd)) ];
+ method inj : type c.
+ (int -> string -> noarg -> unit, c) ty_sel * c ->
+ [`A of int | `B of string | `C] =
+ function
+ Thd, v -> `A v
+ | Ttl Thd, v -> `B v
+ | Ttl (Ttl Thd), Noarg -> `C
+ | _ -> assert false
+ end)
+
+type 'a vlist = [`Nil | `Cons of 'a * 'a vlist]
+
+let ty_list : type a e. (a, e) ty -> (a vlist, e) ty = fun t ->
+ let tcons = Pair (Pop t, Var) in
+ Rec (Sum (object
+ method proj = function
+ `Nil -> "Nil", None
+ | `Cons p -> "Cons", Some (Tdyn (tcons, p))
+ method cases = ["Nil", TCnoarg Thd; "Cons", TCarg (Ttl Thd, tcons)]
+ method inj : type c.(noarg -> a * a vlist -> unit, c) ty_sel * c -> a vlist
+ = function
+ | Thd, Noarg -> `Nil
+ | Ttl Thd, v -> `Cons v
+ end))
+;;
+
+(*
+type (_,_) ty_assoc =
+ | Anil : (unit,'e) ty_assoc
+ | Acons : string * ('a,'e) ty * ('b,'e) ty_assoc -> ('a -> 'b, 'e) ty_assoc
+
+and (_,_) ty_pvar =
+ | Pnil : ('a,'e) ty_pvar
+ | Pconst : 't * ('b,'e) ty_pvar -> ('t -> 'b, 'e) ty_pvar
+ | Parg : 't * ('a,'e) ty * ('b,'e) ty_pvar -> ('t * 'a -> 'b, 'e) ty_pvar
+*)
diff --git a/testsuite/tests/typing-gadts/dynamic_frisch.ml.principal.reference b/testsuite/tests/typing-gadts/dynamic_frisch.ml.principal.reference
new file mode 100644
index 0000000000..7372c163bd
--- /dev/null
+++ b/testsuite/tests/typing-gadts/dynamic_frisch.ml.principal.reference
@@ -0,0 +1,177 @@
+
+# type 'a ty =
+ Int : int ty
+ | String : string ty
+ | List : 'a ty -> 'a list ty
+ | Pair : ('a ty * 'b ty) -> ('a * 'b) ty
+# type variant =
+ VInt of int
+ | VString of string
+ | VList of variant list
+ | VPair of variant * variant
+val variantize : 't ty -> 't -> variant = <fun>
+exception VariantMismatch
+val devariantize : 't ty -> variant -> 't = <fun>
+# type 'a ty =
+ Int : int ty
+ | String : string ty
+ | List : 'a ty -> 'a list ty
+ | Pair : ('a ty * 'b ty) -> ('a * 'b) ty
+ | Record : 'a record -> 'a ty
+and 'a record = { path : string; fields : 'a field_ list; }
+and 'a field_ = Field : ('a, 'b) field -> 'a field_
+and ('a, 'b) field = { label : string; field_type : 'b ty; get : 'a -> 'b; }
+# type variant =
+ VInt of int
+ | VString of string
+ | VList of variant list
+ | VPair of variant * variant
+ | VRecord of (string * variant) list
+val variantize : 't ty -> 't -> variant = <fun>
+# type 'a ty =
+ Int : int ty
+ | String : string ty
+ | List : 'a ty -> 'a list ty
+ | Pair : ('a ty * 'b ty) -> ('a * 'b) ty
+ | Record : ('a, 'builder) record -> 'a ty
+and ('a, 'builder) record = {
+ path : string;
+ fields : ('a, 'builder) field list;
+ create_builder : unit -> 'builder;
+ of_builder : 'builder -> 'a;
+}
+and ('a, 'builder) field =
+ Field : ('a, 'builder, 'b) field_ -> ('a, 'builder) field
+and ('a, 'builder, 'b) field_ = {
+ label : string;
+ field_type : 'b ty;
+ get : 'a -> 'b;
+ set : 'builder -> 'b -> unit;
+}
+val devariantize : 't ty -> variant -> 't = <fun>
+# type my_record = { a : int; b : string list; }
+val my_record : my_record ty =
+ Record
+ {path = "My_module.my_record";
+ fields =
+ [Field {label = "a"; field_type = Int; get = <fun>; set = <fun>};
+ Field {label = "b"; field_type = List String; get = <fun>; set = <fun>}];
+ create_builder = <fun>; of_builder = <fun>}
+# type noarg = Noarg
+type (_, _) ty =
+ Int : (int, 'c) ty
+ | String : (string, 'd) ty
+ | List : ('a, 'e) ty -> ('a list, 'e) ty
+ | Option : ('a, 'e) ty -> ('a option, 'e) ty
+ | Pair : (('a, 'e) ty * ('b, 'e) ty) -> ('a * 'b, 'e) ty
+ | Var : ('a, 'a -> 'e) ty
+ | Rec : ('a, 'a -> 'e) ty -> ('a, 'e) ty
+ | Pop : ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ | Conv : string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ | Sum : ('a, 'e, 'b) ty_sum -> ('a, 'e) ty
+and ('a, 'e, 'b) ty_sum = {
+ sum_proj : 'a -> string * 'e ty_dyn option;
+ sum_cases : (string * ('e, 'b) ty_case) list;
+ sum_inj : 'c. ('b, 'c) ty_sel * 'c -> 'a;
+}
+and 'e ty_dyn = Tdyn : ('a, 'e) ty * 'a -> 'e ty_dyn
+and (_, _) ty_sel =
+ Thd : ('a -> 'b, 'a) ty_sel
+ | Ttl : ('b -> 'c, 'd) ty_sel -> ('a -> 'b -> 'c, 'd) ty_sel
+and (_, _) ty_case =
+ TCarg : ('b, 'a) ty_sel * ('a, 'e) ty -> ('e, 'b) ty_case
+ | TCnoarg : ('b, noarg) ty_sel -> ('e, 'b) ty_case
+# type _ ty_env =
+ Enil : unit ty_env
+ | Econs : ('a, 'e) ty * 'e ty_env -> ('a -> 'e) ty_env
+# type (_, _) eq = Eq : ('a, 'a) eq
+val eq_sel : ('a, 'b) ty_sel -> ('a, 'c) ty_sel -> ('b, 'c) eq option = <fun>
+val get_case :
+ ('b, 'a) ty_sel ->
+ (string * ('e, 'b) ty_case) list -> string * ('a, 'e) ty option = <fun>
+# type variant =
+ VInt of int
+ | VString of string
+ | VList of variant list
+ | VOption of variant option
+ | VPair of variant * variant
+ | VConv of string * variant
+ | VSum of string * variant option
+val may_map : ('a -> 'b) -> 'a option -> 'b option = <fun>
+val variantize : 'e ty_env -> ('a, 'e) ty -> 'a -> variant = <fun>
+# val devariantize : 'e ty_env -> ('t, 'e) ty -> variant -> 't = <fun>
+# val wrap_A : ('a, 'b) ty -> ([ `A of 'a ], 'b) ty = <fun>
+# val ty : ('a, ([ `A of ('a * 'b) option ] as 'b) -> 'c) ty -> ('b, 'c) ty =
+ <fun>
+# val v : ([ `A of (int * 'a) option ] as 'a) -> variant = <fun>
+# val x : variant =
+ VConv ("`A",
+ VOption
+ (Some
+ (VPair (VInt 1,
+ VConv ("`A",
+ VOption (Some (VPair (VInt 2, VConv ("`A", VOption None)))))))))
+# val triple :
+ ('a, 'b) ty -> ('c, 'b) ty -> ('d, 'b) ty -> ('a * 'c * 'd, 'b) ty = <fun>
+val v : variant =
+ VConv ("Triple", VPair (VString "A", VPair (VInt 2, VInt 3)))
+# val ty_abc : ([ `A of int | `B of string | `C ], 'a) ty =
+ Sum
+ {sum_proj = <fun>;
+ sum_cases =
+ [("A", TCarg (Thd, Int)); ("B", TCarg (Ttl Thd, String));
+ ("C", TCnoarg (Ttl (Ttl Thd)))];
+ sum_inj = <fun>}
+# val a : [ `A of int | `B of string | `C ] = `A 3
+type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ]
+val ty_list : ('a, 'e) ty -> ('a vlist, 'e) ty = <fun>
+val v : variant =
+ VSum ("Cons",
+ Some
+ (VPair (VInt 1, VSum ("Cons", Some (VPair (VInt 2, VSum ("Nil", None)))))))
+# type (_, _) ty =
+ Int : (int, 'c) ty
+ | String : (string, 'd) ty
+ | List : ('a, 'e) ty -> ('a list, 'e) ty
+ | Option : ('a, 'e) ty -> ('a option, 'e) ty
+ | Pair : (('a, 'e) ty * ('b, 'e) ty) -> ('a * 'b, 'e) ty
+ | Var : ('a, 'a -> 'e) ty
+ | Rec : ('a, 'a -> 'e) ty -> ('a, 'e) ty
+ | Pop : ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ | Conv : string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ | Sum : ('a -> string * 'e ty_dyn option) *
+ (string * 'e ty_dyn option -> 'a) -> ('a, 'e) ty
+and 'e ty_dyn = Tdyn : ('a, 'e) ty * 'a -> 'e ty_dyn
+val ty_abc : ([ `A of int | `B of string | `C ], 'e) ty = Sum (<fun>, <fun>)
+# Characters 327-344:
+ | "Cons", Some (Tdyn (Pair (_, Var), (p : a * a vlist))) -> `Cons p)))
+ ^^^^^^^^^^^^^^^^^
+Error: This pattern matches values of type a * a vlist
+ but a pattern was expected which matches values of type
+ $Tdyn_'a = $0 * $1
+ Type a is not compatible with type $0
+# type (_, _) ty =
+ Int : (int, 'd) ty
+ | String : (string, 'f) ty
+ | List : ('a, 'e) ty -> ('a list, 'e) ty
+ | Option : ('a, 'e) ty -> ('a option, 'e) ty
+ | Pair : (('a, 'e) ty * ('b, 'e) ty) -> ('a * 'b, 'e) ty
+ | Var : ('a, 'a -> 'e) ty
+ | Rec : ('a, 'a -> 'e) ty -> ('a, 'e) ty
+ | Pop : ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ | Conv : string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ | Sum :
+ < cases : (string * ('e, 'b) ty_case) list;
+ inj : 'c. ('b, 'c) ty_sel * 'c -> 'a;
+ proj : 'a -> string * 'e ty_dyn option > -> ('a, 'e) ty
+and 'e ty_dyn = Tdyn : ('a, 'e) ty * 'a -> 'e ty_dyn
+and (_, _) ty_sel =
+ Thd : ('a -> 'b, 'a) ty_sel
+ | Ttl : ('b -> 'c, 'd) ty_sel -> ('a -> 'b -> 'c, 'd) ty_sel
+and (_, _) ty_case =
+ TCarg : ('b, 'a) ty_sel * ('a, 'e) ty -> ('e, 'b) ty_case
+ | TCnoarg : ('b, noarg) ty_sel -> ('e, 'b) ty_case
+# val ty_abc : ([ `A of int | `B of string | `C ], 'e) ty = Sum <obj>
+type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ]
+val ty_list : ('a, 'e) ty -> ('a vlist, 'e) ty = <fun>
+# * * * * * * * * *
diff --git a/testsuite/tests/typing-gadts/dynamic_frisch.ml.reference b/testsuite/tests/typing-gadts/dynamic_frisch.ml.reference
new file mode 100644
index 0000000000..7372c163bd
--- /dev/null
+++ b/testsuite/tests/typing-gadts/dynamic_frisch.ml.reference
@@ -0,0 +1,177 @@
+
+# type 'a ty =
+ Int : int ty
+ | String : string ty
+ | List : 'a ty -> 'a list ty
+ | Pair : ('a ty * 'b ty) -> ('a * 'b) ty
+# type variant =
+ VInt of int
+ | VString of string
+ | VList of variant list
+ | VPair of variant * variant
+val variantize : 't ty -> 't -> variant = <fun>
+exception VariantMismatch
+val devariantize : 't ty -> variant -> 't = <fun>
+# type 'a ty =
+ Int : int ty
+ | String : string ty
+ | List : 'a ty -> 'a list ty
+ | Pair : ('a ty * 'b ty) -> ('a * 'b) ty
+ | Record : 'a record -> 'a ty
+and 'a record = { path : string; fields : 'a field_ list; }
+and 'a field_ = Field : ('a, 'b) field -> 'a field_
+and ('a, 'b) field = { label : string; field_type : 'b ty; get : 'a -> 'b; }
+# type variant =
+ VInt of int
+ | VString of string
+ | VList of variant list
+ | VPair of variant * variant
+ | VRecord of (string * variant) list
+val variantize : 't ty -> 't -> variant = <fun>
+# type 'a ty =
+ Int : int ty
+ | String : string ty
+ | List : 'a ty -> 'a list ty
+ | Pair : ('a ty * 'b ty) -> ('a * 'b) ty
+ | Record : ('a, 'builder) record -> 'a ty
+and ('a, 'builder) record = {
+ path : string;
+ fields : ('a, 'builder) field list;
+ create_builder : unit -> 'builder;
+ of_builder : 'builder -> 'a;
+}
+and ('a, 'builder) field =
+ Field : ('a, 'builder, 'b) field_ -> ('a, 'builder) field
+and ('a, 'builder, 'b) field_ = {
+ label : string;
+ field_type : 'b ty;
+ get : 'a -> 'b;
+ set : 'builder -> 'b -> unit;
+}
+val devariantize : 't ty -> variant -> 't = <fun>
+# type my_record = { a : int; b : string list; }
+val my_record : my_record ty =
+ Record
+ {path = "My_module.my_record";
+ fields =
+ [Field {label = "a"; field_type = Int; get = <fun>; set = <fun>};
+ Field {label = "b"; field_type = List String; get = <fun>; set = <fun>}];
+ create_builder = <fun>; of_builder = <fun>}
+# type noarg = Noarg
+type (_, _) ty =
+ Int : (int, 'c) ty
+ | String : (string, 'd) ty
+ | List : ('a, 'e) ty -> ('a list, 'e) ty
+ | Option : ('a, 'e) ty -> ('a option, 'e) ty
+ | Pair : (('a, 'e) ty * ('b, 'e) ty) -> ('a * 'b, 'e) ty
+ | Var : ('a, 'a -> 'e) ty
+ | Rec : ('a, 'a -> 'e) ty -> ('a, 'e) ty
+ | Pop : ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ | Conv : string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ | Sum : ('a, 'e, 'b) ty_sum -> ('a, 'e) ty
+and ('a, 'e, 'b) ty_sum = {
+ sum_proj : 'a -> string * 'e ty_dyn option;
+ sum_cases : (string * ('e, 'b) ty_case) list;
+ sum_inj : 'c. ('b, 'c) ty_sel * 'c -> 'a;
+}
+and 'e ty_dyn = Tdyn : ('a, 'e) ty * 'a -> 'e ty_dyn
+and (_, _) ty_sel =
+ Thd : ('a -> 'b, 'a) ty_sel
+ | Ttl : ('b -> 'c, 'd) ty_sel -> ('a -> 'b -> 'c, 'd) ty_sel
+and (_, _) ty_case =
+ TCarg : ('b, 'a) ty_sel * ('a, 'e) ty -> ('e, 'b) ty_case
+ | TCnoarg : ('b, noarg) ty_sel -> ('e, 'b) ty_case
+# type _ ty_env =
+ Enil : unit ty_env
+ | Econs : ('a, 'e) ty * 'e ty_env -> ('a -> 'e) ty_env
+# type (_, _) eq = Eq : ('a, 'a) eq
+val eq_sel : ('a, 'b) ty_sel -> ('a, 'c) ty_sel -> ('b, 'c) eq option = <fun>
+val get_case :
+ ('b, 'a) ty_sel ->
+ (string * ('e, 'b) ty_case) list -> string * ('a, 'e) ty option = <fun>
+# type variant =
+ VInt of int
+ | VString of string
+ | VList of variant list
+ | VOption of variant option
+ | VPair of variant * variant
+ | VConv of string * variant
+ | VSum of string * variant option
+val may_map : ('a -> 'b) -> 'a option -> 'b option = <fun>
+val variantize : 'e ty_env -> ('a, 'e) ty -> 'a -> variant = <fun>
+# val devariantize : 'e ty_env -> ('t, 'e) ty -> variant -> 't = <fun>
+# val wrap_A : ('a, 'b) ty -> ([ `A of 'a ], 'b) ty = <fun>
+# val ty : ('a, ([ `A of ('a * 'b) option ] as 'b) -> 'c) ty -> ('b, 'c) ty =
+ <fun>
+# val v : ([ `A of (int * 'a) option ] as 'a) -> variant = <fun>
+# val x : variant =
+ VConv ("`A",
+ VOption
+ (Some
+ (VPair (VInt 1,
+ VConv ("`A",
+ VOption (Some (VPair (VInt 2, VConv ("`A", VOption None)))))))))
+# val triple :
+ ('a, 'b) ty -> ('c, 'b) ty -> ('d, 'b) ty -> ('a * 'c * 'd, 'b) ty = <fun>
+val v : variant =
+ VConv ("Triple", VPair (VString "A", VPair (VInt 2, VInt 3)))
+# val ty_abc : ([ `A of int | `B of string | `C ], 'a) ty =
+ Sum
+ {sum_proj = <fun>;
+ sum_cases =
+ [("A", TCarg (Thd, Int)); ("B", TCarg (Ttl Thd, String));
+ ("C", TCnoarg (Ttl (Ttl Thd)))];
+ sum_inj = <fun>}
+# val a : [ `A of int | `B of string | `C ] = `A 3
+type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ]
+val ty_list : ('a, 'e) ty -> ('a vlist, 'e) ty = <fun>
+val v : variant =
+ VSum ("Cons",
+ Some
+ (VPair (VInt 1, VSum ("Cons", Some (VPair (VInt 2, VSum ("Nil", None)))))))
+# type (_, _) ty =
+ Int : (int, 'c) ty
+ | String : (string, 'd) ty
+ | List : ('a, 'e) ty -> ('a list, 'e) ty
+ | Option : ('a, 'e) ty -> ('a option, 'e) ty
+ | Pair : (('a, 'e) ty * ('b, 'e) ty) -> ('a * 'b, 'e) ty
+ | Var : ('a, 'a -> 'e) ty
+ | Rec : ('a, 'a -> 'e) ty -> ('a, 'e) ty
+ | Pop : ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ | Conv : string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ | Sum : ('a -> string * 'e ty_dyn option) *
+ (string * 'e ty_dyn option -> 'a) -> ('a, 'e) ty
+and 'e ty_dyn = Tdyn : ('a, 'e) ty * 'a -> 'e ty_dyn
+val ty_abc : ([ `A of int | `B of string | `C ], 'e) ty = Sum (<fun>, <fun>)
+# Characters 327-344:
+ | "Cons", Some (Tdyn (Pair (_, Var), (p : a * a vlist))) -> `Cons p)))
+ ^^^^^^^^^^^^^^^^^
+Error: This pattern matches values of type a * a vlist
+ but a pattern was expected which matches values of type
+ $Tdyn_'a = $0 * $1
+ Type a is not compatible with type $0
+# type (_, _) ty =
+ Int : (int, 'd) ty
+ | String : (string, 'f) ty
+ | List : ('a, 'e) ty -> ('a list, 'e) ty
+ | Option : ('a, 'e) ty -> ('a option, 'e) ty
+ | Pair : (('a, 'e) ty * ('b, 'e) ty) -> ('a * 'b, 'e) ty
+ | Var : ('a, 'a -> 'e) ty
+ | Rec : ('a, 'a -> 'e) ty -> ('a, 'e) ty
+ | Pop : ('a, 'e) ty -> ('a, 'b -> 'e) ty
+ | Conv : string * ('a -> 'b) * ('b -> 'a) * ('b, 'e) ty -> ('a, 'e) ty
+ | Sum :
+ < cases : (string * ('e, 'b) ty_case) list;
+ inj : 'c. ('b, 'c) ty_sel * 'c -> 'a;
+ proj : 'a -> string * 'e ty_dyn option > -> ('a, 'e) ty
+and 'e ty_dyn = Tdyn : ('a, 'e) ty * 'a -> 'e ty_dyn
+and (_, _) ty_sel =
+ Thd : ('a -> 'b, 'a) ty_sel
+ | Ttl : ('b -> 'c, 'd) ty_sel -> ('a -> 'b -> 'c, 'd) ty_sel
+and (_, _) ty_case =
+ TCarg : ('b, 'a) ty_sel * ('a, 'e) ty -> ('e, 'b) ty_case
+ | TCnoarg : ('b, noarg) ty_sel -> ('e, 'b) ty_case
+# val ty_abc : ([ `A of int | `B of string | `C ], 'e) ty = Sum <obj>
+type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ]
+val ty_list : ('a, 'e) ty -> ('a vlist, 'e) ty = <fun>
+# * * * * * * * * *
diff --git a/testsuite/tests/typing-gadts/omega07.ml b/testsuite/tests/typing-gadts/omega07.ml
new file mode 100644
index 0000000000..9b3bd7e2bf
--- /dev/null
+++ b/testsuite/tests/typing-gadts/omega07.ml
@@ -0,0 +1,798 @@
+(*
+ An attempt at encoding omega examples from the 2nd Central European
+ Functional Programming School:
+ Generic Programming in Omega, by Tim Sheard and Nathan Linger
+ http://web.cecs.pdx.edu/~sheard/
+*)
+
+(* Basic types *)
+
+type ('a,'b) sum = Inl of 'a | Inr of 'b
+
+type zero = Zero
+type 'a succ = Succ of 'a
+type _ nat =
+ | NZ : zero nat
+ | NS : 'a nat -> 'a succ nat
+;;
+
+(* 2: A simple example *)
+
+type (_,_) seq =
+ | Snil : ('a,zero) seq
+ | Scons : 'a * ('a,'n) seq -> ('a, 'n succ) seq
+;;
+
+let l1 = Scons (3, Scons (5, Snil)) ;;
+
+(* We do not have type level functions, so we need to use witnesses. *)
+(* We copy here the definitions from section 3.9 *)
+(* Note the addition of the ['a nat] argument to PlusZ, since we do not
+ have kinds *)
+type (_,_,_) plus =
+ | PlusZ : 'a nat -> (zero, 'a, 'a) plus
+ | PlusS : ('a,'b,'c) plus -> ('a succ, 'b, 'c succ) plus
+;;
+
+let rec length : type a n. (a,n) seq -> n nat = function
+ | Snil -> NZ
+ | Scons (_, s) -> NS (length s)
+;;
+
+(* app returns the catenated lists with a witness proving that
+ the size is the sum of its two inputs *)
+type (_,_,_) app = App : ('a,'p) seq * ('n,'m,'p) plus -> ('a,'n,'m) app
+
+let rec app : type a n m. (a,n) seq -> (a,m) seq -> (a,n,m) app =
+ fun xs ys ->
+ match xs with
+ | Snil -> App (ys, PlusZ (length ys))
+ | Scons (x, xs') ->
+ let App (xs'', pl) = app xs' ys in
+ App (Scons (x, xs''), PlusS pl)
+;;
+
+(* 3.1 Feature: kinds *)
+
+(* We do not have kinds, but we can encode them as predicates *)
+
+type tp = TP
+type nd = ND
+type ('a,'b) fk = FK
+type _ shape =
+ | Tp : tp shape
+ | Nd : nd shape
+ | Fk : 'a shape * 'b shape -> ('a,'b) fk shape
+;;
+type tt = TT
+type ff = FF
+type _ boolean =
+ | BT : tt boolean
+ | BF : ff boolean
+;;
+
+(* 3.3 Feature : GADTs *)
+
+type (_,_) path =
+ | Pnone : 'a -> (tp,'a) path
+ | Phere : (nd,'a) path
+ | Pleft : ('x,'a) path -> (('x,'y) fk, 'a) path
+ | Pright : ('y,'a) path -> (('x,'y) fk, 'a) path
+;;
+type (_,_) tree =
+ | Ttip : (tp,'a) tree
+ | Tnode : 'a -> (nd,'a) tree
+ | Tfork : ('x,'a) tree * ('y,'a) tree -> (('x,'y)fk, 'a) tree
+;;
+let tree1 = Tfork (Tfork (Ttip, Tnode 4), Tfork (Tnode 4, Tnode 3))
+;;
+let rec find : type sh.
+ ('a -> 'a -> bool) -> 'a -> (sh,'a) tree -> (sh,'a) path list
+ = fun eq n t ->
+ match t with
+ | Ttip -> []
+ | Tnode m ->
+ if eq n m then [Phere] else []
+ | Tfork (x, y) ->
+ List.map (fun x -> Pleft x) (find eq n x) @
+ List.map (fun x -> Pright x) (find eq n y)
+;;
+let rec extract : type sh. (sh,'a) path -> (sh,'a) tree -> 'a = fun p t ->
+ match (p, t) with
+ | Pnone x, Ttip -> x
+ | Phere, Tnode y -> y
+ | Pleft p, Tfork(l,_) -> extract p l
+ | Pright p, Tfork(_,r) -> extract p r
+;;
+
+(* 3.4 Pattern : Witness *)
+
+type (_,_) le =
+ | LeZ : 'a nat -> (zero, 'a) le
+ | LeS : ('n, 'm) le -> ('n succ, 'm succ) le
+;;
+type _ even =
+ | EvenZ : zero even
+ | EvenSS : 'n even -> 'n succ succ even
+;;
+type one = zero succ
+type two = one succ
+type three = two succ
+type four = three succ
+;;
+let even0 : zero even = EvenZ
+let even2 : two even = EvenSS EvenZ
+let even4 : four even = EvenSS (EvenSS EvenZ)
+;;
+let p1 : (two, one, three) plus = PlusS (PlusS (PlusZ (NS NZ)))
+;;
+let rec summandLessThanSum : type a b c. (a,b,c) plus -> (a,c) le = fun p ->
+ match p with
+ | PlusZ n -> LeZ n
+ | PlusS p' -> LeS (summandLessThanSum p')
+;;
+
+(* 3.8 Pattern: Leibniz Equality *)
+
+type (_,_) equal = Eq : ('a,'a) equal
+
+let convert : type a b. (a,b) equal -> a -> b = fun Eq x -> x
+
+let rec sameNat : type a b. a nat -> b nat -> (a,b) equal option = fun a b ->
+ match a, b with
+ | NZ, NZ -> Some Eq
+ | NS a', NS b' ->
+ begin match sameNat a' b' with
+ | Some Eq -> Some Eq
+ | None -> None
+ end
+ | _ -> None
+;;
+
+(* Extra: associativity of addition *)
+
+let rec plus_func : type a b m n.
+ (a,b,m) plus -> (a,b,n) plus -> (m,n) equal =
+ fun p1 p2 ->
+ match p1, p2 with
+ | PlusZ _, PlusZ _ -> Eq
+ | PlusS p1', PlusS p2' ->
+ let Eq = plus_func p1' p2' in Eq
+
+let rec plus_assoc : type a b c ab bc m n.
+ (a,b,ab) plus -> (ab,c,m) plus ->
+ (b,c,bc) plus -> (a,bc,n) plus -> (m,n) equal = fun p1 p2 p3 p4 ->
+ match p1, p4 with
+ | PlusZ b, PlusZ bc ->
+ let Eq = plus_func p2 p3 in Eq
+ | PlusS p1', PlusS p4' ->
+ let PlusS p2' = p2 in
+ let Eq = plus_assoc p1' p2' p3 p4' in Eq
+;;
+
+(* 3.9 Computing Programs and Properties Simultaneously *)
+
+(* Plus and app1 are moved to section 2 *)
+
+let smaller : type a b. (a succ, b succ) le -> (a,b) le =
+ function LeS x -> x ;;
+
+type (_,_) diff = Diff : 'c nat * ('a,'c,'b) plus -> ('a,'b) diff ;;
+
+(*
+let rec diff : type a b. (a,b) le -> a nat -> b nat -> (a,b) diff =
+ fun le a b ->
+ match a, b, le with
+ | NZ, m, _ -> Diff (m, PlusZ m)
+ | NS x, NZ, _ -> assert false
+ | NS x, NS y, q ->
+ match diff (smaller q) x y with Diff (m, p) -> Diff (m, PlusS p)
+;;
+*)
+
+let rec diff : type a b. (a,b) le -> a nat -> b nat -> (a,b) diff =
+ fun le a b ->
+ match le, a, b with
+ | LeZ _, _, m -> Diff (m, PlusZ m)
+ | LeS q, NS x, NS y ->
+ match diff q x y with Diff (m, p) -> Diff (m, PlusS p)
+;;
+
+let rec diff : type a b. (a,b) le -> a nat -> b nat -> (a,b) diff =
+ fun le a b ->
+ match a, b,le with (* warning *)
+ | NZ, m, LeZ _ -> Diff (m, PlusZ m)
+ | NS x, NS y, LeS q ->
+ match diff q x y with Diff (m, p) -> Diff (m, PlusS p)
+;;
+
+let rec diff : type a b. (a,b) le -> b nat -> (a,b) diff =
+ fun le b ->
+ match b,le with
+ | m, LeZ _ -> Diff (m, PlusZ m)
+ | NS y, LeS q ->
+ match diff q y with Diff (m, p) -> Diff (m, PlusS p)
+;;
+
+type (_,_) filter = Filter : ('m,'n) le * ('a,'m) seq -> ('a,'n) filter
+
+let rec leS' : type m n. (m,n) le -> (m,n succ) le = function
+ | LeZ n -> LeZ (NS n)
+ | LeS le -> LeS (leS' le)
+;;
+
+let rec filter : type a n. (a -> bool) -> (a,n) seq -> (a,n) filter =
+ fun f s ->
+ match s with
+ | Snil -> Filter (LeZ NZ, Snil)
+ | Scons (a,l) ->
+ match filter f l with Filter (le, l') ->
+ if f a then Filter (LeS le, Scons (a, l'))
+ else Filter (leS' le, l')
+;;
+
+(* 4.1 AVL trees *)
+
+type (_,_,_) balance =
+ | Less : ('h, 'h succ, 'h succ) balance
+ | Same : ('h, 'h, 'h) balance
+ | More : ('h succ, 'h, 'h succ) balance
+
+type _ avl =
+ | Leaf : zero avl
+ | Node :
+ ('hL, 'hR, 'hMax) balance * 'hL avl * int * 'hR avl -> 'hMax succ avl
+
+type avl' = Avl : 'h avl -> avl'
+;;
+
+let empty = Avl Leaf
+
+let rec elem : type h. int -> h avl -> bool = fun x t ->
+ match t with
+ | Leaf -> false
+ | Node (_, l, y, r) ->
+ x = y || if x < y then elem x l else elem x r
+;;
+
+let rec rotr : type n. (n succ succ) avl -> int -> n avl ->
+ ((n succ succ) avl, (n succ succ succ) avl) sum =
+ fun tL y tR ->
+ match tL with
+ | Node (Same, a, x, b) -> Inr (Node (Less, a, x, Node (More, b, y, tR)))
+ | Node (More, a, x, b) -> Inl (Node (Same, a, x, Node (Same, b, y, tR)))
+ | Node (Less, a, x, Node (Same, b, z, c)) ->
+ Inl (Node (Same, Node (Same, a, x, b), z, Node (Same, c, y, tR)))
+ | Node (Less, a, x, Node (Less, b, z, c)) ->
+ Inl (Node (Same, Node (More, a, x, b), z, Node (Same, c, y, tR)))
+ | Node (Less, a, x, Node (More, b, z, c)) ->
+ Inl (Node (Same, Node (Same, a, x, b), z, Node (Less, c, y, tR)))
+;;
+let rec rotl : type n. n avl -> int -> (n succ succ) avl ->
+ ((n succ succ) avl, (n succ succ succ) avl) sum =
+ fun tL u tR ->
+ match tR with
+ | Node (Same, a, x, b) -> Inr (Node (More, Node (Less, tL, u, a), x, b))
+ | Node (Less, a, x, b) -> Inl (Node (Same, Node (Same, tL, u, a), x, b))
+ | Node (More, Node (Same, a, x, b), y, c) ->
+ Inl (Node (Same, Node (Same, tL, u, a), x, Node (Same, b, y, c)))
+ | Node (More, Node (Less, a, x, b), y, c) ->
+ Inl (Node (Same, Node (More, tL, u, a), x, Node (Same, b, y, c)))
+ | Node (More, Node (More, a, x, b), y, c) ->
+ Inl (Node (Same, Node (Same, tL, u, a), x, Node (Less, b, y, c)))
+;;
+let rec ins : type n. int -> n avl -> (n avl, (n succ) avl) sum =
+ fun x t ->
+ match t with
+ | Leaf -> Inr (Node (Same, Leaf, x, Leaf))
+ | Node (bal, a, y, b) ->
+ if x = y then Inl t else
+ if x < y then begin
+ match ins x a with
+ | Inl a -> Inl (Node (bal, a, y, b))
+ | Inr a ->
+ match bal with
+ | Less -> Inl (Node (Same, a, y, b))
+ | Same -> Inr (Node (More, a, y, b))
+ | More -> rotr a y b
+ end else begin
+ match ins x b with
+ | Inl b -> Inl (Node (bal, a, y, b) : n avl)
+ | Inr b ->
+ match bal with
+ | More -> Inl (Node (Same, a, y, b) : n avl)
+ | Same -> Inr (Node (Less, a, y, b) : n succ avl)
+ | Less -> rotl a y b
+ end
+;;
+
+let insert x (Avl t) =
+ match ins x t with
+ | Inl t -> Avl t
+ | Inr t -> Avl t
+;;
+
+let rec del_min : type n. (n succ) avl -> int * (n avl, (n succ) avl) sum =
+ function
+ | Node (Less, Leaf, x, r) -> (x, Inl r)
+ | Node (Same, Leaf, x, r) -> (x, Inl r)
+ | Node (bal, (Node _ as l) , x, r) ->
+ match del_min l with
+ | y, Inr l -> (y, Inr (Node (bal, l, x, r)))
+ | y, Inl l ->
+ (y, match bal with
+ | Same -> Inr (Node (Less, l, x, r))
+ | More -> Inl (Node (Same, l, x, r))
+ | Less -> rotl l x r)
+
+type _ avl_del =
+ | Dsame : 'n avl -> 'n avl_del
+ | Ddecr : ('m succ, 'n) equal * 'm avl -> 'n avl_del
+
+let rec del : type n. int -> n avl -> n avl_del = fun y t ->
+ match t with
+ | Leaf -> Dsame Leaf
+ | Node (bal, l, x, r) ->
+ if x = y then begin
+ match r with
+ | Leaf ->
+ begin match bal with
+ | Same -> Ddecr (Eq, l)
+ | More -> Ddecr (Eq, l)
+ end
+ | Node _ ->
+ begin match bal, del_min r with
+ | _, (z, Inr r) -> Dsame (Node (bal, l, z, r))
+ | Same, (z, Inl r) -> Dsame (Node (More, l, z, r))
+ | Less, (z, Inl r) -> Ddecr (Eq, Node (Same, l, z, r))
+ | More, (z, Inl r) ->
+ match rotr l z r with
+ | Inl t -> Ddecr (Eq, t)
+ | Inr t -> Dsame t
+ end
+ end else if y < x then begin
+ match del y l with
+ | Dsame l -> Dsame (Node (bal, l, x, r))
+ | Ddecr(Eq,l) ->
+ begin match bal with
+ | Same -> Dsame (Node (Less, l, x, r))
+ | More -> Ddecr (Eq, Node (Same, l, x, r))
+ | Less ->
+ match rotl l x r with
+ | Inl t -> Ddecr (Eq, t)
+ | Inr t -> Dsame t
+ end
+ end else begin
+ match del y r with
+ | Dsame r -> Dsame (Node (bal, l, x, r))
+ | Ddecr(Eq,r) ->
+ begin match bal with
+ | Same -> Dsame (Node (More, l, x, r))
+ | Less -> Ddecr (Eq, Node (Same, l, x, r))
+ | More ->
+ match rotr l x r with
+ | Inl t -> Ddecr (Eq, t)
+ | Inr t -> Dsame t
+ end
+ end
+;;
+
+let delete x (Avl t) =
+ match del x t with
+ | Dsame t -> Avl t
+ | Ddecr (_, t) -> Avl t
+;;
+
+
+(* Exercise 22: Red-black trees *)
+
+type red = RED
+type black = BLACK
+type (_,_) sub_tree =
+ | Bleaf : (black, zero) sub_tree
+ | Rnode :
+ (black, 'n) sub_tree * int * (black, 'n) sub_tree -> (red, 'n) sub_tree
+ | Bnode :
+ ('cL, 'n) sub_tree * int * ('cR, 'n) sub_tree -> (black, 'n succ) sub_tree
+
+type rb_tree = Root : (black, 'n) sub_tree -> rb_tree
+;;
+
+type dir = LeftD | RightD
+
+type (_,_) ctxt =
+ | CNil : (black,'n) ctxt
+ | CRed : int * dir * (black,'n) sub_tree * (red,'n) ctxt -> (black,'n) ctxt
+ | CBlk : int * dir * ('c1,'n) sub_tree * (black, 'n succ) ctxt -> ('c,'n) ctxt
+;;
+
+let blacken = function
+ Rnode (l, e, r) -> Bnode (l, e, r)
+
+type _ crep =
+ | Red : red crep
+ | Black : black crep
+
+let color : type c n. (c,n) sub_tree -> c crep = function
+ | Bleaf -> Black
+ | Rnode _ -> Red
+ | Bnode _ -> Black
+;;
+
+let rec fill : type c n. (c,n) ctxt -> (c,n) sub_tree -> rb_tree =
+ fun ct t ->
+ match ct with
+ | CNil -> Root t
+ | CRed (e, LeftD, uncle, c) -> fill c (Rnode (uncle, e, t))
+ | CRed (e, RightD, uncle, c) -> fill c (Rnode (t, e, uncle))
+ | CBlk (e, LeftD, uncle, c) -> fill c (Bnode (uncle, e, t))
+ | CBlk (e, RightD, uncle, c) -> fill c (Bnode (t, e, uncle))
+;;
+let recolor d1 pE sib d2 gE uncle t =
+ match d1, d2 with
+ | LeftD, RightD -> Rnode (Bnode (sib, pE, t), gE, uncle)
+ | RightD, RightD -> Rnode (Bnode (t, pE, sib), gE, uncle)
+ | LeftD, LeftD -> Rnode (uncle, gE, Bnode (sib, pE, t))
+ | RightD, LeftD -> Rnode (uncle, gE, Bnode (t, pE, sib))
+;;
+let rotate d1 pE sib d2 gE uncle (Rnode (x, e, y)) =
+ match d1, d2 with
+ | RightD, RightD -> Bnode (Rnode (x,e,y), pE, Rnode (sib, gE, uncle))
+ | LeftD, RightD -> Bnode (Rnode (sib, pE, x), e, Rnode (y, gE, uncle))
+ | LeftD, LeftD -> Bnode (Rnode (uncle, gE, sib), pE, Rnode (x,e,y))
+ | RightD, LeftD -> Bnode (Rnode (uncle, gE, x), e, Rnode (y, pE, sib))
+;;
+let rec repair : type c n. (red,n) sub_tree -> (c,n) ctxt -> rb_tree =
+ fun t ct ->
+ match ct with
+ | CNil -> Root (blacken t)
+ | CBlk (e, LeftD, sib, c) -> fill c (Bnode (sib, e, t))
+ | CBlk (e, RightD, sib, c) -> fill c (Bnode (t, e, sib))
+ | CRed (e, dir, sib, CBlk (e', dir', uncle, ct)) ->
+ match color uncle with
+ | Red -> repair (recolor dir e sib dir' e' (blacken uncle) t) ct
+ | Black -> fill ct (rotate dir e sib dir' e' uncle t)
+;;
+let rec ins : type c n. int -> (c,n) sub_tree -> (c,n) ctxt -> rb_tree =
+ fun e t ct ->
+ match t with
+ | Rnode (l, e', r) ->
+ if e < e' then ins e l (CRed (e', RightD, r, ct))
+ else ins e r (CRed (e', LeftD, l, ct))
+ | Bnode (l, e', r) ->
+ if e < e' then ins e l (CBlk (e', RightD, r, ct))
+ else ins e r (CBlk (e', LeftD, l, ct))
+ | Bleaf -> repair (Rnode (Bleaf, e, Bleaf)) ct
+;;
+let insert e (Root t) = ins e t CNil
+;;
+
+(* 5.7 typed object languages using GADTs *)
+
+type _ term =
+ | Const : int -> int term
+ | Add : (int * int -> int) term
+ | LT : (int * int -> bool) term
+ | Ap : ('a -> 'b) term * 'a term -> 'b term
+ | Pair : 'a term * 'b term -> ('a * 'b) term
+
+let ex1 = Ap (Add, Pair (Const 3, Const 5))
+let ex2 = Pair (ex1, Const 1)
+
+let rec eval_term : type a. a term -> a = function
+ | Const x -> x
+ | Add -> fun (x,y) -> x+y
+ | LT -> fun (x,y) -> x<y
+ | Ap(f,x) -> eval_term f (eval_term x)
+ | Pair(x,y) -> (eval_term x, eval_term y)
+
+type _ rep =
+ | Rint : int rep
+ | Rbool : bool rep
+ | Rpair : 'a rep * 'b rep -> ('a * 'b) rep
+ | Rfun : 'a rep * 'b rep -> ('a -> 'b) rep
+
+type (_,_) equal = Eq : ('a,'a) equal
+
+let rec rep_equal : type a b. a rep -> b rep -> (a, b) equal option =
+ fun ra rb ->
+ match ra, rb with
+ | Rint, Rint -> Some Eq
+ | Rbool, Rbool -> Some Eq
+ | Rpair (a1, a2), Rpair (b1, b2) ->
+ begin match rep_equal a1 b1 with
+ | None -> None
+ | Some Eq -> match rep_equal a2 b2 with
+ | None -> None
+ | Some Eq -> Some Eq
+ end
+ | Rfun (a1, a2), Rfun (b1, b2) ->
+ begin match rep_equal a1 b1 with
+ | None -> None
+ | Some Eq -> match rep_equal a2 b2 with
+ | None -> None
+ | Some Eq -> Some Eq
+ end
+ | _ -> None
+;;
+
+type assoc = Assoc : string * 'a rep * 'a -> assoc
+
+let rec assoc : type a. string -> a rep -> assoc list -> a =
+ fun x r -> function
+ | [] -> raise Not_found
+ | Assoc (x', r', v) :: env ->
+ if x = x' then
+ match rep_equal r r' with
+ | None -> failwith ("Wrong type for " ^ x)
+ | Some Eq -> v
+ else assoc x r env
+
+type _ term =
+ | Var : string * 'a rep -> 'a term
+ | Abs : string * 'a rep * 'b term -> ('a -> 'b) term
+ | Const : int -> int term
+ | Add : (int * int -> int) term
+ | LT : (int * int -> bool) term
+ | Ap : ('a -> 'b) term * 'a term -> 'b term
+ | Pair : 'a term * 'b term -> ('a * 'b) term
+
+let rec eval_term : type a. assoc list -> a term -> a =
+ fun env -> function
+ | Var (x, r) -> assoc x r env
+ | Abs (x, r, e) -> fun v -> eval_term (Assoc (x, r, v) :: env) e
+ | Const x -> x
+ | Add -> fun (x,y) -> x+y
+ | LT -> fun (x,y) -> x<y
+ | Ap(f,x) -> eval_term env f (eval_term env x)
+ | Pair(x,y) -> (eval_term env x, eval_term env y)
+;;
+
+let ex3 = Abs ("x", Rint, Ap (Add, Pair (Var("x",Rint), Var("x",Rint))))
+let ex4 = Ap (ex3, Const 3)
+
+let v4 = eval_term [] ex4
+;;
+
+(* 5.9/5.10 Language with binding *)
+
+type rnil = RNIL
+type ('a,'b,'c) rcons = RCons of 'a * 'b * 'c
+
+type _ is_row =
+ | Rnil : rnil is_row
+ | Rcons : 'c is_row -> ('a,'b,'c) rcons is_row
+
+type (_,_) lam =
+ | Const : int -> ('e, int) lam
+ | Var : 'a -> (('a,'t,'e) rcons, 't) lam
+ | Shift : ('e,'t) lam -> (('a,'q,'e) rcons, 't) lam
+ | Abs : 'a * (('a,'s,'e) rcons, 't) lam -> ('e, 's -> 't) lam
+ | App : ('e, 's -> 't) lam * ('e, 's) lam -> ('e, 't) lam
+
+type x = X
+type y = Y
+
+let ex1 = App (Var X, Shift (Var Y))
+let ex2 = Abs (X, Abs (Y, App (Shift (Var X), Var Y)))
+;;
+
+type _ env =
+ | Enil : rnil env
+ | Econs : 'a * 't * 'e env -> ('a, 't, 'e) rcons env
+
+let rec eval_lam : type e t. e env -> (e, t) lam -> t =
+ fun env m ->
+ match env, m with
+ | _, Const n -> n
+ | Econs (_, v, r), Var _ -> v
+ | Econs (_, _, r), Shift e -> eval_lam r e
+ | _, Abs (n, body) -> fun x -> eval_lam (Econs (n, x, env)) body
+ | _, App (f, x) -> eval_lam env f (eval_lam env x)
+;;
+
+type add = Add
+type suc = Suc
+
+let env0 = Econs (Zero, 0, Econs (Suc, succ, Econs (Add, (+), Enil)))
+
+let _0 : (_, int) lam = Var Zero
+let suc x = App (Shift (Var Suc : (_, int -> int) lam), x)
+let _1 = suc _0
+let _2 = suc _1
+let _3 = suc _2
+let add = Shift (Shift (Var Add : (_, int -> int -> int) lam))
+
+let double = Abs (X, App (App (Shift add, Var X), Var X))
+let ex3 = App (double, _3)
+;;
+
+let v3 = eval_lam env0 ex3
+;;
+
+(* 5.13: Constructing typing derivations at runtime *)
+
+(* Modified slightly to use the language of 5.10, since this is more fun.
+ Of course this works also with the language of 5.12. *)
+
+type _ rep =
+ | I : int rep
+ | Ar : 'a rep * 'b rep -> ('a -> 'b) rep
+
+let rec compare : type a b. a rep -> b rep -> (string, (a,b) equal) sum =
+ fun a b ->
+ match a, b with
+ | I, I -> Inr Eq
+ | Ar(x,y), Ar(s,t) ->
+ begin match compare x s with
+ | Inl _ as e -> e
+ | Inr Eq -> match compare y t with
+ | Inl _ as e -> e
+ | Inr Eq as e -> e
+ end
+ | I, Ar _ -> Inl "I <> Ar _"
+ | Ar _, I -> Inl "Ar _ <> I"
+;;
+
+type term =
+ | C of int
+ | Ab : string * 'a rep * term -> term
+ | Ap of term * term
+ | V of string
+
+type _ ctx =
+ | Cnil : rnil ctx
+ | Ccons : 't * string * 'x rep * 'e ctx -> ('t,'x,'e) rcons ctx
+;;
+
+type _ checked =
+ | Cerror of string
+ | Cok : ('e,'t) lam * 't rep -> 'e checked
+
+let rec lookup : type e. string -> e ctx -> e checked =
+ fun name ctx ->
+ match ctx with
+ | Cnil -> Cerror ("Name not found: " ^ name)
+ | Ccons (l,s,t,rs) ->
+ if s = name then Cok (Var l,t) else
+ match lookup name rs with
+ | Cerror m -> Cerror m
+ | Cok (v, t) -> Cok (Shift v, t)
+;;
+
+let rec tc : type n e. n nat -> e ctx -> term -> e checked =
+ fun n ctx t ->
+ match t with
+ | V s -> lookup s ctx
+ | Ap(f,x) ->
+ begin match tc n ctx f with
+ | Cerror _ as e -> e
+ | Cok (f', ft) -> match tc n ctx x with
+ | Cerror _ as e -> e
+ | Cok (x', xt) ->
+ match ft with
+ | Ar (a, b) ->
+ begin match compare a xt with
+ | Inl s -> Cerror s
+ | Inr Eq -> Cok (App (f',x'), b)
+ end
+ | _ -> Cerror "Non fun in Ap"
+ end
+ | Ab(s,t,body) ->
+ begin match tc (NS n) (Ccons (n, s, t, ctx)) body with
+ | Cerror _ as e -> e
+ | Cok (body', et) -> Cok (Abs (n, body'), Ar (t, et))
+ end
+ | C m -> Cok (Const m, I)
+;;
+
+let ctx0 =
+ Ccons (Zero, "0", I,
+ Ccons (Suc, "S", Ar(I,I),
+ Ccons (Add, "+", Ar(I,Ar(I,I)), Cnil)))
+
+let ex1 = Ab ("x", I, Ap(Ap(V"+",V"x"),V"x"));;
+let c1 = tc NZ ctx0 ex1;;
+let ex2 = Ap (ex1, C 3);;
+let c2 = tc NZ ctx0 ex2;;
+
+let eval_checked env = function
+ | Cerror s -> failwith s
+ | Cok (e, I) -> (eval_lam env e : int)
+ | Cok _ -> failwith "Can only evaluate expressions of type I"
+;;
+
+let v2 = eval_checked env0 c2 ;;
+
+(* 5.12 Soundness *)
+
+type pexp = PEXP
+type pval = PVAL
+type _ mode =
+ | Pexp : pexp mode
+ | Pval : pval mode
+
+type ('a,'b) tarr = TARR
+type tint = TINT
+
+type (_,_) rel =
+ | IntR : (tint, int) rel
+ | IntTo : ('b, 's) rel -> ((tint, 'b) tarr, int -> 's) rel
+
+type (_,_,_) lam =
+ | Const : ('a,'b) rel * 'b -> (pval, 'env, 'a) lam
+ | Var : 'a -> (pval, ('a,'t,'e) rcons, 't) lam
+ | Shift : ('m,'e,'t) lam -> ('m, ('a,'q,'e) rcons, 't) lam
+ | Lam : 'a * ('m, ('a,'s,'e) rcons, 't) lam -> (pval, 'e, ('s,'t) tarr) lam
+ | App : ('m1, 'e, ('s,'t) tarr) lam * ('m2, 'e, 's) lam -> (pexp, 'e, 't) lam
+;;
+
+let ex1 = App (Lam (X, Var X), Const (IntR, 3))
+
+let rec mode : type m e t. (m,e,t) lam -> m mode = function
+ | Lam (v, body) -> Pval
+ | Var v -> Pval
+ | Const (r, v) -> Pval
+ | Shift e -> mode e
+ | App _ -> Pexp
+;;
+
+type (_,_) sub =
+ | Id : ('r,'r) sub
+ | Bind : 't * ('m,'r2,'x) lam * ('r,'r2) sub -> (('t,'x,'r) rcons, 'r2) sub
+ | Push : ('r1,'r2) sub -> (('a,'b,'r1) rcons, ('a,'b,'r2) rcons) sub
+
+type (_,_) lam' = Ex : ('m, 's, 't) lam -> ('s,'t) lam'
+;;
+
+let rec subst : type m1 r t s. (m1,r,t) lam -> (r,s) sub -> (s,t) lam' =
+ fun t s ->
+ match t, s with
+ | _, Id -> Ex t
+ | Const(r,c), sub -> Ex (Const (r,c))
+ | Var v, Bind (x, e, r) -> Ex e
+ | Var v, Push sub -> Ex (Var v)
+ | Shift e, Bind (_, _, r) -> subst e r
+ | Shift e, Push sub ->
+ (match subst e sub with Ex a -> Ex (Shift a))
+ | App(f,x), sub ->
+ (match subst f sub, subst x sub with Ex g, Ex y -> Ex (App (g,y)))
+ | Lam(v,x), sub ->
+ (match subst x (Push sub) with Ex body -> Ex (Lam (v, body)))
+;;
+
+type closed = rnil
+
+type 'a rlam = ((pexp,closed,'a) lam, (pval,closed,'a) lam) sum ;;
+
+let rec rule : type a b.
+ (pval, closed, (a,b) tarr) lam -> (pval, closed, a) lam -> b rlam =
+ fun v1 v2 ->
+ match v1, v2 with
+ | Lam(x,body), v ->
+ begin
+ match subst body (Bind (x, v, Id)) with Ex term ->
+ match mode term with
+ | Pexp -> Inl term
+ | Pval -> Inr term
+ end
+ | Const (IntTo b, f), Const (IntR, x) ->
+ Inr (Const (b, f x))
+;;
+let rec onestep : type m t. (m,closed,t) lam -> t rlam = function
+ | Lam (v, body) -> Inr (Lam (v, body))
+ | Const (r, v) -> Inr (Const (r, v))
+ | App (e1, e2) ->
+ match mode e1, mode e2 with
+ | Pexp, _->
+ begin match onestep e1 with
+ | Inl e -> Inl(App(e,e2))
+ | Inr v -> Inl(App(v,e2))
+ end
+ | Pval, Pexp ->
+ begin match onestep e2 with
+ | Inl e -> Inl(App(e1,e))
+ | Inr v -> Inl(App(e1,v))
+ end
+ | Pval, Pval -> rule e1 e2
+;;
diff --git a/testsuite/tests/typing-gadts/omega07.ml.principal.reference b/testsuite/tests/typing-gadts/omega07.ml.principal.reference
new file mode 100644
index 0000000000..47565e3acb
--- /dev/null
+++ b/testsuite/tests/typing-gadts/omega07.ml.principal.reference
@@ -0,0 +1,312 @@
+
+# * * * * * type ('a, 'b) sum = Inl of 'a | Inr of 'b
+type zero = Zero
+type 'a succ = Succ of 'a
+type _ nat = NZ : zero nat | NS : 'a nat -> 'a succ nat
+# type (_, _) seq =
+ Snil : ('a, zero) seq
+ | Scons : 'a * ('a, 'n) seq -> ('a, 'n succ) seq
+# val l1 : (int, zero succ succ) seq = Scons (3, Scons (5, Snil))
+# * type (_, _, _) plus =
+ PlusZ : 'a nat -> (zero, 'a, 'a) plus
+ | PlusS : ('a, 'b, 'c) plus -> ('a succ, 'b, 'c succ) plus
+# val length : ('a, 'n) seq -> 'n nat = <fun>
+# * type (_, _, _) app =
+ App : ('a, 'p) seq * ('n, 'm, 'p) plus -> ('a, 'n, 'm) app
+val app : ('a, 'n) seq -> ('a, 'm) seq -> ('a, 'n, 'm) app = <fun>
+# type tp = TP
+type nd = ND
+type ('a, 'b) fk = FK
+type _ shape =
+ Tp : tp shape
+ | Nd : nd shape
+ | Fk : 'a shape * 'b shape -> ('a, 'b) fk shape
+# type tt = TT
+type ff = FF
+type _ boolean = BT : tt boolean | BF : ff boolean
+# type (_, _) path =
+ Pnone : 'a -> (tp, 'a) path
+ | Phere : (nd, 'a) path
+ | Pleft : ('x, 'a) path -> (('x, 'y) fk, 'a) path
+ | Pright : ('y, 'a) path -> (('x, 'y) fk, 'a) path
+# type (_, _) tree =
+ Ttip : (tp, 'a) tree
+ | Tnode : 'a -> (nd, 'a) tree
+ | Tfork : ('x, 'a) tree * ('y, 'a) tree -> (('x, 'y) fk, 'a) tree
+# val tree1 : (((tp, nd) fk, (nd, nd) fk) fk, int) tree =
+ Tfork (Tfork (Ttip, Tnode 4), Tfork (Tnode 4, Tnode 3))
+# val find : ('a -> 'a -> bool) -> 'a -> ('sh, 'a) tree -> ('sh, 'a) path list =
+ <fun>
+# val extract : ('sh, 'a) path -> ('sh, 'a) tree -> 'a = <fun>
+# type (_, _) le =
+ LeZ : 'a nat -> (zero, 'a) le
+ | LeS : ('n, 'm) le -> ('n succ, 'm succ) le
+# type _ even = EvenZ : zero even | EvenSS : 'n even -> 'n succ succ even
+# type one = zero succ
+type two = one succ
+type three = two succ
+type four = three succ
+# val even0 : zero even = EvenZ
+val even2 : two even = EvenSS EvenZ
+val even4 : four even = EvenSS (EvenSS EvenZ)
+# val p1 : (two, one, three) plus = PlusS (PlusS (PlusZ (NS NZ)))
+# val summandLessThanSum : ('a, 'b, 'c) plus -> ('a, 'c) le = <fun>
+# type (_, _) equal = Eq : ('a, 'a) equal
+val convert : ('a, 'b) equal -> 'a -> 'b = <fun>
+val sameNat : 'a nat -> 'b nat -> ('a, 'b) equal option = <fun>
+# val plus_func : ('a, 'b, 'm) plus -> ('a, 'b, 'n) plus -> ('m, 'n) equal =
+ <fun>
+val plus_assoc :
+ ('a, 'b, 'ab) plus ->
+ ('ab, 'c, 'm) plus ->
+ ('b, 'c, 'bc) plus -> ('a, 'bc, 'n) plus -> ('m, 'n) equal = <fun>
+# val smaller : ('a succ, 'b succ) le -> ('a, 'b) le = <fun>
+# type (_, _) diff = Diff : 'c nat * ('a, 'c, 'b) plus -> ('a, 'b) diff
+# * * * * * * * * * val diff : ('a, 'b) le -> 'a nat -> 'b nat -> ('a, 'b) diff = <fun>
+# Characters 87-243:
+ ..match a, b,le with (* warning *)
+ | NZ, m, LeZ _ -> Diff (m, PlusZ m)
+ | NS x, NS y, LeS q ->
+ match diff q x y with Diff (m, p) -> Diff (m, PlusS p)
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(NS _, NZ, _)
+val diff : ('a, 'b) le -> 'a nat -> 'b nat -> ('a, 'b) diff = <fun>
+# val diff : ('a, 'b) le -> 'b nat -> ('a, 'b) diff = <fun>
+# type (_, _) filter = Filter : ('m, 'n) le * ('a, 'm) seq -> ('a, 'n) filter
+val leS' : ('m, 'n) le -> ('m, 'n succ) le = <fun>
+# val filter : ('a -> bool) -> ('a, 'n) seq -> ('a, 'n) filter = <fun>
+# type (_, _, _) balance =
+ Less : ('h, 'h succ, 'h succ) balance
+ | Same : ('h, 'h, 'h) balance
+ | More : ('h succ, 'h, 'h succ) balance
+type _ avl =
+ Leaf : zero avl
+ | Node : ('hL, 'hR, 'hMax) balance * 'hL avl * int *
+ 'hR avl -> 'hMax succ avl
+type avl' = Avl : 'h avl -> avl'
+# val empty : avl' = Avl Leaf
+val elem : int -> 'h avl -> bool = <fun>
+# val rotr :
+ 'n succ succ avl ->
+ int -> 'n avl -> ('n succ succ avl, 'n succ succ succ avl) sum = <fun>
+# val rotl :
+ 'n avl ->
+ int -> 'n succ succ avl -> ('n succ succ avl, 'n succ succ succ avl) sum =
+ <fun>
+# val ins : int -> 'n avl -> ('n avl, 'n succ avl) sum = <fun>
+# val insert : int -> avl' -> avl' = <fun>
+# val del_min : 'n succ avl -> int * ('n avl, 'n succ avl) sum = <fun>
+type _ avl_del =
+ Dsame : 'n avl -> 'n avl_del
+ | Ddecr : ('m succ, 'n) equal * 'm avl -> 'n avl_del
+val del : int -> 'n avl -> 'n avl_del = <fun>
+# val delete : int -> avl' -> avl' = <fun>
+# type red = RED
+type black = BLACK
+type (_, _) sub_tree =
+ Bleaf : (black, zero) sub_tree
+ | Rnode : (black, 'n) sub_tree * int *
+ (black, 'n) sub_tree -> (red, 'n) sub_tree
+ | Bnode : ('cL, 'n) sub_tree * int *
+ ('cR, 'n) sub_tree -> (black, 'n succ) sub_tree
+type rb_tree = Root : (black, 'n) sub_tree -> rb_tree
+# type dir = LeftD | RightD
+type (_, _) ctxt =
+ CNil : (black, 'n) ctxt
+ | CRed : int * dir * (black, 'n) sub_tree *
+ (red, 'n) ctxt -> (black, 'n) ctxt
+ | CBlk : int * dir * ('c1, 'n) sub_tree *
+ (black, 'n succ) ctxt -> ('c, 'n) ctxt
+# val blacken : (red, 'a) sub_tree -> (black, 'a succ) sub_tree = <fun>
+type _ crep = Red : red crep | Black : black crep
+val color : ('c, 'n) sub_tree -> 'c crep = <fun>
+# val fill : ('c, 'n) ctxt -> ('c, 'n) sub_tree -> rb_tree = <fun>
+# val recolor :
+ dir ->
+ int ->
+ ('a, 'b) sub_tree ->
+ dir ->
+ int ->
+ (black, 'b succ) sub_tree -> ('c, 'b) sub_tree -> (red, 'b succ) sub_tree =
+ <fun>
+# val rotate :
+ dir ->
+ int ->
+ (black, 'a) sub_tree ->
+ dir ->
+ int ->
+ (black, 'a) sub_tree -> (red, 'a) sub_tree -> (black, 'a succ) sub_tree =
+ <fun>
+# val repair : (red, 'n) sub_tree -> ('c, 'n) ctxt -> rb_tree = <fun>
+# val ins : int -> ('c, 'n) sub_tree -> ('c, 'n) ctxt -> rb_tree = <fun>
+# val insert : int -> rb_tree -> rb_tree = <fun>
+# type _ term =
+ Const : int -> int term
+ | Add : (int * int -> int) term
+ | LT : (int * int -> bool) term
+ | Ap : ('a -> 'b) term * 'a term -> 'b term
+ | Pair : 'a term * 'b term -> ('a * 'b) term
+val ex1 : int term = Ap (Add, Pair (Const 3, Const 5))
+val ex2 : (int * int) term =
+ Pair (Ap (Add, Pair (Const 3, Const 5)), Const 1)
+val eval_term : 'a term -> 'a = <fun>
+type _ rep =
+ Rint : int rep
+ | Rbool : bool rep
+ | Rpair : 'a rep * 'b rep -> ('a * 'b) rep
+ | Rfun : 'a rep * 'b rep -> ('a -> 'b) rep
+type (_, _) equal = Eq : ('a, 'a) equal
+val rep_equal : 'a rep -> 'b rep -> ('a, 'b) equal option = <fun>
+# type assoc = Assoc : string * 'a rep * 'a -> assoc
+val assoc : string -> 'a rep -> assoc list -> 'a = <fun>
+type _ term =
+ Var : string * 'a rep -> 'a term
+ | Abs : string * 'a rep * 'b term -> ('a -> 'b) term
+ | Const : int -> int term
+ | Add : (int * int -> int) term
+ | LT : (int * int -> bool) term
+ | Ap : ('a -> 'b) term * 'a term -> 'b term
+ | Pair : 'a term * 'b term -> ('a * 'b) term
+val eval_term : assoc list -> 'a term -> 'a = <fun>
+# val ex3 : (int -> int) term =
+ Abs ("x", Rint, Ap (Add, Pair (Var ("x", Rint), Var ("x", Rint))))
+val ex4 : int term =
+ Ap (Abs ("x", Rint, Ap (Add, Pair (Var ("x", Rint), Var ("x", Rint)))),
+ Const 3)
+val v4 : int = 6
+# type rnil = RNIL
+type ('a, 'b, 'c) rcons = RCons of 'a * 'b * 'c
+type _ is_row =
+ Rnil : rnil is_row
+ | Rcons : 'c is_row -> ('a, 'b, 'c) rcons is_row
+type (_, _) lam =
+ Const : int -> ('e, int) lam
+ | Var : 'a -> (('a, 't, 'e) rcons, 't) lam
+ | Shift : ('e, 't) lam -> (('a, 'q, 'e) rcons, 't) lam
+ | Abs : 'a * (('a, 's, 'e) rcons, 't) lam -> ('e, 's -> 't) lam
+ | App : ('e, 's -> 't) lam * ('e, 's) lam -> ('e, 't) lam
+type x = X
+type y = Y
+val ex1 : ((x, 'a -> 'b, (y, 'a, 'c) rcons) rcons, 'b) lam =
+ App (Var X, Shift (Var Y))
+val ex2 : ('a, ('b -> 'c) -> 'b -> 'c) lam =
+ Abs (<poly>, Abs (<poly>, App (Shift (Var <poly>), Var <poly>)))
+# type _ env =
+ Enil : rnil env
+ | Econs : 'a * 't * 'e env -> ('a, 't, 'e) rcons env
+val eval_lam : 'e env -> ('e, 't) lam -> 't = <fun>
+# type add = Add
+type suc = Suc
+val env0 :
+ (zero, int, (suc, int -> int, (add, int -> int -> int, rnil) rcons) rcons)
+ rcons env = Econs (Zero, 0, Econs (Suc, <fun>, Econs (Add, <fun>, Enil)))
+val _0 : ((zero, int, 'a) rcons, int) lam = Var Zero
+val suc :
+ (('a, 'b, (suc, int -> int, 'c) rcons) rcons, int) lam ->
+ (('a, 'b, (suc, int -> int, 'c) rcons) rcons, int) lam = <fun>
+val _1 :
+ ((zero, int, (suc, int -> int, (add, int -> int -> int, '_a) rcons) rcons)
+ rcons, int)
+ lam = App (Shift (Var Suc), Var Zero)
+val _2 :
+ ((zero, int, (suc, int -> int, (add, int -> int -> int, '_a) rcons) rcons)
+ rcons, int)
+ lam = App (Shift (Var Suc), App (Shift (Var Suc), Var Zero))
+val _3 :
+ ((zero, int, (suc, int -> int, (add, int -> int -> int, '_a) rcons) rcons)
+ rcons, int)
+ lam =
+ App (Shift (Var Suc),
+ App (Shift (Var Suc), App (Shift (Var Suc), Var Zero)))
+val add :
+ (('a, 'b, ('c, 'd, (add, int -> int -> int, 'e) rcons) rcons) rcons,
+ int -> int -> int)
+ lam = Shift (Shift (Var Add))
+val double :
+ (('a, 'b, ('c, 'd, (add, int -> int -> int, 'e) rcons) rcons) rcons,
+ int -> int)
+ lam =
+ Abs (<poly>,
+ App (App (Shift (Shift (Shift (Var Add))), Var <poly>), Var <poly>))
+val ex3 :
+ ((zero, int, (suc, int -> int, (add, int -> int -> int, '_a) rcons) rcons)
+ rcons, int)
+ lam =
+ App
+ (Abs (<poly>,
+ App (App (Shift (Shift (Shift (Var Add))), Var <poly>), Var <poly>)),
+ App (Shift (Var Suc),
+ App (Shift (Var Suc), App (Shift (Var Suc), Var Zero))))
+# val v3 : int = 6
+# * type _ rep = I : int rep | Ar : 'a rep * 'b rep -> ('a -> 'b) rep
+val compare : 'a rep -> 'b rep -> (string, ('a, 'b) equal) sum = <fun>
+# type term =
+ C of int
+ | Ab : string * 'a rep * term -> term
+ | Ap of term * term
+ | V of string
+type _ ctx =
+ Cnil : rnil ctx
+ | Ccons : 't * string * 'x rep * 'e ctx -> ('t, 'x, 'e) rcons ctx
+# type _ checked = Cerror of string | Cok : ('e, 't) lam * 't rep -> 'e checked
+val lookup : string -> 'e ctx -> 'e checked = <fun>
+# val tc : 'n nat -> 'e ctx -> term -> 'e checked = <fun>
+# val ctx0 :
+ (zero, int, (suc, int -> int, (add, int -> int -> int, rnil) rcons) rcons)
+ rcons ctx =
+ Ccons (Zero, "0", I,
+ Ccons (Suc, "S", Ar (I, I), Ccons (Add, "+", Ar (I, Ar (I, I)), Cnil)))
+val ex1 : term = Ab ("x", I, Ap (Ap (V "+", V "x"), V "x"))
+# val c1 :
+ (zero, int, (suc, int -> int, (add, int -> int -> int, rnil) rcons) rcons)
+ rcons checked =
+ Cok
+ (Abs (<poly>,
+ App (App (Shift (Shift (Shift (Var Add))), Var <poly>), Var <poly>)),
+ Ar (I, I))
+# val ex2 : term = Ap (Ab ("x", I, Ap (Ap (V "+", V "x"), V "x")), C 3)
+# val c2 :
+ (zero, int, (suc, int -> int, (add, int -> int -> int, rnil) rcons) rcons)
+ rcons checked =
+ Cok
+ (App
+ (Abs (<poly>,
+ App (App (Shift (Shift (Shift (Var Add))), Var <poly>), Var <poly>)),
+ Const 3),
+ I)
+# val eval_checked : 'a env -> 'a checked -> int = <fun>
+# val v2 : int = 6
+# type pexp = PEXP
+type pval = PVAL
+type _ mode = Pexp : pexp mode | Pval : pval mode
+type ('a, 'b) tarr = TARR
+type tint = TINT
+type (_, _) rel =
+ IntR : (tint, int) rel
+ | IntTo : ('b, 's) rel -> ((tint, 'b) tarr, int -> 's) rel
+type (_, _, _) lam =
+ Const : ('a, 'b) rel * 'b -> (pval, 'env, 'a) lam
+ | Var : 'a -> (pval, ('a, 't, 'e) rcons, 't) lam
+ | Shift : ('m, 'e, 't) lam -> ('m, ('a, 'q, 'e) rcons, 't) lam
+ | Lam : 'a *
+ ('m, ('a, 's, 'e) rcons, 't) lam -> (pval, 'e, ('s, 't) tarr) lam
+ | App : ('m1, 'e, ('s, 't) tarr) lam *
+ ('m2, 'e, 's) lam -> (pexp, 'e, 't) lam
+# val ex1 : (pexp, 'a, tint) lam =
+ App (Lam (<poly>, Var <poly>), Const (IntR, <poly>))
+val mode : ('m, 'e, 't) lam -> 'm mode = <fun>
+# type (_, _) sub =
+ Id : ('r, 'r) sub
+ | Bind : 't * ('m, 'r2, 'x) lam *
+ ('r, 'r2) sub -> (('t, 'x, 'r) rcons, 'r2) sub
+ | Push : ('r1, 'r2) sub -> (('a, 'b, 'r1) rcons, ('a, 'b, 'r2) rcons) sub
+type (_, _) lam' = Ex : ('m, 's, 't) lam -> ('s, 't) lam'
+# val subst : ('m1, 'r, 't) lam -> ('r, 's) sub -> ('s, 't) lam' = <fun>
+# type closed = rnil
+type 'a rlam = ((pexp, closed, 'a) lam, (pval, closed, 'a) lam) sum
+# val rule :
+ (pval, closed, ('a, 'b) tarr) lam -> (pval, closed, 'a) lam -> 'b rlam =
+ <fun>
+# val onestep : ('m, closed, 't) lam -> 't rlam = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/omega07.ml.reference b/testsuite/tests/typing-gadts/omega07.ml.reference
new file mode 100644
index 0000000000..47565e3acb
--- /dev/null
+++ b/testsuite/tests/typing-gadts/omega07.ml.reference
@@ -0,0 +1,312 @@
+
+# * * * * * type ('a, 'b) sum = Inl of 'a | Inr of 'b
+type zero = Zero
+type 'a succ = Succ of 'a
+type _ nat = NZ : zero nat | NS : 'a nat -> 'a succ nat
+# type (_, _) seq =
+ Snil : ('a, zero) seq
+ | Scons : 'a * ('a, 'n) seq -> ('a, 'n succ) seq
+# val l1 : (int, zero succ succ) seq = Scons (3, Scons (5, Snil))
+# * type (_, _, _) plus =
+ PlusZ : 'a nat -> (zero, 'a, 'a) plus
+ | PlusS : ('a, 'b, 'c) plus -> ('a succ, 'b, 'c succ) plus
+# val length : ('a, 'n) seq -> 'n nat = <fun>
+# * type (_, _, _) app =
+ App : ('a, 'p) seq * ('n, 'm, 'p) plus -> ('a, 'n, 'm) app
+val app : ('a, 'n) seq -> ('a, 'm) seq -> ('a, 'n, 'm) app = <fun>
+# type tp = TP
+type nd = ND
+type ('a, 'b) fk = FK
+type _ shape =
+ Tp : tp shape
+ | Nd : nd shape
+ | Fk : 'a shape * 'b shape -> ('a, 'b) fk shape
+# type tt = TT
+type ff = FF
+type _ boolean = BT : tt boolean | BF : ff boolean
+# type (_, _) path =
+ Pnone : 'a -> (tp, 'a) path
+ | Phere : (nd, 'a) path
+ | Pleft : ('x, 'a) path -> (('x, 'y) fk, 'a) path
+ | Pright : ('y, 'a) path -> (('x, 'y) fk, 'a) path
+# type (_, _) tree =
+ Ttip : (tp, 'a) tree
+ | Tnode : 'a -> (nd, 'a) tree
+ | Tfork : ('x, 'a) tree * ('y, 'a) tree -> (('x, 'y) fk, 'a) tree
+# val tree1 : (((tp, nd) fk, (nd, nd) fk) fk, int) tree =
+ Tfork (Tfork (Ttip, Tnode 4), Tfork (Tnode 4, Tnode 3))
+# val find : ('a -> 'a -> bool) -> 'a -> ('sh, 'a) tree -> ('sh, 'a) path list =
+ <fun>
+# val extract : ('sh, 'a) path -> ('sh, 'a) tree -> 'a = <fun>
+# type (_, _) le =
+ LeZ : 'a nat -> (zero, 'a) le
+ | LeS : ('n, 'm) le -> ('n succ, 'm succ) le
+# type _ even = EvenZ : zero even | EvenSS : 'n even -> 'n succ succ even
+# type one = zero succ
+type two = one succ
+type three = two succ
+type four = three succ
+# val even0 : zero even = EvenZ
+val even2 : two even = EvenSS EvenZ
+val even4 : four even = EvenSS (EvenSS EvenZ)
+# val p1 : (two, one, three) plus = PlusS (PlusS (PlusZ (NS NZ)))
+# val summandLessThanSum : ('a, 'b, 'c) plus -> ('a, 'c) le = <fun>
+# type (_, _) equal = Eq : ('a, 'a) equal
+val convert : ('a, 'b) equal -> 'a -> 'b = <fun>
+val sameNat : 'a nat -> 'b nat -> ('a, 'b) equal option = <fun>
+# val plus_func : ('a, 'b, 'm) plus -> ('a, 'b, 'n) plus -> ('m, 'n) equal =
+ <fun>
+val plus_assoc :
+ ('a, 'b, 'ab) plus ->
+ ('ab, 'c, 'm) plus ->
+ ('b, 'c, 'bc) plus -> ('a, 'bc, 'n) plus -> ('m, 'n) equal = <fun>
+# val smaller : ('a succ, 'b succ) le -> ('a, 'b) le = <fun>
+# type (_, _) diff = Diff : 'c nat * ('a, 'c, 'b) plus -> ('a, 'b) diff
+# * * * * * * * * * val diff : ('a, 'b) le -> 'a nat -> 'b nat -> ('a, 'b) diff = <fun>
+# Characters 87-243:
+ ..match a, b,le with (* warning *)
+ | NZ, m, LeZ _ -> Diff (m, PlusZ m)
+ | NS x, NS y, LeS q ->
+ match diff q x y with Diff (m, p) -> Diff (m, PlusS p)
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(NS _, NZ, _)
+val diff : ('a, 'b) le -> 'a nat -> 'b nat -> ('a, 'b) diff = <fun>
+# val diff : ('a, 'b) le -> 'b nat -> ('a, 'b) diff = <fun>
+# type (_, _) filter = Filter : ('m, 'n) le * ('a, 'm) seq -> ('a, 'n) filter
+val leS' : ('m, 'n) le -> ('m, 'n succ) le = <fun>
+# val filter : ('a -> bool) -> ('a, 'n) seq -> ('a, 'n) filter = <fun>
+# type (_, _, _) balance =
+ Less : ('h, 'h succ, 'h succ) balance
+ | Same : ('h, 'h, 'h) balance
+ | More : ('h succ, 'h, 'h succ) balance
+type _ avl =
+ Leaf : zero avl
+ | Node : ('hL, 'hR, 'hMax) balance * 'hL avl * int *
+ 'hR avl -> 'hMax succ avl
+type avl' = Avl : 'h avl -> avl'
+# val empty : avl' = Avl Leaf
+val elem : int -> 'h avl -> bool = <fun>
+# val rotr :
+ 'n succ succ avl ->
+ int -> 'n avl -> ('n succ succ avl, 'n succ succ succ avl) sum = <fun>
+# val rotl :
+ 'n avl ->
+ int -> 'n succ succ avl -> ('n succ succ avl, 'n succ succ succ avl) sum =
+ <fun>
+# val ins : int -> 'n avl -> ('n avl, 'n succ avl) sum = <fun>
+# val insert : int -> avl' -> avl' = <fun>
+# val del_min : 'n succ avl -> int * ('n avl, 'n succ avl) sum = <fun>
+type _ avl_del =
+ Dsame : 'n avl -> 'n avl_del
+ | Ddecr : ('m succ, 'n) equal * 'm avl -> 'n avl_del
+val del : int -> 'n avl -> 'n avl_del = <fun>
+# val delete : int -> avl' -> avl' = <fun>
+# type red = RED
+type black = BLACK
+type (_, _) sub_tree =
+ Bleaf : (black, zero) sub_tree
+ | Rnode : (black, 'n) sub_tree * int *
+ (black, 'n) sub_tree -> (red, 'n) sub_tree
+ | Bnode : ('cL, 'n) sub_tree * int *
+ ('cR, 'n) sub_tree -> (black, 'n succ) sub_tree
+type rb_tree = Root : (black, 'n) sub_tree -> rb_tree
+# type dir = LeftD | RightD
+type (_, _) ctxt =
+ CNil : (black, 'n) ctxt
+ | CRed : int * dir * (black, 'n) sub_tree *
+ (red, 'n) ctxt -> (black, 'n) ctxt
+ | CBlk : int * dir * ('c1, 'n) sub_tree *
+ (black, 'n succ) ctxt -> ('c, 'n) ctxt
+# val blacken : (red, 'a) sub_tree -> (black, 'a succ) sub_tree = <fun>
+type _ crep = Red : red crep | Black : black crep
+val color : ('c, 'n) sub_tree -> 'c crep = <fun>
+# val fill : ('c, 'n) ctxt -> ('c, 'n) sub_tree -> rb_tree = <fun>
+# val recolor :
+ dir ->
+ int ->
+ ('a, 'b) sub_tree ->
+ dir ->
+ int ->
+ (black, 'b succ) sub_tree -> ('c, 'b) sub_tree -> (red, 'b succ) sub_tree =
+ <fun>
+# val rotate :
+ dir ->
+ int ->
+ (black, 'a) sub_tree ->
+ dir ->
+ int ->
+ (black, 'a) sub_tree -> (red, 'a) sub_tree -> (black, 'a succ) sub_tree =
+ <fun>
+# val repair : (red, 'n) sub_tree -> ('c, 'n) ctxt -> rb_tree = <fun>
+# val ins : int -> ('c, 'n) sub_tree -> ('c, 'n) ctxt -> rb_tree = <fun>
+# val insert : int -> rb_tree -> rb_tree = <fun>
+# type _ term =
+ Const : int -> int term
+ | Add : (int * int -> int) term
+ | LT : (int * int -> bool) term
+ | Ap : ('a -> 'b) term * 'a term -> 'b term
+ | Pair : 'a term * 'b term -> ('a * 'b) term
+val ex1 : int term = Ap (Add, Pair (Const 3, Const 5))
+val ex2 : (int * int) term =
+ Pair (Ap (Add, Pair (Const 3, Const 5)), Const 1)
+val eval_term : 'a term -> 'a = <fun>
+type _ rep =
+ Rint : int rep
+ | Rbool : bool rep
+ | Rpair : 'a rep * 'b rep -> ('a * 'b) rep
+ | Rfun : 'a rep * 'b rep -> ('a -> 'b) rep
+type (_, _) equal = Eq : ('a, 'a) equal
+val rep_equal : 'a rep -> 'b rep -> ('a, 'b) equal option = <fun>
+# type assoc = Assoc : string * 'a rep * 'a -> assoc
+val assoc : string -> 'a rep -> assoc list -> 'a = <fun>
+type _ term =
+ Var : string * 'a rep -> 'a term
+ | Abs : string * 'a rep * 'b term -> ('a -> 'b) term
+ | Const : int -> int term
+ | Add : (int * int -> int) term
+ | LT : (int * int -> bool) term
+ | Ap : ('a -> 'b) term * 'a term -> 'b term
+ | Pair : 'a term * 'b term -> ('a * 'b) term
+val eval_term : assoc list -> 'a term -> 'a = <fun>
+# val ex3 : (int -> int) term =
+ Abs ("x", Rint, Ap (Add, Pair (Var ("x", Rint), Var ("x", Rint))))
+val ex4 : int term =
+ Ap (Abs ("x", Rint, Ap (Add, Pair (Var ("x", Rint), Var ("x", Rint)))),
+ Const 3)
+val v4 : int = 6
+# type rnil = RNIL
+type ('a, 'b, 'c) rcons = RCons of 'a * 'b * 'c
+type _ is_row =
+ Rnil : rnil is_row
+ | Rcons : 'c is_row -> ('a, 'b, 'c) rcons is_row
+type (_, _) lam =
+ Const : int -> ('e, int) lam
+ | Var : 'a -> (('a, 't, 'e) rcons, 't) lam
+ | Shift : ('e, 't) lam -> (('a, 'q, 'e) rcons, 't) lam
+ | Abs : 'a * (('a, 's, 'e) rcons, 't) lam -> ('e, 's -> 't) lam
+ | App : ('e, 's -> 't) lam * ('e, 's) lam -> ('e, 't) lam
+type x = X
+type y = Y
+val ex1 : ((x, 'a -> 'b, (y, 'a, 'c) rcons) rcons, 'b) lam =
+ App (Var X, Shift (Var Y))
+val ex2 : ('a, ('b -> 'c) -> 'b -> 'c) lam =
+ Abs (<poly>, Abs (<poly>, App (Shift (Var <poly>), Var <poly>)))
+# type _ env =
+ Enil : rnil env
+ | Econs : 'a * 't * 'e env -> ('a, 't, 'e) rcons env
+val eval_lam : 'e env -> ('e, 't) lam -> 't = <fun>
+# type add = Add
+type suc = Suc
+val env0 :
+ (zero, int, (suc, int -> int, (add, int -> int -> int, rnil) rcons) rcons)
+ rcons env = Econs (Zero, 0, Econs (Suc, <fun>, Econs (Add, <fun>, Enil)))
+val _0 : ((zero, int, 'a) rcons, int) lam = Var Zero
+val suc :
+ (('a, 'b, (suc, int -> int, 'c) rcons) rcons, int) lam ->
+ (('a, 'b, (suc, int -> int, 'c) rcons) rcons, int) lam = <fun>
+val _1 :
+ ((zero, int, (suc, int -> int, (add, int -> int -> int, '_a) rcons) rcons)
+ rcons, int)
+ lam = App (Shift (Var Suc), Var Zero)
+val _2 :
+ ((zero, int, (suc, int -> int, (add, int -> int -> int, '_a) rcons) rcons)
+ rcons, int)
+ lam = App (Shift (Var Suc), App (Shift (Var Suc), Var Zero))
+val _3 :
+ ((zero, int, (suc, int -> int, (add, int -> int -> int, '_a) rcons) rcons)
+ rcons, int)
+ lam =
+ App (Shift (Var Suc),
+ App (Shift (Var Suc), App (Shift (Var Suc), Var Zero)))
+val add :
+ (('a, 'b, ('c, 'd, (add, int -> int -> int, 'e) rcons) rcons) rcons,
+ int -> int -> int)
+ lam = Shift (Shift (Var Add))
+val double :
+ (('a, 'b, ('c, 'd, (add, int -> int -> int, 'e) rcons) rcons) rcons,
+ int -> int)
+ lam =
+ Abs (<poly>,
+ App (App (Shift (Shift (Shift (Var Add))), Var <poly>), Var <poly>))
+val ex3 :
+ ((zero, int, (suc, int -> int, (add, int -> int -> int, '_a) rcons) rcons)
+ rcons, int)
+ lam =
+ App
+ (Abs (<poly>,
+ App (App (Shift (Shift (Shift (Var Add))), Var <poly>), Var <poly>)),
+ App (Shift (Var Suc),
+ App (Shift (Var Suc), App (Shift (Var Suc), Var Zero))))
+# val v3 : int = 6
+# * type _ rep = I : int rep | Ar : 'a rep * 'b rep -> ('a -> 'b) rep
+val compare : 'a rep -> 'b rep -> (string, ('a, 'b) equal) sum = <fun>
+# type term =
+ C of int
+ | Ab : string * 'a rep * term -> term
+ | Ap of term * term
+ | V of string
+type _ ctx =
+ Cnil : rnil ctx
+ | Ccons : 't * string * 'x rep * 'e ctx -> ('t, 'x, 'e) rcons ctx
+# type _ checked = Cerror of string | Cok : ('e, 't) lam * 't rep -> 'e checked
+val lookup : string -> 'e ctx -> 'e checked = <fun>
+# val tc : 'n nat -> 'e ctx -> term -> 'e checked = <fun>
+# val ctx0 :
+ (zero, int, (suc, int -> int, (add, int -> int -> int, rnil) rcons) rcons)
+ rcons ctx =
+ Ccons (Zero, "0", I,
+ Ccons (Suc, "S", Ar (I, I), Ccons (Add, "+", Ar (I, Ar (I, I)), Cnil)))
+val ex1 : term = Ab ("x", I, Ap (Ap (V "+", V "x"), V "x"))
+# val c1 :
+ (zero, int, (suc, int -> int, (add, int -> int -> int, rnil) rcons) rcons)
+ rcons checked =
+ Cok
+ (Abs (<poly>,
+ App (App (Shift (Shift (Shift (Var Add))), Var <poly>), Var <poly>)),
+ Ar (I, I))
+# val ex2 : term = Ap (Ab ("x", I, Ap (Ap (V "+", V "x"), V "x")), C 3)
+# val c2 :
+ (zero, int, (suc, int -> int, (add, int -> int -> int, rnil) rcons) rcons)
+ rcons checked =
+ Cok
+ (App
+ (Abs (<poly>,
+ App (App (Shift (Shift (Shift (Var Add))), Var <poly>), Var <poly>)),
+ Const 3),
+ I)
+# val eval_checked : 'a env -> 'a checked -> int = <fun>
+# val v2 : int = 6
+# type pexp = PEXP
+type pval = PVAL
+type _ mode = Pexp : pexp mode | Pval : pval mode
+type ('a, 'b) tarr = TARR
+type tint = TINT
+type (_, _) rel =
+ IntR : (tint, int) rel
+ | IntTo : ('b, 's) rel -> ((tint, 'b) tarr, int -> 's) rel
+type (_, _, _) lam =
+ Const : ('a, 'b) rel * 'b -> (pval, 'env, 'a) lam
+ | Var : 'a -> (pval, ('a, 't, 'e) rcons, 't) lam
+ | Shift : ('m, 'e, 't) lam -> ('m, ('a, 'q, 'e) rcons, 't) lam
+ | Lam : 'a *
+ ('m, ('a, 's, 'e) rcons, 't) lam -> (pval, 'e, ('s, 't) tarr) lam
+ | App : ('m1, 'e, ('s, 't) tarr) lam *
+ ('m2, 'e, 's) lam -> (pexp, 'e, 't) lam
+# val ex1 : (pexp, 'a, tint) lam =
+ App (Lam (<poly>, Var <poly>), Const (IntR, <poly>))
+val mode : ('m, 'e, 't) lam -> 'm mode = <fun>
+# type (_, _) sub =
+ Id : ('r, 'r) sub
+ | Bind : 't * ('m, 'r2, 'x) lam *
+ ('r, 'r2) sub -> (('t, 'x, 'r) rcons, 'r2) sub
+ | Push : ('r1, 'r2) sub -> (('a, 'b, 'r1) rcons, ('a, 'b, 'r2) rcons) sub
+type (_, _) lam' = Ex : ('m, 's, 't) lam -> ('s, 't) lam'
+# val subst : ('m1, 'r, 't) lam -> ('r, 's) sub -> ('s, 't) lam' = <fun>
+# type closed = rnil
+type 'a rlam = ((pexp, closed, 'a) lam, (pval, closed, 'a) lam) sum
+# val rule :
+ (pval, closed, ('a, 'b) tarr) lam -> (pval, closed, 'a) lam -> 'b rlam =
+ <fun>
+# val onestep : ('m, closed, 't) lam -> 't rlam = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/pr5332.ml b/testsuite/tests/typing-gadts/pr5332.ml
new file mode 100644
index 0000000000..ef70e5a1a1
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5332.ml
@@ -0,0 +1,17 @@
+type ('env, 'a) var =
+ | Zero : ('a * 'env, 'a) var
+ | Succ : ('env, 'a) var -> ('b * 'env, 'a) var
+;;
+type ('env, 'a) typ =
+ | Tint : ('env, int) typ
+ | Tbool : ('env, bool) typ
+ | Tvar : ('env, 'a) var -> ('env, 'a) typ
+;;
+let f : type env a. (env, a) typ -> (env, a) typ -> int = fun ta tb ->
+ match ta, tb with
+ | Tint, Tint -> 0
+ | Tbool, Tbool -> 1
+ | Tvar var, tb -> 2
+;;
+let x = f Tint (Tvar Zero)
+;;
diff --git a/testsuite/tests/typing-gadts/pr5332.ml.reference b/testsuite/tests/typing-gadts/pr5332.ml.reference
new file mode 100644
index 0000000000..4cf48a22c9
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5332.ml.reference
@@ -0,0 +1,19 @@
+
+# type ('env, 'a) var =
+ Zero : ('a * 'env, 'a) var
+ | Succ : ('env, 'a) var -> ('b * 'env, 'a) var
+# type ('env, 'a) typ =
+ Tint : ('env, int) typ
+ | Tbool : ('env, bool) typ
+ | Tvar : ('env, 'a) var -> ('env, 'a) typ
+# Characters 72-156:
+ .match ta, tb with
+ | Tint, Tint -> 0
+ | Tbool, Tbool -> 1
+ | Tvar var, tb -> 2
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(Tbool, Tvar _)
+val f : ('env, 'a) typ -> ('env, 'a) typ -> int = <fun>
+# Exception: Match_failure ("//toplevel//", 9, 1).
+#
diff --git a/testsuite/tests/typing-gadts/pr5689.ml b/testsuite/tests/typing-gadts/pr5689.ml
new file mode 100644
index 0000000000..856ddc2738
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5689.ml
@@ -0,0 +1,74 @@
+type inkind = [ `Link | `Nonlink ]
+
+type _ inline_t =
+ | Text: string -> [< inkind > `Nonlink ] inline_t
+ | Bold: 'a inline_t list -> 'a inline_t
+ | Link: string -> [< inkind > `Link ] inline_t
+ | Mref: string * [ `Nonlink ] inline_t list -> [< inkind > `Link ] inline_t
+;;
+
+let uppercase seq =
+ let rec process: type a. a inline_t -> a inline_t = function
+ | Text txt -> Text (String.uppercase_ascii txt)
+ | Bold xs -> Bold (List.map process xs)
+ | Link lnk -> Link lnk
+ | Mref (lnk, xs) -> Mref (lnk, List.map process xs)
+ in List.map process seq
+;;
+
+type ast_t =
+ | Ast_Text of string
+ | Ast_Bold of ast_t list
+ | Ast_Link of string
+ | Ast_Mref of string * ast_t list
+;;
+
+let inlineseq_from_astseq seq =
+ let rec process_nonlink = function
+ | Ast_Text txt -> Text txt
+ | Ast_Bold xs -> Bold (List.map process_nonlink xs)
+ | _ -> assert false in
+ let rec process_any = function
+ | Ast_Text txt -> Text txt
+ | Ast_Bold xs -> Bold (List.map process_any xs)
+ | Ast_Link lnk -> Link lnk
+ | Ast_Mref (lnk, xs) -> Mref (lnk, List.map process_nonlink xs)
+ in List.map process_any seq
+;;
+
+(* OK *)
+type _ linkp =
+ | Nonlink : [ `Nonlink ] linkp
+ | Maylink : inkind linkp
+;;
+let inlineseq_from_astseq seq =
+ let rec process : type a. a linkp -> ast_t -> a inline_t =
+ fun allow_link ast ->
+ match (allow_link, ast) with
+ | (Maylink, Ast_Text txt) -> Text txt
+ | (Nonlink, Ast_Text txt) -> Text txt
+ | (x, Ast_Bold xs) -> Bold (List.map (process x) xs)
+ | (Maylink, Ast_Link lnk) -> Link lnk
+ | (Nonlink, Ast_Link _) -> assert false
+ | (Maylink, Ast_Mref (lnk, xs)) ->
+ Mref (lnk, List.map (process Nonlink) xs)
+ | (Nonlink, Ast_Mref _) -> assert false
+ in List.map (process Maylink) seq
+;;
+
+(* Bad *)
+type _ linkp2 = Kind : 'a linkp -> ([< inkind ] as 'a) linkp2
+;;
+let inlineseq_from_astseq seq =
+let rec process : type a. a linkp2 -> ast_t -> a inline_t =
+ fun allow_link ast ->
+ match (allow_link, ast) with
+ | (Kind _, Ast_Text txt) -> Text txt
+ | (x, Ast_Bold xs) -> Bold (List.map (process x) xs)
+ | (Kind Maylink, Ast_Link lnk) -> Link lnk
+ | (Kind Nonlink, Ast_Link _) -> assert false
+ | (Kind Maylink, Ast_Mref (lnk, xs)) ->
+ Mref (lnk, List.map (process (Kind Nonlink)) xs)
+ | (Kind Nonlink, Ast_Mref _) -> assert false
+ in List.map (process (Kind Maylink)) seq
+;;
diff --git a/testsuite/tests/typing-gadts/pr5689.ml.principal.reference b/testsuite/tests/typing-gadts/pr5689.ml.principal.reference
new file mode 100644
index 0000000000..fabdb17cdc
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5689.ml.principal.reference
@@ -0,0 +1,27 @@
+
+# type inkind = [ `Link | `Nonlink ]
+type _ inline_t =
+ Text : string -> [< inkind > `Nonlink ] inline_t
+ | Bold : 'a inline_t list -> 'a inline_t
+ | Link : string -> [< inkind > `Link ] inline_t
+ | Mref : string *
+ [ `Nonlink ] inline_t list -> [< inkind > `Link ] inline_t
+# val uppercase : 'a inline_t list -> 'a inline_t list = <fun>
+# type ast_t =
+ Ast_Text of string
+ | Ast_Bold of ast_t list
+ | Ast_Link of string
+ | Ast_Mref of string * ast_t list
+# val inlineseq_from_astseq : ast_t list -> inkind inline_t list = <fun>
+# type _ linkp = Nonlink : [ `Nonlink ] linkp | Maylink : inkind linkp
+# val inlineseq_from_astseq : ast_t list -> inkind inline_t list = <fun>
+# type _ linkp2 = Kind : 'a linkp -> ([< inkind ] as 'a) linkp2
+# Characters 184-192:
+ | (Kind _, Ast_Text txt) -> Text txt
+ ^^^^^^^^
+Error: This expression has type ([< inkind > `Nonlink ] as 'a) inline_t
+ but an expression was expected of type a inline_t
+ Type 'a = [< `Link | `Nonlink > `Nonlink ] is not compatible with type
+ a = [< `Link | `Nonlink ]
+ Types for tag `Nonlink are incompatible
+#
diff --git a/testsuite/tests/typing-gadts/pr5689.ml.reference b/testsuite/tests/typing-gadts/pr5689.ml.reference
new file mode 100644
index 0000000000..fabdb17cdc
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5689.ml.reference
@@ -0,0 +1,27 @@
+
+# type inkind = [ `Link | `Nonlink ]
+type _ inline_t =
+ Text : string -> [< inkind > `Nonlink ] inline_t
+ | Bold : 'a inline_t list -> 'a inline_t
+ | Link : string -> [< inkind > `Link ] inline_t
+ | Mref : string *
+ [ `Nonlink ] inline_t list -> [< inkind > `Link ] inline_t
+# val uppercase : 'a inline_t list -> 'a inline_t list = <fun>
+# type ast_t =
+ Ast_Text of string
+ | Ast_Bold of ast_t list
+ | Ast_Link of string
+ | Ast_Mref of string * ast_t list
+# val inlineseq_from_astseq : ast_t list -> inkind inline_t list = <fun>
+# type _ linkp = Nonlink : [ `Nonlink ] linkp | Maylink : inkind linkp
+# val inlineseq_from_astseq : ast_t list -> inkind inline_t list = <fun>
+# type _ linkp2 = Kind : 'a linkp -> ([< inkind ] as 'a) linkp2
+# Characters 184-192:
+ | (Kind _, Ast_Text txt) -> Text txt
+ ^^^^^^^^
+Error: This expression has type ([< inkind > `Nonlink ] as 'a) inline_t
+ but an expression was expected of type a inline_t
+ Type 'a = [< `Link | `Nonlink > `Nonlink ] is not compatible with type
+ a = [< `Link | `Nonlink ]
+ Types for tag `Nonlink are incompatible
+#
diff --git a/testsuite/tests/typing-gadts/pr5785.ml b/testsuite/tests/typing-gadts/pr5785.ml
new file mode 100644
index 0000000000..fdfa7ebfc8
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5785.ml
@@ -0,0 +1,10 @@
+module Add (T : sig type two end) =
+struct
+ type _ t =
+ | One : [`One] t
+ | Two : T.two t
+
+ let add (type a) : a t * a t -> string = function
+ | One, One -> "two"
+ | Two, Two -> "four"
+end;;
diff --git a/testsuite/tests/typing-gadts/pr5785.ml.reference b/testsuite/tests/typing-gadts/pr5785.ml.reference
new file mode 100644
index 0000000000..0a1fb77476
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5785.ml.reference
@@ -0,0 +1,15 @@
+
+# Characters 137-194:
+ ...........................................function
+ | One, One -> "two"
+ | Two, Two -> "four"
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(Two, One)
+module Add :
+ functor (T : sig type two end) ->
+ sig
+ type _ t = One : [ `One ] t | Two : T.two t
+ val add : 'a t * 'a t -> string
+ end
+#
diff --git a/testsuite/tests/typing-gadts/pr5848.ml b/testsuite/tests/typing-gadts/pr5848.ml
new file mode 100644
index 0000000000..c07e30c9a0
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5848.ml
@@ -0,0 +1,14 @@
+module B : sig
+ type (_, _) t = Eq: ('a, 'a) t
+ val f: 'a -> 'b -> ('a, 'b) t
+end
+=
+struct
+ type (_, _) t = Eq: ('a, 'a) t
+ let f t1 t2 = Obj.magic Eq
+end;;
+
+let of_type: type a. a -> a = fun x ->
+ match B.f x 4 with
+ | Eq -> 5
+;;
diff --git a/testsuite/tests/typing-gadts/pr5848.ml.reference b/testsuite/tests/typing-gadts/pr5848.ml.reference
new file mode 100644
index 0000000000..577a6dc4a5
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5848.ml.reference
@@ -0,0 +1,8 @@
+
+# module B :
+ sig type (_, _) t = Eq : ('a, 'a) t val f : 'a -> 'b -> ('a, 'b) t end
+# Characters 65-67:
+ | Eq -> 5
+ ^^
+Error: The GADT constructor Eq of type B.t must be qualified in this pattern.
+#
diff --git a/testsuite/tests/typing-gadts/pr5906.ml b/testsuite/tests/typing-gadts/pr5906.ml
new file mode 100644
index 0000000000..f0b2f0b07d
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5906.ml
@@ -0,0 +1,18 @@
+type _ constant =
+ | Int: int -> int constant
+ | Bool: bool -> bool constant
+
+type (_, _, _) binop =
+ | Eq: ('a, 'a, bool) binop
+ | Leq: ('a, 'a, bool) binop
+ | Add: (int, int, int) binop
+
+let eval (type a) (type b) (type c) (bop:(a,b,c) binop) (x:a constant)
+ (y:b constant) : c constant =
+ match bop, x, y with
+ | Eq, Bool x, Bool y -> Bool (if x then y else not y)
+ | Leq, Int x, Int y -> Bool (x <= y)
+ | Leq, Bool x, Bool y -> Bool (x <= y)
+ | Add, Int x, Int y -> Int (x + y)
+
+let _ = eval Eq (Int 2) (Int 3)
diff --git a/testsuite/tests/typing-gadts/pr5906.ml.reference b/testsuite/tests/typing-gadts/pr5906.ml.reference
new file mode 100644
index 0000000000..28a103c72c
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5906.ml.reference
@@ -0,0 +1,5 @@
+
+#
+Characters 533-533:
+ Error: Syntax error
+#
diff --git a/testsuite/tests/typing-gadts/pr5948.ml b/testsuite/tests/typing-gadts/pr5948.ml
new file mode 100644
index 0000000000..0acc90868b
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5948.ml
@@ -0,0 +1,30 @@
+type tag = [`TagA | `TagB | `TagC];;
+
+type 'a poly =
+ AandBTags : [< `TagA of int | `TagB ] poly
+ | ATag : [< `TagA of int] poly
+(* constraint 'a = [< `TagA of int | `TagB] *)
+;;
+
+let intA = function `TagA i -> i
+let intB = function `TagB -> 4
+;;
+
+let intAorB = function
+ `TagA i -> i
+ | `TagB -> 4
+;;
+
+type _ wrapPoly =
+ WrapPoly : 'a poly -> ([< `TagA of int | `TagB] as 'a) wrapPoly
+;;
+
+let example6 : type a. a wrapPoly -> (a -> int) =
+ fun w ->
+ match w with
+ | WrapPoly ATag -> intA
+ | WrapPoly _ -> intA (* This should not be allowed *)
+;;
+
+let _ = example6 (WrapPoly AandBTags) `TagB (* This causes a seg fault *)
+;;
diff --git a/testsuite/tests/typing-gadts/pr5948.ml.reference b/testsuite/tests/typing-gadts/pr5948.ml.reference
new file mode 100644
index 0000000000..7d77421206
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5948.ml.reference
@@ -0,0 +1,22 @@
+
+# type tag = [ `TagA | `TagB | `TagC ]
+# type 'a poly =
+ AandBTags : [< `TagA of int | `TagB ] poly
+ | ATag : [< `TagA of int ] poly
+# val intA : [< `TagA of 'a ] -> 'a = <fun>
+val intB : [< `TagB ] -> int = <fun>
+# val intAorB : [< `TagA of int | `TagB ] -> int = <fun>
+# type _ wrapPoly =
+ WrapPoly : 'a poly -> ([< `TagA of int | `TagB ] as 'a) wrapPoly
+# Characters 103-107:
+ | WrapPoly ATag -> intA
+ ^^^^
+Error: This expression has type ([< `TagA of 'b ] as 'a) -> 'b
+ but an expression was expected of type a -> int
+ Type 'a is not compatible with type a = [< `TagA of int | `TagB ]
+ The first variant type does not allow tag(s) `TagB
+# Characters 10-18:
+ let _ = example6 (WrapPoly AandBTags) `TagB (* This causes a seg fault *)
+ ^^^^^^^^
+Error: Unbound value example6
+#
diff --git a/testsuite/tests/typing-gadts/pr5981.ml b/testsuite/tests/typing-gadts/pr5981.ml
new file mode 100644
index 0000000000..f93b4e36f5
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5981.ml
@@ -0,0 +1,22 @@
+module F(S : sig type 'a t end) = struct
+ type _ ab =
+ A : int S.t ab
+ | B : float S.t ab
+
+ let f : int S.t ab -> float S.t ab -> string =
+ fun (l : int S.t ab) (r : float S.t ab) -> match l, r with
+ | A, B -> "f A B"
+end;;
+
+module F(S : sig type 'a t end) = struct
+ type a = int * int
+ type b = int -> int
+
+ type _ ab =
+ A : a S.t ab
+ | B : b S.t ab
+
+ let f : a S.t ab -> b S.t ab -> string =
+ fun l r -> match l, r with
+ | A, B -> "f A B"
+end;;
diff --git a/testsuite/tests/typing-gadts/pr5981.ml.reference b/testsuite/tests/typing-gadts/pr5981.ml.reference
new file mode 100644
index 0000000000..3a2d7b1625
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5981.ml.reference
@@ -0,0 +1,28 @@
+
+# Characters 196-233:
+ ...............................................match l, r with
+ | A, B -> "f A B"
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(A, A)
+module F :
+ functor (S : sig type 'a t end) ->
+ sig
+ type _ ab = A : int S.t ab | B : float S.t ab
+ val f : int S.t ab -> float S.t ab -> string
+ end
+# Characters 197-234:
+ ...............match l, r with
+ | A, B -> "f A B"
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(A, A)
+module F :
+ functor (S : sig type 'a t end) ->
+ sig
+ type a = int * int
+ type b = int -> int
+ type _ ab = A : a S.t ab | B : b S.t ab
+ val f : a S.t ab -> b S.t ab -> string
+ end
+#
diff --git a/testsuite/tests/typing-gadts/pr5985.ml b/testsuite/tests/typing-gadts/pr5985.ml
new file mode 100644
index 0000000000..23902add37
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5985.ml
@@ -0,0 +1,102 @@
+(* Report from Jeremy Yallop *)
+module F (S : sig type 'a s end) = struct
+ include S
+ type _ t = T : 'a -> 'a s t
+end;; (* fail *)
+(*
+module M = F (struct type 'a s = int end) ;;
+let M.T x = M.T 3 in x = true;;
+*)
+
+(* Fix it using #-annotations *)
+module F (S : sig type #'a s end) = struct
+ include S
+ type _ t = T : 'a -> 'a s t
+end;; (* syntax error *)
+(*
+module M = F (struct type 'a s = int end) ;; (* fail *)
+module M = F (struct type 'a s = new int end) ;; (* ok *)
+let M.T x = M.T 3 in x = true;; (* fail *)
+let M.T x = M.T 3 in x = 3;; (* ok *)
+*)
+
+(* Another version using OCaml 2.00 objects *)
+module F(T:sig type 'a t end) = struct
+ class ['a] c x =
+ object constraint 'a = 'b T.t val x' : 'b = x method x = x' end
+end;; (* fail *)
+
+(* Another (more direct) instance using polymorphic variants *)
+(* PR#6275 *)
+type 'x t = A of 'a constraint 'x = [< `X of 'a ] ;; (* fail *)
+let magic (x : int) : bool =
+ let A x = A x in
+ x;; (* fail *)
+type 'a t = A : 'a -> [< `X of 'a ] t;; (* fail *)
+
+(* It is not OK to allow modules exported by other compilation units *)
+type (_,_) eq = Eq : ('a,'a) eq;;
+let eq = Obj.magic Eq;;
+(* pretend that Queue.t is not injective *)
+let eq : ('a Queue.t, 'b Queue.t) eq = eq;;
+type _ t = T : 'a -> 'a Queue.t t;; (* fail *)
+(*
+let castT (type a) (type b) (x : a t) (e: (a, b) eq) : b t =
+ let Eq = e in (x : b t);;
+let T (x : bool) = castT (T 3) eq;; (* we found a contradiction *)
+*)
+
+(* The following signature should not be accepted *)
+module type S = sig
+ type 'a s
+ type _ t = T : 'a -> 'a s t
+end;; (* fail *)
+(* Otherwise we can write the following *)
+module rec M : (S with type 'a s = unit) = M;;
+(* For the above reason, we cannot allow the abstract declaration
+ of s and the definition of t to be in the same module, as
+ we could create the signature using [module type of ...] *)
+
+
+(* Another problem with variance *)
+module M = struct type 'a t = 'a -> unit end;;
+module F(X:sig type #'a t end) =
+ struct type +'a s = S of 'b constraint 'a = 'b X.t end;; (* fail *)
+(*
+module N = F(M);;
+let o = N.S (object end);;
+let N.S o' = (o :> <m : int> M.t N.s);; (* unsound! *)
+*)
+
+(* And yet another *)
+type 'a q = Q;;
+type +'a t = 'b constraint 'a = 'b q;;
+(* shoud fail: we do not know for sure the variance of Queue.t *)
+
+type +'a t = T of 'a;;
+type +'a s = 'b constraint 'a = 'b t;; (* ok *)
+type -'a s = 'b constraint 'a = 'b t;; (* fail *)
+type +'a u = 'a t;;
+type 'a t = T of ('a -> 'a);;
+type -'a s = 'b constraint 'a = 'b t;; (* ok *)
+type +'a s = 'b constraint 'a = 'b q t;; (* ok *)
+type +'a s = 'b constraint 'a = 'b t q;; (* fail *)
+
+
+(* the problem from lablgtk2 *)
+
+module Gobject = struct
+ type -'a obj
+end
+open Gobject;;
+
+class virtual ['a] item_container =
+ object
+ constraint 'a = < as_item : [>`widget] obj; .. >
+ method virtual add : 'a -> unit
+ end;;
+
+
+(* Another variance anomaly, should not expand t in g before checking *)
+type +'a t = unit constraint 'a = 'b list;;
+type _ g = G : 'a -> 'a t g;; (* fail *)
diff --git a/testsuite/tests/typing-gadts/pr5985.ml.reference b/testsuite/tests/typing-gadts/pr5985.ml.reference
new file mode 100644
index 0000000000..4c29f6dae2
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5985.ml.reference
@@ -0,0 +1,89 @@
+
+# Characters 88-115:
+ type _ t = T : 'a -> 'a s t
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable cannot be deduced
+ from the type parameters.
+# * * * Characters 140-141:
+ module F (S : sig type #'a s end) = struct
+ ^
+Error: Syntax error
+# * * * * * Characters 290-374:
+ ..class ['a] c x =
+ object constraint 'a = 'b T.t val x' : 'b = x method x = x' end
+Error: In this definition, a type variable cannot be deduced
+ from the type parameters.
+# Characters 79-128:
+ type 'x t = A of 'a constraint 'x = [< `X of 'a ] ;; (* fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable cannot be deduced
+ from the type parameters.
+# Characters 36-37:
+ let A x = A x in
+ ^
+Error: Unbound constructor A
+# Characters 0-37:
+ type 'a t = A : 'a -> [< `X of 'a ] t;; (* fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable cannot be deduced
+ from the type parameters.
+# type (_, _) eq = Eq : ('a, 'a) eq
+# val eq : 'a = <poly>
+# val eq : ('a Queue.t, 'b Queue.t) eq = Eq
+# Characters 0-33:
+ type _ t = T : 'a -> 'a Queue.t t;; (* fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable cannot be deduced
+ from the type parameters.
+# * * * * Characters 250-277:
+ type _ t = T : 'a -> 'a s t
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable cannot be deduced
+ from the type parameters.
+# Characters 59-60:
+ module rec M : (S with type 'a s = unit) = M;;
+ ^
+Error: Unbound module type S
+# * * module M : sig type 'a t = 'a -> unit end
+# Characters 20-21:
+ module F(X:sig type #'a t end) =
+ ^
+Error: Syntax error
+# * * * * type 'a q = Q
+# Characters 0-36:
+ type +'a t = 'b constraint 'a = 'b q;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable has a variance that
+ cannot be deduced from the type parameters.
+ It was expected to be unrestricted, but it is covariant.
+# type 'a t = T of 'a
+# type +'a s = 'b constraint 'a = 'b t
+# Characters 0-36:
+ type -'a s = 'b constraint 'a = 'b t;; (* fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable has a variance that
+ is not reflected by its occurrence in type parameters.
+ It was expected to be contravariant, but it is covariant.
+# type 'a u = 'a t
+# type 'a t = T of ('a -> 'a)
+# type -'a s = 'b constraint 'a = 'b t
+# type +'a s = 'b constraint 'a = 'b q t
+# Characters 0-38:
+ type +'a s = 'b constraint 'a = 'b t q;; (* fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable has a variance that
+ cannot be deduced from the type parameters.
+ It was expected to be unrestricted, but it is covariant.
+# module Gobject : sig type -'a obj end
+# class virtual ['a] item_container :
+ object
+ constraint 'a = < as_item : [> `widget ] Gobject.obj; .. >
+ method virtual add : 'a -> unit
+ end
+# type +'a t = unit constraint 'a = 'b list
+# Characters 0-27:
+ type _ g = G : 'a -> 'a t g;; (* fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, a type variable cannot be deduced
+ from the type parameters.
+#
diff --git a/testsuite/tests/typing-gadts/pr5989.ml b/testsuite/tests/typing-gadts/pr5989.ml
new file mode 100644
index 0000000000..392df7f2d6
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5989.ml
@@ -0,0 +1,35 @@
+type (_, _) t =
+ Any : ('a, 'b) t
+ | Eq : ('a, 'a) t
+;;
+
+module M :
+sig
+ type s = private [> `A]
+ val eq : (s, [`A | `B]) t
+end =
+struct
+ type s = [`A | `B]
+ let eq = Eq
+end;;
+
+let f : (M.s, [`A | `B]) t -> string = function
+ | Any -> "Any"
+;;
+
+let () = print_endline (f M.eq) ;;
+
+module N :
+sig
+ type s = private < a : int; .. >
+ val eq : (s, <a : int; b : bool>) t
+end =
+struct
+ type s = <a : int; b : bool>
+ let eq = Eq
+end
+;;
+
+let f : (N.s, <a : int; b : bool>) t -> string = function
+ | Any -> "Any"
+;;
diff --git a/testsuite/tests/typing-gadts/pr5989.ml.reference b/testsuite/tests/typing-gadts/pr5989.ml.reference
new file mode 100644
index 0000000000..f881c9b823
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5989.ml.reference
@@ -0,0 +1,24 @@
+
+# type (_, _) t = Any : ('a, 'b) t | Eq : ('a, 'a) t
+# module M : sig type s = private [> `A ] val eq : (s, [ `A | `B ]) t end
+# Characters 40-65:
+ .......................................function
+ | Any -> "Any"
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Eq
+val f : (M.s, [ `A | `B ]) t -> string = <fun>
+# Exception: Match_failure ("//toplevel//", 14, 39).
+# module N :
+ sig
+ type s = private < a : int; .. >
+ val eq : (s, < a : int; b : bool >) t
+ end
+# Characters 50-75:
+ .................................................function
+ | Any -> "Any"
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Eq
+val f : (N.s, < a : int; b : bool >) t -> string = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/pr5997.ml b/testsuite/tests/typing-gadts/pr5997.ml
new file mode 100644
index 0000000000..81eec13748
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5997.ml
@@ -0,0 +1,28 @@
+type (_, _) comp =
+ | Eq : ('a, 'a) comp
+ | Diff : ('a, 'b) comp
+;;
+
+module U = struct type t = T end;;
+
+module M : sig
+ type t = T
+ val comp : (U.t, t) comp
+end = struct
+ include U
+ let comp = Eq
+end;;
+
+match M.comp with | Diff -> false;;
+
+module U = struct type t = {x : int} end;;
+
+module M : sig
+ type t = {x : int}
+ val comp : (U.t, t) comp
+end = struct
+ include U
+ let comp = Eq
+end;;
+
+match M.comp with | Diff -> false;;
diff --git a/testsuite/tests/typing-gadts/pr5997.ml.reference b/testsuite/tests/typing-gadts/pr5997.ml.reference
new file mode 100644
index 0000000000..65af9f3b14
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr5997.ml.reference
@@ -0,0 +1,21 @@
+
+# type (_, _) comp = Eq : ('a, 'a) comp | Diff : ('a, 'b) comp
+# module U : sig type t = T end
+# module M : sig type t = T val comp : (U.t, t) comp end
+# Characters 1-34:
+ match M.comp with | Diff -> false;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Eq
+Exception: Match_failure ("//toplevel//", 13, 0).
+# module U : sig type t = { x : int; } end
+# module M : sig type t = { x : int; } val comp : (U.t, t) comp end
+# Characters 1-34:
+ match M.comp with | Diff -> false;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Eq
+Exception: Match_failure ("//toplevel//", 22, 0).
+#
diff --git a/testsuite/tests/typing-gadts/pr6158.ml b/testsuite/tests/typing-gadts/pr6158.ml
new file mode 100644
index 0000000000..752380cb37
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6158.ml
@@ -0,0 +1,9 @@
+type 'a t = T of 'a
+type 'a s = S of 'a
+
+type (_, _) eq = Refl : ('a, 'a) eq;;
+
+let f : (int s, int t) eq -> unit = function Refl -> ();;
+
+module M (S : sig type 'a t = T of 'a type 'a s = T of 'a end) =
+struct let f : ('a S.s, 'a S.t) eq -> unit = function Refl -> () end;;
diff --git a/testsuite/tests/typing-gadts/pr6158.ml.principal.reference b/testsuite/tests/typing-gadts/pr6158.ml.principal.reference
new file mode 100644
index 0000000000..c022a4613a
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6158.ml.principal.reference
@@ -0,0 +1,19 @@
+
+# type 'a t = T of 'a
+type 'a s = S of 'a
+type (_, _) eq = Refl : ('a, 'a) eq
+# Characters 46-50:
+ let f : (int s, int t) eq -> unit = function Refl -> ();;
+ ^^^^
+Error: This pattern matches values of type (int s, int s) eq
+ but a pattern was expected which matches values of type
+ (int s, int t) eq
+ Type int s is not compatible with type int t
+# Characters 120-124:
+ struct let f : ('a S.s, 'a S.t) eq -> unit = function Refl -> () end;;
+ ^^^^
+Error: This pattern matches values of type ($0 S.s, $1 S.t) eq
+ but a pattern was expected which matches values of type
+ ('a S.s, 'a S.t) eq
+ The type constructor $0 would escape its scope
+#
diff --git a/testsuite/tests/typing-gadts/pr6158.ml.reference b/testsuite/tests/typing-gadts/pr6158.ml.reference
new file mode 100644
index 0000000000..1e5193c6dd
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6158.ml.reference
@@ -0,0 +1,15 @@
+
+# type 'a t = T of 'a
+type 'a s = S of 'a
+type (_, _) eq = Refl : ('a, 'a) eq
+# Characters 46-50:
+ let f : (int s, int t) eq -> unit = function Refl -> ();;
+ ^^^^
+Error: This pattern matches values of type (int s, int s) eq
+ but a pattern was expected which matches values of type
+ (int s, int t) eq
+ Type int s is not compatible with type int t
+# module M :
+ functor (S : sig type 'a t = T of 'a type 'a s = T of 'a end) ->
+ sig val f : ($'a S.s, $'a S.t) eq -> unit end
+#
diff --git a/testsuite/tests/typing-gadts/pr6163.ml b/testsuite/tests/typing-gadts/pr6163.ml
new file mode 100644
index 0000000000..ad5e8eda73
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6163.ml
@@ -0,0 +1,14 @@
+type _ nat =
+ Zero : [`Zero] nat
+ | Succ : 'a nat -> [`Succ of 'a] nat;;
+type 'a pre_nat = [`Zero | `Succ of 'a];;
+type aux =
+ | Aux : [`Succ of [<[<[<[`Zero] pre_nat] pre_nat] pre_nat]] nat -> aux;;
+
+let f (Aux x) =
+ match x with
+ | Succ Zero -> "1"
+ | Succ (Succ Zero) -> "2"
+ | Succ (Succ (Succ Zero)) -> "3"
+ | Succ (Succ (Succ (Succ Zero))) -> "4"
+;;
diff --git a/testsuite/tests/typing-gadts/pr6163.ml.principal.reference b/testsuite/tests/typing-gadts/pr6163.ml.principal.reference
new file mode 100644
index 0000000000..0b771dc76f
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6163.ml.principal.reference
@@ -0,0 +1,18 @@
+
+# type _ nat = Zero : [ `Zero ] nat | Succ : 'a nat -> [ `Succ of 'a ] nat
+# type 'a pre_nat = [ `Succ of 'a | `Zero ]
+# type aux =
+ Aux :
+ [ `Succ of [< [< [< [ `Zero ] pre_nat ] pre_nat ] pre_nat ] ] nat ->
+ aux
+# Characters 19-157:
+ ..match x with
+ | Succ Zero -> "1"
+ | Succ (Succ Zero) -> "2"
+ | Succ (Succ (Succ Zero)) -> "3"
+ | Succ (Succ (Succ (Succ Zero))) -> "4"
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Succ (Succ (Succ (Succ (Succ _))))
+val f : aux -> string = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/pr6163.ml.reference b/testsuite/tests/typing-gadts/pr6163.ml.reference
new file mode 100644
index 0000000000..0b771dc76f
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6163.ml.reference
@@ -0,0 +1,18 @@
+
+# type _ nat = Zero : [ `Zero ] nat | Succ : 'a nat -> [ `Succ of 'a ] nat
+# type 'a pre_nat = [ `Succ of 'a | `Zero ]
+# type aux =
+ Aux :
+ [ `Succ of [< [< [< [ `Zero ] pre_nat ] pre_nat ] pre_nat ] ] nat ->
+ aux
+# Characters 19-157:
+ ..match x with
+ | Succ Zero -> "1"
+ | Succ (Succ Zero) -> "2"
+ | Succ (Succ (Succ Zero)) -> "3"
+ | Succ (Succ (Succ (Succ Zero))) -> "4"
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Succ (Succ (Succ (Succ (Succ _))))
+val f : aux -> string = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/pr6174.ml b/testsuite/tests/typing-gadts/pr6174.ml
new file mode 100644
index 0000000000..84f79ba0e5
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6174.ml
@@ -0,0 +1,3 @@
+type _ t = C : ((('a -> 'o) -> 'o) -> ('b -> 'o) -> 'o) t
+let f : type a o. ((a -> o) -> o) t -> (a -> o) -> o =
+ fun C k -> k (fun x -> x);;
diff --git a/testsuite/tests/typing-gadts/pr6174.ml.principal.reference b/testsuite/tests/typing-gadts/pr6174.ml.principal.reference
new file mode 100644
index 0000000000..e47a32fa14
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6174.ml.principal.reference
@@ -0,0 +1,7 @@
+
+# Characters 137-138:
+ fun C k -> k (fun x -> x);;
+ ^
+Error: This expression has type $0 but an expression was expected of type
+ $1 = ($2 -> $1) -> $1
+#
diff --git a/testsuite/tests/typing-gadts/pr6174.ml.reference b/testsuite/tests/typing-gadts/pr6174.ml.reference
new file mode 100644
index 0000000000..e47a32fa14
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6174.ml.reference
@@ -0,0 +1,7 @@
+
+# Characters 137-138:
+ fun C k -> k (fun x -> x);;
+ ^
+Error: This expression has type $0 but an expression was expected of type
+ $1 = ($2 -> $1) -> $1
+#
diff --git a/testsuite/tests/typing-gadts/pr6241.ml b/testsuite/tests/typing-gadts/pr6241.ml
new file mode 100644
index 0000000000..4034e4f891
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6241.ml
@@ -0,0 +1,16 @@
+type (_, _) t =
+ A : ('a, 'a) t
+| B : string -> ('a, 'b) t
+;;
+
+module M (A : sig module type T end) (B : sig module type T end) =
+struct
+ let f : ((module A.T), (module B.T)) t -> string = function
+ | B s -> s
+end;;
+
+module A = struct module type T = sig end end;;
+
+module N = M(A)(A);;
+
+let x = N.f A;;
diff --git a/testsuite/tests/typing-gadts/pr6241.ml.principal.reference b/testsuite/tests/typing-gadts/pr6241.ml.principal.reference
new file mode 100644
index 0000000000..cb3095a018
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6241.ml.principal.reference
@@ -0,0 +1,15 @@
+
+# type (_, _) t = A : ('a, 'a) t | B : string -> ('a, 'b) t
+# Characters 127-149:
+ ....................................................function
+ | B s -> s
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+A
+module M :
+ functor (A : sig module type T end) (B : sig module type T end) ->
+ sig val f : ((module A.T), (module B.T)) t -> string end
+# module A : sig module type T = sig end end
+# module N : sig val f : ((module A.T), (module A.T)) t -> string end
+# Exception: Match_failure ("//toplevel//", 7, 52).
+#
diff --git a/testsuite/tests/typing-gadts/pr6241.ml.reference b/testsuite/tests/typing-gadts/pr6241.ml.reference
new file mode 100644
index 0000000000..cb3095a018
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6241.ml.reference
@@ -0,0 +1,15 @@
+
+# type (_, _) t = A : ('a, 'a) t | B : string -> ('a, 'b) t
+# Characters 127-149:
+ ....................................................function
+ | B s -> s
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+A
+module M :
+ functor (A : sig module type T end) (B : sig module type T end) ->
+ sig val f : ((module A.T), (module B.T)) t -> string end
+# module A : sig module type T = sig end end
+# module N : sig val f : ((module A.T), (module A.T)) t -> string end
+# Exception: Match_failure ("//toplevel//", 7, 52).
+#
diff --git a/testsuite/tests/typing-gadts/pr6690.ml b/testsuite/tests/typing-gadts/pr6690.ml
new file mode 100644
index 0000000000..151e995509
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6690.ml
@@ -0,0 +1,31 @@
+type 'a visit_action
+
+type insert
+
+type 'a local_visit_action
+
+type ('a, 'result, 'visit_action) context =
+ | Local : ('a, ('a * insert) as 'result, 'a local_visit_action) context
+ | Global : ('a, 'a, 'a visit_action) context
+;;
+
+let vexpr (type visit_action)
+ : (_, _, visit_action) context -> _ -> visit_action =
+ function
+ | Local -> fun _ -> raise Exit
+ | Global -> fun _ -> raise Exit
+;;
+
+let vexpr (type visit_action)
+ : ('a, 'result, visit_action) context -> 'a -> visit_action =
+ function
+ | Local -> fun _ -> raise Exit
+ | Global -> fun _ -> raise Exit
+;;
+
+let vexpr (type result) (type visit_action)
+ : (unit, result, visit_action) context -> unit -> visit_action =
+ function
+ | Local -> fun _ -> raise Exit
+ | Global -> fun _ -> raise Exit
+;;
diff --git a/testsuite/tests/typing-gadts/pr6690.ml.principal.reference b/testsuite/tests/typing-gadts/pr6690.ml.principal.reference
new file mode 100644
index 0000000000..5c9215bfeb
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6690.ml.principal.reference
@@ -0,0 +1,23 @@
+
+# type 'a visit_action
+type insert
+type 'a local_visit_action
+type ('a, 'result, 'visit_action) context =
+ Local : ('a, 'a * insert, 'a local_visit_action) context
+ | Global : ('a, 'a, 'a visit_action) context
+# Characters 137-143:
+ | Global -> fun _ -> raise Exit
+ ^^^^^^
+Error: This pattern matches values of type ($1, $1, visit_action) context
+ but a pattern was expected which matches values of type
+ ($0, $0 * insert, visit_action) context
+ Type $1 is not compatible with type $0
+# Characters 145-151:
+ | Global -> fun _ -> raise Exit
+ ^^^^^^
+Error: This pattern matches values of type ($1, $1, visit_action) context
+ but a pattern was expected which matches values of type
+ ($0, $0 * insert, visit_action) context
+ Type $1 is not compatible with type $0
+# val vexpr : (unit, 'a, 'b) context -> unit -> 'b = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/pr6690.ml.reference b/testsuite/tests/typing-gadts/pr6690.ml.reference
new file mode 100644
index 0000000000..3f435f67bf
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6690.ml.reference
@@ -0,0 +1,27 @@
+
+# type 'a visit_action
+type insert
+type 'a local_visit_action
+type ('a, 'result, 'visit_action) context =
+ Local : ('a, 'a * insert, 'a local_visit_action) context
+ | Global : ('a, 'a, 'a visit_action) context
+# Characters 11-166:
+ ..........(type visit_action)
+ : (_, _, visit_action) context -> _ -> visit_action =
+ function
+ | Local -> fun _ -> raise Exit
+ | Global -> fun _ -> raise Exit
+Error: This expression has type ($0, $0 * insert, 'a) context -> 'b -> 'a
+ but an expression was expected of type 'c
+ The type constructor $0 would escape its scope
+# Characters 11-174:
+ ..........(type visit_action)
+ : ('a, 'result, visit_action) context -> 'a -> visit_action =
+ function
+ | Local -> fun _ -> raise Exit
+ | Global -> fun _ -> raise Exit
+Error: This expression has type ($'a, $'a * insert, 'a) context -> $'a -> 'a
+ but an expression was expected of type 'b
+ The type constructor $'a would escape its scope
+# val vexpr : (unit, 'a, 'b) context -> unit -> 'b = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/pr6817.ml b/testsuite/tests/typing-gadts/pr6817.ml
new file mode 100644
index 0000000000..73c1f6351e
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6817.ml
@@ -0,0 +1,24 @@
+module A = struct
+ type nil = Cstr
+ end
+open A
+;;
+
+type _ s =
+ | Nil : nil s
+ | Cons : 't s -> ('h -> 't) s
+
+type ('stack, 'typ) var =
+ | Head : (('typ -> _) s, 'typ) var
+ | Tail : ('tail s, 'typ) var -> ((_ -> 'tail) s, 'typ) var
+
+type _ lst =
+ | CNil : nil lst
+ | CCons : 'h * ('t lst) -> ('h -> 't) lst
+;;
+
+let rec get_var : type stk ret. (stk s, ret) var -> stk lst -> ret = fun n s ->
+ match n, s with
+ | Head, CCons (h, _) -> h
+ | Tail n', CCons (_, t) -> get_var n' t
+;;
diff --git a/testsuite/tests/typing-gadts/pr6817.ml.reference b/testsuite/tests/typing-gadts/pr6817.ml.reference
new file mode 100644
index 0000000000..ec47bcc99e
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6817.ml.reference
@@ -0,0 +1,9 @@
+
+# module A : sig type nil = Cstr end
+# type _ s = Nil : A.nil s | Cons : 't s -> ('h -> 't) s
+type ('stack, 'typ) var =
+ Head : (('typ -> 'a) s, 'typ) var
+ | Tail : ('tail s, 'typ) var -> (('b -> 'tail) s, 'typ) var
+type _ lst = CNil : A.nil lst | CCons : 'h * 't lst -> ('h -> 't) lst
+# val get_var : ('stk s, 'ret) var -> 'stk lst -> 'ret = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/pr6993_bad.ml b/testsuite/tests/typing-gadts/pr6993_bad.ml
new file mode 100644
index 0000000000..122b50f33b
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6993_bad.ml
@@ -0,0 +1,12 @@
+type (_, _) eqp = Y : ('a, 'a) eqp | N : string -> ('a, 'b) eqp
+let f : ('a list, 'a) eqp -> unit = function N s -> print_string s;;
+
+module rec A : sig type t = B.t list end =
+ struct type t = B.t list end
+and B : sig type t val eq : (B.t list, t) eqp end =
+ struct
+ type t = A.t
+ let eq = Y
+ end;;
+
+f B.eq;;
diff --git a/testsuite/tests/typing-gadts/pr6993_bad.ml.reference b/testsuite/tests/typing-gadts/pr6993_bad.ml.reference
new file mode 100644
index 0000000000..cda1b16a47
--- /dev/null
+++ b/testsuite/tests/typing-gadts/pr6993_bad.ml.reference
@@ -0,0 +1,13 @@
+
+# Characters 100-130:
+ let f : ('a list, 'a) eqp -> unit = function N s -> print_string s;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Y
+type (_, _) eqp = Y : ('a, 'a) eqp | N : string -> ('a, 'b) eqp
+val f : ('a list, 'a) eqp -> unit = <fun>
+# module rec A : sig type t = B.t list end
+and B : sig type t val eq : (B.t list, t) eqp end
+# Exception: Match_failure ("//toplevel//", 2, 36).
+#
diff --git a/testsuite/tests/typing-gadts/term-conv.ml b/testsuite/tests/typing-gadts/term-conv.ml
new file mode 100644
index 0000000000..9b53cd6ea8
--- /dev/null
+++ b/testsuite/tests/typing-gadts/term-conv.ml
@@ -0,0 +1,139 @@
+(* HOAS to de Bruijn, by chak *)
+(* http://www.cse.unsw.edu.au/~chak/haskell/term-conv/ *)
+
+module Typeable = struct
+ type 'a ty =
+ | Int: int ty
+ | String: string ty
+ | List: 'a ty -> 'a list ty
+ | Pair: ('a ty * 'b ty) -> ('a * 'b) ty
+ | Fun: ('a ty * 'b ty) -> ('a -> 'b) ty
+
+ type (_,_) eq = Eq : ('a,'a) eq
+
+ exception CastFailure
+ let rec check_eq : type t t'. t ty -> t' ty -> (t,t') eq = fun t t' ->
+ match t, t' with
+ | Int, Int -> Eq
+ | String, String -> Eq
+ | List t, List t' -> (match check_eq t t' with Eq -> Eq)
+ | Pair (t1,t2), Pair (t1',t2') ->
+ (match check_eq t1 t1', check_eq t2 t2' with Eq, Eq -> Eq)
+ | Fun (t1,t2), Fun (t1',t2') ->
+ (match check_eq t1 t1', check_eq t2 t2' with Eq, Eq -> Eq)
+ | _ -> raise CastFailure
+
+ let gcast : type t t'. t ty -> t' ty -> t -> t' = fun t t' x ->
+ match check_eq t t' with Eq -> x
+end;;
+
+module HOAS = struct
+ open Typeable
+
+ type _ term =
+ | Tag : 't ty * int -> 't term
+ | Con : 't -> 't term
+ | Lam : 's ty * ('s term -> 't term) -> ('s -> 't) term
+ | App : ('s -> 't) term * 's term -> 't term
+
+ let rec intp : type t. t term -> t = function
+ | Tag (_, ix) -> failwith "HOAS.intp"
+ | Con v -> v
+ | Lam (_, f) -> fun x -> intp (f (Con x))
+ | App (f, a) -> intp f (intp a)
+end;;
+
+module DeBruijn = struct
+ type ('env,'t) ix =
+ | ZeroIx : ('env * 't, 't) ix
+ | SuccIx : ('env,'t) ix -> ('env * 's, 't) ix
+
+ let rec to_int : type env t. (env,t) ix -> int = function
+ | ZeroIx -> 0
+ | SuccIx n -> to_int n + 1
+
+ type ('env,'t) term =
+ | Var : ('env,'t) ix -> ('env,'t) term
+ | Con : 't -> ('env,'t) term
+ | Lam : ('env * 's, 't) term -> ('env, 's -> 't) term
+ | App : ('env, 's -> 't) term * ('env, 's) term -> ('env, 't) term
+
+ type _ stack =
+ | Empty : unit stack
+ | Push : 'env stack * 't -> ('env * 't) stack
+
+ let rec prj : type env t. (env,t) ix -> env stack -> t = fun i s ->
+ match i, s with
+ | ZeroIx, Push (s,v) -> v
+ | SuccIx i, Push (s,_) -> prj i s
+
+ let rec intp : type env t. (env,t) term -> env stack -> t = fun t s ->
+ match t with
+ | Var ix -> prj ix s
+ | Con v -> v
+ | Lam b -> fun x -> intp b (Push (s, x))
+ | App(f,a) -> intp f s (intp a s)
+end;;
+
+module Convert = struct
+ type (_,_) layout =
+ | EmptyLayout : ('env, unit) layout
+ | PushLayout :
+ 't Typeable.ty * ('env,'env') layout * ('env,'t) DeBruijn.ix
+ -> ('env,'env' * 't) layout
+
+ let rec size : type env env'. (env,env') layout -> int = function
+ | EmptyLayout -> 0
+ | PushLayout (_, lyt, _) -> size lyt + 1
+
+ let rec inc : type env env'. (env,env') layout -> (env * 't, env') layout =
+ function
+ | EmptyLayout -> EmptyLayout
+ | PushLayout (t, lyt, ix) -> PushLayout (t, inc lyt, DeBruijn.SuccIx ix)
+
+ let rec prj : type env env' t.
+ t Typeable.ty -> int -> (env,env') layout -> (env,t) DeBruijn.ix
+ = fun t n -> function
+ | EmptyLayout -> failwith "Convert.prj: internal error"
+ | PushLayout (t', l, ix) ->
+ if n = 0 then
+ match Typeable.check_eq t t' with Typeable.Eq -> ix
+ else prj t (n-1) l
+
+ let rec cvt :
+ type env t. (env,env) layout -> t HOAS.term -> (env,t) DeBruijn.term =
+ fun lyt -> function
+ | HOAS.Tag (t, sz) -> DeBruijn.Var (prj t (size lyt - sz -1) lyt)
+ | HOAS.Con v -> DeBruijn.Con v
+ | HOAS.Lam (t, f) ->
+ let lyt' = PushLayout (t, inc lyt, DeBruijn.ZeroIx) in
+ DeBruijn.Lam (cvt lyt' (f (HOAS.Tag (t, size lyt))))
+ | HOAS.App (f, a) ->
+ DeBruijn.App (cvt lyt f, cvt lyt a)
+
+ let convert t = cvt EmptyLayout t
+end;;
+
+module Main = struct
+ open HOAS
+ let i t = Lam (t, fun x -> x)
+ let zero t = Lam (Typeable.Fun(t,t), fun f -> Lam(t, fun x -> x))
+ let one t = Lam (Typeable.Fun(t,t), fun f -> Lam(t, fun x -> App (f, x)))
+ let two t =
+ Lam (Typeable.Fun(t,t), fun f -> Lam(t, fun x -> App (f, App (f, x))))
+ let three t =
+ Lam (Typeable.Fun(t,t),
+ fun f -> Lam(t, fun x -> App (f, App (f, App (f, x)))))
+ let plus t =
+ let t1 = Typeable.Fun(t,t) in let t2 = Typeable.Fun(t1,t1) in
+ Lam (t2, fun m -> Lam (t2, fun n ->
+ Lam (t1, fun f -> Lam(t, fun x -> App(App(m,f), App(App(n,f),x))))))
+
+ let plus_2_3 t = App (App (plus t, two t), three t)
+
+ open Convert
+
+ let i' = convert (i Typeable.Int)
+ let plus_2_3' = convert (plus_2_3 Typeable.Int)
+ let eval_plus_2_3' = DeBruijn.intp plus_2_3' DeBruijn.Empty succ 0
+end;;
diff --git a/testsuite/tests/typing-gadts/term-conv.ml.principal.reference b/testsuite/tests/typing-gadts/term-conv.ml.principal.reference
new file mode 100644
index 0000000000..cff10f16f9
--- /dev/null
+++ b/testsuite/tests/typing-gadts/term-conv.ml.principal.reference
@@ -0,0 +1,71 @@
+
+# module Typeable :
+ sig
+ type 'a ty =
+ Int : int ty
+ | String : string ty
+ | List : 'a ty -> 'a list ty
+ | Pair : ('a ty * 'b ty) -> ('a * 'b) ty
+ | Fun : ('a ty * 'b ty) -> ('a -> 'b) ty
+ type (_, _) eq = Eq : ('a, 'a) eq
+ exception CastFailure
+ val check_eq : 't ty -> 't' ty -> ('t, 't') eq
+ val gcast : 't ty -> 't' ty -> 't -> 't'
+ end
+# module HOAS :
+ sig
+ type _ term =
+ Tag : 't Typeable.ty * int -> 't term
+ | Con : 't -> 't term
+ | Lam : 's Typeable.ty * ('s term -> 't term) -> ('s -> 't) term
+ | App : ('s -> 't) term * 's term -> 't term
+ val intp : 't term -> 't
+ end
+# module DeBruijn :
+ sig
+ type ('env, 't) ix =
+ ZeroIx : ('env * 't, 't) ix
+ | SuccIx : ('env, 't) ix -> ('env * 's, 't) ix
+ val to_int : ('env, 't) ix -> int
+ type ('env, 't) term =
+ Var : ('env, 't) ix -> ('env, 't) term
+ | Con : 't -> ('env, 't) term
+ | Lam : ('env * 's, 't) term -> ('env, 's -> 't) term
+ | App : ('env, 's -> 't) term * ('env, 's) term -> ('env, 't) term
+ type _ stack =
+ Empty : unit stack
+ | Push : 'env stack * 't -> ('env * 't) stack
+ val prj : ('env, 't) ix -> 'env stack -> 't
+ val intp : ('env, 't) term -> 'env stack -> 't
+ end
+# module Convert :
+ sig
+ type (_, _) layout =
+ EmptyLayout : ('env, unit) layout
+ | PushLayout : 't Typeable.ty * ('env, 'env') layout *
+ ('env, 't) DeBruijn.ix -> ('env, 'env' * 't) layout
+ val size : ('env, 'env') layout -> int
+ val inc : ('env, 'env') layout -> ('env * 't, 'env') layout
+ val prj :
+ 't Typeable.ty -> int -> ('env, 'env') layout -> ('env, 't) DeBruijn.ix
+ val cvt : ('env, 'env) layout -> 't HOAS.term -> ('env, 't) DeBruijn.term
+ val convert : 'a HOAS.term -> (unit, 'a) DeBruijn.term
+ end
+# module Main :
+ sig
+ val i : 'a Typeable.ty -> ('a -> 'a) HOAS.term
+ val zero : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val one : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val two : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val three : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val plus :
+ 'a Typeable.ty ->
+ ((('a -> 'a) -> 'a -> 'a) ->
+ (('a -> 'a) -> 'a -> 'a) -> ('a -> 'a) -> 'a -> 'a)
+ HOAS.term
+ val plus_2_3 : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val i' : (unit, int -> int) DeBruijn.term
+ val plus_2_3' : (unit, (int -> int) -> int -> int) DeBruijn.term
+ val eval_plus_2_3' : int
+ end
+#
diff --git a/testsuite/tests/typing-gadts/term-conv.ml.reference b/testsuite/tests/typing-gadts/term-conv.ml.reference
new file mode 100644
index 0000000000..cff10f16f9
--- /dev/null
+++ b/testsuite/tests/typing-gadts/term-conv.ml.reference
@@ -0,0 +1,71 @@
+
+# module Typeable :
+ sig
+ type 'a ty =
+ Int : int ty
+ | String : string ty
+ | List : 'a ty -> 'a list ty
+ | Pair : ('a ty * 'b ty) -> ('a * 'b) ty
+ | Fun : ('a ty * 'b ty) -> ('a -> 'b) ty
+ type (_, _) eq = Eq : ('a, 'a) eq
+ exception CastFailure
+ val check_eq : 't ty -> 't' ty -> ('t, 't') eq
+ val gcast : 't ty -> 't' ty -> 't -> 't'
+ end
+# module HOAS :
+ sig
+ type _ term =
+ Tag : 't Typeable.ty * int -> 't term
+ | Con : 't -> 't term
+ | Lam : 's Typeable.ty * ('s term -> 't term) -> ('s -> 't) term
+ | App : ('s -> 't) term * 's term -> 't term
+ val intp : 't term -> 't
+ end
+# module DeBruijn :
+ sig
+ type ('env, 't) ix =
+ ZeroIx : ('env * 't, 't) ix
+ | SuccIx : ('env, 't) ix -> ('env * 's, 't) ix
+ val to_int : ('env, 't) ix -> int
+ type ('env, 't) term =
+ Var : ('env, 't) ix -> ('env, 't) term
+ | Con : 't -> ('env, 't) term
+ | Lam : ('env * 's, 't) term -> ('env, 's -> 't) term
+ | App : ('env, 's -> 't) term * ('env, 's) term -> ('env, 't) term
+ type _ stack =
+ Empty : unit stack
+ | Push : 'env stack * 't -> ('env * 't) stack
+ val prj : ('env, 't) ix -> 'env stack -> 't
+ val intp : ('env, 't) term -> 'env stack -> 't
+ end
+# module Convert :
+ sig
+ type (_, _) layout =
+ EmptyLayout : ('env, unit) layout
+ | PushLayout : 't Typeable.ty * ('env, 'env') layout *
+ ('env, 't) DeBruijn.ix -> ('env, 'env' * 't) layout
+ val size : ('env, 'env') layout -> int
+ val inc : ('env, 'env') layout -> ('env * 't, 'env') layout
+ val prj :
+ 't Typeable.ty -> int -> ('env, 'env') layout -> ('env, 't) DeBruijn.ix
+ val cvt : ('env, 'env) layout -> 't HOAS.term -> ('env, 't) DeBruijn.term
+ val convert : 'a HOAS.term -> (unit, 'a) DeBruijn.term
+ end
+# module Main :
+ sig
+ val i : 'a Typeable.ty -> ('a -> 'a) HOAS.term
+ val zero : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val one : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val two : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val three : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val plus :
+ 'a Typeable.ty ->
+ ((('a -> 'a) -> 'a -> 'a) ->
+ (('a -> 'a) -> 'a -> 'a) -> ('a -> 'a) -> 'a -> 'a)
+ HOAS.term
+ val plus_2_3 : 'a Typeable.ty -> (('a -> 'a) -> 'a -> 'a) HOAS.term
+ val i' : (unit, int -> int) DeBruijn.term
+ val plus_2_3' : (unit, (int -> int) -> int -> int) DeBruijn.term
+ val eval_plus_2_3' : int
+ end
+#
diff --git a/testsuite/tests/typing-gadts/test.ml b/testsuite/tests/typing-gadts/test.ml
new file mode 100644
index 0000000000..70b391f51c
--- /dev/null
+++ b/testsuite/tests/typing-gadts/test.ml
@@ -0,0 +1,548 @@
+module Exp =
+ struct
+
+ type _ t =
+ | IntLit : int -> int t
+ | BoolLit : bool -> bool t
+ | Pair : 'a t * 'b t -> ('a * 'b) t
+ | App : ('a -> 'b) t * 'a t -> 'b t
+ | Abs : ('a -> 'b) -> ('a -> 'b) t
+
+
+ let rec eval : type s . s t -> s =
+ function
+ | IntLit x -> x
+ | BoolLit y -> y
+ | Pair (x,y) ->
+ (eval x,eval y)
+ | App (f,a) ->
+ (eval f) (eval a)
+ | Abs f -> f
+
+ let discern : type a. a t -> _ = function
+ IntLit _ -> 1
+ | BoolLit _ -> 2
+ | Pair _ -> 3
+ | App _ -> 4
+ | Abs _ -> 5
+ end
+;;
+
+module List =
+ struct
+ type zero
+ type _ t =
+ | Nil : zero t
+ | Cons : 'a * 'b t -> ('a * 'b) t
+ let head =
+ function
+ | Cons (a,b) -> a
+ let tail =
+ function
+ | Cons (a,b) -> b
+ let rec length : type a . a t -> int =
+ function
+ | Nil -> 0
+ | Cons (a,b) -> length b
+ end
+;;
+
+module Nonexhaustive =
+ struct
+ type 'a u =
+ | C1 : int -> int u
+ | C2 : bool -> bool u
+
+ type 'a v =
+ | C1 : int -> int v
+
+ let unexhaustive : type s . s u -> s =
+ function
+ | C2 x -> x
+
+
+ module M : sig type t type u end =
+ struct
+ type t = int
+ type u = bool
+ end
+ type 'a t =
+ | Foo : M.t -> M.t t
+ | Bar : M.u -> M.u t
+ let same_type : type s . s t * s t -> bool =
+ function
+ | Foo _ , Foo _ -> true
+ | Bar _, Bar _ -> true
+ end
+;;
+
+module Exhaustive =
+ struct
+ type t = int
+ type u = bool
+ type 'a v =
+ | Foo : t -> t v
+ | Bar : u -> u v
+
+ let same_type : type s . s v * s v -> bool =
+ function
+ | Foo _ , Foo _ -> true
+ | Bar _, Bar _ -> true
+ end
+;;
+
+module PR6862 = struct
+ class c (Some x) = object method x : int = x end
+ type _ opt = Just : 'a -> 'a opt | Nothing : 'a opt
+ class d (Just x) = object method x : int = x end
+end;;
+
+module Existential_escape =
+ struct
+ type _ t = C : int -> int t
+ type u = D : 'a t -> u
+ let eval (D x) = x
+ end
+;;
+
+module Rectype =
+ struct
+ type (_,_) t = C : ('a,'a) t
+ let f : type s. (s, s*s) t -> unit =
+ fun C -> () (* here s = s*s! *)
+ end
+;;
+
+module Or_patterns =
+struct
+ type _ t =
+ | IntLit : int -> int t
+ | BoolLit : bool -> bool t
+
+ let rec eval : type s . s t -> unit =
+ function
+ | (IntLit _ | BoolLit _) -> ()
+
+end
+;;
+
+module Polymorphic_variants =
+ struct
+ type _ t =
+ | IntLit : int -> int t
+ | BoolLit : bool -> bool t
+
+ let rec eval : type s . [`A] * s t -> unit =
+ function
+ | `A, IntLit _ -> ()
+ | `A, BoolLit _ -> ()
+ end
+;;
+
+module Propagation = struct
+ type _ t =
+ IntLit : int -> int t
+ | BoolLit : bool -> bool t
+
+ let check : type s. s t -> s = function
+ | IntLit n -> n
+ | BoolLit b -> b
+
+ let check : type s. s t -> s = fun x ->
+ let r = match x with
+ | IntLit n -> (n : s )
+ | BoolLit b -> b
+ in r
+end
+;;
+
+module Normal_constrs = struct
+ type a = A
+ type b = B
+
+ let f = function A -> 1 | B -> 2
+end;;
+
+module PR6849 = struct
+ type 'a t = Foo : int t
+
+ let f : int -> int = function
+ Foo -> 5
+end;;
+
+type _ t = Int : int t ;;
+
+let ky x y = ignore (x = y); x ;;
+
+let test : type a. a t -> a =
+ function Int -> ky (1 : a) 1
+;;
+
+let test : type a. a t -> _ =
+ function Int -> 1 (* ok *)
+;;
+
+let test : type a. a t -> _ =
+ function Int -> ky (1 : a) 1 (* fails *)
+;;
+
+let test : type a. a t -> a = fun x ->
+ let r = match x with Int -> ky (1 : a) 1 (* fails *)
+ in r
+;;
+let test : type a. a t -> a = fun x ->
+ let r = match x with Int -> ky 1 (1 : a) (* fails *)
+ in r
+;;
+let test (type a) x =
+ let r = match (x : a t) with Int -> ky 1 1
+ in r
+;;
+let test : type a. a t -> a = fun x ->
+ let r = match x with Int -> (1 : a) (* ok! *)
+ in r
+;;
+let test : type a. a t -> _ = fun x ->
+ let r = match x with Int -> 1 (* ok! *)
+ in r
+;;
+let test : type a. a t -> a = fun x ->
+ let r : a = match x with Int -> 1
+ in r (* ok *)
+;;
+let test2 : type a. a t -> a option = fun x ->
+ let r = ref None in
+ begin match x with Int -> r := Some (1 : a) end;
+ !r (* ok *)
+;;
+let test2 : type a. a t -> a option = fun x ->
+ let r : a option ref = ref None in
+ begin match x with Int -> r := Some 1 end;
+ !r (* ok *)
+;;
+let test2 : type a. a t -> a option = fun x ->
+ let r : a option ref = ref None in
+ let u = ref None in
+ begin match x with Int -> r := Some 1; u := !r end;
+ !u
+;; (* ok (u non-ambiguous) *)
+let test2 : type a. a t -> a option = fun x ->
+ let r : a option ref = ref None in
+ let u = ref None in
+ begin match x with Int -> u := Some 1; r := !u end;
+ !u
+;; (* fails because u : (int | a) option ref *)
+let test2 : type a. a t -> a option = fun x ->
+ let u = ref None in
+ let r : a option ref = ref None in
+ begin match x with Int -> r := Some 1; u := !r end;
+ !u
+;; (* ok *)
+let test2 : type a. a t -> a option = fun x ->
+ let u = ref None in
+ let a =
+ let r : a option ref = ref None in
+ begin match x with Int -> r := Some 1; u := !r end;
+ !u
+ in a
+;; (* ok *)
+let either = ky
+let we_y1x (type a) (x : a) (v : a t) =
+ match v with Int -> let y = either 1 x in y
+;; (* fail *)
+
+(* Effect of external consraints *)
+let f (type a) (x : a t) y =
+ ignore (y : a);
+ let r = match x with Int -> (y : a) in (* ok *)
+ r
+;;
+let f (type a) (x : a t) y =
+ let r = match x with Int -> (y : a) in
+ ignore (y : a); (* ok *)
+ r
+;;
+let f (type a) (x : a t) y =
+ ignore (y : a);
+ let r = match x with Int -> y in (* ok *)
+ r
+;;
+let f (type a) (x : a t) y =
+ let r = match x with Int -> y in
+ ignore (y : a); (* ok *)
+ r
+;;
+let f (type a) (x : a t) (y : a) =
+ match x with Int -> y (* returns 'a *)
+;;
+
+(* Combination with local modules *)
+
+let f (type a) (x : a t) y =
+ match x with Int ->
+ let module M = struct type b = a let z = (y : b) end
+ in M.z
+;; (* fails because of aliasing... *)
+
+let f (type a) (x : a t) y =
+ match x with Int ->
+ let module M = struct type b = int let z = (y : b) end
+ in M.z
+;; (* ok *)
+
+(* Objects and variants *)
+
+type _ h =
+ | Has_m : <m : int> h
+ | Has_b : <b : bool> h
+
+let f : type a. a h -> a = function
+ | Has_m -> object method m = 1 end
+ | Has_b -> object method b = true end
+;;
+type _ j =
+ | Has_A : [`A of int] j
+ | Has_B : [`B of bool] j
+
+let f : type a. a j -> a = function
+ | Has_A -> `A 1
+ | Has_B -> `B true
+;;
+
+type (_,_) eq = Eq : ('a,'a) eq ;;
+
+let f : type a b. (a,b) eq -> (<m : a; ..> as 'c) -> (<m : b; ..> as 'c) =
+ fun Eq o -> o
+;; (* fail *)
+
+let f : type a b. (a,b) eq -> <m : a; ..> -> <m : b; ..> =
+ fun Eq o -> o
+;; (* fail *)
+
+let f (type a) (type b) (eq : (a,b) eq) (o : <m : a; ..>) : <m : b; ..> =
+ match eq with Eq -> o ;; (* should fail *)
+
+let f : type a b. (a,b) eq -> <m : a> -> <m : b> =
+ fun Eq o -> o
+;; (* ok *)
+
+let int_of_bool : (bool,int) eq = Obj.magic Eq;;
+
+let x = object method m = true end;;
+let y = (x, f int_of_bool x);;
+
+let f : type a. (a, int) eq -> <m : a> -> bool =
+ fun Eq o -> ignore (o : <m : int; ..>); o#m = 3
+;; (* should be ok *)
+
+let f : type a b. (a,b) eq -> < m : a; .. > -> < m : b > =
+ fun eq o ->
+ ignore (o : < m : a >);
+ let r : < m : b > = match eq with Eq -> o in (* fail with principal *)
+ r;;
+
+let f : type a b. (a,b) eq -> < m : a; .. > -> < m : b > =
+ fun eq o ->
+ let r : < m : b > = match eq with Eq -> o in (* fail *)
+ ignore (o : < m : a >);
+ r;;
+
+let f : type a b. (a,b) eq -> [> `A of a] -> [> `A of b] =
+ fun Eq o -> o ;; (* fail *)
+
+let f (type a b) (eq : (a,b) eq) (v : [> `A of a]) : [> `A of b] =
+ match eq with Eq -> v ;; (* should fail *)
+
+let f : type a b. (a,b) eq -> [< `A of a | `B] -> [< `A of b | `B] =
+ fun Eq o -> o ;; (* fail *)
+
+let f : type a b. (a,b) eq -> [`A of a | `B] -> [`A of b | `B] =
+ fun Eq o -> o ;; (* ok *)
+
+let f : type a. (a, int) eq -> [`A of a] -> bool =
+ fun Eq v -> match v with `A 1 -> true | _ -> false
+;; (* ok *)
+
+let f : type a b. (a,b) eq -> [> `A of a | `B] -> [`A of b | `B] =
+ fun eq o ->
+ ignore (o : [< `A of a | `B]);
+ let r : [`A of b | `B] = match eq with Eq -> o in (* fail with principal *)
+ r;;
+
+let f : type a b. (a,b) eq -> [> `A of a | `B] -> [`A of b | `B] =
+ fun eq o ->
+ let r : [`A of b | `B] = match eq with Eq -> o in (* fail *)
+ ignore (o : [< `A of a | `B]);
+ r;;
+
+(* Pattern matching *)
+
+type 'a t =
+ A of int | B of bool | C of float | D of 'a
+
+type _ ty =
+ | TE : 'a ty -> 'a array ty
+ | TA : int ty
+ | TB : bool ty
+ | TC : float ty
+ | TD : string -> bool ty
+
+let f : type a. a ty -> a t -> int = fun x y ->
+ match x, y with
+ | _, A z -> z
+ | _, B z -> if z then 1 else 2
+ | _, C z -> truncate z
+ | TE TC, D [|1.0|] -> 14
+ | TA, D 0 -> -1
+ | TA, D z -> z
+ | TD "bye", D false -> 13
+ | TD "hello", D true -> 12
+ (* | TB, D z -> if z then 1 else 2 *)
+ | TC, D z -> truncate z
+ | _, D _ -> 0
+;;
+
+let f : type a. a ty -> a t -> int = fun x y ->
+ match x, y with
+ | _, A z -> z
+ | _, B z -> if z then 1 else 2
+ | _, C z -> truncate z
+ | TE TC, D [|1.0|] -> 14
+ | TA, D 0 -> -1
+ | TA, D z -> z
+;; (* warn *)
+
+let f : type a. a ty -> a t -> int = fun x y ->
+ match y, x with
+ | A z, _ -> z
+ | B z, _ -> if z then 1 else 2
+ | C z, _ -> truncate z
+ | D [|1.0|], TE TC -> 14
+ | D 0, TA -> -1
+ | D z, TA -> z
+;; (* fail *)
+
+type ('a,'b) pair = {right:'a; left:'b}
+
+let f : type a. a ty -> a t -> int = fun x y ->
+ match {left=x; right=y} with
+ | {left=_; right=A z} -> z
+ | {left=_; right=B z} -> if z then 1 else 2
+ | {left=_; right=C z} -> truncate z
+ | {left=TE TC; right=D [|1.0|]} -> 14
+ | {left=TA; right=D 0} -> -1
+ | {left=TA; right=D z} -> z
+;; (* fail *)
+
+type ('a,'b) pair = {left:'a; right:'b}
+
+let f : type a. a ty -> a t -> int = fun x y ->
+ match {left=x; right=y} with
+ | {left=_; right=A z} -> z
+ | {left=_; right=B z} -> if z then 1 else 2
+ | {left=_; right=C z} -> truncate z
+ | {left=TE TC; right=D [|1.0|]} -> 14
+ | {left=TA; right=D 0} -> -1
+ | {left=TA; right=D z} -> z
+;; (* ok *)
+
+(* Injectivity *)
+
+module M : sig type 'a t val eq : ('a t, 'b t) eq end =
+ struct type 'a t = int let eq = Eq end
+;;
+
+let f : type a b. (a M.t, b M.t) eq -> (a, b) eq =
+ function Eq -> Eq (* fail *)
+;;
+
+let f : type a b. (a M.t * a, b M.t * b) eq -> (a, b) eq =
+ function Eq -> Eq (* ok *)
+;;
+
+let f : type a b. (a * a M.t, b * b M.t) eq -> (a, b) eq =
+ function Eq -> Eq (* ok *)
+;;
+
+(* Applications of polymorphic variants *)
+
+type _ t =
+ | V1 : [`A | `B] t
+ | V2 : [`C | `D] t
+
+let f : type a. a t -> a = function
+ | V1 -> `A
+ | V2 -> `C
+;;
+
+f V1;;
+
+(* PR#5425 and PR#5427 *)
+
+type _ int_foo =
+ | IF_constr : <foo:int; ..> int_foo
+
+type _ int_bar =
+ | IB_constr : <bar:int; ..> int_bar
+;;
+
+let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
+ let IF_constr, IB_constr = e, e' in
+ (x:<foo:int>)
+;;
+
+let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
+ let IF_constr, IB_constr = e, e' in
+ (x:<foo:int;bar:int>)
+;;
+
+let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
+ let IF_constr, IB_constr = e, e' in
+ (x:<foo:int;bar:int;..>)
+;;
+
+let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) : t =
+ let IF_constr, IB_constr = e, e' in
+ (x:<foo:int;bar:int;..>)
+;;
+
+let g (type t) (x:t) (e : t int_foo) (e' : t int_bar) =
+ let IF_constr, IB_constr = e, e' in
+ x, x#foo, x#bar
+;;
+
+(* PR#5554 *)
+
+type 'a ty = Int : int -> int ty;;
+
+let f : type a. a ty -> a =
+ fun x -> match x with Int y -> y;;
+
+let g : type a. a ty -> a =
+ let () = () in
+ fun x -> match x with Int y -> y;;
+
+(* Printing of anonymous variables *)
+
+module M = struct type _ t = int end;;
+module M = struct type _ t = T : int t end;;
+module N = M;;
+
+(* Principality *)
+
+(* adding a useless equation should not break inference *)
+let f : type a b. (a,b) eq -> (a,int) eq -> a -> b -> _ = fun ab aint a b ->
+ let Eq = ab in
+ let x =
+ let Eq = aint in
+ if true then a else b
+ in ignore x
+;; (* ok *)
+
+let f : type a b. (a,b) eq -> (b,int) eq -> a -> b -> _ = fun ab bint a b ->
+ let Eq = ab in
+ let x =
+ let Eq = bint in
+ if true then a else b
+ in ignore x
+;; (* ok *)
diff --git a/testsuite/tests/typing-gadts/test.ml.principal.reference b/testsuite/tests/typing-gadts/test.ml.principal.reference
new file mode 100644
index 0000000000..4a36e4fa7e
--- /dev/null
+++ b/testsuite/tests/typing-gadts/test.ml.principal.reference
@@ -0,0 +1,337 @@
+
+# module Exp :
+ sig
+ type _ t =
+ IntLit : int -> int t
+ | BoolLit : bool -> bool t
+ | Pair : 'a t * 'b t -> ('a * 'b) t
+ | App : ('a -> 'b) t * 'a t -> 'b t
+ | Abs : ('a -> 'b) -> ('a -> 'b) t
+ val eval : 's t -> 's
+ val discern : 'a t -> int
+ end
+# module List :
+ sig
+ type zero
+ type _ t = Nil : zero t | Cons : 'a * 'b t -> ('a * 'b) t
+ val head : ('a * 'b) t -> 'a
+ val tail : ('a * 'b) t -> 'b t
+ val length : 'a t -> int
+ end
+# Characters 196-224:
+ ......function
+ | C2 x -> x
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+C1 _
+Characters 458-529:
+ ......function
+ | Foo _ , Foo _ -> true
+ | Bar _, Bar _ -> true
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(Bar _, Foo _)
+module Nonexhaustive :
+ sig
+ type 'a u = C1 : int -> int u | C2 : bool -> bool u
+ type 'a v = C1 : int -> int v
+ val unexhaustive : 's u -> 's
+ module M : sig type t type u end
+ type 'a t = Foo : M.t -> M.t t | Bar : M.u -> M.u t
+ val same_type : 's t * 's t -> bool
+ end
+# module Exhaustive :
+ sig
+ type t = int
+ type u = bool
+ type 'a v = Foo : t -> t v | Bar : u -> u v
+ val same_type : 's v * 's v -> bool
+ end
+# Characters 34-42:
+ class c (Some x) = object method x : int = x end
+ ^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+None
+Characters 139-147:
+ class d (Just x) = object method x : int = x end
+ ^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Nothing
+module PR6862 :
+ sig
+ class c : int option -> object method x : int end
+ type _ opt = Just : 'a -> 'a opt | Nothing : 'a opt
+ class d : int opt -> object method x : int end
+ end
+# Characters 118-119:
+ let eval (D x) = x
+ ^
+Error: This expression has type $D_'a t
+ but an expression was expected of type 'a
+ The type constructor $D_'a would escape its scope
+# module Rectype :
+ sig type (_, _) t = C : ('a, 'a) t val f : ('s, 's * 's) t -> unit end
+# Characters 178-186:
+ | (IntLit _ | BoolLit _) -> ()
+ ^^^^^^^^
+Error: This pattern matches values of type int t
+ but a pattern was expected which matches values of type s t
+ Type int is not compatible with type s
+# module Polymorphic_variants :
+ sig
+ type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
+ val eval : [ `A ] * 's t -> unit
+ end
+# Characters 299-300:
+ | BoolLit b -> b
+ ^
+Error: This expression has type bool but an expression was expected of type s
+# Characters 87-88:
+ let f = function A -> 1 | B -> 2
+ ^
+Error: This pattern matches values of type b
+ but a pattern was expected which matches values of type a
+# Characters 89-92:
+ Foo -> 5
+ ^^^
+Error: This pattern matches values of type 'a t
+ but a pattern was expected which matches values of type int
+# type _ t = Int : int t
+# val ky : 'a -> 'a -> 'a = <fun>
+# val test : 'a t -> 'a = <fun>
+# val test : 'a t -> int = <fun>
+# Characters 49-61:
+ function Int -> ky (1 : a) 1 (* fails *)
+ ^^^^^^^^^^^^
+Error: This expression has type a = int
+ but an expression was expected of type 'a
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# Characters 70-82:
+ let r = match x with Int -> ky (1 : a) 1 (* fails *)
+ ^^^^^^^^^^^^
+Error: This expression has type a = int
+ but an expression was expected of type 'a
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# Characters 69-81:
+ let r = match x with Int -> ky 1 (1 : a) (* fails *)
+ ^^^^^^^^^^^^
+Error: This expression has type a = int
+ but an expression was expected of type 'a
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# val test : 'a t -> int = <fun>
+# val test : 'a t -> 'a = <fun>
+# val test : 'a t -> int = <fun>
+# val test : 'a t -> 'a = <fun>
+# val test2 : 'a t -> 'a option = <fun>
+# val test2 : 'a t -> 'a option = <fun>
+# val test2 : 'a t -> 'a option = <fun>
+# Characters 152-154:
+ begin match x with Int -> u := Some 1; r := !u end;
+ ^^
+Error: This expression has type int option
+ but an expression was expected of type a option
+ Type int is not compatible with type a = int
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# val test2 : 'a t -> 'a option = <fun>
+# val test2 : 'a t -> 'a option = <fun>
+# Characters 100-101:
+ match v with Int -> let y = either 1 x in y
+ ^
+Error: This expression has type a = int
+ but an expression was expected of type 'a
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# val f : 'a t -> 'a -> 'a = <fun>
+# val f : 'a t -> 'a -> 'a = <fun>
+# val f : 'a t -> 'a -> 'a = <fun>
+# val f : 'a t -> 'a -> 'a = <fun>
+# val f : 'a t -> 'a -> 'a = <fun>
+# Characters 136-137:
+ let module M = struct type b = a let z = (y : b) end
+ ^
+Error: This expression has type a = int
+ but an expression was expected of type b = int
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# val f : 'a t -> int -> int = <fun>
+# type _ h = Has_m : < m : int > h | Has_b : < b : bool > h
+val f : 'a h -> 'a = <fun>
+# type _ j = Has_A : [ `A of int ] j | Has_B : [ `B of bool ] j
+val f : 'a j -> 'a = <fun>
+# type (_, _) eq = Eq : ('a, 'a) eq
+# Characters 5-91:
+ ....f : type a b. (a,b) eq -> (<m : a; ..> as 'c) -> (<m : b; ..> as 'c) =
+ fun Eq o -> o
+Error: The universal type variable 'b cannot be generalized:
+ it is already bound to another variable.
+# Characters 74-75:
+ fun Eq o -> o
+ ^
+Error: This expression has type < m : a; .. >
+ but an expression was expected of type < m : b; .. >
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 97-98:
+ match eq with Eq -> o ;; (* should fail *)
+ ^
+Error: This expression has type < m : a; .. >
+ but an expression was expected of type < m : b; .. >
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# val f : ('a, 'b) eq -> < m : 'a > -> < m : 'b > = <fun>
+# val int_of_bool : (bool, int) eq = Eq
+# val x : < m : bool > = <obj>
+# val y : < m : bool > * < m : int > = (<obj>, <obj>)
+# val f : ('a, int) eq -> < m : 'a > -> bool = <fun>
+# Characters 146-147:
+ let r : < m : b > = match eq with Eq -> o in (* fail with principal *)
+ ^
+Error: This expression has type < m : a >
+ but an expression was expected of type < m : b >
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 118-119:
+ let r : < m : b > = match eq with Eq -> o in (* fail *)
+ ^
+Error: This expression has type < m : a; .. >
+ but an expression was expected of type < m : b >
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 74-75:
+ fun Eq o -> o ;; (* fail *)
+ ^
+Error: This expression has type [> `A of a ]
+ but an expression was expected of type [> `A of b ]
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 90-91:
+ match eq with Eq -> v ;; (* should fail *)
+ ^
+Error: This expression has type [> `A of a ]
+ but an expression was expected of type [> `A of b ]
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 5-85:
+ ....f : type a b. (a,b) eq -> [< `A of a | `B] -> [< `A of b | `B] =
+ fun Eq o -> o..............
+Error: This definition has type
+ ('a, 'b) eq -> ([< `A of 'b & 'a | `B ] as 'c) -> 'c
+ which is less general than 'a0 'b0. ('a0, 'b0) eq -> 'c -> 'c
+# val f : ('a, 'b) eq -> [ `A of 'a | `B ] -> [ `A of 'b | `B ] = <fun>
+# val f : ('a, int) eq -> [ `A of 'a ] -> bool = <fun>
+# Characters 166-167:
+ let r : [`A of b | `B] = match eq with Eq -> o in (* fail with principal *)
+ ^
+Error: This expression has type [ `A of a | `B ]
+ but an expression was expected of type [ `A of b | `B ]
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 131-132:
+ let r : [`A of b | `B] = match eq with Eq -> o in (* fail *)
+ ^
+Error: This expression has type [> `A of a | `B ]
+ but an expression was expected of type [ `A of b | `B ]
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# type 'a t = A of int | B of bool | C of float | D of 'a
+type _ ty =
+ TE : 'a ty -> 'a array ty
+ | TA : int ty
+ | TB : bool ty
+ | TC : float ty
+ | TD : string -> bool ty
+val f : 'a ty -> 'a t -> int = <fun>
+# Characters 51-202:
+ ..match x, y with
+ | _, A z -> z
+ | _, B z -> if z then 1 else 2
+ | _, C z -> truncate z
+ | TE TC, D [|1.0|] -> 14
+ | TA, D 0 -> -1
+ | TA, D z -> z
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(TE TC, D [| |])
+val f : 'a ty -> 'a t -> int = <fun>
+# Characters 147-154:
+ | D [|1.0|], TE TC -> 14
+ ^^^^^^^
+Error: This pattern matches values of type 'a array
+ but a pattern was expected which matches values of type a
+# Characters 259-266:
+ | {left=TE TC; right=D [|1.0|]} -> 14
+ ^^^^^^^
+Error: This pattern matches values of type 'a array
+ but a pattern was expected which matches values of type a
+# Characters 92-334:
+ ..match {left=x; right=y} with
+ | {left=_; right=A z} -> z
+ | {left=_; right=B z} -> if z then 1 else 2
+ | {left=_; right=C z} -> truncate z
+ | {left=TE TC; right=D [|1.0|]} -> 14
+ | {left=TA; right=D 0} -> -1
+ | {left=TA; right=D z} -> z
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+{left=TE TC; right=D [| |]}
+type ('a, 'b) pair = { left : 'a; right : 'b; }
+val f : 'a ty -> 'a t -> int = <fun>
+# module M : sig type 'a t val eq : ('a t, 'b t) eq end
+# Characters 69-71:
+ function Eq -> Eq (* fail *)
+ ^^
+Error: This expression has type (a, a) eq
+ but an expression was expected of type (a, b) eq
+ Type a is not compatible with type b
+# val f : ('a M.t * 'a, 'b M.t * 'b) eq -> ('a, 'b) eq = <fun>
+# val f : ('a * 'a M.t, 'b * 'b M.t) eq -> ('a, 'b) eq = <fun>
+# type _ t = V1 : [ `A | `B ] t | V2 : [ `C | `D ] t
+val f : 'a t -> 'a = <fun>
+# - : [ `A | `B ] = `A
+# type _ int_foo = IF_constr : < foo : int; .. > int_foo
+type _ int_bar = IB_constr : < bar : int; .. > int_bar
+# Characters 98-99:
+ (x:<foo:int>)
+ ^
+Error: This expression has type t = < foo : int; .. >
+ but an expression was expected of type < foo : int >
+ Type $0 = < bar : int; .. > is not compatible with type < >
+ The second object type has no method bar
+# Characters 98-99:
+ (x:<foo:int;bar:int>)
+ ^
+Error: This expression has type t = < foo : int; .. >
+ but an expression was expected of type < bar : int; foo : int >
+ Type $0 = < bar : int; .. > is not compatible with type < bar : int >
+ The first object type has an abstract row, it cannot be closed
+# Characters 98-99:
+ (x:<foo:int;bar:int;..>)
+ ^
+Error: This expression has type < bar : int; foo : int; .. >
+ but an expression was expected of type 'a
+ The type constructor $1 would escape its scope
+# val g : 'a -> 'a int_foo -> 'a int_bar -> 'a = <fun>
+# val g : 'a -> 'a int_foo -> 'a int_bar -> 'a * int * int = <fun>
+# type 'a ty = Int : int -> int ty
+# val f : 'a ty -> 'a = <fun>
+# val g : 'a ty -> 'a = <fun>
+# module M : sig type _ t = int end
+# module M : sig type _ t = T : int t end
+# module N = M
+# val f : ('a, 'b) eq -> ('a, int) eq -> 'a -> 'b -> unit = <fun>
+# val f : ('a, 'b) eq -> ('b, int) eq -> 'a -> 'b -> unit = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/test.ml.reference b/testsuite/tests/typing-gadts/test.ml.reference
new file mode 100644
index 0000000000..384da5b0ee
--- /dev/null
+++ b/testsuite/tests/typing-gadts/test.ml.reference
@@ -0,0 +1,324 @@
+
+# module Exp :
+ sig
+ type _ t =
+ IntLit : int -> int t
+ | BoolLit : bool -> bool t
+ | Pair : 'a t * 'b t -> ('a * 'b) t
+ | App : ('a -> 'b) t * 'a t -> 'b t
+ | Abs : ('a -> 'b) -> ('a -> 'b) t
+ val eval : 's t -> 's
+ val discern : 'a t -> int
+ end
+# module List :
+ sig
+ type zero
+ type _ t = Nil : zero t | Cons : 'a * 'b t -> ('a * 'b) t
+ val head : ('a * 'b) t -> 'a
+ val tail : ('a * 'b) t -> 'b t
+ val length : 'a t -> int
+ end
+# Characters 196-224:
+ ......function
+ | C2 x -> x
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+C1 _
+Characters 458-529:
+ ......function
+ | Foo _ , Foo _ -> true
+ | Bar _, Bar _ -> true
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(Bar _, Foo _)
+module Nonexhaustive :
+ sig
+ type 'a u = C1 : int -> int u | C2 : bool -> bool u
+ type 'a v = C1 : int -> int v
+ val unexhaustive : 's u -> 's
+ module M : sig type t type u end
+ type 'a t = Foo : M.t -> M.t t | Bar : M.u -> M.u t
+ val same_type : 's t * 's t -> bool
+ end
+# module Exhaustive :
+ sig
+ type t = int
+ type u = bool
+ type 'a v = Foo : t -> t v | Bar : u -> u v
+ val same_type : 's v * 's v -> bool
+ end
+# Characters 34-42:
+ class c (Some x) = object method x : int = x end
+ ^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+None
+Characters 139-147:
+ class d (Just x) = object method x : int = x end
+ ^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Nothing
+module PR6862 :
+ sig
+ class c : int option -> object method x : int end
+ type _ opt = Just : 'a -> 'a opt | Nothing : 'a opt
+ class d : int opt -> object method x : int end
+ end
+# Characters 118-119:
+ let eval (D x) = x
+ ^
+Error: This expression has type $D_'a t
+ but an expression was expected of type 'a
+ The type constructor $D_'a would escape its scope
+# module Rectype :
+ sig type (_, _) t = C : ('a, 'a) t val f : ('s, 's * 's) t -> unit end
+# Characters 178-186:
+ | (IntLit _ | BoolLit _) -> ()
+ ^^^^^^^^
+Error: This pattern matches values of type int t
+ but a pattern was expected which matches values of type s t
+ Type int is not compatible with type s
+# module Polymorphic_variants :
+ sig
+ type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
+ val eval : [ `A ] * 's t -> unit
+ end
+# module Propagation :
+ sig
+ type _ t = IntLit : int -> int t | BoolLit : bool -> bool t
+ val check : 's t -> 's
+ end
+# Characters 87-88:
+ let f = function A -> 1 | B -> 2
+ ^
+Error: This variant pattern is expected to have type a
+ The constructor B does not belong to type a
+# Characters 89-92:
+ Foo -> 5
+ ^^^
+Error: This pattern matches values of type 'a t
+ but a pattern was expected which matches values of type int
+# type _ t = Int : int t
+# val ky : 'a -> 'a -> 'a = <fun>
+# val test : 'a t -> 'a = <fun>
+# val test : 'a t -> int = <fun>
+# Characters 49-61:
+ function Int -> ky (1 : a) 1 (* fails *)
+ ^^^^^^^^^^^^
+Error: This expression has type a = int
+ but an expression was expected of type 'a
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# Characters 70-82:
+ let r = match x with Int -> ky (1 : a) 1 (* fails *)
+ ^^^^^^^^^^^^
+Error: This expression has type a = int
+ but an expression was expected of type 'a
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# Characters 69-81:
+ let r = match x with Int -> ky 1 (1 : a) (* fails *)
+ ^^^^^^^^^^^^
+Error: This expression has type a = int
+ but an expression was expected of type 'a
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# val test : 'a t -> int = <fun>
+# val test : 'a t -> 'a = <fun>
+# val test : 'a t -> int = <fun>
+# val test : 'a t -> 'a = <fun>
+# val test2 : 'a t -> 'a option = <fun>
+# val test2 : 'a t -> 'a option = <fun>
+# val test2 : 'a t -> 'a option = <fun>
+# Characters 152-154:
+ begin match x with Int -> u := Some 1; r := !u end;
+ ^^
+Error: This expression has type int option
+ but an expression was expected of type a option
+ Type int is not compatible with type a = int
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# val test2 : 'a t -> 'a option = <fun>
+# val test2 : 'a t -> 'a option = <fun>
+# Characters 100-101:
+ match v with Int -> let y = either 1 x in y
+ ^
+Error: This expression has type a = int
+ but an expression was expected of type 'a
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# val f : 'a t -> 'a -> 'a = <fun>
+# val f : 'a t -> 'a -> 'a = <fun>
+# val f : 'a t -> 'a -> 'a = <fun>
+# val f : 'a t -> 'a -> 'a = <fun>
+# val f : 'a t -> 'a -> 'a = <fun>
+# Characters 136-137:
+ let module M = struct type b = a let z = (y : b) end
+ ^
+Error: This expression has type a = int
+ but an expression was expected of type b = int
+ This instance of int is ambiguous:
+ it would escape the scope of its equation
+# val f : 'a t -> int -> int = <fun>
+# type _ h = Has_m : < m : int > h | Has_b : < b : bool > h
+val f : 'a h -> 'a = <fun>
+# type _ j = Has_A : [ `A of int ] j | Has_B : [ `B of bool ] j
+val f : 'a j -> 'a = <fun>
+# type (_, _) eq = Eq : ('a, 'a) eq
+# Characters 5-91:
+ ....f : type a b. (a,b) eq -> (<m : a; ..> as 'c) -> (<m : b; ..> as 'c) =
+ fun Eq o -> o
+Error: The universal type variable 'b cannot be generalized:
+ it is already bound to another variable.
+# Characters 74-75:
+ fun Eq o -> o
+ ^
+Error: This expression has type < m : a; .. >
+ but an expression was expected of type < m : b; .. >
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 97-98:
+ match eq with Eq -> o ;; (* should fail *)
+ ^
+Error: This expression has type < m : a; .. >
+ but an expression was expected of type < m : b; .. >
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# val f : ('a, 'b) eq -> < m : 'a > -> < m : 'b > = <fun>
+# val int_of_bool : (bool, int) eq = Eq
+# val x : < m : bool > = <obj>
+# val y : < m : bool > * < m : int > = (<obj>, <obj>)
+# val f : ('a, int) eq -> < m : 'a > -> bool = <fun>
+# val f : ('a, 'b) eq -> < m : 'a > -> < m : 'b > = <fun>
+# Characters 118-119:
+ let r : < m : b > = match eq with Eq -> o in (* fail *)
+ ^
+Error: This expression has type < m : a; .. >
+ but an expression was expected of type < m : b >
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 74-75:
+ fun Eq o -> o ;; (* fail *)
+ ^
+Error: This expression has type [> `A of a ]
+ but an expression was expected of type [> `A of b ]
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 90-91:
+ match eq with Eq -> v ;; (* should fail *)
+ ^
+Error: This expression has type [> `A of a ]
+ but an expression was expected of type [> `A of b ]
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# Characters 5-85:
+ ....f : type a b. (a,b) eq -> [< `A of a | `B] -> [< `A of b | `B] =
+ fun Eq o -> o..............
+Error: This definition has type
+ ('a, 'b) eq -> ([< `A of 'b & 'a | `B ] as 'c) -> 'c
+ which is less general than 'a0 'b0. ('a0, 'b0) eq -> 'c -> 'c
+# val f : ('a, 'b) eq -> [ `A of 'a | `B ] -> [ `A of 'b | `B ] = <fun>
+# val f : ('a, int) eq -> [ `A of 'a ] -> bool = <fun>
+# val f : ('a, 'b) eq -> [ `A of 'a | `B ] -> [ `A of 'b | `B ] = <fun>
+# Characters 131-132:
+ let r : [`A of b | `B] = match eq with Eq -> o in (* fail *)
+ ^
+Error: This expression has type [> `A of a | `B ]
+ but an expression was expected of type [ `A of b | `B ]
+ Type a is not compatible with type b = a
+ This instance of a is ambiguous:
+ it would escape the scope of its equation
+# type 'a t = A of int | B of bool | C of float | D of 'a
+type _ ty =
+ TE : 'a ty -> 'a array ty
+ | TA : int ty
+ | TB : bool ty
+ | TC : float ty
+ | TD : string -> bool ty
+val f : 'a ty -> 'a t -> int = <fun>
+# Characters 51-202:
+ ..match x, y with
+ | _, A z -> z
+ | _, B z -> if z then 1 else 2
+ | _, C z -> truncate z
+ | TE TC, D [|1.0|] -> 14
+ | TA, D 0 -> -1
+ | TA, D z -> z
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(TE TC, D [| |])
+val f : 'a ty -> 'a t -> int = <fun>
+# Characters 147-154:
+ | D [|1.0|], TE TC -> 14
+ ^^^^^^^
+Error: This pattern matches values of type 'a array
+ but a pattern was expected which matches values of type a
+# Characters 259-266:
+ | {left=TE TC; right=D [|1.0|]} -> 14
+ ^^^^^^^
+Error: This pattern matches values of type 'a array
+ but a pattern was expected which matches values of type a
+# Characters 92-334:
+ ..match {left=x; right=y} with
+ | {left=_; right=A z} -> z
+ | {left=_; right=B z} -> if z then 1 else 2
+ | {left=_; right=C z} -> truncate z
+ | {left=TE TC; right=D [|1.0|]} -> 14
+ | {left=TA; right=D 0} -> -1
+ | {left=TA; right=D z} -> z
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+{left=TE TC; right=D [| |]}
+type ('a, 'b) pair = { left : 'a; right : 'b; }
+val f : 'a ty -> 'a t -> int = <fun>
+# module M : sig type 'a t val eq : ('a t, 'b t) eq end
+# Characters 69-71:
+ function Eq -> Eq (* fail *)
+ ^^
+Error: This expression has type (a, a) eq
+ but an expression was expected of type (a, b) eq
+ Type a is not compatible with type b
+# val f : ('a M.t * 'a, 'b M.t * 'b) eq -> ('a, 'b) eq = <fun>
+# val f : ('a * 'a M.t, 'b * 'b M.t) eq -> ('a, 'b) eq = <fun>
+# type _ t = V1 : [ `A | `B ] t | V2 : [ `C | `D ] t
+val f : 'a t -> 'a = <fun>
+# - : [ `A | `B ] = `A
+# type _ int_foo = IF_constr : < foo : int; .. > int_foo
+type _ int_bar = IB_constr : < bar : int; .. > int_bar
+# Characters 98-99:
+ (x:<foo:int>)
+ ^
+Error: This expression has type t = < foo : int; .. >
+ but an expression was expected of type < foo : int >
+ Type $0 = < bar : int; .. > is not compatible with type < >
+ The second object type has no method bar
+# Characters 98-99:
+ (x:<foo:int;bar:int>)
+ ^
+Error: This expression has type t = < foo : int; .. >
+ but an expression was expected of type < bar : int; foo : int >
+ Type $0 = < bar : int; .. > is not compatible with type < bar : int >
+ The first object type has an abstract row, it cannot be closed
+# Characters 98-99:
+ (x:<foo:int;bar:int;..>)
+ ^
+Error: This expression has type < bar : int; foo : int; .. >
+ but an expression was expected of type 'a
+ The type constructor $1 would escape its scope
+# val g : 'a -> 'a int_foo -> 'a int_bar -> 'a = <fun>
+# val g : 'a -> 'a int_foo -> 'a int_bar -> 'a * int * int = <fun>
+# type 'a ty = Int : int -> int ty
+# val f : 'a ty -> 'a = <fun>
+# val g : 'a ty -> 'a = <fun>
+# module M : sig type _ t = int end
+# module M : sig type _ t = T : int t end
+# module N = M
+# val f : ('a, 'b) eq -> ('a, int) eq -> 'a -> 'b -> unit = <fun>
+# val f : ('a, 'b) eq -> ('b, int) eq -> 'a -> 'b -> unit = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/unify_mb.ml b/testsuite/tests/typing-gadts/unify_mb.ml
new file mode 100644
index 0000000000..89f6921188
--- /dev/null
+++ b/testsuite/tests/typing-gadts/unify_mb.ml
@@ -0,0 +1,170 @@
+(* First-Order Unification by Structural Recursion *)
+(* Conor McBride, JFP 13(6) *)
+(* http://strictlypositive.org/publications.html *)
+
+(* This is a translation of the code part to ocaml *)
+(* Of course, we do not prove other properties, not even termination *)
+
+(* 2.2 Inductive Families *)
+
+type zero = Zero
+type _ succ = Succ
+type _ nat =
+ | NZ : zero nat
+ | NS : 'a nat -> 'a succ nat
+
+type _ fin =
+ | FZ : 'a succ fin
+ | FS : 'a fin -> 'a succ fin
+
+(* We cannot define
+ val empty : zero fin -> 'a
+ because we cannot write an empty pattern matching.
+ This might be useful to have *)
+
+(* In place, prove that the parameter is 'a succ *)
+type _ is_succ = IS : 'a succ is_succ
+
+let fin_succ : type n. n fin -> n is_succ = function
+ | FZ -> IS
+ | FS _ -> IS
+;;
+
+(* 3 First-Order Terms, Renaming and Substitution *)
+
+type 'a term =
+ | Var of 'a fin
+ | Leaf
+ | Fork of 'a term * 'a term
+
+let var x = Var x
+
+let lift r : 'm fin -> 'n term = fun x -> Var (r x)
+
+let rec pre_subst f = function
+ | Var x -> f x
+ | Leaf -> Leaf
+ | Fork (t1, t2) -> Fork (pre_subst f t1, pre_subst f t2)
+
+let comp_subst f g (x : 'a fin) = pre_subst f (g x)
+(* val comp_subst :
+ ('b fin -> 'c term) -> ('a fin -> 'b term) -> 'a fin -> 'c term *)
+;;
+
+(* 4 The Occur-Check, through thick and thin *)
+
+let rec thin : type n. n succ fin -> n fin -> n succ fin =
+ fun x y -> match x, y with
+ | FZ, y -> FS y
+ | FS x, FZ -> FZ
+ | FS x, FS y -> FS (thin x y)
+
+let bind t f =
+ match t with
+ | None -> None
+ | Some x -> f x
+(* val bind : 'a option -> ('a -> 'b option) -> 'b option *)
+
+let rec thick : type n. n succ fin -> n succ fin -> n fin option =
+ fun x y -> match x, y with
+ | FZ, FZ -> None
+ | FZ, FS y -> Some y
+ | FS x, FZ -> let IS = fin_succ x in Some FZ
+ | FS x, FS y ->
+ let IS = fin_succ x in bind (thick x y) (fun x -> Some (FS x))
+
+let rec check : type n. n succ fin -> n succ term -> n term option =
+ fun x t -> match t with
+ | Var y -> bind (thick x y) (fun x -> Some (Var x))
+ | Leaf -> Some Leaf
+ | Fork (t1, t2) ->
+ bind (check x t1) (fun t1 ->
+ bind (check x t2) (fun t2 -> Some (Fork (t1, t2))))
+
+let subst_var x t' y =
+ match thick x y with
+ | None -> t'
+ | Some y' -> Var y'
+(* val subst_var : 'a succ fin -> 'a term -> 'a succ fin -> 'a term *)
+
+let subst x t' = pre_subst (subst_var x t')
+(* val subst : 'a succ fin -> 'a term -> 'a succ term -> 'a term *)
+;;
+
+(* 5 A Refinement of Substitution *)
+
+type (_,_) alist =
+ | Anil : ('n,'n) alist
+ | Asnoc : ('m,'n) alist * 'm term * 'm succ fin -> ('m succ, 'n) alist
+
+let rec sub : type m n. (m,n) alist -> m fin -> n term = function
+ | Anil -> var
+ | Asnoc (s, t, x) -> comp_subst (sub s) (subst_var x t)
+
+let rec append : type m n l. (m,n) alist -> (l,m) alist -> (l,n) alist =
+ fun r s -> match s with
+ | Anil -> r
+ | Asnoc (s, t, x) -> Asnoc (append r s, t, x)
+
+type _ ealist = EAlist : ('a,'b) alist -> 'a ealist
+
+let asnoc a t' x = EAlist (Asnoc (a, t', x))
+
+(* Extra work: we need sub to work on ealist too, for examples *)
+let rec weaken_fin : type n. n fin -> n succ fin = function
+ | FZ -> FZ
+ | FS x -> FS (weaken_fin x)
+
+let weaken_term t = pre_subst (fun x -> Var (weaken_fin x)) t
+
+let rec weaken_alist : type m n. (m, n) alist -> (m succ, n succ) alist =
+ function
+ | Anil -> Anil
+ | Asnoc (s, t, x) -> Asnoc (weaken_alist s, weaken_term t, weaken_fin x)
+
+let rec sub' : type m. m ealist -> m fin -> m term = function
+ | EAlist Anil -> var
+ | EAlist (Asnoc (s, t, x)) ->
+ comp_subst (sub' (EAlist (weaken_alist s)))
+ (fun t' -> weaken_term (subst_var x t t'))
+
+let subst' d = pre_subst (sub' d)
+(* val subst' : 'a ealist -> 'a term -> 'a term *)
+;;
+
+(* 6 First-Order Unification *)
+
+let flex_flex x y =
+ match thick x y with
+ | Some y' -> asnoc Anil (Var y') x
+ | None -> EAlist Anil
+(* val flex_flex : 'a succ fin -> 'a succ fin -> 'a succ ealist *)
+
+let flex_rigid x t =
+ bind (check x t) (fun t' -> Some (asnoc Anil t' x))
+(* val flex_rigid : 'a succ fin -> 'a succ term -> 'a succ ealist option *)
+
+let rec amgu : type m. m term -> m term -> m ealist -> m ealist option =
+ fun s t acc -> match s, t, acc with
+ | Leaf, Leaf, _ -> Some acc
+ | Leaf, Fork _, _ -> None
+ | Fork _, Leaf, _ -> None
+ | Fork (s1, s2), Fork (t1, t2), _ ->
+ bind (amgu s1 t1 acc) (amgu s2 t2)
+ | Var x, Var y, EAlist Anil -> let IS = fin_succ x in Some (flex_flex x y)
+ | Var x, t, EAlist Anil -> let IS = fin_succ x in flex_rigid x t
+ | t, Var x, EAlist Anil -> let IS = fin_succ x in flex_rigid x t
+ | s, t, EAlist(Asnoc(d,r,z)) ->
+ bind (amgu (subst z r s) (subst z r t) (EAlist d))
+ (fun (EAlist d) -> Some (asnoc d r z))
+
+let mgu s t = amgu s t (EAlist Anil)
+(* val mgu : 'a term -> 'a term -> 'a ealist option *)
+;;
+
+let s = Fork (Var FZ, Fork (Var (FS (FS FZ)), Leaf))
+let t = Fork (Var (FS FZ), Var (FS FZ))
+let d = match mgu s t with Some x -> x | None -> failwith "mgu"
+let s' = subst' d s
+let t' = subst' d t
+;;
diff --git a/testsuite/tests/typing-gadts/unify_mb.ml.principal.reference b/testsuite/tests/typing-gadts/unify_mb.ml.principal.reference
new file mode 100644
index 0000000000..90e69dc0f6
--- /dev/null
+++ b/testsuite/tests/typing-gadts/unify_mb.ml.principal.reference
@@ -0,0 +1,45 @@
+
+# * * * type zero = Zero
+type _ succ = Succ
+type _ nat = NZ : zero nat | NS : 'a nat -> 'a succ nat
+type _ fin = FZ : 'a succ fin | FS : 'a fin -> 'a succ fin
+type _ is_succ = IS : 'a succ is_succ
+val fin_succ : 'n fin -> 'n is_succ = <fun>
+# * type 'a term = Var of 'a fin | Leaf | Fork of 'a term * 'a term
+val var : 'a fin -> 'a term = <fun>
+val lift : ('m fin -> 'n fin) -> 'm fin -> 'n term = <fun>
+val pre_subst : ('a fin -> 'b term) -> 'a term -> 'b term = <fun>
+val comp_subst :
+ ('b fin -> 'c term) -> ('a fin -> 'b term) -> 'a fin -> 'c term = <fun>
+# val thin : 'n succ fin -> 'n fin -> 'n succ fin = <fun>
+val bind : 'a option -> ('a -> 'b option) -> 'b option = <fun>
+val thick : 'n succ fin -> 'n succ fin -> 'n fin option = <fun>
+val check : 'n succ fin -> 'n succ term -> 'n term option = <fun>
+val subst_var : 'a succ fin -> 'a term -> 'a succ fin -> 'a term = <fun>
+val subst : 'a succ fin -> 'a term -> 'a succ term -> 'a term = <fun>
+# type (_, _) alist =
+ Anil : ('n, 'n) alist
+ | Asnoc : ('m, 'n) alist * 'm term * 'm succ fin -> ('m succ, 'n) alist
+val sub : ('m, 'n) alist -> 'm fin -> 'n term = <fun>
+val append : ('m, 'n) alist -> ('l, 'm) alist -> ('l, 'n) alist = <fun>
+type _ ealist = EAlist : ('a, 'b) alist -> 'a ealist
+val asnoc : ('a, 'b) alist -> 'a term -> 'a succ fin -> 'a succ ealist =
+ <fun>
+val weaken_fin : 'n fin -> 'n succ fin = <fun>
+val weaken_term : 'a term -> 'a succ term = <fun>
+val weaken_alist : ('m, 'n) alist -> ('m succ, 'n succ) alist = <fun>
+val sub' : 'm ealist -> 'm fin -> 'm term = <fun>
+val subst' : 'a ealist -> 'a term -> 'a term = <fun>
+# val flex_flex : 'a succ fin -> 'a succ fin -> 'a succ ealist = <fun>
+val flex_rigid : 'a succ fin -> 'a succ term -> 'a succ ealist option = <fun>
+val amgu : 'm term -> 'm term -> 'm ealist -> 'm ealist option = <fun>
+val mgu : 'a term -> 'a term -> 'a ealist option = <fun>
+# val s : 'a succ succ succ term = Fork (Var FZ, Fork (Var (FS (FS FZ)), Leaf))
+val t : 'a succ succ term = Fork (Var (FS FZ), Var (FS FZ))
+val d : '_a succ succ succ ealist =
+ EAlist (Asnoc (Asnoc (Anil, Fork (Var FZ, Leaf), FZ), Var FZ, FZ))
+val s' : '_a succ succ succ term =
+ Fork (Fork (Var FZ, Leaf), Fork (Var FZ, Leaf))
+val t' : '_a succ succ succ term =
+ Fork (Fork (Var FZ, Leaf), Fork (Var FZ, Leaf))
+#
diff --git a/testsuite/tests/typing-gadts/unify_mb.ml.reference b/testsuite/tests/typing-gadts/unify_mb.ml.reference
new file mode 100644
index 0000000000..90e69dc0f6
--- /dev/null
+++ b/testsuite/tests/typing-gadts/unify_mb.ml.reference
@@ -0,0 +1,45 @@
+
+# * * * type zero = Zero
+type _ succ = Succ
+type _ nat = NZ : zero nat | NS : 'a nat -> 'a succ nat
+type _ fin = FZ : 'a succ fin | FS : 'a fin -> 'a succ fin
+type _ is_succ = IS : 'a succ is_succ
+val fin_succ : 'n fin -> 'n is_succ = <fun>
+# * type 'a term = Var of 'a fin | Leaf | Fork of 'a term * 'a term
+val var : 'a fin -> 'a term = <fun>
+val lift : ('m fin -> 'n fin) -> 'm fin -> 'n term = <fun>
+val pre_subst : ('a fin -> 'b term) -> 'a term -> 'b term = <fun>
+val comp_subst :
+ ('b fin -> 'c term) -> ('a fin -> 'b term) -> 'a fin -> 'c term = <fun>
+# val thin : 'n succ fin -> 'n fin -> 'n succ fin = <fun>
+val bind : 'a option -> ('a -> 'b option) -> 'b option = <fun>
+val thick : 'n succ fin -> 'n succ fin -> 'n fin option = <fun>
+val check : 'n succ fin -> 'n succ term -> 'n term option = <fun>
+val subst_var : 'a succ fin -> 'a term -> 'a succ fin -> 'a term = <fun>
+val subst : 'a succ fin -> 'a term -> 'a succ term -> 'a term = <fun>
+# type (_, _) alist =
+ Anil : ('n, 'n) alist
+ | Asnoc : ('m, 'n) alist * 'm term * 'm succ fin -> ('m succ, 'n) alist
+val sub : ('m, 'n) alist -> 'm fin -> 'n term = <fun>
+val append : ('m, 'n) alist -> ('l, 'm) alist -> ('l, 'n) alist = <fun>
+type _ ealist = EAlist : ('a, 'b) alist -> 'a ealist
+val asnoc : ('a, 'b) alist -> 'a term -> 'a succ fin -> 'a succ ealist =
+ <fun>
+val weaken_fin : 'n fin -> 'n succ fin = <fun>
+val weaken_term : 'a term -> 'a succ term = <fun>
+val weaken_alist : ('m, 'n) alist -> ('m succ, 'n succ) alist = <fun>
+val sub' : 'm ealist -> 'm fin -> 'm term = <fun>
+val subst' : 'a ealist -> 'a term -> 'a term = <fun>
+# val flex_flex : 'a succ fin -> 'a succ fin -> 'a succ ealist = <fun>
+val flex_rigid : 'a succ fin -> 'a succ term -> 'a succ ealist option = <fun>
+val amgu : 'm term -> 'm term -> 'm ealist -> 'm ealist option = <fun>
+val mgu : 'a term -> 'a term -> 'a ealist option = <fun>
+# val s : 'a succ succ succ term = Fork (Var FZ, Fork (Var (FS (FS FZ)), Leaf))
+val t : 'a succ succ term = Fork (Var (FS FZ), Var (FS FZ))
+val d : '_a succ succ succ ealist =
+ EAlist (Asnoc (Asnoc (Anil, Fork (Var FZ, Leaf), FZ), Var FZ, FZ))
+val s' : '_a succ succ succ term =
+ Fork (Fork (Var FZ, Leaf), Fork (Var FZ, Leaf))
+val t' : '_a succ succ succ term =
+ Fork (Fork (Var FZ, Leaf), Fork (Var FZ, Leaf))
+#
diff --git a/testsuite/tests/typing-gadts/yallop_bugs.ml b/testsuite/tests/typing-gadts/yallop_bugs.ml
new file mode 100644
index 0000000000..983822bcc8
--- /dev/null
+++ b/testsuite/tests/typing-gadts/yallop_bugs.ml
@@ -0,0 +1,45 @@
+(* Injectivity *)
+
+type (_, _) eq = Refl : ('a, 'a) eq
+
+let magic : 'a 'b. 'a -> 'b =
+ fun (type a b) (x : a) ->
+ let module M =
+ (functor (T : sig type 'a t end) ->
+ struct
+ let f (Refl : (a T.t, b T.t) eq) = (x :> b)
+ end)
+ (struct type 'a t = unit end)
+ in M.f Refl
+;;
+
+(* Variance and subtyping *)
+
+type (_, +_) eq = Refl : ('a, 'a) eq
+
+let magic : 'a 'b. 'a -> 'b =
+ fun (type a) (type b) (x : a) ->
+ let bad_proof (type a) =
+ (Refl : (< m : a>, <m : a>) eq :> (<m : a>, < >) eq) in
+ let downcast : type a. (a, < >) eq -> < > -> a =
+ fun (type a) (Refl : (a, < >) eq) (s : < >) -> (s :> a) in
+ (downcast bad_proof ((object method m = x end) :> < >)) # m
+;;
+
+(* Record patterns *)
+
+type _ t =
+ | IntLit : int t
+ | BoolLit : bool t
+
+let check : type s . s t * s -> bool = function
+ | BoolLit, false -> false
+ | IntLit , 6 -> false
+;;
+
+type ('a, 'b) pair = { fst : 'a; snd : 'b }
+
+let check : type s . (s t, s) pair -> bool = function
+ | {fst = BoolLit; snd = false} -> false
+ | {fst = IntLit ; snd = 6} -> false
+;;
diff --git a/testsuite/tests/typing-gadts/yallop_bugs.ml.principal.reference b/testsuite/tests/typing-gadts/yallop_bugs.ml.principal.reference
new file mode 100644
index 0000000000..accbebf428
--- /dev/null
+++ b/testsuite/tests/typing-gadts/yallop_bugs.ml.principal.reference
@@ -0,0 +1,29 @@
+
+# Characters 233-241:
+ let f (Refl : (a T.t, b T.t) eq) = (x :> b)
+ ^^^^^^^^
+Error: Type a is not a subtype of b
+# Characters 31-67:
+ type (_, +_) eq = Refl : ('a, 'a) eq
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this GADT definition, the variance of some parameter
+ cannot be checked
+# Characters 115-175:
+ .......................................function
+ | BoolLit, false -> false
+ | IntLit , 6 -> false
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(IntLit, 0)
+type _ t = IntLit : int t | BoolLit : bool t
+val check : 's t * 's -> bool = <fun>
+# Characters 91-180:
+ .............................................function
+ | {fst = BoolLit; snd = false} -> false
+ | {fst = IntLit ; snd = 6} -> false
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+{fst=IntLit; snd=0}
+type ('a, 'b) pair = { fst : 'a; snd : 'b; }
+val check : ('s t, 's) pair -> bool = <fun>
+#
diff --git a/testsuite/tests/typing-gadts/yallop_bugs.ml.reference b/testsuite/tests/typing-gadts/yallop_bugs.ml.reference
new file mode 100644
index 0000000000..accbebf428
--- /dev/null
+++ b/testsuite/tests/typing-gadts/yallop_bugs.ml.reference
@@ -0,0 +1,29 @@
+
+# Characters 233-241:
+ let f (Refl : (a T.t, b T.t) eq) = (x :> b)
+ ^^^^^^^^
+Error: Type a is not a subtype of b
+# Characters 31-67:
+ type (_, +_) eq = Refl : ('a, 'a) eq
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In this GADT definition, the variance of some parameter
+ cannot be checked
+# Characters 115-175:
+ .......................................function
+ | BoolLit, false -> false
+ | IntLit , 6 -> false
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(IntLit, 0)
+type _ t = IntLit : int t | BoolLit : bool t
+val check : 's t * 's -> bool = <fun>
+# Characters 91-180:
+ .............................................function
+ | {fst = BoolLit; snd = false} -> false
+ | {fst = IntLit ; snd = 6} -> false
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+{fst=IntLit; snd=0}
+type ('a, 'b) pair = { fst : 'a; snd : 'b; }
+val check : ('s t, 's) pair -> bool = <fun>
+#
diff --git a/testsuite/tests/typing-implicit_unpack/Makefile b/testsuite/tests/typing-implicit_unpack/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-implicit_unpack/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-implicit_unpack/implicit_unpack.ml b/testsuite/tests/typing-implicit_unpack/implicit_unpack.ml
new file mode 100644
index 0000000000..82fca3a5d0
--- /dev/null
+++ b/testsuite/tests/typing-implicit_unpack/implicit_unpack.ml
@@ -0,0 +1,165 @@
+(*
+ Implicit unpack allows to omit the signature in (val ...) expressions.
+
+ It also adds (module M : S) and (module M) patterns, relying on
+ implicit (val ...) for the implementation. Such patterns can only
+ be used in function definition, match clauses, and let ... in.
+
+ New: implicit pack is also supported, and you only need to be able
+ to infer the the module type path from the context.
+ *)
+(* ocaml -principal *)
+
+(* Use a module pattern *)
+let sort (type s) (module Set : Set.S with type elt = s) l =
+ Set.elements (List.fold_right Set.add l Set.empty)
+
+(* No real improvement here? *)
+let make_set (type s) cmp : (module Set.S with type elt = s) =
+ (module Set.Make (struct type t = s let compare = cmp end))
+
+(* No type annotation here *)
+let sort_cmp (type s) cmp =
+ sort (module Set.Make (struct type t = s let compare = cmp end))
+
+module type S = sig type t val x : t end;;
+let f (module M : S with type t = int) = M.x;;
+let f (module M : S with type t = 'a) = M.x;; (* Error *)
+let f (type a) (module M : S with type t = a) = M.x;;
+f (module struct type t = int let x = 1 end);;
+
+type 'a s = {s: (module S with type t = 'a)};;
+{s=(module struct type t = int let x = 1 end)};;
+let f {s=(module M)} = M.x;; (* Error *)
+let f (type a) ({s=(module M)} : a s) = M.x;;
+
+type s = {s: (module S with type t = int)};;
+let f {s=(module M)} = M.x;;
+let f {s=(module M)} {s=(module N)} = M.x + N.x;;
+
+module type S = sig val x : int end;;
+let f (module M : S) y (module N : S) = M.x + y + N.x;;
+let m = (module struct let x = 3 end);; (* Error *)
+let m = (module struct let x = 3 end : S);;
+f m 1 m;;
+f m 1 (module struct let x = 2 end);;
+
+let (module M) = m in M.x;;
+let (module M) = m;; (* Error: only allowed in [let .. in] *)
+class c = let (module M) = m in object end;; (* Error again *)
+module M = (val m);;
+
+module type S' = sig val f : int -> int end;;
+(* Even works with recursion, but must be fully explicit *)
+let rec (module M : S') =
+ (module struct let f n = if n <= 0 then 1 else n * M.f (n-1) end : S')
+in M.f 3;;
+
+(* Subtyping *)
+
+module type S = sig type t type u val x : t * u end
+let f (l : (module S with type t = int and type u = bool) list) =
+ (l :> (module S with type u = bool) list)
+
+(* GADTs from the manual *)
+(* the only modification is in to_string *)
+
+module TypEq : sig
+ type ('a, 'b) t
+ val apply: ('a, 'b) t -> 'a -> 'b
+ val refl: ('a, 'a) t
+ val sym: ('a, 'b) t -> ('b, 'a) t
+end = struct
+ type ('a, 'b) t = ('a -> 'b) * ('b -> 'a)
+ let refl = (fun x -> x), (fun x -> x)
+ let apply (f, _) x = f x
+ let sym (f, g) = (g, f)
+end
+
+module rec Typ : sig
+ module type PAIR = sig
+ type t and t1 and t2
+ val eq: (t, t1 * t2) TypEq.t
+ val t1: t1 Typ.typ
+ val t2: t2 Typ.typ
+ end
+
+ type 'a typ =
+ | Int of ('a, int) TypEq.t
+ | String of ('a, string) TypEq.t
+ | Pair of (module PAIR with type t = 'a)
+end = Typ
+
+let int = Typ.Int TypEq.refl
+
+let str = Typ.String TypEq.refl
+
+let pair (type s1) (type s2) t1 t2 =
+ let module P = struct
+ type t = s1 * s2
+ type t1 = s1
+ type t2 = s2
+ let eq = TypEq.refl
+ let t1 = t1
+ let t2 = t2
+ end in
+ Typ.Pair (module P)
+
+open Typ
+let rec to_string: 'a. 'a Typ.typ -> 'a -> string =
+ fun (type s) t x ->
+ match (t : s typ) with
+ | Int eq -> string_of_int (TypEq.apply eq x)
+ | String eq -> Printf.sprintf "%S" (TypEq.apply eq x)
+ | Pair (module P) ->
+ let (x1, x2) = TypEq.apply P.eq x in
+ Printf.sprintf "(%s,%s)" (to_string P.t1 x1) (to_string P.t2 x2)
+
+(* Wrapping maps *)
+module type MapT = sig
+ include Map.S
+ type data
+ type map
+ val of_t : data t -> map
+ val to_t : map -> data t
+end
+
+type ('k,'d,'m) map =
+ (module MapT with type key = 'k and type data = 'd and type map = 'm)
+
+let add (type k) (type d) (type m) (m:(k,d,m) map) x y s =
+ let module M =
+ (val m:MapT with type key = k and type data = d and type map = m) in
+ M.of_t (M.add x y (M.to_t s))
+
+module SSMap = struct
+ include Map.Make(String)
+ type data = string
+ type map = data t
+ let of_t x = x
+ let to_t x = x
+end
+
+let ssmap =
+ (module SSMap:
+ MapT with type key = string and type data = string and type map = SSMap.map)
+;;
+
+let ssmap =
+ (module struct include SSMap end :
+ MapT with type key = string and type data = string and type map = SSMap.map)
+;;
+
+let ssmap =
+ (let module S = struct include SSMap end in (module S) :
+ (module
+ MapT with type key = string and type data = string and type map = SSMap.map))
+;;
+
+let ssmap =
+ (module SSMap: MapT with type key = _ and type data = _ and type map = _)
+;;
+
+let ssmap : (_,_,_) map = (module SSMap);;
+
+add ssmap;;
diff --git a/testsuite/tests/typing-implicit_unpack/implicit_unpack.ml.reference b/testsuite/tests/typing-implicit_unpack/implicit_unpack.ml.reference
new file mode 100644
index 0000000000..32c49a2961
--- /dev/null
+++ b/testsuite/tests/typing-implicit_unpack/implicit_unpack.ml.reference
@@ -0,0 +1,166 @@
+
+# * * * * * * * * * val sort : (module Set.S with type elt = 'a) -> 'a list -> 'a list = <fun>
+val make_set : ('a -> 'a -> int) -> (module Set.S with type elt = 'a) = <fun>
+val sort_cmp : ('a -> 'a -> int) -> 'a list -> 'a list = <fun>
+module type S = sig type t val x : t end
+# val f : (module S with type t = int) -> int = <fun>
+# Characters 6-37:
+ let f (module M : S with type t = 'a) = M.x;; (* Error *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: The type of this packed module contains variables:
+(module S with type t = 'a)
+# val f : (module S with type t = 'a) -> 'a = <fun>
+# - : int = 1
+# type 'a s = { s : (module S with type t = 'a); }
+# - : int s = {s = <module>}
+# Characters 9-19:
+ let f {s=(module M)} = M.x;; (* Error *)
+ ^^^^^^^^^^
+Error: The type of this packed module contains variables:
+(module S with type t = 'a)
+# val f : 'a s -> 'a = <fun>
+# type s = { s : (module S with type t = int); }
+# val f : s -> int = <fun>
+# val f : s -> s -> int = <fun>
+# module type S = sig val x : int end
+# val f : (module S) -> int -> (module S) -> int = <fun>
+# Characters 8-37:
+ let m = (module struct let x = 3 end);; (* Error *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: The signature for this packaged module couldn't be inferred.
+# val m : (module S) = <module>
+# - : int = 7
+# - : int = 6
+# - : int = 3
+# Characters 4-14:
+ let (module M) = m;; (* Error: only allowed in [let .. in] *)
+ ^^^^^^^^^^
+Error: Modules are not allowed in this pattern.
+# Characters 14-24:
+ class c = let (module M) = m in object end;; (* Error again *)
+ ^^^^^^^^^^
+Error: Modules are not allowed in this pattern.
+# module M : S
+# module type S' = sig val f : int -> int end
+# - : int = 6
+# module type S = sig type t type u val x : t * u end
+val f :
+ (module S with type t = int and type u = bool) list ->
+ (module S with type u = bool) list = <fun>
+module TypEq :
+ sig
+ type ('a, 'b) t
+ val apply : ('a, 'b) t -> 'a -> 'b
+ val refl : ('a, 'a) t
+ val sym : ('a, 'b) t -> ('b, 'a) t
+ end
+module rec Typ :
+ sig
+ module type PAIR =
+ sig
+ type t
+ and t1
+ and t2
+ val eq : (t, t1 * t2) TypEq.t
+ val t1 : t1 Typ.typ
+ val t2 : t2 Typ.typ
+ end
+ type 'a typ =
+ Int of ('a, int) TypEq.t
+ | String of ('a, string) TypEq.t
+ | Pair of (module PAIR with type t = 'a)
+ end
+val int : int Typ.typ = Int <abstr>
+val str : string Typ.typ = String <abstr>
+val pair : 'a Typ.typ -> 'b Typ.typ -> ('a * 'b) Typ.typ = <fun>
+val to_string : 'a Typ.typ -> 'a -> string = <fun>
+module type MapT =
+ sig
+ type key
+ type +'a t
+ val empty : 'a t
+ val is_empty : 'a t -> bool
+ val mem : key -> 'a t -> bool
+ val add : key -> 'a -> 'a t -> 'a t
+ val singleton : key -> 'a -> 'a t
+ val remove : key -> 'a t -> 'a t
+ val merge :
+ (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
+ val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
+ val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
+ val iter : (key -> 'a -> unit) -> 'a t -> unit
+ val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ val for_all : (key -> 'a -> bool) -> 'a t -> bool
+ val exists : (key -> 'a -> bool) -> 'a t -> bool
+ val filter : (key -> 'a -> bool) -> 'a t -> 'a t
+ val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
+ val cardinal : 'a t -> int
+ val bindings : 'a t -> (key * 'a) list
+ val min_binding : 'a t -> key * 'a
+ val max_binding : 'a t -> key * 'a
+ val choose : 'a t -> key * 'a
+ val split : key -> 'a t -> 'a t * 'a option * 'a t
+ val find : key -> 'a t -> 'a
+ val map : ('a -> 'b) -> 'a t -> 'b t
+ val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
+ type data
+ type map
+ val of_t : data t -> map
+ val to_t : map -> data t
+ end
+type ('k, 'd, 'm) map =
+ (module MapT with type data = 'd and type key = 'k and type map = 'm)
+val add : ('a, 'b, 'c) map -> 'a -> 'b -> 'c -> 'c = <fun>
+module SSMap :
+ sig
+ type key = String.t
+ type 'a t = 'a Map.Make(String).t
+ val empty : 'a t
+ val is_empty : 'a t -> bool
+ val mem : key -> 'a t -> bool
+ val add : key -> 'a -> 'a t -> 'a t
+ val singleton : key -> 'a -> 'a t
+ val remove : key -> 'a t -> 'a t
+ val merge :
+ (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t
+ val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
+ val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
+ val iter : (key -> 'a -> unit) -> 'a t -> unit
+ val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ val for_all : (key -> 'a -> bool) -> 'a t -> bool
+ val exists : (key -> 'a -> bool) -> 'a t -> bool
+ val filter : (key -> 'a -> bool) -> 'a t -> 'a t
+ val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
+ val cardinal : 'a t -> int
+ val bindings : 'a t -> (key * 'a) list
+ val min_binding : 'a t -> key * 'a
+ val max_binding : 'a t -> key * 'a
+ val choose : 'a t -> key * 'a
+ val split : key -> 'a t -> 'a t * 'a option * 'a t
+ val find : key -> 'a t -> 'a
+ val map : ('a -> 'b) -> 'a t -> 'b t
+ val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
+ type data = string
+ type map = data t
+ val of_t : 'a -> 'a
+ val to_t : 'a -> 'a
+ end
+val ssmap :
+ (module MapT with type data = string and type key = string and type map =
+ SSMap.map) =
+ <module>
+# val ssmap :
+ (module MapT with type data = string and type key = string and type map =
+ SSMap.map) =
+ <module>
+# val ssmap :
+ (module MapT with type data = string and type key = string and type map =
+ SSMap.map) =
+ <module>
+# val ssmap :
+ (module MapT with type data = SSMap.data and type key = SSMap.key and type map =
+ SSMap.map) =
+ <module>
+# val ssmap : (SSMap.key, SSMap.data, SSMap.map) map = <module>
+# - : SSMap.key -> SSMap.data -> SSMap.map -> SSMap.map = <fun>
+#
diff --git a/testsuite/tests/typing-labels/Makefile b/testsuite/tests/typing-labels/Makefile
new file mode 100644
index 0000000000..299656b246
--- /dev/null
+++ b/testsuite/tests/typing-labels/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-labels/mixin.ml b/testsuite/tests/typing-labels/mixin.ml
new file mode 100644
index 0000000000..5ca686a118
--- /dev/null
+++ b/testsuite/tests/typing-labels/mixin.ml
@@ -0,0 +1,155 @@
+open StdLabels
+open MoreLabels
+
+(* Use maps for substitutions and sets for free variables *)
+
+module Subst = Map.Make(struct type t = string let compare = compare end)
+module Names = Set.Make(struct type t = string let compare = compare end)
+
+
+(* Variables are common to lambda and expr *)
+
+type var = [`Var of string]
+
+let subst_var ~subst : var -> _ =
+ function `Var s as x ->
+ try Subst.find s subst
+ with Not_found -> x
+
+let free_var : var -> _ = function `Var s -> Names.singleton s
+
+
+(* The lambda language: free variables, substitutions, and evaluation *)
+
+type 'a lambda = [`Var of string | `Abs of string * 'a | `App of 'a * 'a]
+
+let free_lambda ~free_rec : _ lambda -> _ = function
+ #var as x -> free_var x
+ | `Abs (s, t) -> Names.remove s (free_rec t)
+ | `App (t1, t2) -> Names.union (free_rec t1) (free_rec t2)
+
+let map_lambda ~map_rec : _ lambda -> _ = function
+ #var as x -> x
+ | `Abs (s, t) as l ->
+ let t' = map_rec t in
+ if t == t' then l else `Abs(s, t')
+ | `App (t1, t2) as l ->
+ let t'1 = map_rec t1 and t'2 = map_rec t2 in
+ if t'1 == t1 && t'2 == t2 then l else `App (t'1, t'2)
+
+let next_id =
+ let current = ref 3 in
+ fun () -> incr current; !current
+
+let subst_lambda ~subst_rec ~free ~subst : _ lambda -> _ = function
+ #var as x -> subst_var ~subst x
+ | `Abs(s, t) as l ->
+ let used = free t in
+ let used_expr =
+ Subst.fold subst ~init:[]
+ ~f:(fun ~key ~data acc ->
+ if Names.mem s used then data::acc else acc) in
+ if List.exists used_expr ~f:(fun t -> Names.mem s (free t)) then
+ let name = s ^ string_of_int (next_id ()) in
+ `Abs(name,
+ subst_rec ~subst:(Subst.add ~key:s ~data:(`Var name) subst) t)
+ else
+ map_lambda ~map_rec:(subst_rec ~subst:(Subst.remove s subst)) l
+ | `App _ as l ->
+ map_lambda ~map_rec:(subst_rec ~subst) l
+
+let eval_lambda ~eval_rec ~subst l =
+ match map_lambda ~map_rec:eval_rec l with
+ `App(`Abs(s,t1), t2) ->
+ eval_rec (subst ~subst:(Subst.add ~key:s ~data:t2 Subst.empty) t1)
+ | t -> t
+
+(* Specialized versions to use on lambda *)
+
+let rec free1 x = free_lambda ~free_rec:free1 x
+let rec subst1 ~subst = subst_lambda ~subst_rec:subst1 ~free:free1 ~subst
+let rec eval1 x = eval_lambda ~eval_rec:eval1 ~subst:subst1 x
+
+
+(* The expr language of arithmetic expressions *)
+
+type 'a expr =
+ [`Var of string | `Num of int | `Add of 'a * 'a
+ | `Neg of 'a | `Mult of 'a * 'a]
+
+let free_expr ~free_rec : _ expr -> _ = function
+ #var as x -> free_var x
+ | `Num _ -> Names.empty
+ | `Add(x, y) -> Names.union (free_rec x) (free_rec y)
+ | `Neg x -> free_rec x
+ | `Mult(x, y) -> Names.union (free_rec x) (free_rec y)
+
+(* Here map_expr helps a lot *)
+let map_expr ~map_rec : _ expr -> _ = function
+ #var as x -> x
+ | `Num _ as x -> x
+ | `Add(x, y) as e ->
+ let x' = map_rec x and y' = map_rec y in
+ if x == x' && y == y' then e
+ else `Add(x', y')
+ | `Neg x as e ->
+ let x' = map_rec x in
+ if x == x' then e else `Neg x'
+ | `Mult(x, y) as e ->
+ let x' = map_rec x and y' = map_rec y in
+ if x == x' && y == y' then e
+ else `Mult(x', y')
+
+let subst_expr ~subst_rec ~subst : _ expr -> _ = function
+ #var as x -> subst_var ~subst x
+ | #expr as e -> map_expr ~map_rec:(subst_rec ~subst) e
+
+let eval_expr ~eval_rec e =
+ match map_expr ~map_rec:eval_rec e with
+ `Add(`Num m, `Num n) -> `Num (m+n)
+ | `Neg(`Num n) -> `Num (-n)
+ | `Mult(`Num m, `Num n) -> `Num (m*n)
+ | #expr as e -> e
+
+(* Specialized versions *)
+
+let rec free2 x = free_expr ~free_rec:free2 x
+let rec subst2 ~subst = subst_expr ~subst_rec:subst2 ~subst
+let rec eval2 x = eval_expr ~eval_rec:eval2 x
+
+
+(* The lexpr language, reunion of lambda and expr *)
+
+type lexpr =
+ [ `Var of string | `Abs of string * lexpr | `App of lexpr * lexpr
+ | `Num of int | `Add of lexpr * lexpr | `Neg of lexpr
+ | `Mult of lexpr * lexpr ]
+
+let rec free : lexpr -> _ = function
+ #lambda as x -> free_lambda ~free_rec:free x
+ | #expr as x -> free_expr ~free_rec:free x
+
+let rec subst ~subst:s : lexpr -> _ = function
+ #lambda as x -> subst_lambda ~subst_rec:subst ~subst:s ~free x
+ | #expr as x -> subst_expr ~subst_rec:subst ~subst:s x
+
+let rec eval : lexpr -> _ = function
+ #lambda as x -> eval_lambda ~eval_rec:eval ~subst x
+ | #expr as x -> eval_expr ~eval_rec:eval x
+
+let rec print = function
+ | `Var id -> print_string id
+ | `Abs (id, l) -> print_string ("\ " ^ id ^ " . "); print l
+ | `App (l1, l2) -> print l1; print_string " "; print l2
+ | `Num x -> print_int x
+ | `Add (e1, e2) -> print e1; print_string " + "; print e2
+ | `Neg e -> print_string "-"; print e
+ | `Mult (e1, e2) -> print e1; print_string " * "; print e2
+
+let () =
+ let e1 = eval1 (`App(`Abs("x",`Var"x"), `Var"y")) in
+ let e2 = eval2 (`Add(`Mult(`Num 3,`Neg(`Num 2)), `Var"x")) in
+ let e3 = eval (`Add(`App(`Abs("x",`Mult(`Var"x",`Var"x")),`Num 2), `Num 5)) in
+ print e1; print_newline ();
+ print e2; print_newline ();
+ print e3; print_newline ()
diff --git a/testsuite/tests/typing-labels/mixin.reference b/testsuite/tests/typing-labels/mixin.reference
new file mode 100644
index 0000000000..27087bd915
--- /dev/null
+++ b/testsuite/tests/typing-labels/mixin.reference
@@ -0,0 +1,3 @@
+y
+-6 + x
+9
diff --git a/testsuite/tests/typing-labels/mixin2.ml b/testsuite/tests/typing-labels/mixin2.ml
new file mode 100644
index 0000000000..fd2b289796
--- /dev/null
+++ b/testsuite/tests/typing-labels/mixin2.ml
@@ -0,0 +1,190 @@
+(* Full fledge version, using objects to structure code *)
+
+open StdLabels
+open MoreLabels
+
+(* Use maps for substitutions and sets for free variables *)
+
+module Subst = Map.Make(struct type t = string let compare = compare end)
+module Names = Set.Make(struct type t = string let compare = compare end)
+
+(* To build recursive objects *)
+
+let lazy_fix make =
+ let rec obj () = make (lazy (obj ()) : _ Lazy.t) in
+ obj ()
+
+let (!!) = Lazy.force
+
+(* The basic operations *)
+
+class type ['a, 'b] ops =
+ object
+ method free : 'b -> Names.t
+ method subst : sub:'a Subst.t -> 'b -> 'a
+ method eval : 'b -> 'a
+ end
+
+(* Variables are common to lambda and expr *)
+
+type var = [`Var of string]
+
+class ['a] var_ops = object (self : ('a, var) #ops)
+ constraint 'a = [> var]
+ method subst ~sub (`Var s as x) =
+ try Subst.find s sub with Not_found -> x
+ method free (`Var s) =
+ Names.singleton s
+ method eval (#var as v) = v
+end
+
+(* The lambda language: free variables, substitutions, and evaluation *)
+
+type 'a lambda = [`Var of string | `Abs of string * 'a | `App of 'a * 'a]
+
+let next_id =
+ let current = ref 3 in
+ fun () -> incr current; !current
+
+class ['a] lambda_ops (ops : ('a,'a) #ops Lazy.t) =
+ let var : 'a var_ops = new var_ops
+ and free = lazy !!ops#free
+ and subst = lazy !!ops#subst
+ and eval = lazy !!ops#eval in
+ object (self : ('a, 'a lambda) #ops)
+ constraint 'a = [> 'a lambda]
+ method free = function
+ #var as x -> var#free x
+ | `Abs (s, t) -> Names.remove s (!!free t)
+ | `App (t1, t2) -> Names.union (!!free t1) (!!free t2)
+
+ method map ~f = function
+ #var as x -> x
+ | `Abs (s, t) as l ->
+ let t' = f t in
+ if t == t' then l else `Abs(s, t')
+ | `App (t1, t2) as l ->
+ let t'1 = f t1 and t'2 = f t2 in
+ if t'1 == t1 && t'2 == t2 then l else `App (t'1, t'2)
+
+ method subst ~sub = function
+ #var as x -> var#subst ~sub x
+ | `Abs(s, t) as l ->
+ let used = !!free t in
+ let used_expr =
+ Subst.fold sub ~init:[]
+ ~f:(fun ~key ~data acc ->
+ if Names.mem s used then data::acc else acc) in
+ if List.exists used_expr ~f:(fun t -> Names.mem s (!!free t)) then
+ let name = s ^ string_of_int (next_id ()) in
+ `Abs(name,
+ !!subst ~sub:(Subst.add ~key:s ~data:(`Var name) sub) t)
+ else
+ self#map ~f:(!!subst ~sub:(Subst.remove s sub)) l
+ | `App _ as l ->
+ self#map ~f:(!!subst ~sub) l
+
+ method eval l =
+ match self#map ~f:!!eval l with
+ `App(`Abs(s,t1), t2) ->
+ !!eval (!!subst ~sub:(Subst.add ~key:s ~data:t2 Subst.empty) t1)
+ | t -> t
+end
+
+(* Operations specialized to lambda *)
+
+let lambda = lazy_fix (new lambda_ops)
+
+(* The expr language of arithmetic expressions *)
+
+type 'a expr =
+ [ `Var of string | `Num of int | `Add of 'a * 'a
+ | `Neg of 'a | `Mult of 'a * 'a]
+
+class ['a] expr_ops (ops : ('a,'a) #ops Lazy.t) =
+ let var : 'a var_ops = new var_ops
+ and free = lazy !!ops#free
+ and subst = lazy !!ops#subst
+ and eval = lazy !!ops#eval in
+ object (self : ('a, 'a expr) #ops)
+ constraint 'a = [> 'a expr]
+ method free = function
+ #var as x -> var#free x
+ | `Num _ -> Names.empty
+ | `Add(x, y) -> Names.union (!!free x) (!!free y)
+ | `Neg x -> !!free x
+ | `Mult(x, y) -> Names.union (!!free x) (!!free y)
+
+ method map ~f = function
+ #var as x -> x
+ | `Num _ as x -> x
+ | `Add(x, y) as e ->
+ let x' = f x and y' = f y in
+ if x == x' && y == y' then e
+ else `Add(x', y')
+ | `Neg x as e ->
+ let x' = f x in
+ if x == x' then e else `Neg x'
+ | `Mult(x, y) as e ->
+ let x' = f x and y' = f y in
+ if x == x' && y == y' then e
+ else `Mult(x', y')
+
+ method subst ~sub = function
+ #var as x -> var#subst ~sub x
+ | #expr as e -> self#map ~f:(!!subst ~sub) e
+
+ method eval (#expr as e) =
+ match self#map ~f:!!eval e with
+ `Add(`Num m, `Num n) -> `Num (m+n)
+ | `Neg(`Num n) -> `Num (-n)
+ | `Mult(`Num m, `Num n) -> `Num (m*n)
+ | e -> e
+ end
+
+(* Specialized versions *)
+
+let expr = lazy_fix (new expr_ops)
+
+(* The lexpr language, reunion of lambda and expr *)
+
+type 'a lexpr = [ 'a lambda | 'a expr ]
+
+class ['a] lexpr_ops (ops : ('a,'a) #ops Lazy.t) =
+ let lambda = new lambda_ops ops in
+ let expr = new expr_ops ops in
+ object (self : ('a, 'a lexpr) #ops)
+ constraint 'a = [> 'a lexpr]
+ method free = function
+ #lambda as x -> lambda#free x
+ | #expr as x -> expr#free x
+
+ method subst ~sub = function
+ #lambda as x -> lambda#subst ~sub x
+ | #expr as x -> expr#subst ~sub x
+
+ method eval = function
+ #lambda as x -> lambda#eval x
+ | #expr as x -> expr#eval x
+end
+
+let lexpr = lazy_fix (new lexpr_ops)
+
+let rec print = function
+ | `Var id -> print_string id
+ | `Abs (id, l) -> print_string ("\ " ^ id ^ " . "); print l
+ | `App (l1, l2) -> print l1; print_string " "; print l2
+ | `Num x -> print_int x
+ | `Add (e1, e2) -> print e1; print_string " + "; print e2
+ | `Neg e -> print_string "-"; print e
+ | `Mult (e1, e2) -> print e1; print_string " * "; print e2
+
+let () =
+ let e1 = lambda#eval (`App(`Abs("x",`Var"x"), `Var"y")) in
+ let e2 = expr#eval (`Add(`Mult(`Num 3,`Neg(`Num 2)), `Var"x")) in
+ let e3 =
+ lexpr#eval (`Add(`App(`Abs("x",`Mult(`Var"x",`Var"x")),`Num 2), `Num 5))
+ in
+ print e1; print_newline ();
+ print e2; print_newline ();
+ print e3; print_newline ()
diff --git a/testsuite/tests/typing-labels/mixin2.reference b/testsuite/tests/typing-labels/mixin2.reference
new file mode 100644
index 0000000000..27087bd915
--- /dev/null
+++ b/testsuite/tests/typing-labels/mixin2.reference
@@ -0,0 +1,3 @@
+y
+-6 + x
+9
diff --git a/testsuite/tests/typing-labels/mixin3.ml b/testsuite/tests/typing-labels/mixin3.ml
new file mode 100644
index 0000000000..5b987e8198
--- /dev/null
+++ b/testsuite/tests/typing-labels/mixin3.ml
@@ -0,0 +1,184 @@
+(* Full fledge version, using objects to structure code *)
+
+open StdLabels
+open MoreLabels
+
+(* Use maps for substitutions and sets for free variables *)
+
+module Subst = Map.Make(struct type t = string let compare = compare end)
+module Names = Set.Make(struct type t = string let compare = compare end)
+
+(* To build recursive objects *)
+
+let lazy_fix make =
+ let rec obj () = make (lazy (obj ()) : _ Lazy.t) in
+ obj ()
+
+let (!!) = Lazy.force
+
+(* The basic operations *)
+
+class type ['a, 'b] ops =
+ object
+ method free : 'b -> Names.t
+ method subst : sub:'a Subst.t -> 'b -> 'a
+ method eval : 'b -> 'a
+ end
+
+(* Variables are common to lambda and expr *)
+
+type var = [`Var of string]
+
+let var = object (self : ([>var], var) #ops)
+ method subst ~sub (`Var s as x) =
+ try Subst.find s sub with Not_found -> x
+ method free (`Var s) =
+ Names.singleton s
+ method eval (#var as v) = v
+end
+
+(* The lambda language: free variables, substitutions, and evaluation *)
+
+type 'a lambda = [`Var of string | `Abs of string * 'a | `App of 'a * 'a]
+
+let next_id =
+ let current = ref 3 in
+ fun () -> incr current; !current
+
+let lambda_ops (ops : ('a,'a) #ops Lazy.t) =
+ let free = lazy !!ops#free
+ and subst = lazy !!ops#subst
+ and eval = lazy !!ops#eval in
+ object (self : ([> 'a lambda], 'a lambda) #ops)
+ method free = function
+ #var as x -> var#free x
+ | `Abs (s, t) -> Names.remove s (!!free t)
+ | `App (t1, t2) -> Names.union (!!free t1) (!!free t2)
+
+ method private map ~f = function
+ #var as x -> x
+ | `Abs (s, t) as l ->
+ let t' = f t in
+ if t == t' then l else `Abs(s, t')
+ | `App (t1, t2) as l ->
+ let t'1 = f t1 and t'2 = f t2 in
+ if t'1 == t1 && t'2 == t2 then l else `App (t'1, t'2)
+
+ method subst ~sub = function
+ #var as x -> var#subst ~sub x
+ | `Abs(s, t) as l ->
+ let used = !!free t in
+ let used_expr =
+ Subst.fold sub ~init:[]
+ ~f:(fun ~key ~data acc ->
+ if Names.mem s used then data::acc else acc) in
+ if List.exists used_expr ~f:(fun t -> Names.mem s (!!free t)) then
+ let name = s ^ string_of_int (next_id ()) in
+ `Abs(name,
+ !!subst ~sub:(Subst.add ~key:s ~data:(`Var name) sub) t)
+ else
+ self#map ~f:(!!subst ~sub:(Subst.remove s sub)) l
+ | `App _ as l ->
+ self#map ~f:(!!subst ~sub) l
+
+ method eval l =
+ match self#map ~f:!!eval l with
+ `App(`Abs(s,t1), t2) ->
+ !!eval (!!subst ~sub:(Subst.add ~key:s ~data:t2 Subst.empty) t1)
+ | t -> t
+end
+
+(* Operations specialized to lambda *)
+
+let lambda = lazy_fix lambda_ops
+
+(* The expr language of arithmetic expressions *)
+
+type 'a expr =
+ [ `Var of string | `Num of int | `Add of 'a * 'a
+ | `Neg of 'a | `Mult of 'a * 'a]
+
+let expr_ops (ops : ('a,'a) #ops Lazy.t) =
+ let free = lazy !!ops#free
+ and subst = lazy !!ops#subst
+ and eval = lazy !!ops#eval in
+ object (self : ([> 'a expr], 'a expr) #ops)
+ method free = function
+ #var as x -> var#free x
+ | `Num _ -> Names.empty
+ | `Add(x, y) -> Names.union (!!free x) (!!free y)
+ | `Neg x -> !!free x
+ | `Mult(x, y) -> Names.union (!!free x) (!!free y)
+
+ method private map ~f = function
+ #var as x -> x
+ | `Num _ as x -> x
+ | `Add(x, y) as e ->
+ let x' = f x and y' = f y in
+ if x == x' && y == y' then e
+ else `Add(x', y')
+ | `Neg x as e ->
+ let x' = f x in
+ if x == x' then e else `Neg x'
+ | `Mult(x, y) as e ->
+ let x' = f x and y' = f y in
+ if x == x' && y == y' then e
+ else `Mult(x', y')
+
+ method subst ~sub = function
+ #var as x -> var#subst ~sub x
+ | #expr as e -> self#map ~f:(!!subst ~sub) e
+
+ method eval (#expr as e) =
+ match self#map ~f:!!eval e with
+ `Add(`Num m, `Num n) -> `Num (m+n)
+ | `Neg(`Num n) -> `Num (-n)
+ | `Mult(`Num m, `Num n) -> `Num (m*n)
+ | e -> e
+ end
+
+(* Specialized versions *)
+
+let expr = lazy_fix expr_ops
+
+(* The lexpr language, reunion of lambda and expr *)
+
+type 'a lexpr = [ 'a lambda | 'a expr ]
+
+let lexpr_ops (ops : ('a,'a) #ops Lazy.t) =
+ let lambda = lambda_ops ops in
+ let expr = expr_ops ops in
+ object (self : ([> 'a lexpr], 'a lexpr) #ops)
+ method free = function
+ #lambda as x -> lambda#free x
+ | #expr as x -> expr#free x
+
+ method subst ~sub = function
+ #lambda as x -> lambda#subst ~sub x
+ | #expr as x -> expr#subst ~sub x
+
+ method eval = function
+ #lambda as x -> lambda#eval x
+ | #expr as x -> expr#eval x
+end
+
+let lexpr = lazy_fix lexpr_ops
+
+let rec print = function
+ | `Var id -> print_string id
+ | `Abs (id, l) -> print_string ("\ " ^ id ^ " . "); print l
+ | `App (l1, l2) -> print l1; print_string " "; print l2
+ | `Num x -> print_int x
+ | `Add (e1, e2) -> print e1; print_string " + "; print e2
+ | `Neg e -> print_string "-"; print e
+ | `Mult (e1, e2) -> print e1; print_string " * "; print e2
+
+let () =
+ let e1 = lambda#eval (`App(`Abs("x",`Var"x"), `Var"y")) in
+ let e2 = expr#eval (`Add(`Mult(`Num 3,`Neg(`Num 2)), `Var"x")) in
+ let e3 =
+ lexpr#eval (`Add(`App(`Abs("x",`Mult(`Var"x",`Var"x")),`Num 2), `Num 5))
+ in
+ print e1; print_newline ();
+ print e2; print_newline ();
+ print e3; print_newline ()
diff --git a/testsuite/tests/typing-labels/mixin3.reference b/testsuite/tests/typing-labels/mixin3.reference
new file mode 100644
index 0000000000..27087bd915
--- /dev/null
+++ b/testsuite/tests/typing-labels/mixin3.reference
@@ -0,0 +1,3 @@
+y
+-6 + x
+9
diff --git a/testsuite/tests/typing-misc-bugs/Makefile b/testsuite/tests/typing-misc-bugs/Makefile
new file mode 100644
index 0000000000..04ded44514
--- /dev/null
+++ b/testsuite/tests/typing-misc-bugs/Makefile
@@ -0,0 +1,14 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+include ../../makefiles/Makefile.okbad
+include ../../makefiles/Makefile.common
diff --git a/testsuite/tests/typing-misc-bugs/pr6303_bad.ml b/testsuite/tests/typing-misc-bugs/pr6303_bad.ml
new file mode 100644
index 0000000000..7d4539c5f8
--- /dev/null
+++ b/testsuite/tests/typing-misc-bugs/pr6303_bad.ml
@@ -0,0 +1,3 @@
+type 'a foo = {x: 'a; y: int}
+let r = {{x = 0; y = 0} with x = 0}
+let r' : string foo = r
diff --git a/testsuite/tests/typing-misc/Makefile b/testsuite/tests/typing-misc/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-misc/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-misc/constraints.ml b/testsuite/tests/typing-misc/constraints.ml
new file mode 100644
index 0000000000..a006363254
--- /dev/null
+++ b/testsuite/tests/typing-misc/constraints.ml
@@ -0,0 +1,24 @@
+type 'a t = [`A of 'a t t] as 'a;; (* fails *)
+
+type 'a t = [`A of 'a t t];; (* fails *)
+
+type 'a t = [`A of 'a t t] constraint 'a = 'a t;;
+
+type 'a t = [`A of 'a t] constraint 'a = 'a t;;
+
+type 'a t = [`A of 'a] as 'a;;
+
+type 'a v = [`A of u v] constraint 'a = t and t = u and u = t;; (* fails *)
+
+type 'a t = 'a;;
+let f (x : 'a t as 'a) = ();; (* fails *)
+
+let f (x : 'a t) (y : 'a) = x = y;;
+
+(* PR#6505 *)
+module type PR6505 = sig
+ type 'o is_an_object = < .. > as 'o
+ and 'o abs constraint 'o = 'o is_an_object
+ val abs : 'o is_an_object -> 'o abs
+ val unabs : 'o abs -> 'o
+end;; (* fails *)
diff --git a/testsuite/tests/typing-misc/constraints.ml.reference b/testsuite/tests/typing-misc/constraints.ml.reference
new file mode 100644
index 0000000000..41a324c69a
--- /dev/null
+++ b/testsuite/tests/typing-misc/constraints.ml.reference
@@ -0,0 +1,34 @@
+
+# Characters 12-32:
+ type 'a t = [`A of 'a t t] as 'a;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type
+ [ `A of 'a ] t t as 'a
+ should be an instance of
+ ([ `A of 'b t t ] as 'b) t
+# Characters 1-27:
+ type 'a t = [`A of 'a t t];; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In the definition of t, type 'a t t should be 'a t
+# type 'a t = [ `A of 'a t t ] constraint 'a = 'a t
+# type 'a t = [ `A of 'a t ] constraint 'a = 'a t
+# type 'a t = 'a constraint 'a = [ `A of 'a ]
+# Characters 43-52:
+ type 'a v = [`A of u v] constraint 'a = t and t = u and u = t;; (* fails *)
+ ^^^^^^^^^
+Error: The type abbreviation t is cyclic
+# type 'a t = 'a
+# Characters 11-21:
+ let f (x : 'a t as 'a) = ();; (* fails *)
+ ^^^^^^^^^^
+Error: This alias is bound to type 'a t = 'a
+ but is used as an instance of type 'a
+ The type variable 'a occurs inside 'a
+# val f : 'a t -> 'a -> bool = <fun>
+# Characters 80-122:
+ and 'o abs constraint 'o = 'o is_an_object
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: The definition of abs contains a cycle:
+ 'a is_an_object as 'a
+#
diff --git a/testsuite/tests/typing-misc/labels.ml b/testsuite/tests/typing-misc/labels.ml
new file mode 100644
index 0000000000..2d4b9d19d8
--- /dev/null
+++ b/testsuite/tests/typing-misc/labels.ml
@@ -0,0 +1,11 @@
+(* PR#5835 *)
+let f ~x = x + 1;;
+f ?x:0;;
+
+(* PR#6352 *)
+let foo (f : unit -> unit) = ();;
+let g ?x () = ();;
+foo ((); g);;
+
+(* PR#5748 *)
+foo (fun ?opt () -> ()) ;; (* fails *)
diff --git a/testsuite/tests/typing-misc/labels.ml.principal.reference b/testsuite/tests/typing-misc/labels.ml.principal.reference
new file mode 100644
index 0000000000..f8be126bb8
--- /dev/null
+++ b/testsuite/tests/typing-misc/labels.ml.principal.reference
@@ -0,0 +1,16 @@
+
+# val f : x:int -> int = <fun>
+# Characters 5-6:
+ f ?x:0;;
+ ^
+Warning 43: the label x is not optional.
+- : int = 1
+# val foo : (unit -> unit) -> unit = <fun>
+# val g : ?x:'a -> unit -> unit = <fun>
+# - : unit = ()
+# Characters 19-38:
+ foo (fun ?opt () -> ()) ;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^
+Error: This function should have type unit -> unit
+ but its first argument is labelled ?opt
+#
diff --git a/testsuite/tests/typing-misc/labels.ml.reference b/testsuite/tests/typing-misc/labels.ml.reference
new file mode 100644
index 0000000000..f8be126bb8
--- /dev/null
+++ b/testsuite/tests/typing-misc/labels.ml.reference
@@ -0,0 +1,16 @@
+
+# val f : x:int -> int = <fun>
+# Characters 5-6:
+ f ?x:0;;
+ ^
+Warning 43: the label x is not optional.
+- : int = 1
+# val foo : (unit -> unit) -> unit = <fun>
+# val g : ?x:'a -> unit -> unit = <fun>
+# - : unit = ()
+# Characters 19-38:
+ foo (fun ?opt () -> ()) ;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^
+Error: This function should have type unit -> unit
+ but its first argument is labelled ?opt
+#
diff --git a/testsuite/tests/typing-misc/occur_check.ml b/testsuite/tests/typing-misc/occur_check.ml
new file mode 100644
index 0000000000..5509b6f5ff
--- /dev/null
+++ b/testsuite/tests/typing-misc/occur_check.ml
@@ -0,0 +1,5 @@
+(* PR#5907 *)
+
+type 'a t = 'a;;
+let f (g : 'a list -> 'a t -> 'a) s = g s s;;
+let f (g : 'a * 'b -> 'a t -> 'a) s = g s s;;
diff --git a/testsuite/tests/typing-misc/occur_check.ml.reference b/testsuite/tests/typing-misc/occur_check.ml.reference
new file mode 100644
index 0000000000..865c7d6441
--- /dev/null
+++ b/testsuite/tests/typing-misc/occur_check.ml.reference
@@ -0,0 +1,15 @@
+
+# type 'a t = 'a
+# Characters 42-43:
+ let f (g : 'a list -> 'a t -> 'a) s = g s s;;
+ ^
+Error: This expression has type 'a list
+ but an expression was expected of type 'a t = 'a
+ The type variable 'a occurs inside 'a list
+# Characters 42-43:
+ let f (g : 'a * 'b -> 'a t -> 'a) s = g s s;;
+ ^
+Error: This expression has type 'a * 'b
+ but an expression was expected of type 'a t = 'a
+ The type variable 'a occurs inside 'a * 'b
+#
diff --git a/testsuite/tests/typing-misc/polyvars.ml b/testsuite/tests/typing-misc/polyvars.ml
new file mode 100644
index 0000000000..de8cb221bb
--- /dev/null
+++ b/testsuite/tests/typing-misc/polyvars.ml
@@ -0,0 +1,15 @@
+type ab = [ `A | `B ];;
+let f (x : [`A]) = match x with #ab -> 1;;
+let f x = ignore (match x with #ab -> 1); ignore (x : [`A]);;
+let f x = ignore (match x with `A|`B -> 1); ignore (x : [`A]);;
+
+let f (x : [< `A | `B]) = match x with `A | `B | `C -> 0;; (* warn *)
+let f (x : [`A | `B]) = match x with `A | `B | `C -> 0;; (* fail *)
+
+(* PR#6787 *)
+let revapply x f = f x;;
+
+let f x (g : [< `Foo]) =
+ let y = `Bar x, g in
+ revapply y (fun ((`Bar i), _) -> i);;
+(* f : 'a -> [< `Foo ] -> 'a *)
diff --git a/testsuite/tests/typing-misc/polyvars.ml.principal.reference b/testsuite/tests/typing-misc/polyvars.ml.principal.reference
new file mode 100644
index 0000000000..6732640e9f
--- /dev/null
+++ b/testsuite/tests/typing-misc/polyvars.ml.principal.reference
@@ -0,0 +1,34 @@
+
+# type ab = [ `A | `B ]
+# Characters 32-35:
+ let f (x : [`A]) = match x with #ab -> 1;;
+ ^^^
+Error: This pattern matches values of type [? `A | `B ]
+ but a pattern was expected which matches values of type [ `A ]
+ The second variant type does not allow tag(s) `B
+# Characters 31-34:
+ let f x = ignore (match x with #ab -> 1); ignore (x : [`A]);;
+ ^^^
+Error: This pattern matches values of type [? `B ]
+ but a pattern was expected which matches values of type [ `A ]
+ Types for tag `B are incompatible
+# Characters 34-36:
+ let f x = ignore (match x with `A|`B -> 1); ignore (x : [`A]);;
+ ^^
+Error: This pattern matches values of type [? `B ]
+ but a pattern was expected which matches values of type [ `A ]
+ Types for tag `B are incompatible
+# Characters 50-52:
+ let f (x : [< `A | `B]) = match x with `A | `B | `C -> 0;; (* warn *)
+ ^^
+Warning 12: this sub-pattern is unused.
+val f : [< `A | `B ] -> int = <fun>
+# Characters 47-49:
+ let f (x : [`A | `B]) = match x with `A | `B | `C -> 0;; (* fail *)
+ ^^
+Error: This pattern matches values of type [? `C ]
+ but a pattern was expected which matches values of type [ `A | `B ]
+ The second variant type does not allow tag(s) `C
+# val revapply : 'a -> ('a -> 'b) -> 'b = <fun>
+# val f : 'a -> [< `Foo ] -> 'a = <fun>
+#
diff --git a/testsuite/tests/typing-misc/polyvars.ml.reference b/testsuite/tests/typing-misc/polyvars.ml.reference
new file mode 100644
index 0000000000..751b02fc07
--- /dev/null
+++ b/testsuite/tests/typing-misc/polyvars.ml.reference
@@ -0,0 +1,34 @@
+
+# type ab = [ `A | `B ]
+# Characters 32-35:
+ let f (x : [`A]) = match x with #ab -> 1;;
+ ^^^
+Error: This pattern matches values of type [? `A | `B ]
+ but a pattern was expected which matches values of type [ `A ]
+ The second variant type does not allow tag(s) `B
+# Characters 31-34:
+ let f x = ignore (match x with #ab -> 1); ignore (x : [`A]);;
+ ^^^
+Error: This pattern matches values of type [? `B ]
+ but a pattern was expected which matches values of type [ `A ]
+ The second variant type does not allow tag(s) `B
+# Characters 34-36:
+ let f x = ignore (match x with `A|`B -> 1); ignore (x : [`A]);;
+ ^^
+Error: This pattern matches values of type [? `B ]
+ but a pattern was expected which matches values of type [ `A ]
+ The second variant type does not allow tag(s) `B
+# Characters 50-52:
+ let f (x : [< `A | `B]) = match x with `A | `B | `C -> 0;; (* warn *)
+ ^^
+Warning 12: this sub-pattern is unused.
+val f : [< `A | `B ] -> int = <fun>
+# Characters 47-49:
+ let f (x : [`A | `B]) = match x with `A | `B | `C -> 0;; (* fail *)
+ ^^
+Error: This pattern matches values of type [? `C ]
+ but a pattern was expected which matches values of type [ `A | `B ]
+ The second variant type does not allow tag(s) `C
+# val revapply : 'a -> ('a -> 'b) -> 'b = <fun>
+# val f : 'a -> [< `Foo ] -> 'a = <fun>
+#
diff --git a/testsuite/tests/typing-misc/records.ml b/testsuite/tests/typing-misc/records.ml
new file mode 100644
index 0000000000..ae296cf125
--- /dev/null
+++ b/testsuite/tests/typing-misc/records.ml
@@ -0,0 +1,38 @@
+(* undefined labels *)
+type t = {x:int;y:int};;
+{x=3;z=2};;
+fun {x=3;z=2} -> ();;
+
+(* mixed labels *)
+{x=3; contents=2};;
+
+(* private types *)
+type u = private {mutable u:int};;
+{u=3};;
+fun x -> x.u <- 3;;
+
+(* Punning and abbreviations *)
+module M = struct
+ type t = {x: int; y: int}
+end;;
+
+let f {M.x; y} = x+y;;
+let r = {M.x=1; y=2};;
+let z = f r;;
+
+(* messages *)
+type foo = { mutable y:int };;
+let f (r: int) = r.y <- 3;;
+
+(* bugs *)
+type foo = { y: int; z: int };;
+type bar = { x: int };;
+let f (r: bar) = ({ r with z = 3 } : foo)
+
+type foo = { x: int };;
+let r : foo = { ZZZ.x = 2 };;
+
+(ZZZ.X : int option);;
+
+(* PR#5865 *)
+let f (x : Complex.t) = x.Complex.z;;
diff --git a/testsuite/tests/typing-misc/records.ml.principal.reference b/testsuite/tests/typing-misc/records.ml.principal.reference
new file mode 100644
index 0000000000..f084d039db
--- /dev/null
+++ b/testsuite/tests/typing-misc/records.ml.principal.reference
@@ -0,0 +1,54 @@
+
+# type t = { x : int; y : int; }
+# Characters 5-6:
+ {x=3;z=2};;
+ ^
+Error: Unbound record field z
+# Characters 9-10:
+ fun {x=3;z=2} -> ();;
+ ^
+Error: Unbound record field z
+# Characters 26-34:
+ {x=3; contents=2};;
+ ^^^^^^^^
+Error: The record field contents belongs to the type 'a ref
+ but is mixed here with fields of type t
+# type u = private { mutable u : int; }
+# Characters 0-5:
+ {u=3};;
+ ^^^^^
+Error: Cannot create values of the private type u
+# Characters 11-12:
+ fun x -> x.u <- 3;;
+ ^
+Error: Cannot assign field u of the private type u
+# module M : sig type t = { x : int; y : int; } end
+# val f : M.t -> int = <fun>
+# val r : M.t = {M.x = 1; y = 2}
+# val z : int = 3
+# type foo = { mutable y : int; }
+# Characters 17-18:
+ let f (r: int) = r.y <- 3;;
+ ^
+Error: This expression has type int but an expression was expected of type
+ foo
+# type foo = { y : int; z : int; }
+# type bar = { x : int; }
+# Characters 20-21:
+ let f (r: bar) = ({ r with z = 3 } : foo)
+ ^
+Error: This expression has type bar but an expression was expected of type
+ foo
+# Characters 16-21:
+ let r : foo = { ZZZ.x = 2 };;
+ ^^^^^
+Error: Unbound module ZZZ
+# Characters 2-7:
+ (ZZZ.X : int option);;
+ ^^^^^
+Error: Unbound module ZZZ
+# Characters 41-50:
+ let f (x : Complex.t) = x.Complex.z;;
+ ^^^^^^^^^
+Error: Unbound record field Complex.z
+#
diff --git a/testsuite/tests/typing-misc/records.ml.reference b/testsuite/tests/typing-misc/records.ml.reference
new file mode 100644
index 0000000000..f084d039db
--- /dev/null
+++ b/testsuite/tests/typing-misc/records.ml.reference
@@ -0,0 +1,54 @@
+
+# type t = { x : int; y : int; }
+# Characters 5-6:
+ {x=3;z=2};;
+ ^
+Error: Unbound record field z
+# Characters 9-10:
+ fun {x=3;z=2} -> ();;
+ ^
+Error: Unbound record field z
+# Characters 26-34:
+ {x=3; contents=2};;
+ ^^^^^^^^
+Error: The record field contents belongs to the type 'a ref
+ but is mixed here with fields of type t
+# type u = private { mutable u : int; }
+# Characters 0-5:
+ {u=3};;
+ ^^^^^
+Error: Cannot create values of the private type u
+# Characters 11-12:
+ fun x -> x.u <- 3;;
+ ^
+Error: Cannot assign field u of the private type u
+# module M : sig type t = { x : int; y : int; } end
+# val f : M.t -> int = <fun>
+# val r : M.t = {M.x = 1; y = 2}
+# val z : int = 3
+# type foo = { mutable y : int; }
+# Characters 17-18:
+ let f (r: int) = r.y <- 3;;
+ ^
+Error: This expression has type int but an expression was expected of type
+ foo
+# type foo = { y : int; z : int; }
+# type bar = { x : int; }
+# Characters 20-21:
+ let f (r: bar) = ({ r with z = 3 } : foo)
+ ^
+Error: This expression has type bar but an expression was expected of type
+ foo
+# Characters 16-21:
+ let r : foo = { ZZZ.x = 2 };;
+ ^^^^^
+Error: Unbound module ZZZ
+# Characters 2-7:
+ (ZZZ.X : int option);;
+ ^^^^^
+Error: Unbound module ZZZ
+# Characters 41-50:
+ let f (x : Complex.t) = x.Complex.z;;
+ ^^^^^^^^^
+Error: Unbound record field Complex.z
+#
diff --git a/testsuite/tests/typing-misc/variant.ml b/testsuite/tests/typing-misc/variant.ml
new file mode 100644
index 0000000000..b0bd522277
--- /dev/null
+++ b/testsuite/tests/typing-misc/variant.ml
@@ -0,0 +1,8 @@
+(* PR#6394 *)
+
+module rec X : sig
+ type t = int * bool
+end = struct
+ type t = A | B
+ let f = function A | B -> 0
+end;;
diff --git a/testsuite/tests/typing-misc/variant.ml.reference b/testsuite/tests/typing-misc/variant.ml.reference
new file mode 100644
index 0000000000..4de6b611e6
--- /dev/null
+++ b/testsuite/tests/typing-misc/variant.ml.reference
@@ -0,0 +1,16 @@
+
+# Characters 61-116:
+ ......struct
+ type t = A | B
+ let f = function A | B -> 0
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = X.t = A | B val f : t -> int end
+ is not included in
+ sig type t = int * bool end
+ Type declarations do not match:
+ type t = X.t = A | B
+ is not included in
+ type t = int * bool
+#
diff --git a/testsuite/tests/typing-misc/wellfounded.ml b/testsuite/tests/typing-misc/wellfounded.ml
new file mode 100644
index 0000000000..b33adc5e17
--- /dev/null
+++ b/testsuite/tests/typing-misc/wellfounded.ml
@@ -0,0 +1,11 @@
+(* PR#6768 *)
+
+type _ prod = Prod : ('a * 'y) prod;;
+
+let f : type t. t prod -> _ = function Prod ->
+ let module M =
+ struct
+ type d = d * d
+ end
+ in ()
+;;
diff --git a/testsuite/tests/typing-misc/wellfounded.ml.principal.reference b/testsuite/tests/typing-misc/wellfounded.ml.principal.reference
new file mode 100644
index 0000000000..04bf5586bb
--- /dev/null
+++ b/testsuite/tests/typing-misc/wellfounded.ml.principal.reference
@@ -0,0 +1,7 @@
+
+# type _ prod = Prod : ('a * 'y) prod
+# Characters 82-96:
+ type d = d * d
+ ^^^^^^^^^^^^^^
+Error: The type abbreviation d is cyclic
+#
diff --git a/testsuite/tests/typing-misc/wellfounded.ml.reference b/testsuite/tests/typing-misc/wellfounded.ml.reference
new file mode 100644
index 0000000000..04bf5586bb
--- /dev/null
+++ b/testsuite/tests/typing-misc/wellfounded.ml.reference
@@ -0,0 +1,7 @@
+
+# type _ prod = Prod : ('a * 'y) prod
+# Characters 82-96:
+ type d = d * d
+ ^^^^^^^^^^^^^^
+Error: The type abbreviation d is cyclic
+#
diff --git a/testsuite/tests/typing-modules-bugs/Makefile b/testsuite/tests/typing-modules-bugs/Makefile
new file mode 100644
index 0000000000..04ded44514
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/Makefile
@@ -0,0 +1,14 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+include ../../makefiles/Makefile.okbad
+include ../../makefiles/Makefile.common
diff --git a/testsuite/tests/typing-modules-bugs/gatien_baron_20131019_ok.ml b/testsuite/tests/typing-modules-bugs/gatien_baron_20131019_ok.ml
new file mode 100644
index 0000000000..5887445493
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/gatien_baron_20131019_ok.ml
@@ -0,0 +1,31 @@
+module Std = struct module Hash = Hashtbl end;;
+
+open Std;;
+module Hash1 : module type of Hash = Hash;;
+module Hash2 : sig include (module type of Hash) end = Hash;;
+let f1 (x : (_,_) Hash1.t) = (x : (_,_) Hashtbl.t);;
+let f2 (x : (_,_) Hash2.t) = (x : (_,_) Hashtbl.t);;
+
+(* Another case, not using include *)
+
+module Std2 = struct module M = struct type t end end;;
+module Std' = Std2;;
+module M' : module type of Std'.M = Std2.M;;
+let f3 (x : M'.t) = (x : Std2.M.t);;
+
+(* original report required Core_kernel:
+module type S = sig
+open Core_kernel.Std
+
+module Hashtbl1 : module type of Hashtbl
+module Hashtbl2 : sig
+ include (module type of Hashtbl)
+end
+
+module Coverage : Core_kernel.Std.Hashable
+
+type types = unit constraint 'a Coverage.Table.t = (Coverage.t, 'a) Hashtbl1.t
+type doesnt_type = unit
+ constraint 'a Coverage.Table.t = (Coverage.t, 'a) Hashtbl2.t
+end
+*)
diff --git a/testsuite/tests/typing-modules-bugs/pr5164_ok.ml b/testsuite/tests/typing-modules-bugs/pr5164_ok.ml
new file mode 100644
index 0000000000..5a59808ef4
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr5164_ok.ml
@@ -0,0 +1,9 @@
+module type INCLUDING = sig
+ include module type of List
+ include module type of ListLabels
+end
+
+module Including_typed: INCLUDING = struct
+ include List
+ include ListLabels
+end
diff --git a/testsuite/tests/typing-modules-bugs/pr51_ok.ml b/testsuite/tests/typing-modules-bugs/pr51_ok.ml
new file mode 100644
index 0000000000..0826fa31a9
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr51_ok.ml
@@ -0,0 +1,18 @@
+module X=struct
+ module type SIG=sig type t=int val x:t end
+ module F(Y:SIG) : SIG = struct type t=Y.t let x=Y.x end
+end;;
+module DUMMY=struct type t=int let x=2 end;;
+let x = (3 : X.F(DUMMY).t);;
+
+module X2=struct
+ module type SIG=sig type t=int val x:t end
+ module F(Y:SIG)(Z:SIG) = struct
+ type t=Y.t
+ let x=Y.x
+ type t'=Z.t
+ let x'=Z.x
+ end
+end;;
+let x = (3 : X2.F(DUMMY)(DUMMY).t);;
+let x = (3 : X2.F(DUMMY)(DUMMY).t');;
diff --git a/testsuite/tests/typing-modules-bugs/pr5663_ok.ml b/testsuite/tests/typing-modules-bugs/pr5663_ok.ml
new file mode 100644
index 0000000000..ce791f9075
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr5663_ok.ml
@@ -0,0 +1,7 @@
+module F (M : sig
+ type 'a t
+ type 'a u = string
+ val f : unit -> _ u t
+ end) = struct
+ let t = M.f ()
+ end
diff --git a/testsuite/tests/typing-modules-bugs/pr5914_ok.ml b/testsuite/tests/typing-modules-bugs/pr5914_ok.ml
new file mode 100644
index 0000000000..fb21cd4b4a
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr5914_ok.ml
@@ -0,0 +1,18 @@
+type 't a = [ `A ]
+type 't wrap = 't constraint 't = [> 't wrap a ]
+type t = t a wrap
+
+module T = struct
+ let foo : 't wrap -> 't wrap -> unit = fun _ _ -> ()
+ let bar : ('a a wrap as 'a) = `A
+end
+
+module Good : sig
+ val bar: t
+ val foo: t -> t -> unit
+end = T
+
+module Bad : sig
+ val foo: t -> t -> unit
+ val bar: t
+end = T
diff --git a/testsuite/tests/typing-modules-bugs/pr6240_ok.ml b/testsuite/tests/typing-modules-bugs/pr6240_ok.ml
new file mode 100644
index 0000000000..de1754aa05
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6240_ok.ml
@@ -0,0 +1,11 @@
+module M : sig
+ module type T
+ module F (X : T) : sig end
+end = struct
+ module type T = sig end
+ module F (X : T) = struct end
+end
+
+module type T = M.T
+
+module F : functor (X : T) -> sig end = M.F
diff --git a/testsuite/tests/typing-modules-bugs/pr6293_bad.ml b/testsuite/tests/typing-modules-bugs/pr6293_bad.ml
new file mode 100644
index 0000000000..fe16fe4db5
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6293_bad.ml
@@ -0,0 +1,2 @@
+module type S = sig type t = { a : int; b : int; } end;;
+let f (module M : S with type t = int) = { M.a = 0 };;
diff --git a/testsuite/tests/typing-modules-bugs/pr6427_bad.ml b/testsuite/tests/typing-modules-bugs/pr6427_bad.ml
new file mode 100644
index 0000000000..286dafb88a
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6427_bad.ml
@@ -0,0 +1,20 @@
+let flag = ref false
+module F(S : sig module type T end) (A : S.T) (B : S.T) =
+struct
+ module X = (val if !flag then (module A) else (module B) : S.T)
+end
+
+(* If the above were accepted, one could break soundness *)
+module type S = sig type t val x : t end
+module Float = struct type t = float let x = 0.0 end
+module Int = struct type t = int let x = 0 end
+
+module M = F(struct module type T = S end)
+
+let () = flag := false
+module M1 = M(Float)(Int)
+
+let () = flag := true
+module M2 = M(Float)(Int)
+
+let _ = [| M2.X.x; M1.X.x |]
diff --git a/testsuite/tests/typing-modules-bugs/pr6513_ok.ml b/testsuite/tests/typing-modules-bugs/pr6513_ok.ml
new file mode 100644
index 0000000000..7474ba93a2
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6513_ok.ml
@@ -0,0 +1,28 @@
+module type PR6513 = sig
+module type S = sig type u end
+
+module type T = sig
+ type 'a wrap
+ type uri
+end
+
+module Make: functor (Html5 : T with type 'a wrap = 'a) ->
+ S with type u = < foo : Html5.uri >
+end
+
+(* Requires -package tyxml
+module type PR6513_orig = sig
+module type S =
+sig
+ type t
+ type u
+end
+
+module Make: functor (Html5: Html5_sigs.T
+ with type 'a Xml.wrap = 'a and
+ type 'a wrap = 'a and
+ type 'a list_wrap = 'a list)
+ -> S with type t = Html5_types.div Html5.elt and
+ type u = < foo: Html5.uri >
+end
+*)
diff --git a/testsuite/tests/typing-modules-bugs/pr6572_ok.ml b/testsuite/tests/typing-modules-bugs/pr6572_ok.ml
new file mode 100644
index 0000000000..00c2f091d6
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6572_ok.ml
@@ -0,0 +1,19 @@
+module type S = sig
+ include Set.S
+ module E : sig val x : int end
+end
+
+module Make(O : Set.OrderedType) : S with type elt = O.t =
+ struct
+ include Set.Make(O)
+ module E = struct let x = 1 end
+ end
+
+module rec A : Set.OrderedType = struct
+ type t = int
+ let compare = Pervasives.compare
+end
+and B : S = struct
+ module C = Make(A)
+ include C
+end
diff --git a/testsuite/tests/typing-modules-bugs/pr6651_ok.ml b/testsuite/tests/typing-modules-bugs/pr6651_ok.ml
new file mode 100644
index 0000000000..9c43005149
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6651_ok.ml
@@ -0,0 +1,13 @@
+module type S = sig
+ module type T
+ module X : T
+end
+
+module F (X : S) = X.X
+
+module M = struct
+ module type T = sig type t end
+ module X = struct type t = int end
+end
+
+type t = F(M).t
diff --git a/testsuite/tests/typing-modules-bugs/pr6752_ok.ml b/testsuite/tests/typing-modules-bugs/pr6752_ok.ml
new file mode 100644
index 0000000000..846af0d178
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6752_ok.ml
@@ -0,0 +1,43 @@
+module Common0 =
+ struct
+ type msg = Msg
+
+ let handle_msg = ref (function _ -> failwith "Unable to handle message")
+ let extend_handle f =
+ let old = !handle_msg in
+ handle_msg := f old
+
+ let q : _ Queue.t = Queue.create ()
+ let add msg = Queue.add msg q
+ let handle_queue_messages () = Queue.iter !handle_msg q
+ end
+
+let q' : Common0.msg Queue.t = Common0.q
+
+module Common =
+ struct
+ type msg = ..
+
+ let handle_msg = ref (function _ -> failwith "Unable to handle message")
+ let extend_handle f =
+ let old = !handle_msg in
+ handle_msg := f old
+
+ let q : _ Queue.t = Queue.create ()
+ let add msg = Queue.add msg q
+ let handle_queue_messages () = Queue.iter !handle_msg q
+ end
+
+module M1 =
+ struct
+ type Common.msg += Reload of string | Alert of string
+
+ let handle fallback = function
+ Reload s -> print_endline ("Reload "^s)
+ | Alert s -> print_endline ("Alert "^s)
+ | x -> fallback x
+
+ let () = Common.extend_handle handle
+ let () = Common.add (Reload "config.file")
+ let () = Common.add (Alert "Initialisation done")
+ end
diff --git a/testsuite/tests/typing-modules-bugs/pr6899_first_bad.ml b/testsuite/tests/typing-modules-bugs/pr6899_first_bad.ml
new file mode 100644
index 0000000000..07435e11c5
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6899_first_bad.ml
@@ -0,0 +1,3 @@
+let should_reject =
+ let table = Hashtbl.create 1 in
+ fun x y -> Hashtbl.add table x y
diff --git a/testsuite/tests/typing-modules-bugs/pr6899_ok.ml b/testsuite/tests/typing-modules-bugs/pr6899_ok.ml
new file mode 100644
index 0000000000..e049534ded
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6899_ok.ml
@@ -0,0 +1,6 @@
+type 'a t = 'a option
+let is_some = function
+ | None -> false
+ | Some _ -> true
+
+let should_accept ?x () = is_some x
diff --git a/testsuite/tests/typing-modules-bugs/pr6899_second_bad.ml b/testsuite/tests/typing-modules-bugs/pr6899_second_bad.ml
new file mode 100644
index 0000000000..4d49fe1e70
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6899_second_bad.ml
@@ -0,0 +1,5 @@
+include struct
+ let foo `Test = ()
+ let wrap f `Test = f
+ let bar = wrap ()
+end
diff --git a/testsuite/tests/typing-modules-bugs/pr6944_ok.ml b/testsuite/tests/typing-modules-bugs/pr6944_ok.ml
new file mode 100644
index 0000000000..dffba4e9f4
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6944_ok.ml
@@ -0,0 +1,4 @@
+let f () =
+ let module S = String in
+ let module N = Map.Make(S) in
+ N.add "sum" 41 N.empty;;
diff --git a/testsuite/tests/typing-modules-bugs/pr6982_ok.ml b/testsuite/tests/typing-modules-bugs/pr6982_ok.ml
new file mode 100644
index 0000000000..7e24940a03
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6982_ok.ml
@@ -0,0 +1,26 @@
+module A = struct
+ module type A_S = sig
+ end
+
+ type t = (module A_S)
+end
+
+module type S = sig type t end
+
+let f (type a) (module X : S with type t = a) = ()
+
+let _ = f (module A) (* ok *)
+
+module A_annotated_alias : S with type t = (module A.A_S) = A
+
+let _ = f (module A_annotated_alias) (* ok *)
+let _ = f (module A_annotated_alias : S with type t = (module A.A_S)) (* ok *)
+
+module A_alias = A
+module A_alias_expanded = struct include A_alias end
+
+let _ = f (module A_alias_expanded : S with type t = (module A.A_S)) (* ok *)
+let _ = f (module A_alias_expanded) (* ok *)
+
+let _ = f (module A_alias : S with type t = (module A.A_S)) (* doesn't type *)
+let _ = f (module A_alias) (* doesn't type either *)
diff --git a/testsuite/tests/typing-modules-bugs/pr6985_ok.ml b/testsuite/tests/typing-modules-bugs/pr6985_ok.ml
new file mode 100644
index 0000000000..f6078c97b1
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6985_ok.ml
@@ -0,0 +1,7 @@
+module Foo
+ (Bar : sig type a = private [> `A ] end)
+ (Baz : module type of struct include Bar end) =
+struct
+end
+module Bazoinks = struct type a = [ `A ] end
+module Bug = Foo(Bazoinks)(Bazoinks)
diff --git a/testsuite/tests/typing-modules-bugs/pr6992_bad.ml b/testsuite/tests/typing-modules-bugs/pr6992_bad.ml
new file mode 100644
index 0000000000..c2814d4482
--- /dev/null
+++ b/testsuite/tests/typing-modules-bugs/pr6992_bad.ml
@@ -0,0 +1,15 @@
+(* PR#6992, reported by Stephen Dolan *)
+
+type (_, _) eq = Eq : ('a, 'a) eq
+let cast : type a b . (a, b) eq -> a -> b = fun Eq x -> x
+
+module Fix (F : sig type 'a f end) = struct
+ type 'a fix = ('a, 'a F.f) eq
+ let uniq (type a) (type b) (Eq : a fix) (Eq : b fix) : (a, b) eq = Eq
+end
+
+(* This would allow:
+module FixId = Fix (struct type 'a f = 'a end)
+ let bad : (int, string) eq = FixId.uniq Eq Eq
+ let _ = Printf.printf "Oh dear: %s" (cast bad 42)
+*)
diff --git a/testsuite/tests/typing-modules/Makefile b/testsuite/tests/typing-modules/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-modules/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-modules/Test.ml b/testsuite/tests/typing-modules/Test.ml
new file mode 100644
index 0000000000..640655eb12
--- /dev/null
+++ b/testsuite/tests/typing-modules/Test.ml
@@ -0,0 +1,62 @@
+(* with module *)
+
+module type S = sig type t and s = t end;;
+module type S' = S with type t := int;;
+
+module type S = sig module rec M : sig end and N : sig end end;;
+module type S' = S with module M := String;;
+
+(* with module type *)
+(*
+module type S = sig module type T module F(X:T) : T end;;
+module type T0 = sig type t end;;
+module type S1 = S with module type T = T0;;
+module type S2 = S with module type T := T0;;
+module type S3 = S with module type T := sig type t = int end;;
+module H = struct
+ include (Hashtbl : module type of Hashtbl with
+ type statistics := Hashtbl.statistics
+ and module type S := Hashtbl.S
+ and module Make := Hashtbl.Make
+ and module MakeSeeded := Hashtbl.MakeSeeded
+ and module type SeededS := Hashtbl.SeededS
+ and module type HashedType := Hashtbl.HashedType
+ and module type SeededHashedType := Hashtbl.SeededHashedType)
+end;;
+*)
+
+(* A subtle problem appearing with -principal *)
+type -'a t
+class type c = object method m : [ `A ] t end;;
+module M : sig val v : (#c as 'a) -> 'a end =
+ struct let v x = ignore (x :> c); x end;;
+
+(* PR#4838 *)
+
+let id = let module M = struct end in fun x -> x;;
+
+(* PR#4511 *)
+
+let ko = let module M = struct end in fun _ -> ();;
+
+(* PR#5993 *)
+
+module M : sig type -'a t = private int end =
+ struct type +'a t = private int end
+;;
+
+(* PR#6005 *)
+
+module type A = sig type t = X of int end;;
+type u = X of bool;;
+module type B = A with type t = u;; (* fail *)
+
+(* PR#5815 *)
+(* ---> duplicated exception name is now an error *)
+
+module type S = sig exception Foo of int exception Foo of bool end;;
+
+(* PR#6410 *)
+
+module F(X : sig end) = struct let x = 3 end;;
+F.x;; (* fail *)
diff --git a/testsuite/tests/typing-modules/Test.ml.principal.reference b/testsuite/tests/typing-modules/Test.ml.principal.reference
new file mode 100644
index 0000000000..9646d3d0a5
--- /dev/null
+++ b/testsuite/tests/typing-modules/Test.ml.principal.reference
@@ -0,0 +1,41 @@
+
+# module type S = sig type t and s = t end
+# module type S' = sig type s = int end
+# module type S = sig module rec M : sig end and N : sig end end
+# module type S' = sig module rec N : sig end end
+# * * * * * * * * * * * * * * * * type -'a t
+class type c = object method m : [ `A ] t end
+# module M : sig val v : (#c as 'a) -> 'a end
+# val id : 'a -> 'a = <fun>
+# val ko : 'a -> unit = <fun>
+# Characters 64-99:
+ struct type +'a t = private int end
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type +'a t = private int end
+ is not included in
+ sig type -'a t = private int end
+ Type declarations do not match:
+ type +'a t = private int
+ is not included in
+ type -'a t = private int
+ Their variances do not agree.
+# module type A = sig type t = X of int end
+# type u = X of bool
+# Characters 23-33:
+ module type B = A with type t = u;; (* fail *)
+ ^^^^^^^^^^
+Error: This variant or record definition does not match that of type u
+ The types for field X are not equal.
+# Characters 121-124:
+ module type S = sig exception Foo of int exception Foo of bool end;;
+ ^^^
+Error: Multiple definition of the extension constructor name Foo.
+ Names must be unique in a given structure or signature.
+# module F : functor (X : sig end) -> sig val x : int end
+# Characters 0-3:
+ F.x;; (* fail *)
+ ^^^
+Error: The module F is a functor, not a structure
+#
diff --git a/testsuite/tests/typing-modules/Test.ml.reference b/testsuite/tests/typing-modules/Test.ml.reference
new file mode 100644
index 0000000000..9646d3d0a5
--- /dev/null
+++ b/testsuite/tests/typing-modules/Test.ml.reference
@@ -0,0 +1,41 @@
+
+# module type S = sig type t and s = t end
+# module type S' = sig type s = int end
+# module type S = sig module rec M : sig end and N : sig end end
+# module type S' = sig module rec N : sig end end
+# * * * * * * * * * * * * * * * * type -'a t
+class type c = object method m : [ `A ] t end
+# module M : sig val v : (#c as 'a) -> 'a end
+# val id : 'a -> 'a = <fun>
+# val ko : 'a -> unit = <fun>
+# Characters 64-99:
+ struct type +'a t = private int end
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type +'a t = private int end
+ is not included in
+ sig type -'a t = private int end
+ Type declarations do not match:
+ type +'a t = private int
+ is not included in
+ type -'a t = private int
+ Their variances do not agree.
+# module type A = sig type t = X of int end
+# type u = X of bool
+# Characters 23-33:
+ module type B = A with type t = u;; (* fail *)
+ ^^^^^^^^^^
+Error: This variant or record definition does not match that of type u
+ The types for field X are not equal.
+# Characters 121-124:
+ module type S = sig exception Foo of int exception Foo of bool end;;
+ ^^^
+Error: Multiple definition of the extension constructor name Foo.
+ Names must be unique in a given structure or signature.
+# module F : functor (X : sig end) -> sig val x : int end
+# Characters 0-3:
+ F.x;; (* fail *)
+ ^^^
+Error: The module F is a functor, not a structure
+#
diff --git a/testsuite/tests/typing-modules/a.mli b/testsuite/tests/typing-modules/a.mli
new file mode 100644
index 0000000000..ea15bf005b
--- /dev/null
+++ b/testsuite/tests/typing-modules/a.mli
@@ -0,0 +1,3 @@
+module L = List
+module S = String
+module D' = D
diff --git a/testsuite/tests/typing-modules/aliases.ml b/testsuite/tests/typing-modules/aliases.ml
new file mode 100644
index 0000000000..7580bebe7c
--- /dev/null
+++ b/testsuite/tests/typing-modules/aliases.ml
@@ -0,0 +1,246 @@
+module C = Char;;
+C.chr 66;;
+
+module C' : module type of Char = C;;
+C'.chr 66;;
+
+module C3 = struct include Char end;;
+C3.chr 66;;
+
+let f x = let module M = struct module L = List end in M.L.length x;;
+let g x = let module L = List in L.length (L.map succ x);;
+
+module F(X:sig end) = Char;;
+module C4 = F(struct end);;
+C4.chr 66;;
+
+module G(X:sig end) = struct module M = X end;; (* does not alias X *)
+module M = G(struct end);;
+
+module M' = struct
+ module N = struct let x = 1 end
+ module N' = N
+end;;
+M'.N'.x;;
+
+module M'' : sig module N' : sig val x : int end end = M';;
+M''.N'.x;;
+module M2 = struct include M' end;;
+module M3 : sig module N' : sig val x : int end end = struct include M' end;;
+M3.N'.x;;
+module M3' : sig module N' : sig val x : int end end = M2;;
+M3'.N'.x;;
+
+module M4 : sig module N' : sig val x : int end end = struct
+ module N = struct let x = 1 end
+ module N' = N
+end;;
+M4.N'.x;;
+
+module F(X:sig end) = struct
+ module N = struct let x = 1 end
+ module N' = N
+end;;
+module G : functor(X:sig end) -> sig module N' : sig val x : int end end = F;;
+module M5 = G(struct end);;
+M5.N'.x;;
+
+module M = struct
+ module D = struct let y = 3 end
+ module N = struct let x = 1 end
+ module N' = N
+end;;
+
+module M1 : sig module N : sig val x : int end module N' = N end = M;;
+M1.N'.x;;
+module M2 : sig module N' : sig val x : int end end =
+ (M : sig module N : sig val x : int end module N' = N end);;
+M2.N'.x;;
+
+open M;;
+N'.x;;
+
+module M = struct
+ module C = Char
+ module C' = C
+end;;
+module M1
+ : sig module C : sig val escaped : char -> string end module C' = C end
+ = M;; (* sound, but should probably fail *)
+M1.C'.escaped 'A';;
+module M2 : sig module C' : sig val chr : int -> char end end =
+ (M : sig module C : sig val chr : int -> char end module C' = C end);;
+M2.C'.chr 66;;
+
+StdLabels.List.map;;
+
+module Q = Queue;;
+exception QE = Q.Empty;;
+try Q.pop (Q.create ()) with QE -> "Ok";;
+
+module type Complex = module type of Complex with type t = Complex.t;;
+module M : sig module C : Complex end = struct module C = Complex end;;
+
+module C = Complex;;
+C.one.Complex.re;;
+include C;;
+
+module F(X:sig module C = Char end) = struct module C = X.C end;;
+
+(* Applicative functors *)
+module S = String
+module StringSet = Set.Make(String)
+module SSet = Set.Make(S);;
+let f (x : StringSet.t) = (x : SSet.t);;
+
+(* Also using include (cf. Leo's mail 2013-11-16) *)
+module F (M : sig end) : sig type t end = struct type t = int end
+module T = struct
+ module M = struct end
+ include F(M)
+end;;
+include T;;
+let f (x : t) : T.t = x ;;
+
+(* PR#4049 *)
+(* This works thanks to abbreviations *)
+module A = struct
+ module B = struct type t let compare x y = 0 end
+ module S = Set.Make(B)
+ let empty = S.empty
+end
+module A1 = A;;
+A1.empty = A.empty;;
+
+(* PR#3476 *)
+(* Does not work yet *)
+module FF(X : sig end) = struct type t end
+module M = struct
+ module X = struct end
+ module Y = FF (X) (* XXX *)
+ type t = Y.t
+end
+module F (Y : sig type t end) (M : sig type t = Y.t end) = struct end;;
+
+module G = F (M.Y);;
+(*module N = G (M);;
+module N = F (M.Y) (M);;*)
+
+(* PR#6307 *)
+
+module A1 = struct end
+module A2 = struct end
+module L1 = struct module X = A1 end
+module L2 = struct module X = A2 end;;
+
+module F (L : (module type of L1)) = struct end;;
+
+module F1 = F(L1);; (* ok *)
+module F2 = F(L2);; (* should succeed too *)
+
+(* Counter example: why we need to be careful with PR#6307 *)
+module Int = struct type t = int let compare = compare end
+module SInt = Set.Make(Int)
+type (_,_) eq = Eq : ('a,'a) eq
+type wrap = W of (SInt.t, SInt.t) eq
+
+module M = struct
+ module I = Int
+ type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
+end;;
+module type S = module type of M;; (* keep alias *)
+
+module Int2 = struct type t = int let compare x y = compare y x end;;
+module type S' = sig
+ module I = Int2
+ include S with module I := I
+end;; (* fail *)
+
+(* (* if the above succeeded, one could break invariants *)
+module rec M2 : S' = M2;; (* should succeed! (but this is bad) *)
+
+let M2.W eq = W Eq;;
+
+let s = List.fold_right SInt.add [1;2;3] SInt.empty;;
+module SInt2 = Set.Make(Int2);;
+let conv : type a b. (a,b) eq -> a -> b = fun Eq x -> x;;
+let s' : SInt2.t = conv eq s;;
+SInt2.elements s';;
+SInt2.mem 2 s';; (* invariants are broken *)
+*)
+
+(* Check behavior with submodules *)
+module M = struct
+ module N = struct module I = Int end
+ module P = struct module I = N.I end
+ module Q = struct
+ type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq
+ end
+end;;
+module type S = module type of M ;;
+
+module M = struct
+ module N = struct module I = Int end
+ module P = struct module I = N.I end
+ module Q = struct
+ type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq
+ end
+end;;
+module type S = module type of M ;;
+
+(* PR#6365 *)
+module type S = sig module M : sig type t val x : t end end;;
+module H = struct type t = A let x = A end;;
+module H' = H;;
+module type S' = S with module M = H';; (* shouldn't introduce an alias *)
+
+(* PR#6376 *)
+module type Alias = sig module N : sig end module M = N end;;
+module F (X : sig end) = struct type t end;;
+module type A = Alias with module N := F(List);;
+module rec Bad : A = Bad;;
+
+(* Shinwell 2014-04-23 *)
+module B = struct
+ module R = struct
+ type t = string
+ end
+
+ module O = R
+end
+
+module K = struct
+ module E = B
+ module N = E.O
+end;;
+
+let x : K.N.t = "foo";;
+
+(* PR#6465 *)
+
+module M = struct type t = A module B = struct type u = B end end;;
+module P : sig type t = M.t = A module B = M.B end = M;; (* should be ok *)
+module P : sig type t = M.t = A module B = M.B end = struct include M end;;
+
+module type S = sig
+ module M : sig module P : sig end end
+ module Q = M
+end;;
+module type S = sig
+ module M : sig module N : sig end module P : sig end end
+ module Q : sig module N = M.N module P = M.P end
+end;;
+module R = struct
+ module M = struct module N = struct end module P = struct end end
+ module Q = M
+end;;
+module R' : S = R;; (* should be ok *)
+
+(* PR#6578 *)
+
+module M = struct let f x = x end
+module rec R : sig module M : sig val f : 'a -> 'a end end =
+ struct module M = M end;;
+R.M.f 3;;
+module rec R : sig module M = M end = struct module M = M end;;
+R.M.f 3;;
diff --git a/testsuite/tests/typing-modules/aliases.ml.reference b/testsuite/tests/typing-modules/aliases.ml.reference
new file mode 100644
index 0000000000..724f01389c
--- /dev/null
+++ b/testsuite/tests/typing-modules/aliases.ml.reference
@@ -0,0 +1,402 @@
+
+# module C = Char
+# - : char = 'B'
+# module C' :
+ sig
+ external code : char -> int = "%identity"
+ val chr : int -> char
+ val escaped : char -> string
+ val lowercase : char -> char
+ val uppercase : char -> char
+ val lowercase_ascii : char -> char
+ val uppercase_ascii : char -> char
+ type t = char
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ external unsafe_chr : int -> char = "%identity"
+ end
+# - : char = 'B'
+# module C3 :
+ sig
+ external code : char -> int = "%identity"
+ val chr : int -> char
+ val escaped : char -> string
+ val lowercase : char -> char
+ val uppercase : char -> char
+ val lowercase_ascii : char -> char
+ val uppercase_ascii : char -> char
+ type t = char
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ external unsafe_chr : int -> char = "%identity"
+ end
+# - : char = 'B'
+# val f : 'a list -> int = <fun>
+# val g : int list -> int = <fun>
+# module F :
+ functor (X : sig end) ->
+ sig
+ external code : char -> int = "%identity"
+ val chr : int -> char
+ val escaped : char -> string
+ val lowercase : char -> char
+ val uppercase : char -> char
+ val lowercase_ascii : char -> char
+ val uppercase_ascii : char -> char
+ type t = char
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ external unsafe_chr : int -> char = "%identity"
+ end
+# module C4 :
+ sig
+ external code : char -> int = "%identity"
+ val chr : int -> char
+ val escaped : char -> string
+ val lowercase : char -> char
+ val uppercase : char -> char
+ val lowercase_ascii : char -> char
+ val uppercase_ascii : char -> char
+ type t = char
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ external unsafe_chr : int -> char = "%identity"
+ end
+# - : char = 'B'
+# module G : functor (X : sig end) -> sig module M : sig end end
+# module M : sig module M : sig end end
+# module M' : sig module N : sig val x : int end module N' = N end
+# - : int = 1
+# module M'' : sig module N' : sig val x : int end end
+# - : int = 1
+# module M2 : sig module N = M'.N module N' = M'.N' end
+# module M3 : sig module N' : sig val x : int end end
+# - : int = 1
+# module M3' : sig module N' : sig val x : int end end
+# - : int = 1
+# module M4 : sig module N' : sig val x : int end end
+# - : int = 1
+# module F :
+ functor (X : sig end) ->
+ sig module N : sig val x : int end module N' = N end
+# module G : functor (X : sig end) -> sig module N' : sig val x : int end end
+# module M5 : sig module N' : sig val x : int end end
+# - : int = 1
+# module M :
+ sig
+ module D : sig val y : int end
+ module N : sig val x : int end
+ module N' = N
+ end
+# module M1 : sig module N : sig val x : int end module N' = N end
+# - : int = 1
+# module M2 : sig module N' : sig val x : int end end
+# - : int = 1
+# # - : int = 1
+# module M : sig module C = Char module C' = C end
+# module M1 :
+ sig module C : sig val escaped : char -> string end module C' = C end
+# - : string = "A"
+# module M2 : sig module C' : sig val chr : int -> char end end
+# - : char = 'B'
+# - : f:('a -> 'b) -> 'a list -> 'b list = <fun>
+# module Q = Queue
+# exception QE
+# - : string = "Ok"
+# module type Complex =
+ sig
+ type t = Complex.t = { re : float; im : float; }
+ val zero : t
+ val one : t
+ val i : t
+ val neg : t -> t
+ val conj : t -> t
+ val add : t -> t -> t
+ val sub : t -> t -> t
+ val mul : t -> t -> t
+ val inv : t -> t
+ val div : t -> t -> t
+ val sqrt : t -> t
+ val norm2 : t -> float
+ val norm : t -> float
+ val arg : t -> float
+ val polar : float -> float -> t
+ val exp : t -> t
+ val log : t -> t
+ val pow : t -> t -> t
+ end
+# module M : sig module C : Complex end
+# module C = Complex
+# - : float = 1.
+# type t = Complex.t = { re : float; im : float; }
+val zero : t = {re = 0.; im = 0.}
+val one : t = {re = 1.; im = 0.}
+val i : t = {re = 0.; im = 1.}
+val neg : t -> t = <fun>
+val conj : t -> t = <fun>
+val add : t -> t -> t = <fun>
+val sub : t -> t -> t = <fun>
+val mul : t -> t -> t = <fun>
+val inv : t -> t = <fun>
+val div : t -> t -> t = <fun>
+val sqrt : t -> t = <fun>
+val norm2 : t -> float = <fun>
+val norm : t -> float = <fun>
+val arg : t -> float = <fun>
+val polar : float -> float -> t = <fun>
+val exp : t -> t = <fun>
+val log : t -> t = <fun>
+val pow : t -> t -> t = <fun>
+# module F : functor (X : sig module C = Char end) -> sig module C = Char end
+# module S = String
+module StringSet :
+ sig
+ type elt = String.t
+ type t = Set.Make(String).t
+ val empty : t
+ val is_empty : t -> bool
+ val mem : elt -> t -> bool
+ val add : elt -> t -> t
+ val singleton : elt -> t
+ val remove : elt -> t -> t
+ val union : t -> t -> t
+ val inter : t -> t -> t
+ val diff : t -> t -> t
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ val subset : t -> t -> bool
+ val iter : (elt -> unit) -> t -> unit
+ val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
+ val for_all : (elt -> bool) -> t -> bool
+ val exists : (elt -> bool) -> t -> bool
+ val filter : (elt -> bool) -> t -> t
+ val partition : (elt -> bool) -> t -> t * t
+ val cardinal : t -> int
+ val elements : t -> elt list
+ val min_elt : t -> elt
+ val max_elt : t -> elt
+ val choose : t -> elt
+ val split : elt -> t -> t * bool * t
+ val find : elt -> t -> elt
+ val of_list : elt list -> t
+ end
+module SSet :
+ sig
+ type elt = S.t
+ type t = Set.Make(S).t
+ val empty : t
+ val is_empty : t -> bool
+ val mem : elt -> t -> bool
+ val add : elt -> t -> t
+ val singleton : elt -> t
+ val remove : elt -> t -> t
+ val union : t -> t -> t
+ val inter : t -> t -> t
+ val diff : t -> t -> t
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ val subset : t -> t -> bool
+ val iter : (elt -> unit) -> t -> unit
+ val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
+ val for_all : (elt -> bool) -> t -> bool
+ val exists : (elt -> bool) -> t -> bool
+ val filter : (elt -> bool) -> t -> t
+ val partition : (elt -> bool) -> t -> t * t
+ val cardinal : t -> int
+ val elements : t -> elt list
+ val min_elt : t -> elt
+ val max_elt : t -> elt
+ val choose : t -> elt
+ val split : elt -> t -> t * bool * t
+ val find : elt -> t -> elt
+ val of_list : elt list -> t
+ end
+# val f : StringSet.t -> SSet.t = <fun>
+# module F : functor (M : sig end) -> sig type t end
+module T : sig module M : sig end type t = F(M).t end
+# module M = T.M
+type t = F(M).t
+# val f : t -> T.t = <fun>
+# module A :
+ sig
+ module B : sig type t val compare : 'a -> 'b -> int end
+ module S :
+ sig
+ type elt = B.t
+ type t = Set.Make(B).t
+ val empty : t
+ val is_empty : t -> bool
+ val mem : elt -> t -> bool
+ val add : elt -> t -> t
+ val singleton : elt -> t
+ val remove : elt -> t -> t
+ val union : t -> t -> t
+ val inter : t -> t -> t
+ val diff : t -> t -> t
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ val subset : t -> t -> bool
+ val iter : (elt -> unit) -> t -> unit
+ val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
+ val for_all : (elt -> bool) -> t -> bool
+ val exists : (elt -> bool) -> t -> bool
+ val filter : (elt -> bool) -> t -> t
+ val partition : (elt -> bool) -> t -> t * t
+ val cardinal : t -> int
+ val elements : t -> elt list
+ val min_elt : t -> elt
+ val max_elt : t -> elt
+ val choose : t -> elt
+ val split : elt -> t -> t * bool * t
+ val find : elt -> t -> elt
+ val of_list : elt list -> t
+ end
+ val empty : S.t
+ end
+module A1 = A
+# - : bool = true
+# module FF : functor (X : sig end) -> sig type t end
+module M :
+ sig
+ module X : sig end
+ module Y : sig type t = FF(X).t end
+ type t = Y.t
+ end
+module F :
+ functor (Y : sig type t end) (M : sig type t = Y.t end) -> sig end
+# module G : functor (M : sig type t = M.Y.t end) -> sig end
+# * module A1 : sig end
+module A2 : sig end
+module L1 : sig module X = A1 end
+module L2 : sig module X = A2 end
+# module F : functor (L : sig module X : sig end end) -> sig end
+# module F1 : sig end
+# module F2 : sig end
+# module Int : sig type t = int val compare : 'a -> 'a -> int end
+module SInt :
+ sig
+ type elt = Int.t
+ type t = Set.Make(Int).t
+ val empty : t
+ val is_empty : t -> bool
+ val mem : elt -> t -> bool
+ val add : elt -> t -> t
+ val singleton : elt -> t
+ val remove : elt -> t -> t
+ val union : t -> t -> t
+ val inter : t -> t -> t
+ val diff : t -> t -> t
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ val subset : t -> t -> bool
+ val iter : (elt -> unit) -> t -> unit
+ val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
+ val for_all : (elt -> bool) -> t -> bool
+ val exists : (elt -> bool) -> t -> bool
+ val filter : (elt -> bool) -> t -> t
+ val partition : (elt -> bool) -> t -> t * t
+ val cardinal : t -> int
+ val elements : t -> elt list
+ val min_elt : t -> elt
+ val max_elt : t -> elt
+ val choose : t -> elt
+ val split : elt -> t -> t * bool * t
+ val find : elt -> t -> elt
+ val of_list : elt list -> t
+ end
+type (_, _) eq = Eq : ('a, 'a) eq
+type wrap = W of (SInt.t, SInt.t) eq
+module M :
+ sig
+ module I = Int
+ type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
+ end
+# module type S =
+ sig
+ module I = Int
+ type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
+ end
+# module Int2 : sig type t = int val compare : 'a -> 'a -> int end
+# Characters 49-69:
+ include S with module I := I
+ ^^^^^^^^^^^^^^^^^^^^
+Error: In this `with' constraint, the new definition of I
+ does not match its original definition in the constrained signature:
+ Modules do not match: (module Int2) is not included in (module Int)
+# * * * * * * * * * * * module M :
+ sig
+ module N : sig module I = Int end
+ module P : sig module I = N.I end
+ module Q :
+ sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq end
+ end
+# module type S =
+ sig
+ module N : sig module I = Int end
+ module P : sig module I = N.I end
+ module Q :
+ sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq end
+ end
+# module M :
+ sig
+ module N : sig module I = Int end
+ module P : sig module I = N.I end
+ module Q :
+ sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq end
+ end
+# module type S =
+ sig
+ module N : sig module I = Int end
+ module P :
+ sig module I : sig type t = int val compare : 'a -> 'a -> int end end
+ module Q :
+ sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq end
+ end
+# module type S = sig module M : sig type t val x : t end end
+# module H : sig type t = A val x : t end
+# module H' = H
+# module type S' = sig module M : sig type t = H.t = A val x : t end end
+# module type Alias = sig module N : sig end module M = N end
+# module F : functor (X : sig end) -> sig type t end
+# Characters -1--1:
+ module type A = Alias with module N := F(List);;
+
+Error: Module type declarations do not match:
+ module type A = sig module M = F(List) end
+ does not match
+ module type A = sig module M = F(List) end
+ At position module type A = <here>
+ Modules do not match:
+ sig module M = F(List) end
+ is not included in
+ sig module M = F(List) end
+ At position module type A = sig module M : <here> end
+ Module F(List) cannot be aliased
+# Characters 17-18:
+ module rec Bad : A = Bad;;
+ ^
+Error: Unbound module type A
+# module B : sig module R : sig type t = string end module O = R end
+module K : sig module E = B module N = E.O end
+# val x : K.N.t = "foo"
+# module M : sig type t = A module B : sig type u = B end end
+# module P : sig type t = M.t = A module B = M.B end
+# module P : sig type t = M.t = A module B = M.B end
+# module type S = sig module M : sig module P : sig end end module Q = M end
+# module type S =
+ sig
+ module M : sig module N : sig end module P : sig end end
+ module Q : sig module N = M.N module P = M.P end
+ end
+# module R :
+ sig
+ module M : sig module N : sig end module P : sig end end
+ module Q = M
+ end
+# module R' : S
+# module M : sig val f : 'a -> 'a end
+module rec R : sig module M : sig val f : 'a -> 'a end end
+# - : int = 3
+# module rec R : sig module M = M end
+# - : int = 3
+#
diff --git a/testsuite/tests/typing-modules/b.ml b/testsuite/tests/typing-modules/b.ml
new file mode 100644
index 0000000000..4c43e809fd
--- /dev/null
+++ b/testsuite/tests/typing-modules/b.ml
@@ -0,0 +1,18 @@
+open A
+let f =
+ L.map S.capitalize
+
+let () =
+ L.iter print_endline (f ["jacques"; "garrigue"])
+
+module C : sig module L : module type of List end = struct include A end
+
+(* The following introduces a (useless) dependency on A:
+module C : sig module L : module type of List end = A
+*)
+
+include D'
+(*
+let () =
+ print_endline (string_of_int D'.M.y)
+*)
diff --git a/testsuite/tests/typing-modules/b2.ml b/testsuite/tests/typing-modules/b2.ml
new file mode 100644
index 0000000000..034e432c34
--- /dev/null
+++ b/testsuite/tests/typing-modules/b2.ml
@@ -0,0 +1,14 @@
+open A
+let f =
+ L.map S.capitalize
+
+let () =
+ L.iter print_endline (f ["jacques"; "garrigue"])
+
+module C : sig module L : module type of List end = struct include A end
+
+(* The following introduces a (useless) dependency on A:
+module C : sig module L : module type of List end = A
+*)
+
+(* No dependency on D *)
diff --git a/testsuite/tests/typing-modules/b3.mli b/testsuite/tests/typing-modules/b3.mli
new file mode 100644
index 0000000000..04599abe34
--- /dev/null
+++ b/testsuite/tests/typing-modules/b3.mli
@@ -0,0 +1,4 @@
+open A
+(*module type S = module type of D'.M*)
+type t = Complex.t
+type s = String.t
diff --git a/testsuite/tests/typing-modules/d.ml b/testsuite/tests/typing-modules/d.ml
new file mode 100644
index 0000000000..55d311f408
--- /dev/null
+++ b/testsuite/tests/typing-modules/d.ml
@@ -0,0 +1,2 @@
+let x = 3
+module M = struct let y = 5 end
diff --git a/testsuite/tests/typing-modules/firstclass.ml b/testsuite/tests/typing-modules/firstclass.ml
new file mode 100644
index 0000000000..b778443a8d
--- /dev/null
+++ b/testsuite/tests/typing-modules/firstclass.ml
@@ -0,0 +1,21 @@
+module type S = sig type u type t end;;
+module type S' = sig type t = int type u = bool end;;
+
+(* ok to convert between structurally equal signatures, and parameters
+ are inferred *)
+let f (x : (module S with type t = 'a and type u = 'b)) = (x : (module S'));;
+let g x = (x : (module S with type t = 'a and type u = 'b) :> (module S'));;
+
+(* with subtyping it is also ok to forget some types *)
+module type S2 = sig type u type t type w end;;
+let g2 x = (x : (module S2 with type t = 'a and type u = 'b) :> (module S'));;
+let h x = (x : (module S2 with type t = 'a) :> (module S with type t = 'a));;
+let f2 (x : (module S2 with type t = 'a and type u = 'b)) =
+ (x : (module S'));; (* fail *)
+let k (x : (module S2 with type t = 'a)) =
+ (x : (module S with type t = 'a));; (* fail *)
+
+(* but you cannot forget values (no physical coercions) *)
+module type S3 = sig type u type t val x : int end;;
+let g3 x =
+ (x : (module S3 with type t = 'a and type u = 'b) :> (module S'));; (* fail *)
diff --git a/testsuite/tests/typing-modules/firstclass.ml.reference b/testsuite/tests/typing-modules/firstclass.ml.reference
new file mode 100644
index 0000000000..db376005a1
--- /dev/null
+++ b/testsuite/tests/typing-modules/firstclass.ml.reference
@@ -0,0 +1,27 @@
+
+# module type S = sig type u type t end
+# module type S' = sig type t = int type u = bool end
+# * val f : (module S with type t = int and type u = bool) -> (module S') = <fun>
+# val g : (module S with type t = int and type u = bool) -> (module S') = <fun>
+# module type S2 = sig type u type t type w end
+# val g2 : (module S2 with type t = int and type u = bool) -> (module S') =
+ <fun>
+# val h : (module S2 with type t = 'a) -> (module S with type t = 'a) = <fun>
+# Characters 63-64:
+ (x : (module S'));; (* fail *)
+ ^
+Error: This expression has type
+ (module S2 with type t = int and type u = bool)
+ but an expression was expected of type (module S')
+# Characters 46-47:
+ (x : (module S with type t = 'a));; (* fail *)
+ ^
+Error: This expression has type (module S2 with type t = 'a)
+ but an expression was expected of type (module S with type t = 'a)
+# module type S3 = sig type u type t val x : int end
+# Characters 13-78:
+ (x : (module S3 with type t = 'a and type u = 'b) :> (module S'));; (* fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type (module S3 with type t = int and type u = bool)
+ is not a subtype of (module S')
+#
diff --git a/testsuite/tests/typing-modules/generative.ml b/testsuite/tests/typing-modules/generative.ml
new file mode 100644
index 0000000000..dc5bf52898
--- /dev/null
+++ b/testsuite/tests/typing-modules/generative.ml
@@ -0,0 +1,34 @@
+(* Using generative functors *)
+
+(* Without type *)
+module type S = sig val x : int end;;
+let v = (module struct let x = 3 end : S);;
+module F() = (val v);; (* ok *)
+module G (X : sig end) : S = F ();; (* ok *)
+module H (X : sig end) = (val v);; (* ok *)
+
+(* With type *)
+module type S = sig type t val x : t end;;
+let v = (module struct type t = int let x = 3 end : S);;
+module F() = (val v);; (* ok *)
+module G (X : sig end) : S = F ();; (* fail *)
+module H() = F();; (* ok *)
+
+(* Alias *)
+module U = struct end;;
+module M = F(struct end);; (* ok *)
+module M = F(U);; (* fail *)
+
+(* Cannot coerce between applicative and generative *)
+module F1 (X : sig end) = struct end;;
+module F2 : functor () -> sig end = F1;; (* fail *)
+module F3 () = struct end;;
+module F4 : functor (X : sig end) -> sig end = F3;; (* fail *)
+
+(* tests for shortened functor notation () *)
+module X (X: sig end) (Y: sig end) = functor (Z: sig end) -> struct end;;
+module Y = functor (X: sig end) (Y:sig end) -> functor (Z: sig end) ->
+ struct end;;
+module Z = functor (_: sig end) (_:sig end) (_: sig end) -> struct end;;
+module GZ : functor (X: sig end) () (Z: sig end) -> sig end
+ = functor (X: sig end) () (Z: sig end) -> struct end;;
diff --git a/testsuite/tests/typing-modules/generative.ml.reference b/testsuite/tests/typing-modules/generative.ml.reference
new file mode 100644
index 0000000000..a6aa100266
--- /dev/null
+++ b/testsuite/tests/typing-modules/generative.ml.reference
@@ -0,0 +1,44 @@
+
+# module type S = sig val x : int end
+# val v : (module S) = <module>
+# module F : functor () -> S
+# module G : functor (X : sig end) -> S
+# module H : functor (X : sig end) -> S
+# module type S = sig type t val x : t end
+# val v : (module S) = <module>
+# module F : functor () -> S
+# Characters 29-33:
+ module G (X : sig end) : S = F ();; (* fail *)
+ ^^^^
+Error: This expression creates fresh types.
+ It is not allowed inside applicative functors.
+# module H : functor () -> S
+# module U : sig end
+# module M : S
+# Characters 11-12:
+ module M = F(U);; (* fail *)
+ ^
+Error: This is a generative functor. It can only be applied to ()
+# module F1 : functor (X : sig end) -> sig end
+# Characters 36-38:
+ module F2 : functor () -> sig end = F1;; (* fail *)
+ ^^
+Error: Signature mismatch:
+ Modules do not match:
+ functor (X : sig end) -> sig end
+ is not included in
+ functor () -> sig end
+# module F3 : functor () -> sig end
+# Characters 47-49:
+ module F4 : functor (X : sig end) -> sig end = F3;; (* fail *)
+ ^^
+Error: Signature mismatch:
+ Modules do not match:
+ functor () -> sig end
+ is not included in
+ functor (X : sig end) -> sig end
+# module X : functor (X : sig end) (Y : sig end) (Z : sig end) -> sig end
+# module Y : functor (X : sig end) (Y : sig end) (Z : sig end) -> sig end
+# module Z : functor (_ : sig end) (_ : sig end) (_ : sig end) -> sig end
+# module GZ : functor (X : sig end) () (Z : sig end) -> sig end
+#
diff --git a/testsuite/tests/typing-modules/pr5911.ml b/testsuite/tests/typing-modules/pr5911.ml
new file mode 100644
index 0000000000..1fa991f179
--- /dev/null
+++ b/testsuite/tests/typing-modules/pr5911.ml
@@ -0,0 +1,14 @@
+module type S = sig
+ type t
+ val x : t
+end;;
+
+module Good (X : S with type t := unit) = struct
+ let () = X.x
+end;;
+
+module type T = sig module M : S end;;
+
+module Bad (X : T with type M.t := unit) = struct
+ let () = X.M.x
+end;;
diff --git a/testsuite/tests/typing-modules/pr5911.ml.reference b/testsuite/tests/typing-modules/pr5911.ml.reference
new file mode 100644
index 0000000000..e5357b8449
--- /dev/null
+++ b/testsuite/tests/typing-modules/pr5911.ml.reference
@@ -0,0 +1,9 @@
+
+# module type S = sig type t val x : t end
+# module Good : functor (X : sig val x : unit end) -> sig end
+# module type T = sig module M : S end
+# Characters 33-35:
+ module Bad (X : T with type M.t := unit) = struct
+ ^^
+Error: Syntax error
+#
diff --git a/testsuite/tests/typing-modules/printing.ml b/testsuite/tests/typing-modules/printing.ml
new file mode 100644
index 0000000000..77dd8c70ee
--- /dev/null
+++ b/testsuite/tests/typing-modules/printing.ml
@@ -0,0 +1,14 @@
+(* PR#6650 *)
+
+module type S = sig
+ class type c = object method m : int end
+ module M : sig
+ class type d = c
+ end
+end;;
+module F (X : S) = X.M;;
+
+(* PR#6648 *)
+
+module M = struct module N = struct let x = 1 end end;;
+#show_module M;;
diff --git a/testsuite/tests/typing-modules/printing.ml.reference b/testsuite/tests/typing-modules/printing.ml.reference
new file mode 100644
index 0000000000..c5a9a773db
--- /dev/null
+++ b/testsuite/tests/typing-modules/printing.ml.reference
@@ -0,0 +1,10 @@
+
+# module type S =
+ sig
+ class type c = object method m : int end
+ module M : sig class type d = c end
+ end
+# module F : functor (X : S) -> sig class type d = X.c end
+# module M : sig module N : sig val x : int end end
+# module M : sig module N : sig ... end end
+#
diff --git a/testsuite/tests/typing-objects-bugs/Makefile b/testsuite/tests/typing-objects-bugs/Makefile
new file mode 100644
index 0000000000..1103dbffda
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.okbad
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-objects-bugs/pr3968_bad.ml b/testsuite/tests/typing-objects-bugs/pr3968_bad.ml
new file mode 100644
index 0000000000..01c5066654
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/pr3968_bad.ml
@@ -0,0 +1,21 @@
+type expr =
+ [ `Abs of string * expr
+ | `App of expr * expr
+ ]
+
+class type exp =
+object
+ method eval : (string, exp) Hashtbl.t -> expr
+end;;
+
+class app e1 e2 : exp =
+object
+ val l = e1
+ val r = e2
+ method eval env =
+ match l with
+ | `Abs(var,body) ->
+ Hashtbl.add env var r;
+ body
+ | _ -> `App(l,r);
+end
diff --git a/testsuite/tests/typing-objects-bugs/pr4018_bad.ml b/testsuite/tests/typing-objects-bugs/pr4018_bad.ml
new file mode 100644
index 0000000000..5195d46397
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/pr4018_bad.ml
@@ -0,0 +1,46 @@
+
+class virtual ['subject, 'event] observer =
+ object
+ method virtual notify : 'subject -> 'event -> unit
+ end
+
+class ['event] subject =
+ object (self : 'subject)
+ val mutable observers = ([]: (('subject, 'event) observer) list)
+ method add_observer obs = observers <- (obs :: observers)
+ method notify_observers (e : 'event) =
+ List.iter (fun x -> x#notify self e) observers
+ end
+
+type id = int
+
+class entity (id : id) =
+ object
+ val ent_destroy_subject = new subject
+ method destroy_subject : (id) subject = ent_destroy_subject
+
+ method entity_id = id
+ end
+
+class ['entity] entity_container =
+ object (self)
+ inherit ['entity, id] observer as observer
+
+ method add_entity (e : 'entity) =
+ e#destroy_subject#add_observer (self)
+
+ method notify _ id = ()
+ end
+
+let f (x : entity entity_container) = ()
+
+(*
+class world =
+ object
+ val entity_container : entity entity_container = new entity_container
+
+ method add_entity (s : entity) =
+ entity_container#add_entity (s :> entity)
+
+ end
+*)
diff --git a/testsuite/tests/typing-objects-bugs/pr4435_bad.ml b/testsuite/tests/typing-objects-bugs/pr4435_bad.ml
new file mode 100644
index 0000000000..c9e1d4997b
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/pr4435_bad.ml
@@ -0,0 +1,11 @@
+(* Two v's in the same class *)
+class c v = object initializer print_endline v val v = 42 end;;
+new c "42";;
+
+(* Two hidden v's in the same class! *)
+class c (v : int) =
+ object
+ method v0 = v
+ inherit ((fun v -> object method v : string = v end) "42")
+ end;;
+(new c 42)#v0;;
diff --git a/testsuite/tests/typing-objects-bugs/pr4766_ok.ml b/testsuite/tests/typing-objects-bugs/pr4766_ok.ml
new file mode 100644
index 0000000000..726cc86669
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/pr4766_ok.ml
@@ -0,0 +1,10 @@
+class virtual ['a] c =
+object (s : 'a)
+ method virtual m : 'b
+end
+
+let o =
+ object (s :'a)
+ inherit ['a] c
+ method m = 42
+ end
diff --git a/testsuite/tests/typing-objects-bugs/pr4824_ok.ml b/testsuite/tests/typing-objects-bugs/pr4824_ok.ml
new file mode 100644
index 0000000000..906959374b
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/pr4824_ok.ml
@@ -0,0 +1,10 @@
+module M :
+ sig
+ class x : int -> object method m : int end
+ end
+=
+struct
+ class x _ = object
+ method m = 42
+ end
+end;;
diff --git a/testsuite/tests/typing-objects-bugs/pr4824a_bad.ml b/testsuite/tests/typing-objects-bugs/pr4824a_bad.ml
new file mode 100644
index 0000000000..983455b4b4
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/pr4824a_bad.ml
@@ -0,0 +1,6 @@
+module M : sig class c : 'a -> object val x : 'b end end =
+ struct class c x = object val x = x end end
+
+class c (x : int) = object inherit M.c x method x : bool = x end
+
+let r = (new c 2)#x;;
diff --git a/testsuite/tests/typing-objects-bugs/pr5156_ok.ml b/testsuite/tests/typing-objects-bugs/pr5156_ok.ml
new file mode 100644
index 0000000000..ba8288da0a
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/pr5156_ok.ml
@@ -0,0 +1,10 @@
+class type t = object end;;
+class ['a] o1 = object (self : #t as 'a) end;;
+type 'a obj = ( < .. > as 'a);;
+class type ['a] o2 = object ('a obj) end;;
+class ['a] o3 = object (self : 'a obj) end;;
+class ['a] o4 = object (self) method m = (self : 'a obj) end;;
+(*
+let o = object (self : 'a obj) end;;
+let o = object (self) method m = (self : 'a obj) end;;
+*)
diff --git a/testsuite/tests/typing-objects-bugs/woodyatt_ok.ml b/testsuite/tests/typing-objects-bugs/woodyatt_ok.ml
new file mode 100644
index 0000000000..627158bc87
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/woodyatt_ok.ml
@@ -0,0 +1,14 @@
+(* test.ml *)
+class alfa = object(_:'self)
+ method x: 'a. ('a, out_channel, unit) format -> 'a = Printf.printf
+end
+
+class bravo a = object
+ val y = (a :> alfa)
+ initializer y#x "bravo initialized"
+end
+
+class charlie a = object
+ inherit bravo a
+ initializer y#x "charlie initialized"
+end
diff --git a/testsuite/tests/typing-objects-bugs/yamagata021012_ok.ml b/testsuite/tests/typing-objects-bugs/yamagata021012_ok.ml
new file mode 100644
index 0000000000..fda0d123ce
--- /dev/null
+++ b/testsuite/tests/typing-objects-bugs/yamagata021012_ok.ml
@@ -0,0 +1,193 @@
+(* The module begins *)
+exception Out_of_range
+
+class type ['a] cursor =
+ object
+ method get : 'a
+ method incr : unit -> unit
+ method is_last : bool
+ end
+
+class type ['a] storage =
+ object ('self)
+ method first : 'a cursor
+ method len : int
+ method nth : int -> 'a cursor
+ method copy : 'self
+ method sub : int -> int -> 'self
+ method concat : 'a storage -> 'self
+ method fold : 'b. ('a -> int -> 'b -> 'b) -> 'b -> 'b
+ method iter : ('a -> unit) -> unit
+ end
+
+class virtual ['a, 'cursor] storage_base =
+ object (self : 'self)
+ constraint 'cursor = 'a #cursor
+ method virtual first : 'cursor
+ method virtual len : int
+ method virtual copy : 'self
+ method virtual sub : int -> int -> 'self
+ method virtual concat : 'a storage -> 'self
+ method fold : 'b. ('a -> int -> 'b -> 'b) -> 'b -> 'b = fun f a0 ->
+ let cur = self#first in
+ let rec loop count a =
+ if count >= self#len then a else
+ let a' = f cur#get count a in
+ cur#incr (); loop (count + 1) a'
+ in
+ loop 0 a0
+ method iter proc =
+ let p = self#first in
+ for i = 0 to self#len - 2 do proc p#get; p#incr () done;
+ if self#len > 0 then proc p#get else ()
+ end
+
+class type ['a] obj_input_channel =
+ object
+ method get : unit -> 'a
+ method close : unit -> unit
+ end
+
+class type ['a] obj_output_channel =
+ object
+ method put : 'a -> unit
+ method flush : unit -> unit
+ method close : unit -> unit
+ end
+
+module UChar =
+struct
+
+ type t = int
+
+ let highest_bit = 1 lsl 30
+ let lower_bits = highest_bit - 1
+
+ let char_of c =
+ try Char.chr c with Invalid_argument _ -> raise Out_of_range
+
+ let of_char = Char.code
+
+ let code c =
+ if c lsr 30 = 0
+ then c
+ else raise Out_of_range
+
+ let chr n =
+ if n >= 0 && (n lsr 31 = 0) then n else raise Out_of_range
+
+ let uint_code c = c
+ let chr_of_uint n = n
+
+end
+
+type uchar = UChar.t
+
+let int_of_uchar u = UChar.uint_code u
+let uchar_of_int n = UChar.chr_of_uint n
+
+class type ucursor = [uchar] cursor
+
+class type ustorage = [uchar] storage
+
+class virtual ['ucursor] ustorage_base = [uchar, 'ucursor] storage_base
+
+module UText =
+struct
+
+(* the internal representation is UCS4 with big endian*)
+(* The most significant digit appears first. *)
+let get_buf s i =
+ let n = Char.code s.[i] in
+ let n = (n lsl 8) lor (Char.code s.[i + 1]) in
+ let n = (n lsl 8) lor (Char.code s.[i + 2]) in
+ let n = (n lsl 8) lor (Char.code s.[i + 3]) in
+ UChar.chr_of_uint n
+
+let set_buf s i u =
+ let n = UChar.uint_code u in
+ begin
+ s.[i] <- Char.chr (n lsr 24);
+ s.[i + 1] <- Char.chr (n lsr 16 lor 0xff);
+ s.[i + 2] <- Char.chr (n lsr 8 lor 0xff);
+ s.[i + 3] <- Char.chr (n lor 0xff);
+ end
+
+let init_buf buf pos init =
+ if init#len = 0 then () else
+ let cur = init#first in
+ for i = 0 to init#len - 2 do
+ set_buf buf (pos + i lsl 2) (cur#get); cur#incr ()
+ done;
+ set_buf buf (pos + (init#len - 1) lsl 2) (cur#get)
+
+let make_buf init =
+ let s = String.create (init#len lsl 2) in
+ init_buf s 0 init; s
+
+class text_raw buf =
+ object (self : 'self)
+ inherit [cursor] ustorage_base
+ val contents = buf
+ method first = new cursor (self :> text_raw) 0
+ method len = (String.length contents) / 4
+ method get i = get_buf contents (4 * i)
+ method nth i = new cursor (self :> text_raw) i
+ method copy = {< contents = String.copy contents >}
+ method sub pos len =
+ {< contents = String.sub contents (pos * 4) (len * 4) >}
+ method concat (text : ustorage) =
+ let buf = String.create (String.length contents + 4 * text#len) in
+ String.blit contents 0 buf 0 (String.length contents);
+ init_buf buf (String.length contents) text;
+ {< contents = buf >}
+ end
+and cursor text i =
+ object
+ val contents = text
+ val mutable pos = i
+ method get = contents#get pos
+ method incr () = pos <- pos + 1
+ method is_last = (pos + 1 >= contents#len)
+ end
+
+class string_raw buf =
+ object
+ inherit text_raw buf
+ method set i u = set_buf contents (4 * i) u
+ end
+
+class text init = text_raw (make_buf init)
+class string init = string_raw (make_buf init)
+
+let of_string s =
+ let buf = String.make (4 * String.length s) '\000' in
+ for i = 0 to String.length s - 1 do
+ buf.[4 * i] <- s.[i]
+ done;
+ new text_raw buf
+
+let make len u =
+ let s = String.create (4 * len) in
+ for i = 0 to len - 1 do set_buf s (4 * i) u done;
+ new string_raw s
+
+let create len = make len (UChar.chr 0)
+
+let copy s = s#copy
+
+let sub s start len = s#sub start len
+
+let fill s start len u =
+ for i = start to start + len - 1 do s#set i u done
+
+let blit src srcoff dst dstoff len =
+ for i = 0 to len - 1 do
+ let u = src#get (srcoff + i) in
+ dst#set (dstoff + i) u
+ done
+
+let concat s1 s2 = s1#concat (s2 (* : #ustorage *) :> uchar storage)
+
+let iter proc s = s#iter proc
+end
diff --git a/testsuite/tests/typing-objects/Exemples.ml b/testsuite/tests/typing-objects/Exemples.ml
new file mode 100644
index 0000000000..5ffc6498f9
--- /dev/null
+++ b/testsuite/tests/typing-objects/Exemples.ml
@@ -0,0 +1,333 @@
+
+class point x_init = object
+ val mutable x = x_init
+ method get_x = x
+ method move d = x <- x + d
+end;;
+
+let p = new point 7;;
+
+p#get_x;;
+p#move 3;;
+p#get_x;;
+
+let q = Oo.copy p;;
+
+q#move 7; p#get_x, q#get_x;;
+
+class color_point x (c : string) = object
+ inherit point x
+ val c = c
+ method color = c
+end;;
+
+let p' = new color_point 5 "red";;
+
+p'#get_x, p'#color;;
+
+let l = [p; (p' :> point)];;
+
+let get_x p = p#get_x;;
+let set_x p = p#set_x;;
+List.map get_x l;;
+
+class ref x_init = object
+ val mutable x = x_init
+ method get = x
+ method set y = x <- y
+end;;
+
+class ref (x_init:int) = object
+ val mutable x = x_init
+ method get = x
+ method set y = x <- y
+end;;
+
+class ['a] ref x_init = object
+ val mutable x = (x_init : 'a)
+ method get = x
+ method set y = x <- y
+end;;
+
+let r = new ref 1 in r#set 2; (r#get);;
+
+class ['a] circle (c : 'a) = object
+ val mutable center = c
+ method center = center
+ method set_center c = center <- c
+ method move = (center#move : int -> unit)
+end;;
+
+class ['a] circle (c : 'a) = object
+ constraint 'a = #point
+ val mutable center = c
+ method center = center
+ method set_center c = center <- c
+ method move = center#move
+end;;
+
+let (c, c') = (new circle p, new circle p');;
+
+class ['a] color_circle c = object
+ constraint 'a = #color_point
+ inherit ['a] circle c
+ method color = center#color
+end;;
+
+let c'' = new color_circle p;;
+let c'' = new color_circle p';;
+
+(c'' :> color_point circle);;
+(c'' :> point circle);; (* Echec *)
+fun x -> (x : color_point color_circle :> point circle);;
+
+class printable_point y = object (s)
+ inherit point y
+ method print = print_int s#get_x
+end;;
+
+let p = new printable_point 7;;
+p#print;;
+
+class printable_color_point y c = object (self)
+ inherit color_point y c
+ inherit printable_point y as super
+ method print =
+ print_string "(";
+ super#print;
+ print_string ", ";
+ print_string (self#color);
+ print_string ")"
+end;;
+
+let p' = new printable_color_point 7 "red";;
+p'#print;;
+
+class functional_point y = object
+ val x = y
+ method get_x = x
+ method move d = {< x = x + d >}
+end;;
+
+let p = new functional_point 7;;
+
+p#get_x;;
+(p#move 3)#get_x;;
+p#get_x;;
+
+fun x -> (x :> functional_point);;
+
+(*******************************************************************)
+
+class virtual ['a] lst () = object (self)
+ method virtual null : bool
+ method virtual hd : 'a
+ method virtual tl : 'a lst
+ method map f =
+ (if self#null then
+ new nil ()
+ else
+ new cons (f self#hd) (self#tl#map f)
+ : 'a lst)
+ method iter (f : 'a -> unit) =
+ if self#null then ()
+ else begin
+ f self#hd;
+ self#tl#iter f
+ end
+ method print (f : 'a -> unit) =
+ print_string "(";
+ self#iter (fun x -> f x; print_string "::");
+ print_string "[]";
+ print_string ")"
+end and ['a] nil () = object
+ inherit ['a] lst ()
+ method null = true
+ method hd = failwith "hd"
+ method tl = failwith "tl"
+end and ['a] cons h t = object
+ inherit ['a] lst ()
+ val h = h val t = t
+ method null = false
+ method hd = h
+ method tl = t
+end;;
+
+let l1 = new cons 3 (new cons 10 (new nil ()));;
+
+l1#print print_int;;
+
+let l2 = l1#map (fun x -> x + 1);;
+l2#print print_int;;
+
+let rec map_list f (x:'a lst) =
+ if x#null then new nil()
+ else new cons (f x#hd) (map_list f x#tl);;
+
+let p1 = (map_list (fun x -> new printable_color_point x "red") l1);;
+p1#print (fun x -> x#print);;
+
+(*******************************************************************)
+
+class virtual comparable () = object (self : 'a)
+ method virtual cmp : 'a -> int
+ end;;
+
+class int_comparable (x : int) = object
+ inherit comparable ()
+ val x = x
+ method x = x
+ method cmp p = compare x p#x
+end;;
+
+class int_comparable2 xi = object
+ inherit int_comparable xi
+ val mutable x' = xi
+ method set_x y = x' <- y
+end;;
+
+class ['a] sorted_list () = object
+ constraint 'a = #comparable
+ val mutable l = ([] : 'a list)
+ method add x =
+ let rec insert =
+ function
+ [] -> [x]
+ | a::l as l' -> if a#cmp x <= 0 then a::(insert l) else x::l'
+ in
+ l <- insert l
+ method hd = List.hd l
+end;;
+
+let l = new sorted_list ();;
+let c = new int_comparable 10;;
+l#add c;;
+
+let c2 = new int_comparable2 15;;
+l#add (c2 :> int_comparable);; (* Echec : 'a comp2 n'est un sous-type *)
+(new sorted_list ())#add c2;;
+
+class int_comparable3 (x : int) = object
+ val mutable x = x
+ method cmp (y : int_comparable) = compare x y#x
+ method x = x
+ method setx y = x <- y
+end;;
+
+let c3 = new int_comparable3 15;;
+l#add (c3 :> int_comparable);;
+(new sorted_list ())#add c3;; (* Error; strange message with -principal *)
+
+let sort (l : #comparable list) = List.sort (fun x -> x#cmp) l;;
+let pr l =
+ List.map (fun c -> print_int c#x; print_string " ") l;
+ print_newline ();;
+let l = [new int_comparable 5; (new int_comparable3 2 :> int_comparable);
+ new int_comparable 4];;
+pr l;;
+pr (sort l);;
+let l = [new int_comparable2 2; new int_comparable2 0];;
+pr l;;
+pr (sort l);;
+
+let min (x : #comparable) y =
+ if x#cmp y <= 0 then x else y;;
+
+(min (new int_comparable 7) (new int_comparable 11))#x;;
+(min (new int_comparable2 5) (new int_comparable2 3))#x;;
+
+(*******************************************************************)
+
+class ['a] link (x : 'a) = object (self : 'b)
+ val mutable x = x
+ val mutable next = (None : 'b option)
+ method x = x
+ method next = next
+ method set_x y = x <- y
+ method set_next l = next <- l
+ method append l =
+ match next with
+ None ->
+ self#set_next l
+ | Some l' ->
+ l'#append l
+end;;
+
+class ['a] double_link x = object (self)
+ inherit ['a] link x
+ val mutable prev = None
+ method prev = prev
+ method set_next l =
+ next <- l;
+ match l with Some l -> l#set_prev (Some self) | None -> ()
+ method set_prev l = prev <- l
+end;;
+
+let rec fold_right f (l : 'a #link option) accu =
+ match l with
+ None -> accu
+ | Some l ->
+ f l#x (fold_right f l#next accu);;
+
+(*******************************************************************)
+
+class calculator () = object (self)
+ val mutable arg = 0.
+ val mutable acc = 0.
+ val mutable equals = function s -> s#arg
+ method arg = arg
+ method acc = acc
+ method enter n = arg <- n; self
+ method add =
+ acc <- equals self;
+ equals <- (function s -> s#acc +. s#arg);
+ self
+ method sub =
+ acc <- equals self;
+ equals <- (function s -> s#acc -. s#arg);
+ self
+ method equals = equals self
+end;;
+
+((new calculator ())#enter 5.)#equals;;
+(((new calculator ())#enter 5.)#sub#enter 3.5)#equals;;
+((new calculator ())#enter 5.)#add#add#equals;;
+
+class calculator () = object (self)
+ val mutable arg = 0.
+ val mutable acc = 0.
+ val mutable equals = function s -> s#arg
+ method arg = arg
+ method acc = acc
+ method enter n = arg <- n; self
+ method add = {< acc = equals self; equals = function s -> s#acc +. s#arg >}
+ method sub = {< acc = equals self; equals = function s -> s#acc -. s#arg >}
+ method equals = equals self
+end;;
+
+((new calculator ())#enter 5.)#equals;;
+(((new calculator ())#enter 5.)#sub#enter 3.5)#equals;;
+((new calculator ())#enter 5.)#add#add#equals;;
+
+class calculator arg acc = object (self)
+ val arg = arg
+ val acc = acc
+ method enter n = new calculator n acc
+ method add = new calculator_add arg self#equals
+ method sub = new calculator_sub arg self#equals
+ method equals = arg
+end and calculator_add arg acc = object
+ inherit calculator arg acc
+ method enter n = new calculator_add n acc
+ method equals = acc +. arg
+end and calculator_sub arg acc = object
+ inherit calculator arg acc
+ method enter n = new calculator_sub n acc
+ method equals = acc -. arg
+end;;
+
+let calculator = new calculator 0. 0.;;
+
+(calculator#enter 5.)#equals;;
+((calculator#enter 5.)#sub#enter 3.5)#equals;;
+(calculator#enter 5.)#add#add#equals;;
diff --git a/testsuite/tests/typing-objects/Exemples.ml.principal.reference b/testsuite/tests/typing-objects/Exemples.ml.principal.reference
new file mode 100644
index 0000000000..f0f3812ea3
--- /dev/null
+++ b/testsuite/tests/typing-objects/Exemples.ml.principal.reference
@@ -0,0 +1,358 @@
+
+# class point :
+ int ->
+ object val mutable x : int method get_x : int method move : int -> unit end
+# val p : point = <obj>
+# - : int = 7
+# - : unit = ()
+# - : int = 10
+# val q : < get_x : int; move : int -> unit > = <obj>
+# - : int * int = (10, 17)
+# class color_point :
+ int ->
+ string ->
+ object
+ val c : string
+ val mutable x : int
+ method color : string
+ method get_x : int
+ method move : int -> unit
+ end
+# val p' : color_point = <obj>
+# - : int * string = (5, "red")
+# val l : point list = [<obj>; <obj>]
+# val get_x : < get_x : 'a; .. > -> 'a = <fun>
+# val set_x : < set_x : 'a; .. > -> 'a = <fun>
+# - : int list = [10; 5]
+# Characters 1-96:
+ class ref x_init = object
+ val mutable x = x_init
+ method get = x
+ method set y = x <- y
+ end..
+Error: Some type variables are unbound in this type:
+ class ref :
+ 'a ->
+ object
+ val mutable x : 'a
+ method get : 'a
+ method set : 'a -> unit
+ end
+ The method get has type 'a where 'a is unbound
+# class ref :
+ int ->
+ object val mutable x : int method get : int method set : int -> unit end
+# class ['a] ref :
+ 'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end
+# - : int = 2
+# class ['a] circle :
+ 'a ->
+ object
+ constraint 'a = < move : int -> unit; .. >
+ val mutable center : 'a
+ method center : 'a
+ method move : int -> unit
+ method set_center : 'a -> unit
+ end
+# class ['a] circle :
+ 'a ->
+ object
+ constraint 'a = #point
+ val mutable center : 'a
+ method center : 'a
+ method move : int -> unit
+ method set_center : 'a -> unit
+ end
+# val c : point circle = <obj>
+val c' : < color : string; get_x : int; move : int -> unit > circle = <obj>
+# class ['a] color_circle :
+ 'a ->
+ object
+ constraint 'a = #color_point
+ val mutable center : 'a
+ method center : 'a
+ method color : string
+ method move : int -> unit
+ method set_center : 'a -> unit
+ end
+# Characters 28-29:
+ let c'' = new color_circle p;;
+ ^
+Error: This expression has type point but an expression was expected of type
+ #color_point
+ The first object type has no method color
+# val c'' : color_point color_circle = <obj>
+# - : color_point circle = <obj>
+# Characters 0-21:
+ (c'' :> point circle);; (* Echec *)
+ ^^^^^^^^^^^^^^^^^^^^^
+Error: Type
+ color_point color_circle =
+ < center : color_point; color : string; move : int -> unit;
+ set_center : color_point -> unit >
+ is not a subtype of
+ point circle =
+ < center : point; move : int -> unit; set_center : point -> unit >
+ Type point is not a subtype of color_point
+# Characters 9-55:
+ fun x -> (x : color_point color_circle :> point circle);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type
+ color_point color_circle =
+ < center : color_point; color : string; move : int -> unit;
+ set_center : color_point -> unit >
+ is not a subtype of
+ point circle =
+ < center : point; move : int -> unit; set_center : point -> unit >
+ Type point is not a subtype of color_point
+# class printable_point :
+ int ->
+ object
+ val mutable x : int
+ method get_x : int
+ method move : int -> unit
+ method print : unit
+ end
+# val p : printable_point = <obj>
+# 7- : unit = ()
+# Characters 85-102:
+ inherit printable_point y as super
+ ^^^^^^^^^^^^^^^^^
+Warning 13: the following instance variables are overridden by the class printable_point :
+ x
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+class printable_color_point :
+ int ->
+ string ->
+ object
+ val c : string
+ val mutable x : int
+ method color : string
+ method get_x : int
+ method move : int -> unit
+ method print : unit
+ end
+# val p' : printable_color_point = <obj>
+# (7, red)- : unit = ()
+# class functional_point :
+ int ->
+ object ('a) val x : int method get_x : int method move : int -> 'a end
+# val p : functional_point = <obj>
+# - : int = 7
+# - : int = 10
+# - : int = 7
+# - : #functional_point -> functional_point = <fun>
+# class virtual ['a] lst :
+ unit ->
+ object
+ method virtual hd : 'a
+ method iter : ('a -> unit) -> unit
+ method map : ('a -> 'a) -> 'a lst
+ method virtual null : bool
+ method print : ('a -> unit) -> unit
+ method virtual tl : 'a lst
+ end
+and ['a] nil :
+ unit ->
+ object
+ method hd : 'a
+ method iter : ('a -> unit) -> unit
+ method map : ('a -> 'a) -> 'a lst
+ method null : bool
+ method print : ('a -> unit) -> unit
+ method tl : 'a lst
+ end
+and ['a] cons :
+ 'a ->
+ 'a lst ->
+ object
+ val h : 'a
+ val t : 'a lst
+ method hd : 'a
+ method iter : ('a -> unit) -> unit
+ method map : ('a -> 'a) -> 'a lst
+ method null : bool
+ method print : ('a -> unit) -> unit
+ method tl : 'a lst
+ end
+# val l1 : int lst = <obj>
+# (3::10::[])- : unit = ()
+# val l2 : int lst = <obj>
+# (4::11::[])- : unit = ()
+# val map_list : ('a -> 'b) -> 'a lst -> 'b lst = <fun>
+# val p1 : printable_color_point lst = <obj>
+# ((3, red)::(10, red)::[])- : unit = ()
+# class virtual comparable :
+ unit -> object ('a) method virtual cmp : 'a -> int end
+# class int_comparable :
+ int -> object ('a) val x : int method cmp : 'a -> int method x : int end
+# class int_comparable2 :
+ int ->
+ object ('a)
+ val x : int
+ val mutable x' : int
+ method cmp : 'a -> int
+ method set_x : int -> unit
+ method x : int
+ end
+# class ['a] sorted_list :
+ unit ->
+ object
+ constraint 'a = #comparable
+ val mutable l : 'a list
+ method add : 'a -> unit
+ method hd : 'a
+ end
+# val l : _#comparable sorted_list = <obj>
+# val c : int_comparable = <obj>
+# - : unit = ()
+# val c2 : int_comparable2 = <obj>
+# Characters 6-28:
+ l#add (c2 :> int_comparable);; (* Echec : 'a comp2 n'est un sous-type *)
+ ^^^^^^^^^^^^^^^^^^^^^^
+Error: Type
+ int_comparable2 =
+ < cmp : int_comparable2 -> int; set_x : int -> unit; x : int >
+ is not a subtype of
+ int_comparable = < cmp : int_comparable -> int; x : int >
+ Type int_comparable = < cmp : int_comparable -> int; x : int >
+ is not a subtype of
+ int_comparable2 =
+ < cmp : int_comparable2 -> int; set_x : int -> unit; x : int >
+# - : unit = ()
+# class int_comparable3 :
+ int ->
+ object
+ val mutable x : int
+ method cmp : int_comparable -> int
+ method setx : int -> unit
+ method x : int
+ end
+# val c3 : int_comparable3 = <obj>
+# - : unit = ()
+# Characters 25-27:
+ (new sorted_list ())#add c3;; (* Error; strange message with -principal *)
+ ^^
+Error: This expression has type
+ int_comparable3 =
+ < cmp : int_comparable -> int; setx : int -> unit; x : int >
+ but an expression was expected of type
+ #comparable as 'a = < cmp : 'a -> int; .. >
+ Type int_comparable = < cmp : int_comparable -> int; x : int >
+ is not compatible with type 'a = < cmp : 'a -> int; .. >
+ The first object type has no method setx
+# val sort : (#comparable as 'a) list -> 'a list = <fun>
+# Characters 13-66:
+ List.map (fun c -> print_int c#x; print_string " ") l;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 10: this expression should have type unit.
+val pr : < x : int; .. > list -> unit = <fun>
+# val l : int_comparable list = [<obj>; <obj>; <obj>]
+# 5 2 4
+- : unit = ()
+# 2 4 5
+- : unit = ()
+# val l : int_comparable2 list = [<obj>; <obj>]
+# 2 0
+- : unit = ()
+# 0 2
+- : unit = ()
+# val min : (#comparable as 'a) -> 'a -> 'a = <fun>
+# - : int = 7
+# - : int = 3
+# class ['a] link :
+ 'a ->
+ object ('b)
+ val mutable next : 'b option
+ val mutable x : 'a
+ method append : 'b option -> unit
+ method next : 'b option
+ method set_next : 'b option -> unit
+ method set_x : 'a -> unit
+ method x : 'a
+ end
+# class ['a] double_link :
+ 'a ->
+ object ('b)
+ val mutable next : 'b option
+ val mutable prev : 'b option
+ val mutable x : 'a
+ method append : 'b option -> unit
+ method next : 'b option
+ method prev : 'b option
+ method set_next : 'b option -> unit
+ method set_prev : 'b option -> unit
+ method set_x : 'a -> unit
+ method x : 'a
+ end
+# val fold_right : ('a -> 'b -> 'b) -> 'a #link option -> 'b -> 'b = <fun>
+# class calculator :
+ unit ->
+ object ('a)
+ val mutable acc : float
+ val mutable arg : float
+ val mutable equals : 'a -> float
+ method acc : float
+ method add : 'a
+ method arg : float
+ method enter : float -> 'a
+ method equals : float
+ method sub : 'a
+ end
+# - : float = 5.
+# - : float = 1.5
+# - : float = 15.
+# class calculator :
+ unit ->
+ object ('a)
+ val mutable acc : float
+ val mutable arg : float
+ val mutable equals : 'a -> float
+ method acc : float
+ method add : 'a
+ method arg : float
+ method enter : float -> 'a
+ method equals : float
+ method sub : 'a
+ end
+# - : float = 5.
+# - : float = 1.5
+# - : float = 15.
+# class calculator :
+ float ->
+ float ->
+ object
+ val acc : float
+ val arg : float
+ method add : calculator
+ method enter : float -> calculator
+ method equals : float
+ method sub : calculator
+ end
+and calculator_add :
+ float ->
+ float ->
+ object
+ val acc : float
+ val arg : float
+ method add : calculator
+ method enter : float -> calculator
+ method equals : float
+ method sub : calculator
+ end
+and calculator_sub :
+ float ->
+ float ->
+ object
+ val acc : float
+ val arg : float
+ method add : calculator
+ method enter : float -> calculator
+ method equals : float
+ method sub : calculator
+ end
+# val calculator : calculator = <obj>
+# - : float = 5.
+# - : float = 1.5
+# - : float = 15.
+#
diff --git a/testsuite/tests/typing-objects/Exemples.ml.reference b/testsuite/tests/typing-objects/Exemples.ml.reference
new file mode 100644
index 0000000000..085a9e92ec
--- /dev/null
+++ b/testsuite/tests/typing-objects/Exemples.ml.reference
@@ -0,0 +1,360 @@
+
+# class point :
+ int ->
+ object val mutable x : int method get_x : int method move : int -> unit end
+# val p : point = <obj>
+# - : int = 7
+# - : unit = ()
+# - : int = 10
+# val q : point = <obj>
+# - : int * int = (10, 17)
+# class color_point :
+ int ->
+ string ->
+ object
+ val c : string
+ val mutable x : int
+ method color : string
+ method get_x : int
+ method move : int -> unit
+ end
+# val p' : color_point = <obj>
+# - : int * string = (5, "red")
+# val l : point list = [<obj>; <obj>]
+# val get_x : < get_x : 'a; .. > -> 'a = <fun>
+# val set_x : < set_x : 'a; .. > -> 'a = <fun>
+# - : int list = [10; 5]
+# Characters 1-96:
+ class ref x_init = object
+ val mutable x = x_init
+ method get = x
+ method set y = x <- y
+ end..
+Error: Some type variables are unbound in this type:
+ class ref :
+ 'a ->
+ object
+ val mutable x : 'a
+ method get : 'a
+ method set : 'a -> unit
+ end
+ The method get has type 'a where 'a is unbound
+# class ref :
+ int ->
+ object val mutable x : int method get : int method set : int -> unit end
+# class ['a] ref :
+ 'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end
+# - : int = 2
+# class ['a] circle :
+ 'a ->
+ object
+ constraint 'a = < move : int -> unit; .. >
+ val mutable center : 'a
+ method center : 'a
+ method move : int -> unit
+ method set_center : 'a -> unit
+ end
+# class ['a] circle :
+ 'a ->
+ object
+ constraint 'a = #point
+ val mutable center : 'a
+ method center : 'a
+ method move : int -> unit
+ method set_center : 'a -> unit
+ end
+# val c : point circle = <obj>
+val c' : color_point circle = <obj>
+# class ['a] color_circle :
+ 'a ->
+ object
+ constraint 'a = #color_point
+ val mutable center : 'a
+ method center : 'a
+ method color : string
+ method move : int -> unit
+ method set_center : 'a -> unit
+ end
+# Characters 28-29:
+ let c'' = new color_circle p;;
+ ^
+Error: This expression has type point but an expression was expected of type
+ #color_point
+ The first object type has no method color
+# val c'' : color_point color_circle = <obj>
+# - : color_point circle = <obj>
+# Characters 0-21:
+ (c'' :> point circle);; (* Echec *)
+ ^^^^^^^^^^^^^^^^^^^^^
+Error: Type
+ color_point color_circle =
+ < center : color_point; color : string; move : int -> unit;
+ set_center : color_point -> unit >
+ is not a subtype of
+ point circle =
+ < center : point; move : int -> unit; set_center : point -> unit >
+ Type point is not a subtype of color_point
+# Characters 9-55:
+ fun x -> (x : color_point color_circle :> point circle);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type
+ color_point color_circle =
+ < center : color_point; color : string; move : int -> unit;
+ set_center : color_point -> unit >
+ is not a subtype of
+ point circle =
+ < center : point; move : int -> unit; set_center : point -> unit >
+ Type point is not a subtype of color_point
+# class printable_point :
+ int ->
+ object
+ val mutable x : int
+ method get_x : int
+ method move : int -> unit
+ method print : unit
+ end
+# val p : printable_point = <obj>
+# 7- : unit = ()
+# Characters 85-102:
+ inherit printable_point y as super
+ ^^^^^^^^^^^^^^^^^
+Warning 13: the following instance variables are overridden by the class printable_point :
+ x
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+class printable_color_point :
+ int ->
+ string ->
+ object
+ val c : string
+ val mutable x : int
+ method color : string
+ method get_x : int
+ method move : int -> unit
+ method print : unit
+ end
+# val p' : printable_color_point = <obj>
+# (7, red)- : unit = ()
+# class functional_point :
+ int ->
+ object ('a) val x : int method get_x : int method move : int -> 'a end
+# val p : functional_point = <obj>
+# - : int = 7
+# - : int = 10
+# - : int = 7
+# - : #functional_point -> functional_point = <fun>
+# class virtual ['a] lst :
+ unit ->
+ object
+ method virtual hd : 'a
+ method iter : ('a -> unit) -> unit
+ method map : ('a -> 'a) -> 'a lst
+ method virtual null : bool
+ method print : ('a -> unit) -> unit
+ method virtual tl : 'a lst
+ end
+and ['a] nil :
+ unit ->
+ object
+ method hd : 'a
+ method iter : ('a -> unit) -> unit
+ method map : ('a -> 'a) -> 'a lst
+ method null : bool
+ method print : ('a -> unit) -> unit
+ method tl : 'a lst
+ end
+and ['a] cons :
+ 'a ->
+ 'a lst ->
+ object
+ val h : 'a
+ val t : 'a lst
+ method hd : 'a
+ method iter : ('a -> unit) -> unit
+ method map : ('a -> 'a) -> 'a lst
+ method null : bool
+ method print : ('a -> unit) -> unit
+ method tl : 'a lst
+ end
+# val l1 : int lst = <obj>
+# (3::10::[])- : unit = ()
+# val l2 : int lst = <obj>
+# (4::11::[])- : unit = ()
+# val map_list : ('a -> 'b) -> 'a lst -> 'b lst = <fun>
+# val p1 : printable_color_point lst = <obj>
+# ((3, red)::(10, red)::[])- : unit = ()
+# class virtual comparable :
+ unit -> object ('a) method virtual cmp : 'a -> int end
+# class int_comparable :
+ int -> object ('a) val x : int method cmp : 'a -> int method x : int end
+# class int_comparable2 :
+ int ->
+ object ('a)
+ val x : int
+ val mutable x' : int
+ method cmp : 'a -> int
+ method set_x : int -> unit
+ method x : int
+ end
+# class ['a] sorted_list :
+ unit ->
+ object
+ constraint 'a = #comparable
+ val mutable l : 'a list
+ method add : 'a -> unit
+ method hd : 'a
+ end
+# val l : _#comparable sorted_list = <obj>
+# val c : int_comparable = <obj>
+# - : unit = ()
+# val c2 : int_comparable2 = <obj>
+# Characters 6-28:
+ l#add (c2 :> int_comparable);; (* Echec : 'a comp2 n'est un sous-type *)
+ ^^^^^^^^^^^^^^^^^^^^^^
+Error: Type
+ int_comparable2 =
+ < cmp : int_comparable2 -> int; set_x : int -> unit; x : int >
+ is not a subtype of
+ int_comparable = < cmp : int_comparable -> int; x : int >
+ Type int_comparable = < cmp : int_comparable -> int; x : int >
+ is not a subtype of
+ int_comparable2 =
+ < cmp : int_comparable2 -> int; set_x : int -> unit; x : int >
+# - : unit = ()
+# class int_comparable3 :
+ int ->
+ object
+ val mutable x : int
+ method cmp : int_comparable -> int
+ method setx : int -> unit
+ method x : int
+ end
+# val c3 : int_comparable3 = <obj>
+# - : unit = ()
+# Characters 25-27:
+ (new sorted_list ())#add c3;; (* Error; strange message with -principal *)
+ ^^
+Error: This expression has type
+ int_comparable3 =
+ < cmp : int_comparable -> int; setx : int -> unit; x : int >
+ but an expression was expected of type
+ #comparable as 'a = < cmp : 'a -> int; .. >
+ Type int_comparable = < cmp : int_comparable -> int; x : int >
+ is not compatible with type
+ int_comparable3 =
+ < cmp : int_comparable -> int; setx : int -> unit; x : int >
+ The first object type has no method setx
+# val sort : (#comparable as 'a) list -> 'a list = <fun>
+# Characters 13-66:
+ List.map (fun c -> print_int c#x; print_string " ") l;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 10: this expression should have type unit.
+val pr : < x : int; .. > list -> unit = <fun>
+# val l : int_comparable list = [<obj>; <obj>; <obj>]
+# 5 2 4
+- : unit = ()
+# 2 4 5
+- : unit = ()
+# val l : int_comparable2 list = [<obj>; <obj>]
+# 2 0
+- : unit = ()
+# 0 2
+- : unit = ()
+# val min : (#comparable as 'a) -> 'a -> 'a = <fun>
+# - : int = 7
+# - : int = 3
+# class ['a] link :
+ 'a ->
+ object ('b)
+ val mutable next : 'b option
+ val mutable x : 'a
+ method append : 'b option -> unit
+ method next : 'b option
+ method set_next : 'b option -> unit
+ method set_x : 'a -> unit
+ method x : 'a
+ end
+# class ['a] double_link :
+ 'a ->
+ object ('b)
+ val mutable next : 'b option
+ val mutable prev : 'b option
+ val mutable x : 'a
+ method append : 'b option -> unit
+ method next : 'b option
+ method prev : 'b option
+ method set_next : 'b option -> unit
+ method set_prev : 'b option -> unit
+ method set_x : 'a -> unit
+ method x : 'a
+ end
+# val fold_right : ('a -> 'b -> 'b) -> 'a #link option -> 'b -> 'b = <fun>
+# class calculator :
+ unit ->
+ object ('a)
+ val mutable acc : float
+ val mutable arg : float
+ val mutable equals : 'a -> float
+ method acc : float
+ method add : 'a
+ method arg : float
+ method enter : float -> 'a
+ method equals : float
+ method sub : 'a
+ end
+# - : float = 5.
+# - : float = 1.5
+# - : float = 15.
+# class calculator :
+ unit ->
+ object ('a)
+ val mutable acc : float
+ val mutable arg : float
+ val mutable equals : 'a -> float
+ method acc : float
+ method add : 'a
+ method arg : float
+ method enter : float -> 'a
+ method equals : float
+ method sub : 'a
+ end
+# - : float = 5.
+# - : float = 1.5
+# - : float = 15.
+# class calculator :
+ float ->
+ float ->
+ object
+ val acc : float
+ val arg : float
+ method add : calculator
+ method enter : float -> calculator
+ method equals : float
+ method sub : calculator
+ end
+and calculator_add :
+ float ->
+ float ->
+ object
+ val acc : float
+ val arg : float
+ method add : calculator
+ method enter : float -> calculator
+ method equals : float
+ method sub : calculator
+ end
+and calculator_sub :
+ float ->
+ float ->
+ object
+ val acc : float
+ val arg : float
+ method add : calculator
+ method enter : float -> calculator
+ method equals : float
+ method sub : calculator
+ end
+# val calculator : calculator = <obj>
+# - : float = 5.
+# - : float = 1.5
+# - : float = 15.
+#
diff --git a/testsuite/tests/typing-objects/Makefile b/testsuite/tests/typing-objects/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-objects/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-objects/Tests.ml b/testsuite/tests/typing-objects/Tests.ml
new file mode 100644
index 0000000000..917474f961
--- /dev/null
+++ b/testsuite/tests/typing-objects/Tests.ml
@@ -0,0 +1,336 @@
+(* Le sous-typage est "syntaxique" *)
+fun (x : < x : int >) y z -> (y :> 'a), (x :> 'a), (z :> 'a);;
+(* - : (< x : int > as 'a) -> 'a -> 'a * 'a = <fun> *)
+
+(* Bizarrerie du typage des classes *)
+class ['a] c () = object
+ method f = (new c (): int c)
+end and ['a] d () = object
+ inherit ['a] c ()
+end;;
+(* class ['a] c : unit -> object constraint 'a = int method f : 'a c end *)
+(* and ['a] d : unit -> object constraint 'a = int method f : 'a c end *)
+
+(* 'a libre dans classe d *)
+class ['a] c () = object
+ method f (x : 'a) = ()
+end and d () = object
+ inherit ['a] c ()
+end;;
+
+(* Instancie #c *)
+class virtual c () = object
+end and ['a] d () = object
+ constraint 'a = #c
+ method f (x : #c) = (x#x : int)
+end;;
+(* class virtual c : unit -> object end *)
+(* and ['a] d : *)
+(* unit -> object constraint 'a = < x : int; .. > method f : 'a -> int end *)
+
+class ['a] c () = object
+ constraint 'a = int
+end and ['a] d () = object
+ constraint 'a = 'b #c
+end;;
+(* class ['a] c : unit -> object constraint 'a = int end
+ and ['a] d : unit -> object constraint 'a = int #c end *)
+
+(* Self en parametre *)
+class ['a] c (x : 'a) = object (self : 'b)
+ constraint 'a = 'b
+ method f = self
+end;;
+new c;;
+(* class ['a] c :
+ 'a -> object ('a) constraint 'a = < f : 'a; .. > method f : 'a end *)
+(* - : ('a c as 'a) -> 'a = <fun> *)
+
+class x () = object
+ method virtual f : int
+end;;
+(* The class x should be virtual: its methods f is undefined *)
+
+(* Methode g en trop *)
+class virtual c ((x : 'a): < f : int >) = object (_ : 'a) end
+and virtual d x = object (_ : 'a)
+ inherit c x
+ method g = true
+end;;
+
+(* Contrainte non respectee *)
+class ['a] c () = object
+ constraint 'a = int
+ method f x = (x : bool c)
+end;;
+
+(* Differentes contraintes *)
+class ['a, 'b] c () = object
+ constraint 'a = int -> 'c
+ constraint 'b = 'a * <x : 'b> * 'c * 'd
+ method f (x : 'a) (y : 'b) = ()
+end;;
+class ['a, 'b] d () = object
+ inherit ['a, 'b] c ()
+end;;
+
+(* Contrainte non generique *)
+let x = ref [];;
+class ['a] c () = object
+ method f = (x : 'a)
+end;;
+
+(* Abreviations *)
+type 'a c = <f : 'a c; g : 'a d>
+and 'a d = <f : int c>;;
+type 'a c = <f : 'a c; g : 'a d>
+and 'a d = <f : 'a c>;;
+type 'a c = <f : 'a c>
+and 'a d = <f : int c>;;
+type 'a u = < x : 'a>
+and 'a t = 'a t u;;
+type 'a u = 'a
+and 'a t = 'a t u;;
+type 'a u = 'a;;
+type t = t u * t u;;
+
+type t = <x : 'a> as 'a;;
+type 'a u = 'a;;
+fun (x : t) (y : 'a u) -> x = y;;
+fun (x : t) (y : 'a u) -> y = x;;
+(* - : t -> t u -> bool = <fun> *)
+
+(* Modules *)
+module M =
+ struct
+ class ['a, 'b] c (x: int) (y: 'b) = object
+ constraint 'a = int -> bool
+ val x : float list = []
+ val y = y
+ method f (x : 'a) = ()
+ method g = y
+ end
+ end;;
+module M' = (M :
+ sig
+ class virtual ['a, 'b] c : int -> 'b -> object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+ end);;
+class ['a, 'b] d () y = object inherit ['a, 'b] M.c 7 y end;;
+class ['a, 'b] e () y = object inherit ['a, 'b] M'.c 1 y end;;
+(new M.c 3 "a")#g;;
+(new d () 10)#g;;
+(new e () 7.1)#g;;
+open M;;
+(new c 5 true)#g;;
+
+(* #cl quand cl est fermee *)
+module M = struct class ['a] c () = object method f (x : 'a) = () end end;;
+module M' =
+ (M : sig class ['a] c : unit -> object method f : 'a -> unit end end);;
+fun x -> (x :> 'a #M.c);;
+fun x -> (x :> 'a #M'.c);;
+class ['a] c (x : 'b #c) = object end;;
+class ['a] c (x : 'b #c) = object end;;
+
+(* Ordre de calcul *)
+class c () = object method f = 1 end and d () = object method f = 2 end;;
+class e () = object inherit c () inherit d () end;;
+(new e ())#f;;
+class c () = object val x = - true val y = -. () end;;
+
+class c () = object method f = 1 method g = 1 method h = 1 end;;
+class d () = object method h = 2 method i = 2 method j = 2 end;;
+class e () = object
+ method f = 3
+ inherit c ()
+ method g = 3
+ method i = 3
+ inherit d ()
+ method j = 3
+end;;
+let e = new e ();;
+e#f, e#g, e#h, e#i, e#j;;
+
+class c a = object val x = 1 val y = 1 val z = 1 val a = a end;;
+class d b = object val z = 2 val t = 2 val u = 2 val b = b end;;
+class e () = object
+ val x = 3
+ inherit c 5
+ val y = 3
+ val t = 3
+ inherit d 7
+ val u = 3
+ method x = x
+ method y = y
+ method z = z
+ method t = t
+ method u = u
+ method a = a
+ method b = b
+end;;
+let e = new e ();;
+e#x, e#y, e#z, e#t, e#u, e#a, e#b;;
+
+class c (x : int) (y : int) = object
+ val x = x
+ val y = y
+ method x = x
+ method y = y
+end;;
+class d x y = object inherit c x y end;;
+let c = new c 1 2 in c#x, c#y;;
+let d = new d 1 2 in d#x, d#y;;
+
+(* Parametres n'apparaissant pas dans le type de l'objet *)
+class ['a] c (x : 'a) = object end;;
+new c;;
+
+(* Variables privees *)
+(*
+module type M = sig
+ class c : unit -> object val x : int end
+ class d : unit -> object inherit c val private x : int val x : bool end
+end;;
+class c (x : int) =
+ val private mutable x = x
+ method get = x
+ method set y = x <- y
+end;;
+let c = new c 5;;
+c#get;;
+c#set 7; c#get;;
+
+
+class c () = val x = 1 val y = 1 method c = x end;;
+class d () = inherit c () val private x method d = x end;;
+class e () =
+ val x = 2 val y = 2 inherit d () method x = x method y = y
+end;;
+let e = new e () in e#x, e#y, e#c, e#d;;
+*)
+
+(* Oubli de variables dans l'interface *)
+module M :
+ sig
+ class c : unit -> object
+ method xc : int
+ end
+ end =
+ struct
+ class c () = object
+ val x = 1
+ method xc = x
+ end
+ end;;
+class d () = object
+ val x = 2
+ method xd = x
+ inherit M.c ()
+end;;
+let d = new d () in d#xc, d#xd;;
+
+class virtual ['a] matrix (sz, init : int * 'a) = object
+ val m = Array.make_matrix sz sz init
+ method add (mtx : 'a matrix) = (mtx#m.(0).(0) : 'a)
+end;;
+
+class c () = object method m = new c () end;;
+(new c ())#m;;
+module M = struct class c () = object method m = new c () end end;;
+(new M.c ())#m;;
+
+type uu = A of int | B of (<leq: 'a> as 'a);;
+
+class virtual c () = object (_ : 'a) method virtual m : 'a end;;
+module S = (struct
+ let f (x : #c) = x
+end : sig
+ val f : (#c as 'a) -> 'a
+end);;
+module S = (struct
+ let f (x : #c) = x
+end : sig
+ val f : #c -> #c
+end);;
+
+module M = struct type t = int class t () = object end end;;
+
+fun x -> (x :> < m : 'a -> 'a > as 'a);;
+
+fun x -> (x : int -> bool :> 'a -> 'a);;
+fun x -> (x : int -> bool :> int -> int);;
+fun x -> (x : < > :> < .. >);;
+fun x -> (x : < .. > :> < >);;
+
+let x = ref [];;
+module F(X : sig end) =
+ struct type t = int let _ = (x : < m : t> list ref) end;;
+x;;
+
+type 'a t;;
+fun (x : 'a t as 'a) -> ();;
+fun (x : 'a t) -> (x : 'a); ();;
+type 'a t = < x : 'a >;;
+fun (x : 'a t as 'a) -> ();;
+fun (x : 'a t) -> (x : 'a); ();;
+
+class ['a] c () = object
+ constraint 'a = < .. > -> unit
+ method m = (fun x -> () : 'a)
+end;;
+class ['a] c () = object
+ constraint 'a = unit -> < .. >
+ method m (f : 'a) = f ()
+end;;
+
+class c () = object (self)
+ method private m = 1
+ method n = self#m
+end;;
+
+class d () = object (self)
+ inherit c ()
+ method o = self#m
+end;;
+
+let x = new d () in x#n, x#o;;
+
+class c () = object method virtual m : int method private m = 1 end;;
+
+(* Marshaling (cf. PR#5436) *)
+
+let r = ref 0;;
+let id o = Oo.id o - !r;;
+r := Oo.id (object end);;
+id (object end);;
+id (object end);;
+let o = object end in
+ let s = Marshal.to_string o [] in
+ let o' : < > = Marshal.from_string s 0 in
+ let o'' : < > = Marshal.from_string s 0 in
+ (id o, id o', id o'');;
+
+let o = object val x = 33 method m = x end in
+ let s = Marshal.to_string o [Marshal.Closures] in
+ let o' : <m:int> = Marshal.from_string s 0 in
+ let o'' : <m:int> = Marshal.from_string s 0 in
+ (id o, id o', id o'', o#m, o'#m);;
+
+let o = object val x = 33 val y = 44 method m = x end in
+ let s = Marshal.to_string (o,o) [Marshal.Closures] in
+ let (o1, o2) : (<m:int> * <m:int>) = Marshal.from_string s 0 in
+ let (o3, o4) : (<m:int> * <m:int>) = Marshal.from_string s 0 in
+ (id o, id o1, id o2, id o3, id o4, o#m, o1#m);;
+
+(* Recursion (cf. PR#5291) *)
+
+class a = let _ = new b in object end
+and b = let _ = new a in object end;;
+
+class a = let _ = new a in object end;;
diff --git a/testsuite/tests/typing-objects/Tests.ml.principal.reference b/testsuite/tests/typing-objects/Tests.ml.principal.reference
new file mode 100644
index 0000000000..6c9449441e
--- /dev/null
+++ b/testsuite/tests/typing-objects/Tests.ml.principal.reference
@@ -0,0 +1,314 @@
+
+# - : < x : int > ->
+ < x : int > -> < x : int > -> < x : int > * < x : int > * < x : int >
+= <fun>
+# class ['a] c : unit -> object constraint 'a = int method f : int c end
+and ['a] d : unit -> object constraint 'a = int method f : int c end
+# Characters 234-275:
+ ....and d () = object
+ inherit ['a] c ()
+ end..
+Error: Some type variables are unbound in this type:
+ class d : unit -> object method f : 'a -> unit end
+ The method f has type 'a -> unit where 'a is unbound
+# class virtual c : unit -> object end
+and ['a] d :
+ unit -> object constraint 'a = < x : int; .. > method f : 'a -> int end
+# class ['a] c : unit -> object constraint 'a = int end
+and ['a] d : unit -> object constraint 'a = int #c end
+# * class ['a] c :
+ 'a -> object ('a) constraint 'a = < f : 'a; .. > method f : 'a end
+# - : ('a c as 'a) -> 'a = <fun>
+# * Characters 128-176:
+ class x () = object
+ method virtual f : int
+ end..
+Error: This class should be virtual. The following methods are undefined : f
+# Characters 139-147:
+ class virtual c ((x : 'a): < f : int >) = object (_ : 'a) end
+ ^^^^^^^^
+Error: This pattern cannot match self: it only matches values of type
+ < f : int >
+# Characters 32-110:
+ class ['a] c () = object
+ constraint 'a = int
+ method f x = (x : bool c)
+ end..
+Error: The abbreviation c is used with parameters bool c
+ wich are incompatible with constraints int c
+# class ['a, 'b] c :
+ unit ->
+ object
+ constraint 'a = int -> 'c
+ constraint 'b = 'a * < x : 'b > * 'c * 'd
+ method f : 'a -> 'b -> unit
+ end
+# class ['a, 'b] d :
+ unit ->
+ object
+ constraint 'a = int -> 'c
+ constraint 'b = 'a * < x : 'b > * 'c * 'd
+ method f : 'a -> 'b -> unit
+ end
+# val x : '_a list ref = {contents = []}
+# Characters 0-50:
+ class ['a] c () = object
+ method f = (x : 'a)
+ end..
+Error: The type of this class,
+ class ['a] c :
+ unit -> object constraint 'a = '_b list ref method f : 'a end,
+ contains type variables that cannot be generalized
+# Characters 20-52:
+ type 'a c = <f : 'a c; g : 'a d>
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In the definition of d, type int c should be 'a c
+# type 'a c = < f : 'a c; g : 'a d >
+and 'a d = < f : 'a c >
+# type 'a c = < f : 'a c >
+and 'a d = < f : int c >
+# type 'a u = < x : 'a >
+and 'a t = 'a t u
+# Characters 15-32:
+ and 'a t = 'a t u;;
+ ^^^^^^^^^^^^^^^^^
+Error: The type abbreviation t is cyclic
+# type 'a u = 'a
+# Characters 0-18:
+ type t = t u * t u;;
+ ^^^^^^^^^^^^^^^^^^
+Error: The type abbreviation t is cyclic
+# type t = < x : 'a > as 'a
+# type 'a u = 'a
+# - : t -> t u -> bool = <fun>
+# - : t -> t u -> bool = <fun>
+# module M :
+ sig
+ class ['a, 'b] c :
+ int ->
+ 'b ->
+ object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+ end
+# module M' :
+ sig
+ class virtual ['a, 'b] c :
+ int ->
+ 'b ->
+ object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+ end
+# class ['a, 'b] d :
+ unit ->
+ 'b ->
+ object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+# class ['a, 'b] e :
+ unit ->
+ 'b ->
+ object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+# - : string = "a"
+# - : int = 10
+# - : float = 7.1
+# # - : bool = true
+# module M : sig class ['a] c : unit -> object method f : 'a -> unit end end
+# module M' : sig class ['a] c : unit -> object method f : 'a -> unit end end
+# - : ('a #M.c as 'b) -> 'b = <fun>
+# - : ('a #M'.c as 'b) -> 'b = <fun>
+# class ['a] c : 'a #c -> object end
+# class ['a] c : 'a #c -> object end
+# class c : unit -> object method f : int end
+and d : unit -> object method f : int end
+# class e : unit -> object method f : int end
+# - : int = 2
+# Characters 30-34:
+ class c () = object val x = - true val y = -. () end;;
+ ^^^^
+Error: This expression has type bool but an expression was expected of type
+ int
+# class c : unit -> object method f : int method g : int method h : int end
+# class d : unit -> object method h : int method i : int method j : int end
+# class e :
+ unit ->
+ object
+ method f : int
+ method g : int
+ method h : int
+ method i : int
+ method j : int
+ end
+# val e : e = <obj>
+# - : int * int * int * int * int = (1, 3, 2, 2, 3)
+# class c : 'a -> object val a : 'a val x : int val y : int val z : int end
+# class d : 'a -> object val b : 'a val t : int val u : int val z : int end
+# Characters 42-45:
+ inherit c 5
+ ^^^
+Warning 13: the following instance variables are overridden by the class c :
+ x
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+Characters 52-53:
+ val y = 3
+ ^
+Warning 13: the instance variable y is overridden.
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+Characters 80-83:
+ inherit d 7
+ ^^^
+Warning 13: the following instance variables are overridden by the class d :
+ t z
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+Characters 90-91:
+ val u = 3
+ ^
+Warning 13: the instance variable u is overridden.
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+class e :
+ unit ->
+ object
+ val a : int
+ val b : int
+ val t : int
+ val u : int
+ val x : int
+ val y : int
+ val z : int
+ method a : int
+ method b : int
+ method t : int
+ method u : int
+ method x : int
+ method y : int
+ method z : int
+ end
+# val e : e = <obj>
+# - : int * int * int * int * int * int * int = (1, 3, 2, 2, 3, 5, 7)
+# class c :
+ int ->
+ int -> object val x : int val y : int method x : int method y : int end
+# class d :
+ int ->
+ int -> object val x : int val y : int method x : int method y : int end
+# - : int * int = (1, 2)
+# - : int * int = (1, 2)
+# class ['a] c : 'a -> object end
+# - : 'a -> 'a c = <fun>
+# * * * * * * * * * * * * * * * * * * * * * module M : sig class c : unit -> object method xc : int end end
+# class d : unit -> object val x : int method xc : int method xd : int end
+# - : int * int = (1, 2)
+# Characters 1-154:
+ class virtual ['a] matrix (sz, init : int * 'a) = object
+ val m = Array.make_matrix sz sz init
+ method add (mtx : 'a matrix) = (mtx#m.(0).(0) : 'a)
+ end..
+Error: The abbreviation 'a matrix expands to type < add : 'a matrix -> 'a >
+ but is used with type < m : 'a array array; .. >
+# class c : unit -> object method m : c end
+# - : c = <obj>
+# module M : sig class c : unit -> object method m : c end end
+# - : M.c = <obj>
+# type uu = A of int | B of (< leq : 'a > as 'a)
+# class virtual c : unit -> object ('a) method virtual m : 'a end
+# module S : sig val f : (#c as 'a) -> 'a end
+# Characters 12-43:
+ ............struct
+ let f (x : #c) = x
+ end......
+Error: Signature mismatch:
+ Modules do not match:
+ sig val f : (#c as 'a) -> 'a end
+ is not included in
+ sig val f : #c -> #c end
+ Values do not match:
+ val f : (#c as 'a) -> 'a
+ is not included in
+ val f : #c -> #c
+# Characters 38-39:
+ module M = struct type t = int class t () = object end end;;
+ ^
+Error: Multiple definition of the type name t.
+ Names must be unique in a given structure or signature.
+# - : < m : (< m : 'a > as 'b) -> 'b as 'a; .. > -> 'b = <fun>
+# Characters 10-39:
+ fun x -> (x : int -> bool :> 'a -> 'a);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type int -> bool is not a subtype of int -> int
+ Type bool is not a subtype of int
+# Characters 9-40:
+ fun x -> (x : int -> bool :> int -> int);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type int -> bool is not a subtype of int -> int
+ Type bool is not a subtype of int
+# - : < > -> < > = <fun>
+# - : < .. > -> < > = <fun>
+# val x : '_a list ref = {contents = []}
+# module F : functor (X : sig end) -> sig type t = int end
+# - : < m : int > list ref = {contents = []}
+# type 'a t
+# Characters 9-19:
+ fun (x : 'a t as 'a) -> ();;
+ ^^^^^^^^^^
+Error: This alias is bound to type 'a t but is used as an instance of type 'a
+ The type variable 'a occurs inside 'a t
+# Characters 19-20:
+ fun (x : 'a t) -> (x : 'a); ();;
+ ^
+Error: This expression has type 'a t but an expression was expected of type
+ 'a
+ The type variable 'a occurs inside 'a t
+# type 'a t = < x : 'a >
+# - : ('a t as 'a) -> unit = <fun>
+# Characters 18-26:
+ fun (x : 'a t) -> (x : 'a); ();;
+ ^^^^^^^^
+Warning 10: this expression should have type unit.
+- : ('a t as 'a) t -> unit = <fun>
+# class ['a] c :
+ unit ->
+ object constraint 'a = (< .. > as 'b) -> unit method m : 'b -> unit end
+# class ['a] c :
+ unit ->
+ object constraint 'a = unit -> (< .. > as 'b) method m : 'a -> 'b end
+# class c : unit -> object method private m : int method n : int end
+# class d :
+ unit -> object method private m : int method n : int method o : int end
+# - : int * int = (1, 1)
+# class c : unit -> object method m : int end
+# val r : int ref = {contents = 0}
+# val id : < .. > -> int = <fun>
+# - : unit = ()
+# - : int = 1
+# - : int = 2
+# - : int * int * int = (3, 4, 5)
+# - : int * int * int * int * int = (6, 7, 8, 33, 33)
+# - : int * int * int * int * int * int * int = (9, 10, 10, 11, 11, 33, 33)
+# Characters 42-69:
+ class a = let _ = new b in object end
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This kind of recursive class expression is not allowed
+# Characters 11-38:
+ class a = let _ = new a in object end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This kind of recursive class expression is not allowed
+#
diff --git a/testsuite/tests/typing-objects/Tests.ml.reference b/testsuite/tests/typing-objects/Tests.ml.reference
new file mode 100644
index 0000000000..6c9449441e
--- /dev/null
+++ b/testsuite/tests/typing-objects/Tests.ml.reference
@@ -0,0 +1,314 @@
+
+# - : < x : int > ->
+ < x : int > -> < x : int > -> < x : int > * < x : int > * < x : int >
+= <fun>
+# class ['a] c : unit -> object constraint 'a = int method f : int c end
+and ['a] d : unit -> object constraint 'a = int method f : int c end
+# Characters 234-275:
+ ....and d () = object
+ inherit ['a] c ()
+ end..
+Error: Some type variables are unbound in this type:
+ class d : unit -> object method f : 'a -> unit end
+ The method f has type 'a -> unit where 'a is unbound
+# class virtual c : unit -> object end
+and ['a] d :
+ unit -> object constraint 'a = < x : int; .. > method f : 'a -> int end
+# class ['a] c : unit -> object constraint 'a = int end
+and ['a] d : unit -> object constraint 'a = int #c end
+# * class ['a] c :
+ 'a -> object ('a) constraint 'a = < f : 'a; .. > method f : 'a end
+# - : ('a c as 'a) -> 'a = <fun>
+# * Characters 128-176:
+ class x () = object
+ method virtual f : int
+ end..
+Error: This class should be virtual. The following methods are undefined : f
+# Characters 139-147:
+ class virtual c ((x : 'a): < f : int >) = object (_ : 'a) end
+ ^^^^^^^^
+Error: This pattern cannot match self: it only matches values of type
+ < f : int >
+# Characters 32-110:
+ class ['a] c () = object
+ constraint 'a = int
+ method f x = (x : bool c)
+ end..
+Error: The abbreviation c is used with parameters bool c
+ wich are incompatible with constraints int c
+# class ['a, 'b] c :
+ unit ->
+ object
+ constraint 'a = int -> 'c
+ constraint 'b = 'a * < x : 'b > * 'c * 'd
+ method f : 'a -> 'b -> unit
+ end
+# class ['a, 'b] d :
+ unit ->
+ object
+ constraint 'a = int -> 'c
+ constraint 'b = 'a * < x : 'b > * 'c * 'd
+ method f : 'a -> 'b -> unit
+ end
+# val x : '_a list ref = {contents = []}
+# Characters 0-50:
+ class ['a] c () = object
+ method f = (x : 'a)
+ end..
+Error: The type of this class,
+ class ['a] c :
+ unit -> object constraint 'a = '_b list ref method f : 'a end,
+ contains type variables that cannot be generalized
+# Characters 20-52:
+ type 'a c = <f : 'a c; g : 'a d>
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In the definition of d, type int c should be 'a c
+# type 'a c = < f : 'a c; g : 'a d >
+and 'a d = < f : 'a c >
+# type 'a c = < f : 'a c >
+and 'a d = < f : int c >
+# type 'a u = < x : 'a >
+and 'a t = 'a t u
+# Characters 15-32:
+ and 'a t = 'a t u;;
+ ^^^^^^^^^^^^^^^^^
+Error: The type abbreviation t is cyclic
+# type 'a u = 'a
+# Characters 0-18:
+ type t = t u * t u;;
+ ^^^^^^^^^^^^^^^^^^
+Error: The type abbreviation t is cyclic
+# type t = < x : 'a > as 'a
+# type 'a u = 'a
+# - : t -> t u -> bool = <fun>
+# - : t -> t u -> bool = <fun>
+# module M :
+ sig
+ class ['a, 'b] c :
+ int ->
+ 'b ->
+ object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+ end
+# module M' :
+ sig
+ class virtual ['a, 'b] c :
+ int ->
+ 'b ->
+ object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+ end
+# class ['a, 'b] d :
+ unit ->
+ 'b ->
+ object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+# class ['a, 'b] e :
+ unit ->
+ 'b ->
+ object
+ constraint 'a = int -> bool
+ val x : float list
+ val y : 'b
+ method f : 'a -> unit
+ method g : 'b
+ end
+# - : string = "a"
+# - : int = 10
+# - : float = 7.1
+# # - : bool = true
+# module M : sig class ['a] c : unit -> object method f : 'a -> unit end end
+# module M' : sig class ['a] c : unit -> object method f : 'a -> unit end end
+# - : ('a #M.c as 'b) -> 'b = <fun>
+# - : ('a #M'.c as 'b) -> 'b = <fun>
+# class ['a] c : 'a #c -> object end
+# class ['a] c : 'a #c -> object end
+# class c : unit -> object method f : int end
+and d : unit -> object method f : int end
+# class e : unit -> object method f : int end
+# - : int = 2
+# Characters 30-34:
+ class c () = object val x = - true val y = -. () end;;
+ ^^^^
+Error: This expression has type bool but an expression was expected of type
+ int
+# class c : unit -> object method f : int method g : int method h : int end
+# class d : unit -> object method h : int method i : int method j : int end
+# class e :
+ unit ->
+ object
+ method f : int
+ method g : int
+ method h : int
+ method i : int
+ method j : int
+ end
+# val e : e = <obj>
+# - : int * int * int * int * int = (1, 3, 2, 2, 3)
+# class c : 'a -> object val a : 'a val x : int val y : int val z : int end
+# class d : 'a -> object val b : 'a val t : int val u : int val z : int end
+# Characters 42-45:
+ inherit c 5
+ ^^^
+Warning 13: the following instance variables are overridden by the class c :
+ x
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+Characters 52-53:
+ val y = 3
+ ^
+Warning 13: the instance variable y is overridden.
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+Characters 80-83:
+ inherit d 7
+ ^^^
+Warning 13: the following instance variables are overridden by the class d :
+ t z
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+Characters 90-91:
+ val u = 3
+ ^
+Warning 13: the instance variable u is overridden.
+The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)
+class e :
+ unit ->
+ object
+ val a : int
+ val b : int
+ val t : int
+ val u : int
+ val x : int
+ val y : int
+ val z : int
+ method a : int
+ method b : int
+ method t : int
+ method u : int
+ method x : int
+ method y : int
+ method z : int
+ end
+# val e : e = <obj>
+# - : int * int * int * int * int * int * int = (1, 3, 2, 2, 3, 5, 7)
+# class c :
+ int ->
+ int -> object val x : int val y : int method x : int method y : int end
+# class d :
+ int ->
+ int -> object val x : int val y : int method x : int method y : int end
+# - : int * int = (1, 2)
+# - : int * int = (1, 2)
+# class ['a] c : 'a -> object end
+# - : 'a -> 'a c = <fun>
+# * * * * * * * * * * * * * * * * * * * * * module M : sig class c : unit -> object method xc : int end end
+# class d : unit -> object val x : int method xc : int method xd : int end
+# - : int * int = (1, 2)
+# Characters 1-154:
+ class virtual ['a] matrix (sz, init : int * 'a) = object
+ val m = Array.make_matrix sz sz init
+ method add (mtx : 'a matrix) = (mtx#m.(0).(0) : 'a)
+ end..
+Error: The abbreviation 'a matrix expands to type < add : 'a matrix -> 'a >
+ but is used with type < m : 'a array array; .. >
+# class c : unit -> object method m : c end
+# - : c = <obj>
+# module M : sig class c : unit -> object method m : c end end
+# - : M.c = <obj>
+# type uu = A of int | B of (< leq : 'a > as 'a)
+# class virtual c : unit -> object ('a) method virtual m : 'a end
+# module S : sig val f : (#c as 'a) -> 'a end
+# Characters 12-43:
+ ............struct
+ let f (x : #c) = x
+ end......
+Error: Signature mismatch:
+ Modules do not match:
+ sig val f : (#c as 'a) -> 'a end
+ is not included in
+ sig val f : #c -> #c end
+ Values do not match:
+ val f : (#c as 'a) -> 'a
+ is not included in
+ val f : #c -> #c
+# Characters 38-39:
+ module M = struct type t = int class t () = object end end;;
+ ^
+Error: Multiple definition of the type name t.
+ Names must be unique in a given structure or signature.
+# - : < m : (< m : 'a > as 'b) -> 'b as 'a; .. > -> 'b = <fun>
+# Characters 10-39:
+ fun x -> (x : int -> bool :> 'a -> 'a);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type int -> bool is not a subtype of int -> int
+ Type bool is not a subtype of int
+# Characters 9-40:
+ fun x -> (x : int -> bool :> int -> int);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type int -> bool is not a subtype of int -> int
+ Type bool is not a subtype of int
+# - : < > -> < > = <fun>
+# - : < .. > -> < > = <fun>
+# val x : '_a list ref = {contents = []}
+# module F : functor (X : sig end) -> sig type t = int end
+# - : < m : int > list ref = {contents = []}
+# type 'a t
+# Characters 9-19:
+ fun (x : 'a t as 'a) -> ();;
+ ^^^^^^^^^^
+Error: This alias is bound to type 'a t but is used as an instance of type 'a
+ The type variable 'a occurs inside 'a t
+# Characters 19-20:
+ fun (x : 'a t) -> (x : 'a); ();;
+ ^
+Error: This expression has type 'a t but an expression was expected of type
+ 'a
+ The type variable 'a occurs inside 'a t
+# type 'a t = < x : 'a >
+# - : ('a t as 'a) -> unit = <fun>
+# Characters 18-26:
+ fun (x : 'a t) -> (x : 'a); ();;
+ ^^^^^^^^
+Warning 10: this expression should have type unit.
+- : ('a t as 'a) t -> unit = <fun>
+# class ['a] c :
+ unit ->
+ object constraint 'a = (< .. > as 'b) -> unit method m : 'b -> unit end
+# class ['a] c :
+ unit ->
+ object constraint 'a = unit -> (< .. > as 'b) method m : 'a -> 'b end
+# class c : unit -> object method private m : int method n : int end
+# class d :
+ unit -> object method private m : int method n : int method o : int end
+# - : int * int = (1, 1)
+# class c : unit -> object method m : int end
+# val r : int ref = {contents = 0}
+# val id : < .. > -> int = <fun>
+# - : unit = ()
+# - : int = 1
+# - : int = 2
+# - : int * int * int = (3, 4, 5)
+# - : int * int * int * int * int = (6, 7, 8, 33, 33)
+# - : int * int * int * int * int * int * int = (9, 10, 10, 11, 11, 33, 33)
+# Characters 42-69:
+ class a = let _ = new b in object end
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This kind of recursive class expression is not allowed
+# Characters 11-38:
+ class a = let _ = new a in object end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This kind of recursive class expression is not allowed
+#
diff --git a/testsuite/tests/typing-objects/pr5545.ml b/testsuite/tests/typing-objects/pr5545.ml
new file mode 100644
index 0000000000..1273e6f0b1
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr5545.ml
@@ -0,0 +1,22 @@
+type foo = int;;
+
+class o =
+ object(this)
+ method x : foo = 10
+ method y : int = this # x
+ end;;
+
+
+class o =
+ object(this)
+ method x : foo = 10
+ method y = (this # x : int)
+ end;;
+
+
+
+class o =
+ object(this)
+ method x : int = (10 : int)
+ method y = (this # x : foo)
+ end;;
diff --git a/testsuite/tests/typing-objects/pr5545.ml.principal.reference b/testsuite/tests/typing-objects/pr5545.ml.principal.reference
new file mode 100644
index 0000000000..4f7fda9661
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr5545.ml.principal.reference
@@ -0,0 +1,6 @@
+
+# type foo = int
+# class o : object method x : foo method y : int end
+# class o : object method x : foo method y : int end
+# class o : object method x : int method y : foo end
+#
diff --git a/testsuite/tests/typing-objects/pr5545.ml.reference b/testsuite/tests/typing-objects/pr5545.ml.reference
new file mode 100644
index 0000000000..4f7fda9661
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr5545.ml.reference
@@ -0,0 +1,6 @@
+
+# type foo = int
+# class o : object method x : foo method y : int end
+# class o : object method x : foo method y : int end
+# class o : object method x : int method y : foo end
+#
diff --git a/testsuite/tests/typing-objects/pr5619_bad.ml b/testsuite/tests/typing-objects/pr5619_bad.ml
new file mode 100644
index 0000000000..2dd3eaaa59
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr5619_bad.ml
@@ -0,0 +1,29 @@
+class type foo_t =
+ object
+ method foo: string
+ end
+
+type 'a name =
+ Foo: foo_t name
+ | Int: int name
+;;
+
+class foo =
+ object(self)
+ method foo = "foo"
+ method cast =
+ function
+ Foo -> (self :> <foo : string>)
+ | _ -> raise Exit
+ end
+;;
+
+class foo: foo_t =
+ object(self)
+ method foo = "foo"
+ method cast: type a. a name -> a =
+ function
+ Foo -> (self :> foo_t)
+ | _ -> ((raise Exit) : a)
+ end
+;;
diff --git a/testsuite/tests/typing-objects/pr5619_bad.ml.principal.reference b/testsuite/tests/typing-objects/pr5619_bad.ml.principal.reference
new file mode 100644
index 0000000000..48777229ce
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr5619_bad.ml.principal.reference
@@ -0,0 +1,18 @@
+
+# class type foo_t = object method foo : string end
+type 'a name = Foo : foo_t name | Int : int name
+# class foo :
+ object method cast : foo_t name -> < foo : string > method foo : string end
+# Characters 22-184:
+ ..object(self)
+ method foo = "foo"
+ method cast: type a. a name -> a =
+ function
+ Foo -> (self :> foo_t)
+ | _ -> ((raise Exit) : a)
+ end
+Error: The class type
+ object method cast : 'a name -> 'a method foo : string end
+ is not matched by the class type foo_t
+ The public method cast cannot be hidden
+#
diff --git a/testsuite/tests/typing-objects/pr5619_bad.ml.reference b/testsuite/tests/typing-objects/pr5619_bad.ml.reference
new file mode 100644
index 0000000000..48777229ce
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr5619_bad.ml.reference
@@ -0,0 +1,18 @@
+
+# class type foo_t = object method foo : string end
+type 'a name = Foo : foo_t name | Int : int name
+# class foo :
+ object method cast : foo_t name -> < foo : string > method foo : string end
+# Characters 22-184:
+ ..object(self)
+ method foo = "foo"
+ method cast: type a. a name -> a =
+ function
+ Foo -> (self :> foo_t)
+ | _ -> ((raise Exit) : a)
+ end
+Error: The class type
+ object method cast : 'a name -> 'a method foo : string end
+ is not matched by the class type foo_t
+ The public method cast cannot be hidden
+#
diff --git a/testsuite/tests/typing-objects/pr5858.ml b/testsuite/tests/typing-objects/pr5858.ml
new file mode 100644
index 0000000000..3795cf3121
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr5858.ml
@@ -0,0 +1,2 @@
+class type c = object end;;
+module type S = sig class c: c end;;
diff --git a/testsuite/tests/typing-objects/pr5858.ml.reference b/testsuite/tests/typing-objects/pr5858.ml.reference
new file mode 100644
index 0000000000..94e6348447
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr5858.ml.reference
@@ -0,0 +1,7 @@
+
+# class type c = object end
+# Characters 29-30:
+ module type S = sig class c: c end;;
+ ^
+Error: The class type c is not yet completely defined
+#
diff --git a/testsuite/tests/typing-objects/pr6123_bad.ml b/testsuite/tests/typing-objects/pr6123_bad.ml
new file mode 100644
index 0000000000..a773f8d70e
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr6123_bad.ml
@@ -0,0 +1,23 @@
+class virtual name =
+object
+end
+
+and func (args_ty, ret_ty) =
+object(self)
+ inherit name
+
+ val mutable memo_args = None
+
+ method arguments =
+ match memo_args with
+ | Some xs -> xs
+ | None ->
+ let args = List.map (fun ty -> new argument(self, ty)) args_ty in
+ memo_args <- Some args; args
+end
+
+and argument (func, ty) =
+object
+ inherit name
+end
+;;
diff --git a/testsuite/tests/typing-objects/pr6123_bad.ml.principal.reference b/testsuite/tests/typing-objects/pr6123_bad.ml.principal.reference
new file mode 100644
index 0000000000..eb3b05c083
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr6123_bad.ml.principal.reference
@@ -0,0 +1,8 @@
+
+# Characters 253-257:
+ let args = List.map (fun ty -> new argument(self, ty)) args_ty in
+ ^^^^
+Error: This expression has type < arguments : 'a; .. >
+ but an expression was expected of type 'b
+ Self type cannot escape its class
+#
diff --git a/testsuite/tests/typing-objects/pr6123_bad.ml.reference b/testsuite/tests/typing-objects/pr6123_bad.ml.reference
new file mode 100644
index 0000000000..eb3b05c083
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr6123_bad.ml.reference
@@ -0,0 +1,8 @@
+
+# Characters 253-257:
+ let args = List.map (fun ty -> new argument(self, ty)) args_ty in
+ ^^^^
+Error: This expression has type < arguments : 'a; .. >
+ but an expression was expected of type 'b
+ Self type cannot escape its class
+#
diff --git a/testsuite/tests/typing-objects/pr6383.ml b/testsuite/tests/typing-objects/pr6383.ml
new file mode 100644
index 0000000000..bd2fdb06f0
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr6383.ml
@@ -0,0 +1 @@
+let f (x: #M.foo) = 0;;
diff --git a/testsuite/tests/typing-objects/pr6383.ml.reference b/testsuite/tests/typing-objects/pr6383.ml.reference
new file mode 100644
index 0000000000..01b6141d3f
--- /dev/null
+++ b/testsuite/tests/typing-objects/pr6383.ml.reference
@@ -0,0 +1,6 @@
+
+# Characters 10-16:
+ let f (x: #M.foo) = 0;;
+ ^^^^^^
+Error: Unbound module M
+#
diff --git a/testsuite/tests/typing-poly-bugs/Makefile b/testsuite/tests/typing-poly-bugs/Makefile
new file mode 100644
index 0000000000..1103dbffda
--- /dev/null
+++ b/testsuite/tests/typing-poly-bugs/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.okbad
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-poly-bugs/pr5322_ok.ml b/testsuite/tests/typing-poly-bugs/pr5322_ok.ml
new file mode 100644
index 0000000000..d6cbca1a7a
--- /dev/null
+++ b/testsuite/tests/typing-poly-bugs/pr5322_ok.ml
@@ -0,0 +1,6 @@
+type 'par t = 'par
+module M : sig val x : <m : 'a. 'a> end =
+ struct let x : <m : 'a. 'a t> = Obj.magic () end
+
+let ident v = v
+class alias = object method alias : 'a . 'a t -> 'a = ident end
diff --git a/testsuite/tests/typing-poly-bugs/pr5673_bad.ml b/testsuite/tests/typing-poly-bugs/pr5673_bad.ml
new file mode 100644
index 0000000000..990880008d
--- /dev/null
+++ b/testsuite/tests/typing-poly-bugs/pr5673_bad.ml
@@ -0,0 +1,23 @@
+module Classdef = struct
+ class virtual ['a, 'b, 'c] cl0 =
+ object
+ constraint 'c = < m : 'a -> 'b -> int; .. >
+ end
+
+ class virtual ['a, 'b] cl1 =
+ object
+ method virtual raise_trouble : int -> 'a
+ method virtual m : 'a -> 'b -> int
+ end
+
+ class virtual ['a, 'b] cl2 =
+ object
+ method virtual as_cl0 : ('a, 'b, ('a, 'b) cl1) cl0
+ end
+end
+
+type refer1 = < poly : 'a 'b 'c . (('b, 'c) #Classdef.cl2 as 'a) >
+type refer2 = < poly : 'a 'b 'c . (('b, 'c) #Classdef.cl2 as 'a) >
+
+(* Actually this should succeed ... *)
+let f (x : refer1) = (x : refer2)
diff --git a/testsuite/tests/typing-poly-bugs/pr5673_ok.ml b/testsuite/tests/typing-poly-bugs/pr5673_ok.ml
new file mode 100644
index 0000000000..26ad1606d9
--- /dev/null
+++ b/testsuite/tests/typing-poly-bugs/pr5673_ok.ml
@@ -0,0 +1,23 @@
+module Classdef = struct
+ class virtual ['a, 'b, 'c] cl0 =
+ object
+ constraint 'c = < m : 'a -> 'b -> int; .. >
+ end
+
+ class virtual ['a, 'b] cl1 =
+ object
+ method virtual raise_trouble : int -> 'a
+ method virtual m : 'a -> 'b -> int
+ end
+
+ class virtual ['a, 'b] cl2 =
+ object
+ method virtual as_cl0 : ('a, 'b, ('a, 'b) cl1) cl0
+ end
+end
+
+module M : sig
+ type refer = { poly : 'a 'b 'c . (('b, 'c) #Classdef.cl2 as 'a) }
+end = struct
+ type refer = { poly : 'a 'b 'c . (('b, 'c) #Classdef.cl2 as 'a) }
+end
diff --git a/testsuite/tests/typing-poly/Makefile b/testsuite/tests/typing-poly/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-poly/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-poly/poly.ml b/testsuite/tests/typing-poly/poly.ml
new file mode 100644
index 0000000000..cb7804bf42
--- /dev/null
+++ b/testsuite/tests/typing-poly/poly.ml
@@ -0,0 +1,689 @@
+(*
+ Polymorphic methods are now available in the main branch.
+ Enjoy.
+*)
+
+(* Tests for explicit polymorphism *)
+open StdLabels;;
+
+type 'a t = { t : 'a };;
+type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b };;
+let f l = { fold = List.fold_left l };;
+(f [1;2;3]).fold ~f:(+) ~init:0;;
+
+class ['b] ilist l = object
+ val l = l
+ method add x = {< l = x :: l >}
+ method fold : 'a. f:('a -> 'b -> 'a) -> init:'a -> 'a =
+ List.fold_left l
+end
+;;
+class virtual ['a] vlist = object (_ : 'self)
+ method virtual add : 'a -> 'self
+ method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
+end
+;;
+class ilist2 l = object
+ inherit [int] vlist
+ val l = l
+ method add x = {< l = x :: l >}
+ method fold = List.fold_left l
+end
+;;
+let ilist2 l = object
+ inherit [_] vlist
+ val l = l
+ method add x = {< l = x :: l >}
+ method fold = List.fold_left l
+end
+;;
+class ['a] ilist3 l = object
+ inherit ['a] vlist
+ val l = l
+ method add x = {< l = x :: l >}
+ method fold = List.fold_left l
+end
+;;
+class ['a] ilist4 (l : 'a list) = object
+ val l = l
+ method virtual add : _
+ method add x = {< l = x :: l >}
+ method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
+ method fold = List.fold_left l
+end
+;;
+class ['a] ilist5 (l : 'a list) = object (self)
+ val l = l
+ method add x = {< l = x :: l >}
+ method virtual fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
+ method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
+ method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init)
+ method fold = List.fold_left l
+end
+;;
+class ['a] ilist6 l = object (self)
+ inherit ['a] vlist
+ val l = l
+ method add x = {< l = x :: l >}
+ method virtual fold2 : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b
+ method fold2 ~f ~init = self#fold ~f ~init:(self#fold ~f ~init)
+ method fold = List.fold_left l
+end
+;;
+class virtual ['a] olist = object
+ method virtual fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c
+end
+;;
+class ['a] onil = object
+ inherit ['a] olist
+ method fold ~f ~init = init
+end
+;;
+class ['a] ocons ~hd ~tl = object (_ : 'b)
+ inherit ['a] olist
+ val hd : 'a = hd
+ val tl : 'a olist = tl
+ method fold ~f ~init = f hd (tl#fold ~f ~init)
+end
+;;
+class ['a] ostream ~hd ~tl = object (_ : 'b)
+ inherit ['a] olist
+ val hd : 'a = hd
+ val tl : _ #olist = (tl : 'a ostream)
+ method fold ~f ~init = f hd (tl#fold ~f ~init)
+ method empty = false
+end
+;;
+class ['a] ostream1 ~hd ~tl = object (self : 'b)
+ inherit ['a] olist
+ val hd = hd
+ val tl : 'b = tl
+ method hd = hd
+ method tl = tl
+ method fold ~f ~init =
+ self#tl#fold ~f ~init:(f self#hd init)
+end
+;;
+
+class vari = object
+ method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int
+ method m = function `A -> 1 | `B|`C -> 0
+end
+;;
+class vari = object
+ method m : 'a. ([< `A|`B|`C] as 'a) -> int = function `A -> 1 | `B|`C -> 0
+end
+;;
+module V =
+ struct
+ type v = [`A | `B | `C]
+ let m : [< v] -> int = function `A -> 1 | #v -> 0
+ end
+;;
+class varj = object
+ method virtual m : 'a. ([< V.v] as 'a) -> int
+ method m = V.m
+end
+;;
+
+module type T = sig
+ class vari : object method m : 'a. ([< `A | `B | `C] as 'a) -> int end
+end
+;;
+module M0 = struct
+ class vari = object
+ method virtual m : 'a. ([< `A|`B|`C] as 'a) -> int
+ method m = function `A -> 1 | `B|`C -> 0
+ end
+end
+;;
+module M : T = M0
+;;
+let v = new M.vari;;
+v#m `A;;
+
+class point ~x ~y = object
+ val x : int = x
+ val y : int = y
+ method x = x
+ method y = y
+end
+;;
+class color_point ~x ~y ~color = object
+ inherit point ~x ~y
+ val color : string = color
+ method color = color
+end
+;;
+class circle (p : #point) ~r = object
+ val p = (p :> point)
+ val r = r
+ method virtual distance : 'a. (#point as 'a) -> float
+ method distance p' =
+ let dx = p#x - p'#x and dy = p#y - p'#y in
+ let d = sqrt (float (dx * dx + dy * dy)) -. float r in
+ if d < 0. then 0. else d
+end
+;;
+let p0 = new point ~x:3 ~y:5
+let p1 = new point ~x:10 ~y:13
+let cp = new color_point ~x:12 ~y:(-5) ~color:"green"
+let c = new circle p0 ~r:2
+let d = floor (c#distance cp)
+;;
+let f (x : < m : 'a. 'a -> 'a >) = (x : < m : 'b. 'b -> 'b >)
+;;
+let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >)
+;;
+
+class id = object
+ method virtual id : 'a. 'a -> 'a
+ method id x = x
+end
+;;
+
+class type id_spec = object
+ method id : 'a -> 'a
+end
+;;
+class id_impl = object (_ : #id_spec)
+ method id x = x
+end
+;;
+
+class a = object
+ method m = (new b : id_spec)#id true
+end
+and b = object (_ : #id_spec)
+ method id x = x
+end
+;;
+
+class ['a] id1 = object
+ method virtual id : 'b. 'b -> 'a
+ method id x = x
+end
+;;
+class id2 (x : 'a) = object
+ method virtual id : 'b. 'b -> 'a
+ method id x = x
+end
+;;
+class id3 x = object
+ val x = x
+ method virtual id : 'a. 'a -> 'a
+ method id _ = x
+end
+;;
+class id4 () = object
+ val mutable r = None
+ method virtual id : 'a. 'a -> 'a
+ method id x =
+ match r with
+ None -> r <- Some x; x
+ | Some y -> y
+end
+;;
+class c = object
+ method virtual m : 'a 'b. 'a -> 'b -> 'a
+ method m x y = x
+end
+;;
+
+let f1 (f : id) = f#id 1, f#id true
+;;
+let f2 f = (f : id)#id 1, (f : id)#id true
+;;
+let f3 f = f#id 1, f#id true
+;;
+let f4 f = ignore(f : id); f#id 1, f#id true
+;;
+
+class c = object
+ method virtual m : 'a. (#id as 'a) -> int * bool
+ method m (f : #id) = f#id 1, f#id true
+end
+;;
+
+class id2 = object (_ : 'b)
+ method virtual id : 'a. 'a -> 'a
+ method id x = x
+ method mono (x : int) = x
+end
+;;
+let app = new c #m (new id2)
+;;
+type 'a foo = 'a foo list
+;;
+
+class ['a] bar (x : 'a) = object end
+;;
+type 'a foo = 'a foo bar
+;;
+
+fun x -> (x : < m : 'a. 'a * 'b > as 'b)#m;;
+fun x -> (x : < m : 'a. 'b * 'a list> as 'b)#m;;
+let f x = (x : < m : 'a. 'b * (< n : 'a; .. > as 'a) > as 'b)#m;;
+fun (x : < p : 'a. < m : 'a ; n : 'b ; .. > as 'a > as 'b) -> x#p;;
+fun (x : <m:'a. 'a * <p:'b. 'b * 'c * 'd> as 'c> as 'd) -> x#m;;
+(* printer is wrong on the next (no official syntax) *)
+fun (x : <m:'a.<p:'a;..> >) -> x#m;;
+
+type sum = T of < id: 'a. 'a -> 'a > ;;
+fun (T x) -> x#id;;
+
+type record = { r: < id: 'a. 'a -> 'a > } ;;
+fun x -> x.r#id;;
+fun {r=x} -> x#id;;
+
+class myself = object (self)
+ method self : 'a. 'a -> 'b = fun _ -> self
+end;;
+
+class number = object (self : 'self)
+ val num = 0
+ method num = num
+ method succ = {< num = num + 1 >}
+ method prev =
+ self#switch ~zero:(fun () -> failwith "zero") ~prev:(fun x -> x)
+ method switch : 'a. zero:(unit -> 'a) -> prev:('self -> 'a) -> 'a =
+ fun ~zero ~prev ->
+ if num = 0 then zero () else prev {< num = num - 1 >}
+end
+;;
+
+let id x = x
+;;
+class c = object
+ method id : 'a. 'a -> 'a = id
+end
+;;
+class c' = object
+ inherit c
+ method id = id
+end
+;;
+class d = object
+ inherit c as c
+ val mutable count = 0
+ method id x = count <- count+1; x
+ method count = count
+ method old : 'a. 'a -> 'a = c#id
+end
+;;
+class ['a] olist l = object
+ val l = l
+ method fold : 'b. f:('a -> 'b -> 'b) -> init:'b -> 'b
+ = List.fold_right l
+ method cons a = {< l = a :: l >}
+end
+;;
+let sum (l : 'a #olist) = l#fold ~f:(fun x acc -> x+acc) ~init:0
+;;
+let count (l : 'a #olist) = l#fold ~f:(fun _ acc -> acc+1) ~init:0
+;;
+let append (l : 'a #olist) (l' : 'b #olist) =
+ l#fold ~init:l' ~f:(fun x acc -> acc#cons x)
+;;
+
+type 'a t = unit
+;;
+class o = object method x : 'a. ([> `A] as 'a) t -> unit = fun _ -> () end
+;;
+
+class c = object method m = new d () end and d ?(x=0) () = object end;;
+class d ?(x=0) () = object end and c = object method m = new d () end;;
+
+class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end
+class zero = object (_ : #numeral) method fold f x = x end
+class next (n : #numeral) =
+ object (_ : #numeral) method fold f x = n#fold f (f x) end
+;;
+
+class type node_type = object
+ method as_variant : [> `Node of node_type]
+end;;
+class node : node_type = object (self)
+ method as_variant : 'a. [> `Node of node_type] as 'a
+ = `Node (self :> node_type)
+end;;
+class node = object (self : #node_type)
+ method as_variant = `Node (self :> node_type)
+end;;
+
+type bad = {bad : 'a. 'a option ref};;
+let bad = {bad = ref None};;
+type bad2 = {mutable bad2 : 'a. 'a option ref option};;
+let bad2 = {bad2 = None};;
+bad2.bad2 <- Some (ref None);;
+
+(* Type variable scope *)
+
+let f (x: <m:'a.<p: 'a * 'b> as 'b>) (y : 'b) = ();;
+let f (x: <m:'a. 'a * (<p:int*'b> as 'b)>) (y : 'b) = ();;
+
+(* PR#1374 *)
+
+type 'a t= [`A of 'a];;
+class c = object (self)
+ method m : 'a. ([> 'a t] as 'a) -> unit
+ = fun x -> self#m x
+end;;
+class c = object (self)
+ method m : 'a. ([> 'a t] as 'a) -> unit = function
+ | `A x' -> self#m x'
+ | _ -> failwith "c#m"
+end;;
+class c = object (self)
+ method m : 'a. ([> 'a t] as 'a) -> 'a = fun x -> self#m x
+end;;
+
+(* usage avant instance *)
+class c = object method m : 'a. 'a option -> ([> `A] as 'a) = fun x -> `A end;;
+
+(* various old bugs *)
+class virtual ['a] visitor =
+object method virtual caseNil : 'a end
+and virtual int_list =
+object method virtual visit : 'a.('a visitor -> 'a) end;;
+
+type ('a,'b) list_visitor = < caseNil : 'a; caseCons : 'b -> 'b list -> 'a >
+type 'b alist = < visit : 'a. ('a,'b) list_visitor -> 'a >
+
+(* PR#1607 *)
+class type ct = object ('s)
+ method fold : ('b -> 's -> 'b) -> 'b -> 'b
+end
+type t = {f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b};;
+
+(* PR#1663 *)
+type t = u and u = t;;
+
+(* PR#1731 *)
+class ['t] a = object constraint 't = [> `A of 't a] end
+type t = [ `A of t a ];;
+
+(* Wrong in 3.06 *)
+type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;;
+
+(* Full polymorphism if we do not expand *)
+type 'a t = 'a and u = int t;;
+
+(* Loose polymorphism if we expand *)
+type 'a t constraint 'a = int;;
+type 'a u = 'a and 'a v = 'a u t;;
+type 'a u = 'a and 'a v = 'a u t constraint 'a = int;;
+
+(* Behaviour is unstable *)
+type g = int;;
+type 'a t = unit constraint 'a = g;;
+type 'a u = 'a and 'a v = 'a u t;;
+type 'a u = 'a and 'a v = 'a u t constraint 'a = int;;
+
+(* Example of wrong expansion *)
+type 'a u = < m : 'a v > and 'a v = 'a list u;;
+
+(* PR#1744: Ctype.matches *)
+type 'a t = 'a
+type 'a u = A of 'a t;;
+
+(* Unification of cyclic terms *)
+type 'a t = < a : 'a >;;
+fun (x : 'a t as 'a) -> (x : 'b t);;
+type u = 'a t as 'a;;
+
+
+(* Variant tests *)
+type t = A | B;;
+function `A,_ -> 1 | _,A -> 2 | _,B -> 3;;
+function `A,_ -> 1 | _,(A|B) -> 2;;
+function Some `A, _ -> 1 | Some _, A -> 2 | None, A -> 3 | _, B -> 4;;
+function Some `A, A -> 1 | Some `A, B -> 1
+ | Some _, A -> 2 | None, A -> 3 | _, B -> 4;;
+function A, `A -> 1 | A, `B -> 2 | B, _ -> 3;;
+function `A, A -> 1 | `B, A -> 2 | _, B -> 3;;
+function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;;
+function `B,1 -> 1 | _,1 -> 2;;
+function 1,`B -> 1 | 1,_ -> 2;;
+
+(* pass typetexp, but fails during Typedecl.check_recursion *)
+type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b]
+and ('a, 'b) b = 'b -> unit constraint 'b = [> `A of ('a, 'b) a as 'a];;
+
+(* PR#1917: expanding may change original in Ctype.unify2 *)
+(* Note: since 3.11, the abbreviations are not used when printing
+ a type where they occur recursively inside. *)
+class type ['a, 'b] a = object
+ method b: ('a, 'b) #b as 'b
+ method as_a: ('a, 'b) a
+end and ['a, 'b] b = object
+ method a: ('a, 'b) #a as 'a
+ method as_b: ('a, 'b) b
+end
+
+class type ['b] ca = object ('s) inherit ['s, 'b] a end
+class type ['a] cb = object ('s) inherit ['a, 's] b end
+
+type bt = 'b ca cb as 'b
+;;
+
+(* final classes, etc... *)
+class c = object method m = 1 end;;
+let f () = object (self:c) method m = 1 end;;
+let f () = object (self:c) method private n = 1 method m = self#n end;;
+let f () = object method private n = 1 method m = {<>}#n end;;
+let f () = object (self:c) method n = 1 method m = 2 end;;
+let f () = object (_:'s) constraint 's = < n : int > method m = 1 end;;
+class c = object (_ : 's)
+ method x = 1
+ method private m =
+ object (self: 's) method x = 3 method private m = self end
+end;;
+let o = object (_ : 's)
+ method x = 1
+ method private m =
+ object (self: 's) method x = 3 method private m = self end
+end;;
+
+
+(* Unsound! *)
+fun (x : <m : 'a. 'a * <m: 'b. 'a * 'foo> > as 'foo) ->
+ (x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);;
+type 'a foo = <m: 'b. 'a * 'a foo>
+type foo' = <m: 'a. 'a * 'a foo>
+type 'a bar = <m: 'b. 'a * <m: 'c. 'c * 'a bar> >
+type bar' = <m: 'a. 'a * 'a bar >
+let f (x : foo') = (x : bar');;
+
+fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) ->
+ (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);;
+fun (x : <m : 'a. 'a * ('a * <m : 'a. 'a * 'foo> as 'foo)>) ->
+ (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('b * 'bar)>)> as 'bar);;
+fun (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) ->
+ (x : <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>);;
+let f x =
+ (x : <m : 'a. 'a -> ('a * <m:'c. 'c -> 'bar> as 'bar)>
+ :> <m : 'a. 'a -> ('a * 'foo)> as 'foo);;
+
+module M
+: sig val f : (<m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>) -> unit end
+= struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;;
+module M
+: sig type t = <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)> end
+= struct type t = <m : 'a. 'a * ('a * 'foo)> as 'foo end;;
+
+module M : sig type 'a t type u = <m: 'a. 'a t> end
+= struct type 'a t = int type u = <m: int> end;;
+module M : sig type 'a t val f : <m: 'a. 'a t> -> int end
+= struct type 'a t = int let f (x : <m:int>) = x#m end;;
+(* The following should be accepted too! *)
+module M : sig type 'a t val f : <m: 'a. 'a t> -> int end
+= struct type 'a t = int let f x = x#m end;;
+
+let f x y =
+ ignore (x :> <m:'a.'a -> 'c * < > > as 'c);
+ ignore (y :> <m:'b.'b -> 'd * < > > as 'd);
+ x = y;;
+
+
+(* Subtyping *)
+
+type t = [`A|`B];;
+type v = private [> t];;
+fun x -> (x : t :> v);;
+type u = private [< t];;
+fun x -> (x : u :> v);;
+fun x -> (x : v :> u);;
+type v = private [< t];;
+fun x -> (x : u :> v);;
+type p = <x:p>;;
+type q = private <x:p; ..>;;
+fun x -> (x : q :> p);;
+fun x -> (x : p :> q);;
+
+let f1 x =
+ (x : <m:'a. (<p:int;..> as 'a) -> int>
+ :> <m:'b. (<p:int;q:int;..> as 'b) -> int>);;
+let f2 x =
+ (x : <m:'a. (<p:<a:int>;..> as 'a) -> int>
+ :> <m:'b. (<p:<a:int;b:int>;..> as 'b) -> int>);;
+let f3 x =
+ (x : <m:'a. (<p:<a:int;b:int>;..> as 'a) -> int>
+ :> <m:'b. (<p:<a:int>;..> as 'b) -> int>);;
+let f4 x = (x : <p:<a:int;b:int>;..> :> <p:<a:int>;..>);;
+let f5 x =
+ (x : <m:'a. [< `A of <p:int> ] as 'a> :> <m:'a. [< `A of < > ] as 'a>);;
+let f6 x =
+ (x : <m:'a. [< `A of < > ] as 'a> :> <m:'a. [< `A of <p:int> ] as 'a>);;
+
+(* Keep sharing the epsilons *)
+let f x = if true then (x : < m : 'a. 'a -> 'a >) else x;;
+fun x -> (f x)#m;; (* Warning 18 *)
+let f (x, y) = if true then (x : < m : 'a. 'a -> 'a >) else x;;
+fun x -> (f (x,x))#m;; (* Warning 18 *)
+let f x = if true then [| (x : < m : 'a. 'a -> 'a >) |] else [|x|];;
+fun x -> (f x).(0)#m;; (* Warning 18 *)
+
+(* Not really principal? *)
+class c = object method id : 'a. 'a -> 'a = fun x -> x end;;
+type u = c option;;
+let just = function None -> failwith "just" | Some x -> x;;
+let f x = let l = [Some x; (None : u)] in (just(List.hd l))#id;;
+let g x =
+ let none = (fun y -> ignore [y;(None:u)]; y) None in
+ let x = List.hd [Some x; none] in (just x)#id;;
+let h x =
+ let none = let y = None in ignore [y;(None:u)]; y in
+ let x = List.hd [Some x; none] in (just x)#id;;
+
+(* Only solved for parameterless abbreviations *)
+type 'a u = c option;;
+let just = function None -> failwith "just" | Some x -> x;;
+let f x = let l = [Some x; (None : _ u)] in (just(List.hd l))#id;;
+
+(* polymorphic recursion *)
+
+let rec f : 'a. 'a -> _ = fun x -> 1 and g x = f x;;
+type 'a t = Leaf of 'a | Node of ('a * 'a) t;;
+let rec depth : 'a. 'a t -> _ =
+ function Leaf _ -> 1 | Node x -> 1 + depth x;;
+let rec depth : 'a. 'a t -> _ =
+ function Leaf _ -> 1 | Node x -> 1 + d x
+and d x = depth x;; (* fails *)
+let rec depth : 'a. 'a t -> _ =
+ function Leaf x -> x | Node x -> 1 + depth x;; (* fails *)
+let rec depth : 'a. 'a t -> _ =
+ function Leaf x -> x | Node x -> depth x;; (* fails *)
+let rec depth : 'a 'b. 'a t -> 'b =
+ function Leaf x -> x | Node x -> depth x;; (* fails *)
+let rec r : 'a. 'a list * 'b list ref = [], ref []
+and q () = r;;
+let f : 'a. _ -> _ = fun x -> x;;
+let zero : 'a. [> `Int of int | `B of 'a] as 'a = `Int 0;; (* ok *)
+let zero : 'a. [< `Int of int] as 'a = `Int 0;; (* fails *)
+
+(* compare with records (should be the same) *)
+type t = {f: 'a. [> `Int of int | `B of 'a] as 'a}
+let zero = {f = `Int 0} ;;
+type t = {f: 'a. [< `Int of int] as 'a}
+let zero = {f = `Int 0} ;; (* fails *)
+
+(* Yet another example *)
+let rec id : 'a. 'a -> 'a = fun x -> x
+and neg i b = (id (-i), id (not b));;
+
+(* De Xavier *)
+
+type t = A of int | B of (int*t) list | C of (string*t) list
+
+let rec transf f = function
+ | A x -> f x
+ | B l -> B (transf_alist f l)
+ | C l -> C (transf_alist f l)
+and transf_alist : 'a. _ -> ('a*t) list -> ('a*t) list = fun f -> function
+ | [] -> []
+ | (k,v)::tl -> (k, transf f v) :: transf_alist f tl
+;;
+
+(* PR#4862 *)
+
+type t = {f: 'a. ('a list -> int) Lazy.t}
+let l : t = { f = lazy (raise Not_found)};;
+
+(* variant *)
+type t = {f: 'a. 'a -> unit};;
+let f ?x y = () in {f};;
+let f ?x y = y in {f};; (* fail *)
+
+(* Polux Moon caml-list 2011-07-26 *)
+module Polux = struct
+ type 'par t = 'par
+ let ident v = v
+ class alias = object method alias : 'a . 'a t -> 'a = ident end
+ let f (x : <m : 'a. 'a t>) = (x : <m : 'a. 'a>)
+end;;
+
+(* PR#5560 *)
+
+let (a, b) = (raise Exit : int * int);;
+type t = { foo : int }
+let {foo} = (raise Exit : t);;
+type s = A of int
+let (A x) = (raise Exit : s);;
+
+(* PR#5224 *)
+
+type 'x t = < f : 'y. 'y t >;;
+
+(* PR#6056, PR#6057 *)
+let using_match b =
+ let f =
+ match b with
+ | true -> fun x -> x
+ | false -> fun x -> x
+ in
+ f 0,f
+;;
+
+match (fun x -> x), fun x -> x with x, y -> x, y;;
+match fun x -> x with x -> x, x;;
+
+(* PR#6747 *)
+(* ok *)
+let n = object
+ method m : 'x 'o. ([< `Foo of 'x] as 'o) -> 'x = fun x -> assert false
+end;;
+(* ok, but not with -principal *)
+let n =
+ object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
+(* fail *)
+let (n : < m : 'a. [< `Foo of int] -> 'a >) =
+ object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
+(* fail *)
+let (n : 'b -> < m : 'a . ([< `Foo of int] as 'b) -> 'a >) = fun x ->
+ object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
+
+(* PR#6171 *)
+let f b (x: 'x) =
+ let module M = struct type t = A end in
+ if b then x else M.A;;
diff --git a/testsuite/tests/typing-poly/poly.ml.principal.reference b/testsuite/tests/typing-poly/poly.ml.principal.reference
new file mode 100644
index 0000000000..d480e82f80
--- /dev/null
+++ b/testsuite/tests/typing-poly/poly.ml.principal.reference
@@ -0,0 +1,675 @@
+
+# * * * # type 'a t = { t : 'a; }
+# type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b; }
+# val f : 'a list -> 'a fold = <fun>
+# - : int = 6
+# class ['b] ilist :
+ 'b list ->
+ object ('c)
+ val l : 'b list
+ method add : 'b -> 'c
+ method fold : f:('a -> 'b -> 'a) -> init:'a -> 'a
+ end
+# class virtual ['a] vlist :
+ object ('c)
+ method virtual add : 'a -> 'c
+ method virtual fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class ilist2 :
+ int list ->
+ object ('a)
+ val l : int list
+ method add : int -> 'a
+ method fold : f:('b -> int -> 'b) -> init:'b -> 'b
+ end
+# val ilist2 : 'a list -> 'a vlist = <fun>
+# class ['a] ilist3 :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method add : 'a -> 'c
+ method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class ['a] ilist4 :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method add : 'a -> 'c
+ method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class ['a] ilist5 :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method add : 'a -> 'c
+ method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ method fold2 : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class ['a] ilist6 :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method add : 'a -> 'c
+ method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ method fold2 : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class virtual ['a] olist :
+ object method virtual fold : f:('a -> 'c -> 'c) -> init:'c -> 'c end
+# class ['a] onil :
+ object method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c end
+# class ['a] ocons :
+ hd:'a ->
+ tl:'a olist ->
+ object
+ val hd : 'a
+ val tl : 'a olist
+ method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
+ end
+# class ['a] ostream :
+ hd:'a ->
+ tl:'a ostream ->
+ object
+ val hd : 'a
+ val tl : < empty : bool; fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c >
+ method empty : bool
+ method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
+ end
+# Characters 166-178:
+ self#tl#fold ~f ~init:(f self#hd init)
+ ^^^^^^^^^^^^
+Warning 18: this use of a polymorphic method is not principal.
+class ['a] ostream1 :
+ hd:'a ->
+ tl:'b ->
+ object ('b)
+ val hd : 'a
+ val tl : 'b
+ method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
+ method hd : 'a
+ method tl : 'b
+ end
+# class vari : object method m : [< `A | `B | `C ] -> int end
+# class vari : object method m : [< `A | `B | `C ] -> int end
+# module V : sig type v = [ `A | `B | `C ] val m : [< v ] -> int end
+# class varj : object method m : [< V.v ] -> int end
+# module type T =
+ sig class vari : object method m : [< `A | `B | `C ] -> int end end
+# module M0 :
+ sig class vari : object method m : [< `A | `B | `C ] -> int end end
+# module M : T
+# val v : M.vari = <obj>
+# - : int = 1
+# class point :
+ x:int ->
+ y:int -> object val x : int val y : int method x : int method y : int end
+# class color_point :
+ x:int ->
+ y:int ->
+ color:string ->
+ object
+ val color : string
+ val x : int
+ val y : int
+ method color : string
+ method x : int
+ method y : int
+ end
+# class circle :
+ #point ->
+ r:int ->
+ object val p : point val r : int method distance : #point -> float end
+# val p0 : point = <obj>
+val p1 : point = <obj>
+val cp : color_point = <obj>
+val c : circle = <obj>
+val d : float = 11.
+# val f : < m : 'a. 'a -> 'a > -> < m : 'b. 'b -> 'b > = <fun>
+# Characters 41-42:
+ let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >)
+ ^
+Error: This expression has type < m : 'b. 'b -> 'b list >
+ but an expression was expected of type < m : 'b. 'b -> 'c >
+ The universal variable 'b would escape its scope
+# class id : object method id : 'a -> 'a end
+# class type id_spec = object method id : 'a -> 'a end
+# class id_impl : object method id : 'a -> 'a end
+# class a : object method m : bool end
+and b : object method id : 'a -> 'a end
+# Characters 72-77:
+ method id x = x
+ ^^^^^
+Error: This method has type 'a -> 'a which is less general than 'b. 'b -> 'a
+# Characters 75-80:
+ method id x = x
+ ^^^^^
+Error: This method has type 'a -> 'a which is less general than 'b. 'b -> 'a
+# Characters 80-85:
+ method id _ = x
+ ^^^^^
+Error: This method has type 'b -> 'b which is less general than 'a. 'a -> 'a
+# Characters 92-159:
+ ............x =
+ match r with
+ None -> r <- Some x; x
+ | Some y -> y
+Error: This method has type 'b -> 'b which is less general than 'a. 'a -> 'a
+# class c : object method m : 'a -> 'b -> 'a end
+# val f1 : id -> int * bool = <fun>
+# val f2 : id -> int * bool = <fun>
+# Characters 24-28:
+ let f3 f = f#id 1, f#id true
+ ^^^^
+Error: This expression has type bool but an expression was expected of type
+ int
+# Characters 27-31:
+ let f4 f = ignore(f : id); f#id 1, f#id true
+ ^^^^
+Warning 18: this use of a polymorphic method is not principal.
+Characters 35-39:
+ let f4 f = ignore(f : id); f#id 1, f#id true
+ ^^^^
+Warning 18: this use of a polymorphic method is not principal.
+val f4 : id -> int * bool = <fun>
+# class c : object method m : #id -> int * bool end
+# class id2 : object method id : 'a -> 'a method mono : int -> int end
+# val app : int * bool = (1, true)
+# Characters 0-25:
+ type 'a foo = 'a foo list
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: The type abbreviation foo is cyclic
+# class ['a] bar : 'a -> object end
+# type 'a foo = 'a foo bar
+# - : (< m : 'a. 'a * 'b > as 'b) -> 'c * (< m : 'a. 'a * 'd > as 'd) = <fun>
+# - : (< m : 'a. 'b * 'a list > as 'b) ->
+ (< m : 'a. 'c * 'a list > as 'c) * 'd list
+= <fun>
+# val f :
+ (< m : 'b. 'a * (< n : 'b; .. > as 'b) > as 'a) ->
+ (< m : 'd. 'c * (< n : 'd; .. > as 'd) > as 'c) * (< n : 'e; .. > as 'e) =
+ <fun>
+# - : (< p : 'b. < m : 'b; n : 'a; .. > as 'b > as 'a) ->
+ (< m : 'c; n : < p : 'e. < m : 'e; n : 'd; .. > as 'e > as 'd; .. > as 'c)
+= <fun>
+# - : (< m : 'a. 'a * < p : 'b. 'b * 'd * 'c > as 'd > as 'c) ->
+ ('f *
+ < p : 'b.
+ 'b * 'e *
+ (< m : 'a. 'a * < p : 'b0. 'b0 * 'h * 'g > as 'h > as 'g) >
+ as 'e)
+= <fun>
+# - : < m : 'a. < p : 'a; .. > as 'b > -> 'b = <fun>
+# type sum = T of < id : 'a. 'a -> 'a >
+# - : sum -> 'a -> 'a = <fun>
+# type record = { r : < id : 'a. 'a -> 'a >; }
+# - : record -> 'a -> 'a = <fun>
+# - : record -> 'a -> 'a = <fun>
+# class myself : object ('b) method self : 'a -> 'b end
+# class number :
+ object ('b)
+ val num : int
+ method num : int
+ method prev : 'b
+ method succ : 'b
+ method switch : zero:(unit -> 'a) -> prev:('b -> 'a) -> 'a
+ end
+# val id : 'a -> 'a = <fun>
+# class c : object method id : 'a -> 'a end
+# class c' : object method id : 'a -> 'a end
+# class d :
+ object
+ val mutable count : int
+ method count : int
+ method id : 'a -> 'a
+ method old : 'a -> 'a
+ end
+# class ['a] olist :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method cons : 'a -> 'c
+ method fold : f:('a -> 'b -> 'b) -> init:'b -> 'b
+ end
+# val sum : int #olist -> int = <fun>
+# val count : 'a #olist -> int = <fun>
+# val append : 'a #olist -> ('a #olist as 'b) -> 'b = <fun>
+# type 'a t = unit
+# class o : object method x : [> `A ] t -> unit end
+# class c : object method m : d end
+and d : ?x:int -> unit -> object end
+# class d : ?x:int -> unit -> object end
+and c : object method m : d end
+# class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end
+class zero : object method fold : ('a -> 'a) -> 'a -> 'a end
+class next : #numeral -> object method fold : ('a -> 'a) -> 'a -> 'a end
+# class type node_type = object method as_variant : [> `Node of node_type ] end
+# class node : node_type
+# class node : object method as_variant : [> `Node of node_type ] end
+# type bad = { bad : 'a. 'a option ref; }
+# Characters 17-25:
+ let bad = {bad = ref None};;
+ ^^^^^^^^
+Error: This field value has type 'b option ref which is less general than
+ 'a. 'a option ref
+# type bad2 = { mutable bad2 : 'a. 'a option ref option; }
+# val bad2 : bad2 = {bad2 = None}
+# Characters 13-28:
+ bad2.bad2 <- Some (ref None);;
+ ^^^^^^^^^^^^^^^
+Error: This field value has type 'b option ref option
+ which is less general than 'a. 'a option ref option
+# val f : < m : 'a. < p : 'a * 'c > as 'c > -> 'b -> unit = <fun>
+# val f :
+ < m : 'a. 'a * (< p : int * 'b > as 'b) > ->
+ (< p : int * 'c > as 'c) -> unit = <fun>
+# type 'a t = [ `A of 'a ]
+# class c : object method m : ([> 'a t ] as 'a) -> unit end
+# class c : object method m : ([> 'a t ] as 'a) -> unit end
+# class c : object method m : ([> 'a t ] as 'a) -> 'a end
+# class c : object method m : ([> `A ] as 'a) option -> 'a end
+# Characters 145-166:
+ object method virtual visit : 'a.('a visitor -> 'a) end;;
+ ^^^^^^^^^^^^^^^^^^^^^
+Error: The universal type variable 'a cannot be generalized:
+ it escapes its scope.
+# type ('a, 'b) list_visitor = < caseCons : 'b -> 'b list -> 'a; caseNil : 'a >
+type 'b alist = < visit : 'a. ('a, 'b) list_visitor -> 'a >
+class type ct = object ('a) method fold : ('b -> 'a -> 'b) -> 'b -> 'b end
+type t = { f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b; }
+# Characters 15-25:
+ type t = u and u = t;;
+ ^^^^^^^^^^
+Error: The type abbreviation t is cyclic
+# class ['a] a : object constraint 'a = [> `A of 'a a ] end
+type t = [ `A of t a ]
+# Characters 71-80:
+ type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;;
+ ^^^^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type ('a, 'b) t should be an instance of ('c, 'c) t
+# type 'a t = 'a
+and u = int t
+# type 'a t constraint 'a = int
+# Characters 26-32:
+ type 'a u = 'a and 'a v = 'a u t;;
+ ^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type 'a u t should be an instance of int t
+# type 'a u = 'a constraint 'a = int
+and 'a v = 'a u t constraint 'a = int
+# type g = int
+# type 'a t = unit constraint 'a = g
+# Characters 26-32:
+ type 'a u = 'a and 'a v = 'a u t;;
+ ^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type 'a u t should be an instance of g t
+# type 'a u = 'a constraint 'a = g
+and 'a v = 'a u t constraint 'a = g
+# Characters 34-58:
+ type 'a u = < m : 'a v > and 'a v = 'a list u;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In the definition of v, type 'a list u should be 'a u
+# type 'a t = 'a
+type 'a u = A of 'a t
+# type 'a t = < a : 'a >
+# - : ('a t as 'a) -> ('b t as 'b) t = <fun>
+# type u = 'a t as 'a
+# type t = A | B
+# - : [> `A ] * t -> int = <fun>
+# - : [> `A ] * t -> int = <fun>
+# - : [> `A ] option * t -> int = <fun>
+# - : [> `A ] option * t -> int = <fun>
+# - : t * [< `A | `B ] -> int = <fun>
+# - : [< `A | `B ] * t -> int = <fun>
+# Characters 0-41:
+ function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(`AnyExtraTag, `AnyExtraTag)
+- : [> `A | `B ] * [> `A | `B ] -> int = <fun>
+# Characters 0-29:
+ function `B,1 -> 1 | _,1 -> 2;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(_, 0)
+Characters 21-24:
+ function `B,1 -> 1 | _,1 -> 2;;
+ ^^^
+Warning 11: this match case is unused.
+- : [< `B ] * int -> int = <fun>
+# Characters 0-29:
+ function 1,`B -> 1 | 1,_ -> 2;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(0, _)
+Characters 21-24:
+ function 1,`B -> 1 | 1,_ -> 2;;
+ ^^^
+Warning 11: this match case is unused.
+- : int * [< `B ] -> int = <fun>
+# Characters 64-135:
+ type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b]
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type
+ ([> `B of 'a ], 'a) b as 'a
+ should be an instance of
+ (('b, [> `A of ('d, 'c) a as 'd ] as 'c) a as 'b, 'c) b
+# * class type ['a, 'b] a =
+ object
+ constraint 'a = < as_a : ('a, 'b) a as 'c; b : 'b; .. >
+ constraint 'b = < a : 'a; as_b : ('a, 'b) b; .. >
+ method as_a : 'c
+ method b : 'b
+ end
+and ['a, 'b] b =
+ object
+ constraint 'a = < as_a : ('a, 'b) a; b : 'b; .. >
+ constraint 'b = < a : 'a; as_b : ('a, 'b) b; .. >
+ method a : 'a
+ method as_b : ('a, 'b) b
+ end
+class type ['a] ca =
+ object ('b)
+ constraint 'a = < a : 'b; as_b : ('b, 'a) b; .. >
+ method as_a : ('b, 'a) a
+ method b : 'a
+ end
+class type ['a] cb =
+ object ('b)
+ constraint 'a = < as_a : ('a, 'b) a; b : 'b; .. >
+ method a : 'a
+ method as_b : ('a, 'b) b
+ end
+type bt = 'a ca cb as 'a
+# class c : object method m : int end
+# val f : unit -> c = <fun>
+# val f : unit -> c = <fun>
+# Characters 11-60:
+ let f () = object method private n = 1 method m = {<>}#n end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 15: the following private methods were made public implicitly:
+ n.
+val f : unit -> < m : int; n : int > = <fun>
+# Characters 11-56:
+ let f () = object (self:c) method n = 1 method m = 2 end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This object is expected to have type c but actually has type
+ < m : int; n : 'a >
+ The first object type has no method n
+# Characters 11-69:
+ let f () = object (_:'s) constraint 's = < n : int > method m = 1 end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This object is expected to have type < n : int > but actually has type
+ < m : 'a >
+ The second object type has no method n
+# Characters 66-124:
+ object (self: 's) method x = 3 method private m = self end
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This object is expected to have type < x : int; .. >
+ but actually has type < x : int >
+ Self type cannot be unified with a closed object type
+# val o : < x : int > = <obj>
+# Characters 76-77:
+ (x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);;
+ ^
+Error: This expression has type < m : 'a. 'a * < m : 'a * 'b > > as 'b
+ but an expression was expected of type
+ < m : 'a. 'a * (< m : 'a * < m : 'c. 'c * 'd > > as 'd) >
+ Types for method m are incompatible
+# Characters 176-177:
+ let f (x : foo') = (x : bar');;
+ ^
+Error: This expression has type foo' = < m : 'a. 'a * 'a foo >
+ but an expression was expected of type bar' = < m : 'a. 'a * 'a bar >
+ Type 'a foo = < m : 'a * 'a foo > is not compatible with type
+ 'a bar = < m : 'a * < m : 'c. 'c * 'a bar > >
+ Type 'a foo = < m : 'a * 'a foo > is not compatible with type
+ < m : 'c. 'c * 'a bar >
+ Types for method m are incompatible
+# Characters 67-68:
+ (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);;
+ ^
+Error: This expression has type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) >
+ but an expression was expected of type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * ('c * 'd) >) > as 'd
+ Types for method m are incompatible
+# Characters 66-67:
+ (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('b * 'bar)>)> as 'bar);;
+ ^
+Error: This expression has type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) >
+ but an expression was expected of type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * ('b * 'd) >) > as 'd
+ Types for method m are incompatible
+# Characters 51-52:
+ (x : <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>);;
+ ^
+Error: This expression has type < m : 'b. 'b * ('b * 'a) > as 'a
+ but an expression was expected of type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * 'd > as 'd) >
+ Types for method m are incompatible
+# Characters 14-115:
+ ....(x : <m : 'a. 'a -> ('a * <m:'c. 'c -> 'bar> as 'bar)>
+ :> <m : 'a. 'a -> ('a * 'foo)> as 'foo)..
+Error: Type < m : 'a. 'a -> ('a * (< m : 'c. 'c -> 'b as 'e > as 'd) as 'b) >
+ is not a subtype of < m : 'a. 'a -> ('a * 'f as 'h) as 'g > as 'f
+ Type 'c. 'e is not a subtype of 'a. 'g
+# Characters 88-150:
+ = struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig val f : (< m : 'a. 'a * ('a * 'b) > as 'b) -> unit end
+ is not included in
+ sig
+ val f : < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > -> unit
+ end
+ Values do not match:
+ val f : (< m : 'a. 'a * ('a * 'b) > as 'b) -> unit
+ is not included in
+ val f : < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > -> unit
+# Characters 78-132:
+ = struct type t = <m : 'a. 'a * ('a * 'foo)> as 'foo end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = < m : 'a. 'a * ('a * 'b) > as 'b end
+ is not included in
+ sig type t = < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > end
+ Type declarations do not match:
+ type t = < m : 'a. 'a * ('a * 'b) > as 'b
+ is not included in
+ type t = < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) >
+# module M : sig type 'a t type u = < m : 'a. 'a t > end
+# module M : sig type 'a t val f : < m : 'a. 'a t > -> int end
+# module M : sig type 'a t val f : < m : 'a. 'a t > -> int end
+# val f :
+ (< m : 'a. 'a -> (< m : 'a. 'a -> 'c * < > > as 'c) * < .. >; .. > as 'b) ->
+ 'b -> bool = <fun>
+# type t = [ `A | `B ]
+# type v = private [> t ]
+# - : t -> v = <fun>
+# type u = private [< t ]
+# - : u -> v = <fun>
+# Characters 9-21:
+ fun x -> (x : v :> u);;
+ ^^^^^^^^^^^^
+Error: Type v = [> `A | `B ] is not a subtype of u = [< `A | `B ]
+# type v = private [< t ]
+# Characters 9-21:
+ fun x -> (x : u :> v);;
+ ^^^^^^^^^^^^
+Error: Type u = [< `A | `B ] is not a subtype of v = [< `A | `B ]
+# type p = < x : p >
+# type q = private < x : p; .. >
+# - : q -> p = <fun>
+# Characters 9-21:
+ fun x -> (x : p :> q);;
+ ^^^^^^^^^^^^
+Error: Type p = < x : p > is not a subtype of q = < x : p; .. >
+# Characters 14-100:
+ ..(x : <m:'a. (<p:int;..> as 'a) -> int>
+ :> <m:'b. (<p:int;q:int;..> as 'b) -> int>)..
+Error: Type < m : 'a. (< p : int; .. > as 'a) -> int > is not a subtype of
+ < m : 'b. (< p : int; q : int; .. > as 'b) -> int >
+ Type < p : int; q : int; .. > as 'c is not a subtype of
+ < p : int; .. > as 'd
+# val f2 :
+ < m : 'a. (< p : < a : int >; .. > as 'a) -> int > ->
+ < m : 'b. (< p : < a : int; b : int >; .. > as 'b) -> int > = <fun>
+# Characters 13-107:
+ ..(x : <m:'a. (<p:<a:int;b:int>;..> as 'a) -> int>
+ :> <m:'b. (<p:<a:int>;..> as 'b) -> int>)..
+Error: Type < m : 'a. (< p : < a : int; b : int >; .. > as 'a) -> int >
+ is not a subtype of < m : 'b. (< p : < a : int >; .. > as 'b) -> int >
+ Type < a : int > is not a subtype of < a : int; b : int >
+# Characters 11-55:
+ let f4 x = (x : <p:<a:int;b:int>;..> :> <p:<a:int>;..>);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type < p : < a : int; b : int >; .. > is not a subtype of
+ < p : < a : int >; .. >
+ The second object type has no method b
+# val f5 :
+ < m : 'a. [< `A of < p : int > ] as 'a > ->
+ < m : 'b. [< `A of < > ] as 'b > = <fun>
+# Characters 13-83:
+ (x : <m:'a. [< `A of < > ] as 'a> :> <m:'a. [< `A of <p:int> ] as 'a>);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type < m : 'a. [< `A of < > ] as 'a > is not a subtype of
+ < m : 'b. [< `A of < p : int > ] as 'b >
+ Type < > is not a subtype of < p : int >
+# val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > = <fun>
+# Characters 9-16:
+ fun x -> (f x)#m;; (* Warning 18 *)
+ ^^^^^^^
+Warning 18: this use of a polymorphic method is not principal.
+- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
+# val f : < m : 'a. 'a -> 'a > * 'b -> < m : 'a. 'a -> 'a > = <fun>
+# Characters 9-20:
+ fun x -> (f (x,x))#m;; (* Warning 18 *)
+ ^^^^^^^^^^^
+Warning 18: this use of a polymorphic method is not principal.
+- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
+# val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > array = <fun>
+# Characters 9-20:
+ fun x -> (f x).(0)#m;; (* Warning 18 *)
+ ^^^^^^^^^^^
+Warning 18: this use of a polymorphic method is not principal.
+- : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
+# class c : object method id : 'a -> 'a end
+# type u = c option
+# val just : 'a option -> 'a = <fun>
+# Characters 42-62:
+ let f x = let l = [Some x; (None : u)] in (just(List.hd l))#id;;
+ ^^^^^^^^^^^^^^^^^^^^
+Warning 18: this use of a polymorphic method is not principal.
+val f : c -> 'a -> 'a = <fun>
+# Characters 101-112:
+ let x = List.hd [Some x; none] in (just x)#id;;
+ ^^^^^^^^^^^
+Warning 18: this use of a polymorphic method is not principal.
+val g : c -> 'a -> 'a = <fun>
+# val h : < id : 'a; .. > -> 'a = <fun>
+# type 'a u = c option
+# val just : 'a option -> 'a = <fun>
+# val f : c -> 'a -> 'a = <fun>
+# val f : 'a -> int = <fun>
+val g : 'a -> int = <fun>
+# type 'a t = Leaf of 'a | Node of ('a * 'a) t
+# val depth : 'a t -> int = <fun>
+# Characters 34-74:
+ function Leaf _ -> 1 | Node x -> 1 + d x
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This definition has type 'a t -> int which is less general than
+ 'a0. 'a0 t -> int
+# Characters 34-78:
+ function Leaf x -> x | Node x -> 1 + depth x;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This definition has type int t -> int which is less general than
+ 'a. 'a t -> int
+# Characters 34-74:
+ function Leaf x -> x | Node x -> depth x;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This definition has type 'a t -> 'a which is less general than
+ 'a0. 'a0 t -> 'a
+# Characters 38-78:
+ function Leaf x -> x | Node x -> depth x;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This definition has type 'b. 'b t -> 'b which is less general than
+ 'a 'b. 'a t -> 'b
+# val r : 'a list * '_b list ref = ([], {contents = []})
+val q : unit -> 'a list * '_b list ref = <fun>
+# val f : 'a -> 'a = <fun>
+# val zero : [> `B of 'a | `Int of int ] as 'a = `Int 0
+# Characters 39-45:
+ let zero : 'a. [< `Int of int] as 'a = `Int 0;; (* fails *)
+ ^^^^^^
+Error: This expression has type [> `Int of int ]
+ but an expression was expected of type [< `Int of int ]
+ Types for tag `Int are incompatible
+# type t = { f : 'a. [> `B of 'a | `Int of int ] as 'a; }
+val zero : t = {f = `Int 0}
+# Characters 56-62:
+ let zero = {f = `Int 0} ;; (* fails *)
+ ^^^^^^
+Error: This expression has type [> `Int of int ]
+ but an expression was expected of type [< `Int of int ]
+ Types for tag `Int are incompatible
+# val id : 'a -> 'a = <fun>
+val neg : int -> bool -> int * bool = <fun>
+# type t = A of int | B of (int * t) list | C of (string * t) list
+val transf : (int -> t) -> t -> t = <fun>
+val transf_alist : (int -> t) -> ('a * t) list -> ('a * t) list = <fun>
+# type t = { f : 'a. ('a list -> int) Lazy.t; }
+val l : t = {f = <lazy>}
+# type t = { f : 'a. 'a -> unit; }
+# - : t = {f = <fun>}
+# Characters 19-20:
+ let f ?x y = y in {f};; (* fail *)
+ ^
+Error: This field value has type unit -> unit which is less general than
+ 'a. 'a -> unit
+# module Polux :
+ sig
+ type 'par t = 'par
+ val ident : 'a -> 'a
+ class alias : object method alias : 'a t -> 'a end
+ val f : < m : 'a. 'a t > -> < m : 'a. 'a >
+ end
+# Exception: Pervasives.Exit.
+# Exception: Pervasives.Exit.
+# Exception: Pervasives.Exit.
+# Characters 16-44:
+ type 'x t = < f : 'y. 'y t >;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In the definition of t, type 'y t should be 'x t
+# val using_match : bool -> int * ('a -> 'a) = <fun>
+# - : ('a -> 'a) * ('b -> 'b) = (<fun>, <fun>)
+# - : ('a -> 'a) * ('b -> 'b) = (<fun>, <fun>)
+# val n : < m : 'x 'a. ([< `Foo of 'x ] as 'a) -> 'x > = <obj>
+# Characters 89-110:
+ object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
+ ^^^^^^^^^^^^^^^^^^^^^
+Error: This method has type ([< `Foo of 'b ] as 'a) -> 'b
+ which is less general than 'x. 'a -> 'x
+# Characters 104-125:
+ object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
+ ^^^^^^^^^^^^^^^^^^^^^
+Error: This method has type ([< `Foo of 'b ] as 'a) -> 'b
+ which is less general than 'x. 'a -> 'x
+# Characters 128-149:
+ object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
+ ^^^^^^^^^^^^^^^^^^^^^
+Error: This method has type ([< `Foo of 'b ] as 'a) -> 'b
+ which is less general than 'x. 'a -> 'x
+# Characters 94-97:
+ if b then x else M.A;;
+ ^^^
+Error: This expression has type M.t but an expression was expected of type 'x
+ The type constructor M.t would escape its scope
+#
diff --git a/testsuite/tests/typing-poly/poly.ml.reference b/testsuite/tests/typing-poly/poly.ml.reference
new file mode 100644
index 0000000000..637fefa70b
--- /dev/null
+++ b/testsuite/tests/typing-poly/poly.ml.reference
@@ -0,0 +1,629 @@
+
+# * * * # type 'a t = { t : 'a; }
+# type 'a fold = { fold : 'b. f:('b -> 'a -> 'b) -> init:'b -> 'b; }
+# val f : 'a list -> 'a fold = <fun>
+# - : int = 6
+# class ['b] ilist :
+ 'b list ->
+ object ('c)
+ val l : 'b list
+ method add : 'b -> 'c
+ method fold : f:('a -> 'b -> 'a) -> init:'a -> 'a
+ end
+# class virtual ['a] vlist :
+ object ('c)
+ method virtual add : 'a -> 'c
+ method virtual fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class ilist2 :
+ int list ->
+ object ('a)
+ val l : int list
+ method add : int -> 'a
+ method fold : f:('b -> int -> 'b) -> init:'b -> 'b
+ end
+# val ilist2 : 'a list -> 'a vlist = <fun>
+# class ['a] ilist3 :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method add : 'a -> 'c
+ method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class ['a] ilist4 :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method add : 'a -> 'c
+ method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class ['a] ilist5 :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method add : 'a -> 'c
+ method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ method fold2 : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class ['a] ilist6 :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method add : 'a -> 'c
+ method fold : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ method fold2 : f:('b -> 'a -> 'b) -> init:'b -> 'b
+ end
+# class virtual ['a] olist :
+ object method virtual fold : f:('a -> 'c -> 'c) -> init:'c -> 'c end
+# class ['a] onil :
+ object method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c end
+# class ['a] ocons :
+ hd:'a ->
+ tl:'a olist ->
+ object
+ val hd : 'a
+ val tl : 'a olist
+ method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
+ end
+# class ['a] ostream :
+ hd:'a ->
+ tl:'a ostream ->
+ object
+ val hd : 'a
+ val tl : < empty : bool; fold : 'c. f:('a -> 'c -> 'c) -> init:'c -> 'c >
+ method empty : bool
+ method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
+ end
+# class ['a] ostream1 :
+ hd:'a ->
+ tl:'b ->
+ object ('b)
+ val hd : 'a
+ val tl : 'b
+ method fold : f:('a -> 'c -> 'c) -> init:'c -> 'c
+ method hd : 'a
+ method tl : 'b
+ end
+# class vari : object method m : [< `A | `B | `C ] -> int end
+# class vari : object method m : [< `A | `B | `C ] -> int end
+# module V : sig type v = [ `A | `B | `C ] val m : [< v ] -> int end
+# class varj : object method m : [< V.v ] -> int end
+# module type T =
+ sig class vari : object method m : [< `A | `B | `C ] -> int end end
+# module M0 :
+ sig class vari : object method m : [< `A | `B | `C ] -> int end end
+# module M : T
+# val v : M.vari = <obj>
+# - : int = 1
+# class point :
+ x:int ->
+ y:int -> object val x : int val y : int method x : int method y : int end
+# class color_point :
+ x:int ->
+ y:int ->
+ color:string ->
+ object
+ val color : string
+ val x : int
+ val y : int
+ method color : string
+ method x : int
+ method y : int
+ end
+# class circle :
+ #point ->
+ r:int ->
+ object val p : point val r : int method distance : #point -> float end
+# val p0 : point = <obj>
+val p1 : point = <obj>
+val cp : color_point = <obj>
+val c : circle = <obj>
+val d : float = 11.
+# val f : < m : 'a. 'a -> 'a > -> < m : 'b. 'b -> 'b > = <fun>
+# Characters 41-42:
+ let f (x : < m : 'a. 'a -> 'a list >) = (x : < m : 'b. 'b -> 'c >)
+ ^
+Error: This expression has type < m : 'b. 'b -> 'b list >
+ but an expression was expected of type < m : 'b. 'b -> 'c >
+ The universal variable 'b would escape its scope
+# class id : object method id : 'a -> 'a end
+# class type id_spec = object method id : 'a -> 'a end
+# class id_impl : object method id : 'a -> 'a end
+# class a : object method m : bool end
+and b : object method id : 'a -> 'a end
+# Characters 72-77:
+ method id x = x
+ ^^^^^
+Error: This method has type 'a -> 'a which is less general than 'b. 'b -> 'a
+# Characters 75-80:
+ method id x = x
+ ^^^^^
+Error: This method has type 'a -> 'a which is less general than 'b. 'b -> 'a
+# Characters 80-85:
+ method id _ = x
+ ^^^^^
+Error: This method has type 'b -> 'b which is less general than 'a. 'a -> 'a
+# Characters 92-159:
+ ............x =
+ match r with
+ None -> r <- Some x; x
+ | Some y -> y
+Error: This method has type 'b -> 'b which is less general than 'a. 'a -> 'a
+# class c : object method m : 'a -> 'b -> 'a end
+# val f1 : id -> int * bool = <fun>
+# val f2 : id -> int * bool = <fun>
+# Characters 24-28:
+ let f3 f = f#id 1, f#id true
+ ^^^^
+Error: This expression has type bool but an expression was expected of type
+ int
+# val f4 : id -> int * bool = <fun>
+# class c : object method m : #id -> int * bool end
+# class id2 : object method id : 'a -> 'a method mono : int -> int end
+# val app : int * bool = (1, true)
+# Characters 0-25:
+ type 'a foo = 'a foo list
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: The type abbreviation foo is cyclic
+# class ['a] bar : 'a -> object end
+# type 'a foo = 'a foo bar
+# - : (< m : 'a. 'a * 'b > as 'b) -> 'c * 'b = <fun>
+# - : (< m : 'a. 'b * 'a list > as 'b) -> 'b * 'c list = <fun>
+# val f :
+ (< m : 'b. 'a * (< n : 'b; .. > as 'b) > as 'a) ->
+ 'a * (< n : 'c; .. > as 'c) = <fun>
+# - : (< p : 'b. < m : 'b; n : 'a; .. > as 'b > as 'a) ->
+ (< m : 'c; n : 'a; .. > as 'c)
+= <fun>
+# - : (< m : 'a. 'a * < p : 'b. 'b * 'd * 'c > as 'd > as 'c) ->
+ ('f * < p : 'b. 'b * 'e * 'c > as 'e)
+= <fun>
+# - : < m : 'a. < p : 'a; .. > as 'b > -> 'b = <fun>
+# type sum = T of < id : 'a. 'a -> 'a >
+# - : sum -> 'a -> 'a = <fun>
+# type record = { r : < id : 'a. 'a -> 'a >; }
+# - : record -> 'a -> 'a = <fun>
+# - : record -> 'a -> 'a = <fun>
+# class myself : object ('b) method self : 'a -> 'b end
+# class number :
+ object ('b)
+ val num : int
+ method num : int
+ method prev : 'b
+ method succ : 'b
+ method switch : zero:(unit -> 'a) -> prev:('b -> 'a) -> 'a
+ end
+# val id : 'a -> 'a = <fun>
+# class c : object method id : 'a -> 'a end
+# class c' : object method id : 'a -> 'a end
+# class d :
+ object
+ val mutable count : int
+ method count : int
+ method id : 'a -> 'a
+ method old : 'a -> 'a
+ end
+# class ['a] olist :
+ 'a list ->
+ object ('c)
+ val l : 'a list
+ method cons : 'a -> 'c
+ method fold : f:('a -> 'b -> 'b) -> init:'b -> 'b
+ end
+# val sum : int #olist -> int = <fun>
+# val count : 'a #olist -> int = <fun>
+# val append : 'a #olist -> ('a #olist as 'b) -> 'b = <fun>
+# type 'a t = unit
+# class o : object method x : [> `A ] t -> unit end
+# class c : object method m : d end
+and d : ?x:int -> unit -> object end
+# class d : ?x:int -> unit -> object end
+and c : object method m : d end
+# class type numeral = object method fold : ('a -> 'a) -> 'a -> 'a end
+class zero : object method fold : ('a -> 'a) -> 'a -> 'a end
+class next : #numeral -> object method fold : ('a -> 'a) -> 'a -> 'a end
+# class type node_type = object method as_variant : [> `Node of node_type ] end
+# class node : node_type
+# class node : object method as_variant : [> `Node of node_type ] end
+# type bad = { bad : 'a. 'a option ref; }
+# Characters 17-25:
+ let bad = {bad = ref None};;
+ ^^^^^^^^
+Error: This field value has type 'b option ref which is less general than
+ 'a. 'a option ref
+# type bad2 = { mutable bad2 : 'a. 'a option ref option; }
+# val bad2 : bad2 = {bad2 = None}
+# Characters 13-28:
+ bad2.bad2 <- Some (ref None);;
+ ^^^^^^^^^^^^^^^
+Error: This field value has type 'b option ref option
+ which is less general than 'a. 'a option ref option
+# val f : < m : 'a. < p : 'a * 'c > as 'c > -> 'b -> unit = <fun>
+# val f : < m : 'a. 'a * (< p : int * 'b > as 'b) > -> 'b -> unit = <fun>
+# type 'a t = [ `A of 'a ]
+# class c : object method m : ([> 'a t ] as 'a) -> unit end
+# class c : object method m : ([> 'a t ] as 'a) -> unit end
+# class c : object method m : ([> 'a t ] as 'a) -> 'a end
+# class c : object method m : ([> `A ] as 'a) option -> 'a end
+# Characters 145-166:
+ object method virtual visit : 'a.('a visitor -> 'a) end;;
+ ^^^^^^^^^^^^^^^^^^^^^
+Error: The universal type variable 'a cannot be generalized:
+ it escapes its scope.
+# type ('a, 'b) list_visitor = < caseCons : 'b -> 'b list -> 'a; caseNil : 'a >
+type 'b alist = < visit : 'a. ('a, 'b) list_visitor -> 'a >
+class type ct = object ('a) method fold : ('b -> 'a -> 'b) -> 'b -> 'b end
+type t = { f : 'a 'b. ('b -> (#ct as 'a) -> 'b) -> 'b; }
+# Characters 15-25:
+ type t = u and u = t;;
+ ^^^^^^^^^^
+Error: The type abbreviation t is cyclic
+# class ['a] a : object constraint 'a = [> `A of 'a a ] end
+type t = [ `A of t a ]
+# Characters 71-80:
+ type ('a,'b) t constraint 'a = 'b and ('a,'b) u = ('a,'b) t;;
+ ^^^^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type ('a, 'b) t should be an instance of ('c, 'c) t
+# type 'a t = 'a
+and u = int t
+# type 'a t constraint 'a = int
+# Characters 26-32:
+ type 'a u = 'a and 'a v = 'a u t;;
+ ^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type 'a u t should be an instance of int t
+# type 'a u = 'a constraint 'a = int
+and 'a v = 'a u t constraint 'a = int
+# type g = int
+# type 'a t = unit constraint 'a = g
+# Characters 26-32:
+ type 'a u = 'a and 'a v = 'a u t;;
+ ^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type 'a u t should be an instance of g t
+# type 'a u = 'a constraint 'a = g
+and 'a v = 'a u t constraint 'a = g
+# Characters 34-58:
+ type 'a u = < m : 'a v > and 'a v = 'a list u;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In the definition of v, type 'a list u should be 'a u
+# type 'a t = 'a
+type 'a u = A of 'a t
+# type 'a t = < a : 'a >
+# - : ('a t as 'a) -> 'a t = <fun>
+# type u = 'a t as 'a
+# type t = A | B
+# - : [> `A ] * t -> int = <fun>
+# - : [> `A ] * t -> int = <fun>
+# - : [> `A ] option * t -> int = <fun>
+# - : [> `A ] option * t -> int = <fun>
+# - : t * [< `A | `B ] -> int = <fun>
+# - : [< `A | `B ] * t -> int = <fun>
+# Characters 0-41:
+ function (`A|`B), _ -> 0 | _,(`A|`B) -> 1;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(`AnyExtraTag, `AnyExtraTag)
+- : [> `A | `B ] * [> `A | `B ] -> int = <fun>
+# Characters 0-29:
+ function `B,1 -> 1 | _,1 -> 2;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(_, 0)
+Characters 21-24:
+ function `B,1 -> 1 | _,1 -> 2;;
+ ^^^
+Warning 11: this match case is unused.
+- : [< `B ] * int -> int = <fun>
+# Characters 0-29:
+ function 1,`B -> 1 | 1,_ -> 2;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+(0, _)
+Characters 21-24:
+ function 1,`B -> 1 | 1,_ -> 2;;
+ ^^^
+Warning 11: this match case is unused.
+- : int * [< `B ] -> int = <fun>
+# Characters 64-135:
+ type ('a, 'b) a = 'a -> unit constraint 'a = [> `B of ('a, 'b) b as 'b]
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Constraints are not satisfied in this type.
+ Type
+ ([> `B of 'a ], 'a) b as 'a
+ should be an instance of
+ (('b, [> `A of 'b ] as 'c) a as 'b, 'c) b
+# * class type ['a, 'b] a =
+ object
+ constraint 'a = < as_a : ('a, 'b) a as 'c; b : 'b; .. >
+ constraint 'b = < a : 'a; as_b : ('a, 'b) b; .. >
+ method as_a : 'c
+ method b : 'b
+ end
+and ['a, 'b] b =
+ object
+ constraint 'a = < as_a : ('a, 'b) a; b : 'b; .. >
+ constraint 'b = < a : 'a; as_b : ('a, 'b) b; .. >
+ method a : 'a
+ method as_b : ('a, 'b) b
+ end
+class type ['a] ca =
+ object ('b)
+ constraint 'a = < a : 'b; as_b : ('b, 'a) b; .. >
+ method as_a : ('b, 'a) a
+ method b : 'a
+ end
+class type ['a] cb =
+ object ('b)
+ constraint 'a = < as_a : ('a, 'b) a; b : 'b; .. >
+ method a : 'a
+ method as_b : ('a, 'b) b
+ end
+type bt = 'a ca cb as 'a
+# class c : object method m : int end
+# val f : unit -> c = <fun>
+# val f : unit -> c = <fun>
+# Characters 11-60:
+ let f () = object method private n = 1 method m = {<>}#n end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 15: the following private methods were made public implicitly:
+ n.
+val f : unit -> < m : int; n : int > = <fun>
+# Characters 11-56:
+ let f () = object (self:c) method n = 1 method m = 2 end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This object is expected to have type c but actually has type
+ < m : int; n : 'a >
+ The first object type has no method n
+# Characters 11-69:
+ let f () = object (_:'s) constraint 's = < n : int > method m = 1 end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This object is expected to have type < n : int > but actually has type
+ < m : 'a >
+ The second object type has no method n
+# Characters 66-124:
+ object (self: 's) method x = 3 method private m = self end
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This object is expected to have type < x : int; .. >
+ but actually has type < x : int >
+ Self type cannot be unified with a closed object type
+# val o : < x : int > = <obj>
+# Characters 76-77:
+ (x : <m : 'a. 'a * (<m:'b. 'a * <m:'c. 'c * 'bar> > as 'bar) >);;
+ ^
+Error: This expression has type < m : 'a. 'a * < m : 'a * 'b > > as 'b
+ but an expression was expected of type
+ < m : 'a. 'a * (< m : 'a * < m : 'c. 'c * 'd > > as 'd) >
+ Types for method m are incompatible
+# Characters 176-177:
+ let f (x : foo') = (x : bar');;
+ ^
+Error: This expression has type foo' = < m : 'a. 'a * 'a foo >
+ but an expression was expected of type bar' = < m : 'a. 'a * 'a bar >
+ Type 'a foo = < m : 'a * 'a foo > is not compatible with type
+ 'a bar = < m : 'a * < m : 'c. 'c * 'a bar > >
+ Type 'a foo = < m : 'a * 'a foo > is not compatible with type
+ < m : 'c. 'c * 'a bar >
+ Types for method m are incompatible
+# Characters 67-68:
+ (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('c * 'bar)>)> as 'bar);;
+ ^
+Error: This expression has type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) >
+ but an expression was expected of type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * ('c * 'd) >) > as 'd
+ Types for method m are incompatible
+# Characters 66-67:
+ (x : <m : 'b. 'b * ('b * <m : 'c. 'c * ('b * 'bar)>)> as 'bar);;
+ ^
+Error: This expression has type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) >
+ but an expression was expected of type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * ('b * 'd) >) > as 'd
+ Types for method m are incompatible
+# Characters 51-52:
+ (x : <m : 'b. 'b * ('b * <m:'c. 'c * 'bar> as 'bar)>);;
+ ^
+Error: This expression has type < m : 'b. 'b * ('b * 'a) > as 'a
+ but an expression was expected of type
+ < m : 'b. 'b * ('b * < m : 'c. 'c * 'd > as 'd) >
+ Types for method m are incompatible
+# Characters 14-115:
+ ....(x : <m : 'a. 'a -> ('a * <m:'c. 'c -> 'bar> as 'bar)>
+ :> <m : 'a. 'a -> ('a * 'foo)> as 'foo)..
+Error: Type < m : 'a. 'a -> ('a * (< m : 'c. 'c -> 'b as 'e > as 'd) as 'b) >
+ is not a subtype of < m : 'a. 'a -> ('a * 'f as 'h) as 'g > as 'f
+ Type 'c. 'e is not a subtype of 'a. 'g
+# Characters 88-150:
+ = struct let f (x : <m : 'a. 'a * ('a * 'foo)> as 'foo) = () end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Signature mismatch:
+ ...
+ Values do not match:
+ val f : (< m : 'a. 'a * ('a * 'b) > as 'b) -> unit
+ is not included in
+ val f : < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > -> unit
+# Characters 78-132:
+ = struct type t = <m : 'a. 'a * ('a * 'foo)> as 'foo end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = < m : 'a. 'a * ('a * 'b) > as 'b end
+ is not included in
+ sig type t = < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) > end
+ Type declarations do not match:
+ type t = < m : 'a. 'a * ('a * 'b) > as 'b
+ is not included in
+ type t = < m : 'b. 'b * ('b * < m : 'c. 'c * 'a > as 'a) >
+# module M : sig type 'a t type u = < m : 'a. 'a t > end
+# module M : sig type 'a t val f : < m : 'a. 'a t > -> int end
+# module M : sig type 'a t val f : < m : 'a. 'a t > -> int end
+# val f :
+ (< m : 'a. 'a -> (< m : 'a. 'a -> 'c * < > > as 'c) * < .. >; .. > as 'b) ->
+ 'b -> bool = <fun>
+# type t = [ `A | `B ]
+# type v = private [> t ]
+# - : t -> v = <fun>
+# type u = private [< t ]
+# - : u -> v = <fun>
+# Characters 9-21:
+ fun x -> (x : v :> u);;
+ ^^^^^^^^^^^^
+Error: Type v = [> `A | `B ] is not a subtype of u = [< `A | `B ]
+# type v = private [< t ]
+# Characters 9-21:
+ fun x -> (x : u :> v);;
+ ^^^^^^^^^^^^
+Error: Type u = [< `A | `B ] is not a subtype of v = [< `A | `B ]
+# type p = < x : p >
+# type q = private < x : p; .. >
+# - : q -> p = <fun>
+# Characters 9-21:
+ fun x -> (x : p :> q);;
+ ^^^^^^^^^^^^
+Error: Type p = < x : p > is not a subtype of q = < x : p; .. >
+# Characters 14-100:
+ ..(x : <m:'a. (<p:int;..> as 'a) -> int>
+ :> <m:'b. (<p:int;q:int;..> as 'b) -> int>)..
+Error: Type < m : 'a. (< p : int; .. > as 'a) -> int > is not a subtype of
+ < m : 'b. (< p : int; q : int; .. > as 'b) -> int >
+ Type < p : int; q : int; .. > as 'c is not a subtype of
+ < p : int; .. > as 'd
+# val f2 :
+ < m : 'a. (< p : < a : int >; .. > as 'a) -> int > ->
+ < m : 'b. (< p : < a : int; b : int >; .. > as 'b) -> int > = <fun>
+# Characters 13-107:
+ ..(x : <m:'a. (<p:<a:int;b:int>;..> as 'a) -> int>
+ :> <m:'b. (<p:<a:int>;..> as 'b) -> int>)..
+Error: Type < m : 'a. (< p : < a : int; b : int >; .. > as 'a) -> int >
+ is not a subtype of < m : 'b. (< p : < a : int >; .. > as 'b) -> int >
+ Type < a : int > is not a subtype of < a : int; b : int >
+# Characters 11-55:
+ let f4 x = (x : <p:<a:int;b:int>;..> :> <p:<a:int>;..>);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type < p : < a : int; b : int >; .. > is not a subtype of
+ < p : < a : int >; .. >
+ The second object type has no method b
+# val f5 :
+ < m : 'a. [< `A of < p : int > ] as 'a > ->
+ < m : 'b. [< `A of < > ] as 'b > = <fun>
+# Characters 13-83:
+ (x : <m:'a. [< `A of < > ] as 'a> :> <m:'a. [< `A of <p:int> ] as 'a>);;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Type < m : 'a. [< `A of < > ] as 'a > is not a subtype of
+ < m : 'b. [< `A of < p : int > ] as 'b >
+ Type < > is not a subtype of < p : int >
+# val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > = <fun>
+# - : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
+# val f : < m : 'a. 'a -> 'a > * 'b -> < m : 'a. 'a -> 'a > = <fun>
+# - : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
+# val f : < m : 'a. 'a -> 'a > -> < m : 'a. 'a -> 'a > array = <fun>
+# - : < m : 'a. 'a -> 'a > -> 'b -> 'b = <fun>
+# class c : object method id : 'a -> 'a end
+# type u = c option
+# val just : 'a option -> 'a = <fun>
+# val f : c -> 'a -> 'a = <fun>
+# val g : c -> 'a -> 'a = <fun>
+# val h : < id : 'a; .. > -> 'a = <fun>
+# type 'a u = c option
+# val just : 'a option -> 'a = <fun>
+# val f : c -> 'a -> 'a = <fun>
+# val f : 'a -> int = <fun>
+val g : 'a -> int = <fun>
+# type 'a t = Leaf of 'a | Node of ('a * 'a) t
+# val depth : 'a t -> int = <fun>
+# Characters 34-74:
+ function Leaf _ -> 1 | Node x -> 1 + d x
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This definition has type 'a t -> int which is less general than
+ 'a0. 'a0 t -> int
+# Characters 34-78:
+ function Leaf x -> x | Node x -> 1 + depth x;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This definition has type int t -> int which is less general than
+ 'a. 'a t -> int
+# Characters 34-74:
+ function Leaf x -> x | Node x -> depth x;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This definition has type 'a t -> 'a which is less general than
+ 'a0. 'a0 t -> 'a
+# Characters 38-78:
+ function Leaf x -> x | Node x -> depth x;; (* fails *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This definition has type 'b. 'b t -> 'b which is less general than
+ 'a 'b. 'a t -> 'b
+# val r : 'a list * '_b list ref = ([], {contents = []})
+val q : unit -> 'a list * '_b list ref = <fun>
+# val f : 'a -> 'a = <fun>
+# val zero : [> `B of 'a | `Int of int ] as 'a = `Int 0
+# Characters 39-45:
+ let zero : 'a. [< `Int of int] as 'a = `Int 0;; (* fails *)
+ ^^^^^^
+Error: This expression has type [> `Int of int ]
+ but an expression was expected of type [< `Int of int ]
+ Types for tag `Int are incompatible
+# type t = { f : 'a. [> `B of 'a | `Int of int ] as 'a; }
+val zero : t = {f = `Int 0}
+# Characters 56-62:
+ let zero = {f = `Int 0} ;; (* fails *)
+ ^^^^^^
+Error: This expression has type [> `Int of int ]
+ but an expression was expected of type [< `Int of int ]
+ Types for tag `Int are incompatible
+# val id : 'a -> 'a = <fun>
+val neg : int -> bool -> int * bool = <fun>
+# type t = A of int | B of (int * t) list | C of (string * t) list
+val transf : (int -> t) -> t -> t = <fun>
+val transf_alist : (int -> t) -> ('a * t) list -> ('a * t) list = <fun>
+# type t = { f : 'a. ('a list -> int) Lazy.t; }
+val l : t = {f = <lazy>}
+# type t = { f : 'a. 'a -> unit; }
+# - : t = {f = <fun>}
+# Characters 19-20:
+ let f ?x y = y in {f};; (* fail *)
+ ^
+Error: This field value has type unit -> unit which is less general than
+ 'a. 'a -> unit
+# module Polux :
+ sig
+ type 'par t = 'par
+ val ident : 'a -> 'a
+ class alias : object method alias : 'a t -> 'a end
+ val f : < m : 'a. 'a t > -> < m : 'a. 'a >
+ end
+# Exception: Pervasives.Exit.
+# Exception: Pervasives.Exit.
+# Exception: Pervasives.Exit.
+# Characters 16-44:
+ type 'x t = < f : 'y. 'y t >;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: In the definition of t, type 'y t should be 'x t
+# val using_match : bool -> int * ('a -> 'a) = <fun>
+# - : ('a -> 'a) * ('b -> 'b) = (<fun>, <fun>)
+# - : ('a -> 'a) * ('b -> 'b) = (<fun>, <fun>)
+# val n : < m : 'x 'a. ([< `Foo of 'x ] as 'a) -> 'x > = <obj>
+# val n : < m : 'x. [< `Foo of 'x ] -> 'x > = <obj>
+# Characters 59-129:
+ object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This expression has type < m : 'x. [< `Foo of 'x ] -> 'x >
+ but an expression was expected of type
+ < m : 'a. [< `Foo of int ] -> 'a >
+ The universal variable 'x would escape its scope
+# Characters 83-153:
+ object method m : 'x. [< `Foo of 'x] -> 'x = fun x -> assert false end;;
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: This expression has type < m : 'x. [< `Foo of 'x ] -> 'x >
+ but an expression was expected of type
+ < m : 'a. [< `Foo of int ] -> 'a >
+ The universal variable 'x would escape its scope
+# Characters 94-97:
+ if b then x else M.A;;
+ ^^^
+Error: This expression has type M.t but an expression was expected of type 'x
+ The type constructor M.t would escape its scope
+#
diff --git a/testsuite/tests/typing-polyvariants-bugs-2/Makefile b/testsuite/tests/typing-polyvariants-bugs-2/Makefile
new file mode 100644
index 0000000000..4cf35f3ccd
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs-2/Makefile
@@ -0,0 +1,23 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+default:
+ @printf " ... testing 'pr3918':"
+ @($(OCAMLC) -c pr3918a.mli \
+ && $(OCAMLC) -c pr3918b.mli \
+ && $(OCAMLC) -c pr3918c.ml \
+ && echo " => passed") || echo " => failed"
+
+clean: defaultclean
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-polyvariants-bugs-2/pr3918a.mli b/testsuite/tests/typing-polyvariants-bugs-2/pr3918a.mli
new file mode 100644
index 0000000000..b0afbbe579
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs-2/pr3918a.mli
@@ -0,0 +1 @@
+type 'a voption = [ `None | `Some of 'a]
diff --git a/testsuite/tests/typing-polyvariants-bugs-2/pr3918b.mli b/testsuite/tests/typing-polyvariants-bugs-2/pr3918b.mli
new file mode 100644
index 0000000000..3513ff9c26
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs-2/pr3918b.mli
@@ -0,0 +1 @@
+type 'a vlist = ('a * 'b) Pr3918a.voption as 'b
diff --git a/testsuite/tests/typing-polyvariants-bugs-2/pr3918c.ml b/testsuite/tests/typing-polyvariants-bugs-2/pr3918c.ml
new file mode 100644
index 0000000000..c49ed6e070
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs-2/pr3918c.ml
@@ -0,0 +1,10 @@
+(*
+ ocamlc -c pr3918a.mli pr3918b.mli
+ rm -f pr3918a.cmi
+ ocamlc -c pr3918c.ml
+*)
+
+open Pr3918b
+
+let f x = (x : 'a vlist :> 'b vlist)
+let f (x : 'a vlist) = (x : 'b vlist)
diff --git a/testsuite/tests/typing-polyvariants-bugs/Makefile b/testsuite/tests/typing-polyvariants-bugs/Makefile
new file mode 100644
index 0000000000..1103dbffda
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.okbad
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-polyvariants-bugs/pr4775_ok.ml b/testsuite/tests/typing-polyvariants-bugs/pr4775_ok.ml
new file mode 100644
index 0000000000..ef857149ee
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs/pr4775_ok.ml
@@ -0,0 +1,11 @@
+module type Poly = sig
+ type 'a t = 'a constraint 'a = [> ]
+end
+
+module Combine (A : Poly) (B : Poly) = struct
+ type ('a, 'b) t = 'a A.t constraint 'a = 'b B.t
+end
+
+module C = Combine
+ (struct type 'a t = 'a constraint 'a = [> ] end)
+ (struct type 'a t = 'a constraint 'a = [> ] end)
diff --git a/testsuite/tests/typing-polyvariants-bugs/pr4933_ok.ml b/testsuite/tests/typing-polyvariants-bugs/pr4933_ok.ml
new file mode 100644
index 0000000000..b486290c50
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs/pr4933_ok.ml
@@ -0,0 +1,15 @@
+module type Priv = sig
+ type t = private int
+end
+
+module Make (Unit:sig end): Priv = struct type t = int end
+
+module A = Make (struct end)
+
+module type Priv' = sig
+ type t = private [> `A]
+end
+
+module Make' (Unit:sig end): Priv' = struct type t = [`A] end
+
+module A' = Make' (struct end)
diff --git a/testsuite/tests/typing-polyvariants-bugs/pr5057_ok.ml b/testsuite/tests/typing-polyvariants-bugs/pr5057_ok.ml
new file mode 100644
index 0000000000..86cb665ad4
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs/pr5057_ok.ml
@@ -0,0 +1,14 @@
+(* PR5057 *)
+
+module TT = struct
+ module IntSet = Set.Make(struct type t = int let compare = compare end)
+end
+
+let () =
+ let f flag =
+ let module T = TT in
+ let _ = match flag with `A -> 0 | `B r -> r in
+ let _ = match flag with `A -> T.IntSet.mem | `B r -> r in
+ ()
+ in
+ f `A
diff --git a/testsuite/tests/typing-polyvariants-bugs/pr5057a_bad.ml b/testsuite/tests/typing-polyvariants-bugs/pr5057a_bad.ml
new file mode 100644
index 0000000000..15bb776b7f
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs/pr5057a_bad.ml
@@ -0,0 +1,7 @@
+(* This one should fail *)
+
+let f flag =
+ let module T = Set.Make(struct type t = int let compare = compare end) in
+ let _ = match flag with `A -> 0 | `B r -> r in
+ let _ = match flag with `A -> T.mem | `B r -> r in
+ ()
diff --git a/testsuite/tests/typing-polyvariants-bugs/privrowsabate_ok.ml b/testsuite/tests/typing-polyvariants-bugs/privrowsabate_ok.ml
new file mode 100644
index 0000000000..4e31243bce
--- /dev/null
+++ b/testsuite/tests/typing-polyvariants-bugs/privrowsabate_ok.ml
@@ -0,0 +1,53 @@
+type 'a termpc =
+ [`And of 'a * 'a
+ |`Or of 'a * 'a
+ |`Not of 'a
+ |`Atom of string
+ ]
+
+type 'a termk =
+ [`Dia of 'a
+ |`Box of 'a
+ |'a termpc
+ ]
+
+module type T = sig
+ type term
+ val map : (term -> term) -> term -> term
+ val nnf : term -> term
+ val nnf_not : term -> term
+end
+
+module Fpc(X : T with type term = private [> 'a termpc] as 'a) =
+ struct
+ type term = X.term termpc
+ let nnf = function
+ |`Not(`Atom _) as x -> x
+ |`Not x -> X.nnf_not x
+ | x -> X.map X.nnf x
+ let map f : term -> X.term = function
+ |`Not x -> `Not (f x)
+ |`And(x,y) -> `And (f x, f y)
+ |`Or (x,y) -> `Or (f x, f y)
+ |`Atom _ as x -> x
+ let nnf_not : term -> _ = function
+ |`Not x -> X.nnf x
+ |`And(x,y) -> `Or (X.nnf_not x, X.nnf_not y)
+ |`Or (x,y) -> `And (X.nnf_not x, X.nnf_not y)
+ |`Atom _ as x -> `Not x
+ end
+
+module Fk(X : T with type term = private [> 'a termk] as 'a) =
+ struct
+ type term = X.term termk
+ module Pc = Fpc(X)
+ let map f : term -> _ = function
+ |`Dia x -> `Dia (f x)
+ |`Box x -> `Box (f x)
+ |#termpc as x -> Pc.map f x
+ let nnf = Pc.nnf
+ let nnf_not : term -> _ = function
+ |`Dia x -> `Box (X.nnf_not x)
+ |`Box x -> `Dia (X.nnf_not x)
+ |#termpc as x -> Pc.nnf_not x
+ end
diff --git a/testsuite/tests/typing-private-bugs/Makefile b/testsuite/tests/typing-private-bugs/Makefile
new file mode 100644
index 0000000000..1103dbffda
--- /dev/null
+++ b/testsuite/tests/typing-private-bugs/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.okbad
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-private-bugs/pr5026_bad.ml b/testsuite/tests/typing-private-bugs/pr5026_bad.ml
new file mode 100644
index 0000000000..10699952b2
--- /dev/null
+++ b/testsuite/tests/typing-private-bugs/pr5026_bad.ml
@@ -0,0 +1,11 @@
+type untyped;;
+type -'a typed = private untyped;;
+type -'typing wrapped = private sexp
+and +'a t = 'a typed wrapped
+and sexp = private untyped wrapped;;
+class type ['a] s3 = object
+ val underlying : 'a t
+end;;
+class ['a] s3object r : ['a] s3 = object
+ val underlying = r
+end;;
diff --git a/testsuite/tests/typing-private-bugs/pr5469_ok.ml b/testsuite/tests/typing-private-bugs/pr5469_ok.ml
new file mode 100644
index 0000000000..74d355499c
--- /dev/null
+++ b/testsuite/tests/typing-private-bugs/pr5469_ok.ml
@@ -0,0 +1,7 @@
+module M (T:sig type t end)
+ = struct type t = private { t : T.t } end
+module P
+ = struct
+ module T = struct type t end
+ module R = M(T)
+ end
diff --git a/testsuite/tests/typing-private/Makefile b/testsuite/tests/typing-private/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-private/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-private/private.ml b/testsuite/tests/typing-private/private.ml
new file mode 100644
index 0000000000..bab86eb845
--- /dev/null
+++ b/testsuite/tests/typing-private/private.ml
@@ -0,0 +1,113 @@
+module Foobar : sig
+ type t = private int
+end = struct
+ type t = int
+end;;
+
+module F0 : sig type t = private int end = Foobar;;
+
+let f (x : F0.t) = (x : Foobar.t);; (* fails *)
+
+module F = Foobar;;
+
+let f (x : F.t) = (x : Foobar.t);;
+
+module M = struct type t = <m:int> end;;
+module M1 : sig type t = private <m:int; ..> end = M;;
+module M2 : sig type t = private <m:int; ..> end = M1;;
+fun (x : M1.t) -> (x : M2.t);; (* fails *)
+
+module M3 : sig type t = private M1.t end = M1;;
+fun x -> (x : M3.t :> M1.t);;
+fun x -> (x : M3.t :> M.t);;
+module M4 : sig type t = private M3.t end = M2;; (* fails *)
+module M4 : sig type t = private M3.t end = M;; (* fails *)
+module M4 : sig type t = private M3.t end = M1;; (* might be ok *)
+module M5 : sig type t = private M1.t end = M3;;
+module M6 : sig type t = private < n:int; .. > end = M1;; (* fails *)
+
+module Bar : sig type t = private Foobar.t val f : int -> t end =
+ struct type t = int let f (x : int) = (x : t) end;; (* must fail *)
+
+module M : sig
+ type t = private T of int
+ val mk : int -> t
+end = struct
+ type t = T of int
+ let mk x = T(x)
+end;;
+
+module M1 : sig
+ type t = M.t
+ val mk : int -> t
+end = struct
+ type t = M.t
+ let mk = M.mk
+end;;
+
+module M2 : sig
+ type t = M.t
+ val mk : int -> t
+end = struct
+ include M
+end;;
+
+module M3 : sig
+ type t = M.t
+ val mk : int -> t
+end = M;;
+
+module M4 : sig
+ type t = M.t = T of int
+ val mk : int -> t
+ end = M;;
+(* Error: The variant or record definition does not match that of type M.t *)
+
+module M5 : sig
+ type t = M.t = private T of int
+ val mk : int -> t
+end = M;;
+
+module M6 : sig
+ type t = private T of int
+ val mk : int -> t
+end = M;;
+
+module M' : sig
+ type t_priv = private T of int
+ type t = t_priv
+ val mk : int -> t
+end = struct
+ type t_priv = T of int
+ type t = t_priv
+ let mk x = T(x)
+end;;
+
+module M3' : sig
+ type t = M'.t
+ val mk : int -> t
+end = M';;
+
+module M : sig type 'a t = private T of 'a end =
+ struct type 'a t = T of 'a end;;
+
+module M1 : sig type 'a t = 'a M.t = private T of 'a end =
+ struct type 'a t = 'a M.t = private T of 'a end;;
+
+(* PR#6090 *)
+module Test = struct type t = private A end
+module Test2 : module type of Test with type t = Test.t = Test;;
+let f (x : Test.t) = (x : Test2.t);;
+let f Test2.A = ();;
+let a = Test2.A;; (* fail *)
+(* The following should fail from a semantical point of view,
+ but allow it for backward compatibility *)
+module Test2 : module type of Test with type t = private Test.t = Test;;
+
+(* PR#6331 *)
+type t = private < x : int; .. > as 'a;;
+type t = private (< x : int; .. > as 'a) as 'a;;
+type t = private < x : int > as 'a;;
+type t = private (< x : int > as 'a) as 'b;;
+type 'a t = private < x : int; .. > as 'a;;
+type 'a t = private 'a constraint 'a = < x : int; .. >;;
diff --git a/testsuite/tests/typing-private/private.ml.principal.reference b/testsuite/tests/typing-private/private.ml.principal.reference
new file mode 100644
index 0000000000..db933583f5
--- /dev/null
+++ b/testsuite/tests/typing-private/private.ml.principal.reference
@@ -0,0 +1,125 @@
+
+# module Foobar : sig type t = private int end
+# module F0 : sig type t = private int end
+# Characters 21-22:
+ let f (x : F0.t) = (x : Foobar.t);; (* fails *)
+ ^
+Error: This expression has type F0.t but an expression was expected of type
+ Foobar.t
+# module F = Foobar
+# val f : F.t -> Foobar.t = <fun>
+# module M : sig type t = < m : int > end
+# module M1 : sig type t = private < m : int; .. > end
+# module M2 : sig type t = private < m : int; .. > end
+# Characters 19-20:
+ fun (x : M1.t) -> (x : M2.t);; (* fails *)
+ ^
+Error: This expression has type M1.t but an expression was expected of type
+ M2.t
+# module M3 : sig type t = private M1.t end
+# - : M3.t -> M1.t = <fun>
+# - : M3.t -> M.t = <fun>
+# Characters 44-46:
+ module M4 : sig type t = private M3.t end = M2;; (* fails *)
+ ^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = M2.t end
+ is not included in
+ sig type t = private M3.t end
+ Type declarations do not match:
+ type t = M2.t
+ is not included in
+ type t = private M3.t
+# Characters 44-45:
+ module M4 : sig type t = private M3.t end = M;; (* fails *)
+ ^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = < m : int > end
+ is not included in
+ sig type t = private M3.t end
+ Type declarations do not match:
+ type t = < m : int >
+ is not included in
+ type t = private M3.t
+# Characters 44-46:
+ module M4 : sig type t = private M3.t end = M1;; (* might be ok *)
+ ^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = M1.t end
+ is not included in
+ sig type t = private M3.t end
+ Type declarations do not match:
+ type t = M1.t
+ is not included in
+ type t = private M3.t
+# module M5 : sig type t = private M1.t end
+# Characters 53-55:
+ module M6 : sig type t = private < n:int; .. > end = M1;; (* fails *)
+ ^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = M1.t end
+ is not included in
+ sig type t = private < n : int; .. > end
+ Type declarations do not match:
+ type t = M1.t
+ is not included in
+ type t = private < n : int; .. >
+# Characters 69-118:
+ struct type t = int let f (x : int) = (x : t) end;; (* must fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = int val f : int -> t end
+ is not included in
+ sig type t = private Foobar.t val f : int -> t end
+ Type declarations do not match:
+ type t = int
+ is not included in
+ type t = private Foobar.t
+# module M : sig type t = private T of int val mk : int -> t end
+# module M1 : sig type t = M.t val mk : int -> t end
+# module M2 : sig type t = M.t val mk : int -> t end
+# module M3 : sig type t = M.t val mk : int -> t end
+# Characters 21-44:
+ type t = M.t = T of int
+ ^^^^^^^^^^^^^^^^^^^^^^^
+Error: This variant or record definition does not match that of type M.t
+ A private type would be revealed.
+# module M5 : sig type t = M.t = private T of int val mk : int -> t end
+# module M6 : sig type t = private T of int val mk : int -> t end
+# module M' :
+ sig type t_priv = private T of int type t = t_priv val mk : int -> t end
+# module M3' : sig type t = M'.t val mk : int -> t end
+# module M : sig type 'a t = private T of 'a end
+# module M1 : sig type 'a t = 'a M.t = private T of 'a end
+# module Test : sig type t = private A end
+module Test2 : sig type t = Test.t = private A end
+# val f : Test.t -> Test2.t = <fun>
+# val f : Test2.t -> unit = <fun>
+# Characters 8-15:
+ let a = Test2.A;; (* fail *)
+ ^^^^^^^
+Error: Cannot create values of the private type Test2.t
+# * Characters 148-171:
+ module Test2 : module type of Test with type t = private Test.t = Test;;
+ ^^^^^^^^^^^^^^^^^^^^^^^
+Warning 3: deprecated: spurious use of private
+module Test2 : sig type t = Test.t = private A end
+# type t = private < x : int; .. >
+# type t = private < x : int; .. >
+# type t = private < x : int >
+# type t = private < x : int >
+# Characters -1--1:
+ type 'a t = private < x : int; .. > as 'a;;
+
+Error: Type declarations do not match:
+ type 'a t = private 'a constraint 'a = < x : int; .. >
+ is not included in
+ type 'a t
+ Their constraints differ.
+# type 'a t = private 'a constraint 'a = < x : int; .. >
+#
diff --git a/testsuite/tests/typing-private/private.ml.reference b/testsuite/tests/typing-private/private.ml.reference
new file mode 100644
index 0000000000..341bc93686
--- /dev/null
+++ b/testsuite/tests/typing-private/private.ml.reference
@@ -0,0 +1,125 @@
+
+# module Foobar : sig type t = private int end
+# module F0 : sig type t = private int end
+# Characters 21-22:
+ let f (x : F0.t) = (x : Foobar.t);; (* fails *)
+ ^
+Error: This expression has type F0.t but an expression was expected of type
+ Foobar.t
+# module F = Foobar
+# val f : F.t -> Foobar.t = <fun>
+# module M : sig type t = < m : int > end
+# module M1 : sig type t = private < m : int; .. > end
+# module M2 : sig type t = private < m : int; .. > end
+# Characters 19-20:
+ fun (x : M1.t) -> (x : M2.t);; (* fails *)
+ ^
+Error: This expression has type M1.t but an expression was expected of type
+ M2.t
+# module M3 : sig type t = private M1.t end
+# - : M3.t -> M1.t = <fun>
+# - : M3.t -> M.t = <fun>
+# Characters 44-46:
+ module M4 : sig type t = private M3.t end = M2;; (* fails *)
+ ^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = M2.t end
+ is not included in
+ sig type t = private M3.t end
+ Type declarations do not match:
+ type t = M2.t
+ is not included in
+ type t = private M3.t
+# Characters 44-45:
+ module M4 : sig type t = private M3.t end = M;; (* fails *)
+ ^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = < m : int > end
+ is not included in
+ sig type t = private M3.t end
+ Type declarations do not match:
+ type t = < m : int >
+ is not included in
+ type t = private M3.t
+# Characters 44-46:
+ module M4 : sig type t = private M3.t end = M1;; (* might be ok *)
+ ^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = M1.t end
+ is not included in
+ sig type t = private M3.t end
+ Type declarations do not match:
+ type t = M1.t
+ is not included in
+ type t = private M3.t
+# module M5 : sig type t = private M1.t end
+# Characters 53-55:
+ module M6 : sig type t = private < n:int; .. > end = M1;; (* fails *)
+ ^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = M1.t end
+ is not included in
+ sig type t = private < n : int; .. > end
+ Type declarations do not match:
+ type t = M1.t
+ is not included in
+ type t = private < n : int; .. >
+# Characters 69-118:
+ struct type t = int let f (x : int) = (x : t) end;; (* must fail *)
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Signature mismatch:
+ Modules do not match:
+ sig type t = int val f : int -> t end
+ is not included in
+ sig type t = private Foobar.t val f : int -> t end
+ Type declarations do not match:
+ type t = int
+ is not included in
+ type t = private Foobar.t
+# module M : sig type t = private T of int val mk : int -> t end
+# module M1 : sig type t = M.t val mk : int -> t end
+# module M2 : sig type t = M.t val mk : int -> t end
+# module M3 : sig type t = M.t val mk : int -> t end
+# Characters 21-44:
+ type t = M.t = T of int
+ ^^^^^^^^^^^^^^^^^^^^^^^
+Error: This variant or record definition does not match that of type M.t
+ A private type would be revealed.
+# module M5 : sig type t = M.t = private T of int val mk : int -> t end
+# module M6 : sig type t = private T of int val mk : int -> t end
+# module M' :
+ sig type t_priv = private T of int type t = t_priv val mk : int -> t end
+# module M3' : sig type t = M'.t val mk : int -> t end
+# module M : sig type 'a t = private T of 'a end
+# module M1 : sig type 'a t = 'a M.t = private T of 'a end
+# module Test : sig type t = private A end
+module Test2 : sig type t = Test.t = private A end
+# val f : Test.t -> Test2.t = <fun>
+# val f : Test2.t -> unit = <fun>
+# Characters 8-15:
+ let a = Test2.A;; (* fail *)
+ ^^^^^^^
+Error: Cannot create values of the private type Test2.t
+# * Characters 148-171:
+ module Test2 : module type of Test with type t = private Test.t = Test;;
+ ^^^^^^^^^^^^^^^^^^^^^^^
+Warning 3: deprecated: spurious use of private
+module Test2 : sig type t = Test.t = private A end
+# type t = private < x : int; .. >
+# type t = private < x : int; .. >
+# type t = private < x : int >
+# type t = private < x : int >
+# Characters -1--1:
+ type 'a t = private < x : int; .. > as 'a;;
+
+Error: Type declarations do not match:
+ type 'a t = private < x : int; .. > constraint 'a = 'a t
+ is not included in
+ type 'a t
+ Their constraints differ.
+# type 'a t = private 'a constraint 'a = < x : int; .. >
+#
diff --git a/testsuite/tests/typing-recmod/Makefile b/testsuite/tests/typing-recmod/Makefile
new file mode 100644
index 0000000000..1103dbffda
--- /dev/null
+++ b/testsuite/tests/typing-recmod/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.okbad
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-recmod/t01bad.ml b/testsuite/tests/typing-recmod/t01bad.ml
new file mode 100644
index 0000000000..8a471e074a
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t01bad.ml
@@ -0,0 +1,2 @@
+(* Bad (t = t) *)
+module rec A : sig type t = A.t end = struct type t = A.t end;;
diff --git a/testsuite/tests/typing-recmod/t02bad.ml b/testsuite/tests/typing-recmod/t02bad.ml
new file mode 100644
index 0000000000..b4301a417e
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t02bad.ml
@@ -0,0 +1,3 @@
+(* Bad (t = t) *)
+module rec A : sig type t = B.t end = struct type t = B.t end
+ and B : sig type t = A.t end = struct type t = A.t end;;
diff --git a/testsuite/tests/typing-recmod/t03ok.ml b/testsuite/tests/typing-recmod/t03ok.ml
new file mode 100644
index 0000000000..577ea20adf
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t03ok.ml
@@ -0,0 +1,3 @@
+(* OK (t = int) *)
+module rec A : sig type t = B.t end = struct type t = B.t end
+ and B : sig type t = int end = struct type t = int end;;
diff --git a/testsuite/tests/typing-recmod/t04bad.ml b/testsuite/tests/typing-recmod/t04bad.ml
new file mode 100644
index 0000000000..ad3f985aa1
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t04bad.ml
@@ -0,0 +1,2 @@
+(* Bad (t = int * t) *)
+module rec A : sig type t = int * A.t end = struct type t = int * A.t end;;
diff --git a/testsuite/tests/typing-recmod/t05bad.ml b/testsuite/tests/typing-recmod/t05bad.ml
new file mode 100644
index 0000000000..08fe60f07f
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t05bad.ml
@@ -0,0 +1,3 @@
+(* Bad (t = t -> int) *)
+module rec A : sig type t = B.t -> int end = struct type t = B.t -> int end
+ and B : sig type t = A.t end = struct type t = A.t end;;
diff --git a/testsuite/tests/typing-recmod/t06ok.ml b/testsuite/tests/typing-recmod/t06ok.ml
new file mode 100644
index 0000000000..a220a8e04b
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t06ok.ml
@@ -0,0 +1,3 @@
+(* OK (t = <m:t>) *)
+module rec A : sig type t = <m:B.t> end = struct type t = <m:B.t> end
+ and B : sig type t = A.t end = struct type t = A.t end;;
diff --git a/testsuite/tests/typing-recmod/t07bad.ml b/testsuite/tests/typing-recmod/t07bad.ml
new file mode 100644
index 0000000000..ec24ea4d3b
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t07bad.ml
@@ -0,0 +1,3 @@
+(* Bad (not regular) *)
+module rec A : sig type 'a t = <m: 'a list A.t> end
+ = struct type 'a t = <m: 'a list A.t> end;;
diff --git a/testsuite/tests/typing-recmod/t08bad.ml b/testsuite/tests/typing-recmod/t08bad.ml
new file mode 100644
index 0000000000..5ebafd11ab
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t08bad.ml
@@ -0,0 +1,4 @@
+(* Bad (not regular) *)
+module rec A : sig type 'a t = <m: 'a list B.t; n: 'a array B.t> end
+ = struct type 'a t = <m: 'a list B.t; n: 'a array B.t> end
+ and B : sig type 'a t = 'a A.t end = struct type 'a t = 'a A.t end;;
diff --git a/testsuite/tests/typing-recmod/t09bad.ml b/testsuite/tests/typing-recmod/t09bad.ml
new file mode 100644
index 0000000000..ade5bcb753
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t09bad.ml
@@ -0,0 +1,5 @@
+(* Bad (not regular) *)
+module rec A : sig type 'a t = 'a B.t end
+ = struct type 'a t = 'a B.t end
+ and B : sig type 'a t = <m: 'a list A.t; n: 'a array A.t> end
+ = struct type 'a t = <m: 'a list A.t; n: 'a array A.t> end;;
diff --git a/testsuite/tests/typing-recmod/t10ok.ml b/testsuite/tests/typing-recmod/t10ok.ml
new file mode 100644
index 0000000000..3094a42a9f
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t10ok.ml
@@ -0,0 +1,5 @@
+(* OK *)
+module rec A : sig type 'a t = 'a array B.t * 'a list B.t end
+ = struct type 'a t = 'a array B.t * 'a list B.t end
+ and B : sig type 'a t = <m: 'a B.t> end
+ = struct type 'a t = <m: 'a B.t> end;;
diff --git a/testsuite/tests/typing-recmod/t11bad.ml b/testsuite/tests/typing-recmod/t11bad.ml
new file mode 100644
index 0000000000..e18339acd4
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t11bad.ml
@@ -0,0 +1,5 @@
+(* Bad (not regular) *)
+module rec A : sig type 'a t = 'a list B.t end
+ = struct type 'a t = 'a list B.t end
+ and B : sig type 'a t = <m: 'a array B.t> end
+ = struct type 'a t = <m: 'a array B.t> end;;
diff --git a/testsuite/tests/typing-recmod/t12bad.ml b/testsuite/tests/typing-recmod/t12bad.ml
new file mode 100644
index 0000000000..71100e6e19
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t12bad.ml
@@ -0,0 +1,13 @@
+(* Bad (not regular) *)
+module rec M :
+ sig
+ class ['a] c : 'a -> object
+ method map : ('a -> 'b) -> 'b M.c
+ end
+ end
+ = struct
+ class ['a] c (x : 'a) = object
+ method map : 'b. ('a -> 'b) -> 'b M.c
+ = fun f -> new M.c (f x)
+ end
+ end;;
diff --git a/testsuite/tests/typing-recmod/t13ok.ml b/testsuite/tests/typing-recmod/t13ok.ml
new file mode 100644
index 0000000000..4fea6e1faf
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t13ok.ml
@@ -0,0 +1,5 @@
+(* OK *)
+class type [ 'node ] extension = object method node : 'node end
+class type [ 'ext ] node = object constraint 'ext = 'ext node #extension end
+class x = object method node : x node = assert false end
+type t = x node;;
diff --git a/testsuite/tests/typing-recmod/t14bad.ml b/testsuite/tests/typing-recmod/t14bad.ml
new file mode 100644
index 0000000000..1b92a28c5c
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t14bad.ml
@@ -0,0 +1,17 @@
+(* Bad - PR 4261 *)
+
+module PR_4261 = struct
+ module type S =
+ sig
+ type t
+ end
+
+ module type T =
+ sig
+ module D : S
+ type t = D.t
+ end
+
+ module rec U : T with module D = U' = U
+ and U' : S with type t = U'.t = U
+end;;
diff --git a/testsuite/tests/typing-recmod/t15bad.ml b/testsuite/tests/typing-recmod/t15bad.ml
new file mode 100644
index 0000000000..b387ae53f2
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t15bad.ml
@@ -0,0 +1,3 @@
+(* Bad - PR 4512 *)
+module type S' = sig type t = int end
+module rec M : S' with type t = M.t = struct type t = M.t end;;
diff --git a/testsuite/tests/typing-recmod/t16ok.ml b/testsuite/tests/typing-recmod/t16ok.ml
new file mode 100644
index 0000000000..583b69bb52
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t16ok.ml
@@ -0,0 +1,30 @@
+(* PR#4450 *)
+
+module PR_4450_1 = struct
+ module type MyT = sig type 'a t = Succ of 'a t end
+ module MyMap(X : MyT) = X
+ module rec MyList : MyT = MyMap(MyList)
+end;;
+
+module PR_4450_2 = struct
+ module type MyT = sig
+ type 'a wrap = My of 'a t
+ and 'a t = private < map : 'b. ('a -> 'b) ->'b wrap; .. >
+ val create : 'a list -> 'a t
+ end
+ module MyMap(X : MyT) = struct
+ include X
+ class ['a] c l = object (self)
+ method map : 'b. ('a -> 'b) -> 'b wrap =
+ fun f -> My (create (List.map f l))
+ end
+ end
+ module rec MyList : sig
+ type 'a wrap = My of 'a t
+ and 'a t = < map : 'b. ('a -> 'b) ->'b wrap >
+ val create : 'a list -> 'a t
+ end = struct
+ include MyMap(MyList)
+ let create l = new c l
+ end
+end;;
diff --git a/testsuite/tests/typing-recmod/t17ok.ml b/testsuite/tests/typing-recmod/t17ok.ml
new file mode 100644
index 0000000000..4521b66cfa
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t17ok.ml
@@ -0,0 +1,41 @@
+(* A synthetic example of bootstrapped data structure
+ (suggested by J-C Filliatre) *)
+
+module type ORD = sig
+ type t
+ val compare : t -> t -> int
+end
+
+module type SET = sig
+ type elt
+ type t
+ val iter : (elt -> unit) -> t -> unit
+end
+
+type 'a tree = E | N of 'a tree * 'a * 'a tree
+
+module Bootstrap2
+ (MakeDiet : functor (X: ORD) -> SET with type t = X.t tree and type elt = X.t)
+ : SET with type elt = int =
+struct
+
+ type elt = int
+
+ module rec Elt : sig
+ type t = I of int * int | D of int * Diet.t * int
+ val compare : t -> t -> int
+ val iter : (int -> unit) -> t -> unit
+ end =
+ struct
+ type t = I of int * int | D of int * Diet.t * int
+ let compare x1 x2 = 0
+ let rec iter f = function
+ | I (l, r) -> for i = l to r do f i done
+ | D (_, d, _) -> Diet.iter (iter f) d
+ end
+
+ and Diet : SET with type t = Elt.t tree and type elt = Elt.t = MakeDiet(Elt)
+
+ type t = Diet.t
+ let iter f = Diet.iter (Elt.iter f)
+end
diff --git a/testsuite/tests/typing-recmod/t18ok.ml b/testsuite/tests/typing-recmod/t18ok.ml
new file mode 100644
index 0000000000..64fcf6aba8
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t18ok.ml
@@ -0,0 +1,25 @@
+(* PR 4470: simplified from OMake's sources *)
+
+module rec DirElt
+ : sig
+ type t = DirRoot | DirSub of DirHash.t
+ end
+ = struct
+ type t = DirRoot | DirSub of DirHash.t
+ end
+
+and DirCompare
+ : sig
+ type t = DirElt.t
+ end
+ = struct
+ type t = DirElt.t
+ end
+
+and DirHash
+ : sig
+ type t = DirElt.t list
+ end
+ = struct
+ type t = DirCompare.t list
+ end
diff --git a/testsuite/tests/typing-recmod/t19ok.ml b/testsuite/tests/typing-recmod/t19ok.ml
new file mode 100644
index 0000000000..e51fa5c922
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t19ok.ml
@@ -0,0 +1,15 @@
+(* PR 4758, PR 4266 *)
+
+module PR_4758 = struct
+ module type S = sig end
+ module type Mod = sig
+ module Other : S
+ end
+ module rec A : S = struct end
+ and C : sig include Mod with module Other = A end = struct
+ module Other = A
+ end
+ module C' = C (* check that we can take an alias *)
+ module F(X:sig end) = struct type t end
+ let f (x : F(C).t) = (x : F(C').t)
+end
diff --git a/testsuite/tests/typing-recmod/t20ok.ml b/testsuite/tests/typing-recmod/t20ok.ml
new file mode 100644
index 0000000000..fec78c1db8
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t20ok.ml
@@ -0,0 +1,30 @@
+(* PR 4557 *)
+module PR_4557 = struct
+ module F ( X : Set.OrderedType ) = struct
+ module rec Mod : sig
+ module XSet :
+ sig
+ type elt = X.t
+ type t = Set.Make( X ).t
+ end
+ module XMap :
+ sig
+ type key = X.t
+ type 'a t = 'a Map.Make(X).t
+ end
+ type elt = X.t
+ type t = XSet.t XMap.t
+ val compare: t -> t -> int
+ end
+ =
+ struct
+ module XSet = Set.Make( X )
+ module XMap = Map.Make( X )
+
+ type elt = X.t
+ type t = XSet.t XMap.t
+ let compare = (fun x y -> 0)
+ end
+ and ModSet : Set.S with type elt = Mod.t = Set.Make( Mod )
+ end
+end
diff --git a/testsuite/tests/typing-recmod/t21ok.ml b/testsuite/tests/typing-recmod/t21ok.ml
new file mode 100644
index 0000000000..0415fe48e5
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t21ok.ml
@@ -0,0 +1,27 @@
+module F ( X : Set.OrderedType ) = struct
+ module rec Mod : sig
+ module XSet :
+ sig
+ type elt = X.t
+ type t = Set.Make( X ).t
+ end
+ module XMap :
+ sig
+ type key = X.t
+ type 'a t = 'a Map.Make(X).t
+ end
+ type elt = X.t
+ type t = XSet.t XMap.t
+ val compare: t -> t -> int
+ end
+ =
+ struct
+ module XSet = Set.Make( X )
+ module XMap = Map.Make( X )
+
+ type elt = X.t
+ type t = XSet.t XMap.t
+ let compare = (fun x y -> 0)
+ end
+ and ModSet : Set.S with type elt = Mod.t = Set.Make( Mod )
+end
diff --git a/testsuite/tests/typing-recmod/t22ok.ml b/testsuite/tests/typing-recmod/t22ok.ml
new file mode 100644
index 0000000000..de96eced55
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t22ok.ml
@@ -0,0 +1,511 @@
+(* Tests for recursive modules *)
+
+let test number result expected =
+ if result = expected
+ then Printf.printf "Test %d passed.\n" number
+ else Printf.printf "Test %d FAILED.\n" number;
+ flush stdout
+
+(* Tree of sets *)
+
+module rec A
+ : sig
+ type t = Leaf of int | Node of ASet.t
+ val compare: t -> t -> int
+ end
+ = struct
+ type t = Leaf of int | Node of ASet.t
+ let compare x y =
+ match (x,y) with
+ (Leaf i, Leaf j) -> Pervasives.compare i j
+ | (Leaf i, Node t) -> -1
+ | (Node s, Leaf j) -> 1
+ | (Node s, Node t) -> ASet.compare s t
+ end
+
+and ASet : Set.S with type elt = A.t = Set.Make(A)
+;;
+
+let _ =
+ let x = A.Node (ASet.add (A.Leaf 3) (ASet.singleton (A.Leaf 2))) in
+ let y = A.Node (ASet.add (A.Leaf 1) (ASet.singleton x)) in
+ test 10 (A.compare x x) 0;
+ test 11 (A.compare x (A.Leaf 3)) 1;
+ test 12 (A.compare (A.Leaf 0) x) (-1);
+ test 13 (A.compare y y) 0;
+ test 14 (A.compare x y) 1
+;;
+
+(* Simple value recursion *)
+
+module rec Fib
+ : sig val f : int -> int end
+ = struct let f x = if x < 2 then 1 else Fib.f(x-1) + Fib.f(x-2) end
+;;
+
+let _ =
+ test 20 (Fib.f 10) 89
+;;
+
+(* Update function by infix *)
+
+module rec Fib2
+ : sig val f : int -> int end
+ = struct let rec g x = Fib2.f(x-1) + Fib2.f(x-2)
+ and f x = if x < 2 then 1 else g x
+ end
+;;
+
+let _ =
+ test 21 (Fib2.f 10) 89
+;;
+
+(* Early application *)
+
+let _ =
+ let res =
+ try
+ let module A =
+ struct
+ module rec Bad
+ : sig val f : int -> int end
+ = struct let f = let y = Bad.f 5 in fun x -> x+y end
+ end in
+ false
+ with Undefined_recursive_module _ ->
+ true in
+ test 30 res true
+;;
+
+(* Early strict evaluation *)
+
+(*
+module rec Cyclic
+ : sig val x : int end
+ = struct let x = Cyclic.x + 1 end
+;;
+*)
+
+(* Reordering of evaluation based on dependencies *)
+
+module rec After
+ : sig val x : int end
+ = struct let x = Before.x + 1 end
+and Before
+ : sig val x : int end
+ = struct let x = 3 end
+;;
+
+let _ =
+ test 40 After.x 4
+;;
+
+(* Type identity between A.t and t within A's definition *)
+
+module rec Strengthen
+ : sig type t val f : t -> t end
+ = struct
+ type t = A | B
+ let _ = (A : Strengthen.t)
+ let f x = if true then A else Strengthen.f B
+ end
+;;
+
+module rec Strengthen2
+ : sig type t
+ val f : t -> t
+ module M : sig type u end
+ module R : sig type v end
+ end
+ = struct
+ type t = A | B
+ let _ = (A : Strengthen2.t)
+ let f x = if true then A else Strengthen2.f B
+ module M =
+ struct
+ type u = C
+ let _ = (C: Strengthen2.M.u)
+ end
+ module rec R : sig type v = Strengthen2.R.v end =
+ struct
+ type v = D
+ let _ = (D : R.v)
+ let _ = (D : Strengthen2.R.v)
+ end
+ end
+;;
+
+(* Polymorphic recursion *)
+
+module rec PolyRec
+ : sig
+ type 'a t = Leaf of 'a | Node of 'a list t * 'a list t
+ val depth: 'a t -> int
+ end
+ = struct
+ type 'a t = Leaf of 'a | Node of 'a list t * 'a list t
+ let x = (PolyRec.Leaf 1 : int t)
+ let depth = function
+ Leaf x -> 0
+ | Node(l,r) -> 1 + max (PolyRec.depth l) (PolyRec.depth r)
+ end
+;;
+
+(* Wrong LHS signatures (PR#4336) *)
+
+(*
+module type ASig = sig type a val a:a val print:a -> unit end
+module type BSig = sig type b val b:b val print:b -> unit end
+
+module A = struct type a = int let a = 0 let print = print_int end
+module B = struct type b = float let b = 0.0 let print = print_float end
+
+module MakeA (Empty:sig end) : ASig = A
+module MakeB (Empty:sig end) : BSig = B
+
+module
+ rec NewA : ASig = MakeA (struct end)
+ and NewB : BSig with type b = NewA.a = MakeB (struct end);;
+
+*)
+
+(* Expressions and bindings *)
+
+module StringSet = Set.Make(String);;
+
+module rec Expr
+ : sig
+ type t =
+ Var of string
+ | Const of int
+ | Add of t * t
+ | Binding of Binding.t * t
+ val make_let: string -> t -> t -> t
+ val fv: t -> StringSet.t
+ val simpl: t -> t
+ end
+ = struct
+ type t =
+ Var of string
+ | Const of int
+ | Add of t * t
+ | Binding of Binding.t * t
+ let make_let id e1 e2 = Binding([id, e1], e2)
+ let rec fv = function
+ Var s -> StringSet.singleton s
+ | Const n -> StringSet.empty
+ | Add(t1,t2) -> StringSet.union (fv t1) (fv t2)
+ | Binding(b,t) ->
+ StringSet.union (Binding.fv b)
+ (StringSet.diff (fv t) (Binding.bv b))
+ let rec simpl = function
+ Var s -> Var s
+ | Const n -> Const n
+ | Add(Const i, Const j) -> Const (i+j)
+ | Add(Const 0, t) -> simpl t
+ | Add(t, Const 0) -> simpl t
+ | Add(t1,t2) -> Add(simpl t1, simpl t2)
+ | Binding(b, t) -> Binding(Binding.simpl b, simpl t)
+ end
+
+and Binding
+ : sig
+ type t = (string * Expr.t) list
+ val fv: t -> StringSet.t
+ val bv: t -> StringSet.t
+ val simpl: t -> t
+ end
+ = struct
+ type t = (string * Expr.t) list
+ let fv b =
+ List.fold_left (fun v (id,e) -> StringSet.union v (Expr.fv e))
+ StringSet.empty b
+ let bv b =
+ List.fold_left (fun v (id,e) -> StringSet.add id v)
+ StringSet.empty b
+ let simpl b =
+ List.map (fun (id,e) -> (id, Expr.simpl e)) b
+ end
+;;
+
+let _ =
+ let e = Expr.make_let "x" (Expr.Add (Expr.Var "y", Expr.Const 0))
+ (Expr.Var "x") in
+ let e' = Expr.make_let "x" (Expr.Var "y") (Expr.Var "x") in
+ test 50 (StringSet.elements (Expr.fv e)) ["y"];
+ test 51 (Expr.simpl e) e'
+;;
+
+(* Okasaki's bootstrapping *)
+
+module type ORDERED =
+ sig
+ type t
+ val eq: t -> t -> bool
+ val lt: t -> t -> bool
+ val leq: t -> t -> bool
+ end
+
+module type HEAP =
+ sig
+ module Elem: ORDERED
+ type heap
+ val empty: heap
+ val isEmpty: heap -> bool
+ val insert: Elem.t -> heap -> heap
+ val merge: heap -> heap -> heap
+ val findMin: heap -> Elem.t
+ val deleteMin: heap -> heap
+ end
+
+module Bootstrap (MakeH: functor (Element:ORDERED) ->
+ HEAP with module Elem = Element)
+ (Element: ORDERED) : HEAP with module Elem = Element =
+ struct
+ module Elem = Element
+ module rec BE
+ : sig type t = E | H of Elem.t * PrimH.heap
+ val eq: t -> t -> bool
+ val lt: t -> t -> bool
+ val leq: t -> t -> bool
+ end
+ = struct
+ type t = E | H of Elem.t * PrimH.heap
+ let leq t1 t2 =
+ match t1, t2 with
+ | (H(x, _)), (H(y, _)) -> Elem.leq x y
+ | H _, E -> false
+ | E, H _ -> true
+ | E, E -> true
+ let eq t1 t2 =
+ match t1, t2 with
+ | (H(x, _)), (H(y, _)) -> Elem.eq x y
+ | H _, E -> false
+ | E, H _ -> false
+ | E, E -> true
+ let lt t1 t2 =
+ match t1, t2 with
+ | (H(x, _)), (H(y, _)) -> Elem.lt x y
+ | H _, E -> false
+ | E, H _ -> true
+ | E, E -> false
+ end
+ and PrimH
+ : HEAP with type Elem.t = BE.t
+ = MakeH(BE)
+ type heap = BE.t
+ let empty = BE.E
+ let isEmpty = function BE.E -> true | _ -> false
+ let rec merge x y =
+ match (x,y) with
+ (BE.E, _) -> y
+ | (_, BE.E) -> x
+ | (BE.H(e1,p1) as h1), (BE.H(e2,p2) as h2) ->
+ if Elem.leq e1 e2
+ then BE.H(e1, PrimH.insert h2 p1)
+ else BE.H(e2, PrimH.insert h1 p2)
+ let insert x h =
+ merge (BE.H(x, PrimH.empty)) h
+ let findMin = function
+ BE.E -> raise Not_found
+ | BE.H(x, _) -> x
+ let deleteMin = function
+ BE.E -> raise Not_found
+ | BE.H(x, p) ->
+ if PrimH.isEmpty p then BE.E else begin
+ match PrimH.findMin p with
+ | (BE.H(y, p1)) ->
+ let p2 = PrimH.deleteMin p in
+ BE.H(y, PrimH.merge p1 p2)
+ | BE.E -> assert false
+ end
+ end
+;;
+
+module LeftistHeap(Element: ORDERED): HEAP with module Elem = Element =
+ struct
+ module Elem = Element
+ type heap = E | T of int * Elem.t * heap * heap
+ let rank = function E -> 0 | T(r,_,_,_) -> r
+ let make x a b =
+ if rank a >= rank b
+ then T(rank b + 1, x, a, b)
+ else T(rank a + 1, x, b, a)
+ let empty = E
+ let isEmpty = function E -> true | _ -> false
+ let rec merge h1 h2 =
+ match (h1, h2) with
+ (_, E) -> h1
+ | (E, _) -> h2
+ | (T(_, x1, a1, b1), T(_, x2, a2, b2)) ->
+ if Elem.leq x1 x2
+ then make x1 a1 (merge b1 h2)
+ else make x2 a2 (merge h1 b2)
+ let insert x h = merge (T(1, x, E, E)) h
+ let findMin = function
+ E -> raise Not_found
+ | T(_, x, _, _) -> x
+ let deleteMin = function
+ E -> raise Not_found
+ | T(_, x, a, b) -> merge a b
+ end
+;;
+
+module Ints =
+ struct
+ type t = int
+ let eq = (=)
+ let lt = (<)
+ let leq = (<=)
+ end
+;;
+
+module C = Bootstrap(LeftistHeap)(Ints);;
+
+let _ =
+ let h = List.fold_right C.insert [6;4;8;7;3;1] C.empty in
+ test 60 (C.findMin h) 1;
+ test 61 (C.findMin (C.deleteMin h)) 3;
+ test 62 (C.findMin (C.deleteMin (C.deleteMin h))) 4
+;;
+
+(* Classes *)
+
+module rec Class1
+ : sig
+ class c : object method m : int -> int end
+ end
+ = struct
+ class c =
+ object
+ method m x = if x <= 0 then x else (new Class2.d)#m x
+ end
+ end
+and Class2
+ : sig
+ class d : object method m : int -> int end
+ end
+ = struct
+ class d =
+ object(self)
+ inherit Class1.c as super
+ method m (x:int) = super#m 0
+ end
+ end
+;;
+
+let _ =
+ test 70 ((new Class1.c)#m 7) 0
+;;
+
+let _ =
+ try
+ let module A = struct
+ module rec BadClass1
+ : sig
+ class c : object method m : int end
+ end
+ = struct
+ class c = object method m = 123 end
+ end
+ and BadClass2
+ : sig
+ val x: int
+ end
+ = struct
+ let x = (new BadClass1.c)#m
+ end
+ end in
+ test 71 true false
+ with Undefined_recursive_module _ ->
+ test 71 true true
+;;
+
+(* Coercions *)
+
+module rec Coerce1
+ : sig
+ val g: int -> int
+ val f: int -> int
+ end
+ = struct
+ module A = (Coerce1: sig val f: int -> int end)
+ let g x = x
+ let f x = if x <= 0 then 1 else A.f (x-1) * x
+ end
+;;
+
+let _ =
+ test 80 (Coerce1.f 10) 3628800
+;;
+
+module CoerceF(S: sig end) = struct
+ let f1 () = 1
+ let f2 () = 2
+ let f3 () = 3
+ let f4 () = 4
+ let f5 () = 5
+end
+
+module rec Coerce2: sig val f1: unit -> int end = CoerceF(Coerce3)
+ and Coerce3: sig end = struct end
+;;
+
+let _ =
+ test 81 (Coerce2.f1 ()) 1
+;;
+
+module Coerce4(A : sig val f : int -> int end) = struct
+ let x = 0
+ let at a = A.f a
+end
+
+module rec Coerce5
+ : sig val blabla: int -> int val f: int -> int end
+ = struct let blabla x = 0 let f x = 5 end
+and Coerce6
+ : sig val at: int -> int end
+ = Coerce4(Coerce5)
+
+let _ =
+ test 82 (Coerce6.at 100) 5
+;;
+
+(* Miscellaneous bug reports *)
+
+module rec F
+ : sig type t = X of int | Y of int
+ val f: t -> bool
+ end
+ = struct
+ type t = X of int | Y of int
+ let f = function
+ | X _ -> false
+ | _ -> true
+ end;;
+
+let _ =
+ test 100 (F.f (F.X 1)) false;
+ test 101 (F.f (F.Y 2)) true
+
+(* PR#4316 *)
+module G(S : sig val x : int Lazy.t end) = struct include S end
+
+module M1 = struct let x = lazy 3 end
+
+let _ = Lazy.force M1.x
+
+module rec M2 : sig val x : int Lazy.t end = G(M1)
+
+let _ =
+ test 102 (Lazy.force M2.x) 3
+
+let _ = Gc.full_major() (* will shortcut forwarding in M1.x *)
+
+module rec M3 : sig val x : int Lazy.t end = G(M1)
+
+let _ =
+ test 103 (Lazy.force M3.x) 3
+
+
+(** Pure type-checking tests: see recmod/*.ml *)
diff --git a/testsuite/tests/typing-recmod/t22ok.mli b/testsuite/tests/typing-recmod/t22ok.mli
new file mode 100644
index 0000000000..6c1fad3610
--- /dev/null
+++ b/testsuite/tests/typing-recmod/t22ok.mli
@@ -0,0 +1,134 @@
+module rec A :
+ sig type t = Leaf of int | Node of ASet.t val compare : t -> t -> int end
+and ASet : Set.S with type elt = A.t
+module Fib : sig val f : int -> int end
+module After : sig val x : int end
+module Before : sig val x : int end
+module Strengthen : sig type t val f : t -> t end
+module Strengthen2 :
+ sig
+ type t
+ val f : t -> t
+ module M : sig type u end
+ module R : sig type v end
+ end
+module PolyRec :
+ sig
+ type 'a t = Leaf of 'a | Node of 'a list t * 'a list t
+ val depth : 'a t -> int
+ end
+module StringSet : Set.S with type elt = string
+module rec Expr :
+ sig
+ type t =
+ Var of string
+ | Const of int
+ | Add of t * t
+ | Binding of Binding.t * t
+ val make_let : string -> t -> t -> t
+ val fv : t -> StringSet.t
+ val simpl : t -> t
+ end
+and Binding :
+ sig
+ type t = (string * Expr.t) list
+ val fv : t -> StringSet.t
+ val bv : t -> StringSet.t
+ val simpl : t -> t
+ end
+module type ORDERED =
+ sig
+ type t
+ val eq : t -> t -> bool
+ val lt : t -> t -> bool
+ val leq : t -> t -> bool
+ end
+module type HEAP =
+ sig
+ module Elem : ORDERED
+ type heap
+ val empty : heap
+ val isEmpty : heap -> bool
+ val insert : Elem.t -> heap -> heap
+ val merge : heap -> heap -> heap
+ val findMin : heap -> Elem.t
+ val deleteMin : heap -> heap
+ end
+module Bootstrap :
+ functor
+ (MakeH : functor (Element : ORDERED) ->
+ sig
+ module Elem :
+ sig
+ type t = Element.t
+ val eq : t -> t -> bool
+ val lt : t -> t -> bool
+ val leq : t -> t -> bool
+ end
+ type heap
+ val empty : heap
+ val isEmpty : heap -> bool
+ val insert : Elem.t -> heap -> heap
+ val merge : heap -> heap -> heap
+ val findMin : heap -> Elem.t
+ val deleteMin : heap -> heap
+ end) ->
+ functor (Element : ORDERED) ->
+ sig
+ module Elem :
+ sig
+ type t = Element.t
+ val eq : t -> t -> bool
+ val lt : t -> t -> bool
+ val leq : t -> t -> bool
+ end
+ type heap
+ val empty : heap
+ val isEmpty : heap -> bool
+ val insert : Elem.t -> heap -> heap
+ val merge : heap -> heap -> heap
+ val findMin : heap -> Elem.t
+ val deleteMin : heap -> heap
+ end
+module LeftistHeap :
+ functor (Element : ORDERED) ->
+ sig
+ module Elem :
+ sig
+ type t = Element.t
+ val eq : t -> t -> bool
+ val lt : t -> t -> bool
+ val leq : t -> t -> bool
+ end
+ type heap
+ val empty : heap
+ val isEmpty : heap -> bool
+ val insert : Elem.t -> heap -> heap
+ val merge : heap -> heap -> heap
+ val findMin : heap -> Elem.t
+ val deleteMin : heap -> heap
+ end
+module Ints :
+ sig
+ type t = int
+ val eq : 'a -> 'a -> bool
+ val lt : 'a -> 'a -> bool
+ val leq : 'a -> 'a -> bool
+ end
+module C :
+ sig
+ module Elem :
+ sig
+ type t = Ints.t
+ val eq : t -> t -> bool
+ val lt : t -> t -> bool
+ val leq : t -> t -> bool
+ end
+ type heap = Bootstrap(LeftistHeap)(Ints).heap
+ val empty : heap
+ val isEmpty : heap -> bool
+ val insert : Elem.t -> heap -> heap
+ val merge : heap -> heap -> heap
+ val findMin : heap -> Elem.t
+ val deleteMin : heap -> heap
+ end
diff --git a/testsuite/tests/typing-recordarg/Makefile b/testsuite/tests/typing-recordarg/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-recordarg/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-recordarg/recordarg.ml b/testsuite/tests/typing-recordarg/recordarg.ml
new file mode 100644
index 0000000000..ebd8d05671
--- /dev/null
+++ b/testsuite/tests/typing-recordarg/recordarg.ml
@@ -0,0 +1,92 @@
+type t = A of {x:int; mutable y:int};;
+let f (A r) = r;; (* -> escape *)
+let f (A r) = r.x;; (* ok *)
+let f x = A {x; y = x};; (* ok *)
+let f (A r) = A {r with y = r.x + 1};; (* ok *)
+let f () = A {a = 1};; (* customized error message *)
+let f () = A {x = 1; y = 3};; (* ok *)
+
+type _ t = A: {x : 'a; y : 'b} -> 'a t;;
+let f (A {x; y}) = A {x; y = ()};; (* ok *)
+let f (A ({x; y} as r)) = A {x = r.x; y = r.y};; (* ok *)
+
+module M = struct
+ type 'a t =
+ | A of {x : 'a}
+ | B: {u : 'b} -> unit t;;
+
+ exception Foo of {x : int};;
+end;;
+
+module N : sig
+ type 'b t = 'b M.t =
+ | A of {x : 'b}
+ | B: {u : 'bla} -> unit t
+
+ exception Foo of {x : int}
+end = struct
+ type 'b t = 'b M.t =
+ | A of {x : 'b}
+ | B: {u : 'z} -> unit t
+
+ exception Foo = M.Foo
+end;;
+
+
+module type S = sig exception A of {x:int} end;;
+
+module F (X : sig val x : (module S) end) = struct
+ module A = (val X.x)
+end;; (* -> this expression creates fresh types (not really!) *)
+
+
+module type S = sig
+ exception A of {x : int}
+ exception A of {x : string}
+end;;
+
+module M = struct
+ exception A of {x : int}
+ exception A of {x : string}
+end;;
+
+
+module M1 = struct
+ exception A of {x : int}
+end;;
+
+module M = struct
+ include M1
+ include M1
+end;;
+
+
+module type S1 = sig
+ exception A of {x : int}
+end;;
+
+module type S = sig
+ include S1
+ include S1
+end;;
+
+module M = struct
+ exception A = M1.A
+end;;
+
+module X1 = struct
+ type t = ..
+end;;
+module X2 = struct
+ type t = ..
+end;;
+module Z = struct
+ type X1.t += A of {x: int}
+ type X2.t += A of {x: int}
+end;;
+
+(* PR#6716 *)
+
+type _ c = C : [`A] c
+type t = T : {x:[<`A] c} -> t;;
+let f (T { x = C }) = ();;
diff --git a/testsuite/tests/typing-recordarg/recordarg.ml.reference b/testsuite/tests/typing-recordarg/recordarg.ml.reference
new file mode 100644
index 0000000000..5a671d6528
--- /dev/null
+++ b/testsuite/tests/typing-recordarg/recordarg.ml.reference
@@ -0,0 +1,67 @@
+
+# type t = A of { x : int; mutable y : int; }
+# Characters 14-15:
+ let f (A r) = r;; (* -> escape *)
+ ^
+Error: This form is not allowed as the type of the inlined record could escape.
+# val f : t -> int = <fun>
+# val f : int -> t = <fun>
+# val f : t -> t = <fun>
+# Characters 14-15:
+ let f () = A {a = 1};; (* customized error message *)
+ ^
+Error: The field a is not part of the record argument for the t.A constructor
+# val f : unit -> t = <fun>
+# type _ t = A : { x : 'a; y : 'b; } -> 'a t
+# val f : 'a t -> 'a t = <fun>
+# val f : 'a t -> 'a t = <fun>
+# module M :
+ sig
+ type 'a t = A of { x : 'a; } | B : { u : 'b; } -> unit t
+ exception Foo of { x : int; }
+ end
+# module N :
+ sig
+ type 'b t = 'b M.t = A of { x : 'b; } | B : { u : 'bla; } -> unit t
+ exception Foo of { x : int; }
+ end
+# module type S = sig exception A of { x : int; } end
+# Characters 65-74:
+ module A = (val X.x)
+ ^^^^^^^^^
+Error: This expression creates fresh types.
+ It is not allowed inside applicative functors.
+# Characters 61-62:
+ exception A of {x : string}
+ ^
+Error: Multiple definition of the extension constructor name A.
+ Names must be unique in a given structure or signature.
+# Characters 58-59:
+ exception A of {x : string}
+ ^
+Error: Multiple definition of the extension constructor name A.
+ Names must be unique in a given structure or signature.
+# module M1 : sig exception A of { x : int; } end
+# Characters 34-44:
+ include M1
+ ^^^^^^^^^^
+Error: Multiple definition of the extension constructor name A.
+ Names must be unique in a given structure or signature.
+# module type S1 = sig exception A of { x : int; } end
+# Characters 36-46:
+ include S1
+ ^^^^^^^^^^
+Error: Multiple definition of the extension constructor name A.
+ Names must be unique in a given structure or signature.
+# module M : sig exception A of { x : int; } end
+# module X1 : sig type t = .. end
+# module X2 : sig type t = .. end
+# Characters 62-63:
+ type X2.t += A of {x: int}
+ ^
+Error: Multiple definition of the extension constructor name A.
+ Names must be unique in a given structure or signature.
+# type _ c = C : [ `A ] c
+type t = T : { x : [< `A ] c; } -> t
+# val f : t -> unit = <fun>
+#
diff --git a/testsuite/tests/typing-rectypes-bugs/Makefile b/testsuite/tests/typing-rectypes-bugs/Makefile
new file mode 100644
index 0000000000..e0202b0ad5
--- /dev/null
+++ b/testsuite/tests/typing-rectypes-bugs/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+include ../../makefiles/Makefile.okbad
+include ../../makefiles/Makefile.common
+COMPFLAGS = -rectypes
diff --git a/testsuite/tests/typing-rectypes-bugs/pr5343_bad.ml b/testsuite/tests/typing-rectypes-bugs/pr5343_bad.ml
new file mode 100644
index 0000000000..0484c677cb
--- /dev/null
+++ b/testsuite/tests/typing-rectypes-bugs/pr5343_bad.ml
@@ -0,0 +1,13 @@
+module M : sig
+ type 'a t
+ type u = u t and v = v t
+ val f : int -> u
+ val g : v -> bool
+end = struct
+ type 'a t = 'a
+ type u = int and v = bool
+ let f x = x
+ let g x = x
+end;;
+
+let h (x : int) : bool = M.g (M.f x);;
diff --git a/testsuite/tests/typing-rectypes-bugs/pr6174_bad.ml b/testsuite/tests/typing-rectypes-bugs/pr6174_bad.ml
new file mode 100644
index 0000000000..84f79ba0e5
--- /dev/null
+++ b/testsuite/tests/typing-rectypes-bugs/pr6174_bad.ml
@@ -0,0 +1,3 @@
+type _ t = C : ((('a -> 'o) -> 'o) -> ('b -> 'o) -> 'o) t
+let f : type a o. ((a -> o) -> o) t -> (a -> o) -> o =
+ fun C k -> k (fun x -> x);;
diff --git a/testsuite/tests/typing-rectypes-bugs/pr6870_bad.ml b/testsuite/tests/typing-rectypes-bugs/pr6870_bad.ml
new file mode 100644
index 0000000000..ed83460555
--- /dev/null
+++ b/testsuite/tests/typing-rectypes-bugs/pr6870_bad.ml
@@ -0,0 +1,2 @@
+module type T = sig type 'a t end
+module Fix (T : T) = struct type r = ('r T.t as 'r) end
diff --git a/testsuite/tests/typing-short-paths/Makefile b/testsuite/tests/typing-short-paths/Makefile
new file mode 100644
index 0000000000..3b7cbaa3b3
--- /dev/null
+++ b/testsuite/tests/typing-short-paths/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
+TOPFLAGS = -short-paths
diff --git a/testsuite/tests/typing-short-paths/pr5918.ml b/testsuite/tests/typing-short-paths/pr5918.ml
new file mode 100644
index 0000000000..604f66d84f
--- /dev/null
+++ b/testsuite/tests/typing-short-paths/pr5918.ml
@@ -0,0 +1,7 @@
+module rec A : sig
+ type t
+end = struct
+ type t = { a : unit; b : unit }
+ let _ = { a = () }
+end
+;;
diff --git a/testsuite/tests/typing-short-paths/pr5918.ml.reference b/testsuite/tests/typing-short-paths/pr5918.ml.reference
new file mode 100644
index 0000000000..3364e16d29
--- /dev/null
+++ b/testsuite/tests/typing-short-paths/pr5918.ml.reference
@@ -0,0 +1,6 @@
+
+# Characters 82-92:
+ let _ = { a = () }
+ ^^^^^^^^^^
+Error: Some record fields are undefined: b
+#
diff --git a/testsuite/tests/typing-short-paths/pr6836.ml b/testsuite/tests/typing-short-paths/pr6836.ml
new file mode 100644
index 0000000000..121bc463d5
--- /dev/null
+++ b/testsuite/tests/typing-short-paths/pr6836.ml
@@ -0,0 +1,6 @@
+type t = [`A | `B];;
+type 'a u = t;;
+let a : [< int u] = `A;;
+
+type 'a s = 'a;;
+let b : [< t s] = `B;;
diff --git a/testsuite/tests/typing-short-paths/pr6836.ml.reference b/testsuite/tests/typing-short-paths/pr6836.ml.reference
new file mode 100644
index 0000000000..3f8c6dbd01
--- /dev/null
+++ b/testsuite/tests/typing-short-paths/pr6836.ml.reference
@@ -0,0 +1,7 @@
+
+# type t = [ `A | `B ]
+# type 'a u = t
+# val a : [< int u > `A ] = `A
+# type 'a s = 'a
+# val b : [< t > `B ] = `B
+#
diff --git a/testsuite/tests/typing-short-paths/short-paths.ml b/testsuite/tests/typing-short-paths/short-paths.ml
new file mode 100644
index 0000000000..5d691acaab
--- /dev/null
+++ b/testsuite/tests/typing-short-paths/short-paths.ml
@@ -0,0 +1,57 @@
+module Core = struct
+ module Int = struct
+ module T = struct
+ type t = int
+ let compare = compare
+ let (+) x y = x + y
+ end
+ include T
+ module Map = Map.Make(T)
+ end
+
+ module Std = struct
+ module Int = Int
+ end
+end
+;;
+
+open Core.Std
+;;
+
+let x = Int.Map.empty ;;
+let y = x + x ;;
+
+(* Avoid ambiguity *)
+
+module M = struct type t = A type u = C end
+module N = struct type t = B end
+open M open N;;
+A;;
+B;;
+C;;
+
+include M open M;;
+C;;
+
+module L = struct type v = V end
+open L;;
+V;;
+module L = struct type v = V end
+open L;;
+V;;
+
+
+type t1 = A;;
+module M1 = struct type u = v and v = t1 end;;
+module N1 = struct type u = v and v = M1.v end;;
+type t1 = B;;
+module N2 = struct type u = v and v = M1.v end;;
+
+
+(* PR#6566 *)
+module type PR6566 = sig type t = string end;;
+module PR6566 = struct type t = int end;;
+module PR6566' : PR6566 = PR6566;;
+
+module A = struct module B = struct type t = T end end;;
+module M2 = struct type u = A.B.t type foo = int type v = A.B.t end;;
diff --git a/testsuite/tests/typing-short-paths/short-paths.ml.reference b/testsuite/tests/typing-short-paths/short-paths.ml.reference
new file mode 100644
index 0000000000..db44521aa2
--- /dev/null
+++ b/testsuite/tests/typing-short-paths/short-paths.ml.reference
@@ -0,0 +1,85 @@
+
+# module Core :
+ sig
+ module Int :
+ sig
+ module T :
+ sig
+ type t = int
+ val compare : 'a -> 'a -> t
+ val ( + ) : t -> t -> t
+ end
+ type t = int
+ val compare : 'a -> 'a -> t
+ val ( + ) : t -> t -> t
+ module Map :
+ sig
+ type key = t
+ type 'a t = 'a Map.Make(T).t
+ val empty : 'a t
+ val is_empty : 'a t -> bool
+ val mem : key -> 'a t -> bool
+ val add : key -> 'a -> 'a t -> 'a t
+ val singleton : key -> 'a -> 'a t
+ val remove : key -> 'a t -> 'a t
+ val merge :
+ (key -> 'a option -> 'b option -> 'c option) ->
+ 'a t -> 'b t -> 'c t
+ val compare : ('a -> 'a -> key) -> 'a t -> 'a t -> key
+ val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
+ val iter : (key -> 'a -> unit) -> 'a t -> unit
+ val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
+ val for_all : (key -> 'a -> bool) -> 'a t -> bool
+ val exists : (key -> 'a -> bool) -> 'a t -> bool
+ val filter : (key -> 'a -> bool) -> 'a t -> 'a t
+ val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t
+ val cardinal : 'a t -> key
+ val bindings : 'a t -> (key * 'a) list
+ val min_binding : 'a t -> key * 'a
+ val max_binding : 'a t -> key * 'a
+ val choose : 'a t -> key * 'a
+ val split : key -> 'a t -> 'a t * 'a option * 'a t
+ val find : key -> 'a t -> 'a
+ val map : ('a -> 'b) -> 'a t -> 'b t
+ val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t
+ end
+ end
+ module Std : sig module Int = Int end
+ end
+# # val x : 'a Int.Map.t = <abstr>
+# Characters 8-9:
+ let y = x + x ;;
+ ^
+Error: This expression has type 'a Int.Map.t
+ but an expression was expected of type int
+# module M : sig type t = A type u = C end
+module N : sig type t = B end
+# - : M.t = A
+# - : N.t = B
+# - : u = C
+# type t = M.t = A
+type u = M.u = C
+# - : u = C
+# module L : sig type v = V end
+# - : v = V
+# module L : sig type v = V end
+# - : v = V
+# type t1 = A
+# module M1 : sig type u = v and v = t1 end
+# module N1 : sig type u = v and v = t1 end
+# type t1 = B
+# module N2 : sig type u = v and v = N1.v end
+# module type PR6566 = sig type t = string end
+# module PR6566 : sig type t = int end
+# Characters 26-32:
+ module PR6566' : PR6566 = PR6566;;
+ ^^^^^^
+Error: Signature mismatch:
+ Modules do not match: sig type t = int end is not included in PR6566
+ Type declarations do not match:
+ type t = int
+ is not included in
+ type t = string
+# module A : sig module B : sig type t = T end end
+# module M2 : sig type u = A.B.t type foo = int type v = u end
+#
diff --git a/testsuite/tests/typing-signatures/Makefile b/testsuite/tests/typing-signatures/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-signatures/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-signatures/els.ml b/testsuite/tests/typing-signatures/els.ml
new file mode 100644
index 0000000000..dfc2e07450
--- /dev/null
+++ b/testsuite/tests/typing-signatures/els.ml
@@ -0,0 +1,95 @@
+(* Adapted from: An Expressive Language of Signatures
+ by Norman Ramsey, Kathleen Fisher and Paul Govereau *)
+
+module type VALUE = sig
+ type value (* a Lua value *)
+ type state (* the state of a Lua interpreter *)
+ type usert (* a user-defined value *)
+end;;
+
+module type CORE0 = sig
+ module V : VALUE
+ val setglobal : V.state -> string -> V.value -> unit
+ (* five more functions common to core and evaluator *)
+end;;
+
+module type CORE = sig
+ include CORE0
+ val apply : V.value -> V.state -> V.value list -> V.value
+ (* apply function f in state s to list of args *)
+end;;
+
+module type AST = sig
+ module Value : VALUE
+ type chunk
+ type program
+ val get_value : chunk -> Value.value
+end;;
+
+module type EVALUATOR = sig
+ module Value : VALUE
+ module Ast : (AST with module Value := Value)
+ type state = Value.state
+ type value = Value.value
+ exception Error of string
+ val compile : Ast.program -> string
+ include CORE0 with module V := Value
+end;;
+
+module type PARSER = sig
+ type chunk
+ val parse : string -> chunk
+end;;
+
+module type INTERP = sig
+ include EVALUATOR
+ module Parser : PARSER with type chunk = Ast.chunk
+ val dostring : state -> string -> value list
+ val mk : unit -> state
+end;;
+
+module type USERTYPE = sig
+ type t
+ val eq : t -> t -> bool
+ val to_string : t -> string
+end;;
+
+module type TYPEVIEW = sig
+ type combined
+ type t
+ val map : (combined -> t) * (t -> combined)
+end;;
+
+module type COMBINED_COMMON = sig
+ module T : sig type t end
+ module TV1 : TYPEVIEW with type combined := T.t
+ module TV2 : TYPEVIEW with type combined := T.t
+end;;
+
+module type COMBINED_TYPE = sig
+ module T : USERTYPE
+ include COMBINED_COMMON with module T := T
+end;;
+
+module type BARECODE = sig
+ type state
+ val init : state -> unit
+end;;
+
+module USERCODE(X : TYPEVIEW) = struct
+ module type F =
+ functor (C : CORE with type V.usert = X.combined) ->
+ BARECODE with type state := C.V.state
+end;;
+
+module Weapon = struct type t end;;
+
+module type WEAPON_LIB = sig
+ type t = Weapon.t
+ module T : USERTYPE with type t = t
+ module Make :
+ functor (TV : TYPEVIEW with type t = t) -> USERCODE(TV).F
+end;;
+
+module type X = functor (X: CORE) -> BARECODE;;
+module type X = functor (_: CORE) -> BARECODE;;
diff --git a/testsuite/tests/typing-signatures/els.ml.reference b/testsuite/tests/typing-signatures/els.ml.reference
new file mode 100644
index 0000000000..407ced1d18
--- /dev/null
+++ b/testsuite/tests/typing-signatures/els.ml.reference
@@ -0,0 +1,95 @@
+
+# * module type VALUE = sig type value type state type usert end
+# module type CORE0 =
+ sig
+ module V : VALUE
+ val setglobal : V.state -> string -> V.value -> unit
+ end
+# module type CORE =
+ sig
+ module V : VALUE
+ val setglobal : V.state -> string -> V.value -> unit
+ val apply : V.value -> V.state -> V.value list -> V.value
+ end
+# module type AST =
+ sig
+ module Value : VALUE
+ type chunk
+ type program
+ val get_value : chunk -> Value.value
+ end
+# module type EVALUATOR =
+ sig
+ module Value : VALUE
+ module Ast :
+ sig type chunk type program val get_value : chunk -> Value.value end
+ type state = Value.state
+ type value = Value.value
+ exception Error of string
+ val compile : Ast.program -> string
+ val setglobal : Value.state -> string -> Value.value -> unit
+ end
+# module type PARSER = sig type chunk val parse : string -> chunk end
+# module type INTERP =
+ sig
+ module Value : VALUE
+ module Ast :
+ sig type chunk type program val get_value : chunk -> Value.value end
+ type state = Value.state
+ type value = Value.value
+ exception Error of string
+ val compile : Ast.program -> string
+ val setglobal : Value.state -> string -> Value.value -> unit
+ module Parser :
+ sig type chunk = Ast.chunk val parse : string -> chunk end
+ val dostring : state -> string -> value list
+ val mk : unit -> state
+ end
+# module type USERTYPE =
+ sig type t val eq : t -> t -> bool val to_string : t -> string end
+# module type TYPEVIEW =
+ sig type combined type t val map : (combined -> t) * (t -> combined) end
+# module type COMBINED_COMMON =
+ sig
+ module T : sig type t end
+ module TV1 : sig type t val map : (T.t -> t) * (t -> T.t) end
+ module TV2 : sig type t val map : (T.t -> t) * (t -> T.t) end
+ end
+# module type COMBINED_TYPE =
+ sig
+ module T : USERTYPE
+ module TV1 : sig type t val map : (T.t -> t) * (t -> T.t) end
+ module TV2 : sig type t val map : (T.t -> t) * (t -> T.t) end
+ end
+# module type BARECODE = sig type state val init : state -> unit end
+# module USERCODE :
+ functor (X : TYPEVIEW) ->
+ sig
+ module type F =
+ functor
+ (C : sig
+ module V :
+ sig type value type state type usert = X.combined end
+ val setglobal : V.state -> string -> V.value -> unit
+ val apply : V.value -> V.state -> V.value list -> V.value
+ end) ->
+ sig val init : C.V.state -> unit end
+ end
+# module Weapon : sig type t end
+# module type WEAPON_LIB =
+ sig
+ type t = Weapon.t
+ module T :
+ sig type t = t val eq : t -> t -> bool val to_string : t -> string end
+ module Make :
+ functor
+ (TV : sig
+ type combined
+ type t = t
+ val map : (combined -> t) * (t -> combined)
+ end) ->
+ USERCODE(TV).F
+ end
+# module type X = functor (X : CORE) -> BARECODE
+# module type X = functor (_ : CORE) -> BARECODE
+#
diff --git a/testsuite/tests/typing-signatures/pr6371.ml b/testsuite/tests/typing-signatures/pr6371.ml
new file mode 100644
index 0000000000..d717b9e683
--- /dev/null
+++ b/testsuite/tests/typing-signatures/pr6371.ml
@@ -0,0 +1,7 @@
+module M = struct
+ type t = int * (< m : 'a > as 'a)
+end;;
+
+module type S =
+ sig module M : sig type t end end with module M = M
+;;
diff --git a/testsuite/tests/typing-signatures/pr6371.ml.reference b/testsuite/tests/typing-signatures/pr6371.ml.reference
new file mode 100644
index 0000000000..d6d916a71d
--- /dev/null
+++ b/testsuite/tests/typing-signatures/pr6371.ml.reference
@@ -0,0 +1,4 @@
+
+# module M : sig type t = int * (< m : 'a > as 'a) end
+# module type S = sig module M : sig type t = int * (< m : 'a > as 'a) end end
+#
diff --git a/testsuite/tests/typing-signatures/pr6672.ml b/testsuite/tests/typing-signatures/pr6672.ml
new file mode 100644
index 0000000000..5b168f05a0
--- /dev/null
+++ b/testsuite/tests/typing-signatures/pr6672.ml
@@ -0,0 +1,3 @@
+module type S = sig type 'a t end;;
+module type T = S with type +'a t = 'a list;;
+module type T = S with type -'a t = 'a list;;
diff --git a/testsuite/tests/typing-signatures/pr6672.ml.reference b/testsuite/tests/typing-signatures/pr6672.ml.reference
new file mode 100644
index 0000000000..959cee7eb6
--- /dev/null
+++ b/testsuite/tests/typing-signatures/pr6672.ml.reference
@@ -0,0 +1,10 @@
+
+# module type S = sig type 'a t end
+# module type T = sig type 'a t = 'a list end
+# Characters 23-43:
+ module type T = S with type -'a t = 'a list;;
+ ^^^^^^^^^^^^^^^^^^^^
+Error: In this definition, expected parameter variances are not satisfied.
+ The 1st type parameter was expected to be contravariant,
+ but it is injective covariant.
+#
diff --git a/testsuite/tests/typing-sigsubst/Makefile b/testsuite/tests/typing-sigsubst/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-sigsubst/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-sigsubst/sigsubst.ml b/testsuite/tests/typing-sigsubst/sigsubst.ml
new file mode 100644
index 0000000000..6759f63ab2
--- /dev/null
+++ b/testsuite/tests/typing-sigsubst/sigsubst.ml
@@ -0,0 +1,40 @@
+module type Printable = sig
+ type t
+ val print : Format.formatter -> t -> unit
+end;;
+module type Comparable = sig
+ type t
+ val compare : t -> t -> int
+end;;
+module type PrintableComparable = sig
+ include Printable
+ include Comparable with type t = t
+end;; (* Fails *)
+module type PrintableComparable = sig
+ type t
+ include Printable with type t := t
+ include Comparable with type t := t
+end;;
+module type PrintableComparable = sig
+ include Printable
+ include Comparable with type t := t
+end;;
+module type ComparableInt = Comparable with type t := int;;
+module type S = sig type t val f : t -> t end;;
+module type S' = S with type t := int;;
+
+module type S = sig type 'a t val map : ('a -> 'b) -> 'a t -> 'b t end;;
+module type S1 = S with type 'a t := 'a list;;
+module type S2 = sig
+ type 'a dict = (string * 'a) list
+ include S with type 'a t := 'a dict
+end;;
+
+
+module type S =
+ sig module T : sig type exp type arg end val f : T.exp -> T.arg end;;
+module M = struct type exp = string type arg = int end;;
+module type S' = S with module T := M;;
+
+
+module type S = sig type 'a t end with type 'a t := unit;; (* Fails *)
diff --git a/testsuite/tests/typing-sigsubst/sigsubst.ml.reference b/testsuite/tests/typing-sigsubst/sigsubst.ml.reference
new file mode 100644
index 0000000000..5a160347b4
--- /dev/null
+++ b/testsuite/tests/typing-sigsubst/sigsubst.ml.reference
@@ -0,0 +1,40 @@
+
+# module type Printable =
+ sig type t val print : Format.formatter -> t -> unit end
+# module type Comparable = sig type t val compare : t -> t -> int end
+# Characters 60-94:
+ include Comparable with type t = t
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Error: Multiple definition of the type name t.
+ Names must be unique in a given structure or signature.
+# module type PrintableComparable =
+ sig
+ type t
+ val print : Format.formatter -> t -> unit
+ val compare : t -> t -> int
+ end
+# module type PrintableComparable =
+ sig
+ type t
+ val print : Format.formatter -> t -> unit
+ val compare : t -> t -> int
+ end
+# module type ComparableInt = sig val compare : int -> int -> int end
+# module type S = sig type t val f : t -> t end
+# module type S' = sig val f : int -> int end
+# module type S = sig type 'a t val map : ('a -> 'b) -> 'a t -> 'b t end
+# module type S1 = sig val map : ('a -> 'b) -> 'a list -> 'b list end
+# module type S2 =
+ sig
+ type 'a dict = (string * 'a) list
+ val map : ('a -> 'b) -> 'a dict -> 'b dict
+ end
+# module type S =
+ sig module T : sig type exp type arg end val f : T.exp -> T.arg end
+# module M : sig type exp = string type arg = int end
+# module type S' = sig val f : M.exp -> M.arg end
+# Characters 41-58:
+ module type S = sig type 'a t end with type 'a t := unit;; (* Fails *)
+ ^^^^^^^^^^^^^^^^^
+Error: Only type constructors with identical parameters can be substituted.
+#
diff --git a/testsuite/tests/typing-typeparam/Makefile b/testsuite/tests/typing-typeparam/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-typeparam/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-typeparam/newtype.ml b/testsuite/tests/typing-typeparam/newtype.ml
new file mode 100644
index 0000000000..abe587634c
--- /dev/null
+++ b/testsuite/tests/typing-typeparam/newtype.ml
@@ -0,0 +1,32 @@
+let property (type t) () =
+ let module M = struct exception E of t end in
+ (fun x -> M.E x), (function M.E x -> Some x | _ -> None)
+;;
+
+let () =
+ let (int_inj, int_proj) = property () in
+ let (string_inj, string_proj) = property () in
+
+ let i = int_inj 3 in
+ let s = string_inj "abc" in
+
+ Printf.printf "%b\n%!" (int_proj i = None);
+ Printf.printf "%b\n%!" (int_proj s = None);
+ Printf.printf "%b\n%!" (string_proj i = None);
+ Printf.printf "%b\n%!" (string_proj s = None)
+;;
+
+let sort_uniq (type s) cmp l =
+ let module S = Set.Make(struct type t = s let compare = cmp end) in
+ S.elements (List.fold_right S.add l S.empty)
+;;
+
+let () =
+ print_endline (String.concat "," (sort_uniq compare [ "abc"; "xyz"; "abc" ]))
+;;
+
+let f x (type a) (y : a) = (x = y);; (* Fails *)
+class ['a] c = object (self)
+ method m : 'a -> 'a = fun x -> x
+ method n : 'a -> 'a = fun (type g) (x:g) -> self#m x
+end;; (* Fails *)
diff --git a/testsuite/tests/typing-typeparam/newtype.ml.reference b/testsuite/tests/typing-typeparam/newtype.ml.reference
new file mode 100644
index 0000000000..217697531f
--- /dev/null
+++ b/testsuite/tests/typing-typeparam/newtype.ml.reference
@@ -0,0 +1,19 @@
+
+# val property : unit -> ('a -> exn) * (exn -> 'a option) = <fun>
+# false
+true
+true
+false
+# val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list = <fun>
+# abc,xyz
+# Characters 33-34:
+ let f x (type a) (y : a) = (x = y);; (* Fails *)
+ ^
+Error: This expression has type a but an expression was expected of type 'a
+ The type constructor a would escape its scope
+# Characters 117-118:
+ method n : 'a -> 'a = fun (type g) (x:g) -> self#m x
+ ^
+Error: This expression has type g but an expression was expected of type 'a
+ The type constructor g would escape its scope
+#
diff --git a/testsuite/tests/typing-unboxed/Makefile b/testsuite/tests/typing-unboxed/Makefile
new file mode 100644
index 0000000000..c9433b2ecb
--- /dev/null
+++ b/testsuite/tests/typing-unboxed/Makefile
@@ -0,0 +1,15 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/typing-unboxed/test.ml b/testsuite/tests/typing-unboxed/test.ml
new file mode 100644
index 0000000000..65091481b4
--- /dev/null
+++ b/testsuite/tests/typing-unboxed/test.ml
@@ -0,0 +1,94 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jeremie Dimino, Jane Street Europe *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+
+external a : (int [@untagged]) -> unit = "a"
+external b : (int32 [@unboxed]) -> unit = "b"
+external c : (int64 [@unboxed]) -> unit = "c"
+external d : (nativeint [@unboxed]) -> unit = "d"
+external e : (float [@unboxed]) -> unit = "e"
+
+type t = private int
+
+external f : (t [@untagged]) -> unit = "f"
+
+module M : sig
+ external a : int -> (int [@untagged]) = "a"
+ external b : (int [@untagged]) -> int = "b"
+end = struct
+ external a : int -> (int [@untagged]) = "a"
+ external b : (int [@untagged]) -> int = "b"
+end;;
+
+(* Bad: attributes not reported in the interface *)
+
+module Bad1 : sig
+ external f : int -> int = "f"
+end = struct
+ external f : int -> (int [@untagged]) = "f"
+end;;
+
+module Bad2 : sig
+ external f : int -> int = "a"
+end = struct
+ external f : (int [@untagged]) -> int = "f"
+end;;
+
+module Bad3 : sig
+ external f : float -> float = "f"
+end = struct
+ external f : float -> (float [@unboxed]) = "f"
+end;;
+
+module Bad4 : sig
+ external f : float -> float = "a"
+end = struct
+ external f : (float [@unboxed]) -> float = "f"
+end;;
+
+(* Bad: attributes in the interface but not in the implementation *)
+
+module Bad5 : sig
+ external f : int -> (int [@untagged]) = "f"
+end = struct
+ external f : int -> int = "f"
+end;;
+
+module Bad6 : sig
+ external f : (int [@untagged]) -> int = "f"
+end = struct
+ external f : int -> int = "a"
+end;;
+
+module Bad7 : sig
+ external f : float -> (float [@unboxed]) = "f"
+end = struct
+ external f : float -> float = "f"
+end;;
+
+module Bad8 : sig
+ external f : (float [@unboxed]) -> float = "f"
+end = struct
+ external f : float -> float = "a"
+end;;
+
+(* Bad: unboxed or untagged with the wrong type *)
+
+external g : (float [@untagged]) -> float = "g";;
+external h : (int [@unboxed]) -> float = "h";;
+
+(* This should be rejected, but it is quite complicated to do
+ in the current state of things *)
+
+external i : int -> float [@unboxed] = "i";;
+external j : int -> (float [@unboxed]) * float = "j";;
+external k : int -> (float [@unboxd]) = "k";;
diff --git a/testsuite/tests/typing-unboxed/test.ml.reference b/testsuite/tests/typing-unboxed/test.ml.reference
new file mode 100644
index 0000000000..cb70eaaa1e
--- /dev/null
+++ b/testsuite/tests/typing-unboxed/test.ml.reference
@@ -0,0 +1,129 @@
+
+# external a : (int [@untagged]) -> unit = "a"
+external b : (int32 [@unboxed]) -> unit = "b"
+external c : (int64 [@unboxed]) -> unit = "c"
+external d : (nativeint [@unboxed]) -> unit = "d"
+external e : (float [@unboxed]) -> unit = "e"
+type t = private int
+external f : (t [@untagged]) -> unit = "f"
+module M :
+ sig
+ external a : int -> (int [@untagged]) = "a"
+ external b : (int [@untagged]) -> int = "b"
+ end
+# Characters 110-166:
+ ......struct
+ external f : int -> (int [@untagged]) = "f"
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig external f : int -> (int [@untagged]) = "f" end
+ is not included in
+ sig external f : int -> int = "f" end
+ Values do not match:
+ external f : int -> (int [@untagged]) = "f"
+ is not included in
+ external f : int -> int = "f"
+# Characters 57-113:
+ ......struct
+ external f : (int [@untagged]) -> int = "f"
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig external f : (int [@untagged]) -> int = "f" end
+ is not included in
+ sig external f : int -> int = "a" end
+ Values do not match:
+ external f : (int [@untagged]) -> int = "f"
+ is not included in
+ external f : int -> int = "a"
+# Characters 61-120:
+ ......struct
+ external f : float -> (float [@unboxed]) = "f"
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig external f : float -> (float [@unboxed]) = "f" end
+ is not included in
+ sig external f : float -> float = "f" end
+ Values do not match:
+ external f : float -> (float [@unboxed]) = "f"
+ is not included in
+ external f : float -> float = "f"
+# Characters 61-120:
+ ......struct
+ external f : (float [@unboxed]) -> float = "f"
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig external f : (float [@unboxed]) -> float = "f" end
+ is not included in
+ sig external f : float -> float = "a" end
+ Values do not match:
+ external f : (float [@unboxed]) -> float = "f"
+ is not included in
+ external f : float -> float = "a"
+# Characters 141-183:
+ ......struct
+ external f : int -> int = "f"
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig external f : int -> int = "f" end
+ is not included in
+ sig external f : int -> (int [@untagged]) = "f" end
+ Values do not match:
+ external f : int -> int = "f"
+ is not included in
+ external f : int -> (int [@untagged]) = "f"
+# Characters 71-113:
+ ......struct
+ external f : int -> int = "a"
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig external f : int -> int = "a" end
+ is not included in
+ sig external f : (int [@untagged]) -> int = "f" end
+ Values do not match:
+ external f : int -> int = "a"
+ is not included in
+ external f : (int [@untagged]) -> int = "f"
+# Characters 74-120:
+ ......struct
+ external f : float -> float = "f"
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig external f : float -> float = "f" end
+ is not included in
+ sig external f : float -> (float [@unboxed]) = "f" end
+ Values do not match:
+ external f : float -> float = "f"
+ is not included in
+ external f : float -> (float [@unboxed]) = "f"
+# Characters 74-120:
+ ......struct
+ external f : float -> float = "a"
+ end..
+Error: Signature mismatch:
+ Modules do not match:
+ sig external f : float -> float = "a" end
+ is not included in
+ sig external f : (float [@unboxed]) -> float = "f" end
+ Values do not match:
+ external f : float -> float = "a"
+ is not included in
+ external f : (float [@unboxed]) -> float = "f"
+# Characters 67-72:
+ external g : (float [@untagged]) -> float = "g";;
+ ^^^^^
+Error: Don't know how to untag this type. Only int can be untagged
+# Characters 14-17:
+ external h : (int [@unboxed]) -> float = "h";;
+ ^^^
+Error: Don't know how to unbox this type. Only float, int32, int64 and nativeint can be unboxed
+# * external i : int -> float = "i"
+# external j : int -> float * float = "j"
+# external k : int -> float = "k"
+#
diff --git a/testsuite/tests/typing-warnings/Makefile b/testsuite/tests/typing-warnings/Makefile
new file mode 100644
index 0000000000..9d79c58e23
--- /dev/null
+++ b/testsuite/tests/typing-warnings/Makefile
@@ -0,0 +1,16 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+include $(BASEDIR)/makefiles/Makefile.toplevel
+include $(BASEDIR)/makefiles/Makefile.common
+TOPFLAGS = -w A
diff --git a/testsuite/tests/typing-warnings/coercions.ml b/testsuite/tests/typing-warnings/coercions.ml
new file mode 100644
index 0000000000..1ca390b28e
--- /dev/null
+++ b/testsuite/tests/typing-warnings/coercions.ml
@@ -0,0 +1,5 @@
+(* comment 9644 of PR#6000 *)
+
+fun b -> if b then format_of_string "x" else "y";;
+fun b -> if b then "x" else format_of_string "y";;
+fun b -> (if b then "x" else "y" : (_,_,_) format);;
diff --git a/testsuite/tests/typing-warnings/coercions.ml.principal.reference b/testsuite/tests/typing-warnings/coercions.ml.principal.reference
new file mode 100644
index 0000000000..d5397bf05e
--- /dev/null
+++ b/testsuite/tests/typing-warnings/coercions.ml.principal.reference
@@ -0,0 +1,15 @@
+
+# Characters 76-79:
+ fun b -> if b then format_of_string "x" else "y";;
+ ^^^
+Warning 18: this coercion to format6 is not principal.
+- : bool -> ('a, 'b, 'c, 'd, 'd, 'a) format6 = <fun>
+# Characters 28-48:
+ fun b -> if b then "x" else format_of_string "y";;
+ ^^^^^^^^^^^^^^^^^^^^
+Error: This expression has type
+ ('a, 'b, 'c, 'd, 'd, 'a) format6 =
+ ('a, 'b, 'c, 'd, 'd, 'a) CamlinternalFormatBasics.format6
+ but an expression was expected of type string
+# - : bool -> ('a, 'b, 'a) format = <fun>
+#
diff --git a/testsuite/tests/typing-warnings/coercions.ml.reference b/testsuite/tests/typing-warnings/coercions.ml.reference
new file mode 100644
index 0000000000..f442130510
--- /dev/null
+++ b/testsuite/tests/typing-warnings/coercions.ml.reference
@@ -0,0 +1,11 @@
+
+# - : bool -> ('a, 'b, 'c, 'd, 'd, 'a) format6 = <fun>
+# Characters 28-48:
+ fun b -> if b then "x" else format_of_string "y";;
+ ^^^^^^^^^^^^^^^^^^^^
+Error: This expression has type
+ ('a, 'b, 'c, 'd, 'd, 'a) format6 =
+ ('a, 'b, 'c, 'd, 'd, 'a) CamlinternalFormatBasics.format6
+ but an expression was expected of type string
+# - : bool -> ('a, 'b, 'a) format = <fun>
+#
diff --git a/testsuite/tests/typing-warnings/pr5892.ml b/testsuite/tests/typing-warnings/pr5892.ml
new file mode 100644
index 0000000000..bbc73b55dc
--- /dev/null
+++ b/testsuite/tests/typing-warnings/pr5892.ml
@@ -0,0 +1,3 @@
+open CamlinternalOO;;
+type _ choice = Left : label choice | Right : tag choice;;
+let f : label choice -> bool = function Left -> true;; (* warn *)
diff --git a/testsuite/tests/typing-warnings/pr5892.ml.reference b/testsuite/tests/typing-warnings/pr5892.ml.reference
new file mode 100644
index 0000000000..1321634aff
--- /dev/null
+++ b/testsuite/tests/typing-warnings/pr5892.ml.reference
@@ -0,0 +1,12 @@
+
+# # type _ choice =
+ Left : CamlinternalOO.label choice
+ | Right : CamlinternalOO.tag choice
+# Characters 31-52:
+ let f : label choice -> bool = function Left -> true;; (* warn *)
+ ^^^^^^^^^^^^^^^^^^^^^
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+Right
+val f : CamlinternalOO.label choice -> bool = <fun>
+#
diff --git a/testsuite/tests/typing-warnings/pr6872.ml b/testsuite/tests/typing-warnings/pr6872.ml
new file mode 100644
index 0000000000..283af4ccd4
--- /dev/null
+++ b/testsuite/tests/typing-warnings/pr6872.ml
@@ -0,0 +1,8 @@
+exception A;;
+type a = A;;
+
+A;;
+raise A;;
+fun (A : a) -> ();;
+function Not_found -> 1 | A -> 2 | _ -> 3;;
+try raise A with A -> 2;;
diff --git a/testsuite/tests/typing-warnings/pr6872.ml.principal.reference b/testsuite/tests/typing-warnings/pr6872.ml.principal.reference
new file mode 100644
index 0000000000..097e34f978
--- /dev/null
+++ b/testsuite/tests/typing-warnings/pr6872.ml.principal.reference
@@ -0,0 +1,35 @@
+
+# exception A
+# type a = A
+# Characters 1-2:
+ A;;
+ ^
+Warning 41: A belongs to several types: a exn
+The first one was selected. Please disambiguate if this is wrong.
+- : a = A
+# Characters 6-7:
+ raise A;;
+ ^
+Warning 42: this use of A required disambiguation.
+Exception: A.
+# - : a -> unit = <fun>
+# Characters 26-27:
+ function Not_found -> 1 | A -> 2 | _ -> 3;;
+ ^
+Warning 41: A belongs to several types: a exn
+The first one was selected. Please disambiguate if this is wrong.
+Characters 26-27:
+ function Not_found -> 1 | A -> 2 | _ -> 3;;
+ ^
+Error: This pattern matches values of type a
+ but a pattern was expected which matches values of type exn
+# Characters 10-11:
+ try raise A with A -> 2;;
+ ^
+Warning 42: this use of A required disambiguation.
+Characters 17-18:
+ try raise A with A -> 2;;
+ ^
+Warning 42: this use of A required disambiguation.
+- : int = 2
+#
diff --git a/testsuite/tests/typing-warnings/pr6872.ml.reference b/testsuite/tests/typing-warnings/pr6872.ml.reference
new file mode 100644
index 0000000000..072ccb4daa
--- /dev/null
+++ b/testsuite/tests/typing-warnings/pr6872.ml.reference
@@ -0,0 +1,30 @@
+
+# exception A
+# type a = A
+# Characters 1-2:
+ A;;
+ ^
+Warning 41: A belongs to several types: a exn
+The first one was selected. Please disambiguate if this is wrong.
+- : a = A
+# Characters 6-7:
+ raise A;;
+ ^
+Warning 42: this use of A required disambiguation.
+Exception: A.
+# - : a -> unit = <fun>
+# Characters 26-27:
+ function Not_found -> 1 | A -> 2 | _ -> 3;;
+ ^
+Warning 42: this use of A required disambiguation.
+- : exn -> int = <fun>
+# Characters 10-11:
+ try raise A with A -> 2;;
+ ^
+Warning 42: this use of A required disambiguation.
+Characters 17-18:
+ try raise A with A -> 2;;
+ ^
+Warning 42: this use of A required disambiguation.
+- : int = 2
+#
diff --git a/testsuite/tests/typing-warnings/records.ml b/testsuite/tests/typing-warnings/records.ml
new file mode 100644
index 0000000000..768bb965c5
--- /dev/null
+++ b/testsuite/tests/typing-warnings/records.ml
@@ -0,0 +1,180 @@
+(* Use type information *)
+module M1 = struct
+ type t = {x: int; y: int}
+ type u = {x: bool; y: bool}
+end;;
+
+module OK = struct
+ open M1
+ let f1 (r:t) = r.x (* ok *)
+ let f2 r = ignore (r:t); r.x (* non principal *)
+
+ let f3 (r: t) =
+ match r with {x; y} -> y + y (* ok *)
+end;;
+
+module F1 = struct
+ open M1
+ let f r = match r with {x; y} -> y + y
+end;; (* fails *)
+
+module F2 = struct
+ open M1
+ let f r =
+ ignore (r: t);
+ match r with
+ {x; y} -> y + y
+end;; (* fails for -principal *)
+
+(* Use type information with modules*)
+module M = struct
+ type t = {x:int}
+ type u = {x:bool}
+end;;
+let f (r:M.t) = r.M.x;; (* ok *)
+let f (r:M.t) = r.x;; (* warning *)
+let f ({x}:M.t) = x;; (* warning *)
+
+module M = struct
+ type t = {x: int; y: int}
+end;;
+module N = struct
+ type u = {x: bool; y: bool}
+end;;
+module OK = struct
+ open M
+ open N
+ let f (r:M.t) = r.x
+end;;
+
+module M = struct
+ type t = {x:int}
+ module N = struct type s = t = {x:int} end
+ type u = {x:bool}
+end;;
+module OK = struct
+ open M.N
+ let f (r:M.t) = r.x
+end;;
+
+(* Use field information *)
+module M = struct
+ type u = {x:bool;y:int;z:char}
+ type t = {x:int;y:bool}
+end;;
+module OK = struct
+ open M
+ let f {x;z} = x,z
+end;; (* ok *)
+module F3 = struct
+ open M
+ let r = {x=true;z='z'}
+end;; (* fail for missing label *)
+
+module OK = struct
+ type u = {x:int;y:bool}
+ type t = {x:bool;y:int;z:char}
+ let r = {x=3; y=true}
+end;; (* ok *)
+
+(* Corner cases *)
+
+module F4 = struct
+ type foo = {x:int; y:int}
+ type bar = {x:int}
+ let b : bar = {x=3; y=4}
+end;; (* fail but don't warn *)
+
+module M = struct type foo = {x:int;y:int} end;;
+module N = struct type bar = {x:int;y:int} end;;
+let r = { M.x = 3; N.y = 4; };; (* error: different definitions *)
+
+module MN = struct include M include N end
+module NM = struct include N include M end;;
+let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
+
+(* Lpw25 *)
+
+module M = struct
+ type foo = { x: int; y: int }
+ type bar = { x:int; y: int; z: int}
+end;;
+module F5 = struct
+ open M
+ let f r = ignore (r: foo); {r with x = 2; z = 3}
+end;;
+module M = struct
+ include M
+ type other = { a: int; b: int }
+end;;
+module F6 = struct
+ open M
+ let f r = ignore (r: foo); { r with x = 3; a = 4 }
+end;;
+module F7 = struct
+ open M
+ let r = {x=1; y=2}
+ let r: other = {x=1; y=2}
+end;;
+
+module A = struct type t = {x: int} end
+module B = struct type t = {x: int} end;;
+let f (r : B.t) = r.A.x;; (* fail *)
+
+(* Spellchecking *)
+
+module F8 = struct
+ type t = {x:int; yyy:int}
+ let a : t = {x=1;yyz=2}
+end;;
+
+(* PR#6004 *)
+
+type t = A
+type s = A
+
+class f (_ : t) = object end;;
+class g = f A;; (* ok *)
+
+class f (_ : 'a) (_ : 'a) = object end;;
+class g = f (A : t) A;; (* warn with -principal *)
+
+
+(* PR#5980 *)
+
+module Shadow1 = struct
+ type t = {x: int}
+ module M = struct
+ type s = {x: string}
+ end
+ open M (* this open is unused, it isn't reported as shadowing 'x' *)
+ let y : t = {x = 0}
+end;;
+module Shadow2 = struct
+ type t = {x: int}
+ module M = struct
+ type s = {x: string}
+ end
+ open M (* this open shadows label 'x' *)
+ let y = {x = ""}
+end;;
+
+(* PR#6235 *)
+
+module P6235 = struct
+ type t = { loc : string; }
+ type v = { loc : string; x : int; }
+ type u = [ `Key of t ]
+ let f (u : u) = match u with `Key {loc} -> loc
+end;;
+
+(* Remove interaction between branches *)
+
+module P6235' = struct
+ type t = { loc : string; }
+ type v = { loc : string; x : int; }
+ type u = [ `Key of t ]
+ let f = function
+ | (_ : u) when false -> ""
+ |`Key {loc} -> loc
+end;;
diff --git a/testsuite/tests/typing-warnings/records.ml.principal.reference b/testsuite/tests/typing-warnings/records.ml.principal.reference
new file mode 100644
index 0000000000..c208dee25d
--- /dev/null
+++ b/testsuite/tests/typing-warnings/records.ml.principal.reference
@@ -0,0 +1,301 @@
+
+# module M1 :
+ sig type t = { x : int; y : int; } type u = { x : bool; y : bool; } end
+# Characters 49-50:
+ let f1 (r:t) = r.x (* ok *)
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 89-90:
+ let f2 r = ignore (r:t); r.x (* non principal *)
+ ^
+Warning 18: this type-based field disambiguation is not principal.
+Characters 89-90:
+ let f2 r = ignore (r:t); r.x (* non principal *)
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 148-149:
+ match r with {x; y} -> y + y (* ok *)
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 151-152:
+ match r with {x; y} -> y + y (* ok *)
+ ^
+Warning 42: this use of y required disambiguation.
+Characters 148-149:
+ match r with {x; y} -> y + y (* ok *)
+ ^
+Warning 27: unused variable x.
+module OK :
+ sig val f1 : M1.t -> int val f2 : M1.t -> int val f3 : M1.t -> int end
+# Characters 55-61:
+ let f r = match r with {x; y} -> y + y
+ ^^^^^^
+Warning 41: these field labels belong to several types: M1.u M1.t
+The first one was selected. Please disambiguate if this is wrong.
+Characters 65-66:
+ let f r = match r with {x; y} -> y + y
+ ^
+Error: This expression has type bool but an expression was expected of type
+ int
+# Characters 85-91:
+ {x; y} -> y + y
+ ^^^^^^
+Warning 41: these field labels belong to several types: M1.u M1.t
+The first one was selected. Please disambiguate if this is wrong.
+Characters 85-91:
+ {x; y} -> y + y
+ ^^^^^^
+Error: This pattern matches values of type M1.u
+ but a pattern was expected which matches values of type M1.t
+# module M : sig type t = { x : int; } type u = { x : bool; } end
+# Characters 18-21:
+ let f (r:M.t) = r.M.x;; (* ok *)
+ ^^^
+Warning 42: this use of x required disambiguation.
+val f : M.t -> int = <fun>
+# Characters 18-19:
+ let f (r:M.t) = r.x;; (* warning *)
+ ^
+Warning 40: x was selected from type M.t.
+It is not visible in the current scope, and will not
+be selected if the type becomes unknown.
+Characters 18-19:
+ let f (r:M.t) = r.x;; (* warning *)
+ ^
+Warning 42: this use of x required disambiguation.
+val f : M.t -> int = <fun>
+# Characters 8-9:
+ let f ({x}:M.t) = x;; (* warning *)
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 7-10:
+ let f ({x}:M.t) = x;; (* warning *)
+ ^^^
+Warning 40: this record of type M.t contains fields that are
+not visible in the current scope: x.
+They will not be selected if the type becomes unknown.
+val f : M.t -> int = <fun>
+# module M : sig type t = { x : int; y : int; } end
+# module N : sig type u = { x : bool; y : bool; } end
+# Characters 57-58:
+ let f (r:M.t) = r.x
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 30-36:
+ open N
+ ^^^^^^
+Warning 33: unused open N.
+module OK : sig val f : M.t -> int end
+# module M :
+ sig
+ type t = { x : int; }
+ module N : sig type s = t = { x : int; } end
+ type u = { x : bool; }
+ end
+# module OK : sig val f : M.t -> int end
+# module M :
+ sig
+ type u = { x : bool; y : int; z : char; }
+ type t = { x : int; y : bool; }
+ end
+# Characters 37-38:
+ let f {x;z} = x,z
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 36-41:
+ let f {x;z} = x,z
+ ^^^^^
+Warning 9: the following labels are not bound in this record pattern:
+y
+Either bind these labels explicitly or add '; _' to the pattern.
+module OK : sig val f : M.u -> bool * char end
+# Characters 38-52:
+ let r = {x=true;z='z'}
+ ^^^^^^^^^^^^^^
+Error: Some record fields are undefined: y
+# Characters 90-91:
+ let r = {x=3; y=true}
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 95-96:
+ let r = {x=3; y=true}
+ ^
+Warning 42: this use of y required disambiguation.
+module OK :
+ sig
+ type u = { x : int; y : bool; }
+ type t = { x : bool; y : int; z : char; }
+ val r : u
+ end
+# Characters 111-112:
+ let b : bar = {x=3; y=4}
+ ^
+Error: This record expression is expected to have type bar
+ The field y does not belong to type bar
+# module M : sig type foo = { x : int; y : int; } end
+# module N : sig type bar = { x : int; y : int; } end
+# Characters 19-22:
+ let r = { M.x = 3; N.y = 4; };; (* error: different definitions *)
+ ^^^
+Error: The record field N.y belongs to the type N.bar
+ but is mixed here with fields of type M.foo
+# module MN :
+ sig
+ type foo = M.foo = { x : int; y : int; }
+ type bar = N.bar = { x : int; y : int; }
+ end
+module NM :
+ sig
+ type bar = N.bar = { x : int; y : int; }
+ type foo = M.foo = { x : int; y : int; }
+ end
+# Characters 8-28:
+ let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
+ ^^^^^^^^^^^^^^^^^^^^
+Warning 41: x belongs to several types: MN.bar MN.foo
+The first one was selected. Please disambiguate if this is wrong.
+Characters 8-28:
+ let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
+ ^^^^^^^^^^^^^^^^^^^^
+Warning 41: y belongs to several types: NM.foo NM.bar
+The first one was selected. Please disambiguate if this is wrong.
+Characters 19-23:
+ let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
+ ^^^^
+Error: The record field NM.y belongs to the type NM.foo = M.foo
+ but is mixed here with fields of type MN.bar = N.bar
+# module M :
+ sig
+ type foo = { x : int; y : int; }
+ type bar = { x : int; y : int; z : int; }
+ end
+# Characters 65-66:
+ let f r = ignore (r: foo); {r with x = 2; z = 3}
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 72-73:
+ let f r = ignore (r: foo); {r with x = 2; z = 3}
+ ^
+Error: This record expression is expected to have type M.foo
+ The field z does not belong to type M.foo
+# module M :
+ sig
+ type foo = M.foo = { x : int; y : int; }
+ type bar = M.bar = { x : int; y : int; z : int; }
+ type other = { a : int; b : int; }
+ end
+# Characters 66-67:
+ let f r = ignore (r: foo); { r with x = 3; a = 4 }
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 73-74:
+ let f r = ignore (r: foo); { r with x = 3; a = 4 }
+ ^
+Error: This record expression is expected to have type M.foo
+ The field a does not belong to type M.foo
+# Characters 39-40:
+ let r = {x=1; y=2}
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 44-45:
+ let r = {x=1; y=2}
+ ^
+Warning 42: this use of y required disambiguation.
+Characters 67-68:
+ let r: other = {x=1; y=2}
+ ^
+Error: This record expression is expected to have type M.other
+ The field x does not belong to type M.other
+# module A : sig type t = { x : int; } end
+module B : sig type t = { x : int; } end
+# Characters 20-23:
+ let f (r : B.t) = r.A.x;; (* fail *)
+ ^^^
+Error: The field A.x belongs to the record type A.t
+ but a field was expected belonging to the record type B.t
+# Characters 88-91:
+ let a : t = {x=1;yyz=2}
+ ^^^
+Error: This record expression is expected to have type t
+ The field yyz does not belong to type t
+Hint: Did you mean yyy?
+# type t = A
+type s = A
+class f : t -> object end
+# Characters 12-13:
+ class g = f A;; (* ok *)
+ ^
+Warning 42: this use of A required disambiguation.
+class g : f
+# class f : 'a -> 'a -> object end
+# Characters 13-14:
+ class g = f (A : t) A;; (* warn with -principal *)
+ ^
+Warning 42: this use of A required disambiguation.
+Characters 20-21:
+ class g = f (A : t) A;; (* warn with -principal *)
+ ^
+Warning 18: this type-based constructor disambiguation is not principal.
+Characters 20-21:
+ class g = f (A : t) A;; (* warn with -principal *)
+ ^
+Warning 42: this use of A required disambiguation.
+class g : f
+# Characters 199-200:
+ let y : t = {x = 0}
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 114-120:
+ open M (* this open is unused, it isn't reported as shadowing 'x' *)
+ ^^^^^^
+Warning 33: unused open M.
+module Shadow1 :
+ sig
+ type t = { x : int; }
+ module M : sig type s = { x : string; } end
+ val y : t
+ end
+# Characters 97-103:
+ open M (* this open shadows label 'x' *)
+ ^^^^^^
+Warning 45: this open statement shadows the label x (which is later used)
+Characters 149-157:
+ let y = {x = ""}
+ ^^^^^^^^
+Warning 41: these field labels belong to several types: M.s t
+The first one was selected. Please disambiguate if this is wrong.
+module Shadow2 :
+ sig
+ type t = { x : int; }
+ module M : sig type s = { x : string; } end
+ val y : M.s
+ end
+# Characters 167-170:
+ let f (u : u) = match u with `Key {loc} -> loc
+ ^^^
+Warning 42: this use of loc required disambiguation.
+module P6235 :
+ sig
+ type t = { loc : string; }
+ type v = { loc : string; x : int; }
+ type u = [ `Key of t ]
+ val f : u -> string
+ end
+# Characters 219-224:
+ |`Key {loc} -> loc
+ ^^^^^
+Warning 41: these field labels belong to several types: v t
+The first one was selected. Please disambiguate if this is wrong.
+Characters 219-224:
+ |`Key {loc} -> loc
+ ^^^^^
+Warning 9: the following labels are not bound in this record pattern:
+x
+Either bind these labels explicitly or add '; _' to the pattern.
+Characters 214-224:
+ |`Key {loc} -> loc
+ ^^^^^^^^^^
+Error: This pattern matches values of type [? `Key of v ]
+ but a pattern was expected which matches values of type u
+ Types for tag `Key are incompatible
+#
diff --git a/testsuite/tests/typing-warnings/records.ml.reference b/testsuite/tests/typing-warnings/records.ml.reference
new file mode 100644
index 0000000000..2853439c65
--- /dev/null
+++ b/testsuite/tests/typing-warnings/records.ml.reference
@@ -0,0 +1,290 @@
+
+# module M1 :
+ sig type t = { x : int; y : int; } type u = { x : bool; y : bool; } end
+# Characters 49-50:
+ let f1 (r:t) = r.x (* ok *)
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 89-90:
+ let f2 r = ignore (r:t); r.x (* non principal *)
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 148-149:
+ match r with {x; y} -> y + y (* ok *)
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 151-152:
+ match r with {x; y} -> y + y (* ok *)
+ ^
+Warning 42: this use of y required disambiguation.
+Characters 148-149:
+ match r with {x; y} -> y + y (* ok *)
+ ^
+Warning 27: unused variable x.
+module OK :
+ sig val f1 : M1.t -> int val f2 : M1.t -> int val f3 : M1.t -> int end
+# Characters 55-61:
+ let f r = match r with {x; y} -> y + y
+ ^^^^^^
+Warning 41: these field labels belong to several types: M1.u M1.t
+The first one was selected. Please disambiguate if this is wrong.
+Characters 65-66:
+ let f r = match r with {x; y} -> y + y
+ ^
+Error: This expression has type bool but an expression was expected of type
+ int
+# Characters 86-87:
+ {x; y} -> y + y
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 89-90:
+ {x; y} -> y + y
+ ^
+Warning 42: this use of y required disambiguation.
+Characters 86-87:
+ {x; y} -> y + y
+ ^
+Warning 27: unused variable x.
+module F2 : sig val f : M1.t -> int end
+# module M : sig type t = { x : int; } type u = { x : bool; } end
+# Characters 18-21:
+ let f (r:M.t) = r.M.x;; (* ok *)
+ ^^^
+Warning 42: this use of x required disambiguation.
+val f : M.t -> int = <fun>
+# Characters 18-19:
+ let f (r:M.t) = r.x;; (* warning *)
+ ^
+Warning 40: x was selected from type M.t.
+It is not visible in the current scope, and will not
+be selected if the type becomes unknown.
+Characters 18-19:
+ let f (r:M.t) = r.x;; (* warning *)
+ ^
+Warning 42: this use of x required disambiguation.
+val f : M.t -> int = <fun>
+# Characters 8-9:
+ let f ({x}:M.t) = x;; (* warning *)
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 7-10:
+ let f ({x}:M.t) = x;; (* warning *)
+ ^^^
+Warning 40: this record of type M.t contains fields that are
+not visible in the current scope: x.
+They will not be selected if the type becomes unknown.
+val f : M.t -> int = <fun>
+# module M : sig type t = { x : int; y : int; } end
+# module N : sig type u = { x : bool; y : bool; } end
+# Characters 57-58:
+ let f (r:M.t) = r.x
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 30-36:
+ open N
+ ^^^^^^
+Warning 33: unused open N.
+module OK : sig val f : M.t -> int end
+# module M :
+ sig
+ type t = { x : int; }
+ module N : sig type s = t = { x : int; } end
+ type u = { x : bool; }
+ end
+# module OK : sig val f : M.t -> int end
+# module M :
+ sig
+ type u = { x : bool; y : int; z : char; }
+ type t = { x : int; y : bool; }
+ end
+# Characters 37-38:
+ let f {x;z} = x,z
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 36-41:
+ let f {x;z} = x,z
+ ^^^^^
+Warning 9: the following labels are not bound in this record pattern:
+y
+Either bind these labels explicitly or add '; _' to the pattern.
+module OK : sig val f : M.u -> bool * char end
+# Characters 38-52:
+ let r = {x=true;z='z'}
+ ^^^^^^^^^^^^^^
+Error: Some record fields are undefined: y
+# Characters 90-91:
+ let r = {x=3; y=true}
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 95-96:
+ let r = {x=3; y=true}
+ ^
+Warning 42: this use of y required disambiguation.
+module OK :
+ sig
+ type u = { x : int; y : bool; }
+ type t = { x : bool; y : int; z : char; }
+ val r : u
+ end
+# Characters 111-112:
+ let b : bar = {x=3; y=4}
+ ^
+Error: This record expression is expected to have type bar
+ The field y does not belong to type bar
+# module M : sig type foo = { x : int; y : int; } end
+# module N : sig type bar = { x : int; y : int; } end
+# Characters 19-22:
+ let r = { M.x = 3; N.y = 4; };; (* error: different definitions *)
+ ^^^
+Error: The record field N.y belongs to the type N.bar
+ but is mixed here with fields of type M.foo
+# module MN :
+ sig
+ type foo = M.foo = { x : int; y : int; }
+ type bar = N.bar = { x : int; y : int; }
+ end
+module NM :
+ sig
+ type bar = N.bar = { x : int; y : int; }
+ type foo = M.foo = { x : int; y : int; }
+ end
+# Characters 8-28:
+ let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
+ ^^^^^^^^^^^^^^^^^^^^
+Warning 41: x belongs to several types: MN.bar MN.foo
+The first one was selected. Please disambiguate if this is wrong.
+Characters 8-28:
+ let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
+ ^^^^^^^^^^^^^^^^^^^^
+Warning 41: y belongs to several types: NM.foo NM.bar
+The first one was selected. Please disambiguate if this is wrong.
+Characters 19-23:
+ let r = {MN.x = 3; NM.y = 4};; (* error: type would change with order *)
+ ^^^^
+Error: The record field NM.y belongs to the type NM.foo = M.foo
+ but is mixed here with fields of type MN.bar = N.bar
+# module M :
+ sig
+ type foo = { x : int; y : int; }
+ type bar = { x : int; y : int; z : int; }
+ end
+# Characters 65-66:
+ let f r = ignore (r: foo); {r with x = 2; z = 3}
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 72-73:
+ let f r = ignore (r: foo); {r with x = 2; z = 3}
+ ^
+Error: This record expression is expected to have type M.foo
+ The field z does not belong to type M.foo
+# module M :
+ sig
+ type foo = M.foo = { x : int; y : int; }
+ type bar = M.bar = { x : int; y : int; z : int; }
+ type other = { a : int; b : int; }
+ end
+# Characters 66-67:
+ let f r = ignore (r: foo); { r with x = 3; a = 4 }
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 73-74:
+ let f r = ignore (r: foo); { r with x = 3; a = 4 }
+ ^
+Error: This record expression is expected to have type M.foo
+ The field a does not belong to type M.foo
+# Characters 39-40:
+ let r = {x=1; y=2}
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 44-45:
+ let r = {x=1; y=2}
+ ^
+Warning 42: this use of y required disambiguation.
+Characters 67-68:
+ let r: other = {x=1; y=2}
+ ^
+Error: This record expression is expected to have type M.other
+ The field x does not belong to type M.other
+# module A : sig type t = { x : int; } end
+module B : sig type t = { x : int; } end
+# Characters 20-23:
+ let f (r : B.t) = r.A.x;; (* fail *)
+ ^^^
+Error: The field A.x belongs to the record type A.t
+ but a field was expected belonging to the record type B.t
+# Characters 88-91:
+ let a : t = {x=1;yyz=2}
+ ^^^
+Error: This record expression is expected to have type t
+ The field yyz does not belong to type t
+Hint: Did you mean yyy?
+# type t = A
+type s = A
+class f : t -> object end
+# Characters 12-13:
+ class g = f A;; (* ok *)
+ ^
+Warning 42: this use of A required disambiguation.
+class g : f
+# class f : 'a -> 'a -> object end
+# Characters 13-14:
+ class g = f (A : t) A;; (* warn with -principal *)
+ ^
+Warning 42: this use of A required disambiguation.
+Characters 20-21:
+ class g = f (A : t) A;; (* warn with -principal *)
+ ^
+Warning 42: this use of A required disambiguation.
+class g : f
+# Characters 199-200:
+ let y : t = {x = 0}
+ ^
+Warning 42: this use of x required disambiguation.
+Characters 114-120:
+ open M (* this open is unused, it isn't reported as shadowing 'x' *)
+ ^^^^^^
+Warning 33: unused open M.
+module Shadow1 :
+ sig
+ type t = { x : int; }
+ module M : sig type s = { x : string; } end
+ val y : t
+ end
+# Characters 97-103:
+ open M (* this open shadows label 'x' *)
+ ^^^^^^
+Warning 45: this open statement shadows the label x (which is later used)
+Characters 149-157:
+ let y = {x = ""}
+ ^^^^^^^^
+Warning 41: these field labels belong to several types: M.s t
+The first one was selected. Please disambiguate if this is wrong.
+module Shadow2 :
+ sig
+ type t = { x : int; }
+ module M : sig type s = { x : string; } end
+ val y : M.s
+ end
+# Characters 167-170:
+ let f (u : u) = match u with `Key {loc} -> loc
+ ^^^
+Warning 42: this use of loc required disambiguation.
+module P6235 :
+ sig
+ type t = { loc : string; }
+ type v = { loc : string; x : int; }
+ type u = [ `Key of t ]
+ val f : u -> string
+ end
+# Characters 220-223:
+ |`Key {loc} -> loc
+ ^^^
+Warning 42: this use of loc required disambiguation.
+module P6235' :
+ sig
+ type t = { loc : string; }
+ type v = { loc : string; x : int; }
+ type u = [ `Key of t ]
+ val f : u -> string
+ end
+#
diff --git a/testsuite/tests/typing-warnings/unused_types.ml b/testsuite/tests/typing-warnings/unused_types.ml
new file mode 100644
index 0000000000..afe7d4cf16
--- /dev/null
+++ b/testsuite/tests/typing-warnings/unused_types.ml
@@ -0,0 +1,18 @@
+module Unused : sig
+end = struct
+ type unused = int
+end
+;;
+
+module Unused_nonrec : sig
+end = struct
+ type nonrec used = int
+ type nonrec unused = used
+end
+;;
+
+module Unused_rec : sig
+end = struct
+ type unused = A of unused
+end
+;;
diff --git a/testsuite/tests/typing-warnings/unused_types.ml.reference b/testsuite/tests/typing-warnings/unused_types.ml.reference
new file mode 100644
index 0000000000..d515c24e47
--- /dev/null
+++ b/testsuite/tests/typing-warnings/unused_types.ml.reference
@@ -0,0 +1,21 @@
+
+# Characters 35-52:
+ type unused = int
+ ^^^^^^^^^^^^^^^^^
+Warning 34: unused type unused.
+module Unused : sig end
+# Characters 68-93:
+ type nonrec unused = used
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 34: unused type unused.
+module Unused_nonrec : sig end
+# Characters 40-65:
+ type unused = A of unused
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 34: unused type unused.
+Characters 40-65:
+ type unused = A of unused
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
+Warning 37: unused constructor A.
+module Unused_rec : sig end
+#
diff --git a/testsuite/tests/unboxed-primitive-args/Makefile b/testsuite/tests/unboxed-primitive-args/Makefile
new file mode 100644
index 0000000000..cda32a72f6
--- /dev/null
+++ b/testsuite/tests/unboxed-primitive-args/Makefile
@@ -0,0 +1,36 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Jeremie Dimino, Jane Street Europe #
+# #
+# Copyright 2015 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+LIBRARIES=unix bigarray
+MODULES=common
+MAIN_MODULE=main
+C_FILES=test_common stubs
+ADD_COMPFLAGS=-I $(OTOPDIR)/otherlibs/bigarray \
+ -I $(OTOPDIR)/otherlibs/$(UNIXLIB)
+
+include $(BASEDIR)/makefiles/Makefile.one
+include $(BASEDIR)/makefiles/Makefile.common
+
+NATIVECODE_ONLY=true
+NATIVECCCOMPOPTS+=-I $(OTOPDIR)/otherlibs/bigarray
+GENERATED_SOURCES+=main.ml stubs.c
+
+main.ml: gen_test.ml
+ @$(OCAML) gen_test.ml ml > $@
+
+stubs.c: gen_test.ml
+ @$(OCAML) gen_test.ml c > $@
+
+common.cmx: common.cmi
+
+compile: stubs.c
diff --git a/testsuite/tests/unboxed-primitive-args/README b/testsuite/tests/unboxed-primitive-args/README
new file mode 100644
index 0000000000..4bd7601e51
--- /dev/null
+++ b/testsuite/tests/unboxed-primitive-args/README
@@ -0,0 +1,26 @@
+This directory contains tests to check that OCaml values are correctly
+passed between OCaml and C when a primitive takes some or all of its
+arguments unboxed/untagged and/or return its result unboxed/untagged.
+
+To test one primitive we do:
+- write all its argument and expected result in buffer A
+- call the C external using arguments read from buffer A
+- the C function write all the arguments it receive into buffer B
+- the C function read the result from buffer A and returns it
+- on the OCaml side we write the received result into buffer B
+- the test is successful if A and B have the same contents
+
+Between each call, we call a function with 128 value arguments set to
+0 and a function with 32 unboxed float arguments set to 0., just to
+clean-up the registers and stacks in case garbage would make a test
+succeed. We don't pass more floats as it doesn't build on arm32.
+
+We construct the set of primitives to test as follow:
+- all combination of unboxed int32/int64/float arguments for functions
+ taking up to 6 arguments (with more than 6 ocamlopt takes a really
+ long time to compile the test files)
+- a bunch of manual tests for the rest and specific patterns.
+ The list is [Gen_test.manual_tests]
+
+We test the set of primitives a thousand times, with different random
+data each time.
diff --git a/testsuite/tests/unboxed-primitive-args/common.ml b/testsuite/tests/unboxed-primitive-args/common.ml
new file mode 100644
index 0000000000..52b5ef992b
--- /dev/null
+++ b/testsuite/tests/unboxed-primitive-args/common.ml
@@ -0,0 +1,298 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jeremie Dimino, Jane Street Europe *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open StdLabels
+
+open Bigarray
+
+type 'a typ =
+ | Int : int typ
+ | Int32 : int32 typ
+ | Int64 : int64 typ
+ | Nativeint : nativeint typ
+ | Float : float typ
+
+type 'a proto =
+ | Ret : 'a typ -> 'a proto
+ | Abs : 'a typ * 'b proto -> ('a -> 'b) proto
+
+let ( ** ) x y = Abs (x, y)
+
+(* This form is easier to process programmatically. We don't expose it as
+ ocamlopt takes a really really long time to compile a constant list
+ of these. *)
+type simplified_test = Test : string * 'a * 'a proto -> simplified_test
+
+type test =
+ | T1 : string * ('a -> 'b) * 'a typ * 'b typ -> test
+ | T2 : string * ('a -> 'b -> 'c) * 'a typ * 'b typ * 'c typ -> test
+ | T3 : string * ('a -> 'b -> 'c -> 'd) *
+ 'a typ * 'b typ * 'c typ * 'd typ -> test
+ | T4 : string * ('a -> 'b -> 'c -> 'd -> 'e) *
+ 'a typ * 'b typ * 'c typ * 'd typ * 'e typ -> test
+ | T5 : string * ('a -> 'b -> 'c -> 'd -> 'e -> 'f) *
+ 'a typ * 'b typ * 'c typ * 'd typ * 'e typ * 'f typ -> test
+ | T6 : string * ('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g) *
+ 'a typ * 'b typ * 'c typ * 'd typ * 'e typ * 'f typ * 'g typ -> test
+ | T : string * 'a * 'a proto -> test
+
+let expand_test = function
+ | T1 (s, fn, a, b) -> Test (s, fn, a ** Ret b)
+ | T2 (s, fn, a, b, c) -> Test (s, fn, a ** b ** Ret c)
+ | T3 (s, fn, a, b, c, d) -> Test (s, fn, a ** b ** c ** Ret d)
+ | T4 (s, fn, a, b, c, d, e) -> Test (s, fn, a ** b ** c ** d ** Ret e)
+ | T5 (s, fn, a, b, c, d, e, f) ->
+ Test (s, fn, a ** b ** c ** d ** e ** Ret f)
+ | T6 (s, fn, a, b, c, d, e, f, g) ->
+ Test (s, fn, a ** b ** c ** d ** e ** f ** Ret g)
+ | T (s, fn, p) -> Test (s, fn, p)
+
+let string_of : type a. a typ -> a -> string = function
+ | Int -> string_of_int
+ | Int32 -> Printf.sprintf "%ldl"
+ | Int64 -> Printf.sprintf "%LdL"
+ | Nativeint -> Printf.sprintf "%ndn"
+ | Float ->
+ fun f -> Printf.sprintf "float_of_bits 0x%LxL" (Int64.bits_of_float f)
+
+let rec arity : type a. a proto -> int = function
+ | Ret _ -> 0
+ | Abs (_, p) -> 1 + arity p
+
+module Buffer = struct
+ type t = (char, int8_unsigned_elt, c_layout) Array1.t
+
+ let arg_size = 8
+
+ let create ~arity : t =
+ Array1.create char c_layout ((arity + 1) * arg_size)
+
+ let clear (t : t) = Array1.fill t '\000'
+
+ let length : t -> int = Array1.dim
+
+ external init_c_side : ocaml_buffer:t -> c_buffer:t -> unit
+ = "test_set_buffers"
+
+ external get_int32 : t -> int -> int32 = "%caml_bigstring_get32"
+ external get_int64 : t -> int -> int64 = "%caml_bigstring_get64"
+ external set_int32 : t -> int -> int32 -> unit = "%caml_bigstring_set32"
+ external set_int64 : t -> int -> int64 -> unit = "%caml_bigstring_set64"
+
+ let get_int32 t ~arg = get_int32 t (arg * arg_size)
+ let get_int64 t ~arg = get_int64 t (arg * arg_size)
+ let set_int32 t ~arg x = set_int32 t (arg * arg_size) x
+ let set_int64 t ~arg x = set_int64 t (arg * arg_size) x
+
+ let get_nativeint, set_nativeint =
+ match Sys.word_size with
+ | 32 -> ((fun t ~arg -> get_int32 t ~arg |> Nativeint.of_int32),
+ (fun t ~arg x -> set_int32 t ~arg (Nativeint.to_int32 x)))
+ | 64 -> ((fun t ~arg -> get_int64 t ~arg |> Int64.to_nativeint),
+ (fun t ~arg x -> set_int64 t ~arg (Int64.of_nativeint x)))
+ | n -> Printf.ksprintf failwith "unknown word size (%d)" n
+
+ let get_int =
+ if Sys.word_size = 32 then
+ fun buf ~arg -> get_int32 buf ~arg |> Int32.to_int
+ else
+ fun buf ~arg -> get_int64 buf ~arg |> Int64.to_int
+
+ let set_int =
+ if Sys.word_size = 32 then
+ fun buf ~arg x -> set_int32 buf ~arg (Int32.of_int x)
+ else
+ fun buf ~arg x -> set_int64 buf ~arg (Int64.of_int x)
+
+ let get_float buf ~arg = get_int64 buf ~arg |> Int64.float_of_bits
+ let set_float buf ~arg x = set_int64 buf ~arg (Int64.bits_of_float x)
+
+ let get : type a. a typ -> t -> arg:int -> a = function
+ | Int -> get_int
+ | Int32 -> get_int32
+ | Int64 -> get_int64
+ | Nativeint -> get_nativeint
+ | Float -> get_float
+
+ let set : type a. a typ -> t -> arg:int -> a -> unit = function
+ | Int -> set_int
+ | Int32 -> set_int32
+ | Int64 -> set_int64
+ | Nativeint -> set_nativeint
+ | Float -> set_float
+
+ (* This is almost a memcpy except that we use get/set which should
+ ensure that the values in [dst] don't overflow. *)
+ let copy_args ~src ~dst proto =
+ let rec loop : type a. a proto -> int -> unit = fun proto arg ->
+ match proto with
+ | Ret typ ->
+ set typ dst ~arg (get typ src ~arg)
+ | Abs (typ, rest) ->
+ set typ dst ~arg (get typ src ~arg);
+ loop rest (arg + 1)
+ in
+ loop proto 0
+end
+
+let exec proto f ~ocaml_buffer ~c_buffer =
+ let rec loop : type a. a proto -> a -> int -> unit = fun proto f arg ->
+ match proto with
+ | Ret typ ->
+ Buffer.set typ c_buffer ~arg f
+ | Abs (typ, rest) ->
+ let x = Buffer.get typ ocaml_buffer ~arg in
+ loop rest (f x) (arg + 1)
+ in
+ loop proto f 0
+
+let strings_of_test_instance name proto buffer =
+ let rec loop : type a. a proto -> int -> string list -> string list * string =
+ fun proto arg acc ->
+ match proto with
+ | Ret typ ->
+ (List.rev acc, string_of typ (Buffer.get typ buffer ~arg))
+ | Abs (typ, rest) ->
+ let s = string_of typ (Buffer.get typ buffer ~arg) in
+ loop rest (arg + 1) (s :: acc)
+ in
+ loop proto 0 []
+
+let typ_size : type a. a typ -> int = function
+ | Int -> Sys.word_size / 8
+ | Int32 -> 4
+ | Int64 -> 8
+ | Nativeint -> Sys.word_size / 8
+ | Float -> 8
+
+let rec sizes : type a. a proto -> int list = function
+ | Ret typ -> [typ_size typ]
+ | Abs (typ, rest) -> typ_size typ :: sizes rest
+
+let print_hex ~sizes ~arity buffer =
+ let printf = Printf.printf in
+ printf "(";
+ for i = 0 to arity do
+ if i = arity then
+ printf ") -> "
+ else if i > 0 then
+ printf ", ";
+ for ofs = i * Buffer.arg_size to i * Buffer.arg_size + sizes.(i) - 1 do
+ printf "%02x" (Char.code buffer.{ofs});
+ done;
+ done
+
+let printed_mismatches = ref 0
+
+let print_mismatch name proto ~ocaml_buffer ~c_buffer =
+ let printf = Printf.printf in
+ printf "Mismatch for %s\n" name;
+ let o_args, o_res = strings_of_test_instance name proto ocaml_buffer in
+ let c_args, c_res = strings_of_test_instance name proto c_buffer in
+ let o_args, c_args =
+ (* Align arguments *)
+ List.map2 o_args c_args ~f:(fun a b ->
+ let len_a = String.length a and len_b = String.length b in
+ let len = max len_a len_b in
+ (Printf.sprintf "%*s" len a,
+ Printf.sprintf "%*s" len b))
+ |> List.split
+ in
+ printf "ocaml side : (%s) -> %s\n" (String.concat ~sep:", " o_args) o_res;
+ printf "c side : (%s) -> %s\n" (String.concat ~sep:", " c_args) c_res;
+ let sizes = sizes proto |> Array.of_list in
+ let arity = arity proto in
+ printf "ocaml side : "; print_hex ~sizes ~arity ocaml_buffer; printf "\n";
+ printf "c side : "; print_hex ~sizes ~arity c_buffer; printf "\n";
+ incr printed_mismatches;
+ if !printed_mismatches >= 1000 then begin
+ printf "Output truncated at 1000 failures.";
+ exit 0
+ end
+
+external cleanup_normal
+ : int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int -> int -> int -> int -> int -> int -> int -> int
+ -> int = "" "noalloc" "test_cleanup_normal"
+
+external cleanup_float
+ : float -> float -> float -> float -> float -> float -> float -> float
+ -> float -> float -> float -> float -> float -> float -> float -> float
+ -> float -> float -> float -> float -> float -> float -> float -> float
+ -> float -> float -> float -> float -> float -> float -> float -> float
+ -> float = "" "noalloc" "test_cleanup_normal" "float"
+
+let cleanup_args_and_stack () =
+ let _ : int =
+ cleanup_normal
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+ in
+ let _ : float =
+ cleanup_float
+ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
+ in
+ ()
+
+let run_test ~random_data ~ocaml_buffer ~c_buffer (Test (name, f, proto)) =
+ Buffer.clear ocaml_buffer;
+ Buffer.clear c_buffer;
+ Buffer.copy_args ~src:random_data ~dst:ocaml_buffer proto;
+ cleanup_args_and_stack ();
+ exec proto f ~ocaml_buffer ~c_buffer;
+ let success = ocaml_buffer = c_buffer in
+ if not success then print_mismatch name proto ~ocaml_buffer ~c_buffer;
+ success
+
+let run_tests tests =
+ let tests = List.map tests ~f:expand_test in
+ let max_args =
+ List.fold_left tests ~init:0 ~f:(fun acc (Test (_, _, p)) ->
+ max acc (arity p))
+ in
+
+ let ocaml_buffer = Buffer.create ~arity:max_args
+ and c_buffer = Buffer.create ~arity:max_args in
+ Buffer.init_c_side ~ocaml_buffer ~c_buffer;
+
+ let random_data = Buffer.create ~arity:max_args in
+ let new_random_data () =
+ for i = 0 to Buffer.length random_data - 1 do
+ random_data.{i} <- char_of_int (Random.int 256)
+ done
+ in
+
+ let failure = ref false in
+ for i = 1 to 1000 do
+ new_random_data ();
+ List.iter tests ~f:(fun test ->
+ if not (run_test ~random_data ~ocaml_buffer ~c_buffer test) then
+ failure := true)
+ done;
+ exit (if !failure then 1 else 0)
diff --git a/testsuite/tests/unboxed-primitive-args/common.mli b/testsuite/tests/unboxed-primitive-args/common.mli
new file mode 100644
index 0000000000..09b42f1251
--- /dev/null
+++ b/testsuite/tests/unboxed-primitive-args/common.mli
@@ -0,0 +1,41 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jeremie Dimino, Jane Street Europe *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Type of arguments/result *)
+type 'a typ =
+ | Int : int typ
+ | Int32 : int32 typ
+ | Int64 : int64 typ
+ | Nativeint : nativeint typ
+ | Float : float typ
+
+type 'a proto =
+ | Ret : 'a typ -> 'a proto
+ | Abs : 'a typ * 'b proto -> ('a -> 'b) proto
+
+(** Same as [Abs]. We choose this operator for its associativity. *)
+val ( ** ) : 'a typ -> 'b proto -> ('a -> 'b) proto
+
+type test =
+ | T1 : string * ('a -> 'b) * 'a typ * 'b typ -> test
+ | T2 : string * ('a -> 'b -> 'c) * 'a typ * 'b typ * 'c typ -> test
+ | T3 : string * ('a -> 'b -> 'c -> 'd) *
+ 'a typ * 'b typ * 'c typ * 'd typ -> test
+ | T4 : string * ('a -> 'b -> 'c -> 'd -> 'e) *
+ 'a typ * 'b typ * 'c typ * 'd typ * 'e typ -> test
+ | T5 : string * ('a -> 'b -> 'c -> 'd -> 'e -> 'f) *
+ 'a typ * 'b typ * 'c typ * 'd typ * 'e typ * 'f typ -> test
+ | T6 : string * ('a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g) *
+ 'a typ * 'b typ * 'c typ * 'd typ * 'e typ * 'f typ * 'g typ -> test
+ | T : string * 'a * 'a proto -> test
+
+val run_tests : test list -> unit
diff --git a/testsuite/tests/unboxed-primitive-args/gen_test.ml b/testsuite/tests/unboxed-primitive-args/gen_test.ml
new file mode 100644
index 0000000000..0aab332c00
--- /dev/null
+++ b/testsuite/tests/unboxed-primitive-args/gen_test.ml
@@ -0,0 +1,240 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jeremie Dimino, Jane Street Europe *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* This programs generate stubs with various prototype combinations *)
+
+open StdLabels
+
+type boxed_integer = Pnativeint | Pint32 | Pint64
+
+type native_repr =
+ | Same_as_ocaml_repr
+ | Unboxed_float
+ | Unboxed_integer of boxed_integer
+ | Untagged_int
+
+(* Generate primitives with up to this number of arguments *)
+let test_all_combination_up_to_n_args = 6
+
+(* Generate primitives using all combination of these argument
+ representations. No need to test all combination of other
+ representations: regarding the calling convention
+ [Same_as_ocaml_repr], [Untagged_int] and
+ [Unboxed_integer Pnativeint] are all the same, and are the
+ same as [Unboxed_integer Pint<word-size>].
+
+ We have specific tests for the other representations and for the
+ result representation in [manual_tests].
+*)
+let test_all_args_combination_of =
+ [ Unboxed_float
+ ; Unboxed_integer Pint32
+ ; Unboxed_integer Pint64
+ ]
+
+let code_of_repr = function
+ | Same_as_ocaml_repr -> "v" (* for "value" *)
+ | Unboxed_float -> "f"
+ | Unboxed_integer Pint32 -> "l"
+ | Unboxed_integer Pint64 -> "L"
+ | Unboxed_integer Pnativeint -> "n"
+ | Untagged_int -> "i"
+
+let repr_of_code = function
+ | 'v' -> Same_as_ocaml_repr
+ | 'f' -> Unboxed_float
+ | 'l' -> Unboxed_integer Pint32
+ | 'L' -> Unboxed_integer Pint64
+ | 'n' -> Unboxed_integer Pnativeint
+ | 'i' -> Untagged_int
+ | _ -> assert false
+
+let manual_tests =
+ [ "v_v"
+ ; "f_f"
+ ; "l_l"
+ ; "L_L"
+ ; "n_n"
+ ; "i_i"
+ ; "f_fffff"
+ ; "f_ffffff"
+ ; "f_fffffff"
+ ; "f_fffffffffffffffff"
+ ; "v_iiiiiiiiiiiiiiiii"
+ ; "v_lllllllllllllllll"
+ ; "v_LLLLLLLLLLLLLLLLL"
+ ; "v_iLiLiLiLiLiLiLiLi"
+ ; "v_LiLiLiLiLiLiLiLiL"
+ ; "v_flflflflflflflflflflflflflflflflflfl"
+ ; "v_fLfLfLfLfLfLfLfLfLfLfLfLfLfLfLfLfLfL"
+ ]
+
+let ocaml_type_of_repr = function
+ (* Doesn't really matters what we choose for this case *)
+ | Same_as_ocaml_repr -> "int"
+ | Unboxed_float -> "(float [@unboxed])"
+ | Unboxed_integer Pint32 -> "(int32 [@unboxed])"
+ | Unboxed_integer Pint64 -> "(int64 [@unboxed])"
+ | Unboxed_integer Pnativeint -> "(nativeint [@unboxed])"
+ | Untagged_int -> "(int [@untagged])"
+
+let ocaml_type_gadt_of_repr = function
+ (* Doesn't really matters what we choose for this case *)
+ | Same_as_ocaml_repr -> "Int"
+ | Unboxed_float -> "Float"
+ | Unboxed_integer Pint32 -> "Int32"
+ | Unboxed_integer Pint64 -> "Int64"
+ | Unboxed_integer Pnativeint -> "Nativeint"
+ | Untagged_int -> "Int"
+
+let c_type_of_repr = function
+ | Same_as_ocaml_repr -> "value"
+ | Unboxed_float -> "double"
+ | Unboxed_integer Pint32 -> "int32_t"
+ | Unboxed_integer Pint64 -> "int64_t"
+ | Unboxed_integer Pnativeint -> "intnat"
+ | Untagged_int -> "intnat"
+
+type proto =
+ { params : native_repr list
+ ; return : native_repr
+ }
+
+let rec explode s =
+ let rec loop i acc =
+ if i < 0 then
+ acc
+ else
+ loop (i - 1) (s.[i] :: acc)
+ in
+ loop (String.length s - 1) []
+
+let proto_of_str s =
+ Scanf.sscanf s "%c_%s" (fun return params ->
+ { params = List.map (explode params) ~f:repr_of_code
+ ; return = repr_of_code return
+ })
+
+let function_name_of_proto proto =
+ Printf.sprintf "test_%s_%s" (code_of_repr proto.return)
+ (String.concat ~sep:"" (List.map proto.params ~f:code_of_repr))
+
+let ocaml_type_gadt_of_proto proto =
+ Printf.sprintf "%s ** Ret %s"
+ (String.concat ~sep:" ** "
+ (List.map proto.params ~f:ocaml_type_gadt_of_repr))
+ (ocaml_type_gadt_of_repr proto.return)
+
+let ocaml_type_of_proto proto =
+ String.concat ~sep:" -> "
+ (List.map proto.params ~f:ocaml_type_of_repr
+ @ [ocaml_type_of_repr proto.return])
+
+let c_args_of_proto proto =
+ String.concat ~sep:", "
+ (List.mapi proto.params ~f:(fun i p ->
+ Printf.sprintf "%s x%d" (c_type_of_repr p) i))
+
+let manual_protos = List.map manual_tests ~f:proto_of_str
+
+let iter_protos ~f =
+ let iter_for_arity arity =
+ let rec loop params to_gen =
+ List.iter test_all_args_combination_of ~f:(fun repr ->
+ let params = repr :: params in
+ let to_gen = to_gen - 1 in
+ if to_gen = 0 then
+ f { params = List.rev params
+ ; return = Same_as_ocaml_repr
+ }
+ else
+ loop params to_gen)
+ in
+ loop [] arity
+ in
+ let rec iter_arities arity =
+ if arity <= test_all_combination_up_to_n_args then begin
+ iter_for_arity arity;
+ iter_arities (arity + 1)
+ end
+ in
+ List.iter manual_protos ~f;
+ iter_arities 1
+
+let pr fmt = Printf.ksprintf (fun s -> print_string s; print_char '\n') fmt
+
+let generate_ml () =
+ pr "open Common";
+ pr "";
+ iter_protos ~f:(fun proto ->
+ let name = function_name_of_proto proto in
+ pr "external %s : %s = \"\" \"noalloc\" %S"
+ name (ocaml_type_of_proto proto) name;
+ );
+ pr "";
+ pr "let tests = []";
+ iter_protos ~f:(fun proto ->
+ let name = function_name_of_proto proto in
+ let arity = List.length proto.params in
+ if arity <= 6 then
+ pr "let tests = T%d (%S, %s, %s, %s) :: tests"
+ arity name name
+ (List.map proto.params ~f:ocaml_type_gadt_of_repr
+ |> String.concat ~sep:", ")
+ (ocaml_type_gadt_of_repr proto.return)
+ else
+ pr "let tests = T (%S, %s, %s) :: tests"
+ name name (ocaml_type_gadt_of_proto proto));
+ pr "";
+ pr "let () = run_tests (List.rev tests)"
+
+let generate_stubs () =
+ pr "#include <stdio.h>";
+ pr "#include <caml/mlvalues.h>";
+ pr "#include \"test_common.h\"";
+ iter_protos ~f:(fun proto ->
+ let name = function_name_of_proto proto in
+ pr "";
+ pr "%s %s(%s)"
+ (c_type_of_repr proto.return)
+ name
+ (c_args_of_proto proto);
+ pr "{";
+ List.iteri proto.params ~f:(fun i p ->
+ pr " %(%d%d%);"
+ (match p with
+ | Same_as_ocaml_repr -> "set_intnat(%d, Long_val(x%d))"
+ | Unboxed_float -> "set_double(%d, x%d)"
+ | Unboxed_integer Pint32 -> "set_int32(%d, x%d)"
+ | Unboxed_integer Pint64 -> "set_int64(%d, x%d)"
+ | Unboxed_integer Pnativeint -> "set_intnat(%d, x%d)"
+ | Untagged_int -> "set_intnat(%d, x%d)")
+ i i);
+ pr " return %(%d%);"
+ (match proto.return with
+ | Same_as_ocaml_repr -> "Val_long(get_intnat(%d))"
+ | Unboxed_float -> "get_double(%d)"
+ | Unboxed_integer Pint32 -> "get_int32(%d)"
+ | Unboxed_integer Pint64 -> "get_int64(%d)"
+ | Unboxed_integer Pnativeint -> "get_intnat(%d)"
+ | Untagged_int -> "get_intnat(%d)")
+ (List.length proto.params);
+ pr "}"
+ )
+
+let () =
+ match Sys.argv with
+ | [|_; "ml"|] -> generate_ml ()
+ | [|_; "c" |] -> generate_stubs ()
+ | _ ->
+ prerr_endline "Usage: ocaml gen_test.ml {ml|c}";
+ exit 2
diff --git a/testsuite/tests/unboxed-primitive-args/main.reference b/testsuite/tests/unboxed-primitive-args/main.reference
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/testsuite/tests/unboxed-primitive-args/main.reference
diff --git a/testsuite/tests/unboxed-primitive-args/test_common.c b/testsuite/tests/unboxed-primitive-args/test_common.c
new file mode 100644
index 0000000000..30305b2c87
--- /dev/null
+++ b/testsuite/tests/unboxed-primitive-args/test_common.c
@@ -0,0 +1,34 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Jeremie Dimino, Jane Street Europe */
+/* */
+/* Copyright 2015 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <caml/mlvalues.h>
+#include <bigarray.h>
+
+char *ocaml_buffer;
+char *c_buffer;
+
+value test_set_buffers(value v_ocaml_buffer, value v_c_buffer)
+{
+ ocaml_buffer = Caml_ba_data_val(v_ocaml_buffer);
+ c_buffer = Caml_ba_data_val(v_c_buffer);
+ return Val_unit;
+}
+
+value test_cleanup_normal()
+{
+ return Val_int(0);
+}
+
+double test_cleanup_float()
+{
+ return 0.;
+}
diff --git a/testsuite/tests/unboxed-primitive-args/test_common.h b/testsuite/tests/unboxed-primitive-args/test_common.h
new file mode 100644
index 0000000000..06ed341eb7
--- /dev/null
+++ b/testsuite/tests/unboxed-primitive-args/test_common.h
@@ -0,0 +1,41 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Jeremie Dimino, Jane Street Europe */
+/* */
+/* Copyright 2015 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#ifndef __TEST_COMMON_H
+#define __TEST_COMMON_H
+
+/* Where the OCaml side stores the arguments and result for a test
+ case. The C function will read the result it is supposed to return
+ from this buffer.
+
+ Argument [n] is stored at [n * 8] and the result is stored at
+ [arity * 8].
+*/
+extern char *ocaml_buffer;
+
+/* Where the C function stores the arguments it receive for a test
+ case. The OCaml side will store the result from the C function in
+ this buffer. At the of a test case, both these buffers must be
+ equal. */
+extern char *c_buffer;
+
+#define get_intnat(n) *(intnat*)(ocaml_buffer+((n)*8))
+#define get_int32(n) *(int32_t*)(ocaml_buffer+((n)*8))
+#define get_int64(n) *(int64_t*)(ocaml_buffer+((n)*8))
+#define get_double(n) *(double*)(ocaml_buffer+((n)*8))
+
+#define set_intnat(n, x) *(intnat*)(c_buffer+((n)*8)) = (x)
+#define set_int32(n, x) *(int32_t*)(c_buffer+((n)*8)) = (x)
+#define set_int64(n, x) *(int64_t*)(c_buffer+((n)*8)) = (x)
+#define set_double(n, x) *(double*)(c_buffer+((n)*8)) = (x)
+
+#endif /* __TEST_COMMON_H */
diff --git a/testsuite/tests/utils/Makefile b/testsuite/tests/utils/Makefile
new file mode 100644
index 0000000000..1d50868024
--- /dev/null
+++ b/testsuite/tests/utils/Makefile
@@ -0,0 +1,22 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Alain Frisch, LexiFi #
+# #
+# Copyright 2012 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+MODULES=testing misc
+INCLUDES= -I $(OTOPDIR)/utils
+ADD_COMPFLAGS=$(INCLUDES)
+CMO_FILES+="misc.cmo"
+
+include $(BASEDIR)/makefiles/Makefile.several
+include $(BASEDIR)/makefiles/Makefile.common
+
+BYTECODE_ONLY=true
diff --git a/testsuite/tests/utils/edit_distance.ml b/testsuite/tests/utils/edit_distance.ml
new file mode 100644
index 0000000000..294b02ce4e
--- /dev/null
+++ b/testsuite/tests/utils/edit_distance.ml
@@ -0,0 +1,48 @@
+let edit_distance = Misc.edit_distance
+
+let show_cutoff n =
+ if n = max_int then "max_int" else Printf.sprintf "%d" n
+;;
+
+let test =
+ let counter = ref 0 in
+ fun a b cutoff expected ->
+ let show_result = function
+ | None -> "None"
+ | Some d -> "Some " ^ string_of_int d in
+ incr counter;
+ Printf.printf "[%02d] (edit_distance %S %S %s), expected %s\n"
+ !counter a b (show_cutoff cutoff) (show_result expected);
+ let result = edit_distance a b cutoff in
+ if result = expected
+ then print_endline "OK"
+ else Printf.printf "FAIL: got %s\n%!" (show_result result)
+
+let () =
+ test "a" "a" 1 (Some 0);
+ test "a" "a" 0 (Some 0);
+ test "a" "b" 1 (Some 1);
+ test "a" "b" 0 None;
+ test "add" "adad" 3 (Some 1);
+ test "delete" "delte" 3 (Some 1);
+ test "subst" "sabst" 3 (Some 1);
+ test "swap" "sawp" 3 (Some 1);
+ test "abbb" "bbba" 3 (Some 2);
+ test "abbb" "bbba" 1 None;
+
+ (* check for bugs where a small common suffix, or common prefix, is
+ enough to make the distance goes down *)
+ test "xyzwabc" "mnpqrabc" 10 (Some 5);
+ test "abcxyzw" "abcmnpqr" 10 (Some 5);
+
+ (* check that using "max_int" as cutoff works *)
+ test "a" "a" max_int (Some 0);
+ test "a" "b" max_int (Some 1);
+ test "abc" "ade" max_int (Some 2);
+
+ (* check empty strings*)
+ test "" "" 3 (Some 0);
+ test "" "abc" 3 (Some 3);
+ test "abcd" "" 3 None;
+
+ ()
diff --git a/testsuite/tests/utils/edit_distance.reference b/testsuite/tests/utils/edit_distance.reference
new file mode 100644
index 0000000000..c2816dabcc
--- /dev/null
+++ b/testsuite/tests/utils/edit_distance.reference
@@ -0,0 +1,38 @@
+[01] (edit_distance "a" "a" 1), expected Some 0
+OK
+[02] (edit_distance "a" "a" 0), expected Some 0
+OK
+[03] (edit_distance "a" "b" 1), expected Some 1
+OK
+[04] (edit_distance "a" "b" 0), expected None
+OK
+[05] (edit_distance "add" "adad" 3), expected Some 1
+OK
+[06] (edit_distance "delete" "delte" 3), expected Some 1
+OK
+[07] (edit_distance "subst" "sabst" 3), expected Some 1
+OK
+[08] (edit_distance "swap" "sawp" 3), expected Some 1
+OK
+[09] (edit_distance "abbb" "bbba" 3), expected Some 2
+OK
+[10] (edit_distance "abbb" "bbba" 1), expected None
+OK
+[11] (edit_distance "xyzwabc" "mnpqrabc" 10), expected Some 5
+OK
+[12] (edit_distance "abcxyzw" "abcmnpqr" 10), expected Some 5
+OK
+[13] (edit_distance "a" "a" max_int), expected Some 0
+OK
+[14] (edit_distance "a" "b" max_int), expected Some 1
+OK
+[15] (edit_distance "abc" "ade" max_int), expected Some 2
+OK
+[16] (edit_distance "" "" 3), expected Some 0
+OK
+[17] (edit_distance "" "abc" 3), expected Some 3
+OK
+[18] (edit_distance "abcd" "" 3), expected None
+OK
+
+All tests succeeded.
diff --git a/testsuite/tests/warnings/Makefile b/testsuite/tests/warnings/Makefile
new file mode 100644
index 0000000000..06f574f14f
--- /dev/null
+++ b/testsuite/tests/warnings/Makefile
@@ -0,0 +1,31 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Clerc, SED, INRIA Rocquencourt #
+# #
+# Copyright 2010 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+BASEDIR=../..
+FLAGS=-w A
+EXECNAME=./program
+
+run-all:
+ @for file in *.ml; do \
+ printf " ... testing '$$file':"; \
+ F="`basename $$file .ml`"; \
+ $(OCAMLC) $(FLAGS) -o $(EXECNAME) $$file 2>$$F.result; \
+ $(DIFF) $$F.reference $$F.result >/dev/null \
+ && echo " => passed" || echo " => failed"; \
+ done;
+
+promote: defaultpromote
+
+clean: defaultclean
+ @rm -f *.result $(EXECNAME)
+
+include $(BASEDIR)/makefiles/Makefile.common
diff --git a/testsuite/tests/warnings/w01.ml b/testsuite/tests/warnings/w01.ml
new file mode 100644
index 0000000000..24a6accc9e
--- /dev/null
+++ b/testsuite/tests/warnings/w01.ml
@@ -0,0 +1,55 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2000 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* C *)
+
+let foo = ( *);;
+
+
+(* F *)
+
+let f x y = x;;
+f 1; f 1;;
+
+
+(* M *)
+
+(* duh *)
+
+
+(* P *)
+
+let 1 = 1;;
+
+
+(* S *)
+
+1; 1;;
+
+
+(* U *)
+
+match 1 with
+| 1 -> ()
+| 1 -> ()
+| _ -> ()
+;;
+
+
+(* V *)
+
+(* re-duh *)
+
+
+(* X *)
+
+(* re-re *)
diff --git a/testsuite/tests/warnings/w01.reference b/testsuite/tests/warnings/w01.reference
new file mode 100644
index 0000000000..730da03c9a
--- /dev/null
+++ b/testsuite/tests/warnings/w01.reference
@@ -0,0 +1,15 @@
+File "w01.ml", line 15, characters 12-14:
+Warning 2: this is not the end of a comment.
+File "w01.ml", line 21, characters 0-3:
+Warning 5: this function application is partial,
+maybe some arguments are missing.
+File "w01.ml", line 31, characters 4-5:
+Warning 8: this pattern-matching is not exhaustive.
+Here is an example of a value that is not matched:
+0
+File "w01.ml", line 36, characters 0-1:
+Warning 10: this expression should have type unit.
+File "w01.ml", line 20, characters 8-9:
+Warning 27: unused variable y.
+File "w01.ml", line 43, characters 2-3:
+Warning 11: this match case is unused.
diff --git a/testsuite/tests/warnings/w06.ml b/testsuite/tests/warnings/w06.ml
new file mode 100644
index 0000000000..6e8a1bca03
--- /dev/null
+++ b/testsuite/tests/warnings/w06.ml
@@ -0,0 +1,6 @@
+let foo ~bar = ignore bar (* one label *)
+
+let bar ~foo ~baz = ignore (foo, baz) (* two labels *)
+
+let () = foo 2
+let () = bar 4 2
diff --git a/testsuite/tests/warnings/w06.reference b/testsuite/tests/warnings/w06.reference
new file mode 100644
index 0000000000..b3019f4d1d
--- /dev/null
+++ b/testsuite/tests/warnings/w06.reference
@@ -0,0 +1,4 @@
+File "w06.ml", line 5, characters 9-12:
+Warning 6: label bar was omitted in the application of this function.
+File "w06.ml", line 6, characters 9-12:
+Warning 6: labels foo, baz were omitted in the application of this function.
diff --git a/testsuite/tests/warnings/w51.ml b/testsuite/tests/warnings/w51.ml
new file mode 100644
index 0000000000..25e087068d
--- /dev/null
+++ b/testsuite/tests/warnings/w51.ml
@@ -0,0 +1,5 @@
+
+let rec fact = function
+ | 1 -> 1
+ | n -> n * (fact [@tailcall]) (n-1)
+;;
diff --git a/testsuite/tests/warnings/w51.reference b/testsuite/tests/warnings/w51.reference
new file mode 100644
index 0000000000..5e3cf374d6
--- /dev/null
+++ b/testsuite/tests/warnings/w51.reference
@@ -0,0 +1,2 @@
+File "w51.ml", line 4, characters 13-37:
+Warning 51: expected tailcall
diff --git a/testsuite/tests/warnings/w51_bis.ml b/testsuite/tests/warnings/w51_bis.ml
new file mode 100644
index 0000000000..810fcdd4f5
--- /dev/null
+++ b/testsuite/tests/warnings/w51_bis.ml
@@ -0,0 +1,5 @@
+let rec foldl op acc = function
+ [] -> acc
+ | x :: xs ->
+ try (foldl [@tailcall]) op (op x acc) xs
+ with Not_found -> assert false
diff --git a/testsuite/tests/warnings/w51_bis.reference b/testsuite/tests/warnings/w51_bis.reference
new file mode 100644
index 0000000000..ee5cab5a35
--- /dev/null
+++ b/testsuite/tests/warnings/w51_bis.reference
@@ -0,0 +1,2 @@
+File "w51_bis.ml", line 4, characters 12-48:
+Warning 51: expected tailcall
diff --git a/testsuite/typing b/testsuite/typing
new file mode 100644
index 0000000000..4357fdf3c7
--- /dev/null
+++ b/testsuite/typing
@@ -0,0 +1,33 @@
+tests/basic
+tests/basic-float
+tests/basic-io
+tests/basic-io-2
+tests/basic-manyargs
+tests/basic-modules
+tests/basic-more
+tests/basic-multdef
+tests/basic-private
+tests/typing-extensions
+tests/typing-fstclassmod
+tests/typing-gadts
+tests/typing-implicit_unpack
+tests/typing-labels
+tests/typing-misc
+tests/typing-misc-bugs
+tests/typing-modules
+tests/typing-modules-bugs
+tests/typing-objects
+tests/typing-objects-bugs
+tests/typing-poly
+tests/typing-poly-bugs
+tests/typing-polyvariants-bugs
+tests/typing-polyvariants-bugs-2
+tests/typing-private
+tests/typing-private-bugs
+tests/typing-recmod
+tests/typing-rectypes-bugs
+tests/typing-short-paths
+tests/typing-signatures
+tests/typing-sigsubst
+tests/typing-typeparam
+tests/typing-warnings
diff --git a/tools/.depend b/tools/.depend
new file mode 100644
index 0000000000..b3f23fba6f
--- /dev/null
+++ b/tools/.depend
@@ -0,0 +1,80 @@
+depend.cmi : ../parsing/parsetree.cmi ../parsing/longident.cmi
+profiling.cmi :
+addlabels.cmo : ../parsing/parsetree.cmi ../parsing/parse.cmi \
+ ../parsing/longident.cmi ../parsing/location.cmi ../parsing/asttypes.cmi
+addlabels.cmx : ../parsing/parsetree.cmi ../parsing/parse.cmx \
+ ../parsing/longident.cmx ../parsing/location.cmx ../parsing/asttypes.cmi
+cmt2annot.cmo : ../typing/untypeast.cmi ../typing/types.cmi \
+ ../typing/typedtree.cmi ../typing/tast_mapper.cmi ../typing/stypes.cmi \
+ ../parsing/pprintast.cmi ../typing/path.cmi ../typing/oprint.cmi \
+ ../parsing/location.cmi ../typing/ident.cmi ../typing/envaux.cmi \
+ ../typing/env.cmi ../utils/config.cmi ../typing/cmt_format.cmi \
+ ../parsing/asttypes.cmi ../typing/annot.cmi
+cmt2annot.cmx : ../typing/untypeast.cmx ../typing/types.cmx \
+ ../typing/typedtree.cmx ../typing/tast_mapper.cmx ../typing/stypes.cmx \
+ ../parsing/pprintast.cmx ../typing/path.cmx ../typing/oprint.cmx \
+ ../parsing/location.cmx ../typing/ident.cmx ../typing/envaux.cmx \
+ ../typing/env.cmx ../utils/config.cmx ../typing/cmt_format.cmx \
+ ../parsing/asttypes.cmi ../typing/annot.cmi
+cvt_emit.cmo :
+cvt_emit.cmx :
+depend.cmo : ../parsing/parsetree.cmi ../utils/misc.cmi \
+ ../parsing/longident.cmi ../parsing/location.cmi ../parsing/asttypes.cmi \
+ depend.cmi
+depend.cmx : ../parsing/parsetree.cmi ../utils/misc.cmx \
+ ../parsing/longident.cmx ../parsing/location.cmx ../parsing/asttypes.cmi \
+ depend.cmi
+dumpobj.cmo : ../utils/tbl.cmi opnames.cmo ../bytecomp/opcodes.cmo \
+ ../parsing/location.cmi ../bytecomp/lambda.cmi ../bytecomp/instruct.cmi \
+ ../typing/ident.cmi ../utils/config.cmi ../bytecomp/cmo_format.cmi \
+ ../bytecomp/bytesections.cmi ../parsing/asttypes.cmi
+dumpobj.cmx : ../utils/tbl.cmx opnames.cmx ../bytecomp/opcodes.cmx \
+ ../parsing/location.cmx ../bytecomp/lambda.cmx ../bytecomp/instruct.cmx \
+ ../typing/ident.cmx ../utils/config.cmx ../bytecomp/cmo_format.cmi \
+ ../bytecomp/bytesections.cmx ../parsing/asttypes.cmi
+eqparsetree.cmo : ../parsing/parsetree.cmi ../parsing/longident.cmi \
+ ../parsing/location.cmi ../parsing/asttypes.cmi
+eqparsetree.cmx : ../parsing/parsetree.cmi ../parsing/longident.cmx \
+ ../parsing/location.cmx ../parsing/asttypes.cmi
+objinfo.cmo : ../asmcomp/printclambda.cmi ../utils/misc.cmi \
+ ../utils/config.cmi ../asmcomp/cmx_format.cmi ../typing/cmt_format.cmi \
+ ../bytecomp/cmo_format.cmi ../typing/cmi_format.cmi \
+ ../bytecomp/bytesections.cmi
+objinfo.cmx : ../asmcomp/printclambda.cmx ../utils/misc.cmx \
+ ../utils/config.cmx ../asmcomp/cmx_format.cmi ../typing/cmt_format.cmx \
+ ../bytecomp/cmo_format.cmi ../typing/cmi_format.cmx \
+ ../bytecomp/bytesections.cmx
+ocaml299to3.cmo :
+ocaml299to3.cmx :
+ocamlcp.cmo : ../driver/main_args.cmi
+ocamlcp.cmx : ../driver/main_args.cmx
+ocamldep.cmo : ../driver/pparse.cmi ../parsing/parsetree.cmi \
+ ../parsing/parser.cmi ../parsing/parse.cmi ../utils/misc.cmi \
+ ../parsing/longident.cmi ../parsing/location.cmi ../parsing/lexer.cmi \
+ depend.cmi ../utils/config.cmi ../driver/compenv.cmi ../utils/clflags.cmi
+ocamldep.cmx : ../driver/pparse.cmx ../parsing/parsetree.cmi \
+ ../parsing/parser.cmx ../parsing/parse.cmx ../utils/misc.cmx \
+ ../parsing/longident.cmx ../parsing/location.cmx ../parsing/lexer.cmx \
+ depend.cmx ../utils/config.cmx ../driver/compenv.cmx ../utils/clflags.cmx
+ocamlmklibconfig.cmo :
+ocamlmklibconfig.cmx :
+ocamlmklib.cmo : ocamlmklibconfig.cmo
+ocamlmklib.cmx : ocamlmklibconfig.cmx
+ocamlmktop.cmo : ../utils/ccomp.cmi
+ocamlmktop.cmx : ../utils/ccomp.cmx
+ocamloptp.cmo : ../driver/main_args.cmi
+ocamloptp.cmx : ../driver/main_args.cmx
+ocamlprof.cmo : ../utils/warnings.cmi ../parsing/parsetree.cmi \
+ ../parsing/parse.cmi ../parsing/location.cmi
+ocamlprof.cmx : ../utils/warnings.cmx ../parsing/parsetree.cmi \
+ ../parsing/parse.cmx ../parsing/location.cmx
+opnames.cmo :
+opnames.cmx :
+primreq.cmo : ../utils/config.cmi ../bytecomp/cmo_format.cmi
+primreq.cmx : ../utils/config.cmx ../bytecomp/cmo_format.cmi
+profiling.cmo : profiling.cmi
+profiling.cmx : profiling.cmi
+read_cmt.cmo : ../typing/cmt_format.cmi cmt2annot.cmo ../utils/clflags.cmi
+read_cmt.cmx : ../typing/cmt_format.cmx cmt2annot.cmx ../utils/clflags.cmx
+scrapelabels.cmo :
+scrapelabels.cmx :
diff --git a/tools/.ignore b/tools/.ignore
new file mode 100644
index 0000000000..94fac02fbc
--- /dev/null
+++ b/tools/.ignore
@@ -0,0 +1,27 @@
+ocamldep
+ocamldep.opt
+ocamldep.bak
+ocamlprof
+opnames.ml
+dumpobj
+dumpapprox
+objinfo
+cvt_emit
+cvt_emit.bak
+cvt_emit.ml
+ocamlcp
+ocamloptp
+ocamlmktop
+primreq
+ocamldumpobj
+keywords
+lexer299.ml
+ocaml299to3
+ocamlmklib
+ocamlmklibconfig.ml
+lexer301.ml
+scrapelabels
+addlabels
+objinfo_helper
+read_cmt
+read_cmt.opt
diff --git a/tools/Makefile b/tools/Makefile
new file mode 100644
index 0000000000..b5cc10109b
--- /dev/null
+++ b/tools/Makefile
@@ -0,0 +1,25 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+include Makefile.shared
+
+# To make custom toplevels
+
+ocamlmktop: ocamlmktop.tpl ../config/Makefile
+ sed -e 's|%%BINDIR%%|$(BINDIR)|' ocamlmktop.tpl > ocamlmktop
+ chmod +x ocamlmktop
+
+install::
+ cp ocamlmktop $(INSTALL_BINDIR)
+
+clean::
+ rm -f ocamlmktop
diff --git a/tools/Makefile.nt b/tools/Makefile.nt
new file mode 100644
index 0000000000..ed9b35946d
--- /dev/null
+++ b/tools/Makefile.nt
@@ -0,0 +1,27 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+include Makefile.shared
+
+# To make custom toplevels
+
+OCAMLMKTOP=ocamlmktop.cmo
+OCAMLMKTOP_IMPORTS=misc.cmo config.cmo clflags.cmo ccomp.cmo
+
+ocamlmktop: $(OCAMLMKTOP)
+ $(CAMLC) $(LINKFLAGS) -o ocamlmktop $(OCAMLMKTOP_IMPORTS) $(OCAMLMKTOP)
+
+install::
+ cp ocamlmktop $(INSTALL_BINDIR)/ocamlmktop$(EXE)
+
+clean::
+ rm -f ocamlmktop$(EXE)
diff --git a/tools/Makefile.shared b/tools/Makefile.shared
new file mode 100644
index 0000000000..c4a56e5259
--- /dev/null
+++ b/tools/Makefile.shared
@@ -0,0 +1,313 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+include ../config/Makefile
+CAMLRUN ?= ../boot/ocamlrun
+CAMLYACC ?= ../boot/ocamlyacc
+
+CAMLC=$(CAMLRUN) ../boot/ocamlc -nostdlib -I ../boot
+CAMLOPT=$(CAMLRUN) ../ocamlopt -nostdlib -I ../stdlib
+CAMLLEX=$(CAMLRUN) ../boot/ocamllex
+INCLUDES=-I ../utils -I ../parsing -I ../typing -I ../bytecomp -I ../asmcomp \
+ -I ../driver -I ../toplevel
+COMPFLAGS= -strict-sequence -w +27+32..39 -warn-error A -safe-string $(INCLUDES)
+LINKFLAGS=$(INCLUDES)
+
+all: ocamldep ocamlprof ocamlcp ocamloptp ocamlmktop ocamlmklib dumpobj \
+ objinfo read_cmt
+
+# scrapelabels addlabels
+
+.PHONY: all
+
+opt.opt: ocamldep.opt read_cmt.opt
+.PHONY: opt.opt
+
+# The dependency generator
+
+CAMLDEP_OBJ=depend.cmo ocamldep.cmo
+CAMLDEP_IMPORTS=misc.cmo config.cmo clflags.cmo terminfo.cmo \
+ warnings.cmo location.cmo longident.cmo docstrings.cmo \
+ syntaxerr.cmo ast_helper.cmo parser.cmo lexer.cmo parse.cmo \
+ ccomp.cmo ast_mapper.cmo pparse.cmo compenv.cmo
+
+ocamldep: depend.cmi $(CAMLDEP_OBJ)
+ $(CAMLC) $(LINKFLAGS) -compat-32 -o ocamldep $(CAMLDEP_IMPORTS) $(CAMLDEP_OBJ)
+
+ocamldep.opt: depend.cmi $(CAMLDEP_OBJ:.cmo=.cmx)
+ $(CAMLOPT) $(LINKFLAGS) -o ocamldep.opt $(CAMLDEP_IMPORTS:.cmo=.cmx) \
+ $(CAMLDEP_OBJ:.cmo=.cmx)
+
+# ocamldep is precious: sometimes we are stuck in the middle of a
+# bootstrap and we need to remake the dependencies
+clean::
+ if test -f ocamldep; then mv -f ocamldep ocamldep.bak; else :; fi
+ rm -f ocamldep.opt
+
+
+INSTALL_BINDIR=$(DESTDIR)$(BINDIR)
+INSTALL_LIBDIR=$(DESTDIR)$(LIBDIR)
+
+install::
+ cp ocamldep $(INSTALL_BINDIR)/ocamldep$(EXE)
+ if test -f ocamldep.opt; \
+ then cp ocamldep.opt $(INSTALL_BINDIR)/ocamldep.opt$(EXE); else :; fi
+
+# The profiler
+
+CSLPROF=ocamlprof.cmo
+CSLPROF_IMPORTS=misc.cmo config.cmo clflags.cmo terminfo.cmo \
+ warnings.cmo location.cmo longident.cmo docstrings.cmo \
+ syntaxerr.cmo ast_helper.cmo parser.cmo lexer.cmo parse.cmo
+
+ocamlprof: $(CSLPROF) profiling.cmo
+ $(CAMLC) $(LINKFLAGS) -o ocamlprof $(CSLPROF_IMPORTS) $(CSLPROF)
+
+ocamlcp: ocamlcp.cmo
+ $(CAMLC) $(LINKFLAGS) -o ocamlcp warnings.cmo main_args.cmo ocamlcp.cmo
+
+ocamloptp: ocamloptp.cmo
+ $(CAMLC) $(LINKFLAGS) -o ocamloptp warnings.cmo main_args.cmo \
+ ocamloptp.cmo
+
+opt:: profiling.cmx
+
+install::
+ cp ocamlprof $(INSTALL_BINDIR)/ocamlprof$(EXE)
+ cp ocamlcp $(INSTALL_BINDIR)/ocamlcp$(EXE)
+ cp ocamloptp $(INSTALL_BINDIR)/ocamloptp$(EXE)
+ cp profiling.cmi profiling.cmo $(INSTALL_LIBDIR)
+
+installopt::
+ cp profiling.cmx profiling.$(O) $(INSTALL_LIBDIR)
+
+clean::
+ rm -f ocamlprof ocamlcp ocamloptp
+
+
+# To help building mixed-mode libraries (OCaml + C)
+
+ocamlmklib: ocamlmklibconfig.cmo ocamlmklib.cmo
+ $(CAMLC) $(LINKFLAGS) -o ocamlmklib ocamlmklibconfig.cmo ocamlmklib.cmo
+
+install::
+ cp ocamlmklib $(INSTALL_BINDIR)/ocamlmklib$(EXE)
+
+clean::
+ rm -f ocamlmklib
+
+ocamlmklibconfig.ml: ../config/Makefile
+ (echo 'let bindir = "$(BINDIR)"'; \
+ echo 'let ext_lib = "$(EXT_LIB)"'; \
+ echo 'let ext_dll = "$(EXT_DLL)"'; \
+ echo 'let supports_shared_libraries = $(SUPPORTS_SHARED_LIBRARIES)';\
+ echo 'let mkdll = "$(MKDLL)"'; \
+ echo 'let byteccrpath = "$(BYTECCRPATH)"'; \
+ echo 'let nativeccrpath = "$(NATIVECCRPATH)"'; \
+ echo 'let mksharedlibrpath = "$(MKSHAREDLIBRPATH)"'; \
+ echo 'let toolpref = "$(TOOLPREF)"'; \
+ sed -n -e 's/^#ml //p' ../config/Makefile) \
+ > ocamlmklibconfig.ml
+
+beforedepend:: ocamlmklibconfig.ml
+
+clean::
+ rm -f ocamlmklibconfig.ml
+
+# Converter olabl/ocaml 2.99 to ocaml 3
+
+OCAML299TO3= lexer299.cmo ocaml299to3.cmo
+LIBRARY3= misc.cmo warnings.cmo location.cmo
+
+ocaml299to3: $(OCAML299TO3)
+ $(CAMLC) $(LINKFLAGS) -o ocaml299to3 $(LIBRARY3) $(OCAML299TO3)
+
+lexer299.ml: lexer299.mll
+ $(CAMLLEX) lexer299.mll
+
+#install::
+# cp ocaml299to3 $(INSTALL_BINDIR)/ocaml299to3$(EXE)
+
+clean::
+ rm -f ocaml299to3 lexer299.ml
+
+# Label remover for interface files (upgrade 3.02 to 3.03)
+
+SCRAPELABELS= lexer301.cmo scrapelabels.cmo
+
+scrapelabels: $(SCRAPELABELS)
+ $(CAMLC) $(LINKFLAGS) -o scrapelabels $(LIBRARY3) $(SCRAPELABELS)
+
+lexer301.ml: lexer301.mll
+ $(CAMLLEX) lexer301.mll
+
+#install::
+# cp scrapelabels $(INSTALL_LIBDIR)
+
+clean::
+ rm -f scrapelabels lexer301.ml
+
+# Insert labels following an interface file (upgrade 3.02 to 3.03)
+
+ADDLABELS_IMPORTS=misc.cmo config.cmo clflags.cmo terminfo.cmo \
+ warnings.cmo location.cmo longident.cmo docstrings.cmo \
+ syntaxerr.cmo ast_helper.cmo parser.cmo lexer.cmo parse.cmo
+
+addlabels: addlabels.cmo
+ $(CAMLC) $(LINKFLAGS) -w sl -o addlabels \
+ $(ADDLABELS_IMPORTS) addlabels.cmo
+
+#install::
+# cp addlabels $(INSTALL_LIBDIR)
+
+clean::
+ rm -f addlabels
+
+# The preprocessor for asm generators
+
+CVT_EMIT=cvt_emit.cmo
+
+cvt_emit: $(CVT_EMIT)
+ $(CAMLC) $(LINKFLAGS) -o cvt_emit $(CVT_EMIT)
+
+# cvt_emit is precious: sometimes we are stuck in the middle of a
+# bootstrap and we need to remake the dependencies
+clean::
+ if test -f cvt_emit; then mv -f cvt_emit cvt_emit.bak; else :; fi
+
+cvt_emit.ml: cvt_emit.mll
+ $(CAMLLEX) cvt_emit.mll
+
+clean::
+ rm -f cvt_emit.ml
+
+beforedepend:: cvt_emit.ml
+
+
+# Reading cmt files
+
+READ_CMT= \
+ ../compilerlibs/ocamlcommon.cma \
+ ../compilerlibs/ocamlbytecomp.cma \
+ \
+ cmt2annot.cmo read_cmt.cmo
+
+READ_CMT_OPT1 = $(READ_CMT:.cmo=.cmx)
+READ_CMT_OPT = $(READ_CMT_OPT1:.cma=.cmxa)
+
+read_cmt: $(READ_CMT)
+ $(CAMLC) $(LINKFLAGS) -o read_cmt $(READ_CMT)
+
+read_cmt.opt: $(READ_CMT_OPT)
+ $(CAMLOPT) $(LINKFLAGS) -o read_cmt.opt $(READ_CMT_OPT)
+
+clean::
+ rm -f read_cmt read_cmt.opt
+
+beforedepend::
+
+# The bytecode disassembler
+
+DUMPOBJ=opnames.cmo dumpobj.cmo
+
+dumpobj: $(DUMPOBJ)
+ $(CAMLC) $(LINKFLAGS) -o dumpobj \
+ misc.cmo tbl.cmo config.cmo ident.cmo \
+ opcodes.cmo bytesections.cmo $(DUMPOBJ)
+
+clean::
+ rm -f dumpobj
+
+opnames.ml: ../byterun/caml/instruct.h
+ unset LC_ALL || : ; \
+ unset LC_CTYPE || : ; \
+ unset LC_COLLATE LANG || : ; \
+ sed -e '/\/\*/d' \
+ -e '/^#/d' \
+ -e 's/enum \(.*\) {/let names_of_\1 = [|/' \
+ -e 's/.*};$$/ |]/' \
+ -e 's/\([A-Z][A-Z_0-9a-z]*\)/"\1"/g' \
+ -e 's/,/;/g' \
+ ../byterun/caml/instruct.h > opnames.ml
+
+clean::
+ rm -f opnames.ml
+
+beforedepend:: opnames.ml
+
+# Display info on compiled files
+
+ifeq "$(SYSTEM)" "macosx"
+DEF_SYMBOL_PREFIX = '-Dsymbol_prefix="_"'
+else
+DEF_SYMBOL_PREFIX = '-Dsymbol_prefix=""'
+endif
+
+ifeq "$(CCOMPTYPE)" "msvc"
+CCOUT = -Fe
+else
+EMPTY =
+CCOUT = -o $(EMPTY)
+endif
+
+objinfo_helper$(EXE): objinfo_helper.c ../config/s.h
+ $(BYTECC) $(CCOUT)objinfo_helper$(EXE) $(BYTECCCOMPOPTS) \
+ $(DEF_SYMBOL_PREFIX) $(LIBBFD_INCLUDE) objinfo_helper.c $(LIBBFD_LINK)
+
+OBJINFO=../compilerlibs/ocamlcommon.cma \
+ ../compilerlibs/ocamlbytecomp.cma \
+ ../asmcomp/printclambda.cmo \
+ objinfo.cmo
+
+objinfo: objinfo_helper$(EXE) $(OBJINFO)
+ $(CAMLC) -o objinfo $(OBJINFO)
+
+install::
+ cp objinfo $(INSTALL_BINDIR)/ocamlobjinfo$(EXE)
+ cp objinfo_helper$(EXE) $(INSTALL_LIBDIR)/objinfo_helper$(EXE)
+
+clean::
+ rm -f objinfo objinfo_helper$(EXE)
+
+# Scan object files for required primitives
+
+PRIMREQ=primreq.cmo
+
+primreq: $(PRIMREQ)
+ $(CAMLC) $(LINKFLAGS) -o primreq config.cmo $(PRIMREQ)
+
+clean::
+ rm -f primreq
+
+# Common stuff
+
+.SUFFIXES:
+.SUFFIXES: .ml .cmo .mli .cmi .cmx
+
+.ml.cmo:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.mli.cmi:
+ $(CAMLC) -c $(COMPFLAGS) $<
+
+.ml.cmx:
+ $(CAMLOPT) $(COMPFLAGS) -c $<
+
+clean::
+ rm -f *.cmo *.cmi *.cma *.dll *.so *.lib *.a
+
+depend: beforedepend
+ $(CAMLRUN) ./ocamldep $(INCLUDES) *.mli *.ml > .depend
+
+.PHONY: clean install beforedepend depend
+
+include .depend
diff --git a/tools/addlabels.ml b/tools/addlabels.ml
new file mode 100644
index 0000000000..1579be19db
--- /dev/null
+++ b/tools/addlabels.ml
@@ -0,0 +1,466 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique and Kyoto University. All rights reserved. *)
+(* This file is distributed under the terms of the Q Public License *)
+(* version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open StdLabels
+open Asttypes
+open Parsetree
+
+let norec = ref false
+
+let input_file file =
+ let ic = try open_in file with _ -> failwith ("input_file : " ^ file) in
+ let b = Buffer.create 1024 in
+ let buf = String.create 1024 and len = ref 0 in
+ while len := input ic buf 0 1024; !len > 0 do
+ Buffer.add_substring b buf 0 !len
+ done;
+ close_in ic;
+ Buffer.contents b
+
+module SMap = struct
+ include Map.Make(struct type t = string let compare = compare end)
+ let rec removes l m =
+ match l with [] -> m
+ | k::l ->
+ let m = try remove k m with Not_found -> m in
+ removes l m
+end
+
+let rec labels_of_sty sty =
+ match sty.ptyp_desc with
+ Ptyp_arrow (lab, _, rem) -> lab :: labels_of_sty rem
+ | Ptyp_alias (rem, _) -> labels_of_sty rem
+ | _ -> []
+
+let rec labels_of_cty cty =
+ match cty.pcty_desc with
+ Pcty_arrow (lab, _, rem) ->
+ let (labs, meths) = labels_of_cty rem in
+ (lab :: labs, meths)
+ | Pcty_signature { pcsig_fields = fields } ->
+ ([],
+ List.fold_left fields ~init:[] ~f:
+ begin fun meths -> function
+ { pctf_desc = Pctf_meth (s, _, sty) } -> (s, labels_of_sty sty)::meths
+ | _ -> meths
+ end)
+ | _ ->
+ ([],[])
+
+let rec pattern_vars pat =
+ match pat.ppat_desc with
+ Ppat_var s -> [s.txt]
+ | Ppat_alias (pat, s) ->
+ s.txt :: pattern_vars pat
+ | Ppat_tuple l
+ | Ppat_array l ->
+ List.concat (List.map pattern_vars l)
+ | Ppat_construct (_, Some pat)
+ | Ppat_variant (_, Some pat)
+ | Ppat_constraint (pat, _) ->
+ pattern_vars pat
+ | Ppat_record(l, _) ->
+ List.concat (List.map l ~f:(fun (_,p) -> pattern_vars p))
+ | Ppat_or (pat1, pat2) ->
+ pattern_vars pat1 @ pattern_vars pat2
+ | Ppat_lazy pat -> pattern_vars pat
+ | Ppat_any | Ppat_constant _ | Ppat_construct _ | Ppat_variant _
+ | Ppat_type _ | Ppat_unpack _ ->
+ []
+
+let pattern_name pat =
+ match pat.ppat_desc with
+ Ppat_var s -> Some s
+ | Ppat_constraint ({ppat_desc = Ppat_var s}, _) -> Some s
+ | _ -> None
+
+let insertions = ref []
+let add_insertion pos s = insertions := (pos,s) :: !insertions
+let sort_insertions () =
+ List.sort !insertions ~cmp:(fun (pos1,_) (pos2,_) -> pos1 - pos2)
+
+let is_space = function ' '|'\t'|'\n'|'\r' -> true | _ -> false
+let is_alphanum = function 'A'..'Z'|'a'..'z'|'_'|'\192'..'\214'|'\216'..'\246'
+ | '\248'..'\255'|'\''|'0'..'9' -> true
+ | _ -> false
+
+(* Remove "(" or "begin" before a pattern *)
+let rec insertion_point pos ~text =
+ let pos' = ref (pos-1) in
+ while is_space text.[!pos'] do decr pos' done;
+ if text.[!pos'] = '(' then insertion_point !pos' ~text else
+ if !pos' >= 5 && String.sub text ~pos:(!pos'-4) ~len:5 = "begin"
+ && not (is_alphanum text.[!pos'-5]) then insertion_point (!pos'-4) ~text
+ else pos
+
+(* Search "=" or "->" before "function" *)
+let rec insertion_point2 pos ~text =
+ let pos' = ref (pos-1) in
+ while is_space text.[!pos'] do decr pos' done;
+ if text.[!pos'] = '(' then insertion_point2 !pos' ~text else
+ if !pos' >= 5 && String.sub text ~pos:(!pos'-4) ~len:5 = "begin"
+ && not (is_alphanum text.[!pos'-5]) then insertion_point2 (!pos'-4) ~text
+ else if text.[!pos'] = '=' then Some !pos' else
+ if !pos' >= 1 && text.[!pos'-1] = '-' && text.[!pos'] = '>'
+ then Some (!pos' - 1)
+ else None
+
+let rec insert_labels ~labels ~text expr =
+ match labels, expr.pexp_desc with
+ l::labels, Pexp_function(l', _, [pat, rem]) ->
+ if l <> "" && l.[0] <> '?' && l' = "" then begin
+ let start_c = pat.ppat_loc.Location.loc_start.Lexing.pos_cnum in
+ let pos = insertion_point start_c ~text in
+ match pattern_name pat with
+ | Some name when l = name.txt -> add_insertion pos "~"
+ | _ -> add_insertion pos ("~" ^ l ^ ":")
+ end;
+ insert_labels ~labels ~text rem
+ | l::labels, Pexp_function(l', _, lst) ->
+ let pos = expr.pexp_loc.Location.loc_start.Lexing.pos_cnum in
+ if l <> "" && l.[0] <> '?' && l' = ""
+ && String.sub text ~pos ~len:8 = "function" then begin
+ String.blit ~src:"match th" ~src_pos:0 ~dst:text
+ ~dst_pos:pos ~len:8;
+ add_insertion (pos+6) (l ^ " wi");
+ match insertion_point2 pos ~text with
+ Some pos' ->
+ add_insertion pos' ("~" ^ l ^ " ")
+ | None ->
+ add_insertion pos ("fun ~" ^ l ^ " -> ")
+ end;
+ List.iter lst ~f:(fun (p,e) -> insert_labels ~labels ~text e)
+ | _, Pexp_match( _, lst) ->
+ List.iter lst ~f:(fun (p,e) -> insert_labels ~labels ~text e)
+ | _, Pexp_try(expr, lst) ->
+ insert_labels ~labels ~text expr;
+ List.iter lst ~f:(fun (p,e) -> insert_labels ~labels ~text e)
+ | _, ( Pexp_let(_,_,e) | Pexp_sequence(_,e) | Pexp_when(_,e)
+ | Pexp_constraint(e,_,_) | Pexp_letmodule(_,_,e)
+ | Pexp_ifthenelse(_,e,None) ) ->
+ insert_labels ~labels ~text e
+ | _, Pexp_ifthenelse (_, e1, Some e2) ->
+ insert_labels ~labels ~text e1;
+ insert_labels ~labels ~text e2
+ | _ ->
+ ()
+
+let rec insert_labels_class ~labels ~text expr =
+ match labels, expr.pcl_desc with
+ l::labels, Pcl_fun(l', _, pat, rem) ->
+ if l <> "" && l.[0] <> '?' && l' = "" then begin
+ let start_c = pat.ppat_loc.Location.loc_start.Lexing.pos_cnum in
+ let pos = insertion_point start_c ~text in
+ match pattern_name pat with
+ | Some name when l = name.txt -> add_insertion pos "~"
+ | _ -> add_insertion pos ("~" ^ l ^ ":")
+ end;
+ insert_labels_class ~labels ~text rem
+ | labels, (Pcl_constraint (expr, _) | Pcl_let (_, _, expr)) ->
+ insert_labels_class ~labels ~text expr
+ | _ ->
+ ()
+
+let rec insert_labels_type ~labels ~text ty =
+ match labels, ty.ptyp_desc with
+ l::labels, Ptyp_arrow(l', _, rem) ->
+ if l <> "" && l.[0] <> '?' && l' = "" then begin
+ let start_c = ty.ptyp_loc.Location.loc_start.Lexing.pos_cnum in
+ let pos = insertion_point start_c ~text in
+ add_insertion pos (l ^ ":")
+ end;
+ insert_labels_type ~labels ~text rem
+ | _ ->
+ ()
+
+let rec insert_labels_app ~labels ~text args =
+ match labels, args with
+ l::labels, (l',arg)::args ->
+ if l <> "" && l.[0] <> '?' && l' = "" then begin
+ let pos0 = arg.pexp_loc.Location.loc_start.Lexing.pos_cnum in
+ let pos = insertion_point pos0 ~text in
+ match arg.pexp_desc with
+ | Pexp_ident({ txt = Longident.Lident name })
+ when l = name && pos = pos0 ->
+ add_insertion pos "~"
+ | _ -> add_insertion pos ("~" ^ l ^ ":")
+ end;
+ insert_labels_app ~labels ~text args
+ | _ ->
+ ()
+
+let insert_labels_app ~labels ~text args =
+ let labels, opt_labels =
+ List.partition labels ~f:(fun l -> l = "" || l.[0] <> '?') in
+ let nopt_labels =
+ List.map opt_labels
+ ~f:(fun l -> String.sub l ~pos:1 ~len:(String.length l - 1)) in
+ (* avoid ambiguous labels *)
+ if List.exists labels ~f:(List.mem ~set:nopt_labels) then () else
+ let aopt_labels = opt_labels @ nopt_labels in
+ let args, lab_args = List.partition args ~f:(fun (l,_) -> l = "") in
+ (* only optional arguments are labeled *)
+ if List.for_all lab_args ~f:(fun (l,_) -> List.mem l ~set:aopt_labels)
+ then insert_labels_app ~labels ~text args
+
+let rec add_labels_expr ~text ~values ~classes expr =
+ let add_labels_rec ?(values=values) expr =
+ add_labels_expr ~text ~values ~classes expr in
+ match expr.pexp_desc with
+ Pexp_apply ({pexp_desc=Pexp_ident({ txt = Longident.Lident s })}, args) ->
+ begin try
+ let labels = SMap.find s values in
+ insert_labels_app ~labels ~text args
+ with Not_found -> ()
+ end;
+ List.iter args ~f:(fun (_,e) -> add_labels_rec e)
+ | Pexp_apply ({pexp_desc=Pexp_send
+ ({pexp_desc=Pexp_ident({ txt = Longident.Lident s })},
+ meth)},
+ args) ->
+ begin try
+ if SMap.find s values = ["<object>"] then
+ let labels = SMap.find (s ^ "#" ^ meth) values in
+ insert_labels_app ~labels ~text args
+ with Not_found -> ()
+ end
+ | Pexp_apply ({pexp_desc=Pexp_new ({ txt = Longident.Lident s })}, args) ->
+ begin try
+ let labels = SMap.find s classes in
+ insert_labels_app ~labels ~text args
+ with Not_found -> ()
+ end
+ | Pexp_let (recp, lst, expr) ->
+ let vars = List.concat (List.map lst ~f:(fun (p,_) -> pattern_vars p)) in
+ let vals = SMap.removes vars values in
+ List.iter lst ~f:
+ begin fun (_,e) ->
+ add_labels_rec e ~values:(if recp = Recursive then vals else values)
+ end;
+ add_labels_rec expr ~values:vals
+ | Pexp_function (_, None, lst) ->
+ List.iter lst ~f:
+ (fun (p,e) ->
+ add_labels_rec e ~values:(SMap.removes (pattern_vars p) values))
+ | Pexp_function (_, Some e, lst)
+ | Pexp_match (e, lst)
+ | Pexp_try (e, lst) ->
+ add_labels_rec e;
+ List.iter lst ~f:
+ (fun (p,e) ->
+ add_labels_rec e ~values:(SMap.removes (pattern_vars p) values))
+ | Pexp_apply (e, args) ->
+ List.iter add_labels_rec (e :: List.map snd args)
+ | Pexp_tuple l | Pexp_array l ->
+ List.iter add_labels_rec l
+ | Pexp_construct (_, Some e)
+ | Pexp_variant (_, Some e)
+ | Pexp_field (e, _)
+ | Pexp_constraint (e, _, _)
+ | Pexp_send (e, _)
+ | Pexp_setinstvar (_, e)
+ | Pexp_letmodule (_, _, e)
+ | Pexp_assert e
+ | Pexp_lazy e
+ | Pexp_poly (e, _)
+ | Pexp_newtype (_, e)
+ | Pexp_open (_, e) ->
+ add_labels_rec e
+ | Pexp_record (lst, opt) ->
+ List.iter lst ~f:(fun (_,e) -> add_labels_rec e);
+ begin match opt with Some e -> add_labels_rec e | None -> () end
+ | Pexp_setfield (e1, _, e2)
+ | Pexp_ifthenelse (e1, e2, None)
+ | Pexp_sequence (e1, e2)
+ | Pexp_while (e1, e2)
+ | Pexp_when (e1, e2) ->
+ add_labels_rec e1; add_labels_rec e2
+ | Pexp_ifthenelse (e1, e2, Some e3) ->
+ add_labels_rec e1; add_labels_rec e2; add_labels_rec e3
+ | Pexp_for (s, e1, e2, _, e3) ->
+ add_labels_rec e1; add_labels_rec e2;
+ add_labels_rec e3 ~values:(SMap.removes [s.txt] values)
+ | Pexp_override lst ->
+ List.iter lst ~f:(fun (_,e) -> add_labels_rec e)
+ | Pexp_ident _ | Pexp_constant _ | Pexp_construct _ | Pexp_variant _
+ | Pexp_new _ | Pexp_object _ | Pexp_pack _ ->
+ ()
+
+let rec add_labels_class ~text ~classes ~values ~methods cl =
+ match cl.pcl_desc with
+ Pcl_constr _ -> ()
+ | Pcl_structure { pcstr_self = p; pcstr_fields = l } ->
+ let values = SMap.removes (pattern_vars p) values in
+ let values =
+ match pattern_name p with None -> values
+ | Some s ->
+ List.fold_left methods
+ ~init:(SMap.add s.txt ["<object>"] values)
+ ~f:(fun m (k,l) -> SMap.add (s.txt^"#"^k) l m)
+ in
+ ignore (List.fold_left l ~init:values ~f:
+ begin fun values -> function e -> match e.pcf_desc with
+ | Pcf_val (s, _, _, e) ->
+ add_labels_expr ~text ~classes ~values e;
+ SMap.removes [s.txt] values
+ | Pcf_meth (s, _, _, e) ->
+ begin try
+ let labels = List.assoc s.txt methods in
+ insert_labels ~labels ~text e
+ with Not_found -> ()
+ end;
+ add_labels_expr ~text ~classes ~values e;
+ values
+ | Pcf_init e ->
+ add_labels_expr ~text ~classes ~values e;
+ values
+ | Pcf_inher _ | Pcf_valvirt _ | Pcf_virt _ | Pcf_constr _ -> values
+ end)
+ | Pcl_fun (_, opt, pat, cl) ->
+ begin match opt with None -> ()
+ | Some e -> add_labels_expr ~text ~classes ~values e
+ end;
+ let values = SMap.removes (pattern_vars pat) values in
+ add_labels_class ~text ~classes ~values ~methods cl
+ | Pcl_apply (cl, args) ->
+ List.iter args ~f:(fun (_,e) -> add_labels_expr ~text ~classes ~values e);
+ add_labels_class ~text ~classes ~values ~methods cl
+ | Pcl_let (recp, lst, cl) ->
+ let vars = List.concat (List.map lst ~f:(fun (p,_) -> pattern_vars p)) in
+ let vals = SMap.removes vars values in
+ List.iter lst ~f:
+ begin fun (_,e) ->
+ add_labels_expr e ~text ~classes
+ ~values:(if recp = Recursive then vals else values)
+ end;
+ add_labels_class cl ~text ~classes ~values:vals ~methods
+ | Pcl_constraint (cl, _) ->
+ add_labels_class ~text ~classes ~values ~methods cl
+
+let add_labels ~intf ~impl ~file =
+ insertions := [];
+ let values, classes =
+ List.fold_left intf ~init:(SMap.empty, SMap.empty) ~f:
+ begin fun (values, classes as acc) item ->
+ match item.psig_desc with
+ Psig_value (name, {pval_type = sty}) ->
+ (SMap.add name.txt (labels_of_sty sty) values, classes)
+ | Psig_class l ->
+ (values,
+ List.fold_left l ~init:classes ~f:
+ begin fun classes {pci_name=name; pci_expr=cty} ->
+ SMap.add name.txt (labels_of_cty cty) classes
+ end)
+ | _ ->
+ acc
+ end
+ in
+ let text = input_file file in
+ ignore (List.fold_right impl ~init:(values, classes) ~f:
+ begin fun item (values, classes as acc) ->
+ match item.pstr_desc with
+ Pstr_value (recp, l) ->
+ let names =
+ List.concat (List.map l ~f:(fun (p,_) -> pattern_vars p)) in
+ List.iter l ~f:
+ begin fun (pat, expr) ->
+ begin match pattern_name pat with
+ | Some s ->
+ begin try
+ let labels = SMap.find s.txt values in
+ insert_labels ~labels ~text expr;
+ if !norec then () else
+ let values =
+ SMap.fold
+ (fun s l m ->
+ if List.mem s names then SMap.add s l m else m)
+ values SMap.empty in
+ add_labels_expr expr ~text ~values ~classes:SMap.empty
+ with Not_found -> ()
+ end
+ | None -> ()
+ end;
+ end;
+ (SMap.removes names values, classes)
+ | Pstr_primitive (s, {pval_type=sty}) ->
+ begin try
+ let labels = SMap.find s.txt values in
+ insert_labels_type ~labels ~text sty;
+ (SMap.removes [s.txt] values, classes)
+ with Not_found -> acc
+ end
+ | Pstr_class l ->
+ let names = List.map l ~f:(fun pci -> pci.pci_name.txt) in
+ List.iter l ~f:
+ begin fun {pci_name=name; pci_expr=expr} ->
+ try
+ let (labels, methods) = SMap.find name.txt classes in
+ insert_labels_class ~labels ~text expr;
+ if !norec then () else
+ let classes =
+ SMap.fold
+ (fun s (l,_) m ->
+ if List.mem s names then SMap.add s l m else m)
+ classes SMap.empty in
+ add_labels_class expr ~text ~classes ~methods
+ ~values:SMap.empty
+ with Not_found -> ()
+ end;
+ (values, SMap.removes names classes)
+ | _ ->
+ acc
+ end);
+ if !insertions <> [] then begin
+ let backup = file ^ ".bak" in
+ if Sys.file_exists backup then Sys.remove file
+ else Sys.rename file backup;
+ let oc = open_out file in
+ let last_pos =
+ List.fold_left (sort_insertions ()) ~init:0 ~f:
+ begin fun pos (pos', s) ->
+ output oc text pos (pos'-pos);
+ output_string oc s;
+ pos'
+ end in
+ if last_pos < String.length text then
+ output oc text last_pos (String.length text - last_pos);
+ close_out oc
+ end
+ else prerr_endline ("No labels to insert in " ^ file)
+
+let process_file file =
+ prerr_endline ("Processing " ^ file);
+ if Filename.check_suffix file ".ml" then
+ let intf = Filename.chop_suffix file ".ml" ^ ".mli" in
+ let ic = open_in intf in
+ let lexbuf = Lexing.from_channel ic in
+ Location.init lexbuf intf;
+ let intf = Parse.interface lexbuf in
+ close_in ic;
+ let ic = open_in file in
+ let lexbuf = Lexing.from_channel ic in
+ Location.init lexbuf file;
+ let impl = Parse.implementation lexbuf in
+ close_in ic;
+ add_labels ~intf ~impl ~file
+ else prerr_endline (file ^ " is not an implementation")
+
+let main () =
+ let files = ref [] in
+ Arg.parse ["-norec", Arg.Set norec, "do not labelize recursive calls"]
+ (fun f -> files := f :: !files)
+ "addlabels [-norec] <files>";
+ let files = List.rev !files in
+ List.iter files ~f:process_file
+
+let () = main ()
diff --git a/tools/check-typo b/tools/check-typo
new file mode 100755
index 0000000000..a28e4dc153
--- /dev/null
+++ b/tools/check-typo
@@ -0,0 +1,239 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2012 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# check-typo - Check typographic conventions on OCaml sources.
+
+# This program will check files for the following rules:
+
+# - absence of TAB characters (tab)
+# - absence of non-ASCII characters (non-ascii)
+# - absence of non-printing ASCII characters (non-printing)
+# - absence of white space at end of line (white-at-eol)
+# - absence of empty lines at end of file (white-at-eof)
+# - presence of a LF character at the end of the file (missing-lf)
+# - maximum line length of 80 characters (long-line)
+# - maximum line length of 132 characters (very-long-line)
+# - presence of a copyright header (missing-header)
+# - absence of a leftover "$Id" string (svn-keyword)
+
+# Exceptions are handled with a SVN property: "ocaml:typo".
+# Its value for a given file is a comma-separated list of rule names,
+# which lists the rules that should be disabled for this file.
+# The rule names are the ones shown above in parentheses.
+
+# Built-in exceptions:
+# - Any binary file (i.e. with svn:mime-type = application/octet-stream)
+# is automatically exempt from all the rules.
+# - Any file whose name matches one of the following patterns is
+# automatically exempt from all rules
+# *.reference
+# */reference
+# */.depend*
+# - Any file whose name begins with "Makefile" is automatically exempt
+# from the "tabs" rule.
+# - Any file whose name matches one of the following patterns is
+# automatically exempt from the "missing-header" rule.
+# */.ignore
+# *.mlpack
+# *.mllib
+# *.mltop
+# *.odocl
+# *.clib
+# - Any file whose name matches the following pattern is automatically
+# exempt from the "long-line" rule (but not from "very-long-line").
+# */ocamldoc/*
+
+# ASCII characters are bytes from 0 to 127. Any other byte is
+# flagged as a non-ASCII character.
+
+# For the purpose of this tool, printing ASCII characters are:
+# - the non-white printable ASCII characters (33 to 126)
+# - TAB (09)
+# - LF (10)
+# - SPC (32)
+# Anything else is flagged as a non-printing ASCII character.
+
+# This program will recursively explore the files and directories given
+# on the command line (or by default the current directory), and check
+# every file therein for compliance to the rules.
+
+# Directories named .svn and _build (and their contents) are always ignored.
+# This program ignores any file that is not under svn control, unless
+# explicitly given on the command line.
+
+# If a directory has the SVN property "ocaml:typo" set to "prune",
+# then it and its contents are ignored.
+
+# You can ignore a rule by giving the option -<rule> on the command
+# line (before any file names).
+
+# Special case for recursive call from the find command (see IGNORE_DIRS).
+case "$1" in
+ --check-prune)
+ case `svn propget ocaml:typo "$2" 2>/dev/null` in
+ prune) echo "INFO: pruned directory $2 (ocaml:typo=prune)" >&2; exit 0;;
+ *) exit 3;;
+ esac;;
+esac
+
+usage () {
+ echo "usage: check-typo {-<rule>} [--] {<file-or-dir>}" >&2
+ exit 2
+}
+
+userrules=''
+
+while : ; do
+ case "$1" in
+ -help|--help) usage;;
+ -*) userrules="${1#-},$userrules"; shift;;
+ --) shift; break;;
+ *) break;;
+ esac
+done
+
+IGNORE_DIRS="
+ -name .svn -prune -o
+ -name _build -prune -o
+ -type d -exec $0 --check-prune {} ; -prune -o
+"
+
+( case $# in
+ 0) find . $IGNORE_DIRS -type f -print;;
+ *) for i in "$@"; do find "$i" $IGNORE_DIRS -type f -print; done;;
+ esac
+) | (
+ while read f; do
+ case `svn status "$f" 2>&1` in
+ '?'*) is_svn=false;;
+ I*) is_svn=false;;
+ svn:*"is not a working copy") is_svn=false;;
+ *) is_svn=true;;
+ esac
+ case "$*" in
+ *$f*) is_cmd_line=true;;
+ *) is_cmd_line=false;;
+ esac
+ if $is_svn || $is_cmd_line; then :; else continue; fi
+ svnrules=''
+ if $is_svn; then
+ case `svn propget svn:mime-type "$f"` in
+ application/octet-stream) continue;;
+ esac
+ svnrules=`svn propget ocaml:typo "$f"`
+ fi
+ rules="$userrules"
+ add_hd(){ rules="missing-header,$rules"; }
+ case "$f" in
+ Makefile*|*/Makefile*) rules="tab,$rules";;
+ */.ignore) add_hd;;
+ *.mlpack|*.mllib|*.mltop|*.odocl|*.itarget|*.clib) add_hd;;
+ *.reference|*/reference|*/.depend*) continue;;
+ esac
+ case "$f" in
+ ocamldoc/*|*/ocamldoc/*) rules="long-line,$rules";;
+ esac
+
+ (cat "$f"; echo) \
+ | awk -v rules="$rules" -v svnrules="$svnrules" -v file="$f" \
+ '
+ function err(name, msg) {
+ ++ counts[name];
+ if (("," rules svnrules ",") !~ ("[, ]" name "[, ]") \
+ && counts[name] <= 10){
+ printf ("%s:%d.%d:", file, NR, RSTART + RLENGTH);
+ printf (" [%s] %s\n", name, msg);
+ if (counts[name] == 10){
+ printf ("WARNING: too many [%s] in this file.", name);
+ printf (" Others will not be reported.\n");
+ }
+ }
+ }
+
+ match($0, /\t/) {
+ err("tab", "TAB character(s)");
+ }
+
+ match($0, /[\200-\377]/) {
+ err("non-ascii", "non-ASCII character(s)");
+ }
+
+ match($0, /[^\t\200-\377 -~]/) {
+ err("non-printing", "non-printing ASCII character(s)");
+ }
+
+ match($0, /[ \t]+$/) {
+ err("white-at-eol", "whitespace at end of line");
+ }
+
+ match($0, /\$Id(: .*)?\$/) {
+ err("svn-keyword", "SVN keyword marker");
+ }
+
+ length($0) > 80 {
+ RSTART = 81;
+ RLENGTH = 0;
+ err("long-line", "line is over 80 characters");
+ }
+
+ length($0) > 132 {
+ RSTART = 133;
+ RLENGTH = 0;
+ err("very-long-line", "line is over 132 characters");
+ }
+
+ 3 <= NR && NR <= 5 \
+ && (/ OCaml / || / ocamlbuild / || / OCamldoc /) {
+ header_ocaml = NR;
+ }
+
+ header_ocaml && header_ocaml + 4 <= NR && NR <= header_ocaml + 6 \
+ && / Copyright / {
+ header_copyright = 1;
+ }
+
+ {
+ prev_line = last_line;
+ last_line = $0;
+ }
+
+ END {
+ if (match(last_line, /.+/)){
+ err("missing-lf", "missing linefeed at EOF");
+ prev_line = last_line;
+ ++ NR;
+ empty_file = 0;
+ }else{
+ empty_file = NR == 1;
+ }
+ if (!empty_file && match(prev_line, /^$/)){
+ err("white-at-eof", "empty line(s) at EOF");
+ }
+ NR = 1;
+ RSTART = 1;
+ RLENGTH = 0;
+ if (!(header_ocaml && header_copyright)){
+ err("missing-header", "missing copyright header");
+ }
+ split(svnrules, r, "[, ]");
+ for (i in r){
+ name = r[i];
+ if (name != "" && !counts[name]){
+ err("unused-prop", sprintf("unused [%s] in ocaml:typo", name));
+ }
+ }
+ }
+ '
+ done
+)
diff --git a/tools/checkstack.c b/tools/checkstack.c
new file mode 100644
index 0000000000..dea6a0a6a3
--- /dev/null
+++ b/tools/checkstack.c
@@ -0,0 +1,40 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Damien Doligez, projet Moscova, INRIA Rocquencourt */
+/* */
+/* Copyright 2002 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+
+#define MINSTACKBYTES (384 * 1024 * sizeof (long))
+
+int main(int argc, char ** argv)
+{
+ struct rlimit limit;
+ int rc;
+
+ rc = getrlimit (RLIMIT_STACK, &limit);
+ if (rc != 0) exit (0);
+ if (limit.rlim_cur < MINSTACKBYTES){
+ fprintf (stderr,
+ "\nThe current stack size limit is too low (%luk)\n"
+ "You must increase it with one of the following commands:\n"
+ "Under sh, bash, zsh: ulimit -s %lu\n"
+ "Under csh, tcsh: limit stacksize %lu\n\n",
+ (unsigned long) (limit.rlim_cur / 1024),
+ (unsigned long) (MINSTACKBYTES / 1024),
+ (unsigned long) (MINSTACKBYTES / 1024));
+ exit (3);
+ }
+ exit (0);
+}
diff --git a/tools/ci-build b/tools/ci-build
new file mode 100755
index 0000000000..31a2540351
--- /dev/null
+++ b/tools/ci-build
@@ -0,0 +1,171 @@
+#!/bin/sh
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2014 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# This script is run on our continuous-integration servers to recompile
+# from scratch and run the test suite.
+
+# arguments:
+# 1. architecture: bsd, macos, linux, cygwin, mingw, mingw64, msvc, msvc64
+# 2. directory in which to build (trunk, 4.02, etc)
+# for windows, this is relative to $HOME/jenkins-workspace
+# for bsd, macos, linux, this is "." or an absolute directory
+# 3. options:
+# -conf configure-option
+# -patch1 file-name apply patch with -p1
+
+error () {
+ echo "$1" >&2
+ exit 3
+}
+
+quote1 () {
+ printf "'%s'" "`printf %s "$1" | sed -e "s/'/'\\\\\\\\''/g"`";
+}
+
+#########################################################################
+# be verbose
+set -x
+
+#########################################################################
+# "Parse" mandatory command-line arguments.
+
+arch="$1"
+branch="$2"
+shift 2
+
+#########################################################################
+# If we are called from a Windows batch script, we must set up the
+# Unix environment variables (e.g. PATH).
+
+case "$arch" in
+ bsd|macos|linux) ;;
+ cygwin|mingw|mingw64)
+ . /etc/profile
+ . "$HOME/.profile"
+ ;;
+ msvc)
+ . /etc/profile
+ . "$HOME/.profile"
+ . "$HOME/.msenv32"
+ ;;
+ msvc64)
+ . /etc/profile
+ . "$HOME/.profile"
+ . "$HOME/.msenv64"
+ ;;
+ *) error "unknown architecture: $arch";;
+esac
+
+#########################################################################
+
+# be verbose and stop on error
+set -ex
+
+#########################################################################
+# set up variables
+
+# default values
+make=make
+instdir="$HOME/ocaml-tmp-install"
+workdir="$branch"
+docheckout=false
+nt=
+
+case "$arch" in
+ bsd)
+ make=gmake
+ ;;
+ macos)
+ workdir=.
+ ;;
+ linux)
+ workdir=.
+ ;;
+ cygwin)
+ workdir="$HOME/jenkins-workspace/$branch"
+ docheckout=true
+ ;;
+ mingw)
+ instdir=/cygdrive/c/ocamlmgw
+ workdir="$HOME/jenkins-workspace/$branch"
+ docheckout=true
+ nt=.nt
+ ;;
+ mingw64)
+ instdir=/cygdrive/c/ocamlmgw64
+ workdir="$HOME/jenkins-workspace/$branch"
+ docheckout=true
+ nt=.nt
+ ;;
+ msvc)
+ instdir=/cygdrive/c/ocamlms
+ workdir="$HOME/jenkins-workspace/$branch"
+ docheckout=true
+ nt=.nt
+ ;;
+ msvc64)
+ instdir=/cygdrive/c/ocamlms64
+ workdir="$HOME/jenkins-workspace/$branch"
+ docheckout=true
+ nt=.nt
+ ;;
+ *) error "unknown architecture: $arch";;
+esac
+
+#########################################################################
+# Go to the right directory
+
+pwd
+cd "$workdir"
+
+#########################################################################
+# parse optional command-line arguments (has to be done after the "cd")
+# Configure options are not allowed to have spaces or special characters
+# for the moment. We'll fix that when needed.
+confoptions=""
+while [ $# -gt 0 ]; do
+ case $1 in
+ -conf) confoptions="$confoptions `quote1 "$2"`"; shift 2;;
+ -patch1) patch -f -p1 <"$2"; shift 2;;
+ *) error "unknown option $1";;
+ esac
+done
+
+#########################################################################
+# Do the work
+
+# Tell gcc to use only ASCII in its diagnostic outputs.
+export LC_ALL=C
+
+$make -f Makefile$nt distclean || :
+
+if $docheckout; then
+ svn update --accept theirs-full
+fi
+
+case $nt in
+ "") eval "./configure -prefix '$instdir' $confoptions";;
+ .nt)
+ cp config/m-nt.h config/m.h
+ cp config/s-nt.h config/s.h
+ cp config/Makefile.$arch config/Makefile
+ ;;
+ *) error "internal error";;
+esac
+
+$make -f Makefile$nt world.opt
+$make -f Makefile$nt install
+
+rm -rf "$instdir"
+cd testsuite
+$make all
diff --git a/tools/cleanup-header b/tools/cleanup-header
new file mode 100644
index 0000000000..bc64f2e921
--- /dev/null
+++ b/tools/cleanup-header
@@ -0,0 +1,26 @@
+#!/bin/sed -f
+
+#######################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2002 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#######################################################################
+
+# Remove private parts from runtime include files, before installation
+# in /usr/local/lib/ocaml/caml
+
+/\/\* <include \.\.\/config\/m\.h> \*\// {
+ r ../config/m.h
+ d
+}
+/\/\* <include \.\.\/config\/s\.h> \*\// {
+ r ../config/s.h
+ d
+}
+/\/\* <private> \*\//,/\/\* <\/private> \*\//d
diff --git a/tools/cmt2annot.ml b/tools/cmt2annot.ml
new file mode 100644
index 0000000000..820bd0c7f4
--- /dev/null
+++ b/tools/cmt2annot.ml
@@ -0,0 +1,211 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Generate an .annot file from a .cmt file. *)
+
+open Asttypes
+open Typedtree
+open Tast_mapper
+
+let bind_variables scope =
+ let super = Tast_mapper.default in
+ let pat sub p =
+ begin match p.pat_desc with
+ | Tpat_var (id, _) | Tpat_alias (_, id, _) ->
+ Stypes.record (Stypes.An_ident (p.pat_loc,
+ Ident.name id,
+ Annot.Idef scope))
+ | _ -> ()
+ end;
+ super.pat sub p;
+ in
+ {super with pat}
+
+let bind_variables scope =
+ let o = bind_variables scope in
+ fun p -> ignore (o.pat o p)
+
+let bind_bindings scope bindings =
+ let o = bind_variables scope in
+ List.iter (fun x -> o x.vb_pat) bindings
+
+let bind_cases l =
+ List.iter
+ (fun {c_lhs; c_guard; c_rhs} ->
+ let loc =
+ let open Location in
+ match c_guard with
+ | None -> c_rhs.exp_loc
+ | Some g -> {c_rhs.exp_loc with loc_start=g.exp_loc.loc_start}
+ in
+ bind_variables loc c_lhs
+ )
+ l
+
+let rec iterator ~scope rebuild_env =
+ let super = Tast_mapper.default in
+ let class_expr sub node =
+ Stypes.record (Stypes.Ti_class node);
+ super.class_expr sub node
+
+ and module_expr _sub node =
+ Stypes.record (Stypes.Ti_mod node);
+ super.module_expr (iterator ~scope:node.mod_loc rebuild_env) node
+
+ and expr sub exp =
+ begin match exp.exp_desc with
+ | Texp_ident (path, _, _) ->
+ let full_name = Path.name ~paren:Oprint.parenthesized_ident path in
+ let env =
+ if rebuild_env then
+ try
+ Env.env_of_only_summary Envaux.env_from_summary exp.exp_env
+ with Envaux.Error err ->
+ Format.eprintf "%a@." Envaux.report_error err;
+ exit 2
+ else
+ exp.exp_env
+ in
+ let annot =
+ try
+ let desc = Env.find_value path env in
+ let dloc = desc.Types.val_loc in
+ if dloc.Location.loc_ghost then Annot.Iref_external
+ else Annot.Iref_internal dloc
+ with Not_found ->
+ Annot.Iref_external
+ in
+ Stypes.record
+ (Stypes.An_ident (exp.exp_loc, full_name , annot))
+ | Texp_let (Recursive, bindings, _) ->
+ bind_bindings exp.exp_loc bindings
+ | Texp_let (Nonrecursive, bindings, body) ->
+ bind_bindings body.exp_loc bindings
+ | Texp_match (_, f1, f2, _) ->
+ bind_cases f1;
+ bind_cases f2
+ | Texp_function (_, f, _)
+ | Texp_try (_, f) ->
+ bind_cases f
+ | _ -> ()
+ end;
+ Stypes.record (Stypes.Ti_expr exp);
+ super.expr sub exp
+
+ and pat sub p =
+ Stypes.record (Stypes.Ti_pat p);
+ super.pat sub p
+ in
+
+ let structure_item_rem sub s rem =
+ begin match s with
+ | {str_desc = Tstr_value (rec_flag, bindings); str_loc = loc} ->
+ let open Location in
+ let doit loc_start = bind_bindings {scope with loc_start} bindings in
+ begin match rec_flag, rem with
+ | Recursive, _ -> doit loc.loc_start
+ | Nonrecursive, [] -> doit loc.loc_end
+ | Nonrecursive, {str_loc = loc2} :: _ -> doit loc2.loc_start
+ end
+ | _ ->
+ ()
+ end;
+ Stypes.record_phrase s.str_loc;
+ super.structure_item sub s
+ in
+ let structure_item sub s =
+ (* This will be used for Partial_structure_item.
+ We don't have here the location of the "next" item,
+ this will give a slightly different scope for the non-recursive
+ binding case. *)
+ structure_item_rem sub s []
+ and structure sub l =
+ let rec loop = function
+ | str :: rem -> structure_item_rem sub str rem :: loop rem
+ | [] -> []
+ in
+ {l with str_items = loop l.str_items}
+ in
+ {super with class_expr; module_expr; expr; pat; structure_item; structure}
+
+let binary_part iter x =
+ let app f x = ignore (f iter x) in
+ let open Cmt_format in
+ match x with
+ | Partial_structure x -> app iter.structure x
+ | Partial_structure_item x -> app iter.structure_item x
+ | Partial_expression x -> app iter.expr x
+ | Partial_pattern x -> app iter.pat x
+ | Partial_class_expr x -> app iter.class_expr x
+ | Partial_signature x -> app iter.signature x
+ | Partial_signature_item x -> app iter.signature_item x
+ | Partial_module_type x -> app iter.module_type x
+
+let gen_annot target_filename filename
+ {Cmt_format.cmt_loadpath; cmt_annots; cmt_use_summaries; _} =
+ let open Cmt_format in
+ Envaux.reset_cache ();
+ Config.load_path := cmt_loadpath;
+ let target_filename =
+ match target_filename with
+ | None -> Some (filename ^ ".annot")
+ | Some "-" -> None
+ | Some _ -> target_filename
+ in
+ let iterator = iterator ~scope:Location.none cmt_use_summaries in
+ match cmt_annots with
+ | Implementation typedtree ->
+ ignore (iterator.structure iterator typedtree);
+ Stypes.dump target_filename
+ | Interface _ ->
+ Printf.eprintf "Cannot generate annotations for interface file\n%!";
+ exit 2
+ | Partial_implementation parts ->
+ Array.iter (binary_part iterator) parts;
+ Stypes.dump target_filename
+ | _ ->
+ Printf.fprintf stderr "File was generated with an error\n%!";
+ exit 2
+
+
+
+let gen_ml target_filename filename cmt =
+ let (printer, ext) =
+ match cmt.Cmt_format.cmt_annots with
+ | Cmt_format.Implementation typedtree ->
+ (fun ppf -> Pprintast.structure ppf
+ (Untypeast.untype_structure typedtree)),
+ ".ml"
+ | Cmt_format.Interface typedtree ->
+ (fun ppf -> Pprintast.signature ppf
+ (Untypeast.untype_signature typedtree)),
+ ".mli"
+ | _ ->
+ Printf.fprintf stderr "File was generated with an error\n%!";
+ exit 2
+ in
+ let target_filename = match target_filename with
+ None -> Some (filename ^ ext)
+ | Some "-" -> None
+ | Some _ -> target_filename
+ in
+ let oc = match target_filename with
+ None -> None
+ | Some filename -> Some (open_out filename) in
+ let ppf = match oc with
+ None -> Format.std_formatter
+ | Some oc -> Format.formatter_of_out_channel oc in
+ printer ppf;
+ Format.pp_print_flush ppf ();
+ match oc with
+ None -> flush stdout
+ | Some oc -> close_out oc
diff --git a/tools/cvt_emit.mll b/tools/cvt_emit.mll
new file mode 100644
index 0000000000..d54243e27c
--- /dev/null
+++ b/tools/cvt_emit.mll
@@ -0,0 +1,83 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+{
+let first_item = ref false
+let command_beginning = ref 0
+
+let add_semicolon () =
+ if !first_item
+ then first_item := false
+ else print_string "; "
+
+let print_unescaped_string s =
+ let l = String.length s in
+ let i = ref 0 in
+ while !i < l do
+ if s.[!i] = '\\'
+ && !i+1 < l
+ && (let c = s.[!i+1] in c = '{' || c = '`') (* ` *)
+ then i := !i+1;
+ print_char s.[!i];
+ i := !i + 1
+ done
+}
+
+rule main = parse
+ "`" { command_beginning := Lexing.lexeme_start lexbuf;
+ first_item := true;
+ print_char '(';
+ command lexbuf;
+ print_char ')';
+ main lexbuf }
+ | "\\`"
+ { print_string "`"; main lexbuf }
+ | eof { () }
+ | _ { print_char(Lexing.lexeme_char lexbuf 0); main lexbuf }
+
+and command = parse
+ "`" { () }
+ | eof { prerr_string "Unterminated `...` at character ";
+ prerr_int !command_beginning;
+ prerr_newline();
+ exit 2 }
+ | "{" [^ '}'] * "}"
+ { let s = Lexing.lexeme lexbuf in
+ add_semicolon();
+ print_string (String.sub s 1 (String.length s - 2));
+ command lexbuf }
+ | ( [^ '`' '{' '\\'] |
+ '\\' ['\\' '"' 'n' 't' 'b' 'r' '`' '{' ] |
+ '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] |
+ '\\' ('\n' | "\r\n")) +
+ { let s = Lexing.lexeme lexbuf in
+ add_semicolon();
+ (* Optimise one-character strings *)
+ if String.length s = 1 && s.[0] <> '\\' && s.[0] <> '\''
+ || String.length s = 2 && s.[0] = '\\' && s.[1] <> '`' && s.[1]<>'{'
+ (* ` *)
+ then begin
+ print_string "emit_char '";
+ print_unescaped_string s;
+ print_string "'"
+ end else begin
+ print_string "emit_string \"";
+ print_unescaped_string s;
+ print_string "\""
+ end;
+ command lexbuf }
+
+{
+let _ = main(Lexing.from_channel stdin)
+
+let _ = exit (0)
+}
diff --git a/tools/depend.ml b/tools/depend.ml
new file mode 100644
index 0000000000..a09c156765
--- /dev/null
+++ b/tools/depend.ml
@@ -0,0 +1,380 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Asttypes
+open Location
+open Longident
+open Parsetree
+
+module StringSet = Set.Make(struct type t = string let compare = compare end)
+
+(* Collect free module identifiers in the a.s.t. *)
+
+let free_structure_names = ref StringSet.empty
+
+let rec add_path bv = function
+ | Lident s ->
+ if not (StringSet.mem s bv)
+ then free_structure_names := StringSet.add s !free_structure_names
+ | Ldot(l, _s) -> add_path bv l
+ | Lapply(l1, l2) -> add_path bv l1; add_path bv l2
+
+let open_module bv lid = add_path bv lid
+
+let add bv lid =
+ match lid.txt with
+ Ldot(l, _s) -> add_path bv l
+ | _ -> ()
+
+let addmodule bv lid = add_path bv lid.txt
+
+let rec add_type bv ty =
+ match ty.ptyp_desc with
+ Ptyp_any -> ()
+ | Ptyp_var _ -> ()
+ | Ptyp_arrow(_, t1, t2) -> add_type bv t1; add_type bv t2
+ | Ptyp_tuple tl -> List.iter (add_type bv) tl
+ | Ptyp_constr(c, tl) -> add bv c; List.iter (add_type bv) tl
+ | Ptyp_object (fl, _) -> List.iter (fun (_, _, t) -> add_type bv t) fl
+ | Ptyp_class(c, tl) -> add bv c; List.iter (add_type bv) tl
+ | Ptyp_alias(t, _) -> add_type bv t
+ | Ptyp_variant(fl, _, _) ->
+ List.iter
+ (function Rtag(_,_,_,stl) -> List.iter (add_type bv) stl
+ | Rinherit sty -> add_type bv sty)
+ fl
+ | Ptyp_poly(_, t) -> add_type bv t
+ | Ptyp_package pt -> add_package_type bv pt
+ | Ptyp_extension _ -> ()
+
+and add_package_type bv (lid, l) =
+ add bv lid;
+ List.iter (add_type bv) (List.map (fun (_, e) -> e) l)
+
+let add_opt add_fn bv = function
+ None -> ()
+ | Some x -> add_fn bv x
+
+let add_constructor_arguments bv = function
+ | Pcstr_tuple l -> List.iter (add_type bv) l
+ | Pcstr_record l -> List.iter (fun l -> add_type bv l.pld_type) l
+
+let add_constructor_decl bv pcd =
+ add_constructor_arguments bv pcd.pcd_args;
+ Misc.may (add_type bv) pcd.pcd_res
+
+let add_type_declaration bv td =
+ List.iter
+ (fun (ty1, ty2, _) -> add_type bv ty1; add_type bv ty2)
+ td.ptype_cstrs;
+ add_opt add_type bv td.ptype_manifest;
+ let add_tkind = function
+ Ptype_abstract -> ()
+ | Ptype_variant cstrs ->
+ List.iter (add_constructor_decl bv) cstrs
+ | Ptype_record lbls ->
+ List.iter (fun pld -> add_type bv pld.pld_type) lbls
+ | Ptype_open -> () in
+ add_tkind td.ptype_kind
+
+let add_extension_constructor bv ext =
+ match ext.pext_kind with
+ Pext_decl(args, rty) ->
+ add_constructor_arguments bv args;
+ Misc.may (add_type bv) rty
+ | Pext_rebind lid -> add bv lid
+
+let add_type_extension bv te =
+ add bv te.ptyext_path;
+ List.iter (add_extension_constructor bv) te.ptyext_constructors
+
+let rec add_class_type bv cty =
+ match cty.pcty_desc with
+ Pcty_constr(l, tyl) ->
+ add bv l; List.iter (add_type bv) tyl
+ | Pcty_signature { pcsig_self = ty; pcsig_fields = fieldl } ->
+ add_type bv ty;
+ List.iter (add_class_type_field bv) fieldl
+ | Pcty_arrow(_, ty1, cty2) ->
+ add_type bv ty1; add_class_type bv cty2
+ | Pcty_extension _ -> ()
+
+and add_class_type_field bv pctf =
+ match pctf.pctf_desc with
+ Pctf_inherit cty -> add_class_type bv cty
+ | Pctf_val(_, _, _, ty) -> add_type bv ty
+ | Pctf_method(_, _, _, ty) -> add_type bv ty
+ | Pctf_constraint(ty1, ty2) -> add_type bv ty1; add_type bv ty2
+ | Pctf_attribute _ -> ()
+ | Pctf_extension _ -> ()
+
+let add_class_description bv infos =
+ add_class_type bv infos.pci_expr
+
+let add_class_type_declaration = add_class_description
+
+let pattern_bv = ref StringSet.empty
+
+let rec add_pattern bv pat =
+ match pat.ppat_desc with
+ Ppat_any -> ()
+ | Ppat_var _ -> ()
+ | Ppat_alias(p, _) -> add_pattern bv p
+ | Ppat_interval _
+ | Ppat_constant _ -> ()
+ | Ppat_tuple pl -> List.iter (add_pattern bv) pl
+ | Ppat_construct(c, op) -> add bv c; add_opt add_pattern bv op
+ | Ppat_record(pl, _) ->
+ List.iter (fun (lbl, p) -> add bv lbl; add_pattern bv p) pl
+ | Ppat_array pl -> List.iter (add_pattern bv) pl
+ | Ppat_or(p1, p2) -> add_pattern bv p1; add_pattern bv p2
+ | Ppat_constraint(p, ty) -> add_pattern bv p; add_type bv ty
+ | Ppat_variant(_, op) -> add_opt add_pattern bv op
+ | Ppat_type li -> add bv li
+ | Ppat_lazy p -> add_pattern bv p
+ | Ppat_unpack id -> pattern_bv := StringSet.add id.txt !pattern_bv
+ | Ppat_exception p -> add_pattern bv p
+ | Ppat_extension _ -> ()
+
+let add_pattern bv pat =
+ pattern_bv := bv;
+ add_pattern bv pat;
+ !pattern_bv
+
+let rec add_expr bv exp =
+ match exp.pexp_desc with
+ Pexp_ident l -> add bv l
+ | Pexp_constant _ -> ()
+ | Pexp_let(rf, pel, e) ->
+ let bv = add_bindings rf bv pel in add_expr bv e
+ | Pexp_fun (_, opte, p, e) ->
+ add_opt add_expr bv opte; add_expr (add_pattern bv p) e
+ | Pexp_function pel ->
+ add_cases bv pel
+ | Pexp_apply(e, el) ->
+ add_expr bv e; List.iter (fun (_,e) -> add_expr bv e) el
+ | Pexp_match(e, pel) -> add_expr bv e; add_cases bv pel
+ | Pexp_try(e, pel) -> add_expr bv e; add_cases bv pel
+ | Pexp_tuple el -> List.iter (add_expr bv) el
+ | Pexp_construct(c, opte) -> add bv c; add_opt add_expr bv opte
+ | Pexp_variant(_, opte) -> add_opt add_expr bv opte
+ | Pexp_record(lblel, opte) ->
+ List.iter (fun (lbl, e) -> add bv lbl; add_expr bv e) lblel;
+ add_opt add_expr bv opte
+ | Pexp_field(e, fld) -> add_expr bv e; add bv fld
+ | Pexp_setfield(e1, fld, e2) -> add_expr bv e1; add bv fld; add_expr bv e2
+ | Pexp_array el -> List.iter (add_expr bv) el
+ | Pexp_ifthenelse(e1, e2, opte3) ->
+ add_expr bv e1; add_expr bv e2; add_opt add_expr bv opte3
+ | Pexp_sequence(e1, e2) -> add_expr bv e1; add_expr bv e2
+ | Pexp_while(e1, e2) -> add_expr bv e1; add_expr bv e2
+ | Pexp_for( _, e1, e2, _, e3) ->
+ add_expr bv e1; add_expr bv e2; add_expr bv e3
+ | Pexp_coerce(e1, oty2, ty3) ->
+ add_expr bv e1;
+ add_opt add_type bv oty2;
+ add_type bv ty3
+ | Pexp_constraint(e1, ty2) ->
+ add_expr bv e1;
+ add_type bv ty2
+ | Pexp_send(e, _m) -> add_expr bv e
+ | Pexp_new li -> add bv li
+ | Pexp_setinstvar(_v, e) -> add_expr bv e
+ | Pexp_override sel -> List.iter (fun (_s, e) -> add_expr bv e) sel
+ | Pexp_letmodule(id, m, e) ->
+ add_module bv m; add_expr (StringSet.add id.txt bv) e
+ | Pexp_assert (e) -> add_expr bv e
+ | Pexp_lazy (e) -> add_expr bv e
+ | Pexp_poly (e, t) -> add_expr bv e; add_opt add_type bv t
+ | Pexp_object { pcstr_self = pat; pcstr_fields = fieldl } ->
+ let bv = add_pattern bv pat in List.iter (add_class_field bv) fieldl
+ | Pexp_newtype (_, e) -> add_expr bv e
+ | Pexp_pack m -> add_module bv m
+ | Pexp_open (_ovf, m, e) -> open_module bv m.txt; add_expr bv e
+ | Pexp_extension _ -> ()
+
+and add_cases bv cases =
+ List.iter (add_case bv) cases
+
+and add_case bv {pc_lhs; pc_guard; pc_rhs} =
+ let bv = add_pattern bv pc_lhs in
+ add_opt add_expr bv pc_guard;
+ add_expr bv pc_rhs
+
+and add_bindings recf bv pel =
+ let bv' = List.fold_left (fun bv x -> add_pattern bv x.pvb_pat) bv pel in
+ let bv = if recf = Recursive then bv' else bv in
+ List.iter (fun x -> add_expr bv x.pvb_expr) pel;
+ bv'
+
+and add_modtype bv mty =
+ match mty.pmty_desc with
+ Pmty_ident l -> add bv l
+ | Pmty_alias l -> addmodule bv l
+ | Pmty_signature s -> add_signature bv s
+ | Pmty_functor(id, mty1, mty2) ->
+ Misc.may (add_modtype bv) mty1;
+ add_modtype (StringSet.add id.txt bv) mty2
+ | Pmty_with(mty, cstrl) ->
+ add_modtype bv mty;
+ List.iter
+ (function
+ | Pwith_type (_, td) -> add_type_declaration bv td
+ | Pwith_module (_, lid) -> addmodule bv lid
+ | Pwith_typesubst td -> add_type_declaration bv td
+ | Pwith_modsubst (_, lid) -> addmodule bv lid
+ )
+ cstrl
+ | Pmty_typeof m -> add_module bv m
+ | Pmty_extension _ -> ()
+
+and add_signature bv = function
+ [] -> ()
+ | item :: rem -> add_signature (add_sig_item bv item) rem
+
+and add_sig_item bv item =
+ match item.psig_desc with
+ Psig_value vd ->
+ add_type bv vd.pval_type; bv
+ | Psig_type (_, dcls) ->
+ List.iter (add_type_declaration bv) dcls; bv
+ | Psig_typext te ->
+ add_type_extension bv te; bv
+ | Psig_exception pext ->
+ add_extension_constructor bv pext; bv
+ | Psig_module pmd ->
+ add_modtype bv pmd.pmd_type; StringSet.add pmd.pmd_name.txt bv
+ | Psig_recmodule decls ->
+ let bv' =
+ List.fold_right StringSet.add
+ (List.map (fun pmd -> pmd.pmd_name.txt) decls) bv
+ in
+ List.iter (fun pmd -> add_modtype bv' pmd.pmd_type) decls;
+ bv'
+ | Psig_modtype x ->
+ begin match x.pmtd_type with
+ None -> ()
+ | Some mty -> add_modtype bv mty
+ end;
+ bv
+ | Psig_open od ->
+ open_module bv od.popen_lid.txt; bv
+ | Psig_include incl ->
+ add_modtype bv incl.pincl_mod; bv
+ | Psig_class cdl ->
+ List.iter (add_class_description bv) cdl; bv
+ | Psig_class_type cdtl ->
+ List.iter (add_class_type_declaration bv) cdtl; bv
+ | Psig_attribute _ | Psig_extension _ ->
+ bv
+
+and add_module bv modl =
+ match modl.pmod_desc with
+ Pmod_ident l -> addmodule bv l
+ | Pmod_structure s -> ignore (add_structure bv s)
+ | Pmod_functor(id, mty, modl) ->
+ Misc.may (add_modtype bv) mty;
+ add_module (StringSet.add id.txt bv) modl
+ | Pmod_apply(mod1, mod2) ->
+ add_module bv mod1; add_module bv mod2
+ | Pmod_constraint(modl, mty) ->
+ add_module bv modl; add_modtype bv mty
+ | Pmod_unpack(e) ->
+ add_expr bv e
+ | Pmod_extension _ ->
+ ()
+
+and add_structure bv item_list =
+ List.fold_left add_struct_item bv item_list
+
+and add_struct_item bv item =
+ match item.pstr_desc with
+ Pstr_eval (e, _attrs) ->
+ add_expr bv e; bv
+ | Pstr_value(rf, pel) ->
+ let bv = add_bindings rf bv pel in bv
+ | Pstr_primitive vd ->
+ add_type bv vd.pval_type; bv
+ | Pstr_type (_, dcls) ->
+ List.iter (add_type_declaration bv) dcls; bv
+ | Pstr_typext te ->
+ add_type_extension bv te;
+ bv
+ | Pstr_exception pext ->
+ add_extension_constructor bv pext; bv
+ | Pstr_module x ->
+ add_module bv x.pmb_expr; StringSet.add x.pmb_name.txt bv
+ | Pstr_recmodule bindings ->
+ let bv' =
+ List.fold_right StringSet.add
+ (List.map (fun x -> x.pmb_name.txt) bindings) bv in
+ List.iter
+ (fun x -> add_module bv' x.pmb_expr)
+ bindings;
+ bv'
+ | Pstr_modtype x ->
+ begin match x.pmtd_type with
+ None -> ()
+ | Some mty -> add_modtype bv mty
+ end;
+ bv
+ | Pstr_open od ->
+ open_module bv od.popen_lid.txt; bv
+ | Pstr_class cdl ->
+ List.iter (add_class_declaration bv) cdl; bv
+ | Pstr_class_type cdtl ->
+ List.iter (add_class_type_declaration bv) cdtl; bv
+ | Pstr_include incl ->
+ add_module bv incl.pincl_mod; bv
+ | Pstr_attribute _ | Pstr_extension _ ->
+ bv
+
+and add_use_file bv top_phrs =
+ ignore (List.fold_left add_top_phrase bv top_phrs)
+
+and add_implementation bv l =
+ ignore (add_structure bv l)
+
+and add_top_phrase bv = function
+ | Ptop_def str -> add_structure bv str
+ | Ptop_dir (_, _) -> bv
+
+and add_class_expr bv ce =
+ match ce.pcl_desc with
+ Pcl_constr(l, tyl) ->
+ add bv l; List.iter (add_type bv) tyl
+ | Pcl_structure { pcstr_self = pat; pcstr_fields = fieldl } ->
+ let bv = add_pattern bv pat in List.iter (add_class_field bv) fieldl
+ | Pcl_fun(_, opte, pat, ce) ->
+ add_opt add_expr bv opte;
+ let bv = add_pattern bv pat in add_class_expr bv ce
+ | Pcl_apply(ce, exprl) ->
+ add_class_expr bv ce; List.iter (fun (_,e) -> add_expr bv e) exprl
+ | Pcl_let(rf, pel, ce) ->
+ let bv = add_bindings rf bv pel in add_class_expr bv ce
+ | Pcl_constraint(ce, ct) ->
+ add_class_expr bv ce; add_class_type bv ct
+ | Pcl_extension _ -> ()
+
+and add_class_field bv pcf =
+ match pcf.pcf_desc with
+ Pcf_inherit(_, ce, _) -> add_class_expr bv ce
+ | Pcf_val(_, _, Cfk_concrete (_, e))
+ | Pcf_method(_, _, Cfk_concrete (_, e)) -> add_expr bv e
+ | Pcf_val(_, _, Cfk_virtual ty)
+ | Pcf_method(_, _, Cfk_virtual ty) -> add_type bv ty
+ | Pcf_constraint(ty1, ty2) -> add_type bv ty1; add_type bv ty2
+ | Pcf_initializer e -> add_expr bv e
+ | Pcf_attribute _ | Pcf_extension _ -> ()
+
+and add_class_declaration bv decl =
+ add_class_expr bv decl.pci_expr
diff --git a/tools/depend.mli b/tools/depend.mli
new file mode 100644
index 0000000000..93fc084f79
--- /dev/null
+++ b/tools/depend.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** Module dependencies. *)
+
+module StringSet : Set.S with type elt = string
+
+val free_structure_names : StringSet.t ref
+
+val open_module : StringSet.t -> Longident.t -> unit
+
+val add_use_file : StringSet.t -> Parsetree.toplevel_phrase list -> unit
+
+val add_signature : StringSet.t -> Parsetree.signature -> unit
+
+val add_implementation : StringSet.t -> Parsetree.structure -> unit
diff --git a/tools/dumpobj.ml b/tools/dumpobj.ml
new file mode 100644
index 0000000000..7fd3e43914
--- /dev/null
+++ b/tools/dumpobj.ml
@@ -0,0 +1,573 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Disassembler for executable and .cmo object files *)
+
+open Asttypes
+open Config
+open Instruct
+open Lambda
+open Location
+open Opcodes
+open Opnames
+open Cmo_format
+open Printf
+
+let print_locations = ref true
+
+(* Read signed and unsigned integers *)
+
+let inputu ic =
+ let b1 = input_byte ic in
+ let b2 = input_byte ic in
+ let b3 = input_byte ic in
+ let b4 = input_byte ic in
+ (b4 lsl 24) + (b3 lsl 16) + (b2 lsl 8) + b1
+
+let inputs ic =
+ let b1 = input_byte ic in
+ let b2 = input_byte ic in
+ let b3 = input_byte ic in
+ let b4 = input_byte ic in
+ let b4' = if b4 >= 128 then b4-256 else b4 in
+ (b4' lsl 24) + (b3 lsl 16) + (b2 lsl 8) + b1
+
+(* Global variables *)
+
+type global_table_entry =
+ Empty
+ | Global of Ident.t
+ | Constant of Obj.t
+
+let start = ref 0 (* Position of beg. of code *)
+let reloc = ref ([] : (reloc_info * int) list) (* Relocation table *)
+let globals = ref ([||] : global_table_entry array) (* Global map *)
+let primitives = ref ([||] : string array) (* Table of primitives *)
+let objfile = ref false (* true if dumping a .cmo *)
+
+(* Events (indexed by PC) *)
+
+let event_table = (Hashtbl.create 253 : (int, debug_event) Hashtbl.t)
+
+let relocate_event orig ev =
+ ev.ev_pos <- orig + ev.ev_pos;
+ match ev.ev_repr with
+ Event_parent repr -> repr := ev.ev_pos
+ | _ -> ()
+
+let record_events orig evl =
+ List.iter
+ (fun ev ->
+ relocate_event orig ev;
+ Hashtbl.add event_table ev.ev_pos ev)
+ evl
+
+(* Print a structured constant *)
+
+let print_float f =
+ if String.contains f '.'
+ then printf "%s" f
+ else printf "%s." f
+;;
+
+let rec print_struct_const = function
+ Const_base(Const_int i) -> printf "%d" i
+ | Const_base(Const_float f) -> print_float f
+ | Const_base(Const_string (s, _)) -> printf "%S" s
+ | Const_immstring s -> printf "%S" s
+ | Const_base(Const_char c) -> printf "%C" c
+ | Const_base(Const_int32 i) -> printf "%ldl" i
+ | Const_base(Const_nativeint i) -> printf "%ndn" i
+ | Const_base(Const_int64 i) -> printf "%LdL" i
+ | Const_pointer n -> printf "%da" n
+ | Const_block(tag, args) ->
+ printf "<%d>" tag;
+ begin match args with
+ [] -> ()
+ | [a1] ->
+ printf "("; print_struct_const a1; printf ")"
+ | a1::al ->
+ printf "("; print_struct_const a1;
+ List.iter (fun a -> printf ", "; print_struct_const a) al;
+ printf ")"
+ end
+ | Const_float_array a ->
+ printf "[|";
+ List.iter (fun f -> print_float f; printf "; ") a;
+ printf "|]"
+
+(* Print an obj *)
+
+let same_custom x y =
+ Obj.field x 0 = Obj.field (Obj.repr y) 0
+
+let rec print_obj x =
+ if Obj.is_block x then begin
+ let tag = Obj.tag x in
+ if tag = Obj.string_tag then
+ printf "%S" (Obj.magic x : string)
+ else if tag = Obj.double_tag then
+ printf "%.12g" (Obj.magic x : float)
+ else if tag = Obj.double_array_tag then begin
+ let a = (Obj.magic x : float array) in
+ printf "[|";
+ for i = 0 to Array.length a - 1 do
+ if i > 0 then printf ", ";
+ printf "%.12g" a.(i)
+ done;
+ printf "|]"
+ end else if tag = Obj.custom_tag && same_custom x 0l then
+ printf "%ldl" (Obj.magic x : int32)
+ else if tag = Obj.custom_tag && same_custom x 0n then
+ printf "%ndn" (Obj.magic x : nativeint)
+ else if tag = Obj.custom_tag && same_custom x 0L then
+ printf "%LdL" (Obj.magic x : int64)
+ else if tag < Obj.no_scan_tag then begin
+ printf "<%d>" (Obj.tag x);
+ match Obj.size x with
+ 0 -> ()
+ | 1 ->
+ printf "("; print_obj (Obj.field x 0); printf ")"
+ | n ->
+ printf "("; print_obj (Obj.field x 0);
+ for i = 1 to n - 1 do
+ printf ", "; print_obj (Obj.field x i)
+ done;
+ printf ")"
+ end else
+ printf "<tag %d>" tag
+ end else
+ printf "%d" (Obj.magic x : int)
+
+(* Current position in input file *)
+
+let currpos ic =
+ pos_in ic - !start
+
+(* Access in the relocation table *)
+
+let rec rassoc key = function
+ [] -> raise Not_found
+ | (a,b) :: l -> if b = key then a else rassoc key l
+
+let find_reloc ic =
+ rassoc (pos_in ic - !start) !reloc
+
+(* Symbolic printing of global names, etc *)
+
+let print_getglobal_name ic =
+ if !objfile then begin
+ begin try
+ match find_reloc ic with
+ Reloc_getglobal id -> print_string (Ident.name id)
+ | Reloc_literal sc -> print_struct_const sc
+ | _ -> print_string "<wrong reloc>"
+ with Not_found ->
+ print_string "<no reloc>"
+ end;
+ ignore (inputu ic);
+ end
+ else begin
+ let n = inputu ic in
+ if n >= Array.length !globals || n < 0
+ then print_string "<global table overflow>"
+ else match !globals.(n) with
+ Global id -> print_string(Ident.name id)
+ | Constant obj -> print_obj obj
+ | _ -> print_string "???"
+ end
+
+let print_setglobal_name ic =
+ if !objfile then begin
+ begin try
+ match find_reloc ic with
+ Reloc_setglobal id -> print_string (Ident.name id)
+ | _ -> print_string "<wrong reloc>"
+ with Not_found ->
+ print_string "<no reloc>"
+ end;
+ ignore (inputu ic);
+ end
+ else begin
+ let n = inputu ic in
+ if n >= Array.length !globals || n < 0
+ then print_string "<global table overflow>"
+ else match !globals.(n) with
+ Global id -> print_string(Ident.name id)
+ | _ -> print_string "???"
+ end
+
+let print_primitive ic =
+ if !objfile then begin
+ begin try
+ match find_reloc ic with
+ Reloc_primitive s -> print_string s
+ | _ -> print_string "<wrong reloc>"
+ with Not_found ->
+ print_string "<no reloc>"
+ end;
+ ignore (inputu ic);
+ end
+ else begin
+ let n = inputu ic in
+ if n >= Array.length !primitives || n < 0
+ then print_int n
+ else print_string !primitives.(n)
+ end
+
+(* Disassemble one instruction *)
+
+let currpc ic =
+ currpos ic / 4
+
+type shape =
+ | Nothing
+ | Uint
+ | Sint
+ | Uint_Uint
+ | Disp
+ | Uint_Disp
+ | Sint_Disp
+ | Getglobal
+ | Getglobal_Uint
+ | Setglobal
+ | Primitive
+ | Uint_Primitive
+ | Switch
+ | Closurerec
+ | Pubmet
+;;
+
+let op_shapes = [
+ opACC0, Nothing;
+ opACC1, Nothing;
+ opACC2, Nothing;
+ opACC3, Nothing;
+ opACC4, Nothing;
+ opACC5, Nothing;
+ opACC6, Nothing;
+ opACC7, Nothing;
+ opACC, Uint;
+ opPUSH, Nothing;
+ opPUSHACC0, Nothing;
+ opPUSHACC1, Nothing;
+ opPUSHACC2, Nothing;
+ opPUSHACC3, Nothing;
+ opPUSHACC4, Nothing;
+ opPUSHACC5, Nothing;
+ opPUSHACC6, Nothing;
+ opPUSHACC7, Nothing;
+ opPUSHACC, Uint;
+ opPOP, Uint;
+ opASSIGN, Uint;
+ opENVACC1, Nothing;
+ opENVACC2, Nothing;
+ opENVACC3, Nothing;
+ opENVACC4, Nothing;
+ opENVACC, Uint;
+ opPUSHENVACC1, Nothing;
+ opPUSHENVACC2, Nothing;
+ opPUSHENVACC3, Nothing;
+ opPUSHENVACC4, Nothing;
+ opPUSHENVACC, Uint;
+ opPUSH_RETADDR, Disp;
+ opAPPLY, Uint;
+ opAPPLY1, Nothing;
+ opAPPLY2, Nothing;
+ opAPPLY3, Nothing;
+ opAPPTERM, Uint_Uint;
+ opAPPTERM1, Uint;
+ opAPPTERM2, Uint;
+ opAPPTERM3, Uint;
+ opRETURN, Uint;
+ opRESTART, Nothing;
+ opGRAB, Uint;
+ opCLOSURE, Uint_Disp;
+ opCLOSUREREC, Closurerec;
+ opOFFSETCLOSUREM2, Nothing;
+ opOFFSETCLOSURE0, Nothing;
+ opOFFSETCLOSURE2, Nothing;
+ opOFFSETCLOSURE, Sint; (* was Uint *)
+ opPUSHOFFSETCLOSUREM2, Nothing;
+ opPUSHOFFSETCLOSURE0, Nothing;
+ opPUSHOFFSETCLOSURE2, Nothing;
+ opPUSHOFFSETCLOSURE, Sint; (* was Nothing *)
+ opGETGLOBAL, Getglobal;
+ opPUSHGETGLOBAL, Getglobal;
+ opGETGLOBALFIELD, Getglobal_Uint;
+ opPUSHGETGLOBALFIELD, Getglobal_Uint;
+ opSETGLOBAL, Setglobal;
+ opATOM0, Nothing;
+ opATOM, Uint;
+ opPUSHATOM0, Nothing;
+ opPUSHATOM, Uint;
+ opMAKEBLOCK, Uint_Uint;
+ opMAKEBLOCK1, Uint;
+ opMAKEBLOCK2, Uint;
+ opMAKEBLOCK3, Uint;
+ opMAKEFLOATBLOCK, Uint;
+ opGETFIELD0, Nothing;
+ opGETFIELD1, Nothing;
+ opGETFIELD2, Nothing;
+ opGETFIELD3, Nothing;
+ opGETFIELD, Uint;
+ opGETFLOATFIELD, Uint;
+ opSETFIELD0, Nothing;
+ opSETFIELD1, Nothing;
+ opSETFIELD2, Nothing;
+ opSETFIELD3, Nothing;
+ opSETFIELD, Uint;
+ opSETFLOATFIELD, Uint;
+ opVECTLENGTH, Nothing;
+ opGETVECTITEM, Nothing;
+ opSETVECTITEM, Nothing;
+ opGETSTRINGCHAR, Nothing;
+ opSETSTRINGCHAR, Nothing;
+ opBRANCH, Disp;
+ opBRANCHIF, Disp;
+ opBRANCHIFNOT, Disp;
+ opSWITCH, Switch;
+ opBOOLNOT, Nothing;
+ opPUSHTRAP, Disp;
+ opPOPTRAP, Nothing;
+ opRAISE, Nothing;
+ opCHECK_SIGNALS, Nothing;
+ opC_CALL1, Primitive;
+ opC_CALL2, Primitive;
+ opC_CALL3, Primitive;
+ opC_CALL4, Primitive;
+ opC_CALL5, Primitive;
+ opC_CALLN, Uint_Primitive;
+ opCONST0, Nothing;
+ opCONST1, Nothing;
+ opCONST2, Nothing;
+ opCONST3, Nothing;
+ opCONSTINT, Sint;
+ opPUSHCONST0, Nothing;
+ opPUSHCONST1, Nothing;
+ opPUSHCONST2, Nothing;
+ opPUSHCONST3, Nothing;
+ opPUSHCONSTINT, Sint;
+ opNEGINT, Nothing;
+ opADDINT, Nothing;
+ opSUBINT, Nothing;
+ opMULINT, Nothing;
+ opDIVINT, Nothing;
+ opMODINT, Nothing;
+ opANDINT, Nothing;
+ opORINT, Nothing;
+ opXORINT, Nothing;
+ opLSLINT, Nothing;
+ opLSRINT, Nothing;
+ opASRINT, Nothing;
+ opEQ, Nothing;
+ opNEQ, Nothing;
+ opLTINT, Nothing;
+ opLEINT, Nothing;
+ opGTINT, Nothing;
+ opGEINT, Nothing;
+ opOFFSETINT, Sint;
+ opOFFSETREF, Sint;
+ opISINT, Nothing;
+ opGETMETHOD, Nothing;
+ opGETDYNMET, Nothing;
+ opGETPUBMET, Pubmet;
+ opBEQ, Sint_Disp;
+ opBNEQ, Sint_Disp;
+ opBLTINT, Sint_Disp;
+ opBLEINT, Sint_Disp;
+ opBGTINT, Sint_Disp;
+ opBGEINT, Sint_Disp;
+ opULTINT, Nothing;
+ opUGEINT, Nothing;
+ opBULTINT, Uint_Disp;
+ opBUGEINT, Uint_Disp;
+ opSTOP, Nothing;
+ opEVENT, Nothing;
+ opBREAK, Nothing;
+ opRERAISE, Nothing;
+ opRAISE_NOTRACE, Nothing;
+];;
+
+let print_event ev =
+ if !print_locations then
+ let ls = ev.ev_loc.loc_start in
+ let le = ev.ev_loc.loc_end in
+ printf "File \"%s\", line %d, characters %d-%d:\n" ls.Lexing.pos_fname
+ ls.Lexing.pos_lnum (ls.Lexing.pos_cnum - ls.Lexing.pos_bol)
+ (le.Lexing.pos_cnum - ls.Lexing.pos_bol)
+
+let print_instr ic =
+ let pos = currpos ic in
+ List.iter print_event (Hashtbl.find_all event_table pos);
+ printf "%8d " (pos / 4);
+ let op = inputu ic in
+ if op >= Array.length names_of_instructions || op < 0
+ then (print_string "*** unknown opcode : "; print_int op)
+ else print_string names_of_instructions.(op);
+ begin try
+ let shape = List.assoc op op_shapes in
+ if shape <> Nothing then print_string " ";
+ match shape with
+ | Uint -> print_int (inputu ic)
+ | Sint -> print_int (inputs ic)
+ | Uint_Uint
+ -> print_int (inputu ic); print_string ", "; print_int (inputu ic)
+ | Disp -> let p = currpc ic in print_int (p + inputs ic)
+ | Uint_Disp
+ -> print_int (inputu ic); print_string ", ";
+ let p = currpc ic in print_int (p + inputs ic)
+ | Sint_Disp
+ -> print_int (inputs ic); print_string ", ";
+ let p = currpc ic in print_int (p + inputs ic)
+ | Getglobal -> print_getglobal_name ic
+ | Getglobal_Uint
+ -> print_getglobal_name ic; print_string ", "; print_int (inputu ic)
+ | Setglobal -> print_setglobal_name ic
+ | Primitive -> print_primitive ic
+ | Uint_Primitive
+ -> print_int(inputu ic); print_string ", "; print_primitive ic
+ | Switch
+ -> let n = inputu ic in
+ let orig = currpc ic in
+ for i = 0 to (n land 0xFFFF) - 1 do
+ print_string "\n int "; print_int i; print_string " -> ";
+ print_int(orig + inputs ic);
+ done;
+ for i = 0 to (n lsr 16) - 1 do
+ print_string "\n tag "; print_int i; print_string " -> ";
+ print_int(orig + inputs ic);
+ done;
+ | Closurerec
+ -> let nfuncs = inputu ic in
+ let nvars = inputu ic in
+ let orig = currpc ic in
+ print_int nvars;
+ for _i = 0 to nfuncs - 1 do
+ print_string ", ";
+ print_int (orig + inputs ic);
+ done;
+ | Pubmet
+ -> let tag = inputs ic in
+ let _cache = inputu ic in
+ print_int tag
+ | Nothing -> ()
+ with Not_found -> print_string " (unknown arguments)"
+ end;
+ print_string "\n";
+;;
+
+(* Disassemble a block of code *)
+
+let print_code ic len =
+ start := pos_in ic;
+ let stop = !start + len in
+ while pos_in ic < stop do print_instr ic done
+
+(* Dump relocation info *)
+
+let print_reloc (info, pos) =
+ printf " %d (%d) " pos (pos/4);
+ match info with
+ Reloc_literal sc -> print_struct_const sc; printf "\n"
+ | Reloc_getglobal id -> printf "require %s\n" (Ident.name id)
+ | Reloc_setglobal id -> printf "provide %s\n" (Ident.name id)
+ | Reloc_primitive s -> printf "prim %s\n" s
+
+(* Print a .cmo file *)
+
+let dump_obj ic =
+ let buffer = really_input_string ic (String.length cmo_magic_number) in
+ if buffer <> cmo_magic_number then begin
+ prerr_endline "Not an object file"; exit 2
+ end;
+ let cu_pos = input_binary_int ic in
+ seek_in ic cu_pos;
+ let cu = (input_value ic : compilation_unit) in
+ reloc := cu.cu_reloc;
+ if cu.cu_debug > 0 then begin
+ seek_in ic cu.cu_debug;
+ let evl = (input_value ic : debug_event list) in
+ ignore (input_value ic); (* Skip the list of absolute directory names *)
+ record_events 0 evl
+ end;
+ seek_in ic cu.cu_pos;
+ print_code ic cu.cu_codesize
+
+(* Read the primitive table from an executable *)
+
+let read_primitive_table ic len =
+ let p = really_input_string ic len in
+ let rec split beg cur =
+ if cur >= len then []
+ else if p.[cur] = '\000' then
+ String.sub p beg (cur - beg) :: split (cur + 1) (cur + 1)
+ else
+ split beg (cur + 1) in
+ Array.of_list(split 0 0)
+
+(* Print an executable file *)
+
+let dump_exe ic =
+ Bytesections.read_toc ic;
+ let prim_size = Bytesections.seek_section ic "PRIM" in
+ primitives := read_primitive_table ic prim_size;
+ ignore(Bytesections.seek_section ic "DATA");
+ let init_data = (input_value ic : Obj.t array) in
+ globals := Array.make (Array.length init_data) Empty;
+ for i = 0 to Array.length init_data - 1 do
+ !globals.(i) <- Constant (init_data.(i))
+ done;
+ ignore(Bytesections.seek_section ic "SYMB");
+ let (_, sym_table) = (input_value ic : int * (Ident.t, int) Tbl.t) in
+ Tbl.iter (fun id pos -> !globals.(pos) <- Global id) sym_table;
+ begin try
+ ignore (Bytesections.seek_section ic "DBUG");
+ let num_eventlists = input_binary_int ic in
+ for _i = 1 to num_eventlists do
+ let orig = input_binary_int ic in
+ let evl = (input_value ic : debug_event list) in
+ ignore (input_value ic); (* Skip the list of absolute directory names *)
+ record_events orig evl
+ done
+ with Not_found -> ()
+ end;
+ let code_size = Bytesections.seek_section ic "CODE" in
+ print_code ic code_size
+
+let arg_list = [
+ "-noloc", Arg.Clear print_locations, " : don't print source information";
+]
+let arg_usage =
+ Printf.sprintf "%s [OPTIONS] FILES : dump content of bytecode files"
+ Sys.argv.(0)
+
+let first_file = ref true
+
+let arg_fun filename =
+ let ic = open_in_bin filename in
+ if not !first_file then print_newline ();
+ first_file := false;
+ printf "## start of ocaml dump of %S\n%!" filename;
+ begin try
+ objfile := false; dump_exe ic
+ with Bytesections.Bad_magic_number ->
+ objfile := true; seek_in ic 0; dump_obj ic
+ end;
+ close_in ic;
+ printf "## end of ocaml dump of %S\n%!" filename
+
+let main() =
+ Arg.parse arg_list arg_fun arg_usage;
+ exit 0
+
+let _ = main ()
diff --git a/tools/eqparsetree.ml b/tools/eqparsetree.ml
new file mode 100644
index 0000000000..4c699e9988
--- /dev/null
+++ b/tools/eqparsetree.ml
@@ -0,0 +1,781 @@
+(**************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Hongbo Zhang (University of Pennsylvania) *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(**************************************************************************)
+
+
+(*
+ This module is mainly used to diff two parsetree, it helps to automate the
+ test for parsing/pprintast.ml
+ *)
+
+
+open Parsetree
+let curry f (g, h) = f g h
+let eq_int : (int*int)->bool = curry (=)
+let eq_char : (char*char)->bool=curry (=)
+let eq_string : (string*string)->bool = curry (=)
+let eq_int32 : (int32*int32)->bool=curry (=)
+let eq_int64 : (int64*int64)->bool =curry (=)
+let eq_nativeint : (nativeint*nativeint)->bool= curry (=)
+let eq_bool :(bool*bool) -> bool = curry (=)
+let eq_list mf_a (xs, ys) =
+ let rec loop =
+ function
+ | ([], []) -> true
+ | (x :: xs, y :: ys) -> (mf_a (x, y)) && (loop (xs, ys))
+ | (_, _) -> false
+ in loop (xs, ys)
+let eq_option mf_a (x, y) =
+ match (x, y) with
+ | (None, None) -> true
+ | (Some x, Some y) -> mf_a (x, y)
+ | (_, _) -> false
+
+module Location =struct
+ include Location
+ let eq_t : (t*t) -> bool = fun (_,_) -> true
+end
+module Longident = struct
+ include Longident
+ let rec eq_t : (t * t) -> 'result =
+ function
+ | (Lident a0, Lident b0) -> eq_string (a0, b0)
+ | (Ldot (a0, a1), Ldot (b0, b1)) ->
+ (eq_t (a0, b0)) && (eq_string (a1, b1))
+ | (Lapply (a0, a1), Lapply (b0, b1)) ->
+ (eq_t (a0, b0)) && (eq_t (a1, b1))
+ | (_, _) -> false
+end
+module Asttypes = struct
+ open Asttypes
+ let eq_constant : (constant * constant) -> 'result =
+ function
+ | (Const_int a0, Const_int b0) -> eq_int (a0, b0)
+ | (Const_char a0, Const_char b0) -> eq_char (a0, b0)
+ | (Const_string a0, Const_string b0) -> eq_string (a0, b0)
+ | (Const_float a0, Const_float b0) -> eq_string (a0, b0)
+ | (Const_int32 a0, Const_int32 b0) -> eq_int32 (a0, b0)
+ | (Const_int64 a0, Const_int64 b0) -> eq_int64 (a0, b0)
+ | (Const_nativeint a0, Const_nativeint b0) -> eq_nativeint (a0, b0)
+ | (_, _) -> false
+
+ let eq_rec_flag : (rec_flag * rec_flag) -> 'result =
+ function
+ | (Nonrecursive, Nonrecursive) -> true
+ | (Recursive, Recursive) -> true
+ | (Default, Default) -> true
+ | (_, _) -> false
+
+ let eq_direction_flag :
+ (direction_flag * direction_flag) -> 'result =
+ function
+ | (Upto, Upto) -> true
+ | (Downto, Downto) -> true
+ | (_, _) -> false
+
+ let eq_private_flag : (private_flag * private_flag) -> 'result =
+ function
+ | (Private, Private) -> true
+ | (Public, Public) -> true
+ | (_, _) -> false
+
+ let eq_mutable_flag : (mutable_flag * mutable_flag) -> 'result =
+ function
+ | (Immutable, Immutable) -> true
+ | (Mutable, Mutable) -> true
+ | (_, _) -> false
+
+ let eq_virtual_flag : (virtual_flag * virtual_flag) -> 'result =
+ function
+ | (Virtual, Virtual) -> true
+ | (Concrete, Concrete) -> true
+ | (_, _) -> false
+
+ let eq_override_flag : (override_flag * override_flag) -> 'result =
+ function
+ | (Override, Override) -> true
+ | (Fresh, Fresh) -> true
+ | (_, _) -> false
+
+ let eq_closed_flag : (closed_flag * closed_flag) -> 'result =
+ function
+ | (Closed, Closed) -> true
+ | (Open, Open) -> true
+ | (_, _) -> false
+
+ let eq_label : (label * label) -> 'result =
+ fun (a0, a1) -> eq_string (a0, a1)
+
+ let eq_loc :
+ 'all_a0.
+ (('all_a0 * 'all_a0) -> 'result) ->
+ (('all_a0 loc) * ('all_a0 loc)) -> 'result =
+ fun mf_a ({ txt = a0; loc = a1 }, { txt = b0; loc = b1 }) ->
+ (mf_a (a0, b0)) && (Location.eq_t (a1, b1))
+
+end
+
+let rec eq_row_field : (row_field * row_field) -> 'result =
+ function
+ | (Rtag (a0, a1, a2), Rtag (b0, b1, b2)) ->
+ ((Asttypes.eq_label (a0, b0)) && (eq_bool (a1, b1))) &&
+ (eq_list eq_core_type (a2, b2))
+ | (Rinherit a0, Rinherit b0) -> eq_core_type (a0, b0)
+ | (_, _) -> false
+and eq_core_field_desc :
+ (core_field_desc * core_field_desc) -> 'result =
+ function
+ | (Pfield (a0, a1), Pfield (b0, b1)) ->
+ (eq_string (a0, b0)) && (eq_core_type (a1, b1))
+ | (Pfield_var, Pfield_var) -> true
+ | (_, _) -> false
+and eq_core_field_type :
+ (core_field_type * core_field_type) -> 'result =
+ fun
+ ({ pfield_desc = a0; pfield_loc = a1 },
+ { pfield_desc = b0; pfield_loc = b1 })
+ -> (eq_core_field_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_package_type : (package_type * package_type) -> 'result =
+ fun (a0, a1) ->
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_core_type (a1, b1)))
+ (a1, b1)))
+ (a0, a1)
+and eq_core_type_desc :
+ (core_type_desc * core_type_desc) -> 'result =
+ function
+ | (Ptyp_any, Ptyp_any) -> true
+ | (Ptyp_var a0, Ptyp_var b0) -> eq_string (a0, b0)
+ | (Ptyp_arrow (a0, a1, a2), Ptyp_arrow (b0, b1, b2)) ->
+ ((Asttypes.eq_label (a0, b0)) && (eq_core_type (a1, b1))) &&
+ (eq_core_type (a2, b2))
+ | (Ptyp_tuple a0, Ptyp_tuple b0) -> eq_list eq_core_type (a0, b0)
+ | (Ptyp_constr (a0, a1), Ptyp_constr (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_list eq_core_type (a1, b1))
+ | (Ptyp_object a0, Ptyp_object b0) ->
+ eq_list eq_core_field_type (a0, b0)
+ | (Ptyp_class (a0, a1, a2), Ptyp_class (b0, b1, b2)) ->
+ ((Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_list eq_core_type (a1, b1)))
+ && (eq_list Asttypes.eq_label (a2, b2))
+ | (Ptyp_alias (a0, a1), Ptyp_alias (b0, b1)) ->
+ (eq_core_type (a0, b0)) && (eq_string (a1, b1))
+ | (Ptyp_variant (a0, a1, a2), Ptyp_variant (b0, b1, b2)) ->
+ ((eq_list eq_row_field (a0, b0)) && (eq_bool (a1, b1))) &&
+ (eq_option (eq_list Asttypes.eq_label) (a2, b2))
+ | (Ptyp_poly (a0, a1), Ptyp_poly (b0, b1)) ->
+ (eq_list eq_string (a0, b0)) && (eq_core_type (a1, b1))
+ | (Ptyp_package a0, Ptyp_package b0) -> eq_package_type (a0, b0)
+ | (_, _) -> false
+and eq_core_type : (core_type * core_type) -> 'result =
+ fun
+ ({ ptyp_desc = a0; ptyp_loc = a1 },
+ { ptyp_desc = b0; ptyp_loc = b1 })
+ -> (eq_core_type_desc (a0, b0)) && (Location.eq_t (a1, b1))
+
+let eq_class_infos :
+ 'all_a0.
+ (('all_a0 * 'all_a0) -> 'result) ->
+ (('all_a0 class_infos) * ('all_a0 class_infos)) -> 'result =
+ fun mf_a
+ ({
+ pci_virt = a0;
+ pci_params = a1;
+ pci_name = a2;
+ pci_expr = a3;
+ pci_variance = a4;
+ pci_loc = a5
+ },
+ {
+ pci_virt = b0;
+ pci_params = b1;
+ pci_name = b2;
+ pci_expr = b3;
+ pci_variance = b4;
+ pci_loc = b5
+ })
+ ->
+ (((((Asttypes.eq_virtual_flag (a0, b0)) &&
+ ((fun ((a0, a1), (b0, b1)) ->
+ (eq_list (Asttypes.eq_loc eq_string) (a0, b0)) &&
+ (Location.eq_t (a1, b1)))
+ (a1, b1)))
+ && (Asttypes.eq_loc eq_string (a2, b2)))
+ && (mf_a (a3, b3)))
+ &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_bool (a0, b0)) && (eq_bool (a1, b1)))
+ (a4, b4)))
+ && (Location.eq_t (a5, b5))
+
+let rec eq_pattern_desc : (pattern_desc * pattern_desc) -> 'result =
+ function
+ | (Ppat_any, Ppat_any) -> true
+ | (Ppat_var a0, Ppat_var b0) -> Asttypes.eq_loc eq_string (a0, b0)
+ | (Ppat_alias (a0, a1), Ppat_alias (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (Asttypes.eq_loc eq_string (a1, b1))
+ | (Ppat_constant a0, Ppat_constant b0) ->
+ Asttypes.eq_constant (a0, b0)
+ | (Ppat_tuple a0, Ppat_tuple b0) -> eq_list eq_pattern (a0, b0)
+ | (Ppat_construct (a0, a1), Ppat_construct (b0, b1)) ->
+ ((Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_option eq_pattern (a1, b1)))
+ | (Ppat_variant (a0, a1), Ppat_variant (b0, b1)) ->
+ (Asttypes.eq_label (a0, b0)) && (eq_option eq_pattern (a1, b1))
+ | (Ppat_record (a0, a1), Ppat_record (b0, b1)) ->
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_pattern (a1, b1)))
+ (a0, b0))
+ && (Asttypes.eq_closed_flag (a1, b1))
+ | (Ppat_array a0, Ppat_array b0) -> eq_list eq_pattern (a0, b0)
+ | (Ppat_or (a0, a1), Ppat_or (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (eq_pattern (a1, b1))
+ | (Ppat_constraint (a0, a1), Ppat_constraint (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (eq_core_type (a1, b1))
+ | (Ppat_type a0, Ppat_type b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (Ppat_lazy a0, Ppat_lazy b0) -> eq_pattern (a0, b0)
+ | (Ppat_unpack a0, Ppat_unpack b0) ->
+ Asttypes.eq_loc eq_string (a0, b0)
+ | (_, _) -> false
+and eq_pattern : (pattern * pattern) -> 'result =
+ fun
+ ({ ppat_desc = a0; ppat_loc = a1 },
+ { ppat_desc = b0; ppat_loc = b1 })
+ -> (eq_pattern_desc (a0, b0)) && (Location.eq_t (a1, b1))
+
+let rec eq_structure_item_desc :
+ (structure_item_desc * structure_item_desc) -> 'result =
+ function
+ | (Pstr_eval a0, Pstr_eval b0) -> eq_expression (a0, b0)
+ | (Pstr_value (a0, a1), Pstr_value (b0, b1)) ->
+ (Asttypes.eq_rec_flag (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (eq_expression (a1, b1)))
+ (a1, b1))
+ | (Pstr_primitive (a0, a1), Pstr_primitive (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_value_description (a1, b1))
+ | (Pstr_type (a0, a1), Pstr_type (b0, b1)) ->
+ (Asttypes.eq_rec_flag (a0, b0)) &&
+ eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_type_declaration (a1, b1)))
+ (a1, b1)
+ | (Pstr_exception (a0, a1), Pstr_exception (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_exception_declaration (a1, b1))
+ | (Pstr_exn_rebind (a0, a1), Pstr_exn_rebind (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (Asttypes.eq_loc Longident.eq_t (a1, b1))
+ | (Pstr_module (a0, a1), Pstr_module (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_module_expr (a1, b1))
+ | (Pstr_recmodule a0, Pstr_recmodule b0) ->
+ eq_list
+ (fun ((a0, a1, a2), (b0, b1, b2)) ->
+ ((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_module_type (a1, b1)))
+ && (eq_module_expr (a2, b2)))
+ (a0, b0)
+ | (Pstr_modtype (a0, a1), Pstr_modtype (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_module_type (a1, b1))
+ | (Pstr_open a0, Pstr_open b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (Pstr_class a0, Pstr_class b0) ->
+ eq_list eq_class_declaration (a0, b0)
+ | (Pstr_class_type a0, Pstr_class_type b0) ->
+ eq_list eq_class_type_declaration (a0, b0)
+ | (Pstr_include a0, Pstr_include b0) -> eq_module_expr (a0, b0)
+ | (_, _) -> false
+and eq_structure_item :
+ (structure_item * structure_item) -> 'result =
+ fun
+ ({ pstr_desc = a0; pstr_loc = a1 },
+ { pstr_desc = b0; pstr_loc = b1 })
+ -> (eq_structure_item_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_structure : (structure * structure) -> 'result =
+ fun (a0, a1) -> eq_list eq_structure_item (a0, a1)
+and eq_module_expr_desc :
+ (module_expr_desc * module_expr_desc) -> 'result =
+ function
+ | (Pmod_ident a0, Pmod_ident b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (Pmod_structure a0, Pmod_structure b0) -> eq_structure (a0, b0)
+ | (Pmod_functor (a0, a1, a2), Pmod_functor (b0, b1, b2)) ->
+ ((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_module_type (a1, b1)))
+ && (eq_module_expr (a2, b2))
+ | (Pmod_apply (a0, a1), Pmod_apply (b0, b1)) ->
+ (eq_module_expr (a0, b0)) && (eq_module_expr (a1, b1))
+ | (Pmod_constraint (a0, a1), Pmod_constraint (b0, b1)) ->
+ (eq_module_expr (a0, b0)) && (eq_module_type (a1, b1))
+ | (Pmod_unpack a0, Pmod_unpack b0) -> eq_expression (a0, b0)
+ | (_, _) -> false
+and eq_module_expr : (module_expr * module_expr) -> 'result =
+ fun
+ ({ pmod_desc = a0; pmod_loc = a1 },
+ { pmod_desc = b0; pmod_loc = b1 })
+ -> (eq_module_expr_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_with_constraint :
+ (with_constraint * with_constraint) -> 'result =
+ function
+ | (Pwith_type a0, Pwith_type b0) -> eq_type_declaration (a0, b0)
+ | (Pwith_module a0, Pwith_module b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (Pwith_typesubst a0, Pwith_typesubst b0) ->
+ eq_type_declaration (a0, b0)
+ | (Pwith_modsubst a0, Pwith_modsubst b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (_, _) -> false
+and eq_modtype_declaration :
+ (modtype_declaration * modtype_declaration) -> 'result =
+ function
+ | (Pmodtype_abstract, Pmodtype_abstract) -> true
+ | (Pmodtype_manifest a0, Pmodtype_manifest b0) ->
+ eq_module_type (a0, b0)
+ | (_, _) -> false
+and eq_signature_item_desc :
+ (signature_item_desc * signature_item_desc) -> 'result =
+ function
+ | (Psig_value (a0, a1), Psig_value (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_value_description (a1, b1))
+ | (Psig_type (a0, a1), Psig_type (b0, b1)) ->
+ (Asttypes.eq_rec_flag (a0, b0)) &&
+ eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_type_declaration (a1, b1)))
+ (a1, b1)
+ | (Psig_exception (a0, a1), Psig_exception (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_exception_declaration (a1, b1))
+ | (Psig_module (a0, a1), Psig_module (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_module_type (a1, b1))
+ | (Psig_recmodule a0, Psig_recmodule b0) ->
+ eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_module_type (a1, b1)))
+ (a0, b0)
+ | (Psig_modtype (a0, a1), Psig_modtype (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_modtype_declaration (a1, b1))
+ | (Psig_open a0, Psig_open b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (Psig_include a0, Psig_include b0) -> eq_module_type (a0, b0)
+ | (Psig_class a0, Psig_class b0) ->
+ eq_list eq_class_description (a0, b0)
+ | (Psig_class_type a0, Psig_class_type b0) ->
+ eq_list eq_class_type_declaration (a0, b0)
+ | (_, _) -> false
+and eq_signature_item :
+ (signature_item * signature_item) -> 'result =
+ fun
+ ({ psig_desc = a0; psig_loc = a1 },
+ { psig_desc = b0; psig_loc = b1 })
+ -> (eq_signature_item_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_signature : (signature * signature) -> 'result =
+ fun (a0, a1) -> eq_list eq_signature_item (a0, a1)
+and eq_module_type_desc :
+ (module_type_desc * module_type_desc) -> 'result =
+ function
+ | (Pmty_ident a0, Pmty_ident b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (Pmty_signature a0, Pmty_signature b0) -> eq_signature (a0, b0)
+ | (Pmty_functor (a0, a1, a2), Pmty_functor (b0, b1, b2)) ->
+ ((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_module_type (a1, b1)))
+ && (eq_module_type (a2, b2))
+ | (Pmty_with (a0, a1), Pmty_with (b0, b1)) ->
+ (eq_module_type (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_with_constraint (a1, b1)))
+ (a1, b1))
+ | (Pmty_typeof a0, Pmty_typeof b0) -> eq_module_expr (a0, b0)
+ | (_, _) -> false
+and eq_module_type : (module_type * module_type) -> 'result =
+ fun
+ ({ pmty_desc = a0; pmty_loc = a1 },
+ { pmty_desc = b0; pmty_loc = b1 })
+ -> (eq_module_type_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_class_declaration :
+ (class_declaration * class_declaration) -> 'result =
+ fun (a0, a1) -> eq_class_infos eq_class_expr (a0, a1)
+and eq_class_field_desc :
+ (class_field_desc * class_field_desc) -> 'result =
+ function
+ | (Pcf_inher (a0, a1, a2), Pcf_inher (b0, b1, b2)) ->
+ ((Asttypes.eq_override_flag (a0, b0)) &&
+ (eq_class_expr (a1, b1)))
+ && (eq_option eq_string (a2, b2))
+ | (Pcf_valvirt a0, Pcf_valvirt b0) ->
+ (fun ((a0, a1, a2), (b0, b1, b2)) ->
+ ((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (Asttypes.eq_mutable_flag (a1, b1)))
+ && (eq_core_type (a2, b2)))
+ (a0, b0)
+ | (Pcf_val a0, Pcf_val b0) ->
+ (fun ((a0, a1, a2, a3), (b0, b1, b2, b3)) ->
+ (((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (Asttypes.eq_mutable_flag (a1, b1)))
+ && (Asttypes.eq_override_flag (a2, b2)))
+ && (eq_expression (a3, b3)))
+ (a0, b0)
+ | (Pcf_virt a0, Pcf_virt b0) ->
+ (fun ((a0, a1, a2), (b0, b1, b2)) ->
+ ((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (Asttypes.eq_private_flag (a1, b1)))
+ && (eq_core_type (a2, b2)))
+ (a0, b0)
+ | (Pcf_meth a0, Pcf_meth b0) ->
+ (fun ((a0, a1, a2, a3), (b0, b1, b2, b3)) ->
+ (((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (Asttypes.eq_private_flag (a1, b1)))
+ && (Asttypes.eq_override_flag (a2, b2)))
+ && (eq_expression (a3, b3)))
+ (a0, b0)
+ | (Pcf_constr a0, Pcf_constr b0) ->
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_core_type (a0, b0)) && (eq_core_type (a1, b1)))
+ (a0, b0)
+ | (Pcf_init a0, Pcf_init b0) -> eq_expression (a0, b0)
+ | (_, _) -> false
+and eq_class_field : (class_field * class_field) -> 'result =
+ fun
+ ({ pcf_desc = a0; pcf_loc = a1 }, { pcf_desc = b0; pcf_loc = b1
+ })
+ -> (eq_class_field_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_class_structure :
+ (class_structure * class_structure) -> 'result =
+ fun
+ ({ pcstr_self = a0; pcstr_fields = a1 },
+ { pcstr_self = b0; pcstr_fields = b1 })
+ -> (eq_pattern (a0, b0)) && (eq_list eq_class_field (a1, b1))
+and eq_class_expr_desc :
+ (class_expr_desc * class_expr_desc) -> 'result =
+ function
+ | (Pcl_constr (a0, a1), Pcl_constr (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_list eq_core_type (a1, b1))
+ | (Pcl_structure a0, Pcl_structure b0) ->
+ eq_class_structure (a0, b0)
+ | (Pcl_fun (a0, a1, a2, a3), Pcl_fun (b0, b1, b2, b3)) ->
+ (((Asttypes.eq_label (a0, b0)) &&
+ (eq_option eq_expression (a1, b1)))
+ && (eq_pattern (a2, b2)))
+ && (eq_class_expr (a3, b3))
+ | (Pcl_apply (a0, a1), Pcl_apply (b0, b1)) ->
+ (eq_class_expr (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_label (a0, b0)) &&
+ (eq_expression (a1, b1)))
+ (a1, b1))
+ | (Pcl_let (a0, a1, a2), Pcl_let (b0, b1, b2)) ->
+ ((Asttypes.eq_rec_flag (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (eq_expression (a1, b1)))
+ (a1, b1)))
+ && (eq_class_expr (a2, b2))
+ | (Pcl_constraint (a0, a1), Pcl_constraint (b0, b1)) ->
+ (eq_class_expr (a0, b0)) && (eq_class_type (a1, b1))
+ | (_, _) -> false
+and eq_class_expr : (class_expr * class_expr) -> 'result =
+ fun
+ ({ pcl_desc = a0; pcl_loc = a1 }, { pcl_desc = b0; pcl_loc = b1
+ })
+ -> (eq_class_expr_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_class_type_declaration :
+ (class_type_declaration * class_type_declaration) -> 'result =
+ fun (a0, a1) -> eq_class_infos eq_class_type (a0, a1)
+and eq_class_description :
+ (class_description * class_description) -> 'result =
+ fun (a0, a1) -> eq_class_infos eq_class_type (a0, a1)
+and eq_class_type_field_desc :
+ (class_type_field_desc * class_type_field_desc) -> 'result =
+ function
+ | (Pctf_inher a0, Pctf_inher b0) -> eq_class_type (a0, b0)
+ | (Pctf_val a0, Pctf_val b0) ->
+ (fun ((a0, a1, a2, a3), (b0, b1, b2, b3)) ->
+ (((eq_string (a0, b0)) &&
+ (Asttypes.eq_mutable_flag (a1, b1)))
+ && (Asttypes.eq_virtual_flag (a2, b2)))
+ && (eq_core_type (a3, b3)))
+ (a0, b0)
+ | (Pctf_virt a0, Pctf_virt b0) ->
+ (fun ((a0, a1, a2), (b0, b1, b2)) ->
+ ((eq_string (a0, b0)) && (Asttypes.eq_private_flag (a1, b1)))
+ && (eq_core_type (a2, b2)))
+ (a0, b0)
+ | (Pctf_meth a0, Pctf_meth b0) ->
+ (fun ((a0, a1, a2), (b0, b1, b2)) ->
+ ((eq_string (a0, b0)) && (Asttypes.eq_private_flag (a1, b1)))
+ && (eq_core_type (a2, b2)))
+ (a0, b0)
+ | (Pctf_cstr a0, Pctf_cstr b0) ->
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_core_type (a0, b0)) && (eq_core_type (a1, b1)))
+ (a0, b0)
+ | (_, _) -> false
+and eq_class_type_field :
+ (class_type_field * class_type_field) -> 'result =
+ fun
+ ({ pctf_desc = a0; pctf_loc = a1 },
+ { pctf_desc = b0; pctf_loc = b1 })
+ ->
+ (eq_class_type_field_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_class_signature :
+ (class_signature * class_signature) -> 'result =
+ fun
+ ({ pcsig_self = a0; pcsig_fields = a1; pcsig_loc = a2 },
+ { pcsig_self = b0; pcsig_fields = b1; pcsig_loc = b2 })
+ ->
+ ((eq_core_type (a0, b0)) &&
+ (eq_list eq_class_type_field (a1, b1)))
+ && (Location.eq_t (a2, b2))
+and eq_class_type_desc :
+ (class_type_desc * class_type_desc) -> 'result =
+ function
+ | (Pcty_constr (a0, a1), Pcty_constr (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_list eq_core_type (a1, b1))
+ | (Pcty_signature a0, Pcty_signature b0) ->
+ eq_class_signature (a0, b0)
+ | (Pcty_arrow (a0, a1, a2), Pcty_arrow (b0, b1, b2)) ->
+ ((Asttypes.eq_label (a0, b0)) && (eq_core_type (a1, b1))) &&
+ (eq_class_type (a2, b2))
+ | (_, _) -> false
+and eq_class_type : (class_type * class_type) -> 'result =
+ fun
+ ({ pcty_desc = a0; pcty_loc = a1 },
+ { pcty_desc = b0; pcty_loc = b1 })
+ -> (eq_class_type_desc (a0, b0)) && (Location.eq_t (a1, b1))
+and eq_exception_declaration :
+ (exception_declaration * exception_declaration) -> 'result =
+ fun (a0, a1) -> eq_list eq_core_type (a0, a1)
+and eq_type_kind : (type_kind * type_kind) -> 'result =
+ function
+ | (Ptype_abstract, Ptype_abstract) -> true
+ | (Ptype_variant a0, Ptype_variant b0) ->
+ eq_list
+ (fun ((a0, a1, a2, a3), (b0, b1, b2, b3)) ->
+ (((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_list eq_core_type (a1, b1)))
+ && (eq_option eq_core_type (a2, b2)))
+ && (Location.eq_t (a3, b3)))
+ (a0, b0)
+ | (Ptype_record a0, Ptype_record b0) ->
+ eq_list
+ (fun ((a0, a1, a2, a3), (b0, b1, b2, b3)) ->
+ (((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (Asttypes.eq_mutable_flag (a1, b1)))
+ && (eq_core_type (a2, b2)))
+ && (Location.eq_t (a3, b3)))
+ (a0, b0)
+ | (_, _) -> false
+and eq_type_declaration :
+ (type_declaration * type_declaration) -> 'result =
+ fun
+ ({
+ ptype_params = a0;
+ ptype_cstrs = a1;
+ ptype_kind = a2;
+ ptype_private = a3;
+ ptype_manifest = a4;
+ ptype_variance = a5;
+ ptype_loc = a6
+ },
+ {
+ ptype_params = b0;
+ ptype_cstrs = b1;
+ ptype_kind = b2;
+ ptype_private = b3;
+ ptype_manifest = b4;
+ ptype_variance = b5;
+ ptype_loc = b6
+ })
+ ->
+ ((((((eq_list (eq_option (Asttypes.eq_loc eq_string)) (a0, b0))
+ &&
+ (eq_list
+ (fun ((a0, a1, a2), (b0, b1, b2)) ->
+ ((eq_core_type (a0, b0)) && (eq_core_type (a1, b1)))
+ && (Location.eq_t (a2, b2)))
+ (a1, b1)))
+ && (eq_type_kind (a2, b2)))
+ && (Asttypes.eq_private_flag (a3, b3)))
+ && (eq_option eq_core_type (a4, b4)))
+ &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_bool (a0, b0)) && (eq_bool (a1, b1)))
+ (a5, b5)))
+ && (Location.eq_t (a6, b6))
+and eq_value_description :
+ (value_description * value_description) -> 'result =
+ fun
+ ({ pval_type = a0; pval_prim = a1; pval_loc = a2 },
+ { pval_type = b0; pval_prim = b1; pval_loc = b2 })
+ ->
+ ((eq_core_type (a0, b0)) && (eq_list eq_string (a1, b1))) &&
+ (Location.eq_t (a2, b2))
+and eq_expression_desc :
+ (expression_desc * expression_desc) -> 'result =
+ function
+ | (Pexp_ident a0, Pexp_ident b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (Pexp_constant a0, Pexp_constant b0) ->
+ Asttypes.eq_constant (a0, b0)
+ | (Pexp_let (a0, a1, a2), Pexp_let (b0, b1, b2)) ->
+ ((Asttypes.eq_rec_flag (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (eq_expression (a1, b1)))
+ (a1, b1)))
+ && (eq_expression (a2, b2))
+ | Pexp_fun (a1, a1, a2, a3), Pexp_function (b0, b1, b2, b3) ->
+ ((Asttypes.eq_label (a0, b0)) &&
+ (eq_option eq_expression (a1, b1)) &&
+ (eq_pattern a2 b2) &&
+ (eq_expression (a3, b3)))
+ | (Pexp_function (a0, a1, a2), Pexp_function (b0, b1, b2)) ->
+ (* FIX *)
+ eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (eq_expression (a1, b1)))
+ (a2, b2)
+ | (Pexp_apply (a0, a1), Pexp_apply (b0, b1)) ->
+ (eq_expression (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_label (a0, b0)) &&
+ (eq_expression (a1, b1)))
+ (a1, b1))
+ | (Pexp_match (a0, a1), Pexp_match (b0, b1)) ->
+ (eq_expression (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (eq_expression (a1, b1)))
+ (a1, b1))
+ | (Pexp_try (a0, a1), Pexp_try (b0, b1)) ->
+ (eq_expression (a0, b0)) &&
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (eq_pattern (a0, b0)) && (eq_expression (a1, b1)))
+ (a1, b1))
+ | (Pexp_tuple a0, Pexp_tuple b0) -> eq_list eq_expression (a0, b0)
+ | (Pexp_construct (a0, a1), Pexp_construct (b0, b1)) ->
+ ((Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_option eq_expression (a1, b1)))
+ | (Pexp_variant (a0, a1), Pexp_variant (b0, b1)) ->
+ (Asttypes.eq_label (a0, b0)) &&
+ (eq_option eq_expression (a1, b1))
+ | (Pexp_record (a0, a1), Pexp_record (b0, b1)) ->
+ (eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_expression (a1, b1)))
+ (a0, b0))
+ && (eq_option eq_expression (a1, b1))
+ | (Pexp_field (a0, a1), Pexp_field (b0, b1)) ->
+ (eq_expression (a0, b0)) &&
+ (Asttypes.eq_loc Longident.eq_t (a1, b1))
+ | (Pexp_setfield (a0, a1, a2), Pexp_setfield (b0, b1, b2)) ->
+ ((eq_expression (a0, b0)) &&
+ (Asttypes.eq_loc Longident.eq_t (a1, b1)))
+ && (eq_expression (a2, b2))
+ | (Pexp_array a0, Pexp_array b0) -> eq_list eq_expression (a0, b0)
+ | (Pexp_ifthenelse (a0, a1, a2), Pexp_ifthenelse (b0, b1, b2)) ->
+ ((eq_expression (a0, b0)) && (eq_expression (a1, b1))) &&
+ (eq_option eq_expression (a2, b2))
+ | (Pexp_sequence (a0, a1), Pexp_sequence (b0, b1)) ->
+ (eq_expression (a0, b0)) && (eq_expression (a1, b1))
+ | (Pexp_while (a0, a1), Pexp_while (b0, b1)) ->
+ (eq_expression (a0, b0)) && (eq_expression (a1, b1))
+ | (Pexp_for (a0, a1, a2, a3, a4), Pexp_for (b0, b1, b2, b3, b4)) ->
+ ((((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_expression (a1, b1)))
+ && (eq_expression (a2, b2)))
+ && (Asttypes.eq_direction_flag (a3, b3)))
+ && (eq_expression (a4, b4))
+ | (Pexp_constraint (a0, a1, a2), Pexp_constraint (b0, b1, b2)) ->
+ ((eq_expression (a0, b0)) && (eq_option eq_core_type (a1, b1)))
+ && (eq_option eq_core_type (a2, b2))
+ | (Pexp_when (a0, a1), Pexp_when (b0, b1)) ->
+ (eq_expression (a0, b0)) && (eq_expression (a1, b1))
+ | (Pexp_send (a0, a1), Pexp_send (b0, b1)) ->
+ (eq_expression (a0, b0)) && (eq_string (a1, b1))
+ | (Pexp_new a0, Pexp_new b0) ->
+ Asttypes.eq_loc Longident.eq_t (a0, b0)
+ | (Pexp_setinstvar (a0, a1), Pexp_setinstvar (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_expression (a1, b1))
+ | (Pexp_override a0, Pexp_override b0) ->
+ eq_list
+ (fun ((a0, a1), (b0, b1)) ->
+ (Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_expression (a1, b1)))
+ (a0, b0)
+ | (Pexp_letmodule (a0, a1, a2), Pexp_letmodule (b0, b1, b2)) ->
+ ((Asttypes.eq_loc eq_string (a0, b0)) &&
+ (eq_module_expr (a1, b1)))
+ && (eq_expression (a2, b2))
+ | (Pexp_assert a0, Pexp_assert b0) -> eq_expression (a0, b0)
+ | (Pexp_lazy a0, Pexp_lazy b0) -> eq_expression (a0, b0)
+ | (Pexp_poly (a0, a1), Pexp_poly (b0, b1)) ->
+ (eq_expression (a0, b0)) && (eq_option eq_core_type (a1, b1))
+ | (Pexp_object a0, Pexp_object b0) -> eq_class_structure (a0, b0)
+ | (Pexp_newtype (a0, a1), Pexp_newtype (b0, b1)) ->
+ (eq_string (a0, b0)) && (eq_expression (a1, b1))
+ | (Pexp_pack a0, Pexp_pack b0) -> eq_module_expr (a0, b0)
+ | (Pexp_open (a0, a1), Pexp_open (b0, b1)) ->
+ (Asttypes.eq_loc Longident.eq_t (a0, b0)) &&
+ (eq_expression (a1, b1))
+ | (_, _) -> false
+and eq_expression : (expression * expression) -> 'result =
+ fun
+ ({ pexp_desc = a0; pexp_loc = a1 },
+ { pexp_desc = b0; pexp_loc = b1 })
+ -> (eq_expression_desc (a0, b0)) && (Location.eq_t (a1, b1))
+
+let rec eq_directive_argument :
+ (directive_argument * directive_argument) -> 'result =
+ function
+ | (Pdir_none, Pdir_none) -> true
+ | (Pdir_string a0, Pdir_string b0) -> eq_string (a0, b0)
+ | (Pdir_int a0, Pdir_int b0) -> eq_int (a0, b0)
+ | (Pdir_ident a0, Pdir_ident b0) -> Longident.eq_t (a0, b0)
+ | (Pdir_bool a0, Pdir_bool b0) -> eq_bool (a0, b0)
+ | (_, _) -> false
+and eq_toplevel_phrase :
+ (toplevel_phrase * toplevel_phrase) -> 'result =
+ function
+ | (Ptop_def a0, Ptop_def b0) -> eq_structure (a0, b0)
+ | (Ptop_dir (a0, a1), Ptop_dir (b0, b1)) ->
+ (eq_string (a0, b0)) && (eq_directive_argument (a1, b1))
+ | (_, _) -> false
diff --git a/tools/gdb-macros b/tools/gdb-macros
new file mode 100644
index 0000000000..157bfe2e4f
--- /dev/null
+++ b/tools/gdb-macros
@@ -0,0 +1,318 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, Jane Street Group, LLC #
+# #
+# Copyright 2015 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# A set of macros for low-level debugging of OCaml programs and of the
+# OCaml runtime itself (both native and byte-code).
+
+# This file should be loaded in gdb with [ source gdb-macros ].
+# It defines one command: [caml]
+# Usage:
+# [caml <value>]
+# If <value> is an OCaml value, this will display it in a low-level
+# but legible format, including the header information.
+
+# To do: a [camlsearch] command to find all (gc-traceable) pointers to
+# a given heap block.
+
+set $camlwordsize = sizeof(char *)
+
+if $camlwordsize == 8
+ set $caml_unalloc_mask = 0xFF00FFFFFF00FFFF
+ set $caml_unalloc_value = 0xD700D7D7D700D6D7
+else
+ set $caml_unalloc_mask = 0xFF00FFFF
+ set $caml_unalloc_value = 0xD700D6D7
+end
+
+define camlcheckheader
+ if $arg0 >> 10 <= 0 || $arg0 >> 10 >= 0x1000000000000
+ if ($arg0 & $caml_unalloc_mask) == $caml_unalloc_value
+ set $camlcheckheader_result = 2
+ else
+ if $arg0 == (unsigned long) 0
+ set $camlcheckheader_result = 3
+ else
+ set $camlcheckheader_result = 1
+ end
+ end
+ else
+ set $camlcheckheader_result = 0
+ end
+end
+
+define camlheader
+ set $hd = * (unsigned long *) ($arg0 - $camlwordsize)
+ set $tag = $hd & 0xFF
+ set $color = ($hd >> 8) & 3
+ set $size = $hd >> 10
+
+ camlcheckheader $hd
+ if $camlcheckheader_result != 0
+ if $camlcheckheader_result == 2
+ printf "[UNALLOCATED MEMORY]"
+ else
+ if $camlcheckheader_result == 3
+ printf "[** fragment **] 0x%016lu", $hd
+ else
+ printf "[**invalid header**] 0x%016lu", $hd
+ end
+ end
+ set $size = 0
+ else
+ printf "["
+ if $color == 0
+ printf "white "
+ end
+ if $color == 1
+ printf "gray "
+ end
+ if $color == 2
+ printf "blue "
+ end
+ if $color == 3
+ printf "black "
+ end
+
+ if $tag < 246
+ printf "tag%d ", $tag
+ end
+ if $tag == 246
+ printf "Lazy "
+ end
+ if $tag == 247
+ printf "Closure "
+ end
+ if $tag == 248
+ printf "Object "
+ end
+ if $tag == 249
+ printf "Infix "
+ end
+ if $tag == 250
+ printf "Forward "
+ end
+ if $tag == 251
+ printf "Abstract "
+ end
+ if $tag == 252
+ printf "String "
+ end
+ if $tag == 253
+ printf "Double "
+ end
+ if $tag == 254
+ printf "Double_array "
+ end
+ if $tag == 255
+ printf "Custom "
+ end
+
+ printf "%lu]", $size
+ end
+end
+
+define camlheap
+ if $arg0 >= caml_young_start && $arg0 < caml_young_end
+ printf "YOUNG"
+ set $camlheap_result = 1
+ else
+ set $chunk = caml_heap_start
+ set $found = 0
+ while $chunk != 0 && ! $found
+ set $chunk_size = * (unsigned long *) ($chunk - 2 * $camlwordsize)
+ if $arg0 > $chunk && $arg0 <= $chunk + $chunk_size
+ printf "OLD"
+ set $found = 1
+ end
+ set $chunk = * (unsigned long *) ($chunk - $camlwordsize)
+ end
+ if $found
+ set $camlheap_result = 1
+ else
+ printf "OUT-OF-HEAP"
+ set $camlheap_result = 0
+ end
+ end
+end
+
+define camlint
+ if ($arg0 & $caml_unalloc_mask) == $caml_unalloc_value
+ printf "UNALLOCATED MEMORY"
+ else
+ printf "INT %ld", ($arg0 >> 1)
+ end
+ if ($arg0 & 0xFF) == 0xF9 && ($arg0 >> 10) < 0x1000000000000
+ printf " [possible infix header]"
+ end
+end
+
+define camlblock
+ printf "%#lx: ", $arg0 - $camlwordsize
+ camlheap $arg0
+ printf " "
+ camlheader $arg0
+ set $mysize = $size
+ set $camlnext = $arg0 + $camlwordsize * ($size + 1)
+ printf "\n"
+
+ if $tag == 252
+ x/s $arg0
+ end
+ if $tag == 253
+ x/f $arg0
+ end
+ if $tag == 254
+ while $count < $mysize && $count < 10
+ if $count + 1 < $size
+ x/2f $arg0 + $camlwordsize * $count
+ else
+ x/f $arg0 + $camlwordsize * $count
+ end
+ set $count = $count + 2
+ end
+ if $count < $mysize
+ printf "... truncated ...\n"
+ end
+ end
+
+ if $tag == 249
+ printf "... infix header, displaying enclosing block:\n"
+ set $mybaseaddr = $arg0 - $camlwordsize * $mysize
+ camlblock $mybaseaddr
+ # reset $tag, which was clobbered by the recursive call (yuck)
+ set $tag = 249
+ end
+
+ if $tag != 249 && $tag != 252 && $tag != 253 && $tag != 254
+ set $isvalues = $tag < 251
+ set $count = 0
+ while $count < $mysize && $count < 10
+ set $adr = $arg0 + $camlwordsize * $count
+ set $field = * (unsigned long *) $adr
+ printf "%#lx: [%d] 0x%016lx ", $adr, $count, $field
+ if ($field & 7) == 0 && $isvalues
+ camlheap $field
+ if $camlheap_result
+ printf " "
+ camlheader $field
+ end
+ end
+ if ($field & 1) == 1
+ camlint $field
+ end
+ printf "\n"
+ set $count = $count + 1
+ end
+ if $count < $mysize
+ printf "... truncated ...\n"
+ end
+ end
+ printf "next block head: %#lx value: %#lx\n", \
+ $arg0 + $camlwordsize * $mysize, $arg0 + $camlwordsize * ($mysize+1)
+end
+
+# displays an OCaml value
+define caml
+ set $camllast = (long) $arg0
+ if ($camllast & 1) == 1
+ set $camlnext = 0
+ camlint $camllast
+ printf "\n"
+ end
+ if ($camllast & 7) == 0
+ camlblock $camllast
+ end
+ if ($camllast & 7) != 0 && ($camllast & 1) != 1
+ set $camlnext = 0
+ printf "invalid pointer: %#016lx\n", $camllast
+ end
+end
+
+# displays the next OCaml value in memory
+define camlnext
+ caml $camlnext
+end
+
+# displays the n-th field of the previously displayed value
+define camlfield
+ set $camlfield_addr = ((long *) $camllast)[$arg0]
+ caml $camlfield_addr
+end
+
+# displays the list of heap chunks
+define camlchunks
+ set $chunk = * (unsigned long *) &caml_heap_start
+ while $chunk != 0
+ set $chunk_size = * (unsigned long *) ($chunk - 2 * $camlwordsize)
+ set $chunk_alloc = * (unsigned long *) ($chunk - 3 * $camlwordsize)
+ printf "chunk: addr = %#lx .. %#lx", $chunk, $chunk + $chunk_size
+ printf " (size = %#lx; alloc = %#lx)\n", $chunk_size, $chunk_alloc
+ set $chunk = * (unsigned long *) ($chunk - $camlwordsize)
+ end
+end
+
+# walk the heap and launch command `camlvisitfun` on each block
+# the variables `$hp` `$val` `$hd` `$tag` `$color` and `$size`
+# are set before calling `camlvisitfun`
+# `camlvisitfun` can set `$camlvisitstop` to stop the iteration
+
+define camlvisit
+ set $cvchunk = * (unsigned long *) &caml_heap_start
+ set $camlvisitstop = 0
+ while $cvchunk != 0 && ! $camlvisitstop
+ set $cvchunk_size = * (unsigned long *) ($cvchunk - 2 * $camlwordsize)
+ set $cvhp = $cvchunk
+ while $cvhp < $cvchunk + $cvchunk_size && !$camlvisitstop
+ set $hp = $cvhp
+ set $val = $hp + $camlwordsize
+ set $hd = * (unsigned long *) $hp
+ set $tag = $hd & 0xFF
+ set $color = ($hd >> 8) & 3
+ set $cvsize = $hd >> 10
+ set $size = $cvsize
+ camlvisitfun
+ set $cvhp = $cvhp + (($cvsize + 1) * $camlwordsize)
+ end
+ set $cvchunk = * (unsigned long *) ($cvchunk - $camlwordsize)
+ end
+end
+
+define caml_cv_check_fl0
+ if $hp == * (unsigned long *) &caml_heap_start
+ set $flcheck_prev = ((unsigned long) &sentinels + 16)
+ end
+ if $color == 2 && $size > 5
+ if $val != * (unsigned long *) $flcheck_prev
+ printf "free-list: missing link %#x -> %#x\n", $flcheck_prev, $val
+ set $camlvisitstop = 1
+ end
+ set $flcheck_prev = $val
+ end
+end
+
+define caml_check_fl
+ set $listsize = $arg0
+ set $blueseen = $listsize == 0
+ set $val = * (unsigned long *) ((long) &sentinels + 16 + 32 * $listsize)
+ while $val != 0
+ printf "%#x\n", $val
+ set $hd = * (unsigned long *) ($val - 8)
+ set $color = ($hd >> 8) & 3
+ if $blueseen && $color != 2
+ printf "non-blue block at address %#x\n", $val
+ loop_break
+ else
+ set $blueseen = 1
+ end
+ set $val = * (unsigned long *) $val
+ end
+end
diff --git a/tools/lexer299.mll b/tools/lexer299.mll
new file mode 100644
index 0000000000..e7709602d8
--- /dev/null
+++ b/tools/lexer299.mll
@@ -0,0 +1,458 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexer definition *)
+
+{
+open Lexing
+open Misc
+
+type token =
+ AMPERAMPER
+ | AMPERSAND
+ | AND
+ | AS
+ | ASSERT
+ | BACKQUOTE
+ | BAR
+ | BARBAR
+ | BARRBRACKET
+ | BEGIN
+ | CHAR of (char)
+ | CLASS
+ | COLON
+ | COLONCOLON
+ | COLONEQUAL
+ | COLONGREATER
+ | COMMA
+ | CONSTRAINT
+ | DO
+ | DONE
+ | DOT
+ | DOTDOT
+ | DOWNTO
+ | ELSE
+ | END
+ | EOF
+ | EQUAL
+ | EXCEPTION
+ | EXTERNAL
+ | FALSE
+ | FLOAT of (string)
+ | FOR
+ | FUN
+ | FUNCTION
+ | FUNCTOR
+ | GREATER
+ | GREATERRBRACE
+ | GREATERRBRACKET
+ | IF
+ | IN
+ | INCLUDE
+ | INFIXOP0 of (string)
+ | INFIXOP1 of (string)
+ | INFIXOP2 of (string)
+ | INFIXOP3 of (string)
+ | INFIXOP4 of (string)
+ | INHERIT
+ | INITIALIZER
+ | INT of (int)
+ | LABEL of (string)
+ | LABELID of (string)
+ | LAZY
+ | LBRACE
+ | LBRACELESS
+ | LBRACKET
+ | LBRACKETBAR
+ | LBRACKETLESS
+ | LESS
+ | LESSMINUS
+ | LET
+ | LIDENT of (string)
+ | LPAREN
+ | MATCH
+ | METHOD
+ | MINUSGREATER
+ | MODULE
+ | MUTABLE
+ | NEW
+ | OBJECT
+ | OF
+ | OPEN
+ | OR
+ | PARSER
+ | PREFIXOP of (string)
+ | PRIVATE
+ | QUESTION
+ | QUESTION2
+ | QUOTE
+ | RBRACE
+ | RBRACKET
+ | REC
+ | RPAREN
+ | SEMI
+ | SEMISEMI
+ | SHARP
+ | SIG
+ | STAR
+ | STRING of (string)
+ | STRUCT
+ | SUBTRACTIVE of (string)
+ | THEN
+ | TO
+ | TRUE
+ | TRY
+ | TYPE
+ | UIDENT of (string)
+ | UNDERSCORE
+ | VAL
+ | VIRTUAL
+ | WHEN
+ | WHILE
+ | WITH
+
+type error =
+ | Illegal_character of char
+ | Unterminated_comment
+ | Unterminated_string
+ | Unterminated_string_in_comment
+;;
+
+exception Error of error * int * int
+
+(* The table of keywords *)
+
+let keyword_table =
+ create_hashtable 149 [
+ "and", AND;
+ "as", AS;
+ "assert", ASSERT;
+ "begin", BEGIN;
+ "class", CLASS;
+ "constraint", CONSTRAINT;
+ "do", DO;
+ "done", DONE;
+ "downto", DOWNTO;
+ "else", ELSE;
+ "end", END;
+ "exception", EXCEPTION;
+ "external", EXTERNAL;
+ "false", FALSE;
+ "for", FOR;
+ "fun", FUN;
+ "function", FUNCTION;
+ "functor", FUNCTOR;
+ "if", IF;
+ "in", IN;
+ "include", INCLUDE;
+ "inherit", INHERIT;
+ "initializer", INITIALIZER;
+ "lazy", LAZY;
+ "let", LET;
+ "match", MATCH;
+ "method", METHOD;
+ "module", MODULE;
+ "mutable", MUTABLE;
+ "new", NEW;
+ "object", OBJECT;
+ "of", OF;
+ "open", OPEN;
+ "or", OR;
+ "parser", PARSER;
+ "private", PRIVATE;
+ "rec", REC;
+ "sig", SIG;
+ "struct", STRUCT;
+ "then", THEN;
+ "to", TO;
+ "true", TRUE;
+ "try", TRY;
+ "type", TYPE;
+ "val", VAL;
+ "virtual", VIRTUAL;
+ "when", WHEN;
+ "while", WHILE;
+ "with", WITH;
+
+ "mod", INFIXOP3("mod");
+ "land", INFIXOP3("land");
+ "lor", INFIXOP3("lor");
+ "lxor", INFIXOP3("lxor");
+ "lsl", INFIXOP4("lsl");
+ "lsr", INFIXOP4("lsr");
+ "asr", INFIXOP4("asr")
+]
+
+(* To buffer string literals *)
+
+let initial_string_buffer = String.create 256
+let string_buff = ref initial_string_buffer
+let string_index = ref 0
+
+let reset_string_buffer () =
+ string_buff := initial_string_buffer;
+ string_index := 0
+
+let store_string_char c =
+ if !string_index >= String.length (!string_buff) then begin
+ let new_buff = String.create (String.length (!string_buff) * 2) in
+ String.blit (!string_buff) 0 new_buff 0 (String.length (!string_buff));
+ string_buff := new_buff
+ end;
+ String.unsafe_set (!string_buff) (!string_index) c;
+ incr string_index
+
+let get_stored_string () =
+ let s = String.sub (!string_buff) 0 (!string_index) in
+ string_buff := initial_string_buffer;
+ s
+
+(* To translate escape sequences *)
+
+let char_for_backslash = function
+ | 'n' -> '\010'
+ | 'r' -> '\013'
+ | 'b' -> '\008'
+ | 't' -> '\009'
+ | c -> c
+
+let char_for_decimal_code lexbuf i =
+ let c = 100 * (Char.code(Lexing.lexeme_char lexbuf i) - 48) +
+ 10 * (Char.code(Lexing.lexeme_char lexbuf (i+1)) - 48) +
+ (Char.code(Lexing.lexeme_char lexbuf (i+2)) - 48) in
+ Char.chr(c land 0xFF)
+
+(* To store the position of the beginning of a string and comment *)
+let string_start_pos = ref 0;;
+let comment_start_pos = ref [];;
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Illegal_character c ->
+ fprintf ppf "Illegal character (%s)" (Char.escaped c)
+ | Unterminated_comment ->
+ fprintf ppf "Comment not terminated"
+ | Unterminated_string ->
+ fprintf ppf "String literal not terminated"
+ | Unterminated_string_in_comment ->
+ fprintf ppf "This comment contains an unterminated string literal"
+;;
+
+}
+
+let blank = [' ' '\010' '\013' '\009' '\012']
+let lowercase = ['a'-'z' '\223'-'\246' '\248'-'\255' '_']
+let uppercase = ['A'-'Z' '\192'-'\214' '\216'-'\222']
+let identchar =
+ ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9']
+let symbolchar =
+ ['!' '$' '%' '&' '*' '+' '-' '.' '/' ':' '<' '=' '>' '?' '@' '^' '|' '~']
+let symbolchar2 =
+ ['!' '$' '%' '&' '*' '+' '-' '.' '/' '<' '=' '>' '?' '@' '^' '|' '~']
+(* ['!' '$' '&' '*' '+' '-' '.' '/' ':' '<' '=' '>' '?' '@' '^' '|' '~'] *)
+let decimal_literal = ['0'-'9']+
+let hex_literal = '0' ['x' 'X'] ['0'-'9' 'A'-'F' 'a'-'f']+
+let oct_literal = '0' ['o' 'O'] ['0'-'7']+
+let bin_literal = '0' ['b' 'B'] ['0'-'1']+
+let float_literal =
+ ['0'-'9']+ ('.' ['0'-'9']* )? (['e' 'E'] ['+' '-']? ['0'-'9']+)?
+
+rule token = parse
+ blank +
+ { token lexbuf }
+ | "_"
+ { UNDERSCORE }
+ | lowercase identchar * ':' [ ^ ':' '=' '>']
+ { let s = Lexing.lexeme lexbuf in
+ lexbuf.lex_curr_pos <- lexbuf.lex_curr_pos - 1;
+ lexbuf.lex_curr_p <-
+ {lexbuf.lex_curr_p with pos_cnum = lexbuf.lex_curr_p.pos_cnum - 1};
+ LABEL (String.sub s 0 (String.length s - 2)) }
+(*
+ | lowercase identchar * ':'
+ { let s = Lexing.lexeme lexbuf in
+ LABEL (String.sub s 0 (String.length s - 1)) }
+ | '%' lowercase identchar *
+*)
+ | ':' lowercase identchar *
+ { let s = Lexing.lexeme lexbuf in
+ let l = String.length s - 1 in
+ LABELID (String.sub s 1 l) }
+ | lowercase identchar *
+ { let s = Lexing.lexeme lexbuf in
+ try
+ Hashtbl.find keyword_table s
+ with Not_found ->
+ LIDENT s }
+ | uppercase identchar *
+ { UIDENT(Lexing.lexeme lexbuf) } (* No capitalized keywords *)
+ | decimal_literal | hex_literal | oct_literal | bin_literal
+ { INT (int_of_string(Lexing.lexeme lexbuf)) }
+ | float_literal
+ { FLOAT (Lexing.lexeme lexbuf) }
+ | "\""
+ { reset_string_buffer();
+ let string_start = Lexing.lexeme_start lexbuf in
+ string_start_pos := string_start;
+ string lexbuf;
+ lexbuf.Lexing.lex_start_pos <-
+ string_start - lexbuf.Lexing.lex_abs_pos;
+ STRING (get_stored_string()) }
+ | "'" [^ '\\' '\''] "'"
+ { CHAR(Lexing.lexeme_char lexbuf 1) }
+ | "'" '\\' ['\\' '\'' 'n' 't' 'b' 'r'] "'"
+ { CHAR(char_for_backslash (Lexing.lexeme_char lexbuf 2)) }
+ | "'" '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
+ { CHAR(char_for_decimal_code lexbuf 2) }
+ | "(*"
+ { comment_start_pos := [Lexing.lexeme_start lexbuf];
+ comment lexbuf;
+ token lexbuf }
+ | "(*)"
+ { let loc = { Location.loc_start = Lexing.lexeme_start_p lexbuf;
+ Location.loc_end = Lexing.lexeme_end_p lexbuf;
+ Location.loc_ghost = false }
+ in
+ Location.prerr_warning loc (Warnings.Comment_start);
+ comment_start_pos := [Lexing.lexeme_start lexbuf];
+ comment lexbuf;
+ token lexbuf
+ }
+ | "*)"
+ { let loc = { Location.loc_start = Lexing.lexeme_start_p lexbuf;
+ Location.loc_end = Lexing.lexeme_end_p lexbuf;
+ Location.loc_ghost = false }
+ in
+ Location.prerr_warning loc Warnings.Comment_not_end;
+ lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_curr_pos - 1;
+ STAR
+ }
+ | "#" [' ' '\t']* ['0'-'9']+ [^ '\n' '\r'] * ('\n' | '\r' | "\r\n")
+ (* # linenum ... *)
+ { token lexbuf }
+ | "#" { SHARP }
+ | "&" { AMPERSAND }
+ | "&&" { AMPERAMPER }
+ | "`" { BACKQUOTE }
+ | "'" { QUOTE }
+ | "(" { LPAREN }
+ | ")" { RPAREN }
+ | "*" { STAR }
+ | "," { COMMA }
+ | "?" { QUESTION }
+ | "??" { QUESTION2 }
+ | "->" { MINUSGREATER }
+ | "." { DOT }
+ | ".." { DOTDOT }
+ | ":" { COLON }
+ | "::" { COLONCOLON }
+ | ":=" { COLONEQUAL }
+ | ":>" { COLONGREATER }
+ | ";" { SEMI }
+ | ";;" { SEMISEMI }
+ | "<" { LESS }
+ | "<-" { LESSMINUS }
+ | "=" { EQUAL }
+ | "[" { LBRACKET }
+ | "[|" { LBRACKETBAR }
+ | "[<" { LBRACKETLESS }
+ | "]" { RBRACKET }
+ | "{" { LBRACE }
+ | "{<" { LBRACELESS }
+ | "|" { BAR }
+ | "||" { BARBAR }
+ | "|]" { BARRBRACKET }
+ | ">" { GREATER }
+ | ">]" { GREATERRBRACKET }
+ | "}" { RBRACE }
+ | ">}" { GREATERRBRACE }
+
+ | "!=" { INFIXOP0 "!=" }
+ | "-" { SUBTRACTIVE "-" }
+ | "-." { SUBTRACTIVE "-." }
+
+ | ['!' '~'] symbolchar *
+ { PREFIXOP(Lexing.lexeme lexbuf) }
+ | '?' symbolchar2 *
+ { PREFIXOP(Lexing.lexeme lexbuf) }
+ | ['=' '<' '>' '|' '&' '$'] symbolchar *
+ { INFIXOP0(Lexing.lexeme lexbuf) }
+ | ['@' '^'] symbolchar *
+ { INFIXOP1(Lexing.lexeme lexbuf) }
+ | ['+' '-'] symbolchar *
+ { INFIXOP2(Lexing.lexeme lexbuf) }
+ | "**" symbolchar *
+ { INFIXOP4(Lexing.lexeme lexbuf) }
+ | ['*' '/' '%'] symbolchar *
+ { INFIXOP3(Lexing.lexeme lexbuf) }
+ | eof { EOF }
+ | _
+ { raise (Error(Illegal_character ((Lexing.lexeme lexbuf).[0]),
+ Lexing.lexeme_start lexbuf, Lexing.lexeme_end lexbuf)) }
+
+and comment = parse
+ "(*"
+ { comment_start_pos := Lexing.lexeme_start lexbuf :: !comment_start_pos;
+ comment lexbuf;
+ }
+ | "*)"
+ { match !comment_start_pos with
+ | [] -> assert false
+ | [x] -> ()
+ | _ :: l -> comment_start_pos := l;
+ comment lexbuf;
+ }
+ | "\""
+ { reset_string_buffer();
+ string_start_pos := Lexing.lexeme_start lexbuf;
+ begin try string lexbuf
+ with Error (Unterminated_string, _, _) ->
+ let st = List.hd !comment_start_pos in
+ raise (Error (Unterminated_string_in_comment, st, st + 2))
+ end;
+ string_buff := initial_string_buffer;
+ comment lexbuf }
+ | "''"
+ { comment lexbuf }
+ | "'" [^ '\\' '\''] "'"
+ { comment lexbuf }
+ | "'\\" ['\\' '\'' 'n' 't' 'b' 'r'] "'"
+ { comment lexbuf }
+ | "'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
+ { comment lexbuf }
+ | eof
+ { let st = List.hd !comment_start_pos in
+ raise (Error (Unterminated_comment, st, st + 2));
+ }
+ | _
+ { comment lexbuf }
+
+and string = parse
+ '"'
+ { () }
+ | '\\' ("\010" | "\013" | "\013\010") [' ' '\009'] *
+ { string lexbuf }
+ | '\\' ['\\' '"' 'n' 't' 'b' 'r']
+ { store_string_char(char_for_backslash(Lexing.lexeme_char lexbuf 1));
+ string lexbuf }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9']
+ { store_string_char(char_for_decimal_code lexbuf 1);
+ string lexbuf }
+ | eof
+ { raise (Error (Unterminated_string,
+ !string_start_pos, !string_start_pos+1)) }
+ | _
+ { store_string_char(Lexing.lexeme_char lexbuf 0);
+ string lexbuf }
diff --git a/tools/lexer301.mll b/tools/lexer301.mll
new file mode 100644
index 0000000000..24bd807f7e
--- /dev/null
+++ b/tools/lexer301.mll
@@ -0,0 +1,459 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The lexer definition *)
+
+{
+open Misc
+
+type token =
+ AMPERAMPER
+ | AMPERSAND
+ | AND
+ | AS
+ | ASSERT
+ | BACKQUOTE
+ | BAR
+ | BARBAR
+ | BARRBRACKET
+ | BEGIN
+ | CHAR of (char)
+ | CLASS
+ | COLON
+ | COLONCOLON
+ | COLONEQUAL
+ | COLONGREATER
+ | COMMA
+ | CONSTRAINT
+ | DO
+ | DONE
+ | DOT
+ | DOTDOT
+ | DOWNTO
+ | ELSE
+ | END
+ | EOF
+ | EQUAL
+ | EXCEPTION
+ | EXTERNAL
+ | FALSE
+ | FLOAT of (string)
+ | FOR
+ | FUN
+ | FUNCTION
+ | FUNCTOR
+ | GREATER
+ | GREATERRBRACE
+ | GREATERRBRACKET
+ | IF
+ | IN
+ | INCLUDE
+ | INFIXOP0 of (string)
+ | INFIXOP1 of (string)
+ | INFIXOP2 of (string)
+ | INFIXOP3 of (string)
+ | INFIXOP4 of (string)
+ | INHERIT
+ | INITIALIZER
+ | INT of (int)
+ | LABEL of (string)
+ | LAZY
+ | LBRACE
+ | LBRACELESS
+ | LBRACKET
+ | LBRACKETBAR
+ | LBRACKETLESS
+ | LESS
+ | LESSMINUS
+ | LET
+ | LIDENT of (string)
+ | LPAREN
+ | MATCH
+ | METHOD
+ | MINUS
+ | MINUSDOT
+ | MINUSGREATER
+ | MODULE
+ | MUTABLE
+ | NEW
+ | OBJECT
+ | OF
+ | OPEN
+ | OPTLABEL of (string)
+ | OR
+ | PARSER
+ | PLUS
+ | PREFIXOP of (string)
+ | PRIVATE
+ | QUESTION
+ | QUESTION2
+ | QUOTE
+ | RBRACE
+ | RBRACKET
+ | REC
+ | RPAREN
+ | SEMI
+ | SEMISEMI
+ | SHARP
+ | SIG
+ | STAR
+ | STRING of (string)
+ | STRUCT
+ | THEN
+ | TILDE
+ | TO
+ | TRUE
+ | TRY
+ | TYPE
+ | UIDENT of (string)
+ | UNDERSCORE
+ | VAL
+ | VIRTUAL
+ | WHEN
+ | WHILE
+ | WITH
+
+type error =
+ | Illegal_character of char
+ | Unterminated_comment
+ | Unterminated_string
+ | Unterminated_string_in_comment
+ | Keyword_as_label of string
+;;
+
+exception Error of error * int * int
+
+(* The table of keywords *)
+
+let keyword_table =
+ create_hashtable 149 [
+ "and", AND;
+ "as", AS;
+ "assert", ASSERT;
+ "begin", BEGIN;
+ "class", CLASS;
+ "constraint", CONSTRAINT;
+ "do", DO;
+ "done", DONE;
+ "downto", DOWNTO;
+ "else", ELSE;
+ "end", END;
+ "exception", EXCEPTION;
+ "external", EXTERNAL;
+ "false", FALSE;
+ "for", FOR;
+ "fun", FUN;
+ "function", FUNCTION;
+ "functor", FUNCTOR;
+ "if", IF;
+ "in", IN;
+ "include", INCLUDE;
+ "inherit", INHERIT;
+ "initializer", INITIALIZER;
+ "lazy", LAZY;
+ "let", LET;
+ "match", MATCH;
+ "method", METHOD;
+ "module", MODULE;
+ "mutable", MUTABLE;
+ "new", NEW;
+ "object", OBJECT;
+ "of", OF;
+ "open", OPEN;
+ "or", OR;
+ "parser", PARSER;
+ "private", PRIVATE;
+ "rec", REC;
+ "sig", SIG;
+ "struct", STRUCT;
+ "then", THEN;
+ "to", TO;
+ "true", TRUE;
+ "try", TRY;
+ "type", TYPE;
+ "val", VAL;
+ "virtual", VIRTUAL;
+ "when", WHEN;
+ "while", WHILE;
+ "with", WITH;
+
+ "mod", INFIXOP3("mod");
+ "land", INFIXOP3("land");
+ "lor", INFIXOP3("lor");
+ "lxor", INFIXOP3("lxor");
+ "lsl", INFIXOP4("lsl");
+ "lsr", INFIXOP4("lsr");
+ "asr", INFIXOP4("asr")
+]
+
+(* To buffer string literals *)
+
+let initial_string_buffer = String.create 256
+let string_buff = ref initial_string_buffer
+let string_index = ref 0
+
+let reset_string_buffer () =
+ string_buff := initial_string_buffer;
+ string_index := 0
+
+let store_string_char c =
+ if !string_index >= String.length (!string_buff) then begin
+ let new_buff = String.create (String.length (!string_buff) * 2) in
+ String.blit (!string_buff) 0 new_buff 0 (String.length (!string_buff));
+ string_buff := new_buff
+ end;
+ String.unsafe_set (!string_buff) (!string_index) c;
+ incr string_index
+
+let get_stored_string () =
+ let s = String.sub (!string_buff) 0 (!string_index) in
+ string_buff := initial_string_buffer;
+ s
+
+(* To translate escape sequences *)
+
+let char_for_backslash = function
+ | 'n' -> '\010'
+ | 'r' -> '\013'
+ | 'b' -> '\008'
+ | 't' -> '\009'
+ | c -> c
+
+let char_for_decimal_code lexbuf i =
+ let c = 100 * (Char.code(Lexing.lexeme_char lexbuf i) - 48) +
+ 10 * (Char.code(Lexing.lexeme_char lexbuf (i+1)) - 48) +
+ (Char.code(Lexing.lexeme_char lexbuf (i+2)) - 48) in
+ Char.chr(c land 0xFF)
+
+(* To store the position of the beginning of a string and comment *)
+let string_start_pos = ref 0;;
+let comment_start_pos = ref [];;
+let in_comment () = !comment_start_pos <> [];;
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Illegal_character c ->
+ fprintf ppf "Illegal character (%s)" (Char.escaped c)
+ | Unterminated_comment ->
+ fprintf ppf "Comment not terminated"
+ | Unterminated_string ->
+ fprintf ppf "String literal not terminated"
+ | Unterminated_string_in_comment ->
+ fprintf ppf "This comment contains an unterminated string literal"
+ | Keyword_as_label kwd ->
+ fprintf ppf "`%s' is a keyword, it cannot be used as label name" kwd
+;;
+
+}
+
+let blank = [' ' '\010' '\013' '\009' '\012']
+let lowercase = ['a'-'z' '\223'-'\246' '\248'-'\255' '_']
+let uppercase = ['A'-'Z' '\192'-'\214' '\216'-'\222']
+let identchar =
+ ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9']
+let symbolchar =
+ ['!' '$' '%' '&' '*' '+' '-' '.' '/' ':' '<' '=' '>' '?' '@' '^' '|' '~']
+let decimal_literal = ['0'-'9']+
+let hex_literal = '0' ['x' 'X'] ['0'-'9' 'A'-'F' 'a'-'f']+
+let oct_literal = '0' ['o' 'O'] ['0'-'7']+
+let bin_literal = '0' ['b' 'B'] ['0'-'1']+
+let float_literal =
+ ['0'-'9']+ ('.' ['0'-'9']* )? (['e' 'E'] ['+' '-']? ['0'-'9']+)?
+
+rule token = parse
+ blank +
+ { token lexbuf }
+ | "_"
+ { UNDERSCORE }
+ | "~" { TILDE }
+ | "~" lowercase identchar * ':'
+ { let s = Lexing.lexeme lexbuf in
+ let name = String.sub s 1 (String.length s - 2) in
+ if Hashtbl.mem keyword_table name then
+ raise (Error(Keyword_as_label name, Lexing.lexeme_start lexbuf,
+ Lexing.lexeme_end lexbuf));
+ LABEL name }
+ | "?" { QUESTION }
+ | "?" lowercase identchar * ':'
+ { let s = Lexing.lexeme lexbuf in
+ let name = String.sub s 1 (String.length s - 2) in
+ if Hashtbl.mem keyword_table name then
+ raise (Error(Keyword_as_label name, Lexing.lexeme_start lexbuf,
+ Lexing.lexeme_end lexbuf));
+ OPTLABEL name }
+ | lowercase identchar *
+ { let s = Lexing.lexeme lexbuf in
+ try
+ Hashtbl.find keyword_table s
+ with Not_found ->
+ LIDENT s }
+ | uppercase identchar *
+ { UIDENT(Lexing.lexeme lexbuf) } (* No capitalized keywords *)
+ | decimal_literal | hex_literal | oct_literal | bin_literal
+ { INT (int_of_string(Lexing.lexeme lexbuf)) }
+ | float_literal
+ { FLOAT (Lexing.lexeme lexbuf) }
+ | "\""
+ { reset_string_buffer();
+ let string_start = Lexing.lexeme_start lexbuf in
+ string_start_pos := string_start;
+ string lexbuf;
+ lexbuf.Lexing.lex_start_pos <-
+ string_start - lexbuf.Lexing.lex_abs_pos;
+ STRING (get_stored_string()) }
+ | "'" [^ '\\' '\''] "'"
+ { CHAR(Lexing.lexeme_char lexbuf 1) }
+ | "'" '\\' ['\\' '\'' 'n' 't' 'b' 'r'] "'"
+ { CHAR(char_for_backslash (Lexing.lexeme_char lexbuf 2)) }
+ | "'" '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
+ { CHAR(char_for_decimal_code lexbuf 2) }
+ | "(*"
+ { comment_start_pos := [Lexing.lexeme_start lexbuf];
+ comment lexbuf;
+ token lexbuf }
+ | "(*)"
+ { let loc = Location.curr lexbuf
+ and warn = Warnings.Comment_start
+ in
+ Location.prerr_warning loc warn;
+ comment_start_pos := [Lexing.lexeme_start lexbuf];
+ comment lexbuf;
+ token lexbuf
+ }
+ | "*)"
+ { let loc = Location.curr lexbuf
+ and warn = Warnings.Comment_not_end
+ in
+ Location.prerr_warning loc warn;
+ lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_curr_pos - 1;
+ STAR
+ }
+ | "#" [' ' '\t']* ['0'-'9']+ [^ '\n' '\r'] * ('\n' | '\r' | "\r\n")
+ (* # linenum ... *)
+ { token lexbuf }
+ | "#" { SHARP }
+ | "&" { AMPERSAND }
+ | "&&" { AMPERAMPER }
+ | "`" { BACKQUOTE }
+ | "'" { QUOTE }
+ | "(" { LPAREN }
+ | ")" { RPAREN }
+ | "*" { STAR }
+ | "," { COMMA }
+ | "??" { QUESTION2 }
+ | "->" { MINUSGREATER }
+ | "." { DOT }
+ | ".." { DOTDOT }
+ | ":" { COLON }
+ | "::" { COLONCOLON }
+ | ":=" { COLONEQUAL }
+ | ":>" { COLONGREATER }
+ | ";" { SEMI }
+ | ";;" { SEMISEMI }
+ | "<" { LESS }
+ | "<-" { LESSMINUS }
+ | "=" { EQUAL }
+ | "[" { LBRACKET }
+ | "[|" { LBRACKETBAR }
+ | "[<" { LBRACKETLESS }
+ | "]" { RBRACKET }
+ | "{" { LBRACE }
+ | "{<" { LBRACELESS }
+ | "|" { BAR }
+ | "||" { BARBAR }
+ | "|]" { BARRBRACKET }
+ | ">" { GREATER }
+ | ">]" { GREATERRBRACKET }
+ | "}" { RBRACE }
+ | ">}" { GREATERRBRACE }
+
+ | "!=" { INFIXOP0 "!=" }
+ | "+" { PLUS }
+ | "-" { MINUS }
+ | "-." { MINUSDOT }
+
+ | "!" symbolchar *
+ { PREFIXOP(Lexing.lexeme lexbuf) }
+ | ['~' '?'] symbolchar +
+ { PREFIXOP(Lexing.lexeme lexbuf) }
+ | ['=' '<' '>' '|' '&' '$'] symbolchar *
+ { INFIXOP0(Lexing.lexeme lexbuf) }
+ | ['@' '^'] symbolchar *
+ { INFIXOP1(Lexing.lexeme lexbuf) }
+ | ['+' '-'] symbolchar *
+ { INFIXOP2(Lexing.lexeme lexbuf) }
+ | "**" symbolchar *
+ { INFIXOP4(Lexing.lexeme lexbuf) }
+ | ['*' '/' '%'] symbolchar *
+ { INFIXOP3(Lexing.lexeme lexbuf) }
+ | eof { EOF }
+ | _
+ { raise (Error(Illegal_character ((Lexing.lexeme lexbuf).[0]),
+ Lexing.lexeme_start lexbuf, Lexing.lexeme_end lexbuf)) }
+
+and comment = parse
+ "(*"
+ { comment_start_pos := Lexing.lexeme_start lexbuf :: !comment_start_pos;
+ comment lexbuf;
+ }
+ | "*)"
+ { match !comment_start_pos with
+ | [] -> assert false
+ | [x] -> comment_start_pos := [];
+ | _ :: l -> comment_start_pos := l;
+ comment lexbuf;
+ }
+ | "\""
+ { reset_string_buffer();
+ string_start_pos := Lexing.lexeme_start lexbuf;
+ begin try string lexbuf
+ with Error (Unterminated_string, _, _) ->
+ let st = List.hd !comment_start_pos in
+ raise (Error (Unterminated_string_in_comment, st, st + 2))
+ end;
+ string_buff := initial_string_buffer;
+ comment lexbuf }
+ | "''"
+ { comment lexbuf }
+ | "'" [^ '\\' '\''] "'"
+ { comment lexbuf }
+ | "'\\" ['\\' '\'' 'n' 't' 'b' 'r'] "'"
+ { comment lexbuf }
+ | "'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
+ { comment lexbuf }
+ | eof
+ { let st = List.hd !comment_start_pos in
+ raise (Error (Unterminated_comment, st, st + 2));
+ }
+ | _
+ { comment lexbuf }
+
+and string = parse
+ '"'
+ { () }
+ | '\\' ("\010" | "\013" | "\013\010") [' ' '\009'] *
+ { string lexbuf }
+ | '\\' ['\\' '"' 'n' 't' 'b' 'r']
+ { store_string_char(char_for_backslash(Lexing.lexeme_char lexbuf 1));
+ string lexbuf }
+ | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9']
+ { store_string_char(char_for_decimal_code lexbuf 1);
+ string lexbuf }
+ | eof
+ { raise (Error (Unterminated_string,
+ !string_start_pos, !string_start_pos+1)) }
+ | _
+ { store_string_char(Lexing.lexeme_char lexbuf 0);
+ string lexbuf }
diff --git a/tools/magic b/tools/magic
new file mode 100644
index 0000000000..089f169a16
--- /dev/null
+++ b/tools/magic
@@ -0,0 +1,11 @@
+# Here are some definitions that can be added to the /usr/share/magic
+# database so that the file(1) command recognizes OCaml compiled files.
+# Contributed by Sven Luther.
+0 string Caml1999 OCaml
+>8 string X bytecode executable
+>8 string I interface data (.cmi)
+>8 string O bytecode object data (.cmo)
+>8 string A bytecode library data (.cma)
+>8 string Y native object data (.cmx)
+>8 string Z native library data (.cmxa)
+>9 string >\0 (Version %3.3s).
diff --git a/tools/make-opcodes b/tools/make-opcodes
new file mode 100644
index 0000000000..7cc7c5aa84
--- /dev/null
+++ b/tools/make-opcodes
@@ -0,0 +1,14 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1995 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+$1=="enum" {n=0; next; }
+ {for (i = 1; i <= NF; i++) {printf("let op%s = %d\n", $i, n++);}}
diff --git a/tools/make-package-macosx b/tools/make-package-macosx
new file mode 100755
index 0000000000..e823156ba0
--- /dev/null
+++ b/tools/make-package-macosx
@@ -0,0 +1,134 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Moscova, INRIA Rocquencourt #
+# #
+# Copyright 2003 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+cd package-macosx
+rm -rf ocaml.pkg ocaml-rw.dmg
+
+VERSION=`sed -e 1q ../VERSION`
+VERSION_MAJOR=`sed -n -e '1s/^\([0-9]*\)\..*/\1/p' ../VERSION`
+VERSION_MINOR=`sed -n -e '1s/^[0-9]*\.\([0-9]*\)[.+].*/\1/p' ../VERSION`
+
+cat >Description.plist <<EOF
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ <key>IFPkgDescriptionDeleteWarning</key>
+ <string></string>
+ <key>IFPkgDescriptionDescription</key>
+ <string>The OCaml compiler and tools</string>
+ <key>IFPkgDescriptionTitle</key>
+ <string>OCaml</string>
+ <key>IFPkgDescriptionVersion</key>
+ <string>${VERSION}</string>
+ </dict>
+ </plist>
+EOF
+
+cat >Info.plist <<EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleGetInfoString</key>
+ <string>OCaml ${VERSION}</string>
+ <key>CFBundleIdentifier</key>
+ <string>fr.inria.ocaml</string>
+ <key>CFBundleName</key>
+ <string>OCaml</string>
+ <key>CFBundleShortVersionString</key>
+ <string>${VERSION}</string>
+ <key>IFMajorVersion</key>
+ <integer>${VERSION_MAJOR}</integer>
+ <key>IFMinorVersion</key>
+ <integer>${VERSION_MINOR}</integer>
+ <key>IFPkgFlagAllowBackRev</key>
+ <true/>
+ <key>IFPkgFlagAuthorizationAction</key>
+ <string>AdminAuthorization</string>
+ <key>IFPkgFlagDefaultLocation</key>
+ <string>/usr/local</string>
+ <key>IFPkgFlagInstallFat</key>
+ <false/>
+ <key>IFPkgFlagIsRequired</key>
+ <false/>
+ <key>IFPkgFlagRelocatable</key>
+ <false/>
+ <key>IFPkgFlagRestartAction</key>
+ <string>NoRestart</string>
+ <key>IFPkgFlagRootVolumeOnly</key>
+ <true/>
+ <key>IFPkgFlagUpdateInstalledLanguages</key>
+ <false/>
+ <key>IFPkgFormatVersion</key>
+ <real>0.10000000149011612</real>
+</dict>
+</plist>
+EOF
+
+mkdir -p resources
+
+# stop here -> |
+cat >resources/ReadMe.txt <<EOF
+This package installs OCaml version ${VERSION}.
+You need Mac OS X 10.7.x (Lion) or later, with the
+XCode tools installed (v4.6.3 or later).
+
+Files will be installed in the following directories:
+
+/usr/local/bin - command-line executables
+/usr/local/lib/ocaml - library and support files
+/usr/local/man - manual pages
+
+Note that this package installs only command-line
+tools and does not include any GUI application.
+EOF
+
+chmod -R g-w root
+sudo chown -R root:wheel root
+
+# HOW TO INSTALL PackageMaker:
+# Get PackageMaker.app from
+# https://developer.apple.com/downloads/index.action?name=Auxiliary
+# It's in the "Auxiliary Tools for Xcode" download.
+# Copy it to /Applications/.
+/Applications/PackageMaker.app/Contents/MacOS/PackageMaker \
+ -build -p "`pwd`/ocaml.pkg" -f "`pwd`/root" -i "`pwd`/Info.plist" \
+ -d "`pwd`/Description.plist" -r "`pwd`/resources"
+
+size=`du -s ocaml.pkg | cut -f 1`
+size=`expr $size + 8192`
+
+hdiutil create -sectors $size ocaml-rw.dmg
+name=`hdid -nomount ocaml-rw.dmg | grep Apple_HFS | cut -d ' ' -f 1`
+volname="OCaml ${VERSION}"
+newfs_hfs -v "$volname" $name
+hdiutil detach $name
+
+name=`hdid ocaml-rw.dmg | grep Apple_HFS | cut -d ' ' -f 1`
+if test -d "/Volumes/$volname"; then
+ ditto -rsrcFork ocaml.pkg "/Volumes/$volname/ocaml.pkg"
+ cp resources/ReadMe.txt "/Volumes/$volname/"
+else
+ echo "Unable to mount the disk image as \"/Volumes/$volname\"" >&2
+ exit 3
+fi
+open "/Volumes/$volname"
+sleep 2
+hdiutil detach $name
+
+rm -rf "ocaml-${VERSION}.dmg"
+hdiutil convert ocaml-rw.dmg -format UDZO -o "ocaml-${VERSION}.dmg"
diff --git a/tools/make-version-header.sh b/tools/make-version-header.sh
new file mode 100755
index 0000000000..26c5c14280
--- /dev/null
+++ b/tools/make-version-header.sh
@@ -0,0 +1,53 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2003 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. As an exception to the #
+# licensing rules of OCaml, this file is freely redistributable, #
+# modified or not, without constraints. #
+# #
+#########################################################################
+
+# This script extracts the components from an OCaml version number
+# and provides them as C defines:
+# OCAML_VERSION_MAJOR: the major version number
+# OCAML_VERSION_MAJOR: the minor version number
+# OCAML_VERSION_PATCHLEVEL: the patchlevel number if present, or 0 if absent
+# OCAML_VERSION_ADDITIONAL: this is defined only if the additional-info
+# field is present, and is a string that contains that field.
+# Note that additional-info is always absent in officially-released
+# versions of OCaml.
+
+# usage:
+# make-version-header.sh [version-file]
+# The argument is the VERSION file from the OCaml sources.
+# If the argument is not given, the version number from "ocamlc -v" will
+# be used.
+
+case $# in
+ 0) version="`ocamlc -v | sed -n -e 's/.*version //p'`";;
+ 1) version="`sed -e 1q $1`";;
+ *) echo "usage: make-version-header.sh [version-file]" >&2
+ exit 2;;
+esac
+
+major="`echo "$version" | sed -n -e '1s/^\([0-9]*\)\..*/\1/p'`"
+minor="`echo "$version" | sed -n -e '1s/^[0-9]*\.\([0-9]*\).*/\1/p'`"
+patchlvl="`echo "$version" | sed -n -e '1s/^[0-9]*\.[0-9]*\.\([0-9]*\).*/\1/p'`"
+suffix="`echo "$version" | sed -n -e '1s/^[^+]*+\(.*\)/\1/p'`"
+
+echo "#define OCAML_VERSION_MAJOR $major"
+printf "#define OCAML_VERSION_MINOR %d\n" $minor
+case $patchlvl in "") patchlvl=0;; esac
+echo "#define OCAML_VERSION_PATCHLEVEL $patchlvl"
+case "$suffix" in
+ "") echo "#undef OCAML_VERSION_ADDITIONAL";;
+ *) echo "#define OCAML_VERSION_ADDITIONAL \"$suffix\"";;
+esac
+printf "#define OCAML_VERSION %d%02d%02d\n" $major $minor $patchlvl
+echo "#define OCAML_VERSION_STRING \"$version\""
diff --git a/tools/objinfo.ml b/tools/objinfo.ml
new file mode 100644
index 0000000000..37a03b3427
--- /dev/null
+++ b/tools/objinfo.ml
@@ -0,0 +1,284 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* Mehdi Dogguy, PPS laboratory, University Paris Diderot *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. Modifications Copyright 2010 Mehdi Dogguy, *)
+(* used and distributed as part of OCaml by permission from *)
+(* the author. This file is distributed under the terms of the *)
+(* Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Dump info on .cmi, .cmo, .cmx, .cma, .cmxa, .cmxs files
+ and on bytecode executables. *)
+
+open Printf
+open Misc
+open Config
+open Cmo_format
+
+let input_stringlist ic len =
+ let get_string_list sect len =
+ let rec fold s e acc =
+ if e != len then
+ if sect.[e] = '\000' then
+ fold (e+1) (e+1) (String.sub sect s (e-s) :: acc)
+ else fold s (e+1) acc
+ else acc
+ in fold 0 0 []
+ in
+ let sect = really_input_string ic len in
+ get_string_list sect len
+
+let dummy_crc = String.make 32 '-'
+
+let print_name_crc (name, crco) =
+ let crc =
+ match crco with
+ None -> dummy_crc
+ | Some crc -> Digest.to_hex crc
+ in
+ printf "\t%s\t%s\n" crc name
+
+let print_line name =
+ printf "\t%s\n" name
+
+let print_cmo_infos cu =
+ printf "Unit name: %s\n" cu.cu_name;
+ print_string "Interfaces imported:\n";
+ List.iter print_name_crc cu.cu_imports;
+ printf "Uses unsafe features: ";
+ (match cu.cu_primitives with
+ | [] -> printf "no\n"
+ | l ->
+ printf "YES\n";
+ printf "Primitives declared in this module:\n";
+ List.iter print_line l);
+ printf "Force link: %s\n" (if cu.cu_force_link then "YES" else "no")
+
+let print_spaced_string s =
+ printf " %s" s
+
+let print_cma_infos (lib : Cmo_format.library) =
+ printf "Force custom: %s\n" (if lib.lib_custom then "YES" else "no");
+ printf "Extra C object files:";
+ (* PR#4949: print in linking order *)
+ List.iter print_spaced_string (List.rev lib.lib_ccobjs);
+ printf "\nExtra C options:";
+ List.iter print_spaced_string lib.lib_ccopts;
+ printf "\n";
+ print_string "Extra dynamically-loaded libraries:";
+ List.iter print_spaced_string lib.lib_dllibs;
+ printf "\n";
+ List.iter print_cmo_infos lib.lib_units
+
+let print_cmi_infos name crcs =
+ printf "Unit name: %s\n" name;
+ printf "Interfaces imported:\n";
+ List.iter print_name_crc crcs
+
+let print_cmt_infos cmt =
+ let open Cmt_format in
+ printf "Cmt unit name: %s\n" cmt.cmt_modname;
+ print_string "Cmt interfaces imported:\n";
+ List.iter print_name_crc cmt.cmt_imports;
+ printf "Source file: %s\n"
+ (match cmt.cmt_sourcefile with None -> "(none)" | Some f -> f);
+ printf "Compilation flags:";
+ Array.iter print_spaced_string cmt.cmt_args;
+ printf "\nLoad path:";
+ List.iter print_spaced_string cmt.cmt_loadpath;
+ printf "\n";
+ printf "cmt interface digest: %s\n"
+ (match cmt.cmt_interface_digest with
+ | None -> ""
+ | Some crc -> Digest.to_hex crc)
+
+let print_general_infos name crc defines cmi cmx =
+ printf "Name: %s\n" name;
+ printf "CRC of implementation: %s\n" (Digest.to_hex crc);
+ printf "Globals defined:\n";
+ List.iter print_line defines;
+ printf "Interfaces imported:\n";
+ List.iter print_name_crc cmi;
+ printf "Implementations imported:\n";
+ List.iter print_name_crc cmx
+
+open Cmx_format
+
+let print_cmx_infos (ui, crc) =
+ print_general_infos
+ ui.ui_name crc ui.ui_defines ui.ui_imports_cmi ui.ui_imports_cmx;
+ printf "Approximation:\n";
+ Format.fprintf Format.std_formatter " %a@." Printclambda.approx ui.ui_approx;
+ let pr_funs _ fns =
+ List.iter (fun arity -> printf " %d" arity) fns in
+ printf "Currying functions:%a\n" pr_funs ui.ui_curry_fun;
+ printf "Apply functions:%a\n" pr_funs ui.ui_apply_fun;
+ printf "Send functions:%a\n" pr_funs ui.ui_send_fun;
+ printf "Force link: %s\n" (if ui.ui_force_link then "YES" else "no")
+
+let print_cmxa_infos (lib : Cmx_format.library_infos) =
+ printf "Extra C object files:";
+ List.iter print_spaced_string (List.rev lib.lib_ccobjs);
+ printf "\nExtra C options:";
+ List.iter print_spaced_string lib.lib_ccopts;
+ printf "\n";
+ List.iter print_cmx_infos lib.lib_units
+
+let print_cmxs_infos header =
+ List.iter
+ (fun ui ->
+ print_general_infos
+ ui.dynu_name
+ ui.dynu_crc
+ ui.dynu_defines
+ ui.dynu_imports_cmi
+ ui.dynu_imports_cmx)
+ header.dynu_units
+
+let p_title title = printf "%s:\n" title
+
+let p_section title = function
+ | [] -> ()
+ | l ->
+ p_title title;
+ List.iter print_name_crc l
+
+let p_list title print = function
+ | [] -> ()
+ | l ->
+ p_title title;
+ List.iter print l
+
+let dump_byte ic =
+ Bytesections.read_toc ic;
+ let toc = Bytesections.toc () in
+ let toc = List.sort Pervasives.compare toc in
+ List.iter
+ (fun (section, _) ->
+ try
+ let len = Bytesections.seek_section ic section in
+ if len > 0 then match section with
+ | "CRCS" ->
+ p_section
+ "Imported units"
+ (input_value ic : (string * Digest.t option) list)
+ | "DLLS" ->
+ p_list
+ "Used DLLs"
+ print_line
+ (input_stringlist ic len)
+ | "DLPT" ->
+ p_list
+ "Additional DLL paths"
+ print_line
+ (input_stringlist ic len)
+ | "PRIM" ->
+ p_list
+ "Primitives used"
+ print_line
+ (input_stringlist ic len)
+ | _ -> ()
+ with _ -> ()
+ )
+ toc
+
+let read_dyn_header filename ic =
+ let tempfile = Filename.temp_file "objinfo" ".out" in
+ let helper = Filename.concat Config.standard_library "objinfo_helper" in
+ try
+ try_finally
+ (fun () ->
+ let rc = Sys.command (sprintf "%s %s > %s"
+ (Filename.quote helper)
+ (Filename.quote filename)
+ tempfile) in
+ if rc <> 0 then failwith "cannot read";
+ let tc = open_in tempfile in
+ try_finally
+ (fun () ->
+ let ofs = Scanf.fscanf tc "%Ld" (fun x -> x) in
+ LargeFile.seek_in ic ofs;
+ Some(input_value ic : dynheader))
+ (fun () -> close_in tc))
+ (fun () -> remove_file tempfile)
+ with Failure _ | Sys_error _ -> None
+
+let dump_obj filename =
+ printf "File %s\n" filename;
+ let ic = open_in_bin filename in
+ let len_magic_number = String.length cmo_magic_number in
+ let magic_number = really_input_string ic len_magic_number in
+ if magic_number = cmo_magic_number then begin
+ let cu_pos = input_binary_int ic in
+ seek_in ic cu_pos;
+ let cu = (input_value ic : compilation_unit) in
+ close_in ic;
+ print_cmo_infos cu
+ end else if magic_number = cma_magic_number then begin
+ let toc_pos = input_binary_int ic in
+ seek_in ic toc_pos;
+ let toc = (input_value ic : library) in
+ close_in ic;
+ print_cma_infos toc
+ end else if magic_number = cmi_magic_number ||
+ magic_number = cmt_magic_number then begin
+ close_in ic;
+ let cmi, cmt = Cmt_format.read filename in
+ begin match cmi with
+ | None -> ()
+ | Some cmi ->
+ print_cmi_infos cmi.Cmi_format.cmi_name cmi.Cmi_format.cmi_crcs
+ end;
+ begin match cmt with
+ | None -> ()
+ | Some cmt -> print_cmt_infos cmt
+ end
+ end else if magic_number = cmx_magic_number then begin
+ let ui = (input_value ic : unit_infos) in
+ let crc = Digest.input ic in
+ close_in ic;
+ print_cmx_infos (ui, crc)
+ end else if magic_number = cmxa_magic_number then begin
+ let li = (input_value ic : library_infos) in
+ close_in ic;
+ print_cmxa_infos li
+ end else begin
+ let pos_trailer = in_channel_length ic - len_magic_number in
+ let _ = seek_in ic pos_trailer in
+ let magic_number = really_input_string ic len_magic_number in
+ if magic_number = Config.exec_magic_number then begin
+ dump_byte ic;
+ close_in ic
+ end else if Filename.check_suffix filename ".cmxs" then begin
+ flush stdout;
+ match read_dyn_header filename ic with
+ | None ->
+ printf "Unable to read info on file %s\n" filename;
+ exit 2
+ | Some header ->
+ if header.dynu_magic = Config.cmxs_magic_number then
+ print_cmxs_infos header
+ else begin
+ printf "Wrong magic number\n"; exit 2
+ end;
+ close_in ic
+ end else begin
+ printf "Not an OCaml object file\n"; exit 2
+ end
+ end
+
+let arg_list = []
+let arg_usage =
+ Printf.sprintf "%s [OPTIONS] FILES : give information on files" Sys.argv.(0)
+
+let main() =
+ Arg.parse arg_list dump_obj arg_usage;
+ exit 0
+
+let _ = main ()
diff --git a/tools/objinfo_helper.c b/tools/objinfo_helper.c
new file mode 100644
index 0000000000..ef7b7af7df
--- /dev/null
+++ b/tools/objinfo_helper.c
@@ -0,0 +1,99 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Mehdi Dogguy, PPS laboratory, University Paris Diderot */
+/* */
+/* Copyright 2010 Mehdi Dogguy. Used and distributed as part of */
+/* OCaml by permission from the author. This file is */
+/* distributed under the terms of the Q Public License version 1.0. */
+/***********************************************************************/
+
+#include "../config/s.h"
+#include "../byterun/caml/mlvalues.h"
+#include "../byterun/caml/alloc.h"
+#include <stdio.h>
+
+#ifdef HAS_LIBBFD
+#include <stdlib.h>
+#include <string.h>
+
+// PACKAGE: protect against binutils change
+// https://sourceware.org/bugzilla/show_bug.cgi?id=14243
+#define PACKAGE "ocamlobjinfo"
+#include <bfd.h>
+#undef PACKAGE
+
+#define plugin_header_sym (symbol_prefix "caml_plugin_header")
+
+int main(int argc, char ** argv)
+{
+ bfd *fd;
+ asection *sec;
+ file_ptr offset;
+ long st_size;
+ asymbol ** symbol_table;
+ long sym_count, i;
+
+ if (argc != 2) {
+ fprintf(stderr, "Usage: objinfo_helper <dynamic library>\n");
+ return 2;
+ }
+
+ fd = bfd_openr(argv[1], "default");
+ if (!fd) {
+ fprintf(stderr, "Error opening file %s\n", argv[1]);
+ return 2;
+ }
+ if (! bfd_check_format (fd, bfd_object)) {
+ fprintf(stderr, "Error: wrong format\n");
+ bfd_close(fd);
+ return 2;
+ }
+
+ sec = bfd_get_section_by_name(fd, ".data");
+ if (! sec) {
+ fprintf(stderr, "Error: section .data not found\n");
+ bfd_close(fd);
+ return 2;
+ }
+
+ offset = sec->filepos;
+ st_size = bfd_get_dynamic_symtab_upper_bound (fd);
+ if (st_size <= 0) {
+ fprintf(stderr, "Error: size of section .data unknown\n");
+ bfd_close(fd);
+ return 2;
+ }
+
+ symbol_table = malloc(st_size);
+ if (! symbol_table) {
+ fprintf(stderr, "Error: out of memory\n");
+ bfd_close(fd);
+ return 2;
+ }
+
+ sym_count = bfd_canonicalize_dynamic_symtab (fd, symbol_table);
+
+ for (i = 0; i < sym_count; i++) {
+ if (strcmp(symbol_table[i]->name, plugin_header_sym) == 0) {
+ printf("%ld\n", (long) (offset + symbol_table[i]->value));
+ bfd_close(fd);
+ return 0;
+ }
+ }
+
+ fprintf(stderr, "Error: missing symbol %s\n", plugin_header_sym);
+ bfd_close(fd);
+ return 2;
+}
+
+#else
+
+int main(int argc, char ** argv)
+{
+ fprintf(stderr,"BFD library unavailable, cannot print info on .cmxs files\n");
+ return 2;
+}
+
+#endif
diff --git a/tools/ocaml-objcopy-macosx b/tools/ocaml-objcopy-macosx
new file mode 100755
index 0000000000..e3fb6cbc36
--- /dev/null
+++ b/tools/ocaml-objcopy-macosx
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2005 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+TMP="${TMPDIR=/tmp}"
+TEMP="${TMP}"/ocaml-objcopy-$$.o
+UNDEF="${TMP}"/ocaml-objcopy-$$.sym
+
+usage () {
+ echo "usage: objcopy {--redefine-sym <old>=<new>} file.o" >&2
+ exit 2
+}
+
+: > "$UNDEF"
+
+while : ; do
+ case $# in
+ 0) break;;
+ *) case $1 in
+ --redefine-sym)
+ case $2 in
+ *=*) ALIAS="$ALIAS -i${2#*=}:${2%%=*}"
+ echo ${2%%=*} >>"$UNDEF"
+ ;;
+ *) usage;;
+ esac
+ shift 2
+ ;;
+ -*) usage;;
+ *) case $FILE in
+ "") FILE=$1; shift;;
+ *) usage;;
+ esac;;
+ esac;;
+ esac
+done
+
+ld -o "$TEMP" -r $ALIAS "$FILE"
+ld -o "$FILE" -r -unexported_symbols_list "$UNDEF" "$TEMP"
+
+rm -f "$TEMP" "$UNDEF"
diff --git a/tools/ocaml299to3.ml b/tools/ocaml299to3.ml
new file mode 100644
index 0000000000..a8eab92a99
--- /dev/null
+++ b/tools/ocaml299to3.ml
@@ -0,0 +1,138 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Lexer299
+
+let input_buffer = Buffer.create 16383
+let input_function ic buf len =
+ let len = input ic buf 0 len in
+ Buffer.add_substring input_buffer buf 0 len;
+ len
+
+let output_buffer = Buffer.create 16383
+
+let modified = ref false
+
+let convert buffer =
+ let input_pos = ref 0 in
+ let copy_input stop =
+ Buffer.add_substring output_buffer (Buffer.contents input_buffer)
+ !input_pos (stop - !input_pos);
+ input_pos := stop
+ in
+ let last = ref (EOF, 0, 0) in
+ try while true do
+ let token = Lexer299.token buffer
+ and start = Lexing.lexeme_start buffer
+ and stop = Lexing.lexeme_end buffer
+ and last_token, last_start, last_stop = !last in
+ begin match token with
+ | LABEL l0 ->
+ let l = if l0 = "fun" then "f" else l0 in
+ begin match last_token with
+ | PREFIXOP "?(" ->
+ modified := true;
+ copy_input last_start;
+ Buffer.add_char output_buffer '?';
+ Buffer.add_string output_buffer l;
+ Buffer.add_string output_buffer ":(";
+ input_pos := stop
+ | QUESTION | LPAREN | LBRACE | SEMI | MINUSGREATER
+ | EQUAL | COLON | COLONGREATER
+ | VAL | MUTABLE | EXTERNAL | METHOD | OF ->
+ if l0 = "fun" then begin
+ modified := true;
+ copy_input start;
+ Buffer.add_string output_buffer l;
+ Buffer.add_char output_buffer ':';
+ input_pos := stop
+ end
+ | _ ->
+ modified := true;
+ copy_input start;
+ Buffer.add_char output_buffer '~';
+ Buffer.add_string output_buffer l;
+ Buffer.add_char output_buffer ':';
+ input_pos := stop
+ end
+ | LABELID l ->
+ modified := true;
+ begin match last_token with
+ | PREFIXOP "?(" ->
+ copy_input last_start;
+ Buffer.add_string output_buffer "?(";
+ Buffer.add_string output_buffer l;
+ input_pos := stop
+ | LPAREN ->
+ copy_input last_start;
+ Buffer.add_string output_buffer "~(";
+ Buffer.add_string output_buffer l;
+ input_pos := stop
+ | QUESTION ->
+ copy_input last_stop;
+ Buffer.add_string output_buffer l;
+ input_pos := stop
+ | _ ->
+ copy_input start;
+ Buffer.add_char output_buffer '~';
+ Buffer.add_string output_buffer l;
+ input_pos := stop
+ end
+ | EOF -> raise End_of_file
+ | _ -> ()
+ end;
+ if last_token = QUESTION && token = LPAREN then
+ last := (PREFIXOP "?(", last_start, stop)
+ else
+ last := (token, start, stop)
+ done with
+ End_of_file ->
+ copy_input (Buffer.length input_buffer)
+
+let convert_file name =
+ let ic = open_in name in
+ Buffer.clear input_buffer;
+ Buffer.clear output_buffer;
+ modified := false;
+ begin
+ try convert (Lexing.from_function (input_function ic)); close_in ic
+ with exn -> close_in ic; raise exn
+ end;
+ if !modified then begin
+ let backup = name ^ ".bak" in
+ if Sys.file_exists backup then Sys.remove name
+ else Sys.rename name backup;
+ let oc = open_out name in
+ Buffer.output_buffer oc output_buffer;
+ close_out oc
+ end
+
+let _ =
+ if Array.length Sys.argv < 2 || Sys.argv.(1) = "-h" || Sys.argv.(1) = "-help"
+ then begin
+ print_endline "Usage: ocaml299to3 <source file> ...";
+ print_endline "Description:";
+ print_endline
+ "Convert OCaml 2.99 O'Labl-style labels in implementation files to";
+ print_endline
+ "a syntax compatible with version 3. Also `fun:' labels are replaced \
+ by `f:'.";
+ print_endline "Other syntactic changes are not handled.";
+ print_endline "Old files are renamed to <file>.bak.";
+ print_endline "Interface files do not need label syntax conversion.";
+ exit 0
+ end;
+ for i = 1 to Array.length Sys.argv - 1 do
+ let name = Sys.argv.(i) in
+ prerr_endline ("Converting " ^ name);
+ Printexc.catch convert_file name
+ done
diff --git a/tools/ocamlcp.ml b/tools/ocamlcp.ml
new file mode 100644
index 0000000000..74724576db
--- /dev/null
+++ b/tools/ocamlcp.ml
@@ -0,0 +1,155 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+
+let compargs = ref ([] : string list)
+let profargs = ref ([] : string list)
+let toremove = ref ([] : string list)
+
+let option opt () = compargs := opt :: !compargs
+let option_with_arg opt arg =
+ compargs := (Filename.quote arg) :: opt :: !compargs
+;;
+
+let make_archive = ref false;;
+let with_impl = ref false;;
+let with_intf = ref false;;
+let with_mli = ref false;;
+let with_ml = ref false;;
+
+let process_file filename =
+ if Filename.check_suffix filename ".ml" then with_ml := true;
+ if Filename.check_suffix filename ".mli" then with_mli := true;
+ compargs := (Filename.quote filename) :: !compargs
+;;
+
+let usage = "Usage: ocamlcp <options> <files>\noptions are:"
+
+let incompatible o =
+ fprintf stderr "ocamlcp: profiling is incompatible with the %s option\n" o;
+ exit 2
+
+module Options = Main_args.Make_bytecomp_options (struct
+ let _a () = make_archive := true; option "-a" ()
+ let _absname = option "-absname"
+ let _annot = option "-annot"
+ let _binannot = option "-bin-annot"
+ let _c = option "-c"
+ let _cc s = option_with_arg "-cc" s
+ let _cclib s = option_with_arg "-cclib" s
+ let _ccopt s = option_with_arg "-ccopt" s
+ let _config = option "-config"
+ let _compat_32 = option "-compat-32"
+ let _custom = option "-custom"
+ let _dllib = option_with_arg "-dllib"
+ let _dllpath = option_with_arg "-dllpath"
+ let _dtypes = option "-dtypes"
+ let _for_pack = option_with_arg "-for-pack"
+ let _g = option "-g"
+ let _i = option "-i"
+ let _I s = option_with_arg "-I" s
+ let _impl s = with_impl := true; option_with_arg "-impl" s
+ let _intf s = with_intf := true; option_with_arg "-intf" s
+ let _intf_suffix s = option_with_arg "-intf-suffix" s
+ let _keep_docs = option "-keep-docs"
+ let _keep_locs = option "-keep-locs"
+ let _labels = option "-labels"
+ let _linkall = option "-linkall"
+ let _make_runtime = option "-make-runtime"
+ let _no_alias_deps = option "-no-alias-deps"
+ let _no_app_funct = option "-no-app-funct"
+ let _no_check_prims = option "-no-check-prims"
+ let _noassert = option "-noassert"
+ let _nolabels = option "-nolabels"
+ let _noautolink = option "-noautolink"
+ let _nostdlib = option "-nostdlib"
+ let _o s = option_with_arg "-o" s
+ let _open s = option_with_arg "-open" s
+ let _output_obj = option "-output-obj"
+ let _output_complete_obj = option "-output-complete-obj"
+ let _pack = option "-pack"
+ let _pp _s = incompatible "-pp"
+ let _ppx _s = incompatible "-ppx"
+ let _principal = option "-principal"
+ let _rectypes = option "-rectypes"
+ let _runtime_variant s = option_with_arg "-runtime-variant" s
+ let _safe_string = option "-safe-string"
+ let _short_paths = option "-short-paths"
+ let _strict_sequence = option "-strict-sequence"
+ let _strict_formats = option "-strict-formats"
+ let _thread () = option "-thread" ()
+ let _vmthread () = option "-vmthread" ()
+ let _unsafe = option "-unsafe"
+ let _unsafe_string = option "-unsafe-string"
+ let _use_prims s = option_with_arg "-use-prims" s
+ let _use_runtime s = option_with_arg "-use-runtime" s
+ let _v = option "-v"
+ let _version = option "-version"
+ let _vnum = option "-vnum"
+ let _verbose = option "-verbose"
+ let _w = option_with_arg "-w"
+ let _warn_error = option_with_arg "-warn-error"
+ let _warn_help = option "-warn-help"
+ let _color s = option_with_arg "-color" s
+ let _where = option "-where"
+ let _nopervasives = option "-nopervasives"
+ let _dsource = option "-dsource"
+ let _dparsetree = option "-dparsetree"
+ let _dtypedtree = option "-dtypedtree"
+ let _drawlambda = option "-drawlambda"
+ let _dlambda = option "-dlambda"
+ let _dinstr = option "-dinstr"
+ let anonymous = process_file
+end);;
+
+let add_profarg s =
+ profargs := (Filename.quote s) :: "-m" :: !profargs
+;;
+
+let optlist =
+ ("-P", Arg.String add_profarg,
+ "[afilmt] Profile constructs specified by argument (default fm):\n\
+ \032 a Everything\n\
+ \032 f Function calls and method calls\n\
+ \032 i if ... then ... else\n\
+ \032 l while and for loops\n\
+ \032 m match ... with\n\
+ \032 t try ... with")
+ :: ("-p", Arg.String add_profarg, "[afilmt] Same as option -P")
+ :: Options.list
+in
+Arg.parse optlist process_file usage;
+if !with_impl && !with_intf then begin
+ fprintf stderr "ocamlcp cannot deal with both \"-impl\" and \"-intf\"\n";
+ fprintf stderr "please compile interfaces and implementations separately\n";
+ exit 2;
+end else if !with_impl && !with_mli then begin
+ fprintf stderr "ocamlcp cannot deal with both \"-impl\" and .mli files\n";
+ fprintf stderr "please compile interfaces and implementations separately\n";
+ exit 2;
+end else if !with_intf && !with_ml then begin
+ fprintf stderr "ocamlcp cannot deal with both \"-intf\" and .ml files\n";
+ fprintf stderr "please compile interfaces and implementations separately\n";
+ exit 2;
+end;
+if !with_impl then profargs := "-impl" :: !profargs;
+if !with_intf then profargs := "-intf" :: !profargs;
+let status =
+ Sys.command
+ (Printf.sprintf "ocamlc -pp \"ocamlprof -instrument %s\" %s %s"
+ (String.concat " " (List.rev !profargs))
+ (if !make_archive then "" else "profiling.cmo")
+ (String.concat " " (List.rev !compargs)))
+in
+exit status
+;;
diff --git a/tools/ocamldep.ml b/tools/ocamldep.ml
new file mode 100644
index 0000000000..94fda41c0a
--- /dev/null
+++ b/tools/ocamldep.ml
@@ -0,0 +1,519 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Compenv
+open Parsetree
+
+let ppf = Format.err_formatter
+(* Print the dependencies *)
+
+type file_kind = ML | MLI;;
+
+let load_path = ref ([] : (string * string array) list)
+let ml_synonyms = ref [".ml"]
+let mli_synonyms = ref [".mli"]
+let native_only = ref false
+let error_occurred = ref false
+let raw_dependencies = ref false
+let sort_files = ref false
+let all_dependencies = ref false
+let one_line = ref false
+let files = ref []
+let allow_approximation = ref false
+
+(* Fix path to use '/' as directory separator instead of '\'.
+ Only under Windows. *)
+
+let fix_slash s =
+ if Sys.os_type = "Unix" then s else begin
+ String.map (function '\\' -> '/' | c -> c) s
+ end
+
+(* Since we reinitialize load_path after reading OCAMLCOMP,
+ we must use a cache instead of calling Sys.readdir too often. *)
+module StringMap = Map.Make(String)
+let dirs = ref StringMap.empty
+let readdir dir =
+ try
+ StringMap.find dir !dirs
+ with Not_found ->
+ let contents =
+ try
+ Sys.readdir dir
+ with Sys_error msg ->
+ Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg;
+ error_occurred := true;
+ [||]
+ in
+ dirs := StringMap.add dir contents !dirs;
+ contents
+
+let add_to_list li s =
+ li := s :: !li
+
+let add_to_load_path dir =
+ try
+ let dir = Misc.expand_directory Config.standard_library dir in
+ let contents = readdir dir in
+ add_to_list load_path (dir, contents)
+ with Sys_error msg ->
+ Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg;
+ error_occurred := true
+
+let add_to_synonym_list synonyms suffix =
+ if (String.length suffix) > 1 && suffix.[0] = '.' then
+ add_to_list synonyms suffix
+ else begin
+ Format.fprintf Format.err_formatter "@[Bad suffix: '%s'@]@." suffix;
+ error_occurred := true
+ end
+
+(* Find file 'name' (capitalized) in search path *)
+let find_file name =
+ let uname = String.uncapitalize_ascii name in
+ let rec find_in_array a pos =
+ if pos >= Array.length a then None else begin
+ let s = a.(pos) in
+ if s = name || s = uname then Some s else find_in_array a (pos + 1)
+ end in
+ let rec find_in_path = function
+ [] -> raise Not_found
+ | (dir, contents) :: rem ->
+ match find_in_array contents 0 with
+ Some truename ->
+ if dir = "." then truename else Filename.concat dir truename
+ | None -> find_in_path rem in
+ find_in_path !load_path
+
+let rec find_file_in_list = function
+ [] -> raise Not_found
+| x :: rem -> try find_file x with Not_found -> find_file_in_list rem
+
+
+let find_dependency target_kind modname (byt_deps, opt_deps) =
+ try
+ let candidates = List.map ((^) modname) !mli_synonyms in
+ let filename = find_file_in_list candidates in
+ let basename = Filename.chop_extension filename in
+ let cmi_file = basename ^ ".cmi" in
+ let ml_exists =
+ List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !ml_synonyms in
+ let new_opt_dep =
+ if !all_dependencies then
+ match target_kind with
+ | MLI -> [ cmi_file ]
+ | ML ->
+ cmi_file :: (if ml_exists then [ basename ^ ".cmx"] else [])
+ else
+ (* this is a make-specific hack that makes .cmx to be a 'proxy'
+ target that would force the dependency on .cmi via transitivity *)
+ if ml_exists
+ then [ basename ^ ".cmx" ]
+ else [ cmi_file ]
+ in
+ ( cmi_file :: byt_deps, new_opt_dep @ opt_deps)
+ with Not_found ->
+ try
+ (* "just .ml" case *)
+ let candidates = List.map ((^) modname) !ml_synonyms in
+ let filename = find_file_in_list candidates in
+ let basename = Filename.chop_extension filename in
+ let bytenames =
+ if !all_dependencies then
+ match target_kind with
+ | MLI -> [basename ^ ".cmi"]
+ | ML -> [basename ^ ".cmi";]
+ else
+ (* again, make-specific hack *)
+ [basename ^ (if !native_only then ".cmx" else ".cmo")] in
+ let optnames =
+ if !all_dependencies
+ then match target_kind with
+ | MLI -> [basename ^ ".cmi"]
+ | ML -> [basename ^ ".cmi"; basename ^ ".cmx"]
+ else [ basename ^ ".cmx" ]
+ in
+ (bytenames @ byt_deps, optnames @ opt_deps)
+ with Not_found ->
+ (byt_deps, opt_deps)
+
+let (depends_on, escaped_eol) = (":", " \\\n ")
+
+let print_filename s =
+ let s = if !Clflags.force_slash then fix_slash s else s in
+ if not (String.contains s ' ') then begin
+ print_string s;
+ end else begin
+ let rec count n i =
+ if i >= String.length s then n
+ else if s.[i] = ' ' then count (n+1) (i+1)
+ else count n (i+1)
+ in
+ let spaces = count 0 0 in
+ let result = Bytes.create (String.length s + spaces) in
+ let rec loop i j =
+ if i >= String.length s then ()
+ else if s.[i] = ' ' then begin
+ Bytes.set result j '\\';
+ Bytes.set result (j+1) ' ';
+ loop (i+1) (j+2);
+ end else begin
+ Bytes.set result j s.[i];
+ loop (i+1) (j+1);
+ end
+ in
+ loop 0 0;
+ print_bytes result;
+ end
+;;
+
+let print_dependencies target_files deps =
+ let rec print_items pos = function
+ [] -> print_string "\n"
+ | dep :: rem ->
+ if !one_line || (pos + 1 + String.length dep <= 77) then begin
+ if pos <> 0 then print_string " "; print_filename dep;
+ print_items (pos + String.length dep + 1) rem
+ end else begin
+ print_string escaped_eol; print_filename dep;
+ print_items (String.length dep + 4) rem
+ end in
+ print_items 0 (target_files @ [depends_on] @ deps)
+
+let print_raw_dependencies source_file deps =
+ print_filename source_file; print_string depends_on;
+ Depend.StringSet.iter
+ (fun dep ->
+ (* filter out "*predef*" *)
+ if (String.length dep > 0)
+ && (match dep.[0] with
+ | 'A'..'Z' | '\128'..'\255' -> true
+ | _ -> false) then
+ begin
+ print_char ' ';
+ print_string dep
+ end)
+ deps;
+ print_char '\n'
+
+
+(* Process one file *)
+
+let report_err exn =
+ error_occurred := true;
+ match exn with
+ | Sys_error msg ->
+ Format.fprintf Format.err_formatter "@[I/O error:@ %s@]@." msg
+ | x ->
+ match Location.error_of_exn x with
+ | Some err ->
+ Format.fprintf Format.err_formatter "@[%a@]@."
+ Location.report_error err
+ | None -> raise x
+
+let tool_name = "ocamldep"
+
+let rec lexical_approximation lexbuf =
+ (* Approximation when a file can't be parsed.
+ Heuristic:
+ - first component of any path starting with an uppercase character is a
+ dependency.
+ - always skip the token after a dot, unless dot is preceded by a
+ lower-case identifier
+ - always skip the token after a backquote
+ *)
+ try
+ let rec process after_lident lexbuf =
+ match Lexer.token lexbuf with
+ | Parser.UIDENT name ->
+ Depend.free_structure_names :=
+ Depend.StringSet.add name !Depend.free_structure_names;
+ process false lexbuf
+ | Parser.LIDENT _ -> process true lexbuf
+ | Parser.DOT when after_lident -> process false lexbuf
+ | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf
+ | Parser.EOF -> ()
+ | _ -> process false lexbuf
+ and skip_one lexbuf =
+ match Lexer.token lexbuf with
+ | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf
+ | Parser.EOF -> ()
+ | _ -> process false lexbuf
+
+ in
+ process false lexbuf
+ with Lexer.Error _ -> lexical_approximation lexbuf
+
+let read_and_approximate inputfile =
+ error_occurred := false;
+ let ic = open_in_bin inputfile in
+ try
+ seek_in ic 0;
+ Location.input_name := inputfile;
+ let lexbuf = Lexing.from_channel ic in
+ Location.init lexbuf inputfile;
+ lexical_approximation lexbuf;
+ close_in ic;
+ !Depend.free_structure_names
+ with exn ->
+ close_in ic;
+ report_err exn;
+ !Depend.free_structure_names
+
+let read_parse_and_extract parse_function extract_function magic source_file =
+ Depend.free_structure_names := Depend.StringSet.empty;
+ try
+ let input_file = Pparse.preprocess source_file in
+ begin try
+ let ast =
+ Pparse.file ~tool_name Format.err_formatter
+ input_file parse_function magic
+ in
+ let bound_vars = Depend.StringSet.empty in
+ List.iter (fun modname ->
+ Depend.open_module bound_vars (Longident.Lident modname)
+ ) !Clflags.open_modules;
+ extract_function bound_vars ast;
+ Pparse.remove_preprocessed input_file;
+ !Depend.free_structure_names
+ with x ->
+ Pparse.remove_preprocessed input_file;
+ raise x
+ end
+ with x -> begin
+ report_err x;
+ if not !allow_approximation
+ then Depend.StringSet.empty
+ else read_and_approximate source_file
+ end
+
+let ml_file_dependencies source_file =
+ let parse_use_file_as_impl lexbuf =
+ let f x =
+ match x with
+ | Ptop_def s -> s
+ | Ptop_dir _ -> []
+ in
+ List.flatten (List.map f (Parse.use_file lexbuf))
+ in
+ let extracted_deps =
+ read_parse_and_extract parse_use_file_as_impl Depend.add_implementation
+ Config.ast_impl_magic_number source_file
+ in
+ if !sort_files then
+ files := (source_file, ML, !Depend.free_structure_names) :: !files
+ else
+ if !raw_dependencies then begin
+ print_raw_dependencies source_file extracted_deps
+ end else begin
+ let basename = Filename.chop_extension source_file in
+ let byte_targets = [ basename ^ ".cmo" ] in
+ let native_targets =
+ if !all_dependencies
+ then [ basename ^ ".cmx"; basename ^ ".o" ]
+ else [ basename ^ ".cmx" ] in
+ let init_deps = if !all_dependencies then [source_file] else [] in
+ let cmi_name = basename ^ ".cmi" in
+ let init_deps, extra_targets =
+ if List.exists (fun ext -> Sys.file_exists (basename ^ ext))
+ !mli_synonyms
+ then (cmi_name :: init_deps, cmi_name :: init_deps), []
+ else (init_deps, init_deps),
+ (if !all_dependencies then [cmi_name] else [])
+ in
+ let (byt_deps, native_deps) =
+ Depend.StringSet.fold (find_dependency ML)
+ extracted_deps init_deps in
+ print_dependencies (byte_targets @ extra_targets) byt_deps;
+ print_dependencies (native_targets @ extra_targets) native_deps;
+ end
+
+let mli_file_dependencies source_file =
+ let extracted_deps =
+ read_parse_and_extract Parse.interface Depend.add_signature
+ Config.ast_intf_magic_number source_file
+ in
+ if !sort_files then
+ files := (source_file, MLI, extracted_deps) :: !files
+ else
+ if !raw_dependencies then begin
+ print_raw_dependencies source_file extracted_deps
+ end else begin
+ let basename = Filename.chop_extension source_file in
+ let (byt_deps, _opt_deps) =
+ Depend.StringSet.fold (find_dependency MLI)
+ extracted_deps ([], []) in
+ print_dependencies [basename ^ ".cmi"] byt_deps
+ end
+
+let file_dependencies_as kind source_file =
+ Compenv.readenv ppf Before_compile;
+ load_path := [];
+ List.iter add_to_load_path (
+ (!Compenv.last_include_dirs @
+ !Clflags.include_dirs @
+ !Compenv.first_include_dirs
+ ));
+ Location.input_name := source_file;
+ try
+ if Sys.file_exists source_file then begin
+ match kind with
+ | ML -> ml_file_dependencies source_file
+ | MLI -> mli_file_dependencies source_file
+ end
+ with x -> report_err x
+
+let file_dependencies source_file =
+ if List.exists (Filename.check_suffix source_file) !ml_synonyms then
+ file_dependencies_as ML source_file
+ else if List.exists (Filename.check_suffix source_file) !mli_synonyms then
+ file_dependencies_as MLI source_file
+ else ()
+
+let sort_files_by_dependencies files =
+ let h = Hashtbl.create 31 in
+ let worklist = ref [] in
+
+(* Init Hashtbl with all defined modules *)
+ let files = List.map (fun (file, file_kind, deps) ->
+ let modname =
+ String.capitalize_ascii (Filename.chop_extension (Filename.basename file))
+ in
+ let key = (modname, file_kind) in
+ let new_deps = ref [] in
+ Hashtbl.add h key (file, new_deps);
+ worklist := key :: !worklist;
+ (modname, file_kind, deps, new_deps)
+ ) files in
+
+(* Keep only dependencies to defined modules *)
+ List.iter (fun (modname, file_kind, deps, new_deps) ->
+ let add_dep modname kind =
+ new_deps := (modname, kind) :: !new_deps;
+ in
+ Depend.StringSet.iter (fun modname ->
+ match file_kind with
+ ML -> (* ML depends both on ML and MLI *)
+ if Hashtbl.mem h (modname, MLI) then add_dep modname MLI;
+ if Hashtbl.mem h (modname, ML) then add_dep modname ML
+ | MLI -> (* MLI depends on MLI if exists, or ML otherwise *)
+ if Hashtbl.mem h (modname, MLI) then add_dep modname MLI
+ else if Hashtbl.mem h (modname, ML) then add_dep modname ML
+ ) deps;
+ if file_kind = ML then (* add dep from .ml to .mli *)
+ if Hashtbl.mem h (modname, MLI) then add_dep modname MLI
+ ) files;
+
+(* Print and remove all files with no remaining dependency. Iterate
+ until all files have been removed (worklist is empty) or
+ no file was removed during a turn (cycle). *)
+ let printed = ref true in
+ while !printed && !worklist <> [] do
+ let files = !worklist in
+ worklist := [];
+ printed := false;
+ List.iter (fun key ->
+ let (file, deps) = Hashtbl.find h key in
+ let set = !deps in
+ deps := [];
+ List.iter (fun key ->
+ if Hashtbl.mem h key then deps := key :: !deps
+ ) set;
+ if !deps = [] then begin
+ printed := true;
+ Printf.printf "%s " file;
+ Hashtbl.remove h key;
+ end else
+ worklist := key :: !worklist
+ ) files
+ done;
+
+ if !worklist <> [] then begin
+ Format.fprintf Format.err_formatter
+ "@[Warning: cycle in dependencies. End of list is not sorted.@]@.";
+ let sorted_deps =
+ let li = ref [] in
+ Hashtbl.iter (fun _ file_deps -> li := file_deps :: !li) h;
+ List.sort (fun (file1, _) (file2, _) -> String.compare file1 file2) !li
+ in
+ List.iter (fun (file, deps) ->
+ Format.fprintf Format.err_formatter "\t@[%s: " file;
+ List.iter (fun (modname, kind) ->
+ Format.fprintf Format.err_formatter "%s.%s " modname
+ (if kind=ML then "ml" else "mli");
+ ) !deps;
+ Format.fprintf Format.err_formatter "@]@.";
+ Printf.printf "%s " file) sorted_deps;
+ end;
+ Printf.printf "\n%!";
+ ()
+
+
+(* Entry point *)
+
+let usage = "Usage: ocamldep [options] <source files>\nOptions are:"
+
+let print_version () =
+ Format.printf "ocamldep, version %s@." Sys.ocaml_version;
+ exit 0;
+;;
+
+let print_version_num () =
+ Format.printf "%s@." Sys.ocaml_version;
+ exit 0;
+;;
+
+let _ =
+ Clflags.classic := false;
+ add_to_list first_include_dirs Filename.current_dir_name;
+ Compenv.readenv ppf Before_args;
+ Arg.parse [
+ "-absname", Arg.Set Location.absname,
+ " Show absolute filenames in error messages";
+ "-all", Arg.Set all_dependencies,
+ " Generate dependencies on all files";
+ "-I", Arg.String (add_to_list Clflags.include_dirs),
+ "<dir> Add <dir> to the list of include directories";
+ "-impl", Arg.String (file_dependencies_as ML),
+ "<f> Process <f> as a .ml file";
+ "-intf", Arg.String (file_dependencies_as MLI),
+ "<f> Process <f> as a .mli file";
+ "-allow-approx", Arg.Set allow_approximation,
+ " Fallback to a lexer-based approximation on unparseable files.";
+ "-ml-synonym", Arg.String(add_to_synonym_list ml_synonyms),
+ "<e> Consider <e> as a synonym of the .ml extension";
+ "-mli-synonym", Arg.String(add_to_synonym_list mli_synonyms),
+ "<e> Consider <e> as a synonym of the .mli extension";
+ "-modules", Arg.Set raw_dependencies,
+ " Print module dependencies in raw form (not suitable for make)";
+ "-native", Arg.Set native_only,
+ " Generate dependencies for native-code only (no .cmo files)";
+ "-one-line", Arg.Set one_line,
+ " Output one line per file, regardless of the length";
+ "-open", Arg.String (add_to_list Clflags.open_modules),
+ "<module> Opens the module <module> before typing";
+ "-pp", Arg.String(fun s -> Clflags.preprocessor := Some s),
+ "<cmd> Pipe sources through preprocessor <cmd>";
+ "-ppx", Arg.String (add_to_list first_ppx),
+ "<cmd> Pipe abstract syntax trees through preprocessor <cmd>";
+ "-slash", Arg.Set Clflags.force_slash,
+ " (Windows) Use forward slash / instead of backslash \\ in file paths";
+ "-sort", Arg.Set sort_files,
+ " Sort files according to their dependencies";
+ "-version", Arg.Unit print_version,
+ " Print version and exit";
+ "-vnum", Arg.Unit print_version_num,
+ " Print version number and exit";
+ ] file_dependencies usage;
+ Compenv.readenv ppf Before_link;
+ if !sort_files then sort_files_by_dependencies !files;
+ exit (if !error_occurred then 2 else 0)
diff --git a/tools/ocamlmklib.ml b/tools/ocamlmklib.ml
new file mode 100644
index 0000000000..69cb0452fa
--- /dev/null
+++ b/tools/ocamlmklib.ml
@@ -0,0 +1,308 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+open Ocamlmklibconfig
+
+(* PR#4783: under Windows, don't use absolute paths because we do
+ not know where the binary distribution will be installed. *)
+let compiler_path name =
+ if Sys.os_type = "Win32" then name else Filename.concat bindir name
+
+let bytecode_objs = ref [] (* .cmo,.cma,.ml,.mli files to pass to ocamlc *)
+and native_objs = ref [] (* .cmx,.cmxa,.ml,.mli files to pass to ocamlopt *)
+and c_objs = ref [] (* .o, .a, .obj, .lib, .dll, .dylib, .so files to
+ pass to mksharedlib and ar *)
+and caml_libs = ref [] (* -cclib to pass to ocamlc, ocamlopt *)
+and caml_opts = ref [] (* -ccopt to pass to ocamlc, ocamlopt *)
+and dynlink = ref supports_shared_libraries
+and failsafe = ref false (* whether to fall back on static build only *)
+and c_libs = ref [] (* libs to pass to mksharedlib and ocamlc -cclib *)
+and c_Lopts = ref [] (* options to pass to mksharedlib and ocamlc -cclib *)
+and c_opts = ref [] (* options to pass to mksharedlib and ocamlc -ccopt *)
+and ld_opts = ref [] (* options to pass only to the linker *)
+and ocamlc = ref (compiler_path "ocamlc")
+and ocamlc_opts = ref [] (* options to pass only to ocamlc *)
+and ocamlopt = ref (compiler_path "ocamlopt")
+and ocamlopt_opts = ref [] (* options to pass only to ocamlc *)
+and output = ref "a" (* Output name for OCaml part of library *)
+and output_c = ref "" (* Output name for C part of library *)
+and rpath = ref [] (* rpath options *)
+and debug = ref false (* -g option *)
+and verbose = ref false
+
+let starts_with s pref =
+ String.length s >= String.length pref &&
+ String.sub s 0 (String.length pref) = pref
+let ends_with = Filename.check_suffix
+let chop_prefix s pref =
+ String.sub s (String.length pref) (String.length s - String.length pref)
+let chop_suffix = Filename.chop_suffix
+
+exception Bad_argument of string
+
+let print_version () =
+ printf "ocamlmklib, version %s\n" Sys.ocaml_version;
+ exit 0;
+;;
+
+let print_version_num () =
+ printf "%s\n" Sys.ocaml_version;
+ exit 0;
+;;
+
+let parse_arguments argv =
+ let i = ref 1 in
+ let next_arg () =
+ if !i + 1 >= Array.length argv
+ then raise (Bad_argument("Option " ^ argv.(!i) ^ " expects one argument"));
+ incr i; argv.(!i) in
+ while !i < Array.length argv do
+ let s = argv.(!i) in
+ if ends_with s ".cmo" || ends_with s ".cma" then
+ bytecode_objs := s :: !bytecode_objs
+ else if ends_with s ".cmx" || ends_with s ".cmxa" then
+ native_objs := s :: !native_objs
+ else if ends_with s ".ml" || ends_with s ".mli" then
+ (bytecode_objs := s :: !bytecode_objs;
+ native_objs := s :: !native_objs)
+ else if List.exists (ends_with s)
+ [".o"; ".a"; ".obj"; ".lib"; ".dll"; ".dylib"; ".so"]
+ then
+ c_objs := s :: !c_objs
+ else if s = "-cclib" then
+ caml_libs := next_arg () :: "-cclib" :: !caml_libs
+ else if s = "-ccopt" then
+ caml_opts := next_arg () :: "-ccopt" :: !caml_opts
+ else if s = "-custom" then
+ dynlink := false
+ else if s = "-I" then
+ caml_opts := next_arg () :: "-I" :: !caml_opts
+ else if s = "-failsafe" then
+ failsafe := true
+ else if s = "-g" then
+ debug := true
+ else if s = "-h" || s = "-help" || s = "--help" then
+ raise (Bad_argument "")
+ else if s = "-ldopt" then
+ ld_opts := next_arg () :: !ld_opts
+ else if s = "-linkall" then
+ caml_opts := s :: !caml_opts
+ else if starts_with s "-l" then
+ c_libs := s :: !c_libs
+ else if starts_with s "-L" then
+ (c_Lopts := s :: !c_Lopts;
+ let l = chop_prefix s "-L" in
+ if not (Filename.is_relative l) then rpath := l :: !rpath)
+ else if s = "-ocamlcflags" then
+ ocamlc_opts := next_arg () :: !ocamlc_opts
+ else if s = "-ocamlc" then
+ ocamlc := next_arg ()
+ else if s = "-ocamlopt" then
+ ocamlopt := next_arg ()
+ else if s = "-ocamloptflags" then
+ ocamlopt_opts := next_arg () :: !ocamlopt_opts
+ else if s = "-o" then
+ output := next_arg()
+ else if s = "-oc" then
+ output_c := next_arg()
+ else if s = "-dllpath" || s = "-R" || s = "-rpath" then
+ rpath := next_arg() :: !rpath
+ else if starts_with s "-R" then
+ rpath := chop_prefix s "-R" :: !rpath
+ else if s = "-Wl,-rpath" then
+ (let a = next_arg() in
+ if starts_with a "-Wl,"
+ then rpath := chop_prefix a "-Wl," :: !rpath
+ else raise (Bad_argument("Option -Wl,-rpath expects a -Wl, argument")))
+ else if starts_with s "-Wl,-rpath," then
+ rpath := chop_prefix s "-Wl,-rpath," :: !rpath
+ else if starts_with s "-Wl,-R" then
+ rpath := chop_prefix s "-Wl,-R" :: !rpath
+ else if s = "-v" || s = "-verbose" then
+ verbose := true
+ else if s = "-version" then
+ print_version ()
+ else if s = "-vnum" then
+ print_version_num ()
+ else if starts_with s "-F" then
+ c_opts := s :: !c_opts
+ else if s = "-framework" then
+ (let a = next_arg() in c_opts := a :: s :: !c_opts)
+ else if starts_with s "-" then
+ prerr_endline ("Unknown option " ^ s)
+ else
+ raise (Bad_argument("Don't know what to do with " ^ s));
+ incr i
+ done;
+ List.iter
+ (fun r -> r := List.rev !r)
+ [ bytecode_objs; native_objs; caml_libs; caml_opts;
+ c_libs; c_objs; c_opts; ld_opts; rpath ];
+(* Put -L options in front of -l options in -cclib to mimic -ccopt behavior *)
+ c_libs := !c_Lopts @ !c_libs;
+
+ if !output_c = "" then output_c := !output
+
+let usage = "\
+Usage: ocamlmklib [options] <.cmo|.cma|.cmx|.cmxa|.ml|.mli|.o|.a|.obj|.lib|\
+ .dll|.dylib files>\
+\nOptions are:\
+\n -cclib <lib> C library passed to ocamlc -a or ocamlopt -a only\
+\n -ccopt <opt> C option passed to ocamlc -a or ocamlopt -a only\
+\n -custom Disable dynamic loading\
+\n -g Build with debug information\
+\n -dllpath <dir> Add <dir> to the run-time search path for DLLs\
+\n -F<dir> Specify a framework directory (MacOSX)\
+\n -framework <name> Use framework <name> (MacOSX)\
+\n -help Print this help message and exit\
+\n --help Same as -help\
+\n -h Same as -help\
+\n -I <dir> Add <dir> to the path searched for OCaml object files\
+\n -failsafe fall back to static linking if DLL construction failed\
+\n -ldopt <opt> C option passed to the shared linker only\
+\n -linkall Build OCaml archive with link-all behavior\
+\n -l<lib> Specify a dependent C library\
+\n -L<dir> Add <dir> to the path searched for C libraries\
+\n -ocamlc <cmd> Use <cmd> in place of \"ocamlc\"\
+\n -ocamlcflags <opt> Pass <opt> to ocamlc\
+\n -ocamlopt <cmd> Use <cmd> in place of \"ocamlopt\"\
+\n -ocamloptflags <opt> Pass <opt> to ocamlopt\
+\n -o <name> Generated OCaml library is named <name>.cma or <name>.cmxa\
+\n -oc <name> Generated C library is named dll<name>.so or lib<name>.a\
+\n -rpath <dir> Same as -dllpath <dir>\
+\n -R<dir> Same as -rpath\
+\n -verbose Print commands before executing them\
+\n -v same as -verbose\
+\n -version Print version and exit\
+\n -vnum Print version number and exit\
+\n -Wl,-rpath,<dir> Same as -dllpath <dir>\
+\n -Wl,-rpath -Wl,<dir> Same as -dllpath <dir>\
+\n -Wl,-R<dir> Same as -dllpath <dir>\
+\n"
+
+let command cmd =
+ if !verbose then (print_string "+ "; print_string cmd; print_newline());
+ Sys.command cmd
+
+let scommand cmd =
+ if command cmd <> 0 then exit 2
+
+let safe_remove s =
+ try Sys.remove s with Sys_error _ -> ()
+
+let make_set l =
+ let rec merge l = function
+ [] -> List.rev l
+ | p :: r -> if List.mem p l then merge l r else merge (p::l) r
+ in
+ merge [] l
+
+let make_rpath flag =
+ if !rpath = [] || flag = ""
+ then ""
+ else flag ^ String.concat ":" (make_set !rpath)
+
+let make_rpath_ccopt flag =
+ if !rpath = [] || flag = ""
+ then ""
+ else "-ccopt " ^ flag ^ String.concat ":" (make_set !rpath)
+
+let prefix_list pref l =
+ List.map (fun s -> pref ^ s) l
+
+let prepostfix pre name post =
+ let base = Filename.basename name in
+ let dir = Filename.dirname name in
+ Filename.concat dir (pre ^ base ^ post)
+;;
+
+let transl_path s =
+ match Sys.os_type with
+ | "Win32" ->
+ let s = Bytes.of_string s in
+ let rec aux i =
+ if i = Bytes.length s || Bytes.get s i = ' ' then s
+ else begin
+ if Bytes.get s i = '/' then Bytes.set s i '\\';
+ aux (i + 1)
+ end
+ in Bytes.to_string (aux 0)
+ | _ -> s
+
+let build_libs () =
+ if !c_objs <> [] then begin
+ if !dynlink then begin
+ let retcode = command
+ (Printf.sprintf "%s %s -o %s %s %s %s %s %s"
+ mkdll
+ (if !debug then "-g" else "")
+ (prepostfix "dll" !output_c ext_dll)
+ (String.concat " " !c_objs)
+ (String.concat " " !c_opts)
+ (String.concat " " !ld_opts)
+ (make_rpath mksharedlibrpath)
+ (String.concat " " !c_libs)
+ )
+ in
+ if retcode <> 0 then if !failsafe then dynlink := false else exit 2
+ end;
+ safe_remove (prepostfix "lib" !output_c ext_lib);
+ scommand
+ (mklib (prepostfix "lib" !output_c ext_lib)
+ (String.concat " " !c_objs) "");
+ end;
+ if !bytecode_objs <> [] then
+ scommand
+ (sprintf "%s -a %s %s %s -o %s.cma %s %s -dllib -l%s -cclib -l%s \
+ %s %s %s %s"
+ (transl_path !ocamlc)
+ (if !debug then "-g" else "")
+ (if !dynlink then "" else "-custom")
+ (String.concat " " !ocamlc_opts)
+ !output
+ (String.concat " " !caml_opts)
+ (String.concat " " !bytecode_objs)
+ (Filename.basename !output_c)
+ (Filename.basename !output_c)
+ (String.concat " " (prefix_list "-ccopt " !c_opts))
+ (make_rpath_ccopt byteccrpath)
+ (String.concat " " (prefix_list "-cclib " !c_libs))
+ (String.concat " " !caml_libs));
+ if !native_objs <> [] then
+ scommand
+ (sprintf "%s -a %s %s -o %s.cmxa %s %s -cclib -l%s %s %s %s %s"
+ (transl_path !ocamlopt)
+ (if !debug then "-g" else "")
+ (String.concat " " !ocamlopt_opts)
+ !output
+ (String.concat " " !caml_opts)
+ (String.concat " " !native_objs)
+ (Filename.basename !output_c)
+ (String.concat " " (prefix_list "-ccopt " !c_opts))
+ (make_rpath_ccopt nativeccrpath)
+ (String.concat " " (prefix_list "-cclib " !c_libs))
+ (String.concat " " !caml_libs))
+
+let _ =
+ try
+ parse_arguments Sys.argv;
+ build_libs()
+ with
+ | Bad_argument "" ->
+ prerr_string usage; exit 0
+ | Bad_argument s ->
+ prerr_endline s; prerr_string usage; exit 4
+ | Sys_error s ->
+ prerr_string "System error: "; prerr_endline s; exit 4
+ | x ->
+ raise x
diff --git a/tools/ocamlmktop.ml b/tools/ocamlmktop.ml
new file mode 100644
index 0000000000..06288d740b
--- /dev/null
+++ b/tools/ocamlmktop.ml
@@ -0,0 +1,17 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let _ =
+ let args = Ccomp.quote_files (List.tl (Array.to_list Sys.argv)) in
+ exit(Sys.command("ocamlc -I +compiler-libs -linkall ocamlcommon.cma \
+ ocamlbytecomp.cma ocamltoplevel.cma "
+ ^ args ^ " topstart.cmo"))
diff --git a/tools/ocamlmktop.tpl b/tools/ocamlmktop.tpl
new file mode 100644
index 0000000000..6d7d68b41e
--- /dev/null
+++ b/tools/ocamlmktop.tpl
@@ -0,0 +1,15 @@
+#!/bin/sh
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Para, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+exec %%BINDIR%%/ocamlc -I +compiler-libs -linkall ocamlcommon.cma \
+ ocamlbytecomp.cma ocamltoplevel.cma "$@" topstart.cmo
diff --git a/tools/ocamloptp.ml b/tools/ocamloptp.ml
new file mode 100644
index 0000000000..6daaa252ab
--- /dev/null
+++ b/tools/ocamloptp.ml
@@ -0,0 +1,171 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+
+let compargs = ref ([] : string list)
+let profargs = ref ([] : string list)
+let toremove = ref ([] : string list)
+
+let option opt () = compargs := opt :: !compargs
+let option_with_arg opt arg =
+ compargs := (Filename.quote arg) :: opt :: !compargs
+;;
+let option_with_int opt arg =
+ compargs := (string_of_int arg) :: opt :: !compargs
+;;
+
+let make_archive = ref false;;
+let with_impl = ref false;;
+let with_intf = ref false;;
+let with_mli = ref false;;
+let with_ml = ref false;;
+
+let process_file filename =
+ if Filename.check_suffix filename ".ml" then with_ml := true;
+ if Filename.check_suffix filename ".mli" then with_mli := true;
+ compargs := (Filename.quote filename) :: !compargs
+;;
+
+let usage = "Usage: ocamloptp <options> <files>\noptions are:"
+
+let incompatible o =
+ fprintf stderr "ocamloptp: profiling is incompatible with the %s option\n" o;
+ exit 2
+
+module Options = Main_args.Make_optcomp_options (struct
+ let _a () = make_archive := true; option "-a" ()
+ let _absname = option "-absname"
+ let _annot = option "-annot"
+ let _binannot = option "-bin-annot"
+ let _c = option "-c"
+ let _cc s = option_with_arg "-cc" s
+ let _cclib s = option_with_arg "-cclib" s
+ let _ccopt s = option_with_arg "-ccopt" s
+ let _compact = option "-compact"
+ let _config = option "-config"
+ let _for_pack s = option_with_arg "-for-pack" s
+ let _g = option "-g"
+ let _i = option "-i"
+ let _I s = option_with_arg "-I" s
+ let _impl s = with_impl := true; option_with_arg "-impl" s
+ let _inline n = option_with_int "-inline" n
+ let _intf s = with_intf := true; option_with_arg "-intf" s
+ let _intf_suffix s = option_with_arg "-intf-suffix" s
+ let _keep_docs = option "-keep-docs"
+ let _keep_locs = option "-keep-locs"
+ let _labels = option "-labels"
+ let _linkall = option "-linkall"
+ let _no_alias_deps = option "-no-alias-deps"
+ let _no_app_funct = option "-no-app-funct"
+ let _no_float_const_prop = option "-no-float-const-prop"
+ let _noassert = option "-noassert"
+ let _noautolink = option "-noautolink"
+ let _nodynlink = option "-nodynlink"
+ let _nolabels = option "-nolabels"
+ let _nostdlib = option "-nostdlib"
+ let _o s = option_with_arg "-o" s
+ let _open s = option_with_arg "-open" s
+ let _output_obj = option "-output-obj"
+ let _output_complete_obj = option "-output-complete-obj"
+ let _p = option "-p"
+ let _pack = option "-pack"
+ let _pp _s = incompatible "-pp"
+ let _ppx _s = incompatible "-ppx"
+ let _principal = option "-principal"
+ let _rectypes = option "-rectypes"
+ let _runtime_variant s = option_with_arg "-runtime-variant" s
+ let _S = option "-S"
+ let _safe_string = option "-safe-string"
+ let _short_paths = option "-short-paths"
+ let _strict_sequence = option "-strict-sequence"
+ let _strict_formats = option "-strict-formats"
+ let _shared = option "-shared"
+ let _thread = option "-thread"
+ let _unsafe = option "-unsafe"
+ let _unsafe_string = option "-unsafe-string"
+ let _v = option "-v"
+ let _version = option "-version"
+ let _vnum = option "-vnum"
+ let _verbose = option "-verbose"
+ let _w = option_with_arg "-w"
+ let _warn_error = option_with_arg "-warn-error"
+ let _warn_help = option "-warn-help"
+ let _color s = option_with_arg "-color" s
+ let _where = option "-where"
+
+ let _nopervasives = option "-nopervasives"
+ let _dsource = option "-dsource"
+ let _dparsetree = option "-dparsetree"
+ let _dtypedtree = option "-dtypedtree"
+ let _drawlambda = option "-drawlambda"
+ let _dlambda = option "-dlambda"
+ let _dclambda = option "-dclambda"
+ let _dcmm = option "-dcmm"
+ let _dsel = option "-dsel"
+ let _dcombine = option "-dcombine"
+ let _dcse = option "-dcse"
+ let _dlive = option "-dlive"
+ let _dspill = option "-dspill"
+ let _dsplit = option "-dsplit"
+ let _dinterf = option "-dinterf"
+ let _dprefer = option "-dprefer"
+ let _dalloc = option "-dalloc"
+ let _dreload = option "-dreload"
+ let _dscheduling = option "-dscheduling"
+ let _dlinear = option "-dlinear"
+ let _dstartup = option "-dstartup"
+ let _opaque = option "-opaque"
+
+ let anonymous = process_file
+end);;
+
+let add_profarg s =
+ profargs := (Filename.quote s) :: "-m" :: !profargs
+;;
+
+let optlist =
+ ("-P", Arg.String add_profarg,
+ "[afilmt] Profile constructs specified by argument (default fm):\n\
+ \032 a Everything\n\
+ \032 f Function calls and method calls\n\
+ \032 i if ... then ... else\n\
+ \032 l while and for loops\n\
+ \032 m match ... with\n\
+ \032 t try ... with")
+ :: Options.list
+in
+Arg.parse optlist process_file usage;
+if !with_impl && !with_intf then begin
+ fprintf stderr "ocamloptp cannot deal with both \"-impl\" and \"-intf\"\n";
+ fprintf stderr "please compile interfaces and implementations separately\n";
+ exit 2;
+end else if !with_impl && !with_mli then begin
+ fprintf stderr "ocamloptp cannot deal with both \"-impl\" and .mli files\n";
+ fprintf stderr "please compile interfaces and implementations separately\n";
+ exit 2;
+end else if !with_intf && !with_ml then begin
+ fprintf stderr "ocamloptp cannot deal with both \"-intf\" and .ml files\n";
+ fprintf stderr "please compile interfaces and implementations separately\n";
+ exit 2;
+end;
+if !with_impl then profargs := "-impl" :: !profargs;
+if !with_intf then profargs := "-intf" :: !profargs;
+let status =
+ Sys.command
+ (Printf.sprintf "ocamlopt -pp \"ocamlprof -instrument %s\" %s %s"
+ (String.concat " " (List.rev !profargs))
+ (if !make_archive then "" else "profiling.cmx")
+ (String.concat " " (List.rev !compargs)))
+in
+exit status
+;;
diff --git a/tools/ocamlprof.ml b/tools/ocamlprof.ml
new file mode 100644
index 0000000000..dde248cd48
--- /dev/null
+++ b/tools/ocamlprof.ml
@@ -0,0 +1,510 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez and Francois Rouaix, INRIA Rocquencourt *)
+(* Ported to Caml Special Light by John Malecki *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Printf
+
+open Location
+open Parsetree
+
+(* User programs must not use identifiers that start with these prefixes. *)
+let idprefix = "__ocaml_prof_";;
+let modprefix = "OCAML__prof_";;
+
+(* Errors specific to the profiler *)
+exception Profiler of string
+
+(* Modes *)
+let instr_fun = ref false
+and instr_match = ref false
+and instr_if = ref false
+and instr_loops = ref false
+and instr_try = ref false
+
+let cur_point = ref 0
+and inchan = ref stdin
+and outchan = ref stdout
+
+(* To copy source fragments *)
+let copy_buffer = Bytes.create 256
+
+let copy_chars_unix nchars =
+ let n = ref nchars in
+ while !n > 0 do
+ let m = input !inchan copy_buffer 0 (min !n 256) in
+ if m = 0 then raise End_of_file;
+ output !outchan copy_buffer 0 m;
+ n := !n - m
+ done
+
+let copy_chars_win32 nchars =
+ for _i = 1 to nchars do
+ let c = input_char !inchan in
+ if c <> '\r' then output_char !outchan c
+ done
+
+let copy_chars =
+ match Sys.os_type with
+ "Win32" | "Cygwin" -> copy_chars_win32
+ | _ -> copy_chars_unix
+
+let copy next =
+ assert (next >= !cur_point);
+ seek_in !inchan !cur_point;
+ copy_chars (next - !cur_point);
+ cur_point := next;
+;;
+
+let prof_counter = ref 0;;
+
+let instr_mode = ref false
+
+type insert = Open | Close;;
+let to_insert = ref ([] : (insert * int) list);;
+
+let insert_action st en =
+ to_insert := (Open, st) :: (Close, en) :: !to_insert
+;;
+
+(* Producing instrumented code *)
+let add_incr_counter modul (kind,pos) =
+ copy pos;
+ match kind with
+ | Open ->
+ fprintf !outchan "(%sProfiling.incr %s%s_cnt %d; "
+ modprefix idprefix modul !prof_counter;
+ incr prof_counter;
+ | Close -> fprintf !outchan ")";
+;;
+
+let counters = ref (Array.make 0 0)
+
+(* User defined marker *)
+let special_id = ref ""
+
+(* Producing results of profile run *)
+let add_val_counter (kind,pos) =
+ if kind = Open then begin
+ copy pos;
+ fprintf !outchan "(* %s%d *) " !special_id !counters.(!prof_counter);
+ incr prof_counter;
+ end
+;;
+
+(* ************* rewrite ************* *)
+
+let insert_profile rw_exp ex =
+ let st = ex.pexp_loc.loc_start.Lexing.pos_cnum
+ and en = ex.pexp_loc.loc_end.Lexing.pos_cnum
+ and gh = ex.pexp_loc.loc_ghost
+ in
+ if gh || st = en then
+ rw_exp true ex
+ else begin
+ insert_action st en;
+ rw_exp false ex;
+ end
+;;
+
+
+let pos_len = ref 0
+
+let init_rewrite modes mod_name =
+ cur_point := 0;
+ if !instr_mode then begin
+ fprintf !outchan "module %sProfiling = Profiling;; " modprefix;
+ fprintf !outchan "let %s%s_cnt = Array.make 000000000" idprefix mod_name;
+ pos_len := pos_out !outchan;
+ fprintf !outchan
+ " 0;; Profiling.counters := \
+ (\"%s\", (\"%s\", %s%s_cnt)) :: !Profiling.counters;; "
+ mod_name modes idprefix mod_name;
+ end
+
+let final_rewrite add_function =
+ to_insert := List.sort (fun x y -> compare (snd x) (snd y)) !to_insert;
+ prof_counter := 0;
+ List.iter add_function !to_insert;
+ copy (in_channel_length !inchan);
+ if !instr_mode then begin
+ let len = string_of_int !prof_counter in
+ if String.length len > 9 then raise (Profiler "too many counters");
+ seek_out !outchan (!pos_len - String.length len);
+ output_string !outchan len
+ end;
+ (* Cannot close because outchan is stdout and Format doesn't like
+ a closed stdout.
+ close_out !outchan;
+ *)
+;;
+
+let rec rewrite_patexp_list iflag l =
+ rewrite_exp_list iflag (List.map (fun x -> x.pvb_expr) l)
+
+and rewrite_cases iflag l =
+ List.iter
+ (fun pc ->
+ begin match pc.pc_guard with
+ | None -> ()
+ | Some g -> rewrite_exp iflag g
+ end;
+ rewrite_exp iflag pc.pc_rhs
+ )
+ l
+
+and rewrite_labelexp_list iflag l =
+ rewrite_exp_list iflag (List.map snd l)
+
+and rewrite_exp_list iflag l =
+ List.iter (rewrite_exp iflag) l
+
+and rewrite_exp iflag sexp =
+ if iflag then insert_profile rw_exp sexp
+ else rw_exp false sexp
+
+and rw_exp iflag sexp =
+ match sexp.pexp_desc with
+ Pexp_ident _lid -> ()
+ | Pexp_constant _cst -> ()
+
+ | Pexp_let(_, spat_sexp_list, sbody) ->
+ rewrite_patexp_list iflag spat_sexp_list;
+ rewrite_exp iflag sbody
+
+ | Pexp_function caselist ->
+ if !instr_fun then
+ rewrite_function iflag caselist
+ else
+ rewrite_cases iflag caselist
+
+ | Pexp_fun (_, _, p, e) ->
+ let l = [{pc_lhs=p; pc_guard=None; pc_rhs=e}] in
+ if !instr_fun then
+ rewrite_function iflag l
+ else
+ rewrite_cases iflag l
+
+ | Pexp_match(sarg, caselist) ->
+ rewrite_exp iflag sarg;
+ if !instr_match && not sexp.pexp_loc.loc_ghost then
+ rewrite_funmatching caselist
+ else
+ rewrite_cases iflag caselist
+
+ | Pexp_try(sbody, caselist) ->
+ rewrite_exp iflag sbody;
+ if !instr_try && not sexp.pexp_loc.loc_ghost then
+ rewrite_trymatching caselist
+ else
+ rewrite_cases iflag caselist
+
+ | Pexp_apply(sfunct, sargs) ->
+ rewrite_exp iflag sfunct;
+ rewrite_exp_list iflag (List.map snd sargs)
+
+ | Pexp_tuple sexpl ->
+ rewrite_exp_list iflag sexpl
+
+ | Pexp_construct(_, None) -> ()
+ | Pexp_construct(_, Some sarg) ->
+ rewrite_exp iflag sarg
+
+ | Pexp_variant(_, None) -> ()
+ | Pexp_variant(_, Some sarg) ->
+ rewrite_exp iflag sarg
+
+ | Pexp_record(lid_sexp_list, None) ->
+ rewrite_labelexp_list iflag lid_sexp_list
+ | Pexp_record(lid_sexp_list, Some sexp) ->
+ rewrite_exp iflag sexp;
+ rewrite_labelexp_list iflag lid_sexp_list
+
+ | Pexp_field(sarg, _) ->
+ rewrite_exp iflag sarg
+
+ | Pexp_setfield(srecord, _, snewval) ->
+ rewrite_exp iflag srecord;
+ rewrite_exp iflag snewval
+
+ | Pexp_array(sargl) ->
+ rewrite_exp_list iflag sargl
+
+ | Pexp_ifthenelse(scond, sifso, None) ->
+ rewrite_exp iflag scond;
+ rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso
+ | Pexp_ifthenelse(scond, sifso, Some sifnot) ->
+ rewrite_exp iflag scond;
+ rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso;
+ rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifnot
+
+ | Pexp_sequence(sexp1, sexp2) ->
+ rewrite_exp iflag sexp1;
+ rewrite_exp iflag sexp2
+
+ | Pexp_while(scond, sbody) ->
+ rewrite_exp iflag scond;
+ if !instr_loops && not sexp.pexp_loc.loc_ghost
+ then insert_profile rw_exp sbody
+ else rewrite_exp iflag sbody
+
+ | Pexp_for(_, slow, shigh, _, sbody) ->
+ rewrite_exp iflag slow;
+ rewrite_exp iflag shigh;
+ if !instr_loops && not sexp.pexp_loc.loc_ghost
+ then insert_profile rw_exp sbody
+ else rewrite_exp iflag sbody
+
+ | Pexp_constraint(sarg, _) | Pexp_coerce(sarg, _, _) ->
+ rewrite_exp iflag sarg
+
+ | Pexp_send (sobj, _) ->
+ rewrite_exp iflag sobj
+
+ | Pexp_new _ -> ()
+
+ | Pexp_setinstvar (_, sarg) ->
+ rewrite_exp iflag sarg
+
+ | Pexp_override l ->
+ List.iter (fun (_, sexp) -> rewrite_exp iflag sexp) l
+
+ | Pexp_letmodule (_, smod, sexp) ->
+ rewrite_mod iflag smod;
+ rewrite_exp iflag sexp
+
+ | Pexp_assert (cond) -> rewrite_exp iflag cond
+
+ | Pexp_lazy (expr) -> rewrite_exp iflag expr
+
+ | Pexp_poly (sexp, _) -> rewrite_exp iflag sexp
+
+ | Pexp_object cl ->
+ List.iter (rewrite_class_field iflag) cl.pcstr_fields
+
+ | Pexp_newtype (_, sexp) -> rewrite_exp iflag sexp
+ | Pexp_open (_ovf, _, e) -> rewrite_exp iflag e
+ | Pexp_pack (smod) -> rewrite_mod iflag smod
+ | Pexp_extension _ -> ()
+
+and rewrite_ifbody iflag ghost sifbody =
+ if !instr_if && not ghost then
+ insert_profile rw_exp sifbody
+ else
+ rewrite_exp iflag sifbody
+
+(* called only when !instr_fun *)
+and rewrite_annotate_exp_list l =
+ List.iter
+ (function
+ | {pc_guard=Some scond; pc_rhs=sbody} ->
+ insert_profile rw_exp scond;
+ insert_profile rw_exp sbody;
+ | {pc_rhs={pexp_desc = Pexp_constraint(sbody, _)}} (* let f x : t = e *)
+ -> insert_profile rw_exp sbody
+ | {pc_rhs=sexp} -> insert_profile rw_exp sexp)
+ l
+
+and rewrite_function iflag = function
+ | [{pc_lhs=_; pc_guard=None;
+ pc_rhs={pexp_desc = (Pexp_function _|Pexp_fun _)} as sexp}] ->
+ rewrite_exp iflag sexp
+ | l -> rewrite_funmatching l
+
+and rewrite_funmatching l =
+ rewrite_annotate_exp_list l
+
+and rewrite_trymatching l =
+ rewrite_annotate_exp_list l
+
+(* Rewrite a class definition *)
+
+and rewrite_class_field iflag cf =
+ match cf.pcf_desc with
+ Pcf_inherit (_, cexpr, _) -> rewrite_class_expr iflag cexpr
+ | Pcf_val (_, _, Cfk_concrete (_, sexp)) -> rewrite_exp iflag sexp
+ | Pcf_method (_, _,
+ Cfk_concrete (_, ({pexp_desc = (Pexp_function _|Pexp_fun _)}
+ as sexp))) ->
+ rewrite_exp iflag sexp
+ | Pcf_method (_, _, Cfk_concrete(_, sexp)) ->
+ let loc = cf.pcf_loc in
+ if !instr_fun && not loc.loc_ghost then insert_profile rw_exp sexp
+ else rewrite_exp iflag sexp
+ | Pcf_initializer sexp ->
+ rewrite_exp iflag sexp
+ | Pcf_method (_, _, Cfk_virtual _)
+ | Pcf_val (_, _, Cfk_virtual _)
+ | Pcf_constraint _ -> ()
+ | Pcf_attribute _ -> ()
+ | Pcf_extension _ -> ()
+
+and rewrite_class_expr iflag cexpr =
+ match cexpr.pcl_desc with
+ Pcl_constr _ -> ()
+ | Pcl_structure st ->
+ List.iter (rewrite_class_field iflag) st.pcstr_fields
+ | Pcl_fun (_, _, _, cexpr) ->
+ rewrite_class_expr iflag cexpr
+ | Pcl_apply (cexpr, exprs) ->
+ rewrite_class_expr iflag cexpr;
+ List.iter (rewrite_exp iflag) (List.map snd exprs)
+ | Pcl_let (_, spat_sexp_list, cexpr) ->
+ rewrite_patexp_list iflag spat_sexp_list;
+ rewrite_class_expr iflag cexpr
+ | Pcl_constraint (cexpr, _) ->
+ rewrite_class_expr iflag cexpr
+ | Pcl_extension _ -> ()
+
+and rewrite_class_declaration iflag cl =
+ rewrite_class_expr iflag cl.pci_expr
+
+(* Rewrite a module expression or structure expression *)
+
+and rewrite_mod iflag smod =
+ match smod.pmod_desc with
+ Pmod_ident _ -> ()
+ | Pmod_structure sstr -> List.iter (rewrite_str_item iflag) sstr
+ | Pmod_functor(_param, _smty, sbody) -> rewrite_mod iflag sbody
+ | Pmod_apply(smod1, smod2) -> rewrite_mod iflag smod1; rewrite_mod iflag smod2
+ | Pmod_constraint(smod, _smty) -> rewrite_mod iflag smod
+ | Pmod_unpack(sexp) -> rewrite_exp iflag sexp
+ | Pmod_extension _ -> ()
+
+and rewrite_str_item iflag item =
+ match item.pstr_desc with
+ Pstr_eval (exp, _attrs) -> rewrite_exp iflag exp
+ | Pstr_value(_, exps)
+ -> List.iter (fun x -> rewrite_exp iflag x.pvb_expr) exps
+ | Pstr_module x -> rewrite_mod iflag x.pmb_expr
+ (* todo: Pstr_recmodule?? *)
+ | Pstr_class classes -> List.iter (rewrite_class_declaration iflag) classes
+ | _ -> ()
+
+(* Rewrite a .ml file *)
+let rewrite_file srcfile add_function =
+ inchan := open_in_bin srcfile;
+ let lb = Lexing.from_channel !inchan in
+ Location.input_name := srcfile;
+ Location.init lb srcfile;
+ List.iter (rewrite_str_item false) (Parse.implementation lb);
+ final_rewrite add_function;
+ close_in !inchan
+
+(* Copy a non-.ml file without change *)
+let null_rewrite srcfile =
+ inchan := open_in_bin srcfile;
+ copy (in_channel_length !inchan);
+ close_in !inchan
+;;
+
+(* Setting flags from saved config *)
+let set_flags s =
+ for i = 0 to String.length s - 1 do
+ match String.get s i with
+ 'f' -> instr_fun := true
+ | 'm' -> instr_match := true
+ | 'i' -> instr_if := true
+ | 'l' -> instr_loops := true
+ | 't' -> instr_try := true
+ | 'a' -> instr_fun := true; instr_match := true;
+ instr_if := true; instr_loops := true;
+ instr_try := true
+ | _ -> ()
+ done
+
+(* Command-line options *)
+
+let modes = ref "fm"
+let dumpfile = ref "ocamlprof.dump"
+
+(* Process a file *)
+
+let process_intf_file filename = null_rewrite filename;;
+
+let process_impl_file filename =
+ let modname = Filename.basename(Filename.chop_extension filename) in
+ (* FIXME should let modname = String.capitalize modname *)
+ if !instr_mode then begin
+ (* Instrumentation mode *)
+ set_flags !modes;
+ init_rewrite !modes modname;
+ rewrite_file filename (add_incr_counter modname);
+ end else begin
+ (* Results mode *)
+ let ic = open_in_bin !dumpfile in
+ let allcounters =
+ (input_value ic : (string * (string * int array)) list) in
+ close_in ic;
+ let (modes, cv) =
+ try
+ List.assoc modname allcounters
+ with Not_found ->
+ raise(Profiler("Module " ^ modname ^ " not used in this profile."))
+ in
+ counters := cv;
+ set_flags modes;
+ init_rewrite modes modname;
+ rewrite_file filename add_val_counter;
+ end
+;;
+
+let process_anon_file filename =
+ if Filename.check_suffix filename ".ml" then
+ process_impl_file filename
+ else
+ process_intf_file filename
+;;
+
+(* Main function *)
+
+open Format
+
+let usage = "Usage: ocamlprof <options> <files>\noptions are:"
+
+let print_version () =
+ printf "ocamlprof, version %s@." Sys.ocaml_version;
+ exit 0;
+;;
+
+let print_version_num () =
+ printf "%s@." Sys.ocaml_version;
+ exit 0;
+;;
+
+let main () =
+ try
+ Warnings.parse_options false "a";
+ Arg.parse [
+ "-f", Arg.String (fun s -> dumpfile := s),
+ "<file> Use <file> as dump file (default ocamlprof.dump)";
+ "-F", Arg.String (fun s -> special_id := s),
+ "<s> Insert string <s> with the counts";
+ "-impl", Arg.String process_impl_file,
+ "<file> Process <file> as a .ml file";
+ "-instrument", Arg.Set instr_mode, " (undocumented)";
+ "-intf", Arg.String process_intf_file,
+ "<file> Process <file> as a .mli file";
+ "-m", Arg.String (fun s -> modes := s), "<flags> (undocumented)";
+ "-version", Arg.Unit print_version,
+ " Print version and exit";
+ "-vnum", Arg.Unit print_version_num,
+ " Print version number and exit";
+ ] process_anon_file usage;
+ exit 0
+ with
+ | Profiler msg ->
+ fprintf Format.err_formatter "@[%s@]@." msg;
+ exit 2
+ | exn ->
+ Location.report_exception Format.err_formatter exn
+
+let _ = main ()
diff --git a/tools/ocamlsize b/tools/ocamlsize
new file mode 100755
index 0000000000..7b419cebac
--- /dev/null
+++ b/tools/ocamlsize
@@ -0,0 +1,61 @@
+#!/usr/bin/perl
+
+#######################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 2002 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#######################################################################
+
+foreach $f (@ARGV) {
+ open(FILE, $f) || die("Cannot open $f");
+ seek(FILE, -16, 2);
+ $num_sections = do read_int();
+ read(FILE, $magic, 12);
+ seek(FILE, -16 - 8 * $num_sections, 2);
+ @secname = ();
+ @seclength = ();
+ %length = ();
+ for ($i = 0; $i < $num_sections; $i++) {
+ read(FILE, $sec, 4);
+ $secname[$i] = $sec;
+ $seclength[$i] = do read_int();
+ $length{$sec} = $seclength[$i];
+ }
+ print $f, ":\n" if ($#ARGV > 0);
+ $path =
+ $length{'RNTM'} > 0 ?
+ do read_section('RNTM') :
+ "(default runtime)\n";
+ printf ("\tcode: %-7d data: %-7d symbols: %-7d debug: %-7d\n",
+ $length{'CODE'}, $length{'DATA'},
+ $length{'SYMB'}, $length{'DBUG'});
+ printf ("\tmagic number: %s runtime system: %s",
+ $magic, $path);
+ close(FILE);
+}
+
+sub read_int {
+ read(FILE, $buff, 4) == 4 || die("Truncated bytecode file $f");
+ @int = unpack("C4", $buff);
+ return ($int[0] << 24) + ($int[1] << 16) + ($int[2] << 8) + $int[3];
+}
+
+sub read_section {
+ local ($sec) = @_;
+ local ($i, $ofs, $data);
+ for ($i = $num_sections - 1; $i >= 0; $i--) {
+ $ofs += $seclength[$i];
+ if ($secname[$i] eq $sec) {
+ seek(FILE, -16 - 8 * $num_sections - $ofs, 2);
+ read(FILE, $data, $seclength[$i]);
+ return $data;
+ }
+ }
+ return '';
+}
diff --git a/tools/primreq.ml b/tools/primreq.ml
new file mode 100644
index 0000000000..aea932f8d5
--- /dev/null
+++ b/tools/primreq.ml
@@ -0,0 +1,88 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Determine the set of C primitives required by the given .cmo and .cma
+ files *)
+
+open Config
+open Cmo_format
+
+module StringSet = Set.Make(struct type t = string let compare = compare end)
+
+let defined = ref true
+let used = ref false
+let exclude_file = ref ""
+
+let primitives = ref StringSet.empty
+
+let scan_reloc = function
+ (Reloc_primitive s, _) -> primitives := StringSet.add s !primitives
+ | _ -> ()
+
+let scan_prim s =
+ primitives := StringSet.add s !primitives
+
+let scan_info cu =
+ if !used then List.iter scan_reloc cu.cu_reloc;
+ if !defined then List.iter scan_prim cu.cu_primitives
+
+let scan_obj filename =
+ let ic = open_in_bin filename in
+ let buffer = String.create (String.length cmo_magic_number) in
+ really_input ic buffer 0 (String.length cmo_magic_number);
+ if buffer = cmo_magic_number then begin
+ let cu_pos = input_binary_int ic in
+ seek_in ic cu_pos;
+ let cu = (input_value ic : compilation_unit) in
+ close_in ic;
+ scan_info cu
+ end else
+ if buffer = cma_magic_number then begin
+ let toc_pos = input_binary_int ic in
+ seek_in ic toc_pos;
+ let toc = (input_value ic : library) in
+ close_in ic;
+ List.iter scan_info toc.lib_units
+ end else begin
+ prerr_endline "Not an object file"; exit 2
+ end
+
+let exclude filename =
+ let ic = open_in filename in
+ try
+ while true do
+ let s = input_line ic in
+ primitives := StringSet.remove s !primitives
+ done
+ with End_of_file -> close_in ic
+ | x -> close_in ic; raise x
+
+let main() =
+ Arg.parse
+ ["-used", Arg.Unit(fun () -> used := true; defined := false),
+ "show primitives referenced in the object files";
+ "-defined", Arg.Unit(fun () -> defined := true; used := false),
+ "show primitives defined in the object files (default)";
+ "-all", Arg.Unit(fun () -> defined := true; used := true),
+ "show primitives defined or referenced in the object files";
+ "-exclude", Arg.String(fun s -> exclude_file := s),
+ "<file> don't print the primitives mentioned in <file>"]
+ scan_obj
+ "Usage: primreq [options] <.cmo and .cma files>\nOptions are:";
+ if String.length !exclude_file > 0 then exclude !exclude_file;
+ StringSet.iter
+ (fun s ->
+ if s.[0] <> '%' then begin print_string s; print_newline() end)
+ !primitives;
+ exit 0
+
+let _ = main ()
diff --git a/tools/profiling.ml b/tools/profiling.ml
new file mode 100644
index 0000000000..49a84108ec
--- /dev/null
+++ b/tools/profiling.ml
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez and Francois Rouaix, INRIA Rocquencourt *)
+(* Ported to Caml Special Light by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Run-time library for profiled programs *)
+
+type profiling_counters = (string * (string * int array)) list
+
+let counters = ref ([] : profiling_counters);;
+let incr a i = a.(i) <- a.(i) + 1;;
+
+exception Bad_profile
+
+let dump_counters () =
+ let dumpfile =
+ try Sys.getenv "OCAMLPROF_DUMP" with Not_found -> "ocamlprof.dump"
+ in
+ begin try
+ let ic = open_in_bin dumpfile in
+ let prevl = (input_value ic : profiling_counters) in
+ close_in ic;
+ List.iter2
+ (fun (curname, (curmodes,curcount)) (prevname, (prevmodes,prevcount)) ->
+ if curname <> prevname
+ || curmodes <> prevmodes
+ || Array.length curcount <> Array.length prevcount
+ then raise Bad_profile)
+ !counters prevl;
+ List.iter2
+ (fun (_curname, (_,curcount)) (_prevname, (_,prevcount)) ->
+ for i = 0 to Array.length curcount - 1 do
+ curcount.(i) <- curcount.(i) + prevcount.(i)
+ done)
+ !counters prevl
+ with _ -> ()
+ end;
+ begin try
+ let oc = open_out_bin dumpfile in
+ output_value oc !counters;
+ close_out oc
+ with _ -> ()
+ end
+
+let _ = at_exit dump_counters
diff --git a/tools/profiling.mli b/tools/profiling.mli
new file mode 100644
index 0000000000..baedc24107
--- /dev/null
+++ b/tools/profiling.mli
@@ -0,0 +1,18 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez and Francois Rouaix, INRIA Rocquencourt *)
+(* Ported to OCaml by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the GNU Library General Public License, with *)
+(* the special exception on linking described in file ../LICENSE. *)
+(* *)
+(***********************************************************************)
+
+(* Run-time library for profiled programs *)
+
+val counters: (string * (string * int array)) list ref;;
+val incr: int array -> int -> unit;;
diff --git a/tools/read_cmt.ml b/tools/read_cmt.ml
new file mode 100644
index 0000000000..eacba02a50
--- /dev/null
+++ b/tools/read_cmt.ml
@@ -0,0 +1,94 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let gen_annot = ref false
+let gen_ml = ref false
+let print_info_arg = ref false
+let target_filename = ref None
+
+let arg_list = [
+ "-o", Arg.String (fun s -> target_filename := Some s),
+ " FILE (or -) : dump to file FILE (or stdout)";
+ "-annot", Arg.Set gen_annot, " : generate the corresponding .annot file";
+ "-src", Arg.Set gen_ml,
+ " : convert .cmt or .cmti back to source code (without comments)";
+ "-info", Arg.Set print_info_arg, " : print information on the file";
+ ]
+
+let arg_usage =
+ "read_cmt [OPTIONS] FILE.cmt : read FILE.cmt and print related information"
+
+let dummy_crc = String.make 32 '-'
+
+let print_info cmt =
+ let open Cmt_format in
+ Printf.printf "module name: %s\n" cmt.cmt_modname;
+ begin match cmt.cmt_annots with
+ Packed (_, list) ->
+ Printf.printf "pack: %s\n" (String.concat " " list)
+ | Implementation _ -> Printf.printf "kind: implementation\n"
+ | Interface _ -> Printf.printf "kind: interface\n"
+ | Partial_implementation _ ->
+ Printf.printf "kind: implementation with errors\n"
+ | Partial_interface _ -> Printf.printf "kind: interface with errors\n"
+ end;
+ Printf.printf "command: %s\n"
+ (String.concat " " (Array.to_list cmt.cmt_args));
+ begin match cmt.cmt_sourcefile with
+ None -> ()
+ | Some name ->
+ Printf.printf "sourcefile: %s\n" name;
+ end;
+ Printf.printf "build directory: %s\n" cmt.cmt_builddir;
+ List.iter (Printf.printf "load path: %s\n%!") cmt.cmt_loadpath;
+ begin
+ match cmt.cmt_source_digest with
+ None -> ()
+ | Some digest ->
+ Printf.printf "source digest: %s\n" (Digest.to_hex digest);
+ end;
+ begin
+ match cmt.cmt_interface_digest with
+ None -> ()
+ | Some digest ->
+ Printf.printf "interface digest: %s\n" (Digest.to_hex digest);
+ end;
+ List.iter (fun (name, crco) ->
+ let crc =
+ match crco with
+ None -> dummy_crc
+ | Some crc -> Digest.to_hex crc
+ in
+ Printf.printf "import: %s %s\n" name crc;
+ ) (List.sort compare cmt.cmt_imports);
+ Printf.printf "%!";
+ ()
+
+let _ =
+ Clflags.annotations := true;
+
+ Arg.parse arg_list (fun filename ->
+ if
+ Filename.check_suffix filename ".cmt" ||
+ Filename.check_suffix filename ".cmti"
+ then begin
+ (* init_path(); *)
+ let cmt = Cmt_format.read_cmt filename in
+ if !gen_annot then Cmt2annot.gen_annot !target_filename filename cmt;
+ if !gen_ml then Cmt2annot.gen_ml !target_filename filename cmt;
+ if !print_info_arg || not (!gen_ml || !gen_annot) then print_info cmt;
+ end else begin
+ Printf.fprintf stderr
+ "Error: the file's extension must be .cmt or .cmti.\n%!";
+ Arg.usage arg_list arg_usage
+ end
+ ) arg_usage
diff --git a/tools/scrapelabels.ml b/tools/scrapelabels.ml
new file mode 100644
index 0000000000..3927932023
--- /dev/null
+++ b/tools/scrapelabels.ml
@@ -0,0 +1,287 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jacques Garrigue, Kyoto University RIMS *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open StdLabels
+open Lexer301
+
+let input_buffer = Buffer.create 16383
+let input_function ic buf len =
+ let len = input ic buf 0 len in
+ Buffer.add_substring input_buffer buf 0 len;
+ len
+
+let output_buffer = Buffer.create 16383
+
+let modified = ref false
+
+let modules =
+ ref [ "Arg"; "BigArray"; "Buffer"; "Condition"; "Dbm"; "Digest"; "Dynlink";
+ "Event"; "Filename"; "Format"; "Gc"; "Genlex"; "Graphics";
+ "Lexing"; "Marshal"; "Mutex"; "Parsing"; "Pervasives"; "Queue";
+ "Sort"; "Stack"; "Str"; "Stream"; "Sys";
+ "Thread"; "ThreadUnix"; "Weak" ]
+
+let stdlabels = ["Array"; "List"; "String"]
+let morelabels = ["Hashtbl"; "Map"; "Set"]
+let alllabels = ref false
+let noopen = ref false
+
+exception Closing of token
+
+let convert_impl buffer =
+ let input_pos = ref 0 in
+ let copy_input stop =
+ Buffer.add_substring output_buffer (Buffer.contents input_buffer)
+ !input_pos (stop - !input_pos);
+ input_pos := stop
+ in
+ let next_token () =
+ let token = Lexer301.token buffer
+ and start = Lexing.lexeme_start buffer
+ and stop = Lexing.lexeme_end buffer in
+ match token with
+ RPAREN | RBRACKET |BARRBRACKET | GREATERRBRACKET | END
+ | RBRACE | GREATERRBRACE ->
+ raise (Closing token)
+ | EOF ->
+ raise End_of_file
+ | _ ->
+ (token, start, stop)
+ in
+ let openunix = ref None and openstd = ref None and openmore = ref None in
+ let rec may_start (token, s, e) =
+ match token with
+ LIDENT _ -> search_start (dropext (next_token ()))
+ | UIDENT m when List.mem m !modules ->
+ may_discard (dropext (next_token ()))
+ | UIDENT m ->
+ List.iter ~f:
+ (fun (set,r) ->
+ if !r = None && List.mem m ~set then r := Some true)
+ [stdlabels, openstd; ["Unix"], openunix; morelabels, openmore];
+ search_start (next_token ())
+ | _ -> search_start (token, s, e)
+
+ and dropext (token, s, e) =
+ match token with
+ DOT ->
+ let (token, s, e) = next_token () in
+ begin match token with
+ LPAREN | LBRACKET | LBRACE ->
+ process_paren (token, s, e);
+ dropext (next_token ())
+ | UIDENT _ | LIDENT _ ->
+ dropext (next_token ())
+ | _ ->
+ prerr_endline ("bad index at position " ^ string_of_int s);
+ (token, s, e)
+ end
+ | _ ->
+ (token, s, e)
+
+ and may_discard (token, s, e) =
+ match token with
+ TILDE | LABEL _ ->
+ modified := true;
+ copy_input s; input_pos := e;
+ may_discard (next_token ())
+ | _ when !alllabels ->
+ may_discard (next_token ())
+ | LPAREN | LBRACKET | LBRACKETBAR | LBRACKETLESS | BEGIN
+ | LBRACE | LBRACELESS | STRUCT | SIG | OBJECT->
+ process_paren (token, s, e);
+ may_discard (next_token ())
+ | PREFIXOP _ ->
+ may_discard (next_token ())
+ | LIDENT _ | UIDENT _ ->
+ may_discard (dropext (next_token ()))
+ | BACKQUOTE ->
+ ignore (next_token ());
+ may_discard (next_token ())
+ | INT _ | CHAR _ | STRING _ | FLOAT _ | FALSE | TRUE ->
+ may_discard (next_token ())
+ | _ ->
+ search_start (token, s, e)
+
+ and search_start (token, s, e) =
+ match token with
+ LPAREN | LBRACKET | LBRACKETBAR | LBRACKETLESS | BEGIN
+ | LBRACE | LBRACELESS | STRUCT | SIG | OBJECT ->
+ process_paren (token, s, e);
+ search_start (next_token ())
+ | EQUAL | SEMI | SEMISEMI | MINUSGREATER | LESSMINUS | COMMA
+ | IF | THEN | ELSE | WHILE | TO | DOWNTO | DO | IN | MATCH | TRY
+ | INFIXOP0 _ | INFIXOP1 _ | INFIXOP2 _ | INFIXOP3 _ | INFIXOP4 _
+ | PLUS | MINUS | MINUSDOT | STAR | LESS | GREATER
+ | OR | BARBAR | AMPERSAND | AMPERAMPER | COLONEQUAL ->
+ may_start (next_token ())
+ | OPEN ->
+ begin match next_token () with
+ | UIDENT m, _, _ ->
+ List.iter
+ ~f:(fun (set,r) -> if List.mem m ~set then r := Some false)
+ [stdlabels, openstd; ["Unix"], openunix; morelabels, openmore]
+ | _ -> ()
+ end;
+ search_start (next_token ())
+ | _ ->
+ search_start (next_token ())
+
+ and process_paren (token, s, e) =
+ try match token with
+ LPAREN | LBRACKET | LBRACKETBAR | LBRACKETLESS | BEGIN ->
+ may_start (next_token ())
+ | LBRACE | LBRACELESS | STRUCT | SIG | OBJECT ->
+ search_start (next_token ())
+ | _ ->
+ assert false
+ with Closing last ->
+ match token, last with
+ LPAREN, RPAREN
+ | (LBRACKET|LBRACKETBAR|LBRACKETLESS),
+ (RBRACKET|BARRBRACKET|GREATERRBRACKET)
+ | (BEGIN|STRUCT|SIG|OBJECT), END
+ | LBRACE, RBRACE
+ | LBRACELESS, GREATERRBRACE -> ()
+ | _ -> raise (Closing last)
+ in
+ let first = next_token () in
+ try
+ if !alllabels then may_discard first else may_start first
+ with End_of_file ->
+ copy_input (Buffer.length input_buffer);
+ if not !alllabels
+ && List.exists (fun r -> !r = Some true) [openstd; openunix; openmore]
+ then begin
+ modified := true;
+ let text = Buffer.contents output_buffer in
+ Buffer.clear output_buffer;
+ let (token, s, _) = first in
+ Buffer.add_substring output_buffer text 0 s;
+ List.iter ~f:
+ (fun (r, s) ->
+ if !r = Some true then Buffer.add_string output_buffer s)
+ [ openstd, "open StdLabels\n"; openmore, "open MoreLabels\n";
+ openunix, "module Unix = UnixLabels\n" ];
+ let sep =
+ if List.mem token [CLASS; EXTERNAL; EXCEPTION; FUNCTOR; LET;
+ MODULE; FUNCTOR; TYPE; VAL]
+ then "\n"
+ else if token = OPEN then "" else ";;\n\n"
+ in
+ Buffer.add_string output_buffer sep;
+ Buffer.add_substring output_buffer text s (String.length text - s)
+ end
+ | Closing _ ->
+ prerr_endline ("bad closing token at position " ^
+ string_of_int (Lexing.lexeme_start buffer));
+ modified := false
+
+type state = Out | Enter | In | Escape
+
+let convert_intf buffer =
+ let input_pos = ref 0 in
+ let copy_input stop =
+ Buffer.add_substring output_buffer (Buffer.contents input_buffer)
+ !input_pos (stop - !input_pos);
+ input_pos := stop
+ in
+ let last = ref (EOF, 0, 0) in
+ let state = ref Out in
+ try while true do
+ let token = Lexer301.token buffer
+ and start = Lexing.lexeme_start buffer
+ and stop = Lexing.lexeme_end buffer
+ and last_token, last_start, last_stop = !last in
+ begin match token with
+ | EXCEPTION | CONSTRAINT ->
+ state := In
+ | VAL | EXTERNAL | CLASS | METHOD | TYPE | AND ->
+ state := Enter
+ | EQUAL when !state = Enter ->
+ state := In
+ | COLON ->
+ begin match !state, last_token with
+ | In, LIDENT _ ->
+ modified := true;
+ copy_input last_start;
+ input_pos := stop
+ | Enter, _ ->
+ state := In
+ | Escape, _ ->
+ state := In
+ | _ ->
+ state := Out
+ end
+ | LBRACE | SEMI | QUESTION when !state = In ->
+ state := Escape
+ | SEMISEMI | SIG | STRUCT | END | OBJECT | OPEN | INCLUDE | MODULE ->
+ state := Out
+ | EOF -> raise End_of_file
+ | _ -> ()
+ end;
+ last := (token, start, stop)
+ done with
+ End_of_file ->
+ copy_input (Buffer.length input_buffer)
+
+let convert_file ~intf name =
+ let ic = open_in name in
+ Buffer.clear input_buffer;
+ Buffer.clear output_buffer;
+ modified := false;
+ begin
+ let convert = if intf then convert_intf else convert_impl in
+ try convert (Lexing.from_function (input_function ic)); close_in ic
+ with exn -> close_in ic; raise exn
+ end;
+ if !modified then begin
+ let backup = name ^ ".bak" in
+ if Sys.file_exists backup then Sys.remove name
+ else Sys.rename name backup;
+ let oc = open_out name in
+ Buffer.output_buffer oc output_buffer;
+ close_out oc
+ end
+ else prerr_endline ("No changes in " ^ name)
+
+let _ =
+ let files = ref [] and intf = ref false
+ and keepstd = ref false and keepmore = ref false in
+ Arg.parse
+ [ "-intf", Arg.Set intf,
+ " remove all non-optional labels from an interface;\n" ^
+ " other options are ignored";
+ "-all", Arg.Set alllabels,
+ " remove all labels, possibly including optional ones!";
+ "-keepstd", Arg.Set keepstd,
+ " keep labels for Array, List, String and Unix";
+ "-keepmore", Arg.Set keepmore,
+ " keep also labels for Hashtbl, Map and Set; implies -keepstd";
+ "-m", Arg.String (fun s -> modules := s :: !modules),
+ "<module> remove also labels for <module>";
+ "-noopen", Arg.Set noopen,
+ " do not insert `open' statements for -keepstd/-keepmore" ]
+ (fun s -> files := s :: !files)
+ ("Usage: scrapelabels <options> <source files>\n" ^
+ " Remove labels from function arguments in standard library modules.\n" ^
+ " With -intf option below, can also process interfaces.\n" ^
+ " Old files are renamed to <file>.bak if there is no backup yet.\n" ^
+ "Options are:");
+ if !keepmore then keepstd := true;
+ if not !keepstd then modules := "Unix" :: stdlabels @ !modules;
+ if not !keepmore then modules := morelabels @ !modules;
+ List.iter (List.rev !files) ~f:
+ begin fun name ->
+ prerr_endline ("Processing " ^ name);
+ Printexc.catch (convert_file ~intf:!intf) name
+ end
diff --git a/tools/setignore b/tools/setignore
new file mode 100755
index 0000000000..43d37a97dd
--- /dev/null
+++ b/tools/setignore
@@ -0,0 +1,44 @@
+#!/bin/sh
+
+#########################################################################
+# #
+# OCaml #
+# #
+# Damien Doligez, projet Gallium, INRIA Rocquencourt #
+# #
+# Copyright 2011 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+(
+ cat <<EOF
+*.o
+*.a
+*.so
+*.obj
+*.lib
+*.dll
+
+*.cm[ioxat]
+*.cmx[as]
+*.cmti
+*.annot
+
+*.result
+*.byte
+*.native
+program
+*.exe
+*.exe.manifest
+
+.depend
+.depend.nt
+.DS_Store
+
+EOF
+
+ if [ -f .ignore ]; then cat .ignore; fi
+
+) | svn propset svn:ignore -F - .
diff --git a/toplevel/expunge.ml b/toplevel/expunge.ml
new file mode 100644
index 0000000000..0d01b3290b
--- /dev/null
+++ b/toplevel/expunge.ml
@@ -0,0 +1,81 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* "Expunge" a toplevel by removing compiler modules from the global map.
+ Usage: expunge <source file> <dest file> <names of modules to keep> *)
+
+open Misc
+
+module StringSet =
+ Set.Make(struct
+ type t = string
+ let compare = compare
+ end)
+
+let is_exn =
+ let h = Hashtbl.create 64 in
+ Array.iter (fun n -> Hashtbl.add h n ()) Runtimedef.builtin_exceptions;
+ Hashtbl.mem h
+
+let to_keep = ref StringSet.empty
+
+let negate = Sys.argv.(3) = "-v"
+
+let keep =
+ if negate then fun name -> is_exn name || not (StringSet.mem name !to_keep)
+ else fun name -> is_exn name || (StringSet.mem name !to_keep)
+
+let expunge_map tbl =
+ Symtable.filter_global_map (fun id -> keep (Ident.name id)) tbl
+
+let expunge_crcs tbl =
+ List.filter (fun (unit, crc) -> keep unit) tbl
+
+let main () =
+ let input_name = Sys.argv.(1) in
+ let output_name = Sys.argv.(2) in
+ for i = (if negate then 4 else 3) to Array.length Sys.argv - 1 do
+ to_keep := StringSet.add (String.capitalize_ascii Sys.argv.(i)) !to_keep
+ done;
+ let ic = open_in_bin input_name in
+ Bytesections.read_toc ic;
+ let toc = Bytesections.toc() in
+ let pos_first_section = Bytesections.pos_first_section ic in
+ let oc =
+ open_out_gen [Open_wronly; Open_creat; Open_trunc; Open_binary] 0o777
+ output_name in
+ (* Copy the file up to the symbol section as is *)
+ seek_in ic 0;
+ copy_file_chunk ic oc pos_first_section;
+ (* Copy each section, modifying the symbol section in passing *)
+ Bytesections.init_record oc;
+ List.iter
+ (fun (name, len) ->
+ begin match name with
+ "SYMB" ->
+ let global_map = (input_value ic : Symtable.global_map) in
+ output_value oc (expunge_map global_map)
+ | "CRCS" ->
+ let crcs = (input_value ic : (string * Digest.t option) list) in
+ output_value oc (expunge_crcs crcs)
+ | _ ->
+ copy_file_chunk ic oc len
+ end;
+ Bytesections.record oc name)
+ toc;
+ (* Rewrite the toc and trailer *)
+ Bytesections.write_toc_and_trailer oc;
+ (* Done *)
+ close_in ic;
+ close_out oc
+
+let _ = Printexc.catch main (); exit 0
diff --git a/toplevel/genprintval.ml b/toplevel/genprintval.ml
new file mode 100644
index 0000000000..b8a03736a0
--- /dev/null
+++ b/toplevel/genprintval.ml
@@ -0,0 +1,573 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Jerome Vouillon, projet Cristal, INRIA Rocquencourt*)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* To print values *)
+
+open Misc
+open Format
+open Longident
+open Path
+open Types
+open Outcometree
+
+module type OBJ =
+ sig
+ type t
+ val obj : t -> 'a
+ val is_block : t -> bool
+ val tag : t -> int
+ val size : t -> int
+ val field : t -> int -> t
+ end
+
+module type EVALPATH =
+ sig
+ type valu
+ val eval_path: Env.t -> Path.t -> valu
+ exception Error
+ val same_value: valu -> valu -> bool
+ end
+
+type ('a, 'b) gen_printer =
+ | Zero of 'b
+ | Succ of ('a -> ('a, 'b) gen_printer)
+
+module type S =
+ sig
+ type t
+ val install_printer :
+ Path.t -> Types.type_expr -> (formatter -> t -> unit) -> unit
+ val install_generic_printer :
+ Path.t -> Path.t ->
+ (int -> (int -> t -> Outcometree.out_value,
+ t -> Outcometree.out_value) gen_printer) ->
+ unit
+ val install_generic_printer' :
+ Path.t -> Path.t ->
+ (formatter -> t -> unit,
+ formatter -> t -> unit) gen_printer ->
+ unit
+ val remove_printer : Path.t -> unit
+ val outval_of_untyped_exception : t -> Outcometree.out_value
+ val outval_of_value :
+ int -> int ->
+ (int -> t -> Types.type_expr -> Outcometree.out_value option) ->
+ Env.t -> t -> type_expr -> Outcometree.out_value
+ end
+
+module Make(O : OBJ)(EVP : EVALPATH with type valu = O.t) = struct
+
+ type t = O.t
+
+ module ObjTbl = Hashtbl.Make(struct
+ type t = O.t
+ let equal = (==)
+ let hash x =
+ try
+ Hashtbl.hash x
+ with exn -> 0
+ end)
+
+
+ (* Given an exception value, we cannot recover its type,
+ hence we cannot print its arguments in general.
+ Here, we do a feeble attempt to print
+ integer, string and float arguments... *)
+ let outval_of_untyped_exception_args obj start_offset =
+ if O.size obj > start_offset then begin
+ let list = ref [] in
+ for i = start_offset to O.size obj - 1 do
+ let arg = O.field obj i in
+ if not (O.is_block arg) then
+ list := Oval_int (O.obj arg : int) :: !list
+ (* Note: this could be a char or a constant constructor... *)
+ else if O.tag arg = Obj.string_tag then
+ list :=
+ Oval_string (String.escaped (O.obj arg : string)) :: !list
+ else if O.tag arg = Obj.double_tag then
+ list := Oval_float (O.obj arg : float) :: !list
+ else
+ list := Oval_constr (Oide_ident "_", []) :: !list
+ done;
+ List.rev !list
+ end
+ else []
+
+ let outval_of_untyped_exception bucket =
+ if O.tag bucket <> 0 then
+ Oval_constr (Oide_ident (O.obj (O.field bucket 0) : string), [])
+ else
+ let name = (O.obj(O.field(O.field bucket 0) 0) : string) in
+ let args =
+ if (name = "Match_failure"
+ || name = "Assert_failure"
+ || name = "Undefined_recursive_module")
+ && O.size bucket = 2
+ && O.tag(O.field bucket 1) = 0
+ then outval_of_untyped_exception_args (O.field bucket 1) 0
+ else outval_of_untyped_exception_args bucket 1 in
+ Oval_constr (Oide_ident name, args)
+
+ (* The user-defined printers. Also used for some builtin types. *)
+
+ type printer =
+ | Simple of Types.type_expr * (O.t -> Outcometree.out_value)
+ | Generic of Path.t * (int -> (int -> O.t -> Outcometree.out_value,
+ O.t -> Outcometree.out_value) gen_printer)
+
+ let printers = ref ([
+ ( Pident(Ident.create "print_int"),
+ Simple (Predef.type_int,
+ (fun x -> Oval_int (O.obj x : int))) );
+ ( Pident(Ident.create "print_float"),
+ Simple (Predef.type_float,
+ (fun x -> Oval_float (O.obj x : float))) );
+ ( Pident(Ident.create "print_char"),
+ Simple (Predef.type_char,
+ (fun x -> Oval_char (O.obj x : char))) );
+ ( Pident(Ident.create "print_string"),
+ Simple (Predef.type_string,
+ (fun x -> Oval_string (O.obj x : string))) );
+ ( Pident(Ident.create "print_int32"),
+ Simple (Predef.type_int32,
+ (fun x -> Oval_int32 (O.obj x : int32))) );
+ ( Pident(Ident.create "print_nativeint"),
+ Simple (Predef.type_nativeint,
+ (fun x -> Oval_nativeint (O.obj x : nativeint))) );
+ ( Pident(Ident.create "print_int64"),
+ Simple (Predef.type_int64,
+ (fun x -> Oval_int64 (O.obj x : int64)) ))
+ ] : (Path.t * printer) list)
+
+ let exn_printer ppf path =
+ fprintf ppf "<printer %a raised an exception>" Printtyp.path path
+
+ let out_exn path =
+ Oval_printer (fun ppf -> exn_printer ppf path)
+
+ let install_printer path ty fn =
+ let print_val ppf obj =
+ try fn ppf obj with exn -> exn_printer ppf path in
+ let printer obj = Oval_printer (fun ppf -> print_val ppf obj) in
+ printers := (path, Simple (ty, printer)) :: !printers
+
+ let install_generic_printer function_path constr_path fn =
+ printers := (function_path, Generic (constr_path, fn)) :: !printers
+
+ let install_generic_printer' function_path ty_path fn =
+ let rec build gp depth =
+ match gp with
+ | Zero fn ->
+ let out_printer obj =
+ let printer ppf =
+ try fn ppf obj with _ -> exn_printer ppf function_path in
+ Oval_printer printer in
+ Zero out_printer
+ | Succ fn ->
+ let print_val fn_arg =
+ let print_arg ppf o =
+ !Oprint.out_value ppf (fn_arg (depth+1) o) in
+ build (fn print_arg) depth in
+ Succ print_val in
+ printers := (function_path, Generic (ty_path, build fn)) :: !printers
+
+ let remove_printer path =
+ let rec remove = function
+ | [] -> raise Not_found
+ | ((p, _) as printer) :: rem ->
+ if Path.same p path then rem else printer :: remove rem in
+ printers := remove !printers
+
+ (* Print a constructor or label, giving it the same prefix as the type
+ it comes from. Attempt to omit the prefix if the type comes from
+ a module that has been opened. *)
+
+ let tree_of_qualified lookup_fun env ty_path name =
+ match ty_path with
+ | Pident id ->
+ Oide_ident name
+ | Pdot(p, s, pos) ->
+ if try
+ match (lookup_fun (Lident name) env).desc with
+ | Tconstr(ty_path', _, _) -> Path.same ty_path ty_path'
+ | _ -> false
+ with Not_found -> false
+ then Oide_ident name
+ else Oide_dot (Printtyp.tree_of_path p, name)
+ | Papply(p1, p2) ->
+ Printtyp.tree_of_path ty_path
+
+ let tree_of_constr =
+ tree_of_qualified
+ (fun lid env -> (Env.lookup_constructor lid env).cstr_res)
+
+ and tree_of_label =
+ tree_of_qualified (fun lid env -> (Env.lookup_label lid env).lbl_res)
+
+ (* An abstract type *)
+
+ let abstract_type =
+ Ctype.newty (Tconstr (Pident (Ident.create "abstract"), [], ref Mnil))
+
+ (* The main printing function *)
+
+ let outval_of_value max_steps max_depth check_depth env obj ty =
+
+ let printer_steps = ref max_steps in
+
+ let nested_values = ObjTbl.create 8 in
+ let nest_gen err f depth obj ty =
+ let repr = obj in
+ if not (O.is_block repr) then
+ f depth obj ty
+ else
+ if ObjTbl.mem nested_values repr then
+ err
+ else begin
+ ObjTbl.add nested_values repr ();
+ let ret = f depth obj ty in
+ ObjTbl.remove nested_values repr;
+ ret
+ end
+ in
+
+ let nest f = nest_gen (Oval_stuff "<cycle>") f in
+
+ let rec tree_of_val depth obj ty =
+ decr printer_steps;
+ if !printer_steps < 0 || depth < 0 then Oval_ellipsis
+ else begin
+ try
+ find_printer depth env ty obj
+ with Not_found ->
+ match (Ctype.repr ty).desc with
+ | Tvar _ | Tunivar _ ->
+ Oval_stuff "<poly>"
+ | Tarrow(_, ty1, ty2, _) ->
+ Oval_stuff "<fun>"
+ | Ttuple(ty_list) ->
+ Oval_tuple (tree_of_val_list 0 depth obj ty_list)
+ | Tconstr(path, [ty_arg], _)
+ when Path.same path Predef.path_list ->
+ if O.is_block obj then
+ match check_depth depth obj ty with
+ Some x -> x
+ | None ->
+ let rec tree_of_conses tree_list depth obj ty_arg =
+ if !printer_steps < 0 || depth < 0 then
+ Oval_ellipsis :: tree_list
+ else if O.is_block obj then
+ let tree =
+ nest tree_of_val (depth - 1) (O.field obj 0) ty_arg
+ in
+ let next_obj = O.field obj 1 in
+ nest_gen (Oval_stuff "<cycle>" :: tree :: tree_list)
+ (tree_of_conses (tree :: tree_list))
+ depth next_obj ty_arg
+ else tree_list
+ in
+ Oval_list (List.rev (tree_of_conses [] depth obj ty_arg))
+ else
+ Oval_list []
+ | Tconstr(path, [ty_arg], _)
+ when Path.same path Predef.path_array ->
+ let length = O.size obj in
+ if length > 0 then
+ match check_depth depth obj ty with
+ Some x -> x
+ | None ->
+ let rec tree_of_items tree_list i =
+ if !printer_steps < 0 || depth < 0 then
+ Oval_ellipsis :: tree_list
+ else if i < length then
+ let tree =
+ nest tree_of_val (depth - 1) (O.field obj i) ty_arg
+ in
+ tree_of_items (tree :: tree_list) (i + 1)
+ else tree_list
+ in
+ Oval_array (List.rev (tree_of_items [] 0))
+ else
+ Oval_array []
+ | Tconstr (path, [ty_arg], _)
+ when Path.same path Predef.path_lazy_t ->
+ let obj_tag = O.tag obj in
+ (* Lazy values are represented in three possible ways:
+
+ 1. a lazy thunk that is not yet forced has tag
+ Obj.lazy_tag
+
+ 2. a lazy thunk that has just been forced has tag
+ Obj.forward_tag; its first field is the forced
+ result, which we can print
+
+ 3. when the GC moves a forced trunk with forward_tag,
+ or when a thunk is directly created from a value,
+ we get a third representation where the value is
+ directly exposed, without the Obj.forward_tag
+ (if its own tag is not ambiguous, that is neither
+ lazy_tag nor forward_tag)
+
+ Note that using Lazy.is_val and Lazy.force would be
+ unsafe, because they use the Obj.* functions rather
+ than the O.* functions of the functor argument, and
+ would thus crash if called from the toplevel
+ (debugger/printval instantiates Genprintval.Make with
+ an Obj module talking over a socket).
+ *)
+ if obj_tag = Obj.lazy_tag then Oval_stuff "<lazy>"
+ else begin
+ let forced_obj =
+ if obj_tag = Obj.forward_tag then O.field obj 0 else obj
+ in
+ (* calling oneself recursively on forced_obj risks
+ having a false positive for cycle detection;
+ indeed, in case (3) above, the value is stored
+ as-is instead of being wrapped in a forward
+ pointer. It means that, for (lazy "foo"), we have
+ forced_obj == obj
+ and it is easy to wrongly print (lazy <cycle>) in such
+ a case (PR#6669).
+
+ Unfortunately, there is a corner-case that *is*
+ a real cycle: using -rectypes one can define
+ let rec x = lazy x
+ which creates a Forward_tagged block that points to
+ itself. For this reason, we still "nest"
+ (detect head cycles) on forward tags.
+ *)
+ let v =
+ if obj_tag = Obj.forward_tag
+ then nest tree_of_val depth forced_obj ty_arg
+ else tree_of_val depth forced_obj ty_arg
+ in
+ Oval_constr (Oide_ident "lazy", [v])
+ end
+ | Tconstr(path, ty_list, _) -> begin
+ try
+ let decl = Env.find_type path env in
+ match decl with
+ | {type_kind = Type_abstract; type_manifest = None} ->
+ Oval_stuff "<abstr>"
+ | {type_kind = Type_abstract; type_manifest = Some body} ->
+ tree_of_val depth obj
+ (try Ctype.apply env decl.type_params body ty_list with
+ Ctype.Cannot_apply -> abstract_type)
+ | {type_kind = Type_variant constr_list} ->
+ let tag =
+ if O.is_block obj
+ then Cstr_block(O.tag obj)
+ else Cstr_constant(O.obj obj) in
+ let {cd_id;cd_args;cd_res} =
+ Datarepr.find_constr_by_tag tag constr_list in
+ let type_params =
+ match cd_res with
+ Some t ->
+ begin match (Ctype.repr t).desc with
+ Tconstr (_,params,_) ->
+ params
+ | _ -> assert false end
+ | None -> decl.type_params
+ in
+ begin
+ match cd_args with
+ | Cstr_tuple l ->
+ let ty_args =
+ List.map
+ (function ty ->
+ try Ctype.apply env type_params ty ty_list with
+ Ctype.Cannot_apply -> abstract_type)
+ l
+ in
+ tree_of_constr_with_args (tree_of_constr env path)
+ (Ident.name cd_id) false 0 depth obj
+ ty_args
+ | Cstr_record lbls ->
+ let r =
+ tree_of_record_fields depth
+ env path type_params ty_list
+ lbls 0 obj
+ in
+ Oval_constr(tree_of_constr env path
+ (Ident.name cd_id),
+ [ r ])
+ end
+ | {type_kind = Type_record(lbl_list, rep)} ->
+ begin match check_depth depth obj ty with
+ Some x -> x
+ | None ->
+ let pos =
+ match rep with
+ | Record_extension -> 1
+ | _ -> 0
+ in
+ tree_of_record_fields depth
+ env path decl.type_params ty_list
+ lbl_list pos obj
+ end
+ | {type_kind = Type_open} ->
+ tree_of_extension path depth obj
+ with
+ Not_found -> (* raised by Env.find_type *)
+ Oval_stuff "<abstr>"
+ | Datarepr.Constr_not_found -> (* raised by find_constr_by_tag *)
+ Oval_stuff "<unknown constructor>"
+ end
+ | Tvariant row ->
+ let row = Btype.row_repr row in
+ if O.is_block obj then
+ let tag : int = O.obj (O.field obj 0) in
+ let rec find = function
+ | (l, f) :: fields ->
+ if Btype.hash_variant l = tag then
+ match Btype.row_field_repr f with
+ | Rpresent(Some ty) | Reither(_,[ty],_,_) ->
+ let args =
+ nest tree_of_val (depth - 1) (O.field obj 1) ty
+ in
+ Oval_variant (l, Some args)
+ | _ -> find fields
+ else find fields
+ | [] -> Oval_stuff "<variant>" in
+ find row.row_fields
+ else
+ let tag : int = O.obj obj in
+ let rec find = function
+ | (l, _) :: fields ->
+ if Btype.hash_variant l = tag then
+ Oval_variant (l, None)
+ else find fields
+ | [] -> Oval_stuff "<variant>" in
+ find row.row_fields
+ | Tobject (_, _) ->
+ Oval_stuff "<obj>"
+ | Tsubst ty ->
+ tree_of_val (depth - 1) obj ty
+ | Tfield(_, _, _, _) | Tnil | Tlink _ ->
+ fatal_error "Printval.outval_of_value"
+ | Tpoly (ty, _) ->
+ tree_of_val (depth - 1) obj ty
+ | Tpackage _ ->
+ Oval_stuff "<module>"
+ end
+
+ and tree_of_record_fields depth env path type_params ty_list
+ lbl_list pos obj =
+ let rec tree_of_fields pos = function
+ | [] -> []
+ | {ld_id; ld_type} :: remainder ->
+ let ty_arg =
+ try
+ Ctype.apply env type_params ld_type
+ ty_list
+ with
+ Ctype.Cannot_apply -> abstract_type in
+ let name = Ident.name ld_id in
+ (* PR#5722: print full module path only
+ for first record field *)
+ let lid =
+ if pos = 0 then tree_of_label env path name
+ else Oide_ident name
+ and v =
+ nest tree_of_val (depth - 1) (O.field obj pos)
+ ty_arg
+ in
+ (lid, v) :: tree_of_fields (pos + 1) remainder
+ in
+ Oval_record (tree_of_fields pos lbl_list)
+
+ and tree_of_val_list start depth obj ty_list =
+ let rec tree_list i = function
+ | [] -> []
+ | ty :: ty_list ->
+ let tree = nest tree_of_val (depth - 1) (O.field obj i) ty in
+ tree :: tree_list (i + 1) ty_list in
+ tree_list start ty_list
+
+ and tree_of_constr_with_args
+ tree_of_cstr cstr_name inlined start depth obj ty_args =
+ let lid = tree_of_cstr cstr_name in
+ let args =
+ if inlined then
+ match ty_args with
+ | [ty] -> [ tree_of_val (depth - 1) obj ty ]
+ | _ -> assert false
+ else
+ tree_of_val_list start depth obj ty_args
+ in
+ Oval_constr (lid, args)
+
+ and tree_of_extension type_path depth bucket =
+ let slot =
+ if O.tag bucket <> 0 then bucket
+ else O.field bucket 0
+ in
+ let name = (O.obj(O.field slot 0) : string) in
+ let lid = Longident.parse name in
+ try
+ (* Attempt to recover the constructor description for the exn
+ from its name *)
+ let cstr = Env.lookup_constructor lid env in
+ let path =
+ match cstr.cstr_tag with
+ Cstr_extension(p, _) -> p
+ | _ -> raise Not_found
+ in
+ (* Make sure this is the right exception and not an homonym,
+ by evaluating the exception found and comparing with the
+ identifier contained in the exception bucket *)
+ if not (EVP.same_value slot (EVP.eval_path env path))
+ then raise Not_found;
+ tree_of_constr_with_args
+ (fun x -> Oide_ident x) name (cstr.cstr_inlined <> None)
+ 1 depth bucket
+ cstr.cstr_args
+ with Not_found | EVP.Error ->
+ match check_depth depth bucket ty with
+ Some x -> x
+ | None when Path.same type_path Predef.path_exn->
+ outval_of_untyped_exception bucket
+ | None ->
+ Oval_stuff "<extension>"
+
+ and find_printer depth env ty =
+ let rec find = function
+ | [] -> raise Not_found
+ | (name, Simple (sch, printer)) :: remainder ->
+ if Ctype.moregeneral env false sch ty
+ then printer
+ else find remainder
+ | (name, Generic (path, fn)) :: remainder ->
+ begin match (Ctype.expand_head env ty).desc with
+ | Tconstr (p, args, _) when Path.same p path ->
+ begin try apply_generic_printer path (fn depth) args
+ with _ -> (fun obj -> out_exn path) end
+ | _ -> find remainder end in
+ find !printers
+
+ and apply_generic_printer path printer args =
+ match (printer, args) with
+ | (Zero fn, []) -> (fun (obj : O.t)-> try fn obj with _ -> out_exn path)
+ | (Succ fn, arg :: args) ->
+ let printer = fn (fun depth obj -> tree_of_val depth obj arg) in
+ apply_generic_printer path printer args
+ | _ ->
+ (fun obj ->
+ let printer ppf =
+ fprintf ppf "<internal error: incorrect arity for '%a'>"
+ Printtyp.path path in
+ Oval_printer printer)
+
+
+ in nest tree_of_val max_depth obj ty
+
+end
diff --git a/toplevel/genprintval.mli b/toplevel/genprintval.mli
new file mode 100644
index 0000000000..1c2ec471b8
--- /dev/null
+++ b/toplevel/genprintval.mli
@@ -0,0 +1,67 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Printing of values *)
+
+open Types
+open Format
+
+module type OBJ =
+ sig
+ type t
+ val obj : t -> 'a
+ val is_block : t -> bool
+ val tag : t -> int
+ val size : t -> int
+ val field : t -> int -> t
+ end
+
+module type EVALPATH =
+ sig
+ type valu
+ val eval_path: Env.t -> Path.t -> valu
+ exception Error
+ val same_value: valu -> valu -> bool
+ end
+
+type ('a, 'b) gen_printer =
+ | Zero of 'b
+ | Succ of ('a -> ('a, 'b) gen_printer)
+
+module type S =
+ sig
+ type t
+ val install_printer :
+ Path.t -> Types.type_expr -> (formatter -> t -> unit) -> unit
+ val install_generic_printer :
+ Path.t -> Path.t ->
+ (int -> (int -> t -> Outcometree.out_value,
+ t -> Outcometree.out_value) gen_printer) ->
+ unit
+ val install_generic_printer' :
+ Path.t -> Path.t ->
+ (formatter -> t -> unit,
+ formatter -> t -> unit) gen_printer ->
+ unit
+ (** [install_generic_printer' function_path constructor_path printer]
+ function_path is used to remove the printer. *)
+
+ val remove_printer : Path.t -> unit
+ val outval_of_untyped_exception : t -> Outcometree.out_value
+ val outval_of_value :
+ int -> int ->
+ (int -> t -> Types.type_expr -> Outcometree.out_value option) ->
+ Env.t -> t -> type_expr -> Outcometree.out_value
+ end
+
+module Make(O : OBJ)(EVP : EVALPATH with type valu = O.t) :
+ (S with type t = O.t)
diff --git a/toplevel/opttopdirs.ml b/toplevel/opttopdirs.ml
new file mode 100644
index 0000000000..9741d17bea
--- /dev/null
+++ b/toplevel/opttopdirs.ml
@@ -0,0 +1,186 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Toplevel directives *)
+
+open Format
+open Misc
+open Longident
+open Types
+open Opttoploop
+
+(* The standard output formatter *)
+let std_out = std_formatter
+
+(* To quit *)
+
+let dir_quit () = exit 0
+
+let _ = Hashtbl.add directive_table "quit" (Directive_none dir_quit)
+
+(* To add a directory to the load path *)
+
+let dir_directory s =
+ let d = expand_directory Config.standard_library s in
+ Config.load_path := d :: !Config.load_path
+
+let _ = Hashtbl.add directive_table "directory" (Directive_string dir_directory)
+let _ = Hashtbl.add directive_table "show_dirs"
+ (Directive_none
+ (fun () ->
+ List.iter print_endline !Config.load_path
+ ))
+
+(* To change the current directory *)
+
+let dir_cd s = Sys.chdir s
+
+let _ = Hashtbl.add directive_table "cd" (Directive_string dir_cd)
+
+(* Load in-core a .cmxs file *)
+
+let load_file ppf name0 =
+ let name =
+ try Some (find_in_path !Config.load_path name0)
+ with Not_found -> None in
+ match name with
+ | None -> fprintf ppf "File not found: %s@." name0; false
+ | Some name ->
+ let fn,tmp =
+ if Filename.check_suffix name ".cmx" || Filename.check_suffix name ".cmxa"
+ then
+ let cmxs = Filename.temp_file "caml" ".cmxs" in
+ Asmlink.link_shared ppf [name] cmxs;
+ cmxs,true
+ else
+ name,false in
+
+ let success =
+ (* The Dynlink interface does not allow us to distinguish between
+ a Dynlink.Error exceptions raised in the loaded modules
+ or a genuine error during dynlink... *)
+ try Dynlink.loadfile fn; true
+ with
+ | Dynlink.Error err ->
+ fprintf ppf "Error while loading %s: %s.@."
+ name (Dynlink.error_message err);
+ false
+ | exn ->
+ print_exception_outcome ppf exn;
+ false
+ in
+ if tmp then (try Sys.remove fn with Sys_error _ -> ());
+ success
+
+
+let dir_load ppf name = ignore (load_file ppf name)
+
+let _ = Hashtbl.add directive_table "load" (Directive_string (dir_load std_out))
+
+(* Load commands from a file *)
+
+let dir_use ppf name = ignore(Opttoploop.use_file ppf name)
+
+let _ = Hashtbl.add directive_table "use" (Directive_string (dir_use std_out))
+
+(* Install, remove a printer *)
+
+type 'a printer_type_new = Format.formatter -> 'a -> unit
+type 'a printer_type_old = 'a -> unit
+
+let match_printer_type ppf desc typename =
+ let (printer_type, _) =
+ try
+ Env.lookup_type (Ldot(Lident "Topdirs", typename)) !toplevel_env
+ with Not_found ->
+ fprintf ppf "Cannot find type Topdirs.%s.@." typename;
+ raise Exit in
+ Ctype.init_def(Ident.current_time());
+ Ctype.begin_def();
+ let ty_arg = Ctype.newvar() in
+ Ctype.unify !toplevel_env
+ (Ctype.newconstr printer_type [ty_arg])
+ (Ctype.instance_def desc.val_type);
+ Ctype.end_def();
+ Ctype.generalize ty_arg;
+ ty_arg
+
+let find_printer_type ppf lid =
+ try
+ let (path, desc) = Env.lookup_value lid !toplevel_env in
+ let (ty_arg, is_old_style) =
+ try
+ (match_printer_type ppf desc "printer_type_new", false)
+ with Ctype.Unify _ ->
+ (match_printer_type ppf desc "printer_type_old", true) in
+ (ty_arg, path, is_old_style)
+ with
+ | Not_found ->
+ fprintf ppf "Unbound value %a.@." Printtyp.longident lid;
+ raise Exit
+ | Ctype.Unify _ ->
+ fprintf ppf "%a has a wrong type for a printing function.@."
+ Printtyp.longident lid;
+ raise Exit
+
+let dir_install_printer ppf lid =
+ try
+ let (ty_arg, path, is_old_style) = find_printer_type ppf lid in
+ let v = eval_path path in
+ let print_function =
+ if is_old_style then
+ (fun formatter repr -> Obj.obj v (Obj.obj repr))
+ else
+ (fun formatter repr -> Obj.obj v formatter (Obj.obj repr)) in
+ install_printer path ty_arg print_function
+ with Exit -> ()
+
+let dir_remove_printer ppf lid =
+ try
+ let (ty_arg, path, is_old_style) = find_printer_type ppf lid in
+ begin try
+ remove_printer path
+ with Not_found ->
+ fprintf ppf "No printer named %a.@." Printtyp.longident lid
+ end
+ with Exit -> ()
+
+let _ = Hashtbl.add directive_table "install_printer"
+ (Directive_ident (dir_install_printer std_out))
+let _ = Hashtbl.add directive_table "remove_printer"
+ (Directive_ident (dir_remove_printer std_out))
+
+let parse_warnings ppf iserr s =
+ try Warnings.parse_options iserr s
+ with Arg.Bad err -> fprintf ppf "%s.@." err
+
+let _ =
+(* Control the printing of values *)
+
+ Hashtbl.add directive_table "print_depth"
+ (Directive_int(fun n -> max_printer_depth := n));
+ Hashtbl.add directive_table "print_length"
+ (Directive_int(fun n -> max_printer_steps := n));
+
+(* Set various compiler flags *)
+
+ Hashtbl.add directive_table "labels"
+ (Directive_bool(fun b -> Clflags.classic := not b));
+
+ Hashtbl.add directive_table "principal"
+ (Directive_bool(fun b -> Clflags.principal := b));
+
+ Hashtbl.add directive_table "warnings"
+ (Directive_string (parse_warnings std_out false));
+
+ Hashtbl.add directive_table "warn_error"
+ (Directive_string (parse_warnings std_out true))
diff --git a/toplevel/opttopdirs.mli b/toplevel/opttopdirs.mli
new file mode 100644
index 0000000000..8caf71d443
--- /dev/null
+++ b/toplevel/opttopdirs.mli
@@ -0,0 +1,29 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The toplevel directives. *)
+
+open Format
+
+val dir_quit : unit -> unit
+val dir_directory : string -> unit
+val dir_cd : string -> unit
+val dir_load : formatter -> string -> unit
+val dir_use : formatter -> string -> unit
+val dir_install_printer : formatter -> Longident.t -> unit
+val dir_remove_printer : formatter -> Longident.t -> unit
+
+type 'a printer_type_new = Format.formatter -> 'a -> unit
+type 'a printer_type_old = 'a -> unit
+
+(* For topmain.ml. Maybe shouldn't be there *)
+val load_file : formatter -> string -> bool
diff --git a/toplevel/opttoploop.ml b/toplevel/opttoploop.ml
new file mode 100644
index 0000000000..ab73a51e34
--- /dev/null
+++ b/toplevel/opttoploop.ml
@@ -0,0 +1,464 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The interactive toplevel loop *)
+
+open Path
+open Format
+open Config
+open Misc
+open Parsetree
+open Types
+open Typedtree
+open Outcometree
+
+type res = Ok of Obj.t | Err of string
+type evaluation_outcome = Result of Obj.t | Exception of exn
+
+let _dummy = (Ok (Obj.magic 0), Err "")
+
+external ndl_run_toplevel: string -> string -> res
+ = "caml_natdynlink_run_toplevel"
+external ndl_loadsym: string -> Obj.t = "caml_natdynlink_loadsym"
+
+let global_symbol id =
+ let sym = Compilenv.symbol_for_global id in
+ try ndl_loadsym sym
+ with _ -> fatal_error ("Opttoploop.global_symbol " ^ (Ident.unique_name id))
+
+let need_symbol sym =
+ try ignore (ndl_loadsym sym); false
+ with _ -> true
+
+let dll_run dll entry =
+ match (try Result (Obj.magic (ndl_run_toplevel dll entry))
+ with exn -> Exception exn)
+ with
+ | Exception _ as r -> r
+ | Result r ->
+ match Obj.magic r with
+ | Ok x -> Result x
+ | Err s -> fatal_error ("Opttoploop.dll_run " ^ s)
+
+
+type directive_fun =
+ | Directive_none of (unit -> unit)
+ | Directive_string of (string -> unit)
+ | Directive_int of (int -> unit)
+ | Directive_ident of (Longident.t -> unit)
+ | Directive_bool of (bool -> unit)
+
+
+(* Return the value referred to by a path *)
+
+let toplevel_value id =
+ let (glb,pos) = Translmod.nat_toplevel_name id in
+ (Obj.magic (global_symbol glb)).(pos)
+
+let rec eval_path = function
+ | Pident id ->
+ if Ident.persistent id || Ident.global id
+ then global_symbol id
+ else toplevel_value id
+ | Pdot(p, s, pos) ->
+ Obj.field (eval_path p) pos
+ | Papply(p1, p2) ->
+ fatal_error "Toploop.eval_path"
+
+(* To print values *)
+
+module EvalPath = struct
+ type valu = Obj.t
+ exception Error
+ let eval_path p = try eval_path p with _ -> raise Error
+ let same_value v1 v2 = (v1 == v2)
+end
+
+module Printer = Genprintval.Make(Obj)(EvalPath)
+
+let max_printer_depth = ref 100
+let max_printer_steps = ref 300
+
+let print_out_value = Oprint.out_value
+let print_out_type = Oprint.out_type
+let print_out_class_type = Oprint.out_class_type
+let print_out_module_type = Oprint.out_module_type
+let print_out_type_extension = Oprint.out_type_extension
+let print_out_sig_item = Oprint.out_sig_item
+let print_out_signature = Oprint.out_signature
+let print_out_phrase = Oprint.out_phrase
+
+let print_untyped_exception ppf obj =
+ !print_out_value ppf (Printer.outval_of_untyped_exception obj)
+let outval_of_value env obj ty =
+ Printer.outval_of_value !max_printer_steps !max_printer_depth
+ (fun _ _ _ -> None) env obj ty
+let print_value env obj ppf ty =
+ !print_out_value ppf (outval_of_value env obj ty)
+
+let install_printer = Printer.install_printer
+let remove_printer = Printer.remove_printer
+
+(* Hooks for parsing functions *)
+
+let parse_toplevel_phrase = ref Parse.toplevel_phrase
+let parse_use_file = ref Parse.use_file
+let print_location = Location.print_error (* FIXME change back to print *)
+let print_error = Location.print_error
+let print_warning = Location.print_warning
+let input_name = Location.input_name
+
+(* Hooks for initialization *)
+
+let toplevel_startup_hook = ref (fun () -> ())
+
+(* Load in-core and execute a lambda term *)
+
+let phrase_seqid = ref 0
+let phrase_name = ref "TOP"
+
+let load_lambda ppf (size, lam) =
+ if !Clflags.dump_rawlambda then fprintf ppf "%a@." Printlambda.lambda lam;
+ let slam = Simplif.simplify_lambda lam in
+ if !Clflags.dump_lambda then fprintf ppf "%a@." Printlambda.lambda slam;
+
+ let dll =
+ if !Clflags.keep_asm_file then !phrase_name ^ ext_dll
+ else Filename.temp_file ("caml" ^ !phrase_name) ext_dll
+ in
+ let fn = Filename.chop_extension dll in
+ Asmgen.compile_implementation ~toplevel:need_symbol fn ppf (size, slam);
+ Asmlink.call_linker_shared [fn ^ ext_obj] dll;
+ Sys.remove (fn ^ ext_obj);
+
+ let dll =
+ if Filename.is_implicit dll
+ then Filename.concat (Sys.getcwd ()) dll
+ else dll in
+ let res = dll_run dll !phrase_name in
+ (try Sys.remove dll with Sys_error _ -> ());
+ (* note: under windows, cannot remove a loaded dll
+ (should remember the handles, close them in at_exit, and then remove
+ files) *)
+ res
+
+(* Print the outcome of an evaluation *)
+
+let rec pr_item env = function
+ | Sig_value(id, decl) :: rem ->
+ let tree = Printtyp.tree_of_value_description id decl in
+ let valopt =
+ match decl.val_kind with
+ | Val_prim _ -> None
+ | _ ->
+ let v =
+ outval_of_value env (toplevel_value id)
+ decl.val_type
+ in
+ Some v
+ in
+ Some (tree, valopt, rem)
+ | Sig_type(id, _, _) :: rem when Btype.is_row_name (Ident.name id) ->
+ pr_item env rem
+ | Sig_type(id, decl, rs) :: rem ->
+ let tree = Printtyp.tree_of_type_declaration id decl rs in
+ Some (tree, None, rem)
+ | Sig_typext(id, ext, es) :: rem ->
+ let tree = Printtyp.tree_of_extension_constructor id ext es in
+ Some (tree, None, rem)
+ | Sig_module(id, mty, rs) :: rem ->
+ let tree = Printtyp.tree_of_module id mty rs in
+ Some (tree, None, rem)
+ | Sig_modtype(id, decl) :: rem ->
+ let tree = Printtyp.tree_of_modtype_declaration id decl in
+ Some (tree, None, rem)
+ | Sig_class(id, decl, rs) :: cltydecl :: tydecl1 :: tydecl2 :: rem ->
+ let tree = Printtyp.tree_of_class_declaration id decl rs in
+ Some (tree, None, rem)
+ | Sig_class_type(id, decl, rs) :: tydecl1 :: tydecl2 :: rem ->
+ let tree = Printtyp.tree_of_cltype_declaration id decl rs in
+ Some (tree, None, rem)
+ | _ -> None
+
+let rec item_list env = function
+ | [] -> []
+ | items ->
+ match pr_item env items with
+ | None -> []
+ | Some (tree, valopt, items) -> (tree, valopt) :: item_list env items
+
+(* The current typing environment for the toplevel *)
+
+let toplevel_env = ref Env.empty
+
+(* Print an exception produced by an evaluation *)
+
+let print_out_exception ppf exn outv =
+ !print_out_phrase ppf (Ophr_exception (exn, outv))
+
+let print_exception_outcome ppf exn =
+ if exn = Out_of_memory then Gc.full_major ();
+ let outv = outval_of_value !toplevel_env (Obj.repr exn) Predef.type_exn in
+ print_out_exception ppf exn outv
+
+(* The table of toplevel directives.
+ Filled by functions from module topdirs. *)
+
+let directive_table = (Hashtbl.create 13 : (string, directive_fun) Hashtbl.t)
+
+(* Execute a toplevel phrase *)
+
+let execute_phrase print_outcome ppf phr =
+ match phr with
+ | Ptop_def sstr ->
+ let oldenv = !toplevel_env in
+ incr phrase_seqid;
+ phrase_name := Printf.sprintf "TOP%i" !phrase_seqid;
+ Compilenv.reset ?packname:None !phrase_name;
+ Typecore.reset_delayed_checks ();
+ let (str, sg, newenv) = Typemod.type_structure oldenv sstr Location.none
+ in
+ if !Clflags.dump_typedtree then Printtyped.implementation ppf str;
+ Typecore.force_delayed_checks ();
+ let res = Translmod.transl_store_phrases !phrase_name str in
+ Warnings.check_fatal ();
+ begin try
+ toplevel_env := newenv;
+ let res = load_lambda ppf res in
+ let out_phr =
+ match res with
+ | Result v ->
+ Compilenv.record_global_approx_toplevel ();
+ if print_outcome then
+ match str.str_items with
+ | [ {str_desc = Tstr_eval exp} ] ->
+ let outv = outval_of_value newenv v exp.exp_type in
+ let ty = Printtyp.tree_of_type_scheme exp.exp_type in
+ Ophr_eval (outv, ty)
+ | [] -> Ophr_signature []
+ | _ ->
+ Ophr_signature (item_list newenv
+ (Typemod.simplify_signature sg))
+
+ else Ophr_signature []
+ | Exception exn ->
+ toplevel_env := oldenv;
+ if exn = Out_of_memory then Gc.full_major();
+ let outv =
+ outval_of_value !toplevel_env (Obj.repr exn) Predef.type_exn
+ in
+ Ophr_exception (exn, outv)
+ in
+ !print_out_phrase ppf out_phr;
+ begin match out_phr with
+ | Ophr_eval (_, _) | Ophr_signature _ -> true
+ | Ophr_exception _ -> false
+ end
+ with x ->
+ toplevel_env := oldenv; raise x
+ end
+ | Ptop_dir(dir_name, dir_arg) ->
+ try
+ match (Hashtbl.find directive_table dir_name, dir_arg) with
+ | (Directive_none f, Pdir_none) -> f (); true
+ | (Directive_string f, Pdir_string s) -> f s; true
+ | (Directive_int f, Pdir_int n) -> f n; true
+ | (Directive_ident f, Pdir_ident lid) -> f lid; true
+ | (Directive_bool f, Pdir_bool b) -> f b; true
+ | (_, _) ->
+ fprintf ppf "Wrong type of argument for directive `%s'.@." dir_name;
+ false
+ with Not_found ->
+ fprintf ppf "Unknown directive `%s'.@." dir_name;
+ false
+
+(* Temporary assignment to a reference *)
+
+let protect r newval body =
+ let oldval = !r in
+ try
+ r := newval;
+ let res = body() in
+ r := oldval;
+ res
+ with x ->
+ r := oldval;
+ raise x
+
+(* Read and execute commands from a file *)
+
+let use_print_results = ref true
+
+let use_file ppf name =
+ try
+ let (filename, ic, must_close) =
+ if name = "" then
+ ("(stdin)", stdin, false)
+ else begin
+ let filename = find_in_path !Config.load_path name in
+ let ic = open_in_bin filename in
+ (filename, ic, true)
+ end
+ in
+ let lb = Lexing.from_channel ic in
+ Location.init lb filename;
+ (* Skip initial #! line if any *)
+ Lexer.skip_sharp_bang lb;
+ let success =
+ protect Location.input_name filename (fun () ->
+ try
+ List.iter
+ (fun ph ->
+ if !Clflags.dump_parsetree then Printast.top_phrase ppf ph;
+ if !Clflags.dump_source then Pprintast.top_phrase ppf ph;
+ if not (execute_phrase !use_print_results ppf ph) then raise Exit)
+ (!parse_use_file lb);
+ true
+ with
+ | Exit -> false
+ | Sys.Break -> fprintf ppf "Interrupted.@."; false
+ | x -> Location.report_exception ppf x; false) in
+ if must_close then close_in ic;
+ success
+ with Not_found -> fprintf ppf "Cannot find file %s.@." name; false
+
+let use_silently ppf name =
+ protect use_print_results false (fun () -> use_file ppf name)
+
+(* Reading function for interactive use *)
+
+let first_line = ref true
+let got_eof = ref false;;
+
+let read_input_default prompt buffer len =
+ output_string Pervasives.stdout prompt; flush Pervasives.stdout;
+ let i = ref 0 in
+ try
+ while true do
+ if !i >= len then raise Exit;
+ let c = input_char stdin in
+ buffer.[!i] <- c;
+ incr i;
+ if c = '\n' then raise Exit;
+ done;
+ (!i, false)
+ with
+ | End_of_file ->
+ (!i, true)
+ | Exit ->
+ (!i, false)
+
+let read_interactive_input = ref read_input_default
+
+let refill_lexbuf buffer len =
+ if !got_eof then (got_eof := false; 0) else begin
+ let prompt =
+ if !Clflags.noprompt then ""
+ else if !first_line then "# "
+ else if !Clflags.nopromptcont then ""
+ else if Lexer.in_comment () then "* "
+ else " "
+ in
+ first_line := false;
+ let (len, eof) = !read_interactive_input prompt buffer len in
+ if eof then begin
+ Location.echo_eof ();
+ if len > 0 then got_eof := true;
+ len
+ end else
+ len
+ end
+
+(* Toplevel initialization. Performed here instead of at the
+ beginning of loop() so that user code linked in with ocamlmktop
+ can call directives from Topdirs. *)
+
+let _ =
+ Sys.interactive := true;
+ Dynlink.init ();
+ Compmisc.init_path true;
+ Clflags.dlcode := true;
+ ()
+
+let load_ocamlinit ppf =
+ if !Clflags.noinit then ()
+ else match !Clflags.init_file with
+ | Some f -> if Sys.file_exists f then ignore (use_silently ppf f)
+ else fprintf ppf "Init file not found: \"%s\".@." f
+ | None ->
+ if Sys.file_exists ".ocamlinit" then ignore (use_silently ppf ".ocamlinit")
+ else try
+ let home_init = Filename.concat (Sys.getenv "HOME") ".ocamlinit" in
+ if Sys.file_exists home_init then ignore (use_silently ppf home_init)
+ with Not_found -> ()
+;;
+
+let set_paths () =
+ (* Add whatever -I options have been specified on the command line,
+ but keep the directories that user code linked in with ocamlmktop
+ may have added to load_path. *)
+ load_path := !load_path @ [Filename.concat Config.standard_library "camlp4"];
+ load_path := "" :: (List.rev !Clflags.include_dirs @ !load_path);
+ ()
+
+let initialize_toplevel_env () =
+ toplevel_env := Compmisc.initial_env()
+
+(* The interactive loop *)
+
+exception PPerror
+
+let loop ppf =
+ fprintf ppf " OCaml version %s - native toplevel@.@." Config.version;
+ initialize_toplevel_env ();
+ let lb = Lexing.from_function refill_lexbuf in
+ Location.init lb "//toplevel//";
+ Location.input_name := "//toplevel//";
+ Location.input_lexbuf := Some lb;
+ Sys.catch_break true;
+ load_ocamlinit ppf;
+ while true do
+ let snap = Btype.snapshot () in
+ try
+ Lexing.flush_input lb;
+ Location.reset();
+ first_line := true;
+ let phr = try !parse_toplevel_phrase lb with Exit -> raise PPerror in
+ if !Clflags.dump_parsetree then Printast.top_phrase ppf phr;
+ if !Clflags.dump_source then Pprintast.top_phrase ppf phr;
+ ignore(execute_phrase true ppf phr)
+ with
+ | End_of_file -> exit 0
+ | Sys.Break -> fprintf ppf "Interrupted.@."; Btype.backtrack snap
+ | PPerror -> ()
+ | x -> Location.report_exception ppf x; Btype.backtrack snap
+ done
+
+(* Execute a script *)
+
+let run_script ppf name args =
+ let len = Array.length args in
+ if Array.length Sys.argv < len then invalid_arg "Toploop.run_script";
+ Array.blit args 0 Sys.argv 0 len;
+ Obj.truncate (Obj.repr Sys.argv) len;
+ Arg.current := 0;
+ Compmisc.init_path ~dir:(Filename.dirname name) true;
+ (* Note: would use [Filename.abspath] here, if we had it. *)
+ toplevel_env := Compmisc.initial_env();
+ Sys.interactive := false;
+ let explicit_name =
+ (* Prevent use_silently from searching in the path. *)
+ if Filename.is_implicit name
+ then Filename.concat Filename.current_dir_name name
+ else name
+ in
+ use_silently ppf explicit_name
diff --git a/toplevel/opttoploop.mli b/toplevel/opttoploop.mli
new file mode 100644
index 0000000000..2236255818
--- /dev/null
+++ b/toplevel/opttoploop.mli
@@ -0,0 +1,102 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+(* Set the load paths, before running anything *)
+
+val set_paths : unit -> unit
+
+(* The interactive toplevel loop *)
+
+val loop : formatter -> unit
+
+(* Read and execute a script from the given file *)
+
+val run_script : formatter -> string -> string array -> bool
+ (* true if successful, false if error *)
+
+(* Interface with toplevel directives *)
+
+type directive_fun =
+ | Directive_none of (unit -> unit)
+ | Directive_string of (string -> unit)
+ | Directive_int of (int -> unit)
+ | Directive_ident of (Longident.t -> unit)
+ | Directive_bool of (bool -> unit)
+
+val directive_table : (string, directive_fun) Hashtbl.t
+ (* Table of known directives, with their execution function *)
+val toplevel_env : Env.t ref
+ (* Typing environment for the toplevel *)
+val initialize_toplevel_env : unit -> unit
+ (* Initialize the typing environment for the toplevel *)
+val print_exception_outcome : formatter -> exn -> unit
+ (* Print an exception resulting from the evaluation of user code. *)
+val execute_phrase : bool -> formatter -> Parsetree.toplevel_phrase -> bool
+ (* Execute the given toplevel phrase. Return [true] if the
+ phrase executed with no errors and [false] otherwise.
+ First bool says whether the values and types of the results
+ should be printed. Uncaught exceptions are always printed. *)
+val use_file : formatter -> string -> bool
+val use_silently : formatter -> string -> bool
+ (* Read and execute commands from a file.
+ [use_file] prints the types and values of the results.
+ [use_silently] does not print them. *)
+val eval_path: Path.t -> Obj.t
+ (* Return the toplevel object referred to by the given path *)
+
+(* Printing of values *)
+
+val print_value: Env.t -> Obj.t -> formatter -> Types.type_expr -> unit
+val print_untyped_exception: formatter -> Obj.t -> unit
+
+val install_printer :
+ Path.t -> Types.type_expr -> (formatter -> Obj.t -> unit) -> unit
+val remove_printer : Path.t -> unit
+
+val max_printer_depth: int ref
+val max_printer_steps: int ref
+
+(* Hooks for external parsers and printers *)
+
+val parse_toplevel_phrase : (Lexing.lexbuf -> Parsetree.toplevel_phrase) ref
+val parse_use_file : (Lexing.lexbuf -> Parsetree.toplevel_phrase list) ref
+val print_location : formatter -> Location.t -> unit
+val print_error : formatter -> Location.t -> unit
+val print_warning : Location.t -> formatter -> Warnings.t -> unit
+val input_name : string ref
+
+val print_out_value :
+ (formatter -> Outcometree.out_value -> unit) ref
+val print_out_type :
+ (formatter -> Outcometree.out_type -> unit) ref
+val print_out_class_type :
+ (formatter -> Outcometree.out_class_type -> unit) ref
+val print_out_module_type :
+ (formatter -> Outcometree.out_module_type -> unit) ref
+val print_out_type_extension :
+ (formatter -> Outcometree.out_type_extension -> unit) ref
+val print_out_sig_item :
+ (formatter -> Outcometree.out_sig_item -> unit) ref
+val print_out_signature :
+ (formatter -> Outcometree.out_sig_item list -> unit) ref
+val print_out_phrase :
+ (formatter -> Outcometree.out_phrase -> unit) ref
+
+(* Hooks for external line editor *)
+
+val read_interactive_input : (string -> string -> int -> int * bool) ref
+
+(* Hooks for initialization *)
+
+val toplevel_startup_hook : (unit -> unit) ref
diff --git a/toplevel/opttopmain.ml b/toplevel/opttopmain.ml
new file mode 100644
index 0000000000..51d1daac55
--- /dev/null
+++ b/toplevel/opttopmain.ml
@@ -0,0 +1,121 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Clflags
+
+let usage =
+ "Usage: ocamlnat <options> <object-files> [script-file]\noptions are:"
+
+let preload_objects = ref []
+
+let prepare ppf =
+ Opttoploop.set_paths ();
+ try
+ let res =
+ List.for_all (Opttopdirs.load_file ppf) (List.rev !preload_objects)
+ in
+ !Opttoploop.toplevel_startup_hook ();
+ res
+ with x ->
+ try Location.report_exception ppf x; false
+ with x ->
+ Format.fprintf ppf "Uncaught exception: %s\n" (Printexc.to_string x);
+ false
+
+let file_argument name =
+ let ppf = Format.err_formatter in
+ if Filename.check_suffix name ".cmxs"
+ || Filename.check_suffix name ".cmx"
+ || Filename.check_suffix name ".cmxa"
+ then preload_objects := name :: !preload_objects
+ else
+ begin
+ let newargs = Array.sub Sys.argv !Arg.current
+ (Array.length Sys.argv - !Arg.current)
+ in
+ if prepare ppf && Opttoploop.run_script ppf name newargs
+ then exit 0
+ else exit 2
+ end
+
+let print_version () =
+ Printf.printf "The OCaml toplevel, version %s\n" Sys.ocaml_version;
+ exit 0;
+;;
+
+let print_version_num () =
+ Printf.printf "%s\n" Sys.ocaml_version;
+ exit 0;
+;;
+
+module Options = Main_args.Make_opttop_options (struct
+ let set r () = r := true
+ let clear r () = r := false
+
+ let _absname = set Location.absname
+ let _compact = clear optimize_for_speed
+ let _I dir =
+ let dir = Misc.expand_directory Config.standard_library dir in
+ include_dirs := dir :: !include_dirs
+ let _init s = init_file := Some s
+ let _inline n = inline_threshold := n * 8
+ let _labels = clear classic
+ let _no_alias_deps = set transparent_modules
+ let _no_app_funct = clear applicative_functors
+ let _noassert = set noassert
+ let _nolabels = set classic
+ let _noprompt = set noprompt
+ let _nopromptcont = set nopromptcont
+ let _nostdlib = set no_std_include
+ let _ppx s = Compenv.first_ppx := s :: !Compenv.first_ppx
+ let _principal = set principal
+ let _real_paths = set real_paths
+ let _rectypes = set recursive_types
+ let _strict_sequence = set strict_sequence
+ let _strict_formats = set strict_formats
+ let _S = set keep_asm_file
+ let _short_paths = clear real_paths
+ let _stdin () = file_argument ""
+ let _unsafe = set fast
+ let _version () = print_version ()
+ let _vnum () = print_version_num ()
+ let _w s = Warnings.parse_options false s
+ let _warn_error s = Warnings.parse_options true s
+ let _warn_help = Warnings.help_warnings
+
+ let _dsource = set dump_source
+ let _dparsetree = set dump_parsetree
+ let _dtypedtree = set dump_typedtree
+ let _drawlambda = set dump_rawlambda
+ let _dlambda = set dump_lambda
+ let _dclambda = set dump_clambda
+ let _dcmm = set dump_cmm
+ let _dsel = set dump_selection
+ let _dcombine = set dump_combine
+ let _dlive () = dump_live := true; Printmach.print_live := true
+ let _dspill = set dump_spill
+ let _dsplit = set dump_split
+ let _dinterf = set dump_interf
+ let _dprefer = set dump_prefer
+ let _dalloc = set dump_regalloc
+ let _dreload = set dump_reload
+ let _dscheduling = set dump_scheduling
+ let _dlinear = set dump_linear
+ let _dstartup = set keep_startup_file
+
+ let anonymous = file_argument
+end);;
+
+let main () =
+ Arg.parse Options.list file_argument usage;
+ if not (prepare Format.err_formatter) then exit 2;
+ Opttoploop.loop Format.std_formatter
diff --git a/toplevel/opttopmain.mli b/toplevel/opttopmain.mli
new file mode 100644
index 0000000000..74044e5149
--- /dev/null
+++ b/toplevel/opttopmain.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Start the [ocaml] toplevel loop *)
+
+val main: unit -> unit
diff --git a/toplevel/opttopstart.ml b/toplevel/opttopstart.ml
new file mode 100644
index 0000000000..9fa9b47fc9
--- /dev/null
+++ b/toplevel/opttopstart.ml
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let _ = Opttopmain.main()
diff --git a/toplevel/topdirs.ml b/toplevel/topdirs.ml
new file mode 100644
index 0000000000..7a3b1eb617
--- /dev/null
+++ b/toplevel/topdirs.ml
@@ -0,0 +1,562 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Toplevel directives *)
+
+open Format
+open Misc
+open Longident
+open Types
+open Cmo_format
+open Trace
+open Toploop
+
+(* The standard output formatter *)
+let std_out = std_formatter
+
+(* To quit *)
+
+let dir_quit () = exit 0
+
+let _ = Hashtbl.add directive_table "quit" (Directive_none dir_quit)
+
+(* To add a directory to the load path *)
+
+let dir_directory s =
+ let d = expand_directory Config.standard_library s in
+ Config.load_path := d :: !Config.load_path;
+ Dll.add_path [d]
+
+let _ = Hashtbl.add directive_table "directory" (Directive_string dir_directory)
+
+(* To remove a directory from the load path *)
+let dir_remove_directory s =
+ let d = expand_directory Config.standard_library s in
+ Config.load_path := List.filter (fun d' -> d' <> d) !Config.load_path;
+ Dll.remove_path [d]
+
+let _ =
+ Hashtbl.add directive_table "remove_directory"
+ (Directive_string dir_remove_directory)
+
+(* To change the current directory *)
+
+let dir_cd s = Sys.chdir s
+
+let _ = Hashtbl.add directive_table "cd" (Directive_string dir_cd)
+
+(* Load in-core a .cmo file *)
+
+exception Load_failed
+
+let check_consistency ppf filename cu =
+ try
+ List.iter
+ (fun (name, crco) ->
+ Env.add_import name;
+ match crco with
+ None -> ()
+ | Some crc->
+ Consistbl.check Env.crc_units name crc filename)
+ cu.cu_imports
+ with Consistbl.Inconsistency(name, user, auth) ->
+ fprintf ppf "@[<hv 0>The files %s@ and %s@ \
+ disagree over interface %s@]@."
+ user auth name;
+ raise Load_failed
+
+let load_compunit ic filename ppf compunit =
+ check_consistency ppf filename compunit;
+ seek_in ic compunit.cu_pos;
+ let code_size = compunit.cu_codesize + 8 in
+ let code = Meta.static_alloc code_size in
+ unsafe_really_input ic code 0 compunit.cu_codesize;
+ Bytes.unsafe_set code compunit.cu_codesize (Char.chr Opcodes.opRETURN);
+ String.unsafe_blit "\000\000\000\001\000\000\000" 0
+ code (compunit.cu_codesize + 1) 7;
+ let initial_symtable = Symtable.current_state() in
+ Symtable.patch_object code compunit.cu_reloc;
+ Symtable.update_global_table();
+ let events =
+ if compunit.cu_debug = 0 then [| |]
+ else begin
+ seek_in ic compunit.cu_debug;
+ [| input_value ic |]
+ end in
+ Meta.add_debug_info code code_size events;
+ begin try
+ may_trace := true;
+ ignore((Meta.reify_bytecode code code_size) ());
+ may_trace := false;
+ with exn ->
+ record_backtrace ();
+ may_trace := false;
+ Symtable.restore_state initial_symtable;
+ print_exception_outcome ppf exn;
+ raise Load_failed
+ end
+
+let rec load_file recursive ppf name =
+ let filename =
+ try Some (find_in_path !Config.load_path name) with Not_found -> None
+ in
+ match filename with
+ | None -> fprintf ppf "Cannot find file %s.@." name; false
+ | Some filename ->
+ let ic = open_in_bin filename in
+ try
+ let success = really_load_file recursive ppf name filename ic in
+ close_in ic;
+ success
+ with exn ->
+ close_in ic;
+ raise exn
+
+and really_load_file recursive ppf name filename ic =
+ let ic = open_in_bin filename in
+ let buffer = really_input_string ic (String.length Config.cmo_magic_number) in
+ try
+ if buffer = Config.cmo_magic_number then begin
+ let compunit_pos = input_binary_int ic in (* Go to descriptor *)
+ seek_in ic compunit_pos;
+ let cu : compilation_unit = input_value ic in
+ if recursive then
+ List.iter
+ (function
+ | (Reloc_getglobal id, _)
+ when not (Symtable.is_global_defined id) ->
+ let file = Ident.name id ^ ".cmo" in
+ begin match try Some (Misc.find_in_path_uncap !Config.load_path
+ file)
+ with Not_found -> None
+ with
+ | None -> ()
+ | Some file ->
+ if not (load_file recursive ppf file) then raise Load_failed
+ end
+ | _ -> ()
+ )
+ cu.cu_reloc;
+ load_compunit ic filename ppf cu;
+ true
+ end else
+ if buffer = Config.cma_magic_number then begin
+ let toc_pos = input_binary_int ic in (* Go to table of contents *)
+ seek_in ic toc_pos;
+ let lib = (input_value ic : library) in
+ List.iter
+ (fun dllib ->
+ let name = Dll.extract_dll_name dllib in
+ try Dll.open_dlls Dll.For_execution [name]
+ with Failure reason ->
+ fprintf ppf
+ "Cannot load required shared library %s.@.Reason: %s.@."
+ name reason;
+ raise Load_failed)
+ lib.lib_dllibs;
+ List.iter (load_compunit ic filename ppf) lib.lib_units;
+ true
+ end else begin
+ fprintf ppf "File %s is not a bytecode object file.@." name;
+ false
+ end
+ with Load_failed -> false
+
+let dir_load ppf name = ignore (load_file false ppf name)
+
+let _ = Hashtbl.add directive_table "load" (Directive_string (dir_load std_out))
+
+let dir_load_rec ppf name = ignore (load_file true ppf name)
+
+let _ = Hashtbl.add directive_table "load_rec"
+ (Directive_string (dir_load_rec std_out))
+
+let load_file = load_file false
+
+(* Load commands from a file *)
+
+let dir_use ppf name = ignore(Toploop.use_file ppf name)
+let dir_mod_use ppf name = ignore(Toploop.mod_use_file ppf name)
+
+let _ = Hashtbl.add directive_table "use" (Directive_string (dir_use std_out))
+let _ = Hashtbl.add directive_table "mod_use"
+ (Directive_string (dir_mod_use std_out))
+
+(* Install, remove a printer *)
+
+let filter_arrow ty =
+ let ty = Ctype.expand_head !toplevel_env ty in
+ match ty.desc with
+ | Tarrow (lbl, l, r, _) when not (Btype.is_optional lbl) -> Some (l, r)
+ | _ -> None
+
+let rec extract_last_arrow desc =
+ match filter_arrow desc with
+ | None -> raise (Ctype.Unify [])
+ | Some (_, r as res) ->
+ try extract_last_arrow r
+ with Ctype.Unify _ -> res
+
+let extract_target_type ty = fst (extract_last_arrow ty)
+let extract_target_parameters ty =
+ let ty = extract_target_type ty |> Ctype.expand_head !toplevel_env in
+ match ty.desc with
+ | Tconstr (path, (_ :: _ as args), _)
+ when Ctype.all_distinct_vars !toplevel_env args -> Some (path, args)
+ | _ -> None
+
+type 'a printer_type_new = Format.formatter -> 'a -> unit
+type 'a printer_type_old = 'a -> unit
+
+let printer_type ppf typename =
+ let (printer_type, _) =
+ try
+ Env.lookup_type (Ldot(Lident "Topdirs", typename)) !toplevel_env
+ with Not_found ->
+ fprintf ppf "Cannot find type Topdirs.%s.@." typename;
+ raise Exit in
+ printer_type
+
+let match_simple_printer_type ppf desc printer_type =
+ Ctype.begin_def();
+ let ty_arg = Ctype.newvar() in
+ Ctype.unify !toplevel_env
+ (Ctype.newconstr printer_type [ty_arg])
+ (Ctype.instance_def desc.val_type);
+ Ctype.end_def();
+ Ctype.generalize ty_arg;
+ (ty_arg, None)
+
+let match_generic_printer_type ppf desc path args printer_type =
+ Ctype.begin_def();
+ let args = List.map (fun _ -> Ctype.newvar ()) args in
+ let ty_target = Ctype.newty (Tconstr (path, args, ref Mnil)) in
+ let ty_args =
+ List.map (fun ty_var -> Ctype.newconstr printer_type [ty_var]) args in
+ let ty_expected =
+ List.fold_right
+ (fun ty_arg ty -> Ctype.newty (Tarrow (Asttypes.Nolabel, ty_arg, ty,
+ Cunknown)))
+ ty_args (Ctype.newconstr printer_type [ty_target]) in
+ Ctype.unify !toplevel_env
+ ty_expected
+ (Ctype.instance_def desc.val_type);
+ Ctype.end_def();
+ Ctype.generalize ty_expected;
+ if not (Ctype.all_distinct_vars !toplevel_env args) then
+ raise (Ctype.Unify []);
+ (ty_expected, Some (path, ty_args))
+
+let match_printer_type ppf desc =
+ let printer_type_new = printer_type ppf "printer_type_new" in
+ let printer_type_old = printer_type ppf "printer_type_old" in
+ Ctype.init_def(Ident.current_time());
+ try
+ (match_simple_printer_type ppf desc printer_type_new, false)
+ with Ctype.Unify _ ->
+ try
+ (match_simple_printer_type ppf desc printer_type_old, true)
+ with Ctype.Unify _ as exn ->
+ match extract_target_parameters desc.val_type with
+ | None -> raise exn
+ | Some (path, args) ->
+ (match_generic_printer_type ppf desc path args printer_type_new,
+ false)
+
+let find_printer_type ppf lid =
+ try
+ let (path, desc) = Env.lookup_value lid !toplevel_env in
+ let (ty_arg, is_old_style) = match_printer_type ppf desc in
+ (ty_arg, path, is_old_style)
+ with
+ | Not_found ->
+ fprintf ppf "Unbound value %a.@." Printtyp.longident lid;
+ raise Exit
+ | Ctype.Unify _ ->
+ fprintf ppf "%a has a wrong type for a printing function.@."
+ Printtyp.longident lid;
+ raise Exit
+
+let dir_install_printer ppf lid =
+ try
+ let ((ty_arg, ty), path, is_old_style) =
+ find_printer_type ppf lid in
+ let v = eval_path !toplevel_env path in
+ match ty with
+ | None ->
+ let print_function =
+ if is_old_style then
+ (fun formatter repr -> Obj.obj v (Obj.obj repr))
+ else
+ (fun formatter repr -> Obj.obj v formatter (Obj.obj repr)) in
+ install_printer path ty_arg print_function
+ | Some (ty_path, ty_args) ->
+ let rec build v = function
+ | [] ->
+ let print_function =
+ if is_old_style then
+ (fun formatter repr -> Obj.obj v (Obj.obj repr))
+ else
+ (fun formatter repr -> Obj.obj v formatter (Obj.obj repr)) in
+ Zero print_function
+ | _ :: args ->
+ Succ
+ (fun fn -> build ((Obj.obj v : _ -> Obj.t) fn) args) in
+ install_generic_printer' path ty_path (build v ty_args)
+ with Exit -> ()
+
+let dir_remove_printer ppf lid =
+ try
+ let (ty_arg, path, is_old_style) = find_printer_type ppf lid in
+ begin try
+ remove_printer path
+ with Not_found ->
+ fprintf ppf "No printer named %a.@." Printtyp.longident lid
+ end
+ with Exit -> ()
+
+let _ = Hashtbl.add directive_table "install_printer"
+ (Directive_ident (dir_install_printer std_out))
+let _ = Hashtbl.add directive_table "remove_printer"
+ (Directive_ident (dir_remove_printer std_out))
+
+(* The trace *)
+
+external current_environment: unit -> Obj.t = "caml_get_current_environment"
+
+let tracing_function_ptr =
+ get_code_pointer
+ (Obj.repr (fun arg -> Trace.print_trace (current_environment()) arg))
+
+let dir_trace ppf lid =
+ try
+ let (path, desc) = Env.lookup_value lid !toplevel_env in
+ (* Check if this is a primitive *)
+ match desc.val_kind with
+ | Val_prim p ->
+ fprintf ppf "%a is an external function and cannot be traced.@."
+ Printtyp.longident lid
+ | _ ->
+ let clos = eval_path !toplevel_env path in
+ (* Nothing to do if it's not a closure *)
+ if Obj.is_block clos
+ && (Obj.tag clos = Obj.closure_tag || Obj.tag clos = Obj.infix_tag)
+ && (match Ctype.(repr (expand_head !toplevel_env desc.val_type))
+ with {desc=Tarrow _} -> true | _ -> false)
+ then begin
+ match is_traced clos with
+ | Some opath ->
+ fprintf ppf "%a is already traced (under the name %a).@."
+ Printtyp.path path
+ Printtyp.path opath
+ | None ->
+ (* Instrument the old closure *)
+ traced_functions :=
+ { path = path;
+ closure = clos;
+ actual_code = get_code_pointer clos;
+ instrumented_fun =
+ instrument_closure !toplevel_env lid ppf desc.val_type }
+ :: !traced_functions;
+ (* Redirect the code field of the closure to point
+ to the instrumentation function *)
+ set_code_pointer clos tracing_function_ptr;
+ fprintf ppf "%a is now traced.@." Printtyp.longident lid
+ end else fprintf ppf "%a is not a function.@." Printtyp.longident lid
+ with
+ | Not_found -> fprintf ppf "Unbound value %a.@." Printtyp.longident lid
+
+let dir_untrace ppf lid =
+ try
+ let (path, desc) = Env.lookup_value lid !toplevel_env in
+ let rec remove = function
+ | [] ->
+ fprintf ppf "%a was not traced.@." Printtyp.longident lid;
+ []
+ | f :: rem ->
+ if Path.same f.path path then begin
+ set_code_pointer f.closure f.actual_code;
+ fprintf ppf "%a is no longer traced.@." Printtyp.longident lid;
+ rem
+ end else f :: remove rem in
+ traced_functions := remove !traced_functions
+ with
+ | Not_found -> fprintf ppf "Unbound value %a.@." Printtyp.longident lid
+
+let dir_untrace_all ppf () =
+ List.iter
+ (fun f ->
+ set_code_pointer f.closure f.actual_code;
+ fprintf ppf "%a is no longer traced.@." Printtyp.path f.path)
+ !traced_functions;
+ traced_functions := []
+
+let parse_warnings ppf iserr s =
+ try Warnings.parse_options iserr s
+ with Arg.Bad err -> fprintf ppf "%s.@." err
+
+(* Typing information *)
+
+let trim_signature = function
+ Mty_signature sg ->
+ Mty_signature
+ (List.map
+ (function
+ Sig_module (id, md, rs) ->
+ Sig_module (id, {md with md_attributes =
+ (Location.mknoloc "...", Parsetree.PStr [])
+ :: md.md_attributes},
+ rs)
+ (*| Sig_modtype (id, Modtype_manifest mty) ->
+ Sig_modtype (id, Modtype_manifest (trim_modtype mty))*)
+ | item -> item)
+ sg)
+ | mty -> mty
+
+let show_prim to_sig ppf lid =
+ let env = !Toploop.toplevel_env in
+ let loc = Location.none in
+ try
+ let s =
+ match lid with
+ | Longident.Lident s -> s
+ | Longident.Ldot (_,s) -> s
+ | Longident.Lapply _ ->
+ fprintf ppf "Invalid path %a@." Printtyp.longident lid;
+ raise Exit
+ in
+ let id = Ident.create_persistent s in
+ let sg = to_sig env loc id lid in
+ Printtyp.wrap_printing_env env
+ (fun () -> fprintf ppf "@[%a@]@." Printtyp.signature sg)
+ with
+ | Not_found ->
+ fprintf ppf "@[Unknown element.@]@."
+ | Exit -> ()
+
+let all_show_funs = ref []
+
+let reg_show_prim name to_sig =
+ all_show_funs := to_sig :: !all_show_funs;
+ Hashtbl.add directive_table name (Directive_ident (show_prim to_sig std_out))
+
+let () =
+ reg_show_prim "show_val"
+ (fun env loc id lid ->
+ let path, desc = Typetexp.find_value env loc lid in
+ [ Sig_value (id, desc) ]
+ )
+
+let () =
+ reg_show_prim "show_type"
+ (fun env loc id lid ->
+ let path, desc = Typetexp.find_type env loc lid in
+ [ Sig_type (id, desc, Trec_not) ]
+ )
+
+let () =
+ reg_show_prim "show_exception"
+ (fun env loc id lid ->
+ let desc = Typetexp.find_constructor env loc lid in
+ if not (Ctype.equal env true [desc.cstr_res] [Predef.type_exn]) then
+ raise Not_found;
+ let ret_type =
+ if desc.cstr_generalized then Some Predef.type_exn
+ else None
+ in
+ let ext =
+ { ext_type_path = Predef.path_exn;
+ ext_type_params = [];
+ ext_args = Cstr_tuple desc.cstr_args;
+ ext_ret_type = ret_type;
+ ext_private = Asttypes.Public;
+ Types.ext_loc = desc.cstr_loc;
+ Types.ext_attributes = desc.cstr_attributes; }
+ in
+ [Sig_typext (id, ext, Text_exception)]
+ )
+
+let () =
+ reg_show_prim "show_module"
+ (fun env loc id lid ->
+ let path, md = Typetexp.find_module env loc lid in
+ [ Sig_module (id, {md with md_type = trim_signature md.md_type},
+ Trec_not) ]
+ )
+
+let () =
+ reg_show_prim "show_module_type"
+ (fun env loc id lid ->
+ let path, desc = Typetexp.find_modtype env loc lid in
+ [ Sig_modtype (id, desc) ]
+ )
+
+let () =
+ reg_show_prim "show_class"
+ (fun env loc id lid ->
+ let path, desc = Typetexp.find_class env loc lid in
+ [ Sig_class (id, desc, Trec_not) ]
+ )
+
+let () =
+ reg_show_prim "show_class_type"
+ (fun env loc id lid ->
+ let path, desc = Typetexp.find_class_type env loc lid in
+ [ Sig_class_type (id, desc, Trec_not) ]
+ )
+
+
+let show env loc id lid =
+ let sg =
+ List.fold_left
+ (fun sg f -> try (f env loc id lid) @ sg with _ -> sg)
+ [] !all_show_funs
+ in
+ if sg = [] then raise Not_found else sg
+
+let () =
+ Hashtbl.add directive_table "show" (Directive_ident (show_prim show std_out))
+
+let _ =
+ Hashtbl.add directive_table "trace" (Directive_ident (dir_trace std_out));
+ Hashtbl.add directive_table "untrace" (Directive_ident (dir_untrace std_out));
+ Hashtbl.add directive_table
+ "untrace_all" (Directive_none (dir_untrace_all std_out));
+
+(* Control the printing of values *)
+
+ Hashtbl.add directive_table "print_depth"
+ (Directive_int(fun n -> max_printer_depth := n));
+ Hashtbl.add directive_table "print_length"
+ (Directive_int(fun n -> max_printer_steps := n));
+
+(* Set various compiler flags *)
+
+ Hashtbl.add directive_table "labels"
+ (Directive_bool(fun b -> Clflags.classic := not b));
+
+ Hashtbl.add directive_table "principal"
+ (Directive_bool(fun b -> Clflags.principal := b));
+
+ Hashtbl.add directive_table "rectypes"
+ (Directive_none(fun () -> Clflags.recursive_types := true));
+
+ Hashtbl.add directive_table "ppx"
+ (Directive_string(fun s -> Clflags.all_ppx := s :: !Clflags.all_ppx));
+
+ Hashtbl.add directive_table "warnings"
+ (Directive_string (parse_warnings std_out false));
+
+ Hashtbl.add directive_table "warn_error"
+ (Directive_string (parse_warnings std_out true));
+
+ ()
diff --git a/toplevel/topdirs.mli b/toplevel/topdirs.mli
new file mode 100644
index 0000000000..42ea4ddb5c
--- /dev/null
+++ b/toplevel/topdirs.mli
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The toplevel directives. *)
+
+open Format
+
+val dir_quit : unit -> unit
+val dir_directory : string -> unit
+val dir_remove_directory : string -> unit
+val dir_cd : string -> unit
+val dir_load : formatter -> string -> unit
+val dir_use : formatter -> string -> unit
+val dir_install_printer : formatter -> Longident.t -> unit
+val dir_remove_printer : formatter -> Longident.t -> unit
+val dir_trace : formatter -> Longident.t -> unit
+val dir_untrace : formatter -> Longident.t -> unit
+val dir_untrace_all : formatter -> unit -> unit
+
+type 'a printer_type_new = Format.formatter -> 'a -> unit
+type 'a printer_type_old = 'a -> unit
+
+(* For topmain.ml. Maybe shouldn't be there *)
+val load_file : formatter -> string -> bool
diff --git a/toplevel/toplevellib.mllib b/toplevel/toplevellib.mllib
new file mode 100644
index 0000000000..886d1d2c82
--- /dev/null
+++ b/toplevel/toplevellib.mllib
@@ -0,0 +1,21 @@
+Myocamlbuild_config
+Misc Tbl Config Clflags Terminfo Ccomp Warnings Consistbl
+
+Location Longident Syntaxerr Parser
+Lexer Parse Printast
+
+Ident Path Primitive Types
+Btype Oprint Subst Predef Datarepr
+Cmi_format Env
+Typedtree
+Cmt_format Ctype Printtyp Includeclass Mtype Includecore
+Includemod Parmatch Typetexp Stypes Typecore
+Typedecl Typeclass Typemod
+
+Lambda Printlambda Typeopt Switch Matching Translobj Translcore
+Translclass Translmod Simplif Runtimedef
+
+Meta Instruct Bytegen Printinstr Opcodes Emitcode
+Bytesections Dll Symtable Bytelink Bytelibrarian Bytepackager
+
+Pparse Errors Compile Main_args Genprintval Toploop Trace Topdirs Topmain
diff --git a/toplevel/toploop.ml b/toplevel/toploop.ml
new file mode 100644
index 0000000000..21712aebb1
--- /dev/null
+++ b/toplevel/toploop.ml
@@ -0,0 +1,514 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The interactive toplevel loop *)
+
+open Path
+open Format
+open Config
+open Misc
+open Parsetree
+open Types
+open Typedtree
+open Outcometree
+open Ast_helper
+
+type directive_fun =
+ | Directive_none of (unit -> unit)
+ | Directive_string of (string -> unit)
+ | Directive_int of (int -> unit)
+ | Directive_ident of (Longident.t -> unit)
+ | Directive_bool of (bool -> unit)
+
+(* The table of toplevel value bindings and its accessors *)
+
+module StringMap = Map.Make(String)
+
+let toplevel_value_bindings : Obj.t StringMap.t ref = ref StringMap.empty
+
+let getvalue name =
+ try
+ StringMap.find name !toplevel_value_bindings
+ with Not_found ->
+ fatal_error (name ^ " unbound at toplevel")
+
+let setvalue name v =
+ toplevel_value_bindings := StringMap.add name v !toplevel_value_bindings
+
+(* Return the value referred to by a path *)
+
+let rec eval_path = function
+ | Pident id ->
+ if Ident.persistent id || Ident.global id then
+ Symtable.get_global_value id
+ else begin
+ let name = Translmod.toplevel_name id in
+ try
+ StringMap.find name !toplevel_value_bindings
+ with Not_found ->
+ raise (Symtable.Error(Symtable.Undefined_global name))
+ end
+ | Pdot(p, s, pos) ->
+ Obj.field (eval_path p) pos
+ | Papply(p1, p2) ->
+ fatal_error "Toploop.eval_path"
+
+let eval_path env path =
+ eval_path (Env.normalize_path (Some Location.none) env path)
+
+(* To print values *)
+
+module EvalPath = struct
+ type valu = Obj.t
+ exception Error
+ let eval_path env p = try eval_path env p with Symtable.Error _ -> raise Error
+ let same_value v1 v2 = (v1 == v2)
+end
+
+module Printer = Genprintval.Make(Obj)(EvalPath)
+
+let max_printer_depth = ref 100
+let max_printer_steps = ref 300
+
+let print_out_value = Oprint.out_value
+let print_out_type = Oprint.out_type
+let print_out_class_type = Oprint.out_class_type
+let print_out_module_type = Oprint.out_module_type
+let print_out_type_extension = Oprint.out_type_extension
+let print_out_sig_item = Oprint.out_sig_item
+let print_out_signature = Oprint.out_signature
+let print_out_phrase = Oprint.out_phrase
+
+let print_untyped_exception ppf obj =
+ !print_out_value ppf (Printer.outval_of_untyped_exception obj)
+let outval_of_value env obj ty =
+ Printer.outval_of_value !max_printer_steps !max_printer_depth
+ (fun _ _ _ -> None) env obj ty
+let print_value env obj ppf ty =
+ !print_out_value ppf (outval_of_value env obj ty)
+
+type ('a, 'b) gen_printer = ('a, 'b) Genprintval.gen_printer =
+ | Zero of 'b
+ | Succ of ('a -> ('a, 'b) gen_printer)
+
+let install_printer = Printer.install_printer
+let install_generic_printer = Printer.install_generic_printer
+let install_generic_printer' = Printer.install_generic_printer'
+let remove_printer = Printer.remove_printer
+
+(* Hooks for parsing functions *)
+
+let parse_toplevel_phrase = ref Parse.toplevel_phrase
+let parse_use_file = ref Parse.use_file
+let print_location = Location.print_error (* FIXME change back to print *)
+let print_error = Location.print_error
+let print_warning = Location.print_warning
+let input_name = Location.input_name
+
+let parse_mod_use_file name lb =
+ let modname =
+ String.capitalize_ascii (Filename.chop_extension (Filename.basename name))
+ in
+ let items =
+ List.concat
+ (List.map
+ (function Ptop_def s -> s | Ptop_dir _ -> [])
+ (!parse_use_file lb))
+ in
+ [ Ptop_def
+ [ Str.module_
+ (Mb.mk
+ (Location.mknoloc modname)
+ (Mod.structure items)
+ )
+ ]
+ ]
+
+(* Hooks for initialization *)
+
+let toplevel_startup_hook = ref (fun () -> ())
+
+(* Load in-core and execute a lambda term *)
+
+let may_trace = ref false (* Global lock on tracing *)
+type evaluation_outcome = Result of Obj.t | Exception of exn
+
+let backtrace = ref None
+
+let record_backtrace () =
+ if Printexc.backtrace_status ()
+ then backtrace := Some (Printexc.get_backtrace ())
+
+let load_lambda ppf lam =
+ if !Clflags.dump_rawlambda then fprintf ppf "%a@." Printlambda.lambda lam;
+ let slam = Simplif.simplify_lambda lam in
+ if !Clflags.dump_lambda then fprintf ppf "%a@." Printlambda.lambda slam;
+ let (init_code, fun_code) = Bytegen.compile_phrase slam in
+ if !Clflags.dump_instr then
+ fprintf ppf "%a%a@."
+ Printinstr.instrlist init_code
+ Printinstr.instrlist fun_code;
+ let (code, code_size, reloc, events) =
+ Emitcode.to_memory init_code fun_code
+ in
+ Meta.add_debug_info code code_size [| events |];
+ let can_free = (fun_code = []) in
+ let initial_symtable = Symtable.current_state() in
+ Symtable.patch_object code reloc;
+ Symtable.check_global_initialized reloc;
+ Symtable.update_global_table();
+ let initial_bindings = !toplevel_value_bindings in
+ try
+ may_trace := true;
+ let retval = (Meta.reify_bytecode code code_size) () in
+ may_trace := false;
+ if can_free then begin
+ Meta.remove_debug_info code;
+ Meta.static_release_bytecode code code_size;
+ Meta.static_free code;
+ end;
+ Result retval
+ with x ->
+ may_trace := false;
+ record_backtrace ();
+ if can_free then begin
+ Meta.remove_debug_info code;
+ Meta.static_release_bytecode code code_size;
+ Meta.static_free code;
+ end;
+ toplevel_value_bindings := initial_bindings; (* PR#6211 *)
+ Symtable.restore_state initial_symtable;
+ Exception x
+
+(* Print the outcome of an evaluation *)
+
+let pr_item =
+ Printtyp.print_items
+ (fun env -> function
+ | Sig_value(id, {val_kind = Val_reg; val_type}) ->
+ Some (outval_of_value env (getvalue (Translmod.toplevel_name id))
+ val_type)
+ | _ -> None
+ )
+
+(* The current typing environment for the toplevel *)
+
+let toplevel_env = ref Env.empty
+
+(* Print an exception produced by an evaluation *)
+
+let print_out_exception ppf exn outv =
+ !print_out_phrase ppf (Ophr_exception (exn, outv))
+
+let print_exception_outcome ppf exn =
+ if exn = Out_of_memory then Gc.full_major ();
+ let outv = outval_of_value !toplevel_env (Obj.repr exn) Predef.type_exn in
+ print_out_exception ppf exn outv;
+ if Printexc.backtrace_status ()
+ then
+ match !backtrace with
+ | None -> ()
+ | Some b ->
+ print_string b;
+ backtrace := None
+
+(* The table of toplevel directives.
+ Filled by functions from module topdirs. *)
+
+let directive_table = (Hashtbl.create 13 : (string, directive_fun) Hashtbl.t)
+
+(* Execute a toplevel phrase *)
+
+let execute_phrase print_outcome ppf phr =
+ match phr with
+ | Ptop_def sstr ->
+ let oldenv = !toplevel_env in
+ Typecore.reset_delayed_checks ();
+ let (str, sg, newenv) = Typemod.type_toplevel_phrase oldenv sstr in
+ if !Clflags.dump_typedtree then Printtyped.implementation ppf str;
+ let sg' = Typemod.simplify_signature sg in
+ ignore (Includemod.signatures oldenv sg sg');
+ Typecore.force_delayed_checks ();
+ let lam = Translmod.transl_toplevel_definition str in
+ Warnings.check_fatal ();
+ begin try
+ toplevel_env := newenv;
+ let res = load_lambda ppf lam in
+ let out_phr =
+ match res with
+ | Result v ->
+ if print_outcome then
+ Printtyp.wrap_printing_env oldenv (fun () ->
+ match str.str_items with
+ | [ { str_desc = Tstr_eval (exp, _attrs) }] ->
+ let outv = outval_of_value newenv v exp.exp_type in
+ let ty = Printtyp.tree_of_type_scheme exp.exp_type in
+ Ophr_eval (outv, ty)
+ | [] -> Ophr_signature []
+ | _ -> Ophr_signature (pr_item newenv sg'))
+ else Ophr_signature []
+ | Exception exn ->
+ toplevel_env := oldenv;
+ if exn = Out_of_memory then Gc.full_major();
+ let outv =
+ outval_of_value !toplevel_env (Obj.repr exn) Predef.type_exn
+ in
+ Ophr_exception (exn, outv)
+ in
+ !print_out_phrase ppf out_phr;
+ if Printexc.backtrace_status ()
+ then begin
+ match !backtrace with
+ | None -> ()
+ | Some b ->
+ pp_print_string ppf b;
+ pp_print_flush ppf ();
+ backtrace := None;
+ end;
+ begin match out_phr with
+ | Ophr_eval (_, _) | Ophr_signature _ -> true
+ | Ophr_exception _ -> false
+ end
+ with x ->
+ toplevel_env := oldenv; raise x
+ end
+ | Ptop_dir(dir_name, dir_arg) ->
+ let d =
+ try Some (Hashtbl.find directive_table dir_name)
+ with Not_found -> None
+ in
+ begin match d with
+ | None ->
+ fprintf ppf "Unknown directive `%s'.@." dir_name;
+ false
+ | Some d ->
+ match d, dir_arg with
+ | Directive_none f, Pdir_none -> f (); true
+ | Directive_string f, Pdir_string s -> f s; true
+ | Directive_int f, Pdir_int n -> f n; true
+ | Directive_ident f, Pdir_ident lid -> f lid; true
+ | Directive_bool f, Pdir_bool b -> f b; true
+ | _ ->
+ fprintf ppf "Wrong type of argument for directive `%s'.@."
+ dir_name;
+ false
+ end
+
+
+(* Temporary assignment to a reference *)
+
+let protect r newval body =
+ let oldval = !r in
+ try
+ r := newval;
+ let res = body() in
+ r := oldval;
+ res
+ with x ->
+ r := oldval;
+ raise x
+
+(* Read and execute commands from a file, or from stdin if [name] is "". *)
+
+let use_print_results = ref true
+
+let preprocess_phrase ppf phr =
+ let phr =
+ match phr with
+ | Ptop_def str ->
+ let str =
+ Pparse.apply_rewriters_str ~restore:true ~tool_name:"ocaml" str
+ in
+ Ptop_def str
+ | phr -> phr
+ in
+ if !Clflags.dump_parsetree then Printast.top_phrase ppf phr;
+ if !Clflags.dump_source then Pprintast.top_phrase ppf phr;
+ phr
+
+let use_file ppf wrap_mod name =
+ try
+ let (filename, ic, must_close) =
+ if name = "" then
+ ("(stdin)", stdin, false)
+ else begin
+ let filename = find_in_path !Config.load_path name in
+ let ic = open_in_bin filename in
+ (filename, ic, true)
+ end
+ in
+ let lb = Lexing.from_channel ic in
+ Location.init lb filename;
+ (* Skip initial #! line if any *)
+ Lexer.skip_sharp_bang lb;
+ let success =
+ protect Location.input_name filename (fun () ->
+ try
+ List.iter
+ (fun ph ->
+ let ph = preprocess_phrase ppf ph in
+ if not (execute_phrase !use_print_results ppf ph) then raise Exit)
+ (if wrap_mod then
+ parse_mod_use_file name lb
+ else
+ !parse_use_file lb);
+ true
+ with
+ | Exit -> false
+ | Sys.Break -> fprintf ppf "Interrupted.@."; false
+ | x -> Location.report_exception ppf x; false) in
+ if must_close then close_in ic;
+ success
+ with Not_found -> fprintf ppf "Cannot find file %s.@." name; false
+
+let mod_use_file ppf name = use_file ppf true name
+let use_file ppf name = use_file ppf false name
+
+let use_silently ppf name =
+ protect use_print_results false (fun () -> use_file ppf name)
+
+(* Reading function for interactive use *)
+
+let first_line = ref true
+let got_eof = ref false;;
+
+let read_input_default prompt buffer len =
+ output_string Pervasives.stdout prompt; flush Pervasives.stdout;
+ let i = ref 0 in
+ try
+ while true do
+ if !i >= len then raise Exit;
+ let c = input_char Pervasives.stdin in
+ Bytes.set buffer !i c;
+ incr i;
+ if c = '\n' then raise Exit;
+ done;
+ (!i, false)
+ with
+ | End_of_file ->
+ (!i, true)
+ | Exit ->
+ (!i, false)
+
+let read_interactive_input = ref read_input_default
+
+let refill_lexbuf buffer len =
+ if !got_eof then (got_eof := false; 0) else begin
+ let prompt =
+ if !Clflags.noprompt then ""
+ else if !first_line then "# "
+ else if !Clflags.nopromptcont then ""
+ else if Lexer.in_comment () then "* "
+ else " "
+ in
+ first_line := false;
+ let (len, eof) = !read_interactive_input prompt buffer len in
+ if eof then begin
+ Location.echo_eof ();
+ if len > 0 then got_eof := true;
+ len
+ end else
+ len
+ end
+
+(* Toplevel initialization. Performed here instead of at the
+ beginning of loop() so that user code linked in with ocamlmktop
+ can call directives from Topdirs. *)
+
+let _ =
+ Clflags.debug := true;
+ Sys.interactive := true;
+ let crc_intfs = Symtable.init_toplevel() in
+ Compmisc.init_path false;
+ List.iter
+ (fun (name, crco) ->
+ Env.add_import name;
+ match crco with
+ None -> ()
+ | Some crc->
+ Consistbl.set Env.crc_units name crc Sys.executable_name)
+ crc_intfs
+
+let load_ocamlinit ppf =
+ if !Clflags.noinit then ()
+ else match !Clflags.init_file with
+ | Some f -> if Sys.file_exists f then ignore (use_silently ppf f)
+ else fprintf ppf "Init file not found: \"%s\".@." f
+ | None ->
+ if Sys.file_exists ".ocamlinit" then ignore (use_silently ppf ".ocamlinit")
+ else try
+ let home_init = Filename.concat (Sys.getenv "HOME") ".ocamlinit" in
+ if Sys.file_exists home_init then ignore (use_silently ppf home_init)
+ with Not_found -> ()
+;;
+
+let set_paths () =
+ (* Add whatever -I options have been specified on the command line,
+ but keep the directories that user code linked in with ocamlmktop
+ may have added to load_path. *)
+ load_path := !load_path @ [Filename.concat Config.standard_library "camlp4"];
+ load_path := "" :: (List.rev !Clflags.include_dirs @ !load_path);
+ Dll.add_path !load_path
+
+let initialize_toplevel_env () =
+ toplevel_env := Compmisc.initial_env()
+
+(* The interactive loop *)
+
+exception PPerror
+
+let loop ppf =
+ Location.formatter_for_warnings := ppf;
+ fprintf ppf " OCaml version %s@.@." Config.version;
+ initialize_toplevel_env ();
+ let lb = Lexing.from_function refill_lexbuf in
+ Location.init lb "//toplevel//";
+ Location.input_name := "//toplevel//";
+ Location.input_lexbuf := Some lb;
+ Sys.catch_break true;
+ load_ocamlinit ppf;
+ while true do
+ let snap = Btype.snapshot () in
+ try
+ Lexing.flush_input lb;
+ Location.reset();
+ first_line := true;
+ let phr = try !parse_toplevel_phrase lb with Exit -> raise PPerror in
+ let phr = preprocess_phrase ppf phr in
+ Env.reset_cache_toplevel ();
+ ignore(execute_phrase true ppf phr)
+ with
+ | End_of_file -> exit 0
+ | Sys.Break -> fprintf ppf "Interrupted.@."; Btype.backtrack snap
+ | PPerror -> ()
+ | x -> Location.report_exception ppf x; Btype.backtrack snap
+ done
+
+(* Execute a script. If [name] is "", read the script from stdin. *)
+
+let run_script ppf name args =
+ let len = Array.length args in
+ if Array.length Sys.argv < len then invalid_arg "Toploop.run_script";
+ Array.blit args 0 Sys.argv 0 len;
+ Obj.truncate (Obj.repr Sys.argv) len;
+ Arg.current := 0;
+ Compmisc.init_path ~dir:(Filename.dirname name) true;
+ (* Note: would use [Filename.abspath] here, if we had it. *)
+ toplevel_env := Compmisc.initial_env();
+ Sys.interactive := false;
+ let explicit_name =
+ (* Prevent use_silently from searching in the path. *)
+ if Filename.is_implicit name
+ then Filename.concat Filename.current_dir_name name
+ else name
+ in
+ use_silently ppf explicit_name
diff --git a/toplevel/toploop.mli b/toplevel/toploop.mli
new file mode 100644
index 0000000000..f0d5c40960
--- /dev/null
+++ b/toplevel/toploop.mli
@@ -0,0 +1,130 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+(* Accessors for the table of toplevel value bindings. These functions
+ must appear as first and second exported functions in this module.
+ (See module Translmod.) *)
+val getvalue : string -> Obj.t
+val setvalue : string -> Obj.t -> unit
+
+(* Set the load paths, before running anything *)
+
+val set_paths : unit -> unit
+
+(* The interactive toplevel loop *)
+
+val loop : formatter -> unit
+
+(* Read and execute a script from the given file *)
+
+val run_script : formatter -> string -> string array -> bool
+ (* true if successful, false if error *)
+
+(* Interface with toplevel directives *)
+
+type directive_fun =
+ | Directive_none of (unit -> unit)
+ | Directive_string of (string -> unit)
+ | Directive_int of (int -> unit)
+ | Directive_ident of (Longident.t -> unit)
+ | Directive_bool of (bool -> unit)
+
+val directive_table : (string, directive_fun) Hashtbl.t
+ (* Table of known directives, with their execution function *)
+val toplevel_env : Env.t ref
+ (* Typing environment for the toplevel *)
+val initialize_toplevel_env : unit -> unit
+ (* Initialize the typing environment for the toplevel *)
+val print_exception_outcome : formatter -> exn -> unit
+ (* Print an exception resulting from the evaluation of user code. *)
+val execute_phrase : bool -> formatter -> Parsetree.toplevel_phrase -> bool
+ (* Execute the given toplevel phrase. Return [true] if the
+ phrase executed with no errors and [false] otherwise.
+ First bool says whether the values and types of the results
+ should be printed. Uncaught exceptions are always printed. *)
+val preprocess_phrase :
+ formatter -> Parsetree.toplevel_phrase -> Parsetree.toplevel_phrase
+ (* Preprocess the given toplevel phrase using regular and ppx
+ preprocessors. Return the updated phrase. *)
+val use_file : formatter -> string -> bool
+val use_silently : formatter -> string -> bool
+val mod_use_file : formatter -> string -> bool
+ (* Read and execute commands from a file.
+ [use_file] prints the types and values of the results.
+ [use_silently] does not print them.
+ [mod_use_file] wrap the file contents into a module. *)
+val eval_path: Env.t -> Path.t -> Obj.t
+ (* Return the toplevel object referred to by the given path *)
+val record_backtrace : unit -> unit
+
+(* Printing of values *)
+
+val print_value: Env.t -> Obj.t -> formatter -> Types.type_expr -> unit
+val print_untyped_exception: formatter -> Obj.t -> unit
+
+type ('a, 'b) gen_printer =
+ | Zero of 'b
+ | Succ of ('a -> ('a, 'b) gen_printer)
+
+val install_printer :
+ Path.t -> Types.type_expr -> (formatter -> Obj.t -> unit) -> unit
+val install_generic_printer :
+ Path.t -> Path.t ->
+ (int -> (int -> Obj.t -> Outcometree.out_value,
+ Obj.t -> Outcometree.out_value) gen_printer) -> unit
+val install_generic_printer' :
+ Path.t -> Path.t -> (formatter -> Obj.t -> unit,
+ formatter -> Obj.t -> unit) gen_printer -> unit
+val remove_printer : Path.t -> unit
+
+val max_printer_depth: int ref
+val max_printer_steps: int ref
+
+(* Hooks for external parsers and printers *)
+
+val parse_toplevel_phrase : (Lexing.lexbuf -> Parsetree.toplevel_phrase) ref
+val parse_use_file : (Lexing.lexbuf -> Parsetree.toplevel_phrase list) ref
+val print_location : formatter -> Location.t -> unit
+val print_error : formatter -> Location.t -> unit
+val print_warning : Location.t -> formatter -> Warnings.t -> unit
+val input_name : string ref
+
+val print_out_value :
+ (formatter -> Outcometree.out_value -> unit) ref
+val print_out_type :
+ (formatter -> Outcometree.out_type -> unit) ref
+val print_out_class_type :
+ (formatter -> Outcometree.out_class_type -> unit) ref
+val print_out_module_type :
+ (formatter -> Outcometree.out_module_type -> unit) ref
+val print_out_type_extension :
+ (formatter -> Outcometree.out_type_extension -> unit) ref
+val print_out_sig_item :
+ (formatter -> Outcometree.out_sig_item -> unit) ref
+val print_out_signature :
+ (formatter -> Outcometree.out_sig_item list -> unit) ref
+val print_out_phrase :
+ (formatter -> Outcometree.out_phrase -> unit) ref
+
+(* Hooks for external line editor *)
+
+val read_interactive_input : (string -> bytes -> int -> int * bool) ref
+
+(* Hooks for initialization *)
+
+val toplevel_startup_hook : (unit -> unit) ref
+
+(* Used by Trace module *)
+
+val may_trace : bool ref
diff --git a/toplevel/topmain.ml b/toplevel/topmain.ml
new file mode 100644
index 0000000000..0d8f2d4c21
--- /dev/null
+++ b/toplevel/topmain.ml
@@ -0,0 +1,111 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Clflags
+open Compenv
+
+let usage = "Usage: ocaml <options> <object-files> [script-file [arguments]]\n\
+ options are:"
+
+let preload_objects = ref []
+
+let prepare ppf =
+ Toploop.set_paths ();
+ try
+ let res =
+ List.for_all (Topdirs.load_file ppf) (List.rev !preload_objects) in
+ !Toploop.toplevel_startup_hook ();
+ res
+ with x ->
+ try Location.report_exception ppf x; false
+ with x ->
+ Format.fprintf ppf "Uncaught exception: %s\n" (Printexc.to_string x);
+ false
+
+(* If [name] is "", then the "file" is stdin treated as a script file. *)
+let file_argument name =
+ let ppf = Format.err_formatter in
+ if Filename.check_suffix name ".cmo" || Filename.check_suffix name ".cma"
+ then preload_objects := name :: !preload_objects
+ else
+ begin
+ let newargs = Array.sub Sys.argv !Arg.current
+ (Array.length Sys.argv - !Arg.current)
+ in
+ Compenv.readenv ppf Before_link;
+ if prepare ppf && Toploop.run_script ppf name newargs
+ then exit 0
+ else exit 2
+ end
+
+let print_version () =
+ Printf.printf "The OCaml toplevel, version %s\n" Sys.ocaml_version;
+ exit 0;
+;;
+
+let print_version_num () =
+ Printf.printf "%s\n" Sys.ocaml_version;
+ exit 0;
+;;
+
+module Options = Main_args.Make_bytetop_options (struct
+ let set r () = r := true
+ let clear r () = r := false
+
+ let _absname = set Location.absname
+ let _I dir =
+ let dir = Misc.expand_directory Config.standard_library dir in
+ include_dirs := dir :: !include_dirs
+ let _init s = init_file := Some s
+ let _noinit = set noinit
+ let _labels = clear classic
+ let _no_alias_deps = set transparent_modules
+ let _no_app_funct = clear applicative_functors
+ let _noassert = set noassert
+ let _nolabels = set classic
+ let _noprompt = set noprompt
+ let _nopromptcont = set nopromptcont
+ let _nostdlib = set no_std_include
+ let _open s = open_modules := s :: !open_modules
+ let _ppx s = first_ppx := s :: !first_ppx
+ let _principal = set principal
+ let _rectypes = set recursive_types
+ let _safe_string = clear unsafe_string
+ let _short_paths = clear real_paths
+ let _stdin () = file_argument ""
+ let _strict_sequence = set strict_sequence
+ let _strict_formats = set strict_formats
+ let _unsafe = set fast
+ let _unsafe_string = set unsafe_string
+ let _version () = print_version ()
+ let _vnum () = print_version_num ()
+ let _w s = Warnings.parse_options false s
+ let _warn_error s = Warnings.parse_options true s
+ let _warn_help = Warnings.help_warnings
+ let _dparsetree = set dump_parsetree
+ let _dtypedtree = set dump_typedtree
+ let _dsource = set dump_source
+ let _drawlambda = set dump_rawlambda
+ let _dlambda = set dump_lambda
+ let _dinstr = set dump_instr
+
+ let anonymous s = file_argument s
+end);;
+
+
+let main () =
+ let ppf = Format.err_formatter in
+ Compenv.readenv ppf Before_args;
+ Arg.parse Options.list file_argument usage;
+ Compenv.readenv ppf Before_link;
+ if not (prepare ppf) then exit 2;
+ Toploop.loop Format.std_formatter
diff --git a/toplevel/topmain.mli b/toplevel/topmain.mli
new file mode 100644
index 0000000000..74044e5149
--- /dev/null
+++ b/toplevel/topmain.mli
@@ -0,0 +1,15 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Start the [ocaml] toplevel loop *)
+
+val main: unit -> unit
diff --git a/toplevel/topstart.ml b/toplevel/topstart.ml
new file mode 100644
index 0000000000..f03e2aa6a8
--- /dev/null
+++ b/toplevel/topstart.ml
@@ -0,0 +1,13 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+let _ = Topmain.main()
diff --git a/toplevel/trace.ml b/toplevel/trace.ml
new file mode 100644
index 0000000000..8c5fabecca
--- /dev/null
+++ b/toplevel/trace.ml
@@ -0,0 +1,147 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The "trace" facility *)
+
+open Format
+open Misc
+open Longident
+open Types
+open Toploop
+
+type codeptr = Obj.t
+
+type traced_function =
+ { path: Path.t; (* Name under which it is traced *)
+ closure: Obj.t; (* Its function closure (patched) *)
+ actual_code: codeptr; (* Its original code pointer *)
+ instrumented_fun: codeptr -> Obj.t -> Obj.t -> Obj.t }
+ (* Printing function *)
+
+let traced_functions = ref ([] : traced_function list)
+
+(* Check if a function is already traced *)
+
+let is_traced clos =
+ let rec is_traced = function
+ [] -> None
+ | tf :: rem -> if tf.closure == clos then Some tf.path else is_traced rem
+ in is_traced !traced_functions
+
+(* Get or overwrite the code pointer of a closure *)
+
+let get_code_pointer cls = Obj.field cls 0
+
+let set_code_pointer cls ptr = Obj.set_field cls 0 ptr
+
+(* Call a traced function (use old code pointer, but new closure as
+ environment so that recursive calls are also traced).
+ It is necessary to wrap Meta.invoke_traced_function in an ML function
+ so that the RETURN at the end of the ML wrapper takes us to the
+ code of the function. *)
+
+let invoke_traced_function codeptr env arg =
+ Meta.invoke_traced_function codeptr env arg
+
+let print_label ppf l =
+ if l <> Asttypes.Nolabel then fprintf ppf "%s:" (Printtyp.string_of_label l)
+
+(* If a function returns a functional value, wrap it into a trace code *)
+
+let rec instrument_result env name ppf clos_typ =
+ match (Ctype.repr(Ctype.expand_head env clos_typ)).desc with
+ | Tarrow(l, t1, t2, _) ->
+ let starred_name =
+ match name with
+ | Lident s -> Lident(s ^ "*")
+ | Ldot(lid, s) -> Ldot(lid, s ^ "*")
+ | Lapply(l1, l2) -> fatal_error "Trace.instrument_result" in
+ let trace_res = instrument_result env starred_name ppf t2 in
+ (fun clos_val ->
+ Obj.repr (fun arg ->
+ if not !may_trace then
+ (Obj.magic clos_val : Obj.t -> Obj.t) arg
+ else begin
+ may_trace := false;
+ try
+ fprintf ppf "@[<2>%a <--@ %a%a@]@."
+ Printtyp.longident starred_name
+ print_label l
+ (print_value !toplevel_env arg) t1;
+ may_trace := true;
+ let res = (Obj.magic clos_val : Obj.t -> Obj.t) arg in
+ may_trace := false;
+ fprintf ppf "@[<2>%a -->@ %a@]@."
+ Printtyp.longident starred_name
+ (print_value !toplevel_env res) t2;
+ may_trace := true;
+ trace_res res
+ with exn ->
+ may_trace := false;
+ fprintf ppf "@[<2>%a raises@ %a@]@."
+ Printtyp.longident starred_name
+ (print_value !toplevel_env (Obj.repr exn)) Predef.type_exn;
+ may_trace := true;
+ raise exn
+ end))
+ | _ -> (fun v -> v)
+
+(* Same as instrument_result, but for a toplevel closure (modified in place) *)
+
+exception Dummy
+let _ = Dummy
+
+let instrument_closure env name ppf clos_typ =
+ match (Ctype.repr(Ctype.expand_head env clos_typ)).desc with
+ | Tarrow(l, t1, t2, _) ->
+ let trace_res = instrument_result env name ppf t2 in
+ (fun actual_code closure arg ->
+ if not !may_trace then begin
+ try invoke_traced_function actual_code closure arg
+ with Dummy -> assert false
+ (* do not remove handler, prevents tail-call to invoke_traced_ *)
+ end else begin
+ may_trace := false;
+ try
+ fprintf ppf "@[<2>%a <--@ %a%a@]@."
+ Printtyp.longident name
+ print_label l
+ (print_value !toplevel_env arg) t1;
+ may_trace := true;
+ let res = invoke_traced_function actual_code closure arg in
+ may_trace := false;
+ fprintf ppf "@[<2>%a -->@ %a@]@."
+ Printtyp.longident name
+ (print_value !toplevel_env res) t2;
+ may_trace := true;
+ trace_res res
+ with exn ->
+ may_trace := false;
+ fprintf ppf "@[<2>%a raises@ %a@]@."
+ Printtyp.longident name
+ (print_value !toplevel_env (Obj.repr exn)) Predef.type_exn;
+ may_trace := true;
+ raise exn
+ end)
+ | _ -> assert false
+
+(* Given the address of a closure, find its tracing info *)
+
+let rec find_traced_closure clos = function
+ | [] -> fatal_error "Trace.find_traced_closure"
+ | f :: rem -> if f.closure == clos then f else find_traced_closure clos rem
+
+(* Trace the application of an (instrumented) closure to an argument *)
+
+let print_trace clos arg =
+ let f = find_traced_closure clos !traced_functions in
+ f.instrumented_fun f.actual_code clos arg
diff --git a/toplevel/trace.mli b/toplevel/trace.mli
new file mode 100644
index 0000000000..41c119e666
--- /dev/null
+++ b/toplevel/trace.mli
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* The "trace" facility *)
+
+open Format
+
+type codeptr
+
+type traced_function =
+ { path: Path.t; (* Name under which it is traced *)
+ closure: Obj.t; (* Its function closure (patched) *)
+ actual_code: codeptr; (* Its original code pointer *)
+ instrumented_fun: codeptr -> Obj.t -> Obj.t -> Obj.t }
+ (* Printing function *)
+
+val traced_functions: traced_function list ref
+val is_traced: Obj.t -> Path.t option
+val get_code_pointer: Obj.t -> codeptr
+val set_code_pointer: Obj.t -> codeptr -> unit
+val instrument_closure:
+ Env.t -> Longident.t -> formatter -> Types.type_expr ->
+ codeptr -> Obj.t -> Obj.t -> Obj.t
+val print_trace: Obj.t -> Obj.t -> Obj.t
diff --git a/typing/annot.mli b/typing/annot.mli
new file mode 100644
index 0000000000..f75d4c1996
--- /dev/null
+++ b/typing/annot.mli
@@ -0,0 +1,21 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Gallium, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Data types for annotations (Stypes.ml) *)
+
+type call = Tail | Stack | Inline;;
+
+type ident =
+ | Iref_internal of Location.t (* defining occurrence *)
+ | Iref_external
+ | Idef of Location.t (* scope *)
+;;
diff --git a/typing/btype.ml b/typing/btype.ml
new file mode 100644
index 0000000000..7627913c9e
--- /dev/null
+++ b/typing/btype.ml
@@ -0,0 +1,691 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Jerome Vouillon, projet Cristal, INRIA Rocquencourt*)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Basic operations on core types *)
+
+open Misc
+open Asttypes
+open Types
+
+(**** Sets, maps and hashtables of types ****)
+
+module TypeSet = Set.Make(TypeOps)
+module TypeMap = Map.Make (TypeOps)
+module TypeHash = Hashtbl.Make(TypeOps)
+
+(**** Forward declarations ****)
+
+let print_raw =
+ ref (fun _ -> assert false : Format.formatter -> type_expr -> unit)
+
+(**** Type level management ****)
+
+let generic_level = 100000000
+
+(* Used to mark a type during a traversal. *)
+let lowest_level = 0
+let pivot_level = 2 * lowest_level - 1
+ (* pivot_level - lowest_level < lowest_level *)
+
+(**** Some type creators ****)
+
+let new_id = ref (-1)
+
+let newty2 level desc =
+ incr new_id; { desc; level; id = !new_id }
+let newgenty desc = newty2 generic_level desc
+let newgenvar ?name () = newgenty (Tvar name)
+(*
+let newmarkedvar level =
+ incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id }
+let newmarkedgenvar () =
+ incr new_id;
+ { desc = Tvar; level = pivot_level - generic_level; id = !new_id }
+*)
+
+(**** Check some types ****)
+
+let is_Tvar = function {desc=Tvar _} -> true | _ -> false
+let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false
+
+let dummy_method = "*dummy method*"
+let default_mty = function
+ Some mty -> mty
+ | None -> Mty_signature []
+
+(**** Representative of a type ****)
+
+let rec field_kind_repr =
+ function
+ Fvar {contents = Some kind} -> field_kind_repr kind
+ | kind -> kind
+
+let rec repr =
+ function
+ {desc = Tlink t'} ->
+ (*
+ We do no path compression. Path compression does not seem to
+ improve notably efficiency, and it prevents from changing a
+ [Tlink] into another type (for instance, for undoing a
+ unification).
+ *)
+ repr t'
+ | {desc = Tfield (_, k, _, t')} when field_kind_repr k = Fabsent ->
+ repr t'
+ | t -> t
+
+let rec commu_repr = function
+ Clink r when !r <> Cunknown -> commu_repr !r
+ | c -> c
+
+let rec row_field_repr_aux tl = function
+ Reither(_, tl', _, {contents = Some fi}) ->
+ row_field_repr_aux (tl@tl') fi
+ | Reither(c, tl', m, r) ->
+ Reither(c, tl@tl', m, r)
+ | Rpresent (Some _) when tl <> [] ->
+ Rpresent (Some (List.hd tl))
+ | fi -> fi
+
+let row_field_repr fi = row_field_repr_aux [] fi
+
+let rec rev_concat l ll =
+ match ll with
+ [] -> l
+ | l'::ll -> rev_concat (l'@l) ll
+
+let rec row_repr_aux ll row =
+ match (repr row.row_more).desc with
+ | Tvariant row' ->
+ let f = row.row_fields in
+ row_repr_aux (if f = [] then ll else f::ll) row'
+ | _ ->
+ if ll = [] then row else
+ {row with row_fields = rev_concat row.row_fields ll}
+
+let row_repr row = row_repr_aux [] row
+
+let rec row_field tag row =
+ let rec find = function
+ | (tag',f) :: fields ->
+ if tag = tag' then row_field_repr f else find fields
+ | [] ->
+ match repr row.row_more with
+ | {desc=Tvariant row'} -> row_field tag row'
+ | _ -> Rabsent
+ in find row.row_fields
+
+let rec row_more row =
+ match repr row.row_more with
+ | {desc=Tvariant row'} -> row_more row'
+ | ty -> ty
+
+let row_fixed row =
+ let row = row_repr row in
+ row.row_fixed ||
+ match (repr row.row_more).desc with
+ Tvar _ | Tnil -> false
+ | Tunivar _ | Tconstr _ -> true
+ | _ -> assert false
+
+let static_row row =
+ let row = row_repr row in
+ row.row_closed &&
+ List.for_all
+ (fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true)
+ row.row_fields
+
+let hash_variant s =
+ let accu = ref 0 in
+ for i = 0 to String.length s - 1 do
+ accu := 223 * !accu + Char.code s.[i]
+ done;
+ (* reduce to 31 bits *)
+ accu := !accu land (1 lsl 31 - 1);
+ (* make it signed for 64 bits architectures *)
+ if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu
+
+let proxy ty =
+ let ty0 = repr ty in
+ match ty0.desc with
+ | Tvariant row when not (static_row row) ->
+ row_more row
+ | Tobject (ty, _) ->
+ let rec proxy_obj ty =
+ match ty.desc with
+ Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty
+ | Tvar _ | Tunivar _ | Tconstr _ -> ty
+ | Tnil -> ty0
+ | _ -> assert false
+ in proxy_obj ty
+ | _ -> ty0
+
+(**** Utilities for fixed row private types ****)
+
+let has_constr_row t =
+ match (repr t).desc with
+ Tobject(t,_) ->
+ let rec check_row t =
+ match (repr t).desc with
+ Tfield(_,_,_,t) -> check_row t
+ | Tconstr _ -> true
+ | _ -> false
+ in check_row t
+ | Tvariant row ->
+ (match row_more row with {desc=Tconstr _} -> true | _ -> false)
+ | _ ->
+ false
+
+let is_row_name s =
+ let l = String.length s in
+ if l < 4 then false else String.sub s (l-4) 4 = "#row"
+
+let is_constr_row t =
+ match t.desc with
+ Tconstr (Path.Pident id, _, _) -> is_row_name (Ident.name id)
+ | Tconstr (Path.Pdot (_, s, _), _, _) -> is_row_name s
+ | _ -> false
+
+
+ (**********************************)
+ (* Utilities for type traversal *)
+ (**********************************)
+
+let rec iter_row f row =
+ List.iter
+ (fun (_, fi) ->
+ match row_field_repr fi with
+ | Rpresent(Some ty) -> f ty
+ | Reither(_, tl, _, _) -> List.iter f tl
+ | _ -> ())
+ row.row_fields;
+ match (repr row.row_more).desc with
+ Tvariant row -> iter_row f row
+ | Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ | Tnil ->
+ Misc.may (fun (_,l) -> List.iter f l) row.row_name
+ | _ -> assert false
+
+let iter_type_expr f ty =
+ match ty.desc with
+ Tvar _ -> ()
+ | Tarrow (_, ty1, ty2, _) -> f ty1; f ty2
+ | Ttuple l -> List.iter f l
+ | Tconstr (_, l, _) -> List.iter f l
+ | Tobject(ty, {contents = Some (_, p)})
+ -> f ty; List.iter f p
+ | Tobject (ty, _) -> f ty
+ | Tvariant row -> iter_row f row; f (row_more row)
+ | Tfield (_, _, ty1, ty2) -> f ty1; f ty2
+ | Tnil -> ()
+ | Tlink ty -> f ty
+ | Tsubst ty -> f ty
+ | Tunivar _ -> ()
+ | Tpoly (ty, tyl) -> f ty; List.iter f tyl
+ | Tpackage (_, _, l) -> List.iter f l
+
+let rec iter_abbrev f = function
+ Mnil -> ()
+ | Mcons(_, _, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem
+ | Mlink rem -> iter_abbrev f !rem
+
+type type_iterators =
+ { it_signature: type_iterators -> signature -> unit;
+ it_signature_item: type_iterators -> signature_item -> unit;
+ it_value_description: type_iterators -> value_description -> unit;
+ it_type_declaration: type_iterators -> type_declaration -> unit;
+ it_extension_constructor: type_iterators -> extension_constructor -> unit;
+ it_module_declaration: type_iterators -> module_declaration -> unit;
+ it_modtype_declaration: type_iterators -> modtype_declaration -> unit;
+ it_class_declaration: type_iterators -> class_declaration -> unit;
+ it_class_type_declaration: type_iterators -> class_type_declaration -> unit;
+ it_module_type: type_iterators -> module_type -> unit;
+ it_class_type: type_iterators -> class_type -> unit;
+ it_type_kind: type_iterators -> type_kind -> unit;
+ it_do_type_expr: type_iterators -> type_expr -> unit;
+ it_type_expr: type_iterators -> type_expr -> unit;
+ it_path: Path.t -> unit; }
+
+let iter_type_expr_cstr_args f = function
+ | Cstr_tuple tl -> List.iter f tl
+ | Cstr_record lbls -> List.iter (fun d -> f d.ld_type) lbls
+
+let map_type_expr_cstr_args f = function
+ | Cstr_tuple tl -> Cstr_tuple (List.map f tl)
+ | Cstr_record lbls ->
+ Cstr_record (List.map (fun d -> {d with ld_type=f d.ld_type}) lbls)
+
+let iter_type_expr_kind f = function
+ | Type_abstract -> ()
+ | Type_variant cstrs ->
+ List.iter
+ (fun cd ->
+ iter_type_expr_cstr_args f cd.cd_args;
+ Misc.may f cd.cd_res
+ )
+ cstrs
+ | Type_record(lbls, _) ->
+ List.iter (fun d -> f d.ld_type) lbls
+ | Type_open ->
+ ()
+
+
+let type_iterators =
+ let it_signature it =
+ List.iter (it.it_signature_item it)
+ and it_signature_item it = function
+ Sig_value (_, vd) -> it.it_value_description it vd
+ | Sig_type (_, td, _) -> it.it_type_declaration it td
+ | Sig_typext (_, td, _) -> it.it_extension_constructor it td
+ | Sig_module (_, md, _) -> it.it_module_declaration it md
+ | Sig_modtype (_, mtd) -> it.it_modtype_declaration it mtd
+ | Sig_class (_, cd, _) -> it.it_class_declaration it cd
+ | Sig_class_type (_, ctd, _) -> it.it_class_type_declaration it ctd
+ and it_value_description it vd =
+ it.it_type_expr it vd.val_type
+ and it_type_declaration it td =
+ List.iter (it.it_type_expr it) td.type_params;
+ may (it.it_type_expr it) td.type_manifest;
+ it.it_type_kind it td.type_kind
+ and it_extension_constructor it td =
+ it.it_path td.ext_type_path;
+ List.iter (it.it_type_expr it) td.ext_type_params;
+ iter_type_expr_cstr_args (it.it_type_expr it) td.ext_args;
+ may (it.it_type_expr it) td.ext_ret_type
+ and it_module_declaration it md =
+ it.it_module_type it md.md_type
+ and it_modtype_declaration it mtd =
+ may (it.it_module_type it) mtd.mtd_type
+ and it_class_declaration it cd =
+ List.iter (it.it_type_expr it) cd.cty_params;
+ it.it_class_type it cd.cty_type;
+ may (it.it_type_expr it) cd.cty_new;
+ it.it_path cd.cty_path
+ and it_class_type_declaration it ctd =
+ List.iter (it.it_type_expr it) ctd.clty_params;
+ it.it_class_type it ctd.clty_type;
+ it.it_path ctd.clty_path
+ and it_module_type it = function
+ Mty_ident p
+ | Mty_alias p -> it.it_path p
+ | Mty_signature sg -> it.it_signature it sg
+ | Mty_functor (_, mto, mt) ->
+ may (it.it_module_type it) mto;
+ it.it_module_type it mt
+ and it_class_type it = function
+ Cty_constr (p, tyl, cty) ->
+ it.it_path p;
+ List.iter (it.it_type_expr it) tyl;
+ it.it_class_type it cty
+ | Cty_signature cs ->
+ it.it_type_expr it cs.csig_self;
+ Vars.iter (fun _ (_,_,ty) -> it.it_type_expr it ty) cs.csig_vars;
+ List.iter
+ (fun (p, tl) -> it.it_path p; List.iter (it.it_type_expr it) tl)
+ cs.csig_inher
+ | Cty_arrow (_, ty, cty) ->
+ it.it_type_expr it ty;
+ it.it_class_type it cty
+ and it_type_kind it kind =
+ iter_type_expr_kind (it.it_type_expr it) kind
+ and it_do_type_expr it ty =
+ iter_type_expr (it.it_type_expr it) ty;
+ match ty.desc with
+ Tconstr (p, _, _)
+ | Tobject (_, {contents=Some (p, _)})
+ | Tpackage (p, _, _) ->
+ it.it_path p
+ | Tvariant row ->
+ may (fun (p,_) -> it.it_path p) (row_repr row).row_name
+ | _ -> ()
+ and it_path p = ()
+ in
+ { it_path; it_type_expr = it_do_type_expr; it_do_type_expr;
+ it_type_kind; it_class_type; it_module_type;
+ it_signature; it_class_type_declaration; it_class_declaration;
+ it_modtype_declaration; it_module_declaration; it_extension_constructor;
+ it_type_declaration; it_value_description; it_signature_item; }
+
+let copy_row f fixed row keep more =
+ let fields = List.map
+ (fun (l, fi) -> l,
+ match row_field_repr fi with
+ | Rpresent(Some ty) -> Rpresent(Some(f ty))
+ | Reither(c, tl, m, e) ->
+ let e = if keep then e else ref None in
+ let m = if row.row_fixed then fixed else m in
+ let tl = List.map f tl in
+ Reither(c, tl, m, e)
+ | _ -> fi)
+ row.row_fields in
+ let name =
+ match row.row_name with None -> None
+ | Some (path, tl) -> Some (path, List.map f tl) in
+ { row_fields = fields; row_more = more;
+ row_bound = (); row_fixed = row.row_fixed && fixed;
+ row_closed = row.row_closed; row_name = name; }
+
+let rec copy_kind = function
+ Fvar{contents = Some k} -> copy_kind k
+ | Fvar _ -> Fvar (ref None)
+ | Fpresent -> Fpresent
+ | Fabsent -> assert false
+
+let copy_commu c =
+ if commu_repr c = Cok then Cok else Clink (ref Cunknown)
+
+(* Since univars may be used as row variables, we need to do some
+ encoding during substitution *)
+let rec norm_univar ty =
+ match ty.desc with
+ Tunivar _ | Tsubst _ -> ty
+ | Tlink ty -> norm_univar ty
+ | Ttuple (ty :: _) -> norm_univar ty
+ | _ -> assert false
+
+let rec copy_type_desc ?(keep_names=false) f = function
+ Tvar _ as ty -> if keep_names then ty else Tvar None
+ | Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c)
+ | Ttuple l -> Ttuple (List.map f l)
+ | Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil)
+ | Tobject(ty, {contents = Some (p, tl)})
+ -> Tobject (f ty, ref (Some(p, List.map f tl)))
+ | Tobject (ty, _) -> Tobject (f ty, ref None)
+ | Tvariant row -> assert false (* too ambiguous *)
+ | Tfield (p, k, ty1, ty2) -> (* the kind is kept shared *)
+ Tfield (p, field_kind_repr k, f ty1, f ty2)
+ | Tnil -> Tnil
+ | Tlink ty -> copy_type_desc f ty.desc
+ | Tsubst ty -> assert false
+ | Tunivar _ as ty -> ty (* always keep the name *)
+ | Tpoly (ty, tyl) ->
+ let tyl = List.map (fun x -> norm_univar (f x)) tyl in
+ Tpoly (f ty, tyl)
+ | Tpackage (p, n, l) -> Tpackage (p, n, List.map f l)
+
+(* Utilities for copying *)
+
+let saved_desc = ref []
+ (* Saved association of generic nodes with their description. *)
+
+let save_desc ty desc =
+ saved_desc := (ty, desc)::!saved_desc
+
+let saved_kinds = ref [] (* duplicated kind variables *)
+let new_kinds = ref [] (* new kind variables *)
+let dup_kind r =
+ (match !r with None -> () | Some _ -> assert false);
+ if not (List.memq r !new_kinds) then begin
+ saved_kinds := r :: !saved_kinds;
+ let r' = ref None in
+ new_kinds := r' :: !new_kinds;
+ r := Some (Fvar r')
+ end
+
+(* Restored type descriptions. *)
+let cleanup_types () =
+ List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc;
+ List.iter (fun r -> r := None) !saved_kinds;
+ saved_desc := []; saved_kinds := []; new_kinds := []
+
+(* Mark a type. *)
+let rec mark_type ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ iter_type_expr mark_type ty
+ end
+
+let mark_type_node ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ end
+
+let mark_type_params ty =
+ iter_type_expr mark_type ty
+
+let type_iterators =
+ let it_type_expr it ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ mark_type_node ty;
+ it.it_do_type_expr it ty;
+ end
+ in
+ {type_iterators with it_type_expr}
+
+
+(* Remove marks from a type. *)
+let rec unmark_type ty =
+ let ty = repr ty in
+ if ty.level < lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ iter_type_expr unmark_type ty
+ end
+
+let unmark_iterators =
+ let it_type_expr it ty = unmark_type ty in
+ {type_iterators with it_type_expr}
+
+let unmark_type_decl decl =
+ unmark_iterators.it_type_declaration unmark_iterators decl
+
+let unmark_extension_constructor ext =
+ List.iter unmark_type ext.ext_type_params;
+ iter_type_expr_cstr_args unmark_type ext.ext_args;
+ Misc.may unmark_type ext.ext_ret_type
+
+let unmark_class_signature sign =
+ unmark_type sign.csig_self;
+ Vars.iter (fun l (m, v, t) -> unmark_type t) sign.csig_vars
+
+let unmark_class_type cty =
+ unmark_iterators.it_class_type unmark_iterators cty
+
+
+ (*******************************************)
+ (* Memorization of abbreviation expansion *)
+ (*******************************************)
+
+(* Search whether the expansion has been memorized. *)
+let rec find_expans priv p1 = function
+ Mnil -> None
+ | Mcons (priv', p2, ty0, ty, _)
+ when priv' >= priv && Path.same p1 p2 -> Some ty
+ | Mcons (_, _, _, _, rem) -> find_expans priv p1 rem
+ | Mlink {contents = rem} -> find_expans priv p1 rem
+
+(* debug: check for cycles in abbreviation. only works with -principal
+let rec check_expans visited ty =
+ let ty = repr ty in
+ assert (not (List.memq ty visited));
+ match ty.desc with
+ Tconstr (path, args, abbrev) ->
+ begin match find_expans path !abbrev with
+ Some ty' -> check_expans (ty :: visited) ty'
+ | None -> ()
+ end
+ | _ -> ()
+*)
+
+let memo = ref []
+ (* Contains the list of saved abbreviation expansions. *)
+
+let cleanup_abbrev () =
+ (* Remove all memorized abbreviation expansions. *)
+ List.iter (fun abbr -> abbr := Mnil) !memo;
+ memo := []
+
+let memorize_abbrev mem priv path v v' =
+ (* Memorize the expansion of an abbreviation. *)
+ mem := Mcons (priv, path, v, v', !mem);
+ (* check_expans [] v; *)
+ memo := mem :: !memo
+
+let rec forget_abbrev_rec mem path =
+ match mem with
+ Mnil ->
+ assert false
+ | Mcons (_, path', _, _, rem) when Path.same path path' ->
+ rem
+ | Mcons (priv, path', v, v', rem) ->
+ Mcons (priv, path', v, v', forget_abbrev_rec rem path)
+ | Mlink mem' ->
+ mem' := forget_abbrev_rec !mem' path;
+ raise Exit
+
+let forget_abbrev mem path =
+ try mem := forget_abbrev_rec !mem path with Exit -> ()
+
+(* debug: check for invalid abbreviations
+let rec check_abbrev_rec = function
+ Mnil -> true
+ | Mcons (_, ty1, ty2, rem) ->
+ repr ty1 != repr ty2
+ | Mlink mem' ->
+ check_abbrev_rec !mem'
+
+let check_memorized_abbrevs () =
+ List.for_all (fun mem -> check_abbrev_rec !mem) !memo
+*)
+
+ (**********************************)
+ (* Utilities for labels *)
+ (**********************************)
+
+let is_optional = function Optional _ -> true | _ -> false
+
+let label_name = function
+ Nolabel -> ""
+ | Labelled s
+ | Optional s -> s
+
+let prefixed_label_name = function
+ Nolabel -> ""
+ | Labelled s -> "~" ^ s
+ | Optional s -> "?" ^ s
+
+let rec extract_label_aux hd l = function
+ [] -> raise Not_found
+ | (l',t as p) :: ls ->
+ if label_name l' = l then (l', t, List.rev hd, ls)
+ else extract_label_aux (p::hd) l ls
+
+let extract_label l ls = extract_label_aux [] l ls
+
+
+ (**********************************)
+ (* Utilities for backtracking *)
+ (**********************************)
+
+type change =
+ Ctype of type_expr * type_desc
+ | Clevel of type_expr * int
+ | Cname of
+ (Path.t * type_expr list) option ref * (Path.t * type_expr list) option
+ | Crow of row_field option ref * row_field option
+ | Ckind of field_kind option ref * field_kind option
+ | Ccommu of commutable ref * commutable
+ | Cuniv of type_expr option ref * type_expr option
+ | Ctypeset of TypeSet.t ref * TypeSet.t
+
+let undo_change = function
+ Ctype (ty, desc) -> ty.desc <- desc
+ | Clevel (ty, level) -> ty.level <- level
+ | Cname (r, v) -> r := v
+ | Crow (r, v) -> r := v
+ | Ckind (r, v) -> r := v
+ | Ccommu (r, v) -> r := v
+ | Cuniv (r, v) -> r := v
+ | Ctypeset (r, v) -> r := v
+
+type changes =
+ Change of change * changes ref
+ | Unchanged
+ | Invalid
+
+type snapshot = changes ref * int
+
+let trail = Weak.create 1
+let last_snapshot = ref 0
+
+let log_change ch =
+ match Weak.get trail 0 with None -> ()
+ | Some r ->
+ let r' = ref Unchanged in
+ r := Change (ch, r');
+ Weak.set trail 0 (Some r')
+
+let log_type ty =
+ if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc))
+let link_type ty ty' =
+ log_type ty;
+ let desc = ty.desc in
+ ty.desc <- Tlink ty';
+ (* Name is a user-supplied name for this unification variable (obtained
+ * through a type annotation for instance). *)
+ match desc, ty'.desc with
+ Tvar name, Tvar name' ->
+ begin match name, name' with
+ | Some _, None -> log_type ty'; ty'.desc <- Tvar name
+ | None, Some _ -> ()
+ | Some _, Some _ ->
+ if ty.level < ty'.level then (log_type ty'; ty'.desc <- Tvar name)
+ | None, None -> ()
+ end
+ | _ -> ()
+ (* ; assert (check_memorized_abbrevs ()) *)
+ (* ; check_expans [] ty' *)
+let set_level ty level =
+ if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level));
+ ty.level <- level
+let set_univar rty ty =
+ log_change (Cuniv (rty, !rty)); rty := Some ty
+let set_name nm v =
+ log_change (Cname (nm, !nm)); nm := v
+let set_row_field e v =
+ log_change (Crow (e, !e)); e := Some v
+let set_kind rk k =
+ log_change (Ckind (rk, !rk)); rk := Some k
+let set_commu rc c =
+ log_change (Ccommu (rc, !rc)); rc := c
+let set_typeset rs s =
+ log_change (Ctypeset (rs, !rs)); rs := s
+
+let snapshot () =
+ let old = !last_snapshot in
+ last_snapshot := !new_id;
+ match Weak.get trail 0 with Some r -> (r, old)
+ | None ->
+ let r = ref Unchanged in
+ Weak.set trail 0 (Some r);
+ (r, old)
+
+let rec rev_log accu = function
+ Unchanged -> accu
+ | Invalid -> assert false
+ | Change (ch, next) ->
+ let d = !next in
+ next := Invalid;
+ rev_log (ch::accu) d
+
+let backtrack (changes, old) =
+ match !changes with
+ Unchanged -> last_snapshot := old
+ | Invalid -> failwith "Btype.backtrack"
+ | Change _ as change ->
+ cleanup_abbrev ();
+ let backlog = rev_log [] change in
+ List.iter undo_change backlog;
+ changes := Unchanged;
+ last_snapshot := old;
+ Weak.set trail 0 (Some changes)
diff --git a/typing/btype.mli b/typing/btype.mli
new file mode 100644
index 0000000000..4e1b1413c3
--- /dev/null
+++ b/typing/btype.mli
@@ -0,0 +1,212 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Basic operations on core types *)
+
+open Asttypes
+open Types
+
+(**** Sets, maps and hashtables of types ****)
+
+module TypeSet : Set.S with type elt = type_expr
+module TypeMap : Map.S with type key = type_expr
+module TypeHash : Hashtbl.S with type key = type_expr
+
+(**** Levels ****)
+
+val generic_level: int
+
+val newty2: int -> type_desc -> type_expr
+ (* Create a type *)
+val newgenty: type_desc -> type_expr
+ (* Create a generic type *)
+val newgenvar: ?name:string -> unit -> type_expr
+ (* Return a fresh generic variable *)
+
+(* Use Tsubst instead
+val newmarkedvar: int -> type_expr
+ (* Return a fresh marked variable *)
+val newmarkedgenvar: unit -> type_expr
+ (* Return a fresh marked generic variable *)
+*)
+
+(**** Types ****)
+
+val is_Tvar: type_expr -> bool
+val is_Tunivar: type_expr -> bool
+val dummy_method: label
+val default_mty: module_type option -> module_type
+
+val repr: type_expr -> type_expr
+ (* Return the canonical representative of a type. *)
+
+val field_kind_repr: field_kind -> field_kind
+ (* Return the canonical representative of an object field
+ kind. *)
+
+val commu_repr: commutable -> commutable
+ (* Return the canonical representative of a commutation lock *)
+
+(**** polymorphic variants ****)
+
+val row_repr: row_desc -> row_desc
+ (* Return the canonical representative of a row description *)
+val row_field_repr: row_field -> row_field
+val row_field: label -> row_desc -> row_field
+ (* Return the canonical representative of a row field *)
+val row_more: row_desc -> type_expr
+ (* Return the extension variable of the row *)
+val row_fixed: row_desc -> bool
+ (* Return whether the row should be treated as fixed or not *)
+val static_row: row_desc -> bool
+ (* Return whether the row is static or not *)
+val hash_variant: label -> int
+ (* Hash function for variant tags *)
+
+val proxy: type_expr -> type_expr
+ (* Return the proxy representative of the type: either itself
+ or a row variable *)
+
+(**** Utilities for private abbreviations with fixed rows ****)
+val has_constr_row: type_expr -> bool
+val is_row_name: string -> bool
+val is_constr_row: type_expr -> bool
+
+(**** Utilities for type traversal ****)
+
+val iter_type_expr: (type_expr -> unit) -> type_expr -> unit
+ (* Iteration on types *)
+val iter_row: (type_expr -> unit) -> row_desc -> unit
+ (* Iteration on types in a row *)
+val iter_abbrev: (type_expr -> unit) -> abbrev_memo -> unit
+ (* Iteration on types in an abbreviation list *)
+
+type type_iterators =
+ { it_signature: type_iterators -> signature -> unit;
+ it_signature_item: type_iterators -> signature_item -> unit;
+ it_value_description: type_iterators -> value_description -> unit;
+ it_type_declaration: type_iterators -> type_declaration -> unit;
+ it_extension_constructor: type_iterators -> extension_constructor -> unit;
+ it_module_declaration: type_iterators -> module_declaration -> unit;
+ it_modtype_declaration: type_iterators -> modtype_declaration -> unit;
+ it_class_declaration: type_iterators -> class_declaration -> unit;
+ it_class_type_declaration: type_iterators -> class_type_declaration -> unit;
+ it_module_type: type_iterators -> module_type -> unit;
+ it_class_type: type_iterators -> class_type -> unit;
+ it_type_kind: type_iterators -> type_kind -> unit;
+ it_do_type_expr: type_iterators -> type_expr -> unit;
+ it_type_expr: type_iterators -> type_expr -> unit;
+ it_path: Path.t -> unit; }
+val type_iterators: type_iterators
+ (* Iteration on arbitrary type information.
+ [it_type_expr] calls [mark_type_node] to avoid loops. *)
+val unmark_iterators: type_iterators
+ (* Unmark any structure containing types. See [unmark_type] below. *)
+
+val copy_type_desc:
+ ?keep_names:bool -> (type_expr -> type_expr) -> type_desc -> type_desc
+ (* Copy on types *)
+val copy_row:
+ (type_expr -> type_expr) ->
+ bool -> row_desc -> bool -> type_expr -> row_desc
+val copy_kind: field_kind -> field_kind
+
+val save_desc: type_expr -> type_desc -> unit
+ (* Save a type description *)
+val dup_kind: field_kind option ref -> unit
+ (* Save a None field_kind, and make it point to a fresh Fvar *)
+val cleanup_types: unit -> unit
+ (* Restore type descriptions *)
+
+val lowest_level: int
+ (* Marked type: ty.level < lowest_level *)
+val pivot_level: int
+ (* Type marking: ty.level <- pivot_level - ty.level *)
+val mark_type: type_expr -> unit
+ (* Mark a type *)
+val mark_type_node: type_expr -> unit
+ (* Mark a type node (but not its sons) *)
+val mark_type_params: type_expr -> unit
+ (* Mark the sons of a type node *)
+val unmark_type: type_expr -> unit
+val unmark_type_decl: type_declaration -> unit
+val unmark_extension_constructor: extension_constructor -> unit
+val unmark_class_type: class_type -> unit
+val unmark_class_signature: class_signature -> unit
+ (* Remove marks from a type *)
+
+(**** Memorization of abbreviation expansion ****)
+
+val find_expans: private_flag -> Path.t -> abbrev_memo -> type_expr option
+ (* Look up a memorized abbreviation *)
+val cleanup_abbrev: unit -> unit
+ (* Flush the cache of abbreviation expansions.
+ When some types are saved (using [output_value]), this
+ function MUST be called just before. *)
+val memorize_abbrev:
+ abbrev_memo ref ->
+ private_flag -> Path.t -> type_expr -> type_expr -> unit
+ (* Add an expansion in the cache *)
+val forget_abbrev:
+ abbrev_memo ref -> Path.t -> unit
+ (* Remove an abbreviation from the cache *)
+
+(**** Utilities for labels ****)
+
+val is_optional : arg_label -> bool
+val label_name : arg_label -> label
+
+(* Returns the label name with first character '?' or '~' as appropriate. *)
+val prefixed_label_name : arg_label -> label
+
+val extract_label :
+ label -> (arg_label * 'a) list ->
+ arg_label * 'a * (arg_label * 'a) list * (arg_label * 'a) list
+ (* actual label, value, before list, after list *)
+
+(**** Utilities for backtracking ****)
+
+type snapshot
+ (* A snapshot for backtracking *)
+val snapshot: unit -> snapshot
+ (* Make a snapshot for later backtracking. Costs nothing *)
+val backtrack: snapshot -> unit
+ (* Backtrack to a given snapshot. Only possible if you have
+ not already backtracked to a previous snapshot.
+ Calls [cleanup_abbrev] internally *)
+
+(* Functions to use when modifying a type (only Ctype?) *)
+val link_type: type_expr -> type_expr -> unit
+ (* Set the desc field of [t1] to [Tlink t2], logging the old
+ value if there is an active snapshot *)
+val set_level: type_expr -> int -> unit
+val set_name:
+ (Path.t * type_expr list) option ref ->
+ (Path.t * type_expr list) option -> unit
+val set_row_field: row_field option ref -> row_field -> unit
+val set_univar: type_expr option ref -> type_expr -> unit
+val set_kind: field_kind option ref -> field_kind -> unit
+val set_commu: commutable ref -> commutable -> unit
+val set_typeset: TypeSet.t ref -> TypeSet.t -> unit
+ (* Set references, logging the old value *)
+val log_type: type_expr -> unit
+ (* Log the old value of a type, before modifying it by hand *)
+
+(**** Forward declarations ****)
+val print_raw: (Format.formatter -> type_expr -> unit) ref
+
+val iter_type_expr_kind: (type_expr -> unit) -> (type_kind -> unit)
+
+val iter_type_expr_cstr_args: (type_expr -> unit) ->
+ (constructor_arguments -> unit)
+val map_type_expr_cstr_args: (type_expr -> type_expr) ->
+ (constructor_arguments -> constructor_arguments)
diff --git a/typing/cmi_format.ml b/typing/cmi_format.ml
new file mode 100644
index 0000000000..6f421fdcff
--- /dev/null
+++ b/typing/cmi_format.ml
@@ -0,0 +1,102 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type pers_flags = Rectypes
+
+type error =
+ Not_an_interface of string
+ | Wrong_version_interface of string * string
+ | Corrupted_interface of string
+
+exception Error of error
+
+type cmi_infos = {
+ cmi_name : string;
+ cmi_sign : Types.signature_item list;
+ cmi_crcs : (string * Digest.t option) list;
+ cmi_flags : pers_flags list;
+}
+
+let input_cmi ic =
+ let (name, sign) = input_value ic in
+ let crcs = input_value ic in
+ let flags = input_value ic in
+ {
+ cmi_name = name;
+ cmi_sign = sign;
+ cmi_crcs = crcs;
+ cmi_flags = flags;
+ }
+
+let read_cmi filename =
+ let ic = open_in_bin filename in
+ try
+ let buffer =
+ really_input_string ic (String.length Config.cmi_magic_number)
+ in
+ if buffer <> Config.cmi_magic_number then begin
+ close_in ic;
+ let pre_len = String.length Config.cmi_magic_number - 3 in
+ if String.sub buffer 0 pre_len
+ = String.sub Config.cmi_magic_number 0 pre_len then
+ begin
+ let msg =
+ if buffer < Config.cmi_magic_number then "an older" else "a newer" in
+ raise (Error (Wrong_version_interface (filename, msg)))
+ end else begin
+ raise(Error(Not_an_interface filename))
+ end
+ end;
+ let cmi = input_cmi ic in
+ close_in ic;
+ cmi
+ with End_of_file | Failure _ ->
+ close_in ic;
+ raise(Error(Corrupted_interface(filename)))
+ | Error e ->
+ close_in ic;
+ raise (Error e)
+
+let output_cmi filename oc cmi =
+(* beware: the provided signature must have been substituted for saving *)
+ output_string oc Config.cmi_magic_number;
+ output_value oc (cmi.cmi_name, cmi.cmi_sign);
+ flush oc;
+ let crc = Digest.file filename in
+ let crcs = (cmi.cmi_name, Some crc) :: cmi.cmi_crcs in
+ output_value oc crcs;
+ output_value oc cmi.cmi_flags;
+ crc
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Not_an_interface filename ->
+ fprintf ppf "%a@ is not a compiled interface"
+ Location.print_filename filename
+ | Wrong_version_interface (filename, older_newer) ->
+ fprintf ppf
+ "%a@ is not a compiled interface for this version of OCaml.@.\
+ It seems to be for %s version of OCaml."
+ Location.print_filename filename older_newer
+ | Corrupted_interface filename ->
+ fprintf ppf "Corrupted compiled interface@ %a"
+ Location.print_filename filename
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
diff --git a/typing/cmi_format.mli b/typing/cmi_format.mli
new file mode 100644
index 0000000000..32cec451fb
--- /dev/null
+++ b/typing/cmi_format.mli
@@ -0,0 +1,42 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type pers_flags = Rectypes
+
+type cmi_infos = {
+ cmi_name : string;
+ cmi_sign : Types.signature_item list;
+ cmi_crcs : (string * Digest.t option) list;
+ cmi_flags : pers_flags list;
+}
+
+(* write the magic + the cmi information *)
+val output_cmi : string -> out_channel -> cmi_infos -> Digest.t
+
+(* read the cmi information (the magic is supposed to have already been read) *)
+val input_cmi : in_channel -> cmi_infos
+
+(* read a cmi from a filename, checking the magic *)
+val read_cmi : string -> cmi_infos
+
+(* Error report *)
+
+type error =
+ Not_an_interface of string
+ | Wrong_version_interface of string * string
+ | Corrupted_interface of string
+
+exception Error of error
+
+open Format
+
+val report_error: formatter -> error -> unit
diff --git a/typing/cmt_format.ml b/typing/cmt_format.ml
new file mode 100644
index 0000000000..772d7e3af8
--- /dev/null
+++ b/typing/cmt_format.ml
@@ -0,0 +1,207 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Cmi_format
+open Typedtree
+
+(* Note that in Typerex, there is an awful hack to save a cmt file
+ together with the interface file that was generated by ocaml (this
+ is because the installed version of ocaml might differ from the one
+ integrated in Typerex).
+*)
+
+
+
+let read_magic_number ic =
+ let len_magic_number = String.length Config.cmt_magic_number in
+ really_input_string ic len_magic_number
+
+type binary_annots =
+ | Packed of Types.signature * string list
+ | Implementation of structure
+ | Interface of signature
+ | Partial_implementation of binary_part array
+ | Partial_interface of binary_part array
+
+and binary_part =
+| Partial_structure of structure
+| Partial_structure_item of structure_item
+| Partial_expression of expression
+| Partial_pattern of pattern
+| Partial_class_expr of class_expr
+| Partial_signature of signature
+| Partial_signature_item of signature_item
+| Partial_module_type of module_type
+
+type cmt_infos = {
+ cmt_modname : string;
+ cmt_annots : binary_annots;
+ cmt_value_dependencies :
+ (Types.value_description * Types.value_description) list;
+ cmt_comments : (string * Location.t) list;
+ cmt_args : string array;
+ cmt_sourcefile : string option;
+ cmt_builddir : string;
+ cmt_loadpath : string list;
+ cmt_source_digest : Digest.t option;
+ cmt_initial_env : Env.t;
+ cmt_imports : (string * Digest.t option) list;
+ cmt_interface_digest : Digest.t option;
+ cmt_use_summaries : bool;
+}
+
+type error =
+ Not_a_typedtree of string
+
+let need_to_clear_env =
+ try ignore (Sys.getenv "OCAML_BINANNOT_WITHENV"); false
+ with Not_found -> true
+
+let keep_only_summary = Env.keep_only_summary
+
+open Tast_mapper
+
+let cenv =
+ {Tast_mapper.default with env = fun _sub env -> keep_only_summary env}
+
+let clear_part = function
+ | Partial_structure s -> Partial_structure (cenv.structure cenv s)
+ | Partial_structure_item s ->
+ Partial_structure_item (cenv.structure_item cenv s)
+ | Partial_expression e -> Partial_expression (cenv.expr cenv e)
+ | Partial_pattern p -> Partial_pattern (cenv.pat cenv p)
+ | Partial_class_expr ce -> Partial_class_expr (cenv.class_expr cenv ce)
+ | Partial_signature s -> Partial_signature (cenv.signature cenv s)
+ | Partial_signature_item s ->
+ Partial_signature_item (cenv.signature_item cenv s)
+ | Partial_module_type s -> Partial_module_type (cenv.module_type cenv s)
+
+let clear_env binary_annots =
+ if need_to_clear_env then
+ match binary_annots with
+ | Implementation s -> Implementation (cenv.structure cenv s)
+ | Interface s -> Interface (cenv.signature cenv s)
+ | Packed _ -> binary_annots
+ | Partial_implementation array ->
+ Partial_implementation (Array.map clear_part array)
+ | Partial_interface array ->
+ Partial_interface (Array.map clear_part array)
+
+ else binary_annots
+
+exception Error of error
+
+let input_cmt ic = (input_value ic : cmt_infos)
+
+let output_cmt oc cmt =
+ output_string oc Config.cmt_magic_number;
+ output_value oc (cmt : cmt_infos)
+
+let read filename =
+(* Printf.fprintf stderr "Cmt_format.read %s\n%!" filename; *)
+ let ic = open_in_bin filename in
+ try
+ let magic_number = read_magic_number ic in
+ let cmi, cmt =
+ if magic_number = Config.cmt_magic_number then
+ None, Some (input_cmt ic)
+ else if magic_number = Config.cmi_magic_number then
+ let cmi = Cmi_format.input_cmi ic in
+ let cmt = try
+ let magic_number = read_magic_number ic in
+ if magic_number = Config.cmt_magic_number then
+ let cmt = input_cmt ic in
+ Some cmt
+ else None
+ with _ -> None
+ in
+ Some cmi, cmt
+ else
+ raise(Cmi_format.Error(Cmi_format.Not_an_interface filename))
+ in
+ close_in ic;
+(* Printf.fprintf stderr "Cmt_format.read done\n%!"; *)
+ cmi, cmt
+ with e ->
+ close_in ic;
+ raise e
+
+let string_of_file filename =
+ let ic = open_in filename in
+ let s = Misc.string_of_file ic in
+ close_in ic;
+ s
+
+let read_cmt filename =
+ match read filename with
+ _, None -> raise (Error (Not_a_typedtree filename))
+ | _, Some cmt -> cmt
+
+let read_cmi filename =
+ match read filename with
+ None, _ ->
+ raise (Cmi_format.Error (Cmi_format.Not_an_interface filename))
+ | Some cmi, _ -> cmi
+
+let saved_types = ref []
+let value_deps = ref []
+
+let clear () =
+ saved_types := [];
+ value_deps := []
+
+let add_saved_type b = saved_types := b :: !saved_types
+let get_saved_types () = !saved_types
+let set_saved_types l = saved_types := l
+
+let record_value_dependency vd1 vd2 =
+ if vd1.Types.val_loc <> vd2.Types.val_loc then
+ value_deps := (vd1, vd2) :: !value_deps
+
+let save_cmt filename modname binary_annots sourcefile initial_env sg =
+ if !Clflags.binary_annotations && not !Clflags.print_types then begin
+ let imports = Env.imports () in
+ let oc = open_out_bin filename in
+ let this_crc =
+ match sg with
+ None -> None
+ | Some (sg) ->
+ let cmi = {
+ cmi_name = modname;
+ cmi_sign = sg;
+ cmi_flags =
+ if !Clflags.recursive_types then [Cmi_format.Rectypes] else [];
+ cmi_crcs = imports;
+ } in
+ Some (output_cmi filename oc cmi)
+ in
+ let source_digest = Misc.may_map Digest.file sourcefile in
+ let cmt = {
+ cmt_modname = modname;
+ cmt_annots = clear_env binary_annots;
+ cmt_value_dependencies = !value_deps;
+ cmt_comments = Lexer.comments ();
+ cmt_args = Sys.argv;
+ cmt_sourcefile = sourcefile;
+ cmt_builddir = Sys.getcwd ();
+ cmt_loadpath = !Config.load_path;
+ cmt_source_digest = source_digest;
+ cmt_initial_env = if need_to_clear_env then
+ keep_only_summary initial_env else initial_env;
+ cmt_imports = List.sort compare imports;
+ cmt_interface_digest = this_crc;
+ cmt_use_summaries = need_to_clear_env;
+ } in
+ output_cmt oc cmt;
+ close_out oc;
+ end;
+ clear ()
diff --git a/typing/cmt_format.mli b/typing/cmt_format.mli
new file mode 100644
index 0000000000..48fbc639e8
--- /dev/null
+++ b/typing/cmt_format.mli
@@ -0,0 +1,119 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(** cmt and cmti files format. *)
+
+(** The layout of a cmt file is as follows:
+ <cmt> := \{<cmi>\} <cmt magic> \{cmt infos\} \{<source info>\}
+ where <cmi> is the cmi file format:
+ <cmi> := <cmi magic> <cmi info>.
+ More precisely, the optional <cmi> part must be present if and only if
+ the file is:
+ - a cmti, or
+ - a cmt, for a ml file which has no corresponding mli (hence no
+ corresponding cmti).
+
+ Thus, we provide a common reading function for cmi and cmt(i)
+ files which returns an option for each of the three parts: cmi
+ info, cmt info, source info. *)
+
+open Typedtree
+
+type binary_annots =
+ | Packed of Types.signature * string list
+ | Implementation of structure
+ | Interface of signature
+ | Partial_implementation of binary_part array
+ | Partial_interface of binary_part array
+
+and binary_part =
+ | Partial_structure of structure
+ | Partial_structure_item of structure_item
+ | Partial_expression of expression
+ | Partial_pattern of pattern
+ | Partial_class_expr of class_expr
+ | Partial_signature of signature
+ | Partial_signature_item of signature_item
+ | Partial_module_type of module_type
+
+type cmt_infos = {
+ cmt_modname : string;
+ cmt_annots : binary_annots;
+ cmt_value_dependencies :
+ (Types.value_description * Types.value_description) list;
+ cmt_comments : (string * Location.t) list;
+ cmt_args : string array;
+ cmt_sourcefile : string option;
+ cmt_builddir : string;
+ cmt_loadpath : string list;
+ cmt_source_digest : string option;
+ cmt_initial_env : Env.t;
+ cmt_imports : (string * Digest.t option) list;
+ cmt_interface_digest : Digest.t option;
+ cmt_use_summaries : bool;
+}
+
+type error =
+ Not_a_typedtree of string
+
+exception Error of error
+
+(** [read filename] opens filename, and extract both the cmi_infos, if
+ it exists, and the cmt_infos, if it exists. Thus, it can be used
+ with .cmi, .cmt and .cmti files.
+
+ .cmti files always contain a cmi_infos at the beginning. .cmt files
+ only contain a cmi_infos at the beginning if there is no associated
+ .cmti file.
+*)
+val read : string -> Cmi_format.cmi_infos option * cmt_infos option
+
+val read_cmt : string -> cmt_infos
+val read_cmi : string -> Cmi_format.cmi_infos
+
+(** [save_cmt modname filename binary_annots sourcefile initial_env sg]
+ writes a cmt(i) file. *)
+val save_cmt :
+ string -> (* filename.cmt to generate *)
+ string -> (* module name *)
+ binary_annots ->
+ string option -> (* source file *)
+ Env.t -> (* initial env *)
+ Types.signature option -> (* if a .cmi was generated,
+ the signature saved there *)
+ unit
+
+(* Miscellaneous functions *)
+
+val read_magic_number : in_channel -> string
+
+val clear: unit -> unit
+
+val add_saved_type : binary_part -> unit
+val get_saved_types : unit -> binary_part list
+val set_saved_types : binary_part list -> unit
+
+val record_value_dependency:
+ Types.value_description -> Types.value_description -> unit
+
+
+(*
+
+ val is_magic_number : string -> bool
+ val read : in_channel -> Env.cmi_infos option * t
+ val write_magic_number : out_channel -> unit
+ val write : out_channel -> t -> unit
+
+ val find : string list -> string -> string
+ val read_signature : 'a -> string -> Types.signature * 'b list * 'c list
+
+*)
diff --git a/typing/ctype.ml b/typing/ctype.ml
new file mode 100644
index 0000000000..512adb372c
--- /dev/null
+++ b/typing/ctype.ml
@@ -0,0 +1,4534 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Jerome Vouillon, projet Cristal, INRIA Rocquencourt*)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Operations on core types *)
+
+open Misc
+open Asttypes
+open Types
+open Btype
+
+(*
+ Type manipulation after type inference
+ ======================================
+ If one wants to manipulate a type after type inference (for
+ instance, during code generation or in the debugger), one must
+ first make sure that the type levels are correct, using the
+ function [correct_levels]. Then, this type can be correctely
+ manipulated by [apply], [expand_head] and [moregeneral].
+*)
+
+(*
+ General notes
+ =============
+ - As much sharing as possible should be kept : it makes types
+ smaller and better abbreviated.
+ When necessary, some sharing can be lost. Types will still be
+ printed correctly (+++ TO DO...), and abbreviations defined by a
+ class do not depend on sharing thanks to constrained
+ abbreviations. (Of course, even if some sharing is lost, typing
+ will still be correct.)
+ - All nodes of a type have a level : that way, one know whether a
+ node need to be duplicated or not when instantiating a type.
+ - Levels of a type are decreasing (generic level being considered
+ as greatest).
+ - The level of a type constructor is superior to the binding
+ time of its path.
+ - Recursive types without limitation should be handled (even if
+ there is still an occur check). This avoid treating specially the
+ case for objects, for instance. Furthermore, the occur check
+ policy can then be easily changed.
+*)
+
+(*
+ A faire
+ =======
+ - Revoir affichage des types.
+ - Etendre la portee d'un alias [... as 'a] a tout le type englobant.
+ - #-type implementes comme de vraies abreviations.
+ - Niveaux plus fins pour les identificateurs :
+ Champ [global] renomme en [level];
+ Niveau -1 : global
+ 0 : module toplevel
+ 1 : module contenu dans module toplevel
+ ...
+ En fait, incrementer le niveau a chaque fois que l'on rentre dans
+ un module.
+
+ 3 4 6
+ \ / /
+ 1 2 5
+ \|/
+ 0
+
+ [Subst] doit ecreter les niveaux (pour qu'un variable non
+ generalisable dans un module de niveau 2 ne se retrouve pas
+ generalisable lorsque l'on l'utilise au niveau 0).
+
+ - Traitement de la trace de l'unification separe de la fonction
+ [unify].
+*)
+
+(**** Errors ****)
+
+exception Unify of (type_expr * type_expr) list
+
+exception Tags of label * label
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Tags (l, l') ->
+ Some
+ Location.
+ (errorf ~loc:(in_file !input_name)
+ "In this program,@ variant constructors@ `%s and `%s@ \
+ have the same hash value.@ Change one of them." l l'
+ )
+ | _ -> None
+ )
+
+exception Subtype of
+ (type_expr * type_expr) list * (type_expr * type_expr) list
+
+exception Cannot_expand
+
+exception Cannot_apply
+
+exception Recursive_abbrev
+
+(* GADT: recursive abbrevs can appear as a result of local constraints *)
+exception Unification_recursive_abbrev of (type_expr * type_expr) list
+
+(**** Type level management ****)
+
+let current_level = ref 0
+let nongen_level = ref 0
+let global_level = ref 1
+let saved_level = ref []
+
+let get_current_level () = !current_level
+let init_def level = current_level := level; nongen_level := level
+let begin_def () =
+ saved_level := (!current_level, !nongen_level) :: !saved_level;
+ incr current_level; nongen_level := !current_level
+let begin_class_def () =
+ saved_level := (!current_level, !nongen_level) :: !saved_level;
+ incr current_level
+let raise_nongen_level () =
+ saved_level := (!current_level, !nongen_level) :: !saved_level;
+ nongen_level := !current_level
+let end_def () =
+ let (cl, nl) = List.hd !saved_level in
+ saved_level := List.tl !saved_level;
+ current_level := cl; nongen_level := nl
+
+let reset_global_level () =
+ global_level := !current_level + 1
+let increase_global_level () =
+ let gl = !global_level in
+ global_level := !current_level;
+ gl
+let restore_global_level gl =
+ global_level := gl
+
+(**** Whether a path points to an object type (with hidden row variable) ****)
+let is_object_type path =
+ let name =
+ match path with Path.Pident id -> Ident.name id
+ | Path.Pdot(_, s,_) -> s
+ | Path.Papply _ -> assert false
+ in name.[0] = '#'
+
+(**** Control tracing of GADT instances *)
+
+let trace_gadt_instances = ref false
+let check_trace_gadt_instances env =
+ not !trace_gadt_instances && Env.has_local_constraints env &&
+ (trace_gadt_instances := true; cleanup_abbrev (); true)
+
+let reset_trace_gadt_instances b =
+ if b then trace_gadt_instances := false
+
+let wrap_trace_gadt_instances env f x =
+ let b = check_trace_gadt_instances env in
+ let y = f x in
+ reset_trace_gadt_instances b;
+ y
+
+(**** Abbreviations without parameters ****)
+(* Shall reset after generalizing *)
+
+let simple_abbrevs = ref Mnil
+
+let proper_abbrevs path tl abbrev =
+ if tl <> [] || !trace_gadt_instances || !Clflags.principal ||
+ is_object_type path
+ then abbrev
+ else simple_abbrevs
+
+(**** Some type creators ****)
+
+(* Re-export generic type creators *)
+
+let newty2 = Btype.newty2
+let newty desc = newty2 !current_level desc
+let new_global_ty desc = newty2 !global_level desc
+
+let newvar ?name () = newty2 !current_level (Tvar name)
+let newvar2 ?name level = newty2 level (Tvar name)
+let new_global_var ?name () = newty2 !global_level (Tvar name)
+
+let newobj fields = newty (Tobject (fields, ref None))
+
+let newconstr path tyl = newty (Tconstr (path, tyl, ref Mnil))
+
+let none = newty (Ttuple []) (* Clearly ill-formed type *)
+
+(**** Representative of a type ****)
+
+(* Re-export repr *)
+let repr = repr
+
+(**** Type maps ****)
+
+module TypePairs =
+ Hashtbl.Make (struct
+ type t = type_expr * type_expr
+ let equal (t1, t1') (t2, t2') = (t1 == t2) && (t1' == t2')
+ let hash (t, t') = t.id + 93 * t'.id
+ end)
+
+
+(**** unification mode ****)
+
+type unification_mode =
+ | Expression (* unification in expression *)
+ | Pattern (* unification in pattern which may add local constraints *)
+
+let umode = ref Expression
+let generate_equations = ref false
+let assume_injective = ref false
+
+let set_mode_expression f =
+ let old_unification_mode = !umode in
+ try
+ umode := Expression;
+ let ret = f () in
+ umode := old_unification_mode;
+ ret
+ with e ->
+ umode := old_unification_mode;
+ raise e
+
+let set_mode_pattern ~generate ~injective f =
+ let old_unification_mode = !umode
+ and old_gen = !generate_equations
+ and old_inj = !assume_injective in
+ try
+ umode := Pattern;
+ generate_equations := generate;
+ assume_injective := injective;
+ let ret = f () in
+ umode := old_unification_mode;
+ generate_equations := old_gen;
+ assume_injective := old_inj;
+ ret
+ with e ->
+ umode := old_unification_mode;
+ generate_equations := old_gen;
+ assume_injective := old_inj;
+ raise e
+
+(*** Checks for type definitions ***)
+
+let in_current_module = function
+ | Path.Pident _ -> true
+ | Path.Pdot _ | Path.Papply _ -> false
+
+let in_pervasives p =
+ in_current_module p &&
+ try ignore (Env.find_type p Env.initial_safe_string); true
+ with Not_found -> false
+
+let is_datatype decl=
+ match decl.type_kind with
+ Type_record _ | Type_variant _ | Type_open -> true
+ | Type_abstract -> false
+
+
+ (**********************************************)
+ (* Miscellaneous operations on object types *)
+ (**********************************************)
+
+(* Note:
+ We need to maintain some invariants:
+ * cty_self must be a Tobject
+ * ...
+*)
+
+(**** Object field manipulation. ****)
+
+let object_fields ty =
+ match (repr ty).desc with
+ Tobject (fields, _) -> fields
+ | _ -> assert false
+
+let flatten_fields ty =
+ let rec flatten l ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tfield(s, k, ty1, ty2) ->
+ flatten ((s, k, ty1)::l) ty2
+ | _ ->
+ (l, ty)
+ in
+ let (l, r) = flatten [] ty in
+ (List.sort (fun (n, _, _) (n', _, _) -> compare n n') l, r)
+
+let build_fields level =
+ List.fold_right
+ (fun (s, k, ty1) ty2 -> newty2 level (Tfield(s, k, ty1, ty2)))
+
+let associate_fields fields1 fields2 =
+ let rec associate p s s' =
+ function
+ (l, []) ->
+ (List.rev p, (List.rev s) @ l, List.rev s')
+ | ([], l') ->
+ (List.rev p, List.rev s, (List.rev s') @ l')
+ | ((n, k, t)::r, (n', k', t')::r') when n = n' ->
+ associate ((n, k, t, k', t')::p) s s' (r, r')
+ | ((n, k, t)::r, ((n', k', t')::_ as l')) when n < n' ->
+ associate p ((n, k, t)::s) s' (r, l')
+ | (((n, k, t)::r as l), (n', k', t')::r') (* when n > n' *) ->
+ associate p s ((n', k', t')::s') (l, r')
+ in
+ associate [] [] [] (fields1, fields2)
+
+(**** Check whether an object is open ****)
+
+(* +++ Il faudra penser a eventuellement expanser l'abreviation *)
+let rec object_row ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tobject (t, _) -> object_row t
+ | Tfield(_, _, _, t) -> object_row t
+ | _ -> ty
+
+let opened_object ty =
+ match (object_row ty).desc with
+ | Tvar _ | Tunivar _ | Tconstr _ -> true
+ | _ -> false
+
+let concrete_object ty =
+ match (object_row ty).desc with
+ | Tvar _ -> false
+ | _ -> true
+
+(**** Close an object ****)
+
+let close_object ty =
+ let rec close ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tvar _ ->
+ link_type ty (newty2 ty.level Tnil)
+ | Tfield(_, _, _, ty') -> close ty'
+ | _ -> assert false
+ in
+ match (repr ty).desc with
+ Tobject (ty, _) -> close ty
+ | _ -> assert false
+
+(**** Row variable of an object type ****)
+
+let row_variable ty =
+ let rec find ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tfield (_, _, _, ty) -> find ty
+ | Tvar _ -> ty
+ | _ -> assert false
+ in
+ match (repr ty).desc with
+ Tobject (fi, _) -> find fi
+ | _ -> assert false
+
+(**** Object name manipulation ****)
+(* +++ Bientot obsolete *)
+
+let set_object_name id rv params ty =
+ match (repr ty).desc with
+ Tobject (fi, nm) ->
+ set_name nm (Some (Path.Pident id, rv::params))
+ | _ ->
+ assert false
+
+let remove_object_name ty =
+ match (repr ty).desc with
+ Tobject (_, nm) -> set_name nm None
+ | Tconstr (_, _, _) -> ()
+ | _ -> fatal_error "Ctype.remove_object_name"
+
+(**** Hiding of private methods ****)
+
+let hide_private_methods ty =
+ match (repr ty).desc with
+ Tobject (fi, nm) ->
+ nm := None;
+ let (fl, _) = flatten_fields fi in
+ List.iter
+ (function (_, k, _) ->
+ match field_kind_repr k with
+ Fvar r -> set_kind r Fabsent
+ | _ -> ())
+ fl
+ | _ ->
+ assert false
+
+
+ (*******************************)
+ (* Operations on class types *)
+ (*******************************)
+
+
+let rec signature_of_class_type =
+ function
+ Cty_constr (_, _, cty) -> signature_of_class_type cty
+ | Cty_signature sign -> sign
+ | Cty_arrow (_, ty, cty) -> signature_of_class_type cty
+
+let self_type cty =
+ repr (signature_of_class_type cty).csig_self
+
+let rec class_type_arity =
+ function
+ Cty_constr (_, _, cty) -> class_type_arity cty
+ | Cty_signature _ -> 0
+ | Cty_arrow (_, _, cty) -> 1 + class_type_arity cty
+
+
+ (*******************************************)
+ (* Miscellaneous operations on row types *)
+ (*******************************************)
+
+let sort_row_fields = List.sort (fun (p,_) (q,_) -> compare p q)
+
+let rec merge_rf r1 r2 pairs fi1 fi2 =
+ match fi1, fi2 with
+ (l1,f1 as p1)::fi1', (l2,f2 as p2)::fi2' ->
+ if l1 = l2 then merge_rf r1 r2 ((l1,f1,f2)::pairs) fi1' fi2' else
+ if l1 < l2 then merge_rf (p1::r1) r2 pairs fi1' fi2 else
+ merge_rf r1 (p2::r2) pairs fi1 fi2'
+ | [], _ -> (List.rev r1, List.rev_append r2 fi2, pairs)
+ | _, [] -> (List.rev_append r1 fi1, List.rev r2, pairs)
+
+let merge_row_fields fi1 fi2 =
+ match fi1, fi2 with
+ [], _ | _, [] -> (fi1, fi2, [])
+ | [p1], _ when not (List.mem_assoc (fst p1) fi2) -> (fi1, fi2, [])
+ | _, [p2] when not (List.mem_assoc (fst p2) fi1) -> (fi1, fi2, [])
+ | _ -> merge_rf [] [] [] (sort_row_fields fi1) (sort_row_fields fi2)
+
+let rec filter_row_fields erase = function
+ [] -> []
+ | (l,f as p)::fi ->
+ let fi = filter_row_fields erase fi in
+ match row_field_repr f with
+ Rabsent -> fi
+ | Reither(_,_,false,e) when erase -> set_row_field e Rabsent; fi
+ | _ -> p :: fi
+
+ (**************************************)
+ (* Check genericity of type schemes *)
+ (**************************************)
+
+
+exception Non_closed of type_expr * bool
+
+let free_variables = ref []
+let really_closed = ref None
+
+let rec free_vars_rec real ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ begin match ty.desc, !really_closed with
+ Tvar _, _ ->
+ free_variables := (ty, real) :: !free_variables
+ | Tconstr (path, tl, _), Some env ->
+ begin try
+ let (_, body, _) = Env.find_type_expansion path env in
+ if (repr body).level <> generic_level then
+ free_variables := (ty, real) :: !free_variables
+ with Not_found -> ()
+ end;
+ List.iter (free_vars_rec true) tl
+(* Do not count "virtual" free variables
+ | Tobject(ty, {contents = Some (_, p)}) ->
+ free_vars_rec false ty; List.iter (free_vars_rec true) p
+*)
+ | Tobject (ty, _), _ ->
+ free_vars_rec false ty
+ | Tfield (_, _, ty1, ty2), _ ->
+ free_vars_rec true ty1; free_vars_rec false ty2
+ | Tvariant row, _ ->
+ let row = row_repr row in
+ iter_row (free_vars_rec true) row;
+ if not (static_row row) then free_vars_rec false row.row_more
+ | _ ->
+ iter_type_expr (free_vars_rec true) ty
+ end;
+ end
+
+let free_vars ?env ty =
+ free_variables := [];
+ really_closed := env;
+ free_vars_rec true ty;
+ let res = !free_variables in
+ free_variables := [];
+ really_closed := None;
+ res
+
+let free_variables ?env ty =
+ let tl = List.map fst (free_vars ?env ty) in
+ unmark_type ty;
+ tl
+
+let closed_type ty =
+ match free_vars ty with
+ [] -> ()
+ | (v, real) :: _ -> raise (Non_closed (v, real))
+
+let closed_parameterized_type params ty =
+ List.iter mark_type params;
+ let ok =
+ try closed_type ty; true with Non_closed _ -> false in
+ List.iter unmark_type params;
+ unmark_type ty;
+ ok
+
+let closed_type_decl decl =
+ try
+ List.iter mark_type decl.type_params;
+ begin match decl.type_kind with
+ Type_abstract ->
+ ()
+ | Type_variant v ->
+ List.iter
+ (fun {cd_args; cd_res; _} ->
+ match cd_res with
+ | Some _ -> ()
+ | None ->
+ match cd_args with
+ | Cstr_tuple l -> List.iter closed_type l
+ | Cstr_record l -> List.iter (fun l -> closed_type l.ld_type) l
+ )
+ v
+ | Type_record(r, rep) ->
+ List.iter (fun l -> closed_type l.ld_type) r
+ | Type_open -> ()
+ end;
+ begin match decl.type_manifest with
+ None -> ()
+ | Some ty -> closed_type ty
+ end;
+ unmark_type_decl decl;
+ None
+ with Non_closed (ty, _) ->
+ unmark_type_decl decl;
+ Some ty
+
+let closed_extension_constructor ext =
+ try
+ List.iter mark_type ext.ext_type_params;
+ begin match ext.ext_ret_type with
+ | Some _ -> ()
+ | None -> iter_type_expr_cstr_args closed_type ext.ext_args
+ end;
+ unmark_extension_constructor ext;
+ None
+ with Non_closed (ty, _) ->
+ unmark_extension_constructor ext;
+ Some ty
+
+type closed_class_failure =
+ CC_Method of type_expr * bool * string * type_expr
+ | CC_Value of type_expr * bool * string * type_expr
+
+exception CCFailure of closed_class_failure
+
+let closed_class params sign =
+ let ty = object_fields (repr sign.csig_self) in
+ let (fields, rest) = flatten_fields ty in
+ List.iter mark_type params;
+ mark_type rest;
+ List.iter
+ (fun (lab, _, ty) -> if lab = dummy_method then mark_type ty)
+ fields;
+ try
+ mark_type_node (repr sign.csig_self);
+ List.iter
+ (fun (lab, kind, ty) ->
+ if field_kind_repr kind = Fpresent then
+ try closed_type ty with Non_closed (ty0, real) ->
+ raise (CCFailure (CC_Method (ty0, real, lab, ty))))
+ fields;
+ mark_type_params (repr sign.csig_self);
+ List.iter unmark_type params;
+ unmark_class_signature sign;
+ None
+ with CCFailure reason ->
+ mark_type_params (repr sign.csig_self);
+ List.iter unmark_type params;
+ unmark_class_signature sign;
+ Some reason
+
+
+ (**********************)
+ (* Type duplication *)
+ (**********************)
+
+
+(* Duplicate a type, preserving only type variables *)
+let duplicate_type ty =
+ Subst.type_expr Subst.identity ty
+
+(* Same, for class types *)
+let duplicate_class_type ty =
+ Subst.class_type Subst.identity ty
+
+
+ (*****************************)
+ (* Type level manipulation *)
+ (*****************************)
+
+(*
+ It would be a bit more efficient to remove abbreviation expansions
+ rather than generalizing them: these expansions will usually not be
+ used anymore. However, this is not possible in the general case, as
+ [expand_abbrev] (via [subst]) requires these expansions to be
+ preserved. Does it worth duplicating this code ?
+*)
+let rec iter_generalize tyl ty =
+ let ty = repr ty in
+ if (ty.level > !current_level) && (ty.level <> generic_level) then begin
+ set_level ty generic_level;
+ begin match ty.desc with
+ Tconstr (_, _, abbrev) ->
+ iter_abbrev (iter_generalize tyl) !abbrev
+ | _ -> ()
+ end;
+ iter_type_expr (iter_generalize tyl) ty
+ end else
+ tyl := ty :: !tyl
+
+let iter_generalize tyl ty =
+ simple_abbrevs := Mnil;
+ iter_generalize tyl ty
+
+let generalize ty =
+ iter_generalize (ref []) ty
+
+(* Efficient repeated generalisation of the same type *)
+let iterative_generalization min_level tyl =
+ let tyl' = ref [] in
+ List.iter (iter_generalize tyl') tyl;
+ List.fold_right (fun ty l -> if ty.level <= min_level then l else ty::l)
+ !tyl' []
+
+(* Generalize the structure and lower the variables *)
+
+let rec generalize_structure var_level ty =
+ let ty = repr ty in
+ if ty.level <> generic_level then begin
+ if is_Tvar ty && ty.level > var_level then
+ set_level ty var_level
+ else if
+ ty.level > !current_level &&
+ match ty.desc with
+ Tconstr (p, _, abbrev) ->
+ not (is_object_type p) && (abbrev := Mnil; true)
+ | _ -> true
+ then begin
+ set_level ty generic_level;
+ iter_type_expr (generalize_structure var_level) ty
+ end
+ end
+
+let generalize_structure var_level ty =
+ simple_abbrevs := Mnil;
+ generalize_structure var_level ty
+
+(* Generalize the spine of a function, if the level >= !current_level *)
+
+let rec generalize_spine ty =
+ let ty = repr ty in
+ if ty.level < !current_level || ty.level = generic_level then () else
+ match ty.desc with
+ Tarrow (_, ty1, ty2, _) ->
+ set_level ty generic_level;
+ generalize_spine ty1;
+ generalize_spine ty2;
+ | Tpoly (ty', _) ->
+ set_level ty generic_level;
+ generalize_spine ty'
+ | Ttuple tyl
+ | Tpackage (_, _, tyl) ->
+ set_level ty generic_level;
+ List.iter generalize_spine tyl
+ | Tconstr (p, tyl, memo) when not (is_object_type p) ->
+ set_level ty generic_level;
+ memo := Mnil;
+ List.iter generalize_spine tyl
+ | _ -> ()
+
+let forward_try_expand_once = (* Forward declaration *)
+ ref (fun env ty -> raise Cannot_expand)
+
+(*
+ Lower the levels of a type (assume [level] is not
+ [generic_level]).
+*)
+(*
+ The level of a type constructor must be greater than its binding
+ time. That way, a type constructor cannot escape the scope of its
+ definition, as would be the case in
+ let x = ref []
+ module M = struct type t let _ = (x : t list ref) end
+ (without this constraint, the type system would actually be unsound.)
+*)
+let get_level env p =
+ try
+ match (Env.find_type p env).type_newtype_level with
+ | None -> Path.binding_time p
+ | Some (x, _) -> x
+ with
+ | Not_found ->
+ (* no newtypes in predef *)
+ Path.binding_time p
+
+let rec normalize_package_path env p =
+ let t =
+ try (Env.find_modtype p env).mtd_type
+ with Not_found -> None
+ in
+ match t with
+ | Some (Mty_ident p) -> normalize_package_path env p
+ | Some (Mty_signature _ | Mty_functor _ | Mty_alias _) | None -> p
+
+let rec update_level env level ty =
+ let ty = repr ty in
+ if ty.level > level then begin
+ begin match Env.gadt_instance_level env ty with
+ Some lv -> if level < lv then raise (Unify [(ty, newvar2 level)])
+ | None -> ()
+ end;
+ match ty.desc with
+ Tconstr(p, tl, abbrev) when level < get_level env p ->
+ (* Try first to replace an abbreviation by its expansion. *)
+ begin try
+ (* if is_newtype env p then raise Cannot_expand; *)
+ link_type ty (!forward_try_expand_once env ty);
+ update_level env level ty
+ with Cannot_expand ->
+ (* +++ Levels should be restored... *)
+ (* Format.printf "update_level: %i < %i@." level (get_level env p); *)
+ if level < get_level env p then raise (Unify [(ty, newvar2 level)]);
+ iter_type_expr (update_level env level) ty
+ end
+ | Tpackage (p, nl, tl) when level < Path.binding_time p ->
+ let p' = normalize_package_path env p in
+ if Path.same p p' then raise (Unify [(ty, newvar2 level)]);
+ log_type ty; ty.desc <- Tpackage (p', nl, tl);
+ update_level env level ty
+ | Tobject(_, ({contents=Some(p, tl)} as nm))
+ when level < get_level env p ->
+ set_name nm None;
+ update_level env level ty
+ | Tvariant row ->
+ let row = row_repr row in
+ begin match row.row_name with
+ | Some (p, tl) when level < get_level env p ->
+ log_type ty;
+ ty.desc <- Tvariant {row with row_name = None}
+ | _ -> ()
+ end;
+ set_level ty level;
+ iter_type_expr (update_level env level) ty
+ | Tfield(lab, _, ty1, _)
+ when lab = dummy_method && (repr ty1).level > level ->
+ raise (Unify [(ty1, newvar2 level)])
+ | _ ->
+ set_level ty level;
+ (* XXX what about abbreviations in Tconstr ? *)
+ iter_type_expr (update_level env level) ty
+ end
+
+(* Generalize and lower levels of contravariant branches simultaneously *)
+
+let generalize_contravariant env =
+ if !Clflags.principal then generalize_structure else update_level env
+
+let rec generalize_expansive env var_level ty =
+ let ty = repr ty in
+ if ty.level <> generic_level then begin
+ if ty.level > var_level then begin
+ set_level ty generic_level;
+ match ty.desc with
+ Tconstr (path, tyl, abbrev) ->
+ let variance =
+ try (Env.find_type path env).type_variance
+ with Not_found -> List.map (fun _ -> Variance.may_inv) tyl in
+ abbrev := Mnil;
+ List.iter2
+ (fun v t ->
+ if Variance.(mem May_weak v)
+ then generalize_contravariant env var_level t
+ else generalize_expansive env var_level t)
+ variance tyl
+ | Tpackage (_, _, tyl) ->
+ List.iter (generalize_contravariant env var_level) tyl
+ | Tarrow (_, t1, t2, _) ->
+ generalize_contravariant env var_level t1;
+ generalize_expansive env var_level t2
+ | _ ->
+ iter_type_expr (generalize_expansive env var_level) ty
+ end
+ end
+
+let generalize_expansive env ty =
+ simple_abbrevs := Mnil;
+ try
+ generalize_expansive env !nongen_level ty
+ with Unify ([_, ty'] as tr) ->
+ raise (Unify ((ty, ty') :: tr))
+
+let generalize_global ty = generalize_structure !global_level ty
+let generalize_structure ty = generalize_structure !current_level ty
+
+(* Correct the levels of type [ty]. *)
+let correct_levels ty =
+ duplicate_type ty
+
+(* Only generalize the type ty0 in ty *)
+let limited_generalize ty0 ty =
+ let ty0 = repr ty0 in
+
+ let graph = Hashtbl.create 17 in
+ let idx = ref lowest_level in
+ let roots = ref [] in
+
+ let rec inverse pty ty =
+ let ty = repr ty in
+ if (ty.level > !current_level) || (ty.level = generic_level) then begin
+ decr idx;
+ Hashtbl.add graph !idx (ty, ref pty);
+ if (ty.level = generic_level) || (ty == ty0) then
+ roots := ty :: !roots;
+ set_level ty !idx;
+ iter_type_expr (inverse [ty]) ty
+ end else if ty.level < lowest_level then begin
+ let (_, parents) = Hashtbl.find graph ty.level in
+ parents := pty @ !parents
+ end
+
+ and generalize_parents ty =
+ let idx = ty.level in
+ if idx <> generic_level then begin
+ set_level ty generic_level;
+ List.iter generalize_parents !(snd (Hashtbl.find graph idx));
+ (* Special case for rows: must generalize the row variable *)
+ match ty.desc with
+ Tvariant row ->
+ let more = row_more row in
+ let lv = more.level in
+ if (lv < lowest_level || lv > !current_level)
+ && lv <> generic_level then set_level more generic_level
+ | _ -> ()
+ end
+ in
+
+ inverse [] ty;
+ if ty0.level < lowest_level then
+ iter_type_expr (inverse []) ty0;
+ List.iter generalize_parents !roots;
+ Hashtbl.iter
+ (fun _ (ty, _) ->
+ if ty.level <> generic_level then set_level ty !current_level)
+ graph
+
+
+(* Compute statically the free univars of all nodes in a type *)
+(* This avoids doing it repeatedly during instantiation *)
+
+type inv_type_expr =
+ { inv_type : type_expr;
+ mutable inv_parents : inv_type_expr list }
+
+let rec inv_type hash pty ty =
+ let ty = repr ty in
+ try
+ let inv = TypeHash.find hash ty in
+ inv.inv_parents <- pty @ inv.inv_parents
+ with Not_found ->
+ let inv = { inv_type = ty; inv_parents = pty } in
+ TypeHash.add hash ty inv;
+ iter_type_expr (inv_type hash [inv]) ty
+
+let compute_univars ty =
+ let inverted = TypeHash.create 17 in
+ inv_type inverted [] ty;
+ let node_univars = TypeHash.create 17 in
+ let rec add_univar univ inv =
+ match inv.inv_type.desc with
+ Tpoly (ty, tl) when List.memq univ (List.map repr tl) -> ()
+ | _ ->
+ try
+ let univs = TypeHash.find node_univars inv.inv_type in
+ if not (TypeSet.mem univ !univs) then begin
+ univs := TypeSet.add univ !univs;
+ List.iter (add_univar univ) inv.inv_parents
+ end
+ with Not_found ->
+ TypeHash.add node_univars inv.inv_type (ref(TypeSet.singleton univ));
+ List.iter (add_univar univ) inv.inv_parents
+ in
+ TypeHash.iter (fun ty inv -> if is_Tunivar ty then add_univar ty inv)
+ inverted;
+ fun ty ->
+ try !(TypeHash.find node_univars ty) with Not_found -> TypeSet.empty
+
+
+ (*******************)
+ (* Instantiation *)
+ (*******************)
+
+
+let rec find_repr p1 =
+ function
+ Mnil ->
+ None
+ | Mcons (Public, p2, ty, _, _) when Path.same p1 p2 ->
+ Some ty
+ | Mcons (_, _, _, _, rem) ->
+ find_repr p1 rem
+ | Mlink {contents = rem} ->
+ find_repr p1 rem
+
+(*
+ Generic nodes are duplicated, while non-generic nodes are left
+ as-is.
+ During instantiation, the description of a generic node is first
+ replaced by a link to a stub ([Tsubst (newvar ())]). Once the
+ copy is made, it replaces the stub.
+ After instantiation, the description of generic node, which was
+ stored by [save_desc], must be put back, using [cleanup_types].
+*)
+
+let abbreviations = ref (ref Mnil)
+ (* Abbreviation memorized. *)
+
+(* partial: we may not wish to copy the non generic types
+ before we call type_pat *)
+let rec copy ?env ?partial ?keep_names ty =
+ let copy = copy ?env ?partial ?keep_names in
+ let ty = repr ty in
+ match ty.desc with
+ Tsubst ty -> ty
+ | _ ->
+ if ty.level <> generic_level && partial = None then ty else
+ (* We only forget types that are non generic and do not contain
+ free univars *)
+ let forget =
+ if ty.level = generic_level then generic_level else
+ match partial with
+ None -> assert false
+ | Some (free_univars, keep) ->
+ if TypeSet.is_empty (free_univars ty) then
+ if keep then ty.level else !current_level
+ else generic_level
+ in
+ if forget <> generic_level then newty2 forget (Tvar None) else
+ let desc = ty.desc in
+ save_desc ty desc;
+ let t = newvar() in (* Stub *)
+ begin match env with
+ Some env when Env.has_local_constraints env ->
+ begin match Env.gadt_instance_level env ty with
+ Some lv -> Env.add_gadt_instances env lv [t]
+ | None -> ()
+ end
+ | _ -> ()
+ end;
+ ty.desc <- Tsubst t;
+ t.desc <-
+ begin match desc with
+ | Tconstr (p, tl, _) ->
+ let abbrevs = proper_abbrevs p tl !abbreviations in
+ begin match find_repr p !abbrevs with
+ Some ty when repr ty != t -> (* XXX Commentaire... *)
+ Tlink ty
+ | _ ->
+ (*
+ One must allocate a new reference, so that abbrevia-
+ tions belonging to different branches of a type are
+ independent.
+ Moreover, a reference containing a [Mcons] must be
+ shared, so that the memorized expansion of an abbrevi-
+ ation can be released by changing the content of just
+ one reference.
+ *)
+ Tconstr (p, List.map copy tl,
+ ref (match !(!abbreviations) with
+ Mcons _ -> Mlink !abbreviations
+ | abbrev -> abbrev))
+ end
+ | Tvariant row0 ->
+ let row = row_repr row0 in
+ let more = repr row.row_more in
+ (* We must substitute in a subtle way *)
+ (* Tsubst takes a tuple containing the row var and the variant *)
+ begin match more.desc with
+ Tsubst {desc = Ttuple [_;ty2]} ->
+ (* This variant type has been already copied *)
+ ty.desc <- Tsubst ty2; (* avoid Tlink in the new type *)
+ Tlink ty2
+ | _ ->
+ (* If the row variable is not generic, we must keep it *)
+ let keep = more.level <> generic_level in
+ let more' =
+ match more.desc with
+ Tsubst ty -> ty
+ | Tconstr _ | Tnil ->
+ if keep then save_desc more more.desc;
+ copy more
+ | Tvar _ | Tunivar _ ->
+ save_desc more more.desc;
+ if keep then more else newty more.desc
+ | _ -> assert false
+ in
+ let row =
+ match repr more' with (* PR#6163 *)
+ {desc=Tconstr _} when not row.row_fixed ->
+ {row with row_fixed = true}
+ | _ -> row
+ in
+ (* Open row if partial for pattern and contains Reither *)
+ let more', row =
+ match partial with
+ Some (free_univars, false) ->
+ let more' =
+ if more.id != more'.id then more' else
+ let lv = if keep then more.level else !current_level in
+ newty2 lv (Tvar None)
+ in
+ let not_reither (_, f) =
+ match row_field_repr f with
+ Reither _ -> false
+ | _ -> true
+ in
+ if row.row_closed && not row.row_fixed
+ && TypeSet.is_empty (free_univars ty)
+ && not (List.for_all not_reither row.row_fields) then
+ (more',
+ {row_fields = List.filter not_reither row.row_fields;
+ row_more = more'; row_bound = ();
+ row_closed = false; row_fixed = false; row_name = None})
+ else (more', row)
+ | _ -> (more', row)
+ in
+ (* Register new type first for recursion *)
+ more.desc <- Tsubst(newgenty(Ttuple[more';t]));
+ (* Return a new copy *)
+ Tvariant (copy_row copy true row keep more')
+ end
+ | Tfield (p, k, ty1, ty2) ->
+ begin match field_kind_repr k with
+ Fabsent -> Tlink (copy ty2)
+ | Fpresent -> copy_type_desc copy desc
+ | Fvar r ->
+ dup_kind r;
+ copy_type_desc copy desc
+ end
+ | Tobject (ty1, _) when partial <> None ->
+ Tobject (copy ty1, ref None)
+ | _ -> copy_type_desc ?keep_names copy desc
+ end;
+ t
+
+let simple_copy t = copy t
+
+(**** Variants of instantiations ****)
+
+let gadt_env env =
+ if Env.has_local_constraints env
+ then Some env
+ else None
+
+let instance ?partial env sch =
+ let env = gadt_env env in
+ let partial =
+ match partial with
+ None -> None
+ | Some keep -> Some (compute_univars sch, keep)
+ in
+ let ty = copy ?env ?partial sch in
+ cleanup_types ();
+ ty
+
+let instance_def sch =
+ let ty = copy sch in
+ cleanup_types ();
+ ty
+
+let generic_instance ?partial env sch =
+ let old = !current_level in
+ current_level := generic_level;
+ let ty = instance env sch in
+ current_level := old;
+ ty
+
+let instance_list env schl =
+ let env = gadt_env env in
+ let tyl = List.map (fun t -> copy ?env t) schl in
+ cleanup_types ();
+ tyl
+
+let reified_var_counter = ref Vars.empty
+let reset_reified_var_counter () =
+ reified_var_counter := Vars.empty
+
+(* names given to new type constructors.
+ Used for existential types and
+ local constraints *)
+let get_new_abstract_name s =
+ let index =
+ try Vars.find s !reified_var_counter + 1
+ with Not_found -> 0 in
+ reified_var_counter := Vars.add s index !reified_var_counter;
+ if index = 0 && s <> "" && s.[String.length s - 1] <> '$' then s else
+ Printf.sprintf "%s%d" s index
+
+let new_declaration newtype manifest =
+ {
+ type_params = [];
+ type_arity = 0;
+ type_kind = Type_abstract;
+ type_private = Public;
+ type_manifest = manifest;
+ type_variance = [];
+ type_newtype_level = newtype;
+ type_loc = Location.none;
+ type_attributes = [];
+ }
+
+let instance_constructor ?in_pattern cstr =
+ begin match in_pattern with
+ | None -> ()
+ | Some (env, newtype_lev) ->
+ let process existential =
+ let decl = new_declaration (Some (newtype_lev, newtype_lev)) None in
+ let name =
+ match repr existential with
+ {desc = Tvar (Some name)} -> "$" ^ cstr.cstr_name ^ "_'" ^ name
+ | _ -> "$" ^ cstr.cstr_name
+ in
+ let (id, new_env) =
+ Env.enter_type (get_new_abstract_name name) decl !env in
+ env := new_env;
+ let to_unify = newty (Tconstr (Path.Pident id,[],ref Mnil)) in
+ let tv = copy existential in
+ assert (is_Tvar tv);
+ link_type tv to_unify
+ in
+ List.iter process cstr.cstr_existentials
+ end;
+ let ty_res = copy cstr.cstr_res in
+ let ty_args = List.map simple_copy cstr.cstr_args in
+ cleanup_types ();
+ (ty_args, ty_res)
+
+let instance_parameterized_type ?keep_names sch_args sch =
+ let ty_args = List.map (fun t -> copy ?keep_names t) sch_args in
+ let ty = copy sch in
+ cleanup_types ();
+ (ty_args, ty)
+
+let instance_parameterized_type_2 sch_args sch_lst sch =
+ let ty_args = List.map simple_copy sch_args in
+ let ty_lst = List.map simple_copy sch_lst in
+ let ty = copy sch in
+ cleanup_types ();
+ (ty_args, ty_lst, ty)
+
+let map_kind f = function
+ | Type_abstract -> Type_abstract
+ | Type_open -> Type_open
+ | Type_variant cl ->
+ Type_variant (
+ List.map
+ (fun c ->
+ {c with
+ cd_args = map_type_expr_cstr_args f c.cd_args;
+ cd_res = may_map f c.cd_res
+ })
+ cl)
+ | Type_record (fl, rr) ->
+ Type_record (
+ List.map
+ (fun l ->
+ {l with ld_type = f l.ld_type}
+ ) fl, rr)
+
+
+let instance_declaration decl =
+ let decl =
+ {decl with type_params = List.map simple_copy decl.type_params;
+ type_manifest = may_map simple_copy decl.type_manifest;
+ type_kind = map_kind simple_copy decl.type_kind;
+ }
+ in
+ cleanup_types ();
+ decl
+
+let instance_class params cty =
+ let rec copy_class_type =
+ function
+ Cty_constr (path, tyl, cty) ->
+ Cty_constr (path, List.map simple_copy tyl, copy_class_type cty)
+ | Cty_signature sign ->
+ Cty_signature
+ {csig_self = copy sign.csig_self;
+ csig_vars =
+ Vars.map (function (m, v, ty) -> (m, v, copy ty)) sign.csig_vars;
+ csig_concr = sign.csig_concr;
+ csig_inher =
+ List.map (fun (p,tl) -> (p, List.map simple_copy tl))
+ sign.csig_inher}
+ | Cty_arrow (l, ty, cty) ->
+ Cty_arrow (l, copy ty, copy_class_type cty)
+ in
+ let params' = List.map simple_copy params in
+ let cty' = copy_class_type cty in
+ cleanup_types ();
+ (params', cty')
+
+(**** Instanciation for types with free universal variables ****)
+
+let rec diff_list l1 l2 =
+ if l1 == l2 then [] else
+ match l1 with [] -> invalid_arg "Ctype.diff_list"
+ | a :: l1 -> a :: diff_list l1 l2
+
+let conflicts free bound =
+ let bound = List.map repr bound in
+ TypeSet.exists (fun t -> List.memq (repr t) bound) free
+
+let delayed_copy = ref []
+ (* copying to do later *)
+
+(* Copy without sharing until there are no free univars left *)
+(* all free univars must be included in [visited] *)
+let rec copy_sep fixed free bound visited ty =
+ let ty = repr ty in
+ let univars = free ty in
+ if TypeSet.is_empty univars then
+ if ty.level <> generic_level then ty else
+ let t = newvar () in
+ delayed_copy :=
+ lazy (t.desc <- Tlink (copy ty))
+ :: !delayed_copy;
+ t
+ else try
+ let t, bound_t = List.assq ty visited in
+ let dl = if is_Tunivar ty then [] else diff_list bound bound_t in
+ if dl <> [] && conflicts univars dl then raise Not_found;
+ t
+ with Not_found -> begin
+ let t = newvar() in (* Stub *)
+ let visited =
+ match ty.desc with
+ Tarrow _ | Ttuple _ | Tvariant _ | Tconstr _ | Tobject _ | Tpackage _ ->
+ (ty,(t,bound)) :: visited
+ | _ -> visited in
+ let copy_rec = copy_sep fixed free bound visited in
+ t.desc <-
+ begin match ty.desc with
+ | Tvariant row0 ->
+ let row = row_repr row0 in
+ let more = repr row.row_more in
+ (* We shall really check the level on the row variable *)
+ let keep = is_Tvar more && more.level <> generic_level in
+ let more' = copy_rec more in
+ let fixed' = fixed && is_Tvar (repr more') in
+ let row = copy_row copy_rec fixed' row keep more' in
+ Tvariant row
+ | Tpoly (t1, tl) ->
+ let tl = List.map repr tl in
+ let tl' = List.map (fun t -> newty t.desc) tl in
+ let bound = tl @ bound in
+ let visited =
+ List.map2 (fun ty t -> ty,(t,bound)) tl tl' @ visited in
+ Tpoly (copy_sep fixed free bound visited t1, tl')
+ | _ -> copy_type_desc copy_rec ty.desc
+ end;
+ t
+ end
+
+let instance_poly ?(keep_names=false) fixed univars sch =
+ let univars = List.map repr univars in
+ let copy_var ty =
+ match ty.desc with
+ Tunivar name -> if keep_names then newty (Tvar name) else newvar ()
+ | _ -> assert false
+ in
+ let vars = List.map copy_var univars in
+ let pairs = List.map2 (fun u v -> u, (v, [])) univars vars in
+ delayed_copy := [];
+ let ty = copy_sep fixed (compute_univars sch) [] pairs sch in
+ List.iter Lazy.force !delayed_copy;
+ delayed_copy := [];
+ cleanup_types ();
+ vars, ty
+
+let instance_label fixed lbl =
+ let ty_res = copy lbl.lbl_res in
+ let vars, ty_arg =
+ match repr lbl.lbl_arg with
+ {desc = Tpoly (ty, tl)} ->
+ instance_poly fixed tl ty
+ | ty ->
+ [], copy lbl.lbl_arg
+ in
+ cleanup_types ();
+ (vars, ty_arg, ty_res)
+
+(**** Instantiation with parameter substitution ****)
+
+let unify' = (* Forward declaration *)
+ ref (fun env ty1 ty2 -> raise (Unify []))
+
+let subst env level priv abbrev ty params args body =
+ if List.length params <> List.length args then raise (Unify []);
+ let old_level = !current_level in
+ current_level := level;
+ try
+ let body0 = newvar () in (* Stub *)
+ begin match ty with
+ None -> ()
+ | Some ({desc = Tconstr (path, tl, _)} as ty) ->
+ let abbrev = proper_abbrevs path tl abbrev in
+ memorize_abbrev abbrev priv path ty body0
+ | _ ->
+ assert false
+ end;
+ abbreviations := abbrev;
+ let (params', body') = instance_parameterized_type params body in
+ abbreviations := ref Mnil;
+ !unify' env body0 body';
+ List.iter2 (!unify' env) params' args;
+ current_level := old_level;
+ body'
+ with Unify _ as exn ->
+ current_level := old_level;
+ raise exn
+
+(*
+ Only the shape of the type matters, not whether is is generic or
+ not. [generic_level] might be somewhat slower, but it ensures
+ invariants on types are enforced (decreasing levels.), and we don't
+ care about efficiency here.
+*)
+let apply env params body args =
+ try
+ subst env generic_level Public (ref Mnil) None params args body
+ with
+ Unify _ -> raise Cannot_apply
+
+
+ (****************************)
+ (* Abbreviation expansion *)
+ (****************************)
+
+(*
+ If the environnement has changed, memorized expansions might not
+ be correct anymore, and so we flush the cache. This is safe but
+ quite pessimistic: it would be enough to flush the cache when a
+ type or module definition is overridden in the environnement.
+*)
+let previous_env = ref Env.empty
+let string_of_kind = function Public -> "public" | Private -> "private"
+let check_abbrev_env env =
+ if env != !previous_env then begin
+ (* prerr_endline "cleanup expansion cache"; *)
+ cleanup_abbrev ();
+ previous_env := env
+ end
+
+
+(* Expand an abbreviation. The expansion is memorized. *)
+(*
+ Assume the level is greater than the path binding time of the
+ expanded abbreviation.
+*)
+(*
+ An abbreviation expansion will fail in either of these cases:
+ 1. The type constructor does not correspond to a manifest type.
+ 2. The type constructor is defined in an external file, and this
+ file is not in the path (missing -I options).
+ 3. The type constructor is not in the "local" environment. This can
+ happens when a non-generic type variable has been instantiated
+ afterwards to the not yet defined type constructor. (Actually,
+ this cannot happen at the moment due to the strong constraints
+ between type levels and constructor binding time.)
+ 4. The expansion requires the expansion of another abbreviation,
+ and this other expansion fails.
+*)
+let expand_abbrev_gen kind find_type_expansion env ty =
+ check_abbrev_env env;
+ match ty with
+ {desc = Tconstr (path, args, abbrev); level = level} ->
+ let lookup_abbrev = proper_abbrevs path args abbrev in
+ begin match find_expans kind path !lookup_abbrev with
+ Some ty ->
+ (* prerr_endline
+ ("found a "^string_of_kind kind^" expansion for "^Path.name path);*)
+ if level <> generic_level then
+ begin try
+ update_level env level ty
+ with Unify _ ->
+ (* XXX This should not happen.
+ However, levels are not correctly restored after a
+ typing error *)
+ ()
+ end;
+ ty
+ | None ->
+ let (params, body, lv) =
+ try find_type_expansion path env with Not_found ->
+ raise Cannot_expand
+ in
+ (* prerr_endline
+ ("add a "^string_of_kind kind^" expansion for "^Path.name path);*)
+ let ty' = subst env level kind abbrev (Some ty) params args body in
+ (* Hack to name the variant type *)
+ begin match repr ty' with
+ {desc=Tvariant row} as ty when static_row row ->
+ ty.desc <- Tvariant { row with row_name = Some (path, args) }
+ | _ -> ()
+ end;
+ (* For gadts, remember type as non exportable *)
+ (* The ambiguous level registered for ty' should be the highest *)
+ if !trace_gadt_instances then begin
+ match max lv (Env.gadt_instance_level env ty) with
+ None -> ()
+ | Some lv ->
+ if level < lv then raise (Unify [(ty, newvar2 level)]);
+ Env.add_gadt_instances env lv [ty; ty']
+ end;
+ ty'
+ end
+ | _ ->
+ assert false
+
+(* Expand respecting privacy *)
+let expand_abbrev env ty =
+ expand_abbrev_gen Public Env.find_type_expansion env ty
+
+(* Expand once the head of a type *)
+let expand_head_once env ty =
+ try expand_abbrev env (repr ty) with Cannot_expand -> assert false
+
+(* Check whether a type can be expanded *)
+let safe_abbrev env ty =
+ let snap = Btype.snapshot () in
+ try ignore (expand_abbrev env ty); true
+ with Cannot_expand | Unify _ ->
+ Btype.backtrack snap;
+ false
+
+(* Expand the head of a type once.
+ Raise Cannot_expand if the type cannot be expanded.
+ May raise Unify, if a recursion was hidden in the type. *)
+let try_expand_once env ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tconstr (p, _, _) -> repr (expand_abbrev env ty)
+ | _ -> raise Cannot_expand
+
+(* This one only raises Cannot_expand *)
+let try_expand_safe env ty =
+ let snap = Btype.snapshot () in
+ try try_expand_once env ty
+ with Unify _ ->
+ Btype.backtrack snap; raise Cannot_expand
+
+(* Fully expand the head of a type. *)
+let rec try_expand_head try_once env ty =
+ let ty' = try_once env ty in
+ try try_expand_head try_once env ty'
+ with Cannot_expand -> ty'
+
+let try_expand_head try_once env ty =
+ let ty' = try_expand_head try_once env ty in
+ begin match Env.gadt_instance_level env ty' with
+ None -> ()
+ | Some lv -> Env.add_gadt_instance_chain env lv ty
+ end;
+ ty'
+
+(* Unsafe full expansion, may raise Unify. *)
+let expand_head_unif env ty =
+ try try_expand_head try_expand_once env ty with Cannot_expand -> repr ty
+
+(* Safe version of expand_head, never fails *)
+let expand_head env ty =
+ try try_expand_head try_expand_safe env ty with Cannot_expand -> repr ty
+
+let _ = forward_try_expand_once := try_expand_safe
+
+
+(* Expand until we find a non-abstract type declaration *)
+
+let rec extract_concrete_typedecl env ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tconstr (p, _, _) ->
+ let decl = Env.find_type p env in
+ if decl.type_kind <> Type_abstract then (p, p, decl) else
+ let ty =
+ try try_expand_once env ty with Cannot_expand -> raise Not_found
+ in
+ let (_, p', decl) = extract_concrete_typedecl env ty in
+ (p, p', decl)
+ | _ -> raise Not_found
+
+(* Implementing function [expand_head_opt], the compiler's own version of
+ [expand_head] used for type-based optimisations.
+ [expand_head_opt] uses [Env.find_type_expansion_opt] to access the
+ manifest type information of private abstract data types which is
+ normally hidden to the type-checker out of the implementation module of
+ the private abbreviation. *)
+
+let expand_abbrev_opt =
+ expand_abbrev_gen Private Env.find_type_expansion_opt
+
+let try_expand_once_opt env ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tconstr _ -> repr (expand_abbrev_opt env ty)
+ | _ -> raise Cannot_expand
+
+let rec try_expand_head_opt env ty =
+ let ty' = try_expand_once_opt env ty in
+ begin try
+ try_expand_head_opt env ty'
+ with Cannot_expand ->
+ ty'
+ end
+
+let expand_head_opt env ty =
+ let snap = Btype.snapshot () in
+ try try_expand_head_opt env ty
+ with Cannot_expand | Unify _ -> (* expand_head shall never fail *)
+ Btype.backtrack snap;
+ repr ty
+
+(* Make sure that the type parameters of the type constructor [ty]
+ respect the type constraints *)
+let enforce_constraints env ty =
+ match ty with
+ {desc = Tconstr (path, args, abbrev); level = level} ->
+ begin try
+ let decl = Env.find_type path env in
+ ignore
+ (subst env level Public (ref Mnil) None decl.type_params args
+ (newvar2 level))
+ with Not_found -> ()
+ end
+ | _ ->
+ assert false
+
+(* Recursively expand the head of a type.
+ Also expand #-types. *)
+let full_expand env ty =
+ let ty = repr (expand_head env ty) in
+ match ty.desc with
+ Tobject (fi, {contents = Some (_, v::_)}) when is_Tvar (repr v) ->
+ newty2 ty.level (Tobject (fi, ref None))
+ | _ ->
+ ty
+
+(*
+ Check whether the abbreviation expands to a well-defined type.
+ During the typing of a class, abbreviations for correspondings
+ types expand to non-generic types.
+*)
+let generic_abbrev env path =
+ try
+ let (_, body, _) = Env.find_type_expansion path env in
+ (repr body).level = generic_level
+ with
+ Not_found ->
+ false
+
+let generic_private_abbrev env path =
+ try
+ match Env.find_type path env with
+ {type_kind = Type_abstract;
+ type_private = Private;
+ type_manifest = Some body} ->
+ (repr body).level = generic_level
+ | _ -> false
+ with Not_found -> false
+
+let is_contractive env ty =
+ try match (repr ty).desc with
+ Tconstr (p, _, _) ->
+ let decl = Env.find_type p env in
+ in_pervasives p && decl.type_manifest = None || is_datatype decl
+ | _ -> true
+ with Not_found -> false
+
+(* Code moved to Typedecl
+
+(* The marks are already used by [expand_abbrev]... *)
+let visited = ref []
+
+let rec non_recursive_abbrev env ty0 ty =
+ let ty = repr ty in
+ if ty == repr ty0 then raise Recursive_abbrev;
+ if not (List.memq ty !visited) then begin
+ visited := ty :: !visited;
+ match ty.desc with
+ Tconstr(p, args, abbrev) ->
+ begin try
+ non_recursive_abbrev env ty0 (try_expand_once_opt env ty)
+ with Cannot_expand ->
+ if !Clflags.recursive_types &&
+ (in_pervasives p ||
+ try is_datatype (Env.find_type p env) with Not_found -> false)
+ then ()
+ else iter_type_expr (non_recursive_abbrev env ty0) ty
+ end
+ | Tobject _ | Tvariant _ ->
+ ()
+ | _ ->
+ if !Clflags.recursive_types then () else
+ iter_type_expr (non_recursive_abbrev env ty0) ty
+ end
+
+let correct_abbrev env path params ty =
+ check_abbrev_env env;
+ let ty0 = newgenvar () in
+ visited := [];
+ let abbrev = Mcons (Public, path, ty0, ty0, Mnil) in
+ simple_abbrevs := abbrev;
+ try
+ non_recursive_abbrev env ty0
+ (subst env generic_level Public (ref abbrev) None [] [] ty);
+ simple_abbrevs := Mnil;
+ visited := []
+ with exn ->
+ simple_abbrevs := Mnil;
+ visited := [];
+ raise exn
+*)
+
+ (*****************)
+ (* Occur check *)
+ (*****************)
+
+
+exception Occur
+
+let allow_recursive env ty =
+ (!Clflags.recursive_types || !umode = Pattern) && is_contractive env ty
+
+let rec occur_rec env visited ty0 ty =
+ if ty == ty0 then raise Occur;
+ if allow_recursive env ty then () else
+ match ty.desc with
+ Tconstr(p, tl, abbrev) ->
+ begin try
+ if List.memq ty visited then raise Occur;
+ iter_type_expr (occur_rec env (ty::visited) ty0) ty
+ with Occur -> try
+ let ty' = try_expand_head try_expand_once env ty in
+ (* Maybe we could simply make a recursive call here,
+ but it seems it could make the occur check loop
+ (see change in rev. 1.58) *)
+ if ty' == ty0 || List.memq ty' visited then raise Occur;
+ match ty'.desc with
+ Tobject _ | Tvariant _ -> ()
+ | _ ->
+ if allow_recursive env ty' then () else
+ iter_type_expr (occur_rec env (ty'::visited) ty0) ty'
+ with Cannot_expand ->
+ raise Occur
+ end
+ | Tobject _ | Tvariant _ ->
+ ()
+ | _ ->
+ iter_type_expr (occur_rec env visited ty0) ty
+
+let type_changed = ref false (* trace possible changes to the studied type *)
+
+let merge r b = if b then r := true
+
+let occur env ty0 ty =
+ let old = !type_changed in
+ try
+ while type_changed := false; occur_rec env [] ty0 ty; !type_changed
+ do () (* prerr_endline "changed" *) done;
+ merge type_changed old
+ with exn ->
+ merge type_changed old;
+ raise (match exn with Occur -> Unify [] | _ -> exn)
+
+let occur_in env ty0 t =
+ try occur env ty0 t; false with Unify _ -> true
+
+(* Check that a local constraint is well-founded *)
+(* PR#6405: not needed since we allow recursion and work on normalized types *)
+(* PR#6992: we actually need it for contractiveness *)
+(* This is a simplified version of occur, only for the rectypes case *)
+let rec local_non_recursive_abbrev visited env p ty =
+ let ty = repr ty in
+ if not (List.memq ty visited) then begin
+ match ty.desc with
+ Tconstr(p', args, abbrev) ->
+ if Path.same p p' then raise Occur;
+ if is_contractive env ty then () else
+ let visited = ty :: visited in
+ begin try
+ List.iter (local_non_recursive_abbrev visited env p) args
+ with Occur -> try
+ local_non_recursive_abbrev visited env p
+ (try_expand_head try_expand_once env ty)
+ with Cannot_expand ->
+ raise Occur
+ end
+ | _ -> ()
+ end
+
+let local_non_recursive_abbrev env p ty =
+ try local_non_recursive_abbrev [] env p ty with Occur -> raise (Unify [])
+
+
+ (*****************************)
+ (* Polymorphic Unification *)
+ (*****************************)
+
+(* Since we cannot duplicate universal variables, unification must
+ be done at meta-level, using bindings in univar_pairs *)
+let rec unify_univar t1 t2 = function
+ (cl1, cl2) :: rem ->
+ let find_univ t cl =
+ try
+ let (_, r) = List.find (fun (t',_) -> t == repr t') cl in
+ Some r
+ with Not_found -> None
+ in
+ begin match find_univ t1 cl1, find_univ t2 cl2 with
+ Some {contents=Some t'2}, Some _ when t2 == repr t'2 ->
+ ()
+ | Some({contents=None} as r1), Some({contents=None} as r2) ->
+ set_univar r1 t2; set_univar r2 t1
+ | None, None ->
+ unify_univar t1 t2 rem
+ | _ ->
+ raise (Unify [])
+ end
+ | [] -> raise (Unify [])
+
+(* Test the occurence of free univars in a type *)
+(* that's way too expansive. Must do some kind of cacheing *)
+let occur_univar env ty =
+ let visited = ref TypeMap.empty in
+ let rec occur_rec bound ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level &&
+ if TypeSet.is_empty bound then
+ (ty.level <- pivot_level - ty.level; true)
+ else try
+ let bound' = TypeMap.find ty !visited in
+ if TypeSet.exists (fun x -> not (TypeSet.mem x bound)) bound' then
+ (visited := TypeMap.add ty (TypeSet.inter bound bound') !visited;
+ true)
+ else false
+ with Not_found ->
+ visited := TypeMap.add ty bound !visited;
+ true
+ then
+ match ty.desc with
+ Tunivar _ ->
+ if not (TypeSet.mem ty bound) then raise (Unify [ty, newgenvar ()])
+ | Tpoly (ty, tyl) ->
+ let bound = List.fold_right TypeSet.add (List.map repr tyl) bound in
+ occur_rec bound ty
+ | Tconstr (_, [], _) -> ()
+ | Tconstr (p, tl, _) ->
+ begin try
+ let td = Env.find_type p env in
+ List.iter2
+ (fun t v ->
+ if Variance.(mem May_pos v || mem May_neg v)
+ then occur_rec bound t)
+ tl td.type_variance
+ with Not_found ->
+ List.iter (occur_rec bound) tl
+ end
+ | _ -> iter_type_expr (occur_rec bound) ty
+ in
+ try
+ occur_rec TypeSet.empty ty; unmark_type ty
+ with exn ->
+ unmark_type ty; raise exn
+
+(* Grouping univars by families according to their binders *)
+let add_univars =
+ List.fold_left (fun s (t,_) -> TypeSet.add (repr t) s)
+
+let get_univar_family univar_pairs univars =
+ if univars = [] then TypeSet.empty else
+ let insert s = function
+ cl1, (_::_ as cl2) ->
+ if List.exists (fun (t1,_) -> TypeSet.mem (repr t1) s) cl1 then
+ add_univars s cl2
+ else s
+ | _ -> s
+ in
+ let s = List.fold_right TypeSet.add univars TypeSet.empty in
+ List.fold_left insert s univar_pairs
+
+(* Whether a family of univars escapes from a type *)
+let univars_escape env univar_pairs vl ty =
+ let family = get_univar_family univar_pairs vl in
+ let visited = ref TypeSet.empty in
+ let rec occur t =
+ let t = repr t in
+ if TypeSet.mem t !visited then () else begin
+ visited := TypeSet.add t !visited;
+ match t.desc with
+ Tpoly (t, tl) ->
+ if List.exists (fun t -> TypeSet.mem (repr t) family) tl then ()
+ else occur t
+ | Tunivar _ ->
+ if TypeSet.mem t family then raise Occur
+ | Tconstr (_, [], _) -> ()
+ | Tconstr (p, tl, _) ->
+ begin try
+ let td = Env.find_type p env in
+ List.iter2
+ (fun t v ->
+ if Variance.(mem May_pos v || mem May_neg v) then occur t)
+ tl td.type_variance
+ with Not_found ->
+ List.iter occur tl
+ end
+ | _ ->
+ iter_type_expr occur t
+ end
+ in
+ try occur ty; false with Occur -> true
+
+(* Wrapper checking that no variable escapes and updating univar_pairs *)
+let enter_poly env univar_pairs t1 tl1 t2 tl2 f =
+ let old_univars = !univar_pairs in
+ let known_univars =
+ List.fold_left (fun s (cl,_) -> add_univars s cl)
+ TypeSet.empty old_univars
+ in
+ let tl1 = List.map repr tl1 and tl2 = List.map repr tl2 in
+ if List.exists (fun t -> TypeSet.mem t known_univars) tl1 &&
+ univars_escape env old_univars tl1 (newty(Tpoly(t2,tl2)))
+ || List.exists (fun t -> TypeSet.mem t known_univars) tl2 &&
+ univars_escape env old_univars tl2 (newty(Tpoly(t1,tl1)))
+ then raise (Unify []);
+ let cl1 = List.map (fun t -> t, ref None) tl1
+ and cl2 = List.map (fun t -> t, ref None) tl2 in
+ univar_pairs := (cl1,cl2) :: (cl2,cl1) :: old_univars;
+ try let res = f t1 t2 in univar_pairs := old_univars; res
+ with exn -> univar_pairs := old_univars; raise exn
+
+let univar_pairs = ref []
+
+
+ (*****************)
+ (* Unification *)
+ (*****************)
+
+
+
+let rec has_cached_expansion p abbrev =
+ match abbrev with
+ Mnil -> false
+ | Mcons(_, p', _, _, rem) -> Path.same p p' || has_cached_expansion p rem
+ | Mlink rem -> has_cached_expansion p !rem
+
+(**** Transform error trace ****)
+(* +++ Move it to some other place ? *)
+
+let expand_trace env trace =
+ List.fold_right
+ (fun (t1, t2) rem ->
+ (repr t1, full_expand env t1)::(repr t2, full_expand env t2)::rem)
+ trace []
+
+(* build a dummy variant type *)
+let mkvariant fields closed =
+ newgenty
+ (Tvariant
+ {row_fields = fields; row_closed = closed; row_more = newvar();
+ row_bound = (); row_fixed = false; row_name = None })
+
+(* force unification in Reither when one side has as non-conjunctive type *)
+let rigid_variants = ref false
+
+(**** Unification ****)
+
+(* Return whether [t0] occurs in [ty]. Objects are also traversed. *)
+let deep_occur t0 ty =
+ let rec occur_rec ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ if ty == t0 then raise Occur;
+ ty.level <- pivot_level - ty.level;
+ iter_type_expr occur_rec ty
+ end
+ in
+ try
+ occur_rec ty; unmark_type ty; false
+ with Occur ->
+ unmark_type ty; true
+
+(*
+ 1. When unifying two non-abbreviated types, one type is made a link
+ to the other. When unifying an abbreviated type with a
+ non-abbreviated type, the non-abbreviated type is made a link to
+ the other one. When unifying to abbreviated types, these two
+ types are kept distincts, but they are made to (temporally)
+ expand to the same type.
+ 2. Abbreviations with at least one parameter are systematically
+ expanded. The overhead does not seem to high, and that way
+ abbreviations where some parameters does not appear in the
+ expansion, such as ['a t = int], are correctly handled. In
+ particular, for this example, unifying ['a t] with ['b t] keeps
+ ['a] and ['b] distincts. (Is it really important ?)
+ 3. Unifying an abbreviation ['a t = 'a] with ['a] should not yield
+ ['a t as 'a]. Indeed, the type variable would otherwise be lost.
+ This problem occurs for abbreviations expanding to a type
+ variable, but also to many other constrained abbreviations (for
+ instance, [(< x : 'a > -> unit) t = <x : 'a>]). The solution is
+ that, if an abbreviation is unified with some subpart of its
+ parameters, then the parameter actually does not get
+ abbreviated. It would be possible to check whether some
+ information is indeed lost, but it probably does not worth it.
+*)
+
+let newtype_level = ref None
+
+let get_newtype_level () =
+ match !newtype_level with
+ | None -> assert false
+ | Some x -> x
+
+(* a local constraint can be added only if the rhs
+ of the constraint does not contain any Tvars.
+ They need to be removed using this function *)
+let reify env t =
+ let newtype_level = get_newtype_level () in
+ let create_fresh_constr lev name =
+ let decl = new_declaration (Some (newtype_level, newtype_level)) None in
+ let name = match name with Some s -> "$'"^s | _ -> "$" in
+ let name = get_new_abstract_name name in
+ let (id, new_env) = Env.enter_type name decl !env in
+ let t = newty2 lev (Tconstr (Path.Pident id,[],ref Mnil)) in
+ env := new_env;
+ t
+ in
+ let visited = ref TypeSet.empty in
+ let rec iterator ty =
+ let ty = repr ty in
+ if TypeSet.mem ty !visited then () else begin
+ visited := TypeSet.add ty !visited;
+ match ty.desc with
+ Tvar o ->
+ let t = create_fresh_constr ty.level o in
+ link_type ty t
+ | Tvariant r ->
+ let r = row_repr r in
+ if not (static_row r) then begin
+ if r.row_fixed then iterator (row_more r) else
+ let m = r.row_more in
+ match m.desc with
+ Tvar o ->
+ let t = create_fresh_constr m.level o in
+ let row =
+ {r with row_fields=[]; row_fixed=true; row_more = t} in
+ link_type m (newty2 m.level (Tvariant row))
+ | _ -> assert false
+ end;
+ iter_row iterator r
+ | Tconstr (p, _, _) when is_object_type p ->
+ iter_type_expr iterator (full_expand !env ty)
+ | _ ->
+ iter_type_expr iterator ty
+ end
+ in
+ iterator t
+
+let is_newtype env p =
+ try
+ let decl = Env.find_type p env in
+ decl.type_newtype_level <> None &&
+ decl.type_kind = Type_abstract &&
+ decl.type_private = Public
+ with Not_found -> false
+
+let non_aliasable p decl =
+ (* in_pervasives p || (subsumed by in_current_module) *)
+ in_current_module p && decl.type_newtype_level = None
+
+(* Check for datatypes carefully; see PR#6348 *)
+let rec expands_to_datatype env ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tconstr (p, _, _) ->
+ begin try
+ is_datatype (Env.find_type p env) ||
+ expands_to_datatype env (try_expand_once env ty)
+ with Not_found | Cannot_expand -> false
+ end
+ | _ -> false
+
+(* mcomp type_pairs subst env t1 t2 does not raise an
+ exception if it is possible that t1 and t2 are actually
+ equal, assuming the types in type_pairs are equal and
+ that the mapping subst holds.
+ Assumes that both t1 and t2 do not contain any tvars
+ and that both their objects and variants are closed
+ *)
+
+let rec mcomp type_pairs env t1 t2 =
+ if t1 == t2 then () else
+ let t1 = repr t1 in
+ let t2 = repr t2 in
+ if t1 == t2 then () else
+ match (t1.desc, t2.desc) with
+ | (Tvar _, _)
+ | (_, Tvar _) ->
+ ()
+ | (Tconstr (p1, [], _), Tconstr (p2, [], _)) when Path.same p1 p2 ->
+ ()
+ | _ ->
+ let t1' = expand_head_opt env t1 in
+ let t2' = expand_head_opt env t2 in
+ (* Expansion may have changed the representative of the types... *)
+ let t1' = repr t1' and t2' = repr t2' in
+ if t1' == t2' then () else
+ begin try TypePairs.find type_pairs (t1', t2')
+ with Not_found ->
+ TypePairs.add type_pairs (t1', t2') ();
+ match (t1'.desc, t2'.desc) with
+ (Tvar _, Tvar _) -> assert false
+ | (Tarrow (l1, t1, u1, _), Tarrow (l2, t2, u2, _))
+ when l1 = l2 || not (is_optional l1 || is_optional l2) ->
+ mcomp type_pairs env t1 t2;
+ mcomp type_pairs env u1 u2;
+ | (Ttuple tl1, Ttuple tl2) ->
+ mcomp_list type_pairs env tl1 tl2
+ | (Tconstr (p1, tl1, _), Tconstr (p2, tl2, _)) ->
+ mcomp_type_decl type_pairs env p1 p2 tl1 tl2
+ | (Tconstr (p, _, _), _) | (_, Tconstr (p, _, _)) ->
+ begin try
+ let decl = Env.find_type p env in
+ if non_aliasable p decl || is_datatype decl then raise (Unify [])
+ with Not_found -> ()
+ end
+ (*
+ | (Tpackage (p1, n1, tl1), Tpackage (p2, n2, tl2)) when n1 = n2 ->
+ mcomp_list type_pairs env tl1 tl2
+ *)
+ | (Tpackage _, Tpackage _) -> ()
+ | (Tvariant row1, Tvariant row2) ->
+ mcomp_row type_pairs env row1 row2
+ | (Tobject (fi1, _), Tobject (fi2, _)) ->
+ mcomp_fields type_pairs env fi1 fi2
+ | (Tfield _, Tfield _) -> (* Actually unused *)
+ mcomp_fields type_pairs env t1' t2'
+ | (Tnil, Tnil) ->
+ ()
+ | (Tpoly (t1, []), Tpoly (t2, [])) ->
+ mcomp type_pairs env t1 t2
+ | (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
+ enter_poly env univar_pairs t1 tl1 t2 tl2
+ (mcomp type_pairs env)
+ | (Tunivar _, Tunivar _) ->
+ unify_univar t1' t2' !univar_pairs
+ | (_, _) ->
+ raise (Unify [])
+ end
+
+and mcomp_list type_pairs env tl1 tl2 =
+ if List.length tl1 <> List.length tl2 then
+ raise (Unify []);
+ List.iter2 (mcomp type_pairs env) tl1 tl2
+
+and mcomp_fields type_pairs env ty1 ty2 =
+ if not (concrete_object ty1 && concrete_object ty2) then assert false;
+ let (fields2, rest2) = flatten_fields ty2 in
+ let (fields1, rest1) = flatten_fields ty1 in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ mcomp type_pairs env rest1 rest2;
+ if miss1 <> [] && (object_row ty1).desc = Tnil
+ || miss2 <> [] && (object_row ty2).desc = Tnil then raise (Unify []);
+ List.iter
+ (function (n, k1, t1, k2, t2) ->
+ mcomp_kind k1 k2;
+ mcomp type_pairs env t1 t2)
+ pairs
+
+and mcomp_kind k1 k2 =
+ let k1 = field_kind_repr k1 in
+ let k2 = field_kind_repr k2 in
+ match k1, k2 with
+ (Fvar _, Fvar _)
+ | (Fpresent, Fpresent) -> ()
+ | _ -> raise (Unify [])
+
+and mcomp_row type_pairs env row1 row2 =
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let r1, r2, pairs = merge_row_fields row1.row_fields row2.row_fields in
+ let cannot_erase (_,f) =
+ match row_field_repr f with
+ Rpresent _ -> true
+ | Rabsent | Reither _ -> false
+ in
+ if row1.row_closed && List.exists cannot_erase r2
+ || row2.row_closed && List.exists cannot_erase r1 then raise (Unify []);
+ List.iter
+ (fun (_,f1,f2) ->
+ match row_field_repr f1, row_field_repr f2 with
+ | Rpresent None, (Rpresent (Some _) | Reither (_, _::_, _, _) | Rabsent)
+ | Rpresent (Some _), (Rpresent None | Reither (true, _, _, _) | Rabsent)
+ | (Reither (_, _::_, _, _) | Rabsent), Rpresent None
+ | (Reither (true, _, _, _) | Rabsent), Rpresent (Some _) ->
+ raise (Unify [])
+ | Rpresent(Some t1), Rpresent(Some t2) ->
+ mcomp type_pairs env t1 t2
+ | Rpresent(Some t1), Reither(false, tl2, _, _) ->
+ List.iter (mcomp type_pairs env t1) tl2
+ | Reither(false, tl1, _, _), Rpresent(Some t2) ->
+ List.iter (mcomp type_pairs env t2) tl1
+ | _ -> ())
+ pairs
+
+and mcomp_type_decl type_pairs env p1 p2 tl1 tl2 =
+ try
+ let decl = Env.find_type p1 env in
+ let decl' = Env.find_type p2 env in
+ if Path.same p1 p2 then begin
+ let inj =
+ try List.map Variance.(mem Inj) (Env.find_type p1 env).type_variance
+ with Not_found -> List.map (fun _ -> false) tl1
+ in
+ List.iter2
+ (fun i (t1,t2) -> if i then mcomp type_pairs env t1 t2)
+ inj (List.combine tl1 tl2)
+ end else if non_aliasable p1 decl && non_aliasable p2 decl' then
+ raise (Unify [])
+ else
+ match decl.type_kind, decl'.type_kind with
+ | Type_record (lst,r), Type_record (lst',r') when r = r' ->
+ mcomp_list type_pairs env tl1 tl2;
+ mcomp_record_description type_pairs env lst lst'
+ | Type_variant v1, Type_variant v2 ->
+ mcomp_list type_pairs env tl1 tl2;
+ mcomp_variant_description type_pairs env v1 v2
+ | Type_open, Type_open ->
+ mcomp_list type_pairs env tl1 tl2
+ | Type_abstract, Type_abstract -> ()
+ | Type_abstract, _ when not (non_aliasable p1 decl)-> ()
+ | _, Type_abstract when not (non_aliasable p2 decl') -> ()
+ | _ -> raise (Unify [])
+ with Not_found -> ()
+
+and mcomp_type_option type_pairs env t t' =
+ match t, t' with
+ None, None -> ()
+ | Some t, Some t' -> mcomp type_pairs env t t'
+ | _ -> raise (Unify [])
+
+and mcomp_variant_description type_pairs env xs ys =
+ let rec iter = fun x y ->
+ match x, y with
+ | c1 :: xs, c2 :: ys ->
+ mcomp_type_option type_pairs env c1.cd_res c2.cd_res;
+ begin match c1.cd_args, c2.cd_args with
+ | Cstr_tuple l1, Cstr_tuple l2 -> mcomp_list type_pairs env l1 l2
+ | Cstr_record l1, Cstr_record l2 ->
+ mcomp_record_description type_pairs env l1 l2
+ | _ -> raise (Unify [])
+ end;
+ if Ident.name c1.cd_id = Ident.name c2.cd_id
+ then iter xs ys
+ else raise (Unify [])
+ | [],[] -> ()
+ | _ -> raise (Unify [])
+ in
+ iter xs ys
+
+and mcomp_record_description type_pairs env =
+ let rec iter x y =
+ match x, y with
+ | l1 :: xs, l2 :: ys ->
+ mcomp type_pairs env l1.ld_type l2.ld_type;
+ if Ident.name l1.ld_id = Ident.name l2.ld_id &&
+ l1.ld_mutable = l2.ld_mutable
+ then iter xs ys
+ else raise (Unify [])
+ | [], [] -> ()
+ | _ -> raise (Unify [])
+ in
+ iter
+
+let mcomp env t1 t2 =
+ mcomp (TypePairs.create 4) env t1 t2
+
+(* Real unification *)
+
+let find_lowest_level ty =
+ let lowest = ref generic_level in
+ let rec find ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ if ty.level < !lowest then lowest := ty.level;
+ ty.level <- pivot_level - ty.level;
+ iter_type_expr find ty
+ end
+ in find ty; unmark_type ty; !lowest
+
+let find_newtype_level env path =
+ try match (Env.find_type path env).type_newtype_level with
+ Some x -> x
+ | None -> assert false
+ with Not_found -> assert false
+
+let add_gadt_equation env source destination =
+ local_non_recursive_abbrev !env (Path.Pident source) destination;
+ let destination = duplicate_type destination in
+ let source_lev = find_newtype_level !env (Path.Pident source) in
+ let decl = new_declaration (Some source_lev) (Some destination) in
+ let newtype_level = get_newtype_level () in
+ env := Env.add_local_constraint source decl newtype_level !env;
+ cleanup_abbrev ()
+
+let unify_eq_set = TypePairs.create 11
+
+let order_type_pair t1 t2 =
+ if t1.id <= t2.id then (t1, t2) else (t2, t1)
+
+let add_type_equality t1 t2 =
+ TypePairs.add unify_eq_set (order_type_pair t1 t2) ()
+
+let eq_package_path env p1 p2 =
+ Path.same p1 p2 ||
+ Path.same (normalize_package_path env p1) (normalize_package_path env p2)
+
+let nondep_type' = ref (fun _ _ _ -> assert false)
+let package_subtype = ref (fun _ _ _ _ _ _ _ -> assert false)
+
+let rec concat_longident lid1 =
+ let open Longident in
+ function
+ Lident s -> Ldot (lid1, s)
+ | Ldot (lid2, s) -> Ldot (concat_longident lid1 lid2, s)
+ | Lapply (lid2, lid) -> Lapply (concat_longident lid1 lid2, lid)
+
+let nondep_instance env level id ty =
+ let ty = !nondep_type' env id ty in
+ if level = generic_level then duplicate_type ty else
+ let old = !current_level in
+ current_level := level;
+ let ty = instance env ty in
+ current_level := old;
+ ty
+
+(* Find the type paths nl1 in the module type mty2, and add them to the
+ list (nl2, tl2). raise Not_found if impossible *)
+let complete_type_list ?(allow_absent=false) env nl1 lv2 mty2 nl2 tl2 =
+ let id2 = Ident.create "Pkg" in
+ let env' = Env.add_module id2 mty2 env in
+ let rec complete nl1 ntl2 =
+ match nl1, ntl2 with
+ [], _ -> ntl2
+ | n :: nl, (n2, _ as nt2) :: ntl' when n >= n2 ->
+ nt2 :: complete (if n = n2 then nl else nl1) ntl'
+ | n :: nl, _ ->
+ try
+ let (_, decl) =
+ Env.lookup_type (concat_longident (Longident.Lident "Pkg") n) env'
+ in
+ match decl with
+ {type_arity = 0; type_kind = Type_abstract;
+ type_private = Public; type_manifest = Some t2} ->
+ (n, nondep_instance env' lv2 id2 t2) :: complete nl ntl2
+ | {type_arity = 0; type_kind = Type_abstract;
+ type_private = Public; type_manifest = None} when allow_absent ->
+ complete nl ntl2
+ | _ -> raise Exit
+ with
+ | Not_found when allow_absent -> complete nl ntl2
+ | Exit -> raise Not_found
+ in
+ complete nl1 (List.combine nl2 tl2)
+
+(* raise Not_found rather than Unify if the module types are incompatible *)
+let unify_package env unify_list lv1 p1 n1 tl1 lv2 p2 n2 tl2 =
+ let ntl2 = complete_type_list env n1 lv2 (Mty_ident p2) n2 tl2
+ and ntl1 = complete_type_list env n2 lv2 (Mty_ident p1) n1 tl1 in
+ unify_list (List.map snd ntl1) (List.map snd ntl2);
+ if eq_package_path env p1 p2
+ || !package_subtype env p1 n1 tl1 p2 n2 tl2
+ && !package_subtype env p2 n2 tl2 p1 n1 tl1 then () else raise Not_found
+
+
+let unify_eq env t1 t2 =
+ t1 == t2 ||
+ match !umode with
+ | Expression -> false
+ | Pattern ->
+ try TypePairs.find unify_eq_set (order_type_pair t1 t2); true
+ with Not_found -> false
+
+let unify1_var env t1 t2 =
+ assert (is_Tvar t1);
+ occur env t1 t2;
+ occur_univar env t2;
+ let d1 = t1.desc in
+ link_type t1 t2;
+ try
+ update_level env t1.level t2
+ with Unify _ as e ->
+ t1.desc <- d1;
+ raise e
+
+let rec unify (env:Env.t ref) t1 t2 =
+ (* First step: special cases (optimizations) *)
+ if t1 == t2 then () else
+ let t1 = repr t1 in
+ let t2 = repr t2 in
+ if unify_eq !env t1 t2 then () else
+ let reset_tracing = check_trace_gadt_instances !env in
+
+ try
+ type_changed := true;
+ begin match (t1.desc, t2.desc) with
+ (Tvar _, Tconstr _) when deep_occur t1 t2 ->
+ unify2 env t1 t2
+ | (Tconstr _, Tvar _) when deep_occur t2 t1 ->
+ unify2 env t1 t2
+ | (Tvar _, _) ->
+ unify1_var !env t1 t2
+ | (_, Tvar _) ->
+ unify1_var !env t2 t1
+ | (Tunivar _, Tunivar _) ->
+ unify_univar t1 t2 !univar_pairs;
+ update_level !env t1.level t2;
+ link_type t1 t2
+ | (Tconstr (p1, [], a1), Tconstr (p2, [], a2))
+ when Path.same p1 p2 (* && actual_mode !env = Old *)
+ (* This optimization assumes that t1 does not expand to t2
+ (and conversely), so we fall back to the general case
+ when any of the types has a cached expansion. *)
+ && not (has_cached_expansion p1 !a1
+ || has_cached_expansion p2 !a2) ->
+ update_level !env t1.level t2;
+ link_type t1 t2
+ | (Tconstr (p1, [], _), Tconstr (p2, [], _))
+ when Env.has_local_constraints !env
+ && is_newtype !env p1 && is_newtype !env p2 ->
+ (* Do not use local constraints more than necessary *)
+ begin try
+ if find_newtype_level !env p1 < find_newtype_level !env p2 then
+ unify env t1 (try_expand_once !env t2)
+ else
+ unify env (try_expand_once !env t1) t2
+ with Cannot_expand ->
+ unify2 env t1 t2
+ end
+ | _ ->
+ unify2 env t1 t2
+ end;
+ reset_trace_gadt_instances reset_tracing;
+ with Unify trace ->
+ reset_trace_gadt_instances reset_tracing;
+ raise (Unify ((t1, t2)::trace))
+
+and unify2 env t1 t2 =
+ (* Second step: expansion of abbreviations *)
+ let rec expand_both t1'' t2'' =
+ let t1' = expand_head_unif !env t1 in
+ let t2' = expand_head_unif !env t2 in
+ (* Expansion may have changed the representative of the types... *)
+ if unify_eq !env t1' t1'' && unify_eq !env t2' t2'' then (t1',t2') else
+ expand_both t1' t2'
+ in
+ let t1', t2' = expand_both t1 t2 in
+ let lv = min t1'.level t2'.level in
+ update_level !env lv t2;
+ update_level !env lv t1;
+ if unify_eq !env t1' t2' then () else
+
+ let t1 = repr t1 and t2 = repr t2 in
+ if !trace_gadt_instances then begin
+ (* All types in chains already have the same ambiguity levels *)
+ let ilevel t =
+ match Env.gadt_instance_level !env t with None -> 0 | Some lv -> lv in
+ let lv1 = ilevel t1 and lv2 = ilevel t2 in
+ if lv1 > lv2 then Env.add_gadt_instance_chain !env lv1 t2 else
+ if lv2 > lv1 then Env.add_gadt_instance_chain !env lv2 t1
+ end;
+ let t1, t2 =
+ if !Clflags.principal
+ && (find_lowest_level t1' < lv || find_lowest_level t2' < lv) then
+ (* Expand abbreviations hiding a lower level *)
+ (* Should also do it for parameterized types, after unification... *)
+ (match t1.desc with Tconstr (_, [], _) -> t1' | _ -> t1),
+ (match t2.desc with Tconstr (_, [], _) -> t2' | _ -> t2)
+ else (t1, t2)
+ in
+ if unify_eq !env t1 t1' || not (unify_eq !env t2 t2') then
+ unify3 env t1 t1' t2 t2'
+ else
+ try unify3 env t2 t2' t1 t1' with Unify trace ->
+ raise (Unify (List.map (fun (x, y) -> (y, x)) trace))
+
+and unify3 env t1 t1' t2 t2' =
+ (* Third step: truly unification *)
+ (* Assumes either [t1 == t1'] or [t2 != t2'] *)
+ let d1 = t1'.desc and d2 = t2'.desc in
+ let create_recursion = (t2 != t2') && (deep_occur t1' t2) in
+
+ begin match (d1, d2) with (* handle vars and univars specially *)
+ (Tunivar _, Tunivar _) ->
+ unify_univar t1' t2' !univar_pairs;
+ link_type t1' t2'
+ | (Tvar _, _) ->
+ occur !env t1' t2;
+ occur_univar !env t2;
+ link_type t1' t2;
+ | (_, Tvar _) ->
+ occur !env t2' t1;
+ occur_univar !env t1;
+ link_type t2' t1;
+ | (Tfield _, Tfield _) -> (* special case for GADTs *)
+ unify_fields env t1' t2'
+ | _ ->
+ begin match !umode with
+ | Expression ->
+ occur !env t1' t2';
+ link_type t1' t2
+ | Pattern ->
+ add_type_equality t1' t2'
+ end;
+ try
+ begin match (d1, d2) with
+ (Tarrow (l1, t1, u1, c1), Tarrow (l2, t2, u2, c2)) when l1 = l2 ||
+ !Clflags.classic && not (is_optional l1 || is_optional l2) ->
+ unify env t1 t2; unify env u1 u2;
+ begin match commu_repr c1, commu_repr c2 with
+ Clink r, c2 -> set_commu r c2
+ | c1, Clink r -> set_commu r c1
+ | _ -> ()
+ end
+ | (Ttuple tl1, Ttuple tl2) ->
+ unify_list env tl1 tl2
+ | (Tconstr (p1, tl1, _), Tconstr (p2, tl2, _)) when Path.same p1 p2 ->
+ if !umode = Expression || not !generate_equations then
+ unify_list env tl1 tl2
+ else if !assume_injective then
+ set_mode_pattern ~generate:true ~injective:false
+ (fun () -> unify_list env tl1 tl2)
+ else if in_current_module p1 (* || in_pervasives p1 *)
+ || List.exists (expands_to_datatype !env) [t1'; t1; t2] then
+ unify_list env tl1 tl2
+ else
+ let inj =
+ try List.map Variance.(mem Inj)
+ (Env.find_type p1 !env).type_variance
+ with Not_found -> List.map (fun _ -> false) tl1
+ in
+ List.iter2
+ (fun i (t1, t2) ->
+ if i then unify env t1 t2 else
+ set_mode_pattern ~generate:false ~injective:false
+ begin fun () ->
+ let snap = snapshot () in
+ try unify env t1 t2 with Unify _ ->
+ backtrack snap;
+ reify env t1; reify env t2
+ end)
+ inj (List.combine tl1 tl2)
+ | (Tconstr ((Path.Pident p) as path,[],_),
+ Tconstr ((Path.Pident p') as path',[],_))
+ when is_newtype !env path && is_newtype !env path'
+ && !generate_equations ->
+ let source, destination =
+ if find_newtype_level !env path > find_newtype_level !env path'
+ then p,t2'
+ else p',t1'
+ in
+ add_gadt_equation env source destination
+ | (Tconstr ((Path.Pident p) as path,[],_), _)
+ when is_newtype !env path && !generate_equations ->
+ reify env t2';
+ add_gadt_equation env p t2'
+ | (_, Tconstr ((Path.Pident p) as path,[],_))
+ when is_newtype !env path && !generate_equations ->
+ reify env t1';
+ add_gadt_equation env p t1'
+ | (Tconstr (_,_,_), _) | (_, Tconstr (_,_,_)) when !umode = Pattern ->
+ reify env t1';
+ reify env t2';
+ if !generate_equations then mcomp !env t1' t2'
+ | (Tobject (fi1, nm1), Tobject (fi2, _)) ->
+ unify_fields env fi1 fi2;
+ (* Type [t2'] may have been instantiated by [unify_fields] *)
+ (* XXX One should do some kind of unification... *)
+ begin match (repr t2').desc with
+ Tobject (_, {contents = Some (_, va::_)}) when
+ (match (repr va).desc with
+ Tvar _|Tunivar _|Tnil -> true | _ -> false) -> ()
+ | Tobject (_, nm2) -> set_name nm2 !nm1
+ | _ -> ()
+ end
+ | (Tvariant row1, Tvariant row2) ->
+ if !umode = Expression then
+ unify_row env row1 row2
+ else begin
+ let snap = snapshot () in
+ try unify_row env row1 row2
+ with Unify _ ->
+ backtrack snap;
+ reify env t1';
+ reify env t2';
+ if !generate_equations then mcomp !env t1' t2'
+ end
+ | (Tfield(f,kind,_,rem), Tnil) | (Tnil, Tfield(f,kind,_,rem)) ->
+ begin match field_kind_repr kind with
+ Fvar r when f <> dummy_method ->
+ set_kind r Fabsent;
+ if d2 = Tnil then unify env rem t2'
+ else unify env (newty2 rem.level Tnil) rem
+ | _ -> raise (Unify [])
+ end
+ | (Tnil, Tnil) ->
+ ()
+ | (Tpoly (t1, []), Tpoly (t2, [])) ->
+ unify env t1 t2
+ | (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
+ enter_poly !env univar_pairs t1 tl1 t2 tl2 (unify env)
+ | (Tpackage (p1, n1, tl1), Tpackage (p2, n2, tl2)) ->
+ begin try
+ unify_package !env (unify_list env)
+ t1.level p1 n1 tl1 t2.level p2 n2 tl2
+ with Not_found ->
+ if !umode = Expression then raise (Unify []);
+ List.iter (reify env) (tl1 @ tl2);
+ (* if !generate_equations then List.iter2 (mcomp !env) tl1 tl2 *)
+ end
+ | (_, _) ->
+ raise (Unify [])
+ end;
+ (* XXX Commentaires + changer "create_recursion" *)
+ if create_recursion then
+ match t2.desc with
+ Tconstr (p, tl, abbrev) ->
+ forget_abbrev abbrev p;
+ let t2'' = expand_head_unif !env t2 in
+ if not (closed_parameterized_type tl t2'') then
+ link_type (repr t2) (repr t2')
+ | _ ->
+ () (* t2 has already been expanded by update_level *)
+ with Unify trace ->
+ t1'.desc <- d1;
+ raise (Unify trace)
+ end
+
+and unify_list env tl1 tl2 =
+ if List.length tl1 <> List.length tl2 then
+ raise (Unify []);
+ List.iter2 (unify env) tl1 tl2
+
+(* Build a fresh row variable for unification *)
+and make_rowvar level use1 rest1 use2 rest2 =
+ let set_name ty name =
+ match ty.desc with
+ Tvar None -> log_type ty; ty.desc <- Tvar name
+ | _ -> ()
+ in
+ let name =
+ match rest1.desc, rest2.desc with
+ Tvar (Some _ as name1), Tvar (Some _ as name2) ->
+ if rest1.level <= rest2.level then name1 else name2
+ | Tvar (Some _ as name), _ ->
+ if use2 then set_name rest2 name; name
+ | _, Tvar (Some _ as name) ->
+ if use1 then set_name rest2 name; name
+ | _ -> None
+ in
+ if use1 then rest1 else
+ if use2 then rest2 else newvar2 ?name level
+
+and unify_fields env ty1 ty2 = (* Optimization *)
+ let (fields1, rest1) = flatten_fields ty1
+ and (fields2, rest2) = flatten_fields ty2 in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ let l1 = (repr ty1).level and l2 = (repr ty2).level in
+ let va = make_rowvar (min l1 l2) (miss2=[]) rest1 (miss1=[]) rest2 in
+ let d1 = rest1.desc and d2 = rest2.desc in
+ try
+ unify env (build_fields l1 miss1 va) rest2;
+ unify env rest1 (build_fields l2 miss2 va);
+ List.iter
+ (fun (n, k1, t1, k2, t2) ->
+ unify_kind k1 k2;
+ try
+ if !trace_gadt_instances then update_level !env va.level t1;
+ unify env t1 t2
+ with Unify trace ->
+ raise (Unify ((newty (Tfield(n, k1, t1, newty Tnil)),
+ newty (Tfield(n, k2, t2, newty Tnil)))::trace)))
+ pairs
+ with exn ->
+ log_type rest1; rest1.desc <- d1;
+ log_type rest2; rest2.desc <- d2;
+ raise exn
+
+and unify_kind k1 k2 =
+ let k1 = field_kind_repr k1 in
+ let k2 = field_kind_repr k2 in
+ if k1 == k2 then () else
+ match k1, k2 with
+ (Fvar r, (Fvar _ | Fpresent)) -> set_kind r k2
+ | (Fpresent, Fvar r) -> set_kind r k1
+ | (Fpresent, Fpresent) -> ()
+ | _ -> assert false
+
+and unify_pairs mode env tpl =
+ List.iter (fun (t1, t2) -> unify env t1 t2) tpl
+
+and unify_row env row1 row2 =
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let rm1 = row_more row1 and rm2 = row_more row2 in
+ if unify_eq !env rm1 rm2 then () else
+ let r1, r2, pairs = merge_row_fields row1.row_fields row2.row_fields in
+ if r1 <> [] && r2 <> [] then begin
+ let ht = Hashtbl.create (List.length r1) in
+ List.iter (fun (l,_) -> Hashtbl.add ht (hash_variant l) l) r1;
+ List.iter
+ (fun (l,_) ->
+ try raise (Tags(l, Hashtbl.find ht (hash_variant l)))
+ with Not_found -> ())
+ r2
+ end;
+ let fixed1 = row_fixed row1 and fixed2 = row_fixed row2 in
+ let more =
+ if fixed1 then rm1 else
+ if fixed2 then rm2 else
+ newty2 (min rm1.level rm2.level) (Tvar None) in
+ let fixed = fixed1 || fixed2
+ and closed = row1.row_closed || row2.row_closed in
+ let keep switch =
+ List.for_all
+ (fun (_,f1,f2) ->
+ let f1, f2 = switch f1 f2 in
+ row_field_repr f1 = Rabsent || row_field_repr f2 <> Rabsent)
+ pairs
+ in
+ let empty fields =
+ List.for_all (fun (_,f) -> row_field_repr f = Rabsent) fields in
+ (* Check whether we are going to build an empty type *)
+ if closed && (empty r1 || row2.row_closed) && (empty r2 || row1.row_closed)
+ && List.for_all
+ (fun (_,f1,f2) ->
+ row_field_repr f1 = Rabsent || row_field_repr f2 = Rabsent)
+ pairs
+ then raise (Unify [mkvariant [] true, mkvariant [] true]);
+ let name =
+ if row1.row_name <> None && (row1.row_closed || empty r2) &&
+ (not row2.row_closed || keep (fun f1 f2 -> f1, f2) && empty r1)
+ then row1.row_name
+ else if row2.row_name <> None && (row2.row_closed || empty r1) &&
+ (not row1.row_closed || keep (fun f1 f2 -> f2, f1) && empty r2)
+ then row2.row_name
+ else None
+ in
+ let row0 = {row_fields = []; row_more = more; row_bound = ();
+ row_closed = closed; row_fixed = fixed; row_name = name} in
+ let set_more row rest =
+ let rest =
+ if closed then
+ filter_row_fields row.row_closed rest
+ else rest in
+ if rest <> [] && (row.row_closed || row_fixed row)
+ || closed && row_fixed row && not row.row_closed then begin
+ let t1 = mkvariant [] true and t2 = mkvariant rest false in
+ raise (Unify [if row == row1 then (t1,t2) else (t2,t1)])
+ end;
+ (* The following test is not principal... should rather use Tnil *)
+ let rm = row_more row in
+ if !trace_gadt_instances && rm.desc = Tnil then () else
+ if !trace_gadt_instances then
+ update_level !env rm.level (newgenty (Tvariant row));
+ if row_fixed row then
+ if more == rm then () else
+ if is_Tvar rm then link_type rm more else unify env rm more
+ else
+ let ty = newgenty (Tvariant {row0 with row_fields = rest}) in
+ update_level !env rm.level ty;
+ link_type rm ty
+ in
+ let md1 = rm1.desc and md2 = rm2.desc in
+ begin try
+ set_more row2 r1;
+ set_more row1 r2;
+ List.iter
+ (fun (l,f1,f2) ->
+ try unify_row_field env fixed1 fixed2 more l f1 f2
+ with Unify trace ->
+ raise (Unify ((mkvariant [l,f1] true,
+ mkvariant [l,f2] true) :: trace)))
+ pairs;
+ with exn ->
+ log_type rm1; rm1.desc <- md1; log_type rm2; rm2.desc <- md2; raise exn
+ end
+
+and unify_row_field env fixed1 fixed2 more l f1 f2 =
+ let f1 = row_field_repr f1 and f2 = row_field_repr f2 in
+ if f1 == f2 then () else
+ match f1, f2 with
+ Rpresent(Some t1), Rpresent(Some t2) -> unify env t1 t2
+ | Rpresent None, Rpresent None -> ()
+ | Reither(c1, tl1, m1, e1), Reither(c2, tl2, m2, e2) ->
+ if e1 == e2 then () else
+ let redo =
+ (m1 || m2 || fixed1 || fixed2 ||
+ !rigid_variants && (List.length tl1 = 1 || List.length tl2 = 1)) &&
+ begin match tl1 @ tl2 with [] -> false
+ | t1 :: tl ->
+ if c1 || c2 then raise (Unify []);
+ List.iter (unify env t1) tl;
+ !e1 <> None || !e2 <> None
+ end in
+ if redo then unify_row_field env fixed1 fixed2 more l f1 f2 else
+ let tl1 = List.map repr tl1 and tl2 = List.map repr tl2 in
+ let rec remq tl = function [] -> []
+ | ty :: tl' ->
+ if List.memq ty tl then remq tl tl' else ty :: remq tl tl'
+ in
+ let tl2' = remq tl2 tl1 and tl1' = remq tl1 tl2 in
+ (* PR#6744 *)
+ let split_univars =
+ List.partition
+ (fun ty -> try occur_univar !env ty; true with Unify _ -> false) in
+ let (tl1',tlu1) = split_univars tl1'
+ and (tl2',tlu2) = split_univars tl2' in
+ begin match tlu1, tlu2 with
+ [], [] -> ()
+ | (tu1::tlu1), (tu2::_) ->
+ (* Attempt to merge all the types containing univars *)
+ List.iter (unify env tu1) (tlu1@tlu2)
+ | (tu::_, []) | ([], tu::_) -> occur_univar !env tu
+ end;
+ (* Is this handling of levels really principal? *)
+ List.iter (update_level !env (repr more).level) (tl1' @ tl2');
+ let e = ref None in
+ let f1' = Reither(c1 || c2, tl1', m1 || m2, e)
+ and f2' = Reither(c1 || c2, tl2', m1 || m2, e) in
+ set_row_field e1 f1'; set_row_field e2 f2';
+ | Reither(_, _, false, e1), Rabsent when not fixed1 -> set_row_field e1 f2
+ | Rabsent, Reither(_, _, false, e2) when not fixed2 -> set_row_field e2 f1
+ | Rabsent, Rabsent -> ()
+ | Reither(false, tl, _, e1), Rpresent(Some t2) when not fixed1 ->
+ set_row_field e1 f2;
+ update_level !env (repr more).level t2;
+ (try List.iter (fun t1 -> unify env t1 t2) tl
+ with exn -> e1 := None; raise exn)
+ | Rpresent(Some t1), Reither(false, tl, _, e2) when not fixed2 ->
+ set_row_field e2 f1;
+ update_level !env (repr more).level t1;
+ (try List.iter (unify env t1) tl
+ with exn -> e2 := None; raise exn)
+ | Reither(true, [], _, e1), Rpresent None when not fixed1 ->
+ set_row_field e1 f2
+ | Rpresent None, Reither(true, [], _, e2) when not fixed2 ->
+ set_row_field e2 f1
+ | _ -> raise (Unify [])
+
+
+let unify env ty1 ty2 =
+ try
+ unify env ty1 ty2
+ with
+ Unify trace ->
+ raise (Unify (expand_trace !env trace))
+ | Recursive_abbrev ->
+ raise (Unification_recursive_abbrev (expand_trace !env [(ty1,ty2)]))
+
+let unify_gadt ~newtype_level:lev (env:Env.t ref) ty1 ty2 =
+ try
+ univar_pairs := [];
+ newtype_level := Some lev;
+ set_mode_pattern ~generate:true ~injective:true
+ (fun () -> unify env ty1 ty2);
+ newtype_level := None;
+ TypePairs.clear unify_eq_set;
+ with e ->
+ TypePairs.clear unify_eq_set;
+ match e with
+ Unify e -> raise (Unify e)
+ | e -> newtype_level := None; raise e
+
+let unify_var env t1 t2 =
+ let t1 = repr t1 and t2 = repr t2 in
+ if t1 == t2 then () else
+ match t1.desc with
+ Tvar _ ->
+ let reset_tracing = check_trace_gadt_instances env in
+ begin try
+ occur env t1 t2;
+ update_level env t1.level t2;
+ link_type t1 t2;
+ reset_trace_gadt_instances reset_tracing;
+ with Unify trace ->
+ reset_trace_gadt_instances reset_tracing;
+ let expanded_trace = expand_trace env ((t1,t2)::trace) in
+ raise (Unify expanded_trace)
+ end
+ | _ ->
+ unify (ref env) t1 t2
+
+let _ = unify' := unify_var
+
+let unify_pairs env ty1 ty2 pairs =
+ univar_pairs := pairs;
+ unify env ty1 ty2
+
+let unify env ty1 ty2 =
+ unify_pairs (ref env) ty1 ty2 []
+
+
+
+(**** Special cases of unification ****)
+
+let expand_head_trace env t =
+ let reset_tracing = check_trace_gadt_instances env in
+ let t = expand_head_unif env t in
+ reset_trace_gadt_instances reset_tracing;
+ t
+
+(*
+ Unify [t] and [l:'a -> 'b]. Return ['a] and ['b].
+ In label mode, label mismatch is accepted when
+ (1) the requested label is ""
+ (2) the original label is not optional
+*)
+
+let filter_arrow env t l =
+ let t = expand_head_trace env t in
+ match t.desc with
+ Tvar _ ->
+ let lv = t.level in
+ let t1 = newvar2 lv and t2 = newvar2 lv in
+ let t' = newty2 lv (Tarrow (l, t1, t2, Cok)) in
+ link_type t t';
+ (t1, t2)
+ | Tarrow(l', t1, t2, _)
+ when l = l' || !Clflags.classic && l = Nolabel && not (is_optional l') ->
+ (t1, t2)
+ | _ ->
+ raise (Unify [])
+
+(* Used by [filter_method]. *)
+let rec filter_method_field env name priv ty =
+ let ty = expand_head_trace env ty in
+ match ty.desc with
+ Tvar _ ->
+ let level = ty.level in
+ let ty1 = newvar2 level and ty2 = newvar2 level in
+ let ty' = newty2 level (Tfield (name,
+ begin match priv with
+ Private -> Fvar (ref None)
+ | Public -> Fpresent
+ end,
+ ty1, ty2))
+ in
+ link_type ty ty';
+ ty1
+ | Tfield(n, kind, ty1, ty2) ->
+ let kind = field_kind_repr kind in
+ if (n = name) && (kind <> Fabsent) then begin
+ if priv = Public then
+ unify_kind kind Fpresent;
+ ty1
+ end else
+ filter_method_field env name priv ty2
+ | _ ->
+ raise (Unify [])
+
+(* Unify [ty] and [< name : 'a; .. >]. Return ['a]. *)
+let filter_method env name priv ty =
+ let ty = expand_head_trace env ty in
+ match ty.desc with
+ Tvar _ ->
+ let ty1 = newvar () in
+ let ty' = newobj ty1 in
+ update_level env ty.level ty';
+ link_type ty ty';
+ filter_method_field env name priv ty1
+ | Tobject(f, _) ->
+ filter_method_field env name priv f
+ | _ ->
+ raise (Unify [])
+
+let check_filter_method env name priv ty =
+ ignore(filter_method env name priv ty)
+
+let filter_self_method env lab priv meths ty =
+ let ty' = filter_method env lab priv ty in
+ try
+ Meths.find lab !meths
+ with Not_found ->
+ let pair = (Ident.create lab, ty') in
+ meths := Meths.add lab pair !meths;
+ pair
+
+
+ (***********************************)
+ (* Matching between type schemes *)
+ (***********************************)
+
+(*
+ Update the level of [ty]. First check that the levels of generic
+ variables from the subject are not lowered.
+*)
+let moregen_occur env level ty =
+ let rec occur ty =
+ let ty = repr ty in
+ if ty.level > level then begin
+ if is_Tvar ty && ty.level >= generic_level - 1 then raise Occur;
+ ty.level <- pivot_level - ty.level;
+ match ty.desc with
+ Tvariant row when static_row row ->
+ iter_row occur row
+ | _ ->
+ iter_type_expr occur ty
+ end
+ in
+ begin try
+ occur ty; unmark_type ty
+ with Occur ->
+ unmark_type ty; raise (Unify [])
+ end;
+ (* also check for free univars *)
+ occur_univar env ty;
+ update_level env level ty
+
+let may_instantiate inst_nongen t1 =
+ if inst_nongen then t1.level <> generic_level - 1
+ else t1.level = generic_level
+
+let rec moregen inst_nongen type_pairs env t1 t2 =
+ if t1 == t2 then () else
+ let t1 = repr t1 in
+ let t2 = repr t2 in
+ if t1 == t2 then () else
+
+ try
+ match (t1.desc, t2.desc) with
+ (Tvar _, _) when may_instantiate inst_nongen t1 ->
+ moregen_occur env t1.level t2;
+ occur env t1 t2;
+ link_type t1 t2
+ | (Tconstr (p1, [], _), Tconstr (p2, [], _)) when Path.same p1 p2 ->
+ ()
+ | _ ->
+ let t1' = expand_head env t1 in
+ let t2' = expand_head env t2 in
+ (* Expansion may have changed the representative of the types... *)
+ let t1' = repr t1' and t2' = repr t2' in
+ if t1' == t2' then () else
+ begin try
+ TypePairs.find type_pairs (t1', t2')
+ with Not_found ->
+ TypePairs.add type_pairs (t1', t2') ();
+ match (t1'.desc, t2'.desc) with
+ (Tvar _, _) when may_instantiate inst_nongen t1' ->
+ moregen_occur env t1'.level t2;
+ link_type t1' t2
+ | (Tarrow (l1, t1, u1, _), Tarrow (l2, t2, u2, _)) when l1 = l2
+ || !Clflags.classic && not (is_optional l1 || is_optional l2) ->
+ moregen inst_nongen type_pairs env t1 t2;
+ moregen inst_nongen type_pairs env u1 u2
+ | (Ttuple tl1, Ttuple tl2) ->
+ moregen_list inst_nongen type_pairs env tl1 tl2
+ | (Tconstr (p1, tl1, _), Tconstr (p2, tl2, _))
+ when Path.same p1 p2 ->
+ moregen_list inst_nongen type_pairs env tl1 tl2
+ | (Tpackage (p1, n1, tl1), Tpackage (p2, n2, tl2)) ->
+ begin try
+ unify_package env (moregen_list inst_nongen type_pairs env)
+ t1'.level p1 n1 tl1 t2'.level p2 n2 tl2
+ with Not_found -> raise (Unify [])
+ end
+ | (Tvariant row1, Tvariant row2) ->
+ moregen_row inst_nongen type_pairs env row1 row2
+ | (Tobject (fi1, nm1), Tobject (fi2, nm2)) ->
+ moregen_fields inst_nongen type_pairs env fi1 fi2
+ | (Tfield _, Tfield _) -> (* Actually unused *)
+ moregen_fields inst_nongen type_pairs env t1' t2'
+ | (Tnil, Tnil) ->
+ ()
+ | (Tpoly (t1, []), Tpoly (t2, [])) ->
+ moregen inst_nongen type_pairs env t1 t2
+ | (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
+ enter_poly env univar_pairs t1 tl1 t2 tl2
+ (moregen inst_nongen type_pairs env)
+ | (Tunivar _, Tunivar _) ->
+ unify_univar t1' t2' !univar_pairs
+ | (_, _) ->
+ raise (Unify [])
+ end
+ with Unify trace ->
+ raise (Unify ((t1, t2)::trace))
+
+and moregen_list inst_nongen type_pairs env tl1 tl2 =
+ if List.length tl1 <> List.length tl2 then
+ raise (Unify []);
+ List.iter2 (moregen inst_nongen type_pairs env) tl1 tl2
+
+and moregen_fields inst_nongen type_pairs env ty1 ty2 =
+ let (fields1, rest1) = flatten_fields ty1
+ and (fields2, rest2) = flatten_fields ty2 in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ if miss1 <> [] then raise (Unify []);
+ moregen inst_nongen type_pairs env rest1
+ (build_fields (repr ty2).level miss2 rest2);
+ List.iter
+ (fun (n, k1, t1, k2, t2) ->
+ moregen_kind k1 k2;
+ try moregen inst_nongen type_pairs env t1 t2 with Unify trace ->
+ raise (Unify ((newty (Tfield(n, k1, t1, rest2)),
+ newty (Tfield(n, k2, t2, rest2)))::trace)))
+ pairs
+
+and moregen_kind k1 k2 =
+ let k1 = field_kind_repr k1 in
+ let k2 = field_kind_repr k2 in
+ if k1 == k2 then () else
+ match k1, k2 with
+ (Fvar r, (Fvar _ | Fpresent)) -> set_kind r k2
+ | (Fpresent, Fpresent) -> ()
+ | _ -> raise (Unify [])
+
+and moregen_row inst_nongen type_pairs env row1 row2 =
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let rm1 = repr row1.row_more and rm2 = repr row2.row_more in
+ if rm1 == rm2 then () else
+ let may_inst =
+ is_Tvar rm1 && may_instantiate inst_nongen rm1 || rm1.desc = Tnil in
+ let r1, r2, pairs = merge_row_fields row1.row_fields row2.row_fields in
+ let r1, r2 =
+ if row2.row_closed then
+ filter_row_fields may_inst r1, filter_row_fields false r2
+ else r1, r2
+ in
+ if r1 <> [] || row1.row_closed && (not row2.row_closed || r2 <> [])
+ then raise (Unify []);
+ begin match rm1.desc, rm2.desc with
+ Tunivar _, Tunivar _ ->
+ unify_univar rm1 rm2 !univar_pairs
+ | Tunivar _, _ | _, Tunivar _ ->
+ raise (Unify [])
+ | _ when static_row row1 -> ()
+ | _ when may_inst ->
+ let ext = newgenty (Tvariant {row2 with row_fields = r2}) in
+ moregen_occur env rm1.level ext;
+ link_type rm1 ext
+ | Tconstr _, Tconstr _ ->
+ moregen inst_nongen type_pairs env rm1 rm2
+ | _ -> raise (Unify [])
+ end;
+ List.iter
+ (fun (l,f1,f2) ->
+ let f1 = row_field_repr f1 and f2 = row_field_repr f2 in
+ if f1 == f2 then () else
+ match f1, f2 with
+ Rpresent(Some t1), Rpresent(Some t2) ->
+ moregen inst_nongen type_pairs env t1 t2
+ | Rpresent None, Rpresent None -> ()
+ | Reither(false, tl1, _, e1), Rpresent(Some t2) when may_inst ->
+ set_row_field e1 f2;
+ List.iter (fun t1 -> moregen inst_nongen type_pairs env t1 t2) tl1
+ | Reither(c1, tl1, _, e1), Reither(c2, tl2, m2, e2) ->
+ if e1 != e2 then begin
+ if c1 && not c2 then raise(Unify []);
+ set_row_field e1 (Reither (c2, [], m2, e2));
+ if List.length tl1 = List.length tl2 then
+ List.iter2 (moregen inst_nongen type_pairs env) tl1 tl2
+ else match tl2 with
+ t2 :: _ ->
+ List.iter (fun t1 -> moregen inst_nongen type_pairs env t1 t2)
+ tl1
+ | [] ->
+ if tl1 <> [] then raise (Unify [])
+ end
+ | Reither(true, [], _, e1), Rpresent None when may_inst ->
+ set_row_field e1 f2
+ | Reither(_, _, _, e1), Rabsent when may_inst ->
+ set_row_field e1 f2
+ | Rabsent, Rabsent -> ()
+ | _ -> raise (Unify []))
+ pairs
+
+(* Must empty univar_pairs first *)
+let moregen inst_nongen type_pairs env patt subj =
+ univar_pairs := [];
+ moregen inst_nongen type_pairs env patt subj
+
+(*
+ Non-generic variable can be instanciated only if [inst_nongen] is
+ true. So, [inst_nongen] should be set to false if the subject might
+ contain non-generic variables (and we do not want them to be
+ instanciated).
+ Usually, the subject is given by the user, and the pattern
+ is unimportant. So, no need to propagate abbreviations.
+*)
+let moregeneral env inst_nongen pat_sch subj_sch =
+ let old_level = !current_level in
+ current_level := generic_level - 1;
+ (*
+ Generic variables are first duplicated with [instance]. So,
+ their levels are lowered to [generic_level - 1]. The subject is
+ then copied with [duplicate_type]. That way, its levels won't be
+ changed.
+ *)
+ let subj = duplicate_type (instance env subj_sch) in
+ current_level := generic_level;
+ (* Duplicate generic variables *)
+ let patt = instance env pat_sch in
+ let res =
+ try moregen inst_nongen (TypePairs.create 13) env patt subj; true with
+ Unify _ -> false
+ in
+ current_level := old_level;
+ res
+
+
+(* Alternative approach: "rigidify" a type scheme,
+ and check validity after unification *)
+(* Simpler, no? *)
+
+let rec rigidify_rec vars ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ match ty.desc with
+ | Tvar _ ->
+ if not (List.memq ty !vars) then vars := ty :: !vars
+ | Tvariant row ->
+ let row = row_repr row in
+ let more = repr row.row_more in
+ if is_Tvar more && not (row_fixed row) then begin
+ let more' = newty2 more.level more.desc in
+ let row' = {row with row_fixed=true; row_fields=[]; row_more=more'}
+ in link_type more (newty2 ty.level (Tvariant row'))
+ end;
+ iter_row (rigidify_rec vars) row;
+ (* only consider the row variable if the variant is not static *)
+ if not (static_row row) then rigidify_rec vars (row_more row)
+ | _ ->
+ iter_type_expr (rigidify_rec vars) ty
+ end
+
+let rigidify ty =
+ let vars = ref [] in
+ rigidify_rec vars ty;
+ unmark_type ty;
+ !vars
+
+let all_distinct_vars env vars =
+ let tyl = ref [] in
+ List.for_all
+ (fun ty ->
+ let ty = expand_head env ty in
+ if List.memq ty !tyl then false else
+ (tyl := ty :: !tyl; is_Tvar ty))
+ vars
+
+let matches env ty ty' =
+ let snap = snapshot () in
+ let vars = rigidify ty in
+ cleanup_abbrev ();
+ let ok =
+ try unify env ty ty'; all_distinct_vars env vars
+ with Unify _ -> false
+ in
+ backtrack snap;
+ ok
+
+
+ (*********************************************)
+ (* Equivalence between parameterized types *)
+ (*********************************************)
+
+let rec get_object_row ty =
+ match repr ty with
+ | {desc=Tfield (_, _, _, tl)} -> get_object_row tl
+ | ty -> ty
+
+let expand_head_rigid env ty =
+ let old = !rigid_variants in
+ rigid_variants := true;
+ let ty' = expand_head env ty in
+ rigid_variants := old; ty'
+
+let normalize_subst subst =
+ if List.exists
+ (function {desc=Tlink _}, _ | _, {desc=Tlink _} -> true | _ -> false)
+ !subst
+ then subst := List.map (fun (t1,t2) -> repr t1, repr t2) !subst
+
+let rec eqtype rename type_pairs subst env t1 t2 =
+ if t1 == t2 then () else
+ let t1 = repr t1 in
+ let t2 = repr t2 in
+ if t1 == t2 then () else
+
+ try
+ match (t1.desc, t2.desc) with
+ (Tvar _, Tvar _) when rename ->
+ begin try
+ normalize_subst subst;
+ if List.assq t1 !subst != t2 then raise (Unify [])
+ with Not_found ->
+ if List.exists (fun (_, t) -> t == t2) !subst then raise (Unify []);
+ subst := (t1, t2) :: !subst
+ end
+ | (Tconstr (p1, [], _), Tconstr (p2, [], _)) when Path.same p1 p2 ->
+ ()
+ | _ ->
+ let t1' = expand_head_rigid env t1 in
+ let t2' = expand_head_rigid env t2 in
+ (* Expansion may have changed the representative of the types... *)
+ let t1' = repr t1' and t2' = repr t2' in
+ if t1' == t2' then () else
+ begin try
+ TypePairs.find type_pairs (t1', t2')
+ with Not_found ->
+ TypePairs.add type_pairs (t1', t2') ();
+ match (t1'.desc, t2'.desc) with
+ (Tvar _, Tvar _) when rename ->
+ begin try
+ normalize_subst subst;
+ if List.assq t1' !subst != t2' then raise (Unify [])
+ with Not_found ->
+ if List.exists (fun (_, t) -> t == t2') !subst
+ then raise (Unify []);
+ subst := (t1', t2') :: !subst
+ end
+ | (Tarrow (l1, t1, u1, _), Tarrow (l2, t2, u2, _)) when l1 = l2
+ || !Clflags.classic && not (is_optional l1 || is_optional l2) ->
+ eqtype rename type_pairs subst env t1 t2;
+ eqtype rename type_pairs subst env u1 u2;
+ | (Ttuple tl1, Ttuple tl2) ->
+ eqtype_list rename type_pairs subst env tl1 tl2
+ | (Tconstr (p1, tl1, _), Tconstr (p2, tl2, _))
+ when Path.same p1 p2 ->
+ eqtype_list rename type_pairs subst env tl1 tl2
+ | (Tpackage (p1, n1, tl1), Tpackage (p2, n2, tl2)) ->
+ begin try
+ unify_package env (eqtype_list rename type_pairs subst env)
+ t1'.level p1 n1 tl1 t2'.level p2 n2 tl2
+ with Not_found -> raise (Unify [])
+ end
+ | (Tvariant row1, Tvariant row2) ->
+ eqtype_row rename type_pairs subst env row1 row2
+ | (Tobject (fi1, nm1), Tobject (fi2, nm2)) ->
+ eqtype_fields rename type_pairs subst env fi1 fi2
+ | (Tfield _, Tfield _) -> (* Actually unused *)
+ eqtype_fields rename type_pairs subst env t1' t2'
+ | (Tnil, Tnil) ->
+ ()
+ | (Tpoly (t1, []), Tpoly (t2, [])) ->
+ eqtype rename type_pairs subst env t1 t2
+ | (Tpoly (t1, tl1), Tpoly (t2, tl2)) ->
+ enter_poly env univar_pairs t1 tl1 t2 tl2
+ (eqtype rename type_pairs subst env)
+ | (Tunivar _, Tunivar _) ->
+ unify_univar t1' t2' !univar_pairs
+ | (_, _) ->
+ raise (Unify [])
+ end
+ with Unify trace ->
+ raise (Unify ((t1, t2)::trace))
+
+and eqtype_list rename type_pairs subst env tl1 tl2 =
+ if List.length tl1 <> List.length tl2 then
+ raise (Unify []);
+ List.iter2 (eqtype rename type_pairs subst env) tl1 tl2
+
+and eqtype_fields rename type_pairs subst env ty1 ty2 =
+ let (fields1, rest1) = flatten_fields ty1 in
+ let (fields2, rest2) = flatten_fields ty2 in
+ (* First check if same row => already equal *)
+ let same_row =
+ rest1 == rest2 || TypePairs.mem type_pairs (rest1,rest2) ||
+ (rename && List.mem (rest1, rest2) !subst)
+ in
+ if same_row then () else
+ (* Try expansion, needed when called from Includecore.type_manifest *)
+ match expand_head_rigid env rest2 with
+ {desc=Tobject(ty2,_)} -> eqtype_fields rename type_pairs subst env ty1 ty2
+ | _ ->
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ eqtype rename type_pairs subst env rest1 rest2;
+ if (miss1 <> []) || (miss2 <> []) then raise (Unify []);
+ List.iter
+ (function (n, k1, t1, k2, t2) ->
+ eqtype_kind k1 k2;
+ try eqtype rename type_pairs subst env t1 t2 with Unify trace ->
+ raise (Unify ((newty (Tfield(n, k1, t1, rest2)),
+ newty (Tfield(n, k2, t2, rest2)))::trace)))
+ pairs
+
+and eqtype_kind k1 k2 =
+ let k1 = field_kind_repr k1 in
+ let k2 = field_kind_repr k2 in
+ match k1, k2 with
+ (Fvar _, Fvar _)
+ | (Fpresent, Fpresent) -> ()
+ | _ -> raise (Unify [])
+
+and eqtype_row rename type_pairs subst env row1 row2 =
+ (* Try expansion, needed when called from Includecore.type_manifest *)
+ match expand_head_rigid env (row_more row2) with
+ {desc=Tvariant row2} -> eqtype_row rename type_pairs subst env row1 row2
+ | _ ->
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let r1, r2, pairs = merge_row_fields row1.row_fields row2.row_fields in
+ if row1.row_closed <> row2.row_closed
+ || not row1.row_closed && (r1 <> [] || r2 <> [])
+ || filter_row_fields false (r1 @ r2) <> []
+ then raise (Unify []);
+ if not (static_row row1) then
+ eqtype rename type_pairs subst env row1.row_more row2.row_more;
+ List.iter
+ (fun (_,f1,f2) ->
+ match row_field_repr f1, row_field_repr f2 with
+ Rpresent(Some t1), Rpresent(Some t2) ->
+ eqtype rename type_pairs subst env t1 t2
+ | Reither(true, [], _, _), Reither(true, [], _, _) ->
+ ()
+ | Reither(false, t1::tl1, _, _), Reither(false, t2::tl2, _, _) ->
+ eqtype rename type_pairs subst env t1 t2;
+ if List.length tl1 = List.length tl2 then
+ (* if same length allow different types (meaning?) *)
+ List.iter2 (eqtype rename type_pairs subst env) tl1 tl2
+ else begin
+ (* otherwise everything must be equal *)
+ List.iter (eqtype rename type_pairs subst env t1) tl2;
+ List.iter (fun t1 -> eqtype rename type_pairs subst env t1 t2) tl1
+ end
+ | Rpresent None, Rpresent None -> ()
+ | Rabsent, Rabsent -> ()
+ | _ -> raise (Unify []))
+ pairs
+
+(* Two modes: with or without renaming of variables *)
+let equal env rename tyl1 tyl2 =
+ try
+ univar_pairs := [];
+ eqtype_list rename (TypePairs.create 11) (ref []) env tyl1 tyl2; true
+ with
+ Unify _ -> false
+
+(* Must empty univar_pairs first *)
+let eqtype rename type_pairs subst env t1 t2 =
+ univar_pairs := [];
+ eqtype rename type_pairs subst env t1 t2
+
+
+ (*************************)
+ (* Class type matching *)
+ (*************************)
+
+
+type class_match_failure =
+ CM_Virtual_class
+ | CM_Parameter_arity_mismatch of int * int
+ | CM_Type_parameter_mismatch of Env.t * (type_expr * type_expr) list
+ | CM_Class_type_mismatch of Env.t * class_type * class_type
+ | CM_Parameter_mismatch of Env.t * (type_expr * type_expr) list
+ | CM_Val_type_mismatch of string * Env.t * (type_expr * type_expr) list
+ | CM_Meth_type_mismatch of string * Env.t * (type_expr * type_expr) list
+ | CM_Non_mutable_value of string
+ | CM_Non_concrete_value of string
+ | CM_Missing_value of string
+ | CM_Missing_method of string
+ | CM_Hide_public of string
+ | CM_Hide_virtual of string * string
+ | CM_Public_method of string
+ | CM_Private_method of string
+ | CM_Virtual_method of string
+
+exception Failure of class_match_failure list
+
+let rec moregen_clty trace type_pairs env cty1 cty2 =
+ try
+ match cty1, cty2 with
+ Cty_constr (_, _, cty1), _ ->
+ moregen_clty true type_pairs env cty1 cty2
+ | _, Cty_constr (_, _, cty2) ->
+ moregen_clty true type_pairs env cty1 cty2
+ | Cty_arrow (l1, ty1, cty1'), Cty_arrow (l2, ty2, cty2') when l1 = l2 ->
+ begin try moregen true type_pairs env ty1 ty2 with Unify trace ->
+ raise (Failure [CM_Parameter_mismatch (env, expand_trace env trace)])
+ end;
+ moregen_clty false type_pairs env cty1' cty2'
+ | Cty_signature sign1, Cty_signature sign2 ->
+ let ty1 = object_fields (repr sign1.csig_self) in
+ let ty2 = object_fields (repr sign2.csig_self) in
+ let (fields1, rest1) = flatten_fields ty1
+ and (fields2, rest2) = flatten_fields ty2 in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ List.iter
+ (fun (lab, k1, t1, k2, t2) ->
+ begin try moregen true type_pairs env t1 t2 with Unify trace ->
+ raise (Failure [CM_Meth_type_mismatch
+ (lab, env, expand_trace env trace)])
+ end)
+ pairs;
+ Vars.iter
+ (fun lab (mut, v, ty) ->
+ let (mut', v', ty') = Vars.find lab sign1.csig_vars in
+ try moregen true type_pairs env ty' ty with Unify trace ->
+ raise (Failure [CM_Val_type_mismatch
+ (lab, env, expand_trace env trace)]))
+ sign2.csig_vars
+ | _ ->
+ raise (Failure [])
+ with
+ Failure error when trace || error = [] ->
+ raise (Failure (CM_Class_type_mismatch (env, cty1, cty2)::error))
+
+let match_class_types ?(trace=true) env pat_sch subj_sch =
+ let type_pairs = TypePairs.create 53 in
+ let old_level = !current_level in
+ current_level := generic_level - 1;
+ (*
+ Generic variables are first duplicated with [instance]. So,
+ their levels are lowered to [generic_level - 1]. The subject is
+ then copied with [duplicate_type]. That way, its levels won't be
+ changed.
+ *)
+ let (_, subj_inst) = instance_class [] subj_sch in
+ let subj = duplicate_class_type subj_inst in
+ current_level := generic_level;
+ (* Duplicate generic variables *)
+ let (_, patt) = instance_class [] pat_sch in
+ let res =
+ let sign1 = signature_of_class_type patt in
+ let sign2 = signature_of_class_type subj in
+ let t1 = repr sign1.csig_self in
+ let t2 = repr sign2.csig_self in
+ TypePairs.add type_pairs (t1, t2) ();
+ let (fields1, rest1) = flatten_fields (object_fields t1)
+ and (fields2, rest2) = flatten_fields (object_fields t2) in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ let error =
+ List.fold_right
+ (fun (lab, k, _) err ->
+ let err =
+ let k = field_kind_repr k in
+ begin match k with
+ Fvar r -> set_kind r Fabsent; err
+ | _ -> CM_Hide_public lab::err
+ end
+ in
+ if Concr.mem lab sign1.csig_concr then err
+ else CM_Hide_virtual ("method", lab) :: err)
+ miss1 []
+ in
+ let missing_method = List.map (fun (m, _, _) -> m) miss2 in
+ let error =
+ (List.map (fun m -> CM_Missing_method m) missing_method) @ error
+ in
+ (* Always succeeds *)
+ moregen true type_pairs env rest1 rest2;
+ let error =
+ List.fold_right
+ (fun (lab, k1, t1, k2, t2) err ->
+ try moregen_kind k1 k2; err with
+ Unify _ -> CM_Public_method lab::err)
+ pairs error
+ in
+ let error =
+ Vars.fold
+ (fun lab (mut, vr, ty) err ->
+ try
+ let (mut', vr', ty') = Vars.find lab sign1.csig_vars in
+ if mut = Mutable && mut' <> Mutable then
+ CM_Non_mutable_value lab::err
+ else if vr = Concrete && vr' <> Concrete then
+ CM_Non_concrete_value lab::err
+ else
+ err
+ with Not_found ->
+ CM_Missing_value lab::err)
+ sign2.csig_vars error
+ in
+ let error =
+ Vars.fold
+ (fun lab (_,vr,_) err ->
+ if vr = Virtual && not (Vars.mem lab sign2.csig_vars) then
+ CM_Hide_virtual ("instance variable", lab) :: err
+ else err)
+ sign1.csig_vars error
+ in
+ let error =
+ List.fold_right
+ (fun e l ->
+ if List.mem e missing_method then l else CM_Virtual_method e::l)
+ (Concr.elements (Concr.diff sign2.csig_concr sign1.csig_concr))
+ error
+ in
+ match error with
+ [] ->
+ begin try
+ moregen_clty trace type_pairs env patt subj;
+ []
+ with
+ Failure r -> r
+ end
+ | error ->
+ CM_Class_type_mismatch (env, patt, subj)::error
+ in
+ current_level := old_level;
+ res
+
+let rec equal_clty trace type_pairs subst env cty1 cty2 =
+ try
+ match cty1, cty2 with
+ Cty_constr (_, _, cty1), Cty_constr (_, _, cty2) ->
+ equal_clty true type_pairs subst env cty1 cty2
+ | Cty_constr (_, _, cty1), _ ->
+ equal_clty true type_pairs subst env cty1 cty2
+ | _, Cty_constr (_, _, cty2) ->
+ equal_clty true type_pairs subst env cty1 cty2
+ | Cty_arrow (l1, ty1, cty1'), Cty_arrow (l2, ty2, cty2') when l1 = l2 ->
+ begin try eqtype true type_pairs subst env ty1 ty2 with Unify trace ->
+ raise (Failure [CM_Parameter_mismatch (env, expand_trace env trace)])
+ end;
+ equal_clty false type_pairs subst env cty1' cty2'
+ | Cty_signature sign1, Cty_signature sign2 ->
+ let ty1 = object_fields (repr sign1.csig_self) in
+ let ty2 = object_fields (repr sign2.csig_self) in
+ let (fields1, rest1) = flatten_fields ty1
+ and (fields2, rest2) = flatten_fields ty2 in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ List.iter
+ (fun (lab, k1, t1, k2, t2) ->
+ begin try eqtype true type_pairs subst env t1 t2 with
+ Unify trace ->
+ raise (Failure [CM_Meth_type_mismatch
+ (lab, env, expand_trace env trace)])
+ end)
+ pairs;
+ Vars.iter
+ (fun lab (_, _, ty) ->
+ let (_, _, ty') = Vars.find lab sign1.csig_vars in
+ try eqtype true type_pairs subst env ty' ty with Unify trace ->
+ raise (Failure [CM_Val_type_mismatch
+ (lab, env, expand_trace env trace)]))
+ sign2.csig_vars
+ | _ ->
+ raise
+ (Failure (if trace then []
+ else [CM_Class_type_mismatch (env, cty1, cty2)]))
+ with
+ Failure error when trace ->
+ raise (Failure (CM_Class_type_mismatch (env, cty1, cty2)::error))
+
+let match_class_declarations env patt_params patt_type subj_params subj_type =
+ let type_pairs = TypePairs.create 53 in
+ let subst = ref [] in
+ let sign1 = signature_of_class_type patt_type in
+ let sign2 = signature_of_class_type subj_type in
+ let t1 = repr sign1.csig_self in
+ let t2 = repr sign2.csig_self in
+ TypePairs.add type_pairs (t1, t2) ();
+ let (fields1, rest1) = flatten_fields (object_fields t1)
+ and (fields2, rest2) = flatten_fields (object_fields t2) in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ let error =
+ List.fold_right
+ (fun (lab, k, _) err ->
+ let err =
+ let k = field_kind_repr k in
+ begin match k with
+ Fvar r -> err
+ | _ -> CM_Hide_public lab::err
+ end
+ in
+ if Concr.mem lab sign1.csig_concr then err
+ else CM_Hide_virtual ("method", lab) :: err)
+ miss1 []
+ in
+ let missing_method = List.map (fun (m, _, _) -> m) miss2 in
+ let error =
+ (List.map (fun m -> CM_Missing_method m) missing_method) @ error
+ in
+ (* Always succeeds *)
+ eqtype true type_pairs subst env rest1 rest2;
+ let error =
+ List.fold_right
+ (fun (lab, k1, t1, k2, t2) err ->
+ let k1 = field_kind_repr k1 in
+ let k2 = field_kind_repr k2 in
+ match k1, k2 with
+ (Fvar _, Fvar _)
+ | (Fpresent, Fpresent) -> err
+ | (Fvar _, Fpresent) -> CM_Private_method lab::err
+ | (Fpresent, Fvar _) -> CM_Public_method lab::err
+ | _ -> assert false)
+ pairs error
+ in
+ let error =
+ Vars.fold
+ (fun lab (mut, vr, ty) err ->
+ try
+ let (mut', vr', ty') = Vars.find lab sign1.csig_vars in
+ if mut = Mutable && mut' <> Mutable then
+ CM_Non_mutable_value lab::err
+ else if vr = Concrete && vr' <> Concrete then
+ CM_Non_concrete_value lab::err
+ else
+ err
+ with Not_found ->
+ CM_Missing_value lab::err)
+ sign2.csig_vars error
+ in
+ let error =
+ Vars.fold
+ (fun lab (_,vr,_) err ->
+ if vr = Virtual && not (Vars.mem lab sign2.csig_vars) then
+ CM_Hide_virtual ("instance variable", lab) :: err
+ else err)
+ sign1.csig_vars error
+ in
+ let error =
+ List.fold_right
+ (fun e l ->
+ if List.mem e missing_method then l else CM_Virtual_method e::l)
+ (Concr.elements (Concr.diff sign2.csig_concr sign1.csig_concr))
+ error
+ in
+ match error with
+ [] ->
+ begin try
+ let lp = List.length patt_params in
+ let ls = List.length subj_params in
+ if lp <> ls then
+ raise (Failure [CM_Parameter_arity_mismatch (lp, ls)]);
+ List.iter2 (fun p s ->
+ try eqtype true type_pairs subst env p s with Unify trace ->
+ raise (Failure [CM_Type_parameter_mismatch
+ (env, expand_trace env trace)]))
+ patt_params subj_params;
+ (* old code: equal_clty false type_pairs subst env patt_type subj_type; *)
+ equal_clty false type_pairs subst env
+ (Cty_signature sign1) (Cty_signature sign2);
+ (* Use moregeneral for class parameters, need to recheck everything to
+ keeps relationships (PR#4824) *)
+ let clty_params =
+ List.fold_right (fun ty cty -> Cty_arrow (Labelled "*",ty,cty)) in
+ match_class_types ~trace:false env
+ (clty_params patt_params patt_type)
+ (clty_params subj_params subj_type)
+ with
+ Failure r -> r
+ end
+ | error ->
+ error
+
+
+ (***************)
+ (* Subtyping *)
+ (***************)
+
+
+(**** Build a subtype of a given type. ****)
+
+(* build_subtype:
+ [visited] traces traversed object and variant types
+ [loops] is a mapping from variables to variables, to reproduce
+ positive loops in a class type
+ [posi] true if the current variance is positive
+ [level] number of expansions/enlargement allowed on this branch *)
+
+let warn = ref false (* whether double coercion might do better *)
+let pred_expand n = if n mod 2 = 0 && n > 0 then pred n else n
+let pred_enlarge n = if n mod 2 = 1 then pred n else n
+
+type change = Unchanged | Equiv | Changed
+let collect l = List.fold_left (fun c1 (_, c2) -> max c1 c2) Unchanged l
+
+let rec filter_visited = function
+ [] -> []
+ | {desc=Tobject _|Tvariant _} :: _ as l -> l
+ | _ :: l -> filter_visited l
+
+let memq_warn t visited =
+ if List.memq t visited then (warn := true; true) else false
+
+let rec lid_of_path ?(sharp="") = function
+ Path.Pident id ->
+ Longident.Lident (sharp ^ Ident.name id)
+ | Path.Pdot (p1, s, _) ->
+ Longident.Ldot (lid_of_path p1, sharp ^ s)
+ | Path.Papply (p1, p2) ->
+ Longident.Lapply (lid_of_path ~sharp p1, lid_of_path p2)
+
+let find_cltype_for_path env p =
+ let path, cl_abbr = Env.lookup_type (lid_of_path ~sharp:"#" p) env in
+ match cl_abbr.type_manifest with
+ Some ty ->
+ begin match (repr ty).desc with
+ Tobject(_,{contents=Some(p',_)}) when Path.same p p' -> cl_abbr, ty
+ | _ -> raise Not_found
+ end
+ | None -> assert false
+
+let has_constr_row' env t =
+ has_constr_row (expand_abbrev env t)
+
+let rec build_subtype env visited loops posi level t =
+ let t = repr t in
+ match t.desc with
+ Tvar _ ->
+ if posi then
+ try
+ let t' = List.assq t loops in
+ warn := true;
+ (t', Equiv)
+ with Not_found ->
+ (t, Unchanged)
+ else
+ (t, Unchanged)
+ | Tarrow(l, t1, t2, _) ->
+ if memq_warn t visited then (t, Unchanged) else
+ let visited = t :: visited in
+ let (t1', c1) = build_subtype env visited loops (not posi) level t1 in
+ let (t2', c2) = build_subtype env visited loops posi level t2 in
+ let c = max c1 c2 in
+ if c > Unchanged then (newty (Tarrow(l, t1', t2', Cok)), c)
+ else (t, Unchanged)
+ | Ttuple tlist ->
+ if memq_warn t visited then (t, Unchanged) else
+ let visited = t :: visited in
+ let tlist' =
+ List.map (build_subtype env visited loops posi level) tlist
+ in
+ let c = collect tlist' in
+ if c > Unchanged then (newty (Ttuple (List.map fst tlist')), c)
+ else (t, Unchanged)
+ | Tconstr(p, tl, abbrev)
+ when level > 0 && generic_abbrev env p && safe_abbrev env t
+ && not (has_constr_row' env t) ->
+ let t' = repr (expand_abbrev env t) in
+ let level' = pred_expand level in
+ begin try match t'.desc with
+ Tobject _ when posi && not (opened_object t') ->
+ let cl_abbr, body = find_cltype_for_path env p in
+ let ty =
+ subst env !current_level Public abbrev None
+ cl_abbr.type_params tl body in
+ let ty = repr ty in
+ let ty1, tl1 =
+ match ty.desc with
+ Tobject(ty1,{contents=Some(p',tl1)}) when Path.same p p' ->
+ ty1, tl1
+ | _ -> raise Not_found
+ in
+ (* Fix PR4505: do not set ty to Tvar when it appears in tl1,
+ as this occurence might break the occur check.
+ XXX not clear whether this correct anyway... *)
+ if List.exists (deep_occur ty) tl1 then raise Not_found;
+ ty.desc <- Tvar None;
+ let t'' = newvar () in
+ let loops = (ty, t'') :: loops in
+ (* May discard [visited] as level is going down *)
+ let (ty1', c) =
+ build_subtype env [t'] loops posi (pred_enlarge level') ty1 in
+ assert (is_Tvar t'');
+ let nm =
+ if c > Equiv || deep_occur ty ty1' then None else Some(p,tl1) in
+ t''.desc <- Tobject (ty1', ref nm);
+ (try unify_var env ty t with Unify _ -> assert false);
+ (t'', Changed)
+ | _ -> raise Not_found
+ with Not_found ->
+ let (t'',c) = build_subtype env visited loops posi level' t' in
+ if c > Unchanged then (t'',c)
+ else (t, Unchanged)
+ end
+ | Tconstr(p, tl, abbrev) ->
+ (* Must check recursion on constructors, since we do not always
+ expand them *)
+ if memq_warn t visited then (t, Unchanged) else
+ let visited = t :: visited in
+ begin try
+ let decl = Env.find_type p env in
+ if level = 0 && generic_abbrev env p && safe_abbrev env t
+ && not (has_constr_row' env t)
+ then warn := true;
+ let tl' =
+ List.map2
+ (fun v t ->
+ let (co,cn) = Variance.get_upper v in
+ if cn then
+ if co then (t, Unchanged)
+ else build_subtype env visited loops (not posi) level t
+ else
+ if co then build_subtype env visited loops posi level t
+ else (newvar(), Changed))
+ decl.type_variance tl
+ in
+ let c = collect tl' in
+ if c > Unchanged then (newconstr p (List.map fst tl'), c)
+ else (t, Unchanged)
+ with Not_found ->
+ (t, Unchanged)
+ end
+ | Tvariant row ->
+ let row = row_repr row in
+ if memq_warn t visited || not (static_row row) then (t, Unchanged) else
+ let level' = pred_enlarge level in
+ let visited =
+ t :: if level' < level then [] else filter_visited visited in
+ let fields = filter_row_fields false row.row_fields in
+ let fields =
+ List.map
+ (fun (l,f as orig) -> match row_field_repr f with
+ Rpresent None ->
+ if posi then
+ (l, Reither(true, [], false, ref None)), Unchanged
+ else
+ orig, Unchanged
+ | Rpresent(Some t) ->
+ let (t', c) = build_subtype env visited loops posi level' t in
+ let f =
+ if posi && level > 0
+ then Reither(false, [t'], false, ref None)
+ else Rpresent(Some t')
+ in (l, f), c
+ | _ -> assert false)
+ fields
+ in
+ let c = collect fields in
+ let row =
+ { row_fields = List.map fst fields; row_more = newvar();
+ row_bound = (); row_closed = posi; row_fixed = false;
+ row_name = if c > Unchanged then None else row.row_name }
+ in
+ (newty (Tvariant row), Changed)
+ | Tobject (t1, _) ->
+ if memq_warn t visited || opened_object t1 then (t, Unchanged) else
+ let level' = pred_enlarge level in
+ let visited =
+ t :: if level' < level then [] else filter_visited visited in
+ let (t1', c) = build_subtype env visited loops posi level' t1 in
+ if c > Unchanged then (newty (Tobject (t1', ref None)), c)
+ else (t, Unchanged)
+ | Tfield(s, _, t1, t2) (* Always present *) ->
+ let (t1', c1) = build_subtype env visited loops posi level t1 in
+ let (t2', c2) = build_subtype env visited loops posi level t2 in
+ let c = max c1 c2 in
+ if c > Unchanged then (newty (Tfield(s, Fpresent, t1', t2')), c)
+ else (t, Unchanged)
+ | Tnil ->
+ if posi then
+ let v = newvar () in
+ (v, Changed)
+ else begin
+ warn := true;
+ (t, Unchanged)
+ end
+ | Tsubst _ | Tlink _ ->
+ assert false
+ | Tpoly(t1, tl) ->
+ let (t1', c) = build_subtype env visited loops posi level t1 in
+ if c > Unchanged then (newty (Tpoly(t1', tl)), c)
+ else (t, Unchanged)
+ | Tunivar _ | Tpackage _ ->
+ (t, Unchanged)
+
+let enlarge_type env ty =
+ warn := false;
+ (* [level = 4] allows 2 expansions involving objects/variants *)
+ let (ty', _) = build_subtype env [] [] true 4 ty in
+ (ty', !warn)
+
+(**** Check whether a type is a subtype of another type. ****)
+
+(*
+ During the traversal, a trace of visited types is maintained. It
+ is printed in case of error.
+ Constraints (pairs of types that must be equals) are accumulated
+ rather than being enforced straight. Indeed, the result would
+ otherwise depend on the order in which these constraints are
+ enforced.
+ A function enforcing these constraints is returned. That way, type
+ variables can be bound to their actual values before this function
+ is called (see Typecore).
+ Only well-defined abbreviations are expanded (hence the tests
+ [generic_abbrev ...]).
+*)
+
+let subtypes = TypePairs.create 17
+
+let subtype_error env trace =
+ raise (Subtype (expand_trace env (List.rev trace), []))
+
+(* check list inclusion, assuming lists are ordered *)
+let rec included nl1 nl2 =
+ match nl1, nl2 with
+ (a::nl1', b::nl2') ->
+ if a = b then included nl1' nl2' else
+ a > b && included nl1 nl2'
+ | ([], _) -> true
+ | (_, []) -> false
+
+let rec extract_assoc nl1 nl2 tl2 =
+ match (nl1, nl2, tl2) with
+ (a::nl1', b::nl2, t::tl2) ->
+ if a = b then t :: extract_assoc nl1' nl2 tl2
+ else extract_assoc nl1 nl2 tl2
+ | ([], _, _) -> []
+ | _ -> assert false
+
+let rec subtype_rec env trace t1 t2 cstrs =
+ let t1 = repr t1 in
+ let t2 = repr t2 in
+ if t1 == t2 then cstrs else
+
+ begin try
+ TypePairs.find subtypes (t1, t2);
+ cstrs
+ with Not_found ->
+ TypePairs.add subtypes (t1, t2) ();
+ match (t1.desc, t2.desc) with
+ (Tvar _, _) | (_, Tvar _) ->
+ (trace, t1, t2, !univar_pairs)::cstrs
+ | (Tarrow(l1, t1, u1, _), Tarrow(l2, t2, u2, _)) when l1 = l2
+ || !Clflags.classic && not (is_optional l1 || is_optional l2) ->
+ let cstrs = subtype_rec env ((t2, t1)::trace) t2 t1 cstrs in
+ subtype_rec env ((u1, u2)::trace) u1 u2 cstrs
+ | (Ttuple tl1, Ttuple tl2) ->
+ subtype_list env trace tl1 tl2 cstrs
+ | (Tconstr(p1, [], _), Tconstr(p2, [], _)) when Path.same p1 p2 ->
+ cstrs
+ | (Tconstr(p1, tl1, abbrev1), _)
+ when generic_abbrev env p1 && safe_abbrev env t1 ->
+ subtype_rec env trace (expand_abbrev env t1) t2 cstrs
+ | (_, Tconstr(p2, tl2, abbrev2))
+ when generic_abbrev env p2 && safe_abbrev env t2 ->
+ subtype_rec env trace t1 (expand_abbrev env t2) cstrs
+ | (Tconstr(p1, tl1, _), Tconstr(p2, tl2, _)) when Path.same p1 p2 ->
+ begin try
+ let decl = Env.find_type p1 env in
+ List.fold_left2
+ (fun cstrs v (t1, t2) ->
+ let (co, cn) = Variance.get_upper v in
+ if co then
+ if cn then
+ (trace, newty2 t1.level (Ttuple[t1]),
+ newty2 t2.level (Ttuple[t2]), !univar_pairs) :: cstrs
+ else subtype_rec env ((t1, t2)::trace) t1 t2 cstrs
+ else
+ if cn then subtype_rec env ((t2, t1)::trace) t2 t1 cstrs
+ else cstrs)
+ cstrs decl.type_variance (List.combine tl1 tl2)
+ with Not_found ->
+ (trace, t1, t2, !univar_pairs)::cstrs
+ end
+ | (Tconstr(p1, _, _), _) when generic_private_abbrev env p1 ->
+ subtype_rec env trace (expand_abbrev_opt env t1) t2 cstrs
+(* | (_, Tconstr(p2, _, _)) when generic_private_abbrev false env p2 ->
+ subtype_rec env trace t1 (expand_abbrev_opt env t2) cstrs *)
+ | (Tobject (f1, _), Tobject (f2, _))
+ when is_Tvar (object_row f1) && is_Tvar (object_row f2) ->
+ (* Same row variable implies same object. *)
+ (trace, t1, t2, !univar_pairs)::cstrs
+ | (Tobject (f1, _), Tobject (f2, _)) ->
+ subtype_fields env trace f1 f2 cstrs
+ | (Tvariant row1, Tvariant row2) ->
+ begin try
+ subtype_row env trace row1 row2 cstrs
+ with Exit ->
+ (trace, t1, t2, !univar_pairs)::cstrs
+ end
+ | (Tpoly (u1, []), Tpoly (u2, [])) ->
+ subtype_rec env trace u1 u2 cstrs
+ | (Tpoly (u1, tl1), Tpoly (u2, [])) ->
+ let _, u1' = instance_poly false tl1 u1 in
+ subtype_rec env trace u1' u2 cstrs
+ | (Tpoly (u1, tl1), Tpoly (u2,tl2)) ->
+ begin try
+ enter_poly env univar_pairs u1 tl1 u2 tl2
+ (fun t1 t2 -> subtype_rec env trace t1 t2 cstrs)
+ with Unify _ ->
+ (trace, t1, t2, !univar_pairs)::cstrs
+ end
+(* | (Tpackage (p1, nl1, tl1), Tpackage (p2, nl2, tl2))
+ when eq_package_path env p1 p2 && included nl2 nl1 ->
+ List.map2 (fun t1 t2 -> (trace, t1, t2, !univar_pairs))
+ (extract_assoc nl2 nl1 tl1) tl2
+ @ cstrs *)
+ | (Tpackage (p1, nl1, tl1), Tpackage (p2, nl2, tl2)) ->
+ begin try
+ let ntl1 = complete_type_list env nl2 t1.level (Mty_ident p1) nl1 tl1
+ and ntl2 = complete_type_list env nl1 t2.level (Mty_ident p2) nl2 tl2
+ ~allow_absent:true in
+ let cstrs' =
+ List.map
+ (fun (n2,t2) -> (trace, List.assoc n2 ntl1, t2, !univar_pairs))
+ ntl2
+ in
+ if eq_package_path env p1 p2 then cstrs' @ cstrs
+ else begin
+ (* need to check module subtyping *)
+ let snap = Btype.snapshot () in
+ try
+ List.iter (fun (_, t1, t2, _) -> unify env t1 t2) cstrs';
+ if !package_subtype env p1 nl1 tl1 p2 nl2 tl2
+ then (Btype.backtrack snap; cstrs' @ cstrs)
+ else raise (Unify [])
+ with Unify _ ->
+ Btype.backtrack snap; raise Not_found
+ end
+ with Not_found ->
+ (trace, t1, t2, !univar_pairs)::cstrs
+ end
+ | (_, _) ->
+ (trace, t1, t2, !univar_pairs)::cstrs
+ end
+
+and subtype_list env trace tl1 tl2 cstrs =
+ if List.length tl1 <> List.length tl2 then
+ subtype_error env trace;
+ List.fold_left2
+ (fun cstrs t1 t2 -> subtype_rec env ((t1, t2)::trace) t1 t2 cstrs)
+ cstrs tl1 tl2
+
+and subtype_fields env trace ty1 ty2 cstrs =
+ (* Assume that either rest1 or rest2 is not Tvar *)
+ let (fields1, rest1) = flatten_fields ty1 in
+ let (fields2, rest2) = flatten_fields ty2 in
+ let (pairs, miss1, miss2) = associate_fields fields1 fields2 in
+ let cstrs =
+ if rest2.desc = Tnil then cstrs else
+ if miss1 = [] then
+ subtype_rec env ((rest1, rest2)::trace) rest1 rest2 cstrs
+ else
+ (trace, build_fields (repr ty1).level miss1 rest1, rest2,
+ !univar_pairs) :: cstrs
+ in
+ let cstrs =
+ if miss2 = [] then cstrs else
+ (trace, rest1, build_fields (repr ty2).level miss2 (newvar ()),
+ !univar_pairs) :: cstrs
+ in
+ List.fold_left
+ (fun cstrs (_, k1, t1, k2, t2) ->
+ (* Theses fields are always present *)
+ subtype_rec env ((t1, t2)::trace) t1 t2 cstrs)
+ cstrs pairs
+
+and subtype_row env trace row1 row2 cstrs =
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ let r1, r2, pairs =
+ merge_row_fields row1.row_fields row2.row_fields in
+ let more1 = repr row1.row_more
+ and more2 = repr row2.row_more in
+ match more1.desc, more2.desc with
+ Tconstr(p1,_,_), Tconstr(p2,_,_) when Path.same p1 p2 ->
+ subtype_rec env ((more1,more2)::trace) more1 more2 cstrs
+ | (Tvar _|Tconstr _|Tnil), (Tvar _|Tconstr _|Tnil)
+ when row1.row_closed && r1 = [] ->
+ List.fold_left
+ (fun cstrs (_,f1,f2) ->
+ match row_field_repr f1, row_field_repr f2 with
+ (Rpresent None|Reither(true,_,_,_)), Rpresent None ->
+ cstrs
+ | Rpresent(Some t1), Rpresent(Some t2) ->
+ subtype_rec env ((t1, t2)::trace) t1 t2 cstrs
+ | Reither(false, t1::_, _, _), Rpresent(Some t2) ->
+ subtype_rec env ((t1, t2)::trace) t1 t2 cstrs
+ | Rabsent, _ -> cstrs
+ | _ -> raise Exit)
+ cstrs pairs
+ | Tunivar _, Tunivar _
+ when row1.row_closed = row2.row_closed && r1 = [] && r2 = [] ->
+ let cstrs =
+ subtype_rec env ((more1,more2)::trace) more1 more2 cstrs in
+ List.fold_left
+ (fun cstrs (_,f1,f2) ->
+ match row_field_repr f1, row_field_repr f2 with
+ Rpresent None, Rpresent None
+ | Reither(true,[],_,_), Reither(true,[],_,_)
+ | Rabsent, Rabsent ->
+ cstrs
+ | Rpresent(Some t1), Rpresent(Some t2)
+ | Reither(false,[t1],_,_), Reither(false,[t2],_,_) ->
+ subtype_rec env ((t1, t2)::trace) t1 t2 cstrs
+ | _ -> raise Exit)
+ cstrs pairs
+ | _ ->
+ raise Exit
+
+let subtype env ty1 ty2 =
+ TypePairs.clear subtypes;
+ univar_pairs := [];
+ (* Build constraint set. *)
+ let cstrs = subtype_rec env [(ty1, ty2)] ty1 ty2 [] in
+ TypePairs.clear subtypes;
+ (* Enforce constraints. *)
+ function () ->
+ List.iter
+ (function (trace0, t1, t2, pairs) ->
+ try unify_pairs (ref env) t1 t2 pairs with Unify trace ->
+ raise (Subtype (expand_trace env (List.rev trace0),
+ List.tl (List.tl trace))))
+ (List.rev cstrs)
+
+ (*******************)
+ (* Miscellaneous *)
+ (*******************)
+
+(* Utility for printing. The resulting type is not used in computation. *)
+let rec unalias_object ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tfield (s, k, t1, t2) ->
+ newty2 ty.level (Tfield (s, k, t1, unalias_object t2))
+ | Tvar _ | Tnil ->
+ newty2 ty.level ty.desc
+ | Tunivar _ ->
+ ty
+ | Tconstr _ ->
+ newvar2 ty.level
+ | _ ->
+ assert false
+
+let unalias ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tvar _ | Tunivar _ ->
+ ty
+ | Tvariant row ->
+ let row = row_repr row in
+ let more = row.row_more in
+ newty2 ty.level
+ (Tvariant {row with row_more = newty2 more.level more.desc})
+ | Tobject (ty, nm) ->
+ newty2 ty.level (Tobject (unalias_object ty, nm))
+ | _ ->
+ newty2 ty.level ty.desc
+
+(* Return the arity (as for curried functions) of the given type. *)
+let rec arity ty =
+ match (repr ty).desc with
+ Tarrow(_, t1, t2, _) -> 1 + arity t2
+ | _ -> 0
+
+(* Check whether an abbreviation expands to itself. *)
+let cyclic_abbrev env id ty =
+ let rec check_cycle seen ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tconstr (p, tl, abbrev) ->
+ p = Path.Pident id || List.memq ty seen ||
+ begin try
+ check_cycle (ty :: seen) (expand_abbrev_opt env ty)
+ with
+ Cannot_expand -> false
+ | Unify _ -> true
+ end
+ | _ ->
+ false
+ in check_cycle [] ty
+
+(* Check for non-generalizable type variables *)
+exception Non_closed0
+let visited = ref TypeSet.empty
+
+let rec closed_schema_rec env ty =
+ let ty = expand_head env ty in
+ if TypeSet.mem ty !visited then () else begin
+ visited := TypeSet.add ty !visited;
+ match ty.desc with
+ Tvar _ when ty.level <> generic_level ->
+ raise Non_closed0
+ | Tfield(_, kind, t1, t2) ->
+ if field_kind_repr kind = Fpresent then
+ closed_schema_rec env t1;
+ closed_schema_rec env t2
+ | Tvariant row ->
+ let row = row_repr row in
+ iter_row (closed_schema_rec env) row;
+ if not (static_row row) then closed_schema_rec env row.row_more
+ | _ ->
+ iter_type_expr (closed_schema_rec env) ty
+ end
+
+(* Return whether all variables of type [ty] are generic. *)
+let closed_schema env ty =
+ visited := TypeSet.empty;
+ try
+ closed_schema_rec env ty;
+ visited := TypeSet.empty;
+ true
+ with Non_closed0 ->
+ visited := TypeSet.empty;
+ false
+
+(* Normalize a type before printing, saving... *)
+(* Cannot use mark_type because deep_occur uses it too *)
+let rec normalize_type_rec env visited ty =
+ let ty = repr ty in
+ if not (TypeSet.mem ty !visited) then begin
+ visited := TypeSet.add ty !visited;
+ begin match ty.desc with
+ | Tvariant row ->
+ let row = row_repr row in
+ let fields = List.map
+ (fun (l,f0) ->
+ let f = row_field_repr f0 in l,
+ match f with Reither(b, ty::(_::_ as tyl), m, e) ->
+ let tyl' =
+ List.fold_left
+ (fun tyl ty ->
+ if List.exists (fun ty' -> equal env false [ty] [ty']) tyl
+ then tyl else ty::tyl)
+ [ty] tyl
+ in
+ if f != f0 || List.length tyl' < List.length tyl then
+ Reither(b, List.rev tyl', m, e)
+ else f
+ | _ -> f)
+ row.row_fields in
+ let fields =
+ List.sort (fun (p,_) (q,_) -> compare p q)
+ (List.filter (fun (_,fi) -> fi <> Rabsent) fields) in
+ log_type ty;
+ ty.desc <- Tvariant {row with row_fields = fields}
+ | Tobject (fi, nm) ->
+ begin match !nm with
+ | None -> ()
+ | Some (n, v :: l) ->
+ if deep_occur ty (newgenty (Ttuple l)) then
+ (* The abbreviation may be hiding something, so remove it *)
+ set_name nm None
+ else let v' = repr v in
+ begin match v'.desc with
+ | Tvar _ | Tunivar _ ->
+ if v' != v then set_name nm (Some (n, v' :: l))
+ | Tnil ->
+ log_type ty; ty.desc <- Tconstr (n, l, ref Mnil)
+ | _ -> set_name nm None
+ end
+ | _ ->
+ fatal_error "Ctype.normalize_type_rec"
+ end;
+ let fi = repr fi in
+ if fi.level < lowest_level then () else
+ let fields, row = flatten_fields fi in
+ let fi' = build_fields fi.level fields row in
+ log_type ty; fi.desc <- fi'.desc
+ | _ -> ()
+ end;
+ iter_type_expr (normalize_type_rec env visited) ty
+ end
+
+let normalize_type env ty =
+ normalize_type_rec env (ref TypeSet.empty) ty
+
+
+ (*************************)
+ (* Remove dependencies *)
+ (*************************)
+
+
+(*
+ Variables are left unchanged. Other type nodes are duplicated, with
+ levels set to generic level.
+ We cannot use Tsubst here, because unification may be called by
+ expand_abbrev.
+*)
+
+let nondep_hash = TypeHash.create 47
+let nondep_variants = TypeHash.create 17
+let clear_hash () =
+ TypeHash.clear nondep_hash; TypeHash.clear nondep_variants
+
+let rec nondep_type_rec env id ty =
+ match ty.desc with
+ Tvar _ | Tunivar _ -> ty
+ | Tlink ty -> nondep_type_rec env id ty
+ | _ -> try TypeHash.find nondep_hash ty
+ with Not_found ->
+ let ty' = newgenvar () in (* Stub *)
+ TypeHash.add nondep_hash ty ty';
+ ty'.desc <-
+ begin match ty.desc with
+ | Tconstr(p, tl, abbrev) ->
+ if Path.isfree id p then
+ begin try
+ Tlink (nondep_type_rec env id
+ (expand_abbrev env (newty2 ty.level ty.desc)))
+ (*
+ The [Tlink] is important. The expanded type may be a
+ variable, or may not be completely copied yet
+ (recursive type), so one cannot just take its
+ description.
+ *)
+ with Cannot_expand | Unify _ ->
+ raise Not_found
+ end
+ else
+ Tconstr(p, List.map (nondep_type_rec env id) tl, ref Mnil)
+ | Tpackage(p, nl, tl) when Path.isfree id p ->
+ let p' = normalize_package_path env p in
+ if Path.isfree id p' then raise Not_found;
+ Tpackage (p', nl, List.map (nondep_type_rec env id) tl)
+ | Tobject (t1, name) ->
+ Tobject (nondep_type_rec env id t1,
+ ref (match !name with
+ None -> None
+ | Some (p, tl) ->
+ if Path.isfree id p then None
+ else Some (p, List.map (nondep_type_rec env id) tl)))
+ | Tvariant row ->
+ let row = row_repr row in
+ let more = repr row.row_more in
+ (* We must keep sharing according to the row variable *)
+ begin try
+ let ty2 = TypeHash.find nondep_variants more in
+ (* This variant type has been already copied *)
+ TypeHash.add nondep_hash ty ty2;
+ Tlink ty2
+ with Not_found ->
+ (* Register new type first for recursion *)
+ TypeHash.add nondep_variants more ty';
+ let static = static_row row in
+ let more' = if static then newgenty Tnil else more in
+ (* Return a new copy *)
+ let row =
+ copy_row (nondep_type_rec env id) true row true more' in
+ match row.row_name with
+ Some (p, tl) when Path.isfree id p ->
+ Tvariant {row with row_name = None}
+ | _ -> Tvariant row
+ end
+ | _ -> copy_type_desc (nondep_type_rec env id) ty.desc
+ end;
+ ty'
+
+let nondep_type env id ty =
+ try
+ let ty' = nondep_type_rec env id ty in
+ clear_hash ();
+ ty'
+ with Not_found ->
+ clear_hash ();
+ raise Not_found
+
+let () = nondep_type' := nondep_type
+
+let unroll_abbrev id tl ty =
+ let ty = repr ty and path = Path.Pident id in
+ if is_Tvar ty || (List.exists (deep_occur ty) tl)
+ || is_object_type path then
+ ty
+ else
+ let ty' = newty2 ty.level ty.desc in
+ link_type ty (newty2 ty.level (Tconstr (path, tl, ref Mnil)));
+ ty'
+
+(* Preserve sharing inside type declarations. *)
+let nondep_type_decl env mid id is_covariant decl =
+ try
+ let params = List.map (nondep_type_rec env mid) decl.type_params in
+ let tk =
+ try map_kind (nondep_type_rec env mid) decl.type_kind
+ with Not_found when is_covariant -> Type_abstract
+ and tm =
+ try match decl.type_manifest with
+ None -> None
+ | Some ty ->
+ Some (unroll_abbrev id params (nondep_type_rec env mid ty))
+ with Not_found when is_covariant ->
+ None
+ in
+ clear_hash ();
+ let priv =
+ match tm with
+ | Some ty when Btype.has_constr_row ty -> Private
+ | _ -> decl.type_private
+ in
+ { type_params = params;
+ type_arity = decl.type_arity;
+ type_kind = tk;
+ type_manifest = tm;
+ type_private = priv;
+ type_variance = decl.type_variance;
+ type_newtype_level = None;
+ type_loc = decl.type_loc;
+ type_attributes = decl.type_attributes;
+ }
+ with Not_found ->
+ clear_hash ();
+ raise Not_found
+
+(* Preserve sharing inside extension constructors. *)
+let nondep_extension_constructor env mid ext =
+ try
+ let type_path, type_params =
+ if Path.isfree mid ext.ext_type_path then
+ begin
+ let ty =
+ newgenty (Tconstr(ext.ext_type_path, ext.ext_type_params, ref Mnil))
+ in
+ let ty' = nondep_type_rec env mid ty in
+ match (repr ty').desc with
+ Tconstr(p, tl, _) -> p, tl
+ | _ -> raise Not_found
+ end
+ else
+ let type_params =
+ List.map (nondep_type_rec env mid) ext.ext_type_params
+ in
+ ext.ext_type_path, type_params
+ in
+ let args = map_type_expr_cstr_args (nondep_type_rec env mid) ext.ext_args in
+ let ret_type = may_map (nondep_type_rec env mid) ext.ext_ret_type in
+ clear_hash ();
+ { ext_type_path = type_path;
+ ext_type_params = type_params;
+ ext_args = args;
+ ext_ret_type = ret_type;
+ ext_private = ext.ext_private;
+ ext_attributes = ext.ext_attributes;
+ ext_loc = ext.ext_loc;
+ }
+ with Not_found ->
+ clear_hash ();
+ raise Not_found
+
+
+(* Preserve sharing inside class types. *)
+let nondep_class_signature env id sign =
+ { csig_self = nondep_type_rec env id sign.csig_self;
+ csig_vars =
+ Vars.map (function (m, v, t) -> (m, v, nondep_type_rec env id t))
+ sign.csig_vars;
+ csig_concr = sign.csig_concr;
+ csig_inher =
+ List.map (fun (p,tl) -> (p, List.map (nondep_type_rec env id) tl))
+ sign.csig_inher }
+
+let rec nondep_class_type env id =
+ function
+ Cty_constr (p, _, cty) when Path.isfree id p ->
+ nondep_class_type env id cty
+ | Cty_constr (p, tyl, cty) ->
+ Cty_constr (p, List.map (nondep_type_rec env id) tyl,
+ nondep_class_type env id cty)
+ | Cty_signature sign ->
+ Cty_signature (nondep_class_signature env id sign)
+ | Cty_arrow (l, ty, cty) ->
+ Cty_arrow (l, nondep_type_rec env id ty, nondep_class_type env id cty)
+
+let nondep_class_declaration env id decl =
+ assert (not (Path.isfree id decl.cty_path));
+ let decl =
+ { cty_params = List.map (nondep_type_rec env id) decl.cty_params;
+ cty_variance = decl.cty_variance;
+ cty_type = nondep_class_type env id decl.cty_type;
+ cty_path = decl.cty_path;
+ cty_new =
+ begin match decl.cty_new with
+ None -> None
+ | Some ty -> Some (nondep_type_rec env id ty)
+ end;
+ cty_loc = decl.cty_loc;
+ cty_attributes = decl.cty_attributes;
+ }
+ in
+ clear_hash ();
+ decl
+
+let nondep_cltype_declaration env id decl =
+ assert (not (Path.isfree id decl.clty_path));
+ let decl =
+ { clty_params = List.map (nondep_type_rec env id) decl.clty_params;
+ clty_variance = decl.clty_variance;
+ clty_type = nondep_class_type env id decl.clty_type;
+ clty_path = decl.clty_path;
+ clty_loc = decl.clty_loc;
+ clty_attributes = decl.clty_attributes;
+ }
+ in
+ clear_hash ();
+ decl
+
+(* collapse conjonctive types in class parameters *)
+let rec collapse_conj env visited ty =
+ let ty = repr ty in
+ if List.memq ty visited then () else
+ let visited = ty :: visited in
+ match ty.desc with
+ Tvariant row ->
+ let row = row_repr row in
+ List.iter
+ (fun (l,fi) ->
+ match row_field_repr fi with
+ Reither (c, t1::(_::_ as tl), m, e) ->
+ List.iter (unify env t1) tl;
+ set_row_field e (Reither (c, [t1], m, ref None))
+ | _ ->
+ ())
+ row.row_fields;
+ iter_row (collapse_conj env visited) row
+ | _ ->
+ iter_type_expr (collapse_conj env visited) ty
+
+let collapse_conj_params env params =
+ List.iter (collapse_conj env []) params
diff --git a/typing/ctype.mli b/typing/ctype.mli
new file mode 100644
index 0000000000..aad989ef79
--- /dev/null
+++ b/typing/ctype.mli
@@ -0,0 +1,281 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Operations on core types *)
+
+open Asttypes
+open Types
+
+exception Unify of (type_expr * type_expr) list
+exception Tags of label * label
+exception Subtype of
+ (type_expr * type_expr) list * (type_expr * type_expr) list
+exception Cannot_expand
+exception Cannot_apply
+exception Recursive_abbrev
+exception Unification_recursive_abbrev of (type_expr * type_expr) list
+
+val init_def: int -> unit
+ (* Set the initial variable level *)
+val begin_def: unit -> unit
+ (* Raise the variable level by one at the beginning of a definition. *)
+val end_def: unit -> unit
+ (* Lower the variable level by one at the end of a definition *)
+val begin_class_def: unit -> unit
+val raise_nongen_level: unit -> unit
+val reset_global_level: unit -> unit
+ (* Reset the global level before typing an expression *)
+val increase_global_level: unit -> int
+val restore_global_level: int -> unit
+ (* This pair of functions is only used in Typetexp *)
+
+val newty: type_desc -> type_expr
+val newvar: ?name:string -> unit -> type_expr
+val newvar2: ?name:string -> int -> type_expr
+ (* Return a fresh variable *)
+val new_global_var: ?name:string -> unit -> type_expr
+ (* Return a fresh variable, bound at toplevel
+ (as type variables ['a] in type constraints). *)
+val newobj: type_expr -> type_expr
+val newconstr: Path.t -> type_expr list -> type_expr
+val none: type_expr
+ (* A dummy type expression *)
+
+val repr: type_expr -> type_expr
+ (* Return the canonical representative of a type. *)
+
+val object_fields: type_expr -> type_expr
+val flatten_fields:
+ type_expr -> (string * field_kind * type_expr) list * type_expr
+ (* Transform a field type into a list of pairs label-type *)
+ (* The fields are sorted *)
+val associate_fields:
+ (string * field_kind * type_expr) list ->
+ (string * field_kind * type_expr) list ->
+ (string * field_kind * type_expr * field_kind * type_expr) list *
+ (string * field_kind * type_expr) list *
+ (string * field_kind * type_expr) list
+val opened_object: type_expr -> bool
+val close_object: type_expr -> unit
+val row_variable: type_expr -> type_expr
+ (* Return the row variable of an open object type *)
+val set_object_name:
+ Ident.t -> type_expr -> type_expr list -> type_expr -> unit
+val remove_object_name: type_expr -> unit
+val hide_private_methods: type_expr -> unit
+val find_cltype_for_path: Env.t -> Path.t -> type_declaration * type_expr
+val lid_of_path: ?sharp:string -> Path.t -> Longident.t
+
+val sort_row_fields: (label * row_field) list -> (label * row_field) list
+val merge_row_fields:
+ (label * row_field) list -> (label * row_field) list ->
+ (label * row_field) list * (label * row_field) list *
+ (label * row_field * row_field) list
+val filter_row_fields:
+ bool -> (label * row_field) list -> (label * row_field) list
+
+val generalize: type_expr -> unit
+ (* Generalize in-place the given type *)
+val iterative_generalization: int -> type_expr list -> type_expr list
+ (* Efficient repeated generalization of a type *)
+val generalize_expansive: Env.t -> type_expr -> unit
+ (* Generalize the covariant part of a type, making
+ contravariant branches non-generalizable *)
+val generalize_global: type_expr -> unit
+ (* Generalize the structure of a type, lowering variables
+ to !global_level *)
+val generalize_structure: type_expr -> unit
+ (* Same, but variables are only lowered to !current_level *)
+val generalize_spine: type_expr -> unit
+ (* Special function to generalize a method during inference *)
+val correct_levels: type_expr -> type_expr
+ (* Returns a copy with decreasing levels *)
+val limited_generalize: type_expr -> type_expr -> unit
+ (* Only generalize some part of the type
+ Make the remaining of the type non-generalizable *)
+
+val instance: ?partial:bool -> Env.t -> type_expr -> type_expr
+ (* Take an instance of a type scheme *)
+ (* partial=None -> normal
+ partial=false -> newvar() for non generic subterms
+ partial=true -> newty2 ty.level Tvar for non generic subterms *)
+val instance_def: type_expr -> type_expr
+ (* use defaults *)
+val generic_instance: ?partial:bool -> Env.t -> type_expr -> type_expr
+ (* Same as instance, but new nodes at generic_level *)
+val instance_list: Env.t -> type_expr list -> type_expr list
+ (* Take an instance of a list of type schemes *)
+val instance_constructor:
+ ?in_pattern:Env.t ref * int ->
+ constructor_description -> type_expr list * type_expr
+ (* Same, for a constructor *)
+val instance_parameterized_type:
+ ?keep_names:bool ->
+ type_expr list -> type_expr -> type_expr list * type_expr
+val instance_parameterized_type_2:
+ type_expr list -> type_expr list -> type_expr ->
+ type_expr list * type_expr list * type_expr
+val instance_declaration: type_declaration -> type_declaration
+val instance_class:
+ type_expr list -> class_type -> type_expr list * class_type
+val instance_poly:
+ ?keep_names:bool ->
+ bool -> type_expr list -> type_expr -> type_expr list * type_expr
+ (* Take an instance of a type scheme containing free univars *)
+val instance_label:
+ bool -> label_description -> type_expr list * type_expr * type_expr
+ (* Same, for a label *)
+val apply:
+ Env.t -> type_expr list -> type_expr -> type_expr list -> type_expr
+ (* [apply [p1...pN] t [a1...aN]] match the arguments [ai] to
+ the parameters [pi] and returns the corresponding instance of
+ [t]. Exception [Cannot_apply] is raised in case of failure. *)
+
+val expand_head_once: Env.t -> type_expr -> type_expr
+val expand_head: Env.t -> type_expr -> type_expr
+val try_expand_once_opt: Env.t -> type_expr -> type_expr
+val expand_head_opt: Env.t -> type_expr -> type_expr
+(** The compiler's own version of [expand_head] necessary for type-based
+ optimisations. *)
+
+val full_expand: Env.t -> type_expr -> type_expr
+val extract_concrete_typedecl:
+ Env.t -> type_expr -> Path.t * Path.t * type_declaration
+ (* Return the original path of the types, and the first concrete
+ type declaration found expanding it.
+ Raise [Not_found] if none appears or not a type constructor. *)
+
+val enforce_constraints: Env.t -> type_expr -> unit
+
+val unify: Env.t -> type_expr -> type_expr -> unit
+ (* Unify the two types given. Raise [Unify] if not possible. *)
+val unify_gadt: newtype_level:int -> Env.t ref -> type_expr -> type_expr -> unit
+ (* Unify the two types given and update the environment with the
+ local constraints. Raise [Unify] if not possible. *)
+val unify_var: Env.t -> type_expr -> type_expr -> unit
+ (* Same as [unify], but allow free univars when first type
+ is a variable. *)
+val filter_arrow: Env.t -> type_expr -> arg_label -> type_expr * type_expr
+ (* A special case of unification (with l:'a -> 'b). *)
+val filter_method: Env.t -> string -> private_flag -> type_expr -> type_expr
+ (* A special case of unification (with {m : 'a; 'b}). *)
+val check_filter_method: Env.t -> string -> private_flag -> type_expr -> unit
+ (* A special case of unification (with {m : 'a; 'b}), returning unit. *)
+val occur_in: Env.t -> type_expr -> type_expr -> bool
+val deep_occur: type_expr -> type_expr -> bool
+val filter_self_method:
+ Env.t -> string -> private_flag -> (Ident.t * type_expr) Meths.t ref ->
+ type_expr -> Ident.t * type_expr
+val moregeneral: Env.t -> bool -> type_expr -> type_expr -> bool
+ (* Check if the first type scheme is more general than the second. *)
+
+val rigidify: type_expr -> type_expr list
+ (* "Rigidify" a type and return its type variable *)
+val all_distinct_vars: Env.t -> type_expr list -> bool
+ (* Check those types are all distinct type variables *)
+val matches: Env.t -> type_expr -> type_expr -> bool
+ (* Same as [moregeneral false], implemented using the two above
+ functions and backtracking. Ignore levels *)
+
+type class_match_failure =
+ CM_Virtual_class
+ | CM_Parameter_arity_mismatch of int * int
+ | CM_Type_parameter_mismatch of Env.t * (type_expr * type_expr) list
+ | CM_Class_type_mismatch of Env.t * class_type * class_type
+ | CM_Parameter_mismatch of Env.t * (type_expr * type_expr) list
+ | CM_Val_type_mismatch of string * Env.t * (type_expr * type_expr) list
+ | CM_Meth_type_mismatch of string * Env.t * (type_expr * type_expr) list
+ | CM_Non_mutable_value of string
+ | CM_Non_concrete_value of string
+ | CM_Missing_value of string
+ | CM_Missing_method of string
+ | CM_Hide_public of string
+ | CM_Hide_virtual of string * string
+ | CM_Public_method of string
+ | CM_Private_method of string
+ | CM_Virtual_method of string
+val match_class_types:
+ ?trace:bool -> Env.t -> class_type -> class_type -> class_match_failure list
+ (* Check if the first class type is more general than the second. *)
+val equal: Env.t -> bool -> type_expr list -> type_expr list -> bool
+ (* [equal env [x1...xn] tau [y1...yn] sigma]
+ checks whether the parameterized types
+ [/\x1.../\xn.tau] and [/\y1.../\yn.sigma] are equivalent. *)
+val match_class_declarations:
+ Env.t -> type_expr list -> class_type -> type_expr list ->
+ class_type -> class_match_failure list
+ (* Check if the first class type is more general than the second. *)
+
+val enlarge_type: Env.t -> type_expr -> type_expr * bool
+ (* Make a type larger, flag is true if some pruning had to be done *)
+val subtype: Env.t -> type_expr -> type_expr -> unit -> unit
+ (* [subtype env t1 t2] checks that [t1] is a subtype of [t2].
+ It accumulates the constraints the type variables must
+ enforce and returns a function that inforce this
+ constraints. *)
+
+val nondep_type: Env.t -> Ident.t -> type_expr -> type_expr
+ (* Return a type equivalent to the given type but without
+ references to the given module identifier. Raise [Not_found]
+ if no such type exists. *)
+val nondep_type_decl:
+ Env.t -> Ident.t -> Ident.t -> bool -> type_declaration ->
+ type_declaration
+ (* Same for type declarations. *)
+val nondep_extension_constructor:
+ Env.t -> Ident.t -> extension_constructor ->
+ extension_constructor
+ (* Same for extension constructor *)
+val nondep_class_declaration:
+ Env.t -> Ident.t -> class_declaration -> class_declaration
+ (* Same for class declarations. *)
+val nondep_cltype_declaration:
+ Env.t -> Ident.t -> class_type_declaration -> class_type_declaration
+ (* Same for class type declarations. *)
+(*val correct_abbrev: Env.t -> Path.t -> type_expr list -> type_expr -> unit*)
+val cyclic_abbrev: Env.t -> Ident.t -> type_expr -> bool
+val is_contractive: Env.t -> type_expr -> bool
+val normalize_type: Env.t -> type_expr -> unit
+
+val closed_schema: Env.t -> type_expr -> bool
+ (* Check whether the given type scheme contains no non-generic
+ type variables *)
+
+val free_variables: ?env:Env.t -> type_expr -> type_expr list
+ (* If env present, then check for incomplete definitions too *)
+val closed_type_decl: type_declaration -> type_expr option
+val closed_extension_constructor: extension_constructor -> type_expr option
+type closed_class_failure =
+ CC_Method of type_expr * bool * string * type_expr
+ | CC_Value of type_expr * bool * string * type_expr
+val closed_class:
+ type_expr list -> class_signature -> closed_class_failure option
+ (* Check whether all type variables are bound *)
+
+val unalias: type_expr -> type_expr
+val signature_of_class_type: class_type -> class_signature
+val self_type: class_type -> type_expr
+val class_type_arity: class_type -> int
+val arity: type_expr -> int
+ (* Return the arity (as for curried functions) of the given type. *)
+
+val collapse_conj_params: Env.t -> type_expr list -> unit
+ (* Collapse conjunctive types in class parameters *)
+
+val get_current_level: unit -> int
+val wrap_trace_gadt_instances: Env.t -> ('a -> 'b) -> 'a -> 'b
+val reset_reified_var_counter: unit -> unit
+
+(* Stubs *)
+val package_subtype :
+ (Env.t -> Path.t -> Longident.t list -> type_expr list ->
+ Path.t -> Longident.t list -> type_expr list -> bool) ref
diff --git a/typing/datarepr.ml b/typing/datarepr.ml
new file mode 100644
index 0000000000..1c90fea588
--- /dev/null
+++ b/typing/datarepr.ml
@@ -0,0 +1,217 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compute constructor and label descriptions from type declarations,
+ determining their representation. *)
+
+open Asttypes
+open Types
+open Btype
+
+(* Simplified version of Ctype.free_vars *)
+let free_vars ?(param=false) ty =
+ let ret = ref TypeSet.empty in
+ let rec loop ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ ty.level <- pivot_level - ty.level;
+ match ty.desc with
+ | Tvar _ ->
+ ret := TypeSet.add ty !ret
+ | Tvariant row ->
+ let row = row_repr row in
+ iter_row loop row;
+ if not (static_row row) then begin
+ match row.row_more.desc with
+ | Tvar _ when param -> ret := TypeSet.add ty !ret
+ | _ -> loop row.row_more
+ end
+ (* XXX: What about Tobject ? *)
+ | _ ->
+ iter_type_expr loop ty
+ end
+ in
+ loop ty;
+ unmark_type ty;
+ !ret
+
+let newgenconstr path tyl = newgenty (Tconstr (path, tyl, ref Mnil))
+
+let constructor_args cd_args cd_res path rep =
+ let tyl =
+ match cd_args with
+ | Cstr_tuple l -> l
+ | Cstr_record l -> List.map (fun l -> l.ld_type) l
+ in
+ let existentials =
+ match cd_res with
+ | None -> []
+ | Some type_ret ->
+ let arg_vars_set = free_vars (newgenty (Ttuple tyl)) in
+ let res_vars = free_vars type_ret in
+ TypeSet.elements (TypeSet.diff arg_vars_set res_vars)
+ in
+ match cd_args with
+ | Cstr_tuple l -> existentials, l, None
+ | Cstr_record lbls ->
+ let arg_vars_set = free_vars ~param:true (newgenty (Ttuple tyl)) in
+ let type_params = TypeSet.elements arg_vars_set in
+ let tdecl =
+ {
+ type_params;
+ type_arity = List.length type_params;
+ type_kind = Type_record (lbls, rep);
+ type_private = Public;
+ type_manifest = None;
+ type_variance = List.map (fun _ -> Variance.full) type_params;
+ type_newtype_level = None;
+ type_loc = Location.none;
+ type_attributes = [];
+ }
+ in
+ existentials,
+ [ newgenconstr path type_params ],
+ Some tdecl
+
+let constructor_descrs ty_path decl cstrs =
+ let ty_res = newgenconstr ty_path decl.type_params in
+ let num_consts = ref 0 and num_nonconsts = ref 0 and num_normal = ref 0 in
+ List.iter
+ (fun {cd_args; cd_res; _} ->
+ if cd_args = Cstr_tuple [] then incr num_consts else incr num_nonconsts;
+ if cd_res = None then incr num_normal)
+ cstrs;
+ let rec describe_constructors idx_const idx_nonconst = function
+ [] -> []
+ | {cd_id; cd_args; cd_res; cd_loc; cd_attributes} :: rem ->
+ let ty_res =
+ match cd_res with
+ | Some ty_res' -> ty_res'
+ | None -> ty_res
+ in
+ let (tag, descr_rem) =
+ match cd_args with
+ Cstr_tuple [] -> (Cstr_constant idx_const,
+ describe_constructors (idx_const+1) idx_nonconst rem)
+ | _ -> (Cstr_block idx_nonconst,
+ describe_constructors idx_const (idx_nonconst+1) rem) in
+
+ let cstr_name = Ident.name cd_id in
+ let existentials, cstr_args, cstr_inlined =
+ constructor_args cd_args cd_res
+ (Path.Pdot (ty_path, cstr_name, Path.nopos))
+ (Record_inlined idx_nonconst)
+ in
+ let cstr =
+ { cstr_name;
+ cstr_res = ty_res;
+ cstr_existentials = existentials;
+ cstr_args;
+ cstr_arity = List.length cstr_args;
+ cstr_tag = tag;
+ cstr_consts = !num_consts;
+ cstr_nonconsts = !num_nonconsts;
+ cstr_normal = !num_normal;
+ cstr_private = decl.type_private;
+ cstr_generalized = cd_res <> None;
+ cstr_loc = cd_loc;
+ cstr_attributes = cd_attributes;
+ cstr_inlined;
+ } in
+ (cd_id, cstr) :: descr_rem in
+ describe_constructors 0 0 cstrs
+
+let extension_descr path_ext ext =
+ let ty_res =
+ match ext.ext_ret_type with
+ Some type_ret -> type_ret
+ | None -> newgenconstr ext.ext_type_path ext.ext_type_params
+ in
+ let existentials, cstr_args, cstr_inlined =
+ constructor_args ext.ext_args ext.ext_ret_type
+ path_ext Record_extension
+ in
+ { cstr_name = Path.last path_ext;
+ cstr_res = ty_res;
+ cstr_existentials = existentials;
+ cstr_args;
+ cstr_arity = List.length cstr_args;
+ cstr_tag = Cstr_extension(path_ext, cstr_args = []);
+ cstr_consts = -1;
+ cstr_nonconsts = -1;
+ cstr_private = ext.ext_private;
+ cstr_normal = -1;
+ cstr_generalized = ext.ext_ret_type <> None;
+ cstr_loc = ext.ext_loc;
+ cstr_attributes = ext.ext_attributes;
+ cstr_inlined;
+ }
+
+let none = {desc = Ttuple []; level = -1; id = -1}
+ (* Clearly ill-formed type *)
+let dummy_label =
+ { lbl_name = ""; lbl_res = none; lbl_arg = none; lbl_mut = Immutable;
+ lbl_pos = (-1); lbl_all = [||]; lbl_repres = Record_regular;
+ lbl_private = Public;
+ lbl_loc = Location.none;
+ lbl_attributes = [];
+ }
+
+let label_descrs ty_res lbls repres priv =
+ let all_labels = Array.make (List.length lbls) dummy_label in
+ let rec describe_labels num = function
+ [] -> []
+ | l :: rest ->
+ let lbl =
+ { lbl_name = Ident.name l.ld_id;
+ lbl_res = ty_res;
+ lbl_arg = l.ld_type;
+ lbl_mut = l.ld_mutable;
+ lbl_pos = num;
+ lbl_all = all_labels;
+ lbl_repres = repres;
+ lbl_private = priv;
+ lbl_loc = l.ld_loc;
+ lbl_attributes = l.ld_attributes;
+ } in
+ all_labels.(num) <- lbl;
+ (l.ld_id, lbl) :: describe_labels (num+1) rest in
+ describe_labels 0 lbls
+
+exception Constr_not_found
+
+let rec find_constr tag num_const num_nonconst = function
+ [] ->
+ raise Constr_not_found
+ | {cd_args = Cstr_tuple []; _} as c :: rem ->
+ if tag = Cstr_constant num_const
+ then c
+ else find_constr tag (num_const + 1) num_nonconst rem
+ | c :: rem ->
+ if tag = Cstr_block num_nonconst
+ then c
+ else find_constr tag num_const (num_nonconst + 1) rem
+
+let find_constr_by_tag tag cstrlist =
+ find_constr tag 0 0 cstrlist
+
+let constructors_of_type ty_path decl =
+ match decl.type_kind with
+ | Type_variant cstrs -> constructor_descrs ty_path decl cstrs
+ | Type_record _ | Type_abstract | Type_open -> []
+
+let labels_of_type ty_path decl =
+ match decl.type_kind with
+ | Type_record(labels, rep) ->
+ label_descrs (newgenconstr ty_path decl.type_params)
+ labels rep decl.type_private
+ | Type_variant _ | Type_abstract | Type_open -> []
diff --git a/typing/datarepr.mli b/typing/datarepr.mli
new file mode 100644
index 0000000000..d56446a243
--- /dev/null
+++ b/typing/datarepr.mli
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compute constructor and label descriptions from type declarations,
+ determining their representation. *)
+
+open Types
+
+val extension_descr:
+ Path.t -> extension_constructor -> constructor_description
+
+val labels_of_type:
+ Path.t -> type_declaration ->
+ (Ident.t * label_description) list
+val constructors_of_type:
+ Path.t -> type_declaration ->
+ (Ident.t * constructor_description) list
+
+
+exception Constr_not_found
+
+val find_constr_by_tag:
+ constructor_tag -> constructor_declaration list ->
+ constructor_declaration
diff --git a/typing/env.ml b/typing/env.ml
new file mode 100644
index 0000000000..2c7a6705a7
--- /dev/null
+++ b/typing/env.ml
@@ -0,0 +1,1890 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Environment handling *)
+
+open Cmi_format
+open Config
+open Misc
+open Asttypes
+open Longident
+open Path
+open Types
+open Btype
+
+let add_delayed_check_forward = ref (fun _ -> assert false)
+
+let value_declarations : ((string * Location.t), (unit -> unit)) Hashtbl.t =
+ Hashtbl.create 16
+ (* This table is used to usage of value declarations. A declaration is
+ identified with its name and location. The callback attached to a
+ declaration is called whenever the value is used explicitly
+ (lookup_value) or implicitly (inclusion test between signatures,
+ cf Includemod.value_descriptions). *)
+
+let type_declarations = Hashtbl.create 16
+
+type constructor_usage = Positive | Pattern | Privatize
+type constructor_usages =
+ {
+ mutable cu_positive: bool;
+ mutable cu_pattern: bool;
+ mutable cu_privatize: bool;
+ }
+let add_constructor_usage cu = function
+ | Positive -> cu.cu_positive <- true
+ | Pattern -> cu.cu_pattern <- true
+ | Privatize -> cu.cu_privatize <- true
+let constructor_usages () =
+ {cu_positive = false; cu_pattern = false; cu_privatize = false}
+
+let used_constructors :
+ (string * Location.t * string, (constructor_usage -> unit)) Hashtbl.t
+ = Hashtbl.create 16
+
+let prefixed_sg = Hashtbl.create 113
+
+type error =
+ | Illegal_renaming of string * string * string
+ | Inconsistent_import of string * string * string
+ | Need_recursive_types of string * string
+ | Missing_module of Location.t * Path.t * Path.t
+ | Illegal_value_name of Location.t * string
+
+exception Error of error
+
+let error err = raise (Error err)
+
+module EnvLazy : sig
+ type ('a,'b) t
+
+ val force : ('a -> 'b) -> ('a,'b) t -> 'b
+ val create : 'a -> ('a,'b) t
+ val is_val : ('a,'b) t -> bool
+ val get_arg : ('a,'b) t -> 'a option
+
+end = struct
+
+ type ('a,'b) t = ('a,'b) eval ref
+
+ and ('a,'b) eval =
+ Done of 'b
+ | Raise of exn
+ | Thunk of 'a
+
+ let force f x =
+ match !x with
+ Done x -> x
+ | Raise e -> raise e
+ | Thunk e ->
+ try
+ let y = f e in
+ x := Done y;
+ y
+ with e ->
+ x := Raise e;
+ raise e
+
+ let is_val x =
+ match !x with Done _ -> true | _ -> false
+
+ let get_arg x =
+ match !x with Thunk a -> Some a | _ -> None
+
+ let create x =
+ let x = ref (Thunk x) in
+ x
+
+end
+
+
+type summary =
+ Env_empty
+ | Env_value of summary * Ident.t * value_description
+ | Env_type of summary * Ident.t * type_declaration
+ | Env_extension of summary * Ident.t * extension_constructor
+ | Env_module of summary * Ident.t * module_declaration
+ | Env_modtype of summary * Ident.t * modtype_declaration
+ | Env_class of summary * Ident.t * class_declaration
+ | Env_cltype of summary * Ident.t * class_type_declaration
+ | Env_open of summary * Path.t
+ | Env_functor_arg of summary * Ident.t
+
+module EnvTbl =
+ struct
+ (* A table indexed by identifier, with an extra slot to record usage. *)
+ type 'a t = ('a * (unit -> unit)) Ident.tbl
+
+ let empty = Ident.empty
+ let nothing = fun () -> ()
+
+ let already_defined s tbl =
+ try ignore (Ident.find_name s tbl); true
+ with Not_found -> false
+
+ let add kind slot id x tbl ref_tbl =
+ let slot =
+ match slot with
+ | None -> nothing
+ | Some f ->
+ (fun () ->
+ let s = Ident.name id in
+ f kind s (already_defined s ref_tbl)
+ )
+ in
+ Ident.add id (x, slot) tbl
+
+ let add_dont_track id x tbl =
+ Ident.add id (x, nothing) tbl
+
+ let find_same_not_using id tbl =
+ fst (Ident.find_same id tbl)
+
+ let find_same id tbl =
+ let (x, slot) = Ident.find_same id tbl in
+ slot ();
+ x
+
+ let find_name s tbl =
+ let (x, slot) = Ident.find_name s tbl in
+ slot ();
+ x
+
+ let find_all s tbl =
+ Ident.find_all s tbl
+
+ let fold_name f = Ident.fold_name (fun k (d,_) -> f k d)
+ let keys tbl = Ident.fold_all (fun k _ accu -> k::accu) tbl []
+ end
+
+type type_descriptions =
+ constructor_description list * label_description list
+
+let in_signature_flag = 0x01
+let implicit_coercion_flag = 0x02
+
+type t = {
+ values: (Path.t * value_description) EnvTbl.t;
+ constrs: constructor_description EnvTbl.t;
+ labels: label_description EnvTbl.t;
+ types: (Path.t * (type_declaration * type_descriptions)) EnvTbl.t;
+ modules: (Path.t * module_declaration) EnvTbl.t;
+ modtypes: (Path.t * modtype_declaration) EnvTbl.t;
+ components: (Path.t * module_components) EnvTbl.t;
+ classes: (Path.t * class_declaration) EnvTbl.t;
+ cltypes: (Path.t * class_type_declaration) EnvTbl.t;
+ functor_args: unit Ident.tbl;
+ summary: summary;
+ local_constraints: bool;
+ gadt_instances: (int * TypeSet.t ref) list;
+ flags: int;
+}
+
+and module_components =
+ (t * Subst.t * Path.t * Types.module_type, module_components_repr) EnvLazy.t
+
+and module_components_repr =
+ Structure_comps of structure_components
+ | Functor_comps of functor_components
+
+and structure_components = {
+ mutable comp_values: (string, (value_description * int)) Tbl.t;
+ mutable comp_constrs: (string, (constructor_description * int) list) Tbl.t;
+ mutable comp_labels: (string, (label_description * int) list) Tbl.t;
+ mutable comp_types:
+ (string, ((type_declaration * type_descriptions) * int)) Tbl.t;
+ mutable comp_modules:
+ (string, ((Subst.t * Types.module_type,module_type) EnvLazy.t * int)) Tbl.t;
+ mutable comp_modtypes: (string, (modtype_declaration * int)) Tbl.t;
+ mutable comp_components: (string, (module_components * int)) Tbl.t;
+ mutable comp_classes: (string, (class_declaration * int)) Tbl.t;
+ mutable comp_cltypes: (string, (class_type_declaration * int)) Tbl.t
+}
+
+and functor_components = {
+ fcomp_param: Ident.t; (* Formal parameter *)
+ fcomp_arg: module_type option; (* Argument signature *)
+ fcomp_res: module_type; (* Result signature *)
+ fcomp_cache: (Path.t, module_components) Hashtbl.t; (* For memoization *)
+ fcomp_subst_cache: (Path.t, module_type) Hashtbl.t
+}
+
+let subst_modtype_maker (subst, mty) = Subst.modtype subst mty
+
+let empty = {
+ values = EnvTbl.empty; constrs = EnvTbl.empty;
+ labels = EnvTbl.empty; types = EnvTbl.empty;
+ modules = EnvTbl.empty; modtypes = EnvTbl.empty;
+ components = EnvTbl.empty; classes = EnvTbl.empty;
+ cltypes = EnvTbl.empty;
+ summary = Env_empty; local_constraints = false; gadt_instances = [];
+ flags = 0;
+ functor_args = Ident.empty;
+ }
+
+let in_signature b env =
+ let flags =
+ if b then env.flags lor in_signature_flag
+ else env.flags land (lnot in_signature_flag)
+ in
+ {env with flags}
+
+let implicit_coercion env =
+ {env with flags = env.flags lor implicit_coercion_flag}
+
+let is_in_signature env = env.flags land in_signature_flag <> 0
+let is_implicit_coercion env = env.flags land implicit_coercion_flag <> 0
+
+let diff_keys is_local tbl1 tbl2 =
+ let keys2 = EnvTbl.keys tbl2 in
+ List.filter
+ (fun id ->
+ is_local (EnvTbl.find_same_not_using id tbl2) &&
+ try ignore (EnvTbl.find_same_not_using id tbl1); false
+ with Not_found -> true)
+ keys2
+
+let is_ident = function
+ Pident _ -> true
+ | Pdot _ | Papply _ -> false
+
+let is_local (p, _) = is_ident p
+
+let is_local_ext = function
+ | {cstr_tag = Cstr_extension(p, _)} -> is_ident p
+ | _ -> false
+
+let diff env1 env2 =
+ diff_keys is_local env1.values env2.values @
+ diff_keys is_local_ext env1.constrs env2.constrs @
+ diff_keys is_local env1.modules env2.modules @
+ diff_keys is_local env1.classes env2.classes
+
+(* Forward declarations *)
+
+let components_of_module' =
+ ref ((fun env sub path mty -> assert false) :
+ t -> Subst.t -> Path.t -> module_type -> module_components)
+let components_of_module_maker' =
+ ref ((fun (env, sub, path, mty) -> assert false) :
+ t * Subst.t * Path.t * module_type -> module_components_repr)
+let components_of_functor_appl' =
+ ref ((fun f env p1 p2 -> assert false) :
+ functor_components -> t -> Path.t -> Path.t -> module_components)
+let check_modtype_inclusion =
+ (* to be filled with Includemod.check_modtype_inclusion *)
+ ref ((fun env mty1 path1 mty2 -> assert false) :
+ t -> module_type -> Path.t -> module_type -> unit)
+let strengthen =
+ (* to be filled with Mtype.strengthen *)
+ ref ((fun env mty path -> assert false) :
+ t -> module_type -> Path.t -> module_type)
+
+let md md_type =
+ {md_type; md_attributes=[]; md_loc=Location.none}
+
+(* The name of the compilation unit currently compiled.
+ "" if outside a compilation unit. *)
+
+let current_unit = ref ""
+
+(* Persistent structure descriptions *)
+
+type pers_struct =
+ { ps_name: string;
+ ps_sig: signature Lazy.t;
+ ps_comps: module_components;
+ ps_crcs: (string * Digest.t option) list;
+ mutable ps_crcs_checked: bool;
+ ps_filename: string;
+ ps_flags: pers_flags list }
+
+let persistent_structures =
+ (Hashtbl.create 17 : (string, pers_struct option) Hashtbl.t)
+
+(* Consistency between persistent structures *)
+
+let crc_units = Consistbl.create()
+
+module StringSet =
+ Set.Make(struct type t = string let compare = String.compare end)
+
+let imported_units = ref StringSet.empty
+
+let add_import s =
+ imported_units := StringSet.add s !imported_units
+
+let clear_imports () =
+ Consistbl.clear crc_units;
+ imported_units := StringSet.empty
+
+let check_consistency ps =
+ if not ps.ps_crcs_checked then
+ try
+ List.iter
+ (fun (name, crco) ->
+ match crco with
+ None -> ()
+ | Some crc ->
+ add_import name;
+ Consistbl.check crc_units name crc ps.ps_filename)
+ ps.ps_crcs;
+ ps.ps_crcs_checked <- true;
+ with Consistbl.Inconsistency(name, source, auth) ->
+ error (Inconsistent_import(name, auth, source))
+
+(* Reading persistent structures from .cmi files *)
+
+let save_pers_struct crc ps =
+ let modname = ps.ps_name in
+ Hashtbl.add persistent_structures modname (Some ps);
+ Consistbl.set crc_units modname crc ps.ps_filename;
+ add_import modname
+
+let read_pers_struct modname filename =
+ let cmi = read_cmi filename in
+ let name = cmi.cmi_name in
+ let sign = cmi.cmi_sign in
+ let crcs = cmi.cmi_crcs in
+ let flags = cmi.cmi_flags in
+ let comps =
+ !components_of_module' empty Subst.identity
+ (Pident(Ident.create_persistent name))
+ (Mty_signature sign)
+ in
+ let ps = { ps_name = name;
+ ps_sig = lazy (Subst.signature Subst.identity sign);
+ ps_comps = comps;
+ ps_crcs = crcs;
+ ps_filename = filename;
+ ps_flags = flags;
+ ps_crcs_checked = false;
+ } in
+ if ps.ps_name <> modname then
+ error (Illegal_renaming(modname, ps.ps_name, filename));
+ add_import name;
+ List.iter
+ (function Rectypes ->
+ if not !Clflags.recursive_types then
+ error (Need_recursive_types(ps.ps_name, !current_unit)))
+ ps.ps_flags;
+ Hashtbl.add persistent_structures modname (Some ps);
+ ps
+
+let find_pers_struct ?(check=true) name =
+ if name = "*predef*" then raise Not_found;
+ let r =
+ try Some (Hashtbl.find persistent_structures name)
+ with Not_found -> None
+ in
+ let ps =
+ match r with
+ | Some None -> raise Not_found
+ | Some (Some sg) -> sg
+ | None ->
+ (* PR#6843: record the weak dependency ([add_import]) even if
+ the [find_in_path_uncap] call below fails to find the .cmi,
+ to help make builds more deterministic. *)
+ add_import name;
+ let filename =
+ try find_in_path_uncap !load_path (name ^ ".cmi")
+ with Not_found ->
+ Hashtbl.add persistent_structures name None;
+ raise Not_found
+ in
+ read_pers_struct name filename
+ in
+ if check then check_consistency ps;
+ ps
+
+let reset_cache () =
+ current_unit := "";
+ Hashtbl.clear persistent_structures;
+ clear_imports ();
+ Hashtbl.clear value_declarations;
+ Hashtbl.clear type_declarations;
+ Hashtbl.clear used_constructors;
+ Hashtbl.clear prefixed_sg
+
+let reset_cache_toplevel () =
+ (* Delete 'missing cmi' entries from the cache. *)
+ let l =
+ Hashtbl.fold
+ (fun name r acc -> if r = None then name :: acc else acc)
+ persistent_structures []
+ in
+ List.iter (Hashtbl.remove persistent_structures) l;
+ Hashtbl.clear value_declarations;
+ Hashtbl.clear type_declarations;
+ Hashtbl.clear used_constructors;
+ Hashtbl.clear prefixed_sg
+
+
+let set_unit_name name =
+ current_unit := name
+
+let get_unit_name () =
+ !current_unit
+
+(* Lookup by identifier *)
+
+let rec find_module_descr path env =
+ match path with
+ Pident id ->
+ begin try
+ let (p, desc) = EnvTbl.find_same id env.components
+ in desc
+ with Not_found ->
+ if Ident.persistent id && not (Ident.name id = !current_unit)
+ then (find_pers_struct (Ident.name id)).ps_comps
+ else raise Not_found
+ end
+ | Pdot(p, s, pos) ->
+ begin match
+ EnvLazy.force !components_of_module_maker' (find_module_descr p env)
+ with
+ Structure_comps c ->
+ let (descr, pos) = Tbl.find s c.comp_components in
+ descr
+ | Functor_comps f ->
+ raise Not_found
+ end
+ | Papply(p1, p2) ->
+ begin match
+ EnvLazy.force !components_of_module_maker' (find_module_descr p1 env)
+ with
+ Functor_comps f ->
+ !components_of_functor_appl' f env p1 p2
+ | Structure_comps c ->
+ raise Not_found
+ end
+
+let find proj1 proj2 path env =
+ match path with
+ Pident id ->
+ let (p, data) = EnvTbl.find_same id (proj1 env)
+ in data
+ | Pdot(p, s, pos) ->
+ begin match
+ EnvLazy.force !components_of_module_maker' (find_module_descr p env)
+ with
+ Structure_comps c ->
+ let (data, pos) = Tbl.find s (proj2 c) in data
+ | Functor_comps f ->
+ raise Not_found
+ end
+ | Papply(p1, p2) ->
+ raise Not_found
+
+let find_value =
+ find (fun env -> env.values) (fun sc -> sc.comp_values)
+and find_type_full =
+ find (fun env -> env.types) (fun sc -> sc.comp_types)
+and find_modtype =
+ find (fun env -> env.modtypes) (fun sc -> sc.comp_modtypes)
+and find_class =
+ find (fun env -> env.classes) (fun sc -> sc.comp_classes)
+and find_cltype =
+ find (fun env -> env.cltypes) (fun sc -> sc.comp_cltypes)
+
+let type_of_cstr path = function
+ | {cstr_inlined = Some d; _} ->
+ (d, ([], List.map snd (Datarepr.labels_of_type path d)))
+ | _ ->
+ assert false
+
+let find_type_full path env =
+ match Path.constructor_typath path with
+ | Regular p -> find_type_full p env
+ | Cstr (ty_path, s) ->
+ let (_, (cstrs, _)) =
+ try find_type_full ty_path env
+ with Not_found -> assert false
+ in
+ let cstr =
+ try List.find (fun cstr -> cstr.cstr_name = s) cstrs
+ with Not_found -> assert false
+ in
+ type_of_cstr path cstr
+ | LocalExt id ->
+ let cstr =
+ try EnvTbl.find_same id env.constrs
+ with Not_found -> assert false
+ in
+ type_of_cstr path cstr
+ | Ext (mod_path, s) ->
+ let comps =
+ try find_module_descr mod_path env
+ with Not_found -> assert false
+ in
+ let comps =
+ match EnvLazy.force !components_of_module_maker' comps with
+ | Structure_comps c -> c
+ | Functor_comps _ -> assert false
+ in
+ let exts =
+ List.filter
+ (function ({cstr_tag=Cstr_extension _}, _) -> true | _ -> false)
+ (try Tbl.find s comps.comp_constrs
+ with Not_found -> assert false)
+ in
+ match exts with
+ | [(cstr, _)] -> type_of_cstr path cstr
+ | _ -> assert false
+
+let find_type p env =
+ fst (find_type_full p env)
+let find_type_descrs p env =
+ snd (find_type_full p env)
+
+let find_module ~alias path env =
+ match path with
+ Pident id ->
+ begin try
+ let (p, data) = EnvTbl.find_same id env.modules
+ in data
+ with Not_found ->
+ if Ident.persistent id && not (Ident.name id = !current_unit) then
+ let ps = find_pers_struct (Ident.name id) in
+ md (Mty_signature(Lazy.force ps.ps_sig))
+ else raise Not_found
+ end
+ | Pdot(p, s, pos) ->
+ begin match
+ EnvLazy.force !components_of_module_maker' (find_module_descr p env)
+ with
+ Structure_comps c ->
+ let (data, pos) = Tbl.find s c.comp_modules in
+ md (EnvLazy.force subst_modtype_maker data)
+ | Functor_comps f ->
+ raise Not_found
+ end
+ | Papply(p1, p2) ->
+ let desc1 = find_module_descr p1 env in
+ begin match EnvLazy.force !components_of_module_maker' desc1 with
+ Functor_comps f ->
+ md begin match f.fcomp_res with
+ | Mty_alias p as mty-> mty
+ | mty ->
+ if alias then mty else
+ try
+ Hashtbl.find f.fcomp_subst_cache p2
+ with Not_found ->
+ let mty =
+ Subst.modtype
+ (Subst.add_module f.fcomp_param p2 Subst.identity)
+ f.fcomp_res in
+ Hashtbl.add f.fcomp_subst_cache p2 mty;
+ mty
+ end
+ | Structure_comps c ->
+ raise Not_found
+ end
+
+let required_globals = ref []
+let reset_required_globals () = required_globals := []
+let get_required_globals () = !required_globals
+let add_required_global id =
+ if Ident.global id && not !Clflags.transparent_modules
+ && not (List.exists (Ident.same id) !required_globals)
+ then required_globals := id :: !required_globals
+
+let rec normalize_path lax env path =
+ let path =
+ match path with
+ Pdot(p, s, pos) ->
+ Pdot(normalize_path lax env p, s, pos)
+ | Papply(p1, p2) ->
+ Papply(normalize_path lax env p1, normalize_path true env p2)
+ | _ -> path
+ in
+ try match find_module ~alias:true path env with
+ {md_type=Mty_alias path1} ->
+ let path' = normalize_path lax env path1 in
+ if lax || !Clflags.transparent_modules then path' else
+ let id = Path.head path in
+ if Ident.global id && not (Ident.same id (Path.head path'))
+ then add_required_global id;
+ path'
+ | _ -> path
+ with Not_found when lax
+ || (match path with Pident id -> not (Ident.persistent id) | _ -> true) ->
+ path
+
+let normalize_path oloc env path =
+ try normalize_path (oloc = None) env path
+ with Not_found ->
+ match oloc with None -> assert false
+ | Some loc ->
+ raise (Error(Missing_module(loc, path, normalize_path true env path)))
+
+let find_module = find_module ~alias:false
+
+(* Find the manifest type associated to a type when appropriate:
+ - the type should be public or should have a private row,
+ - the type should have an associated manifest type. *)
+let find_type_expansion path env =
+ let decl = find_type path env in
+ match decl.type_manifest with
+ | Some body when decl.type_private = Public
+ || decl.type_kind <> Type_abstract
+ || Btype.has_constr_row body ->
+ (decl.type_params, body, may_map snd decl.type_newtype_level)
+ (* The manifest type of Private abstract data types without
+ private row are still considered unknown to the type system.
+ Hence, this case is caught by the following clause that also handles
+ purely abstract data types without manifest type definition. *)
+ | _ ->
+ (* another way to expand is to normalize the path itself *)
+ let path' = normalize_path None env path in
+ if Path.same path path' then raise Not_found else
+ (decl.type_params,
+ newgenty (Tconstr (path', decl.type_params, ref Mnil)),
+ may_map snd decl.type_newtype_level)
+
+(* Find the manifest type information associated to a type, i.e.
+ the necessary information for the compiler's type-based optimisations.
+ In particular, the manifest type associated to a private abstract type
+ is revealed for the sake of compiler's type-based optimisations. *)
+let find_type_expansion_opt path env =
+ let decl = find_type path env in
+ match decl.type_manifest with
+ (* The manifest type of Private abstract data types can still get
+ an approximation using their manifest type. *)
+ | Some body -> (decl.type_params, body, may_map snd decl.type_newtype_level)
+ | _ ->
+ let path' = normalize_path None env path in
+ if Path.same path path' then raise Not_found else
+ (decl.type_params,
+ newgenty (Tconstr (path', decl.type_params, ref Mnil)),
+ may_map snd decl.type_newtype_level)
+
+let find_modtype_expansion path env =
+ match (find_modtype path env).mtd_type with
+ | None -> raise Not_found
+ | Some mty -> mty
+
+let rec is_functor_arg path env =
+ match path with
+ Pident id ->
+ begin try Ident.find_same id env.functor_args; true
+ with Not_found -> false
+ end
+ | Pdot (p, s, _) -> is_functor_arg p env
+ | Papply _ -> true
+
+(* Lookup by name *)
+
+exception Recmodule
+
+let rec lookup_module_descr lid env =
+ match lid with
+ Lident s ->
+ begin try
+ EnvTbl.find_name s env.components
+ with Not_found ->
+ if s = !current_unit then raise Not_found;
+ let ps = find_pers_struct s in
+ (Pident(Ident.create_persistent s), ps.ps_comps)
+ end
+ | Ldot(l, s) ->
+ let (p, descr) = lookup_module_descr l env in
+ begin match EnvLazy.force !components_of_module_maker' descr with
+ Structure_comps c ->
+ let (descr, pos) = Tbl.find s c.comp_components in
+ (Pdot(p, s, pos), descr)
+ | Functor_comps f ->
+ raise Not_found
+ end
+ | Lapply(l1, l2) ->
+ let (p1, desc1) = lookup_module_descr l1 env in
+ let p2 = lookup_module true l2 env in
+ let {md_type=mty2} = find_module p2 env in
+ begin match EnvLazy.force !components_of_module_maker' desc1 with
+ Functor_comps f ->
+ Misc.may (!check_modtype_inclusion env mty2 p2) f.fcomp_arg;
+ (Papply(p1, p2), !components_of_functor_appl' f env p1 p2)
+ | Structure_comps c ->
+ raise Not_found
+ end
+
+and lookup_module ~load lid env : Path.t =
+ match lid with
+ Lident s ->
+ begin try
+ let (p, {md_type}) as r = EnvTbl.find_name s env.modules in
+ begin match md_type with
+ | Mty_ident (Path.Pident id) when Ident.name id = "#recmod#" ->
+ (* see #5965 *)
+ raise Recmodule
+ | _ -> ()
+ end;
+ p
+ with Not_found ->
+ if s = !current_unit then raise Not_found;
+ if !Clflags.transparent_modules && not load then
+ try ignore (find_pers_struct ~check:false s)
+ with Not_found ->
+ Location.prerr_warning Location.none (Warnings.No_cmi_file s)
+ else ignore (find_pers_struct s);
+ Pident(Ident.create_persistent s)
+ end
+ | Ldot(l, s) ->
+ let (p, descr) = lookup_module_descr l env in
+ begin match EnvLazy.force !components_of_module_maker' descr with
+ Structure_comps c ->
+ let (data, pos) = Tbl.find s c.comp_modules in
+ Pdot(p, s, pos)
+ | Functor_comps f ->
+ raise Not_found
+ end
+ | Lapply(l1, l2) ->
+ let (p1, desc1) = lookup_module_descr l1 env in
+ let p2 = lookup_module true l2 env in
+ let {md_type=mty2} = find_module p2 env in
+ let p = Papply(p1, p2) in
+ begin match EnvLazy.force !components_of_module_maker' desc1 with
+ Functor_comps f ->
+ Misc.may (!check_modtype_inclusion env mty2 p2) f.fcomp_arg;
+ p
+ | Structure_comps c ->
+ raise Not_found
+ end
+
+let lookup proj1 proj2 lid env =
+ match lid with
+ Lident s ->
+ EnvTbl.find_name s (proj1 env)
+ | Ldot(l, s) ->
+ let (p, desc) = lookup_module_descr l env in
+ begin match EnvLazy.force !components_of_module_maker' desc with
+ Structure_comps c ->
+ let (data, pos) = Tbl.find s (proj2 c) in
+ (Pdot(p, s, pos), data)
+ | Functor_comps f ->
+ raise Not_found
+ end
+ | Lapply(l1, l2) ->
+ raise Not_found
+
+let lookup_all_simple proj1 proj2 shadow lid env =
+ match lid with
+ Lident s ->
+ let xl = EnvTbl.find_all s (proj1 env) in
+ let rec do_shadow =
+ function
+ | [] -> []
+ | ((x, f) :: xs) ->
+ (x, f) ::
+ (do_shadow (List.filter (fun (y, g) -> not (shadow x y)) xs))
+ in
+ do_shadow xl
+ | Ldot(l, s) ->
+ let (p, desc) = lookup_module_descr l env in
+ begin match EnvLazy.force !components_of_module_maker' desc with
+ Structure_comps c ->
+ let comps =
+ try Tbl.find s (proj2 c) with Not_found -> []
+ in
+ List.map
+ (fun (data, pos) -> (data, (fun () -> ())))
+ comps
+ | Functor_comps f ->
+ raise Not_found
+ end
+ | Lapply(l1, l2) ->
+ raise Not_found
+
+let has_local_constraints env = env.local_constraints
+
+let cstr_shadow cstr1 cstr2 =
+ match cstr1.cstr_tag, cstr2.cstr_tag with
+ | Cstr_extension _, Cstr_extension _ -> true
+ | _ -> false
+
+let lbl_shadow lbl1 lbl2 = false
+
+let lookup_value =
+ lookup (fun env -> env.values) (fun sc -> sc.comp_values)
+and lookup_all_constructors =
+ lookup_all_simple (fun env -> env.constrs) (fun sc -> sc.comp_constrs)
+ cstr_shadow
+and lookup_all_labels =
+ lookup_all_simple (fun env -> env.labels) (fun sc -> sc.comp_labels)
+ lbl_shadow
+and lookup_type =
+ lookup (fun env -> env.types) (fun sc -> sc.comp_types)
+and lookup_modtype =
+ lookup (fun env -> env.modtypes) (fun sc -> sc.comp_modtypes)
+and lookup_class =
+ lookup (fun env -> env.classes) (fun sc -> sc.comp_classes)
+and lookup_cltype =
+ lookup (fun env -> env.cltypes) (fun sc -> sc.comp_cltypes)
+
+let mark_value_used env name vd =
+ if not (is_implicit_coercion env) then
+ try Hashtbl.find value_declarations (name, vd.val_loc) ()
+ with Not_found -> ()
+
+let mark_type_used env name vd =
+ if not (is_implicit_coercion env) then
+ try Hashtbl.find type_declarations (name, vd.type_loc) ()
+ with Not_found -> ()
+
+let mark_constructor_used usage env name vd constr =
+ if not (is_implicit_coercion env) then
+ try Hashtbl.find used_constructors (name, vd.type_loc, constr) usage
+ with Not_found -> ()
+
+let mark_extension_used usage env ext name =
+ if not (is_implicit_coercion env) then
+ let ty_name = Path.last ext.ext_type_path in
+ try Hashtbl.find used_constructors (ty_name, ext.ext_loc, name) usage
+ with Not_found -> ()
+
+let set_value_used_callback name vd callback =
+ let key = (name, vd.val_loc) in
+ try
+ let old = Hashtbl.find value_declarations key in
+ Hashtbl.replace value_declarations key (fun () -> old (); callback ())
+ (* this is to support cases like:
+ let x = let x = 1 in x in x
+ where the two declarations have the same location
+ (e.g. resulting from Camlp4 expansion of grammar entries) *)
+ with Not_found ->
+ Hashtbl.add value_declarations key callback
+
+let set_type_used_callback name td callback =
+ let loc = td.type_loc in
+ if loc.Location.loc_ghost then ()
+ else let key = (name, loc) in
+ let old =
+ try Hashtbl.find type_declarations key
+ with Not_found -> assert false
+ in
+ Hashtbl.replace type_declarations key (fun () -> callback old)
+
+let lookup_value lid env =
+ let (_, desc) as r = lookup_value lid env in
+ mark_value_used env (Longident.last lid) desc;
+ r
+
+let lookup_type lid env =
+ let (path, (decl, _)) = lookup_type lid env in
+ mark_type_used env (Longident.last lid) decl;
+ (path, decl)
+
+(* [path] must be the path to a type, not to a module ! *)
+let path_subst_last path id =
+ match path with
+ Pident _ -> Pident id
+ | Pdot (p, name, pos) -> Pdot(p, Ident.name id, pos)
+ | Papply (p1, p2) -> assert false
+
+let mark_type_path env path =
+ try
+ let decl = find_type path env in
+ mark_type_used env (Path.last path) decl
+ with Not_found -> ()
+
+let ty_path t =
+ match repr t with
+ | {desc=Tconstr(path, _, _)} -> path
+ | _ -> assert false
+
+let lookup_constructor lid env =
+ match lookup_all_constructors lid env with
+ [] -> raise Not_found
+ | (desc, use) :: _ ->
+ mark_type_path env (ty_path desc.cstr_res);
+ use ();
+ desc
+
+let is_lident = function
+ Lident _ -> true
+ | _ -> false
+
+let lookup_all_constructors lid env =
+ try
+ let cstrs = lookup_all_constructors lid env in
+ let wrap_use desc use () =
+ mark_type_path env (ty_path desc.cstr_res);
+ use ()
+ in
+ List.map (fun (cstr, use) -> (cstr, wrap_use cstr use)) cstrs
+ with
+ Not_found when is_lident lid -> []
+
+let mark_constructor usage env name desc =
+ if not (is_implicit_coercion env)
+ then match desc.cstr_tag with
+ | Cstr_extension _ ->
+ begin
+ let ty_path = ty_path desc.cstr_res in
+ let ty_name = Path.last ty_path in
+ try Hashtbl.find used_constructors (ty_name, desc.cstr_loc, name) usage
+ with Not_found -> ()
+ end
+ | _ ->
+ let ty_path = ty_path desc.cstr_res in
+ let ty_decl = try find_type ty_path env with Not_found -> assert false in
+ let ty_name = Path.last ty_path in
+ mark_constructor_used usage env ty_name ty_decl name
+
+let lookup_label lid env =
+ match lookup_all_labels lid env with
+ [] -> raise Not_found
+ | (desc, use) :: _ ->
+ mark_type_path env (ty_path desc.lbl_res);
+ use ();
+ desc
+
+let lookup_all_labels lid env =
+ try
+ let lbls = lookup_all_labels lid env in
+ let wrap_use desc use () =
+ mark_type_path env (ty_path desc.lbl_res);
+ use ()
+ in
+ List.map (fun (lbl, use) -> (lbl, wrap_use lbl use)) lbls
+ with
+ Not_found when is_lident lid -> []
+
+let lookup_class lid env =
+ let (_, desc) as r = lookup_class lid env in
+ (* special support for Typeclass.unbound_class *)
+ if Path.name desc.cty_path = "" then ignore (lookup_type lid env)
+ else mark_type_path env desc.cty_path;
+ r
+
+let lookup_cltype lid env =
+ let (_, desc) as r = lookup_cltype lid env in
+ if Path.name desc.clty_path = "" then ignore (lookup_type lid env)
+ else mark_type_path env desc.clty_path;
+ mark_type_path env desc.clty_path;
+ r
+
+(* Iter on an environment (ignoring the body of functors and
+ not yet evaluated structures) *)
+
+type iter_cont = unit -> unit
+let iter_env_cont = ref []
+
+let rec scrape_alias_safe env mty =
+ match mty with
+ | Mty_alias (Pident id) when Ident.persistent id -> false
+ | Mty_alias path -> (* PR#6600: find_module may raise Not_found *)
+ scrape_alias_safe env (find_module path env).md_type
+ | _ -> true
+
+let iter_env proj1 proj2 f env () =
+ Ident.iter (fun id (x,_) -> f (Pident id) x) (proj1 env);
+ let rec iter_components path path' mcomps =
+ let cont () =
+ let safe =
+ match EnvLazy.get_arg mcomps with
+ None -> true
+ | Some (env, sub, path, mty) ->
+ try scrape_alias_safe env mty with Not_found -> false
+ in
+ if not safe then () else
+ match EnvLazy.force !components_of_module_maker' mcomps with
+ Structure_comps comps ->
+ Tbl.iter
+ (fun s (d, n) -> f (Pdot (path, s, n)) (Pdot (path', s, n), d))
+ (proj2 comps);
+ Tbl.iter
+ (fun s (c, n) ->
+ iter_components (Pdot (path, s, n)) (Pdot (path', s, n)) c)
+ comps.comp_components
+ | Functor_comps _ -> ()
+ in iter_env_cont := (path, cont) :: !iter_env_cont
+ in
+ Hashtbl.iter
+ (fun s pso ->
+ match pso with None -> ()
+ | Some ps ->
+ let id = Pident (Ident.create_persistent s) in
+ iter_components id id ps.ps_comps)
+ persistent_structures;
+ Ident.iter
+ (fun id ((path, comps), _) -> iter_components (Pident id) path comps)
+ env.components
+
+let run_iter_cont l =
+ iter_env_cont := [];
+ List.iter (fun c -> c ()) l;
+ let cont = List.rev !iter_env_cont in
+ iter_env_cont := [];
+ cont
+
+let iter_types f = iter_env (fun env -> env.types) (fun sc -> sc.comp_types) f
+
+let same_types env1 env2 =
+ env1.types == env2.types && env1.components == env2.components
+
+let used_persistent () =
+ let r = ref Concr.empty in
+ Hashtbl.iter (fun s pso -> if pso != None then r := Concr.add s !r)
+ persistent_structures;
+ !r
+
+let find_all_comps proj s (p,mcomps) =
+ match EnvLazy.force !components_of_module_maker' mcomps with
+ Functor_comps _ -> []
+ | Structure_comps comps ->
+ try let (c,n) = Tbl.find s (proj comps) in [Pdot(p,s,n), c]
+ with Not_found -> []
+
+let rec find_shadowed_comps path env =
+ match path with
+ Pident id ->
+ List.map fst (Ident.find_all (Ident.name id) env.components)
+ | Pdot (p, s, _) ->
+ let l = find_shadowed_comps p env in
+ let l' =
+ List.map (find_all_comps (fun comps -> comps.comp_components) s) l in
+ List.flatten l'
+ | Papply _ -> []
+
+let find_shadowed proj1 proj2 path env =
+ match path with
+ Pident id ->
+ List.map fst (Ident.find_all (Ident.name id) (proj1 env))
+ | Pdot (p, s, _) ->
+ let l = find_shadowed_comps p env in
+ let l' = List.map (find_all_comps proj2 s) l in
+ List.flatten l'
+ | Papply _ -> []
+
+let find_shadowed_types path env =
+ let l =
+ find_shadowed
+ (fun env -> env.types) (fun comps -> comps.comp_types) path env
+ in
+ List.map fst l
+
+
+(* GADT instance tracking *)
+
+let add_gadt_instance_level lv env =
+ {env with
+ gadt_instances = (lv, ref TypeSet.empty) :: env.gadt_instances}
+
+let is_Tlink = function {desc = Tlink _} -> true | _ -> false
+
+let gadt_instance_level env t =
+ let rec find_instance = function
+ [] -> None
+ | (lv, r) :: rem ->
+ if TypeSet.exists is_Tlink !r then
+ (* Should we use set_typeset ? *)
+ r := TypeSet.fold (fun ty -> TypeSet.add (repr ty)) !r TypeSet.empty;
+ if TypeSet.mem t !r then Some lv else find_instance rem
+ in find_instance env.gadt_instances
+
+let add_gadt_instances env lv tl =
+ let r =
+ try List.assoc lv env.gadt_instances with Not_found -> assert false in
+ (* Format.eprintf "Added";
+ List.iter (fun ty -> Format.eprintf "@ %a" !Btype.print_raw ty) tl;
+ Format.eprintf "@."; *)
+ set_typeset r (List.fold_right TypeSet.add tl !r)
+
+(* Only use this after expand_head! *)
+let add_gadt_instance_chain env lv t =
+ let r =
+ try List.assoc lv env.gadt_instances with Not_found -> assert false in
+ let rec add_instance t =
+ let t = repr t in
+ if not (TypeSet.mem t !r) then begin
+ (* Format.eprintf "@ %a" !Btype.print_raw t; *)
+ set_typeset r (TypeSet.add t !r);
+ match t.desc with
+ Tconstr (p, _, memo) ->
+ may add_instance (find_expans Private p !memo)
+ | _ -> ()
+ end
+ in
+ (* Format.eprintf "Added chain"; *)
+ add_instance t
+ (* Format.eprintf "@." *)
+
+(* Expand manifest module type names at the top of the given module type *)
+
+let rec scrape_alias env ?path mty =
+ match mty, path with
+ Mty_ident p, _ ->
+ begin try
+ scrape_alias env (find_modtype_expansion p env) ?path
+ with Not_found ->
+ mty
+ end
+ | Mty_alias path, _ ->
+ begin try
+ scrape_alias env (find_module path env).md_type ~path
+ with Not_found ->
+ (*Location.prerr_warning Location.none
+ (Warnings.No_cmi_file (Path.name path));*)
+ mty
+ end
+ | mty, Some path ->
+ !strengthen env mty path
+ | _ -> mty
+
+let scrape_alias env mty = scrape_alias env mty
+
+(* Given a signature and a root path, prefix all idents in the signature
+ by the root path and build the corresponding substitution. *)
+
+let rec prefix_idents root pos sub = function
+ [] -> ([], sub)
+ | Sig_value(id, decl) :: rem ->
+ let p = Pdot(root, Ident.name id, pos) in
+ let nextpos = match decl.val_kind with Val_prim _ -> pos | _ -> pos+1 in
+ let (pl, final_sub) = prefix_idents root nextpos sub rem in
+ (p::pl, final_sub)
+ | Sig_type(id, decl, _) :: rem ->
+ let p = Pdot(root, Ident.name id, nopos) in
+ let (pl, final_sub) =
+ prefix_idents root pos (Subst.add_type id p sub) rem in
+ (p::pl, final_sub)
+ | Sig_typext(id, ext, _) :: rem ->
+ let p = Pdot(root, Ident.name id, pos) in
+ (* we extend the substitution in case of an inlined record *)
+ let (pl, final_sub) =
+ prefix_idents root (pos+1) (Subst.add_type id p sub) rem in
+ (p::pl, final_sub)
+ | Sig_module(id, mty, _) :: rem ->
+ let p = Pdot(root, Ident.name id, pos) in
+ let (pl, final_sub) =
+ prefix_idents root (pos+1) (Subst.add_module id p sub) rem in
+ (p::pl, final_sub)
+ | Sig_modtype(id, decl) :: rem ->
+ let p = Pdot(root, Ident.name id, nopos) in
+ let (pl, final_sub) =
+ prefix_idents root pos
+ (Subst.add_modtype id (Mty_ident p) sub) rem in
+ (p::pl, final_sub)
+ | Sig_class(id, decl, _) :: rem ->
+ (* pretend this is a type, cf. PR#6650 *)
+ let p = Pdot(root, Ident.name id, pos) in
+ let (pl, final_sub) =
+ prefix_idents root (pos + 1) (Subst.add_type id p sub) rem in
+ (p::pl, final_sub)
+ | Sig_class_type(id, decl, _) :: rem ->
+ let p = Pdot(root, Ident.name id, nopos) in
+ let (pl, final_sub) =
+ prefix_idents root pos (Subst.add_type id p sub) rem in
+ (p::pl, final_sub)
+
+let subst_signature sub sg =
+ List.map
+ (fun item ->
+ match item with
+ | Sig_value(id, decl) ->
+ Sig_value (id, Subst.value_description sub decl)
+ | Sig_type(id, decl, x) ->
+ Sig_type(id, Subst.type_declaration sub decl, x)
+ | Sig_typext(id, ext, es) ->
+ Sig_typext (id, Subst.extension_constructor sub ext, es)
+ | Sig_module(id, mty, x) ->
+ Sig_module(id, Subst.module_declaration sub mty,x)
+ | Sig_modtype(id, decl) ->
+ Sig_modtype(id, Subst.modtype_declaration sub decl)
+ | Sig_class(id, decl, x) ->
+ Sig_class(id, Subst.class_declaration sub decl, x)
+ | Sig_class_type(id, decl, x) ->
+ Sig_class_type(id, Subst.cltype_declaration sub decl, x)
+ )
+ sg
+
+
+let prefix_idents_and_subst root sub sg =
+ let (pl, sub) = prefix_idents root 0 sub sg in
+ pl, sub, lazy (subst_signature sub sg)
+
+let prefix_idents_and_subst root sub sg =
+ if sub = Subst.identity then
+ let sgs =
+ try
+ Hashtbl.find prefixed_sg root
+ with Not_found ->
+ let sgs = ref [] in
+ Hashtbl.add prefixed_sg root sgs;
+ sgs
+ in
+ try
+ List.assq sg !sgs
+ with Not_found ->
+ let r = prefix_idents_and_subst root sub sg in
+ sgs := (sg, r) :: !sgs;
+ r
+ else
+ prefix_idents_and_subst root sub sg
+
+(* Compute structure descriptions *)
+
+let add_to_tbl id decl tbl =
+ let decls =
+ try Tbl.find id tbl with Not_found -> [] in
+ Tbl.add id (decl :: decls) tbl
+
+let rec components_of_module env sub path mty =
+ EnvLazy.create (env, sub, path, mty)
+
+and components_of_module_maker (env, sub, path, mty) =
+ (match scrape_alias env mty with
+ Mty_signature sg ->
+ let c =
+ { comp_values = Tbl.empty;
+ comp_constrs = Tbl.empty;
+ comp_labels = Tbl.empty; comp_types = Tbl.empty;
+ comp_modules = Tbl.empty; comp_modtypes = Tbl.empty;
+ comp_components = Tbl.empty; comp_classes = Tbl.empty;
+ comp_cltypes = Tbl.empty } in
+ let pl, sub, _ = prefix_idents_and_subst path sub sg in
+ let env = ref env in
+ let pos = ref 0 in
+ List.iter2 (fun item path ->
+ match item with
+ Sig_value(id, decl) ->
+ let decl' = Subst.value_description sub decl in
+ c.comp_values <-
+ Tbl.add (Ident.name id) (decl', !pos) c.comp_values;
+ begin match decl.val_kind with
+ Val_prim _ -> () | _ -> incr pos
+ end
+ | Sig_type(id, decl, _) ->
+ let decl' = Subst.type_declaration sub decl in
+ let constructors =
+ List.map snd (Datarepr.constructors_of_type path decl') in
+ let labels =
+ List.map snd (Datarepr.labels_of_type path decl') in
+ c.comp_types <-
+ Tbl.add (Ident.name id)
+ ((decl', (constructors, labels)), nopos)
+ c.comp_types;
+ List.iter
+ (fun descr ->
+ c.comp_constrs <-
+ add_to_tbl descr.cstr_name (descr, nopos) c.comp_constrs)
+ constructors;
+ List.iter
+ (fun descr ->
+ c.comp_labels <-
+ add_to_tbl descr.lbl_name (descr, nopos) c.comp_labels)
+ labels;
+ env := store_type_infos None id (Pident id) decl !env !env
+ | Sig_typext(id, ext, _) ->
+ let ext' = Subst.extension_constructor sub ext in
+ let descr = Datarepr.extension_descr path ext' in
+ c.comp_constrs <-
+ add_to_tbl (Ident.name id) (descr, !pos) c.comp_constrs;
+ incr pos
+ | Sig_module(id, md, _) ->
+ let mty = md.md_type in
+ let mty' = EnvLazy.create (sub, mty) in
+ c.comp_modules <-
+ Tbl.add (Ident.name id) (mty', !pos) c.comp_modules;
+ let comps = components_of_module !env sub path mty in
+ c.comp_components <-
+ Tbl.add (Ident.name id) (comps, !pos) c.comp_components;
+ env := store_module None id (Pident id) md !env !env;
+ incr pos
+ | Sig_modtype(id, decl) ->
+ let decl' = Subst.modtype_declaration sub decl in
+ c.comp_modtypes <-
+ Tbl.add (Ident.name id) (decl', nopos) c.comp_modtypes;
+ env := store_modtype None id (Pident id) decl !env !env
+ | Sig_class(id, decl, _) ->
+ let decl' = Subst.class_declaration sub decl in
+ c.comp_classes <-
+ Tbl.add (Ident.name id) (decl', !pos) c.comp_classes;
+ incr pos
+ | Sig_class_type(id, decl, _) ->
+ let decl' = Subst.cltype_declaration sub decl in
+ c.comp_cltypes <-
+ Tbl.add (Ident.name id) (decl', !pos) c.comp_cltypes)
+ sg pl;
+ Structure_comps c
+ | Mty_functor(param, ty_arg, ty_res) ->
+ Functor_comps {
+ fcomp_param = param;
+ (* fcomp_arg and fcomp_res must be prefixed eagerly, because
+ they are interpreted in the outer environment *)
+ fcomp_arg = may_map (Subst.modtype sub) ty_arg;
+ fcomp_res = Subst.modtype sub ty_res;
+ fcomp_cache = Hashtbl.create 17;
+ fcomp_subst_cache = Hashtbl.create 17 }
+ | Mty_ident _
+ | Mty_alias _ ->
+ Structure_comps {
+ comp_values = Tbl.empty;
+ comp_constrs = Tbl.empty;
+ comp_labels = Tbl.empty;
+ comp_types = Tbl.empty;
+ comp_modules = Tbl.empty; comp_modtypes = Tbl.empty;
+ comp_components = Tbl.empty; comp_classes = Tbl.empty;
+ comp_cltypes = Tbl.empty })
+
+(* Insertion of bindings by identifier + path *)
+
+and check_usage loc id warn tbl =
+ if not loc.Location.loc_ghost && Warnings.is_active (warn "") then begin
+ let name = Ident.name id in
+ let key = (name, loc) in
+ if Hashtbl.mem tbl key then ()
+ else let used = ref false in
+ Hashtbl.add tbl key (fun () -> used := true);
+ if not (name = "" || name.[0] = '_' || name.[0] = '#')
+ then
+ !add_delayed_check_forward
+ (fun () -> if not !used then Location.prerr_warning loc (warn name))
+ end;
+
+and check_value_name name loc =
+ (* Note: we could also check here general validity of the
+ identifier, to protect against bad identifiers forged by -pp or
+ -ppx preprocessors. *)
+
+ if String.length name > 0 && (name.[0] = '#') then
+ for i = 1 to String.length name - 1 do
+ if name.[i] = '#' then
+ raise (Error(Illegal_value_name(loc, name)))
+ done
+
+
+and store_value ?check slot id path decl env renv =
+ check_value_name (Ident.name id) decl.val_loc;
+ may (fun f -> check_usage decl.val_loc id f value_declarations) check;
+ { env with
+ values = EnvTbl.add "value" slot id (path, decl) env.values renv.values;
+ summary = Env_value(env.summary, id, decl) }
+
+and store_type ~check slot id path info env renv =
+ let loc = info.type_loc in
+ if check then
+ check_usage loc id (fun s -> Warnings.Unused_type_declaration s)
+ type_declarations;
+ let constructors = Datarepr.constructors_of_type path info in
+ let labels = Datarepr.labels_of_type path info in
+ let descrs = (List.map snd constructors, List.map snd labels) in
+
+ if check && not loc.Location.loc_ghost &&
+ Warnings.is_active (Warnings.Unused_constructor ("", false, false))
+ then begin
+ let ty = Ident.name id in
+ List.iter
+ begin fun (_, {cstr_name = c; _}) ->
+ let k = (ty, loc, c) in
+ if not (Hashtbl.mem used_constructors k) then
+ let used = constructor_usages () in
+ Hashtbl.add used_constructors k (add_constructor_usage used);
+ if not (ty = "" || ty.[0] = '_')
+ then !add_delayed_check_forward
+ (fun () ->
+ if not (is_in_signature env) && not used.cu_positive then
+ Location.prerr_warning loc
+ (Warnings.Unused_constructor
+ (c, used.cu_pattern, used.cu_privatize)))
+ end
+ constructors
+ end;
+ { env with
+ constrs =
+ List.fold_right
+ (fun (id, descr) constrs ->
+ EnvTbl.add "constructor" slot id descr constrs renv.constrs)
+ constructors
+ env.constrs;
+ labels =
+ List.fold_right
+ (fun (id, descr) labels ->
+ EnvTbl.add "label" slot id descr labels renv.labels)
+ labels
+ env.labels;
+ types = EnvTbl.add "type" slot id (path, (info, descrs)) env.types
+ renv.types;
+ summary = Env_type(env.summary, id, info) }
+
+and store_type_infos slot id path info env renv =
+ (* Simplified version of store_type that doesn't compute and store
+ constructor and label infos, but simply record the arity and
+ manifest-ness of the type. Used in components_of_module to
+ keep track of type abbreviations (e.g. type t = float) in the
+ computation of label representations. *)
+ { env with
+ types = EnvTbl.add "type" slot id (path, (info,([],[]))) env.types
+ renv.types;
+ summary = Env_type(env.summary, id, info) }
+
+and store_extension ~check slot id path ext env renv =
+ let loc = ext.ext_loc in
+ if check && not loc.Location.loc_ghost &&
+ Warnings.is_active (Warnings.Unused_extension ("", false, false))
+ then begin
+ let ty = Path.last ext.ext_type_path in
+ let n = Ident.name id in
+ let k = (ty, loc, n) in
+ if not (Hashtbl.mem used_constructors k) then begin
+ let used = constructor_usages () in
+ Hashtbl.add used_constructors k (add_constructor_usage used);
+ !add_delayed_check_forward
+ (fun () ->
+ if not (is_in_signature env) && not used.cu_positive then
+ Location.prerr_warning loc
+ (Warnings.Unused_extension
+ (n, used.cu_pattern, used.cu_privatize)
+ )
+ )
+ end;
+ end;
+ { env with
+ constrs = EnvTbl.add "constructor" slot id
+ (Datarepr.extension_descr path ext)
+ env.constrs renv.constrs;
+ summary = Env_extension(env.summary, id, ext) }
+
+and store_module slot id path md env renv =
+ { env with
+ modules = EnvTbl.add "module" slot id (path, md) env.modules renv.modules;
+ components =
+ EnvTbl.add "module" slot id
+ (path, components_of_module env Subst.identity path md.md_type)
+ env.components renv.components;
+ summary = Env_module(env.summary, id, md) }
+
+and store_modtype slot id path info env renv =
+ { env with
+ modtypes = EnvTbl.add "module type" slot id (path, info) env.modtypes
+ renv.modtypes;
+ summary = Env_modtype(env.summary, id, info) }
+
+and store_class slot id path desc env renv =
+ { env with
+ classes = EnvTbl.add "class" slot id (path, desc) env.classes renv.classes;
+ summary = Env_class(env.summary, id, desc) }
+
+and store_cltype slot id path desc env renv =
+ { env with
+ cltypes = EnvTbl.add "class type" slot id (path, desc) env.cltypes
+ renv.cltypes;
+ summary = Env_cltype(env.summary, id, desc) }
+
+(* Compute the components of a functor application in a path. *)
+
+let components_of_functor_appl f env p1 p2 =
+ try
+ Hashtbl.find f.fcomp_cache p2
+ with Not_found ->
+ let p = Papply(p1, p2) in
+ let sub = Subst.add_module f.fcomp_param p2 Subst.identity in
+ let mty = Subst.modtype sub f.fcomp_res in
+ let comps = components_of_module env Subst.identity p mty in
+ Hashtbl.add f.fcomp_cache p2 comps;
+ comps
+
+(* Define forward functions *)
+
+let _ =
+ components_of_module' := components_of_module;
+ components_of_functor_appl' := components_of_functor_appl;
+ components_of_module_maker' := components_of_module_maker
+
+(* Insertion of bindings by identifier *)
+
+let add_functor_arg id env =
+ {env with
+ functor_args = Ident.add id () env.functor_args;
+ summary = Env_functor_arg (env.summary, id)}
+
+let add_value ?check id desc env =
+ store_value None ?check id (Pident id) desc env env
+
+let add_type ~check id info env =
+ store_type ~check None id (Pident id) info env env
+
+and add_extension ~check id ext env =
+ store_extension ~check None id (Pident id) ext env env
+
+and add_module_declaration ?(arg=false) id md env =
+ let path =
+ (*match md.md_type with
+ Mty_alias path -> normalize_path env path
+ | _ ->*) Pident id
+ in
+ let env = store_module None id path md env env in
+ if arg then add_functor_arg id env else env
+
+and add_modtype id info env =
+ store_modtype None id (Pident id) info env env
+
+and add_class id ty env =
+ store_class None id (Pident id) ty env env
+
+and add_cltype id ty env =
+ store_cltype None id (Pident id) ty env env
+
+let add_module ?arg id mty env =
+ add_module_declaration ?arg id (md mty) env
+
+let add_local_constraint id info elv env =
+ match info with
+ {type_manifest = Some ty; type_newtype_level = Some (lv, _)} ->
+ (* elv is the expansion level, lv is the definition level *)
+ let env =
+ add_type ~check:false
+ id {info with type_newtype_level = Some (lv, elv)} env in
+ { env with local_constraints = true }
+ | _ -> assert false
+
+(* Insertion of bindings by name *)
+
+let enter store_fun name data env =
+ let id = Ident.create name in (id, store_fun None id (Pident id) data env env)
+
+let enter_value ?check = enter (store_value ?check)
+and enter_type = enter (store_type ~check:true)
+and enter_extension = enter (store_extension ~check:true)
+and enter_module_declaration ?arg id md env =
+ add_module_declaration ?arg id md env
+ (* let (id, env) = enter store_module name md env in
+ (id, add_functor_arg ?arg id env) *)
+and enter_modtype = enter store_modtype
+and enter_class = enter store_class
+and enter_cltype = enter store_cltype
+
+let enter_module ?arg s mty env =
+ let id = Ident.create s in
+ (id, enter_module_declaration ?arg id (md mty) env)
+
+(* Insertion of all components of a signature *)
+
+let add_item comp env =
+ match comp with
+ Sig_value(id, decl) -> add_value id decl env
+ | Sig_type(id, decl, _) -> add_type ~check:false id decl env
+ | Sig_typext(id, ext, _) -> add_extension ~check:false id ext env
+ | Sig_module(id, md, _) -> add_module_declaration id md env
+ | Sig_modtype(id, decl) -> add_modtype id decl env
+ | Sig_class(id, decl, _) -> add_class id decl env
+ | Sig_class_type(id, decl, _) -> add_cltype id decl env
+
+let rec add_signature sg env =
+ match sg with
+ [] -> env
+ | comp :: rem -> add_signature rem (add_item comp env)
+
+(* Open a signature path *)
+
+let open_signature slot root sg env0 =
+ (* First build the paths and substitution *)
+ let (pl, sub, sg) = prefix_idents_and_subst root Subst.identity sg in
+ let sg = Lazy.force sg in
+
+ (* Then enter the components in the environment after substitution *)
+
+ let newenv =
+ List.fold_left2
+ (fun env item p ->
+ match item with
+ Sig_value(id, decl) ->
+ store_value slot (Ident.hide id) p decl env env0
+ | Sig_type(id, decl, _) ->
+ store_type ~check:false slot (Ident.hide id) p decl env env0
+ | Sig_typext(id, ext, _) ->
+ store_extension ~check:false slot (Ident.hide id) p ext env env0
+ | Sig_module(id, mty, _) ->
+ store_module slot (Ident.hide id) p mty env env0
+ | Sig_modtype(id, decl) ->
+ store_modtype slot (Ident.hide id) p decl env env0
+ | Sig_class(id, decl, _) ->
+ store_class slot (Ident.hide id) p decl env env0
+ | Sig_class_type(id, decl, _) ->
+ store_cltype slot (Ident.hide id) p decl env env0
+ )
+ env0 sg pl in
+ { newenv with summary = Env_open(env0.summary, root) }
+
+(* Open a signature from a file *)
+
+let open_pers_signature name env =
+ let ps = find_pers_struct name in
+ open_signature None (Pident(Ident.create_persistent name))
+ (Lazy.force ps.ps_sig) env
+
+let open_signature ?(loc = Location.none) ?(toplevel = false) ovf root sg env =
+ if not toplevel && ovf = Asttypes.Fresh && not loc.Location.loc_ghost
+ && (Warnings.is_active (Warnings.Unused_open "")
+ || Warnings.is_active (Warnings.Open_shadow_identifier ("", ""))
+ || Warnings.is_active (Warnings.Open_shadow_label_constructor ("","")))
+ then begin
+ let used = ref false in
+ !add_delayed_check_forward
+ (fun () ->
+ if not !used then
+ Location.prerr_warning loc (Warnings.Unused_open (Path.name root))
+ );
+ let shadowed = ref [] in
+ let slot kind s b =
+ if b && not (List.mem (kind, s) !shadowed) then begin
+ shadowed := (kind, s) :: !shadowed;
+ let w =
+ match kind with
+ | "label" | "constructor" ->
+ Warnings.Open_shadow_label_constructor (kind, s)
+ | _ -> Warnings.Open_shadow_identifier (kind, s)
+ in
+ Location.prerr_warning loc w
+ end;
+ used := true
+ in
+ open_signature (Some slot) root sg env
+ end
+ else open_signature None root sg env
+
+(* Read a signature from a file *)
+
+let read_signature modname filename =
+ let ps = read_pers_struct modname filename in
+ check_consistency ps;
+ Lazy.force ps.ps_sig
+
+(* Return the CRC of the interface of the given compilation unit *)
+
+let crc_of_unit name =
+ let ps = find_pers_struct name in
+ let crco =
+ try
+ List.assoc name ps.ps_crcs
+ with Not_found ->
+ assert false
+ in
+ match crco with
+ None -> assert false
+ | Some crc -> crc
+
+(* Return the list of imported interfaces with their CRCs *)
+
+let imports() =
+ Consistbl.extract (StringSet.elements !imported_units) crc_units
+
+(* Save a signature to a file *)
+
+let save_signature_with_imports sg modname filename imports =
+ (*prerr_endline filename;
+ List.iter (fun (name, crc) -> prerr_endline name) imports;*)
+ Btype.cleanup_abbrev ();
+ Subst.reset_for_saving ();
+ let sg = Subst.signature (Subst.for_saving Subst.identity) sg in
+ let oc = open_out_bin filename in
+ try
+ let cmi = {
+ cmi_name = modname;
+ cmi_sign = sg;
+ cmi_crcs = imports;
+ cmi_flags = if !Clflags.recursive_types then [Rectypes] else [];
+ } in
+ let crc = output_cmi filename oc cmi in
+ close_out oc;
+ (* Enter signature in persistent table so that imported_unit()
+ will also return its crc *)
+ let comps =
+ components_of_module empty Subst.identity
+ (Pident(Ident.create_persistent modname)) (Mty_signature sg) in
+ let ps =
+ { ps_name = modname;
+ ps_sig = lazy (Subst.signature Subst.identity sg);
+ ps_comps = comps;
+ ps_crcs = (cmi.cmi_name, Some crc) :: imports;
+ ps_filename = filename;
+ ps_flags = cmi.cmi_flags;
+ ps_crcs_checked = false;
+ } in
+ save_pers_struct crc ps;
+ sg
+ with exn ->
+ close_out oc;
+ remove_file filename;
+ raise exn
+
+let save_signature sg modname filename =
+ save_signature_with_imports sg modname filename (imports())
+
+(* Folding on environments *)
+
+let find_all proj1 proj2 f lid env acc =
+ match lid with
+ | None ->
+ EnvTbl.fold_name
+ (fun id (p, data) acc -> f (Ident.name id) p data acc)
+ (proj1 env) acc
+ | Some l ->
+ let p, desc = lookup_module_descr l env in
+ begin match EnvLazy.force components_of_module_maker desc with
+ Structure_comps c ->
+ Tbl.fold
+ (fun s (data, pos) acc -> f s (Pdot (p, s, pos)) data acc)
+ (proj2 c) acc
+ | Functor_comps _ ->
+ acc
+ end
+
+let find_all_simple_list proj1 proj2 f lid env acc =
+ match lid with
+ | None ->
+ EnvTbl.fold_name
+ (fun id data acc -> f data acc)
+ (proj1 env) acc
+ | Some l ->
+ let p, desc = lookup_module_descr l env in
+ begin match EnvLazy.force components_of_module_maker desc with
+ Structure_comps c ->
+ Tbl.fold
+ (fun s comps acc ->
+ match comps with
+ [] -> acc
+ | (data, pos) :: _ ->
+ f data acc)
+ (proj2 c) acc
+ | Functor_comps _ ->
+ acc
+ end
+
+let fold_modules f lid env acc =
+ match lid with
+ | None ->
+ let acc =
+ EnvTbl.fold_name
+ (fun id (p, data) acc -> f (Ident.name id) p data acc)
+ env.modules
+ acc
+ in
+ Hashtbl.fold
+ (fun name ps acc ->
+ match ps with
+ None -> acc
+ | Some ps ->
+ f name (Pident(Ident.create_persistent name))
+ (md (Mty_signature (Lazy.force ps.ps_sig))) acc)
+ persistent_structures
+ acc
+ | Some l ->
+ let p, desc = lookup_module_descr l env in
+ begin match EnvLazy.force components_of_module_maker desc with
+ Structure_comps c ->
+ Tbl.fold
+ (fun s (data, pos) acc ->
+ f s (Pdot (p, s, pos))
+ (md (EnvLazy.force subst_modtype_maker data)) acc)
+ c.comp_modules
+ acc
+ | Functor_comps _ ->
+ acc
+ end
+
+let fold_values f =
+ find_all (fun env -> env.values) (fun sc -> sc.comp_values) f
+and fold_constructors f =
+ find_all_simple_list (fun env -> env.constrs) (fun sc -> sc.comp_constrs) f
+and fold_labels f =
+ find_all_simple_list (fun env -> env.labels) (fun sc -> sc.comp_labels) f
+and fold_types f =
+ find_all (fun env -> env.types) (fun sc -> sc.comp_types) f
+and fold_modtypes f =
+ find_all (fun env -> env.modtypes) (fun sc -> sc.comp_modtypes) f
+and fold_classs f =
+ find_all (fun env -> env.classes) (fun sc -> sc.comp_classes) f
+and fold_cltypes f =
+ find_all (fun env -> env.cltypes) (fun sc -> sc.comp_cltypes) f
+
+
+(* Make the initial environment *)
+let (initial_safe_string, initial_unsafe_string) =
+ Predef.build_initial_env
+ (add_type ~check:false)
+ (add_extension ~check:false)
+ empty
+
+(* Return the environment summary *)
+
+let summary env = env.summary
+
+let last_env = ref empty
+let last_reduced_env = ref empty
+
+let keep_only_summary env =
+ if !last_env == env then !last_reduced_env
+ else begin
+ let new_env =
+ {
+ empty with
+ summary = env.summary;
+ local_constraints = env.local_constraints;
+ flags = env.flags;
+ }
+ in
+ last_env := env;
+ last_reduced_env := new_env;
+ new_env
+ end
+
+
+let env_of_only_summary env_from_summary env =
+ let new_env = env_from_summary env.summary Subst.identity in
+ { new_env with
+ local_constraints = env.local_constraints;
+ flags = env.flags;
+ }
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Illegal_renaming(modname, ps_name, filename) -> fprintf ppf
+ "Wrong file naming: %a@ contains the compiled interface for @ \
+ %s when %s was expected"
+ Location.print_filename filename ps_name modname
+ | Inconsistent_import(name, source1, source2) -> fprintf ppf
+ "@[<hov>The files %a@ and %a@ \
+ make inconsistent assumptions@ over interface %s@]"
+ Location.print_filename source1 Location.print_filename source2 name
+ | Need_recursive_types(import, export) ->
+ fprintf ppf
+ "@[<hov>Unit %s imports from %s, which uses recursive types.@ %s@]"
+ export import "The compilation flag -rectypes is required"
+ | Missing_module(_, path1, path2) ->
+ fprintf ppf "@[@[<hov>";
+ if Path.same path1 path2 then
+ fprintf ppf "Internal path@ %s@ is dangling." (Path.name path1)
+ else
+ fprintf ppf "Internal path@ %s@ expands to@ %s@ which is dangling."
+ (Path.name path1) (Path.name path2);
+ fprintf ppf "@]@ @[%s@ %s@ %s.@]@]"
+ "The compiled interface for module" (Ident.name (Path.head path2))
+ "was not found"
+ | Illegal_value_name(_loc, name) ->
+ fprintf ppf "'%s' is not a valid value identifier."
+ name
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (Missing_module (loc, _, _)
+ | Illegal_value_name (loc, _)
+ as err) when loc <> Location.none ->
+ Some (Location.error_of_printer loc report_error err)
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
diff --git a/typing/env.mli b/typing/env.mli
new file mode 100644
index 0000000000..367299aa69
--- /dev/null
+++ b/typing/env.mli
@@ -0,0 +1,267 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Environment handling *)
+
+open Types
+
+type summary =
+ Env_empty
+ | Env_value of summary * Ident.t * value_description
+ | Env_type of summary * Ident.t * type_declaration
+ | Env_extension of summary * Ident.t * extension_constructor
+ | Env_module of summary * Ident.t * module_declaration
+ | Env_modtype of summary * Ident.t * modtype_declaration
+ | Env_class of summary * Ident.t * class_declaration
+ | Env_cltype of summary * Ident.t * class_type_declaration
+ | Env_open of summary * Path.t
+ | Env_functor_arg of summary * Ident.t
+
+type t
+
+val empty: t
+val initial_safe_string: t
+val initial_unsafe_string: t
+val diff: t -> t -> Ident.t list
+
+type type_descriptions =
+ constructor_description list * label_description list
+
+(* For short-paths *)
+type iter_cont
+val iter_types:
+ (Path.t -> Path.t * (type_declaration * type_descriptions) -> unit) ->
+ t -> iter_cont
+val run_iter_cont: iter_cont list -> (Path.t * iter_cont) list
+val same_types: t -> t -> bool
+val used_persistent: unit -> Concr.t
+val find_shadowed_types: Path.t -> t -> Path.t list
+
+(* Lookup by paths *)
+
+val find_value: Path.t -> t -> value_description
+val find_type: Path.t -> t -> type_declaration
+val find_type_descrs: Path.t -> t -> type_descriptions
+val find_module: Path.t -> t -> module_declaration
+val find_modtype: Path.t -> t -> modtype_declaration
+val find_class: Path.t -> t -> class_declaration
+val find_cltype: Path.t -> t -> class_type_declaration
+
+val find_type_expansion:
+ Path.t -> t -> type_expr list * type_expr * int option
+val find_type_expansion_opt:
+ Path.t -> t -> type_expr list * type_expr * int option
+(* Find the manifest type information associated to a type for the sake
+ of the compiler's type-based optimisations. *)
+val find_modtype_expansion: Path.t -> t -> module_type
+val add_functor_arg: Ident.t -> t -> t
+val is_functor_arg: Path.t -> t -> bool
+val normalize_path: Location.t option -> t -> Path.t -> Path.t
+(* Normalize the path to a concrete value or module.
+ If the option is None, allow returning dangling paths.
+ Otherwise raise a Missing_module error, and may add forgotten
+ head as required global. *)
+val reset_required_globals: unit -> unit
+val get_required_globals: unit -> Ident.t list
+val add_required_global: Ident.t -> unit
+
+val has_local_constraints: t -> bool
+val add_gadt_instance_level: int -> t -> t
+val gadt_instance_level: t -> type_expr -> int option
+val add_gadt_instances: t -> int -> type_expr list -> unit
+val add_gadt_instance_chain: t -> int -> type_expr -> unit
+
+(* Lookup by long identifiers *)
+
+val lookup_value: Longident.t -> t -> Path.t * value_description
+val lookup_constructor: Longident.t -> t -> constructor_description
+val lookup_all_constructors:
+ Longident.t -> t -> (constructor_description * (unit -> unit)) list
+val lookup_label: Longident.t -> t -> label_description
+val lookup_all_labels:
+ Longident.t -> t -> (label_description * (unit -> unit)) list
+val lookup_type: Longident.t -> t -> Path.t * type_declaration
+val lookup_module: load:bool -> Longident.t -> t -> Path.t
+val lookup_modtype: Longident.t -> t -> Path.t * modtype_declaration
+val lookup_class: Longident.t -> t -> Path.t * class_declaration
+val lookup_cltype: Longident.t -> t -> Path.t * class_type_declaration
+
+exception Recmodule
+ (* Raise by lookup_module when the identifier refers
+ to one of the modules of a recursive definition
+ during the computation of its approximation (see #5965). *)
+
+(* Insertion by identifier *)
+
+val add_value:
+ ?check:(string -> Warnings.t) -> Ident.t -> value_description -> t -> t
+val add_type: check:bool -> Ident.t -> type_declaration -> t -> t
+val add_extension: check:bool -> Ident.t -> extension_constructor -> t -> t
+val add_module: ?arg:bool -> Ident.t -> module_type -> t -> t
+val add_module_declaration: ?arg:bool -> Ident.t -> module_declaration -> t -> t
+val add_modtype: Ident.t -> modtype_declaration -> t -> t
+val add_class: Ident.t -> class_declaration -> t -> t
+val add_cltype: Ident.t -> class_type_declaration -> t -> t
+val add_local_constraint: Ident.t -> type_declaration -> int -> t -> t
+
+(* Insertion of all fields of a signature. *)
+
+val add_item: signature_item -> t -> t
+val add_signature: signature -> t -> t
+
+(* Insertion of all fields of a signature, relative to the given path.
+ Used to implement open. *)
+
+val open_signature:
+ ?loc:Location.t -> ?toplevel:bool -> Asttypes.override_flag -> Path.t ->
+ signature -> t -> t
+val open_pers_signature: string -> t -> t
+
+(* Insertion by name *)
+
+val enter_value:
+ ?check:(string -> Warnings.t) ->
+ string -> value_description -> t -> Ident.t * t
+val enter_type: string -> type_declaration -> t -> Ident.t * t
+val enter_extension: string -> extension_constructor -> t -> Ident.t * t
+val enter_module: ?arg:bool -> string -> module_type -> t -> Ident.t * t
+val enter_module_declaration:
+ ?arg:bool -> Ident.t -> module_declaration -> t -> t
+val enter_modtype: string -> modtype_declaration -> t -> Ident.t * t
+val enter_class: string -> class_declaration -> t -> Ident.t * t
+val enter_cltype: string -> class_type_declaration -> t -> Ident.t * t
+
+(* Initialize the cache of in-core module interfaces. *)
+val reset_cache: unit -> unit
+
+(* To be called before each toplevel phrase. *)
+val reset_cache_toplevel: unit -> unit
+
+(* Remember the name of the current compilation unit. *)
+val set_unit_name: string -> unit
+val get_unit_name: unit -> string
+
+(* Read, save a signature to/from a file *)
+
+val read_signature: string -> string -> signature
+ (* Arguments: module name, file name. Results: signature. *)
+val save_signature: signature -> string -> string -> signature
+ (* Arguments: signature, module name, file name. *)
+val save_signature_with_imports:
+ signature -> string -> string -> (string * Digest.t option) list
+ -> signature
+ (* Arguments: signature, module name, file name,
+ imported units with their CRCs. *)
+
+(* Return the CRC of the interface of the given compilation unit *)
+
+val crc_of_unit: string -> Digest.t
+
+(* Return the set of compilation units imported, with their CRC *)
+
+val imports: unit -> (string * Digest.t option) list
+
+(* Direct access to the table of imported compilation units with their CRC *)
+
+val crc_units: Consistbl.t
+val add_import: string -> unit
+
+(* Summaries -- compact representation of an environment, to be
+ exported in debugging information. *)
+
+val summary: t -> summary
+
+(* Return an equivalent environment where all fields have been reset,
+ except the summary. The initial environment can be rebuilt from the
+ summary, using Envaux.env_of_only_summary. *)
+
+val keep_only_summary : t -> t
+val env_of_only_summary : (summary -> Subst.t -> t) -> t -> t
+
+(* Error report *)
+
+type error =
+ | Illegal_renaming of string * string * string
+ | Inconsistent_import of string * string * string
+ | Need_recursive_types of string * string
+ | Missing_module of Location.t * Path.t * Path.t
+ | Illegal_value_name of Location.t * string
+
+exception Error of error
+
+open Format
+
+val report_error: formatter -> error -> unit
+
+
+val mark_value_used: t -> string -> value_description -> unit
+val mark_type_used: t -> string -> type_declaration -> unit
+
+type constructor_usage = Positive | Pattern | Privatize
+val mark_constructor_used:
+ constructor_usage -> t -> string -> type_declaration -> string -> unit
+val mark_constructor:
+ constructor_usage -> t -> string -> constructor_description -> unit
+val mark_extension_used:
+ constructor_usage -> t -> extension_constructor -> string -> unit
+
+val in_signature: bool -> t -> t
+val implicit_coercion: t -> t
+
+val is_in_signature: t -> bool
+
+val set_value_used_callback:
+ string -> value_description -> (unit -> unit) -> unit
+val set_type_used_callback:
+ string -> type_declaration -> ((unit -> unit) -> unit) -> unit
+
+(* Forward declaration to break mutual recursion with Includemod. *)
+val check_modtype_inclusion:
+ (t -> module_type -> Path.t -> module_type -> unit) ref
+(* Forward declaration to break mutual recursion with Typecore. *)
+val add_delayed_check_forward: ((unit -> unit) -> unit) ref
+(* Forward declaration to break mutual recursion with Mtype. *)
+val strengthen: (t -> module_type -> Path.t -> module_type) ref
+
+(** Folding over all identifiers (for analysis purpose) *)
+
+val fold_values:
+ (string -> Path.t -> value_description -> 'a -> 'a) ->
+ Longident.t option -> t -> 'a -> 'a
+val fold_types:
+ (string -> Path.t -> type_declaration * type_descriptions -> 'a -> 'a) ->
+ Longident.t option -> t -> 'a -> 'a
+val fold_constructors:
+ (constructor_description -> 'a -> 'a) ->
+ Longident.t option -> t -> 'a -> 'a
+val fold_labels:
+ (label_description -> 'a -> 'a) ->
+ Longident.t option -> t -> 'a -> 'a
+
+(** Persistent structures are only traversed if they are already loaded. *)
+val fold_modules:
+ (string -> Path.t -> module_declaration -> 'a -> 'a) ->
+ Longident.t option -> t -> 'a -> 'a
+
+val fold_modtypes:
+ (string -> Path.t -> modtype_declaration -> 'a -> 'a) ->
+ Longident.t option -> t -> 'a -> 'a
+val fold_classs:
+ (string -> Path.t -> class_declaration -> 'a -> 'a) ->
+ Longident.t option -> t -> 'a -> 'a
+val fold_cltypes:
+ (string -> Path.t -> class_type_declaration -> 'a -> 'a) ->
+ Longident.t option -> t -> 'a -> 'a
+
+(** Utilities *)
+val scrape_alias: t -> module_type -> module_type
+val check_value_name: string -> Location.t -> unit
diff --git a/typing/envaux.ml b/typing/envaux.ml
new file mode 100644
index 0000000000..708da443d2
--- /dev/null
+++ b/typing/envaux.ml
@@ -0,0 +1,95 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Misc
+open Types
+open Env
+
+type error =
+ Module_not_found of Path.t
+
+exception Error of error
+
+let env_cache =
+ (Hashtbl.create 59 : ((Env.summary * Subst.t), Env.t) Hashtbl.t)
+
+let reset_cache () =
+ Hashtbl.clear env_cache;
+ Env.reset_cache()
+
+let extract_sig env mty =
+ match Env.scrape_alias env mty with
+ Mty_signature sg -> sg
+ | _ -> fatal_error "Envaux.extract_sig"
+
+let rec env_from_summary sum subst =
+ try
+ Hashtbl.find env_cache (sum, subst)
+ with Not_found ->
+ let env =
+ match sum with
+ Env_empty ->
+ Env.empty
+ | Env_value(s, id, desc) ->
+ Env.add_value id (Subst.value_description subst desc)
+ (env_from_summary s subst)
+ | Env_type(s, id, desc) ->
+ Env.add_type ~check:false id
+ (Subst.type_declaration subst desc)
+ (env_from_summary s subst)
+ | Env_extension(s, id, desc) ->
+ Env.add_extension ~check:false id
+ (Subst.extension_constructor subst desc)
+ (env_from_summary s subst)
+ | Env_module(s, id, desc) ->
+ Env.add_module_declaration id
+ (Subst.module_declaration subst desc)
+ (env_from_summary s subst)
+ | Env_modtype(s, id, desc) ->
+ Env.add_modtype id (Subst.modtype_declaration subst desc)
+ (env_from_summary s subst)
+ | Env_class(s, id, desc) ->
+ Env.add_class id (Subst.class_declaration subst desc)
+ (env_from_summary s subst)
+ | Env_cltype (s, id, desc) ->
+ Env.add_cltype id (Subst.cltype_declaration subst desc)
+ (env_from_summary s subst)
+ | Env_open(s, path) ->
+ let env = env_from_summary s subst in
+ let path' = Subst.module_path subst path in
+ let md =
+ try
+ Env.find_module path' env
+ with Not_found ->
+ raise (Error (Module_not_found path'))
+ in
+ Env.open_signature Asttypes.Override path'
+ (extract_sig env md.md_type) env
+ | Env_functor_arg(Env_module(s, id, desc), id') when Ident.same id id' ->
+ Env.add_module_declaration id (Subst.module_declaration subst desc)
+ ~arg:true (env_from_summary s subst)
+ | Env_functor_arg _ -> assert false
+ in
+ Hashtbl.add env_cache (sum, subst) env;
+ env
+
+let env_of_only_summary env =
+ Env.env_of_only_summary env_from_summary env
+
+(* Error report *)
+
+open Format
+
+let report_error ppf = function
+ | Module_not_found p ->
+ fprintf ppf "@[Cannot find module %a@].@." Printtyp.path p
diff --git a/typing/envaux.mli b/typing/envaux.mli
new file mode 100644
index 0000000000..b893c1412a
--- /dev/null
+++ b/typing/envaux.mli
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* OCaml port by John Malecki and Xavier Leroy *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+(* Convert environment summaries to environments *)
+
+val env_from_summary : Env.summary -> Subst.t -> Env.t
+
+(* Empty the environment caches. To be called when load_path changes. *)
+
+val reset_cache: unit -> unit
+
+val env_of_only_summary : Env.t -> Env.t
+
+(* Error report *)
+
+type error =
+ Module_not_found of Path.t
+
+exception Error of error
+
+val report_error: formatter -> error -> unit
diff --git a/typing/ident.ml b/typing/ident.ml
new file mode 100644
index 0000000000..db4ea69912
--- /dev/null
+++ b/typing/ident.ml
@@ -0,0 +1,223 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+type t = { stamp: int; name: string; mutable flags: int }
+
+let global_flag = 1
+let predef_exn_flag = 2
+
+(* A stamp of 0 denotes a persistent identifier *)
+
+let currentstamp = ref 0
+
+let create s =
+ incr currentstamp;
+ { name = s; stamp = !currentstamp; flags = 0 }
+
+let create_predef_exn s =
+ incr currentstamp;
+ { name = s; stamp = !currentstamp; flags = predef_exn_flag }
+
+let create_persistent s =
+ { name = s; stamp = 0; flags = global_flag }
+
+let rename i =
+ incr currentstamp;
+ { i with stamp = !currentstamp }
+
+let name i = i.name
+
+let stamp i = i.stamp
+
+let unique_name i = i.name ^ "_" ^ string_of_int i.stamp
+
+let unique_toplevel_name i = i.name ^ "/" ^ string_of_int i.stamp
+
+let persistent i = (i.stamp = 0)
+
+let equal i1 i2 = i1.name = i2.name
+
+let same i1 i2 = i1 = i2
+ (* Possibly more efficient version (with a real compiler, at least):
+ if i1.stamp <> 0
+ then i1.stamp = i2.stamp
+ else i2.stamp = 0 && i1.name = i2.name *)
+
+let binding_time i = i.stamp
+
+let current_time() = !currentstamp
+let set_current_time t = currentstamp := max !currentstamp t
+
+let reinit_level = ref (-1)
+
+let reinit () =
+ if !reinit_level < 0
+ then reinit_level := !currentstamp
+ else currentstamp := !reinit_level
+
+let hide i =
+ { i with stamp = -1 }
+
+let make_global i =
+ i.flags <- i.flags lor global_flag
+
+let global i =
+ (i.flags land global_flag) <> 0
+
+let is_predef_exn i =
+ (i.flags land predef_exn_flag) <> 0
+
+let print ppf i =
+ match i.stamp with
+ | 0 -> fprintf ppf "%s!" i.name
+ | -1 -> fprintf ppf "%s#" i.name
+ | n -> fprintf ppf "%s/%i%s" i.name n (if global i then "g" else "")
+
+type 'a tbl =
+ Empty
+ | Node of 'a tbl * 'a data * 'a tbl * int
+
+and 'a data =
+ { ident: t;
+ data: 'a;
+ previous: 'a data option }
+
+let empty = Empty
+
+(* Inline expansion of height for better speed
+ * let height = function
+ * Empty -> 0
+ * | Node(_,_,_,h) -> h
+ *)
+
+let mknode l d r =
+ let hl = match l with Empty -> 0 | Node(_,_,_,h) -> h
+ and hr = match r with Empty -> 0 | Node(_,_,_,h) -> h in
+ Node(l, d, r, (if hl >= hr then hl + 1 else hr + 1))
+
+let balance l d r =
+ let hl = match l with Empty -> 0 | Node(_,_,_,h) -> h
+ and hr = match r with Empty -> 0 | Node(_,_,_,h) -> h in
+ if hl > hr + 1 then
+ match l with
+ | Node (ll, ld, lr, _)
+ when (match ll with Empty -> 0 | Node(_,_,_,h) -> h) >=
+ (match lr with Empty -> 0 | Node(_,_,_,h) -> h) ->
+ mknode ll ld (mknode lr d r)
+ | Node (ll, ld, Node(lrl, lrd, lrr, _), _) ->
+ mknode (mknode ll ld lrl) lrd (mknode lrr d r)
+ | _ -> assert false
+ else if hr > hl + 1 then
+ match r with
+ | Node (rl, rd, rr, _)
+ when (match rr with Empty -> 0 | Node(_,_,_,h) -> h) >=
+ (match rl with Empty -> 0 | Node(_,_,_,h) -> h) ->
+ mknode (mknode l d rl) rd rr
+ | Node (Node (rll, rld, rlr, _), rd, rr, _) ->
+ mknode (mknode l d rll) rld (mknode rlr rd rr)
+ | _ -> assert false
+ else
+ mknode l d r
+
+let rec add id data = function
+ Empty ->
+ Node(Empty, {ident = id; data = data; previous = None}, Empty, 1)
+ | Node(l, k, r, h) ->
+ let c = compare id.name k.ident.name in
+ if c = 0 then
+ Node(l, {ident = id; data = data; previous = Some k}, r, h)
+ else if c < 0 then
+ balance (add id data l) k r
+ else
+ balance l k (add id data r)
+
+let rec find_stamp s = function
+ None ->
+ raise Not_found
+ | Some k ->
+ if k.ident.stamp = s then k.data else find_stamp s k.previous
+
+let rec find_same id = function
+ Empty ->
+ raise Not_found
+ | Node(l, k, r, _) ->
+ let c = compare id.name k.ident.name in
+ if c = 0 then
+ if id.stamp = k.ident.stamp
+ then k.data
+ else find_stamp id.stamp k.previous
+ else
+ find_same id (if c < 0 then l else r)
+
+let rec find_name name = function
+ Empty ->
+ raise Not_found
+ | Node(l, k, r, _) ->
+ let c = compare name k.ident.name in
+ if c = 0 then
+ k.data
+ else
+ find_name name (if c < 0 then l else r)
+
+let rec get_all = function
+ | None -> []
+ | Some k -> k.data :: get_all k.previous
+
+let rec find_all name = function
+ Empty ->
+ []
+ | Node(l, k, r, _) ->
+ let c = compare name k.ident.name in
+ if c = 0 then
+ k.data :: get_all k.previous
+ else
+ find_all name (if c < 0 then l else r)
+
+let rec fold_aux f stack accu = function
+ Empty ->
+ begin match stack with
+ [] -> accu
+ | a :: l -> fold_aux f l accu a
+ end
+ | Node(l, k, r, _) ->
+ fold_aux f (l :: stack) (f k accu) r
+
+let fold_name f tbl accu = fold_aux (fun k -> f k.ident k.data) [] accu tbl
+
+let rec fold_data f d accu =
+ match d with
+ None -> accu
+ | Some k -> f k.ident k.data (fold_data f k.previous accu)
+
+let fold_all f tbl accu =
+ fold_aux (fun k -> fold_data f (Some k)) [] accu tbl
+
+(* let keys tbl = fold_name (fun k _ accu -> k::accu) tbl [] *)
+
+let rec iter f = function
+ Empty -> ()
+ | Node(l, k, r, _) ->
+ iter f l; f k.ident k.data; iter f r
+
+(* Idents for sharing keys *)
+
+(* They should be 'totally fresh' -> neg numbers *)
+let key_name = ""
+
+let make_key_generator () =
+ let c = ref 1 in
+ fun id ->
+ let stamp = !c in
+ decr c ;
+ { id with name = key_name; stamp = stamp; }
diff --git a/typing/ident.mli b/typing/ident.mli
new file mode 100644
index 0000000000..be226c2ddc
--- /dev/null
+++ b/typing/ident.mli
@@ -0,0 +1,65 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Identifiers (unique names) *)
+
+type t = { stamp: int; name: string; mutable flags: int }
+
+val create: string -> t
+val create_persistent: string -> t
+val create_predef_exn: string -> t
+val rename: t -> t
+val name: t -> string
+val unique_name: t -> string
+val unique_toplevel_name: t -> string
+val persistent: t -> bool
+val equal: t -> t -> bool
+ (* Compare identifiers by name. *)
+val same: t -> t -> bool
+ (* Compare identifiers by binding location.
+ Two identifiers are the same either if they are both
+ non-persistent and have been created by the same call to
+ [new], or if they are both persistent and have the same
+ name. *)
+val hide: t -> t
+ (* Return an identifier with same name as the given identifier,
+ but stamp different from any stamp returned by new.
+ When put in a 'a tbl, this identifier can only be looked
+ up by name. *)
+
+val make_global: t -> unit
+val global: t -> bool
+val is_predef_exn: t -> bool
+
+val binding_time: t -> int
+val current_time: unit -> int
+val set_current_time: int -> unit
+val reinit: unit -> unit
+
+val print: Format.formatter -> t -> unit
+
+type 'a tbl
+ (* Association tables from identifiers to type 'a. *)
+
+val empty: 'a tbl
+val add: t -> 'a -> 'a tbl -> 'a tbl
+val find_same: t -> 'a tbl -> 'a
+val find_name: string -> 'a tbl -> 'a
+val find_all: string -> 'a tbl -> 'a list
+val fold_name: (t -> 'a -> 'b -> 'b) -> 'a tbl -> 'b -> 'b
+val fold_all: (t -> 'a -> 'b -> 'b) -> 'a tbl -> 'b -> 'b
+val iter: (t -> 'a -> unit) -> 'a tbl -> unit
+
+
+(* Idents for sharing keys *)
+
+val make_key_generator : unit -> (t -> t)
diff --git a/typing/includeclass.ml b/typing/includeclass.ml
new file mode 100644
index 0000000000..9e3564b172
--- /dev/null
+++ b/typing/includeclass.ml
@@ -0,0 +1,107 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Inclusion checks for the class language *)
+
+open Types
+
+let class_types env cty1 cty2 =
+ Ctype.match_class_types env cty1 cty2
+
+let class_type_declarations env cty1 cty2 =
+ Ctype.match_class_declarations env
+ cty1.clty_params cty1.clty_type
+ cty2.clty_params cty2.clty_type
+
+let class_declarations env cty1 cty2 =
+ match cty1.cty_new, cty2.cty_new with
+ None, Some _ ->
+ [Ctype.CM_Virtual_class]
+ | _ ->
+ Ctype.match_class_declarations env
+ cty1.cty_params cty1.cty_type
+ cty2.cty_params cty2.cty_type
+
+open Format
+open Ctype
+
+(*
+let rec hide_params = function
+ Tcty_arrow ("*", _, cty) -> hide_params cty
+ | cty -> cty
+*)
+
+let include_err ppf =
+ function
+ | CM_Virtual_class ->
+ fprintf ppf "A class cannot be changed from virtual to concrete"
+ | CM_Parameter_arity_mismatch (ls, lp) ->
+ fprintf ppf
+ "The classes do not have the same number of type parameters"
+ | CM_Type_parameter_mismatch (env, trace) ->
+ Printtyp.report_unification_error ppf env ~unif:false trace
+ (function ppf ->
+ fprintf ppf "A type parameter has type")
+ (function ppf ->
+ fprintf ppf "but is expected to have type")
+ | CM_Class_type_mismatch (env, cty1, cty2) ->
+ Printtyp.wrap_printing_env env (fun () ->
+ fprintf ppf
+ "@[The class type@;<1 2>%a@ %s@;<1 2>%a@]"
+ Printtyp.class_type cty1
+ "is not matched by the class type"
+ Printtyp.class_type cty2)
+ | CM_Parameter_mismatch (env, trace) ->
+ Printtyp.report_unification_error ppf env ~unif:false trace
+ (function ppf ->
+ fprintf ppf "A parameter has type")
+ (function ppf ->
+ fprintf ppf "but is expected to have type")
+ | CM_Val_type_mismatch (lab, env, trace) ->
+ Printtyp.report_unification_error ppf env ~unif:false trace
+ (function ppf ->
+ fprintf ppf "The instance variable %s@ has type" lab)
+ (function ppf ->
+ fprintf ppf "but is expected to have type")
+ | CM_Meth_type_mismatch (lab, env, trace) ->
+ Printtyp.report_unification_error ppf env ~unif:false trace
+ (function ppf ->
+ fprintf ppf "The method %s@ has type" lab)
+ (function ppf ->
+ fprintf ppf "but is expected to have type")
+ | CM_Non_mutable_value lab ->
+ fprintf ppf
+ "@[The non-mutable instance variable %s cannot become mutable@]" lab
+ | CM_Non_concrete_value lab ->
+ fprintf ppf
+ "@[The virtual instance variable %s cannot become concrete@]" lab
+ | CM_Missing_value lab ->
+ fprintf ppf "@[The first class type has no instance variable %s@]" lab
+ | CM_Missing_method lab ->
+ fprintf ppf "@[The first class type has no method %s@]" lab
+ | CM_Hide_public lab ->
+ fprintf ppf "@[The public method %s cannot be hidden@]" lab
+ | CM_Hide_virtual (k, lab) ->
+ fprintf ppf "@[The virtual %s %s cannot be hidden@]" k lab
+ | CM_Public_method lab ->
+ fprintf ppf "@[The public method %s cannot become private" lab
+ | CM_Virtual_method lab ->
+ fprintf ppf "@[The virtual method %s cannot become concrete" lab
+ | CM_Private_method lab ->
+ fprintf ppf "The private method %s cannot become public" lab
+
+let report_error ppf = function
+ | [] -> ()
+ | err :: errs ->
+ let print_errs ppf errs =
+ List.iter (fun err -> fprintf ppf "@ %a" include_err err) errs in
+ fprintf ppf "@[<v>%a%a@]" include_err err print_errs errs
diff --git a/typing/includeclass.mli b/typing/includeclass.mli
new file mode 100644
index 0000000000..48c5c0ca33
--- /dev/null
+++ b/typing/includeclass.mli
@@ -0,0 +1,28 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1997 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Inclusion checks for the class language *)
+
+open Types
+open Ctype
+open Format
+
+val class_types:
+ Env.t -> class_type -> class_type -> class_match_failure list
+val class_type_declarations:
+ Env.t -> class_type_declaration -> class_type_declaration ->
+ class_match_failure list
+val class_declarations:
+ Env.t -> class_declaration -> class_declaration ->
+ class_match_failure list
+
+val report_error: formatter -> class_match_failure list -> unit
diff --git a/typing/includecore.ml b/typing/includecore.ml
new file mode 100644
index 0000000000..f3bbbfd86e
--- /dev/null
+++ b/typing/includecore.ml
@@ -0,0 +1,336 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Inclusion checks for the core language *)
+
+open Asttypes
+open Path
+open Types
+open Typedtree
+
+(* Inclusion between value descriptions *)
+
+exception Dont_match
+
+let value_descriptions env vd1 vd2 =
+ if Ctype.moregeneral env true vd1.val_type vd2.val_type then begin
+ match (vd1.val_kind, vd2.val_kind) with
+ (Val_prim p1, Val_prim p2) ->
+ if p1 = p2 then Tcoerce_none else raise Dont_match
+ | (Val_prim p, _) ->
+ let pc = {pc_desc = p; pc_type = vd2.val_type;
+ pc_env = env; pc_loc = vd1.val_loc; } in
+ Tcoerce_primitive pc
+ | (_, Val_prim p) -> raise Dont_match
+ | (_, _) -> Tcoerce_none
+ end else
+ raise Dont_match
+
+(* Inclusion between "private" annotations *)
+
+let private_flags decl1 decl2 =
+ match decl1.type_private, decl2.type_private with
+ | Private, Public ->
+ decl2.type_kind = Type_abstract &&
+ (decl2.type_manifest = None || decl1.type_kind <> Type_abstract)
+ | _, _ -> true
+
+(* Inclusion between manifest types (particularly for private row types) *)
+
+let is_absrow env ty =
+ match ty.desc with
+ Tconstr(Pident id, _, _) ->
+ begin match Ctype.expand_head env ty with
+ {desc=Tobject _|Tvariant _} -> true
+ | _ -> false
+ end
+ | _ -> false
+
+let type_manifest env ty1 params1 ty2 params2 priv2 =
+ let ty1' = Ctype.expand_head env ty1 and ty2' = Ctype.expand_head env ty2 in
+ match ty1'.desc, ty2'.desc with
+ Tvariant row1, Tvariant row2 when is_absrow env (Btype.row_more row2) ->
+ let row1 = Btype.row_repr row1 and row2 = Btype.row_repr row2 in
+ Ctype.equal env true (ty1::params1) (row2.row_more::params2) &&
+ begin match row1.row_more with
+ {desc=Tvar _|Tconstr _|Tnil} -> true
+ | _ -> false
+ end &&
+ let r1, r2, pairs =
+ Ctype.merge_row_fields row1.row_fields row2.row_fields in
+ (not row2.row_closed ||
+ row1.row_closed && Ctype.filter_row_fields false r1 = []) &&
+ List.for_all
+ (fun (_,f) -> match Btype.row_field_repr f with
+ Rabsent | Reither _ -> true | Rpresent _ -> false)
+ r2 &&
+ let to_equal = ref (List.combine params1 params2) in
+ List.for_all
+ (fun (_, f1, f2) ->
+ match Btype.row_field_repr f1, Btype.row_field_repr f2 with
+ Rpresent(Some t1),
+ (Rpresent(Some t2) | Reither(false, [t2], _, _)) ->
+ to_equal := (t1,t2) :: !to_equal; true
+ | Rpresent None, (Rpresent None | Reither(true, [], _, _)) -> true
+ | Reither(c1,tl1,_,_), Reither(c2,tl2,_,_)
+ when List.length tl1 = List.length tl2 && c1 = c2 ->
+ to_equal := List.combine tl1 tl2 @ !to_equal; true
+ | Rabsent, (Reither _ | Rabsent) -> true
+ | _ -> false)
+ pairs &&
+ let tl1, tl2 = List.split !to_equal in
+ Ctype.equal env true tl1 tl2
+ | Tobject (fi1, _), Tobject (fi2, _)
+ when is_absrow env (snd(Ctype.flatten_fields fi2)) ->
+ let (fields2,rest2) = Ctype.flatten_fields fi2 in
+ Ctype.equal env true (ty1::params1) (rest2::params2) &&
+ let (fields1,rest1) = Ctype.flatten_fields fi1 in
+ (match rest1 with {desc=Tnil|Tvar _|Tconstr _} -> true | _ -> false) &&
+ let pairs, miss1, miss2 = Ctype.associate_fields fields1 fields2 in
+ miss2 = [] &&
+ let tl1, tl2 =
+ List.split (List.map (fun (_,_,t1,_,t2) -> t1, t2) pairs) in
+ Ctype.equal env true (params1 @ tl1) (params2 @ tl2)
+ | _ ->
+ let rec check_super ty1 =
+ Ctype.equal env true (ty1 :: params1) (ty2 :: params2) ||
+ priv2 = Private &&
+ try check_super
+ (Ctype.try_expand_once_opt env (Ctype.expand_head env ty1))
+ with Ctype.Cannot_expand -> false
+ in check_super ty1
+
+(* Inclusion between type declarations *)
+
+type type_mismatch =
+ Arity
+ | Privacy
+ | Kind
+ | Constraint
+ | Manifest
+ | Variance
+ | Field_type of Ident.t
+ | Field_mutable of Ident.t
+ | Field_arity of Ident.t
+ | Field_names of int * Ident.t * Ident.t
+ | Field_missing of bool * Ident.t
+ | Record_representation of bool
+
+let report_type_mismatch0 first second decl ppf err =
+ let pr fmt = Format.fprintf ppf fmt in
+ match err with
+ Arity -> pr "They have different arities"
+ | Privacy -> pr "A private type would be revealed"
+ | Kind -> pr "Their kinds differ"
+ | Constraint -> pr "Their constraints differ"
+ | Manifest -> ()
+ | Variance -> pr "Their variances do not agree"
+ | Field_type s ->
+ pr "The types for field %s are not equal" (Ident.name s)
+ | Field_mutable s ->
+ pr "The mutability of field %s is different" (Ident.name s)
+ | Field_arity s ->
+ pr "The arities for field %s differ" (Ident.name s)
+ | Field_names (n, name1, name2) ->
+ pr "Fields number %i have different names, %s and %s"
+ n (Ident.name name1) (Ident.name name2)
+ | Field_missing (b, s) ->
+ pr "The field %s is only present in %s %s"
+ (Ident.name s) (if b then second else first) decl
+ | Record_representation b ->
+ pr "Their internal representations differ:@ %s %s %s"
+ (if b then second else first) decl
+ "uses unboxed float representation"
+
+let report_type_mismatch first second decl ppf =
+ List.iter
+ (fun err ->
+ if err = Manifest then () else
+ Format.fprintf ppf "@ %a." (report_type_mismatch0 first second decl) err)
+
+let rec compare_constructor_arguments env cstr params1 params2 arg1 arg2 =
+ match arg1, arg2 with
+ | Types.Cstr_tuple arg1, Types.Cstr_tuple arg2 ->
+ if List.length arg1 <> List.length arg2 then [Field_arity cstr]
+ else if Misc.for_all2
+ (fun ty1 ty2 -> Ctype.equal env true (ty1::params1) (ty2::params2))
+ (arg1) (arg2)
+ then [] else [Field_type cstr]
+ | Types.Cstr_record l1, Types.Cstr_record l2 ->
+ compare_records env params1 params2 0 l1 l2
+ | _ -> [Field_type cstr]
+
+and compare_variants env params1 params2 n cstrs1 cstrs2 =
+ match cstrs1, cstrs2 with
+ [], [] -> []
+ | [], c::_ -> [Field_missing (true, c.Types.cd_id)]
+ | c::_, [] -> [Field_missing (false, c.Types.cd_id)]
+ | {Types.cd_id=cstr1; cd_args=arg1; cd_res=ret1}::rem1,
+ {Types.cd_id=cstr2; cd_args=arg2; cd_res=ret2}::rem2 ->
+ if Ident.name cstr1 <> Ident.name cstr2 then
+ [Field_names (n, cstr1, cstr2)]
+ else match ret1, ret2 with
+ | Some r1, Some r2 when not (Ctype.equal env true [r1] [r2]) ->
+ [Field_type cstr1]
+ | Some _, None | None, Some _ ->
+ [Field_type cstr1]
+ | _ ->
+ let r =
+ compare_constructor_arguments env cstr1
+ params1 params2 arg1 arg2
+ in
+ if r <> [] then r
+ else compare_variants env params1 params2 (n+1) rem1 rem2
+
+
+and compare_records env params1 params2 n labels1 labels2 =
+ match labels1, labels2 with
+ [], [] -> []
+ | [], l::_ -> [Field_missing (true, l.ld_id)]
+ | l::_, [] -> [Field_missing (false, l.ld_id)]
+ | {Types.ld_id=lab1; ld_mutable=mut1; ld_type=arg1}::rem1,
+ {Types.ld_id=lab2; ld_mutable=mut2; ld_type=arg2}::rem2 ->
+ if Ident.name lab1 <> Ident.name lab2
+ then [Field_names (n, lab1, lab2)]
+ else if mut1 <> mut2 then [Field_mutable lab1] else
+ if Ctype.equal env true (arg1::params1)
+ (arg2::params2)
+ then compare_records env params1 params2 (n+1) rem1 rem2
+ else [Field_type lab1]
+
+let type_declarations ?(equality = false) env name decl1 id decl2 =
+ if decl1.type_arity <> decl2.type_arity then [Arity] else
+ if not (private_flags decl1 decl2) then [Privacy] else
+ let err = match (decl1.type_kind, decl2.type_kind) with
+ (_, Type_abstract) -> []
+ | (Type_variant cstrs1, Type_variant cstrs2) ->
+ let mark cstrs usage name decl =
+ List.iter
+ (fun c ->
+ Env.mark_constructor_used usage env name decl
+ (Ident.name c.Types.cd_id))
+ cstrs
+ in
+ let usage =
+ if decl1.type_private = Private || decl2.type_private = Public
+ then Env.Positive else Env.Privatize
+ in
+ mark cstrs1 usage name decl1;
+ if equality then mark cstrs2 Env.Positive (Ident.name id) decl2;
+ compare_variants env decl1.type_params decl2.type_params 1 cstrs1 cstrs2
+ | (Type_record(labels1,rep1), Type_record(labels2,rep2)) ->
+ let err = compare_records env decl1.type_params decl2.type_params
+ 1 labels1 labels2 in
+ if err <> [] || rep1 = rep2 then err else
+ [Record_representation (rep2 = Record_float)]
+ | (Type_open, Type_open) -> []
+ | (_, _) -> [Kind]
+ in
+ if err <> [] then err else
+ let err = match (decl1.type_manifest, decl2.type_manifest) with
+ (_, None) ->
+ if Ctype.equal env true decl1.type_params decl2.type_params
+ then [] else [Constraint]
+ | (Some ty1, Some ty2) ->
+ if type_manifest env ty1 decl1.type_params ty2 decl2.type_params
+ decl2.type_private
+ then [] else [Manifest]
+ | (None, Some ty2) ->
+ let ty1 =
+ Btype.newgenty (Tconstr(Pident id, decl2.type_params, ref Mnil))
+ in
+ if Ctype.equal env true decl1.type_params decl2.type_params then
+ if Ctype.equal env false [ty1] [ty2] then []
+ else [Manifest]
+ else [Constraint]
+ in
+ if err <> [] then err else
+ let abstr =
+ decl2.type_private = Private ||
+ decl2.type_kind = Type_abstract && decl2.type_manifest = None in
+ let opn = decl2.type_kind = Type_open && decl2.type_manifest = None in
+ let constrained ty = not (Btype.(is_Tvar (repr ty))) in
+ if List.for_all2
+ (fun ty (v1,v2) ->
+ let open Variance in
+ let imp a b = not a || b in
+ let (co1,cn1) = get_upper v1 and (co2,cn2) = get_upper v2 in
+ (if abstr then (imp co1 co2 && imp cn1 cn2)
+ else if opn || constrained ty then (co1 = co2 && cn1 = cn2)
+ else true) &&
+ let (p1,n1,i1,j1) = get_lower v1 and (p2,n2,i2,j2) = get_lower v2 in
+ imp abstr (imp p2 p1 && imp n2 n1 && imp i2 i1 && imp j2 j1))
+ decl2.type_params (List.combine decl1.type_variance decl2.type_variance)
+ then [] else [Variance]
+
+(* Inclusion between extension constructors *)
+
+let extension_constructors env id ext1 ext2 =
+ let usage =
+ if ext1.ext_private = Private || ext2.ext_private = Public
+ then Env.Positive else Env.Privatize
+ in
+ Env.mark_extension_used usage env ext1 (Ident.name id);
+ let ty1 =
+ Btype.newgenty (Tconstr(ext1.ext_type_path, ext1.ext_type_params, ref Mnil))
+ in
+ let ty2 =
+ Btype.newgenty (Tconstr(ext2.ext_type_path, ext2.ext_type_params, ref Mnil))
+ in
+ if Ctype.equal env true
+ (ty1 :: ext1.ext_type_params)
+ (ty2 :: ext2.ext_type_params)
+ then
+ if compare_constructor_arguments env (Ident.create "")
+ ext1.ext_type_params ext2.ext_type_params
+ ext1.ext_args ext2.ext_args = [] then
+ if match ext1.ext_ret_type, ext2.ext_ret_type with
+ Some r1, Some r2 when not (Ctype.equal env true [r1] [r2]) -> false
+ | Some _, None | None, Some _ -> false
+ | _ -> true
+ then
+ match ext1.ext_private, ext2.ext_private with
+ Private, Public -> false
+ | _, _ -> true
+ else false
+ else false
+ else false
+
+(* Inclusion between class types *)
+let encode_val (mut, ty) rem =
+ begin match mut with
+ Asttypes.Mutable -> Predef.type_unit
+ | Asttypes.Immutable -> Btype.newgenvar ()
+ end
+ ::ty::rem
+
+let meths meths1 meths2 =
+ Meths.fold
+ (fun nam t2 (ml1, ml2) ->
+ (begin try
+ Meths.find nam meths1 :: ml1
+ with Not_found ->
+ ml1
+ end,
+ t2 :: ml2))
+ meths2 ([], [])
+
+let vars vars1 vars2 =
+ Vars.fold
+ (fun lab v2 (vl1, vl2) ->
+ (begin try
+ encode_val (Vars.find lab vars1) vl1
+ with Not_found ->
+ vl1
+ end,
+ encode_val v2 vl2))
+ vars2 ([], [])
diff --git a/typing/includecore.mli b/typing/includecore.mli
new file mode 100644
index 0000000000..0c8e9558f4
--- /dev/null
+++ b/typing/includecore.mli
@@ -0,0 +1,48 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Inclusion checks for the core language *)
+
+open Typedtree
+open Types
+
+exception Dont_match
+
+type type_mismatch =
+ Arity
+ | Privacy
+ | Kind
+ | Constraint
+ | Manifest
+ | Variance
+ | Field_type of Ident.t
+ | Field_mutable of Ident.t
+ | Field_arity of Ident.t
+ | Field_names of int * Ident.t * Ident.t
+ | Field_missing of bool * Ident.t
+ | Record_representation of bool
+
+val value_descriptions:
+ Env.t -> value_description -> value_description -> module_coercion
+val type_declarations:
+ ?equality:bool ->
+ Env.t -> string ->
+ type_declaration -> Ident.t -> type_declaration -> type_mismatch list
+val extension_constructors:
+ Env.t -> Ident.t -> extension_constructor -> extension_constructor -> bool
+(*
+val class_types:
+ Env.t -> class_type -> class_type -> bool
+*)
+
+val report_type_mismatch:
+ string -> string -> string -> Format.formatter -> type_mismatch list -> unit
diff --git a/typing/includemod.ml b/typing/includemod.ml
new file mode 100644
index 0000000000..049f37aa4b
--- /dev/null
+++ b/typing/includemod.ml
@@ -0,0 +1,621 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Inclusion checks for the module language *)
+
+open Misc
+open Path
+open Typedtree
+open Types
+
+type symptom =
+ Missing_field of Ident.t * Location.t * string (* kind *)
+ | Value_descriptions of Ident.t * value_description * value_description
+ | Type_declarations of Ident.t * type_declaration
+ * type_declaration * Includecore.type_mismatch list
+ | Extension_constructors of
+ Ident.t * extension_constructor * extension_constructor
+ | Module_types of module_type * module_type
+ | Modtype_infos of Ident.t * modtype_declaration * modtype_declaration
+ | Modtype_permutation
+ | Interface_mismatch of string * string
+ | Class_type_declarations of
+ Ident.t * class_type_declaration * class_type_declaration *
+ Ctype.class_match_failure list
+ | Class_declarations of
+ Ident.t * class_declaration * class_declaration *
+ Ctype.class_match_failure list
+ | Unbound_modtype_path of Path.t
+ | Unbound_module_path of Path.t
+ | Invalid_module_alias of Path.t
+
+type pos =
+ Module of Ident.t | Modtype of Ident.t | Arg of Ident.t | Body of Ident.t
+type error = pos list * Env.t * symptom
+
+exception Error of error list
+
+(* All functions "blah env x1 x2" check that x1 is included in x2,
+ i.e. that x1 is the type of an implementation that fulfills the
+ specification x2. If not, Error is raised with a backtrace of the error. *)
+
+(* Inclusion between value descriptions *)
+
+let value_descriptions env cxt subst id vd1 vd2 =
+ Cmt_format.record_value_dependency vd1 vd2;
+ Env.mark_value_used env (Ident.name id) vd1;
+ let vd2 = Subst.value_description subst vd2 in
+ try
+ Includecore.value_descriptions env vd1 vd2
+ with Includecore.Dont_match ->
+ raise(Error[cxt, env, Value_descriptions(id, vd1, vd2)])
+
+(* Inclusion between type declarations *)
+
+let type_declarations env ?(old_env=env) cxt subst id decl1 decl2 =
+ Env.mark_type_used env (Ident.name id) decl1;
+ let decl2 = Subst.type_declaration subst decl2 in
+ let err = Includecore.type_declarations env (Ident.name id) decl1 id decl2 in
+ if err <> [] then
+ raise(Error[cxt, old_env, Type_declarations(id, decl1, decl2, err)])
+
+(* Inclusion between extension constructors *)
+
+let extension_constructors env cxt subst id ext1 ext2 =
+ let ext2 = Subst.extension_constructor subst ext2 in
+ if Includecore.extension_constructors env id ext1 ext2
+ then ()
+ else raise(Error[cxt, env, Extension_constructors(id, ext1, ext2)])
+
+(* Inclusion between class declarations *)
+
+let class_type_declarations ~old_env env cxt subst id decl1 decl2 =
+ let decl2 = Subst.cltype_declaration subst decl2 in
+ match Includeclass.class_type_declarations env decl1 decl2 with
+ [] -> ()
+ | reason ->
+ raise(Error[cxt, old_env,
+ Class_type_declarations(id, decl1, decl2, reason)])
+
+let class_declarations ~old_env env cxt subst id decl1 decl2 =
+ let decl2 = Subst.class_declaration subst decl2 in
+ match Includeclass.class_declarations env decl1 decl2 with
+ [] -> ()
+ | reason ->
+ raise(Error[cxt, old_env, Class_declarations(id, decl1, decl2, reason)])
+
+(* Expand a module type identifier when possible *)
+
+exception Dont_match
+
+let may_expand_module_path env path =
+ try ignore (Env.find_modtype_expansion path env); true
+ with Not_found -> false
+
+let expand_module_path env cxt path =
+ try
+ Env.find_modtype_expansion path env
+ with Not_found ->
+ raise(Error[cxt, env, Unbound_modtype_path path])
+
+let expand_module_alias env cxt path =
+ try (Env.find_module path env).md_type
+ with Not_found ->
+ raise(Error[cxt, env, Unbound_module_path path])
+
+(*
+let rec normalize_module_path env cxt path =
+ match expand_module_alias env cxt path with
+ Mty_alias path' -> normalize_module_path env cxt path'
+ | _ -> path
+*)
+
+(* Extract name, kind and ident from a signature item *)
+
+type field_desc =
+ Field_value of string
+ | Field_type of string
+ | Field_typext of string
+ | Field_module of string
+ | Field_modtype of string
+ | Field_class of string
+ | Field_classtype of string
+
+let kind_of_field_desc = function
+ | Field_value _ -> "value"
+ | Field_type _ -> "type"
+ | Field_typext _ -> "extension constructor"
+ | Field_module _ -> "module"
+ | Field_modtype _ -> "module type"
+ | Field_class _ -> "class"
+ | Field_classtype _ -> "class type"
+
+let item_ident_name = function
+ Sig_value(id, d) -> (id, d.val_loc, Field_value(Ident.name id))
+ | Sig_type(id, d, _) -> (id, d.type_loc, Field_type(Ident.name id))
+ | Sig_typext(id, d, _) -> (id, d.ext_loc, Field_typext(Ident.name id))
+ | Sig_module(id, d, _) -> (id, d.md_loc, Field_module(Ident.name id))
+ | Sig_modtype(id, d) -> (id, d.mtd_loc, Field_modtype(Ident.name id))
+ | Sig_class(id, d, _) -> (id, d.cty_loc, Field_class(Ident.name id))
+ | Sig_class_type(id, d, _) -> (id, d.clty_loc, Field_classtype(Ident.name id))
+
+let is_runtime_component = function
+ | Sig_value(_,{val_kind = Val_prim _})
+ | Sig_type(_,_,_)
+ | Sig_modtype(_,_)
+ | Sig_class_type(_,_,_) -> false
+ | Sig_value(_,_)
+ | Sig_typext(_,_,_)
+ | Sig_module(_,_,_)
+ | Sig_class(_, _,_) -> true
+
+(* Print a coercion *)
+
+let rec print_list pr ppf = function
+ [] -> ()
+ | [a] -> pr ppf a
+ | a :: l -> pr ppf a; Format.fprintf ppf ";@ "; print_list pr ppf l
+let print_list pr ppf l =
+ Format.fprintf ppf "[@[%a@]]" (print_list pr) l
+
+let rec print_coercion ppf c =
+ let pr fmt = Format.fprintf ppf fmt in
+ match c with
+ Tcoerce_none -> pr "id"
+ | Tcoerce_structure (fl, nl) ->
+ pr "@[<2>struct@ %a@ %a@]"
+ (print_list print_coercion2) fl
+ (print_list print_coercion3) nl
+ | Tcoerce_functor (inp, out) ->
+ pr "@[<2>functor@ (%a)@ (%a)@]"
+ print_coercion inp
+ print_coercion out
+ | Tcoerce_primitive {pc_desc; pc_env = _; pc_type} ->
+ pr "prim %s@ (%a)" pc_desc.Primitive.prim_name
+ Printtyp.raw_type_expr pc_type
+ | Tcoerce_alias (p, c) ->
+ pr "@[<2>alias %a@ (%a)@]"
+ Printtyp.path p
+ print_coercion c
+and print_coercion2 ppf (n, c) =
+ Format.fprintf ppf "@[%d,@ %a@]" n print_coercion c
+and print_coercion3 ppf (i, n, c) =
+ Format.fprintf ppf "@[%s, %d,@ %a@]"
+ (Ident.unique_name i) n print_coercion c
+
+(* Simplify a structure coercion *)
+
+let simplify_structure_coercion cc id_pos_list =
+ let rec is_identity_coercion pos = function
+ | [] ->
+ true
+ | (n, c) :: rem ->
+ n = pos && c = Tcoerce_none && is_identity_coercion (pos + 1) rem in
+ if is_identity_coercion 0 cc
+ then Tcoerce_none
+ else Tcoerce_structure (cc, id_pos_list)
+
+(* Inclusion between module types.
+ Return the restriction that transforms a value of the smaller type
+ into a value of the bigger type. *)
+
+let rec modtypes env cxt subst mty1 mty2 =
+ try
+ try_modtypes env cxt subst mty1 mty2
+ with
+ Dont_match ->
+ raise(Error[cxt, env, Module_types(mty1, Subst.modtype subst mty2)])
+ | Error reasons as err ->
+ match mty1, mty2 with
+ Mty_alias _, _
+ | _, Mty_alias _ -> raise err
+ | _ ->
+ raise(Error((cxt, env, Module_types(mty1, Subst.modtype subst mty2))
+ :: reasons))
+
+and try_modtypes env cxt subst mty1 mty2 =
+ match (mty1, mty2) with
+ | (Mty_alias p1, Mty_alias p2) ->
+ if Env.is_functor_arg p2 env then
+ raise (Error[cxt, env, Invalid_module_alias p2]);
+ if Path.same p1 p2 then Tcoerce_none else
+ let p1 = Env.normalize_path None env p1
+ and p2 = Env.normalize_path None env (Subst.module_path subst p2) in
+ (* Should actually be Tcoerce_ignore, if it existed *)
+ if Path.same p1 p2 then Tcoerce_none else raise Dont_match
+ | (Mty_alias p1, _) ->
+ let p1 = try
+ Env.normalize_path (Some Location.none) env p1
+ with Env.Error (Env.Missing_module (_, _, path)) ->
+ raise (Error[cxt, env, Unbound_module_path path])
+ in
+ let mty1 = Mtype.strengthen env (expand_module_alias env cxt p1) p1 in
+ Tcoerce_alias (p1, modtypes env cxt subst mty1 mty2)
+ | (Mty_ident p1, _) when may_expand_module_path env p1 ->
+ try_modtypes env cxt subst (expand_module_path env cxt p1) mty2
+ | (_, Mty_ident p2) ->
+ try_modtypes2 env cxt mty1 (Subst.modtype subst mty2)
+ | (Mty_signature sig1, Mty_signature sig2) ->
+ signatures env cxt subst sig1 sig2
+ | (Mty_functor(param1, None, res1), Mty_functor(param2, None, res2)) ->
+ begin match modtypes env (Body param1::cxt) subst res1 res2 with
+ Tcoerce_none -> Tcoerce_none
+ | cc -> Tcoerce_functor (Tcoerce_none, cc)
+ end
+ | (Mty_functor(param1, Some arg1, res1),
+ Mty_functor(param2, Some arg2, res2)) ->
+ let arg2' = Subst.modtype subst arg2 in
+ let cc_arg = modtypes env (Arg param1::cxt) Subst.identity arg2' arg1 in
+ let cc_res =
+ modtypes (Env.add_module param1 arg2' env) (Body param1::cxt)
+ (Subst.add_module param2 (Pident param1) subst) res1 res2 in
+ begin match (cc_arg, cc_res) with
+ (Tcoerce_none, Tcoerce_none) -> Tcoerce_none
+ | _ -> Tcoerce_functor(cc_arg, cc_res)
+ end
+ | (_, _) ->
+ raise Dont_match
+
+and try_modtypes2 env cxt mty1 mty2 =
+ (* mty2 is an identifier *)
+ match (mty1, mty2) with
+ (Mty_ident p1, Mty_ident p2) when Path.same p1 p2 ->
+ Tcoerce_none
+ | (_, Mty_ident p2) ->
+ try_modtypes env cxt Subst.identity mty1 (expand_module_path env cxt p2)
+ | (_, _) ->
+ assert false
+
+(* Inclusion between signatures *)
+
+and signatures env cxt subst sig1 sig2 =
+ (* Environment used to check inclusion of components *)
+ let new_env =
+ Env.add_signature sig1 (Env.in_signature true env) in
+ (* Keep ids for module aliases *)
+ let (id_pos_list,_) =
+ List.fold_left
+ (fun (l,pos) -> function
+ Sig_module (id, _, _) ->
+ ((id,pos,Tcoerce_none)::l , pos+1)
+ | item -> (l, if is_runtime_component item then pos+1 else pos))
+ ([], 0) sig1 in
+ (* Build a table of the components of sig1, along with their positions.
+ The table is indexed by kind and name of component *)
+ let rec build_component_table pos tbl = function
+ [] -> pos, tbl
+ | item :: rem ->
+ let (id, _loc, name) = item_ident_name item in
+ let nextpos = if is_runtime_component item then pos + 1 else pos in
+ build_component_table nextpos
+ (Tbl.add name (id, item, pos) tbl) rem in
+ let len1, comps1 =
+ build_component_table 0 Tbl.empty sig1 in
+ let len2 =
+ List.fold_left
+ (fun n i -> if is_runtime_component i then n + 1 else n)
+ 0
+ sig2
+ in
+ (* Pair each component of sig2 with a component of sig1,
+ identifying the names along the way.
+ Return a coercion list indicating, for all run-time components
+ of sig2, the position of the matching run-time components of sig1
+ and the coercion to be applied to it. *)
+ let rec pair_components subst paired unpaired = function
+ [] ->
+ begin match unpaired with
+ [] ->
+ let cc =
+ signature_components env new_env cxt subst (List.rev paired)
+ in
+ if len1 = len2 then (* see PR#5098 *)
+ simplify_structure_coercion cc id_pos_list
+ else
+ Tcoerce_structure (cc, id_pos_list)
+ | _ -> raise(Error unpaired)
+ end
+ | item2 :: rem ->
+ let (id2, loc, name2) = item_ident_name item2 in
+ let name2, report =
+ match item2, name2 with
+ Sig_type (_, {type_manifest=None}, _), Field_type s
+ when let l = String.length s in
+ l >= 4 && String.sub s (l-4) 4 = "#row" ->
+ (* Do not report in case of failure,
+ as the main type will generate an error *)
+ Field_type (String.sub s 0 (String.length s - 4)), false
+ | _ -> name2, true
+ in
+ begin try
+ let (id1, item1, pos1) = Tbl.find name2 comps1 in
+ let new_subst =
+ match item2 with
+ Sig_type _ ->
+ Subst.add_type id2 (Pident id1) subst
+ | Sig_module _ ->
+ Subst.add_module id2 (Pident id1) subst
+ | Sig_modtype _ ->
+ Subst.add_modtype id2 (Mty_ident (Pident id1)) subst
+ | Sig_value _ | Sig_typext _
+ | Sig_class _ | Sig_class_type _ ->
+ subst
+ in
+ pair_components new_subst
+ ((item1, item2, pos1) :: paired) unpaired rem
+ with Not_found ->
+ let unpaired =
+ if report then
+ (cxt, env, Missing_field (id2, loc, kind_of_field_desc name2)) ::
+ unpaired
+ else unpaired in
+ pair_components subst paired unpaired rem
+ end in
+ (* Do the pairing and checking, and return the final coercion *)
+ pair_components subst [] [] sig2
+
+(* Inclusion between signature components *)
+
+and signature_components old_env env cxt subst paired =
+ let comps_rec rem = signature_components old_env env cxt subst rem in
+ match paired with
+ [] -> []
+ | (Sig_value(id1, valdecl1), Sig_value(id2, valdecl2), pos) :: rem ->
+ let cc = value_descriptions env cxt subst id1 valdecl1 valdecl2 in
+ begin match valdecl2.val_kind with
+ Val_prim p -> comps_rec rem
+ | _ -> (pos, cc) :: comps_rec rem
+ end
+ | (Sig_type(id1, tydecl1, _), Sig_type(id2, tydecl2, _), pos) :: rem ->
+ type_declarations ~old_env env cxt subst id1 tydecl1 tydecl2;
+ comps_rec rem
+ | (Sig_typext(id1, ext1, _), Sig_typext(id2, ext2, _), pos)
+ :: rem ->
+ extension_constructors env cxt subst id1 ext1 ext2;
+ (pos, Tcoerce_none) :: comps_rec rem
+ | (Sig_module(id1, mty1, _), Sig_module(id2, mty2, _), pos) :: rem ->
+ let p1 = Pident id1 in
+ let cc =
+ modtypes env (Module id1::cxt) subst
+ (Mtype.strengthen (Env.add_functor_arg id1 env) mty1.md_type p1)
+ mty2.md_type in
+ (pos, cc) :: comps_rec rem
+ | (Sig_modtype(id1, info1), Sig_modtype(id2, info2), pos) :: rem ->
+ modtype_infos env cxt subst id1 info1 info2;
+ comps_rec rem
+ | (Sig_class(id1, decl1, _), Sig_class(id2, decl2, _), pos) :: rem ->
+ class_declarations ~old_env env cxt subst id1 decl1 decl2;
+ (pos, Tcoerce_none) :: comps_rec rem
+ | (Sig_class_type(id1, info1, _),
+ Sig_class_type(id2, info2, _), pos) :: rem ->
+ class_type_declarations ~old_env env cxt subst id1 info1 info2;
+ comps_rec rem
+ | _ ->
+ assert false
+
+(* Inclusion between module type specifications *)
+
+and modtype_infos env cxt subst id info1 info2 =
+ let info2 = Subst.modtype_declaration subst info2 in
+ let cxt' = Modtype id :: cxt in
+ try
+ match (info1.mtd_type, info2.mtd_type) with
+ (None, None) -> ()
+ | (Some mty1, None) -> ()
+ | (Some mty1, Some mty2) ->
+ check_modtype_equiv env cxt' mty1 mty2
+ | (None, Some mty2) ->
+ check_modtype_equiv env cxt' (Mty_ident(Pident id)) mty2
+ with Error reasons ->
+ raise(Error((cxt, env, Modtype_infos(id, info1, info2)) :: reasons))
+
+and check_modtype_equiv env cxt mty1 mty2 =
+ match
+ (modtypes env cxt Subst.identity mty1 mty2,
+ modtypes env cxt Subst.identity mty2 mty1)
+ with
+ (Tcoerce_none, Tcoerce_none) -> ()
+ | (c1, c2) ->
+ (* Format.eprintf "@[c1 = %a@ c2 = %a@]@."
+ print_coercion c1 print_coercion c2; *)
+ raise(Error [cxt, env, Modtype_permutation])
+
+(* Simplified inclusion check between module types (for Env) *)
+
+let check_modtype_inclusion env mty1 path1 mty2 =
+ try
+ ignore(modtypes env [] Subst.identity
+ (Mtype.strengthen env mty1 path1) mty2)
+ with Error reasons ->
+ raise Not_found
+
+let _ = Env.check_modtype_inclusion := check_modtype_inclusion
+
+(* Check that an implementation of a compilation unit meets its
+ interface. *)
+
+let compunit env impl_name impl_sig intf_name intf_sig =
+ try
+ signatures env [] Subst.identity impl_sig intf_sig
+ with Error reasons ->
+ raise(Error(([], Env.empty,Interface_mismatch(impl_name, intf_name))
+ :: reasons))
+
+(* Hide the context and substitution parameters to the outside world *)
+
+let modtypes env mty1 mty2 = modtypes env [] Subst.identity mty1 mty2
+let signatures env sig1 sig2 = signatures env [] Subst.identity sig1 sig2
+let type_declarations env id decl1 decl2 =
+ type_declarations env [] Subst.identity id decl1 decl2
+
+(*
+let modtypes env m1 m2 =
+ let c = modtypes env m1 m2 in
+ Format.eprintf "@[<2>modtypes@ %a@ %a =@ %a@]@."
+ Printtyp.modtype m1 Printtyp.modtype m2
+ print_coercion c;
+ c
+*)
+
+(* Error report *)
+
+open Format
+open Printtyp
+
+let show_loc msg ppf loc =
+ let pos = loc.Location.loc_start in
+ if List.mem pos.Lexing.pos_fname [""; "_none_"; "//toplevel//"] then ()
+ else fprintf ppf "@\n@[<2>%a:@ %s@]" Location.print_loc loc msg
+
+let show_locs ppf (loc1, loc2) =
+ show_loc "Expected declaration" ppf loc2;
+ show_loc "Actual declaration" ppf loc1
+
+let include_err ppf = function
+ | Missing_field (id, loc, kind) ->
+ fprintf ppf "The %s `%a' is required but not provided" kind ident id;
+ show_loc "Expected declaration" ppf loc
+ | Value_descriptions(id, d1, d2) ->
+ fprintf ppf
+ "@[<hv 2>Values do not match:@ %a@;<1 -2>is not included in@ %a@]"
+ (value_description id) d1 (value_description id) d2;
+ show_locs ppf (d1.val_loc, d2.val_loc);
+ | Type_declarations(id, d1, d2, errs) ->
+ fprintf ppf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]%a%a@]"
+ "Type declarations do not match"
+ (type_declaration id) d1
+ "is not included in"
+ (type_declaration id) d2
+ show_locs (d1.type_loc, d2.type_loc)
+ (Includecore.report_type_mismatch
+ "the first" "the second" "declaration") errs
+ | Extension_constructors(id, x1, x2) ->
+ fprintf ppf
+ "@[<hv 2>Extension declarations do not match:@ \
+ %a@;<1 -2>is not included in@ %a@]"
+ (extension_constructor id) x1
+ (extension_constructor id) x2;
+ show_locs ppf (x1.ext_loc, x2.ext_loc)
+ | Module_types(mty1, mty2)->
+ fprintf ppf
+ "@[<hv 2>Modules do not match:@ \
+ %a@;<1 -2>is not included in@ %a@]"
+ modtype mty1
+ modtype mty2
+ | Modtype_infos(id, d1, d2) ->
+ fprintf ppf
+ "@[<hv 2>Module type declarations do not match:@ \
+ %a@;<1 -2>does not match@ %a@]"
+ (modtype_declaration id) d1
+ (modtype_declaration id) d2
+ | Modtype_permutation ->
+ fprintf ppf "Illegal permutation of structure fields"
+ | Interface_mismatch(impl_name, intf_name) ->
+ fprintf ppf "@[The implementation %s@ does not match the interface %s:"
+ impl_name intf_name
+ | Class_type_declarations(id, d1, d2, reason) ->
+ fprintf ppf
+ "@[<hv 2>Class type declarations do not match:@ \
+ %a@;<1 -2>does not match@ %a@]@ %a"
+ (Printtyp.cltype_declaration id) d1
+ (Printtyp.cltype_declaration id) d2
+ Includeclass.report_error reason
+ | Class_declarations(id, d1, d2, reason) ->
+ fprintf ppf
+ "@[<hv 2>Class declarations do not match:@ \
+ %a@;<1 -2>does not match@ %a@]@ %a"
+ (Printtyp.class_declaration id) d1
+ (Printtyp.class_declaration id) d2
+ Includeclass.report_error reason
+ | Unbound_modtype_path path ->
+ fprintf ppf "Unbound module type %a" Printtyp.path path
+ | Unbound_module_path path ->
+ fprintf ppf "Unbound module %a" Printtyp.path path
+ | Invalid_module_alias path ->
+ fprintf ppf "Module %a cannot be aliased" Printtyp.path path
+
+let rec context ppf = function
+ Module id :: rem ->
+ fprintf ppf "@[<2>module %a%a@]" ident id args rem
+ | Modtype id :: rem ->
+ fprintf ppf "@[<2>module type %a =@ %a@]" ident id context_mty rem
+ | Body x :: rem ->
+ fprintf ppf "functor (%s) ->@ %a" (argname x) context_mty rem
+ | Arg x :: rem ->
+ fprintf ppf "functor (%a : %a) -> ..." ident x context_mty rem
+ | [] ->
+ fprintf ppf "<here>"
+and context_mty ppf = function
+ (Module _ | Modtype _) :: _ as rem ->
+ fprintf ppf "@[<2>sig@ %a@;<1 -2>end@]" context rem
+ | cxt -> context ppf cxt
+and args ppf = function
+ Body x :: rem ->
+ fprintf ppf "(%s)%a" (argname x) args rem
+ | Arg x :: rem ->
+ fprintf ppf "(%a :@ %a) : ..." ident x context_mty rem
+ | cxt ->
+ fprintf ppf " :@ %a" context_mty cxt
+and argname x =
+ let s = Ident.name x in
+ if s = "*" then "" else s
+
+let path_of_context = function
+ Module id :: rem ->
+ let rec subm path = function
+ [] -> path
+ | Module id :: rem -> subm (Pdot (path, Ident.name id, -1)) rem
+ | _ -> assert false
+ in subm (Pident id) rem
+ | _ -> assert false
+
+let context ppf cxt =
+ if cxt = [] then () else
+ if List.for_all (function Module _ -> true | _ -> false) cxt then
+ fprintf ppf "In module %a:@ " path (path_of_context cxt)
+ else
+ fprintf ppf "@[<hv 2>At position@ %a@]@ " context cxt
+
+let include_err ppf (cxt, env, err) =
+ Printtyp.wrap_printing_env env (fun () ->
+ fprintf ppf "@[<v>%a%a@]" context (List.rev cxt) include_err err)
+
+let buffer = ref Bytes.empty
+let is_big obj =
+ let size = !Clflags.error_size in
+ size > 0 &&
+ begin
+ if Bytes.length !buffer < size then buffer := Bytes.create size;
+ try ignore (Marshal.to_buffer !buffer 0 size obj []); false
+ with _ -> true
+ end
+
+let report_error ppf errs =
+ if errs = [] then () else
+ let (errs , err) = split_last errs in
+ let pe = ref true in
+ let include_err' ppf (_,_,obj as err) =
+ if not (is_big obj) then fprintf ppf "%a@ " include_err err
+ else if !pe then (fprintf ppf "...@ "; pe := false)
+ in
+ let print_errs ppf = List.iter (include_err' ppf) in
+ fprintf ppf "@[<v>%a%a@]" print_errs errs include_err err
+
+
+(* We could do a better job to split the individual error items
+ as sub-messages of the main interface mismatch on the whole unit. *)
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error err -> Some (Location.error_of_printer_file report_error err)
+ | _ -> None
+ )
diff --git a/typing/includemod.mli b/typing/includemod.mli
new file mode 100644
index 0000000000..5bc3c336bb
--- /dev/null
+++ b/typing/includemod.mli
@@ -0,0 +1,55 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Inclusion checks for the module language *)
+
+open Typedtree
+open Types
+open Format
+
+val modtypes: Env.t -> module_type -> module_type -> module_coercion
+val signatures: Env.t -> signature -> signature -> module_coercion
+val compunit:
+ Env.t -> string -> signature -> string -> signature -> module_coercion
+val type_declarations:
+ Env.t -> Ident.t -> type_declaration -> type_declaration -> unit
+val print_coercion: formatter -> module_coercion -> unit
+
+type symptom =
+ Missing_field of Ident.t * Location.t * string (* kind *)
+ | Value_descriptions of Ident.t * value_description * value_description
+ | Type_declarations of Ident.t * type_declaration
+ * type_declaration * Includecore.type_mismatch list
+ | Extension_constructors of
+ Ident.t * extension_constructor * extension_constructor
+ | Module_types of module_type * module_type
+ | Modtype_infos of Ident.t * modtype_declaration * modtype_declaration
+ | Modtype_permutation
+ | Interface_mismatch of string * string
+ | Class_type_declarations of
+ Ident.t * class_type_declaration * class_type_declaration *
+ Ctype.class_match_failure list
+ | Class_declarations of
+ Ident.t * class_declaration * class_declaration *
+ Ctype.class_match_failure list
+ | Unbound_modtype_path of Path.t
+ | Unbound_module_path of Path.t
+ | Invalid_module_alias of Path.t
+
+type pos =
+ Module of Ident.t | Modtype of Ident.t | Arg of Ident.t | Body of Ident.t
+type error = pos list * Env.t * symptom
+
+exception Error of error list
+
+val report_error: formatter -> error list -> unit
+val expand_module_alias: Env.t -> pos list -> Path.t -> Types.module_type
diff --git a/typing/mtype.ml b/typing/mtype.ml
new file mode 100644
index 0000000000..5e31ac898e
--- /dev/null
+++ b/typing/mtype.ml
@@ -0,0 +1,398 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Operations on module types *)
+
+open Asttypes
+open Path
+open Types
+
+
+let rec scrape env mty =
+ match mty with
+ Mty_ident p ->
+ begin try
+ scrape env (Env.find_modtype_expansion p env)
+ with Not_found ->
+ mty
+ end
+ | _ -> mty
+
+let freshen mty =
+ Subst.modtype Subst.identity mty
+
+let rec strengthen env mty p =
+ match scrape env mty with
+ Mty_signature sg ->
+ Mty_signature(strengthen_sig env sg p 0)
+ | Mty_functor(param, arg, res)
+ when !Clflags.applicative_functors && Ident.name param <> "*" ->
+ Mty_functor(param, arg, strengthen env res (Papply(p, Pident param)))
+ | mty ->
+ mty
+
+and strengthen_sig env sg p pos =
+ match sg with
+ [] -> []
+ | (Sig_value(id, desc) as sigelt) :: rem ->
+ let nextpos = match desc.val_kind with Val_prim _ -> pos | _ -> pos+1 in
+ sigelt :: strengthen_sig env rem p nextpos
+ | Sig_type(id, {type_kind=Type_abstract}, rs) ::
+ (Sig_type(id', {type_private=Private}, _) :: _ as rem)
+ when Ident.name id = Ident.name id' ^ "#row" ->
+ strengthen_sig env rem p pos
+ | Sig_type(id, decl, rs) :: rem ->
+ let newdecl =
+ match decl.type_manifest, decl.type_private, decl.type_kind with
+ Some _, Public, _ -> decl
+ | Some _, Private, (Type_record _ | Type_variant _) -> decl
+ | _ ->
+ let manif =
+ Some(Btype.newgenty(Tconstr(Pdot(p, Ident.name id, nopos),
+ decl.type_params, ref Mnil))) in
+ if decl.type_kind = Type_abstract then
+ { decl with type_private = Public; type_manifest = manif }
+ else
+ { decl with type_manifest = manif }
+ in
+ Sig_type(id, newdecl, rs) :: strengthen_sig env rem p pos
+ | (Sig_typext(id, ext, es) as sigelt) :: rem ->
+ sigelt :: strengthen_sig env rem p (pos+1)
+ | Sig_module(id, md, rs) :: rem ->
+ let str =
+ if Env.is_functor_arg p env then
+ strengthen_decl env md (Pdot(p, Ident.name id, pos))
+ else
+ {md with md_type = Mty_alias (Pdot(p, Ident.name id, pos))}
+ in
+ Sig_module(id, str, rs)
+ :: strengthen_sig (Env.add_module_declaration id md env) rem p (pos+1)
+ (* Need to add the module in case it defines manifest module types *)
+ | Sig_modtype(id, decl) :: rem ->
+ let newdecl =
+ match decl.mtd_type with
+ None ->
+ {decl with mtd_type = Some(Mty_ident(Pdot(p,Ident.name id,nopos)))}
+ | Some _ ->
+ decl
+ in
+ Sig_modtype(id, newdecl) ::
+ strengthen_sig (Env.add_modtype id decl env) rem p pos
+ (* Need to add the module type in case it is manifest *)
+ | (Sig_class(id, decl, rs) as sigelt) :: rem ->
+ sigelt :: strengthen_sig env rem p (pos+1)
+ | (Sig_class_type(id, decl, rs) as sigelt) :: rem ->
+ sigelt :: strengthen_sig env rem p pos
+
+and strengthen_decl env md p =
+ {md with md_type = strengthen env md.md_type p}
+
+let () = Env.strengthen := strengthen
+
+(* In nondep_supertype, env is only used for the type it assigns to id.
+ Hence there is no need to keep env up-to-date by adding the bindings
+ traversed. *)
+
+type variance = Co | Contra | Strict
+
+let nondep_supertype env mid mty =
+
+ let rec nondep_mty env va mty =
+ match mty with
+ Mty_ident p ->
+ if Path.isfree mid p then
+ nondep_mty env va (Env.find_modtype_expansion p env)
+ else mty
+ | Mty_alias p ->
+ if Path.isfree mid p then
+ nondep_mty env va (Env.find_module p env).md_type
+ else mty
+ | Mty_signature sg ->
+ Mty_signature(nondep_sig env va sg)
+ | Mty_functor(param, arg, res) ->
+ let var_inv =
+ match va with Co -> Contra | Contra -> Co | Strict -> Strict in
+ Mty_functor(param, Misc.may_map (nondep_mty env var_inv) arg,
+ nondep_mty
+ (Env.add_module ~arg:true param
+ (Btype.default_mty arg) env) va res)
+
+ and nondep_sig env va = function
+ [] -> []
+ | item :: rem ->
+ let rem' = nondep_sig env va rem in
+ match item with
+ Sig_value(id, d) ->
+ Sig_value(id,
+ {d with val_type = Ctype.nondep_type env mid d.val_type})
+ :: rem'
+ | Sig_type(id, d, rs) ->
+ Sig_type(id, Ctype.nondep_type_decl env mid id (va = Co) d, rs)
+ :: rem'
+ | Sig_typext(id, ext, es) ->
+ Sig_typext(id, Ctype.nondep_extension_constructor env mid ext, es)
+ :: rem'
+ | Sig_module(id, md, rs) ->
+ Sig_module(id, {md with md_type=nondep_mty env va md.md_type}, rs)
+ :: rem'
+ | Sig_modtype(id, d) ->
+ begin try
+ Sig_modtype(id, nondep_modtype_decl env d) :: rem'
+ with Not_found ->
+ match va with
+ Co -> Sig_modtype(id, {mtd_type=None; mtd_loc=Location.none;
+ mtd_attributes=[]}) :: rem'
+ | _ -> raise Not_found
+ end
+ | Sig_class(id, d, rs) ->
+ Sig_class(id, Ctype.nondep_class_declaration env mid d, rs)
+ :: rem'
+ | Sig_class_type(id, d, rs) ->
+ Sig_class_type(id, Ctype.nondep_cltype_declaration env mid d, rs)
+ :: rem'
+
+ and nondep_modtype_decl env mtd =
+ {mtd with mtd_type = Misc.may_map (nondep_mty env Strict) mtd.mtd_type}
+
+ in
+ nondep_mty env Co mty
+
+let enrich_typedecl env p decl =
+ match decl.type_manifest with
+ Some ty -> decl
+ | None ->
+ try
+ let orig_decl = Env.find_type p env in
+ if orig_decl.type_arity <> decl.type_arity
+ then decl
+ else {decl with type_manifest =
+ Some(Btype.newgenty(Tconstr(p, decl.type_params, ref Mnil)))}
+ with Not_found ->
+ decl
+
+let rec enrich_modtype env p mty =
+ match mty with
+ Mty_signature sg ->
+ Mty_signature(List.map (enrich_item env p) sg)
+ | _ ->
+ mty
+
+and enrich_item env p = function
+ Sig_type(id, decl, rs) ->
+ Sig_type(id,
+ enrich_typedecl env (Pdot(p, Ident.name id, nopos)) decl, rs)
+ | Sig_module(id, md, rs) ->
+ Sig_module(id,
+ {md with
+ md_type = enrich_modtype env
+ (Pdot(p, Ident.name id, nopos)) md.md_type},
+ rs)
+ | item -> item
+
+let rec type_paths env p mty =
+ match scrape env mty with
+ Mty_ident p -> []
+ | Mty_alias p -> []
+ | Mty_signature sg -> type_paths_sig env p 0 sg
+ | Mty_functor(param, arg, res) -> []
+
+and type_paths_sig env p pos sg =
+ match sg with
+ [] -> []
+ | Sig_value(id, decl) :: rem ->
+ let pos' = match decl.val_kind with Val_prim _ -> pos | _ -> pos + 1 in
+ type_paths_sig env p pos' rem
+ | Sig_type(id, decl, _) :: rem ->
+ Pdot(p, Ident.name id, nopos) :: type_paths_sig env p pos rem
+ | Sig_module(id, md, _) :: rem ->
+ type_paths env (Pdot(p, Ident.name id, pos)) md.md_type @
+ type_paths_sig (Env.add_module_declaration id md env) p (pos+1) rem
+ | Sig_modtype(id, decl) :: rem ->
+ type_paths_sig (Env.add_modtype id decl env) p pos rem
+ | (Sig_typext _ | Sig_class _) :: rem ->
+ type_paths_sig env p (pos+1) rem
+ | (Sig_class_type _) :: rem ->
+ type_paths_sig env p pos rem
+
+let rec no_code_needed env mty =
+ match scrape env mty with
+ Mty_ident p -> false
+ | Mty_signature sg -> no_code_needed_sig env sg
+ | Mty_functor(_, _, _) -> false
+ | Mty_alias p -> true
+
+and no_code_needed_sig env sg =
+ match sg with
+ [] -> true
+ | Sig_value(id, decl) :: rem ->
+ begin match decl.val_kind with
+ | Val_prim _ -> no_code_needed_sig env rem
+ | _ -> false
+ end
+ | Sig_module(id, md, _) :: rem ->
+ no_code_needed env md.md_type &&
+ no_code_needed_sig (Env.add_module_declaration id md env) rem
+ | (Sig_type _ | Sig_modtype _ | Sig_class_type _) :: rem ->
+ no_code_needed_sig env rem
+ | (Sig_typext _ | Sig_class _) :: rem ->
+ false
+
+
+(* Check whether a module type may return types *)
+
+let rec contains_type env = function
+ Mty_ident path ->
+ begin try match (Env.find_modtype path env).mtd_type with
+ | None -> raise Exit (* PR#6427 *)
+ | Some mty -> contains_type env mty
+ with Not_found -> raise Exit
+ end
+ | Mty_signature sg ->
+ contains_type_sig env sg
+ | Mty_functor (_, _, body) ->
+ contains_type env body
+ | Mty_alias _ ->
+ ()
+
+and contains_type_sig env = List.iter (contains_type_item env)
+
+and contains_type_item env = function
+ Sig_type (_,({type_manifest = None} |
+ {type_kind = Type_abstract; type_private = Private}),_)
+ | Sig_modtype _
+ | Sig_typext (_, {ext_args = Cstr_record _}, _) ->
+ (* We consider that extension constructors with an inlined
+ record create a type (the inlined record), even though
+ it would be technically safe to ignore that considering
+ the current constraints which guarantee that this type
+ is kept local to expressions. *)
+ raise Exit
+ | Sig_module (_, {md_type = mty}, _) ->
+ contains_type env mty
+ | Sig_value _
+ | Sig_type _
+ | Sig_typext _
+ | Sig_class _
+ | Sig_class_type _ ->
+ ()
+
+let contains_type env mty =
+ try contains_type env mty; false with Exit -> true
+
+
+(* Remove module aliases from a signature *)
+
+module P = struct
+ type t = Path.t
+ let compare p1 p2 =
+ if Path.same p1 p2 then 0 else compare p1 p2
+end
+module PathSet = Set.Make (P)
+module PathMap = Map.Make (P)
+module IdentSet = Set.Make (struct type t = Ident.t let compare = compare end)
+
+let rec get_prefixes = function
+ Pident _ -> PathSet.empty
+ | Pdot (p, _, _)
+ | Papply (p, _) -> PathSet.add p (get_prefixes p)
+
+let rec get_arg_paths = function
+ Pident _ -> PathSet.empty
+ | Pdot (p, _, _) -> get_arg_paths p
+ | Papply (p1, p2) ->
+ PathSet.add p2
+ (PathSet.union (get_prefixes p2)
+ (PathSet.union (get_arg_paths p1) (get_arg_paths p2)))
+
+let rec rollback_path subst p =
+ try Pident (PathMap.find p subst)
+ with Not_found ->
+ match p with
+ Pident _ | Papply _ -> p
+ | Pdot (p1, s, n) ->
+ let p1' = rollback_path subst p1 in
+ if Path.same p1 p1' then p else rollback_path subst (Pdot (p1', s, n))
+
+let rec collect_ids subst bindings p =
+ begin match rollback_path subst p with
+ Pident id ->
+ let ids =
+ try collect_ids subst bindings (Ident.find_same id bindings)
+ with Not_found -> IdentSet.empty
+ in
+ IdentSet.add id ids
+ | _ -> IdentSet.empty
+ end
+
+let collect_arg_paths mty =
+ let open Btype in
+ let paths = ref PathSet.empty
+ and subst = ref PathMap.empty
+ and bindings = ref Ident.empty in
+ (* let rt = Ident.create "Root" in
+ and prefix = ref (Path.Pident rt) in *)
+ let it_path p = paths := PathSet.union (get_arg_paths p) !paths
+ and it_signature_item it si =
+ type_iterators.it_signature_item it si;
+ match si with
+ Sig_module (id, {md_type=Mty_alias p}, _) ->
+ bindings := Ident.add id p !bindings
+ | Sig_module (id, {md_type=Mty_signature sg}, _) ->
+ List.iter
+ (function Sig_module (id', _, _) ->
+ subst :=
+ PathMap.add (Pdot (Pident id, Ident.name id', -1)) id' !subst
+ | _ -> ())
+ sg
+ | _ -> ()
+ in
+ let it = {type_iterators with it_path; it_signature_item} in
+ it.it_module_type it mty;
+ it.it_module_type unmark_iterators mty;
+ PathSet.fold (fun p -> IdentSet.union (collect_ids !subst !bindings p))
+ !paths IdentSet.empty
+
+let rec remove_aliases env excl mty =
+ match mty with
+ Mty_signature sg ->
+ Mty_signature (remove_aliases_sig env excl sg)
+ | Mty_alias _ ->
+ let mty' = Env.scrape_alias env mty in
+ if mty' = mty then mty else
+ remove_aliases env excl mty'
+ | mty ->
+ mty
+
+and remove_aliases_sig env excl sg =
+ match sg with
+ [] -> []
+ | Sig_module(id, md, rs) :: rem ->
+ let mty =
+ match md.md_type with
+ Mty_alias _ when IdentSet.mem id excl ->
+ md.md_type
+ | mty ->
+ remove_aliases env excl mty
+ in
+ Sig_module(id, {md with md_type = mty} , rs) ::
+ remove_aliases_sig (Env.add_module id mty env) excl rem
+ | Sig_modtype(id, mtd) :: rem ->
+ Sig_modtype(id, mtd) ::
+ remove_aliases_sig (Env.add_modtype id mtd env) excl rem
+ | it :: rem ->
+ it :: remove_aliases_sig env excl rem
+
+let remove_aliases env sg =
+ let excl = collect_arg_paths sg in
+ (* PathSet.iter (fun p -> Format.eprintf "%a@ " Printtyp.path p) excl;
+ Format.eprintf "@."; *)
+ remove_aliases env excl sg
diff --git a/typing/mtype.mli b/typing/mtype.mli
new file mode 100644
index 0000000000..6e815fad89
--- /dev/null
+++ b/typing/mtype.mli
@@ -0,0 +1,40 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Operations on module types *)
+
+open Types
+
+val scrape: Env.t -> module_type -> module_type
+ (* Expand toplevel module type abbreviations
+ till hitting a "hard" module type (signature, functor,
+ or abstract module type ident. *)
+val freshen: module_type -> module_type
+ (* Return an alpha-equivalent copy of the given module type
+ where bound identifiers are fresh. *)
+val strengthen: Env.t -> module_type -> Path.t -> module_type
+ (* Strengthen abstract type components relative to the
+ given path. *)
+val strengthen_decl: Env.t -> module_declaration -> Path.t -> module_declaration
+val nondep_supertype: Env.t -> Ident.t -> module_type -> module_type
+ (* Return the smallest supertype of the given type
+ in which the given ident does not appear.
+ Raise [Not_found] if no such type exists. *)
+val no_code_needed: Env.t -> module_type -> bool
+val no_code_needed_sig: Env.t -> signature -> bool
+ (* Determine whether a module needs no implementation code,
+ i.e. consists only of type definitions. *)
+val enrich_modtype: Env.t -> Path.t -> module_type -> module_type
+val enrich_typedecl: Env.t -> Path.t -> type_declaration -> type_declaration
+val type_paths: Env.t -> Path.t -> module_type -> Path.t list
+val contains_type: Env.t -> module_type -> bool
+val remove_aliases: Env.t -> module_type -> module_type
diff --git a/typing/oprint.ml b/typing/oprint.ml
new file mode 100644
index 0000000000..2638cdf311
--- /dev/null
+++ b/typing/oprint.ml
@@ -0,0 +1,633 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+open Outcometree
+
+exception Ellipsis
+
+let cautious f ppf arg =
+ try f ppf arg with
+ Ellipsis -> fprintf ppf "..."
+
+let rec print_ident ppf =
+ function
+ Oide_ident s -> pp_print_string ppf s
+ | Oide_dot (id, s) ->
+ print_ident ppf id; pp_print_char ppf '.'; pp_print_string ppf s
+ | Oide_apply (id1, id2) ->
+ fprintf ppf "%a(%a)" print_ident id1 print_ident id2
+
+let parenthesized_ident name =
+ (List.mem name ["or"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"])
+ ||
+ (match name.[0] with
+ 'a'..'z' | 'A'..'Z' | '\223'..'\246' | '\248'..'\255' | '_' ->
+ false
+ | _ -> true)
+
+let value_ident ppf name =
+ if parenthesized_ident name then
+ fprintf ppf "( %s )" name
+ else
+ pp_print_string ppf name
+
+(* Values *)
+
+let valid_float_lexeme s =
+ let l = String.length s in
+ let rec loop i =
+ if i >= l then s ^ "." else
+ match s.[i] with
+ | '0' .. '9' | '-' -> loop (i+1)
+ | _ -> s
+ in loop 0
+
+let float_repres f =
+ match classify_float f with
+ FP_nan -> "nan"
+ | FP_infinite ->
+ if f < 0.0 then "neg_infinity" else "infinity"
+ | _ ->
+ let float_val =
+ let s1 = Printf.sprintf "%.12g" f in
+ if f = float_of_string s1 then s1 else
+ let s2 = Printf.sprintf "%.15g" f in
+ if f = float_of_string s2 then s2 else
+ Printf.sprintf "%.18g" f
+ in valid_float_lexeme float_val
+
+let parenthesize_if_neg ppf fmt v isneg =
+ if isneg then pp_print_char ppf '(';
+ fprintf ppf fmt v;
+ if isneg then pp_print_char ppf ')'
+
+let print_out_value ppf tree =
+ let rec print_tree_1 ppf =
+ function
+ | Oval_constr (name, [param]) ->
+ fprintf ppf "@[<1>%a@ %a@]" print_ident name print_constr_param param
+ | Oval_constr (name, (_ :: _ as params)) ->
+ fprintf ppf "@[<1>%a@ (%a)@]" print_ident name
+ (print_tree_list print_tree_1 ",") params
+ | Oval_variant (name, Some param) ->
+ fprintf ppf "@[<2>`%s@ %a@]" name print_constr_param param
+ | tree -> print_simple_tree ppf tree
+ and print_constr_param ppf = function
+ | Oval_int i -> parenthesize_if_neg ppf "%i" i (i < 0)
+ | Oval_int32 i -> parenthesize_if_neg ppf "%lil" i (i < 0l)
+ | Oval_int64 i -> parenthesize_if_neg ppf "%LiL" i (i < 0L)
+ | Oval_nativeint i -> parenthesize_if_neg ppf "%nin" i (i < 0n)
+ | Oval_float f -> parenthesize_if_neg ppf "%s" (float_repres f) (f < 0.0)
+ | tree -> print_simple_tree ppf tree
+ and print_simple_tree ppf =
+ function
+ Oval_int i -> fprintf ppf "%i" i
+ | Oval_int32 i -> fprintf ppf "%lil" i
+ | Oval_int64 i -> fprintf ppf "%LiL" i
+ | Oval_nativeint i -> fprintf ppf "%nin" i
+ | Oval_float f -> pp_print_string ppf (float_repres f)
+ | Oval_char c -> fprintf ppf "%C" c
+ | Oval_string s ->
+ begin try fprintf ppf "%S" s with
+ Invalid_argument "String.create" -> fprintf ppf "<huge string>"
+ end
+ | Oval_list tl ->
+ fprintf ppf "@[<1>[%a]@]" (print_tree_list print_tree_1 ";") tl
+ | Oval_array tl ->
+ fprintf ppf "@[<2>[|%a|]@]" (print_tree_list print_tree_1 ";") tl
+ | Oval_constr (name, []) -> print_ident ppf name
+ | Oval_variant (name, None) -> fprintf ppf "`%s" name
+ | Oval_stuff s -> pp_print_string ppf s
+ | Oval_record fel ->
+ fprintf ppf "@[<1>{%a}@]" (cautious (print_fields true)) fel
+ | Oval_ellipsis -> raise Ellipsis
+ | Oval_printer f -> f ppf
+ | Oval_tuple tree_list ->
+ fprintf ppf "@[<1>(%a)@]" (print_tree_list print_tree_1 ",") tree_list
+ | tree -> fprintf ppf "@[<1>(%a)@]" (cautious print_tree_1) tree
+ and print_fields first ppf =
+ function
+ [] -> ()
+ | (name, tree) :: fields ->
+ if not first then fprintf ppf ";@ ";
+ fprintf ppf "@[<1>%a@ =@ %a@]" print_ident name (cautious print_tree_1)
+ tree;
+ print_fields false ppf fields
+ and print_tree_list print_item sep ppf tree_list =
+ let rec print_list first ppf =
+ function
+ [] -> ()
+ | tree :: tree_list ->
+ if not first then fprintf ppf "%s@ " sep;
+ print_item ppf tree;
+ print_list false ppf tree_list
+ in
+ cautious (print_list true) ppf tree_list
+ in
+ cautious print_tree_1 ppf tree
+
+let out_value = ref print_out_value
+
+(* Types *)
+
+let rec print_list_init pr sep ppf =
+ function
+ [] -> ()
+ | a :: l -> sep ppf; pr ppf a; print_list_init pr sep ppf l
+
+let rec print_list pr sep ppf =
+ function
+ [] -> ()
+ | [a] -> pr ppf a
+ | a :: l -> pr ppf a; sep ppf; print_list pr sep ppf l
+
+let pr_present =
+ print_list (fun ppf s -> fprintf ppf "`%s" s) (fun ppf -> fprintf ppf "@ ")
+
+let pr_vars =
+ print_list (fun ppf s -> fprintf ppf "'%s" s) (fun ppf -> fprintf ppf "@ ")
+
+let rec print_out_type ppf =
+ function
+ | Otyp_alias (ty, s) ->
+ fprintf ppf "@[%a@ as '%s@]" print_out_type ty s
+ | Otyp_poly (sl, ty) ->
+ fprintf ppf "@[<hov 2>%a.@ %a@]"
+ pr_vars sl
+ print_out_type ty
+ | ty ->
+ print_out_type_1 ppf ty
+
+and print_out_type_1 ppf =
+ function
+ Otyp_arrow (lab, ty1, ty2) ->
+ pp_open_box ppf 0;
+ if lab <> "" then (pp_print_string ppf lab; pp_print_char ppf ':');
+ print_out_type_2 ppf ty1;
+ pp_print_string ppf " ->";
+ pp_print_space ppf ();
+ print_out_type_1 ppf ty2;
+ pp_close_box ppf ()
+ | ty -> print_out_type_2 ppf ty
+and print_out_type_2 ppf =
+ function
+ Otyp_tuple tyl ->
+ fprintf ppf "@[<0>%a@]" (print_typlist print_simple_out_type " *") tyl
+ | ty -> print_simple_out_type ppf ty
+and print_simple_out_type ppf =
+ function
+ Otyp_class (ng, id, tyl) ->
+ fprintf ppf "@[%a%s#%a@]" print_typargs tyl (if ng then "_" else "")
+ print_ident id
+ | Otyp_constr (id, tyl) ->
+ pp_open_box ppf 0;
+ print_typargs ppf tyl;
+ print_ident ppf id;
+ pp_close_box ppf ()
+ | Otyp_object (fields, rest) ->
+ fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields
+ | Otyp_stuff s -> pp_print_string ppf s
+ | Otyp_var (ng, s) -> fprintf ppf "'%s%s" (if ng then "_" else "") s
+ | Otyp_variant (non_gen, row_fields, closed, tags) ->
+ let print_present ppf =
+ function
+ None | Some [] -> ()
+ | Some l -> fprintf ppf "@;<1 -2>> @[<hov>%a@]" pr_present l
+ in
+ let print_fields ppf =
+ function
+ Ovar_fields fields ->
+ print_list print_row_field (fun ppf -> fprintf ppf "@;<1 -2>| ")
+ ppf fields
+ | Ovar_name (id, tyl) ->
+ fprintf ppf "@[%a%a@]" print_typargs tyl print_ident id
+ in
+ fprintf ppf "%s[%s@[<hv>@[<hv>%a@]%a ]@]" (if non_gen then "_" else "")
+ (if closed then if tags = None then " " else "< "
+ else if tags = None then "> " else "? ")
+ print_fields row_fields
+ print_present tags
+ | Otyp_alias _ | Otyp_poly _ | Otyp_arrow _ | Otyp_tuple _ as ty ->
+ pp_open_box ppf 1;
+ pp_print_char ppf '(';
+ print_out_type ppf ty;
+ pp_print_char ppf ')';
+ pp_close_box ppf ()
+ | Otyp_abstract | Otyp_open
+ | Otyp_sum _ | Otyp_manifest (_, _) -> ()
+ | Otyp_record lbls -> print_record_decl ppf lbls
+ | Otyp_module (p, n, tyl) ->
+ fprintf ppf "@[<1>(module %s" p;
+ let first = ref true in
+ List.iter2
+ (fun s t ->
+ let sep = if !first then (first := false; "with") else "and" in
+ fprintf ppf " %s type %s = %a" sep s print_out_type t
+ )
+ n tyl;
+ fprintf ppf ")@]"
+ | Otyp_attribute (t, attr) ->
+ fprintf ppf "@[<1>(%a [@@%s])@]" print_out_type t attr
+and print_record_decl ppf lbls =
+ fprintf ppf "{%a@;<1 -2>}"
+ (print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
+and print_fields rest ppf =
+ function
+ [] ->
+ begin match rest with
+ Some non_gen -> fprintf ppf "%s.." (if non_gen then "_" else "")
+ | None -> ()
+ end
+ | [s, t] ->
+ fprintf ppf "%s : %a" s print_out_type t;
+ begin match rest with
+ Some _ -> fprintf ppf ";@ "
+ | None -> ()
+ end;
+ print_fields rest ppf []
+ | (s, t) :: l ->
+ fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l
+and print_row_field ppf (l, opt_amp, tyl) =
+ let pr_of ppf =
+ if opt_amp then fprintf ppf " of@ &@ "
+ else if tyl <> [] then fprintf ppf " of@ "
+ else fprintf ppf ""
+ in
+ fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &")
+ tyl
+and print_typlist print_elem sep ppf =
+ function
+ [] -> ()
+ | [ty] -> print_elem ppf ty
+ | ty :: tyl ->
+ print_elem ppf ty;
+ pp_print_string ppf sep;
+ pp_print_space ppf ();
+ print_typlist print_elem sep ppf tyl
+and print_typargs ppf =
+ function
+ [] -> ()
+ | [ty1] -> print_simple_out_type ppf ty1; pp_print_space ppf ()
+ | tyl ->
+ pp_open_box ppf 1;
+ pp_print_char ppf '(';
+ print_typlist print_out_type "," ppf tyl;
+ pp_print_char ppf ')';
+ pp_close_box ppf ();
+ pp_print_space ppf ()
+and print_out_label ppf (name, mut, arg) =
+ fprintf ppf "@[<2>%s%s :@ %a@];" (if mut then "mutable " else "") name
+ print_out_type arg
+
+let out_type = ref print_out_type
+
+(* Class types *)
+
+let type_parameter ppf (ty, (co, cn)) =
+ fprintf ppf "%s%s"
+ (if not cn then "+" else if not co then "-" else "")
+ (if ty = "_" then ty else "'"^ty)
+
+let print_out_class_params ppf =
+ function
+ [] -> ()
+ | tyl ->
+ fprintf ppf "@[<1>[%a]@]@ "
+ (print_list type_parameter (fun ppf -> fprintf ppf ", "))
+ tyl
+
+let rec print_out_class_type ppf =
+ function
+ Octy_constr (id, tyl) ->
+ let pr_tyl ppf =
+ function
+ [] -> ()
+ | tyl ->
+ fprintf ppf "@[<1>[%a]@]@ " (print_typlist !out_type ",") tyl
+ in
+ fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
+ | Octy_arrow (lab, ty, cty) ->
+ fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
+ print_out_type_2 ty print_out_class_type cty
+ | Octy_signature (self_ty, csil) ->
+ let pr_param ppf =
+ function
+ Some ty -> fprintf ppf "@ @[(%a)@]" !out_type ty
+ | None -> ()
+ in
+ fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
+ (print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
+ csil
+and print_out_class_sig_item ppf =
+ function
+ Ocsg_constraint (ty1, ty2) ->
+ fprintf ppf "@[<2>constraint %a =@ %a@]" !out_type ty1
+ !out_type ty2
+ | Ocsg_method (name, priv, virt, ty) ->
+ fprintf ppf "@[<2>method %s%s%s :@ %a@]"
+ (if priv then "private " else "") (if virt then "virtual " else "")
+ name !out_type ty
+ | Ocsg_value (name, mut, vr, ty) ->
+ fprintf ppf "@[<2>val %s%s%s :@ %a@]"
+ (if mut then "mutable " else "")
+ (if vr then "virtual " else "")
+ name !out_type ty
+
+let out_class_type = ref print_out_class_type
+
+(* Signature *)
+
+let out_module_type = ref (fun _ -> failwith "Oprint.out_module_type")
+let out_sig_item = ref (fun _ -> failwith "Oprint.out_sig_item")
+let out_signature = ref (fun _ -> failwith "Oprint.out_signature")
+let out_type_extension = ref (fun _ -> failwith "Oprint.out_type_extension")
+
+let rec print_out_functor ppf =
+ function
+ Omty_functor (_, None, mty_res) ->
+ fprintf ppf "() %a" print_out_functor mty_res
+ | Omty_functor (name , Some mty_arg, mty_res) ->
+ fprintf ppf "(%s : %a) %a" name
+ print_out_module_type mty_arg print_out_functor mty_res
+ | m -> fprintf ppf "->@ %a" print_out_module_type m
+and print_out_module_type ppf =
+ function
+ Omty_abstract -> ()
+ | Omty_functor _ as t ->
+ fprintf ppf "@[<2>functor@ %a@]" print_out_functor t
+ | Omty_ident id -> fprintf ppf "%a" print_ident id
+ | Omty_signature sg ->
+ fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" !out_signature sg
+ | Omty_alias id -> fprintf ppf "(module %a)" print_ident id
+and print_out_signature ppf =
+ function
+ [] -> ()
+ | [item] -> !out_sig_item ppf item
+ | Osig_typext(ext, Oext_first) :: items ->
+ (* Gather together the extension constructors *)
+ let rec gather_extensions acc items =
+ match items with
+ Osig_typext(ext, Oext_next) :: items ->
+ gather_extensions
+ ((ext.oext_name, ext.oext_args, ext.oext_ret_type) :: acc)
+ items
+ | _ -> (List.rev acc, items)
+ in
+ let exts, items =
+ gather_extensions
+ [(ext.oext_name, ext.oext_args, ext.oext_ret_type)]
+ items
+ in
+ let te =
+ { otyext_name = ext.oext_type_name;
+ otyext_params = ext.oext_type_params;
+ otyext_constructors = exts;
+ otyext_private = ext.oext_private }
+ in
+ fprintf ppf "%a@ %a" !out_type_extension te print_out_signature items
+ | item :: items ->
+ fprintf ppf "%a@ %a" !out_sig_item item print_out_signature items
+and print_out_sig_item ppf =
+ function
+ Osig_class (vir_flag, name, params, clt, rs) ->
+ fprintf ppf "@[<2>%s%s@ %a%s@ :@ %a@]"
+ (if rs = Orec_next then "and" else "class")
+ (if vir_flag then " virtual" else "") print_out_class_params params
+ name !out_class_type clt
+ | Osig_class_type (vir_flag, name, params, clt, rs) ->
+ fprintf ppf "@[<2>%s%s@ %a%s@ =@ %a@]"
+ (if rs = Orec_next then "and" else "class type")
+ (if vir_flag then " virtual" else "") print_out_class_params params
+ name !out_class_type clt
+ | Osig_typext (ext, Oext_exception) ->
+ fprintf ppf "@[<2>exception %a@]"
+ print_out_constr (ext.oext_name, ext.oext_args, ext.oext_ret_type)
+ | Osig_typext (ext, es) ->
+ print_out_extension_constructor ppf ext
+ | Osig_modtype (name, Omty_abstract) ->
+ fprintf ppf "@[<2>module type %s@]" name
+ | Osig_modtype (name, mty) ->
+ fprintf ppf "@[<2>module type %s =@ %a@]" name !out_module_type mty
+ | Osig_module (name, Omty_alias id, _) ->
+ fprintf ppf "@[<2>module %s =@ %a@]" name print_ident id
+ | Osig_module (name, mty, rs) ->
+ fprintf ppf "@[<2>%s %s :@ %a@]"
+ (match rs with Orec_not -> "module"
+ | Orec_first -> "module rec"
+ | Orec_next -> "and")
+ name !out_module_type mty
+ | Osig_type(td, rs) ->
+ print_out_type_decl
+ (match rs with
+ | Orec_not -> "type nonrec"
+ | Orec_first -> "type"
+ | Orec_next -> "and")
+ ppf td
+ | Osig_value (name, ty, prims) ->
+ let kwd = if prims = [] then "val" else "external" in
+ let pr_prims ppf =
+ function
+ [] -> ()
+ | s :: sl ->
+ fprintf ppf "@ = \"%s\"" s;
+ List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
+ in
+ fprintf ppf "@[<2>%s %a :@ %a%a@]" kwd value_ident name !out_type
+ ty pr_prims prims
+ | Osig_ellipsis ->
+ fprintf ppf "..."
+
+and print_out_type_decl kwd ppf td =
+ let print_constraints ppf =
+ List.iter
+ (fun (ty1, ty2) ->
+ fprintf ppf "@ @[<2>constraint %a =@ %a@]" !out_type ty1
+ !out_type ty2)
+ td.otype_cstrs
+ in
+ let type_defined ppf =
+ match td.otype_params with
+ [] -> pp_print_string ppf td.otype_name
+ | [param] -> fprintf ppf "@[%a@ %s@]" type_parameter param td.otype_name
+ | _ ->
+ fprintf ppf "@[(@[%a)@]@ %s@]"
+ (print_list type_parameter (fun ppf -> fprintf ppf ",@ "))
+ td.otype_params
+ td.otype_name
+ in
+ let print_manifest ppf =
+ function
+ Otyp_manifest (ty, _) -> fprintf ppf " =@ %a" !out_type ty
+ | _ -> ()
+ in
+ let print_name_params ppf =
+ fprintf ppf "%s %t%a" kwd type_defined print_manifest td.otype_type
+ in
+ let ty =
+ match td.otype_type with
+ Otyp_manifest (_, ty) -> ty
+ | _ -> td.otype_type
+ in
+ let print_private ppf = function
+ Asttypes.Private -> fprintf ppf " private"
+ | Asttypes.Public -> ()
+ in
+ let print_out_tkind ppf = function
+ | Otyp_abstract -> ()
+ | Otyp_record lbls ->
+ fprintf ppf " =%a %a"
+ print_private td.otype_private
+ print_record_decl lbls
+ | Otyp_sum constrs ->
+ fprintf ppf " =%a@;<1 2>%a"
+ print_private td.otype_private
+ (print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) constrs
+ | Otyp_open ->
+ fprintf ppf " = .."
+ | ty ->
+ fprintf ppf " =%a@;<1 2>%a"
+ print_private td.otype_private
+ !out_type ty
+ in
+ fprintf ppf "@[<2>@[<hv 2>%t%a@]%t@]"
+ print_name_params
+ print_out_tkind ty
+ print_constraints
+
+and print_out_constr ppf (name, tyl,ret_type_opt) =
+ match ret_type_opt with
+ | None ->
+ begin match tyl with
+ | [] ->
+ pp_print_string ppf name
+ | _ ->
+ fprintf ppf "@[<2>%s of@ %a@]" name
+ (print_typlist print_simple_out_type " *") tyl
+ end
+ | Some ret_type ->
+ begin match tyl with
+ | [] ->
+ fprintf ppf "@[<2>%s :@ %a@]" name print_simple_out_type ret_type
+ | _ ->
+ fprintf ppf "@[<2>%s :@ %a -> %a@]" name
+ (print_typlist print_simple_out_type " *")
+ tyl print_simple_out_type ret_type
+ end
+
+and print_out_extension_constructor ppf ext =
+ let print_extended_type ppf =
+ let print_type_parameter ppf ty =
+ fprintf ppf "%s"
+ (if ty = "_" then ty else "'"^ty)
+ in
+ match ext.oext_type_params with
+ [] -> fprintf ppf "%s" ext.oext_type_name
+ | [ty_param] ->
+ fprintf ppf "@[%a@ %s@]"
+ print_type_parameter
+ ty_param
+ ext.oext_type_name
+ | _ ->
+ fprintf ppf "@[(@[%a)@]@ %s@]"
+ (print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
+ ext.oext_type_params
+ ext.oext_type_name
+ in
+ fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
+ print_extended_type
+ (if ext.oext_private = Asttypes.Private then " private" else "")
+ print_out_constr (ext.oext_name, ext.oext_args, ext.oext_ret_type)
+
+and print_out_type_extension ppf te =
+ let print_extended_type ppf =
+ let print_type_parameter ppf ty =
+ fprintf ppf "%s"
+ (if ty = "_" then ty else "'"^ty)
+ in
+ match te.otyext_params with
+ [] -> fprintf ppf "%s" te.otyext_name
+ | [param] ->
+ fprintf ppf "@[%a@ %s@]"
+ print_type_parameter param
+ te.otyext_name
+ | _ ->
+ fprintf ppf "@[(@[%a)@]@ %s@]"
+ (print_list print_type_parameter (fun ppf -> fprintf ppf ",@ "))
+ te.otyext_params
+ te.otyext_name
+ in
+ fprintf ppf "@[<hv 2>type %t +=%s@;<1 2>%a@]"
+ print_extended_type
+ (if te.otyext_private = Asttypes.Private then " private" else "")
+ (print_list print_out_constr (fun ppf -> fprintf ppf "@ | "))
+ te.otyext_constructors
+
+let _ = out_module_type := print_out_module_type
+let _ = out_signature := print_out_signature
+let _ = out_sig_item := print_out_sig_item
+let _ = out_type_extension := print_out_type_extension
+
+(* Phrases *)
+
+let print_out_exception ppf exn outv =
+ match exn with
+ Sys.Break -> fprintf ppf "Interrupted.@."
+ | Out_of_memory -> fprintf ppf "Out of memory during evaluation.@."
+ | Stack_overflow ->
+ fprintf ppf "Stack overflow during evaluation (looping recursion?).@."
+ | _ -> fprintf ppf "@[Exception:@ %a.@]@." !out_value outv
+
+let rec print_items ppf =
+ function
+ [] -> ()
+ | (Osig_typext(ext, Oext_first), None) :: items ->
+ (* Gather together extension constructors *)
+ let rec gather_extensions acc items =
+ match items with
+ (Osig_typext(ext, Oext_next), None) :: items ->
+ gather_extensions
+ ((ext.oext_name, ext.oext_args, ext.oext_ret_type) :: acc)
+ items
+ | _ -> (List.rev acc, items)
+ in
+ let exts, items =
+ gather_extensions
+ [(ext.oext_name, ext.oext_args, ext.oext_ret_type)]
+ items
+ in
+ let te =
+ { otyext_name = ext.oext_type_name;
+ otyext_params = ext.oext_type_params;
+ otyext_constructors = exts;
+ otyext_private = ext.oext_private }
+ in
+ fprintf ppf "@[%a@]" !out_type_extension te;
+ if items <> [] then fprintf ppf "@ %a" print_items items
+ | (tree, valopt) :: items ->
+ begin match valopt with
+ Some v ->
+ fprintf ppf "@[<2>%a =@ %a@]" !out_sig_item tree
+ !out_value v
+ | None -> fprintf ppf "@[%a@]" !out_sig_item tree
+ end;
+ if items <> [] then fprintf ppf "@ %a" print_items items
+
+let print_out_phrase ppf =
+ function
+ Ophr_eval (outv, ty) ->
+ fprintf ppf "@[- : %a@ =@ %a@]@." !out_type ty !out_value outv
+ | Ophr_signature [] -> ()
+ | Ophr_signature items -> fprintf ppf "@[<v>%a@]@." print_items items
+ | Ophr_exception (exn, outv) -> print_out_exception ppf exn outv
+
+let out_phrase = ref print_out_phrase
diff --git a/typing/oprint.mli b/typing/oprint.mli
new file mode 100644
index 0000000000..1f9ec32b1a
--- /dev/null
+++ b/typing/oprint.mli
@@ -0,0 +1,25 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+open Outcometree
+
+val out_value : (formatter -> out_value -> unit) ref
+val out_type : (formatter -> out_type -> unit) ref
+val out_class_type : (formatter -> out_class_type -> unit) ref
+val out_module_type : (formatter -> out_module_type -> unit) ref
+val out_sig_item : (formatter -> out_sig_item -> unit) ref
+val out_signature : (formatter -> out_sig_item list -> unit) ref
+val out_type_extension : (formatter -> out_type_extension -> unit) ref
+val out_phrase : (formatter -> out_phrase -> unit) ref
+
+val parenthesized_ident : string -> bool
diff --git a/typing/outcometree.mli b/typing/outcometree.mli
new file mode 100644
index 0000000000..3a26f0b01e
--- /dev/null
+++ b/typing/outcometree.mli
@@ -0,0 +1,127 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Daniel de Rauglaudre, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2001 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Module [Outcometree]: results displayed by the toplevel *)
+
+(* These types represent messages that the toplevel displays as normal
+ results or errors. The real displaying is customisable using the hooks:
+ [Toploop.print_out_value]
+ [Toploop.print_out_type]
+ [Toploop.print_out_sig_item]
+ [Toploop.print_out_phrase] *)
+
+type out_ident =
+ | Oide_apply of out_ident * out_ident
+ | Oide_dot of out_ident * string
+ | Oide_ident of string
+
+type out_value =
+ | Oval_array of out_value list
+ | Oval_char of char
+ | Oval_constr of out_ident * out_value list
+ | Oval_ellipsis
+ | Oval_float of float
+ | Oval_int of int
+ | Oval_int32 of int32
+ | Oval_int64 of int64
+ | Oval_nativeint of nativeint
+ | Oval_list of out_value list
+ | Oval_printer of (Format.formatter -> unit)
+ | Oval_record of (out_ident * out_value) list
+ | Oval_string of string
+ | Oval_stuff of string
+ | Oval_tuple of out_value list
+ | Oval_variant of string * out_value option
+
+type out_type =
+ | Otyp_abstract
+ | Otyp_open
+ | Otyp_alias of out_type * string
+ | Otyp_arrow of string * out_type * out_type
+ | Otyp_class of bool * out_ident * out_type list
+ | Otyp_constr of out_ident * out_type list
+ | Otyp_manifest of out_type * out_type
+ | Otyp_object of (string * out_type) list * bool option
+ | Otyp_record of (string * bool * out_type) list
+ | Otyp_stuff of string
+ | Otyp_sum of (string * out_type list * out_type option) list
+ | Otyp_tuple of out_type list
+ | Otyp_var of bool * string
+ | Otyp_variant of
+ bool * out_variant * bool * (string list) option
+ | Otyp_poly of string list * out_type
+ | Otyp_module of string * string list * out_type list
+ | Otyp_attribute of out_type * string
+
+and out_variant =
+ | Ovar_fields of (string * bool * out_type list) list
+ | Ovar_name of out_ident * out_type list
+
+type out_class_type =
+ | Octy_constr of out_ident * out_type list
+ | Octy_arrow of string * out_type * out_class_type
+ | Octy_signature of out_type option * out_class_sig_item list
+and out_class_sig_item =
+ | Ocsg_constraint of out_type * out_type
+ | Ocsg_method of string * bool * bool * out_type
+ | Ocsg_value of string * bool * bool * out_type
+
+type out_module_type =
+ | Omty_abstract
+ | Omty_functor of string * out_module_type option * out_module_type
+ | Omty_ident of out_ident
+ | Omty_signature of out_sig_item list
+ | Omty_alias of out_ident
+and out_sig_item =
+ | Osig_class of
+ bool * string * (string * (bool * bool)) list * out_class_type *
+ out_rec_status
+ | Osig_class_type of
+ bool * string * (string * (bool * bool)) list * out_class_type *
+ out_rec_status
+ | Osig_typext of out_extension_constructor * out_ext_status
+ | Osig_modtype of string * out_module_type
+ | Osig_module of string * out_module_type * out_rec_status
+ | Osig_type of out_type_decl * out_rec_status
+ | Osig_value of string * out_type * string list
+ | Osig_ellipsis
+and out_type_decl =
+ { otype_name: string;
+ otype_params: (string * (bool * bool)) list;
+ otype_type: out_type;
+ otype_private: Asttypes.private_flag;
+ otype_cstrs: (out_type * out_type) list }
+and out_extension_constructor =
+ { oext_name: string;
+ oext_type_name: string;
+ oext_type_params: string list;
+ oext_args: out_type list;
+ oext_ret_type: out_type option;
+ oext_private: Asttypes.private_flag }
+and out_type_extension =
+ { otyext_name: string;
+ otyext_params: string list;
+ otyext_constructors: (string * out_type list * out_type option) list;
+ otyext_private: Asttypes.private_flag }
+and out_rec_status =
+ | Orec_not
+ | Orec_first
+ | Orec_next
+and out_ext_status =
+ | Oext_first
+ | Oext_next
+ | Oext_exception
+
+type out_phrase =
+ | Ophr_eval of out_value * out_type
+ | Ophr_signature of (out_sig_item * out_value option) list
+ | Ophr_exception of (exn * out_value)
diff --git a/typing/parmatch.ml b/typing/parmatch.ml
new file mode 100644
index 0000000000..6e0ffced1c
--- /dev/null
+++ b/typing/parmatch.ml
@@ -0,0 +1,2040 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Detection of partial matches and unused match cases. *)
+
+open Misc
+open Asttypes
+open Types
+open Typedtree
+
+(*************************************)
+(* Utilities for building patterns *)
+(*************************************)
+
+let make_pat desc ty tenv =
+ {pat_desc = desc; pat_loc = Location.none; pat_extra = [];
+ pat_type = ty ; pat_env = tenv;
+ pat_attributes = [];
+ }
+
+let omega = make_pat Tpat_any Ctype.none Env.empty
+
+let extra_pat =
+ make_pat
+ (Tpat_var (Ident.create "+", mknoloc "+"))
+ Ctype.none Env.empty
+
+let rec omegas i =
+ if i <= 0 then [] else omega :: omegas (i-1)
+
+let omega_list l = List.map (fun _ -> omega) l
+
+let zero = make_pat (Tpat_constant (Const_int 0)) Ctype.none Env.empty
+
+(***********************)
+(* Compatibility check *)
+(***********************)
+
+(* p and q compatible means, there exists V that matches both *)
+
+let is_absent tag row = Btype.row_field tag !row = Rabsent
+
+let is_absent_pat p = match p.pat_desc with
+| Tpat_variant (tag, _, row) -> is_absent tag row
+| _ -> false
+
+let const_compare x y =
+ match x,y with
+ | Const_float f1, Const_float f2 ->
+ Pervasives.compare (float_of_string f1) (float_of_string f2)
+ | Const_string (s1, _), Const_string (s2, _) ->
+ String.compare s1 s2
+ | _, _ -> Pervasives.compare x y
+
+let records_args l1 l2 =
+ (* Invariant: fields are already sorted by Typecore.type_label_a_list *)
+ let rec combine r1 r2 l1 l2 = match l1,l2 with
+ | [],[] -> List.rev r1, List.rev r2
+ | [],(_,_,p2)::rem2 -> combine (omega::r1) (p2::r2) [] rem2
+ | (_,_,p1)::rem1,[] -> combine (p1::r1) (omega::r2) rem1 []
+ | (_,lbl1,p1)::rem1, ( _,lbl2,p2)::rem2 ->
+ if lbl1.lbl_pos < lbl2.lbl_pos then
+ combine (p1::r1) (omega::r2) rem1 l2
+ else if lbl1.lbl_pos > lbl2.lbl_pos then
+ combine (omega::r1) (p2::r2) l1 rem2
+ else (* same label on both sides *)
+ combine (p1::r1) (p2::r2) rem1 rem2 in
+ combine [] [] l1 l2
+
+
+let rec compat p q =
+ match p.pat_desc,q.pat_desc with
+ | Tpat_alias (p,_,_),_ -> compat p q
+ | _,Tpat_alias (q,_,_) -> compat p q
+ | (Tpat_any|Tpat_var _),_ -> true
+ | _,(Tpat_any|Tpat_var _) -> true
+ | Tpat_or (p1,p2,_),_ -> compat p1 q || compat p2 q
+ | _,Tpat_or (q1,q2,_) -> compat p q1 || compat p q2
+ | Tpat_constant c1, Tpat_constant c2 -> const_compare c1 c2 = 0
+ | Tpat_tuple ps, Tpat_tuple qs -> compats ps qs
+ | Tpat_lazy p, Tpat_lazy q -> compat p q
+ | Tpat_construct (_, c1,ps1), Tpat_construct (_, c2,ps2) ->
+ c1.cstr_tag = c2.cstr_tag && compats ps1 ps2
+ | Tpat_variant(l1,Some p1, r1), Tpat_variant(l2,Some p2,_) ->
+ l1=l2 && compat p1 p2
+ | Tpat_variant (l1,None,r1), Tpat_variant(l2,None,_) ->
+ l1 = l2
+ | Tpat_variant (_, None, _), Tpat_variant (_,Some _, _) -> false
+ | Tpat_variant (_, Some _, _), Tpat_variant (_, None, _) -> false
+ | Tpat_record (l1,_),Tpat_record (l2,_) ->
+ let ps,qs = records_args l1 l2 in
+ compats ps qs
+ | Tpat_array ps, Tpat_array qs ->
+ List.length ps = List.length qs &&
+ compats ps qs
+ | _,_ ->
+ assert false
+
+and compats ps qs = match ps,qs with
+| [], [] -> true
+| p::ps, q::qs -> compat p q && compats ps qs
+| _,_ -> assert false
+
+exception Empty (* Empty pattern *)
+
+(****************************************)
+(* Utilities for retrieving type paths *)
+(****************************************)
+
+(* May need a clean copy, cf. PR#4745 *)
+let clean_copy ty =
+ if ty.level = Btype.generic_level then ty
+ else Subst.type_expr Subst.identity ty
+
+let get_type_path ty tenv =
+ let ty = Ctype.repr (Ctype.expand_head tenv (clean_copy ty)) in
+ match ty.desc with
+ | Tconstr (path,_,_) -> path
+ | _ -> fatal_error "Parmatch.get_type_path"
+
+(*************************************)
+(* Values as patterns pretty printer *)
+(*************************************)
+
+open Format
+;;
+
+let is_cons = function
+| {cstr_name = "::"} -> true
+| _ -> false
+
+let pretty_const c = match c with
+| Const_int i -> Printf.sprintf "%d" i
+| Const_char c -> Printf.sprintf "%C" c
+| Const_string (s, _) -> Printf.sprintf "%S" s
+| Const_float f -> Printf.sprintf "%s" f
+| Const_int32 i -> Printf.sprintf "%ldl" i
+| Const_int64 i -> Printf.sprintf "%LdL" i
+| Const_nativeint i -> Printf.sprintf "%ndn" i
+
+let rec pretty_val ppf v =
+ match v.pat_extra with
+ (cstr, _loc, _attrs) :: rem ->
+ begin match cstr with
+ | Tpat_unpack ->
+ fprintf ppf "@[(module %a)@]" pretty_val { v with pat_extra = rem }
+ | Tpat_constraint ctyp ->
+ fprintf ppf "@[(%a : _)@]" pretty_val { v with pat_extra = rem }
+ | Tpat_type _ ->
+ fprintf ppf "@[(# %a)@]" pretty_val { v with pat_extra = rem }
+ end
+ | [] ->
+ match v.pat_desc with
+ | Tpat_any -> fprintf ppf "_"
+ | Tpat_var (x,_) -> Ident.print ppf x
+ | Tpat_constant c -> fprintf ppf "%s" (pretty_const c)
+ | Tpat_tuple vs ->
+ fprintf ppf "@[(%a)@]" (pretty_vals ",") vs
+ | Tpat_construct (_, cstr, []) ->
+ fprintf ppf "%s" cstr.cstr_name
+ | Tpat_construct (_, cstr, [w]) ->
+ fprintf ppf "@[<2>%s@ %a@]" cstr.cstr_name pretty_arg w
+ | Tpat_construct (_, cstr, vs) ->
+ let name = cstr.cstr_name in
+ begin match (name, vs) with
+ ("::", [v1;v2]) ->
+ fprintf ppf "@[%a::@,%a@]" pretty_car v1 pretty_cdr v2
+ | _ ->
+ fprintf ppf "@[<2>%s@ @[(%a)@]@]" name (pretty_vals ",") vs
+ end
+ | Tpat_variant (l, None, _) ->
+ fprintf ppf "`%s" l
+ | Tpat_variant (l, Some w, _) ->
+ fprintf ppf "@[<2>`%s@ %a@]" l pretty_arg w
+ | Tpat_record (lvs,_) ->
+ fprintf ppf "@[{%a}@]"
+ pretty_lvals
+ (List.filter
+ (function
+ | (_,_,{pat_desc=Tpat_any}) -> false (* do not show lbl=_ *)
+ | _ -> true) lvs)
+ | Tpat_array vs ->
+ fprintf ppf "@[[| %a |]@]" (pretty_vals " ;") vs
+ | Tpat_lazy v ->
+ fprintf ppf "@[<2>lazy@ %a@]" pretty_arg v
+ | Tpat_alias (v, x,_) ->
+ fprintf ppf "@[(%a@ as %a)@]" pretty_val v Ident.print x
+ | Tpat_or (v,w,_) ->
+ fprintf ppf "@[(%a|@,%a)@]" pretty_or v pretty_or w
+
+and pretty_car ppf v = match v.pat_desc with
+| Tpat_construct (_,cstr, [_ ; _])
+ when is_cons cstr ->
+ fprintf ppf "(%a)" pretty_val v
+| _ -> pretty_val ppf v
+
+and pretty_cdr ppf v = match v.pat_desc with
+| Tpat_construct (_,cstr, [v1 ; v2])
+ when is_cons cstr ->
+ fprintf ppf "%a::@,%a" pretty_car v1 pretty_cdr v2
+| _ -> pretty_val ppf v
+
+and pretty_arg ppf v = match v.pat_desc with
+| Tpat_construct (_,_,_::_)
+| Tpat_variant (_, Some _, _) -> fprintf ppf "(%a)" pretty_val v
+| _ -> pretty_val ppf v
+
+and pretty_or ppf v = match v.pat_desc with
+| Tpat_or (v,w,_) ->
+ fprintf ppf "%a|@,%a" pretty_or v pretty_or w
+| _ -> pretty_val ppf v
+
+and pretty_vals sep ppf = function
+ | [] -> ()
+ | [v] -> pretty_val ppf v
+ | v::vs ->
+ fprintf ppf "%a%s@ %a" pretty_val v sep (pretty_vals sep) vs
+
+and pretty_lvals ppf = function
+ | [] -> ()
+ | [_,lbl,v] ->
+ fprintf ppf "%s=%a" lbl.lbl_name pretty_val v
+ | (_, lbl,v)::rest ->
+ fprintf ppf "%s=%a;@ %a"
+ lbl.lbl_name pretty_val v pretty_lvals rest
+
+let top_pretty ppf v =
+ fprintf ppf "@[%a@]@?" pretty_val v
+
+
+let pretty_pat p =
+ top_pretty Format.str_formatter p ;
+ prerr_string (Format.flush_str_formatter ())
+
+type matrix = pattern list list
+
+let pretty_line ps =
+ List.iter
+ (fun p ->
+ top_pretty Format.str_formatter p ;
+ prerr_string " <" ;
+ prerr_string (Format.flush_str_formatter ()) ;
+ prerr_string ">")
+ ps
+
+let pretty_matrix (pss : matrix) =
+ prerr_endline "begin matrix" ;
+ List.iter
+ (fun ps ->
+ pretty_line ps ;
+ prerr_endline "")
+ pss ;
+ prerr_endline "end matrix"
+
+
+(****************************)
+(* Utilities for matching *)
+(****************************)
+
+(* Check top matching *)
+let simple_match p1 p2 =
+ match p1.pat_desc, p2.pat_desc with
+ | Tpat_construct(_, c1, _), Tpat_construct(_, c2, _) ->
+ c1.cstr_tag = c2.cstr_tag
+ | Tpat_variant(l1, _, _), Tpat_variant(l2, _, _) ->
+ l1 = l2
+ | Tpat_constant(c1), Tpat_constant(c2) -> const_compare c1 c2 = 0
+ | Tpat_tuple _, Tpat_tuple _ -> true
+ | Tpat_lazy _, Tpat_lazy _ -> true
+ | Tpat_record _ , Tpat_record _ -> true
+ | Tpat_array p1s, Tpat_array p2s -> List.length p1s = List.length p2s
+ | _, (Tpat_any | Tpat_var(_)) -> true
+ | _, _ -> false
+
+
+
+
+(* extract record fields as a whole *)
+let record_arg p = match p.pat_desc with
+| Tpat_any -> []
+| Tpat_record (args,_) -> args
+| _ -> fatal_error "Parmatch.as_record"
+
+
+(* Raise Not_found when pos is not present in arg *)
+let get_field pos arg =
+ let _,_, p = List.find (fun (_,lbl,_) -> pos = lbl.lbl_pos) arg in
+ p
+
+let extract_fields omegas arg =
+ List.map
+ (fun (_,lbl,_) ->
+ try
+ get_field lbl.lbl_pos arg
+ with Not_found -> omega)
+ omegas
+
+let all_record_args lbls = match lbls with
+| (_,{lbl_all=lbl_all},_)::_ ->
+ let t =
+ Array.map
+ (fun lbl -> mknoloc (Longident.Lident "?temp?"), lbl,omega)
+ lbl_all in
+ List.iter
+ (fun ((_, lbl,_) as x) -> t.(lbl.lbl_pos) <- x)
+ lbls ;
+ Array.to_list t
+| _ -> fatal_error "Parmatch.all_record_args"
+
+
+(* Build argument list when p2 >= p1, where p1 is a simple pattern *)
+let rec simple_match_args p1 p2 = match p2.pat_desc with
+| Tpat_alias (p2,_,_) -> simple_match_args p1 p2
+| Tpat_construct(_, cstr, args) -> args
+| Tpat_variant(lab, Some arg, _) -> [arg]
+| Tpat_tuple(args) -> args
+| Tpat_record(args,_) -> extract_fields (record_arg p1) args
+| Tpat_array(args) -> args
+| Tpat_lazy arg -> [arg]
+| (Tpat_any | Tpat_var(_)) ->
+ begin match p1.pat_desc with
+ Tpat_construct(_, _,args) -> omega_list args
+ | Tpat_variant(_, Some _, _) -> [omega]
+ | Tpat_tuple(args) -> omega_list args
+ | Tpat_record(args,_) -> omega_list args
+ | Tpat_array(args) -> omega_list args
+ | Tpat_lazy _ -> [omega]
+ | _ -> []
+ end
+| _ -> []
+
+(*
+ Normalize a pattern ->
+ all arguments are omega (simple pattern) and no more variables
+*)
+
+let rec normalize_pat q = match q.pat_desc with
+ | Tpat_any | Tpat_constant _ -> q
+ | Tpat_var _ -> make_pat Tpat_any q.pat_type q.pat_env
+ | Tpat_alias (p,_,_) -> normalize_pat p
+ | Tpat_tuple (args) ->
+ make_pat (Tpat_tuple (omega_list args)) q.pat_type q.pat_env
+ | Tpat_construct (lid, c,args) ->
+ make_pat
+ (Tpat_construct (lid, c,omega_list args))
+ q.pat_type q.pat_env
+ | Tpat_variant (l, arg, row) ->
+ make_pat (Tpat_variant (l, may_map (fun _ -> omega) arg, row))
+ q.pat_type q.pat_env
+ | Tpat_array (args) ->
+ make_pat (Tpat_array (omega_list args)) q.pat_type q.pat_env
+ | Tpat_record (largs, closed) ->
+ make_pat
+ (Tpat_record (List.map (fun (lid,lbl,_) ->
+ lid, lbl,omega) largs, closed))
+ q.pat_type q.pat_env
+ | Tpat_lazy _ ->
+ make_pat (Tpat_lazy omega) q.pat_type q.pat_env
+ | Tpat_or _ -> fatal_error "Parmatch.normalize_pat"
+
+(*
+ Build normalized (cf. supra) discriminating pattern,
+ in the non-data type case
+*)
+
+let discr_pat q pss =
+
+ let rec acc_pat acc pss = match pss with
+ ({pat_desc = Tpat_alias (p,_,_)}::ps)::pss ->
+ acc_pat acc ((p::ps)::pss)
+ | ({pat_desc = Tpat_or (p1,p2,_)}::ps)::pss ->
+ acc_pat acc ((p1::ps)::(p2::ps)::pss)
+ | ({pat_desc = (Tpat_any | Tpat_var _)}::_)::pss ->
+ acc_pat acc pss
+ | (({pat_desc = Tpat_tuple _} as p)::_)::_ -> normalize_pat p
+ | (({pat_desc = Tpat_lazy _} as p)::_)::_ -> normalize_pat p
+ | (({pat_desc = Tpat_record (largs,closed)} as p)::_)::pss ->
+ let new_omegas =
+ List.fold_right
+ (fun (lid, lbl,_) r ->
+ try
+ let _ = get_field lbl.lbl_pos r in
+ r
+ with Not_found ->
+ (lid, lbl,omega)::r)
+ largs (record_arg acc)
+ in
+ acc_pat
+ (make_pat (Tpat_record (new_omegas, closed)) p.pat_type p.pat_env)
+ pss
+ | _ -> acc in
+
+ match normalize_pat q with
+ | {pat_desc= (Tpat_any | Tpat_record _)} as q -> acc_pat q pss
+ | q -> q
+
+(*
+ In case a matching value is found, set actual arguments
+ of the matching pattern.
+*)
+
+let rec read_args xs r = match xs,r with
+| [],_ -> [],r
+| _::xs, arg::rest ->
+ let args,rest = read_args xs rest in
+ arg::args,rest
+| _,_ ->
+ fatal_error "Parmatch.read_args"
+
+let do_set_args erase_mutable q r = match q with
+| {pat_desc = Tpat_tuple omegas} ->
+ let args,rest = read_args omegas r in
+ make_pat (Tpat_tuple args) q.pat_type q.pat_env::rest
+| {pat_desc = Tpat_record (omegas,closed)} ->
+ let args,rest = read_args omegas r in
+ make_pat
+ (Tpat_record
+ (List.map2 (fun (lid, lbl,_) arg ->
+ if
+ erase_mutable &&
+ (match lbl.lbl_mut with
+ | Mutable -> true | Immutable -> false)
+ then
+ lid, lbl, omega
+ else
+ lid, lbl, arg)
+ omegas args, closed))
+ q.pat_type q.pat_env::
+ rest
+| {pat_desc = Tpat_construct (lid, c,omegas)} ->
+ let args,rest = read_args omegas r in
+ make_pat
+ (Tpat_construct (lid, c,args))
+ q.pat_type q.pat_env::
+ rest
+| {pat_desc = Tpat_variant (l, omega, row)} ->
+ let arg, rest =
+ match omega, r with
+ Some _, a::r -> Some a, r
+ | None, r -> None, r
+ | _ -> assert false
+ in
+ make_pat
+ (Tpat_variant (l, arg, row)) q.pat_type q.pat_env::
+ rest
+| {pat_desc = Tpat_lazy omega} ->
+ begin match r with
+ arg::rest ->
+ make_pat (Tpat_lazy arg) q.pat_type q.pat_env::rest
+ | _ -> fatal_error "Parmatch.do_set_args (lazy)"
+ end
+| {pat_desc = Tpat_array omegas} ->
+ let args,rest = read_args omegas r in
+ make_pat
+ (Tpat_array args) q.pat_type q.pat_env::
+ rest
+| {pat_desc=Tpat_constant _|Tpat_any} ->
+ q::r (* case any is used in matching.ml *)
+| _ -> fatal_error "Parmatch.set_args"
+
+let set_args q r = do_set_args false q r
+and set_args_erase_mutable q r = do_set_args true q r
+
+(* filter pss acording to pattern q *)
+let filter_one q pss =
+ let rec filter_rec = function
+ ({pat_desc = Tpat_alias(p,_,_)}::ps)::pss ->
+ filter_rec ((p::ps)::pss)
+ | ({pat_desc = Tpat_or(p1,p2,_)}::ps)::pss ->
+ filter_rec ((p1::ps)::(p2::ps)::pss)
+ | (p::ps)::pss ->
+ if simple_match q p
+ then (simple_match_args q p @ ps) :: filter_rec pss
+ else filter_rec pss
+ | _ -> [] in
+ filter_rec pss
+
+(*
+ Filter pss in the ``extra case''. This applies :
+ - According to an extra constructor (datatype case, non-complete signature).
+ - Acordinng to anything (all-variables case).
+*)
+let filter_extra pss =
+ let rec filter_rec = function
+ ({pat_desc = Tpat_alias(p,_,_)}::ps)::pss ->
+ filter_rec ((p::ps)::pss)
+ | ({pat_desc = Tpat_or(p1,p2,_)}::ps)::pss ->
+ filter_rec ((p1::ps)::(p2::ps)::pss)
+ | ({pat_desc = (Tpat_any | Tpat_var(_))} :: qs) :: pss ->
+ qs :: filter_rec pss
+ | _::pss -> filter_rec pss
+ | [] -> [] in
+ filter_rec pss
+
+(*
+ Pattern p0 is the discriminating pattern,
+ returns [(q0,pss0) ; ... ; (qn,pssn)]
+ where the qi's are simple patterns and the pssi's are
+ matched matrices.
+
+ NOTES
+ * (qi,[]) is impossible.
+ * In the case when matching is useless (all-variable case),
+ returns []
+*)
+
+let filter_all pat0 pss =
+
+ let rec insert q qs env =
+ match env with
+ [] ->
+ let q0 = normalize_pat q in
+ [q0, [simple_match_args q0 q @ qs]]
+ | ((q0,pss) as c)::env ->
+ if simple_match q0 q
+ then (q0, ((simple_match_args q0 q @ qs) :: pss)) :: env
+ else c :: insert q qs env in
+
+ let rec filter_rec env = function
+ ({pat_desc = Tpat_alias(p,_,_)}::ps)::pss ->
+ filter_rec env ((p::ps)::pss)
+ | ({pat_desc = Tpat_or(p1,p2,_)}::ps)::pss ->
+ filter_rec env ((p1::ps)::(p2::ps)::pss)
+ | ({pat_desc = (Tpat_any | Tpat_var(_))}::_)::pss ->
+ filter_rec env pss
+ | (p::ps)::pss ->
+ filter_rec (insert p ps env) pss
+ | _ -> env
+
+ and filter_omega env = function
+ ({pat_desc = Tpat_alias(p,_,_)}::ps)::pss ->
+ filter_omega env ((p::ps)::pss)
+ | ({pat_desc = Tpat_or(p1,p2,_)}::ps)::pss ->
+ filter_omega env ((p1::ps)::(p2::ps)::pss)
+ | ({pat_desc = (Tpat_any | Tpat_var(_))}::ps)::pss ->
+ filter_omega
+ (List.map (fun (q,qss) -> (q,(simple_match_args q omega @ ps) :: qss))
+ env)
+ pss
+ | _::pss -> filter_omega env pss
+ | [] -> env in
+
+ filter_omega
+ (filter_rec
+ (match pat0.pat_desc with
+ (Tpat_record(_) | Tpat_tuple(_) | Tpat_lazy(_)) -> [pat0,[]]
+ | _ -> [])
+ pss)
+ pss
+
+(* Variant related functions *)
+
+let rec set_last a = function
+ [] -> []
+ | [_] -> [a]
+ | x::l -> x :: set_last a l
+
+(* mark constructor lines for failure when they are incomplete *)
+let rec mark_partial = function
+ ({pat_desc = Tpat_alias(p,_,_)}::ps)::pss ->
+ mark_partial ((p::ps)::pss)
+ | ({pat_desc = Tpat_or(p1,p2,_)}::ps)::pss ->
+ mark_partial ((p1::ps)::(p2::ps)::pss)
+ | ({pat_desc = (Tpat_any | Tpat_var(_))} :: _ as ps) :: pss ->
+ ps :: mark_partial pss
+ | ps::pss ->
+ (set_last zero ps) :: mark_partial pss
+ | [] -> []
+
+let close_variant env row =
+ let row = Btype.row_repr row in
+ let nm =
+ List.fold_left
+ (fun nm (tag,f) ->
+ match Btype.row_field_repr f with
+ | Reither(_, _, false, e) ->
+ (* m=false means that this tag is not explicitly matched *)
+ Btype.set_row_field e Rabsent;
+ None
+ | Rabsent | Reither (_, _, true, _) | Rpresent _ -> nm)
+ row.row_name row.row_fields in
+ if not row.row_closed || nm != row.row_name then begin
+ (* this unification cannot fail *)
+ Ctype.unify env row.row_more
+ (Btype.newgenty
+ (Tvariant {row with row_fields = []; row_more = Btype.newgenvar();
+ row_closed = true; row_name = nm}))
+ end
+
+let row_of_pat pat =
+ match Ctype.expand_head pat.pat_env pat.pat_type with
+ {desc = Tvariant row} -> Btype.row_repr row
+ | _ -> assert false
+
+(*
+ Check whether the first column of env makes up a complete signature or
+ not.
+*)
+
+let generalized_constructor x =
+ match x with
+ ({pat_desc = Tpat_construct(_,c,_);pat_env=env},_) ->
+ c.cstr_generalized
+ | _ -> assert false
+
+let clean_env env =
+ let rec loop =
+ function
+ | [] -> []
+ | x :: xs ->
+ if generalized_constructor x then loop xs else x :: loop xs
+ in
+ loop env
+
+let full_match ignore_generalized closing env = match env with
+| ({pat_desc = Tpat_construct(_,c,_);pat_type=typ},_) :: _ ->
+ if c.cstr_consts < 0 then false (* extensions *)
+ else
+ if ignore_generalized then
+ (* remove generalized constructors;
+ those cases will be handled separately *)
+ let env = clean_env env in
+ List.length env = c.cstr_normal
+ else
+ List.length env = c.cstr_consts + c.cstr_nonconsts
+
+| ({pat_desc = Tpat_variant _} as p,_) :: _ ->
+ let fields =
+ List.map
+ (function ({pat_desc = Tpat_variant (tag, _, _)}, _) -> tag
+ | _ -> assert false)
+ env
+ in
+ let row = row_of_pat p in
+ if closing && not (Btype.row_fixed row) then
+ (* closing=true, we are considering the variant as closed *)
+ List.for_all
+ (fun (tag,f) ->
+ match Btype.row_field_repr f with
+ Rabsent | Reither(_, _, false, _) -> true
+ | Reither (_, _, true, _)
+ (* m=true, do not discard matched tags, rather warn *)
+ | Rpresent _ -> List.mem tag fields)
+ row.row_fields
+ else
+ row.row_closed &&
+ List.for_all
+ (fun (tag,f) ->
+ Btype.row_field_repr f = Rabsent || List.mem tag fields)
+ row.row_fields
+| ({pat_desc = Tpat_constant(Const_char _)},_) :: _ ->
+ List.length env = 256
+| ({pat_desc = Tpat_constant(_)},_) :: _ -> false
+| ({pat_desc = Tpat_tuple(_)},_) :: _ -> true
+| ({pat_desc = Tpat_record(_)},_) :: _ -> true
+| ({pat_desc = Tpat_array(_)},_) :: _ -> false
+| ({pat_desc = Tpat_lazy(_)},_) :: _ -> true
+| _ -> fatal_error "Parmatch.full_match"
+
+let full_match_gadt env = match env with
+ | ({pat_desc = Tpat_construct(_,c,_);pat_type=typ},_) :: _ ->
+ List.length env = c.cstr_consts + c.cstr_nonconsts
+ | _ -> true
+
+let extendable_match env = match env with
+| ({pat_desc=Tpat_construct(_,{cstr_tag=(Cstr_constant _|Cstr_block _)},_)}
+ as p,_) :: _ ->
+ let path = get_type_path p.pat_type p.pat_env in
+ not
+ (Path.same path Predef.path_bool ||
+ Path.same path Predef.path_list ||
+ Path.same path Predef.path_option)
+| _ -> false
+
+
+let should_extend ext env = match ext with
+| None -> false
+| Some ext -> match env with
+ | ({pat_desc =
+ Tpat_construct(_, {cstr_tag=(Cstr_constant _|Cstr_block _)},_)}
+ as p, _) :: _ ->
+ let path = get_type_path p.pat_type p.pat_env in
+ Path.same path ext
+ | _ -> false
+
+(* complement constructor tags *)
+let complete_tags nconsts nconstrs tags =
+ let seen_const = Array.make nconsts false
+ and seen_constr = Array.make nconstrs false in
+ List.iter
+ (function
+ | Cstr_constant i -> seen_const.(i) <- true
+ | Cstr_block i -> seen_constr.(i) <- true
+ | _ -> assert false)
+ tags ;
+ let r = ref [] in
+ for i = 0 to nconsts-1 do
+ if not seen_const.(i) then
+ r := Cstr_constant i :: !r
+ done ;
+ for i = 0 to nconstrs-1 do
+ if not seen_constr.(i) then
+ r := Cstr_block i :: !r
+ done ;
+ !r
+
+(* build a pattern from a constructor list *)
+let pat_of_constr ex_pat cstr =
+ {ex_pat with pat_desc =
+ Tpat_construct (mknoloc (Longident.Lident "?pat_of_constr?"),
+ cstr,omegas cstr.cstr_arity)}
+
+let rec pat_of_constrs ex_pat = function
+| [] -> raise Empty
+| [cstr] -> pat_of_constr ex_pat cstr
+| cstr::rem ->
+ {ex_pat with
+ pat_desc=
+ Tpat_or
+ (pat_of_constr ex_pat cstr,
+ pat_of_constrs ex_pat rem, None)}
+
+let rec get_variant_constructors env ty =
+ match (Ctype.repr ty).desc with
+ | Tconstr (path,_,_) -> begin
+ match Env.find_type path env with
+ | {type_kind=Type_variant _} ->
+ fst (Env.find_type_descrs path env)
+ | {type_manifest = Some _} ->
+ get_variant_constructors env
+ (Ctype.expand_head_once env (clean_copy ty))
+ | _ -> fatal_error "Parmatch.get_variant_constructors"
+ end
+ | _ -> fatal_error "Parmatch.get_variant_constructors"
+
+let rec map_filter f =
+ function
+ [] -> []
+ | x :: xs ->
+ match f x with
+ | None -> map_filter f xs
+ | Some y -> y :: map_filter f xs
+
+(* Sends back a pattern that complements constructor tags all_tag *)
+let complete_constrs p all_tags =
+ match p.pat_desc with
+ | Tpat_construct (_,c,_) ->
+ let not_tags = complete_tags c.cstr_consts c.cstr_nonconsts all_tags in
+ let constrs = get_variant_constructors p.pat_env c.cstr_res in
+ map_filter
+ (fun cnstr ->
+ if List.mem cnstr.cstr_tag not_tags then Some cnstr else None)
+ constrs
+ | _ -> fatal_error "Parmatch.complete_constr"
+
+
+(* Auxiliary for build_other *)
+
+let build_other_constant proj make first next p env =
+ let all = List.map (fun (p, _) -> proj p.pat_desc) env in
+ let rec try_const i =
+ if List.mem i all
+ then try_const (next i)
+ else make_pat (make i) p.pat_type p.pat_env
+ in try_const first
+
+(*
+ Builds a pattern that is incompatible with all patterns in
+ in the first column of env
+*)
+
+let build_other ext env = match env with
+| ({pat_desc = Tpat_construct (lid,
+ ({cstr_tag=Cstr_extension _} as c),_)},_) :: _ ->
+ let c = {c with cstr_name = "*extension*"} in
+ make_pat (Tpat_construct(lid, c, [])) Ctype.none Env.empty
+| ({pat_desc = Tpat_construct (_, _,_)} as p,_) :: _ ->
+ begin match ext with
+ | Some ext when Path.same ext (get_type_path p.pat_type p.pat_env) ->
+ extra_pat
+ | _ ->
+ let get_tag = function
+ | {pat_desc = Tpat_construct (_,c,_)} -> c.cstr_tag
+ | _ -> fatal_error "Parmatch.get_tag" in
+ let all_tags = List.map (fun (p,_) -> get_tag p) env in
+ pat_of_constrs p (complete_constrs p all_tags)
+ end
+| ({pat_desc = Tpat_variant (_,_,r)} as p,_) :: _ ->
+ let tags =
+ List.map
+ (function ({pat_desc = Tpat_variant (tag, _, _)}, _) -> tag
+ | _ -> assert false)
+ env
+ in
+ let row = row_of_pat p in
+ let make_other_pat tag const =
+ let arg = if const then None else Some omega in
+ make_pat (Tpat_variant(tag, arg, r)) p.pat_type p.pat_env in
+ begin match
+ List.fold_left
+ (fun others (tag,f) ->
+ if List.mem tag tags then others else
+ match Btype.row_field_repr f with
+ Rabsent (* | Reither _ *) -> others
+ (* This one is called after erasing pattern info *)
+ | Reither (c, _, _, _) -> make_other_pat tag c :: others
+ | Rpresent arg -> make_other_pat tag (arg = None) :: others)
+ [] row.row_fields
+ with
+ [] ->
+ make_other_pat "AnyExtraTag" true
+ | pat::other_pats ->
+ List.fold_left
+ (fun p_res pat ->
+ make_pat (Tpat_or (pat, p_res, None)) p.pat_type p.pat_env)
+ pat other_pats
+ end
+| ({pat_desc = Tpat_constant(Const_char _)} as p,_) :: _ ->
+ let all_chars =
+ List.map
+ (fun (p,_) -> match p.pat_desc with
+ | Tpat_constant (Const_char c) -> c
+ | _ -> assert false)
+ env in
+
+ let rec find_other i imax =
+ if i > imax then raise Not_found
+ else
+ let ci = Char.chr i in
+ if List.mem ci all_chars then
+ find_other (i+1) imax
+ else
+ make_pat (Tpat_constant (Const_char ci)) p.pat_type p.pat_env in
+ let rec try_chars = function
+ | [] -> omega
+ | (c1,c2) :: rest ->
+ try
+ find_other (Char.code c1) (Char.code c2)
+ with
+ | Not_found -> try_chars rest in
+
+ try_chars
+ [ 'a', 'z' ; 'A', 'Z' ; '0', '9' ;
+ ' ', '~' ; Char.chr 0 , Char.chr 255]
+
+| ({pat_desc=(Tpat_constant (Const_int _))} as p,_) :: _ ->
+ build_other_constant
+ (function Tpat_constant(Const_int i) -> i | _ -> assert false)
+ (function i -> Tpat_constant(Const_int i))
+ 0 succ p env
+| ({pat_desc=(Tpat_constant (Const_int32 _))} as p,_) :: _ ->
+ build_other_constant
+ (function Tpat_constant(Const_int32 i) -> i | _ -> assert false)
+ (function i -> Tpat_constant(Const_int32 i))
+ 0l Int32.succ p env
+| ({pat_desc=(Tpat_constant (Const_int64 _))} as p,_) :: _ ->
+ build_other_constant
+ (function Tpat_constant(Const_int64 i) -> i | _ -> assert false)
+ (function i -> Tpat_constant(Const_int64 i))
+ 0L Int64.succ p env
+| ({pat_desc=(Tpat_constant (Const_nativeint _))} as p,_) :: _ ->
+ build_other_constant
+ (function Tpat_constant(Const_nativeint i) -> i | _ -> assert false)
+ (function i -> Tpat_constant(Const_nativeint i))
+ 0n Nativeint.succ p env
+| ({pat_desc=(Tpat_constant (Const_string _))} as p,_) :: _ ->
+ build_other_constant
+ (function Tpat_constant(Const_string (s, _)) -> String.length s
+ | _ -> assert false)
+ (function i -> Tpat_constant(Const_string(String.make i '*', None)))
+ 0 succ p env
+| ({pat_desc=(Tpat_constant (Const_float _))} as p,_) :: _ ->
+ build_other_constant
+ (function Tpat_constant(Const_float f) -> float_of_string f
+ | _ -> assert false)
+ (function f -> Tpat_constant(Const_float (string_of_float f)))
+ 0.0 (fun f -> f +. 1.0) p env
+
+| ({pat_desc = Tpat_array args} as p,_)::_ ->
+ let all_lengths =
+ List.map
+ (fun (p,_) -> match p.pat_desc with
+ | Tpat_array args -> List.length args
+ | _ -> assert false)
+ env in
+ let rec try_arrays l =
+ if List.mem l all_lengths then try_arrays (l+1)
+ else
+ make_pat
+ (Tpat_array (omegas l))
+ p.pat_type p.pat_env in
+ try_arrays 0
+| [] -> omega
+| _ -> omega
+
+let build_other_gadt ext env =
+ match env with
+ | ({pat_desc = Tpat_construct _} as p,_) :: _ ->
+ let get_tag = function
+ | {pat_desc = Tpat_construct (_,c,_)} -> c.cstr_tag
+ | _ -> fatal_error "Parmatch.get_tag" in
+ let all_tags = List.map (fun (p,_) -> get_tag p) env in
+ let cnstrs = complete_constrs p all_tags in
+ let pats = List.map (pat_of_constr p) cnstrs in
+ (* List.iter (Format.eprintf "%a@." top_pretty) pats;
+ Format.eprintf "@.@."; *)
+ pats
+ | _ -> assert false
+
+(*
+ Core function :
+ Is the last row of pattern matrix pss + qs satisfiable ?
+ That is :
+ Does there exists at least one value vector, es such that :
+ 1- for all ps in pss ps # es (ps and es are not compatible)
+ 2- qs <= es (es matches qs)
+*)
+
+let rec has_instance p = match p.pat_desc with
+ | Tpat_variant (l,_,r) when is_absent l r -> false
+ | Tpat_any | Tpat_var _ | Tpat_constant _ | Tpat_variant (_,None,_) -> true
+ | Tpat_alias (p,_,_) | Tpat_variant (_,Some p,_) -> has_instance p
+ | Tpat_or (p1,p2,_) -> has_instance p1 || has_instance p2
+ | Tpat_construct (_,_,ps) | Tpat_tuple ps | Tpat_array ps ->
+ has_instances ps
+ | Tpat_record (lps,_) -> has_instances (List.map (fun (_,_,x) -> x) lps)
+ | Tpat_lazy p
+ -> has_instance p
+
+
+and has_instances = function
+ | [] -> true
+ | q::rem -> has_instance q && has_instances rem
+
+let rec satisfiable pss qs = match pss with
+| [] -> has_instances qs
+| _ ->
+ match qs with
+ | [] -> false
+ | {pat_desc = Tpat_or(q1,q2,_)}::qs ->
+ satisfiable pss (q1::qs) || satisfiable pss (q2::qs)
+ | {pat_desc = Tpat_alias(q,_,_)}::qs ->
+ satisfiable pss (q::qs)
+ | {pat_desc = (Tpat_any | Tpat_var(_))}::qs ->
+ let q0 = discr_pat omega pss in
+ begin match filter_all q0 pss with
+ (* first column of pss is made of variables only *)
+ | [] -> satisfiable (filter_extra pss) qs
+ | constrs ->
+ if full_match false false constrs then
+ List.exists
+ (fun (p,pss) ->
+ not (is_absent_pat p) &&
+ satisfiable pss (simple_match_args p omega @ qs))
+ constrs
+ else
+ satisfiable (filter_extra pss) qs
+ end
+ | {pat_desc=Tpat_variant (l,_,r)}::_ when is_absent l r -> false
+ | q::qs ->
+ let q0 = discr_pat q pss in
+ satisfiable (filter_one q0 pss) (simple_match_args q0 q @ qs)
+
+(*
+ Now another satisfiable function that additionally
+ supplies an example of a matching value.
+
+ This function should be called for exhaustiveness check only.
+*)
+
+type 'a result =
+ | Rnone (* No matching value *)
+ | Rsome of 'a (* This matching value *)
+
+let rec orify_many =
+ let orify x y =
+ make_pat (Tpat_or (x, y, None)) x.pat_type x.pat_env
+ in
+ function
+ | [] -> assert false
+ | [x] -> x
+ | x :: xs -> orify x (orify_many xs)
+
+let rec try_many f = function
+ | [] -> Rnone
+ | (p,pss)::rest ->
+ match f (p,pss) with
+ | Rnone -> try_many f rest
+ | r -> r
+
+let rappend r1 r2 =
+ match r1, r2 with
+ | Rnone, _ -> r2
+ | _, Rnone -> r1
+ | Rsome l1, Rsome l2 -> Rsome (l1 @ l2)
+
+let rec try_many_gadt f = function
+ | [] -> Rnone
+ | (p,pss)::rest ->
+ rappend (f (p, pss)) (try_many_gadt f rest)
+
+let rec exhaust ext pss n = match pss with
+| [] -> Rsome (omegas n)
+| []::_ -> Rnone
+| pss ->
+ let q0 = discr_pat omega pss in
+ begin match filter_all q0 pss with
+ (* first column of pss is made of variables only *)
+ | [] ->
+ begin match exhaust ext (filter_extra pss) (n-1) with
+ | Rsome r -> Rsome (q0::r)
+ | r -> r
+ end
+ | constrs ->
+ let try_non_omega (p,pss) =
+ if is_absent_pat p then
+ Rnone
+ else
+ match
+ exhaust
+ ext pss (List.length (simple_match_args p omega) + n - 1)
+ with
+ | Rsome r -> Rsome (set_args p r)
+ | r -> r in
+ if
+ full_match true false constrs && not (should_extend ext constrs)
+ then
+ try_many try_non_omega constrs
+ else
+ (*
+ D = filter_extra pss is the default matrix
+ as it is included in pss, one can avoid
+ recursive calls on specialized matrices,
+ Essentially :
+ * D exhaustive => pss exhaustive
+ * D non-exhaustive => we have a non-filtered value
+ *)
+ let r = exhaust ext (filter_extra pss) (n-1) in
+ match r with
+ | Rnone -> Rnone
+ | Rsome r ->
+ try
+ Rsome (build_other ext constrs::r)
+ with
+ (* cannot occur, since constructors don't make a full signature *)
+ | Empty -> fatal_error "Parmatch.exhaust"
+ end
+
+let combinations f lst lst' =
+ let rec iter2 x =
+ function
+ [] -> []
+ | y :: ys ->
+ f x y :: iter2 x ys
+ in
+ let rec iter =
+ function
+ [] -> []
+ | x :: xs -> iter2 x lst' @ iter xs
+ in
+ iter lst
+
+(*
+let print_pat pat =
+ let rec string_of_pat pat =
+ match pat.pat_desc with
+ Tpat_var _ -> "v"
+ | Tpat_any -> "_"
+ | Tpat_alias (p, x) -> Printf.sprintf "(%s) as ?" (string_of_pat p)
+ | Tpat_constant n -> "0"
+ | Tpat_construct (_, lid, _) ->
+ Printf.sprintf "%s" (String.concat "." (Longident.flatten lid.txt))
+ | Tpat_lazy p ->
+ Printf.sprintf "(lazy %s)" (string_of_pat p)
+ | Tpat_or (p1,p2,_) ->
+ Printf.sprintf "(%s | %s)" (string_of_pat p1) (string_of_pat p2)
+ | Tpat_tuple list ->
+ Printf.sprintf "(%s)" (String.concat "," (List.map string_of_pat list))
+ | Tpat_variant (_, _, _) -> "variant"
+ | Tpat_record (_, _) -> "record"
+ | Tpat_array _ -> "array"
+ in
+ Printf.fprintf stderr "PAT[%s]\n%!" (string_of_pat pat)
+*)
+
+(* strictly more powerful than exhaust; however, exhaust
+ was kept for backwards compatibility *)
+let rec exhaust_gadt (ext:Path.t option) pss n = match pss with
+| [] -> Rsome [omegas n]
+| []::_ -> Rnone
+| pss ->
+ let q0 = discr_pat omega pss in
+ begin match filter_all q0 pss with
+ (* first column of pss is made of variables only *)
+ | [] ->
+ begin match exhaust_gadt ext (filter_extra pss) (n-1) with
+ | Rsome r -> Rsome (List.map (fun row -> q0::row) r)
+ | r -> r
+ end
+ | constrs ->
+ let try_non_omega (p,pss) =
+ if is_absent_pat p then
+ Rnone
+ else
+ match
+ exhaust_gadt
+ ext pss (List.length (simple_match_args p omega) + n - 1)
+ with
+ | Rsome r -> Rsome (List.map (fun row -> (set_args p row)) r)
+ | r -> r in
+ let before = try_many_gadt try_non_omega constrs in
+ if
+ full_match_gadt constrs && not (should_extend ext constrs)
+ then
+ before
+ else
+ (*
+ D = filter_extra pss is the default matrix
+ as it is included in pss, one can avoid
+ recursive calls on specialized matrices,
+ Essentially :
+ * D exhaustive => pss exhaustive
+ * D non-exhaustive => we have a non-filtered value
+ *)
+ let r = exhaust_gadt ext (filter_extra pss) (n-1) in
+ match r with
+ | Rnone -> before
+ | Rsome r ->
+ try
+ let missing_trailing = build_other_gadt ext constrs in
+ let dug =
+ combinations
+ (fun head tail -> head :: tail)
+ missing_trailing
+ r
+ in
+ match before with
+ | Rnone -> Rsome dug
+ | Rsome x -> Rsome (x @ dug)
+ with
+ (* cannot occur, since constructors don't make a full signature *)
+ | Empty -> fatal_error "Parmatch.exhaust"
+ end
+
+let exhaust_gadt ext pss n =
+ let ret = exhaust_gadt ext pss n in
+ match ret with
+ Rnone -> Rnone
+ | Rsome lst ->
+ (* The following line is needed to compile stdlib/printf.ml *)
+ if lst = [] then Rsome (omegas n) else
+ let singletons =
+ List.map
+ (function
+ [x] -> x
+ | _ -> assert false)
+ lst
+ in
+ Rsome [orify_many singletons]
+
+(*
+ Another exhaustiveness check, enforcing variant typing.
+ Note that it does not check exact exhaustiveness, but whether a
+ matching could be made exhaustive by closing all variant types.
+ When this is true of all other columns, the current column is left
+ open (even if it means that the whole matching is not exhaustive as
+ a result).
+ When this is false for the matrix minus the current column, and the
+ current column is composed of variant tags, we close the variant
+ (even if it doesn't help in making the matching exhaustive).
+*)
+
+let rec pressure_variants tdefs = function
+ | [] -> false
+ | []::_ -> true
+ | pss ->
+ let q0 = discr_pat omega pss in
+ begin match filter_all q0 pss with
+ [] -> pressure_variants tdefs (filter_extra pss)
+ | constrs ->
+ let rec try_non_omega = function
+ (p,pss) :: rem ->
+ let ok = pressure_variants tdefs pss in
+ try_non_omega rem && ok
+ | [] -> true
+ in
+ if full_match true (tdefs=None) constrs then
+ try_non_omega constrs
+ else if tdefs = None then
+ pressure_variants None (filter_extra pss)
+ else
+ let full = full_match true true constrs in
+ let ok =
+ if full then try_non_omega constrs
+ else try_non_omega (filter_all q0 (mark_partial pss))
+ in
+ begin match constrs, tdefs with
+ ({pat_desc=Tpat_variant _} as p,_):: _, Some env ->
+ let row = row_of_pat p in
+ if Btype.row_fixed row
+ || pressure_variants None (filter_extra pss) then ()
+ else close_variant env row
+ | _ -> ()
+ end;
+ ok
+ end
+
+
+(* Yet another satisfiable fonction *)
+
+(*
+ This time every_satisfiable pss qs checks the
+ utility of every expansion of qs.
+ Expansion means expansion of or-patterns inside qs
+*)
+
+type answer =
+ | Used (* Useful pattern *)
+ | Unused (* Useless pattern *)
+ | Upartial of Typedtree.pattern list (* Mixed, with list of useless ones *)
+
+
+
+(* this row type enable column processing inside the matrix
+ - left -> elements not to be processed,
+ - right -> elements to be processed
+*)
+type 'a row = {no_ors : 'a list ; ors : 'a list ; active : 'a list}
+
+
+let pretty_row {ors=ors ; no_ors=no_ors; active=active} =
+ pretty_line ors ; prerr_string " *" ;
+ pretty_line no_ors ; prerr_string " *" ;
+ pretty_line active
+
+let pretty_rows rs =
+ prerr_endline "begin matrix" ;
+ List.iter
+ (fun r ->
+ pretty_row r ;
+ prerr_endline "")
+ rs ;
+ prerr_endline "end matrix"
+
+(* Initial build *)
+let make_row ps = {ors=[] ; no_ors=[]; active=ps}
+
+let make_rows pss = List.map make_row pss
+
+
+(* Useful to detect and expand or pats inside as pats *)
+let rec unalias p = match p.pat_desc with
+| Tpat_alias (p,_,_) -> unalias p
+| _ -> p
+
+
+let is_var p = match (unalias p).pat_desc with
+| Tpat_any|Tpat_var _ -> true
+| _ -> false
+
+let is_var_column rs =
+ List.for_all
+ (fun r -> match r.active with
+ | p::_ -> is_var p
+ | [] -> assert false)
+ rs
+
+(* Standard or-args for left-to-right matching *)
+let rec or_args p = match p.pat_desc with
+| Tpat_or (p1,p2,_) -> p1,p2
+| Tpat_alias (p,_,_) -> or_args p
+| _ -> assert false
+
+(* Just remove current column *)
+let remove r = match r.active with
+| _::rem -> {r with active=rem}
+| [] -> assert false
+
+let remove_column rs = List.map remove rs
+
+(* Current column has been processed *)
+let push_no_or r = match r.active with
+| p::rem -> { r with no_ors = p::r.no_ors ; active=rem}
+| [] -> assert false
+
+let push_or r = match r.active with
+| p::rem -> { r with ors = p::r.ors ; active=rem}
+| [] -> assert false
+
+let push_or_column rs = List.map push_or rs
+and push_no_or_column rs = List.map push_no_or rs
+
+(* Those are adaptations of the previous homonymous functions that
+ work on the current column, instead of the first column
+*)
+
+let discr_pat q rs =
+ discr_pat q (List.map (fun r -> r.active) rs)
+
+let filter_one q rs =
+ let rec filter_rec rs = match rs with
+ | [] -> []
+ | r::rem ->
+ match r.active with
+ | [] -> assert false
+ | {pat_desc = Tpat_alias(p,_,_)}::ps ->
+ filter_rec ({r with active = p::ps}::rem)
+ | {pat_desc = Tpat_or(p1,p2,_)}::ps ->
+ filter_rec
+ ({r with active = p1::ps}::
+ {r with active = p2::ps}::
+ rem)
+ | p::ps ->
+ if simple_match q p then
+ {r with active=simple_match_args q p @ ps} :: filter_rec rem
+ else
+ filter_rec rem in
+ filter_rec rs
+
+
+(* Back to normal matrices *)
+let make_vector r = r.no_ors
+
+let make_matrix rs = List.map make_vector rs
+
+
+(* Standard union on answers *)
+let union_res r1 r2 = match r1, r2 with
+| (Unused,_)
+| (_, Unused) -> Unused
+| Used,_ -> r2
+| _, Used -> r1
+| Upartial u1, Upartial u2 -> Upartial (u1@u2)
+
+(* propose or pats for expansion *)
+let extract_elements qs =
+ let rec do_rec seen = function
+ | [] -> []
+ | q::rem ->
+ {no_ors= List.rev_append seen rem @ qs.no_ors ;
+ ors=[] ;
+ active = [q]}::
+ do_rec (q::seen) rem in
+ do_rec [] qs.ors
+
+(* idem for matrices *)
+let transpose rs = match rs with
+| [] -> assert false
+| r::rem ->
+ let i = List.map (fun x -> [x]) r in
+ List.fold_left
+ (List.map2 (fun r x -> x::r))
+ i rem
+
+let extract_columns pss qs = match pss with
+| [] -> List.map (fun _ -> []) qs.ors
+| _ ->
+ let rows = List.map extract_elements pss in
+ transpose rows
+
+(* Core function
+ The idea is to first look for or patterns (recursive case), then
+ check or-patterns argument usefulness (terminal case)
+*)
+
+let rec every_satisfiables pss qs = match qs.active with
+| [] ->
+ (* qs is now partitionned, check usefulness *)
+ begin match qs.ors with
+ | [] -> (* no or-patterns *)
+ if satisfiable (make_matrix pss) (make_vector qs) then
+ Used
+ else
+ Unused
+ | _ -> (* n or-patterns -> 2n expansions *)
+ List.fold_right2
+ (fun pss qs r -> match r with
+ | Unused -> Unused
+ | _ ->
+ match qs.active with
+ | [q] ->
+ let q1,q2 = or_args q in
+ let r_loc = every_both pss qs q1 q2 in
+ union_res r r_loc
+ | _ -> assert false)
+ (extract_columns pss qs) (extract_elements qs)
+ Used
+ end
+| q::rem ->
+ let uq = unalias q in
+ begin match uq.pat_desc with
+ | Tpat_any | Tpat_var _ ->
+ if is_var_column pss then
+(* forget about ``all-variable'' columns now *)
+ every_satisfiables (remove_column pss) (remove qs)
+ else
+(* otherwise this is direct food for satisfiable *)
+ every_satisfiables (push_no_or_column pss) (push_no_or qs)
+ | Tpat_or (q1,q2,_) ->
+ if
+ q1.pat_loc.Location.loc_ghost &&
+ q2.pat_loc.Location.loc_ghost
+ then
+(* syntactically generated or-pats should not be expanded *)
+ every_satisfiables (push_no_or_column pss) (push_no_or qs)
+ else
+(* this is a real or-pattern *)
+ every_satisfiables (push_or_column pss) (push_or qs)
+ | Tpat_variant (l,_,r) when is_absent l r -> (* Ah Jacques... *)
+ Unused
+ | _ ->
+(* standard case, filter matrix *)
+ let q0 = discr_pat q pss in
+ every_satisfiables
+ (filter_one q0 pss)
+ {qs with active=simple_match_args q0 q @ rem}
+ end
+
+(*
+ This function ``every_both'' performs the usefulness check
+ of or-pat q1|q2.
+ The trick is to call every_satisfied twice with
+ current active columns restricted to q1 and q2,
+ That way,
+ - others orpats in qs.ors will not get expanded.
+ - all matching work performed on qs.no_ors is not performed again.
+ *)
+and every_both pss qs q1 q2 =
+ let qs1 = {qs with active=[q1]}
+ and qs2 = {qs with active=[q2]} in
+ let r1 = every_satisfiables pss qs1
+ and r2 = every_satisfiables (if compat q1 q2 then qs1::pss else pss) qs2 in
+ match r1 with
+ | Unused ->
+ begin match r2 with
+ | Unused -> Unused
+ | Used -> Upartial [q1]
+ | Upartial u2 -> Upartial (q1::u2)
+ end
+ | Used ->
+ begin match r2 with
+ | Unused -> Upartial [q2]
+ | _ -> r2
+ end
+ | Upartial u1 ->
+ begin match r2 with
+ | Unused -> Upartial (u1@[q2])
+ | Used -> r1
+ | Upartial u2 -> Upartial (u1 @ u2)
+ end
+
+
+
+
+(* le_pat p q means, forall V, V matches q implies V matches p *)
+let rec le_pat p q =
+ match (p.pat_desc, q.pat_desc) with
+ | (Tpat_var _|Tpat_any),_ -> true
+ | Tpat_alias(p,_,_), _ -> le_pat p q
+ | _, Tpat_alias(q,_,_) -> le_pat p q
+ | Tpat_constant(c1), Tpat_constant(c2) -> const_compare c1 c2 = 0
+ | Tpat_construct(_,c1,ps), Tpat_construct(_,c2,qs) ->
+ c1.cstr_tag = c2.cstr_tag && le_pats ps qs
+ | Tpat_variant(l1,Some p1,_), Tpat_variant(l2,Some p2,_) ->
+ (l1 = l2 && le_pat p1 p2)
+ | Tpat_variant(l1,None,r1), Tpat_variant(l2,None,_) ->
+ l1 = l2
+ | Tpat_variant(_,_,_), Tpat_variant(_,_,_) -> false
+ | Tpat_tuple(ps), Tpat_tuple(qs) -> le_pats ps qs
+ | Tpat_lazy p, Tpat_lazy q -> le_pat p q
+ | Tpat_record (l1,_), Tpat_record (l2,_) ->
+ let ps,qs = records_args l1 l2 in
+ le_pats ps qs
+ | Tpat_array(ps), Tpat_array(qs) ->
+ List.length ps = List.length qs && le_pats ps qs
+(* In all other cases, enumeration is performed *)
+ | _,_ -> not (satisfiable [[p]] [q])
+
+and le_pats ps qs =
+ match ps,qs with
+ p::ps, q::qs -> le_pat p q && le_pats ps qs
+ | _, _ -> true
+
+let get_mins le ps =
+ let rec select_rec r = function
+ [] -> r
+ | p::ps ->
+ if List.exists (fun p0 -> le p0 p) ps
+ then select_rec r ps
+ else select_rec (p::r) ps in
+ select_rec [] (select_rec [] ps)
+
+(*
+ lub p q is a pattern that matches all values matched by p and q
+ may raise Empty, when p and q and not compatible
+*)
+
+let rec lub p q = match p.pat_desc,q.pat_desc with
+| Tpat_alias (p,_,_),_ -> lub p q
+| _,Tpat_alias (q,_,_) -> lub p q
+| (Tpat_any|Tpat_var _),_ -> q
+| _,(Tpat_any|Tpat_var _) -> p
+| Tpat_or (p1,p2,_),_ -> orlub p1 p2 q
+| _,Tpat_or (q1,q2,_) -> orlub q1 q2 p (* Thanks god, lub is commutative *)
+| Tpat_constant c1, Tpat_constant c2 when const_compare c1 c2 = 0 -> p
+| Tpat_tuple ps, Tpat_tuple qs ->
+ let rs = lubs ps qs in
+ make_pat (Tpat_tuple rs) p.pat_type p.pat_env
+| Tpat_lazy p, Tpat_lazy q ->
+ let r = lub p q in
+ make_pat (Tpat_lazy r) p.pat_type p.pat_env
+| Tpat_construct (lid, c1,ps1), Tpat_construct (_,c2,ps2)
+ when c1.cstr_tag = c2.cstr_tag ->
+ let rs = lubs ps1 ps2 in
+ make_pat (Tpat_construct (lid, c1,rs))
+ p.pat_type p.pat_env
+| Tpat_variant(l1,Some p1,row), Tpat_variant(l2,Some p2,_)
+ when l1=l2 ->
+ let r=lub p1 p2 in
+ make_pat (Tpat_variant (l1,Some r,row)) p.pat_type p.pat_env
+| Tpat_variant (l1,None,row), Tpat_variant(l2,None,_)
+ when l1 = l2 -> p
+| Tpat_record (l1,closed),Tpat_record (l2,_) ->
+ let rs = record_lubs l1 l2 in
+ make_pat (Tpat_record (rs, closed)) p.pat_type p.pat_env
+| Tpat_array ps, Tpat_array qs
+ when List.length ps = List.length qs ->
+ let rs = lubs ps qs in
+ make_pat (Tpat_array rs) p.pat_type p.pat_env
+| _,_ ->
+ raise Empty
+
+and orlub p1 p2 q =
+ try
+ let r1 = lub p1 q in
+ try
+ {q with pat_desc=(Tpat_or (r1,lub p2 q,None))}
+ with
+ | Empty -> r1
+with
+| Empty -> lub p2 q
+
+and record_lubs l1 l2 =
+ let rec lub_rec l1 l2 = match l1,l2 with
+ | [],_ -> l2
+ | _,[] -> l1
+ | (lid1, lbl1,p1)::rem1, (lid2, lbl2,p2)::rem2 ->
+ if lbl1.lbl_pos < lbl2.lbl_pos then
+ (lid1, lbl1,p1)::lub_rec rem1 l2
+ else if lbl2.lbl_pos < lbl1.lbl_pos then
+ (lid2, lbl2,p2)::lub_rec l1 rem2
+ else
+ (lid1, lbl1,lub p1 p2)::lub_rec rem1 rem2 in
+ lub_rec l1 l2
+
+and lubs ps qs = match ps,qs with
+| p::ps, q::qs -> lub p q :: lubs ps qs
+| _,_ -> []
+
+
+(******************************)
+(* Exported variant closing *)
+(******************************)
+
+(* Apply pressure to variants *)
+
+let pressure_variants tdefs patl =
+ let pss = List.map (fun p -> [p;omega]) patl in
+ ignore (pressure_variants (Some tdefs) pss)
+
+(*****************************)
+(* Utilities for diagnostics *)
+(*****************************)
+
+(*
+ Build up a working pattern matrix by forgetting
+ about guarded patterns
+*)
+
+let rec initial_matrix = function
+ [] -> []
+ | {c_guard=Some _} :: rem -> initial_matrix rem
+ | {c_guard=None; c_lhs=p} :: rem -> [p] :: initial_matrix rem
+
+(******************************************)
+(* Look for a row that matches some value *)
+(******************************************)
+
+(*
+ Useful for seeing if the example of
+ non-matched value can indeed be matched
+ (by a guarded clause)
+*)
+
+
+
+exception NoGuard
+
+let rec initial_all no_guard = function
+ | [] ->
+ if no_guard then
+ raise NoGuard
+ else
+ []
+ | {c_lhs=pat; c_guard; _} :: rem ->
+ ([pat], pat.pat_loc) :: initial_all (no_guard && c_guard = None) rem
+
+
+let rec do_filter_var = function
+ | (_::ps,loc)::rem -> (ps,loc)::do_filter_var rem
+ | _ -> []
+
+let do_filter_one q pss =
+ let rec filter_rec = function
+ | ({pat_desc = Tpat_alias(p,_,_)}::ps,loc)::pss ->
+ filter_rec ((p::ps,loc)::pss)
+ | ({pat_desc = Tpat_or(p1,p2,_)}::ps,loc)::pss ->
+ filter_rec ((p1::ps,loc)::(p2::ps,loc)::pss)
+ | (p::ps,loc)::pss ->
+ if simple_match q p
+ then (simple_match_args q p @ ps, loc) :: filter_rec pss
+ else filter_rec pss
+ | _ -> [] in
+ filter_rec pss
+
+let rec do_match pss qs = match qs with
+| [] ->
+ begin match pss with
+ | ([],loc)::_ -> Some loc
+ | _ -> None
+ end
+| q::qs -> match q with
+ | {pat_desc = Tpat_or (q1,q2,_)} ->
+ begin match do_match pss (q1::qs) with
+ | None -> do_match pss (q2::qs)
+ | r -> r
+ end
+ | {pat_desc = Tpat_any} ->
+ do_match (do_filter_var pss) qs
+ | _ ->
+ let q0 = normalize_pat q in
+ do_match (do_filter_one q0 pss) (simple_match_args q0 q @ qs)
+
+
+let check_partial_all v casel =
+ try
+ let pss = initial_all true casel in
+ do_match pss [v]
+ with
+ | NoGuard -> None
+
+(************************)
+(* Exhaustiveness check *)
+(************************)
+
+
+ let rec get_first f =
+ function
+ | [] -> None
+ | x :: xs ->
+ match f x with
+ | None -> get_first f xs
+ | x -> x
+
+
+(* conversion from Typedtree.pattern to Parsetree.pattern list *)
+module Conv = struct
+ open Parsetree
+ let mkpat desc = Ast_helper.Pat.mk desc
+
+ let rec select : 'a list list -> 'a list list =
+ function
+ | xs :: [] -> List.map (fun y -> [y]) xs
+ | (x::xs)::ys ->
+ List.map
+ (fun lst -> x :: lst)
+ (select ys)
+ @
+ select (xs::ys)
+ | _ -> []
+
+ let name_counter = ref 0
+ let fresh name =
+ let current = !name_counter in
+ name_counter := !name_counter + 1;
+ "#$" ^ name ^ string_of_int current
+
+ let conv (typed: Typedtree.pattern) :
+ Parsetree.pattern list *
+ (string, Types.constructor_description) Hashtbl.t *
+ (string, Types.label_description) Hashtbl.t
+ =
+ let constrs = Hashtbl.create 0 in
+ let labels = Hashtbl.create 0 in
+ let rec loop pat =
+ match pat.pat_desc with
+ Tpat_or (a,b,_) ->
+ loop a @ loop b
+ | Tpat_any | Tpat_constant _ | Tpat_var _ ->
+ [mkpat Ppat_any]
+ | Tpat_alias (p,_,_) -> loop p
+ | Tpat_tuple lst ->
+ let results = select (List.map loop lst) in
+ List.map
+ (fun lst -> mkpat (Ppat_tuple lst))
+ results
+ | Tpat_construct (cstr_lid, cstr,lst) ->
+ let id = fresh cstr.cstr_name in
+ let lid = { cstr_lid with txt = Longident.Lident id } in
+ Hashtbl.add constrs id cstr;
+ let results = select (List.map loop lst) in
+ begin match lst with
+ [] ->
+ [mkpat (Ppat_construct(lid, None))]
+ | _ ->
+ List.map
+ (fun lst ->
+ let arg =
+ match lst with
+ [] -> assert false
+ | [x] -> Some x
+ | _ -> Some (mkpat (Ppat_tuple lst))
+ in
+ mkpat (Ppat_construct(lid, arg)))
+ results
+ end
+ | Tpat_variant(label,p_opt,row_desc) ->
+ begin match p_opt with
+ | None ->
+ [mkpat (Ppat_variant(label, None))]
+ | Some p ->
+ let results = loop p in
+ List.map
+ (fun p ->
+ mkpat (Ppat_variant(label, Some p)))
+ results
+ end
+ | Tpat_record (subpatterns, _closed_flag) ->
+ let pats =
+ select
+ (List.map (fun (_,_,x) -> loop x) subpatterns)
+ in
+ let label_idents =
+ List.map
+ (fun (_,lbl,_) ->
+ let id = fresh lbl.lbl_name in
+ Hashtbl.add labels id lbl;
+ Longident.Lident id)
+ subpatterns
+ in
+ List.map
+ (fun lst ->
+ let lst = List.map2 (fun lid pat ->
+ (mknoloc lid, pat)
+ ) label_idents lst in
+ mkpat (Ppat_record (lst, Open)))
+ pats
+ | Tpat_array lst ->
+ let results = select (List.map loop lst) in
+ List.map (fun lst -> mkpat (Ppat_array lst)) results
+ | Tpat_lazy p ->
+ let results = loop p in
+ List.map (fun p -> mkpat (Ppat_lazy p)) results
+ in
+ let ps = loop typed in
+ (ps, constrs, labels)
+end
+
+(* Whether the counter-example contains an extension pattern *)
+let contains_extension pat =
+ let r = ref false in
+ let rec loop = function
+ {pat_desc=Tpat_construct(_, {cstr_name="*extension*"}, _)} ->
+ r := true
+ | p -> Typedtree.iter_pattern_desc loop p.pat_desc
+ in loop pat; !r
+
+let do_check_partial ?pred exhaust loc casel pss = match pss with
+| [] ->
+ (*
+ This can occur
+ - For empty matches generated by ocamlp4 (no warning)
+ - when all patterns have guards (then, casel <> [])
+ (specific warning)
+ Then match MUST be considered non-exhaustive,
+ otherwise compilation of PM is broken.
+ *)
+ begin match casel with
+ | [] -> ()
+ | _ -> Location.prerr_warning loc Warnings.All_clauses_guarded
+ end ;
+ Partial
+| ps::_ ->
+ begin match exhaust None pss (List.length ps) with
+ | Rnone -> Total
+ | Rsome [u] ->
+ let v =
+ match pred with
+ | Some pred ->
+ let (patterns,constrs,labels) = Conv.conv u in
+(* Hashtbl.iter (fun s (path, _) ->
+ Printf.fprintf stderr "CONV: %s -> %s \n%!" s (Path.name path))
+ constrs
+ ; *)
+ get_first (pred constrs labels) patterns
+ | None -> Some u
+ in
+ begin match v with
+ None -> Total
+ | Some v ->
+ let errmsg =
+ try
+ let buf = Buffer.create 16 in
+ let fmt = formatter_of_buffer buf in
+ top_pretty fmt v;
+ begin match check_partial_all v casel with
+ | None -> ()
+ | Some _ ->
+ (* This is 'Some loc', where loc is the location of
+ a possibly matching clause.
+ Forget about loc, because printing two locations
+ is a pain in the top-level *)
+ Buffer.add_string buf
+ "\n(However, some guarded clause may match this value.)"
+ end;
+ if contains_extension v then
+ Buffer.add_string buf
+ "\nMatching over values of extensible variant types \
+ (the *extension* above)\n\
+ must include a wild card pattern in order to be exhaustive."
+ ;
+ Buffer.contents buf
+ with _ ->
+ ""
+ in
+ Location.prerr_warning loc (Warnings.Partial_match errmsg) ;
+ Partial
+ end
+ | _ ->
+ fatal_error "Parmatch.check_partial"
+ end
+
+let do_check_partial_normal loc casel pss =
+ do_check_partial exhaust loc casel pss
+
+let do_check_partial_gadt pred loc casel pss =
+ do_check_partial ~pred exhaust_gadt loc casel pss
+
+
+
+(*****************)
+(* Fragile check *)
+(*****************)
+
+(* Collect all data types in a pattern *)
+
+let rec add_path path = function
+ | [] -> [path]
+ | x::rem as paths ->
+ if Path.same path x then paths
+ else x::add_path path rem
+
+let extendable_path path =
+ not
+ (Path.same path Predef.path_bool ||
+ Path.same path Predef.path_list ||
+ Path.same path Predef.path_unit ||
+ Path.same path Predef.path_option)
+
+let rec collect_paths_from_pat r p = match p.pat_desc with
+| Tpat_construct(_, {cstr_tag=(Cstr_constant _|Cstr_block _)},ps) ->
+ let path = get_type_path p.pat_type p.pat_env in
+ List.fold_left
+ collect_paths_from_pat
+ (if extendable_path path then add_path path r else r)
+ ps
+| Tpat_any|Tpat_var _|Tpat_constant _| Tpat_variant (_,None,_) -> r
+| Tpat_tuple ps | Tpat_array ps
+| Tpat_construct (_, {cstr_tag=Cstr_extension _}, ps)->
+ List.fold_left collect_paths_from_pat r ps
+| Tpat_record (lps,_) ->
+ List.fold_left
+ (fun r (_, _, p) -> collect_paths_from_pat r p)
+ r lps
+| Tpat_variant (_, Some p, _) | Tpat_alias (p,_,_) -> collect_paths_from_pat r p
+| Tpat_or (p1,p2,_) ->
+ collect_paths_from_pat (collect_paths_from_pat r p1) p2
+| Tpat_lazy p
+ ->
+ collect_paths_from_pat r p
+
+
+(*
+ Actual fragile check
+ 1. Collect data types in the patterns of the match.
+ 2. One exhautivity check per datatype, considering that
+ the type is extended.
+*)
+
+let do_check_fragile_param exhaust loc casel pss =
+ let exts =
+ List.fold_left
+ (fun r c -> collect_paths_from_pat r c.c_lhs)
+ [] casel in
+ match exts with
+ | [] -> ()
+ | _ -> match pss with
+ | [] -> ()
+ | ps::_ ->
+ List.iter
+ (fun ext ->
+ match exhaust (Some ext) pss (List.length ps) with
+ | Rnone ->
+ Location.prerr_warning
+ loc
+ (Warnings.Fragile_match (Path.name ext))
+ | Rsome _ -> ())
+ exts
+
+let do_check_fragile_normal = do_check_fragile_param exhaust
+let do_check_fragile_gadt = do_check_fragile_param exhaust_gadt
+
+(********************************)
+(* Exported unused clause check *)
+(********************************)
+
+let check_unused tdefs casel =
+ if Warnings.is_active Warnings.Unused_match then
+ let rec do_rec pref = function
+ | [] -> ()
+ | {c_lhs=q; c_guard} :: rem ->
+ let qs = [q] in
+ begin try
+ let pss =
+ get_mins le_pats (List.filter (compats qs) pref) in
+ let r = every_satisfiables (make_rows pss) (make_row qs) in
+ match r with
+ | Unused ->
+ Location.prerr_warning
+ q.pat_loc Warnings.Unused_match
+ | Upartial ps ->
+ List.iter
+ (fun p ->
+ Location.prerr_warning
+ p.pat_loc Warnings.Unused_pat)
+ ps
+ | Used -> ()
+ with Empty | Not_found | NoGuard -> assert false
+ end ;
+
+ if c_guard <> None then
+ do_rec pref rem
+ else
+ do_rec ([q]::pref) rem in
+
+ do_rec [] casel
+
+(*********************************)
+(* Exported irrefutability tests *)
+(*********************************)
+
+let irrefutable pat = le_pat pat omega
+
+(* An inactive pattern is a pattern whose matching needs only
+ trivial computations (tag/equality tests).
+ Patterns containing (lazy _) subpatterns are active. *)
+
+let rec inactive pat = match pat with
+| Tpat_lazy _ ->
+ false
+| Tpat_any | Tpat_var _ | Tpat_constant _ | Tpat_variant (_, None, _) ->
+ true
+| Tpat_tuple ps | Tpat_construct (_, _, ps) | Tpat_array ps ->
+ List.for_all (fun p -> inactive p.pat_desc) ps
+| Tpat_alias (p,_,_) | Tpat_variant (_, Some p, _) ->
+ inactive p.pat_desc
+| Tpat_record (ldps,_) ->
+ List.exists (fun (_, _, p) -> inactive p.pat_desc) ldps
+| Tpat_or (p,q,_) ->
+ inactive p.pat_desc && inactive q.pat_desc
+
+(* A `fluid' pattern is both irrefutable and inactive *)
+
+let fluid pat = irrefutable pat && inactive pat.pat_desc
+
+
+
+
+
+
+
+
+(********************************)
+(* Exported exhustiveness check *)
+(********************************)
+
+(*
+ Fragile check is performed when required and
+ on exhaustive matches only.
+*)
+
+let check_partial_param do_check_partial do_check_fragile loc casel =
+ if Warnings.is_active (Warnings.Partial_match "") then begin
+ let pss = initial_matrix casel in
+ let pss = get_mins le_pats pss in
+ let total = do_check_partial loc casel pss in
+ if
+ total = Total && Warnings.is_active (Warnings.Fragile_match "")
+ then begin
+ do_check_fragile loc casel pss
+ end ;
+ total
+ end else
+ Partial
+
+let check_partial =
+ check_partial_param
+ do_check_partial_normal
+ do_check_fragile_normal
+
+let check_partial_gadt pred loc casel =
+ (*ignores GADT constructors *)
+ let first_check = check_partial loc casel in
+ match first_check with
+ | Partial -> Partial
+ | Total ->
+ (* checks for missing GADT constructors *)
+ (* let casel =
+ match casel with [] -> [] | a :: l -> a :: l @ [a] in *)
+ check_partial_param (do_check_partial_gadt pred)
+ do_check_fragile_gadt loc casel
diff --git a/typing/parmatch.mli b/typing/parmatch.mli
new file mode 100644
index 0000000000..dfd955a8bb
--- /dev/null
+++ b/typing/parmatch.mli
@@ -0,0 +1,65 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Detection of partial matches and unused match cases. *)
+open Asttypes
+open Typedtree
+open Types
+
+val pretty_const : constant -> string
+val top_pretty : Format.formatter -> pattern -> unit
+val pretty_pat : pattern -> unit
+val pretty_line : pattern list -> unit
+val pretty_matrix : pattern list list -> unit
+
+val omega : pattern
+val omegas : int -> pattern list
+val omega_list : 'a list -> pattern list
+val normalize_pat : pattern -> pattern
+val all_record_args :
+ (Longident.t loc * label_description * pattern) list ->
+ (Longident.t loc * label_description * pattern) list
+val const_compare : constant -> constant -> int
+
+val le_pat : pattern -> pattern -> bool
+val le_pats : pattern list -> pattern list -> bool
+val compat : pattern -> pattern -> bool
+val compats : pattern list -> pattern list -> bool
+exception Empty
+val lub : pattern -> pattern -> pattern
+val lubs : pattern list -> pattern list -> pattern list
+
+val get_mins : ('a -> 'a -> bool) -> 'a list -> 'a list
+
+(* Those two functions recombine one pattern and its arguments:
+ For instance:
+ (_,_)::p1::p2::rem -> (p1, p2)::rem
+ The second one will replace mutable arguments by '_'
+*)
+val set_args : pattern -> pattern list -> pattern list
+val set_args_erase_mutable : pattern -> pattern list -> pattern list
+
+val pat_of_constr : pattern -> constructor_description -> pattern
+val complete_constrs :
+ pattern -> constructor_tag list -> constructor_description list
+
+val pressure_variants: Env.t -> pattern list -> unit
+val check_partial_gadt:
+ ((string, constructor_description) Hashtbl.t ->
+ (string, label_description) Hashtbl.t ->
+ Parsetree.pattern -> pattern option) ->
+ Location.t -> case list -> partial
+val check_unused: Env.t -> case list -> unit
+
+(* Irrefutability tests *)
+val irrefutable : pattern -> bool
+val fluid : pattern -> bool
diff --git a/typing/path.ml b/typing/path.ml
new file mode 100644
index 0000000000..6afa3841b6
--- /dev/null
+++ b/typing/path.ml
@@ -0,0 +1,78 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type t =
+ Pident of Ident.t
+ | Pdot of t * string * int
+ | Papply of t * t
+
+let nopos = -1
+
+let rec same p1 p2 =
+ match (p1, p2) with
+ (Pident id1, Pident id2) -> Ident.same id1 id2
+ | (Pdot(p1, s1, pos1), Pdot(p2, s2, pos2)) -> s1 = s2 && same p1 p2
+ | (Papply(fun1, arg1), Papply(fun2, arg2)) ->
+ same fun1 fun2 && same arg1 arg2
+ | (_, _) -> false
+
+let rec isfree id = function
+ Pident id' -> Ident.same id id'
+ | Pdot(p, s, pos) -> isfree id p
+ | Papply(p1, p2) -> isfree id p1 || isfree id p2
+
+let rec binding_time = function
+ Pident id -> Ident.binding_time id
+ | Pdot(p, s, pos) -> binding_time p
+ | Papply(p1, p2) -> max (binding_time p1) (binding_time p2)
+
+let kfalse x = false
+
+let rec name ?(paren=kfalse) = function
+ Pident id -> Ident.name id
+ | Pdot(p, s, pos) ->
+ name ~paren p ^ if paren s then ".( " ^ s ^ " )" else "." ^ s
+ | Papply(p1, p2) -> name ~paren p1 ^ "(" ^ name ~paren p2 ^ ")"
+
+let rec head = function
+ Pident id -> id
+ | Pdot(p, s, pos) -> head p
+ | Papply(p1, p2) -> assert false
+
+let rec last = function
+ | Pident id -> Ident.name id
+ | Pdot(_, s, _) -> s
+ | Papply(_, p) -> last p
+
+let is_uident s =
+ assert (s <> "");
+ match s.[0] with
+ | 'A'..'Z' -> true
+ | _ -> false
+
+type typath =
+ | Regular of t
+ | Ext of t * string
+ | LocalExt of Ident.t
+ | Cstr of t * string
+
+let constructor_typath = function
+ | Pident id when is_uident (Ident.name id) -> LocalExt id
+ | Pdot(ty_path, s, _) when is_uident s ->
+ if is_uident (last ty_path) then Ext (ty_path, s)
+ else Cstr (ty_path, s)
+ | p -> Regular p
+
+let is_constructor_typath p =
+ match constructor_typath p with
+ | Regular _ -> false
+ | _ -> true
diff --git a/typing/path.mli b/typing/path.mli
new file mode 100644
index 0000000000..07de1c2c5a
--- /dev/null
+++ b/typing/path.mli
@@ -0,0 +1,39 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Access paths *)
+
+type t =
+ Pident of Ident.t
+ | Pdot of t * string * int
+ | Papply of t * t
+
+val same: t -> t -> bool
+val isfree: Ident.t -> t -> bool
+val binding_time: t -> int
+
+val nopos: int
+
+val name: ?paren:(string -> bool) -> t -> string
+ (* [paren] tells whether a path suffix needs parentheses *)
+val head: t -> Ident.t
+
+val last: t -> string
+
+type typath =
+ | Regular of t
+ | Ext of t * string
+ | LocalExt of Ident.t
+ | Cstr of t * string
+
+val constructor_typath: t -> typath
+val is_constructor_typath: t -> bool
diff --git a/typing/predef.ml b/typing/predef.ml
new file mode 100644
index 0000000000..49f9d91981
--- /dev/null
+++ b/typing/predef.ml
@@ -0,0 +1,223 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Predefined type constructors (with special typing rules in typecore) *)
+
+open Path
+open Types
+open Btype
+
+let builtin_idents = ref []
+
+let wrap create s =
+ let id = create s in
+ builtin_idents := (s, id) :: !builtin_idents;
+ id
+
+let ident_create = wrap Ident.create
+let ident_create_predef_exn = wrap Ident.create_predef_exn
+
+let ident_int = ident_create "int"
+and ident_char = ident_create "char"
+and ident_bytes = ident_create "bytes"
+and ident_float = ident_create "float"
+and ident_bool = ident_create "bool"
+and ident_unit = ident_create "unit"
+and ident_exn = ident_create "exn"
+and ident_array = ident_create "array"
+and ident_list = ident_create "list"
+and ident_option = ident_create "option"
+and ident_nativeint = ident_create "nativeint"
+and ident_int32 = ident_create "int32"
+and ident_int64 = ident_create "int64"
+and ident_lazy_t = ident_create "lazy_t"
+and ident_string = ident_create "string"
+
+let path_int = Pident ident_int
+and path_char = Pident ident_char
+and path_bytes = Pident ident_bytes
+and path_float = Pident ident_float
+and path_bool = Pident ident_bool
+and path_unit = Pident ident_unit
+and path_exn = Pident ident_exn
+and path_array = Pident ident_array
+and path_list = Pident ident_list
+and path_option = Pident ident_option
+and path_nativeint = Pident ident_nativeint
+and path_int32 = Pident ident_int32
+and path_int64 = Pident ident_int64
+and path_lazy_t = Pident ident_lazy_t
+and path_string = Pident ident_string
+
+let type_int = newgenty (Tconstr(path_int, [], ref Mnil))
+and type_char = newgenty (Tconstr(path_char, [], ref Mnil))
+and type_bytes = newgenty (Tconstr(path_bytes, [], ref Mnil))
+and type_float = newgenty (Tconstr(path_float, [], ref Mnil))
+and type_bool = newgenty (Tconstr(path_bool, [], ref Mnil))
+and type_unit = newgenty (Tconstr(path_unit, [], ref Mnil))
+and type_exn = newgenty (Tconstr(path_exn, [], ref Mnil))
+and type_array t = newgenty (Tconstr(path_array, [t], ref Mnil))
+and type_list t = newgenty (Tconstr(path_list, [t], ref Mnil))
+and type_option t = newgenty (Tconstr(path_option, [t], ref Mnil))
+and type_nativeint = newgenty (Tconstr(path_nativeint, [], ref Mnil))
+and type_int32 = newgenty (Tconstr(path_int32, [], ref Mnil))
+and type_int64 = newgenty (Tconstr(path_int64, [], ref Mnil))
+and type_lazy_t t = newgenty (Tconstr(path_lazy_t, [t], ref Mnil))
+and type_string = newgenty (Tconstr(path_string, [], ref Mnil))
+
+let ident_match_failure = ident_create_predef_exn "Match_failure"
+and ident_out_of_memory = ident_create_predef_exn "Out_of_memory"
+and ident_invalid_argument = ident_create_predef_exn "Invalid_argument"
+and ident_failure = ident_create_predef_exn "Failure"
+and ident_not_found = ident_create_predef_exn "Not_found"
+and ident_sys_error = ident_create_predef_exn "Sys_error"
+and ident_end_of_file = ident_create_predef_exn "End_of_file"
+and ident_division_by_zero = ident_create_predef_exn "Division_by_zero"
+and ident_stack_overflow = ident_create_predef_exn "Stack_overflow"
+and ident_sys_blocked_io = ident_create_predef_exn "Sys_blocked_io"
+and ident_assert_failure = ident_create_predef_exn "Assert_failure"
+and ident_undefined_recursive_module =
+ ident_create_predef_exn "Undefined_recursive_module"
+
+let path_match_failure = Pident ident_match_failure
+and path_assert_failure = Pident ident_assert_failure
+and path_undefined_recursive_module = Pident ident_undefined_recursive_module
+
+let decl_abstr =
+ {type_params = [];
+ type_arity = 0;
+ type_kind = Type_abstract;
+ type_loc = Location.none;
+ type_private = Asttypes.Public;
+ type_manifest = None;
+ type_variance = [];
+ type_newtype_level = None;
+ type_attributes = [];
+ }
+
+let cstr id args =
+ {
+ cd_id = id;
+ cd_args = Cstr_tuple args;
+ cd_res = None;
+ cd_loc = Location.none;
+ cd_attributes = [];
+ }
+
+let ident_false = ident_create "false"
+and ident_true = ident_create "true"
+and ident_void = ident_create "()"
+and ident_nil = ident_create "[]"
+and ident_cons = ident_create "::"
+and ident_none = ident_create "None"
+and ident_some = ident_create "Some"
+let common_initial_env add_type add_extension empty_env =
+ let decl_bool =
+ {decl_abstr with
+ type_kind = Type_variant([cstr ident_false []; cstr ident_true []])}
+ and decl_unit =
+ {decl_abstr with
+ type_kind = Type_variant([cstr ident_void []])}
+ and decl_exn =
+ {decl_abstr with
+ type_kind = Type_open}
+ and decl_array =
+ let tvar = newgenvar() in
+ {decl_abstr with
+ type_params = [tvar];
+ type_arity = 1;
+ type_variance = [Variance.full]}
+ and decl_list =
+ let tvar = newgenvar() in
+ {decl_abstr with
+ type_params = [tvar];
+ type_arity = 1;
+ type_kind =
+ Type_variant([cstr ident_nil []; cstr ident_cons [tvar; type_list tvar]]);
+ type_variance = [Variance.covariant]}
+ and decl_option =
+ let tvar = newgenvar() in
+ {decl_abstr with
+ type_params = [tvar];
+ type_arity = 1;
+ type_kind = Type_variant([cstr ident_none []; cstr ident_some [tvar]]);
+ type_variance = [Variance.covariant]}
+ and decl_lazy_t =
+ let tvar = newgenvar() in
+ {decl_abstr with
+ type_params = [tvar];
+ type_arity = 1;
+ type_variance = [Variance.covariant]}
+ in
+
+ let add_extension id l =
+ add_extension id
+ { ext_type_path = path_exn;
+ ext_type_params = [];
+ ext_args = Cstr_tuple l;
+ ext_ret_type = None;
+ ext_private = Asttypes.Public;
+ ext_loc = Location.none;
+ ext_attributes = [] }
+ in
+ add_extension ident_match_failure
+ [newgenty (Ttuple[type_string; type_int; type_int])] (
+ add_extension ident_out_of_memory [] (
+ add_extension ident_stack_overflow [] (
+ add_extension ident_invalid_argument [type_string] (
+ add_extension ident_failure [type_string] (
+ add_extension ident_not_found [] (
+ add_extension ident_sys_blocked_io [] (
+ add_extension ident_sys_error [type_string] (
+ add_extension ident_end_of_file [] (
+ add_extension ident_division_by_zero [] (
+ add_extension ident_assert_failure
+ [newgenty (Ttuple[type_string; type_int; type_int])] (
+ add_extension ident_undefined_recursive_module
+ [newgenty (Ttuple[type_string; type_int; type_int])] (
+ add_type ident_int64 decl_abstr (
+ add_type ident_int32 decl_abstr (
+ add_type ident_nativeint decl_abstr (
+ add_type ident_lazy_t decl_lazy_t (
+ add_type ident_option decl_option (
+ add_type ident_list decl_list (
+ add_type ident_array decl_array (
+ add_type ident_exn decl_exn (
+ add_type ident_unit decl_unit (
+ add_type ident_bool decl_bool (
+ add_type ident_float decl_abstr (
+ add_type ident_string decl_abstr (
+ add_type ident_char decl_abstr (
+ add_type ident_int decl_abstr (
+ empty_env))))))))))))))))))))))))))
+
+let build_initial_env add_type add_exception empty_env =
+ let common = common_initial_env add_type add_exception empty_env in
+ let safe_string = add_type ident_bytes decl_abstr common in
+ let decl_bytes_unsafe = {decl_abstr with type_manifest = Some type_string} in
+ let unsafe_string = add_type ident_bytes decl_bytes_unsafe common in
+ (safe_string, unsafe_string)
+
+let builtin_values =
+ List.map (fun id -> Ident.make_global id; (Ident.name id, id))
+ [ident_match_failure; ident_out_of_memory; ident_stack_overflow;
+ ident_invalid_argument;
+ ident_failure; ident_not_found; ident_sys_error; ident_end_of_file;
+ ident_division_by_zero; ident_sys_blocked_io;
+ ident_assert_failure; ident_undefined_recursive_module ]
+
+(* Start non-predef identifiers at 1000. This way, more predefs can
+ be defined in this file (above!) without breaking .cmi
+ compatibility. *)
+
+let _ = Ident.set_current_time 999
+let builtin_idents = List.rev !builtin_idents
diff --git a/typing/predef.mli b/typing/predef.mli
new file mode 100644
index 0000000000..9723671165
--- /dev/null
+++ b/typing/predef.mli
@@ -0,0 +1,65 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Predefined type constructors (with special typing rules in typecore) *)
+
+open Types
+
+val type_int: type_expr
+val type_char: type_expr
+val type_string: type_expr
+val type_bytes: type_expr
+val type_float: type_expr
+val type_bool: type_expr
+val type_unit: type_expr
+val type_exn: type_expr
+val type_array: type_expr -> type_expr
+val type_list: type_expr -> type_expr
+val type_option: type_expr -> type_expr
+val type_nativeint: type_expr
+val type_int32: type_expr
+val type_int64: type_expr
+val type_lazy_t: type_expr -> type_expr
+
+val path_int: Path.t
+val path_char: Path.t
+val path_string: Path.t
+val path_bytes: Path.t
+val path_float: Path.t
+val path_bool: Path.t
+val path_unit: Path.t
+val path_exn: Path.t
+val path_array: Path.t
+val path_list: Path.t
+val path_option: Path.t
+val path_nativeint: Path.t
+val path_int32: Path.t
+val path_int64: Path.t
+val path_lazy_t: Path.t
+
+val path_match_failure: Path.t
+val path_assert_failure : Path.t
+val path_undefined_recursive_module : Path.t
+
+(* To build the initial environment. Since there is a nasty mutual
+ recursion between predef and env, we break it by parameterizing
+ over Env.t, Env.add_type and Env.add_extension. *)
+
+val build_initial_env:
+ (Ident.t -> type_declaration -> 'a -> 'a) ->
+ (Ident.t -> extension_constructor -> 'a -> 'a) ->
+ 'a -> 'a * 'a
+
+(* To initialize linker tables *)
+
+val builtin_values: (string * Ident.t) list
+val builtin_idents: (string * Ident.t) list
diff --git a/typing/primitive.ml b/typing/primitive.ml
new file mode 100644
index 0000000000..dd610815fa
--- /dev/null
+++ b/typing/primitive.ml
@@ -0,0 +1,144 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Description of primitive functions *)
+
+open Misc
+open Parsetree
+
+type boxed_integer = Pnativeint | Pint32 | Pint64
+
+type native_repr =
+ | Same_as_ocaml_repr
+ | Unboxed_float
+ | Unboxed_integer of boxed_integer
+ | Untagged_int
+
+type description =
+ { prim_name: string; (* Name of primitive or C function *)
+ prim_arity: int; (* Number of arguments *)
+ prim_alloc: bool; (* Does it allocates or raise? *)
+ prim_native_name: string; (* Name of C function for the nat. code gen. *)
+ prim_native_repr_args: native_repr list;
+ prim_native_repr_res: native_repr }
+
+type error =
+ | Float_with_native_repr_attribute
+
+exception Error of Location.t * error
+
+let is_ocaml_repor = function
+ | Same_as_ocaml_repr -> true
+ | Unboxed_float
+ | Unboxed_integer _
+ | Untagged_int -> false
+
+let rec make_native_repr_args arity x =
+ if arity = 0 then
+ []
+ else
+ x :: make_native_repr_args (arity - 1) x
+
+let simple ~name ~arity ~alloc =
+ {prim_name = name;
+ prim_arity = arity;
+ prim_alloc = alloc;
+ prim_native_name = "";
+ prim_native_repr_args = make_native_repr_args arity Same_as_ocaml_repr;
+ prim_native_repr_res = Same_as_ocaml_repr}
+
+let parse_declaration valdecl ~native_repr_args ~native_repr_res =
+ let arity = List.length native_repr_args in
+ let name, native_name, noalloc, float =
+ match valdecl.pval_prim with
+ | name :: "noalloc" :: name2 :: "float" :: _ -> (name, name2, true, true)
+ | name :: "noalloc" :: name2 :: _ -> (name, name2, true, false)
+ | name :: name2 :: "float" :: _ -> (name, name2, false, true)
+ | name :: "noalloc" :: _ -> (name, "", true, false)
+ | name :: name2 :: _ -> (name, name2, false, false)
+ | name :: _ -> (name, "", false, false)
+ | [] ->
+ fatal_error "Primitive.parse_declaration"
+ in
+ (* The compiler used to assume "noalloc" with "float", we just make this
+ explicit now (GPR#167): *)
+ let noalloc = noalloc || float in
+ if float &&
+ not (List.for_all is_ocaml_repor native_repr_args &&
+ is_ocaml_repor native_repr_res) then
+ raise (Error (valdecl.pval_loc, Float_with_native_repr_attribute));
+ let native_repr_args, native_repr_res =
+ if float then
+ (make_native_repr_args arity Unboxed_float, Unboxed_float)
+ else
+ (native_repr_args, native_repr_res)
+ in
+ {prim_name = name;
+ prim_arity = arity;
+ prim_alloc = not noalloc;
+ prim_native_name = native_name;
+ prim_native_repr_args = native_repr_args;
+ prim_native_repr_res = native_repr_res}
+
+let description_list_and_attributes p =
+ let list = [p.prim_name] in
+ let list = if not p.prim_alloc then "noalloc" :: list else list in
+ let list =
+ if p.prim_native_name <> "" then p.prim_native_name :: list else list
+ in
+ let has_float =
+ let is_unboxed_float x = x = Unboxed_float in
+ List.for_all is_unboxed_float p.prim_native_repr_args &&
+ is_unboxed_float p.prim_native_repr_res
+ in
+ let list =
+ if has_float then
+ "float" :: list
+ else
+ list
+ in
+ let list = List.rev list in
+ let attr_of_native_repr = function
+ | Same_as_ocaml_repr -> None
+ | Unboxed_float -> if has_float then None else Some "unboxed"
+ | Unboxed_integer _ -> Some "unboxed"
+ | Untagged_int -> Some "untagged"
+ in
+ let attrs =
+ List.map attr_of_native_repr p.prim_native_repr_args @
+ [attr_of_native_repr p.prim_native_repr_res]
+ in
+ (list, attrs)
+
+let native_name p =
+ if p.prim_native_name <> ""
+ then p.prim_native_name
+ else p.prim_name
+
+let byte_name p =
+ p.prim_name
+
+let report_error ppf err =
+ let open Format in
+ match err with
+ | Float_with_native_repr_attribute ->
+ fprintf ppf "Cannot use \"float\" in conjunction with \
+ [@unboxed ]/[@untagged ]"
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, err) ->
+ Some (Location.error_of_printer loc report_error err)
+ | _ ->
+ None
+ )
diff --git a/typing/primitive.mli b/typing/primitive.mli
new file mode 100644
index 0000000000..f6e4ea1eb3
--- /dev/null
+++ b/typing/primitive.mli
@@ -0,0 +1,54 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Description of primitive functions *)
+
+type boxed_integer = Pnativeint | Pint32 | Pint64
+
+(* Representation of arguments/result for the native code version
+ of a primitive *)
+type native_repr =
+ | Same_as_ocaml_repr
+ | Unboxed_float
+ | Unboxed_integer of boxed_integer
+ | Untagged_int
+
+type description = private
+ { prim_name: string; (* Name of primitive or C function *)
+ prim_arity: int; (* Number of arguments *)
+ prim_alloc: bool; (* Does it allocates or raise? *)
+ prim_native_name: string; (* Name of C function for the nat. code gen. *)
+ prim_native_repr_args: native_repr list;
+ prim_native_repr_res: native_repr }
+
+val simple
+ : name:string
+ -> arity:int
+ -> alloc:bool
+ -> description
+
+val parse_declaration
+ : Parsetree.value_description
+ -> native_repr_args:native_repr list
+ -> native_repr_res:native_repr
+ -> description
+
+val description_list_and_attributes
+ : description -> string list * string option list
+
+val native_name: description -> string
+val byte_name: description -> string
+
+type error =
+ | Float_with_native_repr_attribute
+
+exception Error of Location.t * error
diff --git a/typing/printtyp.ml b/typing/printtyp.ml
new file mode 100644
index 0000000000..7232676559
--- /dev/null
+++ b/typing/printtyp.ml
@@ -0,0 +1,1566 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Jerome Vouillon, projet Cristal, INRIA Rocquencourt*)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Printing functions *)
+
+open Misc
+open Ctype
+open Format
+open Longident
+open Path
+open Asttypes
+open Types
+open Btype
+open Outcometree
+
+(* Print a long identifier *)
+
+let rec longident ppf = function
+ | Lident s -> pp_print_string ppf s
+ | Ldot(p, s) -> fprintf ppf "%a.%s" longident p s
+ | Lapply(p1, p2) -> fprintf ppf "%a(%a)" longident p1 longident p2
+
+(* Print an identifier *)
+
+let unique_names = ref Ident.empty
+
+let ident_name id =
+ try Ident.find_same id !unique_names with Not_found -> Ident.name id
+
+let add_unique id =
+ try ignore (Ident.find_same id !unique_names)
+ with Not_found ->
+ unique_names := Ident.add id (Ident.unique_toplevel_name id) !unique_names
+
+let ident ppf id = pp_print_string ppf (ident_name id)
+
+(* Print a path *)
+
+let ident_pervasive = Ident.create_persistent "Pervasives"
+
+let rec tree_of_path = function
+ | Pident id ->
+ Oide_ident (ident_name id)
+ | Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
+ Oide_ident s
+ | Pdot(p, s, pos) ->
+ Oide_dot (tree_of_path p, s)
+ | Papply(p1, p2) ->
+ Oide_apply (tree_of_path p1, tree_of_path p2)
+
+let rec path ppf = function
+ | Pident id ->
+ ident ppf id
+ | Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
+ pp_print_string ppf s
+ | Pdot(p, s, pos) ->
+ path ppf p;
+ pp_print_char ppf '.';
+ pp_print_string ppf s
+ | Papply(p1, p2) ->
+ fprintf ppf "%a(%a)" path p1 path p2
+
+let rec string_of_out_ident = function
+ | Oide_ident s -> s
+ | Oide_dot (id, s) -> String.concat "." [string_of_out_ident id; s]
+ | Oide_apply (id1, id2) ->
+ String.concat ""
+ [string_of_out_ident id1; "("; string_of_out_ident id2; ")"]
+
+let string_of_path p = string_of_out_ident (tree_of_path p)
+
+(* Print a recursive annotation *)
+
+let tree_of_rec = function
+ | Trec_not -> Orec_not
+ | Trec_first -> Orec_first
+ | Trec_next -> Orec_next
+
+(* Print a raw type expression, with sharing *)
+
+let raw_list pr ppf = function
+ [] -> fprintf ppf "[]"
+ | a :: l ->
+ fprintf ppf "@[<1>[%a%t]@]" pr a
+ (fun ppf -> List.iter (fun x -> fprintf ppf ";@,%a" pr x) l)
+
+let rec safe_kind_repr v = function
+ Fvar {contents=Some k} ->
+ if List.memq k v then "Fvar loop" else
+ safe_kind_repr (k::v) k
+ | Fvar _ -> "Fvar None"
+ | Fpresent -> "Fpresent"
+ | Fabsent -> "Fabsent"
+
+let rec safe_commu_repr v = function
+ Cok -> "Cok"
+ | Cunknown -> "Cunknown"
+ | Clink r ->
+ if List.memq r v then "Clink loop" else
+ safe_commu_repr (r::v) !r
+
+let rec safe_repr v = function
+ {desc = Tlink t} when not (List.memq t v) ->
+ safe_repr (t::v) t
+ | t -> t
+
+let rec list_of_memo = function
+ Mnil -> []
+ | Mcons (priv, p, t1, t2, rem) -> p :: list_of_memo rem
+ | Mlink rem -> list_of_memo !rem
+
+let print_name ppf = function
+ None -> fprintf ppf "None"
+ | Some name -> fprintf ppf "\"%s\"" name
+
+let string_of_label = function
+ Nolabel -> ""
+ | Labelled s -> s
+ | Optional s -> "?"^s
+
+let visited = ref []
+let rec raw_type ppf ty =
+ let ty = safe_repr [] ty in
+ if List.memq ty !visited then fprintf ppf "{id=%d}" ty.id else begin
+ visited := ty :: !visited;
+ fprintf ppf "@[<1>{id=%d;level=%d;desc=@,%a}@]" ty.id ty.level
+ raw_type_desc ty.desc
+ end
+and raw_type_list tl = raw_list raw_type tl
+and raw_type_desc ppf = function
+ Tvar name -> fprintf ppf "Tvar %a" print_name name
+ | Tarrow(l,t1,t2,c) ->
+ fprintf ppf "@[<hov1>Tarrow(\"%s\",@,%a,@,%a,@,%s)@]"
+ (string_of_label l) raw_type t1 raw_type t2
+ (safe_commu_repr [] c)
+ | Ttuple tl ->
+ fprintf ppf "@[<1>Ttuple@,%a@]" raw_type_list tl
+ | Tconstr (p, tl, abbrev) ->
+ fprintf ppf "@[<hov1>Tconstr(@,%a,@,%a,@,%a)@]" path p
+ raw_type_list tl
+ (raw_list path) (list_of_memo !abbrev)
+ | Tobject (t, nm) ->
+ fprintf ppf "@[<hov1>Tobject(@,%a,@,@[<1>ref%t@])@]" raw_type t
+ (fun ppf ->
+ match !nm with None -> fprintf ppf " None"
+ | Some(p,tl) ->
+ fprintf ppf "(Some(@,%a,@,%a))" path p raw_type_list tl)
+ | Tfield (f, k, t1, t2) ->
+ fprintf ppf "@[<hov1>Tfield(@,%s,@,%s,@,%a,@;<0 -1>%a)@]" f
+ (safe_kind_repr [] k)
+ raw_type t1 raw_type t2
+ | Tnil -> fprintf ppf "Tnil"
+ | Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
+ | Tsubst t -> fprintf ppf "@[<1>Tsubst@,%a@]" raw_type t
+ | Tunivar name -> fprintf ppf "Tunivar %a" print_name name
+ | Tpoly (t, tl) ->
+ fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
+ raw_type t
+ raw_type_list tl
+ | Tvariant row ->
+ fprintf ppf
+ "@[<hov1>{@[%s@,%a;@]@ @[%s@,%a;@]@ %s%b;@ %s%b;@ @[<1>%s%t@]}@]"
+ "row_fields="
+ (raw_list (fun ppf (l, f) ->
+ fprintf ppf "@[%s,@ %a@]" l raw_field f))
+ row.row_fields
+ "row_more=" raw_type row.row_more
+ "row_closed=" row.row_closed
+ "row_fixed=" row.row_fixed
+ "row_name="
+ (fun ppf ->
+ match row.row_name with None -> fprintf ppf "None"
+ | Some(p,tl) ->
+ fprintf ppf "Some(@,%a,@,%a)" path p raw_type_list tl)
+ | Tpackage (p, _, tl) ->
+ fprintf ppf "@[<hov1>Tpackage(@,%a@,%a)@]" path p
+ raw_type_list tl
+
+and raw_field ppf = function
+ Rpresent None -> fprintf ppf "Rpresent None"
+ | Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
+ | Reither (c,tl,m,e) ->
+ fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,@[<1>ref%t@])@]" c
+ raw_type_list tl m
+ (fun ppf ->
+ match !e with None -> fprintf ppf " None"
+ | Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
+ | Rabsent -> fprintf ppf "Rabsent"
+
+let raw_type_expr ppf t =
+ visited := [];
+ raw_type ppf t;
+ visited := []
+
+let () = Btype.print_raw := raw_type_expr
+
+(* Normalize paths *)
+
+type param_subst = Id | Nth of int | Map of int list
+
+let is_nth = function
+ Nth _ -> true
+ | _ -> false
+
+let compose l1 = function
+ | Id -> Map l1
+ | Map l2 -> Map (List.map (List.nth l1) l2)
+ | Nth n -> Nth (List.nth l1 n)
+
+let apply_subst s1 tyl =
+ match s1 with
+ Nth n1 -> [List.nth tyl n1]
+ | Map l1 -> List.map (List.nth tyl) l1
+ | Id -> tyl
+
+type best_path = Paths of Path.t list | Best of Path.t
+
+let printing_env = ref Env.empty
+let printing_depth = ref 0
+let printing_cont = ref ([] : Env.iter_cont list)
+let printing_old = ref Env.empty
+let printing_pers = ref Concr.empty
+module Path2 = struct
+ include Path
+ let rec compare p1 p2 =
+ (* must ignore position when comparing paths *)
+ match (p1, p2) with
+ (Pdot(p1, s1, pos1), Pdot(p2, s2, pos2)) ->
+ let c = compare p1 p2 in
+ if c <> 0 then c else String.compare s1 s2
+ | (Papply(fun1, arg1), Papply(fun2, arg2)) ->
+ let c = compare fun1 fun2 in
+ if c <> 0 then c else compare arg1 arg2
+ | _ -> Pervasives.compare p1 p2
+end
+module PathMap = Map.Make(Path2)
+let printing_map = ref PathMap.empty
+
+let same_type t t' = repr t == repr t'
+
+let rec index l x =
+ match l with
+ [] -> raise Not_found
+ | a :: l -> if x == a then 0 else 1 + index l x
+
+let rec uniq = function
+ [] -> true
+ | a :: l -> not (List.memq a l) && uniq l
+
+let rec normalize_type_path ?(cache=false) env p =
+ try
+ let (params, ty, _) = Env.find_type_expansion p env in
+ let params = List.map repr params in
+ match repr ty with
+ {desc = Tconstr (p1, tyl, _)} ->
+ let tyl = List.map repr tyl in
+ if List.length params = List.length tyl
+ && List.for_all2 (==) params tyl
+ then normalize_type_path ~cache env p1
+ else if cache || List.length params <= List.length tyl
+ || not (uniq tyl) then (p, Id)
+ else
+ let l1 = List.map (index params) tyl in
+ let (p2, s2) = normalize_type_path ~cache env p1 in
+ (p2, compose l1 s2)
+ | ty ->
+ (p, Nth (index params ty))
+ with
+ Not_found -> (p, Id)
+
+let rec path_size = function
+ Pident id ->
+ (let s = Ident.name id in if s <> "" && s.[0] = '_' then 10 else 1),
+ -Ident.binding_time id
+ | Pdot (p, _, _) ->
+ let (l, b) = path_size p in (1+l, b)
+ | Papply (p1, p2) ->
+ let (l, b) = path_size p1 in
+ (l + fst (path_size p2), b)
+
+let same_printing_env env =
+ let used_pers = Env.used_persistent () in
+ Env.same_types !printing_old env && Concr.equal !printing_pers used_pers
+
+let set_printing_env env =
+ printing_env := if !Clflags.real_paths then Env.empty else env;
+ if !printing_env == Env.empty || same_printing_env env then () else
+ begin
+ (* printf "Reset printing_map@."; *)
+ printing_old := env;
+ printing_pers := Env.used_persistent ();
+ printing_map := PathMap.empty;
+ printing_depth := 0;
+ (* printf "Recompute printing_map.@."; *)
+ let cont =
+ Env.iter_types
+ (fun p (p', decl) ->
+ let (p1, s1) = normalize_type_path env p' ~cache:true in
+ (* Format.eprintf "%a -> %a = %a@." path p path p' path p1 *)
+ if s1 = Id then
+ try
+ let r = PathMap.find p1 !printing_map in
+ match !r with
+ Paths l -> r := Paths (p :: l)
+ | Best p' -> r := Paths [p; p'] (* assert false *)
+ with Not_found ->
+ printing_map := PathMap.add p1 (ref (Paths [p])) !printing_map)
+ env in
+ printing_cont := [cont];
+ end
+
+let wrap_printing_env env f =
+ set_printing_env env;
+ try_finally f (fun () -> set_printing_env Env.empty)
+
+let is_unambiguous path env =
+ let l = Env.find_shadowed_types path env in
+ List.exists (Path.same path) l || (* concrete paths are ok *)
+ match l with
+ [] -> true
+ | p :: rem ->
+ (* allow also coherent paths: *)
+ let normalize p = fst (normalize_type_path ~cache:true env p) in
+ let p' = normalize p in
+ List.for_all (fun p -> Path.same (normalize p) p') rem ||
+ (* also allow repeatedly defining and opening (for toplevel) *)
+ let id = lid_of_path p in
+ List.for_all (fun p -> lid_of_path p = id) rem &&
+ Path.same p (fst (Env.lookup_type id env))
+
+let rec get_best_path r =
+ match !r with
+ Best p' -> p'
+ | Paths [] -> raise Not_found
+ | Paths l ->
+ r := Paths [];
+ List.iter
+ (fun p ->
+ (* Format.eprintf "evaluating %a@." path p; *)
+ match !r with
+ Best p' when path_size p >= path_size p' -> ()
+ | _ -> if is_unambiguous p !printing_env then r := Best p)
+ (* else Format.eprintf "%a ignored as ambiguous@." path p *)
+ l;
+ get_best_path r
+
+let best_type_path p =
+ if !Clflags.real_paths || !printing_env == Env.empty
+ then (p, Id)
+ else
+ let (p', s) = normalize_type_path !printing_env p in
+ let get_path () = get_best_path (PathMap.find p' !printing_map) in
+ while !printing_cont <> [] &&
+ try ignore (get_path ()); false with Not_found -> true
+ do
+ printing_cont := List.map snd (Env.run_iter_cont !printing_cont);
+ incr printing_depth;
+ done;
+ let p'' = try get_path () with Not_found -> p' in
+ (* Format.eprintf "%a = %a -> %a@." path p path p' path p''; *)
+ (p'', s)
+
+(* Print a type expression *)
+
+let names = ref ([] : (type_expr * string) list)
+let name_counter = ref 0
+let named_vars = ref ([] : string list)
+
+let reset_names () = names := []; name_counter := 0; named_vars := []
+let add_named_var ty =
+ match ty.desc with
+ Tvar (Some name) | Tunivar (Some name) ->
+ if List.mem name !named_vars then () else
+ named_vars := name :: !named_vars
+ | _ -> ()
+
+let rec new_name () =
+ let name =
+ if !name_counter < 26
+ then String.make 1 (Char.chr(97 + !name_counter))
+ else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
+ string_of_int(!name_counter / 26) in
+ incr name_counter;
+ if List.mem name !named_vars
+ || List.exists (fun (_, name') -> name = name') !names
+ then new_name ()
+ else name
+
+let name_of_type t =
+ (* We've already been through repr at this stage, so t is our representative
+ of the union-find class. *)
+ try List.assq t !names with Not_found ->
+ let name =
+ match t.desc with
+ Tvar (Some name) | Tunivar (Some name) ->
+ (* Some part of the type we've already printed has assigned another
+ * unification variable to that name. We want to keep the name, so try
+ * adding a number until we find a name that's not taken. *)
+ let current_name = ref name in
+ let i = ref 0 in
+ while List.exists (fun (_, name') -> !current_name = name') !names do
+ current_name := name ^ (string_of_int !i);
+ i := !i + 1;
+ done;
+ !current_name
+ | _ ->
+ (* No name available, create a new one *)
+ new_name ()
+ in
+ (* Exception for type declarations *)
+ if name <> "_" then names := (t, name) :: !names;
+ name
+
+let check_name_of_type t = ignore(name_of_type t)
+
+let remove_names tyl =
+ let tyl = List.map repr tyl in
+ names := List.filter (fun (ty,_) -> not (List.memq ty tyl)) !names
+
+
+let non_gen_mark sch ty =
+ if sch && is_Tvar ty && ty.level <> generic_level then "_" else ""
+
+let print_name_of_type sch ppf t =
+ fprintf ppf "'%s%s" (non_gen_mark sch t) (name_of_type t)
+
+let visited_objects = ref ([] : type_expr list)
+let aliased = ref ([] : type_expr list)
+let delayed = ref ([] : type_expr list)
+
+let add_delayed t =
+ if not (List.memq t !delayed) then delayed := t :: !delayed
+
+let is_aliased ty = List.memq (proxy ty) !aliased
+let add_alias ty =
+ let px = proxy ty in
+ if not (is_aliased px) then begin
+ aliased := px :: !aliased;
+ add_named_var px
+ end
+
+let aliasable ty =
+ match ty.desc with
+ Tvar _ | Tunivar _ | Tpoly _ -> false
+ | Tconstr (p, _, _) ->
+ not (is_nth (snd (best_type_path p)))
+ | _ -> true
+
+let namable_row row =
+ row.row_name <> None &&
+ List.for_all
+ (fun (_, f) ->
+ match row_field_repr f with
+ | Reither(c, l, _, _) ->
+ row.row_closed && if c then l = [] else List.length l = 1
+ | _ -> true)
+ row.row_fields
+
+let rec mark_loops_rec visited ty =
+ let ty = repr ty in
+ let px = proxy ty in
+ if List.memq px visited && aliasable ty then add_alias px else
+ let visited = px :: visited in
+ match ty.desc with
+ | Tvar _ -> add_named_var ty
+ | Tarrow(_, ty1, ty2, _) ->
+ mark_loops_rec visited ty1; mark_loops_rec visited ty2
+ | Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
+ | Tconstr(p, tyl, _) ->
+ let (p', s) = best_type_path p in
+ List.iter (mark_loops_rec visited) (apply_subst s tyl)
+ | Tpackage (_, _, tyl) ->
+ List.iter (mark_loops_rec visited) tyl
+ | Tvariant row ->
+ if List.memq px !visited_objects then add_alias px else
+ begin
+ let row = row_repr row in
+ if not (static_row row) then
+ visited_objects := px :: !visited_objects;
+ match row.row_name with
+ | Some(p, tyl) when namable_row row ->
+ List.iter (mark_loops_rec visited) tyl
+ | _ ->
+ iter_row (mark_loops_rec visited) row
+ end
+ | Tobject (fi, nm) ->
+ if List.memq px !visited_objects then add_alias px else
+ begin
+ if opened_object ty then
+ visited_objects := px :: !visited_objects;
+ begin match !nm with
+ | None ->
+ let fields, _ = flatten_fields fi in
+ List.iter
+ (fun (_, kind, ty) ->
+ if field_kind_repr kind = Fpresent then
+ mark_loops_rec visited ty)
+ fields
+ | Some (_, l) ->
+ List.iter (mark_loops_rec visited) (List.tl l)
+ end
+ end
+ | Tfield(_, kind, ty1, ty2) when field_kind_repr kind = Fpresent ->
+ mark_loops_rec visited ty1; mark_loops_rec visited ty2
+ | Tfield(_, _, _, ty2) ->
+ mark_loops_rec visited ty2
+ | Tnil -> ()
+ | Tsubst ty -> mark_loops_rec visited ty
+ | Tlink _ -> fatal_error "Printtyp.mark_loops_rec (2)"
+ | Tpoly (ty, tyl) ->
+ List.iter (fun t -> add_alias t) tyl;
+ mark_loops_rec visited ty
+ | Tunivar _ -> add_named_var ty
+
+let mark_loops ty =
+ normalize_type Env.empty ty;
+ mark_loops_rec [] ty;;
+
+let reset_loop_marks () =
+ visited_objects := []; aliased := []; delayed := []
+
+let reset () =
+ unique_names := Ident.empty; reset_names (); reset_loop_marks ()
+
+let reset_and_mark_loops ty =
+ reset (); mark_loops ty
+
+let reset_and_mark_loops_list tyl =
+ reset (); List.iter mark_loops tyl
+
+(* Disabled in classic mode when printing an unification error *)
+let print_labels = ref true
+let print_label ppf l =
+ if !print_labels && l <> Nolabel || is_optional l
+ then fprintf ppf "%s:" (string_of_label l)
+
+let rec tree_of_typexp sch ty =
+ let ty = repr ty in
+ let px = proxy ty in
+ if List.mem_assq px !names && not (List.memq px !delayed) then
+ let mark = is_non_gen sch ty in
+ Otyp_var (mark, name_of_type px) else
+
+ let pr_typ () =
+ match ty.desc with
+ | Tvar _ ->
+ Otyp_var (is_non_gen sch ty, name_of_type ty)
+ | Tarrow(l, ty1, ty2, _) ->
+ let pr_arrow l ty1 ty2 =
+ let lab =
+ if !print_labels || is_optional l then string_of_label l else ""
+ in
+ let t1 =
+ if is_optional l then
+ match (repr ty1).desc with
+ | Tconstr(path, [ty], _)
+ when Path.same path Predef.path_option ->
+ tree_of_typexp sch ty
+ | _ -> Otyp_stuff "<hidden>"
+ else tree_of_typexp sch ty1 in
+ Otyp_arrow (lab, t1, tree_of_typexp sch ty2) in
+ pr_arrow l ty1 ty2
+ | Ttuple tyl ->
+ Otyp_tuple (tree_of_typlist sch tyl)
+ | Tconstr(p, tyl, abbrev) ->
+ let p', s = best_type_path p in
+ let tyl' = apply_subst s tyl in
+ if is_nth s then tree_of_typexp sch (List.hd tyl') else
+ Otyp_constr (tree_of_path p', tree_of_typlist sch tyl')
+ | Tvariant row ->
+ let row = row_repr row in
+ let fields =
+ if row.row_closed then
+ List.filter (fun (_, f) -> row_field_repr f <> Rabsent)
+ row.row_fields
+ else row.row_fields in
+ let present =
+ List.filter
+ (fun (_, f) ->
+ match row_field_repr f with
+ | Rpresent _ -> true
+ | _ -> false)
+ fields in
+ let all_present = List.length present = List.length fields in
+ begin match row.row_name with
+ | Some(p, tyl) when namable_row row ->
+ let (p', s) = best_type_path p in
+ let id = tree_of_path p' in
+ let args = tree_of_typlist sch (apply_subst s tyl) in
+ if row.row_closed && all_present then
+ if is_nth s then List.hd args else Otyp_constr (id, args)
+ else
+ let non_gen = is_non_gen sch px in
+ let tags =
+ if all_present then None else Some (List.map fst present) in
+ let inh =
+ match args with
+ [Otyp_constr (i, a)] when is_nth s -> Ovar_name (i, a)
+ | _ ->
+ (* fallback case, should change outcometree... *)
+ Ovar_name (tree_of_path p, tree_of_typlist sch tyl)
+ in
+ Otyp_variant (non_gen, inh, row.row_closed, tags)
+ | _ ->
+ let non_gen =
+ not (row.row_closed && all_present) && is_non_gen sch px in
+ let fields = List.map (tree_of_row_field sch) fields in
+ let tags =
+ if all_present then None else Some (List.map fst present) in
+ Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
+ end
+ | Tobject (fi, nm) ->
+ tree_of_typobject sch fi !nm
+ | Tnil | Tfield _ ->
+ tree_of_typobject sch ty None
+ | Tsubst ty ->
+ tree_of_typexp sch ty
+ | Tlink _ ->
+ fatal_error "Printtyp.tree_of_typexp"
+ | Tpoly (ty, []) ->
+ tree_of_typexp sch ty
+ | Tpoly (ty, tyl) ->
+ (*let print_names () =
+ List.iter (fun (_, name) -> prerr_string (name ^ " ")) !names;
+ prerr_string "; " in *)
+ let tyl = List.map repr tyl in
+ if tyl = [] then tree_of_typexp sch ty else begin
+ let old_delayed = !delayed in
+ (* Make the names delayed, so that the real type is
+ printed once when used as proxy *)
+ List.iter add_delayed tyl;
+ let tl = List.map name_of_type tyl in
+ let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
+ (* Forget names when we leave scope *)
+ remove_names tyl;
+ delayed := old_delayed; tr
+ end
+ | Tunivar _ ->
+ Otyp_var (false, name_of_type ty)
+ | Tpackage (p, n, tyl) ->
+ let n =
+ List.map (fun li -> String.concat "." (Longident.flatten li)) n in
+ Otyp_module (Path.name p, n, tree_of_typlist sch tyl)
+ in
+ if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
+ if is_aliased px && aliasable ty then begin
+ check_name_of_type px;
+ Otyp_alias (pr_typ (), name_of_type px) end
+ else pr_typ ()
+
+and tree_of_row_field sch (l, f) =
+ match row_field_repr f with
+ | Rpresent None | Reither(true, [], _, _) -> (l, false, [])
+ | Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
+ | Reither(c, tyl, _, _) ->
+ if c (* contradiction: un constructeur constant qui a un argument *)
+ then (l, true, tree_of_typlist sch tyl)
+ else (l, false, tree_of_typlist sch tyl)
+ | Rabsent -> (l, false, [] (* une erreur, en fait *))
+
+and tree_of_typlist sch tyl =
+ List.map (tree_of_typexp sch) tyl
+
+and tree_of_typobject sch fi nm =
+ begin match nm with
+ | None ->
+ let pr_fields fi =
+ let (fields, rest) = flatten_fields fi in
+ let present_fields =
+ List.fold_right
+ (fun (n, k, t) l ->
+ match field_kind_repr k with
+ | Fpresent -> (n, t) :: l
+ | _ -> l)
+ fields [] in
+ let sorted_fields =
+ List.sort (fun (n, _) (n', _) -> compare n n') present_fields in
+ tree_of_typfields sch rest sorted_fields in
+ let (fields, rest) = pr_fields fi in
+ Otyp_object (fields, rest)
+ | Some (p, ty :: tyl) ->
+ let non_gen = is_non_gen sch (repr ty) in
+ let args = tree_of_typlist sch tyl in
+ let (p', s) = best_type_path p in
+ assert (s = Id);
+ Otyp_class (non_gen, tree_of_path p', args)
+ | _ ->
+ fatal_error "Printtyp.tree_of_typobject"
+ end
+
+and is_non_gen sch ty =
+ sch && is_Tvar ty && ty.level <> generic_level
+
+and tree_of_typfields sch rest = function
+ | [] ->
+ let rest =
+ match rest.desc with
+ | Tvar _ | Tunivar _ -> Some (is_non_gen sch rest)
+ | Tconstr _ -> Some false
+ | Tnil -> None
+ | _ -> fatal_error "typfields (1)"
+ in
+ ([], rest)
+ | (s, t) :: l ->
+ let field = (s, tree_of_typexp sch t) in
+ let (fields, rest) = tree_of_typfields sch rest l in
+ (field :: fields, rest)
+
+let typexp sch prio ppf ty =
+ !Oprint.out_type ppf (tree_of_typexp sch ty)
+
+let type_expr ppf ty = typexp false 0 ppf ty
+
+and type_sch ppf ty = typexp true 0 ppf ty
+
+and type_scheme ppf ty = reset_and_mark_loops ty; typexp true 0 ppf ty
+
+(* Maxence *)
+let type_scheme_max ?(b_reset_names=true) ppf ty =
+ if b_reset_names then reset_names () ;
+ typexp true 0 ppf ty
+(* Fin Maxence *)
+
+let tree_of_type_scheme ty = reset_and_mark_loops ty; tree_of_typexp true ty
+
+(* Print one type declaration *)
+
+let tree_of_constraints params =
+ List.fold_right
+ (fun ty list ->
+ let ty' = unalias ty in
+ if proxy ty != proxy ty' then
+ let tr = tree_of_typexp true ty in
+ (tr, tree_of_typexp true ty') :: list
+ else list)
+ params []
+
+let filter_params tyl =
+ let params =
+ List.fold_left
+ (fun tyl ty ->
+ let ty = repr ty in
+ if List.memq ty tyl then Btype.newgenty (Tsubst ty) :: tyl
+ else ty :: tyl)
+ [] tyl
+ in List.rev params
+
+let string_of_mutable = function
+ | Immutable -> ""
+ | Mutable -> "mutable "
+
+
+let mark_loops_constructor_arguments = function
+ | Cstr_tuple l -> List.iter mark_loops l
+ | Cstr_record l -> List.iter (fun l -> mark_loops l.ld_type) l
+
+let rec tree_of_type_decl id decl =
+
+ reset();
+
+ let params = filter_params decl.type_params in
+
+ begin match decl.type_manifest with
+ | Some ty ->
+ let vars = free_variables ty in
+ List.iter
+ (function {desc = Tvar (Some "_")} as ty ->
+ if List.memq ty vars then ty.desc <- Tvar None
+ | _ -> ())
+ params
+ | None -> ()
+ end;
+
+ List.iter add_alias params;
+ List.iter mark_loops params;
+ List.iter check_name_of_type (List.map proxy params);
+ let ty_manifest =
+ match decl.type_manifest with
+ | None -> None
+ | Some ty ->
+ let ty =
+ (* Special hack to hide variant name *)
+ match repr ty with {desc=Tvariant row} ->
+ let row = row_repr row in
+ begin match row.row_name with
+ Some (Pident id', _) when Ident.same id id' ->
+ newgenty (Tvariant {row with row_name = None})
+ | _ -> ty
+ end
+ | _ -> ty
+ in
+ mark_loops ty;
+ Some ty
+ in
+ begin match decl.type_kind with
+ | Type_abstract -> ()
+ | Type_variant cstrs ->
+ List.iter
+ (fun c ->
+ mark_loops_constructor_arguments c.cd_args;
+ may mark_loops c.cd_res)
+ cstrs
+ | Type_record(l, rep) ->
+ List.iter (fun l -> mark_loops l.ld_type) l
+ | Type_open -> ()
+ end;
+
+ let type_param =
+ function
+ | Otyp_var (_, id) -> id
+ | _ -> "?"
+ in
+ let type_defined decl =
+ let abstr =
+ match decl.type_kind with
+ Type_abstract ->
+ decl.type_manifest = None || decl.type_private = Private
+ | Type_record _ ->
+ decl.type_private = Private
+ | Type_variant tll ->
+ decl.type_private = Private ||
+ List.exists (fun cd -> cd.cd_res <> None) tll
+ | Type_open ->
+ decl.type_manifest = None
+ in
+ let vari =
+ List.map2
+ (fun ty v ->
+ if abstr || not (is_Tvar (repr ty)) then Variance.get_upper v
+ else (true,true))
+ decl.type_params decl.type_variance
+ in
+ (Ident.name id,
+ List.map2 (fun ty cocn -> type_param (tree_of_typexp false ty), cocn)
+ params vari)
+ in
+ let tree_of_manifest ty1 =
+ match ty_manifest with
+ | None -> ty1
+ | Some ty -> Otyp_manifest (tree_of_typexp false ty, ty1)
+ in
+ let (name, args) = type_defined decl in
+ let constraints = tree_of_constraints params in
+ let ty, priv =
+ match decl.type_kind with
+ | Type_abstract ->
+ begin match ty_manifest with
+ | None -> (Otyp_abstract, Public)
+ | Some ty ->
+ tree_of_typexp false ty, decl.type_private
+ end
+ | Type_variant cstrs ->
+ tree_of_manifest (Otyp_sum (List.map tree_of_constructor cstrs)),
+ decl.type_private
+ | Type_record(lbls, rep) ->
+ tree_of_manifest (Otyp_record (List.map tree_of_label lbls)),
+ decl.type_private
+ | Type_open ->
+ tree_of_manifest Otyp_open,
+ Public
+ in
+ { otype_name = name;
+ otype_params = args;
+ otype_type = ty;
+ otype_private = priv;
+ otype_cstrs = constraints }
+
+and tree_of_constructor_arguments = function
+ | Cstr_tuple l -> tree_of_typlist false l
+ | Cstr_record l -> [ Otyp_record (List.map tree_of_label l) ]
+
+and tree_of_constructor cd =
+ let name = Ident.name cd.cd_id in
+ let arg () = tree_of_constructor_arguments cd.cd_args in
+ match cd.cd_res with
+ | None -> (name, arg (), None)
+ | Some res ->
+ let nm = !names in
+ names := [];
+ let ret = tree_of_typexp false res in
+ let args = arg () in
+ names := nm;
+ (name, args, Some ret)
+
+and tree_of_label l =
+ (Ident.name l.ld_id, l.ld_mutable = Mutable, tree_of_typexp false l.ld_type)
+
+let tree_of_type_declaration id decl rs =
+ Osig_type (tree_of_type_decl id decl, tree_of_rec rs)
+
+let type_declaration id ppf decl =
+ !Oprint.out_sig_item ppf (tree_of_type_declaration id decl Trec_first)
+
+let constructor_arguments ppf a =
+ let tys = tree_of_constructor_arguments a in
+ !Oprint.out_type ppf (Otyp_tuple tys)
+
+(* Print an extension declaration *)
+
+let tree_of_extension_constructor id ext es =
+ reset ();
+ let ty_name = Path.name ext.ext_type_path in
+ let ty_params = filter_params ext.ext_type_params in
+ List.iter add_alias ty_params;
+ List.iter mark_loops ty_params;
+ List.iter check_name_of_type (List.map proxy ty_params);
+ mark_loops_constructor_arguments ext.ext_args;
+ may mark_loops ext.ext_ret_type;
+ let type_param =
+ function
+ | Otyp_var (_, id) -> id
+ | _ -> "?"
+ in
+ let ty_params =
+ List.map (fun ty -> type_param (tree_of_typexp false ty)) ty_params
+ in
+ let name = Ident.name id in
+ let args, ret =
+ match ext.ext_ret_type with
+ | None -> (tree_of_constructor_arguments ext.ext_args, None)
+ | Some res ->
+ let nm = !names in
+ names := [];
+ let ret = tree_of_typexp false res in
+ let args = tree_of_constructor_arguments ext.ext_args in
+ names := nm;
+ (args, Some ret)
+ in
+ let ext =
+ { oext_name = name;
+ oext_type_name = ty_name;
+ oext_type_params = ty_params;
+ oext_args = args;
+ oext_ret_type = ret;
+ oext_private = ext.ext_private }
+ in
+ let es =
+ match es with
+ Text_first -> Oext_first
+ | Text_next -> Oext_next
+ | Text_exception -> Oext_exception
+ in
+ Osig_typext (ext, es)
+
+let extension_constructor id ppf ext =
+ !Oprint.out_sig_item ppf (tree_of_extension_constructor id ext Text_first)
+
+(* Print a value declaration *)
+
+let rec add_native_repr_attributes ty attrs =
+ match ty, attrs with
+ | Otyp_arrow (label, a, b), attr_opt :: rest ->
+ let b = add_native_repr_attributes b rest in
+ let a =
+ match attr_opt with
+ | None -> a
+ | Some attr -> Otyp_attribute (a, attr)
+ in
+ Otyp_arrow (label, a, b)
+ | _, [Some attr] -> Otyp_attribute (ty, attr)
+ | _ ->
+ assert (List.for_all (fun x -> x = None) attrs);
+ ty
+
+let tree_of_value_description id decl =
+ (* Format.eprintf "@[%a@]@." raw_type_expr decl.val_type; *)
+ let id = Ident.name id in
+ let ty = tree_of_type_scheme decl.val_type in
+ let prims, native_repr_attributes =
+ match decl.val_kind with
+ | Val_prim p -> Primitive.description_list_and_attributes p
+ | _ -> ([], [])
+ in
+ Osig_value (id, add_native_repr_attributes ty native_repr_attributes, prims)
+
+let value_description id ppf decl =
+ !Oprint.out_sig_item ppf (tree_of_value_description id decl)
+
+(* Print a class type *)
+
+let class_var sch ppf l (m, t) =
+ fprintf ppf
+ "@ @[<2>val %s%s :@ %a@]" (string_of_mutable m) l (typexp sch 0) t
+
+let method_type (_, kind, ty) =
+ match field_kind_repr kind, repr ty with
+ Fpresent, {desc=Tpoly(ty, tyl)} -> (ty, tyl)
+ | _ , ty -> (ty, [])
+
+let tree_of_metho sch concrete csil (lab, kind, ty) =
+ if lab <> dummy_method then begin
+ let kind = field_kind_repr kind in
+ let priv = kind <> Fpresent in
+ let virt = not (Concr.mem lab concrete) in
+ let (ty, tyl) = method_type (lab, kind, ty) in
+ let tty = tree_of_typexp sch ty in
+ remove_names tyl;
+ Ocsg_method (lab, priv, virt, tty) :: csil
+ end
+ else csil
+
+let rec prepare_class_type params = function
+ | Cty_constr (p, tyl, cty) ->
+ let sty = Ctype.self_type cty in
+ if List.memq (proxy sty) !visited_objects
+ || not (List.for_all is_Tvar params)
+ || List.exists (deep_occur sty) tyl
+ then prepare_class_type params cty
+ else List.iter mark_loops tyl
+ | Cty_signature sign ->
+ let sty = repr sign.csig_self in
+ (* Self may have a name *)
+ let px = proxy sty in
+ if List.memq px !visited_objects then add_alias sty
+ else visited_objects := px :: !visited_objects;
+ let (fields, _) =
+ Ctype.flatten_fields (Ctype.object_fields sign.csig_self)
+ in
+ List.iter (fun met -> mark_loops (fst (method_type met))) fields;
+ Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.csig_vars
+ | Cty_arrow (_, ty, cty) ->
+ mark_loops ty;
+ prepare_class_type params cty
+
+let rec tree_of_class_type sch params =
+ function
+ | Cty_constr (p', tyl, cty) ->
+ let sty = Ctype.self_type cty in
+ if List.memq (proxy sty) !visited_objects
+ || not (List.for_all is_Tvar params)
+ then
+ tree_of_class_type sch params cty
+ else
+ Octy_constr (tree_of_path p', tree_of_typlist true tyl)
+ | Cty_signature sign ->
+ let sty = repr sign.csig_self in
+ let self_ty =
+ if is_aliased sty then
+ Some (Otyp_var (false, name_of_type (proxy sty)))
+ else None
+ in
+ let (fields, _) =
+ Ctype.flatten_fields (Ctype.object_fields sign.csig_self)
+ in
+ let csil = [] in
+ let csil =
+ List.fold_left
+ (fun csil (ty1, ty2) -> Ocsg_constraint (ty1, ty2) :: csil)
+ csil (tree_of_constraints params)
+ in
+ let all_vars =
+ Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.csig_vars []
+ in
+ (* Consequence of PR#3607: order of Map.fold has changed! *)
+ let all_vars = List.rev all_vars in
+ let csil =
+ List.fold_left
+ (fun csil (l, m, v, t) ->
+ Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
+ :: csil)
+ csil all_vars
+ in
+ let csil =
+ List.fold_left (tree_of_metho sch sign.csig_concr) csil fields
+ in
+ Octy_signature (self_ty, List.rev csil)
+ | Cty_arrow (l, ty, cty) ->
+ let lab =
+ if !print_labels || is_optional l then string_of_label l else ""
+ in
+ let ty =
+ if is_optional l then
+ match (repr ty).desc with
+ | Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty
+ | _ -> newconstr (Path.Pident(Ident.create "<hidden>")) []
+ else ty in
+ let tr = tree_of_typexp sch ty in
+ Octy_arrow (lab, tr, tree_of_class_type sch params cty)
+
+let class_type ppf cty =
+ reset ();
+ prepare_class_type [] cty;
+ !Oprint.out_class_type ppf (tree_of_class_type false [] cty)
+
+let tree_of_class_param param variance =
+ (match tree_of_typexp true param with
+ Otyp_var (_, s) -> s
+ | _ -> "?"),
+ if is_Tvar (repr param) then (true, true) else variance
+
+let tree_of_class_params params =
+ let tyl = tree_of_typlist true params in
+ List.map (function Otyp_var (_, s) -> s | _ -> "?") tyl
+
+let class_variance =
+ List.map Variance.(fun v -> mem May_pos v, mem May_neg v)
+
+let tree_of_class_declaration id cl rs =
+ let params = filter_params cl.cty_params in
+
+ reset ();
+ List.iter add_alias params;
+ prepare_class_type params cl.cty_type;
+ let sty = Ctype.self_type cl.cty_type in
+ List.iter mark_loops params;
+
+ List.iter check_name_of_type (List.map proxy params);
+ if is_aliased sty then check_name_of_type (proxy sty);
+
+ let vir_flag = cl.cty_new = None in
+ Osig_class
+ (vir_flag, Ident.name id,
+ List.map2 tree_of_class_param params (class_variance cl.cty_variance),
+ tree_of_class_type true params cl.cty_type,
+ tree_of_rec rs)
+
+let class_declaration id ppf cl =
+ !Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
+
+let tree_of_cltype_declaration id cl rs =
+ let params = List.map repr cl.clty_params in
+
+ reset ();
+ List.iter add_alias params;
+ prepare_class_type params cl.clty_type;
+ let sty = Ctype.self_type cl.clty_type in
+ List.iter mark_loops params;
+
+ List.iter check_name_of_type (List.map proxy params);
+ if is_aliased sty then check_name_of_type (proxy sty);
+
+ let sign = Ctype.signature_of_class_type cl.clty_type in
+
+ let virt =
+ let (fields, _) =
+ Ctype.flatten_fields (Ctype.object_fields sign.csig_self) in
+ List.exists
+ (fun (lab, _, ty) ->
+ not (lab = dummy_method || Concr.mem lab sign.csig_concr))
+ fields
+ || Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.csig_vars false
+ in
+
+ Osig_class_type
+ (virt, Ident.name id,
+ List.map2 tree_of_class_param params (class_variance cl.clty_variance),
+ tree_of_class_type true params cl.clty_type,
+ tree_of_rec rs)
+
+let cltype_declaration id ppf cl =
+ !Oprint.out_sig_item ppf (tree_of_cltype_declaration id cl Trec_first)
+
+(* Print a module type *)
+
+let wrap_env fenv ftree arg =
+ let env = !printing_env in
+ set_printing_env (fenv env);
+ let tree = ftree arg in
+ set_printing_env env;
+ tree
+
+let filter_rem_sig item rem =
+ match item, rem with
+ | Sig_class _, ctydecl :: tydecl1 :: tydecl2 :: rem ->
+ ([ctydecl; tydecl1; tydecl2], rem)
+ | Sig_class_type _, tydecl1 :: tydecl2 :: rem ->
+ ([tydecl1; tydecl2], rem)
+ | _ ->
+ ([], rem)
+
+let dummy =
+ { type_params = []; type_arity = 0; type_kind = Type_abstract;
+ type_private = Public; type_manifest = None; type_variance = [];
+ type_newtype_level = None; type_loc = Location.none;
+ type_attributes = [];
+ }
+
+let hide_rec_items = function
+ | Sig_type(id, decl, rs) ::rem
+ when rs = Trec_first && not !Clflags.real_paths ->
+ let rec get_ids = function
+ Sig_type (id, _, Trec_next) :: rem ->
+ id :: get_ids rem
+ | _ -> []
+ in
+ let ids = id :: get_ids rem in
+ set_printing_env
+ (List.fold_right
+ (fun id -> Env.add_type ~check:false (Ident.rename id) dummy)
+ ids !printing_env)
+ | _ -> ()
+
+let rec tree_of_modtype ?(ellipsis=false) = function
+ | Mty_ident p ->
+ Omty_ident (tree_of_path p)
+ | Mty_signature sg ->
+ Omty_signature (if ellipsis then [Osig_ellipsis]
+ else tree_of_signature sg)
+ | Mty_functor(param, ty_arg, ty_res) ->
+ let res =
+ match ty_arg with None -> tree_of_modtype ~ellipsis ty_res
+ | Some mty ->
+ wrap_env (Env.add_module ~arg:true param mty)
+ (tree_of_modtype ~ellipsis) ty_res
+ in
+ Omty_functor (Ident.name param,
+ may_map (tree_of_modtype ~ellipsis:false) ty_arg, res)
+ | Mty_alias p ->
+ Omty_alias (tree_of_path p)
+
+and tree_of_signature sg =
+ wrap_env (fun env -> env) (tree_of_signature_rec !printing_env false) sg
+
+and tree_of_signature_rec env' in_type_group = function
+ [] -> []
+ | item :: rem as items ->
+ let in_type_group =
+ match in_type_group, item with
+ true, Sig_type (_, _, Trec_next) -> true
+ | _, Sig_type (_, _, (Trec_not | Trec_first)) ->
+ set_printing_env env'; true
+ | _ -> set_printing_env env'; false
+ in
+ let (sg, rem) = filter_rem_sig item rem in
+ hide_rec_items items;
+ let trees = trees_of_sigitem item in
+ let env' = Env.add_signature (item :: sg) env' in
+ trees @ tree_of_signature_rec env' in_type_group rem
+
+and trees_of_sigitem = function
+ | Sig_value(id, decl) ->
+ [tree_of_value_description id decl]
+ | Sig_type(id, _, _) when is_row_name (Ident.name id) ->
+ []
+ | Sig_type(id, decl, rs) ->
+ [tree_of_type_declaration id decl rs]
+ | Sig_typext(id, ext, es) ->
+ [tree_of_extension_constructor id ext es]
+ | Sig_module(id, md, rs) ->
+ let ellipsis =
+ List.exists (function ({txt="..."}, Parsetree.PStr []) -> true
+ | _ -> false)
+ md.md_attributes in
+ [tree_of_module id md.md_type rs ~ellipsis]
+ | Sig_modtype(id, decl) ->
+ [tree_of_modtype_declaration id decl]
+ | Sig_class(id, decl, rs) ->
+ [tree_of_class_declaration id decl rs]
+ | Sig_class_type(id, decl, rs) ->
+ [tree_of_cltype_declaration id decl rs]
+
+and tree_of_modtype_declaration id decl =
+ let mty =
+ match decl.mtd_type with
+ | None -> Omty_abstract
+ | Some mty -> tree_of_modtype mty
+ in
+ Osig_modtype (Ident.name id, mty)
+
+and tree_of_module id ?ellipsis mty rs =
+ Osig_module (Ident.name id, tree_of_modtype ?ellipsis mty, tree_of_rec rs)
+
+let modtype ppf mty = !Oprint.out_module_type ppf (tree_of_modtype mty)
+let modtype_declaration id ppf decl =
+ !Oprint.out_sig_item ppf (tree_of_modtype_declaration id decl)
+
+(* For the toplevel: merge with tree_of_signature? *)
+let rec print_items showval env = function
+ | [] -> []
+ | item :: rem as items ->
+ let (sg, rem) = filter_rem_sig item rem in
+ hide_rec_items items;
+ let trees = trees_of_sigitem item in
+ List.map (fun d -> (d, showval env item)) trees @
+ print_items showval env rem
+
+(* Print a signature body (used by -i when compiling a .ml) *)
+
+let print_signature ppf tree =
+ fprintf ppf "@[<v>%a@]" !Oprint.out_signature tree
+
+let signature ppf sg =
+ fprintf ppf "%a" print_signature (tree_of_signature sg)
+
+(* Print an unification error *)
+
+let same_path t t' =
+ let t = repr t and t' = repr t' in
+ t == t' ||
+ match t.desc, t'.desc with
+ Tconstr(p,tl,_), Tconstr(p',tl',_) ->
+ let (p1, s1) = best_type_path p and (p2, s2) = best_type_path p' in
+ begin match s1, s2 with
+ Nth n1, Nth n2 when n1 = n2 -> true
+ | (Id | Map _), (Id | Map _) when Path.same p1 p2 ->
+ let tl = apply_subst s1 tl and tl' = apply_subst s2 tl' in
+ List.length tl = List.length tl' &&
+ List.for_all2 same_type tl tl'
+ | _ -> false
+ end
+ | _ ->
+ false
+
+let type_expansion t ppf t' =
+ if same_path t t' then type_expr ppf t else
+ let t' = if proxy t == proxy t' then unalias t' else t' in
+ fprintf ppf "@[<2>%a@ =@ %a@]" type_expr t type_expr t'
+
+let type_path_expansion tp ppf tp' =
+ if Path.same tp tp' then path ppf tp else
+ fprintf ppf "@[<2>%a@ =@ %a@]" path tp path tp'
+
+let rec trace fst txt ppf = function
+ | (t1, t1') :: (t2, t2') :: rem ->
+ if not fst then fprintf ppf "@,";
+ fprintf ppf "@[Type@;<1 2>%a@ %s@;<1 2>%a@] %a"
+ (type_expansion t1) t1' txt (type_expansion t2) t2'
+ (trace false txt) rem
+ | _ -> ()
+
+let rec filter_trace keep_last = function
+ | (_, t1') :: (_, t2') :: [] when is_Tvar t1' || is_Tvar t2' ->
+ []
+ | (t1, t1') :: (t2, t2') :: rem ->
+ let rem' = filter_trace keep_last rem in
+ if is_constr_row t1' || is_constr_row t2'
+ || same_path t1 t1' && same_path t2 t2' && not (keep_last && rem' = [])
+ then rem'
+ else (t1, t1') :: (t2, t2') :: rem'
+ | _ -> []
+
+let rec type_path_list ppf = function
+ | [tp, tp'] -> type_path_expansion tp ppf tp'
+ | (tp, tp') :: rem ->
+ fprintf ppf "%a@;<2 0>%a"
+ (type_path_expansion tp) tp'
+ type_path_list rem
+ | [] -> ()
+
+(* Hide variant name and var, to force printing the expanded type *)
+let hide_variant_name t =
+ match repr t with
+ | {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
+ newty2 t.level
+ (Tvariant {(row_repr row) with row_name = None;
+ row_more = newvar2 (row_more row).level})
+ | _ -> t
+
+let prepare_expansion (t, t') =
+ let t' = hide_variant_name t' in
+ mark_loops t;
+ if not (same_path t t') then mark_loops t';
+ (t, t')
+
+let may_prepare_expansion compact (t, t') =
+ match (repr t').desc with
+ Tvariant _ | Tobject _ when compact ->
+ mark_loops t; (t, t)
+ | _ -> prepare_expansion (t, t')
+
+let print_tags ppf fields =
+ match fields with [] -> ()
+ | (t, _) :: fields ->
+ fprintf ppf "`%s" t;
+ List.iter (fun (t, _) -> fprintf ppf ",@ `%s" t) fields
+
+let has_explanation unif t3 t4 =
+ match t3.desc, t4.desc with
+ Tfield _, (Tnil|Tconstr _) | (Tnil|Tconstr _), Tfield _
+ | Tnil, Tconstr _ | Tconstr _, Tnil
+ | _, Tvar _ | Tvar _, _
+ | Tvariant _, Tvariant _ -> true
+ | Tfield (l,_,_,{desc=Tnil}), Tfield (l',_,_,{desc=Tnil}) -> l = l'
+ | _ -> false
+
+let rec mismatch unif = function
+ (_, t) :: (_, t') :: rem ->
+ begin match mismatch unif rem with
+ Some _ as m -> m
+ | None ->
+ if has_explanation unif t t' then Some(t,t') else None
+ end
+ | [] -> None
+ | _ -> assert false
+
+let explanation unif t3 t4 ppf =
+ match t3.desc, t4.desc with
+ | Ttuple [], Tvar _ | Tvar _, Ttuple [] ->
+ fprintf ppf "@,Self type cannot escape its class"
+ | Tconstr (p, tl, _), Tvar _
+ when unif && t4.level < Path.binding_time p ->
+ fprintf ppf
+ "@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
+ path p
+ | Tvar _, Tconstr (p, tl, _)
+ when unif && t3.level < Path.binding_time p ->
+ fprintf ppf
+ "@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
+ path p
+ | Tvar _, Tunivar _ | Tunivar _, Tvar _ ->
+ fprintf ppf "@,The universal variable %a would escape its scope"
+ type_expr (if is_Tunivar t3 then t3 else t4)
+ | Tvar _, _ | _, Tvar _ ->
+ let t, t' = if is_Tvar t3 then (t3, t4) else (t4, t3) in
+ if occur_in Env.empty t t' then
+ fprintf ppf "@,@[<hov>The type variable %a occurs inside@ %a@]"
+ type_expr t type_expr t'
+ else
+ fprintf ppf "@,@[<hov>This instance of %a is ambiguous:@ %s@]"
+ type_expr t'
+ "it would escape the scope of its equation"
+ | Tfield (lab, _, _, _), _
+ | _, Tfield (lab, _, _, _) when lab = dummy_method ->
+ fprintf ppf
+ "@,Self type cannot be unified with a closed object type"
+ | Tfield (l,_,_,{desc=Tnil}), Tfield (l',_,_,{desc=Tnil}) when l = l' ->
+ fprintf ppf "@,Types for method %s are incompatible" l
+ | (Tnil|Tconstr _), Tfield (l, _, _, _) ->
+ fprintf ppf
+ "@,@[The first object type has no method %s@]" l
+ | Tfield (l, _, _, _), (Tnil|Tconstr _) ->
+ fprintf ppf
+ "@,@[The second object type has no method %s@]" l
+ | Tnil, Tconstr _ | Tconstr _, Tnil ->
+ fprintf ppf
+ "@,@[The %s object type has an abstract row, it cannot be closed@]"
+ (if t4.desc = Tnil then "first" else "second")
+ | Tvariant row1, Tvariant row2 ->
+ let row1 = row_repr row1 and row2 = row_repr row2 in
+ begin match
+ row1.row_fields, row1.row_closed, row2.row_fields, row2.row_closed with
+ | [], true, [], true ->
+ fprintf ppf "@,These two variant types have no intersection"
+ | [], true, fields, _ ->
+ fprintf ppf
+ "@,@[The first variant type does not allow tag(s)@ @[<hov>%a@]@]"
+ print_tags fields
+ | fields, _, [], true ->
+ fprintf ppf
+ "@,@[The second variant type does not allow tag(s)@ @[<hov>%a@]@]"
+ print_tags fields
+ | [l1,_], true, [l2,_], true when l1 = l2 ->
+ fprintf ppf "@,Types for tag `%s are incompatible" l1
+ | _ -> ()
+ end
+ | _ -> ()
+
+let explanation unif mis ppf =
+ match mis with
+ None -> ()
+ | Some (t3, t4) -> explanation unif t3 t4 ppf
+
+let ident_same_name id1 id2 =
+ if Ident.equal id1 id2 && not (Ident.same id1 id2) then begin
+ add_unique id1; add_unique id2
+ end
+
+let rec path_same_name p1 p2 =
+ match p1, p2 with
+ Pident id1, Pident id2 -> ident_same_name id1 id2
+ | Pdot (p1, s1, _), Pdot (p2, s2, _) when s1 = s2 -> path_same_name p1 p2
+ | Papply (p1, p1'), Papply (p2, p2') ->
+ path_same_name p1 p2; path_same_name p1' p2'
+ | _ -> ()
+
+let type_same_name t1 t2 =
+ match (repr t1).desc, (repr t2).desc with
+ Tconstr (p1, _, _), Tconstr (p2, _, _) ->
+ path_same_name (fst (best_type_path p1)) (fst (best_type_path p2))
+ | _ -> ()
+
+let rec trace_same_names = function
+ (t1, t1') :: (t2, t2') :: rem ->
+ type_same_name t1 t2; type_same_name t1' t2'; trace_same_names rem
+ | _ -> ()
+
+let unification_error unif tr txt1 ppf txt2 =
+ reset ();
+ trace_same_names tr;
+ let tr = List.map (fun (t, t') -> (t, hide_variant_name t')) tr in
+ let mis = mismatch unif tr in
+ match tr with
+ | [] | _ :: [] -> assert false
+ | t1 :: t2 :: tr ->
+ try
+ let tr = filter_trace (mis = None) tr in
+ let t1, t1' = may_prepare_expansion (tr = []) t1
+ and t2, t2' = may_prepare_expansion (tr = []) t2 in
+ print_labels := not !Clflags.classic;
+ let tr = List.map prepare_expansion tr in
+ fprintf ppf
+ "@[<v>\
+ @[%t@;<1 2>%a@ \
+ %t@;<1 2>%a\
+ @]%a%t\
+ @]"
+ txt1 (type_expansion t1) t1'
+ txt2 (type_expansion t2) t2'
+ (trace false "is not compatible with type") tr
+ (explanation unif mis);
+ print_labels := true
+ with exn ->
+ print_labels := true;
+ raise exn
+
+let report_unification_error ppf env ?(unif=true)
+ tr txt1 txt2 =
+ wrap_printing_env env (fun () -> unification_error unif tr txt1 ppf txt2)
+;;
+
+let trace fst keep_last txt ppf tr =
+ print_labels := not !Clflags.classic;
+ trace_same_names tr;
+ try match tr with
+ t1 :: t2 :: tr' ->
+ if fst then trace fst txt ppf (t1 :: t2 :: filter_trace keep_last tr')
+ else trace fst txt ppf (filter_trace keep_last tr);
+ print_labels := true
+ | _ -> ()
+ with exn ->
+ print_labels := true;
+ raise exn
+
+let report_subtyping_error ppf env tr1 txt1 tr2 =
+ wrap_printing_env env (fun () ->
+ reset ();
+ let tr1 = List.map prepare_expansion tr1
+ and tr2 = List.map prepare_expansion tr2 in
+ fprintf ppf "@[<v>%a" (trace true (tr2 = []) txt1) tr1;
+ if tr2 = [] then fprintf ppf "@]" else
+ let mis = mismatch true tr2 in
+ fprintf ppf "%a%t@]"
+ (trace false (mis = None) "is not compatible with type") tr2
+ (explanation true mis))
+
+let report_ambiguous_type_error ppf env (tp0, tp0') tpl txt1 txt2 txt3 =
+ wrap_printing_env env (fun () ->
+ reset ();
+ List.iter
+ (fun (tp, tp') -> path_same_name tp0 tp; path_same_name tp0' tp')
+ tpl;
+ match tpl with
+ [] -> assert false
+ | [tp, tp'] ->
+ fprintf ppf
+ "@[%t@;<1 2>%a@ \
+ %t@;<1 2>%a\
+ @]"
+ txt1 (type_path_expansion tp) tp'
+ txt3 (type_path_expansion tp0) tp0'
+ | _ ->
+ fprintf ppf
+ "@[%t@;<1 2>@[<hv>%a@]\
+ @ %t@;<1 2>%a\
+ @]"
+ txt2 type_path_list tpl
+ txt3 (type_path_expansion tp0) tp0')
diff --git a/typing/printtyp.mli b/typing/printtyp.mli
new file mode 100644
index 0000000000..fd1d53aa7d
--- /dev/null
+++ b/typing/printtyp.mli
@@ -0,0 +1,87 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Printing functions *)
+
+open Format
+open Types
+open Outcometree
+
+val longident: formatter -> Longident.t -> unit
+val ident: formatter -> Ident.t -> unit
+val tree_of_path: Path.t -> out_ident
+val path: formatter -> Path.t -> unit
+val string_of_path: Path.t -> string
+val raw_type_expr: formatter -> type_expr -> unit
+val string_of_label: Asttypes.arg_label -> string
+
+val wrap_printing_env: Env.t -> (unit -> 'a) -> 'a
+ (* Call the function using the environment for type path shortening *)
+ (* This affects all the printing functions below *)
+
+val reset: unit -> unit
+val mark_loops: type_expr -> unit
+val reset_and_mark_loops: type_expr -> unit
+val reset_and_mark_loops_list: type_expr list -> unit
+val type_expr: formatter -> type_expr -> unit
+val constructor_arguments: formatter -> constructor_arguments -> unit
+val tree_of_type_scheme: type_expr -> out_type
+val type_sch : formatter -> type_expr -> unit
+val type_scheme: formatter -> type_expr -> unit
+(* Maxence *)
+val reset_names: unit -> unit
+val type_scheme_max: ?b_reset_names: bool ->
+ formatter -> type_expr -> unit
+(* Fin Maxence *)
+val tree_of_value_description: Ident.t -> value_description -> out_sig_item
+val value_description: Ident.t -> formatter -> value_description -> unit
+val tree_of_type_declaration:
+ Ident.t -> type_declaration -> rec_status -> out_sig_item
+val type_declaration: Ident.t -> formatter -> type_declaration -> unit
+val tree_of_extension_constructor:
+ Ident.t -> extension_constructor -> ext_status -> out_sig_item
+val extension_constructor:
+ Ident.t -> formatter -> extension_constructor -> unit
+val tree_of_module:
+ Ident.t -> ?ellipsis:bool -> module_type -> rec_status -> out_sig_item
+val modtype: formatter -> module_type -> unit
+val signature: formatter -> signature -> unit
+val tree_of_modtype_declaration:
+ Ident.t -> modtype_declaration -> out_sig_item
+val tree_of_signature: Types.signature -> out_sig_item list
+val tree_of_typexp: bool -> type_expr -> out_type
+val modtype_declaration: Ident.t -> formatter -> modtype_declaration -> unit
+val class_type: formatter -> class_type -> unit
+val tree_of_class_declaration:
+ Ident.t -> class_declaration -> rec_status -> out_sig_item
+val class_declaration: Ident.t -> formatter -> class_declaration -> unit
+val tree_of_cltype_declaration:
+ Ident.t -> class_type_declaration -> rec_status -> out_sig_item
+val cltype_declaration: Ident.t -> formatter -> class_type_declaration -> unit
+val type_expansion: type_expr -> Format.formatter -> type_expr -> unit
+val prepare_expansion: type_expr * type_expr -> type_expr * type_expr
+val trace:
+ bool -> bool-> string -> formatter -> (type_expr * type_expr) list -> unit
+val report_unification_error:
+ formatter -> Env.t -> ?unif:bool -> (type_expr * type_expr) list ->
+ (formatter -> unit) -> (formatter -> unit) ->
+ unit
+val report_subtyping_error:
+ formatter -> Env.t -> (type_expr * type_expr) list ->
+ string -> (type_expr * type_expr) list -> unit
+val report_ambiguous_type_error:
+ formatter -> Env.t -> (Path.t * Path.t) -> (Path.t * Path.t) list ->
+ (formatter -> unit) -> (formatter -> unit) -> (formatter -> unit) -> unit
+
+(* for toploop *)
+val print_items: (Env.t -> signature_item -> 'a option) ->
+ Env.t -> signature_item list -> (out_sig_item * 'a option) list
diff --git a/typing/printtyped.ml b/typing/printtyped.ml
new file mode 100644
index 0000000000..58756c6a49
--- /dev/null
+++ b/typing/printtyped.ml
@@ -0,0 +1,859 @@
+2(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Tublic License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Asttypes;;
+open Format;;
+open Lexing;;
+open Location;;
+open Typedtree;;
+
+let fmt_position f l =
+ if l.pos_lnum = -1
+ then fprintf f "%s[%d]" l.pos_fname l.pos_cnum
+ else fprintf f "%s[%d,%d+%d]" l.pos_fname l.pos_lnum l.pos_bol
+ (l.pos_cnum - l.pos_bol)
+;;
+
+let fmt_location f loc =
+ fprintf f "(%a..%a)" fmt_position loc.loc_start fmt_position loc.loc_end;
+ if loc.loc_ghost then fprintf f " ghost";
+;;
+
+let rec fmt_longident_aux f x =
+ match x with
+ | Longident.Lident (s) -> fprintf f "%s" s;
+ | Longident.Ldot (y, s) -> fprintf f "%a.%s" fmt_longident_aux y s;
+ | Longident.Lapply (y, z) ->
+ fprintf f "%a(%a)" fmt_longident_aux y fmt_longident_aux z;
+;;
+
+let fmt_longident_noloc f x = fprintf f "\"%a\"" fmt_longident_aux x;;
+let fmt_longident f x = fprintf f "\"%a\"" fmt_longident_aux x.txt;;
+
+let fmt_ident = Ident.print
+
+let rec fmt_path_aux f x =
+ match x with
+ | Path.Pident (s) -> fprintf f "%a" fmt_ident s;
+ | Path.Pdot (y, s, _pos) -> fprintf f "%a.%s" fmt_path_aux y s;
+ | Path.Papply (y, z) ->
+ fprintf f "%a(%a)" fmt_path_aux y fmt_path_aux z;
+;;
+
+let fmt_path f x = fprintf f "\"%a\"" fmt_path_aux x;;
+let fmt_path_loc f x = fprintf f "\"%a\"" fmt_path_aux x.txt;;
+
+let fmt_constant f x =
+ match x with
+ | Const_int (i) -> fprintf f "Const_int %d" i;
+ | Const_char (c) -> fprintf f "Const_char %02x" (Char.code c);
+ | Const_string (s, None) -> fprintf f "Const_string(%S,None)" s;
+ | Const_string (s, Some delim) ->
+ fprintf f "Const_string (%S,Some %S)" s delim;
+ | Const_float (s) -> fprintf f "Const_float %s" s;
+ | Const_int32 (i) -> fprintf f "Const_int32 %ld" i;
+ | Const_int64 (i) -> fprintf f "Const_int64 %Ld" i;
+ | Const_nativeint (i) -> fprintf f "Const_nativeint %nd" i;
+;;
+
+let fmt_mutable_flag f x =
+ match x with
+ | Immutable -> fprintf f "Immutable";
+ | Mutable -> fprintf f "Mutable";
+;;
+
+let fmt_virtual_flag f x =
+ match x with
+ | Virtual -> fprintf f "Virtual";
+ | Concrete -> fprintf f "Concrete";
+;;
+
+let fmt_override_flag f x =
+ match x with
+ | Override -> fprintf f "Override";
+ | Fresh -> fprintf f "Fresh";
+;;
+
+let fmt_closed_flag f x =
+ match x with
+ | Closed -> fprintf f "Closed"
+ | Open -> fprintf f "Open"
+
+let fmt_rec_flag f x =
+ match x with
+ | Nonrecursive -> fprintf f "Nonrec";
+ | Recursive -> fprintf f "Rec";
+;;
+
+let fmt_direction_flag f x =
+ match x with
+ | Upto -> fprintf f "Up";
+ | Downto -> fprintf f "Down";
+;;
+
+let fmt_private_flag f x =
+ match x with
+ | Public -> fprintf f "Public";
+ | Private -> fprintf f "Private";
+;;
+
+let line i f s (*...*) =
+ fprintf f "%s" (String.make (2*i) ' ');
+ fprintf f s (*...*)
+;;
+
+let list i f ppf l =
+ match l with
+ | [] -> line i ppf "[]\n";
+ | _ :: _ ->
+ line i ppf "[\n";
+ List.iter (f (i+1) ppf) l;
+ line i ppf "]\n";
+;;
+
+let option i f ppf x =
+ match x with
+ | None -> line i ppf "None\n";
+ | Some x ->
+ line i ppf "Some\n";
+ f (i+1) ppf x;
+;;
+
+let longident i ppf li = line i ppf "%a\n" fmt_longident li;;
+let path i ppf li = line i ppf "%a\n" fmt_path li;;
+let ident i ppf li = line i ppf "%a\n" fmt_ident li;;
+let string i ppf s = line i ppf "\"%s\"\n" s;;
+let string_loc i ppf s = line i ppf "\"%s\"\n" s.txt;;
+let bool i ppf x = line i ppf "%s\n" (string_of_bool x);;
+let label i ppf x = line i ppf "label=\"%s\"\n" x;;
+let arg_label i ppf = function
+ | Nolabel -> line i ppf "Nolabel\n"
+ | Optional s -> line i ppf "Optional \"%s\"\n" s
+ | Labelled s -> line i ppf "Labelled \"%s\"\n" s
+;;
+
+let attributes i ppf l =
+ let i = i + 1 in
+ List.iter
+ (fun (s, arg) ->
+ line i ppf "attribute \"%s\"\n" s.txt;
+ Printast.payload (i + 1) ppf arg;
+ )
+ l
+
+let rec core_type i ppf x =
+ line i ppf "core_type %a\n" fmt_location x.ctyp_loc;
+ attributes i ppf x.ctyp_attributes;
+ let i = i+1 in
+ match x.ctyp_desc with
+ | Ttyp_any -> line i ppf "Ttyp_any\n";
+ | Ttyp_var (s) -> line i ppf "Ttyp_var %s\n" s;
+ | Ttyp_arrow (l, ct1, ct2) ->
+ line i ppf "Ttyp_arrow\n";
+ arg_label i ppf l;
+ core_type i ppf ct1;
+ core_type i ppf ct2;
+ | Ttyp_tuple l ->
+ line i ppf "Ttyp_tuple\n";
+ list i core_type ppf l;
+ | Ttyp_constr (li, _, l) ->
+ line i ppf "Ttyp_constr %a\n" fmt_path li;
+ list i core_type ppf l;
+ | Ttyp_variant (l, closed, low) ->
+ line i ppf "Ttyp_variant closed=%a\n" fmt_closed_flag closed;
+ list i label_x_bool_x_core_type_list ppf l;
+ option i (fun i -> list i string) ppf low
+ | Ttyp_object (l, c) ->
+ line i ppf "Ttyp_object %a\n" fmt_closed_flag c;
+ let i = i + 1 in
+ List.iter
+ (fun (s, attrs, t) ->
+ line i ppf "method %s\n" s;
+ attributes i ppf attrs;
+ core_type (i + 1) ppf t
+ )
+ l
+ | Ttyp_class (li, _, l) ->
+ line i ppf "Ttyp_class %a\n" fmt_path li;
+ list i core_type ppf l;
+ | Ttyp_alias (ct, s) ->
+ line i ppf "Ttyp_alias \"%s\"\n" s;
+ core_type i ppf ct;
+ | Ttyp_poly (sl, ct) ->
+ line i ppf "Ttyp_poly%a\n"
+ (fun ppf -> List.iter (fun x -> fprintf ppf " '%s" x)) sl;
+ core_type i ppf ct;
+ | Ttyp_package { pack_path = s; pack_fields = l } ->
+ line i ppf "Ttyp_package %a\n" fmt_path s;
+ list i package_with ppf l;
+
+and package_with i ppf (s, t) =
+ line i ppf "with type %a\n" fmt_longident s;
+ core_type i ppf t
+
+and pattern i ppf x =
+ line i ppf "pattern %a\n" fmt_location x.pat_loc;
+ attributes i ppf x.pat_attributes;
+ let i = i+1 in
+ match x.pat_extra with
+ | (Tpat_unpack, _, attrs) :: rem ->
+ line i ppf "Tpat_unpack\n";
+ attributes i ppf attrs;
+ pattern i ppf { x with pat_extra = rem }
+ | (Tpat_constraint cty, _, attrs) :: rem ->
+ line i ppf "Tpat_constraint\n";
+ attributes i ppf attrs;
+ core_type i ppf cty;
+ pattern i ppf { x with pat_extra = rem }
+ | (Tpat_type (id, _), _, attrs) :: rem ->
+ line i ppf "Tpat_type %a\n" fmt_path id;
+ attributes i ppf attrs;
+ pattern i ppf { x with pat_extra = rem }
+ | [] ->
+ match x.pat_desc with
+ | Tpat_any -> line i ppf "Tpat_any\n";
+ | Tpat_var (s,_) -> line i ppf "Tpat_var \"%a\"\n" fmt_ident s;
+ | Tpat_alias (p, s,_) ->
+ line i ppf "Tpat_alias \"%a\"\n" fmt_ident s;
+ pattern i ppf p;
+ | Tpat_constant (c) -> line i ppf "Tpat_constant %a\n" fmt_constant c;
+ | Tpat_tuple (l) ->
+ line i ppf "Tpat_tuple\n";
+ list i pattern ppf l;
+ | Tpat_construct (li, _, po) ->
+ line i ppf "Tpat_construct %a\n" fmt_longident li;
+ list i pattern ppf po;
+ | Tpat_variant (l, po, _) ->
+ line i ppf "Tpat_variant \"%s\"\n" l;
+ option i pattern ppf po;
+ | Tpat_record (l, c) ->
+ line i ppf "Tpat_record\n";
+ list i longident_x_pattern ppf l;
+ | Tpat_array (l) ->
+ line i ppf "Tpat_array\n";
+ list i pattern ppf l;
+ | Tpat_or (p1, p2, _) ->
+ line i ppf "Tpat_or\n";
+ pattern i ppf p1;
+ pattern i ppf p2;
+ | Tpat_lazy p ->
+ line i ppf "Tpat_lazy\n";
+ pattern i ppf p;
+
+and expression_extra i ppf x attrs =
+ match x with
+ | Texp_constraint ct ->
+ line i ppf "Texp_constraint\n";
+ attributes i ppf attrs;
+ core_type i ppf ct;
+ | Texp_coerce (cto1, cto2) ->
+ line i ppf "Texp_coerce\n";
+ attributes i ppf attrs;
+ option i core_type ppf cto1;
+ core_type i ppf cto2;
+ | Texp_open (ovf, m, _, _) ->
+ line i ppf "Texp_open %a \"%a\"\n" fmt_override_flag ovf fmt_path m;
+ attributes i ppf attrs;
+ | Texp_poly cto ->
+ line i ppf "Texp_poly\n";
+ attributes i ppf attrs;
+ option i core_type ppf cto;
+ | Texp_newtype s ->
+ line i ppf "Texp_newtype \"%s\"\n" s;
+ attributes i ppf attrs;
+
+and expression i ppf x =
+ line i ppf "expression %a\n" fmt_location x.exp_loc;
+ attributes i ppf x.exp_attributes;
+ let i =
+ List.fold_left (fun i (extra,_,attrs) ->
+ expression_extra i ppf extra attrs; i+1)
+ (i+1) x.exp_extra
+ in
+ match x.exp_desc with
+ | Texp_ident (li,_,_) -> line i ppf "Texp_ident %a\n" fmt_path li;
+ | Texp_instvar (_, li,_) -> line i ppf "Texp_instvar %a\n" fmt_path li;
+ | Texp_constant (c) -> line i ppf "Texp_constant %a\n" fmt_constant c;
+ | Texp_let (rf, l, e) ->
+ line i ppf "Texp_let %a\n" fmt_rec_flag rf;
+ list i value_binding ppf l;
+ expression i ppf e;
+ | Texp_function (p, l, _partial) ->
+ line i ppf "Texp_function\n";
+ arg_label i ppf p;
+ list i case ppf l;
+ | Texp_apply (e, l) ->
+ line i ppf "Texp_apply\n";
+ expression i ppf e;
+ list i label_x_expression ppf l;
+ | Texp_match (e, l1, l2, partial) ->
+ line i ppf "Texp_match\n";
+ expression i ppf e;
+ list i case ppf l1;
+ list i case ppf l2;
+ | Texp_try (e, l) ->
+ line i ppf "Texp_try\n";
+ expression i ppf e;
+ list i case ppf l;
+ | Texp_tuple (l) ->
+ line i ppf "Texp_tuple\n";
+ list i expression ppf l;
+ | Texp_construct (li, _, eo) ->
+ line i ppf "Texp_construct %a\n" fmt_longident li;
+ list i expression ppf eo;
+ | Texp_variant (l, eo) ->
+ line i ppf "Texp_variant \"%s\"\n" l;
+ option i expression ppf eo;
+ | Texp_record (l, eo) ->
+ line i ppf "Texp_record\n";
+ list i longident_x_expression ppf l;
+ option i expression ppf eo;
+ | Texp_field (e, li, _) ->
+ line i ppf "Texp_field\n";
+ expression i ppf e;
+ longident i ppf li;
+ | Texp_setfield (e1, li, _, e2) ->
+ line i ppf "Texp_setfield\n";
+ expression i ppf e1;
+ longident i ppf li;
+ expression i ppf e2;
+ | Texp_array (l) ->
+ line i ppf "Texp_array\n";
+ list i expression ppf l;
+ | Texp_ifthenelse (e1, e2, eo) ->
+ line i ppf "Texp_ifthenelse\n";
+ expression i ppf e1;
+ expression i ppf e2;
+ option i expression ppf eo;
+ | Texp_sequence (e1, e2) ->
+ line i ppf "Texp_sequence\n";
+ expression i ppf e1;
+ expression i ppf e2;
+ | Texp_while (e1, e2) ->
+ line i ppf "Texp_while\n";
+ expression i ppf e1;
+ expression i ppf e2;
+ | Texp_for (s, _, e1, e2, df, e3) ->
+ line i ppf "Texp_for \"%a\" %a\n" fmt_ident s fmt_direction_flag df;
+ expression i ppf e1;
+ expression i ppf e2;
+ expression i ppf e3;
+ | Texp_send (e, Tmeth_name s, eo) ->
+ line i ppf "Texp_send \"%s\"\n" s;
+ expression i ppf e;
+ option i expression ppf eo
+ | Texp_send (e, Tmeth_val s, eo) ->
+ line i ppf "Texp_send \"%a\"\n" fmt_ident s;
+ expression i ppf e;
+ option i expression ppf eo
+ | Texp_new (li, _, _) -> line i ppf "Texp_new %a\n" fmt_path li;
+ | Texp_setinstvar (_, s, _, e) ->
+ line i ppf "Texp_setinstvar \"%a\"\n" fmt_path s;
+ expression i ppf e;
+ | Texp_override (_, l) ->
+ line i ppf "Texp_override\n";
+ list i string_x_expression ppf l;
+ | Texp_letmodule (s, _, me, e) ->
+ line i ppf "Texp_letmodule \"%a\"\n" fmt_ident s;
+ module_expr i ppf me;
+ expression i ppf e;
+ | Texp_assert (e) ->
+ line i ppf "Texp_assert";
+ expression i ppf e;
+ | Texp_lazy (e) ->
+ line i ppf "Texp_lazy";
+ expression i ppf e;
+ | Texp_object (s, _) ->
+ line i ppf "Texp_object";
+ class_structure i ppf s
+ | Texp_pack me ->
+ line i ppf "Texp_pack";
+ module_expr i ppf me
+
+and value_description i ppf x =
+ line i ppf "value_description %a %a\n" fmt_ident x.val_id fmt_location
+ x.val_loc;
+ attributes i ppf x.val_attributes;
+ core_type (i+1) ppf x.val_desc;
+ list (i+1) string ppf x.val_prim;
+
+and type_parameter i ppf (x, _variance) = core_type i ppf x
+
+and type_declaration i ppf x =
+ line i ppf "type_declaration %a %a\n" fmt_ident x.typ_id fmt_location
+ x.typ_loc;
+ attributes i ppf x.typ_attributes;
+ let i = i+1 in
+ line i ppf "ptype_params =\n";
+ list (i+1) type_parameter ppf x.typ_params;
+ line i ppf "ptype_cstrs =\n";
+ list (i+1) core_type_x_core_type_x_location ppf x.typ_cstrs;
+ line i ppf "ptype_kind =\n";
+ type_kind (i+1) ppf x.typ_kind;
+ line i ppf "ptype_private = %a\n" fmt_private_flag x.typ_private;
+ line i ppf "ptype_manifest =\n";
+ option (i+1) core_type ppf x.typ_manifest;
+
+and type_kind i ppf x =
+ match x with
+ | Ttype_abstract ->
+ line i ppf "Ttype_abstract\n"
+ | Ttype_variant l ->
+ line i ppf "Ttype_variant\n";
+ list (i+1) constructor_decl ppf l;
+ | Ttype_record l ->
+ line i ppf "Ttype_record\n";
+ list (i+1) label_decl ppf l;
+ | Ttype_open ->
+ line i ppf "Ttype_open\n"
+
+and type_extension i ppf x =
+ line i ppf "type_extension\n";
+ attributes i ppf x.tyext_attributes;
+ let i = i+1 in
+ line i ppf "ptyext_path = %a\n" fmt_path x.tyext_path;
+ line i ppf "ptyext_params =\n";
+ list (i+1) type_parameter ppf x.tyext_params;
+ line i ppf "ptyext_constructors =\n";
+ list (i+1) extension_constructor ppf x.tyext_constructors;
+ line i ppf "ptyext_private = %a\n" fmt_private_flag x.tyext_private;
+
+and extension_constructor i ppf x =
+ line i ppf "extension_constructor %a\n" fmt_location x.ext_loc;
+ attributes i ppf x.ext_attributes;
+ let i = i + 1 in
+ line i ppf "pext_name = \"%a\"\n" fmt_ident x.ext_id;
+ line i ppf "pext_kind =\n";
+ extension_constructor_kind (i + 1) ppf x.ext_kind;
+
+and extension_constructor_kind i ppf x =
+ match x with
+ Text_decl(a, r) ->
+ line i ppf "Text_decl\n";
+ constructor_arguments (i+1) ppf a;
+ option (i+1) core_type ppf r;
+ | Text_rebind(p, _) ->
+ line i ppf "Text_rebind\n";
+ line (i+1) ppf "%a\n" fmt_path p;
+
+and class_type i ppf x =
+ line i ppf "class_type %a\n" fmt_location x.cltyp_loc;
+ attributes i ppf x.cltyp_attributes;
+ let i = i+1 in
+ match x.cltyp_desc with
+ | Tcty_constr (li, _, l) ->
+ line i ppf "Tcty_constr %a\n" fmt_path li;
+ list i core_type ppf l;
+ | Tcty_signature (cs) ->
+ line i ppf "Tcty_signature\n";
+ class_signature i ppf cs;
+ | Tcty_arrow (l, co, cl) ->
+ line i ppf "Tcty_arrow\n";
+ arg_label i ppf l;
+ core_type i ppf co;
+ class_type i ppf cl;
+
+and class_signature i ppf { csig_self = ct; csig_fields = l } =
+ line i ppf "class_signature\n";
+ core_type (i+1) ppf ct;
+ list (i+1) class_type_field ppf l;
+
+and class_type_field i ppf x =
+ line i ppf "class_type_field %a\n" fmt_location x.ctf_loc;
+ let i = i+1 in
+ attributes i ppf x.ctf_attributes;
+ match x.ctf_desc with
+ | Tctf_inherit (ct) ->
+ line i ppf "Tctf_inherit\n";
+ class_type i ppf ct;
+ | Tctf_val (s, mf, vf, ct) ->
+ line i ppf "Tctf_val \"%s\" %a %a\n" s fmt_mutable_flag mf
+ fmt_virtual_flag vf;
+ core_type (i+1) ppf ct;
+ | Tctf_method (s, pf, vf, ct) ->
+ line i ppf "Tctf_method \"%s\" %a %a\n" s fmt_private_flag pf
+ fmt_virtual_flag vf;
+ core_type (i+1) ppf ct;
+ | Tctf_constraint (ct1, ct2) ->
+ line i ppf "Tctf_constraint\n";
+ core_type (i+1) ppf ct1;
+ core_type (i+1) ppf ct2;
+ | Tctf_attribute (s, arg) ->
+ line i ppf "Tctf_attribute \"%s\"\n" s.txt;
+ Printast.payload i ppf arg
+
+and class_description i ppf x =
+ line i ppf "class_description %a\n" fmt_location x.ci_loc;
+ attributes i ppf x.ci_attributes;
+ let i = i+1 in
+ line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt;
+ line i ppf "pci_params =\n";
+ list (i+1) type_parameter ppf x.ci_params;
+ line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt;
+ line i ppf "pci_expr =\n";
+ class_type (i+1) ppf x.ci_expr;
+
+and class_type_declaration i ppf x =
+ line i ppf "class_type_declaration %a\n" fmt_location x.ci_loc;
+ let i = i+1 in
+ line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt;
+ line i ppf "pci_params =\n";
+ list (i+1) type_parameter ppf x.ci_params;
+ line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt;
+ line i ppf "pci_expr =\n";
+ class_type (i+1) ppf x.ci_expr;
+
+and class_expr i ppf x =
+ line i ppf "class_expr %a\n" fmt_location x.cl_loc;
+ attributes i ppf x.cl_attributes;
+ let i = i+1 in
+ match x.cl_desc with
+ | Tcl_ident (li, _, l) ->
+ line i ppf "Tcl_ident %a\n" fmt_path li;
+ list i core_type ppf l;
+ | Tcl_structure (cs) ->
+ line i ppf "Tcl_structure\n";
+ class_structure i ppf cs;
+ | Tcl_fun (l, p, _, ce, _) ->
+ line i ppf "Tcl_fun\n";
+ arg_label i ppf l;
+ pattern i ppf p;
+ class_expr i ppf ce
+ | Tcl_apply (ce, l) ->
+ line i ppf "Tcl_apply\n";
+ class_expr i ppf ce;
+ list i label_x_expression ppf l;
+ | Tcl_let (rf, l1, l2, ce) ->
+ line i ppf "Tcl_let %a\n" fmt_rec_flag rf;
+ list i value_binding ppf l1;
+ list i ident_x_loc_x_expression_def ppf l2;
+ class_expr i ppf ce;
+ | Tcl_constraint (ce, Some ct, _, _, _) ->
+ line i ppf "Tcl_constraint\n";
+ class_expr i ppf ce;
+ class_type i ppf ct
+ | Tcl_constraint (ce, None, _, _, _) -> class_expr i ppf ce
+
+and class_structure i ppf { cstr_self = p; cstr_fields = l } =
+ line i ppf "class_structure\n";
+ pattern (i+1) ppf p;
+ list (i+1) class_field ppf l;
+
+and class_field i ppf x =
+ line i ppf "class_field %a\n" fmt_location x.cf_loc;
+ let i = i + 1 in
+ attributes i ppf x.cf_attributes;
+ match x.cf_desc with
+ | Tcf_inherit (ovf, ce, so, _, _) ->
+ line i ppf "Tcf_inherit %a\n" fmt_override_flag ovf;
+ class_expr (i+1) ppf ce;
+ option (i+1) string ppf so;
+ | Tcf_val (s, mf, _, k, _) ->
+ line i ppf "Tcf_val \"%s\" %a\n" s.txt fmt_mutable_flag mf;
+ class_field_kind (i+1) ppf k
+ | Tcf_method (s, pf, k) ->
+ line i ppf "Tcf_method \"%s\" %a\n" s.txt fmt_private_flag pf;
+ class_field_kind (i+1) ppf k
+ | Tcf_constraint (ct1, ct2) ->
+ line i ppf "Tcf_constraint\n";
+ core_type (i+1) ppf ct1;
+ core_type (i+1) ppf ct2;
+ | Tcf_initializer (e) ->
+ line i ppf "Tcf_initializer\n";
+ expression (i+1) ppf e;
+ | Tcf_attribute (s, arg) ->
+ line i ppf "Tcf_attribute \"%s\"\n" s.txt;
+ Printast.payload i ppf arg
+
+and class_field_kind i ppf = function
+ | Tcfk_concrete (o, e) ->
+ line i ppf "Concrete %a\n" fmt_override_flag o;
+ expression i ppf e
+ | Tcfk_virtual t ->
+ line i ppf "Virtual\n";
+ core_type i ppf t
+
+and class_declaration i ppf x =
+ line i ppf "class_declaration %a\n" fmt_location x.ci_loc;
+ let i = i+1 in
+ line i ppf "pci_virt = %a\n" fmt_virtual_flag x.ci_virt;
+ line i ppf "pci_params =\n";
+ list (i+1) type_parameter ppf x.ci_params;
+ line i ppf "pci_name = \"%s\"\n" x.ci_id_name.txt;
+ line i ppf "pci_expr =\n";
+ class_expr (i+1) ppf x.ci_expr;
+
+and module_type i ppf x =
+ line i ppf "module_type %a\n" fmt_location x.mty_loc;
+ attributes i ppf x.mty_attributes;
+ let i = i+1 in
+ match x.mty_desc with
+ | Tmty_ident (li,_) -> line i ppf "Tmty_ident %a\n" fmt_path li;
+ | Tmty_alias (li,_) -> line i ppf "Tmty_alias %a\n" fmt_path li;
+ | Tmty_signature (s) ->
+ line i ppf "Tmty_signature\n";
+ signature i ppf s;
+ | Tmty_functor (s, _, mt1, mt2) ->
+ line i ppf "Tmty_functor \"%a\"\n" fmt_ident s;
+ Misc.may (module_type i ppf) mt1;
+ module_type i ppf mt2;
+ | Tmty_with (mt, l) ->
+ line i ppf "Tmty_with\n";
+ module_type i ppf mt;
+ list i longident_x_with_constraint ppf l;
+ | Tmty_typeof m ->
+ line i ppf "Tmty_typeof\n";
+ module_expr i ppf m;
+
+and signature i ppf x = list i signature_item ppf x.sig_items
+
+and signature_item i ppf x =
+ line i ppf "signature_item %a\n" fmt_location x.sig_loc;
+ let i = i+1 in
+ match x.sig_desc with
+ | Tsig_value vd ->
+ line i ppf "Tsig_value\n";
+ value_description i ppf vd;
+ | Tsig_type (rf, l) ->
+ line i ppf "Tsig_type %a\n" fmt_rec_flag rf;
+ list i type_declaration ppf l;
+ | Tsig_typext e ->
+ line i ppf "Tsig_typext\n";
+ type_extension i ppf e;
+ | Tsig_exception ext ->
+ line i ppf "Tsig_exception\n";
+ extension_constructor i ppf ext
+ | Tsig_module md ->
+ line i ppf "Tsig_module \"%a\"\n" fmt_ident md.md_id;
+ attributes i ppf md.md_attributes;
+ module_type i ppf md.md_type
+ | Tsig_recmodule decls ->
+ line i ppf "Tsig_recmodule\n";
+ list i module_declaration ppf decls;
+ | Tsig_modtype x ->
+ line i ppf "Tsig_modtype \"%a\"\n" fmt_ident x.mtd_id;
+ attributes i ppf x.mtd_attributes;
+ modtype_declaration i ppf x.mtd_type
+ | Tsig_open od ->
+ line i ppf "Tsig_open %a %a\n"
+ fmt_override_flag od.open_override
+ fmt_path od.open_path;
+ attributes i ppf od.open_attributes
+ | Tsig_include incl ->
+ line i ppf "Tsig_include\n";
+ attributes i ppf incl.incl_attributes;
+ module_type i ppf incl.incl_mod
+ | Tsig_class (l) ->
+ line i ppf "Tsig_class\n";
+ list i class_description ppf l;
+ | Tsig_class_type (l) ->
+ line i ppf "Tsig_class_type\n";
+ list i class_type_declaration ppf l;
+ | Tsig_attribute (s, arg) ->
+ line i ppf "Tsig_attribute \"%s\"\n" s.txt;
+ Printast.payload i ppf arg
+
+and module_declaration i ppf md =
+ line i ppf "%a" fmt_ident md.md_id;
+ attributes i ppf md.md_attributes;
+ module_type (i+1) ppf md.md_type;
+
+and module_binding i ppf x =
+ line i ppf "%a\n" fmt_ident x.mb_id;
+ attributes i ppf x.mb_attributes;
+ module_expr (i+1) ppf x.mb_expr
+
+and modtype_declaration i ppf = function
+ | None -> line i ppf "#abstract"
+ | Some mt -> module_type (i + 1) ppf mt
+
+and with_constraint i ppf x =
+ match x with
+ | Twith_type (td) ->
+ line i ppf "Twith_type\n";
+ type_declaration (i+1) ppf td;
+ | Twith_typesubst (td) ->
+ line i ppf "Twith_typesubst\n";
+ type_declaration (i+1) ppf td;
+ | Twith_module (li,_) -> line i ppf "Twith_module %a\n" fmt_path li;
+ | Twith_modsubst (li,_) -> line i ppf "Twith_modsubst %a\n" fmt_path li;
+
+and module_expr i ppf x =
+ line i ppf "module_expr %a\n" fmt_location x.mod_loc;
+ attributes i ppf x.mod_attributes;
+ let i = i+1 in
+ match x.mod_desc with
+ | Tmod_ident (li,_) -> line i ppf "Tmod_ident %a\n" fmt_path li;
+ | Tmod_structure (s) ->
+ line i ppf "Tmod_structure\n";
+ structure i ppf s;
+ | Tmod_functor (s, _, mt, me) ->
+ line i ppf "Tmod_functor \"%a\"\n" fmt_ident s;
+ Misc.may (module_type i ppf) mt;
+ module_expr i ppf me;
+ | Tmod_apply (me1, me2, _) ->
+ line i ppf "Tmod_apply\n";
+ module_expr i ppf me1;
+ module_expr i ppf me2;
+ | Tmod_constraint (me, _, Tmodtype_explicit mt, _) ->
+ line i ppf "Tmod_constraint\n";
+ module_expr i ppf me;
+ module_type i ppf mt;
+ | Tmod_constraint (me, _, Tmodtype_implicit, _) -> module_expr i ppf me
+ | Tmod_unpack (e, _) ->
+ line i ppf "Tmod_unpack\n";
+ expression i ppf e;
+
+and structure i ppf x = list i structure_item ppf x.str_items
+
+and structure_item i ppf x =
+ line i ppf "structure_item %a\n" fmt_location x.str_loc;
+ let i = i+1 in
+ match x.str_desc with
+ | Tstr_eval (e, attrs) ->
+ line i ppf "Tstr_eval\n";
+ attributes i ppf attrs;
+ expression i ppf e;
+ | Tstr_value (rf, l) ->
+ line i ppf "Tstr_value %a\n" fmt_rec_flag rf;
+ list i value_binding ppf l;
+ | Tstr_primitive vd ->
+ line i ppf "Tstr_primitive\n";
+ value_description i ppf vd;
+ | Tstr_type (rf, l) ->
+ line i ppf "Tstr_type %a\n" fmt_rec_flag rf;
+ list i type_declaration ppf l;
+ | Tstr_typext te ->
+ line i ppf "Tstr_typext\n";
+ type_extension i ppf te
+ | Tstr_exception ext ->
+ line i ppf "Tstr_exception\n";
+ extension_constructor i ppf ext;
+ | Tstr_module x ->
+ line i ppf "Tstr_module\n";
+ module_binding i ppf x
+ | Tstr_recmodule bindings ->
+ line i ppf "Tstr_recmodule\n";
+ list i module_binding ppf bindings
+ | Tstr_modtype x ->
+ line i ppf "Tstr_modtype \"%a\"\n" fmt_ident x.mtd_id;
+ attributes i ppf x.mtd_attributes;
+ modtype_declaration i ppf x.mtd_type
+ | Tstr_open od ->
+ line i ppf "Tstr_open %a %a\n"
+ fmt_override_flag od.open_override
+ fmt_path od.open_path;
+ attributes i ppf od.open_attributes
+ | Tstr_class (l) ->
+ line i ppf "Tstr_class\n";
+ list i class_declaration ppf (List.map (fun (cl, _) -> cl) l);
+ | Tstr_class_type (l) ->
+ line i ppf "Tstr_class_type\n";
+ list i class_type_declaration ppf (List.map (fun (_, _, cl) -> cl) l);
+ | Tstr_include incl ->
+ line i ppf "Tstr_include";
+ attributes i ppf incl.incl_attributes;
+ module_expr i ppf incl.incl_mod;
+ | Tstr_attribute (s, arg) ->
+ line i ppf "Tstr_attribute \"%s\"\n" s.txt;
+ Printast.payload i ppf arg
+
+and string_x_module_type i ppf (s, _, mty) =
+ ident i ppf s;
+ module_type (i+1) ppf mty;
+
+and string_x_modtype_x_module i ppf (s, _, mty, modl) =
+ ident i ppf s;
+ module_type (i+1) ppf mty;
+ module_expr (i+1) ppf modl;
+
+and longident_x_with_constraint i ppf (li, _, wc) =
+ line i ppf "%a\n" fmt_path li;
+ with_constraint (i+1) ppf wc;
+
+and core_type_x_core_type_x_location i ppf (ct1, ct2, l) =
+ line i ppf "<constraint> %a\n" fmt_location l;
+ core_type (i+1) ppf ct1;
+ core_type (i+1) ppf ct2;
+
+and constructor_decl i ppf {cd_id; cd_name = _; cd_args; cd_res; cd_loc;
+ cd_attributes} =
+ line i ppf "%a\n" fmt_location cd_loc;
+ line (i+1) ppf "%a\n" fmt_ident cd_id;
+ attributes i ppf cd_attributes;
+ constructor_arguments (i+1) ppf cd_args;
+ option (i+1) core_type ppf cd_res
+
+and constructor_arguments i ppf = function
+ | Cstr_tuple l -> list i core_type ppf l
+ | Cstr_record l -> list i label_decl ppf l
+
+and label_decl i ppf {ld_id; ld_name = _; ld_mutable; ld_type; ld_loc;
+ ld_attributes} =
+ line i ppf "%a\n" fmt_location ld_loc;
+ attributes i ppf ld_attributes;
+ line (i+1) ppf "%a\n" fmt_mutable_flag ld_mutable;
+ line (i+1) ppf "%a" fmt_ident ld_id;
+ core_type (i+1) ppf ld_type
+
+and longident_x_pattern i ppf (li, _, p) =
+ line i ppf "%a\n" fmt_longident li;
+ pattern (i+1) ppf p;
+
+and case i ppf {c_lhs; c_guard; c_rhs} =
+ line i ppf "<case>\n";
+ pattern (i+1) ppf c_lhs;
+ begin match c_guard with
+ | None -> ()
+ | Some g -> line (i+1) ppf "<when>\n"; expression (i + 2) ppf g
+ end;
+ expression (i+1) ppf c_rhs;
+
+and value_binding i ppf x =
+ line i ppf "<def>\n";
+ attributes (i+1) ppf x.vb_attributes;
+ pattern (i+1) ppf x.vb_pat;
+ expression (i+1) ppf x.vb_expr
+
+and string_x_expression i ppf (s, _, e) =
+ line i ppf "<override> \"%a\"\n" fmt_path s;
+ expression (i+1) ppf e;
+
+and longident_x_expression i ppf (li, _, e) =
+ line i ppf "%a\n" fmt_longident li;
+ expression (i+1) ppf e;
+
+and label_x_expression i ppf (l, e, _) =
+ line i ppf "<arg>\n";
+ arg_label (i+1) ppf l;
+ (match e with None -> () | Some e -> expression (i+1) ppf e)
+
+and ident_x_loc_x_expression_def i ppf (l,_, e) =
+ line i ppf "<def> \"%a\"\n" fmt_ident l;
+ expression (i+1) ppf e;
+
+and label_x_bool_x_core_type_list i ppf x =
+ match x with
+ Ttag (l, attrs, b, ctl) ->
+ line i ppf "Rtag \"%s\" %s\n" l (string_of_bool b);
+ attributes (i+1) ppf attrs;
+ list (i+1) core_type ppf ctl
+ | Tinherit (ct) ->
+ line i ppf "Rinherit\n";
+ core_type (i+1) ppf ct
+;;
+
+let interface ppf x = list 0 signature_item ppf x.sig_items;;
+
+let implementation ppf x = list 0 structure_item ppf x.str_items;;
+
+let implementation_with_coercion ppf (x, _) = implementation ppf x
diff --git a/typing/printtyped.mli b/typing/printtyped.mli
new file mode 100644
index 0000000000..b2f1e3f7d7
--- /dev/null
+++ b/typing/printtyped.mli
@@ -0,0 +1,20 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Para, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1999 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Typedtree;;
+open Format;;
+
+val interface : formatter -> signature -> unit;;
+val implementation : formatter -> structure -> unit;;
+
+val implementation_with_coercion :
+ formatter -> (structure * module_coercion) -> unit;;
diff --git a/typing/stypes.ml b/typing/stypes.ml
new file mode 100644
index 0000000000..1f89e7443b
--- /dev/null
+++ b/typing/stypes.ml
@@ -0,0 +1,209 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2003 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Recording and dumping (partial) type information *)
+
+(*
+ We record all types in a list as they are created.
+ This means we can dump type information even if type inference fails,
+ which is extremely important, since type information is most
+ interesting in case of errors.
+*)
+
+open Annot;;
+open Lexing;;
+open Location;;
+open Typedtree;;
+
+let output_int oc i = output_string oc (string_of_int i)
+
+type annotation =
+ | Ti_pat of pattern
+ | Ti_expr of expression
+ | Ti_class of class_expr
+ | Ti_mod of module_expr
+ | An_call of Location.t * Annot.call
+ | An_ident of Location.t * string * Annot.ident
+;;
+
+let get_location ti =
+ match ti with
+ Ti_pat p -> p.pat_loc
+ | Ti_expr e -> e.exp_loc
+ | Ti_class c -> c.cl_loc
+ | Ti_mod m -> m.mod_loc
+ | An_call (l, k) -> l
+ | An_ident (l, s, k) -> l
+;;
+
+let annotations = ref ([] : annotation list);;
+let phrases = ref ([] : Location.t list);;
+
+let record ti =
+ if !Clflags.annotations && not (get_location ti).Location.loc_ghost then
+ annotations := ti :: !annotations
+;;
+
+let record_phrase loc =
+ if !Clflags.annotations then phrases := loc :: !phrases;
+;;
+
+(* comparison order:
+ the intervals are sorted by order of increasing upper bound
+ same upper bound -> sorted by decreasing lower bound
+*)
+let cmp_loc_inner_first loc1 loc2 =
+ match compare loc1.loc_end.pos_cnum loc2.loc_end.pos_cnum with
+ | 0 -> compare loc2.loc_start.pos_cnum loc1.loc_start.pos_cnum
+ | x -> x
+;;
+let cmp_ti_inner_first ti1 ti2 =
+ cmp_loc_inner_first (get_location ti1) (get_location ti2)
+;;
+
+let print_position pp pos =
+ if pos = dummy_pos then
+ output_string pp "--"
+ else begin
+ output_char pp '\"';
+ output_string pp (String.escaped pos.pos_fname);
+ output_string pp "\" ";
+ output_int pp pos.pos_lnum;
+ output_char pp ' ';
+ output_int pp pos.pos_bol;
+ output_char pp ' ';
+ output_int pp pos.pos_cnum;
+ end
+;;
+
+let print_location pp loc =
+ print_position pp loc.loc_start;
+ output_char pp ' ';
+ print_position pp loc.loc_end;
+;;
+
+let sort_filter_phrases () =
+ let ph = List.sort (fun x y -> cmp_loc_inner_first y x) !phrases in
+ let rec loop accu cur l =
+ match l with
+ | [] -> accu
+ | loc :: t ->
+ if cur.loc_start.pos_cnum <= loc.loc_start.pos_cnum
+ && cur.loc_end.pos_cnum >= loc.loc_end.pos_cnum
+ then loop accu cur t
+ else loop (loc :: accu) loc t
+ in
+ phrases := loop [] Location.none ph;
+;;
+
+let rec printtyp_reset_maybe loc =
+ match !phrases with
+ | cur :: t when cur.loc_start.pos_cnum <= loc.loc_start.pos_cnum ->
+ Printtyp.reset ();
+ phrases := t;
+ printtyp_reset_maybe loc;
+ | _ -> ()
+;;
+
+let call_kind_string k =
+ match k with
+ | Tail -> "tail"
+ | Stack -> "stack"
+ | Inline -> "inline"
+;;
+
+let print_ident_annot pp str k =
+ match k with
+ | Idef l ->
+ output_string pp "def ";
+ output_string pp str;
+ output_char pp ' ';
+ print_location pp l;
+ output_char pp '\n'
+ | Iref_internal l ->
+ output_string pp "int_ref ";
+ output_string pp str;
+ output_char pp ' ';
+ print_location pp l;
+ output_char pp '\n'
+ | Iref_external ->
+ output_string pp "ext_ref ";
+ output_string pp str;
+ output_char pp '\n'
+;;
+
+(* The format of the annotation file is documented in emacs/caml-types.el. *)
+
+let print_info pp prev_loc ti =
+ match ti with
+ | Ti_class _ | Ti_mod _ -> prev_loc
+ | Ti_pat {pat_loc = loc; pat_type = typ; pat_env = env}
+ | Ti_expr {exp_loc = loc; exp_type = typ; exp_env = env} ->
+ if loc <> prev_loc then begin
+ print_location pp loc;
+ output_char pp '\n'
+ end;
+ output_string pp "type(\n";
+ printtyp_reset_maybe loc;
+ Printtyp.mark_loops typ;
+ Format.pp_print_string Format.str_formatter " ";
+ Printtyp.wrap_printing_env env
+ (fun () -> Printtyp.type_sch Format.str_formatter typ);
+ Format.pp_print_newline Format.str_formatter ();
+ let s = Format.flush_str_formatter () in
+ output_string pp s;
+ output_string pp ")\n";
+ loc
+ | An_call (loc, k) ->
+ if loc <> prev_loc then begin
+ print_location pp loc;
+ output_char pp '\n'
+ end;
+ output_string pp "call(\n ";
+ output_string pp (call_kind_string k);
+ output_string pp "\n)\n";
+ loc
+ | An_ident (loc, str, k) ->
+ if loc <> prev_loc then begin
+ print_location pp loc;
+ output_char pp '\n'
+ end;
+ output_string pp "ident(\n ";
+ print_ident_annot pp str k;
+ output_string pp ")\n";
+ loc
+;;
+
+let get_info () =
+ let info = List.fast_sort cmp_ti_inner_first !annotations in
+ annotations := [];
+ info
+;;
+
+let dump filename =
+ if !Clflags.annotations then begin
+ let info = get_info () in
+ let pp =
+ match filename with
+ None -> stdout
+ | Some filename -> open_out filename in
+ sort_filter_phrases ();
+ ignore (List.fold_left (print_info pp) Location.none info);
+ begin match filename with
+ | None -> ()
+ | Some _ -> close_out pp
+ end;
+ phrases := [];
+ end else begin
+ annotations := [];
+ end;
+;;
diff --git a/typing/stypes.mli b/typing/stypes.mli
new file mode 100644
index 0000000000..02a467f576
--- /dev/null
+++ b/typing/stypes.mli
@@ -0,0 +1,33 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Damien Doligez, projet Moscova, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2003 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Recording and dumping (partial) type information *)
+
+(* Clflags.save_types must be true *)
+
+open Typedtree;;
+
+type annotation =
+ | Ti_pat of pattern
+ | Ti_expr of expression
+ | Ti_class of class_expr
+ | Ti_mod of module_expr
+ | An_call of Location.t * Annot.call
+ | An_ident of Location.t * string * Annot.ident
+;;
+
+val record : annotation -> unit;;
+val record_phrase : Location.t -> unit;;
+val dump : string option -> unit;;
+
+val get_location : annotation -> Location.t;;
+val get_info : unit -> annotation list;;
diff --git a/typing/subst.ml b/typing/subst.ml
new file mode 100644
index 0000000000..01780ed2ae
--- /dev/null
+++ b/typing/subst.ml
@@ -0,0 +1,426 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Substitutions *)
+
+open Misc
+open Path
+open Types
+open Btype
+
+type t =
+ { types: (Ident.t, Path.t) Tbl.t;
+ modules: (Ident.t, Path.t) Tbl.t;
+ modtypes: (Ident.t, module_type) Tbl.t;
+ for_saving: bool }
+
+let identity =
+ { types = Tbl.empty; modules = Tbl.empty; modtypes = Tbl.empty;
+ for_saving = false }
+
+let add_type id p s = { s with types = Tbl.add id p s.types }
+
+let add_module id p s = { s with modules = Tbl.add id p s.modules }
+
+let add_modtype id ty s = { s with modtypes = Tbl.add id ty s.modtypes }
+
+let for_saving s = { s with for_saving = true }
+
+let loc s x =
+ if s.for_saving && not !Clflags.keep_locs then Location.none else x
+
+let remove_loc =
+ let open Ast_mapper in
+ {default_mapper with location = (fun _this _loc -> Location.none)}
+
+let is_not_doc = function
+ | ({Location.txt = "ocaml.doc"}, _) -> false
+ | ({Location.txt = "ocaml.text"}, _) -> false
+ | ({Location.txt = "doc"}, _) -> false
+ | ({Location.txt = "text"}, _) -> false
+ | _ -> true
+
+let attrs s x =
+ let x =
+ if s.for_saving && not !Clflags.keep_docs then
+ List.filter is_not_doc x
+ else x
+ in
+ if s.for_saving && not !Clflags.keep_locs
+ then remove_loc.Ast_mapper.attributes remove_loc x
+ else x
+
+let rec module_path s = function
+ Pident id as p ->
+ begin try Tbl.find id s.modules with Not_found -> p end
+ | Pdot(p, n, pos) ->
+ Pdot(module_path s p, n, pos)
+ | Papply(p1, p2) ->
+ Papply(module_path s p1, module_path s p2)
+
+let modtype_path s = function
+ Pident id as p ->
+ begin try
+ match Tbl.find id s.modtypes with
+ | Mty_ident p -> p
+ | _ -> fatal_error "Subst.modtype_path"
+ with Not_found -> p end
+ | Pdot(p, n, pos) ->
+ Pdot(module_path s p, n, pos)
+ | Papply(p1, p2) ->
+ fatal_error "Subst.modtype_path"
+
+let type_path s = function
+ Pident id as p ->
+ begin try Tbl.find id s.types with Not_found -> p end
+ | Pdot(p, n, pos) ->
+ Pdot(module_path s p, n, pos)
+ | Papply(p1, p2) ->
+ fatal_error "Subst.type_path"
+
+let type_path s p =
+ match Path.constructor_typath p with
+ | Regular p -> type_path s p
+ | Cstr (ty_path, cstr) -> Pdot(type_path s ty_path, cstr, nopos)
+ | LocalExt _ -> type_path s p
+ | Ext (p, cstr) -> Pdot(module_path s p, cstr, nopos)
+
+(* Special type ids for saved signatures *)
+
+let new_id = ref (-1)
+let reset_for_saving () = new_id := -1
+
+let newpersty desc =
+ decr new_id;
+ { desc = desc; level = generic_level; id = !new_id }
+
+(* ensure that all occurrences of 'Tvar None' are physically shared *)
+let tvar_none = Tvar None
+let tunivar_none = Tunivar None
+let norm = function
+ | Tvar None -> tvar_none
+ | Tunivar None -> tunivar_none
+ | d -> d
+
+(* Similar to [Ctype.nondep_type_rec]. *)
+let rec typexp s ty =
+ let ty = repr ty in
+ match ty.desc with
+ Tvar _ | Tunivar _ as desc ->
+ if s.for_saving || ty.id < 0 then
+ let ty' =
+ if s.for_saving then newpersty (norm desc)
+ else newty2 ty.level desc
+ in
+ save_desc ty desc; ty.desc <- Tsubst ty'; ty'
+ else ty
+ | Tsubst ty ->
+ ty
+(* cannot do it, since it would omit subsitution
+ | Tvariant row when not (static_row row) ->
+ ty
+*)
+ | _ ->
+ let desc = ty.desc in
+ save_desc ty desc;
+ (* Make a stub *)
+ let ty' = if s.for_saving then newpersty (Tvar None) else newgenvar () in
+ ty.desc <- Tsubst ty';
+ ty'.desc <-
+ begin match desc with
+ | Tconstr(p, tl, abbrev) ->
+ Tconstr(type_path s p, List.map (typexp s) tl, ref Mnil)
+ | Tpackage(p, n, tl) ->
+ Tpackage(modtype_path s p, n, List.map (typexp s) tl)
+ | Tobject (t1, name) ->
+ Tobject (typexp s t1,
+ ref (match !name with
+ None -> None
+ | Some (p, tl) ->
+ Some (type_path s p, List.map (typexp s) tl)))
+ | Tfield (m, k, t1, t2)
+ when s == identity && ty.level < generic_level && m = dummy_method ->
+ (* not allowed to lower the level of the dummy method *)
+ Tfield (m, k, t1, typexp s t2)
+ | Tvariant row ->
+ let row = row_repr row in
+ let more = repr row.row_more in
+ (* We must substitute in a subtle way *)
+ (* Tsubst takes a tuple containing the row var and the variant *)
+ begin match more.desc with
+ Tsubst {desc = Ttuple [_;ty2]} ->
+ (* This variant type has been already copied *)
+ ty.desc <- Tsubst ty2; (* avoid Tlink in the new type *)
+ Tlink ty2
+ | _ ->
+ let dup =
+ s.for_saving || more.level = generic_level || static_row row ||
+ match more.desc with Tconstr _ -> true | _ -> false in
+ (* Various cases for the row variable *)
+ let more' =
+ match more.desc with
+ Tsubst ty -> ty
+ | Tconstr _ | Tnil -> typexp s more
+ | Tunivar _ | Tvar _ ->
+ save_desc more more.desc;
+ if s.for_saving then newpersty (norm more.desc) else
+ if dup && is_Tvar more then newgenty more.desc else more
+ | _ -> assert false
+ in
+ (* Register new type first for recursion *)
+ more.desc <- Tsubst(newgenty(Ttuple[more';ty']));
+ (* Return a new copy *)
+ let row =
+ copy_row (typexp s) true row (not dup) more' in
+ match row.row_name with
+ Some (p, tl) ->
+ Tvariant {row with row_name = Some (type_path s p, tl)}
+ | None ->
+ Tvariant row
+ end
+ | Tfield(label, kind, t1, t2) when field_kind_repr kind = Fabsent ->
+ Tlink (typexp s t2)
+ | _ -> copy_type_desc (typexp s) desc
+ end;
+ ty'
+
+(*
+ Always make a copy of the type. If this is not done, type levels
+ might not be correct.
+*)
+let type_expr s ty =
+ let ty' = typexp s ty in
+ cleanup_types ();
+ ty'
+
+let label_declaration s l =
+ {
+ ld_id = l.ld_id;
+ ld_mutable = l.ld_mutable;
+ ld_type = typexp s l.ld_type;
+ ld_loc = loc s l.ld_loc;
+ ld_attributes = attrs s l.ld_attributes;
+ }
+
+let constructor_arguments s = function
+ | Cstr_tuple l ->
+ Cstr_tuple (List.map (typexp s) l)
+ | Cstr_record l ->
+ Cstr_record (List.map (label_declaration s) l)
+
+let constructor_declaration s c =
+ {
+ cd_id = c.cd_id;
+ cd_args = constructor_arguments s c.cd_args;
+ cd_res = may_map (typexp s) c.cd_res;
+ cd_loc = loc s c.cd_loc;
+ cd_attributes = attrs s c.cd_attributes;
+ }
+
+let type_declaration s decl =
+ let decl =
+ { type_params = List.map (typexp s) decl.type_params;
+ type_arity = decl.type_arity;
+ type_kind =
+ begin match decl.type_kind with
+ Type_abstract -> Type_abstract
+ | Type_variant cstrs ->
+ Type_variant (List.map (constructor_declaration s) cstrs)
+ | Type_record(lbls, rep) ->
+ Type_record (List.map (label_declaration s) lbls, rep)
+ | Type_open -> Type_open
+ end;
+ type_manifest =
+ begin
+ match decl.type_manifest with
+ None -> None
+ | Some ty -> Some(typexp s ty)
+ end;
+ type_private = decl.type_private;
+ type_variance = decl.type_variance;
+ type_newtype_level = None;
+ type_loc = loc s decl.type_loc;
+ type_attributes = attrs s decl.type_attributes;
+ }
+ in
+ cleanup_types ();
+ decl
+
+let class_signature s sign =
+ { csig_self = typexp s sign.csig_self;
+ csig_vars =
+ Vars.map (function (m, v, t) -> (m, v, typexp s t)) sign.csig_vars;
+ csig_concr = sign.csig_concr;
+ csig_inher =
+ List.map (fun (p, tl) -> (type_path s p, List.map (typexp s) tl))
+ sign.csig_inher;
+ }
+
+let rec class_type s =
+ function
+ Cty_constr (p, tyl, cty) ->
+ Cty_constr (type_path s p, List.map (typexp s) tyl, class_type s cty)
+ | Cty_signature sign ->
+ Cty_signature (class_signature s sign)
+ | Cty_arrow (l, ty, cty) ->
+ Cty_arrow (l, typexp s ty, class_type s cty)
+
+let class_declaration s decl =
+ let decl =
+ { cty_params = List.map (typexp s) decl.cty_params;
+ cty_variance = decl.cty_variance;
+ cty_type = class_type s decl.cty_type;
+ cty_path = type_path s decl.cty_path;
+ cty_new =
+ begin match decl.cty_new with
+ None -> None
+ | Some ty -> Some (typexp s ty)
+ end;
+ cty_loc = loc s decl.cty_loc;
+ cty_attributes = attrs s decl.cty_attributes;
+ }
+ in
+ (* Do not clean up if saving: next is cltype_declaration *)
+ if not s.for_saving then cleanup_types ();
+ decl
+
+let cltype_declaration s decl =
+ let decl =
+ { clty_params = List.map (typexp s) decl.clty_params;
+ clty_variance = decl.clty_variance;
+ clty_type = class_type s decl.clty_type;
+ clty_path = type_path s decl.clty_path;
+ clty_loc = loc s decl.clty_loc;
+ clty_attributes = attrs s decl.clty_attributes;
+ }
+ in
+ (* Do clean up even if saving: type_declaration may be recursive *)
+ cleanup_types ();
+ decl
+
+let class_type s cty =
+ let cty = class_type s cty in
+ cleanup_types ();
+ cty
+
+let value_description s descr =
+ { val_type = type_expr s descr.val_type;
+ val_kind = descr.val_kind;
+ val_loc = loc s descr.val_loc;
+ val_attributes = attrs s descr.val_attributes;
+ }
+
+let extension_constructor s ext =
+ let ext =
+ { ext_type_path = type_path s ext.ext_type_path;
+ ext_type_params = List.map (typexp s) ext.ext_type_params;
+ ext_args = constructor_arguments s ext.ext_args;
+ ext_ret_type = may_map (typexp s) ext.ext_ret_type;
+ ext_private = ext.ext_private;
+ ext_attributes = attrs s ext.ext_attributes;
+ ext_loc = if s.for_saving then Location.none else ext.ext_loc; }
+ in
+ cleanup_types ();
+ ext
+
+let rec rename_bound_idents s idents = function
+ [] -> (List.rev idents, s)
+ | Sig_type(id, d, _) :: sg ->
+ let id' = Ident.rename id in
+ rename_bound_idents (add_type id (Pident id') s) (id' :: idents) sg
+ | Sig_module(id, mty, _) :: sg ->
+ let id' = Ident.rename id in
+ rename_bound_idents (add_module id (Pident id') s) (id' :: idents) sg
+ | Sig_modtype(id, d) :: sg ->
+ let id' = Ident.rename id in
+ rename_bound_idents (add_modtype id (Mty_ident(Pident id')) s)
+ (id' :: idents) sg
+ | (Sig_class(id, _, _) | Sig_class_type(id, _, _)) :: sg ->
+ (* cheat and pretend they are types cf. PR#6650 *)
+ let id' = Ident.rename id in
+ rename_bound_idents (add_type id (Pident id') s) (id' :: idents) sg
+ | (Sig_value(id, _) | Sig_typext(id, _, _)) :: sg ->
+ let id' = Ident.rename id in
+ rename_bound_idents s (id' :: idents) sg
+
+let rec modtype s = function
+ Mty_ident p as mty ->
+ begin match p with
+ Pident id ->
+ begin try Tbl.find id s.modtypes with Not_found -> mty end
+ | Pdot(p, n, pos) ->
+ Mty_ident(Pdot(module_path s p, n, pos))
+ | Papply(p1, p2) ->
+ fatal_error "Subst.modtype"
+ end
+ | Mty_signature sg ->
+ Mty_signature(signature s sg)
+ | Mty_functor(id, arg, res) ->
+ let id' = Ident.rename id in
+ Mty_functor(id', may_map (modtype s) arg,
+ modtype (add_module id (Pident id') s) res)
+ | Mty_alias p ->
+ Mty_alias(module_path s p)
+
+and signature s sg =
+ (* Components of signature may be mutually recursive (e.g. type declarations
+ or class and type declarations), so first build global renaming
+ substitution... *)
+ let (new_idents, s') = rename_bound_idents s [] sg in
+ (* ... then apply it to each signature component in turn *)
+ List.map2 (signature_component s') sg new_idents
+
+and signature_component s comp newid =
+ match comp with
+ Sig_value(id, d) ->
+ Sig_value(newid, value_description s d)
+ | Sig_type(id, d, rs) ->
+ Sig_type(newid, type_declaration s d, rs)
+ | Sig_typext(id, ext, es) ->
+ Sig_typext(newid, extension_constructor s ext, es)
+ | Sig_module(id, d, rs) ->
+ Sig_module(newid, module_declaration s d, rs)
+ | Sig_modtype(id, d) ->
+ Sig_modtype(newid, modtype_declaration s d)
+ | Sig_class(id, d, rs) ->
+ Sig_class(newid, class_declaration s d, rs)
+ | Sig_class_type(id, d, rs) ->
+ Sig_class_type(newid, cltype_declaration s d, rs)
+
+and module_declaration s decl =
+ {
+ md_type = modtype s decl.md_type;
+ md_attributes = attrs s decl.md_attributes;
+ md_loc = loc s decl.md_loc;
+ }
+
+and modtype_declaration s decl =
+ {
+ mtd_type = may_map (modtype s) decl.mtd_type;
+ mtd_attributes = attrs s decl.mtd_attributes;
+ mtd_loc = loc s decl.mtd_loc;
+ }
+
+(* For every binding k |-> d of m1, add k |-> f d to m2
+ and return resulting merged map. *)
+
+let merge_tbls f m1 m2 =
+ Tbl.fold (fun k d accu -> Tbl.add k (f d) accu) m1 m2
+
+(* Composition of substitutions:
+ apply (compose s1 s2) x = apply s2 (apply s1 x) *)
+
+let compose s1 s2 =
+ { types = merge_tbls (type_path s2) s1.types s2.types;
+ modules = merge_tbls (module_path s2) s1.modules s2.modules;
+ modtypes = merge_tbls (modtype s2) s1.modtypes s2.modtypes;
+ for_saving = false }
diff --git a/typing/subst.mli b/typing/subst.mli
new file mode 100644
index 0000000000..7f6870e939
--- /dev/null
+++ b/typing/subst.mli
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Substitutions *)
+
+open Types
+
+type t
+
+(*
+ Substitutions are used to translate a type from one context to
+ another. This requires substituing paths for identifiers, and
+ possibly also lowering the level of non-generic variables so that
+ it be inferior to the maximum level of the new context.
+
+ Substitutions can also be used to create a "clean" copy of a type.
+ Indeed, non-variable node of a type are duplicated, with their
+ levels set to generic level. That way, the resulting type is
+ well-formed (decreasing levels), even if the original one was not.
+*)
+
+val identity: t
+
+val add_type: Ident.t -> Path.t -> t -> t
+val add_module: Ident.t -> Path.t -> t -> t
+val add_modtype: Ident.t -> module_type -> t -> t
+val for_saving: t -> t
+val reset_for_saving: unit -> unit
+
+val module_path: t -> Path.t -> Path.t
+val type_path: t -> Path.t -> Path.t
+
+val type_expr: t -> type_expr -> type_expr
+val class_type: t -> class_type -> class_type
+val value_description: t -> value_description -> value_description
+val type_declaration: t -> type_declaration -> type_declaration
+val extension_constructor:
+ t -> extension_constructor -> extension_constructor
+val class_declaration: t -> class_declaration -> class_declaration
+val cltype_declaration: t -> class_type_declaration -> class_type_declaration
+val modtype: t -> module_type -> module_type
+val signature: t -> signature -> signature
+val modtype_declaration: t -> modtype_declaration -> modtype_declaration
+val module_declaration: t -> module_declaration -> module_declaration
+val typexp : t -> Types.type_expr -> Types.type_expr
+val class_signature: t -> class_signature -> class_signature
+
+(* Composition of substitutions:
+ apply (compose s1 s2) x = apply s2 (apply s1 x) *)
+val compose: t -> t -> t
diff --git a/typing/tast_mapper.ml b/typing/tast_mapper.ml
new file mode 100644
index 0000000000..03aa97fc28
--- /dev/null
+++ b/typing/tast_mapper.ml
@@ -0,0 +1,672 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Asttypes
+open Typedtree
+
+(* TODO: add 'methods' for location, attribute, extension,
+ open_description, include_declaration, include_description *)
+
+type mapper =
+ {
+ case: mapper -> case -> case;
+ cases: mapper -> case list -> case list;
+ class_declaration: mapper -> class_declaration -> class_declaration;
+ class_description: mapper -> class_description -> class_description;
+ class_expr: mapper -> class_expr -> class_expr;
+ class_field: mapper -> class_field -> class_field;
+ class_signature: mapper -> class_signature -> class_signature;
+ class_structure: mapper -> class_structure -> class_structure;
+ class_type: mapper -> class_type -> class_type;
+ class_type_declaration: mapper -> class_type_declaration ->
+ class_type_declaration;
+ class_type_field: mapper -> class_type_field -> class_type_field;
+ env: mapper -> Env.t -> Env.t;
+ expr: mapper -> expression -> expression;
+ extension_constructor: mapper -> extension_constructor ->
+ extension_constructor;
+ module_binding: mapper -> module_binding -> module_binding;
+ module_coercion: mapper -> module_coercion -> module_coercion;
+ module_declaration: mapper -> module_declaration -> module_declaration;
+ module_expr: mapper -> module_expr -> module_expr;
+ module_type: mapper -> module_type -> module_type;
+ module_type_declaration:
+ mapper -> module_type_declaration -> module_type_declaration;
+ package_type: mapper -> package_type -> package_type;
+ pat: mapper -> pattern -> pattern;
+ row_field: mapper -> row_field -> row_field;
+ signature: mapper -> signature -> signature;
+ signature_item: mapper -> signature_item -> signature_item;
+ structure: mapper -> structure -> structure;
+ structure_item: mapper -> structure_item -> structure_item;
+ typ: mapper -> core_type -> core_type;
+ type_declaration: mapper -> type_declaration -> type_declaration;
+ type_declarations: mapper -> (rec_flag * type_declaration list) ->
+ (rec_flag * type_declaration list);
+ type_extension: mapper -> type_extension -> type_extension;
+ type_kind: mapper -> type_kind -> type_kind;
+ value_binding: mapper -> value_binding -> value_binding;
+ value_bindings: mapper -> (rec_flag * value_binding list) ->
+ (rec_flag * value_binding list);
+ value_description: mapper -> value_description -> value_description;
+ with_constraint: mapper -> with_constraint -> with_constraint;
+ }
+
+let id x = x
+let tuple2 f1 f2 (x, y) = (f1 x, f2 y)
+let tuple3 f1 f2 f3 (x, y, z) = (f1 x, f2 y, f3 z)
+let opt f = function None -> None | Some x -> Some (f x)
+
+let structure sub {str_items; str_type; str_final_env} =
+ {
+ str_items = List.map (sub.structure_item sub) str_items;
+ str_final_env = sub.env sub str_final_env;
+ str_type;
+ }
+
+let class_infos sub f x =
+ {x with
+ ci_params = List.map (tuple2 (sub.typ sub) id) x.ci_params;
+ ci_expr = f x.ci_expr;
+ }
+
+let module_type_declaration sub x =
+ let mtd_type = opt (sub.module_type sub) x.mtd_type in
+ {x with mtd_type}
+
+let module_declaration sub x =
+ let md_type = sub.module_type sub x.md_type in
+ {x with md_type}
+
+let include_infos f x = {x with incl_mod = f x.incl_mod}
+
+let class_type_declaration sub x =
+ class_infos sub (sub.class_type sub) x
+
+let class_declaration sub x =
+ class_infos sub (sub.class_expr sub) x
+
+let structure_item sub {str_desc; str_loc; str_env} =
+ let str_env = sub.env sub str_env in
+ let str_desc =
+ match str_desc with
+ | Tstr_eval (exp, attrs) -> Tstr_eval (sub.expr sub exp, attrs)
+ | Tstr_value (rec_flag, list) ->
+ let (rec_flag, list) = sub.value_bindings sub (rec_flag, list) in
+ Tstr_value (rec_flag, list)
+ | Tstr_primitive v -> Tstr_primitive (sub.value_description sub v)
+ | Tstr_type (rec_flag, list) ->
+ let (rec_flag, list) = sub.type_declarations sub (rec_flag, list) in
+ Tstr_type (rec_flag, list)
+ | Tstr_typext te -> Tstr_typext (sub.type_extension sub te)
+ | Tstr_exception ext -> Tstr_exception (sub.extension_constructor sub ext)
+ | Tstr_module mb -> Tstr_module (sub.module_binding sub mb)
+ | Tstr_recmodule list ->
+ Tstr_recmodule (List.map (sub.module_binding sub) list)
+ | Tstr_modtype x -> Tstr_modtype (sub.module_type_declaration sub x)
+ | Tstr_class list ->
+ Tstr_class
+ (List.map (tuple2 (sub.class_declaration sub) id) list)
+ | Tstr_class_type list ->
+ Tstr_class_type
+ (List.map (tuple3 id id (sub.class_type_declaration sub)) list)
+ | Tstr_include incl ->
+ Tstr_include (include_infos (sub.module_expr sub) incl)
+ | Tstr_open _
+ | Tstr_attribute _ as d -> d
+ in
+ {str_desc; str_env; str_loc}
+
+let value_description sub x =
+ let val_desc = sub.typ sub x.val_desc in
+ {x with val_desc}
+
+let label_decl sub x =
+ let ld_type = sub.typ sub x.ld_type in
+ {x with ld_type}
+
+let constructor_args sub = function
+ | Cstr_tuple l -> Cstr_tuple (List.map (sub.typ sub) l)
+ | Cstr_record l -> Cstr_record (List.map (label_decl sub) l)
+
+let constructor_decl sub cd =
+ let cd_args = constructor_args sub cd.cd_args in
+ let cd_res = opt (sub.typ sub) cd.cd_res in
+ {cd with cd_args; cd_res}
+
+let type_kind sub = function
+ | Ttype_abstract -> Ttype_abstract
+ | Ttype_variant list -> Ttype_variant (List.map (constructor_decl sub) list)
+ | Ttype_record list -> Ttype_record (List.map (label_decl sub) list)
+ | Ttype_open -> Ttype_open
+
+let type_declaration sub x =
+ let typ_cstrs =
+ List.map
+ (tuple3 (sub.typ sub) (sub.typ sub) id)
+ x.typ_cstrs
+ in
+ let typ_kind = sub.type_kind sub x.typ_kind in
+ let typ_manifest = opt (sub.typ sub) x.typ_manifest in
+ let typ_params = List.map (tuple2 (sub.typ sub) id) x.typ_params in
+ {x with typ_cstrs; typ_kind; typ_manifest; typ_params}
+
+let type_declarations sub (rec_flag, list) =
+ (rec_flag, List.map (sub.type_declaration sub) list)
+
+let type_extension sub x =
+ let tyext_params = List.map (tuple2 (sub.typ sub) id) x.tyext_params in
+ let tyext_constructors =
+ List.map (sub.extension_constructor sub) x.tyext_constructors
+ in
+ {x with tyext_constructors; tyext_params}
+
+let extension_constructor sub x =
+ let ext_kind =
+ match x.ext_kind with
+ Text_decl(ctl, cto) ->
+ Text_decl(constructor_args sub ctl, opt (sub.typ sub) cto)
+ | Text_rebind _ as d -> d
+ in
+ {x with ext_kind}
+
+let pat sub x =
+ let extra = function
+ | Tpat_type _
+ | Tpat_unpack as d -> d
+ | Tpat_constraint ct -> Tpat_constraint (sub.typ sub ct)
+ in
+ let pat_env = sub.env sub x.pat_env in
+ let pat_extra = List.map (tuple3 extra id id) x.pat_extra in
+ let pat_desc =
+ match x.pat_desc with
+ | Tpat_any
+ | Tpat_var _
+ | Tpat_constant _ as d -> d
+ | Tpat_tuple l -> Tpat_tuple (List.map (sub.pat sub) l)
+ | Tpat_construct (loc, cd, l) ->
+ Tpat_construct (loc, cd, List.map (sub.pat sub) l)
+ | Tpat_variant (l, po, rd) -> Tpat_variant (l, opt (sub.pat sub) po, rd)
+ | Tpat_record (l, closed) ->
+ Tpat_record (List.map (tuple3 id id (sub.pat sub)) l, closed)
+ | Tpat_array l -> Tpat_array (List.map (sub.pat sub) l)
+ | Tpat_or (p1, p2, rd) ->
+ Tpat_or (sub.pat sub p1, sub.pat sub p2, rd)
+ | Tpat_alias (p, id, s) -> Tpat_alias (sub.pat sub p, id, s)
+ | Tpat_lazy p -> Tpat_lazy (sub.pat sub p)
+ in
+ {x with pat_extra; pat_desc; pat_env}
+
+let expr sub x =
+ let extra = function
+ | Texp_constraint cty ->
+ Texp_constraint (sub.typ sub cty)
+ | Texp_coerce (cty1, cty2) ->
+ Texp_coerce (opt (sub.typ sub) cty1, sub.typ sub cty2)
+ | Texp_open (ovf, path, loc, env) ->
+ Texp_open (ovf, path, loc, sub.env sub env)
+ | Texp_newtype _ as d -> d
+ | Texp_poly cto -> Texp_poly (opt (sub.typ sub) cto)
+ in
+ let exp_extra = List.map (tuple3 extra id id) x.exp_extra in
+ let exp_env = sub.env sub x.exp_env in
+ let exp_desc =
+ match x.exp_desc with
+ | Texp_ident _
+ | Texp_constant _ as d -> d
+ | Texp_let (rec_flag, list, exp) ->
+ let (rec_flag, list) = sub.value_bindings sub (rec_flag, list) in
+ Texp_let (rec_flag, list, sub.expr sub exp)
+ | Texp_function (l, cases, p) ->
+ Texp_function (l, sub.cases sub cases, p)
+ | Texp_apply (exp, list) ->
+ Texp_apply (
+ sub.expr sub exp,
+ List.map (tuple3 id (opt (sub.expr sub)) id) list
+ )
+ | Texp_match (exp, cases, exn_cases, p) ->
+ Texp_match (
+ sub.expr sub exp,
+ sub.cases sub cases,
+ sub.cases sub exn_cases,
+ p
+ )
+ | Texp_try (exp, cases) ->
+ Texp_try (
+ sub.expr sub exp,
+ sub.cases sub cases
+ )
+ | Texp_tuple list ->
+ Texp_tuple (List.map (sub.expr sub) list)
+ | Texp_construct (lid, cd, args) ->
+ Texp_construct (lid, cd, List.map (sub.expr sub) args)
+ | Texp_variant (l, expo) ->
+ Texp_variant (l, opt (sub.expr sub) expo)
+ | Texp_record (list, expo) ->
+ Texp_record (
+ List.map (tuple3 id id (sub.expr sub)) list,
+ opt (sub.expr sub) expo
+ )
+ | Texp_field (exp, lid, ld) ->
+ Texp_field (sub.expr sub exp, lid, ld)
+ | Texp_setfield (exp1, lid, ld, exp2) ->
+ Texp_setfield (
+ sub.expr sub exp1,
+ lid,
+ ld,
+ sub.expr sub exp2
+ )
+ | Texp_array list ->
+ Texp_array (List.map (sub.expr sub) list)
+ | Texp_ifthenelse (exp1, exp2, expo) ->
+ Texp_ifthenelse (
+ sub.expr sub exp1,
+ sub.expr sub exp2,
+ opt (sub.expr sub) expo
+ )
+ | Texp_sequence (exp1, exp2) ->
+ Texp_sequence (
+ sub.expr sub exp1,
+ sub.expr sub exp2
+ )
+ | Texp_while (exp1, exp2) ->
+ Texp_while (
+ sub.expr sub exp1,
+ sub.expr sub exp2
+ )
+ | Texp_for (id, p, exp1, exp2, dir, exp3) ->
+ Texp_for (
+ id,
+ p,
+ sub.expr sub exp1,
+ sub.expr sub exp2,
+ dir,
+ sub.expr sub exp3
+ )
+ | Texp_send (exp, meth, expo) ->
+ Texp_send
+ (
+ sub.expr sub exp,
+ meth,
+ opt (sub.expr sub) expo
+ )
+ | Texp_new _
+ | Texp_instvar _ as d -> d
+ | Texp_setinstvar (path1, path2, id, exp) ->
+ Texp_setinstvar (
+ path1,
+ path2,
+ id,
+ sub.expr sub exp
+ )
+ | Texp_override (path, list) ->
+ Texp_override (
+ path,
+ List.map (tuple3 id id (sub.expr sub)) list
+ )
+ | Texp_letmodule (id, s, mexpr, exp) ->
+ Texp_letmodule (
+ id,
+ s,
+ sub.module_expr sub mexpr,
+ sub.expr sub exp
+ )
+ | Texp_assert exp ->
+ Texp_assert (sub.expr sub exp)
+ | Texp_lazy exp ->
+ Texp_lazy (sub.expr sub exp)
+ | Texp_object (cl, sl) ->
+ Texp_object (sub.class_structure sub cl, sl)
+ | Texp_pack mexpr ->
+ Texp_pack (sub.module_expr sub mexpr)
+ in
+ {x with exp_extra; exp_desc; exp_env}
+
+
+let package_type sub x =
+ let pack_fields = List.map (tuple2 id (sub.typ sub)) x.pack_fields in
+ {x with pack_fields}
+
+let signature sub x =
+ let sig_final_env = sub.env sub x.sig_final_env in
+ let sig_items = List.map (sub.signature_item sub) x.sig_items in
+ {x with sig_items; sig_final_env}
+
+let signature_item sub x =
+ let sig_env = sub.env sub x.sig_env in
+ let sig_desc =
+ match x.sig_desc with
+ | Tsig_value v ->
+ Tsig_value (sub.value_description sub v)
+ | Tsig_type (rec_flag, list) ->
+ let (rec_flag, list) = sub.type_declarations sub (rec_flag, list) in
+ Tsig_type (rec_flag, list)
+ | Tsig_typext te ->
+ Tsig_typext (sub.type_extension sub te)
+ | Tsig_exception ext ->
+ Tsig_exception (sub.extension_constructor sub ext)
+ | Tsig_module x ->
+ Tsig_module (sub.module_declaration sub x)
+ | Tsig_recmodule list ->
+ Tsig_recmodule (List.map (sub.module_declaration sub) list)
+ | Tsig_modtype x ->
+ Tsig_modtype (sub.module_type_declaration sub x)
+ | Tsig_include incl ->
+ Tsig_include (include_infos (sub.module_type sub) incl)
+ | Tsig_class list ->
+ Tsig_class (List.map (sub.class_description sub) list)
+ | Tsig_class_type list ->
+ Tsig_class_type
+ (List.map (sub.class_type_declaration sub) list)
+ | Tsig_open _
+ | Tsig_attribute _ as d -> d
+ in
+ {x with sig_desc; sig_env}
+
+let class_description sub x =
+ class_infos sub (sub.class_type sub) x
+
+let module_type sub x =
+ let mty_env = sub.env sub x.mty_env in
+ let mty_desc =
+ match x.mty_desc with
+ | Tmty_ident _
+ | Tmty_alias _ as d -> d
+ | Tmty_signature sg -> Tmty_signature (sub.signature sub sg)
+ | Tmty_functor (id, s, mtype1, mtype2) ->
+ Tmty_functor (
+ id,
+ s,
+ opt (sub.module_type sub) mtype1,
+ sub.module_type sub mtype2
+ )
+ | Tmty_with (mtype, list) ->
+ Tmty_with (
+ sub.module_type sub mtype,
+ List.map (tuple3 id id (sub.with_constraint sub)) list
+ )
+ | Tmty_typeof mexpr ->
+ Tmty_typeof (sub.module_expr sub mexpr)
+ in
+ {x with mty_desc; mty_env}
+
+let with_constraint sub = function
+ | Twith_type decl -> Twith_type (sub.type_declaration sub decl)
+ | Twith_typesubst decl -> Twith_typesubst (sub.type_declaration sub decl)
+ | Twith_module _
+ | Twith_modsubst _ as d -> d
+
+let module_coercion sub = function
+ | Tcoerce_none -> Tcoerce_none
+ | Tcoerce_functor (c1,c2) ->
+ Tcoerce_functor (sub.module_coercion sub c1, sub.module_coercion sub c2)
+ | Tcoerce_alias (p, c1) ->
+ Tcoerce_alias (p, sub.module_coercion sub c1)
+ | Tcoerce_structure (l1, l2) ->
+ let l1' = List.map (fun (i,c) -> i, sub.module_coercion sub c) l1 in
+ let l2' =
+ List.map (fun (id,i,c) -> id, i, sub.module_coercion sub c) l2
+ in
+ Tcoerce_structure (l1', l2')
+ | Tcoerce_primitive pc ->
+ Tcoerce_primitive {pc with pc_env = sub.env sub pc.pc_env}
+
+let module_expr sub x =
+ let mod_env = sub.env sub x.mod_env in
+ let mod_desc =
+ match x.mod_desc with
+ | Tmod_ident _ as d -> d
+ | Tmod_structure st -> Tmod_structure (sub.structure sub st)
+ | Tmod_functor (id, s, mtype, mexpr) ->
+ Tmod_functor (
+ id,
+ s,
+ opt (sub.module_type sub) mtype,
+ sub.module_expr sub mexpr
+ )
+ | Tmod_apply (mexp1, mexp2, c) ->
+ Tmod_apply (
+ sub.module_expr sub mexp1,
+ sub.module_expr sub mexp2,
+ sub.module_coercion sub c
+ )
+ | Tmod_constraint (mexpr, mt, Tmodtype_implicit, c) ->
+ Tmod_constraint (sub.module_expr sub mexpr, mt, Tmodtype_implicit,
+ sub.module_coercion sub c)
+ | Tmod_constraint (mexpr, mt, Tmodtype_explicit mtype, c) ->
+ Tmod_constraint (
+ sub.module_expr sub mexpr,
+ mt,
+ Tmodtype_explicit (sub.module_type sub mtype),
+ sub.module_coercion sub c
+ )
+ | Tmod_unpack (exp, mty) ->
+ Tmod_unpack
+ (
+ sub.expr sub exp,
+ mty
+ )
+ in
+ {x with mod_desc; mod_env}
+
+let module_binding sub x =
+ let mb_expr = module_expr sub x.mb_expr in
+ {x with mb_expr}
+
+let class_expr sub x =
+ let cl_env = sub.env sub x.cl_env in
+ let cl_desc =
+ match x.cl_desc with
+ | Tcl_constraint (cl, clty, vals, meths, concrs) ->
+ Tcl_constraint (
+ sub.class_expr sub cl,
+ opt (sub.class_type sub) clty,
+ vals,
+ meths,
+ concrs
+ )
+ | Tcl_structure clstr ->
+ Tcl_structure (sub.class_structure sub clstr)
+ | Tcl_fun (label, pat, priv, cl, partial) ->
+ Tcl_fun (
+ label,
+ sub.pat sub pat,
+ List.map (tuple3 id id (sub.expr sub)) priv,
+ sub.class_expr sub cl,
+ partial
+ )
+ | Tcl_apply (cl, args) ->
+ Tcl_apply (
+ sub.class_expr sub cl,
+ List.map (tuple3 id (opt (sub.expr sub)) id) args
+ )
+ | Tcl_let (rec_flag, value_bindings, ivars, cl) ->
+ let (rec_flag, value_bindings) =
+ sub.value_bindings sub (rec_flag, value_bindings)
+ in
+ Tcl_let (
+ rec_flag,
+ value_bindings,
+ List.map (tuple3 id id (sub.expr sub)) ivars,
+ sub.class_expr sub cl
+ )
+ | Tcl_ident (path, lid, tyl) ->
+ Tcl_ident (path, lid, List.map (sub.typ sub) tyl)
+ in
+ {x with cl_desc; cl_env}
+
+let class_type sub x =
+ let cltyp_env = sub.env sub x.cltyp_env in
+ let cltyp_desc =
+ match x.cltyp_desc with
+ | Tcty_signature csg -> Tcty_signature (sub.class_signature sub csg)
+ | Tcty_constr (path, lid, list) ->
+ Tcty_constr (
+ path,
+ lid,
+ List.map (sub.typ sub) list
+ )
+ | Tcty_arrow (label, ct, cl) ->
+ Tcty_arrow
+ (label,
+ sub.typ sub ct,
+ sub.class_type sub cl
+ )
+ in
+ {x with cltyp_desc; cltyp_env}
+
+let class_signature sub x =
+ let csig_self = sub.typ sub x.csig_self in
+ let csig_fields = List.map (sub.class_type_field sub) x.csig_fields in
+ {x with csig_self; csig_fields}
+
+let class_type_field sub x =
+ let ctf_desc =
+ match x.ctf_desc with
+ | Tctf_inherit ct ->
+ Tctf_inherit (sub.class_type sub ct)
+ | Tctf_val (s, mut, virt, ct) ->
+ Tctf_val (s, mut, virt, sub.typ sub ct)
+ | Tctf_method (s, priv, virt, ct) ->
+ Tctf_method (s, priv, virt, sub.typ sub ct)
+ | Tctf_constraint (ct1, ct2) ->
+ Tctf_constraint (sub.typ sub ct1, sub.typ sub ct2)
+ | Tctf_attribute _ as d -> d
+ in
+ {x with ctf_desc}
+
+let typ sub x =
+ let ctyp_env = sub.env sub x.ctyp_env in
+ let ctyp_desc =
+ match x.ctyp_desc with
+ | Ttyp_any
+ | Ttyp_var _ as d -> d
+ | Ttyp_arrow (label, ct1, ct2) ->
+ Ttyp_arrow (label, sub.typ sub ct1, sub.typ sub ct2)
+ | Ttyp_tuple list -> Ttyp_tuple (List.map (sub.typ sub) list)
+ | Ttyp_constr (path, lid, list) ->
+ Ttyp_constr (path, lid, List.map (sub.typ sub) list)
+ | Ttyp_object (list, closed) ->
+ Ttyp_object (
+ List.map (tuple3 id id (sub.typ sub)) list,
+ closed
+ )
+ | Ttyp_class (path, lid, list) ->
+ Ttyp_class
+ (path,
+ lid,
+ List.map (sub.typ sub) list
+ )
+ | Ttyp_alias (ct, s) ->
+ Ttyp_alias (sub.typ sub ct, s)
+ | Ttyp_variant (list, closed, labels) ->
+ Ttyp_variant (List.map (sub.row_field sub) list, closed, labels)
+ | Ttyp_poly (sl, ct) ->
+ Ttyp_poly (sl, sub.typ sub ct)
+ | Ttyp_package pack ->
+ Ttyp_package (sub.package_type sub pack)
+ in
+ {x with ctyp_desc; ctyp_env}
+
+let class_structure sub x =
+ let cstr_self = sub.pat sub x.cstr_self in
+ let cstr_fields = List.map (sub.class_field sub) x.cstr_fields in
+ {x with cstr_self; cstr_fields}
+
+let row_field sub = function
+ | Ttag (label, attrs, b, list) ->
+ Ttag (label, attrs, b, List.map (sub.typ sub) list)
+ | Tinherit ct -> Tinherit (sub.typ sub ct)
+
+let class_field_kind sub = function
+ | Tcfk_virtual ct -> Tcfk_virtual (sub.typ sub ct)
+ | Tcfk_concrete (ovf, e) -> Tcfk_concrete (ovf, sub.expr sub e)
+
+let class_field sub x =
+ let cf_desc =
+ match x.cf_desc with
+ | Tcf_inherit (ovf, cl, super, vals, meths) ->
+ Tcf_inherit (ovf, sub.class_expr sub cl, super, vals, meths)
+ | Tcf_constraint (cty, cty') ->
+ Tcf_constraint (
+ sub.typ sub cty,
+ sub.typ sub cty'
+ )
+ | Tcf_val (s, mf, id, k, b) ->
+ Tcf_val (s, mf, id, class_field_kind sub k, b)
+ | Tcf_method (s, priv, k) ->
+ Tcf_method (s, priv, class_field_kind sub k)
+ | Tcf_initializer exp ->
+ Tcf_initializer (sub.expr sub exp)
+ | Tcf_attribute _ as d -> d
+ in
+ {x with cf_desc}
+
+let value_bindings sub (rec_flag, list) =
+ (rec_flag, List.map (sub.value_binding sub) list)
+
+let cases sub l =
+ List.map (sub.case sub) l
+
+let case sub {c_lhs; c_guard; c_rhs} =
+ {
+ c_lhs = sub.pat sub c_lhs;
+ c_guard = opt (sub.expr sub) c_guard;
+ c_rhs = sub.expr sub c_rhs;
+ }
+
+let value_binding sub x =
+ let vb_pat = sub.pat sub x.vb_pat in
+ let vb_expr = sub.expr sub x.vb_expr in
+ {x with vb_pat; vb_expr}
+
+let env _sub x = x
+
+let default =
+ {
+ case;
+ cases;
+ class_declaration;
+ class_description;
+ class_expr;
+ class_field;
+ class_signature;
+ class_structure;
+ class_type;
+ class_type_declaration;
+ class_type_field;
+ env;
+ expr;
+ extension_constructor;
+ module_binding;
+ module_coercion;
+ module_declaration;
+ module_expr;
+ module_type;
+ module_type_declaration;
+ package_type;
+ pat;
+ row_field;
+ signature;
+ signature_item;
+ structure;
+ structure_item;
+ typ;
+ type_declaration;
+ type_declarations;
+ type_extension;
+ type_kind;
+ value_binding;
+ value_bindings;
+ value_description;
+ with_constraint;
+ }
diff --git a/typing/tast_mapper.mli b/typing/tast_mapper.mli
new file mode 100644
index 0000000000..863145da02
--- /dev/null
+++ b/typing/tast_mapper.mli
@@ -0,0 +1,64 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Alain Frisch, LexiFi *)
+(* *)
+(* Copyright 2015 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Asttypes
+open Typedtree
+
+(** {2 A generic Typedtree mapper} *)
+
+type mapper =
+ {
+ case: mapper -> case -> case;
+ cases: mapper -> case list -> case list;
+ class_declaration: mapper -> class_declaration -> class_declaration;
+ class_description: mapper -> class_description -> class_description;
+ class_expr: mapper -> class_expr -> class_expr;
+ class_field: mapper -> class_field -> class_field;
+ class_signature: mapper -> class_signature -> class_signature;
+ class_structure: mapper -> class_structure -> class_structure;
+ class_type: mapper -> class_type -> class_type;
+ class_type_declaration: mapper -> class_type_declaration ->
+ class_type_declaration;
+ class_type_field: mapper -> class_type_field -> class_type_field;
+ env: mapper -> Env.t -> Env.t;
+ expr: mapper -> expression -> expression;
+ extension_constructor: mapper -> extension_constructor ->
+ extension_constructor;
+ module_binding: mapper -> module_binding -> module_binding;
+ module_coercion: mapper -> module_coercion -> module_coercion;
+ module_declaration: mapper -> module_declaration -> module_declaration;
+ module_expr: mapper -> module_expr -> module_expr;
+ module_type: mapper -> module_type -> module_type;
+ module_type_declaration:
+ mapper -> module_type_declaration -> module_type_declaration;
+ package_type: mapper -> package_type -> package_type;
+ pat: mapper -> pattern -> pattern;
+ row_field: mapper -> row_field -> row_field;
+ signature: mapper -> signature -> signature;
+ signature_item: mapper -> signature_item -> signature_item;
+ structure: mapper -> structure -> structure;
+ structure_item: mapper -> structure_item -> structure_item;
+ typ: mapper -> core_type -> core_type;
+ type_declaration: mapper -> type_declaration -> type_declaration;
+ type_declarations: mapper -> (rec_flag * type_declaration list) ->
+ (rec_flag * type_declaration list);
+ type_extension: mapper -> type_extension -> type_extension;
+ type_kind: mapper -> type_kind -> type_kind;
+ value_binding: mapper -> value_binding -> value_binding;
+ value_bindings: mapper -> (rec_flag * value_binding list) ->
+ (rec_flag * value_binding list);
+ value_description: mapper -> value_description -> value_description;
+ with_constraint: mapper -> with_constraint -> with_constraint;
+ }
+
+
+val default: mapper
diff --git a/typing/typeclass.ml b/typing/typeclass.ml
new file mode 100644
index 0000000000..46eb5be923
--- /dev/null
+++ b/typing/typeclass.ml
@@ -0,0 +1,1880 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Parsetree
+open Asttypes
+open Path
+open Types
+open Typecore
+open Typetexp
+open Format
+
+type error =
+ Unconsistent_constraint of (type_expr * type_expr) list
+ | Field_type_mismatch of string * string * (type_expr * type_expr) list
+ | Structure_expected of class_type
+ | Cannot_apply of class_type
+ | Apply_wrong_label of arg_label
+ | Pattern_type_clash of type_expr
+ | Repeated_parameter
+ | Unbound_class_2 of Longident.t
+ | Unbound_class_type_2 of Longident.t
+ | Abbrev_type_clash of type_expr * type_expr * type_expr
+ | Constructor_type_mismatch of string * (type_expr * type_expr) list
+ | Virtual_class of bool * bool * string list * string list
+ | Parameter_arity_mismatch of Longident.t * int * int
+ | Parameter_mismatch of (type_expr * type_expr) list
+ | Bad_parameters of Ident.t * type_expr * type_expr
+ | Class_match_failure of Ctype.class_match_failure list
+ | Unbound_val of string
+ | Unbound_type_var of (formatter -> unit) * Ctype.closed_class_failure
+ | Make_nongen_seltype of type_expr
+ | Non_generalizable_class of Ident.t * Types.class_declaration
+ | Cannot_coerce_self of type_expr
+ | Non_collapsable_conjunction of
+ Ident.t * Types.class_declaration * (type_expr * type_expr) list
+ | Final_self_clash of (type_expr * type_expr) list
+ | Mutability_mismatch of string * mutable_flag
+ | No_overriding of string * string
+ | Duplicate of string * string
+
+exception Error of Location.t * Env.t * error
+exception Error_forward of Location.error
+
+open Typedtree
+
+let ctyp desc typ env loc =
+ { ctyp_desc = desc; ctyp_type = typ; ctyp_loc = loc; ctyp_env = env;
+ ctyp_attributes = [] }
+
+ (**********************)
+ (* Useful constants *)
+ (**********************)
+
+
+(*
+ Self type have a dummy private method, thus preventing it to become
+ closed.
+*)
+let dummy_method = Btype.dummy_method
+
+(*
+ Path associated to the temporary class type of a class being typed
+ (its constructor is not available).
+*)
+let unbound_class = Path.Pident (Ident.create "*undef*")
+
+
+ (************************************)
+ (* Some operations on class types *)
+ (************************************)
+
+
+(* Fully expand the head of a class type *)
+let rec scrape_class_type =
+ function
+ Cty_constr (_, _, cty) -> scrape_class_type cty
+ | cty -> cty
+
+(* Generalize a class type *)
+let rec generalize_class_type gen =
+ function
+ Cty_constr (_, params, cty) ->
+ List.iter gen params;
+ generalize_class_type gen cty
+ | Cty_signature {csig_self = sty; csig_vars = vars; csig_inher = inher} ->
+ gen sty;
+ Vars.iter (fun _ (_, _, ty) -> gen ty) vars;
+ List.iter (fun (_,tl) -> List.iter gen tl) inher
+ | Cty_arrow (_, ty, cty) ->
+ gen ty;
+ generalize_class_type gen cty
+
+let generalize_class_type vars =
+ let gen = if vars then Ctype.generalize else Ctype.generalize_structure in
+ generalize_class_type gen
+
+(* Return the virtual methods of a class type *)
+let virtual_methods sign =
+ let (fields, _) =
+ Ctype.flatten_fields (Ctype.object_fields sign.Types.csig_self)
+ in
+ List.fold_left
+ (fun virt (lab, _, _) ->
+ if lab = dummy_method then virt else
+ if Concr.mem lab sign.csig_concr then virt else
+ lab::virt)
+ [] fields
+
+(* Return the constructor type associated to a class type *)
+let rec constructor_type constr cty =
+ match cty with
+ Cty_constr (_, _, cty) ->
+ constructor_type constr cty
+ | Cty_signature sign ->
+ constr
+ | Cty_arrow (l, ty, cty) ->
+ Ctype.newty (Tarrow (l, ty, constructor_type constr cty, Cok))
+
+let rec class_body cty =
+ match cty with
+ Cty_constr (_, _, cty') ->
+ cty (* Only class bodies can be abbreviated *)
+ | Cty_signature sign ->
+ cty
+ | Cty_arrow (_, ty, cty) ->
+ class_body cty
+
+let extract_constraints cty =
+ let sign = Ctype.signature_of_class_type cty in
+ (Vars.fold (fun lab _ vars -> lab :: vars) sign.csig_vars [],
+ begin let (fields, _) =
+ Ctype.flatten_fields (Ctype.object_fields sign.csig_self)
+ in
+ List.fold_left
+ (fun meths (lab, _, _) ->
+ if lab = dummy_method then meths else lab::meths)
+ [] fields
+ end,
+ sign.csig_concr)
+
+let rec abbreviate_class_type path params cty =
+ match cty with
+ Cty_constr (_, _, _) | Cty_signature _ ->
+ Cty_constr (path, params, cty)
+ | Cty_arrow (l, ty, cty) ->
+ Cty_arrow (l, ty, abbreviate_class_type path params cty)
+
+(* Check that all type variables are generalizable *)
+(* Use Env.empty to prevent expansion of recursively defined object types;
+ cf. typing-poly/poly.ml *)
+let rec closed_class_type =
+ function
+ Cty_constr (_, params, _) ->
+ List.for_all (Ctype.closed_schema Env.empty) params
+ | Cty_signature sign ->
+ Ctype.closed_schema Env.empty sign.csig_self
+ &&
+ Vars.fold (fun _ (_, _, ty) cc -> Ctype.closed_schema Env.empty ty && cc)
+ sign.csig_vars
+ true
+ | Cty_arrow (_, ty, cty) ->
+ Ctype.closed_schema Env.empty ty
+ &&
+ closed_class_type cty
+
+let closed_class cty =
+ List.for_all (Ctype.closed_schema Env.empty) cty.cty_params
+ &&
+ closed_class_type cty.cty_type
+
+let rec limited_generalize rv =
+ function
+ Cty_constr (path, params, cty) ->
+ List.iter (Ctype.limited_generalize rv) params;
+ limited_generalize rv cty
+ | Cty_signature sign ->
+ Ctype.limited_generalize rv sign.csig_self;
+ Vars.iter (fun _ (_, _, ty) -> Ctype.limited_generalize rv ty)
+ sign.csig_vars;
+ List.iter (fun (_, tl) -> List.iter (Ctype.limited_generalize rv) tl)
+ sign.csig_inher
+ | Cty_arrow (_, ty, cty) ->
+ Ctype.limited_generalize rv ty;
+ limited_generalize rv cty
+
+(* Record a class type *)
+let rc node =
+ Cmt_format.add_saved_type (Cmt_format.Partial_class_expr node);
+ Stypes.record (Stypes.Ti_class node); (* moved to genannot *)
+ node
+
+
+ (***********************************)
+ (* Primitives for typing classes *)
+ (***********************************)
+
+
+(* Enter a value in the method environment only *)
+let enter_met_env ?check loc lab kind ty val_env met_env par_env =
+ let (id, val_env) =
+ Env.enter_value lab {val_type = ty; val_kind = Val_unbound;
+ val_attributes = [];
+ Types.val_loc = loc} val_env
+ in
+ (id, val_env,
+ Env.add_value ?check id {val_type = ty; val_kind = kind;
+ val_attributes = [];
+ Types.val_loc = loc} met_env,
+ Env.add_value id {val_type = ty; val_kind = Val_unbound;
+ val_attributes = [];
+ Types.val_loc = loc} par_env)
+
+(* Enter an instance variable in the environment *)
+let enter_val cl_num vars inh lab mut virt ty val_env met_env par_env loc =
+ let instance = Ctype.instance val_env in
+ let (id, virt) =
+ try
+ let (id, mut', virt', ty') = Vars.find lab !vars in
+ if mut' <> mut then
+ raise (Error(loc, val_env, Mutability_mismatch(lab, mut)));
+ Ctype.unify val_env (instance ty) (instance ty');
+ (if not inh then Some id else None),
+ (if virt' = Concrete then virt' else virt)
+ with
+ Ctype.Unify tr ->
+ raise (Error(loc, val_env,
+ Field_type_mismatch("instance variable", lab, tr)))
+ | Not_found -> None, virt
+ in
+ let (id, _, _, _) as result =
+ match id with Some id -> (id, val_env, met_env, par_env)
+ | None ->
+ enter_met_env Location.none lab (Val_ivar (mut, cl_num))
+ ty val_env met_env par_env
+ in
+ vars := Vars.add lab (id, mut, virt, ty) !vars;
+ result
+
+let concr_vals vars =
+ Vars.fold
+ (fun id (_, vf, _) s -> if vf = Virtual then s else Concr.add id s)
+ vars Concr.empty
+
+let inheritance self_type env ovf concr_meths warn_vals loc parent =
+ match scrape_class_type parent with
+ Cty_signature cl_sig ->
+
+ (* Methods *)
+ begin try
+ Ctype.unify env self_type cl_sig.csig_self
+ with Ctype.Unify trace ->
+ match trace with
+ _::_::_::({desc = Tfield(n, _, _, _)}, _)::rem ->
+ raise(Error(loc, env, Field_type_mismatch ("method", n, rem)))
+ | _ ->
+ assert false
+ end;
+
+ (* Overriding *)
+ let over_meths = Concr.inter cl_sig.csig_concr concr_meths in
+ let concr_vals = concr_vals cl_sig.csig_vars in
+ let over_vals = Concr.inter concr_vals warn_vals in
+ begin match ovf with
+ Some Fresh ->
+ let cname =
+ match parent with
+ Cty_constr (p, _, _) -> Path.name p
+ | _ -> "inherited"
+ in
+ if not (Concr.is_empty over_meths) then
+ Location.prerr_warning loc
+ (Warnings.Method_override (cname :: Concr.elements over_meths));
+ if not (Concr.is_empty over_vals) then
+ Location.prerr_warning loc
+ (Warnings.Instance_variable_override
+ (cname :: Concr.elements over_vals));
+ | Some Override
+ when Concr.is_empty over_meths && Concr.is_empty over_vals ->
+ raise (Error(loc, env, No_overriding ("","")))
+ | _ -> ()
+ end;
+
+ let concr_meths = Concr.union cl_sig.csig_concr concr_meths
+ and warn_vals = Concr.union concr_vals warn_vals in
+
+ (cl_sig, concr_meths, warn_vals)
+
+ | _ ->
+ raise(Error(loc, env, Structure_expected parent))
+
+let virtual_method val_env meths self_type lab priv sty loc =
+ let (_, ty') =
+ Ctype.filter_self_method val_env lab priv meths self_type
+ in
+ let sty = Ast_helper.Typ.force_poly sty in
+ let cty = transl_simple_type val_env false sty in
+ let ty = cty.ctyp_type in
+ begin
+ try Ctype.unify val_env ty ty' with Ctype.Unify trace ->
+ raise(Error(loc, val_env, Field_type_mismatch ("method", lab, trace)));
+ end;
+ cty
+
+let delayed_meth_specs = ref []
+
+let declare_method val_env meths self_type lab priv sty loc =
+ let (_, ty') =
+ Ctype.filter_self_method val_env lab priv meths self_type
+ in
+ let unif ty =
+ try Ctype.unify val_env ty ty' with Ctype.Unify trace ->
+ raise(Error(loc, val_env, Field_type_mismatch ("method", lab, trace)))
+ in
+ let sty = Ast_helper.Typ.force_poly sty in
+ match sty.ptyp_desc, priv with
+ Ptyp_poly ([],sty'), Public ->
+(* TODO: we moved the [transl_simple_type_univars] outside of the lazy,
+so that we can get an immediate value. Is that correct ? Ask Jacques. *)
+ let returned_cty = ctyp Ttyp_any (Ctype.newty Tnil) val_env loc in
+ delayed_meth_specs :=
+ lazy (
+ let cty = transl_simple_type_univars val_env sty' in
+ let ty = cty.ctyp_type in
+ unif ty;
+ returned_cty.ctyp_desc <- Ttyp_poly ([], cty);
+ returned_cty.ctyp_type <- ty;
+ ) ::
+ !delayed_meth_specs;
+ returned_cty
+ | _ ->
+ let cty = transl_simple_type val_env false sty in
+ let ty = cty.ctyp_type in
+ unif ty;
+ cty
+
+let type_constraint val_env sty sty' loc =
+ let cty = transl_simple_type val_env false sty in
+ let ty = cty.ctyp_type in
+ let cty' = transl_simple_type val_env false sty' in
+ let ty' = cty'.ctyp_type in
+ begin
+ try Ctype.unify val_env ty ty' with Ctype.Unify trace ->
+ raise(Error(loc, val_env, Unconsistent_constraint trace));
+ end;
+ (cty, cty')
+
+let make_method loc cl_num expr =
+ let open Ast_helper in
+ let mkid s = mkloc s loc in
+ Exp.fun_ ~loc:expr.pexp_loc Nolabel None
+ (Pat.alias ~loc (Pat.var ~loc (mkid "self-*")) (mkid ("self-" ^ cl_num)))
+ expr
+
+(*******************************)
+
+let add_val env loc lab (mut, virt, ty) val_sig =
+ let virt =
+ try
+ let (mut', virt', ty') = Vars.find lab val_sig in
+ if virt' = Concrete then virt' else virt
+ with Not_found -> virt
+ in
+ Vars.add lab (mut, virt, ty) val_sig
+
+let rec class_type_field env self_type meths
+ (fields, val_sig, concr_meths, inher) ctf =
+ let loc = ctf.pctf_loc in
+ let mkctf desc =
+ { ctf_desc = desc; ctf_loc = loc; ctf_attributes = ctf.pctf_attributes }
+ in
+ match ctf.pctf_desc with
+ Pctf_inherit sparent ->
+ let parent = class_type env sparent in
+ let inher =
+ match parent.cltyp_type with
+ Cty_constr (p, tl, _) -> (p, tl) :: inher
+ | _ -> inher
+ in
+ let (cl_sig, concr_meths, _) =
+ inheritance self_type env None concr_meths Concr.empty sparent.pcty_loc
+ parent.cltyp_type
+ in
+ let val_sig =
+ Vars.fold (add_val env sparent.pcty_loc) cl_sig.csig_vars val_sig in
+ (mkctf (Tctf_inherit parent) :: fields,
+ val_sig, concr_meths, inher)
+
+ | Pctf_val (lab, mut, virt, sty) ->
+ let cty = transl_simple_type env false sty in
+ let ty = cty.ctyp_type in
+ (mkctf (Tctf_val (lab, mut, virt, cty)) :: fields,
+ add_val env ctf.pctf_loc lab (mut, virt, ty) val_sig, concr_meths, inher)
+
+ | Pctf_method (lab, priv, virt, sty) ->
+ let cty =
+ declare_method env meths self_type lab priv sty ctf.pctf_loc in
+ let concr_meths =
+ match virt with
+ | Concrete -> Concr.add lab concr_meths
+ | Virtual -> concr_meths
+ in
+ (mkctf (Tctf_method (lab, priv, virt, cty)) :: fields,
+ val_sig, concr_meths, inher)
+
+ | Pctf_constraint (sty, sty') ->
+ let (cty, cty') = type_constraint env sty sty' ctf.pctf_loc in
+ (mkctf (Tctf_constraint (cty, cty')) :: fields,
+ val_sig, concr_meths, inher)
+
+ | Pctf_attribute x ->
+ Typetexp.warning_attribute [x];
+ (mkctf (Tctf_attribute x) :: fields,
+ val_sig, concr_meths, inher)
+
+ | Pctf_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+and class_signature env {pcsig_self=sty; pcsig_fields=sign} =
+ let meths = ref Meths.empty in
+ let self_cty = transl_simple_type env false sty in
+ let self_cty = { self_cty with
+ ctyp_type = Ctype.expand_head env self_cty.ctyp_type } in
+ let self_type = self_cty.ctyp_type in
+
+ (* Check that the binder is a correct type, and introduce a dummy
+ method preventing self type from being closed. *)
+ let dummy_obj = Ctype.newvar () in
+ Ctype.unify env (Ctype.filter_method env dummy_method Private dummy_obj)
+ (Ctype.newty (Ttuple []));
+ begin try
+ Ctype.unify env self_type dummy_obj
+ with Ctype.Unify _ ->
+ raise(Error(sty.ptyp_loc, env, Pattern_type_clash self_type))
+ end;
+
+ (* Class type fields *)
+ Typetexp.warning_enter_scope ();
+ let (rev_fields, val_sig, concr_meths, inher) =
+ List.fold_left (class_type_field env self_type meths)
+ ([], Vars.empty, Concr.empty, [])
+ sign
+ in
+ Typetexp.warning_leave_scope ();
+ let cty = {csig_self = self_type;
+ csig_vars = val_sig;
+ csig_concr = concr_meths;
+ csig_inher = inher}
+ in
+ { csig_self = self_cty;
+ csig_fields = List.rev rev_fields;
+ csig_type = cty;
+ }
+
+and class_type env scty =
+ let cltyp desc typ =
+ {
+ cltyp_desc = desc;
+ cltyp_type = typ;
+ cltyp_loc = scty.pcty_loc;
+ cltyp_env = env;
+ cltyp_attributes = scty.pcty_attributes;
+ }
+ in
+ match scty.pcty_desc with
+ Pcty_constr (lid, styl) ->
+ let (path, decl) = Typetexp.find_class_type env scty.pcty_loc lid.txt in
+ if Path.same decl.clty_path unbound_class then
+ raise(Error(scty.pcty_loc, env, Unbound_class_type_2 lid.txt));
+ let (params, clty) =
+ Ctype.instance_class decl.clty_params decl.clty_type
+ in
+ if List.length params <> List.length styl then
+ raise(Error(scty.pcty_loc, env,
+ Parameter_arity_mismatch (lid.txt, List.length params,
+ List.length styl)));
+ let ctys = List.map2
+ (fun sty ty ->
+ let cty' = transl_simple_type env false sty in
+ let ty' = cty'.ctyp_type in
+ begin
+ try Ctype.unify env ty' ty with Ctype.Unify trace ->
+ raise(Error(sty.ptyp_loc, env, Parameter_mismatch trace))
+ end;
+ cty'
+ ) styl params
+ in
+ let typ = Cty_constr (path, params, clty) in
+ cltyp (Tcty_constr ( path, lid , ctys)) typ
+
+ | Pcty_signature pcsig ->
+ let clsig = class_signature env pcsig in
+ let typ = Cty_signature clsig.csig_type in
+ cltyp (Tcty_signature clsig) typ
+
+ | Pcty_arrow (l, sty, scty) ->
+ let cty = transl_simple_type env false sty in
+ let ty = cty.ctyp_type in
+ let ty =
+ if Btype.is_optional l
+ then Ctype.newty (Tconstr(Predef.path_option,[ty], ref Mnil))
+ else ty in
+ let clty = class_type env scty in
+ let typ = Cty_arrow (l, ty, clty.cltyp_type) in
+ cltyp (Tcty_arrow (l, cty, clty)) typ
+ | Pcty_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+let class_type env scty =
+ delayed_meth_specs := [];
+ let cty = class_type env scty in
+ List.iter Lazy.force (List.rev !delayed_meth_specs);
+ delayed_meth_specs := [];
+ cty
+
+(*******************************)
+
+let rec class_field self_loc cl_num self_type meths vars
+ (val_env, met_env, par_env, fields, concr_meths, warn_vals, inher,
+ local_meths, local_vals)
+ cf =
+ let loc = cf.pcf_loc in
+ let mkcf desc =
+ { cf_desc = desc; cf_loc = loc; cf_attributes = cf.pcf_attributes }
+ in
+ match cf.pcf_desc with
+ Pcf_inherit (ovf, sparent, super) ->
+ let parent = class_expr cl_num val_env par_env sparent in
+ let inher =
+ match parent.cl_type with
+ Cty_constr (p, tl, _) -> (p, tl) :: inher
+ | _ -> inher
+ in
+ let (cl_sig, concr_meths, warn_vals) =
+ inheritance self_type val_env (Some ovf) concr_meths warn_vals
+ sparent.pcl_loc parent.cl_type
+ in
+ (* Variables *)
+ let (val_env, met_env, par_env, inh_vars) =
+ Vars.fold
+ (fun lab info (val_env, met_env, par_env, inh_vars) ->
+ let mut, vr, ty = info in
+ let (id, val_env, met_env, par_env) =
+ enter_val cl_num vars true lab mut vr ty val_env met_env par_env
+ sparent.pcl_loc
+ in
+ (val_env, met_env, par_env, (lab, id) :: inh_vars))
+ cl_sig.csig_vars (val_env, met_env, par_env, [])
+ in
+ (* Inherited concrete methods *)
+ let inh_meths =
+ Concr.fold (fun lab rem -> (lab, Ident.create lab)::rem)
+ cl_sig.csig_concr []
+ in
+ (* Super *)
+ let (val_env, met_env, par_env) =
+ match super with
+ None ->
+ (val_env, met_env, par_env)
+ | Some name ->
+ let (id, val_env, met_env, par_env) =
+ enter_met_env ~check:(fun s -> Warnings.Unused_ancestor s)
+ sparent.pcl_loc name (Val_anc (inh_meths, cl_num)) self_type
+ val_env met_env par_env
+ in
+ (val_env, met_env, par_env)
+ in
+ (val_env, met_env, par_env,
+ lazy (mkcf (Tcf_inherit (ovf, parent, super, inh_vars, inh_meths)))
+ :: fields,
+ concr_meths, warn_vals, inher, local_meths, local_vals)
+
+ | Pcf_val (lab, mut, Cfk_virtual styp) ->
+ if !Clflags.principal then Ctype.begin_def ();
+ let cty = Typetexp.transl_simple_type val_env false styp in
+ let ty = cty.ctyp_type in
+ if !Clflags.principal then begin
+ Ctype.end_def ();
+ Ctype.generalize_structure ty
+ end;
+ let (id, val_env, met_env', par_env) =
+ enter_val cl_num vars false lab.txt mut Virtual ty
+ val_env met_env par_env loc
+ in
+ (val_env, met_env', par_env,
+ lazy (mkcf (Tcf_val (lab, mut, id, Tcfk_virtual cty,
+ met_env == met_env')))
+ :: fields,
+ concr_meths, warn_vals, inher, local_meths, local_vals)
+
+ | Pcf_val (lab, mut, Cfk_concrete (ovf, sexp)) ->
+ if Concr.mem lab.txt local_vals then
+ raise(Error(loc, val_env, Duplicate ("instance variable", lab.txt)));
+ if Concr.mem lab.txt warn_vals then begin
+ if ovf = Fresh then
+ Location.prerr_warning lab.loc
+ (Warnings.Instance_variable_override[lab.txt])
+ end else begin
+ if ovf = Override then
+ raise(Error(loc, val_env,
+ No_overriding ("instance variable", lab.txt)))
+ end;
+ if !Clflags.principal then Ctype.begin_def ();
+ let exp =
+ try type_exp val_env sexp with Ctype.Unify [(ty, _)] ->
+ raise(Error(loc, val_env, Make_nongen_seltype ty))
+ in
+ if !Clflags.principal then begin
+ Ctype.end_def ();
+ Ctype.generalize_structure exp.exp_type
+ end;
+ let (id, val_env, met_env', par_env) =
+ enter_val cl_num vars false lab.txt mut Concrete exp.exp_type
+ val_env met_env par_env loc
+ in
+ (val_env, met_env', par_env,
+ lazy (mkcf (Tcf_val (lab, mut, id,
+ Tcfk_concrete (ovf, exp), met_env == met_env')))
+ :: fields,
+ concr_meths, Concr.add lab.txt warn_vals, inher, local_meths,
+ Concr.add lab.txt local_vals)
+
+ | Pcf_method (lab, priv, Cfk_virtual sty) ->
+ let cty = virtual_method val_env meths self_type lab.txt priv sty loc in
+ (val_env, met_env, par_env,
+ lazy (mkcf(Tcf_method (lab, priv, Tcfk_virtual cty)))
+ ::fields,
+ concr_meths, warn_vals, inher, local_meths, local_vals)
+
+ | Pcf_method (lab, priv, Cfk_concrete (ovf, expr)) ->
+ let expr =
+ match expr.pexp_desc with
+ | Pexp_poly _ -> expr
+ | _ -> Ast_helper.Exp.poly ~loc:expr.pexp_loc expr None
+ in
+ if Concr.mem lab.txt local_meths then
+ raise(Error(loc, val_env, Duplicate ("method", lab.txt)));
+ if Concr.mem lab.txt concr_meths then begin
+ if ovf = Fresh then
+ Location.prerr_warning loc (Warnings.Method_override [lab.txt])
+ end else begin
+ if ovf = Override then
+ raise(Error(loc, val_env, No_overriding("method", lab.txt)))
+ end;
+ let (_, ty) =
+ Ctype.filter_self_method val_env lab.txt priv meths self_type
+ in
+ begin try match expr.pexp_desc with
+ Pexp_poly (sbody, sty) ->
+ begin match sty with None -> ()
+ | Some sty ->
+ let sty = Ast_helper.Typ.force_poly sty in
+ let cty' = Typetexp.transl_simple_type val_env false sty in
+ let ty' = cty'.ctyp_type in
+ Ctype.unify val_env ty' ty
+ end;
+ begin match (Ctype.repr ty).desc with
+ Tvar _ ->
+ let ty' = Ctype.newvar () in
+ Ctype.unify val_env (Ctype.newty (Tpoly (ty', []))) ty;
+ Ctype.unify val_env (type_approx val_env sbody) ty'
+ | Tpoly (ty1, tl) ->
+ let _, ty1' = Ctype.instance_poly false tl ty1 in
+ let ty2 = type_approx val_env sbody in
+ Ctype.unify val_env ty2 ty1'
+ | _ -> assert false
+ end
+ | _ -> assert false
+ with Ctype.Unify trace ->
+ raise(Error(loc, val_env,
+ Field_type_mismatch ("method", lab.txt, trace)))
+ end;
+ let meth_expr = make_method self_loc cl_num expr in
+ (* backup variables for Pexp_override *)
+ let vars_local = !vars in
+
+ let field =
+ lazy begin
+ (* Read the generalized type *)
+ let (_, ty) = Meths.find lab.txt !meths in
+ let meth_type =
+ Btype.newgenty (Tarrow(Nolabel, self_type, ty, Cok)) in
+ Ctype.raise_nongen_level ();
+ vars := vars_local;
+ let texp = type_expect met_env meth_expr meth_type in
+ Ctype.end_def ();
+ mkcf (Tcf_method (lab, priv, Tcfk_concrete (ovf, texp)))
+ end in
+ (val_env, met_env, par_env, field::fields,
+ Concr.add lab.txt concr_meths, warn_vals, inher,
+ Concr.add lab.txt local_meths, local_vals)
+
+ | Pcf_constraint (sty, sty') ->
+ let (cty, cty') = type_constraint val_env sty sty' loc in
+ (val_env, met_env, par_env,
+ lazy (mkcf (Tcf_constraint (cty, cty'))) :: fields,
+ concr_meths, warn_vals, inher, local_meths, local_vals)
+
+ | Pcf_initializer expr ->
+ let expr = make_method self_loc cl_num expr in
+ let vars_local = !vars in
+ let field =
+ lazy begin
+ Ctype.raise_nongen_level ();
+ let meth_type =
+ Ctype.newty
+ (Tarrow (Nolabel, self_type,
+ Ctype.instance_def Predef.type_unit, Cok)) in
+ vars := vars_local;
+ let texp = type_expect met_env expr meth_type in
+ Ctype.end_def ();
+ mkcf (Tcf_initializer texp)
+ end in
+ (val_env, met_env, par_env, field::fields, concr_meths, warn_vals,
+ inher, local_meths, local_vals)
+ | Pcf_attribute x ->
+ Typetexp.warning_attribute [x];
+ (val_env, met_env, par_env,
+ lazy (mkcf (Tcf_attribute x)) :: fields,
+ concr_meths, warn_vals, inher, local_meths, local_vals)
+ | Pcf_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+and class_structure cl_num final val_env met_env loc
+ { pcstr_self = spat; pcstr_fields = str } =
+ (* Environment for substructures *)
+ let par_env = met_env in
+
+ (* Location of self. Used for locations of self arguments *)
+ let self_loc = {spat.ppat_loc with Location.loc_ghost = true} in
+
+ (* Self type, with a dummy method preventing it from being closed/escaped. *)
+ let self_type = Ctype.newvar () in
+ Ctype.unify val_env
+ (Ctype.filter_method val_env dummy_method Private self_type)
+ (Ctype.newty (Ttuple []));
+
+ (* Private self is used for private method calls *)
+ let private_self = if final then Ctype.newvar () else self_type in
+
+ (* Self binder *)
+ let (pat, meths, vars, val_env, meth_env, par_env) =
+ type_self_pattern cl_num private_self val_env met_env par_env spat
+ in
+ let public_self = pat.pat_type in
+
+ (* Check that the binder has a correct type *)
+ let ty =
+ if final then Ctype.newty (Tobject (Ctype.newvar(), ref None))
+ else self_type in
+ begin try Ctype.unify val_env public_self ty with
+ Ctype.Unify _ ->
+ raise(Error(spat.ppat_loc, val_env, Pattern_type_clash public_self))
+ end;
+ let get_methods ty =
+ (fst (Ctype.flatten_fields
+ (Ctype.object_fields (Ctype.expand_head val_env ty)))) in
+ if final then begin
+ (* Copy known information to still empty self_type *)
+ List.iter
+ (fun (lab,kind,ty) ->
+ let k =
+ if Btype.field_kind_repr kind = Fpresent then Public else Private in
+ try Ctype.unify val_env ty
+ (Ctype.filter_method val_env lab k self_type)
+ with _ -> assert false)
+ (get_methods public_self)
+ end;
+
+ (* Typing of class fields *)
+ Typetexp.warning_enter_scope ();
+ let (_, _, _, fields, concr_meths, _, inher, _local_meths, _local_vals) =
+ List.fold_left (class_field self_loc cl_num self_type meths vars)
+ (val_env, meth_env, par_env, [], Concr.empty, Concr.empty, [],
+ Concr.empty, Concr.empty)
+ str
+ in
+ Typetexp.warning_leave_scope ();
+ Ctype.unify val_env self_type (Ctype.newvar ());
+ let sign =
+ {csig_self = public_self;
+ csig_vars = Vars.map (fun (id, mut, vr, ty) -> (mut, vr, ty)) !vars;
+ csig_concr = concr_meths;
+ csig_inher = inher} in
+ let methods = get_methods self_type in
+ let priv_meths =
+ List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind <> Fpresent)
+ methods in
+ if final then begin
+ (* Unify private_self and a copy of self_type. self_type will not
+ be modified after this point *)
+ Ctype.close_object self_type;
+ let mets = virtual_methods {sign with csig_self = self_type} in
+ let vals =
+ Vars.fold
+ (fun name (mut, vr, ty) l -> if vr = Virtual then name :: l else l)
+ sign.csig_vars [] in
+ if mets <> [] || vals <> [] then
+ raise(Error(loc, val_env, Virtual_class(true, final, mets, vals)));
+ let self_methods =
+ List.fold_right
+ (fun (lab,kind,ty) rem ->
+ if lab = dummy_method then
+ (* allow public self and private self to be unified *)
+ match Btype.field_kind_repr kind with
+ Fvar r -> Btype.set_kind r Fabsent; rem
+ | _ -> rem
+ else
+ Ctype.newty(Tfield(lab, Btype.copy_kind kind, ty, rem)))
+ methods (Ctype.newty Tnil) in
+ begin try
+ Ctype.unify val_env private_self
+ (Ctype.newty (Tobject(self_methods, ref None)));
+ Ctype.unify val_env public_self self_type
+ with Ctype.Unify trace -> raise(Error(loc, val_env, Final_self_clash trace))
+ end;
+ end;
+
+ (* Typing of method bodies *)
+ (* if !Clflags.principal then *) begin
+ let ms = !meths in
+ (* Generalize the spine of methods accessed through self *)
+ Meths.iter (fun _ (_,ty) -> Ctype.generalize_spine ty) ms;
+ meths :=
+ Meths.map (fun (id,ty) -> (id, Ctype.generic_instance val_env ty)) ms;
+ (* But keep levels correct on the type of self *)
+ Meths.iter (fun _ (_,ty) -> Ctype.unify val_env ty (Ctype.newvar ())) ms
+ end;
+ let fields = List.map Lazy.force (List.rev fields) in
+ let meths = Meths.map (function (id, ty) -> id) !meths in
+
+ (* Check for private methods made public *)
+ let pub_meths' =
+ List.filter (fun (_,kind,_) -> Btype.field_kind_repr kind = Fpresent)
+ (get_methods public_self) in
+ let names = List.map (fun (x,_,_) -> x) in
+ let l1 = names priv_meths and l2 = names pub_meths' in
+ let added = List.filter (fun x -> List.mem x l1) l2 in
+ if added <> [] then
+ Location.prerr_warning loc (Warnings.Implicit_public_methods added);
+ let sign = if final then sign else
+ {sign with csig_self = Ctype.expand_head val_env public_self} in
+ {
+ cstr_self = pat;
+ cstr_fields = fields;
+ cstr_type = sign;
+ cstr_meths = meths}, sign (* redondant, since already in cstr_type *)
+
+and class_expr cl_num val_env met_env scl =
+ match scl.pcl_desc with
+ Pcl_constr (lid, styl) ->
+ let (path, decl) = Typetexp.find_class val_env scl.pcl_loc lid.txt in
+ if Path.same decl.cty_path unbound_class then
+ raise(Error(scl.pcl_loc, val_env, Unbound_class_2 lid.txt));
+ let tyl = List.map
+ (fun sty -> transl_simple_type val_env false sty)
+ styl
+ in
+ let (params, clty) =
+ Ctype.instance_class decl.cty_params decl.cty_type
+ in
+ let clty' = abbreviate_class_type path params clty in
+ if List.length params <> List.length tyl then
+ raise(Error(scl.pcl_loc, val_env,
+ Parameter_arity_mismatch (lid.txt, List.length params,
+ List.length tyl)));
+ List.iter2
+ (fun cty' ty ->
+ let ty' = cty'.ctyp_type in
+ try Ctype.unify val_env ty' ty with Ctype.Unify trace ->
+ raise(Error(cty'.ctyp_loc, val_env, Parameter_mismatch trace)))
+ tyl params;
+ let cl =
+ rc {cl_desc = Tcl_ident (path, lid, tyl);
+ cl_loc = scl.pcl_loc;
+ cl_type = clty';
+ cl_env = val_env;
+ cl_attributes = scl.pcl_attributes;
+ }
+ in
+ let (vals, meths, concrs) = extract_constraints clty in
+ rc {cl_desc = Tcl_constraint (cl, None, vals, meths, concrs);
+ cl_loc = scl.pcl_loc;
+ cl_type = clty';
+ cl_env = val_env;
+ cl_attributes = []; (* attributes are kept on the inner cl node *)
+ }
+ | Pcl_structure cl_str ->
+ let (desc, ty) =
+ class_structure cl_num false val_env met_env scl.pcl_loc cl_str in
+ rc {cl_desc = Tcl_structure desc;
+ cl_loc = scl.pcl_loc;
+ cl_type = Cty_signature ty;
+ cl_env = val_env;
+ cl_attributes = scl.pcl_attributes;
+ }
+ | Pcl_fun (l, Some default, spat, sbody) ->
+ let loc = default.pexp_loc in
+ let open Ast_helper in
+ let scases = [
+ Exp.case
+ (Pat.construct ~loc
+ (mknoloc (Longident.(Ldot (Lident "*predef*", "Some"))))
+ (Some (Pat.var ~loc (mknoloc "*sth*"))))
+ (Exp.ident ~loc (mknoloc (Longident.Lident "*sth*")));
+
+ Exp.case
+ (Pat.construct ~loc
+ (mknoloc (Longident.(Ldot (Lident "*predef*", "None"))))
+ None)
+ default;
+ ]
+ in
+ let smatch =
+ Exp.match_ ~loc (Exp.ident ~loc (mknoloc (Longident.Lident "*opt*")))
+ scases
+ in
+ let sfun =
+ Cl.fun_ ~loc:scl.pcl_loc
+ l None
+ (Pat.var ~loc (mknoloc "*opt*"))
+ (Cl.let_ ~loc:scl.pcl_loc Nonrecursive [Vb.mk spat smatch] sbody)
+ (* Note: we don't put the '#default' attribute, as it
+ is not detected for class-level let bindings. See #5975.*)
+ in
+ class_expr cl_num val_env met_env sfun
+ | Pcl_fun (l, None, spat, scl') ->
+ if !Clflags.principal then Ctype.begin_def ();
+ let (pat, pv, val_env', met_env) =
+ Typecore.type_class_arg_pattern cl_num val_env met_env l spat
+ in
+ if !Clflags.principal then begin
+ Ctype.end_def ();
+ iter_pattern (fun {pat_type=ty} -> Ctype.generalize_structure ty) pat
+ end;
+ let pv =
+ List.map
+ begin fun (id, id_loc, id', ty) ->
+ let path = Pident id' in
+ (* do not mark the value as being used *)
+ let vd = Env.find_value path val_env' in
+ (id, id_loc,
+ {exp_desc =
+ Texp_ident(path, mknoloc (Longident.Lident (Ident.name id)), vd);
+ exp_loc = Location.none; exp_extra = [];
+ exp_type = Ctype.instance val_env' vd.val_type;
+ exp_attributes = []; (* check *)
+ exp_env = val_env'})
+ end
+ pv
+ in
+ let not_function = function
+ Cty_arrow _ -> false
+ | _ -> true
+ in
+ let partial =
+ Typecore.check_partial val_env pat.pat_type pat.pat_loc
+ [{c_lhs=pat;
+ c_guard=None;
+ c_rhs = (* Dummy expression *)
+ {exp_desc = Texp_constant (Asttypes.Const_int 1);
+ exp_loc = Location.none; exp_extra = [];
+ exp_type = Ctype.none;
+ exp_attributes = [];
+ exp_env = Env.empty }}]
+ in
+ Ctype.raise_nongen_level ();
+ let cl = class_expr cl_num val_env' met_env scl' in
+ Ctype.end_def ();
+ if Btype.is_optional l && not_function cl.cl_type then
+ Location.prerr_warning pat.pat_loc
+ Warnings.Unerasable_optional_argument;
+ rc {cl_desc = Tcl_fun (l, pat, pv, cl, partial);
+ cl_loc = scl.pcl_loc;
+ cl_type = Cty_arrow
+ (l, Ctype.instance_def pat.pat_type, cl.cl_type);
+ cl_env = val_env;
+ cl_attributes = scl.pcl_attributes;
+ }
+ | Pcl_apply (scl', sargs) ->
+ if sargs = [] then
+ Syntaxerr.ill_formed_ast scl.pcl_loc
+ "Function application with no argument.";
+ if !Clflags.principal then Ctype.begin_def ();
+ let cl = class_expr cl_num val_env met_env scl' in
+ if !Clflags.principal then begin
+ Ctype.end_def ();
+ generalize_class_type false cl.cl_type;
+ end;
+ let rec nonopt_labels ls ty_fun =
+ match ty_fun with
+ | Cty_arrow (l, _, ty_res) ->
+ if Btype.is_optional l then nonopt_labels ls ty_res
+ else nonopt_labels (l::ls) ty_res
+ | _ -> ls
+ in
+ let ignore_labels =
+ !Clflags.classic ||
+ let labels = nonopt_labels [] cl.cl_type in
+ List.length labels = List.length sargs &&
+ List.for_all (fun (l,_) -> l = Nolabel) sargs &&
+ List.exists (fun l -> l <> Nolabel) labels &&
+ begin
+ Location.prerr_warning
+ cl.cl_loc
+ (Warnings.Labels_omitted
+ (List.map Printtyp.string_of_label
+ (List.filter ((<>) Nolabel) labels)));
+ true
+ end
+ in
+ let rec type_args args omitted ty_fun ty_fun0 sargs more_sargs =
+ match ty_fun, ty_fun0 with
+ | Cty_arrow (l, ty, ty_fun), Cty_arrow (_, ty0, ty_fun0)
+ when sargs <> [] || more_sargs <> [] ->
+ let name = Btype.label_name l
+ and optional =
+ if Btype.is_optional l then Optional else Required in
+ let sargs, more_sargs, arg =
+ if ignore_labels && not (Btype.is_optional l) then begin
+ match sargs, more_sargs with
+ (l', sarg0)::_, _ ->
+ raise(Error(sarg0.pexp_loc, val_env, Apply_wrong_label l'))
+ | _, (l', sarg0)::more_sargs ->
+ if l <> l' && l' <> Nolabel then
+ raise(Error(sarg0.pexp_loc, val_env,
+ Apply_wrong_label l'))
+ else ([], more_sargs,
+ Some (type_argument val_env sarg0 ty ty0))
+ | _ ->
+ assert false
+ end else try
+ let (l', sarg0, sargs, more_sargs) =
+ try
+ let (l', sarg0, sargs1, sargs2) =
+ Btype.extract_label name sargs
+ in (l', sarg0, sargs1 @ sargs2, more_sargs)
+ with Not_found ->
+ let (l', sarg0, sargs1, sargs2) =
+ Btype.extract_label name more_sargs
+ in (l', sarg0, sargs @ sargs1, sargs2)
+ in
+ if optional = Required && Btype.is_optional l' then
+ Location.prerr_warning sarg0.pexp_loc
+ (Warnings.Nonoptional_label (Printtyp.string_of_label l));
+ sargs, more_sargs,
+ if optional = Required || Btype.is_optional l' then
+ Some (type_argument val_env sarg0 ty ty0)
+ else
+ let ty' = extract_option_type val_env ty
+ and ty0' = extract_option_type val_env ty0 in
+ let arg = type_argument val_env sarg0 ty' ty0' in
+ Some (option_some arg)
+ with Not_found ->
+ sargs, more_sargs,
+ if Btype.is_optional l
+ && (List.mem_assoc Nolabel sargs
+ || List.mem_assoc Nolabel more_sargs)
+ then
+ Some (option_none ty0 Location.none)
+ else None
+ in
+ let omitted = if arg = None then (l,ty0) :: omitted else omitted in
+ type_args ((l,arg,optional)::args) omitted ty_fun ty_fun0
+ sargs more_sargs
+ | _ ->
+ match sargs @ more_sargs with
+ (l, sarg0)::_ ->
+ if omitted <> [] then
+ raise(Error(sarg0.pexp_loc, val_env, Apply_wrong_label l))
+ else
+ raise(Error(cl.cl_loc, val_env, Cannot_apply cl.cl_type))
+ | [] ->
+ (List.rev args,
+ List.fold_left
+ (fun ty_fun (l,ty) -> Cty_arrow(l,ty,ty_fun))
+ ty_fun0 omitted)
+ in
+ let (args, cty) =
+ let (_, ty_fun0) = Ctype.instance_class [] cl.cl_type in
+ if ignore_labels then
+ type_args [] [] cl.cl_type ty_fun0 [] sargs
+ else
+ type_args [] [] cl.cl_type ty_fun0 sargs []
+ in
+ rc {cl_desc = Tcl_apply (cl, args);
+ cl_loc = scl.pcl_loc;
+ cl_type = cty;
+ cl_env = val_env;
+ cl_attributes = scl.pcl_attributes;
+ }
+ | Pcl_let (rec_flag, sdefs, scl') ->
+ let (defs, val_env) =
+ try
+ Typecore.type_let val_env rec_flag sdefs None
+ with Ctype.Unify [(ty, _)] ->
+ raise(Error(scl.pcl_loc, val_env, Make_nongen_seltype ty))
+ in
+ let (vals, met_env) =
+ List.fold_right
+ (fun (id, id_loc) (vals, met_env) ->
+ let path = Pident id in
+ (* do not mark the value as used *)
+ let vd = Env.find_value path val_env in
+ Ctype.begin_def ();
+ let expr =
+ {exp_desc =
+ Texp_ident(path, mknoloc(Longident.Lident (Ident.name id)),vd);
+ exp_loc = Location.none; exp_extra = [];
+ exp_type = Ctype.instance val_env vd.val_type;
+ exp_attributes = [];
+ exp_env = val_env;
+ }
+ in
+ Ctype.end_def ();
+ Ctype.generalize expr.exp_type;
+ let desc =
+ {val_type = expr.exp_type; val_kind = Val_ivar (Immutable,
+ cl_num);
+ val_attributes = [];
+ Types.val_loc = vd.Types.val_loc;
+ }
+ in
+ let id' = Ident.create (Ident.name id) in
+ ((id', id_loc, expr)
+ :: vals,
+ Env.add_value id' desc met_env))
+ (let_bound_idents_with_loc defs)
+ ([], met_env)
+ in
+ let cl = class_expr cl_num val_env met_env scl' in
+ rc {cl_desc = Tcl_let (rec_flag, defs, vals, cl);
+ cl_loc = scl.pcl_loc;
+ cl_type = cl.cl_type;
+ cl_env = val_env;
+ cl_attributes = scl.pcl_attributes;
+ }
+ | Pcl_constraint (scl', scty) ->
+ Ctype.begin_class_def ();
+ let context = Typetexp.narrow () in
+ let cl = class_expr cl_num val_env met_env scl' in
+ Typetexp.widen context;
+ let context = Typetexp.narrow () in
+ let clty = class_type val_env scty in
+ Typetexp.widen context;
+ Ctype.end_def ();
+
+ limited_generalize (Ctype.row_variable (Ctype.self_type cl.cl_type))
+ cl.cl_type;
+ limited_generalize (Ctype.row_variable (Ctype.self_type clty.cltyp_type))
+ clty.cltyp_type;
+
+ begin match
+ Includeclass.class_types val_env cl.cl_type clty.cltyp_type
+ with
+ [] -> ()
+ | error -> raise(Error(cl.cl_loc, val_env, Class_match_failure error))
+ end;
+ let (vals, meths, concrs) = extract_constraints clty.cltyp_type in
+ rc {cl_desc = Tcl_constraint (cl, Some clty, vals, meths, concrs);
+ cl_loc = scl.pcl_loc;
+ cl_type = snd (Ctype.instance_class [] clty.cltyp_type);
+ cl_env = val_env;
+ cl_attributes = scl.pcl_attributes;
+ }
+ | Pcl_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+(*******************************)
+
+(* Approximate the type of the constructor to allow recursive use *)
+(* of optional parameters *)
+
+let var_option = Predef.type_option (Btype.newgenvar ())
+
+let rec approx_declaration cl =
+ match cl.pcl_desc with
+ Pcl_fun (l, _, _, cl) ->
+ let arg =
+ if Btype.is_optional l then Ctype.instance_def var_option
+ else Ctype.newvar () in
+ Ctype.newty (Tarrow (l, arg, approx_declaration cl, Cok))
+ | Pcl_let (_, _, cl) ->
+ approx_declaration cl
+ | Pcl_constraint (cl, _) ->
+ approx_declaration cl
+ | _ -> Ctype.newvar ()
+
+let rec approx_description ct =
+ match ct.pcty_desc with
+ Pcty_arrow (l, _, ct) ->
+ let arg =
+ if Btype.is_optional l then Ctype.instance_def var_option
+ else Ctype.newvar () in
+ Ctype.newty (Tarrow (l, arg, approx_description ct, Cok))
+ | _ -> Ctype.newvar ()
+
+(*******************************)
+
+let temp_abbrev loc env id arity =
+ let params = ref [] in
+ for _i = 1 to arity do
+ params := Ctype.newvar () :: !params
+ done;
+ let ty = Ctype.newobj (Ctype.newvar ()) in
+ let env =
+ Env.add_type ~check:true id
+ {type_params = !params;
+ type_arity = arity;
+ type_kind = Type_abstract;
+ type_private = Public;
+ type_manifest = Some ty;
+ type_variance = Misc.replicate_list Variance.full arity;
+ type_newtype_level = None;
+ type_loc = loc;
+ type_attributes = []; (* or keep attrs from the class decl? *)
+ }
+ env
+ in
+ (!params, ty, env)
+
+let initial_env define_class approx
+ (res, env) (cl, id, ty_id, obj_id, cl_id) =
+ (* Temporary abbreviations *)
+ let arity = List.length cl.pci_params in
+ let (obj_params, obj_ty, env) = temp_abbrev cl.pci_loc env obj_id arity in
+ let (cl_params, cl_ty, env) = temp_abbrev cl.pci_loc env cl_id arity in
+
+ (* Temporary type for the class constructor *)
+ let constr_type = approx cl.pci_expr in
+ if !Clflags.principal then Ctype.generalize_spine constr_type;
+ let dummy_cty =
+ Cty_signature
+ { csig_self = Ctype.newvar ();
+ csig_vars = Vars.empty;
+ csig_concr = Concr.empty;
+ csig_inher = [] }
+ in
+ let dummy_class =
+ {Types.cty_params = []; (* Dummy value *)
+ cty_variance = [];
+ cty_type = dummy_cty; (* Dummy value *)
+ cty_path = unbound_class;
+ cty_new =
+ begin match cl.pci_virt with
+ | Virtual -> None
+ | Concrete -> Some constr_type
+ end;
+ cty_loc = Location.none;
+ cty_attributes = [];
+ }
+ in
+ let env =
+ Env.add_cltype ty_id
+ {clty_params = []; (* Dummy value *)
+ clty_variance = [];
+ clty_type = dummy_cty; (* Dummy value *)
+ clty_path = unbound_class;
+ clty_loc = Location.none;
+ clty_attributes = [];
+ }
+ (
+ if define_class then
+ Env.add_class id dummy_class env
+ else
+ env
+ )
+ in
+ ((cl, id, ty_id,
+ obj_id, obj_params, obj_ty,
+ cl_id, cl_params, cl_ty,
+ constr_type, dummy_class)::res,
+ env)
+
+let class_infos define_class kind
+ (cl, id, ty_id,
+ obj_id, obj_params, obj_ty,
+ cl_id, cl_params, cl_ty,
+ constr_type, dummy_class)
+ (res, env) =
+
+ reset_type_variables ();
+ Ctype.begin_class_def ();
+
+ (* Introduce class parameters *)
+ let ci_params =
+ let make_param (sty, v) =
+ try
+ (transl_type_param env sty, v)
+ with Already_bound ->
+ raise(Error(sty.ptyp_loc, env, Repeated_parameter))
+ in
+ List.map make_param cl.pci_params
+ in
+ let params = List.map (fun (cty, _) -> cty.ctyp_type) ci_params in
+
+ (* Allow self coercions (only for class declarations) *)
+ let coercion_locs = ref [] in
+
+ (* Type the class expression *)
+ let (expr, typ) =
+ try
+ Typecore.self_coercion :=
+ (Path.Pident obj_id, coercion_locs) :: !Typecore.self_coercion;
+ let res = kind env cl.pci_expr in
+ Typecore.self_coercion := List.tl !Typecore.self_coercion;
+ res
+ with exn ->
+ Typecore.self_coercion := []; raise exn
+ in
+
+ Ctype.end_def ();
+
+ let sty = Ctype.self_type typ in
+
+ (* First generalize the type of the dummy method (cf PR#6123) *)
+ let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sty) in
+ List.iter (fun (met, _, ty) -> if met = dummy_method then Ctype.generalize ty)
+ fields;
+ (* Generalize the row variable *)
+ let rv = Ctype.row_variable sty in
+ List.iter (Ctype.limited_generalize rv) params;
+ limited_generalize rv typ;
+
+ (* Check the abbreviation for the object type *)
+ let (obj_params', obj_type) = Ctype.instance_class params typ in
+ let constr = Ctype.newconstr (Path.Pident obj_id) obj_params in
+ begin
+ let ty = Ctype.self_type obj_type in
+ Ctype.hide_private_methods ty;
+ Ctype.close_object ty;
+ begin try
+ List.iter2 (Ctype.unify env) obj_params obj_params'
+ with Ctype.Unify _ ->
+ raise(Error(cl.pci_loc, env,
+ Bad_parameters (obj_id, constr,
+ Ctype.newconstr (Path.Pident obj_id)
+ obj_params')))
+ end;
+ begin try
+ Ctype.unify env ty constr
+ with Ctype.Unify _ ->
+ raise(Error(cl.pci_loc, env,
+ Abbrev_type_clash (constr, ty, Ctype.expand_head env constr)))
+ end
+ end;
+
+ (* Check the other temporary abbreviation (#-type) *)
+ begin
+ let (cl_params', cl_type) = Ctype.instance_class params typ in
+ let ty = Ctype.self_type cl_type in
+ Ctype.hide_private_methods ty;
+ Ctype.set_object_name obj_id (Ctype.row_variable ty) cl_params ty;
+ begin try
+ List.iter2 (Ctype.unify env) cl_params cl_params'
+ with Ctype.Unify _ ->
+ raise(Error(cl.pci_loc, env,
+ Bad_parameters (cl_id,
+ Ctype.newconstr (Path.Pident cl_id)
+ cl_params,
+ Ctype.newconstr (Path.Pident cl_id)
+ cl_params')))
+ end;
+ begin try
+ Ctype.unify env ty cl_ty
+ with Ctype.Unify _ ->
+ let constr = Ctype.newconstr (Path.Pident cl_id) params in
+ raise(Error(cl.pci_loc, env, Abbrev_type_clash (constr, ty, cl_ty)))
+ end
+ end;
+
+ (* Type of the class constructor *)
+ begin try
+ Ctype.unify env
+ (constructor_type constr obj_type)
+ (Ctype.instance env constr_type)
+ with Ctype.Unify trace ->
+ raise(Error(cl.pci_loc, env,
+ Constructor_type_mismatch (cl.pci_name.txt, trace)))
+ end;
+
+ (* Class and class type temporary definitions *)
+ let cty_variance = List.map (fun _ -> Variance.full) params in
+ let cltydef =
+ {clty_params = params; clty_type = class_body typ;
+ clty_variance = cty_variance;
+ clty_path = Path.Pident obj_id;
+ clty_loc = cl.pci_loc;
+ clty_attributes = cl.pci_attributes;
+ }
+ and clty =
+ {cty_params = params; cty_type = typ;
+ cty_variance = cty_variance;
+ cty_path = Path.Pident obj_id;
+ cty_new =
+ begin match cl.pci_virt with
+ | Virtual -> None
+ | Concrete -> Some constr_type
+ end;
+ cty_loc = cl.pci_loc;
+ cty_attributes = cl.pci_attributes;
+ }
+ in
+ dummy_class.cty_type <- typ;
+ let env =
+ Env.add_cltype ty_id cltydef (
+ if define_class then Env.add_class id clty env else env)
+ in
+
+ if cl.pci_virt = Concrete then begin
+ let sign = Ctype.signature_of_class_type typ in
+ let mets = virtual_methods sign in
+ let vals =
+ Vars.fold
+ (fun name (mut, vr, ty) l -> if vr = Virtual then name :: l else l)
+ sign.csig_vars [] in
+ if mets <> [] || vals <> [] then
+ raise(Error(cl.pci_loc, env, Virtual_class(define_class, false, mets,
+ vals)));
+ end;
+
+ (* Misc. *)
+ let arity = Ctype.class_type_arity typ in
+ let pub_meths =
+ let (fields, _) =
+ Ctype.flatten_fields (Ctype.object_fields (Ctype.expand_head env obj_ty))
+ in
+ List.map (function (lab, _, _) -> lab) fields
+ in
+
+ (* Final definitions *)
+ let (params', typ') = Ctype.instance_class params typ in
+ let cltydef =
+ {clty_params = params'; clty_type = class_body typ';
+ clty_variance = cty_variance;
+ clty_path = Path.Pident obj_id;
+ clty_loc = cl.pci_loc;
+ clty_attributes = cl.pci_attributes;
+ }
+ and clty =
+ {cty_params = params'; cty_type = typ';
+ cty_variance = cty_variance;
+ cty_path = Path.Pident obj_id;
+ cty_new =
+ begin match cl.pci_virt with
+ | Virtual -> None
+ | Concrete -> Some (Ctype.instance env constr_type)
+ end;
+ cty_loc = cl.pci_loc;
+ cty_attributes = cl.pci_attributes;
+ }
+ in
+ let obj_abbr =
+ {type_params = obj_params;
+ type_arity = List.length obj_params;
+ type_kind = Type_abstract;
+ type_private = Public;
+ type_manifest = Some obj_ty;
+ type_variance = List.map (fun _ -> Variance.full) obj_params;
+ type_newtype_level = None;
+ type_loc = cl.pci_loc;
+ type_attributes = []; (* or keep attrs from cl? *)
+ }
+ in
+ let (cl_params, cl_ty) =
+ Ctype.instance_parameterized_type params (Ctype.self_type typ)
+ in
+ Ctype.hide_private_methods cl_ty;
+ Ctype.set_object_name obj_id (Ctype.row_variable cl_ty) cl_params cl_ty;
+ let cl_abbr =
+ {type_params = cl_params;
+ type_arity = List.length cl_params;
+ type_kind = Type_abstract;
+ type_private = Public;
+ type_manifest = Some cl_ty;
+ type_variance = List.map (fun _ -> Variance.full) cl_params;
+ type_newtype_level = None;
+ type_loc = cl.pci_loc;
+ type_attributes = []; (* or keep attrs from cl? *)
+ }
+ in
+ ((cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, ci_params,
+ arity, pub_meths, List.rev !coercion_locs, expr) :: res,
+ env)
+
+let final_decl env define_class
+ (cl, id, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, ci_params,
+ arity, pub_meths, coe, expr) =
+
+ begin try Ctype.collapse_conj_params env clty.cty_params
+ with Ctype.Unify trace ->
+ raise(Error(cl.pci_loc, env, Non_collapsable_conjunction (id, clty, trace)))
+ end;
+
+ List.iter Ctype.generalize clty.cty_params;
+ generalize_class_type true clty.cty_type;
+ Misc.may Ctype.generalize clty.cty_new;
+ List.iter Ctype.generalize obj_abbr.type_params;
+ Misc.may Ctype.generalize obj_abbr.type_manifest;
+ List.iter Ctype.generalize cl_abbr.type_params;
+ Misc.may Ctype.generalize cl_abbr.type_manifest;
+
+ if not (closed_class clty) then
+ raise(Error(cl.pci_loc, env, Non_generalizable_class (id, clty)));
+
+ begin match
+ Ctype.closed_class clty.cty_params
+ (Ctype.signature_of_class_type clty.cty_type)
+ with
+ None -> ()
+ | Some reason ->
+ let printer =
+ if define_class
+ then function ppf -> Printtyp.class_declaration id ppf clty
+ else function ppf -> Printtyp.cltype_declaration id ppf cltydef
+ in
+ raise(Error(cl.pci_loc, env, Unbound_type_var(printer, reason)))
+ end;
+
+ (id, cl.pci_name, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr,
+ arity, pub_meths, coe, expr,
+ { ci_loc = cl.pci_loc;
+ ci_virt = cl.pci_virt;
+ ci_params = ci_params;
+(* TODO : check that we have the correct use of identifiers *)
+ ci_id_name = cl.pci_name;
+ ci_id_class = id;
+ ci_id_class_type = ty_id;
+ ci_id_object = obj_id;
+ ci_id_typesharp = cl_id;
+ ci_expr = expr;
+ ci_decl = clty;
+ ci_type_decl = cltydef;
+ ci_attributes = cl.pci_attributes;
+ })
+(* (cl.pci_variance, cl.pci_loc)) *)
+
+let extract_type_decls
+ (id, id_loc, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr,
+ arity, pub_meths, coe, expr, required) decls =
+ (obj_id, obj_abbr, cl_abbr, clty, cltydef, required) :: decls
+
+let merge_type_decls
+ (id, id_loc, _clty, ty_id, _cltydef, obj_id, _obj_abbr, cl_id, _cl_abbr,
+ arity, pub_meths, coe, expr, req) (obj_abbr, cl_abbr, clty, cltydef) =
+ (id, id_loc, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr,
+ arity, pub_meths, coe, expr, req)
+
+let final_env define_class env
+ (id, id_loc, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr,
+ arity, pub_meths, coe, expr, req) =
+ (* Add definitions after cleaning them *)
+ Env.add_type ~check:true obj_id
+ (Subst.type_declaration Subst.identity obj_abbr) (
+ Env.add_type ~check:true cl_id
+ (Subst.type_declaration Subst.identity cl_abbr) (
+ Env.add_cltype ty_id (Subst.cltype_declaration Subst.identity cltydef) (
+ if define_class then
+ Env.add_class id (Subst.class_declaration Subst.identity clty) env
+ else env)))
+
+(* Check that #c is coercible to c if there is a self-coercion *)
+let check_coercions env
+ (id, id_loc, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr,
+ arity, pub_meths, coercion_locs, expr, req) =
+ begin match coercion_locs with [] -> ()
+ | loc :: _ ->
+ let cl_ty, obj_ty =
+ match cl_abbr.type_manifest, obj_abbr.type_manifest with
+ Some cl_ab, Some obj_ab ->
+ let cl_params, cl_ty =
+ Ctype.instance_parameterized_type cl_abbr.type_params cl_ab
+ and obj_params, obj_ty =
+ Ctype.instance_parameterized_type obj_abbr.type_params obj_ab
+ in
+ List.iter2 (Ctype.unify env) cl_params obj_params;
+ cl_ty, obj_ty
+ | _ -> assert false
+ in
+ begin try Ctype.subtype env cl_ty obj_ty ()
+ with Ctype.Subtype (tr1, tr2) ->
+ raise(Typecore.Error(loc, env, Typecore.Not_subtype(tr1, tr2)))
+ end;
+ if not (Ctype.opened_object cl_ty) then
+ raise(Error(loc, env, Cannot_coerce_self obj_ty))
+ end;
+ (id, id_loc, clty, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr,
+ arity, pub_meths, req)
+
+(*******************************)
+
+let type_classes define_class approx kind env cls =
+ let cls =
+ List.map
+ (function cl ->
+ (cl,
+ Ident.create cl.pci_name.txt, Ident.create cl.pci_name.txt,
+ Ident.create cl.pci_name.txt, Ident.create ("#" ^ cl.pci_name.txt)))
+ cls
+ in
+ Ctype.init_def (Ident.current_time ());
+ Ctype.begin_class_def ();
+ let (res, env) =
+ List.fold_left (initial_env define_class approx) ([], env) cls
+ in
+ let (res, env) =
+ List.fold_right (class_infos define_class kind) res ([], env)
+ in
+ Ctype.end_def ();
+ let res = List.rev_map (final_decl env define_class) res in
+ let decls = List.fold_right extract_type_decls res [] in
+ let decls = Typedecl.compute_variance_decls env decls in
+ let res = List.map2 merge_type_decls res decls in
+ let env = List.fold_left (final_env define_class) env res in
+ let res = List.map (check_coercions env) res in
+ (res, env)
+
+let class_num = ref 0
+let class_declaration env sexpr =
+ incr class_num;
+ let expr = class_expr (string_of_int !class_num) env env sexpr in
+ (expr, expr.cl_type)
+
+let class_description env sexpr =
+ let expr = class_type env sexpr in
+ (expr, expr.cltyp_type)
+
+let class_declarations env cls =
+ type_classes true approx_declaration class_declaration env cls
+
+let class_descriptions env cls =
+ type_classes true approx_description class_description env cls
+
+let class_type_declarations env cls =
+ let (decl, env) =
+ type_classes false approx_description class_description env cls
+ in
+ (List.map
+ (function
+ (_, id_loc, _, ty_id, cltydef, obj_id, obj_abbr, cl_id, cl_abbr,
+ _, _, ci) ->
+ (ty_id, id_loc, cltydef, obj_id, obj_abbr, cl_id, cl_abbr, ci))
+ decl,
+ env)
+
+let rec unify_parents env ty cl =
+ match cl.cl_desc with
+ Tcl_ident (p, _, _) ->
+ begin try
+ let decl = Env.find_class p env in
+ let _, body = Ctype.find_cltype_for_path env decl.cty_path in
+ Ctype.unify env ty (Ctype.instance env body)
+ with
+ Not_found -> ()
+ | exn -> assert false
+ end
+ | Tcl_structure st -> unify_parents_struct env ty st
+ | Tcl_fun (_, _, _, cl, _)
+ | Tcl_apply (cl, _)
+ | Tcl_let (_, _, _, cl)
+ | Tcl_constraint (cl, _, _, _, _) -> unify_parents env ty cl
+and unify_parents_struct env ty st =
+ List.iter
+ (function
+ | {cf_desc = Tcf_inherit (_, cl, _, _, _)} ->
+ unify_parents env ty cl
+ | _ -> ())
+ st.cstr_fields
+
+let type_object env loc s =
+ incr class_num;
+ let (desc, sign) =
+ class_structure (string_of_int !class_num) true env env loc s in
+ let sty = Ctype.expand_head env sign.csig_self in
+ Ctype.hide_private_methods sty;
+ let (fields, _) = Ctype.flatten_fields (Ctype.object_fields sty) in
+ let meths = List.map (fun (s,_,_) -> s) fields in
+ unify_parents_struct env sign.csig_self desc;
+ (desc, sign, meths)
+
+let () =
+ Typecore.type_object := type_object
+
+(*******************************)
+
+(* Approximate the class declaration as class ['params] id = object end *)
+let approx_class sdecl =
+ let open Ast_helper in
+ let self' = Typ.any () in
+ let clty' = Cty.signature ~loc:sdecl.pci_expr.pcty_loc (Csig.mk self' []) in
+ { sdecl with pci_expr = clty' }
+
+let approx_class_declarations env sdecls =
+ fst (class_type_declarations env (List.map approx_class sdecls))
+
+(*******************************)
+
+(* Error report *)
+
+open Format
+
+let report_error env ppf = function
+ | Repeated_parameter ->
+ fprintf ppf "A type parameter occurs several times"
+ | Unconsistent_constraint trace ->
+ fprintf ppf "The class constraints are not consistent.@.";
+ Printtyp.report_unification_error ppf env trace
+ (fun ppf -> fprintf ppf "Type")
+ (fun ppf -> fprintf ppf "is not compatible with type")
+ | Field_type_mismatch (k, m, trace) ->
+ Printtyp.report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "The %s %s@ has type" k m)
+ (function ppf ->
+ fprintf ppf "but is expected to have type")
+ | Structure_expected clty ->
+ fprintf ppf
+ "@[This class expression is not a class structure; it has type@ %a@]"
+ Printtyp.class_type clty
+ | Cannot_apply clty ->
+ fprintf ppf
+ "This class expression is not a class function, it cannot be applied"
+ | Apply_wrong_label l ->
+ let mark_label = function
+ | Nolabel -> "out label"
+ | l -> sprintf " label %s" (Btype.prefixed_label_name l) in
+ fprintf ppf "This argument cannot be applied with%s" (mark_label l)
+ | Pattern_type_clash ty ->
+ (* XXX Trace *)
+ (* XXX Revoir message d'erreur *)
+ Printtyp.reset_and_mark_loops ty;
+ fprintf ppf "@[%s@ %a@]"
+ "This pattern cannot match self: it only matches values of type"
+ Printtyp.type_expr ty
+ | Unbound_class_2 cl ->
+ fprintf ppf "@[The class@ %a@ is not yet completely defined@]"
+ Printtyp.longident cl
+ | Unbound_class_type_2 cl ->
+ fprintf ppf "@[The class type@ %a@ is not yet completely defined@]"
+ Printtyp.longident cl
+ | Abbrev_type_clash (abbrev, actual, expected) ->
+ (* XXX Afficher une trace ? *)
+ Printtyp.reset_and_mark_loops_list [abbrev; actual; expected];
+ fprintf ppf "@[The abbreviation@ %a@ expands to type@ %a@ \
+ but is used with type@ %a@]"
+ Printtyp.type_expr abbrev
+ Printtyp.type_expr actual
+ Printtyp.type_expr expected
+ | Constructor_type_mismatch (c, trace) ->
+ Printtyp.report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "The expression \"new %s\" has type" c)
+ (function ppf ->
+ fprintf ppf "but is used with type")
+ | Virtual_class (cl, imm, mets, vals) ->
+ let print_mets ppf mets =
+ List.iter (function met -> fprintf ppf "@ %s" met) mets in
+ let missings =
+ match mets, vals with
+ [], _ -> "variables"
+ | _, [] -> "methods"
+ | _ -> "methods and variables"
+ in
+ let print_msg ppf =
+ if imm then fprintf ppf "This object has virtual %s" missings
+ else if cl then fprintf ppf "This class should be virtual"
+ else fprintf ppf "This class type should be virtual"
+ in
+ fprintf ppf
+ "@[%t.@ @[<2>The following %s are undefined :%a@]@]"
+ print_msg missings print_mets (mets @ vals)
+ | Parameter_arity_mismatch(lid, expected, provided) ->
+ fprintf ppf
+ "@[The class constructor %a@ expects %i type argument(s),@ \
+ but is here applied to %i type argument(s)@]"
+ Printtyp.longident lid expected provided
+ | Parameter_mismatch trace ->
+ Printtyp.report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "The type parameter")
+ (function ppf ->
+ fprintf ppf "does not meet its constraint: it should be")
+ | Bad_parameters (id, params, cstrs) ->
+ Printtyp.reset_and_mark_loops_list [params; cstrs];
+ fprintf ppf
+ "@[The abbreviation %a@ is used with parameters@ %a@ \
+ wich are incompatible with constraints@ %a@]"
+ Printtyp.ident id Printtyp.type_expr params Printtyp.type_expr cstrs
+ | Class_match_failure error ->
+ Includeclass.report_error ppf error
+ | Unbound_val lab ->
+ fprintf ppf "Unbound instance variable %s" lab
+ | Unbound_type_var (printer, reason) ->
+ let print_common ppf kind ty0 real lab ty =
+ let ty1 =
+ if real then ty0 else Btype.newgenty(Tobject(ty0, ref None)) in
+ Printtyp.mark_loops ty1;
+ fprintf ppf
+ "The %s %s@ has type@;<1 2>%a@ where@ %a@ is unbound"
+ kind lab Printtyp.type_expr ty Printtyp.type_expr ty0
+ in
+ let print_reason ppf = function
+ | Ctype.CC_Method (ty0, real, lab, ty) ->
+ print_common ppf "method" ty0 real lab ty
+ | Ctype.CC_Value (ty0, real, lab, ty) ->
+ print_common ppf "instance variable" ty0 real lab ty
+ in
+ Printtyp.reset ();
+ fprintf ppf
+ "@[<v>@[Some type variables are unbound in this type:@;<1 2>%t@]@ \
+ @[%a@]@]"
+ printer print_reason reason
+ | Make_nongen_seltype ty ->
+ fprintf ppf
+ "@[<v>@[Self type should not occur in the non-generic type@;<1 2>\
+ %a@]@,\
+ It would escape the scope of its class@]"
+ Printtyp.type_scheme ty
+ | Non_generalizable_class (id, clty) ->
+ fprintf ppf
+ "@[The type of this class,@ %a,@ \
+ contains type variables that cannot be generalized@]"
+ (Printtyp.class_declaration id) clty
+ | Cannot_coerce_self ty ->
+ fprintf ppf
+ "@[The type of self cannot be coerced to@ \
+ the type of the current class:@ %a.@.\
+ Some occurrences are contravariant@]"
+ Printtyp.type_scheme ty
+ | Non_collapsable_conjunction (id, clty, trace) ->
+ fprintf ppf
+ "@[The type of this class,@ %a,@ \
+ contains non-collapsible conjunctive types in constraints@]"
+ (Printtyp.class_declaration id) clty;
+ Printtyp.report_unification_error ppf env trace
+ (fun ppf -> fprintf ppf "Type")
+ (fun ppf -> fprintf ppf "is not compatible with type")
+ | Final_self_clash trace ->
+ Printtyp.report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "This object is expected to have type")
+ (function ppf ->
+ fprintf ppf "but actually has type")
+ | Mutability_mismatch (lab, mut) ->
+ let mut1, mut2 =
+ if mut = Immutable then "mutable", "immutable"
+ else "immutable", "mutable" in
+ fprintf ppf
+ "@[The instance variable is %s;@ it cannot be redefined as %s@]"
+ mut1 mut2
+ | No_overriding (_, "") ->
+ fprintf ppf "@[This inheritance does not override any method@ %s@]"
+ "instance variable"
+ | No_overriding (kind, name) ->
+ fprintf ppf "@[The %s `%s'@ has no previous definition@]" kind name
+ | Duplicate (kind, name) ->
+ fprintf ppf "@[The %s `%s'@ has multiple definitions in this object@]"
+ kind name
+
+let report_error env ppf err =
+ Printtyp.wrap_printing_env env (fun () -> report_error env ppf err)
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, env, err) ->
+ Some (Location.error_of_printer loc (report_error env) err)
+ | Error_forward err ->
+ Some err
+ | _ ->
+ None
+ )
diff --git a/typing/typeclass.mli b/typing/typeclass.mli
new file mode 100644
index 0000000000..d213221a84
--- /dev/null
+++ b/typing/typeclass.mli
@@ -0,0 +1,111 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Asttypes
+open Types
+open Format
+
+val class_declarations:
+ Env.t -> Parsetree.class_declaration list ->
+ (Ident.t * string loc * class_declaration *
+ Ident.t * class_type_declaration *
+ Ident.t * type_declaration *
+ Ident.t * type_declaration *
+ int * string list * Typedtree.class_declaration) list * Env.t
+
+(*
+and class_declaration =
+ (class_expr, Types.class_declaration) class_infos
+*)
+
+val class_descriptions:
+ Env.t -> Parsetree.class_description list ->
+ (Ident.t * string loc * class_declaration *
+ Ident.t * class_type_declaration *
+ Ident.t * type_declaration *
+ Ident.t * type_declaration *
+ int * string list * Typedtree.class_description) list * Env.t
+
+(*
+and class_description =
+ (class_type, unit) class_infos
+*)
+
+val class_type_declarations:
+ Env.t -> Parsetree.class_description list ->
+ (Ident.t * string loc * class_type_declaration *
+ Ident.t * type_declaration *
+ Ident.t * type_declaration *
+ Typedtree.class_type_declaration) list * Env.t
+
+(*
+and class_type_declaration =
+ (class_type, Types.class_type_declaration) class_infos
+*)
+
+val approx_class_declarations:
+ Env.t -> Parsetree.class_description list ->
+ (Ident.t * string loc * class_type_declaration *
+ Ident.t * type_declaration *
+ Ident.t * type_declaration *
+ Typedtree.class_type_declaration) list
+
+val virtual_methods: Types.class_signature -> label list
+
+(*
+val type_classes :
+ bool ->
+ ('a -> Types.type_expr) ->
+ (Env.t -> 'a -> 'b * Types.class_type) ->
+ Env.t ->
+ 'a Parsetree.class_infos list ->
+ ( Ident.t * Types.class_declaration *
+ Ident.t * Types.class_type_declaration *
+ Ident.t * Types.type_declaration *
+ Ident.t * Types.type_declaration *
+ int * string list * 'b * 'b Typedtree.class_infos)
+ list * Env.t
+*)
+
+type error =
+ Unconsistent_constraint of (type_expr * type_expr) list
+ | Field_type_mismatch of string * string * (type_expr * type_expr) list
+ | Structure_expected of class_type
+ | Cannot_apply of class_type
+ | Apply_wrong_label of arg_label
+ | Pattern_type_clash of type_expr
+ | Repeated_parameter
+ | Unbound_class_2 of Longident.t
+ | Unbound_class_type_2 of Longident.t
+ | Abbrev_type_clash of type_expr * type_expr * type_expr
+ | Constructor_type_mismatch of string * (type_expr * type_expr) list
+ | Virtual_class of bool * bool * string list * string list
+ | Parameter_arity_mismatch of Longident.t * int * int
+ | Parameter_mismatch of (type_expr * type_expr) list
+ | Bad_parameters of Ident.t * type_expr * type_expr
+ | Class_match_failure of Ctype.class_match_failure list
+ | Unbound_val of string
+ | Unbound_type_var of (formatter -> unit) * Ctype.closed_class_failure
+ | Make_nongen_seltype of type_expr
+ | Non_generalizable_class of Ident.t * Types.class_declaration
+ | Cannot_coerce_self of type_expr
+ | Non_collapsable_conjunction of
+ Ident.t * Types.class_declaration * (type_expr * type_expr) list
+ | Final_self_clash of (type_expr * type_expr) list
+ | Mutability_mismatch of string * mutable_flag
+ | No_overriding of string * string
+ | Duplicate of string * string
+
+exception Error of Location.t * Env.t * error
+exception Error_forward of Location.error
+
+val report_error : Env.t -> formatter -> error -> unit
diff --git a/typing/typecore.ml b/typing/typecore.ml
new file mode 100644
index 0000000000..516c10f70c
--- /dev/null
+++ b/typing/typecore.ml
@@ -0,0 +1,4120 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Typechecking for the core language *)
+
+open Misc
+open Asttypes
+open Parsetree
+open Types
+open Typedtree
+open Btype
+open Ctype
+
+type error =
+ Polymorphic_label of Longident.t
+ | Constructor_arity_mismatch of Longident.t * int * int
+ | Label_mismatch of Longident.t * (type_expr * type_expr) list
+ | Pattern_type_clash of (type_expr * type_expr) list
+ | Or_pattern_type_clash of Ident.t * (type_expr * type_expr) list
+ | Multiply_bound_variable of string
+ | Orpat_vars of Ident.t * Ident.t list
+ | Expr_type_clash of (type_expr * type_expr) list
+ | Apply_non_function of type_expr
+ | Apply_wrong_label of arg_label * type_expr
+ | Label_multiply_defined of string
+ | Label_missing of Ident.t list
+ | Label_not_mutable of Longident.t
+ | Wrong_name of string * type_expr * string * Path.t * string * string list
+ | Name_type_mismatch of
+ string * Longident.t * (Path.t * Path.t) * (Path.t * Path.t) list
+ | Invalid_format of string
+ | Undefined_method of type_expr * string * string list option
+ | Undefined_inherited_method of string * string list
+ | Virtual_class of Longident.t
+ | Private_type of type_expr
+ | Private_label of Longident.t * type_expr
+ | Unbound_instance_variable of string * string list
+ | Instance_variable_not_mutable of bool * string
+ | Not_subtype of (type_expr * type_expr) list * (type_expr * type_expr) list
+ | Outside_class
+ | Value_multiply_overridden of string
+ | Coercion_failure of
+ type_expr * type_expr * (type_expr * type_expr) list * bool
+ | Too_many_arguments of bool * type_expr
+ | Abstract_wrong_label of arg_label * type_expr
+ | Scoping_let_module of string * type_expr
+ | Masked_instance_variable of Longident.t
+ | Not_a_variant_type of Longident.t
+ | Incoherent_label_order
+ | Less_general of string * (type_expr * type_expr) list
+ | Modules_not_allowed
+ | Cannot_infer_signature
+ | Not_a_packed_module of type_expr
+ | Recursive_local_constraint of (type_expr * type_expr) list
+ | Unexpected_existential
+ | Unqualified_gadt_pattern of Path.t * string
+ | Invalid_interval
+ | Invalid_for_loop_index
+ | No_value_clauses
+ | Exception_pattern_below_toplevel
+ | Inlined_record_escape
+
+exception Error of Location.t * Env.t * error
+exception Error_forward of Location.error
+
+(* Forward declaration, to be filled in by Typemod.type_module *)
+
+let type_module =
+ ref ((fun env md -> assert false) :
+ Env.t -> Parsetree.module_expr -> Typedtree.module_expr)
+
+(* Forward declaration, to be filled in by Typemod.type_open *)
+
+let type_open =
+ ref (fun _ -> assert false)
+
+(* Forward declaration, to be filled in by Typemod.type_package *)
+
+let type_package =
+ ref (fun _ -> assert false)
+
+(* Forward declaration, to be filled in by Typeclass.class_structure *)
+let type_object =
+ ref (fun env s -> assert false :
+ Env.t -> Location.t -> Parsetree.class_structure ->
+ Typedtree.class_structure * Types.class_signature * string list)
+
+(*
+ Saving and outputting type information.
+ We keep these function names short, because they have to be
+ called each time we create a record of type [Typedtree.expression]
+ or [Typedtree.pattern] that will end up in the typed AST.
+*)
+let re node =
+ Cmt_format.add_saved_type (Cmt_format.Partial_expression node);
+ Stypes.record (Stypes.Ti_expr node);
+ node
+;;
+let rp node =
+ Cmt_format.add_saved_type (Cmt_format.Partial_pattern node);
+ Stypes.record (Stypes.Ti_pat node);
+ node
+;;
+
+
+let is_recarg d =
+ match (repr d.val_type).desc with
+ | Tconstr(p, _, _) -> Path.is_constructor_typath p
+ | _ -> false
+
+type recarg =
+ | Allowed
+ | Required
+ | Rejected
+
+
+let fst3 (x, _, _) = x
+let snd3 (_,x,_) = x
+
+let case lhs rhs =
+ {c_lhs = lhs; c_guard = None; c_rhs = rhs}
+
+(* Upper approximation of free identifiers on the parse tree *)
+
+let iter_expression f e =
+
+ let rec expr e =
+ f e;
+ match e.pexp_desc with
+ | Pexp_extension _ (* we don't iterate under extension point *)
+ | Pexp_ident _
+ | Pexp_new _
+ | Pexp_constant _ -> ()
+ | Pexp_function pel -> List.iter case pel
+ | Pexp_fun (_, eo, _, e) -> may expr eo; expr e
+ | Pexp_apply (e, lel) -> expr e; List.iter (fun (_, e) -> expr e) lel
+ | Pexp_let (_, pel, e) -> expr e; List.iter binding pel
+ | Pexp_match (e, pel)
+ | Pexp_try (e, pel) -> expr e; List.iter case pel
+ | Pexp_array el
+ | Pexp_tuple el -> List.iter expr el
+ | Pexp_construct (_, eo)
+ | Pexp_variant (_, eo) -> may expr eo
+ | Pexp_record (iel, eo) ->
+ may expr eo; List.iter (fun (_, e) -> expr e) iel
+ | Pexp_open (_, _, e)
+ | Pexp_newtype (_, e)
+ | Pexp_poly (e, _)
+ | Pexp_lazy e
+ | Pexp_assert e
+ | Pexp_setinstvar (_, e)
+ | Pexp_send (e, _)
+ | Pexp_constraint (e, _)
+ | Pexp_coerce (e, _, _)
+ | Pexp_field (e, _) -> expr e
+ | Pexp_while (e1, e2)
+ | Pexp_sequence (e1, e2)
+ | Pexp_setfield (e1, _, e2) -> expr e1; expr e2
+ | Pexp_ifthenelse (e1, e2, eo) -> expr e1; expr e2; may expr eo
+ | Pexp_for (_, e1, e2, _, e3) -> expr e1; expr e2; expr e3
+ | Pexp_override sel -> List.iter (fun (_, e) -> expr e) sel
+ | Pexp_letmodule (_, me, e) -> expr e; module_expr me
+ | Pexp_object { pcstr_fields = fs } -> List.iter class_field fs
+ | Pexp_pack me -> module_expr me
+
+ and case {pc_lhs = _; pc_guard; pc_rhs} =
+ may expr pc_guard;
+ expr pc_rhs
+
+ and binding x =
+ expr x.pvb_expr
+
+ and module_expr me =
+ match me.pmod_desc with
+ | Pmod_extension _
+ | Pmod_ident _ -> ()
+ | Pmod_structure str -> List.iter structure_item str
+ | Pmod_constraint (me, _)
+ | Pmod_functor (_, _, me) -> module_expr me
+ | Pmod_apply (me1, me2) -> module_expr me1; module_expr me2
+ | Pmod_unpack e -> expr e
+
+
+ and structure_item str =
+ match str.pstr_desc with
+ | Pstr_eval (e, _) -> expr e
+ | Pstr_value (_, pel) -> List.iter binding pel
+ | Pstr_primitive _
+ | Pstr_type _
+ | Pstr_typext _
+ | Pstr_exception _
+ | Pstr_modtype _
+ | Pstr_open _
+ | Pstr_class_type _
+ | Pstr_attribute _
+ | Pstr_extension _ -> ()
+ | Pstr_include {pincl_mod = me}
+ | Pstr_module {pmb_expr = me} -> module_expr me
+ | Pstr_recmodule l -> List.iter (fun x -> module_expr x.pmb_expr) l
+ | Pstr_class cdl -> List.iter (fun c -> class_expr c.pci_expr) cdl
+
+ and class_expr ce =
+ match ce.pcl_desc with
+ | Pcl_constr _ -> ()
+ | Pcl_structure { pcstr_fields = fs } -> List.iter class_field fs
+ | Pcl_fun (_, eo, _, ce) -> may expr eo; class_expr ce
+ | Pcl_apply (ce, lel) ->
+ class_expr ce; List.iter (fun (_, e) -> expr e) lel
+ | Pcl_let (_, pel, ce) ->
+ List.iter binding pel; class_expr ce
+ | Pcl_constraint (ce, _) -> class_expr ce
+ | Pcl_extension _ -> ()
+
+ and class_field cf =
+ match cf.pcf_desc with
+ | Pcf_inherit (_, ce, _) -> class_expr ce
+ | Pcf_val (_, _, Cfk_virtual _)
+ | Pcf_method (_, _, Cfk_virtual _ ) | Pcf_constraint _ -> ()
+ | Pcf_val (_, _, Cfk_concrete (_, e))
+ | Pcf_method (_, _, Cfk_concrete (_, e)) -> expr e
+ | Pcf_initializer e -> expr e
+ | Pcf_attribute _ | Pcf_extension _ -> ()
+
+ in
+ expr e
+
+
+let all_idents_cases el =
+ let idents = Hashtbl.create 8 in
+ let f = function
+ | {pexp_desc=Pexp_ident { txt = Longident.Lident id; _ }; _} ->
+ Hashtbl.replace idents id ()
+ | _ -> ()
+ in
+ List.iter
+ (fun cp ->
+ may (iter_expression f) cp.pc_guard;
+ iter_expression f cp.pc_rhs
+ )
+ el;
+ Hashtbl.fold (fun x () rest -> x :: rest) idents []
+
+
+(* Typing of constants *)
+
+let type_constant = function
+ Const_int _ -> instance_def Predef.type_int
+ | Const_char _ -> instance_def Predef.type_char
+ | Const_string _ -> instance_def Predef.type_string
+ | Const_float _ -> instance_def Predef.type_float
+ | Const_int32 _ -> instance_def Predef.type_int32
+ | Const_int64 _ -> instance_def Predef.type_int64
+ | Const_nativeint _ -> instance_def Predef.type_nativeint
+
+(* Specific version of type_option, using newty rather than newgenty *)
+
+let type_option ty =
+ newty (Tconstr(Predef.path_option,[ty], ref Mnil))
+
+let mkexp exp_desc exp_type exp_loc exp_env =
+ { exp_desc; exp_type; exp_loc; exp_env; exp_extra = []; exp_attributes = [] }
+
+let option_none ty loc =
+ let lid = Longident.Lident "None"
+ and env = Env.initial_safe_string in
+ let cnone = Env.lookup_constructor lid env in
+ mkexp (Texp_construct(mknoloc lid, cnone, [])) ty loc env
+
+let option_some texp =
+ let lid = Longident.Lident "Some" in
+ let csome = Env.lookup_constructor lid Env.initial_safe_string in
+ mkexp ( Texp_construct(mknoloc lid , csome, [texp]) )
+ (type_option texp.exp_type) texp.exp_loc texp.exp_env
+
+let extract_option_type env ty =
+ match expand_head env ty with {desc = Tconstr(path, [ty], _)}
+ when Path.same path Predef.path_option -> ty
+ | _ -> assert false
+
+let extract_concrete_record env ty =
+ match extract_concrete_typedecl env ty with
+ (p0, p, {type_kind=Type_record (fields, _)}) -> (p0, p, fields)
+ | _ -> raise Not_found
+
+let extract_concrete_variant env ty =
+ match extract_concrete_typedecl env ty with
+ (p0, p, {type_kind=Type_variant cstrs}) -> (p0, p, cstrs)
+ | (p0, p, {type_kind=Type_open}) -> (p0, p, [])
+ | _ -> raise Not_found
+
+let extract_label_names sexp env ty =
+ try
+ let (_, _,fields) = extract_concrete_record env ty in
+ List.map (fun l -> l.Types.ld_id) fields
+ with Not_found ->
+ assert false
+
+let explicit_arity =
+ List.exists
+ (function
+ | ({txt="ocaml.explicit_arity"|"explicit_arity"; _}, _) -> true
+ | _ -> false
+ )
+
+(* Typing of patterns *)
+
+(* unification inside type_pat*)
+let unify_pat_types loc env ty ty' =
+ try
+ unify env ty ty'
+ with
+ Unify trace ->
+ raise(Error(loc, env, Pattern_type_clash(trace)))
+ | Tags(l1,l2) ->
+ raise(Typetexp.Error(loc, env, Typetexp.Variant_tags (l1, l2)))
+
+(* unification inside type_exp and type_expect *)
+let unify_exp_types loc env ty expected_ty =
+ (* Format.eprintf "@[%a@ %a@]@." Printtyp.raw_type_expr exp.exp_type
+ Printtyp.raw_type_expr expected_ty; *)
+ try
+ unify env ty expected_ty
+ with
+ Unify trace ->
+ raise(Error(loc, env, Expr_type_clash(trace)))
+ | Tags(l1,l2) ->
+ raise(Typetexp.Error(loc, env, Typetexp.Variant_tags (l1, l2)))
+
+(* level at which to create the local type declarations *)
+let newtype_level = ref None
+let get_newtype_level () =
+ match !newtype_level with
+ Some y -> y
+ | None -> assert false
+
+let unify_pat_types_gadt loc env ty ty' =
+ let newtype_level =
+ match !newtype_level with
+ | None -> assert false
+ | Some x -> x
+ in
+ try
+ unify_gadt ~newtype_level env ty ty'
+ with
+ Unify trace ->
+ raise(Error(loc, !env, Pattern_type_clash(trace)))
+ | Tags(l1,l2) ->
+ raise(Typetexp.Error(loc, !env, Typetexp.Variant_tags (l1, l2)))
+ | Unification_recursive_abbrev trace ->
+ raise(Error(loc, !env, Recursive_local_constraint trace))
+
+
+(* Creating new conjunctive types is not allowed when typing patterns *)
+
+let unify_pat env pat expected_ty =
+ unify_pat_types pat.pat_loc env pat.pat_type expected_ty
+
+(* make all Reither present in open variants *)
+let finalize_variant pat =
+ match pat.pat_desc with
+ Tpat_variant(tag, opat, r) ->
+ let row =
+ match expand_head pat.pat_env pat.pat_type with
+ {desc = Tvariant row} -> r := row; row_repr row
+ | _ -> assert false
+ in
+ begin match row_field tag row with
+ | Rabsent -> () (* assert false *)
+ | Reither (true, [], _, e) when not row.row_closed ->
+ set_row_field e (Rpresent None)
+ | Reither (false, ty::tl, _, e) when not row.row_closed ->
+ set_row_field e (Rpresent (Some ty));
+ begin match opat with None -> assert false
+ | Some pat -> List.iter (unify_pat pat.pat_env pat) (ty::tl)
+ end
+ | Reither (c, l, true, e) when not (row_fixed row) ->
+ set_row_field e (Reither (c, [], false, ref None))
+ | _ -> ()
+ end;
+ (* Force check of well-formedness WHY? *)
+ (* unify_pat pat.pat_env pat
+ (newty(Tvariant{row_fields=[]; row_more=newvar(); row_closed=false;
+ row_bound=(); row_fixed=false; row_name=None})); *)
+ | _ -> ()
+
+let rec iter_pattern f p =
+ f p;
+ iter_pattern_desc (iter_pattern f) p.pat_desc
+
+let has_variants p =
+ try
+ iter_pattern (function {pat_desc=Tpat_variant _} -> raise Exit | _ -> ())
+ p;
+ false
+ with Exit ->
+ true
+
+
+(* pattern environment *)
+let pattern_variables = ref ([] :
+ (Ident.t * type_expr * string loc * Location.t * bool (* as-variable *)) list)
+let pattern_force = ref ([] : (unit -> unit) list)
+let pattern_scope = ref (None : Annot.ident option);;
+let allow_modules = ref false
+let module_variables = ref ([] : (string loc * Location.t) list)
+let reset_pattern scope allow =
+ pattern_variables := [];
+ pattern_force := [];
+ pattern_scope := scope;
+ allow_modules := allow;
+ module_variables := [];
+;;
+
+let enter_variable ?(is_module=false) ?(is_as_variable=false) loc name ty =
+ if List.exists (fun (id, _, _, _, _) -> Ident.name id = name.txt)
+ !pattern_variables
+ then raise(Error(loc, Env.empty, Multiply_bound_variable name.txt));
+ let id = Ident.create name.txt in
+ pattern_variables :=
+ (id, ty, name, loc, is_as_variable) :: !pattern_variables;
+ if is_module then begin
+ (* Note: unpack patterns enter a variable of the same name *)
+ if not !allow_modules then
+ raise (Error (loc, Env.empty, Modules_not_allowed));
+ module_variables := (name, loc) :: !module_variables
+ end else
+ (* moved to genannot *)
+ may (fun s -> Stypes.record (Stypes.An_ident (name.loc, name.txt, s)))
+ !pattern_scope;
+ id
+
+let sort_pattern_variables vs =
+ List.sort
+ (fun (x,_,_,_,_) (y,_,_,_,_) ->
+ Pervasives.compare (Ident.name x) (Ident.name y))
+ vs
+
+let enter_orpat_variables loc env p1_vs p2_vs =
+ (* unify_vars operate on sorted lists *)
+
+ let p1_vs = sort_pattern_variables p1_vs
+ and p2_vs = sort_pattern_variables p2_vs in
+
+ let rec unify_vars p1_vs p2_vs =
+ let vars vs = List.map (fun (x,_t,_,_l,_a) -> x) vs in
+ match p1_vs, p2_vs with
+ | (x1,t1,_,l1,a1)::rem1, (x2,t2,_,l2,a2)::rem2 when Ident.equal x1 x2 ->
+ if x1==x2 then
+ unify_vars rem1 rem2
+ else begin
+ begin try
+ unify env t1 t2
+ with
+ | Unify trace ->
+ raise(Error(loc, env, Or_pattern_type_clash(x1, trace)))
+ end;
+ (x2,x1)::unify_vars rem1 rem2
+ end
+ | [],[] -> []
+ | (x,_,_,_,_)::_, [] ->
+ raise (Error (loc, env, Orpat_vars (x, vars p2_vs)))
+ | [],(y,_,_,_,_)::_ ->
+ raise (Error (loc, env, Orpat_vars (y, vars p1_vs)))
+ | (x,_,_,_,_)::_, (y,_,_,_,_)::_ ->
+ let err =
+ if Ident.name x < Ident.name y
+ then Orpat_vars (x, vars p2_vs)
+ else Orpat_vars (y, vars p1_vs) in
+ raise (Error (loc, env, err)) in
+ unify_vars p1_vs p2_vs
+
+let rec build_as_type env p =
+ match p.pat_desc with
+ Tpat_alias(p1,_, _) -> build_as_type env p1
+ | Tpat_tuple pl ->
+ let tyl = List.map (build_as_type env) pl in
+ newty (Ttuple tyl)
+ | Tpat_construct(_, cstr, pl) ->
+ let keep = cstr.cstr_private = Private || cstr.cstr_existentials <> [] in
+ if keep then p.pat_type else
+ let tyl = List.map (build_as_type env) pl in
+ let ty_args, ty_res = instance_constructor cstr in
+ List.iter2 (fun (p,ty) -> unify_pat env {p with pat_type = ty})
+ (List.combine pl tyl) ty_args;
+ ty_res
+ | Tpat_variant(l, p', _) ->
+ let ty = may_map (build_as_type env) p' in
+ newty (Tvariant{row_fields=[l, Rpresent ty]; row_more=newvar();
+ row_bound=(); row_name=None;
+ row_fixed=false; row_closed=false})
+ | Tpat_record (lpl,_) ->
+ let lbl = snd3 (List.hd lpl) in
+ if lbl.lbl_private = Private then p.pat_type else
+ let ty = newvar () in
+ let ppl = List.map (fun (_, l, p) -> l.lbl_pos, p) lpl in
+ let do_label lbl =
+ let _, ty_arg, ty_res = instance_label false lbl in
+ unify_pat env {p with pat_type = ty} ty_res;
+ let refinable =
+ lbl.lbl_mut = Immutable && List.mem_assoc lbl.lbl_pos ppl &&
+ match (repr lbl.lbl_arg).desc with Tpoly _ -> false | _ -> true in
+ if refinable then begin
+ let arg = List.assoc lbl.lbl_pos ppl in
+ unify_pat env {arg with pat_type = build_as_type env arg} ty_arg
+ end else begin
+ let _, ty_arg', ty_res' = instance_label false lbl in
+ unify env ty_arg ty_arg';
+ unify_pat env p ty_res'
+ end in
+ Array.iter do_label lbl.lbl_all;
+ ty
+ | Tpat_or(p1, p2, row) ->
+ begin match row with
+ None ->
+ let ty1 = build_as_type env p1 and ty2 = build_as_type env p2 in
+ unify_pat env {p2 with pat_type = ty2} ty1;
+ ty1
+ | Some row ->
+ let row = row_repr row in
+ newty (Tvariant{row with row_closed=false; row_more=newvar()})
+ end
+ | Tpat_any | Tpat_var _ | Tpat_constant _
+ | Tpat_array _ | Tpat_lazy _ -> p.pat_type
+
+let build_or_pat env loc lid =
+ let path, decl = Typetexp.find_type env loc lid
+ in
+ let tyl = List.map (fun _ -> newvar()) decl.type_params in
+ let row0 =
+ let ty = expand_head env (newty(Tconstr(path, tyl, ref Mnil))) in
+ match ty.desc with
+ Tvariant row when static_row row -> row
+ | _ -> raise(Error(loc, env, Not_a_variant_type lid))
+ in
+ let pats, fields =
+ List.fold_left
+ (fun (pats,fields) (l,f) ->
+ match row_field_repr f with
+ Rpresent None ->
+ (l,None) :: pats,
+ (l, Reither(true,[], true, ref None)) :: fields
+ | Rpresent (Some ty) ->
+ (l, Some {pat_desc=Tpat_any; pat_loc=Location.none; pat_env=env;
+ pat_type=ty; pat_extra=[]; pat_attributes=[]})
+ :: pats,
+ (l, Reither(false, [ty], true, ref None)) :: fields
+ | _ -> pats, fields)
+ ([],[]) (row_repr row0).row_fields in
+ let row =
+ { row_fields = List.rev fields; row_more = newvar(); row_bound = ();
+ row_closed = false; row_fixed = false; row_name = Some (path, tyl) }
+ in
+ let ty = newty (Tvariant row) in
+ let gloc = {loc with Location.loc_ghost=true} in
+ let row' = ref {row with row_more=newvar()} in
+ let pats =
+ List.map
+ (fun (l,p) ->
+ {pat_desc=Tpat_variant(l,p,row'); pat_loc=gloc;
+ pat_env=env; pat_type=ty; pat_extra=[]; pat_attributes=[]})
+ pats
+ in
+ match pats with
+ [] -> raise(Error(loc, env, Not_a_variant_type lid))
+ | pat :: pats ->
+ let r =
+ List.fold_left
+ (fun pat pat0 ->
+ {pat_desc=Tpat_or(pat0,pat,Some row0); pat_extra=[];
+ pat_loc=gloc; pat_env=env; pat_type=ty; pat_attributes=[]})
+ pat pats in
+ (path, rp { r with pat_loc = loc },ty)
+
+(* Type paths *)
+
+let rec expand_path env p =
+ let decl =
+ try Some (Env.find_type p env) with Not_found -> None
+ in
+ match decl with
+ Some {type_manifest = Some ty} ->
+ begin match repr ty with
+ {desc=Tconstr(p,_,_)} -> expand_path env p
+ | _ -> p
+ (* PR#6394: recursive module may introduce incoherent manifest *)
+ end
+ | _ ->
+ let p' = Env.normalize_path None env p in
+ if Path.same p p' then p else expand_path env p'
+
+let compare_type_path env tpath1 tpath2 =
+ Path.same (expand_path env tpath1) (expand_path env tpath2)
+
+(* Records *)
+let label_of_kind kind =
+ if kind = "record" then "field" else "constructor"
+
+module NameChoice(Name : sig
+ type t
+ val type_kind: string
+ val get_name: t -> string
+ val get_type: t -> type_expr
+ val get_descrs: Env.type_descriptions -> t list
+ val unbound_name_error: Env.t -> Longident.t loc -> 'a
+ val in_env: t -> bool
+end) = struct
+ open Name
+
+ let get_type_path env d =
+ match (repr (get_type d)).desc with
+ | Tconstr(p, _, _) -> p
+ | _ -> assert false
+
+ let lookup_from_type env tpath lid =
+ let descrs = get_descrs (Env.find_type_descrs tpath env) in
+ Env.mark_type_used env (Path.last tpath) (Env.find_type tpath env);
+ match lid.txt with
+ Longident.Lident s -> begin
+ try
+ List.find (fun nd -> get_name nd = s) descrs
+ with Not_found ->
+ let names = List.map get_name descrs in
+ raise (Error (lid.loc, env,
+ Wrong_name ("", newvar (), type_kind, tpath, s, names)))
+ end
+ | _ -> raise Not_found
+
+ let rec unique eq acc = function
+ [] -> List.rev acc
+ | x :: rem ->
+ if List.exists (eq x) acc then unique eq acc rem
+ else unique eq (x :: acc) rem
+
+ let ambiguous_types env lbl others =
+ let tpath = get_type_path env lbl in
+ let others =
+ List.map (fun (lbl, _) -> get_type_path env lbl) others in
+ let tpaths = unique (compare_type_path env) [tpath] others in
+ match tpaths with
+ [_] -> []
+ | _ -> List.map Printtyp.string_of_path tpaths
+
+ let disambiguate_by_type env tpath lbls =
+ let check_type (lbl, _) =
+ let lbl_tpath = get_type_path env lbl in
+ compare_type_path env tpath lbl_tpath
+ in
+ List.find check_type lbls
+
+ let disambiguate ?(warn=Location.prerr_warning) ?(check_lk=fun _ _ -> ())
+ ?scope lid env opath lbls =
+ let scope = match scope with None -> lbls | Some l -> l in
+ let lbl = match opath with
+ None ->
+ begin match lbls with
+ [] -> unbound_name_error env lid
+ | (lbl, use) :: rest ->
+ use ();
+ let paths = ambiguous_types env lbl rest in
+ if paths <> [] then
+ warn lid.loc
+ (Warnings.Ambiguous_name ([Longident.last lid.txt],
+ paths, false));
+ lbl
+ end
+ | Some(tpath0, tpath, pr) ->
+ let warn_pr () =
+ let label = label_of_kind type_kind in
+ warn lid.loc
+ (Warnings.Not_principal
+ ("this type-based " ^ label ^ " disambiguation"))
+ in
+ try
+ let lbl, use = disambiguate_by_type env tpath scope in
+ use ();
+ if not pr then begin
+ (* Check if non-principal type is affecting result *)
+ match lbls with
+ [] -> warn_pr ()
+ | (lbl', use') :: rest ->
+ let lbl_tpath = get_type_path env lbl' in
+ if not (compare_type_path env tpath lbl_tpath) then warn_pr ()
+ else
+ let paths = ambiguous_types env lbl rest in
+ if paths <> [] then
+ warn lid.loc
+ (Warnings.Ambiguous_name ([Longident.last lid.txt],
+ paths, false))
+ end;
+ lbl
+ with Not_found -> try
+ let lbl = lookup_from_type env tpath lid in
+ check_lk tpath lbl;
+ if in_env lbl then
+ begin
+ let s = Printtyp.string_of_path tpath in
+ warn lid.loc
+ (Warnings.Name_out_of_scope (s, [Longident.last lid.txt], false));
+ end;
+ if not pr then warn_pr ();
+ lbl
+ with Not_found ->
+ if lbls = [] then unbound_name_error env lid else
+ let tp = (tpath0, expand_path env tpath) in
+ let tpl =
+ List.map
+ (fun (lbl, _) ->
+ let tp0 = get_type_path env lbl in
+ let tp = expand_path env tp0 in
+ (tp0, tp))
+ lbls
+ in
+ raise (Error (lid.loc, env,
+ Name_type_mismatch (type_kind, lid.txt, tp, tpl)))
+ in
+ if in_env lbl then
+ begin match scope with
+ (lab1,_)::_ when lab1 == lbl -> ()
+ | _ ->
+ Location.prerr_warning lid.loc
+ (Warnings.Disambiguated_name(get_name lbl))
+ end;
+ lbl
+end
+
+let wrap_disambiguate kind ty f x =
+ try f x with Error (loc, env, Wrong_name ("",_,tk,tp,name,valid_names)) ->
+ raise (Error (loc, env, Wrong_name (kind,ty,tk,tp,name,valid_names)))
+
+module Label = NameChoice (struct
+ type t = label_description
+ let type_kind = "record"
+ let get_name lbl = lbl.lbl_name
+ let get_type lbl = lbl.lbl_res
+ let get_descrs = snd
+ let unbound_name_error = Typetexp.unbound_label_error
+ let in_env lbl =
+ match lbl.lbl_repres with
+ | Record_regular | Record_float -> true
+ | Record_inlined _ | Record_extension -> false
+end)
+
+let disambiguate_label_by_ids keep env closed ids labels =
+ let check_ids (lbl, _) =
+ let lbls = Hashtbl.create 8 in
+ Array.iter (fun lbl -> Hashtbl.add lbls lbl.lbl_name ()) lbl.lbl_all;
+ List.for_all (Hashtbl.mem lbls) ids
+ and check_closed (lbl, _) =
+ (not closed || List.length ids = Array.length lbl.lbl_all)
+ in
+ let labels' = List.filter check_ids labels in
+ if keep && labels' = [] then (false, labels) else
+ let labels'' = List.filter check_closed labels' in
+ if keep && labels'' = [] then (false, labels') else (true, labels'')
+
+(* Only issue warnings once per record constructor/pattern *)
+let disambiguate_lid_a_list loc closed env opath lid_a_list =
+ let ids = List.map (fun (lid, _) -> Longident.last lid.txt) lid_a_list in
+ let w_pr = ref false and w_amb = ref []
+ and w_scope = ref [] and w_scope_ty = ref "" in
+ let warn loc msg =
+ let open Warnings in
+ match msg with
+ | Not_principal _ -> w_pr := true
+ | Ambiguous_name([s], l, _) -> w_amb := (s, l) :: !w_amb
+ | Name_out_of_scope(ty, [s], _) ->
+ w_scope := s :: !w_scope; w_scope_ty := ty
+ | _ -> Location.prerr_warning loc msg
+ in
+ let process_label lid =
+ (* Strategy for each field:
+ * collect all the labels in scope for that name
+ * if the type is known and principal, just eventually warn
+ if the real label was not in scope
+ * fail if there is no known type and no label found
+ * otherwise use other fields to reduce the list of candidates
+ * if there is no known type reduce it incrementally, so that
+ there is still at least one candidate (for error message)
+ * if the reduced list is valid, call Label.disambiguate
+ *)
+ let scope = Typetexp.find_all_labels env lid.loc lid.txt in
+ if opath = None && scope = [] then
+ Typetexp.unbound_label_error env lid;
+ let (ok, labels) =
+ match opath with
+ Some (_, _, true) -> (true, scope) (* disambiguate only checks scope *)
+ | _ -> disambiguate_label_by_ids (opath=None) env closed ids scope
+ in
+ if ok then Label.disambiguate lid env opath labels ~warn ~scope
+ else fst (List.hd labels) (* will fail later *)
+ in
+ let lbl_a_list =
+ List.map (fun (lid,a) -> lid, process_label lid, a) lid_a_list in
+ if !w_pr then
+ Location.prerr_warning loc
+ (Warnings.Not_principal "this type-based record disambiguation")
+ else begin
+ match List.rev !w_amb with
+ (_,types)::others as amb ->
+ let paths =
+ List.map (fun (_,lbl,_) -> Label.get_type_path env lbl) lbl_a_list in
+ let path = List.hd paths in
+ if List.for_all (compare_type_path env path) (List.tl paths) then
+ Location.prerr_warning loc
+ (Warnings.Ambiguous_name (List.map fst amb, types, true))
+ else
+ List.iter
+ (fun (s,l) -> Location.prerr_warning loc
+ (Warnings.Ambiguous_name ([s],l,false)))
+ amb
+ | _ -> ()
+ end;
+ if !w_scope <> [] then
+ Location.prerr_warning loc
+ (Warnings.Name_out_of_scope (!w_scope_ty, List.rev !w_scope, true));
+ lbl_a_list
+
+let rec find_record_qual = function
+ | [] -> None
+ | ({ txt = Longident.Ldot (modname, _) }, _) :: _ -> Some modname
+ | _ :: rest -> find_record_qual rest
+
+let type_label_a_list ?labels loc closed env type_lbl_a opath lid_a_list =
+ let lbl_a_list =
+ match lid_a_list, labels with
+ ({txt=Longident.Lident s}, _)::_, Some labels when Hashtbl.mem labels s ->
+ (* Special case for rebuilt syntax trees *)
+ List.map
+ (function lid, a -> match lid.txt with
+ Longident.Lident s -> lid, Hashtbl.find labels s, a
+ | _ -> assert false)
+ lid_a_list
+ | _ ->
+ let lid_a_list =
+ match find_record_qual lid_a_list with
+ None -> lid_a_list
+ | Some modname ->
+ List.map
+ (fun (lid, a as lid_a) ->
+ match lid.txt with Longident.Lident s ->
+ {lid with txt=Longident.Ldot (modname, s)}, a
+ | _ -> lid_a)
+ lid_a_list
+ in
+ disambiguate_lid_a_list loc closed env opath lid_a_list
+ in
+ (* Invariant: records are sorted in the typed tree *)
+ let lbl_a_list =
+ List.sort
+ (fun (_,lbl1,_) (_,lbl2,_) -> compare lbl1.lbl_pos lbl2.lbl_pos)
+ lbl_a_list
+ in
+ List.map type_lbl_a lbl_a_list
+;;
+
+(* Checks over the labels mentioned in a record pattern:
+ no duplicate definitions (error); properly closed (warning) *)
+
+let check_recordpat_labels loc lbl_pat_list closed =
+ match lbl_pat_list with
+ | [] -> () (* should not happen *)
+ | (_, label1, _) :: _ ->
+ let all = label1.lbl_all in
+ let defined = Array.make (Array.length all) false in
+ let check_defined (_, label, _) =
+ if defined.(label.lbl_pos)
+ then raise(Error(loc, Env.empty, Label_multiply_defined label.lbl_name))
+ else defined.(label.lbl_pos) <- true in
+ List.iter check_defined lbl_pat_list;
+ if closed = Closed
+ && Warnings.is_active (Warnings.Non_closed_record_pattern "")
+ then begin
+ let undefined = ref [] in
+ for i = 0 to Array.length all - 1 do
+ if not defined.(i) then undefined := all.(i).lbl_name :: !undefined
+ done;
+ if !undefined <> [] then begin
+ let u = String.concat ", " (List.rev !undefined) in
+ Location.prerr_warning loc (Warnings.Non_closed_record_pattern u)
+ end
+ end
+
+(* Constructors *)
+
+module Constructor = NameChoice (struct
+ type t = constructor_description
+ let type_kind = "variant"
+ let get_name cstr = cstr.cstr_name
+ let get_type cstr = cstr.cstr_res
+ let get_descrs = fst
+ let unbound_name_error = Typetexp.unbound_constructor_error
+ let in_env _ = true
+end)
+
+(* unification of a type with a tconstr with
+ freshly created arguments *)
+let unify_head_only loc env ty constr =
+ let (_, ty_res) = instance_constructor constr in
+ match (repr ty_res).desc with
+ | Tconstr(p,args,m) ->
+ ty_res.desc <- Tconstr(p,List.map (fun _ -> newvar ()) args,m);
+ enforce_constraints env ty_res;
+ unify_pat_types loc env ty_res ty
+ | _ -> assert false
+
+(* Typing of patterns *)
+
+(* type_pat does not generate local constraints inside or patterns *)
+type type_pat_mode =
+ | Normal
+ | Inside_or
+
+(* type_pat propagates the expected type as well as maps for
+ constructors and labels.
+ Unification may update the typing environment. *)
+let rec type_pat ~constrs ~labels ~no_existentials ~mode ~env sp expected_ty =
+ let type_pat ?(mode=mode) ?(env=env) =
+ type_pat ~constrs ~labels ~no_existentials ~mode ~env in
+ let loc = sp.ppat_loc in
+ match sp.ppat_desc with
+ Ppat_any ->
+ rp {
+ pat_desc = Tpat_any;
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_var name ->
+ let id = enter_variable loc name expected_ty in
+ rp {
+ pat_desc = Tpat_var (id, name);
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_unpack name ->
+ let id = enter_variable loc name expected_ty ~is_module:true in
+ rp {
+ pat_desc = Tpat_var (id, name);
+ pat_loc = sp.ppat_loc;
+ pat_extra=[Tpat_unpack, loc, sp.ppat_attributes];
+ pat_type = expected_ty;
+ pat_attributes = [];
+ pat_env = !env }
+ | Ppat_constraint({ppat_desc=Ppat_var name; ppat_loc=lloc},
+ ({ptyp_desc=Ptyp_poly _} as sty)) ->
+ (* explicitly polymorphic type *)
+ let cty, force = Typetexp.transl_simple_type_delayed !env sty in
+ let ty = cty.ctyp_type in
+ unify_pat_types lloc !env ty expected_ty;
+ pattern_force := force :: !pattern_force;
+ begin match ty.desc with
+ | Tpoly (body, tyl) ->
+ begin_def ();
+ let _, ty' = instance_poly ~keep_names:true false tyl body in
+ end_def ();
+ generalize ty';
+ let id = enter_variable lloc name ty' in
+ rp {
+ pat_desc = Tpat_var (id, name);
+ pat_loc = lloc;
+ pat_extra = [Tpat_constraint cty, loc, sp.ppat_attributes];
+ pat_type = ty;
+ pat_attributes = [];
+ pat_env = !env
+ }
+ | _ -> assert false
+ end
+ | Ppat_alias(sq, name) ->
+ let q = type_pat sq expected_ty in
+ begin_def ();
+ let ty_var = build_as_type !env q in
+ end_def ();
+ generalize ty_var;
+ let id = enter_variable ~is_as_variable:true loc name ty_var in
+ rp {
+ pat_desc = Tpat_alias(q, id, name);
+ pat_loc = loc; pat_extra=[];
+ pat_type = q.pat_type;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_constant cst ->
+ unify_pat_types loc !env (type_constant cst) expected_ty;
+ rp {
+ pat_desc = Tpat_constant cst;
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_interval (Const_char c1, Const_char c2) ->
+ let open Ast_helper.Pat in
+ let gloc = {loc with Location.loc_ghost=true} in
+ let rec loop c1 c2 =
+ if c1 = c2 then constant ~loc:gloc (Const_char c1)
+ else
+ or_ ~loc:gloc
+ (constant ~loc:gloc (Const_char c1))
+ (loop (Char.chr(Char.code c1 + 1)) c2)
+ in
+ let p = if c1 <= c2 then loop c1 c2 else loop c2 c1 in
+ let p = {p with ppat_loc=loc} in
+ type_pat p expected_ty
+ (* TODO: record 'extra' to remember about interval *)
+ | Ppat_interval _ ->
+ raise (Error (loc, !env, Invalid_interval))
+ | Ppat_tuple spl ->
+ if List.length spl < 2 then
+ Syntaxerr.ill_formed_ast loc "Tuples must have at least 2 components.";
+ let spl_ann = List.map (fun p -> (p,newvar ())) spl in
+ let ty = newty (Ttuple(List.map snd spl_ann)) in
+ unify_pat_types loc !env ty expected_ty;
+ let pl = List.map (fun (p,t) -> type_pat p t) spl_ann in
+ rp {
+ pat_desc = Tpat_tuple pl;
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_construct(lid, sarg) ->
+ let opath =
+ try
+ let (p0, p, _) = extract_concrete_variant !env expected_ty in
+ Some (p0, p, true)
+ with Not_found -> None
+ in
+ let constrs =
+ match lid.txt, constrs with
+ Longident.Lident s, Some constrs when Hashtbl.mem constrs s ->
+ [Hashtbl.find constrs s, (fun () -> ())]
+ | _ -> Typetexp.find_all_constructors !env lid.loc lid.txt
+ in
+ let check_lk tpath constr =
+ if constr.cstr_generalized then
+ raise (Error (lid.loc, !env,
+ Unqualified_gadt_pattern (tpath, constr.cstr_name)))
+ in
+ let constr =
+ wrap_disambiguate "This variant pattern is expected to have" expected_ty
+ (Constructor.disambiguate lid !env opath ~check_lk) constrs
+ in
+ Env.mark_constructor Env.Pattern !env (Longident.last lid.txt) constr;
+ Typetexp.check_deprecated loc constr.cstr_attributes constr.cstr_name;
+ if no_existentials && constr.cstr_existentials <> [] then
+ raise (Error (loc, !env, Unexpected_existential));
+ (* if constructor is gadt, we must verify that the expected type has the
+ correct head *)
+ if constr.cstr_generalized then
+ unify_head_only loc !env expected_ty constr;
+ let sargs =
+ match sarg with
+ None -> []
+ | Some {ppat_desc = Ppat_tuple spl} when
+ constr.cstr_arity > 1 || explicit_arity sp.ppat_attributes
+ -> spl
+ | Some({ppat_desc = Ppat_any} as sp) when constr.cstr_arity <> 1 ->
+ if constr.cstr_arity = 0 then
+ Location.prerr_warning sp.ppat_loc
+ Warnings.Wildcard_arg_to_constant_constr;
+ replicate_list sp constr.cstr_arity
+ | Some sp -> [sp] in
+ if List.length sargs <> constr.cstr_arity then
+ raise(Error(loc, !env, Constructor_arity_mismatch(lid.txt,
+ constr.cstr_arity, List.length sargs)));
+ let (ty_args, ty_res) =
+ instance_constructor ~in_pattern:(env, get_newtype_level ()) constr
+ in
+ if constr.cstr_generalized && mode = Normal then
+ unify_pat_types_gadt loc env ty_res expected_ty
+ else
+ unify_pat_types loc !env ty_res expected_ty;
+
+ let rec check_non_escaping p =
+ match p.ppat_desc with
+ | Ppat_or (p1, p2) ->
+ check_non_escaping p1;
+ check_non_escaping p2
+ | Ppat_alias (p, _) ->
+ check_non_escaping p
+ | Ppat_constraint _ ->
+ raise (Error (p.ppat_loc, !env, Inlined_record_escape))
+ | _ ->
+ ()
+ in
+ if constr.cstr_inlined <> None then List.iter check_non_escaping sargs;
+
+ let args = List.map2 (fun p t -> type_pat p t) sargs ty_args in
+ rp {
+ pat_desc=Tpat_construct(lid, constr, args);
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_variant(l, sarg) ->
+ let arg_type = match sarg with None -> [] | Some _ -> [newvar()] in
+ let row = { row_fields =
+ [l, Reither(sarg = None, arg_type, true, ref None)];
+ row_bound = ();
+ row_closed = false;
+ row_more = newvar ();
+ row_fixed = false;
+ row_name = None } in
+ unify_pat_types loc !env (newty (Tvariant row)) expected_ty;
+ let arg =
+ (* PR#6235: propagate type information *)
+ match sarg, arg_type with
+ Some p, [ty] -> Some (type_pat p ty)
+ | _ -> None
+ in
+ rp {
+ pat_desc = Tpat_variant(l, arg, ref {row with row_more = newvar()});
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_record(lid_sp_list, closed) ->
+ if lid_sp_list = [] then
+ Syntaxerr.ill_formed_ast loc "Records cannot be empty.";
+ let opath, record_ty =
+ try
+ let (p0, p,_) = extract_concrete_record !env expected_ty in
+ Some (p0, p, true), expected_ty
+ with Not_found -> None, newvar ()
+ in
+ let type_label_pat (label_lid, label, sarg) =
+ begin_def ();
+ let (vars, ty_arg, ty_res) = instance_label false label in
+ if vars = [] then end_def ();
+ begin try
+ unify_pat_types loc !env ty_res record_ty
+ with Unify trace ->
+ raise(Error(label_lid.loc, !env,
+ Label_mismatch(label_lid.txt, trace)))
+ end;
+ let arg = type_pat sarg ty_arg in
+ if vars <> [] then begin
+ end_def ();
+ generalize ty_arg;
+ List.iter generalize vars;
+ let instantiated tv =
+ let tv = expand_head !env tv in
+ not (is_Tvar tv) || tv.level <> generic_level in
+ if List.exists instantiated vars then
+ raise (Error(label_lid.loc, !env, Polymorphic_label label_lid.txt))
+ end;
+ (label_lid, label, arg)
+ in
+ let lbl_pat_list =
+ wrap_disambiguate "This record pattern is expected to have" expected_ty
+ (type_label_a_list ?labels loc false !env type_label_pat opath)
+ lid_sp_list
+ in
+ check_recordpat_labels loc lbl_pat_list closed;
+ unify_pat_types loc !env record_ty expected_ty;
+ rp {
+ pat_desc = Tpat_record (lbl_pat_list, closed);
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_array spl ->
+ let ty_elt = newvar() in
+ unify_pat_types
+ loc !env (instance_def (Predef.type_array ty_elt)) expected_ty;
+ let spl_ann = List.map (fun p -> (p,newvar())) spl in
+ let pl = List.map (fun (p,t) -> type_pat p ty_elt) spl_ann in
+ rp {
+ pat_desc = Tpat_array pl;
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_or(sp1, sp2) ->
+ let initial_pattern_variables = !pattern_variables in
+ let p1 = type_pat ~mode:Inside_or sp1 expected_ty in
+ let p1_variables = !pattern_variables in
+ pattern_variables := initial_pattern_variables;
+ let p2 = type_pat ~mode:Inside_or sp2 expected_ty in
+ let p2_variables = !pattern_variables in
+ let alpha_env =
+ enter_orpat_variables loc !env p1_variables p2_variables in
+ pattern_variables := p1_variables;
+ rp {
+ pat_desc = Tpat_or(p1, alpha_pat alpha_env p2, None);
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_lazy sp1 ->
+ let nv = newvar () in
+ unify_pat_types loc !env (instance_def (Predef.type_lazy_t nv))
+ expected_ty;
+ let p1 = type_pat sp1 nv in
+ rp {
+ pat_desc = Tpat_lazy p1;
+ pat_loc = loc; pat_extra=[];
+ pat_type = expected_ty;
+ pat_attributes = sp.ppat_attributes;
+ pat_env = !env }
+ | Ppat_constraint(sp, sty) ->
+ (* Separate when not already separated by !principal *)
+ let separate = true in
+ if separate then begin_def();
+ let cty, force = Typetexp.transl_simple_type_delayed !env sty in
+ let ty = cty.ctyp_type in
+ let ty, expected_ty' =
+ if separate then begin
+ end_def();
+ generalize_structure ty;
+ instance !env ty, instance !env ty
+ end else ty, ty
+ in
+ unify_pat_types loc !env ty expected_ty;
+ let p = type_pat sp expected_ty' in
+ (*Format.printf "%a@.%a@."
+ Printtyp.raw_type_expr ty
+ Printtyp.raw_type_expr p.pat_type;*)
+ pattern_force := force :: !pattern_force;
+ let extra = (Tpat_constraint cty, loc, sp.ppat_attributes) in
+ if separate then
+ match p.pat_desc with
+ Tpat_var (id,s) ->
+ {p with pat_type = ty;
+ pat_desc = Tpat_alias
+ ({p with pat_desc = Tpat_any; pat_attributes = []}, id,s);
+ pat_extra = [extra];
+ }
+ | _ -> {p with pat_type = ty;
+ pat_extra = extra :: p.pat_extra}
+ else p
+ | Ppat_type lid ->
+ let (path, p,ty) = build_or_pat !env loc lid.txt in
+ unify_pat_types loc !env ty expected_ty;
+ { p with pat_extra =
+ (Tpat_type (path, lid), loc, sp.ppat_attributes) :: p.pat_extra }
+ | Ppat_exception _ ->
+ raise (Error (loc, !env, Exception_pattern_below_toplevel))
+ | Ppat_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+let type_pat ?(allow_existentials=false) ?constrs ?labels
+ ?(lev=get_current_level()) env sp expected_ty =
+ newtype_level := Some lev;
+ try
+ let r =
+ type_pat ~no_existentials:(not allow_existentials) ~constrs ~labels
+ ~mode:Normal ~env sp expected_ty in
+ iter_pattern (fun p -> p.pat_env <- !env) r;
+ newtype_level := None;
+ r
+ with e ->
+ newtype_level := None;
+ raise e
+
+
+(* this function is passed to Partial.parmatch
+ to type check gadt nonexhaustiveness *)
+let partial_pred ~lev env expected_ty constrs labels p =
+ let snap = snapshot () in
+ try
+ reset_pattern None true;
+ let typed_p =
+ type_pat ~allow_existentials:true ~lev
+ ~constrs ~labels (ref env) p expected_ty
+ in
+ backtrack snap;
+ (* types are invalidated but we don't need them here *)
+ Some typed_p
+ with _ ->
+ backtrack snap;
+ None
+
+let check_partial ?(lev=get_current_level ()) env expected_ty =
+ Parmatch.check_partial_gadt (partial_pred ~lev env expected_ty)
+
+let rec iter3 f lst1 lst2 lst3 =
+ match lst1,lst2,lst3 with
+ | x1::xs1,x2::xs2,x3::xs3 ->
+ f x1 x2 x3;
+ iter3 f xs1 xs2 xs3
+ | [],[],[] ->
+ ()
+ | _ ->
+ assert false
+
+let add_pattern_variables ?check ?check_as env =
+ let pv = get_ref pattern_variables in
+ (List.fold_right
+ (fun (id, ty, name, loc, as_var) env ->
+ let check = if as_var then check_as else check in
+ Env.add_value ?check id
+ {val_type = ty; val_kind = Val_reg; Types.val_loc = loc;
+ val_attributes = [];
+ } env
+ )
+ pv env,
+ get_ref module_variables)
+
+let type_pattern ~lev env spat scope expected_ty =
+ reset_pattern scope true;
+ let new_env = ref env in
+ let pat = type_pat ~allow_existentials:true ~lev new_env spat expected_ty in
+ let new_env, unpacks =
+ add_pattern_variables !new_env
+ ~check:(fun s -> Warnings.Unused_var_strict s)
+ ~check_as:(fun s -> Warnings.Unused_var s) in
+ (pat, new_env, get_ref pattern_force, unpacks)
+
+let type_pattern_list env spatl scope expected_tys allow =
+ reset_pattern scope allow;
+ let new_env = ref env in
+ let patl = List.map2 (type_pat new_env) spatl expected_tys in
+ let new_env, unpacks = add_pattern_variables !new_env in
+ (patl, new_env, get_ref pattern_force, unpacks)
+
+let type_class_arg_pattern cl_num val_env met_env l spat =
+ reset_pattern None false;
+ let nv = newvar () in
+ let pat = type_pat (ref val_env) spat nv in
+ if has_variants pat then begin
+ Parmatch.pressure_variants val_env [pat];
+ iter_pattern finalize_variant pat
+ end;
+ List.iter (fun f -> f()) (get_ref pattern_force);
+ if is_optional l then unify_pat val_env pat (type_option (newvar ()));
+ let (pv, met_env) =
+ List.fold_right
+ (fun (id, ty, name, loc, as_var) (pv, env) ->
+ let check s =
+ if as_var then Warnings.Unused_var s
+ else Warnings.Unused_var_strict s in
+ let id' = Ident.create (Ident.name id) in
+ ((id', name, id, ty)::pv,
+ Env.add_value id' {val_type = ty;
+ val_kind = Val_ivar (Immutable, cl_num);
+ val_attributes = [];
+ Types.val_loc = loc;
+ } ~check
+ env))
+ !pattern_variables ([], met_env)
+ in
+ let val_env, _ = add_pattern_variables val_env in
+ (pat, pv, val_env, met_env)
+
+let type_self_pattern cl_num privty val_env met_env par_env spat =
+ let open Ast_helper in
+ let spat =
+ Pat.mk (Ppat_alias (Pat.mk(Ppat_alias (spat, mknoloc "selfpat-*")),
+ mknoloc ("selfpat-" ^ cl_num)))
+ in
+ reset_pattern None false;
+ let nv = newvar() in
+ let pat = type_pat (ref val_env) spat nv in
+ List.iter (fun f -> f()) (get_ref pattern_force);
+ let meths = ref Meths.empty in
+ let vars = ref Vars.empty in
+ let pv = !pattern_variables in
+ pattern_variables := [];
+ let (val_env, met_env, par_env) =
+ List.fold_right
+ (fun (id, ty, name, loc, as_var) (val_env, met_env, par_env) ->
+ (Env.add_value id {val_type = ty;
+ val_kind = Val_unbound;
+ val_attributes = [];
+ Types.val_loc = loc;
+ } val_env,
+ Env.add_value id {val_type = ty;
+ val_kind = Val_self (meths, vars, cl_num, privty);
+ val_attributes = [];
+ Types.val_loc = loc;
+ }
+ ~check:(fun s -> if as_var then Warnings.Unused_var s
+ else Warnings.Unused_var_strict s)
+ met_env,
+ Env.add_value id {val_type = ty; val_kind = Val_unbound;
+ val_attributes = [];
+ Types.val_loc = loc;
+ } par_env))
+ pv (val_env, met_env, par_env)
+ in
+ (pat, meths, vars, val_env, met_env, par_env)
+
+let delayed_checks = ref []
+let reset_delayed_checks () = delayed_checks := []
+let add_delayed_check f =
+ delayed_checks := (f, Warnings.backup ()) :: !delayed_checks
+
+let force_delayed_checks () =
+ (* checks may change type levels *)
+ let snap = Btype.snapshot () in
+ let w_old = Warnings.backup () in
+ List.iter
+ (fun (f, w) -> Warnings.restore w; f ())
+ (List.rev !delayed_checks);
+ Warnings.restore w_old;
+ reset_delayed_checks ();
+ Btype.backtrack snap
+
+let rec final_subexpression sexp =
+ match sexp.pexp_desc with
+ Pexp_let (_, _, e)
+ | Pexp_sequence (_, e)
+ | Pexp_try (e, _)
+ | Pexp_ifthenelse (_, e, _)
+ | Pexp_match (_, {pc_rhs=e} :: _)
+ -> final_subexpression e
+ | _ -> sexp
+
+(* Generalization criterion for expressions *)
+
+let rec is_nonexpansive exp =
+ match exp.exp_desc with
+ Texp_ident(_,_,_) -> true
+ | Texp_constant _ -> true
+ | Texp_let(rec_flag, pat_exp_list, body) ->
+ List.for_all (fun vb -> is_nonexpansive vb.vb_expr) pat_exp_list &&
+ is_nonexpansive body
+ | Texp_function _ -> true
+ | Texp_apply(e, (_,None,_)::el) ->
+ is_nonexpansive e && List.for_all is_nonexpansive_opt (List.map snd3 el)
+ | Texp_match(e, cases, [], _) ->
+ is_nonexpansive e &&
+ List.for_all
+ (fun {c_lhs = _; c_guard; c_rhs} ->
+ is_nonexpansive_opt c_guard && is_nonexpansive c_rhs
+ ) cases
+ | Texp_tuple el ->
+ List.for_all is_nonexpansive el
+ | Texp_construct( _, _, el) ->
+ List.for_all is_nonexpansive el
+ | Texp_variant(_, arg) -> is_nonexpansive_opt arg
+ | Texp_record(lbl_exp_list, opt_init_exp) ->
+ List.for_all
+ (fun (_, lbl, exp) -> lbl.lbl_mut = Immutable && is_nonexpansive exp)
+ lbl_exp_list
+ && is_nonexpansive_opt opt_init_exp
+ | Texp_field(exp, lbl, _) -> is_nonexpansive exp
+ | Texp_array [] -> true
+ | Texp_ifthenelse(cond, ifso, ifnot) ->
+ is_nonexpansive ifso && is_nonexpansive_opt ifnot
+ | Texp_sequence (e1, e2) -> is_nonexpansive e2 (* PR#4354 *)
+ | Texp_new (_, _, cl_decl) when Ctype.class_type_arity cl_decl.cty_type > 0 ->
+ true
+ (* Note: nonexpansive only means no _observable_ side effects *)
+ | Texp_lazy e -> is_nonexpansive e
+ | Texp_object ({cstr_fields=fields; cstr_type = { csig_vars=vars}}, _) ->
+ let count = ref 0 in
+ List.for_all
+ (fun field -> match field.cf_desc with
+ Tcf_method _ -> true
+ | Tcf_val (_, _, _, Tcfk_concrete (_, e), _) ->
+ incr count; is_nonexpansive e
+ | Tcf_val (_, _, _, Tcfk_virtual _, _) ->
+ incr count; true
+ | Tcf_initializer e -> is_nonexpansive e
+ | Tcf_constraint _ -> true
+ | Tcf_inherit _ -> false
+ | Tcf_attribute _ -> true)
+ fields &&
+ Vars.fold (fun _ (mut,_,_) b -> decr count; b && mut = Immutable)
+ vars true &&
+ !count = 0
+ | Texp_letmodule (_, _, mexp, e) ->
+ is_nonexpansive_mod mexp && is_nonexpansive e
+ | Texp_pack mexp ->
+ is_nonexpansive_mod mexp
+ | _ -> false
+
+and is_nonexpansive_mod mexp =
+ match mexp.mod_desc with
+ | Tmod_ident _ -> true
+ | Tmod_functor _ -> true
+ | Tmod_unpack (e, _) -> is_nonexpansive e
+ | Tmod_constraint (m, _, _, _) -> is_nonexpansive_mod m
+ | Tmod_structure str ->
+ List.for_all
+ (fun item -> match item.str_desc with
+ | Tstr_eval _ | Tstr_primitive _ | Tstr_type _
+ | Tstr_modtype _ | Tstr_open _ | Tstr_class_type _ -> true
+ | Tstr_value (_, pat_exp_list) ->
+ List.for_all (fun vb -> is_nonexpansive vb.vb_expr) pat_exp_list
+ | Tstr_module {mb_expr=m;_}
+ | Tstr_include {incl_mod=m;_} -> is_nonexpansive_mod m
+ | Tstr_recmodule id_mod_list ->
+ List.for_all (fun {mb_expr=m;_} -> is_nonexpansive_mod m)
+ id_mod_list
+ | Tstr_exception {ext_kind = Text_decl _} ->
+ false (* true would be unsound *)
+ | Tstr_exception {ext_kind = Text_rebind _} -> true
+ | Tstr_typext te ->
+ List.for_all
+ (function {ext_kind = Text_decl _} -> false
+ | {ext_kind = Text_rebind _} -> true)
+ te.tyext_constructors
+ | Tstr_class _ -> false (* could be more precise *)
+ | Tstr_attribute _ -> true
+ )
+ str.str_items
+ | Tmod_apply _ -> false
+
+and is_nonexpansive_opt = function
+ None -> true
+ | Some e -> is_nonexpansive e
+
+(* Approximate the type of an expression, for better recursion *)
+
+let rec approx_type env sty =
+ match sty.ptyp_desc with
+ Ptyp_arrow (p, _, sty) ->
+ let ty1 = if is_optional p then type_option (newvar ()) else newvar () in
+ newty (Tarrow (p, ty1, approx_type env sty, Cok))
+ | Ptyp_tuple args ->
+ newty (Ttuple (List.map (approx_type env) args))
+ | Ptyp_constr (lid, ctl) ->
+ begin try
+ let (path, decl) = Env.lookup_type lid.txt env in
+ if List.length ctl <> decl.type_arity then raise Not_found;
+ let tyl = List.map (approx_type env) ctl in
+ newconstr path tyl
+ with Not_found -> newvar ()
+ end
+ | Ptyp_poly (_, sty) ->
+ approx_type env sty
+ | _ -> newvar ()
+
+let rec type_approx env sexp =
+ match sexp.pexp_desc with
+ Pexp_let (_, _, e) -> type_approx env e
+ | Pexp_fun (p, _, _, e) ->
+ let ty = if is_optional p then type_option (newvar ()) else newvar () in
+ newty (Tarrow(p, ty, type_approx env e, Cok))
+ | Pexp_function ({pc_rhs=e}::_) ->
+ newty (Tarrow(Nolabel, newvar (), type_approx env e, Cok))
+ | Pexp_match (_, {pc_rhs=e}::_) -> type_approx env e
+ | Pexp_try (e, _) -> type_approx env e
+ | Pexp_tuple l -> newty (Ttuple(List.map (type_approx env) l))
+ | Pexp_ifthenelse (_,e,_) -> type_approx env e
+ | Pexp_sequence (_,e) -> type_approx env e
+ | Pexp_constraint (e, sty) ->
+ let ty = type_approx env e in
+ let ty1 = approx_type env sty in
+ begin try unify env ty ty1 with Unify trace ->
+ raise(Error(sexp.pexp_loc, env, Expr_type_clash trace))
+ end;
+ ty1
+ | Pexp_coerce (e, sty1, sty2) ->
+ let approx_ty_opt = function
+ | None -> newvar ()
+ | Some sty -> approx_type env sty
+ in
+ let ty = type_approx env e
+ and ty1 = approx_ty_opt sty1
+ and ty2 = approx_type env sty2 in
+ begin try unify env ty ty1 with Unify trace ->
+ raise(Error(sexp.pexp_loc, env, Expr_type_clash trace))
+ end;
+ ty2
+ | _ -> newvar ()
+
+(* List labels in a function type, and whether return type is a variable *)
+let rec list_labels_aux env visited ls ty_fun =
+ let ty = expand_head env ty_fun in
+ if List.memq ty visited then
+ List.rev ls, false
+ else match ty.desc with
+ Tarrow (l, _, ty_res, _) ->
+ list_labels_aux env (ty::visited) (l::ls) ty_res
+ | _ ->
+ List.rev ls, is_Tvar ty
+
+let list_labels env ty =
+ wrap_trace_gadt_instances env (list_labels_aux env [] []) ty
+
+(* Check that all univars are safe in a type *)
+let check_univars env expans kind exp ty_expected vars =
+ if expans && not (is_nonexpansive exp) then
+ generalize_expansive env exp.exp_type;
+ (* need to expand twice? cf. Ctype.unify2 *)
+ let vars = List.map (expand_head env) vars in
+ let vars = List.map (expand_head env) vars in
+ let vars' =
+ List.filter
+ (fun t ->
+ let t = repr t in
+ generalize t;
+ match t.desc with
+ Tvar name when t.level = generic_level ->
+ log_type t; t.desc <- Tunivar name; true
+ | _ -> false)
+ vars in
+ if List.length vars = List.length vars' then () else
+ let ty = newgenty (Tpoly(repr exp.exp_type, vars'))
+ and ty_expected = repr ty_expected in
+ raise (Error (exp.exp_loc, env,
+ Less_general(kind, [ty, ty; ty_expected, ty_expected])))
+
+(* Check that a type is not a function *)
+let check_application_result env statement exp =
+ let loc = exp.exp_loc in
+ match (expand_head env exp.exp_type).desc with
+ | Tarrow _ ->
+ Location.prerr_warning exp.exp_loc Warnings.Partial_application
+ | Tvar _ -> ()
+ | Tconstr (p, _, _) when Path.same p Predef.path_unit -> ()
+ | _ ->
+ if statement then
+ Location.prerr_warning loc Warnings.Statement_type
+
+(* Check that a type is generalizable at some level *)
+let generalizable level ty =
+ let rec check ty =
+ let ty = repr ty in
+ if ty.level < lowest_level then () else
+ if ty.level <= level then raise Exit else
+ (mark_type_node ty; iter_type_expr check ty)
+ in
+ try check ty; unmark_type ty; true
+ with Exit -> unmark_type ty; false
+
+(* Hack to allow coercion of self. Will clean-up later. *)
+let self_coercion = ref ([] : (Path.t * Location.t list ref) list)
+
+(* Helpers for packaged modules. *)
+let create_package_type loc env (p, l) =
+ let s = !Typetexp.transl_modtype_longident loc env p in
+ let fields = List.map (fun (name, ct) ->
+ name, Typetexp.transl_simple_type env false ct) l in
+ let ty = newty (Tpackage (s,
+ List.map fst l,
+ List.map (fun (_, cty) -> cty.ctyp_type) fields))
+ in
+ (s, fields, ty)
+
+ let wrap_unpacks sexp unpacks =
+ let open Ast_helper in
+ List.fold_left
+ (fun sexp (name, loc) ->
+ Exp.letmodule ~loc:sexp.pexp_loc ~attrs:[mknoloc "#modulepat",PStr []]
+ name
+ (Mod.unpack ~loc
+ (Exp.ident ~loc:name.loc (mkloc (Longident.Lident name.txt)
+ name.loc)))
+ sexp
+ )
+ sexp unpacks
+
+(* Helpers for type_cases *)
+
+let contains_variant_either ty =
+ let rec loop ty =
+ let ty = repr ty in
+ if ty.level >= lowest_level then begin
+ mark_type_node ty;
+ match ty.desc with
+ Tvariant row ->
+ let row = row_repr row in
+ if not row.row_fixed then
+ List.iter
+ (fun (_,f) ->
+ match row_field_repr f with Reither _ -> raise Exit | _ -> ())
+ row.row_fields;
+ iter_row loop row
+ | _ ->
+ iter_type_expr loop ty
+ end
+ in
+ try loop ty; unmark_type ty; false
+ with Exit -> unmark_type ty; true
+
+let iter_ppat f p =
+ match p.ppat_desc with
+ | Ppat_any | Ppat_var _ | Ppat_constant _ | Ppat_interval _
+ | Ppat_extension _
+ | Ppat_type _ | Ppat_unpack _ -> ()
+ | Ppat_array pats -> List.iter f pats
+ | Ppat_or (p1,p2) -> f p1; f p2
+ | Ppat_variant (_, arg) | Ppat_construct (_, arg) -> may f arg
+ | Ppat_tuple lst -> List.iter f lst
+ | Ppat_exception p | Ppat_alias (p,_)
+ | Ppat_constraint (p,_) | Ppat_lazy p -> f p
+ | Ppat_record (args, flag) -> List.iter (fun (_,p) -> f p) args
+
+let contains_polymorphic_variant p =
+ let rec loop p =
+ match p.ppat_desc with
+ Ppat_variant _ | Ppat_type _ -> raise Exit
+ | _ -> iter_ppat loop p
+ in
+ try loop p; false with Exit -> true
+
+let contains_gadt env p =
+ let rec loop p =
+ match p.ppat_desc with
+ Ppat_construct (lid, _) ->
+ begin try
+ let cstrs = Env.lookup_all_constructors lid.txt env in
+ List.iter (fun (cstr,_) -> if cstr.cstr_generalized then raise Exit)
+ cstrs
+ with Not_found -> ()
+ end; iter_ppat loop p
+ | _ -> iter_ppat loop p
+ in
+ try loop p; false with Exit -> true
+
+let check_absent_variant env =
+ iter_pattern
+ (function {pat_desc = Tpat_variant (s, arg, row)} as pat ->
+ let row = row_repr !row in
+ if List.exists (fun (s',fi) -> s = s' && row_field_repr fi <> Rabsent)
+ row.row_fields
+ || not row.row_fixed && not (static_row row) (* same as Ctype.poly *)
+ then () else
+ let ty_arg =
+ match arg with None -> [] | Some p -> [correct_levels p.pat_type] in
+ let row' = {row_fields = [s, Reither(arg=None,ty_arg,true,ref None)];
+ row_more = newvar (); row_bound = ();
+ row_closed = false; row_fixed = false; row_name = None} in
+ (* Should fail *)
+ unify_pat env {pat with pat_type = newty (Tvariant row')}
+ (correct_levels pat.pat_type)
+ | _ -> ())
+
+(* Duplicate types of values in the environment *)
+(* XXX Should we do something about global type variables too? *)
+
+let duplicate_ident_types loc caselist env =
+ let caselist =
+ List.filter (fun {pc_lhs} -> contains_gadt env pc_lhs) caselist in
+ let idents = all_idents_cases caselist in
+ List.fold_left
+ (fun env s ->
+ try
+ (* XXX This will mark the value as being used;
+ I don't think this is what we want *)
+ let (path, desc) = Env.lookup_value (Longident.Lident s) env in
+ match path with
+ Path.Pident id ->
+ let desc = {desc with val_type = correct_levels desc.val_type} in
+ Env.add_value id desc env
+ | _ -> env
+ with Not_found -> env)
+ env idents
+
+(* Typing of expressions *)
+
+let unify_exp env exp expected_ty =
+ (* Format.eprintf "@[%a@ %a@]@." Printtyp.raw_type_expr exp.exp_type
+ Printtyp.raw_type_expr expected_ty; *)
+ unify_exp_types exp.exp_loc env exp.exp_type expected_ty
+
+let rec type_exp ?recarg env sexp =
+ (* We now delegate everything to type_expect *)
+ type_expect ?recarg env sexp (newvar ())
+
+(* Typing of an expression with an expected type.
+ This provide better error messages, and allows controlled
+ propagation of return type information.
+ In the principal case, [type_expected'] may be at generic_level.
+ *)
+
+and type_expect ?in_function ?recarg env sexp ty_expected =
+ let previous_saved_types = Cmt_format.get_saved_types () in
+ Typetexp.warning_enter_scope ();
+ Typetexp.warning_attribute sexp.pexp_attributes;
+ let exp = type_expect_ ?in_function ?recarg env sexp ty_expected in
+ Typetexp.warning_leave_scope ();
+ Cmt_format.set_saved_types
+ (Cmt_format.Partial_expression exp :: previous_saved_types);
+ exp
+
+and type_expect_ ?in_function ?(recarg=Rejected) env sexp ty_expected =
+ let loc = sexp.pexp_loc in
+ (* Record the expression type before unifying it with the expected type *)
+ let rue exp =
+ unify_exp env (re exp) (instance env ty_expected);
+ exp
+ in
+ match sexp.pexp_desc with
+ | Pexp_ident lid ->
+ begin
+ let (path, desc) = Typetexp.find_value env loc lid.txt in
+ if !Clflags.annotations then begin
+ let dloc = desc.Types.val_loc in
+ let annot =
+ if dloc.Location.loc_ghost then Annot.Iref_external
+ else Annot.Iref_internal dloc
+ in
+ let name = Path.name ~paren:Oprint.parenthesized_ident path in
+ Stypes.record (Stypes.An_ident (loc, name, annot))
+ end;
+ begin match is_recarg desc, recarg with
+ | _, Allowed | true, Required | false, Rejected -> ()
+ | true, Rejected | false, Required ->
+ raise (Error (loc, env, Inlined_record_escape));
+ end;
+ rue {
+ exp_desc =
+ begin match desc.val_kind with
+ Val_ivar (_, cl_num) ->
+ let (self_path, _) =
+ Env.lookup_value (Longident.Lident ("self-" ^ cl_num)) env
+ in
+ Texp_instvar(self_path, path,
+ match lid.txt with
+ Longident.Lident txt -> { txt; loc = lid.loc }
+ | _ -> assert false)
+ | Val_self (_, _, cl_num, _) ->
+ let (path, _) =
+ Env.lookup_value (Longident.Lident ("self-" ^ cl_num)) env
+ in
+ Texp_ident(path, lid, desc)
+ | Val_unbound ->
+ raise(Error(loc, env, Masked_instance_variable lid.txt))
+ (*| Val_prim _ ->
+ let p = Env.normalize_path (Some loc) env path in
+ Env.add_required_global (Path.head p);
+ Texp_ident(path, lid, desc)*)
+ | _ ->
+ Texp_ident(path, lid, desc)
+ end;
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance env desc.val_type;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ end
+ | Pexp_constant(Const_string (str, _) as cst) -> (
+ (* Terrible hack for format strings *)
+ let ty_exp = expand_head env ty_expected in
+ let fmt6_path =
+ Path.(Pdot (Pident (Ident.create_persistent "CamlinternalFormatBasics"),
+ "format6", 0)) in
+ let is_format = match ty_exp.desc with
+ | Tconstr(path, _, _) when Path.same path fmt6_path ->
+ if !Clflags.principal && ty_exp.level <> generic_level then
+ Location.prerr_warning loc
+ (Warnings.Not_principal "this coercion to format6");
+ true
+ | _ -> false
+ in
+ if is_format then
+ let format_parsetree =
+ { (type_format loc str env) with pexp_loc = sexp.pexp_loc } in
+ type_expect ?in_function env format_parsetree ty_expected
+ else
+ rue {
+ exp_desc = Texp_constant cst;
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance_def Predef.type_string;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ )
+ | Pexp_constant cst ->
+ rue {
+ exp_desc = Texp_constant cst;
+ exp_loc = loc; exp_extra = [];
+ exp_type = type_constant cst;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_let(Nonrecursive,
+ [{pvb_pat=spat; pvb_expr=sval; pvb_attributes=[]}], sbody)
+ when contains_gadt env spat ->
+ (* TODO: allow non-empty attributes? *)
+ type_expect ?in_function env
+ {sexp with
+ pexp_desc = Pexp_match (sval, [Ast_helper.Exp.case spat sbody])}
+ ty_expected
+ | Pexp_let(rec_flag, spat_sexp_list, sbody) ->
+ let scp =
+ match sexp.pexp_attributes, rec_flag with
+ | [{txt="#default"},_], _ -> None
+ | _, Recursive -> Some (Annot.Idef loc)
+ | _, Nonrecursive -> Some (Annot.Idef sbody.pexp_loc)
+ in
+ let (pat_exp_list, new_env, unpacks) =
+ type_let env rec_flag spat_sexp_list scp true in
+ let body =
+ type_expect new_env (wrap_unpacks sbody unpacks) ty_expected in
+ re {
+ exp_desc = Texp_let(rec_flag, pat_exp_list, body);
+ exp_loc = loc; exp_extra = [];
+ exp_type = body.exp_type;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_fun (l, Some default, spat, sbody) ->
+ assert(is_optional l); (* default allowed only with optional argument *)
+ let open Ast_helper in
+ let default_loc = default.pexp_loc in
+ let scases = [
+ Exp.case
+ (Pat.construct ~loc:default_loc
+ (mknoloc (Longident.(Ldot (Lident "*predef*", "Some"))))
+ (Some (Pat.var ~loc:default_loc (mknoloc "*sth*"))))
+ (Exp.ident ~loc:default_loc (mknoloc (Longident.Lident "*sth*")));
+
+ Exp.case
+ (Pat.construct ~loc:default_loc
+ (mknoloc (Longident.(Ldot (Lident "*predef*", "None"))))
+ None)
+ default;
+ ]
+ in
+ let smatch =
+ Exp.match_ ~loc (Exp.ident ~loc (mknoloc (Longident.Lident "*opt*")))
+ scases
+ in
+ let pat = Pat.var ~loc (mknoloc "*opt*") in
+ let body =
+ Exp.let_ ~loc Nonrecursive ~attrs:[mknoloc "#default",PStr []]
+ [Vb.mk spat smatch] sbody
+ in
+ type_function ?in_function loc sexp.pexp_attributes env ty_expected
+ l [Exp.case pat body]
+ | Pexp_fun (l, None, spat, sbody) ->
+ type_function ?in_function loc sexp.pexp_attributes env ty_expected
+ l [Ast_helper.Exp.case spat sbody]
+ | Pexp_function caselist ->
+ type_function ?in_function
+ loc sexp.pexp_attributes env ty_expected Nolabel caselist
+ | Pexp_apply(sfunct, sargs) ->
+ if sargs = [] then
+ Syntaxerr.ill_formed_ast loc "Function application with no argument.";
+ begin_def (); (* one more level for non-returning functions *)
+ if !Clflags.principal then begin_def ();
+ let funct = type_exp env sfunct in
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure funct.exp_type
+ end;
+ let rec lower_args seen ty_fun =
+ let ty = expand_head env ty_fun in
+ if List.memq ty seen then () else
+ match ty.desc with
+ Tarrow (l, ty_arg, ty_fun, com) ->
+ (try unify_var env (newvar()) ty_arg with Unify _ -> assert false);
+ lower_args (ty::seen) ty_fun
+ | _ -> ()
+ in
+ let ty = instance env funct.exp_type in
+ end_def ();
+ wrap_trace_gadt_instances env (lower_args []) ty;
+ begin_def ();
+ let (args, ty_res) = type_application env funct sargs in
+ end_def ();
+ unify_var env (newvar()) funct.exp_type;
+ rue {
+ exp_desc = Texp_apply(funct, args);
+ exp_loc = loc; exp_extra = [];
+ exp_type = ty_res;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_match(sarg, caselist) ->
+ begin_def ();
+ let arg = type_exp env sarg in
+ end_def ();
+ if is_nonexpansive arg then generalize arg.exp_type
+ else generalize_expansive env arg.exp_type;
+ let rec split_cases vc ec = function
+ | [] -> List.rev vc, List.rev ec
+ | {pc_lhs = {ppat_desc=Ppat_exception p}} as c :: rest ->
+ split_cases vc ({c with pc_lhs = p} :: ec) rest
+ | c :: rest ->
+ split_cases (c :: vc) ec rest
+ in
+ let val_caselist, exn_caselist = split_cases [] [] caselist in
+ if val_caselist = [] && exn_caselist <> [] then
+ raise (Error (loc, env, No_value_clauses));
+ (* Note: val_caselist = [] and exn_caselist = [], i.e. a fully
+ empty pattern matching can be generated by Camlp4 with its
+ revised syntax. Let's accept it for backward compatibility. *)
+ let val_cases, partial =
+ type_cases env arg.exp_type ty_expected true loc val_caselist in
+ let exn_cases, _ =
+ type_cases env Predef.type_exn ty_expected false loc exn_caselist in
+ re {
+ exp_desc = Texp_match(arg, val_cases, exn_cases, partial);
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance env ty_expected;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_try(sbody, caselist) ->
+ let body = type_expect env sbody ty_expected in
+ let cases, _ =
+ type_cases env Predef.type_exn ty_expected false loc caselist in
+ re {
+ exp_desc = Texp_try(body, cases);
+ exp_loc = loc; exp_extra = [];
+ exp_type = body.exp_type;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_tuple sexpl ->
+ if List.length sexpl < 2 then
+ Syntaxerr.ill_formed_ast loc "Tuples must have at least 2 components.";
+ let subtypes = List.map (fun _ -> newgenvar ()) sexpl in
+ let to_unify = newgenty (Ttuple subtypes) in
+ unify_exp_types loc env to_unify ty_expected;
+ let expl =
+ List.map2 (fun body ty -> type_expect env body ty) sexpl subtypes
+ in
+ re {
+ exp_desc = Texp_tuple expl;
+ exp_loc = loc; exp_extra = [];
+ (* Keep sharing *)
+ exp_type = newty (Ttuple (List.map (fun e -> e.exp_type) expl));
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_construct(lid, sarg) ->
+ type_construct env loc lid sarg ty_expected sexp.pexp_attributes
+ | Pexp_variant(l, sarg) ->
+ (* Keep sharing *)
+ let ty_expected0 = instance env ty_expected in
+ begin try match
+ sarg, expand_head env ty_expected, expand_head env ty_expected0 with
+ | Some sarg, {desc = Tvariant row}, {desc = Tvariant row0} ->
+ let row = row_repr row in
+ begin match row_field_repr (List.assoc l row.row_fields),
+ row_field_repr (List.assoc l row0.row_fields) with
+ Rpresent (Some ty), Rpresent (Some ty0) ->
+ let arg = type_argument env sarg ty ty0 in
+ re { exp_desc = Texp_variant(l, Some arg);
+ exp_loc = loc; exp_extra = [];
+ exp_type = ty_expected0;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | _ -> raise Not_found
+ end
+ | _ -> raise Not_found
+ with Not_found ->
+ let arg = may_map (type_exp env) sarg in
+ let arg_type = may_map (fun arg -> arg.exp_type) arg in
+ rue {
+ exp_desc = Texp_variant(l, arg);
+ exp_loc = loc; exp_extra = [];
+ exp_type= newty (Tvariant{row_fields = [l, Rpresent arg_type];
+ row_more = newvar ();
+ row_bound = ();
+ row_closed = false;
+ row_fixed = false;
+ row_name = None});
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ end
+ | Pexp_record(lid_sexp_list, opt_sexp) ->
+ if lid_sexp_list = [] then
+ Syntaxerr.ill_formed_ast loc "Records cannot be empty.";
+ let opt_exp =
+ match opt_sexp with
+ None -> None
+ | Some sexp ->
+ if !Clflags.principal then begin_def ();
+ let exp = type_exp ~recarg env sexp in
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure exp.exp_type
+ end;
+ Some exp
+ in
+ let ty_record, opath =
+ let get_path ty =
+ try
+ let (p0, p,_) = extract_concrete_record env ty in
+ (* XXX level may be wrong *)
+ Some (p0, p, ty.level = generic_level || not !Clflags.principal)
+ with Not_found -> None
+ in
+ match get_path ty_expected with
+ None ->
+ begin match opt_exp with
+ None -> newvar (), None
+ | Some exp ->
+ match get_path exp.exp_type with
+ None -> newvar (), None
+ | Some (_, p', _) as op ->
+ let decl = Env.find_type p' env in
+ begin_def ();
+ let ty =
+ newconstr p' (instance_list env decl.type_params) in
+ end_def ();
+ generalize_structure ty;
+ ty, op
+ end
+ | op -> ty_expected, op
+ in
+ let closed = (opt_sexp = None) in
+ let lbl_exp_list =
+ wrap_disambiguate "This record expression is expected to have" ty_record
+ (type_label_a_list loc closed env
+ (type_label_exp true env loc ty_record)
+ opath)
+ lid_sexp_list
+ in
+ unify_exp_types loc env ty_record (instance env ty_expected);
+
+ (* type_label_a_list returns a list of labels sorted by lbl_pos *)
+ (* note: check_duplicates would better be implemented in
+ type_label_a_list directly *)
+ let rec check_duplicates = function
+ | (_, lbl1, _) :: (_, lbl2, _) :: _ when lbl1.lbl_pos = lbl2.lbl_pos ->
+ raise(Error(loc, env, Label_multiply_defined lbl1.lbl_name))
+ | _ :: rem ->
+ check_duplicates rem
+ | [] -> ()
+ in
+ check_duplicates lbl_exp_list;
+ let opt_exp =
+ match opt_exp, lbl_exp_list with
+ None, _ -> None
+ | Some exp, (lid, lbl, lbl_exp) :: _ ->
+ let ty_exp = instance env exp.exp_type in
+ let unify_kept lbl =
+ (* do not connect overridden labels *)
+ if List.for_all
+ (fun (_, lbl',_) -> lbl'.lbl_pos <> lbl.lbl_pos)
+ lbl_exp_list
+ then begin
+ let _, ty_arg1, ty_res1 = instance_label false lbl
+ and _, ty_arg2, ty_res2 = instance_label false lbl in
+ unify env ty_arg1 ty_arg2;
+ unify env (instance env ty_expected) ty_res2;
+ unify_exp_types exp.exp_loc env ty_exp ty_res1;
+ end in
+ Array.iter unify_kept lbl.lbl_all;
+ Some {exp with exp_type = ty_exp}
+ | _ -> assert false
+ in
+ let num_fields =
+ match lbl_exp_list with [] -> assert false
+ | (_, lbl,_)::_ -> Array.length lbl.lbl_all in
+ if opt_sexp = None && List.length lid_sexp_list <> num_fields then begin
+ let present_indices =
+ List.map (fun (_, lbl, _) -> lbl.lbl_pos) lbl_exp_list in
+ let label_names = extract_label_names sexp env ty_expected in
+ let rec missing_labels n = function
+ [] -> []
+ | lbl :: rem ->
+ if List.mem n present_indices then missing_labels (n + 1) rem
+ else lbl :: missing_labels (n + 1) rem
+ in
+ let missing = missing_labels 0 label_names in
+ raise(Error(loc, env, Label_missing missing))
+ end
+ else if opt_sexp <> None && List.length lid_sexp_list = num_fields then
+ Location.prerr_warning loc Warnings.Useless_record_with;
+ re {
+ exp_desc = Texp_record(lbl_exp_list, opt_exp);
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance env ty_expected;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_field(srecord, lid) ->
+ let (record, label, _) = type_label_access env loc srecord lid in
+ let (_, ty_arg, ty_res) = instance_label false label in
+ unify_exp env record ty_res;
+ rue {
+ exp_desc = Texp_field(record, lid, label);
+ exp_loc = loc; exp_extra = [];
+ exp_type = ty_arg;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_setfield(srecord, lid, snewval) ->
+ let (record, label, opath) = type_label_access env loc srecord lid in
+ let ty_record = if opath = None then newvar () else record.exp_type in
+ let (label_loc, label, newval) =
+ type_label_exp false env loc ty_record (lid, label, snewval) in
+ unify_exp env record ty_record;
+ if label.lbl_mut = Immutable then
+ raise(Error(loc, env, Label_not_mutable lid.txt));
+ rue {
+ exp_desc = Texp_setfield(record, label_loc, label, newval);
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance_def Predef.type_unit;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_array(sargl) ->
+ let ty = newgenvar() in
+ let to_unify = Predef.type_array ty in
+ unify_exp_types loc env to_unify ty_expected;
+ let argl = List.map (fun sarg -> type_expect env sarg ty) sargl in
+ re {
+ exp_desc = Texp_array argl;
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance env ty_expected;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_ifthenelse(scond, sifso, sifnot) ->
+ let cond = type_expect env scond Predef.type_bool in
+ begin match sifnot with
+ None ->
+ let ifso = type_expect env sifso Predef.type_unit in
+ rue {
+ exp_desc = Texp_ifthenelse(cond, ifso, None);
+ exp_loc = loc; exp_extra = [];
+ exp_type = ifso.exp_type;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Some sifnot ->
+ let ifso = type_expect env sifso ty_expected in
+ let ifnot = type_expect env sifnot ty_expected in
+ (* Keep sharing *)
+ unify_exp env ifnot ifso.exp_type;
+ re {
+ exp_desc = Texp_ifthenelse(cond, ifso, Some ifnot);
+ exp_loc = loc; exp_extra = [];
+ exp_type = ifso.exp_type;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ end
+ | Pexp_sequence(sexp1, sexp2) ->
+ let exp1 = type_statement env sexp1 in
+ let exp2 = type_expect env sexp2 ty_expected in
+ re {
+ exp_desc = Texp_sequence(exp1, exp2);
+ exp_loc = loc; exp_extra = [];
+ exp_type = exp2.exp_type;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_while(scond, sbody) ->
+ let cond = type_expect env scond Predef.type_bool in
+ let body = type_statement env sbody in
+ rue {
+ exp_desc = Texp_while(cond, body);
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance_def Predef.type_unit;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_for(param, slow, shigh, dir, sbody) ->
+ let low = type_expect env slow Predef.type_int in
+ let high = type_expect env shigh Predef.type_int in
+ let id, new_env =
+ match param.ppat_desc with
+ | Ppat_any -> Ident.create "_for", env
+ | Ppat_var {txt} ->
+ Env.enter_value txt {val_type = instance_def Predef.type_int;
+ val_attributes = [];
+ val_kind = Val_reg; Types.val_loc = loc; } env
+ ~check:(fun s -> Warnings.Unused_for_index s)
+ | _ ->
+ raise (Error (param.ppat_loc, env, Invalid_for_loop_index))
+ in
+ let body = type_statement new_env sbody in
+ rue {
+ exp_desc = Texp_for(id, param, low, high, dir, body);
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance_def Predef.type_unit;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_constraint (sarg, sty) ->
+ let separate = true in (* always separate, 1% slowdown for lablgtk *)
+ if separate then begin_def ();
+ let cty = Typetexp.transl_simple_type env false sty in
+ let ty = cty.ctyp_type in
+ let (arg, ty') =
+ if separate then begin
+ end_def ();
+ generalize_structure ty;
+ (type_argument env sarg ty (instance env ty), instance env ty)
+ end else
+ (type_argument env sarg ty ty, ty)
+ in
+ rue {
+ exp_desc = arg.exp_desc;
+ exp_loc = arg.exp_loc;
+ exp_type = ty';
+ exp_attributes = arg.exp_attributes;
+ exp_env = env;
+ exp_extra =
+ (Texp_constraint cty, loc, sexp.pexp_attributes) :: arg.exp_extra;
+ }
+ | Pexp_coerce(sarg, sty, sty') ->
+ let separate = true (* always separate, 1% slowdown for lablgtk *)
+ (* !Clflags.principal || Env.has_local_constraints env *) in
+ let (arg, ty',cty,cty') =
+ match sty with
+ | None ->
+ let (cty', force) =
+ Typetexp.transl_simple_type_delayed env sty'
+ in
+ let ty' = cty'.ctyp_type in
+ if separate then begin_def ();
+ let arg = type_exp env sarg in
+ let gen =
+ if separate then begin
+ end_def ();
+ let tv = newvar () in
+ let gen = generalizable tv.level arg.exp_type in
+ unify_var env tv arg.exp_type;
+ gen
+ end else true
+ in
+ begin match arg.exp_desc, !self_coercion, (repr ty').desc with
+ Texp_ident(_, _, {val_kind=Val_self _}), (path,r) :: _,
+ Tconstr(path',_,_) when Path.same path path' ->
+ (* prerr_endline "self coercion"; *)
+ r := loc :: !r;
+ force ()
+ | _ when free_variables ~env arg.exp_type = []
+ && free_variables ~env ty' = [] ->
+ if not gen && (* first try a single coercion *)
+ let snap = snapshot () in
+ let ty, b = enlarge_type env ty' in
+ try
+ force (); Ctype.unify env arg.exp_type ty; true
+ with Unify _ ->
+ backtrack snap; false
+ then ()
+ else begin try
+ let force' = subtype env arg.exp_type ty' in
+ force (); force' ();
+ if not gen then
+ Location.prerr_warning loc
+ (Warnings.Not_principal "this ground coercion");
+ with Subtype (tr1, tr2) ->
+ (* prerr_endline "coercion failed"; *)
+ raise(Error(loc, env, Not_subtype(tr1, tr2)))
+ end;
+ | _ ->
+ let ty, b = enlarge_type env ty' in
+ force ();
+ begin try Ctype.unify env arg.exp_type ty with Unify trace ->
+ raise(Error(sarg.pexp_loc, env,
+ Coercion_failure(ty', full_expand env ty', trace, b)))
+ end
+ end;
+ (arg, ty', None, cty')
+ | Some sty ->
+ if separate then begin_def ();
+ let (cty, force) =
+ Typetexp.transl_simple_type_delayed env sty
+ and (cty', force') =
+ Typetexp.transl_simple_type_delayed env sty'
+ in
+ let ty = cty.ctyp_type in
+ let ty' = cty'.ctyp_type in
+ begin try
+ let force'' = subtype env ty ty' in
+ force (); force' (); force'' ()
+ with Subtype (tr1, tr2) ->
+ raise(Error(loc, env, Not_subtype(tr1, tr2)))
+ end;
+ if separate then begin
+ end_def ();
+ generalize_structure ty;
+ generalize_structure ty';
+ (type_argument env sarg ty (instance env ty),
+ instance env ty', Some cty, cty')
+ end else
+ (type_argument env sarg ty ty, ty', Some cty, cty')
+ in
+ rue {
+ exp_desc = arg.exp_desc;
+ exp_loc = arg.exp_loc;
+ exp_type = ty';
+ exp_attributes = arg.exp_attributes;
+ exp_env = env;
+ exp_extra = (Texp_coerce (cty, cty'), loc, sexp.pexp_attributes) ::
+ arg.exp_extra;
+ }
+ | Pexp_send (e, met) ->
+ if !Clflags.principal then begin_def ();
+ let obj = type_exp env e in
+ let obj_meths = ref None in
+ begin try
+ let (meth, exp, typ) =
+ match obj.exp_desc with
+ Texp_ident(path, _, {val_kind = Val_self (meths, _, _, privty)}) ->
+ obj_meths := Some meths;
+ let (id, typ) =
+ filter_self_method env met Private meths privty
+ in
+ if is_Tvar (repr typ) then
+ Location.prerr_warning loc
+ (Warnings.Undeclared_virtual_method met);
+ (Tmeth_val id, None, typ)
+ | Texp_ident(path, lid, {val_kind = Val_anc (methods, cl_num)}) ->
+ let method_id =
+ begin try List.assoc met methods with Not_found ->
+ let valid_methods = List.map fst methods in
+ raise(Error(e.pexp_loc, env,
+ Undefined_inherited_method (met, valid_methods)))
+ end
+ in
+ begin match
+ Env.lookup_value (Longident.Lident ("selfpat-" ^ cl_num)) env,
+ Env.lookup_value (Longident.Lident ("self-" ^cl_num)) env
+ with
+ (_, ({val_kind = Val_self (meths, _, _, privty)} as desc)),
+ (path, _) ->
+ obj_meths := Some meths;
+ let (_, typ) =
+ filter_self_method env met Private meths privty
+ in
+ let method_type = newvar () in
+ let (obj_ty, res_ty) = filter_arrow env method_type Nolabel in
+ unify env obj_ty desc.val_type;
+ unify env res_ty (instance env typ);
+ let exp =
+ Texp_apply({exp_desc =
+ Texp_ident(Path.Pident method_id, lid,
+ {val_type = method_type;
+ val_kind = Val_reg;
+ val_attributes = [];
+ Types.val_loc = Location.none});
+ exp_loc = loc; exp_extra = [];
+ exp_type = method_type;
+ exp_attributes = []; (* check *)
+ exp_env = env},
+ [ Nolabel,
+ Some {exp_desc = Texp_ident(path, lid, desc);
+ exp_loc = obj.exp_loc; exp_extra = [];
+ exp_type = desc.val_type;
+ exp_attributes = []; (* check *)
+ exp_env = env},
+ Required ])
+ in
+ (Tmeth_name met, Some (re {exp_desc = exp;
+ exp_loc = loc; exp_extra = [];
+ exp_type = typ;
+ exp_attributes = []; (* check *)
+ exp_env = env}), typ)
+ | _ ->
+ assert false
+ end
+ | _ ->
+ (Tmeth_name met, None,
+ filter_method env met Public obj.exp_type)
+ in
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure typ;
+ end;
+ let typ =
+ match repr typ with
+ {desc = Tpoly (ty, [])} ->
+ instance env ty
+ | {desc = Tpoly (ty, tl); level = l} ->
+ if !Clflags.principal && l <> generic_level then
+ Location.prerr_warning loc
+ (Warnings.Not_principal "this use of a polymorphic method");
+ snd (instance_poly false tl ty)
+ | {desc = Tvar _} as ty ->
+ let ty' = newvar () in
+ unify env (instance_def ty) (newty(Tpoly(ty',[])));
+ (* if not !Clflags.nolabels then
+ Location.prerr_warning loc (Warnings.Unknown_method met); *)
+ ty'
+ | _ ->
+ assert false
+ in
+ rue {
+ exp_desc = Texp_send(obj, meth, exp);
+ exp_loc = loc; exp_extra = [];
+ exp_type = typ;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ with Unify _ ->
+ let valid_methods =
+ match !obj_meths with
+ | Some meths ->
+ Some (Meths.fold (fun meth _meth_ty li -> meth::li) !meths [])
+ | None ->
+ match (expand_head env obj.exp_type).desc with
+ | Tobject (fields, _) ->
+ let (fields, _) = Ctype.flatten_fields fields in
+ let collect_fields li (meth, meth_kind, _meth_ty) =
+ if meth_kind = Fpresent then meth::li else li in
+ Some (List.fold_left collect_fields [] fields)
+ | _ -> None
+ in
+ raise(Error(e.pexp_loc, env,
+ Undefined_method (obj.exp_type, met, valid_methods)))
+ end
+ | Pexp_new cl ->
+ let (cl_path, cl_decl) = Typetexp.find_class env loc cl.txt in
+ begin match cl_decl.cty_new with
+ None ->
+ raise(Error(loc, env, Virtual_class cl.txt))
+ | Some ty ->
+ rue {
+ exp_desc = Texp_new (cl_path, cl, cl_decl);
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance_def ty;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ end
+ | Pexp_setinstvar (lab, snewval) ->
+ begin try
+ let (path, desc) = Env.lookup_value (Longident.Lident lab.txt) env in
+ match desc.val_kind with
+ Val_ivar (Mutable, cl_num) ->
+ let newval =
+ type_expect env snewval (instance env desc.val_type) in
+ let (path_self, _) =
+ Env.lookup_value (Longident.Lident ("self-" ^ cl_num)) env
+ in
+ rue {
+ exp_desc = Texp_setinstvar(path_self, path, lab, newval);
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance_def Predef.type_unit;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Val_ivar _ ->
+ raise(Error(loc, env, Instance_variable_not_mutable(true,lab.txt)))
+ | _ ->
+ raise(Error(loc, env, Instance_variable_not_mutable(false,lab.txt)))
+ with
+ Not_found ->
+ let collect_vars name _path val_desc li =
+ match val_desc.val_kind with
+ | Val_ivar (Mutable, _) -> name::li
+ | _ -> li in
+ let valid_vars = Env.fold_values collect_vars None env [] in
+ raise(Error(loc, env,
+ Unbound_instance_variable (lab.txt, valid_vars)))
+ end
+ | Pexp_override lst ->
+ let _ =
+ List.fold_right
+ (fun (lab, _) l ->
+ if List.exists (fun l -> l.txt = lab.txt) l then
+ raise(Error(loc, env,
+ Value_multiply_overridden lab.txt));
+ lab::l)
+ lst
+ [] in
+ begin match
+ try
+ Env.lookup_value (Longident.Lident "selfpat-*") env,
+ Env.lookup_value (Longident.Lident "self-*") env
+ with Not_found ->
+ raise(Error(loc, env, Outside_class))
+ with
+ (_, {val_type = self_ty; val_kind = Val_self (_, vars, _, _)}),
+ (path_self, _) ->
+ let type_override (lab, snewval) =
+ begin try
+ let (id, _, _, ty) = Vars.find lab.txt !vars in
+ (Path.Pident id, lab, type_expect env snewval (instance env ty))
+ with
+ Not_found ->
+ let vars = Vars.fold (fun var _ li -> var::li) !vars [] in
+ raise(Error(loc, env,
+ Unbound_instance_variable (lab.txt, vars)))
+ end
+ in
+ let modifs = List.map type_override lst in
+ rue {
+ exp_desc = Texp_override(path_self, modifs);
+ exp_loc = loc; exp_extra = [];
+ exp_type = self_ty;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | _ ->
+ assert false
+ end
+ | Pexp_letmodule(name, smodl, sbody) ->
+ let ty = newvar() in
+ (* remember original level *)
+ begin_def ();
+ Ident.set_current_time ty.level;
+ let context = Typetexp.narrow () in
+ let modl = !type_module env smodl in
+ let (id, new_env) = Env.enter_module name.txt modl.mod_type env in
+ Ctype.init_def(Ident.current_time());
+ Typetexp.widen context;
+ let body = type_expect new_env sbody ty_expected in
+ (* go back to original level *)
+ end_def ();
+ (* Unification of body.exp_type with the fresh variable ty
+ fails if and only if the prefix condition is violated,
+ i.e. if generative types rooted at id show up in the
+ type body.exp_type. Thus, this unification enforces the
+ scoping condition on "let module". *)
+ begin try
+ Ctype.unify_var new_env ty body.exp_type
+ with Unify _ ->
+ raise(Error(loc, env, Scoping_let_module(name.txt, body.exp_type)))
+ end;
+ re {
+ exp_desc = Texp_letmodule(id, name, modl, body);
+ exp_loc = loc; exp_extra = [];
+ exp_type = ty;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_assert (e) ->
+ let cond = type_expect env e Predef.type_bool in
+ let exp_type =
+ match cond.exp_desc with
+ | Texp_construct(_, {cstr_name="false"}, _) ->
+ instance env ty_expected
+ | _ ->
+ instance_def Predef.type_unit
+ in
+ rue {
+ exp_desc = Texp_assert cond;
+ exp_loc = loc; exp_extra = [];
+ exp_type;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env;
+ }
+ | Pexp_lazy e ->
+ let ty = newgenvar () in
+ let to_unify = Predef.type_lazy_t ty in
+ unify_exp_types loc env to_unify ty_expected;
+ let arg = type_expect env e ty in
+ re {
+ exp_desc = Texp_lazy arg;
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance env ty_expected;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env;
+ }
+ | Pexp_object s ->
+ let desc, sign, meths = !type_object env loc s in
+ rue {
+ exp_desc = Texp_object (desc, (*sign,*) meths);
+ exp_loc = loc; exp_extra = [];
+ exp_type = sign.csig_self;
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env;
+ }
+ | Pexp_poly(sbody, sty) ->
+ if !Clflags.principal then begin_def ();
+ let ty, cty =
+ match sty with None -> repr ty_expected, None
+ | Some sty ->
+ let sty = Ast_helper.Typ.force_poly sty in
+ let cty = Typetexp.transl_simple_type env false sty in
+ repr cty.ctyp_type, Some cty
+ in
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure ty
+ end;
+ if sty <> None then
+ unify_exp_types loc env (instance env ty) (instance env ty_expected);
+ let exp =
+ match (expand_head env ty).desc with
+ Tpoly (ty', []) ->
+ let exp = type_expect env sbody ty' in
+ { exp with exp_type = instance env ty }
+ | Tpoly (ty', tl) ->
+ (* One more level to generalize locally *)
+ begin_def ();
+ if !Clflags.principal then begin_def ();
+ let vars, ty'' = instance_poly true tl ty' in
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure ty''
+ end;
+ let exp = type_expect env sbody ty'' in
+ end_def ();
+ check_univars env false "method" exp ty_expected vars;
+ { exp with exp_type = instance env ty }
+ | Tvar _ ->
+ let exp = type_exp env sbody in
+ let exp = {exp with exp_type = newty (Tpoly (exp.exp_type, []))} in
+ unify_exp env exp ty;
+ exp
+ | _ -> assert false
+ in
+ re { exp with exp_extra =
+ (Texp_poly cty, loc, sexp.pexp_attributes) :: exp.exp_extra }
+ | Pexp_newtype(name, sbody) ->
+ let ty = newvar () in
+ (* remember original level *)
+ begin_def ();
+ (* Create a fake abstract type declaration for name. *)
+ let level = get_current_level () in
+ let decl = {
+ type_params = [];
+ type_arity = 0;
+ type_kind = Type_abstract;
+ type_private = Public;
+ type_manifest = None;
+ type_variance = [];
+ type_newtype_level = Some (level, level);
+ type_loc = loc;
+ type_attributes = [];
+ }
+ in
+ Ident.set_current_time ty.level;
+ let (id, new_env) = Env.enter_type name decl env in
+ Ctype.init_def(Ident.current_time());
+
+ let body = type_exp new_env sbody in
+ (* Replace every instance of this type constructor in the resulting
+ type. *)
+ let seen = Hashtbl.create 8 in
+ let rec replace t =
+ if Hashtbl.mem seen t.id then ()
+ else begin
+ Hashtbl.add seen t.id ();
+ match t.desc with
+ | Tconstr (Path.Pident id', _, _) when id == id' -> link_type t ty
+ | _ -> Btype.iter_type_expr replace t
+ end
+ in
+ let ety = Subst.type_expr Subst.identity body.exp_type in
+ replace ety;
+ (* back to original level *)
+ end_def ();
+ (* lower the levels of the result type *)
+ (* unify_var env ty ety; *)
+
+ (* non-expansive if the body is non-expansive, so we don't introduce
+ any new extra node in the typed AST. *)
+ rue { body with exp_loc = loc; exp_type = ety;
+ exp_extra =
+ (Texp_newtype name, loc, sexp.pexp_attributes) :: body.exp_extra }
+ | Pexp_pack m ->
+ let (p, nl, tl) =
+ match Ctype.expand_head env (instance env ty_expected) with
+ {desc = Tpackage (p, nl, tl)} ->
+ if !Clflags.principal &&
+ (Ctype.expand_head env ty_expected).level < Btype.generic_level
+ then
+ Location.prerr_warning loc
+ (Warnings.Not_principal "this module packing");
+ (p, nl, tl)
+ | {desc = Tvar _} ->
+ raise (Error (loc, env, Cannot_infer_signature))
+ | _ ->
+ raise (Error (loc, env, Not_a_packed_module ty_expected))
+ in
+ let (modl, tl') = !type_package env m p nl tl in
+ rue {
+ exp_desc = Texp_pack modl;
+ exp_loc = loc; exp_extra = [];
+ exp_type = newty (Tpackage (p, nl, tl'));
+ exp_attributes = sexp.pexp_attributes;
+ exp_env = env }
+ | Pexp_open (ovf, lid, e) ->
+ let (path, newenv) = !type_open ovf env sexp.pexp_loc lid in
+ let exp = type_expect newenv e ty_expected in
+ { exp with
+ exp_extra = (Texp_open (ovf, path, lid, newenv), loc,
+ sexp.pexp_attributes) ::
+ exp.exp_extra;
+ }
+ | Pexp_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+and type_function ?in_function loc attrs env ty_expected l caselist =
+ let (loc_fun, ty_fun) =
+ match in_function with Some p -> p
+ | None -> (loc, instance env ty_expected)
+ in
+ let separate = !Clflags.principal || Env.has_local_constraints env in
+ if separate then begin_def ();
+ let (ty_arg, ty_res) =
+ try filter_arrow env (instance env ty_expected) l
+ with Unify _ ->
+ match expand_head env ty_expected with
+ {desc = Tarrow _} as ty ->
+ raise(Error(loc, env, Abstract_wrong_label(l, ty)))
+ | _ ->
+ raise(Error(loc_fun, env,
+ Too_many_arguments (in_function <> None, ty_fun)))
+ in
+ let ty_arg =
+ if is_optional l then
+ let tv = newvar() in
+ begin
+ try unify env ty_arg (type_option tv)
+ with Unify _ -> assert false
+ end;
+ type_option tv
+ else ty_arg
+ in
+ if separate then begin
+ end_def ();
+ generalize_structure ty_arg;
+ generalize_structure ty_res
+ end;
+ let cases, partial =
+ type_cases ~in_function:(loc_fun,ty_fun) env ty_arg ty_res
+ true loc caselist in
+ let not_function ty =
+ let ls, tvar = list_labels env ty in
+ ls = [] && not tvar
+ in
+ if is_optional l && not_function ty_res then
+ Location.prerr_warning (List.hd cases).c_lhs.pat_loc
+ Warnings.Unerasable_optional_argument;
+ re {
+ exp_desc = Texp_function(l,cases, partial);
+ exp_loc = loc; exp_extra = [];
+ exp_type = instance env (newgenty (Tarrow(l, ty_arg, ty_res, Cok)));
+ exp_attributes = attrs;
+ exp_env = env }
+
+
+and type_label_access env loc srecord lid =
+ if !Clflags.principal then begin_def ();
+ let record = type_exp ~recarg:Allowed env srecord in
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure record.exp_type
+ end;
+ let ty_exp = record.exp_type in
+ let opath =
+ try
+ let (p0, p,_) = extract_concrete_record env ty_exp in
+ Some(p0, p, ty_exp.level = generic_level || not !Clflags.principal)
+ with Not_found -> None
+ in
+ let labels = Typetexp.find_all_labels env lid.loc lid.txt in
+ let label =
+ wrap_disambiguate "This expression has" ty_exp
+ (Label.disambiguate lid env opath) labels in
+ (record, label, opath)
+
+(* Typing format strings for printing or reading.
+ These formats are used by functions in modules Printf, Format, and Scanf.
+ (Handling of * modifiers contributed by Thorsten Ohl.) *)
+
+and type_format loc str env =
+ let loc = {loc with Location.loc_ghost = true} in
+ try
+ CamlinternalFormatBasics.(CamlinternalFormat.(
+ let mk_exp_loc pexp_desc = {
+ pexp_desc = pexp_desc;
+ pexp_loc = loc;
+ pexp_attributes = [];
+ } and mk_lid_loc lid = {
+ txt = lid;
+ loc = loc;
+ } in
+ let mk_constr name args =
+ let lid = Longident.(Ldot(Lident "CamlinternalFormatBasics", name)) in
+ let arg = match args with
+ | [] -> None
+ | [ e ] -> Some e
+ | _ :: _ :: _ -> Some (mk_exp_loc (Pexp_tuple args)) in
+ mk_exp_loc (Pexp_construct (mk_lid_loc lid, arg)) in
+ let mk_cst cst = mk_exp_loc (Pexp_constant cst) in
+ let mk_int n = mk_cst (Const_int n)
+ and mk_string str = mk_cst (Const_string (str, None))
+ and mk_char chr = mk_cst (Const_char chr) in
+ let rec mk_formatting_lit fmting = match fmting with
+ | Close_box ->
+ mk_constr "Close_box" []
+ | Close_tag ->
+ mk_constr "Close_tag" []
+ | Break (org, ns, ni) ->
+ mk_constr "Break" [ mk_string org; mk_int ns; mk_int ni ]
+ | FFlush ->
+ mk_constr "FFlush" []
+ | Force_newline ->
+ mk_constr "Force_newline" []
+ | Flush_newline ->
+ mk_constr "Flush_newline" []
+ | Magic_size (org, sz) ->
+ mk_constr "Magic_size" [ mk_string org; mk_int sz ]
+ | Escaped_at ->
+ mk_constr "Escaped_at" []
+ | Escaped_percent ->
+ mk_constr "Escaped_percent" []
+ | Scan_indic c ->
+ mk_constr "Scan_indic" [ mk_char c ]
+ and mk_formatting_gen : type a b c d e f .
+ (a, b, c, d, e, f) formatting_gen -> Parsetree.expression =
+ fun fmting -> match fmting with
+ | Open_tag (Format (fmt', str')) ->
+ mk_constr "Open_tag" [ mk_format fmt' str' ]
+ | Open_box (Format (fmt', str')) ->
+ mk_constr "Open_box" [ mk_format fmt' str' ]
+ and mk_format : type a b c d e f .
+ (a, b, c, d, e, f) CamlinternalFormatBasics.fmt -> string ->
+ Parsetree.expression = fun fmt str ->
+ mk_constr "Format" [ mk_fmt fmt; mk_string str ]
+ and mk_side side = match side with
+ | Left -> mk_constr "Left" []
+ | Right -> mk_constr "Right" []
+ | Zeros -> mk_constr "Zeros" []
+ and mk_iconv iconv = match iconv with
+ | Int_d -> mk_constr "Int_d" [] | Int_pd -> mk_constr "Int_pd" []
+ | Int_sd -> mk_constr "Int_sd" [] | Int_i -> mk_constr "Int_i" []
+ | Int_pi -> mk_constr "Int_pi" [] | Int_si -> mk_constr "Int_si" []
+ | Int_x -> mk_constr "Int_x" [] | Int_Cx -> mk_constr "Int_Cx" []
+ | Int_X -> mk_constr "Int_X" [] | Int_CX -> mk_constr "Int_CX" []
+ | Int_o -> mk_constr "Int_o" [] | Int_Co -> mk_constr "Int_Co" []
+ | Int_u -> mk_constr "Int_u" []
+ and mk_fconv fconv = match fconv with
+ | Float_f -> mk_constr "Float_f" []
+ | Float_pf -> mk_constr "Float_pf" []
+ | Float_sf -> mk_constr "Float_sf" []
+ | Float_e -> mk_constr "Float_e" []
+ | Float_pe -> mk_constr "Float_pe" []
+ | Float_se -> mk_constr "Float_se" []
+ | Float_E -> mk_constr "Float_E" []
+ | Float_pE -> mk_constr "Float_pE" []
+ | Float_sE -> mk_constr "Float_sE" []
+ | Float_g -> mk_constr "Float_g" []
+ | Float_pg -> mk_constr "Float_pg" []
+ | Float_sg -> mk_constr "Float_sg" []
+ | Float_G -> mk_constr "Float_G" []
+ | Float_pG -> mk_constr "Float_pG" []
+ | Float_sG -> mk_constr "Float_sG" []
+ | Float_F -> mk_constr "Float_F" []
+ and mk_counter cnt = match cnt with
+ | Line_counter -> mk_constr "Line_counter" []
+ | Char_counter -> mk_constr "Char_counter" []
+ | Token_counter -> mk_constr "Token_counter" []
+ and mk_int_opt n_opt = match n_opt with
+ | None ->
+ let lid_loc = mk_lid_loc (Longident.Lident "None") in
+ mk_exp_loc (Pexp_construct (lid_loc, None))
+ | Some n ->
+ let lid_loc = mk_lid_loc (Longident.Lident "Some") in
+ mk_exp_loc (Pexp_construct (lid_loc, Some (mk_int n)))
+ and mk_fmtty : type a b c d e f g h i j k l .
+ (a, b, c, d, e, f, g, h, i, j, k, l) fmtty_rel -> Parsetree.expression
+ =
+ fun fmtty -> match fmtty with
+ | Char_ty rest -> mk_constr "Char_ty" [ mk_fmtty rest ]
+ | String_ty rest -> mk_constr "String_ty" [ mk_fmtty rest ]
+ | Int_ty rest -> mk_constr "Int_ty" [ mk_fmtty rest ]
+ | Int32_ty rest -> mk_constr "Int32_ty" [ mk_fmtty rest ]
+ | Nativeint_ty rest -> mk_constr "Nativeint_ty" [ mk_fmtty rest ]
+ | Int64_ty rest -> mk_constr "Int64_ty" [ mk_fmtty rest ]
+ | Float_ty rest -> mk_constr "Float_ty" [ mk_fmtty rest ]
+ | Bool_ty rest -> mk_constr "Bool_ty" [ mk_fmtty rest ]
+ | Alpha_ty rest -> mk_constr "Alpha_ty" [ mk_fmtty rest ]
+ | Theta_ty rest -> mk_constr "Theta_ty" [ mk_fmtty rest ]
+ | Any_ty rest -> mk_constr "Any_ty" [ mk_fmtty rest ]
+ | Reader_ty rest -> mk_constr "Reader_ty" [ mk_fmtty rest ]
+ | Ignored_reader_ty rest ->
+ mk_constr "Ignored_reader_ty" [ mk_fmtty rest ]
+ | Format_arg_ty (sub_fmtty, rest) ->
+ mk_constr "Format_arg_ty" [ mk_fmtty sub_fmtty; mk_fmtty rest ]
+ | Format_subst_ty (sub_fmtty1, sub_fmtty2, rest) ->
+ mk_constr "Format_subst_ty"
+ [ mk_fmtty sub_fmtty1; mk_fmtty sub_fmtty2; mk_fmtty rest ]
+ | End_of_fmtty -> mk_constr "End_of_fmtty" []
+ and mk_ignored : type a b c d e f .
+ (a, b, c, d, e, f) ignored -> Parsetree.expression =
+ fun ign -> match ign with
+ | Ignored_char ->
+ mk_constr "Ignored_char" []
+ | Ignored_caml_char ->
+ mk_constr "Ignored_caml_char" []
+ | Ignored_string pad_opt ->
+ mk_constr "Ignored_string" [ mk_int_opt pad_opt ]
+ | Ignored_caml_string pad_opt ->
+ mk_constr "Ignored_caml_string" [ mk_int_opt pad_opt ]
+ | Ignored_int (iconv, pad_opt) ->
+ mk_constr "Ignored_int" [ mk_iconv iconv; mk_int_opt pad_opt ]
+ | Ignored_int32 (iconv, pad_opt) ->
+ mk_constr "Ignored_int32" [ mk_iconv iconv; mk_int_opt pad_opt ]
+ | Ignored_nativeint (iconv, pad_opt) ->
+ mk_constr "Ignored_nativeint" [ mk_iconv iconv; mk_int_opt pad_opt ]
+ | Ignored_int64 (iconv, pad_opt) ->
+ mk_constr "Ignored_int64" [ mk_iconv iconv; mk_int_opt pad_opt ]
+ | Ignored_float (pad_opt, prec_opt) ->
+ mk_constr "Ignored_float" [ mk_int_opt pad_opt; mk_int_opt prec_opt ]
+ | Ignored_bool ->
+ mk_constr "Ignored_bool" []
+ | Ignored_format_arg (pad_opt, fmtty) ->
+ mk_constr "Ignored_format_arg" [ mk_int_opt pad_opt; mk_fmtty fmtty ]
+ | Ignored_format_subst (pad_opt, fmtty) ->
+ mk_constr "Ignored_format_subst" [
+ mk_int_opt pad_opt; mk_fmtty fmtty ]
+ | Ignored_reader ->
+ mk_constr "Ignored_reader" []
+ | Ignored_scan_char_set (width_opt, char_set) ->
+ mk_constr "Ignored_scan_char_set" [
+ mk_int_opt width_opt; mk_string char_set ]
+ | Ignored_scan_get_counter counter ->
+ mk_constr "Ignored_scan_get_counter" [
+ mk_counter counter
+ ]
+ | Ignored_scan_next_char ->
+ mk_constr "Ignored_scan_next_char" []
+ and mk_padding : type x y . (x, y) padding -> Parsetree.expression =
+ fun pad -> match pad with
+ | No_padding -> mk_constr "No_padding" []
+ | Lit_padding (s, w) -> mk_constr "Lit_padding" [ mk_side s; mk_int w ]
+ | Arg_padding s -> mk_constr "Arg_padding" [ mk_side s ]
+ and mk_precision : type x y . (x, y) precision -> Parsetree.expression =
+ fun prec -> match prec with
+ | No_precision -> mk_constr "No_precision" []
+ | Lit_precision w -> mk_constr "Lit_precision" [ mk_int w ]
+ | Arg_precision -> mk_constr "Arg_precision" []
+ and mk_fmt : type a b c d e f .
+ (a, b, c, d, e, f) fmt -> Parsetree.expression =
+ fun fmt -> match fmt with
+ | Char rest ->
+ mk_constr "Char" [ mk_fmt rest ]
+ | Caml_char rest ->
+ mk_constr "Caml_char" [ mk_fmt rest ]
+ | String (pad, rest) ->
+ mk_constr "String" [ mk_padding pad; mk_fmt rest ]
+ | Caml_string (pad, rest) ->
+ mk_constr "Caml_string" [ mk_padding pad; mk_fmt rest ]
+ | Int (iconv, pad, prec, rest) ->
+ mk_constr "Int" [
+ mk_iconv iconv; mk_padding pad; mk_precision prec; mk_fmt rest ]
+ | Int32 (iconv, pad, prec, rest) ->
+ mk_constr "Int32" [
+ mk_iconv iconv; mk_padding pad; mk_precision prec; mk_fmt rest ]
+ | Nativeint (iconv, pad, prec, rest) ->
+ mk_constr "Nativeint" [
+ mk_iconv iconv; mk_padding pad; mk_precision prec; mk_fmt rest ]
+ | Int64 (iconv, pad, prec, rest) ->
+ mk_constr "Int64" [
+ mk_iconv iconv; mk_padding pad; mk_precision prec; mk_fmt rest ]
+ | Float (fconv, pad, prec, rest) ->
+ mk_constr "Float" [
+ mk_fconv fconv; mk_padding pad; mk_precision prec; mk_fmt rest ]
+ | Bool rest ->
+ mk_constr "Bool" [ mk_fmt rest ]
+ | Flush rest ->
+ mk_constr "Flush" [ mk_fmt rest ]
+ | String_literal (s, rest) ->
+ mk_constr "String_literal" [ mk_string s; mk_fmt rest ]
+ | Char_literal (c, rest) ->
+ mk_constr "Char_literal" [ mk_char c; mk_fmt rest ]
+ | Format_arg (pad_opt, fmtty, rest) ->
+ mk_constr "Format_arg" [
+ mk_int_opt pad_opt; mk_fmtty fmtty; mk_fmt rest ]
+ | Format_subst (pad_opt, fmtty, rest) ->
+ mk_constr "Format_subst" [
+ mk_int_opt pad_opt; mk_fmtty fmtty; mk_fmt rest ]
+ | Alpha rest ->
+ mk_constr "Alpha" [ mk_fmt rest ]
+ | Theta rest ->
+ mk_constr "Theta" [ mk_fmt rest ]
+ | Formatting_lit (fmting, rest) ->
+ mk_constr "Formatting_lit" [ mk_formatting_lit fmting; mk_fmt rest ]
+ | Formatting_gen (fmting, rest) ->
+ mk_constr "Formatting_gen" [ mk_formatting_gen fmting; mk_fmt rest ]
+ | Reader rest ->
+ mk_constr "Reader" [ mk_fmt rest ]
+ | Scan_char_set (width_opt, char_set, rest) ->
+ mk_constr "Scan_char_set" [
+ mk_int_opt width_opt; mk_string char_set; mk_fmt rest ]
+ | Scan_get_counter (cnt, rest) ->
+ mk_constr "Scan_get_counter" [ mk_counter cnt; mk_fmt rest ]
+ | Scan_next_char rest ->
+ mk_constr "Scan_next_char" [ mk_fmt rest ]
+ | Ignored_param (ign, rest) ->
+ mk_constr "Ignored_param" [ mk_ignored ign; mk_fmt rest ]
+ | End_of_format ->
+ mk_constr "End_of_format" []
+ | Custom _ ->
+ (* Custom formatters have no syntax so they will never appear
+ in formats parsed from strings. *)
+ assert false
+ in
+ let legacy_behavior = not !Clflags.strict_formats in
+ let Fmt_EBB fmt = fmt_ebb_of_string ~legacy_behavior str in
+ mk_constr "Format" [ mk_fmt fmt; mk_string str ]
+ ))
+ with Failure msg ->
+ raise (Error (loc, env, Invalid_format msg))
+
+and type_label_exp create env loc ty_expected
+ (lid, label, sarg) =
+ (* Here also ty_expected may be at generic_level *)
+ begin_def ();
+ let separate = !Clflags.principal || Env.has_local_constraints env in
+ if separate then (begin_def (); begin_def ());
+ let (vars, ty_arg, ty_res) = instance_label true label in
+ if separate then begin
+ end_def ();
+ (* Generalize label information *)
+ generalize_structure ty_arg;
+ generalize_structure ty_res
+ end;
+ begin try
+ unify env (instance_def ty_res) (instance env ty_expected)
+ with Unify trace ->
+ raise (Error(lid.loc, env, Label_mismatch(lid.txt, trace)))
+ end;
+ (* Instantiate so that we can generalize internal nodes *)
+ let ty_arg = instance_def ty_arg in
+ if separate then begin
+ end_def ();
+ (* Generalize information merged from ty_expected *)
+ generalize_structure ty_arg
+ end;
+ if label.lbl_private = Private then
+ if create then
+ raise (Error(loc, env, Private_type ty_expected))
+ else
+ raise (Error(lid.loc, env, Private_label(lid.txt, ty_expected)));
+ let arg =
+ let snap = if vars = [] then None else Some (Btype.snapshot ()) in
+ let arg = type_argument env sarg ty_arg (instance env ty_arg) in
+ end_def ();
+ try
+ check_univars env (vars <> []) "field value" arg label.lbl_arg vars;
+ arg
+ with exn when not (is_nonexpansive arg) -> try
+ (* Try to retype without propagating ty_arg, cf PR#4862 *)
+ may Btype.backtrack snap;
+ begin_def ();
+ let arg = type_exp env sarg in
+ end_def ();
+ generalize_expansive env arg.exp_type;
+ unify_exp env arg ty_arg;
+ check_univars env false "field value" arg label.lbl_arg vars;
+ arg
+ with Error (_, _, Less_general _) as e -> raise e
+ | _ -> raise exn (* In case of failure return the first error *)
+ in
+ (lid, label, {arg with exp_type = instance env arg.exp_type})
+
+and type_argument ?recarg env sarg ty_expected' ty_expected =
+ (* ty_expected' may be generic *)
+ let no_labels ty =
+ let ls, tvar = list_labels env ty in
+ not tvar && List.for_all ((=) Nolabel) ls
+ in
+ let rec is_inferred sexp =
+ match sexp.pexp_desc with
+ Pexp_ident _ | Pexp_apply _ | Pexp_field _ | Pexp_constraint _
+ | Pexp_coerce _ | Pexp_send _ | Pexp_new _ -> true
+ | Pexp_sequence (_, e) | Pexp_open (_, _, e) -> is_inferred e
+ | Pexp_ifthenelse (_, e1, Some e2) -> is_inferred e1 && is_inferred e2
+ | _ -> false
+ in
+ match expand_head env ty_expected' with
+ {desc = Tarrow(Nolabel,ty_arg,ty_res,_); level = lv}
+ when is_inferred sarg ->
+ (* apply optional arguments when expected type is "" *)
+ (* we must be very careful about not breaking the semantics *)
+ if !Clflags.principal then begin_def ();
+ let texp = type_exp env sarg in
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure texp.exp_type
+ end;
+ let rec make_args args ty_fun =
+ match (expand_head env ty_fun).desc with
+ | Tarrow (l,ty_arg,ty_fun,_) when is_optional l ->
+ let ty = option_none (instance env ty_arg) sarg.pexp_loc in
+ make_args ((l, Some ty, Optional) :: args) ty_fun
+ | Tarrow (l,_,ty_res',_) when l = Nolabel || !Clflags.classic ->
+ List.rev args, ty_fun, no_labels ty_res'
+ | Tvar _ -> List.rev args, ty_fun, false
+ | _ -> [], texp.exp_type, false
+ in
+ let args, ty_fun', simple_res = make_args [] texp.exp_type in
+ let warn = !Clflags.principal &&
+ (lv <> generic_level || (repr ty_fun').level <> generic_level)
+ and texp = {texp with exp_type = instance env texp.exp_type}
+ and ty_fun = instance env ty_fun' in
+ if not (simple_res || no_labels ty_res) then begin
+ unify_exp env texp ty_expected;
+ texp
+ end else begin
+ unify_exp env {texp with exp_type = ty_fun} ty_expected;
+ if args = [] then texp else
+ (* eta-expand to avoid side effects *)
+ let var_pair name ty =
+ let id = Ident.create name in
+ {pat_desc = Tpat_var (id, mknoloc name); pat_type = ty;pat_extra=[];
+ pat_attributes = [];
+ pat_loc = Location.none; pat_env = env},
+ {exp_type = ty; exp_loc = Location.none; exp_env = env;
+ exp_extra = []; exp_attributes = [];
+ exp_desc =
+ Texp_ident(Path.Pident id, mknoloc (Longident.Lident name),
+ {val_type = ty; val_kind = Val_reg;
+ val_attributes = [];
+ Types.val_loc = Location.none})}
+ in
+ let eta_pat, eta_var = var_pair "eta" ty_arg in
+ let func texp =
+ let e =
+ {texp with exp_type = ty_res; exp_desc =
+ Texp_apply
+ (texp,
+ args @ [Nolabel, Some eta_var, Required])}
+ in
+ { texp with exp_type = ty_fun; exp_desc =
+ Texp_function(Nolabel, [case eta_pat e], Total) }
+ in
+ Location.prerr_warning texp.exp_loc
+ (Warnings.Eliminated_optional_arguments
+ (List.map (fun (l, _, _) -> Printtyp.string_of_label l) args));
+ if warn then Location.prerr_warning texp.exp_loc
+ (Warnings.Without_principality "eliminated optional argument");
+ if is_nonexpansive texp then func texp else
+ (* let-expand to have side effects *)
+ let let_pat, let_var = var_pair "arg" texp.exp_type in
+ re { texp with exp_type = ty_fun; exp_desc =
+ Texp_let (Nonrecursive,
+ [{vb_pat=let_pat; vb_expr=texp; vb_attributes=[];
+ vb_loc=Location.none;
+ }],
+ func let_var) }
+ end
+ | _ ->
+ let texp = type_expect ?recarg env sarg ty_expected' in
+ unify_exp env texp ty_expected;
+ texp
+
+and type_application env funct sargs =
+ (* funct.exp_type may be generic *)
+ let result_type omitted ty_fun =
+ List.fold_left
+ (fun ty_fun (l,ty,lv) -> newty2 lv (Tarrow(l,ty,ty_fun,Cok)))
+ ty_fun omitted
+ in
+ let has_label l ty_fun =
+ let ls, tvar = list_labels env ty_fun in
+ tvar || List.mem l ls
+ in
+ let ignored = ref [] in
+ let rec type_unknown_args
+ (args :
+ (Asttypes.arg_label * (unit -> Typedtree.expression) option *
+ Typedtree.optional) list)
+ omitted ty_fun = function
+ [] ->
+ (List.map
+ (function l, None, x -> l, None, x
+ | l, Some f, x -> l, Some (f ()), x)
+ (List.rev args),
+ instance env (result_type omitted ty_fun))
+ | (l1, sarg1) :: sargl ->
+ let (ty1, ty2) =
+ let ty_fun = expand_head env ty_fun in
+ match ty_fun.desc with
+ Tvar _ ->
+ let t1 = newvar () and t2 = newvar () in
+ let not_identity = function
+ Texp_ident(_,_,{val_kind=Val_prim
+ {Primitive.prim_name="%identity"}}) ->
+ false
+ | _ -> true
+ in
+ if ty_fun.level >= t1.level && not_identity funct.exp_desc then
+ Location.prerr_warning sarg1.pexp_loc Warnings.Unused_argument;
+ unify env ty_fun (newty (Tarrow(l1,t1,t2,Clink(ref Cunknown))));
+ (t1, t2)
+ | Tarrow (l,t1,t2,_) when l = l1
+ || !Clflags.classic && l1 = Nolabel && not (is_optional l) ->
+ (t1, t2)
+ | td ->
+ let ty_fun =
+ match td with Tarrow _ -> newty td | _ -> ty_fun in
+ let ty_res = result_type (omitted @ !ignored) ty_fun in
+ match ty_res.desc with
+ Tarrow _ ->
+ if (!Clflags.classic || not (has_label l1 ty_fun)) then
+ raise (Error(sarg1.pexp_loc, env,
+ Apply_wrong_label(l1, ty_res)))
+ else
+ raise (Error(funct.exp_loc, env, Incoherent_label_order))
+ | _ ->
+ raise(Error(funct.exp_loc, env, Apply_non_function
+ (expand_head env funct.exp_type)))
+ in
+ let optional = if is_optional l1 then Optional else Required in
+ let arg1 () =
+ let arg1 = type_expect env sarg1 ty1 in
+ if optional = Optional then
+ unify_exp env arg1 (type_option(newvar()));
+ arg1
+ in
+ type_unknown_args ((l1, Some arg1, optional) :: args) omitted ty2 sargl
+ in
+ let ignore_labels =
+ !Clflags.classic ||
+ begin
+ let ls, tvar = list_labels env funct.exp_type in
+ not tvar &&
+ let labels = List.filter (fun l -> not (is_optional l)) ls in
+ List.length labels = List.length sargs &&
+ List.for_all (fun (l,_) -> l = Nolabel) sargs &&
+ List.exists (fun l -> l <> Nolabel) labels &&
+ (Location.prerr_warning
+ funct.exp_loc
+ (Warnings.Labels_omitted
+ (List.map Printtyp.string_of_label
+ (List.filter ((<>) Nolabel) labels)));
+ true)
+ end
+ in
+ let warned = ref false in
+ let rec type_args args omitted ty_fun ty_fun0 ty_old sargs more_sargs =
+ match expand_head env ty_fun, expand_head env ty_fun0 with
+ {desc=Tarrow (l, ty, ty_fun, com); level=lv} as ty_fun',
+ {desc=Tarrow (_, ty0, ty_fun0, _)}
+ when (sargs <> [] || more_sargs <> []) && commu_repr com = Cok ->
+ let may_warn loc w =
+ if not !warned && !Clflags.principal && lv <> generic_level
+ then begin
+ warned := true;
+ Location.prerr_warning loc w
+ end
+ in
+ let name = label_name l
+ and optional = if is_optional l then Optional else Required in
+ let sargs, more_sargs, arg =
+ if ignore_labels && not (is_optional l) then begin
+ (* In classic mode, omitted = [] *)
+ match sargs, more_sargs with
+ (l', sarg0) :: _, _ ->
+ raise(Error(sarg0.pexp_loc, env,
+ Apply_wrong_label(l', ty_old)))
+ | _, (l', sarg0) :: more_sargs ->
+ if l <> l' && l' <> Nolabel then
+ raise(Error(sarg0.pexp_loc, env,
+ Apply_wrong_label(l', ty_fun')))
+ else
+ ([], more_sargs,
+ Some (fun () -> type_argument env sarg0 ty ty0))
+ | _ ->
+ assert false
+ end else try
+ let (l', sarg0, sargs, more_sargs) =
+ try
+ let (l', sarg0, sargs1, sargs2) = extract_label name sargs in
+ if sargs1 <> [] then
+ may_warn sarg0.pexp_loc
+ (Warnings.Not_principal "commuting this argument");
+ (l', sarg0, sargs1 @ sargs2, more_sargs)
+ with Not_found ->
+ let (l', sarg0, sargs1, sargs2) =
+ extract_label name more_sargs in
+ if sargs1 <> [] || sargs <> [] then
+ may_warn sarg0.pexp_loc
+ (Warnings.Not_principal "commuting this argument");
+ (l', sarg0, sargs @ sargs1, sargs2)
+ in
+ if optional = Required && is_optional l' then
+ Location.prerr_warning sarg0.pexp_loc
+ (Warnings.Nonoptional_label (Printtyp.string_of_label l));
+ sargs, more_sargs,
+ if optional = Required || is_optional l' then
+ Some (fun () -> type_argument env sarg0 ty ty0)
+ else begin
+ may_warn sarg0.pexp_loc
+ (Warnings.Not_principal "using an optional argument here");
+ Some (fun () -> option_some (type_argument env sarg0
+ (extract_option_type env ty)
+ (extract_option_type env ty0)))
+ end
+ with Not_found ->
+ sargs, more_sargs,
+ if optional = Optional &&
+ (List.mem_assoc Nolabel sargs
+ || List.mem_assoc Nolabel more_sargs)
+ then begin
+ may_warn funct.exp_loc
+ (Warnings.Without_principality "eliminated optional argument");
+ ignored := (l,ty,lv) :: !ignored;
+ Some (fun () -> option_none (instance env ty) Location.none)
+ end else begin
+ may_warn funct.exp_loc
+ (Warnings.Without_principality "commuted an argument");
+ None
+ end
+ in
+ let omitted =
+ if arg = None then (l,ty,lv) :: omitted else omitted in
+ let ty_old = if sargs = [] then ty_fun else ty_old in
+ type_args ((l,arg,optional)::args) omitted ty_fun ty_fun0
+ ty_old sargs more_sargs
+ | _ ->
+ match sargs with
+ (l, sarg0) :: _ when ignore_labels ->
+ raise(Error(sarg0.pexp_loc, env,
+ Apply_wrong_label(l, ty_old)))
+ | _ ->
+ type_unknown_args args omitted ty_fun0
+ (sargs @ more_sargs)
+ in
+ match funct.exp_desc, sargs with
+ (* Special case for ignore: avoid discarding warning *)
+ Texp_ident (_, _, {val_kind=Val_prim{Primitive.prim_name="%ignore"}}),
+ [Nolabel, sarg] ->
+ let ty_arg, ty_res =
+ filter_arrow env (instance env funct.exp_type) Nolabel
+ in
+ let exp = type_expect env sarg ty_arg in
+ begin match (expand_head env exp.exp_type).desc with
+ | Tarrow _ ->
+ Location.prerr_warning exp.exp_loc Warnings.Partial_application
+ | Tvar _ ->
+ add_delayed_check (fun () -> check_application_result env false exp)
+ | _ -> ()
+ end;
+ ([Nolabel, Some exp, Required], ty_res)
+ | _ ->
+ let ty = funct.exp_type in
+ if ignore_labels then
+ type_args [] [] ty (instance env ty) ty [] sargs
+ else
+ type_args [] [] ty (instance env ty) ty sargs []
+
+and type_construct env loc lid sarg ty_expected attrs =
+ let opath =
+ try
+ let (p0, p,_) = extract_concrete_variant env ty_expected in
+ Some(p0, p, ty_expected.level = generic_level || not !Clflags.principal)
+ with Not_found -> None
+ in
+ let constrs = Typetexp.find_all_constructors env lid.loc lid.txt in
+ let constr =
+ wrap_disambiguate "This variant expression is expected to have" ty_expected
+ (Constructor.disambiguate lid env opath) constrs in
+ Env.mark_constructor Env.Positive env (Longident.last lid.txt) constr;
+ Typetexp.check_deprecated loc constr.cstr_attributes constr.cstr_name;
+ let sargs =
+ match sarg with
+ None -> []
+ | Some {pexp_desc = Pexp_tuple sel} when
+ constr.cstr_arity > 1 || explicit_arity attrs
+ -> sel
+ | Some se -> [se] in
+ if List.length sargs <> constr.cstr_arity then
+ raise(Error(loc, env, Constructor_arity_mismatch
+ (lid.txt, constr.cstr_arity, List.length sargs)));
+ let separate = !Clflags.principal || Env.has_local_constraints env in
+ if separate then (begin_def (); begin_def ());
+ let (ty_args, ty_res) = instance_constructor constr in
+ let texp =
+ re {
+ exp_desc = Texp_construct(lid, constr, []);
+ exp_loc = loc; exp_extra = [];
+ exp_type = ty_res;
+ exp_attributes = attrs;
+ exp_env = env } in
+ if separate then begin
+ end_def ();
+ generalize_structure ty_res;
+ unify_exp env {texp with exp_type = instance_def ty_res}
+ (instance env ty_expected);
+ end_def ();
+ List.iter generalize_structure ty_args;
+ generalize_structure ty_res;
+ end;
+ let ty_args0, ty_res =
+ match instance_list env (ty_res :: ty_args) with
+ t :: tl -> tl, t
+ | _ -> assert false
+ in
+ let texp = {texp with exp_type = ty_res} in
+ if not separate then unify_exp env texp (instance env ty_expected);
+ let recarg =
+ match constr.cstr_inlined with
+ | None -> Rejected
+ | Some _ ->
+ begin match sargs with
+ | [{pexp_desc =
+ Pexp_ident _ |
+ Pexp_record (_, (Some {pexp_desc = Pexp_ident _}| None))}] ->
+ Required
+ | _ ->
+ raise (Error(loc, env, Inlined_record_escape))
+ end
+ in
+ let args =
+ List.map2 (fun e (t,t0) -> type_argument ~recarg env e t t0) sargs
+ (List.combine ty_args ty_args0) in
+ if constr.cstr_private = Private then
+ raise(Error(loc, env, Private_type ty_res));
+ (* NOTE: shouldn't we call "re" on this final expression? -- AF *)
+ { texp with
+ exp_desc = Texp_construct(lid, constr, args) }
+
+(* Typing of statements (expressions whose values are discarded) *)
+
+and type_statement env sexp =
+ let loc = (final_subexpression sexp).pexp_loc in
+ begin_def();
+ let exp = type_exp env sexp in
+ end_def();
+ if !Clflags.strict_sequence then
+ let expected_ty = instance_def Predef.type_unit in
+ unify_exp env exp expected_ty;
+ exp else
+ let ty = expand_head env exp.exp_type and tv = newvar() in
+ begin match ty.desc with
+ | Tarrow _ ->
+ Location.prerr_warning loc Warnings.Partial_application
+ | Tconstr (p, _, _) when Path.same p Predef.path_unit -> ()
+ | Tvar _ when ty.level > tv.level ->
+ Location.prerr_warning loc Warnings.Nonreturning_statement
+ | Tvar _ ->
+ add_delayed_check (fun () -> check_application_result env true exp)
+ | _ ->
+ Location.prerr_warning loc Warnings.Statement_type
+ end;
+ unify_var env tv ty;
+ exp
+
+(* Typing of match cases *)
+
+and type_cases ?in_function env ty_arg ty_res partial_flag loc caselist =
+ (* ty_arg is _fully_ generalized *)
+ let patterns = List.map (fun {pc_lhs=p} -> p) caselist in
+ let erase_either =
+ List.exists contains_polymorphic_variant patterns
+ && contains_variant_either ty_arg
+ and has_gadts = List.exists (contains_gadt env) patterns in
+(* prerr_endline ( if has_gadts then "contains gadt" else "no gadt"); *)
+ let ty_arg =
+ if (has_gadts || erase_either) && not !Clflags.principal
+ then correct_levels ty_arg else ty_arg
+ and ty_res, env =
+ if has_gadts && not !Clflags.principal then
+ correct_levels ty_res, duplicate_ident_types loc caselist env
+ else ty_res, env
+ in
+ let lev, env =
+ if has_gadts then begin
+ (* raise level for existentials *)
+ begin_def ();
+ Ident.set_current_time (get_current_level ());
+ let lev = Ident.current_time () in
+ Ctype.init_def (lev+1000); (* up to 1000 existentials *)
+ (lev, Env.add_gadt_instance_level lev env)
+ end else (get_current_level (), env)
+ in
+(* if has_gadts then
+ Format.printf "lev = %d@.%a@." lev Printtyp.raw_type_expr ty_res; *)
+ begin_def (); (* propagation of the argument *)
+ let ty_arg' = newvar () in
+ let pattern_force = ref [] in
+(* Format.printf "@[%i %i@ %a@]@." lev (get_current_level())
+ Printtyp.raw_type_expr ty_arg; *)
+ let pat_env_list =
+ List.map
+ (fun {pc_lhs; pc_guard; pc_rhs} ->
+ let loc =
+ let open Location in
+ match pc_guard with
+ | None -> pc_rhs.pexp_loc
+ | Some g -> {pc_rhs.pexp_loc with loc_start=g.pexp_loc.loc_start}
+ in
+ if !Clflags.principal then begin_def (); (* propagation of pattern *)
+ let scope = Some (Annot.Idef loc) in
+ let (pat, ext_env, force, unpacks) =
+ let partial =
+ if !Clflags.principal || erase_either
+ then Some false else None in
+ let ty_arg = instance ?partial env ty_arg in
+ type_pattern ~lev env pc_lhs scope ty_arg
+ in
+ pattern_force := force @ !pattern_force;
+ let pat =
+ if !Clflags.principal then begin
+ end_def ();
+ iter_pattern (fun {pat_type=t} -> generalize_structure t) pat;
+ { pat with pat_type = instance env pat.pat_type }
+ end else pat
+ in
+ (pat, (ext_env, unpacks)))
+ caselist in
+ (* Unify cases (delayed to keep it order-free) *)
+ let patl = List.map fst pat_env_list in
+ List.iter (fun pat -> unify_pat env pat ty_arg') patl;
+ (* Check for polymorphic variants to close *)
+ if List.exists has_variants patl then begin
+ Parmatch.pressure_variants env patl;
+ List.iter (iter_pattern finalize_variant) patl
+ end;
+ (* `Contaminating' unifications start here *)
+ List.iter (fun f -> f()) !pattern_force;
+ (* Post-processing and generalization *)
+ List.iter (iter_pattern (fun {pat_type=t} -> unify_var env t (newvar())))
+ patl;
+ List.iter (fun pat -> unify_pat env pat (instance env ty_arg)) patl;
+ end_def ();
+ List.iter (iter_pattern (fun {pat_type=t} -> generalize t)) patl;
+ (* type bodies *)
+ let in_function = if List.length caselist = 1 then in_function else None in
+ let cases =
+ List.map2
+ (fun (pat, (ext_env, unpacks)) {pc_lhs; pc_guard; pc_rhs} ->
+ let sexp = wrap_unpacks pc_rhs unpacks in
+ let ty_res' =
+ if !Clflags.principal then begin
+ begin_def ();
+ let ty = instance ~partial:true env ty_res in
+ end_def ();
+ generalize_structure ty; ty
+ end
+ else if contains_gadt env pc_lhs then correct_levels ty_res
+ else ty_res in
+(* Format.printf "@[%i %i, ty_res' =@ %a@]@." lev (get_current_level())
+ Printtyp.raw_type_expr ty_res'; *)
+ let guard =
+ match pc_guard with
+ | None -> None
+ | Some scond ->
+ Some
+ (type_expect ext_env (wrap_unpacks scond unpacks)
+ Predef.type_bool)
+ in
+ let exp = type_expect ?in_function ext_env sexp ty_res' in
+ {
+ c_lhs = pat;
+ c_guard = guard;
+ c_rhs = {exp with exp_type = instance env ty_res'}
+ }
+ )
+ pat_env_list caselist
+ in
+ if !Clflags.principal || has_gadts then begin
+ let ty_res' = instance env ty_res in
+ List.iter (fun c -> unify_exp env c.c_rhs ty_res') cases
+ end;
+ let partial =
+ if partial_flag then
+ check_partial ~lev env ty_arg loc cases
+ else
+ Partial
+ in
+ add_delayed_check
+ (fun () ->
+ List.iter (fun (pat, (env, _)) -> check_absent_variant env pat)
+ pat_env_list;
+ Parmatch.check_unused env cases);
+ if has_gadts then begin
+ end_def ();
+ (* Ensure that existential types do not escape *)
+ unify_exp_types loc env (instance env ty_res) (newvar ()) ;
+ end;
+ cases, partial
+
+(* Typing of let bindings *)
+
+and type_let ?(check = fun s -> Warnings.Unused_var s)
+ ?(check_strict = fun s -> Warnings.Unused_var_strict s)
+ env rec_flag spat_sexp_list scope allow =
+ let open Ast_helper in
+ begin_def();
+ if !Clflags.principal then begin_def ();
+
+ let is_fake_let =
+ match spat_sexp_list with
+ | [{pvb_expr={pexp_desc=Pexp_match(
+ {pexp_desc=Pexp_ident({ txt = Longident.Lident "*opt*"})},_)}}] ->
+ true (* the fake let-declaration introduced by fun ?(x = e) -> ... *)
+ | _ ->
+ false
+ in
+ let check = if is_fake_let then check_strict else check in
+
+ let spatl =
+ List.map
+ (fun {pvb_pat=spat; pvb_expr=sexp; pvb_attributes=_} ->
+ match spat.ppat_desc, sexp.pexp_desc with
+ (Ppat_any | Ppat_constraint _), _ -> spat
+ | _, Pexp_coerce (_, _, sty)
+ | _, Pexp_constraint (_, sty) when !Clflags.principal ->
+ (* propagate type annotation to pattern,
+ to allow it to be generalized in -principal mode *)
+ Pat.constraint_
+ ~loc:{spat.ppat_loc with Location.loc_ghost=true}
+ spat
+ sty
+ | _ -> spat)
+ spat_sexp_list in
+ let nvs = List.map (fun _ -> newvar ()) spatl in
+ let (pat_list, new_env, force, unpacks) =
+ type_pattern_list env spatl scope nvs allow in
+ let is_recursive = (rec_flag = Recursive) in
+ (* If recursive, first unify with an approximation of the expression *)
+ if is_recursive then
+ List.iter2
+ (fun pat binding ->
+ let pat =
+ match pat.pat_type.desc with
+ | Tpoly (ty, tl) ->
+ {pat with pat_type =
+ snd (instance_poly ~keep_names:true false tl ty)}
+ | _ -> pat
+ in unify_pat env pat (type_approx env binding.pvb_expr))
+ pat_list spat_sexp_list;
+ (* Polymorphic variant processing *)
+ List.iter
+ (fun pat ->
+ if has_variants pat then begin
+ Parmatch.pressure_variants env [pat];
+ iter_pattern finalize_variant pat
+ end)
+ pat_list;
+ (* Generalize the structure *)
+ let pat_list =
+ if !Clflags.principal then begin
+ end_def ();
+ List.map
+ (fun pat ->
+ iter_pattern (fun pat -> generalize_structure pat.pat_type) pat;
+ {pat with pat_type = instance env pat.pat_type})
+ pat_list
+ end else pat_list in
+ (* Only bind pattern variables after generalizing *)
+ List.iter (fun f -> f()) force;
+ let exp_env =
+ if is_recursive then new_env else env in
+
+ let current_slot = ref None in
+ let rec_needed = ref false in
+ let warn_unused =
+ Warnings.is_active (check "") || Warnings.is_active (check_strict "") ||
+ (is_recursive && (Warnings.is_active Warnings.Unused_rec_flag))
+ in
+ let pat_slot_list =
+ (* Algorithm to detect unused declarations in recursive bindings:
+ - During type checking of the definitions, we capture the 'value_used'
+ events on the bound identifiers and record them in a slot corresponding
+ to the current definition (!current_slot).
+ In effect, this creates a dependency graph between definitions.
+
+ - After type checking the definition (!current_slot = None),
+ when one of the bound identifier is effectively used, we trigger
+ again all the events recorded in the corresponding slot.
+ The effect is to traverse the transitive closure of the graph created
+ in the first step.
+
+ We also keep track of whether *all* variables in a given pattern
+ are unused. If this is the case, for local declarations, the issued
+ warning is 26, not 27.
+ *)
+ List.map
+ (fun pat ->
+ if not warn_unused then pat, None
+ else
+ let some_used = ref false in
+ (* has one of the identifier of this pattern been used? *)
+ let slot = ref [] in
+ List.iter
+ (fun (id,_) ->
+ let vd = Env.find_value (Path.Pident id) new_env in
+ (* note: Env.find_value does not trigger the value_used event *)
+ let name = Ident.name id in
+ let used = ref false in
+ if not (name = "" || name.[0] = '_' || name.[0] = '#') then
+ add_delayed_check
+ (fun () ->
+ if not !used then
+ Location.prerr_warning vd.Types.val_loc
+ ((if !some_used then check_strict else check) name)
+ );
+ Env.set_value_used_callback
+ name vd
+ (fun () ->
+ match !current_slot with
+ | Some slot ->
+ slot := (name, vd) :: !slot; rec_needed := true
+ | None ->
+ List.iter
+ (fun (name, vd) -> Env.mark_value_used env name vd)
+ (get_ref slot);
+ used := true;
+ some_used := true
+ )
+ )
+ (Typedtree.pat_bound_idents pat);
+ pat, Some slot
+ )
+ pat_list
+ in
+ let exp_list =
+ List.map2
+ (fun {pvb_expr=sexp; pvb_attributes; _} (pat, slot) ->
+ let sexp =
+ if rec_flag = Recursive then wrap_unpacks sexp unpacks else sexp in
+ if is_recursive then current_slot := slot;
+ match pat.pat_type.desc with
+ | Tpoly (ty, tl) ->
+ begin_def ();
+ if !Clflags.principal then begin_def ();
+ let vars, ty' = instance_poly ~keep_names:true true tl ty in
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure ty'
+ end;
+ let exp =
+ Typetexp.with_warning_attribute pvb_attributes (fun () ->
+ type_expect exp_env sexp ty')
+ in
+ end_def ();
+ check_univars env true "definition" exp pat.pat_type vars;
+ {exp with exp_type = instance env exp.exp_type}
+ | _ ->
+ Typetexp.with_warning_attribute pvb_attributes (fun () ->
+ type_expect exp_env sexp pat.pat_type))
+ spat_sexp_list pat_slot_list in
+ current_slot := None;
+ if is_recursive && not !rec_needed
+ && Warnings.is_active Warnings.Unused_rec_flag then
+ Location.prerr_warning (List.hd spat_sexp_list).pvb_pat.ppat_loc
+ Warnings.Unused_rec_flag;
+ List.iter2
+ (fun pat exp ->
+ ignore(check_partial env pat.pat_type pat.pat_loc [case pat exp]))
+ pat_list exp_list;
+ end_def();
+ List.iter2
+ (fun pat exp ->
+ if not (is_nonexpansive exp) then
+ iter_pattern (fun pat -> generalize_expansive env pat.pat_type) pat)
+ pat_list exp_list;
+ List.iter
+ (fun pat -> iter_pattern (fun pat -> generalize pat.pat_type) pat)
+ pat_list;
+ let l = List.combine pat_list exp_list in
+ let l =
+ List.map2
+ (fun (p, e) pvb ->
+ {vb_pat=p; vb_expr=e; vb_attributes=pvb.pvb_attributes;
+ vb_loc=pvb.pvb_loc;
+ })
+ l spat_sexp_list
+ in
+ (l, new_env, unpacks)
+
+(* Typing of toplevel bindings *)
+
+let type_binding env rec_flag spat_sexp_list scope =
+ Typetexp.reset_type_variables();
+ let (pat_exp_list, new_env, unpacks) =
+ type_let
+ ~check:(fun s -> Warnings.Unused_value_declaration s)
+ ~check_strict:(fun s -> Warnings.Unused_value_declaration s)
+ env rec_flag spat_sexp_list scope false
+ in
+ (pat_exp_list, new_env)
+
+let type_let env rec_flag spat_sexp_list scope =
+ let (pat_exp_list, new_env, unpacks) =
+ type_let env rec_flag spat_sexp_list scope false in
+ (pat_exp_list, new_env)
+
+(* Typing of toplevel expressions *)
+
+let type_expression env sexp =
+ Typetexp.reset_type_variables();
+ begin_def();
+ let exp = type_exp env sexp in
+ end_def();
+ if is_nonexpansive exp then generalize exp.exp_type
+ else generalize_expansive env exp.exp_type;
+ match sexp.pexp_desc with
+ Pexp_ident lid ->
+ (* Special case for keeping type variables when looking-up a variable *)
+ let (path, desc) = Env.lookup_value lid.txt env in
+ {exp with exp_type = desc.val_type}
+ | _ -> exp
+
+(* Error report *)
+
+let spellcheck ppf unbound_name valid_names =
+ Misc.did_you_mean ppf (fun () ->
+ Misc.spellcheck valid_names unbound_name
+ )
+
+let spellcheck_idents ppf unbound valid_idents =
+ spellcheck ppf (Ident.name unbound) (List.map Ident.name valid_idents)
+
+open Format
+open Printtyp
+
+let report_error env ppf = function
+ | Polymorphic_label lid ->
+ fprintf ppf "@[The record field %a is polymorphic.@ %s@]"
+ longident lid "You cannot instantiate it in a pattern."
+ | Constructor_arity_mismatch(lid, expected, provided) ->
+ fprintf ppf
+ "@[The constructor %a@ expects %i argument(s),@ \
+ but is applied here to %i argument(s)@]"
+ longident lid expected provided
+ | Label_mismatch(lid, trace) ->
+ report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "The record field %a@ belongs to the type"
+ longident lid)
+ (function ppf ->
+ fprintf ppf "but is mixed here with fields of type")
+ | Pattern_type_clash trace ->
+ report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "This pattern matches values of type")
+ (function ppf ->
+ fprintf ppf "but a pattern was expected which matches values of type")
+ | Or_pattern_type_clash (id, trace) ->
+ report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "The variable %s on the left-hand side of this \
+ or-pattern has type" (Ident.name id))
+ (function ppf ->
+ fprintf ppf "but on the right-hand side it has type")
+ | Multiply_bound_variable name ->
+ fprintf ppf "Variable %s is bound several times in this matching" name
+ | Orpat_vars (id, valid_idents) ->
+ fprintf ppf "Variable %s must occur on both sides of this | pattern"
+ (Ident.name id);
+ spellcheck_idents ppf id valid_idents
+ | Expr_type_clash trace ->
+ report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "This expression has type")
+ (function ppf ->
+ fprintf ppf "but an expression was expected of type")
+ | Apply_non_function typ ->
+ reset_and_mark_loops typ;
+ begin match (repr typ).desc with
+ Tarrow _ ->
+ fprintf ppf "@[<v>@[<2>This function has type@ %a@]"
+ type_expr typ;
+ fprintf ppf "@ @[It is applied to too many arguments;@ %s@]@]"
+ "maybe you forgot a `;'."
+ | _ ->
+ fprintf ppf "@[<v>@[<2>This expression has type@ %a@]@ %s@]"
+ type_expr typ
+ "This is not a function; it cannot be applied."
+ end
+ | Apply_wrong_label (l, ty) ->
+ let print_label ppf = function
+ | Nolabel -> fprintf ppf "without label"
+ | l ->
+ fprintf ppf "with label %s" (prefixed_label_name l)
+ in
+ reset_and_mark_loops ty;
+ fprintf ppf
+ "@[<v>@[<2>The function applied to this argument has type@ %a@]@.\
+ This argument cannot be applied %a@]"
+ type_expr ty print_label l
+ | Label_multiply_defined s ->
+ fprintf ppf "The record field label %s is defined several times" s
+ | Label_missing labels ->
+ let print_labels ppf =
+ List.iter (fun lbl -> fprintf ppf "@ %s" (Ident.name lbl)) in
+ fprintf ppf "@[<hov>Some record fields are undefined:%a@]"
+ print_labels labels
+ | Label_not_mutable lid ->
+ fprintf ppf "The record field %a is not mutable" longident lid
+ | Wrong_name (eorp, ty, kind, p, name, valid_names) ->
+ reset_and_mark_loops ty;
+ if Path.is_constructor_typath p then begin
+ fprintf ppf "@[The field %s is not part of the record \
+ argument for the %a constructor@]"
+ name
+ path p;
+ end else begin
+ fprintf ppf "@[@[<2>%s type@ %a@]@ "
+ eorp type_expr ty;
+ fprintf ppf "The %s %s does not belong to type %a@]"
+ (label_of_kind kind)
+ name (*kind*) path p;
+ end;
+ spellcheck ppf name valid_names;
+ | Name_type_mismatch (kind, lid, tp, tpl) ->
+ let name = label_of_kind kind in
+ report_ambiguous_type_error ppf env tp tpl
+ (function ppf ->
+ fprintf ppf "The %s %a@ belongs to the %s type"
+ name longident lid kind)
+ (function ppf ->
+ fprintf ppf "The %s %a@ belongs to one of the following %s types:"
+ name longident lid kind)
+ (function ppf ->
+ fprintf ppf "but a %s was expected belonging to the %s type"
+ name kind)
+ | Invalid_format msg ->
+ fprintf ppf "%s" msg
+ | Undefined_method (ty, me, valid_methods) ->
+ reset_and_mark_loops ty;
+ fprintf ppf
+ "@[<v>@[This expression has type@;<1 2>%a@]@,\
+ It has no method %s@]" type_expr ty me;
+ begin match valid_methods with
+ | None -> ()
+ | Some valid_methods -> spellcheck ppf me valid_methods
+ end
+ | Undefined_inherited_method (me, valid_methods) ->
+ fprintf ppf "This expression has no method %s" me;
+ spellcheck ppf me valid_methods;
+ | Virtual_class cl ->
+ fprintf ppf "Cannot instantiate the virtual class %a"
+ longident cl
+ | Unbound_instance_variable (var, valid_vars) ->
+ fprintf ppf "Unbound instance variable %s" var;
+ spellcheck ppf var valid_vars;
+ | Instance_variable_not_mutable (b, v) ->
+ if b then
+ fprintf ppf "The instance variable %s is not mutable" v
+ else
+ fprintf ppf "The value %s is not an instance variable" v
+ | Not_subtype(tr1, tr2) ->
+ report_subtyping_error ppf env tr1 "is not a subtype of" tr2
+ | Outside_class ->
+ fprintf ppf "This object duplication occurs outside a method definition"
+ | Value_multiply_overridden v ->
+ fprintf ppf "The instance variable %s is overridden several times" v
+ | Coercion_failure (ty, ty', trace, b) ->
+ report_unification_error ppf env trace
+ (function ppf ->
+ let ty, ty' = prepare_expansion (ty, ty') in
+ fprintf ppf
+ "This expression cannot be coerced to type@;<1 2>%a;@ it has type"
+ (type_expansion ty) ty')
+ (function ppf ->
+ fprintf ppf "but is here used with type");
+ if b then
+ fprintf ppf ".@.@[<hov>%s@ %s@]"
+ "This simple coercion was not fully general."
+ "Consider using a double coercion."
+ | Too_many_arguments (in_function, ty) ->
+ reset_and_mark_loops ty;
+ if in_function then begin
+ fprintf ppf "This function expects too many arguments,@ ";
+ fprintf ppf "it should have type@ %a"
+ type_expr ty
+ end else begin
+ fprintf ppf "This expression should not be a function,@ ";
+ fprintf ppf "the expected type is@ %a"
+ type_expr ty
+ end
+ | Abstract_wrong_label (l, ty) ->
+ let label_mark = function
+ | Nolabel -> "but its first argument is not labelled"
+ | l -> sprintf "but its first argument is labelled %s"
+ (prefixed_label_name l) in
+ reset_and_mark_loops ty;
+ fprintf ppf "@[<v>@[<2>This function should have type@ %a@]@,%s@]"
+ type_expr ty (label_mark l)
+ | Scoping_let_module(id, ty) ->
+ reset_and_mark_loops ty;
+ fprintf ppf
+ "This `let module' expression has type@ %a@ " type_expr ty;
+ fprintf ppf
+ "In this type, the locally bound module name %s escapes its scope" id
+ | Masked_instance_variable lid ->
+ fprintf ppf
+ "The instance variable %a@ \
+ cannot be accessed from the definition of another instance variable"
+ longident lid
+ | Private_type ty ->
+ fprintf ppf "Cannot create values of the private type %a" type_expr ty
+ | Private_label (lid, ty) ->
+ fprintf ppf "Cannot assign field %a of the private type %a"
+ longident lid type_expr ty
+ | Not_a_variant_type lid ->
+ fprintf ppf "The type %a@ is not a variant type" longident lid
+ | Incoherent_label_order ->
+ fprintf ppf "This function is applied to arguments@ ";
+ fprintf ppf "in an order different from other calls.@ ";
+ fprintf ppf "This is only allowed when the real type is known."
+ | Less_general (kind, trace) ->
+ report_unification_error ppf env trace
+ (fun ppf -> fprintf ppf "This %s has type" kind)
+ (fun ppf -> fprintf ppf "which is less general than")
+ | Modules_not_allowed ->
+ fprintf ppf "Modules are not allowed in this pattern."
+ | Cannot_infer_signature ->
+ fprintf ppf
+ "The signature for this packaged module couldn't be inferred."
+ | Not_a_packed_module ty ->
+ fprintf ppf
+ "This expression is packed module, but the expected type is@ %a"
+ type_expr ty
+ | Recursive_local_constraint trace ->
+ report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "Recursive local constraint when unifying")
+ (function ppf ->
+ fprintf ppf "with")
+ | Unexpected_existential ->
+ fprintf ppf
+ "Unexpected existential"
+ | Unqualified_gadt_pattern (tpath, name) ->
+ fprintf ppf "@[The GADT constructor %s of type %a@ %s.@]"
+ name path tpath
+ "must be qualified in this pattern"
+ | Invalid_interval ->
+ fprintf ppf "@[Only character intervals are supported in patterns.@]"
+ | Invalid_for_loop_index ->
+ fprintf ppf
+ "@[Invalid for-loop index: only variables and _ are allowed.@]"
+ | No_value_clauses ->
+ fprintf ppf
+ "None of the patterns in this 'match' expression match values."
+ | Exception_pattern_below_toplevel ->
+ fprintf ppf
+ "@[Exception patterns must be at the top level of a match case.@]"
+ | Inlined_record_escape ->
+ fprintf ppf
+ "@[This form is not allowed as the type of the inlined record could \
+ escape.@]"
+
+let report_error env ppf err =
+ wrap_printing_env env (fun () -> report_error env ppf err)
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, env, err) ->
+ Some (Location.error_of_printer loc (report_error env) err)
+ | Error_forward err ->
+ Some err
+ | _ ->
+ None
+ )
+
+let () =
+ Env.add_delayed_check_forward := add_delayed_check
+
+(* drop ?recarg argument from the external API *)
+let type_expect ?in_function env e ty = type_expect ?in_function env e ty
+let type_exp env e = type_exp env e
+let type_argument env e t1 t2 = type_argument env e t1 t2
diff --git a/typing/typecore.mli b/typing/typecore.mli
new file mode 100644
index 0000000000..6251fe4b73
--- /dev/null
+++ b/typing/typecore.mli
@@ -0,0 +1,139 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Type inference for the core language *)
+
+open Asttypes
+open Types
+open Format
+
+val is_nonexpansive: Typedtree.expression -> bool
+
+val type_binding:
+ Env.t -> rec_flag ->
+ Parsetree.value_binding list ->
+ Annot.ident option ->
+ Typedtree.value_binding list * Env.t
+val type_let:
+ Env.t -> rec_flag ->
+ Parsetree.value_binding list ->
+ Annot.ident option ->
+ Typedtree.value_binding list * Env.t
+val type_expression:
+ Env.t -> Parsetree.expression -> Typedtree.expression
+val type_class_arg_pattern:
+ string -> Env.t -> Env.t -> arg_label -> Parsetree.pattern ->
+ Typedtree.pattern * (Ident.t * string loc * Ident.t * type_expr) list *
+ Env.t * Env.t
+val type_self_pattern:
+ string -> type_expr -> Env.t -> Env.t -> Env.t -> Parsetree.pattern ->
+ Typedtree.pattern *
+ (Ident.t * type_expr) Meths.t ref *
+ (Ident.t * Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr)
+ Vars.t ref *
+ Env.t * Env.t * Env.t
+val check_partial:
+ ?lev:int -> Env.t -> type_expr ->
+ Location.t -> Typedtree.case list -> Typedtree.partial
+val type_expect:
+ ?in_function:(Location.t * type_expr) ->
+ Env.t -> Parsetree.expression -> type_expr -> Typedtree.expression
+val type_exp:
+ Env.t -> Parsetree.expression -> Typedtree.expression
+val type_approx:
+ Env.t -> Parsetree.expression -> type_expr
+val type_argument:
+ Env.t -> Parsetree.expression ->
+ type_expr -> type_expr -> Typedtree.expression
+
+val option_some: Typedtree.expression -> Typedtree.expression
+val option_none: type_expr -> Location.t -> Typedtree.expression
+val extract_option_type: Env.t -> type_expr -> type_expr
+val iter_pattern: (Typedtree.pattern -> unit) -> Typedtree.pattern -> unit
+val generalizable: int -> type_expr -> bool
+val reset_delayed_checks: unit -> unit
+val force_delayed_checks: unit -> unit
+
+val self_coercion : (Path.t * Location.t list ref) list ref
+
+type error =
+ Polymorphic_label of Longident.t
+ | Constructor_arity_mismatch of Longident.t * int * int
+ | Label_mismatch of Longident.t * (type_expr * type_expr) list
+ | Pattern_type_clash of (type_expr * type_expr) list
+ | Or_pattern_type_clash of Ident.t * (type_expr * type_expr) list
+ | Multiply_bound_variable of string
+ | Orpat_vars of Ident.t * Ident.t list
+ | Expr_type_clash of (type_expr * type_expr) list
+ | Apply_non_function of type_expr
+ | Apply_wrong_label of arg_label * type_expr
+ | Label_multiply_defined of string
+ | Label_missing of Ident.t list
+ | Label_not_mutable of Longident.t
+ | Wrong_name of string * type_expr * string * Path.t * string * string list
+ | Name_type_mismatch of
+ string * Longident.t * (Path.t * Path.t) * (Path.t * Path.t) list
+ | Invalid_format of string
+ | Undefined_method of type_expr * string * string list option
+ | Undefined_inherited_method of string * string list
+ | Virtual_class of Longident.t
+ | Private_type of type_expr
+ | Private_label of Longident.t * type_expr
+ | Unbound_instance_variable of string * string list
+ | Instance_variable_not_mutable of bool * string
+ | Not_subtype of (type_expr * type_expr) list * (type_expr * type_expr) list
+ | Outside_class
+ | Value_multiply_overridden of string
+ | Coercion_failure of
+ type_expr * type_expr * (type_expr * type_expr) list * bool
+ | Too_many_arguments of bool * type_expr
+ | Abstract_wrong_label of arg_label * type_expr
+ | Scoping_let_module of string * type_expr
+ | Masked_instance_variable of Longident.t
+ | Not_a_variant_type of Longident.t
+ | Incoherent_label_order
+ | Less_general of string * (type_expr * type_expr) list
+ | Modules_not_allowed
+ | Cannot_infer_signature
+ | Not_a_packed_module of type_expr
+ | Recursive_local_constraint of (type_expr * type_expr) list
+ | Unexpected_existential
+ | Unqualified_gadt_pattern of Path.t * string
+ | Invalid_interval
+ | Invalid_for_loop_index
+ | No_value_clauses
+ | Exception_pattern_below_toplevel
+ | Inlined_record_escape
+
+exception Error of Location.t * Env.t * error
+exception Error_forward of Location.error
+
+val report_error: Env.t -> formatter -> error -> unit
+ (* Deprecated. Use Location.{error_of_exn, report_error}. *)
+
+(* Forward declaration, to be filled in by Typemod.type_module *)
+val type_module: (Env.t -> Parsetree.module_expr -> Typedtree.module_expr) ref
+(* Forward declaration, to be filled in by Typemod.type_open *)
+val type_open:
+ (override_flag -> Env.t -> Location.t -> Longident.t loc -> Path.t * Env.t)
+ ref
+(* Forward declaration, to be filled in by Typeclass.class_structure *)
+val type_object:
+ (Env.t -> Location.t -> Parsetree.class_structure ->
+ Typedtree.class_structure * Types.class_signature * string list) ref
+val type_package:
+ (Env.t -> Parsetree.module_expr -> Path.t -> Longident.t list ->
+ type_expr list -> Typedtree.module_expr * type_expr list) ref
+
+val create_package_type : Location.t -> Env.t ->
+ Longident.t * (Longident.t * Parsetree.core_type) list ->
+ Path.t * (Longident.t * Typedtree.core_type) list * Types.type_expr
diff --git a/typing/typedecl.ml b/typing/typedecl.ml
new file mode 100644
index 0000000000..5d2a993d67
--- /dev/null
+++ b/typing/typedecl.ml
@@ -0,0 +1,1813 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy and Jerome Vouillon, projet Cristal, INRIA Rocquencourt*)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(**** Typing of type definitions ****)
+
+open Misc
+open Asttypes
+open Parsetree
+open Primitive
+open Types
+open Typetexp
+
+type native_repr_kind = Unboxed | Untagged
+
+let string_of_native_repr_kind = function
+ | Unboxed -> "unboxed"
+ | Untagged -> "untagged"
+
+type error =
+ Repeated_parameter
+ | Duplicate_constructor of string
+ | Too_many_constructors
+ | Duplicate_label of string
+ | Recursive_abbrev of string
+ | Cycle_in_def of string * type_expr
+ | Definition_mismatch of type_expr * Includecore.type_mismatch list
+ | Constraint_failed of type_expr * type_expr
+ | Inconsistent_constraint of Env.t * (type_expr * type_expr) list
+ | Type_clash of Env.t * (type_expr * type_expr) list
+ | Parameters_differ of Path.t * type_expr * type_expr
+ | Null_arity_external
+ | Missing_native_external
+ | Unbound_type_var of type_expr * type_declaration
+ | Not_open_type of Path.t
+ | Not_extensible_type of Path.t
+ | Extension_mismatch of Path.t * Includecore.type_mismatch list
+ | Rebind_wrong_type of Longident.t * Env.t * (type_expr * type_expr) list
+ | Rebind_mismatch of Longident.t * Path.t * Path.t
+ | Rebind_private of Longident.t
+ | Bad_variance of int * (bool * bool * bool) * (bool * bool * bool)
+ | Unavailable_type_constructor of Path.t
+ | Bad_fixed_type of string
+ | Unbound_type_var_ext of type_expr * extension_constructor
+ | Varying_anonymous
+ | Val_in_structure
+ | Invalid_native_repr_attribute_payload of native_repr_kind
+ | Multiple_native_repr_attributes
+ | Cannot_unbox_or_untag_type of native_repr_kind
+
+open Typedtree
+
+exception Error of Location.t * error
+
+(* Enter all declared types in the environment as abstract types *)
+
+let enter_type env sdecl id =
+ let decl =
+ { type_params =
+ List.map (fun _ -> Btype.newgenvar ()) sdecl.ptype_params;
+ type_arity = List.length sdecl.ptype_params;
+ type_kind = Type_abstract;
+ type_private = sdecl.ptype_private;
+ type_manifest =
+ begin match sdecl.ptype_manifest with None -> None
+ | Some _ -> Some(Ctype.newvar ()) end;
+ type_variance = List.map (fun _ -> Variance.full) sdecl.ptype_params;
+ type_newtype_level = None;
+ type_loc = sdecl.ptype_loc;
+ type_attributes = sdecl.ptype_attributes;
+ }
+ in
+ Env.add_type ~check:true id decl env
+
+let update_type temp_env env id loc =
+ let path = Path.Pident id in
+ let decl = Env.find_type path temp_env in
+ match decl.type_manifest with None -> ()
+ | Some ty ->
+ let params = List.map (fun _ -> Ctype.newvar ()) decl.type_params in
+ try Ctype.unify env (Ctype.newconstr path params) ty
+ with Ctype.Unify trace ->
+ raise (Error(loc, Type_clash (env, trace)))
+
+(* Determine if a type is (an abbreviation for) the type "float" *)
+(* We use the Ctype.expand_head_opt version of expand_head to get access
+ to the manifest type of private abbreviations. *)
+let is_float env ty =
+ match Ctype.repr (Ctype.expand_head_opt env ty) with
+ {desc = Tconstr(p, _, _)} -> Path.same p Predef.path_float
+ | _ -> false
+
+(* Determine if a type definition defines a fixed type. (PW) *)
+let is_fixed_type sd =
+ let rec has_row_var sty =
+ match sty.ptyp_desc with
+ Ptyp_alias (sty, _) -> has_row_var sty
+ | Ptyp_class _
+ | Ptyp_object (_, Open)
+ | Ptyp_variant (_, Open, _)
+ | Ptyp_variant (_, Closed, Some _) -> true
+ | _ -> false
+ in
+ match sd.ptype_manifest with
+ None -> false
+ | Some sty ->
+ sd.ptype_kind = Ptype_abstract &&
+ sd.ptype_private = Private &&
+ has_row_var sty
+
+(* Set the row variable in a fixed type *)
+let set_fixed_row env loc p decl =
+ let tm =
+ match decl.type_manifest with
+ None -> assert false
+ | Some t -> Ctype.expand_head env t
+ in
+ let rv =
+ match tm.desc with
+ Tvariant row ->
+ let row = Btype.row_repr row in
+ tm.desc <- Tvariant {row with row_fixed = true};
+ if Btype.static_row row then Btype.newgenty Tnil
+ else row.row_more
+ | Tobject (ty, _) ->
+ snd (Ctype.flatten_fields ty)
+ | _ ->
+ raise (Error (loc, Bad_fixed_type "is not an object or variant"))
+ in
+ if not (Btype.is_Tvar rv) then
+ raise (Error (loc, Bad_fixed_type "has no row variable"));
+ rv.desc <- Tconstr (p, decl.type_params, ref Mnil)
+
+(* Translate one type declaration *)
+
+module StringSet =
+ Set.Make(struct
+ type t = string
+ let compare (x:t) y = compare x y
+ end)
+
+let make_params env params =
+ let make_param (sty, v) =
+ try
+ (transl_type_param env sty, v)
+ with Already_bound ->
+ raise(Error(sty.ptyp_loc, Repeated_parameter))
+ in
+ List.map make_param params
+
+let transl_labels loc env closed lbls =
+ if lbls = [] then
+ Syntaxerr.ill_formed_ast loc "Records cannot be empty.";
+ let all_labels = ref StringSet.empty in
+ List.iter
+ (fun {pld_name = {txt=name; loc}} ->
+ if StringSet.mem name !all_labels then
+ raise(Error(loc, Duplicate_label name));
+ all_labels := StringSet.add name !all_labels)
+ lbls;
+ let mk {pld_name=name;pld_mutable=mut;pld_type=arg;pld_loc=loc;
+ pld_attributes=attrs} =
+ let arg = Ast_helper.Typ.force_poly arg in
+ let cty = transl_simple_type env closed arg in
+ {ld_id = Ident.create name.txt; ld_name = name; ld_mutable = mut;
+ ld_type = cty; ld_loc = loc; ld_attributes = attrs}
+ in
+ let lbls = List.map mk lbls in
+ let lbls' =
+ List.map
+ (fun ld ->
+ let ty = ld.ld_type.ctyp_type in
+ let ty = match ty.desc with Tpoly(t,[]) -> t | _ -> ty in
+ {Types.ld_id = ld.ld_id;
+ ld_mutable = ld.ld_mutable;
+ ld_type = ty;
+ ld_loc = ld.ld_loc;
+ ld_attributes = ld.ld_attributes
+ }
+ )
+ lbls in
+ lbls, lbls'
+
+let transl_constructor_arguments loc env closed = function
+ | Pcstr_tuple l ->
+ let l = List.map (transl_simple_type env closed) l in
+ Types.Cstr_tuple (List.map (fun t -> t.ctyp_type) l),
+ Cstr_tuple l
+ | Pcstr_record l ->
+ let lbls, lbls' = transl_labels loc env closed l in
+ Types.Cstr_record lbls',
+ Cstr_record lbls
+
+let make_constructor loc env type_path type_params sargs sret_type =
+ match sret_type with
+ | None ->
+ let args, targs =
+ transl_constructor_arguments loc env true sargs
+ in
+ targs, None, args, None
+ | Some sret_type ->
+ (* if it's a generalized constructor we must first narrow and
+ then widen so as to not introduce any new constraints *)
+ let z = narrow () in
+ reset_type_variables ();
+ let args, targs =
+ transl_constructor_arguments loc env false sargs
+ in
+ let tret_type = transl_simple_type env false sret_type in
+ let ret_type = tret_type.ctyp_type in
+ begin
+ match (Ctype.repr ret_type).desc with
+ Tconstr (p', _, _) when Path.same type_path p' -> ()
+ | _ ->
+ raise (Error (sret_type.ptyp_loc, Constraint_failed
+ (ret_type, Ctype.newconstr type_path type_params)))
+ end;
+ widen z;
+ targs, Some tret_type, args, Some ret_type
+
+let transl_declaration env sdecl id =
+ (* Bind type parameters *)
+ reset_type_variables();
+ Ctype.begin_def ();
+ let tparams = make_params env sdecl.ptype_params in
+ let params = List.map (fun (cty, _) -> cty.ctyp_type) tparams in
+ let cstrs = List.map
+ (fun (sty, sty', loc) ->
+ transl_simple_type env false sty,
+ transl_simple_type env false sty', loc)
+ sdecl.ptype_cstrs
+ in
+ let (tkind, kind) =
+ match sdecl.ptype_kind with
+ Ptype_abstract -> Ttype_abstract, Type_abstract
+ | Ptype_variant scstrs ->
+ if scstrs = [] then
+ Syntaxerr.ill_formed_ast sdecl.ptype_loc
+ "Variant types cannot be empty.";
+ let all_constrs = ref StringSet.empty in
+ List.iter
+ (fun {pcd_name = {txt = name}} ->
+ if StringSet.mem name !all_constrs then
+ raise(Error(sdecl.ptype_loc, Duplicate_constructor name));
+ all_constrs := StringSet.add name !all_constrs)
+ scstrs;
+ if List.length
+ (List.filter (fun cd -> cd.pcd_args <> Pcstr_tuple []) scstrs)
+ > (Config.max_tag + 1) then
+ raise(Error(sdecl.ptype_loc, Too_many_constructors));
+ let make_cstr scstr =
+ let name = Ident.create scstr.pcd_name.txt in
+ let targs, tret_type, args, ret_type =
+ make_constructor scstr.pcd_loc env (Path.Pident id) params
+ scstr.pcd_args scstr.pcd_res
+ in
+ let tcstr =
+ { cd_id = name;
+ cd_name = scstr.pcd_name;
+ cd_args = targs;
+ cd_res = tret_type;
+ cd_loc = scstr.pcd_loc;
+ cd_attributes = scstr.pcd_attributes }
+ in
+ let cstr =
+ { Types.cd_id = name;
+ cd_args = args;
+ cd_res = ret_type;
+ cd_loc = scstr.pcd_loc;
+ cd_attributes = scstr.pcd_attributes }
+ in
+ tcstr, cstr
+ in
+ let tcstrs, cstrs = List.split (List.map make_cstr scstrs) in
+ Ttype_variant tcstrs, Type_variant cstrs
+ | Ptype_record lbls ->
+ let lbls, lbls' = transl_labels sdecl.ptype_loc env true lbls in
+ let rep =
+ if List.for_all (fun l -> is_float env l.Types.ld_type) lbls'
+ then Record_float
+ else Record_regular
+ in
+ Ttype_record lbls, Type_record(lbls', rep)
+ | Ptype_open -> Ttype_open, Type_open
+ in
+ let (tman, man) = match sdecl.ptype_manifest with
+ None -> None, None
+ | Some sty ->
+ let no_row = not (is_fixed_type sdecl) in
+ let cty = transl_simple_type env no_row sty in
+ Some cty, Some cty.ctyp_type
+ in
+ let decl =
+ { type_params = params;
+ type_arity = List.length params;
+ type_kind = kind;
+ type_private = sdecl.ptype_private;
+ type_manifest = man;
+ type_variance = List.map (fun _ -> Variance.full) params;
+ type_newtype_level = None;
+ type_loc = sdecl.ptype_loc;
+ type_attributes = sdecl.ptype_attributes;
+ } in
+
+ (* Check constraints *)
+ List.iter
+ (fun (cty, cty', loc) ->
+ let ty = cty.ctyp_type in
+ let ty' = cty'.ctyp_type in
+ try Ctype.unify env ty ty' with Ctype.Unify tr ->
+ raise(Error(loc, Inconsistent_constraint (env, tr))))
+ cstrs;
+ Ctype.end_def ();
+ (* Add abstract row *)
+ if is_fixed_type sdecl then begin
+ let (p, _) =
+ try Env.lookup_type (Longident.Lident(Ident.name id ^ "#row")) env
+ with Not_found -> assert false in
+ set_fixed_row env sdecl.ptype_loc p decl
+ end;
+ (* Check for cyclic abbreviations *)
+ begin match decl.type_manifest with None -> ()
+ | Some ty ->
+ if Ctype.cyclic_abbrev env id ty then
+ raise(Error(sdecl.ptype_loc, Recursive_abbrev sdecl.ptype_name.txt));
+ end;
+ {
+ typ_id = id;
+ typ_name = sdecl.ptype_name;
+ typ_params = tparams;
+ typ_type = decl;
+ typ_cstrs = cstrs;
+ typ_loc = sdecl.ptype_loc;
+ typ_manifest = tman;
+ typ_kind = tkind;
+ typ_private = sdecl.ptype_private;
+ typ_attributes = sdecl.ptype_attributes;
+ }
+
+(* Generalize a type declaration *)
+
+let generalize_decl decl =
+ List.iter Ctype.generalize decl.type_params;
+ Btype.iter_type_expr_kind Ctype.generalize decl.type_kind;
+ begin match decl.type_manifest with
+ | None -> ()
+ | Some ty -> Ctype.generalize ty
+ end
+
+(* Check that all constraints are enforced *)
+
+module TypeSet = Btype.TypeSet
+module TypeMap = Btype.TypeMap
+
+let rec check_constraints_rec env loc visited ty =
+ let ty = Ctype.repr ty in
+ if TypeSet.mem ty !visited then () else begin
+ visited := TypeSet.add ty !visited;
+ match ty.desc with
+ | Tconstr (path, args, _) ->
+ let args' = List.map (fun _ -> Ctype.newvar ()) args in
+ let ty' = Ctype.newconstr path args' in
+ begin try Ctype.enforce_constraints env ty'
+ with Ctype.Unify _ -> assert false
+ | Not_found -> raise (Error(loc, Unavailable_type_constructor path))
+ end;
+ if not (Ctype.matches env ty ty') then
+ raise (Error(loc, Constraint_failed (ty, ty')));
+ List.iter (check_constraints_rec env loc visited) args
+ | Tpoly (ty, tl) ->
+ let _, ty = Ctype.instance_poly false tl ty in
+ check_constraints_rec env loc visited ty
+ | _ ->
+ Btype.iter_type_expr (check_constraints_rec env loc visited) ty
+ end
+
+module SMap = Map.Make(String)
+
+let check_constraints_labels env visited l pl =
+ let rec get_loc name = function
+ [] -> assert false
+ | pld :: tl ->
+ if name = pld.pld_name.txt then pld.pld_type.ptyp_loc
+ else get_loc name tl
+ in
+ List.iter
+ (fun {Types.ld_id=name; ld_type=ty} ->
+ check_constraints_rec env (get_loc (Ident.name name) pl) visited ty)
+ l
+
+let check_constraints env sdecl (_, decl) =
+ let visited = ref TypeSet.empty in
+ begin match decl.type_kind with
+ | Type_abstract -> ()
+ | Type_variant l ->
+ let find_pl = function
+ Ptype_variant pl -> pl
+ | Ptype_record _ | Ptype_abstract | Ptype_open -> assert false
+ in
+ let pl = find_pl sdecl.ptype_kind in
+ let pl_index =
+ let foldf acc x =
+ SMap.add x.pcd_name.txt x acc
+ in
+ List.fold_left foldf SMap.empty pl
+ in
+ List.iter
+ (fun {Types.cd_id=name; cd_args; cd_res} ->
+ let {pcd_args; pcd_res; _} =
+ try SMap.find (Ident.name name) pl_index
+ with Not_found -> assert false in
+ begin match cd_args, pcd_args with
+ | Cstr_tuple tyl, Pcstr_tuple styl ->
+ List.iter2
+ (fun sty ty ->
+ check_constraints_rec env sty.ptyp_loc visited ty)
+ styl tyl
+ | Cstr_record tyl, Pcstr_record styl ->
+ check_constraints_labels env visited tyl styl
+ | _ -> assert false
+ end;
+ match pcd_res, cd_res with
+ | Some sr, Some r ->
+ check_constraints_rec env sr.ptyp_loc visited r
+ | _ ->
+ () )
+ l
+ | Type_record (l, _) ->
+ let find_pl = function
+ Ptype_record pl -> pl
+ | Ptype_variant _ | Ptype_abstract | Ptype_open -> assert false
+ in
+ let pl = find_pl sdecl.ptype_kind in
+ check_constraints_labels env visited l pl
+ | Type_open -> ()
+ end;
+ begin match decl.type_manifest with
+ | None -> ()
+ | Some ty ->
+ let sty =
+ match sdecl.ptype_manifest with Some sty -> sty | _ -> assert false
+ in
+ check_constraints_rec env sty.ptyp_loc visited ty
+ end
+
+(*
+ If both a variant/record definition and a type equation are given,
+ need to check that the equation refers to a type of the same kind
+ with the same constructors and labels.
+*)
+let check_coherence env loc id decl =
+ match decl with
+ { type_kind = (Type_variant _ | Type_record _| Type_open);
+ type_manifest = Some ty } ->
+ begin match (Ctype.repr ty).desc with
+ Tconstr(path, args, _) ->
+ begin try
+ let decl' = Env.find_type path env in
+ let err =
+ if List.length args <> List.length decl.type_params
+ then [Includecore.Arity]
+ else if not (Ctype.equal env false args decl.type_params)
+ then [Includecore.Constraint]
+ else
+ Includecore.type_declarations ~equality:true env
+ (Path.last path)
+ decl'
+ id
+ (Subst.type_declaration
+ (Subst.add_type id path Subst.identity) decl)
+ in
+ if err <> [] then
+ raise(Error(loc, Definition_mismatch (ty, err)))
+ with Not_found ->
+ raise(Error(loc, Unavailable_type_constructor path))
+ end
+ | _ -> raise(Error(loc, Definition_mismatch (ty, [])))
+ end
+ | _ -> ()
+
+let check_abbrev env sdecl (id, decl) =
+ check_coherence env sdecl.ptype_loc id decl
+
+(* Check that recursion is well-founded *)
+
+let check_well_founded env loc path to_check ty =
+ let visited = ref TypeMap.empty in
+ let rec check ty0 exp_nodes ty =
+ let ty = Btype.repr ty in
+ if TypeSet.mem ty exp_nodes then begin
+ (*Format.eprintf "@[%a@]@." Printtyp.raw_type_expr ty;*)
+ if match ty0.desc with
+ | Tconstr (p, _, _) -> Path.same p path
+ | _ -> false
+ then raise (Error (loc, Recursive_abbrev (Path.name path)))
+ else raise (Error (loc, Cycle_in_def (Path.name path, ty0)))
+ end;
+ let (fini, exp_nodes) =
+ try
+ let prev = TypeMap.find ty !visited in
+ if TypeSet.subset exp_nodes prev then (true, exp_nodes) else
+ (false, TypeSet.union exp_nodes prev)
+ with Not_found ->
+ (false, exp_nodes)
+ in
+ let snap = Btype.snapshot () in
+ if fini then () else try
+ visited := TypeMap.add ty exp_nodes !visited;
+ match ty.desc with
+ | Tconstr(p, args, _)
+ when not (TypeSet.is_empty exp_nodes) || to_check p ->
+ let ty' = Ctype.try_expand_once_opt env ty in
+ let ty0 = if TypeSet.is_empty exp_nodes then ty else ty0 in
+ check ty0 (TypeSet.add ty exp_nodes) ty'
+ | _ -> raise Ctype.Cannot_expand
+ with
+ | Ctype.Cannot_expand ->
+ let nodes =
+ if !Clflags.recursive_types && Ctype.is_contractive env ty
+ || match ty.desc with Tobject _ | Tvariant _ -> true | _ -> false
+ then TypeSet.empty
+ else exp_nodes in
+ Btype.iter_type_expr (check ty0 nodes) ty
+ | Ctype.Unify _ ->
+ (* Will be detected by check_recursion *)
+ Btype.backtrack snap
+ in
+ Ctype.wrap_trace_gadt_instances env (check ty TypeSet.empty) ty
+
+let check_well_founded_manifest env loc path decl =
+ if decl.type_manifest = None then () else
+ let args = List.map (fun _ -> Ctype.newvar()) decl.type_params in
+ check_well_founded env loc path (Path.same path) (Ctype.newconstr path args)
+
+let check_well_founded_decl env loc path decl to_check =
+ let open Btype in
+ let it =
+ {type_iterators with
+ it_type_expr = (fun _ -> check_well_founded env loc path to_check)} in
+ it.it_type_declaration it (Ctype.instance_declaration decl)
+
+(* Check for ill-defined abbrevs *)
+
+let check_recursion env loc path decl to_check =
+ (* to_check is true for potentially mutually recursive paths.
+ (path, decl) is the type declaration to be checked. *)
+
+ if decl.type_params = [] then () else
+
+ let visited = ref [] in
+
+ let rec check_regular cpath args prev_exp ty =
+ let ty = Ctype.repr ty in
+ if not (List.memq ty !visited) then begin
+ visited := ty :: !visited;
+ match ty.desc with
+ | Tconstr(path', args', _) ->
+ if Path.same path path' then begin
+ if not (Ctype.equal env false args args') then
+ raise (Error(loc,
+ Parameters_differ(cpath, ty, Ctype.newconstr path args)))
+ end
+ (* Attempt to expand a type abbreviation if:
+ 1- [to_check path'] holds
+ (otherwise the expansion cannot involve [path]);
+ 2- we haven't expanded this type constructor before
+ (otherwise we could loop if [path'] is itself
+ a non-regular abbreviation). *)
+ else if to_check path' && not (List.mem path' prev_exp) then begin
+ try
+ (* Attempt expansion *)
+ let (params0, body0, _) = Env.find_type_expansion path' env in
+ let (params, body) =
+ Ctype.instance_parameterized_type params0 body0 in
+ begin
+ try List.iter2 (Ctype.unify env) params args'
+ with Ctype.Unify _ ->
+ raise (Error(loc, Constraint_failed
+ (ty, Ctype.newconstr path' params0)));
+ end;
+ check_regular path' args (path' :: prev_exp) body
+ with Not_found -> ()
+ end;
+ List.iter (check_regular cpath args prev_exp) args'
+ | Tpoly (ty, tl) ->
+ let (_, ty) = Ctype.instance_poly ~keep_names:true false tl ty in
+ check_regular cpath args prev_exp ty
+ | _ ->
+ Btype.iter_type_expr (check_regular cpath args prev_exp) ty
+ end in
+
+ Misc.may
+ (fun body ->
+ let (args, body) =
+ Ctype.instance_parameterized_type
+ ~keep_names:true decl.type_params body in
+ check_regular path args [] body)
+ decl.type_manifest
+
+let check_abbrev_recursion env id_loc_list to_check tdecl =
+ let decl = tdecl.typ_type in
+ let id = tdecl.typ_id in
+ check_recursion env (List.assoc id id_loc_list) (Path.Pident id) decl to_check
+
+(* Compute variance *)
+
+let get_variance ty visited =
+ try TypeMap.find ty !visited with Not_found -> Variance.null
+
+let compute_variance env visited vari ty =
+ let rec compute_variance_rec vari ty =
+ (* Format.eprintf "%a: %x@." Printtyp.type_expr ty (Obj.magic vari); *)
+ let ty = Ctype.repr ty in
+ let vari' = get_variance ty visited in
+ if Variance.subset vari vari' then () else
+ let vari = Variance.union vari vari' in
+ visited := TypeMap.add ty vari !visited;
+ let compute_same = compute_variance_rec vari in
+ match ty.desc with
+ Tarrow (_, ty1, ty2, _) ->
+ let open Variance in
+ let v = conjugate vari in
+ let v1 =
+ if mem May_pos v || mem May_neg v
+ then set May_weak true v else v
+ in
+ compute_variance_rec v1 ty1;
+ compute_same ty2
+ | Ttuple tl ->
+ List.iter compute_same tl
+ | Tconstr (path, tl, _) ->
+ let open Variance in
+ if tl = [] then () else begin
+ try
+ let decl = Env.find_type path env in
+ let cvari f = mem f vari in
+ List.iter2
+ (fun ty v ->
+ let cv f = mem f v in
+ let strict =
+ cvari Inv && cv Inj || (cvari Pos || cvari Neg) && cv Inv
+ in
+ if strict then compute_variance_rec full ty else
+ let p1 = inter v vari
+ and n1 = inter v (conjugate vari) in
+ let v1 =
+ union (inter covariant (union p1 (conjugate p1)))
+ (inter (conjugate covariant) (union n1 (conjugate n1)))
+ and weak =
+ cvari May_weak && (cv May_pos || cv May_neg) ||
+ (cvari May_pos || cvari May_neg) && cv May_weak
+ in
+ let v2 = set May_weak weak v1 in
+ compute_variance_rec v2 ty)
+ tl decl.type_variance
+ with Not_found ->
+ List.iter (compute_variance_rec may_inv) tl
+ end
+ | Tobject (ty, _) ->
+ compute_same ty
+ | Tfield (_, _, ty1, ty2) ->
+ compute_same ty1;
+ compute_same ty2
+ | Tsubst ty ->
+ compute_same ty
+ | Tvariant row ->
+ let row = Btype.row_repr row in
+ List.iter
+ (fun (_,f) ->
+ match Btype.row_field_repr f with
+ Rpresent (Some ty) ->
+ compute_same ty
+ | Reither (_, tyl, _, _) ->
+ let open Variance in
+ let upper =
+ List.fold_left (fun s f -> set f true s)
+ null [May_pos; May_neg; May_weak]
+ in
+ let v = inter vari upper in
+ List.iter (compute_variance_rec v) tyl
+ | _ -> ())
+ row.row_fields;
+ compute_same row.row_more
+ | Tpoly (ty, _) ->
+ compute_same ty
+ | Tvar _ | Tnil | Tlink _ | Tunivar _ -> ()
+ | Tpackage (_, _, tyl) ->
+ let v =
+ Variance.(if mem Pos vari || mem Neg vari then full else may_inv)
+ in
+ List.iter (compute_variance_rec v) tyl
+ in
+ compute_variance_rec vari ty
+
+let make p n i =
+ let open Variance in
+ set May_pos p (set May_neg n (set May_weak n (set Inj i null)))
+
+let compute_variance_type env check (required, loc) decl tyl =
+ (* Requirements *)
+ let required =
+ List.map (fun (c,n,i) -> if c || n then (c,n,i) else (true,true,i))
+ required
+ in
+ (* Prepare *)
+ let params = List.map Btype.repr decl.type_params in
+ let tvl = ref TypeMap.empty in
+ (* Compute occurences in body *)
+ let open Variance in
+ List.iter
+ (fun (cn,ty) ->
+ compute_variance env tvl (if cn then full else covariant) ty)
+ tyl;
+ if check then begin
+ (* Check variance of parameters *)
+ let pos = ref 0 in
+ List.iter2
+ (fun ty (c, n, i) ->
+ incr pos;
+ let var = get_variance ty tvl in
+ let (co,cn) = get_upper var and ij = mem Inj var in
+ if Btype.is_Tvar ty && (co && not c || cn && not n || not ij && i)
+ then raise (Error(loc, Bad_variance (!pos, (co,cn,ij), (c,n,i)))))
+ params required;
+ (* Check propagation from constrained parameters *)
+ let args = Btype.newgenty (Ttuple params) in
+ let fvl = Ctype.free_variables args in
+ let fvl = List.filter (fun v -> not (List.memq v params)) fvl in
+ (* If there are no extra variables there is nothing to do *)
+ if fvl = [] then () else
+ let tvl2 = ref TypeMap.empty in
+ List.iter2
+ (fun ty (p,n,i) ->
+ if Btype.is_Tvar ty then () else
+ let v =
+ if p then if n then full else covariant else conjugate covariant in
+ compute_variance env tvl2 v ty)
+ params required;
+ let visited = ref TypeSet.empty in
+ let rec check ty =
+ let ty = Ctype.repr ty in
+ if TypeSet.mem ty !visited then () else
+ let visited' = TypeSet.add ty !visited in
+ visited := visited';
+ let v1 = get_variance ty tvl in
+ let snap = Btype.snapshot () in
+ let v2 =
+ TypeMap.fold
+ (fun t vt v ->
+ if Ctype.equal env false [ty] [t] then union vt v else v)
+ !tvl2 null in
+ Btype.backtrack snap;
+ let (c1,n1) = get_upper v1 and (c2,n2,_,i2) = get_lower v2 in
+ if c1 && not c2 || n1 && not n2 then
+ if List.memq ty fvl then
+ let code = if not i2 then -2 else if c2 || n2 then -1 else -3 in
+ raise (Error (loc, Bad_variance (code, (c1,n1,false), (c2,n2,false))))
+ else
+ Btype.iter_type_expr check ty
+ in
+ List.iter (fun (_,ty) -> check ty) tyl;
+ end;
+ List.map2
+ (fun ty (p, n, i) ->
+ let v = get_variance ty tvl in
+ let tr = decl.type_private in
+ (* Use required variance where relevant *)
+ let concr = decl.type_kind <> Type_abstract (*|| tr = Type_new*) in
+ let (p, n) =
+ if tr = Private || not (Btype.is_Tvar ty) then (p, n) (* set *)
+ else (false, false) (* only check *)
+ and i = concr || i && tr = Private in
+ let v = union v (make p n i) in
+ let v =
+ if not concr then v else
+ if mem Pos v && mem Neg v then full else
+ if Btype.is_Tvar ty then v else
+ union v
+ (if p then if n then full else covariant else conjugate covariant)
+ in
+ if decl.type_kind = Type_abstract && tr = Public then v else
+ set May_weak (mem May_neg v) v)
+ params required
+
+let add_false = List.map (fun ty -> false, ty)
+
+(* A parameter is constrained if either is is instantiated,
+ or it is a variable appearing in another parameter *)
+let constrained vars ty =
+ match ty.desc with
+ | Tvar _ -> List.exists (fun tl -> List.memq ty tl) vars
+ | _ -> true
+
+let for_constr = function
+ | Types.Cstr_tuple l -> add_false l
+ | Types.Cstr_record l ->
+ List.map
+ (fun {Types.ld_mutable; ld_type} -> (ld_mutable = Mutable, ld_type))
+ l
+
+let compute_variance_gadt env check (required, loc as rloc) decl
+ (tl, ret_type_opt) =
+ match ret_type_opt with
+ | None ->
+ compute_variance_type env check rloc {decl with type_private = Private}
+ (for_constr tl)
+ | Some ret_type ->
+ match Ctype.repr ret_type with
+ | {desc=Tconstr (_, tyl, _)} ->
+ (* let tyl = List.map (Ctype.expand_head env) tyl in *)
+ let tyl = List.map Ctype.repr tyl in
+ let fvl = List.map (Ctype.free_variables ?env:None) tyl in
+ let _ =
+ List.fold_left2
+ (fun (fv1,fv2) ty (c,n,i) ->
+ match fv2 with [] -> assert false
+ | fv :: fv2 ->
+ (* fv1 @ fv2 = free_variables of other parameters *)
+ if (c||n) && constrained (fv1 @ fv2) ty then
+ raise (Error(loc, Varying_anonymous));
+ (fv :: fv1, fv2))
+ ([], fvl) tyl required
+ in
+ compute_variance_type env check rloc
+ {decl with type_params = tyl; type_private = Private}
+ (for_constr tl)
+ | _ -> assert false
+
+let compute_variance_extension env check decl ext rloc =
+ compute_variance_gadt env check rloc
+ {decl with type_params = ext.ext_type_params}
+ (ext.ext_args, ext.ext_ret_type)
+
+let compute_variance_decl env check decl (required, _ as rloc) =
+ if (decl.type_kind = Type_abstract || decl.type_kind = Type_open)
+ && decl.type_manifest = None then
+ List.map
+ (fun (c, n, i) ->
+ make (not n) (not c) (decl.type_kind <> Type_abstract || i))
+ required
+ else
+ let mn =
+ match decl.type_manifest with
+ None -> []
+ | Some ty -> [false, ty]
+ in
+ match decl.type_kind with
+ Type_abstract | Type_open ->
+ compute_variance_type env check rloc decl mn
+ | Type_variant tll ->
+ if List.for_all (fun c -> c.Types.cd_res = None) tll then
+ compute_variance_type env check rloc decl
+ (mn @ List.flatten (List.map (fun c -> for_constr c.Types.cd_args)
+ tll))
+ else begin
+ let mn =
+ List.map (fun (_,ty) -> (Types.Cstr_tuple [ty],None)) mn in
+ let tll =
+ mn @ List.map (fun c -> c.Types.cd_args, c.Types.cd_res) tll in
+ match List.map (compute_variance_gadt env check rloc decl) tll with
+ | vari :: rem ->
+ let varl = List.fold_left (List.map2 Variance.union) vari rem in
+ List.map
+ Variance.(fun v -> if mem Pos v && mem Neg v then full else v)
+ varl
+ | _ -> assert false
+ end
+ | Type_record (ftl, _) ->
+ compute_variance_type env check rloc decl
+ (mn @ List.map (fun {Types.ld_mutable; ld_type} ->
+ (ld_mutable = Mutable, ld_type)) ftl)
+
+let is_sharp id =
+ let s = Ident.name id in
+ String.length s > 0 && s.[0] = '#'
+
+let rec compute_variance_fixpoint env decls required variances =
+ let new_decls =
+ List.map2
+ (fun (id, decl) variance -> id, {decl with type_variance = variance})
+ decls variances
+ in
+ let new_env =
+ List.fold_right
+ (fun (id, decl) env -> Env.add_type ~check:true id decl env)
+ new_decls env
+ in
+ let new_variances =
+ List.map2
+ (fun (id, decl) -> compute_variance_decl new_env false decl)
+ new_decls required
+ in
+ let new_variances =
+ List.map2 (List.map2 Variance.union) new_variances variances in
+ if new_variances <> variances then
+ compute_variance_fixpoint env decls required new_variances
+ else begin
+ (* List.iter (fun (id, decl) ->
+ Printf.eprintf "%s:" (Ident.name id);
+ List.iter (fun (v : Variance.t) ->
+ Printf.eprintf " %x" (Obj.magic v : int))
+ decl.type_variance;
+ prerr_endline "")
+ new_decls; *)
+ List.iter2
+ (fun (id, decl) req -> if not (is_sharp id) then
+ ignore (compute_variance_decl new_env true decl req))
+ new_decls required;
+ new_decls, new_env
+ end
+
+let init_variance (id, decl) =
+ List.map (fun _ -> Variance.null) decl.type_params
+
+let add_injectivity =
+ List.map
+ (function
+ | Covariant -> (true, false, false)
+ | Contravariant -> (false, true, false)
+ | Invariant -> (false, false, false)
+ )
+
+(* for typeclass.ml *)
+let compute_variance_decls env cldecls =
+ let decls, required =
+ List.fold_right
+ (fun (obj_id, obj_abbr, cl_abbr, clty, cltydef, ci) (decls, req) ->
+ let variance = List.map snd ci.ci_params in
+ (obj_id, obj_abbr) :: decls,
+ (add_injectivity variance, ci.ci_loc) :: req)
+ cldecls ([],[])
+ in
+ let variances = List.map init_variance decls in
+ let (decls, _) = compute_variance_fixpoint env decls required variances in
+ List.map2
+ (fun (_,decl) (_, _, cl_abbr, clty, cltydef, _) ->
+ let variance = decl.type_variance in
+ (decl, {cl_abbr with type_variance = variance},
+ {clty with cty_variance = variance},
+ {cltydef with clty_variance = variance}))
+ decls cldecls
+
+(* Check multiple declarations of labels/constructors *)
+
+let check_duplicates sdecl_list =
+ let labels = Hashtbl.create 7 and constrs = Hashtbl.create 7 in
+ List.iter
+ (fun sdecl -> match sdecl.ptype_kind with
+ Ptype_variant cl ->
+ List.iter
+ (fun pcd ->
+ try
+ let name' = Hashtbl.find constrs pcd.pcd_name.txt in
+ Location.prerr_warning pcd.pcd_loc
+ (Warnings.Duplicate_definitions
+ ("constructor", pcd.pcd_name.txt, name',
+ sdecl.ptype_name.txt))
+ with Not_found ->
+ Hashtbl.add constrs pcd.pcd_name.txt sdecl.ptype_name.txt)
+ cl
+ | Ptype_record fl ->
+ List.iter
+ (fun {pld_name=cname;pld_loc=loc} ->
+ try
+ let name' = Hashtbl.find labels cname.txt in
+ Location.prerr_warning loc
+ (Warnings.Duplicate_definitions
+ ("label", cname.txt, name', sdecl.ptype_name.txt))
+ with Not_found -> Hashtbl.add labels cname.txt sdecl.ptype_name.txt)
+ fl
+ | Ptype_abstract -> ()
+ | Ptype_open -> ())
+ sdecl_list
+
+(* Force recursion to go through id for private types*)
+let name_recursion sdecl id decl =
+ match decl with
+ | { type_kind = Type_abstract;
+ type_manifest = Some ty;
+ type_private = Private; } when is_fixed_type sdecl ->
+ let ty = Ctype.repr ty in
+ let ty' = Btype.newty2 ty.level ty.desc in
+ if Ctype.deep_occur ty ty' then
+ let td = Tconstr(Path.Pident id, decl.type_params, ref Mnil) in
+ Btype.link_type ty (Btype.newty2 ty.level td);
+ {decl with type_manifest = Some ty'}
+ else decl
+ | _ -> decl
+
+(* Translate a set of type declarations, mutually recursive or not *)
+let transl_type_decl env rec_flag sdecl_list =
+ (* Add dummy types for fixed rows *)
+ let fixed_types = List.filter is_fixed_type sdecl_list in
+ let sdecl_list =
+ List.map
+ (fun sdecl ->
+ let ptype_name =
+ mkloc (sdecl.ptype_name.txt ^"#row") sdecl.ptype_name.loc in
+ {sdecl with
+ ptype_name; ptype_kind = Ptype_abstract; ptype_manifest = None})
+ fixed_types
+ @ sdecl_list
+ in
+
+ (* Create identifiers. *)
+ let id_list =
+ List.map (fun sdecl -> Ident.create sdecl.ptype_name.txt) sdecl_list
+ in
+ (*
+ Since we've introduced fresh idents, make sure the definition
+ level is at least the binding time of these events. Otherwise,
+ passing one of the recursively-defined type constrs as argument
+ to an abbreviation may fail.
+ *)
+ Ctype.init_def(Ident.current_time());
+ Ctype.begin_def();
+ (* Enter types. *)
+ let temp_env =
+ match rec_flag with
+ | Asttypes.Nonrecursive -> env
+ | Asttypes.Recursive -> List.fold_left2 enter_type env sdecl_list id_list
+ in
+ (* Translate each declaration. *)
+ let current_slot = ref None in
+ let warn_unused = Warnings.is_active (Warnings.Unused_type_declaration "") in
+ let id_slots id =
+ match rec_flag with
+ | Asttypes.Recursive when warn_unused ->
+ (* See typecore.ml for a description of the algorithm used
+ to detect unused declarations in a set of recursive definitions. *)
+ let slot = ref [] in
+ let td = Env.find_type (Path.Pident id) temp_env in
+ let name = Ident.name id in
+ Env.set_type_used_callback
+ name td
+ (fun old_callback ->
+ match !current_slot with
+ | Some slot -> slot := (name, td) :: !slot
+ | None ->
+ List.iter (fun (name, d) -> Env.mark_type_used env name d)
+ (get_ref slot);
+ old_callback ()
+ );
+ id, Some slot
+ | Asttypes.Recursive | Asttypes.Nonrecursive ->
+ id, None
+ in
+ let transl_declaration name_sdecl (id, slot) =
+ current_slot := slot; transl_declaration temp_env name_sdecl id in
+ let tdecls =
+ List.map2 transl_declaration sdecl_list (List.map id_slots id_list) in
+ let decls =
+ List.map (fun tdecl -> (tdecl.typ_id, tdecl.typ_type)) tdecls in
+ current_slot := None;
+ (* Check for duplicates *)
+ check_duplicates sdecl_list;
+ (* Build the final env. *)
+ let newenv =
+ List.fold_right
+ (fun (id, decl) env -> Env.add_type ~check:true id decl env)
+ decls env
+ in
+ (* Update stubs *)
+ begin match rec_flag with
+ | Asttypes.Nonrecursive -> ()
+ | Asttypes.Recursive ->
+ List.iter2
+ (fun id sdecl -> update_type temp_env newenv id sdecl.ptype_loc)
+ id_list sdecl_list
+ end;
+ (* Generalize type declarations. *)
+ Ctype.end_def();
+ List.iter (fun (_, decl) -> generalize_decl decl) decls;
+ (* Check for ill-formed abbrevs *)
+ let id_loc_list =
+ List.map2 (fun id sdecl -> (id, sdecl.ptype_loc))
+ id_list sdecl_list
+ in
+ List.iter (fun (id, decl) ->
+ check_well_founded_manifest newenv (List.assoc id id_loc_list)
+ (Path.Pident id) decl)
+ decls;
+ let to_check =
+ function Path.Pident id -> List.mem_assoc id id_loc_list | _ -> false in
+ List.iter (fun (id, decl) ->
+ check_well_founded_decl newenv (List.assoc id id_loc_list) (Path.Pident id)
+ decl to_check)
+ decls;
+ List.iter (check_abbrev_recursion newenv id_loc_list to_check) tdecls;
+ (* Check that all type variable are closed *)
+ List.iter2
+ (fun sdecl tdecl ->
+ let decl = tdecl.typ_type in
+ match Ctype.closed_type_decl decl with
+ Some ty -> raise(Error(sdecl.ptype_loc, Unbound_type_var(ty,decl)))
+ | None -> ())
+ sdecl_list tdecls;
+ (* Check that constraints are enforced *)
+ List.iter2 (check_constraints newenv) sdecl_list decls;
+ (* Name recursion *)
+ let decls =
+ List.map2 (fun sdecl (id, decl) -> id, name_recursion sdecl id decl)
+ sdecl_list decls
+ in
+ (* Add variances to the environment *)
+ let required =
+ List.map
+ (fun sdecl ->
+ add_injectivity (List.map snd sdecl.ptype_params),
+ sdecl.ptype_loc
+ )
+ sdecl_list
+ in
+ let final_decls, final_env =
+ compute_variance_fixpoint env decls required (List.map init_variance decls)
+ in
+ (* Check re-exportation *)
+ List.iter2 (check_abbrev final_env) sdecl_list final_decls;
+ (* Keep original declaration *)
+ let final_decls =
+ List.map2
+ (fun tdecl (id2, decl) ->
+ { tdecl with typ_type = decl }
+ ) tdecls final_decls
+ in
+ (* Done *)
+ (final_decls, final_env)
+
+(* Translating type extensions *)
+
+let transl_extension_constructor env type_path type_params
+ typext_params priv sext =
+ let id = Ident.create sext.pext_name.txt in
+ let args, ret_type, kind =
+ match sext.pext_kind with
+ Pext_decl(sargs, sret_type) ->
+ let targs, tret_type, args, ret_type =
+ make_constructor sext.pext_loc env type_path typext_params
+ sargs sret_type
+ in
+ args, ret_type, Text_decl(targs, tret_type)
+ | Pext_rebind lid ->
+ let cdescr = Typetexp.find_constructor env sext.pext_loc lid.txt in
+ let usage =
+ if cdescr.cstr_private = Private || priv = Public
+ then Env.Positive else Env.Privatize
+ in
+ Env.mark_constructor usage env (Longident.last lid.txt) cdescr;
+ let (args, cstr_res) = Ctype.instance_constructor cdescr in
+ let res, ret_type =
+ if cdescr.cstr_generalized then
+ let params = Ctype.instance_list env type_params in
+ let res = Ctype.newconstr type_path params in
+ let ret_type = Some (Ctype.newconstr type_path params) in
+ res, ret_type
+ else (Ctype.newconstr type_path typext_params), None
+ in
+ begin
+ try
+ Ctype.unify env cstr_res res
+ with Ctype.Unify trace ->
+ raise (Error(lid.loc,
+ Rebind_wrong_type(lid.txt, env, trace)))
+ end;
+ (* Remove "_" names from parameters used in the constructor *)
+ if not cdescr.cstr_generalized then begin
+ let vars =
+ Ctype.free_variables (Btype.newgenty (Ttuple args))
+ in
+ List.iter
+ (function {desc = Tvar (Some "_")} as ty ->
+ if List.memq ty vars then ty.desc <- Tvar None
+ | _ -> ())
+ typext_params
+ end;
+ (* Ensure that constructor's type matches the type being extended *)
+ let cstr_type_path, cstr_type_params =
+ match cdescr.cstr_res.desc with
+ Tconstr (p, _, _) ->
+ let decl = Env.find_type p env in
+ p, decl.type_params
+ | _ -> assert false
+ in
+ let cstr_types =
+ (Btype.newgenty
+ (Tconstr(cstr_type_path, cstr_type_params, ref Mnil)))
+ :: cstr_type_params
+ in
+ let ext_types =
+ (Btype.newgenty
+ (Tconstr(type_path, type_params, ref Mnil)))
+ :: type_params
+ in
+ if not (Ctype.equal env true cstr_types ext_types) then
+ raise (Error(lid.loc,
+ Rebind_mismatch(lid.txt, cstr_type_path, type_path)));
+ (* Disallow rebinding private constructors to non-private *)
+ begin
+ match cdescr.cstr_private, priv with
+ Private, Public ->
+ raise (Error(lid.loc, Rebind_private lid.txt))
+ | _ -> ()
+ end;
+ let path =
+ match cdescr.cstr_tag with
+ Cstr_extension(path, _) -> path
+ | _ -> assert false
+ in
+ let args =
+ match cdescr.cstr_inlined with
+ | None ->
+ Types.Cstr_tuple args
+ | Some decl ->
+ let tl =
+ match args with
+ | [ {desc=Tconstr(_, tl, _)} ] -> tl
+ | _ -> assert false
+ in
+ let decl = Ctype.instance_declaration decl in
+ assert (List.length decl.type_params = List.length tl);
+ List.iter2 (Ctype.unify env) decl.type_params tl;
+ let lbls =
+ match decl.type_kind with
+ | Type_record (lbls, Record_extension) -> lbls
+ | _ -> assert false
+ in
+ Types.Cstr_record lbls
+ in
+ args, ret_type, Text_rebind(path, lid)
+ in
+ let ext =
+ { ext_type_path = type_path;
+ ext_type_params = typext_params;
+ ext_args = args;
+ ext_ret_type = ret_type;
+ ext_private = priv;
+ Types.ext_loc = sext.pext_loc;
+ Types.ext_attributes = sext.pext_attributes; }
+ in
+ { ext_id = id;
+ ext_name = sext.pext_name;
+ ext_type = ext;
+ ext_kind = kind;
+ Typedtree.ext_loc = sext.pext_loc;
+ Typedtree.ext_attributes = sext.pext_attributes; }
+
+let transl_type_extension check_open env loc styext =
+ reset_type_variables();
+ Ctype.begin_def();
+ let (type_path, type_decl) =
+ Typetexp.find_type env loc styext.ptyext_path.txt
+ in
+ begin
+ match type_decl.type_kind with
+ Type_open -> ()
+ | Type_abstract ->
+ if check_open then begin
+ try
+ let {pext_loc} =
+ List.find (function {pext_kind = Pext_decl _} -> true
+ | {pext_kind = Pext_rebind _} -> false)
+ styext.ptyext_constructors
+ in
+ raise (Error(pext_loc, Not_open_type type_path))
+ with Not_found -> ()
+ end
+ | _ -> raise (Error(loc, Not_extensible_type type_path))
+ end;
+ let type_variance =
+ List.map (fun v ->
+ let (co, cn) = Variance.get_upper v in
+ (not cn, not co, false))
+ type_decl.type_variance
+ in
+ let err =
+ if type_decl.type_arity <> List.length styext.ptyext_params then
+ [Includecore.Arity]
+ else
+ if List.for_all2
+ (fun (c1, n1, _) (c2, n2, _) -> (not c2 || c1) && (not n2 || n1))
+ type_variance
+ (add_injectivity (List.map snd styext.ptyext_params))
+ then [] else [Includecore.Variance]
+ in
+ if err <> [] then
+ raise (Error(loc, Extension_mismatch (type_path, err)));
+ let ttype_params = make_params env styext.ptyext_params in
+ let type_params = List.map (fun (cty, _) -> cty.ctyp_type) ttype_params in
+ List.iter2 (Ctype.unify_var env)
+ (Ctype.instance_list env type_decl.type_params)
+ type_params;
+ let constructors =
+ List.map (transl_extension_constructor env type_path
+ type_decl.type_params type_params styext.ptyext_private)
+ styext.ptyext_constructors
+ in
+ Ctype.end_def();
+ (* Generalize types *)
+ List.iter Ctype.generalize type_params;
+ List.iter
+ (fun ext ->
+ Btype.iter_type_expr_cstr_args Ctype.generalize ext.ext_type.ext_args;
+ may Ctype.generalize ext.ext_type.ext_ret_type)
+ constructors;
+ (* Check that all type variable are closed *)
+ List.iter
+ (fun ext ->
+ match Ctype.closed_extension_constructor ext.ext_type with
+ Some ty ->
+ raise(Error(ext.ext_loc, Unbound_type_var_ext(ty, ext.ext_type)))
+ | None -> ())
+ constructors;
+ (* Check variances are correct *)
+ List.iter
+ (fun ext->
+ ignore (compute_variance_extension env true type_decl
+ ext.ext_type (type_variance, loc)))
+ constructors;
+ (* Add extension constructors to the environment *)
+ let newenv =
+ List.fold_left
+ (fun env ext ->
+ Env.add_extension ~check:true ext.ext_id ext.ext_type env)
+ env constructors
+ in
+ let tyext =
+ { tyext_path = type_path;
+ tyext_txt = styext.ptyext_path;
+ tyext_params = ttype_params;
+ tyext_constructors = constructors;
+ tyext_private = styext.ptyext_private;
+ tyext_attributes = styext.ptyext_attributes; }
+ in
+ (tyext, newenv)
+
+let transl_exception env sext =
+ reset_type_variables();
+ Ctype.begin_def();
+ let ext =
+ transl_extension_constructor env
+ Predef.path_exn [] [] Asttypes.Public sext
+ in
+ Ctype.end_def();
+ (* Generalize types *)
+ Btype.iter_type_expr_cstr_args Ctype.generalize ext.ext_type.ext_args;
+ may Ctype.generalize ext.ext_type.ext_ret_type;
+ (* Check that all type variable are closed *)
+ begin match Ctype.closed_extension_constructor ext.ext_type with
+ Some ty ->
+ raise (Error(ext.ext_loc, Unbound_type_var_ext(ty, ext.ext_type)))
+ | None -> ()
+ end;
+ let newenv = Env.add_extension ~check:true ext.ext_id ext.ext_type env in
+ ext, newenv
+
+type native_repr_attribute =
+ | Native_repr_attr_absent
+ | Native_repr_attr_present of native_repr_kind
+
+let get_native_repr_attribute core_type =
+ match
+ List.filter
+ (fun (n, _) ->
+ match n.Location.txt with
+ | "unboxed" | "untagged" -> true
+ | _ -> false)
+ core_type.ptyp_attributes
+ with
+ | [] ->
+ Native_repr_attr_absent
+ | _ :: (n, _) :: _ ->
+ raise (Error (n.Location.loc, Multiple_native_repr_attributes))
+ | [(n, payload)] ->
+ let kind = if n.txt = "unboxed" then Unboxed else Untagged in
+ match payload with
+ | PStr [] ->
+ Native_repr_attr_present kind
+ | _ ->
+ raise (Error (n.Location.loc,
+ Invalid_native_repr_attribute_payload kind))
+
+let native_repr_of_type env kind ty =
+ match kind, (Ctype.expand_head_opt env ty).desc with
+ | Untagged, Tconstr (path, _, _) when Path.same path Predef.path_int ->
+ Some Untagged_int
+ | Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_float ->
+ Some Unboxed_float
+ | Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_int32 ->
+ Some (Unboxed_integer Pint32)
+ | Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_int64 ->
+ Some (Unboxed_integer Pint64)
+ | Unboxed, Tconstr (path, _, _) when Path.same path Predef.path_nativeint ->
+ Some (Unboxed_integer Pnativeint)
+ | _ ->
+ None
+
+let make_native_repr env core_type ty =
+ match get_native_repr_attribute core_type with
+ | Native_repr_attr_absent -> Same_as_ocaml_repr
+ | Native_repr_attr_present kind ->
+ begin match native_repr_of_type env kind ty with
+ | None ->
+ raise (Error (core_type.ptyp_loc, Cannot_unbox_or_untag_type kind))
+ | Some repr -> repr
+ end
+
+let rec parse_native_repr_attributes env core_type ty =
+ match core_type.ptyp_desc, (Ctype.repr ty).desc with
+ | Ptyp_arrow (_, ct1, ct2), Tarrow (_, t1, t2, _) ->
+ let repr_arg = make_native_repr env ct1 t1 in
+ let repr_args, repr_res = parse_native_repr_attributes env ct2 t2 in
+ (repr_arg :: repr_args, repr_res)
+ | Ptyp_arrow _, _ | _, Tarrow _ -> assert false
+ | _ -> ([], make_native_repr env core_type ty)
+
+(* Translate a value declaration *)
+let transl_value_decl env loc valdecl =
+ let cty = Typetexp.transl_type_scheme env valdecl.pval_type in
+ let ty = cty.ctyp_type in
+ let v =
+ match valdecl.pval_prim with
+ [] when Env.is_in_signature env ->
+ { val_type = ty; val_kind = Val_reg; Types.val_loc = loc;
+ val_attributes = valdecl.pval_attributes }
+ | [] ->
+ raise (Error(valdecl.pval_loc, Val_in_structure))
+ | _ ->
+ let native_repr_args, native_repr_res =
+ parse_native_repr_attributes env valdecl.pval_type ty
+ in
+ let prim =
+ Primitive.parse_declaration valdecl
+ ~native_repr_args
+ ~native_repr_res
+ in
+ if prim.prim_arity = 0 &&
+ (prim.prim_name = "" || prim.prim_name.[0] <> '%') then
+ raise(Error(valdecl.pval_type.ptyp_loc, Null_arity_external));
+ if !Clflags.native_code
+ && prim.prim_arity > 5
+ && prim.prim_native_name = ""
+ then raise(Error(valdecl.pval_type.ptyp_loc, Missing_native_external));
+ { val_type = ty; val_kind = Val_prim prim; Types.val_loc = loc;
+ val_attributes = valdecl.pval_attributes }
+ in
+ let (id, newenv) =
+ Env.enter_value valdecl.pval_name.txt v env
+ ~check:(fun s -> Warnings.Unused_value_declaration s)
+ in
+ let desc =
+ {
+ val_id = id;
+ val_name = valdecl.pval_name;
+ val_desc = cty; val_val = v;
+ val_prim = valdecl.pval_prim;
+ val_loc = valdecl.pval_loc;
+ val_attributes = valdecl.pval_attributes;
+ }
+ in
+ desc, newenv
+
+(* Translate a "with" constraint -- much simplified version of
+ transl_type_decl. *)
+let transl_with_constraint env id row_path orig_decl sdecl =
+ Env.mark_type_used env (Ident.name id) orig_decl;
+ reset_type_variables();
+ Ctype.begin_def();
+ let tparams = make_params env sdecl.ptype_params in
+ let params = List.map (fun (cty, _) -> cty.ctyp_type) tparams in
+ let orig_decl = Ctype.instance_declaration orig_decl in
+ let arity_ok = List.length params = orig_decl.type_arity in
+ if arity_ok then
+ List.iter2 (Ctype.unify_var env) params orig_decl.type_params;
+ let constraints = List.map
+ (function (ty, ty', loc) ->
+ try
+ let cty = transl_simple_type env false ty in
+ let cty' = transl_simple_type env false ty' in
+ let ty = cty.ctyp_type in
+ let ty' = cty'.ctyp_type in
+ Ctype.unify env ty ty';
+ (cty, cty', loc)
+ with Ctype.Unify tr ->
+ raise(Error(loc, Inconsistent_constraint (env, tr))))
+ sdecl.ptype_cstrs
+ in
+ let no_row = not (is_fixed_type sdecl) in
+ let (tman, man) = match sdecl.ptype_manifest with
+ None -> None, None
+ | Some sty ->
+ let cty = transl_simple_type env no_row sty in
+ Some cty, Some cty.ctyp_type
+ in
+ let priv =
+ if sdecl.ptype_private = Private then Private else
+ if arity_ok && orig_decl.type_kind <> Type_abstract
+ then orig_decl.type_private else sdecl.ptype_private
+ in
+ if arity_ok && orig_decl.type_kind <> Type_abstract
+ && sdecl.ptype_private = Private then
+ Location.prerr_warning sdecl.ptype_loc
+ (Warnings.Deprecated "spurious use of private");
+ let decl =
+ { type_params = params;
+ type_arity = List.length params;
+ type_kind =
+ if arity_ok && man <> None then orig_decl.type_kind else Type_abstract;
+ type_private = priv;
+ type_manifest = man;
+ type_variance = [];
+ type_newtype_level = None;
+ type_loc = sdecl.ptype_loc;
+ type_attributes = sdecl.ptype_attributes;
+ }
+ in
+ begin match row_path with None -> ()
+ | Some p -> set_fixed_row env sdecl.ptype_loc p decl
+ end;
+ begin match Ctype.closed_type_decl decl with None -> ()
+ | Some ty -> raise(Error(sdecl.ptype_loc, Unbound_type_var(ty,decl)))
+ end;
+ let decl = name_recursion sdecl id decl in
+ let decl =
+ {decl with type_variance =
+ compute_variance_decl env true decl
+ (add_injectivity (List.map snd sdecl.ptype_params), sdecl.ptype_loc)} in
+ Ctype.end_def();
+ generalize_decl decl;
+ {
+ typ_id = id;
+ typ_name = sdecl.ptype_name;
+ typ_params = tparams;
+ typ_type = decl;
+ typ_cstrs = constraints;
+ typ_loc = sdecl.ptype_loc;
+ typ_manifest = tman;
+ typ_kind = Ttype_abstract;
+ typ_private = sdecl.ptype_private;
+ typ_attributes = sdecl.ptype_attributes;
+ }
+
+(* Approximate a type declaration: just make all types abstract *)
+
+let abstract_type_decl arity =
+ let rec make_params n =
+ if n <= 0 then [] else Ctype.newvar() :: make_params (n-1) in
+ Ctype.begin_def();
+ let decl =
+ { type_params = make_params arity;
+ type_arity = arity;
+ type_kind = Type_abstract;
+ type_private = Public;
+ type_manifest = None;
+ type_variance = replicate_list Variance.full arity;
+ type_newtype_level = None;
+ type_loc = Location.none;
+ type_attributes = [];
+ } in
+ Ctype.end_def();
+ generalize_decl decl;
+ decl
+
+let approx_type_decl env sdecl_list =
+ List.map
+ (fun sdecl ->
+ (Ident.create sdecl.ptype_name.txt,
+ abstract_type_decl (List.length sdecl.ptype_params)))
+ sdecl_list
+
+(* Variant of check_abbrev_recursion to check the well-formedness
+ conditions on type abbreviations defined within recursive modules. *)
+
+let check_recmod_typedecl env loc recmod_ids path decl =
+ (* recmod_ids is the list of recursively-defined module idents.
+ (path, decl) is the type declaration to be checked. *)
+ let to_check path =
+ List.exists (fun id -> Path.isfree id path) recmod_ids in
+ check_well_founded_decl env loc path decl to_check;
+ check_recursion env loc path decl to_check
+
+
+(**** Error report ****)
+
+open Format
+
+let explain_unbound_gen ppf tv tl typ kwd pr =
+ try
+ let ti = List.find (fun ti -> Ctype.deep_occur tv (typ ti)) tl in
+ let ty0 = (* Hack to force aliasing when needed *)
+ Btype.newgenty (Tobject(tv, ref None)) in
+ Printtyp.reset_and_mark_loops_list [typ ti; ty0];
+ fprintf ppf
+ ".@.@[<hov2>In %s@ %a@;<1 -2>the variable %a is unbound@]"
+ kwd pr ti Printtyp.type_expr tv
+ with Not_found -> ()
+
+let explain_unbound ppf tv tl typ kwd lab =
+ explain_unbound_gen ppf tv tl typ kwd
+ (fun ppf ti -> fprintf ppf "%s%a" (lab ti) Printtyp.type_expr (typ ti))
+
+let explain_unbound_single ppf tv ty =
+ let trivial ty =
+ explain_unbound ppf tv [ty] (fun t -> t) "type" (fun _ -> "") in
+ match (Ctype.repr ty).desc with
+ Tobject(fi,_) ->
+ let (tl, rv) = Ctype.flatten_fields fi in
+ if rv == tv then trivial ty else
+ explain_unbound ppf tv tl (fun (_,_,t) -> t)
+ "method" (fun (lab,_,_) -> lab ^ ": ")
+ | Tvariant row ->
+ let row = Btype.row_repr row in
+ if row.row_more == tv then trivial ty else
+ explain_unbound ppf tv row.row_fields
+ (fun (l,f) -> match Btype.row_field_repr f with
+ Rpresent (Some t) -> t
+ | Reither (_,[t],_,_) -> t
+ | Reither (_,tl,_,_) -> Btype.newgenty (Ttuple tl)
+ | _ -> Btype.newgenty (Ttuple[]))
+ "case" (fun (lab,_) -> "`" ^ lab ^ " of ")
+ | _ -> trivial ty
+
+
+let tys_of_constr_args = function
+ | Types.Cstr_tuple tl -> tl
+ | Types.Cstr_record lbls -> List.map (fun l -> l.Types.ld_type) lbls
+
+let report_error ppf = function
+ | Repeated_parameter ->
+ fprintf ppf "A type parameter occurs several times"
+ | Duplicate_constructor s ->
+ fprintf ppf "Two constructors are named %s" s
+ | Too_many_constructors ->
+ fprintf ppf
+ "@[Too many non-constant constructors@ -- maximum is %i %s@]"
+ (Config.max_tag + 1) "non-constant constructors"
+ | Duplicate_label s ->
+ fprintf ppf "Two labels are named %s" s
+ | Recursive_abbrev s ->
+ fprintf ppf "The type abbreviation %s is cyclic" s
+ | Cycle_in_def (s, ty) ->
+ Printtyp.reset_and_mark_loops ty;
+ fprintf ppf "@[<v>The definition of %s contains a cycle:@ %a@]"
+ s Printtyp.type_expr ty
+ | Definition_mismatch (ty, errs) ->
+ Printtyp.reset_and_mark_loops ty;
+ fprintf ppf "@[<v>@[<hov>%s@ %s@;<1 2>%a@]%a@]"
+ "This variant or record definition" "does not match that of type"
+ Printtyp.type_expr ty
+ (Includecore.report_type_mismatch "the original" "this" "definition")
+ errs
+ | Constraint_failed (ty, ty') ->
+ Printtyp.reset_and_mark_loops ty;
+ Printtyp.mark_loops ty';
+ fprintf ppf "@[%s@ @[<hv>Type@ %a@ should be an instance of@ %a@]@]"
+ "Constraints are not satisfied in this type."
+ Printtyp.type_expr ty Printtyp.type_expr ty'
+ | Parameters_differ (path, ty, ty') ->
+ Printtyp.reset_and_mark_loops ty;
+ Printtyp.mark_loops ty';
+ fprintf ppf
+ "@[<hv>In the definition of %s, type@ %a@ should be@ %a@]"
+ (Path.name path) Printtyp.type_expr ty Printtyp.type_expr ty'
+ | Inconsistent_constraint (env, trace) ->
+ fprintf ppf "The type constraints are not consistent.@.";
+ Printtyp.report_unification_error ppf env trace
+ (fun ppf -> fprintf ppf "Type")
+ (fun ppf -> fprintf ppf "is not compatible with type")
+ | Type_clash (env, trace) ->
+ Printtyp.report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "This type constructor expands to type")
+ (function ppf ->
+ fprintf ppf "but is used here with type")
+ | Null_arity_external ->
+ fprintf ppf "External identifiers must be functions"
+ | Missing_native_external ->
+ fprintf ppf "@[<hv>An external function with more than 5 arguments \
+ requires a second stub function@ \
+ for native-code compilation@]"
+ | Unbound_type_var (ty, decl) ->
+ fprintf ppf "A type variable is unbound in this type declaration";
+ let ty = Ctype.repr ty in
+ begin match decl.type_kind, decl.type_manifest with
+ | Type_variant tl, _ ->
+ explain_unbound_gen ppf ty tl (fun c ->
+ let tl = tys_of_constr_args c.cd_args in
+ Btype.newgenty (Ttuple tl)
+ )
+ "case" (fun ppf c ->
+ fprintf ppf
+ "%s of %a" (Ident.name c.Types.cd_id)
+ Printtyp.constructor_arguments c.cd_args)
+ | Type_record (tl, _), _ ->
+ explain_unbound ppf ty tl (fun l -> l.Types.ld_type)
+ "field" (fun l -> Ident.name l.Types.ld_id ^ ": ")
+ | Type_abstract, Some ty' ->
+ explain_unbound_single ppf ty ty'
+ | _ -> ()
+ end
+ | Unbound_type_var_ext (ty, ext) ->
+ fprintf ppf "A type variable is unbound in this extension constructor";
+ let args = tys_of_constr_args ext.ext_args in
+ explain_unbound ppf ty args (fun c -> c) "type" (fun _ -> "")
+ | Not_open_type path ->
+ fprintf ppf "@[%s@ %a@]"
+ "Cannot extend type definition"
+ Printtyp.path path
+ | Not_extensible_type path ->
+ fprintf ppf "@[%s@ %a@ %s@]"
+ "Type"
+ Printtyp.path path
+ "is not extensible"
+ | Extension_mismatch (path, errs) ->
+ fprintf ppf "@[<v>@[<hov>%s@ %s@;<1 2>%s@]%a@]"
+ "This extension" "does not match the definition of type"
+ (Path.name path)
+ (Includecore.report_type_mismatch
+ "the type" "this extension" "definition")
+ errs
+ | Rebind_wrong_type (lid, env, trace) ->
+ Printtyp.report_unification_error ppf env trace
+ (function ppf ->
+ fprintf ppf "The constructor %a@ has type"
+ Printtyp.longident lid)
+ (function ppf ->
+ fprintf ppf "but was expected to be of type")
+ | Rebind_mismatch (lid, p, p') ->
+ fprintf ppf
+ "@[%s@ %a@ %s@ %s@ %s@ %s@ %s@]"
+ "The constructor" Printtyp.longident lid
+ "extends type" (Path.name p)
+ "whose declaration does not match"
+ "the declaration of type" (Path.name p')
+ | Rebind_private lid ->
+ fprintf ppf "@[%s@ %a@ %s@]"
+ "The constructor"
+ Printtyp.longident lid
+ "is private"
+ | Bad_variance (n, v1, v2) ->
+ let variance (p,n,i) =
+ let inj = if i then "injective " else "" in
+ match p, n with
+ true, true -> inj ^ "invariant"
+ | true, false -> inj ^ "covariant"
+ | false, true -> inj ^ "contravariant"
+ | false, false -> if inj = "" then "unrestricted" else inj
+ in
+ let suffix n =
+ let teen = (n mod 100)/10 = 1 in
+ match n mod 10 with
+ | 1 when not teen -> "st"
+ | 2 when not teen -> "nd"
+ | 3 when not teen -> "rd"
+ | _ -> "th"
+ in
+ if n = -1 then
+ fprintf ppf "@[%s@ %s@ It"
+ "In this definition, a type variable has a variance that"
+ "is not reflected by its occurrence in type parameters."
+ else if n = -2 then
+ fprintf ppf "@[%s@ %s@]"
+ "In this definition, a type variable cannot be deduced"
+ "from the type parameters."
+ else if n = -3 then
+ fprintf ppf "@[%s@ %s@ It"
+ "In this definition, a type variable has a variance that"
+ "cannot be deduced from the type parameters."
+ else
+ fprintf ppf "@[%s@ %s@ The %d%s type parameter"
+ "In this definition, expected parameter"
+ "variances are not satisfied."
+ n (suffix n);
+ if n <> -2 then
+ fprintf ppf " was expected to be %s,@ but it is %s.@]"
+ (variance v2) (variance v1)
+ | Unavailable_type_constructor p ->
+ fprintf ppf "The definition of type %a@ is unavailable" Printtyp.path p
+ | Bad_fixed_type r ->
+ fprintf ppf "This fixed type %s" r
+ | Varying_anonymous ->
+ fprintf ppf "@[%s@ %s@ %s@]"
+ "In this GADT definition," "the variance of some parameter"
+ "cannot be checked"
+ | Val_in_structure ->
+ fprintf ppf "Value declarations are only allowed in signatures"
+ | Invalid_native_repr_attribute_payload kind ->
+ fprintf ppf "[@%s] attribute does not accept a payload"
+ (string_of_native_repr_kind kind)
+ | Multiple_native_repr_attributes ->
+ fprintf ppf "Too many [@unboxed]/[@untagged] attributes"
+ | Cannot_unbox_or_untag_type Unboxed ->
+ fprintf ppf "Don't know how to unbox this type. Only float, int32, \
+ int64 and nativeint can be unboxed"
+ | Cannot_unbox_or_untag_type Untagged ->
+ fprintf ppf "Don't know how to untag this type. Only int \
+ can be untagged"
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, err) ->
+ Some (Location.error_of_printer loc report_error err)
+ | _ ->
+ None
+ )
diff --git a/typing/typedecl.mli b/typing/typedecl.mli
new file mode 100644
index 0000000000..7f3b96c204
--- /dev/null
+++ b/typing/typedecl.mli
@@ -0,0 +1,94 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Typing of type definitions and primitive definitions *)
+
+open Types
+open Format
+
+val transl_type_decl:
+ Env.t -> Asttypes.rec_flag -> Parsetree.type_declaration list ->
+ Typedtree.type_declaration list * Env.t
+
+val transl_exception:
+ Env.t ->
+ Parsetree.extension_constructor -> Typedtree.extension_constructor * Env.t
+
+val transl_type_extension:
+ bool -> Env.t -> Location.t -> Parsetree.type_extension ->
+ Typedtree.type_extension * Env.t
+
+val transl_value_decl:
+ Env.t -> Location.t ->
+ Parsetree.value_description -> Typedtree.value_description * Env.t
+
+val transl_with_constraint:
+ Env.t -> Ident.t -> Path.t option -> Types.type_declaration ->
+ Parsetree.type_declaration -> Typedtree.type_declaration
+
+val abstract_type_decl: int -> type_declaration
+val approx_type_decl:
+ Env.t -> Parsetree.type_declaration list ->
+ (Ident.t * type_declaration) list
+val check_recmod_typedecl:
+ Env.t -> Location.t -> Ident.t list -> Path.t -> type_declaration -> unit
+val check_coherence:
+ Env.t -> Location.t -> Ident.t -> type_declaration -> unit
+
+(* for fixed types *)
+val is_fixed_type : Parsetree.type_declaration -> bool
+
+(* for typeclass.ml *)
+val compute_variance_decls:
+ Env.t ->
+ (Ident.t * Types.type_declaration * Types.type_declaration *
+ Types.class_declaration * Types.class_type_declaration *
+ 'a Typedtree.class_infos) list ->
+ (Types.type_declaration * Types.type_declaration *
+ Types.class_declaration * Types.class_type_declaration) list
+
+type native_repr_kind = Unboxed | Untagged
+
+type error =
+ Repeated_parameter
+ | Duplicate_constructor of string
+ | Too_many_constructors
+ | Duplicate_label of string
+ | Recursive_abbrev of string
+ | Cycle_in_def of string * type_expr
+ | Definition_mismatch of type_expr * Includecore.type_mismatch list
+ | Constraint_failed of type_expr * type_expr
+ | Inconsistent_constraint of Env.t * (type_expr * type_expr) list
+ | Type_clash of Env.t * (type_expr * type_expr) list
+ | Parameters_differ of Path.t * type_expr * type_expr
+ | Null_arity_external
+ | Missing_native_external
+ | Unbound_type_var of type_expr * type_declaration
+ | Not_open_type of Path.t
+ | Not_extensible_type of Path.t
+ | Extension_mismatch of Path.t * Includecore.type_mismatch list
+ | Rebind_wrong_type of Longident.t * Env.t * (type_expr * type_expr) list
+ | Rebind_mismatch of Longident.t * Path.t * Path.t
+ | Rebind_private of Longident.t
+ | Bad_variance of int * (bool*bool*bool) * (bool*bool*bool)
+ | Unavailable_type_constructor of Path.t
+ | Bad_fixed_type of string
+ | Unbound_type_var_ext of type_expr * extension_constructor
+ | Varying_anonymous
+ | Val_in_structure
+ | Invalid_native_repr_attribute_payload of native_repr_kind
+ | Multiple_native_repr_attributes
+ | Cannot_unbox_or_untag_type of native_repr_kind
+
+exception Error of Location.t * error
+
+val report_error: formatter -> error -> unit
diff --git a/typing/typedtree.ml b/typing/typedtree.ml
new file mode 100644
index 0000000000..c3c9446f0b
--- /dev/null
+++ b/typing/typedtree.ml
@@ -0,0 +1,596 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Abstract syntax tree after typing *)
+
+open Misc
+open Asttypes
+open Types
+
+(* Value expressions for the core language *)
+
+type partial = Partial | Total
+type optional = Required | Optional
+
+type attribute = Parsetree.attribute
+type attributes = attribute list
+
+type pattern =
+ { pat_desc: pattern_desc;
+ pat_loc: Location.t;
+ pat_extra : (pat_extra * Location.t * attribute list) list;
+ pat_type: type_expr;
+ mutable pat_env: Env.t;
+ pat_attributes: attribute list;
+ }
+
+and pat_extra =
+ | Tpat_constraint of core_type
+ | Tpat_type of Path.t * Longident.t loc
+ | Tpat_unpack
+
+and pattern_desc =
+ Tpat_any
+ | Tpat_var of Ident.t * string loc
+ | Tpat_alias of pattern * Ident.t * string loc
+ | Tpat_constant of constant
+ | Tpat_tuple of pattern list
+ | Tpat_construct of
+ Longident.t loc * constructor_description * pattern list
+ | Tpat_variant of label * pattern option * row_desc ref
+ | Tpat_record of
+ (Longident.t loc * label_description * pattern) list *
+ closed_flag
+ | Tpat_array of pattern list
+ | Tpat_or of pattern * pattern * row_desc option
+ | Tpat_lazy of pattern
+
+and expression =
+ { exp_desc: expression_desc;
+ exp_loc: Location.t;
+ exp_extra: (exp_extra * Location.t * attribute list) list;
+ exp_type: type_expr;
+ exp_env: Env.t;
+ exp_attributes: attribute list;
+ }
+
+and exp_extra =
+ | Texp_constraint of core_type
+ | Texp_coerce of core_type option * core_type
+ | Texp_open of override_flag * Path.t * Longident.t loc * Env.t
+ | Texp_poly of core_type option
+ | Texp_newtype of string
+
+and expression_desc =
+ Texp_ident of Path.t * Longident.t loc * Types.value_description
+ | Texp_constant of constant
+ | Texp_let of rec_flag * value_binding list * expression
+ | Texp_function of arg_label * case list * partial
+ | Texp_apply of expression * (arg_label * expression option * optional) list
+ | Texp_match of expression * case list * case list * partial
+ | Texp_try of expression * case list
+ | Texp_tuple of expression list
+ | Texp_construct of
+ Longident.t loc * constructor_description * expression list
+ | Texp_variant of label * expression option
+ | Texp_record of
+ (Longident.t loc * label_description * expression) list *
+ expression option
+ | Texp_field of expression * Longident.t loc * label_description
+ | Texp_setfield of
+ expression * Longident.t loc * label_description * expression
+ | Texp_array of expression list
+ | Texp_ifthenelse of expression * expression * expression option
+ | Texp_sequence of expression * expression
+ | Texp_while of expression * expression
+ | Texp_for of
+ Ident.t * Parsetree.pattern * expression * expression * direction_flag *
+ expression
+ | Texp_send of expression * meth * expression option
+ | Texp_new of Path.t * Longident.t loc * Types.class_declaration
+ | Texp_instvar of Path.t * Path.t * string loc
+ | Texp_setinstvar of Path.t * Path.t * string loc * expression
+ | Texp_override of Path.t * (Path.t * string loc * expression) list
+ | Texp_letmodule of Ident.t * string loc * module_expr * expression
+ | Texp_assert of expression
+ | Texp_lazy of expression
+ | Texp_object of class_structure * string list
+ | Texp_pack of module_expr
+
+and meth =
+ Tmeth_name of string
+ | Tmeth_val of Ident.t
+
+and case =
+ {
+ c_lhs: pattern;
+ c_guard: expression option;
+ c_rhs: expression;
+ }
+
+(* Value expressions for the class language *)
+
+and class_expr =
+ {
+ cl_desc: class_expr_desc;
+ cl_loc: Location.t;
+ cl_type: Types.class_type;
+ cl_env: Env.t;
+ cl_attributes: attribute list;
+ }
+
+and class_expr_desc =
+ Tcl_ident of Path.t * Longident.t loc * core_type list
+ | Tcl_structure of class_structure
+ | Tcl_fun of
+ arg_label * pattern * (Ident.t * string loc * expression) list
+ * class_expr * partial
+ | Tcl_apply of class_expr * (arg_label * expression option * optional) list
+ | Tcl_let of rec_flag * value_binding list *
+ (Ident.t * string loc * expression) list * class_expr
+ | Tcl_constraint of
+ class_expr * class_type option * string list * string list * Concr.t
+ (* Visible instance variables, methods and concretes methods *)
+
+and class_structure =
+ {
+ cstr_self: pattern;
+ cstr_fields: class_field list;
+ cstr_type: Types.class_signature;
+ cstr_meths: Ident.t Meths.t;
+ }
+
+and class_field =
+ {
+ cf_desc: class_field_desc;
+ cf_loc: Location.t;
+ cf_attributes: attribute list;
+ }
+
+and class_field_kind =
+ | Tcfk_virtual of core_type
+ | Tcfk_concrete of override_flag * expression
+
+and class_field_desc =
+ Tcf_inherit of
+ override_flag * class_expr * string option * (string * Ident.t) list *
+ (string * Ident.t) list
+ (* Inherited instance variables and concrete methods *)
+ | Tcf_val of string loc * mutable_flag * Ident.t * class_field_kind * bool
+ | Tcf_method of string loc * private_flag * class_field_kind
+ | Tcf_constraint of core_type * core_type
+ | Tcf_initializer of expression
+ | Tcf_attribute of attribute
+
+(* Value expressions for the module language *)
+
+and module_expr =
+ { mod_desc: module_expr_desc;
+ mod_loc: Location.t;
+ mod_type: Types.module_type;
+ mod_env: Env.t;
+ mod_attributes: attribute list;
+ }
+
+and module_type_constraint =
+ Tmodtype_implicit
+| Tmodtype_explicit of module_type
+
+and module_expr_desc =
+ Tmod_ident of Path.t * Longident.t loc
+ | Tmod_structure of structure
+ | Tmod_functor of Ident.t * string loc * module_type option * module_expr
+ | Tmod_apply of module_expr * module_expr * module_coercion
+ | Tmod_constraint of
+ module_expr * Types.module_type * module_type_constraint * module_coercion
+ | Tmod_unpack of expression * Types.module_type
+
+and structure = {
+ str_items : structure_item list;
+ str_type : Types.signature;
+ str_final_env : Env.t;
+}
+
+and structure_item =
+ { str_desc : structure_item_desc;
+ str_loc : Location.t;
+ str_env : Env.t
+ }
+
+and structure_item_desc =
+ Tstr_eval of expression * attributes
+ | Tstr_value of rec_flag * value_binding list
+ | Tstr_primitive of value_description
+ | Tstr_type of rec_flag * type_declaration list
+ | Tstr_typext of type_extension
+ | Tstr_exception of extension_constructor
+ | Tstr_module of module_binding
+ | Tstr_recmodule of module_binding list
+ | Tstr_modtype of module_type_declaration
+ | Tstr_open of open_description
+ | Tstr_class of (class_declaration * string list) list
+ | Tstr_class_type of (Ident.t * string loc * class_type_declaration) list
+ | Tstr_include of include_declaration
+ | Tstr_attribute of attribute
+
+and module_binding =
+ {
+ mb_id: Ident.t;
+ mb_name: string loc;
+ mb_expr: module_expr;
+ mb_attributes: attribute list;
+ mb_loc: Location.t;
+ }
+
+and value_binding =
+ {
+ vb_pat: pattern;
+ vb_expr: expression;
+ vb_attributes: attributes;
+ vb_loc: Location.t;
+ }
+
+and module_coercion =
+ Tcoerce_none
+ | Tcoerce_structure of (int * module_coercion) list *
+ (Ident.t * int * module_coercion) list
+ | Tcoerce_functor of module_coercion * module_coercion
+ | Tcoerce_primitive of primitive_coercion
+ | Tcoerce_alias of Path.t * module_coercion
+
+and module_type =
+ { mty_desc: module_type_desc;
+ mty_type : Types.module_type;
+ mty_env : Env.t;
+ mty_loc: Location.t;
+ mty_attributes: attribute list;
+ }
+
+and module_type_desc =
+ Tmty_ident of Path.t * Longident.t loc
+ | Tmty_signature of signature
+ | Tmty_functor of Ident.t * string loc * module_type option * module_type
+ | Tmty_with of module_type * (Path.t * Longident.t loc * with_constraint) list
+ | Tmty_typeof of module_expr
+ | Tmty_alias of Path.t * Longident.t loc
+
+(* Keep primitive type information for type-based lambda-code specialization *)
+and primitive_coercion =
+ {
+ pc_desc: Primitive.description;
+ pc_type: type_expr;
+ pc_env: Env.t;
+ pc_loc : Location.t;
+ }
+
+and signature = {
+ sig_items : signature_item list;
+ sig_type : Types.signature;
+ sig_final_env : Env.t;
+}
+
+and signature_item =
+ { sig_desc: signature_item_desc;
+ sig_env : Env.t; (* BINANNOT ADDED *)
+ sig_loc: Location.t }
+
+and signature_item_desc =
+ Tsig_value of value_description
+ | Tsig_type of rec_flag * type_declaration list
+ | Tsig_typext of type_extension
+ | Tsig_exception of extension_constructor
+ | Tsig_module of module_declaration
+ | Tsig_recmodule of module_declaration list
+ | Tsig_modtype of module_type_declaration
+ | Tsig_open of open_description
+ | Tsig_include of include_description
+ | Tsig_class of class_description list
+ | Tsig_class_type of class_type_declaration list
+ | Tsig_attribute of attribute
+
+and module_declaration =
+ {
+ md_id: Ident.t;
+ md_name: string loc;
+ md_type: module_type;
+ md_attributes: attribute list;
+ md_loc: Location.t;
+ }
+
+and module_type_declaration =
+ {
+ mtd_id: Ident.t;
+ mtd_name: string loc;
+ mtd_type: module_type option;
+ mtd_attributes: attribute list;
+ mtd_loc: Location.t;
+ }
+
+and open_description =
+ {
+ open_path: Path.t;
+ open_txt: Longident.t loc;
+ open_override: override_flag;
+ open_loc: Location.t;
+ open_attributes: attribute list;
+ }
+
+and 'a include_infos =
+ {
+ incl_mod: 'a;
+ incl_type: Types.signature;
+ incl_loc: Location.t;
+ incl_attributes: attribute list;
+ }
+
+and include_description = module_type include_infos
+
+and include_declaration = module_expr include_infos
+
+and with_constraint =
+ Twith_type of type_declaration
+ | Twith_module of Path.t * Longident.t loc
+ | Twith_typesubst of type_declaration
+ | Twith_modsubst of Path.t * Longident.t loc
+
+and core_type =
+(* mutable because of [Typeclass.declare_method] *)
+ { mutable ctyp_desc : core_type_desc;
+ mutable ctyp_type : type_expr;
+ ctyp_env : Env.t; (* BINANNOT ADDED *)
+ ctyp_loc : Location.t;
+ ctyp_attributes: attribute list;
+ }
+
+and core_type_desc =
+ Ttyp_any
+ | Ttyp_var of string
+ | Ttyp_arrow of arg_label * core_type * core_type
+ | Ttyp_tuple of core_type list
+ | Ttyp_constr of Path.t * Longident.t loc * core_type list
+ | Ttyp_object of (string * attributes * core_type) list * closed_flag
+ | Ttyp_class of Path.t * Longident.t loc * core_type list
+ | Ttyp_alias of core_type * string
+ | Ttyp_variant of row_field list * closed_flag * label list option
+ | Ttyp_poly of string list * core_type
+ | Ttyp_package of package_type
+
+and package_type = {
+ pack_path : Path.t;
+ pack_fields : (Longident.t loc * core_type) list;
+ pack_type : Types.module_type;
+ pack_txt : Longident.t loc;
+}
+
+and row_field =
+ Ttag of label * attributes * bool * core_type list
+ | Tinherit of core_type
+
+and value_description =
+ { val_id: Ident.t;
+ val_name: string loc;
+ val_desc: core_type;
+ val_val: Types.value_description;
+ val_prim: string list;
+ val_loc: Location.t;
+ val_attributes: attribute list;
+ }
+
+and type_declaration =
+ { typ_id: Ident.t;
+ typ_name: string loc;
+ typ_params: (core_type * variance) list;
+ typ_type: Types.type_declaration;
+ typ_cstrs: (core_type * core_type * Location.t) list;
+ typ_kind: type_kind;
+ typ_private: private_flag;
+ typ_manifest: core_type option;
+ typ_loc: Location.t;
+ typ_attributes: attribute list;
+ }
+
+and type_kind =
+ Ttype_abstract
+ | Ttype_variant of constructor_declaration list
+ | Ttype_record of label_declaration list
+ | Ttype_open
+
+and label_declaration =
+ {
+ ld_id: Ident.t;
+ ld_name: string loc;
+ ld_mutable: mutable_flag;
+ ld_type: core_type;
+ ld_loc: Location.t;
+ ld_attributes: attribute list;
+ }
+
+and constructor_declaration =
+ {
+ cd_id: Ident.t;
+ cd_name: string loc;
+ cd_args: constructor_arguments;
+ cd_res: core_type option;
+ cd_loc: Location.t;
+ cd_attributes: attribute list;
+ }
+
+and constructor_arguments =
+ | Cstr_tuple of core_type list
+ | Cstr_record of label_declaration list
+
+and type_extension =
+ {
+ tyext_path: Path.t;
+ tyext_txt: Longident.t loc;
+ tyext_params: (core_type * variance) list;
+ tyext_constructors: extension_constructor list;
+ tyext_private: private_flag;
+ tyext_attributes: attribute list;
+ }
+
+and extension_constructor =
+ {
+ ext_id: Ident.t;
+ ext_name: string loc;
+ ext_type: Types.extension_constructor;
+ ext_kind: extension_constructor_kind;
+ ext_loc: Location.t;
+ ext_attributes: attribute list;
+ }
+
+and extension_constructor_kind =
+ Text_decl of constructor_arguments * core_type option
+ | Text_rebind of Path.t * Longident.t loc
+
+and class_type =
+ {
+ cltyp_desc: class_type_desc;
+ cltyp_type: Types.class_type;
+ cltyp_env: Env.t;
+ cltyp_loc: Location.t;
+ cltyp_attributes: attribute list;
+ }
+
+and class_type_desc =
+ Tcty_constr of Path.t * Longident.t loc * core_type list
+ | Tcty_signature of class_signature
+ | Tcty_arrow of arg_label * core_type * class_type
+
+and class_signature = {
+ csig_self: core_type;
+ csig_fields: class_type_field list;
+ csig_type: Types.class_signature;
+ }
+
+and class_type_field = {
+ ctf_desc: class_type_field_desc;
+ ctf_loc: Location.t;
+ ctf_attributes: attribute list;
+ }
+
+and class_type_field_desc =
+ | Tctf_inherit of class_type
+ | Tctf_val of (string * mutable_flag * virtual_flag * core_type)
+ | Tctf_method of (string * private_flag * virtual_flag * core_type)
+ | Tctf_constraint of (core_type * core_type)
+ | Tctf_attribute of attribute
+
+and class_declaration =
+ class_expr class_infos
+
+and class_description =
+ class_type class_infos
+
+and class_type_declaration =
+ class_type class_infos
+
+and 'a class_infos =
+ { ci_virt: virtual_flag;
+ ci_params: (core_type * variance) list;
+ ci_id_name: string loc;
+ ci_id_class: Ident.t;
+ ci_id_class_type: Ident.t;
+ ci_id_object: Ident.t;
+ ci_id_typesharp: Ident.t;
+ ci_expr: 'a;
+ ci_decl: Types.class_declaration;
+ ci_type_decl: Types.class_type_declaration;
+ ci_loc: Location.t;
+ ci_attributes: attribute list;
+ }
+
+(* Auxiliary functions over the a.s.t. *)
+
+let iter_pattern_desc f = function
+ | Tpat_alias(p, _, _) -> f p
+ | Tpat_tuple patl -> List.iter f patl
+ | Tpat_construct(_, cstr, patl) -> List.iter f patl
+ | Tpat_variant(_, pat, _) -> may f pat
+ | Tpat_record (lbl_pat_list, _) ->
+ List.iter (fun (_, lbl, pat) -> f pat) lbl_pat_list
+ | Tpat_array patl -> List.iter f patl
+ | Tpat_or(p1, p2, _) -> f p1; f p2
+ | Tpat_lazy p -> f p
+ | Tpat_any
+ | Tpat_var _
+ | Tpat_constant _ -> ()
+
+let map_pattern_desc f d =
+ match d with
+ | Tpat_alias (p1, id, s) ->
+ Tpat_alias (f p1, id, s)
+ | Tpat_tuple pats ->
+ Tpat_tuple (List.map f pats)
+ | Tpat_record (lpats, closed) ->
+ Tpat_record (List.map (fun (lid, l,p) -> lid, l, f p) lpats, closed)
+ | Tpat_construct (lid, c,pats) ->
+ Tpat_construct (lid, c, List.map f pats)
+ | Tpat_array pats ->
+ Tpat_array (List.map f pats)
+ | Tpat_lazy p1 -> Tpat_lazy (f p1)
+ | Tpat_variant (x1, Some p1, x2) ->
+ Tpat_variant (x1, Some (f p1), x2)
+ | Tpat_or (p1,p2,path) ->
+ Tpat_or (f p1, f p2, path)
+ | Tpat_var _
+ | Tpat_constant _
+ | Tpat_any
+ | Tpat_variant (_,None,_) -> d
+
+(* List the identifiers bound by a pattern or a let *)
+
+let idents = ref([]: (Ident.t * string loc) list)
+
+let rec bound_idents pat =
+ match pat.pat_desc with
+ | Tpat_var (id,s) -> idents := (id,s) :: !idents
+ | Tpat_alias(p, id, s ) ->
+ bound_idents p; idents := (id,s) :: !idents
+ | Tpat_or(p1, _, _) ->
+ (* Invariant : both arguments binds the same variables *)
+ bound_idents p1
+ | d -> iter_pattern_desc bound_idents d
+
+let pat_bound_idents pat =
+ idents := []; bound_idents pat; let res = !idents in idents := []; res
+
+let rev_let_bound_idents_with_loc bindings =
+ idents := [];
+ List.iter (fun vb -> bound_idents vb.vb_pat) bindings;
+ let res = !idents in idents := []; res
+
+let let_bound_idents_with_loc pat_expr_list =
+ List.rev(rev_let_bound_idents_with_loc pat_expr_list)
+
+let rev_let_bound_idents pat = List.map fst (rev_let_bound_idents_with_loc pat)
+let let_bound_idents pat = List.map fst (let_bound_idents_with_loc pat)
+
+let alpha_var env id = List.assoc id env
+
+let rec alpha_pat env p = match p.pat_desc with
+| Tpat_var (id, s) -> (* note the ``Not_found'' case *)
+ {p with pat_desc =
+ try Tpat_var (alpha_var env id, s) with
+ | Not_found -> Tpat_any}
+| Tpat_alias (p1, id, s) ->
+ let new_p = alpha_pat env p1 in
+ begin try
+ {p with pat_desc = Tpat_alias (new_p, alpha_var env id, s)}
+ with
+ | Not_found -> new_p
+ end
+| d ->
+ {p with pat_desc = map_pattern_desc (alpha_pat env) d}
+
+let mkloc = Location.mkloc
+let mknoloc = Location.mknoloc
diff --git a/typing/typedtree.mli b/typing/typedtree.mli
new file mode 100644
index 0000000000..1526282d2b
--- /dev/null
+++ b/typing/typedtree.mli
@@ -0,0 +1,528 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Abstract syntax tree after typing *)
+
+open Asttypes
+open Types
+
+(* Value expressions for the core language *)
+
+type partial = Partial | Total
+type optional = Required | Optional
+
+type attribute = Parsetree.attribute
+type attributes = attribute list
+
+type pattern =
+ { pat_desc: pattern_desc;
+ pat_loc: Location.t;
+ pat_extra : (pat_extra * Location.t * attributes) list;
+ pat_type: type_expr;
+ mutable pat_env: Env.t;
+ pat_attributes: attributes;
+ }
+
+and pat_extra =
+ | Tpat_constraint of core_type
+ | Tpat_type of Path.t * Longident.t loc
+ | Tpat_unpack
+
+and pattern_desc =
+ Tpat_any
+ | Tpat_var of Ident.t * string loc
+ | Tpat_alias of pattern * Ident.t * string loc
+ | Tpat_constant of constant
+ | Tpat_tuple of pattern list
+ | Tpat_construct of
+ Longident.t loc * constructor_description * pattern list
+ | Tpat_variant of label * pattern option * row_desc ref
+ | Tpat_record of
+ (Longident.t loc * label_description * pattern) list *
+ closed_flag
+ | Tpat_array of pattern list
+ | Tpat_or of pattern * pattern * row_desc option
+ | Tpat_lazy of pattern
+
+and expression =
+ { exp_desc: expression_desc;
+ exp_loc: Location.t;
+ exp_extra: (exp_extra * Location.t * attributes) list;
+ exp_type: type_expr;
+ exp_env: Env.t;
+ exp_attributes: attributes;
+ }
+
+and exp_extra =
+ | Texp_constraint of core_type
+ | Texp_coerce of core_type option * core_type
+ | Texp_open of override_flag * Path.t * Longident.t loc * Env.t
+ | Texp_poly of core_type option
+ | Texp_newtype of string
+
+and expression_desc =
+ Texp_ident of Path.t * Longident.t loc * Types.value_description
+ | Texp_constant of constant
+ | Texp_let of rec_flag * value_binding list * expression
+ | Texp_function of arg_label * case list * partial
+ | Texp_apply of expression * (arg_label * expression option * optional) list
+ | Texp_match of expression * case list * case list * partial
+ | Texp_try of expression * case list
+ | Texp_tuple of expression list
+ | Texp_construct of
+ Longident.t loc * constructor_description * expression list
+ | Texp_variant of label * expression option
+ | Texp_record of
+ (Longident.t loc * label_description * expression) list *
+ expression option
+ | Texp_field of expression * Longident.t loc * label_description
+ | Texp_setfield of
+ expression * Longident.t loc * label_description * expression
+ | Texp_array of expression list
+ | Texp_ifthenelse of expression * expression * expression option
+ | Texp_sequence of expression * expression
+ | Texp_while of expression * expression
+ | Texp_for of
+ Ident.t * Parsetree.pattern * expression * expression * direction_flag *
+ expression
+ | Texp_send of expression * meth * expression option
+ | Texp_new of Path.t * Longident.t loc * Types.class_declaration
+ | Texp_instvar of Path.t * Path.t * string loc
+ | Texp_setinstvar of Path.t * Path.t * string loc * expression
+ | Texp_override of Path.t * (Path.t * string loc * expression) list
+ | Texp_letmodule of Ident.t * string loc * module_expr * expression
+ | Texp_assert of expression
+ | Texp_lazy of expression
+ | Texp_object of class_structure * string list
+ | Texp_pack of module_expr
+
+and meth =
+ Tmeth_name of string
+ | Tmeth_val of Ident.t
+
+and case =
+ {
+ c_lhs: pattern;
+ c_guard: expression option;
+ c_rhs: expression;
+ }
+
+(* Value expressions for the class language *)
+
+and class_expr =
+ {
+ cl_desc: class_expr_desc;
+ cl_loc: Location.t;
+ cl_type: Types.class_type;
+ cl_env: Env.t;
+ cl_attributes: attributes;
+ }
+
+and class_expr_desc =
+ Tcl_ident of Path.t * Longident.t loc * core_type list
+ | Tcl_structure of class_structure
+ | Tcl_fun of
+ arg_label * pattern * (Ident.t * string loc * expression) list
+ * class_expr * partial
+ | Tcl_apply of class_expr * (arg_label * expression option * optional) list
+ | Tcl_let of rec_flag * value_binding list *
+ (Ident.t * string loc * expression) list * class_expr
+ | Tcl_constraint of
+ class_expr * class_type option * string list * string list * Concr.t
+ (* Visible instance variables, methods and concretes methods *)
+
+and class_structure =
+ {
+ cstr_self: pattern;
+ cstr_fields: class_field list;
+ cstr_type: Types.class_signature;
+ cstr_meths: Ident.t Meths.t;
+ }
+
+and class_field =
+ {
+ cf_desc: class_field_desc;
+ cf_loc: Location.t;
+ cf_attributes: attributes;
+ }
+
+and class_field_kind =
+ | Tcfk_virtual of core_type
+ | Tcfk_concrete of override_flag * expression
+
+and class_field_desc =
+ Tcf_inherit of
+ override_flag * class_expr * string option * (string * Ident.t) list *
+ (string * Ident.t) list
+ (* Inherited instance variables and concrete methods *)
+ | Tcf_val of string loc * mutable_flag * Ident.t * class_field_kind * bool
+ | Tcf_method of string loc * private_flag * class_field_kind
+ | Tcf_constraint of core_type * core_type
+ | Tcf_initializer of expression
+ | Tcf_attribute of attribute
+
+(* Value expressions for the module language *)
+
+and module_expr =
+ { mod_desc: module_expr_desc;
+ mod_loc: Location.t;
+ mod_type: Types.module_type;
+ mod_env: Env.t;
+ mod_attributes: attributes;
+ }
+
+and module_type_constraint =
+ Tmodtype_implicit
+ | Tmodtype_explicit of module_type
+
+and module_expr_desc =
+ Tmod_ident of Path.t * Longident.t loc
+ | Tmod_structure of structure
+ | Tmod_functor of Ident.t * string loc * module_type option * module_expr
+ | Tmod_apply of module_expr * module_expr * module_coercion
+ | Tmod_constraint of
+ module_expr * Types.module_type * module_type_constraint * module_coercion
+ | Tmod_unpack of expression * Types.module_type
+
+and structure = {
+ str_items : structure_item list;
+ str_type : Types.signature;
+ str_final_env : Env.t;
+}
+
+and structure_item =
+ { str_desc : structure_item_desc;
+ str_loc : Location.t;
+ str_env : Env.t
+ }
+
+and structure_item_desc =
+ Tstr_eval of expression * attributes
+ | Tstr_value of rec_flag * value_binding list
+ | Tstr_primitive of value_description
+ | Tstr_type of rec_flag * type_declaration list
+ | Tstr_typext of type_extension
+ | Tstr_exception of extension_constructor
+ | Tstr_module of module_binding
+ | Tstr_recmodule of module_binding list
+ | Tstr_modtype of module_type_declaration
+ | Tstr_open of open_description
+ | Tstr_class of (class_declaration * string list) list
+ | Tstr_class_type of (Ident.t * string loc * class_type_declaration) list
+ | Tstr_include of include_declaration
+ | Tstr_attribute of attribute
+
+and module_binding =
+ {
+ mb_id: Ident.t;
+ mb_name: string loc;
+ mb_expr: module_expr;
+ mb_attributes: attributes;
+ mb_loc: Location.t;
+ }
+
+and value_binding =
+ {
+ vb_pat: pattern;
+ vb_expr: expression;
+ vb_attributes: attributes;
+ vb_loc: Location.t;
+ }
+
+and module_coercion =
+ Tcoerce_none
+ | Tcoerce_structure of (int * module_coercion) list *
+ (Ident.t * int * module_coercion) list
+ | Tcoerce_functor of module_coercion * module_coercion
+ | Tcoerce_primitive of primitive_coercion
+ | Tcoerce_alias of Path.t * module_coercion
+
+and module_type =
+ { mty_desc: module_type_desc;
+ mty_type : Types.module_type;
+ mty_env : Env.t;
+ mty_loc: Location.t;
+ mty_attributes: attributes;
+ }
+
+and module_type_desc =
+ Tmty_ident of Path.t * Longident.t loc
+ | Tmty_signature of signature
+ | Tmty_functor of Ident.t * string loc * module_type option * module_type
+ | Tmty_with of module_type * (Path.t * Longident.t loc * with_constraint) list
+ | Tmty_typeof of module_expr
+ | Tmty_alias of Path.t * Longident.t loc
+
+and primitive_coercion =
+ {
+ pc_desc: Primitive.description;
+ pc_type: type_expr;
+ pc_env: Env.t;
+ pc_loc : Location.t;
+ }
+
+and signature = {
+ sig_items : signature_item list;
+ sig_type : Types.signature;
+ sig_final_env : Env.t;
+}
+
+and signature_item =
+ { sig_desc: signature_item_desc;
+ sig_env : Env.t; (* BINANNOT ADDED *)
+ sig_loc: Location.t }
+
+and signature_item_desc =
+ Tsig_value of value_description
+ | Tsig_type of rec_flag * type_declaration list
+ | Tsig_typext of type_extension
+ | Tsig_exception of extension_constructor
+ | Tsig_module of module_declaration
+ | Tsig_recmodule of module_declaration list
+ | Tsig_modtype of module_type_declaration
+ | Tsig_open of open_description
+ | Tsig_include of include_description
+ | Tsig_class of class_description list
+ | Tsig_class_type of class_type_declaration list
+ | Tsig_attribute of attribute
+
+and module_declaration =
+ {
+ md_id: Ident.t;
+ md_name: string loc;
+ md_type: module_type;
+ md_attributes: attributes;
+ md_loc: Location.t;
+ }
+
+and module_type_declaration =
+ {
+ mtd_id: Ident.t;
+ mtd_name: string loc;
+ mtd_type: module_type option;
+ mtd_attributes: attributes;
+ mtd_loc: Location.t;
+ }
+
+and open_description =
+ {
+ open_path: Path.t;
+ open_txt: Longident.t loc;
+ open_override: override_flag;
+ open_loc: Location.t;
+ open_attributes: attribute list;
+ }
+
+and 'a include_infos =
+ {
+ incl_mod: 'a;
+ incl_type: Types.signature;
+ incl_loc: Location.t;
+ incl_attributes: attribute list;
+ }
+
+and include_description = module_type include_infos
+
+and include_declaration = module_expr include_infos
+
+and with_constraint =
+ Twith_type of type_declaration
+ | Twith_module of Path.t * Longident.t loc
+ | Twith_typesubst of type_declaration
+ | Twith_modsubst of Path.t * Longident.t loc
+
+and core_type =
+(* mutable because of [Typeclass.declare_method] *)
+ { mutable ctyp_desc : core_type_desc;
+ mutable ctyp_type : type_expr;
+ ctyp_env : Env.t; (* BINANNOT ADDED *)
+ ctyp_loc : Location.t;
+ ctyp_attributes: attributes;
+ }
+
+and core_type_desc =
+ Ttyp_any
+ | Ttyp_var of string
+ | Ttyp_arrow of arg_label * core_type * core_type
+ | Ttyp_tuple of core_type list
+ | Ttyp_constr of Path.t * Longident.t loc * core_type list
+ | Ttyp_object of (string * attributes * core_type) list * closed_flag
+ | Ttyp_class of Path.t * Longident.t loc * core_type list
+ | Ttyp_alias of core_type * string
+ | Ttyp_variant of row_field list * closed_flag * label list option
+ | Ttyp_poly of string list * core_type
+ | Ttyp_package of package_type
+
+and package_type = {
+ pack_path : Path.t;
+ pack_fields : (Longident.t loc * core_type) list;
+ pack_type : Types.module_type;
+ pack_txt : Longident.t loc;
+}
+
+and row_field =
+ Ttag of label * attributes * bool * core_type list
+ | Tinherit of core_type
+
+and value_description =
+ { val_id: Ident.t;
+ val_name: string loc;
+ val_desc: core_type;
+ val_val: Types.value_description;
+ val_prim: string list;
+ val_loc: Location.t;
+ val_attributes: attributes;
+ }
+
+and type_declaration =
+ {
+ typ_id: Ident.t;
+ typ_name: string loc;
+ typ_params: (core_type * variance) list;
+ typ_type: Types.type_declaration;
+ typ_cstrs: (core_type * core_type * Location.t) list;
+ typ_kind: type_kind;
+ typ_private: private_flag;
+ typ_manifest: core_type option;
+ typ_loc: Location.t;
+ typ_attributes: attributes;
+ }
+
+and type_kind =
+ Ttype_abstract
+ | Ttype_variant of constructor_declaration list
+ | Ttype_record of label_declaration list
+ | Ttype_open
+
+and label_declaration =
+ {
+ ld_id: Ident.t;
+ ld_name: string loc;
+ ld_mutable: mutable_flag;
+ ld_type: core_type;
+ ld_loc: Location.t;
+ ld_attributes: attributes;
+ }
+
+and constructor_declaration =
+ {
+ cd_id: Ident.t;
+ cd_name: string loc;
+ cd_args: constructor_arguments;
+ cd_res: core_type option;
+ cd_loc: Location.t;
+ cd_attributes: attributes;
+ }
+
+and constructor_arguments =
+ | Cstr_tuple of core_type list
+ | Cstr_record of label_declaration list
+
+and type_extension =
+ {
+ tyext_path: Path.t;
+ tyext_txt: Longident.t loc;
+ tyext_params: (core_type * variance) list;
+ tyext_constructors: extension_constructor list;
+ tyext_private: private_flag;
+ tyext_attributes: attributes;
+ }
+
+and extension_constructor =
+ {
+ ext_id: Ident.t;
+ ext_name: string loc;
+ ext_type : Types.extension_constructor;
+ ext_kind : extension_constructor_kind;
+ ext_loc : Location.t;
+ ext_attributes: attributes;
+ }
+
+and extension_constructor_kind =
+ Text_decl of constructor_arguments * core_type option
+ | Text_rebind of Path.t * Longident.t loc
+
+and class_type =
+ {
+ cltyp_desc: class_type_desc;
+ cltyp_type: Types.class_type;
+ cltyp_env: Env.t;
+ cltyp_loc: Location.t;
+ cltyp_attributes: attributes;
+ }
+
+and class_type_desc =
+ Tcty_constr of Path.t * Longident.t loc * core_type list
+ | Tcty_signature of class_signature
+ | Tcty_arrow of arg_label * core_type * class_type
+
+and class_signature = {
+ csig_self : core_type;
+ csig_fields : class_type_field list;
+ csig_type : Types.class_signature;
+ }
+
+and class_type_field = {
+ ctf_desc: class_type_field_desc;
+ ctf_loc: Location.t;
+ ctf_attributes: attributes;
+ }
+
+and class_type_field_desc =
+ | Tctf_inherit of class_type
+ | Tctf_val of (string * mutable_flag * virtual_flag * core_type)
+ | Tctf_method of (string * private_flag * virtual_flag * core_type)
+ | Tctf_constraint of (core_type * core_type)
+ | Tctf_attribute of attribute
+
+and class_declaration =
+ class_expr class_infos
+
+and class_description =
+ class_type class_infos
+
+and class_type_declaration =
+ class_type class_infos
+
+and 'a class_infos =
+ { ci_virt: virtual_flag;
+ ci_params: (core_type * variance) list;
+ ci_id_name : string loc;
+ ci_id_class: Ident.t;
+ ci_id_class_type : Ident.t;
+ ci_id_object : Ident.t;
+ ci_id_typesharp : Ident.t;
+ ci_expr: 'a;
+ ci_decl: Types.class_declaration;
+ ci_type_decl : Types.class_type_declaration;
+ ci_loc: Location.t;
+ ci_attributes: attributes;
+ }
+
+(* Auxiliary functions over the a.s.t. *)
+
+val iter_pattern_desc: (pattern -> unit) -> pattern_desc -> unit
+val map_pattern_desc: (pattern -> pattern) -> pattern_desc -> pattern_desc
+
+val let_bound_idents: value_binding list -> Ident.t list
+val rev_let_bound_idents: value_binding list -> Ident.t list
+
+val let_bound_idents_with_loc:
+ value_binding list -> (Ident.t * string loc) list
+
+(* Alpha conversion of patterns *)
+val alpha_pat: (Ident.t * Ident.t) list -> pattern -> pattern
+
+val mknoloc: 'a -> 'a Asttypes.loc
+val mkloc: 'a -> Location.t -> 'a Asttypes.loc
+
+val pat_bound_idents: pattern -> (Ident.t * string Asttypes.loc) list
diff --git a/typing/typedtreeIter.ml b/typing/typedtreeIter.ml
new file mode 100644
index 0000000000..8de50d711b
--- /dev/null
+++ b/typing/typedtreeIter.ml
@@ -0,0 +1,667 @@
+(**************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Thomas Gazagnaire (OCamlPro), Fabrice Le Fessant (INRIA Saclay) *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(**************************************************************************)
+
+(*
+TODO:
+ - 2012/05/10: Follow camlp4 way of building map and iter using classes
+ and inheritance ?
+*)
+
+open Asttypes
+open Typedtree
+
+module type IteratorArgument = sig
+
+ val enter_structure : structure -> unit
+ val enter_value_description : value_description -> unit
+ val enter_type_extension : type_extension -> unit
+ val enter_extension_constructor : extension_constructor -> unit
+ val enter_pattern : pattern -> unit
+ val enter_expression : expression -> unit
+ val enter_package_type : package_type -> unit
+ val enter_signature : signature -> unit
+ val enter_signature_item : signature_item -> unit
+ val enter_module_type_declaration : module_type_declaration -> unit
+ val enter_module_type : module_type -> unit
+ val enter_module_expr : module_expr -> unit
+ val enter_with_constraint : with_constraint -> unit
+ val enter_class_expr : class_expr -> unit
+ val enter_class_signature : class_signature -> unit
+ val enter_class_declaration : class_declaration -> unit
+ val enter_class_description : class_description -> unit
+ val enter_class_type_declaration : class_type_declaration -> unit
+ val enter_class_type : class_type -> unit
+ val enter_class_type_field : class_type_field -> unit
+ val enter_core_type : core_type -> unit
+ val enter_class_structure : class_structure -> unit
+ val enter_class_field : class_field -> unit
+ val enter_structure_item : structure_item -> unit
+
+
+ val leave_structure : structure -> unit
+ val leave_value_description : value_description -> unit
+ val leave_type_extension : type_extension -> unit
+ val leave_extension_constructor : extension_constructor -> unit
+ val leave_pattern : pattern -> unit
+ val leave_expression : expression -> unit
+ val leave_package_type : package_type -> unit
+ val leave_signature : signature -> unit
+ val leave_signature_item : signature_item -> unit
+ val leave_module_type_declaration : module_type_declaration -> unit
+ val leave_module_type : module_type -> unit
+ val leave_module_expr : module_expr -> unit
+ val leave_with_constraint : with_constraint -> unit
+ val leave_class_expr : class_expr -> unit
+ val leave_class_signature : class_signature -> unit
+ val leave_class_declaration : class_declaration -> unit
+ val leave_class_description : class_description -> unit
+ val leave_class_type_declaration : class_type_declaration -> unit
+ val leave_class_type : class_type -> unit
+ val leave_class_type_field : class_type_field -> unit
+ val leave_core_type : core_type -> unit
+ val leave_class_structure : class_structure -> unit
+ val leave_class_field : class_field -> unit
+ val leave_structure_item : structure_item -> unit
+
+ val enter_bindings : rec_flag -> unit
+ val enter_binding : value_binding -> unit
+ val leave_binding : value_binding -> unit
+ val leave_bindings : rec_flag -> unit
+
+ val enter_type_declarations : rec_flag -> unit
+ val enter_type_declaration : type_declaration -> unit
+ val leave_type_declaration : type_declaration -> unit
+ val leave_type_declarations : rec_flag -> unit
+
+ end
+
+module MakeIterator(Iter : IteratorArgument) : sig
+
+ val iter_structure : structure -> unit
+ val iter_signature : signature -> unit
+ val iter_structure_item : structure_item -> unit
+ val iter_signature_item : signature_item -> unit
+ val iter_expression : expression -> unit
+ val iter_module_type : module_type -> unit
+ val iter_pattern : pattern -> unit
+ val iter_class_expr : class_expr -> unit
+
+ end = struct
+
+ let may_iter f v =
+ match v with
+ None -> ()
+ | Some x -> f x
+
+
+ let rec iter_structure str =
+ Iter.enter_structure str;
+ List.iter iter_structure_item str.str_items;
+ Iter.leave_structure str
+
+
+ and iter_binding vb =
+ Iter.enter_binding vb;
+ iter_pattern vb.vb_pat;
+ iter_expression vb.vb_expr;
+ Iter.leave_binding vb
+
+ and iter_bindings rec_flag list =
+ Iter.enter_bindings rec_flag;
+ List.iter iter_binding list;
+ Iter.leave_bindings rec_flag
+
+ and iter_case {c_lhs; c_guard; c_rhs} =
+ iter_pattern c_lhs;
+ may_iter iter_expression c_guard;
+ iter_expression c_rhs
+
+ and iter_cases cases =
+ List.iter iter_case cases
+
+ and iter_structure_item item =
+ Iter.enter_structure_item item;
+ begin
+ match item.str_desc with
+ Tstr_eval (exp, _attrs) -> iter_expression exp
+ | Tstr_value (rec_flag, list) ->
+ iter_bindings rec_flag list
+ | Tstr_primitive vd -> iter_value_description vd
+ | Tstr_type (rf, list) -> iter_type_declarations rf list
+ | Tstr_typext tyext -> iter_type_extension tyext
+ | Tstr_exception ext -> iter_extension_constructor ext
+ | Tstr_module x -> iter_module_binding x
+ | Tstr_recmodule list -> List.iter iter_module_binding list
+ | Tstr_modtype mtd -> iter_module_type_declaration mtd
+ | Tstr_open _ -> ()
+ | Tstr_class list ->
+ List.iter (fun (ci, _) -> iter_class_declaration ci) list
+ | Tstr_class_type list ->
+ List.iter
+ (fun (id, _, ct) -> iter_class_type_declaration ct)
+ list
+ | Tstr_include incl -> iter_module_expr incl.incl_mod
+ | Tstr_attribute _ ->
+ ()
+ end;
+ Iter.leave_structure_item item
+
+ and iter_module_binding x =
+ iter_module_expr x.mb_expr
+
+ and iter_value_description v =
+ Iter.enter_value_description v;
+ iter_core_type v.val_desc;
+ Iter.leave_value_description v
+
+ and iter_constructor_arguments = function
+ | Cstr_tuple l -> List.iter iter_core_type l
+ | Cstr_record l -> List.iter (fun ld -> iter_core_type ld.ld_type) l
+
+ and iter_constructor_declaration cd =
+ iter_constructor_arguments cd.cd_args;
+ option iter_core_type cd.cd_res;
+
+ and iter_type_parameter (ct, v) =
+ iter_core_type ct
+
+ and iter_type_declaration decl =
+ Iter.enter_type_declaration decl;
+ List.iter iter_type_parameter decl.typ_params;
+ List.iter (fun (ct1, ct2, loc) ->
+ iter_core_type ct1;
+ iter_core_type ct2
+ ) decl.typ_cstrs;
+ begin match decl.typ_kind with
+ Ttype_abstract -> ()
+ | Ttype_variant list ->
+ List.iter iter_constructor_declaration list
+ | Ttype_record list ->
+ List.iter
+ (fun ld ->
+ iter_core_type ld.ld_type
+ ) list
+ | Ttype_open -> ()
+ end;
+ option iter_core_type decl.typ_manifest;
+ Iter.leave_type_declaration decl
+
+ and iter_type_declarations rec_flag decls =
+ Iter.enter_type_declarations rec_flag;
+ List.iter iter_type_declaration decls;
+ Iter.leave_type_declarations rec_flag
+
+ and iter_extension_constructor ext =
+ Iter.enter_extension_constructor ext;
+ begin match ext.ext_kind with
+ Text_decl(args, ret) ->
+ iter_constructor_arguments args;
+ option iter_core_type ret
+ | Text_rebind _ -> ()
+ end;
+ Iter.leave_extension_constructor ext;
+
+ and iter_type_extension tyext =
+ Iter.enter_type_extension tyext;
+ List.iter iter_type_parameter tyext.tyext_params;
+ List.iter iter_extension_constructor tyext.tyext_constructors;
+ Iter.leave_type_extension tyext
+
+ and iter_pattern pat =
+ Iter.enter_pattern pat;
+ List.iter (fun (cstr, _, _attrs) -> match cstr with
+ | Tpat_type _ -> ()
+ | Tpat_unpack -> ()
+ | Tpat_constraint ct -> iter_core_type ct) pat.pat_extra;
+ begin
+ match pat.pat_desc with
+ Tpat_any -> ()
+ | Tpat_var (id, _) -> ()
+ | Tpat_alias (pat1, _, _) -> iter_pattern pat1
+ | Tpat_constant cst -> ()
+ | Tpat_tuple list ->
+ List.iter iter_pattern list
+ | Tpat_construct (_, _, args) ->
+ List.iter iter_pattern args
+ | Tpat_variant (label, pato, _) ->
+ begin match pato with
+ None -> ()
+ | Some pat -> iter_pattern pat
+ end
+ | Tpat_record (list, closed) ->
+ List.iter (fun (_, _, pat) -> iter_pattern pat) list
+ | Tpat_array list -> List.iter iter_pattern list
+ | Tpat_or (p1, p2, _) -> iter_pattern p1; iter_pattern p2
+ | Tpat_lazy p -> iter_pattern p
+ end;
+ Iter.leave_pattern pat
+
+ and option f x = match x with None -> () | Some e -> f e
+
+ and iter_expression exp =
+ Iter.enter_expression exp;
+ List.iter (function (cstr, _, _attrs) ->
+ match cstr with
+ Texp_constraint ct ->
+ iter_core_type ct
+ | Texp_coerce (cty1, cty2) ->
+ option iter_core_type cty1; iter_core_type cty2
+ | Texp_open (_, path, _, _) -> ()
+ | Texp_poly cto -> option iter_core_type cto
+ | Texp_newtype s -> ())
+ exp.exp_extra;
+ begin
+ match exp.exp_desc with
+ Texp_ident (path, _, _) -> ()
+ | Texp_constant cst -> ()
+ | Texp_let (rec_flag, list, exp) ->
+ iter_bindings rec_flag list;
+ iter_expression exp
+ | Texp_function (label, cases, _) ->
+ iter_cases cases
+ | Texp_apply (exp, list) ->
+ iter_expression exp;
+ List.iter (fun (label, expo, _) ->
+ match expo with
+ None -> ()
+ | Some exp -> iter_expression exp
+ ) list
+ | Texp_match (exp, list1, list2, _) ->
+ iter_expression exp;
+ iter_cases list1;
+ iter_cases list2;
+ | Texp_try (exp, list) ->
+ iter_expression exp;
+ iter_cases list
+ | Texp_tuple list ->
+ List.iter iter_expression list
+ | Texp_construct (_, _, args) ->
+ List.iter iter_expression args
+ | Texp_variant (label, expo) ->
+ begin match expo with
+ None -> ()
+ | Some exp -> iter_expression exp
+ end
+ | Texp_record (list, expo) ->
+ List.iter (fun (_, _, exp) -> iter_expression exp) list;
+ begin match expo with
+ None -> ()
+ | Some exp -> iter_expression exp
+ end
+ | Texp_field (exp, _, label) ->
+ iter_expression exp
+ | Texp_setfield (exp1, _, label, exp2) ->
+ iter_expression exp1;
+ iter_expression exp2
+ | Texp_array list ->
+ List.iter iter_expression list
+ | Texp_ifthenelse (exp1, exp2, expo) ->
+ iter_expression exp1;
+ iter_expression exp2;
+ begin match expo with
+ None -> ()
+ | Some exp -> iter_expression exp
+ end
+ | Texp_sequence (exp1, exp2) ->
+ iter_expression exp1;
+ iter_expression exp2
+ | Texp_while (exp1, exp2) ->
+ iter_expression exp1;
+ iter_expression exp2
+ | Texp_for (id, _, exp1, exp2, dir, exp3) ->
+ iter_expression exp1;
+ iter_expression exp2;
+ iter_expression exp3
+ | Texp_send (exp, meth, expo) ->
+ iter_expression exp;
+ begin
+ match expo with
+ None -> ()
+ | Some exp -> iter_expression exp
+ end
+ | Texp_new (path, _, _) -> ()
+ | Texp_instvar (_, path, _) -> ()
+ | Texp_setinstvar (_, _, _, exp) ->
+ iter_expression exp
+ | Texp_override (_, list) ->
+ List.iter (fun (path, _, exp) ->
+ iter_expression exp
+ ) list
+ | Texp_letmodule (id, _, mexpr, exp) ->
+ iter_module_expr mexpr;
+ iter_expression exp
+ | Texp_assert exp -> iter_expression exp
+ | Texp_lazy exp -> iter_expression exp
+ | Texp_object (cl, _) ->
+ iter_class_structure cl
+ | Texp_pack (mexpr) ->
+ iter_module_expr mexpr
+ end;
+ Iter.leave_expression exp;
+
+ and iter_package_type pack =
+ Iter.enter_package_type pack;
+ List.iter (fun (s, ct) -> iter_core_type ct) pack.pack_fields;
+ Iter.leave_package_type pack;
+
+ and iter_signature sg =
+ Iter.enter_signature sg;
+ List.iter iter_signature_item sg.sig_items;
+ Iter.leave_signature sg;
+
+ and iter_signature_item item =
+ Iter.enter_signature_item item;
+ begin
+ match item.sig_desc with
+ Tsig_value vd ->
+ iter_value_description vd
+ | Tsig_type (rf, list) ->
+ iter_type_declarations rf list
+ | Tsig_exception ext ->
+ iter_extension_constructor ext
+ | Tsig_typext tyext ->
+ iter_type_extension tyext
+ | Tsig_module md ->
+ iter_module_type md.md_type
+ | Tsig_recmodule list ->
+ List.iter (fun md -> iter_module_type md.md_type) list
+ | Tsig_modtype mtd ->
+ iter_module_type_declaration mtd
+ | Tsig_open _ -> ()
+ | Tsig_include incl -> iter_module_type incl.incl_mod
+ | Tsig_class list ->
+ List.iter iter_class_description list
+ | Tsig_class_type list ->
+ List.iter iter_class_type_declaration list
+ | Tsig_attribute _ -> ()
+ end;
+ Iter.leave_signature_item item;
+
+ and iter_module_type_declaration mtd =
+ Iter.enter_module_type_declaration mtd;
+ begin
+ match mtd.mtd_type with
+ | None -> ()
+ | Some mtype -> iter_module_type mtype
+ end;
+ Iter.leave_module_type_declaration mtd
+
+ and iter_class_declaration cd =
+ Iter.enter_class_declaration cd;
+ List.iter iter_type_parameter cd.ci_params;
+ iter_class_expr cd.ci_expr;
+ Iter.leave_class_declaration cd;
+
+ and iter_class_description cd =
+ Iter.enter_class_description cd;
+ List.iter iter_type_parameter cd.ci_params;
+ iter_class_type cd.ci_expr;
+ Iter.leave_class_description cd;
+
+ and iter_class_type_declaration cd =
+ Iter.enter_class_type_declaration cd;
+ List.iter iter_type_parameter cd.ci_params;
+ iter_class_type cd.ci_expr;
+ Iter.leave_class_type_declaration cd;
+
+ and iter_module_type mty =
+ Iter.enter_module_type mty;
+ begin
+ match mty.mty_desc with
+ Tmty_ident (path, _) -> ()
+ | Tmty_alias (path, _) -> ()
+ | Tmty_signature sg -> iter_signature sg
+ | Tmty_functor (id, _, mtype1, mtype2) ->
+ Misc.may iter_module_type mtype1; iter_module_type mtype2
+ | Tmty_with (mtype, list) ->
+ iter_module_type mtype;
+ List.iter (fun (path, _, withc) ->
+ iter_with_constraint withc
+ ) list
+ | Tmty_typeof mexpr ->
+ iter_module_expr mexpr
+ end;
+ Iter.leave_module_type mty;
+
+ and iter_with_constraint cstr =
+ Iter.enter_with_constraint cstr;
+ begin
+ match cstr with
+ Twith_type decl -> iter_type_declaration decl
+ | Twith_module _ -> ()
+ | Twith_typesubst decl -> iter_type_declaration decl
+ | Twith_modsubst _ -> ()
+ end;
+ Iter.leave_with_constraint cstr;
+
+ and iter_module_expr mexpr =
+ Iter.enter_module_expr mexpr;
+ begin
+ match mexpr.mod_desc with
+ Tmod_ident (p, _) -> ()
+ | Tmod_structure st -> iter_structure st
+ | Tmod_functor (id, _, mtype, mexpr) ->
+ Misc.may iter_module_type mtype;
+ iter_module_expr mexpr
+ | Tmod_apply (mexp1, mexp2, _) ->
+ iter_module_expr mexp1;
+ iter_module_expr mexp2
+ | Tmod_constraint (mexpr, _, Tmodtype_implicit, _ ) ->
+ iter_module_expr mexpr
+ | Tmod_constraint (mexpr, _, Tmodtype_explicit mtype, _) ->
+ iter_module_expr mexpr;
+ iter_module_type mtype
+ | Tmod_unpack (exp, mty) ->
+ iter_expression exp
+(* iter_module_type mty *)
+ end;
+ Iter.leave_module_expr mexpr;
+
+ and iter_class_expr cexpr =
+ Iter.enter_class_expr cexpr;
+ begin
+ match cexpr.cl_desc with
+ | Tcl_constraint (cl, None, _, _, _ ) ->
+ iter_class_expr cl;
+ | Tcl_structure clstr -> iter_class_structure clstr
+ | Tcl_fun (label, pat, priv, cl, partial) ->
+ iter_pattern pat;
+ List.iter (fun (id, _, exp) -> iter_expression exp) priv;
+ iter_class_expr cl
+
+ | Tcl_apply (cl, args) ->
+ iter_class_expr cl;
+ List.iter (fun (label, expo, _) ->
+ match expo with
+ None -> ()
+ | Some exp -> iter_expression exp
+ ) args
+
+ | Tcl_let (rec_flat, bindings, ivars, cl) ->
+ iter_bindings rec_flat bindings;
+ List.iter (fun (id, _, exp) -> iter_expression exp) ivars;
+ iter_class_expr cl
+
+ | Tcl_constraint (cl, Some clty, vals, meths, concrs) ->
+ iter_class_expr cl;
+ iter_class_type clty
+
+ | Tcl_ident (_, _, tyl) ->
+ List.iter iter_core_type tyl
+ end;
+ Iter.leave_class_expr cexpr;
+
+ and iter_class_type ct =
+ Iter.enter_class_type ct;
+ begin
+ match ct.cltyp_desc with
+ Tcty_signature csg -> iter_class_signature csg
+ | Tcty_constr (path, _, list) ->
+ List.iter iter_core_type list
+ | Tcty_arrow (label, ct, cl) ->
+ iter_core_type ct;
+ iter_class_type cl
+ end;
+ Iter.leave_class_type ct;
+
+ and iter_class_signature cs =
+ Iter.enter_class_signature cs;
+ iter_core_type cs.csig_self;
+ List.iter iter_class_type_field cs.csig_fields;
+ Iter.leave_class_signature cs
+
+
+ and iter_class_type_field ctf =
+ Iter.enter_class_type_field ctf;
+ begin
+ match ctf.ctf_desc with
+ Tctf_inherit ct -> iter_class_type ct
+ | Tctf_val (s, _mut, _virt, ct) ->
+ iter_core_type ct
+ | Tctf_method (s, _priv, _virt, ct) ->
+ iter_core_type ct
+ | Tctf_constraint (ct1, ct2) ->
+ iter_core_type ct1;
+ iter_core_type ct2
+ | Tctf_attribute _ -> ()
+ end;
+ Iter.leave_class_type_field ctf
+
+ and iter_core_type ct =
+ Iter.enter_core_type ct;
+ begin
+ match ct.ctyp_desc with
+ Ttyp_any -> ()
+ | Ttyp_var s -> ()
+ | Ttyp_arrow (label, ct1, ct2) ->
+ iter_core_type ct1;
+ iter_core_type ct2
+ | Ttyp_tuple list -> List.iter iter_core_type list
+ | Ttyp_constr (path, _, list) ->
+ List.iter iter_core_type list
+ | Ttyp_object (list, o) ->
+ List.iter (fun (_, _, t) -> iter_core_type t) list
+ | Ttyp_class (path, _, list) ->
+ List.iter iter_core_type list
+ | Ttyp_alias (ct, s) ->
+ iter_core_type ct
+ | Ttyp_variant (list, bool, labels) ->
+ List.iter iter_row_field list
+ | Ttyp_poly (list, ct) -> iter_core_type ct
+ | Ttyp_package pack -> iter_package_type pack
+ end;
+ Iter.leave_core_type ct
+
+ and iter_class_structure cs =
+ Iter.enter_class_structure cs;
+ iter_pattern cs.cstr_self;
+ List.iter iter_class_field cs.cstr_fields;
+ Iter.leave_class_structure cs;
+
+
+ and iter_row_field rf =
+ match rf with
+ Ttag (label, _attrs, bool, list) ->
+ List.iter iter_core_type list
+ | Tinherit ct -> iter_core_type ct
+
+ and iter_class_field cf =
+ Iter.enter_class_field cf;
+ begin
+ match cf.cf_desc with
+ Tcf_inherit (ovf, cl, super, _vals, _meths) ->
+ iter_class_expr cl
+ | Tcf_constraint (cty, cty') ->
+ iter_core_type cty;
+ iter_core_type cty'
+ | Tcf_val (lab, _, _, Tcfk_virtual cty, _) ->
+ iter_core_type cty
+ | Tcf_val (lab, _, _, Tcfk_concrete (_, exp), _) ->
+ iter_expression exp
+ | Tcf_method (lab, _, Tcfk_virtual cty) ->
+ iter_core_type cty
+ | Tcf_method (lab, _, Tcfk_concrete (_, exp)) ->
+ iter_expression exp
+ | Tcf_initializer exp ->
+ iter_expression exp
+ | Tcf_attribute _ -> ()
+ end;
+ Iter.leave_class_field cf;
+ end
+
+module DefaultIteratorArgument = struct
+
+ let enter_structure _ = ()
+ let enter_value_description _ = ()
+ let enter_type_extension _ = ()
+ let enter_extension_constructor _ = ()
+ let enter_pattern _ = ()
+ let enter_expression _ = ()
+ let enter_package_type _ = ()
+ let enter_signature _ = ()
+ let enter_signature_item _ = ()
+ let enter_module_type_declaration _ = ()
+ let enter_module_type _ = ()
+ let enter_module_expr _ = ()
+ let enter_with_constraint _ = ()
+ let enter_class_expr _ = ()
+ let enter_class_signature _ = ()
+ let enter_class_declaration _ = ()
+ let enter_class_description _ = ()
+ let enter_class_type_declaration _ = ()
+ let enter_class_type _ = ()
+ let enter_class_type_field _ = ()
+ let enter_core_type _ = ()
+ let enter_core_field_type _ = ()
+ let enter_class_structure _ = ()
+ let enter_class_field _ = ()
+ let enter_structure_item _ = ()
+
+
+ let leave_structure _ = ()
+ let leave_value_description _ = ()
+ let leave_type_extension _ = ()
+ let leave_extension_constructor _ = ()
+ let leave_pattern _ = ()
+ let leave_expression _ = ()
+ let leave_package_type _ = ()
+ let leave_signature _ = ()
+ let leave_signature_item _ = ()
+ let leave_module_type_declaration _ = ()
+ let leave_module_type _ = ()
+ let leave_module_expr _ = ()
+ let leave_with_constraint _ = ()
+ let leave_class_expr _ = ()
+ let leave_class_signature _ = ()
+ let leave_class_declaration _ = ()
+ let leave_class_description _ = ()
+ let leave_class_type_declaration _ = ()
+ let leave_class_type _ = ()
+ let leave_class_type_field _ = ()
+ let leave_core_type _ = ()
+ let leave_core_field_type _ = ()
+ let leave_class_structure _ = ()
+ let leave_class_field _ = ()
+ let leave_structure_item _ = ()
+
+ let enter_binding _ = ()
+ let leave_binding _ = ()
+
+ let enter_bindings _ = ()
+ let leave_bindings _ = ()
+
+ let enter_type_declaration _ = ()
+ let leave_type_declaration _ = ()
+
+ let enter_type_declarations _ = ()
+ let leave_type_declarations _ = ()
+end
diff --git a/typing/typedtreeIter.mli b/typing/typedtreeIter.mli
new file mode 100644
index 0000000000..cfb096286e
--- /dev/null
+++ b/typing/typedtreeIter.mli
@@ -0,0 +1,94 @@
+(**************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Thomas Gazagnaire (OCamlPro), Fabrice Le Fessant (INRIA Saclay) *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(**************************************************************************)
+
+open Asttypes
+open Typedtree
+
+
+module type IteratorArgument = sig
+ val enter_structure : structure -> unit
+ val enter_value_description : value_description -> unit
+ val enter_type_extension : type_extension -> unit
+ val enter_extension_constructor : extension_constructor -> unit
+ val enter_pattern : pattern -> unit
+ val enter_expression : expression -> unit
+ val enter_package_type : package_type -> unit
+ val enter_signature : signature -> unit
+ val enter_signature_item : signature_item -> unit
+ val enter_module_type_declaration : module_type_declaration -> unit
+ val enter_module_type : module_type -> unit
+ val enter_module_expr : module_expr -> unit
+ val enter_with_constraint : with_constraint -> unit
+ val enter_class_expr : class_expr -> unit
+ val enter_class_signature : class_signature -> unit
+ val enter_class_declaration : class_declaration -> unit
+ val enter_class_description : class_description -> unit
+ val enter_class_type_declaration : class_type_declaration -> unit
+ val enter_class_type : class_type -> unit
+ val enter_class_type_field : class_type_field -> unit
+ val enter_core_type : core_type -> unit
+ val enter_class_structure : class_structure -> unit
+ val enter_class_field : class_field -> unit
+ val enter_structure_item : structure_item -> unit
+
+
+ val leave_structure : structure -> unit
+ val leave_value_description : value_description -> unit
+ val leave_type_extension : type_extension -> unit
+ val leave_extension_constructor : extension_constructor -> unit
+ val leave_pattern : pattern -> unit
+ val leave_expression : expression -> unit
+ val leave_package_type : package_type -> unit
+ val leave_signature : signature -> unit
+ val leave_signature_item : signature_item -> unit
+ val leave_module_type_declaration : module_type_declaration -> unit
+ val leave_module_type : module_type -> unit
+ val leave_module_expr : module_expr -> unit
+ val leave_with_constraint : with_constraint -> unit
+ val leave_class_expr : class_expr -> unit
+ val leave_class_signature : class_signature -> unit
+ val leave_class_declaration : class_declaration -> unit
+ val leave_class_description : class_description -> unit
+ val leave_class_type_declaration : class_type_declaration -> unit
+ val leave_class_type : class_type -> unit
+ val leave_class_type_field : class_type_field -> unit
+ val leave_core_type : core_type -> unit
+ val leave_class_structure : class_structure -> unit
+ val leave_class_field : class_field -> unit
+ val leave_structure_item : structure_item -> unit
+
+ val enter_bindings : rec_flag -> unit
+ val enter_binding : value_binding -> unit
+ val leave_binding : value_binding -> unit
+ val leave_bindings : rec_flag -> unit
+
+ val enter_type_declarations : rec_flag -> unit
+ val enter_type_declaration : type_declaration -> unit
+ val leave_type_declaration : type_declaration -> unit
+ val leave_type_declarations : rec_flag -> unit
+
+end
+
+module MakeIterator :
+ functor (Iter : IteratorArgument) ->
+ sig
+ val iter_structure : structure -> unit
+ val iter_signature : signature -> unit
+ val iter_structure_item : structure_item -> unit
+ val iter_signature_item : signature_item -> unit
+ val iter_expression : expression -> unit
+ val iter_module_type : module_type -> unit
+ val iter_pattern : pattern -> unit
+ val iter_class_expr : class_expr -> unit
+ end
+
+module DefaultIteratorArgument : IteratorArgument
diff --git a/typing/typedtreeMap.ml b/typing/typedtreeMap.ml
new file mode 100644
index 0000000000..704a427b88
--- /dev/null
+++ b/typing/typedtreeMap.ml
@@ -0,0 +1,714 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Typedtree
+
+module type MapArgument = sig
+ val enter_structure : structure -> structure
+ val enter_value_description : value_description -> value_description
+ val enter_type_declaration : type_declaration -> type_declaration
+ val enter_type_extension : type_extension -> type_extension
+ val enter_extension_constructor :
+ extension_constructor -> extension_constructor
+ val enter_pattern : pattern -> pattern
+ val enter_expression : expression -> expression
+ val enter_package_type : package_type -> package_type
+ val enter_signature : signature -> signature
+ val enter_signature_item : signature_item -> signature_item
+ val enter_module_type_declaration :
+ module_type_declaration -> module_type_declaration
+ val enter_module_type : module_type -> module_type
+ val enter_module_expr : module_expr -> module_expr
+ val enter_with_constraint : with_constraint -> with_constraint
+ val enter_class_expr : class_expr -> class_expr
+ val enter_class_signature : class_signature -> class_signature
+ val enter_class_declaration : class_declaration -> class_declaration
+ val enter_class_description : class_description -> class_description
+ val enter_class_type_declaration :
+ class_type_declaration -> class_type_declaration
+ val enter_class_type : class_type -> class_type
+ val enter_class_type_field : class_type_field -> class_type_field
+ val enter_core_type : core_type -> core_type
+ val enter_class_structure : class_structure -> class_structure
+ val enter_class_field : class_field -> class_field
+ val enter_structure_item : structure_item -> structure_item
+
+ val leave_structure : structure -> structure
+ val leave_value_description : value_description -> value_description
+ val leave_type_declaration : type_declaration -> type_declaration
+ val leave_type_extension : type_extension -> type_extension
+ val leave_extension_constructor :
+ extension_constructor -> extension_constructor
+ val leave_pattern : pattern -> pattern
+ val leave_expression : expression -> expression
+ val leave_package_type : package_type -> package_type
+ val leave_signature : signature -> signature
+ val leave_signature_item : signature_item -> signature_item
+ val leave_module_type_declaration :
+ module_type_declaration -> module_type_declaration
+ val leave_module_type : module_type -> module_type
+ val leave_module_expr : module_expr -> module_expr
+ val leave_with_constraint : with_constraint -> with_constraint
+ val leave_class_expr : class_expr -> class_expr
+ val leave_class_signature : class_signature -> class_signature
+ val leave_class_declaration : class_declaration -> class_declaration
+ val leave_class_description : class_description -> class_description
+ val leave_class_type_declaration :
+ class_type_declaration -> class_type_declaration
+ val leave_class_type : class_type -> class_type
+ val leave_class_type_field : class_type_field -> class_type_field
+ val leave_core_type : core_type -> core_type
+ val leave_class_structure : class_structure -> class_structure
+ val leave_class_field : class_field -> class_field
+ val leave_structure_item : structure_item -> structure_item
+
+end
+
+
+module MakeMap(Map : MapArgument) = struct
+
+ let may_map f v =
+ match v with
+ None -> v
+ | Some x -> Some (f x)
+
+
+ open Misc
+
+ let rec map_structure str =
+ let str = Map.enter_structure str in
+ let str_items = List.map map_structure_item str.str_items in
+ Map.leave_structure { str with str_items = str_items }
+
+ and map_binding vb =
+ {
+ vb_pat = map_pattern vb.vb_pat;
+ vb_expr = map_expression vb.vb_expr;
+ vb_attributes = vb.vb_attributes;
+ vb_loc = vb.vb_loc;
+ }
+
+ and map_bindings rec_flag list =
+ List.map map_binding list
+
+ and map_case {c_lhs; c_guard; c_rhs} =
+ {
+ c_lhs = map_pattern c_lhs;
+ c_guard = may_map map_expression c_guard;
+ c_rhs = map_expression c_rhs;
+ }
+
+ and map_cases list =
+ List.map map_case list
+
+ and map_structure_item item =
+ let item = Map.enter_structure_item item in
+ let str_desc =
+ match item.str_desc with
+ Tstr_eval (exp, attrs) -> Tstr_eval (map_expression exp, attrs)
+ | Tstr_value (rec_flag, list) ->
+ Tstr_value (rec_flag, map_bindings rec_flag list)
+ | Tstr_primitive vd ->
+ Tstr_primitive (map_value_description vd)
+ | Tstr_type (rf, list) ->
+ Tstr_type (rf, List.map map_type_declaration list)
+ | Tstr_typext tyext ->
+ Tstr_typext (map_type_extension tyext)
+ | Tstr_exception ext ->
+ Tstr_exception (map_extension_constructor ext)
+ | Tstr_module x ->
+ Tstr_module (map_module_binding x)
+ | Tstr_recmodule list ->
+ let list = List.map map_module_binding list in
+ Tstr_recmodule list
+ | Tstr_modtype mtd ->
+ Tstr_modtype (map_module_type_declaration mtd)
+ | Tstr_open od -> Tstr_open od
+ | Tstr_class list ->
+ let list =
+ List.map
+ (fun (ci, string_list) ->
+ map_class_declaration ci, string_list)
+ list
+ in
+ Tstr_class list
+ | Tstr_class_type list ->
+ let list =
+ List.map
+ (fun (id, name, ct) ->
+ id, name, map_class_type_declaration ct)
+ list
+ in
+ Tstr_class_type list
+ | Tstr_include incl ->
+ Tstr_include {incl with incl_mod = map_module_expr incl.incl_mod}
+ | Tstr_attribute x -> Tstr_attribute x
+ in
+ Map.leave_structure_item { item with str_desc = str_desc}
+
+ and map_module_binding x =
+ {x with mb_expr = map_module_expr x.mb_expr}
+
+ and map_value_description v =
+ let v = Map.enter_value_description v in
+ let val_desc = map_core_type v.val_desc in
+ Map.leave_value_description { v with val_desc = val_desc }
+
+ and map_type_declaration decl =
+ let decl = Map.enter_type_declaration decl in
+ let typ_params = List.map map_type_parameter decl.typ_params in
+ let typ_cstrs = List.map (fun (ct1, ct2, loc) ->
+ (map_core_type ct1,
+ map_core_type ct2,
+ loc)
+ ) decl.typ_cstrs in
+ let typ_kind = match decl.typ_kind with
+ Ttype_abstract -> Ttype_abstract
+ | Ttype_variant list ->
+ let list = List.map map_constructor_declaration list in
+ Ttype_variant list
+ | Ttype_record list ->
+ let list =
+ List.map
+ (fun ld ->
+ {ld with ld_type = map_core_type ld.ld_type}
+ ) list
+ in
+ Ttype_record list
+ | Ttype_open -> Ttype_open
+ in
+ let typ_manifest = may_map map_core_type decl.typ_manifest in
+ Map.leave_type_declaration { decl with typ_params = typ_params;
+ typ_cstrs = typ_cstrs; typ_kind = typ_kind; typ_manifest = typ_manifest }
+
+ and map_type_parameter (ct, v) = (map_core_type ct, v)
+
+ and map_constructor_arguments = function
+ | Cstr_tuple l ->
+ Cstr_tuple (List.map map_core_type l)
+ | Cstr_record l ->
+ Cstr_record
+ (List.map (fun ld -> {ld with ld_type = map_core_type ld.ld_type})
+ l)
+
+ and map_constructor_declaration cd =
+ let cd_args = map_constructor_arguments cd.cd_args in
+ {cd with cd_args;
+ cd_res = may_map map_core_type cd.cd_res
+ }
+
+ and map_type_extension tyext =
+ let tyext = Map.enter_type_extension tyext in
+ let tyext_params = List.map map_type_parameter tyext.tyext_params in
+ let tyext_constructors =
+ List.map map_extension_constructor tyext.tyext_constructors
+ in
+ Map.leave_type_extension { tyext with tyext_params = tyext_params;
+ tyext_constructors = tyext_constructors }
+
+ and map_extension_constructor ext =
+ let ext = Map.enter_extension_constructor ext in
+ let ext_kind = match ext.ext_kind with
+ Text_decl(args, ret) ->
+ let args = map_constructor_arguments args in
+ let ret = may_map map_core_type ret in
+ Text_decl(args, ret)
+ | Text_rebind(p, lid) -> Text_rebind(p, lid)
+ in
+ Map.leave_extension_constructor {ext with ext_kind = ext_kind}
+
+ and map_pattern pat =
+ let pat = Map.enter_pattern pat in
+ let pat_desc =
+ match pat.pat_desc with
+ | Tpat_alias (pat1, p, text) ->
+ let pat1 = map_pattern pat1 in
+ Tpat_alias (pat1, p, text)
+ | Tpat_tuple list -> Tpat_tuple (List.map map_pattern list)
+ | Tpat_construct (lid, cstr_decl, args) ->
+ Tpat_construct (lid, cstr_decl,
+ List.map map_pattern args)
+ | Tpat_variant (label, pato, rowo) ->
+ let pato = match pato with
+ None -> pato
+ | Some pat -> Some (map_pattern pat)
+ in
+ Tpat_variant (label, pato, rowo)
+ | Tpat_record (list, closed) ->
+ Tpat_record (List.map (fun (lid, lab_desc, pat) ->
+ (lid, lab_desc, map_pattern pat) ) list, closed)
+ | Tpat_array list -> Tpat_array (List.map map_pattern list)
+ | Tpat_or (p1, p2, rowo) ->
+ Tpat_or (map_pattern p1, map_pattern p2, rowo)
+ | Tpat_lazy p -> Tpat_lazy (map_pattern p)
+ | Tpat_constant _
+ | Tpat_any
+ | Tpat_var _ -> pat.pat_desc
+
+ in
+ let pat_extra = List.map map_pat_extra pat.pat_extra in
+ Map.leave_pattern { pat with pat_desc = pat_desc; pat_extra = pat_extra }
+
+ and map_pat_extra pat_extra =
+ match pat_extra with
+ | Tpat_constraint ct, loc, attrs ->
+ (Tpat_constraint (map_core_type ct), loc, attrs)
+ | (Tpat_type _ | Tpat_unpack), _, _ -> pat_extra
+
+ and map_expression exp =
+ let exp = Map.enter_expression exp in
+ let exp_desc =
+ match exp.exp_desc with
+ Texp_ident (_, _, _)
+ | Texp_constant _ -> exp.exp_desc
+ | Texp_let (rec_flag, list, exp) ->
+ Texp_let (rec_flag,
+ map_bindings rec_flag list,
+ map_expression exp)
+ | Texp_function (label, cases, partial) ->
+ Texp_function (label, map_cases cases, partial)
+ | Texp_apply (exp, list) ->
+ Texp_apply (map_expression exp,
+ List.map (fun (label, expo, optional) ->
+ let expo =
+ match expo with
+ None -> expo
+ | Some exp -> Some (map_expression exp)
+ in
+ (label, expo, optional)
+ ) list )
+ | Texp_match (exp, list1, list2, partial) ->
+ Texp_match (
+ map_expression exp,
+ map_cases list1,
+ map_cases list2,
+ partial
+ )
+ | Texp_try (exp, list) ->
+ Texp_try (
+ map_expression exp,
+ map_cases list
+ )
+ | Texp_tuple list ->
+ Texp_tuple (List.map map_expression list)
+ | Texp_construct (lid, cstr_desc, args) ->
+ Texp_construct (lid, cstr_desc,
+ List.map map_expression args )
+ | Texp_variant (label, expo) ->
+ let expo =match expo with
+ None -> expo
+ | Some exp -> Some (map_expression exp)
+ in
+ Texp_variant (label, expo)
+ | Texp_record (list, expo) ->
+ let list =
+ List.map (fun (lid, lab_desc, exp) ->
+ (lid, lab_desc, map_expression exp)
+ ) list in
+ let expo = match expo with
+ None -> expo
+ | Some exp -> Some (map_expression exp)
+ in
+ Texp_record (list, expo)
+ | Texp_field (exp, lid, label) ->
+ Texp_field (map_expression exp, lid, label)
+ | Texp_setfield (exp1, lid, label, exp2) ->
+ Texp_setfield (
+ map_expression exp1,
+ lid,
+ label,
+ map_expression exp2)
+ | Texp_array list ->
+ Texp_array (List.map map_expression list)
+ | Texp_ifthenelse (exp1, exp2, expo) ->
+ Texp_ifthenelse (
+ map_expression exp1,
+ map_expression exp2,
+ match expo with
+ None -> expo
+ | Some exp -> Some (map_expression exp)
+ )
+ | Texp_sequence (exp1, exp2) ->
+ Texp_sequence (
+ map_expression exp1,
+ map_expression exp2
+ )
+ | Texp_while (exp1, exp2) ->
+ Texp_while (
+ map_expression exp1,
+ map_expression exp2
+ )
+ | Texp_for (id, name, exp1, exp2, dir, exp3) ->
+ Texp_for (
+ id, name,
+ map_expression exp1,
+ map_expression exp2,
+ dir,
+ map_expression exp3
+ )
+ | Texp_send (exp, meth, expo) ->
+ Texp_send (map_expression exp, meth, may_map map_expression expo)
+ | Texp_new (path, lid, cl_decl) -> exp.exp_desc
+ | Texp_instvar (_, path, _) -> exp.exp_desc
+ | Texp_setinstvar (path, lid, path2, exp) ->
+ Texp_setinstvar (path, lid, path2, map_expression exp)
+ | Texp_override (path, list) ->
+ Texp_override (
+ path,
+ List.map (fun (path, lid, exp) ->
+ (path, lid, map_expression exp)
+ ) list
+ )
+ | Texp_letmodule (id, name, mexpr, exp) ->
+ Texp_letmodule (
+ id, name,
+ map_module_expr mexpr,
+ map_expression exp
+ )
+ | Texp_assert exp -> Texp_assert (map_expression exp)
+ | Texp_lazy exp -> Texp_lazy (map_expression exp)
+ | Texp_object (cl, string_list) ->
+ Texp_object (map_class_structure cl, string_list)
+ | Texp_pack (mexpr) ->
+ Texp_pack (map_module_expr mexpr)
+ in
+ let exp_extra = List.map map_exp_extra exp.exp_extra in
+ Map.leave_expression {
+ exp with
+ exp_desc = exp_desc;
+ exp_extra = exp_extra; }
+
+ and map_exp_extra ((desc, loc, attrs) as exp_extra) =
+ match desc with
+ | Texp_constraint ct ->
+ Texp_constraint (map_core_type ct), loc, attrs
+ | Texp_coerce (None, ct) ->
+ Texp_coerce (None, map_core_type ct), loc, attrs
+ | Texp_coerce (Some ct1, ct2) ->
+ Texp_coerce (Some (map_core_type ct1),
+ map_core_type ct2), loc, attrs
+ | Texp_poly (Some ct) ->
+ Texp_poly (Some ( map_core_type ct )), loc, attrs
+ | Texp_newtype _
+ | Texp_open _
+ | Texp_poly None -> exp_extra
+
+
+ and map_package_type pack =
+ let pack = Map.enter_package_type pack in
+ let pack_fields = List.map (
+ fun (s, ct) -> (s, map_core_type ct) ) pack.pack_fields in
+ Map.leave_package_type { pack with pack_fields = pack_fields }
+
+ and map_signature sg =
+ let sg = Map.enter_signature sg in
+ let sig_items = List.map map_signature_item sg.sig_items in
+ Map.leave_signature { sg with sig_items = sig_items }
+
+ and map_signature_item item =
+ let item = Map.enter_signature_item item in
+ let sig_desc =
+ match item.sig_desc with
+ Tsig_value vd ->
+ Tsig_value (map_value_description vd)
+ | Tsig_type (rf, list) ->
+ Tsig_type (rf, List.map map_type_declaration list)
+ | Tsig_typext tyext ->
+ Tsig_typext (map_type_extension tyext)
+ | Tsig_exception ext ->
+ Tsig_exception (map_extension_constructor ext)
+ | Tsig_module md ->
+ Tsig_module {md with md_type = map_module_type md.md_type}
+ | Tsig_recmodule list ->
+ Tsig_recmodule
+ (List.map
+ (fun md -> {md with md_type = map_module_type md.md_type})
+ list
+ )
+ | Tsig_modtype mtd ->
+ Tsig_modtype (map_module_type_declaration mtd)
+ | Tsig_open _ -> item.sig_desc
+ | Tsig_include incl ->
+ Tsig_include {incl with incl_mod = map_module_type incl.incl_mod}
+ | Tsig_class list -> Tsig_class (List.map map_class_description list)
+ | Tsig_class_type list ->
+ Tsig_class_type (List.map map_class_type_declaration list)
+ | Tsig_attribute _ as x -> x
+ in
+ Map.leave_signature_item { item with sig_desc = sig_desc }
+
+ and map_module_type_declaration mtd =
+ let mtd = Map.enter_module_type_declaration mtd in
+ let mtd = {mtd with mtd_type = may_map map_module_type mtd.mtd_type} in
+ Map.leave_module_type_declaration mtd
+
+ and map_class_declaration cd =
+ let cd = Map.enter_class_declaration cd in
+ let ci_params = List.map map_type_parameter cd.ci_params in
+ let ci_expr = map_class_expr cd.ci_expr in
+ Map.leave_class_declaration
+ { cd with ci_params = ci_params; ci_expr = ci_expr }
+
+ and map_class_description cd =
+ let cd = Map.enter_class_description cd in
+ let ci_params = List.map map_type_parameter cd.ci_params in
+ let ci_expr = map_class_type cd.ci_expr in
+ Map.leave_class_description
+ { cd with ci_params = ci_params; ci_expr = ci_expr}
+
+ and map_class_type_declaration cd =
+ let cd = Map.enter_class_type_declaration cd in
+ let ci_params = List.map map_type_parameter cd.ci_params in
+ let ci_expr = map_class_type cd.ci_expr in
+ Map.leave_class_type_declaration
+ { cd with ci_params = ci_params; ci_expr = ci_expr }
+
+ and map_module_type mty =
+ let mty = Map.enter_module_type mty in
+ let mty_desc =
+ match mty.mty_desc with
+ Tmty_ident _ -> mty.mty_desc
+ | Tmty_alias _ -> mty.mty_desc
+ | Tmty_signature sg -> Tmty_signature (map_signature sg)
+ | Tmty_functor (id, name, mtype1, mtype2) ->
+ Tmty_functor (id, name, Misc.may_map map_module_type mtype1,
+ map_module_type mtype2)
+ | Tmty_with (mtype, list) ->
+ Tmty_with (map_module_type mtype,
+ List.map (fun (path, lid, withc) ->
+ (path, lid, map_with_constraint withc)
+ ) list)
+ | Tmty_typeof mexpr ->
+ Tmty_typeof (map_module_expr mexpr)
+ in
+ Map.leave_module_type { mty with mty_desc = mty_desc}
+
+ and map_with_constraint cstr =
+ let cstr = Map.enter_with_constraint cstr in
+ let cstr =
+ match cstr with
+ Twith_type decl -> Twith_type (map_type_declaration decl)
+ | Twith_typesubst decl -> Twith_typesubst (map_type_declaration decl)
+ | Twith_module (path, lid) -> cstr
+ | Twith_modsubst (path, lid) -> cstr
+ in
+ Map.leave_with_constraint cstr
+
+ and map_module_expr mexpr =
+ let mexpr = Map.enter_module_expr mexpr in
+ let mod_desc =
+ match mexpr.mod_desc with
+ Tmod_ident (p, lid) -> mexpr.mod_desc
+ | Tmod_structure st -> Tmod_structure (map_structure st)
+ | Tmod_functor (id, name, mtype, mexpr) ->
+ Tmod_functor (id, name, Misc.may_map map_module_type mtype,
+ map_module_expr mexpr)
+ | Tmod_apply (mexp1, mexp2, coercion) ->
+ Tmod_apply (map_module_expr mexp1, map_module_expr mexp2, coercion)
+ | Tmod_constraint (mexpr, mod_type, Tmodtype_implicit, coercion ) ->
+ Tmod_constraint (map_module_expr mexpr, mod_type,
+ Tmodtype_implicit, coercion)
+ | Tmod_constraint (mexpr, mod_type,
+ Tmodtype_explicit mtype, coercion) ->
+ Tmod_constraint (map_module_expr mexpr, mod_type,
+ Tmodtype_explicit (map_module_type mtype),
+ coercion)
+ | Tmod_unpack (exp, mod_type) ->
+ Tmod_unpack (map_expression exp, mod_type)
+ in
+ Map.leave_module_expr { mexpr with mod_desc = mod_desc }
+
+ and map_class_expr cexpr =
+ let cexpr = Map.enter_class_expr cexpr in
+ let cl_desc =
+ match cexpr.cl_desc with
+ | Tcl_constraint (cl, None, string_list1, string_list2, concr ) ->
+ Tcl_constraint (map_class_expr cl, None, string_list1,
+ string_list2, concr)
+ | Tcl_structure clstr -> Tcl_structure (map_class_structure clstr)
+ | Tcl_fun (label, pat, priv, cl, partial) ->
+ Tcl_fun (label, map_pattern pat,
+ List.map (fun (id, name, exp) ->
+ (id, name, map_expression exp)) priv,
+ map_class_expr cl, partial)
+
+ | Tcl_apply (cl, args) ->
+ Tcl_apply (map_class_expr cl,
+ List.map (fun (label, expo, optional) ->
+ (label, may_map map_expression expo,
+ optional)
+ ) args)
+ | Tcl_let (rec_flat, bindings, ivars, cl) ->
+ Tcl_let (rec_flat, map_bindings rec_flat bindings,
+ List.map (fun (id, name, exp) ->
+ (id, name, map_expression exp)) ivars,
+ map_class_expr cl)
+
+ | Tcl_constraint (cl, Some clty, vals, meths, concrs) ->
+ Tcl_constraint ( map_class_expr cl,
+ Some (map_class_type clty), vals, meths, concrs)
+
+ | Tcl_ident (id, name, tyl) ->
+ Tcl_ident (id, name, List.map map_core_type tyl)
+ in
+ Map.leave_class_expr { cexpr with cl_desc = cl_desc }
+
+ and map_class_type ct =
+ let ct = Map.enter_class_type ct in
+ let cltyp_desc =
+ match ct.cltyp_desc with
+ Tcty_signature csg -> Tcty_signature (map_class_signature csg)
+ | Tcty_constr (path, lid, list) ->
+ Tcty_constr (path, lid, List.map map_core_type list)
+ | Tcty_arrow (label, ct, cl) ->
+ Tcty_arrow (label, map_core_type ct, map_class_type cl)
+ in
+ Map.leave_class_type { ct with cltyp_desc = cltyp_desc }
+
+ and map_class_signature cs =
+ let cs = Map.enter_class_signature cs in
+ let csig_self = map_core_type cs.csig_self in
+ let csig_fields = List.map map_class_type_field cs.csig_fields in
+ Map.leave_class_signature { cs with
+ csig_self = csig_self; csig_fields = csig_fields }
+
+
+ and map_class_type_field ctf =
+ let ctf = Map.enter_class_type_field ctf in
+ let ctf_desc =
+ match ctf.ctf_desc with
+ Tctf_inherit ct -> Tctf_inherit (map_class_type ct)
+ | Tctf_val (s, mut, virt, ct) ->
+ Tctf_val (s, mut, virt, map_core_type ct)
+ | Tctf_method (s, priv, virt, ct) ->
+ Tctf_method (s, priv, virt, map_core_type ct)
+ | Tctf_constraint (ct1, ct2) ->
+ Tctf_constraint (map_core_type ct1, map_core_type ct2)
+ | Tctf_attribute _ as x -> x
+ in
+ Map.leave_class_type_field { ctf with ctf_desc = ctf_desc }
+
+ and map_core_type ct =
+ let ct = Map.enter_core_type ct in
+ let ctyp_desc =
+ match ct.ctyp_desc with
+ Ttyp_any
+ | Ttyp_var _ -> ct.ctyp_desc
+ | Ttyp_arrow (label, ct1, ct2) ->
+ Ttyp_arrow (label, map_core_type ct1, map_core_type ct2)
+ | Ttyp_tuple list -> Ttyp_tuple (List.map map_core_type list)
+ | Ttyp_constr (path, lid, list) ->
+ Ttyp_constr (path, lid, List.map map_core_type list)
+ | Ttyp_object (list, o) ->
+ Ttyp_object
+ (List.map (fun (s, a, t) -> (s, a, map_core_type t)) list, o)
+ | Ttyp_class (path, lid, list) ->
+ Ttyp_class (path, lid, List.map map_core_type list)
+ | Ttyp_alias (ct, s) -> Ttyp_alias (map_core_type ct, s)
+ | Ttyp_variant (list, bool, labels) ->
+ Ttyp_variant (List.map map_row_field list, bool, labels)
+ | Ttyp_poly (list, ct) -> Ttyp_poly (list, map_core_type ct)
+ | Ttyp_package pack -> Ttyp_package (map_package_type pack)
+ in
+ Map.leave_core_type { ct with ctyp_desc = ctyp_desc }
+
+ and map_class_structure cs =
+ let cs = Map.enter_class_structure cs in
+ let cstr_self = map_pattern cs.cstr_self in
+ let cstr_fields = List.map map_class_field cs.cstr_fields in
+ Map.leave_class_structure { cs with cstr_self; cstr_fields }
+
+ and map_row_field rf =
+ match rf with
+ Ttag (label, attrs, bool, list) ->
+ Ttag (label, attrs, bool, List.map map_core_type list)
+ | Tinherit ct -> Tinherit (map_core_type ct)
+
+ and map_class_field cf =
+ let cf = Map.enter_class_field cf in
+ let cf_desc =
+ match cf.cf_desc with
+ Tcf_inherit (ovf, cl, super, vals, meths) ->
+ Tcf_inherit (ovf, map_class_expr cl, super, vals, meths)
+ | Tcf_constraint (cty, cty') ->
+ Tcf_constraint (map_core_type cty, map_core_type cty')
+ | Tcf_val (lab, mut, ident, Tcfk_virtual cty, b) ->
+ Tcf_val (lab, mut, ident, Tcfk_virtual (map_core_type cty), b)
+ | Tcf_val (lab, mut, ident, Tcfk_concrete (o, exp), b) ->
+ Tcf_val (lab, mut, ident, Tcfk_concrete (o, map_expression exp), b)
+ | Tcf_method (lab, priv, Tcfk_virtual cty) ->
+ Tcf_method (lab, priv, Tcfk_virtual (map_core_type cty))
+ | Tcf_method (lab, priv, Tcfk_concrete (o, exp)) ->
+ Tcf_method (lab, priv, Tcfk_concrete (o, map_expression exp))
+ | Tcf_initializer exp -> Tcf_initializer (map_expression exp)
+ | Tcf_attribute _ as x -> x
+ in
+ Map.leave_class_field { cf with cf_desc = cf_desc }
+end
+
+
+module DefaultMapArgument = struct
+
+ let enter_structure t = t
+ let enter_value_description t = t
+ let enter_type_declaration t = t
+ let enter_type_extension t = t
+ let enter_extension_constructor t = t
+ let enter_pattern t = t
+ let enter_expression t = t
+ let enter_package_type t = t
+ let enter_signature t = t
+ let enter_signature_item t = t
+ let enter_module_type_declaration t = t
+ let enter_module_type t = t
+ let enter_module_expr t = t
+ let enter_with_constraint t = t
+ let enter_class_expr t = t
+ let enter_class_signature t = t
+ let enter_class_declaration t = t
+ let enter_class_description t = t
+ let enter_class_type_declaration t = t
+ let enter_class_type t = t
+ let enter_class_type_field t = t
+ let enter_core_type t = t
+ let enter_class_structure t = t
+ let enter_class_field t = t
+ let enter_structure_item t = t
+
+
+ let leave_structure t = t
+ let leave_value_description t = t
+ let leave_type_declaration t = t
+ let leave_type_extension t = t
+ let leave_extension_constructor t = t
+ let leave_pattern t = t
+ let leave_expression t = t
+ let leave_package_type t = t
+ let leave_signature t = t
+ let leave_signature_item t = t
+ let leave_module_type_declaration t = t
+ let leave_module_type t = t
+ let leave_module_expr t = t
+ let leave_with_constraint t = t
+ let leave_class_expr t = t
+ let leave_class_signature t = t
+ let leave_class_declaration t = t
+ let leave_class_description t = t
+ let leave_class_type_declaration t = t
+ let leave_class_type t = t
+ let leave_class_type_field t = t
+ let leave_core_type t = t
+ let leave_class_structure t = t
+ let leave_class_field t = t
+ let leave_structure_item t = t
+
+end
diff --git a/typing/typedtreeMap.mli b/typing/typedtreeMap.mli
new file mode 100644
index 0000000000..d212a93d97
--- /dev/null
+++ b/typing/typedtreeMap.mli
@@ -0,0 +1,91 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Fabrice Le Fessant, INRIA Saclay *)
+(* *)
+(* Copyright 2012 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Typedtree
+
+module type MapArgument = sig
+ val enter_structure : structure -> structure
+ val enter_value_description : value_description -> value_description
+ val enter_type_declaration : type_declaration -> type_declaration
+ val enter_type_extension : type_extension -> type_extension
+ val enter_extension_constructor :
+ extension_constructor -> extension_constructor
+ val enter_pattern : pattern -> pattern
+ val enter_expression : expression -> expression
+ val enter_package_type : package_type -> package_type
+ val enter_signature : signature -> signature
+ val enter_signature_item : signature_item -> signature_item
+ val enter_module_type_declaration :
+ module_type_declaration -> module_type_declaration
+ val enter_module_type : module_type -> module_type
+ val enter_module_expr : module_expr -> module_expr
+ val enter_with_constraint : with_constraint -> with_constraint
+ val enter_class_expr : class_expr -> class_expr
+ val enter_class_signature : class_signature -> class_signature
+ val enter_class_declaration : class_declaration -> class_declaration
+ val enter_class_description : class_description -> class_description
+ val enter_class_type_declaration :
+ class_type_declaration -> class_type_declaration
+ val enter_class_type : class_type -> class_type
+ val enter_class_type_field : class_type_field -> class_type_field
+ val enter_core_type : core_type -> core_type
+ val enter_class_structure : class_structure -> class_structure
+ val enter_class_field : class_field -> class_field
+ val enter_structure_item : structure_item -> structure_item
+
+ val leave_structure : structure -> structure
+ val leave_value_description : value_description -> value_description
+ val leave_type_declaration : type_declaration -> type_declaration
+ val leave_type_extension : type_extension -> type_extension
+ val leave_extension_constructor :
+ extension_constructor -> extension_constructor
+ val leave_pattern : pattern -> pattern
+ val leave_expression : expression -> expression
+ val leave_package_type : package_type -> package_type
+ val leave_signature : signature -> signature
+ val leave_signature_item : signature_item -> signature_item
+ val leave_module_type_declaration :
+ module_type_declaration -> module_type_declaration
+ val leave_module_type : module_type -> module_type
+ val leave_module_expr : module_expr -> module_expr
+ val leave_with_constraint : with_constraint -> with_constraint
+ val leave_class_expr : class_expr -> class_expr
+ val leave_class_signature : class_signature -> class_signature
+ val leave_class_declaration : class_declaration -> class_declaration
+ val leave_class_description : class_description -> class_description
+ val leave_class_type_declaration :
+ class_type_declaration -> class_type_declaration
+ val leave_class_type : class_type -> class_type
+ val leave_class_type_field : class_type_field -> class_type_field
+ val leave_core_type : core_type -> core_type
+ val leave_class_structure : class_structure -> class_structure
+ val leave_class_field : class_field -> class_field
+ val leave_structure_item : structure_item -> structure_item
+
+end
+
+module MakeMap :
+ functor
+ (Iter : MapArgument) ->
+sig
+ val map_structure : structure -> structure
+ val map_pattern : pattern -> pattern
+ val map_structure_item : structure_item -> structure_item
+ val map_expression : expression -> expression
+ val map_class_expr : class_expr -> class_expr
+
+ val map_signature : signature -> signature
+ val map_signature_item : signature_item -> signature_item
+ val map_module_type : module_type -> module_type
+end
+
+module DefaultMapArgument : MapArgument
diff --git a/typing/typemod.ml b/typing/typemod.ml
new file mode 100644
index 0000000000..0c50f86aaa
--- /dev/null
+++ b/typing/typemod.ml
@@ -0,0 +1,1799 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Misc
+open Longident
+open Path
+open Asttypes
+open Parsetree
+open Types
+open Format
+
+type error =
+ Cannot_apply of module_type
+ | Not_included of Includemod.error list
+ | Cannot_eliminate_dependency of module_type
+ | Signature_expected
+ | Structure_expected of module_type
+ | With_no_component of Longident.t
+ | With_mismatch of Longident.t * Includemod.error list
+ | Repeated_name of string * string
+ | Non_generalizable of type_expr
+ | Non_generalizable_class of Ident.t * class_declaration
+ | Non_generalizable_module of module_type
+ | Implementation_is_required of string
+ | Interface_not_compiled of string
+ | Not_allowed_in_functor_body
+ | With_need_typeconstr
+ | Not_a_packed_module of type_expr
+ | Incomplete_packed_module of type_expr
+ | Scoping_pack of Longident.t * type_expr
+ | Recursive_module_require_explicit_type
+ | Apply_generative
+
+exception Error of Location.t * Env.t * error
+exception Error_forward of Location.error
+
+open Typedtree
+
+let fst3 (x,_,_) = x
+
+let rec path_concat head p =
+ match p with
+ Pident tail -> Pdot (Pident head, Ident.name tail, 0)
+ | Pdot (pre, s, pos) -> Pdot (path_concat head pre, s, pos)
+ | Papply _ -> assert false
+
+(* Extract a signature from a module type *)
+
+let extract_sig env loc mty =
+ match Env.scrape_alias env mty with
+ Mty_signature sg -> sg
+ | _ -> raise(Error(loc, env, Signature_expected))
+
+let extract_sig_open env loc mty =
+ match Env.scrape_alias env mty with
+ Mty_signature sg -> sg
+ | _ -> raise(Error(loc, env, Structure_expected mty))
+
+(* Compute the environment after opening a module *)
+
+let type_open_ ?toplevel ovf env loc lid =
+ let path, md = Typetexp.find_module env lid.loc lid.txt in
+ let sg = extract_sig_open env lid.loc md.md_type in
+ path, Env.open_signature ~loc ?toplevel ovf path sg env
+
+let type_open ?toplevel env sod =
+ let (path, newenv) =
+ type_open_ ?toplevel sod.popen_override env sod.popen_loc sod.popen_lid
+ in
+ let od =
+ {
+ open_override = sod.popen_override;
+ open_path = path;
+ open_txt = sod.popen_lid;
+ open_attributes = sod.popen_attributes;
+ open_loc = sod.popen_loc;
+ }
+ in
+ (path, newenv, od)
+
+(* Record a module type *)
+let rm node =
+ Stypes.record (Stypes.Ti_mod node);
+ node
+
+(* Forward declaration, to be filled in by type_module_type_of *)
+let type_module_type_of_fwd :
+ (Env.t -> Parsetree.module_expr ->
+ Typedtree.module_expr * Types.module_type) ref
+ = ref (fun env m -> assert false)
+
+(* Merge one "with" constraint in a signature *)
+
+let rec add_rec_types env = function
+ Sig_type(id, decl, Trec_next) :: rem ->
+ add_rec_types (Env.add_type ~check:true id decl env) rem
+ | _ -> env
+
+let check_type_decl env loc id row_id newdecl decl rs rem =
+ let env = Env.add_type ~check:true id newdecl env in
+ let env =
+ match row_id with
+ | None -> env
+ | Some id -> Env.add_type ~check:true id newdecl env
+ in
+ let env = if rs = Trec_not then env else add_rec_types env rem in
+ Includemod.type_declarations env id newdecl decl;
+ Typedecl.check_coherence env loc id newdecl
+
+let rec make_params n = function
+ [] -> []
+ | _ :: l -> ("a" ^ string_of_int n) :: make_params (n+1) l
+
+let update_rec_next rs rem =
+ match rs with
+ Trec_next -> rem
+ | Trec_first | Trec_not ->
+ match rem with
+ Sig_type (id, decl, Trec_next) :: rem ->
+ Sig_type (id, decl, rs) :: rem
+ | Sig_module (id, mty, Trec_next) :: rem ->
+ Sig_module (id, mty, rs) :: rem
+ | _ -> rem
+
+let sig_item desc typ env loc = {
+ Typedtree.sig_desc = desc; sig_loc = loc; sig_env = env
+}
+
+let make p n i =
+ let open Variance in
+ set May_pos p (set May_neg n (set May_weak n (set Inj i null)))
+
+let ensure_functor_arg p env =
+ if Env.is_functor_arg p env then env else
+ Env.add_functor_arg (Path.head p) env
+
+let merge_constraint initial_env loc sg constr =
+ let lid =
+ match constr with
+ | Pwith_type (lid, _) | Pwith_module (lid, _) -> lid
+ | Pwith_typesubst {ptype_name=s} | Pwith_modsubst (s, _) ->
+ {loc = s.loc; txt=Lident s.txt}
+ in
+ let real_id = ref None in
+ let rec merge env sg namelist row_id =
+ match (sg, namelist, constr) with
+ ([], _, _) ->
+ raise(Error(loc, env, With_no_component lid.txt))
+ | (Sig_type(id, decl, rs) :: rem, [s],
+ Pwith_type (_, ({ptype_kind = Ptype_abstract} as sdecl)))
+ when Ident.name id = s && Typedecl.is_fixed_type sdecl ->
+ let decl_row =
+ { type_params =
+ List.map (fun _ -> Btype.newgenvar()) sdecl.ptype_params;
+ type_arity = List.length sdecl.ptype_params;
+ type_kind = Type_abstract;
+ type_private = Private;
+ type_manifest = None;
+ type_variance =
+ List.map
+ (fun (_, v) ->
+ let (c, n) =
+ match v with
+ | Covariant -> true, false
+ | Contravariant -> false, true
+ | Invariant -> false, false
+ in
+ make (not n) (not c) false
+ )
+ sdecl.ptype_params;
+ type_loc = sdecl.ptype_loc;
+ type_newtype_level = None;
+ type_attributes = [];
+ }
+ and id_row = Ident.create (s^"#row") in
+ let initial_env =
+ Env.add_type ~check:true id_row decl_row initial_env
+ in
+ let tdecl = Typedecl.transl_with_constraint
+ initial_env id (Some(Pident id_row)) decl sdecl in
+ let newdecl = tdecl.typ_type in
+ check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem;
+ let decl_row = {decl_row with type_params = newdecl.type_params} in
+ let rs' = if rs = Trec_first then Trec_not else rs in
+ (Pident id, lid, Twith_type tdecl),
+ Sig_type(id_row, decl_row, rs') :: Sig_type(id, newdecl, rs) :: rem
+ | (Sig_type(id, decl, rs) :: rem , [s], Pwith_type (_, sdecl))
+ when Ident.name id = s ->
+ let tdecl =
+ Typedecl.transl_with_constraint initial_env id None decl sdecl in
+ let newdecl = tdecl.typ_type in
+ check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem;
+ (Pident id, lid, Twith_type tdecl), Sig_type(id, newdecl, rs) :: rem
+ | (Sig_type(id, decl, rs) :: rem, [s], (Pwith_type _ | Pwith_typesubst _))
+ when Ident.name id = s ^ "#row" ->
+ merge env rem namelist (Some id)
+ | (Sig_type(id, decl, rs) :: rem, [s], Pwith_typesubst sdecl)
+ when Ident.name id = s ->
+ (* Check as for a normal with constraint, but discard definition *)
+ let tdecl =
+ Typedecl.transl_with_constraint initial_env id None decl sdecl in
+ let newdecl = tdecl.typ_type in
+ check_type_decl env sdecl.ptype_loc id row_id newdecl decl rs rem;
+ real_id := Some id;
+ (Pident id, lid, Twith_typesubst tdecl),
+ update_rec_next rs rem
+ | (Sig_module(id, md, rs) :: rem, [s], Pwith_module (_, lid'))
+ when Ident.name id = s ->
+ let path, md' = Typetexp.find_module initial_env loc lid'.txt in
+ let md'' = {md' with md_type = Mtype.remove_aliases env md'.md_type} in
+ let env = ensure_functor_arg path env in
+ let newmd = Mtype.strengthen_decl env md'' path in
+ ignore(Includemod.modtypes env newmd.md_type md.md_type);
+ (Pident id, lid, Twith_module (path, lid')),
+ Sig_module(id, newmd, rs) :: rem
+ | (Sig_module(id, md, rs) :: rem, [s], Pwith_modsubst (_, lid'))
+ when Ident.name id = s ->
+ let path, md' = Typetexp.find_module initial_env loc lid'.txt in
+ let env = ensure_functor_arg path env in
+ let newmd = Mtype.strengthen_decl env md' path in
+ ignore(Includemod.modtypes env newmd.md_type md.md_type);
+ real_id := Some id;
+ (Pident id, lid, Twith_modsubst (path, lid')),
+ update_rec_next rs rem
+ | (Sig_module(id, md, rs) :: rem, s :: namelist, _)
+ when Ident.name id = s ->
+ let ((path, path_loc, tcstr), newsg) =
+ merge env (extract_sig env loc md.md_type) namelist None in
+ (path_concat id path, lid, tcstr),
+ Sig_module(id, {md with md_type=Mty_signature newsg}, rs) :: rem
+ | (item :: rem, _, _) ->
+ let (cstr, items) = merge (Env.add_item item env) rem namelist row_id
+ in
+ cstr, item :: items
+ in
+ try
+ let names = Longident.flatten lid.txt in
+ let (tcstr, sg) = merge initial_env sg names None in
+ let sg =
+ match names, constr with
+ [s], Pwith_typesubst sdecl ->
+ let id =
+ match !real_id with None -> assert false | Some id -> id in
+ let lid =
+ try match sdecl.ptype_manifest with
+ | Some {ptyp_desc = Ptyp_constr (lid, stl)}
+ when List.length stl = List.length sdecl.ptype_params ->
+ List.iter2 (fun x (y, _) ->
+ match x, y with
+ {ptyp_desc=Ptyp_var sx}, {ptyp_desc=Ptyp_var sy}
+ when sx = sy -> ()
+ | _, _ -> raise Exit)
+ stl sdecl.ptype_params;
+ lid
+ | _ -> raise Exit
+ with Exit ->
+ raise(Error(sdecl.ptype_loc, initial_env, With_need_typeconstr))
+ in
+ let (path, _) =
+ try Env.lookup_type lid.txt initial_env with Not_found -> assert false
+ in
+ let sub = Subst.add_type id path Subst.identity in
+ Subst.signature sub sg
+ | [s], Pwith_modsubst (_, lid) ->
+ let id =
+ match !real_id with None -> assert false | Some id -> id in
+ let path = Typetexp.lookup_module initial_env loc lid.txt in
+ let sub = Subst.add_module id path Subst.identity in
+ Subst.signature sub sg
+ | _ ->
+ sg
+ in
+ (tcstr, sg)
+ with Includemod.Error explanation ->
+ raise(Error(loc, initial_env, With_mismatch(lid.txt, explanation)))
+
+(* Add recursion flags on declarations arising from a mutually recursive
+ block. *)
+
+let map_rec fn decls rem =
+ match decls with
+ | [] -> rem
+ | d1 :: dl -> fn Trec_first d1 :: map_end (fn Trec_next) dl rem
+
+let map_rec_type ~rec_flag fn decls rem =
+ match decls with
+ | [] -> rem
+ | d1 :: dl ->
+ let first =
+ match rec_flag with
+ | Recursive -> Trec_first
+ | Nonrecursive -> Trec_not
+ in
+ fn first d1 :: map_end (fn Trec_next) dl rem
+
+let rec map_rec_type_with_row_types ~rec_flag fn decls rem =
+ match decls with
+ | [] -> rem
+ | d1 :: dl ->
+ if Btype.is_row_name (Ident.name d1.typ_id) then
+ fn Trec_not d1 :: map_rec_type_with_row_types ~rec_flag fn dl rem
+ else
+ map_rec_type ~rec_flag fn decls rem
+
+(* Add type extension flags to extension contructors *)
+let map_ext fn exts rem =
+ match exts with
+ | [] -> rem
+ | d1 :: dl -> fn Text_first d1 :: map_end (fn Text_next) dl rem
+
+(* Auxiliary for translating recursively-defined module types.
+ Return a module type that approximates the shape of the given module
+ type AST. Retain only module, type, and module type
+ components of signatures. For types, retain only their arity,
+ making them abstract otherwise. *)
+
+let rec approx_modtype env smty =
+ match smty.pmty_desc with
+ Pmty_ident lid ->
+ let (path, info) = Typetexp.find_modtype env smty.pmty_loc lid.txt in
+ Mty_ident path
+ | Pmty_alias lid ->
+ let path = Typetexp.lookup_module env smty.pmty_loc lid.txt in
+ Mty_alias path
+ | Pmty_signature ssg ->
+ Mty_signature(approx_sig env ssg)
+ | Pmty_functor(param, sarg, sres) ->
+ let arg = may_map (approx_modtype env) sarg in
+ let (id, newenv) =
+ Env.enter_module ~arg:true param.txt (Btype.default_mty arg) env in
+ let res = approx_modtype newenv sres in
+ Mty_functor(id, arg, res)
+ | Pmty_with(sbody, constraints) ->
+ approx_modtype env sbody
+ | Pmty_typeof smod ->
+ let (_, mty) = !type_module_type_of_fwd env smod in
+ mty
+ | Pmty_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+and approx_module_declaration env pmd =
+ {
+ Types.md_type = approx_modtype env pmd.pmd_type;
+ md_attributes = pmd.pmd_attributes;
+ md_loc = pmd.pmd_loc;
+ }
+
+and approx_sig env ssg =
+ match ssg with
+ [] -> []
+ | item :: srem ->
+ match item.psig_desc with
+ | Psig_type (rec_flag, sdecls) ->
+ let decls = Typedecl.approx_type_decl env sdecls in
+ let rem = approx_sig env srem in
+ map_rec_type ~rec_flag
+ (fun rs (id, info) -> Sig_type(id, info, rs)) decls rem
+ | Psig_module pmd ->
+ let id = Ident.create pmd.pmd_name.txt in
+ let md = approx_module_declaration env pmd in
+ let newenv = Env.enter_module_declaration id md env in
+ Sig_module(id, md, Trec_not) :: approx_sig newenv srem
+ | Psig_recmodule sdecls ->
+ let decls =
+ List.map
+ (fun pmd ->
+ (Ident.create pmd.pmd_name.txt,
+ approx_module_declaration env pmd)
+ )
+ sdecls
+ in
+ let newenv =
+ List.fold_left
+ (fun env (id, md) -> Env.add_module_declaration id md env)
+ env decls in
+ map_rec (fun rs (id, md) -> Sig_module(id, md, rs)) decls
+ (approx_sig newenv srem)
+ | Psig_modtype d ->
+ let info = approx_modtype_info env d in
+ let (id, newenv) = Env.enter_modtype d.pmtd_name.txt info env in
+ Sig_modtype(id, info) :: approx_sig newenv srem
+ | Psig_open sod ->
+ let (path, mty, _od) = type_open env sod in
+ approx_sig mty srem
+ | Psig_include sincl ->
+ let smty = sincl.pincl_mod in
+ let mty = approx_modtype env smty in
+ let sg = Subst.signature Subst.identity
+ (extract_sig env smty.pmty_loc mty) in
+ let newenv = Env.add_signature sg env in
+ sg @ approx_sig newenv srem
+ | Psig_class sdecls | Psig_class_type sdecls ->
+ let decls = Typeclass.approx_class_declarations env sdecls in
+ let rem = approx_sig env srem in
+ List.flatten
+ (map_rec
+ (fun rs (i1, _, d1, i2, d2, i3, d3, _) ->
+ [Sig_class_type(i1, d1, rs);
+ Sig_type(i2, d2, rs);
+ Sig_type(i3, d3, rs)])
+ decls [rem])
+ | _ ->
+ approx_sig env srem
+
+and approx_modtype_info env sinfo =
+ {
+ mtd_type = may_map (approx_modtype env) sinfo.pmtd_type;
+ mtd_attributes = sinfo.pmtd_attributes;
+ mtd_loc = sinfo.pmtd_loc;
+ }
+
+(* Additional validity checks on type definitions arising from
+ recursive modules *)
+
+let check_recmod_typedecls env sdecls decls =
+ let recmod_ids = List.map fst3 decls in
+ List.iter2
+ (fun pmd (id, _, mty) ->
+ let mty = mty.mty_type in
+ List.iter
+ (fun path ->
+ Typedecl.check_recmod_typedecl env pmd.pmd_type.pmty_loc recmod_ids
+ path (Env.find_type path env))
+ (Mtype.type_paths env (Pident id) mty))
+ sdecls decls
+
+(* Auxiliaries for checking uniqueness of names in signatures and structures *)
+
+module StringSet =
+ Set.Make(struct type t = string let compare (x:t) y = compare x y end)
+
+let check cl loc set_ref name =
+ if StringSet.mem name !set_ref
+ then raise(Error(loc, Env.empty, Repeated_name(cl, name)))
+ else set_ref := StringSet.add name !set_ref
+
+type names =
+ {
+ types: StringSet.t ref;
+ modules: StringSet.t ref;
+ modtypes: StringSet.t ref;
+ typexts: StringSet.t ref;
+ }
+
+let new_names () =
+ {
+ types = ref StringSet.empty;
+ modules = ref StringSet.empty;
+ modtypes = ref StringSet.empty;
+ typexts = ref StringSet.empty;
+ }
+
+
+let check_name check names name = check names name.loc name.txt
+let check_type names loc s = check "type" loc names.types s
+let check_module names loc s = check "module" loc names.modules s
+let check_modtype names loc s = check "module type" loc names.modtypes s
+let check_typext names loc s = check "extension constructor" loc names.typexts s
+
+
+let check_sig_item names loc = function
+ | Sig_type(id, _, _) -> check_type names loc (Ident.name id)
+ | Sig_module(id, _, _) -> check_module names loc (Ident.name id)
+ | Sig_modtype(id, _) -> check_modtype names loc (Ident.name id)
+ | Sig_typext(id, _, _) -> check_typext names loc (Ident.name id)
+ | _ -> ()
+
+(* Simplify multiple specifications of a value or an extension in a signature.
+ (Other signature components, e.g. types, modules, etc, are checked for
+ name uniqueness.) If multiple specifications with the same name,
+ keep only the last (rightmost) one. *)
+
+let simplify_signature sg =
+ let rec aux = function
+ | [] -> [], StringSet.empty
+ | (Sig_value(id, descr) as component) :: sg ->
+ let (sg, val_names) as k = aux sg in
+ let name = Ident.name id in
+ if StringSet.mem name val_names then k
+ else (component :: sg, StringSet.add name val_names)
+ | component :: sg ->
+ let (sg, val_names) = aux sg in
+ (component :: sg, val_names)
+ in
+ let (sg, _) = aux sg in
+ sg
+
+(* Check and translate a module type expression *)
+
+let transl_modtype_longident loc env lid =
+ let (path, info) = Typetexp.find_modtype env loc lid in
+ path
+
+let transl_module_alias loc env lid =
+ Typetexp.lookup_module env loc lid
+
+let mkmty desc typ env loc attrs =
+ let mty = {
+ mty_desc = desc;
+ mty_type = typ;
+ mty_loc = loc;
+ mty_env = env;
+ mty_attributes = attrs;
+ } in
+ Cmt_format.add_saved_type (Cmt_format.Partial_module_type mty);
+ mty
+
+let mksig desc env loc =
+ let sg = { sig_desc = desc; sig_loc = loc; sig_env = env } in
+ Cmt_format.add_saved_type (Cmt_format.Partial_signature_item sg);
+ sg
+
+(* let signature sg = List.map (fun item -> item.sig_type) sg *)
+
+let rec transl_modtype env smty =
+ let loc = smty.pmty_loc in
+ match smty.pmty_desc with
+ Pmty_ident lid ->
+ let path = transl_modtype_longident loc env lid.txt in
+ mkmty (Tmty_ident (path, lid)) (Mty_ident path) env loc
+ smty.pmty_attributes
+ | Pmty_alias lid ->
+ let path = transl_module_alias loc env lid.txt in
+ mkmty (Tmty_alias (path, lid)) (Mty_alias path) env loc
+ smty.pmty_attributes
+ | Pmty_signature ssg ->
+ let sg = transl_signature env ssg in
+ mkmty (Tmty_signature sg) (Mty_signature sg.sig_type) env loc
+ smty.pmty_attributes
+ | Pmty_functor(param, sarg, sres) ->
+ let arg = Misc.may_map (transl_modtype env) sarg in
+ let ty_arg = Misc.may_map (fun m -> m.mty_type) arg in
+ let (id, newenv) =
+ Env.enter_module ~arg:true param.txt (Btype.default_mty ty_arg) env in
+ Ctype.init_def(Ident.current_time()); (* PR#6513 *)
+ let res = transl_modtype newenv sres in
+ mkmty (Tmty_functor (id, param, arg, res))
+ (Mty_functor(id, ty_arg, res.mty_type)) env loc
+ smty.pmty_attributes
+ | Pmty_with(sbody, constraints) ->
+ let body = transl_modtype env sbody in
+ let init_sg = extract_sig env sbody.pmty_loc body.mty_type in
+ let (rev_tcstrs, final_sg) =
+ List.fold_left
+ (fun (rev_tcstrs,sg) sdecl ->
+ let (tcstr, sg) = merge_constraint env smty.pmty_loc sg sdecl
+ in
+ (tcstr :: rev_tcstrs, sg)
+ )
+ ([],init_sg) constraints in
+ mkmty (Tmty_with ( body, List.rev rev_tcstrs))
+ (Mtype.freshen (Mty_signature final_sg)) env loc
+ smty.pmty_attributes
+ | Pmty_typeof smod ->
+ let env = Env.in_signature false env in
+ let tmty, mty = !type_module_type_of_fwd env smod in
+ mkmty (Tmty_typeof tmty) mty env loc smty.pmty_attributes
+ | Pmty_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+and transl_signature env sg =
+ let names = new_names () in
+ let rec transl_sig env sg =
+ Ctype.init_def(Ident.current_time());
+ match sg with
+ [] -> [], [], env
+ | item :: srem ->
+ let loc = item.psig_loc in
+ match item.psig_desc with
+ | Psig_value sdesc ->
+ let (tdesc, newenv) =
+ Typetexp.with_warning_attribute sdesc.pval_attributes (fun () ->
+ Typedecl.transl_value_decl env item.psig_loc sdesc)
+ in
+ let (trem,rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_value tdesc) env loc :: trem,
+ Sig_value(tdesc.val_id, tdesc.val_val) :: rem,
+ final_env
+ | Psig_type (rec_flag, sdecls) ->
+ List.iter
+ (fun decl -> check_name check_type names decl.ptype_name)
+ sdecls;
+ let (decls, newenv) =
+ Typedecl.transl_type_decl env rec_flag sdecls
+ in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_type (rec_flag, decls)) env loc :: trem,
+ map_rec_type_with_row_types ~rec_flag
+ (fun rs td -> Sig_type(td.typ_id, td.typ_type, rs)) decls rem,
+ final_env
+ | Psig_typext styext ->
+ List.iter
+ (fun pext -> check_name check_typext names pext.pext_name)
+ styext.ptyext_constructors;
+ let (tyext, newenv) =
+ Typedecl.transl_type_extension false env item.psig_loc styext
+ in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ let constructors = tyext.tyext_constructors in
+ mksig (Tsig_typext tyext) env loc :: trem,
+ map_ext (fun es ext ->
+ Sig_typext(ext.ext_id, ext.ext_type, es)) constructors rem,
+ final_env
+ | Psig_exception sext ->
+ check_name check_typext names sext.pext_name;
+ let (ext, newenv) = Typedecl.transl_exception env sext in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_exception ext) env loc :: trem,
+ Sig_typext(ext.ext_id, ext.ext_type, Text_exception) :: rem,
+ final_env
+ | Psig_module pmd ->
+ check_name check_module names pmd.pmd_name;
+ let id = Ident.create pmd.pmd_name.txt in
+ let tmty =
+ Typetexp.with_warning_attribute pmd.pmd_attributes (fun () ->
+ transl_modtype env pmd.pmd_type)
+ in
+ let md = {
+ md_type=tmty.mty_type;
+ md_attributes=pmd.pmd_attributes;
+ md_loc=pmd.pmd_loc;
+ }
+ in
+ let newenv = Env.enter_module_declaration id md env in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_module {md_id=id; md_name=pmd.pmd_name; md_type=tmty;
+ md_loc=pmd.pmd_loc;
+ md_attributes=pmd.pmd_attributes})
+ env loc :: trem,
+ Sig_module(id, md, Trec_not) :: rem,
+ final_env
+ | Psig_recmodule sdecls ->
+ List.iter
+ (fun pmd -> check_name check_module names pmd.pmd_name)
+ sdecls;
+ let (decls, newenv) =
+ transl_recmodule_modtypes item.psig_loc env sdecls in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_recmodule decls) env loc :: trem,
+ map_rec (fun rs md ->
+ let d = {Types.md_type = md.md_type.mty_type;
+ md_attributes = md.md_attributes;
+ md_loc = md.md_loc;
+ } in
+ Sig_module(md.md_id, d, rs))
+ decls rem,
+ final_env
+ | Psig_modtype pmtd ->
+ let newenv, mtd, sg =
+ Typetexp.with_warning_attribute pmtd.pmtd_attributes (fun () ->
+ transl_modtype_decl names env item.psig_loc pmtd)
+ in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_modtype mtd) env loc :: trem,
+ sg :: rem,
+ final_env
+ | Psig_open sod ->
+ let (path, newenv, od) = type_open env sod in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_open od) env loc :: trem,
+ rem, final_env
+ | Psig_include sincl ->
+ let smty = sincl.pincl_mod in
+ let tmty =
+ Typetexp.with_warning_attribute sincl.pincl_attributes (fun () ->
+ transl_modtype env smty)
+ in
+ let mty = tmty.mty_type in
+ let sg = Subst.signature Subst.identity
+ (extract_sig env smty.pmty_loc mty) in
+ List.iter (check_sig_item names item.psig_loc) sg;
+ let newenv = Env.add_signature sg env in
+ let incl =
+ { incl_mod = tmty;
+ incl_type = sg;
+ incl_attributes = sincl.pincl_attributes;
+ incl_loc = sincl.pincl_loc;
+ }
+ in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_include incl) env loc :: trem,
+ sg @ rem,
+ final_env
+ | Psig_class cl ->
+ List.iter
+ (fun {pci_name} -> check_name check_type names pci_name)
+ cl;
+ let (classes, newenv) = Typeclass.class_descriptions env cl in
+ let (trem, rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_class
+ (List.map2
+ (fun pcl tcl ->
+ let (_, _, _, _, _, _, _, _, _, _, _, tcl) = tcl in
+ tcl)
+ cl classes)) env loc
+ :: trem,
+ List.flatten
+ (map_rec
+ (fun rs (i, _, d, i', d', i'', d'', i''', d''', _, _, _) ->
+ [Sig_class(i, d, rs);
+ Sig_class_type(i', d', rs);
+ Sig_type(i'', d'', rs);
+ Sig_type(i''', d''', rs)])
+ classes [rem]),
+ final_env
+ | Psig_class_type cl ->
+ List.iter
+ (fun {pci_name} -> check_name check_type names pci_name)
+ cl;
+ let (classes, newenv) = Typeclass.class_type_declarations env cl in
+ let (trem,rem, final_env) = transl_sig newenv srem in
+ mksig (Tsig_class_type (List.map2 (fun pcl tcl ->
+ let (_, _, _, _, _, _, _, tcl) = tcl in
+ tcl
+ ) cl classes)) env loc :: trem,
+ List.flatten
+ (map_rec
+ (fun rs (i, _, d, i', d', i'', d'', _) ->
+ [Sig_class_type(i, d, rs);
+ Sig_type(i', d', rs);
+ Sig_type(i'', d'', rs)])
+ classes [rem]),
+ final_env
+ | Psig_attribute x ->
+ Typetexp.warning_attribute [x];
+ let (trem,rem, final_env) = transl_sig env srem in
+ mksig (Tsig_attribute x) env loc :: trem, rem, final_env
+ | Psig_extension (ext, _attrs) ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+ in
+ let previous_saved_types = Cmt_format.get_saved_types () in
+ Typetexp.warning_enter_scope ();
+ let (trem, rem, final_env) = transl_sig (Env.in_signature true env) sg in
+ let rem = simplify_signature rem in
+ let sg = { sig_items = trem; sig_type = rem; sig_final_env = final_env } in
+ Typetexp.warning_leave_scope ();
+ Cmt_format.set_saved_types
+ ((Cmt_format.Partial_signature sg) :: previous_saved_types);
+ sg
+
+and transl_modtype_decl names env loc
+ {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} =
+ check_name check_modtype names pmtd_name;
+ let tmty = Misc.may_map (transl_modtype env) pmtd_type in
+ let decl =
+ {
+ Types.mtd_type=may_map (fun t -> t.mty_type) tmty;
+ mtd_attributes=pmtd_attributes;
+ mtd_loc=pmtd_loc;
+ }
+ in
+ let (id, newenv) = Env.enter_modtype pmtd_name.txt decl env in
+ let mtd =
+ {
+ mtd_id=id;
+ mtd_name=pmtd_name;
+ mtd_type=tmty;
+ mtd_attributes=pmtd_attributes;
+ mtd_loc=pmtd_loc;
+ }
+ in
+ newenv, mtd, Sig_modtype(id, decl)
+
+and transl_recmodule_modtypes loc env sdecls =
+ let make_env curr =
+ List.fold_left
+ (fun env (id, _, mty) -> Env.add_module ~arg:true id mty env)
+ env curr in
+ let make_env2 curr =
+ List.fold_left
+ (fun env (id, _, mty) -> Env.add_module ~arg:true id mty.mty_type env)
+ env curr in
+ let transition env_c curr =
+ List.map2
+ (fun pmd (id, id_loc, mty) ->
+ let tmty =
+ Typetexp.with_warning_attribute pmd.pmd_attributes (fun () ->
+ transl_modtype env_c pmd.pmd_type)
+ in
+ (id, id_loc, tmty))
+ sdecls curr in
+ let ids = List.map (fun x -> Ident.create x.pmd_name.txt) sdecls in
+ let approx_env =
+ (*
+ cf #5965
+ We use a dummy module type in order to detect a reference to one
+ of the module being defined during the call to approx_modtype.
+ It will be detected in Env.lookup_module.
+ *)
+ List.fold_left
+ (fun env id ->
+ let dummy = Mty_ident (Path.Pident (Ident.create "#recmod#")) in
+ Env.add_module ~arg:true id dummy env
+ )
+ env ids
+ in
+ let init =
+ List.map2
+ (fun id pmd ->
+ (id, pmd.pmd_name, approx_modtype approx_env pmd.pmd_type))
+ ids sdecls
+ in
+ let env0 = make_env init in
+ let dcl1 = transition env0 init in
+ let env1 = make_env2 dcl1 in
+ check_recmod_typedecls env1 sdecls dcl1;
+ let dcl2 = transition env1 dcl1 in
+(*
+ List.iter
+ (fun (id, mty) ->
+ Format.printf "%a: %a@." Printtyp.ident id Printtyp.modtype mty)
+ dcl2;
+*)
+ let env2 = make_env2 dcl2 in
+ check_recmod_typedecls env2 sdecls dcl2;
+ let dcl2 =
+ List.map2
+ (fun pmd (id, id_loc, mty) ->
+ {md_id=id; md_name=id_loc; md_type=mty;
+ md_loc=pmd.pmd_loc;
+ md_attributes=pmd.pmd_attributes})
+ sdecls dcl2
+ in
+ (dcl2, env2)
+
+(* Try to convert a module expression to a module path. *)
+
+exception Not_a_path
+
+let rec path_of_module mexp =
+ match mexp.mod_desc with
+ Tmod_ident (p,_) -> p
+ | Tmod_apply(funct, arg, coercion) when !Clflags.applicative_functors ->
+ Papply(path_of_module funct, path_of_module arg)
+ | Tmod_constraint (mexp, _, _, _) ->
+ path_of_module mexp
+ | _ -> raise Not_a_path
+
+let path_of_module mexp =
+ try Some (path_of_module mexp) with Not_a_path -> None
+
+(* Check that all core type schemes in a structure are closed *)
+
+let rec closed_modtype env = function
+ Mty_ident p -> true
+ | Mty_alias p -> true
+ | Mty_signature sg ->
+ let env = Env.add_signature sg env in
+ List.for_all (closed_signature_item env) sg
+ | Mty_functor(id, param, body) ->
+ let env = Env.add_module ~arg:true id (Btype.default_mty param) env in
+ closed_modtype env body
+
+and closed_signature_item env = function
+ Sig_value(id, desc) -> Ctype.closed_schema env desc.val_type
+ | Sig_module(id, md, _) -> closed_modtype env md.md_type
+ | _ -> true
+
+let check_nongen_scheme env sig_item =
+ match sig_item with
+ Sig_value(_id, vd) ->
+ if not (Ctype.closed_schema env vd.val_type) then
+ raise (Error (vd.val_loc, env, Non_generalizable vd.val_type))
+ | Sig_module (_id, md, _) ->
+ if not (closed_modtype env md.md_type) then
+ raise(Error(md.md_loc, env, Non_generalizable_module md.md_type))
+ | _ -> ()
+
+let check_nongen_schemes env sg =
+ List.iter (check_nongen_scheme env) sg
+
+(* Helpers for typing recursive modules *)
+
+let anchor_submodule name anchor =
+ match anchor with None -> None | Some p -> Some(Pdot(p, name, nopos))
+let anchor_recmodule id anchor =
+ Some (Pident id)
+
+let enrich_type_decls anchor decls oldenv newenv =
+ match anchor with
+ None -> newenv
+ | Some p ->
+ List.fold_left
+ (fun e info ->
+ let id = info.typ_id in
+ let info' =
+ Mtype.enrich_typedecl oldenv (Pdot(p, Ident.name id, nopos))
+ info.typ_type
+ in
+ Env.add_type ~check:true id info' e)
+ oldenv decls
+
+let enrich_module_type anchor name mty env =
+ match anchor with
+ None -> mty
+ | Some p -> Mtype.enrich_modtype env (Pdot(p, name, nopos)) mty
+
+let check_recmodule_inclusion env bindings =
+ (* PR#4450, PR#4470: consider
+ module rec X : DECL = MOD where MOD has inferred type ACTUAL
+ The "natural" typing condition
+ E, X: ACTUAL |- ACTUAL <: DECL
+ leads to circularities through manifest types.
+ Instead, we "unroll away" the potential circularities a finite number
+ of times. The (weaker) condition we implement is:
+ E, X: DECL,
+ X1: ACTUAL,
+ X2: ACTUAL{X <- X1}/X1
+ ...
+ Xn: ACTUAL{X <- X(n-1)}/X(n-1)
+ |- ACTUAL{X <- Xn}/Xn <: DECL{X <- Xn}
+ so that manifest types rooted at X(n+1) are expanded in terms of X(n),
+ avoiding circularities. The strengthenings ensure that
+ Xn.t = X(n-1).t = ... = X2.t = X1.t.
+ N can be chosen arbitrarily; larger values of N result in more
+ recursive definitions being accepted. A good choice appears to be
+ the number of mutually recursive declarations. *)
+
+ let subst_and_strengthen env s id mty =
+ let p = Subst.module_path s (Pident id) in
+ let env = ensure_functor_arg p env in
+ Mtype.strengthen env (Subst.modtype s mty) p
+ in
+
+ let rec check_incl first_time n env s =
+ if n > 0 then begin
+ (* Generate fresh names Y_i for the rec. bound module idents X_i *)
+ let bindings1 =
+ List.map
+ (fun (id, _, mty_decl, modl, mty_actual, _attrs, _loc) ->
+ (id, Ident.rename id, mty_actual))
+ bindings in
+ (* Enter the Y_i in the environment with their actual types substituted
+ by the input substitution s *)
+ let env' =
+ List.fold_left
+ (fun env (id, id', mty_actual) ->
+ let mty_actual' =
+ if first_time
+ then mty_actual
+ else subst_and_strengthen env s id mty_actual in
+ Env.add_module ~arg:false id' mty_actual' env)
+ env bindings1 in
+ (* Build the output substitution Y_i <- X_i *)
+ let s' =
+ List.fold_left
+ (fun s (id, id', mty_actual) ->
+ Subst.add_module id (Pident id') s)
+ Subst.identity bindings1 in
+ (* Recurse with env' and s' *)
+ check_incl false (n-1) env' s'
+ end else begin
+ (* Base case: check inclusion of s(mty_actual) in s(mty_decl)
+ and insert coercion if needed *)
+ let check_inclusion (id, id_loc, mty_decl, modl, mty_actual, attrs, loc) =
+ let mty_decl' = Subst.modtype s mty_decl.mty_type
+ and mty_actual' = subst_and_strengthen env s id mty_actual in
+ let coercion =
+ try
+ Includemod.modtypes env mty_actual' mty_decl'
+ with Includemod.Error msg ->
+ raise(Error(modl.mod_loc, env, Not_included msg)) in
+ let modl' =
+ { mod_desc = Tmod_constraint(modl, mty_decl.mty_type,
+ Tmodtype_explicit mty_decl, coercion);
+ mod_type = mty_decl.mty_type;
+ mod_env = env;
+ mod_loc = modl.mod_loc;
+ mod_attributes = [];
+ } in
+ {
+ mb_id = id;
+ mb_name = id_loc;
+ mb_expr = modl';
+ mb_attributes = attrs;
+ mb_loc = loc;
+ }
+ in
+ List.map check_inclusion bindings
+ end
+ in check_incl true (List.length bindings) env Subst.identity
+
+(* Helper for unpack *)
+
+let rec package_constraints env loc mty constrs =
+ if constrs = [] then mty
+ else let sg = extract_sig env loc mty in
+ let sg' =
+ List.map
+ (function
+ | Sig_type (id, ({type_params=[]} as td), rs)
+ when List.mem_assoc [Ident.name id] constrs ->
+ let ty = List.assoc [Ident.name id] constrs in
+ Sig_type (id, {td with type_manifest = Some ty}, rs)
+ | Sig_module (id, md, rs) ->
+ let rec aux = function
+ | (m :: ((_ :: _) as l), t) :: rest when m = Ident.name id ->
+ (l, t) :: aux rest
+ | _ :: rest -> aux rest
+ | [] -> []
+ in
+ let md =
+ {md with
+ md_type = package_constraints env loc md.md_type (aux constrs)
+ }
+ in
+ Sig_module (id, md, rs)
+ | item -> item
+ )
+ sg
+ in
+ Mty_signature sg'
+
+let modtype_of_package env loc p nl tl =
+ try match (Env.find_modtype p env).mtd_type with
+ | Some mty when nl <> [] ->
+ package_constraints env loc mty
+ (List.combine (List.map Longident.flatten nl) tl)
+ | _ ->
+ if nl = [] then Mty_ident p
+ else raise(Error(loc, env, Signature_expected))
+ with Not_found ->
+ let error = Typetexp.Unbound_modtype (Ctype.lid_of_path p) in
+ raise(Typetexp.Error(loc, env, error))
+
+let package_subtype env p1 nl1 tl1 p2 nl2 tl2 =
+ let mkmty p nl tl =
+ let ntl =
+ List.filter (fun (n,t) -> Ctype.free_variables t = [])
+ (List.combine nl tl) in
+ let (nl, tl) = List.split ntl in
+ modtype_of_package env Location.none p nl tl
+ in
+ let mty1 = mkmty p1 nl1 tl1 and mty2 = mkmty p2 nl2 tl2 in
+ try Includemod.modtypes env mty1 mty2 = Tcoerce_none
+ with Includemod.Error msg -> false
+ (* raise(Error(Location.none, env, Not_included msg)) *)
+
+let () = Ctype.package_subtype := package_subtype
+
+let wrap_constraint env arg mty explicit =
+ let coercion =
+ try
+ Includemod.modtypes env arg.mod_type mty
+ with Includemod.Error msg ->
+ raise(Error(arg.mod_loc, env, Not_included msg)) in
+ { mod_desc = Tmod_constraint(arg, mty, explicit, coercion);
+ mod_type = mty;
+ mod_env = env;
+ mod_attributes = [];
+ mod_loc = arg.mod_loc }
+
+(* Type a module value expression *)
+
+let rec type_module ?(alias=false) sttn funct_body anchor env smod =
+ match smod.pmod_desc with
+ Pmod_ident lid ->
+ let path =
+ Typetexp.lookup_module ~load:(not alias) env smod.pmod_loc lid.txt in
+ let md = { mod_desc = Tmod_ident (path, lid);
+ mod_type = Mty_alias path;
+ mod_env = env;
+ mod_attributes = smod.pmod_attributes;
+ mod_loc = smod.pmod_loc } in
+ let md =
+ if alias && not (Env.is_functor_arg path env) then
+ (Env.add_required_global (Path.head path); md)
+ else match (Env.find_module path env).md_type with
+ Mty_alias p1 when not alias ->
+ let p1 = Env.normalize_path (Some smod.pmod_loc) env p1 in
+ let mty = Includemod.expand_module_alias env [] p1 in
+ { md with
+ mod_desc = Tmod_constraint (md, mty, Tmodtype_implicit,
+ Tcoerce_alias (p1, Tcoerce_none));
+ mod_type = if sttn then Mtype.strengthen env mty p1 else mty }
+ | mty ->
+ let mty =
+ if sttn then Mtype.strengthen env mty path else mty in
+ { md with mod_type = mty }
+ in rm md
+ | Pmod_structure sstr ->
+ let (str, sg, finalenv) =
+ type_structure funct_body anchor env sstr smod.pmod_loc in
+ let md =
+ rm { mod_desc = Tmod_structure str;
+ mod_type = Mty_signature sg;
+ mod_env = env;
+ mod_attributes = smod.pmod_attributes;
+ mod_loc = smod.pmod_loc }
+ in
+ let sg' = simplify_signature sg in
+ if List.length sg' = List.length sg then md else
+ wrap_constraint (Env.implicit_coercion env) md (Mty_signature sg')
+ Tmodtype_implicit
+ | Pmod_functor(name, smty, sbody) ->
+ let mty = may_map (transl_modtype env) smty in
+ let ty_arg = may_map (fun m -> m.mty_type) mty in
+ let (id, newenv), funct_body =
+ match ty_arg with None -> (Ident.create "*", env), false
+ | Some mty -> Env.enter_module ~arg:true name.txt mty env, true in
+ let body = type_module sttn funct_body None newenv sbody in
+ rm { mod_desc = Tmod_functor(id, name, mty, body);
+ mod_type = Mty_functor(id, ty_arg, body.mod_type);
+ mod_env = env;
+ mod_attributes = smod.pmod_attributes;
+ mod_loc = smod.pmod_loc }
+ | Pmod_apply(sfunct, sarg) ->
+ let arg = type_module true funct_body None env sarg in
+ let path = path_of_module arg in
+ let funct =
+ type_module (sttn && path <> None) funct_body None env sfunct in
+ begin match Env.scrape_alias env funct.mod_type with
+ Mty_functor(param, mty_param, mty_res) as mty_functor ->
+ let generative, mty_param =
+ (mty_param = None, Btype.default_mty mty_param) in
+ if generative then begin
+ if sarg.pmod_desc <> Pmod_structure [] then
+ raise (Error (sfunct.pmod_loc, env, Apply_generative));
+ if funct_body && Mtype.contains_type env funct.mod_type then
+ raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body));
+ end;
+ let coercion =
+ try
+ Includemod.modtypes env arg.mod_type mty_param
+ with Includemod.Error msg ->
+ raise(Error(sarg.pmod_loc, env, Not_included msg)) in
+ let mty_appl =
+ match path with
+ Some path ->
+ Subst.modtype (Subst.add_module param path Subst.identity)
+ mty_res
+ | None ->
+ if generative then mty_res else
+ try
+ Mtype.nondep_supertype
+ (Env.add_module ~arg:true param arg.mod_type env)
+ param mty_res
+ with Not_found ->
+ raise(Error(smod.pmod_loc, env,
+ Cannot_eliminate_dependency mty_functor))
+ in
+ rm { mod_desc = Tmod_apply(funct, arg, coercion);
+ mod_type = mty_appl;
+ mod_env = env;
+ mod_attributes = smod.pmod_attributes;
+ mod_loc = smod.pmod_loc }
+ | _ ->
+ raise(Error(sfunct.pmod_loc, env, Cannot_apply funct.mod_type))
+ end
+ | Pmod_constraint(sarg, smty) ->
+ let arg = type_module ~alias true funct_body anchor env sarg in
+ let mty = transl_modtype env smty in
+ rm {(wrap_constraint env arg mty.mty_type (Tmodtype_explicit mty)) with
+ mod_loc = smod.pmod_loc;
+ mod_attributes = smod.pmod_attributes;
+ }
+
+ | Pmod_unpack sexp ->
+ if !Clflags.principal then Ctype.begin_def ();
+ let exp = Typecore.type_exp env sexp in
+ if !Clflags.principal then begin
+ Ctype.end_def ();
+ Ctype.generalize_structure exp.exp_type
+ end;
+ let mty =
+ match Ctype.expand_head env exp.exp_type with
+ {desc = Tpackage (p, nl, tl)} ->
+ if List.exists (fun t -> Ctype.free_variables t <> []) tl then
+ raise (Error (smod.pmod_loc, env,
+ Incomplete_packed_module exp.exp_type));
+ if !Clflags.principal &&
+ not (Typecore.generalizable (Btype.generic_level-1) exp.exp_type)
+ then
+ Location.prerr_warning smod.pmod_loc
+ (Warnings.Not_principal "this module unpacking");
+ modtype_of_package env smod.pmod_loc p nl tl
+ | {desc = Tvar _} ->
+ raise (Typecore.Error
+ (smod.pmod_loc, env, Typecore.Cannot_infer_signature))
+ | _ ->
+ raise (Error(smod.pmod_loc, env, Not_a_packed_module exp.exp_type))
+ in
+ if funct_body && Mtype.contains_type env mty then
+ raise (Error (smod.pmod_loc, env, Not_allowed_in_functor_body));
+ rm { mod_desc = Tmod_unpack(exp, mty);
+ mod_type = mty;
+ mod_env = env;
+ mod_attributes = smod.pmod_attributes;
+ mod_loc = smod.pmod_loc }
+ | Pmod_extension ext ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+
+and type_structure ?(toplevel = false) funct_body anchor env sstr scope =
+ let names = new_names () in
+
+ let type_str_item env srem {pstr_loc = loc; pstr_desc = desc} =
+ match desc with
+ | Pstr_eval (sexpr, attrs) ->
+ let expr =
+ Typetexp.with_warning_attribute attrs (fun () ->
+ Typecore.type_expression env sexpr)
+ in
+ Tstr_eval (expr, attrs), [], env
+ | Pstr_value(rec_flag, sdefs) ->
+ let scope =
+ match rec_flag with
+ | Recursive ->
+ Some (Annot.Idef {scope with
+ Location.loc_start = loc.Location.loc_start})
+ | Nonrecursive ->
+ let start =
+ match srem with
+ | [] -> loc.Location.loc_end
+ | {pstr_loc = loc2} :: _ -> loc2.Location.loc_start
+ in
+ Some (Annot.Idef {scope with Location.loc_start = start})
+ in
+ let (defs, newenv) =
+ Typecore.type_binding env rec_flag sdefs scope in
+ (* Note: Env.find_value does not trigger the value_used event. Values
+ will be marked as being used during the signature inclusion test. *)
+ Tstr_value(rec_flag, defs),
+ List.map (fun id -> Sig_value(id, Env.find_value (Pident id) newenv))
+ (let_bound_idents defs),
+ newenv
+ | Pstr_primitive sdesc ->
+ let (desc, newenv) = Typedecl.transl_value_decl env loc sdesc in
+ Tstr_primitive desc, [Sig_value(desc.val_id, desc.val_val)], newenv
+ | Pstr_type (rec_flag, sdecls) ->
+ List.iter
+ (fun decl -> check_name check_type names decl.ptype_name)
+ sdecls;
+ let (decls, newenv) = Typedecl.transl_type_decl env rec_flag sdecls in
+ Tstr_type (rec_flag, decls),
+ map_rec_type_with_row_types ~rec_flag
+ (fun rs info -> Sig_type(info.typ_id, info.typ_type, rs))
+ decls [],
+ enrich_type_decls anchor decls env newenv
+ | Pstr_typext styext ->
+ List.iter
+ (fun pext -> check_name check_typext names pext.pext_name)
+ styext.ptyext_constructors;
+ let (tyext, newenv) =
+ Typedecl.transl_type_extension true env loc styext
+ in
+ (Tstr_typext tyext,
+ map_ext
+ (fun es ext -> Sig_typext(ext.ext_id, ext.ext_type, es))
+ tyext.tyext_constructors [],
+ newenv)
+ | Pstr_exception sext ->
+ check_name check_typext names sext.pext_name;
+ let (ext, newenv) = Typedecl.transl_exception env sext in
+ Tstr_exception ext,
+ [Sig_typext(ext.ext_id, ext.ext_type, Text_exception)],
+ newenv
+ | Pstr_module {pmb_name = name; pmb_expr = smodl; pmb_attributes = attrs;
+ pmb_loc;
+ } ->
+ check_name check_module names name;
+ let id = Ident.create name.txt in (* create early for PR#6752 *)
+ let modl =
+ Typetexp.with_warning_attribute attrs (fun () ->
+ type_module ~alias:true true funct_body
+ (anchor_submodule name.txt anchor) env smodl)
+ in
+ let md =
+ { md_type = enrich_module_type anchor name.txt modl.mod_type env;
+ md_attributes = attrs;
+ md_loc = pmb_loc;
+ }
+ in
+ let newenv = Env.enter_module_declaration id md env in
+ Tstr_module {mb_id=id; mb_name=name; mb_expr=modl;
+ mb_attributes=attrs; mb_loc=pmb_loc;
+ },
+ [Sig_module(id,
+ {md_type = modl.mod_type;
+ md_attributes = attrs;
+ md_loc = pmb_loc;
+ }, Trec_not)],
+ newenv
+ | Pstr_recmodule sbind ->
+ let sbind =
+ List.map
+ (function
+ | {pmb_name = name;
+ pmb_expr = {pmod_desc=Pmod_constraint(expr, typ)};
+ pmb_attributes = attrs;
+ pmb_loc = loc;
+ } ->
+ name, typ, expr, attrs, loc
+ | mb ->
+ raise (Error (mb.pmb_expr.pmod_loc, env,
+ Recursive_module_require_explicit_type))
+ )
+ sbind
+ in
+ List.iter
+ (fun (name, _, _, _, _) -> check_name check_module names name)
+ sbind;
+ let (decls, newenv) =
+ transl_recmodule_modtypes loc env
+ (List.map (fun (name, smty, smodl, attrs, loc) ->
+ {pmd_name=name; pmd_type=smty;
+ pmd_attributes=attrs; pmd_loc=loc}) sbind
+ ) in
+ let bindings1 =
+ List.map2
+ (fun {md_id=id; md_type=mty} (name, _, smodl, attrs, loc) ->
+ let modl =
+ Typetexp.with_warning_attribute attrs (fun () ->
+ type_module true funct_body (anchor_recmodule id anchor)
+ newenv smodl)
+ in
+ let mty' =
+ enrich_module_type anchor (Ident.name id) modl.mod_type newenv
+ in
+ (id, name, mty, modl, mty', attrs, loc))
+ decls sbind in
+ let newenv = (* allow aliasing recursive modules from outside *)
+ List.fold_left
+ (fun env md ->
+ let mdecl =
+ {
+ md_type = md.md_type.mty_type;
+ md_attributes = md.md_attributes;
+ md_loc = md.md_loc;
+ }
+ in
+ Env.add_module_declaration md.md_id mdecl env
+ )
+ env decls
+ in
+ let bindings2 =
+ check_recmodule_inclusion newenv bindings1 in
+ Tstr_recmodule bindings2,
+ map_rec (fun rs mb ->
+ Sig_module(mb.mb_id, {
+ md_type=mb.mb_expr.mod_type;
+ md_attributes=mb.mb_attributes;
+ md_loc=mb.mb_loc;
+ }, rs))
+ bindings2 [],
+ newenv
+ | Pstr_modtype pmtd ->
+ (* check that it is non-abstract *)
+ let newenv, mtd, sg =
+ Typetexp.with_warning_attribute pmtd.pmtd_attributes (fun () ->
+ transl_modtype_decl names env loc pmtd)
+ in
+ Tstr_modtype mtd, [sg], newenv
+ | Pstr_open sod ->
+ let (path, newenv, od) = type_open ~toplevel env sod in
+ Tstr_open od, [], newenv
+ | Pstr_class cl ->
+ List.iter
+ (fun {pci_name} -> check_name check_type names pci_name)
+ cl;
+ let (classes, new_env) = Typeclass.class_declarations env cl in
+ Tstr_class
+ (List.map (fun (_,_,_,_,_,_,_,_,_,_, m, c) -> (c, m)) classes),
+(* TODO: check with Jacques why this is here
+ Tstr_class_type
+ (List.map (fun (_,_, i, d, _,_,_,_,_,_,c) -> (i, c)) classes) ::
+ Tstr_type
+ (List.map (fun (_,_,_,_, i, d, _,_,_,_,_) -> (i, d)) classes) ::
+ Tstr_type
+ (List.map (fun (_,_,_,_,_,_, i, d, _,_,_) -> (i, d)) classes) ::
+*)
+ List.flatten
+ (map_rec
+ (fun rs (i, _, d, i', d', i'', d'', i''', d''', _, _, _) ->
+ [Sig_class(i, d, rs);
+ Sig_class_type(i', d', rs);
+ Sig_type(i'', d'', rs);
+ Sig_type(i''', d''', rs)])
+ classes []),
+ new_env
+ | Pstr_class_type cl ->
+ List.iter
+ (fun {pci_name} -> check_name check_type names pci_name)
+ cl;
+ let (classes, new_env) = Typeclass.class_type_declarations env cl in
+ Tstr_class_type
+ (List.map (fun (i, i_loc, d, _, _, _, _, c) ->
+ (i, i_loc, c)) classes),
+(* TODO: check with Jacques why this is here
+ Tstr_type
+ (List.map (fun (_, _, i, d, _, _) -> (i, d)) classes) ::
+ Tstr_type
+ (List.map (fun (_, _, _, _, i, d) -> (i, d)) classes) :: *)
+ List.flatten
+ (map_rec
+ (fun rs (i, _, d, i', d', i'', d'', _) ->
+ [Sig_class_type(i, d, rs);
+ Sig_type(i', d', rs);
+ Sig_type(i'', d'', rs)])
+ classes []),
+ new_env
+ | Pstr_include sincl ->
+ let smodl = sincl.pincl_mod in
+ let modl =
+ Typetexp.with_warning_attribute sincl.pincl_attributes (fun () ->
+ type_module true funct_body None env smodl)
+ in
+ (* Rename all identifiers bound by this signature to avoid clashes *)
+ let sg = Subst.signature Subst.identity
+ (extract_sig_open env smodl.pmod_loc modl.mod_type) in
+ List.iter (check_sig_item names loc) sg;
+ let new_env = Env.add_signature sg env in
+ let incl =
+ { incl_mod = modl;
+ incl_type = sg;
+ incl_attributes = sincl.pincl_attributes;
+ incl_loc = sincl.pincl_loc;
+ }
+ in
+ Tstr_include incl, sg, new_env
+ | Pstr_extension (ext, _attrs) ->
+ raise (Error_forward (Typetexp.error_of_extension ext))
+ | Pstr_attribute x ->
+ Typetexp.warning_attribute [x];
+ Tstr_attribute x, [], env
+ in
+ let rec type_struct env sstr =
+ Ctype.init_def(Ident.current_time());
+ match sstr with
+ | [] -> ([], [], env)
+ | pstr :: srem ->
+ let previous_saved_types = Cmt_format.get_saved_types () in
+ let desc, sg, new_env = type_str_item env srem pstr in
+ let str = { str_desc = desc; str_loc = pstr.pstr_loc; str_env = env } in
+ Cmt_format.set_saved_types (Cmt_format.Partial_structure_item str
+ :: previous_saved_types);
+ let (str_rem, sig_rem, final_env) = type_struct new_env srem in
+ (str :: str_rem, sg @ sig_rem, final_env)
+ in
+ if !Clflags.annotations then
+ (* moved to genannot *)
+ List.iter (function {pstr_loc = l} -> Stypes.record_phrase l) sstr;
+ let previous_saved_types = Cmt_format.get_saved_types () in
+ Typetexp.warning_enter_scope ();
+ let (items, sg, final_env) = type_struct env sstr in
+ let str = { str_items = items; str_type = sg; str_final_env = final_env } in
+ Typetexp.warning_leave_scope ();
+ Cmt_format.set_saved_types
+ (Cmt_format.Partial_structure str :: previous_saved_types);
+ str, sg, final_env
+
+let type_toplevel_phrase env s =
+ Env.reset_required_globals ();
+ type_structure ~toplevel:true false None env s Location.none
+let type_module_alias = type_module ~alias:true true false None
+let type_module = type_module true false None
+let type_structure = type_structure false None
+
+(* Normalize types in a signature *)
+
+let rec normalize_modtype env = function
+ Mty_ident p -> ()
+ | Mty_alias p -> ()
+ | Mty_signature sg -> normalize_signature env sg
+ | Mty_functor(id, param, body) -> normalize_modtype env body
+
+and normalize_signature env = List.iter (normalize_signature_item env)
+
+and normalize_signature_item env = function
+ Sig_value(id, desc) -> Ctype.normalize_type env desc.val_type
+ | Sig_module(id, md, _) -> normalize_modtype env md.md_type
+ | _ -> ()
+
+(* Extract the module type of a module expression *)
+
+let type_module_type_of env smod =
+ let tmty =
+ match smod.pmod_desc with
+ | Pmod_ident lid -> (* turn off strengthening in this case *)
+ let path, md = Typetexp.find_module env smod.pmod_loc lid.txt in
+ rm { mod_desc = Tmod_ident (path, lid);
+ mod_type = md.md_type;
+ mod_env = env;
+ mod_attributes = smod.pmod_attributes;
+ mod_loc = smod.pmod_loc }
+ | _ -> type_module env smod in
+ let mty = tmty.mod_type in
+ (* PR#6307: expand aliases at root and submodules *)
+ let mty = Mtype.remove_aliases env mty in
+ (* PR#5036: must not contain non-generalized type variables *)
+ if not (closed_modtype env mty) then
+ raise(Error(smod.pmod_loc, env, Non_generalizable_module mty));
+ tmty, mty
+
+(* For Typecore *)
+
+let rec get_manifest_types = function
+ [] -> []
+ | Sig_type (id, {type_params=[]; type_manifest=Some ty}, _) :: rem ->
+ (Ident.name id, ty) :: get_manifest_types rem
+ | _ :: rem -> get_manifest_types rem
+
+let type_package env m p nl tl =
+ (* Same as Pexp_letmodule *)
+ (* remember original level *)
+ let lv = Ctype.get_current_level () in
+ Ctype.begin_def ();
+ Ident.set_current_time lv;
+ let context = Typetexp.narrow () in
+ let modl = type_module env m in
+ Ctype.init_def(Ident.current_time());
+ Typetexp.widen context;
+ let (mp, env) =
+ match modl.mod_desc with
+ Tmod_ident (mp,_) -> (mp, env)
+ | Tmod_constraint ({mod_desc=Tmod_ident (mp,_)}, mty, Tmodtype_implicit, _)
+ -> (mp, env) (* PR#6982 *)
+ | _ ->
+ let (id, new_env) = Env.enter_module ~arg:true "%M" modl.mod_type env in
+ (Pident id, new_env)
+ in
+ let rec mkpath mp = function
+ | Lident name -> Pdot(mp, name, nopos)
+ | Ldot (m, name) -> Pdot(mkpath mp m, name, nopos)
+ | _ -> assert false
+ in
+ let tl' =
+ List.map
+ (fun name -> Btype.newgenty (Tconstr (mkpath mp name,[],ref Mnil)))
+ nl in
+ (* go back to original level *)
+ Ctype.end_def ();
+ if nl = [] then
+ (wrap_constraint env modl (Mty_ident p) Tmodtype_implicit, [])
+ else let mty = modtype_of_package env modl.mod_loc p nl tl' in
+ List.iter2
+ (fun n ty ->
+ try Ctype.unify env ty (Ctype.newvar ())
+ with Ctype.Unify _ ->
+ raise (Error(m.pmod_loc, env, Scoping_pack (n,ty))))
+ nl tl';
+ (wrap_constraint env modl mty Tmodtype_implicit, tl')
+
+(* Fill in the forward declarations *)
+let () =
+ Typecore.type_module := type_module_alias;
+ Typetexp.transl_modtype_longident := transl_modtype_longident;
+ Typetexp.transl_modtype := transl_modtype;
+ Typecore.type_open := type_open_ ?toplevel:None;
+ Typecore.type_package := type_package;
+ type_module_type_of_fwd := type_module_type_of
+
+
+(* Typecheck an implementation file *)
+
+let type_implementation sourcefile outputprefix modulename initial_env ast =
+ Cmt_format.clear ();
+ try
+ Typecore.reset_delayed_checks ();
+ Env.reset_required_globals ();
+ begin
+ let map = Typetexp.emit_external_warnings in
+ ignore (map.Ast_mapper.structure map ast)
+ end;
+
+ let (str, sg, finalenv) =
+ type_structure initial_env ast (Location.in_file sourcefile) in
+ let simple_sg = simplify_signature sg in
+ if !Clflags.print_types then begin
+ Printtyp.wrap_printing_env initial_env
+ (fun () -> fprintf std_formatter "%a@." Printtyp.signature simple_sg);
+ (str, Tcoerce_none) (* result is ignored by Compile.implementation *)
+ end else begin
+ let sourceintf =
+ Misc.chop_extension_if_any sourcefile ^ !Config.interface_suffix in
+ if Sys.file_exists sourceintf then begin
+ let intf_file =
+ try
+ find_in_path_uncap !Config.load_path (modulename ^ ".cmi")
+ with Not_found ->
+ raise(Error(Location.in_file sourcefile, Env.empty,
+ Interface_not_compiled sourceintf)) in
+ let dclsig = Env.read_signature modulename intf_file in
+ let coercion =
+ Includemod.compunit initial_env sourcefile sg intf_file dclsig in
+ Typecore.force_delayed_checks ();
+ (* It is important to run these checks after the inclusion test above,
+ so that value declarations which are not used internally but exported
+ are not reported as being unused. *)
+ Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename
+ (Cmt_format.Implementation str) (Some sourcefile) initial_env None;
+ (str, coercion)
+ end else begin
+ check_nongen_schemes finalenv sg;
+ normalize_signature finalenv simple_sg;
+ let coercion =
+ Includemod.compunit initial_env sourcefile sg
+ "(inferred signature)" simple_sg in
+ Typecore.force_delayed_checks ();
+ (* See comment above. Here the target signature contains all
+ the value being exported. We can still capture unused
+ declarations like "let x = true;; let x = 1;;", because in this
+ case, the inferred signature contains only the last declaration. *)
+ if not !Clflags.dont_write_files then begin
+ let sg =
+ Env.save_signature simple_sg modulename (outputprefix ^ ".cmi") in
+ Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename
+ (Cmt_format.Implementation str)
+ (Some sourcefile) initial_env (Some sg);
+ end;
+ (str, coercion)
+ end
+ end
+ with e ->
+ Cmt_format.save_cmt (outputprefix ^ ".cmt") modulename
+ (Cmt_format.Partial_implementation
+ (Array.of_list (Cmt_format.get_saved_types ())))
+ (Some sourcefile) initial_env None;
+ raise e
+
+
+let save_signature modname tsg outputprefix source_file initial_env cmi =
+ Cmt_format.save_cmt (outputprefix ^ ".cmti") modname
+ (Cmt_format.Interface tsg) (Some source_file) initial_env (Some cmi)
+
+let type_interface env ast =
+ begin
+ let map = Typetexp.emit_external_warnings in
+ ignore (map.Ast_mapper.signature map ast)
+ end;
+ transl_signature env ast
+
+(* "Packaging" of several compilation units into one unit
+ having them as sub-modules. *)
+
+let rec package_signatures subst = function
+ [] -> []
+ | (name, sg) :: rem ->
+ let sg' = Subst.signature subst sg in
+ let oldid = Ident.create_persistent name
+ and newid = Ident.create name in
+ Sig_module(newid, {md_type=Mty_signature sg';
+ md_attributes=[];
+ md_loc=Location.none;
+ },
+ Trec_not) ::
+ package_signatures (Subst.add_module oldid (Pident newid) subst) rem
+
+let package_units initial_env objfiles cmifile modulename =
+ (* Read the signatures of the units *)
+ let units =
+ List.map
+ (fun f ->
+ let pref = chop_extensions f in
+ let modname = String.capitalize_ascii(Filename.basename pref) in
+ let sg = Env.read_signature modname (pref ^ ".cmi") in
+ if Filename.check_suffix f ".cmi" &&
+ not(Mtype.no_code_needed_sig Env.initial_safe_string sg)
+ then raise(Error(Location.none, Env.empty,
+ Implementation_is_required f));
+ (modname, Env.read_signature modname (pref ^ ".cmi")))
+ objfiles in
+ (* Compute signature of packaged unit *)
+ Ident.reinit();
+ let sg = package_signatures Subst.identity units in
+ (* See if explicit interface is provided *)
+ let prefix = chop_extension_if_any cmifile in
+ let mlifile = prefix ^ !Config.interface_suffix in
+ if Sys.file_exists mlifile then begin
+ if not (Sys.file_exists cmifile) then begin
+ raise(Error(Location.in_file mlifile, Env.empty,
+ Interface_not_compiled mlifile))
+ end;
+ let dclsig = Env.read_signature modulename cmifile in
+ Cmt_format.save_cmt (prefix ^ ".cmt") modulename
+ (Cmt_format.Packed (sg, objfiles)) None initial_env None ;
+ Includemod.compunit initial_env "(obtained by packing)" sg mlifile dclsig
+ end else begin
+ (* Determine imports *)
+ let unit_names = List.map fst units in
+ let imports =
+ List.filter
+ (fun (name, crc) -> not (List.mem name unit_names))
+ (Env.imports()) in
+ (* Write packaged signature *)
+ if not !Clflags.dont_write_files then begin
+ let sg =
+ Env.save_signature_with_imports sg modulename
+ (prefix ^ ".cmi") imports in
+ Cmt_format.save_cmt (prefix ^ ".cmt") modulename
+ (Cmt_format.Packed (sg, objfiles)) None initial_env (Some sg)
+ end;
+ Tcoerce_none
+ end
+
+(* Error report *)
+
+open Printtyp
+
+let report_error ppf = function
+ Cannot_apply mty ->
+ fprintf ppf
+ "@[This module is not a functor; it has type@ %a@]" modtype mty
+ | Not_included errs ->
+ fprintf ppf
+ "@[<v>Signature mismatch:@ %a@]" Includemod.report_error errs
+ | Cannot_eliminate_dependency mty ->
+ fprintf ppf
+ "@[This functor has type@ %a@ \
+ The parameter cannot be eliminated in the result type.@ \
+ Please bind the argument to a module identifier.@]" modtype mty
+ | Signature_expected -> fprintf ppf "This module type is not a signature"
+ | Structure_expected mty ->
+ fprintf ppf
+ "@[This module is not a structure; it has type@ %a" modtype mty
+ | With_no_component lid ->
+ fprintf ppf
+ "@[The signature constrained by `with' has no component named %a@]"
+ longident lid
+ | With_mismatch(lid, explanation) ->
+ fprintf ppf
+ "@[<v>\
+ @[In this `with' constraint, the new definition of %a@ \
+ does not match its original definition@ \
+ in the constrained signature:@]@ \
+ %a@]"
+ longident lid Includemod.report_error explanation
+ | Repeated_name(kind, name) ->
+ fprintf ppf
+ "@[Multiple definition of the %s name %s.@ \
+ Names must be unique in a given structure or signature.@]" kind name
+ | Non_generalizable typ ->
+ fprintf ppf
+ "@[The type of this expression,@ %a,@ \
+ contains type variables that cannot be generalized@]" type_scheme typ
+ | Non_generalizable_class (id, desc) ->
+ fprintf ppf
+ "@[The type of this class,@ %a,@ \
+ contains type variables that cannot be generalized@]"
+ (class_declaration id) desc
+ | Non_generalizable_module mty ->
+ fprintf ppf
+ "@[The type of this module,@ %a,@ \
+ contains type variables that cannot be generalized@]" modtype mty
+ | Implementation_is_required intf_name ->
+ fprintf ppf
+ "@[The interface %a@ declares values, not just types.@ \
+ An implementation must be provided.@]"
+ Location.print_filename intf_name
+ | Interface_not_compiled intf_name ->
+ fprintf ppf
+ "@[Could not find the .cmi file for interface@ %a.@]"
+ Location.print_filename intf_name
+ | Not_allowed_in_functor_body ->
+ fprintf ppf
+ "@[This expression creates fresh types.@ %s@]"
+ "It is not allowed inside applicative functors."
+ | With_need_typeconstr ->
+ fprintf ppf
+ "Only type constructors with identical parameters can be substituted."
+ | Not_a_packed_module ty ->
+ fprintf ppf
+ "This expression is not a packed module. It has type@ %a"
+ type_expr ty
+ | Incomplete_packed_module ty ->
+ fprintf ppf
+ "The type of this packed module contains variables:@ %a"
+ type_expr ty
+ | Scoping_pack (lid, ty) ->
+ fprintf ppf
+ "The type %a in this module cannot be exported.@ " longident lid;
+ fprintf ppf
+ "Its type contains local dependencies:@ %a" type_expr ty
+ | Recursive_module_require_explicit_type ->
+ fprintf ppf "Recursive modules require an explicit module type."
+ | Apply_generative ->
+ fprintf ppf "This is a generative functor. It can only be applied to ()"
+
+let report_error env ppf err =
+ Printtyp.wrap_printing_env env (fun () -> report_error ppf err)
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, env, err) ->
+ Some (Location.error_of_printer loc (report_error env) err)
+ | Error_forward err ->
+ Some err
+ | _ ->
+ None
+ )
diff --git a/typing/typemod.mli b/typing/typemod.mli
new file mode 100644
index 0000000000..25c1110006
--- /dev/null
+++ b/typing/typemod.mli
@@ -0,0 +1,77 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Type-checking of the module language *)
+
+open Types
+open Format
+
+val type_module:
+ Env.t -> Parsetree.module_expr -> Typedtree.module_expr
+val type_structure:
+ Env.t -> Parsetree.structure -> Location.t ->
+ Typedtree.structure * Types.signature * Env.t
+val type_toplevel_phrase:
+ Env.t -> Parsetree.structure ->
+ Typedtree.structure * Types.signature * Env.t
+val type_implementation:
+ string -> string -> string -> Env.t -> Parsetree.structure ->
+ Typedtree.structure * Typedtree.module_coercion
+val type_interface:
+ Env.t -> Parsetree.signature -> Typedtree.signature
+val transl_signature:
+ Env.t -> Parsetree.signature -> Typedtree.signature
+val check_nongen_schemes:
+ Env.t -> Types.signature -> unit
+val type_open_:
+ ?toplevel:bool -> Asttypes.override_flag ->
+ Env.t -> Location.t -> Longident.t Asttypes.loc -> Path.t * Env.t
+val modtype_of_package:
+ Env.t -> Location.t ->
+ Path.t -> Longident.t list -> type_expr list -> module_type
+val simplify_signature: signature -> signature
+
+val path_of_module : Typedtree.module_expr -> Path.t option
+
+val save_signature:
+ string -> Typedtree.signature -> string -> string ->
+ Env.t -> Types.signature_item list -> unit
+
+val package_units:
+ Env.t -> string list -> string -> string -> Typedtree.module_coercion
+
+type error =
+ Cannot_apply of module_type
+ | Not_included of Includemod.error list
+ | Cannot_eliminate_dependency of module_type
+ | Signature_expected
+ | Structure_expected of module_type
+ | With_no_component of Longident.t
+ | With_mismatch of Longident.t * Includemod.error list
+ | Repeated_name of string * string
+ | Non_generalizable of type_expr
+ | Non_generalizable_class of Ident.t * class_declaration
+ | Non_generalizable_module of module_type
+ | Implementation_is_required of string
+ | Interface_not_compiled of string
+ | Not_allowed_in_functor_body
+ | With_need_typeconstr
+ | Not_a_packed_module of type_expr
+ | Incomplete_packed_module of type_expr
+ | Scoping_pack of Longident.t * type_expr
+ | Recursive_module_require_explicit_type
+ | Apply_generative
+
+exception Error of Location.t * Env.t * error
+exception Error_forward of Location.error
+
+val report_error: Env.t -> formatter -> error -> unit
diff --git a/typing/types.ml b/typing/types.ml
new file mode 100644
index 0000000000..3fca839376
--- /dev/null
+++ b/typing/types.ml
@@ -0,0 +1,314 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Representation of types and declarations *)
+
+open Asttypes
+
+(* Type expressions for the core language *)
+
+type type_expr =
+ { mutable desc: type_desc;
+ mutable level: int;
+ mutable id: int }
+
+and type_desc =
+ Tvar of string option
+ | Tarrow of arg_label * type_expr * type_expr * commutable
+ | Ttuple of type_expr list
+ | Tconstr of Path.t * type_expr list * abbrev_memo ref
+ | Tobject of type_expr * (Path.t * type_expr list) option ref
+ | Tfield of string * field_kind * type_expr * type_expr
+ | Tnil
+ | Tlink of type_expr
+ | Tsubst of type_expr (* for copying *)
+ | Tvariant of row_desc
+ | Tunivar of string option
+ | Tpoly of type_expr * type_expr list
+ | Tpackage of Path.t * Longident.t list * type_expr list
+
+and row_desc =
+ { row_fields: (label * row_field) list;
+ row_more: type_expr;
+ row_bound: unit;
+ row_closed: bool;
+ row_fixed: bool;
+ row_name: (Path.t * type_expr list) option }
+
+and row_field =
+ Rpresent of type_expr option
+ | Reither of bool * type_expr list * bool * row_field option ref
+ (* 1st true denotes a constant constructor *)
+ (* 2nd true denotes a tag in a pattern matching, and
+ is erased later *)
+ | Rabsent
+
+and abbrev_memo =
+ Mnil
+ | Mcons of private_flag * Path.t * type_expr * type_expr * abbrev_memo
+ | Mlink of abbrev_memo ref
+
+and field_kind =
+ Fvar of field_kind option ref
+ | Fpresent
+ | Fabsent
+
+and commutable =
+ Cok
+ | Cunknown
+ | Clink of commutable ref
+
+module TypeOps = struct
+ type t = type_expr
+ let compare t1 t2 = t1.id - t2.id
+ let hash t = t.id
+ let equal t1 t2 = t1 == t2
+end
+
+(* Maps of methods and instance variables *)
+
+module OrderedString =
+ struct type t = string let compare (x:t) y = compare x y end
+module Meths = Map.Make(OrderedString)
+module Vars = Meths
+
+(* Value descriptions *)
+
+type value_description =
+ { val_type: type_expr; (* Type of the value *)
+ val_kind: value_kind;
+ val_loc: Location.t;
+ val_attributes: Parsetree.attributes;
+ }
+
+and value_kind =
+ Val_reg (* Regular value *)
+ | Val_prim of Primitive.description (* Primitive *)
+ | Val_ivar of mutable_flag * string (* Instance variable (mutable ?) *)
+ | Val_self of (Ident.t * type_expr) Meths.t ref *
+ (Ident.t * Asttypes.mutable_flag *
+ Asttypes.virtual_flag * type_expr) Vars.t ref *
+ string * type_expr
+ (* Self *)
+ | Val_anc of (string * Ident.t) list * string
+ (* Ancestor *)
+ | Val_unbound (* Unbound variable *)
+
+(* Variance *)
+
+module Variance = struct
+ type t = int
+ type f = May_pos | May_neg | May_weak | Inj | Pos | Neg | Inv
+ let single = function
+ | May_pos -> 1
+ | May_neg -> 2
+ | May_weak -> 4
+ | Inj -> 8
+ | Pos -> 16
+ | Neg -> 32
+ | Inv -> 64
+ let union v1 v2 = v1 lor v2
+ let inter v1 v2 = v1 land v2
+ let subset v1 v2 = (v1 land v2 = v1)
+ let set x b v =
+ if b then v lor single x else v land (lnot (single x))
+ let mem x = subset (single x)
+ let null = 0
+ let may_inv = 7
+ let full = 127
+ let covariant = single May_pos lor single Pos lor single Inj
+ let swap f1 f2 v =
+ let v' = set f1 (mem f2 v) v in set f2 (mem f1 v) v'
+ let conjugate v = swap May_pos May_neg (swap Pos Neg v)
+ let get_upper v = (mem May_pos v, mem May_neg v)
+ let get_lower v = (mem Pos v, mem Neg v, mem Inv v, mem Inj v)
+end
+
+(* Type definitions *)
+
+type type_declaration =
+ { type_params: type_expr list;
+ type_arity: int;
+ type_kind: type_kind;
+ type_private: private_flag;
+ type_manifest: type_expr option;
+ type_variance: Variance.t list;
+ type_newtype_level: (int * int) option;
+ type_loc: Location.t;
+ type_attributes: Parsetree.attributes;
+ }
+
+and type_kind =
+ Type_abstract
+ | Type_record of label_declaration list * record_representation
+ | Type_variant of constructor_declaration list
+ | Type_open
+
+and record_representation =
+ Record_regular (* All fields are boxed / tagged *)
+ | Record_float (* All fields are floats *)
+ | Record_inlined of int (* Inlined record *)
+ | Record_extension (* Inlined record under extension *)
+
+and label_declaration =
+ {
+ ld_id: Ident.t;
+ ld_mutable: mutable_flag;
+ ld_type: type_expr;
+ ld_loc: Location.t;
+ ld_attributes: Parsetree.attributes;
+ }
+
+and constructor_declaration =
+ {
+ cd_id: Ident.t;
+ cd_args: constructor_arguments;
+ cd_res: type_expr option;
+ cd_loc: Location.t;
+ cd_attributes: Parsetree.attributes;
+ }
+
+and constructor_arguments =
+ | Cstr_tuple of type_expr list
+ | Cstr_record of label_declaration list
+
+type extension_constructor =
+ { ext_type_path: Path.t;
+ ext_type_params: type_expr list;
+ ext_args: constructor_arguments;
+ ext_ret_type: type_expr option;
+ ext_private: private_flag;
+ ext_loc: Location.t;
+ ext_attributes: Parsetree.attributes; }
+
+and type_transparence =
+ Type_public (* unrestricted expansion *)
+ | Type_new (* "new" type *)
+ | Type_private (* private type *)
+
+(* Type expressions for the class language *)
+
+module Concr = Set.Make(OrderedString)
+
+type class_type =
+ Cty_constr of Path.t * type_expr list * class_type
+ | Cty_signature of class_signature
+ | Cty_arrow of arg_label * type_expr * class_type
+
+and class_signature =
+ { csig_self: type_expr;
+ csig_vars:
+ (Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t;
+ csig_concr: Concr.t;
+ csig_inher: (Path.t * type_expr list) list }
+
+type class_declaration =
+ { cty_params: type_expr list;
+ mutable cty_type: class_type;
+ cty_path: Path.t;
+ cty_new: type_expr option;
+ cty_variance: Variance.t list;
+ cty_loc: Location.t;
+ cty_attributes: Parsetree.attributes;
+ }
+
+type class_type_declaration =
+ { clty_params: type_expr list;
+ clty_type: class_type;
+ clty_path: Path.t;
+ clty_variance: Variance.t list;
+ clty_loc: Location.t;
+ clty_attributes: Parsetree.attributes;
+ }
+
+(* Type expressions for the module language *)
+
+type module_type =
+ Mty_ident of Path.t
+ | Mty_signature of signature
+ | Mty_functor of Ident.t * module_type option * module_type
+ | Mty_alias of Path.t
+
+and signature = signature_item list
+
+and signature_item =
+ Sig_value of Ident.t * value_description
+ | Sig_type of Ident.t * type_declaration * rec_status
+ | Sig_typext of Ident.t * extension_constructor * ext_status
+ | Sig_module of Ident.t * module_declaration * rec_status
+ | Sig_modtype of Ident.t * modtype_declaration
+ | Sig_class of Ident.t * class_declaration * rec_status
+ | Sig_class_type of Ident.t * class_type_declaration * rec_status
+
+and module_declaration =
+ {
+ md_type: module_type;
+ md_attributes: Parsetree.attributes;
+ md_loc: Location.t;
+ }
+
+and modtype_declaration =
+ {
+ mtd_type: module_type option; (* Nonte: abstract *)
+ mtd_attributes: Parsetree.attributes;
+ mtd_loc: Location.t;
+ }
+
+and rec_status =
+ Trec_not (* first in a nonrecursive group *)
+ | Trec_first (* first in a recursive group *)
+ | Trec_next (* not first in a recursive/nonrecursive group *)
+
+and ext_status =
+ Text_first (* first constructor of an extension *)
+ | Text_next (* not first constructor of an extension *)
+ | Text_exception (* an exception *)
+
+
+(* Constructor and record label descriptions inserted held in typing
+ environments *)
+
+type constructor_description =
+ { cstr_name: string; (* Constructor name *)
+ cstr_res: type_expr; (* Type of the result *)
+ cstr_existentials: type_expr list; (* list of existentials *)
+ cstr_args: type_expr list; (* Type of the arguments *)
+ cstr_arity: int; (* Number of arguments *)
+ cstr_tag: constructor_tag; (* Tag for heap blocks *)
+ cstr_consts: int; (* Number of constant constructors *)
+ cstr_nonconsts: int; (* Number of non-const constructors *)
+ cstr_normal: int; (* Number of non generalized constrs *)
+ cstr_generalized: bool; (* Constrained return type? *)
+ cstr_private: private_flag; (* Read-only constructor? *)
+ cstr_loc: Location.t;
+ cstr_attributes: Parsetree.attributes;
+ cstr_inlined: type_declaration option;
+ }
+
+and constructor_tag =
+ Cstr_constant of int (* Constant constructor (an int) *)
+ | Cstr_block of int (* Regular constructor (a block) *)
+ | Cstr_extension of Path.t * bool (* Extension constructor
+ true if a constant false if a block*)
+
+type label_description =
+ { lbl_name: string; (* Short name *)
+ lbl_res: type_expr; (* Type of the result *)
+ lbl_arg: type_expr; (* Type of the argument *)
+ lbl_mut: mutable_flag; (* Is this a mutable field? *)
+ lbl_pos: int; (* Position in block *)
+ lbl_all: label_description array; (* All the labels in this type *)
+ lbl_repres: record_representation; (* Representation for this record *)
+ lbl_private: private_flag; (* Read-only field? *)
+ lbl_loc: Location.t;
+ lbl_attributes: Parsetree.attributes;
+ }
diff --git a/typing/types.mli b/typing/types.mli
new file mode 100644
index 0000000000..84131ccda1
--- /dev/null
+++ b/typing/types.mli
@@ -0,0 +1,304 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Representation of types and declarations *)
+
+open Asttypes
+
+(* Type expressions for the core language *)
+
+type type_expr =
+ { mutable desc: type_desc;
+ mutable level: int;
+ mutable id: int }
+
+and type_desc =
+ Tvar of string option
+ | Tarrow of arg_label * type_expr * type_expr * commutable
+ | Ttuple of type_expr list
+ | Tconstr of Path.t * type_expr list * abbrev_memo ref
+ | Tobject of type_expr * (Path.t * type_expr list) option ref
+ | Tfield of string * field_kind * type_expr * type_expr
+ | Tnil
+ | Tlink of type_expr
+ | Tsubst of type_expr (* for copying *)
+ | Tvariant of row_desc
+ | Tunivar of string option
+ | Tpoly of type_expr * type_expr list
+ | Tpackage of Path.t * Longident.t list * type_expr list
+
+and row_desc =
+ { row_fields: (label * row_field) list;
+ row_more: type_expr;
+ row_bound: unit; (* kept for compatibility *)
+ row_closed: bool;
+ row_fixed: bool;
+ row_name: (Path.t * type_expr list) option }
+
+and row_field =
+ Rpresent of type_expr option
+ | Reither of bool * type_expr list * bool * row_field option ref
+ (* 1st true denotes a constant constructor *)
+ (* 2nd true denotes a tag in a pattern matching, and
+ is erased later *)
+ | Rabsent
+
+and abbrev_memo =
+ Mnil
+ | Mcons of private_flag * Path.t * type_expr * type_expr * abbrev_memo
+ | Mlink of abbrev_memo ref
+
+and field_kind =
+ Fvar of field_kind option ref
+ | Fpresent
+ | Fabsent
+
+and commutable =
+ Cok
+ | Cunknown
+ | Clink of commutable ref
+
+module TypeOps : sig
+ type t = type_expr
+ val compare : t -> t -> int
+ val equal : t -> t -> bool
+ val hash : t -> int
+end
+
+(* Maps of methods and instance variables *)
+
+module Meths : Map.S with type key = string
+module Vars : Map.S with type key = string
+
+(* Value descriptions *)
+
+type value_description =
+ { val_type: type_expr; (* Type of the value *)
+ val_kind: value_kind;
+ val_loc: Location.t;
+ val_attributes: Parsetree.attributes;
+ }
+
+and value_kind =
+ Val_reg (* Regular value *)
+ | Val_prim of Primitive.description (* Primitive *)
+ | Val_ivar of mutable_flag * string (* Instance variable (mutable ?) *)
+ | Val_self of (Ident.t * type_expr) Meths.t ref *
+ (Ident.t * mutable_flag * virtual_flag * type_expr) Vars.t ref *
+ string * type_expr
+ (* Self *)
+ | Val_anc of (string * Ident.t) list * string
+ (* Ancestor *)
+ | Val_unbound (* Unbound variable *)
+
+(* Variance *)
+
+module Variance : sig
+ type t
+ type f = May_pos | May_neg | May_weak | Inj | Pos | Neg | Inv
+ val null : t (* no occurence *)
+ val full : t (* strictly invariant *)
+ val covariant : t (* strictly covariant *)
+ val may_inv : t (* maybe invariant *)
+ val union : t -> t -> t
+ val inter : t -> t -> t
+ val subset : t -> t -> bool
+ val set : f -> bool -> t -> t
+ val mem : f -> t -> bool
+ val conjugate : t -> t (* exchange positive and negative *)
+ val get_upper : t -> bool * bool (* may_pos, may_neg *)
+ val get_lower : t -> bool * bool * bool * bool (* pos, neg, inv, inj *)
+end
+
+(* Type definitions *)
+
+type type_declaration =
+ { type_params: type_expr list;
+ type_arity: int;
+ type_kind: type_kind;
+ type_private: private_flag;
+ type_manifest: type_expr option;
+ type_variance: Variance.t list;
+ (* covariant, contravariant, weakly contravariant, injective *)
+ type_newtype_level: (int * int) option;
+ (* definition level * expansion level *)
+ type_loc: Location.t;
+ type_attributes: Parsetree.attributes;
+ }
+
+and type_kind =
+ Type_abstract
+ | Type_record of label_declaration list * record_representation
+ | Type_variant of constructor_declaration list
+ | Type_open
+
+and record_representation =
+ Record_regular (* All fields are boxed / tagged *)
+ | Record_float (* All fields are floats *)
+ | Record_inlined of int (* Inlined record *)
+ | Record_extension (* Inlined record under extension *)
+
+and label_declaration =
+ {
+ ld_id: Ident.t;
+ ld_mutable: mutable_flag;
+ ld_type: type_expr;
+ ld_loc: Location.t;
+ ld_attributes: Parsetree.attributes;
+ }
+
+and constructor_declaration =
+ {
+ cd_id: Ident.t;
+ cd_args: constructor_arguments;
+ cd_res: type_expr option;
+ cd_loc: Location.t;
+ cd_attributes: Parsetree.attributes;
+ }
+
+and constructor_arguments =
+ | Cstr_tuple of type_expr list
+ | Cstr_record of label_declaration list
+
+type extension_constructor =
+ {
+ ext_type_path: Path.t;
+ ext_type_params: type_expr list;
+ ext_args: constructor_arguments;
+ ext_ret_type: type_expr option;
+ ext_private: private_flag;
+ ext_loc: Location.t;
+ ext_attributes: Parsetree.attributes;
+ }
+
+and type_transparence =
+ Type_public (* unrestricted expansion *)
+ | Type_new (* "new" type *)
+ | Type_private (* private type *)
+
+(* Type expressions for the class language *)
+
+module Concr : Set.S with type elt = string
+
+type class_type =
+ Cty_constr of Path.t * type_expr list * class_type
+ | Cty_signature of class_signature
+ | Cty_arrow of arg_label * type_expr * class_type
+
+and class_signature =
+ { csig_self: type_expr;
+ csig_vars:
+ (Asttypes.mutable_flag * Asttypes.virtual_flag * type_expr) Vars.t;
+ csig_concr: Concr.t;
+ csig_inher: (Path.t * type_expr list) list }
+
+type class_declaration =
+ { cty_params: type_expr list;
+ mutable cty_type: class_type;
+ cty_path: Path.t;
+ cty_new: type_expr option;
+ cty_variance: Variance.t list;
+ cty_loc: Location.t;
+ cty_attributes: Parsetree.attributes;
+ }
+
+type class_type_declaration =
+ { clty_params: type_expr list;
+ clty_type: class_type;
+ clty_path: Path.t;
+ clty_variance: Variance.t list;
+ clty_loc: Location.t;
+ clty_attributes: Parsetree.attributes;
+ }
+
+(* Type expressions for the module language *)
+
+type module_type =
+ Mty_ident of Path.t
+ | Mty_signature of signature
+ | Mty_functor of Ident.t * module_type option * module_type
+ | Mty_alias of Path.t
+
+and signature = signature_item list
+
+and signature_item =
+ Sig_value of Ident.t * value_description
+ | Sig_type of Ident.t * type_declaration * rec_status
+ | Sig_typext of Ident.t * extension_constructor * ext_status
+ | Sig_module of Ident.t * module_declaration * rec_status
+ | Sig_modtype of Ident.t * modtype_declaration
+ | Sig_class of Ident.t * class_declaration * rec_status
+ | Sig_class_type of Ident.t * class_type_declaration * rec_status
+
+and module_declaration =
+ {
+ md_type: module_type;
+ md_attributes: Parsetree.attributes;
+ md_loc: Location.t;
+ }
+
+and modtype_declaration =
+ {
+ mtd_type: module_type option; (* None: abstract *)
+ mtd_attributes: Parsetree.attributes;
+ mtd_loc: Location.t;
+ }
+
+and rec_status =
+ Trec_not (* first in a nonrecursive group *)
+ | Trec_first (* first in a recursive group *)
+ | Trec_next (* not first in a recursive/nonrecursive group *)
+
+and ext_status =
+ Text_first (* first constructor in an extension *)
+ | Text_next (* not first constructor in an extension *)
+ | Text_exception
+
+
+(* Constructor and record label descriptions inserted held in typing
+ environments *)
+
+type constructor_description =
+ { cstr_name: string; (* Constructor name *)
+ cstr_res: type_expr; (* Type of the result *)
+ cstr_existentials: type_expr list; (* list of existentials *)
+ cstr_args: type_expr list; (* Type of the arguments *)
+ cstr_arity: int; (* Number of arguments *)
+ cstr_tag: constructor_tag; (* Tag for heap blocks *)
+ cstr_consts: int; (* Number of constant constructors *)
+ cstr_nonconsts: int; (* Number of non-const constructors *)
+ cstr_normal: int; (* Number of non generalized constrs *)
+ cstr_generalized: bool; (* Constrained return type? *)
+ cstr_private: private_flag; (* Read-only constructor? *)
+ cstr_loc: Location.t;
+ cstr_attributes: Parsetree.attributes;
+ cstr_inlined: type_declaration option;
+ }
+
+and constructor_tag =
+ Cstr_constant of int (* Constant constructor (an int) *)
+ | Cstr_block of int (* Regular constructor (a block) *)
+ | Cstr_extension of Path.t * bool (* Extension constructor
+ true if a constant false if a block*)
+
+type label_description =
+ { lbl_name: string; (* Short name *)
+ lbl_res: type_expr; (* Type of the result *)
+ lbl_arg: type_expr; (* Type of the argument *)
+ lbl_mut: mutable_flag; (* Is this a mutable field? *)
+ lbl_pos: int; (* Position in block *)
+ lbl_all: label_description array; (* All the labels in this type *)
+ lbl_repres: record_representation; (* Representation for this record *)
+ lbl_private: private_flag; (* Read-only field? *)
+ lbl_loc: Location.t;
+ lbl_attributes: Parsetree.attributes;
+ }
diff --git a/typing/typetexp.ml b/typing/typetexp.ml
new file mode 100644
index 0000000000..c3dbe6d9c1
--- /dev/null
+++ b/typing/typetexp.ml
@@ -0,0 +1,1010 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* typetexp.ml,v 1.34.4.9 2002/01/07 08:39:16 garrigue Exp *)
+
+(* Typechecking of type expressions for the core language *)
+
+open Asttypes
+open Misc
+open Parsetree
+open Typedtree
+open Types
+open Ctype
+
+exception Already_bound
+
+type error =
+ Unbound_type_variable of string
+ | Unbound_type_constructor of Longident.t
+ | Unbound_type_constructor_2 of Path.t
+ | Type_arity_mismatch of Longident.t * int * int
+ | Bound_type_variable of string
+ | Recursive_type
+ | Unbound_row_variable of Longident.t
+ | Type_mismatch of (type_expr * type_expr) list
+ | Alias_type_mismatch of (type_expr * type_expr) list
+ | Present_has_conjunction of string
+ | Present_has_no_type of string
+ | Constructor_mismatch of type_expr * type_expr
+ | Not_a_variant of type_expr
+ | Variant_tags of string * string
+ | Invalid_variable_name of string
+ | Cannot_quantify of string * type_expr
+ | Multiple_constraints_on_type of Longident.t
+ | Repeated_method_label of string
+ | Unbound_value of Longident.t
+ | Unbound_constructor of Longident.t
+ | Unbound_label of Longident.t
+ | Unbound_module of Longident.t
+ | Unbound_class of Longident.t
+ | Unbound_modtype of Longident.t
+ | Unbound_cltype of Longident.t
+ | Ill_typed_functor_application of Longident.t
+ | Illegal_reference_to_recursive_module
+ | Access_functor_as_structure of Longident.t
+
+exception Error of Location.t * Env.t * error
+exception Error_forward of Location.error
+
+let string_of_cst = function
+ | Const_string(s, _) -> Some s
+ | _ -> None
+
+let string_of_payload = function
+ | PStr[{pstr_desc=Pstr_eval({pexp_desc=Pexp_constant c},_)}] ->
+ string_of_cst c
+ | _ -> None
+
+let rec error_of_extension ext =
+ match ext with
+ | ({txt = ("ocaml.error"|"error") as txt; loc}, p) ->
+ let rec sub_from inner =
+ match inner with
+ | {pstr_desc=Pstr_extension (ext, _)} :: rest ->
+ error_of_extension ext :: sub_from rest
+ | {pstr_loc} :: rest ->
+ (Location.errorf ~loc
+ "Invalid syntax for sub-error of extension '%s'." txt) ::
+ sub_from rest
+ | [] -> []
+ in
+ begin match p with
+ | PStr({pstr_desc=Pstr_eval
+ ({pexp_desc=Pexp_constant(Const_string(msg,_))}, _)}::
+ {pstr_desc=Pstr_eval
+ ({pexp_desc=Pexp_constant(Const_string(if_highlight,_))}, _)}::
+ inner) ->
+ Location.error ~loc ~if_highlight ~sub:(sub_from inner) msg
+ | PStr({pstr_desc=Pstr_eval
+ ({pexp_desc=Pexp_constant(Const_string(msg,_))}, _)}::inner) ->
+ Location.error ~loc ~sub:(sub_from inner) msg
+ | _ -> Location.errorf ~loc "Invalid syntax for extension '%s'." txt
+ end
+ | ({txt; loc}, _) ->
+ Location.errorf ~loc "Uninterpreted extension '%s'." txt
+
+let check_deprecated loc attrs s =
+ List.iter
+ (function
+ | ({txt = "ocaml.deprecated"|"deprecated"; _}, p) ->
+ begin match string_of_payload p with
+ | Some txt ->
+ Location.prerr_warning loc (Warnings.Deprecated (s ^ "\n" ^ txt))
+ | None ->
+ Location.prerr_warning loc (Warnings.Deprecated s)
+ end
+ | _ -> ())
+ attrs
+
+let emit_external_warnings =
+ (* Note: this is run as a preliminary pass when type-checking an
+ interface or implementation. This allows to cover all kinds of
+ attributes, but the drawback is that it doesn't take local
+ configuration of warnings (with '@@warning'/'@@warnerror'
+ attributes) into account. We should rather check for
+ 'ppwarning' attributes during the actual type-checking, making
+ sure to cover all contexts (easier and more ugly alternative:
+ duplicate here the logic which control warnings locally). *)
+ let open Ast_mapper in
+ {
+ default_mapper with
+ attribute = (fun _ a ->
+ begin match a with
+ | {txt="ocaml.ppwarning"|"ppwarning"},
+ PStr[{pstr_desc=Pstr_eval({pexp_desc=Pexp_constant
+ (Const_string (s, _))},_);
+ pstr_loc}] ->
+ Location.prerr_warning pstr_loc (Warnings.Preprocessor s)
+ | _ -> ()
+ end;
+ a
+ )
+ }
+
+
+let warning_scope = ref []
+
+let warning_enter_scope () =
+ warning_scope := (Warnings.backup ()) :: !warning_scope
+let warning_leave_scope () =
+ match !warning_scope with
+ | [] -> assert false
+ | hd :: tl ->
+ Warnings.restore hd;
+ warning_scope := tl
+
+let warning_attribute attrs =
+ let process loc txt errflag payload =
+ match string_of_payload payload with
+ | Some s ->
+ begin try Warnings.parse_options errflag s
+ with Arg.Bad _ ->
+ Location.prerr_warning loc
+ (Warnings.Attribute_payload
+ (txt, "Ill-formed list of warnings"))
+ end
+ | None ->
+ Location.prerr_warning loc
+ (Warnings.Attribute_payload
+ (txt, "A single string literal is expected"))
+ in
+ List.iter
+ (function
+ | ({txt = ("ocaml.warning"|"warning") as txt; loc}, payload) ->
+ process loc txt false payload
+ | ({txt = ("ocaml.warnerror"|"warnerror") as txt; loc}, payload) ->
+ process loc txt true payload
+ | _ ->
+ ()
+ )
+ attrs
+
+let with_warning_attribute attrs f =
+ try
+ warning_enter_scope ();
+ warning_attribute attrs;
+ let ret = f () in
+ warning_leave_scope ();
+ ret
+ with exn ->
+ warning_leave_scope ();
+ raise exn
+
+type variable_context = int * (string, type_expr) Tbl.t
+
+(* Local definitions *)
+
+let instance_list = Ctype.instance_list Env.empty
+
+(* Narrowing unbound identifier errors. *)
+
+let rec narrow_unbound_lid_error : 'a. _ -> _ -> _ -> _ -> 'a =
+ fun env loc lid make_error ->
+ let check_module mlid =
+ try ignore (Env.lookup_module true mlid env) with
+ | Not_found ->
+ narrow_unbound_lid_error env loc mlid (fun lid -> Unbound_module lid)
+ | Env.Recmodule ->
+ raise (Error (loc, env, Illegal_reference_to_recursive_module))
+ in
+ begin match lid with
+ | Longident.Lident _ -> ()
+ | Longident.Ldot (mlid, _) ->
+ check_module mlid;
+ let md = Env.find_module (Env.lookup_module true mlid env) env in
+ begin match Env.scrape_alias env md.md_type with
+ Mty_functor _ ->
+ raise (Error (loc, env, Access_functor_as_structure mlid))
+ | _ -> ()
+ end
+ | Longident.Lapply (flid, mlid) ->
+ check_module flid;
+ check_module mlid;
+ raise (Error (loc, env, Ill_typed_functor_application lid))
+ end;
+ raise (Error (loc, env, make_error lid))
+
+let find_component lookup make_error env loc lid =
+ try
+ match lid with
+ | Longident.Ldot (Longident.Lident "*predef*", s) ->
+ lookup (Longident.Lident s) Env.initial_safe_string
+ | _ -> lookup lid env
+ with Not_found ->
+ narrow_unbound_lid_error env loc lid make_error
+ | Env.Recmodule ->
+ raise (Error (loc, env, Illegal_reference_to_recursive_module))
+
+let find_type env loc lid =
+ let (path, decl) as r =
+ find_component Env.lookup_type (fun lid -> Unbound_type_constructor lid)
+ env loc lid
+ in
+ check_deprecated loc decl.type_attributes (Path.name path);
+ r
+
+let find_constructor =
+ find_component Env.lookup_constructor (fun lid -> Unbound_constructor lid)
+let find_all_constructors =
+ find_component Env.lookup_all_constructors
+ (fun lid -> Unbound_constructor lid)
+let find_label =
+ find_component Env.lookup_label (fun lid -> Unbound_label lid)
+let find_all_labels =
+ find_component Env.lookup_all_labels (fun lid -> Unbound_label lid)
+
+let find_class env loc lid =
+ let (path, decl) as r =
+ find_component Env.lookup_class (fun lid -> Unbound_class lid) env loc lid
+ in
+ check_deprecated loc decl.cty_attributes (Path.name path);
+ r
+
+let find_value env loc lid =
+ Env.check_value_name (Longident.last lid) loc;
+ let (path, decl) as r =
+ find_component Env.lookup_value (fun lid -> Unbound_value lid) env loc lid
+ in
+ check_deprecated loc decl.val_attributes (Path.name path);
+ r
+
+let lookup_module ?(load=false) env loc lid =
+ let (path, decl) as r =
+ find_component (fun lid env -> (Env.lookup_module ~load lid env, ()))
+ (fun lid -> Unbound_module lid) env loc lid
+ in path
+
+let find_module env loc lid =
+ let path = lookup_module ~load:true env loc lid in
+ let decl = Env.find_module path env in
+ check_deprecated loc decl.md_attributes (Path.name path);
+ (path, decl)
+
+let find_modtype env loc lid =
+ let (path, decl) as r =
+ find_component Env.lookup_modtype (fun lid -> Unbound_modtype lid)
+ env loc lid
+ in
+ check_deprecated loc decl.mtd_attributes (Path.name path);
+ r
+
+let find_class_type env loc lid =
+ let (path, decl) as r =
+ find_component Env.lookup_cltype (fun lid -> Unbound_cltype lid)
+ env loc lid
+ in
+ check_deprecated loc decl.clty_attributes (Path.name path);
+ r
+
+let unbound_constructor_error env lid =
+ narrow_unbound_lid_error env lid.loc lid.txt
+ (fun lid -> Unbound_constructor lid)
+
+let unbound_label_error env lid =
+ narrow_unbound_lid_error env lid.loc lid.txt
+ (fun lid -> Unbound_label lid)
+
+(* Support for first-class modules. *)
+
+let transl_modtype_longident = ref (fun _ -> assert false)
+let transl_modtype = ref (fun _ -> assert false)
+
+let create_package_mty fake loc env (p, l) =
+ let l =
+ List.sort
+ (fun (s1, t1) (s2, t2) ->
+ if s1.txt = s2.txt then
+ raise (Error (loc, env, Multiple_constraints_on_type s1.txt));
+ compare s1.txt s2.txt)
+ l
+ in
+ l,
+ List.fold_left
+ (fun mty (s, t) ->
+ let d = {ptype_name = mkloc (Longident.last s.txt) s.loc;
+ ptype_params = [];
+ ptype_cstrs = [];
+ ptype_kind = Ptype_abstract;
+ ptype_private = Asttypes.Public;
+ ptype_manifest = if fake then None else Some t;
+ ptype_attributes = [];
+ ptype_loc = loc} in
+ Ast_helper.Mty.mk ~loc
+ (Pmty_with (mty, [ Pwith_type ({ txt = s.txt; loc }, d) ]))
+ )
+ (Ast_helper.Mty.mk ~loc (Pmty_ident p))
+ l
+
+(* Translation of type expressions *)
+
+let type_variables = ref (Tbl.empty : (string, type_expr) Tbl.t)
+let univars = ref ([] : (string * type_expr) list)
+let pre_univars = ref ([] : type_expr list)
+let used_variables = ref (Tbl.empty : (string, type_expr * Location.t) Tbl.t)
+
+let reset_type_variables () =
+ reset_global_level ();
+ Ctype.reset_reified_var_counter ();
+ type_variables := Tbl.empty
+
+let narrow () =
+ (increase_global_level (), !type_variables)
+
+let widen (gl, tv) =
+ restore_global_level gl;
+ type_variables := tv
+
+let strict_lowercase c = (c = '_' || c >= 'a' && c <= 'z')
+
+let validate_name = function
+ None -> None
+ | Some name as s ->
+ if name <> "" && strict_lowercase name.[0] then s else None
+
+let new_global_var ?name () =
+ new_global_var ?name:(validate_name name) ()
+let newvar ?name () =
+ newvar ?name:(validate_name name) ()
+
+let type_variable loc name =
+ try
+ Tbl.find name !type_variables
+ with Not_found ->
+ raise(Error(loc, Env.empty, Unbound_type_variable ("'" ^ name)))
+
+let transl_type_param env styp =
+ let loc = styp.ptyp_loc in
+ match styp.ptyp_desc with
+ Ptyp_any ->
+ let ty = new_global_var ~name:"_" () in
+ { ctyp_desc = Ttyp_any; ctyp_type = ty; ctyp_env = env;
+ ctyp_loc = loc; ctyp_attributes = styp.ptyp_attributes; }
+ | Ptyp_var name ->
+ let ty =
+ try
+ if name <> "" && name.[0] = '_' then
+ raise (Error (loc, Env.empty, Invalid_variable_name ("'" ^ name)));
+ ignore (Tbl.find name !type_variables);
+ raise Already_bound
+ with Not_found ->
+ let v = new_global_var ~name () in
+ type_variables := Tbl.add name v !type_variables;
+ v
+ in
+ { ctyp_desc = Ttyp_var name; ctyp_type = ty; ctyp_env = env;
+ ctyp_loc = loc; ctyp_attributes = styp.ptyp_attributes; }
+ | _ -> assert false
+
+let wrap_method ty =
+ match (Ctype.repr ty).desc with
+ Tpoly _ -> ty
+ | _ -> Ctype.newty (Tpoly (ty, []))
+
+let new_pre_univar ?name () =
+ let v = newvar ?name () in pre_univars := v :: !pre_univars; v
+
+let rec swap_list = function
+ x :: y :: l -> y :: x :: swap_list l
+ | l -> l
+
+type policy = Fixed | Extensible | Univars
+
+let rec transl_type env policy styp =
+ let loc = styp.ptyp_loc in
+ let ctyp ctyp_desc ctyp_type =
+ { ctyp_desc; ctyp_type; ctyp_env = env;
+ ctyp_loc = loc; ctyp_attributes = styp.ptyp_attributes }
+ in
+ match styp.ptyp_desc with
+ Ptyp_any ->
+ let ty =
+ if policy = Univars then new_pre_univar () else
+ if policy = Fixed then
+ raise (Error (styp.ptyp_loc, env, Unbound_type_variable "_"))
+ else newvar ()
+ in
+ ctyp Ttyp_any ty
+ | Ptyp_var name ->
+ let ty =
+ if name <> "" && name.[0] = '_' then
+ raise (Error (styp.ptyp_loc, env, Invalid_variable_name ("'" ^ name)));
+ begin try
+ instance env (List.assoc name !univars)
+ with Not_found -> try
+ instance env (fst(Tbl.find name !used_variables))
+ with Not_found ->
+ let v =
+ if policy = Univars then new_pre_univar ~name () else newvar ~name ()
+ in
+ used_variables := Tbl.add name (v, styp.ptyp_loc) !used_variables;
+ v
+ end
+ in
+ ctyp (Ttyp_var name) ty
+ | Ptyp_arrow(l, st1, st2) ->
+ let cty1 = transl_type env policy st1 in
+ let cty2 = transl_type env policy st2 in
+ let ty1 = cty1.ctyp_type in
+ let ty1 =
+ if Btype.is_optional l
+ then newty (Tconstr(Predef.path_option,[ty1], ref Mnil))
+ else ty1 in
+ let ty = newty (Tarrow(l, ty1, cty2.ctyp_type, Cok)) in
+ ctyp (Ttyp_arrow (l, cty1, cty2)) ty
+ | Ptyp_tuple stl ->
+ if List.length stl < 2 then
+ Syntaxerr.ill_formed_ast loc "Tuples must have at least 2 components.";
+ let ctys = List.map (transl_type env policy) stl in
+ let ty = newty (Ttuple (List.map (fun ctyp -> ctyp.ctyp_type) ctys)) in
+ ctyp (Ttyp_tuple ctys) ty
+ | Ptyp_constr(lid, stl) ->
+ let (path, decl) = find_type env styp.ptyp_loc lid.txt in
+ let stl =
+ match stl with
+ | [ {ptyp_desc=Ptyp_any} as t ] when decl.type_arity > 1 ->
+ List.map (fun _ -> t) decl.type_params
+ | _ -> stl
+ in
+ if List.length stl <> decl.type_arity then
+ raise(Error(styp.ptyp_loc, env,
+ Type_arity_mismatch(lid.txt, decl.type_arity,
+ List.length stl)));
+ let args = List.map (transl_type env policy) stl in
+ let params = instance_list decl.type_params in
+ let unify_param =
+ match decl.type_manifest with
+ None -> unify_var
+ | Some ty ->
+ if (repr ty).level = Btype.generic_level then unify_var else unify
+ in
+ List.iter2
+ (fun (sty, cty) ty' ->
+ try unify_param env ty' cty.ctyp_type with Unify trace ->
+ raise (Error(sty.ptyp_loc, env, Type_mismatch (swap_list trace))))
+ (List.combine stl args) params;
+ let constr =
+ newconstr path (List.map (fun ctyp -> ctyp.ctyp_type) args) in
+ begin try
+ Ctype.enforce_constraints env constr
+ with Unify trace ->
+ raise (Error(styp.ptyp_loc, env, Type_mismatch trace))
+ end;
+ ctyp (Ttyp_constr (path, lid, args)) constr
+ | Ptyp_object (fields, o) ->
+ let fields =
+ List.map (fun (s, a, t) -> (s, a, transl_poly_type env policy t))
+ fields
+ in
+ let ty = newobj (transl_fields loc env policy [] o fields) in
+ ctyp (Ttyp_object (fields, o)) ty
+ | Ptyp_class(lid, stl) ->
+ let (path, decl, is_variant) =
+ try
+ let (path, decl) = Env.lookup_type lid.txt env in
+ let rec check decl =
+ match decl.type_manifest with
+ None -> raise Not_found
+ | Some ty ->
+ match (repr ty).desc with
+ Tvariant row when Btype.static_row row -> ()
+ | Tconstr (path, _, _) ->
+ check (Env.find_type path env)
+ | _ -> raise Not_found
+ in check decl;
+ Location.prerr_warning styp.ptyp_loc
+ (Warnings.Deprecated "old syntax for polymorphic variant type");
+ (path, decl,true)
+ with Not_found -> try
+ let lid2 =
+ match lid.txt with
+ Longident.Lident s -> Longident.Lident ("#" ^ s)
+ | Longident.Ldot(r, s) -> Longident.Ldot (r, "#" ^ s)
+ | Longident.Lapply(_, _) -> fatal_error "Typetexp.transl_type"
+ in
+ let (path, decl) = Env.lookup_type lid2 env in
+ (path, decl, false)
+ with Not_found ->
+ ignore (find_class env styp.ptyp_loc lid.txt); assert false
+ in
+ if List.length stl <> decl.type_arity then
+ raise(Error(styp.ptyp_loc, env,
+ Type_arity_mismatch(lid.txt, decl.type_arity,
+ List.length stl)));
+ let args = List.map (transl_type env policy) stl in
+ let params = instance_list decl.type_params in
+ List.iter2
+ (fun (sty, cty) ty' ->
+ try unify_var env ty' cty.ctyp_type with Unify trace ->
+ raise (Error(sty.ptyp_loc, env, Type_mismatch (swap_list trace))))
+ (List.combine stl args) params;
+ let ty_args = List.map (fun ctyp -> ctyp.ctyp_type) args in
+ let ty =
+ try Ctype.expand_head env (newconstr path ty_args)
+ with Unify trace ->
+ raise (Error(styp.ptyp_loc, env, Type_mismatch trace))
+ in
+ let ty = match ty.desc with
+ Tvariant row ->
+ let row = Btype.row_repr row in
+ let fields =
+ List.map
+ (fun (l,f) -> l,
+ match Btype.row_field_repr f with
+ | Rpresent (Some ty) ->
+ Reither(false, [ty], false, ref None)
+ | Rpresent None ->
+ Reither (true, [], false, ref None)
+ | _ -> f)
+ row.row_fields
+ in
+ let row = { row_closed = true; row_fields = fields;
+ row_bound = (); row_name = Some (path, ty_args);
+ row_fixed = false; row_more = newvar () } in
+ let static = Btype.static_row row in
+ let row =
+ if static then { row with row_more = newty Tnil }
+ else if policy <> Univars then row
+ else { row with row_more = new_pre_univar () }
+ in
+ newty (Tvariant row)
+ | Tobject (fi, _) ->
+ let _, tv = flatten_fields fi in
+ if policy = Univars then pre_univars := tv :: !pre_univars;
+ ty
+ | _ ->
+ assert false
+ in
+ ctyp (Ttyp_class (path, lid, args)) ty
+ | Ptyp_alias(st, alias) ->
+ let cty =
+ try
+ let t =
+ try List.assoc alias !univars
+ with Not_found ->
+ instance env (fst(Tbl.find alias !used_variables))
+ in
+ let ty = transl_type env policy st in
+ begin try unify_var env t ty.ctyp_type with Unify trace ->
+ let trace = swap_list trace in
+ raise(Error(styp.ptyp_loc, env, Alias_type_mismatch trace))
+ end;
+ ty
+ with Not_found ->
+ if !Clflags.principal then begin_def ();
+ let t = newvar () in
+ used_variables := Tbl.add alias (t, styp.ptyp_loc) !used_variables;
+ let ty = transl_type env policy st in
+ begin try unify_var env t ty.ctyp_type with Unify trace ->
+ let trace = swap_list trace in
+ raise(Error(styp.ptyp_loc, env, Alias_type_mismatch trace))
+ end;
+ if !Clflags.principal then begin
+ end_def ();
+ generalize_structure t;
+ end;
+ let t = instance env t in
+ let px = Btype.proxy t in
+ begin match px.desc with
+ | Tvar None -> Btype.log_type px; px.desc <- Tvar (Some alias)
+ | Tunivar None -> Btype.log_type px; px.desc <- Tunivar (Some alias)
+ | _ -> ()
+ end;
+ { ty with ctyp_type = t }
+ in
+ ctyp (Ttyp_alias (cty, alias)) cty.ctyp_type
+ | Ptyp_variant(fields, closed, present) ->
+ let name = ref None in
+ let mkfield l f =
+ newty (Tvariant {row_fields=[l,f]; row_more=newvar();
+ row_bound=(); row_closed=true;
+ row_fixed=false; row_name=None}) in
+ let hfields = Hashtbl.create 17 in
+ let add_typed_field loc l f =
+ let h = Btype.hash_variant l in
+ try
+ let (l',f') = Hashtbl.find hfields h in
+ (* Check for tag conflicts *)
+ if l <> l' then raise(Error(styp.ptyp_loc, env, Variant_tags(l, l')));
+ let ty = mkfield l f and ty' = mkfield l f' in
+ if equal env false [ty] [ty'] then () else
+ try unify env ty ty'
+ with Unify trace ->
+ raise(Error(loc, env, Constructor_mismatch (ty,ty')))
+ with Not_found ->
+ Hashtbl.add hfields h (l,f)
+ in
+ let add_field = function
+ Rtag (l, attrs, c, stl) ->
+ name := None;
+ let tl = List.map (transl_type env policy) stl in
+ let f = match present with
+ Some present when not (List.mem l present) ->
+ let ty_tl = List.map (fun cty -> cty.ctyp_type) tl in
+ Reither(c, ty_tl, false, ref None)
+ | _ ->
+ if List.length stl > 1 || c && stl <> [] then
+ raise(Error(styp.ptyp_loc, env, Present_has_conjunction l));
+ match tl with [] -> Rpresent None
+ | st :: _ ->
+ Rpresent (Some st.ctyp_type)
+ in
+ add_typed_field styp.ptyp_loc l f;
+ Ttag (l,attrs,c,tl)
+ | Rinherit sty ->
+ let cty = transl_type env policy sty in
+ let ty = cty.ctyp_type in
+ let nm =
+ match repr cty.ctyp_type with
+ {desc=Tconstr(p, tl, _)} -> Some(p, tl)
+ | _ -> None
+ in
+ begin try
+ (* Set name if there are no fields yet *)
+ Hashtbl.iter (fun _ _ -> raise Exit) hfields;
+ name := nm
+ with Exit ->
+ (* Unset it otherwise *)
+ name := None
+ end;
+ let fl = match expand_head env cty.ctyp_type, nm with
+ {desc=Tvariant row}, _ when Btype.static_row row ->
+ let row = Btype.row_repr row in
+ row.row_fields
+ | {desc=Tvar _}, Some(p, _) ->
+ raise(Error(sty.ptyp_loc, env, Unbound_type_constructor_2 p))
+ | _ ->
+ raise(Error(sty.ptyp_loc, env, Not_a_variant ty))
+ in
+ List.iter
+ (fun (l, f) ->
+ let f = match present with
+ Some present when not (List.mem l present) ->
+ begin match f with
+ Rpresent(Some ty) ->
+ Reither(false, [ty], false, ref None)
+ | Rpresent None ->
+ Reither(true, [], false, ref None)
+ | _ ->
+ assert false
+ end
+ | _ -> f
+ in
+ add_typed_field sty.ptyp_loc l f)
+ fl;
+ Tinherit cty
+ in
+ let tfields = List.map add_field fields in
+ let fields = Hashtbl.fold (fun _ p l -> p :: l) hfields [] in
+ begin match present with None -> ()
+ | Some present ->
+ List.iter
+ (fun l -> if not (List.mem_assoc l fields) then
+ raise(Error(styp.ptyp_loc, env, Present_has_no_type l)))
+ present
+ end;
+ let row =
+ { row_fields = List.rev fields; row_more = newvar ();
+ row_bound = (); row_closed = (closed = Closed);
+ row_fixed = false; row_name = !name } in
+ let static = Btype.static_row row in
+ let row =
+ if static then { row with row_more = newty Tnil }
+ else if policy <> Univars then row
+ else { row with row_more = new_pre_univar () }
+ in
+ let ty = newty (Tvariant row) in
+ ctyp (Ttyp_variant (tfields, closed, present)) ty
+ | Ptyp_poly(vars, st) ->
+ begin_def();
+ let new_univars = List.map (fun name -> name, newvar ~name ()) vars in
+ let old_univars = !univars in
+ univars := new_univars @ !univars;
+ let cty = transl_type env policy st in
+ let ty = cty.ctyp_type in
+ univars := old_univars;
+ end_def();
+ generalize ty;
+ let ty_list =
+ List.fold_left
+ (fun tyl (name, ty1) ->
+ let v = Btype.proxy ty1 in
+ if deep_occur v ty then begin
+ match v.desc with
+ Tvar name when v.level = Btype.generic_level ->
+ v.desc <- Tunivar name;
+ v :: tyl
+ | _ ->
+ raise (Error (styp.ptyp_loc, env, Cannot_quantify (name, v)))
+ end else tyl)
+ [] new_univars
+ in
+ let ty' = Btype.newgenty (Tpoly(ty, List.rev ty_list)) in
+ unify_var env (newvar()) ty';
+ ctyp (Ttyp_poly (vars, cty)) ty'
+ | Ptyp_package (p, l) ->
+ let l, mty = create_package_mty true styp.ptyp_loc env (p, l) in
+ let z = narrow () in
+ let mty = !transl_modtype env mty in
+ widen z;
+ let ptys = List.map (fun (s, pty) ->
+ s, transl_type env policy pty
+ ) l in
+ let path = !transl_modtype_longident styp.ptyp_loc env p.txt in
+ let ty = newty (Tpackage (path,
+ List.map (fun (s, pty) -> s.txt) l,
+ List.map (fun (_,cty) -> cty.ctyp_type) ptys))
+ in
+ ctyp (Ttyp_package {
+ pack_path = path;
+ pack_type = mty.mty_type;
+ pack_fields = ptys;
+ pack_txt = p;
+ }) ty
+ | Ptyp_extension ext ->
+ raise (Error_forward (error_of_extension ext))
+
+and transl_poly_type env policy t =
+ transl_type env policy (Ast_helper.Typ.force_poly t)
+
+and transl_fields loc env policy seen o =
+ function
+ [] ->
+ begin match o, policy with
+ | Closed, _ -> newty Tnil
+ | Open, Univars -> new_pre_univar ()
+ | Open, _ -> newvar ()
+ end
+ | (s, _attrs, ty1) :: l ->
+ if List.mem s seen then raise (Error (loc, env, Repeated_method_label s));
+ let ty2 = transl_fields loc env policy (s :: seen) o l in
+ newty (Tfield (s, Fpresent, ty1.ctyp_type, ty2))
+
+(* Make the rows "fixed" in this type, to make universal check easier *)
+let rec make_fixed_univars ty =
+ let ty = repr ty in
+ if ty.level >= Btype.lowest_level then begin
+ Btype.mark_type_node ty;
+ match ty.desc with
+ | Tvariant row ->
+ let row = Btype.row_repr row in
+ if Btype.is_Tunivar (Btype.row_more row) then
+ ty.desc <- Tvariant
+ {row with row_fixed=true;
+ row_fields = List.map
+ (fun (s,f as p) -> match Btype.row_field_repr f with
+ Reither (c, tl, m, r) -> s, Reither (c, tl, true, r)
+ | _ -> p)
+ row.row_fields};
+ Btype.iter_row make_fixed_univars row
+ | _ ->
+ Btype.iter_type_expr make_fixed_univars ty
+ end
+
+let make_fixed_univars ty =
+ make_fixed_univars ty;
+ Btype.unmark_type ty
+
+let create_package_mty = create_package_mty false
+
+let globalize_used_variables env fixed =
+ let r = ref [] in
+ Tbl.iter
+ (fun name (ty, loc) ->
+ let v = new_global_var () in
+ let snap = Btype.snapshot () in
+ if try unify env v ty; true with _ -> Btype.backtrack snap; false
+ then try
+ r := (loc, v, Tbl.find name !type_variables) :: !r
+ with Not_found ->
+ if fixed && Btype.is_Tvar (repr ty) then
+ raise(Error(loc, env, Unbound_type_variable ("'"^name)));
+ let v2 = new_global_var () in
+ r := (loc, v, v2) :: !r;
+ type_variables := Tbl.add name v2 !type_variables)
+ !used_variables;
+ used_variables := Tbl.empty;
+ fun () ->
+ List.iter
+ (function (loc, t1, t2) ->
+ try unify env t1 t2 with Unify trace ->
+ raise (Error(loc, env, Type_mismatch trace)))
+ !r
+
+let transl_simple_type env fixed styp =
+ univars := []; used_variables := Tbl.empty;
+ let typ = transl_type env (if fixed then Fixed else Extensible) styp in
+ globalize_used_variables env fixed ();
+ make_fixed_univars typ.ctyp_type;
+ typ
+
+let transl_simple_type_univars env styp =
+ univars := []; used_variables := Tbl.empty; pre_univars := [];
+ begin_def ();
+ let typ = transl_type env Univars styp in
+ (* Only keep already global variables in used_variables *)
+ let new_variables = !used_variables in
+ used_variables := Tbl.empty;
+ Tbl.iter
+ (fun name p ->
+ if Tbl.mem name !type_variables then
+ used_variables := Tbl.add name p !used_variables)
+ new_variables;
+ globalize_used_variables env false ();
+ end_def ();
+ generalize typ.ctyp_type;
+ let univs =
+ List.fold_left
+ (fun acc v ->
+ let v = repr v in
+ match v.desc with
+ Tvar name when v.level = Btype.generic_level ->
+ v.desc <- Tunivar name; v :: acc
+ | _ -> acc)
+ [] !pre_univars
+ in
+ make_fixed_univars typ.ctyp_type;
+ { typ with ctyp_type =
+ instance env (Btype.newgenty (Tpoly (typ.ctyp_type, univs))) }
+
+let transl_simple_type_delayed env styp =
+ univars := []; used_variables := Tbl.empty;
+ let typ = transl_type env Extensible styp in
+ make_fixed_univars typ.ctyp_type;
+ (typ, globalize_used_variables env false)
+
+let transl_type_scheme env styp =
+ reset_type_variables();
+ begin_def();
+ let typ = transl_simple_type env false styp in
+ end_def();
+ generalize typ.ctyp_type;
+ typ
+
+
+(* Error report *)
+
+open Format
+open Printtyp
+
+let spellcheck ppf fold env lid =
+ let choices ~path name =
+ let env = fold (fun x xs -> x::xs) path env [] in
+ Misc.spellcheck env name in
+ match lid with
+ | Longident.Lapply _ -> ()
+ | Longident.Lident s ->
+ Misc.did_you_mean ppf (fun () -> choices ~path:None s)
+ | Longident.Ldot (r, s) ->
+ Misc.did_you_mean ppf (fun () -> choices ~path:(Some r) s)
+
+let fold_descr fold get_name f = fold (fun descr acc -> f (get_name descr) acc)
+let fold_simple fold4 f = fold4 (fun name _path _descr acc -> f name acc)
+
+let fold_values = fold_simple Env.fold_values
+let fold_types = fold_simple Env.fold_types
+let fold_modules = fold_simple Env.fold_modules
+let fold_constructors = fold_descr Env.fold_constructors (fun d -> d.cstr_name)
+let fold_labels = fold_descr Env.fold_labels (fun d -> d.lbl_name)
+let fold_classs = fold_simple Env.fold_classs
+let fold_modtypes = fold_simple Env.fold_modtypes
+let fold_cltypes = fold_simple Env.fold_cltypes
+
+let report_error env ppf = function
+ | Unbound_type_variable name ->
+ (* we don't use "spellcheck" here: the function that raises this
+ error seems not to be called anywhere, so it's unclear how it
+ should be handled *)
+ fprintf ppf "Unbound type parameter %s@." name
+ | Unbound_type_constructor lid ->
+ fprintf ppf "Unbound type constructor %a" longident lid;
+ spellcheck ppf fold_types env lid;
+ | Unbound_type_constructor_2 p ->
+ fprintf ppf "The type constructor@ %a@ is not yet completely defined"
+ path p
+ | Type_arity_mismatch(lid, expected, provided) ->
+ fprintf ppf
+ "@[The type constructor %a@ expects %i argument(s),@ \
+ but is here applied to %i argument(s)@]"
+ longident lid expected provided
+ | Bound_type_variable name ->
+ fprintf ppf "Already bound type parameter '%s" name
+ | Recursive_type ->
+ fprintf ppf "This type is recursive"
+ | Unbound_row_variable lid ->
+ (* we don't use "spellcheck" here: this error is not raised
+ anywhere so it's unclear how it should be handled *)
+ fprintf ppf "Unbound row variable in #%a" longident lid
+ | Type_mismatch trace ->
+ Printtyp.report_unification_error ppf Env.empty trace
+ (function ppf ->
+ fprintf ppf "This type")
+ (function ppf ->
+ fprintf ppf "should be an instance of type")
+ | Alias_type_mismatch trace ->
+ Printtyp.report_unification_error ppf Env.empty trace
+ (function ppf ->
+ fprintf ppf "This alias is bound to type")
+ (function ppf ->
+ fprintf ppf "but is used as an instance of type")
+ | Present_has_conjunction l ->
+ fprintf ppf "The present constructor %s has a conjunctive type" l
+ | Present_has_no_type l ->
+ fprintf ppf "The present constructor %s has no type" l
+ | Constructor_mismatch (ty, ty') ->
+ wrap_printing_env env (fun () ->
+ Printtyp.reset_and_mark_loops_list [ty; ty'];
+ fprintf ppf "@[<hov>%s %a@ %s@ %a@]"
+ "This variant type contains a constructor"
+ Printtyp.type_expr ty
+ "which should be"
+ Printtyp.type_expr ty')
+ | Not_a_variant ty ->
+ Printtyp.reset_and_mark_loops ty;
+ fprintf ppf "@[The type %a@ is not a polymorphic variant type@]"
+ Printtyp.type_expr ty
+ | Variant_tags (lab1, lab2) ->
+ fprintf ppf
+ "@[Variant tags `%s@ and `%s have the same hash value.@ %s@]"
+ lab1 lab2 "Change one of them."
+ | Invalid_variable_name name ->
+ fprintf ppf "The type variable name %s is not allowed in programs" name
+ | Cannot_quantify (name, v) ->
+ fprintf ppf
+ "@[<hov>The universal type variable '%s cannot be generalized:@ %s.@]"
+ name
+ (if Btype.is_Tvar v then "it escapes its scope" else
+ if Btype.is_Tunivar v then "it is already bound to another variable"
+ else "it is not a variable")
+ | Multiple_constraints_on_type s ->
+ fprintf ppf "Multiple constraints for type %a" longident s
+ | Repeated_method_label s ->
+ fprintf ppf "@[This is the second method `%s' of this object type.@ %s@]"
+ s "Multiple occurences are not allowed."
+ | Unbound_value lid ->
+ fprintf ppf "Unbound value %a" longident lid;
+ spellcheck ppf fold_values env lid;
+ | Unbound_module lid ->
+ fprintf ppf "Unbound module %a" longident lid;
+ spellcheck ppf fold_modules env lid;
+ | Unbound_constructor lid ->
+ fprintf ppf "Unbound constructor %a" longident lid;
+ spellcheck ppf fold_constructors env lid;
+ | Unbound_label lid ->
+ fprintf ppf "Unbound record field %a" longident lid;
+ spellcheck ppf fold_labels env lid;
+ | Unbound_class lid ->
+ fprintf ppf "Unbound class %a" longident lid;
+ spellcheck ppf fold_classs env lid;
+ | Unbound_modtype lid ->
+ fprintf ppf "Unbound module type %a" longident lid;
+ spellcheck ppf fold_modtypes env lid;
+ | Unbound_cltype lid ->
+ fprintf ppf "Unbound class type %a" longident lid;
+ spellcheck ppf fold_cltypes env lid;
+ | Ill_typed_functor_application lid ->
+ fprintf ppf "Ill-typed functor application %a" longident lid
+ | Illegal_reference_to_recursive_module ->
+ fprintf ppf "Illegal recursive module reference"
+ | Access_functor_as_structure lid ->
+ fprintf ppf "The module %a is a functor, not a structure" longident lid
+
+let () =
+ Location.register_error_of_exn
+ (function
+ | Error (loc, env, err) ->
+ Some (Location.error_of_printer loc (report_error env) err)
+ | Error_forward err ->
+ Some err
+ | _ ->
+ None
+ )
diff --git a/typing/typetexp.mli b/typing/typetexp.mli
new file mode 100644
index 0000000000..b51d52f2f3
--- /dev/null
+++ b/typing/typetexp.mli
@@ -0,0 +1,119 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Typechecking of type expressions for the core language *)
+
+open Types
+
+val transl_simple_type:
+ Env.t -> bool -> Parsetree.core_type -> Typedtree.core_type
+val transl_simple_type_univars:
+ Env.t -> Parsetree.core_type -> Typedtree.core_type
+val transl_simple_type_delayed:
+ Env.t -> Parsetree.core_type -> Typedtree.core_type * (unit -> unit)
+ (* Translate a type, but leave type variables unbound. Returns
+ the type and a function that binds the type variable. *)
+val transl_type_scheme:
+ Env.t -> Parsetree.core_type -> Typedtree.core_type
+val reset_type_variables: unit -> unit
+val type_variable: Location.t -> string -> type_expr
+val transl_type_param:
+ Env.t -> Parsetree.core_type -> Typedtree.core_type
+
+type variable_context
+val narrow: unit -> variable_context
+val widen: variable_context -> unit
+
+exception Already_bound
+
+type error =
+ Unbound_type_variable of string
+ | Unbound_type_constructor of Longident.t
+ | Unbound_type_constructor_2 of Path.t
+ | Type_arity_mismatch of Longident.t * int * int
+ | Bound_type_variable of string
+ | Recursive_type
+ | Unbound_row_variable of Longident.t
+ | Type_mismatch of (type_expr * type_expr) list
+ | Alias_type_mismatch of (type_expr * type_expr) list
+ | Present_has_conjunction of string
+ | Present_has_no_type of string
+ | Constructor_mismatch of type_expr * type_expr
+ | Not_a_variant of type_expr
+ | Variant_tags of string * string
+ | Invalid_variable_name of string
+ | Cannot_quantify of string * type_expr
+ | Multiple_constraints_on_type of Longident.t
+ | Repeated_method_label of string
+ | Unbound_value of Longident.t
+ | Unbound_constructor of Longident.t
+ | Unbound_label of Longident.t
+ | Unbound_module of Longident.t
+ | Unbound_class of Longident.t
+ | Unbound_modtype of Longident.t
+ | Unbound_cltype of Longident.t
+ | Ill_typed_functor_application of Longident.t
+ | Illegal_reference_to_recursive_module
+ | Access_functor_as_structure of Longident.t
+
+exception Error of Location.t * Env.t * error
+
+val report_error: Env.t -> Format.formatter -> error -> unit
+
+(* Support for first-class modules. *)
+val transl_modtype_longident: (* from Typemod *)
+ (Location.t -> Env.t -> Longident.t -> Path.t) ref
+val transl_modtype: (* from Typemod *)
+ (Env.t -> Parsetree.module_type -> Typedtree.module_type) ref
+val create_package_mty:
+ Location.t -> Env.t -> Parsetree.package_type ->
+ (Longident.t Asttypes.loc * Parsetree.core_type) list *
+ Parsetree.module_type
+
+val find_type:
+ Env.t -> Location.t -> Longident.t -> Path.t * type_declaration
+val find_constructor:
+ Env.t -> Location.t -> Longident.t -> constructor_description
+val find_all_constructors:
+ Env.t -> Location.t -> Longident.t ->
+ (constructor_description * (unit -> unit)) list
+val find_label:
+ Env.t -> Location.t -> Longident.t -> label_description
+val find_all_labels:
+ Env.t -> Location.t -> Longident.t ->
+ (label_description * (unit -> unit)) list
+val find_value:
+ Env.t -> Location.t -> Longident.t -> Path.t * value_description
+val find_class:
+ Env.t -> Location.t -> Longident.t -> Path.t * class_declaration
+val find_module:
+ Env.t -> Location.t -> Longident.t -> Path.t * module_declaration
+val lookup_module:
+ ?load:bool -> Env.t -> Location.t -> Longident.t -> Path.t
+val find_modtype:
+ Env.t -> Location.t -> Longident.t -> Path.t * modtype_declaration
+val find_class_type:
+ Env.t -> Location.t -> Longident.t -> Path.t * class_type_declaration
+
+val unbound_constructor_error: Env.t -> Longident.t Location.loc -> 'a
+val unbound_label_error: Env.t -> Longident.t Location.loc -> 'a
+
+val check_deprecated: Location.t -> Parsetree.attributes -> string -> unit
+
+val warning_enter_scope: unit -> unit
+val warning_leave_scope: unit -> unit
+val warning_attribute: Parsetree.attributes -> unit
+val with_warning_attribute: Parsetree.attributes -> (unit -> 'a) -> 'a
+
+val error_of_extension: Parsetree.extension -> Location.error
+
+val emit_external_warnings: Ast_mapper.mapper
diff --git a/typing/untypeast.ml b/typing/untypeast.ml
new file mode 100644
index 0000000000..4693ef157f
--- /dev/null
+++ b/typing/untypeast.ml
@@ -0,0 +1,781 @@
+(**************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Thomas Gazagnaire (OCamlPro), Fabrice Le Fessant (INRIA Saclay) *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(**************************************************************************)
+
+open Longident
+open Asttypes
+open Parsetree
+open Ast_helper
+
+module T = Typedtree
+
+type mapper = {
+ attribute: mapper -> T.attribute -> attribute;
+ attributes: mapper -> T.attribute list -> attribute list;
+ case: mapper -> T.case -> case;
+ cases: mapper -> T.case list -> case list;
+ class_declaration: mapper -> T.class_declaration -> class_declaration;
+ class_description: mapper -> T.class_description -> class_description;
+ class_expr: mapper -> T.class_expr -> class_expr;
+ class_field: mapper -> T.class_field -> class_field;
+ class_signature: mapper -> T.class_signature -> class_signature;
+ class_structure: mapper -> T.class_structure -> class_structure;
+ class_type: mapper -> T.class_type -> class_type;
+ class_type_declaration: mapper -> T.class_type_declaration
+ -> class_type_declaration;
+ class_type_field: mapper -> T.class_type_field -> class_type_field;
+ constructor_declaration: mapper -> T.constructor_declaration
+ -> constructor_declaration;
+ expr: mapper -> T.expression -> expression;
+ extension_constructor: mapper -> T.extension_constructor
+ -> extension_constructor;
+ include_declaration: mapper -> T.include_declaration -> include_declaration;
+ include_description: mapper -> T.include_description -> include_description;
+ label_declaration: mapper -> T.label_declaration -> label_declaration;
+ location: mapper -> Location.t -> Location.t;
+ module_binding: mapper -> T.module_binding -> module_binding;
+ module_declaration: mapper -> T.module_declaration -> module_declaration;
+ module_expr: mapper -> T.module_expr -> module_expr;
+ module_type: mapper -> T.module_type -> module_type;
+ module_type_declaration:
+ mapper -> T.module_type_declaration -> module_type_declaration;
+ package_type: mapper -> T.package_type -> package_type;
+ open_description: mapper -> T.open_description -> open_description;
+ pat: mapper -> T.pattern -> pattern;
+ row_field: mapper -> T.row_field -> row_field;
+ signature: mapper -> T.signature -> signature;
+ signature_item: mapper -> T.signature_item -> signature_item;
+ structure: mapper -> T.structure -> structure;
+ structure_item: mapper -> T.structure_item -> structure_item;
+ typ: mapper -> T.core_type -> core_type;
+ type_declaration: mapper -> T.type_declaration -> type_declaration;
+ type_extension: mapper -> T.type_extension -> type_extension;
+ type_kind: mapper -> T.type_kind -> type_kind;
+ value_binding: mapper -> T.value_binding -> value_binding;
+ value_description: mapper -> T.value_description -> value_description;
+ with_constraint:
+ mapper -> (Path.t * Longident.t Location.loc * T.with_constraint)
+ -> with_constraint;
+}
+
+open T
+
+(*
+Some notes:
+
+ * For Pexp_function, we cannot go back to the exact original version
+ when there is a default argument, because the default argument is
+ translated in the typer. The code, if printed, will not be parsable because
+ new generated identifiers are not correct.
+
+ * For Pexp_apply, it is unclear whether arguments are reordered, especially
+ when there are optional arguments.
+
+*)
+
+
+(** Utility functions. *)
+
+let string_is_prefix sub str =
+ let sublen = String.length sub in
+ String.length str >= sublen && String.sub str 0 sublen = sub
+
+let map_opt f = function None -> None | Some e -> Some (f e)
+
+let rec lident_of_path = function
+ | Path.Pident id -> Longident.Lident (Ident.name id)
+ | Path.Pdot (p, s, _) -> Longident.Ldot (lident_of_path p, s)
+ | Path.Papply (p1, p2) ->
+ Longident.Lapply (lident_of_path p1, lident_of_path p2)
+
+let map_loc sub {loc; txt} = {loc = sub.location sub loc; txt}
+
+(** Try a name [$name$0], check if it's free, if not, increment and repeat. *)
+let fresh_name s env =
+ let rec aux i =
+ let name = s ^ string_of_int i in
+ try
+ let _ = Env.lookup_value (Lident name) env in
+ name
+ with
+ | Not_found -> aux (i+1)
+ in
+ aux 0
+
+(** Mapping functions. *)
+
+let attribute sub (s, p) = (map_loc sub s, p)
+let attributes sub l = List.map (sub.attribute sub) l
+
+let structure sub str =
+ List.map (sub.structure_item sub) str.str_items
+
+let open_description sub od =
+ let loc = sub.location sub od.open_loc in
+ let attrs = sub.attributes sub od.open_attributes in
+ Opn.mk ~loc ~attrs
+ ~override:od.open_override
+ (map_loc sub od.open_txt)
+
+let structure_item sub item =
+ let loc = sub.location sub item.str_loc in
+ let desc =
+ match item.str_desc with
+ Tstr_eval (exp, attrs) -> Pstr_eval (sub.expr sub exp, attrs)
+ | Tstr_value (rec_flag, list) ->
+ Pstr_value (rec_flag, List.map (sub.value_binding sub) list)
+ | Tstr_primitive vd ->
+ Pstr_primitive (sub.value_description sub vd)
+ | Tstr_type (rec_flag, list) ->
+ Pstr_type (rec_flag, List.map (sub.type_declaration sub) list)
+ | Tstr_typext tyext ->
+ Pstr_typext (sub.type_extension sub tyext)
+ | Tstr_exception ext ->
+ Pstr_exception (sub.extension_constructor sub ext)
+ | Tstr_module mb ->
+ Pstr_module (sub.module_binding sub mb)
+ | Tstr_recmodule list ->
+ Pstr_recmodule (List.map (sub.module_binding sub) list)
+ | Tstr_modtype mtd ->
+ Pstr_modtype (sub.module_type_declaration sub mtd)
+ | Tstr_open od ->
+ Pstr_open (sub.open_description sub od)
+ | Tstr_class list ->
+ Pstr_class
+ (List.map
+ (fun (ci, _) -> sub.class_declaration sub ci)
+ list)
+ | Tstr_class_type list ->
+ Pstr_class_type
+ (List.map
+ (fun (_id, _name, ct) -> sub.class_type_declaration sub ct)
+ list)
+ | Tstr_include incl ->
+ Pstr_include (sub.include_declaration sub incl)
+ | Tstr_attribute x ->
+ Pstr_attribute x
+ in
+ Str.mk ~loc desc
+
+let value_description sub v =
+ let loc = sub.location sub v.val_loc in
+ let attrs = sub.attributes sub v.val_attributes in
+ Val.mk ~loc ~attrs
+ ~prim:v.val_prim
+ (map_loc sub v.val_name)
+ (sub.typ sub v.val_desc)
+
+let module_binding sub mb =
+ let loc = sub.location sub mb.mb_loc; in
+ let attrs = sub.attributes sub mb.mb_attributes in
+ Mb.mk ~loc ~attrs
+ (map_loc sub mb.mb_name)
+ (sub.module_expr sub mb.mb_expr)
+
+let type_parameter sub (ct, v) = (sub.typ sub ct, v)
+
+let type_declaration sub decl =
+ let loc = sub.location sub decl.typ_loc; in
+ let attrs = sub.attributes sub decl.typ_attributes in
+ Type.mk ~loc ~attrs
+ ~params:(List.map (type_parameter sub) decl.typ_params)
+ ~cstrs:(
+ List.map
+ (fun (ct1, ct2, loc) ->
+ (sub.typ sub ct1, sub.typ sub ct2, sub.location sub loc))
+ decl.typ_cstrs)
+ ~kind:(sub.type_kind sub decl.typ_kind)
+ ~priv:decl.typ_private
+ ?manifest:(map_opt (sub.typ sub) decl.typ_manifest)
+ (map_loc sub decl.typ_name)
+
+let type_kind sub tk = match tk with
+ | Ttype_abstract -> Ptype_abstract
+ | Ttype_variant list ->
+ Ptype_variant (List.map (sub.constructor_declaration sub) list)
+ | Ttype_record list ->
+ Ptype_record (List.map (sub.label_declaration sub) list)
+ | Ttype_open -> Ptype_open
+
+let constructor_arguments sub = function
+ | Cstr_tuple l -> Pcstr_tuple (List.map (sub.typ sub) l)
+ | Cstr_record l -> Pcstr_record (List.map (sub.label_declaration sub) l)
+
+let constructor_declaration sub cd =
+ let loc = sub.location sub cd.cd_loc; in
+ let attrs = sub.attributes sub cd.cd_attributes in
+ Type.constructor ~loc ~attrs
+ ~args:(constructor_arguments sub cd.cd_args)
+ ?res:(map_opt (sub.typ sub) cd.cd_res)
+ (map_loc sub cd.cd_name)
+
+let label_declaration sub ld =
+ let loc = sub.location sub ld.ld_loc; in
+ let attrs = sub.attributes sub ld.ld_attributes in
+ Type.field ~loc ~attrs
+ ~mut:ld.ld_mutable
+ (map_loc sub ld.ld_name)
+ (sub.typ sub ld.ld_type)
+
+let type_extension sub tyext =
+ let attrs = sub.attributes sub tyext.tyext_attributes in
+ Te.mk ~attrs
+ ~params:(List.map (type_parameter sub) tyext.tyext_params)
+ ~priv:tyext.tyext_private
+ (map_loc sub tyext.tyext_txt)
+ (List.map (sub.extension_constructor sub) tyext.tyext_constructors)
+
+let extension_constructor sub ext =
+ let loc = sub.location sub ext.ext_loc; in
+ let attrs = sub.attributes sub ext.ext_attributes in
+ Te.constructor ~loc ~attrs
+ (map_loc sub ext.ext_name)
+ (match ext.ext_kind with
+ | Text_decl (args, ret) ->
+ Pext_decl (constructor_arguments sub args,
+ map_opt (sub.typ sub) ret)
+ | Text_rebind (_p, lid) -> Pext_rebind (map_loc sub lid)
+ )
+
+let pattern sub pat =
+ let loc = sub.location sub pat.pat_loc; in
+ (* todo: fix attributes on extras *)
+ let attrs = sub.attributes sub pat.pat_attributes in
+ let desc =
+ match pat with
+ { pat_extra=[Tpat_unpack, _, _attrs]; pat_desc = Tpat_var (_,name); _ } ->
+ Ppat_unpack name
+ | { pat_extra=[Tpat_type (_path, lid), _, _attrs]; _ } ->
+ Ppat_type (map_loc sub lid)
+ | { pat_extra= (Tpat_constraint ct, _, _attrs) :: rem; _ } ->
+ Ppat_constraint (sub.pat sub { pat with pat_extra=rem },
+ sub.typ sub ct)
+ | _ ->
+ match pat.pat_desc with
+ Tpat_any -> Ppat_any
+ | Tpat_var (id, name) ->
+ begin
+ match (Ident.name id).[0] with
+ 'A'..'Z' ->
+ Ppat_unpack name
+ | _ ->
+ Ppat_var name
+ end
+
+ (* We transform (_ as x) in x if _ and x have the same location.
+ The compiler transforms (x:t) into (_ as x : t).
+ This avoids transforming a warning 27 into a 26.
+ *)
+ | Tpat_alias ({pat_desc = Tpat_any; pat_loc}, _id, name)
+ when pat_loc = pat.pat_loc ->
+ Ppat_var name
+
+ | Tpat_alias (pat, _id, name) ->
+ Ppat_alias (sub.pat sub pat, name)
+ | Tpat_constant cst -> Ppat_constant cst
+ | Tpat_tuple list ->
+ Ppat_tuple (List.map (sub.pat sub) list)
+ | Tpat_construct (lid, _, args) ->
+ Ppat_construct (map_loc sub lid,
+ (match args with
+ [] -> None
+ | [arg] -> Some (sub.pat sub arg)
+ | args ->
+ Some
+ (Pat.tuple ~loc
+ (List.map (sub.pat sub) args)
+ )
+ ))
+ | Tpat_variant (label, pato, _) ->
+ Ppat_variant (label, map_opt (sub.pat sub) pato)
+ | Tpat_record (list, closed) ->
+ Ppat_record (List.map (fun (lid, _, pat) ->
+ map_loc sub lid, sub.pat sub pat) list, closed)
+ | Tpat_array list -> Ppat_array (List.map (sub.pat sub) list)
+ | Tpat_or (p1, p2, _) -> Ppat_or (sub.pat sub p1, sub.pat sub p2)
+ | Tpat_lazy p -> Ppat_lazy (sub.pat sub p)
+ in
+ Pat.mk ~loc ~attrs desc
+
+let exp_extra sub (extra, loc, attrs) sexp =
+ let loc = sub.location sub loc; in
+ let attrs = sub.attributes sub attrs in
+ let desc =
+ match extra with
+ Texp_coerce (cty1, cty2) ->
+ Pexp_coerce (sexp,
+ map_opt (sub.typ sub) cty1,
+ sub.typ sub cty2)
+ | Texp_constraint cty ->
+ Pexp_constraint (sexp, sub.typ sub cty)
+ | Texp_open (ovf, _path, lid, _) ->
+ Pexp_open (ovf, map_loc sub lid, sexp)
+ | Texp_poly cto -> Pexp_poly (sexp, map_opt (sub.typ sub) cto)
+ | Texp_newtype s -> Pexp_newtype (s, sexp)
+ in
+ Exp.mk ~loc ~attrs desc
+
+let cases sub l = List.map (sub.case sub) l
+
+let case sub {c_lhs; c_guard; c_rhs} =
+ {
+ pc_lhs = sub.pat sub c_lhs;
+ pc_guard = map_opt (sub.expr sub) c_guard;
+ pc_rhs = sub.expr sub c_rhs;
+ }
+
+let value_binding sub vb =
+ let loc = sub.location sub vb.vb_loc; in
+ let attrs = sub.attributes sub vb.vb_attributes in
+ Vb.mk ~loc ~attrs
+ (sub.pat sub vb.vb_pat)
+ (sub.expr sub vb.vb_expr)
+
+let expression sub exp =
+ let loc = sub.location sub exp.exp_loc; in
+ let attrs = sub.attributes sub exp.exp_attributes in
+ let desc =
+ match exp.exp_desc with
+ Texp_ident (_path, lid, _) -> Pexp_ident (map_loc sub lid)
+ | Texp_constant cst -> Pexp_constant cst
+ | Texp_let (rec_flag, list, exp) ->
+ Pexp_let (rec_flag,
+ List.map (sub.value_binding sub) list,
+ sub.expr sub exp)
+
+ (* Pexp_function can't have a label, so we split in 3 cases. *)
+ (* One case, no guard: It's a fun. *)
+ | Texp_function (label, [{c_lhs=p; c_guard=None; c_rhs=e}], _) ->
+ Pexp_fun (label, None, sub.pat sub p, sub.expr sub e)
+ (* No label: it's a function. *)
+ | Texp_function (Nolabel, cases, _) ->
+ Pexp_function (sub.cases sub cases)
+ (* Mix of both, we generate `fun ~label:$name$ -> match $name$ with ...` *)
+ | Texp_function (Labelled s | Optional s as label, cases, _) ->
+ let name = fresh_name s exp.exp_env in
+ Pexp_fun (label, None, Pat.var ~loc {loc;txt = name },
+ Exp.match_ ~loc (Exp.ident ~loc {loc;txt= Lident name})
+ (sub.cases sub cases))
+ | Texp_apply (exp, list) ->
+ Pexp_apply (sub.expr sub exp,
+ List.fold_right (fun (label, expo, _) list ->
+ match expo with
+ None -> list
+ | Some exp -> (label, sub.expr sub exp) :: list
+ ) list [])
+ | Texp_match (exp, cases, exn_cases, _) ->
+ let merged_cases = sub.cases sub cases
+ @ List.map
+ (fun c ->
+ let uc = sub.case sub c in
+ let pat = { uc.pc_lhs
+ with ppat_desc = Ppat_exception uc.pc_lhs }
+ in
+ { uc with pc_lhs = pat })
+ exn_cases
+ in
+ Pexp_match (sub.expr sub exp, merged_cases)
+ | Texp_try (exp, cases) ->
+ Pexp_try (sub.expr sub exp, sub.cases sub cases)
+ | Texp_tuple list ->
+ Pexp_tuple (List.map (sub.expr sub) list)
+ | Texp_construct (lid, _, args) ->
+ Pexp_construct (map_loc sub lid,
+ (match args with
+ [] -> None
+ | [ arg ] -> Some (sub.expr sub arg)
+ | args ->
+ Some
+ (Exp.tuple ~loc (List.map (sub.expr sub) args))
+ ))
+ | Texp_variant (label, expo) ->
+ Pexp_variant (label, map_opt (sub.expr sub) expo)
+ | Texp_record (list, expo) ->
+ Pexp_record (List.map (fun (lid, _, exp) ->
+ (map_loc sub lid, sub.expr sub exp)
+ ) list,
+ map_opt (sub.expr sub) expo)
+ | Texp_field (exp, lid, _label) ->
+ Pexp_field (sub.expr sub exp, map_loc sub lid)
+ | Texp_setfield (exp1, lid, _label, exp2) ->
+ Pexp_setfield (sub.expr sub exp1, map_loc sub lid,
+ sub.expr sub exp2)
+ | Texp_array list ->
+ Pexp_array (List.map (sub.expr sub) list)
+ | Texp_ifthenelse (exp1, exp2, expo) ->
+ Pexp_ifthenelse (sub.expr sub exp1,
+ sub.expr sub exp2,
+ map_opt (sub.expr sub) expo)
+ | Texp_sequence (exp1, exp2) ->
+ Pexp_sequence (sub.expr sub exp1, sub.expr sub exp2)
+ | Texp_while (exp1, exp2) ->
+ Pexp_while (sub.expr sub exp1, sub.expr sub exp2)
+ | Texp_for (_id, name, exp1, exp2, dir, exp3) ->
+ Pexp_for (name,
+ sub.expr sub exp1, sub.expr sub exp2,
+ dir, sub.expr sub exp3)
+ | Texp_send (exp, meth, _) ->
+ Pexp_send (sub.expr sub exp, match meth with
+ Tmeth_name name -> name
+ | Tmeth_val id -> Ident.name id)
+ | Texp_new (_path, lid, _) -> Pexp_new (map_loc sub lid)
+ | Texp_instvar (_, path, name) ->
+ Pexp_ident ({loc = sub.location sub name.loc ; txt = lident_of_path path})
+ | Texp_setinstvar (_, _path, lid, exp) ->
+ Pexp_setinstvar (map_loc sub lid, sub.expr sub exp)
+ | Texp_override (_, list) ->
+ Pexp_override (List.map (fun (_path, lid, exp) ->
+ (map_loc sub lid, sub.expr sub exp)
+ ) list)
+ | Texp_letmodule (_id, name, mexpr, exp) ->
+ Pexp_letmodule (name, sub.module_expr sub mexpr,
+ sub.expr sub exp)
+ | Texp_assert exp -> Pexp_assert (sub.expr sub exp)
+ | Texp_lazy exp -> Pexp_lazy (sub.expr sub exp)
+ | Texp_object (cl, _) ->
+ Pexp_object (sub.class_structure sub cl)
+ | Texp_pack (mexpr) ->
+ Pexp_pack (sub.module_expr sub mexpr)
+ in
+ List.fold_right (exp_extra sub) exp.exp_extra
+ (Exp.mk ~loc ~attrs desc)
+
+let package_type sub pack =
+ (map_loc sub pack.pack_txt,
+ List.map (fun (s, ct) ->
+ (s, sub.typ sub ct)) pack.pack_fields)
+
+let module_type_declaration sub mtd =
+ let loc = sub.location sub mtd.mtd_loc; in
+ let attrs = sub.attributes sub mtd.mtd_attributes in
+ Mtd.mk ~loc ~attrs
+ ?typ:(map_opt (sub.module_type sub) mtd.mtd_type)
+ (map_loc sub mtd.mtd_name)
+
+let signature sub sg =
+ List.map (sub.signature_item sub) sg.sig_items
+
+let signature_item sub item =
+ let loc = sub.location sub item.sig_loc; in
+ let desc =
+ match item.sig_desc with
+ Tsig_value v ->
+ Psig_value (sub.value_description sub v)
+ | Tsig_type (rec_flag, list) ->
+ Psig_type (rec_flag, List.map (sub.type_declaration sub) list)
+ | Tsig_typext tyext ->
+ Psig_typext (sub.type_extension sub tyext)
+ | Tsig_exception ext ->
+ Psig_exception (sub.extension_constructor sub ext)
+ | Tsig_module md ->
+ Psig_module (sub.module_declaration sub md)
+ | Tsig_recmodule list ->
+ Psig_recmodule (List.map (sub.module_declaration sub) list)
+ | Tsig_modtype mtd ->
+ Psig_modtype (sub.module_type_declaration sub mtd)
+ | Tsig_open od ->
+ Psig_open (sub.open_description sub od)
+ | Tsig_include incl ->
+ Psig_include (sub.include_description sub incl)
+ | Tsig_class list ->
+ Psig_class (List.map (sub.class_description sub) list)
+ | Tsig_class_type list ->
+ Psig_class_type (List.map (sub.class_type_declaration sub) list)
+ | Tsig_attribute x ->
+ Psig_attribute x
+ in
+ Sig.mk ~loc desc
+
+let module_declaration sub md =
+ let loc = sub.location sub md.md_loc; in
+ let attrs = sub.attributes sub md.md_attributes in
+ Md.mk ~loc ~attrs
+ (map_loc sub md.md_name)
+ (sub.module_type sub md.md_type)
+
+let include_infos f sub incl =
+ let loc = sub.location sub incl.incl_loc; in
+ let attrs = sub.attributes sub incl.incl_attributes in
+ Incl.mk ~loc ~attrs
+ (f sub incl.incl_mod)
+
+let include_declaration sub = include_infos sub.module_expr sub
+let include_description sub = include_infos sub.module_type sub
+
+let class_infos f sub ci =
+ let loc = sub.location sub ci.ci_loc; in
+ let attrs = sub.attributes sub ci.ci_attributes in
+ Ci.mk ~loc ~attrs
+ ~virt:ci.ci_virt
+ ~params:(List.map (type_parameter sub) ci.ci_params)
+ (map_loc sub ci.ci_id_name)
+ (f sub ci.ci_expr)
+
+let class_declaration sub = class_infos sub.class_expr sub
+let class_description sub = class_infos sub.class_type sub
+let class_type_declaration sub = class_infos sub.class_type sub
+
+let module_type sub mty =
+ let loc = sub.location sub mty.mty_loc; in
+ let attrs = sub.attributes sub mty.mty_attributes in
+ let desc = match mty.mty_desc with
+ Tmty_ident (_path, lid) -> Pmty_ident (map_loc sub lid)
+ | Tmty_alias (_path, lid) -> Pmty_alias (map_loc sub lid)
+ | Tmty_signature sg -> Pmty_signature (sub.signature sub sg)
+ | Tmty_functor (_id, name, mtype1, mtype2) ->
+ Pmty_functor (name, map_opt (sub.module_type sub) mtype1,
+ sub.module_type sub mtype2)
+ | Tmty_with (mtype, list) ->
+ Pmty_with (sub.module_type sub mtype,
+ List.map (sub.with_constraint sub) list)
+ | Tmty_typeof mexpr ->
+ Pmty_typeof (sub.module_expr sub mexpr)
+ in
+ Mty.mk ~loc ~attrs desc
+
+let with_constraint sub (_path, lid, cstr) =
+ match cstr with
+ | Twith_type decl ->
+ Pwith_type (map_loc sub lid, sub.type_declaration sub decl)
+ | Twith_module (_path, lid2) ->
+ Pwith_module (map_loc sub lid, map_loc sub lid2)
+ | Twith_typesubst decl -> Pwith_typesubst (sub.type_declaration sub decl)
+ | Twith_modsubst (_path, lid2) ->
+ Pwith_modsubst
+ ({loc = sub.location sub lid.loc; txt=Longident.last lid.txt},
+ map_loc sub lid2)
+
+let module_expr sub mexpr =
+ let loc = sub.location sub mexpr.mod_loc; in
+ let attrs = sub.attributes sub mexpr.mod_attributes in
+ match mexpr.mod_desc with
+ Tmod_constraint (m, _, Tmodtype_implicit, _ ) ->
+ sub.module_expr sub m
+ | _ ->
+ let desc = match mexpr.mod_desc with
+ Tmod_ident (_p, lid) -> Pmod_ident (map_loc sub lid)
+ | Tmod_structure st -> Pmod_structure (sub.structure sub st)
+ | Tmod_functor (_id, name, mtype, mexpr) ->
+ Pmod_functor (name, Misc.may_map (sub.module_type sub) mtype,
+ sub.module_expr sub mexpr)
+ | Tmod_apply (mexp1, mexp2, _) ->
+ Pmod_apply (sub.module_expr sub mexp1, sub.module_expr sub mexp2)
+ | Tmod_constraint (mexpr, _, Tmodtype_explicit mtype, _) ->
+ Pmod_constraint (sub.module_expr sub mexpr,
+ sub.module_type sub mtype)
+ | Tmod_constraint (_mexpr, _, Tmodtype_implicit, _) ->
+ assert false
+ | Tmod_unpack (exp, _pack) ->
+ Pmod_unpack (sub.expr sub exp)
+ (* TODO , sub.package_type sub pack) *)
+ in
+ Mod.mk ~loc ~attrs desc
+
+let class_expr sub cexpr =
+ let loc = sub.location sub cexpr.cl_loc; in
+ let attrs = sub.attributes sub cexpr.cl_attributes in
+ let desc = match cexpr.cl_desc with
+ | Tcl_constraint ( { cl_desc = Tcl_ident (_path, lid, tyl); _ },
+ None, _, _, _ ) ->
+ Pcl_constr (map_loc sub lid,
+ List.map (sub.typ sub) tyl)
+ | Tcl_structure clstr -> Pcl_structure (sub.class_structure sub clstr)
+
+ | Tcl_fun (label, pat, _pv, cl, _partial) ->
+ Pcl_fun (label, None, sub.pat sub pat, sub.class_expr sub cl)
+
+ | Tcl_apply (cl, args) ->
+ Pcl_apply (sub.class_expr sub cl,
+ List.fold_right (fun (label, expo, _) list ->
+ match expo with
+ None -> list
+ | Some exp -> (label, sub.expr sub exp) :: list
+ ) args [])
+
+ | Tcl_let (rec_flat, bindings, _ivars, cl) ->
+ Pcl_let (rec_flat,
+ List.map (sub.value_binding sub) bindings,
+ sub.class_expr sub cl)
+
+ | Tcl_constraint (cl, Some clty, _vals, _meths, _concrs) ->
+ Pcl_constraint (sub.class_expr sub cl, sub.class_type sub clty)
+
+ | Tcl_ident _ -> assert false
+ | Tcl_constraint (_, None, _, _, _) -> assert false
+ in
+ Cl.mk ~loc ~attrs desc
+
+let class_type sub ct =
+ let loc = sub.location sub ct.cltyp_loc; in
+ let attrs = sub.attributes sub ct.cltyp_attributes in
+ let desc = match ct.cltyp_desc with
+ Tcty_signature csg -> Pcty_signature (sub.class_signature sub csg)
+ | Tcty_constr (_path, lid, list) ->
+ Pcty_constr (map_loc sub lid, List.map (sub.typ sub) list)
+ | Tcty_arrow (label, ct, cl) ->
+ Pcty_arrow (label, sub.typ sub ct, sub.class_type sub cl)
+ in
+ Cty.mk ~loc ~attrs desc
+
+let class_signature sub cs =
+ {
+ pcsig_self = sub.typ sub cs.csig_self;
+ pcsig_fields = List.map (sub.class_type_field sub) cs.csig_fields;
+ }
+
+let class_type_field sub ctf =
+ let loc = sub.location sub ctf.ctf_loc; in
+ let attrs = sub.attributes sub ctf.ctf_attributes in
+ let desc = match ctf.ctf_desc with
+ Tctf_inherit ct -> Pctf_inherit (sub.class_type sub ct)
+ | Tctf_val (s, mut, virt, ct) ->
+ Pctf_val (s, mut, virt, sub.typ sub ct)
+ | Tctf_method (s, priv, virt, ct) ->
+ Pctf_method (s, priv, virt, sub.typ sub ct)
+ | Tctf_constraint (ct1, ct2) ->
+ Pctf_constraint (sub.typ sub ct1, sub.typ sub ct2)
+ | Tctf_attribute x -> Pctf_attribute x
+ in
+ Ctf.mk ~loc ~attrs desc
+
+let core_type sub ct =
+ let loc = sub.location sub ct.ctyp_loc; in
+ let attrs = sub.attributes sub ct.ctyp_attributes in
+ let desc = match ct.ctyp_desc with
+ Ttyp_any -> Ptyp_any
+ | Ttyp_var s -> Ptyp_var s
+ | Ttyp_arrow (label, ct1, ct2) ->
+ Ptyp_arrow (label, sub.typ sub ct1, sub.typ sub ct2)
+ | Ttyp_tuple list -> Ptyp_tuple (List.map (sub.typ sub) list)
+ | Ttyp_constr (_path, lid, list) ->
+ Ptyp_constr (map_loc sub lid,
+ List.map (sub.typ sub) list)
+ | Ttyp_object (list, o) ->
+ Ptyp_object
+ (List.map (fun (s, a, t) -> (s, a, sub.typ sub t)) list, o)
+ | Ttyp_class (_path, lid, list) ->
+ Ptyp_class (map_loc sub lid, List.map (sub.typ sub) list)
+ | Ttyp_alias (ct, s) ->
+ Ptyp_alias (sub.typ sub ct, s)
+ | Ttyp_variant (list, bool, labels) ->
+ Ptyp_variant (List.map (sub.row_field sub) list, bool, labels)
+ | Ttyp_poly (list, ct) -> Ptyp_poly (list, sub.typ sub ct)
+ | Ttyp_package pack -> Ptyp_package (sub.package_type sub pack)
+ in
+ Typ.mk ~loc ~attrs desc
+
+let class_structure sub cs =
+ let rec remove_self = function
+ | { pat_desc = Tpat_alias (p, id, _s) }
+ when string_is_prefix "selfpat-" id.Ident.name ->
+ remove_self p
+ | p -> p
+ in
+ { pcstr_self = sub.pat sub (remove_self cs.cstr_self);
+ pcstr_fields = List.map (sub.class_field sub) cs.cstr_fields;
+ }
+
+let row_field sub rf =
+ match rf with
+ Ttag (label, attrs, bool, list) ->
+ Rtag (label, sub.attributes sub attrs, bool, List.map (sub.typ sub) list)
+ | Tinherit ct -> Rinherit (sub.typ sub ct)
+
+and is_self_pat = function
+ | { pat_desc = Tpat_alias(_pat, id, _) } ->
+ string_is_prefix "self-" (Ident.name id)
+ | _ -> false
+
+let class_field sub cf =
+ let loc = sub.location sub cf.cf_loc; in
+ let attrs = sub.attributes sub cf.cf_attributes in
+ let desc = match cf.cf_desc with
+ Tcf_inherit (ovf, cl, super, _vals, _meths) ->
+ Pcf_inherit (ovf, sub.class_expr sub cl, super)
+ | Tcf_constraint (cty, cty') ->
+ Pcf_constraint (sub.typ sub cty, sub.typ sub cty')
+ | Tcf_val (lab, mut, _, Tcfk_virtual cty, _) ->
+ Pcf_val (lab, mut, Cfk_virtual (sub.typ sub cty))
+ | Tcf_val (lab, mut, _, Tcfk_concrete (o, exp), _) ->
+ Pcf_val (lab, mut, Cfk_concrete (o, sub.expr sub exp))
+ | Tcf_method (lab, priv, Tcfk_virtual cty) ->
+ Pcf_method (lab, priv, Cfk_virtual (sub.typ sub cty))
+ | Tcf_method (lab, priv, Tcfk_concrete (o, exp)) ->
+ let remove_fun_self = function
+ | { exp_desc = Texp_function(Nolabel, [case], _) }
+ when is_self_pat case.c_lhs && case.c_guard = None -> case.c_rhs
+ | e -> e
+ in
+ let exp = remove_fun_self exp in
+ Pcf_method (lab, priv, Cfk_concrete (o, sub.expr sub exp))
+ | Tcf_initializer exp ->
+ let remove_fun_self = function
+ | { exp_desc = Texp_function(Nolabel, [case], _) }
+ when is_self_pat case.c_lhs && case.c_guard = None -> case.c_rhs
+ | e -> e
+ in
+ let exp = remove_fun_self exp in
+ Pcf_initializer (sub.expr sub exp)
+ | Tcf_attribute x -> Pcf_attribute x
+ in
+ Cf.mk ~loc ~attrs desc
+
+let location sub l = l
+
+let default_mapper =
+ {
+ attribute = attribute ;
+ attributes = attributes ;
+ structure = structure;
+ structure_item = structure_item;
+ module_expr = module_expr;
+ signature = signature;
+ signature_item = signature_item;
+ module_type = module_type;
+ with_constraint = with_constraint;
+ class_declaration = class_declaration;
+ class_expr = class_expr;
+ class_field = class_field;
+ class_structure = class_structure;
+ class_type = class_type;
+ class_type_field = class_type_field;
+ class_signature = class_signature;
+ class_type_declaration = class_type_declaration;
+ class_description = class_description;
+ type_declaration = type_declaration;
+ type_kind = type_kind;
+ typ = core_type;
+ type_extension = type_extension;
+ extension_constructor = extension_constructor;
+ value_description = value_description;
+ pat = pattern;
+ expr = expression;
+ module_declaration = module_declaration;
+ module_type_declaration = module_type_declaration;
+ module_binding = module_binding;
+ package_type = package_type ;
+ open_description = open_description;
+ include_description = include_description;
+ include_declaration = include_declaration;
+ value_binding = value_binding;
+ constructor_declaration = constructor_declaration;
+ label_declaration = label_declaration;
+ cases = cases;
+ case = case;
+ location = location;
+ row_field = row_field ;
+ }
+
+let untype_structure ?(mapper=default_mapper) structure =
+ mapper.structure mapper structure
+
+let untype_signature ?(mapper=default_mapper) signature =
+ mapper.signature mapper signature
diff --git a/typing/untypeast.mli b/typing/untypeast.mli
new file mode 100644
index 0000000000..702fe0cd73
--- /dev/null
+++ b/typing/untypeast.mli
@@ -0,0 +1,73 @@
+(**************************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Thomas Gazagnaire (OCamlPro), Fabrice Le Fessant (INRIA Saclay) *)
+(* *)
+(* Copyright 2007 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(**************************************************************************)
+
+open Parsetree
+
+val lident_of_path : Path.t -> Longident.t
+
+type mapper = {
+ attribute: mapper -> Typedtree.attribute -> attribute;
+ attributes: mapper -> Typedtree.attribute list -> attribute list;
+ case: mapper -> Typedtree.case -> case;
+ cases: mapper -> Typedtree.case list -> case list;
+ class_declaration: mapper -> Typedtree.class_declaration -> class_declaration;
+ class_description: mapper -> Typedtree.class_description -> class_description;
+ class_expr: mapper -> Typedtree.class_expr -> class_expr;
+ class_field: mapper -> Typedtree.class_field -> class_field;
+ class_signature: mapper -> Typedtree.class_signature -> class_signature;
+ class_structure: mapper -> Typedtree.class_structure -> class_structure;
+ class_type: mapper -> Typedtree.class_type -> class_type;
+ class_type_declaration: mapper -> Typedtree.class_type_declaration
+ -> class_type_declaration;
+ class_type_field: mapper -> Typedtree.class_type_field -> class_type_field;
+ constructor_declaration: mapper -> Typedtree.constructor_declaration
+ -> constructor_declaration;
+ expr: mapper -> Typedtree.expression -> expression;
+ extension_constructor: mapper -> Typedtree.extension_constructor
+ -> extension_constructor;
+ include_declaration:
+ mapper -> Typedtree.include_declaration -> include_declaration;
+ include_description:
+ mapper -> Typedtree.include_description -> include_description;
+ label_declaration:
+ mapper -> Typedtree.label_declaration -> label_declaration;
+ location: mapper -> Location.t -> Location.t;
+ module_binding: mapper -> Typedtree.module_binding -> module_binding;
+ module_declaration:
+ mapper -> Typedtree.module_declaration -> module_declaration;
+ module_expr: mapper -> Typedtree.module_expr -> module_expr;
+ module_type: mapper -> Typedtree.module_type -> module_type;
+ module_type_declaration:
+ mapper -> Typedtree.module_type_declaration -> module_type_declaration;
+ package_type: mapper -> Typedtree.package_type -> package_type;
+ open_description: mapper -> Typedtree.open_description -> open_description;
+ pat: mapper -> Typedtree.pattern -> pattern;
+ row_field: mapper -> Typedtree.row_field -> row_field;
+ signature: mapper -> Typedtree.signature -> signature;
+ signature_item: mapper -> Typedtree.signature_item -> signature_item;
+ structure: mapper -> Typedtree.structure -> structure;
+ structure_item: mapper -> Typedtree.structure_item -> structure_item;
+ typ: mapper -> Typedtree.core_type -> core_type;
+ type_declaration: mapper -> Typedtree.type_declaration -> type_declaration;
+ type_extension: mapper -> Typedtree.type_extension -> type_extension;
+ type_kind: mapper -> Typedtree.type_kind -> type_kind;
+ value_binding: mapper -> Typedtree.value_binding -> value_binding;
+ value_description: mapper -> Typedtree.value_description -> value_description;
+ with_constraint:
+ mapper -> (Path.t * Longident.t Location.loc * Typedtree.with_constraint)
+ -> with_constraint;
+}
+
+val default_mapper : mapper
+
+val untype_structure : ?mapper:mapper -> Typedtree.structure -> structure
+val untype_signature : ?mapper:mapper -> Typedtree.signature -> signature
diff --git a/utils/.ignore b/utils/.ignore
new file mode 100644
index 0000000000..25b6d3bc86
--- /dev/null
+++ b/utils/.ignore
@@ -0,0 +1 @@
+config.ml
diff --git a/utils/ccomp.ml b/utils/ccomp.ml
new file mode 100644
index 0000000000..a897ddc0d9
--- /dev/null
+++ b/utils/ccomp.ml
@@ -0,0 +1,138 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compiling C files and building C libraries *)
+
+let command cmdline =
+ if !Clflags.verbose then begin
+ prerr_string "+ ";
+ prerr_string cmdline;
+ prerr_newline()
+ end;
+ Sys.command cmdline
+
+let run_command cmdline = ignore(command cmdline)
+
+(* Build @responsefile to work around Windows limitations on
+ command-line length *)
+let build_diversion lst =
+ let (responsefile, oc) = Filename.open_temp_file "camlresp" "" in
+ List.iter (fun f -> Printf.fprintf oc "%s\n" f) lst;
+ close_out oc;
+ at_exit (fun () -> Misc.remove_file responsefile);
+ "@" ^ responsefile
+
+let quote_files lst =
+ let lst = List.filter (fun f -> f <> "") lst in
+ let quoted = List.map Filename.quote lst in
+ let s = String.concat " " quoted in
+ if String.length s >= 4096 && Sys.os_type = "Win32"
+ then build_diversion quoted
+ else s
+
+let quote_prefixed pr lst =
+ let lst = List.filter (fun f -> f <> "") lst in
+ let lst = List.map (fun f -> pr ^ f) lst in
+ quote_files lst
+
+let quote_optfile = function
+ | None -> ""
+ | Some f -> Filename.quote f
+
+let compile_file ~output_name name =
+ command
+ (Printf.sprintf
+ "%s%s -c %s %s %s %s %s"
+ (match !Clflags.c_compiler with
+ | Some cc -> cc
+ | None ->
+ if !Clflags.native_code
+ then Config.native_c_compiler
+ else Config.bytecomp_c_compiler)
+ (match output_name with
+ | Some n -> " -o " ^ Filename.quote n
+ | None -> "")
+ (if !Clflags.debug then "-g" else "")
+ (String.concat " " (List.rev !Clflags.all_ccopts))
+ (quote_prefixed "-I" (List.rev !Clflags.include_dirs))
+ (Clflags.std_include_flag "-I")
+ (Filename.quote name))
+
+let create_archive archive file_list =
+ Misc.remove_file archive;
+ let quoted_archive = Filename.quote archive in
+ match Config.ccomp_type with
+ "msvc" ->
+ command(Printf.sprintf "link /lib /nologo /out:%s %s"
+ quoted_archive (quote_files file_list))
+ | _ ->
+ assert(String.length Config.ar > 0);
+ let r1 =
+ command(Printf.sprintf "%s rc %s %s"
+ Config.ar quoted_archive (quote_files file_list)) in
+ if r1 <> 0 || String.length Config.ranlib = 0
+ then r1
+ else command(Config.ranlib ^ " " ^ quoted_archive)
+
+let expand_libname name =
+ if String.length name < 2 || String.sub name 0 2 <> "-l"
+ then name
+ else begin
+ let libname =
+ "lib" ^ String.sub name 2 (String.length name - 2) ^ Config.ext_lib in
+ try
+ Misc.find_in_path !Config.load_path libname
+ with Not_found ->
+ libname
+ end
+
+type link_mode =
+ | Exe
+ | Dll
+ | MainDll
+ | Partial
+
+let remove_Wl cclibs =
+ cclibs |> List.map (fun cclib ->
+ (* -Wl,-foo,bar -> -foo bar *)
+ if String.length cclib >= 4 && "-Wl," = String.sub cclib 0 4 then
+ String.map (function ',' -> ' ' | c -> c)
+ (String.sub cclib 4 (String.length cclib - 4))
+ else cclib)
+
+let call_linker mode output_name files extra =
+ let cmd =
+ if mode = Partial then
+ Printf.sprintf "%s%s %s %s %s"
+ Config.native_pack_linker
+ (Filename.quote output_name)
+ (quote_prefixed "-L" !Config.load_path)
+ (quote_files (remove_Wl files))
+ extra
+ else
+ Printf.sprintf "%s -o %s %s %s %s %s %s %s"
+ (match !Clflags.c_compiler, mode with
+ | Some cc, _ -> cc
+ | None, Exe -> Config.mkexe
+ | None, Dll -> Config.mkdll
+ | None, MainDll -> Config.mkmaindll
+ | None, Partial -> assert false
+ )
+ (Filename.quote output_name)
+ (if !Clflags.gprofile then Config.cc_profile else "")
+ "" (*(Clflags.std_include_flag "-I")*)
+ (quote_prefixed "-L" !Config.load_path)
+ (String.concat " " (List.rev !Clflags.all_ccopts))
+ (quote_files files)
+ extra
+ in
+ command cmd = 0
diff --git a/utils/ccomp.mli b/utils/ccomp.mli
new file mode 100644
index 0000000000..897c2abbfa
--- /dev/null
+++ b/utils/ccomp.mli
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Compiling C files and building C libraries *)
+
+val command: string -> int
+val run_command: string -> unit
+val compile_file: output_name:string option -> string -> int
+val create_archive: string -> string list -> int
+val expand_libname: string -> string
+val quote_files: string list -> string
+val quote_optfile: string option -> string
+(*val make_link_options: string list -> string*)
+
+type link_mode =
+ | Exe
+ | Dll
+ | MainDll
+ | Partial
+
+val call_linker: link_mode -> string -> string list -> string -> bool
diff --git a/utils/clflags.ml b/utils/clflags.ml
new file mode 100644
index 0000000000..0e6dc345ad
--- /dev/null
+++ b/utils/clflags.ml
@@ -0,0 +1,127 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Command-line parameters *)
+
+let objfiles = ref ([] : string list) (* .cmo and .cma files *)
+and ccobjs = ref ([] : string list) (* .o, .a, .so and -cclib -lxxx *)
+and dllibs = ref ([] : string list) (* .so and -dllib -lxxx *)
+
+let compile_only = ref false (* -c *)
+and output_name = ref (None : string option) (* -o *)
+and include_dirs = ref ([] : string list)(* -I *)
+and no_std_include = ref false (* -nostdlib *)
+and print_types = ref false (* -i *)
+and make_archive = ref false (* -a *)
+and debug = ref false (* -g *)
+and fast = ref false (* -unsafe *)
+and link_everything = ref false (* -linkall *)
+and custom_runtime = ref false (* -custom *)
+and no_check_prims = ref false (* -no-check-prims *)
+and bytecode_compatible_32 = ref false (* -compat-32 *)
+and output_c_object = ref false (* -output-obj *)
+and output_complete_object = ref false (* -output-complete-obj *)
+and all_ccopts = ref ([] : string list) (* -ccopt *)
+and classic = ref false (* -nolabels *)
+and nopervasives = ref false (* -nopervasives *)
+and preprocessor = ref(None : string option) (* -pp *)
+and all_ppx = ref ([] : string list) (* -ppx *)
+let annotations = ref false (* -annot *)
+let binary_annotations = ref false (* -annot *)
+and use_threads = ref false (* -thread *)
+and use_vmthreads = ref false (* -vmthread *)
+and noassert = ref false (* -noassert *)
+and verbose = ref false (* -verbose *)
+and noprompt = ref false (* -noprompt *)
+and nopromptcont = ref false (* -nopromptcont *)
+and init_file = ref (None : string option) (* -init *)
+and noinit = ref false (* -noinit *)
+and open_modules = ref [] (* -open *)
+and use_prims = ref "" (* -use-prims ... *)
+and use_runtime = ref "" (* -use-runtime ... *)
+and principal = ref false (* -principal *)
+and real_paths = ref true (* -short-paths *)
+and recursive_types = ref false (* -rectypes *)
+and strict_sequence = ref false (* -strict-sequence *)
+and strict_formats = ref false (* -strict-formats *)
+and applicative_functors = ref true (* -no-app-funct *)
+and make_runtime = ref false (* -make-runtime *)
+and gprofile = ref false (* -p *)
+and c_compiler = ref (None: string option) (* -cc *)
+and no_auto_link = ref false (* -noautolink *)
+and dllpaths = ref ([] : string list) (* -dllpath *)
+and make_package = ref false (* -pack *)
+and for_package = ref (None: string option) (* -for-pack *)
+and error_size = ref 500 (* -error-size *)
+and float_const_prop = ref true (* -no-float-const-prop *)
+and transparent_modules = ref false (* -trans-mod *)
+let dump_source = ref false (* -dsource *)
+let dump_parsetree = ref false (* -dparsetree *)
+and dump_typedtree = ref false (* -dtypedtree *)
+and dump_rawlambda = ref false (* -drawlambda *)
+and dump_lambda = ref false (* -dlambda *)
+and dump_clambda = ref false (* -dclambda *)
+and dump_instr = ref false (* -dinstr *)
+
+let keep_asm_file = ref false (* -S *)
+let optimize_for_speed = ref true (* -compact *)
+and opaque = ref false (* -opaque *)
+
+and dump_cmm = ref false (* -dcmm *)
+let dump_selection = ref false (* -dsel *)
+let dump_cse = ref false (* -dcse *)
+let dump_live = ref false (* -dlive *)
+let dump_spill = ref false (* -dspill *)
+let dump_split = ref false (* -dsplit *)
+let dump_interf = ref false (* -dinterf *)
+let dump_prefer = ref false (* -dprefer *)
+let dump_regalloc = ref false (* -dalloc *)
+let dump_reload = ref false (* -dreload *)
+let dump_scheduling = ref false (* -dscheduling *)
+let dump_linear = ref false (* -dlinear *)
+let keep_startup_file = ref false (* -dstartup *)
+let dump_combine = ref false (* -dcombine *)
+let native_code = ref false (* set to true under ocamlopt *)
+let inline_threshold = ref 10
+let force_slash = ref false (* for ocamldep *)
+
+let dont_write_files = ref false (* set to true under ocamldoc *)
+
+let std_include_flag prefix =
+ if !no_std_include then ""
+ else (prefix ^ (Filename.quote Config.standard_library))
+;;
+
+let std_include_dir () =
+ if !no_std_include then [] else [Config.standard_library]
+;;
+
+let shared = ref false (* -shared *)
+let dlcode = ref true (* not -nodynlink *)
+
+let pic_code = ref (match Config.architecture with (* -fPIC *)
+ | "amd64" -> true
+ | _ -> false)
+
+let runtime_variant = ref "";; (* -runtime-variant *)
+
+let keep_docs = ref false (* -keep-docs *)
+let keep_locs = ref false (* -keep-locs *)
+let unsafe_string = ref true;; (* -safe-string / -unsafe-string *)
+
+type color_setting = Auto | Always | Never
+let parse_color_setting = function
+ | "auto" -> Some Auto
+ | "always" -> Some Always
+ | "never" -> Some Never
+ | _ -> None
+let color = ref Auto ;; (* -color *)
diff --git a/utils/clflags.mli b/utils/clflags.mli
new file mode 100644
index 0000000000..4b6d4786ba
--- /dev/null
+++ b/utils/clflags.mli
@@ -0,0 +1,104 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2005 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+val objfiles : string list ref
+val ccobjs : string list ref
+val dllibs : string list ref
+val compile_only : bool ref
+val output_name : string option ref
+val include_dirs : string list ref
+val no_std_include : bool ref
+val print_types : bool ref
+val make_archive : bool ref
+val debug : bool ref
+val fast : bool ref
+val link_everything : bool ref
+val custom_runtime : bool ref
+val no_check_prims : bool ref
+val bytecode_compatible_32 : bool ref
+val output_c_object : bool ref
+val output_complete_object : bool ref
+val all_ccopts : string list ref
+val classic : bool ref
+val nopervasives : bool ref
+val open_modules : string list ref
+val preprocessor : string option ref
+val all_ppx : string list ref
+val annotations : bool ref
+val binary_annotations : bool ref
+val use_threads : bool ref
+val use_vmthreads : bool ref
+val noassert : bool ref
+val verbose : bool ref
+val noprompt : bool ref
+val nopromptcont : bool ref
+val init_file : string option ref
+val noinit : bool ref
+val use_prims : string ref
+val use_runtime : string ref
+val principal : bool ref
+val real_paths : bool ref
+val recursive_types : bool ref
+val strict_sequence : bool ref
+val strict_formats : bool ref
+val applicative_functors : bool ref
+val make_runtime : bool ref
+val gprofile : bool ref
+val c_compiler : string option ref
+val no_auto_link : bool ref
+val dllpaths : string list ref
+val make_package : bool ref
+val for_package : string option ref
+val error_size : int ref
+val float_const_prop : bool ref
+val transparent_modules : bool ref
+val dump_source : bool ref
+val dump_parsetree : bool ref
+val dump_typedtree : bool ref
+val dump_rawlambda : bool ref
+val dump_lambda : bool ref
+val dump_clambda : bool ref
+val dump_instr : bool ref
+val keep_asm_file : bool ref
+val optimize_for_speed : bool ref
+val dump_cmm : bool ref
+val dump_selection : bool ref
+val dump_cse : bool ref
+val dump_live : bool ref
+val dump_spill : bool ref
+val dump_split : bool ref
+val dump_interf : bool ref
+val dump_prefer : bool ref
+val dump_regalloc : bool ref
+val dump_reload : bool ref
+val dump_scheduling : bool ref
+val dump_linear : bool ref
+val keep_startup_file : bool ref
+val dump_combine : bool ref
+val native_code : bool ref
+val inline_threshold : int ref
+val dont_write_files : bool ref
+val std_include_flag : string -> string
+val std_include_dir : unit -> string list
+val shared : bool ref
+val dlcode : bool ref
+val pic_code : bool ref
+val runtime_variant : string ref
+val force_slash : bool ref
+val keep_docs : bool ref
+val keep_locs : bool ref
+val unsafe_string : bool ref
+val opaque : bool ref
+
+type color_setting = Auto | Always | Never
+val parse_color_setting : string -> color_setting option
+val color : color_setting ref
diff --git a/utils/config.mlbuild b/utils/config.mlbuild
new file mode 100644
index 0000000000..35e8c5b504
--- /dev/null
+++ b/utils/config.mlbuild
@@ -0,0 +1,151 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(***********************************************************************)
+(** **)
+(** WARNING WARNING WARNING **)
+(** **)
+(** When you change this file, you must make the parallel change **)
+(** in config.mlp **)
+(** **)
+(***********************************************************************)
+
+
+(* The main OCaml version string has moved to ../VERSION *)
+let version = Sys.ocaml_version
+
+module C = Myocamlbuild_config
+
+let standard_library_default = C.libdir
+
+let standard_library =
+ try
+ Sys.getenv "OCAMLLIB"
+ with Not_found ->
+ try
+ Sys.getenv "CAMLLIB"
+ with Not_found ->
+ standard_library_default
+
+let windows =
+ match Sys.os_type with
+ | "Win32" -> true
+ | _ -> false
+
+let sf = Printf.sprintf
+
+let standard_runtime =
+ if windows then "ocamlrun"
+ else C.bindir^"/ocamlrun"
+let ccomp_type = C.ccomptype
+let bytecomp_c_compiler =
+ sf "%s %s %s" C.bytecc C.bytecccompopts C.sharedcccompopts
+let bytecomp_c_libraries = C.bytecclibs
+let native_c_compiler = sf "%s %s" C.nativecc C.nativecccompopts
+let native_c_libraries = C.nativecclibs
+let native_pack_linker = C.packld
+let ranlib = C.ranlibcmd
+let ar = C.arcmd
+let cc_profile = C.cc_profile
+let mkdll = C.mkdll
+let mkexe = C.mkexe
+let mkmaindll = C.mkmaindll
+
+let exec_magic_number = "Caml1999X011"
+and cmi_magic_number = "Caml1999I019"
+and cmo_magic_number = "Caml1999O009"
+and cma_magic_number = "Caml1999A010"
+and cmx_magic_number = "Caml1999Y011"
+and cmxa_magic_number = "Caml1999Z010"
+and ast_impl_magic_number = "Caml1999M019"
+and ast_intf_magic_number = "Caml1999N018"
+and cmxs_magic_number = "Caml2007D001"
+and cmt_magic_number = "Caml2012T006"
+
+let load_path = ref ([] : string list)
+
+let interface_suffix = ref ".mli"
+
+let max_tag = 245
+(* This is normally the same as in obj.ml, but we have to define it
+ separately because it can differ when we're in the middle of a
+ bootstrapping phase. *)
+let lazy_tag = 246
+
+let max_young_wosize = 256
+let stack_threshold = 256 (* see byterun/config.h *)
+
+let architecture = C.arch
+let model = C.model
+let system = C.system
+
+let asm = C.asm
+let asm_cfi_supported = C.asm_cfi_supported
+
+let ext_obj = C.ext_obj
+let ext_asm = C.ext_asm
+let ext_lib = C.ext_lib
+let ext_dll = C.ext_dll
+
+let host = C.host
+let target = C.target
+
+let default_executable_name =
+ match Sys.os_type with
+ "Unix" -> "a.out"
+ | "Win32" | "Cygwin" -> "camlprog.exe"
+ | _ -> "camlprog"
+
+let systhread_supported = C.systhread_support;;
+
+let print_config oc =
+ let p name valu = Printf.fprintf oc "%s: %s\n" name valu in
+ let p_bool name valu = Printf.fprintf oc "%s: %B\n" name valu in
+ p "version" version;
+ p "standard_library_default" standard_library_default;
+ p "standard_library" standard_library;
+ p "standard_runtime" standard_runtime;
+ p "ccomp_type" ccomp_type;
+ p "bytecomp_c_compiler" bytecomp_c_compiler;
+ p "bytecomp_c_libraries" bytecomp_c_libraries;
+ p "native_c_compiler" native_c_compiler;
+ p "native_c_libraries" native_c_libraries;
+ p "native_pack_linker" native_pack_linker;
+ p "ranlib" ranlib;
+ p "cc_profile" cc_profile;
+ p "architecture" architecture;
+ p "model" model;
+ p "system" system;
+ p "asm" asm;
+ p_bool "asm_cfi_supported" asm_cfi_supported;
+ p "ext_obj" ext_obj;
+ p "ext_asm" ext_asm;
+ p "ext_lib" ext_lib;
+ p "ext_dll" ext_dll;
+ p "os_type" Sys.os_type;
+ p "default_executable_name" default_executable_name;
+ p_bool "systhread_supported" systhread_supported;
+ p "host" host;
+ p "target" target;
+ p "exec_magic_number" exec_magic_number;
+ p "cmi_magic_number" cmi_magic_number;
+ p "cmo_magic_number" cmo_magic_number;
+ p "cma_magic_number" cma_magic_number;
+ p "cmx_magic_number" cmx_magic_number;
+ p "cmxa_magic_number" cmxa_magic_number;
+ p "ast_impl_magic_number" ast_impl_magic_number;
+ p "ast_intf_magic_number" ast_intf_magic_number;
+ p "cmxs_magic_number" cmxs_magic_number;
+ p "cmt_magic_number" cmt_magic_number;
+
+ flush oc;
+;;
diff --git a/utils/config.mli b/utils/config.mli
new file mode 100644
index 0000000000..c9b8904d77
--- /dev/null
+++ b/utils/config.mli
@@ -0,0 +1,129 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* System configuration *)
+
+val version: string
+ (* The current version number of the system *)
+
+val standard_library: string
+ (* The directory containing the standard libraries *)
+val standard_runtime: string
+ (* The full path to the standard bytecode interpreter ocamlrun *)
+val ccomp_type: string
+ (* The "kind" of the C compiler, assembler and linker used: one of
+ "cc" (for Unix-style C compilers)
+ "msvc" (for Microsoft Visual C++ and MASM) *)
+val bytecomp_c_compiler: string
+ (* The C compiler to use for compiling C files
+ with the bytecode compiler *)
+val bytecomp_c_libraries: string
+ (* The C libraries to link with custom runtimes *)
+val native_c_compiler: string
+ (* The C compiler to use for compiling C files
+ with the native-code compiler *)
+val native_c_libraries: string
+ (* The C libraries to link with native-code programs *)
+val native_pack_linker: string
+ (* The linker to use for packaging (ocamlopt -pack) and for partial
+ links (ocamlopt -output-obj). *)
+val mkdll: string
+ (* The linker command line to build dynamic libraries. *)
+val mkexe: string
+ (* The linker command line to build executables. *)
+val mkmaindll: string
+ (* The linker command line to build main programs as dlls. *)
+val ranlib: string
+ (* Command to randomize a library, or "" if not needed *)
+val ar: string
+ (* Name of the ar command, or "" if not needed (MSVC) *)
+val cc_profile : string
+ (* The command line option to the C compiler to enable profiling. *)
+
+val load_path: string list ref
+ (* Directories in the search path for .cmi and .cmo files *)
+
+val interface_suffix: string ref
+ (* Suffix for interface file names *)
+
+val exec_magic_number: string
+ (* Magic number for bytecode executable files *)
+val cmi_magic_number: string
+ (* Magic number for compiled interface files *)
+val cmo_magic_number: string
+ (* Magic number for object bytecode files *)
+val cma_magic_number: string
+ (* Magic number for archive files *)
+val cmx_magic_number: string
+ (* Magic number for compilation unit descriptions *)
+val cmxa_magic_number: string
+ (* Magic number for libraries of compilation unit descriptions *)
+val ast_intf_magic_number: string
+ (* Magic number for file holding an interface syntax tree *)
+val ast_impl_magic_number: string
+ (* Magic number for file holding an implementation syntax tree *)
+val cmxs_magic_number: string
+ (* Magic number for dynamically-loadable plugins *)
+val cmt_magic_number: string
+ (* Magic number for compiled interface files *)
+
+val max_tag: int
+ (* Biggest tag that can be stored in the header of a regular block. *)
+val lazy_tag : int
+ (* Normally the same as Obj.lazy_tag. Separate definition because
+ of technical reasons for bootstrapping. *)
+val max_young_wosize: int
+ (* Maximal size of arrays that are directly allocated in the
+ minor heap *)
+val stack_threshold: int
+ (* Size in words of safe area at bottom of VM stack,
+ see byterun/config.h *)
+
+val architecture: string
+ (* Name of processor type for the native-code compiler *)
+val model: string
+ (* Name of processor submodel for the native-code compiler *)
+val system: string
+ (* Name of operating system for the native-code compiler *)
+
+val asm: string
+ (* The assembler (and flags) to use for assembling
+ ocamlopt-generated code. *)
+
+val asm_cfi_supported: bool
+ (* Whether assembler understands CFI directives *)
+val with_frame_pointers : bool
+ (* Whether assembler should maintain frame pointers *)
+
+val ext_obj: string
+ (* Extension for object files, e.g. [.o] under Unix. *)
+val ext_asm: string
+ (* Extension for assembler files, e.g. [.s] under Unix. *)
+val ext_lib: string
+ (* Extension for library files, e.g. [.a] under Unix. *)
+val ext_dll: string
+ (* Extension for dynamically-loaded libraries, e.g. [.so] under Unix.*)
+
+val default_executable_name: string
+ (* Name of executable produced by linking if none is given with -o,
+ e.g. [a.out] under Unix. *)
+
+val systhread_supported : bool
+ (* Whether the system thread library is implemented *)
+
+val host : string
+ (* Whether the compiler is a cross-compiler *)
+
+val target : string
+ (* Whether the compiler is a cross-compiler *)
+
+val print_config : out_channel -> unit;;
diff --git a/utils/config.mlp b/utils/config.mlp
new file mode 100644
index 0000000000..c668d13214
--- /dev/null
+++ b/utils/config.mlp
@@ -0,0 +1,143 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(***********************************************************************)
+(** **)
+(** WARNING WARNING WARNING **)
+(** **)
+(** When you change this file, you must make the parallel change **)
+(** in config.mlbuild **)
+(** **)
+(***********************************************************************)
+
+
+(* The main OCaml version string has moved to ../VERSION *)
+let version = Sys.ocaml_version
+
+let standard_library_default = "%%LIBDIR%%"
+
+let standard_library =
+ try
+ Sys.getenv "OCAMLLIB"
+ with Not_found ->
+ try
+ Sys.getenv "CAMLLIB"
+ with Not_found ->
+ standard_library_default
+
+let standard_runtime = "%%BYTERUN%%"
+let ccomp_type = "%%CCOMPTYPE%%"
+let bytecomp_c_compiler = "%%BYTECC%%"
+let bytecomp_c_libraries = "%%BYTECCLIBS%%"
+let native_c_compiler = "%%NATIVECC%%"
+let native_c_libraries = "%%NATIVECCLIBS%%"
+let native_pack_linker = "%%PACKLD%%"
+let ranlib = "%%RANLIBCMD%%"
+let ar = "%%ARCMD%%"
+let cc_profile = "%%CC_PROFILE%%"
+let mkdll = "%%MKDLL%%"
+let mkexe = "%%MKEXE%%"
+let mkmaindll = "%%MKMAINDLL%%"
+
+let exec_magic_number = "Caml1999X011"
+and cmi_magic_number = "Caml1999I020"
+and cmo_magic_number = "Caml1999O011"
+and cma_magic_number = "Caml1999A012"
+and cmx_magic_number = "Caml1999Y015"
+and cmxa_magic_number = "Caml1999Z014"
+and ast_impl_magic_number = "Caml1999M019"
+and ast_intf_magic_number = "Caml1999N018"
+and cmxs_magic_number = "Caml2007D002"
+and cmt_magic_number = "Caml2012T006"
+
+let load_path = ref ([] : string list)
+
+let interface_suffix = ref ".mli"
+
+let max_tag = 245
+(* This is normally the same as in obj.ml, but we have to define it
+ separately because it can differ when we're in the middle of a
+ bootstrapping phase. *)
+let lazy_tag = 246
+
+let max_young_wosize = 256
+let stack_threshold = 256 (* see byterun/config.h *)
+
+let architecture = "%%ARCH%%"
+let model = "%%MODEL%%"
+let system = "%%SYSTEM%%"
+
+let asm = "%%ASM%%"
+let asm_cfi_supported = %%ASM_CFI_SUPPORTED%%
+let with_frame_pointers = %%WITH_FRAME_POINTERS%%
+
+let ext_obj = "%%EXT_OBJ%%"
+let ext_asm = "%%EXT_ASM%%"
+let ext_lib = "%%EXT_LIB%%"
+let ext_dll = "%%EXT_DLL%%"
+
+let host = "%%HOST%%"
+let target = "%%TARGET%%"
+
+let default_executable_name =
+ match Sys.os_type with
+ "Unix" -> "a.out"
+ | "Win32" | "Cygwin" -> "camlprog.exe"
+ | _ -> "camlprog"
+
+let systhread_supported = %%SYSTHREAD_SUPPORT%%;;
+
+let print_config oc =
+ let p name valu = Printf.fprintf oc "%s: %s\n" name valu in
+ let p_bool name valu = Printf.fprintf oc "%s: %B\n" name valu in
+ p "version" version;
+ p "standard_library_default" standard_library_default;
+ p "standard_library" standard_library;
+ p "standard_runtime" standard_runtime;
+ p "ccomp_type" ccomp_type;
+ p "bytecomp_c_compiler" bytecomp_c_compiler;
+ p "bytecomp_c_libraries" bytecomp_c_libraries;
+ p "native_c_compiler" native_c_compiler;
+ p "native_c_libraries" native_c_libraries;
+ p "native_pack_linker" native_pack_linker;
+ p "ranlib" ranlib;
+ p "cc_profile" cc_profile;
+ p "architecture" architecture;
+ p "model" model;
+ p "system" system;
+ p "asm" asm;
+ p_bool "asm_cfi_supported" asm_cfi_supported;
+ p_bool "with_frame_pointers" with_frame_pointers;
+ p "ext_obj" ext_obj;
+ p "ext_asm" ext_asm;
+ p "ext_lib" ext_lib;
+ p "ext_dll" ext_dll;
+ p "os_type" Sys.os_type;
+ p "default_executable_name" default_executable_name;
+ p_bool "systhread_supported" systhread_supported;
+ p "host" host;
+ p "target" target;
+
+ (* print the magic number *)
+ p "exec_magic_number" exec_magic_number;
+ p "cmi_magic_number" cmi_magic_number;
+ p "cmo_magic_number" cmo_magic_number;
+ p "cma_magic_number" cma_magic_number;
+ p "cmx_magic_number" cmx_magic_number;
+ p "cmxa_magic_number" cmxa_magic_number;
+ p "ast_impl_magic_number" ast_impl_magic_number;
+ p "ast_intf_magic_number" ast_intf_magic_number;
+ p "cmxs_magic_number" cmxs_magic_number;
+ p "cmt_magic_number" cmt_magic_number;
+
+ flush oc;
+;;
diff --git a/utils/consistbl.ml b/utils/consistbl.ml
new file mode 100644
index 0000000000..37f6a2b1e6
--- /dev/null
+++ b/utils/consistbl.ml
@@ -0,0 +1,63 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Consistency tables: for checking consistency of module CRCs *)
+
+type t = (string, Digest.t * string) Hashtbl.t
+
+let create () = Hashtbl.create 13
+
+let clear = Hashtbl.clear
+
+exception Inconsistency of string * string * string
+
+exception Not_available of string
+
+let check tbl name crc source =
+ try
+ let (old_crc, old_source) = Hashtbl.find tbl name in
+ if crc <> old_crc then raise(Inconsistency(name, source, old_source))
+ with Not_found ->
+ Hashtbl.add tbl name (crc, source)
+
+let check_noadd tbl name crc source =
+ try
+ let (old_crc, old_source) = Hashtbl.find tbl name in
+ if crc <> old_crc then raise(Inconsistency(name, source, old_source))
+ with Not_found ->
+ raise (Not_available name)
+
+let set tbl name crc source = Hashtbl.add tbl name (crc, source)
+
+let source tbl name = snd (Hashtbl.find tbl name)
+
+let extract l tbl =
+ let l = List.sort_uniq String.compare l in
+ List.fold_left
+ (fun assc name ->
+ try
+ let (crc, _) = Hashtbl.find tbl name in
+ (name, Some crc) :: assc
+ with Not_found ->
+ (name, None) :: assc)
+ [] l
+
+let filter p tbl =
+ let to_remove = ref [] in
+ Hashtbl.iter
+ (fun name (crc, auth) ->
+ if not (p name) then to_remove := name :: !to_remove)
+ tbl;
+ List.iter
+ (fun name ->
+ while Hashtbl.mem tbl name do Hashtbl.remove tbl name done)
+ !to_remove
diff --git a/utils/consistbl.mli b/utils/consistbl.mli
new file mode 100644
index 0000000000..012bd734fa
--- /dev/null
+++ b/utils/consistbl.mli
@@ -0,0 +1,59 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 2002 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Consistency tables: for checking consistency of module CRCs *)
+
+type t
+
+val create: unit -> t
+
+val clear: t -> unit
+
+val check: t -> string -> Digest.t -> string -> unit
+ (* [check tbl name crc source]
+ checks consistency of ([name], [crc]) with infos previously
+ stored in [tbl]. If no CRC was previously associated with
+ [name], record ([name], [crc]) in [tbl].
+ [source] is the name of the file from which the information
+ comes from. This is used for error reporting. *)
+
+val check_noadd: t -> string -> Digest.t -> string -> unit
+ (* Same as [check], but raise [Not_available] if no CRC was previously
+ associated with [name]. *)
+
+val set: t -> string -> Digest.t -> string -> unit
+ (* [set tbl name crc source] forcefully associates [name] with
+ [crc] in [tbl], even if [name] already had a different CRC
+ associated with [name] in [tbl]. *)
+
+val source: t -> string -> string
+ (* [source tbl name] returns the file name associated with [name]
+ if the latter has an associated CRC in [tbl].
+ Raise [Not_found] otherwise. *)
+
+val extract: string list -> t -> (string * Digest.t option) list
+ (* [extract tbl names] returns an associative list mapping each string
+ in [names] to the CRC associated with it in [tbl]. If no CRC is
+ associated with a name then it is mapped to [None]. *)
+
+val filter: (string -> bool) -> t -> unit
+ (* [filter pred tbl] removes from [tbl] table all (name, CRC) pairs
+ such that [pred name] is [false]. *)
+
+exception Inconsistency of string * string * string
+ (* Raised by [check] when a CRC mismatch is detected.
+ First string is the name of the compilation unit.
+ Second string is the source that caused the inconsistency.
+ Third string is the source that set the CRC. *)
+
+exception Not_available of string
+ (* Raised by [check_noadd] when a name doesn't have an associated CRC. *)
diff --git a/utils/misc.ml b/utils/misc.ml
new file mode 100644
index 0000000000..b6dba3db7d
--- /dev/null
+++ b/utils/misc.ml
@@ -0,0 +1,516 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Errors *)
+
+exception Fatal_error
+
+let fatal_error msg =
+ prerr_string ">> Fatal error: "; prerr_endline msg; raise Fatal_error
+
+(* Exceptions *)
+
+let try_finally work cleanup =
+ let result = (try work () with e -> cleanup (); raise e) in
+ cleanup ();
+ result
+;;
+
+(* List functions *)
+
+let rec map_end f l1 l2 =
+ match l1 with
+ [] -> l2
+ | hd::tl -> f hd :: map_end f tl l2
+
+let rec map_left_right f = function
+ [] -> []
+ | hd::tl -> let res = f hd in res :: map_left_right f tl
+
+let rec for_all2 pred l1 l2 =
+ match (l1, l2) with
+ ([], []) -> true
+ | (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2
+ | (_, _) -> false
+
+let rec replicate_list elem n =
+ if n <= 0 then [] else elem :: replicate_list elem (n-1)
+
+let rec list_remove x = function
+ [] -> []
+ | hd :: tl ->
+ if hd = x then tl else hd :: list_remove x tl
+
+let rec split_last = function
+ [] -> assert false
+ | [x] -> ([], x)
+ | hd :: tl ->
+ let (lst, last) = split_last tl in
+ (hd :: lst, last)
+
+let rec samelist pred l1 l2 =
+ match (l1, l2) with
+ | ([], []) -> true
+ | (hd1 :: tl1, hd2 :: tl2) -> pred hd1 hd2 && samelist pred tl1 tl2
+ | (_, _) -> false
+
+(* Options *)
+
+let may f = function
+ Some x -> f x
+ | None -> ()
+
+let may_map f = function
+ Some x -> Some (f x)
+ | None -> None
+
+(* File functions *)
+
+let find_in_path path name =
+ if not (Filename.is_implicit name) then
+ if Sys.file_exists name then name else raise Not_found
+ else begin
+ let rec try_dir = function
+ [] -> raise Not_found
+ | dir::rem ->
+ let fullname = Filename.concat dir name in
+ if Sys.file_exists fullname then fullname else try_dir rem
+ in try_dir path
+ end
+
+let find_in_path_rel path name =
+ let rec simplify s =
+ let open Filename in
+ let base = basename s in
+ let dir = dirname s in
+ if dir = s then dir
+ else if base = current_dir_name then simplify dir
+ else concat (simplify dir) base
+ in
+ let rec try_dir = function
+ [] -> raise Not_found
+ | dir::rem ->
+ let fullname = simplify (Filename.concat dir name) in
+ if Sys.file_exists fullname then fullname else try_dir rem
+ in try_dir path
+
+let find_in_path_uncap path name =
+ let uname = String.uncapitalize_ascii name in
+ let rec try_dir = function
+ [] -> raise Not_found
+ | dir::rem ->
+ let fullname = Filename.concat dir name
+ and ufullname = Filename.concat dir uname in
+ if Sys.file_exists ufullname then ufullname
+ else if Sys.file_exists fullname then fullname
+ else try_dir rem
+ in try_dir path
+
+let remove_file filename =
+ try
+ Sys.remove filename
+ with Sys_error msg ->
+ ()
+
+(* Expand a -I option: if it starts with +, make it relative to the standard
+ library directory *)
+
+let expand_directory alt s =
+ if String.length s > 0 && s.[0] = '+'
+ then Filename.concat alt
+ (String.sub s 1 (String.length s - 1))
+ else s
+
+(* Hashtable functions *)
+
+let create_hashtable size init =
+ let tbl = Hashtbl.create size in
+ List.iter (fun (key, data) -> Hashtbl.add tbl key data) init;
+ tbl
+
+(* File copy *)
+
+let copy_file ic oc =
+ let buff = Bytes.create 0x1000 in
+ let rec copy () =
+ let n = input ic buff 0 0x1000 in
+ if n = 0 then () else (output oc buff 0 n; copy())
+ in copy()
+
+let copy_file_chunk ic oc len =
+ let buff = Bytes.create 0x1000 in
+ let rec copy n =
+ if n <= 0 then () else begin
+ let r = input ic buff 0 (min n 0x1000) in
+ if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r))
+ end
+ in copy len
+
+let string_of_file ic =
+ let b = Buffer.create 0x10000 in
+ let buff = Bytes.create 0x1000 in
+ let rec copy () =
+ let n = input ic buff 0 0x1000 in
+ if n = 0 then Buffer.contents b else
+ (Buffer.add_subbytes b buff 0 n; copy())
+ in copy()
+
+(* Integer operations *)
+
+let rec log2 n =
+ if n <= 1 then 0 else 1 + log2(n asr 1)
+
+let align n a =
+ if n >= 0 then (n + a - 1) land (-a) else n land (-a)
+
+let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0
+
+let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0
+
+let no_overflow_mul a b = b <> 0 && (a * b) / b = a
+
+let no_overflow_lsl a k =
+ 0 <= k && k < Sys.word_size && min_int asr k <= a && a <= max_int asr k
+
+(* String operations *)
+
+let chop_extension_if_any fname =
+ try Filename.chop_extension fname with Invalid_argument _ -> fname
+
+let chop_extensions file =
+ let dirname = Filename.dirname file and basename = Filename.basename file in
+ try
+ let pos = String.index basename '.' in
+ let basename = String.sub basename 0 pos in
+ if Filename.is_implicit file && dirname = Filename.current_dir_name then
+ basename
+ else
+ Filename.concat dirname basename
+ with Not_found -> file
+
+let search_substring pat str start =
+ let rec search i j =
+ if j >= String.length pat then i
+ else if i + j >= String.length str then raise Not_found
+ else if str.[i + j] = pat.[j] then search i (j+1)
+ else search (i+1) 0
+ in search start 0
+
+let replace_substring ~before ~after str =
+ let rec search acc curr =
+ match search_substring before str curr with
+ | next ->
+ let prefix = String.sub str curr (next - curr) in
+ search (prefix :: acc) (next + String.length before)
+ | exception Not_found ->
+ let suffix = String.sub str curr (String.length str - curr) in
+ List.rev (suffix :: acc)
+ in String.concat after (search [] 0)
+
+let rev_split_words s =
+ let rec split1 res i =
+ if i >= String.length s then res else begin
+ match s.[i] with
+ ' ' | '\t' | '\r' | '\n' -> split1 res (i+1)
+ | _ -> split2 res i (i+1)
+ end
+ and split2 res i j =
+ if j >= String.length s then String.sub s i (j-i) :: res else begin
+ match s.[j] with
+ ' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1)
+ | _ -> split2 res i (j+1)
+ end
+ in split1 [] 0
+
+let get_ref r =
+ let v = !r in
+ r := []; v
+
+let fst3 (x, _, _) = x
+let snd3 (_,x,_) = x
+let thd3 (_,_,x) = x
+
+let fst4 (x, _, _, _) = x
+let snd4 (_,x,_, _) = x
+let thd4 (_,_,x,_) = x
+let for4 (_,_,_,x) = x
+
+
+module LongString = struct
+ type t = bytes array
+
+ let create str_size =
+ let tbl_size = str_size / Sys.max_string_length + 1 in
+ let tbl = Array.make tbl_size Bytes.empty in
+ for i = 0 to tbl_size - 2 do
+ tbl.(i) <- Bytes.create Sys.max_string_length;
+ done;
+ tbl.(tbl_size - 1) <- Bytes.create (str_size mod Sys.max_string_length);
+ tbl
+
+ let length tbl =
+ let tbl_size = Array.length tbl in
+ Sys.max_string_length * (tbl_size - 1) + Bytes.length tbl.(tbl_size - 1)
+
+ let get tbl ind =
+ Bytes.get tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length)
+
+ let set tbl ind c =
+ Bytes.set tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length)
+ c
+
+ let blit src srcoff dst dstoff len =
+ for i = 0 to len - 1 do
+ set dst (dstoff + i) (get src (srcoff + i))
+ done
+
+ let output oc tbl pos len =
+ for i = pos to pos + len - 1 do
+ output_char oc (get tbl i)
+ done
+
+ let unsafe_blit_to_bytes src srcoff dst dstoff len =
+ for i = 0 to len - 1 do
+ Bytes.unsafe_set dst (dstoff + i) (get src (srcoff + i))
+ done
+
+ let input_bytes ic len =
+ let tbl = create len in
+ Array.iter (fun str -> really_input ic str 0 (Bytes.length str)) tbl;
+ tbl
+end
+
+
+let edit_distance a b cutoff =
+ let la, lb = String.length a, String.length b in
+ let cutoff =
+ (* using max_int for cutoff would cause overflows in (i + cutoff + 1);
+ we bring it back to the (max la lb) worstcase *)
+ min (max la lb) cutoff in
+ if abs (la - lb) > cutoff then None
+ else begin
+ (* initialize with 'cutoff + 1' so that not-yet-written-to cases have
+ the worst possible cost; this is useful when computing the cost of
+ a case just at the boundary of the cutoff diagonal. *)
+ let m = Array.make_matrix (la + 1) (lb + 1) (cutoff + 1) in
+ m.(0).(0) <- 0;
+ for i = 1 to la do
+ m.(i).(0) <- i;
+ done;
+ for j = 1 to lb do
+ m.(0).(j) <- j;
+ done;
+ for i = 1 to la do
+ for j = max 1 (i - cutoff - 1) to min lb (i + cutoff + 1) do
+ let cost = if a.[i-1] = b.[j-1] then 0 else 1 in
+ let best =
+ (* insert, delete or substitute *)
+ min (1 + min m.(i-1).(j) m.(i).(j-1)) (m.(i-1).(j-1) + cost)
+ in
+ let best =
+ (* swap two adjacent letters; we use "cost" again in case of
+ a swap between two identical letters; this is slightly
+ redundant as this is a double-substitution case, but it
+ was done this way in most online implementations and
+ imitation has its virtues *)
+ if not (i > 1 && j > 1 && a.[i-1] = b.[j-2] && a.[i-2] = b.[j-1])
+ then best
+ else min best (m.(i-2).(j-2) + cost)
+ in
+ m.(i).(j) <- best
+ done;
+ done;
+ let result = m.(la).(lb) in
+ if result > cutoff
+ then None
+ else Some result
+ end
+
+let spellcheck env name =
+ let cutoff =
+ match String.length name with
+ | 1 | 2 -> 0
+ | 3 | 4 -> 1
+ | 5 | 6 -> 2
+ | _ -> 3
+ in
+ let compare target acc head =
+ match edit_distance target head cutoff with
+ | None -> acc
+ | Some dist ->
+ let (best_choice, best_dist) = acc in
+ if dist < best_dist then ([head], dist)
+ else if dist = best_dist then (head :: best_choice, dist)
+ else acc
+ in
+ fst (List.fold_left (compare name) ([], max_int) env)
+
+let did_you_mean ppf get_choices =
+ (* flush now to get the error report early, in the (unheard of) case
+ where the search in the get_choices function would take a bit of
+ time; in the worst case, the user has seen the error, she can
+ interrupt the process before the spell-checking terminates. *)
+ Format.fprintf ppf "@?";
+ match get_choices () with
+ | [] -> ()
+ | choices ->
+ let rest, last = split_last choices in
+ Format.fprintf ppf "@\nHint: Did you mean %s%s%s?"
+ (String.concat ", " rest)
+ (if rest = [] then "" else " or ")
+ last
+
+(* split a string [s] at every char [c], and return the list of sub-strings *)
+let split s c =
+ let len = String.length s in
+ let rec iter pos to_rev =
+ if pos = len then List.rev ("" :: to_rev) else
+ match try
+ Some ( String.index_from s pos c )
+ with Not_found -> None
+ with
+ Some pos2 ->
+ if pos2 = pos then iter (pos+1) ("" :: to_rev) else
+ iter (pos2+1) ((String.sub s pos (pos2-pos)) :: to_rev)
+ | None -> List.rev ( String.sub s pos (len-pos) :: to_rev )
+ in
+ iter 0 []
+
+let cut_at s c =
+ let pos = String.index s c in
+ String.sub s 0 pos, String.sub s (pos+1) (String.length s - pos - 1)
+
+
+module StringSet = Set.Make(struct type t = string let compare = compare end)
+module StringMap = Map.Make(struct type t = string let compare = compare end)
+
+(* Color handling *)
+module Color = struct
+ (* use ANSI color codes, see https://en.wikipedia.org/wiki/ANSI_escape_code *)
+ type color =
+ | Black
+ | Red
+ | Green
+ | Yellow
+ | Blue
+ | Magenta
+ | Cyan
+ | White
+ ;;
+
+ type style =
+ | FG of color (* foreground *)
+ | BG of color (* background *)
+ | Bold
+ | Reset
+
+ let ansi_of_color = function
+ | Black -> "0"
+ | Red -> "1"
+ | Green -> "2"
+ | Yellow -> "3"
+ | Blue -> "4"
+ | Magenta -> "5"
+ | Cyan -> "6"
+ | White -> "7"
+
+ let code_of_style = function
+ | FG c -> "3" ^ ansi_of_color c
+ | BG c -> "4" ^ ansi_of_color c
+ | Bold -> "1"
+ | Reset -> "0"
+
+ let ansi_of_style_l l =
+ let s = match l with
+ | [] -> code_of_style Reset
+ | [s] -> code_of_style s
+ | _ -> String.concat ";" (List.map code_of_style l)
+ in
+ "\x1b[" ^ s ^ "m"
+
+ type styles = {
+ error: style list;
+ warning: style list;
+ loc: style list;
+ }
+
+ let default_styles = {
+ warning = [Bold; FG Magenta];
+ error = [Bold; FG Red];
+ loc = [Bold];
+ }
+
+ let cur_styles = ref default_styles
+ let get_styles () = !cur_styles
+ let set_styles s = cur_styles := s
+
+ (* map a tag to a style, if the tag is known.
+ @raise Not_found otherwise *)
+ let style_of_tag s = match s with
+ | "error" -> (!cur_styles).error
+ | "warning" -> (!cur_styles).warning
+ | "loc" -> (!cur_styles).loc
+ | _ -> raise Not_found
+
+ let color_enabled = ref true
+
+ (* either prints the tag of [s] or delegate to [or_else] *)
+ let mark_open_tag ~or_else s =
+ try
+ let style = style_of_tag s in
+ if !color_enabled then ansi_of_style_l style else ""
+ with Not_found -> or_else s
+
+ let mark_close_tag ~or_else s =
+ try
+ let _ = style_of_tag s in
+ if !color_enabled then ansi_of_style_l [Reset] else ""
+ with Not_found -> or_else s
+
+ (* add color handling to formatter [ppf] *)
+ let set_color_tag_handling ppf =
+ let open Format in
+ let functions = pp_get_formatter_tag_functions ppf () in
+ let functions' = {functions with
+ mark_open_tag=(mark_open_tag ~or_else:functions.mark_open_tag);
+ mark_close_tag=(mark_close_tag ~or_else:functions.mark_close_tag);
+ } in
+ pp_set_mark_tags ppf true; (* enable tags *)
+ pp_set_formatter_tag_functions ppf functions'
+
+ external isatty : out_channel -> bool = "caml_sys_isatty"
+
+ (* reasonable heuristic on whether colors should be enabled *)
+ let should_enable_color () =
+ let term = try Sys.getenv "TERM" with Not_found -> "" in
+ term <> "dumb"
+ && term <> ""
+ && isatty stderr
+
+ let setup =
+ let first = ref true in (* initialize only once *)
+ let formatter_l =
+ [Format.std_formatter; Format.err_formatter; Format.str_formatter]
+ in
+ fun o ->
+ if !first then (
+ first := false;
+ Format.set_mark_tags true;
+ List.iter set_color_tag_handling formatter_l;
+ color_enabled := (match o with
+ | Clflags.Always -> true
+ | Clflags.Auto -> should_enable_color ()
+ | Clflags.Never -> false
+ )
+ );
+ ()
+end
diff --git a/utils/misc.mli b/utils/misc.mli
new file mode 100644
index 0000000000..cffa5062cd
--- /dev/null
+++ b/utils/misc.mli
@@ -0,0 +1,237 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Miscellaneous useful types and functions *)
+
+val fatal_error: string -> 'a
+exception Fatal_error
+
+val try_finally : (unit -> 'a) -> (unit -> unit) -> 'a;;
+
+val map_end: ('a -> 'b) -> 'a list -> 'b list -> 'b list
+ (* [map_end f l t] is [map f l @ t], just more efficient. *)
+val map_left_right: ('a -> 'b) -> 'a list -> 'b list
+ (* Like [List.map], with guaranteed left-to-right evaluation order *)
+val for_all2: ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
+ (* Same as [List.for_all] but for a binary predicate.
+ In addition, this [for_all2] never fails: given two lists
+ with different lengths, it returns false. *)
+val replicate_list: 'a -> int -> 'a list
+ (* [replicate_list elem n] is the list with [n] elements
+ all identical to [elem]. *)
+val list_remove: 'a -> 'a list -> 'a list
+ (* [list_remove x l] returns a copy of [l] with the first
+ element equal to [x] removed. *)
+val split_last: 'a list -> 'a list * 'a
+ (* Return the last element and the other elements of the given list. *)
+val samelist: ('a -> 'a -> bool) -> 'a list -> 'a list -> bool
+ (* Like [List.for_all2] but returns [false] if the two
+ lists have different length. *)
+
+val may: ('a -> unit) -> 'a option -> unit
+val may_map: ('a -> 'b) -> 'a option -> 'b option
+
+val find_in_path: string list -> string -> string
+ (* Search a file in a list of directories. *)
+val find_in_path_rel: string list -> string -> string
+ (* Search a relative file in a list of directories. *)
+val find_in_path_uncap: string list -> string -> string
+ (* Same, but search also for uncapitalized name, i.e.
+ if name is Foo.ml, allow /path/Foo.ml and /path/foo.ml
+ to match. *)
+val remove_file: string -> unit
+ (* Delete the given file if it exists. Never raise an error. *)
+val expand_directory: string -> string -> string
+ (* [expand_directory alt file] eventually expands a [+] at the
+ beginning of file into [alt] (an alternate root directory) *)
+
+val create_hashtable: int -> ('a * 'b) list -> ('a, 'b) Hashtbl.t
+ (* Create a hashtable of the given size and fills it with the
+ given bindings. *)
+
+val copy_file: in_channel -> out_channel -> unit
+ (* [copy_file ic oc] reads the contents of file [ic] and copies
+ them to [oc]. It stops when encountering EOF on [ic]. *)
+val copy_file_chunk: in_channel -> out_channel -> int -> unit
+ (* [copy_file_chunk ic oc n] reads [n] bytes from [ic] and copies
+ them to [oc]. It raises [End_of_file] when encountering
+ EOF on [ic]. *)
+val string_of_file: in_channel -> string
+ (* [string_of_file ic] reads the contents of file [ic] and copies
+ them to a string. It stops when encountering EOF on [ic]. *)
+val log2: int -> int
+ (* [log2 n] returns [s] such that [n = 1 lsl s]
+ if [n] is a power of 2*)
+val align: int -> int -> int
+ (* [align n a] rounds [n] upwards to a multiple of [a]
+ (a power of 2). *)
+val no_overflow_add: int -> int -> bool
+ (* [no_overflow_add n1 n2] returns [true] if the computation of
+ [n1 + n2] does not overflow. *)
+val no_overflow_sub: int -> int -> bool
+ (* [no_overflow_add n1 n2] returns [true] if the computation of
+ [n1 - n2] does not overflow. *)
+val no_overflow_mul: int -> int -> bool
+ (* [no_overflow_mul n1 n2] returns [true] if the computation of
+ [n1 * n2] does not overflow. *)
+val no_overflow_lsl: int -> int -> bool
+ (* [no_overflow_lsl n k] returns [true] if the computation of
+ [n lsl k] does not overflow. *)
+
+val chop_extension_if_any: string -> string
+ (* Like Filename.chop_extension but returns the initial file
+ name if it has no extension *)
+
+val chop_extensions: string -> string
+ (* Return the given file name without its extensions. The extensions
+ is the longest suffix starting with a period and not including
+ a directory separator, [.xyz.uvw] for instance.
+
+ Return the given name if it does not contain an extension. *)
+
+val search_substring: string -> string -> int -> int
+ (* [search_substring pat str start] returns the position of the first
+ occurrence of string [pat] in string [str]. Search starts
+ at offset [start] in [str]. Raise [Not_found] if [pat]
+ does not occur. *)
+
+val replace_substring: before:string -> after:string -> string -> string
+ (* [search_substring ~before ~after str] replaces all
+ occurences of [before] with [after] in [str] and returns
+ the resulting string. *)
+
+val rev_split_words: string -> string list
+ (* [rev_split_words s] splits [s] in blank-separated words, and return
+ the list of words in reverse order. *)
+
+val get_ref: 'a list ref -> 'a list
+ (* [get_ref lr] returns the content of the list reference [lr] and reset
+ its content to the empty list. *)
+
+
+val fst3: 'a * 'b * 'c -> 'a
+val snd3: 'a * 'b * 'c -> 'b
+val thd3: 'a * 'b * 'c -> 'c
+
+val fst4: 'a * 'b * 'c * 'd -> 'a
+val snd4: 'a * 'b * 'c * 'd -> 'b
+val thd4: 'a * 'b * 'c * 'd -> 'c
+val for4: 'a * 'b * 'c * 'd -> 'd
+
+module LongString :
+ sig
+ type t = bytes array
+ val create : int -> t
+ val length : t -> int
+ val get : t -> int -> char
+ val set : t -> int -> char -> unit
+ val blit : t -> int -> t -> int -> int -> unit
+ val output : out_channel -> t -> int -> int -> unit
+ val unsafe_blit_to_bytes : t -> int -> bytes -> int -> int -> unit
+ val input_bytes : in_channel -> int -> t
+ end
+
+val edit_distance : string -> string -> int -> int option
+(** [edit_distance a b cutoff] computes the edit distance between
+ strings [a] and [b]. To help efficiency, it uses a cutoff: if the
+ distance [d] is smaller than [cutoff], it returns [Some d], else
+ [None].
+
+ The distance algorithm currently used is Damerau-Levenshtein: it
+ computes the number of insertion, deletion, substitution of
+ letters, or swapping of adjacent letters to go from one word to the
+ other. The particular algorithm may change in the future.
+*)
+
+val spellcheck : string list -> string -> string list
+(** [spellcheck env name] takes a list of names [env] that exist in
+ the current environment and an erroneous [name], and returns a
+ list of suggestions taken from [env], that are close enough to
+ [name] that it may be a typo for one of them. *)
+
+val did_you_mean : Format.formatter -> (unit -> string list) -> unit
+(** [did_you_mean ppf get_choices] hints that the user may have meant
+ one of the option returned by calling [get_choices]. It does nothing
+ if the returned list is empty.
+
+ The [unit -> ...] thunking is meant to delay any potentially-slow
+ computation (typically computing edit-distance with many things
+ from the current environment) to when the hint message is to be
+ printed. You should print an understandable error message before
+ calling [did_you_mean], so that users get a clear notification of
+ the failure even if producing the hint is slow.
+*)
+
+val split : string -> char -> string list
+(** [String.split string char] splits the string [string] at every char
+ [char], and returns the list of sub-strings between the chars.
+ [String.concat (String.make 1 c) (String.split s c)] is the identity.
+ @since 4.01
+ *)
+
+val cut_at : string -> char -> string * string
+(** [String.cut_at s c] returns a pair containing the sub-string before
+ the first occurrence of [c] in [s], and the sub-string after the
+ first occurrence of [c] in [s].
+ [let (before, after) = String.cut_at s c in
+ before ^ String.make 1 c ^ after] is the identity if [s] contains [c].
+
+ Raise [Not_found] if the character does not appear in the string
+ @since 4.01
+*)
+
+
+module StringSet: Set.S with type elt = string
+module StringMap: Map.S with type key = string
+(* TODO: replace all custom instantiations of StringSet/StringMap in various
+ compiler modules with this one. *)
+
+(* Color handling *)
+module Color : sig
+ type color =
+ | Black
+ | Red
+ | Green
+ | Yellow
+ | Blue
+ | Magenta
+ | Cyan
+ | White
+ ;;
+
+ type style =
+ | FG of color (* foreground *)
+ | BG of color (* background *)
+ | Bold
+ | Reset
+
+ val ansi_of_style_l : style list -> string
+ (* ANSI escape sequence for the given style *)
+
+ type styles = {
+ error: style list;
+ warning: style list;
+ loc: style list;
+ }
+
+ val default_styles: styles
+ val get_styles: unit -> styles
+ val set_styles: styles -> unit
+
+ val setup : Clflags.color_setting -> unit
+ (* [setup opt] will enable or disable color handling on standard formatters
+ according to the value of color setting [opt].
+ Only the first call to this function has an effect. *)
+
+ val set_color_tag_handling : Format.formatter -> unit
+ (* adds functions to support color tags to the given formatter. *)
+end
diff --git a/utils/tbl.ml b/utils/tbl.ml
new file mode 100644
index 0000000000..265bf3b8c0
--- /dev/null
+++ b/utils/tbl.ml
@@ -0,0 +1,112 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+type ('a, 'b) t =
+ Empty
+ | Node of ('a, 'b) t * 'a * 'b * ('a, 'b) t * int
+
+let empty = Empty
+
+let height = function
+ Empty -> 0
+ | Node(_,_,_,_,h) -> h
+
+let create l x d r =
+ let hl = height l and hr = height r in
+ Node(l, x, d, r, (if hl >= hr then hl + 1 else hr + 1))
+
+let bal l x d r =
+ let hl = height l and hr = height r in
+ if hl > hr + 1 then
+ match l with
+ | Node (ll, lv, ld, lr, _) when height ll >= height lr ->
+ create ll lv ld (create lr x d r)
+ | Node (ll, lv, ld, Node (lrl, lrv, lrd, lrr, _), _) ->
+ create (create ll lv ld lrl) lrv lrd (create lrr x d r)
+ | _ -> assert false
+ else if hr > hl + 1 then
+ match r with
+ | Node (rl, rv, rd, rr, _) when height rr >= height rl ->
+ create (create l x d rl) rv rd rr
+ | Node (Node (rll, rlv, rld, rlr, _), rv, rd, rr, _) ->
+ create (create l x d rll) rlv rld (create rlr rv rd rr)
+ | _ -> assert false
+ else
+ create l x d r
+
+let rec add x data = function
+ Empty ->
+ Node(Empty, x, data, Empty, 1)
+ | Node(l, v, d, r, h) ->
+ let c = compare x v in
+ if c = 0 then
+ Node(l, x, data, r, h)
+ else if c < 0 then
+ bal (add x data l) v d r
+ else
+ bal l v d (add x data r)
+
+let rec find x = function
+ Empty ->
+ raise Not_found
+ | Node(l, v, d, r, _) ->
+ let c = compare x v in
+ if c = 0 then d
+ else find x (if c < 0 then l else r)
+
+let rec mem x = function
+ Empty -> false
+ | Node(l, v, d, r, _) ->
+ let c = compare x v in
+ c = 0 || mem x (if c < 0 then l else r)
+
+let rec merge t1 t2 =
+ match (t1, t2) with
+ (Empty, t) -> t
+ | (t, Empty) -> t
+ | (Node(l1, v1, d1, r1, h1), Node(l2, v2, d2, r2, h2)) ->
+ bal l1 v1 d1 (bal (merge r1 l2) v2 d2 r2)
+
+let rec remove x = function
+ Empty ->
+ Empty
+ | Node(l, v, d, r, h) ->
+ let c = compare x v in
+ if c = 0 then
+ merge l r
+ else if c < 0 then
+ bal (remove x l) v d r
+ else
+ bal l v d (remove x r)
+
+let rec iter f = function
+ Empty -> ()
+ | Node(l, v, d, r, _) ->
+ iter f l; f v d; iter f r
+
+let rec map f = function
+ Empty -> Empty
+ | Node(l, v, d, r, h) -> Node(map f l, v, f v d, map f r, h)
+
+let rec fold f m accu =
+ match m with
+ | Empty -> accu
+ | Node(l, v, d, r, _) ->
+ fold f r (f v d (fold f l accu))
+
+open Format
+
+let print print_key print_data ppf tbl =
+ let print_tbl ppf tbl =
+ iter (fun k d -> fprintf ppf "@[<2>%a ->@ %a;@]@ " print_key k print_data d)
+ tbl in
+ fprintf ppf "@[<hv 2>[[%a]]@]" print_tbl tbl
diff --git a/utils/tbl.mli b/utils/tbl.mli
new file mode 100644
index 0000000000..3167aa9868
--- /dev/null
+++ b/utils/tbl.mli
@@ -0,0 +1,30 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Association tables from any ordered type to any type.
+ We use the generic ordering to compare keys. *)
+
+type ('a, 'b) t
+
+val empty: ('a, 'b) t
+val add: 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t
+val find: 'a -> ('a, 'b) t -> 'b
+val mem: 'a -> ('a, 'b) t -> bool
+val remove: 'a -> ('a, 'b) t -> ('a, 'b) t
+val iter: ('a -> 'b -> unit) -> ('a, 'b) t -> unit
+val map: ('a -> 'b -> 'c) -> ('a, 'b) t -> ('a, 'c) t
+val fold: ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
+
+open Format
+
+val print: (formatter -> 'a -> unit) -> (formatter -> 'b -> unit) ->
+ formatter -> ('a, 'b) t -> unit
diff --git a/utils/terminfo.ml b/utils/terminfo.ml
new file mode 100644
index 0000000000..509e495c5d
--- /dev/null
+++ b/utils/terminfo.ml
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Basic interface to the terminfo database *)
+
+type status =
+ | Uninitialised
+ | Bad_term
+ | Good_term of int
+;;
+external setup : out_channel -> status = "caml_terminfo_setup";;
+external backup : int -> unit = "caml_terminfo_backup";;
+external standout : bool -> unit = "caml_terminfo_standout";;
+external resume : int -> unit = "caml_terminfo_resume";;
diff --git a/utils/terminfo.mli b/utils/terminfo.mli
new file mode 100644
index 0000000000..3e8ab512fe
--- /dev/null
+++ b/utils/terminfo.mli
@@ -0,0 +1,23 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1996 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* Basic interface to the terminfo database *)
+
+type status =
+ | Uninitialised
+ | Bad_term
+ | Good_term of int (* number of lines of the terminal *)
+;;
+external setup : out_channel -> status = "caml_terminfo_setup";;
+external backup : int -> unit = "caml_terminfo_backup";;
+external standout : bool -> unit = "caml_terminfo_standout";;
+external resume : int -> unit = "caml_terminfo_resume";;
diff --git a/utils/warnings.ml b/utils/warnings.ml
new file mode 100644
index 0000000000..b2d5e573cc
--- /dev/null
+++ b/utils/warnings.ml
@@ -0,0 +1,504 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis && Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+(* When you change this, you need to update the documentation:
+ - man/ocamlc.m in ocaml
+ - man/ocamlopt.m in ocaml
+ - manual/cmds/comp.etex in the doc sources
+ - manual/cmds/native.etex in the doc sources
+*)
+
+type t =
+ | Comment_start (* 1 *)
+ | Comment_not_end (* 2 *)
+ | Deprecated of string (* 3 *)
+ | Fragile_match of string (* 4 *)
+ | Partial_application (* 5 *)
+ | Labels_omitted of string list (* 6 *)
+ | Method_override of string list (* 7 *)
+ | Partial_match of string (* 8 *)
+ | Non_closed_record_pattern of string (* 9 *)
+ | Statement_type (* 10 *)
+ | Unused_match (* 11 *)
+ | Unused_pat (* 12 *)
+ | Instance_variable_override of string list (* 13 *)
+ | Illegal_backslash (* 14 *)
+ | Implicit_public_methods of string list (* 15 *)
+ | Unerasable_optional_argument (* 16 *)
+ | Undeclared_virtual_method of string (* 17 *)
+ | Not_principal of string (* 18 *)
+ | Without_principality of string (* 19 *)
+ | Unused_argument (* 20 *)
+ | Nonreturning_statement (* 21 *)
+ | Preprocessor of string (* 22 *)
+ | Useless_record_with (* 23 *)
+ | Bad_module_name of string (* 24 *)
+ | All_clauses_guarded (* 25 *)
+ | Unused_var of string (* 26 *)
+ | Unused_var_strict of string (* 27 *)
+ | Wildcard_arg_to_constant_constr (* 28 *)
+ | Eol_in_string (* 29 *)
+ | Duplicate_definitions of string * string * string * string (*30 *)
+ | Multiple_definition of string * string * string (* 31 *)
+ | Unused_value_declaration of string (* 32 *)
+ | Unused_open of string (* 33 *)
+ | Unused_type_declaration of string (* 34 *)
+ | Unused_for_index of string (* 35 *)
+ | Unused_ancestor of string (* 36 *)
+ | Unused_constructor of string * bool * bool (* 37 *)
+ | Unused_extension of string * bool * bool (* 38 *)
+ | Unused_rec_flag (* 39 *)
+ | Name_out_of_scope of string * string list * bool (* 40 *)
+ | Ambiguous_name of string list * string list * bool (* 41 *)
+ | Disambiguated_name of string (* 42 *)
+ | Nonoptional_label of string (* 43 *)
+ | Open_shadow_identifier of string * string (* 44 *)
+ | Open_shadow_label_constructor of string * string (* 45 *)
+ | Bad_env_variable of string * string (* 46 *)
+ | Attribute_payload of string * string (* 47 *)
+ | Eliminated_optional_arguments of string list (* 48 *)
+ | No_cmi_file of string (* 49 *)
+ | Bad_docstring of bool (* 50 *)
+ | Expect_tailcall (* 51 *)
+;;
+
+(* If you remove a warning, leave a hole in the numbering. NEVER change
+ the numbers of existing warnings.
+ If you add a new warning, add it at the end with a new number;
+ do NOT reuse one of the holes.
+*)
+
+let number = function
+ | Comment_start -> 1
+ | Comment_not_end -> 2
+ | Deprecated _ -> 3
+ | Fragile_match _ -> 4
+ | Partial_application -> 5
+ | Labels_omitted _ -> 6
+ | Method_override _ -> 7
+ | Partial_match _ -> 8
+ | Non_closed_record_pattern _ -> 9
+ | Statement_type -> 10
+ | Unused_match -> 11
+ | Unused_pat -> 12
+ | Instance_variable_override _ -> 13
+ | Illegal_backslash -> 14
+ | Implicit_public_methods _ -> 15
+ | Unerasable_optional_argument -> 16
+ | Undeclared_virtual_method _ -> 17
+ | Not_principal _ -> 18
+ | Without_principality _ -> 19
+ | Unused_argument -> 20
+ | Nonreturning_statement -> 21
+ | Preprocessor _ -> 22
+ | Useless_record_with -> 23
+ | Bad_module_name _ -> 24
+ | All_clauses_guarded -> 25
+ | Unused_var _ -> 26
+ | Unused_var_strict _ -> 27
+ | Wildcard_arg_to_constant_constr -> 28
+ | Eol_in_string -> 29
+ | Duplicate_definitions _ -> 30
+ | Multiple_definition _ -> 31
+ | Unused_value_declaration _ -> 32
+ | Unused_open _ -> 33
+ | Unused_type_declaration _ -> 34
+ | Unused_for_index _ -> 35
+ | Unused_ancestor _ -> 36
+ | Unused_constructor _ -> 37
+ | Unused_extension _ -> 38
+ | Unused_rec_flag -> 39
+ | Name_out_of_scope _ -> 40
+ | Ambiguous_name _ -> 41
+ | Disambiguated_name _ -> 42
+ | Nonoptional_label _ -> 43
+ | Open_shadow_identifier _ -> 44
+ | Open_shadow_label_constructor _ -> 45
+ | Bad_env_variable _ -> 46
+ | Attribute_payload _ -> 47
+ | Eliminated_optional_arguments _ -> 48
+ | No_cmi_file _ -> 49
+ | Bad_docstring _ -> 50
+ | Expect_tailcall -> 51
+;;
+
+let last_warning_number = 51
+(* Must be the max number returned by the [number] function. *)
+
+let letter = function
+ | 'a' ->
+ let rec loop i = if i = 0 then [] else i :: loop (i - 1) in
+ loop last_warning_number
+ | 'b' -> []
+ | 'c' -> [1; 2]
+ | 'd' -> [3]
+ | 'e' -> [4]
+ | 'f' -> [5]
+ | 'g' -> []
+ | 'h' -> []
+ | 'i' -> []
+ | 'j' -> []
+ | 'k' -> [32; 33; 34; 35; 36; 37; 38; 39]
+ | 'l' -> [6]
+ | 'm' -> [7]
+ | 'n' -> []
+ | 'o' -> []
+ | 'p' -> [8]
+ | 'q' -> []
+ | 'r' -> [9]
+ | 's' -> [10]
+ | 't' -> []
+ | 'u' -> [11; 12]
+ | 'v' -> [13]
+ | 'w' -> []
+ | 'x' -> [14; 15; 16; 17; 18; 19; 20; 21; 22; 23; 24; 25; 30]
+ | 'y' -> [26]
+ | 'z' -> [27]
+ | _ -> assert false
+;;
+
+type state =
+ {
+ active: bool array;
+ error: bool array;
+ }
+
+let current =
+ ref
+ {
+ active = Array.make (last_warning_number + 1) true;
+ error = Array.make (last_warning_number + 1) false;
+ }
+
+let backup () = !current
+
+let restore x = current := x
+
+let is_active x = (!current).active.(number x);;
+let is_error x = (!current).error.(number x);;
+
+let parse_opt error active flags s =
+ let set i = flags.(i) <- true in
+ let clear i = flags.(i) <- false in
+ let set_all i = active.(i) <- true; error.(i) <- true in
+ let error () = raise (Arg.Bad "Ill-formed list of warnings") in
+ let rec get_num n i =
+ if i >= String.length s then i, n
+ else match s.[i] with
+ | '0'..'9' -> get_num (10 * n + Char.code s.[i] - Char.code '0') (i + 1)
+ | _ -> i, n
+ in
+ let get_range i =
+ let i, n1 = get_num 0 i in
+ if i + 2 < String.length s && s.[i] = '.' && s.[i + 1] = '.' then
+ let i, n2 = get_num 0 (i + 2) in
+ if n2 < n1 then error ();
+ i, n1, n2
+ else
+ i, n1, n1
+ in
+ let rec loop i =
+ if i >= String.length s then () else
+ match s.[i] with
+ | 'A' .. 'Z' ->
+ List.iter set (letter (Char.lowercase_ascii s.[i]));
+ loop (i+1)
+ | 'a' .. 'z' ->
+ List.iter clear (letter s.[i]);
+ loop (i+1)
+ | '+' -> loop_letter_num set (i+1)
+ | '-' -> loop_letter_num clear (i+1)
+ | '@' -> loop_letter_num set_all (i+1)
+ | c -> error ()
+ and loop_letter_num myset i =
+ if i >= String.length s then error () else
+ match s.[i] with
+ | '0' .. '9' ->
+ let i, n1, n2 = get_range i in
+ for n = n1 to min n2 last_warning_number do myset n done;
+ loop i
+ | 'A' .. 'Z' ->
+ List.iter myset (letter (Char.lowercase_ascii s.[i]));
+ loop (i+1)
+ | 'a' .. 'z' ->
+ List.iter myset (letter s.[i]);
+ loop (i+1)
+ | _ -> error ()
+ in
+ loop 0
+;;
+
+let parse_options errflag s =
+ let error = Array.copy (!current).error in
+ let active = Array.copy (!current).active in
+ parse_opt error active (if errflag then error else active) s;
+ current := {error; active}
+
+(* If you change these, don't forget to change them in man/ocamlc.m *)
+let defaults_w = "+a-4-6-7-9-27-29-32..39-41..42-44-45-48-50";;
+let defaults_warn_error = "-a";;
+
+let () = parse_options false defaults_w;;
+let () = parse_options true defaults_warn_error;;
+
+let message = function
+ | Comment_start -> "this is the start of a comment."
+ | Comment_not_end -> "this is not the end of a comment."
+ | Deprecated s -> "deprecated: " ^ s
+ | Fragile_match "" ->
+ "this pattern-matching is fragile."
+ | Fragile_match s ->
+ "this pattern-matching is fragile.\n\
+ It will remain exhaustive when constructors are added to type " ^ s ^ "."
+ | Partial_application ->
+ "this function application is partial,\n\
+ maybe some arguments are missing."
+ | Labels_omitted [] -> assert false
+ | Labels_omitted [l] ->
+ "label " ^ l ^ " was omitted in the application of this function."
+ | Labels_omitted ls ->
+ "labels " ^ String.concat ", " ls ^
+ " were omitted in the application of this function."
+ | Method_override [lab] ->
+ "the method " ^ lab ^ " is overridden."
+ | Method_override (cname :: slist) ->
+ String.concat " "
+ ("the following methods are overridden by the class"
+ :: cname :: ":\n " :: slist)
+ | Method_override [] -> assert false
+ | Partial_match "" -> "this pattern-matching is not exhaustive."
+ | Partial_match s ->
+ "this pattern-matching is not exhaustive.\n\
+ Here is an example of a value that is not matched:\n" ^ s
+ | Non_closed_record_pattern s ->
+ "the following labels are not bound in this record pattern:\n" ^ s ^
+ "\nEither bind these labels explicitly or add '; _' to the pattern."
+ | Statement_type ->
+ "this expression should have type unit."
+ | Unused_match -> "this match case is unused."
+ | Unused_pat -> "this sub-pattern is unused."
+ | Instance_variable_override [lab] ->
+ "the instance variable " ^ lab ^ " is overridden.\n" ^
+ "The behaviour changed in ocaml 3.10 (previous behaviour was hiding.)"
+ | Instance_variable_override (cname :: slist) ->
+ String.concat " "
+ ("the following instance variables are overridden by the class"
+ :: cname :: ":\n " :: slist) ^
+ "\nThe behaviour changed in ocaml 3.10 (previous behaviour was hiding.)"
+ | Instance_variable_override [] -> assert false
+ | Illegal_backslash -> "illegal backslash escape in string."
+ | Implicit_public_methods l ->
+ "the following private methods were made public implicitly:\n "
+ ^ String.concat " " l ^ "."
+ | Unerasable_optional_argument -> "this optional argument cannot be erased."
+ | Undeclared_virtual_method m -> "the virtual method "^m^" is not declared."
+ | Not_principal s -> s^" is not principal."
+ | Without_principality s -> s^" without principality."
+ | Unused_argument -> "this argument will not be used by the function."
+ | Nonreturning_statement ->
+ "this statement never returns (or has an unsound type.)"
+ | Preprocessor s -> s
+ | Useless_record_with ->
+ "all the fields are explicitly listed in this record:\n\
+ the 'with' clause is useless."
+ | Bad_module_name (modname) ->
+ "bad source file name: \"" ^ modname ^ "\" is not a valid module name."
+ | All_clauses_guarded ->
+ "bad style, all clauses in this pattern-matching are guarded."
+ | Unused_var v | Unused_var_strict v -> "unused variable " ^ v ^ "."
+ | Wildcard_arg_to_constant_constr ->
+ "wildcard pattern given as argument to a constant constructor"
+ | Eol_in_string ->
+ "unescaped end-of-line in a string constant (non-portable code)"
+ | Duplicate_definitions (kind, cname, tc1, tc2) ->
+ Printf.sprintf "the %s %s is defined in both types %s and %s."
+ kind cname tc1 tc2
+ | Multiple_definition(modname, file1, file2) ->
+ Printf.sprintf
+ "files %s and %s both define a module named %s"
+ file1 file2 modname
+ | Unused_value_declaration v -> "unused value " ^ v ^ "."
+ | Unused_open s -> "unused open " ^ s ^ "."
+ | Unused_type_declaration s -> "unused type " ^ s ^ "."
+ | Unused_for_index s -> "unused for-loop index " ^ s ^ "."
+ | Unused_ancestor s -> "unused ancestor variable " ^ s ^ "."
+ | Unused_constructor (s, false, false) -> "unused constructor " ^ s ^ "."
+ | Unused_constructor (s, true, _) ->
+ "constructor " ^ s ^
+ " is never used to build values.\n\
+ (However, this constructor appears in patterns.)"
+ | Unused_constructor (s, false, true) ->
+ "constructor " ^ s ^
+ " is never used to build values.\n\
+ Its type is exported as a private type."
+ | Unused_extension (s, false, false) ->
+ "unused extension constructor " ^ s ^ "."
+ | Unused_extension (s, true, _) ->
+ "extension constructor " ^ s ^
+ " is never used to build values.\n\
+ (However, this constructor appears in patterns.)"
+ | Unused_extension (s, false, true) ->
+ "extension constructor " ^ s ^
+ " is never used to build values.\n\
+ It is exported or rebound as a private extension."
+ | Unused_rec_flag ->
+ "unused rec flag."
+ | Name_out_of_scope (ty, [nm], false) ->
+ nm ^ " was selected from type " ^ ty ^
+ ".\nIt is not visible in the current scope, and will not \n\
+ be selected if the type becomes unknown."
+ | Name_out_of_scope (_, _, false) -> assert false
+ | Name_out_of_scope (ty, slist, true) ->
+ "this record of type "^ ty ^" contains fields that are \n\
+ not visible in the current scope: "
+ ^ String.concat " " slist ^ ".\n\
+ They will not be selected if the type becomes unknown."
+ | Ambiguous_name ([s], tl, false) ->
+ s ^ " belongs to several types: " ^ String.concat " " tl ^
+ "\nThe first one was selected. Please disambiguate if this is wrong."
+ | Ambiguous_name (_, _, false) -> assert false
+ | Ambiguous_name (slist, tl, true) ->
+ "these field labels belong to several types: " ^
+ String.concat " " tl ^
+ "\nThe first one was selected. Please disambiguate if this is wrong."
+ | Disambiguated_name s ->
+ "this use of " ^ s ^ " required disambiguation."
+ | Nonoptional_label s ->
+ "the label " ^ s ^ " is not optional."
+ | Open_shadow_identifier (kind, s) ->
+ Printf.sprintf
+ "this open statement shadows the %s identifier %s (which is later used)"
+ kind s
+ | Open_shadow_label_constructor (kind, s) ->
+ Printf.sprintf
+ "this open statement shadows the %s %s (which is later used)"
+ kind s
+ | Bad_env_variable (var, s) ->
+ Printf.sprintf "illegal environment variable %s : %s" var s
+ | Attribute_payload (a, s) ->
+ Printf.sprintf "illegal payload for attribute '%s'.\n%s" a s
+ | Eliminated_optional_arguments sl ->
+ Printf.sprintf "implicit elimination of optional argument%s %s"
+ (if List.length sl = 1 then "" else "s")
+ (String.concat ", " sl)
+ | No_cmi_file s ->
+ "no cmi file was found in path for module " ^ s
+ | Bad_docstring unattached ->
+ if unattached then "unattached documentation comment (ignored)"
+ else "ambiguous documentation comment"
+ | Expect_tailcall ->
+ Printf.sprintf "expected tailcall"
+;;
+
+let nerrors = ref 0;;
+
+let print ppf w =
+ let msg = message w in
+ let num = number w in
+ Format.fprintf ppf "%d: %s" num msg;
+ Format.pp_print_flush ppf ();
+ if (!current).error.(num) then incr nerrors
+;;
+
+exception Errors of int;;
+
+let check_fatal () =
+ if !nerrors > 0 then begin
+ let e = Errors !nerrors in
+ nerrors := 0;
+ raise e;
+ end;
+;;
+
+let descriptions =
+ [
+ 1, "Suspicious-looking start-of-comment mark.";
+ 2, "Suspicious-looking end-of-comment mark.";
+ 3, "Deprecated feature.";
+ 4, "Fragile pattern matching: matching that will remain complete even\n\
+ \ if additional constructors are added to one of the variant types\n\
+ \ matched.";
+ 5, "Partially applied function: expression whose result has function\n\
+ \ type and is ignored.";
+ 6, "Label omitted in function application.";
+ 7, "Method overridden.";
+ 8, "Partial match: missing cases in pattern-matching.";
+ 9, "Missing fields in a record pattern.";
+ 10, "Expression on the left-hand side of a sequence that doesn't have type\n\
+ \ \"unit\" (and that is not a function, see warning number 5).";
+ 11, "Redundant case in a pattern matching (unused match case).";
+ 12, "Redundant sub-pattern in a pattern-matching.";
+ 13, "Instance variable overridden.";
+ 14, "Illegal backslash escape in a string constant.";
+ 15, "Private method made public implicitly.";
+ 16, "Unerasable optional argument.";
+ 17, "Undeclared virtual method.";
+ 18, "Non-principal type.";
+ 19, "Type without principality.";
+ 20, "Unused function argument.";
+ 21, "Non-returning statement.";
+ 22, "Preprocessor warning.";
+ 23, "Useless record \"with\" clause.";
+ 24, "Bad module name: the source file name is not a valid OCaml module \
+ name.";
+ 25, "Pattern-matching with all clauses guarded. Exhaustiveness cannot be\n\
+ \ checked.";
+ 26, "Suspicious unused variable: unused variable that is bound\n\
+ \ with \"let\" or \"as\", and doesn't start with an underscore (\"_\")\n\
+ \ character.";
+ 27, "Innocuous unused variable: unused variable that is not bound with\n\
+ \ \"let\" nor \"as\", and doesn't start with an underscore (\"_\")\n\
+ \ character.";
+ 28, "Wildcard pattern given as argument to a constant constructor.";
+ 29, "Unescaped end-of-line in a string constant (non-portable code).";
+ 30, "Two labels or constructors of the same name are defined in two\n\
+ \ mutually recursive types.";
+ 31, "A module is linked twice in the same executable.";
+ 32, "Unused value declaration.";
+ 33, "Unused open statement.";
+ 34, "Unused type declaration.";
+ 35, "Unused for-loop index.";
+ 36, "Unused ancestor variable.";
+ 37, "Unused constructor.";
+ 38, "Unused extension constructor.";
+ 39, "Unused rec flag.";
+ 40, "Constructor or label name used out of scope.";
+ 41, "Ambiguous constructor or label name.";
+ 42, "Disambiguated constructor or label name.";
+ 43, "Nonoptional label applied as optional.";
+ 44, "Open statement shadows an already defined identifier.";
+ 45, "Open statement shadows an already defined label or constructor.";
+ 46, "Error in environment variable.";
+ 47, "Illegal attribute payload.";
+ 48, "Implicit elimination of optional arguments.";
+ 49, "Missing cmi file when looking up module alias.";
+ 50, "Unexpected documentation comment.";
+ 51, "Warning on non-tail calls if @tailcall present";
+ ]
+;;
+
+let help_warnings () =
+ List.iter (fun (i, s) -> Printf.printf "%3i %s\n" i s) descriptions;
+ print_endline " A all warnings";
+ for i = Char.code 'b' to Char.code 'z' do
+ let c = Char.chr i in
+ match letter c with
+ | [] -> ()
+ | [n] ->
+ Printf.printf " %c Alias for warning %i.\n" (Char.uppercase_ascii c) n
+ | l ->
+ Printf.printf " %c warnings %s.\n"
+ (Char.uppercase_ascii c)
+ (String.concat ", " (List.map string_of_int l))
+ done;
+ exit 0
+;;
diff --git a/utils/warnings.mli b/utils/warnings.mli
new file mode 100644
index 0000000000..75d0a3d79d
--- /dev/null
+++ b/utils/warnings.mli
@@ -0,0 +1,87 @@
+(***********************************************************************)
+(* *)
+(* OCaml *)
+(* *)
+(* Pierre Weis && Damien Doligez, INRIA Rocquencourt *)
+(* *)
+(* Copyright 1998 Institut National de Recherche en Informatique et *)
+(* en Automatique. All rights reserved. This file is distributed *)
+(* under the terms of the Q Public License version 1.0. *)
+(* *)
+(***********************************************************************)
+
+open Format
+
+type t =
+ | Comment_start (* 1 *)
+ | Comment_not_end (* 2 *)
+ | Deprecated of string (* 3 *)
+ | Fragile_match of string (* 4 *)
+ | Partial_application (* 5 *)
+ | Labels_omitted of string list (* 6 *)
+ | Method_override of string list (* 7 *)
+ | Partial_match of string (* 8 *)
+ | Non_closed_record_pattern of string (* 9 *)
+ | Statement_type (* 10 *)
+ | Unused_match (* 11 *)
+ | Unused_pat (* 12 *)
+ | Instance_variable_override of string list (* 13 *)
+ | Illegal_backslash (* 14 *)
+ | Implicit_public_methods of string list (* 15 *)
+ | Unerasable_optional_argument (* 16 *)
+ | Undeclared_virtual_method of string (* 17 *)
+ | Not_principal of string (* 18 *)
+ | Without_principality of string (* 19 *)
+ | Unused_argument (* 20 *)
+ | Nonreturning_statement (* 21 *)
+ | Preprocessor of string (* 22 *)
+ | Useless_record_with (* 23 *)
+ | Bad_module_name of string (* 24 *)
+ | All_clauses_guarded (* 25 *)
+ | Unused_var of string (* 26 *)
+ | Unused_var_strict of string (* 27 *)
+ | Wildcard_arg_to_constant_constr (* 28 *)
+ | Eol_in_string (* 29 *)
+ | Duplicate_definitions of string * string * string * string (* 30 *)
+ | Multiple_definition of string * string * string (* 31 *)
+ | Unused_value_declaration of string (* 32 *)
+ | Unused_open of string (* 33 *)
+ | Unused_type_declaration of string (* 34 *)
+ | Unused_for_index of string (* 35 *)
+ | Unused_ancestor of string (* 36 *)
+ | Unused_constructor of string * bool * bool (* 37 *)
+ | Unused_extension of string * bool * bool (* 38 *)
+ | Unused_rec_flag (* 39 *)
+ | Name_out_of_scope of string * string list * bool (* 40 *)
+ | Ambiguous_name of string list * string list * bool (* 41 *)
+ | Disambiguated_name of string (* 42 *)
+ | Nonoptional_label of string (* 43 *)
+ | Open_shadow_identifier of string * string (* 44 *)
+ | Open_shadow_label_constructor of string * string (* 45 *)
+ | Bad_env_variable of string * string (* 46 *)
+ | Attribute_payload of string * string (* 47 *)
+ | Eliminated_optional_arguments of string list (* 48 *)
+ | No_cmi_file of string (* 49 *)
+ | Bad_docstring of bool (* 50 *)
+ | Expect_tailcall (* 51 *)
+;;
+
+val parse_options : bool -> string -> unit;;
+
+val is_active : t -> bool;;
+val is_error : t -> bool;;
+
+val defaults_w : string;;
+val defaults_warn_error : string;;
+
+val print : formatter -> t -> unit;;
+
+exception Errors of int;;
+
+val check_fatal : unit -> unit;;
+
+val help_warnings: unit -> unit
+
+type state
+val backup: unit -> state
+val restore: state -> unit
diff --git a/yacc/.ignore b/yacc/.ignore
new file mode 100644
index 0000000000..833c2dea6d
--- /dev/null
+++ b/yacc/.ignore
@@ -0,0 +1,4 @@
+ocamlyacc
+ocamlyacc.exe
+version.h
+.gdb_history
diff --git a/yacc/Makefile b/yacc/Makefile
new file mode 100644
index 0000000000..e7acf86908
--- /dev/null
+++ b/yacc/Makefile
@@ -0,0 +1,47 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# Makefile for the parser generator.
+
+include ../config/Makefile
+
+CC=$(BYTECC)
+CFLAGS=-DNDEBUG $(BYTECCCOMPOPTS)
+
+OBJS= closure.o error.o lalr.o lr0.o main.o mkpar.o output.o reader.o \
+ skeleton.o symtab.o verbose.o warshall.o
+
+all: ocamlyacc$(EXE)
+
+ocamlyacc$(EXE): $(OBJS)
+ $(CC) $(CFLAGS) $(CCLINKFLAGS) -o ocamlyacc$(EXE) $(OBJS)
+
+version.h : ../VERSION
+ echo "#define OCAML_VERSION \"`sed -e 1q ../VERSION`\"" >version.h
+
+clean:
+ rm -f *.o ocamlyacc$(EXE) *~ version.h
+
+depend:
+
+closure.o: defs.h
+error.o: defs.h
+lalr.o: defs.h
+lr0.o: defs.h
+main.o: defs.h version.h
+mkpar.o: defs.h
+output.o: defs.h
+reader.o: defs.h
+skeleton.o: defs.h
+symtab.o: defs.h
+verbose.o: defs.h
+warshall.o: defs.h
diff --git a/yacc/Makefile.nt b/yacc/Makefile.nt
new file mode 100644
index 0000000000..9537365a5f
--- /dev/null
+++ b/yacc/Makefile.nt
@@ -0,0 +1,48 @@
+#########################################################################
+# #
+# OCaml #
+# #
+# Xavier Leroy, projet Cristal, INRIA Rocquencourt #
+# #
+# Copyright 1999 Institut National de Recherche en Informatique et #
+# en Automatique. All rights reserved. This file is distributed #
+# under the terms of the Q Public License version 1.0. #
+# #
+#########################################################################
+
+# Makefile for the parser generator.
+
+include ../config/Makefile
+
+OBJS= closure.$(O) error.$(O) lalr.$(O) lr0.$(O) main.$(O) \
+ mkpar.$(O) output.$(O) reader.$(O) \
+ skeleton.$(O) symtab.$(O) verbose.$(O) warshall.$(O)
+
+all: ocamlyacc.exe
+
+ocamlyacc.exe: $(OBJS)
+ $(MKEXE) -o ocamlyacc.exe $(OBJS) $(EXTRALIBS)
+
+version.h : ../VERSION
+ echo "#define OCAML_VERSION \"`sed -e 1q ../VERSION`\"" >version.h
+
+clean:
+ rm -f *.$(O) ocamlyacc.exe *~ version.h
+
+%.$(O): %.c
+ $(BYTECC) -DNDEBUG -DNO_UNIX $(BYTECCCOMPOPTS) -c $<
+
+depend:
+
+closure.$(O): defs.h
+error.$(O): defs.h
+lalr.$(O): defs.h
+lr0.$(O): defs.h
+main.$(O): defs.h version.h
+mkpar.$(O): defs.h
+output.$(O): defs.h
+reader.$(O): defs.h
+skeleton.$(O): defs.h
+symtab.$(O): defs.h
+verbose.$(O): defs.h
+warshall.$(O): defs.h
diff --git a/yacc/closure.c b/yacc/closure.c
new file mode 100644
index 0000000000..d84c125bf2
--- /dev/null
+++ b/yacc/closure.c
@@ -0,0 +1,281 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include "defs.h"
+
+short *itemset;
+short *itemsetend;
+unsigned *ruleset;
+
+static unsigned *first_derives;
+static unsigned *EFF;
+
+
+
+void print_EFF ();
+void print_first_derives ();
+void print_closure ();
+
+void set_EFF(void)
+{
+ register unsigned *row;
+ register int symbol;
+ register short *sp;
+ register int rowsize;
+ register int i;
+ register int rule;
+
+ rowsize = WORDSIZE(nvars);
+ EFF = NEW2(nvars * rowsize, unsigned);
+
+ row = EFF;
+ for (i = start_symbol; i < nsyms; i++)
+ {
+ sp = derives[i];
+ for (rule = *sp; rule > 0; rule = *++sp)
+ {
+ symbol = ritem[rrhs[rule]];
+ if (ISVAR(symbol))
+ {
+ symbol -= start_symbol;
+ SETBIT(row, symbol);
+ }
+ }
+ row += rowsize;
+ }
+
+ reflexive_transitive_closure(EFF, nvars);
+
+#ifdef DEBUG
+ print_EFF();
+#endif
+}
+
+
+void set_first_derives(void)
+{
+ register unsigned *rrow;
+ register unsigned *vrow;
+ register int j;
+ register unsigned mask;
+ register unsigned cword;
+ register short *rp;
+
+ int rule;
+ int i;
+ int rulesetsize;
+ int varsetsize;
+
+ rulesetsize = WORDSIZE(nrules);
+ varsetsize = WORDSIZE(nvars);
+ first_derives = NEW2(nvars * rulesetsize, unsigned) - ntokens * rulesetsize;
+
+ set_EFF();
+
+ rrow = first_derives + ntokens * rulesetsize;
+ for (i = start_symbol; i < nsyms; i++)
+ {
+ vrow = EFF + ((i - ntokens) * varsetsize);
+ cword = *vrow++;
+ mask = 1;
+ for (j = start_symbol; j < nsyms; j++)
+ {
+ if (cword & mask)
+ {
+ rp = derives[j];
+ while ((rule = *rp++) >= 0)
+ {
+ SETBIT(rrow, rule);
+ }
+ }
+
+ mask <<= 1;
+ if (mask == 0)
+ {
+ cword = *vrow++;
+ mask = 1;
+ }
+ }
+
+ vrow += varsetsize;
+ rrow += rulesetsize;
+ }
+
+#ifdef DEBUG
+ print_first_derives();
+#endif
+
+ FREE(EFF);
+}
+
+
+void closure(short int *nucleus, int n)
+{
+ register int ruleno;
+ register unsigned word;
+ register unsigned mask;
+ register short *csp;
+ register unsigned *dsp;
+ register unsigned *rsp;
+ register int rulesetsize;
+
+ short *csend;
+ unsigned *rsend;
+ int symbol;
+ int itemno;
+
+ rulesetsize = WORDSIZE(nrules);
+ rsp = ruleset;
+ rsend = ruleset + rulesetsize;
+ for (rsp = ruleset; rsp < rsend; rsp++)
+ *rsp = 0;
+
+ csend = nucleus + n;
+ for (csp = nucleus; csp < csend; ++csp)
+ {
+ symbol = ritem[*csp];
+ if (ISVAR(symbol))
+ {
+ dsp = first_derives + symbol * rulesetsize;
+ rsp = ruleset;
+ while (rsp < rsend)
+ *rsp++ |= *dsp++;
+ }
+ }
+
+ ruleno = 0;
+ itemsetend = itemset;
+ csp = nucleus;
+ for (rsp = ruleset; rsp < rsend; ++rsp)
+ {
+ word = *rsp;
+ if (word == 0)
+ ruleno += BITS_PER_WORD;
+ else
+ {
+ mask = 1;
+ while (mask)
+ {
+ if (word & mask)
+ {
+ itemno = rrhs[ruleno];
+ while (csp < csend && *csp < itemno)
+ *itemsetend++ = *csp++;
+ *itemsetend++ = itemno;
+ while (csp < csend && *csp == itemno)
+ ++csp;
+ }
+
+ mask <<= 1;
+ ++ruleno;
+ }
+ }
+ }
+
+ while (csp < csend)
+ *itemsetend++ = *csp++;
+
+#ifdef DEBUG
+ print_closure(n);
+#endif
+}
+
+
+
+void finalize_closure(void)
+{
+ FREE(itemset);
+ FREE(ruleset);
+ FREE(first_derives + ntokens * WORDSIZE(nrules));
+}
+
+
+#ifdef DEBUG
+
+void print_closure(int n)
+{
+ register short *isp;
+
+ printf("\n\nn = %d\n\n", n);
+ for (isp = itemset; isp < itemsetend; isp++)
+ printf(" %d\n", *isp);
+}
+
+
+void print_EFF(void)
+{
+ register int i, j;
+ register unsigned *rowp;
+ register unsigned word;
+ register unsigned mask;
+
+ printf("\n\nEpsilon Free Firsts\n");
+
+ for (i = start_symbol; i < nsyms; i++)
+ {
+ printf("\n%s", symbol_name[i]);
+ rowp = EFF + ((i - start_symbol) * WORDSIZE(nvars));
+ word = *rowp++;
+
+ mask = 1;
+ for (j = 0; j < nvars; j++)
+ {
+ if (word & mask)
+ printf(" %s", symbol_name[start_symbol + j]);
+
+ mask <<= 1;
+ if (mask == 0)
+ {
+ word = *rowp++;
+ mask = 1;
+ }
+ }
+ }
+}
+
+
+void print_first_derives(void)
+{
+ register int i;
+ register int j;
+ register unsigned *rp;
+ register unsigned cword;
+ register unsigned mask;
+
+ printf("\n\n\nFirst Derives\n");
+
+ for (i = start_symbol; i < nsyms; i++)
+ {
+ printf("\n%s derives\n", symbol_name[i]);
+ rp = first_derives + i * WORDSIZE(nrules);
+ cword = *rp++;
+ mask = 1;
+ for (j = 0; j <= nrules; j++)
+ {
+ if (cword & mask)
+ printf(" %d\n", j);
+
+ mask <<= 1;
+ if (mask == 0)
+ {
+ cword = *rp++;
+ mask = 1;
+ }
+ }
+ }
+
+ fflush(stdout);
+}
+
+#endif
diff --git a/yacc/defs.h b/yacc/defs.h
new file mode 100644
index 0000000000..32114ea568
--- /dev/null
+++ b/yacc/defs.h
@@ -0,0 +1,356 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include "../config/s.h"
+
+/* machine-dependent definitions */
+/* the following definitions are for the Tahoe */
+/* they might have to be changed for other machines */
+
+/* MAXCHAR is the largest unsigned character value */
+/* MAXSHORT is the largest value of a C short */
+/* MINSHORT is the most negative value of a C short */
+/* MAXTABLE is the maximum table size */
+/* BITS_PER_WORD is the number of bits in a C unsigned */
+/* WORDSIZE computes the number of words needed to */
+/* store n bits */
+/* BIT returns the value of the n-th bit starting */
+/* from r (0-indexed) */
+/* SETBIT sets the n-th bit starting from r */
+
+#define MAXCHAR UCHAR_MAX
+#define MAXSHORT SHRT_MAX
+#define MINSHORT SHRT_MIN
+#define MAXTABLE 32500
+
+#define BITS_PER_WORD (8*sizeof(unsigned))
+#define WORDSIZE(n) (((n)+(BITS_PER_WORD-1))/BITS_PER_WORD)
+#define BIT(r, n) ((((r)[(n)/BITS_PER_WORD])>>((n)%BITS_PER_WORD))&1)
+#define SETBIT(r, n) ((r)[(n)/BITS_PER_WORD]|=(1<<((n)%BITS_PER_WORD)))
+
+/* character names */
+
+#define NUL '\0' /* the null character */
+#define NEWLINE '\n' /* line feed */
+#define SP ' ' /* space */
+#define BS '\b' /* backspace */
+#define HT '\t' /* horizontal tab */
+#define VT '\013' /* vertical tab */
+#define CR '\r' /* carriage return */
+#define FF '\f' /* form feed */
+#define QUOTE '\'' /* single quote */
+#define DOUBLE_QUOTE '\"' /* double quote */
+#define BACKSLASH '\\' /* backslash */
+
+
+/* defines for constructing filenames */
+
+#define CODE_SUFFIX ".code.c"
+#define DEFINES_SUFFIX ".tab.h"
+#define OUTPUT_SUFFIX ".ml"
+#define VERBOSE_SUFFIX ".output"
+#define INTERFACE_SUFFIX ".mli"
+
+/* keyword codes */
+
+#define TOKEN 0
+#define LEFT 1
+#define RIGHT 2
+#define NONASSOC 3
+#define MARK 4
+#define TEXT 5
+#define TYPE 6
+#define START 7
+#define UNION 8
+#define IDENT 9
+
+/* symbol classes */
+
+#define UNKNOWN 0
+#define TERM 1
+#define NONTERM 2
+
+
+/* the undefined value */
+
+#define UNDEFINED (-1)
+
+
+/* action codes */
+
+#define SHIFT 1
+#define REDUCE 2
+
+
+/* character macros */
+
+#define IS_IDENT(c) (isalnum(c) || (c) == '_' || (c) == '.' || (c) == '$')
+#define IS_OCTAL(c) ((c) >= '0' && (c) <= '7')
+#define NUMERIC_VALUE(c) ((c) - '0')
+
+
+/* symbol macros */
+
+#define ISTOKEN(s) ((s) < start_symbol)
+#define ISVAR(s) ((s) >= start_symbol)
+
+
+/* storage allocation macros */
+
+#define CALLOC(k,n) (calloc((unsigned)(k),(unsigned)(n)))
+#define FREE(x) (free((char*)(x)))
+#define MALLOC(n) (malloc((unsigned)(n)))
+#define NEW(t) ((t*)allocate(sizeof(t)))
+#define NEW2(n,t) ((t*)allocate((unsigned)((n)*sizeof(t))))
+#define REALLOC(p,n) (realloc((char*)(p),(unsigned)(n)))
+
+
+/* the structure of a symbol table entry */
+
+typedef struct bucket bucket;
+struct bucket
+{
+ struct bucket *link;
+ struct bucket *next;
+ char *name;
+ char *tag;
+ short value;
+ short index;
+ short prec;
+ char class;
+ char assoc;
+ char entry;
+ char true_token;
+};
+
+/* TABLE_SIZE is the number of entries in the symbol table. */
+/* TABLE_SIZE must be a power of two. */
+
+#define TABLE_SIZE 4096
+
+/* the structure of the LR(0) state machine */
+
+typedef struct core core;
+struct core
+{
+ struct core *next;
+ struct core *link;
+ short number;
+ short accessing_symbol;
+ short nitems;
+ short items[1];
+};
+
+
+/* the structure used to record shifts */
+
+typedef struct shifts shifts;
+struct shifts
+{
+ struct shifts *next;
+ short number;
+ short nshifts;
+ short shift[1];
+};
+
+
+/* the structure used to store reductions */
+
+typedef struct reductions reductions;
+struct reductions
+{
+ struct reductions *next;
+ short number;
+ short nreds;
+ short rules[1];
+};
+
+
+/* the structure used to represent parser actions */
+
+typedef struct action action;
+struct action
+{
+ struct action *next;
+ short symbol;
+ short number;
+ short prec;
+ char action_code;
+ char assoc;
+ char suppressed;
+};
+
+
+/* global variables */
+
+extern char dflag;
+extern char lflag;
+extern char rflag;
+extern char tflag;
+extern char vflag;
+extern char qflag;
+extern char sflag;
+extern char big_endian;
+
+extern char *myname;
+extern char *cptr;
+extern char *line;
+extern int lineno;
+extern char *virtual_input_file_name;
+extern int outline;
+
+extern char *action_file_name;
+extern char *entry_file_name;
+extern char *code_file_name;
+extern char *defines_file_name;
+extern char *input_file_name;
+extern char *output_file_name;
+extern char *text_file_name;
+extern char *union_file_name;
+extern char *verbose_file_name;
+extern char *interface_file_name;
+
+extern FILE *action_file;
+extern FILE *entry_file;
+extern FILE *code_file;
+extern FILE *defines_file;
+extern FILE *input_file;
+extern FILE *output_file;
+extern FILE *text_file;
+extern FILE *union_file;
+extern FILE *verbose_file;
+extern FILE *interface_file;
+
+extern int nitems;
+extern int nrules;
+extern int ntotalrules;
+extern int nsyms;
+extern int ntokens;
+extern int nvars;
+extern int ntags;
+
+extern char unionized;
+extern char line_format[];
+
+extern int start_symbol;
+extern char **symbol_name;
+extern short *symbol_value;
+extern short *symbol_prec;
+extern char *symbol_assoc;
+extern char **symbol_tag;
+extern char *symbol_true_token;
+
+extern short *ritem;
+extern short *rlhs;
+extern short *rrhs;
+extern short *rprec;
+extern char *rassoc;
+
+extern short **derives;
+extern char *nullable;
+
+extern bucket *first_symbol;
+extern bucket *last_symbol;
+
+extern int nstates;
+extern core *first_state;
+extern shifts *first_shift;
+extern reductions *first_reduction;
+extern short *accessing_symbol;
+extern core **state_table;
+extern shifts **shift_table;
+extern reductions **reduction_table;
+extern unsigned *LA;
+extern short *LAruleno;
+extern short *lookaheads;
+extern short *goto_map;
+extern short *from_state;
+extern short *to_state;
+
+extern action **parser;
+extern int SRtotal;
+extern int RRtotal;
+extern short *SRconflicts;
+extern short *RRconflicts;
+extern short *defred;
+extern short *rules_used;
+extern short nunused;
+extern short final_state;
+
+/* global functions */
+
+#ifdef __GNUC__
+/* Works only in GCC 2.5 and later */
+#define Noreturn __attribute ((noreturn))
+#else
+#define Noreturn
+#endif
+
+extern char *allocate(unsigned int n);
+extern bucket *lookup(char *name);
+extern bucket *make_bucket(char *name);
+extern action *parse_actions(register int stateno);
+extern action *get_shifts(int stateno);
+extern action *add_reductions(int stateno, register action *actions);
+extern action *add_reduce(register action *actions, register int ruleno, register int symbol);
+extern void closure (short int *nucleus, int n);
+extern void create_symbol_table (void);
+extern void default_action_error (void) Noreturn;
+extern void done (int k) Noreturn;
+extern void entry_without_type (char *s) Noreturn;
+extern void fatal (char *msg) Noreturn;
+extern void finalize_closure (void);
+extern void free_parser (void);
+extern void free_symbol_table (void);
+extern void free_symbols (void);
+extern void illegal_character (char *c_cptr) Noreturn;
+extern void illegal_token_ref (int i, char *name) Noreturn;
+extern void lalr (void);
+extern void lr0 (void);
+extern void make_parser (void);
+extern void no_grammar (void) Noreturn;
+extern void no_space (void) Noreturn;
+extern void open_error (char *filename) Noreturn;
+extern void output (void);
+extern void over_unionized (char *u_cptr) Noreturn;
+extern void prec_redeclared (void);
+extern void polymorphic_entry_point(char *s) Noreturn;
+extern void reader (void);
+extern void reflexive_transitive_closure (unsigned int *R, int n);
+extern void reprec_warning (char *s);
+extern void retyped_warning (char *s);
+extern void revalued_warning (char *s);
+extern void set_first_derives (void);
+extern void syntax_error (int st_lineno, char *st_line, char *st_cptr) Noreturn, terminal_lhs (int s_lineno) Noreturn;
+extern void terminal_start (char *s) Noreturn;
+extern void tokenized_start (char *s) Noreturn;
+extern void too_many_entries (void) Noreturn;
+extern void undefined_goal (char *s);
+extern void undefined_symbol (char *s);
+extern void unexpected_EOF (void) Noreturn;
+extern void unknown_rhs (int i) Noreturn;
+extern void unterminated_action (int a_lineno, char *a_line, char *a_cptr) Noreturn;
+extern void unterminated_comment (int c_lineno, char *c_line, char *c_cptr) Noreturn;
+extern void unterminated_string (int s_lineno, char *s_line, char *s_cptr) Noreturn;
+extern void unterminated_text (int t_lineno, char *t_line, char *t_cptr) Noreturn;
+extern void unterminated_union (int u_lineno, char *u_line, char *u_cptr) Noreturn;
+extern void used_reserved (char *s) Noreturn;
+extern void verbose (void);
+extern void write_section (char **section);
diff --git a/yacc/error.c b/yacc/error.c
new file mode 100644
index 0000000000..bae0565aed
--- /dev/null
+++ b/yacc/error.c
@@ -0,0 +1,312 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+/* routines for printing error messages */
+
+#include "defs.h"
+
+void fatal(char *msg)
+{
+ fprintf(stderr, "%s: f - %s\n", myname, msg);
+ done(2);
+}
+
+
+void no_space(void)
+{
+ fprintf(stderr, "%s: f - out of space\n", myname);
+ done(2);
+}
+
+
+void open_error(char *filename)
+{
+ fprintf(stderr, "%s: f - cannot open \"%s\"\n", myname, filename);
+ done(2);
+}
+
+
+void unexpected_EOF(void)
+{
+ fprintf(stderr, "File \"%s\", line %d: unexpected end-of-file\n",
+ virtual_input_file_name, lineno);
+ done(1);
+}
+
+
+void print_pos(char *st_line, char *st_cptr)
+{
+ register char *s;
+
+ if (st_line == 0) return;
+ for (s = st_line; *s != '\n'; ++s)
+ {
+ if (isprint((unsigned char) *s) || *s == '\t')
+ putc(*s, stderr);
+ else
+ putc('?', stderr);
+ }
+ putc('\n', stderr);
+ for (s = st_line; s < st_cptr; ++s)
+ {
+ if (*s == '\t')
+ putc('\t', stderr);
+ else
+ putc(' ', stderr);
+ }
+ putc('^', stderr);
+ putc('\n', stderr);
+}
+
+
+void syntax_error(int st_lineno, char *st_line, char *st_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: syntax error\n",
+ virtual_input_file_name, st_lineno);
+ print_pos(st_line, st_cptr);
+ done(1);
+}
+
+
+void unterminated_comment(int c_lineno, char *c_line, char *c_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: unmatched /*\n",
+ virtual_input_file_name, c_lineno);
+ print_pos(c_line, c_cptr);
+ done(1);
+}
+
+
+void unterminated_string(int s_lineno, char *s_line, char *s_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: unterminated string\n",
+ virtual_input_file_name, s_lineno);
+ print_pos(s_line, s_cptr);
+ done(1);
+}
+
+
+void unterminated_text(int t_lineno, char *t_line, char *t_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: unmatched %%{\n",
+ virtual_input_file_name, t_lineno);
+ print_pos(t_line, t_cptr);
+ done(1);
+}
+
+
+void unterminated_union(int u_lineno, char *u_line, char *u_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: unterminated %%union declaration\n",
+ virtual_input_file_name, u_lineno);
+ print_pos(u_line, u_cptr);
+ done(1);
+}
+
+
+void over_unionized(char *u_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: too many %%union declarations\n",
+ virtual_input_file_name, lineno);
+ print_pos(line, u_cptr);
+ done(1);
+}
+
+
+void illegal_tag(int t_lineno, char *t_line, char *t_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: illegal tag\n",
+ virtual_input_file_name, t_lineno);
+ print_pos(t_line, t_cptr);
+ done(1);
+}
+
+
+void illegal_character(char *c_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: illegal character\n",
+ virtual_input_file_name, lineno);
+ print_pos(line, c_cptr);
+ done(1);
+}
+
+
+void used_reserved(char *s)
+{
+ fprintf(stderr, "File \"%s\", line %d: illegal use of reserved symbol \
+`%s'\n", virtual_input_file_name, lineno, s);
+ done(1);
+}
+
+
+void tokenized_start(char *s)
+{
+ fprintf(stderr, "File \"%s\", line %d: the start symbol `%s' cannot \
+be declared to be a token\n", virtual_input_file_name, lineno, s);
+ done(1);
+}
+
+
+void retyped_warning(char *s)
+{
+ fprintf(stderr, "File \"%s\", line %d: warning: the type of `%s' has been \
+redeclared\n", virtual_input_file_name, lineno, s);
+}
+
+
+void reprec_warning(char *s)
+{
+ fprintf(stderr, "File \"%s\", line %d: warning: the precedence of `%s' has \
+been redeclared\n", virtual_input_file_name, lineno, s);
+}
+
+
+void revalued_warning(char *s)
+{
+ fprintf(stderr, "File \"%s\", line %d: warning: the value of `%s' has been \
+redeclared\n", virtual_input_file_name, lineno, s);
+}
+
+
+void terminal_start(char *s)
+{
+ fprintf(stderr, "File \"%s\", line %d: the entry point `%s' is a \
+token\n", virtual_input_file_name, lineno, s);
+ done(1);
+}
+
+void too_many_entries(void)
+{
+ fprintf(stderr, "File \"%s\", line %d: more than 256 entry points\n",
+ virtual_input_file_name, lineno);
+ done(1);
+}
+
+
+void no_grammar(void)
+{
+ fprintf(stderr, "File \"%s\", line %d: no grammar has been specified\n",
+ virtual_input_file_name, lineno);
+ done(1);
+}
+
+
+void terminal_lhs(int s_lineno)
+{
+ fprintf(stderr, "File \"%s\", line %d: a token appears on the lhs \
+of a production\n", virtual_input_file_name, s_lineno);
+ done(1);
+}
+
+
+void prec_redeclared(void)
+{
+ fprintf(stderr, "File \"%s\", line %d: warning: conflicting %%prec \
+specifiers\n", virtual_input_file_name, lineno);
+}
+
+
+void unterminated_action(int a_lineno, char *a_line, char *a_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: unterminated action\n",
+ virtual_input_file_name, a_lineno);
+ print_pos(a_line, a_cptr);
+ done(1);
+}
+
+
+void dollar_warning(int a_lineno, int i)
+{
+ fprintf(stderr, "File \"%s\", line %d: warning: $%d references beyond the \
+end of the current rule\n", virtual_input_file_name, a_lineno, i);
+}
+
+
+void dollar_error(int a_lineno, char *a_line, char *a_cptr)
+{
+ fprintf(stderr, "File \"%s\", line %d: illegal $-name\n",
+ virtual_input_file_name, a_lineno);
+ print_pos(a_line, a_cptr);
+ done(1);
+}
+
+
+void untyped_lhs(void)
+{
+ fprintf(stderr, "File \"%s\", line %d: $$ is untyped\n",
+ virtual_input_file_name, lineno);
+ done(1);
+}
+
+
+void untyped_rhs(int i, char *s)
+{
+ fprintf(stderr, "File \"%s\", line %d: $%d (%s) is untyped\n",
+ virtual_input_file_name, lineno, i, s);
+ done(1);
+}
+
+
+void unknown_rhs(int i)
+{
+ fprintf(stderr, "File \"%s\", line %d: $%d is unbound\n",
+ virtual_input_file_name, lineno, i);
+ done(1);
+}
+
+void illegal_token_ref(int i, char *name)
+{
+ fprintf(stderr, "File \"%s\", line %d: $%d refers to terminal `%s', \
+which has no argument\n",
+ virtual_input_file_name, lineno, i, name);
+ done(1);
+}
+
+void default_action_error(void)
+{
+ fprintf(stderr, "File \"%s\", line %d: no action specified for this \
+production\n",
+ virtual_input_file_name, lineno);
+ done(1);
+}
+
+
+void undefined_goal(char *s)
+{
+ fprintf(stderr, "%s: e - the start symbol `%s' is undefined\n", myname, s);
+ done(1);
+}
+
+void undefined_symbol(char *s)
+{
+ fprintf(stderr, "%s: e - the symbol `%s' is undefined\n", myname, s);
+ done(1);
+}
+
+
+void entry_without_type(char *s)
+{
+ fprintf(stderr,
+ "%s: e - no type has been declared for the start symbol `%s'\n",
+ myname, s);
+ done(1);
+}
+
+void polymorphic_entry_point(char *s)
+{
+ fprintf(stderr,
+ "%s: e - the start symbol `%s' has a polymorphic type\n",
+ myname, s);
+ done(1);
+}
diff --git a/yacc/lalr.c b/yacc/lalr.c
new file mode 100644
index 0000000000..7819980115
--- /dev/null
+++ b/yacc/lalr.c
@@ -0,0 +1,661 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include "defs.h"
+
+typedef
+ struct shorts
+ {
+ struct shorts *next;
+ short value;
+ }
+ shorts;
+
+int tokensetsize;
+short *lookaheads;
+short *LAruleno;
+unsigned *LA;
+short *accessing_symbol;
+core **state_table;
+shifts **shift_table;
+reductions **reduction_table;
+short *goto_map;
+short *from_state;
+short *to_state;
+
+short **transpose(short int **R, int n);
+
+static int infinity;
+static int maxrhs;
+static int ngotos;
+static unsigned *F;
+static short **includes;
+static shorts **lookback;
+static short **R;
+static short *INDEX;
+static short *VERTICES;
+static int top;
+
+
+
+void set_state_table (void);
+void set_accessing_symbol (void);
+void set_shift_table (void);
+void set_reduction_table (void);
+void set_maxrhs (void);
+void initialize_LA (void);
+void set_goto_map (void);
+void initialize_F (void);
+void build_relations (void);
+void compute_FOLLOWS (void);
+void compute_lookaheads (void);
+void digraph (short int **relation);
+void add_lookback_edge (int stateno, int ruleno, int gotono);
+void traverse (register int i);
+
+void lalr(void)
+{
+ tokensetsize = WORDSIZE(ntokens);
+
+ set_state_table();
+ set_accessing_symbol();
+ set_shift_table();
+ set_reduction_table();
+ set_maxrhs();
+ initialize_LA();
+ set_goto_map();
+ initialize_F();
+ build_relations();
+ compute_FOLLOWS();
+ compute_lookaheads();
+}
+
+
+
+void set_state_table(void)
+{
+ register core *sp;
+
+ state_table = NEW2(nstates, core *);
+ for (sp = first_state; sp; sp = sp->next)
+ state_table[sp->number] = sp;
+}
+
+
+
+void set_accessing_symbol(void)
+{
+ register core *sp;
+
+ accessing_symbol = NEW2(nstates, short);
+ for (sp = first_state; sp; sp = sp->next)
+ accessing_symbol[sp->number] = sp->accessing_symbol;
+}
+
+
+
+void set_shift_table(void)
+{
+ register shifts *sp;
+
+ shift_table = NEW2(nstates, shifts *);
+ for (sp = first_shift; sp; sp = sp->next)
+ shift_table[sp->number] = sp;
+}
+
+
+
+void set_reduction_table(void)
+{
+ register reductions *rp;
+
+ reduction_table = NEW2(nstates, reductions *);
+ for (rp = first_reduction; rp; rp = rp->next)
+ reduction_table[rp->number] = rp;
+}
+
+
+
+void set_maxrhs(void)
+{
+ register short *itemp;
+ register short *item_end;
+ register int length;
+ register int max;
+
+ length = 0;
+ max = 0;
+ item_end = ritem + nitems;
+ for (itemp = ritem; itemp < item_end; itemp++)
+ {
+ if (*itemp >= 0)
+ {
+ length++;
+ }
+ else
+ {
+ if (length > max) max = length;
+ length = 0;
+ }
+ }
+
+ maxrhs = max;
+}
+
+
+
+void initialize_LA(void)
+{
+ register int i, j, k;
+ register reductions *rp;
+
+ lookaheads = NEW2(nstates + 1, short);
+
+ k = 0;
+ for (i = 0; i < nstates; i++)
+ {
+ lookaheads[i] = k;
+ rp = reduction_table[i];
+ if (rp)
+ k += rp->nreds;
+ }
+ lookaheads[nstates] = k;
+
+ LA = NEW2(k * tokensetsize, unsigned);
+ LAruleno = NEW2(k, short);
+ lookback = NEW2(k, shorts *);
+
+ k = 0;
+ for (i = 0; i < nstates; i++)
+ {
+ rp = reduction_table[i];
+ if (rp)
+ {
+ for (j = 0; j < rp->nreds; j++)
+ {
+ LAruleno[k] = rp->rules[j];
+ k++;
+ }
+ }
+ }
+}
+
+
+void set_goto_map(void)
+{
+ register shifts *sp;
+ register int i;
+ register int symbol;
+ register int k;
+ register short *temp_map;
+ register int state2;
+ register int state1;
+
+ goto_map = NEW2(nvars + 1, short) - ntokens;
+ temp_map = NEW2(nvars + 1, short) - ntokens;
+
+ ngotos = 0;
+ for (sp = first_shift; sp; sp = sp->next)
+ {
+ for (i = sp->nshifts - 1; i >= 0; i--)
+ {
+ symbol = accessing_symbol[sp->shift[i]];
+
+ if (ISTOKEN(symbol)) break;
+
+ if (ngotos == MAXSHORT)
+ fatal("too many gotos");
+
+ ngotos++;
+ goto_map[symbol]++;
+ }
+ }
+
+ k = 0;
+ for (i = ntokens; i < nsyms; i++)
+ {
+ temp_map[i] = k;
+ k += goto_map[i];
+ }
+
+ for (i = ntokens; i < nsyms; i++)
+ goto_map[i] = temp_map[i];
+
+ goto_map[nsyms] = ngotos;
+ temp_map[nsyms] = ngotos;
+
+ from_state = NEW2(ngotos, short);
+ to_state = NEW2(ngotos, short);
+
+ for (sp = first_shift; sp; sp = sp->next)
+ {
+ state1 = sp->number;
+ for (i = sp->nshifts - 1; i >= 0; i--)
+ {
+ state2 = sp->shift[i];
+ symbol = accessing_symbol[state2];
+
+ if (ISTOKEN(symbol)) break;
+
+ k = temp_map[symbol]++;
+ from_state[k] = state1;
+ to_state[k] = state2;
+ }
+ }
+
+ FREE(temp_map + ntokens);
+}
+
+
+
+/* Map_goto maps a state/symbol pair into its numeric representation. */
+
+int
+map_goto(int state, int symbol)
+{
+ register int high;
+ register int low;
+ register int middle;
+ register int s;
+
+ low = goto_map[symbol];
+ high = goto_map[symbol + 1];
+
+ for (;;)
+ {
+ assert(low <= high);
+ middle = (low + high) >> 1;
+ s = from_state[middle];
+ if (s == state)
+ return (middle);
+ else if (s < state)
+ low = middle + 1;
+ else
+ high = middle - 1;
+ }
+}
+
+
+
+void initialize_F(void)
+{
+ register int i;
+ register int j;
+ register int k;
+ register shifts *sp;
+ register short *edge;
+ register unsigned *rowp;
+ register short *rp;
+ register short **reads;
+ register int nedges;
+ register int stateno;
+ register int symbol;
+ register int nwords;
+
+ nwords = ngotos * tokensetsize;
+ F = NEW2(nwords, unsigned);
+
+ reads = NEW2(ngotos, short *);
+ edge = NEW2(ngotos + 1, short);
+ nedges = 0;
+
+ rowp = F;
+ for (i = 0; i < ngotos; i++)
+ {
+ stateno = to_state[i];
+ sp = shift_table[stateno];
+
+ if (sp)
+ {
+ k = sp->nshifts;
+
+ for (j = 0; j < k; j++)
+ {
+ symbol = accessing_symbol[sp->shift[j]];
+ if (ISVAR(symbol))
+ break;
+ SETBIT(rowp, symbol);
+ }
+
+ for (; j < k; j++)
+ {
+ symbol = accessing_symbol[sp->shift[j]];
+ if (nullable[symbol])
+ edge[nedges++] = map_goto(stateno, symbol);
+ }
+
+ if (nedges)
+ {
+ reads[i] = rp = NEW2(nedges + 1, short);
+
+ for (j = 0; j < nedges; j++)
+ rp[j] = edge[j];
+
+ rp[nedges] = -1;
+ nedges = 0;
+ }
+ }
+
+ rowp += tokensetsize;
+ }
+
+ SETBIT(F, 0);
+ digraph(reads);
+
+ for (i = 0; i < ngotos; i++)
+ {
+ if (reads[i])
+ FREE(reads[i]);
+ }
+
+ FREE(reads);
+ FREE(edge);
+}
+
+
+
+void build_relations(void)
+{
+ register int i;
+ register int j;
+ register int k;
+ register short *rulep;
+ register short *rp;
+ register shifts *sp;
+ register int length;
+ register int nedges;
+ register int done;
+ register int state1;
+ register int stateno;
+ register int symbol1;
+ register int symbol2;
+ register short *shortp;
+ register short *edge;
+ register short *states;
+ register short **new_includes;
+
+ includes = NEW2(ngotos, short *);
+ edge = NEW2(ngotos + 1, short);
+ states = NEW2(maxrhs + 1, short);
+
+ for (i = 0; i < ngotos; i++)
+ {
+ nedges = 0;
+ state1 = from_state[i];
+ symbol1 = accessing_symbol[to_state[i]];
+
+ for (rulep = derives[symbol1]; *rulep >= 0; rulep++)
+ {
+ length = 1;
+ states[0] = state1;
+ stateno = state1;
+
+ for (rp = ritem + rrhs[*rulep]; *rp >= 0; rp++)
+ {
+ symbol2 = *rp;
+ sp = shift_table[stateno];
+ k = sp->nshifts;
+
+ for (j = 0; j < k; j++)
+ {
+ stateno = sp->shift[j];
+ if (accessing_symbol[stateno] == symbol2) break;
+ }
+
+ states[length++] = stateno;
+ }
+
+ add_lookback_edge(stateno, *rulep, i);
+
+ length--;
+ done = 0;
+ while (!done)
+ {
+ done = 1;
+ rp--;
+ if (ISVAR(*rp))
+ {
+ stateno = states[--length];
+ edge[nedges++] = map_goto(stateno, *rp);
+ if (nullable[*rp] && length > 0) done = 0;
+ }
+ }
+ }
+
+ if (nedges)
+ {
+ includes[i] = shortp = NEW2(nedges + 1, short);
+ for (j = 0; j < nedges; j++)
+ shortp[j] = edge[j];
+ shortp[nedges] = -1;
+ }
+ }
+
+ new_includes = transpose(includes, ngotos);
+
+ for (i = 0; i < ngotos; i++)
+ if (includes[i])
+ FREE(includes[i]);
+
+ FREE(includes);
+
+ includes = new_includes;
+
+ FREE(edge);
+ FREE(states);
+}
+
+
+void add_lookback_edge(int stateno, int ruleno, int gotono)
+{
+ register int i, k;
+ register int found;
+ register shorts *sp;
+
+ i = lookaheads[stateno];
+ k = lookaheads[stateno + 1];
+ found = 0;
+ while (!found && i < k)
+ {
+ if (LAruleno[i] == ruleno)
+ found = 1;
+ else
+ ++i;
+ }
+ assert(found);
+
+ sp = NEW(shorts);
+ sp->next = lookback[i];
+ sp->value = gotono;
+ lookback[i] = sp;
+}
+
+
+
+short **
+transpose(short int **R, int n)
+{
+ register short **new_R;
+ register short **temp_R;
+ register short *nedges;
+ register short *sp;
+ register int i;
+ register int k;
+
+ nedges = NEW2(n, short);
+
+ for (i = 0; i < n; i++)
+ {
+ sp = R[i];
+ if (sp)
+ {
+ while (*sp >= 0)
+ nedges[*sp++]++;
+ }
+ }
+
+ new_R = NEW2(n, short *);
+ temp_R = NEW2(n, short *);
+
+ for (i = 0; i < n; i++)
+ {
+ k = nedges[i];
+ if (k > 0)
+ {
+ sp = NEW2(k + 1, short);
+ new_R[i] = sp;
+ temp_R[i] = sp;
+ sp[k] = -1;
+ }
+ }
+
+ FREE(nedges);
+
+ for (i = 0; i < n; i++)
+ {
+ sp = R[i];
+ if (sp)
+ {
+ while (*sp >= 0)
+ *temp_R[*sp++]++ = i;
+ }
+ }
+
+ FREE(temp_R);
+
+ return (new_R);
+}
+
+
+
+void compute_FOLLOWS(void)
+{
+ digraph(includes);
+}
+
+
+void compute_lookaheads(void)
+{
+ register int i, n;
+ register unsigned *fp1, *fp2, *fp3;
+ register shorts *sp, *next;
+ register unsigned *rowp;
+
+ rowp = LA;
+ n = lookaheads[nstates];
+ for (i = 0; i < n; i++)
+ {
+ fp3 = rowp + tokensetsize;
+ for (sp = lookback[i]; sp; sp = sp->next)
+ {
+ fp1 = rowp;
+ fp2 = F + tokensetsize * sp->value;
+ while (fp1 < fp3)
+ *fp1++ |= *fp2++;
+ }
+ rowp = fp3;
+ }
+
+ for (i = 0; i < n; i++)
+ for (sp = lookback[i]; sp; sp = next)
+ {
+ next = sp->next;
+ FREE(sp);
+ }
+
+ FREE(lookback);
+ FREE(F);
+}
+
+
+void digraph(short int **relation)
+{
+ register int i;
+
+ infinity = ngotos + 2;
+ INDEX = NEW2(ngotos + 1, short);
+ VERTICES = NEW2(ngotos + 1, short);
+ top = 0;
+
+ R = relation;
+
+ for (i = 0; i < ngotos; i++)
+ INDEX[i] = 0;
+
+ for (i = 0; i < ngotos; i++)
+ {
+ if (INDEX[i] == 0 && R[i])
+ traverse(i);
+ }
+
+ FREE(INDEX);
+ FREE(VERTICES);
+}
+
+
+
+void traverse(register int i)
+{
+ register unsigned *fp1;
+ register unsigned *fp2;
+ register unsigned *fp3;
+ register int j;
+ register short *rp;
+
+ int height;
+ unsigned *base;
+
+ VERTICES[++top] = i;
+ INDEX[i] = height = top;
+
+ base = F + i * tokensetsize;
+ fp3 = base + tokensetsize;
+
+ rp = R[i];
+ if (rp)
+ {
+ while ((j = *rp++) >= 0)
+ {
+ if (INDEX[j] == 0)
+ traverse(j);
+
+ if (INDEX[i] > INDEX[j])
+ INDEX[i] = INDEX[j];
+
+ fp1 = base;
+ fp2 = F + j * tokensetsize;
+
+ while (fp1 < fp3)
+ *fp1++ |= *fp2++;
+ }
+ }
+
+ if (INDEX[i] == height)
+ {
+ for (;;)
+ {
+ j = VERTICES[top--];
+ INDEX[j] = infinity;
+
+ if (i == j)
+ break;
+
+ fp1 = base;
+ fp2 = F + j * tokensetsize;
+
+ while (fp1 < fp3)
+ *fp2++ = *fp1++;
+ }
+ }
+}
diff --git a/yacc/lr0.c b/yacc/lr0.c
new file mode 100644
index 0000000000..a5a62d341c
--- /dev/null
+++ b/yacc/lr0.c
@@ -0,0 +1,618 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include "defs.h"
+
+extern short *itemset;
+extern short *itemsetend;
+extern unsigned *ruleset;
+
+int nstates;
+core *first_state;
+shifts *first_shift;
+reductions *first_reduction;
+
+int get_state(int symbol);
+core *new_state(int symbol);
+
+static core **state_set;
+static core *this_state;
+static core *last_state;
+static shifts *last_shift;
+static reductions *last_reduction;
+
+static int nshifts;
+static short *shift_symbol;
+
+static short *redset;
+static short *shiftset;
+
+static short **kernel_base;
+static short **kernel_end;
+static short *kernel_items;
+
+
+
+void initialize_states (void);
+void save_reductions (void);
+void new_itemsets (void);
+void save_shifts (void);
+void print_derives ();
+void show_cores (void), show_ritems (void), show_rrhs (void), show_shifts (void);
+
+void allocate_itemsets(void)
+{
+ register short *itemp;
+ register short *item_end;
+ register int symbol;
+ register int i;
+ register int count;
+ register int max;
+ register short *symbol_count;
+
+ count = 0;
+ symbol_count = NEW2(nsyms, short);
+
+ item_end = ritem + nitems;
+ for (itemp = ritem; itemp < item_end; itemp++)
+ {
+ symbol = *itemp;
+ if (symbol >= 0)
+ {
+ count++;
+ symbol_count[symbol]++;
+ }
+ }
+
+ kernel_base = NEW2(nsyms, short *);
+ kernel_items = NEW2(count, short);
+
+ count = 0;
+ max = 0;
+ for (i = 0; i < nsyms; i++)
+ {
+ kernel_base[i] = kernel_items + count;
+ count += symbol_count[i];
+ if (max < symbol_count[i])
+ max = symbol_count[i];
+ }
+
+ shift_symbol = symbol_count;
+ kernel_end = NEW2(nsyms, short *);
+}
+
+
+void allocate_storage(void)
+{
+ allocate_itemsets();
+ shiftset = NEW2(nsyms, short);
+ redset = NEW2(nrules + 1, short);
+ state_set = NEW2(nitems, core *);
+}
+
+
+void append_states(void)
+{
+ register int i;
+ register int j;
+ register int symbol;
+
+#ifdef TRACE
+ fprintf(stderr, "Entering append_states()\n");
+#endif
+ for (i = 1; i < nshifts; i++)
+ {
+ symbol = shift_symbol[i];
+ j = i;
+ while (j > 0 && shift_symbol[j - 1] > symbol)
+ {
+ shift_symbol[j] = shift_symbol[j - 1];
+ j--;
+ }
+ shift_symbol[j] = symbol;
+ }
+
+ for (i = 0; i < nshifts; i++)
+ {
+ symbol = shift_symbol[i];
+ shiftset[i] = get_state(symbol);
+ }
+}
+
+
+void free_storage(void)
+{
+ FREE(shift_symbol);
+ FREE(redset);
+ FREE(shiftset);
+ FREE(kernel_base);
+ FREE(kernel_end);
+ FREE(kernel_items);
+ FREE(state_set);
+}
+
+
+
+void generate_states(void)
+{
+ allocate_storage();
+ itemset = NEW2(nitems, short);
+ ruleset = NEW2(WORDSIZE(nrules), unsigned);
+ set_first_derives();
+ initialize_states();
+
+ while (this_state)
+ {
+ closure(this_state->items, this_state->nitems);
+ save_reductions();
+ new_itemsets();
+ append_states();
+
+ if (nshifts > 0)
+ save_shifts();
+
+ this_state = this_state->next;
+ }
+
+ finalize_closure();
+ free_storage();
+}
+
+
+
+int
+get_state(int symbol)
+{
+ register int key;
+ register short *isp1;
+ register short *isp2;
+ register short *iend;
+ register core *sp;
+ register int found;
+ register int n;
+
+#ifdef TRACE
+ fprintf(stderr, "Entering get_state(%d)\n", symbol);
+#endif
+
+ isp1 = kernel_base[symbol];
+ iend = kernel_end[symbol];
+ n = iend - isp1;
+
+ key = *isp1;
+ assert(0 <= key && key < nitems);
+ sp = state_set[key];
+ if (sp)
+ {
+ found = 0;
+ while (!found)
+ {
+ if (sp->nitems == n)
+ {
+ found = 1;
+ isp1 = kernel_base[symbol];
+ isp2 = sp->items;
+
+ while (found && isp1 < iend)
+ {
+ if (*isp1++ != *isp2++)
+ found = 0;
+ }
+ }
+
+ if (!found)
+ {
+ if (sp->link)
+ {
+ sp = sp->link;
+ }
+ else
+ {
+ sp = sp->link = new_state(symbol);
+ found = 1;
+ }
+ }
+ }
+ }
+ else
+ {
+ state_set[key] = sp = new_state(symbol);
+ }
+
+ return (sp->number);
+}
+
+
+
+void initialize_states(void)
+{
+ register int i;
+ register short *start_derives;
+ register core *p;
+
+ start_derives = derives[start_symbol];
+ for (i = 0; start_derives[i] >= 0; ++i)
+ continue;
+
+ p = (core *) MALLOC(sizeof(core) + i*sizeof(short));
+ if (p == 0) no_space();
+
+ p->next = 0;
+ p->link = 0;
+ p->number = 0;
+ p->accessing_symbol = 0;
+ p->nitems = i;
+
+ for (i = 0; start_derives[i] >= 0; ++i)
+ p->items[i] = rrhs[start_derives[i]];
+
+ first_state = last_state = this_state = p;
+ nstates = 1;
+}
+
+
+void new_itemsets(void)
+{
+ register int i;
+ register int shiftcount;
+ register short *isp;
+ register short *ksp;
+ register int symbol;
+
+ for (i = 0; i < nsyms; i++)
+ kernel_end[i] = 0;
+
+ shiftcount = 0;
+ isp = itemset;
+ while (isp < itemsetend)
+ {
+ i = *isp++;
+ symbol = ritem[i];
+ if (symbol > 0)
+ {
+ ksp = kernel_end[symbol];
+ if (!ksp)
+ {
+ shift_symbol[shiftcount++] = symbol;
+ ksp = kernel_base[symbol];
+ }
+
+ *ksp++ = i + 1;
+ kernel_end[symbol] = ksp;
+ }
+ }
+
+ nshifts = shiftcount;
+}
+
+
+
+core *
+new_state(int symbol)
+{
+ register int n;
+ register core *p;
+ register short *isp1;
+ register short *isp2;
+ register short *iend;
+
+#ifdef TRACE
+ fprintf(stderr, "Entering new_state(%d)\n", symbol);
+#endif
+
+ if (nstates >= MAXSHORT)
+ fatal("too many states");
+
+ isp1 = kernel_base[symbol];
+ iend = kernel_end[symbol];
+ n = iend - isp1;
+
+ p = (core *) allocate((unsigned) (sizeof(core) + (n - 1) * sizeof(short)));
+ p->accessing_symbol = symbol;
+ p->number = nstates;
+ p->nitems = n;
+
+ isp2 = p->items;
+ while (isp1 < iend)
+ *isp2++ = *isp1++;
+
+ last_state->next = p;
+ last_state = p;
+
+ nstates++;
+
+ return (p);
+}
+
+
+/* show_cores is used for debugging */
+
+void show_cores(void)
+{
+ core *p;
+ int i, j, k, n;
+ int itemno;
+
+ k = 0;
+ for (p = first_state; p; ++k, p = p->next)
+ {
+ if (k) printf("\n");
+ printf("state %d, number = %d, accessing symbol = %s\n",
+ k, p->number, symbol_name[p->accessing_symbol]);
+ n = p->nitems;
+ for (i = 0; i < n; ++i)
+ {
+ itemno = p->items[i];
+ printf("%4d ", itemno);
+ j = itemno;
+ while (ritem[j] >= 0) ++j;
+ printf("%s :", symbol_name[rlhs[-ritem[j]]]);
+ j = rrhs[-ritem[j]];
+ while (j < itemno)
+ printf(" %s", symbol_name[ritem[j++]]);
+ printf(" .");
+ while (ritem[j] >= 0)
+ printf(" %s", symbol_name[ritem[j++]]);
+ printf("\n");
+ fflush(stdout);
+ }
+ }
+}
+
+
+/* show_ritems is used for debugging */
+
+void show_ritems(void)
+{
+ int i;
+
+ for (i = 0; i < nitems; ++i)
+ printf("ritem[%d] = %d\n", i, ritem[i]);
+}
+
+
+/* show_rrhs is used for debugging */
+
+void show_rrhs(void)
+{
+ int i;
+
+ for (i = 0; i < nrules; ++i)
+ printf("rrhs[%d] = %d\n", i, rrhs[i]);
+}
+
+
+/* show_shifts is used for debugging */
+
+void show_shifts(void)
+{
+ shifts *p;
+ int i, j, k;
+
+ k = 0;
+ for (p = first_shift; p; ++k, p = p->next)
+ {
+ if (k) printf("\n");
+ printf("shift %d, number = %d, nshifts = %d\n", k, p->number,
+ p->nshifts);
+ j = p->nshifts;
+ for (i = 0; i < j; ++i)
+ printf("\t%d\n", p->shift[i]);
+ }
+}
+
+
+void save_shifts(void)
+{
+ register shifts *p;
+ register short *sp1;
+ register short *sp2;
+ register short *send;
+
+ p = (shifts *) allocate((unsigned) (sizeof(shifts) +
+ (nshifts - 1) * sizeof(short)));
+
+ p->number = this_state->number;
+ p->nshifts = nshifts;
+
+ sp1 = shiftset;
+ sp2 = p->shift;
+ send = shiftset + nshifts;
+
+ while (sp1 < send)
+ *sp2++ = *sp1++;
+
+ if (last_shift)
+ {
+ last_shift->next = p;
+ last_shift = p;
+ }
+ else
+ {
+ first_shift = p;
+ last_shift = p;
+ }
+}
+
+
+
+void save_reductions(void)
+{
+ register short *isp;
+ register short *rp1;
+ register short *rp2;
+ register int item;
+ register int count;
+ register reductions *p;
+ register short *rend;
+
+ count = 0;
+ for (isp = itemset; isp < itemsetend; isp++)
+ {
+ item = ritem[*isp];
+ if (item < 0)
+ {
+ redset[count++] = -item;
+ }
+ }
+
+ if (count)
+ {
+ p = (reductions *) allocate((unsigned) (sizeof(reductions) +
+ (count - 1) * sizeof(short)));
+
+ p->number = this_state->number;
+ p->nreds = count;
+
+ rp1 = redset;
+ rp2 = p->rules;
+ rend = rp1 + count;
+
+ while (rp1 < rend)
+ *rp2++ = *rp1++;
+
+ if (last_reduction)
+ {
+ last_reduction->next = p;
+ last_reduction = p;
+ }
+ else
+ {
+ first_reduction = p;
+ last_reduction = p;
+ }
+ }
+}
+
+
+void set_derives(void)
+{
+ register int i, k;
+ register int lhs;
+ register short *rules;
+
+ derives = NEW2(nsyms, short *);
+ rules = NEW2(nvars + nrules, short);
+
+ k = 0;
+ for (lhs = start_symbol; lhs < nsyms; lhs++)
+ {
+ derives[lhs] = rules + k;
+ for (i = 0; i < nrules; i++)
+ {
+ if (rlhs[i] == lhs)
+ {
+ rules[k] = i;
+ k++;
+ }
+ }
+ rules[k] = -1;
+ k++;
+ }
+
+#ifdef DEBUG
+ print_derives();
+#endif
+}
+
+void free_derives(void)
+{
+ FREE(derives[start_symbol]);
+ FREE(derives);
+}
+
+#ifdef DEBUG
+void print_derives(void)
+{
+ register int i;
+ register short *sp;
+
+ printf("\nDERIVES\n\n");
+
+ for (i = start_symbol; i < nsyms; i++)
+ {
+ printf("%s derives ", symbol_name[i]);
+ for (sp = derives[i]; *sp >= 0; sp++)
+ {
+ printf(" %d", *sp);
+ }
+ putchar('\n');
+ }
+
+ putchar('\n');
+}
+#endif
+
+
+void set_nullable(void)
+{
+ register int i, j;
+ register int empty;
+ int done;
+
+ nullable = MALLOC(nsyms);
+ if (nullable == 0) no_space();
+
+ for (i = 0; i < nsyms; ++i)
+ nullable[i] = 0;
+
+ done = 0;
+ while (!done)
+ {
+ done = 1;
+ for (i = 1; i < nitems; i++)
+ {
+ empty = 1;
+ while ((j = ritem[i]) >= 0)
+ {
+ if (!nullable[j])
+ empty = 0;
+ ++i;
+ }
+ if (empty)
+ {
+ j = rlhs[-j];
+ if (!nullable[j])
+ {
+ nullable[j] = 1;
+ done = 0;
+ }
+ }
+ }
+ }
+
+#ifdef DEBUG
+ for (i = 0; i < nsyms; i++)
+ {
+ if (nullable[i])
+ printf("%s is nullable\n", symbol_name[i]);
+ else
+ printf("%s is not nullable\n", symbol_name[i]);
+ }
+#endif
+}
+
+
+void free_nullable(void)
+{
+ FREE(nullable);
+}
+
+
+void lr0(void)
+{
+ set_derives();
+ set_nullable();
+ generate_states();
+}
diff --git a/yacc/main.c b/yacc/main.c
new file mode 100644
index 0000000000..9388b9d1a8
--- /dev/null
+++ b/yacc/main.c
@@ -0,0 +1,461 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include <signal.h>
+#include <string.h>
+#include "defs.h"
+#ifdef HAS_UNISTD
+#include <unistd.h>
+#endif
+
+#include "version.h"
+
+char dflag;
+char lflag;
+char rflag;
+char tflag;
+char vflag;
+char qflag;
+char sflag;
+char big_endian;
+
+char *file_prefix = 0;
+char *myname = "yacc";
+char temp_form[] = "yacc.XXXXXXX";
+
+#ifdef NO_UNIX
+char dirsep = '\\';
+#else
+char dirsep = '/';
+#endif
+
+int lineno;
+char *virtual_input_file_name = NULL;
+int outline;
+
+char *action_file_name;
+char *entry_file_name;
+char *code_file_name;
+char *interface_file_name;
+char *defines_file_name;
+char *input_file_name = "";
+char *output_file_name;
+char *text_file_name;
+char *union_file_name;
+char *verbose_file_name;
+
+#ifdef HAS_MKSTEMP
+int action_fd = -1, entry_fd = -1, text_fd = -1, union_fd = -1;
+#endif
+
+FILE *action_file; /* a temp file, used to save actions associated */
+ /* with rules until the parser is written */
+FILE *entry_file;
+FILE *code_file; /* y.code.c (used when the -r option is specified) */
+FILE *defines_file; /* y.tab.h */
+FILE *input_file; /* the input file */
+FILE *output_file; /* y.tab.c */
+FILE *text_file; /* a temp file, used to save text until all */
+ /* symbols have been defined */
+FILE *union_file; /* a temp file, used to save the union */
+ /* definition until all symbol have been */
+ /* defined */
+FILE *verbose_file; /* y.output */
+FILE *interface_file;
+
+int nitems;
+int nrules;
+int ntotalrules;
+int nsyms;
+int ntokens;
+int nvars;
+
+int start_symbol;
+char **symbol_name;
+short *symbol_value;
+short *symbol_prec;
+char *symbol_assoc;
+char **symbol_tag;
+char *symbol_true_token;
+
+short *ritem;
+short *rlhs;
+short *rrhs;
+short *rprec;
+char *rassoc;
+short **derives;
+char *nullable;
+
+#if !defined(HAS_MKSTEMP)
+extern char *mktemp(char *);
+#endif
+#ifndef NO_UNIX
+extern char *getenv(const char *);
+#endif
+
+
+void done(int k)
+{
+#ifdef HAS_MKSTEMP
+ if (action_fd != -1)
+ unlink(action_file_name);
+ if (entry_fd != -1)
+ unlink(entry_file_name);
+ if (text_fd != -1)
+ unlink(text_file_name);
+ if (union_fd != -1)
+ unlink(union_file_name);
+#else
+ if (action_file) { fclose(action_file); unlink(action_file_name); }
+ if (entry_file) { fclose(entry_file); unlink(entry_file_name); }
+ if (text_file) { fclose(text_file); unlink(text_file_name); }
+ if (union_file) { fclose(union_file); unlink(union_file_name); }
+#endif
+ if (output_file && k > 0) {
+ fclose(output_file); unlink(output_file_name);
+ }
+ if (interface_file && k > 0) {
+ fclose(interface_file); unlink(interface_file_name);
+ }
+ exit(k);
+}
+
+
+void onintr(int dummy)
+{
+ done(1);
+}
+
+
+void set_signals(void)
+{
+#ifdef SIGINT
+ if (signal(SIGINT, SIG_IGN) != SIG_IGN)
+ signal(SIGINT, onintr);
+#endif
+#ifdef SIGTERM
+ if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
+ signal(SIGTERM, onintr);
+#endif
+#ifdef SIGHUP
+ if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
+ signal(SIGHUP, onintr);
+#endif
+}
+
+
+void usage(void)
+{
+ fprintf(stderr, "usage: %s [-v] [-q] [-b file_prefix] filename\n",
+ myname);
+ exit(1);
+}
+
+void getargs(int argc, char **argv)
+{
+ register int i;
+ register char *s;
+
+ if (argc > 0) myname = argv[0];
+ for (i = 1; i < argc; ++i)
+ {
+ s = argv[i];
+ if (*s != '-') break;
+ switch (*++s)
+ {
+ case '\0':
+ input_file = stdin;
+ file_prefix = "stdin";
+ if (i + 1 < argc) usage();
+ return;
+
+ case '-':
+ ++i;
+ goto no_more_options;
+
+ case 'v':
+ if (!strcmp (argv[i], "-version")){
+ printf ("The OCaml parser generator, version "
+ OCAML_VERSION "\n");
+ exit (0);
+ }else if (!strcmp (argv[i], "-vnum")){
+ printf (OCAML_VERSION "\n");
+ exit (0);
+ }else{
+ vflag = 1;
+ }
+ break;
+
+ case 'q':
+ qflag = 1;
+ break;
+
+ case 'b':
+ if (*++s)
+ file_prefix = s;
+ else if (++i < argc)
+ file_prefix = argv[i];
+ else
+ usage();
+ continue;
+
+ default:
+ usage();
+ }
+
+ for (;;)
+ {
+ switch (*++s)
+ {
+ case '\0':
+ goto end_of_option;
+
+ case 'v':
+ vflag = 1;
+ break;
+
+ case 'q':
+ qflag = 1;
+ break;
+
+ default:
+ usage();
+ }
+ }
+end_of_option:;
+ }
+
+no_more_options:;
+ if (i + 1 != argc) usage();
+ input_file_name = argv[i];
+ if (file_prefix == 0) {
+ int len;
+ len = strlen(argv[i]);
+ file_prefix = malloc(len + 1);
+ if (file_prefix == 0) no_space();
+ strcpy(file_prefix, argv[i]);
+ while (len > 0) {
+ len--;
+ if (file_prefix[len] == '.') {
+ file_prefix[len] = 0;
+ break;
+ }
+ }
+ }
+}
+
+
+char *
+allocate(unsigned int n)
+{
+ register char *p;
+
+ p = NULL;
+ if (n)
+ {
+ p = CALLOC(1, n);
+ if (!p) no_space();
+ }
+ return (p);
+}
+
+
+void create_file_names(void)
+{
+ int i, len;
+ char *tmpdir;
+
+#ifdef NO_UNIX
+ tmpdir = getenv("TEMP");
+ if (tmpdir == 0) tmpdir = ".";
+#else
+ tmpdir = getenv("TMPDIR");
+ if (tmpdir == 0) tmpdir = "/tmp";
+#endif
+ len = strlen(tmpdir);
+ i = len + sizeof(temp_form);
+ if (len && tmpdir[len-1] != dirsep)
+ ++i;
+
+ action_file_name = MALLOC(i);
+ if (action_file_name == 0) no_space();
+ entry_file_name = MALLOC(i);
+ if (entry_file_name == 0) no_space();
+ text_file_name = MALLOC(i);
+ if (text_file_name == 0) no_space();
+ union_file_name = MALLOC(i);
+ if (union_file_name == 0) no_space();
+
+ strcpy(action_file_name, tmpdir);
+ strcpy(entry_file_name, tmpdir);
+ strcpy(text_file_name, tmpdir);
+ strcpy(union_file_name, tmpdir);
+
+ if (len && tmpdir[len - 1] != dirsep)
+ {
+ action_file_name[len] = dirsep;
+ entry_file_name[len] = dirsep;
+ text_file_name[len] = dirsep;
+ union_file_name[len] = dirsep;
+ ++len;
+ }
+
+ strcpy(action_file_name + len, temp_form);
+ strcpy(entry_file_name + len, temp_form);
+ strcpy(text_file_name + len, temp_form);
+ strcpy(union_file_name + len, temp_form);
+
+ action_file_name[len + 5] = 'a';
+ entry_file_name[len + 5] = 'e';
+ text_file_name[len + 5] = 't';
+ union_file_name[len + 5] = 'u';
+
+#ifdef HAS_MKSTEMP
+ action_fd = mkstemp(action_file_name);
+ if (action_fd == -1)
+ open_error(action_file_name);
+ entry_fd = mkstemp(entry_file_name);
+ if (entry_fd == -1)
+ open_error(entry_file_name);
+ text_fd = mkstemp(text_file_name);
+ if (text_fd == -1)
+ open_error(text_file_name);
+ union_fd = mkstemp(union_file_name);
+ if (union_fd == -1)
+ open_error(union_file_name);
+#else
+ mktemp(action_file_name);
+ mktemp(entry_file_name);
+ mktemp(text_file_name);
+ mktemp(union_file_name);
+#endif
+
+ len = strlen(file_prefix);
+
+ output_file_name = MALLOC(len + 7);
+ if (output_file_name == 0)
+ no_space();
+ strcpy(output_file_name, file_prefix);
+ strcpy(output_file_name + len, OUTPUT_SUFFIX);
+
+ code_file_name = output_file_name;
+
+ if (vflag)
+ {
+ verbose_file_name = MALLOC(len + 8);
+ if (verbose_file_name == 0)
+ no_space();
+ strcpy(verbose_file_name, file_prefix);
+ strcpy(verbose_file_name + len, VERBOSE_SUFFIX);
+ }
+
+ interface_file_name = MALLOC(len + 8);
+ if (interface_file_name == 0)
+ no_space();
+ strcpy(interface_file_name, file_prefix);
+ strcpy(interface_file_name + len, INTERFACE_SUFFIX);
+
+}
+
+
+void open_files(void)
+{
+ create_file_names();
+
+ if (input_file == 0)
+ {
+ input_file = fopen(input_file_name, "r");
+ if (input_file == 0)
+ open_error(input_file_name);
+ }
+
+#ifdef HAS_MKSTEMP
+ action_file = fdopen(action_fd, "w");
+#else
+ action_file = fopen(action_file_name, "w");
+#endif
+ if (action_file == 0)
+ open_error(action_file_name);
+
+#ifdef HAS_MKSTEMP
+ entry_file = fdopen(entry_fd, "w");
+#else
+ entry_file = fopen(entry_file_name, "w");
+#endif
+ if (entry_file == 0)
+ open_error(entry_file_name);
+
+#ifdef HAS_MKSTEMP
+ text_file = fdopen(text_fd, "w");
+#else
+ text_file = fopen(text_file_name, "w");
+#endif
+ if (text_file == 0)
+ open_error(text_file_name);
+
+ if (vflag)
+ {
+ verbose_file = fopen(verbose_file_name, "w");
+ if (verbose_file == 0)
+ open_error(verbose_file_name);
+ }
+
+ if (dflag)
+ {
+ defines_file = fopen(defines_file_name, "w");
+ if (defines_file == 0)
+ open_error(defines_file_name);
+#ifdef HAS_MKSTEMP
+ union_file = fdopen(union_fd, "w");
+#else
+ union_file = fopen(union_file_name, "w");
+#endif
+ if (union_file == 0)
+ open_error(union_file_name);
+ }
+
+ output_file = fopen(output_file_name, "w");
+ if (output_file == 0)
+ open_error(output_file_name);
+
+ if (rflag)
+ {
+ code_file = fopen(code_file_name, "w");
+ if (code_file == 0)
+ open_error(code_file_name);
+ }
+ else
+ code_file = output_file;
+
+
+ interface_file = fopen(interface_file_name, "w");
+ if (interface_file == 0)
+ open_error(interface_file_name);
+}
+
+int main(int argc, char **argv)
+{
+ set_signals();
+ getargs(argc, argv);
+ open_files();
+ reader();
+ lr0();
+ lalr();
+ make_parser();
+ verbose();
+ output();
+ done(0);
+ /*NOTREACHED*/
+ return 0;
+}
diff --git a/yacc/mkpar.c b/yacc/mkpar.c
new file mode 100644
index 0000000000..55f4d4e55d
--- /dev/null
+++ b/yacc/mkpar.c
@@ -0,0 +1,362 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include "defs.h"
+
+action **parser;
+int SRtotal;
+int RRtotal;
+short *SRconflicts;
+short *RRconflicts;
+short *defred;
+short *rules_used;
+short nunused;
+short final_state;
+
+static int SRcount;
+static int RRcount;
+
+void find_final_state (void);
+void remove_conflicts (void);
+void unused_rules (void);
+void total_conflicts (void);
+void defreds (void);
+
+void make_parser(void)
+{
+ register int i;
+
+ parser = NEW2(nstates, action *);
+ for (i = 0; i < nstates; i++)
+ parser[i] = parse_actions(i);
+
+ find_final_state();
+ remove_conflicts();
+ unused_rules();
+ if (SRtotal + RRtotal > 0) total_conflicts();
+ defreds();
+}
+
+
+action *
+parse_actions(register int stateno)
+{
+ register action *actions;
+
+ actions = get_shifts(stateno);
+ actions = add_reductions(stateno, actions);
+ return (actions);
+}
+
+
+action *
+get_shifts(int stateno)
+{
+ register action *actions, *temp;
+ register shifts *sp;
+ register short *to_state;
+ register int i, k;
+ register int symbol;
+
+ actions = 0;
+ sp = shift_table[stateno];
+ if (sp)
+ {
+ to_state = sp->shift;
+ for (i = sp->nshifts - 1; i >= 0; i--)
+ {
+ k = to_state[i];
+ symbol = accessing_symbol[k];
+ if (ISTOKEN(symbol))
+ {
+ temp = NEW(action);
+ temp->next = actions;
+ temp->symbol = symbol;
+ temp->number = k;
+ temp->prec = symbol_prec[symbol];
+ temp->action_code = SHIFT;
+ temp->assoc = symbol_assoc[symbol];
+ actions = temp;
+ }
+ }
+ }
+ return (actions);
+}
+
+action *
+add_reductions(int stateno, register action *actions)
+{
+ register int i, j, m, n;
+ register int ruleno, tokensetsize;
+ register unsigned *rowp;
+
+ tokensetsize = WORDSIZE(ntokens);
+ m = lookaheads[stateno];
+ n = lookaheads[stateno + 1];
+ for (i = m; i < n; i++)
+ {
+ ruleno = LAruleno[i];
+ rowp = LA + i * tokensetsize;
+ for (j = ntokens - 1; j >= 0; j--)
+ {
+ if (BIT(rowp, j))
+ actions = add_reduce(actions, ruleno, j);
+ }
+ }
+ return (actions);
+}
+
+
+action *
+add_reduce(register action *actions, register int ruleno, register int symbol)
+{
+ register action *temp, *prev, *next;
+
+ prev = 0;
+ for (next = actions; next && next->symbol < symbol; next = next->next)
+ prev = next;
+
+ while (next && next->symbol == symbol && next->action_code == SHIFT)
+ {
+ prev = next;
+ next = next->next;
+ }
+
+ while (next && next->symbol == symbol &&
+ next->action_code == REDUCE && next->number < ruleno)
+ {
+ prev = next;
+ next = next->next;
+ }
+
+ temp = NEW(action);
+ temp->next = next;
+ temp->symbol = symbol;
+ temp->number = ruleno;
+ temp->prec = rprec[ruleno];
+ temp->action_code = REDUCE;
+ temp->assoc = rassoc[ruleno];
+
+ if (prev)
+ prev->next = temp;
+ else
+ actions = temp;
+
+ return (actions);
+}
+
+
+void find_final_state(void)
+{
+ register int goal, i;
+ register short *to_state;
+ register shifts *p;
+
+ p = shift_table[0];
+ to_state = p->shift;
+ goal = ritem[1];
+ for (i = p->nshifts - 1; i >= 0; --i)
+ {
+ final_state = to_state[i];
+ if (accessing_symbol[final_state] == goal) break;
+ }
+}
+
+
+void unused_rules(void)
+{
+ register int i;
+ register action *p;
+
+ rules_used = (short *) MALLOC(nrules*sizeof(short));
+ if (rules_used == 0) no_space();
+
+ for (i = 0; i < nrules; ++i)
+ rules_used[i] = 0;
+
+ for (i = 0; i < nstates; ++i)
+ {
+ for (p = parser[i]; p; p = p->next)
+ {
+ if (p->action_code == REDUCE && p->suppressed == 0)
+ rules_used[p->number] = 1;
+ }
+ }
+
+ nunused = 0;
+ for (i = 3; i < nrules; ++i)
+ if (!rules_used[i]) ++nunused;
+
+ if (nunused){
+ if (nunused == 1)
+ fprintf(stderr, "1 rule never reduced\n");
+ else
+ fprintf(stderr, "%d rules never reduced\n", nunused);
+ }
+}
+
+
+void remove_conflicts(void)
+{
+ register int i;
+ register int symbol;
+ register action *p, *pref;
+
+ SRtotal = 0;
+ RRtotal = 0;
+ SRconflicts = NEW2(nstates, short);
+ RRconflicts = NEW2(nstates, short);
+ pref = NULL;
+ for (i = 0; i < nstates; i++)
+ {
+ SRcount = 0;
+ RRcount = 0;
+ symbol = -1;
+ for (p = parser[i]; p; p = p->next)
+ {
+ if (p->symbol != symbol)
+ {
+ pref = p;
+ symbol = p->symbol;
+ }
+ else if (i == final_state && symbol == 0)
+ {
+ SRcount++;
+ p->suppressed = 1;
+ }
+ else if (pref->action_code == SHIFT)
+ {
+ if (pref->prec > 0 && p->prec > 0)
+ {
+ if (pref->prec < p->prec)
+ {
+ pref->suppressed = 2;
+ pref = p;
+ }
+ else if (pref->prec > p->prec)
+ {
+ p->suppressed = 2;
+ }
+ else if (pref->assoc == LEFT)
+ {
+ pref->suppressed = 2;
+ pref = p;
+ }
+ else if (pref->assoc == RIGHT)
+ {
+ p->suppressed = 2;
+ }
+ else
+ {
+ pref->suppressed = 2;
+ p->suppressed = 2;
+ }
+ }
+ else
+ {
+ SRcount++;
+ p->suppressed = 1;
+ }
+ }
+ else
+ {
+ RRcount++;
+ p->suppressed = 1;
+ }
+ }
+ SRtotal += SRcount;
+ RRtotal += RRcount;
+ SRconflicts[i] = SRcount;
+ RRconflicts[i] = RRcount;
+ }
+}
+
+
+void total_conflicts(void)
+{
+ if (SRtotal == 1)
+ fprintf(stderr, "1 shift/reduce conflict");
+ else if (SRtotal > 1)
+ fprintf(stderr, "%d shift/reduce conflicts", SRtotal);
+
+ if (SRtotal && RRtotal)
+ fprintf(stderr, ", ");
+
+ if (RRtotal == 1)
+ fprintf(stderr, "1 reduce/reduce conflict");
+ else if (RRtotal > 1)
+ fprintf(stderr, "%d reduce/reduce conflicts", RRtotal);
+
+ fprintf(stderr, ".\n");
+}
+
+
+int
+sole_reduction(int stateno)
+{
+ register int count, ruleno;
+ register action *p;
+
+ count = 0;
+ ruleno = 0;
+ for (p = parser[stateno]; p; p = p->next)
+ {
+ if (p->action_code == SHIFT && p->suppressed == 0)
+ return (0);
+ else if (p->action_code == REDUCE && p->suppressed == 0)
+ {
+ if (ruleno > 0 && p->number != ruleno)
+ return (0);
+ if (p->symbol != 1)
+ ++count;
+ ruleno = p->number;
+ }
+ }
+
+ if (count == 0)
+ return (0);
+ return (ruleno);
+}
+
+
+void defreds(void)
+{
+ register int i;
+
+ defred = NEW2(nstates, short);
+ for (i = 0; i < nstates; i++)
+ defred[i] = sole_reduction(i);
+}
+
+void free_action_row(register action *p)
+{
+ register action *q;
+
+ while (p)
+ {
+ q = p->next;
+ FREE(p);
+ p = q;
+ }
+}
+
+void free_parser(void)
+{
+ register int i;
+
+ for (i = 0; i < nstates; i++)
+ free_action_row(parser[i]);
+
+ FREE(parser);
+}
diff --git a/yacc/output.c b/yacc/output.c
new file mode 100644
index 0000000000..4a497ebba8
--- /dev/null
+++ b/yacc/output.c
@@ -0,0 +1,982 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include "defs.h"
+
+static int nvectors;
+static int nentries;
+static short **froms;
+static short **tos;
+static short *tally;
+static short *width;
+static short *state_count;
+static short *order;
+static short *base;
+static short *pos;
+static int maxtable;
+static short *table;
+static short *check;
+static int lowzero;
+static int high;
+
+
+void free_itemsets (void);
+void free_shifts (void);
+void free_reductions (void);
+void output_stored_text (void);
+void output_transl (void);
+void output_rule_data (void);
+void output_yydefred (void);
+void output_actions (void);
+void output_debug (void);
+void output_trailing_text (void);
+void output_semantic_actions (void);
+void output_entries (void);
+void token_actions (void);
+void goto_actions (void);
+void sort_actions (void);
+void pack_table (void);
+void output_base (void);
+void output_table (void);
+void output_check (void);
+int default_goto (int symbol);
+void save_column (int symbol, int default_state);
+int matching_vector (int vector);
+int pack_vector (int vector);
+
+
+void output(void)
+{
+ extern char *header[], *define_tables[];
+
+ free_itemsets();
+ free_shifts();
+ free_reductions();
+ write_section(header);
+ output_stored_text();
+ output_transl();
+ output_rule_data();
+ output_yydefred();
+ output_actions();
+ output_debug();
+ free_parser();
+ if (sflag){
+ if (!rflag) ++outline;
+ fprintf(output_file,
+ "let yyact = Array.new %d (fun _ -> (failwith \"parser\" : Obj.t))\n",
+ ntotalrules);
+ }else{
+ if (!rflag) outline += 2;
+ fprintf(output_file,
+ "let yyact = [|\n (fun _ -> failwith \"parser\")\n");
+ }
+ output_semantic_actions();
+ if (!sflag){
+ if (!rflag) ++outline;
+ fprintf(output_file, "|]\n");
+ }
+ write_section(define_tables);
+ output_entries();
+ output_trailing_text();
+}
+
+
+static void output_char(unsigned int n)
+{
+ n = n & 0xFF;
+ putc('\\', output_file);
+ putc('0' + n / 100, output_file);
+ putc('0' + (n / 10) % 10, output_file);
+ putc('0' + n % 10, output_file);
+}
+
+static void output_short(int n)
+{
+ output_char(n);
+ output_char(n >> 8);
+}
+
+void output_rule_data(void)
+{
+ register int i;
+ register int j;
+
+
+ fprintf(output_file, "let yylhs = \"");
+ output_short(symbol_value[start_symbol]);
+
+ j = 8;
+ for (i = 3; i < nrules; i++)
+ {
+ if (j >= 8)
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+ else
+ ++j;
+
+ output_short(symbol_value[rlhs[i]]);
+ }
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+
+ fprintf(output_file, "let yylen = \"");
+ output_short(2);
+
+ j = 8;
+ for (i = 3; i < nrules; i++)
+ {
+ if (j >= 8)
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+ else
+ j++;
+
+ output_short(rrhs[i + 1] - rrhs[i] - 1);
+ }
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+}
+
+
+void output_yydefred(void)
+{
+ register int i, j;
+
+ fprintf(output_file, "let yydefred = \"");
+ output_short(defred[0] ? defred[0] - 2 : 0);
+
+ j = 8;
+ for (i = 1; i < nstates; i++)
+ {
+ if (j < 8)
+ ++j;
+ else
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+
+ output_short(defred[i] ? defred[i] - 2 : 0);
+ }
+
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+}
+
+
+void output_actions(void)
+{
+ nvectors = 2*nstates + nvars;
+
+ froms = NEW2(nvectors, short *);
+ tos = NEW2(nvectors, short *);
+ tally = NEW2(nvectors, short);
+ width = NEW2(nvectors, short);
+
+ token_actions();
+ FREE(lookaheads);
+ FREE(LA);
+ FREE(LAruleno);
+ FREE(accessing_symbol);
+
+ goto_actions();
+ FREE(goto_map + ntokens);
+ FREE(from_state);
+ FREE(to_state);
+
+ sort_actions();
+ pack_table();
+ output_base();
+ output_table();
+ output_check();
+}
+
+
+void token_actions(void)
+{
+ register int i, j;
+ register int shiftcount, reducecount;
+ register int max, min;
+ register short *actionrow, *r, *s;
+ register action *p;
+
+ actionrow = NEW2(2*ntokens, short);
+ for (i = 0; i < nstates; ++i)
+ {
+ if (parser[i])
+ {
+ for (j = 0; j < 2*ntokens; ++j)
+ actionrow[j] = 0;
+
+ shiftcount = 0;
+ reducecount = 0;
+ for (p = parser[i]; p; p = p->next)
+ {
+ if (p->suppressed == 0)
+ {
+ if (p->action_code == SHIFT)
+ {
+ ++shiftcount;
+ actionrow[p->symbol] = p->number;
+ }
+ else if (p->action_code == REDUCE && p->number != defred[i])
+ {
+ ++reducecount;
+ actionrow[p->symbol + ntokens] = p->number;
+ }
+ }
+ }
+
+ tally[i] = shiftcount;
+ tally[nstates+i] = reducecount;
+ width[i] = 0;
+ width[nstates+i] = 0;
+ if (shiftcount > 0)
+ {
+ froms[i] = r = NEW2(shiftcount, short);
+ tos[i] = s = NEW2(shiftcount, short);
+ min = MAXSHORT;
+ max = 0;
+ for (j = 0; j < ntokens; ++j)
+ {
+ if (actionrow[j])
+ {
+ if (min > symbol_value[j])
+ min = symbol_value[j];
+ if (max < symbol_value[j])
+ max = symbol_value[j];
+ *r++ = symbol_value[j];
+ *s++ = actionrow[j];
+ }
+ }
+ width[i] = max - min + 1;
+ }
+ if (reducecount > 0)
+ {
+ froms[nstates+i] = r = NEW2(reducecount, short);
+ tos[nstates+i] = s = NEW2(reducecount, short);
+ min = MAXSHORT;
+ max = 0;
+ for (j = 0; j < ntokens; ++j)
+ {
+ if (actionrow[ntokens+j])
+ {
+ if (min > symbol_value[j])
+ min = symbol_value[j];
+ if (max < symbol_value[j])
+ max = symbol_value[j];
+ *r++ = symbol_value[j];
+ *s++ = actionrow[ntokens+j] - 2;
+ }
+ }
+ width[nstates+i] = max - min + 1;
+ }
+ }
+ }
+ FREE(actionrow);
+}
+
+void goto_actions(void)
+{
+ register int i, j, k;
+
+ state_count = NEW2(nstates, short);
+
+ k = default_goto(start_symbol + 1);
+ fprintf(output_file, "let yydgoto = \"");
+ output_short(k);
+
+ save_column(start_symbol + 1, k);
+
+ j = 8;
+ for (i = start_symbol + 2; i < nsyms; i++)
+ {
+ if (j >= 8)
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+ else
+ ++j;
+
+ k = default_goto(i);
+ output_short(k);
+ save_column(i, k);
+ }
+
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+ FREE(state_count);
+}
+
+int
+default_goto(int symbol)
+{
+ register int i;
+ register int m;
+ register int n;
+ register int default_state;
+ register int max;
+
+ m = goto_map[symbol];
+ n = goto_map[symbol + 1];
+
+ if (m == n) return (0);
+
+ for (i = 0; i < nstates; i++)
+ state_count[i] = 0;
+
+ for (i = m; i < n; i++)
+ state_count[to_state[i]]++;
+
+ max = 0;
+ default_state = 0;
+ for (i = 0; i < nstates; i++)
+ {
+ if (state_count[i] > max)
+ {
+ max = state_count[i];
+ default_state = i;
+ }
+ }
+
+ return (default_state);
+}
+
+
+
+void save_column(int symbol, int default_state)
+{
+ register int i;
+ register int m;
+ register int n;
+ register short *sp;
+ register short *sp1;
+ register short *sp2;
+ register int count;
+ register int symno;
+
+ m = goto_map[symbol];
+ n = goto_map[symbol + 1];
+
+ count = 0;
+ for (i = m; i < n; i++)
+ {
+ if (to_state[i] != default_state)
+ ++count;
+ }
+ if (count == 0) return;
+
+ symno = symbol_value[symbol] + 2*nstates;
+
+ froms[symno] = sp1 = sp = NEW2(count, short);
+ tos[symno] = sp2 = NEW2(count, short);
+
+ for (i = m; i < n; i++)
+ {
+ if (to_state[i] != default_state)
+ {
+ *sp1++ = from_state[i];
+ *sp2++ = to_state[i];
+ }
+ }
+
+ tally[symno] = count;
+ width[symno] = sp1[-1] - sp[0] + 1;
+}
+
+void sort_actions(void)
+{
+ register int i;
+ register int j;
+ register int k;
+ register int t;
+ register int w;
+
+ order = NEW2(nvectors, short);
+ nentries = 0;
+
+ for (i = 0; i < nvectors; i++)
+ {
+ if (tally[i] > 0)
+ {
+ t = tally[i];
+ w = width[i];
+ j = nentries - 1;
+
+ while (j >= 0 && (width[order[j]] < w))
+ j--;
+
+ while (j >= 0 && (width[order[j]] == w) && (tally[order[j]] < t))
+ j--;
+
+ for (k = nentries - 1; k > j; k--)
+ order[k + 1] = order[k];
+
+ order[j + 1] = i;
+ nentries++;
+ }
+ }
+}
+
+
+void pack_table(void)
+{
+ register int i;
+ register int place;
+ register int state;
+
+ base = NEW2(nvectors, short);
+ pos = NEW2(nentries, short);
+
+ maxtable = 1000;
+ table = NEW2(maxtable, short);
+ check = NEW2(maxtable, short);
+
+ lowzero = 0;
+ high = 0;
+
+ for (i = 0; i < maxtable; i++)
+ check[i] = -1;
+
+ for (i = 0; i < nentries; i++)
+ {
+ state = matching_vector(i);
+
+ if (state < 0)
+ place = pack_vector(i);
+ else
+ place = base[state];
+
+ pos[i] = place;
+ base[order[i]] = place;
+ }
+
+ for (i = 0; i < nvectors; i++)
+ {
+ if (froms[i])
+ FREE(froms[i]);
+ if (tos[i])
+ FREE(tos[i]);
+ }
+
+ FREE(froms);
+ FREE(tos);
+ FREE(pos);
+}
+
+
+/* The function matching_vector determines if the vector specified by */
+/* the input parameter matches a previously considered vector. The */
+/* test at the start of the function checks if the vector represents */
+/* a row of shifts over terminal symbols or a row of reductions, or a */
+/* column of shifts over a nonterminal symbol. Berkeley Yacc does not */
+/* check if a column of shifts over a nonterminal symbols matches a */
+/* previously considered vector. Because of the nature of LR parsing */
+/* tables, no two columns can match. Therefore, the only possible */
+/* match would be between a row and a column. Such matches are */
+/* unlikely. Therefore, to save time, no attempt is made to see if a */
+/* column matches a previously considered vector. */
+/* */
+/* Matching_vector is poorly designed. The test could easily be made */
+/* faster. Also, it depends on the vectors being in a specific */
+/* order. */
+
+int
+matching_vector(int vector)
+{
+ register int i;
+ register int j;
+ register int k;
+ register int t;
+ register int w;
+ register int match;
+ register int prev;
+
+ i = order[vector];
+ if (i >= 2*nstates)
+ return (-1);
+
+ t = tally[i];
+ w = width[i];
+
+ for (prev = vector - 1; prev >= 0; prev--)
+ {
+ j = order[prev];
+ if (width[j] != w || tally[j] != t)
+ return (-1);
+
+ match = 1;
+ for (k = 0; match && k < t; k++)
+ {
+ if (tos[j][k] != tos[i][k] || froms[j][k] != froms[i][k])
+ match = 0;
+ }
+
+ if (match)
+ return (j);
+ }
+
+ return (-1);
+}
+
+
+
+int
+pack_vector(int vector)
+{
+ register int i, j, k, l;
+ register int t;
+ register int loc;
+ register int ok;
+ register short *from;
+ register short *to;
+ int newmax;
+
+ i = order[vector];
+ t = tally[i];
+ assert(t);
+
+ from = froms[i];
+ to = tos[i];
+
+ j = lowzero - from[0];
+ for (k = 1; k < t; ++k)
+ if (lowzero - from[k] > j)
+ j = lowzero - from[k];
+ for (;; ++j)
+ {
+ if (j == 0)
+ continue;
+ ok = 1;
+ for (k = 0; ok && k < t; k++)
+ {
+ loc = j + from[k];
+ if (loc >= maxtable)
+ {
+ if (loc >= MAXTABLE)
+ fatal("maximum table size exceeded");
+
+ newmax = maxtable;
+ do { newmax += 200; } while (newmax <= loc);
+ table = (short *) REALLOC(table, newmax*sizeof(short));
+ if (table == 0) no_space();
+ check = (short *) REALLOC(check, newmax*sizeof(short));
+ if (check == 0) no_space();
+ for (l = maxtable; l < newmax; ++l)
+ {
+ table[l] = 0;
+ check[l] = -1;
+ }
+ maxtable = newmax;
+ }
+
+ if (check[loc] != -1)
+ ok = 0;
+ }
+ for (k = 0; ok && k < vector; k++)
+ {
+ if (pos[k] == j)
+ ok = 0;
+ }
+ if (ok)
+ {
+ for (k = 0; k < t; k++)
+ {
+ loc = j + from[k];
+ table[loc] = to[k];
+ check[loc] = from[k];
+ if (loc > high) high = loc;
+ }
+
+ while (lowzero < maxtable && check[lowzero] != -1)
+ ++lowzero;
+
+ return (j);
+ }
+ }
+}
+
+
+
+void output_base(void)
+{
+ register int i, j;
+
+ fprintf(output_file, "let yysindex = \"");
+ output_short(base[0]);
+
+ j = 8;
+ for (i = 1; i < nstates; i++)
+ {
+ if (j >= 8)
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+ else
+ ++j;
+
+ output_short(base[i]);
+ }
+
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+
+ fprintf(output_file, "let yyrindex = \"");
+ output_short(base[nstates]);
+
+ j = 8;
+ for (i = nstates + 1; i < 2*nstates; i++)
+ {
+ if (j >= 8)
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+ else
+ ++j;
+
+ output_short(base[i]);
+ }
+
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+
+ fprintf(output_file, "let yygindex = \"");
+ output_short(base[2*nstates]);
+
+ j = 8;
+ for (i = 2*nstates + 1; i < nvectors - 1; i++)
+ {
+ if (j >= 8)
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+ else
+ ++j;
+
+ output_short(base[i]);
+ }
+
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+ FREE(base);
+}
+
+
+
+void output_table(void)
+{
+ register int i;
+ register int j;
+
+ ++outline;
+ fprintf(code_file, "let yytablesize = %d\n", high);
+ fprintf(output_file, "let yytable = \"");
+ output_short(table[0]);
+
+ j = 8;
+ for (i = 1; i <= high; i++)
+ {
+ if (j >= 8)
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+ else
+ ++j;
+
+ output_short(table[i]);
+ }
+
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+ FREE(table);
+}
+
+
+
+void output_check(void)
+{
+ register int i;
+ register int j;
+
+ fprintf(output_file, "let yycheck = \"");
+ output_short(check[0]);
+
+ j = 8;
+ for (i = 1; i <= high; i++)
+ {
+ if (j >= 8)
+ {
+ if (!rflag) ++outline;
+ fprintf(output_file, "\\\n");
+ j = 1;
+ }
+ else
+ ++j;
+
+ output_short(check[i]);
+ }
+
+ if (!rflag) outline += 2;
+ fprintf(output_file, "\"\n\n");
+ FREE(check);
+}
+
+
+void output_transl(void)
+{
+ int i;
+
+ ++outline;
+ fprintf(code_file, "let yytransl_const = [|\n");
+ for (i = 0; i < ntokens; i++) {
+ if (symbol_true_token[i] && symbol_tag[i] == NULL) {
+ ++outline;
+ fprintf(code_file, " %3d (* %s *);\n", symbol_value[i], symbol_name[i]);
+ }
+ }
+ outline += 2;
+ fprintf(code_file, " 0|]\n\n");
+ ++outline;
+ fprintf(code_file, "let yytransl_block = [|\n");
+ for (i = 0; i < ntokens; i++) {
+ if (symbol_true_token[i] && symbol_tag[i] != NULL) {
+ ++outline;
+ fprintf(code_file, " %3d (* %s *);\n", symbol_value[i], symbol_name[i]);
+ }
+ }
+ outline += 2;
+ fprintf(code_file, " 0|]\n\n");
+}
+
+void output_stored_text(void)
+{
+ register int c;
+ register FILE *in, *out;
+
+ fclose(text_file);
+ text_file = fopen(text_file_name, "r");
+ if (text_file == NULL)
+ open_error(text_file_name);
+ in = text_file;
+ if ((c = getc(in)) == EOF)
+ return;
+ out = code_file;
+ if (c == '\n')
+ ++outline;
+ putc(c, out);
+ while ((c = getc(in)) != EOF)
+ {
+ if (c == '\n')
+ ++outline;
+ putc(c, out);
+ }
+ if (!lflag)
+ fprintf(out, line_format, ++outline + 1, code_file_name);
+}
+
+
+void output_debug(void)
+{
+ int i;
+
+ ++outline;
+ fprintf(code_file, "let yynames_const = \"\\\n");
+ for (i = 0; i < ntokens; i++) {
+ if (symbol_true_token[i] && symbol_tag[i] == NULL) {
+ ++outline;
+ fprintf(code_file, " %s\\000\\\n", symbol_name[i]);
+ }
+ }
+ outline += 2;
+ fprintf(code_file, " \"\n\n");
+ ++outline;
+ fprintf(code_file, "let yynames_block = \"\\\n");
+ for (i = 0; i < ntokens; i++) {
+ if (symbol_true_token[i] && symbol_tag[i] != NULL) {
+ ++outline;
+ fprintf(code_file, " %s\\000\\\n", symbol_name[i]);
+ }
+ }
+ outline += 2;
+ fprintf(code_file, " \"\n\n");
+}
+
+void output_trailing_text(void)
+{
+ register int c, last;
+ register FILE *in, *out;
+
+ if (line == 0)
+ return;
+
+ in = input_file;
+ out = code_file;
+
+ ++outline;
+ fprintf (out, ";;\n");
+
+ c = *cptr;
+ if (c == '\n')
+ {
+ ++lineno;
+ if ((c = getc(in)) == EOF)
+ return;
+ if (!lflag)
+ {
+ ++outline;
+ fprintf(out, line_format, lineno, input_file_name);
+ }
+ if (c == '\n')
+ ++outline;
+ putc(c, out);
+ last = c;
+ }
+ else
+ {
+ if (!lflag)
+ {
+ ++outline;
+ fprintf(out, line_format, lineno, input_file_name);
+ }
+ do { putc(c, out); } while ((c = *++cptr) != '\n');
+ ++outline;
+ putc('\n', out);
+ last = '\n';
+ }
+
+
+ while ((c = getc(in)) != EOF)
+ {
+ if (c == '\n')
+ ++outline;
+ putc(c, out);
+ last = c;
+ }
+
+ if (last != '\n')
+ {
+ ++outline;
+ putc('\n', out);
+ }
+ if (!lflag)
+ fprintf(out, line_format, ++outline + 1, code_file_name);
+}
+
+
+void copy_file(FILE **file, char *file_name)
+{
+ register int c, last;
+ register FILE *out = code_file;
+ int state = 0;
+
+ fclose(*file);
+ *file = fopen(file_name, "r");
+ if (*file == NULL)
+ open_error(file_name);
+
+ last = '\n';
+
+ while ((c = getc(*file)) != EOF)
+ {
+ switch (c){
+ case '\n': state = 1; break;
+ case '#': state = (state == 1) ? 2 : 0; break;
+ case ' ': state = (state == 2) ? 3 : 0; break;
+ case '0':
+ if (state == 3){
+ fprintf (out, "%d \"%s", outline+2, code_file_name);
+ c = '"';
+ }
+ state = 0;
+ break;
+ default: state = 0; break;
+ }
+ if (c == '\n') ++outline;
+ putc(c, out);
+ last = c;
+ }
+
+ if (last != '\n')
+ {
+ ++outline;
+ putc('\n', out);
+ }
+
+}
+
+void output_semantic_actions(void)
+{
+ copy_file (&action_file, action_file_name);
+}
+
+void output_entries(void)
+{
+ copy_file (&entry_file, entry_file_name);
+}
+
+void free_itemsets(void)
+{
+ register core *cp, *next;
+
+ FREE(state_table);
+ for (cp = first_state; cp; cp = next)
+ {
+ next = cp->next;
+ FREE(cp);
+ }
+}
+
+
+void free_shifts(void)
+{
+ register shifts *sp, *next;
+
+ FREE(shift_table);
+ for (sp = first_shift; sp; sp = next)
+ {
+ next = sp->next;
+ FREE(sp);
+ }
+}
+
+
+
+void free_reductions(void)
+{
+ register reductions *rp, *next;
+
+ FREE(reduction_table);
+ for (rp = first_reduction; rp; rp = next)
+ {
+ next = rp->next;
+ FREE(rp);
+ }
+}
diff --git a/yacc/reader.c b/yacc/reader.c
new file mode 100644
index 0000000000..600c909836
--- /dev/null
+++ b/yacc/reader.c
@@ -0,0 +1,1906 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include <string.h>
+#include "defs.h"
+
+/* The line size must be a positive integer. One hundred was chosen */
+/* because few lines in Yacc input grammars exceed 100 characters. */
+/* Note that if a line exceeds LINESIZE characters, the line buffer */
+/* will be expanded to accomodate it. */
+
+#define LINESIZE 100
+
+char *cache;
+int cinc, cache_size;
+
+int ntags, tagmax;
+char **tag_table;
+
+char saw_eof, unionized;
+char *cptr, *line;
+int linesize;
+
+bucket *goal;
+int prec;
+int gensym;
+char last_was_action;
+
+int maxitems;
+bucket **pitem;
+
+int maxrules;
+bucket **plhs;
+
+int name_pool_size;
+char *name_pool;
+
+char line_format[] = "# %d \"%s\"\n";
+
+
+
+void start_rule (register bucket *bp, int s_lineno);
+
+void cachec(int c)
+{
+ assert(cinc >= 0);
+ if (cinc >= cache_size)
+ {
+ cache_size += 256;
+ cache = REALLOC(cache, cache_size);
+ if (cache == 0) no_space();
+ }
+ cache[cinc] = c;
+ ++cinc;
+}
+
+
+void get_line(void)
+{
+ register FILE *f = input_file;
+ register int c;
+ register int i;
+
+ if (saw_eof || (c = getc(f)) == EOF)
+ {
+ if (line) { FREE(line); line = 0; }
+ cptr = 0;
+ saw_eof = 1;
+ return;
+ }
+
+ if (line == 0 || linesize != (LINESIZE + 1))
+ {
+ if (line) FREE(line);
+ linesize = LINESIZE + 1;
+ line = MALLOC(linesize);
+ if (line == 0) no_space();
+ }
+
+ i = 0;
+ ++lineno;
+ for (;;)
+ {
+ line[i] = c;
+ if (++i >= linesize)
+ {
+ linesize += LINESIZE;
+ line = REALLOC(line, linesize);
+ if (line == 0) no_space();
+ }
+ if (c == '\n') { line[i] = '\0'; cptr = line; return; }
+ c = getc(f);
+ if (c == EOF) { saw_eof = 1; c = '\n'; }
+ }
+}
+
+
+char *
+dup_line(void)
+{
+ register char *p, *s, *t;
+
+ if (line == 0) return (0);
+ s = line;
+ while (*s != '\n') ++s;
+ p = MALLOC(s - line + 1);
+ if (p == 0) no_space();
+
+ s = line;
+ t = p;
+ while ((*t++ = *s++) != '\n') continue;
+ return (p);
+}
+
+
+void skip_comment(void)
+{
+ register char *s;
+
+ int st_lineno = lineno;
+ char *st_line = dup_line();
+ char *st_cptr = st_line + (cptr - line);
+
+ s = cptr + 2;
+ for (;;)
+ {
+ if (*s == '*' && s[1] == '/')
+ {
+ cptr = s + 2;
+ FREE(st_line);
+ return;
+ }
+ if (*s == '\n')
+ {
+ get_line();
+ if (line == 0)
+ unterminated_comment(st_lineno, st_line, st_cptr);
+ s = cptr;
+ }
+ else
+ ++s;
+ }
+}
+
+char *substring (char *str, int start, int len)
+{
+ int i;
+ char *buf = MALLOC (len+1);
+ if (buf == NULL) return NULL;
+ for (i = 0; i < len; i++){
+ buf[i] = str[start+i];
+ }
+ buf[i] = '\0'; /* PR#4796 */
+ return buf;
+}
+
+void parse_line_directive (void)
+{
+ int i = 0, j = 0;
+ int line_number = 0;
+ char *file_name = NULL;
+
+ again:
+ if (line == 0) return;
+ if (line[i] != '#') return;
+ ++ i;
+ while (line[i] == ' ' || line[i] == '\t') ++ i;
+ if (line[i] < '0' || line[i] > '9') return;
+ while (line[i] >= '0' && line[i] <= '9'){
+ line_number = line_number * 10 + line[i] - '0';
+ ++ i;
+ }
+ while (line[i] == ' ' || line[i] == '\t') ++ i;
+ if (line[i] == '"'){
+ ++ i;
+ j = i;
+ while (line[j] != '"' && line[j] != '\0') ++j;
+ if (line[j] == '"'){
+ file_name = substring (line, i, j - i);
+ if (file_name == NULL) no_space ();
+ }
+ }
+ lineno = line_number - 1;
+ if (file_name != NULL){
+ if (virtual_input_file_name != NULL) FREE (virtual_input_file_name);
+ virtual_input_file_name = file_name;
+ }
+ get_line ();
+ goto again;
+}
+
+int
+nextc(void)
+{
+ register char *s;
+
+ if (line == 0)
+ {
+ get_line();
+ parse_line_directive ();
+ if (line == 0)
+ return (EOF);
+ }
+
+ s = cptr;
+ for (;;)
+ {
+ switch (*s)
+ {
+ case '\n':
+ get_line();
+ parse_line_directive ();
+ if (line == 0) return (EOF);
+ s = cptr;
+ break;
+
+ case ' ':
+ case '\t':
+ case '\f':
+ case '\r':
+ case '\v':
+ case ',':
+ case ';':
+ ++s;
+ break;
+
+ case '\\':
+ cptr = s;
+ return ('%');
+
+ case '/':
+ if (s[1] == '*')
+ {
+ cptr = s;
+ skip_comment();
+ s = cptr;
+ break;
+ }
+ else if (s[1] == '/')
+ {
+ get_line();
+ parse_line_directive ();
+ if (line == 0) return (EOF);
+ s = cptr;
+ break;
+ }
+ /* fall through */
+
+ default:
+ cptr = s;
+ return (*s);
+ }
+ }
+}
+
+
+int
+keyword(void)
+{
+ register int c;
+ char *t_cptr = cptr;
+
+ c = *++cptr;
+ if (isalpha(c))
+ {
+ cinc = 0;
+ for (;;)
+ {
+ if (isalpha(c))
+ {
+ if (isupper(c)) c = tolower(c);
+ cachec(c);
+ }
+ else if (isdigit(c) || c == '_' || c == '.' || c == '$')
+ cachec(c);
+ else
+ break;
+ c = *++cptr;
+ }
+ cachec(NUL);
+
+ if (strcmp(cache, "token") == 0 || strcmp(cache, "term") == 0)
+ return (TOKEN);
+ if (strcmp(cache, "type") == 0)
+ return (TYPE);
+ if (strcmp(cache, "left") == 0)
+ return (LEFT);
+ if (strcmp(cache, "right") == 0)
+ return (RIGHT);
+ if (strcmp(cache, "nonassoc") == 0 || strcmp(cache, "binary") == 0)
+ return (NONASSOC);
+ if (strcmp(cache, "start") == 0)
+ return (START);
+ if (strcmp(cache, "union") == 0)
+ return (UNION);
+ if (strcmp(cache, "ident") == 0)
+ return (IDENT);
+ }
+ else
+ {
+ ++cptr;
+ if (c == '{')
+ return (TEXT);
+ if (c == '%' || c == '\\')
+ return (MARK);
+ if (c == '<')
+ return (LEFT);
+ if (c == '>')
+ return (RIGHT);
+ if (c == '0')
+ return (TOKEN);
+ if (c == '2')
+ return (NONASSOC);
+ }
+ syntax_error(lineno, line, t_cptr);
+ /*NOTREACHED*/
+ return 0;
+}
+
+
+void copy_ident(void)
+{
+ register int c;
+ register FILE *f = output_file;
+
+ c = nextc();
+ if (c == EOF) unexpected_EOF();
+ if (c != '"') syntax_error(lineno, line, cptr);
+ ++outline;
+ fprintf(f, "#ident \"");
+ for (;;)
+ {
+ c = *++cptr;
+ if (c == '\n')
+ {
+ fprintf(f, "\"\n");
+ return;
+ }
+ putc(c, f);
+ if (c == '"')
+ {
+ putc('\n', f);
+ ++cptr;
+ return;
+ }
+ }
+}
+
+
+void copy_text(void)
+{
+ register int c;
+ int quote;
+ register FILE *f = text_file;
+ int need_newline = 0;
+ int t_lineno = lineno;
+ char *t_line = dup_line();
+ char *t_cptr = t_line + (cptr - line - 2);
+
+ if (*cptr == '\n')
+ {
+ get_line();
+ if (line == 0)
+ unterminated_text(t_lineno, t_line, t_cptr);
+ }
+ fprintf(f, line_format, lineno, input_file_name);
+
+loop:
+ c = *cptr++;
+ switch (c)
+ {
+ case '\n':
+ putc('\n', f);
+ need_newline = 0;
+ get_line();
+ if (line) goto loop;
+ unterminated_text(t_lineno, t_line, t_cptr);
+
+ case '"':
+ {
+ int s_lineno = lineno;
+ char *s_line = dup_line();
+ char *s_cptr = s_line + (cptr - line - 1);
+
+ quote = c;
+ putc(c, f);
+ for (;;)
+ {
+ c = *cptr++;
+ putc(c, f);
+ if (c == quote)
+ {
+ need_newline = 1;
+ FREE(s_line);
+ goto loop;
+ }
+ if (c == '\n')
+ unterminated_string(s_lineno, s_line, s_cptr);
+ if (c == '\\')
+ {
+ c = *cptr++;
+ putc(c, f);
+ if (c == '\n')
+ {
+ get_line();
+ if (line == 0)
+ unterminated_string(s_lineno, s_line, s_cptr);
+ }
+ }
+ }
+ }
+
+ case '\'':
+ putc(c, f);
+ if (cptr[0] != 0 && cptr[0] != '\\' && cptr[1] == '\'') {
+ fwrite(cptr, 1, 2, f);
+ cptr += 2;
+ } else
+ if (cptr[0] == '\\'
+ && isdigit((unsigned char) cptr[1])
+ && isdigit((unsigned char) cptr[2])
+ && isdigit((unsigned char) cptr[3])
+ && cptr[4] == '\'') {
+ fwrite(cptr, 1, 5, f);
+ cptr += 5;
+ } else
+ if (cptr[0] == '\\' && cptr[2] == '\'') {
+ fwrite(cptr, 1, 3, f);
+ cptr += 3;
+ }
+ goto loop;
+
+ case '(':
+ putc(c, f);
+ need_newline = 1;
+ c = *cptr;
+ if (c == '*')
+ {
+ int c_lineno = lineno;
+ char *c_line = dup_line();
+ char *c_cptr = c_line + (cptr - line - 1);
+
+ putc('*', f);
+ ++cptr;
+ for (;;)
+ {
+ c = *cptr++;
+ putc(c, f);
+ if (c == '*' && *cptr == ')')
+ {
+ putc(')', f);
+ ++cptr;
+ FREE(c_line);
+ goto loop;
+ }
+ if (c == '\n')
+ {
+ get_line();
+ if (line == 0)
+ unterminated_comment(c_lineno, c_line, c_cptr);
+ }
+ }
+ }
+ need_newline = 1;
+ goto loop;
+
+ case '%':
+ case '\\':
+ if (*cptr == '}')
+ {
+ if (need_newline) putc('\n', f);
+ ++cptr;
+ FREE(t_line);
+ return;
+ }
+ /* fall through */
+
+ default:
+ putc(c, f);
+ need_newline = 1;
+ goto loop;
+ }
+}
+
+
+void copy_union(void)
+{
+ register int c;
+ int quote;
+ int depth;
+ int u_lineno = lineno;
+ char *u_line = dup_line();
+ char *u_cptr = u_line + (cptr - line - 6);
+
+ if (unionized) over_unionized(cptr - 6);
+ unionized = 1;
+
+ if (!lflag)
+ fprintf(text_file, line_format, lineno, input_file_name);
+
+ fprintf(text_file, "typedef union");
+ if (dflag) fprintf(union_file, "typedef union");
+
+ depth = 1;
+ cptr++;
+
+loop:
+ c = *cptr++;
+ putc(c, text_file);
+ if (dflag) putc(c, union_file);
+ switch (c)
+ {
+ case '\n':
+ get_line();
+ if (line == 0) unterminated_union(u_lineno, u_line, u_cptr);
+ goto loop;
+
+ case '{':
+ ++depth;
+ goto loop;
+
+ case '}':
+ --depth;
+ if (c == '}' && depth == 0) {
+ fprintf(text_file, " YYSTYPE;\n");
+ FREE(u_line);
+ return;
+ }
+ goto loop;
+
+ case '\'':
+ case '"':
+ {
+ int s_lineno = lineno;
+ char *s_line = dup_line();
+ char *s_cptr = s_line + (cptr - line - 1);
+
+ quote = c;
+ for (;;)
+ {
+ c = *cptr++;
+ putc(c, text_file);
+ if (dflag) putc(c, union_file);
+ if (c == quote)
+ {
+ FREE(s_line);
+ goto loop;
+ }
+ if (c == '\n')
+ unterminated_string(s_lineno, s_line, s_cptr);
+ if (c == '\\')
+ {
+ c = *cptr++;
+ putc(c, text_file);
+ if (dflag) putc(c, union_file);
+ if (c == '\n')
+ {
+ get_line();
+ if (line == 0)
+ unterminated_string(s_lineno, s_line, s_cptr);
+ }
+ }
+ }
+ }
+
+ case '(':
+ c = *cptr;
+ if (c == '*')
+ {
+ int c_lineno = lineno;
+ char *c_line = dup_line();
+ char *c_cptr = c_line + (cptr - line - 1);
+
+ putc('*', text_file);
+ if (dflag) putc('*', union_file);
+ ++cptr;
+ for (;;)
+ {
+ c = *cptr++;
+ putc(c, text_file);
+ if (dflag) putc(c, union_file);
+ if (c == '*' && *cptr == ')')
+ {
+ putc(')', text_file);
+ if (dflag) putc(')', union_file);
+ ++cptr;
+ FREE(c_line);
+ goto loop;
+ }
+ if (c == '\n')
+ {
+ get_line();
+ if (line == 0)
+ unterminated_comment(c_lineno, c_line, c_cptr);
+ }
+ }
+ }
+ goto loop;
+
+ default:
+ goto loop;
+ }
+}
+
+
+int
+hexval(int c)
+{
+ if (c >= '0' && c <= '9')
+ return (c - '0');
+ if (c >= 'A' && c <= 'F')
+ return (c - 'A' + 10);
+ if (c >= 'a' && c <= 'f')
+ return (c - 'a' + 10);
+ return (-1);
+}
+
+
+bucket *
+get_literal(void)
+{
+ register int c, quote;
+ register int i;
+ register int n;
+ register char *s;
+ register bucket *bp;
+ int s_lineno = lineno;
+ char *s_line = dup_line();
+ char *s_cptr = s_line + (cptr - line);
+
+ quote = *cptr++;
+ cinc = 0;
+ for (;;)
+ {
+ c = *cptr++;
+ if (c == quote) break;
+ if (c == '\n') unterminated_string(s_lineno, s_line, s_cptr);
+ if (c == '\\')
+ {
+ char *c_cptr = cptr - 1;
+
+ c = *cptr++;
+ switch (c)
+ {
+ case '\n':
+ get_line();
+ if (line == 0) unterminated_string(s_lineno, s_line, s_cptr);
+ continue;
+
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ n = c - '0';
+ c = *cptr;
+ if (IS_OCTAL(c))
+ {
+ n = (n << 3) + (c - '0');
+ c = *++cptr;
+ if (IS_OCTAL(c))
+ {
+ n = (n << 3) + (c - '0');
+ ++cptr;
+ }
+ }
+ if (n > MAXCHAR) illegal_character(c_cptr);
+ c = n;
+ break;
+
+ case 'x':
+ c = *cptr++;
+ n = hexval(c);
+ if (n < 0 || n >= 16)
+ illegal_character(c_cptr);
+ for (;;)
+ {
+ c = *cptr;
+ i = hexval(c);
+ if (i < 0 || i >= 16) break;
+ ++cptr;
+ n = (n << 4) + i;
+ if (n > MAXCHAR) illegal_character(c_cptr);
+ }
+ c = n;
+ break;
+
+ case 'a': c = 7; break;
+ case 'b': c = '\b'; break;
+ case 'f': c = '\f'; break;
+ case 'n': c = '\n'; break;
+ case 'r': c = '\r'; break;
+ case 't': c = '\t'; break;
+ case 'v': c = '\v'; break;
+ }
+ }
+ cachec(c);
+ }
+ FREE(s_line);
+
+ n = cinc;
+ s = MALLOC(n);
+ if (s == 0) no_space();
+
+ for (i = 0; i < n; ++i)
+ s[i] = cache[i];
+
+ cinc = 0;
+ if (n == 1)
+ cachec('\'');
+ else
+ cachec('"');
+
+ for (i = 0; i < n; ++i)
+ {
+ c = ((unsigned char *)s)[i];
+ if (c == '\\' || c == cache[0])
+ {
+ cachec('\\');
+ cachec(c);
+ }
+ else if (isprint(c))
+ cachec(c);
+ else
+ {
+ cachec('\\');
+ switch (c)
+ {
+ case 7: cachec('a'); break;
+ case '\b': cachec('b'); break;
+ case '\f': cachec('f'); break;
+ case '\n': cachec('n'); break;
+ case '\r': cachec('r'); break;
+ case '\t': cachec('t'); break;
+ case '\v': cachec('v'); break;
+ default:
+ cachec(((c >> 6) & 7) + '0');
+ cachec(((c >> 3) & 7) + '0');
+ cachec((c & 7) + '0');
+ break;
+ }
+ }
+ }
+
+ if (n == 1)
+ cachec('\'');
+ else
+ cachec('"');
+
+ cachec(NUL);
+ bp = lookup(cache);
+ bp->class = TERM;
+ if (n == 1 && bp->value == UNDEFINED)
+ bp->value = *(unsigned char *)s;
+ FREE(s);
+
+ return (bp);
+}
+
+
+int
+is_reserved(char *name)
+{
+ char *s;
+
+ if (strcmp(name, ".") == 0 ||
+ strcmp(name, "$accept") == 0 ||
+ strcmp(name, "$end") == 0)
+ return (1);
+
+ if (name[0] == '$' && name[1] == '$' && isdigit((unsigned char) name[2]))
+ {
+ s = name + 3;
+ while (isdigit((unsigned char) *s)) ++s;
+ if (*s == NUL) return (1);
+ }
+
+ return (0);
+}
+
+
+bucket *
+get_name(void)
+{
+ register int c;
+
+ cinc = 0;
+ for (c = *cptr; IS_IDENT(c); c = *++cptr)
+ cachec(c);
+ cachec(NUL);
+
+ if (is_reserved(cache)) used_reserved(cache);
+
+ return (lookup(cache));
+}
+
+
+int
+get_number(void)
+{
+ register int c;
+ register int n;
+
+ n = 0;
+ for (c = *cptr; isdigit(c); c = *++cptr)
+ n = 10*n + (c - '0');
+
+ return (n);
+}
+
+
+char *
+get_tag(void)
+{
+ register int c;
+ register int i;
+ register char *s;
+ char *t_line = dup_line();
+ long bracket_depth;
+
+ cinc = 0;
+ bracket_depth = 0;
+ while (1) {
+ c = *++cptr;
+ if (c == EOF) unexpected_EOF();
+ if (c == '\n') syntax_error(lineno, line, cptr);
+ if (c == '>' && 0 == bracket_depth && cptr[-1] != '-') break;
+ if (c == '[') ++ bracket_depth;
+ if (c == ']') -- bracket_depth;
+ cachec(c);
+ }
+ ++cptr;
+ cachec(NUL);
+
+ for (i = 0; i < ntags; ++i)
+ {
+ if (strcmp(cache, tag_table[i]) == 0)
+ return (tag_table[i]);
+ }
+
+ if (ntags >= tagmax)
+ {
+ tagmax += 16;
+ tag_table = (char **)
+ (tag_table ? REALLOC(tag_table, tagmax*sizeof(char *))
+ : MALLOC(tagmax*sizeof(char *)));
+ if (tag_table == 0) no_space();
+ }
+
+ s = MALLOC(cinc);
+ if (s == 0) no_space();
+ strcpy(s, cache);
+ tag_table[ntags] = s;
+ ++ntags;
+ FREE(t_line);
+ return (s);
+}
+
+
+void declare_tokens(int assoc)
+{
+ register int c;
+ register bucket *bp;
+ char *tag = 0;
+
+ if (assoc != TOKEN) ++prec;
+
+ c = nextc();
+ if (c == EOF) unexpected_EOF();
+ if (c == '<')
+ {
+ tag = get_tag();
+ c = nextc();
+ if (c == EOF) unexpected_EOF();
+ }
+
+ for (;;)
+ {
+ if (isalpha(c) || c == '_' || c == '.' || c == '$')
+ bp = get_name();
+ else if (c == '\'' || c == '"')
+ bp = get_literal();
+ else
+ return;
+
+ if (bp == goal) tokenized_start(bp->name);
+ bp->class = TERM;
+
+ if (tag)
+ {
+ if (bp->tag && tag != bp->tag)
+ retyped_warning(bp->name);
+ bp->tag = tag;
+ }
+
+ if (assoc == TOKEN)
+ {
+ bp->true_token = 1;
+ }
+ else
+ {
+ if (bp->prec && prec != bp->prec)
+ reprec_warning(bp->name);
+ bp->assoc = assoc;
+ bp->prec = prec;
+ }
+
+ if (strcmp(bp->name, "EOF") == 0)
+ bp->value = 0;
+
+ c = nextc();
+ if (c == EOF) unexpected_EOF();
+ if (isdigit(c))
+ {
+ int value = get_number();
+ if (bp->value != UNDEFINED && value != bp->value)
+ revalued_warning(bp->name);
+ bp->value = value;
+ c = nextc();
+ if (c == EOF) unexpected_EOF();
+ }
+ }
+}
+
+
+void declare_types(void)
+{
+ register int c;
+ register bucket *bp;
+ char *tag;
+
+ c = nextc();
+ if (c == EOF) unexpected_EOF();
+ if (c != '<') syntax_error(lineno, line, cptr);
+ tag = get_tag();
+
+ for (;;)
+ {
+ c = nextc();
+ if (isalpha(c) || c == '_' || c == '.' || c == '$')
+ bp = get_name();
+ else if (c == '\'' || c == '"')
+ bp = get_literal();
+ else
+ return;
+
+ if (bp->tag && tag != bp->tag)
+ retyped_warning(bp->name);
+ bp->tag = tag;
+ }
+}
+
+
+void declare_start(void)
+{
+ register int c;
+ register bucket *bp;
+ static int entry_counter = 0;
+
+ for (;;) {
+ c = nextc();
+ if (!isalpha(c) && c != '_' && c != '.' && c != '$') return;
+ bp = get_name();
+
+ if (bp->class == TERM)
+ terminal_start(bp->name);
+ bp->entry = ++entry_counter;
+ if (entry_counter == 256)
+ too_many_entries();
+ }
+}
+
+
+void read_declarations(void)
+{
+ register int c, k;
+
+ cache_size = 256;
+ cache = MALLOC(cache_size);
+ if (cache == 0) no_space();
+
+ for (;;)
+ {
+ c = nextc();
+ if (c == EOF) unexpected_EOF();
+ if (c != '%') syntax_error(lineno, line, cptr);
+ switch (k = keyword())
+ {
+ case MARK:
+ return;
+
+ case IDENT:
+ copy_ident();
+ break;
+
+ case TEXT:
+ copy_text();
+ break;
+
+ case UNION:
+ copy_union();
+ break;
+
+ case TOKEN:
+ case LEFT:
+ case RIGHT:
+ case NONASSOC:
+ declare_tokens(k);
+ break;
+
+ case TYPE:
+ declare_types();
+ break;
+
+ case START:
+ declare_start();
+ break;
+ }
+ }
+}
+
+void output_token_type(void)
+{
+ bucket * bp;
+ int n;
+
+ fprintf(interface_file, "type token =\n");
+ if (!rflag) ++outline;
+ fprintf(output_file, "type token =\n");
+ n = 0;
+ for (bp = first_symbol; bp; bp = bp->next) {
+ if (bp->class == TERM && bp->true_token) {
+ fprintf(interface_file, " | %s", bp->name);
+ fprintf(output_file, " | %s", bp->name);
+ if (bp->tag) {
+ /* Print the type expression in parentheses to make sure
+ that the constructor is unary */
+ fprintf(interface_file, " of (%s)", bp->tag);
+ fprintf(output_file, " of (%s)", bp->tag);
+ }
+ fprintf(interface_file, "\n");
+ if (!rflag) ++outline;
+ fprintf(output_file, "\n");
+ n++;
+ }
+ }
+ fprintf(interface_file, "\n");
+ if (!rflag) ++outline;
+ fprintf(output_file, "\n");
+}
+
+void initialize_grammar(void)
+{
+ nitems = 4;
+ maxitems = 300;
+ pitem = (bucket **) MALLOC(maxitems*sizeof(bucket *));
+ if (pitem == 0) no_space();
+ pitem[0] = 0;
+ pitem[1] = 0;
+ pitem[2] = 0;
+ pitem[3] = 0;
+
+ nrules = 3;
+ maxrules = 100;
+ plhs = (bucket **) MALLOC(maxrules*sizeof(bucket *));
+ if (plhs == 0) no_space();
+ plhs[0] = 0;
+ plhs[1] = 0;
+ plhs[2] = 0;
+ rprec = (short *) MALLOC(maxrules*sizeof(short));
+ if (rprec == 0) no_space();
+ rprec[0] = 0;
+ rprec[1] = 0;
+ rprec[2] = 0;
+ rassoc = (char *) MALLOC(maxrules*sizeof(char));
+ if (rassoc == 0) no_space();
+ rassoc[0] = TOKEN;
+ rassoc[1] = TOKEN;
+ rassoc[2] = TOKEN;
+}
+
+
+void expand_items(void)
+{
+ maxitems += 300;
+ pitem = (bucket **) REALLOC(pitem, maxitems*sizeof(bucket *));
+ if (pitem == 0) no_space();
+}
+
+
+void expand_rules(void)
+{
+ maxrules += 100;
+ plhs = (bucket **) REALLOC(plhs, maxrules*sizeof(bucket *));
+ if (plhs == 0) no_space();
+ rprec = (short *) REALLOC(rprec, maxrules*sizeof(short));
+ if (rprec == 0) no_space();
+ rassoc = (char *) REALLOC(rassoc, maxrules*sizeof(char));
+ if (rassoc == 0) no_space();
+}
+
+
+void advance_to_start(void)
+{
+ register int c;
+ register bucket *bp;
+ char *s_cptr;
+ int s_lineno;
+
+ for (;;)
+ {
+ c = nextc();
+ if (c != '%') break;
+ s_cptr = cptr;
+ switch (keyword())
+ {
+ case MARK:
+ no_grammar();
+
+ case TEXT:
+ copy_text();
+ break;
+
+ case START:
+ declare_start();
+ break;
+
+ default:
+ syntax_error(lineno, line, s_cptr);
+ }
+ }
+
+ c = nextc();
+ if (!isalpha(c) && c != '_' && c != '.' && c != '_')
+ syntax_error(lineno, line, cptr);
+ bp = get_name();
+ if (goal == 0)
+ {
+ if (bp->class == TERM)
+ terminal_start(bp->name);
+ goal = bp;
+ }
+
+ s_lineno = lineno;
+ c = nextc();
+ if (c == EOF) unexpected_EOF();
+ if (c != ':') syntax_error(lineno, line, cptr);
+ start_rule(bp, s_lineno);
+ ++cptr;
+}
+
+
+int at_first;
+
+void start_rule(register bucket *bp, int s_lineno)
+{
+ if (bp->class == TERM)
+ terminal_lhs(s_lineno);
+ bp->class = NONTERM;
+ if (nrules >= maxrules)
+ expand_rules();
+ plhs[nrules] = bp;
+ rprec[nrules] = UNDEFINED;
+ rassoc[nrules] = TOKEN;
+ at_first = 1;
+}
+
+
+void end_rule(void)
+{
+ if (!last_was_action) default_action_error();
+
+ last_was_action = 0;
+ if (nitems >= maxitems) expand_items();
+ pitem[nitems] = 0;
+ ++nitems;
+ ++nrules;
+}
+
+
+void insert_empty_rule(void)
+{
+ register bucket *bp, **bpp;
+
+ assert(cache);
+ sprintf(cache, "$$%d", ++gensym);
+ bp = make_bucket(cache);
+ last_symbol->next = bp;
+ last_symbol = bp;
+ bp->tag = plhs[nrules]->tag;
+ bp->class = NONTERM;
+
+ if ((nitems += 2) > maxitems)
+ expand_items();
+ bpp = pitem + nitems - 1;
+ *bpp-- = bp;
+ while ((bpp[0] = bpp[-1])) --bpp;
+
+ if (++nrules >= maxrules)
+ expand_rules();
+ plhs[nrules] = plhs[nrules-1];
+ plhs[nrules-1] = bp;
+ rprec[nrules] = rprec[nrules-1];
+ rprec[nrules-1] = 0;
+ rassoc[nrules] = rassoc[nrules-1];
+ rassoc[nrules-1] = TOKEN;
+}
+
+
+void add_symbol(void)
+{
+ register int c;
+ register bucket *bp;
+ int s_lineno = lineno;
+ char *ecptr = cptr;
+
+ c = *cptr;
+ if (c == '\'' || c == '"')
+ bp = get_literal();
+ else
+ bp = get_name();
+
+ c = nextc();
+ if (c == ':')
+ {
+ end_rule();
+ start_rule(bp, s_lineno);
+ ++cptr;
+ return;
+ }
+
+ if (last_was_action) syntax_error (lineno, line, ecptr);
+ last_was_action = 0;
+
+ if (++nitems > maxitems)
+ expand_items();
+ pitem[nitems-1] = bp;
+}
+
+
+void copy_action(void)
+{
+ register int c;
+ register int i, n;
+ int depth;
+ int quote;
+ bucket *item;
+ char *tagres;
+ register FILE *f = action_file;
+ int a_lineno = lineno;
+ char *a_line = dup_line();
+ char *a_cptr = a_line + (cptr - line);
+
+ if (last_was_action) syntax_error (lineno, line, cptr);
+ last_was_action = 1;
+
+ /*
+ fprintf(f, "(* Rule %d, file %s, line %d *)\n",
+ nrules-2, input_file_name, lineno);
+ */
+ if (sflag)
+ fprintf(f, "yyact.(%d) <- (fun __caml_parser_env ->\n", nrules-2);
+ else
+ fprintf(f, "; (fun __caml_parser_env ->\n");
+
+ n = 0;
+ for (i = nitems - 1; pitem[i]; --i) ++n;
+
+ for (i = 1; i <= n; i++) {
+ item = pitem[nitems + i - n - 1];
+ if (item->class == TERM && !item->tag) continue;
+ fprintf(f, " let _%d = ", i);
+ if (item->tag)
+ fprintf(f, "(Parsing.peek_val __caml_parser_env %d : %s) in\n", n - i,
+ item->tag);
+ else if (sflag)
+ fprintf(f, "Parsing.peek_val __caml_parser_env %d in\n", n - i);
+ else
+ fprintf(f, "(Parsing.peek_val __caml_parser_env %d : '%s) in\n", n - i,
+ item->name);
+ }
+ fprintf(f, " Obj.repr(\n");
+ fprintf(f, line_format, lineno, input_file_name);
+ for (i = 0; i < cptr - line; i++) fputc(' ', f);
+ fputc ('(', f);
+
+ depth = 1;
+ cptr++;
+
+loop:
+ c = *cptr;
+ if (c == '$')
+ {
+ if (isdigit((unsigned char) cptr[1]))
+ {
+ ++cptr;
+ i = get_number();
+
+ if (i <= 0 || i > n)
+ unknown_rhs(i);
+ item = pitem[nitems + i - n - 1];
+ if (item->class == TERM && !item->tag)
+ illegal_token_ref(i, item->name);
+ fprintf(f, "_%d", i);
+ goto loop;
+ }
+ }
+ if (isalpha(c) || c == '_' || c == '$')
+ {
+ do
+ {
+ putc(c, f);
+ c = *++cptr;
+ } while (isalnum(c) || c == '_' || c == '$');
+ goto loop;
+ }
+ if (c == '}' && depth == 1) {
+ fprintf(f, ")\n# 0\n ");
+ cptr++;
+ tagres = plhs[nrules]->tag;
+ if (tagres)
+ fprintf(f, " : %s))\n", tagres);
+ else if (sflag)
+ fprintf(f, "))\n");
+ else
+ fprintf(f, " : '%s))\n", plhs[nrules]->name);
+ if (sflag)
+ fprintf(f, "\n");
+ FREE(a_line);
+ return;
+ }
+ putc(c, f);
+ ++cptr;
+ switch (c)
+ {
+ case '\n':
+ get_line();
+ if (line) goto loop;
+ unterminated_action(a_lineno, a_line, a_cptr);
+
+ case '{':
+ ++depth;
+ goto loop;
+
+ case '}':
+ --depth;
+ goto loop;
+
+ case '"':
+ {
+ int s_lineno = lineno;
+ char *s_line = dup_line();
+ char *s_cptr = s_line + (cptr - line - 1);
+
+ quote = c;
+ for (;;)
+ {
+ c = *cptr++;
+ putc(c, f);
+ if (c == quote)
+ {
+ FREE(s_line);
+ goto loop;
+ }
+ if (c == '\n')
+ unterminated_string(s_lineno, s_line, s_cptr);
+ if (c == '\\')
+ {
+ c = *cptr++;
+ putc(c, f);
+ if (c == '\n')
+ {
+ get_line();
+ if (line == 0)
+ unterminated_string(s_lineno, s_line, s_cptr);
+ }
+ }
+ }
+ }
+
+ case '\'':
+ if (cptr[0] != 0 && cptr[0] != '\\' && cptr[1] == '\'') {
+ fwrite(cptr, 1, 2, f);
+ cptr += 2;
+ } else
+ if (cptr[0] == '\\'
+ && isdigit((unsigned char) cptr[1])
+ && isdigit((unsigned char) cptr[2])
+ && isdigit((unsigned char) cptr[3])
+ && cptr[4] == '\'') {
+ fwrite(cptr, 1, 5, f);
+ cptr += 5;
+ } else
+ if (cptr[0] == '\\' && cptr[2] == '\'') {
+ fwrite(cptr, 1, 3, f);
+ cptr += 3;
+ }
+ goto loop;
+
+ case '(':
+ c = *cptr;
+ if (c == '*')
+ {
+ int c_lineno = lineno;
+ char *c_line = dup_line();
+ char *c_cptr = c_line + (cptr - line - 1);
+
+ putc('*', f);
+ ++cptr;
+ for (;;)
+ {
+ c = *cptr++;
+ putc(c, f);
+ if (c == '*' && *cptr == ')')
+ {
+ putc(')', f);
+ ++cptr;
+ FREE(c_line);
+ goto loop;
+ }
+ if (c == '\n')
+ {
+ get_line();
+ if (line == 0)
+ unterminated_comment(c_lineno, c_line, c_cptr);
+ }
+ }
+ }
+ goto loop;
+
+ default:
+ goto loop;
+ }
+}
+
+
+int
+mark_symbol(void)
+{
+ register int c;
+ register bucket *bp;
+
+ c = cptr[1];
+ if (c == '%' || c == '\\')
+ {
+ cptr += 2;
+ return (1);
+ }
+
+ if (c == '=')
+ cptr += 2;
+ else if ((c == 'p' || c == 'P') &&
+ ((c = cptr[2]) == 'r' || c == 'R') &&
+ ((c = cptr[3]) == 'e' || c == 'E') &&
+ ((c = cptr[4]) == 'c' || c == 'C') &&
+ ((c = cptr[5], !IS_IDENT(c))))
+ cptr += 5;
+ else
+ syntax_error(lineno, line, cptr);
+
+ c = nextc();
+ if (isalpha(c) || c == '_' || c == '.' || c == '$')
+ bp = get_name();
+ else if (c == '\'' || c == '"')
+ bp = get_literal();
+ else
+ {
+ syntax_error(lineno, line, cptr);
+ /*NOTREACHED*/
+ }
+
+ if (rprec[nrules] != UNDEFINED && bp->prec != rprec[nrules])
+ prec_redeclared();
+
+ rprec[nrules] = bp->prec;
+ rassoc[nrules] = bp->assoc;
+ return (0);
+}
+
+
+void read_grammar(void)
+{
+ register int c;
+
+ initialize_grammar();
+ advance_to_start();
+
+ for (;;)
+ {
+ c = nextc();
+ if (c == '|' && at_first){
+ ++cptr;
+ c = nextc();
+ }
+ at_first = 0;
+ if (c == EOF) break;
+ if (isalpha(c) || c == '_' || c == '.' || c == '$' || c == '\'' ||
+ c == '"')
+ add_symbol();
+ else if (c == '{' || c == '=')
+ copy_action();
+ else if (c == '|')
+ {
+ end_rule();
+ start_rule(plhs[nrules-1], 0);
+ ++cptr;
+ }
+ else if (c == '%')
+ {
+ if (mark_symbol()) break;
+ }
+ else
+ syntax_error(lineno, line, cptr);
+ }
+ end_rule();
+}
+
+
+void free_tags(void)
+{
+ register int i;
+
+ if (tag_table == 0) return;
+
+ for (i = 0; i < ntags; ++i)
+ {
+ assert(tag_table[i]);
+ FREE(tag_table[i]);
+ }
+ FREE(tag_table);
+}
+
+
+void pack_names(void)
+{
+ register bucket *bp;
+ register char *p, *s, *t;
+
+ name_pool_size = 13; /* 13 == sizeof("$end") + sizeof("$accept") */
+ for (bp = first_symbol; bp; bp = bp->next)
+ name_pool_size += strlen(bp->name) + 1;
+ name_pool = MALLOC(name_pool_size);
+ if (name_pool == 0) no_space();
+
+ strcpy(name_pool, "$accept");
+ strcpy(name_pool+8, "$end");
+ t = name_pool + 13;
+ for (bp = first_symbol; bp; bp = bp->next)
+ {
+ p = t;
+ s = bp->name;
+ while ((*t++ = *s++)) continue;
+ FREE(bp->name);
+ bp->name = p;
+ }
+}
+
+
+void check_symbols(void)
+{
+ register bucket *bp;
+
+ if (goal->class == UNKNOWN)
+ undefined_goal(goal->name);
+
+ for (bp = first_symbol; bp; bp = bp->next)
+ {
+ if (bp->class == UNKNOWN)
+ {
+ undefined_symbol(bp->name);
+ bp->class = TERM;
+ }
+ }
+}
+
+
+void pack_symbols(void)
+{
+ register bucket *bp;
+ register bucket **v;
+ register int i, j, k, n;
+
+ nsyms = 2;
+ ntokens = 1;
+ for (bp = first_symbol; bp; bp = bp->next)
+ {
+ ++nsyms;
+ if (bp->class == TERM) ++ntokens;
+ }
+ start_symbol = ntokens;
+ nvars = nsyms - ntokens;
+
+ symbol_name = (char **) MALLOC(nsyms*sizeof(char *));
+ if (symbol_name == 0) no_space();
+ symbol_value = (short *) MALLOC(nsyms*sizeof(short));
+ if (symbol_value == 0) no_space();
+ symbol_prec = (short *) MALLOC(nsyms*sizeof(short));
+ if (symbol_prec == 0) no_space();
+ symbol_assoc = MALLOC(nsyms);
+ if (symbol_assoc == 0) no_space();
+ symbol_tag = (char **) MALLOC(nsyms*sizeof(char *));
+ if (symbol_tag == 0) no_space();
+ symbol_true_token = (char *) MALLOC(nsyms*sizeof(char));
+ if (symbol_true_token == 0) no_space();
+
+ v = (bucket **) MALLOC(nsyms*sizeof(bucket *));
+ if (v == 0) no_space();
+
+ v[0] = 0;
+ v[start_symbol] = 0;
+
+ i = 1;
+ j = start_symbol + 1;
+ for (bp = first_symbol; bp; bp = bp->next)
+ {
+ if (bp->class == TERM)
+ v[i++] = bp;
+ else
+ v[j++] = bp;
+ }
+ assert(i == ntokens && j == nsyms);
+
+ for (i = 1; i < ntokens; ++i)
+ v[i]->index = i;
+
+ goal->index = start_symbol + 1;
+ k = start_symbol + 2;
+ while (++i < nsyms)
+ if (v[i] != goal)
+ {
+ v[i]->index = k;
+ ++k;
+ }
+
+ goal->value = 0;
+ k = 1;
+ for (i = start_symbol + 1; i < nsyms; ++i)
+ {
+ if (v[i] != goal)
+ {
+ v[i]->value = k;
+ ++k;
+ }
+ }
+
+ k = 0;
+ for (i = 1; i < ntokens; ++i)
+ {
+ n = v[i]->value;
+ if (n > 256)
+ {
+ for (j = k++; j > 0 && symbol_value[j-1] > n; --j)
+ symbol_value[j] = symbol_value[j-1];
+ symbol_value[j] = n;
+ }
+ }
+
+ if (v[1]->value == UNDEFINED)
+ v[1]->value = 256;
+
+ j = 0;
+ n = 257;
+ for (i = 2; i < ntokens; ++i)
+ {
+ if (v[i]->value == UNDEFINED)
+ {
+ while (j < k && n == symbol_value[j])
+ {
+ while (++j < k && n == symbol_value[j]) continue;
+ ++n;
+ }
+ v[i]->value = n;
+ ++n;
+ }
+ }
+
+ symbol_name[0] = name_pool + 8;
+ symbol_value[0] = 0;
+ symbol_prec[0] = 0;
+ symbol_assoc[0] = TOKEN;
+ symbol_tag[0] = "";
+ symbol_true_token[0] = 0;
+ for (i = 1; i < ntokens; ++i)
+ {
+ symbol_name[i] = v[i]->name;
+ symbol_value[i] = v[i]->value;
+ symbol_prec[i] = v[i]->prec;
+ symbol_assoc[i] = v[i]->assoc;
+ symbol_tag[i] = v[i]->tag;
+ symbol_true_token[i] = v[i]->true_token;
+ }
+ symbol_name[start_symbol] = name_pool;
+ symbol_value[start_symbol] = -1;
+ symbol_prec[start_symbol] = 0;
+ symbol_assoc[start_symbol] = TOKEN;
+ symbol_tag[start_symbol] = "";
+ symbol_true_token[start_symbol] = 0;
+ for (++i; i < nsyms; ++i)
+ {
+ k = v[i]->index;
+ symbol_name[k] = v[i]->name;
+ symbol_value[k] = v[i]->value;
+ symbol_prec[k] = v[i]->prec;
+ symbol_assoc[k] = v[i]->assoc;
+ symbol_tag[i] = v[i]->tag;
+ symbol_true_token[i] = v[i]->true_token;
+ }
+
+ FREE(v);
+}
+
+static unsigned char caml_ident_start[32] =
+"\000\000\000\000\000\000\000\000\376\377\377\207\376\377\377\007\000\000\000\000\000\000\000\000\377\377\177\377\377\377\177\377";
+static unsigned char caml_ident_body[32] =
+"\000\000\000\000\200\000\377\003\376\377\377\207\376\377\377\007\000\000\000\000\000\000\000\000\377\377\177\377\377\377\177\377";
+
+#define In_bitmap(bm,c) (bm[(unsigned char)(c) >> 3] & (1 << ((c) & 7)))
+
+static int is_polymorphic(char * s)
+{
+ while (*s != 0) {
+ char c = *s++;
+ if (c == '\'' || c == '#') return 1;
+ if (c == '[') {
+ c = *s;
+ while (c == ' ' || c == '\t' || c == '\r' || c == '\n') c = *++s;
+ if (c == '<' || c == '>') return 1;
+ }
+ if (In_bitmap(caml_ident_start, c)) {
+ while (In_bitmap(caml_ident_body, *s)) s++;
+ }
+ }
+ return 0;
+}
+
+void make_goal(void)
+{
+ static char name[7] = "'\\xxx'";
+ bucket * bp;
+ bucket * bc;
+
+ goal = lookup("%entry%");
+ ntotalrules = nrules - 2;
+ for(bp = first_symbol; bp != 0; bp = bp->next) {
+ if (bp->entry) {
+ start_rule(goal, 0);
+ if (nitems + 2> maxitems)
+ expand_items();
+ name[2] = '0' + ((bp->entry >> 6) & 7);
+ name[3] = '0' + ((bp->entry >> 3) & 7);
+ name[4] = '0' + (bp->entry & 7);
+ bc = lookup(name);
+ bc->class = TERM;
+ bc->value = (unsigned char) bp->entry;
+ pitem[nitems++] = bc;
+ pitem[nitems++] = bp;
+ if (bp->tag == NULL)
+ entry_without_type(bp->name);
+ if (is_polymorphic(bp->tag))
+ polymorphic_entry_point(bp->name);
+ fprintf(entry_file,
+ "let %s (lexfun : Lexing.lexbuf -> token) (lexbuf : Lexing.lexbuf) =\n (Parsing.yyparse yytables %d lexfun lexbuf : %s)\n",
+ bp->name, bp->entry, bp->tag);
+ fprintf(interface_file,
+ "val %s :\n (Lexing.lexbuf -> token) -> Lexing.lexbuf -> %s\n",
+ bp->name,
+ bp->tag);
+ fprintf(action_file,
+ "(* Entry %s *)\n", bp->name);
+ if (sflag)
+ fprintf(action_file,
+ "yyact.(%d) <- (fun __caml_parser_env -> raise "
+ "(Parsing.YYexit (Parsing.peek_val __caml_parser_env 0)))\n",
+ ntotalrules);
+ else
+ fprintf(action_file,
+ "; (fun __caml_parser_env -> raise "
+ "(Parsing.YYexit (Parsing.peek_val __caml_parser_env 0)))\n");
+ ntotalrules++;
+ last_was_action = 1;
+ end_rule();
+ }
+ }
+}
+
+void pack_grammar(void)
+{
+ register int i, j;
+ int assoc, prec;
+
+ ritem = (short *) MALLOC(nitems*sizeof(short));
+ if (ritem == 0) no_space();
+ rlhs = (short *) MALLOC(nrules*sizeof(short));
+ if (rlhs == 0) no_space();
+ rrhs = (short *) MALLOC((nrules+1)*sizeof(short));
+ if (rrhs == 0) no_space();
+ rprec = (short *) REALLOC(rprec, nrules*sizeof(short));
+ if (rprec == 0) no_space();
+ rassoc = REALLOC(rassoc, nrules);
+ if (rassoc == 0) no_space();
+
+ ritem[0] = -1;
+ ritem[1] = goal->index;
+ ritem[2] = 0;
+ ritem[3] = -2;
+ rlhs[0] = 0;
+ rlhs[1] = 0;
+ rlhs[2] = start_symbol;
+ rrhs[0] = 0;
+ rrhs[1] = 0;
+ rrhs[2] = 1;
+
+ j = 4;
+ for (i = 3; i < nrules; ++i)
+ {
+ rlhs[i] = plhs[i]->index;
+ rrhs[i] = j;
+ assoc = TOKEN;
+ prec = 0;
+ while (pitem[j])
+ {
+ ritem[j] = pitem[j]->index;
+ if (pitem[j]->class == TERM)
+ {
+ prec = pitem[j]->prec;
+ assoc = pitem[j]->assoc;
+ }
+ ++j;
+ }
+ ritem[j] = -i;
+ ++j;
+ if (rprec[i] == UNDEFINED)
+ {
+ rprec[i] = prec;
+ rassoc[i] = assoc;
+ }
+ }
+ rrhs[i] = j;
+
+ FREE(plhs);
+ FREE(pitem);
+}
+
+
+void print_grammar(void)
+{
+ register int i, j, k;
+ int spacing = 0;
+ register FILE *f = verbose_file;
+
+ if (!vflag) return;
+
+ k = 1;
+ for (i = 2; i < nrules; ++i)
+ {
+ if (rlhs[i] != rlhs[i-1])
+ {
+ if (i != 2) fprintf(f, "\n");
+ fprintf(f, "%4d %s :", i - 2, symbol_name[rlhs[i]]);
+ spacing = strlen(symbol_name[rlhs[i]]) + 1;
+ }
+ else
+ {
+ fprintf(f, "%4d ", i - 2);
+ j = spacing;
+ while (--j >= 0) putc(' ', f);
+ putc('|', f);
+ }
+
+ while (ritem[k] >= 0)
+ {
+ fprintf(f, " %s", symbol_name[ritem[k]]);
+ ++k;
+ }
+ ++k;
+ putc('\n', f);
+ }
+}
+
+
+void reader(void)
+{
+ virtual_input_file_name = substring (input_file_name, 0,
+ strlen (input_file_name));
+ create_symbol_table();
+ read_declarations();
+ output_token_type();
+ read_grammar();
+ make_goal();
+ free_symbol_table();
+ free_tags();
+ pack_names();
+ check_symbols();
+ pack_symbols();
+ pack_grammar();
+ free_symbols();
+ print_grammar();
+}
diff --git a/yacc/skeleton.c b/yacc/skeleton.c
new file mode 100644
index 0000000000..976bec63fd
--- /dev/null
+++ b/yacc/skeleton.c
@@ -0,0 +1,57 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include "defs.h"
+
+char *header[] =
+{
+ "open Parsing;;",
+ "let _ = parse_error;;", /* avoid warning 33 (PR#5719) */
+ 0
+};
+
+char *define_tables[] =
+{
+ "let yytables =",
+ " { Parsing.actions=yyact;",
+ " Parsing.transl_const=yytransl_const;",
+ " Parsing.transl_block=yytransl_block;",
+ " Parsing.lhs=yylhs;",
+ " Parsing.len=yylen;",
+ " Parsing.defred=yydefred;",
+ " Parsing.dgoto=yydgoto;",
+ " Parsing.sindex=yysindex;",
+ " Parsing.rindex=yyrindex;",
+ " Parsing.gindex=yygindex;",
+ " Parsing.tablesize=yytablesize;",
+ " Parsing.table=yytable;",
+ " Parsing.check=yycheck;",
+ " Parsing.error_function=parse_error;",
+ " Parsing.names_const=yynames_const;",
+ " Parsing.names_block=yynames_block }",
+ 0
+};
+
+void write_section(char **section)
+{
+ register int i;
+ register FILE *fp;
+
+ fp = code_file;
+ for (i = 0; section[i]; ++i)
+ {
+ ++outline;
+ fprintf(fp, "%s\n", section[i]);
+ }
+}
diff --git a/yacc/symtab.c b/yacc/symtab.c
new file mode 100644
index 0000000000..9d6e2c33be
--- /dev/null
+++ b/yacc/symtab.c
@@ -0,0 +1,127 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include <string.h>
+#include "defs.h"
+
+
+bucket **symbol_table;
+bucket *first_symbol;
+bucket *last_symbol;
+
+
+int
+hash(char *name)
+{
+ register char *s;
+ register int c, k;
+
+ assert(name && *name);
+ s = name;
+ k = *s;
+ while ((c = *++s))
+ k = (31*k + c) & (TABLE_SIZE - 1);
+
+ return (k);
+}
+
+
+bucket *
+make_bucket(char *name)
+{
+ register bucket *bp;
+
+ assert(name);
+ bp = (bucket *) MALLOC(sizeof(bucket));
+ if (bp == 0) no_space();
+ bp->link = 0;
+ bp->next = 0;
+ bp->name = MALLOC(strlen(name) + 1);
+ if (bp->name == 0) no_space();
+ bp->tag = 0;
+ bp->value = UNDEFINED;
+ bp->index = 0;
+ bp->prec = 0;
+ bp-> class = UNKNOWN;
+ bp->assoc = TOKEN;
+ bp->entry = 0;
+ bp->true_token = 0;
+
+ if (bp->name == 0) no_space();
+ strcpy(bp->name, name);
+
+ return (bp);
+}
+
+
+bucket *
+lookup(char *name)
+{
+ register bucket *bp, **bpp;
+
+ bpp = symbol_table + hash(name);
+ bp = *bpp;
+
+ while (bp)
+ {
+ if (strcmp(name, bp->name) == 0) return (bp);
+ bpp = &bp->link;
+ bp = *bpp;
+ }
+
+ *bpp = bp = make_bucket(name);
+ last_symbol->next = bp;
+ last_symbol = bp;
+
+ return (bp);
+}
+
+
+void create_symbol_table(void)
+{
+ register int i;
+ register bucket *bp;
+
+ symbol_table = (bucket **) MALLOC(TABLE_SIZE*sizeof(bucket *));
+ if (symbol_table == 0) no_space();
+ for (i = 0; i < TABLE_SIZE; i++)
+ symbol_table[i] = 0;
+
+ bp = make_bucket("error");
+ bp->index = 1;
+ bp->class = TERM;
+
+ first_symbol = bp;
+ last_symbol = bp;
+ symbol_table[hash("error")] = bp;
+}
+
+
+void free_symbol_table(void)
+{
+ FREE(symbol_table);
+ symbol_table = 0;
+}
+
+
+void free_symbols(void)
+{
+ register bucket *p, *q;
+
+ for (p = first_symbol; p; p = q)
+ {
+ q = p->next;
+ FREE(p);
+ }
+}
diff --git a/yacc/verbose.c b/yacc/verbose.c
new file mode 100644
index 0000000000..b28c871194
--- /dev/null
+++ b/yacc/verbose.c
@@ -0,0 +1,346 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include "defs.h"
+
+
+static short *null_rules;
+
+
+void print_state (int state);
+void log_unused (void);
+void log_conflicts (void);
+void print_conflicts (int state);
+void print_core (int state);
+void print_nulls (int state);
+void print_actions (int stateno);
+void print_shifts (register action *p);
+void print_reductions (register action *p, register int defred);
+void print_gotos (int stateno);
+
+void verbose(void)
+{
+ register int i;
+
+ if (!vflag) return;
+
+ null_rules = (short *) MALLOC(nrules*sizeof(short));
+ if (null_rules == 0) no_space();
+ fprintf(verbose_file, "\f\n");
+ for (i = 0; i < nstates; i++)
+ print_state(i);
+ FREE(null_rules);
+
+ if (nunused)
+ log_unused();
+ if (SRtotal || RRtotal)
+ log_conflicts();
+
+ fprintf(verbose_file, "\n\n%d terminals, %d nonterminals\n", ntokens,
+ nvars);
+ fprintf(verbose_file, "%d grammar rules, %d states\n", nrules - 2, nstates);
+}
+
+
+void log_unused(void)
+{
+ register int i;
+ register short *p;
+
+ fprintf(verbose_file, "\n\nRules never reduced:\n");
+ for (i = 3; i < nrules; ++i)
+ {
+ if (!rules_used[i])
+ {
+ fprintf(verbose_file, "\t%s :", symbol_name[rlhs[i]]);
+ for (p = ritem + rrhs[i]; *p >= 0; ++p)
+ fprintf(verbose_file, " %s", symbol_name[*p]);
+ fprintf(verbose_file, " (%d)\n", i - 2);
+ }
+ }
+}
+
+
+void log_conflicts(void)
+{
+ register int i;
+
+ fprintf(verbose_file, "\n\n");
+ for (i = 0; i < nstates; i++)
+ {
+ if (SRconflicts[i] || RRconflicts[i])
+ {
+ fprintf(verbose_file, "State %d contains ", i);
+ if (SRconflicts[i] == 1)
+ fprintf(verbose_file, "1 shift/reduce conflict");
+ else if (SRconflicts[i] > 1)
+ fprintf(verbose_file, "%d shift/reduce conflicts",
+ SRconflicts[i]);
+ if (SRconflicts[i] && RRconflicts[i])
+ fprintf(verbose_file, ", ");
+ if (RRconflicts[i] == 1)
+ fprintf(verbose_file, "1 reduce/reduce conflict");
+ else if (RRconflicts[i] > 1)
+ fprintf(verbose_file, "%d reduce/reduce conflicts",
+ RRconflicts[i]);
+ fprintf(verbose_file, ".\n");
+ }
+ }
+}
+
+
+void print_state(int state)
+{
+ if (state)
+ fprintf(verbose_file, "\n\n");
+ if (SRconflicts[state] || RRconflicts[state])
+ print_conflicts(state);
+ fprintf(verbose_file, "state %d\n", state);
+ print_core(state);
+ print_nulls(state);
+ print_actions(state);
+}
+
+
+void print_conflicts(int state)
+{
+ register int symbol, act, number;
+ register action *p;
+
+ symbol = -1;
+ act = 0;
+ number = 0;
+ for (p = parser[state]; p; p = p->next)
+ {
+ if (p->suppressed == 2)
+ continue;
+
+ if (p->symbol != symbol)
+ {
+ symbol = p->symbol;
+ number = p->number;
+ if (p->action_code == SHIFT)
+ act = SHIFT;
+ else
+ act = REDUCE;
+ }
+ else if (p->suppressed == 1)
+ {
+ if (state == final_state && symbol == 0)
+ {
+ fprintf(verbose_file, "%d: shift/reduce conflict \
+(accept, reduce %d) on $end\n", state, p->number - 2);
+ }
+ else
+ {
+ if (act == SHIFT)
+ {
+ fprintf(verbose_file, "%d: shift/reduce conflict \
+(shift %d, reduce %d) on %s\n", state, number, p->number - 2,
+ symbol_name[symbol]);
+ }
+ else
+ {
+ fprintf(verbose_file, "%d: reduce/reduce conflict \
+(reduce %d, reduce %d) on %s\n", state, number - 2, p->number - 2,
+ symbol_name[symbol]);
+ }
+ }
+ }
+ }
+}
+
+
+void print_core(int state)
+{
+ register int i;
+ register int k;
+ register int rule;
+ register core *statep;
+ register short *sp;
+ register short *sp1;
+
+ statep = state_table[state];
+ k = statep->nitems;
+
+ for (i = 0; i < k; i++)
+ {
+ sp1 = sp = ritem + statep->items[i];
+
+ while (*sp >= 0) ++sp;
+ rule = -(*sp);
+ fprintf(verbose_file, "\t%s : ", symbol_name[rlhs[rule]]);
+
+ for (sp = ritem + rrhs[rule]; sp < sp1; sp++)
+ fprintf(verbose_file, "%s ", symbol_name[*sp]);
+
+ putc('.', verbose_file);
+
+ while (*sp >= 0)
+ {
+ fprintf(verbose_file, " %s", symbol_name[*sp]);
+ sp++;
+ }
+ fprintf(verbose_file, " (%d)\n", -2 - *sp);
+ }
+}
+
+
+void print_nulls(int state)
+{
+ register action *p;
+ register int i, j, k, nnulls;
+
+ nnulls = 0;
+ for (p = parser[state]; p; p = p->next)
+ {
+ if (p->action_code == REDUCE &&
+ (p->suppressed == 0 || p->suppressed == 1))
+ {
+ i = p->number;
+ if (rrhs[i] + 1 == rrhs[i+1])
+ {
+ for (j = 0; j < nnulls && i > null_rules[j]; ++j)
+ continue;
+
+ if (j == nnulls)
+ {
+ ++nnulls;
+ null_rules[j] = i;
+ }
+ else if (i != null_rules[j])
+ {
+ ++nnulls;
+ for (k = nnulls - 1; k > j; --k)
+ null_rules[k] = null_rules[k-1];
+ null_rules[j] = i;
+ }
+ }
+ }
+ }
+
+ for (i = 0; i < nnulls; ++i)
+ {
+ j = null_rules[i];
+ fprintf(verbose_file, "\t%s : . (%d)\n", symbol_name[rlhs[j]],
+ j - 2);
+ }
+ fprintf(verbose_file, "\n");
+}
+
+
+void print_actions(int stateno)
+{
+ register action *p;
+ register shifts *sp;
+ register int as;
+
+ if (stateno == final_state)
+ fprintf(verbose_file, "\t$end accept\n");
+
+ p = parser[stateno];
+ if (p)
+ {
+ print_shifts(p);
+ print_reductions(p, defred[stateno]);
+ }
+
+ sp = shift_table[stateno];
+ if (sp && sp->nshifts > 0)
+ {
+ as = accessing_symbol[sp->shift[sp->nshifts - 1]];
+ if (ISVAR(as))
+ print_gotos(stateno);
+ }
+}
+
+
+void print_shifts(register action *p)
+{
+ register int count;
+ register action *q;
+
+ count = 0;
+ for (q = p; q; q = q->next)
+ {
+ if (q->suppressed < 2 && q->action_code == SHIFT)
+ ++count;
+ }
+
+ if (count > 0)
+ {
+ for (; p; p = p->next)
+ {
+ if (p->action_code == SHIFT && p->suppressed == 0)
+ fprintf(verbose_file, "\t%s shift %d\n",
+ symbol_name[p->symbol], p->number);
+ }
+ }
+}
+
+
+void print_reductions(register action *p, register int defred)
+{
+ register int k, anyreds;
+ register action *q;
+
+ anyreds = 0;
+ for (q = p; q ; q = q->next)
+ {
+ if (q->action_code == REDUCE && q->suppressed < 2)
+ {
+ anyreds = 1;
+ break;
+ }
+ }
+
+ if (anyreds == 0)
+ fprintf(verbose_file, "\t. error\n");
+ else
+ {
+ for (; p; p = p->next)
+ {
+ if (p->action_code == REDUCE && p->number != defred)
+ {
+ k = p->number - 2;
+ if (p->suppressed == 0)
+ fprintf(verbose_file, "\t%s reduce %d\n",
+ symbol_name[p->symbol], k);
+ }
+ }
+
+ if (defred > 0)
+ fprintf(verbose_file, "\t. reduce %d\n", defred - 2);
+ }
+}
+
+
+void print_gotos(int stateno)
+{
+ register int i, k;
+ register int as;
+ register short *to_state;
+ register shifts *sp;
+
+ putc('\n', verbose_file);
+ sp = shift_table[stateno];
+ to_state = sp->shift;
+ for (i = 0; i < sp->nshifts; ++i)
+ {
+ k = to_state[i];
+ as = accessing_symbol[k];
+ if (ISVAR(as))
+ fprintf(verbose_file, "\t%s goto %d\n", symbol_name[as], k);
+ }
+}
diff --git a/yacc/warshall.c b/yacc/warshall.c
new file mode 100644
index 0000000000..f341cdfbc0
--- /dev/null
+++ b/yacc/warshall.c
@@ -0,0 +1,94 @@
+/***********************************************************************/
+/* */
+/* OCaml */
+/* */
+/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */
+/* */
+/* Copyright 1996 Institut National de Recherche en Informatique et */
+/* en Automatique. All rights reserved. This file is distributed */
+/* under the terms of the Q Public License version 1.0. */
+/* */
+/***********************************************************************/
+
+/* Based on public-domain code from Berkeley Yacc */
+
+#include "defs.h"
+
+void transitive_closure(unsigned int *R, int n)
+{
+ register int rowsize;
+ register unsigned mask;
+ register unsigned *rowj;
+ register unsigned *rp;
+ register unsigned *rend;
+ register unsigned *ccol;
+ register unsigned *relend;
+ register unsigned *cword;
+ register unsigned *rowi;
+
+ rowsize = WORDSIZE(n);
+ relend = R + n*rowsize;
+
+ cword = R;
+ mask = 1;
+ rowi = R;
+ while (rowi < relend)
+ {
+ ccol = cword;
+ rowj = R;
+
+ while (rowj < relend)
+ {
+ if (*ccol & mask)
+ {
+ rp = rowi;
+ rend = rowj + rowsize;
+ while (rowj < rend)
+ *rowj++ |= *rp++;
+ }
+ else
+ {
+ rowj += rowsize;
+ }
+
+ ccol += rowsize;
+ }
+
+ mask <<= 1;
+ if (mask == 0)
+ {
+ mask = 1;
+ cword++;
+ }
+
+ rowi += rowsize;
+ }
+}
+
+void reflexive_transitive_closure(unsigned int *R, int n)
+{
+ register int rowsize;
+ register unsigned mask;
+ register unsigned *rp;
+ register unsigned *relend;
+
+ transitive_closure(R, n);
+
+ rowsize = WORDSIZE(n);
+ relend = R + n*rowsize;
+
+ mask = 1;
+ rp = R;
+ while (rp < relend)
+ {
+ *rp |= mask;
+ mask <<= 1;
+ if (mask == 0)
+ {
+ mask = 1;
+ rp++;
+ }
+
+ rp += rowsize;
+ }
+}